farming-code 2.2.12 → 2.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/README.zh_cn.md +1 -1
- package/backend/agent-manager.js +4 -0
- package/backend/server.js +10 -0
- package/dist/assets/{App-DWsa7DXG.js → App-xASd_Y0F.js} +3 -3
- package/dist/assets/{index-CUFPJoa5.js → index-CYZKdoqi.js} +2 -2
- package/dist/crt-markdown-assets/KaTeX_AMS-Regular-CYEKBG2K.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_AMS-Regular-JKX5W2C4.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_AMS-Regular-U6PRYMIZ.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Caligraphic-Bold-5QL5CMTE.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Caligraphic-Bold-WZ3QSGD3.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Caligraphic-Bold-ZTS3R3HK.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Caligraphic-Regular-3LKEU76G.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Caligraphic-Regular-A7XRTZ5Q.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Caligraphic-Regular-KX5MEWCF.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Fraktur-Bold-2QVFK6NQ.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Fraktur-Bold-T4SWXBMT.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Fraktur-Bold-WGHVTYOR.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Fraktur-Regular-2PEIFJSJ.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Fraktur-Regular-5U4OPH2X.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Fraktur-Regular-PQMHCIK6.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Main-Bold-2GA4IZIN.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Main-Bold-W5FBVCZM.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Main-Bold-YP5VVQRP.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Main-BoldItalic-4P4C7HJH.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Main-BoldItalic-N4V3DX7S.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Main-BoldItalic-ODMLBJJQ.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Main-Italic-I43T2HSR.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Main-Italic-RELBIK7M.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Main-Italic-SASNQFN2.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Main-Regular-ARRPAO67.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Main-Regular-P5I74A2A.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Main-Regular-W74P5G27.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Math-BoldItalic-6EBV3DK5.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Math-BoldItalic-K4WTGH3J.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Math-BoldItalic-VB447A4D.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Math-Italic-6KGCHLFN.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Math-Italic-KKK3USB2.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Math-Italic-SON4MRCA.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_SansSerif-Bold-RRNVJFFW.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_SansSerif-Bold-STQ6RXC7.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_SansSerif-Bold-X5M5EMOD.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_SansSerif-Italic-HMPFTM52.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_SansSerif-Italic-PSN4QKYX.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_SansSerif-Italic-WTBAZBGY.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_SansSerif-Regular-2TL3USAE.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_SansSerif-Regular-OQCII6EP.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_SansSerif-Regular-XIQ62X4E.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Script-Regular-72OLXYNA.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Script-Regular-A5IFOEBS.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Script-Regular-APUWIHLP.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Size1-Regular-4HRHTS65.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Size1-Regular-5LRUTBFT.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Size1-Regular-7K6AASVL.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Size2-Regular-222HN3GT.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Size2-Regular-K5ZHAIS6.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Size2-Regular-LELKET5D.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Size3-Regular-TLFPAHDE.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Size3-Regular-UFCO6WCA.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Size3-Regular-WQRQ47UD.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Size4-Regular-7PGNVPQK.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Size4-Regular-CDMV7U5C.woff2 +0 -0
- package/dist/crt-markdown-assets/KaTeX_Size4-Regular-PKMWZHNC.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Typewriter-Regular-3F5K6SQ6.ttf +0 -0
- package/dist/crt-markdown-assets/KaTeX_Typewriter-Regular-MJMFSK64.woff +0 -0
- package/dist/crt-markdown-assets/KaTeX_Typewriter-Regular-VBYJ4NRC.woff2 +0 -0
- package/dist/crt-markdown-renderer.css +1 -0
- package/dist/crt-markdown-renderer.js +361 -0
- package/dist/crt-mermaid-renderer.js +3595 -0
- package/dist/index.html +1 -1
- package/frontend/skins/crt/app.js +53 -32
- package/frontend/skins/crt/index.html +47 -31
- package/frontend/skins/crt/styles/markdown.css +251 -0
- package/frontend/skins/crt/styles/monochrome-green.css +14 -3
- package/package.json +5 -2
|
@@ -151,7 +151,7 @@ void main() {
|
|
|
151
151
|
`))return e;let{start:r}=uy(t),i=e.split(`
|
|
152
152
|
`);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?``:`
|
|
153
153
|
`}${t}`},``)}function gy(e){let t=e.getSelection?.()||``,n=e.getSelectionPosition?.(),r=e.buffer?.active;if(!n||!r||typeof r.getLine!=`function`)return t;let i=my(n,r);return i===null?hy(t,n,r):i}function _y(e){if(!e.includes(`
|
|
154
|
-
`))return e;let t=$v(e.split(/\r?\n/).map((e,t)=>t===0?e.trimEnd():e.trim()).join(``));return Wv(t)?t:e}function vy(e){return e.length>0&&!/\s/u.test(e)}function yy(e,t,n){return Math.max(1,(t.row-e.row)*n+(t.col-e.col)+1)}function by(e){let t=e.getScrollbackLength?.();return Number.isFinite(t)?Math.max(0,Number(t)):0}function xy(e){let t=Number(e.viewportY||0);return Number.isFinite(t)?Math.max(0,t):0}function Sy(e){let t=e.getVisibleBufferBase?.();return Number.isFinite(t)?Math.max(0,Number(t)):xy(e)}function Cy(e){return xy(e.terminal)<=0}function wy(e){e.followOutputHandler?.({following:e.followOutput,hasUnreadOutput:e.hasUnreadOutput})}function Ty(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,wy(e))}function Ey(e){e.preserveUnreadOutputUntilJump=!0,Ty(e,!1,!0)}function Dy(e,t,n){let r=by(e),i=xy(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 Oy(e,t,n){let r=by(e)-n;return Math.max(0,t+r)}function ky(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 Ay(e,t){let n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return null;let r=t.proposeDimensions();return r?ky(r.cols,r.rows):null}function jy(e,t,n,r,i={}){let a=ky(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 My(e){e.lastNotifiedResize=null}function Ny(e,t,n={}){return n.force!==!0&&(e.cols!==t.cols||e.rows!==t.rows)}function Py(e,t){return!!(e&&t&&e.cols===t.cols&&e.rows===t.rows)}function Fy(e,t,n,r){let i=ky(t,n);return i?e.resizeRequestInFlight?(e.pendingResizeRequest=i,!0):r(i.cols,i.rows)===!1?!1:(e.resizeRequestInFlight=i,!0):!1}function Iy(e,t,n){let r=ky(t,n);if(!Py(e.resizeRequestInFlight,r))return{matched:!1,preserveLocalGeometry:e.resizeRequestInFlight!==null,next:null};let i=e.pendingResizeRequest;return e.resizeRequestInFlight=null,e.pendingResizeRequest=null,!i||Py(i,r)?{matched:!0,preserveLocalGeometry:!1,next:null}:{matched:!0,preserveLocalGeometry:!0,next:i}}function Ly(e){e.resizeRequestInFlight=null,e.pendingResizeRequest=null}function Ry(e){let t=e.pendingResizeRequest;return Ly(e),t}var zy=512;function By(e){if(Fv(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||(Vy(e),t.render(n,!0,e.terminal.viewportY||0,e.terminal))}function Vy(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=Gn.background,n.fillRect(0,0,t.width,t.height),n.restore())}function Hy(e){return e===void 0?e:+(e>0)}function Uy(e){By(e),requestAnimationFrame(()=>{e.disposed||By(e)})}function Wy(e,t){let n=by(e.terminal),r=Math.max(0,Math.min(n,t));typeof e.terminal.scrollToLine==`function`?e.terminal.scrollToLine(r):e.terminal.viewportY=r,By(e)}function Gy(e,t){let n=by(e.terminal);Wy(e,n-Math.max(0,Math.min(n,t)))}function Ky(e,t={}){if(!e.disposed){if(by(e.terminal)<=0){By(e),Ty(e,!0,!1,t);return}typeof e.terminal.scrollToBottom==`function`?(e.terminal.scrollToBottom(),By(e)):Wy(e,0),Ty(e,!0,!1,t)}}function qy(e,t,n,r){e.disposed||(Wy(e,Oy(e.terminal,t,n)),Ty(e,!1,r))}function Jy(e,t,n){qy(e,t,n,!0),Ey(e)}function Yy(e,t,n,r,i){if(!e.disposed){if(r){Ky(e,{allowClearUnread:!e.preserveUnreadOutputUntilJump});return}qy(e,t,n,i)}}function Xy(e,t,n){e.terminal.write(t,n)}function Zy(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 Qy(e){let t=Array.from(e.terminalWriteResolvers);e.terminalWriteResolvers.clear(),t.forEach(e=>e(!0))}function $y(e,t){e()&&t?.()}function eb(e,t,n){if(!t||e.disposed||!Fv(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 tb(e,t,n,r={}){if(!t){n?.();return}Zy(e,i=>{if(e.disposed){$y(i,n);return}let a=xy(e.terminal),o=by(e.terminal),s=e.followOutput,c=r.quiet===!0||t.length>=zy,l=r.isOutputObserved?.()??!0;c&&(e.suspendRendering=!0),Xy(e,t,()=>{if(e.disposed){$y(i,n);return}e.suspendRendering=!1,s?l?c?Ky(e,{allowClearUnread:!e.preserveUnreadOutputUntilJump}):Ty(e,!0,!1,{allowClearUnread:!e.preserveUnreadOutputUntilJump}):Ey(e):l?(Jy(e,a,o),requestAnimationFrame(()=>{e.disposed||(Jy(e,a,o),By(e))})):Ey(e),l&&By(e),$y(i,n)})},n)}function nb(e,t,n,r={}){Zy(e,i=>{if(e.disposed){$y(i,n);return}let a=xy(e.terminal),o=by(e.terminal),s=e.followOutput;if(e.suspendRendering=!0,e.terminal.reset(),!t){e.suspendRendering=!1,By(e),$y(i,n);return}Xy(e,t,()=>{if(e.disposed){$y(i,n);return}e.suspendRendering=!1,s?Ky(e,{allowClearUnread:!e.preserveUnreadOutputUntilJump}):Jy(e,a,o),!s&&o===by(e.terminal)&&By(e),eb(e,r.cursor??null,()=>{if(e.disposed){$y(i,n);return}By(e),$y(i,n)})})},n)}function rb(){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 ib(e){return!e.disposed&&e.attachedMount!==null&&e.hostEl.parentElement===e.attachedMount}function ab(e,t){return e.attachGeneration===t&&ib(e)}function ob(e){return e.attachGeneration+=1,e.attachGeneration}function sb(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 cb(e,t){return!(e.disposed||t&&e.attachedMount!==t||t&&e.hostEl.parentElement!==t)}function lb(e){return e.disposed?!1:(e.attachedMount=null,e.attachGeneration+=1,rb().appendChild(e.hostEl),!0)}function ub(e,t){let n=t.target;return n instanceof Node&&e.contains(n)}function db(e,t,n){return!n&&ub(e,t)}function fb(e,t,n){return n&&ub(e,t)}function pb(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 mb(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 hb(e){let t=e.session&&typeof e.session==`object`?e.session.runtimeEpoch:e.runtimeEpoch;return typeof t==`string`?t:``}function gb(e){let t=e.session&&typeof e.session==`object`?e.session.stateRevision:e.stateRevision,n=Number(t);return Number.isFinite(n)&&n>=0?n:null}function _b(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:null}function vb(e){let t=e.session&&typeof e.session==`object`?e.session:null;return{cols:_b(t?.previewCols??t?.cols??e.previewCols??e.cols),rows:_b(t?.previewRows??t?.rows??e.previewRows??e.rows)}}function yb(e){let t=pb(e),n=e.session&&typeof e.session==`object`?e.session.output??``:e.output??``,r=vb(e);return{runtimeEpoch:hb(e),output:t,textOutput:n,cursor:null,outputSeq:mb(e),stateRevision:gb(e),cols:r.cols,rows:r.rows}}var bb=5e3,xb=250,Sb=1500,Cb=FarmingTerminalReplay,wb=new Map,Tb=0,Eb=6,Db=520,Ob=.025,kb=3.2,Ab=.972,jb=90,Mb=.28,Nb=30,Pb=240,Fb=3e4;function Ib(){return oe()}function Lb(e,t){sb(e,t,()=>Jb(e.hostEl,t)),Kb(e)}function Rb(e){for(let t of wb.values())if(!(t instanceof Promise)&&t.hostEl===e)return t;return null}function zb(e){e.reconnectSnapshotSeq+=1,yx(e),e.bootstrapRequestControllers.forEach(e=>e.abort()),e.bootstrapRequestControllers.clear(),e.checkpointRequestInFlight=!1}function Bb(e){e.resizeDeliveryTimeout!==null&&(window.clearTimeout(e.resizeDeliveryTimeout),e.resizeDeliveryTimeout=null)}function Vb(e){e.fitResizeTimer!==null&&(window.clearTimeout(e.fitResizeTimer),e.fitResizeTimer=null),e.pendingFitResize=null}function Hb(e,t){e.fitResizeTimer!==null&&window.clearTimeout(e.fitResizeTimer),e.pendingFitResize=t,e.fitResizeTimer=window.setTimeout(()=>{e.fitResizeTimer=null;let t=e.pendingFitResize;e.pendingFitResize=null,!(!t||e.disposed)&&Jx(e,t.cols,t.rows)},xb)}function Ub(e){Vb(e),Bb(e),Ly(e)}function Wb(e){Bb(e),e.resizeDeliveryTimeout=window.setTimeout(()=>{e.resizeDeliveryTimeout=null;let t=Ry(e);!t||e.disposed||qx(e,t.cols,t.rows)},Sb)}function Gb(e){e.disposed||(e.parkedViewportState={viewportY:xy(e.terminal),scrollbackLength:by(e.terminal),following:e.followOutput,hasUnreadOutput:e.hasUnreadOutput,preserveUnreadOutputUntilJump:e.preserveUnreadOutputUntilJump,readingAnchor:vS(e)},zb(e),Ub(e),e.followOutputHandler=null,e.pathOpenHandler=null,e.pathResolveHandler=null,qb(e),XS(e),lb(e))}function Kb(e){e.disposed||!e.resizeObserver||e.resizeObserver.observe(e.hostEl)}function qb(e){e.resizeObserver?.disconnect()}function Jb(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=Rb(t);n?Gb(n):rb().appendChild(t)})}function Yb(e){let t=e.dataset.terminalFontSize,n=t?Number(t):NaN;return Number.isFinite(n)&&n>0?n:12}async function Xb(e,t){let n=await fetch(r(`/api/agents/${e}/session-view`),{signal:t});if(!n.ok)throw Error(`Terminal session view failed: ${n.status}`);return yb(await n.json())}async function Zb(e){let t=new AbortController;e.bootstrapRequestControllers.add(t);let n=window.setTimeout(()=>t.abort(new DOMException(`Terminal checkpoint request timed out`,`TimeoutError`)),bb);try{return await Xb(e.agentId,t.signal)}finally{window.clearTimeout(n),e.bootstrapRequestControllers.delete(t)}}function Qb(e,t){if(Fv(t))return t.focus(),!0;let n=e.querySelector(`textarea`);return n instanceof HTMLTextAreaElement?(px(e,t),n.focus(),!0):(t.focus(),!1)}function $b(e){return e.disposed||e.attachedMount===null?!1:(Tb+=1,Qb(e.hostEl,e.terminal))}function ex(e,t,n){if(e.disposed||e.attachedMount===null||Tb!==n)return!1;let r=document.activeElement;return r===document.body||t.contains(r)||e.hostEl.contains(r)}function tx(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 nx(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 rx(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(nx(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 ix(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 ax(e,t){if(!ix(t)||e.disposed||e.attachedMount===null)return!1;let n=t.target;if(n instanceof Node&&e.hostEl.contains(n))return!0;if(nx(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 ox(e){return e.key.toLowerCase()!==`k`||e.altKey||e.shiftKey||e.ctrlKey?!1:navigator.platform.toLowerCase().includes(`mac`)&&e.metaKey}function sx(e,t){if(!ox(t)||e.disposed||e.attachedMount===null)return!1;let n=t.target;return n instanceof Node&&e.hostEl.contains(n)}function cx(e,t){return sx(e,t)?(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),KS(e),!0):!1}function lx(e){return ib(e)}function ux(e){return lx(e)}function dx(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 fx(e,t){if(!dx(e,t))return!1;t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation();let n=Dy(e.terminal,t.key===`PageUp`?`PageUp`:`PageDown`,10);return Wy(e,n),Ty(e,n<=0,n<=0?!1:e.hasUnreadOutput,{allowClearUnread:n<=0}),wy(e),!0}function px(e,t){let n=e.querySelector(`textarea`),r=t.renderer?.getMetrics?.(),i=t.wasmTerm?.getCursor?.();if(!(n instanceof HTMLTextAreaElement)||!r||!i)return;let a=Yb(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=Kn,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 mx(e,t){return ab(e,t)}function hx(e,t=e.attachGeneration){if(!(e.fixtureOverrideActive||e.disposed||!e.pendingSnapshotReplay||!mx(e,t))){if(e.pendingSnapshotReplay=!1,!e.snapshotRuntimeEpoch||e.snapshotOutputSeq===null||e.snapshotStateRevision===null||e.snapshotCols===null||e.snapshotRows===null){Dx(e,t);return}Ex(e,{runtimeEpoch:e.snapshotRuntimeEpoch,output:e.snapshotOutput,textOutput:``,cursor:null,outputSeq:e.snapshotOutputSeq,stateRevision:e.snapshotStateRevision,cols:e.snapshotCols,rows:e.snapshotRows},t)}}function gx(e,t){if(!t||e.fixtureOverrideActive)return!1;let n=_x(t);return Cb.evaluateCheckpoint(e.replayState,n).action!==`install`||t.runtimeEpoch===e.snapshotRuntimeEpoch&&e.snapshotStateRevision!==null&&t.stateRevision<=e.snapshotStateRevision?!1:(e.snapshotOutput=t.output,e.snapshotRuntimeEpoch=t.runtimeEpoch,e.snapshotOutputSeq=t.outputSeq,e.snapshotStateRevision=t.stateRevision,e.snapshotCols=t.cols,e.snapshotRows=t.rows,e.pendingSnapshotReplay=!0,e.bootstrappingSnapshot=!0,e.needsReconnectOutputSync=!0,!0)}function _x(e){return{runtimeEpoch:e.runtimeEpoch,outputSeq:e.outputSeq,stateRevision:e.stateRevision,cols:e.cols,rows:e.rows}}function vx(e,t){Cb.queueTransition(e.replayState,t).queued||(e.needsReconnectOutputSync=!0,e.bootstrappingSnapshot=!0,Dx(e,e.attachGeneration))}function yx(e){e.checkpointRetryTimer!==null&&(window.clearTimeout(e.checkpointRetryTimer),e.checkpointRetryTimer=null)}function bx(e,t,n=e.attachGeneration){e.disposed||e.replayState.halted||e.checkpointRetryTimer!==null||(e.checkpointRetryTimer=window.setTimeout(()=>{e.checkpointRetryTimer=null,!(e.disposed||!mx(e,n))&&Dx(e,n)},t))}function xx(e,t,n){if(e.checkpointRequestInFlight=!1,e.needsReconnectOutputSync=!0,e.bootstrappingSnapshot=!0,t.halted){Sx(e,t.message);return}bx(e,t.delay,n)}function Sx(e,t){yx(e),e.checkpointRequestInFlight=!1,e.replayInProgress=!1,e.bootstrappingSnapshot=!1,e.pendingSnapshotReplay=!1,Cb.clearQueuedTransitions(e.replayState),e.hostEl.classList.add(`terminal-checkpoint-installing`),Wx(e,t)}function Cx(e,t){if(!(e.disposed||!mx(e,t)||e.replayInProgress||e.checkpointRequestInFlight||e.pendingSnapshotReplay||e.liveWriteInProgress)&&!(e.replayState.queuedTransitions.length>0&&(Ax(e),e.replayState.queuedTransitions.length>0||e.liveWriteInProgress||e.checkpointRequestInFlight))){if(e.needsReconnectOutputSync||Cb.isReplayTargetPending(e.replayState)){Dx(e,t);return}e.bootstrappingSnapshot=!1,Ub(e),requestAnimationFrame(()=>{!mx(e,t)||e.disposed||(e.hostEl.classList.remove(`terminal-checkpoint-installing`),Kx(e,{force:!0}),iC(e,t))})}}function wx(e){if(e.parkedViewportState)return{...e.parkedViewportState,hasUnreadOutput:e.parkedViewportState.hasUnreadOutput||e.hasUnreadOutput,preserveUnreadOutputUntilJump:e.parkedViewportState.preserveUnreadOutputUntilJump||e.preserveUnreadOutputUntilJump};let t=ne(ue(e.agentId,`terminal`)),n=t?.surface===`terminal`?t:vS(e);return{viewportY:xy(e.terminal),scrollbackLength:by(e.terminal),following:n?!1:e.followOutput,hasUnreadOutput:e.hasUnreadOutput,preserveUnreadOutputUntilJump:e.preserveUnreadOutputUntilJump,readingAnchor:n}}function Tx(e,t){if(e.followOutput=t.following,e.hasUnreadOutput=t.hasUnreadOutput,e.preserveUnreadOutputUntilJump=t.preserveUnreadOutputUntilJump,t.following){Yy(e,t.viewportY,t.scrollbackLength,!0,t.hasUnreadOutput);return}t.readingAnchor&&yS(e,t.readingAnchor)||(ae(ue(e.agentId,`terminal`)),Ky(e,{allowClearUnread:!0}))}function Ex(e,t,n){if(e.disposed||!mx(e,n))return!1;e.checkpointRequestInFlight=!1;let r=_x(t),i=Cb.evaluateCheckpoint(e.replayState,r);if(i.action===`reject`)return xx(e,Cb.recordInvariantFailure(e.replayState,i.signature||`invalid-checkpoint`,i.message||`Terminal replay returned an invalid screen state`),n),!1;if(i.action===`current`&&e.terminal.cols===t.cols&&e.terminal.rows===t.rows){let t=wx(e);return Cb.commitCheckpoint(e.replayState,r),e.needsReconnectOutputSync=!1,e.bootstrappingSnapshot=!1,Tx(e,t),Ax(e),Cx(e,n),!0}let a=e.reconnectSnapshotSeq+1;e.reconnectSnapshotSeq=a;let o=wx(e);if(e.replayInProgress=!0,e.bootstrappingSnapshot=!0,e.hostEl.classList.add(`terminal-checkpoint-installing`),e.terminal.cols!==t.cols||e.terminal.rows!==t.rows){e.applyingLocalResize=!0;try{e.terminal.resize?.(t.cols,t.rows)}finally{e.applyingLocalResize=!1}}return nb(e,t.output,()=>{e.disposed||!mx(e,n)||e.reconnectSnapshotSeq!==a||(Cb.commitCheckpoint(e.replayState,r),e.followOutput=o.following,e.hasUnreadOutput=o.hasUnreadOutput,e.preserveUnreadOutputUntilJump=o.preserveUnreadOutputUntilJump,Tx(e,o),e.replayInProgress=!1,e.needsReconnectOutputSync=!1,e.bootstrappingSnapshot=!1,Ix(e),Ax(e),Cx(e,n))}),!0}function Dx(e,t=e.attachGeneration){if(e.disposed||e.fixtureOverrideActive||e.pageOutputSuspended||e.checkpointRequestInFlight||e.checkpointRetryTimer!==null||e.replayInProgress||e.replayState.halted||!mx(e,t))return;Cb.beginRecovery(e.replayState);let n=e.reconnectSnapshotSeq+1;e.reconnectSnapshotSeq=n,e.checkpointRequestInFlight=!0,e.bootstrappingSnapshot=!0,e.needsReconnectOutputSync=!0,Zb(e).then(r=>{e.disposed||e.reconnectSnapshotSeq!==n||e.pageOutputSuspended||!mx(e,t)||(e.checkpointRequestInFlight=!1,Ex(e,r,t))}).catch(r=>{e.disposed||e.reconnectSnapshotSeq!==n||(xx(e,Cb.recordTransportFailure(e.replayState),t),r instanceof Error&&r.name!==`AbortError`&&console.warn(`Terminal replay request failed; retrying:`,r))})}function Ox(e,t,n,r,i=``,a,o,s,c=`output`){if(n){if(e.fixtureOverrideActive||e.pageOutputSuspended)return;zb(e),Ex(e,{runtimeEpoch:i,output:t,textOutput:``,cursor:null,outputSeq:Number.isFinite(r)?r:null,stateRevision:Number.isFinite(a)?a:null,cols:Number.isFinite(o)?o:null,rows:Number.isFinite(s)?s:null},e.attachGeneration);return}let l={kind:c,data:t,outputSeq:r,runtimeEpoch:i,stateRevision:a,cols:o,rows:s},u=Cb.classifyTransition(e.replayState,l);if(u.action===`drop`)return;if(u.action===`recover`){vx(e,l),e.needsReconnectOutputSync=!0,e.bootstrappingSnapshot=!0,Dx(e);return}if(c===`resize`){let t=Math.floor(o),n=Math.floor(s),r=Iy(e,t,n);if(r.matched&&Bb(e),!r.preserveLocalGeometry&&(e.terminal.cols!==t||e.terminal.rows!==n)){e.applyingLocalResize=!0;try{e.terminal.resize?.(t,n)}finally{e.applyingLocalResize=!1}}Cb.commitTransition(e.replayState,l),r.next&&qx(e,r.next.cols,r.next.rows),Ix(e),Ax(e),iC(e,e.attachGeneration);return}let d=c===`clear`?`\x1B[2J\x1B[3J\x1B[H`:t;if(!d){Cb.commitTransition(e.replayState,l),Ax(e);return}e.liveWriteInProgress=!0,tb(e,d,()=>{e.disposed||(Cb.commitTransition(e.replayState,l),c===`clear`&&e.terminal.clearTerminalSelection?.(),e.liveWriteInProgress=!1,e.followOutput&&!e.hasUnreadOutput&&wy(e),Ix(e),Ax(e),e.hostEl.classList.contains(`terminal-checkpoint-installing`)?Cx(e,e.attachGeneration):iC(e,e.attachGeneration))},{isOutputObserved:()=>lx(e)})}function kx(e,t,n,r,i=``,a,o,s,c=`output`){if(e.disposed||Date.now()<e.suppressOutputUntil)return;if(e.pageOutputSuspended||document.visibilityState===`hidden`){Cb.clearQueuedTransitions(e.replayState),Cb.beginRecovery(e.replayState,{kind:c,data:t,outputSeq:r,runtimeEpoch:i,stateRevision:a,cols:o,rows:s}),e.needsReconnectOutputSync=!0;return}let l=e.needsReconnectOutputSync||e.bootstrappingSnapshot||e.pendingSnapshotReplay||e.replayInProgress||e.checkpointRequestInFlight||e.replayState.recovering;if(e.liveWriteInProgress&&!l){vx(e,{kind:c,data:t,outputSeq:r,runtimeEpoch:i,stateRevision:a,cols:o,rows:s});return}if(l){if(n){Ox(e,t,!0,r,i,a,o,s,c);return}vx(e,{kind:c,data:t,outputSeq:r,runtimeEpoch:i,stateRevision:a,cols:o,rows:s}),e.bootstrappingSnapshot=!0,Dx(e);return}Ox(e,t,n,r,i,a,o,s,c)}function Ax(e){if(!(e.disposed||e.bootstrappingSnapshot||e.pendingSnapshotReplay||e.replayInProgress||e.checkpointRequestInFlight||e.liveWriteInProgress))for(;!e.bootstrappingSnapshot&&!e.replayInProgress&&!e.checkpointRequestInFlight&&!e.liveWriteInProgress;){let t=Cb.takeQueuedTransition(e.replayState);if(!t)break;Ox(e,t.data,!1,t.outputSeq,t.runtimeEpoch,t.stateRevision,t.cols,t.rows,t.kind)}}function jx(e){return e.terminal.getCellMetrics?.()??e.terminal.renderer?.getMetrics?.()}function Mx(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 Nx(e,t={}){let n=Cy(e);Ty(e,n,n?!1:e.hasUnreadOutput,{allowClearUnread:n&&t.allowClearUnread===!0})}function Px(e){Cb.clearQueuedTransitions(e.replayState),e.bootstrappingSnapshot=!1,e.pendingSnapshotReplay=!1}function Fx(e,t={}){e.followCheckFrame!==null&&cancelAnimationFrame(e.followCheckFrame),e.followCheckFrame=requestAnimationFrame(()=>{if(e.followCheckFrame=null,e.disposed||!lx(e))return;let n=Cy(e);Ty(e,n,n?!1:e.hasUnreadOutput,{allowClearUnread:n&&t.allowClearUnread===!0})})}function Ix(e){e.imeComposing&&requestAnimationFrame(()=>{!e.disposed&&e.imeComposing&&px(e.hostEl,e.terminal)})}function Lx(e){return Fv(e.terminal)?!1:e.imeComposing||e.suppressRendererCursor}function Rx(e,t=!0){let n=e.terminal.renderer;if(!e.disposed){if(e.hostEl.classList.toggle(`terminal-renderer-cursor-suppressed`,Lx(e)),!n){t&&By(e);return}Lx(e)?n.cursorVisible=!1:!e.imeComposing&&e.rendererCursorWasVisible!==void 0&&(n.cursorVisible=e.rendererCursorWasVisible,e.rendererCursorWasVisible=void 0),t&&By(e)}}function zx(e,t){if(e.suppressRendererCursor===t){e.hostEl.classList.toggle(`terminal-renderer-cursor-suppressed`,Lx(e));return}e.suppressRendererCursor=t,Rx(e)}function Bx(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,Rx(e);return}if(e.imeComposing){if(e.imeComposing=!1,e.suppressRendererCursor){n.cursorVisible=!1,By(e);return}n.cursorVisible=e.rendererCursorWasVisible??!0,e.rendererCursorWasVisible=void 0,By(e)}}}function Vx(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=Hy(s);if(!e.suspendRendering){if(!Lx(e)){n(r,i,a,o,c);return}t.cursorVisible=!1,n(r,!0,a,o,c),t.cursorVisible=!1}}}function Hx(e){if(Fv(e.terminal))return;let t=e.hostEl.querySelector(`textarea`);if(!(t instanceof HTMLTextAreaElement))return;let n=()=>{e.disposed||px(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`),Bx(e,!0)},o=()=>{Bx(e,!1),requestAnimationFrame(()=>{e.hostEl.classList.remove(`terminal-ime-active`),t.classList.remove(`terminal-ime-composing`),t.value=``,n()})},s=()=>{Bx(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 Ux(e,t,n=12){if(mx(e,t)&&tx(e.hostEl)){if(e.replayInProgress||e.bootstrappingSnapshot||e.pendingSnapshotReplay){if(n<=0)return;requestAnimationFrame(()=>{Ux(e,t,n-1)});return}$b(e)||n<=0||requestAnimationFrame(()=>{Ux(e,t,n-1)})}}function Wx(e,t){e.errorHandler?.(Error(t))}function Gx(e,t){return e.disposed||e.attachedMount===null||e.inputDisabled||!Je({type:`input`,agentId:e.agentId,...Array.isArray(t)?{inputParts:t}:{input:t}})?!1:(e.fixtureOverrideActive=!1,e.inputCount+=1,e.contextMenuSelection=``,e.lastNonEmptySelection=``,!0)}function Kx(e,t={}){try{let n=Ay(e.hostEl,e.fitAddon);if(!n)return;let r={cols:e.terminal.cols||n.cols,rows:e.terminal.rows||n.rows};if(r.cols===n.cols&&r.rows===n.rows){Vb(e);return}if(Ny(r,n,t)){Hb(e,n);return}Vb(e),Jx(e,n.cols,n.rows,t)}catch{}}function qx(e,t,n){if(!lx(e)||e.replayInProgress||e.bootstrappingSnapshot||e.pageOutputSuspended)return!1;let r=e.resizeRequestInFlight!==null,i=Fy(e,t,n,(t,n)=>Je({type:`resize-agent`,agentId:e.agentId,cols:t,rows:n}));return i&&!r&&e.resizeRequestInFlight&&Wb(e),i}function Jx(e,t,n,r={}){!lx(e)||e.replayInProgress||e.bootstrappingSnapshot||jy(e,t,n,(t,n)=>{if(typeof e.terminal.resize!=`function`)return!1;if(e.terminal.cols!==t||e.terminal.rows!==n){e.applyingLocalResize=!0;try{e.terminal.resize(t,n)}finally{e.applyingLocalResize=!1}}return qx(e,t,n)},r)}function Yx(e){My(e),Ub(e),Cb.resetRecovery(e.replayState),Cb.beginRecovery(e.replayState),e.needsReconnectOutputSync=!0,!(e.disposed||e.pageOutputSuspended)&&(!e.attachedMount||e.hostEl.parentElement!==e.attachedMount||(zb(e),Dx(e,e.attachGeneration)))}function Xx(e){My(e),Ub(e),Cb.resetRecovery(e.replayState),Cb.beginRecovery(e.replayState),e.needsReconnectOutputSync=!0,!(e.disposed||e.pageOutputSuspended)&&(!e.attachedMount||e.hostEl.parentElement!==e.attachedMount||(zb(e),Dx(e,e.attachGeneration)))}function Zx(e,t){return Math.max(0,(typeof e?.length==`number`?e.length:t)-1)}function Qx(e,t,n){return dy(e.getLine(t)?.getCell?.(n))}function $x(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:Zx(a,r)}}function eS(e,t,n,r){if(n<Zx(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 tS(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=Sy(e.terminal)+n;if(!vy(Qx(r,a,t)))return``;let o={row:a,col:t};for(;;){let e=$x(r,o.row,o.col,i);if(!e||!vy(Qx(r,e.row,e.col)))break;o=e}if(/^[#$%>]$/u.test(Qx(r,o.row,o.col))){let e=eS(r,o.row,o.col,i);e&&(o=e)}let s={row:a,col:t};for(;;){let e=eS(r,s.row,s.col,i);if(!e||!vy(Qx(r,e.row,e.col)))break;s=e}return e.terminal.select(o.col,o.row,yy(o,s,i)),e.cachedSelection=gy(e.terminal),e.cachedSelection}function nS(e,t,n){let r=e.terminal.buffer?.active,i=e.terminal.cols||80;if(!r||typeof e.terminal.select!=`function`)return``;let a=Sy(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,yy(c.start,c.end,i)),e.cachedSelection=gy(e.terminal),e.cachedSelection}function rS(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:Sy(e.terminal)+(e.terminal.rows||1),i=Math.max(0,r-1),a=Zx(t.getLine(i),n);return e.terminal.select(0,0,yy({row:0,col:0},{row:i,col:a},n)),e.cachedSelection=gy(e.terminal),e.cachedSelection}function iS(e,t){let n=jx(e),r=Mx(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 aS(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+=dy(i.getCell(e))||` `;return r?o.trimEnd():o}function oS(e){return e.button===0&&(e.ctrlKey||e.metaKey)}function sS(e){return e.ctrlKey||e.metaKey}function cS(e,t){return sS(t)||e.openModifierActive}function lS(e,t){if(!e.decorations){e.decorations=t;return}e.decorations.pointerCursor=t.pointerCursor,e.decorations.underline=t.underline}function uS(e){return[e.path,e.lineNumber??``,e.column??``,e.endColumn??``].join(`\0`)}async function dS(e,t){if(!e.pathResolveHandler)return t;let n=uS(t),r=e.pathResolveCache.get(n);if(r&&Date.now()-r.resolvedAt<=Fb)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 fS(e,t){return e.pathResolveHandler?(await Promise.all(t.map(async t=>{if(t.kind!==`path`||!t.pathTarget)return t;let n=await dS(e,t.pathTarget);return n?{...t,pathTarget:n}:null}))).filter(e=>!!e):t}function pS(e,t){if(!e.pathResolveHandler||t.kind!==`path`||!t.pathTarget)return t;let n=e.pathResolveCache.get(uS(t.pathTarget));return!n||n.promise||Date.now()-n.resolvedAt>Fb?null:n.target?{...t,pathTarget:n.target}:null}function mS(e){if(!Fv(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=gS(e,t-1);if(!r?.text){n(void 0);return}let i=cy(r.text,!!e.pathOpenHandler);if(i.length===0){n(void 0);return}(async()=>{let t=await fS(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:ly(t,r),text:t.text,decorations:{pointerCursor:n,underline:n||t.kind===`url`},activate:r=>{if(r.button!==0)return;let i=cS(e,r);lx(e)&&(t.kind===`url`&&!i||t.kind===`path`&&!n||(r.preventDefault(),r.stopPropagation(),r.stopImmediatePropagation(),t.kind===`url`?NS(t.text):t.pathTarget&&e.pathOpenHandler&&e.pathOpenHandler(e.agentId,t.pathTarget),e.suppressClickUntil=Date.now()+250))},hover:r=>{if(!ux(e)||Ib())return;e.linkProviderHoverTarget={kind:t.kind,text:t.text,...t.pathTarget?{pathTarget:t.pathTarget}:{}},e.lastLinkHoverEvent=r;let a=n||cS(e,r);lS(i,{pointerCursor:a,underline:n||t.kind===`url`||a}),zS(e,a)},leave:()=>{e.linkProviderHoverTarget?.text===t.text&&(e.linkProviderHoverTarget=null),lS(i,{pointerCursor:n,underline:n||t.kind===`url`}),IS(e)},dispose:()=>{e.linkProviderHoverTarget?.text===t.text&&(e.linkProviderHoverTarget=null)}};return i}))})()}});e.linkProviderDisposable=()=>t.dispose()}function hS(e,t){let n=e.terminal.buffer?.active;if(!t||!n||typeof n.getLine!=`function`)return null;let r=Sy(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(aS(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 gS(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(aS(n,e,r,e===a));return{text:o.join(``).trimEnd(),col:0,startRow:i,endRow:a,bufferRow:t,cols:r,buffer:n}}var _S=3;function vS(e){let t=ue(e.agentId,`terminal`);if(e.followOutput)return ae(t),null;let n=Sy(e.terminal),r=gS(e,n);if(!r)return null;let i=[],a=r.startRow;for(let t=0;t<_S;t+=1){let t=gS(e,a);if(!t)break;i.push(t.text),a=t.endRow+1}if(i.length===0)return null;let o={version:1,surface:`terminal`,resource:{kind:`agent`,id:e.agentId},locator:{kind:`terminal-lines`,id:z(i),lineCount:i.length},position:{unit:`row`,value:Math.max(0,n-r.startRow)}};return B(o),o}function yS(e,t){let n=e.terminal.buffer?.active;if(!n||typeof n.getLine!=`function`)return!1;let r=Math.max(0,by(e.terminal)+Math.max(1,e.terminal.rows||1)),i=Math.max(1,t.locator.lineCount||1),a=null,o=1/0;for(let n=0;n<=r;){let r=gS(e,n);if(!r){n+=1;continue}let s=[r.text],c=r.endRow+1;for(let t=1;t<i;t+=1){let t=gS(e,c);if(!t)break;s.push(t.text),c=t.endRow+1}if(s.length===i&&z(s)===t.locator.id){let t=Math.abs(r.startRow-Sy(e.terminal));t<o&&(a=r,o=t)}n=Math.max(n+1,r.endRow+1)}return a?(Gy(e,Math.min(a.endRow,a.startRow+Math.max(0,t.position.value))),Ty(e,!1,e.hasUnreadOutput),!0):!1}function bS(e,t){let n=hS(e,t);return n?{text:n.text,col:n.col}:null}function xS(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=jx(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=Zv(t.clientX-a.left,i.width,o.length);return s===null?null:{text:o,col:s}}function SS(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:aS(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 CS(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 wS(e,t){let n=hS(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:aS(r,e,a,e===n.endRow),startCol:0});for(;;){let e=o[0];if(!e||e.row<=0)break;let t=SS(r,e.row-1,a),n=ey(t.text),i=n?ay(e.text,n.rawUrl):null;if(!n||ty(n)||!i||!iy(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=ey(o.map(e=>e.text).join(``));if(!t||ty(t)||!iy(e.text,t.rawUrl,a)||!r.getLine(e.row+1))break;let n=ay(aS(r,e.row+1,a),t.rawUrl);if(!n)break;o.push({row:e.row+1,text:n.text,startCol:n.startCol})}return CS(o,i,t.col)}function TS(e,t){let n=iS(e,t);if(n){let t=bS(e,n),r=t?Xv(t.text,t.col):null;if(r)return r}let r=xS(e,t);return r?Xv(r.text,r.col):null}function ES(e,t){let n=TS(e,t);return n?pS(e,n):null}function DS(e,t){return ES(e,t)?.pathTarget??null}function OS(e,t){let n=iS(e,t);if(n){let t=wS(e,n),r=t?oy(t.text,t.col):null;if(r)return r}let r=xS(e,t);return r?oy(r.text,r.col):null}function kS(e){return _y(e.terminal.getSelection()||``)}function AS(e,t){return(Fv(e.terminal)?kS(e):_y(gy(e.terminal)))||(!Fv(e.terminal)&&t?.includeNativeFallback?_y(MS(e.hostEl)):``)}function jS(e,t){let n=e.terminal.getSelectionPosition?.();if(!n||!e.terminal.getSelection?.())return!1;let r=iS(e,t);if(!r)return!1;let{start:i,end:a}=uy(n),o={x:r.col,y:Sy(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 MS(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 NS(e){window.open(e,`_blank`,`noopener,noreferrer`)}function PS(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 FS(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=PS(t)):(delete e.hostEl.dataset.terminalOpenTarget,e.hostEl.removeAttribute(`title`))}function IS(e){e.openModifierActive=!1,e.lastLinkHoverEvent=null,e.linkProviderHoverTarget=null,FS(e,null)}function LS(e,t,n=cS(e,t)){return e.pathOpenHandler&&DS(e,t)?`path`:n&&OS(e,t)?`url`:null}async function RS(e,t){if(!e.pathOpenHandler)return null;let n=TS(e,t);if(!n?.pathTarget)return null;let r=await dS(e,n.pathTarget);return r?{...n,pathTarget:r}:null}function zS(e,t){if(!ux(e)||Ib()){FS(e,null);return}let n=e.linkProviderHoverTarget,r=t??e.openModifierActive;if(n){FS(e,n.kind===`path`||r?n.kind:null);return}if(!e.lastLinkHoverEvent){FS(e,null);return}FS(e,LS(e,e.lastLinkHoverEvent,r))}function BS(e){e.contextMenuCleanup?.(),e.contextMenuCleanup=null,e.contextMenuEl?.remove(),e.contextMenuEl=null,e.contextMenuSelection=``}function VS(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 HS(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 US(e){e.querySelector(`button:not(:disabled)`)?.focus()}function WS(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 GS(e,t){return!(!t||e.disposed||e.attachedMount===null||(Ky(e,{allowClearUnread:!0}),!Gx(e,t)))}function KS(e){e.disposed||e.attachedMount===null||(YS(e),e.contextMenuSelection=``,e.lastNonEmptySelection=``,e.terminal.clearSearch?.(),Ty(e,!0,!1,{allowClearUnread:!0}),Je({type:`clear-terminal`,agentId:e.agentId}))}function qS(e,t,n){BS(e);let r=HS(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=WS(VS(`copy`),()=>{let t=Tb;F(n).finally(()=>{let n=ex(e,i,t);BS(e),!Ib()&&n&&$b(e)})},{disabled:!n}),o=WS(VS(`paste`),()=>{let t=Tb;N().then(t=>{GS(e,t)}).finally(()=>{let n=ex(e,i,t);BS(e),!Ib()&&n&&$b(e)})}),s=WS(VS(`selectAll`),()=>{BS(e),YS(e),requestAnimationFrame(()=>{if(e.disposed)return;let t=rS(e);e.contextMenuSelection=t,e.lastNonEmptySelection=t||e.lastNonEmptySelection,Ib()||$b(e)})},{disabled:typeof e.terminal.select!=`function`||!e.terminal.buffer?.active}),c=WS(VS(`clear`),()=>{BS(e),KS(e),Ib()||$b(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)||BS(e)},u=t=>{t.key===`Escape`&&(t.preventDefault(),BS(e),Ib()||$b(e))},d=()=>BS(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(()=>US(i))}function JS(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 YS(e){e.cachedSelection=``,e.contextMenuSelection=``,e.lastNonEmptySelection=``,e.dragSelection=null,e.terminal.clearTerminalSelection?.(),JS(e.hostEl)}function XS(e){BS(e),IS(e),YS(e)}function ZS(e){XS(e),Fv(e.terminal)&&(e.terminal.reattach?.(),e.terminal.syncAppearanceTheme?.(),e.terminal.forceRedraw?.()),Uy(e),requestAnimationFrame(()=>{e.disposed||e.attachedMount===null||(Fv(e.terminal)&&e.terminal.forceRedraw?.(),By(e))})}function QS(e,t){let n=AS(e)||e.contextMenuSelection||e.lastNonEmptySelection,r=OS(e,t),i=e.pathOpenHandler?ES(e,t):null,a=!!n&&jS(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=iS(e,t);return s?tS(e,s.col,s.row):``}function $S(e,t){let n=n=>{if(!(n.target instanceof Node)||!e.hostEl.contains(n.target))return;let r=e.pathOpenHandler?TS(e,n):null;if(r?.pathTarget){n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),dS(e,r.pathTarget).then(t=>{if(!e.disposed){if(t){qS(e,n,r.text);return}qS(e,n,QS(e,n))}});return}if(e.pathOpenHandler&&oS(n)){let r=DS(e,n);if(r){n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),e.pathOpenHandler(t,r);return}}let i=QS(e,n);n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),qS(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=AS(e)||_y(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 eC(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(-kb,Math.min(kb,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 ${Pb}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},Pb)))},x=e=>{b(Math.max(-Nb,Math.min(Nb,f+e*Mb)))},S=(e=!0)=>{f===0&&p===null||b(0,e)},C=(e,t)=>{d.push({y:e,at:t});let n=t-jb;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=QS(e,t);n&&qS(e,t,n)},E=t=>{let n=Math.max(8,jx(e)?.height||16);s+=t;let r=Math.trunc(s/n);if(r===0)return!1;s-=r*n;let i=xy(e.terminal);Wy(e,i+r);let a=xy(e.terminal)!==i;return a&&(Nx(e,{allowClearUnread:!0}),BS(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*=Ab**(n/16),!i||Math.abs(o)<Ob){i||x(r),D(),S();return}l=window.requestAnimationFrame(O)},k=()=>{if(Math.abs(o)<Ob){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,Db);try{e.hostEl.setPointerCapture(o.pointerId)}catch{}}},j=e=>{if(t===null||e.pointerId!==t)return;Math.hypot(e.clientX-n,e.clientY-r)>Eb&&(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())},M=n=>{if(t===null||n.pointerId!==t)return;let r=c;t=null,_(),r?(n.preventDefault(),n.stopPropagation(),Nx(e,{allowClearUnread:!0}),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`,j,{capture:!0,passive:!1}),e.hostEl.addEventListener(`pointerup`,M,{capture:!0,passive:!1}),e.hostEl.addEventListener(`pointercancel`,M,{capture:!0,passive:!1}),e.hostEl.addEventListener(`lostpointercapture`,M,{capture:!0,passive:!1}),e.touchInteraction={pointerDownHandler:A,pointerMoveHandler:j,pointerUpHandler:M,stopTouchMomentum:D}}function tC(){typeof window>`u`||!window.__FARMING_E2E__||window.__farmingTerminalTest||(window.__farmingTerminalTest={async writeFixture(e,t){let n=wb.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);r.bootstrapRefreshSeq+=1,zb(r),r.snapshotOutput=``,r.snapshotRuntimeEpoch=``,r.snapshotOutputSeq=null,r.snapshotStateRevision=null,r.snapshotCols=null,r.snapshotRows=null,Cb.resetRecovery(r.replayState,{keepCursor:!1}),r.replayInProgress=!1,r.liveWriteInProgress=!1,r.pendingSnapshotReplay=!1,r.bootstrappingSnapshot=!1,r.needsReconnectOutputSync=!1,r.fixtureOverrideActive=!0,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),Ty(r,Cy(r),!1,{allowClearUnread:!0}),By(r),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},async resumeLive(e){let t=wb.get(e),n=t instanceof Promise?await t:t;if(!n||n.disposed)throw Error(`Terminal session not found: ${e}`);n.fixtureOverrideActive=!1,n.suppressOutputUntil=0,zb(n),Cb.resetRecovery(n.replayState),Cb.beginRecovery(n.replayState),n.needsReconnectOutputSync=!0,Dx(n,n.attachGeneration)},getSelection(e){return fC(e)},getCellCenter(e,t,n){let r=wb.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=jx(r),a=Mx(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=wb.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=Sy(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);fy(n)||o.push(dy(n)||` `)}i.push(o.join(``).trimEnd())}return i},getHostDiagnostics(){return Array.from(document.querySelectorAll(`.terminal-session-host`)).map(e=>{let t=e,n=Rb(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?lx(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=wb.get(e);return!r||r instanceof Promise||r.disposed?``:tS(r,t,n)},getUrlAtCell(e,t,n){let r=wb.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=wS(r,{col:t,row:n});return i?oy(i.text,i.col):null},isReady(e){let t=wb.get(e);return!!(t&&!(t instanceof Promise)&&!t.disposed&&!t.bootstrappingSnapshot&&!t.pendingSnapshotReplay)},getPathAtCell(e,t,n){let r=wb.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=bS(r,{col:t,row:n});return i?qv(i.text,i.col)??Jv(i.text,i.col):null},openPathAtCell(e,t,n){let r=wb.get(e);if(!r||r instanceof Promise||r.disposed||!r.pathOpenHandler)return!1;let i=bS(r,{col:t,row:n}),a=i?qv(i.text,i.col)??Jv(i.text,i.col):null;return a?(r.pathOpenHandler(e,a),!0):!1},getCursor(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?null:t.terminal.wasmTerm?.getCursor?.()??null},getCursorVisible(e){let t=wb.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=wb.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=wb.get(e);if(!t||t instanceof Promise||t.disposed)return null;let n=t.terminal.renderer?.getCanvas?.()||t.hostEl.querySelector(`canvas`),r=jx(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||Gn.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=wb.get(e);if(!t||t instanceof Promise||t.disposed)return 0;let n=t.terminal.renderer?.getCanvas?.(),r=[...new Set([...n instanceof HTMLCanvasElement?[n]:[],...t.hostEl.querySelectorAll(`canvas`)])];if(r.length===0)return(t.hostEl.querySelector(`.xterm-rows`)?.textContent?.trim()??``).length*8;let i=0;for(let e of r){let t=null,n=e.getContext(`2d`);if(n)t=n.getImageData(0,0,e.width,e.height).data;else{let n=e.getContext(`webgl2`)||e.getContext(`webgl`);n&&(t=new Uint8Array(e.width*e.height*4),n.readPixels(0,0,e.width,e.height,n.RGBA,n.UNSIGNED_BYTE,t))}if(t)for(let e=0;e<t.length;e+=4){let n=t[e]??255,r=t[e+1]??255,a=t[e+2]??255;(t[e+3]??0)>0&&!(n>248&&r>248&&a>245)&&(i+=1)}}return i},async writeRaw(e,t){let n=wb.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);await new Promise(e=>tb(r,t,e,{isOutputObserved:()=>lx(r)})),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},async writeSequenced(e,t,n,r=``,i){let a=wb.get(e),o=a instanceof Promise?await a:a;if(!o||o.disposed)throw Error(`Terminal session not found: ${e}`);Ox(o,t,!1,n,r,i??(o.replayState.stateRevision??0)+1),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},async streamSequenced(e,t,n,r=``,i){let a=wb.get(e),o=a instanceof Promise?await a:a;if(!o||o.disposed)throw Error(`Terminal session not found: ${e}`);kx(o,t,!1,n,r,i??(o.replayState.stateRevision??0)+1)},async writeRawAndSampleViewport(e,t){let n=wb.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);let i=xy(r.terminal),a=by(r.terminal),o=i;return await new Promise(e=>{tb(r,t,e,{isOutputObserved:()=>lx(r)}),o=xy(r.terminal)}),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e()))),{before:i,during:o,after:xy(r.terminal),beforeScrollbackLength:a,afterScrollbackLength:by(r.terminal),following:r.followOutput,hasUnreadOutput:r.hasUnreadOutput}},getViewport(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?null:{viewportY:xy(t.terminal),scrollbackLength:by(t.terminal),following:t.followOutput,hasUnreadOutput:t.hasUnreadOutput}},getInputCount(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?0:t.inputCount},getLastNotifiedResize(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?null:t.lastNotifiedResize},getResizeNotificationCount(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?0:t.resizeNotificationCount},notifyResizeForTest(e,t,n){let r=wb.get(e);return!r||r instanceof Promise||r.disposed?0:(Jx(r,t,n),r.resizeNotificationCount)},getLastOutputSeq(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?null:t.replayState.outputSeq},getRuntimeEpoch(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?``:t.replayState.runtimeEpoch},getStateRevision(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?null:t.replayState.stateRevision},setCheckpointAckSuppressed(e){let t=wb.get(e);return!!(t&&!(t instanceof Promise)&&!t.disposed)},getBufferDiagnostics(e){let t=wb.get(e);if(!t||t instanceof Promise||t.disposed)return null;let n=t.terminal.buffer?.active;return{engine:t.terminal.__farmingTerminalEngine,renderer:t.terminal.getRendererType?.(),cols:t.terminal.cols||0,rows:t.terminal.rows||0,viewportY:xy(t.terminal),scrollbackLength:by(t.terminal),visibleBufferBase:Sy(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,queuedTransitions:t.replayState.queuedTransitions.length,queuedBytes:t.replayState.queuedBytes,replayTargetEpoch:t.replayState.replayTargetEpoch,replayTargetRevision:t.replayState.replayTargetRevision,checkpointHalted:t.replayState.halted,checkpointFailureCount:t.replayState.failureCount,checkpointRequestInFlight:t.checkpointRequestInFlight,replayInProgress:t.replayInProgress,bootstrappingSnapshot:t.bootstrappingSnapshot,pendingSnapshotReplay:t.pendingSnapshotReplay,runtimeEpoch:t.replayState.runtimeEpoch,stateRevision:t.replayState.stateRevision,lastOutputSeq:t.replayState.outputSeq,reconnectSnapshotSeq:t.reconnectSnapshotSeq,bootstrapRefreshSeq:t.bootstrapRefreshSeq,attachGeneration:t.attachGeneration,currentAttachment:mx(t,t.attachGeneration),attachedMount:t.attachedMount!==null,fixtureOverrideActive:t.fixtureOverrideActive,pageOutputSuspended:t.pageOutputSuspended,suppressOutputForMs:Math.max(0,t.suppressOutputUntil-Date.now()),needsReconnectOutputSync:t.needsReconnectOutputSync,lastNotifiedResize:t.lastNotifiedResize,resizeNotificationCount:t.resizeNotificationCount,resizeRequestInFlight:t.resizeRequestInFlight,pendingResizeRequest:t.pendingResizeRequest,resizeDeliveryTimeoutPending:t.resizeDeliveryTimeout!==null,pendingFitResize:t.pendingFitResize,fitResizeTimerPending:t.fitResizeTimer!==null}},async scrollToLine(e,t){let n=wb.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);r.touchInteraction?.stopTouchMomentum(),Gy(r,t);let i=Cy(r);Ty(r,i,i?!1:r.hasUnreadOutput,{allowClearUnread:i}),await new Promise(e=>requestAnimationFrame(()=>e()))},async scrollToBottom(e){let t=wb.get(e),n=t instanceof Promise?await t:t;if(!n||n.disposed)throw Error(`Terminal session not found: ${e}`);n.touchInteraction?.stopTouchMomentum(),Ky(n,{allowClearUnread:!0}),await new Promise(e=>requestAnimationFrame(()=>e()))},async search(e,t,n=`next`,r={}){return yC(e,t,n,r)},async clearSearch(e){await bC(e)},dispatchPasteToTextarea(e,t){let n=wb.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=wb.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 nC(e,t){let n=Ib()?11:12,r=await Lv({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,attachReadyHandler:null,attachReadyGeneration:null,attachReadyNotified:!1,terminal:a,fitAddon:o,unsubscribeOutput:null,selectionChangeDisposable:null,imeOverlayDisposables:[],resizeObserver:null,applyingLocalResize:!1,parkedViewportState:null,inputDisabled:!!t.inputDisabled,errorHandler:t.onError??null,rendererFailureDisposable: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,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,lastNotifiedResize:null,resizeNotificationCount:0,resizeRequestInFlight:null,pendingResizeRequest:null,resizeDeliveryTimeout:null,pendingFitResize:null,fitResizeTimer:null,followOutputHandler:t.onFollowOutputChange??null,pathOpenHandler:t.onPathOpen??null,pathResolveHandler:t.onPathResolve??null,pathResolveCache:new Map,originalRender:null,snapshotOutput:``,snapshotRuntimeEpoch:``,snapshotOutputSeq:null,snapshotStateRevision:null,snapshotCols:null,snapshotRows:null,replayState:Cb.createState(),replayInProgress:!1,liveWriteInProgress:!1,terminalWriteQueue:Promise.resolve(),terminalWriteResolvers:new Set,bootstrapRefreshSeq:0,reconnectSnapshotSeq:0,checkpointRequestInFlight:!1,checkpointRetryTimer:null,bootstrapRequestControllers:new Set,needsReconnectOutputSync:!1,pageOutputSuspended:document.visibilityState===`hidden`,pageLifecycleHandler:null,pendingSnapshotReplay:!1,bootstrappingSnapshot:!0,fixtureOverrideActive:!1,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};gx(s,t.bootstrapState),a.onData(e=>{s.inputDisabled||Gx(s,e)}),a.onResize(({cols:e,rows:t})=>{s.applyingLocalResize||s.replayInProgress||s.bootstrappingSnapshot||Jx(s,e,t)}),$S(s,e);let c=a.onRendererFailure?.(e=>{s.disposed||(s.inputDisabled=!0,Ub(s),s.errorHandler?.(e),mC(s.agentId).catch(e=>{console.error(`Failed to dispose terminal after renderer failure:`,e)}))});s.rendererFailureDisposable=c?()=>c.dispose():null,a.open(i),mS(s),a.syncAppearanceTheme?.(),requestAnimationFrame(()=>{s.disposed||a.syncAppearanceTheme?.()}),Vx(s),Rx(s,!1);let l=a.onSelectionChange?.(()=>{s.cachedSelection=gy(a),s.cachedSelection&&(s.lastNonEmptySelection=_y(s.cachedSelection))});s.selectionChangeDisposable=l?()=>l.dispose():null;let u=a.onScroll?.(()=>{Fx(s),vS(s)}),d=a.onRender?.(()=>{Fx(s)});s.scrollChangeDisposable=u||d?()=>{u?.dispose(),d?.dispose()}:null;let f=()=>Yx(s);window.addEventListener(`farming:backend-connected`,f),s.backendConnectedHandler=f;let p=e=>{let t=e.type===`pagehide`||document.visibilityState===`hidden`;if(s.pageOutputSuspended=t,t){Ub(s),s.needsReconnectOutputSync=!0;return}Xx(s)};document.addEventListener(`visibilitychange`,p),window.addEventListener(`pagehide`,p),window.addEventListener(`pageshow`,p),s.pageLifecycleHandler=p,Hx(s);let m=t=>{let n=cS(s,t),r=t.button===0&&n?OS(s,t):null;if(r)return t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),NS(r),s.suppressClickUntil=Date.now()+250,!0;if(s.pathOpenHandler&&t.button===0){let n=DS(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(Ib()||e.button!==0||e.ctrlKey||e.metaKey||e.altKey)return!1;let n=iS(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=iS(s,e);return!n||n.col===t.start.col&&n.row===t.start.row&&!t.moved?!1:(t.moved=!0,nS(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=gy(a),e.preventDefault(),e.stopPropagation(),!0)},v=e=>{if(s.openTargetMouseDown=null,Ib()||e.button!==0||e.ctrlKey||e.metaKey||e.altKey)return;let t=s.pathOpenHandler?TS(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(Ib()||t.button!==0)return;if(cS(s,t)){let e=OS(s,t);if(e){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),NS(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}AS(s)||m(t)||(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),dS(s,n.pathTarget).then(t=>{if(!s.disposed){if(!t){$b(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(!Fv(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(!Ib()){if(Date.now()<s.suppressClickUntil){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();return}m(e)||$b(s)}};i.addEventListener(`click`,x,!0),s.clickHandler=x;let S=e=>{if(Fv(a)||Ib())return;let t=iS(s,e);t&&tS(s,t.col,t.row)&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation())};i.addEventListener(`dblclick`,S,!0),s.doubleClickHandler=S;let C=e=>{if(!rx(s,e))return;let t=AS(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(!ax(s,e))return;let t=AS(s,{includeNativeFallback:!0});t&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),F(t))};document.addEventListener(`keydown`,w,!0),s.copyKeyHandler=w;let T=e=>{cx(s,e)};a.attachCustomKeyEventHandler||(document.addEventListener(`keydown`,T,!0),s.clearKeyHandler=T);let E=e=>{let t=lx(s);if(db(s.hostEl,e,t)){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();return}fb(s.hostEl,e,t)&&(Fv(s.terminal)||GS(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(!ux(s)){IS(s);return}s.lastLinkHoverEvent=e,LS(s,e)||(s.linkProviderHoverTarget=null,FS(s,null)),zS(s),RS(s,e).then(t=>{!t||s.disposed||s.lastLinkHoverEvent!==e||(s.linkProviderHoverTarget={kind:`path`,text:t.text,...t.pathTarget?{pathTarget:t.pathTarget}:{}},FS(s,`path`))})};i.addEventListener(`mousemove`,D,!0),s.linkHoverHandler=D;let O=()=>{IS(s)};i.addEventListener(`mouseleave`,O,!0),s.linkHoverLeaveHandler=O;let k=e=>{if(!ux(s)){IS(s);return}e.type===`keydown`&&[`Control`,`Meta`].includes(e.key)?s.openModifierActive=!0:s.openModifierActive=sS(e),s.lastLinkHoverEvent&&(![`Control`,`Meta`].includes(e.key)&&!s.openModifierActive||zS(s,s.openModifierActive))};window.addEventListener(`keydown`,k,!0),window.addEventListener(`keyup`,k,!0),s.linkHoverKeyHandler=k;let A=()=>{IS(s)};window.addEventListener(`blur`,A),s.linkHoverBlurHandler=A;let j=e=>{e instanceof WheelEvent&&e.deltaY<0&&Ty(s,!1,s.hasUnreadOutput),vS(s),Fx(s,{allowClearUnread:!0}),window.setTimeout(()=>Fx(s,{allowClearUnread:!0}),80)};i.addEventListener(`wheel`,j,!0),i.addEventListener(`pointerup`,j,!0),s.scrollIntentHandler=j;let M=e=>{fx(s,e)};return a.attachCustomKeyEventHandler?a.attachCustomKeyEventHandler(e=>!(cx(s,e)||fx(s,e))):(document.addEventListener(`keydown`,M,!0),i.addEventListener(`keydown`,M,!0),s.scrollKeyHandler=M),eC(s),s.resizeObserver=new ResizeObserver(()=>{requestAnimationFrame(()=>{if(!s.disposed)try{Kx(s)}catch{}})}),s.unsubscribeOutput=t.onSessionOutput(e,(e,t,n,r,i,a,o,c)=>{s.disposed||kx(s,e,t,n,r,i,a,o,c)}),tC(),s}async function rC(e,t){let n=wb.get(e);if(n)return n instanceof Promise?n:Promise.resolve(n);let r=nC(e,t).then(t=>(wb.set(e,t),t)).catch(n=>{throw wb.delete(e),t.onError?.(n instanceof Error?n:Error(String(n))),n});return wb.set(e,r),r}function iC(e,t){if(e.attachReadyNotified||e.attachReadyGeneration!==t||!mx(e,t)||e.bootstrappingSnapshot||e.pendingSnapshotReplay||e.needsReconnectOutputSync||e.replayInProgress||e.liveWriteInProgress||e.replayState.queuedTransitions.length>0||!e.replayState.runtimeEpoch||e.replayState.outputSeq===null||e.replayState.stateRevision===null)return!1;e.attachReadyNotified=!0;let n=!!(e.parkedViewportState?.following&&Cy(e));return e.parkedViewportState=null,n&&Ty(e,!0,!1,{allowClearUnread:!0}),e.attachReadyHandler?.(),!0}function aC(e,t){if(mx(e,t)){if(e.pendingSnapshotReplay&&e.snapshotRuntimeEpoch&&e.snapshotOutputSeq!==null&&e.snapshotStateRevision!==null&&e.snapshotCols!==null&&e.snapshotRows!==null&&Date.now()>=e.suppressOutputUntil){hx(e,t);return}iC(e,t)||e.replayInProgress||e.checkpointRequestInFlight||(e.needsReconnectOutputSync=!0,Dx(e,t))}}function oC(e,t,n){let r=e.followOutput,i=xy(e.terminal),a=by(e.terminal),o=e.hasUnreadOutput;requestAnimationFrame(()=>{mx(e,n)&&(Kx(e,{force:!0}),Yy(e,i,a,r,o),Uy(e),t.autoFocus&&!Ib()&&tx(e.hostEl)&&Ux(e,n),requestAnimationFrame(()=>{mx(e,n)&&(Kx(e,{force:!0}),Yy(e,i,a,r,o),Uy(e),aC(e,n))}))})}async function sC(e,t){if(t.signal?.aborted)return;let n=await rC(e,t);if(n.disposed||t.signal?.aborted||wb.get(e)!==n)return;let r=ob(n);n.attachReadyHandler=t.onReady??null,n.attachReadyGeneration=r,n.attachReadyNotified=!1,zb(n),Cb.resetRecovery(n.replayState),Cb.beginRecovery(n.replayState),Lb(n,t.mountEl),n.parkedViewportState&&(n.followOutput=n.parkedViewportState.following,n.hasUnreadOutput=n.hasUnreadOutput||n.parkedViewportState.hasUnreadOutput,n.preserveUnreadOutputUntilJump=n.preserveUnreadOutputUntilJump||n.parkedViewportState.preserveUnreadOutputUntilJump),ZS(n),n.errorHandler=t.onError??null,n.inputDisabled=!!t.inputDisabled,n.followOutputHandler=t.onFollowOutputChange??null,n.pathOpenHandler=t.onPathOpen??null,n.pathResolveHandler=t.onPathResolve??null,gx(n,t.bootstrapState),wy(n),zx(n,!!t.suppressRendererCursor),oC(n,t,r)}async function cC(e,t){let n=wb.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed||!r.bootstrappingSnapshot&&!r.needsReconnectOutputSync)return!1;zb(r);let i=gx(r,t);return!i&&!r.pendingSnapshotReplay?!1:(lx(r)&&requestAnimationFrame(()=>{!r.disposed&&r.pendingSnapshotReplay&&hx(r,r.attachGeneration)}),i)}async function lC(e,t){let n=wb.get(e);if(!n)return;let r=await n;r.disposed||wb.get(e)===r&&cb(r,t)&&Gb(r)}function uC(e,t){let n=wb.get(e);return!n||n instanceof Promise?!1:Gx(n,t)}async function dC(e){let t=wb.get(e);if(!t)return``;let n=await t;return n.disposed?``:(n.cachedSelection=gy(n.terminal),n.cachedSelection&&(n.lastNonEmptySelection=_y(n.cachedSelection)),n.cachedSelection)}function fC(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?``:(t.cachedSelection=gy(t.terminal),t.cachedSelection&&(t.lastNonEmptySelection=_y(t.cachedSelection)),t.cachedSelection)}function pC(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed||!t.replayState.runtimeEpoch||t.replayState.outputSeq===null?null:{runtimeEpoch:t.replayState.runtimeEpoch,outputSeq:t.replayState.outputSeq}}async function mC(e){let t=wb.get(e);if(!t)return;wb.delete(e);let n=await t;n.disposed||(n.disposed=!0,zb(n),Ub(n),Px(n),Qy(n),n.unsubscribeOutput?.(),n.rendererFailureDisposable?.(),n.selectionChangeDisposable?.(),n.scrollChangeDisposable?.(),n.backendConnectedHandler&&window.removeEventListener(`farming:backend-connected`,n.backendConnectedHandler),n.pageLifecycleHandler&&(document.removeEventListener(`visibilitychange`,n.pageLifecycleHandler),window.removeEventListener(`pagehide`,n.pageLifecycleHandler),window.removeEventListener(`pageshow`,n.pageLifecycleHandler)),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.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)),BS(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 hC(e){let t=new Set(e),n=[...wb.keys()].filter(e=>!t.has(e));await Promise.all(n.map(e=>mC(e)))}function gC(e){let t=wb.get(e);if(!t)return Promise.resolve(!1);if(typeof t.then!=`function`){let e=t;return Promise.resolve($b(e))}return t.then(e=>$b(e))}async function _C(e,t={}){let n=wb.get(e);if(!n)return!1;let r=await n;if(r.disposed||!lx(r))return!1;let i=r.followOutput,a=xy(r.terminal),o=by(r.terminal),s=r.hasUnreadOutput,c=()=>{r.disposed||!lx(r)||(Kx(r,{force:!0}),Yy(r,a,o,i,s),Uy(r),t.autoFocus&&!Ib()&&tx(r.hostEl)&&Ux(r,r.attachGeneration))};return requestAnimationFrame(()=>{c(),requestAnimationFrame(c)}),!0}async function vC(e){let t=wb.get(e);if(!t)return;let n=await t;n.disposed||(n.touchInteraction?.stopTouchMomentum(),Ky(n,{allowClearUnread:!0}))}async function yC(e,t,n=`next`,r={}){let i=wb.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 bC(e){let t=wb.get(e);if(!t)return;let n=await t;n.disposed||n.terminal.clearSearch?.()}function xC({agentId:e,containerRef:t,onSessionOutput:n,suppressRendererCursor:r=!1,inputDisabled:i=!1,onFollowOutputChange:a,onPathOpen:o,onPathResolve:s,onReady:c,onError:l,bootstrapState:u}){let d=(0,G.useRef)({onSessionOutput:n,onFollowOutputChange:a,onPathOpen:o,onPathResolve:s,onReady:c,onError:l,bootstrapState:u});d.current={onSessionOutput:n,onFollowOutputChange:a,onPathOpen:o,onPathResolve:s,onReady:c,onError:l,bootstrapState:u};let f=(0,G.useCallback)((e,t)=>d.current.onSessionOutput(e,t),[]),p=(0,G.useCallback)(e=>{d.current.onFollowOutputChange?.(e)},[]),m=(0,G.useCallback)((e,t)=>{d.current.onPathOpen?.(e,t)},[]),h=(0,G.useCallback)((e,t)=>d.current.onPathResolve?.(e,t)??null,[]),g=(0,G.useCallback)(()=>{d.current.onReady?.()},[]),_=(0,G.useCallback)(e=>{d.current.onError?.(e)},[]);return(0,G.useEffect)(()=>{if(!e||!t.current)return;let n=t.current,a=new AbortController,o=!1;return n.replaceChildren(),sC(e,{mountEl:n,onSessionOutput:f,suppressRendererCursor:r,inputDisabled:i,onFollowOutputChange:p,onPathOpen:m,onPathResolve:h,onError:_,bootstrapState:d.current.bootstrapState,signal:a.signal,onReady:()=>{o||g()}}).catch(e=>{console.error(`Failed to attach terminal session:`,e),_(e instanceof Error?e:Error(String(e)))}),()=>{o=!0,a.abort(),lC(e,n).catch(e=>{console.error(`Failed to detach terminal session:`,e)})}},[e,t,_,p,m,h,g,f,i,r]),(0,G.useEffect)(()=>{!e||!u?.runtimeEpoch||u.stateRevision===null||cC(e,u).catch(e=>{console.error(`Failed to apply terminal bootstrap state:`,e)})},[e,u?.runtimeEpoch,u?.outputSeq,u?.stateRevision,u?.output,u?.cols,u?.rows]),{focus:(0,G.useCallback)(()=>{let n=t.current;!e||!n||gC(e).then(t=>{if(!t)return sC(e,{mountEl:n,onSessionOutput:f,autoFocus:!0,suppressRendererCursor:r,inputDisabled:i,onFollowOutputChange:p,onPathOpen:m,onPathResolve:h,onError:_,bootstrapState:d.current.bootstrapState,onReady:g})}).catch(e=>{console.error(`Failed to focus terminal session:`,e),_(e instanceof Error?e:Error(String(e)))})},[e,t,_,p,m,h,g,f,i,r]),refreshLayout:(0,G.useCallback)((t={})=>{e&&_C(e,t).catch(e=>{console.error(`Failed to refresh terminal layout:`,e)})},[e]),getSelection:(0,G.useCallback)(async()=>e?dC(e):``,[e]),getSelectionNow:(0,G.useCallback)(()=>e?fC(e):``,[e]),getReadCutNow:(0,G.useCallback)(()=>e?pC(e):null,[e]),scrollToBottom:(0,G.useCallback)(()=>{e&&vC(e).catch(e=>{console.error(`Failed to scroll terminal session to bottom:`,e)})},[e]),search:(0,G.useCallback)((t,n=`next`,r)=>e?yC(e,t,n,r):Promise.resolve({found:!1,resultIndex:0,resultCount:0}),[e]),clearSearch:(0,G.useCallback)(()=>e?bC(e):Promise.resolve(),[e])}}function SC(e){let t=String(e||``).trim().split(/\s+/)[0]||``;return[`claude`,`codex`,`qwen`,`opencode`,`qodercli`,`aider`,`github-copilot-cli`,`amazon-q`].includes(t)}function CC(){return oe()}function wC(e){return(e.metaKey&&!e.ctrlKey||e.ctrlKey&&!e.metaKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`f`}function TC(e){return e.key===`F3`&&!e.metaKey&&!e.ctrlKey&&!e.altKey}function EC(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 DC(e,t){return!(e instanceof Node)||t?.contains(e)?!0:e===document.body||e===document.documentElement}function OC(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 kC(e){let t=e.replace(/\r/g,``).trim();if(!t)return``;let n=t.split(`
|
|
154
|
+
`))return e;let t=$v(e.split(/\r?\n/).map((e,t)=>t===0?e.trimEnd():e.trim()).join(``));return Wv(t)?t:e}function vy(e){return e.length>0&&!/\s/u.test(e)}function yy(e,t,n){return Math.max(1,(t.row-e.row)*n+(t.col-e.col)+1)}function by(e){let t=e.getScrollbackLength?.();return Number.isFinite(t)?Math.max(0,Number(t)):0}function xy(e){let t=Number(e.viewportY||0);return Number.isFinite(t)?Math.max(0,t):0}function Sy(e){let t=e.getVisibleBufferBase?.();return Number.isFinite(t)?Math.max(0,Number(t)):xy(e)}function Cy(e){return xy(e.terminal)<=0}function wy(e){e.followOutputHandler?.({following:e.followOutput,hasUnreadOutput:e.hasUnreadOutput})}function Ty(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,wy(e))}function Ey(e){e.preserveUnreadOutputUntilJump=!0,Ty(e,!1,!0)}function Dy(e,t,n){let r=by(e),i=xy(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 Oy(e,t,n){let r=by(e)-n;return Math.max(0,t+r)}function ky(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 Ay(e,t){let n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return null;let r=t.proposeDimensions();return r?ky(r.cols,r.rows):null}function jy(e,t,n,r,i={}){let a=ky(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 My(e){e.lastNotifiedResize=null}function Ny(e,t,n={}){return n.force!==!0&&(e.cols!==t.cols||e.rows!==t.rows)}function Py(e,t){return!!(e&&t&&e.cols===t.cols&&e.rows===t.rows)}function Fy(e,t,n,r){let i=ky(t,n);return i?e.resizeRequestInFlight?(e.pendingResizeRequest=i,!0):r(i.cols,i.rows)===!1?!1:(e.resizeRequestInFlight=i,!0):!1}function Iy(e,t,n){let r=ky(t,n);if(!Py(e.resizeRequestInFlight,r))return{matched:!1,preserveLocalGeometry:e.resizeRequestInFlight!==null,next:null};let i=e.pendingResizeRequest;return e.resizeRequestInFlight=null,e.pendingResizeRequest=null,!i||Py(i,r)?{matched:!0,preserveLocalGeometry:!1,next:null}:{matched:!0,preserveLocalGeometry:!0,next:i}}function Ly(e){e.resizeRequestInFlight=null,e.pendingResizeRequest=null}function Ry(e){let t=e.pendingResizeRequest;return Ly(e),t}var zy=512;function By(e){if(Fv(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||(Vy(e),t.render(n,!0,e.terminal.viewportY||0,e.terminal))}function Vy(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=Gn.background,n.fillRect(0,0,t.width,t.height),n.restore())}function Hy(e){return e===void 0?e:+(e>0)}function Uy(e){By(e),requestAnimationFrame(()=>{e.disposed||By(e)})}function Wy(e,t){let n=by(e.terminal),r=Math.max(0,Math.min(n,t));typeof e.terminal.scrollToLine==`function`?e.terminal.scrollToLine(r):e.terminal.viewportY=r,By(e)}function Gy(e,t){let n=by(e.terminal);Wy(e,n-Math.max(0,Math.min(n,t)))}function Ky(e,t={}){if(!e.disposed){if(by(e.terminal)<=0){By(e),Ty(e,!0,!1,t);return}typeof e.terminal.scrollToBottom==`function`?(e.terminal.scrollToBottom(),By(e)):Wy(e,0),Ty(e,!0,!1,t)}}function qy(e,t,n,r){e.disposed||(Wy(e,Oy(e.terminal,t,n)),Ty(e,!1,r))}function Jy(e,t,n){qy(e,t,n,!0),Ey(e)}function Yy(e,t,n,r,i){if(!e.disposed){if(r){Ky(e,{allowClearUnread:!e.preserveUnreadOutputUntilJump});return}qy(e,t,n,i)}}function Xy(e,t,n){e.terminal.write(t,n)}function Zy(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 Qy(e){let t=Array.from(e.terminalWriteResolvers);e.terminalWriteResolvers.clear(),t.forEach(e=>e(!0))}function $y(e,t){e()&&t?.()}function eb(e,t,n){if(!t||e.disposed||!Fv(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 tb(e,t,n,r={}){if(!t){n?.();return}Zy(e,i=>{if(e.disposed){$y(i,n);return}let a=xy(e.terminal),o=by(e.terminal),s=e.followOutput,c=r.quiet===!0||t.length>=zy,l=r.isOutputObserved?.()??!0;c&&(e.suspendRendering=!0),Xy(e,t,()=>{if(e.disposed){$y(i,n);return}e.suspendRendering=!1,s?l?c?Ky(e,{allowClearUnread:!e.preserveUnreadOutputUntilJump}):Ty(e,!0,!1,{allowClearUnread:!e.preserveUnreadOutputUntilJump}):Ey(e):l?(Jy(e,a,o),requestAnimationFrame(()=>{e.disposed||(Jy(e,a,o),By(e))})):Ey(e),l&&By(e),$y(i,n)})},n)}function nb(e,t,n,r={}){Zy(e,i=>{if(e.disposed){$y(i,n);return}let a=xy(e.terminal),o=by(e.terminal),s=e.followOutput;if(e.suspendRendering=!0,e.terminal.reset(),!t){e.suspendRendering=!1,By(e),$y(i,n);return}Xy(e,t,()=>{if(e.disposed){$y(i,n);return}e.suspendRendering=!1,s?Ky(e,{allowClearUnread:!e.preserveUnreadOutputUntilJump}):Jy(e,a,o),!s&&o===by(e.terminal)&&By(e),eb(e,r.cursor??null,()=>{if(e.disposed){$y(i,n);return}By(e),$y(i,n)})})},n)}function rb(){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 ib(e){return!e.disposed&&e.attachedMount!==null&&e.hostEl.parentElement===e.attachedMount}function ab(e,t){return e.attachGeneration===t&&ib(e)}function ob(e){return e.attachGeneration+=1,e.attachGeneration}function sb(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 cb(e,t){return!(e.disposed||t&&e.attachedMount!==t||t&&e.hostEl.parentElement!==t)}function lb(e){return e.disposed?!1:(e.attachedMount=null,e.attachGeneration+=1,rb().appendChild(e.hostEl),!0)}function ub(e,t){let n=t.target;return n instanceof Node&&e.contains(n)}function db(e,t,n){return!n&&ub(e,t)}function fb(e,t,n){return n&&ub(e,t)}function pb(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 mb(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 hb(e){let t=e.session&&typeof e.session==`object`?e.session.runtimeEpoch:e.runtimeEpoch;return typeof t==`string`?t:``}function gb(e){let t=e.session&&typeof e.session==`object`?e.session.stateRevision:e.stateRevision,n=Number(t);return Number.isFinite(n)&&n>=0?n:null}function _b(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:null}function vb(e){let t=e.session&&typeof e.session==`object`?e.session:null;return{cols:_b(t?.previewCols??t?.cols??e.previewCols??e.cols),rows:_b(t?.previewRows??t?.rows??e.previewRows??e.rows)}}function yb(e){let t=pb(e),n=e.session&&typeof e.session==`object`?e.session.output??``:e.output??``,r=vb(e);return{runtimeEpoch:hb(e),output:t,textOutput:n,cursor:null,outputSeq:mb(e),stateRevision:gb(e),cols:r.cols,rows:r.rows}}var bb=5e3,xb=250,Sb=1500,Cb=FarmingTerminalReplay,wb=new Map,Tb=0,Eb=6,Db=520,Ob=.025,kb=3.2,Ab=.972,jb=90,Mb=.28,Nb=30,Pb=240,Fb=3e4;function Ib(){return oe()}function Lb(e,t){sb(e,t,()=>Jb(e.hostEl,t)),Kb(e)}function Rb(e){for(let t of wb.values())if(!(t instanceof Promise)&&t.hostEl===e)return t;return null}function zb(e){e.reconnectSnapshotSeq+=1,yx(e),e.bootstrapRequestControllers.forEach(e=>e.abort()),e.bootstrapRequestControllers.clear(),e.checkpointRequestInFlight=!1}function Bb(e){e.resizeDeliveryTimeout!==null&&(window.clearTimeout(e.resizeDeliveryTimeout),e.resizeDeliveryTimeout=null)}function Vb(e){e.fitResizeTimer!==null&&(window.clearTimeout(e.fitResizeTimer),e.fitResizeTimer=null),e.pendingFitResize=null}function Hb(e,t){e.fitResizeTimer!==null&&window.clearTimeout(e.fitResizeTimer),e.pendingFitResize=t,e.fitResizeTimer=window.setTimeout(()=>{e.fitResizeTimer=null;let t=e.pendingFitResize;e.pendingFitResize=null,!(!t||e.disposed)&&Jx(e,t.cols,t.rows)},xb)}function Ub(e){Vb(e),Bb(e),Ly(e)}function Wb(e){Bb(e),e.resizeDeliveryTimeout=window.setTimeout(()=>{e.resizeDeliveryTimeout=null;let t=Ry(e);!t||e.disposed||qx(e,t.cols,t.rows)},Sb)}function Gb(e){e.disposed||(e.parkedViewportState={viewportY:xy(e.terminal),scrollbackLength:by(e.terminal),following:e.followOutput,hasUnreadOutput:e.hasUnreadOutput,preserveUnreadOutputUntilJump:e.preserveUnreadOutputUntilJump,readingAnchor:vS(e)},zb(e),Ub(e),e.followOutputHandler=null,e.pathOpenHandler=null,e.pathResolveHandler=null,qb(e),XS(e),lb(e))}function Kb(e){e.disposed||!e.resizeObserver||e.resizeObserver.observe(e.hostEl)}function qb(e){e.resizeObserver?.disconnect()}function Jb(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=Rb(t);n?Gb(n):rb().appendChild(t)})}function Yb(e){let t=e.dataset.terminalFontSize,n=t?Number(t):NaN;return Number.isFinite(n)&&n>0?n:12}async function Xb(e,t){let n=await fetch(r(`/api/agents/${e}/session-view`),{signal:t});if(!n.ok)throw Error(`Terminal session view failed: ${n.status}`);return yb(await n.json())}async function Zb(e){let t=new AbortController;e.bootstrapRequestControllers.add(t);let n=window.setTimeout(()=>t.abort(new DOMException(`Terminal checkpoint request timed out`,`TimeoutError`)),bb);try{return await Xb(e.agentId,t.signal)}finally{window.clearTimeout(n),e.bootstrapRequestControllers.delete(t)}}function Qb(e,t){if(Fv(t))return t.focus(),!0;let n=e.querySelector(`textarea`);return n instanceof HTMLTextAreaElement?(px(e,t),n.focus(),!0):(t.focus(),!1)}function $b(e){return e.disposed||e.attachedMount===null?!1:(Tb+=1,Qb(e.hostEl,e.terminal))}function ex(e,t,n){if(e.disposed||e.attachedMount===null||Tb!==n)return!1;let r=document.activeElement;return r===document.body||t.contains(r)||e.hostEl.contains(r)}function tx(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 nx(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 rx(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(nx(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 ix(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 ax(e,t){if(!ix(t)||e.disposed||e.attachedMount===null)return!1;let n=t.target;if(n instanceof Node&&e.hostEl.contains(n))return!0;if(nx(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 ox(e){return e.key.toLowerCase()!==`k`||e.altKey||e.shiftKey||e.ctrlKey?!1:navigator.platform.toLowerCase().includes(`mac`)&&e.metaKey}function sx(e,t){if(!ox(t)||e.disposed||e.attachedMount===null)return!1;let n=t.target;return n instanceof Node&&e.hostEl.contains(n)}function cx(e,t){return sx(e,t)?(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),KS(e),!0):!1}function lx(e){return ib(e)}function ux(e){return lx(e)}function dx(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 fx(e,t){if(!dx(e,t))return!1;t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation();let n=Dy(e.terminal,t.key===`PageUp`?`PageUp`:`PageDown`,10);return Wy(e,n),Ty(e,n<=0,n<=0?!1:e.hasUnreadOutput,{allowClearUnread:n<=0}),wy(e),!0}function px(e,t){let n=e.querySelector(`textarea`),r=t.renderer?.getMetrics?.(),i=t.wasmTerm?.getCursor?.();if(!(n instanceof HTMLTextAreaElement)||!r||!i)return;let a=Yb(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=Kn,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 mx(e,t){return ab(e,t)}function hx(e,t=e.attachGeneration){if(!(e.fixtureOverrideActive||e.disposed||!e.pendingSnapshotReplay||!mx(e,t))){if(e.pendingSnapshotReplay=!1,!e.snapshotRuntimeEpoch||e.snapshotOutputSeq===null||e.snapshotStateRevision===null||e.snapshotCols===null||e.snapshotRows===null){Dx(e,t);return}Ex(e,{runtimeEpoch:e.snapshotRuntimeEpoch,output:e.snapshotOutput,textOutput:``,cursor:null,outputSeq:e.snapshotOutputSeq,stateRevision:e.snapshotStateRevision,cols:e.snapshotCols,rows:e.snapshotRows},t)}}function gx(e,t){if(!t||e.fixtureOverrideActive)return!1;let n=_x(t);return Cb.evaluateCheckpoint(e.replayState,n).action!==`install`||t.runtimeEpoch===e.snapshotRuntimeEpoch&&e.snapshotStateRevision!==null&&t.stateRevision<=e.snapshotStateRevision?!1:(e.snapshotOutput=t.output,e.snapshotRuntimeEpoch=t.runtimeEpoch,e.snapshotOutputSeq=t.outputSeq,e.snapshotStateRevision=t.stateRevision,e.snapshotCols=t.cols,e.snapshotRows=t.rows,e.pendingSnapshotReplay=!0,e.bootstrappingSnapshot=!0,e.needsReconnectOutputSync=!0,!0)}function _x(e){return{runtimeEpoch:e.runtimeEpoch,outputSeq:e.outputSeq,stateRevision:e.stateRevision,cols:e.cols,rows:e.rows}}function vx(e,t){Cb.queueTransition(e.replayState,t).queued||(e.needsReconnectOutputSync=!0,e.bootstrappingSnapshot=!0,Dx(e,e.attachGeneration))}function yx(e){e.checkpointRetryTimer!==null&&(window.clearTimeout(e.checkpointRetryTimer),e.checkpointRetryTimer=null)}function bx(e,t,n=e.attachGeneration){e.disposed||e.replayState.halted||e.checkpointRetryTimer!==null||(e.checkpointRetryTimer=window.setTimeout(()=>{e.checkpointRetryTimer=null,!(e.disposed||!mx(e,n))&&Dx(e,n)},t))}function xx(e,t,n){if(e.checkpointRequestInFlight=!1,e.needsReconnectOutputSync=!0,e.bootstrappingSnapshot=!0,t.halted){Sx(e,t.message);return}bx(e,t.delay,n)}function Sx(e,t){yx(e),e.checkpointRequestInFlight=!1,e.replayInProgress=!1,e.bootstrappingSnapshot=!1,e.pendingSnapshotReplay=!1,Cb.clearQueuedTransitions(e.replayState),e.hostEl.classList.add(`terminal-checkpoint-installing`),Wx(e,t)}function Cx(e,t){if(!(e.disposed||!mx(e,t)||e.replayInProgress||e.checkpointRequestInFlight||e.pendingSnapshotReplay||e.liveWriteInProgress)&&!(e.replayState.queuedTransitions.length>0&&(Ax(e),e.replayState.queuedTransitions.length>0||e.liveWriteInProgress||e.checkpointRequestInFlight))){if(e.needsReconnectOutputSync||Cb.isReplayTargetPending(e.replayState)){Dx(e,t);return}e.bootstrappingSnapshot=!1,Ub(e),requestAnimationFrame(()=>{!mx(e,t)||e.disposed||(e.hostEl.classList.remove(`terminal-checkpoint-installing`),Kx(e,{force:!0}),iC(e,t))})}}function wx(e){if(e.parkedViewportState)return{...e.parkedViewportState,hasUnreadOutput:e.parkedViewportState.hasUnreadOutput||e.hasUnreadOutput,preserveUnreadOutputUntilJump:e.parkedViewportState.preserveUnreadOutputUntilJump||e.preserveUnreadOutputUntilJump};let t=ne(ue(e.agentId,`terminal`)),n=t?.surface===`terminal`?t:vS(e);return{viewportY:xy(e.terminal),scrollbackLength:by(e.terminal),following:n?!1:e.followOutput,hasUnreadOutput:e.hasUnreadOutput,preserveUnreadOutputUntilJump:e.preserveUnreadOutputUntilJump,readingAnchor:n}}function Tx(e,t){if(e.followOutput=t.following,e.hasUnreadOutput=t.hasUnreadOutput,e.preserveUnreadOutputUntilJump=t.preserveUnreadOutputUntilJump,t.following){Yy(e,t.viewportY,t.scrollbackLength,!0,t.hasUnreadOutput);return}t.readingAnchor&&yS(e,t.readingAnchor)||(ae(ue(e.agentId,`terminal`)),Ky(e,{allowClearUnread:!0}))}function Ex(e,t,n){if(e.disposed||!mx(e,n))return!1;e.checkpointRequestInFlight=!1;let r=_x(t),i=Cb.evaluateCheckpoint(e.replayState,r);if(i.action===`reject`)return xx(e,Cb.recordInvariantFailure(e.replayState,i.signature||`invalid-checkpoint`,i.message||`Terminal replay returned an invalid screen state`),n),!1;if(i.action===`current`&&e.terminal.cols===t.cols&&e.terminal.rows===t.rows){let t=wx(e);return Cb.commitCheckpoint(e.replayState,r),e.needsReconnectOutputSync=!1,e.bootstrappingSnapshot=!1,Tx(e,t),Ax(e),Cx(e,n),!0}let a=e.reconnectSnapshotSeq+1;e.reconnectSnapshotSeq=a;let o=wx(e);if(e.replayInProgress=!0,e.bootstrappingSnapshot=!0,e.hostEl.classList.add(`terminal-checkpoint-installing`),e.terminal.cols!==t.cols||e.terminal.rows!==t.rows){e.applyingLocalResize=!0;try{e.terminal.resize?.(t.cols,t.rows)}finally{e.applyingLocalResize=!1}}return nb(e,t.output,()=>{e.disposed||!mx(e,n)||e.reconnectSnapshotSeq!==a||(Cb.commitCheckpoint(e.replayState,r),e.followOutput=o.following,e.hasUnreadOutput=o.hasUnreadOutput,e.preserveUnreadOutputUntilJump=o.preserveUnreadOutputUntilJump,Tx(e,o),e.replayInProgress=!1,e.needsReconnectOutputSync=!1,e.bootstrappingSnapshot=!1,Ix(e),Ax(e),Cx(e,n))}),!0}function Dx(e,t=e.attachGeneration){if(e.disposed||e.fixtureOverrideActive||e.pageOutputSuspended||e.checkpointRequestInFlight||e.checkpointRetryTimer!==null||e.replayInProgress||e.replayState.halted||!mx(e,t))return;Cb.beginRecovery(e.replayState);let n=e.reconnectSnapshotSeq+1;e.reconnectSnapshotSeq=n,e.checkpointRequestInFlight=!0,e.bootstrappingSnapshot=!0,e.needsReconnectOutputSync=!0,Zb(e).then(r=>{e.disposed||e.reconnectSnapshotSeq!==n||e.pageOutputSuspended||!mx(e,t)||(e.checkpointRequestInFlight=!1,Ex(e,r,t))}).catch(r=>{e.disposed||e.reconnectSnapshotSeq!==n||(xx(e,Cb.recordTransportFailure(e.replayState),t),r instanceof Error&&r.name!==`AbortError`&&console.warn(`Terminal replay request failed; retrying:`,r))})}function Ox(e,t,n,r,i=``,a,o,s,c=`output`){if(n){if(e.fixtureOverrideActive||e.pageOutputSuspended)return;zb(e),Ex(e,{runtimeEpoch:i,output:t,textOutput:``,cursor:null,outputSeq:Number.isFinite(r)?r:null,stateRevision:Number.isFinite(a)?a:null,cols:Number.isFinite(o)?o:null,rows:Number.isFinite(s)?s:null},e.attachGeneration);return}let l={kind:c,data:t,outputSeq:r,runtimeEpoch:i,stateRevision:a,cols:o,rows:s},u=Cb.classifyTransition(e.replayState,l);if(u.action===`drop`)return;if(u.action===`recover`){vx(e,l),e.needsReconnectOutputSync=!0,e.bootstrappingSnapshot=!0,Dx(e);return}if(c===`resize`){let t=Math.floor(o),n=Math.floor(s),r=Iy(e,t,n);if(r.matched&&Bb(e),!r.preserveLocalGeometry&&(e.terminal.cols!==t||e.terminal.rows!==n)){e.applyingLocalResize=!0;try{e.terminal.resize?.(t,n)}finally{e.applyingLocalResize=!1}}Cb.commitTransition(e.replayState,l),r.next&&qx(e,r.next.cols,r.next.rows),Ix(e),Ax(e),iC(e,e.attachGeneration);return}let d=c===`clear`?`\x1B[2J\x1B[3J\x1B[H`:t;if(!d){Cb.commitTransition(e.replayState,l),Ax(e);return}e.liveWriteInProgress=!0,tb(e,d,()=>{e.disposed||(Cb.commitTransition(e.replayState,l),c===`clear`&&e.terminal.clearTerminalSelection?.(),e.liveWriteInProgress=!1,e.followOutput&&!e.hasUnreadOutput&&wy(e),Ix(e),Ax(e),e.hostEl.classList.contains(`terminal-checkpoint-installing`)?Cx(e,e.attachGeneration):iC(e,e.attachGeneration))},{isOutputObserved:()=>lx(e)})}function kx(e,t,n,r,i=``,a,o,s,c=`output`){if(e.disposed||Date.now()<e.suppressOutputUntil)return;if(e.pageOutputSuspended||document.visibilityState===`hidden`){Cb.clearQueuedTransitions(e.replayState),Cb.beginRecovery(e.replayState,{kind:c,data:t,outputSeq:r,runtimeEpoch:i,stateRevision:a,cols:o,rows:s}),e.needsReconnectOutputSync=!0;return}let l=e.needsReconnectOutputSync||e.bootstrappingSnapshot||e.pendingSnapshotReplay||e.replayInProgress||e.checkpointRequestInFlight||e.replayState.recovering;if(e.liveWriteInProgress&&!l){vx(e,{kind:c,data:t,outputSeq:r,runtimeEpoch:i,stateRevision:a,cols:o,rows:s});return}if(l){if(n){Ox(e,t,!0,r,i,a,o,s,c);return}vx(e,{kind:c,data:t,outputSeq:r,runtimeEpoch:i,stateRevision:a,cols:o,rows:s}),e.bootstrappingSnapshot=!0,Dx(e);return}Ox(e,t,n,r,i,a,o,s,c)}function Ax(e){if(!(e.disposed||e.bootstrappingSnapshot||e.pendingSnapshotReplay||e.replayInProgress||e.checkpointRequestInFlight||e.liveWriteInProgress))for(;!e.bootstrappingSnapshot&&!e.replayInProgress&&!e.checkpointRequestInFlight&&!e.liveWriteInProgress;){let t=Cb.takeQueuedTransition(e.replayState);if(!t)break;Ox(e,t.data,!1,t.outputSeq,t.runtimeEpoch,t.stateRevision,t.cols,t.rows,t.kind)}}function jx(e){return e.terminal.getCellMetrics?.()??e.terminal.renderer?.getMetrics?.()}function Mx(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 Nx(e,t={}){let n=Cy(e);Ty(e,n,n?!1:e.hasUnreadOutput,{allowClearUnread:n&&t.allowClearUnread===!0})}function Px(e){Cb.clearQueuedTransitions(e.replayState),e.bootstrappingSnapshot=!1,e.pendingSnapshotReplay=!1}function Fx(e,t={}){e.followCheckFrame!==null&&cancelAnimationFrame(e.followCheckFrame),e.followCheckFrame=requestAnimationFrame(()=>{if(e.followCheckFrame=null,e.disposed||!lx(e))return;let n=Cy(e);Ty(e,n,n?!1:e.hasUnreadOutput,{allowClearUnread:n&&t.allowClearUnread===!0})})}function Ix(e){e.imeComposing&&requestAnimationFrame(()=>{!e.disposed&&e.imeComposing&&px(e.hostEl,e.terminal)})}function Lx(e){return Fv(e.terminal)?!1:e.imeComposing||e.suppressRendererCursor}function Rx(e,t=!0){let n=e.terminal.renderer;if(!e.disposed){if(e.hostEl.classList.toggle(`terminal-renderer-cursor-suppressed`,Lx(e)),!n){t&&By(e);return}Lx(e)?n.cursorVisible=!1:!e.imeComposing&&e.rendererCursorWasVisible!==void 0&&(n.cursorVisible=e.rendererCursorWasVisible,e.rendererCursorWasVisible=void 0),t&&By(e)}}function zx(e,t){if(e.suppressRendererCursor===t){e.hostEl.classList.toggle(`terminal-renderer-cursor-suppressed`,Lx(e));return}e.suppressRendererCursor=t,Rx(e)}function Bx(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,Rx(e);return}if(e.imeComposing){if(e.imeComposing=!1,e.suppressRendererCursor){n.cursorVisible=!1,By(e);return}n.cursorVisible=e.rendererCursorWasVisible??!0,e.rendererCursorWasVisible=void 0,By(e)}}}function Vx(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=Hy(s);if(!e.suspendRendering){if(!Lx(e)){n(r,i,a,o,c);return}t.cursorVisible=!1,n(r,!0,a,o,c),t.cursorVisible=!1}}}function Hx(e){if(Fv(e.terminal))return;let t=e.hostEl.querySelector(`textarea`);if(!(t instanceof HTMLTextAreaElement))return;let n=()=>{e.disposed||px(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`),Bx(e,!0)},o=()=>{Bx(e,!1),requestAnimationFrame(()=>{e.hostEl.classList.remove(`terminal-ime-active`),t.classList.remove(`terminal-ime-composing`),t.value=``,n()})},s=()=>{Bx(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 Ux(e,t,n=12){if(mx(e,t)&&tx(e.hostEl)){if(e.replayInProgress||e.bootstrappingSnapshot||e.pendingSnapshotReplay){if(n<=0)return;requestAnimationFrame(()=>{Ux(e,t,n-1)});return}$b(e)||n<=0||requestAnimationFrame(()=>{Ux(e,t,n-1)})}}function Wx(e,t){e.errorHandler?.(Error(t))}function Gx(e,t){return e.disposed||e.attachedMount===null||e.inputDisabled||!Je({type:`input`,agentId:e.agentId,...Array.isArray(t)?{inputParts:t}:{input:t}})?!1:(e.fixtureOverrideActive=!1,e.inputCount+=1,e.contextMenuSelection=``,e.lastNonEmptySelection=``,!0)}function Kx(e,t={}){try{let n=Ay(e.hostEl,e.fitAddon);if(!n)return;let r={cols:e.terminal.cols||n.cols,rows:e.terminal.rows||n.rows};if(r.cols===n.cols&&r.rows===n.rows){Vb(e);return}if(Ny(r,n,t)){Hb(e,n);return}Vb(e),Jx(e,n.cols,n.rows,t)}catch{}}function qx(e,t,n){if(!lx(e)||e.replayInProgress||e.bootstrappingSnapshot||e.pageOutputSuspended)return!1;let r=e.resizeRequestInFlight!==null,i=Fy(e,t,n,(t,n)=>Je({type:`resize-agent`,agentId:e.agentId,cols:t,rows:n}));return i&&!r&&e.resizeRequestInFlight&&Wb(e),i}function Jx(e,t,n,r={}){!lx(e)||e.replayInProgress||e.bootstrappingSnapshot||jy(e,t,n,(t,n)=>{if(typeof e.terminal.resize!=`function`)return!1;if(e.terminal.cols!==t||e.terminal.rows!==n){e.applyingLocalResize=!0;try{e.terminal.resize(t,n)}finally{e.applyingLocalResize=!1}}return qx(e,t,n)},r)}function Yx(e){My(e),Ub(e),Cb.resetRecovery(e.replayState),Cb.beginRecovery(e.replayState),e.needsReconnectOutputSync=!0,!(e.disposed||e.pageOutputSuspended)&&(!e.attachedMount||e.hostEl.parentElement!==e.attachedMount||(zb(e),Dx(e,e.attachGeneration)))}function Xx(e){My(e),Ub(e),Cb.resetRecovery(e.replayState),Cb.beginRecovery(e.replayState),e.needsReconnectOutputSync=!0,!(e.disposed||e.pageOutputSuspended)&&(!e.attachedMount||e.hostEl.parentElement!==e.attachedMount||(zb(e),Dx(e,e.attachGeneration)))}function Zx(e,t){return Math.max(0,(typeof e?.length==`number`?e.length:t)-1)}function Qx(e,t,n){return dy(e.getLine(t)?.getCell?.(n))}function $x(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:Zx(a,r)}}function eS(e,t,n,r){if(n<Zx(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 tS(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=Sy(e.terminal)+n;if(!vy(Qx(r,a,t)))return``;let o={row:a,col:t};for(;;){let e=$x(r,o.row,o.col,i);if(!e||!vy(Qx(r,e.row,e.col)))break;o=e}if(/^[#$%>]$/u.test(Qx(r,o.row,o.col))){let e=eS(r,o.row,o.col,i);e&&(o=e)}let s={row:a,col:t};for(;;){let e=eS(r,s.row,s.col,i);if(!e||!vy(Qx(r,e.row,e.col)))break;s=e}return e.terminal.select(o.col,o.row,yy(o,s,i)),e.cachedSelection=gy(e.terminal),e.cachedSelection}function nS(e,t,n){let r=e.terminal.buffer?.active,i=e.terminal.cols||80;if(!r||typeof e.terminal.select!=`function`)return``;let a=Sy(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,yy(c.start,c.end,i)),e.cachedSelection=gy(e.terminal),e.cachedSelection}function rS(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:Sy(e.terminal)+(e.terminal.rows||1),i=Math.max(0,r-1),a=Zx(t.getLine(i),n);return e.terminal.select(0,0,yy({row:0,col:0},{row:i,col:a},n)),e.cachedSelection=gy(e.terminal),e.cachedSelection}function iS(e,t){let n=jx(e),r=Mx(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 aS(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+=dy(i.getCell(e))||` `;return r?o.trimEnd():o}function oS(e){return e.button===0&&(e.ctrlKey||e.metaKey)}function sS(e){return e.ctrlKey||e.metaKey}function cS(e,t){return sS(t)||e.openModifierActive}function lS(e,t){if(!e.decorations){e.decorations=t;return}e.decorations.pointerCursor=t.pointerCursor,e.decorations.underline=t.underline}function uS(e){return[e.path,e.lineNumber??``,e.column??``,e.endColumn??``].join(`\0`)}async function dS(e,t){if(!e.pathResolveHandler)return t;let n=uS(t),r=e.pathResolveCache.get(n);if(r&&Date.now()-r.resolvedAt<=Fb)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 fS(e,t){return e.pathResolveHandler?(await Promise.all(t.map(async t=>{if(t.kind!==`path`||!t.pathTarget)return t;let n=await dS(e,t.pathTarget);return n?{...t,pathTarget:n}:null}))).filter(e=>!!e):t}function pS(e,t){if(!e.pathResolveHandler||t.kind!==`path`||!t.pathTarget)return t;let n=e.pathResolveCache.get(uS(t.pathTarget));return!n||n.promise||Date.now()-n.resolvedAt>Fb?null:n.target?{...t,pathTarget:n.target}:null}function mS(e){if(!Fv(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=e.attachGeneration,i=gS(e,t-1);if(!i?.text){n(void 0);return}let a=cy(i.text,!!e.pathOpenHandler);if(a.length===0){n(void 0);return}(async()=>{let t=await fS(e,a);if(!mx(e,r)){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),a={range:ly(t,i),text:t.text,decorations:{pointerCursor:n,underline:n||t.kind===`url`},activate:i=>{if(i.button!==0||Date.now()<e.suppressClickUntil||!mx(e,r))return;let a=cS(e,i);t.kind===`url`&&OS(e,i)!==t.text||t.kind===`path`&&TS(e,i)?.text!==t.text||t.kind===`url`&&!a||t.kind===`path`&&!n||(i.preventDefault(),i.stopPropagation(),i.stopImmediatePropagation(),t.kind===`url`?NS(t.text):t.pathTarget&&e.pathOpenHandler&&e.pathOpenHandler(e.agentId,t.pathTarget),e.suppressClickUntil=Date.now()+250)},hover:r=>{if(!ux(e)||Ib())return;e.linkProviderHoverTarget={kind:t.kind,text:t.text,...t.pathTarget?{pathTarget:t.pathTarget}:{}},e.lastLinkHoverEvent=r;let i=n||cS(e,r);lS(a,{pointerCursor:i,underline:n||t.kind===`url`||i}),zS(e,i)},leave:()=>{e.linkProviderHoverTarget?.text===t.text&&(e.linkProviderHoverTarget=null),lS(a,{pointerCursor:n,underline:n||t.kind===`url`}),IS(e)},dispose:()=>{e.linkProviderHoverTarget?.text===t.text&&(e.linkProviderHoverTarget=null)}};return a}))})()}});e.linkProviderDisposable=()=>t.dispose()}function hS(e,t){let n=e.terminal.buffer?.active;if(!t||!n||typeof n.getLine!=`function`)return null;let r=Sy(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(aS(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 gS(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(aS(n,e,r,e===a));return{text:o.join(``).trimEnd(),col:0,startRow:i,endRow:a,bufferRow:t,cols:r,buffer:n}}var _S=3;function vS(e){let t=ue(e.agentId,`terminal`);if(e.followOutput)return ae(t),null;let n=Sy(e.terminal),r=gS(e,n);if(!r)return null;let i=[],a=r.startRow;for(let t=0;t<_S;t+=1){let t=gS(e,a);if(!t)break;i.push(t.text),a=t.endRow+1}if(i.length===0)return null;let o={version:1,surface:`terminal`,resource:{kind:`agent`,id:e.agentId},locator:{kind:`terminal-lines`,id:z(i),lineCount:i.length},position:{unit:`row`,value:Math.max(0,n-r.startRow)}};return B(o),o}function yS(e,t){let n=e.terminal.buffer?.active;if(!n||typeof n.getLine!=`function`)return!1;let r=Math.max(0,by(e.terminal)+Math.max(1,e.terminal.rows||1)),i=Math.max(1,t.locator.lineCount||1),a=null,o=1/0;for(let n=0;n<=r;){let r=gS(e,n);if(!r){n+=1;continue}let s=[r.text],c=r.endRow+1;for(let t=1;t<i;t+=1){let t=gS(e,c);if(!t)break;s.push(t.text),c=t.endRow+1}if(s.length===i&&z(s)===t.locator.id){let t=Math.abs(r.startRow-Sy(e.terminal));t<o&&(a=r,o=t)}n=Math.max(n+1,r.endRow+1)}return a?(Gy(e,Math.min(a.endRow,a.startRow+Math.max(0,t.position.value))),Ty(e,!1,e.hasUnreadOutput),!0):!1}function bS(e,t){let n=hS(e,t);return n?{text:n.text,col:n.col}:null}function xS(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=jx(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=Zv(t.clientX-a.left,i.width,o.length);return s===null?null:{text:o,col:s}}function SS(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:aS(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 CS(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 wS(e,t){let n=hS(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:aS(r,e,a,e===n.endRow),startCol:0});for(;;){let e=o[0];if(!e||e.row<=0)break;let t=SS(r,e.row-1,a),n=ey(t.text),i=n?ay(e.text,n.rawUrl):null;if(!n||ty(n)||!i||!iy(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=ey(o.map(e=>e.text).join(``));if(!t||ty(t)||!iy(e.text,t.rawUrl,a)||!r.getLine(e.row+1))break;let n=ay(aS(r,e.row+1,a),t.rawUrl);if(!n)break;o.push({row:e.row+1,text:n.text,startCol:n.startCol})}return CS(o,i,t.col)}function TS(e,t){let n=iS(e,t);if(n){let t=bS(e,n);if(t)return Xv(t.text,t.col)}let r=xS(e,t);return r?Xv(r.text,r.col):null}function ES(e,t){let n=TS(e,t);return n?pS(e,n):null}function DS(e,t){return ES(e,t)?.pathTarget??null}function OS(e,t){let n=iS(e,t);if(n){let t=wS(e,n),r=t?oy(t.text,t.col):null;if(r)return r}let r=xS(e,t);return r?oy(r.text,r.col):null}function kS(e){return _y(e.terminal.getSelection()||``)}function AS(e,t){return(Fv(e.terminal)?kS(e):_y(gy(e.terminal)))||(!Fv(e.terminal)&&t?.includeNativeFallback?_y(MS(e.hostEl)):``)}function jS(e,t){let n=e.terminal.getSelectionPosition?.();if(!n||!e.terminal.getSelection?.())return!1;let r=iS(e,t);if(!r)return!1;let{start:i,end:a}=uy(n),o={x:r.col,y:Sy(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 MS(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 NS(e){window.open(e,`_blank`,`noopener,noreferrer`)}function PS(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 FS(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=PS(t)):(delete e.hostEl.dataset.terminalOpenTarget,e.hostEl.removeAttribute(`title`))}function IS(e){e.openModifierActive=!1,e.lastLinkHoverEvent=null,e.linkProviderHoverTarget=null,FS(e,null)}function LS(e,t,n=cS(e,t)){return e.pathOpenHandler&&DS(e,t)?`path`:n&&OS(e,t)?`url`:null}async function RS(e,t){if(!e.pathOpenHandler)return null;let n=TS(e,t);if(!n?.pathTarget)return null;let r=await dS(e,n.pathTarget);return r?{...n,pathTarget:r}:null}function zS(e,t){if(!ux(e)||Ib()){FS(e,null);return}let n=e.linkProviderHoverTarget,r=t??e.openModifierActive;if(n){FS(e,n.kind===`path`||r?n.kind:null);return}if(!e.lastLinkHoverEvent){FS(e,null);return}FS(e,LS(e,e.lastLinkHoverEvent,r))}function BS(e){e.contextMenuCleanup?.(),e.contextMenuCleanup=null,e.contextMenuEl?.remove(),e.contextMenuEl=null,e.contextMenuSelection=``}function VS(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 HS(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 US(e){e.querySelector(`button:not(:disabled)`)?.focus()}function WS(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 GS(e,t){return!(!t||e.disposed||e.attachedMount===null||(Ky(e,{allowClearUnread:!0}),!Gx(e,t)))}function KS(e){e.disposed||e.attachedMount===null||(YS(e),e.contextMenuSelection=``,e.lastNonEmptySelection=``,e.terminal.clearSearch?.(),Ty(e,!0,!1,{allowClearUnread:!0}),Je({type:`clear-terminal`,agentId:e.agentId}))}function qS(e,t,n){BS(e);let r=HS(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=WS(VS(`copy`),()=>{let t=Tb;F(n).finally(()=>{let n=ex(e,i,t);BS(e),!Ib()&&n&&$b(e)})},{disabled:!n}),o=WS(VS(`paste`),()=>{let t=Tb;N().then(t=>{GS(e,t)}).finally(()=>{let n=ex(e,i,t);BS(e),!Ib()&&n&&$b(e)})}),s=WS(VS(`selectAll`),()=>{BS(e),YS(e),requestAnimationFrame(()=>{if(e.disposed)return;let t=rS(e);e.contextMenuSelection=t,e.lastNonEmptySelection=t||e.lastNonEmptySelection,Ib()||$b(e)})},{disabled:typeof e.terminal.select!=`function`||!e.terminal.buffer?.active}),c=WS(VS(`clear`),()=>{BS(e),KS(e),Ib()||$b(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)||BS(e)},u=t=>{t.key===`Escape`&&(t.preventDefault(),BS(e),Ib()||$b(e))},d=()=>BS(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(()=>US(i))}function JS(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 YS(e){e.cachedSelection=``,e.contextMenuSelection=``,e.lastNonEmptySelection=``,e.dragSelection=null,e.terminal.clearTerminalSelection?.(),JS(e.hostEl)}function XS(e){BS(e),IS(e),YS(e)}function ZS(e){XS(e),Fv(e.terminal)&&(e.terminal.reattach?.(),e.terminal.syncAppearanceTheme?.(),e.terminal.forceRedraw?.()),Uy(e),requestAnimationFrame(()=>{e.disposed||e.attachedMount===null||(Fv(e.terminal)&&e.terminal.forceRedraw?.(),By(e))})}function QS(e,t){let n=AS(e)||e.contextMenuSelection||e.lastNonEmptySelection,r=OS(e,t),i=e.pathOpenHandler?ES(e,t):null,a=!!n&&jS(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=iS(e,t);return s?tS(e,s.col,s.row):``}function $S(e,t){let n=n=>{if(!(n.target instanceof Node)||!e.hostEl.contains(n.target))return;let r=e.pathOpenHandler?TS(e,n):null;if(r?.pathTarget){n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),dS(e,r.pathTarget).then(t=>{if(!e.disposed){if(t){qS(e,n,r.text);return}qS(e,n,QS(e,n))}});return}if(e.pathOpenHandler&&oS(n)){let r=DS(e,n);if(r){n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),e.pathOpenHandler(t,r);return}}let i=QS(e,n);n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),qS(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=AS(e)||_y(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 eC(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(-kb,Math.min(kb,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 ${Pb}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},Pb)))},x=e=>{b(Math.max(-Nb,Math.min(Nb,f+e*Mb)))},S=(e=!0)=>{f===0&&p===null||b(0,e)},C=(e,t)=>{d.push({y:e,at:t});let n=t-jb;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=QS(e,t);n&&qS(e,t,n)},E=t=>{let n=Math.max(8,jx(e)?.height||16);s+=t;let r=Math.trunc(s/n);if(r===0)return!1;s-=r*n;let i=xy(e.terminal);Wy(e,i+r);let a=xy(e.terminal)!==i;return a&&(Nx(e,{allowClearUnread:!0}),BS(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*=Ab**(n/16),!i||Math.abs(o)<Ob){i||x(r),D(),S();return}l=window.requestAnimationFrame(O)},k=()=>{if(Math.abs(o)<Ob){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,Db);try{e.hostEl.setPointerCapture(o.pointerId)}catch{}}},j=e=>{if(t===null||e.pointerId!==t)return;Math.hypot(e.clientX-n,e.clientY-r)>Eb&&(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())},M=n=>{if(t===null||n.pointerId!==t)return;let r=c;t=null,_(),r?(n.preventDefault(),n.stopPropagation(),Nx(e,{allowClearUnread:!0}),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`,j,{capture:!0,passive:!1}),e.hostEl.addEventListener(`pointerup`,M,{capture:!0,passive:!1}),e.hostEl.addEventListener(`pointercancel`,M,{capture:!0,passive:!1}),e.hostEl.addEventListener(`lostpointercapture`,M,{capture:!0,passive:!1}),e.touchInteraction={pointerDownHandler:A,pointerMoveHandler:j,pointerUpHandler:M,stopTouchMomentum:D}}function tC(){typeof window>`u`||!window.__FARMING_E2E__||window.__farmingTerminalTest||(window.__farmingTerminalTest={async writeFixture(e,t){let n=wb.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);r.bootstrapRefreshSeq+=1,zb(r),r.snapshotOutput=``,r.snapshotRuntimeEpoch=``,r.snapshotOutputSeq=null,r.snapshotStateRevision=null,r.snapshotCols=null,r.snapshotRows=null,Cb.resetRecovery(r.replayState,{keepCursor:!1}),r.replayInProgress=!1,r.liveWriteInProgress=!1,r.pendingSnapshotReplay=!1,r.bootstrappingSnapshot=!1,r.needsReconnectOutputSync=!1,r.fixtureOverrideActive=!0,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),Ty(r,Cy(r),!1,{allowClearUnread:!0}),By(r),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},async resumeLive(e){let t=wb.get(e),n=t instanceof Promise?await t:t;if(!n||n.disposed)throw Error(`Terminal session not found: ${e}`);n.fixtureOverrideActive=!1,n.suppressOutputUntil=0,zb(n),Cb.resetRecovery(n.replayState),Cb.beginRecovery(n.replayState),n.needsReconnectOutputSync=!0,Dx(n,n.attachGeneration)},getSelection(e){return fC(e)},getCellCenter(e,t,n){let r=wb.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=jx(r),a=Mx(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=wb.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=Sy(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);fy(n)||o.push(dy(n)||` `)}i.push(o.join(``).trimEnd())}return i},getHostDiagnostics(){return Array.from(document.querySelectorAll(`.terminal-session-host`)).map(e=>{let t=e,n=Rb(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?lx(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=wb.get(e);return!r||r instanceof Promise||r.disposed?``:tS(r,t,n)},getUrlAtCell(e,t,n){let r=wb.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=wS(r,{col:t,row:n});return i?oy(i.text,i.col):null},isReady(e){let t=wb.get(e);return!!(t&&!(t instanceof Promise)&&!t.disposed&&!t.bootstrappingSnapshot&&!t.pendingSnapshotReplay)},getPathAtCell(e,t,n){let r=wb.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=bS(r,{col:t,row:n});return i?qv(i.text,i.col)??Jv(i.text,i.col):null},openPathAtCell(e,t,n){let r=wb.get(e);if(!r||r instanceof Promise||r.disposed||!r.pathOpenHandler)return!1;let i=bS(r,{col:t,row:n}),a=i?qv(i.text,i.col)??Jv(i.text,i.col):null;return a?(r.pathOpenHandler(e,a),!0):!1},getCursor(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?null:t.terminal.wasmTerm?.getCursor?.()??null},getCursorVisible(e){let t=wb.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=wb.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=wb.get(e);if(!t||t instanceof Promise||t.disposed)return null;let n=t.terminal.renderer?.getCanvas?.()||t.hostEl.querySelector(`canvas`),r=jx(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||Gn.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=wb.get(e);if(!t||t instanceof Promise||t.disposed)return 0;let n=t.terminal.renderer?.getCanvas?.(),r=[...new Set([...n instanceof HTMLCanvasElement?[n]:[],...t.hostEl.querySelectorAll(`canvas`)])];if(r.length===0)return(t.hostEl.querySelector(`.xterm-rows`)?.textContent?.trim()??``).length*8;let i=0;for(let e of r){let t=null,n=e.getContext(`2d`);if(n)t=n.getImageData(0,0,e.width,e.height).data;else{let n=e.getContext(`webgl2`)||e.getContext(`webgl`);n&&(t=new Uint8Array(e.width*e.height*4),n.readPixels(0,0,e.width,e.height,n.RGBA,n.UNSIGNED_BYTE,t))}if(t)for(let e=0;e<t.length;e+=4){let n=t[e]??255,r=t[e+1]??255,a=t[e+2]??255;(t[e+3]??0)>0&&!(n>248&&r>248&&a>245)&&(i+=1)}}return i},async writeRaw(e,t){let n=wb.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);await new Promise(e=>tb(r,t,e,{isOutputObserved:()=>lx(r)})),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},async writeSequenced(e,t,n,r=``,i){let a=wb.get(e),o=a instanceof Promise?await a:a;if(!o||o.disposed)throw Error(`Terminal session not found: ${e}`);Ox(o,t,!1,n,r,i??(o.replayState.stateRevision??0)+1),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},async streamSequenced(e,t,n,r=``,i){let a=wb.get(e),o=a instanceof Promise?await a:a;if(!o||o.disposed)throw Error(`Terminal session not found: ${e}`);kx(o,t,!1,n,r,i??(o.replayState.stateRevision??0)+1)},async writeRawAndSampleViewport(e,t){let n=wb.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);let i=xy(r.terminal),a=by(r.terminal),o=i;return await new Promise(e=>{tb(r,t,e,{isOutputObserved:()=>lx(r)}),o=xy(r.terminal)}),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e()))),{before:i,during:o,after:xy(r.terminal),beforeScrollbackLength:a,afterScrollbackLength:by(r.terminal),following:r.followOutput,hasUnreadOutput:r.hasUnreadOutput}},getViewport(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?null:{viewportY:xy(t.terminal),scrollbackLength:by(t.terminal),following:t.followOutput,hasUnreadOutput:t.hasUnreadOutput}},getInputCount(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?0:t.inputCount},getLastNotifiedResize(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?null:t.lastNotifiedResize},getResizeNotificationCount(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?0:t.resizeNotificationCount},notifyResizeForTest(e,t,n){let r=wb.get(e);return!r||r instanceof Promise||r.disposed?0:(Jx(r,t,n),r.resizeNotificationCount)},getLastOutputSeq(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?null:t.replayState.outputSeq},getRuntimeEpoch(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?``:t.replayState.runtimeEpoch},getStateRevision(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?null:t.replayState.stateRevision},setCheckpointAckSuppressed(e){let t=wb.get(e);return!!(t&&!(t instanceof Promise)&&!t.disposed)},getBufferDiagnostics(e){let t=wb.get(e);if(!t||t instanceof Promise||t.disposed)return null;let n=t.terminal.buffer?.active;return{engine:t.terminal.__farmingTerminalEngine,renderer:t.terminal.getRendererType?.(),cols:t.terminal.cols||0,rows:t.terminal.rows||0,viewportY:xy(t.terminal),scrollbackLength:by(t.terminal),visibleBufferBase:Sy(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,queuedTransitions:t.replayState.queuedTransitions.length,queuedBytes:t.replayState.queuedBytes,replayTargetEpoch:t.replayState.replayTargetEpoch,replayTargetRevision:t.replayState.replayTargetRevision,checkpointHalted:t.replayState.halted,checkpointFailureCount:t.replayState.failureCount,checkpointRequestInFlight:t.checkpointRequestInFlight,replayInProgress:t.replayInProgress,bootstrappingSnapshot:t.bootstrappingSnapshot,pendingSnapshotReplay:t.pendingSnapshotReplay,runtimeEpoch:t.replayState.runtimeEpoch,stateRevision:t.replayState.stateRevision,lastOutputSeq:t.replayState.outputSeq,reconnectSnapshotSeq:t.reconnectSnapshotSeq,bootstrapRefreshSeq:t.bootstrapRefreshSeq,attachGeneration:t.attachGeneration,currentAttachment:mx(t,t.attachGeneration),attachedMount:t.attachedMount!==null,fixtureOverrideActive:t.fixtureOverrideActive,pageOutputSuspended:t.pageOutputSuspended,suppressOutputForMs:Math.max(0,t.suppressOutputUntil-Date.now()),needsReconnectOutputSync:t.needsReconnectOutputSync,lastNotifiedResize:t.lastNotifiedResize,resizeNotificationCount:t.resizeNotificationCount,resizeRequestInFlight:t.resizeRequestInFlight,pendingResizeRequest:t.pendingResizeRequest,resizeDeliveryTimeoutPending:t.resizeDeliveryTimeout!==null,pendingFitResize:t.pendingFitResize,fitResizeTimerPending:t.fitResizeTimer!==null}},async scrollToLine(e,t){let n=wb.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);r.touchInteraction?.stopTouchMomentum(),Gy(r,t);let i=Cy(r);Ty(r,i,i?!1:r.hasUnreadOutput,{allowClearUnread:i}),await new Promise(e=>requestAnimationFrame(()=>e()))},async scrollToBottom(e){let t=wb.get(e),n=t instanceof Promise?await t:t;if(!n||n.disposed)throw Error(`Terminal session not found: ${e}`);n.touchInteraction?.stopTouchMomentum(),Ky(n,{allowClearUnread:!0}),await new Promise(e=>requestAnimationFrame(()=>e()))},async search(e,t,n=`next`,r={}){return yC(e,t,n,r)},async clearSearch(e){await bC(e)},dispatchPasteToTextarea(e,t){let n=wb.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=wb.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 nC(e,t){let n=Ib()?11:12,r=await Lv({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,attachReadyHandler:null,attachReadyGeneration:null,attachReadyNotified:!1,terminal:a,fitAddon:o,unsubscribeOutput:null,selectionChangeDisposable:null,imeOverlayDisposables:[],resizeObserver:null,applyingLocalResize:!1,parkedViewportState:null,inputDisabled:!!t.inputDisabled,errorHandler:t.onError??null,rendererFailureDisposable: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,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,lastNotifiedResize:null,resizeNotificationCount:0,resizeRequestInFlight:null,pendingResizeRequest:null,resizeDeliveryTimeout:null,pendingFitResize:null,fitResizeTimer:null,followOutputHandler:t.onFollowOutputChange??null,pathOpenHandler:t.onPathOpen??null,pathResolveHandler:t.onPathResolve??null,pathResolveCache:new Map,originalRender:null,snapshotOutput:``,snapshotRuntimeEpoch:``,snapshotOutputSeq:null,snapshotStateRevision:null,snapshotCols:null,snapshotRows:null,replayState:Cb.createState(),replayInProgress:!1,liveWriteInProgress:!1,terminalWriteQueue:Promise.resolve(),terminalWriteResolvers:new Set,bootstrapRefreshSeq:0,reconnectSnapshotSeq:0,checkpointRequestInFlight:!1,checkpointRetryTimer:null,bootstrapRequestControllers:new Set,needsReconnectOutputSync:!1,pageOutputSuspended:document.visibilityState===`hidden`,pageLifecycleHandler:null,pendingSnapshotReplay:!1,bootstrappingSnapshot:!0,fixtureOverrideActive:!1,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};gx(s,t.bootstrapState),a.onData(e=>{s.inputDisabled||Gx(s,e)}),a.onResize(({cols:e,rows:t})=>{s.applyingLocalResize||s.replayInProgress||s.bootstrappingSnapshot||Jx(s,e,t)}),$S(s,e);let c=a.onRendererFailure?.(e=>{s.disposed||(s.inputDisabled=!0,Ub(s),s.errorHandler?.(e),mC(s.agentId).catch(e=>{console.error(`Failed to dispose terminal after renderer failure:`,e)}))});s.rendererFailureDisposable=c?()=>c.dispose():null,a.open(i),mS(s),a.syncAppearanceTheme?.(),requestAnimationFrame(()=>{s.disposed||a.syncAppearanceTheme?.()}),Vx(s),Rx(s,!1);let l=a.onSelectionChange?.(()=>{s.cachedSelection=gy(a),s.cachedSelection&&(s.lastNonEmptySelection=_y(s.cachedSelection))});s.selectionChangeDisposable=l?()=>l.dispose():null;let u=a.onScroll?.(()=>{Fx(s),vS(s)}),d=a.onRender?.(()=>{Fx(s)});s.scrollChangeDisposable=u||d?()=>{u?.dispose(),d?.dispose()}:null;let f=()=>Yx(s);window.addEventListener(`farming:backend-connected`,f),s.backendConnectedHandler=f;let p=e=>{let t=e.type===`pagehide`||document.visibilityState===`hidden`;if(s.pageOutputSuspended=t,t){Ub(s),s.needsReconnectOutputSync=!0;return}Xx(s)};document.addEventListener(`visibilitychange`,p),window.addEventListener(`pagehide`,p),window.addEventListener(`pageshow`,p),s.pageLifecycleHandler=p,Hx(s);let m=t=>{let n=cS(s,t),r=t.button===0&&n?OS(s,t):null;if(r)return t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),NS(r),s.suppressClickUntil=Date.now()+250,!0;if(s.pathOpenHandler&&t.button===0){let n=DS(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(Ib()||e.button!==0||e.ctrlKey||e.metaKey||e.altKey)return!1;let n=iS(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=iS(s,e);return!n||n.col===t.start.col&&n.row===t.start.row&&!t.moved?!1:(t.moved=!0,nS(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=gy(a),e.preventDefault(),e.stopPropagation(),!0)},v=e=>{if(s.openTargetMouseDown=null,Ib()||e.button!==0||e.ctrlKey||e.metaKey||e.altKey)return;let t=s.pathOpenHandler?TS(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(Ib()||t.button!==0)return;if(Date.now()<s.suppressClickUntil){s.openTargetMouseDown=null;return}if(cS(s,t)){let e=OS(s,t);if(e){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),NS(e),s.suppressClickUntil=Date.now()+250;return}}let n=s.openTargetMouseDown;if(s.openTargetMouseDown=null,!n)return;if(Math.hypot(t.clientX-n.x,t.clientY-n.y)>4){s.suppressClickUntil=Date.now()+250;return}if(AS(s)||m(t))return;t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),s.suppressClickUntil=Date.now()+250;let r=s.attachGeneration;dS(s,n.pathTarget).then(t=>{if(mx(s,r)){if(!t){$b(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(!Fv(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(!Ib()){if(Date.now()<s.suppressClickUntil){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();return}m(e)||$b(s)}};i.addEventListener(`click`,x,!0),s.clickHandler=x;let S=e=>{if(Fv(a)||Ib())return;let t=iS(s,e);t&&tS(s,t.col,t.row)&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation())};i.addEventListener(`dblclick`,S,!0),s.doubleClickHandler=S;let C=e=>{if(!rx(s,e))return;let t=AS(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(!ax(s,e))return;let t=AS(s,{includeNativeFallback:!0});t&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),F(t))};document.addEventListener(`keydown`,w,!0),s.copyKeyHandler=w;let T=e=>{cx(s,e)};a.attachCustomKeyEventHandler||(document.addEventListener(`keydown`,T,!0),s.clearKeyHandler=T);let E=e=>{let t=lx(s);if(db(s.hostEl,e,t)){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();return}fb(s.hostEl,e,t)&&(Fv(s.terminal)||GS(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(!ux(s)){IS(s);return}s.lastLinkHoverEvent=e,LS(s,e)||(s.linkProviderHoverTarget=null,FS(s,null)),zS(s),RS(s,e).then(t=>{!t||s.disposed||s.lastLinkHoverEvent!==e||(s.linkProviderHoverTarget={kind:`path`,text:t.text,...t.pathTarget?{pathTarget:t.pathTarget}:{}},FS(s,`path`))})};i.addEventListener(`mousemove`,D,!0),s.linkHoverHandler=D;let O=()=>{IS(s)};i.addEventListener(`mouseleave`,O,!0),s.linkHoverLeaveHandler=O;let k=e=>{if(!ux(s)){IS(s);return}e.type===`keydown`&&[`Control`,`Meta`].includes(e.key)?s.openModifierActive=!0:s.openModifierActive=sS(e),s.lastLinkHoverEvent&&(![`Control`,`Meta`].includes(e.key)&&!s.openModifierActive||zS(s,s.openModifierActive))};window.addEventListener(`keydown`,k,!0),window.addEventListener(`keyup`,k,!0),s.linkHoverKeyHandler=k;let A=()=>{IS(s)};window.addEventListener(`blur`,A),s.linkHoverBlurHandler=A;let j=e=>{e instanceof WheelEvent&&e.deltaY<0&&Ty(s,!1,s.hasUnreadOutput),vS(s),Fx(s,{allowClearUnread:!0}),window.setTimeout(()=>Fx(s,{allowClearUnread:!0}),80)};i.addEventListener(`wheel`,j,!0),i.addEventListener(`pointerup`,j,!0),s.scrollIntentHandler=j;let M=e=>{fx(s,e)};return a.attachCustomKeyEventHandler?a.attachCustomKeyEventHandler(e=>!(cx(s,e)||fx(s,e))):(document.addEventListener(`keydown`,M,!0),i.addEventListener(`keydown`,M,!0),s.scrollKeyHandler=M),eC(s),s.resizeObserver=new ResizeObserver(()=>{requestAnimationFrame(()=>{if(!s.disposed)try{Kx(s)}catch{}})}),s.unsubscribeOutput=t.onSessionOutput(e,(e,t,n,r,i,a,o,c)=>{s.disposed||kx(s,e,t,n,r,i,a,o,c)}),tC(),s}async function rC(e,t){let n=wb.get(e);if(n)return n instanceof Promise?n:Promise.resolve(n);let r=nC(e,t).then(t=>(wb.set(e,t),t)).catch(n=>{throw wb.delete(e),t.onError?.(n instanceof Error?n:Error(String(n))),n});return wb.set(e,r),r}function iC(e,t){if(e.attachReadyNotified||e.attachReadyGeneration!==t||!mx(e,t)||e.bootstrappingSnapshot||e.pendingSnapshotReplay||e.needsReconnectOutputSync||e.replayInProgress||e.liveWriteInProgress||e.replayState.queuedTransitions.length>0||!e.replayState.runtimeEpoch||e.replayState.outputSeq===null||e.replayState.stateRevision===null)return!1;e.attachReadyNotified=!0;let n=!!(e.parkedViewportState?.following&&Cy(e));return e.parkedViewportState=null,n&&Ty(e,!0,!1,{allowClearUnread:!0}),e.attachReadyHandler?.(),!0}function aC(e,t){if(mx(e,t)){if(e.pendingSnapshotReplay&&e.snapshotRuntimeEpoch&&e.snapshotOutputSeq!==null&&e.snapshotStateRevision!==null&&e.snapshotCols!==null&&e.snapshotRows!==null&&Date.now()>=e.suppressOutputUntil){hx(e,t);return}iC(e,t)||e.replayInProgress||e.checkpointRequestInFlight||(e.needsReconnectOutputSync=!0,Dx(e,t))}}function oC(e,t,n){let r=e.followOutput,i=xy(e.terminal),a=by(e.terminal),o=e.hasUnreadOutput;requestAnimationFrame(()=>{mx(e,n)&&(Kx(e,{force:!0}),Yy(e,i,a,r,o),Uy(e),t.autoFocus&&!Ib()&&tx(e.hostEl)&&Ux(e,n),requestAnimationFrame(()=>{mx(e,n)&&(Kx(e,{force:!0}),Yy(e,i,a,r,o),Uy(e),aC(e,n))}))})}async function sC(e,t){if(t.signal?.aborted)return;let n=await rC(e,t);if(n.disposed||t.signal?.aborted||wb.get(e)!==n)return;let r=ob(n);n.attachReadyHandler=t.onReady??null,n.attachReadyGeneration=r,n.attachReadyNotified=!1,zb(n),Cb.resetRecovery(n.replayState),Cb.beginRecovery(n.replayState),Lb(n,t.mountEl),n.parkedViewportState&&(n.followOutput=n.parkedViewportState.following,n.hasUnreadOutput=n.hasUnreadOutput||n.parkedViewportState.hasUnreadOutput,n.preserveUnreadOutputUntilJump=n.preserveUnreadOutputUntilJump||n.parkedViewportState.preserveUnreadOutputUntilJump),ZS(n),n.errorHandler=t.onError??null,n.inputDisabled=!!t.inputDisabled,n.followOutputHandler=t.onFollowOutputChange??null,n.pathOpenHandler=t.onPathOpen??null,n.pathResolveHandler=t.onPathResolve??null,gx(n,t.bootstrapState),wy(n),zx(n,!!t.suppressRendererCursor),oC(n,t,r)}async function cC(e,t){let n=wb.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed||!r.bootstrappingSnapshot&&!r.needsReconnectOutputSync)return!1;zb(r);let i=gx(r,t);return!i&&!r.pendingSnapshotReplay?!1:(lx(r)&&requestAnimationFrame(()=>{!r.disposed&&r.pendingSnapshotReplay&&hx(r,r.attachGeneration)}),i)}async function lC(e,t){let n=wb.get(e);if(!n)return;let r=await n;r.disposed||wb.get(e)===r&&cb(r,t)&&Gb(r)}function uC(e,t){let n=wb.get(e);return!n||n instanceof Promise?!1:Gx(n,t)}async function dC(e){let t=wb.get(e);if(!t)return``;let n=await t;return n.disposed?``:(n.cachedSelection=gy(n.terminal),n.cachedSelection&&(n.lastNonEmptySelection=_y(n.cachedSelection)),n.cachedSelection)}function fC(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed?``:(t.cachedSelection=gy(t.terminal),t.cachedSelection&&(t.lastNonEmptySelection=_y(t.cachedSelection)),t.cachedSelection)}function pC(e){let t=wb.get(e);return!t||t instanceof Promise||t.disposed||!t.replayState.runtimeEpoch||t.replayState.outputSeq===null?null:{runtimeEpoch:t.replayState.runtimeEpoch,outputSeq:t.replayState.outputSeq}}async function mC(e){let t=wb.get(e);if(!t)return;wb.delete(e);let n=await t;n.disposed||(n.disposed=!0,zb(n),Ub(n),Px(n),Qy(n),n.unsubscribeOutput?.(),n.rendererFailureDisposable?.(),n.selectionChangeDisposable?.(),n.scrollChangeDisposable?.(),n.backendConnectedHandler&&window.removeEventListener(`farming:backend-connected`,n.backendConnectedHandler),n.pageLifecycleHandler&&(document.removeEventListener(`visibilitychange`,n.pageLifecycleHandler),window.removeEventListener(`pagehide`,n.pageLifecycleHandler),window.removeEventListener(`pageshow`,n.pageLifecycleHandler)),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.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)),BS(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 hC(e){let t=new Set(e),n=[...wb.keys()].filter(e=>!t.has(e));await Promise.all(n.map(e=>mC(e)))}function gC(e){let t=wb.get(e);if(!t)return Promise.resolve(!1);if(typeof t.then!=`function`){let e=t;return Promise.resolve($b(e))}return t.then(e=>$b(e))}async function _C(e,t={}){let n=wb.get(e);if(!n)return!1;let r=await n;if(r.disposed||!lx(r))return!1;let i=r.followOutput,a=xy(r.terminal),o=by(r.terminal),s=r.hasUnreadOutput,c=()=>{r.disposed||!lx(r)||(Kx(r,{force:!0}),Yy(r,a,o,i,s),Uy(r),t.autoFocus&&!Ib()&&tx(r.hostEl)&&Ux(r,r.attachGeneration))};return requestAnimationFrame(()=>{c(),requestAnimationFrame(c)}),!0}async function vC(e){let t=wb.get(e);if(!t)return;let n=await t;n.disposed||(n.touchInteraction?.stopTouchMomentum(),Ky(n,{allowClearUnread:!0}))}async function yC(e,t,n=`next`,r={}){let i=wb.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 bC(e){let t=wb.get(e);if(!t)return;let n=await t;n.disposed||n.terminal.clearSearch?.()}function xC({agentId:e,containerRef:t,onSessionOutput:n,suppressRendererCursor:r=!1,inputDisabled:i=!1,onFollowOutputChange:a,onPathOpen:o,onPathResolve:s,onReady:c,onError:l,bootstrapState:u}){let d=(0,G.useRef)({onSessionOutput:n,onFollowOutputChange:a,onPathOpen:o,onPathResolve:s,onReady:c,onError:l,bootstrapState:u});d.current={onSessionOutput:n,onFollowOutputChange:a,onPathOpen:o,onPathResolve:s,onReady:c,onError:l,bootstrapState:u};let f=(0,G.useCallback)((e,t)=>d.current.onSessionOutput(e,t),[]),p=(0,G.useCallback)(e=>{d.current.onFollowOutputChange?.(e)},[]),m=(0,G.useCallback)((e,t)=>{d.current.onPathOpen?.(e,t)},[]),h=(0,G.useCallback)((e,t)=>d.current.onPathResolve?.(e,t)??null,[]),g=(0,G.useCallback)(()=>{d.current.onReady?.()},[]),_=(0,G.useCallback)(e=>{d.current.onError?.(e)},[]);return(0,G.useEffect)(()=>{if(!e||!t.current)return;let n=t.current,a=new AbortController,o=!1;return n.replaceChildren(),sC(e,{mountEl:n,onSessionOutput:f,suppressRendererCursor:r,inputDisabled:i,onFollowOutputChange:p,onPathOpen:m,onPathResolve:h,onError:_,bootstrapState:d.current.bootstrapState,signal:a.signal,onReady:()=>{o||g()}}).catch(e=>{console.error(`Failed to attach terminal session:`,e),_(e instanceof Error?e:Error(String(e)))}),()=>{o=!0,a.abort(),lC(e,n).catch(e=>{console.error(`Failed to detach terminal session:`,e)})}},[e,t,_,p,m,h,g,f,i,r]),(0,G.useEffect)(()=>{!e||!u?.runtimeEpoch||u.stateRevision===null||cC(e,u).catch(e=>{console.error(`Failed to apply terminal bootstrap state:`,e)})},[e,u?.runtimeEpoch,u?.outputSeq,u?.stateRevision,u?.output,u?.cols,u?.rows]),{focus:(0,G.useCallback)(()=>{let n=t.current;!e||!n||gC(e).then(t=>{if(!t)return sC(e,{mountEl:n,onSessionOutput:f,autoFocus:!0,suppressRendererCursor:r,inputDisabled:i,onFollowOutputChange:p,onPathOpen:m,onPathResolve:h,onError:_,bootstrapState:d.current.bootstrapState,onReady:g})}).catch(e=>{console.error(`Failed to focus terminal session:`,e),_(e instanceof Error?e:Error(String(e)))})},[e,t,_,p,m,h,g,f,i,r]),refreshLayout:(0,G.useCallback)((t={})=>{e&&_C(e,t).catch(e=>{console.error(`Failed to refresh terminal layout:`,e)})},[e]),getSelection:(0,G.useCallback)(async()=>e?dC(e):``,[e]),getSelectionNow:(0,G.useCallback)(()=>e?fC(e):``,[e]),getReadCutNow:(0,G.useCallback)(()=>e?pC(e):null,[e]),scrollToBottom:(0,G.useCallback)(()=>{e&&vC(e).catch(e=>{console.error(`Failed to scroll terminal session to bottom:`,e)})},[e]),search:(0,G.useCallback)((t,n=`next`,r)=>e?yC(e,t,n,r):Promise.resolve({found:!1,resultIndex:0,resultCount:0}),[e]),clearSearch:(0,G.useCallback)(()=>e?bC(e):Promise.resolve(),[e])}}function SC(e){let t=String(e||``).trim().split(/\s+/)[0]||``;return[`claude`,`codex`,`qwen`,`opencode`,`qodercli`,`aider`,`github-copilot-cli`,`amazon-q`].includes(t)}function CC(){return oe()}function wC(e){return(e.metaKey&&!e.ctrlKey||e.ctrlKey&&!e.metaKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`f`}function TC(e){return e.key===`F3`&&!e.metaKey&&!e.ctrlKey&&!e.altKey}function EC(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 DC(e,t){return!(e instanceof Node)||t?.contains(e)?!0:e===document.body||e===document.documentElement}function OC(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 kC(e){let t=e.replace(/\r/g,``).trim();if(!t)return``;let n=t.split(`
|
|
155
155
|
`).map(e=>e.trim()).filter(Boolean);if(n.length!==1)return``;let r=n[0];return r?r.slice(0,240):``}function AC(e){return`code-terminal-search-button option${e?` active`:``}`}function jC({agent:e,active:t,focusSignal:n,onActivate:r,onSessionOutput:i,onOpenPath:a,onResolvePath:o,onFollowOutputChange:s,onReadLatest:c,copy:l}){let u=(0,G.useRef)(null),d=(0,G.useRef)(null),f=(0,G.useRef)(null),[p,m]=(0,G.useState)({following:!0,hasUnreadOutput:!1}),[h,g]=(0,G.useState)(!1),[_,v]=(0,G.useState)(!1),[y,b]=(0,G.useState)(``),[x,S]=(0,G.useState)({}),[C,w]=(0,G.useState)(null),[T,E]=(0,G.useState)(null),D=Tn(e)&&e.runtimeBinding.observerDeferred,O=(0,G.useCallback)(t=>{g(!0),m(t),s?.(e.id,t)},[e.id,s]),k=(0,G.useCallback)(()=>{E(null)},[]),A=(0,G.useCallback)(e=>{E(e.message||l.terminalSessionUnavailable)},[l.terminalSessionUnavailable]),{focus:j,refreshLayout:M,getSelectionNow:N,getReadCutNow:P,scrollToBottom:F,search:ee,clearSearch:I}=xC({agentId:e.id,containerRef:d,onSessionOutput:i,inputDisabled:D,suppressRendererCursor:SC(e.command),onFollowOutputChange:O,onPathOpen:a,onPathResolve:o,onReady:k,onError:A});(0,G.useEffect)(()=>{if(!t||!h||e.unread!==!0||!p.following||p.hasUnreadOutput)return;let n=P();if(!n)return;let r=e.attentionOutputEpoch||``,i=Number(e.attentionOutputSeq);r&&(r!==n.runtimeEpoch||Number.isFinite(i)&&i>n.outputSeq)||c?.(e.id,n)},[t,e.attentionOutputEpoch,e.attentionOutputSeq,e.id,e.unread,p.following,p.hasUnreadOutput,h,P,c]);let te=(0,G.useCallback)((e=!1)=>{window.requestAnimationFrame(()=>{M({autoFocus:e}),window.requestAnimationFrame(()=>M({autoFocus:e}))})},[M]);(0,G.useEffect)(()=>{t&&te(!1)},[t,te]),(0,G.useEffect)(()=>{!t||n<=0||CC()||(te(!0),j())},[t,j,n,te]),(0,G.useEffect)(()=>()=>{I()},[I]);let L=(0,G.useCallback)((e,t=`next`,n)=>{let r=e.trim();if(!r){w(null),I();return}ee(r,t,{...x,...n}).then(w).catch(e=>{console.error(`Failed to search terminal:`,e),w({found:!1,resultIndex:0,resultCount:0})})},[I,ee,x]),R=(0,G.useCallback)(e=>{S(t=>({...t,[e]:t[e]!==!0}))},[]),ne=(0,G.useCallback)(()=>{let e=kC(N());e&&(b(e),L(e,`next`,{incremental:!0})),v(!0),window.requestAnimationFrame(()=>{let e=f.current;e?.focus(),e?.select()})},[N,L]),z=(0,G.useCallback)(()=>{v(!1),w(null),I(),CC()||j()},[I,j]),B=(0,G.useCallback)(e=>{let t=EC(e.nativeEvent);if(t){e.preventDefault(),e.stopPropagation(),R(t);return}e.target===f.current&&e.key===`Enter`&&(e.preventDefault(),L(y,e.shiftKey?`previous`:`next`)),e.key===`Escape`&&(e.preventDefault(),z())},[z,L,y,R]);(0,G.useEffect)(()=>{_&&L(y,`next`,{incremental:!0})},[L,_,y]);let re=(0,G.useCallback)(e=>{if(DC(e.target,u.current)){if(wC(e)){e.preventDefault(),e.stopPropagation(),ne();return}if(_&&TC(e)){e.preventDefault(),e.stopPropagation(),L(y,e.shiftKey?`previous`:`next`);return}_&&e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),z())}},[z,ne,L,_,y]);(0,G.useEffect)(()=>{if(!t)return;let e=e=>{re(e)};return window.addEventListener(`keydown`,e,!0),()=>{window.removeEventListener(`keydown`,e,!0)}},[t,re]);let ie=(0,G.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}),(!CC()||o&&o!==`touch`)&&j();return}r(e.id),!(CC()&&(!o||o===`touch`))&&j()},[t,e.id,j,r]),ae=(0,G.useCallback)(()=>{F(),c?.(e.id,P()),!CC()&&j()},[e.id,j,P,c,F]),V=(0,G.useCallback)(()=>{E(null),j()},[j]),oe=!p.following||p.hasUnreadOutput,se=OC(y,C,l);return(0,K.jsxs)(`section`,{className:`code-terminal-pane ${t?`active`:``}`,"data-testid":`code-terminal-pane`,"data-agent-id":e.id,ref:u,onKeyDownCapture:re,onPointerDown:ie,children:[(0,K.jsx)(`div`,{className:`code-terminal-container terminal-container`,"data-testid":`code-terminal-container`,ref:d}),D?(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:l.appServerWaitingForFirstMessage})}):T?(0,K.jsxs)(`div`,{className:`code-terminal-status-card`,"data-testid":`code-terminal-status-card`,title:T,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),children:[(0,K.jsx)(`span`,{children:l.terminalSessionUnavailable}),(0,K.jsx)(`button`,{type:`button`,onClick:V,children:l.retry})]}):null,_?(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(),L(y,`next`)},onKeyDown:B,children:[(0,K.jsx)(`input`,{ref:f,type:`search`,name:`farming-terminal-search`,inputMode:`search`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,value:y,placeholder:l.terminalSearchPlaceholder,"aria-label":l.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=>b(e.target.value)}),(0,K.jsx)(`span`,{className:`code-terminal-search-status ${C&&!C.found?`empty`:``}`,children:se}),(0,K.jsx)(`button`,{type:`button`,className:AC(x.caseSensitive),"aria-label":l.terminalSearchCaseSensitive,"aria-pressed":x.caseSensitive===!0,title:l.terminalSearchCaseSensitive,"data-testid":`code-terminal-search-case-sensitive`,onClick:()=>R(`caseSensitive`),children:(0,K.jsx)(ve,{})}),(0,K.jsx)(`button`,{type:`button`,className:AC(x.wholeWord),"aria-label":l.terminalSearchWholeWord,"aria-pressed":x.wholeWord===!0,title:l.terminalSearchWholeWord,"data-testid":`code-terminal-search-whole-word`,onClick:()=>R(`wholeWord`),children:(0,K.jsx)(he,{})}),(0,K.jsx)(`button`,{type:`button`,className:AC(x.regex),"aria-label":l.terminalSearchRegex,"aria-pressed":x.regex===!0,title:l.terminalSearchRegex,"data-testid":`code-terminal-search-regex`,onClick:()=>R(`regex`),children:(0,K.jsx)(H,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-search-button`,"aria-label":l.terminalSearchPrevious,title:l.terminalSearchPrevious,onClick:()=>L(y,`previous`),children:(0,K.jsx)(Ce,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-search-button`,"aria-label":l.terminalSearchNext,title:l.terminalSearchNext,onClick:()=>L(y,`next`),children:(0,K.jsx)(Ae,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-search-button close`,"aria-label":l.terminalSearchClose,title:l.terminalSearchClose,onClick:z,children:(0,K.jsx)(Se,{})})]}):null,oe?(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)(Ae,{})}):null]})}function MC(e){let t=String(e.status||``).trim().replace(/[_-]/g,``).toLowerCase();return[`running`,`inprogress`,`pending`,`started`,`active`].includes(t)}function NC(e){let t=e[e.length-1];if(String(t?.type||``).toLowerCase()===`thought`)return`thinking`;let n=t&&MC(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`&&MC(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 PC(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(!n||String(n.type||``).toLowerCase()!==`plan`||!MC(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 FC(e,t=10){let n=PC(e);if(!n)return``;let r=[...e].reverse().find(e=>String(e.type||``).toLowerCase()===`plan`&&MC(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 IC({terminalId:e,output:t,interactive:n,onInput:r,onResize:i}){let a=(0,G.useRef)(null),o=(0,G.useRef)(null),s=(0,G.useRef)(``),c=(0,G.useRef)(t),l=(0,G.useRef)(n),u=(0,G.useRef)(r),d=(0,G.useRef)(i),f=(0,G.useRef)(``),[p,m]=(0,G.useState)(``);return c.current=t,l.current=n,u.current=r,d.current=i,(0,G.useEffect)(()=>{let e=a.current;if(!e)return;let t=!1,n=null,r;return Pv({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,G.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 LC=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 LC{};function RC(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 zC(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 BC(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 VC(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 HC(e,t){return BC(e,t,``)}function UC(e,t){return VC(e,t,``)}function WC(e,t){return t.slice(0,GC(e,t))}function GC(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 KC(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 qC(e,t){if(t)return YC(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function JC(e,t){if(t)return YC(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function YC(e,t){if(!t)return[JC(e),qC(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=KC(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}var XC=`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}`,ZC=RegExp(`[${XC}]+|\\s+|[^${XC}]`,`ug`);new class extends LC{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=KC(e,r)}else n=e.match(ZC)||[];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)&&QC(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&QC(n,i,r,null,t.intlSegmenter),e}};function QC(e,t,n,r,i){if(t&&n){let[a,o]=YC(t.value,i),[s,c]=YC(n.value,i);if(e){let r=RC(a,s);e.value=VC(e.value,s,r),t.value=HC(t.value,r),n.value=HC(n.value,r)}if(r){let e=zC(o,c);r.value=BC(r.value,c,e),t.value=UC(t.value,e),n.value=UC(n.value,e)}}else if(n){if(e){let e=JC(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=JC(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=JC(r.value,i),[a,o]=YC(t.value,i),s=RC(n,a);t.value=HC(t.value,s);let c=zC(HC(n,s),o);t.value=UC(t.value,c),r.value=BC(r.value,n,c),e.value=VC(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=JC(r.value,i),n=WC(qC(t.value,i),e);t.value=UC(t.value,n)}else if(e){let n=WC(qC(e.value,i),JC(t.value,i));t.value=HC(t.value,n)}}new class extends LC{tokenize(e){let t=RegExp(`(\\r?\\n)|[${XC}]+|[^\\S\\n\\r]+|[^${XC}]`,`ug`);return e.match(t)||[]}};var $C=new class extends LC{constructor(){super(...arguments),this.tokenize=tw}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
156
156
|
`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
|
|
157
157
|
`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
|
|
@@ -201,6 +201,6 @@ void main() {
|
|
|
201
201
|
|
|
202
202
|
`)).trimEnd()}function zA(e,t){let n=t.filter(e=>!e.path).map(e=>e.messageBlock||``).filter(Boolean);return kA(e.trimEnd(),n.join(`
|
|
203
203
|
|
|
204
|
-
`)).trimEnd()}function BA(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 VA(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 HA(e){let t=await fetch(OA(`/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 UA(e){if(jA(e))return NA(await HA(e));try{return MA(e,await VA(e))}catch{return`Attached file: ${AA(e)}\n\n[Unable to read this file as text]`}}function WA(e){return jA(e)?`Attached image: ${AA(e,`pasted image`)}\n\n[Unable to upload this image]`:`Attached file: ${AA(e)}\n\n[Unable to read this file as text]`}function GA(e){if(!e)return[];let t=Array.from(e.files??[]).filter(jA);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&&jA(e)))}function KA(e,t){return e===`default`?t:`${EA[e]}\n\n${t}`}function qA({agent:e,composerKey:t,draft:n,attachments:r,composerMode:i,turnActive:a,sendMessage:o,updateComposerState:s}){let c=BA(r),l=KA(i,zA(n,r).trim());return!l&&c.length===0||!e||e.runtimeBinding.kind!==`acp`||!t||!a&&!o(e,l,c)?!1:(s(t,e=>({...e,draft:``,attachments:[],mode:`default`,history:dA(e.history,n),...a?{pendingFollowUp:{messages:[...e.pendingFollowUp?.messages||[],_A(l,c)],createdAt:e.pendingFollowUp?.createdAt||Date.now()}}:{}})),r.forEach(IA),!0)}function JA(e,t,n,i=!1){return fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-permission`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:t,optionId:n,cancelled:i})})}function YA(e,t,n,i){return fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-elicitation`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:t,action:n,content:i})})}var XA=`acp:`;function ZA(e){let t=CA(e);return t?`${XA}${t}`:``}function QA(e){return wA(e).map(e=>`${XA}${e}`)}function $A(e){return e.startsWith(XA)}function ej(){return typeof window>`u`?!1:navigator.standalone===!0||window.matchMedia(`(display-mode: standalone)`).matches}function tj(){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 nj(){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 rj(){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 ij({copy:e,title:t,url:n,onClose:r}){let i=ej(),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(!1);(0,G.useEffect)(()=>{let e=e=>{e.key===`Escape`&&r()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[r]),(0,G.useEffect)(()=>{if(!a&&!s)return;let e=window.setTimeout(()=>{o(!1),c(!1)},1800);return()=>window.clearTimeout(e)},[a,s]);let l=(0,G.useCallback)(async()=>{let e=await F(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)(rj,{}),(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)(tj,{})}),(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)(nj,{})})}),(0,K.jsxs)(`span`,{children:[e.mobileInstallAddStep,(0,K.jsx)(`small`,{children:e.mobileInstallOpenStep})]})]})]})]})]})]})})}function aj(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 oj({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,onToggleProjectPinned:O,onRevealProject:k,onCreatePermanentWorktree:A,onMarkProjectRead:j,onArchiveProject:M,onRemoveProject:N,onDeleteWorktree:P,onCloseRenameDialog:F,onRenameDialogTitleChange:ee,onSubmitRenameDialog:I,onCloseKillDialog:te,onSubmitKillDialog:L,onCloseDeleteWorktreeDialog:R,onSubmitDeleteWorktreeDialog:ne,copy:z}){let B=Pk(e),re=Fk(n),ie=Ik(n),ae=!!n?.agents.some(e=>e.unread),V=aj([{type:`item`,id:`pin-agent`,label:e?.pinned?z.unpinAgent:z.pinAgent,hidden:!B.actions.pin,onSelect:()=>v({pinned:!e?.pinned})},{type:`item`,id:`rename-agent`,label:z.renameAgent,hidden:!B.actions.rename,onSelect:y},{type:`item`,id:`archive-agent`,label:z.archiveAgent,hidden:!B.actions.archive,onSelect:()=>v({archived:!0})},{type:`item`,id:`toggle-agent-unread`,label:e?.unread?z.markAsRead:z.markAsUnread,hidden:!B.actions.markUnread,onSelect:()=>v({unread:!e?.unread})},{type:`separator`,id:`agent-copy-separator`},{type:`item`,id:`copy-agent-working-directory`,label:z.copyWorkingDirectory,hidden:!B.actions.copyWorkingDirectory,onSelect:x},{type:`separator`,id:`agent-fork-separator`},{type:`item`,id:`fork-same-worktree`,label:z.forkSameWorktree,hidden:!B.actions.forkSameWorktree,onSelect:()=>S(`same-worktree`)},{type:`item`,id:`fork-new-worktree`,label:z.forkNewWorktree,hidden:!B.actions.forkNewWorktree,onSelect:()=>S(`new-worktree`)},{type:`item`,id:`kill-agent`,label:z.killAgent,danger:!0,hidden:!B.actions.kill,onSelect:C}]),oe=aj([{type:`item`,id:`open-session`,label:z.openSession,onSelect:()=>{t&&w(t.provider,t.id)}},{type:`item`,id:`toggle-session-pinned`,label:t?.pinned?z.unpinChat:z.pinChat,onSelect:T},{type:`item`,id:`archive-session`,label:z.archiveChat,onSelect:E},{type:`item`,id:`copy-session-working-directory`,label:z.copyWorkingDirectory,onSelect:D}]),se=aj([{type:`item`,id:`pin-project`,label:n?.pinned?z.unpinProject:z.pinProject,icon:`pin`,hidden:!n?.workspace,onSelect:O},{type:`item`,id:`reveal-project`,label:z.revealInFinder,icon:`folder`,hidden:!n?.workspace||n.hasMain,onSelect:k},{type:`item`,id:`create-permanent-worktree`,label:z.createPermanentWorktree,icon:`worktree`,hidden:!n?.workspace||n.hasMain,onSelect:A},{type:`separator`,id:`project-primary-separator`},{type:`item`,id:`rename-project`,label:z.renameProject,icon:`rename`,hidden:!n?.workspace,onSelect:b},{type:`item`,id:`mark-project-read`,label:z.markAllAsRead,icon:`check`,disabled:!ae,onSelect:j},{type:`item`,id:`archive-project`,label:z.archiveChats,icon:`archive`,disabled:!re,onSelect:M},{type:`separator`,id:`project-destructive-separator`},{type:`item`,id:`remove-project`,label:z.removeProject,removeIcon:!0,hidden:!n?.workspace||n.hasMain,disabled:!!(n&&(n.agents.length>0||n.agentSessions.length>0||n.hasOpenFile)),onSelect:N},{type:`item`,id:`delete-worktree`,label:z.deleteWorktree,icon:`trash`,danger:!0,hidden:!ie,onSelect:P}]);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)(sj,{entries:V})}),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)(sj,{entries:oe})}),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)(sj,{entries:se})}),o&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-rename-backdrop`,onMouseDown:F,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=>uj(e,d.current),onKeyDown:e=>uj(e,d.current),onSubmit:e=>{e.preventDefault(),I()},children:[(0,K.jsx)(`label`,{id:`code-rename-title`,htmlFor:`code-rename-input`,children:o.kind===`project`?z.renameProject:z.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(),F())}}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:F,children:z.cancel}),(0,K.jsx)(`button`,{type:`submit`,className:`primary`,disabled:!o.title.trim(),children:z.save})]})]})}),s&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-kill-backdrop`,onMouseDown:te,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=>uj(e,p.current),onKeyDown:e=>uj(e,p.current),children:[(0,K.jsx)(`h2`,{id:`code-kill-title`,children:z.killAgentQuestion}),(0,K.jsx)(`p`,{children:z.stopAgentDescription(s.title)}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,ref:m,onClick:te,autoFocus:!0,children:z.cancel}),(0,K.jsx)(`button`,{type:`button`,className:`danger`,onClick:L,children:z.killAgent})]})]})}),c&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-delete-worktree-backdrop`,onMouseDown:R,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=>uj(e,h.current),onKeyDown:e=>uj(e,h.current),children:[(0,K.jsx)(`h2`,{id:`code-delete-worktree-title`,children:z.deleteWorktreeQuestion}),(0,K.jsx)(`p`,{children:z.deleteWorktreeDescription}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,ref:g,onClick:R,autoFocus:!0,children:z.cancel}),(0,K.jsx)(`button`,{type:`button`,className:`danger`,onClick:ne,children:z.forceDelete})]})]})}),l&&(0,K.jsx)(`div`,{className:`code-copy-toast ${l.kind}`,"data-testid":`code-copy-toast`,role:`status`,children:l.message})]})}function sj({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||e.removeIcon)&&(0,K.jsx)(`span`,{className:`code-context-menu-icon`,"aria-hidden":`true`,children:e.removeIcon?(0,K.jsx)(cj,{}):(0,K.jsx)(lj,{kind:e.icon})}),(0,K.jsx)(`span`,{children:e.label})]},e.id))})}function cj(){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.354 3.646a.5.5 0 0 0-.708.708L7.293 8l-3.647 3.646a.5.5 0 0 0 .708.708L8 8.707l3.646 3.647a.5.5 0 0 0 .708-.708L8.707 8l3.647-3.646a.5.5 0 0 0-.708-.708L8 7.293 4.354 3.646Z`})})}function lj({kind:e}){return e===`pin`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M13.5 3C13.303 3 13.109 3.038 12.923 3.114L8.481 4.967L5.659 4.026C5.505 3.976 5.339 4.001 5.209 4.095C5.078 4.189 5.001 4.339 5.001 4.5V7H1.257L0.5 7.5L1.257 8H5V10.5C5 10.661 5.077 10.812 5.208 10.905C5.338 11 5.504 11.023 5.658 10.974L8.48 10.033L12.925 11.887C13.109 11.962 13.302 12 13.499 12C14.326 12 14.999 11.327 14.999 10.5V4.5C14.999 3.673 14.326 3 13.499 3H13.5ZM14 10.5C14 10.843 13.615 11.09 13.308 10.962L8.693 9.038C8.631 9.013 8.566 9 8.501 9C8.447 9 8.395 9.009 8.343 9.025L6.001 9.806V5.193L8.343 5.974C8.457 6.011 8.581 6.007 8.694 5.961L13.306 4.038C13.629 3.902 14.001 4.156 14.001 4.499V10.499L14 10.5Z`})}):e===`folder`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M2 4.5V9.10022L2.92389 7.5C3.45979 6.5718 4.45017 6 5.52196 6L11.9146 6C11.7087 5.4174 11.1531 5 10.5 5H7C6.86739 5 6.74021 4.94732 6.64645 4.85355L4.93934 3.14645C4.84557 3.05268 4.71839 3 4.58579 3H3.5C2.67157 3 2 3.67157 2 4.5ZM7.06895 13.9953C7.04641 13.9984 7.02339 14 7 14H3.5C2.11929 14 1 12.8807 1 11.5V4.5C1 3.11929 2.11929 2 3.5 2H4.58579C4.98361 2 5.36514 2.15804 5.64645 2.43934L7.20711 4H10.5C11.724 4 12.7426 4.87965 12.958 6.04127C14.605 6.34148 15.5443 8.22106 14.6616 9.75L13.0766 12.4953C12.5407 13.4235 11.5503 13.9953 10.4785 13.9953H7.06895ZM5.52196 7C4.80743 7 4.14718 7.3812 3.78991 8L2.20492 10.7453C1.62757 11.7453 2.34926 12.9953 3.50396 12.9953L10.4785 12.9953C11.193 12.9953 11.8533 12.6141 12.2105 11.9953L13.7955 9.25C14.3729 8.25 13.6512 7 12.4965 7L5.52196 7Z`})}):e===`worktree`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M14 5.5C14 4.121 12.879 3 11.5 3C10.121 3 9 4.121 9 5.5C9 6.682 9.826 7.669 10.93 7.928C10.744 8.546 10.177 9 9.5 9H6.5C5.935 9 5.419 9.195 5 9.512V4.949C6.14 4.717 7 3.707 7 2.5C7 1.121 5.879 0 4.5 0C3.121 0 2 1.121 2 2.5C2 3.708 2.86 4.717 4 4.949V11.05C2.86 11.282 2 12.292 2 13.499C2 14.878 3.121 15.999 4.5 15.999C5.879 15.999 7 14.878 7 13.499C7 12.317 6.174 11.33 5.07 11.071C5.256 10.453 5.823 9.999 6.5 9.999H9.5C10.723 9.999 11.74 9.115 11.954 7.953C13.116 7.738 14 6.723 14 5.5ZM3 2.5C3 1.673 3.673 1 4.5 1C5.327 1 6 1.673 6 2.5C6 3.327 5.327 4 4.5 4C3.673 4 3 3.327 3 2.5ZM6 13.5C6 14.327 5.327 15 4.5 15C3.673 15 3 14.327 3 13.5C3 12.673 3.673 12 4.5 12C5.327 12 6 12.673 6 13.5ZM11.5 7C10.673 7 10 6.327 10 5.5C10 4.673 10.673 4 11.5 4C12.327 4 13 4.673 13 5.5C13 6.327 12.327 7 11.5 7Z`})}):e===`check`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M13.6572 3.13573C13.8583 2.9465 14.175 2.95614 14.3643 3.15722C14.5535 3.35831 14.5438 3.675 14.3428 3.86425L5.84277 11.8642C5.64597 12.0494 5.33756 12.0446 5.14648 11.8535L1.64648 8.35351C1.45121 8.15824 1.45121 7.84174 1.64648 7.64647C1.84174 7.45121 2.15825 7.45121 2.35351 7.64647L5.50976 10.8027L13.6572 3.13573Z`})}):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`})}):e===`trash`?(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.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`})}):(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 uj(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 dj=o();function fj({canInstall:e,canFullscreen:t,fullscreenActive:n,copy:i,onClose:a,onInstall:o,onToggleFullscreen:s}){let c=(0,G.useRef)(null);return(0,G.useEffect)(()=>{let e=document.activeElement instanceof HTMLElement?document.activeElement:null;c.current?.focus({preventScroll:!0});let t=e=>{e.key===`Escape`&&a()};return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t),e?.focus({preventScroll:!0})}},[a]),(0,dj.createPortal)((0,K.jsx)(`div`,{className:`code-app-mode-backdrop`,"data-testid":`code-app-mode-dialog`,role:`presentation`,onPointerDown:a,children:(0,K.jsxs)(`section`,{className:`code-app-mode-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-app-mode-title`,onPointerDown:e=>e.stopPropagation(),children:[(0,K.jsx)(`button`,{ref:c,type:`button`,className:`code-app-mode-close`,"aria-label":i.cancel,onClick:a,children:`×`}),(0,K.jsxs)(`header`,{className:`code-app-mode-heading`,children:[(0,K.jsx)(`img`,{src:r(`/farming-2/app-icon-v2-180.png`),alt:``,"aria-hidden":`true`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h2`,{id:`code-app-mode-title`,children:i.appModeTitle}),(0,K.jsx)(`p`,{children:i.appModeDescription})]})]}),(0,K.jsxs)(`section`,{className:`code-app-mode-choice recommended`,children:[(0,K.jsx)(`span`,{className:`code-app-mode-recommended`,children:i.appModeRecommended}),(0,K.jsx)(`h3`,{children:i.appModeInstallTitle}),(0,K.jsx)(`p`,{children:i.appModeInstallDescription}),e&&(0,K.jsx)(`button`,{type:`button`,className:`code-app-mode-install`,"data-testid":`code-app-mode-install`,onClick:o,children:i.appModeInstallAction}),(0,K.jsxs)(`ol`,{className:`code-app-mode-install-steps`,children:[(0,K.jsx)(`li`,{children:i.appModeInstallStepOne}),(0,K.jsx)(`li`,{children:i.appModeInstallStepTwo})]})]}),t&&(0,K.jsxs)(`section`,{className:`code-app-mode-choice temporary`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:i.appModeFullscreenTitle}),(0,K.jsx)(`p`,{children:i.appModeFullscreenDescription})]}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-app-mode-fullscreen`,onClick:s,children:n?i.exitFocusMode:i.enterFocusMode})]})]})}),document.body)}var pj=`https://github.com/zhuwenzhuang/farming`;function mj({copy:e,version:t,onClose:n}){let i=(0,G.useRef)(null);return(0,G.useEffect)(()=>{let e=document.activeElement instanceof HTMLElement?document.activeElement:null;i.current?.focus({preventScroll:!0});let t=e=>{e.key===`Escape`&&n()};return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t),e?.focus({preventScroll:!0})}},[n]),(0,dj.createPortal)((0,K.jsx)(`div`,{className:`code-brand-backdrop`,"data-testid":`code-brand-dialog`,role:`presentation`,onPointerDown:n,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:n,children:`×`}),(0,K.jsx)(`img`,{className:`code-brand-logo`,src:r(`/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:pj,target:`_blank`,rel:`noreferrer`,children:e.brandGithub})]})}),document.body)}var hj=8,gj=26,_j=11,vj=10;function yj(){return typeof window>`u`?{width:220+hj*2,height:vj+hj*2}:{width:window.innerWidth,height:window.innerHeight}}function bj(e,t=0){return vj+e*gj+t*_j}function xj(e,t,n,r=yj(),i=220){let a=Math.max(hj,r.width-i-hj),o=Math.max(hj,r.height-n-hj);return{x:Math.max(hj,Math.min(e,a)),y:Math.max(hj,Math.min(t,o))}}function Sj(e,t,n=yj(),r=220){let i=e.right+hj,a=e.left-r-hj,o=i+r<=n.width-hj?i:a>=hj?a:xj(i,e.top,t,n,r).x;return{x:o,y:xj(o,e.top,t,n,r).y}}function Cj(e,t,n=yj(),r=220){let i=Math.max(hj,n.width-r-hj),a=Math.max(hj,Math.min(e.right-r,i)),o=e.bottom+6,s=Math.max(hj,n.height-t-hj),c=e.top-t-6;return{x:a,y:o<=s?o:Math.max(hj,Math.min(c,s))}}function wj(e){let t=Lk(e);return bj(t.itemCount,t.separatorCount)}var Tj=140,Ej=264,Dj=340,Oj=4,kj=null;function Aj(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 jj(){return kj||=s(()=>import(`./qrcode-DV-_rjU8.js`).then(e=>Aj(e)),[]),kj}function Mj(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 Nj(e,t){return!!(e&&e.expiresAt>t+1e3)}function Pj(e){return e.split(`-`).map(e=>e.trim()).filter(Boolean)}async function Fj(e){e?.code&&await fetch(r(`/api/share/qr-ticket/${encodeURIComponent(e.code)}`),{method:`DELETE`}).catch(()=>{})}function Ij(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 Lj(e,t,n,r){let i=Math.floor((n-r)/2),a=i+r;return e>=i&&e<a&&t>=i&&t<a}function Rj(e,t){return(e+t)%11==0?`#6d8a63`:(e*3+t)%17==0?`#9b7a35`:`#263327`}function zj(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 Bj({value:e,badgeUrl:t,qrCodeFactory:n}){let r=(0,G.useId)().replace(/:/g,``),i=(0,G.useMemo)(()=>{let t=n(0,`H`);return t.addData(e),t.make(),t},[n,e]),a=i.getModuleCount(),o=a+Oj*2,s=Math.max(7,Math.min(11,Math.floor(a*.26)|1)),c=s+1.4,l=Oj+(a-c)/2,u=Oj+(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)&&(Ij(e,t,a)||Lj(e,t,a,s)||f.push((0,K.jsx)(`rect`,{x:Oj+t+.14,y:Oj+e+.14,width:`0.72`,height:`0.72`,rx:`0.24`,fill:Rj(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,zj(Oj,Oj,`top-left`),zj(Oj+a-7,Oj,`top-right`),zj(Oj,Oj+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 Vj(){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 Hj({copy:e,sidebarCollapsed:t,shareTarget:n}){let[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)(!1),[c,l]=(0,G.useState)(null),[u,d]=(0,G.useState)(!1),[f,p]=(0,G.useState)(``),[m,h]=(0,G.useState)(!1),[g,_]=(0,G.useState)(()=>Date.now()),[v,y]=(0,G.useState)({x:0,y:0}),b=(0,G.useRef)(null),x=(0,G.useRef)(null),S=(0,G.useRef)(null),C=(0,G.useRef)(null),w=(0,G.useRef)(null),D=(0,G.useRef)(0),O=(0,G.useRef)(null),k=(0,G.useRef)(null),[A,j]=(0,G.useState)(!0),[M,N]=(0,G.useState)(null),P=r(`/farming-2/app-icon-v2-180.png`),ee=E(n);(0,G.useEffect)(()=>{O.current=c},[c]);let I=(0,G.useCallback)(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null)},[]),te=(0,G.useCallback)(()=>{let e=x.current?.getBoundingClientRect();if(!e)return;let t=e.right+8,n=e.left-Ej-8;y({x:t+Ej+10<=window.innerWidth?t:Math.max(8,n),y:Math.max(8,Math.min(e.top-4,window.innerHeight-Dj-8))})},[]),L=(0,G.useCallback)(()=>{t||jj().then(e=>N(()=>e)).catch(()=>p(e.shareLinkFailed))},[e.shareLinkFailed,t]),R=(0,G.useCallback)(async(t=!1)=>{let i=O.current;if(!t&&Nj(i,Date.now()))return i;let a=D.current+1;D.current=a,d(!0),p(``);try{let t=T(n),i=await fetch(r(`/api/share/qr-ticket`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t?{target:t}:{})}),o=await i.json();if(!i.ok||!(`shortUrl`in o))throw Error(`error`in o&&o.error?o.error:e.shareLinkFailed);return a===D.current?(l(o),_(Date.now()),h(!1),o):(await Fj(o),null)}catch(t){return a===D.current&&p(t instanceof Error?t.message:e.shareLinkFailed),null}finally{a===D.current&&d(!1)}},[e.shareLinkFailed,n,ee]),ne=(0,G.useCallback)(()=>{I(),D.current+=1,a(!1),s(!1),p(``),h(!1),d(!1);let e=O.current;O.current=null,l(null),Fj(e)},[I]),z=(0,G.useCallback)((e,t=!1)=>{I(),te(),a(!0),s(e),L(),R(t)},[I,R,L,te]),B=(0,G.useCallback)(()=>{!i||o||(I(),w.current=window.setTimeout(()=>{w.current=null,ne()},Tj))},[I,ne,i,o]),re=(0,G.useCallback)(()=>{if(i&&o){ne();return}z(!0,!0)},[ne,i,z,o]),ie=(0,G.useCallback)(async()=>{let t=Nj(O.current,Date.now())?O.current:await R(!0);if(t){if(!await F(t.longUrl)){p(e.copyFailed);return}h(!0),k.current!==null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{h(!1),k.current=null},1800)}},[e.copyFailed,R]);(0,G.useLayoutEffect)(()=>{if(i)return te(),window.addEventListener(`resize`,te),()=>window.removeEventListener(`resize`,te)},[i,te]),(0,G.useEffect)(()=>{if(!i)return;let e=window.setInterval(()=>_(Date.now()),1e3);return()=>window.clearInterval(e)},[i]),(0,G.useEffect)(()=>{let e=O.current;e&&(O.current=null,l(null),h(!1),Fj(e))},[ee]),(0,G.useLayoutEffect)(()=>{if(!i)return;let e=()=>{let e=S.current,t=C.current;!e||!t||j(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,G.useEffect)(()=>{if(!i)return;let e=e=>{let t=e.target;t instanceof Node&&b.current?.contains(t)||ne()},t=e=>{e.key===`Escape`&&ne()};return document.addEventListener(`pointerdown`,e,!0),document.addEventListener(`keydown`,t,!0),()=>{document.removeEventListener(`pointerdown`,e,!0),document.removeEventListener(`keydown`,t,!0)}},[ne,i]),(0,G.useEffect)(()=>()=>{I(),k.current!==null&&window.clearTimeout(k.current),D.current+=1,Fj(O.current)},[I]);let ae=!!(c&&c.expiresAt<=g),V=c?Mj(c.expiresAt-g):``,oe=c?.tokenLabel||c?.shortPath||e.copyFullShareLink,se=Pj(oe),ce=A||se.length<=1?[oe]:se;return(0,K.jsxs)(`div`,{ref:b,className:`code-share-root`,onMouseEnter:L,onMouseLeave:B,onFocus:()=>{I(),L()},onBlur:e=>{!e.currentTarget.contains(e.relatedTarget)&&!o&&ne()},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)(Vj,{})}),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:()=>{I()},onMouseLeave:B,onKeyDown:e=>{e.key===`Escape`&&(ne(),x.current?.focus())},children:[(0,K.jsxs)(`div`,{className:`code-share-qr-frame`,"data-expired":ae?`true`:`false`,children:[(0,K.jsx)(`div`,{className:`code-share-qr-canvas`,children:c&&!u&&M?(0,K.jsx)(Bj,{value:c.shortUrl,badgeUrl:P,qrCodeFactory:M}):(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:ae?e.shareLinkExpired:V}),ae&&(0,K.jsx)(`button`,{type:`button`,className:`code-share-refresh`,onClick:()=>void R(!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 ie(),children:[(0,K.jsxs)(`span`,{ref:S,className:`code-share-token ${A?`single-line`:``}`,"aria-label":oe,children:[(0,K.jsx)(`span`,{ref:C,className:`code-share-token-measure`,"aria-hidden":`true`,children:oe}),ce.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 Uj(e,t){return e&&t.some(t=>!t.isMain&&t.id===e)?e:t.find(e=>!e.isMain)?.id??null}function Wj(e){return e&&(e.projectWorkspace||e.cwd)||``}function Gj(e,t,n={},r=[],i=e,a=[],o=[]){let s=pD(e,t),c=new Map(s.map(e=>[e.workspace,e]));r.forEach(e=>{let t=e.sourceAgentId?i.find(t=>t.id===e.sourceAgentId):i.find(t=>t.id===e.agentId),n=e.workspaceRoot||(t?ZE(t):``);if(!n||n===`/`)return;let r=c.get(n);if(r){r.hasOpenFile=!0,!r.gitWorktree&&t?.gitWorktree?.workspace&&(r.gitWorktree=t.gitWorktree);return}let a={id:n,name:QE(n),workspace:n,agents:[],agentSessions:[],hasMain:!1,hasProjectAgent:!1,hasAgentSession:!1,hasOpenFile:!0,gitWorktree:t?.gitWorktree??null};s.push(a),c.set(n,a)}),a.forEach(e=>{if(!e||e===`/`||c.get(e))return;let t={id:e,name:QE(e),workspace:e,agents:[],agentSessions:[],hasMain:!1,hasProjectAgent:!1,hasAgentSession:!1,gitWorktree:null};s.push(t),c.set(e,t)});let l=new Map(o.map((e,t)=>[e,t]));return s.map((e,t)=>{let r=e.workspace?n[e.workspace]?.trim():``,i=r&&!e.hasMain?{...e,name:r}:e,a=l.get(e.workspace);return{project:{...i,pinned:a!==void 0},pinIndex:a,sourceIndex:t}}).sort((e,t)=>e.pinIndex!==void 0&&t.pinIndex!==void 0?e.pinIndex-t.pinIndex:e.pinIndex===void 0?t.pinIndex===void 0?e.sourceIndex-t.sourceIndex:1:-1).map(e=>e.project)}function Kj(e,t,n,r=new Set,i=new Set){return t?rk(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)||C(e).toLowerCase().includes(t)),o=n?e.agentSessions:e.agentSessions.filter(e=>r.has(aD(e))||e.title.toLowerCase().includes(t));return a.length>0||o.length>0||e.workspace&&n?{...e,agents:a,agentSessions:o}:null}).filter(e=>!!e),n,!0):e}function qj(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 Jj=5,Yj=5,Xj=`__project_agent_drop_end__`;function Zj(){return typeof window>`u`?!1:navigator.standalone===!0||window.matchMedia(`(display-mode: standalone)`).matches}function Qj(e){let t=e?.trim().toLowerCase()||``;if(t===`claude-code`)return`claude`;if([`codex`,`claude`,`opencode`,`qoder`,`bash`,`zsh`].includes(t))return t}function $j(e){return Qj(e.providerSessionProvider)||Qj(e.command.trim().split(/\s+/).find(e=>e!==`env`&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(e))?.split(`/`).pop())}function eM(){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 tM(){return(0,K.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,K.jsx)(`circle`,{cx:`4`,cy:`3`,r:`1.5`}),(0,K.jsx)(`circle`,{cx:`4`,cy:`13`,r:`1.5`}),(0,K.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,K.jsx)(`path`,{d:`M4 4.5v7M5.5 8h2.25A4.25 4.25 0 0 0 12 3.75`})]})}function nM(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 rM=(0,G.lazy)(()=>s(()=>import(`./ProjectFilesSection-DE7Nb9Jk.js`).then(e=>({default:e.ProjectFilesSection})),__vite__mapDeps([18,1,5,6,19,20,8,15,16])));function iM({sidebarCollapsed:e,activeView:t,searchOpen:n,displayedProjects:i,collapsedProjectIds:a,normalizedSearch:o,hasProjectListItems:s,hasDisplayedProjectListItems:c,activeTerminalId:l,selectedSearchAgentId:u,selectedSearchSessionHandle:f,claimedAgentSessionKeyByAgentId:p,agentShortcutKeys:m,keyboardShortcutsEnabled:h,now:g,mainAgent:_,usageSummary:v,shareTarget:y,agentLaunchOptions:b,agentCreationWorkspace:x,openWorkspaceFile:S,openWorkspaceFiles:C,fileRevealRequest:w,fileSearchFocusRequest:T,projectListRef:E,canLoadMoreAgentSessions:D,onLoadMoreAgentSessions:O,onNewAgent:k,onStartAgent:A,onToggleSidebar:j,onOpenSearch:M,onOpenWorkspaceView:N,onOpenMainAgent:P,onRestartMainAgent:F,onProjectListKeyDown:ee,onToggleProject:I,onToggleProjectSessions:te,onMountProject:L,onOpenProjectContextMenu:R,onOpenProjectKeyboardMenu:ne,onOpenAgent:z,onUpdateAgentFlags:B,onReorderAgent:re,onOpenAgentContextMenu:ie,onOpenAgentKeyboardMenu:ae,onResumeAgentSession:V,onOpenAgentSessionContextMenu:oe,onOpenAgentSessionKeyboardMenu:se,onOpenProjectFile:ce,onSelectOpenWorkspaceFile:le,onCloseOpenWorkspaceFile:ue,onMoveWorkspaceEntries:de,onDeleteWorkspaceEntries:fe,onRefreshProjectOpenFiles:pe,onOpenOptionsMenu:me,copy:he}){let[H,_e]=(0,G.useState)(null),ve=(0,G.useRef)(null),ye=(0,G.useRef)(!1),xe=(0,G.useRef)(new Map),[Se,Ce]=(0,G.useState)(!0),[Te,Ee]=(0,G.useState)(!1),[De,Oe]=(0,G.useState)(!1),U=(0,G.useCallback)(()=>Oe(!1),[]),[ke,Ae]=(0,G.useState)(!1),[je,Ne]=(0,G.useState)(!1),[Pe,Fe]=(0,G.useState)(Zj),[Ie,Re]=(0,G.useState)(!1),[ze,Ve]=(0,G.useState)(null),[He,Ue]=(0,G.useState)(!1),We=(0,G.useCallback)(e=>{D&&e.scrollHeight-e.scrollTop-e.clientHeight<=240&&O()},[D,O]),Ge=(0,G.useCallback)(()=>{ve.current!==null&&(window.clearTimeout(ve.current),ve.current=null)},[]),Ke=(0,G.useCallback)(()=>{Ge(),_e(null)},[Ge]),qe=(0,G.useCallback)(()=>{ye.current=!1,Ke()},[Ke]),Je=(0,G.useCallback)((e,t,n=!1)=>{Ge();let i=e.currentTarget,a=ye.current?0:n?450:1500;ve.current=window.setTimeout(()=>{if(ve.current=null,!i.matches(`:hover`))return;let e=i.getBoundingClientRect(),n=e.right+10,a=Math.min(320,window.innerWidth-n-12);if(a<200)return;let o=Math.max(8,Math.min(e.top-4,window.innerHeight-152)),s=t.workspaceRootId?xe.current.get(t.workspaceRootId):void 0,c=s&&s.expiresAt>Date.now()?s.branch:``;ye.current=!0,_e({...t,x:n,y:o,width:a,branch:c}),!(!t.workspaceRootId||c)&&fetch(r(`/api/files/branch?rootId=${encodeURIComponent(t.workspaceRootId)}`)).then(e=>e.ok?e.json():null).then(e=>{let n=typeof e?.branch==`string`?e.branch.trim():``;xe.current.set(t.workspaceRootId,{branch:n,expiresAt:Date.now()+3e4}),_e(e=>e?.key===t.key?{...e,branch:n}:e)}).catch(()=>{xe.current.set(t.workspaceRootId,{branch:``,expiresAt:Date.now()+3e4})})},a)},[Ge]);(0,G.useEffect)(()=>()=>Ge(),[Ge]),(0,G.useEffect)(()=>{Ne(!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen));let e=()=>{Ae(!!document.fullscreenElement)};return document.addEventListener(`fullscreenchange`,e),e(),()=>{document.removeEventListener(`fullscreenchange`,e)}},[]),(0,G.useEffect)(()=>{let e=window.matchMedia(`(display-mode: standalone)`),t=()=>{let e=Zj();Fe(e),e&&Re(!1)},n=e=>{e.preventDefault(),Ve(e)};return e.addEventListener(`change`,t),window.addEventListener(`beforeinstallprompt`,n),t(),()=>{e.removeEventListener(`change`,t),window.removeEventListener(`beforeinstallprompt`,n)}},[]);let Ye=(0,G.useCallback)(()=>{if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}document.documentElement.requestFullscreen({navigationUI:`hide`}).catch(()=>{})},[]),Xe=(0,G.useCallback)(()=>{let e=ze;e&&e.prompt().then(()=>e.userChoice).then(e=>{Ve(null),e.outcome===`accepted`&&Re(!1)}).catch(()=>Ve(null))},[ze]),Ze=(0,G.useCallback)(()=>{Re(!1),Ye()},[Ye]),Qe=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`?dD(t.session)-dD(e.session):0:e.kind===`agent`?-1:1),$e=i.filter(e=>e.agents.some(e=>!e.pinned||!e.isMain)||e.agentSessions.some(e=>!e.pinned)||(e.hiddenAgentSessionCount??0)>0||e.hasOpenFile||!!e.workspace),et=i.flatMap(e=>[...e.agents.filter(e=>!e.isMain).map(t=>({agent:t,projectName:e.name}))]),tt=C.filter(e=>Le(e.agentId)),nt=S&&Le(S.agentId)?S:null,rt=w?.agentId===Be,it=tt.length>0||rt;(0,G.useEffect)(()=>{it||Ue(!1)},[it]),(0,G.useEffect)(()=>{rt&&Ue(!1)},[rt]);let at=nM(`2.2.12`),ot=at?`v${at}`:``,st=e;return(0,K.jsxs)(`aside`,{className:`code-sidebar ${e?`collapsed`:``}`,"data-testid":`code-sidebar`,onMouseLeave:qe,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=>k(x,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:he.newAgent}),h&&(0,K.jsx)(`kbd`,{children:`N`})]}),(0,K.jsx)(Hj,{copy:he,sidebarCollapsed:e,shareTarget:y}),!Pe&&!e&&(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-focus-toggle ${ke?`active`:``}`,"data-testid":`code-sidebar-focus-toggle`,"aria-label":he.appModeOpen,title:he.appModeOpen,"aria-haspopup":`dialog`,"aria-expanded":Ie,onClick:()=>Re(!0),children:(0,K.jsx)(`span`,{className:`code-sidebar-focus-icon`,children:(0,K.jsx)(eM,{})})}),!e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-search-toggle ${t===`search`||n?`active`:``}`,"data-testid":`code-nav-search`,"aria-label":he.search,title:he.search,"aria-pressed":t===`search`||n,onClick:M,children:(0,K.jsx)(`span`,{className:`code-sidebar-search-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Me,{})})}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-history-toggle ${t===`history`?`active`:``}`,"data-testid":`code-nav-history`,"aria-label":he.history,title:he.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)(xN,{})})})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-toggle`,"data-testid":`code-sidebar-toggle`,"aria-label":e?he.expandSidebar:he.collapseSidebar,title:e?he.expandSidebar:he.collapseSidebar,onClick:j,children:(0,K.jsx)(`span`,{className:`code-sidebar-toggle-icon ${e?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:e?(0,K.jsx)(W,{}):(0,K.jsx)(we,{})})})]})}),e&&et.length>0&&(0,K.jsx)(eN,{items:et,activeTerminalId:l,now:g,onOpenAgent:z,onShowPreview:Je,onHidePreview:Ke,copy:he}),(0,K.jsxs)(`div`,{className:`code-project-list`,"data-testid":`code-project-list`,ref:E,tabIndex:0,onKeyDown:ee,onScroll:e=>We(e.currentTarget),"aria-label":he.projectsAndAgents,children:[!s&&(0,K.jsx)(`div`,{className:`code-empty-project`,children:he.noAgentsYet}),s&&!c&&(0,K.jsx)(`div`,{className:`code-empty-project`,"data-testid":`code-empty-search`,children:he.noMatchingProjectsOrAgents}),Qe.length>0&&(0,K.jsx)(iN,{items:Qe,collapsed:Te,compressed:st,activeTerminalId:l,selectedSearchAgentId:u,selectedSearchSessionHandle:f,claimedAgentSessionKeyByAgentId:p,agentShortcutKeys:m,keyboardShortcutsEnabled:h,now:g,onOpenAgent:z,onUpdateAgentFlags:B,onReorderAgent:re,onOpenAgentContextMenu:ie,onOpenAgentKeyboardMenu:ae,onResumeAgentSession:V,onOpenAgentSessionContextMenu:oe,onOpenAgentSessionKeyboardMenu:se,onShowAgentPreview:Je,onHideAgentPreview:Ke,onToggleCollapsed:()=>Ee(e=>!e),copy:he}),it&&(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":!He,onClick:()=>Ue(e=>!e),children:[(0,K.jsx)(`span`,{className:`code-folder-icon ${He?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:He?(0,K.jsx)(W,{}):(0,K.jsx)(be,{})}),(0,K.jsx)(`span`,{children:`/`})]})}),!He&&(0,K.jsx)(`div`,{className:`code-project-expanded`,children:(0,K.jsx)(G.Suspense,{fallback:null,children:(0,K.jsx)(rM,{projectId:`__farming_global_files_project__`,projectWorkspace:`/`,agentId:`wroot_global`,agentLaunchOptions:[],activeFilePath:nt?.file.path,openFiles:tt.map(e=>({agentId:e.agentId,workspaceRoot:e.workspaceRoot,key:d(e),path:e.file.path,dirty:e.dirty,externalChanged:e.externalChanged})),revealRequest:w?.agentId===`wroot_global`?w:void 0,focusSearchRequest:T?.agentId===`wroot_global`?T:void 0,onOpenFile:ce,onSelectOpenFile:le,onCloseOpenFile:ue,onMoveEntries:de,onDeleteEntries:fe,onRefreshOpenFiles:pe,readOnly:!0,copy:he})})})]}),$e.map(e=>(0,K.jsx)(cN,{project:e,collapsed:a.has(e.id)&&!o,forceAgentsExpanded:!!o,compactAgents:st,activeTerminalId:l,selectedSearchAgentId:u,selectedSearchSessionHandle:f,claimedAgentSessionKeyByAgentId:p,agentShortcutKeys:m,keyboardShortcutsEnabled:h,now:g,openWorkspaceFile:S,openWorkspaceFiles:C,agentLaunchOptions:b,fileRevealRequest:w,fileSearchFocusRequest:T,onToggleProject:I,onToggleProjectSessions:te,onMountProject:L,onNewAgent:k,onStartAgent:A,onOpenProjectContextMenu:R,onOpenProjectKeyboardMenu:ne,onOpenAgent:z,onUpdateAgentFlags:B,onReorderAgent:re,onOpenAgentContextMenu:ie,onOpenAgentKeyboardMenu:ae,onResumeAgentSession:V,onOpenAgentSessionContextMenu:oe,onOpenAgentSessionKeyboardMenu:se,onShowAgentPreview:Je,onHideAgentPreview:Ke,onOpenProjectFile:ce,onSelectOpenWorkspaceFile:le,onCloseOpenWorkspaceFile:ue,onMoveWorkspaceEntries:de,onDeleteWorkspaceEntries:fe,onRefreshProjectOpenFiles:pe,copy:he},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:()=>Oe(!0),children:[(0,K.jsx)(`img`,{className:`code-product-logo`,src:r(`/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`})]}),ot&&(0,K.jsx)(`span`,{className:`code-product-mark-badge`,children:ot})]})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-options`,"data-testid":`code-sidebar-options`,"aria-label":he.openSettings,title:he.openSettings,onClick:me,children:(0,K.jsx)(ge,{})})]}),!e&&(0,K.jsx)(AM,{collapsed:Se,mainAgent:_,now:g,usageSummary:v,onToggleCollapsed:()=>Ce(e=>!e),onOpenMainAgent:P,onRestartMainAgent:F})]}),H&&(0,K.jsx)(gN,{preview:H,now:g}),De&&(0,K.jsx)(mj,{copy:he,version:ot,onClose:U}),Ie&&(0,K.jsx)(fj,{canInstall:!!ze,canFullscreen:je,fullscreenActive:ke,copy:he,onClose:()=>Re(!1),onInstall:Xe,onToggleFullscreen:Ze})]})}function aM(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 oM(e){let t=Number(e);return Number.isFinite(t)?`${Math.round(t)}%`:`--`}function sM(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 cM(e){let t=e.forecast?.remainingTokens,n=t==null?null:Number(t);return typeof n==`number`&&Number.isFinite(n)&&n>=0?`${fM(Math.round(n))} tok left`:sM(e.usedPercent)}function lM(e){return cM(e)}function uM(e,t){let n=[e],r=oM(t.usedPercent),i=cM(t);return r!==`--`&&n.push(`${r} used`),i!==`-- left`&&n.push(i),n.filter(Boolean).join(` / `)}function dM(e,t){let n=Number(e);if(!Number.isFinite(n)||n<=0)return null;let r=Math.max(0,Math.round((n-t)/6e4));return r===0?`reset now`:r>=1440?`reset ${Math.floor(r/1440)}d ${Math.floor(r%1440/60)}h`:r>=60?`reset ${Math.floor(r/60)}h ${r%60}m`:`reset ${r}m`}function fM(e){if(e>=1e9){let t=e/1e9;return`${t>=10?Math.round(t):Math.round(t*10)/10}B`}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 pM(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?`~`:``}${fM(r)} tok/min`}function mM(e){let t=e.auth?.status||``;return e.auth?.available?/logged in/i.test(t)?`logged in`:t||`available`:`offline`}function hM(e){if(e.tokenUsage.available===!1)return!1;let t=Number(e.tokenUsage.eventCount),n=Number(e.tokenUsage.totalTokens),r=Number.isFinite(t)&&t>0||Number.isFinite(n)&&n>0;return e.auth.available||r}function gM(e){return e?.providers.filter(hM)??[]}function _M(e){let t=gM(e);return t.length?t.reduce((e,t)=>{let n=Number(t.tokenUsage.tokensPerMinute);return e+(Number.isFinite(n)?n:0)},0):null}function vM(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 yM(e){let t=Number(e.windowMinutes);return Number.isFinite(t)&&t>=10020?0:Number.isFinite(t)&&t>=285&&t<=315?1:2}function bM(e){return[e.quota.primary,e.quota.secondary].filter(e=>!!e).map(e=>({label:aM(e.windowMinutes),limit:e,remaining:vM(e),exhaustedAt:typeof e.forecast?.projectedExhaustedAt==`number`&&Number.isFinite(e.forecast.projectedExhaustedAt)?e.forecast.projectedExhaustedAt:null})).filter(e=>e.remaining!==null).sort((e,t)=>yM(e.limit)-yM(t.limit))}function xM(e){let t=Number(e.tokenUsage.tokensPerMinute);return Number.isFinite(t)&&t>0}function SM(e){let t=gM(e);return t.length?t.filter(e=>xM(e)&&e.quota.available).map(e=>{let t=bM(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 CM(e,t){let n=SM(e);if(!n)return null;let r=[n.provider.providerName];return n.limits.forEach(e=>{r.push(`${e.label} ${Math.round(e.remaining??0)}%`);let n=dM(e.limit.resetsAt,t);n&&r.push(n)}),r.join(` · `)}function wM(e,t){let n=[],r=_M(e);return r!==null&&n.push(pM(r)),t&&n.push(`CPU ${t.cpu}% / MEM ${t.memory.percentage}%`),n.join(` · `)||`5m`}function TM(e,t,n){return CM(e,n)||wM(e,t)}function EM(e){return e.status===`pending`?`starting`:e.status===`dead`?`offline`:e.status}function DM(e,t){return e??t?.systemStats??null}function OM({usageSummary:e,now:t}){let n=TM(e,DM(ut(),e),t);return(0,K.jsx)(`span`,{className:`code-usage-summary`,"data-testid":`code-usage-summary`,title:n,children:n})}function kM({usageSummary:e}){let t=DM(ut(),e);return t?(0,K.jsxs)(`div`,{className:`code-usage-row`,children:[(0,K.jsx)(`span`,{children:`System`}),(0,K.jsxs)(`strong`,{children:[`CPU `,t.cpu,`% / MEM `,t.memory.percentage,`%`]})]}):null}function AM(e){let t=dt();return!e.usageSummary&&!e.mainAgent&&!t?null:(0,K.jsx)(QM,{...e})}function jM(e){return new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}function MM(e){return`${String(new Date(e).getHours()).padStart(2,`0`)}:00`}function NM(e){return Math.round(e).toLocaleString(`en-US`)}function PM(e){let t=e.map(e=>Math.max(0,Number(e)||0)).filter(e=>e>0).sort((e,t)=>e-t);if(!t.length)return[];let n=t[0],r=t[t.length-1];return n===r?[.2,.4,.6,.8].map(e=>r*e):[.2,.4,.6,.8].map(e=>{let n=(t.length-1)*e,r=Math.floor(n),i=Math.ceil(n),a=t[r];return a+(t[i]-a)*(n-r)})}function FM(e,t){let n=Math.max(0,Number(e)||0);return n<=0?0:Math.max(1,Math.min(5,1+t.filter(e=>n>e).length))}function IM(e){let t=e.timeline,n=Array.isArray(t?.points)?t.points:[];return n.length>0&&n.every((e,t)=>Number.isFinite(Number(e.startedAt))&&Number.isFinite(Number(e.endedAt))&&Number(e.endedAt)>Number(e.startedAt)&&Number.isFinite(Number(e.totalTokens))&&Number(e.totalTokens)>=0&&(t===0||Number(e.startedAt)>=Number(n[t-1].startedAt)))?n:null}function LM(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),a=new Date(n,r-1,i,12,0,0,0);return a.getFullYear()!==n||a.getMonth()!==r-1||a.getDate()!==i?null:a}function RM(e){let t=Array.isArray(e.daily?.points)?e.daily.points:[];return t.length>0&&t.every((e,n)=>!!LM(e.date)&&Number.isFinite(Number(e.totalTokens))&&Number(e.totalTokens)>=0&&(n===0||e.date>t[n-1].date))?t.slice(-364):null}function zM({usageSummary:e,points:t,onInspect:n}){let r=e.timeline,i=t.reduce((e,t)=>e+Number(t.totalTokens),0),a=aM(Number(r.windowMs)/6e4).toLowerCase(),o=PM(t.map(e=>e.totalTokens)),s=[0,.25,.5,.75,1].map(e=>r.startAt+(r.endAt-r.startAt)*e);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`code-usage-heatmap`,"data-testid":`code-usage-heatmap`,role:`img`,"aria-label":`Token activity over the last ${a}, ${fM(i)} tokens`,title:`Local token activity · last ${a}`,children:t.map((e,t)=>{let r=Number(e.totalTokens),i=`${jM(e.startedAt)}–${jM(e.endedAt)}`,a=`${i} · ${NM(r)} tokens`;return(0,K.jsx)(`span`,{className:`code-usage-heatmap-cell`,"data-level":FM(r,o),"data-start":e.startedAt,title:a,"aria-label":a,onMouseEnter:()=>n({label:i,tokens:r})},`${e.startedAt}-${t}`)})}),(0,K.jsx)(`div`,{className:`code-usage-time-axis`,"data-testid":`code-usage-time-axis`,"aria-hidden":`true`,children:s.map((e,t)=>(0,K.jsx)(`span`,{children:MM(e)},`${e}-${t}`))})]})}function BM({points:e,onInspect:t,inspection:n=null,showDayHighlight:r=!1}){let i=(LM(e[0].date).getDay()+6)%7,a=Math.max(1,Math.ceil((i+e.length)/7)),o=a*7-i-e.length,s=PM(e.map(e=>e.totalTokens)),c=e.filter(e=>e.totalTokens>0).length,l=Math.max(0,e.length-7),u=e.slice(l).reduce((e,t)=>e+t.totalTokens,0),d=e.reduce((e,t)=>!e||t.totalTokens>e.totalTokens?t:e,null),f=d&&d.totalTokens>0?d:null,p=n?e.find(e=>e.date===n.label)??null:null,m=e[e.length-1]??null,h=p??m,g=!!(h&&h.date===f?.date);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`code-usage-activity-heading`,children:[(0,K.jsx)(`span`,{children:`52w · daily`}),r&&h?(0,K.jsxs)(`div`,{className:`code-usage-detail-day-highlight`,"data-state":p?`selected`:`today`,"data-testid":`code-usage-detail-day-highlight`,children:[(0,K.jsxs)(`span`,{children:[p&&g?`Top · `:``,UM(h.date)]}),(0,K.jsx)(`strong`,{children:fM(h.totalTokens)}),(0,K.jsx)(`small`,{children:`tokens`})]}):(0,K.jsxs)(`span`,{children:[`7d `,fM(u)]})]}),(0,K.jsxs)(`div`,{className:`code-usage-daily-heatmap`,"data-testid":`code-usage-daily-heatmap`,role:`img`,"aria-label":`Daily token activity over 52 weeks, ${c} active days`,style:{gridTemplateColumns:`repeat(${a}, minmax(2px, 1fr))`},children:[Array.from({length:i},(e,t)=>(0,K.jsx)(`span`,{className:`code-usage-daily-spacer`,"aria-hidden":`true`},`leading-${t}`)),e.map((e,n)=>{let i=Number(e.totalTokens),a=e.date===f?.date,o=i>1e9,c=a?`Token king`:o?`Over 1B tokens`:``,u=`${e.date} · ${NM(i)} tokens${c?` · ${c}`:``}`,d=e.date===p?.date,m=()=>t({label:e.date,tokens:i});return(0,K.jsx)(`span`,{className:`code-usage-heatmap-cell code-usage-daily-heatmap-cell`,"data-date":e.date,"data-level":FM(i,s),"data-peak":a?`true`:void 0,"data-billion":o?`true`:void 0,"data-shape":r?a?`crown`:o?`flame`:void 0:void 0,"data-recent":n>=l?`true`:void 0,"data-selected":d?`true`:void 0,title:u,"aria-label":u,role:r?`button`:void 0,tabIndex:r?0:void 0,onClick:r?m:void 0,onFocus:r?m:void 0,onKeyDown:r?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),m())}:void 0,onMouseEnter:r?void 0:m,onPointerMove:r?m:void 0},e.date)}),Array.from({length:o},(e,t)=>(0,K.jsx)(`span`,{className:`code-usage-daily-spacer`,"aria-hidden":`true`},`trailing-${t}`))]})]})}function VM(e){return e.reduce((e,t)=>e+Number(t.totalTokens),0)}function HM(e,t){if(t<=0)return e>0?`New`:`0%`;let n=Math.round((e-t)/t*100);return`${n>0?`+`:``}${n}%`}function UM(e){let t=LM(e);return t?t.toLocaleDateString([],{month:`short`,day:`numeric`}):e}function WM(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.date===t&&Array.isArray(n.hours)&&n.hours.length===24&&n.hours.every((e,t)=>e.hour===t&&Number.isFinite(Number(e.totalTokens))&&e.totalTokens>=0&&!!(e.agents&&typeof e.agents==`object`))&&Array.isArray(n.agents)&&n.agents.every(e=>!!(e.key&&e.label)&&Number.isFinite(Number(e.totalTokens))&&e.totalTokens>=0)}function GM(e,t){let[n,i]=(0,G.useState)(0),[a,o]=(0,G.useState)({date:``,detail:null,error:``,loading:!1});return(0,G.useEffect)(()=>{if(!e){o({date:``,detail:null,error:``,loading:!1});return}let n=new AbortController;o({date:e,detail:null,error:``,loading:!0});let i=new URLSearchParams({date:e});return t&&i.set(`live`,`1`),fetch(r(`/api/usage/day?${i.toString()}`),{signal:n.signal}).then(async t=>{let n=await t.json();if(!t.ok)throw Error(n.error||`Failed to load day activity`);if(!WM(n.detail,e))throw Error(`Day activity response was incomplete`);return n.detail}).then(t=>{n.signal.aborted||o({date:e,detail:t,error:``,loading:!1})}).catch(t=>{n.signal.aborted||o({date:e,detail:null,error:t instanceof Error?t.message:`Failed to load day activity`,loading:!1})}),()=>n.abort()},[e,t,n]),{...a,retry:()=>i(e=>e+1)}}var KM=[`#245f1d`,`#3b782f`,`#548f47`,`#70a766`,`#8dbc86`,`#aacda5`,`#486d42`,`#789473`];function qM(e){let t=0;for(let n of e)t=(t<<5)-t+n.charCodeAt(0)|0;return KM[Math.abs(t)%KM.length]}function JM({date:e,detail:t,error:n,loading:r,onRetry:i}){let[a,o]=(0,G.useState)(null);if((0,G.useEffect)(()=>o(null),[e]),r)return(0,K.jsx)(`div`,{className:`code-usage-day-breakdown loading`,"data-testid":`code-usage-day-histogram-loading`,children:(0,K.jsx)(`div`,{className:`code-usage-day-breakdown-status`,children:`Loading hourly Agent activity…`})});if(n)return(0,K.jsxs)(`div`,{className:`code-usage-day-breakdown error`,"data-testid":`code-usage-day-histogram-error`,children:[(0,K.jsx)(`span`,{children:n}),(0,K.jsx)(`button`,{type:`button`,onClick:i,children:`Retry`})]});if(!t)return null;let s=Math.max(0,...t.hours.map(e=>e.totalTokens)),l=Array.from(t.agents.reduce((e,t)=>{let n=e.get(t.provider);return n?n.totalTokens+=t.totalTokens:e.set(t.provider,{key:t.provider,label:c(t.provider),totalTokens:t.totalTokens}),e},new Map).values()).sort((e,t)=>t.totalTokens-e.totalTokens||e.label.localeCompare(t.label)),u=a?`${a.label} · ${fM(a.tokens)} tokens`:`${UM(t.date)} · ${fM(t.total.totalTokens)} tokens`;return(0,K.jsxs)(`div`,{className:`code-usage-day-breakdown`,"data-testid":`code-usage-day-histogram`,onMouseLeave:()=>o(null),children:[(0,K.jsxs)(`div`,{className:`code-usage-day-breakdown-heading`,children:[(0,K.jsx)(`span`,{children:`Hourly by Agent type`}),(0,K.jsx)(`strong`,{"data-testid":`code-usage-day-histogram-readout`,children:u})]}),(0,K.jsxs)(`div`,{className:`code-usage-day-histogram-chart`,role:`img`,"aria-label":`Hourly token activity for ${t.date}, split across ${l.length} Agent types`,children:[(0,K.jsxs)(`div`,{className:`code-usage-day-histogram-scale`,"aria-hidden":`true`,children:[(0,K.jsx)(`span`,{children:fM(s)}),(0,K.jsx)(`span`,{children:`0`})]}),(0,K.jsxs)(`div`,{className:`code-usage-day-histogram-plot`,children:[(0,K.jsx)(`div`,{className:`code-usage-day-histogram-bars`,children:t.hours.map(e=>{let n=s>0?e.totalTokens/s*100:0;return(0,K.jsx)(`div`,{className:`code-usage-day-histogram-column`,"data-hour":e.hour,title:`${e.label}:00 · ${NM(e.totalTokens)} tokens`,children:(0,K.jsx)(`div`,{className:`code-usage-day-histogram-stack`,style:{height:`${n}%`},children:l.map(n=>{let r=t.agents.reduce((t,r)=>r.provider===n.key?t+(Number(e.agents[r.key]?.totalTokens)||0):t,0);if(r<=0||e.totalTokens<=0)return null;let i=`${e.label}:00 · ${n.label}`,a=`${i} · ${NM(r)} tokens`;return(0,K.jsx)(`span`,{className:`code-usage-day-histogram-segment`,"data-agent-type":n.key,style:{backgroundColor:qM(n.key),height:`${r/e.totalTokens*100}%`},title:a,onMouseEnter:()=>o({label:i,tokens:r})},n.key)})})},e.hour)})}),(0,K.jsxs)(`div`,{className:`code-usage-day-histogram-axis`,"aria-hidden":`true`,children:[(0,K.jsx)(`span`,{children:`00:00`}),(0,K.jsx)(`span`,{children:`06:00`}),(0,K.jsx)(`span`,{children:`12:00`}),(0,K.jsx)(`span`,{children:`18:00`}),(0,K.jsx)(`span`,{children:`23:00`})]})]})]}),l.length>0&&(0,K.jsx)(`div`,{className:`code-usage-day-agent-legend`,"data-testid":`code-usage-day-agent-legend`,children:l.map(e=>(0,K.jsxs)(`span`,{title:`${e.label} · ${NM(e.totalTokens)} tokens`,children:[(0,K.jsx)(`i`,{style:{backgroundColor:qM(e.key)},"aria-hidden":`true`}),(0,K.jsx)(`b`,{children:e.label}),(0,K.jsx)(`small`,{children:fM(e.totalTokens)})]},e.key))})]})}function YM({label:e,value:t,detail:n}){return(0,K.jsxs)(`div`,{className:`code-usage-detail-stat`,children:[(0,K.jsx)(`span`,{children:e}),(0,K.jsx)(`strong`,{children:t}),n&&(0,K.jsx)(`small`,{children:n})]})}function XM({initialRange:e,usageSummary:t,onClose:n}){let[r,i]=(0,G.useState)(e),[a,o]=(0,G.useState)(null),s=IM(t),c=RM(t),l=c?.reduce((e,t)=>!e||t.totalTokens>e.totalTokens?t:e,null)??null,u=c?.[c.length-1]??null,d=c?.find(e=>e.date===a?.label)??null,f=r===`year`&&(d??u)?.date||``,p=GM(f,!!(f&&c&&f===c[c.length-1]?.date));if((0,G.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),typeof document>`u`)return null;let m=s?.reduce((e,t)=>e+t.totalTokens,0)??0,h=s?.filter(e=>e.totalTokens>0).length??0,g=s?.reduce((e,t)=>!e||t.totalTokens>e.totalTokens?t:e,null)??null,_=c?.slice(-7)??[],v=c?.slice(-14,-7)??[],y=VM(_),b=VM(v),x=c?VM(c):0,S=c?.filter(e=>e.totalTokens>0).length??0,C=_.reduce((e,t)=>e+(Number(t.cacheReadTokens)||0)+(Number(t.cacheWriteTokens)||0),0),w=y>0?Math.min(100,Math.round(C/y*100)):0,T=a?`${a.label} · ${NM(a.tokens)} tokens`:`Last 24 hours · ${NM(m)} tokens`,E=a?`${a.label} · ${NM(a.tokens)} tokens`:`Last 52 weeks · ${NM(x)} tokens`;return(0,dj.createPortal)((0,K.jsx)(`div`,{className:`code-usage-detail-backdrop`,"data-testid":`code-usage-detail-backdrop`,onMouseDown:e=>{e.target===e.currentTarget&&n()},children:(0,K.jsxs)(`section`,{className:`code-usage-detail-dialog`,"data-testid":`code-usage-detail-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-usage-detail-title`,children:[(0,K.jsxs)(`header`,{className:`code-usage-detail-header`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{className:`code-usage-detail-eyebrow`,children:`Local provider tokens`}),(0,K.jsx)(`h2`,{id:`code-usage-detail-title`,children:`Usage activity`})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-usage-detail-close`,"aria-label":`Close usage activity`,onClick:n,children:(0,K.jsx)(Se,{})})]}),(0,K.jsxs)(`div`,{className:`code-usage-detail-tabs`,role:`tablist`,"aria-label":`Usage activity range`,children:[(0,K.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":r===`day`,"data-testid":`code-usage-detail-day-tab`,onClick:()=>{o(null),i(`day`)},children:`1 Day`}),(0,K.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":r===`year`,"data-testid":`code-usage-detail-year-tab`,onClick:()=>{o(null),i(`year`)},children:`52 Weeks`})]}),(0,K.jsxs)(`div`,{className:`code-usage-detail-chart`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||o(null)},onMouseLeave:()=>o(null),children:[r===`day`&&s&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`code-usage-detail-chart-heading`,children:[(0,K.jsx)(`span`,{children:`Hourly activity`}),(0,K.jsxs)(`strong`,{children:[fM(m),` tokens`]})]}),(0,K.jsx)(zM,{usageSummary:t,points:s,onInspect:o})]}),r===`year`&&c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(BM,{points:c,inspection:a,showDayHighlight:!0,onInspect:o}),(0,K.jsx)(JM,{date:f,detail:p.date===f?p.detail:null,error:p.date===f?p.error:``,loading:p.date===f?p.loading:!0,onRetry:p.retry})]}),(0,K.jsx)(`div`,{className:`code-usage-detail-readout`,"data-testid":`code-usage-detail-readout`,children:r===`day`?T:E})]}),(0,K.jsx)(`div`,{className:`code-usage-detail-analysis`,"data-testid":`code-usage-detail-analysis`,children:r===`day`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(YM,{label:`24-hour tokens`,value:fM(m)}),(0,K.jsx)(YM,{label:`Active hours`,value:`${h}`,detail:`hours with token activity`}),(0,K.jsx)(YM,{label:`Peak hour`,value:g?MM(g.startedAt):`--`,detail:g?`${fM(g.totalTokens)} tokens`:`no activity`})]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(YM,{label:`Last 7 days`,value:fM(y)}),(0,K.jsx)(YM,{label:`Previous 7 days`,value:fM(b),detail:`${HM(y,b)} change`}),(0,K.jsx)(YM,{label:`Peak day`,value:l?UM(l.date):`--`,detail:l?`${fM(l.totalTokens)} tokens`:`no activity`}),(0,K.jsx)(YM,{label:`Active days`,value:`${S}`,detail:`within 52 weeks`}),(0,K.jsx)(YM,{label:`7-day cache share`,value:`${w}%`,detail:`read and write tokens`}),(0,K.jsx)(YM,{label:`52-week tokens`,value:fM(x)})]})})]})}),document.body)}function ZM({usageSummary:e}){let t=IM(e),n=RM(e),[r,i]=(0,G.useState)(null),[a,o]=(0,G.useState)(null);if(!t&&!n)return null;let s=t?.reduce((e,t)=>e+t.totalTokens,0)??0,c=aM(Number(e.timeline?.windowMs)/6e4).toLowerCase(),l=n?.slice(-7).reduce((e,t)=>e+t.totalTokens,0)??0,u=n?.reduce((e,t)=>e+t.totalTokens,0)??0,d=r?`${r.label} · ${NM(r.tokens)} tokens`:`${t?`${c} ${fM(s)}`:``}${t&&n?` · `:``}${n?`7d ${fM(l)} · 52w ${fM(u)}`:``}`;return(0,K.jsxs)(`div`,{className:`code-usage-activity`,onMouseLeave:()=>i(null),children:[t&&(0,K.jsxs)(`button`,{type:`button`,className:`code-usage-chart-trigger`,"data-testid":`code-usage-open-day`,title:`Open 1-day usage details`,onClick:()=>o(`day`),children:[(0,K.jsxs)(`div`,{className:`code-usage-activity-heading`,children:[(0,K.jsxs)(`span`,{children:[c,` · activity`]}),(0,K.jsxs)(`span`,{children:[aM(e.timeline.bucketMs/6e4).toLowerCase(),` buckets`]})]}),(0,K.jsx)(zM,{usageSummary:e,points:t,onInspect:i})]}),n&&(0,K.jsx)(`button`,{type:`button`,className:`code-usage-chart-trigger`,"data-testid":`code-usage-open-year`,title:`Open 52-week usage details`,onClick:()=>o(`year`),children:(0,K.jsx)(BM,{points:n,onInspect:i})}),(0,K.jsx)(`div`,{className:`code-usage-activity-readout`,"data-testid":`code-usage-activity-readout`,title:d,children:d}),a&&(0,K.jsx)(XM,{initialRange:a,usageSummary:e,onClose:()=>o(null)})]})}function QM({collapsed:e,mainAgent:t,now:n,usageSummary:r,onToggleCollapsed:i,onOpenMainAgent:a,onRestartMainAgent:o}){let s=gM(r),c=_M(r),[l,u]=(0,G.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)(W,{}):(0,K.jsx)(be,{})}),(0,K.jsx)(`span`,{children:`Usage`})]}),(0,K.jsx)(`span`,{className:`code-usage-header-meta`,children:e?(0,K.jsx)(OM,{usageSummary:r,now:n}):(0,K.jsx)(`span`,{className:`code-usage-summary`,"data-testid":`code-usage-summary`,title:`5-minute rate · hourly and daily activity`,children:`5m rate · activity`})})]}),!e&&(0,K.jsxs)(K.Fragment,{children:[s.length>0&&r?.timeline&&(0,K.jsx)(ZM,{usageSummary:r}),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:`${ee(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:EM(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))})]}),s.map(e=>(0,K.jsx)($M,{provider:e},e.provider)),s.length>1&&c!==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:pM(c)})]}),(0,K.jsx)(kM,{usageSummary:r})]})]})}function $M({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:mM(e)})]}),e.quota.available&&(0,K.jsxs)(K.Fragment,{children:[t&&(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow`,title:uM(r,t),children:[(0,K.jsx)(`span`,{children:aM(t.windowMinutes)}),(0,K.jsx)(`strong`,{children:lM(t)})]}),n&&(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow`,title:uM(r,n),children:[(0,K.jsx)(`span`,{children:aM(n.windowMinutes)}),(0,K.jsx)(`strong`,{children:lM(n)})]})]}),(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:pM(e.tokenUsage.tokensPerMinute)})]})]})}function eN({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)(tN,{item:e,index:o,activeTerminalId:t,now:n,onOpenAgent:r,onShowPreview:i,onHidePreview:a},Rk({kind:`agent`,agent:e.agent})))})}function tN({item:e,index:t,activeTerminalId:n,now:r,onOpenAgent:i,onShowPreview:a,onHidePreview:o}){let s=Yk({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,mN(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 nN({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=Yk({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,mN(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`})]},Rk({kind:`agent`,agent:e,claimedSessionKey:r.get(e.id)}))})})}function rN({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`?Yk({kind:`agent`,agent:e.agent},a):Yk({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=_?aD(_):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?mN(g,h):hN(_,h),!0),onMouseLeave:p,onContextMenu:e=>{if(g){s(e,g.id);return}_&&u(e,_.provider,aD(_))},onKeyDown:e=>{g?c(e,g.id):_&&d(e,_.provider,aD(_)),!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`?Rk({kind:`agent`,agent:e.agent,claimedSessionKey:i.get(e.agent.id)}):Rk({kind:`history`,session:e.session}))})})}function iN({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,G.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)(W,{}):(0,K.jsx)(be,{})}),(0,K.jsx)(`span`,{children:x.pinned})]}),!t&&(0,K.jsx)(`div`,{className:`code-agent-list code-pinned-list`,children:n?(0,K.jsx)(rN,{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)(wN,{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},Rk({kind:`agent`,agent:t,claimedSessionKey:o.get(t.id)}))}return(0,K.jsx)(wN,{session:e.session,searchSelected:aD(e.session)===a,now:l,onResume:h,onOpenSessionContextMenu:g,onOpenSessionKeyboardMenu:_,onShowPreview:v,onHidePreview:y,copy:x},Rk({kind:`history`,session:e.session}))})})]})}function aN(e,t){return e.branch?e.branch:e.detached?`${t.worktreeDetached}@${e.head.slice(0,7)}`:e.bare?`bare`:e.head.slice(0,7)}function oN({agentId:e,anchorRef:t,copy:n,fallback:r,point:i,onClose:a,onMountProject:o}){let s=(0,G.useRef)(null),c=(0,G.useRef)(null),[l,u]=(0,G.useState)(r),[d,f]=(0,G.useState)(!1),[p,m]=(0,G.useState)(``),h=(0,G.useCallback)(()=>{c.current?.abort();let t=new AbortController;c.current=t,f(!0),m(``),ce(e,{signal:t.signal}).then(e=>{t.signal.aborted||u(e)}).catch(e=>{t.signal.aborted||e?.name===`AbortError`||m(n.worktreeLoadFailed)}).finally(()=>{t.signal.aborted||f(!1)})},[e,n.worktreeLoadFailed]);return(0,G.useEffect)(()=>(h(),()=>c.current?.abort()),[h]),(0,G.useEffect)(()=>{let e=e=>{let n=e.target;n&&(s.current?.contains(n)||t.current?.contains(n))||a()},n=e=>{e.key===`Escape`&&(e.preventDefault(),a(),t.current?.focus())};return window.addEventListener(`pointerdown`,e,!0),window.addEventListener(`keydown`,n,!0),()=>{window.removeEventListener(`pointerdown`,e,!0),window.removeEventListener(`keydown`,n,!0)}},[t,a]),(0,K.jsxs)(`div`,{ref:s,className:`code-worktree-popover`,"data-testid":`code-project-worktree-menu`,role:`dialog`,"aria-label":n.worktrees,style:{left:i.x,top:i.y},children:[(0,K.jsxs)(`div`,{className:`code-worktree-popover-header`,children:[(0,K.jsx)(`span`,{children:n.worktrees}),(0,K.jsx)(`span`,{className:`code-worktree-popover-count`,children:l.items.length}),(0,K.jsx)(`button`,{type:`button`,className:d?`loading`:``,disabled:d,onClick:h,children:n.refresh})]}),p&&(0,K.jsx)(`div`,{className:`code-worktree-popover-status error`,children:p}),!p&&!l.isGitRepo&&(0,K.jsx)(`div`,{className:`code-worktree-popover-status`,children:n.gitHistoryNotRepository}),(0,K.jsx)(`div`,{className:`code-worktree-list`,children:l.items.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-worktree-row ${e.current?`current`:``}`,"data-current":e.current?`true`:void 0,"data-main":e.main?`true`:void 0,title:e.workspace,onClick:()=>{o(e.workspace),a()},children:[(0,K.jsx)(`span`,{className:`code-worktree-row-marker`,"aria-hidden":`true`}),(0,K.jsxs)(`span`,{className:`code-worktree-row-content`,children:[(0,K.jsxs)(`span`,{className:`code-worktree-row-heading`,children:[(0,K.jsx)(`strong`,{children:aN(e,n)}),(0,K.jsxs)(`span`,{className:`code-worktree-row-badges`,children:[e.current&&(0,K.jsx)(`span`,{children:n.worktreeCurrent}),e.main&&(0,K.jsx)(`span`,{children:n.worktreeMain}),e.locked&&(0,K.jsx)(`span`,{title:e.lockReason,children:n.worktreeLocked}),e.prunable&&(0,K.jsx)(`span`,{title:e.pruneReason,children:n.worktreePrunable})]}),e.head&&(0,K.jsx)(`code`,{children:e.head.slice(0,7)})]}),(0,K.jsx)(`span`,{className:`code-worktree-row-path`,children:e.workspace})]})]},e.workspace))})]})}function sN(e){return e?.workspace?{isGitRepo:!0,commonDir:e.commonDir,currentWorkspace:e.workspace,mainWorkspace:e.mainWorkspace,items:Array.isArray(e.worktrees)?e.worktrees:[]}:null}function cN({project:e,collapsed:t,forceAgentsExpanded:n,compactAgents:r,activeTerminalId:i,selectedSearchAgentId:a,selectedSearchSessionHandle:o,claimedAgentSessionKeyByAgentId:s,agentShortcutKeys:l,keyboardShortcutsEnabled:u,now:f,openWorkspaceFile:p,openWorkspaceFiles:h,agentLaunchOptions:g,fileRevealRequest:_,fileSearchFocusRequest:v,onToggleProject:y,onToggleProjectSessions:b,onMountProject:x,onNewAgent:S,onStartAgent:C,onOpenProjectContextMenu:w,onOpenProjectKeyboardMenu:T,onOpenAgent:E,onUpdateAgentFlags:D,onReorderAgent:O,onOpenAgentContextMenu:k,onOpenAgentKeyboardMenu:A,onResumeAgentSession:j,onOpenAgentSessionContextMenu:M,onOpenAgentSessionKeyboardMenu:N,onShowAgentPreview:P,onHideAgentPreview:F,onOpenProjectFile:ee,onSelectOpenWorkspaceFile:I,onCloseOpenWorkspaceFile:te,onMoveWorkspaceEntries:L,onDeleteWorkspaceEntries:R,onRefreshProjectOpenFiles:ne,copy:z}){let B=(0,G.useRef)(null),re=(0,G.useRef)(null),ie=(0,G.useRef)(null),ae=(0,G.useRef)(null),V=(0,G.useRef)(null),se=(0,G.useRef)(null),[le,ue]=(0,G.useState)(null),[de,fe]=(0,G.useState)(null),[pe,me]=(0,G.useState)(()=>sN(e.gitWorktree)),[he,H]=(0,G.useState)(!1),[ge,_e]=(0,G.useState)(!1),[ve,ye]=(0,G.useState)(!1),[xe,Se]=(0,G.useState)(null),[Ce,we]=(0,G.useState)(()=>Uj(null,e.agents)),Te=Uj(Ce,e.agents),Ee=e.agents.find(e=>!e.isMain&&e.id===Te)??null,De=e.workspace?Fn(e.workspace):``,Oe=e.id!==`__farming_main_agent__`&&!!De,U=new Set([De,...e.agents.filter(e=>!e.isMain).map(e=>e.id),...Ee&&!Ee.isMain?[Ee.id]:[]]),ke=t=>t.workspaceRoot===e.workspace||U.has(t.agentId),Ae=p&&ke(p)?p:null,je=h.filter(ke),Me=new Set(je.filter(e=>e.dirty).map(e=>e.file.path)),Ne=new Set(je.filter(e=>e.externalChanged).map(e=>e.file.path)),Pe=e.agents.filter(e=>!e.pinned),Fe=e.agentSessions.filter(e=>!e.pinned),Ie=Pe.length>0||Fe.length>0||(e.hiddenAgentSessionCount??0)>0,Le=ve&&oe()&&Pe.length>1,Re=(r||Le)&&Pe.length>0,ze=Re||he?Pe:fN(Pe,Yj,[i,a]),Be=Math.max(0,Pe.length-ze.length),Ve=ge&&!n;(0,G.useEffect)(()=>{Ce!==Te&&we(Te)},[Te,Ce]),(0,G.useEffect)(()=>{let t=sN(e.gitWorktree);t&&me(t)},[e.gitWorktree]),(0,G.useEffect)(()=>{if(!De)return;let e=new AbortController;return ce(De,{signal:e.signal}).then(me).catch(()=>{}),()=>e.abort()},[De]);let He=(0,G.useCallback)(e=>!Ee?.id||e?.sourceAgentId?e:{...e,sourceAgentId:Ee.id},[Ee?.id]),Ue=(0,G.useCallback)((e,t,n)=>{ee(e,t,He(n))},[ee,He]),We=(0,G.useCallback)((e,t,n)=>I(e,t,He(n)),[I,He]),Ge=(0,G.useCallback)(e=>{ye(!e)},[]),Ke=(e,t)=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),F(),Se({agentId:t,targetAgentId:``,position:`before`})},qe=(e,t)=>{if(!xe||xe.agentId===t)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let n=e.currentTarget.getBoundingClientRect(),r=e.clientY<n.top+n.height/2?`before`:`after`;xe.targetAgentId===t&&xe.position===r||Se(e=>e?{...e,targetAgentId:t,position:r}:null)},Je=()=>Se(null),Ye=(e,t)=>{if(e.preventDefault(),!xe||xe.agentId===t){Je();return}let n=Pe.filter(e=>e.id!==xe.agentId),r=n.findIndex(e=>e.id===t);if(r<0){Je();return}let i=xe.position===`before`?r:r+1;O(xe.agentId,i>0?n[i-1]?.id??``:``,i<n.length?n[i]?.id??``:``),Je()},Xe=e=>{if(e.preventDefault(),!xe)return;let t=Pe.filter(e=>e.id!==xe.agentId);O(xe.agentId,t[t.length-1]?.id??``,``),Je()},Ze=e=>{xe&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,xe.targetAgentId!==Xj&&Se(e=>e?{...e,targetAgentId:Xj,position:`after`}:null))};(0,G.useEffect)(()=>{Pe.length<=Yj&&he&&H(!1)},[he,Pe.length]),(0,G.useLayoutEffect)(()=>{let e=B.current;if(!e)return;let t=()=>{let t=re.current;e.style.setProperty(`--code-project-sticky-height`,t?`${Math.ceil(t.getBoundingClientRect().height)}px`:``);let n=ie.current;e.style.setProperty(`--code-agents-sticky-height`,n?`${Math.ceil(n.getBoundingClientRect().height)}px`:`0px`)};t();let n=re.current,r=ie.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,Ie]),(0,G.useEffect)(()=>{if(!le)return;let e=e=>{let t=e.target;t&&(V.current?.contains(t)||ae.current?.contains(t))||ue(null)},t=e=>{e.key===`Escape`&&(e.preventDefault(),ue(null),ae.current?.focus())};return window.addEventListener(`pointerdown`,e,!0),window.addEventListener(`keydown`,t,!0),()=>{window.removeEventListener(`pointerdown`,e,!0),window.removeEventListener(`keydown`,t,!0)}},[le]);let Qe=t=>{if(t.preventDefault(),t.stopPropagation(),g.length===0){S(e.workspace,void 0,t.currentTarget);return}let n=t.currentTarget.getBoundingClientRect(),r=Math.min(260,g.length*34+12);ue(oe()?Cj(n,r,void 0,160):Sj(n,r,void 0,160))},$e=t=>{ue(null),C(t,e.workspace)},et=pe?.items.find(e=>e.current),tt=pe?.isGitRepo&&et&&et?et.branch||`detached@${et.head.slice(0,7)}`:``,nt=pe?.items.length||0;return(0,K.jsxs)(`section`,{ref:B,className:`code-project-group`,"data-testid":`code-project-group`,children:[(0,K.jsxs)(`div`,{ref:re,className:`code-project-row`,children:[(0,K.jsxs)(`span`,{className:`code-project-title-content`,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:()=>y(e.id),onContextMenu:t=>w(t,e.id),onKeyDown:t=>T(t,e.id),children:[(0,K.jsx)(`span`,{className:`code-folder-icon ${t?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:t?(0,K.jsx)(W,{}):(0,K.jsx)(be,{})}),(0,K.jsx)(`span`,{className:`code-project-title-name`,children:e.name})]}),tt&&pe&&(0,K.jsxs)(`button`,{ref:se,type:`button`,className:`code-project-worktree`,"data-testid":`code-project-worktree`,title:`${tt} · ${nt} ${z.worktrees.toLocaleLowerCase()} · ${z.showWorktrees}`,"aria-label":`${tt} · ${nt} ${z.worktrees}`,"aria-haspopup":`dialog`,"aria-expanded":de?!0:void 0,onClick:e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getBoundingClientRect(),n=Math.min(440,Math.max(320,window.innerWidth-24)),r=Math.min(420,Math.max(132,(pe?.items.length||2)*58+54));fe(oe()?Cj(t,r,void 0,n):Sj(t,r,void 0,n))},children:[(0,K.jsx)(`span`,{className:`code-project-worktree-icon`,"aria-hidden":`true`,children:(0,K.jsx)(tM,{})}),(0,K.jsx)(`span`,{className:`code-project-worktree-name`,children:tt}),nt>1&&(0,K.jsx)(`span`,{className:`code-project-worktree-count`,"aria-hidden":`true`,children:nt})]})]}),(0,K.jsxs)(`span`,{className:`code-project-title-actions`,"aria-hidden":!1,children:[Ie&&!n&&(0,K.jsx)(`button`,{type:`button`,className:`code-project-title-action`,"data-testid":`code-project-agent-visibility`,"data-collapsed":Ve?`true`:`false`,"aria-expanded":!Ve,"aria-label":Ve?z.showAgents:z.hideAgents,title:Ve?z.showAgents:z.hideAgents,onClick:()=>_e(e=>!e),children:Ve?(0,K.jsx)(uN,{}):(0,K.jsx)(dN,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-project-title-action`,"data-testid":`code-project-actions`,"aria-label":z.openOptions,title:z.openOptions,onClick:t=>w(t,e.id),children:(0,K.jsx)(pN,{})}),(0,K.jsx)(`button`,{ref:ae,type:`button`,className:`code-project-title-action`,"data-testid":`code-project-new-agent`,"aria-label":z.newAgent,title:z.newAgent,"aria-haspopup":`menu`,"aria-expanded":le?!0:void 0,onClick:Qe,children:(0,K.jsx)(lN,{})})]}),le&&typeof document<`u`&&(0,dj.createPortal)((0,K.jsx)(`div`,{ref:V,className:`code-context-menu code-project-launch-menu`,"data-testid":`code-project-new-agent-menu`,role:`menu`,style:{left:le.x,top:le.y},children:g.map(e=>(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-project-agent-launch-${e.name}`,onClick:()=>$e(e.command||e.name),children:[(0,K.jsx)(m,{name:e.name}),(0,K.jsx)(`span`,{children:c(e.name)})]},e.name))}),document.body),de&&pe&&typeof document<`u`&&(0,dj.createPortal)((0,K.jsx)(oN,{agentId:De,anchorRef:se,copy:z,fallback:pe,point:de,onClose:()=>fe(null),onMountProject:x}),document.body)]}),!t&&(0,K.jsxs)(`div`,{className:`code-project-expanded`,children:[Ie&&(0,K.jsx)(`div`,{ref:ie,className:`code-agents-section`,"data-testid":`code-agents-section`,"data-project-id":e.id,children:(0,K.jsxs)(`div`,{className:`code-agent-list`,children:[!Ve&&(0,K.jsxs)(K.Fragment,{children:[Re?(0,K.jsx)(nN,{agents:Pe,activeTerminalId:i,selectedSearchAgentId:a,claimedAgentSessionKeyByAgentId:s,now:f,onOpenAgent:E,onOpenAgentContextMenu:k,onOpenAgentKeyboardMenu:A,onShowPreview:P,onHidePreview:F}):ze.map(e=>(0,K.jsx)(wN,{agent:e,shortcutHint:u?l.get(e.id):void 0,active:e.id===i,searchSelected:e.id===a,now:f,onOpenAgent:E,onUpdateAgentFlags:D,reorderable:!0,dragging:xe?.agentId===e.id,dropPosition:xe?.targetAgentId===e.id?xe.position:void 0,onAgentDragStart:Ke,onAgentDragEnd:Je,onAgentDragOver:qe,onAgentDrop:Ye,onOpenAgentContextMenu:k,onOpenAgentKeyboardMenu:A,onShowPreview:P,onHidePreview:F,copy:z},Rk({kind:`agent`,agent:e,claimedSessionKey:s.get(e.id)}))),Fe.map(e=>(0,K.jsx)(wN,{session:e,searchSelected:aD(e)===o,now:f,onResume:j,onOpenSessionContextMenu:M,onOpenSessionKeyboardMenu:N,onShowPreview:P,onHidePreview:F,copy:z},Rk({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:()=>b(e.id),children:[(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:z.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>Jj&&(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row code-session-show-more`,"data-testid":`code-session-show-less`,onClick:()=>b(e.id),children:(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:z.showLess})})})]}),!n&&!Ve&&!Re&&Pe.length>Yj&&(0,K.jsxs)(`div`,{className:`code-agent-list-controls`,"data-testid":`code-agent-list-controls`,children:[Be>0&&(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-row code-session-show-more ${xe?.targetAgentId===Xj?`drop-after`:``}`,"data-testid":`code-agent-show-more`,onClick:()=>H(!0),onDragOver:Ze,onDrop:Xe,children:[(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:z.showMore})}),(0,K.jsx)(`span`,{className:`code-agent-row-trailing`,children:(0,K.jsx)(`span`,{className:`code-agent-age`,children:Be})})]}),he&&(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row code-session-show-more`,"data-testid":`code-agent-show-less`,onClick:()=>H(!1),children:(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:z.showLess})})})]})]})}),Oe&&(0,K.jsx)(G.Suspense,{fallback:null,children:(0,K.jsx)(rM,{projectId:e.id,projectWorkspace:e.workspace,agentId:De,agentLaunchOptions:g,activeFilePath:Ae?.file.path,openFiles:je.map(e=>({agentId:e.agentId,workspaceRoot:e.workspaceRoot,key:d(e),path:e.file.path,dirty:e.dirty,externalChanged:e.externalChanged})),revealRequest:_&&U.has(_.agentId)?_:void 0,focusSearchRequest:v&&U.has(v.agentId)?v:void 0,editorDirtyFilePaths:Me,editorExternalChangedFilePaths:Ne,onOpenFile:Ue,onSelectOpenFile:We,onCloseOpenFile:te,onNewAgent:S,onStartAgent:C,onMoveEntries:L,onDeleteEntries:R,onRefreshOpenFiles:ne,onFilesCollapsedChange:Ge,copy:z})})]})]})}function lN(){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 uN(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M2.98444 8.62471L2.98346 8.62815C2.91251 8.8948 2.63879 9.05404 2.37202 8.9833C1.94098 8.86907 2.01687 8.37186 2.01687 8.37186L2.03453 8.31047C2.03453 8.31047 2.06063 8.22636 2.08166 8.1653C2.12369 8.04329 2.18795 7.87274 2.27931 7.66977C2.46154 7.26493 2.75443 6.72477 3.19877 6.18295C4.09629 5.08851 5.60509 4 8.00017 4C10.3952 4 11.904 5.08851 12.8016 6.18295C13.2459 6.72477 13.5388 7.26493 13.721 7.66977C13.8124 7.87274 13.8766 8.04329 13.9187 8.1653C13.9397 8.22636 13.9552 8.27541 13.9658 8.31047C13.9711 8.328 13.9752 8.34204 13.9781 8.35236L13.9816 8.365L13.9827 8.36916L13.9832 8.37069L13.9835 8.37186C14.0542 8.63878 13.8952 8.91253 13.6283 8.9833C13.3618 9.05397 13.0885 8.89556 13.0172 8.62937L13.0169 8.62815L13.0159 8.62471L13.0085 8.5997C13.0014 8.57616 12.9898 8.53927 12.9732 8.49095C12.9399 8.39422 12.8866 8.25227 12.8091 8.08023C12.6538 7.73508 12.4041 7.27523 12.0283 6.81706C11.2857 5.9115 10.0445 5 8.00017 5C5.95584 5 4.71464 5.9115 3.97201 6.81706C3.59627 7.27523 3.34655 7.73508 3.19119 8.08023C3.11375 8.25227 3.06047 8.39422 3.02715 8.49095C3.01051 8.53927 2.9989 8.57616 2.99179 8.5997L2.98444 8.62471ZM8.00024 7C6.61953 7 5.50024 8.11929 5.50024 9.5C5.50024 10.8807 6.61953 12 8.00024 12C9.38096 12 10.5002 10.8807 10.5002 9.5C10.5002 8.11929 9.38096 7 8.00024 7ZM6.50024 9.5C6.50024 8.67157 7.17182 8 8.00024 8C8.82867 8 9.50024 8.67157 9.50024 9.5C9.50024 10.3284 8.82867 11 8.00024 11C7.17182 11 6.50024 10.3284 6.50024 9.5Z`})})}function dN(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M10.1196 10.8267L14.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.85355L4.37624 5.08334C3.90117 5.4183 3.5126 5.80026 3.19877 6.18295C2.75443 6.72477 2.46154 7.26493 2.27931 7.66977C2.18795 7.87274 2.12369 8.04329 2.08166 8.1653C2.06063 8.22636 2.03453 8.31047 2.03453 8.31047L2.01687 8.37186C2.01687 8.37186 1.94098 8.86907 2.37202 8.9833C2.63879 9.05404 2.91251 8.8948 2.98346 8.62815L2.98444 8.62471L2.99179 8.5997C2.9989 8.57616 3.01051 8.53927 3.02715 8.49095C3.06047 8.39421 3.11375 8.25227 3.19119 8.08023C3.34655 7.73507 3.59627 7.27523 3.97201 6.81706C4.26363 6.46146 4.63213 6.10494 5.09595 5.80306L6.67356 7.38067C5.9688 7.82277 5.50024 8.60667 5.50024 9.5C5.50024 10.8807 6.61953 12 8.00024 12C8.89358 12 9.67747 11.5314 10.1196 10.8267ZM9.3807 10.0878C9.15205 10.6241 8.62005 11 8.00024 11C7.17182 11 6.50024 10.3284 6.50024 9.5C6.50024 8.88019 6.87616 8.34819 7.41244 8.11955L9.3807 10.0878ZM6.31962 4.19853L7.174 5.05291C7.43366 5.01852 7.70875 5 8.00017 5C10.0445 5 11.2857 5.9115 12.0283 6.81706C12.4041 7.27523 12.6538 7.73507 12.8091 8.08023C12.8866 8.25227 12.9399 8.39421 12.9732 8.49095C12.9898 8.53927 13.0014 8.57616 13.0085 8.5997L13.0159 8.62471L13.0169 8.62815L13.0172 8.62937C13.0885 8.89555 13.3618 9.05397 13.6283 8.9833C13.8952 8.91253 14.0542 8.63878 13.9835 8.37186L13.9832 8.37069L13.9827 8.36916L13.9816 8.365L13.9781 8.35236C13.9752 8.34204 13.9711 8.328 13.9658 8.31047C13.9552 8.27541 13.9397 8.22636 13.9187 8.1653C13.8766 8.04329 13.8124 7.87274 13.721 7.66977C13.5388 7.26493 13.2459 6.72477 12.8016 6.18295C11.904 5.0885 10.3952 4 8.00017 4C7.38264 4 6.82403 4.07236 6.31962 4.19853Z`})})}function fN(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 pN(){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 mN(e,t,n){return{key:`agent:${e.id}`,title:t.title,project:n||QE(e.projectWorkspace||e.cwd),lastActive:e.lastActivity||e.startedAt||0,provider:$j(e),workspaceRootId:e.workspaceRootId}}function hN(e,t){return{key:`session:${aD(e)}`,title:t.title,project:uD(e),lastActive:dD(e),provider:Qj(e.provider)}}function gN({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:M(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)(_N,{})}),(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)(m,{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)(vN,{})}),(0,K.jsx)(`span`,{children:e.branch||`—`})]})]})}function _N(){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 vN(){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 yN(){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 bN(){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 xN(){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 SN(){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 CN(){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 wN({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:h,onOpenAgentContextMenu:g,onOpenAgentKeyboardMenu:_,onResume:v,onOpenSessionContextMenu:y,onOpenSessionKeyboardMenu:b,onShowPreview:x,onHidePreview:S,copy:C}){let w=(0,G.useRef)(!1),T=Dt(e),E=T?{kind:`agent`,agent:T}:t?{kind:`history`,session:t,fallbackTitle:C.sessionFallbackTitle(t.providerName)}:null;if(!E)return null;let D=Yk(E,a),O=D.requiresResume,k=T?.id??``,A=t?.provider??``,j=t?.id??``,M=O?`code-active-session-row`:`code-agent-row`,N=T?$j(T):Qj(t?.provider),P=()=>{if(O){S?.(),A&&j&&v?.(A,j,t?.providerHomeId);return}k&&o?.(k)};return(0,K.jsxs)(`div`,{tabIndex:0,className:`code-agent-row ${N?`has-provider`:``} ${O?`requires-resume`:``} ${r?`active`:``} ${i?`search-selected`:``} ${D.pinned?`pinned`:``} ${D.unread?`unread`:``} ${l?`dragging`:``} ${u?`drop-${u}`:``}`,draggable:c||void 0,"data-testid":M,"data-agent-id":T?.id,"data-activity-level":T?.activityLevel,"data-provider":t?.provider,"data-session-id":t?aD(t):void 0,"aria-label":D.rowTitle||D.title,onDragStart:e=>{!k||!c||(w.current=!0,d?.(e,k))},onDragEnd:()=>{f?.(),window.setTimeout(()=>{w.current=!1},0)},onDragOver:e=>k&&p?.(e,k),onDrop:e=>k&&h?.(e,k),onClick:e=>{if(w.current){e.preventDefault(),e.stopPropagation();return}P()},onMouseEnter:e=>{T?x?.(e,mN(T,D)):t&&x?.(e,hN(t,D))},onMouseLeave:S,onContextMenu:e=>{if(O){S?.(),A&&t&&y?.(e,A,aD(t));return}k&&g?.(e,k)},onKeyDown:e=>{O?A&&t&&b?.(e,A,aD(t)):k&&_?.(e,k),!e.defaultPrevented&&(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),P())},children:[N&&(0,K.jsx)(`span`,{className:`code-agent-row-provider-icon`,"aria-hidden":`true`,children:(0,K.jsx)(m,{name:N,variant:`color`})}),(0,K.jsxs)(`span`,{className:`code-agent-row-copy ${D.detailLabel?`has-details`:``}`,children:[(0,K.jsx)(`span`,{className:`code-agent-name`,children:D.title}),D.detailLabel&&(0,K.jsx)(`span`,{className:`code-agent-meta`,"data-testid":`code-agent-row-detail`,title:D.detailLabel,children:D.detailLabel})]}),(0,K.jsxs)(`span`,{className:`code-agent-row-trailing`,children:[D.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-agent-dot ${D.lifecycleStatus} ${D.turnActive?`turn-active`:``}`,title:D.commandTitle||D.lifecycleStatus}),D.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)(CN,{})}),D.scheduled&&(0,K.jsx)(`span`,{className:`code-agent-schedule-clock`,"data-testid":`code-agent-schedule-clock`,title:D.scheduleTitle,"aria-label":D.scheduleTitle||C.scheduledTask}),D.unread&&(0,K.jsx)(`span`,{className:`code-agent-unread`,title:C.unread}),D.ageVisible&&(0,K.jsx)(`span`,{className:`code-agent-age code-agent-relative-age`,"data-testid":`code-agent-row-age`,title:D.ageTitle,children:D.ageLabel}),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 ${D.pinned?`active`:``}`,"data-testid":`code-agent-row-pin`,"aria-label":D.pinned?C.unpinAgent:C.pinAgent,title:D.pinned?C.unpinAgent:C.pinAgent,onClick:e=>{e.preventDefault(),e.stopPropagation(),T&&s?.(T,{pinned:!D.pinned})},children:D.pinned?(0,K.jsx)(bN,{}):(0,K.jsx)(yN,{})}),(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:e=>{e.preventDefault(),e.stopPropagation(),T&&s?.(T,{archived:!0})},children:(0,K.jsx)(SN,{})})]}),(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(),O){S?.(),A&&t&&y?.(e,A,aD(t));return}k&&g?.(e,k)},children:(0,K.jsx)(pN,{})}),n&&(0,K.jsx)(`kbd`,{children:n})]})]})}var TN=[`codex`,`claude`,`opencode`,`qoder`],EN=new Set([`bash`,`zsh`]),DN=/^[A-Za-z0-9._-]+$/,ON=[3,5,10,15,30,60,180];function kN(e){let t=e/1e3;return ON.reduce((e,n)=>Math.abs(n-t)<Math.abs(e-t)?n:e)}function AN(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`,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`,updateAction:t?`更新`:`Update`,updateToVersion:e=>t?`更新到 ${e}`:`Update to ${e}`,updating:t?`更新中…`:`Updating…`,checkingUpdates:t?`正在检查更新…`:`Checking for updates…`,currentVersion:t?`当前版本`:`Current`,latestVersion:t?`最新版本`:`Latest`,targetVersion:t?`升级版本`:`Target`,updateSource:t?`更新源`:`Update source`,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||`-`,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 jN(e){return e.trim().toLowerCase()}function MN(e){let t=e&&typeof e==`object`&&!Array.isArray(e)?e:{},n={};return Object.entries(t).forEach(([e,t])=>{let r=jN(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||!DN.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 NN(e){return e===`codex`?`Codex`:e===`claude`?`Claude`:e===`opencode`?`OpenCode`:e===`qoder`?`Qoder`:e}function PN(e){return{codex:`~/.codex`,claude:`~/.claude`,opencode:`~/.opencode`,qoder:`~/.qoder`}[e]??`~/.${e}`}function FN(e){return!!e?.some(e=>e.id.toLowerCase()!==`default`)}function IN(e){return e.filter(e=>e.supported!==!1&&e.interactive!==!1).filter(e=>!EN.has(e.name)).filter(e=>TN.includes(e.name)).map(e=>jN(e.name)).filter(Boolean)}function LN(e,t){let n=new Set(IN(t)),r=Object.keys(e).filter(t=>FN(e[t])),i=new Set([...n,...r]);return Array.from(i).sort((e,t)=>{let n=TN.indexOf(e),r=TN.indexOf(t),i=n===-1?TN.length:n,a=r===-1?TN.length:r;return i===a?e.localeCompare(t):i-a})}function RN(e,t){let n=e[t]??[];return n.some(e=>e.id.toLowerCase()===`default`)?n:[{id:`default`,path:PN(t)},...n]}function zN(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 BN(e){return{provider:e,id:``,path:``}}function VN({open:e,activeAgentId:t=null,language:n,uiPreferences:i,agentLaunchOptions:a,onClose:o,onUpdateUiPreferences:s}){let c=(0,G.useMemo)(()=>AN(n),[n]),l=(0,G.useRef)(null),u=(0,G.useRef)(null),d=(0,G.useRef)(``),[f,p]=(0,G.useState)(!1),[m,h]=(0,G.useState)(``),[g,_]=(0,G.useState)(15),[v,y]=(0,G.useState)(null),[b,x]=(0,G.useState)(``),[S,C]=(0,G.useState)(!1),[w,T]=(0,G.useState)(!1),[E,D]=(0,G.useState)(()=>MN({codex:[{id:`default`,path:`~/.codex`}],claude:[{id:`default`,path:`~/.claude`}],opencode:[{id:`default`,path:`~/.opencode`}],qoder:[{id:`default`,path:`~/.qoder`}]})),[O,k]=(0,G.useState)(!1),[A,j]=(0,G.useState)(!1),[M,N]=(0,G.useState)(``),[P,F]=(0,G.useState)(``),[ee,I]=(0,G.useState)(null),te=(0,G.useCallback)(()=>{k(!0),F(``),fetch(r(`/api/settings`)).then(e=>e.json()).then(e=>{D(MN(e.settings?.agentHomes)),p(e.settings?.dangerouslySkipAgentPermissionsByDefault===!0),h(String(e.settings?.updateUrl??``)),_(kN(Number(e.settings?.searchTimeoutMs??15e3)))}).catch(()=>F(c.loadFailed)).finally(()=>k(!1))},[c.loadFailed]);(0,G.useEffect)(()=>()=>{u.current!==null&&window.clearTimeout(u.current)},[]),(0,G.useEffect)(()=>{e&&(te(),window.requestAnimationFrame(()=>l.current?.focus({preventScroll:!0})))},[te,e]),(0,G.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 L=(0,G.useCallback)(e=>{j(!0),F(``),N(``),fetch(r(`/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);D(MN(n?.settings?.agentHomes??e)),I(null),N(c.saved),window.dispatchEvent(new CustomEvent(`farming-agent-homes-saved`))}).catch(e=>F(e instanceof Error?e.message:c.saveFailed)).finally(()=>j(!1))},[c.saveFailed,c.saved]),R=(0,G.useCallback)((e=!0,t=!1)=>{t||(C(!0),F(``)),fetch(r(`/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;y(n);let r=n?.versions??[];x(e=>e&&r.some(t=>t.assetName===e)?e:r[0]?.assetName||``)}).catch(e=>{t||F(e instanceof Error?e.message:c.loadFailed)}).finally(()=>{t||C(!1)})},[c.loadFailed]),ne=(0,G.useCallback)(()=>{T(!0),F(``),N(``),fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({updateUrl:m})}).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||c.saveFailed);h(String(t?.settings?.updateUrl??``)),N(c.saved),R(!0)}).catch(e=>F(e instanceof Error?e.message:c.saveFailed)).finally(()=>T(!1))},[c.saveFailed,c.saved,R,m]),z=(0,G.useCallback)(e=>{_(e),F(``),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>{fetch(r(`/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);_(kN(Number(n?.settings?.searchTimeoutMs??e*1e3)))}).catch(e=>F(e instanceof Error?e.message:c.saveFailed))},120)},[c.saveFailed]),B=(0,G.useCallback)(()=>{let e=v?.versions?.find(e=>e.assetName===b);if(!e?.available){R(!0);return}C(!0),F(``),N(``),d.current=e.version||e.assetName||``,fetch(r(`/api/update/install`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({assetName:b})}).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}`)}y(e=>({...e??{},state:t?.update?.state??e?.state,blockingAgents:t?.update?.blockingAgents??e?.blockingAgents}))}).catch(e=>{d.current=``,F(e instanceof Error?e.message:c.saveFailed)}).finally(()=>C(!1))},[c,R,b,v]);(0,G.useEffect)(()=>{e&&R(!1)},[e,R]);let re=(0,G.useCallback)(e=>{p(e),j(!0),F(``),N(``),fetch(r(`/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);p(t?.settings?.dangerouslySkipAgentPermissionsByDefault===!0),N(c.saved)}).catch(t=>{p(!e),F(t instanceof Error?t.message:c.saveFailed)}).finally(()=>j(!1))},[c.saveFailed,c.saved]),ie=(0,G.useCallback)(()=>{if(!ee)return;let e=jN(ee.provider),t=ee.path.trim();if(!t){F(c.missingPath);return}let n=E[e]??[],r=ee.id.trim()||zN(t,n).id;if(!DN.test(r)){F(c.invalidId);return}if(n.some(e=>e.id.toLowerCase()===r.toLowerCase())){F(c.duplicateId);return}L({...E,[e]:[...n,{id:r,path:t}]})},[c.duplicateId,c.invalidId,c.missingPath,ee,E,L]),ae=(0,G.useCallback)((e,t)=>{if(t.toLowerCase()===`default`)return;let n=E[e]??[];window.confirm(c.confirmRemove(t))&&L({...E,[e]:n.filter(e=>e.id!==t)})},[c,E,L]),V=v?.state?.phase||``;if((0,G.useEffect)(()=>{if(!e||![`downloading`,`extracting`,`installing`,`restarting`,`rolling-back`].includes(V))return;let t=window.setInterval(()=>R(!1,!0),1500);return()=>window.clearInterval(t)},[e,R,V]),(0,G.useEffect)(()=>{!e||V!==`succeeded`||!d.current||(v?.state?.version||v?.current?.releaseVersion||v?.current?.packageVersion||``)===d.current&&(d.current=``,window.location.reload())},[e,V,v]),!e)return null;let oe=LN(E,a),se=v?.versions??[],ce=se.find(e=>e.assetName===b),le=[`downloading`,`extracting`,`installing`,`restarting`,`rolling-back`].includes(V),ue=S||w||le,de=v?.method||v?.current?.type||``,fe=c.updateMethodLabel(de),pe=de===`app-bundle`||de===`source-deploy`,me=v?.current?.releaseVersion||v?.current?.packageVersion||v?.state?.previousVersion||`-`,he=v?.latest?.version||`-`,H=ce?.version||v?.selected?.version||he,ge=me!==`-`&&H!==`-`&&me!==H&&(v?.available===!0||ue),_e=v?V===`rolled-back`?c.updateRolledBack:V===`failed`&&v?.state?.error?v.state.error:V===`restarting`?c.updateRestarting:[`downloading`,`extracting`,`installing`,`rolling-back`].includes(V)?c.updateInstalling:v.available?c.updateAvailable:V===`succeeded`?c.updateSucceeded:v.latest?.blockedReason||c.upToDate:c.checkingUpdates,ve=le?c.updating:ce?.available&&H!==`-`?c.updateToVersion(H):c.updateAction;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)(we,{})}),(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)(Se,{})})]}),(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)(Oe,{"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(`${r(`/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(ON.length-1),step:`1`,value:ON.indexOf(g),"aria-label":c.searchTimeout,onChange:e=>z(ON[Number(e.target.value)]??15)}),(0,K.jsx)(`output`,{children:c.searchTimeoutValue(g)})]})})]}),(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.updates})})}),(0,K.jsxs)(`div`,{className:`code-settings-update-card ${v?.available?`available`:``}`,"data-testid":`code-settings-update-card`,children:[(0,K.jsxs)(`div`,{className:`code-settings-update-overview`,children:[(0,K.jsxs)(`div`,{className:`code-settings-update-versions`,"aria-label":`${c.currentVersion} ${me}; ${c.latestVersion} ${he}`,children:[(0,K.jsx)(`span`,{children:me}),ge&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{className:`code-settings-update-arrow`,"aria-hidden":`true`,children:`→`}),(0,K.jsx)(`strong`,{children:H})]})]}),(0,K.jsxs)(`div`,{className:`code-settings-update-summary ${v?.available?`available`:``} ${V?`phase-${V}`:``}`,role:`status`,"aria-live":`polite`,children:[de&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{children:fe}),(0,K.jsx)(`span`,{"aria-hidden":`true`,children:` · `})]}),(0,K.jsx)(`span`,{children:_e})]})]}),(0,K.jsxs)(`div`,{className:`code-settings-update-actions`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-settings-update-refresh`,onClick:()=>R(!0),disabled:ue,"aria-label":c.refreshUpdates,title:c.refreshUpdates,children:`↻`}),(0,K.jsx)(`button`,{type:`button`,className:`primary`,"data-testid":`code-settings-update-action`,onClick:B,disabled:ue||!ce?.available,children:ve})]}),pe&&(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:m,placeholder:c.updateUrlPlaceholder,"aria-label":c.updateUrl,onChange:e=>h(e.target.value),disabled:ue})]}),pe&&(0,K.jsx)(`button`,{type:`button`,className:`code-settings-update-save`,onClick:ne,disabled:ue,children:c.saveUpdateUrl}),se.length>1&&(0,K.jsx)(`label`,{className:`code-settings-update-version`,children:(0,K.jsx)(`select`,{value:b,"aria-label":c.targetVersion,onChange:e=>x(e.target.value),disabled:ue||se.length===0,children:se.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.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 ${f?`active`:``}`,role:`checkbox`,"aria-label":c.dangerousSkipLabel,"aria-pressed":f,disabled:A,onClick:()=>re(!f),children:(0,K.jsx)(ke,{})})]})]}),(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})]}),(O||A||M)&&(0,K.jsx)(`span`,{className:`code-settings-status`,children:O?c.loading:A?c.saving:M})]}),P&&(0,K.jsx)(`div`,{className:`code-settings-error`,role:`alert`,children:P}),oe.length===0&&(0,K.jsx)(`div`,{className:`code-agent-home-empty`,children:c.noAgents}),(0,K.jsx)(`div`,{className:`code-agent-homes-list`,children:oe.map(e=>{let t=RN(E,e),n=IN(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:[NN(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:()=>{F(``),N(``),I(BN(e))},"aria-label":c.addHome(NN(e)),title:c.addHome(NN(e)),children:(0,K.jsx)(Ne,{})})]}),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:()=>ae(e,t.id),"aria-label":c.remove,title:c.remove,children:(0,K.jsx)(Se,{})})})]},t.id)),ee&&ee.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:ee.path,placeholder:c.pathPlaceholder,"aria-label":c.homePath,onChange:e=>I(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:ee.id,placeholder:c.homeNamePlaceholder,"aria-label":c.homeName,onChange:e=>I(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:()=>I(null),"aria-label":c.cancel,title:c.cancel,children:(0,K.jsx)(Se,{})}),(0,K.jsx)(`button`,{type:`button`,className:`primary`,disabled:A,onClick:ie,"aria-label":c.save,title:c.save,children:(0,K.jsx)(ke,{})})]})]})]},e)})})]})]})]})})}var HN=`\r`;function UN(e){return[{type:`paste`,text:e},HN]}var WN={newAgent:`New Agent`,search:`Search`,history:`History`,codex:`Farming Code`,expandSidebar:`Expand sidebar`,collapseSidebar:`Collapse sidebar`,enterFocusMode:`Enter focus mode`,exitFocusMode:`Exit focus mode`,appModeOpen:`App mode and fullscreen`,appModeTitle:`Use Farming without browser controls`,appModeDescription:`Install Farming for a clean app window, or use fullscreen temporarily.`,appModeRecommended:`Recommended`,appModeInstallTitle:`Install Farming 2`,appModeInstallDescription:`Opens as its own window without tabs, the address bar, or browser extensions.`,appModeInstallAction:`Install Farming 2`,appModeInstallStepOne:`Open Chrome’s ⋮ menu, then choose “Cast, save and share”.`,appModeInstallStepTwo:`Choose “Install page as app”, then open Farming 2 from its app icon.`,appModeFullscreenTitle:`Fullscreen for now`,appModeFullscreenDescription:`Hide browser controls for this window. Press Esc to leave fullscreen.`,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`,resizeNavigation:`Resize 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`,pinProject:`Pin project`,unpinProject:`Unpin project`,revealInFinder:`Reveal in Finder`,revealInFinderFailed:`Failed to reveal project in Finder`,createPermanentWorktree:`Create permanent worktree`,permanentWorktreeCreated:`Permanent worktree created`,permanentWorktreeFailed:`Failed to create permanent worktree`,markAllAsRead:`Mark all as read`,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`,removeProject:`Remove Project`,deleteWorktree:`Permanently Delete Worktree`,deleteWorktreeQuestion:`Permanently delete worktree?`,deleteWorktreeDescription:`This permanently deletes the worktree and all of its files.`,forceDelete:`Permanently 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…`,terminalProfileApplying:`Applying model to Codex Terminal…`,terminalProfileApplied:`Codex Terminal model updated.`,terminalProfileFailed:e=>`Codex Terminal model was not changed: ${e}`,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`,historyPagination:`History pages`,historyPageStatus:(e,t,n,r)=>`${e} / ${t}${r?`+`:``} · ${n} loaded`,previousPage:`Previous page`,nextPage:`Next page`,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`,showAgents:`Show agents`,hideAgents:`Hide agents`,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`,worktrees:`Worktrees`,showWorktrees:`Show repository worktrees`,worktreeCurrent:`current`,worktreeMain:`main`,worktreeDetached:`detached`,worktreeLocked:`locked`,worktreePrunable:`prunable`,worktreeLoadFailed:`Unable to load repository worktrees`,gitHistory:`History`,gitHistoryEmpty:`No commits yet`,gitHistoryNotRepository:`This project is not a Git repository`,gitHistoryLoadMore:`Load more`,gitHistoryView:`History view`,gitHistoryCurrentScope:`Current`,gitHistoryAllScope:`All`,gitHistoryCurrentBranch:`Current branch`,gitHistoryAllBranches:`All branches`,gitHistoryCommitMessage:`Message`,gitHistoryParent:`Compare with parent`,gitHistoryRootCommit:`Root commit`,gitHistoryReviewCommit:`Review commit`,gitHistoryCommitChanges:e=>`${e} file${e===1?``:`s`} changed`,gitHistoryNoChanges:`No file changes`,gitHistoryChangesTruncated:`More changed files were omitted`,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`,refreshFiles:`Refresh files`,refreshingFiles:`Refreshing files…`,filesRefreshed:`Files refreshed`,filesRefreshFailed:`Files refresh failed`,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`,chooseWorkspaceDirectory:`Choose workspace folder`,workspaceDirectoryBrowserFailed:`Couldn’t read this directory.`,workspaceDirectoryBrowserHostHint:`Browse folders on the Farming host.`,workspaceDirectoryBrowserGo:`Go to directory`,workspaceDirectoryBrowserParent:`Parent directory`,workspaceDirectoryBrowserEmpty:`No subdirectories.`,workspaceDirectoryBrowserTruncated:`Only the first 500 folders are shown. Enter a more specific path to continue.`,workspaceDirectoryBrowserSelect:`Select this folder`,workspaceMissingTitle:`Create this workspace?`,workspaceMissingDescription:`This directory does not exist yet. Farming can create it and start the Agent there.`,workspaceCreateAndStart:`Create & Start`,workspaceCreating:`Creating...`,workspaceCreateFailedTitle:`Couldn’t create workspace`,workspaceCreateForbiddenDescription:`Farming does not have permission to create this directory. Choose another location or update the parent directory permissions.`,workspaceCreateFailedDescription:`Farming couldn’t create this directory. Check the path and try again.`,returnToWorkspace:`Change Path`,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...`},GN={newAgent:`新建 Agent`,search:`搜索`,history:`历史`,codex:`Farming Code`,expandSidebar:`展开侧边栏`,collapseSidebar:`收起侧边栏`,enterFocusMode:`进入沉浸模式`,exitFocusMode:`退出沉浸模式`,appModeOpen:`应用模式与全屏`,appModeTitle:`隐藏浏览器控制`,appModeDescription:`安装 Farming 获得干净的应用窗口,也可以临时进入全屏。`,appModeRecommended:`推荐`,appModeInstallTitle:`安装 Farming 2`,appModeInstallDescription:`以后从独立窗口打开,不显示标签栏、地址栏和浏览器扩展。`,appModeInstallAction:`安装 Farming 2`,appModeInstallStepOne:`打开 Chrome 右上角 ⋮,选择“投放、保存和分享”。`,appModeInstallStepTwo:`选择“将网页安装为应用”,以后从 Farming 2 应用图标打开。`,appModeFullscreenTitle:`暂时全屏`,appModeFullscreenDescription:`只为当前窗口隐藏浏览器控制,按 Esc 即可退出。`,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:`关闭导航`,resizeNavigation:`调整导航宽度`,openOptions:`打开选项`,openSettings:`设置`,agentActions:`Agent 操作`,appearanceLight:`外观:浅色`,appearanceDark:`外观:深色`,languageEnglish:`语言:English`,languageChinese:`语言:中文`,pinAgent:`置顶 Agent`,unpinAgent:`取消置顶`,pinProject:`置顶项目`,unpinProject:`取消置顶项目`,revealInFinder:`在访达中显示`,revealInFinderFailed:`无法在访达中显示项目`,createPermanentWorktree:`创建永久 worktree`,permanentWorktreeCreated:`已创建永久 worktree`,permanentWorktreeFailed:`创建永久 worktree 失败`,markAllAsRead:`全部标为已读`,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:`归档项目`,removeProject:`移除项目`,deleteWorktree:`彻底删除 worktree`,deleteWorktreeQuestion:`彻底删除 worktree?`,deleteWorktreeDescription:`这会彻底删除该 worktree 及其中的所有文件。`,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…`,terminalProfileApplying:`正在应用 Codex Terminal 模型…`,terminalProfileApplied:`Codex Terminal 模型已更新。`,terminalProfileFailed:e=>`Codex Terminal 模型未修改:${e}`,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`,historyPagination:`历史记录分页`,historyPageStatus:(e,t,n,r)=>`第 ${e} / ${t}${r?`+`:``} 页 · 已载入 ${n} 条`,previousPage:`上一页`,nextPage:`下一页`,agentSessions:`Agent 会话`,recentWorkspaces:`最近工作区`,agentsSessionsSummary:(e,t)=>`${e} 个 Agent · ${t} 个会话`,restore:`恢复`,continueRun:`继续`,open:`打开`,archived:`已归档`,pinned:`已置顶`,unread:`未读`,showMore:`显示更多`,showLess:`收起`,showAgents:`展开 Agent`,hideAgents:`隐藏 Agent`,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:`刷新变更`,worktrees:`工作树`,showWorktrees:`查看仓库工作树`,worktreeCurrent:`当前`,worktreeMain:`主工作树`,worktreeDetached:`游离`,worktreeLocked:`已锁定`,worktreePrunable:`可清理`,worktreeLoadFailed:`无法加载仓库工作树`,gitHistory:`历史`,gitHistoryEmpty:`还没有提交`,gitHistoryNotRepository:`当前项目不是 Git 仓库`,gitHistoryLoadMore:`加载更多`,gitHistoryView:`历史视图`,gitHistoryCurrentScope:`当前`,gitHistoryAllScope:`全部`,gitHistoryCurrentBranch:`当前分支`,gitHistoryAllBranches:`所有分支`,gitHistoryCommitMessage:`提交说明`,gitHistoryParent:`与父提交比较`,gitHistoryRootCommit:`根提交`,gitHistoryReviewCommit:`Review 提交`,gitHistoryCommitChanges:e=>`${e} 个文件有变化`,gitHistoryNoChanges:`没有文件变化`,gitHistoryChangesTruncated:`还有部分变更文件未展示`,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:`新建文件夹`,refreshFiles:`刷新文件`,refreshingFiles:`正在刷新文件…`,filesRefreshed:`文件已刷新`,filesRefreshFailed:`文件刷新失败`,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:`/工作区/路径`,chooseWorkspaceDirectory:`选择工作区目录`,workspaceDirectoryBrowserFailed:`无法读取这个目录。`,workspaceDirectoryBrowserHostHint:`浏览 Farming Host 上的目录。`,workspaceDirectoryBrowserGo:`转到目录`,workspaceDirectoryBrowserParent:`上级目录`,workspaceDirectoryBrowserEmpty:`没有子目录。`,workspaceDirectoryBrowserTruncated:`仅显示前 500 个目录,请输入更具体的路径继续浏览。`,workspaceDirectoryBrowserSelect:`选择此目录`,workspaceMissingTitle:`创建这个工作区?`,workspaceMissingDescription:`这个目录尚不存在。Farming 可以创建目录,并在其中启动 Agent。`,workspaceCreateAndStart:`创建并启动`,workspaceCreating:`正在创建…`,workspaceCreateFailedTitle:`无法创建工作区`,workspaceCreateForbiddenDescription:`Farming 没有权限创建这个目录。请选择其他位置,或调整父目录权限。`,workspaceCreateFailedDescription:`Farming 无法创建这个目录。请检查路径后重试。`,returnToWorkspace:`修改路径`,recentWorkspacesLower:`最近工作区`,start:`启动`,back:`返回`,backToAgent:`返回 Agent`,goBack:`后退`,goForward:`前进`,backendConnecting:`正在连接 Farming 后端...`,backendConnectionLost:`Farming 后端连接已断开,正在重连...`,backendHeartbeatLost:`没有收到 Farming 后端心跳,正在等待恢复...`};function KN(e){return e===`zh`?GN:WN}function qN(){return window}function JN(e,t={},n=qN()){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 YN={ask:`Ask for approval`,approve:`Approve for me`,full:`Full access`,custom:`Custom`},XN={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`},ZN=[`ask`,`approve`,`full`,`custom`].map(e=>({value:e,label:YN[e],description:XN[e],color:e===`approve`?`blue`:e===`full`?`orange`:`muted`})),QN={default:`Default`,auto:`Auto`,acceptEdits:`Accept edits`,dontAsk:`Don't ask`,plan:`Plan`,bypassPermissions:`Bypass permissions`},$N={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`},eP=[`default`,`auto`,`acceptEdits`,`dontAsk`,`plan`,`bypassPermissions`].map(e=>({value:e,label:QN[e],description:$N[e],color:e===`bypassPermissions`?`orange`:[`auto`,`acceptEdits`,`plan`].includes(e)?`blue`:`muted`})),tP=[{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`}],nP=`Claude settings`,rP={value:`config`,effort:`config`,label:nP},iP=[{value:`config`,label:nP,displayName:nP,defaultEffort:`config`,reasoningLevels:[rP,...tP],source:`settings`}],aP={available:!1,effectiveModel:``,effectiveEffort:``,modelOptions:[],effortOptions:tP};function oP(e){return!!(e&&e in YN)}function sP(e){return!!(e&&e in QN)}function cP(e,t,n){return e?oP(t)?t:`custom`:n}function lP(e,t,n){return e?sP(t)?t:`default`:n}function uP(e){if(typeof e!=`string`)return``;let t=e.trim();return!t||/[\s\x00-\x1f\x7f]/.test(t)||t.startsWith(`-`)?``:t}function dP(e){return e===`config`?e:uP(e)||`config`}function fP(e){return e&&tP.some(t=>t.value===e)?e:``}function pP(e){return e===`config`?e:fP(e)||`config`}function mP(e){let t=[];return Array.isArray(e)&&e.forEach(e=>{let n=fP(e?.value);n&&t.push({value:n,effort:n,label:e.label||eD(n),description:e.description})}),t.length>0?t:tP}function hP(e){let t=mP(e?.effortOptions),n=uP(e?.effectiveModel),r=fP(e?.effectiveEffort),i=[];return Array.isArray(e?.modelOptions)&&e.modelOptions.forEach(e=>{let n=uP(e?.value);n&&i.push({...e,value:n,label:e.label||n,displayName:e.displayName||n,defaultEffort:fP(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 gP(e,t){let n=t.effortOptions?.length?t.effortOptions:tP,r=t.modelOptions?.length?t.modelOptions:iP.map(e=>({...e})),i=dP(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 _P(e,t){return e===`config`?t.effectiveModel||t.modelOptions?.[0]?.value||`config`:dP(e)}function vP(e,t){return e===`config`?t.effectiveEffort||`config`:pP(e)}function yP(e,t){let n=t.effortOptions?.length?t.effortOptions:tP;return e===`config`?[rP,...n]:n.some(t=>t.value===e)?n:[...n,{value:e,effort:e,label:eD(e)}]}function bP(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:nD(void 0,e),displayName:nD(void 0,e),defaultEffort:t,reasoningLevels:[{value:t,effort:t,label:eD(t)}],serviceTiers:i,source:`pending-catalog`}]}function xP(e){let t=e.agentLaunchProfiles?.codex??{},n=t.approvalMode??e.codexApprovalMode,r=tD(t.modelPreset??e.codexModelPreset),i=t.model||e.codexModel||r.model,a=t.reasoningEffort||e.codexReasoningEffort||r.effort,o=e.agentLaunchProfiles?.claude??{};return{codexApprovalMode:oP(n)?n:`approve`,codexModel:i,codexReasoningEffort:a,codexServiceTier:t.serviceTier||e.codexServiceTier||`default`,codexModelPreset:`${i}:${a}`,claudePermissionMode:sP(o.permissionMode)?o.permissionMode:`default`,claudeModel:dP(o.model),claudeEffort:pP(o.effort)}}function SP(e,t){return!e?.model||!e.reasoningEffort?t:{model:e.model,reasoningEffort:e.reasoningEffort,serviceTier:e.serviceTier||`default`}}function CP({agentKind:e,codexModel:t,codexReasoningEffort:n,codexServiceTier:r,codexModelPreset:i,codexModelOptions:a,codexApprovalMode:o,claudeModel:s,claudeEffort:c,claudeSettings:l,claudePermissionMode:u}){let d=_P(s,l),f=vP(c,l),p=e===`claude`?gP(s,l):e===`codex`?bP(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`?yP(h,l):v?.reasoningLevels?.length?v.reasoningLevels:h?[{value:h,effort:h,label:eD(h)}]:[],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`?eP:ZN,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:nD(v,m),currentReasoningLabel:x?.label??eD(h),currentSpeedLabel:S?.label??``,permissionModeOptions:C,currentPermissionMode:w,currentPermissionOption:T,currentPermissionLabel:T?.label??w,currentPermissionColor:T?.color??`muted`}}function wP(e){return!e.isMain&&e.archived!==!0&&e.status!==`dead`&&e.status!==`stopped`}function TP(e){return!e.isMain&&e.archived===!0}function EP(e,t=[]){let n=new Map;return e.forEach(e=>{if(!wP(e))return;let t=e.providerSessionKey||nk(e.source);t&&n.set(e.id,t)}),n}function DP(e,t){return t.get(e.id)||`agent:${e.id}`}function OP(e){return e.providerSessionKey&&e.providerSessionTemporary!==!0?120:nk(e.source)?100:e.providerSessionKey?40:0}function kP(e){return e.status===`running`?30:e.status===`pending`?20:0}function AP(e,t){return OP(e)+(t.has(e.id)?50:0)+kP(e)}function jP(e,t){let n=new Map;return e.forEach(e=>{let r=DP(e,t),i=n.get(r);if(!i){n.set(r,e);return}let a=AP(e,t),o=AP(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(DP(e,t))===e)}function MP(e,t){return e.filter(e=>!t.has(aD(e)))}function NP(e,t,n){return e.filter(e=>{let r=aD(e);return(e.archived||!t.has(r))&&!n.has(r)})}function PP({allAgents:e,liveAgents:t,sessions:n,mainPageSessionKeys:r}){let i=t.filter(wP),a=EP(i,n),o=new Set(a.values()),s=jP(i,a),c=n.filter(e=>!e.archived&&r.has(aD(e))).sort(fD),l=MP(c,o),u=MP(n,o).sort(fD),d=NP(n,r,o).sort(fD);return{liveAgents:s,archivedAgents:e.filter(TP).sort((e,t)=>(t.archivedAt??0)-(e.archivedAt??0)),mainPageAgentSessions:c,sidebarAgentSessions:l,searchableAgentSessions:u,historyAgentSessions:d,claimedAgentSessionKeys:o,claimedAgentSessionKeyByAgentId:a}}function FP(){return{activeFile:null,files:[],closedFileCache:new Map}}function IP(e){return{activeFile:e.activeFile,files:e.files,closedFileCache:e.closedFileCache}}function LP(){let[e,t]=(0,G.useState)(()=>FP()),n=(0,G.useRef)(e),r=(0,G.useCallback)(e=>(n.current=IP(e),t(n.current),n.current),[]),i=(0,G.useCallback)((e,t,i)=>r(R(n.current,e,t,i)),[r]),a=(0,G.useCallback)((e,t,i)=>{let a=_(n.current,e,t,i);return a?r(a):null},[r]),o=(0,G.useCallback)(e=>{let t=v(n.current,e);return t.closedFiles.length>0&&r(t),t},[r]),s=(0,G.useCallback)(e=>{let t=u(n.current,{canReopen:e});return t?r(t):null},[r]),c=(0,G.useCallback)(e=>r(O(n.current,e)),[r]),d=(0,G.useCallback)((e,t)=>r(g(n.current,e,t)),[r]),f=(0,G.useCallback)(e=>{let t=n.current.activeFile;if(!t)return null;let i=l(t,e);return r({...n.current,activeFile:i,files:L(n.current.files,i)})},[r]),p=(0,G.useCallback)((e,t)=>{let i=b(n.current,e,t);return i!==n.current&&r(i),i},[r]),m=(0,G.useCallback)((e,t)=>{let i=te(n.current,e,t);return t.length>0&&r(i),i},[r]),h=(0,G.useMemo)(()=>Array.from(e.closedFileCache.values()),[e.closedFileCache]);return(0,G.useMemo)(()=>({activeFile:e.activeFile,files:e.files,closedFiles:h,openFromRead:i,select:a,close:o,reopenLastClosed:s,update:c,refreshFromReads:d,updateDraft:f,move:p,deleteEntries:m}),[h,o,m,p,i,d,s,a,e.activeFile,e.files,c,f])}function RP(){let[e,t]=(0,G.useState)(()=>Rn()),n=(0,G.useRef)(e),r=(0,G.useRef)(!1),i=(0,G.useRef)(null),a=(0,G.useCallback)(e=>(n.current=e,t(e),e),[]),o=(0,G.useCallback)(e=>{r.current||a(Un(n.current,e))},[a]),s=(0,G.useCallback)(e=>{o(zn(e))},[o]),c=(0,G.useCallback)(e=>{o(Bn(e))},[o]),l=(0,G.useCallback)(e=>{r.current||(i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{i.current=null,o(Bn({...e,reason:`cursor`}))},650))},[o]),u=(0,G.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,G.useCallback)(()=>{window.setTimeout(()=>{r.current=!1},120)},[]),f=(0,G.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,G.useEffect)(()=>()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null)},[]),(0,G.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 zP({agents:e,permissionSwitchReplacement:t,onDiscardAttachment:n}){let[r,i]=(0,G.useState)({});(0,G.useLayoutEffect)(()=>{let r=new Set(e.filter(e=>!e.archived&&e.status!==`dead`&&e.status!==`stopped`).flatMap(e=>[CA(e),ZA(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?xA(i,n):n,delete r[e]};e(t.originalAgentId,t.replacementAgentId),e(`acp:${t.originalAgentId}`,`acp:${t.replacementAgentId}`)}return e.forEach(e=>{let t=CA(e);if(!t)return;wA(e).forEach(e=>{if(e===t)return;let n=a[e];if(!n)return;let r=s();r[t]=r[t]?xA(r[t],n):n,delete r[e]});let n=ZA(e);QA(e).forEach(e=>{if(e===n)return;let t=a[e];if(!t)return;let r=s();r[n]=r[n]?xA(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,G.useCallback)(t=>{if(!t)return``;for(let n of e){let e=$A(t),r=e?ZA(n):CA(n);if(!r)continue;let i=e?QA(n):wA(n);if(t===r||i.includes(t))return r}return t},[e]);return{composerByAgentKey:r,updateComposerStateForKey:(0,G.useCallback)((e,t)=>{i(n=>{let r=a(e);if(!r)return n;let i=n[r]??gA(),o=t(i);return o===i?n:{...n,[r]:o}})},[a]),updateExistingComposerStateForKey:(0,G.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 BP(){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 VP(e){return e.replace(/^Language:\s*/i,``).replace(/^语言[::]\s*/,``)}function HP(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 UP(e){return e.replace(/^Appearance:\s*/i,``).replace(/^外观[::]\s*/,``)}function WP(e,t){return e.size===t.length?t.every(t=>e.has(t)):!1}function GP(e){return(e.ctrlKey||e.metaKey)&&e.shiftKey&&!e.altKey&&e.key.toLowerCase()===`t`}var KP=296,qP=220,JP=840,YP=360,XP=5*6e4,ZP=52,QP=172,$P=900,eF=12,tF=4,nF=15e3,rF=286,iF=60,aF=1e3,oF=150,sF=35e3;async function cF(e,t){let n=[],r=!0,i=0,a=Array.from({length:Math.min(tF,t.length)},async()=>{for(;i<t.length;){let a=t[i];i+=1;let o=new AbortController,s=window.setTimeout(()=>o.abort(),nF);try{n.push(await le(e,a,{signal:o.signal}))}catch{r=!1}finally{window.clearTimeout(s)}}});return await Promise.all(a),{files:n,successful:r}}function lF(){return typeof window>`u`?!1:oe()&&re()}function uF(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 dF(e){return!!(e&&Dk(e.command)===`codex`&&e.runtimeBinding.kind===`terminal`)}function fF(e){return e instanceof HTMLElement?e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable:!1}function pF(e){return tk(e)}function mF(e){return e.kind===`agent-session`?aD(e):YE(e)}function hF(){return oe()}function gF(e){return!hF()&&e>0&&e<$P}function _F(){return hF()?!0:typeof window<`u`&&gF(window.innerWidth)}function vF(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}function yF(e){let t=(e||``).replace(/\/+$/,``);return t.split(`/`).filter(Boolean).pop()||t||`workspace`}function bF(e){if(e.lineNumber)return{lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn}}function xF(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 SF(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 CF(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 wF({agents:e,taskHistory:t,mainPageSessionKeys:n,activeView:i,dialogOpen:a,usageSummary:o,contextWindowByAgentId:s={},activeTerminalId:c,permissionSwitchingAgentId:l,agentSwitchingKind:u,permissionSwitchReplacement:m,openTerminalIds:g,terminalFocusRequest:_,keyMap:v,keyboardShortcutsEnabled:y,uiPreferences:b,onOpenTerminal:C,onOpenTerminalWhenReady:E,onNewAgent:O,onStartAgent:M,onRenameAgent:N,onUpdateAgentFlags:F,onOpenArchivedAgent:te,onForkAgent:L,onDeleteForkWorktreeProject:R,onRestartMainAgent:ne,onWorkspaceViewChange:z,onKill:B,onInterruptAgent:re,sendComposerInput:ae,respondToAppServerRequest:se,onSessionOutput:ce,onUpdateUiPreferences:ue}){An(`codeWorkspace`);let fe=It(),{composerByAgentKey:pe,updateComposerStateForKey:me,updateExistingComposerStateForKey:he}=zP({agents:e,permissionSwitchReplacement:m,onDiscardAttachment:IA}),H=(0,G.useRef)({}),ge=(0,G.useRef)({}),[,_e]=(0,G.useState)({}),[ve,ye]=(0,G.useState)(`terminal`),[be]=(0,G.useState)(()=>j().surface),xe=(0,G.useRef)(!1),Se=(0,G.useRef)(!be),Ce=LP(),{canGoBack:we,canGoForward:Te,recordAgent:Ee,recordFile:De,recordFileCursor:Oe,beginNavigation:U,finishNavigation:ke,pruneEntries:Ae}=RP(),W=Ce.activeFile,je=Ce.files,Me=(0,G.useCallback)(async(e,t)=>{let n=Array.from(new Set(Ce.files.filter(e=>e.workspaceRoot===t).map(e=>e.file.path)));if(n.length===0)return!0;let r=await cF(e,n);return Ce.refreshFromReads(t,r.files),r.successful},[Ce]),[Ne,Pe]=(0,G.useState)(!1),[Fe,Ie]=(0,G.useState)(``),[ze,Ve]=(0,G.useState)(0),[,He]=(0,G.useState)([]),[Ue,We]=(0,G.useState)([]),[Ge,Ke]=(0,G.useState)(!1),qe=(0,G.useRef)([]),Je=(0,G.useRef)(0),Ye=(0,G.useRef)(Promise.resolve()),[Xe,Ze]=(0,G.useState)([]),Qe=(0,G.useRef)([]),$e=(0,G.useRef)(0),et=(0,G.useRef)(Promise.resolve()),tt=(0,G.useRef)(new Set),[nt,rt]=(0,G.useState)({}),[it,at]=(0,G.useState)([]),[ot,st]=(0,G.useState)(()=>new Set),[ct,lt]=(0,G.useState)(`approve`),[,ut]=(0,G.useState)(`gpt-5.5:xhigh`),[dt,ft]=(0,G.useState)(`gpt-5.5`),[pt,mt]=(0,G.useState)(`xhigh`),[ht,gt]=(0,G.useState)(`default`),[_t,vt]=(0,G.useState)([]),[yt,bt]=(0,G.useState)(()=>new Set),[xt,St]=(0,G.useState)(()=>new Map),Ct=(0,G.useRef)(new Set),[wt,Tt]=(0,G.useState)(`default`),[Et,Dt]=(0,G.useState)(`config`),[kt,At]=(0,G.useState)(`config`),[jt,Mt]=(0,G.useState)(aP),[Nt,Pt]=(0,G.useState)([]),[Ft,Lt]=(0,G.useState)([]),[Bt,Vt]=(0,G.useState)(``),[Ut,Wt]=(0,G.useState)(!1),[Gt,Kt]=(0,G.useState)([]),[qt,Yt]=(0,G.useState)(!1),Xt=(0,G.useRef)(!1),Zt=(0,G.useRef)(null),Qt=(0,G.useRef)(iF),[en,tn]=(0,G.useState)(()=>XO().pinnedOverrides),[nn,rn]=(0,G.useState)(!1),[an,on]=(0,G.useState)(!1),[sn,cn]=(0,G.useState)(()=>new Set),[ln,un]=(0,G.useState)(()=>new Set),[dn,fn]=(0,G.useState)(KP),[pn,mn]=(0,G.useState)(()=>_F()),[hn,gn]=(0,G.useState)(()=>typeof window>`u`?null:A(window.location.search)),[_n,vn]=(0,G.useState)(0),[yn,bn]=(0,G.useState)(void 0),[xn,Sn]=(0,G.useState)(null),[wn,Dn]=(0,G.useState)(null),[On,kn]=(0,G.useState)(null),[jn,Mn]=(0,G.useState)(null),[Nn,Pn]=(0,G.useState)(!1),[Rn,zn]=(0,G.useState)(``),[Bn,Vn]=(0,G.useState)(null),[Hn,Un]=(0,G.useState)(null),[Gn,Kn]=(0,G.useState)(null),[qn,Jn]=(0,G.useState)(null),[Yn,Xn]=(0,G.useState)(null),[Zn,Qn]=(0,G.useState)(null),$n=Bn?Bn.kind===`agent`?`agent:${Bn.agentId}`:`project:${Bn.projectId}`:``,[er,q]=(0,G.useState)(Date.now()),tr=(0,G.useRef)(null),nr=(0,G.useRef)(null),rr=(0,G.useRef)([]),ir=(0,G.useRef)(null),ar=(0,G.useRef)(null),or=(0,G.useRef)(null),sr=(0,G.useRef)(null),cr=(0,G.useRef)(null),lr=(0,G.useRef)(null),ur=(0,G.useRef)(null),dr=(0,G.useRef)(null),fr=(0,G.useRef)(null),pr=(0,G.useRef)(null),mr=(0,G.useRef)(null),hr=(0,G.useRef)(null),gr=(0,G.useRef)(null),_r=(0,G.useRef)(!1),vr=(0,G.useRef)(0),yr=(0,G.useRef)(null),br=(0,G.useRef)(0),xr=(0,G.useRef)(!1),Sr=(0,G.useRef)(()=>{}),Cr=(0,G.useRef)(c),wr=(0,G.useRef)(0),Tr=(0,G.useRef)(0),Er=(0,G.useRef)(0),Dr=(0,G.useRef)(0),Or=(0,G.useRef)(0),kr=(0,G.useRef)(0),Ar=(0,G.useRef)(null),jr=(0,G.useRef)(null),Mr=(0,G.useRef)(null),Nr=(0,G.useRef)(0),Pr=(0,G.useRef)(new Set),Fr=(0,G.useRef)(!1),Ir=(0,G.useRef)(pn),Lr=(0,G.useRef)(hF()),Rr=(0,G.useCallback)(()=>{Ir.current=!1,mn(!0)},[]),zr=(0,G.useCallback)(()=>{mn(e=>(e||(Ir.current=!0),!0))},[]),Br=(0,G.useCallback)(()=>{Ir.current=!1,mn(!1)},[]),Vr=(0,G.useCallback)(()=>{Ir.current=!1,mn(e=>!e)},[]);Cr.current=c;let J=(0,G.useMemo)(()=>KN(b.language),[b.language]);(0,G.useEffect)(()=>{ZO({promotedKeys:[],pinnedOverrides:en,archivedOverrides:{}})},[en]);let Hr=(0,G.useMemo)(()=>e.filter(e=>!e.isMain),[e]),Ur=(0,G.useMemo)(()=>e.find(e=>e.isMain)??null,[e]),Y=(0,G.useMemo)(()=>Hr.filter(wP),[Hr]),Wr=(0,G.useMemo)(()=>{let e=new Set(Y.map(e=>e.id));return Ur&&e.add(Ur.id),e},[Y,Ur]),Gr=(0,G.useMemo)(()=>{let e=new Set([Be]);return Ue.forEach(t=>e.add(Fn(t))),Y.forEach(t=>e.add(Fn(ZE(t)))),Wr.forEach(t=>e.add(t)),e},[Y,Ue,Wr]);(0,G.useEffect)(()=>{Ae(e=>e.kind===`agent`?Wr.has(e.agentId):Gr.has(e.agentId))},[Ae,Wr,Gr]);let Kr=(0,G.useCallback)((e,t)=>{let n=Ur?[...Y,Ur]:Y;if(Le(e)){let e=n.find(e=>e.id===t);return{filesId:Be,workspaceRoot:`/`,sourceAgentId:e?.id,sourceAgent:e}}let r=In(e);if(r){let e=Y.find(e=>e.id===t&&Fn(ZE(e))===Fn(r));return{filesId:Fn(r),workspaceRoot:r,sourceAgentId:e?.id,sourceAgent:e}}let i=n.find(t=>t.id===e);if(i&&!i.isMain){let e=ZE(i),n=Y.find(n=>n.id===t&&Fn(ZE(n))===Fn(e))??i;return{filesId:Fn(e),workspaceRoot:e,sourceAgentId:n.id,sourceAgent:n}}return{filesId:e,workspaceRoot:i?ZE(i):void 0,sourceAgentId:i?.id,sourceAgent:i}},[Y,Ur]);(0,G.useEffect)(()=>{W?.sourceAgentId&&(Kr(W.agentId,W.sourceAgentId).sourceAgentId||Ce.update({...W,sourceAgentId:void 0}))},[W,Kr,Ce]);let qr=(0,G.useMemo)(()=>$O(Ft,en,{}),[en,Ft]),Jr=(0,G.useMemo)(()=>PP({allAgents:Hr,liveAgents:Y,sessions:qr,mainPageSessionKeys:ot}),[Y,qr,ot,Hr]),Yr=Jr.mainPageAgentSessions,Xr=Jr.sidebarAgentSessions,Zr=Jr.searchableAgentSessions,Qr=Jr.historyAgentSessions,$r=Jr.liveAgents,ei=Jr.archivedAgents,ti=t,ni=Qr,ri=(0,G.useMemo)(()=>new Set(Gt.map(aD)),[Gt]),ii=(0,G.useMemo)(()=>new Set(Array.from(Jr.claimedAgentSessionKeyByAgentId.entries()).filter(([,e])=>ri.has(e)).map(([e])=>e)),[Jr.claimedAgentSessionKeyByAgentId,ri]),ai=(0,G.useMemo)(()=>{let e=new Map(Zr.map(e=>[aD(e),e]));return Gt.forEach(t=>e.set(aD(t),t)),MP(Array.from(e.values()),Jr.claimedAgentSessionKeys)},[Jr.claimedAgentSessionKeys,Gt,Zr]),oi=(0,G.useMemo)(()=>Gj($r,Xr,nt,je,Hr,Ue,Xe),[je,Xe,nt,Ue,Xr,Hr,$r]),si=(0,G.useMemo)(()=>rk(oi,ln,!1),[ln,oi]),ci=(0,G.useMemo)(()=>Gj($r,ai,nt,je,Hr,Ue,Xe),[je,Xe,nt,Ue,ai,Hr,$r]),li=Fe.trim().toLowerCase(),ui=li.length>0,di=(0,G.useMemo)(()=>Kj((i===`search`||Ne)&&ui?ci:si,li,ln,ri,ii),[i,ln,ui,li,si,ci,ii,ri,Ne]),fi=si.some(e=>!!e.workspace),pi=(0,G.useMemo)(()=>ui?di:[],[di,ui]),mi=(0,G.useMemo)(()=>qj(di,sn,li),[sn,di,li]),hi=(0,G.useMemo)(()=>ui?mi:[],[ui,mi]),gi=(0,G.useMemo)(()=>{let e=new Map;return y&&v.forEach((t,n)=>{e.set(t,n)}),e},[v,y]),_i=(0,G.useMemo)(()=>g.map(e=>Y.find(t=>t.id===e)??(Ur?.id===e?Ur:null)).filter(e=>!!e),[Y,Ur,g]),vi=Ot((0,G.useMemo)(()=>_i.find(e=>e.id===c)??_i[0]??null,[c,_i])),yi=vi?[vi]:[],X=Ot((0,G.useMemo)(()=>Y.find(e=>e.id===c)??(Ur?.id===c?Ur:null),[Y,c,Ur])),bi=Cn(X)?X.runtimeBinding:null,xi=Tn(X)?X.runtimeBinding:null,Si=!!(X&&X.id===l),Ci=!!(X&&yt.has(X.id)),wi=X?s[X.id]??null:null,Ti=bi?ZA(X):X?CA(X):``,Ei=(0,G.useMemo)(()=>Pk(X),[X]),Di=Ti?pe[Ti]??(X?(bi?QA(X):wA(X)).map(e=>pe[e]).find(Boolean):void 0)??hA:hA,Oi=Di.draft,ki=Di.attachments,Ai=Di.mode,{plusMenuOpen:ji,approvalMenuOpen:Mi,modelMenuOpen:Ni,modelPickerPane:Pi}=Di.ui,Fi=!!(bi&&X&&ge.current[X.id]!==void 0),Ii=(0,G.useMemo)(()=>Fi||WE(X),[Fi,X]),Li=(0,G.useMemo)(()=>HE(X),[X]),Ri=Ei.kind,zi=(0,G.useMemo)(()=>cP(!!(X&&Ri===`codex`),X?.launchPermissionMode,ct),[X,ct,Ri]),Bi=(0,G.useMemo)(()=>lP(!!(X&&Ri===`claude`),X?.launchPermissionMode,wt),[X,wt,Ri]),Vi=X&&xt.get(X.id)||null,Hi=(0,G.useMemo)(()=>SP(Vi||X?.codexTerminalProfile,{model:dt,reasoningEffort:pt,serviceTier:ht}),[Vi?.model,Vi?.reasoningEffort,Vi?.serviceTier,X?.codexTerminalProfile?.model,X?.codexTerminalProfile?.reasoningEffort,X?.codexTerminalProfile?.serviceTier,dt,pt,ht]),Ui=Hi.model,Wi=Hi.reasoningEffort,Gi=Hi.serviceTier,Ki=`${Ui}:${Wi}`,qi=(0,G.useMemo)(()=>Ii||!!X&&X?.status===`running`&&Ri===`shell`&&Li.terminalBusy,[X,Li.terminalBusy,Ii,Ri]),Z=(0,G.useMemo)(()=>Nk([...Mk(Ri),...Nt]),[Ri,Nt]),Ji=Di.pendingFollowUp;(0,G.useEffect)(()=>{!c||ve!==`terminal`||i!==`projects`||Ee(c)},[c,i,ve,Ee]),(0,G.useEffect)(()=>{!W||ve!==`editor`||i!==`projects`||De({agentId:W.agentId,filePath:W.file.path,view:W.diffRequestId?`diff`:`editor`,lineNumber:W.cursor?.lineNumber,column:W.cursor?.column,endColumn:W.cursor?.endColumn,sourceAgentId:W.sourceAgentId})},[i,ve,W?.agentId,W?.cursor?.column,W?.cursor?.endColumn,W?.cursor?.lineNumber,W?.cursor?.requestId,W?.diffRequestId,W?.file.path,W?.sourceAgentId,De]);let Yi=LA(ki).length>0,Xi=ki.some(e=>e.status===`uploading`),Zi=Ci?`disabled`:X&&!Xi&&(Oi.trim()||Yi)?`send`:qi?`interrupt`:`disabled`,Qi=bi?Zi:`disabled`,$i=(0,G.useCallback)(e=>{Ti&&me(Ti,e)},[Ti,me]),ea=(0,G.useCallback)(()=>{$i(yA)},[$i]),ta=(0,G.useMemo)(()=>Y.find(e=>e.id===xn?.agentId)??null,[Y,xn?.agentId]),na=(0,G.useMemo)(()=>oi.find(e=>e.id===wn?.projectId)??null,[oi,wn?.projectId]),ra=(0,G.useMemo)(()=>di.flatMap(e=>e.agentSessions).find(e=>e.provider===On?.provider&&aD(e)===On?.sessionId)??null,[On?.provider,On?.sessionId,di]),ia=Ne?hi[ze]??null:null,aa=ia?.kind===`agent`?ia.id:null,oa=ia?.kind===`agent-session`?aD(ia):null,sa=X?ZE(X):void 0,ca=(0,G.useMemo)(()=>{if(W&&!Le(W.agentId))return W.agentId;if(X&&!X.isMain)return Fn(ZE(X));if(sa)return Fn(sa);let e=Y.find(e=>!e.isMain);return e?Fn(ZE(e)):null},[X,Y,sa,W]),la=(0,G.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 Fn(ZE(e))}let n=e.closest(`[data-testid="code-project-group"]`)?.querySelector(`[data-testid="code-project-title"][data-project-id]`)?.dataset.projectId;return!n||n===`__farming_main_agent__`?null:Fn(n)},[Y]),ua=X?.isMain?yn??si[0]?.workspace:sa??yn??si[0]?.workspace,da=ve===`editor`&&!!W,fa=(0,G.useMemo)(()=>{if(da&&W){let e=W.workspaceRoot??Y.find(e=>e.id===W.agentId)?.projectWorkspace??Y.find(e=>e.id===W.agentId)?.cwd??``;return{kind:`file`,agentId:W.agentId,filePath:W.file.path,...e?{absolutePath:w(e,W.file.path)}:{},...e?{projectLabel:P(e)}:{},view:W.diffRequestId?`diff`:`editor`,lineNumber:W.cursor?.lineNumber,column:W.cursor?.column,endColumn:W.cursor?.endColumn}}return c&&Wr.has(c)?{kind:`agent`,agentId:c,readingSurface:En(Y.find(e=>e.id===c))?`chat`:`terminal`}:null},[c,W?.agentId,W?.cursor?.column,W?.cursor?.endColumn,W?.cursor?.lineNumber,W?.diffRequestId,W?.file.path,W?.workspaceRoot,da,Y,Wr]),{agentModelOptions:pa,agentModel:ma,agentReasoningEffort:ha,agentServiceTier:ga,agentModelPreset:_a,currentReasoningOptions:va,currentServiceTierOptions:ya,currentPermissionMode:ba,currentPermissionLabel:xa,currentPermissionColor:Sa,currentModelLabel:Ca,currentReasoningLabel:wa,currentSpeedLabel:Ta,permissionModeOptions:Ea}=(0,G.useMemo)(()=>CP({agentKind:Ri,codexModel:Ui,codexReasoningEffort:Wi,codexServiceTier:Gi,codexModelPreset:Ki,codexModelOptions:_t,codexApprovalMode:zi,claudeModel:Et,claudeEffort:kt,claudeSettings:jt,claudePermissionMode:Bi}),[kt,Et,jt,Bi,zi,Ui,_t,Ki,Wi,Gi,Ri]),Da=BP(),Oa=Ne||i===`search`?J.search:i===`history`?J.history:da&&W?XE(W.file.path):X?ee(X):J.codex,ka=X?.isMain?`farming`:yF(X?ZE(X):void 0),Aa=X?`${ka} · ${Da}`:Da,ja=da&&W?W.sourceAgentId:null,Ma=!!ja,Na=(0,G.useCallback)(()=>{let e=nr.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`},[]),Pa=(0,G.useCallback)(()=>{JN(()=>{document.querySelector(`.code-composer-menu`)||(nr.current??document.querySelector(`[data-testid="code-composer-input"]`))?.focus({preventScroll:!0})},{delays:[60]})},[]),Fa=(0,G.useCallback)(e=>{let t=xP(e);lt(t.codexApprovalMode),ft(t.codexModel),mt(t.codexReasoningEffort),gt(t.codexServiceTier),ut(t.codexModelPreset),Tt(t.claudePermissionMode),Dt(t.claudeModel),At(t.claudeEffort)},[]),Ia=(0,G.useCallback)(()=>{let e=!1,t=Nr.current;return fetch(r(`/api/settings`)).then(e=>e.json()).then(n=>{if(e)return;let r=n.settings??{};t===Nr.current&&st(new Set(QO(r.mainPageSessionKeys??[]))),We(Ln(r.projectWorkspaces)),Ze(Ln(r.pinnedProjectWorkspaces)),Ke(!0),rt(HP(r.projectNames)),Fa(r)}).catch(()=>{}),()=>{e=!0}},[Fa]),La=(0,G.useCallback)(()=>{let e=Date.now()-br.current;if(xr.current||br.current>0&&e<=XP)return()=>{};let t=!1;return xr.current=!0,fetch(r(`/api/codex/models`)).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error||`Failed to load Codex model catalog (${e.status})`);return t}).then(e=>{if(t)return;let n=iD(e);if(n.length===0)throw Error(`Codex model catalog did not contain any visible models`);br.current=Date.now(),vt(n)}).catch(e=>{t||(br.current=0,vt([]),Jn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:`Failed to load Codex model catalog`}))}).finally(()=>{xr.current=!1}),()=>{t=!0}},[]),Ra=(0,G.useCallback)(()=>{let e=!1;return fetch(r(`/api/claude/settings`)).then(e=>e.json()).then(t=>{e||Mt(hP(t.settings))}).catch(()=>{e||Mt(aP)}),()=>{e=!0}},[]),za=(0,G.useCallback)(async(e,t)=>{let n=new URLSearchParams({q:e,limit:String(aF),fresh:`1`}),i=await fetch(r(`/api/agent-sessions/search?${n.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:[]},[]),Ba=(0,G.useCallback)(async(e,t)=>NP($O(await za(e,t),en,{}),ot,Jr.claimedAgentSessionKeys),[Jr.claimedAgentSessionKeys,en,za,ot]),Va=(0,G.useCallback)(async(e={})=>{let t=new URLSearchParams({limit:String(e.limit||iF)});e.cursor&&t.set(`cursor`,e.cursor),e.fresh&&t.set(`fresh`,`1`);let n=await(await fetch(r(`/api/agent-sessions?${t.toString()}`),{cache:e.fresh?`no-store`:`default`})).json();return{sessions:Array.isArray(n.sessions)?n.sessions:[],nextCursor:typeof n.nextCursor==`string`?n.nextCursor:``,hasMore:n.hasMore===!0}},[]),Ha=(0,G.useCallback)((e=!1)=>{let t=!1;return Va({fresh:e}).then(e=>{t||(Lt(e.sessions),Vt(e.nextCursor),Wt(e.hasMore),Qt.current=Math.max(iF,e.sessions.length))}).catch(()=>{t||(Lt([]),Vt(``),Wt(!1))}),()=>{t=!0}},[Va]),Ua=(0,G.useCallback)(()=>{if(Zt.current)return Zt.current;let e=Va({limit:Qt.current,fresh:!0}).then(e=>{Lt(e.sessions),Vt(e.nextCursor),Wt(e.hasMore)}).catch(()=>Lt([])).finally(()=>{Zt.current===e&&(Zt.current=null)});return Zt.current=e,e},[Va]),Wa=(0,G.useCallback)(async()=>{if(!Ut||!Bt||Xt.current)return!1;Xt.current=!0;try{let e=await Va({cursor:Bt});return Lt(t=>{let n=new Set(t.map(aD)),r=[...t];return e.sessions.forEach(e=>{let t=aD(e);n.has(t)||(n.add(t),r.push(e))}),Qt.current=Math.max(iF,r.length),r}),Vt(e.nextCursor),Wt(e.hasMore),e.sessions.length>0}catch{return!1}finally{Xt.current=!1}},[Bt,Ut,Va]);(0,G.useEffect)(()=>{if(!((i===`search`||Ne)&&ui)){Kt([]),Yt(!1);return}let e=new AbortController;Kt([]),Yt(!0);let t=window.setTimeout(()=>{za(li,e.signal).then(Kt).catch(e=>{e instanceof DOMException&&e.name===`AbortError`||Kt([])}).finally(()=>{e.signal.aborted||Yt(!1)})},oF);return()=>{window.clearTimeout(t),e.abort()}},[i,za,ui,li,Ne]);let Ga=(0,G.useCallback)((e,t)=>{if(e!==`codex`&&e!==`claude`)return Pt([]),()=>{};let n=!1,i=new URLSearchParams({provider:e});return t&&i.set(`workspace`,t),fetch(r(`/api/slash-commands?${i.toString()}`)).then(e=>e.json()).then(e=>{n||Pt(Array.isArray(e.commands)?e.commands:[])}).catch(()=>{n||Pt([])}),()=>{n=!0}},[]),Ka=(0,G.useCallback)(()=>{Ti&&($i(e=>({...e,ui:{...e.ui,plusMenuOpen:!1}})),ir.current?.click())},[Ti,$i]),qa=(0,G.useCallback)((e,t)=>{let n=PA(t),r=AA(t,`pasted image`),i=FA(t),a={id:n,kind:`image`,name:r,type:t.type||`image/png`,size:t.size,status:`uploading`,previewUrl:i};me(e,e=>({...e,attachments:[...e.attachments,a]})),HA(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:NA({...t,name:r}),error:void 0}:e)}))}).catch(()=>{he(e,e=>({...e,attachments:e.attachments.map(e=>e.id===n?{...e,status:`error`,messageBlock:WA(t),error:`Upload failed`}:e)}))})},[me,he]),Ja=(0,G.useCallback)(async e=>{if(!Ti||e.length===0)return;e.filter(jA).forEach(e=>qa(Ti,e));let t=e.filter(e=>!jA(e));if(t.length===0){Pa();return}let n=[];for(let e of t)try{n.push(await UA(e))}catch{n.push(WA(e))}me(Ti,e=>({...e,draft:kA(e.draft,n.join(`
|
|
204
|
+
`)).trimEnd()}function BA(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 VA(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 HA(e){let t=await fetch(OA(`/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 UA(e){if(jA(e))return NA(await HA(e));try{return MA(e,await VA(e))}catch{return`Attached file: ${AA(e)}\n\n[Unable to read this file as text]`}}function WA(e){return jA(e)?`Attached image: ${AA(e,`pasted image`)}\n\n[Unable to upload this image]`:`Attached file: ${AA(e)}\n\n[Unable to read this file as text]`}function GA(e){if(!e)return[];let t=Array.from(e.files??[]).filter(jA);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&&jA(e)))}function KA(e,t){return e===`default`?t:`${EA[e]}\n\n${t}`}function qA({agent:e,composerKey:t,draft:n,attachments:r,composerMode:i,turnActive:a,sendMessage:o,updateComposerState:s}){let c=BA(r),l=KA(i,zA(n,r).trim());return!l&&c.length===0||!e||e.runtimeBinding.kind!==`acp`||!t||!a&&!o(e,l,c)?!1:(s(t,e=>({...e,draft:``,attachments:[],mode:`default`,history:dA(e.history,n),...a?{pendingFollowUp:{messages:[...e.pendingFollowUp?.messages||[],_A(l,c)],createdAt:e.pendingFollowUp?.createdAt||Date.now()}}:{}})),r.forEach(IA),!0)}function JA(e,t,n,i=!1){return fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-permission`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:t,optionId:n,cancelled:i})})}function YA(e,t,n,i){return fetch(r(`/api/agents/${encodeURIComponent(e)}/acp-elicitation`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:t,action:n,content:i})})}var XA=`acp:`;function ZA(e){let t=CA(e);return t?`${XA}${t}`:``}function QA(e){return wA(e).map(e=>`${XA}${e}`)}function $A(e){return e.startsWith(XA)}function ej(){return typeof window>`u`?!1:navigator.standalone===!0||window.matchMedia(`(display-mode: standalone)`).matches}function tj(){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 nj(){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 rj(){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 ij({copy:e,title:t,url:n,onClose:r}){let i=ej(),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(!1);(0,G.useEffect)(()=>{let e=e=>{e.key===`Escape`&&r()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[r]),(0,G.useEffect)(()=>{if(!a&&!s)return;let e=window.setTimeout(()=>{o(!1),c(!1)},1800);return()=>window.clearTimeout(e)},[a,s]);let l=(0,G.useCallback)(async()=>{let e=await F(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)(rj,{}),(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)(tj,{})}),(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)(nj,{})})}),(0,K.jsxs)(`span`,{children:[e.mobileInstallAddStep,(0,K.jsx)(`small`,{children:e.mobileInstallOpenStep})]})]})]})]})]})]})})}function aj(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 oj({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,onToggleProjectPinned:O,onRevealProject:k,onCreatePermanentWorktree:A,onMarkProjectRead:j,onArchiveProject:M,onRemoveProject:N,onDeleteWorktree:P,onCloseRenameDialog:F,onRenameDialogTitleChange:ee,onSubmitRenameDialog:I,onCloseKillDialog:te,onSubmitKillDialog:L,onCloseDeleteWorktreeDialog:R,onSubmitDeleteWorktreeDialog:ne,copy:z}){let B=Pk(e),re=Fk(n),ie=Ik(n),ae=!!n?.agents.some(e=>e.unread),V=aj([{type:`item`,id:`pin-agent`,label:e?.pinned?z.unpinAgent:z.pinAgent,hidden:!B.actions.pin,onSelect:()=>v({pinned:!e?.pinned})},{type:`item`,id:`rename-agent`,label:z.renameAgent,hidden:!B.actions.rename,onSelect:y},{type:`item`,id:`archive-agent`,label:z.archiveAgent,hidden:!B.actions.archive,onSelect:()=>v({archived:!0})},{type:`item`,id:`toggle-agent-unread`,label:e?.unread?z.markAsRead:z.markAsUnread,hidden:!B.actions.markUnread,onSelect:()=>v({unread:!e?.unread})},{type:`separator`,id:`agent-copy-separator`},{type:`item`,id:`copy-agent-working-directory`,label:z.copyWorkingDirectory,hidden:!B.actions.copyWorkingDirectory,onSelect:x},{type:`separator`,id:`agent-fork-separator`},{type:`item`,id:`fork-same-worktree`,label:z.forkSameWorktree,hidden:!B.actions.forkSameWorktree,onSelect:()=>S(`same-worktree`)},{type:`item`,id:`fork-new-worktree`,label:z.forkNewWorktree,hidden:!B.actions.forkNewWorktree,onSelect:()=>S(`new-worktree`)},{type:`item`,id:`kill-agent`,label:z.killAgent,danger:!0,hidden:!B.actions.kill,onSelect:C}]),oe=aj([{type:`item`,id:`open-session`,label:z.openSession,onSelect:()=>{t&&w(t.provider,t.id)}},{type:`item`,id:`toggle-session-pinned`,label:t?.pinned?z.unpinChat:z.pinChat,onSelect:T},{type:`item`,id:`archive-session`,label:z.archiveChat,onSelect:E},{type:`item`,id:`copy-session-working-directory`,label:z.copyWorkingDirectory,onSelect:D}]),se=aj([{type:`item`,id:`pin-project`,label:n?.pinned?z.unpinProject:z.pinProject,icon:`pin`,hidden:!n?.workspace,onSelect:O},{type:`item`,id:`reveal-project`,label:z.revealInFinder,icon:`folder`,hidden:!n?.workspace||n.hasMain,onSelect:k},{type:`item`,id:`create-permanent-worktree`,label:z.createPermanentWorktree,icon:`worktree`,hidden:!n?.workspace||n.hasMain,onSelect:A},{type:`separator`,id:`project-primary-separator`},{type:`item`,id:`rename-project`,label:z.renameProject,icon:`rename`,hidden:!n?.workspace,onSelect:b},{type:`item`,id:`mark-project-read`,label:z.markAllAsRead,icon:`check`,disabled:!ae,onSelect:j},{type:`item`,id:`archive-project`,label:z.archiveChats,icon:`archive`,disabled:!re,onSelect:M},{type:`separator`,id:`project-destructive-separator`},{type:`item`,id:`remove-project`,label:z.removeProject,removeIcon:!0,hidden:!n?.workspace||n.hasMain,disabled:!!(n&&(n.agents.length>0||n.agentSessions.length>0||n.hasOpenFile)),onSelect:N},{type:`item`,id:`delete-worktree`,label:z.deleteWorktree,icon:`trash`,danger:!0,hidden:!ie,onSelect:P}]);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)(sj,{entries:V})}),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)(sj,{entries:oe})}),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)(sj,{entries:se})}),o&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-rename-backdrop`,onMouseDown:F,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=>uj(e,d.current),onKeyDown:e=>uj(e,d.current),onSubmit:e=>{e.preventDefault(),I()},children:[(0,K.jsx)(`label`,{id:`code-rename-title`,htmlFor:`code-rename-input`,children:o.kind===`project`?z.renameProject:z.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(),F())}}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:F,children:z.cancel}),(0,K.jsx)(`button`,{type:`submit`,className:`primary`,disabled:!o.title.trim(),children:z.save})]})]})}),s&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-kill-backdrop`,onMouseDown:te,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=>uj(e,p.current),onKeyDown:e=>uj(e,p.current),children:[(0,K.jsx)(`h2`,{id:`code-kill-title`,children:z.killAgentQuestion}),(0,K.jsx)(`p`,{children:z.stopAgentDescription(s.title)}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,ref:m,onClick:te,autoFocus:!0,children:z.cancel}),(0,K.jsx)(`button`,{type:`button`,className:`danger`,onClick:L,children:z.killAgent})]})]})}),c&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-delete-worktree-backdrop`,onMouseDown:R,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=>uj(e,h.current),onKeyDown:e=>uj(e,h.current),children:[(0,K.jsx)(`h2`,{id:`code-delete-worktree-title`,children:z.deleteWorktreeQuestion}),(0,K.jsx)(`p`,{children:z.deleteWorktreeDescription}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,ref:g,onClick:R,autoFocus:!0,children:z.cancel}),(0,K.jsx)(`button`,{type:`button`,className:`danger`,onClick:ne,children:z.forceDelete})]})]})}),l&&(0,K.jsx)(`div`,{className:`code-copy-toast ${l.kind}`,"data-testid":`code-copy-toast`,role:`status`,children:l.message})]})}function sj({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||e.removeIcon)&&(0,K.jsx)(`span`,{className:`code-context-menu-icon`,"aria-hidden":`true`,children:e.removeIcon?(0,K.jsx)(cj,{}):(0,K.jsx)(lj,{kind:e.icon})}),(0,K.jsx)(`span`,{children:e.label})]},e.id))})}function cj(){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.354 3.646a.5.5 0 0 0-.708.708L7.293 8l-3.647 3.646a.5.5 0 0 0 .708.708L8 8.707l3.646 3.647a.5.5 0 0 0 .708-.708L8.707 8l3.647-3.646a.5.5 0 0 0-.708-.708L8 7.293 4.354 3.646Z`})})}function lj({kind:e}){return e===`pin`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M13.5 3C13.303 3 13.109 3.038 12.923 3.114L8.481 4.967L5.659 4.026C5.505 3.976 5.339 4.001 5.209 4.095C5.078 4.189 5.001 4.339 5.001 4.5V7H1.257L0.5 7.5L1.257 8H5V10.5C5 10.661 5.077 10.812 5.208 10.905C5.338 11 5.504 11.023 5.658 10.974L8.48 10.033L12.925 11.887C13.109 11.962 13.302 12 13.499 12C14.326 12 14.999 11.327 14.999 10.5V4.5C14.999 3.673 14.326 3 13.499 3H13.5ZM14 10.5C14 10.843 13.615 11.09 13.308 10.962L8.693 9.038C8.631 9.013 8.566 9 8.501 9C8.447 9 8.395 9.009 8.343 9.025L6.001 9.806V5.193L8.343 5.974C8.457 6.011 8.581 6.007 8.694 5.961L13.306 4.038C13.629 3.902 14.001 4.156 14.001 4.499V10.499L14 10.5Z`})}):e===`folder`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M2 4.5V9.10022L2.92389 7.5C3.45979 6.5718 4.45017 6 5.52196 6L11.9146 6C11.7087 5.4174 11.1531 5 10.5 5H7C6.86739 5 6.74021 4.94732 6.64645 4.85355L4.93934 3.14645C4.84557 3.05268 4.71839 3 4.58579 3H3.5C2.67157 3 2 3.67157 2 4.5ZM7.06895 13.9953C7.04641 13.9984 7.02339 14 7 14H3.5C2.11929 14 1 12.8807 1 11.5V4.5C1 3.11929 2.11929 2 3.5 2H4.58579C4.98361 2 5.36514 2.15804 5.64645 2.43934L7.20711 4H10.5C11.724 4 12.7426 4.87965 12.958 6.04127C14.605 6.34148 15.5443 8.22106 14.6616 9.75L13.0766 12.4953C12.5407 13.4235 11.5503 13.9953 10.4785 13.9953H7.06895ZM5.52196 7C4.80743 7 4.14718 7.3812 3.78991 8L2.20492 10.7453C1.62757 11.7453 2.34926 12.9953 3.50396 12.9953L10.4785 12.9953C11.193 12.9953 11.8533 12.6141 12.2105 11.9953L13.7955 9.25C14.3729 8.25 13.6512 7 12.4965 7L5.52196 7Z`})}):e===`worktree`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M14 5.5C14 4.121 12.879 3 11.5 3C10.121 3 9 4.121 9 5.5C9 6.682 9.826 7.669 10.93 7.928C10.744 8.546 10.177 9 9.5 9H6.5C5.935 9 5.419 9.195 5 9.512V4.949C6.14 4.717 7 3.707 7 2.5C7 1.121 5.879 0 4.5 0C3.121 0 2 1.121 2 2.5C2 3.708 2.86 4.717 4 4.949V11.05C2.86 11.282 2 12.292 2 13.499C2 14.878 3.121 15.999 4.5 15.999C5.879 15.999 7 14.878 7 13.499C7 12.317 6.174 11.33 5.07 11.071C5.256 10.453 5.823 9.999 6.5 9.999H9.5C10.723 9.999 11.74 9.115 11.954 7.953C13.116 7.738 14 6.723 14 5.5ZM3 2.5C3 1.673 3.673 1 4.5 1C5.327 1 6 1.673 6 2.5C6 3.327 5.327 4 4.5 4C3.673 4 3 3.327 3 2.5ZM6 13.5C6 14.327 5.327 15 4.5 15C3.673 15 3 14.327 3 13.5C3 12.673 3.673 12 4.5 12C5.327 12 6 12.673 6 13.5ZM11.5 7C10.673 7 10 6.327 10 5.5C10 4.673 10.673 4 11.5 4C12.327 4 13 4.673 13 5.5C13 6.327 12.327 7 11.5 7Z`})}):e===`check`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M13.6572 3.13573C13.8583 2.9465 14.175 2.95614 14.3643 3.15722C14.5535 3.35831 14.5438 3.675 14.3428 3.86425L5.84277 11.8642C5.64597 12.0494 5.33756 12.0446 5.14648 11.8535L1.64648 8.35351C1.45121 8.15824 1.45121 7.84174 1.64648 7.64647C1.84174 7.45121 2.15825 7.45121 2.35351 7.64647L5.50976 10.8027L13.6572 3.13573Z`})}):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`})}):e===`trash`?(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.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`})}):(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 uj(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 dj=o();function fj({canInstall:e,canFullscreen:t,fullscreenActive:n,copy:i,onClose:a,onInstall:o,onToggleFullscreen:s}){let c=(0,G.useRef)(null);return(0,G.useEffect)(()=>{let e=document.activeElement instanceof HTMLElement?document.activeElement:null;c.current?.focus({preventScroll:!0});let t=e=>{e.key===`Escape`&&a()};return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t),e?.focus({preventScroll:!0})}},[a]),(0,dj.createPortal)((0,K.jsx)(`div`,{className:`code-app-mode-backdrop`,"data-testid":`code-app-mode-dialog`,role:`presentation`,onPointerDown:a,children:(0,K.jsxs)(`section`,{className:`code-app-mode-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-app-mode-title`,onPointerDown:e=>e.stopPropagation(),children:[(0,K.jsx)(`button`,{ref:c,type:`button`,className:`code-app-mode-close`,"aria-label":i.cancel,onClick:a,children:`×`}),(0,K.jsxs)(`header`,{className:`code-app-mode-heading`,children:[(0,K.jsx)(`img`,{src:r(`/farming-2/app-icon-v2-180.png`),alt:``,"aria-hidden":`true`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h2`,{id:`code-app-mode-title`,children:i.appModeTitle}),(0,K.jsx)(`p`,{children:i.appModeDescription})]})]}),(0,K.jsxs)(`section`,{className:`code-app-mode-choice recommended`,children:[(0,K.jsx)(`span`,{className:`code-app-mode-recommended`,children:i.appModeRecommended}),(0,K.jsx)(`h3`,{children:i.appModeInstallTitle}),(0,K.jsx)(`p`,{children:i.appModeInstallDescription}),e&&(0,K.jsx)(`button`,{type:`button`,className:`code-app-mode-install`,"data-testid":`code-app-mode-install`,onClick:o,children:i.appModeInstallAction}),(0,K.jsxs)(`ol`,{className:`code-app-mode-install-steps`,children:[(0,K.jsx)(`li`,{children:i.appModeInstallStepOne}),(0,K.jsx)(`li`,{children:i.appModeInstallStepTwo})]})]}),t&&(0,K.jsxs)(`section`,{className:`code-app-mode-choice temporary`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:i.appModeFullscreenTitle}),(0,K.jsx)(`p`,{children:i.appModeFullscreenDescription})]}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-app-mode-fullscreen`,onClick:s,children:n?i.exitFocusMode:i.enterFocusMode})]})]})}),document.body)}var pj=`https://github.com/zhuwenzhuang/farming`;function mj({copy:e,version:t,onClose:n,returnFocusRef:i}){let a=(0,G.useRef)(null);return(0,G.useEffect)(()=>{a.current?.focus({preventScroll:!0});let e=e=>{e.key===`Escape`&&n()};return document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`keydown`,e),i.current?.focus({preventScroll:!0})}},[n,i]),(0,dj.createPortal)((0,K.jsx)(`div`,{className:`code-brand-backdrop`,"data-testid":`code-brand-dialog`,role:`presentation`,onPointerDown:n,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:a,type:`button`,className:`code-brand-close`,"aria-label":e.cancel,onClick:n,children:`×`}),(0,K.jsx)(`img`,{className:`code-brand-logo`,src:r(`/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:pj,target:`_blank`,rel:`noreferrer`,children:e.brandGithub})]})}),document.body)}var hj=8,gj=26,_j=11,vj=10;function yj(){return typeof window>`u`?{width:220+hj*2,height:vj+hj*2}:{width:window.innerWidth,height:window.innerHeight}}function bj(e,t=0){return vj+e*gj+t*_j}function xj(e,t,n,r=yj(),i=220){let a=Math.max(hj,r.width-i-hj),o=Math.max(hj,r.height-n-hj);return{x:Math.max(hj,Math.min(e,a)),y:Math.max(hj,Math.min(t,o))}}function Sj(e,t,n=yj(),r=220){let i=e.right+hj,a=e.left-r-hj,o=i+r<=n.width-hj?i:a>=hj?a:xj(i,e.top,t,n,r).x;return{x:o,y:xj(o,e.top,t,n,r).y}}function Cj(e,t,n=yj(),r=220){let i=Math.max(hj,n.width-r-hj),a=Math.max(hj,Math.min(e.right-r,i)),o=e.bottom+6,s=Math.max(hj,n.height-t-hj),c=e.top-t-6;return{x:a,y:o<=s?o:Math.max(hj,Math.min(c,s))}}function wj(e){let t=Lk(e);return bj(t.itemCount,t.separatorCount)}var Tj=140,Ej=264,Dj=340,Oj=4,kj=null;function Aj(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 jj(){return kj||=s(()=>import(`./qrcode-DV-_rjU8.js`).then(e=>Aj(e)),[]),kj}function Mj(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 Nj(e,t){return!!(e&&e.expiresAt>t+1e3)}function Pj(e){return e.split(`-`).map(e=>e.trim()).filter(Boolean)}async function Fj(e){e?.code&&await fetch(r(`/api/share/qr-ticket/${encodeURIComponent(e.code)}`),{method:`DELETE`}).catch(()=>{})}function Ij(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 Lj(e,t,n,r){let i=Math.floor((n-r)/2),a=i+r;return e>=i&&e<a&&t>=i&&t<a}function Rj(e,t){return(e+t)%11==0?`#6d8a63`:(e*3+t)%17==0?`#9b7a35`:`#263327`}function zj(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 Bj({value:e,badgeUrl:t,qrCodeFactory:n}){let r=(0,G.useId)().replace(/:/g,``),i=(0,G.useMemo)(()=>{let t=n(0,`H`);return t.addData(e),t.make(),t},[n,e]),a=i.getModuleCount(),o=a+Oj*2,s=Math.max(7,Math.min(11,Math.floor(a*.26)|1)),c=s+1.4,l=Oj+(a-c)/2,u=Oj+(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)&&(Ij(e,t,a)||Lj(e,t,a,s)||f.push((0,K.jsx)(`rect`,{x:Oj+t+.14,y:Oj+e+.14,width:`0.72`,height:`0.72`,rx:`0.24`,fill:Rj(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,zj(Oj,Oj,`top-left`),zj(Oj+a-7,Oj,`top-right`),zj(Oj,Oj+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 Vj(){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 Hj({copy:e,sidebarCollapsed:t,shareTarget:n}){let[i,a]=(0,G.useState)(!1),[o,s]=(0,G.useState)(!1),[c,l]=(0,G.useState)(null),[u,d]=(0,G.useState)(!1),[f,p]=(0,G.useState)(``),[m,h]=(0,G.useState)(!1),[g,_]=(0,G.useState)(()=>Date.now()),[v,y]=(0,G.useState)({x:0,y:0}),b=(0,G.useRef)(null),x=(0,G.useRef)(null),S=(0,G.useRef)(null),C=(0,G.useRef)(null),w=(0,G.useRef)(null),D=(0,G.useRef)(0),O=(0,G.useRef)(null),k=(0,G.useRef)(null),[A,j]=(0,G.useState)(!0),[M,N]=(0,G.useState)(null),P=r(`/farming-2/app-icon-v2-180.png`),ee=E(n);(0,G.useEffect)(()=>{O.current=c},[c]);let I=(0,G.useCallback)(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null)},[]),te=(0,G.useCallback)(()=>{let e=x.current?.getBoundingClientRect();if(!e)return;let t=e.right+8,n=e.left-Ej-8;y({x:t+Ej+10<=window.innerWidth?t:Math.max(8,n),y:Math.max(8,Math.min(e.top-4,window.innerHeight-Dj-8))})},[]),L=(0,G.useCallback)(()=>{t||jj().then(e=>N(()=>e)).catch(()=>p(e.shareLinkFailed))},[e.shareLinkFailed,t]),R=(0,G.useCallback)(async(t=!1)=>{let i=O.current;if(!t&&Nj(i,Date.now()))return i;let a=D.current+1;D.current=a,d(!0),p(``);try{let t=T(n),i=await fetch(r(`/api/share/qr-ticket`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t?{target:t}:{})}),o=await i.json();if(!i.ok||!(`shortUrl`in o))throw Error(`error`in o&&o.error?o.error:e.shareLinkFailed);return a===D.current?(l(o),_(Date.now()),h(!1),o):(await Fj(o),null)}catch(t){return a===D.current&&p(t instanceof Error?t.message:e.shareLinkFailed),null}finally{a===D.current&&d(!1)}},[e.shareLinkFailed,n,ee]),ne=(0,G.useCallback)(()=>{I(),D.current+=1,a(!1),s(!1),p(``),h(!1),d(!1);let e=O.current;O.current=null,l(null),Fj(e)},[I]),z=(0,G.useCallback)((e,t=!1)=>{I(),te(),a(!0),s(e),L(),R(t)},[I,R,L,te]),B=(0,G.useCallback)(()=>{!i||o||(I(),w.current=window.setTimeout(()=>{w.current=null,ne()},Tj))},[I,ne,i,o]),re=(0,G.useCallback)(()=>{if(i&&o){ne();return}z(!0,!0)},[ne,i,z,o]),ie=(0,G.useCallback)(async()=>{let t=Nj(O.current,Date.now())?O.current:await R(!0);if(t){if(!await F(t.longUrl)){p(e.copyFailed);return}h(!0),k.current!==null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{h(!1),k.current=null},1800)}},[e.copyFailed,R]);(0,G.useLayoutEffect)(()=>{if(i)return te(),window.addEventListener(`resize`,te),()=>window.removeEventListener(`resize`,te)},[i,te]),(0,G.useEffect)(()=>{if(!i)return;let e=window.setInterval(()=>_(Date.now()),1e3);return()=>window.clearInterval(e)},[i]),(0,G.useEffect)(()=>{let e=O.current;e&&(O.current=null,l(null),h(!1),Fj(e))},[ee]),(0,G.useLayoutEffect)(()=>{if(!i)return;let e=()=>{let e=S.current,t=C.current;!e||!t||j(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,G.useEffect)(()=>{if(!i)return;let e=e=>{let t=e.target;t instanceof Node&&b.current?.contains(t)||ne()},t=e=>{e.key===`Escape`&&ne()};return document.addEventListener(`pointerdown`,e,!0),document.addEventListener(`keydown`,t,!0),()=>{document.removeEventListener(`pointerdown`,e,!0),document.removeEventListener(`keydown`,t,!0)}},[ne,i]),(0,G.useEffect)(()=>()=>{I(),k.current!==null&&window.clearTimeout(k.current),D.current+=1,Fj(O.current)},[I]);let ae=!!(c&&c.expiresAt<=g),V=c?Mj(c.expiresAt-g):``,oe=c?.tokenLabel||c?.shortPath||e.copyFullShareLink,se=Pj(oe),ce=A||se.length<=1?[oe]:se;return(0,K.jsxs)(`div`,{ref:b,className:`code-share-root`,onMouseEnter:L,onMouseLeave:B,onFocus:()=>{I(),L()},onBlur:e=>{!e.currentTarget.contains(e.relatedTarget)&&!o&&ne()},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)(Vj,{})}),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:()=>{I()},onMouseLeave:B,onKeyDown:e=>{e.key===`Escape`&&(ne(),x.current?.focus())},children:[(0,K.jsxs)(`div`,{className:`code-share-qr-frame`,"data-expired":ae?`true`:`false`,children:[(0,K.jsx)(`div`,{className:`code-share-qr-canvas`,children:c&&!u&&M?(0,K.jsx)(Bj,{value:c.shortUrl,badgeUrl:P,qrCodeFactory:M}):(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:ae?e.shareLinkExpired:V}),ae&&(0,K.jsx)(`button`,{type:`button`,className:`code-share-refresh`,onClick:()=>void R(!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 ie(),children:[(0,K.jsxs)(`span`,{ref:S,className:`code-share-token ${A?`single-line`:``}`,"aria-label":oe,children:[(0,K.jsx)(`span`,{ref:C,className:`code-share-token-measure`,"aria-hidden":`true`,children:oe}),ce.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 Uj(e,t){return e&&t.some(t=>!t.isMain&&t.id===e)?e:t.find(e=>!e.isMain)?.id??null}function Wj(e){return e&&(e.projectWorkspace||e.cwd)||``}function Gj(e,t,n={},r=[],i=e,a=[],o=[]){let s=pD(e,t),c=new Map(s.map(e=>[e.workspace,e]));r.forEach(e=>{let t=e.sourceAgentId?i.find(t=>t.id===e.sourceAgentId):i.find(t=>t.id===e.agentId),n=e.workspaceRoot||(t?ZE(t):``);if(!n||n===`/`)return;let r=c.get(n);if(r){r.hasOpenFile=!0,!r.gitWorktree&&t?.gitWorktree?.workspace&&(r.gitWorktree=t.gitWorktree);return}let a={id:n,name:QE(n),workspace:n,agents:[],agentSessions:[],hasMain:!1,hasProjectAgent:!1,hasAgentSession:!1,hasOpenFile:!0,gitWorktree:t?.gitWorktree??null};s.push(a),c.set(n,a)}),a.forEach(e=>{if(!e||e===`/`||c.get(e))return;let t={id:e,name:QE(e),workspace:e,agents:[],agentSessions:[],hasMain:!1,hasProjectAgent:!1,hasAgentSession:!1,gitWorktree:null};s.push(t),c.set(e,t)});let l=new Map(o.map((e,t)=>[e,t]));return s.map((e,t)=>{let r=e.workspace?n[e.workspace]?.trim():``,i=r&&!e.hasMain?{...e,name:r}:e,a=l.get(e.workspace);return{project:{...i,pinned:a!==void 0},pinIndex:a,sourceIndex:t}}).sort((e,t)=>e.pinIndex!==void 0&&t.pinIndex!==void 0?e.pinIndex-t.pinIndex:e.pinIndex===void 0?t.pinIndex===void 0?e.sourceIndex-t.sourceIndex:1:-1).map(e=>e.project)}function Kj(e,t,n,r=new Set,i=new Set){return t?rk(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)||C(e).toLowerCase().includes(t)),o=n?e.agentSessions:e.agentSessions.filter(e=>r.has(aD(e))||e.title.toLowerCase().includes(t));return a.length>0||o.length>0||e.workspace&&n?{...e,agents:a,agentSessions:o}:null}).filter(e=>!!e),n,!0):e}function qj(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 Jj=5,Yj=5,Xj=`__project_agent_drop_end__`;function Zj(){return typeof window>`u`?!1:navigator.standalone===!0||window.matchMedia(`(display-mode: standalone)`).matches}function Qj(e){let t=e?.trim().toLowerCase()||``;if(t===`claude-code`)return`claude`;if([`codex`,`claude`,`opencode`,`qoder`,`bash`,`zsh`].includes(t))return t}function $j(e){return Qj(e.providerSessionProvider)||Qj(e.command.trim().split(/\s+/).find(e=>e!==`env`&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(e))?.split(`/`).pop())}function eM(){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 tM(){return(0,K.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,K.jsx)(`circle`,{cx:`4`,cy:`3`,r:`1.5`}),(0,K.jsx)(`circle`,{cx:`4`,cy:`13`,r:`1.5`}),(0,K.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,K.jsx)(`path`,{d:`M4 4.5v7M5.5 8h2.25A4.25 4.25 0 0 0 12 3.75`})]})}function nM(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 rM=(0,G.lazy)(()=>s(()=>import(`./ProjectFilesSection-DE7Nb9Jk.js`).then(e=>({default:e.ProjectFilesSection})),__vite__mapDeps([18,1,5,6,19,20,8,15,16])));function iM({sidebarCollapsed:e,activeView:t,searchOpen:n,displayedProjects:i,collapsedProjectIds:a,normalizedSearch:o,hasProjectListItems:s,hasDisplayedProjectListItems:c,activeTerminalId:l,selectedSearchAgentId:u,selectedSearchSessionHandle:f,claimedAgentSessionKeyByAgentId:p,agentShortcutKeys:m,keyboardShortcutsEnabled:h,now:g,mainAgent:_,usageSummary:v,shareTarget:y,agentLaunchOptions:b,agentCreationWorkspace:x,openWorkspaceFile:S,openWorkspaceFiles:C,fileRevealRequest:w,fileSearchFocusRequest:T,projectListRef:E,canLoadMoreAgentSessions:D,onLoadMoreAgentSessions:O,onNewAgent:k,onStartAgent:A,onToggleSidebar:j,onOpenSearch:M,onOpenWorkspaceView:N,onOpenMainAgent:P,onRestartMainAgent:F,onProjectListKeyDown:ee,onToggleProject:I,onToggleProjectSessions:te,onMountProject:L,onOpenProjectContextMenu:R,onOpenProjectKeyboardMenu:ne,onOpenAgent:z,onUpdateAgentFlags:B,onReorderAgent:re,onOpenAgentContextMenu:ie,onOpenAgentKeyboardMenu:ae,onResumeAgentSession:V,onOpenAgentSessionContextMenu:oe,onOpenAgentSessionKeyboardMenu:se,onOpenProjectFile:ce,onSelectOpenWorkspaceFile:le,onCloseOpenWorkspaceFile:ue,onMoveWorkspaceEntries:de,onDeleteWorkspaceEntries:fe,onRefreshProjectOpenFiles:pe,onOpenOptionsMenu:me,copy:he}){let[H,_e]=(0,G.useState)(null),ve=(0,G.useRef)(null),ye=(0,G.useRef)(!1),xe=(0,G.useRef)(new Map),[Se,Ce]=(0,G.useState)(!0),[Te,Ee]=(0,G.useState)(!1),[De,Oe]=(0,G.useState)(!1),U=(0,G.useRef)(null),ke=(0,G.useCallback)(()=>Oe(!1),[]),[Ae,je]=(0,G.useState)(!1),[Ne,Pe]=(0,G.useState)(!1),[Fe,Ie]=(0,G.useState)(Zj),[Re,ze]=(0,G.useState)(!1),[Ve,He]=(0,G.useState)(null),[Ue,We]=(0,G.useState)(!1),Ge=(0,G.useCallback)(e=>{D&&e.scrollHeight-e.scrollTop-e.clientHeight<=240&&O()},[D,O]),Ke=(0,G.useCallback)(()=>{ve.current!==null&&(window.clearTimeout(ve.current),ve.current=null)},[]),qe=(0,G.useCallback)(()=>{Ke(),_e(null)},[Ke]),Je=(0,G.useCallback)(()=>{ye.current=!1,qe()},[qe]),Ye=(0,G.useCallback)((e,t,n=!1)=>{Ke();let i=e.currentTarget,a=ye.current?0:n?450:1500;ve.current=window.setTimeout(()=>{if(ve.current=null,!i.matches(`:hover`))return;let e=i.getBoundingClientRect(),n=e.right+10,a=Math.min(320,window.innerWidth-n-12);if(a<200)return;let o=Math.max(8,Math.min(e.top-4,window.innerHeight-152)),s=t.workspaceRootId?xe.current.get(t.workspaceRootId):void 0,c=s&&s.expiresAt>Date.now()?s.branch:``;ye.current=!0,_e({...t,x:n,y:o,width:a,branch:c}),!(!t.workspaceRootId||c)&&fetch(r(`/api/files/branch?rootId=${encodeURIComponent(t.workspaceRootId)}`)).then(e=>e.ok?e.json():null).then(e=>{let n=typeof e?.branch==`string`?e.branch.trim():``;xe.current.set(t.workspaceRootId,{branch:n,expiresAt:Date.now()+3e4}),_e(e=>e?.key===t.key?{...e,branch:n}:e)}).catch(()=>{xe.current.set(t.workspaceRootId,{branch:``,expiresAt:Date.now()+3e4})})},a)},[Ke]);(0,G.useEffect)(()=>()=>Ke(),[Ke]),(0,G.useEffect)(()=>{Pe(!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen));let e=()=>{je(!!document.fullscreenElement)};return document.addEventListener(`fullscreenchange`,e),e(),()=>{document.removeEventListener(`fullscreenchange`,e)}},[]),(0,G.useEffect)(()=>{let e=window.matchMedia(`(display-mode: standalone)`),t=()=>{let e=Zj();Ie(e),e&&ze(!1)},n=e=>{e.preventDefault(),He(e)};return e.addEventListener(`change`,t),window.addEventListener(`beforeinstallprompt`,n),t(),()=>{e.removeEventListener(`change`,t),window.removeEventListener(`beforeinstallprompt`,n)}},[]);let Xe=(0,G.useCallback)(()=>{if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}document.documentElement.requestFullscreen({navigationUI:`hide`}).catch(()=>{})},[]),Ze=(0,G.useCallback)(()=>{let e=Ve;e&&e.prompt().then(()=>e.userChoice).then(e=>{He(null),e.outcome===`accepted`&&ze(!1)}).catch(()=>He(null))},[Ve]),Qe=(0,G.useCallback)(()=>{ze(!1),Xe()},[Xe]),$e=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`?dD(t.session)-dD(e.session):0:e.kind===`agent`?-1:1),et=i.filter(e=>e.agents.some(e=>!e.pinned||!e.isMain)||e.agentSessions.some(e=>!e.pinned)||(e.hiddenAgentSessionCount??0)>0||e.hasOpenFile||!!e.workspace),tt=i.flatMap(e=>[...e.agents.filter(e=>!e.isMain).map(t=>({agent:t,projectName:e.name}))]),nt=C.filter(e=>Le(e.agentId)),rt=S&&Le(S.agentId)?S:null,it=w?.agentId===Be,at=nt.length>0||it;(0,G.useEffect)(()=>{at||We(!1)},[at]),(0,G.useEffect)(()=>{it&&We(!1)},[it]);let ot=nM(`2.2.13`),st=ot?`v${ot}`:``,ct=e;return(0,K.jsxs)(`aside`,{className:`code-sidebar ${e?`collapsed`:``}`,"data-testid":`code-sidebar`,onMouseLeave:Je,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=>k(x,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:he.newAgent}),h&&(0,K.jsx)(`kbd`,{children:`N`})]}),(0,K.jsx)(Hj,{copy:he,sidebarCollapsed:e,shareTarget:y}),!Fe&&!e&&(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-focus-toggle ${Ae?`active`:``}`,"data-testid":`code-sidebar-focus-toggle`,"aria-label":he.appModeOpen,title:he.appModeOpen,"aria-haspopup":`dialog`,"aria-expanded":Re,onClick:()=>ze(!0),children:(0,K.jsx)(`span`,{className:`code-sidebar-focus-icon`,children:(0,K.jsx)(eM,{})})}),!e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-search-toggle ${t===`search`||n?`active`:``}`,"data-testid":`code-nav-search`,"aria-label":he.search,title:he.search,"aria-pressed":t===`search`||n,onClick:M,children:(0,K.jsx)(`span`,{className:`code-sidebar-search-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Me,{})})}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-history-toggle ${t===`history`?`active`:``}`,"data-testid":`code-nav-history`,"aria-label":he.history,title:he.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)(xN,{})})})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-toggle`,"data-testid":`code-sidebar-toggle`,"aria-label":e?he.expandSidebar:he.collapseSidebar,title:e?he.expandSidebar:he.collapseSidebar,onClick:j,children:(0,K.jsx)(`span`,{className:`code-sidebar-toggle-icon ${e?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:e?(0,K.jsx)(W,{}):(0,K.jsx)(we,{})})})]})}),e&&tt.length>0&&(0,K.jsx)(eN,{items:tt,activeTerminalId:l,now:g,onOpenAgent:z,onShowPreview:Ye,onHidePreview:qe,copy:he}),(0,K.jsxs)(`div`,{className:`code-project-list`,"data-testid":`code-project-list`,ref:E,tabIndex:0,onKeyDown:ee,onScroll:e=>Ge(e.currentTarget),"aria-label":he.projectsAndAgents,children:[!s&&(0,K.jsx)(`div`,{className:`code-empty-project`,children:he.noAgentsYet}),s&&!c&&(0,K.jsx)(`div`,{className:`code-empty-project`,"data-testid":`code-empty-search`,children:he.noMatchingProjectsOrAgents}),$e.length>0&&(0,K.jsx)(iN,{items:$e,collapsed:Te,compressed:ct,activeTerminalId:l,selectedSearchAgentId:u,selectedSearchSessionHandle:f,claimedAgentSessionKeyByAgentId:p,agentShortcutKeys:m,keyboardShortcutsEnabled:h,now:g,onOpenAgent:z,onUpdateAgentFlags:B,onReorderAgent:re,onOpenAgentContextMenu:ie,onOpenAgentKeyboardMenu:ae,onResumeAgentSession:V,onOpenAgentSessionContextMenu:oe,onOpenAgentSessionKeyboardMenu:se,onShowAgentPreview:Ye,onHideAgentPreview:qe,onToggleCollapsed:()=>Ee(e=>!e),copy:he}),at&&(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":!Ue,onClick:()=>We(e=>!e),children:[(0,K.jsx)(`span`,{className:`code-folder-icon ${Ue?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:Ue?(0,K.jsx)(W,{}):(0,K.jsx)(be,{})}),(0,K.jsx)(`span`,{children:`/`})]})}),!Ue&&(0,K.jsx)(`div`,{className:`code-project-expanded`,children:(0,K.jsx)(G.Suspense,{fallback:null,children:(0,K.jsx)(rM,{projectId:`__farming_global_files_project__`,projectWorkspace:`/`,agentId:`wroot_global`,agentLaunchOptions:[],activeFilePath:rt?.file.path,openFiles:nt.map(e=>({agentId:e.agentId,workspaceRoot:e.workspaceRoot,key:d(e),path:e.file.path,dirty:e.dirty,externalChanged:e.externalChanged})),revealRequest:w?.agentId===`wroot_global`?w:void 0,focusSearchRequest:T?.agentId===`wroot_global`?T:void 0,onOpenFile:ce,onSelectOpenFile:le,onCloseOpenFile:ue,onMoveEntries:de,onDeleteEntries:fe,onRefreshOpenFiles:pe,readOnly:!0,copy:he})})})]}),et.map(e=>(0,K.jsx)(cN,{project:e,collapsed:a.has(e.id)&&!o,forceAgentsExpanded:!!o,compactAgents:ct,activeTerminalId:l,selectedSearchAgentId:u,selectedSearchSessionHandle:f,claimedAgentSessionKeyByAgentId:p,agentShortcutKeys:m,keyboardShortcutsEnabled:h,now:g,openWorkspaceFile:S,openWorkspaceFiles:C,agentLaunchOptions:b,fileRevealRequest:w,fileSearchFocusRequest:T,onToggleProject:I,onToggleProjectSessions:te,onMountProject:L,onNewAgent:k,onStartAgent:A,onOpenProjectContextMenu:R,onOpenProjectKeyboardMenu:ne,onOpenAgent:z,onUpdateAgentFlags:B,onReorderAgent:re,onOpenAgentContextMenu:ie,onOpenAgentKeyboardMenu:ae,onResumeAgentSession:V,onOpenAgentSessionContextMenu:oe,onOpenAgentSessionKeyboardMenu:se,onShowAgentPreview:Ye,onHideAgentPreview:qe,onOpenProjectFile:ce,onSelectOpenWorkspaceFile:le,onCloseOpenWorkspaceFile:ue,onMoveWorkspaceEntries:de,onDeleteWorkspaceEntries:fe,onRefreshProjectOpenFiles:pe,copy:he},e.id))]}),(0,K.jsxs)(`div`,{className:`code-sidebar-footer`,children:[(0,K.jsxs)(`div`,{className:`code-product-row`,children:[(0,K.jsxs)(`button`,{ref:U,type:`button`,className:`code-product-mark`,"data-testid":`code-product-mark`,title:`Farming Code`,"aria-label":`Farming Code`,onClick:()=>Oe(!0),children:[(0,K.jsx)(`img`,{className:`code-product-logo`,src:r(`/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`})]}),st&&(0,K.jsx)(`span`,{className:`code-product-mark-badge`,children:st})]})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-options`,"data-testid":`code-sidebar-options`,"aria-label":he.openSettings,title:he.openSettings,onClick:me,children:(0,K.jsx)(ge,{})})]}),!e&&(0,K.jsx)(AM,{collapsed:Se,mainAgent:_,now:g,usageSummary:v,onToggleCollapsed:()=>Ce(e=>!e),onOpenMainAgent:P,onRestartMainAgent:F})]}),H&&(0,K.jsx)(gN,{preview:H,now:g}),De&&(0,K.jsx)(mj,{copy:he,version:st,onClose:ke,returnFocusRef:U}),Re&&(0,K.jsx)(fj,{canInstall:!!Ve,canFullscreen:Ne,fullscreenActive:Ae,copy:he,onClose:()=>ze(!1),onInstall:Ze,onToggleFullscreen:Qe})]})}function aM(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 oM(e){let t=Number(e);return Number.isFinite(t)?`${Math.round(t)}%`:`--`}function sM(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 cM(e){let t=e.forecast?.remainingTokens,n=t==null?null:Number(t);return typeof n==`number`&&Number.isFinite(n)&&n>=0?`${fM(Math.round(n))} tok left`:sM(e.usedPercent)}function lM(e){return cM(e)}function uM(e,t){let n=[e],r=oM(t.usedPercent),i=cM(t);return r!==`--`&&n.push(`${r} used`),i!==`-- left`&&n.push(i),n.filter(Boolean).join(` / `)}function dM(e,t){let n=Number(e);if(!Number.isFinite(n)||n<=0)return null;let r=Math.max(0,Math.round((n-t)/6e4));return r===0?`reset now`:r>=1440?`reset ${Math.floor(r/1440)}d ${Math.floor(r%1440/60)}h`:r>=60?`reset ${Math.floor(r/60)}h ${r%60}m`:`reset ${r}m`}function fM(e){if(e>=1e9){let t=e/1e9;return`${t>=10?Math.round(t):Math.round(t*10)/10}B`}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 pM(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?`~`:``}${fM(r)} tok/min`}function mM(e){let t=e.auth?.status||``;return e.auth?.available?/logged in/i.test(t)?`logged in`:t||`available`:`offline`}function hM(e){if(e.tokenUsage.available===!1)return!1;let t=Number(e.tokenUsage.eventCount),n=Number(e.tokenUsage.totalTokens),r=Number.isFinite(t)&&t>0||Number.isFinite(n)&&n>0;return e.auth.available||r}function gM(e){return e?.providers.filter(hM)??[]}function _M(e){let t=gM(e);return t.length?t.reduce((e,t)=>{let n=Number(t.tokenUsage.tokensPerMinute);return e+(Number.isFinite(n)?n:0)},0):null}function vM(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 yM(e){let t=Number(e.windowMinutes);return Number.isFinite(t)&&t>=10020?0:Number.isFinite(t)&&t>=285&&t<=315?1:2}function bM(e){return[e.quota.primary,e.quota.secondary].filter(e=>!!e).map(e=>({label:aM(e.windowMinutes),limit:e,remaining:vM(e),exhaustedAt:typeof e.forecast?.projectedExhaustedAt==`number`&&Number.isFinite(e.forecast.projectedExhaustedAt)?e.forecast.projectedExhaustedAt:null})).filter(e=>e.remaining!==null).sort((e,t)=>yM(e.limit)-yM(t.limit))}function xM(e){let t=Number(e.tokenUsage.tokensPerMinute);return Number.isFinite(t)&&t>0}function SM(e){let t=gM(e);return t.length?t.filter(e=>xM(e)&&e.quota.available).map(e=>{let t=bM(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 CM(e,t){let n=SM(e);if(!n)return null;let r=[n.provider.providerName];return n.limits.forEach(e=>{r.push(`${e.label} ${Math.round(e.remaining??0)}%`);let n=dM(e.limit.resetsAt,t);n&&r.push(n)}),r.join(` · `)}function wM(e,t){let n=[],r=_M(e);return r!==null&&n.push(pM(r)),t&&n.push(`CPU ${t.cpu}% / MEM ${t.memory.percentage}%`),n.join(` · `)||`5m`}function TM(e,t,n){return CM(e,n)||wM(e,t)}function EM(e){return e.status===`pending`?`starting`:e.status===`dead`?`offline`:e.status}function DM(e,t){return e??t?.systemStats??null}function OM({usageSummary:e,now:t}){let n=TM(e,DM(ut(),e),t);return(0,K.jsx)(`span`,{className:`code-usage-summary`,"data-testid":`code-usage-summary`,title:n,children:n})}function kM({usageSummary:e}){let t=DM(ut(),e);return t?(0,K.jsxs)(`div`,{className:`code-usage-row`,children:[(0,K.jsx)(`span`,{children:`System`}),(0,K.jsxs)(`strong`,{children:[`CPU `,t.cpu,`% / MEM `,t.memory.percentage,`%`]})]}):null}function AM(e){let t=dt();return!e.usageSummary&&!e.mainAgent&&!t?null:(0,K.jsx)(QM,{...e})}function jM(e){return new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}function MM(e){return`${String(new Date(e).getHours()).padStart(2,`0`)}:00`}function NM(e){return Math.round(e).toLocaleString(`en-US`)}function PM(e){let t=e.map(e=>Math.max(0,Number(e)||0)).filter(e=>e>0).sort((e,t)=>e-t);if(!t.length)return[];let n=t[0],r=t[t.length-1];return n===r?[.2,.4,.6,.8].map(e=>r*e):[.2,.4,.6,.8].map(e=>{let n=(t.length-1)*e,r=Math.floor(n),i=Math.ceil(n),a=t[r];return a+(t[i]-a)*(n-r)})}function FM(e,t){let n=Math.max(0,Number(e)||0);return n<=0?0:Math.max(1,Math.min(5,1+t.filter(e=>n>e).length))}function IM(e){let t=e.timeline,n=Array.isArray(t?.points)?t.points:[];return n.length>0&&n.every((e,t)=>Number.isFinite(Number(e.startedAt))&&Number.isFinite(Number(e.endedAt))&&Number(e.endedAt)>Number(e.startedAt)&&Number.isFinite(Number(e.totalTokens))&&Number(e.totalTokens)>=0&&(t===0||Number(e.startedAt)>=Number(n[t-1].startedAt)))?n:null}function LM(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),a=new Date(n,r-1,i,12,0,0,0);return a.getFullYear()!==n||a.getMonth()!==r-1||a.getDate()!==i?null:a}function RM(e){let t=Array.isArray(e.daily?.points)?e.daily.points:[];return t.length>0&&t.every((e,n)=>!!LM(e.date)&&Number.isFinite(Number(e.totalTokens))&&Number(e.totalTokens)>=0&&(n===0||e.date>t[n-1].date))?t.slice(-364):null}function zM({usageSummary:e,points:t,onInspect:n}){let r=e.timeline,i=t.reduce((e,t)=>e+Number(t.totalTokens),0),a=aM(Number(r.windowMs)/6e4).toLowerCase(),o=PM(t.map(e=>e.totalTokens)),s=[0,.25,.5,.75,1].map(e=>r.startAt+(r.endAt-r.startAt)*e);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`code-usage-heatmap`,"data-testid":`code-usage-heatmap`,role:`img`,"aria-label":`Token activity over the last ${a}, ${fM(i)} tokens`,title:`Local token activity · last ${a}`,children:t.map((e,t)=>{let r=Number(e.totalTokens),i=`${jM(e.startedAt)}–${jM(e.endedAt)}`,a=`${i} · ${NM(r)} tokens`;return(0,K.jsx)(`span`,{className:`code-usage-heatmap-cell`,"data-level":FM(r,o),"data-start":e.startedAt,title:a,"aria-label":a,onMouseEnter:()=>n({label:i,tokens:r})},`${e.startedAt}-${t}`)})}),(0,K.jsx)(`div`,{className:`code-usage-time-axis`,"data-testid":`code-usage-time-axis`,"aria-hidden":`true`,children:s.map((e,t)=>(0,K.jsx)(`span`,{children:MM(e)},`${e}-${t}`))})]})}function BM({points:e,onInspect:t,inspection:n=null,showDayHighlight:r=!1}){let i=(LM(e[0].date).getDay()+6)%7,a=Math.max(1,Math.ceil((i+e.length)/7)),o=a*7-i-e.length,s=PM(e.map(e=>e.totalTokens)),c=e.filter(e=>e.totalTokens>0).length,l=Math.max(0,e.length-7),u=e.slice(l).reduce((e,t)=>e+t.totalTokens,0),d=e.reduce((e,t)=>!e||t.totalTokens>e.totalTokens?t:e,null),f=d&&d.totalTokens>0?d:null,p=n?e.find(e=>e.date===n.label)??null:null,m=e[e.length-1]??null,h=p??m,g=!!(h&&h.date===f?.date);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`code-usage-activity-heading`,children:[(0,K.jsx)(`span`,{children:`52w · daily`}),r&&h?(0,K.jsxs)(`div`,{className:`code-usage-detail-day-highlight`,"data-state":p?`selected`:`today`,"data-testid":`code-usage-detail-day-highlight`,children:[(0,K.jsxs)(`span`,{children:[p&&g?`Top · `:``,UM(h.date)]}),(0,K.jsx)(`strong`,{children:fM(h.totalTokens)}),(0,K.jsx)(`small`,{children:`tokens`})]}):(0,K.jsxs)(`span`,{children:[`7d `,fM(u)]})]}),(0,K.jsxs)(`div`,{className:`code-usage-daily-heatmap`,"data-testid":`code-usage-daily-heatmap`,role:`img`,"aria-label":`Daily token activity over 52 weeks, ${c} active days`,style:{gridTemplateColumns:`repeat(${a}, minmax(2px, 1fr))`},children:[Array.from({length:i},(e,t)=>(0,K.jsx)(`span`,{className:`code-usage-daily-spacer`,"aria-hidden":`true`},`leading-${t}`)),e.map((e,n)=>{let i=Number(e.totalTokens),a=e.date===f?.date,o=i>1e9,c=a?`Token king`:o?`Over 1B tokens`:``,u=`${e.date} · ${NM(i)} tokens${c?` · ${c}`:``}`,d=e.date===p?.date,m=()=>t({label:e.date,tokens:i});return(0,K.jsx)(`span`,{className:`code-usage-heatmap-cell code-usage-daily-heatmap-cell`,"data-date":e.date,"data-level":FM(i,s),"data-peak":a?`true`:void 0,"data-billion":o?`true`:void 0,"data-shape":r?a?`crown`:o?`flame`:void 0:void 0,"data-recent":n>=l?`true`:void 0,"data-selected":d?`true`:void 0,title:u,"aria-label":u,role:r?`button`:void 0,tabIndex:r?0:void 0,onClick:r?m:void 0,onFocus:r?m:void 0,onKeyDown:r?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),m())}:void 0,onMouseEnter:r?void 0:m,onPointerMove:r?m:void 0},e.date)}),Array.from({length:o},(e,t)=>(0,K.jsx)(`span`,{className:`code-usage-daily-spacer`,"aria-hidden":`true`},`trailing-${t}`))]})]})}function VM(e){return e.reduce((e,t)=>e+Number(t.totalTokens),0)}function HM(e,t){if(t<=0)return e>0?`New`:`0%`;let n=Math.round((e-t)/t*100);return`${n>0?`+`:``}${n}%`}function UM(e){let t=LM(e);return t?t.toLocaleDateString([],{month:`short`,day:`numeric`}):e}function WM(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.date===t&&Array.isArray(n.hours)&&n.hours.length===24&&n.hours.every((e,t)=>e.hour===t&&Number.isFinite(Number(e.totalTokens))&&e.totalTokens>=0&&!!(e.agents&&typeof e.agents==`object`))&&Array.isArray(n.agents)&&n.agents.every(e=>!!(e.key&&e.label)&&Number.isFinite(Number(e.totalTokens))&&e.totalTokens>=0)}function GM(e,t){let[n,i]=(0,G.useState)(0),[a,o]=(0,G.useState)({date:``,detail:null,error:``,loading:!1});return(0,G.useEffect)(()=>{if(!e){o({date:``,detail:null,error:``,loading:!1});return}let n=new AbortController;o({date:e,detail:null,error:``,loading:!0});let i=new URLSearchParams({date:e});return t&&i.set(`live`,`1`),fetch(r(`/api/usage/day?${i.toString()}`),{signal:n.signal}).then(async t=>{let n=await t.json();if(!t.ok)throw Error(n.error||`Failed to load day activity`);if(!WM(n.detail,e))throw Error(`Day activity response was incomplete`);return n.detail}).then(t=>{n.signal.aborted||o({date:e,detail:t,error:``,loading:!1})}).catch(t=>{n.signal.aborted||o({date:e,detail:null,error:t instanceof Error?t.message:`Failed to load day activity`,loading:!1})}),()=>n.abort()},[e,t,n]),{...a,retry:()=>i(e=>e+1)}}var KM=[`#245f1d`,`#3b782f`,`#548f47`,`#70a766`,`#8dbc86`,`#aacda5`,`#486d42`,`#789473`];function qM(e){let t=0;for(let n of e)t=(t<<5)-t+n.charCodeAt(0)|0;return KM[Math.abs(t)%KM.length]}function JM({date:e,detail:t,error:n,loading:r,onRetry:i}){let[a,o]=(0,G.useState)(null);if((0,G.useEffect)(()=>o(null),[e]),r)return(0,K.jsx)(`div`,{className:`code-usage-day-breakdown loading`,"data-testid":`code-usage-day-histogram-loading`,children:(0,K.jsx)(`div`,{className:`code-usage-day-breakdown-status`,children:`Loading hourly Agent activity…`})});if(n)return(0,K.jsxs)(`div`,{className:`code-usage-day-breakdown error`,"data-testid":`code-usage-day-histogram-error`,children:[(0,K.jsx)(`span`,{children:n}),(0,K.jsx)(`button`,{type:`button`,onClick:i,children:`Retry`})]});if(!t)return null;let s=Math.max(0,...t.hours.map(e=>e.totalTokens)),l=Array.from(t.agents.reduce((e,t)=>{let n=e.get(t.provider);return n?n.totalTokens+=t.totalTokens:e.set(t.provider,{key:t.provider,label:c(t.provider),totalTokens:t.totalTokens}),e},new Map).values()).sort((e,t)=>t.totalTokens-e.totalTokens||e.label.localeCompare(t.label)),u=a?`${a.label} · ${fM(a.tokens)} tokens`:`${UM(t.date)} · ${fM(t.total.totalTokens)} tokens`;return(0,K.jsxs)(`div`,{className:`code-usage-day-breakdown`,"data-testid":`code-usage-day-histogram`,onMouseLeave:()=>o(null),children:[(0,K.jsxs)(`div`,{className:`code-usage-day-breakdown-heading`,children:[(0,K.jsx)(`span`,{children:`Hourly by Agent type`}),(0,K.jsx)(`strong`,{"data-testid":`code-usage-day-histogram-readout`,children:u})]}),(0,K.jsxs)(`div`,{className:`code-usage-day-histogram-chart`,role:`img`,"aria-label":`Hourly token activity for ${t.date}, split across ${l.length} Agent types`,children:[(0,K.jsxs)(`div`,{className:`code-usage-day-histogram-scale`,"aria-hidden":`true`,children:[(0,K.jsx)(`span`,{children:fM(s)}),(0,K.jsx)(`span`,{children:`0`})]}),(0,K.jsxs)(`div`,{className:`code-usage-day-histogram-plot`,children:[(0,K.jsx)(`div`,{className:`code-usage-day-histogram-bars`,children:t.hours.map(e=>{let n=s>0?e.totalTokens/s*100:0;return(0,K.jsx)(`div`,{className:`code-usage-day-histogram-column`,"data-hour":e.hour,title:`${e.label}:00 · ${NM(e.totalTokens)} tokens`,children:(0,K.jsx)(`div`,{className:`code-usage-day-histogram-stack`,style:{height:`${n}%`},children:l.map(n=>{let r=t.agents.reduce((t,r)=>r.provider===n.key?t+(Number(e.agents[r.key]?.totalTokens)||0):t,0);if(r<=0||e.totalTokens<=0)return null;let i=`${e.label}:00 · ${n.label}`,a=`${i} · ${NM(r)} tokens`;return(0,K.jsx)(`span`,{className:`code-usage-day-histogram-segment`,"data-agent-type":n.key,style:{backgroundColor:qM(n.key),height:`${r/e.totalTokens*100}%`},title:a,onMouseEnter:()=>o({label:i,tokens:r})},n.key)})})},e.hour)})}),(0,K.jsxs)(`div`,{className:`code-usage-day-histogram-axis`,"aria-hidden":`true`,children:[(0,K.jsx)(`span`,{children:`00:00`}),(0,K.jsx)(`span`,{children:`06:00`}),(0,K.jsx)(`span`,{children:`12:00`}),(0,K.jsx)(`span`,{children:`18:00`}),(0,K.jsx)(`span`,{children:`23:00`})]})]})]}),l.length>0&&(0,K.jsx)(`div`,{className:`code-usage-day-agent-legend`,"data-testid":`code-usage-day-agent-legend`,children:l.map(e=>(0,K.jsxs)(`span`,{title:`${e.label} · ${NM(e.totalTokens)} tokens`,children:[(0,K.jsx)(`i`,{style:{backgroundColor:qM(e.key)},"aria-hidden":`true`}),(0,K.jsx)(`b`,{children:e.label}),(0,K.jsx)(`small`,{children:fM(e.totalTokens)})]},e.key))})]})}function YM({label:e,value:t,detail:n}){return(0,K.jsxs)(`div`,{className:`code-usage-detail-stat`,children:[(0,K.jsx)(`span`,{children:e}),(0,K.jsx)(`strong`,{children:t}),n&&(0,K.jsx)(`small`,{children:n})]})}function XM({initialRange:e,usageSummary:t,onClose:n}){let[r,i]=(0,G.useState)(e),[a,o]=(0,G.useState)(null),s=IM(t),c=RM(t),l=c?.reduce((e,t)=>!e||t.totalTokens>e.totalTokens?t:e,null)??null,u=c?.[c.length-1]??null,d=c?.find(e=>e.date===a?.label)??null,f=r===`year`&&(d??u)?.date||``,p=GM(f,!!(f&&c&&f===c[c.length-1]?.date));if((0,G.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),typeof document>`u`)return null;let m=s?.reduce((e,t)=>e+t.totalTokens,0)??0,h=s?.filter(e=>e.totalTokens>0).length??0,g=s?.reduce((e,t)=>!e||t.totalTokens>e.totalTokens?t:e,null)??null,_=c?.slice(-7)??[],v=c?.slice(-14,-7)??[],y=VM(_),b=VM(v),x=c?VM(c):0,S=c?.filter(e=>e.totalTokens>0).length??0,C=_.reduce((e,t)=>e+(Number(t.cacheReadTokens)||0)+(Number(t.cacheWriteTokens)||0),0),w=y>0?Math.min(100,Math.round(C/y*100)):0,T=a?`${a.label} · ${NM(a.tokens)} tokens`:`Last 24 hours · ${NM(m)} tokens`,E=a?`${a.label} · ${NM(a.tokens)} tokens`:`Last 52 weeks · ${NM(x)} tokens`;return(0,dj.createPortal)((0,K.jsx)(`div`,{className:`code-usage-detail-backdrop`,"data-testid":`code-usage-detail-backdrop`,onMouseDown:e=>{e.target===e.currentTarget&&n()},children:(0,K.jsxs)(`section`,{className:`code-usage-detail-dialog`,"data-testid":`code-usage-detail-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-usage-detail-title`,children:[(0,K.jsxs)(`header`,{className:`code-usage-detail-header`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{className:`code-usage-detail-eyebrow`,children:`Local provider tokens`}),(0,K.jsx)(`h2`,{id:`code-usage-detail-title`,children:`Usage activity`})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-usage-detail-close`,"aria-label":`Close usage activity`,onClick:n,children:(0,K.jsx)(Se,{})})]}),(0,K.jsxs)(`div`,{className:`code-usage-detail-tabs`,role:`tablist`,"aria-label":`Usage activity range`,children:[(0,K.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":r===`day`,"data-testid":`code-usage-detail-day-tab`,onClick:()=>{o(null),i(`day`)},children:`1 Day`}),(0,K.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":r===`year`,"data-testid":`code-usage-detail-year-tab`,onClick:()=>{o(null),i(`year`)},children:`52 Weeks`})]}),(0,K.jsxs)(`div`,{className:`code-usage-detail-chart`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||o(null)},onMouseLeave:()=>o(null),children:[r===`day`&&s&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`code-usage-detail-chart-heading`,children:[(0,K.jsx)(`span`,{children:`Hourly activity`}),(0,K.jsxs)(`strong`,{children:[fM(m),` tokens`]})]}),(0,K.jsx)(zM,{usageSummary:t,points:s,onInspect:o})]}),r===`year`&&c&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(BM,{points:c,inspection:a,showDayHighlight:!0,onInspect:o}),(0,K.jsx)(JM,{date:f,detail:p.date===f?p.detail:null,error:p.date===f?p.error:``,loading:p.date===f?p.loading:!0,onRetry:p.retry})]}),(0,K.jsx)(`div`,{className:`code-usage-detail-readout`,"data-testid":`code-usage-detail-readout`,children:r===`day`?T:E})]}),(0,K.jsx)(`div`,{className:`code-usage-detail-analysis`,"data-testid":`code-usage-detail-analysis`,children:r===`day`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(YM,{label:`24-hour tokens`,value:fM(m)}),(0,K.jsx)(YM,{label:`Active hours`,value:`${h}`,detail:`hours with token activity`}),(0,K.jsx)(YM,{label:`Peak hour`,value:g?MM(g.startedAt):`--`,detail:g?`${fM(g.totalTokens)} tokens`:`no activity`})]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(YM,{label:`Last 7 days`,value:fM(y)}),(0,K.jsx)(YM,{label:`Previous 7 days`,value:fM(b),detail:`${HM(y,b)} change`}),(0,K.jsx)(YM,{label:`Peak day`,value:l?UM(l.date):`--`,detail:l?`${fM(l.totalTokens)} tokens`:`no activity`}),(0,K.jsx)(YM,{label:`Active days`,value:`${S}`,detail:`within 52 weeks`}),(0,K.jsx)(YM,{label:`7-day cache share`,value:`${w}%`,detail:`read and write tokens`}),(0,K.jsx)(YM,{label:`52-week tokens`,value:fM(x)})]})})]})}),document.body)}function ZM({usageSummary:e}){let t=IM(e),n=RM(e),[r,i]=(0,G.useState)(null),[a,o]=(0,G.useState)(null);if(!t&&!n)return null;let s=t?.reduce((e,t)=>e+t.totalTokens,0)??0,c=aM(Number(e.timeline?.windowMs)/6e4).toLowerCase(),l=n?.slice(-7).reduce((e,t)=>e+t.totalTokens,0)??0,u=n?.reduce((e,t)=>e+t.totalTokens,0)??0,d=r?`${r.label} · ${NM(r.tokens)} tokens`:`${t?`${c} ${fM(s)}`:``}${t&&n?` · `:``}${n?`7d ${fM(l)} · 52w ${fM(u)}`:``}`;return(0,K.jsxs)(`div`,{className:`code-usage-activity`,onMouseLeave:()=>i(null),children:[t&&(0,K.jsxs)(`button`,{type:`button`,className:`code-usage-chart-trigger`,"data-testid":`code-usage-open-day`,title:`Open 1-day usage details`,onClick:()=>o(`day`),children:[(0,K.jsxs)(`div`,{className:`code-usage-activity-heading`,children:[(0,K.jsxs)(`span`,{children:[c,` · activity`]}),(0,K.jsxs)(`span`,{children:[aM(e.timeline.bucketMs/6e4).toLowerCase(),` buckets`]})]}),(0,K.jsx)(zM,{usageSummary:e,points:t,onInspect:i})]}),n&&(0,K.jsx)(`button`,{type:`button`,className:`code-usage-chart-trigger`,"data-testid":`code-usage-open-year`,title:`Open 52-week usage details`,onClick:()=>o(`year`),children:(0,K.jsx)(BM,{points:n,onInspect:i})}),(0,K.jsx)(`div`,{className:`code-usage-activity-readout`,"data-testid":`code-usage-activity-readout`,title:d,children:d}),a&&(0,K.jsx)(XM,{initialRange:a,usageSummary:e,onClose:()=>o(null)})]})}function QM({collapsed:e,mainAgent:t,now:n,usageSummary:r,onToggleCollapsed:i,onOpenMainAgent:a,onRestartMainAgent:o}){let s=gM(r),c=_M(r),[l,u]=(0,G.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)(W,{}):(0,K.jsx)(be,{})}),(0,K.jsx)(`span`,{children:`Usage`})]}),(0,K.jsx)(`span`,{className:`code-usage-header-meta`,children:e?(0,K.jsx)(OM,{usageSummary:r,now:n}):(0,K.jsx)(`span`,{className:`code-usage-summary`,"data-testid":`code-usage-summary`,title:`5-minute rate · hourly and daily activity`,children:`5m rate · activity`})})]}),!e&&(0,K.jsxs)(K.Fragment,{children:[s.length>0&&r?.timeline&&(0,K.jsx)(ZM,{usageSummary:r}),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:`${ee(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:EM(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))})]}),s.map(e=>(0,K.jsx)($M,{provider:e},e.provider)),s.length>1&&c!==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:pM(c)})]}),(0,K.jsx)(kM,{usageSummary:r})]})]})}function $M({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:mM(e)})]}),e.quota.available&&(0,K.jsxs)(K.Fragment,{children:[t&&(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow`,title:uM(r,t),children:[(0,K.jsx)(`span`,{children:aM(t.windowMinutes)}),(0,K.jsx)(`strong`,{children:lM(t)})]}),n&&(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow`,title:uM(r,n),children:[(0,K.jsx)(`span`,{children:aM(n.windowMinutes)}),(0,K.jsx)(`strong`,{children:lM(n)})]})]}),(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:pM(e.tokenUsage.tokensPerMinute)})]})]})}function eN({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)(tN,{item:e,index:o,activeTerminalId:t,now:n,onOpenAgent:r,onShowPreview:i,onHidePreview:a},Rk({kind:`agent`,agent:e.agent})))})}function tN({item:e,index:t,activeTerminalId:n,now:r,onOpenAgent:i,onShowPreview:a,onHidePreview:o}){let s=Yk({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,mN(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 nN({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=Yk({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,mN(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`})]},Rk({kind:`agent`,agent:e,claimedSessionKey:r.get(e.id)}))})})}function rN({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`?Yk({kind:`agent`,agent:e.agent},a):Yk({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=_?aD(_):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?mN(g,h):hN(_,h),!0),onMouseLeave:p,onContextMenu:e=>{if(g){s(e,g.id);return}_&&u(e,_.provider,aD(_))},onKeyDown:e=>{g?c(e,g.id):_&&d(e,_.provider,aD(_)),!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`?Rk({kind:`agent`,agent:e.agent,claimedSessionKey:i.get(e.agent.id)}):Rk({kind:`history`,session:e.session}))})})}function iN({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,G.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)(W,{}):(0,K.jsx)(be,{})}),(0,K.jsx)(`span`,{children:x.pinned})]}),!t&&(0,K.jsx)(`div`,{className:`code-agent-list code-pinned-list`,children:n?(0,K.jsx)(rN,{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)(wN,{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},Rk({kind:`agent`,agent:t,claimedSessionKey:o.get(t.id)}))}return(0,K.jsx)(wN,{session:e.session,searchSelected:aD(e.session)===a,now:l,onResume:h,onOpenSessionContextMenu:g,onOpenSessionKeyboardMenu:_,onShowPreview:v,onHidePreview:y,copy:x},Rk({kind:`history`,session:e.session}))})})]})}function aN(e,t){return e.branch?e.branch:e.detached?`${t.worktreeDetached}@${e.head.slice(0,7)}`:e.bare?`bare`:e.head.slice(0,7)}function oN({agentId:e,anchorRef:t,copy:n,fallback:r,point:i,onClose:a,onMountProject:o}){let s=(0,G.useRef)(null),c=(0,G.useRef)(null),[l,u]=(0,G.useState)(r),[d,f]=(0,G.useState)(!1),[p,m]=(0,G.useState)(``),h=(0,G.useCallback)(()=>{c.current?.abort();let t=new AbortController;c.current=t,f(!0),m(``),ce(e,{signal:t.signal}).then(e=>{t.signal.aborted||u(e)}).catch(e=>{t.signal.aborted||e?.name===`AbortError`||m(n.worktreeLoadFailed)}).finally(()=>{t.signal.aborted||f(!1)})},[e,n.worktreeLoadFailed]);return(0,G.useEffect)(()=>(h(),()=>c.current?.abort()),[h]),(0,G.useEffect)(()=>{let e=e=>{let n=e.target;n&&(s.current?.contains(n)||t.current?.contains(n))||a()},n=e=>{e.key===`Escape`&&(e.preventDefault(),a(),t.current?.focus())};return window.addEventListener(`pointerdown`,e,!0),window.addEventListener(`keydown`,n,!0),()=>{window.removeEventListener(`pointerdown`,e,!0),window.removeEventListener(`keydown`,n,!0)}},[t,a]),(0,K.jsxs)(`div`,{ref:s,className:`code-worktree-popover`,"data-testid":`code-project-worktree-menu`,role:`dialog`,"aria-label":n.worktrees,style:{left:i.x,top:i.y},children:[(0,K.jsxs)(`div`,{className:`code-worktree-popover-header`,children:[(0,K.jsx)(`span`,{children:n.worktrees}),(0,K.jsx)(`span`,{className:`code-worktree-popover-count`,children:l.items.length}),(0,K.jsx)(`button`,{type:`button`,className:d?`loading`:``,disabled:d,onClick:h,children:n.refresh})]}),p&&(0,K.jsx)(`div`,{className:`code-worktree-popover-status error`,children:p}),!p&&!l.isGitRepo&&(0,K.jsx)(`div`,{className:`code-worktree-popover-status`,children:n.gitHistoryNotRepository}),(0,K.jsx)(`div`,{className:`code-worktree-list`,children:l.items.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-worktree-row ${e.current?`current`:``}`,"data-current":e.current?`true`:void 0,"data-main":e.main?`true`:void 0,title:e.workspace,onClick:()=>{o(e.workspace),a()},children:[(0,K.jsx)(`span`,{className:`code-worktree-row-marker`,"aria-hidden":`true`}),(0,K.jsxs)(`span`,{className:`code-worktree-row-content`,children:[(0,K.jsxs)(`span`,{className:`code-worktree-row-heading`,children:[(0,K.jsx)(`strong`,{children:aN(e,n)}),(0,K.jsxs)(`span`,{className:`code-worktree-row-badges`,children:[e.current&&(0,K.jsx)(`span`,{children:n.worktreeCurrent}),e.main&&(0,K.jsx)(`span`,{children:n.worktreeMain}),e.locked&&(0,K.jsx)(`span`,{title:e.lockReason,children:n.worktreeLocked}),e.prunable&&(0,K.jsx)(`span`,{title:e.pruneReason,children:n.worktreePrunable})]}),e.head&&(0,K.jsx)(`code`,{children:e.head.slice(0,7)})]}),(0,K.jsx)(`span`,{className:`code-worktree-row-path`,children:e.workspace})]})]},e.workspace))})]})}function sN(e){return e?.workspace?{isGitRepo:!0,commonDir:e.commonDir,currentWorkspace:e.workspace,mainWorkspace:e.mainWorkspace,items:Array.isArray(e.worktrees)?e.worktrees:[]}:null}function cN({project:e,collapsed:t,forceAgentsExpanded:n,compactAgents:r,activeTerminalId:i,selectedSearchAgentId:a,selectedSearchSessionHandle:o,claimedAgentSessionKeyByAgentId:s,agentShortcutKeys:l,keyboardShortcutsEnabled:u,now:f,openWorkspaceFile:p,openWorkspaceFiles:h,agentLaunchOptions:g,fileRevealRequest:_,fileSearchFocusRequest:v,onToggleProject:y,onToggleProjectSessions:b,onMountProject:x,onNewAgent:S,onStartAgent:C,onOpenProjectContextMenu:w,onOpenProjectKeyboardMenu:T,onOpenAgent:E,onUpdateAgentFlags:D,onReorderAgent:O,onOpenAgentContextMenu:k,onOpenAgentKeyboardMenu:A,onResumeAgentSession:j,onOpenAgentSessionContextMenu:M,onOpenAgentSessionKeyboardMenu:N,onShowAgentPreview:P,onHideAgentPreview:F,onOpenProjectFile:ee,onSelectOpenWorkspaceFile:I,onCloseOpenWorkspaceFile:te,onMoveWorkspaceEntries:L,onDeleteWorkspaceEntries:R,onRefreshProjectOpenFiles:ne,copy:z}){let B=(0,G.useRef)(null),re=(0,G.useRef)(null),ie=(0,G.useRef)(null),ae=(0,G.useRef)(null),V=(0,G.useRef)(null),se=(0,G.useRef)(null),[le,ue]=(0,G.useState)(null),[de,fe]=(0,G.useState)(null),[pe,me]=(0,G.useState)(()=>sN(e.gitWorktree)),[he,H]=(0,G.useState)(!1),[ge,_e]=(0,G.useState)(!1),[ve,ye]=(0,G.useState)(!1),[xe,Se]=(0,G.useState)(null),[Ce,we]=(0,G.useState)(()=>Uj(null,e.agents)),Te=Uj(Ce,e.agents),Ee=e.agents.find(e=>!e.isMain&&e.id===Te)??null,De=e.workspace?Fn(e.workspace):``,Oe=e.id!==`__farming_main_agent__`&&!!De,U=new Set([De,...e.agents.filter(e=>!e.isMain).map(e=>e.id),...Ee&&!Ee.isMain?[Ee.id]:[]]),ke=t=>t.workspaceRoot===e.workspace||U.has(t.agentId),Ae=p&&ke(p)?p:null,je=h.filter(ke),Me=new Set(je.filter(e=>e.dirty).map(e=>e.file.path)),Ne=new Set(je.filter(e=>e.externalChanged).map(e=>e.file.path)),Pe=e.agents.filter(e=>!e.pinned),Fe=e.agentSessions.filter(e=>!e.pinned),Ie=Pe.length>0||Fe.length>0||(e.hiddenAgentSessionCount??0)>0,Le=ve&&oe()&&Pe.length>1,Re=(r||Le)&&Pe.length>0,ze=Re||he?Pe:fN(Pe,Yj,[i,a]),Be=Math.max(0,Pe.length-ze.length),Ve=ge&&!n;(0,G.useEffect)(()=>{Ce!==Te&&we(Te)},[Te,Ce]),(0,G.useEffect)(()=>{let t=sN(e.gitWorktree);t&&me(t)},[e.gitWorktree]),(0,G.useEffect)(()=>{if(!De)return;let e=new AbortController;return ce(De,{signal:e.signal}).then(me).catch(()=>{}),()=>e.abort()},[De]);let He=(0,G.useCallback)(e=>!Ee?.id||e?.sourceAgentId?e:{...e,sourceAgentId:Ee.id},[Ee?.id]),Ue=(0,G.useCallback)((e,t,n)=>{ee(e,t,He(n))},[ee,He]),We=(0,G.useCallback)((e,t,n)=>I(e,t,He(n)),[I,He]),Ge=(0,G.useCallback)(e=>{ye(!e)},[]),Ke=(e,t)=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),F(),Se({agentId:t,targetAgentId:``,position:`before`})},qe=(e,t)=>{if(!xe||xe.agentId===t)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let n=e.currentTarget.getBoundingClientRect(),r=e.clientY<n.top+n.height/2?`before`:`after`;xe.targetAgentId===t&&xe.position===r||Se(e=>e?{...e,targetAgentId:t,position:r}:null)},Je=()=>Se(null),Ye=(e,t)=>{if(e.preventDefault(),!xe||xe.agentId===t){Je();return}let n=Pe.filter(e=>e.id!==xe.agentId),r=n.findIndex(e=>e.id===t);if(r<0){Je();return}let i=xe.position===`before`?r:r+1;O(xe.agentId,i>0?n[i-1]?.id??``:``,i<n.length?n[i]?.id??``:``),Je()},Xe=e=>{if(e.preventDefault(),!xe)return;let t=Pe.filter(e=>e.id!==xe.agentId);O(xe.agentId,t[t.length-1]?.id??``,``),Je()},Ze=e=>{xe&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,xe.targetAgentId!==Xj&&Se(e=>e?{...e,targetAgentId:Xj,position:`after`}:null))};(0,G.useEffect)(()=>{Pe.length<=Yj&&he&&H(!1)},[he,Pe.length]),(0,G.useLayoutEffect)(()=>{let e=B.current;if(!e)return;let t=()=>{let t=re.current;e.style.setProperty(`--code-project-sticky-height`,t?`${Math.ceil(t.getBoundingClientRect().height)}px`:``);let n=ie.current;e.style.setProperty(`--code-agents-sticky-height`,n?`${Math.ceil(n.getBoundingClientRect().height)}px`:`0px`)};t();let n=re.current,r=ie.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,Ie]),(0,G.useEffect)(()=>{if(!le)return;let e=e=>{let t=e.target;t&&(V.current?.contains(t)||ae.current?.contains(t))||ue(null)},t=e=>{e.key===`Escape`&&(e.preventDefault(),ue(null),ae.current?.focus())};return window.addEventListener(`pointerdown`,e,!0),window.addEventListener(`keydown`,t,!0),()=>{window.removeEventListener(`pointerdown`,e,!0),window.removeEventListener(`keydown`,t,!0)}},[le]);let Qe=t=>{if(t.preventDefault(),t.stopPropagation(),g.length===0){S(e.workspace,void 0,t.currentTarget);return}let n=t.currentTarget.getBoundingClientRect(),r=Math.min(260,g.length*34+12);ue(oe()?Cj(n,r,void 0,160):Sj(n,r,void 0,160))},$e=t=>{ue(null),C(t,e.workspace)},et=pe?.items.find(e=>e.current),tt=pe?.isGitRepo&&et&&et?et.branch||`detached@${et.head.slice(0,7)}`:``,nt=pe?.items.length||0;return(0,K.jsxs)(`section`,{ref:B,className:`code-project-group`,"data-testid":`code-project-group`,children:[(0,K.jsxs)(`div`,{ref:re,className:`code-project-row`,children:[(0,K.jsxs)(`span`,{className:`code-project-title-content`,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:()=>y(e.id),onContextMenu:t=>w(t,e.id),onKeyDown:t=>T(t,e.id),children:[(0,K.jsx)(`span`,{className:`code-folder-icon ${t?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:t?(0,K.jsx)(W,{}):(0,K.jsx)(be,{})}),(0,K.jsx)(`span`,{className:`code-project-title-name`,children:e.name})]}),tt&&pe&&(0,K.jsxs)(`button`,{ref:se,type:`button`,className:`code-project-worktree`,"data-testid":`code-project-worktree`,title:`${tt} · ${nt} ${z.worktrees.toLocaleLowerCase()} · ${z.showWorktrees}`,"aria-label":`${tt} · ${nt} ${z.worktrees}`,"aria-haspopup":`dialog`,"aria-expanded":de?!0:void 0,onClick:e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getBoundingClientRect(),n=Math.min(440,Math.max(320,window.innerWidth-24)),r=Math.min(420,Math.max(132,(pe?.items.length||2)*58+54));fe(oe()?Cj(t,r,void 0,n):Sj(t,r,void 0,n))},children:[(0,K.jsx)(`span`,{className:`code-project-worktree-icon`,"aria-hidden":`true`,children:(0,K.jsx)(tM,{})}),(0,K.jsx)(`span`,{className:`code-project-worktree-name`,children:tt}),nt>1&&(0,K.jsx)(`span`,{className:`code-project-worktree-count`,"aria-hidden":`true`,children:nt})]})]}),(0,K.jsxs)(`span`,{className:`code-project-title-actions`,"aria-hidden":!1,children:[Ie&&!n&&(0,K.jsx)(`button`,{type:`button`,className:`code-project-title-action`,"data-testid":`code-project-agent-visibility`,"data-collapsed":Ve?`true`:`false`,"aria-expanded":!Ve,"aria-label":Ve?z.showAgents:z.hideAgents,title:Ve?z.showAgents:z.hideAgents,onClick:()=>_e(e=>!e),children:Ve?(0,K.jsx)(uN,{}):(0,K.jsx)(dN,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-project-title-action`,"data-testid":`code-project-actions`,"aria-label":z.openOptions,title:z.openOptions,onClick:t=>w(t,e.id),children:(0,K.jsx)(pN,{})}),(0,K.jsx)(`button`,{ref:ae,type:`button`,className:`code-project-title-action`,"data-testid":`code-project-new-agent`,"aria-label":z.newAgent,title:z.newAgent,"aria-haspopup":`menu`,"aria-expanded":le?!0:void 0,onClick:Qe,children:(0,K.jsx)(lN,{})})]}),le&&typeof document<`u`&&(0,dj.createPortal)((0,K.jsx)(`div`,{ref:V,className:`code-context-menu code-project-launch-menu`,"data-testid":`code-project-new-agent-menu`,role:`menu`,style:{left:le.x,top:le.y},children:g.map(e=>(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-project-agent-launch-${e.name}`,onClick:()=>$e(e.command||e.name),children:[(0,K.jsx)(m,{name:e.name}),(0,K.jsx)(`span`,{children:c(e.name)})]},e.name))}),document.body),de&&pe&&typeof document<`u`&&(0,dj.createPortal)((0,K.jsx)(oN,{agentId:De,anchorRef:se,copy:z,fallback:pe,point:de,onClose:()=>fe(null),onMountProject:x}),document.body)]}),!t&&(0,K.jsxs)(`div`,{className:`code-project-expanded`,children:[Ie&&(0,K.jsx)(`div`,{ref:ie,className:`code-agents-section`,"data-testid":`code-agents-section`,"data-project-id":e.id,children:(0,K.jsxs)(`div`,{className:`code-agent-list`,children:[!Ve&&(0,K.jsxs)(K.Fragment,{children:[Re?(0,K.jsx)(nN,{agents:Pe,activeTerminalId:i,selectedSearchAgentId:a,claimedAgentSessionKeyByAgentId:s,now:f,onOpenAgent:E,onOpenAgentContextMenu:k,onOpenAgentKeyboardMenu:A,onShowPreview:P,onHidePreview:F}):ze.map(e=>(0,K.jsx)(wN,{agent:e,shortcutHint:u?l.get(e.id):void 0,active:e.id===i,searchSelected:e.id===a,now:f,onOpenAgent:E,onUpdateAgentFlags:D,reorderable:!0,dragging:xe?.agentId===e.id,dropPosition:xe?.targetAgentId===e.id?xe.position:void 0,onAgentDragStart:Ke,onAgentDragEnd:Je,onAgentDragOver:qe,onAgentDrop:Ye,onOpenAgentContextMenu:k,onOpenAgentKeyboardMenu:A,onShowPreview:P,onHidePreview:F,copy:z},Rk({kind:`agent`,agent:e,claimedSessionKey:s.get(e.id)}))),Fe.map(e=>(0,K.jsx)(wN,{session:e,searchSelected:aD(e)===o,now:f,onResume:j,onOpenSessionContextMenu:M,onOpenSessionKeyboardMenu:N,onShowPreview:P,onHidePreview:F,copy:z},Rk({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:()=>b(e.id),children:[(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:z.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>Jj&&(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row code-session-show-more`,"data-testid":`code-session-show-less`,onClick:()=>b(e.id),children:(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:z.showLess})})})]}),!n&&!Ve&&!Re&&Pe.length>Yj&&(0,K.jsxs)(`div`,{className:`code-agent-list-controls`,"data-testid":`code-agent-list-controls`,children:[Be>0&&(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-row code-session-show-more ${xe?.targetAgentId===Xj?`drop-after`:``}`,"data-testid":`code-agent-show-more`,onClick:()=>H(!0),onDragOver:Ze,onDrop:Xe,children:[(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:z.showMore})}),(0,K.jsx)(`span`,{className:`code-agent-row-trailing`,children:(0,K.jsx)(`span`,{className:`code-agent-age`,children:Be})})]}),he&&(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row code-session-show-more`,"data-testid":`code-agent-show-less`,onClick:()=>H(!1),children:(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:z.showLess})})})]})]})}),Oe&&(0,K.jsx)(G.Suspense,{fallback:null,children:(0,K.jsx)(rM,{projectId:e.id,projectWorkspace:e.workspace,agentId:De,agentLaunchOptions:g,activeFilePath:Ae?.file.path,openFiles:je.map(e=>({agentId:e.agentId,workspaceRoot:e.workspaceRoot,key:d(e),path:e.file.path,dirty:e.dirty,externalChanged:e.externalChanged})),revealRequest:_&&U.has(_.agentId)?_:void 0,focusSearchRequest:v&&U.has(v.agentId)?v:void 0,editorDirtyFilePaths:Me,editorExternalChangedFilePaths:Ne,onOpenFile:Ue,onSelectOpenFile:We,onCloseOpenFile:te,onNewAgent:S,onStartAgent:C,onMoveEntries:L,onDeleteEntries:R,onRefreshOpenFiles:ne,onFilesCollapsedChange:Ge,copy:z})})]})]})}function lN(){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 uN(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M2.98444 8.62471L2.98346 8.62815C2.91251 8.8948 2.63879 9.05404 2.37202 8.9833C1.94098 8.86907 2.01687 8.37186 2.01687 8.37186L2.03453 8.31047C2.03453 8.31047 2.06063 8.22636 2.08166 8.1653C2.12369 8.04329 2.18795 7.87274 2.27931 7.66977C2.46154 7.26493 2.75443 6.72477 3.19877 6.18295C4.09629 5.08851 5.60509 4 8.00017 4C10.3952 4 11.904 5.08851 12.8016 6.18295C13.2459 6.72477 13.5388 7.26493 13.721 7.66977C13.8124 7.87274 13.8766 8.04329 13.9187 8.1653C13.9397 8.22636 13.9552 8.27541 13.9658 8.31047C13.9711 8.328 13.9752 8.34204 13.9781 8.35236L13.9816 8.365L13.9827 8.36916L13.9832 8.37069L13.9835 8.37186C14.0542 8.63878 13.8952 8.91253 13.6283 8.9833C13.3618 9.05397 13.0885 8.89556 13.0172 8.62937L13.0169 8.62815L13.0159 8.62471L13.0085 8.5997C13.0014 8.57616 12.9898 8.53927 12.9732 8.49095C12.9399 8.39422 12.8866 8.25227 12.8091 8.08023C12.6538 7.73508 12.4041 7.27523 12.0283 6.81706C11.2857 5.9115 10.0445 5 8.00017 5C5.95584 5 4.71464 5.9115 3.97201 6.81706C3.59627 7.27523 3.34655 7.73508 3.19119 8.08023C3.11375 8.25227 3.06047 8.39422 3.02715 8.49095C3.01051 8.53927 2.9989 8.57616 2.99179 8.5997L2.98444 8.62471ZM8.00024 7C6.61953 7 5.50024 8.11929 5.50024 9.5C5.50024 10.8807 6.61953 12 8.00024 12C9.38096 12 10.5002 10.8807 10.5002 9.5C10.5002 8.11929 9.38096 7 8.00024 7ZM6.50024 9.5C6.50024 8.67157 7.17182 8 8.00024 8C8.82867 8 9.50024 8.67157 9.50024 9.5C9.50024 10.3284 8.82867 11 8.00024 11C7.17182 11 6.50024 10.3284 6.50024 9.5Z`})})}function dN(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M10.1196 10.8267L14.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.85355L4.37624 5.08334C3.90117 5.4183 3.5126 5.80026 3.19877 6.18295C2.75443 6.72477 2.46154 7.26493 2.27931 7.66977C2.18795 7.87274 2.12369 8.04329 2.08166 8.1653C2.06063 8.22636 2.03453 8.31047 2.03453 8.31047L2.01687 8.37186C2.01687 8.37186 1.94098 8.86907 2.37202 8.9833C2.63879 9.05404 2.91251 8.8948 2.98346 8.62815L2.98444 8.62471L2.99179 8.5997C2.9989 8.57616 3.01051 8.53927 3.02715 8.49095C3.06047 8.39421 3.11375 8.25227 3.19119 8.08023C3.34655 7.73507 3.59627 7.27523 3.97201 6.81706C4.26363 6.46146 4.63213 6.10494 5.09595 5.80306L6.67356 7.38067C5.9688 7.82277 5.50024 8.60667 5.50024 9.5C5.50024 10.8807 6.61953 12 8.00024 12C8.89358 12 9.67747 11.5314 10.1196 10.8267ZM9.3807 10.0878C9.15205 10.6241 8.62005 11 8.00024 11C7.17182 11 6.50024 10.3284 6.50024 9.5C6.50024 8.88019 6.87616 8.34819 7.41244 8.11955L9.3807 10.0878ZM6.31962 4.19853L7.174 5.05291C7.43366 5.01852 7.70875 5 8.00017 5C10.0445 5 11.2857 5.9115 12.0283 6.81706C12.4041 7.27523 12.6538 7.73507 12.8091 8.08023C12.8866 8.25227 12.9399 8.39421 12.9732 8.49095C12.9898 8.53927 13.0014 8.57616 13.0085 8.5997L13.0159 8.62471L13.0169 8.62815L13.0172 8.62937C13.0885 8.89555 13.3618 9.05397 13.6283 8.9833C13.8952 8.91253 14.0542 8.63878 13.9835 8.37186L13.9832 8.37069L13.9827 8.36916L13.9816 8.365L13.9781 8.35236C13.9752 8.34204 13.9711 8.328 13.9658 8.31047C13.9552 8.27541 13.9397 8.22636 13.9187 8.1653C13.8766 8.04329 13.8124 7.87274 13.721 7.66977C13.5388 7.26493 13.2459 6.72477 12.8016 6.18295C11.904 5.0885 10.3952 4 8.00017 4C7.38264 4 6.82403 4.07236 6.31962 4.19853Z`})})}function fN(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 pN(){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 mN(e,t,n){return{key:`agent:${e.id}`,title:t.title,project:n||QE(e.projectWorkspace||e.cwd),lastActive:e.lastActivity||e.startedAt||0,provider:$j(e),workspaceRootId:e.workspaceRootId}}function hN(e,t){return{key:`session:${aD(e)}`,title:t.title,project:uD(e),lastActive:dD(e),provider:Qj(e.provider)}}function gN({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:M(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)(_N,{})}),(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)(m,{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)(vN,{})}),(0,K.jsx)(`span`,{children:e.branch||`—`})]})]})}function _N(){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 vN(){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 yN(){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 bN(){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 xN(){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 SN(){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 CN(){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 wN({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:h,onOpenAgentContextMenu:g,onOpenAgentKeyboardMenu:_,onResume:v,onOpenSessionContextMenu:y,onOpenSessionKeyboardMenu:b,onShowPreview:x,onHidePreview:S,copy:C}){let w=(0,G.useRef)(!1),T=Dt(e),E=T?{kind:`agent`,agent:T}:t?{kind:`history`,session:t,fallbackTitle:C.sessionFallbackTitle(t.providerName)}:null;if(!E)return null;let D=Yk(E,a),O=D.requiresResume,k=T?.id??``,A=t?.provider??``,j=t?.id??``,M=O?`code-active-session-row`:`code-agent-row`,N=T?$j(T):Qj(t?.provider),P=()=>{if(O){S?.(),A&&j&&v?.(A,j,t?.providerHomeId);return}k&&o?.(k)};return(0,K.jsxs)(`div`,{tabIndex:0,className:`code-agent-row ${N?`has-provider`:``} ${O?`requires-resume`:``} ${r?`active`:``} ${i?`search-selected`:``} ${D.pinned?`pinned`:``} ${D.unread?`unread`:``} ${l?`dragging`:``} ${u?`drop-${u}`:``}`,draggable:c||void 0,"data-testid":M,"data-agent-id":T?.id,"data-activity-level":T?.activityLevel,"data-provider":t?.provider,"data-session-id":t?aD(t):void 0,"aria-label":D.rowTitle||D.title,onDragStart:e=>{!k||!c||(w.current=!0,d?.(e,k))},onDragEnd:()=>{f?.(),window.setTimeout(()=>{w.current=!1},0)},onDragOver:e=>k&&p?.(e,k),onDrop:e=>k&&h?.(e,k),onClick:e=>{if(w.current){e.preventDefault(),e.stopPropagation();return}P()},onMouseEnter:e=>{T?x?.(e,mN(T,D)):t&&x?.(e,hN(t,D))},onMouseLeave:S,onContextMenu:e=>{if(O){S?.(),A&&t&&y?.(e,A,aD(t));return}k&&g?.(e,k)},onKeyDown:e=>{O?A&&t&&b?.(e,A,aD(t)):k&&_?.(e,k),!e.defaultPrevented&&(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),P())},children:[N&&(0,K.jsx)(`span`,{className:`code-agent-row-provider-icon`,"aria-hidden":`true`,children:(0,K.jsx)(m,{name:N,variant:`color`})}),(0,K.jsxs)(`span`,{className:`code-agent-row-copy ${D.detailLabel?`has-details`:``}`,children:[(0,K.jsx)(`span`,{className:`code-agent-name`,children:D.title}),D.detailLabel&&(0,K.jsx)(`span`,{className:`code-agent-meta`,"data-testid":`code-agent-row-detail`,title:D.detailLabel,children:D.detailLabel})]}),(0,K.jsxs)(`span`,{className:`code-agent-row-trailing`,children:[D.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-agent-dot ${D.lifecycleStatus} ${D.turnActive?`turn-active`:``}`,title:D.commandTitle||D.lifecycleStatus}),D.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)(CN,{})}),D.scheduled&&(0,K.jsx)(`span`,{className:`code-agent-schedule-clock`,"data-testid":`code-agent-schedule-clock`,title:D.scheduleTitle,"aria-label":D.scheduleTitle||C.scheduledTask}),D.unread&&(0,K.jsx)(`span`,{className:`code-agent-unread`,title:C.unread}),D.ageVisible&&(0,K.jsx)(`span`,{className:`code-agent-age code-agent-relative-age`,"data-testid":`code-agent-row-age`,title:D.ageTitle,children:D.ageLabel}),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 ${D.pinned?`active`:``}`,"data-testid":`code-agent-row-pin`,"aria-label":D.pinned?C.unpinAgent:C.pinAgent,title:D.pinned?C.unpinAgent:C.pinAgent,onClick:e=>{e.preventDefault(),e.stopPropagation(),T&&s?.(T,{pinned:!D.pinned})},children:D.pinned?(0,K.jsx)(bN,{}):(0,K.jsx)(yN,{})}),(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:e=>{e.preventDefault(),e.stopPropagation(),T&&s?.(T,{archived:!0})},children:(0,K.jsx)(SN,{})})]}),(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(),O){S?.(),A&&t&&y?.(e,A,aD(t));return}k&&g?.(e,k)},children:(0,K.jsx)(pN,{})}),n&&(0,K.jsx)(`kbd`,{children:n})]})]})}var TN=[`codex`,`claude`,`opencode`,`qoder`],EN=new Set([`bash`,`zsh`]),DN=/^[A-Za-z0-9._-]+$/,ON=[3,5,10,15,30,60,180];function kN(e){let t=e/1e3;return ON.reduce((e,n)=>Math.abs(n-t)<Math.abs(e-t)?n:e)}function AN(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`,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`,updateAction:t?`更新`:`Update`,updateToVersion:e=>t?`更新到 ${e}`:`Update to ${e}`,updating:t?`更新中…`:`Updating…`,checkingUpdates:t?`正在检查更新…`:`Checking for updates…`,currentVersion:t?`当前版本`:`Current`,latestVersion:t?`最新版本`:`Latest`,targetVersion:t?`升级版本`:`Target`,updateSource:t?`更新源`:`Update source`,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||`-`,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 jN(e){return e.trim().toLowerCase()}function MN(e){let t=e&&typeof e==`object`&&!Array.isArray(e)?e:{},n={};return Object.entries(t).forEach(([e,t])=>{let r=jN(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||!DN.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 NN(e){return e===`codex`?`Codex`:e===`claude`?`Claude`:e===`opencode`?`OpenCode`:e===`qoder`?`Qoder`:e}function PN(e){return{codex:`~/.codex`,claude:`~/.claude`,opencode:`~/.opencode`,qoder:`~/.qoder`}[e]??`~/.${e}`}function FN(e){return!!e?.some(e=>e.id.toLowerCase()!==`default`)}function IN(e){return e.filter(e=>e.supported!==!1&&e.interactive!==!1).filter(e=>!EN.has(e.name)).filter(e=>TN.includes(e.name)).map(e=>jN(e.name)).filter(Boolean)}function LN(e,t){let n=new Set(IN(t)),r=Object.keys(e).filter(t=>FN(e[t])),i=new Set([...n,...r]);return Array.from(i).sort((e,t)=>{let n=TN.indexOf(e),r=TN.indexOf(t),i=n===-1?TN.length:n,a=r===-1?TN.length:r;return i===a?e.localeCompare(t):i-a})}function RN(e,t){let n=e[t]??[];return n.some(e=>e.id.toLowerCase()===`default`)?n:[{id:`default`,path:PN(t)},...n]}function zN(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 BN(e){return{provider:e,id:``,path:``}}function VN({open:e,activeAgentId:t=null,language:n,uiPreferences:i,agentLaunchOptions:a,onClose:o,onUpdateUiPreferences:s}){let c=(0,G.useMemo)(()=>AN(n),[n]),l=(0,G.useRef)(null),u=(0,G.useRef)(null),d=(0,G.useRef)(``),[f,p]=(0,G.useState)(!1),[m,h]=(0,G.useState)(``),[g,_]=(0,G.useState)(15),[v,y]=(0,G.useState)(null),[b,x]=(0,G.useState)(``),[S,C]=(0,G.useState)(!1),[w,T]=(0,G.useState)(!1),[E,D]=(0,G.useState)(()=>MN({codex:[{id:`default`,path:`~/.codex`}],claude:[{id:`default`,path:`~/.claude`}],opencode:[{id:`default`,path:`~/.opencode`}],qoder:[{id:`default`,path:`~/.qoder`}]})),[O,k]=(0,G.useState)(!1),[A,j]=(0,G.useState)(!1),[M,N]=(0,G.useState)(``),[P,F]=(0,G.useState)(``),[ee,I]=(0,G.useState)(null),te=(0,G.useCallback)(()=>{k(!0),F(``),fetch(r(`/api/settings`)).then(e=>e.json()).then(e=>{D(MN(e.settings?.agentHomes)),p(e.settings?.dangerouslySkipAgentPermissionsByDefault===!0),h(String(e.settings?.updateUrl??``)),_(kN(Number(e.settings?.searchTimeoutMs??15e3)))}).catch(()=>F(c.loadFailed)).finally(()=>k(!1))},[c.loadFailed]);(0,G.useEffect)(()=>()=>{u.current!==null&&window.clearTimeout(u.current)},[]),(0,G.useEffect)(()=>{e&&(te(),window.requestAnimationFrame(()=>l.current?.focus({preventScroll:!0})))},[te,e]),(0,G.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 L=(0,G.useCallback)(e=>{j(!0),F(``),N(``),fetch(r(`/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);D(MN(n?.settings?.agentHomes??e)),I(null),N(c.saved),window.dispatchEvent(new CustomEvent(`farming-agent-homes-saved`))}).catch(e=>F(e instanceof Error?e.message:c.saveFailed)).finally(()=>j(!1))},[c.saveFailed,c.saved]),R=(0,G.useCallback)((e=!0,t=!1)=>{t||(C(!0),F(``)),fetch(r(`/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;y(n);let r=n?.versions??[];x(e=>e&&r.some(t=>t.assetName===e)?e:r[0]?.assetName||``)}).catch(e=>{t||F(e instanceof Error?e.message:c.loadFailed)}).finally(()=>{t||C(!1)})},[c.loadFailed]),ne=(0,G.useCallback)(()=>{T(!0),F(``),N(``),fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({updateUrl:m})}).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||c.saveFailed);h(String(t?.settings?.updateUrl??``)),N(c.saved),R(!0)}).catch(e=>F(e instanceof Error?e.message:c.saveFailed)).finally(()=>T(!1))},[c.saveFailed,c.saved,R,m]),z=(0,G.useCallback)(e=>{_(e),F(``),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>{fetch(r(`/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);_(kN(Number(n?.settings?.searchTimeoutMs??e*1e3)))}).catch(e=>F(e instanceof Error?e.message:c.saveFailed))},120)},[c.saveFailed]),B=(0,G.useCallback)(()=>{let e=v?.versions?.find(e=>e.assetName===b);if(!e?.available){R(!0);return}C(!0),F(``),N(``),d.current=e.version||e.assetName||``,fetch(r(`/api/update/install`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({assetName:b})}).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}`)}y(e=>({...e??{},state:t?.update?.state??e?.state,blockingAgents:t?.update?.blockingAgents??e?.blockingAgents}))}).catch(e=>{d.current=``,F(e instanceof Error?e.message:c.saveFailed)}).finally(()=>C(!1))},[c,R,b,v]);(0,G.useEffect)(()=>{e&&R(!1)},[e,R]);let re=(0,G.useCallback)(e=>{p(e),j(!0),F(``),N(``),fetch(r(`/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);p(t?.settings?.dangerouslySkipAgentPermissionsByDefault===!0),N(c.saved)}).catch(t=>{p(!e),F(t instanceof Error?t.message:c.saveFailed)}).finally(()=>j(!1))},[c.saveFailed,c.saved]),ie=(0,G.useCallback)(()=>{if(!ee)return;let e=jN(ee.provider),t=ee.path.trim();if(!t){F(c.missingPath);return}let n=E[e]??[],r=ee.id.trim()||zN(t,n).id;if(!DN.test(r)){F(c.invalidId);return}if(n.some(e=>e.id.toLowerCase()===r.toLowerCase())){F(c.duplicateId);return}L({...E,[e]:[...n,{id:r,path:t}]})},[c.duplicateId,c.invalidId,c.missingPath,ee,E,L]),ae=(0,G.useCallback)((e,t)=>{if(t.toLowerCase()===`default`)return;let n=E[e]??[];window.confirm(c.confirmRemove(t))&&L({...E,[e]:n.filter(e=>e.id!==t)})},[c,E,L]),V=v?.state?.phase||``;if((0,G.useEffect)(()=>{if(!e||![`downloading`,`extracting`,`installing`,`restarting`,`rolling-back`].includes(V))return;let t=window.setInterval(()=>R(!1,!0),1500);return()=>window.clearInterval(t)},[e,R,V]),(0,G.useEffect)(()=>{!e||V!==`succeeded`||!d.current||(v?.state?.version||v?.current?.releaseVersion||v?.current?.packageVersion||``)===d.current&&(d.current=``,window.location.reload())},[e,V,v]),!e)return null;let oe=LN(E,a),se=v?.versions??[],ce=se.find(e=>e.assetName===b),le=[`downloading`,`extracting`,`installing`,`restarting`,`rolling-back`].includes(V),ue=S||w||le,de=v?.method||v?.current?.type||``,fe=c.updateMethodLabel(de),pe=de===`app-bundle`||de===`source-deploy`,me=v?.current?.releaseVersion||v?.current?.packageVersion||v?.state?.previousVersion||`-`,he=v?.latest?.version||`-`,H=ce?.version||v?.selected?.version||he,ge=me!==`-`&&H!==`-`&&me!==H&&(v?.available===!0||ue),_e=v?V===`rolled-back`?c.updateRolledBack:V===`failed`&&v?.state?.error?v.state.error:V===`restarting`?c.updateRestarting:[`downloading`,`extracting`,`installing`,`rolling-back`].includes(V)?c.updateInstalling:v.available?c.updateAvailable:V===`succeeded`?c.updateSucceeded:v.latest?.blockedReason||c.upToDate:c.checkingUpdates,ve=le?c.updating:ce?.available&&H!==`-`?c.updateToVersion(H):c.updateAction;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)(we,{})}),(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)(Se,{})})]}),(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)(Oe,{"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(`${r(`/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(ON.length-1),step:`1`,value:ON.indexOf(g),"aria-label":c.searchTimeout,onChange:e=>z(ON[Number(e.target.value)]??15)}),(0,K.jsx)(`output`,{children:c.searchTimeoutValue(g)})]})})]}),(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.updates})})}),(0,K.jsxs)(`div`,{className:`code-settings-update-card ${v?.available?`available`:``}`,"data-testid":`code-settings-update-card`,children:[(0,K.jsxs)(`div`,{className:`code-settings-update-overview`,children:[(0,K.jsxs)(`div`,{className:`code-settings-update-versions`,"aria-label":`${c.currentVersion} ${me}; ${c.latestVersion} ${he}`,children:[(0,K.jsx)(`span`,{children:me}),ge&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{className:`code-settings-update-arrow`,"aria-hidden":`true`,children:`→`}),(0,K.jsx)(`strong`,{children:H})]})]}),(0,K.jsxs)(`div`,{className:`code-settings-update-summary ${v?.available?`available`:``} ${V?`phase-${V}`:``}`,role:`status`,"aria-live":`polite`,children:[de&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{children:fe}),(0,K.jsx)(`span`,{"aria-hidden":`true`,children:` · `})]}),(0,K.jsx)(`span`,{children:_e})]})]}),(0,K.jsxs)(`div`,{className:`code-settings-update-actions`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-settings-update-refresh`,onClick:()=>R(!0),disabled:ue,"aria-label":c.refreshUpdates,title:c.refreshUpdates,children:`↻`}),(0,K.jsx)(`button`,{type:`button`,className:`primary`,"data-testid":`code-settings-update-action`,onClick:B,disabled:ue||!ce?.available,children:ve})]}),pe&&(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:m,placeholder:c.updateUrlPlaceholder,"aria-label":c.updateUrl,onChange:e=>h(e.target.value),disabled:ue})]}),pe&&(0,K.jsx)(`button`,{type:`button`,className:`code-settings-update-save`,onClick:ne,disabled:ue,children:c.saveUpdateUrl}),se.length>1&&(0,K.jsx)(`label`,{className:`code-settings-update-version`,children:(0,K.jsx)(`select`,{value:b,"aria-label":c.targetVersion,onChange:e=>x(e.target.value),disabled:ue||se.length===0,children:se.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.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 ${f?`active`:``}`,role:`checkbox`,"aria-label":c.dangerousSkipLabel,"aria-pressed":f,disabled:A,onClick:()=>re(!f),children:(0,K.jsx)(ke,{})})]})]}),(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})]}),(O||A||M)&&(0,K.jsx)(`span`,{className:`code-settings-status`,children:O?c.loading:A?c.saving:M})]}),P&&(0,K.jsx)(`div`,{className:`code-settings-error`,role:`alert`,children:P}),oe.length===0&&(0,K.jsx)(`div`,{className:`code-agent-home-empty`,children:c.noAgents}),(0,K.jsx)(`div`,{className:`code-agent-homes-list`,children:oe.map(e=>{let t=RN(E,e),n=IN(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:[NN(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:()=>{F(``),N(``),I(BN(e))},"aria-label":c.addHome(NN(e)),title:c.addHome(NN(e)),children:(0,K.jsx)(Ne,{})})]}),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:()=>ae(e,t.id),"aria-label":c.remove,title:c.remove,children:(0,K.jsx)(Se,{})})})]},t.id)),ee&&ee.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:ee.path,placeholder:c.pathPlaceholder,"aria-label":c.homePath,onChange:e=>I(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:ee.id,placeholder:c.homeNamePlaceholder,"aria-label":c.homeName,onChange:e=>I(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:()=>I(null),"aria-label":c.cancel,title:c.cancel,children:(0,K.jsx)(Se,{})}),(0,K.jsx)(`button`,{type:`button`,className:`primary`,disabled:A,onClick:ie,"aria-label":c.save,title:c.save,children:(0,K.jsx)(ke,{})})]})]})]},e)})})]})]})]})})}var HN=`\r`;function UN(e){return[{type:`paste`,text:e},HN]}var WN={newAgent:`New Agent`,search:`Search`,history:`History`,codex:`Farming Code`,expandSidebar:`Expand sidebar`,collapseSidebar:`Collapse sidebar`,enterFocusMode:`Enter focus mode`,exitFocusMode:`Exit focus mode`,appModeOpen:`App mode and fullscreen`,appModeTitle:`Use Farming without browser controls`,appModeDescription:`Install Farming for a clean app window, or use fullscreen temporarily.`,appModeRecommended:`Recommended`,appModeInstallTitle:`Install Farming 2`,appModeInstallDescription:`Opens as its own window without tabs, the address bar, or browser extensions.`,appModeInstallAction:`Install Farming 2`,appModeInstallStepOne:`Open Chrome’s ⋮ menu, then choose “Cast, save and share”.`,appModeInstallStepTwo:`Choose “Install page as app”, then open Farming 2 from its app icon.`,appModeFullscreenTitle:`Fullscreen for now`,appModeFullscreenDescription:`Hide browser controls for this window. Press Esc to leave fullscreen.`,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`,resizeNavigation:`Resize 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`,pinProject:`Pin project`,unpinProject:`Unpin project`,revealInFinder:`Reveal in Finder`,revealInFinderFailed:`Failed to reveal project in Finder`,createPermanentWorktree:`Create permanent worktree`,permanentWorktreeCreated:`Permanent worktree created`,permanentWorktreeFailed:`Failed to create permanent worktree`,markAllAsRead:`Mark all as read`,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`,removeProject:`Remove Project`,deleteWorktree:`Permanently Delete Worktree`,deleteWorktreeQuestion:`Permanently delete worktree?`,deleteWorktreeDescription:`This permanently deletes the worktree and all of its files.`,forceDelete:`Permanently 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…`,terminalProfileApplying:`Applying model to Codex Terminal…`,terminalProfileApplied:`Codex Terminal model updated.`,terminalProfileFailed:e=>`Codex Terminal model was not changed: ${e}`,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`,historyPagination:`History pages`,historyPageStatus:(e,t,n,r)=>`${e} / ${t}${r?`+`:``} · ${n} loaded`,previousPage:`Previous page`,nextPage:`Next page`,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`,showAgents:`Show agents`,hideAgents:`Hide agents`,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`,worktrees:`Worktrees`,showWorktrees:`Show repository worktrees`,worktreeCurrent:`current`,worktreeMain:`main`,worktreeDetached:`detached`,worktreeLocked:`locked`,worktreePrunable:`prunable`,worktreeLoadFailed:`Unable to load repository worktrees`,gitHistory:`History`,gitHistoryEmpty:`No commits yet`,gitHistoryNotRepository:`This project is not a Git repository`,gitHistoryLoadMore:`Load more`,gitHistoryView:`History view`,gitHistoryCurrentScope:`Current`,gitHistoryAllScope:`All`,gitHistoryCurrentBranch:`Current branch`,gitHistoryAllBranches:`All branches`,gitHistoryCommitMessage:`Message`,gitHistoryParent:`Compare with parent`,gitHistoryRootCommit:`Root commit`,gitHistoryReviewCommit:`Review commit`,gitHistoryCommitChanges:e=>`${e} file${e===1?``:`s`} changed`,gitHistoryNoChanges:`No file changes`,gitHistoryChangesTruncated:`More changed files were omitted`,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`,refreshFiles:`Refresh files`,refreshingFiles:`Refreshing files…`,filesRefreshed:`Files refreshed`,filesRefreshFailed:`Files refresh failed`,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`,chooseWorkspaceDirectory:`Choose workspace folder`,workspaceDirectoryBrowserFailed:`Couldn’t read this directory.`,workspaceDirectoryBrowserHostHint:`Browse folders on the Farming host.`,workspaceDirectoryBrowserGo:`Go to directory`,workspaceDirectoryBrowserParent:`Parent directory`,workspaceDirectoryBrowserEmpty:`No subdirectories.`,workspaceDirectoryBrowserTruncated:`Only the first 500 folders are shown. Enter a more specific path to continue.`,workspaceDirectoryBrowserSelect:`Select this folder`,workspaceMissingTitle:`Create this workspace?`,workspaceMissingDescription:`This directory does not exist yet. Farming can create it and start the Agent there.`,workspaceCreateAndStart:`Create & Start`,workspaceCreating:`Creating...`,workspaceCreateFailedTitle:`Couldn’t create workspace`,workspaceCreateForbiddenDescription:`Farming does not have permission to create this directory. Choose another location or update the parent directory permissions.`,workspaceCreateFailedDescription:`Farming couldn’t create this directory. Check the path and try again.`,returnToWorkspace:`Change Path`,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...`},GN={newAgent:`新建 Agent`,search:`搜索`,history:`历史`,codex:`Farming Code`,expandSidebar:`展开侧边栏`,collapseSidebar:`收起侧边栏`,enterFocusMode:`进入沉浸模式`,exitFocusMode:`退出沉浸模式`,appModeOpen:`应用模式与全屏`,appModeTitle:`隐藏浏览器控制`,appModeDescription:`安装 Farming 获得干净的应用窗口,也可以临时进入全屏。`,appModeRecommended:`推荐`,appModeInstallTitle:`安装 Farming 2`,appModeInstallDescription:`以后从独立窗口打开,不显示标签栏、地址栏和浏览器扩展。`,appModeInstallAction:`安装 Farming 2`,appModeInstallStepOne:`打开 Chrome 右上角 ⋮,选择“投放、保存和分享”。`,appModeInstallStepTwo:`选择“将网页安装为应用”,以后从 Farming 2 应用图标打开。`,appModeFullscreenTitle:`暂时全屏`,appModeFullscreenDescription:`只为当前窗口隐藏浏览器控制,按 Esc 即可退出。`,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:`关闭导航`,resizeNavigation:`调整导航宽度`,openOptions:`打开选项`,openSettings:`设置`,agentActions:`Agent 操作`,appearanceLight:`外观:浅色`,appearanceDark:`外观:深色`,languageEnglish:`语言:English`,languageChinese:`语言:中文`,pinAgent:`置顶 Agent`,unpinAgent:`取消置顶`,pinProject:`置顶项目`,unpinProject:`取消置顶项目`,revealInFinder:`在访达中显示`,revealInFinderFailed:`无法在访达中显示项目`,createPermanentWorktree:`创建永久 worktree`,permanentWorktreeCreated:`已创建永久 worktree`,permanentWorktreeFailed:`创建永久 worktree 失败`,markAllAsRead:`全部标为已读`,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:`归档项目`,removeProject:`移除项目`,deleteWorktree:`彻底删除 worktree`,deleteWorktreeQuestion:`彻底删除 worktree?`,deleteWorktreeDescription:`这会彻底删除该 worktree 及其中的所有文件。`,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…`,terminalProfileApplying:`正在应用 Codex Terminal 模型…`,terminalProfileApplied:`Codex Terminal 模型已更新。`,terminalProfileFailed:e=>`Codex Terminal 模型未修改:${e}`,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`,historyPagination:`历史记录分页`,historyPageStatus:(e,t,n,r)=>`第 ${e} / ${t}${r?`+`:``} 页 · 已载入 ${n} 条`,previousPage:`上一页`,nextPage:`下一页`,agentSessions:`Agent 会话`,recentWorkspaces:`最近工作区`,agentsSessionsSummary:(e,t)=>`${e} 个 Agent · ${t} 个会话`,restore:`恢复`,continueRun:`继续`,open:`打开`,archived:`已归档`,pinned:`已置顶`,unread:`未读`,showMore:`显示更多`,showLess:`收起`,showAgents:`展开 Agent`,hideAgents:`隐藏 Agent`,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:`刷新变更`,worktrees:`工作树`,showWorktrees:`查看仓库工作树`,worktreeCurrent:`当前`,worktreeMain:`主工作树`,worktreeDetached:`游离`,worktreeLocked:`已锁定`,worktreePrunable:`可清理`,worktreeLoadFailed:`无法加载仓库工作树`,gitHistory:`历史`,gitHistoryEmpty:`还没有提交`,gitHistoryNotRepository:`当前项目不是 Git 仓库`,gitHistoryLoadMore:`加载更多`,gitHistoryView:`历史视图`,gitHistoryCurrentScope:`当前`,gitHistoryAllScope:`全部`,gitHistoryCurrentBranch:`当前分支`,gitHistoryAllBranches:`所有分支`,gitHistoryCommitMessage:`提交说明`,gitHistoryParent:`与父提交比较`,gitHistoryRootCommit:`根提交`,gitHistoryReviewCommit:`Review 提交`,gitHistoryCommitChanges:e=>`${e} 个文件有变化`,gitHistoryNoChanges:`没有文件变化`,gitHistoryChangesTruncated:`还有部分变更文件未展示`,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:`新建文件夹`,refreshFiles:`刷新文件`,refreshingFiles:`正在刷新文件…`,filesRefreshed:`文件已刷新`,filesRefreshFailed:`文件刷新失败`,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:`/工作区/路径`,chooseWorkspaceDirectory:`选择工作区目录`,workspaceDirectoryBrowserFailed:`无法读取这个目录。`,workspaceDirectoryBrowserHostHint:`浏览 Farming Host 上的目录。`,workspaceDirectoryBrowserGo:`转到目录`,workspaceDirectoryBrowserParent:`上级目录`,workspaceDirectoryBrowserEmpty:`没有子目录。`,workspaceDirectoryBrowserTruncated:`仅显示前 500 个目录,请输入更具体的路径继续浏览。`,workspaceDirectoryBrowserSelect:`选择此目录`,workspaceMissingTitle:`创建这个工作区?`,workspaceMissingDescription:`这个目录尚不存在。Farming 可以创建目录,并在其中启动 Agent。`,workspaceCreateAndStart:`创建并启动`,workspaceCreating:`正在创建…`,workspaceCreateFailedTitle:`无法创建工作区`,workspaceCreateForbiddenDescription:`Farming 没有权限创建这个目录。请选择其他位置,或调整父目录权限。`,workspaceCreateFailedDescription:`Farming 无法创建这个目录。请检查路径后重试。`,returnToWorkspace:`修改路径`,recentWorkspacesLower:`最近工作区`,start:`启动`,back:`返回`,backToAgent:`返回 Agent`,goBack:`后退`,goForward:`前进`,backendConnecting:`正在连接 Farming 后端...`,backendConnectionLost:`Farming 后端连接已断开,正在重连...`,backendHeartbeatLost:`没有收到 Farming 后端心跳,正在等待恢复...`};function KN(e){return e===`zh`?GN:WN}function qN(){return window}function JN(e,t={},n=qN()){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 YN={ask:`Ask for approval`,approve:`Approve for me`,full:`Full access`,custom:`Custom`},XN={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`},ZN=[`ask`,`approve`,`full`,`custom`].map(e=>({value:e,label:YN[e],description:XN[e],color:e===`approve`?`blue`:e===`full`?`orange`:`muted`})),QN={default:`Default`,auto:`Auto`,acceptEdits:`Accept edits`,dontAsk:`Don't ask`,plan:`Plan`,bypassPermissions:`Bypass permissions`},$N={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`},eP=[`default`,`auto`,`acceptEdits`,`dontAsk`,`plan`,`bypassPermissions`].map(e=>({value:e,label:QN[e],description:$N[e],color:e===`bypassPermissions`?`orange`:[`auto`,`acceptEdits`,`plan`].includes(e)?`blue`:`muted`})),tP=[{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`}],nP=`Claude settings`,rP={value:`config`,effort:`config`,label:nP},iP=[{value:`config`,label:nP,displayName:nP,defaultEffort:`config`,reasoningLevels:[rP,...tP],source:`settings`}],aP={available:!1,effectiveModel:``,effectiveEffort:``,modelOptions:[],effortOptions:tP};function oP(e){return!!(e&&e in YN)}function sP(e){return!!(e&&e in QN)}function cP(e,t,n){return e?oP(t)?t:`custom`:n}function lP(e,t,n){return e?sP(t)?t:`default`:n}function uP(e){if(typeof e!=`string`)return``;let t=e.trim();return!t||/[\s\x00-\x1f\x7f]/.test(t)||t.startsWith(`-`)?``:t}function dP(e){return e===`config`?e:uP(e)||`config`}function fP(e){return e&&tP.some(t=>t.value===e)?e:``}function pP(e){return e===`config`?e:fP(e)||`config`}function mP(e){let t=[];return Array.isArray(e)&&e.forEach(e=>{let n=fP(e?.value);n&&t.push({value:n,effort:n,label:e.label||eD(n),description:e.description})}),t.length>0?t:tP}function hP(e){let t=mP(e?.effortOptions),n=uP(e?.effectiveModel),r=fP(e?.effectiveEffort),i=[];return Array.isArray(e?.modelOptions)&&e.modelOptions.forEach(e=>{let n=uP(e?.value);n&&i.push({...e,value:n,label:e.label||n,displayName:e.displayName||n,defaultEffort:fP(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 gP(e,t){let n=t.effortOptions?.length?t.effortOptions:tP,r=t.modelOptions?.length?t.modelOptions:iP.map(e=>({...e})),i=dP(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 _P(e,t){return e===`config`?t.effectiveModel||t.modelOptions?.[0]?.value||`config`:dP(e)}function vP(e,t){return e===`config`?t.effectiveEffort||`config`:pP(e)}function yP(e,t){let n=t.effortOptions?.length?t.effortOptions:tP;return e===`config`?[rP,...n]:n.some(t=>t.value===e)?n:[...n,{value:e,effort:e,label:eD(e)}]}function bP(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:nD(void 0,e),displayName:nD(void 0,e),defaultEffort:t,reasoningLevels:[{value:t,effort:t,label:eD(t)}],serviceTiers:i,source:`pending-catalog`}]}function xP(e){let t=e.agentLaunchProfiles?.codex??{},n=t.approvalMode??e.codexApprovalMode,r=tD(t.modelPreset??e.codexModelPreset),i=t.model||e.codexModel||r.model,a=t.reasoningEffort||e.codexReasoningEffort||r.effort,o=e.agentLaunchProfiles?.claude??{};return{codexApprovalMode:oP(n)?n:`approve`,codexModel:i,codexReasoningEffort:a,codexServiceTier:t.serviceTier||e.codexServiceTier||`default`,codexModelPreset:`${i}:${a}`,claudePermissionMode:sP(o.permissionMode)?o.permissionMode:`default`,claudeModel:dP(o.model),claudeEffort:pP(o.effort)}}function SP(e,t){return!e?.model||!e.reasoningEffort?t:{model:e.model,reasoningEffort:e.reasoningEffort,serviceTier:e.serviceTier||`default`}}function CP({agentKind:e,codexModel:t,codexReasoningEffort:n,codexServiceTier:r,codexModelPreset:i,codexModelOptions:a,codexApprovalMode:o,claudeModel:s,claudeEffort:c,claudeSettings:l,claudePermissionMode:u}){let d=_P(s,l),f=vP(c,l),p=e===`claude`?gP(s,l):e===`codex`?bP(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`?yP(h,l):v?.reasoningLevels?.length?v.reasoningLevels:h?[{value:h,effort:h,label:eD(h)}]:[],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`?eP:ZN,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:nD(v,m),currentReasoningLabel:x?.label??eD(h),currentSpeedLabel:S?.label??``,permissionModeOptions:C,currentPermissionMode:w,currentPermissionOption:T,currentPermissionLabel:T?.label??w,currentPermissionColor:T?.color??`muted`}}function wP(e){return!e.isMain&&e.archived!==!0&&e.status!==`dead`&&e.status!==`stopped`}function TP(e){return!e.isMain&&e.archived===!0}function EP(e,t=[]){let n=new Map;return e.forEach(e=>{if(!wP(e))return;let t=e.providerSessionKey||nk(e.source);t&&n.set(e.id,t)}),n}function DP(e,t){return t.get(e.id)||`agent:${e.id}`}function OP(e){return e.providerSessionKey&&e.providerSessionTemporary!==!0?120:nk(e.source)?100:e.providerSessionKey?40:0}function kP(e){return e.status===`running`?30:e.status===`pending`?20:0}function AP(e,t){return OP(e)+(t.has(e.id)?50:0)+kP(e)}function jP(e,t){let n=new Map;return e.forEach(e=>{let r=DP(e,t),i=n.get(r);if(!i){n.set(r,e);return}let a=AP(e,t),o=AP(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(DP(e,t))===e)}function MP(e,t){return e.filter(e=>!t.has(aD(e)))}function NP(e,t,n){return e.filter(e=>{let r=aD(e);return(e.archived||!t.has(r))&&!n.has(r)})}function PP({allAgents:e,liveAgents:t,sessions:n,mainPageSessionKeys:r}){let i=t.filter(wP),a=EP(i,n),o=new Set(a.values()),s=jP(i,a),c=n.filter(e=>!e.archived&&r.has(aD(e))).sort(fD),l=MP(c,o),u=MP(n,o).sort(fD),d=NP(n,r,o).sort(fD);return{liveAgents:s,archivedAgents:e.filter(TP).sort((e,t)=>(t.archivedAt??0)-(e.archivedAt??0)),mainPageAgentSessions:c,sidebarAgentSessions:l,searchableAgentSessions:u,historyAgentSessions:d,claimedAgentSessionKeys:o,claimedAgentSessionKeyByAgentId:a}}function FP(){return{activeFile:null,files:[],closedFileCache:new Map}}function IP(e){return{activeFile:e.activeFile,files:e.files,closedFileCache:e.closedFileCache}}function LP(){let[e,t]=(0,G.useState)(()=>FP()),n=(0,G.useRef)(e),r=(0,G.useCallback)(e=>(n.current=IP(e),t(n.current),n.current),[]),i=(0,G.useCallback)((e,t,i)=>r(R(n.current,e,t,i)),[r]),a=(0,G.useCallback)((e,t,i)=>{let a=_(n.current,e,t,i);return a?r(a):null},[r]),o=(0,G.useCallback)(e=>{let t=v(n.current,e);return t.closedFiles.length>0&&r(t),t},[r]),s=(0,G.useCallback)(e=>{let t=u(n.current,{canReopen:e});return t?r(t):null},[r]),c=(0,G.useCallback)(e=>r(O(n.current,e)),[r]),d=(0,G.useCallback)((e,t)=>r(g(n.current,e,t)),[r]),f=(0,G.useCallback)(e=>{let t=n.current.activeFile;if(!t)return null;let i=l(t,e);return r({...n.current,activeFile:i,files:L(n.current.files,i)})},[r]),p=(0,G.useCallback)((e,t)=>{let i=b(n.current,e,t);return i!==n.current&&r(i),i},[r]),m=(0,G.useCallback)((e,t)=>{let i=te(n.current,e,t);return t.length>0&&r(i),i},[r]),h=(0,G.useMemo)(()=>Array.from(e.closedFileCache.values()),[e.closedFileCache]);return(0,G.useMemo)(()=>({activeFile:e.activeFile,files:e.files,closedFiles:h,openFromRead:i,select:a,close:o,reopenLastClosed:s,update:c,refreshFromReads:d,updateDraft:f,move:p,deleteEntries:m}),[h,o,m,p,i,d,s,a,e.activeFile,e.files,c,f])}function RP(){let[e,t]=(0,G.useState)(()=>Rn()),n=(0,G.useRef)(e),r=(0,G.useRef)(!1),i=(0,G.useRef)(null),a=(0,G.useCallback)(e=>(n.current=e,t(e),e),[]),o=(0,G.useCallback)(e=>{r.current||a(Un(n.current,e))},[a]),s=(0,G.useCallback)(e=>{o(zn(e))},[o]),c=(0,G.useCallback)(e=>{o(Bn(e))},[o]),l=(0,G.useCallback)(e=>{r.current||(i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{i.current=null,o(Bn({...e,reason:`cursor`}))},650))},[o]),u=(0,G.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,G.useCallback)(()=>{window.setTimeout(()=>{r.current=!1},120)},[]),f=(0,G.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,G.useEffect)(()=>()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null)},[]),(0,G.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 zP({agents:e,permissionSwitchReplacement:t,onDiscardAttachment:n}){let[r,i]=(0,G.useState)({});(0,G.useLayoutEffect)(()=>{let r=new Set(e.filter(e=>!e.archived&&e.status!==`dead`&&e.status!==`stopped`).flatMap(e=>[CA(e),ZA(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?xA(i,n):n,delete r[e]};e(t.originalAgentId,t.replacementAgentId),e(`acp:${t.originalAgentId}`,`acp:${t.replacementAgentId}`)}return e.forEach(e=>{let t=CA(e);if(!t)return;wA(e).forEach(e=>{if(e===t)return;let n=a[e];if(!n)return;let r=s();r[t]=r[t]?xA(r[t],n):n,delete r[e]});let n=ZA(e);QA(e).forEach(e=>{if(e===n)return;let t=a[e];if(!t)return;let r=s();r[n]=r[n]?xA(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,G.useCallback)(t=>{if(!t)return``;for(let n of e){let e=$A(t),r=e?ZA(n):CA(n);if(!r)continue;let i=e?QA(n):wA(n);if(t===r||i.includes(t))return r}return t},[e]);return{composerByAgentKey:r,updateComposerStateForKey:(0,G.useCallback)((e,t)=>{i(n=>{let r=a(e);if(!r)return n;let i=n[r]??gA(),o=t(i);return o===i?n:{...n,[r]:o}})},[a]),updateExistingComposerStateForKey:(0,G.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 BP(){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 VP(e){return e.replace(/^Language:\s*/i,``).replace(/^语言[::]\s*/,``)}function HP(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 UP(e){return e.replace(/^Appearance:\s*/i,``).replace(/^外观[::]\s*/,``)}function WP(e,t){return e.size===t.length?t.every(t=>e.has(t)):!1}function GP(e){return(e.ctrlKey||e.metaKey)&&e.shiftKey&&!e.altKey&&e.key.toLowerCase()===`t`}var KP=296,qP=220,JP=840,YP=360,XP=5*6e4,ZP=52,QP=172,$P=900,eF=12,tF=4,nF=15e3,rF=286,iF=60,aF=1e3,oF=150,sF=35e3;async function cF(e,t){let n=[],r=!0,i=0,a=Array.from({length:Math.min(tF,t.length)},async()=>{for(;i<t.length;){let a=t[i];i+=1;let o=new AbortController,s=window.setTimeout(()=>o.abort(),nF);try{n.push(await le(e,a,{signal:o.signal}))}catch{r=!1}finally{window.clearTimeout(s)}}});return await Promise.all(a),{files:n,successful:r}}function lF(){return typeof window>`u`?!1:oe()&&re()}function uF(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 dF(e){return!!(e&&Dk(e.command)===`codex`&&e.runtimeBinding.kind===`terminal`)}function fF(e){return e instanceof HTMLElement?e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable:!1}function pF(e){return tk(e)}function mF(e){return e.kind===`agent-session`?aD(e):YE(e)}function hF(){return oe()}function gF(e){return!hF()&&e>0&&e<$P}function _F(){return hF()?!0:typeof window<`u`&&gF(window.innerWidth)}function vF(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}function yF(e){let t=(e||``).replace(/\/+$/,``);return t.split(`/`).filter(Boolean).pop()||t||`workspace`}function bF(e){if(e.lineNumber)return{lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn}}function xF(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 SF(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 CF(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 wF({agents:e,taskHistory:t,mainPageSessionKeys:n,activeView:i,dialogOpen:a,usageSummary:o,contextWindowByAgentId:s={},activeTerminalId:c,permissionSwitchingAgentId:l,agentSwitchingKind:u,permissionSwitchReplacement:m,openTerminalIds:g,terminalFocusRequest:_,keyMap:v,keyboardShortcutsEnabled:y,uiPreferences:b,onOpenTerminal:C,onOpenTerminalWhenReady:E,onNewAgent:O,onStartAgent:M,onRenameAgent:N,onUpdateAgentFlags:F,onOpenArchivedAgent:te,onForkAgent:L,onDeleteForkWorktreeProject:R,onRestartMainAgent:ne,onWorkspaceViewChange:z,onKill:B,onInterruptAgent:re,sendComposerInput:ae,respondToAppServerRequest:se,onSessionOutput:ce,onUpdateUiPreferences:ue}){An(`codeWorkspace`);let fe=It(),{composerByAgentKey:pe,updateComposerStateForKey:me,updateExistingComposerStateForKey:he}=zP({agents:e,permissionSwitchReplacement:m,onDiscardAttachment:IA}),H=(0,G.useRef)({}),ge=(0,G.useRef)({}),[,_e]=(0,G.useState)({}),[ve,ye]=(0,G.useState)(`terminal`),[be]=(0,G.useState)(()=>j().surface),xe=(0,G.useRef)(!1),Se=(0,G.useRef)(!be),Ce=LP(),{canGoBack:we,canGoForward:Te,recordAgent:Ee,recordFile:De,recordFileCursor:Oe,beginNavigation:U,finishNavigation:ke,pruneEntries:Ae}=RP(),W=Ce.activeFile,je=Ce.files,Me=(0,G.useCallback)(async(e,t)=>{let n=Array.from(new Set(Ce.files.filter(e=>e.workspaceRoot===t).map(e=>e.file.path)));if(n.length===0)return!0;let r=await cF(e,n);return Ce.refreshFromReads(t,r.files),r.successful},[Ce]),[Ne,Pe]=(0,G.useState)(!1),[Fe,Ie]=(0,G.useState)(``),[ze,Ve]=(0,G.useState)(0),[,He]=(0,G.useState)([]),[Ue,We]=(0,G.useState)([]),[Ge,Ke]=(0,G.useState)(!1),qe=(0,G.useRef)([]),Je=(0,G.useRef)(0),Ye=(0,G.useRef)(Promise.resolve()),[Xe,Ze]=(0,G.useState)([]),Qe=(0,G.useRef)([]),$e=(0,G.useRef)(0),et=(0,G.useRef)(Promise.resolve()),tt=(0,G.useRef)(new Set),[nt,rt]=(0,G.useState)({}),[it,at]=(0,G.useState)([]),[ot,st]=(0,G.useState)(()=>new Set),[ct,lt]=(0,G.useState)(`approve`),[,ut]=(0,G.useState)(`gpt-5.5:xhigh`),[dt,ft]=(0,G.useState)(`gpt-5.5`),[pt,mt]=(0,G.useState)(`xhigh`),[ht,gt]=(0,G.useState)(`default`),[_t,vt]=(0,G.useState)([]),[yt,bt]=(0,G.useState)(()=>new Set),[xt,St]=(0,G.useState)(()=>new Map),Ct=(0,G.useRef)(new Set),[wt,Tt]=(0,G.useState)(`default`),[Et,Dt]=(0,G.useState)(`config`),[kt,At]=(0,G.useState)(`config`),[jt,Mt]=(0,G.useState)(aP),[Nt,Pt]=(0,G.useState)([]),[Ft,Lt]=(0,G.useState)([]),[Bt,Vt]=(0,G.useState)(``),[Ut,Wt]=(0,G.useState)(!1),[Gt,Kt]=(0,G.useState)([]),[qt,Yt]=(0,G.useState)(!1),Xt=(0,G.useRef)(!1),Zt=(0,G.useRef)(null),Qt=(0,G.useRef)(iF),[en,tn]=(0,G.useState)(()=>XO().pinnedOverrides),[nn,rn]=(0,G.useState)(!1),[an,on]=(0,G.useState)(!1),[sn,cn]=(0,G.useState)(()=>new Set),[ln,un]=(0,G.useState)(()=>new Set),[dn,fn]=(0,G.useState)(KP),[pn,mn]=(0,G.useState)(()=>_F()),[hn,gn]=(0,G.useState)(()=>typeof window>`u`?null:A(window.location.search)),[_n,vn]=(0,G.useState)(0),[yn,bn]=(0,G.useState)(void 0),[xn,Sn]=(0,G.useState)(null),[wn,Dn]=(0,G.useState)(null),[On,kn]=(0,G.useState)(null),[jn,Mn]=(0,G.useState)(null),[Nn,Pn]=(0,G.useState)(!1),[Rn,zn]=(0,G.useState)(``),[Bn,Vn]=(0,G.useState)(null),[Hn,Un]=(0,G.useState)(null),[Gn,Kn]=(0,G.useState)(null),[qn,Jn]=(0,G.useState)(null),[Yn,Xn]=(0,G.useState)(null),[Zn,Qn]=(0,G.useState)(null),$n=Bn?Bn.kind===`agent`?`agent:${Bn.agentId}`:`project:${Bn.projectId}`:``,[er,q]=(0,G.useState)(Date.now()),tr=(0,G.useRef)(null),nr=(0,G.useRef)(null),rr=(0,G.useRef)([]),ir=(0,G.useRef)(null),ar=(0,G.useRef)(null),or=(0,G.useRef)(null),sr=(0,G.useRef)(null),cr=(0,G.useRef)(null),lr=(0,G.useRef)(null),ur=(0,G.useRef)(null),dr=(0,G.useRef)(null),fr=(0,G.useRef)(null),pr=(0,G.useRef)(null),mr=(0,G.useRef)(null),hr=(0,G.useRef)(null),gr=(0,G.useRef)(null),_r=(0,G.useRef)(!1),vr=(0,G.useRef)(0),yr=(0,G.useRef)(null),br=(0,G.useRef)(0),xr=(0,G.useRef)(!1),Sr=(0,G.useRef)(()=>{}),Cr=(0,G.useRef)(c),wr=(0,G.useRef)(0),Tr=(0,G.useRef)(0),Er=(0,G.useRef)(0),Dr=(0,G.useRef)(0),Or=(0,G.useRef)(0),kr=(0,G.useRef)(0),Ar=(0,G.useRef)(null),jr=(0,G.useRef)(null),Mr=(0,G.useRef)(null),Nr=(0,G.useRef)(0),Pr=(0,G.useRef)(new Set),Fr=(0,G.useRef)(!1),Ir=(0,G.useRef)(pn),Lr=(0,G.useRef)(hF()),Rr=(0,G.useCallback)(()=>{Ir.current=!1,mn(!0)},[]),zr=(0,G.useCallback)(()=>{mn(e=>(e||(Ir.current=!0),!0))},[]),Br=(0,G.useCallback)(()=>{Ir.current=!1,mn(!1)},[]),Vr=(0,G.useCallback)(()=>{Ir.current=!1,mn(e=>!e)},[]);Cr.current=c;let J=(0,G.useMemo)(()=>KN(b.language),[b.language]);(0,G.useEffect)(()=>{ZO({promotedKeys:[],pinnedOverrides:en,archivedOverrides:{}})},[en]);let Hr=(0,G.useMemo)(()=>e.filter(e=>!e.isMain),[e]),Ur=(0,G.useMemo)(()=>e.find(e=>e.isMain)??null,[e]),Y=(0,G.useMemo)(()=>Hr.filter(wP),[Hr]),Wr=(0,G.useMemo)(()=>{let e=new Set(Y.map(e=>e.id));return Ur&&e.add(Ur.id),e},[Y,Ur]),Gr=(0,G.useMemo)(()=>{let e=new Set([Be]);return Ue.forEach(t=>e.add(Fn(t))),Y.forEach(t=>e.add(Fn(ZE(t)))),Wr.forEach(t=>e.add(t)),e},[Y,Ue,Wr]);(0,G.useEffect)(()=>{Ae(e=>e.kind===`agent`?Wr.has(e.agentId):Gr.has(e.agentId))},[Ae,Wr,Gr]);let Kr=(0,G.useCallback)((e,t)=>{let n=Ur?[...Y,Ur]:Y;if(Le(e)){let e=n.find(e=>e.id===t);return{filesId:Be,workspaceRoot:`/`,sourceAgentId:e?.id,sourceAgent:e}}let r=In(e);if(r){let e=Y.find(e=>e.id===t&&Fn(ZE(e))===Fn(r));return{filesId:Fn(r),workspaceRoot:r,sourceAgentId:e?.id,sourceAgent:e}}let i=n.find(t=>t.id===e);if(i&&!i.isMain){let e=ZE(i),n=Y.find(n=>n.id===t&&Fn(ZE(n))===Fn(e))??i;return{filesId:Fn(e),workspaceRoot:e,sourceAgentId:n.id,sourceAgent:n}}return{filesId:e,workspaceRoot:i?ZE(i):void 0,sourceAgentId:i?.id,sourceAgent:i}},[Y,Ur]);(0,G.useEffect)(()=>{W?.sourceAgentId&&(Kr(W.agentId,W.sourceAgentId).sourceAgentId||Ce.update({...W,sourceAgentId:void 0}))},[W,Kr,Ce]);let qr=(0,G.useMemo)(()=>$O(Ft,en,{}),[en,Ft]),Jr=(0,G.useMemo)(()=>PP({allAgents:Hr,liveAgents:Y,sessions:qr,mainPageSessionKeys:ot}),[Y,qr,ot,Hr]),Yr=Jr.mainPageAgentSessions,Xr=Jr.sidebarAgentSessions,Zr=Jr.searchableAgentSessions,Qr=Jr.historyAgentSessions,$r=Jr.liveAgents,ei=Jr.archivedAgents,ti=t,ni=Qr,ri=(0,G.useMemo)(()=>new Set(Gt.map(aD)),[Gt]),ii=(0,G.useMemo)(()=>new Set(Array.from(Jr.claimedAgentSessionKeyByAgentId.entries()).filter(([,e])=>ri.has(e)).map(([e])=>e)),[Jr.claimedAgentSessionKeyByAgentId,ri]),ai=(0,G.useMemo)(()=>{let e=new Map(Zr.map(e=>[aD(e),e]));return Gt.forEach(t=>e.set(aD(t),t)),MP(Array.from(e.values()),Jr.claimedAgentSessionKeys)},[Jr.claimedAgentSessionKeys,Gt,Zr]),oi=(0,G.useMemo)(()=>Gj($r,Xr,nt,je,Hr,Ue,Xe),[je,Xe,nt,Ue,Xr,Hr,$r]),si=(0,G.useMemo)(()=>rk(oi,ln,!1),[ln,oi]),ci=(0,G.useMemo)(()=>Gj($r,ai,nt,je,Hr,Ue,Xe),[je,Xe,nt,Ue,ai,Hr,$r]),li=Fe.trim().toLowerCase(),ui=li.length>0,di=(0,G.useMemo)(()=>Kj((i===`search`||Ne)&&ui?ci:si,li,ln,ri,ii),[i,ln,ui,li,si,ci,ii,ri,Ne]),fi=si.some(e=>!!e.workspace),pi=(0,G.useMemo)(()=>ui?di:[],[di,ui]),mi=(0,G.useMemo)(()=>qj(di,sn,li),[sn,di,li]),hi=(0,G.useMemo)(()=>ui?mi:[],[ui,mi]),gi=(0,G.useMemo)(()=>{let e=new Map;return y&&v.forEach((t,n)=>{e.set(t,n)}),e},[v,y]),_i=(0,G.useMemo)(()=>g.map(e=>Y.find(t=>t.id===e)??(Ur?.id===e?Ur:null)).filter(e=>!!e),[Y,Ur,g]),vi=Ot((0,G.useMemo)(()=>_i.find(e=>e.id===c)??_i[0]??null,[c,_i])),yi=vi?[vi]:[],X=Ot((0,G.useMemo)(()=>Y.find(e=>e.id===c)??(Ur?.id===c?Ur:null),[Y,c,Ur])),bi=Cn(X)?X.runtimeBinding:null,xi=Tn(X)?X.runtimeBinding:null,Si=!!(X&&X.id===l),Ci=!!(X&&yt.has(X.id)),wi=X?s[X.id]??null:null,Ti=bi?ZA(X):X?CA(X):``,Ei=(0,G.useMemo)(()=>Pk(X),[X]),Di=Ti?pe[Ti]??(X?(bi?QA(X):wA(X)).map(e=>pe[e]).find(Boolean):void 0)??hA:hA,Oi=Di.draft,ki=Di.attachments,Ai=Di.mode,{plusMenuOpen:ji,approvalMenuOpen:Mi,modelMenuOpen:Ni,modelPickerPane:Pi}=Di.ui,Fi=!!(bi&&X&&ge.current[X.id]!==void 0),Ii=(0,G.useMemo)(()=>Fi||WE(X),[Fi,X]),Li=(0,G.useMemo)(()=>HE(X),[X]),Ri=Ei.kind,zi=(0,G.useMemo)(()=>cP(!!(X&&Ri===`codex`),X?.launchPermissionMode,ct),[X,ct,Ri]),Bi=(0,G.useMemo)(()=>lP(!!(X&&Ri===`claude`),X?.launchPermissionMode,wt),[X,wt,Ri]),Vi=X&&xt.get(X.id)||null,Hi=(0,G.useMemo)(()=>SP(Vi||X?.codexTerminalProfile,{model:dt,reasoningEffort:pt,serviceTier:ht}),[Vi?.model,Vi?.reasoningEffort,Vi?.serviceTier,X?.codexTerminalProfile?.model,X?.codexTerminalProfile?.reasoningEffort,X?.codexTerminalProfile?.serviceTier,dt,pt,ht]),Ui=Hi.model,Wi=Hi.reasoningEffort,Gi=Hi.serviceTier,Ki=`${Ui}:${Wi}`,qi=(0,G.useMemo)(()=>Ii||!!X&&X?.status===`running`&&Ri===`shell`&&Li.terminalBusy,[X,Li.terminalBusy,Ii,Ri]),Z=(0,G.useMemo)(()=>Nk([...Mk(Ri),...Nt]),[Ri,Nt]),Ji=Di.pendingFollowUp;(0,G.useEffect)(()=>{!c||ve!==`terminal`||i!==`projects`||Ee(c)},[c,i,ve,Ee]),(0,G.useEffect)(()=>{!W||ve!==`editor`||i!==`projects`||De({agentId:W.agentId,filePath:W.file.path,view:W.diffRequestId?`diff`:`editor`,lineNumber:W.cursor?.lineNumber,column:W.cursor?.column,endColumn:W.cursor?.endColumn,sourceAgentId:W.sourceAgentId})},[i,ve,W?.agentId,W?.cursor?.column,W?.cursor?.endColumn,W?.cursor?.lineNumber,W?.cursor?.requestId,W?.diffRequestId,W?.file.path,W?.sourceAgentId,De]);let Yi=LA(ki).length>0,Xi=ki.some(e=>e.status===`uploading`),Zi=Ci?`disabled`:X&&!Xi&&(Oi.trim()||Yi)?`send`:qi?`interrupt`:`disabled`,Qi=bi?Zi:`disabled`,$i=(0,G.useCallback)(e=>{Ti&&me(Ti,e)},[Ti,me]),ea=(0,G.useCallback)(()=>{$i(yA)},[$i]),ta=(0,G.useMemo)(()=>Y.find(e=>e.id===xn?.agentId)??null,[Y,xn?.agentId]),na=(0,G.useMemo)(()=>oi.find(e=>e.id===wn?.projectId)??null,[oi,wn?.projectId]),ra=(0,G.useMemo)(()=>di.flatMap(e=>e.agentSessions).find(e=>e.provider===On?.provider&&aD(e)===On?.sessionId)??null,[On?.provider,On?.sessionId,di]),ia=Ne?hi[ze]??null:null,aa=ia?.kind===`agent`?ia.id:null,oa=ia?.kind===`agent-session`?aD(ia):null,sa=X?ZE(X):void 0,ca=(0,G.useMemo)(()=>{if(W&&!Le(W.agentId))return W.agentId;if(X&&!X.isMain)return Fn(ZE(X));if(sa)return Fn(sa);let e=Y.find(e=>!e.isMain);return e?Fn(ZE(e)):null},[X,Y,sa,W]),la=(0,G.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 Fn(ZE(e))}let n=e.closest(`[data-testid="code-project-group"]`)?.querySelector(`[data-testid="code-project-title"][data-project-id]`)?.dataset.projectId;return!n||n===`__farming_main_agent__`?null:Fn(n)},[Y]),ua=X?.isMain?yn??si[0]?.workspace:sa??yn??si[0]?.workspace,da=ve===`editor`&&!!W,fa=(0,G.useMemo)(()=>{if(da&&W){let e=W.workspaceRoot??Y.find(e=>e.id===W.agentId)?.projectWorkspace??Y.find(e=>e.id===W.agentId)?.cwd??``;return{kind:`file`,agentId:W.agentId,filePath:W.file.path,...e?{absolutePath:w(e,W.file.path)}:{},...e?{projectLabel:P(e)}:{},view:W.diffRequestId?`diff`:`editor`,lineNumber:W.cursor?.lineNumber,column:W.cursor?.column,endColumn:W.cursor?.endColumn}}return c&&Wr.has(c)?{kind:`agent`,agentId:c,readingSurface:En(Y.find(e=>e.id===c))?`chat`:`terminal`}:null},[c,W?.agentId,W?.cursor?.column,W?.cursor?.endColumn,W?.cursor?.lineNumber,W?.diffRequestId,W?.file.path,W?.workspaceRoot,da,Y,Wr]),{agentModelOptions:pa,agentModel:ma,agentReasoningEffort:ha,agentServiceTier:ga,agentModelPreset:_a,currentReasoningOptions:va,currentServiceTierOptions:ya,currentPermissionMode:ba,currentPermissionLabel:xa,currentPermissionColor:Sa,currentModelLabel:Ca,currentReasoningLabel:wa,currentSpeedLabel:Ta,permissionModeOptions:Ea}=(0,G.useMemo)(()=>CP({agentKind:Ri,codexModel:Ui,codexReasoningEffort:Wi,codexServiceTier:Gi,codexModelPreset:Ki,codexModelOptions:_t,codexApprovalMode:zi,claudeModel:Et,claudeEffort:kt,claudeSettings:jt,claudePermissionMode:Bi}),[kt,Et,jt,Bi,zi,Ui,_t,Ki,Wi,Gi,Ri]),Da=BP(),Oa=Ne||i===`search`?J.search:i===`history`?J.history:da&&W?XE(W.file.path):X?ee(X):J.codex,ka=X?.isMain?`farming`:yF(X?ZE(X):void 0),Aa=X?`${ka} · ${Da}`:Da,ja=da&&W?W.sourceAgentId:null,Ma=!!ja,Na=(0,G.useCallback)(()=>{let e=nr.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`},[]),Pa=(0,G.useCallback)(()=>{let e=!1;JN(()=>{if(document.querySelector(`.code-composer-menu`))return;let t=nr.current??document.querySelector(`[data-testid="code-composer-input"]`);e&&document.activeElement instanceof HTMLElement&&document.activeElement!==document.body&&document.activeElement!==t||(t?.focus({preventScroll:!0}),document.activeElement===t&&(e=!0))},{delays:[60]})},[]),Fa=(0,G.useCallback)(e=>{let t=xP(e);lt(t.codexApprovalMode),ft(t.codexModel),mt(t.codexReasoningEffort),gt(t.codexServiceTier),ut(t.codexModelPreset),Tt(t.claudePermissionMode),Dt(t.claudeModel),At(t.claudeEffort)},[]),Ia=(0,G.useCallback)(()=>{let e=!1,t=Nr.current;return fetch(r(`/api/settings`)).then(e=>e.json()).then(n=>{if(e)return;let r=n.settings??{};t===Nr.current&&st(new Set(QO(r.mainPageSessionKeys??[]))),We(Ln(r.projectWorkspaces)),Ze(Ln(r.pinnedProjectWorkspaces)),Ke(!0),rt(HP(r.projectNames)),Fa(r)}).catch(()=>{}),()=>{e=!0}},[Fa]),La=(0,G.useCallback)(()=>{let e=Date.now()-br.current;if(xr.current||br.current>0&&e<=XP)return()=>{};let t=!1;return xr.current=!0,fetch(r(`/api/codex/models`)).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error||`Failed to load Codex model catalog (${e.status})`);return t}).then(e=>{if(t)return;let n=iD(e);if(n.length===0)throw Error(`Codex model catalog did not contain any visible models`);br.current=Date.now(),vt(n)}).catch(e=>{t||(br.current=0,vt([]),Jn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:`Failed to load Codex model catalog`}))}).finally(()=>{xr.current=!1}),()=>{t=!0}},[]),Ra=(0,G.useCallback)(()=>{let e=!1;return fetch(r(`/api/claude/settings`)).then(e=>e.json()).then(t=>{e||Mt(hP(t.settings))}).catch(()=>{e||Mt(aP)}),()=>{e=!0}},[]),za=(0,G.useCallback)(async(e,t)=>{let n=new URLSearchParams({q:e,limit:String(aF),fresh:`1`}),i=await fetch(r(`/api/agent-sessions/search?${n.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:[]},[]),Ba=(0,G.useCallback)(async(e,t)=>NP($O(await za(e,t),en,{}),ot,Jr.claimedAgentSessionKeys),[Jr.claimedAgentSessionKeys,en,za,ot]),Va=(0,G.useCallback)(async(e={})=>{let t=new URLSearchParams({limit:String(e.limit||iF)});e.cursor&&t.set(`cursor`,e.cursor),e.fresh&&t.set(`fresh`,`1`);let n=await(await fetch(r(`/api/agent-sessions?${t.toString()}`),{cache:e.fresh?`no-store`:`default`})).json();return{sessions:Array.isArray(n.sessions)?n.sessions:[],nextCursor:typeof n.nextCursor==`string`?n.nextCursor:``,hasMore:n.hasMore===!0}},[]),Ha=(0,G.useCallback)((e=!1)=>{let t=!1;return Va({fresh:e}).then(e=>{t||(Lt(e.sessions),Vt(e.nextCursor),Wt(e.hasMore),Qt.current=Math.max(iF,e.sessions.length))}).catch(()=>{t||(Lt([]),Vt(``),Wt(!1))}),()=>{t=!0}},[Va]),Ua=(0,G.useCallback)(()=>{if(Zt.current)return Zt.current;let e=Va({limit:Qt.current,fresh:!0}).then(e=>{Lt(e.sessions),Vt(e.nextCursor),Wt(e.hasMore)}).catch(()=>Lt([])).finally(()=>{Zt.current===e&&(Zt.current=null)});return Zt.current=e,e},[Va]),Wa=(0,G.useCallback)(async()=>{if(!Ut||!Bt||Xt.current)return!1;Xt.current=!0;try{let e=await Va({cursor:Bt});return Lt(t=>{let n=new Set(t.map(aD)),r=[...t];return e.sessions.forEach(e=>{let t=aD(e);n.has(t)||(n.add(t),r.push(e))}),Qt.current=Math.max(iF,r.length),r}),Vt(e.nextCursor),Wt(e.hasMore),e.sessions.length>0}catch{return!1}finally{Xt.current=!1}},[Bt,Ut,Va]);(0,G.useEffect)(()=>{if(!((i===`search`||Ne)&&ui)){Kt([]),Yt(!1);return}let e=new AbortController;Kt([]),Yt(!0);let t=window.setTimeout(()=>{za(li,e.signal).then(Kt).catch(e=>{e instanceof DOMException&&e.name===`AbortError`||Kt([])}).finally(()=>{e.signal.aborted||Yt(!1)})},oF);return()=>{window.clearTimeout(t),e.abort()}},[i,za,ui,li,Ne]);let Ga=(0,G.useCallback)((e,t)=>{if(e!==`codex`&&e!==`claude`)return Pt([]),()=>{};let n=!1,i=new URLSearchParams({provider:e});return t&&i.set(`workspace`,t),fetch(r(`/api/slash-commands?${i.toString()}`)).then(e=>e.json()).then(e=>{n||Pt(Array.isArray(e.commands)?e.commands:[])}).catch(()=>{n||Pt([])}),()=>{n=!0}},[]),Ka=(0,G.useCallback)(()=>{Ti&&($i(e=>({...e,ui:{...e.ui,plusMenuOpen:!1}})),ir.current?.click())},[Ti,$i]),qa=(0,G.useCallback)((e,t)=>{let n=PA(t),r=AA(t,`pasted image`),i=FA(t),a={id:n,kind:`image`,name:r,type:t.type||`image/png`,size:t.size,status:`uploading`,previewUrl:i};me(e,e=>({...e,attachments:[...e.attachments,a]})),HA(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:NA({...t,name:r}),error:void 0}:e)}))}).catch(()=>{he(e,e=>({...e,attachments:e.attachments.map(e=>e.id===n?{...e,status:`error`,messageBlock:WA(t),error:`Upload failed`}:e)}))})},[me,he]),Ja=(0,G.useCallback)(async e=>{if(!Ti||e.length===0)return;e.filter(jA).forEach(e=>qa(Ti,e));let t=e.filter(e=>!jA(e));if(t.length===0){Pa();return}let n=[];for(let e of t)try{n.push(await UA(e))}catch{n.push(WA(e))}me(Ti,e=>({...e,draft:kA(e.draft,n.join(`
|
|
205
205
|
|
|
206
|
-
`))})),Pa()},[Ti,qa,Pa,me]),Ya=(0,G.useCallback)(e=>{$i(t=>{let n=t.attachments.find(t=>t.id===e);return n&&IA(n),{...t,attachments:t.attachments.filter(t=>t.id!==e)}}),Pa()},[Pa,$i]),Xa=(0,G.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value=``,Ja(t)},[Ja]),Za=(0,G.useCallback)(e=>{let t=GA(e.clipboardData);t.length!==0&&(e.preventDefault(),Ja(t))},[Ja]);(0,G.useEffect)(()=>{let e=ir.current;if(e)return e.addEventListener(`cancel`,Pa),()=>e.removeEventListener(`cancel`,Pa)},[Pa]),(0,G.useEffect)(()=>{rr.current=Object.values(pe).flatMap(e=>e.attachments)},[pe]),(0,G.useEffect)(()=>()=>{rr.current.forEach(IA)},[]);let Qa=(0,G.useCallback)(e=>{$i(t=>({...t,mode:e,ui:{...t.ui,plusMenuOpen:!1}})),Pa()},[Pa,$i]),$a=(0,G.useCallback)((e,t=!1,n=null)=>{let r=Y.find(t=>t.id===e);if(!r)return;let i=Number.isFinite(r.attentionSeq)?Math.max(0,Number(r.attentionSeq)):0,a=Number.isFinite(r.readAttentionSeq)?Math.max(0,Number(r.readAttentionSeq)):0;!t&&i<=a&&!r.unread||F(e,{unread:!1,...n?{readOutputEpoch:n.runtimeEpoch,readOutputSeq:n.outputSeq}:{}})},[Y,F]),eo=(0,G.useCallback)((e,t=null)=>{$a(e,!0,t)},[$a]),to=(0,G.useCallback)((e,t)=>{_e(n=>{let r=n[e];return r?.following===t.following&&r?.hasUnreadOutput===t.hasUnreadOutput?n:{...n,[e]:t}})},[]),no=(0,G.useCallback)(e=>{$i(t=>({...t,draft:e,history:{...t.history,cursor:null}}))},[$i]),ro=(0,G.useCallback)((e,t)=>{if(!X||!Ti||!fA(t))return null;let n=pA(Di.history,e,t.value);return n.changed?(me(Ti,e=>({...e,draft:n.value,history:n.history})),n.value):null},[X,Ti,Di.history,me]),io=(0,G.useCallback)(async(e,t,n,i)=>{if(!dF(e))return!0;if(Ct.current.has(e.id))return!1;Ct.current.add(e.id);let a={model:t,reasoningEffort:n,serviceTier:i,source:`pending-terminal-command`};St(t=>{let n=new Map(t);return n.set(e.id,a),n}),bt(t=>new Set(t).add(e.id)),Jn({id:Date.now(),kind:`success`,message:J.terminalProfileApplying});let o=new AbortController,s=window.setTimeout(()=>{o.abort(new DOMException(`Timed out applying the Codex Terminal profile`,`TimeoutError`))},sF);try{let a=await fetch(r(`/api/agents/${encodeURIComponent(e.id)}/codex-terminal-profile`),{method:`POST`,headers:{"Content-Type":`application/json`},signal:o.signal,body:JSON.stringify({model:t,effort:n,serviceTier:i})}),s=await a.json().catch(()=>({}));if(!a.ok)throw Error(s.error||`Failed to update Codex Terminal (${a.status})`);return Jn({id:Date.now(),kind:`success`,message:J.terminalProfileApplied}),!0}catch(t){St(t=>{let n=new Map(t);return n.delete(e.id),n});let n=t instanceof Error?t.message:`Failed to update Codex Terminal`;return Jn({id:Date.now(),kind:`error`,message:J.terminalProfileFailed(n)}),!1}finally{window.clearTimeout(s),Ct.current.delete(e.id),bt(t=>{let n=new Set(t);return n.delete(e.id),n})}},[J.terminalProfileApplied,J.terminalProfileApplying,J.terminalProfileFailed]);(0,G.useEffect)(()=>{let e=X?.codexTerminalProfile;!X||!e||St(t=>{let n=t.get(X.id);if(!n||e.model!==n.model||e.reasoningEffort!==n.reasoningEffort||e.serviceTier!==n.serviceTier)return t;let r=new Map(t);return r.delete(X.id),r})},[X?.id,X?.codexTerminalProfile?.model,X?.codexTerminalProfile?.reasoningEffort,X?.codexTerminalProfile?.serviceTier]);let ao=(0,G.useCallback)((e,t,n=[])=>En(e)?ae(t,e.id,Cn(e)?n:[]):Dk(e.command)===`shell`||Pk(e).kind===`shell`||uF(e.command)?uC(e.id,`${t}\r`):uC(e.id,UN(t)),[ae]),oo=(0,G.useCallback)(async(e,t)=>(await fetch(r(`/api/agents/${encodeURIComponent(e.id)}/codex-goal`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({objective:t,status:`active`,tokenBudget:null})})).ok,[]),so=(0,G.useCallback)(e=>{let t=e??nr.current?.value??Oi,n=RA(t,ki);if(!n||!X||!Ti||ki.some(e=>e.status===`uploading`))return;if(Ai===`goal`&&xi){(async()=>{await oo(X,n)&&ao(X,n)&&(me(Ti,e=>(e.attachments.forEach(IA),{...e,draft:``,attachments:[],mode:`default`,history:dA(e.history,t)})),Pa())})();return}let r=KA(Ai,n),i=!0;UE(X)&&X.runtimeBinding.kind===`terminal`?me(Ti,e=>{let t=e.pendingFollowUp;return{...e,pendingFollowUp:{messages:[...t?.messages||[],_A(r)],createdAt:t?.createdAt||Date.now()}}}):i=ao(X,r),i&&(me(Ti,e=>(e.attachments.forEach(IA),{...e,draft:``,attachments:[],mode:`default`,history:dA(e.history,t)})),Pa())},[X,xi,Ti,ki,Ai,Oi,Pa,ao,oo,me]),co=(0,G.useCallback)(e=>{let t=e??nr.current?.value??Oi,n=!!(bi&&X&&ge.current[X.id]!==void 0),r=qA({agent:X,composerKey:Ti,draft:t,attachments:ki,composerMode:Ai,turnActive:Ii||n,sendMessage:ao,updateComposerState:me});r&&X&&bi&&!Ii&&!n&&(ge.current[X.id]=Number(bi.sessionRevision)||0),r&&Pa()},[bi,X,Ii,Ti,ki,Ai,Oi,Pa,ao,me]),lo=(0,G.useCallback)(()=>{!X||!qi||(re(X.id),Pa())},[X,qi,Pa,re]),uo=(0,G.useCallback)((e,t)=>{X&&se(X.id,e,t)},[X,se]),fo=(0,G.useCallback)(e=>{X&&se(X.id,e,void 0,{reject:!0,reason:`Declined in Farming`})},[X,se]),po=(0,G.useCallback)((e,t,n)=>{X&&JA(X.id,e,t,n===!0)},[X]),mo=(0,G.useCallback)((e,t,n)=>{X&&YA(X.id,e,t,n)},[X]),ho=(0,G.useCallback)(e=>{if(!X||!Ti)return;let t=pe[Ti]?.pendingFollowUp;if(!t||t.messages.length===0)return;let n=t.messages.find(t=>t.id===e);n&&ao(X,n.text,n.attachments)&&(H.current[Ti]=n.id,me(Ti,t=>t.pendingFollowUp?{...t,pendingFollowUp:vA(t.pendingFollowUp,e)}:t),Pa())},[X,Ti,pe,Pa,ao,me]),go=(0,G.useCallback)(e=>{!X||!Ti||(me(Ti,t=>t.pendingFollowUp?{...t,pendingFollowUp:vA(t.pendingFollowUp,e)}:t),Pa())},[X,Ti,Pa,me]);(0,G.useEffect)(()=>{let e=new Set(Y.map(e=>e.id));Object.keys(ge.current).forEach(t=>{e.has(t)||delete ge.current[t]}),Y.forEach(e=>{let t=ge.current[e.id];if(t===void 0)return;let n=Cn(e)?e.runtimeBinding:null,r=WE(e)||(Number(n?.sessionRevision)||0)>t;(!n||r||n.state===`error`||e.archived||e.status===`dead`||e.status===`stopped`)&&delete ge.current[e.id]})},[Y]),(0,G.useEffect)(()=>{let e=[];Y.forEach(t=>{let n=Cn(t),r=n?ZA(t):CA(t);if(!r)return;let i=pe[r]?.pendingFollowUp;if(!i||i.messages.length===0){delete H.current[r];return}if(t.archived||t.status===`dead`||t.status===`stopped`||n&&ge.current[t.id]!==void 0)return;if(n?WE(t):UE(t)){delete H.current[r];return}if(H.current[r])return;let a=i.messages[0];a&&e.push({agent:t,composerKey:r,message:a})}),e.length!==0&&e.forEach(({agent:e,composerKey:t,message:n})=>{ao(e,n.text,n.attachments)&&(H.current[t]=n.id,he(t,e=>e.pendingFollowUp?{...e,pendingFollowUp:vA(e.pendingFollowUp,n.id)}:e))})},[Y,pe,ao,he]);let _o=(0,G.useCallback)(()=>{Sn(null),Dn(null),kn(null),Mn(null),ea(),Br(),z(`search`),Pe(!0),requestAnimationFrame(()=>cr.current?.focus())},[ea,Br,z]),vo=(0,G.useCallback)(()=>{hF()&&zr()},[zr]),yo=(0,G.useCallback)(()=>{Br()},[Br]),bo=(0,G.useCallback)((e,t,n)=>{O(e,t,n),vo()},[vo,O]),xo=(0,G.useCallback)((e,t,n)=>{if(Ie(``),Pe(!1),Ve(0),ye(`terminal`),z(`projects`),Dk(e)!==`codex`){M(e,t,n);return}let r=n?.codexApprovalMode||ct;M(e,t,{...n,codexApprovalMode:r,...r===`full`?{dangerouslySkipPermissions:!0}:{}})},[ct,M,z]);(0,G.useEffect)(()=>{let e=!1;return fetch(r(`/api/executables`)).then(e=>{if(!e.ok)throw Error(`Failed to load executables: ${e.status}`);return e.json()}).then(t=>{e||at(Jt(Array.isArray(t)?t:t.agents??[]))}).catch(()=>{e||at([])}),()=>{e=!0}},[]);let So=(0,G.useCallback)(e=>{fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({mainPageSessionKeys:QO(e)})}).catch(()=>{})},[]),Co=(0,G.useCallback)(e=>{st(t=>{let n=QO(e(t));return WP(t,n)?t:(Nr.current+=1,So(n),new Set(n))})},[So]);(0,G.useEffect)(()=>{let e=QO(n);st(t=>WP(t,e)?t:new Set(e))},[n]);let wo=(0,G.useCallback)((e,t,n=``)=>{let r=aD({provider:e,id:t,providerHomeId:n});Co(e=>[...e,r])},[Co]),To=(0,G.useCallback)(e=>{Co(t=>Array.from(t).filter(t=>t!==e))},[Co]),Eo=(0,G.useCallback)(e=>{let t=new Set(e);Co(e=>Array.from(e).filter(e=>!t.has(e)))},[Co]),Do=(0,G.useCallback)(e=>{Promise.resolve(e).then(e=>{if(!e||typeof e!=`object`)return;let t=Array.isArray(e.removedMainPageSessionKeys)?e.removedMainPageSessionKeys:[];t.length>0&&Eo(t)}).catch(()=>{})},[Eo]);(0,G.useEffect)(()=>{let e=!1;Y.forEach(t=>{if(t.providerSessionTemporary===!0)return;let n=t.providerSessionKey||nk(t.source);if(!n)return;let r=`${t.id}:${n}`;Pr.current.has(r)||(Pr.current.add(r),Co(e=>[...e,n]),e=!0)}),e&&Ua()},[Y,Ua,Co]),(0,G.useEffect)(()=>{if(!fe||!Y.some(e=>e.providerSessionTemporary===!0))return;Ua();let e=window.setInterval(Ua,5e3);return()=>window.clearInterval(e)},[Y,fe,Ua]);let Oo=(0,G.useCallback)(()=>{let e=Cr.current,t=Array.from(tr.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]??hr.current;return n?(n.focus({preventScroll:!0}),document.activeElement===n):!1},[]),ko=(0,G.useCallback)(e=>{let t=Array.from(tr.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===mF(e));return t?(t.focus({preventScroll:!0}),document.activeElement===t):!1},[]),Ao=(0,G.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||hr.current?.contains(e)||e.closest(`.code-sidebar`)?!1:!!e.closest(`.code-composer`):!1},[a]),jo=(0,G.useCallback)(e=>{window.requestAnimationFrame(()=>{e?.skipIfFocusMoved&&Ao()||Oo()})},[Oo,Ao]),Mo=(0,G.useCallback)(()=>{Ie(``),Pe(!1),Ve(0)},[]),No=(0,G.useCallback)(()=>{Mo(),z(`projects`),Ar.current=`active-force`},[Mo,z]);(0,G.useEffect)(()=>{if(!Ne||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"]`)||No())};return document.addEventListener(`pointerdown`,e,!0),()=>{document.removeEventListener(`pointerdown`,e,!0)}},[i,No,Ne]);let Po=(0,G.useCallback)(e=>{Sn(null),Dn(null),kn(null),Mn(null),e===`projects`?(Br(),Mo()):e!==`search`&&Mo(),z(e)},[Mo,Br,z]),Fo=(0,G.useCallback)(()=>{_o(),vo()},[vo,_o]),Io=(0,G.useCallback)(e=>{Po(e),vo()},[vo,Po]),Lo=(0,G.useCallback)(e=>{cn(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,G.useEffect)(()=>{qe.current=Ue},[Ue]),(0,G.useEffect)(()=>{Qe.current=Xe},[Xe]);let Ro=(0,G.useCallback)((e,t)=>{let n=Ln(e),i=Je.current+=1;qe.current=n,We(n),Ye.current=Ye.current.catch(()=>{}).then(async()=>{let e=await fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({projectWorkspaces:n})});if(!e.ok)throw Error(`settings request failed (${e.status})`);let t=await e.json();if(i!==Je.current)return;let a=Ln(t.settings?.projectWorkspaces);qe.current=a,We(a)}).catch(()=>{if(i!==Je.current)return;let e=Ln(t);qe.current=e,We(e),Jn({id:Date.now(),kind:`error`,message:J.copyFailed})})},[J.copyFailed]),zo=(0,G.useCallback)((e,t)=>{let n=Ln(e),i=$e.current+=1;Qe.current=n,Ze(n),et.current=et.current.catch(()=>{}).then(async()=>{let e=await fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinnedProjectWorkspaces:n})});if(!e.ok)throw Error(`settings request failed (${e.status})`);let t=await e.json();if(i!==$e.current)return;let a=Ln(t.settings?.pinnedProjectWorkspaces);Qe.current=a,Ze(a)}).catch(()=>{if(i!==$e.current)return;let e=Ln(t);Qe.current=e,Ze(e),Jn({id:Date.now(),kind:`error`,message:J.copyFailed})})},[J.copyFailed]),Bo=(0,G.useCallback)(e=>{let t=e.trim().replace(/[\\/]+$/,``);if(!t)return;let n=qe.current;n.includes(t)||Ro([t,...n],n),cn(e=>{if(!e.has(t))return e;let n=new Set(e);return n.delete(t),n})},[Ro]);(0,G.useEffect)(()=>{if(!Ge)return;let e=qe.current,t=oi.filter(e=>!e.hasMain&&!!e.workspace).map(e=>e.workspace).filter(t=>!e.includes(t)&&!tt.current.has(t));t.length!==0&&(t.forEach(e=>tt.current.add(e)),Ro([...t,...e],e))},[Ro,oi,Ge]);let Vo=(0,G.useCallback)(e=>{un(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Ho=(0,G.useCallback)((e,t)=>{ye(`terminal`),z(`projects`),e.kind===`agent`?C(e.id,{focusTerminal:t?.focusTerminal}):Sr.current(e.provider,e.id,e.providerHomeId)},[C,z]),Uo=(0,G.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 YE({kind:`agent`,id:t.dataset.agentId});if(t?.dataset.sessionId&&t.dataset.provider)return t.dataset.sessionId}let t=Cr.current;return t?YE({kind:`agent`,id:t}):``},[]),Wo=(0,G.useCallback)(e=>{if(mi.length===0)return;let t=Uo(),n=mi.findIndex(e=>mF(e)===t),r=mi[((n===-1?e>0?-1:0:n)+e+mi.length)%mi.length];r&&(Ho(r,{focusTerminal:!1}),r.kind===`agent`&&(Ao()||ko(r),window.requestAnimationFrame(()=>{Ao()||ko(r)})),Ar.current=`active`)},[Uo,ko,Ho,Ao,mi]),Go=(0,G.useCallback)(e=>{if(!(e.ctrlKey||e.metaKey||e.altKey)){if(e.key===`/`&&!e.shiftKey){e.preventDefault(),_o();return}if(e.key===`ArrowDown`){e.preventDefault(),Wo(1);return}e.key===`ArrowUp`&&(e.preventDefault(),Wo(-1))}},[Wo,_o]),Ko=(0,G.useCallback)(e=>{hi.length!==0&&Ve(t=>(t+e+hi.length)%hi.length)},[hi.length]),qo=(0,G.useCallback)(()=>{ia&&(Ho(ia),Mo())},[Mo,Ho,ia]),Jo=(0,G.useCallback)(e=>{if(e.key===`Escape`){e.preventDefault(),No();return}if(e.key===`ArrowDown`){e.preventDefault(),Ko(1);return}if(e.key===`ArrowUp`){e.preventDefault(),Ko(-1);return}e.key===`Enter`&&(e.preventDefault(),qo())},[No,Ko,qo]),Yo=(0,G.useCallback)(e=>{let t=tr.current?.getBoundingClientRect(),n=e-(t?.left??0);if(n<=QP){Rr();return}let r=t?.width??window.innerWidth,i=Math.max(qP,Math.min(JP,r-YP)),a=Math.max(qP,Math.min(i,n));Br(),fn(a)},[Rr,Br]),Xo=(0,G.useCallback)(e=>{let t=Array.from(tr.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},[]),Zo=(0,G.useCallback)(e=>{JN(()=>{Xo(e)},{delays:[80,180]})},[Xo]),Qo=(0,G.useCallback)((e,t)=>{window.requestAnimationFrame(()=>{Array.from(tr.current?.querySelectorAll(`[data-testid="code-active-session-row"]`)??[]).find(n=>n.dataset.provider===e&&n.dataset.sessionId===t)?.focus({preventScroll:!0})})},[]),$o=(0,G.useCallback)(e=>{window.requestAnimationFrame(()=>{Array.from(tr.current?.querySelectorAll(`[data-testid="code-project-title"]`)??[]).find(t=>t.dataset.projectId===e)?.focus()})},[]),es=(0,G.useCallback)(async()=>{if(!ra)return;let e=aD(ra),t=ra.pinned!==!0;tn(n=>({...n,[e]:t})),kn(null),Mn(null),ot.has(e)?Qo(ra.provider,e):window.requestAnimationFrame(()=>hr.current?.focus({preventScroll:!0}));try{if(!(await fetch(r(`/api/agent-sessions/${encodeURIComponent(ra.provider)}/${encodeURIComponent(ra.id)}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:t,providerHomeId:ra.providerHomeId||`default`})})).ok)throw Error(J.updateFailed);let n=await Va({limit:Qt.current});Lt(n.sessions),Vt(n.nextCursor),Wt(n.hasMore),tn(t=>{let n={...t};return delete n[e],n})}catch(n){tn(n=>({...n,[e]:!t})),Jn({id:Date.now(),kind:`error`,message:n instanceof Error?n.message:J.updateFailed})}},[ra,J.updateFailed,Va,Qo,ot]),ts=(0,G.useCallback)(()=>{if(!ra)return;let e=aD(ra);tn(t=>({...t,[e]:!1})),To(e),kn(null),Mn(null),window.requestAnimationFrame(()=>hr.current?.focus({preventScroll:!0}))},[ra,To]),ns=(0,G.useCallback)(e=>{e.preventDefault(),Br(),Fr.current=!0,document.body.classList.add(`code-resizing-sidebar`),Yo(e.clientX)},[Br,Yo]),rs=(0,G.useCallback)((e,t)=>{Sn(null),Dn(null),kn(null),Mn(null),Mo(),ye(`terminal`),z(`projects`),C(e,t)},[Mo,C,z]),is=(0,G.useCallback)(e=>{rs(e),vo()},[vo,rs]),as=(0,G.useCallback)(e=>f(e,{cursorRequestId:e?.lineNumber?wr.current+=1:wr.current,diffRequestId:e?.view===`diff`?Tr.current+=1:Tr.current}),[]),os=(0,G.useCallback)((e,t,n)=>{let r=Kr(e,n?.sourceAgentId),i=Le(r.filesId),a=In(r.filesId);if(!i&&(a||r.sourceAgent)){let e=a||(r.sourceAgent?.isMain?`__farming_main_agent__`:ZE(r.sourceAgent));cn(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}Sn(null),Dn(null),kn(null),Mn(null),Mo(),z(`projects`),ye(`editor`);let o={...as(n),workspaceRoot:r.workspaceRoot,sourceAgentId:r.sourceAgentId};Ce.openFromRead(r.filesId,t,o),p(n)&&Xn({agentId:r.filesId,path:t.path,kind:`file`,requestId:Er.current+=1}),r.sourceAgent&&r.sourceAgentId&&C(r.sourceAgentId,{focusTerminal:!1}),vo()},[Mo,vo,as,C,z,Kr,Ce]);(0,G.useEffect)(()=>{if(Se.current||xe.current)return;let e=be;if(!e){Se.current=!0;return}if(e.kind===`agent`){if(Y.length===0)return;xe.current=!0;let t=Y.find(t=>t.id===e.agentId)??Y.find(t=>!!e.providerSessionKey&&t.providerSessionKey===e.providerSessionKey)??Y.find(t=>!!e.workspace&&ZE(t)===e.workspace);t?rs(t.id,{focusTerminal:!1}):D({surface:void 0}),Se.current=!0;return}if(!Ge)return;xe.current=!0;let t=Y.find(t=>t.id===e.sourceAgentId&&(e.workspace===`/`||Fn(ZE(t))===Fn(e.workspace)))??Y.find(t=>Fn(ZE(t))===Fn(e.workspace)),n=e.workspace===`/`?Be:Fn(e.workspace);if(!(e.workspace===`/`||Ue.some(e=>Fn(e)===n)||t)){D({surface:void 0}),Se.current=!0;return}let r=Kr(n,t?.id);le(r.filesId,e.filePath).then(t=>{os(r.filesId,t,{view:e.view??`editor`,lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn,revealInTree:!0,sourceAgentId:r.sourceAgentId})}).catch(()=>{D({surface:void 0})}).finally(()=>{Se.current=!0})},[Y,be,os,rs,Ue,Ge,Kr]),(0,G.useEffect)(()=>{if(!Se.current||i!==`projects`)return;if(ve===`terminal`){let e=Y.find(e=>e.id===c);if(!e)return;D({surface:{kind:`agent`,agentId:e.id,providerSessionKey:e.providerSessionKey||void 0,workspace:ZE(e)}});return}if(!W)return;let e=W.workspaceRoot??Y.find(e=>e.id===W.agentId)?.projectWorkspace??Y.find(e=>e.id===W.agentId)?.cwd??``;e&&D({surface:{kind:`file`,workspace:e,filePath:W.file.path,view:W.diffRequestId?`diff`:`editor`,lineNumber:W.cursor?.lineNumber,column:W.cursor?.column,endColumn:W.cursor?.endColumn,sourceAgentId:W.sourceAgentId}})},[Y,c,i,ve,W]);let ss=(0,G.useCallback)((e,t)=>{let n=Kr(e),r=In(n.filesId);if(!Le(n.filesId)&&(r||n.sourceAgent)){let e=r||(n.sourceAgent?.isMain?`__farming_main_agent__`:ZE(n.sourceAgent));cn(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}Sn(null),Dn(null),kn(null),Mn(null),Mo(),Br(),z(`projects`),Qn({agentId:n.filesId,...t?{query:t}:{},requestId:Dr.current+=1})},[Mo,Br,z,Kr]),cs=(0,G.useCallback)((e,t,n)=>{let r=Kr(e),i=In(r.filesId);if(!Le(r.filesId)&&(i||r.sourceAgent)){let e=i||(r.sourceAgent?.isMain?`__farming_main_agent__`:ZE(r.sourceAgent));cn(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}Sn(null),Dn(null),kn(null),Mn(null),Mo(),Br(),z(`projects`),Xn({agentId:r.filesId,path:t,kind:n,requestId:Er.current+=1})},[Mo,Br,z,Kr]),ls=(0,G.useCallback)(async(e,t)=>{let n=Kr(e,e),r=Qw(t.path,n.workspaceRoot??``);if(!r)return null;try{let e=xF((await de(n.filesId,r,{limit:eF})).matches),i=e.find(e=>e.path===r)?.path??(e.length===1?e[0]?.path:``);return i?{...t,path:i}:null}catch{return null}},[Kr]),us=(0,G.useCallback)((e,t)=>{let n=Kr(e,e),r=Qw(t.path,n.workspaceRoot??``);if(!r)return;let i=Or.current+1;Or.current=i;let a=bF(t),o={...a??{},sourceAgentId:n.sourceAgentId},s=async(e,t=o)=>{let r=await le(n.filesId,e);Or.current===i&&os(n.filesId,r,t)},c=e=>{Or.current===i&&cs(n.filesId,e,`directory`)},l=async e=>{if(e.entryType===`directory`){c(e.path);return}await s(e.path)},u=()=>{Or.current===i&&ss(n.filesId,r)};(async()=>{try{await V(n.filesId,r),c(r);return}catch{}try{await s(r);return}catch{}try{let e=await de(n.filesId,r,{limit:eF});if(Or.current!==i)return;let t=xF(e.matches);if(t.length===1){let e=t[0];if(!e)return;await l(e);return}let c=SF(e.matches);if(t.length===0&&c.length===1){let e=c[0];if(!e)return;await s(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,sourceAgentId:n.sourceAgentId}:o);return}}catch{}u()})()},[ss,os,Kr,cs]),ds=(0,G.useCallback)((e,t,n)=>{let r=Kr(e,n?.sourceAgentId),i=Le(r.filesId),a=In(r.filesId);if(!i&&(a||r.sourceAgent)){let e=a||(r.sourceAgent?.isMain?`__farming_main_agent__`:ZE(r.sourceAgent));cn(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}let o=h({agentId:r.filesId,workspaceRoot:r.workspaceRoot,filePath:t});if(!je.some(e=>d(e)===o))return!1;let s={...as(n),workspaceRoot:r.workspaceRoot,sourceAgentId:r.sourceAgentId};return Ce.select(r.filesId,t,s)?(Sn(null),Dn(null),kn(null),Mn(null),Mo(),z(`projects`),ye(`editor`),p(n)&&Xn({agentId:r.filesId,path:t,kind:`file`,requestId:Er.current+=1}),r.sourceAgent&&r.sourceAgentId&&C(r.sourceAgentId,{focusTerminal:!1}),vo(),!0):!1},[Mo,vo,as,C,z,je,Kr,Ce]),fs=(0,G.useCallback)(async(e,t,n)=>{let r=Kr(n?.globalRoot?Be:e,n?.sourceAgentId??(n?.globalRoot?e:void 0)),i=r.filesId,a=n?.globalRoot?Re(t):t,o=n?{...n,sourceAgentId:r.sourceAgentId}:r.sourceAgentId?{sourceAgentId:r.sourceAgentId}:void 0;if(ds(i,a,o))return;let s=async(e,t=o)=>{os(i,await le(i,e),t)};try{await s(a,o)}catch{try{await V(i,a),cs(i,a,`directory`)}catch{try{let e=await de(i,a,{limit:eF}),t=xF(e.matches),c=SF(e.matches);if(t.length===1){let e=t[0];if(e?.entryType===`directory`){cs(i,e.path,`directory`);return}if(e?.path){await s(e.path,o);return}}if(t.length===0&&c.length===1){let e=c[0];if(e?.path){await s(e.path,!n&&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,sourceAgentId:r.sourceAgentId}:o);return}}}catch{}o?.suppressSearchOnMiss||ss(i,a)}}},[ss,os,Kr,cs,ds]),ps=(0,G.useCallback)(async e=>{if(ie(e.kind===`agent`?e.readingAnchor:void 0),e.kind===`agent`)return Wr.has(e.agentId)?(Sn(null),Dn(null),kn(null),Mn(null),Mo(),z(`projects`),ye(`terminal`),C(e.agentId,{focusTerminal:!1}),vo(),!0):!1;let t=k(e,[...Y.filter(e=>!e.isMain).map(e=>({agentId:e.id,workspace:ZE(e)})),...Ue.map(e=>({agentId:Fn(e),workspace:e}))],Be);if(!t)return!1;let n=Kr(t.agentId,t.agentId);if(e.kind===`folder`)try{let e=S((await V(n.filesId,t.filePath)).items);if(e){let t=await le(n.filesId,e);return os(n.filesId,t,{sourceAgentId:n.sourceAgentId}),!0}return cs(n.filesId,t.filePath,`directory`),!0}catch{return!1}let r={...I(e),sourceAgentId:n.sourceAgentId};if(ds(n.filesId,t.filePath,r))return!0;try{let e=await le(n.filesId,t.filePath);return os(n.filesId,e,r),!0}catch{return!1}},[Y,Mo,vo,C,z,os,Ue,cs,Kr,ds,Wr]),ms=(0,G.useRef)(ps);ms.current=ps;let hs=(0,G.useCallback)(()=>{if(typeof window>`u`)return;let e=x(window.location.search);window.history.replaceState(window.history.state,``,`${window.location.pathname}${e}${window.location.hash}`)},[]);(0,G.useEffect)(()=>{if(!hn)return;let e=!1,t=null,n=hn.kind===`agent`?hn.agentId:hn.absolutePath||(hn.kind===`folder`?hn.folderPath:hn.filePath);return ms.current(hn).then(r=>{if(!e){if(r){gn(null),hs();return}if(kr.current+=1,kr.current>=20){Jn({id:Date.now(),kind:`error`,message:J.sharedLocationUnavailable(n)}),gn(null),hs();return}t=window.setTimeout(()=>{vn(e=>e+1)},250)}}).catch(()=>{e||(Jn({id:Date.now(),kind:`error`,message:J.sharedLocationUnavailable(n)}),gn(null),hs())}),()=>{e=!0,t!==null&&window.clearTimeout(t)}},[hs,J.sharedLocationUnavailable,hn,_n]);let gs=(0,G.useCallback)(async e=>{if(e.kind===`agent`){if(!Wr.has(e.agentId))return!1}else if(!Gr.has(e.agentId))return!1;if(Sn(null),Dn(null),kn(null),Mn(null),Mo(),z(`projects`),e.kind===`agent`)return ye(`terminal`),C(e.agentId),vo(),!0;let t={view:e.view,lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn,sourceAgentId:e.sourceAgentId},n=Kr(e.agentId,e.sourceAgentId);if(ds(n.filesId,e.filePath,t))return!0;try{let r=await le(n.filesId,e.filePath);return os(n.filesId,r,t),!0}catch{return!1}},[Mo,vo,C,z,os,Kr,ds,Wr,Gr]),_s=(0,G.useCallback)(e=>{let t=U(e);return t?((async()=>{let n=t;for(;n;){if(await gs(n))return;n=U(e)}})().finally(()=>{ke()}),!0):!1},[U,ke,gs]),vs=(0,G.useCallback)(e=>{ye(`terminal`),z(`projects`),C(e,{focusTerminal:!oe()}),vo()},[vo,C,z]),ys=(0,G.useCallback)(e=>{let t=Ce.close(e);t.closedFiles.length!==0&&t.activeFileClosed&&ye(t.activeFile?`editor`:`terminal`)},[Ce]),bs=(0,G.useCallback)((e,t,n)=>{ys([{agentId:e,filePath:t,workspaceRoot:n}])},[ys]),xs=(0,G.useCallback)(()=>{let e=Ce.reopenLastClosed(e=>Gr.has(e.agentId))?.activeFile;if(!e)return!1;Sn(null),Dn(null),kn(null),Mn(null),Mo(),z(`projects`),ye(`editor`);let t=e.sourceAgentId;return t&&Y.some(e=>e.id===t)&&C(t,{focusTerminal:!1}),vo(),!0},[Y,Mo,vo,C,z,Gr,Ce]),Ss=(0,G.useCallback)(e=>{Ce.update(e)},[Ce]),Cs=(0,G.useCallback)(e=>{Ce.updateDraft(e)},[Ce]),ws=(0,G.useCallback)((e,t)=>{t.length!==0&&Ce.move(e,t)},[Ce]),Ts=(0,G.useCallback)((e,t)=>{if(t.length===0)return;let n=Ce.deleteEntries(e,t);n.activeFileDeleted&&(n.activeFile||ye(`terminal`))},[Ce]),Es=(0,G.useCallback)((e,t)=>{e.preventDefault(),e.stopPropagation();let n=Y.find(e=>e.id===t),r=xj(e.clientX,e.clientY,wj(n));Dn(null),kn(null),Mn(null),Sn({agentId:t,x:r.x,y:r.y})},[Y]),Q=(0,G.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=xj(n.left+24,n.top+n.height,wj(r));Dn(null),kn(null),Mn(null),Sn({agentId:t,x:i.x,y:i.y})},[Y]),Ds=(0,G.useCallback)((e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget.getBoundingClientRect(),r=oi.find(e=>e.id===t),i=r?.hasMain?4:Ik(r)?8:7,a=bj(i,r?.hasMain?1:2)+i*8,o=oe()?Cj(n,a,void 0,rF):Sj(n,a);Sn(null),kn(null),Mn(null),Dn({projectId:t,x:o.x,y:o.y})},[oi]),Os=(0,G.useCallback)((e,t)=>{if(e.key!==`ContextMenu`&&!(e.shiftKey&&e.key===`F10`))return;e.preventDefault(),e.stopPropagation();let n=e.currentTarget.getBoundingClientRect(),r=oi.find(e=>e.id===t),i=r?.hasMain?4:Ik(r)?8:7,a=bj(i,r?.hasMain?1:2)+i*8,o=oe()?Cj(n,a,void 0,rF):Sj(n,a);Sn(null),kn(null),Mn(null),Dn({projectId:t,x:o.x,y:o.y})},[oi]),ks=(0,G.useCallback)((e,t,n)=>{e.preventDefault(),e.stopPropagation();let r=xj(e.clientX,e.clientY,bj(3));Sn(null),Dn(null),Mn(null),kn({provider:t,sessionId:n,x:r.x,y:r.y})},[]),As=(0,G.useCallback)((e,t,n)=>{if(e.key!==`ContextMenu`&&!(e.shiftKey&&e.key===`F10`))return;e.preventDefault(),e.stopPropagation();let r=e.currentTarget.getBoundingClientRect(),i=xj(r.left+24,r.top+r.height,bj(3));Sn(null),Dn(null),Mn(null),kn({provider:t,sessionId:n,x:i.x,y:i.y})},[]),js=(0,G.useCallback)(()=>{if(!ta)return;let e=ee(ta);Sn(null),Mn(null),Vn({kind:`agent`,agentId:ta.id,title:e})},[ta]),Ms=(0,G.useCallback)(()=>{na&&(Dn(null),Mn(null),Vn({kind:`project`,projectId:na.id,workspace:na.workspace,title:na.name}))},[na]),Ns=(0,G.useCallback)(()=>{let e=Bn;Vn(null),e&&(e.kind===`agent`&&Zo(e.agentId),e.kind===`project`&&$o(e.projectId))},[Zo,$o,Bn]),Ps=(0,G.useCallback)(()=>{if(!Bn)return;let e=Bn.title.trim();if(Bn.kind===`agent`){if(!e)return;N(Bn.agentId,e),Vn(null),Zo(Bn.agentId);return}if(!e)return;let t={...nt,[Bn.workspace]:e};rt(t),fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({projectNames:t})}).then(e=>e.json()).then(e=>{rt(HP((e.settings??{}).projectNames))}).catch(()=>{Jn({id:Date.now(),kind:`error`,message:J.copyFailed})}),Vn(null),$o(Bn.projectId)},[J.copyFailed,Zo,$o,N,nt,Bn]),Fs=(0,G.useCallback)(async(e,t)=>{Sn(null),Dn(null),kn(null),Mn(null);let n=await CF(e);Jn({id:Date.now(),kind:n?`success`:`error`,message:n?J.copiedWorkingDirectory:J.copyFailed}),t?.kind===`agent`&&Zo(t.id),t?.kind===`agent-session`&&Qo(t.provider,aD(t))},[J.copiedWorkingDirectory,J.copyFailed,Zo,Qo]),Is=(0,G.useCallback)(()=>{ta&&(Sn(null),Mn(null),Un({agentId:ta.id,title:ee(ta)}))},[ta]),Ls=(0,G.useCallback)(()=>{let e=Hn?.agentId;Un(null),e&&Zo(e)},[Zo,Hn?.agentId]),Rs=(0,G.useCallback)(()=>{Hn&&(B(Hn.agentId),Un(null))},[Hn,B]),zs=(0,G.useCallback)(e=>{ta&&(Sn(null),Mn(null),L(ta.id,e))},[ta,L]),Bs=(0,G.useCallback)(e=>{if(!ta)return;let t=ta.id;if(Sn(null),Mn(null),e.archived===!0){let e=ta.providerSessionKey||nk(ta.source);e&&To(e),jr.current=t,window.setTimeout(()=>Oo(),120),window.setTimeout(()=>Oo(),360),window.setTimeout(()=>Oo(),720)}let n=F(t,e);e.archived===!0&&Do(n),e.archived!==!0&&Zo(t)},[ta,Oo,Zo,F,To,Do]),Vs=(0,G.useCallback)((e,t)=>{let n=e.id;if(Sn(null),Mn(null),t.archived===!0){let t=e.providerSessionKey||nk(e.source);t&&To(t),jr.current=n,window.setTimeout(()=>Oo(),120),window.setTimeout(()=>Oo(),360),window.setTimeout(()=>Oo(),720)}let r=F(n,t);t.archived===!0&&Do(r),t.archived!==!0&&Zo(n)},[Oo,Zo,F,To,Do]),Hs=(0,G.useCallback)(async(e,t,n)=>{try{let i=await fetch(r(`/api/agents/${encodeURIComponent(e)}/reorder`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({beforeAgentId:t,afterAgentId:n})});if(!i.ok){let e=await i.json().catch(()=>null);throw Error(e?.error||J.reorderAgentFailed)}}catch(e){Jn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.reorderAgentFailed})}},[J.reorderAgentFailed]),Us=(0,G.useCallback)(e=>{jr.current=null,Mr.current=e,F(e,{archived:!1}),Mo(),z(`projects`),[120,360,720,1200,1800].forEach(t=>{window.setTimeout(()=>{Ao()||Xo(e)},t)})},[Mo,Xo,F,z,Ao]),Ws=(0,G.useCallback)(e=>{te(e)},[te]),Gs=(0,G.useCallback)(async(e,t,n=``,i=``)=>{let a=aD({provider:e,id:t,providerHomeId:n}),o=()=>{Lt(r=>r.map(r=>r.provider===e&&r.id===t&&(r.providerHomeId||`default`)===(n||`default`)?{...r,archived:!1}:r))},s=Y.find(r=>(r.providerSessionKey===a||r.source===ek(e,t,n))&&r.archived!==!0&&r.status!==`dead`&&r.status!==`stopped`);if(s){o(),wo(e,t,n),C(s.id),vo();return}try{let a=await fetch(r(`/api/agent-sessions/${encodeURIComponent(e)}/${encodeURIComponent(t)}/resume`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({unarchiveArchived:!0,providerHomeId:n,...[`codex`,`claude`,`opencode`,`qoder`].includes(e)?{agentRuntimeMode:`acp`,acpHistoryMode:`load`}:{},...i?{customTitle:i}:{}})}),s=await a.json().catch(()=>null);if(!a.ok||!s?.agentId){Jn({id:Date.now(),kind:`error`,message:s?.error||`Failed to resume agent session (${a.status})`});return}o(),wo(e,t,n),E(s.agentId),vo()}catch(e){Jn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:`Failed to resume agent session`})}},[Y,wo,vo,C,E]);Sr.current=Gs;let Ks=(0,G.useCallback)(e=>{let t=pF(e.source);if(t){Gs(t.provider,t.sessionId,t.providerHomeId,e.customTitle||``),z(`projects`);return}O(Wj(e),e.command||void 0,null,e.customTitle||void 0)},[O,z,Gs]),qs=(0,G.useCallback)(e=>{if(e.preventDefault(),e.stopPropagation(),Sn(null),Dn(null),kn(null),!oe()){Mn(null),Pn(!0);return}let t=e.currentTarget.getBoundingClientRect();Mn({x:Math.max(8,t.right-164),y:Math.min(window.innerHeight-12,t.bottom+6),returnFocusTarget:e.currentTarget})},[]),Js=(0,G.useCallback)(async()=>{Mn(null);try{let e=T(fa),t=await fetch(r(`/api/share/qr-ticket`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e?{target:e}:{})}),n=await t.json().catch(()=>null);if(!t.ok||!n?.longUrl&&!n?.shortUrl)throw Error(n?.error||J.shareLinkFailed);zn(n.longUrl||n.shortUrl||``)}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;Jn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.shareLinkFailed})}},[J.shareLinkFailed,fa]),Ys=(0,G.useCallback)(e=>{Mn(null),ue({language:e})},[ue]),Xs=(0,G.useCallback)(e=>{Mn(null),ue({appearance:e})},[ue]),Zs=(0,G.useCallback)(()=>{Mn(null),Pn(!0)},[]),Qs=(0,G.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),Mn(null),Pn(!0)},[]),$s=(0,G.useMemo)(()=>oe()?aj([{type:`separator`,id:`options-mobile-share-separator`},{type:`item`,id:`options-mobile-share`,label:J.sharePage,ariaLabel:J.sharePage,onSelect:Js}]):aj([{type:`item`,id:`options-appearance-light`,label:UP(J.appearanceLight),ariaLabel:J.appearanceLight,checked:b.appearance===`light`,onSelect:()=>Xs(`light`)},{type:`item`,id:`options-appearance-dark`,label:UP(J.appearanceDark),ariaLabel:J.appearanceDark,checked:b.appearance===`dark`,onSelect:()=>Xs(`dark`)},{type:`separator`,id:`options-appearance-language-separator`},{type:`item`,id:`options-language-en`,label:VP(J.languageEnglish),ariaLabel:J.languageEnglish,checked:b.language===`en`,onSelect:()=>Ys(`en`)},{type:`item`,id:`options-language-zh`,label:VP(J.languageChinese),ariaLabel:J.languageChinese,checked:b.language===`zh`,onSelect:()=>Ys(`zh`)},{type:`separator`,id:`options-settings-separator`},{type:`item`,id:`options-open-settings`,label:J.openSettings,ariaLabel:J.openSettings,onSelect:Zs}]),[J.appearanceDark,J.appearanceLight,J.languageChinese,J.languageEnglish,J.openSettings,J.sharePage,Zs,Js,b.appearance,b.language,Xs,Ys]),ec=(0,G.useCallback)((e,t)=>{fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentLaunchProfiles:{[e]:t}})}).catch(()=>{})},[]),tc=(0,G.useCallback)(e=>{if(l)return;if(Ri===`claude`){let t=sP(e)?e:`default`;Tt(t),ec(`claude`,{permissionMode:t}),X&&(Jn({id:Date.now(),kind:`success`,message:J.permissionProfileRestarting}),F(X.id,{launchPermissionMode:t})),ea(),Pa();return}let t=oP(e)?e:`approve`;lt(t),ec(`codex`,{approvalMode:t}),X&&Ri===`codex`&&(Jn({id:Date.now(),kind:`success`,message:xi?J.permissionProfileApplying:J.permissionProfileRestarting}),F(X.id,{launchPermissionMode:t})),ea(),Pa()},[X,xi,ea,Ri,J.permissionProfileApplying,J.permissionProfileRestarting,Pa,F,l,ec]),nc=(0,G.useCallback)((e,t)=>{l||(Jn({id:Date.now(),kind:`success`,message:J.runtimeModeRestarting}),F(e,{agentRuntimeMode:t}))},[J.runtimeModeRestarting,F,l]),rc=(0,G.useCallback)((e,t,n)=>{ft(e),mt(t),gt(n),ut(`${e}:${t}`),ec(`codex`,{model:e,reasoningEffort:t,serviceTier:n})},[ec]),ic=(0,G.useCallback)(e=>{if(Ri===`claude`){let t=dP(e);Dt(t),ea(),Pa(),ec(`claude`,{model:t,effort:kt});return}let t=_t.find(t=>t.value===e),n=t?.reasoningLevels??[],r=t?.serviceTiers??[],i=n.some(e=>e.value===Wi)?Wi:t?.defaultEffort||n[0]?.value||Wi,a=r.some(e=>e.value===Gi)?Gi:`default`;if(ea(),Pa(),X&&dF(X)){io(X,e,i,a).then(t=>{t&&rc(e,i,a)});return}rc(e,i,a)},[X,io,kt,ea,_t,Wi,Gi,rc,Ri,Pa,ec]),ac=(0,G.useCallback)((e,t)=>{if(Ri!==`codex`)return;let n=_t.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===Gi)?Gi:`default`;if(X&&dF(X)){io(X,e,r,i).then(t=>{t&&rc(e,r,i)});return}rc(e,r,i)},[X,io,_t,Gi,rc,Ri]),oc=(0,G.useCallback)(e=>{if(Ri===`claude`){let t=pP(e);At(t),ea(),Pa(),ec(`claude`,{model:Et,effort:t});return}if(ea(),Pa(),X&&dF(X)){io(X,Ui,e,Gi).then(t=>{t&&rc(Ui,e,Gi)});return}rc(Ui,e,Gi)},[X,io,Et,ea,Ui,Gi,rc,Ri,Pa,ec]),sc=(0,G.useCallback)(e=>{if(Ri!==`claude`){if(ea(),Pa(),X&&dF(X)){io(X,Ui,Wi,e).then(t=>{t&&rc(Ui,Wi,e)});return}rc(Ui,Wi,e)}},[X,io,ea,Ui,Wi,rc,Ri,Pa]),cc=(0,G.useCallback)(e=>{if(Ri===`codex`){if(X&&dF(X)){io(X,Ui,Wi,e).then(t=>{t&&rc(Ui,Wi,e)});return}rc(Ui,Wi,e)}},[X,io,Ui,Wi,rc,Ri]),lc=(0,G.useCallback)(()=>{if(an){yr.current?.stop(),yr.current=null,on(!1);return}let e=Ti;if(!e)return;let t=oe(),n=lF(),r=nn&&!n?window.SpeechRecognition||window.webkitSpeechRecognition:null;if(!r){(lF()||t)&&Pa(),on(!1);return}let i=new r,a=null,o=()=>{a!==null&&(window.clearTimeout(a),a=null)},s=()=>{if(yr.current===i)try{i.stop()}catch{on(!1),yr.current=null}};i.continuous=!1,i.interimResults=!1,i.lang=b.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()&&(me(e,e=>{let t=e.draft&&!/\s$/.test(e.draft)?` `:``;return{...e,draft:`${e.draft}${t}${n.trim()}`}}),Pa())},i.onerror=()=>{o(),on(!1)},i.onspeechend=s,i.onaudioend=s,i.onend=()=>{o(),on(!1),yr.current=null},yr.current=i,on(!0);try{i.start(),a=window.setTimeout(s,6e4)}catch{o(),yr.current=null,on(!1),t&&Pa()}},[Ti,Pa,an,nn,b.language,me]),uc=(0,G.useCallback)(()=>{if(!na?.workspace)return;let e=na.id,t=na.workspace,n=Qe.current,r=na.pinned?n.filter(e=>e!==t):[...n.filter(e=>e!==t),t];Dn(null),Mn(null),zo(r,n),window.requestAnimationFrame(()=>$o(e))},[na,$o,zo]),dc=(0,G.useCallback)(async()=>{if(!na?.workspace)return;let e=na.id,t=Fn(na.workspace);Dn(null),Mn(null);try{let e=await fetch(r(`/api/projects/reveal`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({rootId:t})}),n=await e.json().catch(()=>null);if(!e.ok)throw Error(n?.error||J.revealInFinderFailed)}catch(e){Jn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.revealInFinderFailed})}$o(e)},[na,J.revealInFinderFailed,$o]),fc=(0,G.useCallback)(async()=>{if(!na?.workspace)return;let e=na.id,t=Fn(na.workspace);Dn(null),Mn(null);try{await Ye.current.catch(()=>{});let e=await fetch(r(`/api/projects/create-worktree`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({rootId:t})}),n=await e.json().catch(()=>null);if(!e.ok)throw Error(n?.error||J.permanentWorktreeFailed);let i=Ln(n?.projectWorkspaces);Je.current+=1,qe.current=i,We(i),Jn({id:Date.now(),kind:`success`,message:J.permanentWorktreeCreated})}catch(e){Jn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.permanentWorktreeFailed})}$o(e)},[na,J.permanentWorktreeCreated,J.permanentWorktreeFailed,$o]),pc=(0,G.useCallback)(()=>{if(!na)return;let e=na.id;na.agents.forEach(e=>{e.unread&&$a(e.id,!0)}),Dn(null),Mn(null),$o(e)},[na,$o,$a]),mc=(0,G.useCallback)(()=>{if(!na)return;let e=na.workspace,t=na.agents.filter(e=>!e.isMain),n=Yr.filter(t=>sD(t)===e);if(t.length===0&&n.length===0){Dn(null),Mn(null),Ar.current=`list`;return}t.forEach(e=>{F(e.id,{archived:!0})}),Eo(n.map(aD)),Dn(null),Mn(null),Ar.current=`list`},[Yr,na,F,Eo]),hc=(0,G.useCallback)(()=>{if(!na||na.hasMain||na.agents.length>0||na.agentSessions.length>0||na.hasOpenFile)return;let e=qe.current;Ro(e.filter(e=>e!==na.workspace),e);let t=Qe.current;t.includes(na.workspace)&&zo(t.filter(e=>e!==na.workspace),t),Dn(null),Mn(null),Ar.current=`list`},[na,zo,Ro]),gc=(0,G.useCallback)(()=>{na&&(Dn(null),Mn(null),Kn({projectId:na.id,workspace:na.workspace,sessionHandles:na.agentSessions.map(aD)}))},[na]),_c=(0,G.useCallback)(()=>{let e=Gn?.projectId;Kn(null),e&&$o(e)},[Gn?.projectId,$o]),vc=(0,G.useCallback)(async()=>{if(!Gn)return;let e=Gn,t=await R(e.workspace,{force:!0});if(t.deleted){Eo([...e.sessionHandles,...t.removedMainPageSessionKeys??[]]);let n=qe.current;Ro(n.filter(t=>t!==e.workspace),n);let r=Qe.current;r.includes(e.workspace)&&zo(r.filter(t=>t!==e.workspace),r),Ar.current=`list`,Kn(null)}},[Gn,R,zo,Ro,Eo]),yc=(0,G.useCallback)(()=>{let e=xn?.agentId,t=wn?.projectId,n=On?.provider,r=On?.sessionId,i=jn?.returnFocusTarget??null;Sn(null),Dn(null),kn(null),Mn(null),e?Zo(e):t?$o(t):n&&r?Qo(n,r):i&&window.requestAnimationFrame(()=>i.focus({preventScroll:!0}))},[xn?.agentId,On?.provider,On?.sessionId,Zo,Qo,$o,jn?.returnFocusTarget,wn?.projectId]),bc=(0,G.useCallback)((e,t)=>{if(!t)return!1;if(e.key===`Escape`)return e.preventDefault(),e.stopPropagation(),yc(),!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(vr.current,n.length-1),a=r===-1?i:r,o=e=>{vr.current=e,n[e]?.focus()};if(e.key===`Tab`){_r.current=!0,e.preventDefault(),e.stopPropagation();let t=a+(e.shiftKey?-1:1);if(t<0||t>=n.length){yc();return}return o(t),!0}if(e.key===`ArrowDown`||e.key===`ArrowUp`){_r.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`?(_r.current=!0,e.preventDefault(),e.stopPropagation(),o(0),!0):e.key===`End`?(_r.current=!0,e.preventDefault(),e.stopPropagation(),o(n.length-1),!0):!1},[yc]),xc=(0,G.useCallback)(e=>{e.defaultPrevented||bc(e.nativeEvent,e.currentTarget)},[bc]);(0,G.useLayoutEffect)(()=>{if(!xn&&!wn&&!On&&!jn)return;let e=e=>{bc(e,document.querySelector(`.code-context-menu`))&&e.stopImmediatePropagation()};return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[xn,On,bc,jn,wn]);let Sc=(0,G.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(),ea(),Pa();return}if(e.key===`Tab`){e.preventDefault(),e.stopPropagation();let t=Mi?`[data-testid="code-composer-model-picker"]`:Ni?hF()?`[data-testid="code-composer-send"]`:`[data-testid="code-composer-mic"]`:`[data-testid="code-composer-approval"]`;ea(),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())},[Mi,ea,Pa,Ni]),Cc=(0,G.useCallback)(e=>{let t=e.relatedTarget;t&&(t instanceof Node&&e.currentTarget.contains(t)||t instanceof Element&&t.closest(`.code-composer`)||ea())},[ea]);(0,G.useEffect)(()=>{function e(e){if(a)return;let t=e.target;if(xn||wn||On||jn){if(bc(e,gr.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`&&Bn){e.preventDefault(),Ns();return}if(e.key===`Escape`&&Hn){e.preventDefault(),Ls();return}if(e.key===`Escape`&&Gn){e.preventDefault(),_c();return}if(Bn||Hn||Gn){Ht(t)||(e.preventDefault(),e.stopPropagation());return}let n=y?Wn(e):null;if(n){vF(e),_s(n);return}if(GP(e)&&!Ht(t)){e.preventDefault(),e.stopPropagation(),xs();return}if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`p`&&!e.altKey&&!e.shiftKey&&!Bn&&!Hn&&!Gn&&!Ht(t)&&!fF(t)&&!Rt(t)){let n=la(t)??ca;if(!n)return;e.preventDefault(),ss(n);return}if(!(zt(t)||Rt(t))&&!(Ht(t)&&e.key!==`Escape`)){if(e.key===`Escape`&&(ji||Mi||Ni)){e.preventDefault(),ea(),Pa();return}if(e.key===`Escape`&&i!==`projects`){e.preventDefault(),Sn(null),Dn(null),kn(null),Mn(null),Mo(),z(`projects`),Ar.current=`active-force`;return}if(e.key===`Escape`&&(xn||wn||On||jn)){e.preventDefault();let t=xn?.agentId,n=wn?.projectId,r=On?.provider,i=On?.sessionId,a=jn?.returnFocusTarget??null;Sn(null),Dn(null),kn(null),Mn(null),t?Zo(t):n?$o(n):r&&i?Qo(r,i):a&&window.requestAnimationFrame(()=>a.focus({preventScroll:!0}));return}if(y){if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`b`){e.preventDefault(),Vr();return}e.key===`/`&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.shiftKey&&(e.preventDefault(),_o())}}}return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[i,xn,Mi,ea,_c,Ls,Ns,On,Gn,a,Zo,Qo,Pa,$o,ss,bc,Hn,y,Ni,_s,jn,ji,ca,la,wn,Bn,xs,Mo,z,_o,Vr]),(0,G.useEffect)(()=>{if(!Bn)return;let e=Bn.title,t=!1;return JN(()=>{let n=lr.current;if(!n)return;let r=document.activeElement;if(r!==n&&!ur.current?.contains(r)&&n.focus(),!t&&document.activeElement===n&&n.value===e){if(t=!0,Bn.kind===`project`){let e=n.value.length;n.setSelectionRange(e,e);return}n.select()}},{delays:[0,80,180,360]})},[$n]),(0,G.useEffect)(()=>Hn?JN(()=>{dr.current?.contains(document.activeElement)||fr.current?.focus()},{runNow:!1,delays:[180]}):void 0,[Hn]),(0,G.useEffect)(()=>Gn?JN(()=>{pr.current?.contains(document.activeElement)||mr.current?.focus()},{runNow:!1,delays:[180]}):void 0,[Gn]),(0,G.useEffect)(()=>{if(!qn)return;let e=window.setTimeout(()=>Jn(null),1700);return()=>window.clearTimeout(e)},[qn]),(0,G.useEffect)(()=>{function e(e){let t=e.target;t instanceof Element&&t.closest(`.code-context-menu`)||(Sn(null),Dn(null),kn(null),Mn(null))}if(!(!xn&&!wn&&!On&&!jn))return window.addEventListener(`pointerdown`,e),()=>window.removeEventListener(`pointerdown`,e)},[xn,On,jn,wn]),(0,G.useEffect)(()=>{function e(e){let t=e.target;t instanceof Element&&t.closest(`.code-composer-menu-anchor`)||ea()}if(!(!ji&&!Mi&&!Ni))return window.addEventListener(`pointerdown`,e),()=>window.removeEventListener(`pointerdown`,e)},[Mi,ea,Ni,ji]),(0,G.useLayoutEffect)(()=>!xn&&!wn&&!On&&!jn?void 0:(_r.current=!1,vr.current=0,JN(()=>{if(_r.current)return;let e=gr.current;if(!e)return;let t=document.activeElement;if(t instanceof HTMLButtonElement&&e.contains(t))return;let n=e.querySelector(`button:not(:disabled)`);n&&(vr.current=0,n.focus())},{delays:[0,80,180,360]})),[xn,On,jn,wn]),(0,G.useEffect)(()=>{if(!Ni)return;let e=window.setTimeout(()=>{let e=Pi===`model`?`.code-model-submenu .code-model-option.selected`:Pi===`speed`?`.code-speed-submenu .code-model-option.selected`:`.code-model-picker-menu > .code-model-option.selected`,t=sr.current?.querySelector(e),n=sr.current?.querySelector(`button:not(:disabled)`);(t??n)?.focus()},0);return()=>window.clearTimeout(e)},[Ni,Pi,ma,ha,ga]),(0,G.useEffect)(()=>{if(!ji)return;let e=window.setTimeout(()=>{ar.current?.querySelector(`button:not(:disabled)`)?.focus()},0);return()=>window.clearTimeout(e)},[ji]),(0,G.useEffect)(()=>{if(!Mi)return;let e=window.setTimeout(()=>{let e=or.current?.querySelector(`.code-approval-option.selected`),t=or.current?.querySelector(`button:not(:disabled)`);(e??t)?.focus()},0);return()=>window.clearTimeout(e)},[Mi,ba]),(0,G.useEffect)(()=>{if(!fe)return;let e=window.setInterval(()=>q(Date.now()),6e4);return()=>window.clearInterval(e)},[fe]),(0,G.useEffect)(()=>{let e=window.matchMedia(`(max-width: 980px)`),t=()=>{rn(!!(window.SpeechRecognition||window.webkitSpeechRecognition)&&!lF())};return t(),e.addEventListener(`change`,t),()=>{e.removeEventListener(`change`,t),yr.current?.stop(),yr.current=null}},[]),(0,G.useEffect)(()=>Ia(),[Ia]),(0,G.useEffect)(()=>{let e=()=>{Ia(),Ha()};return window.addEventListener(`farming-agent-homes-saved`,e),()=>window.removeEventListener(`farming-agent-homes-saved`,e)},[Ha,Ia]),(0,G.useEffect)(()=>Ra(),[Ra]),(0,G.useEffect)(()=>Ga(Ri||``,X?.cwd),[X?.cwd,Ri,Ga]),(0,G.useEffect)(()=>{if(Ni)return La()},[La,Ni]),(0,G.useEffect)(()=>{if(!(!Ni||Ri!==`claude`))return Ra()},[Ri,Ra,Ni]),(0,G.useEffect)(()=>Ha(),[Ha]),(0,G.useEffect)(()=>{Na()},[Na,Ti,Ai,Oi]),(0,G.useEffect)(()=>{Ei.composer.permissionMode||Ei.composer.modelPicker||$i(e=>{let t=yA(e);return Ei.composer.plusMenu||t.mode===`default`?t:{...t,mode:`default`}})},[Ei,$i]),(0,G.useEffect)(()=>{i!==`search`&&Ne&&Mo(),i!==`projects`&&(Sn(null),Dn(null),kn(null),Mn(null),ea())},[i,Mo,ea,Ne]),(0,G.useEffect)(()=>{a&&(Sn(null),Dn(null),kn(null),Mn(null),ea())},[ea,a]),(0,G.useEffect)(()=>{if(i===`projects`)return Ia()},[i,Ia]),(0,G.useEffect)(()=>{if(i!==`history`)return;let e=!1,t=Nr.current;return fetch(r(`/api/settings`)).then(e=>e.json()).then(n=>{if(e)return;let r=n.settings??{};He($t(r.lastMainWorkspace,r.workspaceHistory??[])),We(Ln(r.projectWorkspaces)),Ze(Ln(r.pinnedProjectWorkspaces)),Ke(!0),rt(HP(r.projectNames)),t===Nr.current&&st(new Set(QO(r.mainPageSessionKeys??[]))),Fa(r),Ha(!0)}).catch(()=>{e||He([])}),()=>{e=!0}},[i,Fa,Ha]),(0,G.useEffect)(()=>{function e(e){Fr.current&&(e.preventDefault(),Yo(e.clientX))}function t(){Fr.current&&(Fr.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`)}},[Yo]),(0,G.useEffect)(()=>{let e=tr.current;if(!e||typeof ResizeObserver>`u`)return;let t=e=>{if(hF()){Lr.current||zr(),Lr.current=!0;return}if(Lr.current=!1,gF(e)){zr();return}Ir.current&&Br()};t(e.getBoundingClientRect().width);let n=new ResizeObserver(n=>{t(n[0]?.contentRect.width??e.getBoundingClientRect().width)});return n.observe(e),()=>n.disconnect()},[zr,Br]),(0,G.useEffect)(()=>{let e=Ar.current;if(!e||i!==`projects`||Ne)return;Ar.current=null;let t,n=0,r=e===`active-force`?4:12,a=()=>{n>=r||(t=window.setTimeout(o,90))},o=()=>{if(n+=1,Ao()){a();return}let t=!1;e===`list`?(hr.current?.focus({preventScroll:!0}),t=document.activeElement===hr.current):t=Oo(),(!t||e===`active-force`)&&a()},s=window.setTimeout(()=>{o()},e===`list`?0:50);return()=>{window.clearTimeout(s),t!==void 0&&window.clearTimeout(t)}},[c,i,Oo,Ne,Ao]),(0,G.useEffect)(()=>{if(!jr.current||i!==`projects`||Ne)return;jr.current=null;let e,t=0,n=()=>{t>=12||(e=window.setTimeout(r,90))},r=()=>{if(t+=1,Ao()){n();return}jo({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,c,i,jo,Ne,Ao]),(0,G.useEffect)(()=>{let e=Mr.current;if(!e||i!==`projects`||Ne||!Y.some(t=>t.id===e))return;Mr.current=null;let t,n=0,r=()=>{n+=1,Ao()||Xo(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,Xo,Ne,Ao]),(0,G.useEffect)(()=>{sa&&bn(sa)},[sa]),(0,G.useEffect)(()=>{Ve(0)},[li,Ne]),(0,G.useEffect)(()=>{Ve(e=>hi.length===0?0:Math.min(e,hi.length-1))},[hi.length]);let wc={"--code-sidebar-width":`${pn?ZP:dn}px`};return(0,K.jsxs)(`div`,{className:`code-workspace ${pn?`sidebar-collapsed`:``}`,"data-testid":`code-workspace`,ref:tr,style:wc,children:[(0,K.jsx)(iM,{sidebarCollapsed:pn,activeView:i,searchOpen:Ne,displayedProjects:si,collapsedProjectIds:sn,normalizedSearch:``,hasProjectListItems:fi,hasDisplayedProjectListItems:fi,activeTerminalId:c,selectedSearchAgentId:aa,selectedSearchSessionHandle:oa,claimedAgentSessionKeyByAgentId:Jr.claimedAgentSessionKeyByAgentId,agentShortcutKeys:gi,keyboardShortcutsEnabled:y,now:er,mainAgent:Ur,usageSummary:o,shareTarget:fa,agentLaunchOptions:it,agentCreationWorkspace:ua,openWorkspaceFile:W,openWorkspaceFiles:je,fileRevealRequest:Yn,fileSearchFocusRequest:Zn,projectListRef:hr,canLoadMoreAgentSessions:Ut,onLoadMoreAgentSessions:Wa,onNewAgent:bo,onStartAgent:xo,onToggleSidebar:Vr,onOpenSearch:Fo,onOpenWorkspaceView:Io,onOpenMainAgent:()=>{Ur&&(ye(`terminal`),z(`projects`),C(Ur.id))},onRestartMainAgent:ne,onProjectListKeyDown:Go,onToggleProject:Lo,onToggleProjectSessions:Vo,onMountProject:Bo,onOpenProjectContextMenu:Ds,onOpenProjectKeyboardMenu:Os,onOpenAgent:is,onUpdateAgentFlags:Vs,onReorderAgent:Hs,onOpenAgentContextMenu:Es,onOpenAgentKeyboardMenu:Q,onResumeAgentSession:Gs,onOpenAgentSessionContextMenu:ks,onOpenAgentSessionKeyboardMenu:As,onOpenProjectFile:os,onSelectOpenWorkspaceFile:ds,onCloseOpenWorkspaceFile:bs,onMoveWorkspaceEntries:ws,onDeleteWorkspaceEntries:Ts,onRefreshProjectOpenFiles:Me,onOpenOptionsMenu:Qs,copy:J}),(0,K.jsx)(VN,{open:Nn,activeAgentId:i===`projects`?X?.id??null:null,language:b.language,uiPreferences:b,agentLaunchOptions:it,onClose:()=>Pn(!1),onUpdateUiPreferences:ue}),Rn&&(0,K.jsx)(ij,{copy:J,title:Oa,url:Rn,onClose:()=>zn(``)}),(0,K.jsx)(`div`,{className:`code-sidebar-resizer`,"data-testid":`code-sidebar-resizer`,role:`separator`,"aria-label":J.resizeNavigation,"aria-orientation":`vertical`,"aria-valuemin":qP,"aria-valuemax":JP,"aria-valuenow":pn?ZP:dn,onPointerDown:ns}),!pn&&(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-sidebar-backdrop`,"data-testid":`code-mobile-sidebar-backdrop`,"aria-label":J.closeNavigation,onPointerDown:zr}),(0,K.jsxs)(`div`,{className:`code-mobile-topbar`,"data-testid":`code-mobile-topbar`,children:[Ma?(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-topbar-button back`,"data-testid":`code-mobile-back`,"aria-label":J.backToAgent,onClick:()=>{ja&&vs(ja)},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:yo,children:(0,K.jsx)(`span`,{"aria-hidden":`true`})}),(0,K.jsxs)(`div`,{className:`code-mobile-topbar-title`,children:[(0,K.jsx)(`strong`,{children:Oa}),Aa&&(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`i`,{"aria-hidden":`true`}),Aa]})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-topbar-button more`,"data-testid":`code-mobile-more`,"aria-label":J.openOptions,onClick:qs,children:(0,K.jsx)(`span`,{"aria-hidden":`true`})})]}),jn&&(0,K.jsx)(`div`,{className:`code-context-menu code-options-menu`,"data-testid":`code-options-menu`,style:{left:jn.x,top:jn.y},role:`menu`,ref:gr,onKeyDownCapture:xc,onKeyDown:xc,children:(0,K.jsx)(TF,{entries:$s})}),(0,K.jsx)(lA,{activeView:i,showFileEditor:da,openWorkspaceFile:W,openWorkspaceFiles:je,openAgentsCount:_i.length,visibleOpenAgents:yi,activeTerminalId:c,permissionSwitchingAgentId:l,agentSwitchingKind:u,terminalFocusRequest:_,agentCreationWorkspace:ua,displayedProjects:pi,searchQuery:Fe,searchHasQuery:ui,searchLoading:qt,visibleSearchTargetCount:hi.length,selectedSearchAgentId:aa,selectedSearchSessionHandle:oa,searchInputRef:cr,archivedRuns:ti,archivedAgents:ei,historyAgentSessions:ni,canLoadMoreHistoryAgentSessions:Ut,now:er,acpComposerProps:{active:!!X&&!Si,agentId:X?.id||``,runtimeState:bi?.state||``,sessionUpdatedAt:bi?.sessionUpdatedAt||``,runtimeError:bi?.error||``,draft:Oi,attachments:ki,composerMode:Ai,contextWindow:wi,pendingFollowUp:Ji??null,submitAction:Qi,textareaRef:nr,attachmentInputRef:ir,permissions:bi?.pendingPermissions.length?bi.pendingPermissions:bi?.pendingPermission?[bi.pendingPermission]:[],elicitations:bi?.pendingElicitations.length?bi.pendingElicitations:bi?.pendingElicitation?[bi.pendingElicitation]:[],activeElicitations:bi?.activeElicitations||[],speechSupported:nn,speechListening:an,onDraftChange:no,onNavigateHistory:ro,onRemoveAttachment:Ya,onSubmit:co,onInterrupt:lo,onDiscardPendingFollowUp:go,onToggleSpeechInput:lc,onPasteAttachment:Za,onAttachmentFiles:Xa,onChooseAttachmentFile:Ka,onActivateComposerMode:Qa,onClearComposerMode:()=>{$i(e=>({...e,mode:`default`}))},onRespondToPermission:po,onRespondToElicitation:mo},composerProps:{active:!!X&&!Si,agentKind:Ri,capabilities:Ei.composer,slashCommands:Z,draft:Oi,attachments:ki,composerMode:Ai,plusMenuOpen:ji,approvalMenuOpen:Mi,modelMenuOpen:Ni,modelPickerPane:Pi,agentModelPreset:_a,agentModel:ma,agentReasoningEffort:ha,agentServiceTier:ga,agentModelOptions:pa,currentPermissionMode:ba,permissionModeDisabled:!!l,modelProfileDisabled:Ci||!!(X&&dF(X)&&X.terminalStatus?.activity===`busy`),currentPermissionLabel:xa,currentPermissionColor:Sa,permissionModeHint:xi?J.permissionAppServerHint:J.permissionRestartHint,currentModelLabel:Ca,currentReasoningLabel:wa,currentSpeedLabel:Ta,currentReasoningOptions:va,currentServiceTierOptions:ya,permissionModeOptions:Ea,contextWindow:wi,pendingFollowUp:Ji?{messages:Ji.messages,createdAt:Ji.createdAt}:null,appServerRequest:xi?.pendingRequest||null,appServerNotice:xi?.notice||null,submitAction:Zi,speechSupported:nn,speechListening:an,textareaRef:nr,attachmentInputRef:ir,plusMenuRef:ar,approvalMenuRef:or,modelMenuRef:sr,onDraftChange:no,onNavigateHistory:ro,onRemoveAttachment:Ya,onSubmit:so,onInterrupt:lo,onSteerPendingFollowUp:ho,onDiscardPendingFollowUp:go,onRespondToAppServerRequest:uo,onRejectAppServerRequest:fo,onPasteAttachment:Za,onAttachmentFiles:Xa,onChooseAttachmentFile:Ka,onActivateComposerMode:Qa,onClearComposerMode:()=>{$i(e=>({...e,mode:`default`})),Pa()},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:ea,onSetModelPickerPane:e=>{$i(t=>({...t,ui:{...t.ui,modelPickerPane:e}}))},onComposerMenuKeyDown:Sc,onComposerMenuBlur:Cc,onUpdatePermissionMode:tc,onUpdateModel:ic,onUpdateReasoningEffort:oc,onUpdateServiceTier:sc,onUpdateModelProfile:ac,onUpdateServiceTierInline:cc,onToggleSpeechInput:lc},onNewAgent:O,onOpenTerminal:C,onOpenTerminalPath:us,onResolveTerminalPath:ls,onTerminalFollowOutputChange:to,onAgentReadLatest:eo,onRuntimeModeChange:nc,onSessionOutput:ce,onOpenSearchAgent:rs,onOpenSearchSession:e=>{Gs(e.provider,e.id,e.providerHomeId),Mo(),z(`projects`)},onSearchQueryChange:Ie,onSearchKeyDown:Jo,onCloseSearch:No,onLoadMoreHistoryAgentSessions:Wa,onSearchHistoryAgentSessions:Ba,onResumeHistorySession:Gs,onContinueArchivedRun:Ks,onOpenArchivedAgent:Ws,onRestoreArchivedAgent:Us,onChangeWorkspaceFileDraft:Cs,onUpdateOpenWorkspaceFile:Ss,onSelectOpenWorkspaceFile:ds,onOpenWorkspaceFilePath:fs,canNavigateWorkspaceBack:we,canNavigateWorkspaceForward:Te,onNavigateWorkspaceHistory:_s,onCloseOpenWorkspaceFile:bs,onCloseOpenWorkspaceFiles:ys,onRevealWorkspaceFileInExplorer:cs,onFocusWorkspaceFilesSearch:ss,onRecordWorkspaceNavigationCursor:Oe,onBackToAgentFromFile:vs,copy:J}),(0,K.jsx)(oj,{contextMenuAgent:ta,contextMenuAgentSession:ra,contextMenuProject:na,agentMenu:xn,projectMenu:wn,agentSessionMenu:On,renameDialog:Bn,killDialog:Hn,deleteWorktreeDialog:Gn,copyNotice:qn,contextMenuRef:gr,renameDialogRef:ur,renameInputRef:lr,killDialogRef:dr,killCancelButtonRef:fr,deleteWorktreeDialogRef:pr,deleteWorktreeCancelButtonRef:mr,onContextMenuKeyDown:xc,onUpdateAgentFlags:Bs,onRenameAgent:js,onRenameProject:Ms,onCopyAgentWorkingDirectory:()=>{ta&&Fs(ZE(ta),{kind:`agent`,id:ta.id})},onForkAgent:zs,onKillAgent:Is,onOpenSession:(e,t)=>{kn(null),Mn(null),Gs(e,t,ra?.providerHomeId),ra&&Qo(e,aD(ra))},onToggleSessionPinned:es,onArchiveSession:ts,onCopySessionWorkingDirectory:()=>{ra&&Fs(cD(ra),{kind:`agent-session`,provider:ra.provider,id:ra.id,providerHomeId:ra.providerHomeId})},onToggleProjectPinned:uc,onRevealProject:dc,onCreatePermanentWorktree:fc,onMarkProjectRead:pc,onArchiveProject:mc,onRemoveProject:hc,onDeleteWorktree:gc,onCloseRenameDialog:Ns,onRenameDialogTitleChange:e=>Vn(t=>t&&{...t,title:e}),onSubmitRenameDialog:Ps,onCloseKillDialog:Ls,onSubmitKillDialog:Rs,onCloseDeleteWorktreeDialog:_c,onSubmitDeleteWorktreeDialog:vc,copy:J})]})}function TF({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)(ke,{}):null}),e.icon&&(0,K.jsx)(`span`,{className:`code-context-menu-icon`,"aria-hidden":`true`,children:(0,K.jsx)(lj,{kind:e.icon})}),(0,K.jsx)(`span`,{children:e.label})]},e.id))})}var EF={appearance:`light`,language:`en`};function DF(e){return e===`light`||e===`dark`?e:EF.appearance}function OF(e){return e===`zh`||e===`en`?e:EF.language}function kF(e){return e}function AF(e=`terminal`,t={}){if(typeof document>`u`)return;let n=document.body,r=t.crtEffects!==!1,i=DF(t.appearance),a=kF(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 jF=!1,MF=240,NF=3e4,PF=1e4,FF=6e4,IF=45e3,LF=6e4;function RF(e){if(e)return e.gitWorktree?.workspace?e.gitWorktree.workspace:e.projectWorkspace?e.projectWorkspace:e.cwd}function zF(e){return!e.archived&&e.status!==`dead`&&e.status!==`stopped`}function BF(e,t){return e.restartedFromAgentId===t||e.restartedFromAgentIds?.includes(t)===!0}function VF(e,t,n){return e.filter(e=>zF(e)&&BF(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 HF(e){return e?.providerSessionProvider===`codex`&&!!e.providerSessionId&&e.providerSessionTemporary!==!0}function UF(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 WF(e){return UF(e)?(e.focus({preventScroll:!0}),document.activeElement===e||e.contains(document.activeElement)):!1}function GF(){An(`app`);let e=Pt(),t=It(),{keyMap:n}=Lt(e.agents,e.mainAgentId),[i]=(0,G.useState)(()=>j()),[a,o]=(0,G.useState)(`none`),[s,c]=(0,G.useState)(void 0),[l,u]=(0,G.useState)(void 0),[d,f]=(0,G.useState)(void 0),[p,m]=(0,G.useState)(()=>i.openTerminalIds??[]),[h,g]=(0,G.useState)(()=>i.activeTerminalId??null),[_,v]=(0,G.useState)(null),[y,b]=(0,G.useState)(null),[x,S]=(0,G.useState)(()=>i.activeView??`projects`),[C,w]=(0,G.useState)(null),[T,E]=(0,G.useState)(null),[O,k]=(0,G.useState)(null),[A,M]=(0,G.useState)(null),[N,P]=(0,G.useState)({}),[F,ee]=(0,G.useState)(EF),I=(0,G.useRef)(null),te=(0,G.useRef)(null),L=(0,G.useRef)(null),R=(0,G.useRef)(null),ne=(0,G.useRef)([]),z=(0,G.useRef)(!1),B=(0,G.useRef)(!1),ie=(0,G.useRef)(!1),ae=(0,G.useRef)(void 0),V=(0,G.useRef)(null),se=(0,G.useRef)(0);(0,G.useLayoutEffect)(()=>{ne.current=p},[p]),(0,G.useEffect)(()=>{D({activeTerminalId:h,activeView:x,openTerminalIds:p})},[h,x,p]);let ce=(0,G.useCallback)(e=>{R.current=e,E(e)},[]),le=a,ue=(0,G.useMemo)(()=>KN(F.language),[F.language]),de=(0,G.useMemo)(()=>{if(!T)return e.agents;let t=e.agents.filter(e=>e.id===T.agent.id||!BF(e,T.originalAgentId));return t.some(e=>e.id===T.agent.id)?t:[...t,T.agent]},[T,e.agents]),fe=(0,G.useMemo)(()=>{let e=new Map,t=new Set(p);return h&&t.add(h),t.forEach(t=>{if(de.some(e=>e.id===t&&zF(e)))return;let n=VF(de,t);n&&e.set(t,n.id)}),e},[h,de,p]),pe=(0,G.useMemo)(()=>{if(h){let e=fe.get(h);if(e)return{originalAgentId:h,replacementAgentId:e}}let e=fe.entries().next().value;return e?{originalAgentId:e[0],replacementAgentId:e[1]}:null},[h,fe]),me=(0,G.useMemo)(()=>Array.from(new Set(p.map(e=>fe.get(e)??e))),[fe,p]),he=h?fe.get(h)??h:null;(0,G.useLayoutEffect)(()=>{pe&&(m(me),g(he),k(pe))},[he,me,pe]),(0,G.useEffect)(()=>{!O||pe||k(null)},[O,pe]),(0,G.useEffect)(()=>{let t=R.current;if(!t)return;let n=VF(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=>BF(n,e)?n.id:e)))),g(e=>e&&BF(n,e)?n.id:e),ce(i)},[ce,T?.agent.id,T?.originalAgentId,e.agents]),(0,G.useEffect)(()=>{let t=T;!t?.requestSettled||!t.replacementAgentId||e.agents.some(e=>e.id===t.agent.id)&&R.current?.agent.id===t.agent.id&&(L.current=null,ce(null))},[ce,T?.agent.id,T?.replacementAgentId,T?.requestSettled,e.agents]),(0,G.useEffect)(()=>{let e=T;if(!e?.requestSettled||!e.requestError||e.replacementAgentId)return;let t=e.requestErrorAt??Date.now(),n=()=>{let n=rt();if(e.requestFreshStateAt||!n.connected||n.lastMessageAt<=t)return!1;let r=R.current;return r?.originalAgentId===e.originalAgentId&&!r.replacementAgentId&&!r.requestFreshStateAt&&ce({...r,requestFreshStateAt:n.lastMessageAt}),!0};if(n())return;let r=it(n),i=t+FF,a=e.requestFreshStateAt?e.requestFreshStateAt+PF:1/0,o=Math.max(0,Math.min(i,a)-Date.now()),s=window.setTimeout(()=>{let t=R.current;!t?.requestSettled||!t.requestError||t.replacementAgentId||t.originalAgentId!==e.originalAgentId||(L.current=null,ce(null),w({id:Date.now(),kind:`error`,message:t.requestError}))},o);return()=>{r(),window.clearTimeout(s)}},[ce,T]),(0,G.useEffect)(()=>{let e=T;if(!e)return;let t=Math.max(0,e.startedAt+LF-Date.now()),n=window.setTimeout(()=>{let t=R.current;!t||t.startedAt!==e.startedAt||(L.current=null,ce(null),w({id:Date.now(),kind:`error`,message:ue.agentRestartTimedOut}))},t);return()=>window.clearTimeout(n)},[ce,ue.agentRestartTimedOut,T]);let H=(0,G.useCallback)(e=>{let t={appearance:DF(e.appearance??F.appearance),language:OF(e.language??F.language)};ee(t),fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}).then(e=>e.json()).then(e=>{let n=e.settings??{};ee({appearance:DF(n.appearance??t.appearance),language:OF(n.language??t.language)})}).catch(()=>{w({id:Date.now(),kind:`error`,message:`Failed to save preferences`})})},[F.appearance,F.language]),ge=(0,G.useCallback)(e=>{let t=Array.from(new Set(e.filter(Boolean)));t.length!==0&&fetch(r(`/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:[];P(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,G.useEffect)(()=>{if(e.connected){if(e.mainAgentId||e.agents.some(e=>e.isMain)){z.current=!1;return}z.current||(z.current=!0,e.startAgent(`bash`,void 0,!0))}},[e.agents,e.connected,e.mainAgentId,e.startAgent]),(0,G.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=oe(),o=window.innerHeight||n||MF,s=a?Math.min(Math.max(n,MF),Math.max(o,MF)):n,c=Math.max(0,o-n-r),l=a&&re(),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 _e=(0,G.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]),ve=(0,G.useCallback)((e,t)=>{b({agentId:e,options:t})},[]),ye=(0,G.useCallback)((e,t)=>{if(e===h&&p.includes(e)){_e(e,t);return}ve(e,t)},[_e,h,p,ve]);(0,G.useEffect)(()=>{y&&de.some(e=>e.id===y.agentId&&zF(e))&&(b(null),_e(y.agentId,y.options))},[_e,de,y]);let be=(0,G.useCallback)(e=>{let t=new Set(e);if(t.size===0)return;let n=ne.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;ne.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]),xe=(0,G.useCallback)(e=>{be([e])},[be]),Se=(0,G.useCallback)(e=>{if(p.length===0)return;let t=p[(Math.max(0,p.findIndex(e=>e===h))+e+p.length)%p.length];t&&ye(t)},[h,ye,p]),Ce=(0,G.useCallback)((e,t,n,r)=>{let i=se.current+1;se.current=i,V.current=n??(document.activeElement instanceof HTMLElement?document.activeElement:null),c(e),u(t),f(r),S(`projects`),o(`input`);let a=()=>{se.current===i&&o(e=>e===`input`?e:`input`)};window.requestAnimationFrame(a),window.setTimeout(a,80),window.setTimeout(a,180)},[]),we=(0,G.useCallback)(()=>{let e=V.current,t=e?.getAttribute(`data-testid`)===`code-new-agent`;V.current=null;let n=()=>{WF(e)||t&&WF(document.querySelector(`[data-testid="code-new-agent"]`))||WF((h?Array.from(document.querySelectorAll(`[data-testid="code-agent-row"]`)).find(e=>e.dataset.agentId===h):null)??null)||WF(document.querySelector(`[data-testid="code-new-agent"]`))||WF(document.querySelector(`[data-testid="code-project-list"]`))};window.requestAnimationFrame(n),window.setTimeout(n,80),window.setTimeout(n,180)},[h]),Te=(0,G.useCallback)(()=>{se.current+=1,o(`none`),we()},[we]),Ee=(0,G.useCallback)(e=>{w({id:Date.now(),kind:`error`,message:e})},[]),De=(0,G.useCallback)(t=>{mC(t).catch(e=>{console.error(`Failed to destroy killed terminal session:`,e)}),e.killAgent(t),xe(t)},[e,xe]),Oe=(0,G.useCallback)(t=>{e.interruptAgent(t)},[e]),U=(0,G.useCallback)(t=>{te.current||(z.current=!0,te.current={beforeIds:new Set(e.agents.map(e=>e.id))},e.restartMainAgent(t)||(te.current=null,z.current=!1))},[e]),ke=(0,G.useCallback)((t,n,r)=>{I.current||(se.current+=1,I.current={beforeIds:new Set(e.agents.map(e=>e.id))},e.startAgent(t,n,!1,r)||(I.current=null))},[e]);(0,G.useEffect)(()=>{let t=e.lastStartedAgentId,n=I.current;!t||!n||n.beforeIds.has(t)||(I.current=null,o(`none`),ve(t))},[ve,e.lastStartedAgentId]);let Ae=(0,G.useCallback)(async(e,t)=>{try{let n=await fetch(r(`/api/agents/${e}/fork`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({mode:t})}),i=await n.json().catch(()=>null);if(!n.ok||!i?.agentId){Ee(i?.error||`Failed to fork agent (${n.status})`);return}ve(i.agentId)}catch(e){Ee(e instanceof Error?e.message:`Failed to fork agent`)}},[Ee,ve]),W=(0,G.useCallback)(async(e,t)=>{try{let n=await fetch(r(`/api/projects/delete-worktree`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({workspace:e,force:t?.force===!0})}),i=await n.json().catch(()=>null);if(!n.ok&&i?.requiresForce!==!0&&Ee(i?.error||`Failed to delete worktree (${n.status})`),i?.deleted&&be(i.archivedAgentIds??[]),i)return i;let a=`Failed to delete worktree (${n.status})`;return Ee(a),{error:a}}catch(e){let t=e instanceof Error?e.message:`Failed to delete worktree`;return Ee(t),{error:t}}},[be,Ee]),je=(0,G.useCallback)(async(e,t)=>{try{let n=await fetch(r(`/api/agents/${e}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({customTitle:t})}),i=await n.json().catch(()=>null);n.ok||Ee(i?.error||`Failed to rename agent (${n.status})`)}catch(e){Ee(e instanceof Error?e.message:`Failed to rename agent`)}},[Ee]),Me=(0,G.useCallback)(async(t,n)=>{if(n.unread===!1&&Object.keys(n).every(e=>e===`unread`||e===`readAttentionSeq`||e===`readOutputEpoch`||e===`readOutputSeq`)&&L.current===t)return!0;let i=typeof n.launchPermissionMode==`string`?n.launchPermissionMode:``,a=typeof n.agentRuntimeMode==`string`,o=i||a?e.agents.find(e=>e.id===t)??null:null,s=Tn(o)&&!a?null:o;if(s){if(L.current)return!1;L.current=t,ce({originalAgentId:t,agent:s,kind:a?`runtime`:`permission`,startedAt:Date.now()})}let c=()=>{s&&R.current?.originalAgentId===t&&(L.current=null,ce(null))};try{let e=new AbortController,a=window.setTimeout(()=>e.abort(),IF),o=await fetch(r(`/api/agents/${t}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n),signal:e.signal});window.clearTimeout(a);let l=await o.json().catch(()=>null);if(!o.ok){let e=R.current;return s&&e?.originalAgentId===t&&e.replacementAgentId?(ce({...e,requestSettled:!0}),l??!0):(c(),Ee(l?.error||`Failed to update agent (${o.status})`),!1)}if(l?.warning&&Ee(l.warning),n.archived===!0&&xe(t),l?.restartedAgentId){let e=l.restartedAgentId,r=R.current;s&&r?.originalAgentId===t&&(r.agent.id===t?(m(n=>n.map(n=>n===t?e:n)),g(n=>n===t?e:n),ce({...r,replacementAgentId:e,transitionFromAgentId:t,requestSettled:!0,agent:{...r.agent,id:e,launchPermissionMode:l.launchPermissionMode??i,runtimeBinding:Dn(l.agentRuntimeMode??n.agentRuntimeMode,r.agent.runtimeBinding),restartedFromAgentId:t,restartedFromAgentIds:Array.from(new Set([...r.agent.restartedFromAgentIds??[],t]))}})):ce({...r,requestSettled:!0,requestError:void 0}))}else c();return l??!0}catch(e){let n=e instanceof DOMException&&e.name===`AbortError`?ue.agentRestartTimedOut:e instanceof Error?e.message:`Failed to update agent`,r=R.current;return s&&r?.originalAgentId===t?(ce({...r,requestSettled:!0,requestError:n,requestErrorAt:Date.now()}),!!r.replacementAgentId):(Ee(n),!1)}},[xe,ce,ue.agentRestartTimedOut,Ee,e.agents]),Ne=(0,G.useCallback)(async e=>{await Me(e,{archived:!1})&&ve(e)},[Me,ve]),Pe=(0,G.useMemo)(()=>de.find(e=>e.id===he)??null,[de,he]);return(0,G.useEffect)(()=>{if(!t||!HF(Pe))return;let e=Pe.id,n,r;return n=window.setTimeout(()=>ge([e]),2500),r=window.setInterval(()=>ge([e]),NF),()=>{n!==void 0&&window.clearTimeout(n),r!==void 0&&window.clearInterval(r)}},[Pe?.id,Pe?.providerSessionId,Pe?.providerSessionProvider,Pe?.providerSessionTemporary,t,ge]),(0,G.useEffect)(()=>{let e=RF(Pe);e&&(ae.current=e)},[Pe]),Wt((0,G.useMemo)(()=>[],[Pe,Se,n,Ce,ye]),jF),(0,G.useEffect)(()=>{e.error&&(I.current=null,b(null),te.current=null,z.current=!1,Ee(e.error))},[Ee,e.error,e.errorId]),(0,G.useEffect)(()=>{if(!C)return;let e=window.setTimeout(()=>w(null),2800);return()=>window.clearTimeout(e)},[C]),(0,G.useEffect)(()=>{if(!t)return;let e=!1,n,i,a=()=>{fetch(r(`/api/usage`)).then(e=>e.json()).then(t=>{e||M(t.usage??null)}).catch(()=>{e||M(null)})};return i=window.setTimeout(a,1500),n=window.setInterval(a,6e4),()=>{e=!0,i!==void 0&&window.clearTimeout(i),n!==void 0&&window.clearInterval(n)}},[t]),(0,G.useEffect)(()=>{hC(de.filter(zF).map(e=>e.id)).catch(e=>{console.error(`Failed to prune terminal sessions:`,e)})},[de]),(0,G.useEffect)(()=>{let e=new Set(de.filter(zF).map(e=>e.id));m(t=>Array.from(new Set(t.map(t=>e.has(t)?t:VF(de,t)?.id??t))).filter(t=>e.has(t)||R.current?.agent.id===t))},[de]),(0,G.useEffect)(()=>{let e=new Set(de.filter(zF).map(e=>e.id));g(t=>t&&(e.has(t)||R.current?.agent.id===t)?t:p[0]??null)},[de,p]),(0,G.useEffect)(()=>{de.some(e=>!e.isMain&&zF(e))||(B.current=!1)},[de]),(0,G.useEffect)(()=>{if(p.length>0||B.current)return;let e=de.find(e=>!e.isMain&&zF(e))?.id;e&&(B.current=!0,m([e]),g(e))},[de,p.length,e.mainAgentId]),(0,G.useEffect)(()=>{let t=te.current;if(!t)return;let n=e.agents.find(e=>e.isMain&&!e.archived&&!t.beforeIds.has(e.id));n&&(te.current=null,z.current=!1,ye(n.id))},[ye,e.agents]),(0,G.useEffect)(()=>{if(ie.current||e.agents.length===0)return;let t=new URLSearchParams(window.location.search).get(`agent`);if(!t){ie.current=!0;return}e.agents.some(e=>e.id===t&&!e.archived)&&(ie.current=!0,ye(t))},[ye,e.agents]),(0,G.useEffect)(()=>(document.body.classList.add(`code-mode`),()=>{document.body.classList.remove(`code-mode`)}),[]),(0,G.useEffect)(()=>{AF(`terminal`,{crtEffects:!1,appearance:F.appearance})},[F.appearance]),(0,G.useEffect)(()=>{let e=!1;return fetch(r(`/api/settings`)).then(e=>e.json()).then(t=>{if(e)return;let n=t.settings??{};ee({appearance:DF(n.appearance),language:OF(n.language)})}).catch(()=>{}),()=>{e=!0}},[]),(0,K.jsxs)(`div`,{className:`app-container code-app-shell`,"data-testid":`app-shell`,children:[(0,K.jsx)(wF,{agents:de,taskHistory:e.taskHistory,mainPageSessionKeys:e.mainPageSessionKeys,activeView:x,dialogOpen:le!==`none`,usageSummary:A,contextWindowByAgentId:N,activeTerminalId:he,permissionSwitchingAgentId:T?.agent.id??null,agentSwitchingKind:T?.kind??null,permissionSwitchReplacement:T?.replacementAgentId?{originalAgentId:T.transitionFromAgentId??T.originalAgentId,replacementAgentId:T.replacementAgentId}:pe??O,openTerminalIds:me,terminalFocusRequest:_,keyMap:n,keyboardShortcutsEnabled:jF,uiPreferences:F,onOpenTerminal:ye,onOpenTerminalWhenReady:ve,onNewAgent:Ce,onStartAgent:ke,onRenameAgent:je,onUpdateAgentFlags:Me,onOpenArchivedAgent:Ne,onForkAgent:Ae,onDeleteForkWorktreeProject:W,onRestartMainAgent:U,onWorkspaceViewChange:S,onKill:De,onInterruptAgent:Oe,sendComposerInput:e.sendComposerInput,respondToAppServerRequest:e.respondToAppServerRequest,onSessionOutput:e.onSessionOutput,onUpdateUiPreferences:H}),(0,K.jsx)(vn,{open:le===`input`,mustStartMain:!1,initialWorkspace:s,initialCommand:l,initialCustomTitle:d,showWorkflowTaskFields:!1,copy:ue,onStart:ke,onClose:Te}),(0,K.jsx)(Sn,{copy:ue}),C&&(0,K.jsx)(`div`,{className:`app-toast ${C.kind}`,"data-testid":`app-toast`,role:`status`,children:C.message})]})}export{GF as App};
|
|
206
|
+
`))})),Pa()},[Ti,qa,Pa,me]),Ya=(0,G.useCallback)(e=>{$i(t=>{let n=t.attachments.find(t=>t.id===e);return n&&IA(n),{...t,attachments:t.attachments.filter(t=>t.id!==e)}}),Pa()},[Pa,$i]),Xa=(0,G.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value=``,Ja(t)},[Ja]),Za=(0,G.useCallback)(e=>{let t=GA(e.clipboardData);t.length!==0&&(e.preventDefault(),Ja(t))},[Ja]);(0,G.useEffect)(()=>{let e=ir.current;if(e)return e.addEventListener(`cancel`,Pa),()=>e.removeEventListener(`cancel`,Pa)},[Pa]),(0,G.useEffect)(()=>{rr.current=Object.values(pe).flatMap(e=>e.attachments)},[pe]),(0,G.useEffect)(()=>()=>{rr.current.forEach(IA)},[]);let Qa=(0,G.useCallback)(e=>{$i(t=>({...t,mode:e,ui:{...t.ui,plusMenuOpen:!1}})),Pa()},[Pa,$i]),$a=(0,G.useCallback)((e,t=!1,n=null)=>{let r=Y.find(t=>t.id===e);if(!r)return;let i=Number.isFinite(r.attentionSeq)?Math.max(0,Number(r.attentionSeq)):0,a=Number.isFinite(r.readAttentionSeq)?Math.max(0,Number(r.readAttentionSeq)):0;!t&&i<=a&&!r.unread||F(e,{unread:!1,...n?{readOutputEpoch:n.runtimeEpoch,readOutputSeq:n.outputSeq}:{}})},[Y,F]),eo=(0,G.useCallback)((e,t=null)=>{$a(e,!0,t)},[$a]),to=(0,G.useCallback)((e,t)=>{_e(n=>{let r=n[e];return r?.following===t.following&&r?.hasUnreadOutput===t.hasUnreadOutput?n:{...n,[e]:t}})},[]),no=(0,G.useCallback)(e=>{$i(t=>({...t,draft:e,history:{...t.history,cursor:null}}))},[$i]),ro=(0,G.useCallback)((e,t)=>{if(!X||!Ti||!fA(t))return null;let n=pA(Di.history,e,t.value);return n.changed?(me(Ti,e=>({...e,draft:n.value,history:n.history})),n.value):null},[X,Ti,Di.history,me]),io=(0,G.useCallback)(async(e,t,n,i)=>{if(!dF(e))return!0;if(Ct.current.has(e.id))return!1;Ct.current.add(e.id);let a={model:t,reasoningEffort:n,serviceTier:i,source:`pending-terminal-command`};St(t=>{let n=new Map(t);return n.set(e.id,a),n}),bt(t=>new Set(t).add(e.id)),Jn({id:Date.now(),kind:`success`,message:J.terminalProfileApplying});let o=new AbortController,s=window.setTimeout(()=>{o.abort(new DOMException(`Timed out applying the Codex Terminal profile`,`TimeoutError`))},sF);try{let a=await fetch(r(`/api/agents/${encodeURIComponent(e.id)}/codex-terminal-profile`),{method:`POST`,headers:{"Content-Type":`application/json`},signal:o.signal,body:JSON.stringify({model:t,effort:n,serviceTier:i})}),s=await a.json().catch(()=>({}));if(!a.ok)throw Error(s.error||`Failed to update Codex Terminal (${a.status})`);return Jn({id:Date.now(),kind:`success`,message:J.terminalProfileApplied}),!0}catch(t){St(t=>{let n=new Map(t);return n.delete(e.id),n});let n=t instanceof Error?t.message:`Failed to update Codex Terminal`;return Jn({id:Date.now(),kind:`error`,message:J.terminalProfileFailed(n)}),!1}finally{window.clearTimeout(s),Ct.current.delete(e.id),bt(t=>{let n=new Set(t);return n.delete(e.id),n})}},[J.terminalProfileApplied,J.terminalProfileApplying,J.terminalProfileFailed]);(0,G.useEffect)(()=>{let e=X?.codexTerminalProfile;!X||!e||St(t=>{let n=t.get(X.id);if(!n||e.model!==n.model||e.reasoningEffort!==n.reasoningEffort||e.serviceTier!==n.serviceTier)return t;let r=new Map(t);return r.delete(X.id),r})},[X?.id,X?.codexTerminalProfile?.model,X?.codexTerminalProfile?.reasoningEffort,X?.codexTerminalProfile?.serviceTier]);let ao=(0,G.useCallback)((e,t,n=[])=>En(e)?ae(t,e.id,Cn(e)?n:[]):Dk(e.command)===`shell`||Pk(e).kind===`shell`||uF(e.command)?uC(e.id,`${t}\r`):uC(e.id,UN(t)),[ae]),oo=(0,G.useCallback)(async(e,t)=>(await fetch(r(`/api/agents/${encodeURIComponent(e.id)}/codex-goal`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({objective:t,status:`active`,tokenBudget:null})})).ok,[]),so=(0,G.useCallback)(e=>{let t=e??nr.current?.value??Oi,n=RA(t,ki);if(!n||!X||!Ti||ki.some(e=>e.status===`uploading`))return;if(Ai===`goal`&&xi){(async()=>{await oo(X,n)&&ao(X,n)&&(me(Ti,e=>(e.attachments.forEach(IA),{...e,draft:``,attachments:[],mode:`default`,history:dA(e.history,t)})),Pa())})();return}let r=KA(Ai,n),i=!0;UE(X)&&X.runtimeBinding.kind===`terminal`?me(Ti,e=>{let t=e.pendingFollowUp;return{...e,pendingFollowUp:{messages:[...t?.messages||[],_A(r)],createdAt:t?.createdAt||Date.now()}}}):i=ao(X,r),i&&(me(Ti,e=>(e.attachments.forEach(IA),{...e,draft:``,attachments:[],mode:`default`,history:dA(e.history,t)})),Pa())},[X,xi,Ti,ki,Ai,Oi,Pa,ao,oo,me]),co=(0,G.useCallback)(e=>{let t=e??nr.current?.value??Oi,n=!!(bi&&X&&ge.current[X.id]!==void 0),r=qA({agent:X,composerKey:Ti,draft:t,attachments:ki,composerMode:Ai,turnActive:Ii||n,sendMessage:ao,updateComposerState:me});r&&X&&bi&&!Ii&&!n&&(ge.current[X.id]=Number(bi.sessionRevision)||0),r&&Pa()},[bi,X,Ii,Ti,ki,Ai,Oi,Pa,ao,me]),lo=(0,G.useCallback)(()=>{!X||!qi||(re(X.id),Pa())},[X,qi,Pa,re]),uo=(0,G.useCallback)((e,t)=>{X&&se(X.id,e,t)},[X,se]),fo=(0,G.useCallback)(e=>{X&&se(X.id,e,void 0,{reject:!0,reason:`Declined in Farming`})},[X,se]),po=(0,G.useCallback)((e,t,n)=>{X&&JA(X.id,e,t,n===!0)},[X]),mo=(0,G.useCallback)((e,t,n)=>{X&&YA(X.id,e,t,n)},[X]),ho=(0,G.useCallback)(e=>{if(!X||!Ti)return;let t=pe[Ti]?.pendingFollowUp;if(!t||t.messages.length===0)return;let n=t.messages.find(t=>t.id===e);n&&ao(X,n.text,n.attachments)&&(H.current[Ti]=n.id,me(Ti,t=>t.pendingFollowUp?{...t,pendingFollowUp:vA(t.pendingFollowUp,e)}:t),Pa())},[X,Ti,pe,Pa,ao,me]),go=(0,G.useCallback)(e=>{!X||!Ti||(me(Ti,t=>t.pendingFollowUp?{...t,pendingFollowUp:vA(t.pendingFollowUp,e)}:t),Pa())},[X,Ti,Pa,me]);(0,G.useEffect)(()=>{let e=new Set(Y.map(e=>e.id));Object.keys(ge.current).forEach(t=>{e.has(t)||delete ge.current[t]}),Y.forEach(e=>{let t=ge.current[e.id];if(t===void 0)return;let n=Cn(e)?e.runtimeBinding:null,r=WE(e)||(Number(n?.sessionRevision)||0)>t;(!n||r||n.state===`error`||e.archived||e.status===`dead`||e.status===`stopped`)&&delete ge.current[e.id]})},[Y]),(0,G.useEffect)(()=>{let e=[];Y.forEach(t=>{let n=Cn(t),r=n?ZA(t):CA(t);if(!r)return;let i=pe[r]?.pendingFollowUp;if(!i||i.messages.length===0){delete H.current[r];return}if(t.archived||t.status===`dead`||t.status===`stopped`||n&&ge.current[t.id]!==void 0)return;if(n?WE(t):UE(t)){delete H.current[r];return}if(H.current[r])return;let a=i.messages[0];a&&e.push({agent:t,composerKey:r,message:a})}),e.length!==0&&e.forEach(({agent:e,composerKey:t,message:n})=>{ao(e,n.text,n.attachments)&&(H.current[t]=n.id,he(t,e=>e.pendingFollowUp?{...e,pendingFollowUp:vA(e.pendingFollowUp,n.id)}:e))})},[Y,pe,ao,he]);let _o=(0,G.useCallback)(()=>{Sn(null),Dn(null),kn(null),Mn(null),ea(),Br(),z(`search`),Pe(!0),requestAnimationFrame(()=>cr.current?.focus())},[ea,Br,z]),vo=(0,G.useCallback)(()=>{hF()&&zr()},[zr]),yo=(0,G.useCallback)(()=>{Br()},[Br]),bo=(0,G.useCallback)((e,t,n)=>{O(e,t,n),vo()},[vo,O]),xo=(0,G.useCallback)((e,t,n)=>{if(Ie(``),Pe(!1),Ve(0),ye(`terminal`),z(`projects`),Dk(e)!==`codex`){M(e,t,n);return}let r=n?.codexApprovalMode||ct;M(e,t,{...n,codexApprovalMode:r,...r===`full`?{dangerouslySkipPermissions:!0}:{}})},[ct,M,z]);(0,G.useEffect)(()=>{let e=!1;return fetch(r(`/api/executables`)).then(e=>{if(!e.ok)throw Error(`Failed to load executables: ${e.status}`);return e.json()}).then(t=>{e||at(Jt(Array.isArray(t)?t:t.agents??[]))}).catch(()=>{e||at([])}),()=>{e=!0}},[]);let So=(0,G.useCallback)(e=>{fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({mainPageSessionKeys:QO(e)})}).catch(()=>{})},[]),Co=(0,G.useCallback)(e=>{st(t=>{let n=QO(e(t));return WP(t,n)?t:(Nr.current+=1,So(n),new Set(n))})},[So]);(0,G.useEffect)(()=>{let e=QO(n);st(t=>WP(t,e)?t:new Set(e))},[n]);let wo=(0,G.useCallback)((e,t,n=``)=>{let r=aD({provider:e,id:t,providerHomeId:n});Co(e=>[...e,r])},[Co]),To=(0,G.useCallback)(e=>{Co(t=>Array.from(t).filter(t=>t!==e))},[Co]),Eo=(0,G.useCallback)(e=>{let t=new Set(e);Co(e=>Array.from(e).filter(e=>!t.has(e)))},[Co]),Do=(0,G.useCallback)(e=>{Promise.resolve(e).then(e=>{if(!e||typeof e!=`object`)return;let t=Array.isArray(e.removedMainPageSessionKeys)?e.removedMainPageSessionKeys:[];t.length>0&&Eo(t)}).catch(()=>{})},[Eo]);(0,G.useEffect)(()=>{let e=!1;Y.forEach(t=>{if(t.providerSessionTemporary===!0)return;let n=t.providerSessionKey||nk(t.source);if(!n)return;let r=`${t.id}:${n}`;Pr.current.has(r)||(Pr.current.add(r),Co(e=>[...e,n]),e=!0)}),e&&Ua()},[Y,Ua,Co]),(0,G.useEffect)(()=>{if(!fe||!Y.some(e=>e.providerSessionTemporary===!0))return;Ua();let e=window.setInterval(Ua,5e3);return()=>window.clearInterval(e)},[Y,fe,Ua]);let Oo=(0,G.useCallback)(()=>{let e=Cr.current,t=Array.from(tr.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]??hr.current;return n?(n.focus({preventScroll:!0}),document.activeElement===n):!1},[]),ko=(0,G.useCallback)(e=>{let t=Array.from(tr.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===mF(e));return t?(t.focus({preventScroll:!0}),document.activeElement===t):!1},[]),Ao=(0,G.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||hr.current?.contains(e)||e.closest(`.code-sidebar`)?!1:!!e.closest(`.code-composer`):!1},[a]),jo=(0,G.useCallback)(e=>{window.requestAnimationFrame(()=>{e?.skipIfFocusMoved&&Ao()||Oo()})},[Oo,Ao]),Mo=(0,G.useCallback)(()=>{Ie(``),Pe(!1),Ve(0)},[]),No=(0,G.useCallback)(()=>{Mo(),z(`projects`),Ar.current=`active-force`},[Mo,z]);(0,G.useEffect)(()=>{if(!Ne||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"]`)||No())};return document.addEventListener(`pointerdown`,e,!0),()=>{document.removeEventListener(`pointerdown`,e,!0)}},[i,No,Ne]);let Po=(0,G.useCallback)(e=>{Sn(null),Dn(null),kn(null),Mn(null),e===`projects`?(Br(),Mo()):e!==`search`&&Mo(),z(e)},[Mo,Br,z]),Fo=(0,G.useCallback)(()=>{_o(),vo()},[vo,_o]),Io=(0,G.useCallback)(e=>{Po(e),vo()},[vo,Po]),Lo=(0,G.useCallback)(e=>{cn(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,G.useEffect)(()=>{qe.current=Ue},[Ue]),(0,G.useEffect)(()=>{Qe.current=Xe},[Xe]);let Ro=(0,G.useCallback)((e,t)=>{let n=Ln(e),i=Je.current+=1;qe.current=n,We(n),Ye.current=Ye.current.catch(()=>{}).then(async()=>{let e=await fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({projectWorkspaces:n})});if(!e.ok)throw Error(`settings request failed (${e.status})`);let t=await e.json();if(i!==Je.current)return;let a=Ln(t.settings?.projectWorkspaces);qe.current=a,We(a)}).catch(()=>{if(i!==Je.current)return;let e=Ln(t);qe.current=e,We(e),Jn({id:Date.now(),kind:`error`,message:J.copyFailed})})},[J.copyFailed]),zo=(0,G.useCallback)((e,t)=>{let n=Ln(e),i=$e.current+=1;Qe.current=n,Ze(n),et.current=et.current.catch(()=>{}).then(async()=>{let e=await fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinnedProjectWorkspaces:n})});if(!e.ok)throw Error(`settings request failed (${e.status})`);let t=await e.json();if(i!==$e.current)return;let a=Ln(t.settings?.pinnedProjectWorkspaces);Qe.current=a,Ze(a)}).catch(()=>{if(i!==$e.current)return;let e=Ln(t);Qe.current=e,Ze(e),Jn({id:Date.now(),kind:`error`,message:J.copyFailed})})},[J.copyFailed]),Bo=(0,G.useCallback)(e=>{let t=e.trim().replace(/[\\/]+$/,``);if(!t)return;let n=qe.current;n.includes(t)||Ro([t,...n],n),cn(e=>{if(!e.has(t))return e;let n=new Set(e);return n.delete(t),n})},[Ro]);(0,G.useEffect)(()=>{if(!Ge)return;let e=qe.current,t=oi.filter(e=>!e.hasMain&&!!e.workspace).map(e=>e.workspace).filter(t=>!e.includes(t)&&!tt.current.has(t));t.length!==0&&(t.forEach(e=>tt.current.add(e)),Ro([...t,...e],e))},[Ro,oi,Ge]);let Vo=(0,G.useCallback)(e=>{un(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Ho=(0,G.useCallback)((e,t)=>{ye(`terminal`),z(`projects`),e.kind===`agent`?C(e.id,{focusTerminal:t?.focusTerminal}):Sr.current(e.provider,e.id,e.providerHomeId)},[C,z]),Uo=(0,G.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 YE({kind:`agent`,id:t.dataset.agentId});if(t?.dataset.sessionId&&t.dataset.provider)return t.dataset.sessionId}let t=Cr.current;return t?YE({kind:`agent`,id:t}):``},[]),Wo=(0,G.useCallback)(e=>{if(mi.length===0)return;let t=Uo(),n=mi.findIndex(e=>mF(e)===t),r=mi[((n===-1?e>0?-1:0:n)+e+mi.length)%mi.length];r&&(Ho(r,{focusTerminal:!1}),r.kind===`agent`&&(Ao()||ko(r),window.requestAnimationFrame(()=>{Ao()||ko(r)})),Ar.current=`active`)},[Uo,ko,Ho,Ao,mi]),Go=(0,G.useCallback)(e=>{if(!(e.ctrlKey||e.metaKey||e.altKey)){if(e.key===`/`&&!e.shiftKey){e.preventDefault(),_o();return}if(e.key===`ArrowDown`){e.preventDefault(),Wo(1);return}e.key===`ArrowUp`&&(e.preventDefault(),Wo(-1))}},[Wo,_o]),Ko=(0,G.useCallback)(e=>{hi.length!==0&&Ve(t=>(t+e+hi.length)%hi.length)},[hi.length]),qo=(0,G.useCallback)(()=>{ia&&(Ho(ia),Mo())},[Mo,Ho,ia]),Jo=(0,G.useCallback)(e=>{if(e.key===`Escape`){e.preventDefault(),No();return}if(e.key===`ArrowDown`){e.preventDefault(),Ko(1);return}if(e.key===`ArrowUp`){e.preventDefault(),Ko(-1);return}e.key===`Enter`&&(e.preventDefault(),qo())},[No,Ko,qo]),Yo=(0,G.useCallback)(e=>{let t=tr.current?.getBoundingClientRect(),n=e-(t?.left??0);if(n<=QP){Rr();return}let r=t?.width??window.innerWidth,i=Math.max(qP,Math.min(JP,r-YP)),a=Math.max(qP,Math.min(i,n));Br(),fn(a)},[Rr,Br]),Xo=(0,G.useCallback)(e=>{let t=Array.from(tr.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},[]),Zo=(0,G.useCallback)(e=>{JN(()=>{Xo(e)},{delays:[80,180]})},[Xo]),Qo=(0,G.useCallback)((e,t)=>{window.requestAnimationFrame(()=>{Array.from(tr.current?.querySelectorAll(`[data-testid="code-active-session-row"]`)??[]).find(n=>n.dataset.provider===e&&n.dataset.sessionId===t)?.focus({preventScroll:!0})})},[]),$o=(0,G.useCallback)(e=>{window.requestAnimationFrame(()=>{Array.from(tr.current?.querySelectorAll(`[data-testid="code-project-title"]`)??[]).find(t=>t.dataset.projectId===e)?.focus()})},[]),es=(0,G.useCallback)(async()=>{if(!ra)return;let e=aD(ra),t=ra.pinned!==!0;tn(n=>({...n,[e]:t})),kn(null),Mn(null),ot.has(e)?Qo(ra.provider,e):window.requestAnimationFrame(()=>hr.current?.focus({preventScroll:!0}));try{if(!(await fetch(r(`/api/agent-sessions/${encodeURIComponent(ra.provider)}/${encodeURIComponent(ra.id)}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:t,providerHomeId:ra.providerHomeId||`default`})})).ok)throw Error(J.updateFailed);let n=await Va({limit:Qt.current});Lt(n.sessions),Vt(n.nextCursor),Wt(n.hasMore),tn(t=>{let n={...t};return delete n[e],n})}catch(n){tn(n=>({...n,[e]:!t})),Jn({id:Date.now(),kind:`error`,message:n instanceof Error?n.message:J.updateFailed})}},[ra,J.updateFailed,Va,Qo,ot]),ts=(0,G.useCallback)(()=>{if(!ra)return;let e=aD(ra);tn(t=>({...t,[e]:!1})),To(e),kn(null),Mn(null),window.requestAnimationFrame(()=>hr.current?.focus({preventScroll:!0}))},[ra,To]),ns=(0,G.useCallback)(e=>{e.preventDefault(),Br(),Fr.current=!0,document.body.classList.add(`code-resizing-sidebar`),Yo(e.clientX)},[Br,Yo]),rs=(0,G.useCallback)((e,t)=>{Sn(null),Dn(null),kn(null),Mn(null),Mo(),ye(`terminal`),z(`projects`),C(e,t)},[Mo,C,z]),is=(0,G.useCallback)(e=>{rs(e),vo()},[vo,rs]),as=(0,G.useCallback)(e=>f(e,{cursorRequestId:e?.lineNumber?wr.current+=1:wr.current,diffRequestId:e?.view===`diff`?Tr.current+=1:Tr.current}),[]),os=(0,G.useCallback)((e,t,n)=>{let r=Kr(e,n?.sourceAgentId),i=Le(r.filesId),a=In(r.filesId);if(!i&&(a||r.sourceAgent)){let e=a||(r.sourceAgent?.isMain?`__farming_main_agent__`:ZE(r.sourceAgent));cn(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}Sn(null),Dn(null),kn(null),Mn(null),Mo(),z(`projects`),ye(`editor`);let o={...as(n),workspaceRoot:r.workspaceRoot,sourceAgentId:r.sourceAgentId};Ce.openFromRead(r.filesId,t,o),p(n)&&Xn({agentId:r.filesId,path:t.path,kind:`file`,requestId:Er.current+=1}),r.sourceAgent&&r.sourceAgentId&&C(r.sourceAgentId,{focusTerminal:!1}),vo()},[Mo,vo,as,C,z,Kr,Ce]);(0,G.useEffect)(()=>{if(Se.current||xe.current)return;let e=be;if(!e){Se.current=!0;return}if(e.kind===`agent`){if(Y.length===0)return;xe.current=!0;let t=Y.find(t=>t.id===e.agentId)??Y.find(t=>!!e.providerSessionKey&&t.providerSessionKey===e.providerSessionKey)??Y.find(t=>!!e.workspace&&ZE(t)===e.workspace);t?rs(t.id,{focusTerminal:!1}):D({surface:void 0}),Se.current=!0;return}if(!Ge)return;xe.current=!0;let t=Y.find(t=>t.id===e.sourceAgentId&&(e.workspace===`/`||Fn(ZE(t))===Fn(e.workspace)))??Y.find(t=>Fn(ZE(t))===Fn(e.workspace)),n=e.workspace===`/`?Be:Fn(e.workspace);if(!(e.workspace===`/`||Ue.some(e=>Fn(e)===n)||t)){D({surface:void 0}),Se.current=!0;return}let r=Kr(n,t?.id);le(r.filesId,e.filePath).then(t=>{os(r.filesId,t,{view:e.view??`editor`,lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn,revealInTree:!0,sourceAgentId:r.sourceAgentId})}).catch(()=>{D({surface:void 0})}).finally(()=>{Se.current=!0})},[Y,be,os,rs,Ue,Ge,Kr]),(0,G.useEffect)(()=>{if(!Se.current||i!==`projects`)return;if(ve===`terminal`){let e=Y.find(e=>e.id===c);if(!e)return;D({surface:{kind:`agent`,agentId:e.id,providerSessionKey:e.providerSessionKey||void 0,workspace:ZE(e)}});return}if(!W)return;let e=W.workspaceRoot??Y.find(e=>e.id===W.agentId)?.projectWorkspace??Y.find(e=>e.id===W.agentId)?.cwd??``;e&&D({surface:{kind:`file`,workspace:e,filePath:W.file.path,view:W.diffRequestId?`diff`:`editor`,lineNumber:W.cursor?.lineNumber,column:W.cursor?.column,endColumn:W.cursor?.endColumn,sourceAgentId:W.sourceAgentId}})},[Y,c,i,ve,W]);let ss=(0,G.useCallback)((e,t)=>{let n=Kr(e),r=In(n.filesId);if(!Le(n.filesId)&&(r||n.sourceAgent)){let e=r||(n.sourceAgent?.isMain?`__farming_main_agent__`:ZE(n.sourceAgent));cn(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}Sn(null),Dn(null),kn(null),Mn(null),Mo(),Br(),z(`projects`),Qn({agentId:n.filesId,...t?{query:t}:{},requestId:Dr.current+=1})},[Mo,Br,z,Kr]),cs=(0,G.useCallback)((e,t,n)=>{let r=Kr(e),i=In(r.filesId);if(!Le(r.filesId)&&(i||r.sourceAgent)){let e=i||(r.sourceAgent?.isMain?`__farming_main_agent__`:ZE(r.sourceAgent));cn(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}Sn(null),Dn(null),kn(null),Mn(null),Mo(),Br(),z(`projects`),Xn({agentId:r.filesId,path:t,kind:n,requestId:Er.current+=1})},[Mo,Br,z,Kr]),ls=(0,G.useCallback)(async(e,t)=>{let n=Kr(e,e),r=Qw(t.path,n.workspaceRoot??``);if(!r)return null;try{let e=xF((await de(n.filesId,r,{limit:eF})).matches),i=e.find(e=>e.path===r)?.path??(e.length===1?e[0]?.path:``);return i?{...t,path:i}:null}catch{return null}},[Kr]),us=(0,G.useCallback)((e,t)=>{let n=Kr(e,e),r=Qw(t.path,n.workspaceRoot??``);if(!r)return;let i=Or.current+1;Or.current=i;let a=bF(t),o={...a??{},sourceAgentId:n.sourceAgentId},s=async(e,t=o)=>{let r=await le(n.filesId,e);Or.current===i&&os(n.filesId,r,t)},c=e=>{Or.current===i&&cs(n.filesId,e,`directory`)},l=async e=>{if(e.entryType===`directory`){c(e.path);return}await s(e.path)},u=()=>{Or.current===i&&ss(n.filesId,r)};(async()=>{try{await V(n.filesId,r),c(r);return}catch{}try{await s(r);return}catch{}try{let e=await de(n.filesId,r,{limit:eF});if(Or.current!==i)return;let t=xF(e.matches);if(t.length===1){let e=t[0];if(!e)return;await l(e);return}let c=SF(e.matches);if(t.length===0&&c.length===1){let e=c[0];if(!e)return;await s(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,sourceAgentId:n.sourceAgentId}:o);return}}catch{}u()})()},[ss,os,Kr,cs]),ds=(0,G.useCallback)((e,t,n)=>{let r=Kr(e,n?.sourceAgentId),i=Le(r.filesId),a=In(r.filesId);if(!i&&(a||r.sourceAgent)){let e=a||(r.sourceAgent?.isMain?`__farming_main_agent__`:ZE(r.sourceAgent));cn(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}let o=h({agentId:r.filesId,workspaceRoot:r.workspaceRoot,filePath:t});if(!je.some(e=>d(e)===o))return!1;let s={...as(n),workspaceRoot:r.workspaceRoot,sourceAgentId:r.sourceAgentId};return Ce.select(r.filesId,t,s)?(Sn(null),Dn(null),kn(null),Mn(null),Mo(),z(`projects`),ye(`editor`),p(n)&&Xn({agentId:r.filesId,path:t,kind:`file`,requestId:Er.current+=1}),r.sourceAgent&&r.sourceAgentId&&C(r.sourceAgentId,{focusTerminal:!1}),vo(),!0):!1},[Mo,vo,as,C,z,je,Kr,Ce]),fs=(0,G.useCallback)(async(e,t,n)=>{let r=Kr(n?.globalRoot?Be:e,n?.sourceAgentId??(n?.globalRoot?e:void 0)),i=r.filesId,a=n?.globalRoot?Re(t):t,o=n?{...n,sourceAgentId:r.sourceAgentId}:r.sourceAgentId?{sourceAgentId:r.sourceAgentId}:void 0;if(ds(i,a,o))return;let s=async(e,t=o)=>{os(i,await le(i,e),t)};try{await s(a,o)}catch{try{await V(i,a),cs(i,a,`directory`)}catch{try{let e=await de(i,a,{limit:eF}),t=xF(e.matches),c=SF(e.matches);if(t.length===1){let e=t[0];if(e?.entryType===`directory`){cs(i,e.path,`directory`);return}if(e?.path){await s(e.path,o);return}}if(t.length===0&&c.length===1){let e=c[0];if(e?.path){await s(e.path,!n&&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,sourceAgentId:r.sourceAgentId}:o);return}}}catch{}o?.suppressSearchOnMiss||ss(i,a)}}},[ss,os,Kr,cs,ds]),ps=(0,G.useCallback)(async e=>{if(ie(e.kind===`agent`?e.readingAnchor:void 0),e.kind===`agent`)return Wr.has(e.agentId)?(Sn(null),Dn(null),kn(null),Mn(null),Mo(),z(`projects`),ye(`terminal`),C(e.agentId,{focusTerminal:!1}),vo(),!0):!1;let t=k(e,[...Y.filter(e=>!e.isMain).map(e=>({agentId:e.id,workspace:ZE(e)})),...Ue.map(e=>({agentId:Fn(e),workspace:e}))],Be);if(!t)return!1;let n=Kr(t.agentId,t.agentId);if(e.kind===`folder`)try{let e=S((await V(n.filesId,t.filePath)).items);if(e){let t=await le(n.filesId,e);return os(n.filesId,t,{sourceAgentId:n.sourceAgentId}),!0}return cs(n.filesId,t.filePath,`directory`),!0}catch{return!1}let r={...I(e),sourceAgentId:n.sourceAgentId};if(ds(n.filesId,t.filePath,r))return!0;try{let e=await le(n.filesId,t.filePath);return os(n.filesId,e,r),!0}catch{return!1}},[Y,Mo,vo,C,z,os,Ue,cs,Kr,ds,Wr]),ms=(0,G.useRef)(ps);ms.current=ps;let hs=(0,G.useCallback)(()=>{if(typeof window>`u`)return;let e=x(window.location.search);window.history.replaceState(window.history.state,``,`${window.location.pathname}${e}${window.location.hash}`)},[]);(0,G.useEffect)(()=>{if(!hn)return;let e=!1,t=null,n=hn.kind===`agent`?hn.agentId:hn.absolutePath||(hn.kind===`folder`?hn.folderPath:hn.filePath);return ms.current(hn).then(r=>{if(!e){if(r){gn(null),hs();return}if(kr.current+=1,kr.current>=20){Jn({id:Date.now(),kind:`error`,message:J.sharedLocationUnavailable(n)}),gn(null),hs();return}t=window.setTimeout(()=>{vn(e=>e+1)},250)}}).catch(()=>{e||(Jn({id:Date.now(),kind:`error`,message:J.sharedLocationUnavailable(n)}),gn(null),hs())}),()=>{e=!0,t!==null&&window.clearTimeout(t)}},[hs,J.sharedLocationUnavailable,hn,_n]);let gs=(0,G.useCallback)(async e=>{if(e.kind===`agent`){if(!Wr.has(e.agentId))return!1}else if(!Gr.has(e.agentId))return!1;if(Sn(null),Dn(null),kn(null),Mn(null),Mo(),z(`projects`),e.kind===`agent`)return ye(`terminal`),C(e.agentId),vo(),!0;let t={view:e.view,lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn,sourceAgentId:e.sourceAgentId},n=Kr(e.agentId,e.sourceAgentId);if(ds(n.filesId,e.filePath,t))return!0;try{let r=await le(n.filesId,e.filePath);return os(n.filesId,r,t),!0}catch{return!1}},[Mo,vo,C,z,os,Kr,ds,Wr,Gr]),_s=(0,G.useCallback)(e=>{let t=U(e);return t?((async()=>{let n=t;for(;n;){if(await gs(n))return;n=U(e)}})().finally(()=>{ke()}),!0):!1},[U,ke,gs]),vs=(0,G.useCallback)(e=>{Or.current+=1,ye(`terminal`),z(`projects`),C(e,{focusTerminal:!oe()}),vo()},[vo,C,z]),ys=(0,G.useCallback)(e=>{let t=Ce.close(e);t.closedFiles.length!==0&&t.activeFileClosed&&ye(t.activeFile?`editor`:`terminal`)},[Ce]),bs=(0,G.useCallback)((e,t,n)=>{ys([{agentId:e,filePath:t,workspaceRoot:n}])},[ys]),xs=(0,G.useCallback)(()=>{let e=Ce.reopenLastClosed(e=>Gr.has(e.agentId))?.activeFile;if(!e)return!1;Sn(null),Dn(null),kn(null),Mn(null),Mo(),z(`projects`),ye(`editor`);let t=e.sourceAgentId;return t&&Y.some(e=>e.id===t)&&C(t,{focusTerminal:!1}),vo(),!0},[Y,Mo,vo,C,z,Gr,Ce]),Ss=(0,G.useCallback)(e=>{Ce.update(e)},[Ce]),Cs=(0,G.useCallback)(e=>{Ce.updateDraft(e)},[Ce]),ws=(0,G.useCallback)((e,t)=>{t.length!==0&&Ce.move(e,t)},[Ce]),Ts=(0,G.useCallback)((e,t)=>{if(t.length===0)return;let n=Ce.deleteEntries(e,t);n.activeFileDeleted&&(n.activeFile||ye(`terminal`))},[Ce]),Es=(0,G.useCallback)((e,t)=>{e.preventDefault(),e.stopPropagation();let n=Y.find(e=>e.id===t),r=xj(e.clientX,e.clientY,wj(n));Dn(null),kn(null),Mn(null),Sn({agentId:t,x:r.x,y:r.y})},[Y]),Q=(0,G.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=xj(n.left+24,n.top+n.height,wj(r));Dn(null),kn(null),Mn(null),Sn({agentId:t,x:i.x,y:i.y})},[Y]),Ds=(0,G.useCallback)((e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget.getBoundingClientRect(),r=oi.find(e=>e.id===t),i=r?.hasMain?4:Ik(r)?8:7,a=bj(i,r?.hasMain?1:2)+i*8,o=oe()?Cj(n,a,void 0,rF):Sj(n,a);Sn(null),kn(null),Mn(null),Dn({projectId:t,x:o.x,y:o.y})},[oi]),Os=(0,G.useCallback)((e,t)=>{if(e.key!==`ContextMenu`&&!(e.shiftKey&&e.key===`F10`))return;e.preventDefault(),e.stopPropagation();let n=e.currentTarget.getBoundingClientRect(),r=oi.find(e=>e.id===t),i=r?.hasMain?4:Ik(r)?8:7,a=bj(i,r?.hasMain?1:2)+i*8,o=oe()?Cj(n,a,void 0,rF):Sj(n,a);Sn(null),kn(null),Mn(null),Dn({projectId:t,x:o.x,y:o.y})},[oi]),ks=(0,G.useCallback)((e,t,n)=>{e.preventDefault(),e.stopPropagation();let r=xj(e.clientX,e.clientY,bj(3));Sn(null),Dn(null),Mn(null),kn({provider:t,sessionId:n,x:r.x,y:r.y})},[]),As=(0,G.useCallback)((e,t,n)=>{if(e.key!==`ContextMenu`&&!(e.shiftKey&&e.key===`F10`))return;e.preventDefault(),e.stopPropagation();let r=e.currentTarget.getBoundingClientRect(),i=xj(r.left+24,r.top+r.height,bj(3));Sn(null),Dn(null),Mn(null),kn({provider:t,sessionId:n,x:i.x,y:i.y})},[]),js=(0,G.useCallback)(()=>{if(!ta)return;let e=ee(ta);Sn(null),Mn(null),Vn({kind:`agent`,agentId:ta.id,title:e})},[ta]),Ms=(0,G.useCallback)(()=>{na&&(Dn(null),Mn(null),Vn({kind:`project`,projectId:na.id,workspace:na.workspace,title:na.name}))},[na]),Ns=(0,G.useCallback)(()=>{let e=Bn;Vn(null),e&&(e.kind===`agent`&&Zo(e.agentId),e.kind===`project`&&$o(e.projectId))},[Zo,$o,Bn]),Ps=(0,G.useCallback)(()=>{if(!Bn)return;let e=Bn.title.trim();if(Bn.kind===`agent`){if(!e)return;N(Bn.agentId,e),Vn(null),Zo(Bn.agentId);return}if(!e)return;let t={...nt,[Bn.workspace]:e};rt(t),fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({projectNames:t})}).then(e=>e.json()).then(e=>{rt(HP((e.settings??{}).projectNames))}).catch(()=>{Jn({id:Date.now(),kind:`error`,message:J.copyFailed})}),Vn(null),$o(Bn.projectId)},[J.copyFailed,Zo,$o,N,nt,Bn]),Fs=(0,G.useCallback)(async(e,t)=>{Sn(null),Dn(null),kn(null),Mn(null);let n=await CF(e);Jn({id:Date.now(),kind:n?`success`:`error`,message:n?J.copiedWorkingDirectory:J.copyFailed}),t?.kind===`agent`&&Zo(t.id),t?.kind===`agent-session`&&Qo(t.provider,aD(t))},[J.copiedWorkingDirectory,J.copyFailed,Zo,Qo]),Is=(0,G.useCallback)(()=>{ta&&(Sn(null),Mn(null),Un({agentId:ta.id,title:ee(ta)}))},[ta]),Ls=(0,G.useCallback)(()=>{let e=Hn?.agentId;Un(null),e&&Zo(e)},[Zo,Hn?.agentId]),Rs=(0,G.useCallback)(()=>{Hn&&(B(Hn.agentId),Un(null))},[Hn,B]),zs=(0,G.useCallback)(e=>{ta&&(Sn(null),Mn(null),L(ta.id,e))},[ta,L]),Bs=(0,G.useCallback)(e=>{if(!ta)return;let t=ta.id;if(Sn(null),Mn(null),e.archived===!0){let e=ta.providerSessionKey||nk(ta.source);e&&To(e),jr.current=t,window.setTimeout(()=>Oo(),120),window.setTimeout(()=>Oo(),360),window.setTimeout(()=>Oo(),720)}let n=F(t,e);e.archived===!0&&Do(n),e.archived!==!0&&Zo(t)},[ta,Oo,Zo,F,To,Do]),Vs=(0,G.useCallback)((e,t)=>{let n=e.id;if(Sn(null),Mn(null),t.archived===!0){let t=e.providerSessionKey||nk(e.source);t&&To(t),jr.current=n,window.setTimeout(()=>Oo(),120),window.setTimeout(()=>Oo(),360),window.setTimeout(()=>Oo(),720)}let r=F(n,t);t.archived===!0&&Do(r),t.archived!==!0&&Zo(n)},[Oo,Zo,F,To,Do]),Hs=(0,G.useCallback)(async(e,t,n)=>{try{let i=await fetch(r(`/api/agents/${encodeURIComponent(e)}/reorder`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({beforeAgentId:t,afterAgentId:n})});if(!i.ok){let e=await i.json().catch(()=>null);throw Error(e?.error||J.reorderAgentFailed)}}catch(e){Jn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.reorderAgentFailed})}},[J.reorderAgentFailed]),Us=(0,G.useCallback)(e=>{jr.current=null,Mr.current=e,F(e,{archived:!1}),Mo(),z(`projects`),[120,360,720,1200,1800].forEach(t=>{window.setTimeout(()=>{Ao()||Xo(e)},t)})},[Mo,Xo,F,z,Ao]),Ws=(0,G.useCallback)(e=>{te(e)},[te]),Gs=(0,G.useCallback)(async(e,t,n=``,i=``)=>{let a=aD({provider:e,id:t,providerHomeId:n}),o=()=>{Lt(r=>r.map(r=>r.provider===e&&r.id===t&&(r.providerHomeId||`default`)===(n||`default`)?{...r,archived:!1}:r))},s=Y.find(r=>(r.providerSessionKey===a||r.source===ek(e,t,n))&&r.archived!==!0&&r.status!==`dead`&&r.status!==`stopped`);if(s){o(),wo(e,t,n),C(s.id),vo();return}try{let a=await fetch(r(`/api/agent-sessions/${encodeURIComponent(e)}/${encodeURIComponent(t)}/resume`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({unarchiveArchived:!0,providerHomeId:n,...[`codex`,`claude`,`opencode`,`qoder`].includes(e)?{agentRuntimeMode:`acp`,acpHistoryMode:`load`}:{},...i?{customTitle:i}:{}})}),s=await a.json().catch(()=>null);if(!a.ok||!s?.agentId){Jn({id:Date.now(),kind:`error`,message:s?.error||`Failed to resume agent session (${a.status})`});return}o(),wo(e,t,n),E(s.agentId),vo()}catch(e){Jn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:`Failed to resume agent session`})}},[Y,wo,vo,C,E]);Sr.current=Gs;let Ks=(0,G.useCallback)(e=>{let t=pF(e.source);if(t){Gs(t.provider,t.sessionId,t.providerHomeId,e.customTitle||``),z(`projects`);return}O(Wj(e),e.command||void 0,null,e.customTitle||void 0)},[O,z,Gs]),qs=(0,G.useCallback)(e=>{if(e.preventDefault(),e.stopPropagation(),Sn(null),Dn(null),kn(null),!oe()){Mn(null),Pn(!0);return}let t=e.currentTarget.getBoundingClientRect();Mn({x:Math.max(8,t.right-164),y:Math.min(window.innerHeight-12,t.bottom+6),returnFocusTarget:e.currentTarget})},[]),Js=(0,G.useCallback)(async()=>{Mn(null);try{let e=T(fa),t=await fetch(r(`/api/share/qr-ticket`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e?{target:e}:{})}),n=await t.json().catch(()=>null);if(!t.ok||!n?.longUrl&&!n?.shortUrl)throw Error(n?.error||J.shareLinkFailed);zn(n.longUrl||n.shortUrl||``)}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;Jn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.shareLinkFailed})}},[J.shareLinkFailed,fa]),Ys=(0,G.useCallback)(e=>{Mn(null),ue({language:e})},[ue]),Xs=(0,G.useCallback)(e=>{Mn(null),ue({appearance:e})},[ue]),Zs=(0,G.useCallback)(()=>{Mn(null),Pn(!0)},[]),Qs=(0,G.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),Mn(null),Pn(!0)},[]),$s=(0,G.useMemo)(()=>oe()?aj([{type:`separator`,id:`options-mobile-share-separator`},{type:`item`,id:`options-mobile-share`,label:J.sharePage,ariaLabel:J.sharePage,onSelect:Js}]):aj([{type:`item`,id:`options-appearance-light`,label:UP(J.appearanceLight),ariaLabel:J.appearanceLight,checked:b.appearance===`light`,onSelect:()=>Xs(`light`)},{type:`item`,id:`options-appearance-dark`,label:UP(J.appearanceDark),ariaLabel:J.appearanceDark,checked:b.appearance===`dark`,onSelect:()=>Xs(`dark`)},{type:`separator`,id:`options-appearance-language-separator`},{type:`item`,id:`options-language-en`,label:VP(J.languageEnglish),ariaLabel:J.languageEnglish,checked:b.language===`en`,onSelect:()=>Ys(`en`)},{type:`item`,id:`options-language-zh`,label:VP(J.languageChinese),ariaLabel:J.languageChinese,checked:b.language===`zh`,onSelect:()=>Ys(`zh`)},{type:`separator`,id:`options-settings-separator`},{type:`item`,id:`options-open-settings`,label:J.openSettings,ariaLabel:J.openSettings,onSelect:Zs}]),[J.appearanceDark,J.appearanceLight,J.languageChinese,J.languageEnglish,J.openSettings,J.sharePage,Zs,Js,b.appearance,b.language,Xs,Ys]),ec=(0,G.useCallback)((e,t)=>{fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentLaunchProfiles:{[e]:t}})}).catch(()=>{})},[]),tc=(0,G.useCallback)(e=>{if(l)return;if(Ri===`claude`){let t=sP(e)?e:`default`;Tt(t),ec(`claude`,{permissionMode:t}),X&&(Jn({id:Date.now(),kind:`success`,message:J.permissionProfileRestarting}),F(X.id,{launchPermissionMode:t})),ea(),Pa();return}let t=oP(e)?e:`approve`;lt(t),ec(`codex`,{approvalMode:t}),X&&Ri===`codex`&&(Jn({id:Date.now(),kind:`success`,message:xi?J.permissionProfileApplying:J.permissionProfileRestarting}),F(X.id,{launchPermissionMode:t})),ea(),Pa()},[X,xi,ea,Ri,J.permissionProfileApplying,J.permissionProfileRestarting,Pa,F,l,ec]),nc=(0,G.useCallback)((e,t)=>{l||(Jn({id:Date.now(),kind:`success`,message:J.runtimeModeRestarting}),F(e,{agentRuntimeMode:t}))},[J.runtimeModeRestarting,F,l]),rc=(0,G.useCallback)((e,t,n)=>{ft(e),mt(t),gt(n),ut(`${e}:${t}`),ec(`codex`,{model:e,reasoningEffort:t,serviceTier:n})},[ec]),ic=(0,G.useCallback)(e=>{if(Ri===`claude`){let t=dP(e);Dt(t),ea(),Pa(),ec(`claude`,{model:t,effort:kt});return}let t=_t.find(t=>t.value===e),n=t?.reasoningLevels??[],r=t?.serviceTiers??[],i=n.some(e=>e.value===Wi)?Wi:t?.defaultEffort||n[0]?.value||Wi,a=r.some(e=>e.value===Gi)?Gi:`default`;if(ea(),Pa(),X&&dF(X)){io(X,e,i,a).then(t=>{t&&rc(e,i,a)});return}rc(e,i,a)},[X,io,kt,ea,_t,Wi,Gi,rc,Ri,Pa,ec]),ac=(0,G.useCallback)((e,t)=>{if(Ri!==`codex`)return;let n=_t.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===Gi)?Gi:`default`;if(X&&dF(X)){io(X,e,r,i).then(t=>{t&&rc(e,r,i)});return}rc(e,r,i)},[X,io,_t,Gi,rc,Ri]),oc=(0,G.useCallback)(e=>{if(Ri===`claude`){let t=pP(e);At(t),ea(),Pa(),ec(`claude`,{model:Et,effort:t});return}if(ea(),Pa(),X&&dF(X)){io(X,Ui,e,Gi).then(t=>{t&&rc(Ui,e,Gi)});return}rc(Ui,e,Gi)},[X,io,Et,ea,Ui,Gi,rc,Ri,Pa,ec]),sc=(0,G.useCallback)(e=>{if(Ri!==`claude`){if(ea(),Pa(),X&&dF(X)){io(X,Ui,Wi,e).then(t=>{t&&rc(Ui,Wi,e)});return}rc(Ui,Wi,e)}},[X,io,ea,Ui,Wi,rc,Ri,Pa]),cc=(0,G.useCallback)(e=>{if(Ri===`codex`){if(X&&dF(X)){io(X,Ui,Wi,e).then(t=>{t&&rc(Ui,Wi,e)});return}rc(Ui,Wi,e)}},[X,io,Ui,Wi,rc,Ri]),lc=(0,G.useCallback)(()=>{if(an){yr.current?.stop(),yr.current=null,on(!1);return}let e=Ti;if(!e)return;let t=oe(),n=lF(),r=nn&&!n?window.SpeechRecognition||window.webkitSpeechRecognition:null;if(!r){(lF()||t)&&Pa(),on(!1);return}let i=new r,a=null,o=()=>{a!==null&&(window.clearTimeout(a),a=null)},s=()=>{if(yr.current===i)try{i.stop()}catch{on(!1),yr.current=null}};i.continuous=!1,i.interimResults=!1,i.lang=b.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()&&(me(e,e=>{let t=e.draft&&!/\s$/.test(e.draft)?` `:``;return{...e,draft:`${e.draft}${t}${n.trim()}`}}),Pa())},i.onerror=()=>{o(),on(!1)},i.onspeechend=s,i.onaudioend=s,i.onend=()=>{o(),on(!1),yr.current=null},yr.current=i,on(!0);try{i.start(),a=window.setTimeout(s,6e4)}catch{o(),yr.current=null,on(!1),t&&Pa()}},[Ti,Pa,an,nn,b.language,me]),uc=(0,G.useCallback)(()=>{if(!na?.workspace)return;let e=na.id,t=na.workspace,n=Qe.current,r=na.pinned?n.filter(e=>e!==t):[...n.filter(e=>e!==t),t];Dn(null),Mn(null),zo(r,n),window.requestAnimationFrame(()=>$o(e))},[na,$o,zo]),dc=(0,G.useCallback)(async()=>{if(!na?.workspace)return;let e=na.id,t=Fn(na.workspace);Dn(null),Mn(null);try{let e=await fetch(r(`/api/projects/reveal`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({rootId:t})}),n=await e.json().catch(()=>null);if(!e.ok)throw Error(n?.error||J.revealInFinderFailed)}catch(e){Jn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.revealInFinderFailed})}$o(e)},[na,J.revealInFinderFailed,$o]),fc=(0,G.useCallback)(async()=>{if(!na?.workspace)return;let e=na.id,t=Fn(na.workspace);Dn(null),Mn(null);try{await Ye.current.catch(()=>{});let e=await fetch(r(`/api/projects/create-worktree`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({rootId:t})}),n=await e.json().catch(()=>null);if(!e.ok)throw Error(n?.error||J.permanentWorktreeFailed);let i=Ln(n?.projectWorkspaces);Je.current+=1,qe.current=i,We(i),Jn({id:Date.now(),kind:`success`,message:J.permanentWorktreeCreated})}catch(e){Jn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.permanentWorktreeFailed})}$o(e)},[na,J.permanentWorktreeCreated,J.permanentWorktreeFailed,$o]),pc=(0,G.useCallback)(()=>{if(!na)return;let e=na.id;na.agents.forEach(e=>{e.unread&&$a(e.id,!0)}),Dn(null),Mn(null),$o(e)},[na,$o,$a]),mc=(0,G.useCallback)(()=>{if(!na)return;let e=na.workspace,t=na.agents.filter(e=>!e.isMain),n=Yr.filter(t=>sD(t)===e);if(t.length===0&&n.length===0){Dn(null),Mn(null),Ar.current=`list`;return}t.forEach(e=>{F(e.id,{archived:!0})}),Eo(n.map(aD)),Dn(null),Mn(null),Ar.current=`list`},[Yr,na,F,Eo]),hc=(0,G.useCallback)(()=>{if(!na||na.hasMain||na.agents.length>0||na.agentSessions.length>0||na.hasOpenFile)return;let e=qe.current;Ro(e.filter(e=>e!==na.workspace),e);let t=Qe.current;t.includes(na.workspace)&&zo(t.filter(e=>e!==na.workspace),t),Dn(null),Mn(null),Ar.current=`list`},[na,zo,Ro]),gc=(0,G.useCallback)(()=>{na&&(Dn(null),Mn(null),Kn({projectId:na.id,workspace:na.workspace,sessionHandles:na.agentSessions.map(aD)}))},[na]),_c=(0,G.useCallback)(()=>{let e=Gn?.projectId;Kn(null),e&&$o(e)},[Gn?.projectId,$o]),vc=(0,G.useCallback)(async()=>{if(!Gn)return;let e=Gn,t=await R(e.workspace,{force:!0});if(t.deleted){Eo([...e.sessionHandles,...t.removedMainPageSessionKeys??[]]);let n=qe.current;Ro(n.filter(t=>t!==e.workspace),n);let r=Qe.current;r.includes(e.workspace)&&zo(r.filter(t=>t!==e.workspace),r),Ar.current=`list`,Kn(null)}},[Gn,R,zo,Ro,Eo]),yc=(0,G.useCallback)(()=>{let e=xn?.agentId,t=wn?.projectId,n=On?.provider,r=On?.sessionId,i=jn?.returnFocusTarget??null;Sn(null),Dn(null),kn(null),Mn(null),e?Zo(e):t?$o(t):n&&r?Qo(n,r):i&&window.requestAnimationFrame(()=>i.focus({preventScroll:!0}))},[xn?.agentId,On?.provider,On?.sessionId,Zo,Qo,$o,jn?.returnFocusTarget,wn?.projectId]),bc=(0,G.useCallback)((e,t)=>{if(!t)return!1;if(e.key===`Escape`)return e.preventDefault(),e.stopPropagation(),yc(),!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(vr.current,n.length-1),a=r===-1?i:r,o=e=>{vr.current=e,n[e]?.focus()};if(e.key===`Tab`){_r.current=!0,e.preventDefault(),e.stopPropagation();let t=a+(e.shiftKey?-1:1);if(t<0||t>=n.length){yc();return}return o(t),!0}if(e.key===`ArrowDown`||e.key===`ArrowUp`){_r.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`?(_r.current=!0,e.preventDefault(),e.stopPropagation(),o(0),!0):e.key===`End`?(_r.current=!0,e.preventDefault(),e.stopPropagation(),o(n.length-1),!0):!1},[yc]),xc=(0,G.useCallback)(e=>{e.defaultPrevented||bc(e.nativeEvent,e.currentTarget)},[bc]);(0,G.useLayoutEffect)(()=>{if(!xn&&!wn&&!On&&!jn)return;let e=e=>{bc(e,document.querySelector(`.code-context-menu`))&&e.stopImmediatePropagation()};return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[xn,On,bc,jn,wn]);let Sc=(0,G.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(),ea(),Pa();return}if(e.key===`Tab`){e.preventDefault(),e.stopPropagation();let t=Mi?`[data-testid="code-composer-model-picker"]`:Ni?hF()?`[data-testid="code-composer-send"]`:`[data-testid="code-composer-mic"]`:`[data-testid="code-composer-approval"]`;ea(),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())},[Mi,ea,Pa,Ni]),Cc=(0,G.useCallback)(e=>{let t=e.relatedTarget;t&&(t instanceof Node&&e.currentTarget.contains(t)||t instanceof Element&&t.closest(`.code-composer`)||ea())},[ea]);(0,G.useEffect)(()=>{function e(e){if(a)return;let t=e.target;if(xn||wn||On||jn){if(bc(e,gr.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`&&Bn){e.preventDefault(),Ns();return}if(e.key===`Escape`&&Hn){e.preventDefault(),Ls();return}if(e.key===`Escape`&&Gn){e.preventDefault(),_c();return}if(Bn||Hn||Gn){Ht(t)||(e.preventDefault(),e.stopPropagation());return}let n=y?Wn(e):null;if(n){vF(e),_s(n);return}if(GP(e)&&!Ht(t)){e.preventDefault(),e.stopPropagation(),xs();return}if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`p`&&!e.altKey&&!e.shiftKey&&!Bn&&!Hn&&!Gn&&!Ht(t)&&!fF(t)&&!Rt(t)){let n=la(t)??ca;if(!n)return;e.preventDefault(),ss(n);return}if(!(zt(t)||Rt(t))&&!(Ht(t)&&e.key!==`Escape`)){if(e.key===`Escape`&&(ji||Mi||Ni)){e.preventDefault(),ea(),Pa();return}if(e.key===`Escape`&&i!==`projects`){e.preventDefault(),Sn(null),Dn(null),kn(null),Mn(null),Mo(),z(`projects`),Ar.current=`active-force`;return}if(e.key===`Escape`&&(xn||wn||On||jn)){e.preventDefault();let t=xn?.agentId,n=wn?.projectId,r=On?.provider,i=On?.sessionId,a=jn?.returnFocusTarget??null;Sn(null),Dn(null),kn(null),Mn(null),t?Zo(t):n?$o(n):r&&i?Qo(r,i):a&&window.requestAnimationFrame(()=>a.focus({preventScroll:!0}));return}if(y){if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`b`){e.preventDefault(),Vr();return}e.key===`/`&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.shiftKey&&(e.preventDefault(),_o())}}}return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[i,xn,Mi,ea,_c,Ls,Ns,On,Gn,a,Zo,Qo,Pa,$o,ss,bc,Hn,y,Ni,_s,jn,ji,ca,la,wn,Bn,xs,Mo,z,_o,Vr]),(0,G.useEffect)(()=>{if(!Bn)return;let e=Bn.title,t=!1;return JN(()=>{let n=lr.current;if(!n)return;let r=document.activeElement;if(r!==n&&!ur.current?.contains(r)&&n.focus(),!t&&document.activeElement===n&&n.value===e){if(t=!0,Bn.kind===`project`){let e=n.value.length;n.setSelectionRange(e,e);return}n.select()}},{delays:[0,80,180,360]})},[$n]),(0,G.useEffect)(()=>Hn?JN(()=>{dr.current?.contains(document.activeElement)||fr.current?.focus()},{runNow:!1,delays:[180]}):void 0,[Hn]),(0,G.useEffect)(()=>Gn?JN(()=>{pr.current?.contains(document.activeElement)||mr.current?.focus()},{runNow:!1,delays:[180]}):void 0,[Gn]),(0,G.useEffect)(()=>{if(!qn)return;let e=window.setTimeout(()=>Jn(null),1700);return()=>window.clearTimeout(e)},[qn]),(0,G.useEffect)(()=>{function e(e){let t=e.target;t instanceof Element&&t.closest(`.code-context-menu`)||(Sn(null),Dn(null),kn(null),Mn(null))}if(!(!xn&&!wn&&!On&&!jn))return window.addEventListener(`pointerdown`,e),()=>window.removeEventListener(`pointerdown`,e)},[xn,On,jn,wn]),(0,G.useEffect)(()=>{function e(e){let t=e.target;t instanceof Element&&t.closest(`.code-composer-menu-anchor`)||ea()}if(!(!ji&&!Mi&&!Ni))return window.addEventListener(`pointerdown`,e),()=>window.removeEventListener(`pointerdown`,e)},[Mi,ea,Ni,ji]),(0,G.useLayoutEffect)(()=>!xn&&!wn&&!On&&!jn?void 0:(_r.current=!1,vr.current=0,JN(()=>{if(_r.current)return;let e=gr.current;if(!e)return;let t=document.activeElement;if(t instanceof HTMLButtonElement&&e.contains(t))return;let n=e.querySelector(`button:not(:disabled)`);n&&(vr.current=0,n.focus())},{delays:[0,80,180,360]})),[xn,On,jn,wn]),(0,G.useEffect)(()=>{if(!Ni)return;let e=window.setTimeout(()=>{let e=Pi===`model`?`.code-model-submenu .code-model-option.selected`:Pi===`speed`?`.code-speed-submenu .code-model-option.selected`:`.code-model-picker-menu > .code-model-option.selected`,t=sr.current?.querySelector(e),n=sr.current?.querySelector(`button:not(:disabled)`);(t??n)?.focus()},0);return()=>window.clearTimeout(e)},[Ni,Pi,ma,ha,ga]),(0,G.useEffect)(()=>{if(!ji)return;let e=window.setTimeout(()=>{ar.current?.querySelector(`button:not(:disabled)`)?.focus()},0);return()=>window.clearTimeout(e)},[ji]),(0,G.useEffect)(()=>{if(!Mi)return;let e=window.setTimeout(()=>{let e=or.current?.querySelector(`.code-approval-option.selected`),t=or.current?.querySelector(`button:not(:disabled)`);(e??t)?.focus()},0);return()=>window.clearTimeout(e)},[Mi,ba]),(0,G.useEffect)(()=>{if(!fe)return;let e=window.setInterval(()=>q(Date.now()),6e4);return()=>window.clearInterval(e)},[fe]),(0,G.useEffect)(()=>{let e=window.matchMedia(`(max-width: 980px)`),t=()=>{rn(!!(window.SpeechRecognition||window.webkitSpeechRecognition)&&!lF())};return t(),e.addEventListener(`change`,t),()=>{e.removeEventListener(`change`,t),yr.current?.stop(),yr.current=null}},[]),(0,G.useEffect)(()=>Ia(),[Ia]),(0,G.useEffect)(()=>{let e=()=>{Ia(),Ha()};return window.addEventListener(`farming-agent-homes-saved`,e),()=>window.removeEventListener(`farming-agent-homes-saved`,e)},[Ha,Ia]),(0,G.useEffect)(()=>Ra(),[Ra]),(0,G.useEffect)(()=>Ga(Ri||``,X?.cwd),[X?.cwd,Ri,Ga]),(0,G.useEffect)(()=>{if(Ni)return La()},[La,Ni]),(0,G.useEffect)(()=>{if(!(!Ni||Ri!==`claude`))return Ra()},[Ri,Ra,Ni]),(0,G.useEffect)(()=>Ha(),[Ha]),(0,G.useEffect)(()=>{Na()},[Na,Ti,Ai,Oi]),(0,G.useEffect)(()=>{Ei.composer.permissionMode||Ei.composer.modelPicker||$i(e=>{let t=yA(e);return Ei.composer.plusMenu||t.mode===`default`?t:{...t,mode:`default`}})},[Ei,$i]),(0,G.useEffect)(()=>{i!==`search`&&Ne&&Mo(),i!==`projects`&&(Sn(null),Dn(null),kn(null),Mn(null),ea())},[i,Mo,ea,Ne]),(0,G.useEffect)(()=>{a&&(Sn(null),Dn(null),kn(null),Mn(null),ea())},[ea,a]),(0,G.useEffect)(()=>{if(i===`projects`)return Ia()},[i,Ia]),(0,G.useEffect)(()=>{if(i!==`history`)return;let e=!1,t=Nr.current;return fetch(r(`/api/settings`)).then(e=>e.json()).then(n=>{if(e)return;let r=n.settings??{};He($t(r.lastMainWorkspace,r.workspaceHistory??[])),We(Ln(r.projectWorkspaces)),Ze(Ln(r.pinnedProjectWorkspaces)),Ke(!0),rt(HP(r.projectNames)),t===Nr.current&&st(new Set(QO(r.mainPageSessionKeys??[]))),Fa(r),Ha(!0)}).catch(()=>{e||He([])}),()=>{e=!0}},[i,Fa,Ha]),(0,G.useEffect)(()=>{function e(e){Fr.current&&(e.preventDefault(),Yo(e.clientX))}function t(){Fr.current&&(Fr.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`)}},[Yo]),(0,G.useEffect)(()=>{let e=tr.current;if(!e||typeof ResizeObserver>`u`)return;let t=e=>{if(hF()){Lr.current||zr(),Lr.current=!0;return}if(Lr.current=!1,gF(e)){zr();return}Ir.current&&Br()};t(e.getBoundingClientRect().width);let n=new ResizeObserver(n=>{t(n[0]?.contentRect.width??e.getBoundingClientRect().width)});return n.observe(e),()=>n.disconnect()},[zr,Br]),(0,G.useEffect)(()=>{let e=Ar.current;if(!e||i!==`projects`||Ne)return;Ar.current=null;let t,n=0,r=e===`active-force`?4:12,a=()=>{n>=r||(t=window.setTimeout(o,90))},o=()=>{if(n+=1,Ao()){a();return}let t=!1;e===`list`?(hr.current?.focus({preventScroll:!0}),t=document.activeElement===hr.current):t=Oo(),(!t||e===`active-force`)&&a()},s=window.setTimeout(()=>{o()},e===`list`?0:50);return()=>{window.clearTimeout(s),t!==void 0&&window.clearTimeout(t)}},[c,i,Oo,Ne,Ao]),(0,G.useEffect)(()=>{if(!jr.current||i!==`projects`||Ne)return;jr.current=null;let e,t=0,n=()=>{t>=12||(e=window.setTimeout(r,90))},r=()=>{if(t+=1,Ao()){n();return}jo({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,c,i,jo,Ne,Ao]),(0,G.useEffect)(()=>{let e=Mr.current;if(!e||i!==`projects`||Ne||!Y.some(t=>t.id===e))return;Mr.current=null;let t,n=0,r=()=>{n+=1,Ao()||Xo(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,Xo,Ne,Ao]),(0,G.useEffect)(()=>{sa&&bn(sa)},[sa]),(0,G.useEffect)(()=>{Ve(0)},[li,Ne]),(0,G.useEffect)(()=>{Ve(e=>hi.length===0?0:Math.min(e,hi.length-1))},[hi.length]);let wc={"--code-sidebar-width":`${pn?ZP:dn}px`};return(0,K.jsxs)(`div`,{className:`code-workspace ${pn?`sidebar-collapsed`:``}`,"data-testid":`code-workspace`,ref:tr,style:wc,children:[(0,K.jsx)(iM,{sidebarCollapsed:pn,activeView:i,searchOpen:Ne,displayedProjects:si,collapsedProjectIds:sn,normalizedSearch:``,hasProjectListItems:fi,hasDisplayedProjectListItems:fi,activeTerminalId:c,selectedSearchAgentId:aa,selectedSearchSessionHandle:oa,claimedAgentSessionKeyByAgentId:Jr.claimedAgentSessionKeyByAgentId,agentShortcutKeys:gi,keyboardShortcutsEnabled:y,now:er,mainAgent:Ur,usageSummary:o,shareTarget:fa,agentLaunchOptions:it,agentCreationWorkspace:ua,openWorkspaceFile:W,openWorkspaceFiles:je,fileRevealRequest:Yn,fileSearchFocusRequest:Zn,projectListRef:hr,canLoadMoreAgentSessions:Ut,onLoadMoreAgentSessions:Wa,onNewAgent:bo,onStartAgent:xo,onToggleSidebar:Vr,onOpenSearch:Fo,onOpenWorkspaceView:Io,onOpenMainAgent:()=>{Ur&&(ye(`terminal`),z(`projects`),C(Ur.id))},onRestartMainAgent:ne,onProjectListKeyDown:Go,onToggleProject:Lo,onToggleProjectSessions:Vo,onMountProject:Bo,onOpenProjectContextMenu:Ds,onOpenProjectKeyboardMenu:Os,onOpenAgent:is,onUpdateAgentFlags:Vs,onReorderAgent:Hs,onOpenAgentContextMenu:Es,onOpenAgentKeyboardMenu:Q,onResumeAgentSession:Gs,onOpenAgentSessionContextMenu:ks,onOpenAgentSessionKeyboardMenu:As,onOpenProjectFile:os,onSelectOpenWorkspaceFile:ds,onCloseOpenWorkspaceFile:bs,onMoveWorkspaceEntries:ws,onDeleteWorkspaceEntries:Ts,onRefreshProjectOpenFiles:Me,onOpenOptionsMenu:Qs,copy:J}),(0,K.jsx)(VN,{open:Nn,activeAgentId:i===`projects`?X?.id??null:null,language:b.language,uiPreferences:b,agentLaunchOptions:it,onClose:()=>Pn(!1),onUpdateUiPreferences:ue}),Rn&&(0,K.jsx)(ij,{copy:J,title:Oa,url:Rn,onClose:()=>zn(``)}),(0,K.jsx)(`div`,{className:`code-sidebar-resizer`,"data-testid":`code-sidebar-resizer`,role:`separator`,"aria-label":J.resizeNavigation,"aria-orientation":`vertical`,"aria-valuemin":qP,"aria-valuemax":JP,"aria-valuenow":pn?ZP:dn,onPointerDown:ns}),!pn&&(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-sidebar-backdrop`,"data-testid":`code-mobile-sidebar-backdrop`,"aria-label":J.closeNavigation,onPointerDown:zr}),(0,K.jsxs)(`div`,{className:`code-mobile-topbar`,"data-testid":`code-mobile-topbar`,children:[Ma?(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-topbar-button back`,"data-testid":`code-mobile-back`,"aria-label":J.backToAgent,onClick:()=>{ja&&vs(ja)},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:yo,children:(0,K.jsx)(`span`,{"aria-hidden":`true`})}),(0,K.jsxs)(`div`,{className:`code-mobile-topbar-title`,children:[(0,K.jsx)(`strong`,{children:Oa}),Aa&&(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`i`,{"aria-hidden":`true`}),Aa]})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-topbar-button more`,"data-testid":`code-mobile-more`,"aria-label":J.openOptions,onClick:qs,children:(0,K.jsx)(`span`,{"aria-hidden":`true`})})]}),jn&&(0,K.jsx)(`div`,{className:`code-context-menu code-options-menu`,"data-testid":`code-options-menu`,style:{left:jn.x,top:jn.y},role:`menu`,ref:gr,onKeyDownCapture:xc,onKeyDown:xc,children:(0,K.jsx)(TF,{entries:$s})}),(0,K.jsx)(lA,{activeView:i,showFileEditor:da,openWorkspaceFile:W,openWorkspaceFiles:je,openAgentsCount:_i.length,visibleOpenAgents:yi,activeTerminalId:c,permissionSwitchingAgentId:l,agentSwitchingKind:u,terminalFocusRequest:_,agentCreationWorkspace:ua,displayedProjects:pi,searchQuery:Fe,searchHasQuery:ui,searchLoading:qt,visibleSearchTargetCount:hi.length,selectedSearchAgentId:aa,selectedSearchSessionHandle:oa,searchInputRef:cr,archivedRuns:ti,archivedAgents:ei,historyAgentSessions:ni,canLoadMoreHistoryAgentSessions:Ut,now:er,acpComposerProps:{active:!!X&&!Si,agentId:X?.id||``,runtimeState:bi?.state||``,sessionUpdatedAt:bi?.sessionUpdatedAt||``,runtimeError:bi?.error||``,draft:Oi,attachments:ki,composerMode:Ai,contextWindow:wi,pendingFollowUp:Ji??null,submitAction:Qi,textareaRef:nr,attachmentInputRef:ir,permissions:bi?.pendingPermissions.length?bi.pendingPermissions:bi?.pendingPermission?[bi.pendingPermission]:[],elicitations:bi?.pendingElicitations.length?bi.pendingElicitations:bi?.pendingElicitation?[bi.pendingElicitation]:[],activeElicitations:bi?.activeElicitations||[],speechSupported:nn,speechListening:an,onDraftChange:no,onNavigateHistory:ro,onRemoveAttachment:Ya,onSubmit:co,onInterrupt:lo,onDiscardPendingFollowUp:go,onToggleSpeechInput:lc,onPasteAttachment:Za,onAttachmentFiles:Xa,onChooseAttachmentFile:Ka,onActivateComposerMode:Qa,onClearComposerMode:()=>{$i(e=>({...e,mode:`default`}))},onRespondToPermission:po,onRespondToElicitation:mo},composerProps:{active:!!X&&!Si,agentKind:Ri,capabilities:Ei.composer,slashCommands:Z,draft:Oi,attachments:ki,composerMode:Ai,plusMenuOpen:ji,approvalMenuOpen:Mi,modelMenuOpen:Ni,modelPickerPane:Pi,agentModelPreset:_a,agentModel:ma,agentReasoningEffort:ha,agentServiceTier:ga,agentModelOptions:pa,currentPermissionMode:ba,permissionModeDisabled:!!l,modelProfileDisabled:Ci||!!(X&&dF(X)&&X.terminalStatus?.activity===`busy`),currentPermissionLabel:xa,currentPermissionColor:Sa,permissionModeHint:xi?J.permissionAppServerHint:J.permissionRestartHint,currentModelLabel:Ca,currentReasoningLabel:wa,currentSpeedLabel:Ta,currentReasoningOptions:va,currentServiceTierOptions:ya,permissionModeOptions:Ea,contextWindow:wi,pendingFollowUp:Ji?{messages:Ji.messages,createdAt:Ji.createdAt}:null,appServerRequest:xi?.pendingRequest||null,appServerNotice:xi?.notice||null,submitAction:Zi,speechSupported:nn,speechListening:an,textareaRef:nr,attachmentInputRef:ir,plusMenuRef:ar,approvalMenuRef:or,modelMenuRef:sr,onDraftChange:no,onNavigateHistory:ro,onRemoveAttachment:Ya,onSubmit:so,onInterrupt:lo,onSteerPendingFollowUp:ho,onDiscardPendingFollowUp:go,onRespondToAppServerRequest:uo,onRejectAppServerRequest:fo,onPasteAttachment:Za,onAttachmentFiles:Xa,onChooseAttachmentFile:Ka,onActivateComposerMode:Qa,onClearComposerMode:()=>{$i(e=>({...e,mode:`default`})),Pa()},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:ea,onSetModelPickerPane:e=>{$i(t=>({...t,ui:{...t.ui,modelPickerPane:e}}))},onComposerMenuKeyDown:Sc,onComposerMenuBlur:Cc,onUpdatePermissionMode:tc,onUpdateModel:ic,onUpdateReasoningEffort:oc,onUpdateServiceTier:sc,onUpdateModelProfile:ac,onUpdateServiceTierInline:cc,onToggleSpeechInput:lc},onNewAgent:O,onOpenTerminal:C,onOpenTerminalPath:us,onResolveTerminalPath:ls,onTerminalFollowOutputChange:to,onAgentReadLatest:eo,onRuntimeModeChange:nc,onSessionOutput:ce,onOpenSearchAgent:rs,onOpenSearchSession:e=>{Gs(e.provider,e.id,e.providerHomeId),Mo(),z(`projects`)},onSearchQueryChange:Ie,onSearchKeyDown:Jo,onCloseSearch:No,onLoadMoreHistoryAgentSessions:Wa,onSearchHistoryAgentSessions:Ba,onResumeHistorySession:Gs,onContinueArchivedRun:Ks,onOpenArchivedAgent:Ws,onRestoreArchivedAgent:Us,onChangeWorkspaceFileDraft:Cs,onUpdateOpenWorkspaceFile:Ss,onSelectOpenWorkspaceFile:ds,onOpenWorkspaceFilePath:fs,canNavigateWorkspaceBack:we,canNavigateWorkspaceForward:Te,onNavigateWorkspaceHistory:_s,onCloseOpenWorkspaceFile:bs,onCloseOpenWorkspaceFiles:ys,onRevealWorkspaceFileInExplorer:cs,onFocusWorkspaceFilesSearch:ss,onRecordWorkspaceNavigationCursor:Oe,onBackToAgentFromFile:vs,copy:J}),(0,K.jsx)(oj,{contextMenuAgent:ta,contextMenuAgentSession:ra,contextMenuProject:na,agentMenu:xn,projectMenu:wn,agentSessionMenu:On,renameDialog:Bn,killDialog:Hn,deleteWorktreeDialog:Gn,copyNotice:qn,contextMenuRef:gr,renameDialogRef:ur,renameInputRef:lr,killDialogRef:dr,killCancelButtonRef:fr,deleteWorktreeDialogRef:pr,deleteWorktreeCancelButtonRef:mr,onContextMenuKeyDown:xc,onUpdateAgentFlags:Bs,onRenameAgent:js,onRenameProject:Ms,onCopyAgentWorkingDirectory:()=>{ta&&Fs(ZE(ta),{kind:`agent`,id:ta.id})},onForkAgent:zs,onKillAgent:Is,onOpenSession:(e,t)=>{kn(null),Mn(null),Gs(e,t,ra?.providerHomeId),ra&&Qo(e,aD(ra))},onToggleSessionPinned:es,onArchiveSession:ts,onCopySessionWorkingDirectory:()=>{ra&&Fs(cD(ra),{kind:`agent-session`,provider:ra.provider,id:ra.id,providerHomeId:ra.providerHomeId})},onToggleProjectPinned:uc,onRevealProject:dc,onCreatePermanentWorktree:fc,onMarkProjectRead:pc,onArchiveProject:mc,onRemoveProject:hc,onDeleteWorktree:gc,onCloseRenameDialog:Ns,onRenameDialogTitleChange:e=>Vn(t=>t&&{...t,title:e}),onSubmitRenameDialog:Ps,onCloseKillDialog:Ls,onSubmitKillDialog:Rs,onCloseDeleteWorktreeDialog:_c,onSubmitDeleteWorktreeDialog:vc,copy:J})]})}function TF({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)(ke,{}):null}),e.icon&&(0,K.jsx)(`span`,{className:`code-context-menu-icon`,"aria-hidden":`true`,children:(0,K.jsx)(lj,{kind:e.icon})}),(0,K.jsx)(`span`,{children:e.label})]},e.id))})}var EF={appearance:`light`,language:`en`};function DF(e){return e===`light`||e===`dark`?e:EF.appearance}function OF(e){return e===`zh`||e===`en`?e:EF.language}function kF(e){return e}function AF(e=`terminal`,t={}){if(typeof document>`u`)return;let n=document.body,r=t.crtEffects!==!1,i=DF(t.appearance),a=kF(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 jF=!1,MF=240,NF=3e4,PF=1e4,FF=6e4,IF=45e3,LF=6e4;function RF(e){if(e)return e.gitWorktree?.workspace?e.gitWorktree.workspace:e.projectWorkspace?e.projectWorkspace:e.cwd}function zF(e){return!e.archived&&e.status!==`dead`&&e.status!==`stopped`}function BF(e,t){return e.restartedFromAgentId===t||e.restartedFromAgentIds?.includes(t)===!0}function VF(e,t,n){return e.filter(e=>zF(e)&&BF(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 HF(e){return e?.providerSessionProvider===`codex`&&!!e.providerSessionId&&e.providerSessionTemporary!==!0}function UF(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 WF(e){return UF(e)?(e.focus({preventScroll:!0}),document.activeElement===e||e.contains(document.activeElement)):!1}function GF(){An(`app`);let e=Pt(),t=It(),{keyMap:n}=Lt(e.agents,e.mainAgentId),[i]=(0,G.useState)(()=>j()),[a,o]=(0,G.useState)(`none`),[s,c]=(0,G.useState)(void 0),[l,u]=(0,G.useState)(void 0),[d,f]=(0,G.useState)(void 0),[p,m]=(0,G.useState)(()=>i.openTerminalIds??[]),[h,g]=(0,G.useState)(()=>i.activeTerminalId??null),[_,v]=(0,G.useState)(null),[y,b]=(0,G.useState)(null),[x,S]=(0,G.useState)(()=>i.activeView??`projects`),[C,w]=(0,G.useState)(null),[T,E]=(0,G.useState)(null),[O,k]=(0,G.useState)(null),[A,M]=(0,G.useState)(null),[N,P]=(0,G.useState)({}),[F,ee]=(0,G.useState)(EF),I=(0,G.useRef)(null),te=(0,G.useRef)(null),L=(0,G.useRef)(null),R=(0,G.useRef)(null),ne=(0,G.useRef)([]),z=(0,G.useRef)(!1),B=(0,G.useRef)(!1),ie=(0,G.useRef)(!1),ae=(0,G.useRef)(void 0),V=(0,G.useRef)(null),se=(0,G.useRef)(0);(0,G.useLayoutEffect)(()=>{ne.current=p},[p]),(0,G.useEffect)(()=>{D({activeTerminalId:h,activeView:x,openTerminalIds:p})},[h,x,p]);let ce=(0,G.useCallback)(e=>{R.current=e,E(e)},[]),le=a,ue=(0,G.useMemo)(()=>KN(F.language),[F.language]),de=(0,G.useMemo)(()=>{if(!T)return e.agents;let t=e.agents.filter(e=>e.id===T.agent.id||!BF(e,T.originalAgentId));return t.some(e=>e.id===T.agent.id)?t:[...t,T.agent]},[T,e.agents]),fe=(0,G.useMemo)(()=>{let e=new Map,t=new Set(p);return h&&t.add(h),t.forEach(t=>{if(de.some(e=>e.id===t&&zF(e)))return;let n=VF(de,t);n&&e.set(t,n.id)}),e},[h,de,p]),pe=(0,G.useMemo)(()=>{if(h){let e=fe.get(h);if(e)return{originalAgentId:h,replacementAgentId:e}}let e=fe.entries().next().value;return e?{originalAgentId:e[0],replacementAgentId:e[1]}:null},[h,fe]),me=(0,G.useMemo)(()=>Array.from(new Set(p.map(e=>fe.get(e)??e))),[fe,p]),he=h?fe.get(h)??h:null;(0,G.useLayoutEffect)(()=>{pe&&(m(me),g(he),k(pe))},[he,me,pe]),(0,G.useEffect)(()=>{!O||pe||k(null)},[O,pe]),(0,G.useEffect)(()=>{let t=R.current;if(!t)return;let n=VF(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=>BF(n,e)?n.id:e)))),g(e=>e&&BF(n,e)?n.id:e),ce(i)},[ce,T?.agent.id,T?.originalAgentId,e.agents]),(0,G.useEffect)(()=>{let t=T;!t?.requestSettled||!t.replacementAgentId||e.agents.some(e=>e.id===t.agent.id)&&R.current?.agent.id===t.agent.id&&(L.current=null,ce(null))},[ce,T?.agent.id,T?.replacementAgentId,T?.requestSettled,e.agents]),(0,G.useEffect)(()=>{let e=T;if(!e?.requestSettled||!e.requestError||e.replacementAgentId)return;let t=e.requestErrorAt??Date.now(),n=()=>{let n=rt();if(e.requestFreshStateAt||!n.connected||n.lastMessageAt<=t)return!1;let r=R.current;return r?.originalAgentId===e.originalAgentId&&!r.replacementAgentId&&!r.requestFreshStateAt&&ce({...r,requestFreshStateAt:n.lastMessageAt}),!0};if(n())return;let r=it(n),i=t+FF,a=e.requestFreshStateAt?e.requestFreshStateAt+PF:1/0,o=Math.max(0,Math.min(i,a)-Date.now()),s=window.setTimeout(()=>{let t=R.current;!t?.requestSettled||!t.requestError||t.replacementAgentId||t.originalAgentId!==e.originalAgentId||(L.current=null,ce(null),w({id:Date.now(),kind:`error`,message:t.requestError}))},o);return()=>{r(),window.clearTimeout(s)}},[ce,T]),(0,G.useEffect)(()=>{let e=T;if(!e)return;let t=Math.max(0,e.startedAt+LF-Date.now()),n=window.setTimeout(()=>{let t=R.current;!t||t.startedAt!==e.startedAt||(L.current=null,ce(null),w({id:Date.now(),kind:`error`,message:ue.agentRestartTimedOut}))},t);return()=>window.clearTimeout(n)},[ce,ue.agentRestartTimedOut,T]);let H=(0,G.useCallback)(e=>{let t={appearance:DF(e.appearance??F.appearance),language:OF(e.language??F.language)};ee(t),fetch(r(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}).then(e=>e.json()).then(e=>{let n=e.settings??{};ee({appearance:DF(n.appearance??t.appearance),language:OF(n.language??t.language)})}).catch(()=>{w({id:Date.now(),kind:`error`,message:`Failed to save preferences`})})},[F.appearance,F.language]),ge=(0,G.useCallback)(e=>{let t=Array.from(new Set(e.filter(Boolean)));t.length!==0&&fetch(r(`/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:[];P(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,G.useEffect)(()=>{if(e.connected){if(e.mainAgentId||e.agents.some(e=>e.isMain)){z.current=!1;return}z.current||(z.current=!0,e.startAgent(`bash`,void 0,!0))}},[e.agents,e.connected,e.mainAgentId,e.startAgent]),(0,G.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=oe(),o=window.innerHeight||n||MF,s=a?Math.min(Math.max(n,MF),Math.max(o,MF)):n,c=Math.max(0,o-n-r),l=a&&re(),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 _e=(0,G.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]),ve=(0,G.useCallback)((e,t)=>{b({agentId:e,options:t})},[]),ye=(0,G.useCallback)((e,t)=>{if(e===h&&p.includes(e)){_e(e,t);return}ve(e,t)},[_e,h,p,ve]);(0,G.useEffect)(()=>{y&&de.some(e=>e.id===y.agentId&&zF(e))&&(b(null),_e(y.agentId,y.options))},[_e,de,y]);let be=(0,G.useCallback)(e=>{let t=new Set(e);if(t.size===0)return;let n=ne.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;ne.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]),xe=(0,G.useCallback)(e=>{be([e])},[be]),Se=(0,G.useCallback)(e=>{if(p.length===0)return;let t=p[(Math.max(0,p.findIndex(e=>e===h))+e+p.length)%p.length];t&&ye(t)},[h,ye,p]),Ce=(0,G.useCallback)((e,t,n,r)=>{let i=se.current+1;se.current=i,V.current=n??(document.activeElement instanceof HTMLElement?document.activeElement:null),c(e),u(t),f(r),S(`projects`),o(`input`);let a=()=>{se.current===i&&o(e=>e===`input`?e:`input`)};window.requestAnimationFrame(a),window.setTimeout(a,80),window.setTimeout(a,180)},[]),we=(0,G.useCallback)(()=>{let e=V.current,t=e?.getAttribute(`data-testid`)===`code-new-agent`;V.current=null;let n=()=>{WF(e)||t&&WF(document.querySelector(`[data-testid="code-new-agent"]`))||WF((h?Array.from(document.querySelectorAll(`[data-testid="code-agent-row"]`)).find(e=>e.dataset.agentId===h):null)??null)||WF(document.querySelector(`[data-testid="code-new-agent"]`))||WF(document.querySelector(`[data-testid="code-project-list"]`))};window.requestAnimationFrame(n),window.setTimeout(n,80),window.setTimeout(n,180)},[h]),Te=(0,G.useCallback)(()=>{se.current+=1,o(`none`),we()},[we]),Ee=(0,G.useCallback)(e=>{w({id:Date.now(),kind:`error`,message:e})},[]),De=(0,G.useCallback)(t=>{mC(t).catch(e=>{console.error(`Failed to destroy killed terminal session:`,e)}),e.killAgent(t),xe(t)},[e,xe]),Oe=(0,G.useCallback)(t=>{e.interruptAgent(t)},[e]),U=(0,G.useCallback)(t=>{te.current||(z.current=!0,te.current={beforeIds:new Set(e.agents.map(e=>e.id))},e.restartMainAgent(t)||(te.current=null,z.current=!1))},[e]),ke=(0,G.useCallback)((t,n,r)=>{I.current||(se.current+=1,I.current={beforeIds:new Set(e.agents.map(e=>e.id))},e.startAgent(t,n,!1,r)||(I.current=null))},[e]);(0,G.useEffect)(()=>{let t=e.lastStartedAgentId,n=I.current;!t||!n||n.beforeIds.has(t)||(I.current=null,o(`none`),ve(t))},[ve,e.lastStartedAgentId]);let Ae=(0,G.useCallback)(async(e,t)=>{try{let n=await fetch(r(`/api/agents/${e}/fork`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({mode:t})}),i=await n.json().catch(()=>null);if(!n.ok||!i?.agentId){Ee(i?.error||`Failed to fork agent (${n.status})`);return}ve(i.agentId)}catch(e){Ee(e instanceof Error?e.message:`Failed to fork agent`)}},[Ee,ve]),W=(0,G.useCallback)(async(e,t)=>{try{let n=await fetch(r(`/api/projects/delete-worktree`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({workspace:e,force:t?.force===!0})}),i=await n.json().catch(()=>null);if(!n.ok&&i?.requiresForce!==!0&&Ee(i?.error||`Failed to delete worktree (${n.status})`),i?.deleted&&be(i.archivedAgentIds??[]),i)return i;let a=`Failed to delete worktree (${n.status})`;return Ee(a),{error:a}}catch(e){let t=e instanceof Error?e.message:`Failed to delete worktree`;return Ee(t),{error:t}}},[be,Ee]),je=(0,G.useCallback)(async(e,t)=>{try{let n=await fetch(r(`/api/agents/${e}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({customTitle:t})}),i=await n.json().catch(()=>null);n.ok||Ee(i?.error||`Failed to rename agent (${n.status})`)}catch(e){Ee(e instanceof Error?e.message:`Failed to rename agent`)}},[Ee]),Me=(0,G.useCallback)(async(t,n)=>{if(n.unread===!1&&Object.keys(n).every(e=>e===`unread`||e===`readAttentionSeq`||e===`readOutputEpoch`||e===`readOutputSeq`)&&L.current===t)return!0;let i=typeof n.launchPermissionMode==`string`?n.launchPermissionMode:``,a=typeof n.agentRuntimeMode==`string`,o=i||a?e.agents.find(e=>e.id===t)??null:null,s=Tn(o)&&!a?null:o;if(s){if(L.current)return!1;L.current=t,ce({originalAgentId:t,agent:s,kind:a?`runtime`:`permission`,startedAt:Date.now()})}let c=()=>{s&&R.current?.originalAgentId===t&&(L.current=null,ce(null))};try{let e=new AbortController,a=window.setTimeout(()=>e.abort(),IF),o=await fetch(r(`/api/agents/${t}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n),signal:e.signal});window.clearTimeout(a);let l=await o.json().catch(()=>null);if(!o.ok){let e=R.current;return s&&e?.originalAgentId===t&&e.replacementAgentId?(ce({...e,requestSettled:!0}),l??!0):(c(),Ee(l?.error||`Failed to update agent (${o.status})`),!1)}if(l?.warning&&Ee(l.warning),n.archived===!0&&xe(t),l?.restartedAgentId){let e=l.restartedAgentId,r=R.current;s&&r?.originalAgentId===t&&(r.agent.id===t?(m(n=>n.map(n=>n===t?e:n)),g(n=>n===t?e:n),ce({...r,replacementAgentId:e,transitionFromAgentId:t,requestSettled:!0,agent:{...r.agent,id:e,launchPermissionMode:l.launchPermissionMode??i,runtimeBinding:Dn(l.agentRuntimeMode??n.agentRuntimeMode,r.agent.runtimeBinding),restartedFromAgentId:t,restartedFromAgentIds:Array.from(new Set([...r.agent.restartedFromAgentIds??[],t]))}})):ce({...r,requestSettled:!0,requestError:void 0}))}else c();return l??!0}catch(e){let n=e instanceof DOMException&&e.name===`AbortError`?ue.agentRestartTimedOut:e instanceof Error?e.message:`Failed to update agent`,r=R.current;return s&&r?.originalAgentId===t?(ce({...r,requestSettled:!0,requestError:n,requestErrorAt:Date.now()}),!!r.replacementAgentId):(Ee(n),!1)}},[xe,ce,ue.agentRestartTimedOut,Ee,e.agents]),Ne=(0,G.useCallback)(async e=>{await Me(e,{archived:!1})&&ve(e)},[Me,ve]),Pe=(0,G.useMemo)(()=>de.find(e=>e.id===he)??null,[de,he]);return(0,G.useEffect)(()=>{if(!t||!HF(Pe))return;let e=Pe.id,n,r;return n=window.setTimeout(()=>ge([e]),2500),r=window.setInterval(()=>ge([e]),NF),()=>{n!==void 0&&window.clearTimeout(n),r!==void 0&&window.clearInterval(r)}},[Pe?.id,Pe?.providerSessionId,Pe?.providerSessionProvider,Pe?.providerSessionTemporary,t,ge]),(0,G.useEffect)(()=>{let e=RF(Pe);e&&(ae.current=e)},[Pe]),Wt((0,G.useMemo)(()=>[],[Pe,Se,n,Ce,ye]),jF),(0,G.useEffect)(()=>{e.error&&(I.current=null,b(null),te.current=null,z.current=!1,Ee(e.error))},[Ee,e.error,e.errorId]),(0,G.useEffect)(()=>{if(!C)return;let e=window.setTimeout(()=>w(null),2800);return()=>window.clearTimeout(e)},[C]),(0,G.useEffect)(()=>{if(!t)return;let e=!1,n,i,a=()=>{fetch(r(`/api/usage`)).then(e=>e.json()).then(t=>{e||M(t.usage??null)}).catch(()=>{e||M(null)})};return i=window.setTimeout(a,1500),n=window.setInterval(a,6e4),()=>{e=!0,i!==void 0&&window.clearTimeout(i),n!==void 0&&window.clearInterval(n)}},[t]),(0,G.useEffect)(()=>{hC(de.filter(zF).map(e=>e.id)).catch(e=>{console.error(`Failed to prune terminal sessions:`,e)})},[de]),(0,G.useEffect)(()=>{let e=new Set(de.filter(zF).map(e=>e.id));m(t=>Array.from(new Set(t.map(t=>e.has(t)?t:VF(de,t)?.id??t))).filter(t=>e.has(t)||R.current?.agent.id===t))},[de]),(0,G.useEffect)(()=>{let e=new Set(de.filter(zF).map(e=>e.id));g(t=>t&&(e.has(t)||R.current?.agent.id===t)?t:p[0]??null)},[de,p]),(0,G.useEffect)(()=>{de.some(e=>!e.isMain&&zF(e))||(B.current=!1)},[de]),(0,G.useEffect)(()=>{if(p.length>0||B.current)return;let e=de.find(e=>!e.isMain&&zF(e))?.id;e&&(B.current=!0,m([e]),g(e))},[de,p.length,e.mainAgentId]),(0,G.useEffect)(()=>{let t=te.current;if(!t)return;let n=e.agents.find(e=>e.isMain&&!e.archived&&!t.beforeIds.has(e.id));n&&(te.current=null,z.current=!1,ye(n.id))},[ye,e.agents]),(0,G.useEffect)(()=>{if(ie.current||e.agents.length===0)return;let t=new URLSearchParams(window.location.search).get(`agent`);if(!t){ie.current=!0;return}e.agents.some(e=>e.id===t&&!e.archived)&&(ie.current=!0,ye(t))},[ye,e.agents]),(0,G.useEffect)(()=>(document.body.classList.add(`code-mode`),()=>{document.body.classList.remove(`code-mode`)}),[]),(0,G.useEffect)(()=>{AF(`terminal`,{crtEffects:!1,appearance:F.appearance})},[F.appearance]),(0,G.useEffect)(()=>{let e=!1;return fetch(r(`/api/settings`)).then(e=>e.json()).then(t=>{if(e)return;let n=t.settings??{};ee({appearance:DF(n.appearance),language:OF(n.language)})}).catch(()=>{}),()=>{e=!0}},[]),(0,K.jsxs)(`div`,{className:`app-container code-app-shell`,"data-testid":`app-shell`,children:[(0,K.jsx)(wF,{agents:de,taskHistory:e.taskHistory,mainPageSessionKeys:e.mainPageSessionKeys,activeView:x,dialogOpen:le!==`none`,usageSummary:A,contextWindowByAgentId:N,activeTerminalId:he,permissionSwitchingAgentId:T?.agent.id??null,agentSwitchingKind:T?.kind??null,permissionSwitchReplacement:T?.replacementAgentId?{originalAgentId:T.transitionFromAgentId??T.originalAgentId,replacementAgentId:T.replacementAgentId}:pe??O,openTerminalIds:me,terminalFocusRequest:_,keyMap:n,keyboardShortcutsEnabled:jF,uiPreferences:F,onOpenTerminal:ye,onOpenTerminalWhenReady:ve,onNewAgent:Ce,onStartAgent:ke,onRenameAgent:je,onUpdateAgentFlags:Me,onOpenArchivedAgent:Ne,onForkAgent:Ae,onDeleteForkWorktreeProject:W,onRestartMainAgent:U,onWorkspaceViewChange:S,onKill:De,onInterruptAgent:Oe,sendComposerInput:e.sendComposerInput,respondToAppServerRequest:e.respondToAppServerRequest,onSessionOutput:e.onSessionOutput,onUpdateUiPreferences:H}),(0,K.jsx)(vn,{open:le===`input`,mustStartMain:!1,initialWorkspace:s,initialCommand:l,initialCustomTitle:d,showWorkflowTaskFields:!1,copy:ue,onStart:ke,onClose:Te}),(0,K.jsx)(Sn,{copy:ue}),C&&(0,K.jsx)(`div`,{className:`app-toast ${C.kind}`,"data-testid":`app-toast`,role:`status`,children:C.message})]})}export{GF as App};
|