@straiffi/archon 1.2.25 → 1.2.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{TestsDialog-ditcW5bX.js → TestsDialog-CzG_2qwn.js} +1 -1
- package/dist/client/assets/{index-8amI0I2a.js → index-qwXjSQQl.js} +5 -5
- package/dist/client/index.html +1 -1
- package/dist/server/index.js +11 -3
- package/dist/server/index.js.map +1 -1
- package/dist/server/lib/tickets.js +48 -1
- package/dist/server/lib/tickets.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TestsDialog-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TestsDialog-CzG_2qwn.js","assets/rolldown-runtime-BYbx6iT9.js","assets/dropdown-menu-P4osjIhO.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{a as e,i as t,n,r,t as i}from"./rolldown-runtime-BYbx6iT9.js";import{$ as a,A as o,At as s,B as c,Bt as l,C as u,Ct as d,D as f,Dt as p,E as m,Et as h,F as g,Ft as _,G as v,Gt as y,H as b,Ht as x,I as S,It as C,J as w,K as T,Kt as E,L as D,Lt as O,M as k,Mt as A,N as j,Nt as M,O as N,Ot as P,P as F,Pt as I,Q as L,R,Rt as z,S as ee,St as te,T as ne,Tt as re,U as B,Ut as ie,V,Vt as H,W as ae,Wt as oe,X as se,Y as ce,Z as le,_ as ue,_t as de,a as U,at as fe,b as pe,bt as me,c as W,ct as he,d as G,dt as ge,et as _e,f as ve,ft as ye,g as be,gt as xe,h as K,ht as Se,i as Ce,it as we,j as Te,jt as Ee,k as De,kt as Oe,l as ke,lt as Ae,m as q,mt as je,n as Me,nt as Ne,o as Pe,ot as Fe,p as Ie,pt as Le,q as Re,r as ze,rt as Be,s as Ve,st as He,t as Ue,tt as We,u as Ge,ut as Ke,v as qe,vt as Je,w as Ye,wt as Xe,x as Ze,xt as Qe,y as $e,yt as et,z as J,zt as tt}from"./dropdown-menu-P4osjIhO.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var nt=i((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,O());else{var t=n(l);t!==null&&j(x,t.startTime-e)}}var S=!1,C=-1,w=5,T=-1;function E(){return g?!0:!(e.unstable_now()-T<w)}function D(){if(g=!1,S){var t=e.unstable_now();T=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(C),C=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&E());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&j(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var k=new MessageChannel,A=k.port2;k.port1.onmessage=D,O=function(){A.postMessage(null)}}else O=function(){_(D,0)};function j(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):w=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,j(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,O()))),r},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),rt=i(((e,t)=>{t.exports=nt()})),it=i((e=>{var t=rt(),n=E(),r=y();function i(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function a(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function o(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function s(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function c(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function l(e){if(o(e)!==e)throw Error(i(188))}function u(e){var t=e.alternate;if(!t){if(t=o(e),t===null)throw Error(i(188));return t===e?e:null}for(var n=e,r=t;;){var a=n.return;if(a===null)break;var s=a.alternate;if(s===null){if(r=a.return,r!==null){n=r;continue}break}if(a.child===s.child){for(s=a.child;s;){if(s===n)return l(a),e;if(s===r)return l(a),t;s=s.sibling}throw Error(i(188))}if(n.return!==r.return)n=a,r=s;else{for(var c=!1,u=a.child;u;){if(u===n){c=!0,n=a,r=s;break}if(u===r){c=!0,r=a,n=s;break}u=u.sibling}if(!c){for(u=s.child;u;){if(u===n){c=!0,n=s,r=a;break}if(u===r){c=!0,r=s,n=a;break}u=u.sibling}if(!c)throw Error(i(189))}}if(n.alternate!==r)throw Error(i(190))}if(n.tag!==3)throw Error(i(188));return n.stateNode.current===n?e:t}function d(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=d(e),t!==null)return t;e=e.sibling}return null}var f=Object.assign,p=Symbol.for(`react.element`),m=Symbol.for(`react.transitional.element`),h=Symbol.for(`react.portal`),g=Symbol.for(`react.fragment`),_=Symbol.for(`react.strict_mode`),v=Symbol.for(`react.profiler`),b=Symbol.for(`react.consumer`),x=Symbol.for(`react.context`),S=Symbol.for(`react.forward_ref`),C=Symbol.for(`react.suspense`),w=Symbol.for(`react.suspense_list`),T=Symbol.for(`react.memo`),D=Symbol.for(`react.lazy`),O=Symbol.for(`react.activity`),k=Symbol.for(`react.memo_cache_sentinel`),A=Symbol.iterator;function j(e){return typeof e!=`object`||!e?null:(e=A&&e[A]||e[`@@iterator`],typeof e==`function`?e:null)}var M=Symbol.for(`react.client.reference`);function N(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===M?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case g:return`Fragment`;case v:return`Profiler`;case _:return`StrictMode`;case C:return`Suspense`;case w:return`SuspenseList`;case O:return`Activity`}if(typeof e==`object`)switch(e.$$typeof){case h:return`Portal`;case x:return e.displayName||`Context`;case b:return(e._context.displayName||`Context`)+`.Consumer`;case S:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case T:return t=e.displayName||null,t===null?N(e.type)||`Memo`:t;case D:t=e._payload,e=e._init;try{return N(e(t))}catch{}}return null}var P=Array.isArray,F=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,I=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,L={pending:!1,data:null,method:null,action:null},R=[],z=-1;function ee(e){return{current:e}}function te(e){0>z||(e.current=R[z],R[z]=null,z--)}function ne(e,t){z++,R[z]=e.current,e.current=t}var re=ee(null),B=ee(null),ie=ee(null),V=ee(null);function H(e,t){switch(ne(ie,t),ne(B,e),ne(re,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Hd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Hd(t),e=Ud(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}te(re),ne(re,e)}function ae(){te(re),te(B),te(ie)}function oe(e){e.memoizedState!==null&&ne(V,e);var t=re.current,n=Ud(t,e.type);t!==n&&(ne(B,e),ne(re,n))}function se(e){B.current===e&&(te(re),te(B)),V.current===e&&(te(V),$f._currentValue=L)}var ce,le;function ue(e){if(ce===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);ce=t&&t[1]||``,le=-1<e.stack.indexOf(`
|
|
3
3
|
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
|
|
4
4
|
`+ce+e+le}var de=!1;function U(e,t){if(!e||de)return``;de=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,`props`,{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}e.call(n.prototype)}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,`name`,{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
|
|
@@ -138,13 +138,13 @@ ${s.join(`
|
|
|
138
138
|
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),dB&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=PB(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Yz(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-FB),FB),t/=FB,t/Math.abs(t)+Math.round(t*(IB-1)))}shouldForceSelection(e){return sB?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),LB)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(sB&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(!(!this._model.selectionEnd||!this._model.selectionStart)&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<RB&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=bB(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);if(!n){this._oldHasSelection&&this._fireOnSelectionChange(e,t,n);return}!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(!(!t&&o.slice(s,c).trim()===``)){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=PB(n,this._bufferService.cols)}};BB=AP([jP(3,iF),jP(4,oF),jP(5,vF),jP(6,uF),jP(7,yF),jP(8,_F)],BB);var VB=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},HB=class{constructor(){this._color=new VB,this._css=new VB}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},UB=Object.freeze((()=>{let e=[_z.toColor(`#2e3436`),_z.toColor(`#cc0000`),_z.toColor(`#4e9a06`),_z.toColor(`#c4a000`),_z.toColor(`#3465a4`),_z.toColor(`#75507b`),_z.toColor(`#06989a`),_z.toColor(`#d3d7cf`),_z.toColor(`#555753`),_z.toColor(`#ef2929`),_z.toColor(`#8ae234`),_z.toColor(`#fce94f`),_z.toColor(`#729fcf`),_z.toColor(`#ad7fa8`),_z.toColor(`#34e2e2`),_z.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:hz.toCss(r,i,a),rgba:hz.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:hz.toCss(n,n,n),rgba:hz.toRgba(n,n,n)})}return e})()),WB=_z.toColor(`#ffffff`),GB=_z.toColor(`#000000`),KB=_z.toColor(`#ffffff`),qB=GB,JB={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},YB=WB,XB=class extends rI{constructor(e){super(),this._optionsService=e,this._contrastCache=new HB,this._halfContrastCache=new HB,this._onChangeColors=this._register(new OI),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:WB,background:GB,cursor:KB,cursorAccent:qB,selectionForeground:void 0,selectionBackgroundTransparent:JB,selectionBackgroundOpaque:gz.blend(GB,JB),selectionInactiveBackgroundTransparent:JB,selectionInactiveBackgroundOpaque:gz.blend(GB,JB),scrollbarSliderBackground:gz.opacity(WB,.2),scrollbarSliderHoverBackground:gz.opacity(WB,.4),scrollbarSliderActiveBackground:gz.opacity(WB,.5),overviewRulerBorder:WB,ansi:UB.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=ZB(e.foreground,WB),t.background=ZB(e.background,GB),t.cursor=gz.blend(t.background,ZB(e.cursor,KB)),t.cursorAccent=gz.blend(t.background,ZB(e.cursorAccent,qB)),t.selectionBackgroundTransparent=ZB(e.selectionBackground,JB),t.selectionBackgroundOpaque=gz.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=ZB(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=gz.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?ZB(e.selectionForeground,mz):void 0,t.selectionForeground===mz&&(t.selectionForeground=void 0),gz.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=gz.opacity(t.selectionBackgroundTransparent,.3)),gz.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=gz.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=ZB(e.scrollbarSliderBackground,gz.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=ZB(e.scrollbarSliderHoverBackground,gz.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=ZB(e.scrollbarSliderActiveBackground,gz.opacity(t.foreground,.5)),t.overviewRulerBorder=ZB(e.overviewRulerBorder,YB),t.ansi=UB.slice(),t.ansi[0]=ZB(e.black,UB[0]),t.ansi[1]=ZB(e.red,UB[1]),t.ansi[2]=ZB(e.green,UB[2]),t.ansi[3]=ZB(e.yellow,UB[3]),t.ansi[4]=ZB(e.blue,UB[4]),t.ansi[5]=ZB(e.magenta,UB[5]),t.ansi[6]=ZB(e.cyan,UB[6]),t.ansi[7]=ZB(e.white,UB[7]),t.ansi[8]=ZB(e.brightBlack,UB[8]),t.ansi[9]=ZB(e.brightRed,UB[9]),t.ansi[10]=ZB(e.brightGreen,UB[10]),t.ansi[11]=ZB(e.brightYellow,UB[11]),t.ansi[12]=ZB(e.brightBlue,UB[12]),t.ansi[13]=ZB(e.brightMagenta,UB[13]),t.ansi[14]=ZB(e.brightCyan,UB[14]),t.ansi[15]=ZB(e.brightWhite,UB[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=ZB(e.extendedAnsi[r],UB[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0){for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];return}switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};XB=AP([jP(0,uF)],XB);function ZB(e,t){if(e!==void 0)try{return _z.toColor(e)}catch{}return t}var QB=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},$B=class{constructor(){this._services=new QB,this._services.set(cF,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=tF(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},eV={trace:0,debug:1,info:2,warn:3,error:4,off:5},tV=`xterm.js: `,nV=class extends rI{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),rV=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=eV[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:tV)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};nV=AP([jP(0,uF)],nV);var rV,iV=class extends rI{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new OI),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new OI),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new OI),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},aV=3,oV=Object.freeze(new YP),sV=0,cV=2,lV=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*aV);let r=t||ZP.fromCharData([0,qP,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*aV+0],n=t&2097151;return[this._data[e*aV+1],t&2097152?this._combined[e]:n?UP(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*aV+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*aV+0]=e|2097152|t[2]<<22):this._data[e*aV+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*aV+0]>>22}hasWidth(e){return this._data[e*aV+0]&12582912}getFg(e){return this._data[e*aV+1]}getBg(e){return this._data[e*aV+2]}hasContent(e){return this._data[e*aV+0]&4194303}getCodePoint(e){let t=this._data[e*aV+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*aV+0]&2097152}getString(e){let t=this._data[e*aV+0];return t&2097152?this._combined[e]:t&2097151?UP(t&2097151):``}isProtected(e){return this._data[e*aV+2]&536870912}loadCell(e,t){return sV=e*aV,t.content=this._data[sV+0],t.fg=this._data[sV+1],t.bg=this._data[sV+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*aV+0]=t.content,this._data[e*aV+1]=t.fg,this._data[e*aV+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*aV+0]=t|n<<22,this._data[e*aV+1]=r.fg,this._data[e*aV+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*aV+0];r&2097152?this._combined[e]+=UP(t):r&2097151?(this._combined[e]=UP(r&2097151)+UP(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*aV+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new ZP;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new ZP;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r){for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;return}for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*cV<this._data.buffer.byteLength;let n=e*aV;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*cV<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*cV<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t){for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);return}this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*aV+0]&4194303)return e+(this._data[e*aV+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*aV+0]&4194303||this._data[e*aV+2]&50331648)return e+(this._data[e*aV+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<aV;e++)this._data[(n+i)*aV+e]=a[(t+i)*aV+e];a[(t+i)*aV+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<aV;e++)this._data[(n+i)*aV+e]=a[(t+i)*aV+e];a[(t+i)*aV+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*aV+0],n=e&2097151,a=e&2097152?this._combined[t]:n?UP(n):JP;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function uV(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=mV(u,d,t),p=1,m=0;for(;p<u.length;){let e=mV(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function dV(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function fV(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function pV(e,t,n){let r=[],i=e.map((n,r)=>mV(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=mV(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function mV(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var hV=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new OI),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),QF(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};hV._nextId=1;var gV=hV,_V={},vV=_V.B;_V[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:``,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},_V.A={"#":`£`},_V.B=void 0,_V[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},_V.C=_V[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},_V.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},_V.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},_V.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},_V.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},_V.E=_V[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},_V.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},_V.H=_V[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},_V[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var yV=4294967295,bV=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=oV.clone(),this.savedCharset=vV,this.markers=[],this._nullCell=ZP.fromCharData([0,qP,1,0]),this._whitespaceCell=ZP.fromCharData([0,JP,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new gB,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new iV(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new XP),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new XP),this._whitespaceCell}getBlankLine(e,t){return new lV(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>yV?yV:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=oV);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new iV(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(oV),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new lV(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new lV(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=uV(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(oV),n);if(r.length>0){let n=dV(this.lines,r);fV(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(oV),i=n;for(;i-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new lV(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(oV),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=pV(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(oV,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=mV(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new gV(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},xV=class extends rI{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new OI),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,()=>this.setupTabStops()))}reset(){this._normal=new bV(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new bV(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},SV=2,CV=1,wV=class extends rI{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new OI),this.onResize=this._onResize.event,this._onScroll=this._register(new OI),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,SV),this.rows=Math.max(e.rawOptions.rows||0,CV),this.buffers=this._register(new xV(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};wV=AP([jP(0,uF)],wV);var TV={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:sB,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},EV=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],DV=class extends rI{constructor(e){super(),this._onOptionChange=this._register(new OI),this.onOptionChange=this._onOptionChange.event;let t={...TV};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(eI(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in TV))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in TV))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=TV[e],!OV(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=TV[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=EV.includes(t)?t:TV[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={};break}return t}};function OV(e){return e===`block`||e===`underline`||e===`bar`}function kV(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&kV(e[r],t-1);return n}var AV=Object.freeze({insertMode:!1}),jV=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),MV=class extends rI{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new OI),this.onData=this._onData.event,this._onUserInput=this._register(new OI),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new OI),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new OI),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=kV(AV),this.decPrivateModes=kV(jV)}reset(){this.modes=kV(AV),this.decPrivateModes=kV(jV)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};MV=AP([jP(0,iF),jP(1,lF),jP(2,uF)],MV);var NV={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function PV(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var FV=String.fromCharCode,IV={DEFAULT:e=>{let t=[PV(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${FV(t[0])}${FV(t[1])}${FV(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${PV(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${PV(e,!0)};${e.x};${e.y}${t}`}},LV=class extends rI{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new OI),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(NV))this.addProtocol(e,NV[e]);for(let e of Object.keys(IV))this.addEncoding(e,IV[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};LV=AP([jP(0,iF),jP(1,oF),jP(2,uF)],LV);var RV=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],zV=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],BV;function VV(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var HV=class{constructor(){if(this.version=`6`,!BV){BV=new Uint8Array(65536),BV.fill(1),BV[0]=0,BV.fill(0,1,32),BV.fill(0,127,160),BV.fill(2,4352,4448),BV[9001]=2,BV[9002]=2,BV.fill(2,11904,42192),BV[12351]=1,BV.fill(2,44032,55204),BV.fill(2,63744,64256),BV.fill(2,65040,65050),BV.fill(2,65072,65136),BV.fill(2,65280,65377),BV.fill(2,65504,65511);for(let e=0;e<RV.length;++e)BV.fill(0,RV[e][0],RV[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?BV[e]:VV(e,zV)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=UV.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return UV.createPropertyValue(0,n,r)}},UV=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new OI,this.onChange=this._onChange.event;let e=new HV;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return(e&1)!=0}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},WV=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function GV(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var KV=2147483647,qV=256,JV=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>qV)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>KV?KV:e}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>KV?KV:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,KV):e}},YV=[],XV=class{constructor(){this._state=0,this._active=YV,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=YV}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=YV,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||YV,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,WP(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=YV,this._id=-1,this._state=0}}},ZV=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=WP(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},QV=[],$V=class{constructor(){this._handlers=Object.create(null),this._active=QV,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=QV}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=QV,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||QV,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,WP(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=QV,this._ident=0}},eH=new JV;eH.addParam(0);var tH=class{constructor(e){this._handler=e,this._data=``,this._params=eH,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():eH,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=WP(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=eH,this._data=``,this._hitLimit=!1,e));return this._params=eH,this._data=``,this._hitLimit=!1,t}},nH=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},rH=160,iH=function(){let e=new nH(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(rH,0,2,0),e.add(rH,8,5,8),e.add(rH,6,0,6),e.add(rH,11,0,11),e.add(rH,13,13,13),e}(),aH=class extends rI{constructor(e=iH){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new JV,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(eI(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new XV),this._dcsParser=this._register(new $V),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:rH)],i>>4){case 2:for(let i=n+1;;++i){if(i>=t||(r=e[i])<32||r>126&&r<rH){this._printHandler(e,n,i),n=i-1;break}if(++i>=t||(r=e[i])<32||r>126&&r<rH){this._printHandler(e,n,i),n=i-1;break}if(++i>=t||(r=e[i])<32||r>126&&r<rH){this._printHandler(e,n,i),n=i-1;break}if(++i>=t||(r=e[i])<32||r>126&&r<rH){this._printHandler(e,n,i),n=i-1;break}}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<rH){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<rH){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=i&15}}},oH=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,sH=/^[\da-f]+$/;function cH(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=oH.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),sH.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function lH(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function uH(e,t=16){let[n,r,i]=e;return`rgb:${lH(n,t)}/${lH(r,t)}/${lH(i,t)}`}var dH={"(":0,")":1,"*":2,"+":3,"-":1,".":2},fH=131072,pH=10;function mH(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var hH=5e3,gH=0,_H=class extends rI{constructor(e,t,n,r,i,a,o,s,c=new aH){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new GP,this._utf8Decoder=new KP,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=oV.clone(),this._eraseAttrDataInternal=oV.clone(),this._onRequestBell=this._register(new OI),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new OI),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new OI),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new OI),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new OI),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new OI),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new OI),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new OI),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new OI),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new OI),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new OI),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new OI),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new OI),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new vH(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler($.BEL,()=>this.bell()),this._parser.setExecuteHandler($.LF,()=>this.lineFeed()),this._parser.setExecuteHandler($.VT,()=>this.lineFeed()),this._parser.setExecuteHandler($.FF,()=>this.lineFeed()),this._parser.setExecuteHandler($.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler($.BS,()=>this.backspace()),this._parser.setExecuteHandler($.HT,()=>this.tab()),this._parser.setExecuteHandler($.SO,()=>this.shiftOut()),this._parser.setExecuteHandler($.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(sz.IND,()=>this.index()),this._parser.setExecuteHandler(sz.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(sz.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new ZV(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new ZV(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new ZV(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new ZV(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new ZV(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new ZV(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new ZV(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new ZV(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new ZV(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new ZV(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new ZV(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new ZV(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:`7`},()=>this.saveCursor()),this._parser.registerEscHandler({final:`8`},()=>this.restoreCursor()),this._parser.registerEscHandler({final:`D`},()=>this.index()),this._parser.registerEscHandler({final:`E`},()=>this.nextLine()),this._parser.registerEscHandler({final:`H`},()=>this.tabSet()),this._parser.registerEscHandler({final:`M`},()=>this.reverseIndex()),this._parser.registerEscHandler({final:`=`},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:`>`},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:`c`},()=>this.fullReset()),this._parser.registerEscHandler({final:`n`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`o`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`|`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`}`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`~`},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:`%`,final:`@`},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:`%`,final:`G`},()=>this.selectDefaultCharset());for(let e in _V)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new tH((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),hH))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${hH} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>fH&&(a=this._parseStack.position+fH)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<fH&&(this._parseBuffer=new Uint32Array(Math.min(e.length,fH))),o||this._dirtyRowTracker.clearRange(),e.length>fH)for(let t=a;t<e.length;t+=fH){let a=t+fH<e.length?t+fH:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=UV.extractWidth(t);let n=UV.extractShouldJoin(t),m=n?UV.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(UP(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof lV&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>mH(e.params[0],this._optionsService.rawOptions.windowOptions)?t(e):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new tH(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new ZV(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(oV));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=UV.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent($.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent($.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent($.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent($.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent($.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0;break}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,vV),this._charsetService.setgCharset(1,vV),this._charsetService.setgCharset(2,vV),this._charsetService.setgCharset(3,vV);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0;break}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1;break}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0);break}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${$.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=YP.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=oV.fg,e.bg=oV.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=oV.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=oV.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=oV.fg&16777215,r.bg&=-67108864,r.bg|=oV.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${$.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[${e};${t}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[?${e};${t}R`);break;case 15:break;case 25:break;case 26:break;case 53:break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=oV.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`;break}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!mH(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${$.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>pH&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>pH&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(yH(n))if(r===`?`)t.push({type:0,index:n});else{let e=cH(r);e&&t.push({type:1,index:n,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):n.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=cH(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);yH(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,vV),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(dH[e[0]],_V[e[1]]||vV),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=oV.clone(),this._eraseAttrDataInternal=oV.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new ZP;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${$.ESC}${e}${$.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},vH=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(gH=e,e=t,t=gH),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};vH=AP([jP(0,iF)],vH);function yH(e){return 0<=e&&e<256}var bH=5e7,xH=12,SH=50,CH=class extends rI{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new OI),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>bH)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=xH?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=xH)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>SH&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},wH=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};wH=AP([jP(0,iF)],wH);var TH=!1,EH=class extends rI{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new iI),this._onBinary=this._register(new OI),this.onBinary=this._onBinary.event,this._onData=this._register(new OI),this.onData=this._onData.event,this._onLineFeed=this._register(new OI),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new OI),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new OI),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new OI),this._instantiationService=new $B,this.optionsService=this._register(new DV(e)),this._instantiationService.setService(uF,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(wV)),this._instantiationService.setService(iF,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(nV)),this._instantiationService.setService(lF,this._logService),this.coreService=this._register(this._instantiationService.createInstance(MV)),this._instantiationService.setService(oF,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(LV)),this._instantiationService.setService(aF,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(UV)),this._instantiationService.setService(fF,this.unicodeService),this._charsetService=this._instantiationService.createInstance(WV),this._instantiationService.setService(sF,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(wH),this._instantiationService.setService(dF,this._oscLinkService),this._inputHandler=this._register(new _H(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(mI.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(mI.forward(this._bufferService.onResize,this._onResize)),this._register(mI.forward(this.coreService.onData,this._onData)),this._register(mI.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new CH((e,t)=>this._inputHandler.parse(e,t))),this._register(mI.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new OI),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!TH&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),TH=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,SV),t=Math.max(t,CV),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(GV.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(GV(this._bufferService),!1))),this._windowsWrappingHeuristics.value=eI(()=>{for(let t of e)t.dispose()})}}},DH={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function OH(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?t?i.key=$.ESC+`OA`:i.key=$.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?t?i.key=$.ESC+`OD`:i.key=$.ESC+`[D`:e.key===`UIKeyInputRightArrow`?t?i.key=$.ESC+`OC`:i.key=$.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(t?i.key=$.ESC+`OB`:i.key=$.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:$.DEL,e.altKey&&(i.key=$.ESC+i.key);break;case 9:if(e.shiftKey){i.key=$.ESC+`[Z`;break}i.key=$.HT,i.cancel=!0;break;case 13:i.key=e.altKey?$.ESC+$.CR:$.CR,i.cancel=!0;break;case 27:i.key=$.ESC,e.altKey&&(i.key=$.ESC+$.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;a?i.key=$.ESC+`[1;`+(a+1)+`D`:t?i.key=$.ESC+`OD`:i.key=$.ESC+`[D`;break;case 39:if(e.metaKey)break;a?i.key=$.ESC+`[1;`+(a+1)+`C`:t?i.key=$.ESC+`OC`:i.key=$.ESC+`[C`;break;case 38:if(e.metaKey)break;a?i.key=$.ESC+`[1;`+(a+1)+`A`:t?i.key=$.ESC+`OA`:i.key=$.ESC+`[A`;break;case 40:if(e.metaKey)break;a?i.key=$.ESC+`[1;`+(a+1)+`B`:t?i.key=$.ESC+`OB`:i.key=$.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=$.ESC+`[2~`);break;case 46:a?i.key=$.ESC+`[3;`+(a+1)+`~`:i.key=$.ESC+`[3~`;break;case 36:a?i.key=$.ESC+`[1;`+(a+1)+`H`:t?i.key=$.ESC+`OH`:i.key=$.ESC+`[H`;break;case 35:a?i.key=$.ESC+`[1;`+(a+1)+`F`:t?i.key=$.ESC+`OF`:i.key=$.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:e.ctrlKey?i.key=$.ESC+`[5;`+(a+1)+`~`:i.key=$.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:e.ctrlKey?i.key=$.ESC+`[6;`+(a+1)+`~`:i.key=$.ESC+`[6~`;break;case 112:a?i.key=$.ESC+`[1;`+(a+1)+`P`:i.key=$.ESC+`OP`;break;case 113:a?i.key=$.ESC+`[1;`+(a+1)+`Q`:i.key=$.ESC+`OQ`;break;case 114:a?i.key=$.ESC+`[1;`+(a+1)+`R`:i.key=$.ESC+`OR`;break;case 115:a?i.key=$.ESC+`[1;`+(a+1)+`S`:i.key=$.ESC+`OS`;break;case 116:a?i.key=$.ESC+`[15;`+(a+1)+`~`:i.key=$.ESC+`[15~`;break;case 117:a?i.key=$.ESC+`[17;`+(a+1)+`~`:i.key=$.ESC+`[17~`;break;case 118:a?i.key=$.ESC+`[18;`+(a+1)+`~`:i.key=$.ESC+`[18~`;break;case 119:a?i.key=$.ESC+`[19;`+(a+1)+`~`:i.key=$.ESC+`[19~`;break;case 120:a?i.key=$.ESC+`[20;`+(a+1)+`~`:i.key=$.ESC+`[20~`;break;case 121:a?i.key=$.ESC+`[21;`+(a+1)+`~`:i.key=$.ESC+`[21~`;break;case 122:a?i.key=$.ESC+`[23;`+(a+1)+`~`:i.key=$.ESC+`[23~`;break;case 123:a?i.key=$.ESC+`[24;`+(a+1)+`~`:i.key=$.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=$.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=$.DEL:e.keyCode===219?i.key=$.ESC:e.keyCode===220?i.key=$.FS:e.keyCode===221&&(i.key=$.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=DH[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=$.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=$.ESC+n}else if(e.keyCode===32)i.key=$.ESC+(e.ctrlKey?$.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=$.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=$.US),e.key===`@`&&(i.key=$.NUL));break}return i}var kH=0,AH=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new gB,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new gB,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(kH=this._search(t),kH===-1)||this._getKey(this._array[kH])!==t)return!1;do if(this._array[kH]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(kH),!0;while(++kH<this._array.length&&this._getKey(this._array[kH])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(kH=this._search(e),!(kH<0||kH>=this._array.length)&&this._getKey(this._array[kH])===e))do yield this._array[kH];while(++kH<this._array.length&&this._getKey(this._array[kH])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(kH=this._search(e),!(kH<0||kH>=this._array.length)&&this._getKey(this._array[kH])===e))do t(this._array[kH]);while(++kH<this._array.length&&this._getKey(this._array[kH])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},jH=0,MH=0,NH=class extends rI{constructor(){super(),this._decorations=new AH(e=>e?.marker.line),this._onDecorationRegistered=this._register(new OI),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new OI),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(eI(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new PH(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{jH=t.options.x??0,MH=jH+(t.options.width??1),e>=jH&&e<MH&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},PH=class extends nI{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new OI),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new OI),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=_z.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=_z.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},FH=1e3,IH=class{constructor(e,t=FH){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},LH=20,RH=!1,zH=class extends rI{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new IH(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);RH?(this._accessibilityContainer.classList.add(`debug`),this._rowContainer.classList.add(`debug`),this._debugRootContainer=i.createElement(`div`),this._debugRootContainer.classList.add(`xterm`),this._debugRootContainer.appendChild(i.createTextNode(`------start a11y------`)),this._debugRootContainer.appendChild(this._accessibilityContainer),this._debugRootContainer.appendChild(i.createTextNode(`------end a11y------`)),this._terminal.element.insertAdjacentElement(`afterend`,this._debugRootContainer)):this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
|
|
139
139
|
`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(sR(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(eI(()=>{RH?this._debugRootContainer.remove():this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<LH+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
|
|
140
140
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===LH+1&&(this._liveRegion.textContent+=FP.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(!(!a||!o)){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};zH=AP([jP(1,cF),jP(2,_F),jP(3,yF)],zH);var BH=class extends rI{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new OI),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new OI),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(eI(()=>{QF(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(sR(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(sR(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(sR(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(sR(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized){this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1;return}this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&VH(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,QF(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};BH=AP([jP(1,vF),jP(2,yF),jP(3,iF),jP(4,CF)],BH);function VH(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var HH=class extends EH{constructor(e={}){super(e),this._linkifier=this._register(new iI),this.browser=$z,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new iI),this._onCursorMove=this._register(new OI),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new OI),this.onKey=this._onKey.event,this._onRender=this._register(new OI),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new OI),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new OI),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new OI),this.onBell=this._onBell.event,this._onFocus=this._register(new OI),this._onBlur=this._register(new OI),this._onA11yCharEmitter=this._register(new OI),this._onA11yTabEmitter=this._register(new OI),this._onWillOpen=this._register(new OI),this._setup(),this._decorationService=this._instantiationService.createInstance(NH),this._instantiationService.setService(pF,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Jz),this._instantiationService.setService(CF,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(mF)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(mI.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(mI.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(mI.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(mI.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(eI(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=gz.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${$.ESC}]${n};${uH(r)}${cz.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=hz.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=hz.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(zH,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(sR(this.element,`copy`,e=>{this.hasSelection()&&RP(e,this._selectionService)}));let e=e=>zP(e,this.textarea,this.coreService,this.optionsService);this._register(sR(this.textarea,`paste`,e)),this._register(sR(this.element,`paste`,e)),rB?this._register(sR(this.element,`mousedown`,e=>{e.button===2&&HP(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(sR(this.element,`contextmenu`,e=>{HP(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),dB&&this._register(sR(this.element,`auxclick`,e=>{e.button===1&&VP(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(sR(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(sR(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(sR(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(sR(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(sR(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(sR(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(sR(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(sR(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,NP.get()),fB||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Kz,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(_F,this._coreBrowserService),this._register(sR(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(sR(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(Hz,this._document,this._helperContainer),this._instantiationService.setService(gF,this._charSizeService),this._themeService=this._instantiationService.createInstance(XB),this._instantiationService.setService(SF,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Cz),this._instantiationService.setService(xF,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(vB,this.rows,this.screenElement)),this._instantiationService.setService(yF,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(lz,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(Zz),this._instantiationService.setService(vF,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(BH,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(ez,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(BB,this.element,this.screenElement,r)),this._instantiationService.setService(bF,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(mI.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(tz,this.screenElement)),this._register(sR(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(zH,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(oz,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(oz,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Vz,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(sR(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(e)))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(sR(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=$.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){BP(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=OH(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===$.ETX||n.key===$.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(UH(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(oV));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent($.ESC+`[I`):this.coreService.triggerDataEvent($.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[6;${r};${n}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function UH(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var WH=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},GH=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new ZP)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},KH=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new GH(t)}getNullCell(){return new ZP}},qH=class extends rI{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new OI),this.onBufferChange=this._onBufferChange.event,this._normal=new KH(this._core.buffers.normal,`normal`),this._alternate=new KH(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},JH=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},YH=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},XH=[`cols`,`rows`],ZH=0,QH=class extends rI{constructor(e){super(),this._core=this._register(new HH(e)),this._addonManager=this._register(new WH),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(XH.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new JH(this._core),this._parser}get unicode(){return this._checkProposedApi(),new YH(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new qH(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`;break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
|
|
141
|
-
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return NP.get()},set promptLabel(e){NP.set(e)},get tooMuchOutput(){return FP.get()},set tooMuchOutput(e){FP.set(e)}}}_verifyIntegers(...e){for(ZH of e)if(ZH===1/0||isNaN(ZH)||ZH%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(ZH of e)if(ZH&&(ZH===1/0||isNaN(ZH)||ZH%1!=0||ZH<0))throw Error(`This API only accepts positive integers`)}},$H=Object.create(null);$H.open=`0`,$H.close=`1`,$H.ping=`2`,$H.pong=`3`,$H.message=`4`,$H.upgrade=`5`,$H.noop=`6`;var eU=Object.create(null);Object.keys($H).forEach(e=>{eU[$H[e]]=e});var tU={type:`error`,data:`parser error`},nU=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,rU=typeof ArrayBuffer==`function`,iU=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,aU=({type:e,data:t},n,r)=>nU&&t instanceof Blob?n?r(t):oU(t,r):rU&&(t instanceof ArrayBuffer||iU(t))?n?r(t):oU(new Blob([t]),r):r($H[e]+(t||``)),oU=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function sU(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var cU;function lU(e,t){if(nU&&e.data instanceof Blob)return e.data.arrayBuffer().then(sU).then(t);if(rU&&(e.data instanceof ArrayBuffer||iU(e.data)))return t(sU(e.data));aU(e,!1,e=>{cU||=new TextEncoder,t(cU.encode(e))})}var uU=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,dU=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)dU[uU.charCodeAt(e)]=e;var fU=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=dU[e.charCodeAt(r)],o=dU[e.charCodeAt(r+1)],s=dU[e.charCodeAt(r+2)],c=dU[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},pU=typeof ArrayBuffer==`function`,mU=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:gU(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:hU(e.substring(1),t)}:eU[n]?e.length>1?{type:eU[n],data:e.substring(1)}:{type:eU[n]}:tU},hU=(e,t)=>pU?gU(fU(e),t):{base64:!0,data:e},gU=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},_U=``,vU=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{aU(e,!1,e=>{r[a]=e,++i===n&&t(r.join(_U))})})},yU=(e,t)=>{let n=e.split(_U),r=[];for(let e=0;e<n.length;e++){let i=mU(n[e],t);if(r.push(i),i.type===`error`)break}return r};function bU(){return new TransformStream({transform(e,t){lU(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var xU;function SU(e){return e.reduce((e,t)=>e+t.length,0)}function CU(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function wU(e,t){xU||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(SU(n)<1)break;let e=CU(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(SU(n)<2)break;let e=CU(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(SU(n)<8)break;let e=CU(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(tU);break}i=a*2**32+t.getUint32(4),r=3}else{if(SU(n)<i)break;let e=CU(n,i);s.enqueue(mU(a?e:xU.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(tU);break}}}})}function TU(e){if(e)return EU(e)}function EU(e){for(var t in TU.prototype)e[t]=TU.prototype[t];return e}TU.prototype.on=TU.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},TU.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},TU.prototype.off=TU.prototype.removeListener=TU.prototype.removeAllListeners=TU.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks[`$`+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks[`$`+e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks[`$`+e],this},TU.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks[`$`+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,t)}return this},TU.prototype.emitReserved=TU.prototype.emit,TU.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},TU.prototype.hasListeners=function(e){return!!this.listeners(e).length};var DU=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),OU=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),kU=`arraybuffer`;function AU(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var jU=OU.setTimeout,MU=OU.clearTimeout;function NU(e,t){t.useNativeTimers?(e.setTimeoutFn=jU.bind(OU),e.clearTimeoutFn=MU.bind(OU)):(e.setTimeoutFn=OU.setTimeout.bind(OU),e.clearTimeoutFn=OU.clearTimeout.bind(OU))}var PU=1.33;function FU(e){return typeof e==`string`?IU(e):Math.ceil((e.byteLength||e.size)*PU)}function IU(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function LU(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function RU(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function zU(e){let t={},n=e.split(`&`);for(let e=0,r=n.length;e<r;e++){let r=n[e].split(`=`);t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}var BU=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},VU=class extends TU{constructor(e){super(),this.writable=!1,NU(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved(`error`,new BU(e,t,n)),this}open(){return this.readyState=`opening`,this.doOpen(),this}close(){return(this.readyState===`opening`||this.readyState===`open`)&&(this.doClose(),this.onClose()),this}send(e){this.readyState===`open`&&this.write(e)}onOpen(){this.readyState=`open`,this.writable=!0,super.emitReserved(`open`)}onData(e){let t=mU(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved(`packet`,e)}onClose(e){this.readyState=`closed`,super.emitReserved(`close`,e)}pause(e){}createUri(e,t={}){return e+`://`+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(`:`)===-1?e:`[`+e+`]`}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?`:`+this.opts.port:``}_query(e){let t=RU(e);return t.length?`?`+t:``}},HU=class extends VU{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){yU(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,vU(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=LU()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},UU=!1;try{UU=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var WU=UU;function GU(){}var KU=class extends HU{constructor(e){if(super(e),typeof location<`u`){let t=location.protocol===`https:`,n=location.port;n||=t?`443`:`80`,this.xd=typeof location<`u`&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:`POST`,data:e});n.on(`success`,t),n.on(`error`,(e,t)=>{this.onError(`xhr post error`,e,t)})}doPoll(){let e=this.request();e.on(`data`,this.onData.bind(this)),e.on(`error`,(e,t)=>{this.onError(`xhr poll error`,e,t)}),this.pollXhr=e}},qU=class e extends TU{constructor(e,t,n){super(),this.createRequest=e,NU(this,n),this._opts=n,this._method=n.method||`GET`,this._uri=t,this._data=n.data===void 0?null:n.data,this._create()}_create(){var t;let n=AU(this._opts,`agent`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`autoUnref`);n.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch{}if(this._method===`POST`)try{r.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`)}catch{}try{r.setRequestHeader(`Accept`,`*/*`)}catch{}(t=this._opts.cookieJar)==null||t.addCookies(r),`withCredentials`in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;r.readyState===3&&((e=this._opts.cookieJar)==null||e.parseCookies(r.getResponseHeader(`set-cookie`))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status==`number`?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}typeof document<`u`&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved(`error`,e,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(this._xhr===void 0||this._xhr===null)){if(this._xhr.onreadystatechange=GU,t)try{this._xhr.abort()}catch{}typeof document<`u`&&delete e.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved(`data`,e),this.emitReserved(`success`),this._cleanup())}abort(){this._cleanup()}};if(qU.requestsCount=0,qU.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,JU);else if(typeof addEventListener==`function`){let e=`onpagehide`in OU?`pagehide`:`unload`;addEventListener(e,JU,!1)}}function JU(){for(let e in qU.requests)qU.requests.hasOwnProperty(e)&&qU.requests[e].abort()}var YU=(function(){let e=ZU({xdomain:!1});return e&&e.responseType!==null})(),XU=class extends KU{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=YU&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new qU(ZU,this.uri(),e)}};function ZU(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||WU))return new XMLHttpRequest}catch{}if(!t)try{return new OU[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var QU=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,$U=class extends VU{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=QU?{}:AU(this.opts,`agent`,`perMessageDeflate`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`localAddress`,`protocolVersion`,`origin`,`maxPayload`,`family`,`checkServerIdentity`);this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved(`error`,e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:`websocket connection closed`,context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError(`websocket error`,e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;aU(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&DU(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){this.ws!==void 0&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?`wss`:`ws`,t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=LU()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},eW=OU.WebSocket||OU.MozWebSocket,tW={websocket:class extends $U{createSocket(e,t,n){return QU?new eW(e,t,n):t?new eW(e,t):new eW(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends VU{get name(){return`webtransport`}doOpen(){try{this._transport=new WebTransport(this.createUri(`https`),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved(`error`,e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError(`webtransport error`,e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=wU(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=bU();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&DU(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:XU},nW=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,rW=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function iW(e){if(e.length>8e3)throw`URI too long`;let t=e,n=e.indexOf(`[`),r=e.indexOf(`]`);n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,`;`)+e.substring(r,e.length));let i=nW.exec(e||``),a={},o=14;for(;o--;)a[rW[o]]=i[o]||``;return n!=-1&&r!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,`:`),a.authority=a.authority.replace(`[`,``).replace(`]`,``).replace(/;/g,`:`),a.ipv6uri=!0),a.pathNames=aW(a,a.path),a.queryKey=oW(a,a.query),a}function aW(e,t){let n=t.replace(/\/{2,9}/g,`/`).split(`/`);return(t.slice(0,1)==`/`||t.length===0)&&n.splice(0,1),t.slice(-1)==`/`&&n.splice(n.length-1,1),n}function oW(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var sW=typeof addEventListener==`function`&&typeof removeEventListener==`function`,cW=[];sW&&addEventListener(`offline`,()=>{cW.forEach(e=>e())},!1);var lW=class e extends TU{constructor(e,t){if(super(),this.binaryType=kU,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e==`object`&&(t=e,e=null),e){let n=iW(e);t.hostname=n.host,t.secure=n.protocol===`https`||n.protocol===`wss`,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=iW(t.host).host);NU(this,t),this.secure=t.secure==null?typeof location<`u`&&location.protocol===`https:`:t.secure,t.hostname&&!t.port&&(t.port=this.secure?`443`:`80`),this.hostname=t.hostname||(typeof location<`u`?location.hostname:`localhost`),this.port=t.port||(typeof location<`u`&&location.port?location.port:this.secure?`443`:`80`),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:`/engine.io`,agent:!1,withCredentials:!1,upgrade:!0,timestampParam:`t`,rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,``)+(this.opts.addTrailingSlash?`/`:``),typeof this.opts.query==`string`&&(this.opts.query=zU(this.opts.query)),sW&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener(`beforeunload`,this._beforeunloadEventListener,!1)),this.hostname!==`localhost`&&(this._offlineEventListener=()=>{this._onClose(`transport close`,{description:`network connection lost`})},cW.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved(`error`,`No transports available`)},0);return}let t=this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&this.transports.indexOf(`websocket`)!==-1?`websocket`:this.transports[0];this.readyState=`opening`;let n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on(`drain`,this._onDrain.bind(this)).on(`packet`,this._onPacket.bind(this)).on(`error`,this._onError.bind(this)).on(`close`,e=>this._onClose(`transport close`,e))}onOpen(){this.readyState=`open`,e.priorWebsocketSuccess=this.transport.name===`websocket`,this.emitReserved(`open`),this.flush()}_onPacket(e){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`)switch(this.emitReserved(`packet`,e),this.emitReserved(`heartbeat`),e.type){case`open`:this.onHandshake(JSON.parse(e.data));break;case`ping`:this._sendPacket(`pong`),this.emitReserved(`ping`),this.emitReserved(`pong`),this._resetPingTimeout();break;case`error`:let t=Error(`server error`);t.code=e.data,this._onError(t);break;case`message`:this.emitReserved(`data`,e.data),this.emitReserved(`message`,e.data);break}}onHandshake(e){this.emitReserved(`handshake`,e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!==`closed`&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose(`ping timeout`)},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved(`drain`):this.flush()}flush(){if(this.readyState!==`closed`&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved(`flush`)}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name===`polling`&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+=FU(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,DU(()=>{this._onClose(`ping timeout`)},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket(`message`,e,t,n),this}send(e,t,n){return this._sendPacket(`message`,e,t,n),this}_sendPacket(e,t,n,r){if(typeof t==`function`&&(r=t,t=void 0),typeof n==`function`&&(r=n,n=null),this.readyState===`closing`||this.readyState===`closed`)return;n||={},n.compress=!1!==n.compress;let i={type:e,data:t,options:n};this.emitReserved(`packetCreate`,i),this.writeBuffer.push(i),r&&this.once(`flush`,r),this.flush()}close(){let e=()=>{this._onClose(`forced close`),this.transport.close()},t=()=>{this.off(`upgrade`,t),this.off(`upgradeError`,t),e()},n=()=>{this.once(`upgrade`,t),this.once(`upgradeError`,t)};return(this.readyState===`opening`||this.readyState===`open`)&&(this.readyState=`closing`,this.writeBuffer.length?this.once(`drain`,()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(t){if(e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState===`opening`)return this.transports.shift(),this._open();this.emitReserved(`error`,t),this._onClose(`transport error`,t)}_onClose(e,t){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners(`close`),this.transport.close(),this.transport.removeAllListeners(),sW&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=cW.indexOf(this._offlineEventListener);e!==-1&&cW.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};lW.protocol=4;var uW=class extends lW{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState===`open`&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;lW.priorWebsocketSuccess=!1;let r=()=>{n||(t.send([{type:`ping`,data:`probe`}]),t.once(`packet`,e=>{if(!n)if(e.type===`pong`&&e.data===`probe`){if(this.upgrading=!0,this.emitReserved(`upgrading`,t),!t)return;lW.priorWebsocketSuccess=t.name===`websocket`,this.transport.pause(()=>{n||this.readyState!==`closed`&&(l(),this.setTransport(t),t.send([{type:`upgrade`}]),this.emitReserved(`upgrade`,t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error(`probe error`);e.transport=t.name,this.emitReserved(`upgradeError`,e)}}))};function i(){n||(n=!0,l(),t.close(),t=null)}let a=e=>{let n=Error(`probe error: `+e);n.transport=t.name,i(),this.emitReserved(`upgradeError`,n)};function o(){a(`transport closed`)}function s(){a(`socket closed`)}function c(e){t&&e.name!==t.name&&i()}let l=()=>{t.removeListener(`open`,r),t.removeListener(`error`,a),t.removeListener(`close`,o),this.off(`close`,s),this.off(`upgrading`,c)};t.once(`open`,r),t.once(`error`,a),t.once(`close`,o),this.once(`close`,s),this.once(`upgrading`,c),this._upgrades.indexOf(`webtransport`)!==-1&&e!==`webtransport`?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}},dW=class extends uW{constructor(e,t={}){let n=typeof e==`object`?e:t;(!n.transports||n.transports&&typeof n.transports[0]==`string`)&&(n.transports=(n.transports||[`polling`,`websocket`,`webtransport`]).map(e=>tW[e]).filter(e=>!!e)),super(e,n)}};dW.protocol;function fW(e,t=``,n){let r=e;n||=typeof location<`u`&&location,e??=n.protocol+`//`+n.host,typeof e==`string`&&(e.charAt(0)===`/`&&(e=e.charAt(1)===`/`?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=n===void 0?`https://`+e:n.protocol+`//`+e),r=iW(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port=`80`:/^(http|ws)s$/.test(r.protocol)&&(r.port=`443`)),r.path=r.path||`/`;let i=r.host.indexOf(`:`)===-1?r.host:`[`+r.host+`]`;return r.id=r.protocol+`://`+i+`:`+r.port+t,r.href=r.protocol+`://`+i+(n&&n.port===r.port?``:`:`+r.port),r}var pW=typeof ArrayBuffer==`function`,mW=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,hW=Object.prototype.toString,gW=typeof Blob==`function`||typeof Blob<`u`&&hW.call(Blob)===`[object BlobConstructor]`,_W=typeof File==`function`||typeof File<`u`&&hW.call(File)===`[object FileConstructor]`;function vW(e){return pW&&(e instanceof ArrayBuffer||mW(e))||gW&&e instanceof Blob||_W&&e instanceof File}function yW(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(yW(e[t]))return!0;return!1}if(vW(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return yW(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&yW(e[t]))return!0;return!1}function bW(e){let t=[],n=e.data,r=e;return r.data=xW(n,t),r.attachments=t.length,{packet:r,buffers:t}}function xW(e,t){if(!e)return e;if(vW(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=xW(e[r],t);return n}else if(typeof e==`object`&&!(e instanceof Date)){let n={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=xW(e[r],t));return n}return e}function SW(e,t){return e.data=CW(e.data,t),delete e.attachments,e}function CW(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num==`number`&&e.num>=0&&e.num<t.length)return t[e.num];throw Error(`illegal attachments`)}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=CW(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=CW(e[n],t));return e}var wW=r({Decoder:()=>OW,Encoder:()=>DW,PacketType:()=>EW,isPacketValid:()=>FW,protocol:()=>5}),TW=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],EW;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(EW||={});var DW=class{constructor(e){this.replacer=e}encode(e){return(e.type===EW.EVENT||e.type===EW.ACK)&&yW(e)?this.encodeAsBinary({type:e.type===EW.EVENT?EW.BINARY_EVENT:EW.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===EW.BINARY_EVENT||e.type===EW.BINARY_ACK)&&(t+=e.attachments+`-`),e.nsp&&e.nsp!==`/`&&(t+=e.nsp+`,`),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=bW(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},OW=class e extends TU{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e==`function`?{reviver:e}:e)}add(e){let t;if(typeof e==`string`){if(this.reconstructor)throw Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===EW.BINARY_EVENT;n||t.type===EW.BINARY_ACK?(t.type=n?EW.EVENT:EW.ACK,this.reconstructor=new kW(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(vW(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`);else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(EW[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===EW.BINARY_EVENT||r.type===EW.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!jW(a)||a<0)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&!(t.charAt(n)===`,`||n===t.length););r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case EW.CONNECT:return NW(t);case EW.DISCONNECT:return t===void 0;case EW.CONNECT_ERROR:return typeof t==`string`||NW(t);case EW.EVENT:case EW.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&TW.indexOf(t[0])===-1);case EW.ACK:case EW.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},kW=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=SW(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function AW(e){return typeof e==`string`}var jW=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function MW(e){return e===void 0||jW(e)}function NW(e){return Object.prototype.toString.call(e)===`[object Object]`}function PW(e,t){switch(e){case EW.CONNECT:return t===void 0||NW(t);case EW.DISCONNECT:return t===void 0;case EW.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&TW.indexOf(t[0])===-1);case EW.ACK:return Array.isArray(t);case EW.CONNECT_ERROR:return typeof t==`string`||NW(t);default:return!1}}function FW(e){return AW(e.nsp)&&MW(e.id)&&PW(e.type,e.data)}function IW(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var LW=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),RW=class extends TU{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[IW(e,`open`,this.onopen.bind(this)),IW(e,`packet`,this.onpacket.bind(this)),IW(e,`error`,this.onerror.bind(this)),IW(e,`close`,this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState===`open`&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift(`message`),this.emit.apply(this,e),this}emit(e,...t){if(LW.hasOwnProperty(e))throw Error(`"`+e.toString()+`" is a reserved event name`);if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:EW.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth==`function`?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:EW.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved(`connect_error`,e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved(`disconnect`,e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case EW.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,Error(`It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)`));break;case EW.EVENT:case EW.BINARY_EVENT:this.onevent(e);break;case EW.ACK:case EW.BINARY_ACK:this.onack(e);break;case EW.DISCONNECT:this.ondisconnect();break;case EW.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]==`string`&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:EW.ACK,id:e,data:r}))}}onack(e){let t=this.acks[e.id];typeof t==`function`&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved(`connect`)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose(`io server disconnect`)}destroy(){this.subs&&=(this.subs.forEach(e=>e()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:EW.DISCONNECT}),this.destroy(),this.connected&&this.onclose(`io client disconnect`),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function zW(e){e||={},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}zW.prototype.duration=function(){var e=this.ms*this.factor**+ this.attempts++;if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0},zW.prototype.reset=function(){this.attempts=0},zW.prototype.setMin=function(e){this.ms=e},zW.prototype.setMax=function(e){this.max=e},zW.prototype.setJitter=function(e){this.jitter=e};var BW=class extends TU{constructor(e,t){super(),this.nsps={},this.subs=[],e&&typeof e==`object`&&(t=e,e=void 0),t||={},t.path=t.path||`/socket.io`,this.opts=t,NU(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor??.5),this.backoff=new zW({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState=`closed`,this.uri=e;let n=t.parser||wW;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)==null||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)==null||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)==null||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf(`open`))return this;this.engine=new dW(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=IW(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=IW(t,`error`,i);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(Error(`timeout`)),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState=`open`,this.emitReserved(`open`);let e=this.engine;this.subs.push(IW(e,`ping`,this.onping.bind(this)),IW(e,`data`,this.ondata.bind(this)),IW(e,`error`,this.onerror.bind(this)),IW(e,`close`,this.onclose.bind(this)),IW(this.decoder,`decoded`,this.ondecoded.bind(this)))}onping(){this.emitReserved(`ping`)}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose(`parse error`,e)}}ondecoded(e){DU(()=>{this.emitReserved(`packet`,e)},this.setTimeoutFn)}onerror(e){this.emitReserved(`error`,e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new RW(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let e of t)if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose(`forced close`)}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)==null||n.close(),this.backoff.reset(),this._readyState=`closed`,this.emitReserved(`close`,e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(`reconnect_failed`),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved(`reconnect_attempt`,e.backoff.attempts),!e.skipReconnect&&e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved(`reconnect_error`,t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(`reconnect`,e)}},VW={};function HW(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=fW(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=VW[i]&&a in VW[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new BW(r,t):(VW[i]||(VW[i]=new BW(r,t)),c=VW[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(HW,{Manager:BW,Socket:RW,io:HW,connect:HW});var UW=((e=M)=>HW(e))(),WW=({label:e,onClick:t,children:n})=>(0,Z.jsx)(q,{type:`button`,"aria-label":e,onClick:t,variant:`outline`,size:`icon-sm`,className:`bg-secondary/60`,children:n}),GW=({exitCode:e,signal:t})=>t>0?`[archon] Shell exited with signal ${t}`:`[archon] Shell exited with code ${e}`,KW=({createSession:e,isExpanded:t,isVisible:n,onClose:r,onToggleExpanded:i,className:a=``,ariaLabel:o=`Terminal`,title:s=`Terminal`,closeLabel:c=`Close terminal`,headerMeta:l})=>{let u=(0,Y.useRef)(null),d=(0,Y.useRef)(null),f=(0,Y.useRef)(null),p=(0,Y.useRef)(null),m=(0,Y.useRef)(e),h=(0,Y.useRef)(!1),[g,_]=(0,Y.useState)(null),[v,y]=(0,Y.useState)(!0);return(0,Y.useEffect)(()=>{m.current=e},[e]),(0,Y.useEffect)(()=>{if(!u.current)return;let e=new QH({cursorBlink:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`,fontSize:13,theme:{background:`#0b0d14`,foreground:`#d8deef`,cursor:`#c4b5fd`}}),t=new EP,n=null,r=!1;e.loadAddon(t),e.open(u.current),d.current=e,f.current=t;let i=()=>{let e=p.current;!e||h.current||(h.current=!0,wT(e))};window.addEventListener(`pagehide`,i),window.addEventListener(`beforeunload`,i);let a=()=>{p.current&&UW.emit(`terminal:resize`,{sessionId:p.current,cols:e.cols,rows:e.rows})},o=()=>{!u.current||r||(t.fit(),a())},s=t=>{t.sessionId===p.current&&(y(!1),window.setTimeout(()=>{o(),e.focus()},0))},c=t=>{t.sessionId===p.current&&(y(!1),e.write(t.data))},l=t=>{t.sessionId===p.current&&(e.writeln(``),e.writeln(GW(t)))},g=t=>{t.sessionId&&t.sessionId!==p.current||(y(!1),_(t.message),e.writeln(``),e.writeln(`[archon] ${t.message}`))};UW.on(`terminal:ready`,s),UW.on(`terminal:data`,c),UW.on(`terminal:exit`,l),UW.on(`terminal:error`,g);let v=e.onData(e=>{p.current&&UW.emit(`terminal:input`,{sessionId:p.current,input:e})});return typeof ResizeObserver==`function`&&(n=new ResizeObserver(()=>{o()}),n.observe(u.current)),window.setTimeout(()=>{o()},0),m.current().then(e=>{r||(p.current=e.session_id,UW.emit(`terminal:join`,{sessionId:e.session_id}))}).catch(t=>{if(r)return;y(!1);let n=t instanceof Error?t.message:`Unable to open the terminal right now.`;_(n),e.writeln(``),e.writeln(`[archon] ${n}`)}),()=>{r=!0,window.removeEventListener(`pagehide`,i),window.removeEventListener(`beforeunload`,i),p.current&&(h.current||UW.emit(`terminal:destroy`,{sessionId:p.current})),n?.disconnect(),v.dispose(),UW.off(`terminal:ready`,s),UW.off(`terminal:data`,c),UW.off(`terminal:exit`,l),UW.off(`terminal:error`,g),e.dispose(),d.current=null,f.current=null,p.current=null}},[]),(0,Y.useEffect)(()=>{if(!n)return;let e=window.setTimeout(()=>{f.current?.fit(),d.current&&p.current&&(UW.emit(`terminal:resize`,{sessionId:p.current,cols:d.current.cols,rows:d.current.rows}),d.current.focus())},0);return()=>{window.clearTimeout(e)}},[t,n]),(0,Z.jsxs)(gu,{"aria-label":o,"data-terminal-pane":`true`,className:`flex min-h-0 flex-1 flex-col gap-0 overflow-hidden rounded-xl border-border bg-[#0c1119] ${a}`.trim(),children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-b border-border bg-card/80 px-3 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`flex h-8 w-8 items-center justify-center rounded-lg bg-primary/12 text-primary`,children:(0,Z.jsx)(Ic,{className:`h-4 w-4`})}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:s}),l&&(0,Z.jsx)(`div`,{className:`mt-1 min-w-0 text-xs text-muted-foreground`,children:l})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[v&&!g&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Opening terminal...`}),g&&(0,Z.jsx)(`span`,{className:`max-w-56 truncate text-xs text-red-300`,children:g}),(0,Z.jsx)(WW,{label:t?`Collapse terminal`:`Expand terminal`,onClick:i,children:t?(0,Z.jsx)(vf,{className:`h-4 w-4`}):(0,Z.jsx)(yf,{className:`h-4 w-4`})}),(0,Z.jsx)(WW,{label:c,onClick:r,children:(0,Z.jsx)(Ve,{className:`h-4 w-4`})})]})]}),(0,Z.jsx)(`div`,{ref:u,"data-testid":`terminal-viewport`,onClick:()=>d.current?.focus(),className:`min-h-0 flex-1 overflow-hidden bg-[#0b0d14] pb-4`})]})},qW=({actions:e,activeAction:t=null,disableWhenActive:n=!1,className:r,heading:i,headingClassName:a,actionsClassName:o,showDisabledReason:s=!1,disabledReasonClassName:c,error:l,errorClassName:u,leadingContent:d,renderAction:f})=>{if(e.length===0&&!d)return null;let p=e.find(e=>e.disabled&&e.disabledReason)?.disabledReason??null;return(0,Z.jsxs)(`div`,{className:r,children:[i&&(0,Z.jsx)(`div`,{className:a,children:i}),(0,Z.jsxs)(`div`,{className:o,children:[d,e.map(e=>{let r=t===e.id,i=e.disabled||n&&t!==null;return f({action:e,label:r?e.pendingLabel:e.label,disabled:i,title:e.disabledReason??e.title,ariaLabel:e.ariaLabel})})]}),s&&p&&(0,Z.jsx)(`p`,{className:c,children:p}),l&&(0,Z.jsx)(`p`,{className:u,children:l})]})},JW=({id:e,label:t,pendingLabel:n,ariaLabel:r=t,title:i,disabled:a=!1,disabledReason:o=null})=>({id:e,label:t,pendingLabel:n,ariaLabel:r,title:i,disabled:a,disabledReason:o}),YW=(e,t={})=>{let{isEditing:n=!1,includePlanAdvance:r=!0,hideAdvanceWhenBlocked:i=!1,hasOpenBlockers:a=!1,canRun:o=!0,canStopRun:s=!0,canPauseBuild:c=!0,canResumeBuild:l=!0,runDisabled:u=!1,runDisabledReason:d,buildLabel:f=`Build`,reviewLabel:p=`Review`}=t,m=ww(e.state),h=m?Fw(e,m):!1,g=Iw(e),_=e.bundle?.branch??e.branch,v=e.has_worktree??!!_,y=e.worktree_bundle_id!==null,b=e.state===`plan`&&e.agent_status===`running`,x=d??(e.has_run_config===!1?`No run config is available for this project.`:null),S=[];return r&&e.state===`plan`&&!e.parked_at&&S.push(JW({id:`build`,label:f,pendingLabel:`Building...`,ariaLabel:f,disabled:!h,disabledReason:g})),e.state===`build`&&!e.parked_at&&!(i&&a)&&S.push(JW({id:`review`,label:p,pendingLabel:`Starting review...`,ariaLabel:p,disabled:!h,disabledReason:g})),_&&v&&!b&&!n&&!y&&e.is_running!==!0&&o&&S.push(JW({id:`run`,label:`Run`,pendingLabel:`Starting run...`,ariaLabel:`Run`,disabled:u||!!x,disabledReason:x,title:u?x??`Stop the currently running ticket before starting another run.`:void 0})),_&&!n&&!y&&e.is_running===!0&&s&&S.push(JW({id:`stop-run`,label:`Stop Run`,pendingLabel:`Stopping run...`,ariaLabel:`Stop Run`,title:`Stop the currently running ticket.`,disabled:!1,disabledReason:null})),!n&&Dw(e)&&e.agent_status===`running`&&e.session_id&&c&&S.push(JW({id:`pause-build`,label:`Pause Build`,pendingLabel:`Pausing build...`,ariaLabel:`Pause Build`,title:`Pause the build session. You can resume it later.`,disabled:!1,disabledReason:null})),!n&&Dw(e)&&e.agent_status===`stopped`&&e.session_id&&l&&S.push(JW({id:`resume-build`,label:`Resume`,pendingLabel:`Resuming build...`,ariaLabel:`Resume`,disabled:!1,disabledReason:null})),S},XW=(e,t={})=>{let n=e.state===`plan`,r=e.bundle?.branch??e.branch,i=e.has_worktree??!!r;return{isPlan:n,hasWorktree:i,disabledReason:e.agent_status===`running`?n?`Wait for planning to finish before sending another message.`:`Wait for the current build to finish before sending a follow-up prompt.`:t.requireWorktree===!0&&!n&&!i?`Worktree not ready yet.`:null,heading:n?`Planning follow-up`:`Ticket follow-up`,description:n?`Ask the agent to refine this plan.`:`Send a follow-up prompt for this ticket.`,placeholder:n?`Ask the agent to refine this plan...`:`Send a follow-up for this ticket...`}},ZW=(e,t,n={})=>{let r=e.tool===`opencode`||n.persistPlanSettings===!0,i=r&&t.model?t.model:null,a=r&&t.model&&t.variant?t.variant:null,o=r?t.skills:[],s=e.skills??[],c=o.length!==s.length||o.some((e,t)=>e!==s[t]);return{model:i,variant:a,skills:o,shouldPersist:r&&(i!==e.model||a!==e.variant||c)}},QW=`modulepreload`,$W=function(e){return`/`+e},eG={},tG=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=$W(t,n),t in eG)return;eG[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:QW,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},nG=(0,Y.lazy)(()=>tG(()=>Promise.resolve().then(()=>fJ).then(e=>({default:e.TicketChangesModal})),void 0)),rG=(0,Y.lazy)(()=>tG(()=>import(`./TestsDialog-ditcW5bX.js`).then(e=>({default:e.TestsDialog})),__vite__mapDeps([0,1,2]))),iG=`(min-width: 1280px)`,aG=e=>typeof window>`u`||typeof window.matchMedia!=`function`?!0:window.matchMedia(e).matches,oG=e=>{let[t,n]=(0,Y.useState)(()=>aG(e));return(0,Y.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let t=window.matchMedia(e),r=()=>{n(t.matches)};return r(),t.addEventListener(`change`,r),()=>{t.removeEventListener(`change`,r)}},[e]),t},sG=({onClose:e})=>{let{t}=X(`common`);return(0,Z.jsx)(pu,{onClose:e,overlayClassName:`z-[70] bg-black/30 p-[5vh]`,panelClassName:`flex h-full w-full max-w-none items-center justify-center rounded-2xl border border-border bg-card p-6 shadow-2xl`,children:(0,Z.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:t(`ticketModal.loadingDiff`)})})},cG=({ariaLabel:e,title:t,closeAriaLabel:n,className:r,showTopSpacer:i=!0,description:a,onClose:o,...s})=>(0,Z.jsxs)(`aside`,{className:`min-h-0 flex flex-col gap-3 overflow-hidden${r?` ${r}`:``}`,"aria-label":e,children:[i?(0,Z.jsx)(`div`,{"aria-hidden":`true`,className:`h-9 shrink-0`}):null,(0,Z.jsx)(WN,{...s,header:({showThinkingControl:e})=>(0,Z.jsxs)(`div`,{className:`flex w-full items-center justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,Z.jsx)(`h3`,{className:`text-sm font-semibold text-foreground`,children:t}),e]}),a?(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:a}):null]}),(0,Z.jsx)(q,{type:`button`,variant:`ghost`,size:`icon`,"aria-label":n,onClick:o,children:(0,Z.jsx)(Ve,{className:`h-4 w-4`})})]})})]}),lG=(e,t)=>e?t.find(t=>t.id===e)?.label??e:null,uG=({ticket:e,allTickets:t=[],dependencies:n=[],bundles:r=[],projectTestCommands:i=[],showModelSelector:a=!1,availableModels:o=[],availableSkills:s=[],projectBranchState:c=null,projectMemoryEnabled:l=!1,runDisabled:u=!1,runDisabledReason:d,onClose:f,onCreateBundle:p,onDeleteBundle:m,onRefreshBundles:h,onUpdate:g,onDeleteDependency:_,onAdvance:v,onBuildChain:y,onRun:b,onOpenIde:x,onStop:S,onStopBuild:C,onStopBuildChain:w,onResumeBuild:T,onFollowUp:E,onRequestTicketRefresh:D,onProjectMemorySuggestionsChanged:O})=>{let{t:k}=X(`common`),[A,j]=(0,Y.useState)(null),[M,N]=(0,Y.useState)(!1),[P,F]=(0,Y.useState)(!1),[I,L]=(0,Y.useState)(!1),[R,z]=(0,Y.useState)(!1),[ee,te]=(0,Y.useState)(!1),[ne,re]=(0,Y.useState)(!1),[B,ie]=(0,Y.useState)(``),[V,H]=(0,Y.useState)(!1),[ae,oe]=(0,Y.useState)(!1),[se,ce]=(0,Y.useState)(!1),[le,ue]=(0,Y.useState)(0),[de,fe]=(0,Y.useState)(!1),[pe,me]=(0,Y.useState)(!1),[W,he]=(0,Y.useState)(null),G=A??e,[ge,_e]=(0,Y.useState)(G.model??``),[ve,ye]=(0,Y.useState)(G.variant??``),[be,xe]=(0,Y.useState)(G.skills??[]),[K,Se]=(0,Y.useState)(()=>lG(G.model,o)??`Agent`),Ce=(0,Y.useRef)(G.id),we=(0,Y.useRef)(null),Te=(0,Y.useRef)(null),Ee=(0,Y.useRef)(!1),De=(0,Y.useRef)(G.id),Oe=(0,Y.useRef)(G.build_completed_at),ke=oG(iG),[Ae,je]=(0,Y.useState)(!1),[Me,Ne]=(0,Y.useState)({model:G.model,variant:G.variant,skills:G.skills??[]}),Pe=G.state===`plan`,Fe=Tw(G.state),Ie=G.worktree_bundle_id!==null,Le=Pe&&G.agent_status===`running`,Re=Pe&&G.agent_status===`error`,ze=Pe&&!Le||M,Be=async e=>{let t=await Zt(G.id,G.project_id,e);return j(t),g?.(t),h&&await h(),t},Ve=async e=>{try{await Be(e),f()}catch(e){Q.error(e instanceof Error?e.message:`Unable to update the ticket right now.`,{id:`ticket-save-error`})}},He=async e=>{try{if(await Be(e),!v){f();return}await v(),f()}catch(e){Q.error(e instanceof Error?e.message:`Unable to update the ticket right now.`,{id:`ticket-save-error`})}},Ue=async()=>{!v||it?.disabled||(await v(),f())},We=e=>{if(e===`review`){Ue();return}if(e===`run`){b?.();return}if(e===`stop-run`){S?.();return}if(e===`pause-build`){C?.();return}e===`resume-build`&&T?.()},Ge=async e=>{try{if(await Be(e),!y){f();return}await y(),f()}catch(e){Q.error(e instanceof Error?e.message:`Unable to update the ticket right now.`,{id:`ticket-save-error`})}},Ke=Pe?G.planning_session_id:G.session_id,qe=Ke?Ke.startsWith(`ses_`)?`opencode --session ${Ke}`:`claude --resume ${Ke}`:null,Je=G.bundle?.branch??G.branch,Ye=G.has_worktree??!!Je,Xe=`Stop Build Chain`,Ze=new Map(t.map(e=>[e.id,e])),Qe=n.filter(e=>e.blocker_ticket_id===G.id),$e=n.filter(e=>e.dependent_ticket_id===G.id),et=eT(G,Ze,n),J=et.pendingBuildChainOrder.length>0?`Will build in order: ${et.pendingBuildChainOrder.map(e=>e.title).join(` -> `)}`:`All tickets in this chain have already finished build.`,tt=et.skippedBuildChainCount>0?`Skips ${et.skippedBuildChainCount} ticket${et.skippedBuildChainCount===1?``:`s`} that already finished build.`:null,nt=et.hasOpenBlockers,rt=YW(G,{isEditing:ze,includePlanAdvance:!1,hideAdvanceWhenBlocked:!0,hasOpenBlockers:nt,canRun:!!b,canStopRun:!!S,canPauseBuild:!!C,canResumeBuild:!!T,runDisabled:u,runDisabledReason:d,reviewLabel:`Review Bundle`}),it=rt.find(e=>e.id===`review`)??null,at=Aw(G),ot=G.build_chain?.active_ticket_id?`Currently building ${Ze.get(G.build_chain.active_ticket_id)?.title??`Unknown ticket`}.`:`Build chain is active.`,st=G.build_chain&&G.build_chain.queued_ticket_ids.length>0?`Queued next: ${G.build_chain.queued_ticket_ids.map(e=>Ze.get(e)?.title??`Unknown ticket`).join(` -> `)}`:`No additional tickets are queued after the current build.`,ct=Pe&&!!v&&!et.hasOpenBlockers,lt=Pe&&!!y&&et.canStartBuildChain,ut=!!G.project_id&&!Pe&&!Ie,dt=Pe,ft=Ie&&!Pe,pt=!!G.project_id&&!!Je&&Ye&&!ze&&!Le&&!Ie,mt=!!G.project_id&&Ye&&!ze&&!Le&&!!x&&!Ie,ht=!!G.project_id&&i.length>0&&Ye,gt=ut&&!R,_t=k(`workspaceControls.openTerminalAriaLabel`),vt=ut&&ne,yt=B.trim(),bt=!ze&&!Le&&G.state!==`plan`&&Ye&&!!E,xt=dt&&ae,St=ft&&se,Ct=(G.planning_context?.open_questions.length??0)>0,wt=bt&&a&&G.tool===`opencode`,Tt=k(`ticketModal.discardUnsavedDescription`),Et=o.find(e=>e.id===ge)??null,Dt=G.agent_status===`running`,Ot=uT(G,{allTickets:t,preferBundleReviewStatus:!0}),kt=G.skills??[],At=XW(G),jt=Dt?At.disabledReason??void 0:void 0,Mt=Le?At.disabledReason??void 0:void 0,Nt=[...Le?[]:[{label:`Worktree`,value:Je??``}],{label:`Session`,value:qe??``},...Le?[{label:G.bundle?.kind===`project_root`?`Project root branch`:`Bundle`,value:(G.bundle?.kind,G.bundle?Dl(G.bundle):``)}]:Pe?[{label:`Bundle`,value:G.bundle?Dl(G.bundle):``},{label:`Model`,value:G.model??``},{label:`Variant`,value:G.variant??``},{label:`Skills`,value:kt.length>0?`${kt.length} skill${kt.length===1?``:`s`}`:``},{label:`Initiative`,value:G.planning_context?.initiative_prompt??``}]:[]],Pt=Le?{model:G.model??``,variant:G.variant??``,skills:kt}:null,Ft=dt&&ae,It=ft&&se,Lt=(Ft||It)&&!ke,Rt=Ft&&!Lt,zt=Rt||It&&!Lt,Bt=Pe&&(Ft||!ke),Vt=R?`flex h-[92vh] w-[96vw] max-w-7xl flex-col gap-3 overflow-hidden rounded-2xl border border-border bg-card p-4 shadow-2xl sm:p-5 lg:p-6`:zt?`flex h-[92vh] w-[98vw] max-w-[100rem] flex-col gap-3 overflow-visible rounded-2xl border border-border bg-card p-4 shadow-2xl sm:p-5 lg:p-6`:Lt?`flex h-[92vh] w-[98vw] max-w-6xl flex-col gap-3 overflow-hidden rounded-2xl border border-border bg-card p-4 shadow-2xl sm:p-5 lg:p-6`:`flex h-[92vh] w-[96vw] max-w-6xl flex-col gap-3 overflow-visible rounded-2xl border border-border bg-card p-4 shadow-2xl sm:p-5 lg:p-6`,Ht=R&&!ee?`grid min-h-0 flex-1 grid-cols-1 gap-3 lg:grid-cols-2`:zt?`grid min-h-0 flex-1 grid-cols-1 gap-3 xl:grid-cols-[minmax(0,1fr)_minmax(30rem,1fr)]`:`flex min-h-0 flex-1 flex-col`,Ut=()=>{re(!0),z(e=>(e&&te(!1),!e))},Wt=()=>{z(!1),te(!1),re(!1),D?.(G.id)},Gt=()=>{me(!1),he(null)},Kt=()=>{me(!1),W===`cancel_edit`&&!Pe?N(!1):f(),he(null)},qt=()=>{if(!ze){f();return}if(!de){f();return}he(`close_modal`),me(!0)},Jt=()=>{if(Pe){qt();return}if(!de){N(!1);return}he(`cancel_edit`),me(!0)};(0,Y.useEffect)(()=>{j(t=>!t||t.id!==e.id||e.updated_at>=t.updated_at?null:t)},[e]),(0,Y.useEffect)(()=>{if(De.current!==G.id){De.current=G.id,Oe.current=G.build_completed_at;return}if(Oe.current===G.build_completed_at)return;let e=Oe.current;Oe.current=G.build_completed_at,G.build_completed_at&&G.build_completed_at!==e&&ue(e=>e+1)},[G.build_completed_at,G.id]),(0,Y.useEffect)(()=>{_e(G.model??``),ye(G.variant??``),xe(G.skills??[])},[G.model,G.skills,G.variant]),(0,Y.useEffect)(()=>{Ce.current!==G.id&&(Ce.current=G.id,Se(lG(G.model,o)??`Agent`))},[o,G.id,G.model]),(0,Y.useEffect)(()=>{let e=lG(G.model,o);e&&Se(e)},[o,G.model]),(0,Y.useEffect)(()=>{Ne({model:G.model,variant:G.variant,skills:G.skills??[]})},[G.id,G.model,G.skills,G.variant]),(0,Y.useEffect)(()=>{ze||(fe(!1),me(!1),he(null))},[ze]),(0,Y.useEffect)(()=>{de||(me(!1),he(null))},[de]),(0,Y.useEffect)(()=>{if(!Pe){we.current=null,Ee.current=!1;return}let e=we.current!==G.id,t=!Ee.current&&Ct;(e&&Ct||t)&&oe(!0),we.current=G.id,Ee.current=Ct},[Ct,Pe,G.id]),(0,Y.useEffect)(()=>{if(!ft){Te.current=null;return}Te.current!==G.id&&ce(!1),Te.current=G.id},[ft,G.id]);let Yt=async(e,t,n)=>{je(!0);try{let r=await Zt(G.id,G.project_id,{model:e.trim()||null,variant:t.trim()||null,skills:n});j(r),g?.(r)}catch(e){_e(G.model??``),ye(G.variant??``),xe(G.skills??[]),Q.error(e instanceof Error?e.message:`Unable to update the ticket right now.`,{id:`ticket-save-error`})}finally{je(!1)}},Xt=e=>{let t=(o.find(t=>t.id===e)??null)?.variants.includes(ve)?ve:``;_e(e),ye(t),Yt(e,t,be)},Qt=e=>{ye(e),Yt(ge,e,be)},$t=e=>{xe(e),Yt(ge,ve,e)},en=async()=>{if(!(!E||V||Dt||!yt)){H(!0);try{await E(yt),ie(``)}finally{H(!1)}}},tn=async()=>{if(!(V||Le||!yt||!xt)){H(!0);try{let e=ZW(G,Me,{persistPlanSettings:!0});if(e.shouldPersist){let t=await Zt(G.id,G.project_id,{model:e.model,variant:e.variant,skills:e.skills});j(t),g?.(t)}let t=await Sn(G.id,G.project_id,yt);j(t),g?.(t),ie(``)}finally{H(!1)}}},nn=(G.messages??[]).filter(PT).map(e=>e.role===`assistant`?{...e,displayTitle:K}:e.kind===`follow_up`?{...e,displayTitle:k(`chatView.user.you`)}:e),rn=(G.messages??[]).filter(e=>(e.kind===`planning_follow_up`||e.kind===`planning_response`)&&PT(e)).map(e=>e.role===`assistant`?{...e,displayTitle:K}:e.kind===`planning_follow_up`?{...e,displayTitle:k(`chatView.user.you`)}:e),an=Ft?(0,Z.jsx)(cG,{ariaLabel:k(`ticketModal.planningChatAriaLabel`),title:k(`ticketModal.planningChatTitle`),closeAriaLabel:k(`ticketModal.closePlanningChatAriaLabel`),className:Lt?`absolute inset-x-4 bottom-4 top-[4.25rem] z-30 rounded-2xl border border-border bg-card shadow-2xl sm:inset-x-auto sm:right-5 sm:w-[min(34rem,calc(100%-2.5rem))] lg:right-6`:void 0,showTopSpacer:!Lt,description:Ct?(0,Z.jsx)(`p`,{children:k(`ticketModal.planningOpenQuestions`,{count:G.planning_context?.open_questions.length??0})}):void 0,projectId:G.project_id,followUpTicketId:null,messages:rn,internalLog:G.agent_log??null,currentThinkingMessageId:G.agent_message_id??null,previousThinkingLog:G.previous_agent_log??null,previousThinkingMessageId:G.previous_agent_message_id??null,streamingResponse:G.streaming_response??null,isRunning:G.agent_status===`running`,canShowComposer:xt,pendingAgentTitle:K,composerTheme:Fe,followUpPlaceholder:k(`ticketModal.planningFollowUpPlaceholder`),emptyStateText:null,autoFocusComposer:ae,followUpPrompt:B,isSendingFollowUp:V,followUpDisabledReason:Mt,onFollowUpPromptChange:ie,onFollowUpKeyDown:e=>{e.key!==`Enter`||e.shiftKey||Le||V||(e.preventDefault(),tn())},onFollowUpSubmit:()=>{tn()},onClose:()=>{oe(!1)}}):It?(0,Z.jsx)(cG,{ariaLabel:k(`ticketModal.ticketChatAriaLabel`),title:k(`ticketModal.ticketChatTitle`),closeAriaLabel:k(`ticketModal.closeTicketChatAriaLabel`),className:Lt?`absolute inset-x-4 bottom-4 top-[4.25rem] z-30 rounded-2xl border border-border bg-card shadow-2xl sm:inset-x-auto sm:right-5 sm:w-[min(34rem,calc(100%-2.5rem))] lg:right-6`:void 0,showTopSpacer:!Lt,projectId:G.project_id,followUpTicketId:G.id,messages:nn,internalLog:G.agent_log??null,currentThinkingMessageId:G.agent_message_id??null,previousThinkingLog:G.previous_agent_log??null,previousThinkingMessageId:G.previous_agent_message_id??null,streamingResponse:G.streaming_response??null,isRunning:G.agent_status===`running`,canShowComposer:St,pendingAgentTitle:K,composerTheme:Fe,autoFocusComposer:se,followUpPrompt:B,isSendingFollowUp:V,followUpDisabledReason:jt,followUpComposerControls:wt?(0,Z.jsx)(CP,{model:ge,variant:ve,skills:be,showModelSelector:!0,showSkillsSelector:!0,availableModels:o,availableSkills:s,selectedModel:Et,onModelChange:Xt,onVariantChange:Qt,onSkillsChange:$t,modelSelectId:`ticket-follow-up-model`,variantSelectId:`ticket-follow-up-variant`,skillsSelectId:`ticket-follow-up-skills`,disabled:Ae}):void 0,onFollowUpPromptChange:ie,onFollowUpKeyDown:e=>{e.key!==`Enter`||e.shiftKey||Dt||V||(e.preventDefault(),en())},onFollowUpSubmit:()=>{en()},onClose:()=>{ce(!1)}}):null;return(0,Z.jsx)(pu,{onClose:qt,overlayClassName:`bg-black/60`,panelClassName:Vt,renderContent:({closeButton:e})=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`absolute right-4 top-4 z-10 flex items-center gap-2 sm:right-5 sm:top-5 lg:right-6 lg:top-6`,children:[pt&&G.diff_stats&&(0,Z.jsx)(kc,{stats:G.diff_stats,showFiles:!0,className:`text-xs`}),pt&&(0,Z.jsxs)(q,{type:`button`,"aria-label":k(`workspaceControls.changes`),onClick:()=>{D?.(G.id),F(!0)},variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(jc,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:k(`workspaceControls.changes`)})]}),ht&&(0,Z.jsxs)(q,{type:`button`,"aria-label":k(`workspaceControls.tests`),onClick:()=>{L(!0)},variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(Ac,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:k(`workspaceControls.tests`)})]}),mt&&(0,Z.jsxs)(q,{type:`button`,"aria-label":k(`workspaceControls.openIde`),onClick:()=>{x?.()},variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(Mc,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:k(`workspaceControls.openIde`)})]}),gt&&(0,Z.jsxs)(q,{type:`button`,"aria-label":_t,"aria-pressed":R,onClick:Ut,variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(Ic,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:k(`workspaceControls.terminal`)})]}),(dt||ft)&&(0,Z.jsxs)(q,{type:`button`,"aria-label":k(`workspaceControls.chat`),"aria-pressed":Pe?ae:se,onClick:()=>{if(Pe){oe(e=>!e);return}ce(e=>!e)},variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(nm,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:k(`workspaceControls.chat`)})]}),e]}),(0,Z.jsxs)(`div`,{"data-testid":`ticket-modal-layout`,"data-terminal-mode":R?ee?`expanded`:`split`:`closed`,"data-side-chat-mode":zt?`inline`:Lt?`overlay`:`closed`,className:Ht,children:[(0,Z.jsxs)(`div`,{className:`min-h-0 flex flex-1 flex-col gap-3 overflow-hidden`,children:[ze?(0,Z.jsxs)(Z.Fragment,{children:[Re&&G.agent_log&&(0,Z.jsxs)(`div`,{className:`rounded-lg border border-red-500/40 bg-destructive/15 px-3 py-2 text-xs text-red-300`,children:[(0,Z.jsx)(`span`,{className:`font-semibold`,children:k(`ticketModal.planningFailedPrefix`)}),G.agent_log]}),(0,Z.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,Z.jsx)(DT,{tool:G.tool,className:`text-[11px]`})}),(0,Z.jsx)(OT,{externalSource:G.external_source}),(0,Z.jsx)(aP,{heading:`Edit Ticket`,bundles:r,initialTitle:G.title,initialDescription:G.description??``,initialModel:G.model??``,initialVariant:G.variant??``,initialSkills:G.skills??[],initialWorktreeBundleId:G.worktree_bundle_id,projectBranchState:c,projectId:G.project_id,stackConfigurationSections:Rt&&!Bt,preferWideBundleSelector:Rt&&Bt,agentSettingsPresentation:Bt?`popover`:`panel`,showModelSelector:a,availableModels:o,availableSkills:s,onAgentSettingsChange:Ne,onCreateBundle:p,onDeleteBundle:m,onRefreshBundles:h,onCancel:Jt,onDirtyChange:fe,titleInputId:`edit-title`,descriptionInputId:`edit-description`,bundleSelectId:`edit-ticket-bundle`,modelSelectId:`edit-model`,variantSelectId:`edit-variant`,skillsSelectId:`edit-skills`,showEmptyBundleOption:!1,planAction:{label:`Plan`,onClick:async({title:e,description:t,model:n,variant:r,skills:i,worktree_bundle_id:a})=>{let o=await Zt(G.id,G.project_id,{title:e,description:t,model:n,variant:r,skills:i,worktree_bundle_id:a});g?.(o),f(),await Cn(G.id,G.project_id)}},primaryAction:{label:`Save`,variant:ct?`subtle`:`brand`,onClick:Ve},secondaryAction:ct?{label:`Save & Build`,variant:`brand`,showAdvanceIcon:!0,onClick:He}:void 0,tertiaryAction:lt?{label:`Save & Build Chain`,variant:`brand`,showAdvanceIcon:!0,onClick:Ge}:void 0,beforeActionsContent:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,Z.jsx)(gP,{projectId:G.project_id,ticketId:G.id,memoryEnabled:l,refreshKey:le,onSuggestionsChanged:O}),et.hasDependents&&(0,Z.jsx)(FT,{summary:J,detail:tt}),(0,Z.jsx)(qN,{blocks:Qe,blockedBy:$e,resolveTicket:e=>Ze.get(e),onDeleteDependency:_})]}),footerLeadingContent:de?(0,Z.jsx)(U,{variant:`outline`,className:`border-amber-500/35 bg-amber-500/10 text-amber-200`,children:`Unsaved changes`}):null},`${G.id}:${G.updated_at}:${G.title}:${G.description}`)]}):(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 overflow-hidden`,children:[(0,Z.jsx)(`div`,{className:`sticky top-0 -my-1 bg-card py-1 pr-12 sm:pr-24`,children:(0,Z.jsxs)(`div`,{className:`min-w-0 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:G.title}),(0,Z.jsx)(DT,{tool:G.tool,className:`text-[11px]`}),(Ot===`building`||Ot===`done`)&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[G.is_running&&(0,Z.jsx)(`span`,{className:`w-2 h-2 rounded-full bg-emerald-400 animate-pulse flex-shrink-0`}),(0,Z.jsx)(oT,{status:Ot,showBuildGlyph:!0})]}),Ot!==null&&Ot!==`building`&&Ot!==`done`&&(0,Z.jsx)(oT,{status:Ot,showBuildGlyph:!0}),Ct&&(0,Z.jsx)(U,{variant:`warning`,children:k(`ticketModal.openQuestionsBadge`)}),at&&(0,Z.jsx)(U,{variant:`outline`,className:`border-border/80 bg-card/60 text-muted-foreground`,children:`Stale`})]})}),Ie?(0,Z.jsx)(`div`,{className:`mt-3 min-h-0 flex flex-1 flex-col`,children:(0,Z.jsx)(_P,{content:G.description,externalSource:G.external_source})}):(0,Z.jsx)(Z.Fragment,{children:Pe?(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 flex flex-col${Le?` mt-3`:``}`,children:(0,Z.jsx)(_P,{content:G.description,externalSource:G.external_source})}):(0,Z.jsx)(WN,{projectId:G.project_id,followUpTicketId:G.id,messages:nn,internalLog:G.agent_log??null,currentThinkingMessageId:G.agent_message_id??null,previousThinkingLog:G.previous_agent_log??null,previousThinkingMessageId:G.previous_agent_message_id??null,streamingResponse:G.streaming_response??null,isRunning:G.agent_status===`running`,canShowComposer:bt,pendingAgentTitle:K,composerTheme:Fe,followUpComposerControls:wt?(0,Z.jsx)(CP,{model:ge,variant:ve,skills:be,showModelSelector:!0,showSkillsSelector:!0,availableModels:o,availableSkills:s,selectedModel:Et,onModelChange:Xt,onVariantChange:Qt,onSkillsChange:$t,modelSelectId:`ticket-follow-up-model`,variantSelectId:`ticket-follow-up-variant`,skillsSelectId:`ticket-follow-up-skills`,disabled:Ae}):void 0,followUpPrompt:B,isSendingFollowUp:V,followUpDisabledReason:jt,onFollowUpPromptChange:ie,onFollowUpKeyDown:e=>{e.key!==`Enter`||e.shiftKey||Dt||V||(e.preventDefault(),en())},onFollowUpSubmit:()=>{en()}})}),Le&&(0,Z.jsxs)(`section`,{"aria-label":k(`workspaceControls.ticketMetadataAriaLabel`),className:`flex flex-wrap items-center gap-2`,children:[Nt.filter(e=>e.value.trim().length>0).map(e=>(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 sm:flex-none sm:max-w-full`,children:(0,Z.jsx)(AT,{label:e.label,value:e.value,variant:`compact`,className:`min-w-0`})},`${e.label}:${e.value}`)),(0,Z.jsx)(`div`,{className:`min-w-0 sm:flex-none`,children:(0,Z.jsx)(TT,{model:Pt.model,variant:Pt.variant,skills:Pt.skills})})]}),!Le&&!zt&&(0,Z.jsx)(jT,{ariaLabel:k(`workspaceControls.ticketMetadataAriaLabel`),items:Nt}),(0,Z.jsx)(gP,{projectId:G.project_id,ticketId:G.id,memoryEnabled:l,refreshKey:le,onSuggestionsChanged:O}),(0,Z.jsx)(qN,{blocks:Qe,blockedBy:$e,resolveTicket:e=>Ze.get(e),onDeleteDependency:_}),G.build_chain&&(0,Z.jsx)(FT,{summary:ot,detail:st})]}),!ze&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 border-t border-border pt-4 sm:flex-row sm:items-end sm:justify-between`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[(0,Z.jsx)(q,{type:`button`,onClick:f,variant:`ghost`,children:k(`workspaceControls.close`)}),G.build_chain&&w&&(0,Z.jsxs)(q,{type:`button`,onClick:()=>{w()},title:`Stop scheduling the remaining tickets in this build chain.`,"aria-label":Xe,variant:`destructive`,children:[(0,Z.jsx)(Fc,{className:`w-3.5 h-3.5`}),Xe]}),(0,Z.jsx)(qW,{actions:rt,actionsClassName:`contents`,renderAction:({action:e,label:t,disabled:n,title:r,ariaLabel:i})=>{let a=e.id===`review`?(0,Z.jsx)(xw,{className:`w-3.5 h-3.5`}):e.id===`run`||e.id===`resume-build`?(0,Z.jsx)(Nc,{className:`w-3.5 h-3.5`}):(0,Z.jsx)(Fc,{className:`w-3.5 h-3.5`});return(0,Z.jsxs)(q,{type:`button`,disabled:n,title:r,"aria-label":i,variant:e.id===`stop-run`?`destructive`:e.id===`pause-build`||e.id===`resume-build`?`warning`:e.id===`run`?`secondary`:`default`,className:e.id===`run`?`bg-sky-700 text-sky-100 hover:bg-sky-600 hover:text-white disabled:bg-slate-700 disabled:text-slate-400`:e.id===`resume-build`?`bg-amber-700 text-amber-50 hover:bg-amber-600 hover:text-white`:void 0,onClick:()=>We(e.id),children:[e.id===`review`?t:a,e.id===`review`?a:t]},e.id)}})]})]})]}),zt&&an,vt&&(0,Z.jsx)(`div`,{className:R?ee?`fixed inset-0 z-[70] flex items-center justify-center bg-black/30 p-[5vh]`:`mt-12 min-h-0 flex flex-1 flex-col overflow-hidden`:`hidden`,children:(0,Z.jsx)(KW,{createSession:()=>ST(G.id,G.project_id),isExpanded:ee,isVisible:R,ariaLabel:k(`ticketModal.ticketTerminalAriaLabel`),className:ee?`h-full w-full max-w-none rounded-2xl shadow-2xl`:void 0,onClose:Wt,onToggleExpanded:()=>{te(e=>!e)}})})]}),Lt&&an,P&&(0,Z.jsx)(Y.Suspense,{fallback:(0,Z.jsx)(sG,{onClose:()=>{F(!1),D?.(G.id)}}),children:(0,Z.jsx)(nG,{ticketId:G.id,projectId:G.project_id,title:G.title,onTicketUpdate:g,onRequestTicketRefresh:D,onSubmitReviewPrompt:E,canSubmitReviewPrompt:!Dt,reviewSubmitDisabledReason:jt,onClose:()=>{F(!1),D?.(G.id)}})}),I&&ht&&G.project_id&&(0,Z.jsx)(Y.Suspense,{fallback:null,children:(0,Z.jsx)(rG,{scope:`ticket`,ticketId:G.id,projectId:G.project_id,testCommands:i,onClose:()=>{L(!1)}})}),pe&&(0,Z.jsx)(mu,{title:k(`ticketModal.discardUnsavedTitle`),description:Tt,confirmLabel:k(`ticketModal.discardUnsavedConfirm`),cancelLabel:k(`ticketModal.discardUnsavedCancel`),confirmVariant:`destructive`,onConfirm:Kt,onCancel:Gt})]})})},dG=({ticket:e,allTickets:t=[],dependencies:n=[],bundles:r=[],projectMemoryEnabled:i=!1,overlay:a=!1,showModelSelector:o,availableModels:s,runDisabled:c=!1,runDisabledReason:l,dependencyTargetState:u=`idle`,onDependencyStart:d,onDeleteDependency:f,onRegisterNode:p,onRegisterOverlayNode:m,onCreateBundle:h,onDeleteBundle:g,onRefreshBundles:_,onUpdate:v,onDelete:y,onUndo:b,onRetry:x,onAdvance:S,onPark:C,onUnpark:w,onBuildChain:T,onRun:E,onOpenTests:D,onOpenChanges:O,onOpenIde:k,onAddTicketToBundle:A,onStop:j,onStopBuild:M,onStopBuildChain:N,onResumeBuild:P,onFollowUp:F,onOpenBundleDetails:I,onOpenTicketDetails:L,preferBundleDetailsOnClick:R=!1,hideBundleScopedControls:z=!1,hideStatusBadge:ee=!1,onRequestTicketRefresh:te,undoInProgress:ne=!1})=>{let{t:re}=X(`common`),[B,ie]=(0,Y.useState)(!1),[V,H]=(0,Y.useState)(!1),[ae,oe]=(0,Y.useState)(!1),[se,ce]=(0,Y.useState)(!1),[le,ue]=(0,Y.useState)(null),[de,fe]=(0,Y.useState)(!1),[pe,me]=(0,Y.useState)(!1),W=e.agent_status===`running`||ne,he=z,G=e.bundle?.branch??e.branch,ge=e.has_worktree??(e.state===`plan`?!1:!!G),_e=!z&&ge,ve=eT(e,new Map(t.map(e=>[e.id,e])),n),ye=ww(e.state),be=e.state===`review`&&e.can_re_review===!0&&e.agent_status!==`running`,xe=e.worktree_bundle_id!==null,K=Ow(e),Se=kw(e),Ce=Aw(e),we=!z&&Se!==`plan`&&e.diff_stats===void 0,Te=(Ce||K)&&!a,Ee=ye?re(ye===`review`?`card.advance.reviewBundle`:`card.columnLabels.${ye}`):be?re(`card.advance.rerunReview`):null,De=Fw(e,`trash`),Oe=e.undo,ke=!!b&&Oe?.stage!==null,Ae=be||(ye?Fw(e,ye):!1),je=!K&&!!S&&!!Ee&&!ve.hasOpenBlockers,Me=!!C&&Nw(e),Ne=K&&typeof e.state==`string`?re(`card.returnTo`,{state:re(`card.columnLabels.${e.state}`)}):null,Pe=!!w&&Ne!==null&&e.state!==`plan`,Fe=!K&&!!T&&ve.canStartBuildChain,Ie=Dw(e)&&e.agent_status===`running`&&!!e.session_id&&!!M,Le=Dw(e)&&e.agent_status===`stopped`&&!!e.session_id&&!!P,Re=_e&&!!O,ze=_e&&!!e.project_id&&!!D,Be=_e&&!!k,Ve=!K&&!z&&xe&&!!A,He=!he&&ge&&!!G&&!e.is_running&&!!E,Ue=!he&&ge&&!!G&&!!e.is_running&&!!j,We=!!e.build_chain&&!!N,Ge=!!y||ke||je||Me||Pe||Fe||Ie||Le||Ve||He||Ue||ze||Re||Be||We,Ke=async()=>{if(!(!E||c||de)){fe(!0);try{await E()}finally{fe(!1)}}},qe=async()=>{if(!(!j||pe)){me(!0);try{await j()}finally{me(!1)}}},Je=!he&&ge&&G&&e.is_running&&j&&!ne?(0,Z.jsx)(cT,{isRunning:!0,isStopPending:pe,onStop:qe}):!he&&ge&&G&&!e.is_running&&!K&&E?(0,Z.jsx)(cT,{isRunning:!1,isRunPending:de,runDisabled:c,runDisabledReason:l,onRun:Ke}):null;(0,Y.useEffect)(()=>{if(!se)return;let e=()=>{ce(!1)};return window.addEventListener(`click`,e,{once:!0}),()=>{window.removeEventListener(`click`,e)}},[se]);let Ye=()=>{if(a||se||ne){ce(!1);return}if(R&&I){I();return}if(L){L();return}te?.(e.id),oe(!0)},{attributes:Xe,listeners:Ze,setNodeRef:Qe,isDragging:$e}=QC({id:e.id,disabled:a||W}),et=(0,Y.useRef)(Qe);(0,Y.useEffect)(()=>{et.current=Qe},[Qe]);let J=(0,Y.useCallback)(t=>{if(a){m?.(t);return}et.current(t),p?.(e.id,t)},[p,m,a,e.id]),tt=u===`valid`?`border-emerald-400 shadow-[0_0_0_1px_rgba(52,211,153,0.35)]`:u===`invalid`?`border-red-400 shadow-[0_0_0_1px_rgba(248,113,113,0.35)]`:a?`border-violet-400`:ve.isVisibleStartPoint?`border-violet-500/35 shadow-[0_0_0_1px_rgba(168,85,247,0.18)] hover:border-violet-400/55`:`border-border hover:border-primary/40`,nt=a||ne?`pointer-events-none cursor-grabbing shadow-2xl`:`cursor-pointer`,rt=$e?`opacity-30`:Te?`opacity-90`:`opacity-100`,it=Te?`bg-card/60`:`bg-secondary/30`,at=Te?`p-3 text-foreground/70`:`p-3`,ot=Te?`truncate text-sm font-medium text-foreground/70`:`truncate text-sm font-medium text-foreground`,st=Te?`text-[11px] text-foreground/55`:`text-[11px] text-muted-foreground`,ct=Te?`whitespace-pre-line text-xs leading-relaxed text-foreground/55 wrap-anywhere`:`whitespace-pre-line text-xs leading-relaxed text-muted-foreground wrap-anywhere`,lt=e.model??``,ut=!!e.bundle&&!z,dt=!!e.bundle?.pull_request&&!z,ft=ut||dt,pt=ft||lt.length>0,mt=le===e.id,ht=(0,Y.useMemo)(()=>{let t=e.description??``;return t?eN(t):{text:``,truncated:!1}},[e.description]);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(gu,{"data-testid":`ticket-card-${e.id}`,className:`group/card shrink-0 select-none transition-colors ${tt} ${nt} ${rt} ${it} gap-0 rounded-xl border shadow-none`,ref:J,onClick:Ye,...Ze,...Xe,children:[ne&&(0,Z.jsx)(`div`,{className:`absolute inset-0 z-10 flex items-center justify-center rounded-xl bg-background/85 backdrop-blur-[1px]`,children:(0,Z.jsxs)(U,{variant:`warning`,className:`gap-1.5`,children:[(0,Z.jsx)(kf,{className:`h-3.5 w-3.5 animate-spin`}),re(`card.undoInProgress`)]})}),(0,Z.jsxs)(xu,{className:at,children:[(0,Z.jsxs)(`div`,{className:`mb-1.5 flex items-start justify-between gap-2`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Z.jsx)(`div`,{className:ot,children:e.title})}),(0,Z.jsxs)(`div`,{className:`flex flex-shrink-0 items-start gap-1`,children:[(0,Z.jsx)(`div`,{className:`mr-1`,children:Je}),(0,Z.jsx)(`div`,{className:`flex size-7 items-start justify-center`,children:d&&(0,Z.jsx)(xc,{content:re(`card.drawDependency`),children:(0,Z.jsx)(q,{type:`button`,"aria-label":re(`card.createDependencyAriaLabel`,{title:e.title}),variant:`ghost`,size:`icon-xs`,className:`cursor-crosshair opacity-0 transition-all group-hover/card:opacity-100`,onClick:e=>e.stopPropagation(),onPointerDown:t=>{t.stopPropagation(),ce(!0),d(e.id,t)},children:(0,Z.jsx)(Jd,{className:`h-4 w-4`})})})}),(0,Z.jsx)(`div`,{className:`flex size-7 items-start justify-center`,children:Ge&&(0,Z.jsx)(vT,{title:e.title,canDelete:De,undo:Oe,undoInProgress:ne,runDisabled:c,isRunPending:de,isStopPending:pe,showTestsAction:ze,showOpenChangesAction:Re,showOpenIdeAction:Be,showAddTicketToBundleAction:Ve,showRunAction:He,showStopRunAction:Ue,showAdvanceAction:je,advanceLabel:Ee,canAdvance:Ae,showParkAction:Me,showReturnAction:Pe,returnLabel:Ne,showBuildChainAction:Fe,showPauseBuildAction:Ie,showResumeBuildAction:Le,showStopBuildChainAction:We,onDelete:y,onConfirmDelete:()=>ie(!0),onConfirmUndo:()=>H(!0),onOpenTests:D,onOpenChanges:O,onOpenIde:k,onAddTicketToBundle:Ve?()=>A?.(e.worktree_bundle_id):void 0,onAdvance:S,onPark:C,onUnpark:w,onBuildChain:T,onRun:Ke,onStop:qe,onStopBuild:M,onResumeBuild:P,onStopBuildChain:N})})]})]}),(0,Z.jsx)(`div`,{className:`mt-2`,children:(0,Z.jsx)(xT,{ticket:e,hideStatusBadge:ee,hideBundleScopedControls:z,isStale:Ce,runControl:null,onRetry:x,undoInProgress:ne,isChainStart:ve.isVisibleStartPoint})}),pt&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-col gap-1`,children:[ft&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 ${st}`,children:[ut&&(0,Z.jsx)(`span`,{className:`min-w-0 truncate`,children:Dl(e.bundle)}),dt&&e.bundle?.pull_request&&(0,Z.jsx)(yw,{pullRequest:e.bundle.pull_request,asLink:!0,showNumber:!0,onClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation()})]}),lt.length>0&&(0,Z.jsx)(`div`,{className:st,children:(0,Z.jsx)(`span`,{className:`truncate`,children:lt})})]}),e.description&&(0,Z.jsx)(`div`,{className:`mt-2`,children:(0,Z.jsx)(bT,{description:e.description,descriptionClass:ct,isExpanded:mt,collapsedState:ht,useStaleLikeStyling:Te,onExpand:()=>ue(e.id),onCollapse:()=>ue(null)})}),!z&&(Mw(Se,e.diff_stats)||we)&&(0,Z.jsx)(kc,{stats:e.diff_stats,isLoading:we,showFiles:!0,className:`mt-2`})]})]}),ae&&(0,Z.jsx)(uG,{ticket:e,allTickets:t,dependencies:n,bundles:r,projectMemoryEnabled:i,onClose:()=>{oe(!1),te?.(e.id)},showModelSelector:o,availableModels:s,runDisabled:c,runDisabledReason:l,onDeleteDependency:f,onCreateBundle:h,onDeleteBundle:g,onRefreshBundles:_,onUpdate:v,onAdvance:S,onBuildChain:T,onRun:E,onOpenIde:k,onStop:j,onStopBuild:M,onStopBuildChain:N,onResumeBuild:P,onFollowUp:F}),B&&(0,Z.jsx)(yT,{title:e.title,bundleName:e.bundle?Dl(e.bundle):void 0,onConfirm:()=>{ie(!1),y?.()},onCancel:()=>ie(!1)}),V&&Oe?.stage&&(0,Z.jsx)(sT,{title:e.title,stage:Oe.stage,onConfirm:()=>{H(!1),b?.()},onCancel:()=>H(!1)})]})},fG=({index:e})=>{let{t}=X(`common`);return(0,Z.jsx)(gu,{"aria-hidden":`true`,"data-testid":`ticket-card-skeleton`,className:`group shrink-0 select-none gap-0 rounded-xl border border-border/70 bg-secondary/20 shadow-none`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 p-3`,"aria-hidden":`true`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,Z.jsx)(Oc,{className:`h-3.5 w-3/5 rounded-full`}),(0,Z.jsx)(Oc,{className:`h-5 w-11 rounded-full`})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Oc,{className:`h-3 w-full rounded-full`}),(0,Z.jsx)(Oc,{className:`h-3 w-11/12 rounded-full`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Oc,{className:`h-4 w-14 rounded-full`}),(0,Z.jsx)(Oc,{className:`h-4 w-10 rounded-full`})]}),(0,Z.jsx)(`span`,{className:`sr-only`,children:t(`column.loadingCard`,{index:e+1})})]})})},pG=({id:e,title:t,items:n,ticketCount:r,pinnedContent:i=null,allTickets:a,dependencies:o,showModelSelector:s,availableModels:c,activeRunContextKey:l,isProjectRootRunActive:u=!1,isBundleRunDisabled:d,bundles:f,getDependencyTargetState:p,onDependencyStart:m,onDeleteDependency:h,onRegisterTicketNode:g,onAddTicket:_,onCreateBundle:v,onDeleteBundle:y,onRefreshBundles:b,onUpdateTicket:x,onDeleteTicket:S,onUndoTicket:C,undoingColumn:w=null,onRetryTicket:T,onAdvanceTicket:E,onParkTicket:D,onUnparkTicket:O,onBuildChainTicket:k,onRunTicket:A,onOpenTestsTicket:j,canOpenChangesForTicket:M,onOpenChangesTicket:N,canOpenIdeForTicket:P,onOpenIdeTicket:F,onStopTicket:I,onStopBuildTicket:L,onStopBuildChainTicket:R,onResumeBuildTicket:z,onFollowUpTicket:ee,onBuildBundle:te,onReviewBundle:ne,onUndoBundleReview:re,onRunBundle:B,onStopBundle:ie,onParkBundleWrapper:V,onUnparkBundleWrapper:H,bundleActionState:ae,onOpenTicketDetails:oe,onOpenBundleDetails:se,onOpenBundleChanges:ce,onOpenBundleTests:le,onOpenBundleIde:ue,onDeleteBundleWrapper:de,onAddTicketToBundle:fe,onRequestBundleRefresh:pe,onRequestTicketRefresh:me,className:W=``,headerAccessory:he=null,loadingSkeletonCount:G=0})=>{let{t:ge}=X(`common`),{setNodeRef:_e,isOver:ve}=nw({id:e}),ye=(0,Y.useRef)(null),[be,xe]=(0,Y.useState)(!1),[K,Se]=(0,Y.useState)(!1),Ce=e=>e.has_worktree??!!(e.bundle?.branch??e.branch),we=ve?`border-primary`:`border-border`,Te=w===e&&(e===`build`||e===`review`),Ee=(0,Y.useCallback)(()=>{let e=ye.current;if(!e){xe(!1),Se(!1);return}if(!(e.scrollHeight>e.clientHeight+1)){xe(!1),Se(!1);return}let t=e.scrollHeight-e.clientHeight;xe(e.scrollTop>1),Se(e.scrollTop<t-1)},[]);(0,Y.useEffect)(()=>{let e=window.requestAnimationFrame(Ee),t=ye.current;if(!t){window.cancelAnimationFrame(e);return}return t.addEventListener(`scroll`,Ee),window.addEventListener(`resize`,Ee),()=>{window.cancelAnimationFrame(e),t.removeEventListener(`scroll`,Ee),window.removeEventListener(`resize`,Ee)}},[n.length,G,Ee]);let De=(0,Y.useCallback)((t,n)=>{let r=t.worktree_bundle_id!==null,i=n?.nestedInBundle??!1,d=n?.hideStatusBadge??!1,_=r&&e!==`plan`,w=Yw(t),te=u||l!==null&&l!==Ew(t)?ge(`column.runDisabledReason`):w;return(0,Z.jsx)(dG,{ticket:t,allTickets:a,dependencies:o,bundles:f,showModelSelector:s,availableModels:c,runDisabled:te!==void 0,runDisabledReason:te,dependencyTargetState:p?.(t.id)??`idle`,onDependencyStart:m,onDeleteDependency:h,onRegisterNode:g,onCreateBundle:v,onDeleteBundle:y,onRefreshBundles:b,onUpdate:x,onDelete:()=>S(t.id),onUndo:C?()=>C(t.id):void 0,undoInProgress:!1,onRetry:()=>T(t.id),onAdvance:E?()=>E(t.id):void 0,onPark:D?()=>D(t.id):void 0,onUnpark:O?()=>O(t.id):void 0,onBuildChain:k?()=>k(t.id):void 0,onRun:Ce(t)&&t.has_run_config&&A?()=>A(t.id):void 0,onOpenTests:j&&t.project_id&&Ce(t)?()=>j(t.id):void 0,onOpenChanges:M?.(t)&&N?()=>N(t.id):void 0,onOpenIde:P?.(t)&&F?()=>F(t.id):void 0,onStop:I?()=>I(t.id):void 0,onStopBuild:L?()=>L(t.id):void 0,onStopBuildChain:R?()=>R(t.id):void 0,onResumeBuild:z?()=>z(t.id):void 0,onFollowUp:ee?e=>ee(t.id,e):void 0,onAddTicketToBundle:fe,onOpenBundleDetails:_&&se?()=>se(t.worktree_bundle_id,e):void 0,onOpenTicketDetails:()=>oe(t),preferBundleDetailsOnClick:_,hideBundleScopedControls:i,hideStatusBadge:d,onRequestTicketRefresh:me})},[l,a,c,f,M,P,o,p,e,u,fe,E,k,v,y,h,S,m,ee,se,N,F,j,oe,D,b,g,me,z,T,A,R,L,I,C,O,x,s,ge]);return(0,Z.jsxs)(gu,{className:`flex min-h-0 min-w-[280px] flex-1 flex-col rounded-2xl bg-card/80 p-4 transition-colors ${W} ${we}`,ref:_e,children:[(0,Z.jsxs)(`div`,{className:`mb-4 flex min-h-7 items-center justify-between`,children:[(0,Z.jsx)(`h2`,{className:`text-xs font-semibold uppercase tracking-widest text-muted-foreground`,children:t}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[he,(0,Z.jsx)(U,{variant:`outline`,children:r}),_&&(0,Z.jsxs)(q,{type:`button`,onClick:_,size:`xs`,variant:`success`,className:`gap-2 shadow-[0_8px_20px_rgba(16,185,129,0.22)]`,children:[(0,Z.jsx)(`span`,{children:ge(`column.newTicket`)}),(0,Z.jsx)(U,{"aria-hidden":`true`,variant:`hotkeyDark`,className:`rounded-md px-1.5 py-0.5 text-[10px] leading-none`,children:`N`})]})]})]}),(0,Z.jsxs)(`div`,{className:`relative min-h-0 flex-1`,children:[(0,Z.jsxs)(`div`,{ref:ye,className:`flex min-h-0 h-full flex-col gap-2.5 overflow-y-auto pr-1`,children:[i,n.map(e=>{if(e.kind===`bundle`)return(0,Z.jsx)(gT,{group:e.group,renderTicket:t=>De(t,{nestedInBundle:!0,hideStatusBadge:e.group.column===`review`}),runDisabled:d?.(e.group.bundle.id)??!1,onBuildBundle:te,onReviewBundle:ne,onUndoBundleReview:re,onRunBundle:B,onStopBundle:ie,onParkBundleWrapper:V,onUnparkBundleWrapper:H,bundleActionState:ae,onStopBuildTicket:L,onResumeBuildTicket:z,onOpenBundleDetails:se,onOpenBundleChanges:ce,onOpenBundleTests:le,onOpenBundleIde:ue,onDeleteBundleWrapper:de,onAddTicketToBundle:fe,onRequestBundleRefresh:pe},e.group.id);let t=e.ticket;return(0,Z.jsx)(Y.Fragment,{children:De(t)},t.id)}),Array.from({length:G},(t,n)=>(0,Z.jsx)(fG,{index:n},`loading-card-${e}-${n}`))]}),Te&&(0,Z.jsx)(`div`,{"aria-hidden":`true`,"data-testid":`column-undo-overlay-${e}`,className:`absolute inset-0 z-20 flex items-center justify-center rounded-xl bg-background/85 backdrop-blur-[1px]`,children:(0,Z.jsxs)(U,{variant:`warning`,className:`gap-1.5`,children:[(0,Z.jsx)(kf,{className:`h-3.5 w-3.5 animate-spin`}),ge(`column.undoInProgress`)]})}),be&&(0,Z.jsx)(`div`,{"aria-hidden":`true`,"data-testid":`column-top-fade`,className:`pointer-events-none absolute inset-x-0 top-0 h-6 rounded-t-xl bg-gradient-to-b from-card to-transparent`}),K&&(0,Z.jsx)(`div`,{"aria-hidden":`true`,"data-testid":`column-bottom-fade`,className:`pointer-events-none absolute inset-x-0 bottom-0 h-8 rounded-b-xl bg-gradient-to-t from-card to-transparent`})]})]})},mG=({ticketCount:e,isDeleting:t,onCancel:n,onConfirm:r})=>{let{t:i}=X(`common`);return(0,Z.jsxs)(pu,{onClose:t?()=>{}:n,overlayClassName:`bg-black/60`,panelClassName:`max-w-md rounded-2xl border border-border bg-card p-6 shadow-2xl`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold uppercase tracking-widest text-muted-foreground`,children:i(`boardConfirmEmptyDoneModal.heading`)}),(0,Z.jsx)(`p`,{className:`mb-2 text-sm text-foreground`,children:i(`boardConfirmEmptyDoneModal.deletePrompt`,{count:e})}),(0,Z.jsx)(`p`,{className:`mb-6 text-xs text-muted-foreground`,children:i(`boardConfirmEmptyDoneModal.description`)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(q,{type:`button`,variant:`ghost`,disabled:t,onClick:n,children:i(`boardConfirmEmptyDoneModal.cancel`)}),(0,Z.jsx)(q,{type:`button`,variant:`destructive`,disabled:t,onClick:r,children:i(t?`boardConfirmEmptyDoneModal.deleting`:`boardConfirmEmptyDoneModal.confirm`)})]})]})},hG=({projectId:e,followUpTicketId:t=null,messages:n,internalLog:r,currentThinkingMessageId:i=null,legacyThinkingTicketId:a=null,previousThinkingLog:o=null,previousThinkingMessageId:s=null,pendingAgentTitle:c,streamingResponse:l,isRunning:u,isLoading:d=!1,canShowComposer:f,composerControls:p,composerTheme:m=`default`,layoutKey:h,scrollLayoutKey:g,followUpPrompt:_,followUpPlaceholder:v=`Follow up on this bundle`,isSendingFollowUp:y,followUpDisabledReason:b,onFollowUpPromptChange:x,onFollowUpKeyDown:S,onFollowUpSubmit:C})=>(0,Z.jsx)(UN,{projectId:e,followUpTicketId:t,messages:n,internalLog:r,currentThinkingMessageId:i,legacyThinkingTicketId:a,previousThinkingLog:o,previousThinkingMessageId:s,pendingAgentTitle:c,streamingResponse:l,isRunning:u,isLoading:d,autoScrollBehavior:`sticky`,canShowComposer:f,composerInlineControls:p,composerTheme:m,composerSize:`compact-on-laptop`,layoutKey:h,scrollLayoutKey:g,followUpPrompt:_,followUpPlaceholder:v,emptyStateText:`No bundle messages yet.`,autoFocusComposer:!0,isSendingFollowUp:y,followUpDisabledReason:b,onFollowUpPromptChange:x,onFollowUpKeyDown:S,onFollowUpSubmit:C}),gG=({bundleId:e,actionState:t,runDisabled:n,canBuild:r,canStopBuild:i,runningBuildTicketId:a,canResumeBuild:o,resumableBuildTicketId:s,isRunning:c,canRun:l,canReview:u,reviewActionLabel:d=`Review Bundle`,onClose:f,onBuildBundle:p,onStopBuildTicket:m,onResumeBuildTicket:h,onRunBundle:g,onStopBundle:_,onReviewBundle:v})=>{let y=t.review||t.followUp;return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 pt-4 sm:flex-row sm:items-end sm:justify-between`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[(0,Z.jsx)(q,{type:`button`,onClick:f,variant:`ghost`,children:`Close`}),c?(0,Z.jsxs)(q,{type:`button`,variant:`destructive`,disabled:t.stop,onClick:()=>void _(e),children:[(0,Z.jsx)(`span`,{className:`w-2 h-2 rounded-full bg-emerald-400 animate-pulse flex-shrink-0`}),(0,Z.jsx)(Fc,{className:`w-3.5 h-3.5`}),t.stop?`Stopping...`:`Stop Run`]}):l?(0,Z.jsxs)(q,{type:`button`,variant:`secondary`,disabled:t.run||n,title:n?`Stop the currently running ticket before starting another run.`:void 0,onClick:()=>{n||g(e)},className:`bg-sky-700 text-sky-100 hover:bg-sky-600 hover:text-white disabled:bg-slate-700 disabled:text-slate-400`,children:[(0,Z.jsx)(Nc,{className:`w-3.5 h-3.5`}),t.run?`Starting Run...`:`Run`]}):null,r&&(0,Z.jsxs)(q,{type:`button`,disabled:t.build,onClick:()=>void p(e),children:[(0,Z.jsx)(Nc,{className:`w-3.5 h-3.5`}),t.build?`Building Bundle...`:`Build Bundle`]}),i&&a&&(0,Z.jsxs)(q,{type:`button`,variant:`warning`,disabled:t.stopBuild,title:`Pause the build session. You can resume it later.`,"aria-label":`Pause Build`,onClick:()=>void m(a),children:[(0,Z.jsx)(Fc,{className:`w-3.5 h-3.5`}),t.stopBuild?`Pausing...`:`Pause Build`]}),o&&s&&(0,Z.jsxs)(q,{type:`button`,variant:`warning`,className:`bg-amber-700 text-amber-50 hover:bg-amber-600 hover:text-white`,disabled:t.resumeBuild,onClick:()=>void h(s),children:[(0,Z.jsx)(Nc,{className:`w-3.5 h-3.5`}),t.resumeBuild?`Resuming...`:`Resume`]}),u&&(0,Z.jsxs)(q,{type:`button`,disabled:y,onClick:()=>void v(e),children:[(0,Z.jsx)(xw,{className:`w-3.5 h-3.5`}),y?`Reviewing Bundle...`:d]})]})]})},_G=e=>e.agent_status===`running`?`bg-amber-400`:e.agent_status===`error`?`bg-rose-400`:e.agent_status===`stopped`?`bg-amber-300`:e.agent_status===`done`?`bg-emerald-400`:`bg-border`,vG=({tickets:e,onOpenTicketDetails:t,highlightedTicketId:n=null,pendingMemorySuggestionCounts:r={}})=>{let i=e.filter(e=>e.agent_status===`running`).length,a=e.filter(e=>e.agent_status===`error`).length;return(0,Z.jsxs)(`section`,{"aria-label":`Bundle tickets`,className:`flex min-h-0 flex-1 flex-col gap-3 overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground`,children:`Tickets`}),(0,Z.jsx)(U,{variant:`outline`,children:e.length}),i>0&&(0,Z.jsxs)(`span`,{className:`text-[11px] text-muted-foreground`,children:[i,` active`]}),a>0&&(0,Z.jsxs)(`span`,{className:`text-[11px] text-rose-300`,children:[a,` error`,a===1?``:`s`]})]}),(0,Z.jsx)(`div`,{className:`flex min-h-0 flex-col gap-1 overflow-y-auto pr-1`,children:e.map(e=>{let i=r[e.id]??0,a=e.id===n;return(0,Z.jsxs)(`button`,{type:`button`,"data-follow-up-target":a?`true`:`false`,"aria-current":a?`true`:void 0,className:K(`flex cursor-pointer items-center gap-3 rounded-lg px-2.5 py-2.5 text-left text-foreground transition-colors`,a?`border border-sky-500/35 bg-sky-500/10 shadow-[inset_0_0_0_1px_rgba(56,189,248,0.12)] hover:bg-sky-500/15`:`bg-background/20 hover:bg-accent/45`),onClick:()=>t(e),children:[(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:K(`h-2 w-2 shrink-0 rounded-full`,_G(e))}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`truncate text-xs font-medium`,children:e.title}),(0,Z.jsx)(DT,{tool:e.tool,className:`shrink-0 text-[10px]`})]}),(0,Z.jsx)(`div`,{className:`mt-0.5 text-[11px] text-muted-foreground`,children:e.state})]}),a&&(0,Z.jsx)(U,{variant:`info`,className:`shrink-0 px-1.5 text-[10px]`,"aria-label":`Follow-up target`,children:`Follow-up`}),i>0&&(0,Z.jsx)(U,{variant:`warning`,className:`h-5 min-w-5 shrink-0 justify-center rounded-full px-1.5 text-[10px]`,"aria-label":`${i} pending memory suggestion${i===1?``:`s`}`,title:`${i} pending memory suggestion${i===1?``:`s`}`,children:i})]},e.id)})})]})},yG=e=>e.kind===`description`?e.bundle_visible_at??e.created_at:e.created_at,bG=(e,t)=>e?t.get(e)??e:null,xG=(e,t)=>bG(e,t)??`Agent`,SG=e=>e.kind===`planning_follow_up`||e.kind===`planning_response`?0:e.kind===`description`?1:2,CG=(e,t)=>{let n={};for(let r of e){let e=bG(r.model,t);e&&(n[r.id]=e)}return n},wG=(e,t=[])=>{let n=new Map(t.map((e,t)=>[e,t]));return[...e].sort((e,t)=>{let r=n.get(e.id)??e.bundle_execution_position??2**53-1,i=n.get(t.id)??t.bundle_execution_position??2**53-1;if(r!==i)return r-i;if(e.created_at!==t.created_at)return e.created_at.localeCompare(t.created_at);let a=e.title.localeCompare(t.title,void 0,{sensitivity:`base`});return a===0?e.id.localeCompare(t.id):a})},TG=(e,t,n,r=[])=>{let i=wG(e,r),a=new Map(i.map((e,t)=>[e.id,t]));return i.flatMap(e=>{let r=e.messages??[],i=e.agent_status!==null||e.session_id!==null||r.some(e=>e.kind!==`description`&&PT(e)),o=r.filter(e=>PT(e)&&(i||e.kind!==`description`)),s=n[e.id]??xG(e.model,t);return o.map(t=>t.role===`assistant`?{...t,displayTitle:s,ticketOrder:a.get(e.id)??2**53-1}:t.kind===`follow_up`?{...t,displayTitle:`You`,ticketOrder:a.get(e.id)??2**53-1}:{...t,displayTitle:e.title,ticketOrder:a.get(e.id)??2**53-1})}).sort((e,t)=>{if(e.ticket_id===t.ticket_id){let n=SG(e)-SG(t);if(n!==0)return n}let n=yG(e),r=yG(t);if(n!==r)return n.localeCompare(r);if(e.ticket_id!==t.ticket_id&&e.ticketOrder!==t.ticketOrder)return e.ticketOrder-t.ticketOrder;let i=SG(e)-SG(t);return i===0?e.id.localeCompare(t.id):i}).map(e=>{let{ticketOrder:t,...n}=e;return n})},EG=e=>xl(e.tickets,{targetTicketId:e.target_ticket_id,reviewOwnerTicketId:e.review_owner_ticket_id,latestSessionTicketId:e.latest_session_ticket_id}),DG=(0,Y.lazy)(()=>tG(()=>Promise.resolve().then(()=>fJ).then(e=>({default:e.TicketChangesModal})),void 0)),OG=e=>e.replace(/\r\n/g,`
|
|
141
|
+
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return NP.get()},set promptLabel(e){NP.set(e)},get tooMuchOutput(){return FP.get()},set tooMuchOutput(e){FP.set(e)}}}_verifyIntegers(...e){for(ZH of e)if(ZH===1/0||isNaN(ZH)||ZH%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(ZH of e)if(ZH&&(ZH===1/0||isNaN(ZH)||ZH%1!=0||ZH<0))throw Error(`This API only accepts positive integers`)}},$H=Object.create(null);$H.open=`0`,$H.close=`1`,$H.ping=`2`,$H.pong=`3`,$H.message=`4`,$H.upgrade=`5`,$H.noop=`6`;var eU=Object.create(null);Object.keys($H).forEach(e=>{eU[$H[e]]=e});var tU={type:`error`,data:`parser error`},nU=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,rU=typeof ArrayBuffer==`function`,iU=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,aU=({type:e,data:t},n,r)=>nU&&t instanceof Blob?n?r(t):oU(t,r):rU&&(t instanceof ArrayBuffer||iU(t))?n?r(t):oU(new Blob([t]),r):r($H[e]+(t||``)),oU=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function sU(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var cU;function lU(e,t){if(nU&&e.data instanceof Blob)return e.data.arrayBuffer().then(sU).then(t);if(rU&&(e.data instanceof ArrayBuffer||iU(e.data)))return t(sU(e.data));aU(e,!1,e=>{cU||=new TextEncoder,t(cU.encode(e))})}var uU=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,dU=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)dU[uU.charCodeAt(e)]=e;var fU=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=dU[e.charCodeAt(r)],o=dU[e.charCodeAt(r+1)],s=dU[e.charCodeAt(r+2)],c=dU[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},pU=typeof ArrayBuffer==`function`,mU=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:gU(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:hU(e.substring(1),t)}:eU[n]?e.length>1?{type:eU[n],data:e.substring(1)}:{type:eU[n]}:tU},hU=(e,t)=>pU?gU(fU(e),t):{base64:!0,data:e},gU=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},_U=``,vU=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{aU(e,!1,e=>{r[a]=e,++i===n&&t(r.join(_U))})})},yU=(e,t)=>{let n=e.split(_U),r=[];for(let e=0;e<n.length;e++){let i=mU(n[e],t);if(r.push(i),i.type===`error`)break}return r};function bU(){return new TransformStream({transform(e,t){lU(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var xU;function SU(e){return e.reduce((e,t)=>e+t.length,0)}function CU(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function wU(e,t){xU||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(SU(n)<1)break;let e=CU(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(SU(n)<2)break;let e=CU(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(SU(n)<8)break;let e=CU(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(tU);break}i=a*2**32+t.getUint32(4),r=3}else{if(SU(n)<i)break;let e=CU(n,i);s.enqueue(mU(a?e:xU.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(tU);break}}}})}function TU(e){if(e)return EU(e)}function EU(e){for(var t in TU.prototype)e[t]=TU.prototype[t];return e}TU.prototype.on=TU.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},TU.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},TU.prototype.off=TU.prototype.removeListener=TU.prototype.removeAllListeners=TU.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks[`$`+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks[`$`+e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks[`$`+e],this},TU.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks[`$`+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,t)}return this},TU.prototype.emitReserved=TU.prototype.emit,TU.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},TU.prototype.hasListeners=function(e){return!!this.listeners(e).length};var DU=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),OU=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),kU=`arraybuffer`;function AU(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var jU=OU.setTimeout,MU=OU.clearTimeout;function NU(e,t){t.useNativeTimers?(e.setTimeoutFn=jU.bind(OU),e.clearTimeoutFn=MU.bind(OU)):(e.setTimeoutFn=OU.setTimeout.bind(OU),e.clearTimeoutFn=OU.clearTimeout.bind(OU))}var PU=1.33;function FU(e){return typeof e==`string`?IU(e):Math.ceil((e.byteLength||e.size)*PU)}function IU(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function LU(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function RU(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function zU(e){let t={},n=e.split(`&`);for(let e=0,r=n.length;e<r;e++){let r=n[e].split(`=`);t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}var BU=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},VU=class extends TU{constructor(e){super(),this.writable=!1,NU(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved(`error`,new BU(e,t,n)),this}open(){return this.readyState=`opening`,this.doOpen(),this}close(){return(this.readyState===`opening`||this.readyState===`open`)&&(this.doClose(),this.onClose()),this}send(e){this.readyState===`open`&&this.write(e)}onOpen(){this.readyState=`open`,this.writable=!0,super.emitReserved(`open`)}onData(e){let t=mU(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved(`packet`,e)}onClose(e){this.readyState=`closed`,super.emitReserved(`close`,e)}pause(e){}createUri(e,t={}){return e+`://`+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(`:`)===-1?e:`[`+e+`]`}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?`:`+this.opts.port:``}_query(e){let t=RU(e);return t.length?`?`+t:``}},HU=class extends VU{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){yU(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,vU(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=LU()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},UU=!1;try{UU=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var WU=UU;function GU(){}var KU=class extends HU{constructor(e){if(super(e),typeof location<`u`){let t=location.protocol===`https:`,n=location.port;n||=t?`443`:`80`,this.xd=typeof location<`u`&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:`POST`,data:e});n.on(`success`,t),n.on(`error`,(e,t)=>{this.onError(`xhr post error`,e,t)})}doPoll(){let e=this.request();e.on(`data`,this.onData.bind(this)),e.on(`error`,(e,t)=>{this.onError(`xhr poll error`,e,t)}),this.pollXhr=e}},qU=class e extends TU{constructor(e,t,n){super(),this.createRequest=e,NU(this,n),this._opts=n,this._method=n.method||`GET`,this._uri=t,this._data=n.data===void 0?null:n.data,this._create()}_create(){var t;let n=AU(this._opts,`agent`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`autoUnref`);n.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch{}if(this._method===`POST`)try{r.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`)}catch{}try{r.setRequestHeader(`Accept`,`*/*`)}catch{}(t=this._opts.cookieJar)==null||t.addCookies(r),`withCredentials`in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;r.readyState===3&&((e=this._opts.cookieJar)==null||e.parseCookies(r.getResponseHeader(`set-cookie`))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status==`number`?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}typeof document<`u`&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved(`error`,e,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(this._xhr===void 0||this._xhr===null)){if(this._xhr.onreadystatechange=GU,t)try{this._xhr.abort()}catch{}typeof document<`u`&&delete e.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved(`data`,e),this.emitReserved(`success`),this._cleanup())}abort(){this._cleanup()}};if(qU.requestsCount=0,qU.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,JU);else if(typeof addEventListener==`function`){let e=`onpagehide`in OU?`pagehide`:`unload`;addEventListener(e,JU,!1)}}function JU(){for(let e in qU.requests)qU.requests.hasOwnProperty(e)&&qU.requests[e].abort()}var YU=(function(){let e=ZU({xdomain:!1});return e&&e.responseType!==null})(),XU=class extends KU{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=YU&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new qU(ZU,this.uri(),e)}};function ZU(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||WU))return new XMLHttpRequest}catch{}if(!t)try{return new OU[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var QU=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,$U=class extends VU{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=QU?{}:AU(this.opts,`agent`,`perMessageDeflate`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`localAddress`,`protocolVersion`,`origin`,`maxPayload`,`family`,`checkServerIdentity`);this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved(`error`,e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:`websocket connection closed`,context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError(`websocket error`,e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;aU(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&DU(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){this.ws!==void 0&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?`wss`:`ws`,t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=LU()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},eW=OU.WebSocket||OU.MozWebSocket,tW={websocket:class extends $U{createSocket(e,t,n){return QU?new eW(e,t,n):t?new eW(e,t):new eW(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends VU{get name(){return`webtransport`}doOpen(){try{this._transport=new WebTransport(this.createUri(`https`),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved(`error`,e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError(`webtransport error`,e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=wU(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=bU();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&DU(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:XU},nW=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,rW=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function iW(e){if(e.length>8e3)throw`URI too long`;let t=e,n=e.indexOf(`[`),r=e.indexOf(`]`);n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,`;`)+e.substring(r,e.length));let i=nW.exec(e||``),a={},o=14;for(;o--;)a[rW[o]]=i[o]||``;return n!=-1&&r!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,`:`),a.authority=a.authority.replace(`[`,``).replace(`]`,``).replace(/;/g,`:`),a.ipv6uri=!0),a.pathNames=aW(a,a.path),a.queryKey=oW(a,a.query),a}function aW(e,t){let n=t.replace(/\/{2,9}/g,`/`).split(`/`);return(t.slice(0,1)==`/`||t.length===0)&&n.splice(0,1),t.slice(-1)==`/`&&n.splice(n.length-1,1),n}function oW(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var sW=typeof addEventListener==`function`&&typeof removeEventListener==`function`,cW=[];sW&&addEventListener(`offline`,()=>{cW.forEach(e=>e())},!1);var lW=class e extends TU{constructor(e,t){if(super(),this.binaryType=kU,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e==`object`&&(t=e,e=null),e){let n=iW(e);t.hostname=n.host,t.secure=n.protocol===`https`||n.protocol===`wss`,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=iW(t.host).host);NU(this,t),this.secure=t.secure==null?typeof location<`u`&&location.protocol===`https:`:t.secure,t.hostname&&!t.port&&(t.port=this.secure?`443`:`80`),this.hostname=t.hostname||(typeof location<`u`?location.hostname:`localhost`),this.port=t.port||(typeof location<`u`&&location.port?location.port:this.secure?`443`:`80`),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:`/engine.io`,agent:!1,withCredentials:!1,upgrade:!0,timestampParam:`t`,rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,``)+(this.opts.addTrailingSlash?`/`:``),typeof this.opts.query==`string`&&(this.opts.query=zU(this.opts.query)),sW&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener(`beforeunload`,this._beforeunloadEventListener,!1)),this.hostname!==`localhost`&&(this._offlineEventListener=()=>{this._onClose(`transport close`,{description:`network connection lost`})},cW.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved(`error`,`No transports available`)},0);return}let t=this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&this.transports.indexOf(`websocket`)!==-1?`websocket`:this.transports[0];this.readyState=`opening`;let n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on(`drain`,this._onDrain.bind(this)).on(`packet`,this._onPacket.bind(this)).on(`error`,this._onError.bind(this)).on(`close`,e=>this._onClose(`transport close`,e))}onOpen(){this.readyState=`open`,e.priorWebsocketSuccess=this.transport.name===`websocket`,this.emitReserved(`open`),this.flush()}_onPacket(e){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`)switch(this.emitReserved(`packet`,e),this.emitReserved(`heartbeat`),e.type){case`open`:this.onHandshake(JSON.parse(e.data));break;case`ping`:this._sendPacket(`pong`),this.emitReserved(`ping`),this.emitReserved(`pong`),this._resetPingTimeout();break;case`error`:let t=Error(`server error`);t.code=e.data,this._onError(t);break;case`message`:this.emitReserved(`data`,e.data),this.emitReserved(`message`,e.data);break}}onHandshake(e){this.emitReserved(`handshake`,e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!==`closed`&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose(`ping timeout`)},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved(`drain`):this.flush()}flush(){if(this.readyState!==`closed`&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved(`flush`)}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name===`polling`&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+=FU(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,DU(()=>{this._onClose(`ping timeout`)},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket(`message`,e,t,n),this}send(e,t,n){return this._sendPacket(`message`,e,t,n),this}_sendPacket(e,t,n,r){if(typeof t==`function`&&(r=t,t=void 0),typeof n==`function`&&(r=n,n=null),this.readyState===`closing`||this.readyState===`closed`)return;n||={},n.compress=!1!==n.compress;let i={type:e,data:t,options:n};this.emitReserved(`packetCreate`,i),this.writeBuffer.push(i),r&&this.once(`flush`,r),this.flush()}close(){let e=()=>{this._onClose(`forced close`),this.transport.close()},t=()=>{this.off(`upgrade`,t),this.off(`upgradeError`,t),e()},n=()=>{this.once(`upgrade`,t),this.once(`upgradeError`,t)};return(this.readyState===`opening`||this.readyState===`open`)&&(this.readyState=`closing`,this.writeBuffer.length?this.once(`drain`,()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(t){if(e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState===`opening`)return this.transports.shift(),this._open();this.emitReserved(`error`,t),this._onClose(`transport error`,t)}_onClose(e,t){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners(`close`),this.transport.close(),this.transport.removeAllListeners(),sW&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=cW.indexOf(this._offlineEventListener);e!==-1&&cW.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};lW.protocol=4;var uW=class extends lW{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState===`open`&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;lW.priorWebsocketSuccess=!1;let r=()=>{n||(t.send([{type:`ping`,data:`probe`}]),t.once(`packet`,e=>{if(!n)if(e.type===`pong`&&e.data===`probe`){if(this.upgrading=!0,this.emitReserved(`upgrading`,t),!t)return;lW.priorWebsocketSuccess=t.name===`websocket`,this.transport.pause(()=>{n||this.readyState!==`closed`&&(l(),this.setTransport(t),t.send([{type:`upgrade`}]),this.emitReserved(`upgrade`,t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error(`probe error`);e.transport=t.name,this.emitReserved(`upgradeError`,e)}}))};function i(){n||(n=!0,l(),t.close(),t=null)}let a=e=>{let n=Error(`probe error: `+e);n.transport=t.name,i(),this.emitReserved(`upgradeError`,n)};function o(){a(`transport closed`)}function s(){a(`socket closed`)}function c(e){t&&e.name!==t.name&&i()}let l=()=>{t.removeListener(`open`,r),t.removeListener(`error`,a),t.removeListener(`close`,o),this.off(`close`,s),this.off(`upgrading`,c)};t.once(`open`,r),t.once(`error`,a),t.once(`close`,o),this.once(`close`,s),this.once(`upgrading`,c),this._upgrades.indexOf(`webtransport`)!==-1&&e!==`webtransport`?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}},dW=class extends uW{constructor(e,t={}){let n=typeof e==`object`?e:t;(!n.transports||n.transports&&typeof n.transports[0]==`string`)&&(n.transports=(n.transports||[`polling`,`websocket`,`webtransport`]).map(e=>tW[e]).filter(e=>!!e)),super(e,n)}};dW.protocol;function fW(e,t=``,n){let r=e;n||=typeof location<`u`&&location,e??=n.protocol+`//`+n.host,typeof e==`string`&&(e.charAt(0)===`/`&&(e=e.charAt(1)===`/`?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=n===void 0?`https://`+e:n.protocol+`//`+e),r=iW(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port=`80`:/^(http|ws)s$/.test(r.protocol)&&(r.port=`443`)),r.path=r.path||`/`;let i=r.host.indexOf(`:`)===-1?r.host:`[`+r.host+`]`;return r.id=r.protocol+`://`+i+`:`+r.port+t,r.href=r.protocol+`://`+i+(n&&n.port===r.port?``:`:`+r.port),r}var pW=typeof ArrayBuffer==`function`,mW=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,hW=Object.prototype.toString,gW=typeof Blob==`function`||typeof Blob<`u`&&hW.call(Blob)===`[object BlobConstructor]`,_W=typeof File==`function`||typeof File<`u`&&hW.call(File)===`[object FileConstructor]`;function vW(e){return pW&&(e instanceof ArrayBuffer||mW(e))||gW&&e instanceof Blob||_W&&e instanceof File}function yW(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(yW(e[t]))return!0;return!1}if(vW(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return yW(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&yW(e[t]))return!0;return!1}function bW(e){let t=[],n=e.data,r=e;return r.data=xW(n,t),r.attachments=t.length,{packet:r,buffers:t}}function xW(e,t){if(!e)return e;if(vW(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=xW(e[r],t);return n}else if(typeof e==`object`&&!(e instanceof Date)){let n={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=xW(e[r],t));return n}return e}function SW(e,t){return e.data=CW(e.data,t),delete e.attachments,e}function CW(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num==`number`&&e.num>=0&&e.num<t.length)return t[e.num];throw Error(`illegal attachments`)}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=CW(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=CW(e[n],t));return e}var wW=r({Decoder:()=>OW,Encoder:()=>DW,PacketType:()=>EW,isPacketValid:()=>FW,protocol:()=>5}),TW=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],EW;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(EW||={});var DW=class{constructor(e){this.replacer=e}encode(e){return(e.type===EW.EVENT||e.type===EW.ACK)&&yW(e)?this.encodeAsBinary({type:e.type===EW.EVENT?EW.BINARY_EVENT:EW.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===EW.BINARY_EVENT||e.type===EW.BINARY_ACK)&&(t+=e.attachments+`-`),e.nsp&&e.nsp!==`/`&&(t+=e.nsp+`,`),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=bW(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},OW=class e extends TU{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e==`function`?{reviver:e}:e)}add(e){let t;if(typeof e==`string`){if(this.reconstructor)throw Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===EW.BINARY_EVENT;n||t.type===EW.BINARY_ACK?(t.type=n?EW.EVENT:EW.ACK,this.reconstructor=new kW(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(vW(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`);else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(EW[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===EW.BINARY_EVENT||r.type===EW.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!jW(a)||a<0)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&!(t.charAt(n)===`,`||n===t.length););r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case EW.CONNECT:return NW(t);case EW.DISCONNECT:return t===void 0;case EW.CONNECT_ERROR:return typeof t==`string`||NW(t);case EW.EVENT:case EW.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&TW.indexOf(t[0])===-1);case EW.ACK:case EW.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},kW=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=SW(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function AW(e){return typeof e==`string`}var jW=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function MW(e){return e===void 0||jW(e)}function NW(e){return Object.prototype.toString.call(e)===`[object Object]`}function PW(e,t){switch(e){case EW.CONNECT:return t===void 0||NW(t);case EW.DISCONNECT:return t===void 0;case EW.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&TW.indexOf(t[0])===-1);case EW.ACK:return Array.isArray(t);case EW.CONNECT_ERROR:return typeof t==`string`||NW(t);default:return!1}}function FW(e){return AW(e.nsp)&&MW(e.id)&&PW(e.type,e.data)}function IW(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var LW=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),RW=class extends TU{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[IW(e,`open`,this.onopen.bind(this)),IW(e,`packet`,this.onpacket.bind(this)),IW(e,`error`,this.onerror.bind(this)),IW(e,`close`,this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState===`open`&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift(`message`),this.emit.apply(this,e),this}emit(e,...t){if(LW.hasOwnProperty(e))throw Error(`"`+e.toString()+`" is a reserved event name`);if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:EW.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth==`function`?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:EW.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved(`connect_error`,e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved(`disconnect`,e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case EW.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,Error(`It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)`));break;case EW.EVENT:case EW.BINARY_EVENT:this.onevent(e);break;case EW.ACK:case EW.BINARY_ACK:this.onack(e);break;case EW.DISCONNECT:this.ondisconnect();break;case EW.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]==`string`&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:EW.ACK,id:e,data:r}))}}onack(e){let t=this.acks[e.id];typeof t==`function`&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved(`connect`)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose(`io server disconnect`)}destroy(){this.subs&&=(this.subs.forEach(e=>e()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:EW.DISCONNECT}),this.destroy(),this.connected&&this.onclose(`io client disconnect`),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function zW(e){e||={},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}zW.prototype.duration=function(){var e=this.ms*this.factor**+ this.attempts++;if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0},zW.prototype.reset=function(){this.attempts=0},zW.prototype.setMin=function(e){this.ms=e},zW.prototype.setMax=function(e){this.max=e},zW.prototype.setJitter=function(e){this.jitter=e};var BW=class extends TU{constructor(e,t){super(),this.nsps={},this.subs=[],e&&typeof e==`object`&&(t=e,e=void 0),t||={},t.path=t.path||`/socket.io`,this.opts=t,NU(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor??.5),this.backoff=new zW({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState=`closed`,this.uri=e;let n=t.parser||wW;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)==null||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)==null||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)==null||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf(`open`))return this;this.engine=new dW(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=IW(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=IW(t,`error`,i);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(Error(`timeout`)),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState=`open`,this.emitReserved(`open`);let e=this.engine;this.subs.push(IW(e,`ping`,this.onping.bind(this)),IW(e,`data`,this.ondata.bind(this)),IW(e,`error`,this.onerror.bind(this)),IW(e,`close`,this.onclose.bind(this)),IW(this.decoder,`decoded`,this.ondecoded.bind(this)))}onping(){this.emitReserved(`ping`)}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose(`parse error`,e)}}ondecoded(e){DU(()=>{this.emitReserved(`packet`,e)},this.setTimeoutFn)}onerror(e){this.emitReserved(`error`,e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new RW(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let e of t)if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose(`forced close`)}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)==null||n.close(),this.backoff.reset(),this._readyState=`closed`,this.emitReserved(`close`,e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(`reconnect_failed`),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved(`reconnect_attempt`,e.backoff.attempts),!e.skipReconnect&&e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved(`reconnect_error`,t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(`reconnect`,e)}},VW={};function HW(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=fW(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=VW[i]&&a in VW[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new BW(r,t):(VW[i]||(VW[i]=new BW(r,t)),c=VW[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(HW,{Manager:BW,Socket:RW,io:HW,connect:HW});var UW=((e=M)=>HW(e))(),WW=({label:e,onClick:t,children:n})=>(0,Z.jsx)(q,{type:`button`,"aria-label":e,onClick:t,variant:`outline`,size:`icon-sm`,className:`bg-secondary/60`,children:n}),GW=({exitCode:e,signal:t})=>t>0?`[archon] Shell exited with signal ${t}`:`[archon] Shell exited with code ${e}`,KW=({createSession:e,isExpanded:t,isVisible:n,onClose:r,onToggleExpanded:i,className:a=``,ariaLabel:o=`Terminal`,title:s=`Terminal`,closeLabel:c=`Close terminal`,headerMeta:l})=>{let u=(0,Y.useRef)(null),d=(0,Y.useRef)(null),f=(0,Y.useRef)(null),p=(0,Y.useRef)(null),m=(0,Y.useRef)(e),h=(0,Y.useRef)(!1),[g,_]=(0,Y.useState)(null),[v,y]=(0,Y.useState)(!0);return(0,Y.useEffect)(()=>{m.current=e},[e]),(0,Y.useEffect)(()=>{if(!u.current)return;let e=new QH({cursorBlink:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`,fontSize:13,theme:{background:`#0b0d14`,foreground:`#d8deef`,cursor:`#c4b5fd`}}),t=new EP,n=null,r=!1;e.loadAddon(t),e.open(u.current),d.current=e,f.current=t;let i=()=>{let e=p.current;!e||h.current||(h.current=!0,wT(e))};window.addEventListener(`pagehide`,i),window.addEventListener(`beforeunload`,i);let a=()=>{p.current&&UW.emit(`terminal:resize`,{sessionId:p.current,cols:e.cols,rows:e.rows})},o=()=>{!u.current||r||(t.fit(),a())},s=t=>{t.sessionId===p.current&&(y(!1),window.setTimeout(()=>{o(),e.focus()},0))},c=t=>{t.sessionId===p.current&&(y(!1),e.write(t.data))},l=t=>{t.sessionId===p.current&&(e.writeln(``),e.writeln(GW(t)))},g=t=>{t.sessionId&&t.sessionId!==p.current||(y(!1),_(t.message),e.writeln(``),e.writeln(`[archon] ${t.message}`))};UW.on(`terminal:ready`,s),UW.on(`terminal:data`,c),UW.on(`terminal:exit`,l),UW.on(`terminal:error`,g);let v=e.onData(e=>{p.current&&UW.emit(`terminal:input`,{sessionId:p.current,input:e})});return typeof ResizeObserver==`function`&&(n=new ResizeObserver(()=>{o()}),n.observe(u.current)),window.setTimeout(()=>{o()},0),m.current().then(e=>{r||(p.current=e.session_id,UW.emit(`terminal:join`,{sessionId:e.session_id}))}).catch(t=>{if(r)return;y(!1);let n=t instanceof Error?t.message:`Unable to open the terminal right now.`;_(n),e.writeln(``),e.writeln(`[archon] ${n}`)}),()=>{r=!0,window.removeEventListener(`pagehide`,i),window.removeEventListener(`beforeunload`,i),p.current&&(h.current||UW.emit(`terminal:destroy`,{sessionId:p.current})),n?.disconnect(),v.dispose(),UW.off(`terminal:ready`,s),UW.off(`terminal:data`,c),UW.off(`terminal:exit`,l),UW.off(`terminal:error`,g),e.dispose(),d.current=null,f.current=null,p.current=null}},[]),(0,Y.useEffect)(()=>{if(!n)return;let e=window.setTimeout(()=>{f.current?.fit(),d.current&&p.current&&(UW.emit(`terminal:resize`,{sessionId:p.current,cols:d.current.cols,rows:d.current.rows}),d.current.focus())},0);return()=>{window.clearTimeout(e)}},[t,n]),(0,Z.jsxs)(gu,{"aria-label":o,"data-terminal-pane":`true`,className:`flex min-h-0 flex-1 flex-col gap-0 overflow-hidden rounded-xl border-border bg-[#0c1119] ${a}`.trim(),children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-b border-border bg-card/80 px-3 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`flex h-8 w-8 items-center justify-center rounded-lg bg-primary/12 text-primary`,children:(0,Z.jsx)(Ic,{className:`h-4 w-4`})}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:s}),l&&(0,Z.jsx)(`div`,{className:`mt-1 min-w-0 text-xs text-muted-foreground`,children:l})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[v&&!g&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Opening terminal...`}),g&&(0,Z.jsx)(`span`,{className:`max-w-56 truncate text-xs text-red-300`,children:g}),(0,Z.jsx)(WW,{label:t?`Collapse terminal`:`Expand terminal`,onClick:i,children:t?(0,Z.jsx)(vf,{className:`h-4 w-4`}):(0,Z.jsx)(yf,{className:`h-4 w-4`})}),(0,Z.jsx)(WW,{label:c,onClick:r,children:(0,Z.jsx)(Ve,{className:`h-4 w-4`})})]})]}),(0,Z.jsx)(`div`,{ref:u,"data-testid":`terminal-viewport`,onClick:()=>d.current?.focus(),className:`min-h-0 flex-1 overflow-hidden bg-[#0b0d14] pb-4`})]})},qW=({actions:e,activeAction:t=null,disableWhenActive:n=!1,className:r,heading:i,headingClassName:a,actionsClassName:o,showDisabledReason:s=!1,disabledReasonClassName:c,error:l,errorClassName:u,leadingContent:d,renderAction:f})=>{if(e.length===0&&!d)return null;let p=e.find(e=>e.disabled&&e.disabledReason)?.disabledReason??null;return(0,Z.jsxs)(`div`,{className:r,children:[i&&(0,Z.jsx)(`div`,{className:a,children:i}),(0,Z.jsxs)(`div`,{className:o,children:[d,e.map(e=>{let r=t===e.id,i=e.disabled||n&&t!==null;return f({action:e,label:r?e.pendingLabel:e.label,disabled:i,title:e.disabledReason??e.title,ariaLabel:e.ariaLabel})})]}),s&&p&&(0,Z.jsx)(`p`,{className:c,children:p}),l&&(0,Z.jsx)(`p`,{className:u,children:l})]})},JW=({id:e,label:t,pendingLabel:n,ariaLabel:r=t,title:i,disabled:a=!1,disabledReason:o=null})=>({id:e,label:t,pendingLabel:n,ariaLabel:r,title:i,disabled:a,disabledReason:o}),YW=(e,t={})=>{let{isEditing:n=!1,includePlanAdvance:r=!0,hideAdvanceWhenBlocked:i=!1,hasOpenBlockers:a=!1,canRun:o=!0,canStopRun:s=!0,canPauseBuild:c=!0,canResumeBuild:l=!0,runDisabled:u=!1,runDisabledReason:d,buildLabel:f=`Build`,reviewLabel:p=`Review`}=t,m=ww(e.state),h=m?Fw(e,m):!1,g=Iw(e),_=e.bundle?.branch??e.branch,v=e.has_worktree??!!_,y=e.worktree_bundle_id!==null,b=e.state===`plan`&&e.agent_status===`running`,x=d??(e.has_run_config===!1?`No run config is available for this project.`:null),S=[];return r&&e.state===`plan`&&!e.parked_at&&S.push(JW({id:`build`,label:f,pendingLabel:`Building...`,ariaLabel:f,disabled:!h,disabledReason:g})),e.state===`build`&&!e.parked_at&&!(i&&a)&&S.push(JW({id:`review`,label:p,pendingLabel:`Starting review...`,ariaLabel:p,disabled:!h,disabledReason:g})),_&&v&&!b&&!n&&!y&&e.is_running!==!0&&o&&S.push(JW({id:`run`,label:`Run`,pendingLabel:`Starting run...`,ariaLabel:`Run`,disabled:u||!!x,disabledReason:x,title:u?x??`Stop the currently running ticket before starting another run.`:void 0})),_&&!n&&!y&&e.is_running===!0&&s&&S.push(JW({id:`stop-run`,label:`Stop Run`,pendingLabel:`Stopping run...`,ariaLabel:`Stop Run`,title:`Stop the currently running ticket.`,disabled:!1,disabledReason:null})),!n&&Dw(e)&&e.agent_status===`running`&&e.session_id&&c&&S.push(JW({id:`pause-build`,label:`Pause Build`,pendingLabel:`Pausing build...`,ariaLabel:`Pause Build`,title:`Pause the build session. You can resume it later.`,disabled:!1,disabledReason:null})),!n&&Dw(e)&&e.agent_status===`stopped`&&e.session_id&&l&&S.push(JW({id:`resume-build`,label:`Resume`,pendingLabel:`Resuming build...`,ariaLabel:`Resume`,disabled:!1,disabledReason:null})),S},XW=(e,t={})=>{let n=e.state===`plan`,r=e.bundle?.branch??e.branch,i=e.has_worktree??!!r;return{isPlan:n,hasWorktree:i,disabledReason:e.agent_status===`running`?n?`Wait for planning to finish before sending another message.`:`Wait for the current build to finish before sending a follow-up prompt.`:t.requireWorktree===!0&&!n&&!i?`Worktree not ready yet.`:null,heading:n?`Planning follow-up`:`Ticket follow-up`,description:n?`Ask the agent to refine this plan.`:`Send a follow-up prompt for this ticket.`,placeholder:n?`Ask the agent to refine this plan...`:`Send a follow-up for this ticket...`}},ZW=(e,t,n={})=>{let r=e.tool===`opencode`||n.persistPlanSettings===!0,i=r&&t.model?t.model:null,a=r&&t.model&&t.variant?t.variant:null,o=r?t.skills:[],s=e.skills??[],c=o.length!==s.length||o.some((e,t)=>e!==s[t]);return{model:i,variant:a,skills:o,shouldPersist:r&&(i!==e.model||a!==e.variant||c)}},QW=`modulepreload`,$W=function(e){return`/`+e},eG={},tG=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=$W(t,n),t in eG)return;eG[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:QW,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},nG=(0,Y.lazy)(()=>tG(()=>Promise.resolve().then(()=>fJ).then(e=>({default:e.TicketChangesModal})),void 0)),rG=(0,Y.lazy)(()=>tG(()=>import(`./TestsDialog-CzG_2qwn.js`).then(e=>({default:e.TestsDialog})),__vite__mapDeps([0,1,2]))),iG=`(min-width: 1280px)`,aG=e=>typeof window>`u`||typeof window.matchMedia!=`function`?!0:window.matchMedia(e).matches,oG=e=>{let[t,n]=(0,Y.useState)(()=>aG(e));return(0,Y.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let t=window.matchMedia(e),r=()=>{n(t.matches)};return r(),t.addEventListener(`change`,r),()=>{t.removeEventListener(`change`,r)}},[e]),t},sG=({onClose:e})=>{let{t}=X(`common`);return(0,Z.jsx)(pu,{onClose:e,overlayClassName:`z-[70] bg-black/30 p-[5vh]`,panelClassName:`flex h-full w-full max-w-none items-center justify-center rounded-2xl border border-border bg-card p-6 shadow-2xl`,children:(0,Z.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:t(`ticketModal.loadingDiff`)})})},cG=({ariaLabel:e,title:t,closeAriaLabel:n,className:r,showTopSpacer:i=!0,description:a,onClose:o,...s})=>(0,Z.jsxs)(`aside`,{className:`min-h-0 flex flex-col gap-3 overflow-hidden${r?` ${r}`:``}`,"aria-label":e,children:[i?(0,Z.jsx)(`div`,{"aria-hidden":`true`,className:`h-9 shrink-0`}):null,(0,Z.jsx)(WN,{...s,header:({showThinkingControl:e})=>(0,Z.jsxs)(`div`,{className:`flex w-full items-center justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,Z.jsx)(`h3`,{className:`text-sm font-semibold text-foreground`,children:t}),e]}),a?(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:a}):null]}),(0,Z.jsx)(q,{type:`button`,variant:`ghost`,size:`icon`,"aria-label":n,onClick:o,children:(0,Z.jsx)(Ve,{className:`h-4 w-4`})})]})})]}),lG=(e,t)=>e?t.find(t=>t.id===e)?.label??e:null,uG=({ticket:e,allTickets:t=[],dependencies:n=[],bundles:r=[],projectTestCommands:i=[],showModelSelector:a=!1,availableModels:o=[],availableSkills:s=[],projectBranchState:c=null,projectMemoryEnabled:l=!1,runDisabled:u=!1,runDisabledReason:d,onClose:f,onCreateBundle:p,onDeleteBundle:m,onRefreshBundles:h,onUpdate:g,onDeleteDependency:_,onAdvance:v,onBuildChain:y,onRun:b,onOpenIde:x,onStop:S,onStopBuild:C,onStopBuildChain:w,onResumeBuild:T,onFollowUp:E,onRequestTicketRefresh:D,onProjectMemorySuggestionsChanged:O})=>{let{t:k}=X(`common`),[A,j]=(0,Y.useState)(null),[M,N]=(0,Y.useState)(!1),[P,F]=(0,Y.useState)(!1),[I,L]=(0,Y.useState)(!1),[R,z]=(0,Y.useState)(!1),[ee,te]=(0,Y.useState)(!1),[ne,re]=(0,Y.useState)(!1),[B,ie]=(0,Y.useState)(``),[V,H]=(0,Y.useState)(!1),[ae,oe]=(0,Y.useState)(!1),[se,ce]=(0,Y.useState)(!1),[le,ue]=(0,Y.useState)(0),[de,fe]=(0,Y.useState)(!1),[pe,me]=(0,Y.useState)(!1),[W,he]=(0,Y.useState)(null),G=A??e,[ge,_e]=(0,Y.useState)(G.model??``),[ve,ye]=(0,Y.useState)(G.variant??``),[be,xe]=(0,Y.useState)(G.skills??[]),[K,Se]=(0,Y.useState)(()=>lG(G.model,o)??`Agent`),Ce=(0,Y.useRef)(G.id),we=(0,Y.useRef)(null),Te=(0,Y.useRef)(null),Ee=(0,Y.useRef)(!1),De=(0,Y.useRef)(G.id),Oe=(0,Y.useRef)(G.build_completed_at),ke=oG(iG),[Ae,je]=(0,Y.useState)(!1),[Me,Ne]=(0,Y.useState)({model:G.model,variant:G.variant,skills:G.skills??[]}),Pe=G.state===`plan`,Fe=Tw(G.state),Ie=G.worktree_bundle_id!==null,Le=Pe&&G.agent_status===`running`,Re=Pe&&G.agent_status===`error`,ze=Pe&&!Le||M,Be=async e=>{let t=await Zt(G.id,G.project_id,e);return j(t),g?.(t),h&&await h(),t},Ve=async e=>{try{await Be(e),f()}catch(e){Q.error(e instanceof Error?e.message:`Unable to update the ticket right now.`,{id:`ticket-save-error`})}},He=async e=>{try{if(await Be(e),!v){f();return}await v(),f()}catch(e){Q.error(e instanceof Error?e.message:`Unable to update the ticket right now.`,{id:`ticket-save-error`})}},Ue=async()=>{!v||it?.disabled||(await v(),f())},We=e=>{if(e===`review`){Ue();return}if(e===`run`){b?.();return}if(e===`stop-run`){S?.();return}if(e===`pause-build`){C?.();return}e===`resume-build`&&T?.()},Ge=async e=>{try{if(await Be(e),!y){f();return}await y(),f()}catch(e){Q.error(e instanceof Error?e.message:`Unable to update the ticket right now.`,{id:`ticket-save-error`})}},Ke=Pe?G.planning_session_id:G.session_id,qe=Ke?Ke.startsWith(`ses_`)?`opencode --session ${Ke}`:`claude --resume ${Ke}`:null,Je=G.bundle?.branch??G.branch,Ye=G.has_worktree??!!Je,Xe=`Stop Build Chain`,Ze=new Map(t.map(e=>[e.id,e])),Qe=n.filter(e=>e.blocker_ticket_id===G.id),$e=n.filter(e=>e.dependent_ticket_id===G.id),et=eT(G,Ze,n),J=et.pendingBuildChainOrder.length>0?`Will build in order: ${et.pendingBuildChainOrder.map(e=>e.title).join(` -> `)}`:`All tickets in this chain have already finished build.`,tt=et.skippedBuildChainCount>0?`Skips ${et.skippedBuildChainCount} ticket${et.skippedBuildChainCount===1?``:`s`} that already finished build.`:null,nt=et.hasOpenBlockers,rt=YW(G,{isEditing:ze,includePlanAdvance:!1,hideAdvanceWhenBlocked:!0,hasOpenBlockers:nt,canRun:!!b,canStopRun:!!S,canPauseBuild:!!C,canResumeBuild:!!T,runDisabled:u,runDisabledReason:d,reviewLabel:`Review Bundle`}),it=rt.find(e=>e.id===`review`)??null,at=Aw(G),ot=G.build_chain?.active_ticket_id?`Currently building ${Ze.get(G.build_chain.active_ticket_id)?.title??`Unknown ticket`}.`:`Build chain is active.`,st=G.build_chain&&G.build_chain.queued_ticket_ids.length>0?`Queued next: ${G.build_chain.queued_ticket_ids.map(e=>Ze.get(e)?.title??`Unknown ticket`).join(` -> `)}`:`No additional tickets are queued after the current build.`,ct=Pe&&!!v&&!et.hasOpenBlockers,lt=Pe&&!!y&&et.canStartBuildChain,ut=!!G.project_id&&!Pe&&!Ie,dt=Pe,ft=Ie&&!Pe,pt=!!G.project_id&&!!Je&&Ye&&!ze&&!Le&&!Ie,mt=!!G.project_id&&Ye&&!ze&&!Le&&!!x&&!Ie,ht=!!G.project_id&&i.length>0&&Ye,gt=ut&&!R,_t=k(`workspaceControls.openTerminalAriaLabel`),vt=ut&&ne,yt=B.trim(),bt=!ze&&!Le&&G.state!==`plan`&&Ye&&!!E,xt=dt&&ae,St=ft&&se,Ct=(G.planning_context?.open_questions.length??0)>0,wt=bt&&a&&G.tool===`opencode`,Tt=k(`ticketModal.discardUnsavedDescription`),Et=o.find(e=>e.id===ge)??null,Dt=G.agent_status===`running`,Ot=uT(G,{allTickets:t,preferBundleReviewStatus:!0}),kt=G.skills??[],At=XW(G),jt=Dt?At.disabledReason??void 0:void 0,Mt=Le?At.disabledReason??void 0:void 0,Nt=[...Le?[]:[{label:`Worktree`,value:Je??``}],{label:`Session`,value:qe??``},...Le?[{label:G.bundle?.kind===`project_root`?`Project root branch`:`Bundle`,value:(G.bundle?.kind,G.bundle?Dl(G.bundle):``)}]:Pe?[{label:`Bundle`,value:G.bundle?Dl(G.bundle):``},{label:`Model`,value:G.model??``},{label:`Variant`,value:G.variant??``},{label:`Skills`,value:kt.length>0?`${kt.length} skill${kt.length===1?``:`s`}`:``},{label:`Initiative`,value:G.planning_context?.initiative_prompt??``}]:[]],Pt=Le?{model:G.model??``,variant:G.variant??``,skills:kt}:null,Ft=dt&&ae,It=ft&&se,Lt=(Ft||It)&&!ke,Rt=Ft&&!Lt,zt=Rt||It&&!Lt,Bt=Pe&&(Ft||!ke),Vt=R?`flex h-[92vh] w-[96vw] max-w-7xl flex-col gap-3 overflow-hidden rounded-2xl border border-border bg-card p-4 shadow-2xl sm:p-5 lg:p-6`:zt?`flex h-[92vh] w-[98vw] max-w-[100rem] flex-col gap-3 overflow-visible rounded-2xl border border-border bg-card p-4 shadow-2xl sm:p-5 lg:p-6`:Lt?`flex h-[92vh] w-[98vw] max-w-6xl flex-col gap-3 overflow-hidden rounded-2xl border border-border bg-card p-4 shadow-2xl sm:p-5 lg:p-6`:`flex h-[92vh] w-[96vw] max-w-6xl flex-col gap-3 overflow-visible rounded-2xl border border-border bg-card p-4 shadow-2xl sm:p-5 lg:p-6`,Ht=R&&!ee?`grid min-h-0 flex-1 grid-cols-1 gap-3 lg:grid-cols-2`:zt?`grid min-h-0 flex-1 grid-cols-1 gap-3 xl:grid-cols-[minmax(0,1fr)_minmax(30rem,1fr)]`:`flex min-h-0 flex-1 flex-col`,Ut=()=>{re(!0),z(e=>(e&&te(!1),!e))},Wt=()=>{z(!1),te(!1),re(!1),D?.(G.id)},Gt=()=>{me(!1),he(null)},Kt=()=>{me(!1),W===`cancel_edit`&&!Pe?N(!1):f(),he(null)},qt=()=>{if(!ze){f();return}if(!de){f();return}he(`close_modal`),me(!0)},Jt=()=>{if(Pe){qt();return}if(!de){N(!1);return}he(`cancel_edit`),me(!0)};(0,Y.useEffect)(()=>{j(t=>!t||t.id!==e.id||e.updated_at>=t.updated_at?null:t)},[e]),(0,Y.useEffect)(()=>{if(De.current!==G.id){De.current=G.id,Oe.current=G.build_completed_at;return}if(Oe.current===G.build_completed_at)return;let e=Oe.current;Oe.current=G.build_completed_at,G.build_completed_at&&G.build_completed_at!==e&&ue(e=>e+1)},[G.build_completed_at,G.id]),(0,Y.useEffect)(()=>{_e(G.model??``),ye(G.variant??``),xe(G.skills??[])},[G.model,G.skills,G.variant]),(0,Y.useEffect)(()=>{Ce.current!==G.id&&(Ce.current=G.id,Se(lG(G.model,o)??`Agent`))},[o,G.id,G.model]),(0,Y.useEffect)(()=>{let e=lG(G.model,o);e&&Se(e)},[o,G.model]),(0,Y.useEffect)(()=>{Ne({model:G.model,variant:G.variant,skills:G.skills??[]})},[G.id,G.model,G.skills,G.variant]),(0,Y.useEffect)(()=>{ze||(fe(!1),me(!1),he(null))},[ze]),(0,Y.useEffect)(()=>{de||(me(!1),he(null))},[de]),(0,Y.useEffect)(()=>{if(!Pe){we.current=null,Ee.current=!1;return}let e=we.current!==G.id,t=!Ee.current&&Ct;(e&&Ct||t)&&oe(!0),we.current=G.id,Ee.current=Ct},[Ct,Pe,G.id]),(0,Y.useEffect)(()=>{if(!ft){Te.current=null;return}Te.current!==G.id&&ce(!1),Te.current=G.id},[ft,G.id]);let Yt=async(e,t,n)=>{je(!0);try{let r=await Zt(G.id,G.project_id,{model:e.trim()||null,variant:t.trim()||null,skills:n});j(r),g?.(r)}catch(e){_e(G.model??``),ye(G.variant??``),xe(G.skills??[]),Q.error(e instanceof Error?e.message:`Unable to update the ticket right now.`,{id:`ticket-save-error`})}finally{je(!1)}},Xt=e=>{let t=(o.find(t=>t.id===e)??null)?.variants.includes(ve)?ve:``;_e(e),ye(t),Yt(e,t,be)},Qt=e=>{ye(e),Yt(ge,e,be)},$t=e=>{xe(e),Yt(ge,ve,e)},en=async()=>{if(!(!E||V||Dt||!yt)){H(!0);try{await E(yt),ie(``)}finally{H(!1)}}},tn=async()=>{if(!(V||Le||!yt||!xt)){H(!0);try{let e=ZW(G,Me,{persistPlanSettings:!0});if(e.shouldPersist){let t=await Zt(G.id,G.project_id,{model:e.model,variant:e.variant,skills:e.skills});j(t),g?.(t)}let t=await Sn(G.id,G.project_id,yt);j(t),g?.(t),ie(``)}finally{H(!1)}}},nn=(G.messages??[]).filter(PT).map(e=>e.role===`assistant`?{...e,displayTitle:K}:e.kind===`follow_up`?{...e,displayTitle:k(`chatView.user.you`)}:e),rn=(G.messages??[]).filter(e=>(e.kind===`planning_follow_up`||e.kind===`planning_response`)&&PT(e)).map(e=>e.role===`assistant`?{...e,displayTitle:K}:e.kind===`planning_follow_up`?{...e,displayTitle:k(`chatView.user.you`)}:e),an=Ft?(0,Z.jsx)(cG,{ariaLabel:k(`ticketModal.planningChatAriaLabel`),title:k(`ticketModal.planningChatTitle`),closeAriaLabel:k(`ticketModal.closePlanningChatAriaLabel`),className:Lt?`absolute inset-x-4 bottom-4 top-[4.25rem] z-30 rounded-2xl border border-border bg-card shadow-2xl sm:inset-x-auto sm:right-5 sm:w-[min(34rem,calc(100%-2.5rem))] lg:right-6`:void 0,showTopSpacer:!Lt,description:Ct?(0,Z.jsx)(`p`,{children:k(`ticketModal.planningOpenQuestions`,{count:G.planning_context?.open_questions.length??0})}):void 0,projectId:G.project_id,followUpTicketId:null,messages:rn,internalLog:G.agent_log??null,currentThinkingMessageId:G.agent_message_id??null,previousThinkingLog:G.previous_agent_log??null,previousThinkingMessageId:G.previous_agent_message_id??null,streamingResponse:G.streaming_response??null,isRunning:G.agent_status===`running`,canShowComposer:xt,pendingAgentTitle:K,composerTheme:Fe,followUpPlaceholder:k(`ticketModal.planningFollowUpPlaceholder`),emptyStateText:null,autoFocusComposer:ae,followUpPrompt:B,isSendingFollowUp:V,followUpDisabledReason:Mt,onFollowUpPromptChange:ie,onFollowUpKeyDown:e=>{e.key!==`Enter`||e.shiftKey||Le||V||(e.preventDefault(),tn())},onFollowUpSubmit:()=>{tn()},onClose:()=>{oe(!1)}}):It?(0,Z.jsx)(cG,{ariaLabel:k(`ticketModal.ticketChatAriaLabel`),title:k(`ticketModal.ticketChatTitle`),closeAriaLabel:k(`ticketModal.closeTicketChatAriaLabel`),className:Lt?`absolute inset-x-4 bottom-4 top-[4.25rem] z-30 rounded-2xl border border-border bg-card shadow-2xl sm:inset-x-auto sm:right-5 sm:w-[min(34rem,calc(100%-2.5rem))] lg:right-6`:void 0,showTopSpacer:!Lt,projectId:G.project_id,followUpTicketId:G.id,messages:nn,internalLog:G.agent_log??null,currentThinkingMessageId:G.agent_message_id??null,previousThinkingLog:G.previous_agent_log??null,previousThinkingMessageId:G.previous_agent_message_id??null,streamingResponse:G.streaming_response??null,isRunning:G.agent_status===`running`,canShowComposer:St,pendingAgentTitle:K,composerTheme:Fe,autoFocusComposer:se,followUpPrompt:B,isSendingFollowUp:V,followUpDisabledReason:jt,followUpComposerControls:wt?(0,Z.jsx)(CP,{model:ge,variant:ve,skills:be,showModelSelector:!0,showSkillsSelector:!0,availableModels:o,availableSkills:s,selectedModel:Et,onModelChange:Xt,onVariantChange:Qt,onSkillsChange:$t,modelSelectId:`ticket-follow-up-model`,variantSelectId:`ticket-follow-up-variant`,skillsSelectId:`ticket-follow-up-skills`,disabled:Ae}):void 0,onFollowUpPromptChange:ie,onFollowUpKeyDown:e=>{e.key!==`Enter`||e.shiftKey||Dt||V||(e.preventDefault(),en())},onFollowUpSubmit:()=>{en()},onClose:()=>{ce(!1)}}):null;return(0,Z.jsx)(pu,{onClose:qt,overlayClassName:`bg-black/60`,panelClassName:Vt,renderContent:({closeButton:e})=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`absolute right-4 top-4 z-10 flex items-center gap-2 sm:right-5 sm:top-5 lg:right-6 lg:top-6`,children:[pt&&G.diff_stats&&(0,Z.jsx)(kc,{stats:G.diff_stats,showFiles:!0,className:`text-xs`}),pt&&(0,Z.jsxs)(q,{type:`button`,"aria-label":k(`workspaceControls.changes`),onClick:()=>{D?.(G.id),F(!0)},variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(jc,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:k(`workspaceControls.changes`)})]}),ht&&(0,Z.jsxs)(q,{type:`button`,"aria-label":k(`workspaceControls.tests`),onClick:()=>{L(!0)},variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(Ac,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:k(`workspaceControls.tests`)})]}),mt&&(0,Z.jsxs)(q,{type:`button`,"aria-label":k(`workspaceControls.openIde`),onClick:()=>{x?.()},variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(Mc,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:k(`workspaceControls.openIde`)})]}),gt&&(0,Z.jsxs)(q,{type:`button`,"aria-label":_t,"aria-pressed":R,onClick:Ut,variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(Ic,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:k(`workspaceControls.terminal`)})]}),(dt||ft)&&(0,Z.jsxs)(q,{type:`button`,"aria-label":k(`workspaceControls.chat`),"aria-pressed":Pe?ae:se,onClick:()=>{if(Pe){oe(e=>!e);return}ce(e=>!e)},variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(nm,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:k(`workspaceControls.chat`)})]}),e]}),(0,Z.jsxs)(`div`,{"data-testid":`ticket-modal-layout`,"data-terminal-mode":R?ee?`expanded`:`split`:`closed`,"data-side-chat-mode":zt?`inline`:Lt?`overlay`:`closed`,className:Ht,children:[(0,Z.jsxs)(`div`,{className:`min-h-0 flex flex-1 flex-col gap-3 overflow-hidden`,children:[ze?(0,Z.jsxs)(Z.Fragment,{children:[Re&&G.agent_log&&(0,Z.jsxs)(`div`,{className:`rounded-lg border border-red-500/40 bg-destructive/15 px-3 py-2 text-xs text-red-300`,children:[(0,Z.jsx)(`span`,{className:`font-semibold`,children:k(`ticketModal.planningFailedPrefix`)}),G.agent_log]}),(0,Z.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,Z.jsx)(DT,{tool:G.tool,className:`text-[11px]`})}),(0,Z.jsx)(OT,{externalSource:G.external_source}),(0,Z.jsx)(aP,{heading:`Edit Ticket`,bundles:r,initialTitle:G.title,initialDescription:G.description??``,initialModel:G.model??``,initialVariant:G.variant??``,initialSkills:G.skills??[],initialWorktreeBundleId:G.worktree_bundle_id,projectBranchState:c,projectId:G.project_id,stackConfigurationSections:Rt&&!Bt,preferWideBundleSelector:Rt&&Bt,agentSettingsPresentation:Bt?`popover`:`panel`,showModelSelector:a,availableModels:o,availableSkills:s,onAgentSettingsChange:Ne,onCreateBundle:p,onDeleteBundle:m,onRefreshBundles:h,onCancel:Jt,onDirtyChange:fe,titleInputId:`edit-title`,descriptionInputId:`edit-description`,bundleSelectId:`edit-ticket-bundle`,modelSelectId:`edit-model`,variantSelectId:`edit-variant`,skillsSelectId:`edit-skills`,showEmptyBundleOption:!1,planAction:{label:`Plan`,onClick:async({title:e,description:t,model:n,variant:r,skills:i,worktree_bundle_id:a})=>{let o=await Zt(G.id,G.project_id,{title:e,description:t,model:n,variant:r,skills:i,worktree_bundle_id:a});g?.(o),f(),await Cn(G.id,G.project_id)}},primaryAction:{label:`Save`,variant:ct?`subtle`:`brand`,onClick:Ve},secondaryAction:ct?{label:`Save & Build`,variant:`brand`,showAdvanceIcon:!0,onClick:He}:void 0,tertiaryAction:lt?{label:`Save & Build Chain`,variant:`brand`,showAdvanceIcon:!0,onClick:Ge}:void 0,beforeActionsContent:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,Z.jsx)(gP,{projectId:G.project_id,ticketId:G.id,memoryEnabled:l,refreshKey:le,onSuggestionsChanged:O}),et.hasDependents&&(0,Z.jsx)(FT,{summary:J,detail:tt}),(0,Z.jsx)(qN,{blocks:Qe,blockedBy:$e,resolveTicket:e=>Ze.get(e),onDeleteDependency:_})]}),footerLeadingContent:de?(0,Z.jsx)(U,{variant:`outline`,className:`border-amber-500/35 bg-amber-500/10 text-amber-200`,children:`Unsaved changes`}):null},`${G.id}:${G.updated_at}:${G.title}:${G.description}`)]}):(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 overflow-hidden`,children:[(0,Z.jsx)(`div`,{className:`sticky top-0 -my-1 bg-card py-1 pr-12 sm:pr-24`,children:(0,Z.jsxs)(`div`,{className:`min-w-0 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:G.title}),(0,Z.jsx)(DT,{tool:G.tool,className:`text-[11px]`}),(Ot===`building`||Ot===`done`)&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[G.is_running&&(0,Z.jsx)(`span`,{className:`w-2 h-2 rounded-full bg-emerald-400 animate-pulse flex-shrink-0`}),(0,Z.jsx)(oT,{status:Ot,showBuildGlyph:!0})]}),Ot!==null&&Ot!==`building`&&Ot!==`done`&&(0,Z.jsx)(oT,{status:Ot,showBuildGlyph:!0}),Ct&&(0,Z.jsx)(U,{variant:`warning`,children:k(`ticketModal.openQuestionsBadge`)}),at&&(0,Z.jsx)(U,{variant:`outline`,className:`border-border/80 bg-card/60 text-muted-foreground`,children:`Stale`})]})}),Ie?(0,Z.jsx)(`div`,{className:`mt-3 min-h-0 flex flex-1 flex-col`,children:(0,Z.jsx)(_P,{content:G.description,externalSource:G.external_source})}):(0,Z.jsx)(Z.Fragment,{children:Pe?(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 flex flex-col${Le?` mt-3`:``}`,children:(0,Z.jsx)(_P,{content:G.description,externalSource:G.external_source})}):(0,Z.jsx)(WN,{projectId:G.project_id,followUpTicketId:G.id,messages:nn,internalLog:G.agent_log??null,currentThinkingMessageId:G.agent_message_id??null,previousThinkingLog:G.previous_agent_log??null,previousThinkingMessageId:G.previous_agent_message_id??null,streamingResponse:G.streaming_response??null,isRunning:G.agent_status===`running`,canShowComposer:bt,pendingAgentTitle:K,composerTheme:Fe,followUpComposerControls:wt?(0,Z.jsx)(CP,{model:ge,variant:ve,skills:be,showModelSelector:!0,showSkillsSelector:!0,availableModels:o,availableSkills:s,selectedModel:Et,onModelChange:Xt,onVariantChange:Qt,onSkillsChange:$t,modelSelectId:`ticket-follow-up-model`,variantSelectId:`ticket-follow-up-variant`,skillsSelectId:`ticket-follow-up-skills`,disabled:Ae}):void 0,followUpPrompt:B,isSendingFollowUp:V,followUpDisabledReason:jt,onFollowUpPromptChange:ie,onFollowUpKeyDown:e=>{e.key!==`Enter`||e.shiftKey||Dt||V||(e.preventDefault(),en())},onFollowUpSubmit:()=>{en()}})}),Le&&(0,Z.jsxs)(`section`,{"aria-label":k(`workspaceControls.ticketMetadataAriaLabel`),className:`flex flex-wrap items-center gap-2`,children:[Nt.filter(e=>e.value.trim().length>0).map(e=>(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 sm:flex-none sm:max-w-full`,children:(0,Z.jsx)(AT,{label:e.label,value:e.value,variant:`compact`,className:`min-w-0`})},`${e.label}:${e.value}`)),(0,Z.jsx)(`div`,{className:`min-w-0 sm:flex-none`,children:(0,Z.jsx)(TT,{model:Pt.model,variant:Pt.variant,skills:Pt.skills})})]}),!Le&&!zt&&(0,Z.jsx)(jT,{ariaLabel:k(`workspaceControls.ticketMetadataAriaLabel`),items:Nt}),(0,Z.jsx)(gP,{projectId:G.project_id,ticketId:G.id,memoryEnabled:l,refreshKey:le,onSuggestionsChanged:O}),(0,Z.jsx)(qN,{blocks:Qe,blockedBy:$e,resolveTicket:e=>Ze.get(e),onDeleteDependency:_}),G.build_chain&&(0,Z.jsx)(FT,{summary:ot,detail:st})]}),!ze&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 border-t border-border pt-4 sm:flex-row sm:items-end sm:justify-between`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[(0,Z.jsx)(q,{type:`button`,onClick:f,variant:`ghost`,children:k(`workspaceControls.close`)}),G.build_chain&&w&&(0,Z.jsxs)(q,{type:`button`,onClick:()=>{w()},title:`Stop scheduling the remaining tickets in this build chain.`,"aria-label":Xe,variant:`destructive`,children:[(0,Z.jsx)(Fc,{className:`w-3.5 h-3.5`}),Xe]}),(0,Z.jsx)(qW,{actions:rt,actionsClassName:`contents`,renderAction:({action:e,label:t,disabled:n,title:r,ariaLabel:i})=>{let a=e.id===`review`?(0,Z.jsx)(xw,{className:`w-3.5 h-3.5`}):e.id===`run`||e.id===`resume-build`?(0,Z.jsx)(Nc,{className:`w-3.5 h-3.5`}):(0,Z.jsx)(Fc,{className:`w-3.5 h-3.5`});return(0,Z.jsxs)(q,{type:`button`,disabled:n,title:r,"aria-label":i,variant:e.id===`stop-run`?`destructive`:e.id===`pause-build`||e.id===`resume-build`?`warning`:e.id===`run`?`secondary`:`default`,className:e.id===`run`?`bg-sky-700 text-sky-100 hover:bg-sky-600 hover:text-white disabled:bg-slate-700 disabled:text-slate-400`:e.id===`resume-build`?`bg-amber-700 text-amber-50 hover:bg-amber-600 hover:text-white`:void 0,onClick:()=>We(e.id),children:[e.id===`review`?t:a,e.id===`review`?a:t]},e.id)}})]})]})]}),zt&&an,vt&&(0,Z.jsx)(`div`,{className:R?ee?`fixed inset-0 z-[70] flex items-center justify-center bg-black/30 p-[5vh]`:`mt-12 min-h-0 flex flex-1 flex-col overflow-hidden`:`hidden`,children:(0,Z.jsx)(KW,{createSession:()=>ST(G.id,G.project_id),isExpanded:ee,isVisible:R,ariaLabel:k(`ticketModal.ticketTerminalAriaLabel`),className:ee?`h-full w-full max-w-none rounded-2xl shadow-2xl`:void 0,onClose:Wt,onToggleExpanded:()=>{te(e=>!e)}})})]}),Lt&&an,P&&(0,Z.jsx)(Y.Suspense,{fallback:(0,Z.jsx)(sG,{onClose:()=>{F(!1),D?.(G.id)}}),children:(0,Z.jsx)(nG,{ticketId:G.id,projectId:G.project_id,title:G.title,onTicketUpdate:g,onRequestTicketRefresh:D,onSubmitReviewPrompt:E,canSubmitReviewPrompt:!Dt,reviewSubmitDisabledReason:jt,onClose:()=>{F(!1),D?.(G.id)}})}),I&&ht&&G.project_id&&(0,Z.jsx)(Y.Suspense,{fallback:null,children:(0,Z.jsx)(rG,{scope:`ticket`,ticketId:G.id,projectId:G.project_id,testCommands:i,onClose:()=>{L(!1)}})}),pe&&(0,Z.jsx)(mu,{title:k(`ticketModal.discardUnsavedTitle`),description:Tt,confirmLabel:k(`ticketModal.discardUnsavedConfirm`),cancelLabel:k(`ticketModal.discardUnsavedCancel`),confirmVariant:`destructive`,onConfirm:Kt,onCancel:Gt})]})})},dG=({ticket:e,allTickets:t=[],dependencies:n=[],bundles:r=[],projectMemoryEnabled:i=!1,overlay:a=!1,showModelSelector:o,availableModels:s,runDisabled:c=!1,runDisabledReason:l,dependencyTargetState:u=`idle`,onDependencyStart:d,onDeleteDependency:f,onRegisterNode:p,onRegisterOverlayNode:m,onCreateBundle:h,onDeleteBundle:g,onRefreshBundles:_,onUpdate:v,onDelete:y,onUndo:b,onRetry:x,onAdvance:S,onPark:C,onUnpark:w,onBuildChain:T,onRun:E,onOpenTests:D,onOpenChanges:O,onOpenIde:k,onAddTicketToBundle:A,onStop:j,onStopBuild:M,onStopBuildChain:N,onResumeBuild:P,onFollowUp:F,onOpenBundleDetails:I,onOpenTicketDetails:L,preferBundleDetailsOnClick:R=!1,hideBundleScopedControls:z=!1,hideStatusBadge:ee=!1,onRequestTicketRefresh:te,undoInProgress:ne=!1})=>{let{t:re}=X(`common`),[B,ie]=(0,Y.useState)(!1),[V,H]=(0,Y.useState)(!1),[ae,oe]=(0,Y.useState)(!1),[se,ce]=(0,Y.useState)(!1),[le,ue]=(0,Y.useState)(null),[de,fe]=(0,Y.useState)(!1),[pe,me]=(0,Y.useState)(!1),W=e.agent_status===`running`||ne,he=z,G=e.bundle?.branch??e.branch,ge=e.has_worktree??(e.state===`plan`?!1:!!G),_e=!z&&ge,ve=eT(e,new Map(t.map(e=>[e.id,e])),n),ye=ww(e.state),be=e.state===`review`&&e.can_re_review===!0&&e.agent_status!==`running`,xe=e.worktree_bundle_id!==null,K=Ow(e),Se=kw(e),Ce=Aw(e),we=!z&&Se!==`plan`&&e.diff_stats===void 0,Te=(Ce||K)&&!a,Ee=ye?re(ye===`review`?`card.advance.reviewBundle`:`card.columnLabels.${ye}`):be?re(`card.advance.rerunReview`):null,De=Fw(e,`trash`),Oe=e.undo,ke=!!b&&Oe?.stage!==null,Ae=be||(ye?Fw(e,ye):!1),je=!K&&!!S&&!!Ee&&!ve.hasOpenBlockers,Me=!!C&&Nw(e),Ne=K&&typeof e.state==`string`?re(`card.returnTo`,{state:re(`card.columnLabels.${e.state}`)}):null,Pe=!!w&&Ne!==null&&e.state!==`plan`,Fe=!K&&!!T&&ve.canStartBuildChain,Ie=Dw(e)&&e.agent_status===`running`&&!!e.session_id&&!!M,Le=Dw(e)&&e.agent_status===`stopped`&&!!e.session_id&&!!P,Re=_e&&!!O,ze=_e&&!!e.project_id&&!!D,Be=_e&&!!k,Ve=!K&&!z&&xe&&!!A,He=!he&&ge&&!!G&&!e.is_running&&!!E,Ue=!he&&ge&&!!G&&!!e.is_running&&!!j,We=!!e.build_chain&&!!N,Ge=!!y||ke||je||Me||Pe||Fe||Ie||Le||Ve||He||Ue||ze||Re||Be||We,Ke=async()=>{if(!(!E||c||de)){fe(!0);try{await E()}finally{fe(!1)}}},qe=async()=>{if(!(!j||pe)){me(!0);try{await j()}finally{me(!1)}}},Je=!he&&ge&&G&&e.is_running&&j&&!ne?(0,Z.jsx)(cT,{isRunning:!0,isStopPending:pe,onStop:qe}):!he&&ge&&G&&!e.is_running&&!K&&E?(0,Z.jsx)(cT,{isRunning:!1,isRunPending:de,runDisabled:c,runDisabledReason:l,onRun:Ke}):null;(0,Y.useEffect)(()=>{if(!se)return;let e=()=>{ce(!1)};return window.addEventListener(`click`,e,{once:!0}),()=>{window.removeEventListener(`click`,e)}},[se]);let Ye=()=>{if(a||se||ne){ce(!1);return}if(R&&I){I();return}if(L){L();return}te?.(e.id),oe(!0)},{attributes:Xe,listeners:Ze,setNodeRef:Qe,isDragging:$e}=QC({id:e.id,disabled:a||W}),et=(0,Y.useRef)(Qe);(0,Y.useEffect)(()=>{et.current=Qe},[Qe]);let J=(0,Y.useCallback)(t=>{if(a){m?.(t);return}et.current(t),p?.(e.id,t)},[p,m,a,e.id]),tt=u===`valid`?`border-emerald-400 shadow-[0_0_0_1px_rgba(52,211,153,0.35)]`:u===`invalid`?`border-red-400 shadow-[0_0_0_1px_rgba(248,113,113,0.35)]`:a?`border-violet-400`:ve.isVisibleStartPoint?`border-violet-500/35 shadow-[0_0_0_1px_rgba(168,85,247,0.18)] hover:border-violet-400/55`:`border-border hover:border-primary/40`,nt=a||ne?`pointer-events-none cursor-grabbing shadow-2xl`:`cursor-pointer`,rt=$e?`opacity-30`:Te?`opacity-90`:`opacity-100`,it=Te?`bg-card/60`:`bg-secondary/30`,at=Te?`p-3 text-foreground/70`:`p-3`,ot=Te?`truncate text-sm font-medium text-foreground/70`:`truncate text-sm font-medium text-foreground`,st=Te?`text-[11px] text-foreground/55`:`text-[11px] text-muted-foreground`,ct=Te?`whitespace-pre-line text-xs leading-relaxed text-foreground/55 wrap-anywhere`:`whitespace-pre-line text-xs leading-relaxed text-muted-foreground wrap-anywhere`,lt=e.model??``,ut=!!e.bundle&&!z,dt=!!e.bundle?.pull_request&&!z,ft=ut||dt,pt=ft||lt.length>0,mt=le===e.id,ht=(0,Y.useMemo)(()=>{let t=e.description??``;return t?eN(t):{text:``,truncated:!1}},[e.description]);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(gu,{"data-testid":`ticket-card-${e.id}`,className:`group/card shrink-0 select-none transition-colors ${tt} ${nt} ${rt} ${it} gap-0 rounded-xl border shadow-none`,ref:J,onClick:Ye,...Ze,...Xe,children:[ne&&(0,Z.jsx)(`div`,{className:`absolute inset-0 z-10 flex items-center justify-center rounded-xl bg-background/85 backdrop-blur-[1px]`,children:(0,Z.jsxs)(U,{variant:`warning`,className:`gap-1.5`,children:[(0,Z.jsx)(kf,{className:`h-3.5 w-3.5 animate-spin`}),re(`card.undoInProgress`)]})}),(0,Z.jsxs)(xu,{className:at,children:[(0,Z.jsxs)(`div`,{className:`mb-1.5 flex items-start justify-between gap-2`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Z.jsx)(`div`,{className:ot,children:e.title})}),(0,Z.jsxs)(`div`,{className:`flex flex-shrink-0 items-start gap-1`,children:[(0,Z.jsx)(`div`,{className:`mr-1`,children:Je}),(0,Z.jsx)(`div`,{className:`flex size-7 items-start justify-center`,children:d&&(0,Z.jsx)(xc,{content:re(`card.drawDependency`),children:(0,Z.jsx)(q,{type:`button`,"aria-label":re(`card.createDependencyAriaLabel`,{title:e.title}),variant:`ghost`,size:`icon-xs`,className:`cursor-crosshair opacity-0 transition-all group-hover/card:opacity-100`,onClick:e=>e.stopPropagation(),onPointerDown:t=>{t.stopPropagation(),ce(!0),d(e.id,t)},children:(0,Z.jsx)(Jd,{className:`h-4 w-4`})})})}),(0,Z.jsx)(`div`,{className:`flex size-7 items-start justify-center`,children:Ge&&(0,Z.jsx)(vT,{title:e.title,canDelete:De,undo:Oe,undoInProgress:ne,runDisabled:c,isRunPending:de,isStopPending:pe,showTestsAction:ze,showOpenChangesAction:Re,showOpenIdeAction:Be,showAddTicketToBundleAction:Ve,showRunAction:He,showStopRunAction:Ue,showAdvanceAction:je,advanceLabel:Ee,canAdvance:Ae,showParkAction:Me,showReturnAction:Pe,returnLabel:Ne,showBuildChainAction:Fe,showPauseBuildAction:Ie,showResumeBuildAction:Le,showStopBuildChainAction:We,onDelete:y,onConfirmDelete:()=>ie(!0),onConfirmUndo:()=>H(!0),onOpenTests:D,onOpenChanges:O,onOpenIde:k,onAddTicketToBundle:Ve?()=>A?.(e.worktree_bundle_id):void 0,onAdvance:S,onPark:C,onUnpark:w,onBuildChain:T,onRun:Ke,onStop:qe,onStopBuild:M,onResumeBuild:P,onStopBuildChain:N})})]})]}),(0,Z.jsx)(`div`,{className:`mt-2`,children:(0,Z.jsx)(xT,{ticket:e,hideStatusBadge:ee,hideBundleScopedControls:z,isStale:Ce,runControl:null,onRetry:x,undoInProgress:ne,isChainStart:ve.isVisibleStartPoint})}),pt&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-col gap-1`,children:[ft&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 ${st}`,children:[ut&&(0,Z.jsx)(`span`,{className:`min-w-0 truncate`,children:Dl(e.bundle)}),dt&&e.bundle?.pull_request&&(0,Z.jsx)(yw,{pullRequest:e.bundle.pull_request,asLink:!0,showNumber:!0,onClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation()})]}),lt.length>0&&(0,Z.jsx)(`div`,{className:st,children:(0,Z.jsx)(`span`,{className:`truncate`,children:lt})})]}),e.description&&(0,Z.jsx)(`div`,{className:`mt-2`,children:(0,Z.jsx)(bT,{description:e.description,descriptionClass:ct,isExpanded:mt,collapsedState:ht,useStaleLikeStyling:Te,onExpand:()=>ue(e.id),onCollapse:()=>ue(null)})}),!z&&(Mw(Se,e.diff_stats)||we)&&(0,Z.jsx)(kc,{stats:e.diff_stats,isLoading:we,showFiles:!0,className:`mt-2`})]})]}),ae&&(0,Z.jsx)(uG,{ticket:e,allTickets:t,dependencies:n,bundles:r,projectMemoryEnabled:i,onClose:()=>{oe(!1),te?.(e.id)},showModelSelector:o,availableModels:s,runDisabled:c,runDisabledReason:l,onDeleteDependency:f,onCreateBundle:h,onDeleteBundle:g,onRefreshBundles:_,onUpdate:v,onAdvance:S,onBuildChain:T,onRun:E,onOpenIde:k,onStop:j,onStopBuild:M,onStopBuildChain:N,onResumeBuild:P,onFollowUp:F}),B&&(0,Z.jsx)(yT,{title:e.title,bundleName:e.bundle?Dl(e.bundle):void 0,onConfirm:()=>{ie(!1),y?.()},onCancel:()=>ie(!1)}),V&&Oe?.stage&&(0,Z.jsx)(sT,{title:e.title,stage:Oe.stage,onConfirm:()=>{H(!1),b?.()},onCancel:()=>H(!1)})]})},fG=({index:e})=>{let{t}=X(`common`);return(0,Z.jsx)(gu,{"aria-hidden":`true`,"data-testid":`ticket-card-skeleton`,className:`group shrink-0 select-none gap-0 rounded-xl border border-border/70 bg-secondary/20 shadow-none`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 p-3`,"aria-hidden":`true`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,Z.jsx)(Oc,{className:`h-3.5 w-3/5 rounded-full`}),(0,Z.jsx)(Oc,{className:`h-5 w-11 rounded-full`})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Oc,{className:`h-3 w-full rounded-full`}),(0,Z.jsx)(Oc,{className:`h-3 w-11/12 rounded-full`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Oc,{className:`h-4 w-14 rounded-full`}),(0,Z.jsx)(Oc,{className:`h-4 w-10 rounded-full`})]}),(0,Z.jsx)(`span`,{className:`sr-only`,children:t(`column.loadingCard`,{index:e+1})})]})})},pG=({id:e,title:t,items:n,ticketCount:r,pinnedContent:i=null,allTickets:a,dependencies:o,showModelSelector:s,availableModels:c,activeRunContextKey:l,isProjectRootRunActive:u=!1,isBundleRunDisabled:d,bundles:f,getDependencyTargetState:p,onDependencyStart:m,onDeleteDependency:h,onRegisterTicketNode:g,onAddTicket:_,onCreateBundle:v,onDeleteBundle:y,onRefreshBundles:b,onUpdateTicket:x,onDeleteTicket:S,onUndoTicket:C,undoingColumn:w=null,onRetryTicket:T,onAdvanceTicket:E,onParkTicket:D,onUnparkTicket:O,onBuildChainTicket:k,onRunTicket:A,onOpenTestsTicket:j,canOpenChangesForTicket:M,onOpenChangesTicket:N,canOpenIdeForTicket:P,onOpenIdeTicket:F,onStopTicket:I,onStopBuildTicket:L,onStopBuildChainTicket:R,onResumeBuildTicket:z,onFollowUpTicket:ee,onBuildBundle:te,onReviewBundle:ne,onUndoBundleReview:re,onRunBundle:B,onStopBundle:ie,onParkBundleWrapper:V,onUnparkBundleWrapper:H,bundleActionState:ae,onOpenTicketDetails:oe,onOpenBundleDetails:se,onOpenBundleChanges:ce,onOpenBundleTests:le,onOpenBundleIde:ue,onDeleteBundleWrapper:de,onAddTicketToBundle:fe,onRequestBundleRefresh:pe,onRequestTicketRefresh:me,className:W=``,headerAccessory:he=null,loadingSkeletonCount:G=0})=>{let{t:ge}=X(`common`),{setNodeRef:_e,isOver:ve}=nw({id:e}),ye=(0,Y.useRef)(null),[be,xe]=(0,Y.useState)(!1),[K,Se]=(0,Y.useState)(!1),Ce=e=>e.has_worktree??!!(e.bundle?.branch??e.branch),we=ve?`border-primary`:`border-border`,Te=w===e&&(e===`build`||e===`review`),Ee=(0,Y.useCallback)(()=>{let e=ye.current;if(!e){xe(!1),Se(!1);return}if(!(e.scrollHeight>e.clientHeight+1)){xe(!1),Se(!1);return}let t=e.scrollHeight-e.clientHeight;xe(e.scrollTop>1),Se(e.scrollTop<t-1)},[]);(0,Y.useEffect)(()=>{let e=window.requestAnimationFrame(Ee),t=ye.current;if(!t){window.cancelAnimationFrame(e);return}return t.addEventListener(`scroll`,Ee),window.addEventListener(`resize`,Ee),()=>{window.cancelAnimationFrame(e),t.removeEventListener(`scroll`,Ee),window.removeEventListener(`resize`,Ee)}},[n.length,G,Ee]);let De=(0,Y.useCallback)((t,n)=>{let r=t.worktree_bundle_id!==null,i=n?.nestedInBundle??!1,d=n?.hideStatusBadge??!1,_=r&&e!==`plan`,w=Yw(t),te=u||l!==null&&l!==Ew(t)?ge(`column.runDisabledReason`):w;return(0,Z.jsx)(dG,{ticket:t,allTickets:a,dependencies:o,bundles:f,showModelSelector:s,availableModels:c,runDisabled:te!==void 0,runDisabledReason:te,dependencyTargetState:p?.(t.id)??`idle`,onDependencyStart:m,onDeleteDependency:h,onRegisterNode:g,onCreateBundle:v,onDeleteBundle:y,onRefreshBundles:b,onUpdate:x,onDelete:()=>S(t.id),onUndo:C?()=>C(t.id):void 0,undoInProgress:!1,onRetry:()=>T(t.id),onAdvance:E?()=>E(t.id):void 0,onPark:D?()=>D(t.id):void 0,onUnpark:O?()=>O(t.id):void 0,onBuildChain:k?()=>k(t.id):void 0,onRun:Ce(t)&&t.has_run_config&&A?()=>A(t.id):void 0,onOpenTests:j&&t.project_id&&Ce(t)?()=>j(t.id):void 0,onOpenChanges:M?.(t)&&N?()=>N(t.id):void 0,onOpenIde:P?.(t)&&F?()=>F(t.id):void 0,onStop:I?()=>I(t.id):void 0,onStopBuild:L?()=>L(t.id):void 0,onStopBuildChain:R?()=>R(t.id):void 0,onResumeBuild:z?()=>z(t.id):void 0,onFollowUp:ee?e=>ee(t.id,e):void 0,onAddTicketToBundle:fe,onOpenBundleDetails:_&&se?()=>se(t.worktree_bundle_id,e):void 0,onOpenTicketDetails:()=>oe(t),preferBundleDetailsOnClick:_,hideBundleScopedControls:i,hideStatusBadge:d,onRequestTicketRefresh:me})},[l,a,c,f,M,P,o,p,e,u,fe,E,k,v,y,h,S,m,ee,se,N,F,j,oe,D,b,g,me,z,T,A,R,L,I,C,O,x,s,ge]);return(0,Z.jsxs)(gu,{className:`flex min-h-0 min-w-[280px] flex-1 flex-col rounded-2xl bg-card/80 p-4 transition-colors ${W} ${we}`,ref:_e,children:[(0,Z.jsxs)(`div`,{className:`mb-4 flex min-h-7 items-center justify-between`,children:[(0,Z.jsx)(`h2`,{className:`text-xs font-semibold uppercase tracking-widest text-muted-foreground`,children:t}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[he,(0,Z.jsx)(U,{variant:`outline`,children:r}),_&&(0,Z.jsxs)(q,{type:`button`,onClick:_,size:`xs`,variant:`success`,className:`gap-2 shadow-[0_8px_20px_rgba(16,185,129,0.22)]`,children:[(0,Z.jsx)(`span`,{children:ge(`column.newTicket`)}),(0,Z.jsx)(U,{"aria-hidden":`true`,variant:`hotkeyDark`,className:`rounded-md px-1.5 py-0.5 text-[10px] leading-none`,children:`N`})]})]})]}),(0,Z.jsxs)(`div`,{className:`relative min-h-0 flex-1`,children:[(0,Z.jsxs)(`div`,{ref:ye,className:`flex min-h-0 h-full flex-col gap-2.5 overflow-y-auto pr-1`,children:[i,n.map(e=>{if(e.kind===`bundle`)return(0,Z.jsx)(gT,{group:e.group,renderTicket:t=>De(t,{nestedInBundle:!0,hideStatusBadge:e.group.column===`review`}),runDisabled:d?.(e.group.bundle.id)??!1,onBuildBundle:te,onReviewBundle:ne,onUndoBundleReview:re,onRunBundle:B,onStopBundle:ie,onParkBundleWrapper:V,onUnparkBundleWrapper:H,bundleActionState:ae,onStopBuildTicket:L,onResumeBuildTicket:z,onOpenBundleDetails:se,onOpenBundleChanges:ce,onOpenBundleTests:le,onOpenBundleIde:ue,onDeleteBundleWrapper:de,onAddTicketToBundle:fe,onRequestBundleRefresh:pe},e.group.id);let t=e.ticket;return(0,Z.jsx)(Y.Fragment,{children:De(t)},t.id)}),Array.from({length:G},(t,n)=>(0,Z.jsx)(fG,{index:n},`loading-card-${e}-${n}`))]}),Te&&(0,Z.jsx)(`div`,{"aria-hidden":`true`,"data-testid":`column-undo-overlay-${e}`,className:`absolute inset-0 z-20 flex items-center justify-center rounded-xl bg-background/85 backdrop-blur-[1px]`,children:(0,Z.jsxs)(U,{variant:`warning`,className:`gap-1.5`,children:[(0,Z.jsx)(kf,{className:`h-3.5 w-3.5 animate-spin`}),ge(`column.undoInProgress`)]})}),be&&(0,Z.jsx)(`div`,{"aria-hidden":`true`,"data-testid":`column-top-fade`,className:`pointer-events-none absolute inset-x-0 top-0 h-6 rounded-t-xl bg-gradient-to-b from-card to-transparent`}),K&&(0,Z.jsx)(`div`,{"aria-hidden":`true`,"data-testid":`column-bottom-fade`,className:`pointer-events-none absolute inset-x-0 bottom-0 h-8 rounded-b-xl bg-gradient-to-t from-card to-transparent`})]})]})},mG=({ticketCount:e,isDeleting:t,onCancel:n,onConfirm:r})=>{let{t:i}=X(`common`);return(0,Z.jsxs)(pu,{onClose:t?()=>{}:n,overlayClassName:`bg-black/60`,panelClassName:`max-w-md rounded-2xl border border-border bg-card p-6 shadow-2xl`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold uppercase tracking-widest text-muted-foreground`,children:i(`boardConfirmEmptyDoneModal.heading`)}),(0,Z.jsx)(`p`,{className:`mb-2 text-sm text-foreground`,children:i(`boardConfirmEmptyDoneModal.deletePrompt`,{count:e})}),(0,Z.jsx)(`p`,{className:`mb-6 text-xs text-muted-foreground`,children:i(`boardConfirmEmptyDoneModal.description`)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(q,{type:`button`,variant:`ghost`,disabled:t,onClick:n,children:i(`boardConfirmEmptyDoneModal.cancel`)}),(0,Z.jsx)(q,{type:`button`,variant:`destructive`,disabled:t,onClick:r,children:i(t?`boardConfirmEmptyDoneModal.deleting`:`boardConfirmEmptyDoneModal.confirm`)})]})]})},hG=({projectId:e,followUpTicketId:t=null,messages:n,internalLog:r,currentThinkingMessageId:i=null,legacyThinkingTicketId:a=null,previousThinkingLog:o=null,previousThinkingMessageId:s=null,pendingAgentTitle:c,streamingResponse:l,isRunning:u,isLoading:d=!1,canShowComposer:f,composerControls:p,composerTheme:m=`default`,layoutKey:h,scrollLayoutKey:g,followUpPrompt:_,followUpPlaceholder:v=`Follow up on this bundle`,isSendingFollowUp:y,followUpDisabledReason:b,onFollowUpPromptChange:x,onFollowUpKeyDown:S,onFollowUpSubmit:C})=>(0,Z.jsx)(UN,{projectId:e,followUpTicketId:t,messages:n,internalLog:r,currentThinkingMessageId:i,legacyThinkingTicketId:a,previousThinkingLog:o,previousThinkingMessageId:s,pendingAgentTitle:c,streamingResponse:l,isRunning:u,isLoading:d,autoScrollBehavior:`sticky`,canShowComposer:f,composerInlineControls:p,composerTheme:m,composerSize:`compact-on-laptop`,layoutKey:h,scrollLayoutKey:g,followUpPrompt:_,followUpPlaceholder:v,emptyStateText:`No bundle messages yet.`,autoFocusComposer:!0,isSendingFollowUp:y,followUpDisabledReason:b,onFollowUpPromptChange:x,onFollowUpKeyDown:S,onFollowUpSubmit:C}),gG=({bundleId:e,actionState:t,runDisabled:n,canBuild:r,canStopBuild:i,runningBuildTicketId:a,canResumeBuild:o,resumableBuildTicketId:s,isRunning:c,canRun:l,canReview:u,reviewActionLabel:d=`Review Bundle`,onClose:f,onBuildBundle:p,onStopBuildTicket:m,onResumeBuildTicket:h,onRunBundle:g,onStopBundle:_,onReviewBundle:v})=>{let y=t.review||t.followUp;return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 pt-4 sm:flex-row sm:items-end sm:justify-between`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[(0,Z.jsx)(q,{type:`button`,onClick:f,variant:`ghost`,children:`Close`}),c?(0,Z.jsxs)(q,{type:`button`,variant:`destructive`,disabled:t.stop,onClick:()=>void _(e),children:[(0,Z.jsx)(`span`,{className:`w-2 h-2 rounded-full bg-emerald-400 animate-pulse flex-shrink-0`}),(0,Z.jsx)(Fc,{className:`w-3.5 h-3.5`}),t.stop?`Stopping...`:`Stop Run`]}):l?(0,Z.jsxs)(q,{type:`button`,variant:`secondary`,disabled:t.run||n,title:n?`Stop the currently running ticket before starting another run.`:void 0,onClick:()=>{n||g(e)},className:`bg-sky-700 text-sky-100 hover:bg-sky-600 hover:text-white disabled:bg-slate-700 disabled:text-slate-400`,children:[(0,Z.jsx)(Nc,{className:`w-3.5 h-3.5`}),t.run?`Starting Run...`:`Run`]}):null,r&&(0,Z.jsxs)(q,{type:`button`,disabled:t.build,onClick:()=>void p(e),children:[(0,Z.jsx)(Nc,{className:`w-3.5 h-3.5`}),t.build?`Building Bundle...`:`Build Bundle`]}),i&&a&&(0,Z.jsxs)(q,{type:`button`,variant:`warning`,disabled:t.stopBuild,title:`Pause the build session. You can resume it later.`,"aria-label":`Pause Build`,onClick:()=>void m(a),children:[(0,Z.jsx)(Fc,{className:`w-3.5 h-3.5`}),t.stopBuild?`Pausing...`:`Pause Build`]}),o&&s&&(0,Z.jsxs)(q,{type:`button`,variant:`warning`,className:`bg-amber-700 text-amber-50 hover:bg-amber-600 hover:text-white`,disabled:t.resumeBuild,onClick:()=>void h(s),children:[(0,Z.jsx)(Nc,{className:`w-3.5 h-3.5`}),t.resumeBuild?`Resuming...`:`Resume`]}),u&&(0,Z.jsxs)(q,{type:`button`,disabled:y,onClick:()=>void v(e),children:[(0,Z.jsx)(xw,{className:`w-3.5 h-3.5`}),y?`Reviewing Bundle...`:d]})]})]})},_G=e=>e.agent_status===`running`?`bg-amber-400`:e.agent_status===`error`?`bg-rose-400`:e.agent_status===`stopped`?`bg-amber-300`:e.agent_status===`done`?`bg-emerald-400`:`bg-border`,vG=({tickets:e,onOpenTicketDetails:t,highlightedTicketId:n=null,pendingMemorySuggestionCounts:r={}})=>{let i=e.filter(e=>e.agent_status===`running`).length,a=e.filter(e=>e.agent_status===`error`).length;return(0,Z.jsxs)(`section`,{"aria-label":`Bundle tickets`,className:`flex min-h-0 flex-1 flex-col gap-3 overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground`,children:`Tickets`}),(0,Z.jsx)(U,{variant:`outline`,children:e.length}),i>0&&(0,Z.jsxs)(`span`,{className:`text-[11px] text-muted-foreground`,children:[i,` active`]}),a>0&&(0,Z.jsxs)(`span`,{className:`text-[11px] text-rose-300`,children:[a,` error`,a===1?``:`s`]})]}),(0,Z.jsx)(`div`,{className:`flex min-h-0 flex-col gap-1 overflow-y-auto pr-1`,children:e.map(e=>{let i=r[e.id]??0,a=e.id===n;return(0,Z.jsxs)(`button`,{type:`button`,"data-follow-up-target":a?`true`:`false`,"aria-current":a?`true`:void 0,className:K(`flex cursor-pointer items-center gap-3 rounded-lg px-2.5 py-2.5 text-left text-foreground transition-colors`,a?`border border-sky-500/35 bg-sky-500/10 shadow-[inset_0_0_0_1px_rgba(56,189,248,0.12)] hover:bg-sky-500/15`:`bg-background/20 hover:bg-accent/45`),onClick:()=>t(e),children:[(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:K(`h-2 w-2 shrink-0 rounded-full`,_G(e))}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`truncate text-xs font-medium`,children:e.title}),(0,Z.jsx)(DT,{tool:e.tool,className:`shrink-0 text-[10px]`})]}),(0,Z.jsx)(`div`,{className:`mt-0.5 text-[11px] text-muted-foreground`,children:e.state})]}),a&&(0,Z.jsx)(U,{variant:`info`,className:`shrink-0 px-1.5 text-[10px]`,"aria-label":`Follow-up target`,children:`Follow-up`}),i>0&&(0,Z.jsx)(U,{variant:`warning`,className:`h-5 min-w-5 shrink-0 justify-center rounded-full px-1.5 text-[10px]`,"aria-label":`${i} pending memory suggestion${i===1?``:`s`}`,title:`${i} pending memory suggestion${i===1?``:`s`}`,children:i})]},e.id)})})]})},yG=e=>e.kind===`description`?e.bundle_visible_at??e.created_at:e.created_at,bG=(e,t)=>e?t.get(e)??e:null,xG=(e,t)=>bG(e,t)??`Agent`,SG=e=>e.kind===`planning_follow_up`||e.kind===`planning_response`?0:e.kind===`description`?1:2,CG=(e,t)=>{let n={};for(let r of e){let e=bG(r.model,t);e&&(n[r.id]=e)}return n},wG=(e,t=[])=>{let n=new Map(t.map((e,t)=>[e,t]));return[...e].sort((e,t)=>{let r=n.get(e.id)??e.bundle_execution_position??2**53-1,i=n.get(t.id)??t.bundle_execution_position??2**53-1;if(r!==i)return r-i;if(e.created_at!==t.created_at)return e.created_at.localeCompare(t.created_at);let a=e.title.localeCompare(t.title,void 0,{sensitivity:`base`});return a===0?e.id.localeCompare(t.id):a})},TG=(e,t,n,r=[])=>{let i=wG(e,r),a=new Map(i.map((e,t)=>[e.id,t]));return i.flatMap(e=>{let r=e.messages??[],i=e.agent_status!==null||e.session_id!==null||r.some(e=>e.kind!==`description`&&PT(e)),o=r.filter(e=>PT(e)&&(i||e.kind!==`description`)),s=n[e.id]??xG(e.model,t);return o.map(t=>t.role===`assistant`?{...t,displayTitle:s,ticketOrder:a.get(e.id)??2**53-1}:t.kind===`follow_up`?{...t,displayTitle:`You`,ticketOrder:a.get(e.id)??2**53-1}:{...t,displayTitle:e.title,ticketOrder:a.get(e.id)??2**53-1})}).sort((e,t)=>{if(e.ticket_id===t.ticket_id){let n=SG(e)-SG(t);if(n!==0)return n}let n=yG(e),r=yG(t);if(n!==r)return n.localeCompare(r);if(e.ticket_id!==t.ticket_id&&e.ticketOrder!==t.ticketOrder)return e.ticketOrder-t.ticketOrder;let i=SG(e)-SG(t);return i===0?e.id.localeCompare(t.id):i}).map(e=>{let{ticketOrder:t,...n}=e;return n})},EG=e=>xl(e.tickets,{targetTicketId:e.target_ticket_id,reviewOwnerTicketId:e.review_owner_ticket_id,latestSessionTicketId:e.latest_session_ticket_id}),DG=(0,Y.lazy)(()=>tG(()=>Promise.resolve().then(()=>fJ).then(e=>({default:e.TicketChangesModal})),void 0)),OG=e=>e.replace(/\r\n/g,`
|
|
142
142
|
`).trim(),kG=(e,t)=>e.ticket_id===t.ticket_id&&e.role===`user`&&t.role===`user`&&e.kind===`follow_up`&&t.kind===`follow_up`&&OG(e.content)===OG(t.content),AG=(e,t)=>{if(t.length===0)return e;let n=new Set,r=new Set,i=new Map,a=[];for(let a of t){let t=[...e].reverse().find(e=>!r.has(e.id)&&!n.has(a.id)&&kG(a,e));t&&(r.add(t.id),n.add(a.id),i.set(t.id,a))}for(let t of e){let e=i.get(t.id);if(e){a.push(e);continue}a.push(t)}for(let e of t)n.has(e.id)||a.push(e);return a},jG=e=>e?e.startsWith(`ses_`)?`opencode --session ${e}`:`claude --resume ${e}`:null,MG=(e,t)=>e.latest_session_id?jG(e.latest_session_id):jG(t?.session_id??null),NG=(e,t)=>t?.diff_stats?t.diff_stats:e.find(e=>e.diff_stats)?.diff_stats??null,PG=({details:e,activeColumn:t=null,isLoading:n=!1,actionState:r,canOpenIde:i,projectMemoryEnabled:a=!1,memorySuggestionsRefreshKey:o=0,runDisabled:s=!1,showModelSelector:c=!1,availableModels:l=[],availableSkills:u=[],onClose:d,onOpenTicketDetails:f,onOpenIde:p,onOpenTests:m,onRefresh:h,onUpdateTicket:g,onBuildBundle:_,onStopBuildTicket:v,onResumeBuildTicket:y,onReviewBundle:b,onRunBundle:x,onStopBundle:S,onFollowUpBundle:C})=>{let{t:w}=X(`common`),[T,E]=(0,Y.useState)(!1),[D,O]=(0,Y.useState)(``),[k,A]=(0,Y.useState)(!1),[j,M]=(0,Y.useState)(!1),[N,P]=(0,Y.useState)(!1),[F,L]=(0,Y.useState)(``),[R,z]=(0,Y.useState)(``),[ee,te]=(0,Y.useState)([]),[ne,re]=(0,Y.useState)(null),[B,ie]=(0,Y.useState)(!1),[V,H]=(0,Y.useState)(!1),[ae,oe]=(0,Y.useState)({}),[se,ce]=(0,Y.useState)([]),le=(0,Y.useMemo)(()=>EG(e),[e]),ue=(0,Y.useMemo)(()=>new Map(l.map(e=>[e.id,e.label])),[l]),[de,fe]=(0,Y.useState)(()=>CG(e.tickets,ue)),pe=(0,Y.useMemo)(()=>wG(e.tickets,e.execution_order_ticket_ids),[e.execution_order_ticket_ids,e.tickets]),me=t??le?.state??null,W=me===`plan`,he=(0,Y.useMemo)(()=>AG(TG(e.tickets,ue,de,e.execution_order_ticket_ids),se),[ue,e.execution_order_ticket_ids,e.tickets,se,de]),G=(0,Y.useMemo)(()=>dT(e.tickets,me),[me,e.tickets]),ge=(0,Y.useMemo)(()=>(0,Z.jsx)(oT,{status:G}),[G]),_e=(0,Y.useMemo)(()=>MG(e,le),[e,le]),ve=(0,Y.useMemo)(()=>NG(e.tickets,le),[e.tickets,le]),ye=!W&&!!(le?.project_id&&le&&bl(le)),be=!!(m&&le?.project_id&&le&&bl(le)),xe=!W&&!!(le?.project_id&&le),K=xe&&!k,Se=xe&&N&&le!==null,Ce=me===`plan`&&e.tickets.some(e=>e.state===`plan`),we=pe.find(e=>Dw(e)&&e.agent_status===`running`&&!!e.session_id)??null,Te=pe.find(e=>Dw(e)&&e.agent_status===`stopped`&&!!e.session_id)??null,Ee=we!==null,De=!Ee&&Te!==null,Oe=me===`build`&&e.tickets.some(e=>e.state===`build`)&&e.tickets.filter(e=>e.state===`build`).every(e=>e.agent_status===`done`),ke=r.review||r.followUp,Ae=me===`review`&&e.can_re_review===!0&&!e.tickets.some(e=>e.agent_status===`running`)&&!ke,je=Oe||Ae,Me=Ae?`Re-run review`:`Review Bundle`,Ne=e.tickets.some(e=>e.has_run_config&&Jw(e)),Pe=e.tickets.some(e=>e.is_running),Fe=e.tickets.find(e=>e.agent_status===`running`)??le,Ie=Fe?.streaming_response??null,Le=Fe?.agent_log??null,Re=Fe?.agent_message_id??le?.agent_message_id??null,ze=Fe?.previous_agent_log??le?.previous_agent_log??null,Be=Fe?.previous_agent_message_id??le?.previous_agent_message_id??null,Ve=l.find(e=>e.id===F)??null,He=le?.project_id??e.tickets.find(e=>e.project_id)?.project_id??null,Ue=(0,Y.useMemo)(()=>e.tickets.map(e=>e.id).sort().join(`|`),[e.tickets]),We=(0,Y.useMemo)(()=>new Set(Ue.length>0?Ue.split(`|`):[]),[Ue]),Ge=(0,Y.useMemo)(()=>e.tickets.map(e=>`${e.id}:${e.build_completed_at??``}`).sort().join(`|`),[e.tickets]),Ke=Fe??le??e.tickets[0]??null,qe=Ke??le,Ye=qe?.id??null,Xe=Fe?de[Fe.id]??Fe.model??`Agent`:`Agent`,Ze=Fe?.agent_status===`running`?Xe:null,Qe=!W&&!!(le&&bl(le)),$e=Tw(t??le?.state??null),et=Qe&&c&&qe?.tool===`opencode`,J=r.followUp||V,tt=e.tickets.some(e=>e.agent_status===`running`),nt=tt?`Wait for all bundle tickets to finish building before sending a follow-up prompt.`:void 0,rt=Ke?`Follow up on: ${Ke.title}`:`Follow up on this bundle`,it=[{label:e.bundle.kind===`project_root`?`Project root branch`:`Worktree`,value:e.bundle.branch},{label:`Session`,value:_e??``}],at=!W,ot=k&&!j,st=e.bundle.id,ct=k?j?`expanded`:`split`:`closed`,lt=ot?`flex h-[92vh] w-[98vw] max-w-[110rem] flex-col gap-3 overflow-visible rounded-2xl border border-border bg-card p-4 shadow-2xl sm:p-5 lg:p-6`:`flex h-[92vh] w-[96vw] max-w-[100rem] flex-col gap-3 overflow-visible rounded-2xl border border-border bg-card p-4 shadow-2xl sm:p-5 lg:p-6`,ut=ot?`grid min-h-0 flex-1 grid-cols-[16rem_minmax(0,1fr)_minmax(30rem,1fr)] gap-3 2xl:grid-cols-[18rem_minmax(0,1fr)_minmax(30rem,1fr)]`:at?`grid min-h-0 flex-1 grid-cols-[16rem_minmax(0,1fr)] gap-3 2xl:grid-cols-[18rem_minmax(0,1fr)]`:`flex min-h-0 flex-1 flex-col`,dt=j?`fixed inset-0 z-[70] flex items-center justify-center bg-black/30 p-[5vh]`:`fixed inset-4 z-[70] flex items-stretch justify-end bg-black/30 backdrop-blur-sm 2xl:hidden sm:inset-6 lg:inset-8`;(0,Y.useEffect)(()=>{if(!a||W||!He||Ue.length===0){oe({});return}let e=new AbortController;return Je(He,null,e.signal).then(t=>{e.signal.aborted||oe(t.suggestions.reduce((e,t)=>(!t.ticket_id||!We.has(t.ticket_id)||(e[t.ticket_id]=(e[t.ticket_id]??0)+1),e),{}))}).catch(t=>{if(!e.signal.aborted){if(t instanceof I&&(t.status===404||t.status===409)){oe({});return}oe({})}}),()=>{e.abort()}},[Ge,He,We,Ue,W,o,a]),(0,Y.useEffect)(()=>{fe(t=>{let n={...t},r=!1,i=new Set(e.tickets.map(e=>e.id));for(let t of e.tickets){let e=t.model?ue.get(t.model)??t.model:null;!e||n[t.id]===e||(n[t.id]=e,r=!0)}for(let e of Object.keys(n))i.has(e)||(delete n[e],r=!0);return r?n:t})},[ue,e.tickets]),(0,Y.useEffect)(()=>{if(Ye!==null&&ne?.ticketId===Ye)if((qe?.model??``)===ne.model&&(qe?.variant??``)===ne.variant&&(qe?.skills.length??0)===ne.skills.length&&(qe?.skills??[]).every((e,t)=>e===ne.skills[t]))re(null);else return;L(qe?.model??``),z(qe?.variant??``),te(qe?.skills??[])},[qe?.model,qe?.skills,qe?.variant,Ye,ne]);let ft=async(e,t,n)=>{if(qe){re({ticketId:qe.id,model:e,variant:t,skills:n}),ie(!0);try{let r=await Zt(qe.id,qe.project_id,{model:e.trim()||null,variant:t.trim()||null,skills:n});g?.(r)}catch(e){re(null),L(qe.model??``),z(qe.variant??``),te(qe.skills),Q.error(e instanceof Error?e.message:`Unable to update the ticket right now.`,{id:`ticket-save-error`})}finally{ie(!1)}}},pt=async()=>{let t=D.trim();if(!t||J||tt)return;let n=Ke?{id:`optimistic-follow-up-${Date.now()}`,ticket_id:Ke.id,role:`user`,kind:`follow_up`,content:t,created_at:new Date().toISOString(),displayTitle:`You`}:null;H(!0),O(``),n&&ce(e=>[...e,n]);try{await C(e.bundle.id,t)}catch{n&&ce(e=>e.filter(e=>e.id!==n.id)),O(t)}finally{H(!1)}},mt=et?(0,Z.jsx)(`div`,{className:`flex flex-col gap-2.5`,children:et&&(0,Z.jsx)(CP,{model:F,variant:R,skills:ee,showModelSelector:!0,showSkillsSelector:!0,availableModels:l,availableSkills:u,selectedModel:Ve,onModelChange:e=>{let t=(l.find(t=>t.id===e)??null)?.variants.includes(R)?R:``;L(e),z(t),ft(e,t,ee)},onVariantChange:e=>{z(e),ft(F,e,ee)},onSkillsChange:e=>{te(e),ft(F,R,e)},modelSelectId:`bundle-follow-up-model`,variantSelectId:`bundle-follow-up-variant`,skillsSelectId:`bundle-follow-up-skills`,disabled:B})}):void 0;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(pu,{onClose:d,overlayClassName:`bg-black/60 !z-40`,panelClassName:lt,renderContent:({closeButton:t})=>(0,Z.jsx)(Z.Fragment,{children:(0,Z.jsxs)(`div`,{"data-testid":`bundle-modal-layout`,"data-terminal-mode":ct,className:`min-h-0 flex flex-1 flex-col gap-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold text-foreground`,children:Dl(e.bundle)}),ge,e.bundle.pull_request&&(0,Z.jsx)(yw,{pullRequest:e.bundle.pull_request,asLink:!0}),(0,Z.jsxs)(U,{variant:`outline`,children:[e.tickets.length,` tickets`]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[!W&&ve&&(0,Z.jsx)(kc,{stats:ve,showFiles:!0,className:`text-xs`}),ye&&(0,Z.jsxs)(q,{type:`button`,"aria-label":w(`workspaceControls.changes`),onClick:()=>E(!0),variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(jc,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:w(`workspaceControls.changes`)})]}),be&&(0,Z.jsxs)(q,{type:`button`,"aria-label":w(`workspaceControls.tests`),onClick:m,variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(Ac,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:w(`workspaceControls.tests`)})]}),!W&&i&&(0,Z.jsxs)(q,{type:`button`,"aria-label":w(`workspaceControls.openIde`),onClick:p,variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(Mc,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:w(`workspaceControls.openIde`)})]}),K&&(0,Z.jsxs)(q,{type:`button`,"aria-label":w(`workspaceControls.openTerminalAriaLabel`),onClick:()=>{P(!0),A(!0)},variant:`outline`,className:`gap-2`,children:[(0,Z.jsx)(Ic,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:w(`workspaceControls.terminal`)})]}),t]})]}),(0,Z.jsxs)(`div`,{className:ut,children:[at&&(0,Z.jsxs)(`aside`,{"data-testid":`bundle-modal-sidebar`,className:`flex min-h-0 flex-col gap-4`,children:[(0,Z.jsx)(jT,{ariaLabel:w(`workspaceControls.ticketMetadataAriaLabel`),items:it,className:`flex-col items-stretch gap-3`}),(0,Z.jsx)(vG,{tickets:e.tickets,onOpenTicketDetails:f,highlightedTicketId:Ke?.id??null,pendingMemorySuggestionCounts:ae})]}),(0,Z.jsxs)(`div`,{"data-testid":`bundle-modal-main`,className:`min-h-0 flex flex-1 flex-col gap-3 overflow-hidden`,children:[!W&&(0,Z.jsx)(hG,{projectId:le?.project_id??null,followUpTicketId:e.target_ticket_id,messages:he,internalLog:Le,currentThinkingMessageId:Re,legacyThinkingTicketId:Fe?.id??le?.id??null,previousThinkingLog:ze,previousThinkingMessageId:Be,pendingAgentTitle:Ze,streamingResponse:Ie,isRunning:Fe?.agent_status===`running`,isLoading:n,canShowComposer:Qe,layoutKey:st,scrollLayoutKey:ct,composerControls:mt,composerTheme:$e,followUpPrompt:D,followUpPlaceholder:rt,isSendingFollowUp:J,followUpDisabledReason:nt,onFollowUpPromptChange:O,onFollowUpKeyDown:e=>{e.key!==`Enter`||e.shiftKey||tt||J||(e.preventDefault(),pt())},onFollowUpSubmit:()=>{pt()}}),W&&(0,Z.jsx)(vG,{tickets:e.tickets,onOpenTicketDetails:f,pendingMemorySuggestionCounts:ae}),(0,Z.jsx)(gG,{bundleId:e.bundle.id,actionState:r,runDisabled:s,canBuild:Ce,canStopBuild:Ee,runningBuildTicketId:we?.id??null,canResumeBuild:De,resumableBuildTicketId:Te?.id??null,isRunning:Pe,canRun:Ne,canReview:je,reviewActionLabel:Me,onClose:d,onBuildBundle:_,onStopBuildTicket:v,onResumeBuildTicket:y,onRunBundle:x,onStopBundle:S,onReviewBundle:b})]}),Se&&le&&(0,Z.jsx)(`div`,{className:k?ot?`min-h-0 flex flex-col overflow-hidden`:dt:`hidden`,children:(0,Z.jsx)(KW,{createSession:()=>ST(le.id,le.project_id),isExpanded:j,isVisible:k,ariaLabel:w(`bundleDetailsModal.bundleTerminalAriaLabel`),title:w(`workspaceControls.terminalTitle`),className:ot||j?`h-full w-full max-w-none rounded-2xl shadow-2xl`:`h-full w-full max-w-5xl rounded-2xl shadow-2xl`,onClose:()=>{A(!1),M(!1),P(!1),h(e.bundle.id)},onToggleExpanded:()=>{M(e=>!e)}})})]})]})})}),T&&le&&(0,Z.jsx)(Y.Suspense,{fallback:null,children:(0,Z.jsx)(DG,{ticketId:le.id,projectId:le.project_id,reviewCommentsBundleId:e.bundle.id,title:Dl(e.bundle),onSubmitReviewPrompt:t=>C(e.bundle.id,t),canSubmitReviewPrompt:!tt,reviewSubmitDisabledReason:nt,canAddReviewComments:!tt,canModifyChanges:!tt,changesDisabledReason:nt,onClose:()=>{E(!1),h(e.bundle.id)}})})]})},FG=ae(`group/toggle inline-flex cursor-pointer items-center justify-center gap-1 rounded-3xl text-sm font-medium whitespace-nowrap transition-colors outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/30 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-pressed:bg-muted dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,{variants:{variant:{default:`bg-transparent`,outline:`border border-input bg-transparent hover:bg-muted`},size:{default:`h-9 min-w-9 px-3 has-data-[icon=inline-end]:pr-2.5 has-data-[icon=inline-start]:pl-2.5`,sm:`h-8 min-w-8 px-3 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`,lg:`h-10 min-w-10 px-4 has-data-[icon=inline-end]:pr-3 has-data-[icon=inline-start]:pl-3`}},defaultVariants:{variant:`default`,size:`default`}}),IG=Y.createContext({size:`default`,variant:`default`,spacing:0,orientation:`horizontal`});function LG({className:e,variant:t,size:n,spacing:r=0,orientation:i=`horizontal`,children:a,...o}){return(0,Z.jsx)(ca,{"data-slot":`toggle-group`,"data-variant":t,"data-size":n,"data-spacing":r,"data-orientation":i,style:{"--gap":r},className:K(`group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] data-[spacing=0]:data-[variant=outline]:rounded-3xl data-vertical:flex-col data-vertical:items-stretch`,e),...o,children:(0,Z.jsx)(IG.Provider,{value:{variant:t,size:n,spacing:r,orientation:i},children:a})})}function RG({className:e,children:t,variant:n=`default`,size:r=`default`,...i}){let a=Y.useContext(IG);return(0,Z.jsx)(la,{"data-slot":`toggle-group-item`,"data-variant":a.variant||n,"data-size":a.size||r,"data-spacing":a.spacing,className:K(`shrink-0 group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-3 group-data-[spacing=0]/toggle-group:shadow-none focus:z-10 focus-visible:z-10 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-end]:pr-2.5 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-start]:pl-2.5 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-l-3xl group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-t-3xl group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-r-3xl group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-b-3xl data-[state=on]:bg-muted group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t`,FG({variant:a.variant||n,size:a.size||r}),e),...i,children:t})}var zG=`border-sky-400/30 bg-sky-400/10 text-sky-100`,BG=(e,t)=>Pe.t(`common:pendingFixesPopover.${e}`,t),VG=e=>e.old_line_number!==null&&e.new_line_number!==null?BG(`lineReference.oldAndNew`,{oldLine:e.old_line_number,newLine:e.new_line_number}):e.new_line_number===null?e.old_line_number===null?BG(`lineReference.unavailable`):BG(`lineReference.oldOnly`,{oldLine:e.old_line_number}):BG(`lineReference.newOnly`,{newLine:e.new_line_number}),HG=e=>e.old_line_number!==null&&e.new_line_number!==null?BG(`lineReference.oldAndNew`,{oldLine:e.old_line_number,newLine:e.new_line_number}):e.new_line_number===null?e.old_line_number===null?BG(`lineReference.unavailable`):BG(`lineReference.oldOnly`,{oldLine:e.old_line_number}):BG(`lineReference.newOnly`,{newLine:e.new_line_number}),UG=e=>e.subject_type===`file`,WG=({reviewComments:e,reviewFindings:t=[],githubComments:n=[],pendingFixCount:r,triggerMode:i=`full`,canSendReview:a,isSubmittingReview:o,reviewSubmitDisabledReason:s,onClearPendingFixes:c,onSubmitReview:l})=>(0,Z.jsxs)($s,{children:[(0,Z.jsx)(ec,{asChild:!0,children:(0,Z.jsxs)(q,{type:`button`,variant:`default`,size:`sm`,className:i===`compact`?`gap-1.5 px-2.5`:`gap-2`,"aria-label":BG(`triggerLabel`),disabled:r===0,children:[i===`compact`?(0,Z.jsx)(nm,{className:`h-4 w-4`}):(0,Z.jsx)(`span`,{children:BG(`triggerLabel`)}),(0,Z.jsx)(U,{variant:`outline`,className:`h-5 min-w-5 px-1.5 text-[10px]`,children:r}),(0,Z.jsx)(ke,{className:`h-4 w-4`})]})}),(0,Z.jsxs)(tc,{align:`end`,className:`z-[90] w-[30rem] max-w-[calc(100vw-2rem)] p-4`,children:[(0,Z.jsxs)(nc,{className:`flex-row items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(rc,{children:BG(`title`)}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:BG(`description`)})]}),(0,Z.jsx)(U,{variant:`outline`,children:r})]}),r===0?(0,Z.jsx)(`div`,{className:`rounded-xl border border-border bg-background/40 px-4 py-3 text-sm text-muted-foreground`,children:BG(`empty`)}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`max-h-80 space-y-2 overflow-auto pr-1`,children:[e.map(e=>(0,Z.jsx)(`div`,{className:`rounded-xl border border-sky-500/20 bg-sky-500/8 px-3 py-3 shadow-sm`,children:(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(nm,{className:`mt-0.5 h-4 w-4 flex-shrink-0 text-sky-200`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium text-foreground`,children:BG(`manualCommentTitle`)}),(0,Z.jsx)(U,{variant:`outline`,className:zG,children:BG(`manualBadge`)})]}),(0,Z.jsxs)(`div`,{className:`mt-1 text-xs text-sky-100/70`,children:[cb(e.scope),` · `,e.filePath,` · `,sb(e)]}),(0,Z.jsx)(`div`,{className:`mt-2 rounded-lg border border-sky-500/15 bg-background/60 px-3 py-2`,children:(0,Z.jsx)(`p`,{className:`whitespace-pre-wrap text-xs text-foreground`,children:e.comment})})]})]})},`${e.filePath}:${e.changeKey}`)),t.map(e=>(0,Z.jsx)(`div`,{className:`rounded-xl border border-border bg-background/40 px-3 py-3`,children:(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(Kd,{className:`mt-0.5 h-4 w-4 flex-shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium text-foreground`,children:BG(`findingTitle`,{ordinal:e.ordinal})}),(0,Z.jsx)(U,{variant:`outline`,className:`capitalize`,children:e.severity})]}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:[e.file_path,VG(e)].filter(Boolean).join(` · `)}),(0,Z.jsx)(`div`,{className:`mt-2 text-xs font-medium text-foreground`,children:e.title}),(0,Z.jsx)(`p`,{className:`mt-1 whitespace-pre-wrap text-xs text-foreground`,children:e.what_text})]})]})},e.id)),n.map(e=>(0,Z.jsx)(`div`,{className:`rounded-xl border border-border bg-background/40 px-3 py-3`,children:(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(Pc,{className:`mt-0.5 h-4 w-4 flex-shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium text-foreground`,children:e.kind===`review`?BG(`githubReviewSummary`):BG(`githubReviewComment`)}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:[e.file_path,e.kind===`inline`&&!UG(e)?HG(e):e.author].filter(Boolean).join(` · `)}),(0,Z.jsx)(qM,{content:e.body})]})]})},e.id))]}),(0,Z.jsxs)(`div`,{className:`flex justify-between gap-2 pt-2`,children:[(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,disabled:r===0||o,onClick:c,children:BG(`clear`)}),(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`default`,disabled:!a,title:s,onClick:l,className:`gap-2`,children:[(0,Z.jsx)(xw,{className:`h-4 w-4`}),o?BG(`sending`):BG(`sendFixes`,{count:r})]})]})]})]})]}),GG=({commitMessage:e,onCommitMessageChange:t,commitMessageRef:n,selectedFileCount:r,changesDisabledReason:i,canEditCommitMessage:a=!0,canGenerateCommitMessage:o,canCommit:s,isGeneratingCommitMessage:c,isCommitting:l,onGenerateCommitMessage:u,onCommit:d})=>{let{t:f}=X(`common`),p=e.trim()===``,m=!a||c;return(0,Z.jsx)(`div`,{className:`rounded-2xl border border-border bg-background/40 px-4 py-4`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 xl:flex-row xl:items-center xl:gap-4`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 xl:w-56`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-semibold text-foreground`,children:f(`ticketChangesCommitPanel.title`)}),(0,Z.jsx)(`div`,{className:`mt-1 flex items-center gap-3 text-xs text-muted-foreground`,children:(0,Z.jsx)(U,{variant:`outline`,children:f(`ticketChangesCommitPanel.selectedFiles`,{count:r})})})]}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-3 sm:flex-row sm:items-center`,children:[(0,Z.jsxs)(Bs,{"data-disabled":!a,className:`flex-1`,children:[(0,Z.jsx)(Gs,{autocomplete:`off`,"aria-label":f(`ticketChangesCommitPanel.commitMessageAriaLabel`),id:`ticket-changes-commit-message`,ref:n,value:e,onChange:e=>{t(e.target.value)},placeholder:f(`ticketChangesCommitPanel.commitMessagePlaceholder`),disabled:m,title:i}),p&&(0,Z.jsx)(Hs,{align:`inline-end`,children:(0,Z.jsx)(Ws,{"aria-label":f(`ticketChangesCommitPanel.generateCommitMessageAriaLabel`),disabled:!o,onClick:u,title:i,children:f(c?`ticketChangesCommitPanel.generating`:`ticketChangesCommitPanel.generate`)})})]}),(0,Z.jsxs)(q,{type:`button`,onClick:d,disabled:!s,title:i,className:`w-full gap-2 sm:w-auto sm:min-w-32`,children:[(0,Z.jsx)(jc,{className:`h-4 w-4`}),f(l?`ticketChangesCommitPanel.committing`:`ticketChangesCommitPanel.commit`)]})]})]})})},KG=({isCommitsLoading:e,commitsError:t,unpushedCommits:n,canUndoLatestCommit:r,isUndoing:i,aheadCount:a,onUndoLatestCommit:o})=>{let{t:s}=X(`common`);if(!e&&n.length===0&&!t)return null;let c=n.length||a;return(0,Z.jsxs)($s,{children:[(0,Z.jsx)(ec,{asChild:!0,children:(0,Z.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,className:`gap-2`,children:[(0,Z.jsx)(`span`,{children:s(`ticketChangesCommitsPanel.triggerLabel`)}),(0,Z.jsx)(U,{variant:`outline`,className:`h-5 min-w-5 px-1.5 text-[10px]`,children:c}),(0,Z.jsx)(ke,{className:`h-4 w-4`})]})}),(0,Z.jsxs)(tc,{align:`end`,className:`z-[90] w-[28rem] p-4`,children:[(0,Z.jsxs)(nc,{className:`flex-row items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(rc,{children:s(`ticketChangesCommitsPanel.triggerLabel`)}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:s(`ticketChangesCommitsPanel.description`)})]}),!e&&!t&&(0,Z.jsx)(U,{variant:`outline`,children:n.length})]}),e?(0,Z.jsx)(`div`,{className:`rounded-xl border border-border bg-background/40 px-4 py-3 text-sm text-muted-foreground`,children:s(`ticketChangesCommitsPanel.loading`)}):t?(0,Z.jsx)(`div`,{className:`rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm text-amber-100`,children:t}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`flex justify-end`,children:(0,Z.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:o,disabled:!r,children:[(0,Z.jsx)(kf,{className:`h-3.5 w-3.5`}),s(i?`ticketChangesCommitsPanel.undoing`:`ticketChangesCommitsPanel.undoLatestCommit`)]})}),(0,Z.jsx)(`div`,{className:`max-h-72 space-y-2 overflow-auto`,children:n.map(e=>(0,Z.jsxs)(`div`,{className:`rounded-xl border border-border bg-background/40 px-3 py-3`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium text-foreground`,children:e.subject}),(0,Z.jsxs)(`div`,{className:`mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(U,{variant:`outline`,className:`font-mono`,children:e.short_hash}),(0,Z.jsx)(`span`,{children:new Date(e.committed_at).toLocaleString()})]})]},e.hash))})]})]})]})};function qG(e,t,n){let r=n.initialDeps??[],i,a=!0;function o(){let o;n.key&&n.debug?.call(n)&&(o=Date.now());let s=e();if(!(s.length!==r.length||s.some((e,t)=>r[t]!==e)))return i;r=s;let c;if(n.key&&n.debug?.call(n)&&(c=Date.now()),i=t(...s),n.key&&n.debug?.call(n)){let e=Math.round((Date.now()-o)*100)/100,t=Math.round((Date.now()-c)*100)/100,r=t/16,i=(e,t)=>{for(e=String(e);e.length<t;)e=` `+e;return e};console.info(`%c⏱ ${i(t,5)} /${i(e,5)} ms`,`
|
|
143
143
|
font-size: .6rem;
|
|
144
144
|
font-weight: bold;
|
|
145
145
|
color: hsl(${Math.max(0,Math.min(120-120*r,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(i),a=!1,i}return o.updateDeps=e=>{r=e},o}function JG(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var YG=(e,t)=>Math.abs(e-t)<1.01,XG=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},ZG=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},QG=e=>e,$G=e=>{let t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),r=[];for(let e=t;e<=n;e++)r.push(e);return r},eK=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=e=>{let{width:n,height:r}=e;t({width:Math.round(n),height:Math.round(r)})};if(i(ZG(n)),!r.ResizeObserver)return()=>{};let a=new r.ResizeObserver(t=>{let r=()=>{let e=t[0];if(e?.borderBoxSize){let t=e.borderBoxSize[0];if(t){i({width:t.inlineSize,height:t.blockSize});return}}i(ZG(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},tK={passive:!0},nK=typeof window>`u`?!0:`onscrollend`in window,rK=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=0,a=e.options.useScrollendEvent&&nK?()=>void 0:XG(r,()=>{t(i,!1)},e.options.isScrollingResetDelay),o=r=>()=>{let{horizontal:o,isRtl:s}=e.options;i=o?n.scrollLeft*(s&&-1||1):n.scrollTop,a(),t(i,r)},s=o(!0),c=o(!1);n.addEventListener(`scroll`,s,tK);let l=e.options.useScrollendEvent&&nK;return l&&n.addEventListener(`scrollend`,c,tK),()=>{n.removeEventListener(`scroll`,s),l&&n.removeEventListener(`scrollend`,c)}},iK=(e,t,n)=>{if(t?.borderBoxSize){let e=t.borderBoxSize[0];if(e)return Math.round(e[n.options.horizontal?`inlineSize`:`blockSize`])}return e[n.options.horizontal?`offsetWidth`:`offsetHeight`]},aK=(e,{adjustments:t=0,behavior:n},r)=>{var i,a;let o=e+t;(a=(i=r.scrollElement)?.scrollTo)==null||a.call(i,{[r.options.horizontal?`left`:`top`]:o,behavior:n})},oK=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var e;return((e=this.targetWindow?.performance)?.now)?.call(e)??Date.now()},this.observer=(()=>{let e=null,t=()=>e||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:e=new this.targetWindow.ResizeObserver(e=>{e.forEach(e=>{let t=()=>{let t=e.target,n=this.indexFromElement(t);if(!t.isConnected){this.observer.unobserve(t);return}this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,e,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(t):t()})}));return{disconnect:()=>{var n;(n=t())==null||n.disconnect(),e=null},observe:e=>t()?.observe(e,{box:`border-box`}),unobserve:e=>t()?.unobserve(e)}})(),this.range=null,this.setOptions=e=>{Object.entries(e).forEach(([t,n])=>{n===void 0&&delete e[t]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:QG,rangeExtractor:$G,onChange:()=>{},measureElement:iK,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:`data-index`,initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:`estimate`,...e}},this.notify=e=>{var t,n;(n=(t=this.options).onChange)==null||n.call(t,this,e)},this.maybeNotify=qG(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),e=>{this.notify(e)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(e=>e()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{let e=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==e){if(this.cleanup(),!e){this.maybeNotify();return}this.scrollElement=e,this.scrollElement&&`ownerDocument`in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=this.scrollElement?.window??null,this.elementsCache.forEach(e=>{this.observer.observe(e)}),this.unsubs.push(this.options.observeElementRect(this,e=>{this.scrollRect=e,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(e,t)=>{this.scrollAdjustments=0,this.scrollDirection=t?this.getScrollOffset()<e?`forward`:`backward`:null,this.scrollOffset=e,this.isScrolling=t,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?`width`:`height`]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset==`function`?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(e,t)=>{let n=new Map,r=new Map;for(let i=t-1;i>=0;i--){let t=e[i];if(n.has(t.lane))continue;let a=r.get(t.lane);if(a==null||t.end>a.end?r.set(t.lane,t):t.end<a.end&&n.set(t.lane,!0),n.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((e,t)=>e.end===t.end?e.index-t.index:e.end-t.end)[0]:void 0},this.getMeasurementOptions=qG(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(e,t,n,r,i,a,o)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMeasuredCacheIndexes=[],{count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o}),{key:!1}),this.getMeasurements=qG(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o},s)=>{if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>e)for(let t of this.laneAssignments.keys())t>=e&&this.laneAssignments.delete(t);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(e=>{this.itemSizeCache.set(e.key,e.size)}));let c=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1);let l=this.measurementsCache.slice(0,c),u=Array(a).fill(void 0);for(let e=0;e<c;e++){let t=l[e];t&&(u[t.lane]=e)}for(let i=c;i<e;i++){let e=r(i),a=this.laneAssignments.get(i),c,d,f=o===`estimate`||s.has(e);if(a!==void 0&&this.options.lanes>1){c=a;let e=u[c],r=e===void 0?void 0:l[e];d=r?r.end+this.options.gap:t+n}else{let e=this.options.lanes===1?l[i-1]:this.getFurthestMeasurement(l,i);d=e?e.end+this.options.gap:t+n,c=e?e.lane:i%this.options.lanes,this.options.lanes>1&&f&&this.laneAssignments.set(i,c)}let p=s.get(e),m=typeof p==`number`?p:this.options.estimateSize(i),h=d+m;l[i]={index:i,start:d,size:m,end:h,key:e,lane:c},u[c]=i}return this.measurementsCache=l,l},{key:!1,debug:()=>this.options.debug}),this.calculateRange=qG(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>this.range=e.length>0&&t>0?cK({measurements:e,outerSize:t,scrollOffset:n,lanes:r}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=qG(()=>{let e=null,t=null,n=this.calculateRange();return n&&(e=n.startIndex,t=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,e,t]),[this.options.rangeExtractor,this.options.overscan,this.options.count,e,t]},(e,t,n,r,i)=>r===null||i===null?[]:e({startIndex:r,endIndex:i,overscan:t,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=e=>{let t=this.options.indexAttribute,n=e.getAttribute(t);return n?parseInt(n,10):(console.warn(`Missing attribute name '${t}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=e=>{if(!this.scrollState||this.scrollState.behavior!==`smooth`)return!0;let t=this.scrollState.index??this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index;if(t!==void 0&&this.range){let n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),r=Math.max(0,t-n),i=Math.min(this.options.count-1,t+n);return e>=r&&e<=i}return!0},this.measureElement=e=>{if(!e){this.elementsCache.forEach((e,t)=>{e.isConnected||(this.observer.unobserve(e),this.elementsCache.delete(t))});return}let t=this.indexFromElement(e),n=this.options.getItemKey(t),r=this.elementsCache.get(n);r!==e&&(r&&this.observer.unobserve(r),this.observer.observe(e),this.elementsCache.set(n,e)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(t)&&this.resizeItem(t,this.options.measureElement(e,void 0,this))},this.resizeItem=(e,t)=>{let n=this.measurementsCache[e];if(!n)return;let r=t-(this.itemSizeCache.get(n.key)??n.size);r!==0&&(this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?n.start<this.getScrollOffset()+this.scrollAdjustments:this.shouldAdjustScrollPositionOnItemSizeChange(n,r,this))&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=r,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(n.index),this.itemSizeCache=new Map(this.itemSizeCache.set(n.key,t)),this.notify(!1))},this.getVirtualItems=qG(()=>[this.getVirtualIndexes(),this.getMeasurements()],(e,t)=>{let n=[];for(let r=0,i=e.length;r<i;r++){let i=t[e[r]];n.push(i)}return n},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=e=>{let t=this.getMeasurements();if(t.length!==0)return JG(t[sK(0,t.length-1,e=>JG(t[e]).start,e)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if(`scrollHeight`in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{let e=this.scrollElement.document.documentElement;return this.options.horizontal?e.scrollWidth-this.scrollElement.innerWidth:e.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(e,t,n=0)=>{if(!this.scrollElement)return 0;let r=this.getSize(),i=this.getScrollOffset();t===`auto`&&(t=e>=i+r?`end`:`start`),t===`center`?e+=(n-r)/2:t===`end`&&(e-=r);let a=this.getMaxScrollOffset();return Math.max(Math.min(a,e),0)},this.getOffsetForIndex=(e,t=`auto`)=>{e=Math.max(0,Math.min(e,this.options.count-1));let n=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[e];if(!i)return;if(t===`auto`)if(i.end>=r+n-this.options.scrollPaddingEnd)t=`end`;else if(i.start<=r+this.options.scrollPaddingStart)t=`start`;else return[r,t];if(t===`end`&&e===this.options.count-1)return[this.getMaxScrollOffset(),t];let a=t===`end`?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,t,i.size),t]},this.scrollToOffset=(e,{align:t=`start`,behavior:n=`auto`}={})=>{let r=this.getOffsetForAlignment(e,t),i=this.now();this.scrollState={index:null,align:t,behavior:n,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(e,{align:t=`auto`,behavior:n=`auto`}={})=>{e=Math.max(0,Math.min(e,this.options.count-1));let r=this.getOffsetForIndex(e,t);if(!r)return;let[i,a]=r,o=this.now();this.scrollState={index:e,align:a,behavior:n,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(e,{behavior:t=`auto`}={})=>{let n=this.getScrollOffset()+e,r=this.now();this.scrollState={index:null,align:`start`,behavior:t,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:t}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{let e=this.getMeasurements(),t;if(e.length===0)t=this.options.paddingStart;else if(this.options.lanes===1)t=e[e.length-1]?.end??0;else{let n=Array(this.options.lanes).fill(null),r=e.length-1;for(;r>=0&&n.some(e=>e===null);){let t=e[r];n[t.lane]===null&&(n[t.lane]=t.end),r--}t=Math.max(...n.filter(e=>e!==null))}return Math.max(t-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(e,{adjustments:t,behavior:n})=>{this.options.scrollToFn(e,{behavior:n,adjustments:t},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()})}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}let e=this.scrollState.index==null?void 0:this.getOffsetForIndex(this.scrollState.index,this.scrollState.align),t=e?e[0]:this.scrollState.lastTargetOffset,n=t!==this.scrollState.lastTargetOffset;if(!n&&YG(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=1){this.scrollState=null;return}}else this.scrollState.stableFrames=0,n&&(this.scrollState.lastTargetOffset=t,this.scrollState.behavior=`auto`,this._scrollToOffset(t,{adjustments:void 0,behavior:`auto`}));this.scheduleScrollReconcile()}},sK=(e,t,n,r)=>{for(;e<=t;){let i=(e+t)/2|0,a=n(i);if(a<r)e=i+1;else if(a>r)t=i-1;else return i}return e>0?e-1:0};function cK({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){let i=e.length-1,a=t=>e[t].start;if(e.length<=r)return{startIndex:0,endIndex:i};let o=sK(0,i,a,n),s=o;if(r===1)for(;s<i&&e[s].end<n+t;)s++;else if(r>1){let a=Array(r).fill(0);for(;s<i&&a.some(e=>e<n+t);){let t=e[s];a[t.lane]=t.end,s++}let c=Array(r).fill(n+t);for(;o>=0&&c.some(e=>e>=n);){let t=e[o];c[t.lane]=t.start,o--}o=Math.max(0,o-o%r),s=Math.min(i,s+(r-1-s%r))}return{startIndex:o,endIndex:s}}var lK=typeof document<`u`?Y.useLayoutEffect:Y.useEffect;function uK({useFlushSync:e=!0,...t}){let n=Y.useReducer(()=>({}),{})[1],r={...t,onChange:(r,i)=>{var a;e&&i?(0,Lc.flushSync)(n):n(),(a=t.onChange)==null||a.call(t,r,i)}},[i]=Y.useState(()=>new oK(r));return i.setOptions(r),lK(()=>i._didMount(),[]),lK(()=>i._willUpdate()),i}function dK(e){return uK({observeElementRect:eK,observeElementOffset:rK,scrollToFn:aK,...e})}var fK=8,pK=520,mK=2,hK=(e,t)=>Pe.t(`common:ticketChangesDiffPanel.${e}`,t),gK=()=>(0,Z.jsx)(`div`,{"data-testid":`ticket-diff-resize-placeholder`,className:`space-y-4 px-3 py-3`,children:[{gutter:`w-8`,code:`w-[68%]`},{gutter:`w-10`,code:`w-[54%]`},{gutter:`w-8`,code:`w-[74%]`},{gutter:`w-6`,code:`w-[38%]`},{gutter:`w-10`,code:`w-[82%]`},{gutter:`w-7`,code:`w-[61%]`},{gutter:`w-9`,code:`w-[48%]`},{gutter:`w-8`,code:`w-[71%]`},{gutter:`w-11`,code:`w-[57%]`},{gutter:`w-7`,code:`w-[66%]`},{gutter:`w-9`,code:`w-[43%]`},{gutter:`w-8`,code:`w-[76%]`}].map((e,t)=>(0,Z.jsxs)(`div`,{"data-testid":`ticket-diff-resize-placeholder-row`,className:`flex items-center gap-4`,children:[(0,Z.jsx)(`div`,{className:K(`h-4 rounded bg-muted/80`,e.gutter)}),(0,Z.jsx)(`div`,{className:K(`h-4 rounded bg-muted/60`,e.code)})]},`${e.gutter}-${e.code}-${t}`))}),_K=({additions:e,deletions:t,fileCount:n})=>n===null?[{key:`additions`,content:`+${e}`,className:`font-mono text-emerald-400`},{key:`deletions`,content:`-${t}`,className:`font-mono text-rose-400`}]:[{key:`files`,content:hK(`stats.fileCount`,{count:n}),className:`text-muted-foreground`},{key:`additions`,content:`+${e}`,className:`font-mono text-emerald-400`},{key:`deletions`,content:`-${t}`,className:`font-mono text-rose-400`}],vK=({control:e,mode:t})=>typeof e==`function`?e(t):e??null,yK=e=>e.reduce((e,t)=>e+t.hunks.reduce((e,t)=>e+t.changes.length,0),0),bK=e=>Zy(e),xK=(e,t)=>{let n=`oldPath`in e&&typeof e.oldPath==`string`?t(e.oldPath):``,r=`newPath`in e&&typeof e.newPath==`string`?t(e.newPath):``;return[...new Set([r,n].filter(e=>e&&e!==`/dev/null`))]},SK=e=>e.subject_type===`file`,CK=e=>e.subject_type===`line`,wK=`border-sky-400/30 bg-sky-400/10 text-sky-100`,TK=({context:e,comment:t,reviewDraftInput:n,canEdit:r,autoFocus:i,isReadOnly:a,hasSavedComment:o,onReviewDraftInputChange:s,onCancelReviewDraft:c,onEditReviewDraft:l,onRemoveReviewDraft:u,onSaveReviewDraft:d})=>{let f=(0,Y.useRef)(null),[p,m]=(0,Y.useState)(()=>n),h=bK(e.change);return(0,Y.useEffect)(()=>{!i||a||f.current?.focus({preventScroll:!0})},[i,a]),(0,Z.jsxs)(`div`,{className:`rounded-xl border border-sky-500/20 bg-sky-500/8 p-3 shadow-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(U,{variant:`outline`,className:wK,children:hK(`reviewComment.manualBadge`)}),(0,Z.jsx)(`div`,{className:`text-[11px] font-medium uppercase tracking-wide text-sky-100/80`,children:hK(o?`reviewComment.commentOnLine`:`reviewComment.addCommentToLine`,{lineNumber:h})})]}),(0,Z.jsxs)(`div`,{className:`mt-2 space-y-3`,children:[a?(0,Z.jsx)(`div`,{className:`whitespace-pre-wrap rounded-xl border border-sky-500/15 bg-background/70 px-3 py-2.5 text-xs text-foreground`,children:t}):(0,Z.jsx)(zs,{ref:f,"aria-label":hK(`reviewComment.ariaLabel`,{filePath:e.filePath}),value:p,onChange:e=>{m(e.target.value),s(e.target.value)},disabled:!r,className:`min-h-20 text-xs`,placeholder:hK(`reviewComment.placeholder`)}),(0,Z.jsx)(`div`,{className:`flex gap-2`,children:a?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(q,{type:`button`,size:`xs`,variant:`outline`,onClick:()=>{l(e.commentKey)},disabled:!r,children:[(0,Z.jsx)(Ef,{className:`h-3.5 w-3.5`}),hK(`reviewComment.edit`)]}),(0,Z.jsx)(q,{type:`button`,size:`xs`,variant:`ghost`,onClick:()=>{u(e.commentKey)},disabled:!r,children:hK(`reviewComment.remove`)})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(q,{type:`button`,size:`xs`,onClick:()=>{d(e,p)},disabled:!r||!p.trim(),children:hK(`reviewComment.add`)}),(0,Z.jsx)(q,{type:`button`,size:`xs`,variant:`ghost`,onClick:c,children:hK(`reviewComment.cancel`)})]})})]})]})},EK=e=>e===`high`?`destructive`:e===`medium`?`warning`:`outline`,DK=e=>e.old_line_number!==null&&e.new_line_number!==null?hK(`lineReference.oldAndNew`,{oldLine:e.old_line_number,newLine:e.new_line_number}):e.new_line_number===null?e.old_line_number===null?hK(`lineReference.unavailable`):hK(`lineReference.oldOnly`,{oldLine:e.old_line_number}):hK(`lineReference.newOnly`,{newLine:e.new_line_number}),OK=({finding:e,isSelected:t,onToggle:n})=>{let[r,i]=(0,Y.useState)(!1);return(0,Z.jsxs)(`div`,{className:`rounded-xl border border-slate-400/30 bg-slate-400/10 p-3 shadow-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,children:[(0,Z.jsx)(Kd,{className:`h-3.5 w-3.5 flex-shrink-0`}),(0,Z.jsx)(`div`,{children:hK(`reviewFinding.title`,{ordinal:e.ordinal})}),(0,Z.jsx)(U,{variant:EK(e.severity),className:`normal-case`,children:e.severity})]}),(0,Z.jsx)(`div`,{className:`mt-2 text-sm font-medium text-foreground`,children:e.title}),(0,Z.jsx)(`p`,{className:`mt-1 whitespace-pre-wrap text-xs text-foreground`,children:e.what_text})]}),(0,Z.jsxs)(q,{type:`button`,size:`xs`,variant:t?`default`:`outline`,onClick:n,className:`gap-1.5`,children:[!t&&(0,Z.jsx)(zl,{className:`h-3.5 w-3.5`}),hK(t?`reviewFinding.selected`:`reviewFinding.fix`)]})]}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:DK(e)}),e.file_path&&(0,Z.jsx)(`span`,{children:e.file_path})]}),(e.why_text||e.fix_text)&&(0,Z.jsxs)(`div`,{className:`mt-3`,children:[(0,Z.jsx)(q,{type:`button`,size:`xs`,variant:`ghost`,onClick:()=>{i(e=>!e)},children:hK(r?`reviewFinding.hideDetails`:`reviewFinding.details`)}),r&&(0,Z.jsxs)(`div`,{className:`mt-2 space-y-2 rounded-xl border border-border bg-background/60 p-3 text-xs text-foreground`,children:[e.why_text&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`font-medium text-muted-foreground`,children:hK(`reviewFinding.whyItMatters`)}),(0,Z.jsx)(`p`,{className:`mt-1 whitespace-pre-wrap`,children:e.why_text})]}),e.fix_text&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`font-medium text-muted-foreground`,children:hK(`reviewFinding.requestedFix`)}),(0,Z.jsx)(`p`,{className:`mt-1 whitespace-pre-wrap`,children:e.fix_text})]})]})]})]})},kK=e=>e.old_line_number!==null&&e.new_line_number!==null?hK(`lineReference.oldAndNew`,{oldLine:e.old_line_number,newLine:e.new_line_number}):e.new_line_number===null?e.old_line_number===null?hK(`lineReference.unavailable`):hK(`lineReference.oldOnly`,{oldLine:e.old_line_number}):hK(`lineReference.newOnly`,{newLine:e.new_line_number}),AK=e=>e.old_line_number!==null||e.new_line_number!==null,jK=e=>e.kind===`review`?hK(`githubComment.reviewSummary`):SK(e)?hK(`githubComment.fileComment`):AK(e)||CK(e)?hK(`githubComment.inlineComment`):hK(`githubComment.fileComment`),MK=({comment:e,isSelected:t,onToggle:n})=>(0,Z.jsxs)(`div`,{className:`rounded-xl border border-violet-400/30 bg-violet-400/10 p-3 shadow-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,children:[(0,Z.jsx)(U,{variant:`outline`,className:`border-violet-400/40 bg-violet-400/10 text-violet-100`,children:hK(`githubComment.badge`)}),(0,Z.jsx)(`span`,{children:jK(e)}),e.is_outdated&&(0,Z.jsx)(U,{variant:`warning`,className:`normal-case`,children:hK(`githubComment.outdated`)})]}),(0,Z.jsx)(`div`,{className:`mt-2 text-sm font-medium text-foreground`,children:e.author}),(0,Z.jsx)(qM,{content:e.body})]}),(0,Z.jsxs)(q,{type:`button`,size:`xs`,variant:t?`default`:`outline`,onClick:n,className:`gap-1.5`,children:[!t&&(0,Z.jsx)(zl,{className:`h-3.5 w-3.5`}),hK(t?`reviewFinding.selected`:`reviewFinding.fix`)]})]}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2 text-[11px] text-muted-foreground`,children:[e.file_path&&(0,Z.jsx)(`span`,{children:e.file_path}),e.kind===`inline`&&!SK(e)&&AK(e)&&(0,Z.jsx)(`span`,{children:kK(e)}),(0,Z.jsx)(`span`,{children:new Date(e.updated_at).toLocaleString()}),(0,Z.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,className:`text-violet-200 underline underline-offset-2 transition-colors hover:text-violet-100`,children:hK(`githubComment.openOnGitHub`)})]})]}),NK=({allDiffFiles:e,resolveFilePath:t,normalizeDiffPath:n,reviewFindings:r})=>{let i=new Map,a=new Map,o=[],s=new Map;for(let t of e)for(let e of xK(t,n))s.has(e)||s.set(e,t);for(let e of r){let n=e.file_path,r=n?s.get(n):null;if(!r||!n){o.push(e);continue}let c=t(r),l=null;for(let t of r.hunks){for(let n of t.changes)if($y(e,n)){l=lv(n);break}if(l)break}if(l){let t=i.get(c)??new Map,n=t.get(l)??[];t.set(l,[...n,e]),i.set(c,t);continue}a.set(c,[...a.get(c)??[],e])}return{inlineByFilePath:i,fileLevelByFilePath:a,globalFindings:o}},PK=({allDiffFiles:e,resolveFilePath:t,normalizeDiffPath:n,githubComments:r})=>{let i=new Map,a=new Map,o=[],s=new Map;for(let t of e)for(let e of xK(t,n))s.has(e)||s.set(e,t);for(let e of r){if(e.kind===`review`||!e.file_path){o.push(e);continue}let n=s.get(e.file_path);if(!n){o.push(e);continue}let r=t(n);if(SK(e)||!e.subject_type&&!AK(e)){a.set(r,[...a.get(r)??[],e]);continue}let c=null;for(let t of n.hunks){for(let n of t.changes)if(Qy(e,n)){c=lv(n);break}if(c)break}if(!c){o.push(e);continue}let l=i.get(r)??new Map,u=l.get(c)??[];l.set(c,[...u,e]),i.set(r,l)}return{inlineByFilePath:i,fileLevelByFilePath:a,fallbackComments:o}},FK=({filePath:e,hunks:t,activeReviewTarget:n,editingReviewCommentKey:r,reviewDraftInstanceKey:i,reviewDraftInput:a,reviewComments:o,reviewFindingsByChangeKey:s,githubCommentsByChangeKey:c,selectedReviewFindingIds:l,selectedGitHubCommentIds:u,canEditActiveReviewDraft:d,onToggleReviewFindingSelection:f,onToggleGitHubCommentSelection:p,onReviewDraftInputChange:m,onCancelReviewDraft:h,onEditReviewDraft:g,onRemoveReviewDraft:_,onSaveReviewDraft:v})=>{let y=new Map(o.map(e=>[lb(e.filePath,e.changeKey),e]));return t.reduce((t,o)=>{for(let b of o.changes){let x=lv(b),S=lb(e,x),C=n?.commentKey===S,w=y.get(S),T=r===S,E=s.get(x)??[],D=c.get(x)??[];if(!C&&!w&&E.length===0&&D.length===0)continue;let O={filePath:e,changeKey:x,commentKey:S,hunk:o,change:b},k=!!w&&!T&&!C,A=k?w?.comment??``:a;t[x]=(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[E.map(e=>(0,Z.jsx)(OK,{finding:e,isSelected:l.includes(e.id),onToggle:()=>{f(e.id)}},e.id)),D.map(e=>(0,Z.jsx)(MK,{comment:e,isSelected:u.includes(e.id),onToggle:()=>{p(e.id)}},e.id)),(C||w)&&(0,Z.jsx)(TK,{context:O,comment:w?.comment??``,reviewDraftInput:A,canEdit:d,autoFocus:C||T,isReadOnly:k,hasSavedComment:!!w,onReviewDraftInputChange:m,onCancelReviewDraft:h,onEditReviewDraft:g,onRemoveReviewDraft:_,onSaveReviewDraft:v},`${i??O.commentKey}:${k?`readonly`:`editable`}`)]})}return t},{})},IK=e=>e.reduce((e,t)=>{for(let n of t.changes)e.set(lv(n),{hunk:t,change:n});return e},new Map),LK=(0,Y.memo)(({selectedDiffPath:e,sidebarFiles:t,diffResponse:n,isDiffLoading:r,diffError:i,allDiffFiles:a,renderedFiles:o,viewType:s,onViewTypeChange:c,onRetry:l,activeReviewTarget:u,editingReviewCommentKey:d,reviewDraftInstanceKey:f,reviewDraftInput:p,reviewComments:m,reviewFindings:h,githubComments:g,selectedReviewFindingIds:_,selectedGitHubCommentIds:v,canSelectReviewTarget:y,canEditActiveReviewDraft:b,reviewFindingsError:x,gitHubCommentsError:S,hasStaleReviewFindings:C,onSelectReviewTarget:w,onToggleReviewFindingSelection:T,onToggleGitHubCommentSelection:E,onReviewDraftInputChange:D,onCancelReviewDraft:O,onEditReviewDraft:k,onRemoveReviewDraft:A,onSaveReviewDraft:j,diffThemeClassName:M,resolveFilePath:N,normalizeDiffPath:P,emptyStateTitle:F=hK(`states.emptyTitle`),emptyStateDescription:I=null,filePickerControl:L,reviewSummaryControl:R,extraHeaderControl:z,headerLayout:ee=`stacked`,surfaceVariant:te=`default`,showViewTypeToggle:ne=!0,gutterVariant:re=`default`,isResizing:B=!1,resizePlaceholderLineThreshold:ie=1/0,onVisibleFilePathsChange:V})=>{let H=(0,Y.useRef)(null),{mode:ae,ref:oe}=Bp({compactAt:te===`flat`?460:620,tightAt:te===`flat`?360:500}),se=!!n?.diff?.trim()||o.length>0||(n?.files.length??0)>0,ce=(0,Y.useMemo)(()=>yK(o),[o]),le=e===`all`&&o.length>=fK,ue=B&&ce>ie,de=(0,Y.useMemo)(()=>o.map(e=>N(e)).join(`
|
|
146
|
-
`),[o,N]),fe=dK({count:le?o.length:0,getScrollElement:()=>H.current,estimateSize:()=>pK,overscan:mK,getItemKey:e=>{let t=o[e];return t?`${N(t)}:${t.type??`modify`}`:e},initialRect:{width:0,height:900}}),pe=(0,Y.useMemo)(()=>new Map(n?.files.map(e=>[e.path,e])??[]),[n?.files]),me=(0,Y.useMemo)(()=>NK({allDiffFiles:a,resolveFilePath:N,normalizeDiffPath:P,reviewFindings:C?[]:h}),[a,C,P,N,h]),W=(0,Y.useMemo)(()=>PK({allDiffFiles:a,resolveFilePath:N,normalizeDiffPath:P,githubComments:g}),[a,g,P,N]);(0,Y.useEffect)(()=>{let e=H.current;e&&(e.scrollTop=0)},[e]),(0,Y.useEffect)(()=>{let e=H.current;return()=>{window.getSelection()?.removeAllRanges(),e&&(e.scrollTop=0)}},[de]);let he=fe.getVirtualItems(),G=(0,Y.useMemo)(()=>le?he.map(e=>N(o[e.index])):o.map(e=>N(e)),[o,N,le,he]);(0,Y.useEffect)(()=>{V?.(G)},[V,G]);let ge=le&&he.length>0?he[0]?.start??0:0,_e=le&&he.length>0?Math.max(0,fe.getTotalSize()-(he[he.length-1]?.end??0)):0,ve=le?he.map(e=>({file:o[e.index],virtualItem:e})):o.map(e=>({file:e,virtualItem:null})),ye=e===`all`?null:t.find(t=>t.path===e)??null,be=e===`all`?_K({additions:n?.stats?.additions??0,deletions:n?.stats?.deletions??0,fileCount:n?.stats?.files_changed??null}):ye?_K({additions:ye.additions,deletions:ye.deletions,fileCount:null}):[],xe=(0,Y.useMemo)(()=>ne?(0,Z.jsxs)(LG,{type:`single`,size:`sm`,variant:`outline`,value:s,onValueChange:e=>{(e===`split`||e===`unified`)&&c(e)},children:[(0,Z.jsx)(RG,{value:`unified`,children:hK(`viewType.unified`)}),(0,Z.jsx)(RG,{value:`split`,children:hK(`viewType.split`)})]}):null,[c,ne,s]),Se=(0,Y.useMemo)(()=>[vK({control:L,mode:ae}),vK({control:R,mode:ae})].filter(Boolean),[L,ae,R]),Ce=xe||Se.length>0||z;return(0,Z.jsxs)(`section`,{className:K(`flex min-h-0 flex-1 flex-col overflow-hidden`,te===`default`?`rounded-2xl border border-border bg-background/30`:`bg-transparent`),children:[(0,Z.jsx)(`div`,{ref:oe,"data-responsive-mode":ae,"data-testid":`ticket-diff-header`,className:K(`grid min-w-0 items-start gap-x-3 gap-y-2 border-b px-4 py-3`,te===`default`?`border-border`:`border-border/70 px-3`,ee===`stacked`?z?`grid-cols-[minmax(0,1fr)_auto]`:`grid-cols-[minmax(0,1fr)]`:Ce?`grid-cols-[minmax(0,1fr)_auto]`:`grid-cols-[minmax(0,1fr)]`),children:ee===`stacked`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{"data-testid":`ticket-diff-header-left`,className:`grid min-w-0 gap-2`,children:[(0,Z.jsxs)(`div`,{"data-testid":`ticket-diff-header-info`,className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:e===`all`?hK(`header.allChanges`):e}),be.length>0&&(0,Z.jsx)(`div`,{className:`mt-1 flex items-center gap-3 whitespace-nowrap text-xs`,children:be.map(e=>(0,Z.jsx)(`span`,{className:e.className,children:e.content},e.key))})]}),xe||Se.length>0?(0,Z.jsxs)(`div`,{"data-testid":`ticket-diff-header-controls`,className:`flex min-w-0 flex-wrap items-center gap-2 justify-start`,children:[xe?(0,Z.jsx)(`div`,{"data-testid":`ticket-diff-header-primary-controls`,className:`shrink-0`,children:xe}):null,Se.length>0?(0,Z.jsx)(`div`,{"data-testid":`ticket-diff-header-secondary-controls`,className:`flex min-w-0 items-center gap-2 justify-start`,children:Se.map((e,t)=>(0,Z.jsx)(`div`,{className:`min-w-0 shrink-0`,children:e},`header-secondary-control-${t+1}`))}):null]}):null]}),z?(0,Z.jsx)(`div`,{"data-testid":`ticket-diff-header-close`,className:`flex shrink-0 items-start justify-end`,children:z}):null]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{"data-testid":`ticket-diff-header-info`,className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:e===`all`?hK(`header.allChanges`):e}),be.length>0&&(0,Z.jsx)(`div`,{className:`mt-1 flex items-center gap-3 whitespace-nowrap text-xs`,children:be.map(e=>(0,Z.jsx)(`span`,{className:e.className,children:e.content},e.key))})]}),Ce?(0,Z.jsxs)(`div`,{"data-testid":`ticket-diff-header-inline-controls`,className:`flex min-w-0 flex-wrap items-start justify-end gap-2`,children:[xe?(0,Z.jsx)(`div`,{"data-testid":`ticket-diff-header-primary-controls`,className:`shrink-0`,children:xe}):null,Se.length>0?(0,Z.jsx)(`div`,{"data-testid":`ticket-diff-header-secondary-controls`,className:`flex min-w-0 flex-wrap items-center justify-end gap-2`,children:Se.map((e,t)=>(0,Z.jsx)(`div`,{className:`min-w-0 shrink-0`,children:e},`header-secondary-control-${t+1}`))}):null,z?(0,Z.jsx)(`div`,{"data-testid":`ticket-diff-header-close`,className:`flex shrink-0 items-start justify-end`,children:z}):null]}):null]})}),(0,Z.jsx)(`div`,{ref:H,"data-testid":`ticket-diff-scroll-region`,className:`min-h-0 flex-1 overflow-auto`,children:(0,Z.jsxs)(`div`,{className:K(`min-h-full pb-4 pt-4`,te===`default`?`px-4`:`px-0`),children:[r&&(0,Z.jsx)(`div`,{className:`flex h-full min-h-48 items-center justify-center text-sm text-muted-foreground`,children:hK(`states.loading`)}),!r&&i&&(0,Z.jsxs)(`div`,{className:`flex h-full min-h-48 flex-col items-center justify-center gap-4 text-center`,children:[(0,Z.jsx)(`p`,{className:`max-w-md text-sm text-rose-300`,children:i}),(0,Z.jsx)(q,{type:`button`,variant:`outline`,onClick:l,children:hK(`states.retry`)})]}),!r&&!i&&n&&!se&&(0,Z.jsxs)(`div`,{className:`flex h-full min-h-48 flex-col items-center justify-center gap-2 text-center`,children:[(0,Z.jsx)(`div`,{className:`text-sm text-foreground`,children:F}),I&&(0,Z.jsx)(`div`,{className:`max-w-md text-xs text-muted-foreground`,children:I})]}),!r&&!i&&n&&se&&e!==`all`&&o.length===0&&(0,Z.jsxs)(`div`,{className:`flex h-full min-h-48 flex-col items-center justify-center gap-3 text-center`,children:[(0,Z.jsx)(`div`,{className:`text-sm text-foreground`,children:hK(`states.noRenderableFileTitle`)}),(0,Z.jsx)(`div`,{className:`max-w-md text-xs text-muted-foreground`,children:e})]}),!r&&!i&&n&&se&&o.length>0&&ue&&(0,Z.jsx)(gK,{}),!r&&!i&&n&&se&&o.length>0&&!ue&&(0,Z.jsxs)(`div`,{className:K(`archon-diff-viewer`,re===`compact`&&`archon-diff-viewer--compact-gutter`,e===`all`&&te===`default`&&`space-y-6`,e===`all`&&te===`flat`&&`space-y-0`,M),children:[x&&(0,Z.jsx)(`div`,{className:`rounded-xl border border-dashed border-border bg-background/40 px-4 py-3 text-xs text-muted-foreground`,children:x}),S&&(0,Z.jsx)(`div`,{className:`rounded-xl border border-dashed border-border bg-background/40 px-4 py-3 text-xs text-muted-foreground`,children:S}),me.globalFindings.length>0&&(0,Z.jsxs)(`section`,{className:`rounded-xl border border-border bg-card/70 p-3`,children:[(0,Z.jsx)(`div`,{className:`mb-3 text-sm font-semibold text-foreground`,children:hK(`reviewFinding.sectionTitle`)}),(0,Z.jsx)(`div`,{className:`space-y-3`,children:me.globalFindings.map(e=>(0,Z.jsx)(OK,{finding:e,isSelected:_.includes(e.id),onToggle:()=>{T(e.id)}},e.id))})]}),e===`all`&&W.fallbackComments.length>0&&(0,Z.jsxs)(`section`,{className:`rounded-xl border border-border bg-card/70 p-3`,children:[(0,Z.jsx)(`div`,{className:`mb-3 text-sm font-semibold text-foreground`,children:hK(`githubComment.sectionTitle`)}),(0,Z.jsx)(`div`,{className:`space-y-3`,children:W.fallbackComments.map(e=>(0,Z.jsx)(MK,{comment:e,isSelected:v.includes(e.id),onToggle:()=>{E(e.id)}},e.id))})]}),ge>0&&(0,Z.jsx)(`div`,{style:{height:ge}}),ve.map(({file:t,virtualItem:n})=>{let r=N(t),i=pe.get(r),a=IK(t.hunks),o=me.inlineByFilePath.get(r)??new Map,c=W.inlineByFilePath.get(r)??new Map,l=me.fileLevelByFilePath.get(r)??[],h=W.fileLevelByFilePath.get(r)??[],g=d?m.find(e=>lb(e.filePath,e.changeKey)===d)??null:null,x=[...m.filter(e=>e.filePath===r).map(e=>e.changeKey),...u?.filePath===r?[u.changeKey]:[],...g?.filePath===r?[g.changeKey]:[]],S=FK({filePath:r,hunks:t.hunks,activeReviewTarget:u,editingReviewCommentKey:d,reviewDraftInstanceKey:f,reviewDraftInput:p,reviewComments:m,reviewFindingsByChangeKey:o,githubCommentsByChangeKey:c,selectedReviewFindingIds:_,selectedGitHubCommentIds:v,canEditActiveReviewDraft:b,onToggleReviewFindingSelection:T,onToggleGitHubCommentSelection:E,onReviewDraftInputChange:D,onCancelReviewDraft:O,onEditReviewDraft:k,onRemoveReviewDraft:A,onSaveReviewDraft:j}),C=(0,Z.jsx)(Yv,{diffType:t.type,hunks:t.hunks,tokens:t.tokens,viewType:s,selectedChanges:[...new Set(x)],widgets:S,renderGutter:({change:e,side:t,renderDefault:n,wrapInAnchor:r,inHoverState:i})=>{if(!e)return r(n());let a=lv(e),o=t===`new`,c=y&&t===`new`,l=s===`unified`&&e.type===`normal`&&t===`new`?null:r(n());return(0,Z.jsxs)(`div`,{className:K(`flex items-center justify-end pr-1`,re===`compact`?`gap-1 pr-0.5`:`gap-2`),children:[l,o&&(0,Z.jsx)(`span`,{"data-diff-gutter-action-slot":`true`,className:[re===`compact`?`flex size-5 shrink-0 items-center justify-center rounded-md border border-emerald-300/80 bg-emerald-400 text-[#07130d] shadow-[0_8px_20px_rgba(16,185,129,0.22)] transition-all`:`flex size-6 shrink-0 items-center justify-center rounded-md border border-emerald-300/80 bg-emerald-400 text-[#07130d] shadow-[0_8px_20px_rgba(16,185,129,0.22)] transition-all`,c&&i?`border-emerald-200 bg-emerald-300 opacity-100`:`opacity-0`,!c&&`pointer-events-none`].join(` `),"aria-hidden":`true`,children:(0,Z.jsx)(zl,{className:re===`compact`?`h-3 w-3`:`h-3.5 w-3.5`})}),(0,Z.jsx)(`span`,{className:`sr-only`,children:a})]})},gutterEvents:{onClick:({change:e})=>{if(!y||!e)return;let t=a.get(lv(e));t&&w({filePath:r,changeKey:lv(e),commentKey:lb(r,lv(e)),hunk:t.hunk,change:t.change})}},codeEvents:{onClick:({change:e})=>{if(!y||!e)return;let t=a.get(lv(e));t&&w({filePath:r,changeKey:lv(e),commentKey:lb(r,lv(e)),hunk:t.hunk,change:t.change})}},children:e=>e.map(e=>(0,Z.jsx)(Wv,{hunk:e},`${r}-${e.content}`))});return e===`all`?(0,Z.jsx)(`div`,{"data-index":n?.index,ref:n?fe.measureElement:void 0,children:(0,Z.jsxs)(`section`,{className:K(te===`default`?`rounded-xl border border-border bg-card/70`:`border-t border-border/70 bg-transparent first:border-t-0`),children:[(0,Z.jsxs)(`div`,{className:K(`sticky top-0 z-20 border-b text-xs font-medium text-foreground`,te===`default`?`rounded-t-xl border-border bg-card px-4 py-3`:`border-border/70 bg-background/95 px-3 py-2.5 backdrop-blur-sm`),children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[`oldPath`in t&&typeof t.oldPath==`string`&&P(t.oldPath)===`/dev/null`&&(0,Z.jsx)(U,{variant:`success`,className:`shrink-0`,children:hK(`fileBadge.newFile`)}),(0,Z.jsx)(`span`,{children:r})]}),i&&(0,Z.jsxs)(`div`,{className:`mt-1 flex items-center gap-2 text-xs`,children:[(0,Z.jsxs)(`span`,{className:`font-mono text-emerald-400`,children:[`+`,i.additions]}),(0,Z.jsxs)(`span`,{className:`font-mono text-rose-400`,children:[`-`,i.deletions]})]})]}),(0,Z.jsxs)(`div`,{className:K(`overflow-x-auto`,te===`default`?`p-3`:`px-0 py-3`),children:[l.length>0&&(0,Z.jsx)(`div`,{className:K(`mb-3 space-y-3`,te===`flat`&&`px-3`),children:l.map(e=>(0,Z.jsx)(OK,{finding:e,isSelected:_.includes(e.id),onToggle:()=>{T(e.id)}},e.id))}),h.length>0&&(0,Z.jsx)(`div`,{className:K(`mb-3 space-y-3`,te===`flat`&&`px-3`),children:h.map(e=>(0,Z.jsx)(MK,{comment:e,isSelected:v.includes(e.id),onToggle:()=>{E(e.id)}},e.id))}),C]})]})},`${r}-${t.type??`modify`}`):(0,Z.jsxs)(`div`,{"data-index":n?.index,ref:n?fe.measureElement:void 0,children:[l.length>0&&(0,Z.jsx)(`div`,{className:`mb-3 space-y-3`,children:l.map(e=>(0,Z.jsx)(OK,{finding:e,isSelected:_.includes(e.id),onToggle:()=>{T(e.id)}},e.id))}),h.length>0&&(0,Z.jsx)(`div`,{className:`mb-3 space-y-3`,children:h.map(e=>(0,Z.jsx)(MK,{comment:e,isSelected:v.includes(e.id),onToggle:()=>{E(e.id)}},e.id))}),C]},`${r}-${t.type??`modify`}`)}),_e>0&&(0,Z.jsx)(`div`,{style:{height:_e}})]})]})})]})});LK.displayName=`TicketChangesDiffPanel`;var RK=e=>K(`group`,e?`border-sky-700 bg-card/95 shadow-sm`:`border-border/50 bg-transparent text-muted-foreground hover:border-border/80 hover:bg-accent/60 hover:text-accent-foreground hover:shadow-sm`),zK={modified:`border-amber-500/40 bg-amber-500/10 text-amber-200`,added:`border-emerald-500/40 bg-emerald-500/10 text-emerald-200`,deleted:`border-rose-500/40 bg-rose-500/10 text-rose-200`,renamed:`border-sky-500/40 bg-sky-500/10 text-sky-200`,untracked:`border-violet-500/40 bg-violet-500/10 text-violet-200`,typechanged:`border-slate-500/40 bg-slate-500/10 text-slate-200`},BK={modified:`Modified`,added:`Added`,deleted:`Deleted`,renamed:`Renamed`,untracked:`Untracked`,typechanged:`Type changed`},VK=e=>{let t=e.split(/[\\/]/);return t[t.length-1]||e},HK=({selectionWarning:e,gitError:t,sidebarFiles:n,commentCountByPath:r,commentCountTone:i,isGitStatusLoading:a,selectedPaths:o,selectedDiffPath:s,allFilesSelected:c,diffStats:l,title:u=`Changed files`,allChangesDescription:d=`Review the full workspace diff.`,enableSelection:f=!0,onToggleSelectAll:p,onSelectDiffPath:m,onTogglePath:h})=>{let g=i===`bundle_diff`?`rounded-full border border-violet-400/40 bg-violet-400/12 px-1.5 py-0.5 text-[10px] font-semibold leading-none text-violet-100`:`rounded-full border border-sky-400/40 bg-sky-400/12 px-1.5 py-0.5 text-[10px] font-semibold leading-none text-sky-100`;return(0,Z.jsxs)(`aside`,{className:`flex min-h-0 h-full flex-col between overflow-hidden rounded-2xl border border-border bg-background/40`,children:[(e||t)&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 border-b border-border p-4`,children:[e&&(0,Z.jsx)(`div`,{className:`rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm text-amber-100`,children:e}),t&&(0,Z.jsx)(`div`,{className:`rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm text-amber-100`,children:t})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-sm font-semibold text-foreground`,children:u}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[n.length,` file`,n.length===1?``:`s`,` changed`]})]}),f&&(0,Z.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:p,disabled:n.length===0,children:c?`Unselect all`:`Select all`})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto p-3`,children:[a&&(0,Z.jsx)(`div`,{className:`flex h-full min-h-48 items-center justify-center text-sm text-muted-foreground`,children:`Loading file list...`}),!a&&n.length===0&&(0,Z.jsx)(`div`,{className:`flex h-full min-h-48 items-center justify-center text-sm text-muted-foreground`,children:`No changes to review.`}),!a&&n.length>0&&(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{m(`all`)},className:K(`flex w-full cursor-pointer items-start justify-between gap-3 rounded-xl border px-2.5 py-2 text-left transition-colors`,RK(s===`all`)),children:(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-semibold text-foreground`,children:`All changes`}),l&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3 text-[11px]`,children:[(0,Z.jsxs)(`span`,{className:`text-muted-foreground transition-colors group-hover:text-foreground/70`,children:[l.files_changed,` file`,l.files_changed===1?``:`s`]}),(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-emerald-400`,children:[`+`,l.additions]}),(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-rose-400`,children:[`-`,l.deletions]})]})]}),(0,Z.jsx)(`div`,{className:`mt-1 flex w-full flex-1 text-xs text-muted-foreground transition-colors group-hover:text-foreground/70`,children:d})]})}),n.map(e=>{let t=f&&o.has(e.path),n=s===e.path,i=r.get(e.path)??0;return(0,Z.jsxs)(`div`,{className:K(`relative flex cursor-pointer items-start gap-2.5 rounded-xl border px-2.5 py-2 transition-colors`,RK(n)),children:[(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Open diff for ${e.path}`,onClick:()=>{m(e.path)},className:`absolute inset-0 cursor-pointer rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background`}),f&&(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":e.path,checked:t,onChange:()=>{h(e.path)},className:`relative z-10 mt-0.5 h-4 w-4 rounded border-border bg-background text-primary`}),(0,Z.jsxs)(`div`,{className:`relative z-10 min-w-0 flex-1 cursor-pointer text-left pointer-events-none`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex flex-1 items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 truncate font-mono text-xs text-foreground`,children:VK(e.path)}),i>0&&(0,Z.jsx)(`span`,{"aria-label":`${i} comment${i===1?``:`s`} in ${e.path}`,className:g,children:i})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3 text-[11px]`,children:[(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-emerald-400`,children:[`+`,e.additions]}),(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-rose-400`,children:[`-`,e.deletions]})]})]}),(0,Z.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap items-center gap-1.5 text-[11px]`,children:[e.status&&(0,Z.jsx)(U,{variant:`outline`,className:zK[e.status],children:BK[e.status]}),e.staged&&(0,Z.jsx)(U,{variant:`outline`,children:`Staged`}),e.unstaged&&(0,Z.jsx)(U,{variant:`outline`,children:`Unstaged`}),e.conflicted&&(0,Z.jsx)(U,{variant:`destructive`,children:`Conflicted`}),e.originalPath&&(0,Z.jsx)(`span`,{className:`break-all font-mono text-[11px] text-muted-foreground transition-colors group-hover:text-foreground/70`,children:e.status===`renamed`?`from ${e.originalPath}`:e.originalPath})]})]})]},`${e.path}:${e.originalPath??``}`)})]})]})]})},UK=[`[--diff-background-color:transparent]`,`[--diff-text-color:rgb(226_232_240)]`,`[--diff-selection-background-color:rgba(148,163,184,0.2)]`,`[--diff-gutter-insert-background-color:rgba(34,197,94,0.16)]`,`[--diff-gutter-delete-background-color:rgba(244,63,94,0.16)]`,`[--diff-gutter-selected-background-color:rgba(148,163,184,0.12)]`,`[--diff-code-insert-background-color:rgba(34,197,94,0.08)]`,`[--diff-code-delete-background-color:rgba(244,63,94,0.08)]`,`[--diff-code-insert-edit-background-color:rgba(34,197,94,0.22)]`,`[--diff-code-delete-edit-background-color:rgba(244,63,94,0.22)]`,`[--diff-code-selected-background-color:rgba(148,163,184,0.12)]`,`[--diff-font-family:var(--font-mono)]`,`[&_.diff]:w-full`,`[&_.diff]:border-collapse`,`[&_.diff]:font-mono`,`[&_.diff-code]:whitespace-pre-wrap`,`[&_.diff-code]:break-words`,`[&_.diff-gutter]:select-none`].join(` `),WK=25e4,GK=2e3,KK=new Map,qK=e=>e?e.split(`
|
|
147
|
-
`).length:0,JK=e=>{let t=e.diff??``;return t?t.length<=WK&&qK(t)<=GK:!0},YK=({scope:e,projectId:t,ticketId:n,projectTargetBundleId:r=null})=>e===`project_root`?t?`project_root:${t}:${r??`repo_root`}`:null:n?`ticket:${t??`none`}:${n}`:null,XK=e=>e?KK.get(e)??null:null,ZK=({cacheKey:e,diffResponse:t,gitStatus:n})=>{let r=n.workspace_signature?.trim();if(!(!e||!r)){if(!JK(t)){KK.delete(e);return}KK.set(e,{diffResponse:t,gitStatus:n,workspaceSignature:r})}},QK=e=>{e&&KK.delete(e)},$K={css:`css`,html:`markup`,htm:`markup`,js:`javascript`,jsx:`jsx`,json:`json`,md:`markdown`,markdown:`markdown`,sh:`bash`,ts:`typescript`,tsx:`tsx`,yaml:`yaml`,yml:`yaml`},eq=e=>{if(!e)return null;let t=e.split(` -> `),n=t[t.length-1]??e,r=n.split(`/`),i=r[r.length-1]??n,a=``;if(i.includes(`.`)){let e=i.split(`.`);a=e[e.length-1]?.toLowerCase()??``}return $K[a]??null},tq=new Set,nq=e=>{e&&tq.forEach(t=>t(e))},rq=e=>(tq.add(e),()=>{tq.delete(e)}),iq=300,aq=(e,t={})=>{let n=t.dedupeMs??iq,r=0,i=()=>{if(document.visibilityState!==`visible`)return;let t=Date.now();t-r<n||(r=t,e())};return window.addEventListener(`focus`,i),document.addEventListener(`visibilitychange`,i),()=>{window.removeEventListener(`focus`,i),document.removeEventListener(`visibilitychange`,i)}},oq=i(((e,t)=>{t.exports=r;var n=Object.prototype.hasOwnProperty;function r(){for(var e={},t=0;t<arguments.length;t++){var r=arguments[t];for(var i in r)n.call(r,i)&&(e[i]=r[i])}return e}})),sq=i(((e,t)=>{t.exports=r;var n=r.prototype;n.space=null,n.normal={},n.property={};function r(e,t,n){this.property=e,this.normal=t,n&&(this.space=n)}})),cq=i(((e,t)=>{var n=oq(),r=sq();t.exports=i;function i(e){for(var t=e.length,i=[],a=[],o=-1,s,c;++o<t;)s=e[o],i.push(s.property),a.push(s.normal),c=s.space;return new r(n.apply(null,i),n.apply(null,a),c)}})),lq=i(((e,t)=>{t.exports=n;function n(e){return e.toLowerCase()}})),uq=i(((e,t)=>{t.exports=r;var n=r.prototype;n.space=null,n.attribute=null,n.property=null,n.boolean=!1,n.booleanish=!1,n.overloadedBoolean=!1,n.number=!1,n.commaSeparated=!1,n.spaceSeparated=!1,n.commaOrSpaceSeparated=!1,n.mustUseProperty=!1,n.defined=!1;function r(e,t){this.property=e,this.attribute=t}})),dq=i((e=>{var t=0;e.boolean=n(),e.booleanish=n(),e.overloadedBoolean=n(),e.number=n(),e.spaceSeparated=n(),e.commaSeparated=n(),e.commaOrSpaceSeparated=n();function n(){return 2**++t}})),fq=i(((e,t)=>{var n=uq(),r=dq();t.exports=o,o.prototype=new n,o.prototype.defined=!0;var i=[`boolean`,`booleanish`,`overloadedBoolean`,`number`,`commaSeparated`,`spaceSeparated`,`commaOrSpaceSeparated`],a=i.length;function o(e,t,o,c){var l=-1,u;for(s(this,`space`,c),n.call(this,e,t);++l<a;)u=i[l],s(this,u,(o&r[u])===r[u])}function s(e,t,n){n&&(e[t]=n)}})),pq=i(((e,t)=>{var n=lq(),r=sq(),i=fq();t.exports=a;function a(e){var t=e.space,a=e.mustUseProperty||[],o=e.attributes||{},s=e.properties,c=e.transform,l={},u={},d,f;for(d in s)f=new i(d,c(o,d),s[d],t),a.indexOf(d)!==-1&&(f.mustUseProperty=!0),l[d]=f,u[n(d)]=d,u[n(f.attribute)]=d;return new r(l,u,t)}})),mq=i(((e,t)=>{t.exports=pq()({space:`xlink`,transform:n,properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null}});function n(e,t){return`xlink:`+t.slice(5).toLowerCase()}})),hq=i(((e,t)=>{t.exports=pq()({space:`xml`,transform:n,properties:{xmlLang:null,xmlBase:null,xmlSpace:null}});function n(e,t){return`xml:`+t.slice(3).toLowerCase()}})),gq=i(((e,t)=>{t.exports=n;function n(e,t){return t in e?e[t]:t}})),_q=i(((e,t)=>{var n=gq();t.exports=r;function r(e,t){return n(e,t.toLowerCase())}})),vq=i(((e,t)=>{t.exports=pq()({space:`xmlns`,attributes:{xmlnsxlink:`xmlns:xlink`},transform:_q(),properties:{xmlns:null,xmlnsXLink:null}})})),yq=i(((e,t)=>{var n=dq(),r=pq(),i=n.booleanish,a=n.number,o=n.spaceSeparated;t.exports=r({transform:s,properties:{ariaActiveDescendant:null,ariaAtomic:i,ariaAutoComplete:null,ariaBusy:i,ariaChecked:i,ariaColCount:a,ariaColIndex:a,ariaColSpan:a,ariaControls:o,ariaCurrent:null,ariaDescribedBy:o,ariaDetails:null,ariaDisabled:i,ariaDropEffect:o,ariaErrorMessage:null,ariaExpanded:i,ariaFlowTo:o,ariaGrabbed:i,ariaHasPopup:null,ariaHidden:i,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:o,ariaLevel:a,ariaLive:null,ariaModal:i,ariaMultiLine:i,ariaMultiSelectable:i,ariaOrientation:null,ariaOwns:o,ariaPlaceholder:null,ariaPosInSet:a,ariaPressed:i,ariaReadOnly:i,ariaRelevant:null,ariaRequired:i,ariaRoleDescription:o,ariaRowCount:a,ariaRowIndex:a,ariaRowSpan:a,ariaSelected:i,ariaSetSize:a,ariaSort:null,ariaValueMax:a,ariaValueMin:a,ariaValueNow:a,ariaValueText:null,role:null}});function s(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}})),bq=i(((e,t)=>{var n=dq(),r=pq(),i=_q(),a=n.boolean,o=n.overloadedBoolean,s=n.booleanish,c=n.number,l=n.spaceSeparated,u=n.commaSeparated;t.exports=r({space:`html`,attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},transform:i,mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:u,acceptCharset:l,accessKey:l,action:null,allow:null,allowFullScreen:a,allowPaymentRequest:a,allowUserMedia:a,alt:null,as:null,async:a,autoCapitalize:null,autoComplete:l,autoFocus:a,autoPlay:a,capture:a,charSet:null,checked:a,cite:null,className:l,cols:c,colSpan:null,content:null,contentEditable:s,controls:a,controlsList:l,coords:c|u,crossOrigin:null,data:null,dateTime:null,decoding:null,default:a,defer:a,dir:null,dirName:null,disabled:a,download:o,draggable:s,encType:null,enterKeyHint:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:a,formTarget:null,headers:l,height:c,hidden:a,high:c,href:null,hrefLang:null,htmlFor:l,httpEquiv:l,id:null,imageSizes:null,imageSrcSet:u,inputMode:null,integrity:null,is:null,isMap:a,itemId:null,itemProp:l,itemRef:l,itemScope:a,itemType:l,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:a,low:c,manifest:null,max:null,maxLength:c,media:null,method:null,min:null,minLength:c,multiple:a,muted:a,name:null,nonce:null,noModule:a,noValidate:a,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforePrint:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextMenu:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:a,optimum:c,pattern:null,ping:l,placeholder:null,playsInline:a,poster:null,preload:null,readOnly:a,referrerPolicy:null,rel:l,required:a,reversed:a,rows:c,rowSpan:c,sandbox:l,scope:null,scoped:a,seamless:a,selected:a,shape:null,size:c,sizes:null,slot:null,span:c,spellCheck:s,src:null,srcDoc:null,srcLang:null,srcSet:u,start:c,step:null,style:null,tabIndex:c,target:null,title:null,translate:null,type:null,typeMustMatch:a,useMap:null,value:s,width:c,wrap:null,align:null,aLink:null,archive:l,axis:null,background:null,bgColor:null,border:c,borderColor:null,bottomMargin:c,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:a,declare:a,event:null,face:null,frame:null,frameBorder:null,hSpace:c,leftMargin:c,link:null,longDesc:null,lowSrc:null,marginHeight:c,marginWidth:c,noResize:a,noHref:a,noShade:a,noWrap:a,object:null,profile:null,prompt:null,rev:null,rightMargin:c,rules:null,scheme:null,scrolling:s,standby:null,summary:null,text:null,topMargin:c,valueType:null,version:null,vAlign:null,vLink:null,vSpace:c,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:a,disableRemotePlayback:a,prefix:null,property:null,results:c,security:null,unselectable:null}})})),xq=i(((e,t)=>{var n=cq(),r=mq();t.exports=n([hq(),r,vq(),yq(),bq()])})),Sq=i(((e,t)=>{var n=lq(),r=fq(),i=uq(),a=`data`;t.exports=l;var o=/^data[-\w.:]+$/i,s=/-[a-z]/g,c=/[A-Z]/g;function l(e,t){var s=n(t),c=t,l=i;return s in e.normal?e.property[e.normal[s]]:(s.length>4&&s.slice(0,4)===a&&o.test(t)&&(t.charAt(4)===`-`?c=u(t):t=d(t),l=r),new l(c,t))}function u(e){var t=e.slice(5).replace(s,p);return a+t.charAt(0).toUpperCase()+t.slice(1)}function d(e){var t=e.slice(4);return s.test(t)?e:(t=t.replace(c,f),t.charAt(0)!==`-`&&(t=`-`+t),a+t)}function f(e){return`-`+e.toLowerCase()}function p(e){return e.charAt(1).toUpperCase()}})),Cq=i(((e,t)=>{t.exports=r;var n=/[#.]/g;function r(e,t){for(var r=e||``,i=t||`div`,a={},o=0,s,c,l;o<r.length;)n.lastIndex=o,l=n.exec(r),s=r.slice(o,l?l.index:r.length),s&&(c?c===`#`?a.id=s:a.className?a.className.push(s):a.className=[s]:i=s,o+=s.length),l&&(c=l[0],o++);return{type:`element`,tagName:i,properties:a,children:[]}}})),wq=i((e=>{e.parse=i,e.stringify=a;var t=``,n=` `,r=/[ \t\n\r\f]+/g;function i(e){var n=String(e||t).trim();return n===t?[]:n.split(r)}function a(e){return e.join(n).trim()}})),Tq=i((e=>{e.parse=i,e.stringify=a;var t=`,`,n=` `,r=``;function i(e){for(var n=[],i=String(e||r),a=i.indexOf(t),o=0,s=!1,c;!s;)a===-1&&(a=i.length,s=!0),c=i.slice(o,a).trim(),(c||!s)&&n.push(c),o=a+1,a=i.indexOf(t,o);return n}function a(e,i){var a=i||{},o=a.padLeft===!1?r:n,s=a.padRight?n:r;return e[e.length-1]===r&&(e=e.concat(r)),e.join(s+t+o).trim()}})),Eq=i(((e,t)=>{var n=Sq(),r=lq(),i=Cq(),a=wq().parse,o=Tq().parse;t.exports=c;var s={}.hasOwnProperty;function c(e,t,r){var c=r?h(r):null;return u;function u(e,n){var r=i(e,t),a=Array.prototype.slice.call(arguments,2),o=r.tagName.toLowerCase(),u;if(r.tagName=c&&s.call(c,o)?c[o]:o,n&&l(n,r)&&(a.unshift(n),n=null),n)for(u in n)p(r.properties,u,n[u]);return d(r.children,a),r.tagName===`template`&&(r.content={type:`root`,children:r.children},r.children=[]),r}function p(t,r,i){var s,c,l;i==null||i!==i||(s=n(e,r),c=s.property,l=i,typeof l==`string`&&(s.spaceSeparated?l=a(l):s.commaSeparated?l=o(l):s.commaOrSpaceSeparated&&(l=a(o(l).join(` `)))),c===`style`&&typeof i!=`string`&&(l=m(l)),c===`className`&&t.className&&(l=t.className.concat(l)),t[c]=f(s,c,l))}}function l(e,t){return typeof e==`string`||`length`in e||u(t.tagName,e)}function u(e,t){var n=t.type;return e===`input`||!n||typeof n!=`string`?!1:typeof t.children==`object`&&`length`in t.children?!0:(n=n.toLowerCase(),e===`button`?n!==`menu`&&n!==`submit`&&n!==`reset`&&n!==`button`:`value`in t)}function d(e,t){var n,r;if(typeof t==`string`||typeof t==`number`){e.push({type:`text`,value:String(t)});return}if(typeof t==`object`&&`length`in t){for(n=-1,r=t.length;++n<r;)d(e,t[n]);return}if(typeof t!=`object`||!(`type`in t))throw Error("Expected node, nodes, or string, got `"+t+"`");e.push(t)}function f(e,t,n){var r,i,a;if(typeof n!=`object`||!(`length`in n))return p(e,t,n);for(i=n.length,r=-1,a=[];++r<i;)a[r]=p(e,t,n[r]);return a}function p(e,t,n){var i=n;return e.number||e.positiveNumber?!isNaN(i)&&i!==``&&(i=Number(i)):(e.boolean||e.overloadedBoolean)&&typeof i==`string`&&(i===``||r(n)===r(t))&&(i=!0),i}function m(e){var t=[],n;for(n in e)t.push([n,e[n]].join(`: `));return t.join(`; `)}function h(e){for(var t=e.length,n=-1,r={},i;++n<t;)i=e[n],r[i.toLowerCase()]=i;return r}})),Dq=i(((e,t)=>{var n=xq(),r=Eq()(n,`div`);r.displayName=`html`,t.exports=r})),Oq=i(((e,t)=>{t.exports=Dq()})),kq=r({AElig:()=>`Æ`,AMP:()=>`&`,Aacute:()=>`Á`,Acirc:()=>`Â`,Agrave:()=>`À`,Aring:()=>`Å`,Atilde:()=>`Ã`,Auml:()=>`Ä`,COPY:()=>`©`,Ccedil:()=>`Ç`,ETH:()=>`Ð`,Eacute:()=>`É`,Ecirc:()=>`Ê`,Egrave:()=>`È`,Euml:()=>`Ë`,GT:()=>`>`,Iacute:()=>`Í`,Icirc:()=>`Î`,Igrave:()=>`Ì`,Iuml:()=>`Ï`,LT:()=>`<`,Ntilde:()=>`Ñ`,Oacute:()=>`Ó`,Ocirc:()=>`Ô`,Ograve:()=>`Ò`,Oslash:()=>`Ø`,Otilde:()=>`Õ`,Ouml:()=>`Ö`,QUOT:()=>`"`,REG:()=>`®`,THORN:()=>`Þ`,Uacute:()=>`Ú`,Ucirc:()=>`Û`,Ugrave:()=>`Ù`,Uuml:()=>`Ü`,Yacute:()=>`Ý`,aacute:()=>`á`,acirc:()=>`â`,acute:()=>`´`,aelig:()=>`æ`,agrave:()=>`à`,amp:()=>`&`,aring:()=>`å`,atilde:()=>`ã`,auml:()=>`ä`,brvbar:()=>`¦`,ccedil:()=>`ç`,cedil:()=>`¸`,cent:()=>`¢`,copy:()=>`©`,curren:()=>`¤`,default:()=>Aq,deg:()=>`°`,divide:()=>`÷`,eacute:()=>`é`,ecirc:()=>`ê`,egrave:()=>`è`,eth:()=>`ð`,euml:()=>`ë`,frac12:()=>`½`,frac14:()=>`¼`,frac34:()=>`¾`,gt:()=>`>`,iacute:()=>`í`,icirc:()=>`î`,iexcl:()=>`¡`,igrave:()=>`ì`,iquest:()=>`¿`,iuml:()=>`ï`,laquo:()=>`«`,lt:()=>`<`,macr:()=>`¯`,micro:()=>`µ`,middot:()=>`·`,nbsp:()=>`\xA0`,not:()=>`¬`,ntilde:()=>`ñ`,oacute:()=>`ó`,ocirc:()=>`ô`,ograve:()=>`ò`,ordf:()=>`ª`,ordm:()=>`º`,oslash:()=>`ø`,otilde:()=>`õ`,ouml:()=>`ö`,para:()=>`¶`,plusmn:()=>`±`,pound:()=>`£`,quot:()=>`"`,raquo:()=>`»`,reg:()=>`®`,sect:()=>`§`,shy:()=>``,sup1:()=>`¹`,sup2:()=>`²`,sup3:()=>`³`,szlig:()=>`ß`,thorn:()=>`þ`,times:()=>`×`,uacute:()=>`ú`,ucirc:()=>`û`,ugrave:()=>`ù`,uml:()=>`¨`,uuml:()=>`ü`,yacute:()=>`ý`,yen:()=>`¥`,yuml:()=>`ÿ`}),Aq,jq=n((()=>{Aq={AElig:`Æ`,AMP:`&`,Aacute:`Á`,Acirc:`Â`,Agrave:`À`,Aring:`Å`,Atilde:`Ã`,Auml:`Ä`,COPY:`©`,Ccedil:`Ç`,ETH:`Ð`,Eacute:`É`,Ecirc:`Ê`,Egrave:`È`,Euml:`Ë`,GT:`>`,Iacute:`Í`,Icirc:`Î`,Igrave:`Ì`,Iuml:`Ï`,LT:`<`,Ntilde:`Ñ`,Oacute:`Ó`,Ocirc:`Ô`,Ograve:`Ò`,Oslash:`Ø`,Otilde:`Õ`,Ouml:`Ö`,QUOT:`"`,REG:`®`,THORN:`Þ`,Uacute:`Ú`,Ucirc:`Û`,Ugrave:`Ù`,Uuml:`Ü`,Yacute:`Ý`,aacute:`á`,acirc:`â`,acute:`´`,aelig:`æ`,agrave:`à`,amp:`&`,aring:`å`,atilde:`ã`,auml:`ä`,brvbar:`¦`,ccedil:`ç`,cedil:`¸`,cent:`¢`,copy:`©`,curren:`¤`,deg:`°`,divide:`÷`,eacute:`é`,ecirc:`ê`,egrave:`è`,eth:`ð`,euml:`ë`,frac12:`½`,frac14:`¼`,frac34:`¾`,gt:`>`,iacute:`í`,icirc:`î`,iexcl:`¡`,igrave:`ì`,iquest:`¿`,iuml:`ï`,laquo:`«`,lt:`<`,macr:`¯`,micro:`µ`,middot:`·`,nbsp:`\xA0`,not:`¬`,ntilde:`ñ`,oacute:`ó`,ocirc:`ô`,ograve:`ò`,ordf:`ª`,ordm:`º`,oslash:`ø`,otilde:`õ`,ouml:`ö`,para:`¶`,plusmn:`±`,pound:`£`,quot:`"`,raquo:`»`,reg:`®`,sect:`§`,shy:``,sup1:`¹`,sup2:`²`,sup3:`³`,szlig:`ß`,thorn:`þ`,times:`×`,uacute:`ú`,ucirc:`û`,ugrave:`ù`,uml:`¨`,uuml:`ü`,yacute:`ý`,yen:`¥`,yuml:`ÿ`}})),Mq=r({default:()=>Nq}),Nq,Pq=n((()=>{Nq={0:`�`,128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`}})),Fq=i(((e,t)=>{t.exports=n;function n(e){var t=typeof e==`string`?e.charCodeAt(0):e;return t>=48&&t<=57}})),Iq=i(((e,t)=>{t.exports=n;function n(e){var t=typeof e==`string`?e.charCodeAt(0):e;return t>=97&&t<=102||t>=65&&t<=70||t>=48&&t<=57}})),Lq=i(((e,t)=>{t.exports=n;function n(e){var t=typeof e==`string`?e.charCodeAt(0):e;return t>=97&&t<=122||t>=65&&t<=90}})),Rq=i(((e,t)=>{var n=Lq(),r=Fq();t.exports=i;function i(e){return n(e)||r(e)}})),zq=i(((e,t)=>{var n,r=59;t.exports=i;function i(e){var t=`&`+e+`;`,i;return n||=document.createElement(`i`),n.innerHTML=t,i=n.textContent,i.charCodeAt(i.length-1)===r&&e!==`semi`||i===t?!1:i}})),Bq=i(((e,n)=>{var r=(jq(),t(kq).default),i=(Pq(),t(Mq).default),a=Fq(),o=Iq(),s=Rq(),c=zq();n.exports=R;var l={}.hasOwnProperty,u=String.fromCharCode,d=Function.prototype,f={warning:null,reference:null,text:null,warningContext:null,referenceContext:null,textContext:null,position:{},additional:null,attribute:!1,nonTerminated:!0},p=9,m=10,h=12,g=32,_=38,v=59,y=60,b=61,x=35,S=88,C=120,w=65533,T=`named`,E=`hexadecimal`,D=`decimal`,O={};O[E]=16,O[D]=10;var k={};k[T]=s,k[D]=a,k[E]=o;var A=1,j=2,M=3,N=4,P=5,F=6,I=7,L={};L[A]=`Named character references must be terminated by a semicolon`,L[j]=`Numeric character references must be terminated by a semicolon`,L[M]=`Named character references cannot be empty`,L[N]=`Numeric character references cannot be empty`,L[P]=`Named character references must be known`,L[F]=`Numeric character references cannot be disallowed`,L[I]=`Numeric character references cannot be outside the permissible Unicode range`;function R(e,t){var n={},r,i;for(i in t||={},f)r=t[i],n[i]=r??f[i];return(n.position.indent||n.position.start)&&(n.indent=n.position.indent||[],n.position=n.position.start),z(e,n)}function z(e,t){var n=t.additional,a=t.nonTerminated,o=t.text,f=t.reference,R=t.warning,z=t.textContext,ne=t.referenceContext,re=t.warningContext,B=t.position,ie=t.indent||[],V=e.length,H=0,ae=-1,oe=B.column||1,se=B.line||1,ce=``,le=[],ue,de,U,fe,pe,me,W,he,G,ge,_e,ve,ye,be,xe,K,Se,Ce,we;for(typeof n==`string`&&(n=n.charCodeAt(0)),K=Te(),he=R?Ee:d,H--,V++;++H<V;)if(pe===m&&(oe=ie[ae]||1),pe=e.charCodeAt(H),pe===_){if(W=e.charCodeAt(H+1),W===p||W===m||W===h||W===g||W===_||W===y||W!==W||n&&W===n){ce+=u(pe),oe++;continue}for(ye=H+1,ve=ye,we=ye,W===x?(we=++ve,W=e.charCodeAt(we),W===S||W===C?(be=E,we=++ve):be=D):be=T,ue=``,_e=``,fe=``,xe=k[be],we--;++we<V&&(W=e.charCodeAt(we),xe(W));)fe+=u(W),be===T&&l.call(r,fe)&&(ue=fe,_e=r[fe]);U=e.charCodeAt(we)===v,U&&(we++,de=be===T?c(fe):!1,de&&(ue=fe,_e=de)),Ce=1+we-ye,!U&&!a||(fe?be===T?(U&&!_e?he(P,1):(ue!==fe&&(we=ve+ue.length,Ce=1+we-ve,U=!1),U||(G=ue?A:M,t.attribute?(W=e.charCodeAt(we),W===b?(he(G,Ce),_e=null):s(W)?_e=null:he(G,Ce)):he(G,Ce))),me=_e):(U||he(j,Ce),me=parseInt(fe,O[be]),ee(me)?(he(I,Ce),me=u(w)):me in i?(he(F,Ce),me=i[me]):(ge=``,te(me)&&he(F,Ce),me>65535&&(me-=65536,ge+=u(me>>>10|55296),me=56320|me&1023),me=ge+u(me))):be!==T&&he(N,Ce)),me?(De(),K=Te(),H=we-1,oe+=we-ye+1,le.push(me),Se=Te(),Se.offset++,f&&f.call(ne,me,{start:K,end:Se},e.slice(ye-1,we)),K=Se):(fe=e.slice(ye-1,we),ce+=fe,oe+=fe.length,H=we-1)}else pe===10&&(se++,ae++,oe=0),pe===pe?(ce+=u(pe),oe++):De();return le.join(``);function Te(){return{line:se,column:oe,offset:H+(B.offset||0)}}function Ee(e,t){var n=Te();n.column+=t,n.offset+=t,R.call(re,L[e],n,e)}function De(){ce&&=(le.push(ce),o&&o.call(z,ce,{start:K,end:Te()}),``)}}function ee(e){return e>=55296&&e<=57343||e>1114111}function te(e){return e>=1&&e<=8||e===11||e>=13&&e<=31||e>=127&&e<=159||e>=64976&&e<=65007||(e&65535)==65535||(e&65535)==65534}})),Vq=i(((e,t)=>{var n=function(e){var t=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,n=0,r={},i={manual:e.Prism&&e.Prism.manual,disableWorkerMessageHandler:e.Prism&&e.Prism.disableWorkerMessageHandler,util:{encode:function e(t){return t instanceof a?new a(t.type,e(t.content),t.alias):Array.isArray(t)?t.map(e):t.replace(/&/g,`&`).replace(/</g,`<`).replace(/\u00a0/g,` `)},type:function(e){return Object.prototype.toString.call(e).slice(8,-1)},objId:function(e){return e.__id||Object.defineProperty(e,`__id`,{value:++n}),e.__id},clone:function e(t,n){n||={};var r,a;switch(i.util.type(t)){case`Object`:if(a=i.util.objId(t),n[a])return n[a];for(var o in r={},n[a]=r,t)t.hasOwnProperty(o)&&(r[o]=e(t[o],n));return r;case`Array`:return a=i.util.objId(t),n[a]?n[a]:(r=[],n[a]=r,t.forEach(function(t,i){r[i]=e(t,n)}),r);default:return t}},getLanguage:function(e){for(;e;){var n=t.exec(e.className);if(n)return n[1].toLowerCase();e=e.parentElement}return`none`},setLanguage:function(e,n){e.className=e.className.replace(RegExp(t,`gi`),``),e.classList.add(`language-`+n)},currentScript:function(){if(typeof document>`u`)return null;if(`currentScript`in document)return document.currentScript;try{throw Error()}catch(r){var e=(/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(r.stack)||[])[1];if(e){var t=document.getElementsByTagName(`script`);for(var n in t)if(t[n].src==e)return t[n]}return null}},isActive:function(e,t,n){for(var r=`no-`+t;e;){var i=e.classList;if(i.contains(t))return!0;if(i.contains(r))return!1;e=e.parentElement}return!!n}},languages:{plain:r,plaintext:r,text:r,txt:r,extend:function(e,t){var n=i.util.clone(i.languages[e]);for(var r in t)n[r]=t[r];return n},insertBefore:function(e,t,n,r){r||=i.languages;var a=r[e],o={};for(var s in a)if(a.hasOwnProperty(s)){if(s==t)for(var c in n)n.hasOwnProperty(c)&&(o[c]=n[c]);n.hasOwnProperty(s)||(o[s]=a[s])}var l=r[e];return r[e]=o,i.languages.DFS(i.languages,function(t,n){n===l&&t!=e&&(this[t]=o)}),o},DFS:function e(t,n,r,a){a||={};var o=i.util.objId;for(var s in t)if(t.hasOwnProperty(s)){n.call(t,s,t[s],r||s);var c=t[s],l=i.util.type(c);l===`Object`&&!a[o(c)]?(a[o(c)]=!0,e(c,n,null,a)):l===`Array`&&!a[o(c)]&&(a[o(c)]=!0,e(c,n,s,a))}}},plugins:{},highlightAll:function(e,t){i.highlightAllUnder(document,e,t)},highlightAllUnder:function(e,t,n){var r={callback:n,container:e,selector:`code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code`};i.hooks.run(`before-highlightall`,r),r.elements=Array.prototype.slice.apply(r.container.querySelectorAll(r.selector)),i.hooks.run(`before-all-elements-highlight`,r);for(var a=0,o;o=r.elements[a++];)i.highlightElement(o,t===!0,r.callback)},highlightElement:function(t,n,r){var a=i.util.getLanguage(t),o=i.languages[a];i.util.setLanguage(t,a);var s=t.parentElement;s&&s.nodeName.toLowerCase()===`pre`&&i.util.setLanguage(s,a);var c={element:t,language:a,grammar:o,code:t.textContent};function l(e){c.highlightedCode=e,i.hooks.run(`before-insert`,c),c.element.innerHTML=c.highlightedCode,i.hooks.run(`after-highlight`,c),i.hooks.run(`complete`,c),r&&r.call(c.element)}if(i.hooks.run(`before-sanity-check`,c),s=c.element.parentElement,s&&s.nodeName.toLowerCase()===`pre`&&!s.hasAttribute(`tabindex`)&&s.setAttribute(`tabindex`,`0`),!c.code){i.hooks.run(`complete`,c),r&&r.call(c.element);return}if(i.hooks.run(`before-highlight`,c),!c.grammar){l(i.util.encode(c.code));return}if(n&&e.Worker){var u=new Worker(i.filename);u.onmessage=function(e){l(e.data)},u.postMessage(JSON.stringify({language:c.language,code:c.code,immediateClose:!0}))}else l(i.highlight(c.code,c.grammar,c.language))},highlight:function(e,t,n){var r={code:e,grammar:t,language:n};if(i.hooks.run(`before-tokenize`,r),!r.grammar)throw Error(`The language "`+r.language+`" has no grammar.`);return r.tokens=i.tokenize(r.code,r.grammar),i.hooks.run(`after-tokenize`,r),a.stringify(i.util.encode(r.tokens),r.language)},tokenize:function(e,t){var n=t.rest;if(n){for(var r in n)t[r]=n[r];delete t.rest}var i=new c;return l(i,i.head,e),s(e,i,t,i.head,0),d(i)},hooks:{all:{},add:function(e,t){var n=i.hooks.all;n[e]=n[e]||[],n[e].push(t)},run:function(e,t){var n=i.hooks.all[e];if(!(!n||!n.length))for(var r=0,a;a=n[r++];)a(t)}},Token:a};e.Prism=i;function a(e,t,n,r){this.type=e,this.content=t,this.alias=n,this.length=(r||``).length|0}a.stringify=function e(t,n){if(typeof t==`string`)return t;if(Array.isArray(t)){var r=``;return t.forEach(function(t){r+=e(t,n)}),r}var a={type:t.type,content:e(t.content,n),tag:`span`,classes:[`token`,t.type],attributes:{},language:n},o=t.alias;o&&(Array.isArray(o)?Array.prototype.push.apply(a.classes,o):a.classes.push(o)),i.hooks.run(`wrap`,a);var s=``;for(var c in a.attributes)s+=` `+c+`="`+(a.attributes[c]||``).replace(/"/g,`"`)+`"`;return`<`+a.tag+` class="`+a.classes.join(` `)+`"`+s+`>`+a.content+`</`+a.tag+`>`};function o(e,t,n,r){e.lastIndex=t;var i=e.exec(n);if(i&&r&&i[1]){var a=i[1].length;i.index+=a,i[0]=i[0].slice(a)}return i}function s(e,t,n,r,c,d){for(var f in n)if(!(!n.hasOwnProperty(f)||!n[f])){var p=n[f];p=Array.isArray(p)?p:[p];for(var m=0;m<p.length;++m){if(d&&d.cause==f+`,`+m)return;var h=p[m],g=h.inside,_=!!h.lookbehind,v=!!h.greedy,y=h.alias;if(v&&!h.pattern.global){var b=h.pattern.toString().match(/[imsuy]*$/)[0];h.pattern=RegExp(h.pattern.source,b+`g`)}for(var x=h.pattern||h,S=r.next,C=c;S!==t.tail&&!(d&&C>=d.reach);C+=S.value.length,S=S.next){var w=S.value;if(t.length>e.length)return;if(!(w instanceof a)){var T=1,E;if(v){if(E=o(x,C,e,_),!E||E.index>=e.length)break;var D=E.index,O=E.index+E[0].length,k=C;for(k+=S.value.length;D>=k;)S=S.next,k+=S.value.length;if(k-=S.value.length,C=k,S.value instanceof a)continue;for(var A=S;A!==t.tail&&(k<O||typeof A.value==`string`);A=A.next)T++,k+=A.value.length;T--,w=e.slice(C,k),E.index-=C}else if(E=o(x,0,w,_),!E)continue;var D=E.index,j=E[0],M=w.slice(0,D),N=w.slice(D+j.length),P=C+w.length;d&&P>d.reach&&(d.reach=P);var F=S.prev;M&&(F=l(t,F,M),C+=M.length),u(t,F,T);var I=new a(f,g?i.tokenize(j,g):j,y,j);if(S=l(t,F,I),N&&l(t,S,N),T>1){var L={cause:f+`,`+m,reach:P};s(e,t,n,S.prev,C,L),d&&L.reach>d.reach&&(d.reach=L.reach)}}}}}}function c(){var e={value:null,prev:null,next:null},t={value:null,prev:e,next:null};e.next=t,this.head=e,this.tail=t,this.length=0}function l(e,t,n){var r=t.next,i={value:n,prev:t,next:r};return t.next=i,r.prev=i,e.length++,i}function u(e,t,n){for(var r=t.next,i=0;i<n&&r!==e.tail;i++)r=r.next;t.next=r,r.prev=t,e.length-=i}function d(e){for(var t=[],n=e.head.next;n!==e.tail;)t.push(n.value),n=n.next;return t}if(!e.document)return e.addEventListener&&(i.disableWorkerMessageHandler||e.addEventListener(`message`,function(t){var n=JSON.parse(t.data),r=n.language,a=n.code,o=n.immediateClose;e.postMessage(i.highlight(a,i.languages[r],r)),o&&e.close()},!1)),i;var f=i.util.currentScript();f&&(i.filename=f.src,f.hasAttribute(`data-manual`)&&(i.manual=!0));function p(){i.manual||i.highlightAll()}if(!i.manual){var m=document.readyState;m===`loading`||m===`interactive`&&f&&f.defer?document.addEventListener(`DOMContentLoaded`,p):window.requestAnimationFrame?window.requestAnimationFrame(p):window.setTimeout(p,16)}return i}(typeof window<`u`?window:typeof WorkerGlobalScope<`u`&&self instanceof WorkerGlobalScope?self:{});t!==void 0&&t.exports&&(t.exports=n),typeof global<`u`&&(global.Prism=n)})),Hq=i(((e,t)=>{t.exports=n,n.displayName=`markup`,n.aliases=[`html`,`mathml`,`svg`,`xml`,`ssml`,`atom`,`rss`];function n(e){e.languages.markup={comment:{pattern:/<!--(?:(?!<!--)[\s\S])*?-->/,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^<!|>$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:`attr-equals`},/"|'/]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:`named-entity`},/&#x?[\da-f]{1,8};/i]},e.languages.markup.tag.inside[`attr-value`].inside.entity=e.languages.markup.entity,e.languages.markup.doctype.inside[`internal-subset`].inside=e.languages.markup,e.hooks.add(`wrap`,function(e){e.type===`entity`&&(e.attributes.title=e.content.value.replace(/&/,`&`))}),Object.defineProperty(e.languages.markup.tag,`addInlined`,{value:function(t,n){var r={};r[`language-`+n]={pattern:/(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,lookbehind:!0,inside:e.languages[n]},r.cdata=/^<!\[CDATA\[|\]\]>$/i;var i={"included-cdata":{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,inside:r}};i[`language-`+n]={pattern:/[\s\S]+/,inside:e.languages[n]};var a={};a[t]={pattern:RegExp(`(<__[^>]*>)(?:<!\\[CDATA\\[(?:[^\\]]|\\](?!\\]>))*\\]\\]>|(?!<!\\[CDATA\\[)[\\s\\S])*?(?=<\\/__>)`.replace(/__/g,function(){return t}),`i`),lookbehind:!0,greedy:!0,inside:i},e.languages.insertBefore(`markup`,`cdata`,a)}}),Object.defineProperty(e.languages.markup.tag,`addAttribute`,{value:function(t,n){e.languages.markup.tag.inside[`special-attr`].push({pattern:RegExp(`(^|["'\\s])(?:`+t+`)\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s'">=]+(?=[\\s>]))`,`i`),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[n,`language-`+n],inside:e.languages[n]},punctuation:[{pattern:/^=/,alias:`attr-equals`},/"|'/]}}}})}}),e.languages.html=e.languages.markup,e.languages.mathml=e.languages.markup,e.languages.svg=e.languages.markup,e.languages.xml=e.languages.extend(`markup`,{}),e.languages.ssml=e.languages.xml,e.languages.atom=e.languages.xml,e.languages.rss=e.languages.xml}})),Uq=i(((e,t)=>{t.exports=n,n.displayName=`css`,n.aliases=[];function n(e){(function(e){var t=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;e.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:/@[\w-](?:[^;{\s]|\s+(?![\s{]))*(?:;|(?=\s*\{))/,inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:`selector`},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp(`\\burl\\((?:`+t.source+`|(?:[^\\\\\\r\\n()"']|\\\\[\\s\\S])*)\\)`,`i`),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp(`^`+t.source+`$`),alias:`url`}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+t.source+`)*(?=\\s*\\{)`),lookbehind:!0},string:{pattern:t,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},e.languages.css.atrule.inside.rest=e.languages.css;var n=e.languages.markup;n&&(n.tag.addInlined(`style`,`css`),n.tag.addAttribute(`style`,`css`))})(e)}})),Wq=i(((e,t)=>{t.exports=n,n.displayName=`clike`,n.aliases=[];function n(e){e.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/}}})),Gq=i(((e,t)=>{t.exports=n,n.displayName=`javascript`,n.aliases=[`js`];function n(e){e.languages.javascript=e.languages.extend(`clike`,{"class-name":[e.languages.clike[`class-name`],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp(`(^|[^\\w$])(?:NaN|Infinity|0[bB][01]+(?:_[01]+)*n?|0[oO][0-7]+(?:_[0-7]+)*n?|0[xX][\\dA-Fa-f]+(?:_[\\dA-Fa-f]+)*n?|\\d+(?:_\\d+)*n|(?:\\d+(?:_\\d+)*(?:\\.(?:\\d+(?:_\\d+)*)?)?|\\.\\d+(?:_\\d+)*)(?:[Ee][+-]?\\d+(?:_\\d+)*)?)(?![\\w$])`),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/}),e.languages.javascript[`class-name`][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/,e.languages.insertBefore(`javascript`,`keyword`,{regex:{pattern:/((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)\/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/,lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:`language-regex`,inside:e.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:`function`},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:e.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:e.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:e.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:e.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),e.languages.insertBefore(`javascript`,`string`,{hashbang:{pattern:/^#!.*/,greedy:!0,alias:`comment`},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:`string`},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:`punctuation`},rest:e.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:`property`}}),e.languages.insertBefore(`javascript`,`operator`,{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:`property`}}),e.languages.markup&&(e.languages.markup.tag.addInlined(`script`,`javascript`),e.languages.markup.tag.addAttribute(`on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)`,`javascript`)),e.languages.js=e.languages.javascript}})),Kq=i(((e,t)=>{var n=typeof globalThis==`object`?globalThis:typeof self==`object`?self:typeof window==`object`?window:typeof global==`object`?global:{},r=C();n.Prism={manual:!0,disableWorkerMessageHandler:!0};var i=Oq(),a=Bq(),o=Vq(),s=Hq(),c=Uq(),l=Wq(),u=Gq();r();var d={}.hasOwnProperty;function f(){}f.prototype=o;var p=new f;t.exports=p,p.highlight=g,p.register=m,p.alias=h,p.registered=_,p.listLanguages=v,m(s),m(c),m(l),m(u),p.util.encode=x,p.Token.stringify=y;function m(e){if(typeof e!=`function`||!e.displayName)throw Error("Expected `function` for `grammar`, got `"+e+"`");p.languages[e.displayName]===void 0&&e(p)}function h(e,t){var n=p.languages,r=e,i,a,o,s;for(i in t&&(r={},r[e]=t),r)for(a=r[i],a=typeof a==`string`?[a]:a,o=a.length,s=-1;++s<o;)n[a[s]]=n[i]}function g(e,t){var n=o.highlight,r;if(typeof e!=`string`)throw Error("Expected `string` for `value`, got `"+e+"`");if(p.util.type(t)===`Object`)r=t,t=null;else{if(typeof t!=`string`)throw Error("Expected `string` for `name`, got `"+t+"`");if(d.call(p.languages,t))r=p.languages[t];else throw Error("Unknown language: `"+t+"` is not registered")}return n.call(this,e,r,t)}function _(e){if(typeof e!=`string`)throw Error("Expected `string` for `language`, got `"+e+"`");return d.call(p.languages,e)}function v(){var e=p.languages,t=[],n;for(n in e)d.call(e,n)&&typeof e[n]==`object`&&t.push(n);return t}function y(e,t,n){var r;return typeof e==`string`?{type:`text`,value:e}:p.util.type(e)===`Array`?b(e,t):(r={type:e.type,content:p.Token.stringify(e.content,t,n),tag:`span`,classes:[`token`,e.type],attributes:{},language:t,parent:n},e.alias&&(r.classes=r.classes.concat(e.alias)),p.hooks.run(`wrap`,r),i(r.tag+`.`+r.classes.join(`.`),S(r.attributes),r.content))}function b(e,t){for(var n=[],r=e.length,i=-1,a;++i<r;)a=e[i],a!==``&&a!=null&&n.push(a);for(i=-1,r=n.length;++i<r;)a=n[i],n[i]=p.Token.stringify(a,t,n);return n}function x(e){return e}function S(e){for(var t in e)e[t]=a(e[t]);return e}function C(){var e=`Prism`in n,t=e?n.Prism:void 0;return r;function r(){e?n.Prism=t:delete n.Prism,e=void 0,t=void 0}}})),qq=i(((e,t)=>{t.exports=n,n.displayName=`bash`,n.aliases=[`shell`];function n(e){(function(e){var t=`\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b`,n={pattern:/(^(["']?)\w+\2)[ \t]+\S.*/,lookbehind:!0,alias:`punctuation`,inside:null},r={bash:n,environment:{pattern:RegExp(`\\$`+t),alias:`constant`},variable:[{pattern:/\$?\(\([\s\S]+?\)\)/,greedy:!0,inside:{variable:[{pattern:/(^\$\(\([\s\S]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,operator:/--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp(`(\\{)`+t),lookbehind:!0,alias:`constant`}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/};e.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:`important`},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:`function`},{pattern:/\b[\w-]+(?=\s*\(\s*\)\s*\{)/,alias:`function`}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:`variable`,lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?=\+?=)/,inside:{environment:{pattern:RegExp(`(^|[\\s;|&]|[<>]\\()`+t),lookbehind:!0,alias:`constant`}},alias:`variable`,lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:r},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0,inside:{bash:n}},{pattern:/(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,lookbehind:!0,greedy:!0,inside:r},{pattern:/(^|[^$\\])'[^']*'/,lookbehind:!0,greedy:!0},{pattern:/\$'(?:[^'\\]|\\[\s\S])*'/,greedy:!0,inside:{entity:r.entity}}],environment:{pattern:RegExp(`\\$?`+t),alias:`constant`},variable:r.variable,function:{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,lookbehind:!0,alias:`class-name`},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:`important`},operator:{pattern:/\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,inside:{"file-descriptor":{pattern:/^\d/,alias:`important`}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}},n.inside=e.languages.bash;for(var i=[`comment`,`function-name`,`for-or-select`,`assign-left`,`string`,`environment`,`function`,`keyword`,`builtin`,`boolean`,`file-descriptor`,`operator`,`punctuation`,`number`],a=r.variable[1].inside,o=0;o<i.length;o++)a[i[o]]=e.languages.bash[i[o]];e.languages.shell=e.languages.bash})(e)}})),Jq=i(((e,t)=>{t.exports=n,n.displayName=`json`,n.aliases=[`webmanifest`];function n(e){e.languages.json={property:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,lookbehind:!0,greedy:!0},string:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,lookbehind:!0,greedy:!0},comment:{pattern:/\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},number:/-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,punctuation:/[{}[\],]/,operator:/:/,boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:`keyword`}},e.languages.webmanifest=e.languages.json}})),Yq=i(((e,t)=>{t.exports=n,n.displayName=`jsx`,n.aliases=[];function n(e){(function(e){var t=e.util.clone(e.languages.javascript),n=`(?:\\s|\\/\\/.*(?!.)|\\/\\*(?:[^*]|\\*(?!\\/))\\*\\/)`,r=`(?:\\{(?:\\{(?:\\{[^{}]*\\}|[^{}])*\\}|[^{}])*\\})`,i=`(?:\\{<S>*\\.{3}(?:[^{}]|<BRACES>)*\\})`;function a(e,t){return e=e.replace(/<S>/g,function(){return n}).replace(/<BRACES>/g,function(){return r}).replace(/<SPREAD>/g,function(){return i}),RegExp(e,t)}i=a(i).source,e.languages.jsx=e.languages.extend(`markup`,t),e.languages.jsx.tag.pattern=a(`<\\/?(?:[\\w.:-]+(?:<S>+(?:[\\w.:$-]+(?:=(?:"(?:\\\\[\\s\\S]|[^\\\\"])*"|'(?:\\\\[\\s\\S]|[^\\\\'])*'|[^\\s{'"/>=]+|<BRACES>))?|<SPREAD>))*<S>*\\/?)?>`),e.languages.jsx.tag.inside.tag.pattern=/^<\/?[^\s>\/]*/,e.languages.jsx.tag.inside[`attr-value`].pattern=/=(?!\{)(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s'">]+)/,e.languages.jsx.tag.inside.tag.inside[`class-name`]=/^[A-Z]\w*(?:\.[A-Z]\w*)*$/,e.languages.jsx.tag.inside.comment=t.comment,e.languages.insertBefore(`inside`,`attr-name`,{spread:{pattern:a(`<SPREAD>`),inside:e.languages.jsx}},e.languages.jsx.tag),e.languages.insertBefore(`inside`,`special-attr`,{script:{pattern:a(`=<BRACES>`),alias:`language-javascript`,inside:{"script-punctuation":{pattern:/^=(?=\{)/,alias:`punctuation`},rest:e.languages.jsx}}},e.languages.jsx.tag);var o=function(e){return e?typeof e==`string`?e:typeof e.content==`string`?e.content:e.content.map(o).join(``):``},s=function(t){for(var n=[],r=0;r<t.length;r++){var i=t[r],a=!1;if(typeof i!=`string`&&(i.type===`tag`&&i.content[0]&&i.content[0].type===`tag`?i.content[0].content[0].content===`</`?n.length>0&&n[n.length-1].tagName===o(i.content[0].content[1])&&n.pop():i.content[i.content.length-1].content===`/>`||n.push({tagName:o(i.content[0].content[1]),openedBraces:0}):n.length>0&&i.type===`punctuation`&&i.content===`{`?n[n.length-1].openedBraces++:n.length>0&&n[n.length-1].openedBraces>0&&i.type===`punctuation`&&i.content===`}`?n[n.length-1].openedBraces--:a=!0),(a||typeof i==`string`)&&n.length>0&&n[n.length-1].openedBraces===0){var c=o(i);r<t.length-1&&(typeof t[r+1]==`string`||t[r+1].type===`plain-text`)&&(c+=o(t[r+1]),t.splice(r+1,1)),r>0&&(typeof t[r-1]==`string`||t[r-1].type===`plain-text`)&&(c=o(t[r-1])+c,t.splice(r-1,1),r--),t[r]=new e.Token(`plain-text`,c,null,c)}i.content&&typeof i.content!=`string`&&s(i.content)}};e.hooks.add(`after-tokenize`,function(e){e.language!==`jsx`&&e.language!==`tsx`||s(e.tokens)})})(e)}})),Xq=i(((e,t)=>{t.exports=n,n.displayName=`markdown`,n.aliases=[`md`];function n(e){(function(e){var t=`(?:\\\\.|[^\\\\\\n\\r]|(?:\\n|\\r\\n?)(?![\\r\\n]))`;function n(e){return e=e.replace(/<inner>/g,function(){return t}),RegExp(`((?:^|[^\\\\])(?:\\\\{2})*)(?:`+e+`)`)}var r="(?:\\\\.|``(?:[^`\\r\\n]|`(?!`))+``|`[^`\\r\\n]+`|[^\\\\|\\r\\n`])+",i=`\\|?__(?:\\|__)+\\|?(?:(?:\\n|\\r\\n?)|(?![\\s\\S]))`.replace(/__/g,function(){return r}),a=`\\|?[ \\t]*:?-{3,}:?[ \\t]*(?:\\|[ \\t]*:?-{3,}:?[ \\t]*)+\\|?(?:\\n|\\r\\n?)`;e.languages.markdown=e.languages.extend(`markup`,{}),e.languages.insertBefore(`markdown`,`prolog`,{"front-matter-block":{pattern:/(^(?:\s*[\r\n])?)---(?!.)[\s\S]*?[\r\n]---(?!.)/,lookbehind:!0,greedy:!0,inside:{punctuation:/^---|---$/,"front-matter":{pattern:/\S+(?:\s+\S+)*/,alias:[`yaml`,`language-yaml`],inside:e.languages.yaml}}},blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:`punctuation`},table:{pattern:RegExp(`^`+i+a+`(?:`+i+`)*`,`m`),inside:{"table-data-rows":{pattern:RegExp(`^(`+i+a+`)(?:`+i+`)*$`),lookbehind:!0,inside:{"table-data":{pattern:RegExp(r),inside:e.languages.markdown},punctuation:/\|/}},"table-line":{pattern:RegExp(`^(`+i+`)`+a+`$`),lookbehind:!0,inside:{punctuation:/\||:?-{3,}:?/}},"table-header-row":{pattern:RegExp(`^`+i+`$`),inside:{"table-header":{pattern:RegExp(r),alias:`important`,inside:e.languages.markdown},punctuation:/\|/}}}},code:[{pattern:/((?:^|\n)[ \t]*\n|(?:^|\r\n?)[ \t]*\r\n?)(?: {4}|\t).+(?:(?:\n|\r\n?)(?: {4}|\t).+)*/,lookbehind:!0,alias:`keyword`},{pattern:/^```[\s\S]*?^```$/m,greedy:!0,inside:{"code-block":{pattern:/^(```.*(?:\n|\r\n?))[\s\S]+?(?=(?:\n|\r\n?)^```$)/m,lookbehind:!0},"code-language":{pattern:/^(```).+/,lookbehind:!0},punctuation:/```/}}],title:[{pattern:/\S.*(?:\n|\r\n?)(?:==+|--+)(?=[ \t]*$)/m,alias:`important`,inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#.+/m,lookbehind:!0,alias:`important`,inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])(?:[\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:`punctuation`},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:`punctuation`},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:`url`},bold:{pattern:n(`\\b__(?:(?!_)<inner>|_(?:(?!_)<inner>)+_)+__\\b|\\*\\*(?:(?!\\*)<inner>|\\*(?:(?!\\*)<inner>)+\\*)+\\*\\*`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^..)[\s\S]+(?=..$)/,lookbehind:!0,inside:{}},punctuation:/\*\*|__/}},italic:{pattern:n(`\\b_(?:(?!_)<inner>|__(?:(?!_)<inner>)+__)+_\\b|\\*(?:(?!\\*)<inner>|\\*\\*(?:(?!\\*)<inner>)+\\*\\*)+\\*`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^.)[\s\S]+(?=.$)/,lookbehind:!0,inside:{}},punctuation:/[*_]/}},strike:{pattern:n(`(~~?)(?:(?!~)<inner>)+\\2`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^~~?)[\s\S]+(?=\1$)/,lookbehind:!0,inside:{}},punctuation:/~~?/}},"code-snippet":{pattern:/(^|[^\\`])(?:``[^`\r\n]+(?:`[^`\r\n]+)*``(?!`)|`[^`\r\n]+`(?!`))/,lookbehind:!0,greedy:!0,alias:[`code`,`keyword`]},url:{pattern:n(`!?\\[(?:(?!\\])<inner>)+\\](?:\\([^\\s)]+(?:[\\t ]+"(?:\\\\.|[^"\\\\])*")?\\)|[ \\t]?\\[(?:(?!\\])<inner>)+\\])`),lookbehind:!0,greedy:!0,inside:{operator:/^!/,content:{pattern:/(^\[)[^\]]+(?=\])/,lookbehind:!0,inside:{}},variable:{pattern:/(^\][ \t]?\[)[^\]]+(?=\]$)/,lookbehind:!0},url:{pattern:/(^\]\()[^\s)]+/,lookbehind:!0},string:{pattern:/(^[ \t]+)"(?:\\.|[^"\\])*"(?=\)$)/,lookbehind:!0}}}}),[`url`,`bold`,`italic`,`strike`].forEach(function(t){[`url`,`bold`,`italic`,`strike`,`code-snippet`].forEach(function(n){t!==n&&(e.languages.markdown[t].inside.content.inside[n]=e.languages.markdown[n])})}),e.hooks.add(`after-tokenize`,function(e){if(e.language!==`markdown`&&e.language!==`md`)return;function t(e){if(!(!e||typeof e==`string`))for(var n=0,r=e.length;n<r;n++){var i=e[n];if(i.type!==`code`){t(i.content);continue}var a=i.content[1],o=i.content[3];if(a&&o&&a.type===`code-language`&&o.type===`code-block`&&typeof a.content==`string`){var s=a.content.replace(/\b#/g,`sharp`).replace(/\b\+\+/g,`pp`);s=(/[a-z][\w-]*/i.exec(s)||[``])[0].toLowerCase();var c=`language-`+s;o.alias?typeof o.alias==`string`?o.alias=[o.alias,c]:o.alias.push(c):o.alias=[c]}}}t(e.tokens)}),e.hooks.add(`wrap`,function(t){if(t.type===`code-block`){for(var n=``,r=0,i=t.classes.length;r<i;r++){var a=t.classes[r],o=/language-(.+)/.exec(a);if(o){n=o[1];break}}var s=e.languages[n];if(s)t.content=e.highlight(l(t.content.value),s,n);else if(n&&n!==`none`&&e.plugins.autoloader){var c=`md-`+new Date().valueOf()+`-`+Math.floor(Math.random()*0x2386f26fc10000);t.attributes.id=c,e.plugins.autoloader.loadLanguages(n,function(){var t=document.getElementById(c);t&&(t.innerHTML=e.highlight(t.textContent,e.languages[n],n))})}}});var o=RegExp(e.languages.markup.tag.pattern.source,`gi`),s={amp:`&`,lt:`<`,gt:`>`,quot:`"`},c=String.fromCodePoint||String.fromCharCode;function l(e){var t=e.replace(o,``);return t=t.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi,function(e,t){return t=t.toLowerCase(),t[0]===`#`?c(t[1]===`x`?parseInt(t.slice(2),16):Number(t.slice(1))):s[t]||e}),t}e.languages.md=e.languages.markdown})(e)}})),Zq=i(((e,t)=>{t.exports=n,n.displayName=`typescript`,n.aliases=[`ts`];function n(e){(function(e){e.languages.typescript=e.languages.extend(`javascript`,{"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,lookbehind:!0,greedy:!0,inside:null},builtin:/\b(?:Array|Function|Promise|any|boolean|console|never|number|string|symbol|unknown)\b/}),e.languages.typescript.keyword.push(/\b(?:abstract|declare|is|keyof|readonly|require)\b/,/\b(?:asserts|infer|interface|module|namespace|type)\b(?=\s*(?:[{_$a-zA-Z\xA0-\uFFFF]|$))/,/\btype\b(?=\s*(?:[\{*]|$))/),delete e.languages.typescript.parameter,delete e.languages.typescript[`literal-property`];var t=e.languages.extend(`typescript`,{});delete t[`class-name`],e.languages.typescript[`class-name`].inside=t,e.languages.insertBefore(`typescript`,`function`,{decorator:{pattern:/@[$\w\xA0-\uFFFF]+/,inside:{at:{pattern:/^@/,alias:`operator`},function:/^[\s\S]+/}},"generic-function":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,greedy:!0,inside:{function:/^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,generic:{pattern:/<[\s\S]+/,alias:`class-name`,inside:t}}}}),e.languages.ts=e.languages.typescript})(e)}})),Qq=i(((e,t)=>{var n=Yq(),r=Zq();t.exports=i,i.displayName=`tsx`,i.aliases=[];function i(e){e.register(n),e.register(r),(function(e){var t=e.util.clone(e.languages.typescript);e.languages.tsx=e.languages.extend(`jsx`,t),delete e.languages.tsx.parameter,delete e.languages.tsx[`literal-property`];var n=e.languages.tsx.tag;n.pattern=RegExp(`(^|[^\\w$]|(?=<\\/))(?:`+n.pattern.source+`)`,n.pattern.flags),n.lookbehind=!0})(e)}})),$q=i(((e,t)=>{t.exports=n,n.displayName=`yaml`,n.aliases=[`yml`];function n(e){(function(e){var t=/[*&][^\s[\]{},]+/,n=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,r=`(?:`+n.source+`(?:[ ]+`+t.source+`)?|`+t.source+`(?:[ ]+`+n.source+`)?)`,i=`(?:[^\\s\\x00-\\x08\\x0e-\\x1f!"#%&'*,\\-:>?@[\\]\`{|}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]|[?:-]<PLAIN>)(?:[ \\t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*`.replace(/<PLAIN>/g,function(){return`[^\\s\\x00-\\x08\\x0e-\\x1f,[\\]{}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]`}),a=`"(?:[^"\\\\\\r\\n]|\\\\.)*"|'(?:[^'\\\\\\r\\n]|\\\\.)*'`;function o(e,t){t=(t||``).replace(/m/g,``)+`m`;var n=`([:\\-,[{]\\s*(?:\\s<<prop>>[ \\t]+)?)(?:<<value>>)(?=[ \\t]*(?:$|,|\\]|\\}|(?:[\\r\\n]\\s*)?#))`.replace(/<<prop>>/g,function(){return r}).replace(/<<value>>/g,function(){return e});return RegExp(n,t)}e.languages.yaml={scalar:{pattern:RegExp(`([\\-:]\\s*(?:\\s<<prop>>[ \\t]+)?[|>])[ \\t]*(?:((?:\\r?\\n|\\r)[ \\t]+)\\S[^\\r\\n]*(?:\\2[^\\r\\n]+)*)`.replace(/<<prop>>/g,function(){return r})),lookbehind:!0,alias:`string`},comment:/#.*/,key:{pattern:RegExp(`((?:^|[:\\-,[{\\r\\n?])[ \\t]*(?:<<prop>>[ \\t]+)?)<<key>>(?=\\s*:\\s)`.replace(/<<prop>>/g,function(){return r}).replace(/<<key>>/g,function(){return`(?:`+i+`|`+a+`)`})),lookbehind:!0,greedy:!0,alias:`atrule`},directive:{pattern:/(^[ \t]*)%.+/m,lookbehind:!0,alias:`important`},datetime:{pattern:o(`\\d{4}-\\d\\d?-\\d\\d?(?:[tT]|[ \\t]+)\\d\\d?:\\d{2}:\\d{2}(?:\\.\\d*)?(?:[ \\t]*(?:Z|[-+]\\d\\d?(?::\\d{2})?))?|\\d{4}-\\d{2}-\\d{2}|\\d\\d?:\\d{2}(?::\\d{2}(?:\\.\\d*)?)?`),lookbehind:!0,alias:`number`},boolean:{pattern:o(`false|true`,`i`),lookbehind:!0,alias:`important`},null:{pattern:o(`null|~`,`i`),lookbehind:!0,alias:`important`},string:{pattern:o(a),lookbehind:!0,greedy:!0},number:{pattern:o(`[+-]?(?:0x[\\da-f]+|0o[0-7]+|(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?|\\.inf|\\.nan)`,`i`),lookbehind:!0},tag:n,important:t,punctuation:/---|[:[\]{}\-,|>?]|\.\.\./},e.languages.yml=e.languages.yaml})(e)}})),eJ=e(Kq(),1),tJ=e(qq(),1),nJ=e(Uq(),1),rJ=e(Gq(),1),iJ=e(Jq(),1),aJ=e(Yq(),1),oJ=e(Xq(),1),sJ=e(Hq(),1),cJ=e(Qq(),1),lJ=e(Zq(),1),uJ=e($q(),1),dJ=e=>{let t=e.displayName;!t||eJ.default.registered(t)||eJ.default.register(e)};dJ(sJ.default),dJ(nJ.default),dJ(rJ.default),dJ(lJ.default),dJ(cJ.default),dJ(iJ.default),dJ(aJ.default),dJ(oJ.default),dJ(uJ.default),dJ(tJ.default);var fJ=r({TicketChangesModal:()=>UJ}),pJ=(e,t)=>Pe.t(`common:ticketChangesModal.${e}`,t),mJ=4,hJ=1500,gJ=`archon.ticket-changes.review-comments`,_J=[],vJ=[],yJ=[],bJ=e=>new Set(e.map(e=>e.path)),xJ=(e,t)=>{if(!e)return null;if(e.blocked_reason)return e.blocked_reason;let n=e.files.find(e=>!t.has(e.path)&&e.staged);return n?`"${n.path}" already has staged changes. Finish that commit in the terminal first.`:null},SJ=e=>e.replace(/^[ab]\//,``),CJ=e=>{let t=`oldPath`in e&&typeof e.oldPath==`string`?SJ(e.oldPath):``,n=`newPath`in e&&typeof e.newPath==`string`?SJ(e.newPath):``;return[...new Set([n,t].filter(e=>e&&e!==`/dev/null`))]},wJ=e=>{let[t,n]=CJ(e);return!t&&!n?`Unknown file`:t&&n&&t!==n?`${n} -> ${t}`:t??n??`Unknown file`},TJ=e=>{let[t,n]=CJ(e);return t??n??null},EJ=e=>e.hunks.reduce((e,t)=>e+t.changes.length,0),DJ=e=>{if(EJ(e)>hJ)return null;let t=eq(TJ(e));if(!t)return null;try{return Yy(e.hunks,{highlight:!0,refractor:eJ.default,language:t,enhancers:[qy(e.hunks)]})}catch{return null}},OJ=(e,t)=>e instanceof Error?e.message:t,kJ=(e,t)=>`${gJ}:${e}:${t}`,AJ=()=>({activeTarget:null,editingCommentKey:null,draftInput:``,comments:new Map,signature:null}),jJ=()=>({uncommitted:AJ(),bundle_diff:AJ()}),MJ=e=>({uncommitted:e(),bundle_diff:e()}),NJ=()=>MJ(()=>new Map),PJ=e=>{let t=5381;for(let n=0;n<e.length;n+=1)t=(t<<5)+t^e.charCodeAt(n);return`${e.length}:${t>>>0}`},FJ=e=>{if(!e||typeof e!=`object`)return!1;let t=e;return(t.scope===void 0||t.scope===`uncommitted`||t.scope===`bundle_diff`)&&typeof t.filePath==`string`&&typeof t.changeKey==`string`&&typeof t.changeType==`string`&&(typeof t.oldLineNumber==`number`||t.oldLineNumber===null)&&(typeof t.newLineNumber==`number`||t.newLineNumber===null)&&typeof t.hunkHeader==`string`&&typeof t.lineContent==`string`&&typeof t.diffSnippet==`string`&&typeof t.comment==`string`},IJ=e=>{try{let t=JSON.parse(e);if(!t||typeof t!=`object`)return null;let n=t;if(typeof n.diffSignature!=`string`||!Array.isArray(n.comments))return null;let r=n.comments.filter(FJ).map(e=>({scope:e.scope??`uncommitted`,filePath:e.filePath,changeKey:e.changeKey,changeType:e.changeType,oldLineNumber:e.oldLineNumber,newLineNumber:e.newLineNumber,hunkHeader:e.hunkHeader,lineContent:e.lineContent,diffSnippet:e.diffSnippet,comment:e.comment}));return r.length===n.comments.length?{diffSignature:n.diffSignature,comments:r}:null}catch{return null}},LJ=e=>new Map(e.map(e=>[lb(e.filePath,e.changeKey),e])),RJ=(e,t)=>{e.set(t,(e.get(t)??0)+1)},zJ=e=>e.find(e=>e.trim())||``,BJ=({gitStatus:e,isProjectTargetRepoRoot:t,isGitHubConnected:n,effectiveDefaultBaseBranch:r})=>t&&!!e?.branch&&e?.has_upstream===!0&&(e?.ahead??0)===0&&!!r&&e?.branch!==r&&n,VJ=({pullRequest:e,isLoading:t,isOpen:n,canCreate:r,disabledReason:i,isCreating:a,isSyncing:o,isGeneratingDescription:s,title:c,body:l,baseBranch:u,onOpenChange:d,onTitleChange:f,onBodyChange:p,onBaseBranchChange:m,showGenerateDescription:h,onGenerateDescription:g,onCreate:_})=>t?(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,disabled:!0,className:`gap-2`,children:pJ(`loadingPullRequest`)}):o?(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`outline`,disabled:!0,className:`gap-2`,children:[(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}),pJ(`checkingPullRequest`)]}):e?(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 rounded-xl border border-border/80 bg-background/50 px-3 py-2`,children:[(0,Z.jsx)(yw,{pullRequest:e}),(0,Z.jsxs)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,className:`text-xs font-medium text-sky-300 underline underline-offset-2 hover:text-sky-200`,children:[`PR #`,e.number]})]}):(0,Z.jsxs)($s,{open:n,onOpenChange:d,children:[(0,Z.jsx)(ec,{asChild:!0,children:(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`default`,disabled:!r,title:i,className:`gap-2`,children:[a?(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}):(0,Z.jsx)(Pc,{className:`h-4 w-4`}),pJ(a?`creatingPullRequest`:`createPullRequest`)]})}),(0,Z.jsxs)(tc,{align:`end`,className:`z-[90] w-[36rem] max-w-[calc(100vw-2rem)] p-4`,children:[(0,Z.jsx)(nc,{children:(0,Z.jsx)(rc,{children:pJ(`createPullRequestTitle`)})}),(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(Cu,{label:pJ(`pullRequestFieldTitle`),htmlFor:`bundle-pr-title`,children:(0,Z.jsx)(Ge,{id:`bundle-pr-title`,value:c,onChange:e=>f(e.target.value),placeholder:pJ(`pullRequestTitlePlaceholder`),disabled:a})}),(0,Z.jsx)(Cu,{label:pJ(`pullRequestFieldBaseBranch`),htmlFor:`bundle-pr-base-branch`,description:pJ(`pullRequestBaseBranchDescription`),children:(0,Z.jsx)(Ge,{id:`bundle-pr-base-branch`,value:u,onChange:e=>m(e.target.value),placeholder:pJ(`pullRequestBaseBranchPlaceholder`),disabled:a})}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium uppercase tracking-[0.22em] text-muted-foreground`,htmlFor:`bundle-pr-body`,children:pJ(`pullRequestFieldDescription`)}),h&&(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`outline`,className:`gap-2`,disabled:a||s,onClick:g,children:[s?(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}):null,pJ(s?`generatingDescription`:`generateDescription`)]})]}),(0,Z.jsx)(zs,{id:`bundle-pr-body`,value:l,onChange:e=>p(e.target.value),placeholder:pJ(`pullRequestDescriptionPlaceholder`),className:`min-h-40`,disabled:a})]}),(0,Z.jsx)(`div`,{className:`flex justify-end`,children:(0,Z.jsx)(q,{type:`button`,size:`sm`,disabled:!c.trim()||a,onClick:_,children:pJ(a?`creating`:`createPullRequest`)})})]})]})]}),HJ=(e,t,n)=>{if(n)return bJ(t);let r=new Set(t.map(e=>e.path));return new Set([...e].filter(e=>r.has(e)))},UJ=e=>{let{projectId:t,reviewCommentsBundleId:n=null,targetKind:r,repoRootDefaultBranch:i=null,title:a,hasHelperModel:o=!1,onClose:s,onSubmitReviewPrompt:c,canSubmitReviewPrompt:l=!1,reviewSubmitDisabledReason:u,canAddReviewComments:d=!0,canModifyChanges:f=!0,changesDisabledReason:m}=e,h=e.scope??`ticket`,{isGitHubConnected:g,defaultBaseBranch:_}=mf(t),v=e.scope===`project_root`?null:e.ticketId,y=e.scope===`project_root`?void 0:e.onTicketUpdate,b=e.scope===`project_root`?void 0:e.onRequestTicketRefresh,x=h===`project_root`,S=!!(t&&n),C=r??(S?`bundle`:`repo_root`),w=x&&C===`repo_root`,T=_??i,[E,D]=(0,Y.useState)(`uncommitted`),[O,k]=(0,Y.useState)(null),[A,j]=(0,Y.useState)(null),[M,N]=(0,Y.useState)(null),[P,F]=(0,Y.useState)([]),[I,L]=(0,Y.useState)(new Set),[R,z]=(0,Y.useState)(`all`),[ee,ne]=(0,Y.useState)(``),[re,B]=(0,Y.useState)(null),[ie,V]=(0,Y.useState)(null),[H,ae]=(0,Y.useState)(null),[oe,se]=(0,Y.useState)(null),[ce,ue]=(0,Y.useState)(!0),[de,pe]=(0,Y.useState)(!1),[me,he]=(0,Y.useState)(!0),[G,_e]=(0,Y.useState)(!1),[ve,ye]=(0,Y.useState)(!1),[be,xe]=(0,Y.useState)(!1),[K,Se]=(0,Y.useState)(null),[we,Te]=(0,Y.useState)(!1),[Ee,De]=(0,Y.useState)(`unified`),[Oe,je]=(0,Y.useState)(new Map),[Ne,Pe]=(0,Y.useState)(yJ),[Ie,Le]=(0,Y.useState)(jJ),[Re,Be]=(0,Y.useState)(null),[Ve,He]=(0,Y.useState)([]),[Ge,qe]=(0,Y.useState)(null),[Je,Ye]=(0,Y.useState)(null),[Xe,Ze]=(0,Y.useState)(new Set),[Qe,$e]=(0,Y.useState)(new Set),[et,J]=(0,Y.useState)(!1),[tt,nt]=(0,Y.useState)(null),[rt,it]=(0,Y.useState)(null),[at,ot]=(0,Y.useState)(!1),[st,ct]=(0,Y.useState)(!1),[lt,ut]=(0,Y.useState)(``),[dt,ft]=(0,Y.useState)(``),[pt,mt]=(0,Y.useState)(``),[ht,gt]=(0,Y.useState)([]),[_t,vt]=(0,Y.useState)(!1),[yt,bt]=(0,Y.useState)(!1),[X,xt]=(0,Y.useState)(!1),St=(0,Y.useRef)(null),Ct=(0,Y.useRef)(!1),wt=(0,Y.useRef)(null),Tt=(0,Y.useRef)(null),Et=(0,Y.useRef)(0),Ot=(0,Y.useRef)(0),Mt=(0,Y.useRef)(!1),Nt=(0,Y.useRef)(MJ(()=>null)),Pt=(0,Y.useRef)(NJ()),Ft=(0,Y.useRef)(`idle`),zt=(0,Y.useRef)(0),Bt=(0,Y.useRef)(null),Vt=(0,Y.useMemo)(()=>YK({scope:h,projectId:t,ticketId:v,projectTargetBundleId:x?n:null}),[t,n,h,v,x]),Ht=(0,Y.useCallback)(()=>{if(!v)throw Error(`Ticket changes require a ticket id.`);return v},[v]),Ut=(0,Y.useCallback)(e=>{wt.current=e,k(e),B(null)},[]),Wt=(0,Y.useCallback)((e,t)=>{ZK({cacheKey:Vt,diffResponse:e,gitStatus:t})},[Vt]),Gt=(0,Y.useCallback)(e=>{wt.current&&ZK({cacheKey:Vt,diffResponse:wt.current,gitStatus:e})},[Vt]),Kt=(0,Y.useCallback)(async()=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await Ae(t)}return await $t(Ht(),t)},[t,Ht,h]),qt=(0,Y.useCallback)(async()=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await ge(t)}return await en(Ht(),t,{refreshRemote:!1})},[t,Ht,h]),Jt=(0,Y.useCallback)(async()=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await Ke(t)}return await an(Ht(),t)},[t,Ht,h]),Yt=(0,Y.useCallback)(async e=>!n||!t?null:await It(t,n,e),[t,n]),Xt=(0,Y.useCallback)(async e=>!n||!t?null:await Dt(t,n,e),[t,n]),Zt=(0,Y.useCallback)(async e=>!n||!t?null:await Lt(t,n,e),[t,n]),Qt=(0,Y.useCallback)(async e=>!n||!t?null:await Rt(t,n,e),[t,n]),sn=(0,Y.useCallback)(function e({silent:r}){if(!n||!t||!tt?.bundle.pull_request||!g||Ft.current===`loaded`)return Promise.resolve();if(Ft.current===`loading`){let t=Bt.current;return t?t.then(()=>{if(!r&&Ft.current===`idle`)return e({silent:!1})}):Promise.resolve()}r||Ye(null),Ft.current=`loading`;let i=zt.current,a=Qt().then(e=>{if(i===zt.current){if(!e){Ft.current=`idle`;return}if(e.error){r||(He(e.comments),Ye(e.error),$e(t=>{let n=new Set(e.comments.map(e=>e.id));return new Set([...t].filter(e=>n.has(e)))})),Ft.current=`idle`;return}He(e.comments),Ye(null),$e(t=>{let n=new Set(e.comments.map(e=>e.id));return new Set([...t].filter(e=>n.has(e)))}),Ft.current=`loaded`}}).catch(e=>{i===zt.current&&(Ft.current=`idle`,!r&&(He([]),Ye(OJ(e,`Unable to load GitHub review comments right now.`)),$e(new Set)))}).finally(()=>{i===zt.current&&Bt.current===a&&(Bt.current=null)});return Bt.current=a,a},[tt?.bundle.pull_request,g,t,Qt,n]),cn=(0,Y.useCallback)((e,t)=>{Le(n=>({...n,[e]:t(n[e])}))},[]),ln=(0,Y.useCallback)(async e=>{if(S&&n&&t)return await At(t,n,e);if(x){if(!t)throw Error(`Project changes require a project id.`);return await Fe(t,e)}throw Error(`Pull request description generation requires a supported target context.`)},[S,t,n,x]),un=(0,Y.useCallback)(async e=>{if(!t)throw Error(`Project changes require a project id.`);return await We(t,e)},[t]),dn=(0,Y.useCallback)(async e=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await le(t,e)}return await tn(Ht(),t,e)},[t,Ht,h]),fn=(0,Y.useCallback)(async e=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await fe(t,e)}return await nn(Ht(),t,e)},[t,Ht,h]),pn=(0,Y.useCallback)(async(e={})=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await te(t,e)}return await rn(Ht(),t,e)},[t,Ht,h]),mn=(0,Y.useCallback)(async()=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await p(t)}return await on(Ht(),t)},[t,Ht,h]),hn=(0,Y.useCallback)(async(e,t={})=>{let n=t.preserveContent??!1,r=Et.current+1;Et.current=r,_e(!0),n||se(null);try{let t=await Jt();if(!e()||Et.current!==r)return;F(t.commits),se(null)}catch(t){if(!e()||Et.current!==r)return;se(OJ(t,`Unable to load local commits right now.`)),n||F([])}finally{e()&&Et.current===r&&_e(!1)}},[Jt]),gn=(0,Y.useCallback)(()=>{Et.current+=1,F([]),se(null),_e(!1)},[]),_n=(0,Y.useCallback)((e,t={})=>{let n=t.resetSelection??!1;Tt.current=e,N(e),ae(null),L(t=>{let r=HJ(t,e.files,n||!Ct.current);return Ct.current=!0,r})},[]),vn=(0,Y.useCallback)(async(e={})=>{let t=e.preserveContent??!1,n=e.gitStatusForCache??null;t||B(null),ue(!0);try{let e=await Kt();Ut(e),n&&Wt(e,n)}catch(e){n&&QK(Vt),(!t||!wt.current)&&B(OJ(e,`Unable to load the diff right now.`))}finally{ue(!1)}},[Ut,Vt,Kt,Wt]),yn=(0,Y.useCallback)(async(e={})=>{let t=e.preserveContent??!1;if(!S){j(null),V(null),pe(!1);return}t||V(null),pe(!0);try{j(await Zt()),V(null)}catch(e){(!t||!A)&&V(OJ(e,`Unable to load the branch diff right now.`))}finally{pe(!1)}},[A,S,Zt]),bn=(0,Y.useCallback)(async(e,t={})=>{let n=t.preserveContent??!1,r=t.resetSelection??!1,i=t.allowCache??!0?XK(Vt):null;if(n||(B(null),ae(null)),he(!0),i){Ut(i.diffResponse),_n(i.gitStatus,{resetSelection:r}),ue(!1);try{let t=await qt();if(!e())return;_n(t,{resetSelection:r}),he(!1),(t.ahead??0)>0?hn(e,{preserveContent:!0}):gn();let n=t.workspace_signature??null;if(n&&n===i.workspaceSignature){Wt(i.diffResponse,t);return}QK(Vt),await vn({preserveContent:!0,gitStatusForCache:t});return}catch(t){if(!e())return;ae(OJ(t,`Unable to load git status right now.`)),N(null),he(!1),gn();return}}ue(!0),Kt().then(t=>{e()&&(Ut(t),Tt.current&&Wt(t,Tt.current))}).catch(t=>{e()&&(!n||!wt.current)&&B(OJ(t,`Unable to load the diff right now.`))}).finally(()=>{e()&&ue(!1)});try{let t=await qt();if(!e())return;_n(t,{resetSelection:r}),he(!1),wt.current&&Wt(wt.current,t),(t.ahead??0)>0?hn(e,{preserveContent:n}):gn()}catch(t){if(!e())return;ae(OJ(t,`Unable to load git status right now.`)),n||N(null),he(!1),gn()}},[Ut,_n,Vt,gn,hn,vn,Kt,qt,Wt]),xn=(0,Y.useCallback)(async()=>{if(!t)return;let e=Ot.current+1;Ot.current=e,he(!0);try{let t=await qt();if(Ot.current!==e)return;let n=Tt.current?.workspace_signature??null,r=t.workspace_signature??null,i=!wt.current||n!==r;if(_n(t),(t.ahead??0)>0?hn(()=>Ot.current===e,{preserveContent:!0}):gn(),!i){Gt(t);return}await vn({preserveContent:!0,gitStatusForCache:t})}catch{return}finally{Ot.current===e&&he(!1)}},[_n,gn,hn,vn,t,qt,Gt]);(0,Y.useEffect)(()=>{wt.current=O},[O]),(0,Y.useEffect)(()=>{Tt.current=M},[M]),(0,Y.useEffect)(()=>{let e=!0;return bn(()=>e,{resetSelection:!0}),()=>{e=!1}},[bn]),(0,Y.useEffect)(()=>{if(t)return rq(e=>{if(e===t){if(Mt.current){Mt.current=!1;return}xn()}})},[t,xn]),(0,Y.useEffect)(()=>{if(!t)return;let e=aq(()=>{document.visibilityState===`visible`&&xn()});return()=>{e()}},[t,xn]),(0,Y.useEffect)(()=>{if(!S){Be(null),qe(null),Ze(new Set);return}if(!O?.diff?.trim()){Be(null),qe(null),Ze(new Set);return}let e=new AbortController,t=!0;return qe(null),Yt(e.signal).then(e=>{t&&(Be(e),Ze(t=>{let n=new Set((e?.findings??[]).map(e=>e.id));return new Set([...t].filter(e=>n.has(e)))}))}).catch(n=>{!t||e.signal.aborted||(qe(OJ(n,`Unable to load review findings right now.`)),Be(null),Ze(new Set))}),()=>{t=!1,e.abort()}},[O?.diff,S,Yt]),(0,Y.useEffect)(()=>{D(`uncommitted`),Nt.current=MJ(()=>null),Pt.current=NJ(),Le(jJ()),j(null),V(null),pe(!1),zt.current+=1,Ft.current=`idle`,Bt.current=null,He([]),Ye(null),$e(new Set),nt(null),it(null),ot(!1),ct(!1),ut(``),ft(``),mt(``),gt([]),vt(!1),bt(!1),xt(!1)},[n,C]),(0,Y.useEffect)(()=>{if(!S){nt(null),ot(!1);return}if(O===null&&!re){ot(!1);return}let e=new AbortController,t=!0;return ot(!0),Xt(e.signal).then(e=>{t&&(nt(e),ut(t=>t.trim()?t:e?.bundle?Dl(e.bundle):a),ft(t=>t.trim()?t:zJ(e?.recent_commit_subjects??ht)),mt(t=>t.trim()?t:e?.bundle.pull_request?.base_branch??``))}).catch(()=>{!t||e.signal.aborted||nt(null)}).finally(()=>{t&&ot(!1)}),()=>{t=!1,e.abort()}},[re,O,ht,t,Xt,S,a]),(0,Y.useEffect)(()=>{w&&(ut(e=>e.trim()&&e!==a?e:M?.branch??a),ft(e=>e.trim()?e:zJ(ht)))},[M?.branch,w,ht,a]),(0,Y.useEffect)(()=>{if(!S){j(null),V(null),pe(!1);return}if(E!==`bundle_diff`){pe(!1);return}let e=new AbortController,t=!0;return pe(!0),V(null),Zt(e.signal).then(e=>{t&&(j(e),V(null))}).catch(n=>{!t||e.signal.aborted||(V(OJ(n,`Unable to load the branch diff right now.`)),j(null))}).finally(()=>{t&&pe(!1)}),()=>{t=!1,e.abort()}},[E,S,Zt]),(0,Y.useEffect)(()=>{let e=tt?.bundle.pull_request??null;if(!S||!e){zt.current+=1,Ft.current=`idle`,Bt.current=null,He([]),Ye(null),$e(new Set);return}if(!g){zt.current+=1,Ft.current=`idle`,Bt.current=null,He([]),Ye(null),$e(new Set);return}sn({silent:!0})},[tt?.bundle.pull_request,sn,g,S]),(0,Y.useEffect)(()=>{E===`bundle_diff`&&sn({silent:!1})},[E,tt?.bundle.pull_request,sn,g]),(0,Y.useEffect)(()=>{me&&M===null||St.current?.focus()},[M,me]);let Sn=(0,Y.useMemo)(()=>{let e=typeof O?.diff==`string`?O.diff:``;return e.trim()?Bm(e).map(e=>({...e,pathCandidates:CJ(e)})):[]},[O]),Cn=(0,Y.useMemo)(()=>{let e=typeof A?.diff==`string`?A.diff:``;return e.trim()?Bm(e).map(e=>({...e,pathCandidates:CJ(e)})):[]},[A]),wn=(0,Y.useMemo)(()=>{let e=O?.diff??``;return e?PJ(e):null},[O?.diff]),Tn=(0,Y.useMemo)(()=>{let e=A?.diff??``;return e?PJ(e):null},[A?.diff]),En=E===`bundle_diff`?A:O,Dn=E===`bundle_diff`?Cn:Sn,On=(0,Y.useMemo)(()=>n?{uncommitted:kJ(n,`uncommitted`),bundle_diff:kJ(n,`bundle_diff`)}:{uncommitted:null,bundle_diff:null},[n]),kn=(0,Y.useMemo)(()=>({uncommitted:wn,bundle_diff:Tn}),[Tn,wn]),An=(0,Y.useMemo)(()=>{let e=new Map;for(let t of En?.files??[])e.set(t.path,t);return e},[En]),jn=(0,Y.useMemo)(()=>{let e=new Map;for(let t of Dn)for(let n of t.pathCandidates)e.has(n)||e.set(n,t);return e},[Dn]),Mn=(0,Y.useCallback)(e=>{Pe(t=>t.length===e.length&&t.every((t,n)=>t===e[n])?t:e)},[]),Nn=(0,Y.useMemo)(()=>E===`bundle_diff`?(A?.files??[]).map(e=>({path:e.path,originalPath:null,status:null,staged:!1,unstaged:!1,conflicted:!1,additions:e.additions,deletions:e.deletions})):M?(M.files??[]).map(e=>{let t=An.get(e.path)??(e.original_path?An.get(e.original_path):void 0);return{path:e.path,originalPath:e.original_path,status:e.status,staged:e.staged,unstaged:e.unstaged,conflicted:e.conflicted,additions:t?.additions??0,deletions:t?.deletions??0}}):(O?.files??[]).map(e=>({path:e.path,originalPath:null,status:null,staged:!1,unstaged:!1,conflicted:!1,additions:e.additions,deletions:e.deletions})),[E,A?.files,An,O?.files,M]);(0,Y.useEffect)(()=>{R!==`all`&&(Nn.some(e=>e.path===R)||z(`all`))},[R,Nn]);let Pn=E===`bundle_diff`?0:I.size,Fn=K!==null,In=K===`force`,Ln=E===`bundle_diff`?Nn.length:M?.files?.length??Nn.length,Rn=Ln>0&&Pn===Ln,zn=(0,Y.useMemo)(()=>E===`bundle_diff`?null:xJ(M,I),[E,M,I]),Bn=E===`uncommitted`&&!me&&!ve&&f&&!!M&&Pn>0&&ee.trim().length>0&&zn===null,Vn=E===`uncommitted`&&!me&&!ce&&!be&&!ve&&!Fn&&f&&!et&&!!M&&Pn>0,Hn=!me&&(Fn||!!M?.can_push&&(M?.ahead??0)>0),Un=Hn&&!!M?.can_force_push_with_lease,Wn=Hn&&f&&!Fn&&!ve,Gn=Un&&f&&!Fn&&!ve,Kn=f&&!G&&!we&&!ve&&!Fn&&(P?.length??0)>0,qn=(M?.ahead??0)>0?`${M?.ahead??0} to push`:`Up to date`,Jn=(M?.behind??0)>0?`${M?.behind??0} behind`:`In sync`,Yn=M?.branch??null,Xn=R===`all`?null:jn.get(R)??null,Zn=(0,Y.useMemo)(()=>R===`all`?Dn:Xn?[Xn]:[],[Dn,R,Xn]);(0,Y.useEffect)(()=>{je(new Map),Pe(yJ)},[E,Dn]),(0,Y.useEffect)(()=>{let e={uncommitted:On.uncommitted&&kn.uncommitted?`${On.uncommitted}:${kn.uncommitted}`:null,bundle_diff:On.bundle_diff&&kn.bundle_diff?`${On.bundle_diff}:${kn.bundle_diff}`:null},t=Nt.current;t.uncommitted===e.uncommitted&&t.bundle_diff===e.bundle_diff||(Nt.current=e,Le(n=>{let r={...n};return[`uncommitted`,`bundle_diff`].forEach(i=>{if(t[i]===e[i])return;let a=kn[i],o=On[i],s=n[i];if(t[i]===null&&a&&(s.activeTarget||s.editingCommentKey||s.draftInput.trim()||s.comments.size>0)){r[i]={...s,signature:a};return}if(!a){Pt.current[i]=new Map,r[i]=AJ();return}let c=new Map;if(o){let e=window.localStorage.getItem(o),t=e?IJ(e):null;t?.diffSignature===a?c=LJ(t.comments.map(e=>({...e,scope:i}))):e!==null&&window.localStorage.removeItem(o)}Pt.current[i]=new Map,r[i]={activeTarget:null,editingCommentKey:null,draftInput:``,comments:c,signature:a}}),r}))},[kn,On]),(0,Y.useEffect)(()=>{[`uncommitted`,`bundle_diff`].forEach(e=>{let t=On[e],n=kn[e],r=Ie[e];if(!t||!n||r.signature!==n)return;if(r.comments.size===0){window.localStorage.removeItem(t);return}let i={diffSignature:n,comments:[...r.comments.values()]};window.localStorage.setItem(t,JSON.stringify(i))})},[kn,On,Ie]),(0,Y.useEffect)(()=>{if(Dn.length===0)return;let e=!1,t=null,n=(()=>{if(!Xn){let e=[],t=new Set;for(let n of Ne){let r=jn.get(n);if(!r)continue;let i=wJ(r);t.has(i)||(t.add(i),e.push(r))}return e.length>0?e:Dn.slice(0,mJ)}return[Xn]})(),r=0,i=()=>{if(e)return;let a=n.slice(r,r+mJ);a.length!==0&&(je(e=>{let t=new Map(e);for(let e of a){let n=wJ(e);t.has(n)||t.set(n,DJ(e))}return t}),r+=mJ,r<n.length&&(t=window.setTimeout(i,0)))};return n.length<=mJ?i():t=window.setTimeout(i,0),()=>{e=!0,t!==null&&window.clearTimeout(t)}},[Dn,jn,Xn,Ne]);let Qn=(0,Y.useMemo)(()=>Zn.map(e=>({...e,tokens:Oe.get(wJ(e))??null})),[Oe,Zn]),$n=(0,Y.useMemo)(()=>Dn.map(e=>({...e,tokens:null})),[Dn]),er=(0,Y.useMemo)(()=>{let e=new Map;for(let t of Dn){let n=wJ(t);e.set(n,n);for(let r of CJ(t))e.set(r,n)}return e},[Dn]),tr=(0,Y.useMemo)(()=>[...Ie.uncommitted.comments.values()],[Ie.uncommitted.comments]),nr=(0,Y.useMemo)(()=>[...Ie.bundle_diff.comments.values()],[Ie.bundle_diff.comments]),rr=Ie[E],ir=rr.activeTarget,ar=rr.editingCommentKey,or=ir?.commentKey??ar,sr=or?`${E}:${or}`:E,cr=or?Pt.current[E].get(or)??rr.draftInput:rr.draftInput,lr=E===`bundle_diff`?nr:tr,ur=(0,Y.useMemo)(()=>[...tr,...nr],[nr,tr]),dr=(0,Y.useMemo)(()=>Re?.findings??[],[Re]),fr=(0,Y.useMemo)(()=>Re?.is_current_diff?dr.filter(e=>Xe.has(e.id)):[],[dr,Re?.is_current_diff,Xe]),pr=(0,Y.useMemo)(()=>[...Xe],[Xe]),mr=(0,Y.useMemo)(()=>Ve.filter(e=>Qe.has(e.id)),[Ve,Qe]),hr=(0,Y.useMemo)(()=>[...Qe],[Qe]),gr=ur.length+fr.length+mr.length,_r=!!(Re?.review_run&&dr.length>0&&!Re.is_current_diff),vr=tt?.bundle.pull_request??null,yr=vr??rt,br=(0,Y.useMemo)(()=>ht.length>0?ht:tt?.recent_commit_subjects??[],[tt?.recent_commit_subjects,ht]),xr=tt?.has_helper_model===!0||o,Sr=S,Cr=E===`bundle_diff`?ie:re,wr=ce&&O===null,Tr=de&&A===null,Er=me&&M===null,Dr=at&&tt===null,Or=E===`bundle_diff`?Tr:wr,kr=E===`uncommitted`?dr:_J,Ar=E===`uncommitted`?pr:yJ,jr=E===`bundle_diff`?Ve:vJ,Mr=E===`bundle_diff`?hr:yJ,Nr=E===`bundle_diff`?`bundle_diff`:`uncommitted`,Pr=(0,Y.useMemo)(()=>{let e=new Map,t=e=>e?er.get(e)??e:null;for(let n of lr){let r=t(n.filePath);r&&RJ(e,r)}if(E===`uncommitted`){if(_r)return e;for(let n of dr){let r=t(n.file_path);r&&RJ(e,r)}return e}for(let n of Ve){let r=t(n.file_path);r&&RJ(e,r)}return e},[E,er,lr,Ve,_r,dr]),Fr=(_r?0:dr.length)+tr.length,Ir=Ve.length+nr.length,Lr=E===`bundle_diff`?`No branch diff to show.`:`No uncommitted changes to show.`,Rr=E===`uncommitted`&&Sr?`Switch to Branch diff to review the full branch diff.`:null,zr=Sr&&!Dr&&!!tt&&tt?.bundle.kind!==`project_root`&&M?.has_upstream===!0&&g,Br=BJ({gitStatus:M,isProjectTargetRepoRoot:w,isGitHubConnected:g,effectiveDefaultBaseBranch:T}),Vr=zr||Br,Hr=Vr&&!vr&&!rt&&!_t&&!yt&&!X&&!et&&!Fn&&!ve&&!we&&(M?.ahead??0)===0&&!!M?.branch,Ur=(0,Y.useCallback)(e=>{if(!e){ct(!1);return}if(!S){ct(e);return}if(!t||!n||!zr||vr||yt){ct(e);return}bt(!0),jt(t,n).then(e=>{nt(e),mt(t=>t.trim()?t:e.bundle.pull_request?.base_branch??``),ct(!e.bundle.pull_request)}).catch(e=>{Q.error(OJ(e,`Unable to check for an existing pull request right now.`),{id:`ticket-changes-sync-pr-error`}),ct(!0)}).finally(()=>{bt(!1)})},[vr,S,yt,t,n,zr]),Wr=(0,Y.useMemo)(()=>{if(Vr)return(M?.ahead??0)>0?`Push the branch before creating a pull request.`:M?.branch?m:pJ(`branchUnavailable`)},[m,M?.ahead,M?.branch,Vr]),Gr=d&&!Or&&(E===`bundle_diff`||!Er)&&!ve&&!Fn&&!we,Kr=ir?Gr||rr.comments.has(ir.commentKey):Gr,qr=!!c&&l&&gr>0&&!et,Jr=(0,Y.useCallback)(e=>{Ze(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Yr=(0,Y.useCallback)(e=>{$e(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Xr=(0,Y.useCallback)(()=>{Pt.current=NJ(),Le(e=>({uncommitted:{...e.uncommitted,activeTarget:null,editingCommentKey:null,draftInput:``,comments:new Map},bundle_diff:{...e.bundle_diff,activeTarget:null,editingCommentKey:null,draftInput:``,comments:new Map}}))},[]),Zr=(0,Y.useCallback)(()=>{Xr(),Ze(new Set),$e(new Set)},[Xr]),Qr=(0,Y.useCallback)(async()=>{if(!(!t||!Hr)){vt(!0);try{if(S&&n){let e=await kt(t,n,{title:lt.trim(),body:dt.trim(),base_branch:pt.trim()||null});nt(e),mt(e.bundle.pull_request?.base_branch??pt.trim())}else{let e=await un({title:lt.trim(),body:dt.trim(),base_branch:pt.trim()||null});it(e.pull_request),mt(e.pull_request.base_branch||pt.trim())}ct(!1),Q.success(pJ(`pullRequestCreated`),{id:`ticket-changes-create-pr-success`})}catch(e){Q.error(OJ(e,pJ(`createPullRequestFallbackError`)),{id:`ticket-changes-create-pr-error`})}finally{vt(!1)}}},[Hr,t,pt,dt,lt,un,n,S]),$r=(0,Y.useCallback)(async()=>{if(!(!t||!Vr||X)){xt(!0);try{ft((await ln({title:lt.trim(),commit_subjects:br})).description)}catch(e){Q.error(OJ(e,`Unable to generate the pull request description right now.`),{id:`ticket-changes-generate-pr-description-error`})}finally{xt(!1)}}},[X,t,br,lt,ln,Vr]),ei=(0,Y.useCallback)(({filePath:e,changeKey:t,commentKey:n})=>{let r=rr.comments.get(n),i=Pt.current[E].get(n)??r?.comment??``;if(r){z(r.filePath),cn(E,e=>({...e,activeTarget:null,editingCommentKey:n,draftInput:i}));return}Gr&&cn(E,r=>({...r,activeTarget:{filePath:e,changeKey:t,commentKey:n},editingCommentKey:null,draftInput:i}))},[E,rr.comments,Gr,cn]),ti=(0,Y.useCallback)(()=>{or&&Pt.current[E].delete(or),cn(E,e=>({...e,activeTarget:null,editingCommentKey:null,draftInput:``}))},[E,or,cn]),ni=(0,Y.useCallback)(e=>{or&&Pt.current[E].set(or,e)},[E,or]),ri=(0,Y.useCallback)((e,t)=>{let n=rr.comments.has(e.commentKey);if(!Gr&&!n)return;let r=t.trim();if(!r)return;let i=e.change.type===`insert`?null:`oldLineNumber`in e.change?e.change.oldLineNumber:e.change.lineNumber,a=e.change.type===`delete`?null:`newLineNumber`in e.change?e.change.newLineNumber:e.change.lineNumber;cn(E,t=>{let n=new Map(t.comments);return n.set(e.commentKey,{scope:E,filePath:e.filePath,changeKey:e.changeKey,changeType:e.change.type,oldLineNumber:i,newLineNumber:a,hunkHeader:e.hunk.content,lineContent:e.change.content,diffSnippet:ub(e.hunk,e.change),comment:r}),{...t,activeTarget:null,editingCommentKey:null,draftInput:``,comments:n}}),Pt.current[E].delete(e.commentKey)},[E,rr.comments,Gr,cn]),ii=(0,Y.useCallback)(e=>{let t=rr.comments.get(e);if(!t)return;z(t.filePath);let n=Pt.current[E].get(e)??t.comment;cn(E,t=>({...t,activeTarget:null,editingCommentKey:e,draftInput:n}))},[E,rr.comments,cn]),ai=(0,Y.useCallback)(e=>{Pt.current[E].delete(e),cn(E,t=>{let n=new Map(t.comments);return n.delete(e),{...t,activeTarget:t.activeTarget?.commentKey===e?null:t.activeTarget,editingCommentKey:t.editingCommentKey===e?null:t.editingCommentKey,draftInput:t.activeTarget?.commentKey===e||t.editingCommentKey===e?``:t.draftInput,comments:n}})},[E,cn]),oi=(0,Y.useCallback)(async()=>{if(!c||!qr)return;J(!0);let e=yb({drafts:ur,findings:fr,githubComments:mr,uncommittedFiles:Sn,bundleFiles:Cn});try{await c(e),Xr(),Ze(new Set),$e(new Set),Be(e=>e&&{...e,findings:[],is_current_diff:!1}),Q.success(`Fixes submitted.`,{id:`ticket-diff-review-submit-success`}),s()}catch(e){Q.error(OJ(e,`Unable to submit the review right now.`),{id:`ticket-diff-review-submit-error`})}finally{J(!1)}},[ur,Cn,qr,Xr,s,c,mr,fr,Sn]),si=(0,Y.useCallback)(()=>{if(E===`bundle_diff`){yn();return}bn(()=>!0,{allowCache:!1,resetSelection:!Ct.current})},[E,yn,bn]),ci=(0,Y.useMemo)(()=>c?(0,Z.jsx)(WG,{reviewComments:ur,reviewFindings:fr,githubComments:mr,pendingFixCount:gr,canSendReview:qr,isSubmittingReview:et,reviewSubmitDisabledReason:u,onClearPendingFixes:Zr,onSubmitReview:()=>{oi()}}):null,[ur,qr,Zr,oi,et,c,gr,u,mr,fr]),li=e=>{L(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},ui=()=>{M&&L(Rn?new Set:bJ(M.files))},di=async()=>{if(Bn){ye(!0);try{let e=await dn({message:ee.trim(),selected_paths:[...I]});e.ticket&&y?.(e.ticket),_n(e.git_status,{resetSelection:!0}),ne(``),t&&(Mt.current=!0,nq(t)),v&&b?.(v),await vn({preserveContent:!0,gitStatusForCache:e.git_status}),await yn({preserveContent:!0}),(e.git_status.ahead??0)>0?await hn(()=>!0):gn(),Q.success(`Commit created.`,{id:`ticket-git-commit-success`})}catch(e){Q.error(OJ(e,`Unable to create the commit right now.`),{id:`ticket-git-commit-error`})}finally{ye(!1)}}},fi=async()=>{if(Vn){xe(!0);try{ne((await fn({selected_paths:[...I]})).message),St.current?.focus()}catch(e){Q.error(OJ(e,`Unable to generate a commit message right now.`),{id:`ticket-git-commit-message-error`})}finally{xe(!1)}}},pi=async(e=`normal`)=>{if(!(e===`force`?!Gn:!Wn)){Se(e);try{let r=P.map(e=>e.subject.trim()).filter(Boolean),i=await pn({forceWithLease:e===`force`});if(i.ticket&&y?.(i.ticket),_n(i.git_status,{resetSelection:!0}),Gt(i.git_status),gt(r),gn(),t&&(Mt.current=!0,nq(t)),v&&b?.(v),Q.success(e===`force`?i.git_status.ahead===0?pJ(`branchForcePushed`):pJ(`forcePushCompleted`):i.git_status.ahead===0?pJ(`branchPushed`):pJ(`pushCompleted`),{id:`ticket-git-push-success`}),i.git_status.ahead===0)if(S&&t&&n)try{let e=await Dt(t,n);nt(e),ut(t=>t.trim()?t:Dl(e.bundle)),ft(e=>e.trim()?e:zJ(r)),mt(t=>t.trim()?t:e.bundle.pull_request?.base_branch??``)}catch{}else BJ({gitStatus:i.git_status,isProjectTargetRepoRoot:w,isGitHubConnected:g,effectiveDefaultBaseBranch:T})||s()}catch(t){Q.error(OJ(t,pJ(e===`force`?`forcePushFallbackError`:`pushFallbackError`)),{id:`ticket-git-push-error`})}finally{Se(null)}}},mi=async()=>{if(Kn){Te(!0);try{let e=await mn();e.ticket&&y?.(e.ticket),_n(e.git_status,{resetSelection:!0}),F(e.commits),se(null),_e(!1),t&&(Mt.current=!0,nq(t)),v&&b?.(v),await vn({preserveContent:!0,gitStatusForCache:e.git_status}),await yn({preserveContent:!0}),Q.success(`Latest local commit undone.`,{id:`ticket-git-undo-success`})}catch(e){Q.error(OJ(e,`Unable to undo the latest local commit right now.`),{id:`ticket-git-undo-error`})}finally{Te(!1)}}};return(0,Z.jsx)(pu,{onClose:s,overlayClassName:`z-[70] bg-black/30 p-[5vh]`,panelClassName:`flex h-[92vh] w-full max-w-none flex-col overflow-hidden rounded-2xl border border-border bg-card p-6 shadow-2xl`,renderContent:({closeButton:e})=>(0,Z.jsxs)(Z.Fragment,{children:[Fn&&(0,Z.jsx)(`div`,{className:`absolute inset-0 z-10 flex items-center justify-center rounded-2xl bg-black/45 backdrop-blur-sm`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 rounded-xl border border-border bg-card/95 px-4 py-3 text-sm text-foreground shadow-xl`,children:[(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}),(0,Z.jsx)(`span`,{children:`Pushing branch...`})]})}),(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-4 overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-semibold uppercase tracking-widest text-muted-foreground`,children:`Changes`}),Yn?(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`h2`,{className:`max-w-full truncate font-mono text-lg font-semibold text-foreground`,children:Yn}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(U,{variant:(M?.ahead??0)>0?`info`:`outline`,children:qn}),(0,Z.jsx)(U,{variant:(M?.behind??0)>0?`warning`:`outline`,children:Jn}),(0,Z.jsx)(U,{variant:M?.is_dirty?`warning`:`success`,children:M?.is_dirty?`Dirty`:`Clean`})]})]}):(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`h-7 w-56 animate-pulse rounded-md bg-muted/70`,"aria-hidden":`true`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsx)(`div`,{className:`h-6 w-32 animate-pulse rounded-full bg-muted/60`,"aria-hidden":`true`}),(0,Z.jsx)(`div`,{className:`h-6 w-20 animate-pulse rounded-full bg-muted/60`,"aria-hidden":`true`}),(0,Z.jsx)(`div`,{className:`h-6 w-20 animate-pulse rounded-full bg-muted/60`,"aria-hidden":`true`})]})]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-2 text-xs text-muted-foreground`,children:[(yr||Vr)&&(0,Z.jsx)(VJ,{pullRequest:yr,isLoading:Dr,isOpen:st,canCreate:Hr,disabledReason:Wr,isCreating:_t,isSyncing:yt,isGeneratingDescription:X,title:lt,body:dt,baseBranch:pt,onOpenChange:Ur,onTitleChange:ut,onBodyChange:ft,onBaseBranchChange:mt,showGenerateDescription:xr,onGenerateDescription:()=>{$r()},onCreate:()=>{Qr()}}),(0,Z.jsx)(KG,{isCommitsLoading:G,commitsError:oe,unpushedCommits:P,canUndoLatestCommit:Kn,isUndoing:we,aheadCount:M?.ahead??0,onUndoLatestCommit:()=>{mi()}}),Hn&&(Un?(0,Z.jsxs)(`div`,{className:`flex items-stretch`,children:[(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`default`,onClick:()=>{pi()},disabled:!Wn,title:m,className:`gap-2 rounded-r-none`,children:[Fn?(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}):(0,Z.jsx)(Pc,{className:`h-4 w-4`}),pJ(In?`forcePushing`:Fn?`pushing`:`pushBranch`)]}),(0,Z.jsxs)(Ue,{children:[(0,Z.jsx)(Ce,{asChild:!0,children:(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`default`,disabled:!Gn,"aria-label":pJ(`morePushActions`),className:`rounded-l-none border-l border-primary-foreground/20 px-2`,children:(0,Z.jsx)(ke,{className:`h-4 w-4`})})}),(0,Z.jsx)(Me,{align:`end`,className:`w-56`,children:(0,Z.jsx)(ze,{disabled:!Gn,onSelect:()=>{pi(`force`)},children:pJ(`forcePushWithLease`)})})]})]}):(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`default`,onClick:()=>{pi()},disabled:!Wn,title:m,className:`gap-2`,children:[Fn?(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}):(0,Z.jsx)(Pc,{className:`h-4 w-4`}),pJ(Fn?`pushing`:`pushBranch`)]})),e]})]}),(0,Z.jsxs)(`div`,{"data-testid":`ticket-changes-layout`,className:`grid min-h-0 flex-1 gap-4 lg:grid-cols-[18rem_minmax(0,1fr)] xl:grid-cols-[20rem_minmax(0,1fr)]`,children:[(0,Z.jsxs)(`aside`,{className:`flex min-h-0 flex-col`,children:[Sr&&(0,Z.jsxs)(LG,{type:`single`,size:`sm`,variant:`outline`,value:E,onValueChange:e=>{(e===`uncommitted`||e===`bundle_diff`)&&D(e)},className:`mb-3 self-start`,children:[(0,Z.jsxs)(RG,{value:`uncommitted`,className:`gap-2`,children:[(0,Z.jsx)(`span`,{children:`Uncommitted`}),Fr>0&&(0,Z.jsx)(`span`,{className:`rounded-full border border-sky-400/40 bg-sky-400/12 px-1.5 py-0.5 text-[10px] font-semibold leading-none text-sky-100`,children:Fr})]}),(0,Z.jsxs)(RG,{value:`bundle_diff`,className:`gap-2`,children:[(0,Z.jsx)(`span`,{children:`Branch diff`}),Ir>0&&(0,Z.jsx)(`span`,{className:`rounded-full border border-violet-400/40 bg-violet-400/12 px-1.5 py-0.5 text-[10px] font-semibold leading-none text-violet-100`,children:Ir})]})]}),(0,Z.jsx)(HK,{selectionWarning:E===`uncommitted`?zn:null,gitError:E===`uncommitted`?H:ie,sidebarFiles:Nn,commentCountByPath:Pr,commentCountTone:Nr,isGitStatusLoading:E===`bundle_diff`?Tr:Er&&Nn.length===0,selectedPaths:I,selectedDiffPath:R,allFilesSelected:Rn,diffStats:En?.stats??null,title:E===`bundle_diff`?`Branch diff files`:`Changed files`,allChangesDescription:E===`bundle_diff`?`Review the full branch diff against the review base.`:`Review the full workspace diff.`,enableSelection:E===`uncommitted`&&!Er,onToggleSelectAll:ui,onSelectDiffPath:z,onTogglePath:li})]}),(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-col gap-3`,children:[(0,Z.jsx)(LK,{selectedDiffPath:R,sidebarFiles:Nn,diffResponse:En,isDiffLoading:Or,diffError:Cr,allDiffFiles:$n,renderedFiles:Qn,viewType:Ee,onViewTypeChange:De,onRetry:si,activeReviewTarget:ir,editingReviewCommentKey:ar,reviewDraftInstanceKey:sr,reviewDraftInput:cr,reviewComments:lr,reviewFindings:kr,githubComments:jr,selectedReviewFindingIds:Ar,selectedGitHubCommentIds:Mr,canSelectReviewTarget:Gr,canEditActiveReviewDraft:Kr,reviewFindingsError:E===`uncommitted`?Ge:null,gitHubCommentsError:E===`bundle_diff`?Je:null,hasStaleReviewFindings:E===`uncommitted`?_r:!1,onSelectReviewTarget:ei,onToggleReviewFindingSelection:Jr,onToggleGitHubCommentSelection:Yr,onReviewDraftInputChange:ni,onCancelReviewDraft:ti,onEditReviewDraft:ii,onRemoveReviewDraft:ai,onSaveReviewDraft:ri,diffThemeClassName:UK,resolveFilePath:wJ,normalizeDiffPath:SJ,onVisibleFilePathsChange:Mn,emptyStateTitle:Lr,emptyStateDescription:Rr,reviewSummaryControl:ci,headerLayout:`inline-controls`}),E===`uncommitted`&&(0,Z.jsx)(`div`,{className:`mt-auto shrink-0`,children:(0,Z.jsx)(GG,{commitMessage:ee,onCommitMessageChange:ne,commitMessageRef:St,selectedFileCount:Pn,changesDisabledReason:m,canEditCommitMessage:f&&!et,canGenerateCommitMessage:Vn,canCommit:Bn,isGeneratingCommitMessage:be,isCommitting:ve,onGenerateCommitMessage:()=>{fi()},onCommit:()=>{di()}})})]})]})]})]})})},WJ={blocked:{className:`stroke-red-400/80`,markerId:`dependency-arrowhead-blocked`},ready:{className:`stroke-emerald-400/80`,markerId:`dependency-arrowhead-ready`},preview:{className:`stroke-amber-300/80`,markerId:`dependency-arrowhead-preview`}},GJ=e=>qw(e)?`ready`:`blocked`,KJ=180,qJ=560,JJ=88,YJ=12,XJ=18,ZJ=(e,t,n)=>Math.min(Math.max(e,t),n),QJ=(e,t,n)=>n&&n.width>0&&n.height>0?n:Object.values(e).reduce((e,t)=>({width:Math.max(e.width,t.left+t.width),height:Math.max(e.height,t.top+t.height)}),{width:t.x,height:t.y}),$J=(e,t)=>{let n=ZJ(Math.round(e.length*7.2)+24,KJ,qJ),r=Math.max(KJ,t-YJ*2);return Math.min(n,r)},eY=(e,t,n,r,i)=>{let a=n.get(e.blockerTicketId);if(!a)return null;let o=e.hoveredTicketId&&e.hoveredTicketId!==e.blockerTicketId?r[e.hoveredTicketId]:null,s=e.hoveredTicketId&&e.hoveredTicketId!==e.blockerTicketId?n.get(e.hoveredTicketId):null,c=s?`${a.title} is blocking ${s.title}`:`${a.title} is blocking...`,{start:l,end:u}=tT(t,o??{left:e.pointer.x,top:e.pointer.y,width:0,height:0}),d=QJ(r,e.pointer,i),f=o&&s?{x:l.x+(u.x-l.x)*.6,y:l.y+(u.y-l.y)*.6-28}:{x:u.x,y:u.y-28},p=$J(c,d.width);return{text:c,x:o&&s?ZJ(f.x-p/2,YJ,Math.max(YJ,d.width-p-YJ)):(()=>{let e=f.x+XJ,t=f.x-XJ-p;return e+p<=d.width-YJ?e:t>=YJ?t:ZJ(e,YJ,Math.max(YJ,d.width-p-YJ))})(),y:ZJ(f.y,YJ,Math.max(YJ,d.height-JJ-YJ)),width:p}},tY=({blockerRect:e,dependentRect:t,className:n,testId:r,markerEnd:i})=>{let{start:a,end:o}=tT(e,t),{path:s}=nT(a,o);return(0,Z.jsx)(`g`,{"data-testid":r,children:(0,Z.jsx)(`path`,{d:s,className:n,fill:`none`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,markerEnd:i})})},nY=({preview:e,cardRects:t,ticketsById:n,overlaySize:r})=>{if(!e)return null;let i=t[e.blockerTicketId];if(!i)return null;let a=(e.hoveredTicketId&&e.hoveredTicketId!==e.blockerTicketId&&t[e.hoveredTicketId]?t[e.hoveredTicketId]:null)??{left:e.pointer.x,top:e.pointer.y,width:0,height:0},o=eY(e,i,n,t,r);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(tY,{blockerRect:i,dependentRect:a,className:WJ.preview.className,testId:`dependency-preview`,markerEnd:`url(#${WJ.preview.markerId})`}),(e=>o?(0,Z.jsx)(`foreignObject`,{x:o.x,y:o.y,width:o.width,height:JJ,"data-testid":`dependency-preview-label`,children:e}):null)((0,Z.jsx)(`div`,{className:`pointer-events-none flex h-full w-full items-start`,children:(0,Z.jsx)(`div`,{className:`max-w-full rounded-md border border-amber-300/60 bg-stone-950/85 px-3 py-1.5 text-xs font-medium leading-5 text-amber-100 shadow-lg shadow-stone-950/20 whitespace-normal break-words`,children:o?.text})}))]})},rY=({dependencies:e,cardRects:t,preview:n,ticketsById:r,overlaySize:i})=>(0,Z.jsxs)(`svg`,{className:`pointer-events-none absolute inset-0 z-10 h-full w-full overflow-visible`,children:[(0,Z.jsx)(`defs`,{children:Object.values(WJ).map(e=>(0,Z.jsx)(`marker`,{id:e.markerId,markerWidth:`8`,markerHeight:`8`,refX:`7`,refY:`4`,orient:`auto`,markerUnits:`userSpaceOnUse`,children:(0,Z.jsx)(`path`,{d:`M 0 0 L 8 4 L 0 8`,className:e.className,fill:`none`,strokeWidth:`1.6`,strokeLinecap:`round`,strokeLinejoin:`round`})},e.markerId))}),e.map(e=>{let n=r.get(e.blocker_ticket_id),i=r.get(e.dependent_ticket_id),a=t[e.blocker_ticket_id],o=t[e.dependent_ticket_id];if(n?.parked_at||i?.parked_at)return null;let s=WJ[GJ(n)];return!a||!o?null:(0,Z.jsx)(tY,{blockerRect:a,dependentRect:o,className:s.className,testId:`dependency-edge-${e.blocker_ticket_id}-${e.dependent_ticket_id}`,markerEnd:`url(#${s.markerId})`},`${e.blocker_ticket_id}:${e.dependent_ticket_id}`)}),(0,Z.jsx)(nY,{preview:n,cardRects:t,ticketsById:r,overlaySize:i})]}),iY=({onSubmit:e,bundles:t,projectId:n=null,projectBranchState:r=null,tool:i,showModelSelector:a=!1,availableModels:o=[],availableSkills:s=[],initialModel:c=``,initialVariant:l=``,initialSkills:u=[],initialWorktreeBundleId:d=null,onCreateBundle:f,onDeleteBundle:p,onRefreshBundles:m,onClose:h})=>{let{t:g}=X(`common`),{jiraImportState:_,importFromJira:v}=_f(n);return(0,Z.jsx)(pu,{onClose:h,overlayClassName:`bg-black/60`,panelClassName:`h-[92vh] w-[96vw] max-w-6xl overflow-y-auto rounded-2xl border border-border bg-card p-4 shadow-2xl sm:p-5 lg:p-6`,renderContent:({closeButton:y})=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`absolute right-4 top-4 z-10 sm:right-5 sm:top-5 lg:right-6 lg:top-6`,children:y}),(0,Z.jsx)(aP,{heading:g(`newTicketModal.heading`),bundles:t,showModelSelector:a,availableModels:o,availableSkills:s,projectId:n,initialModel:c,initialVariant:l,initialSkills:u,initialWorktreeBundleId:d,projectBranchState:r,jiraImportState:_,onImportFromJira:v,onCancel:h,onCreateBundle:f,onDeleteBundle:p,onRefreshBundles:m,titleInputId:`title`,descriptionInputId:`description`,bundleSelectId:`new-ticket-bundle`,modelSelectId:`new-model`,variantSelectId:`new-variant`,skillsSelectId:`new-skills`,showEmptyBundleOption:!0,planAction:i?{label:g(`newTicketModal.actions.plan`),onClick:async({title:t,description:n,model:r,variant:i,skills:a,worktree_bundle_id:o,external_source:s})=>{await e(t,n,`plan`,r,i,a,{worktree_bundle_id:o??void 0,...s?{external_source:s}:{}}),h()}}:void 0,primaryAction:{label:g(`newTicketModal.actions.createTicket`),variant:`subtle`,onClick:async({title:t,description:n,model:r,variant:i,skills:a,worktree_bundle_id:o,external_source:s})=>{await e(t,n,`create`,r,i,a,{worktree_bundle_id:o??void 0,...s?{external_source:s}:{}}),h()}},secondaryAction:{label:g(`newTicketModal.actions.createAndBuild`),variant:`brand`,showAdvanceIcon:!0,onClick:async({title:t,description:n,model:r,variant:i,skills:a,worktree_bundle_id:o,external_source:s})=>{await e(t,n,`build`,r,i,a,{worktree_bundle_id:o??void 0,...s?{external_source:s}:{}}),h()}}})]})})},aY=e=>{let t=Math.max(0,Date.now()-e),n=Math.floor(t/1e3);return n<60?`${n}s`:`${Math.floor(n/60)}m ${n%60}s`},oY=e=>e.status===`error`?`border-red-500/35 bg-red-500/10`:e.status===`done`?e.boardState===`fading`?`border-emerald-500/25 bg-emerald-500/10 opacity-0 transition-opacity duration-700`:`border-emerald-500/35 bg-emerald-500/10`:`border-violet-500/30 bg-card/60`,sY=({run:e})=>(0,Z.jsxs)(gu,{"data-testid":`planning-run-card-${e.id}`,className:`relative overflow-hidden rounded-xl border shadow-none ${oY(e)}`,children:[e.status===`running`&&(0,Z.jsx)(`div`,{"aria-hidden":`true`,className:`absolute inset-x-0 top-0 h-1 animate-pulse bg-gradient-to-r from-violet-500/0 via-violet-300/80 to-violet-500/0`}),(0,Z.jsxs)(xu,{className:`space-y-3 p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[e.status===`running`?(0,Z.jsx)(aT,{label:`Planning...`}):e.status===`done`?(0,Z.jsx)(aT,{label:`Done`,className:`bg-emerald-500/85 text-emerald-50`}):(0,Z.jsx)(aT,{label:`Planning failed`,className:`bg-red-500/85 text-red-50`}),(0,Z.jsx)(`span`,{className:`text-[11px] uppercase tracking-[0.16em] text-muted-foreground`,children:aY(e.submittedAt)})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`line-clamp-2 text-sm font-medium text-foreground`,children:e.description}),e.status===`done`&&e.summary&&(0,Z.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[`Created `,e.summary.ticketCount,` tickets, `,e.summary.dependencyCount,` dependencies`,e.summary.ticketsWithOpenQuestions>0?`, ${e.summary.ticketsWithOpenQuestions} open question${e.summary.ticketsWithOpenQuestions===1?``:`s`}`:``]}),e.status===`error`&&e.error&&(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-red-200`,children:e.error})]})]})]}),cY={idle:`bg-secondary`,running:`bg-sky-400`,done:`bg-emerald-400`,error:`bg-red-400`},lY=e=>e.some(e=>e.status===`running`)?`running`:e.some(e=>e.status===`error`)?`error`:e.some(e=>e.status===`done`)?`done`:`idle`,uY=e=>{let t=Math.max(0,Date.now()-e),n=Math.floor(t/1e3);return n<60?`${n}s`:`${Math.floor(n/60)}m ${n%60}s`},dY=({status:e})=>{let{t}=X(`common`);return e===`running`?(0,Z.jsx)(aT,{label:t(`planningAgentSidebar.runStatus.planning`),className:`px-2.5 py-0.5 text-[11px]`}):e===`done`?(0,Z.jsx)(U,{className:`bg-emerald-500/85 px-2.5 py-0.5 text-[11px] text-emerald-50`,children:t(`planningAgentSidebar.runStatus.done`)}):(0,Z.jsx)(U,{className:`bg-red-500/85 px-2.5 py-0.5 text-[11px] text-red-50`,children:t(`planningAgentSidebar.runStatus.failed`)})},fY=({heading:e,runs:t})=>{let{t:n}=X(`common`);return t.length===0?null:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2.5`,children:[(0,Z.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-[0.16em] text-muted-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`flex flex-col gap-2.5`,children:t.map(e=>(0,Z.jsx)(gu,{className:`rounded-2xl border-border bg-card/70 shadow-none`,children:(0,Z.jsxs)(xu,{className:`space-y-2 p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsx)(`p`,{className:`line-clamp-2 text-sm font-medium text-foreground`,children:e.description}),(0,Z.jsx)(dY,{status:e.status})]}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:uY(e.submittedAt)}),e.summary&&(0,Z.jsxs)(`span`,{children:[n(`planningAgentSidebar.runSummary.tickets`,{count:e.summary.ticketCount}),`, `,n(`planningAgentSidebar.runSummary.dependencies`,{count:e.summary.dependencyCount}),e.summary.ticketsWithOpenQuestions>0?`, ${n(`planningAgentSidebar.runSummary.openQuestions`,{count:e.summary.ticketsWithOpenQuestions})}`:``]})]}),e.error&&(0,Z.jsx)(`div`,{className:`rounded-xl border border-red-500/30 bg-destructive/15 px-3 py-2 text-xs text-red-200`,children:e.error})]})},e.id))})]})},pY=({projectId:e=null,state:t,bundles:n,showModelSelector:r,availableModels:i,availableSkills:a,onManageBundles:o,onToggle:s,onDescriptionChange:c,onModelChange:l,onVariantChange:u,onSkillsChange:d,onBundleChange:f,onGenerate:p})=>{let{t:m}=X(`common`),h=i.find(e=>e.id===t.composer.model)??null,{jiraImportState:g,importFromJira:_}=_f(t.isOpen?e:null),v=(0,Y.useRef)(null),y=(0,Y.useRef)(t.isOpen),b=(0,Y.useRef)(t.isOpen),x=lY(t.runs),S=t.runs.filter(e=>e.status===`running`),C=t.runs.filter(e=>e.status!==`running`),w=t.composer.description.trim().length>0,T=m(`planningAgentSidebar.actions.planTickets`);(0,Y.useEffect)(()=>{if(t.isOpen&&!y.current&&(b.current=!0),t.isOpen||(b.current=!1),y.current=t.isOpen,!t.isOpen||!b.current)return;let e=window.requestAnimationFrame(()=>{let e=document.activeElement,t=e instanceof HTMLElement&&e.closest(`[data-testid="planning-agent-rail"]`)!==null;if(e instanceof HTMLElement&&e!==document.body&&e!==v.current&&!t){b.current=!1;return}v.current?.focus({preventScroll:!0}),b.current=!1});return()=>{window.cancelAnimationFrame(e)}},[t.isOpen]),(0,Y.useEffect)(()=>{if(!t.isOpen)return;let e=e=>{e.key!==`Escape`||e.defaultPrevented||(e.preventDefault(),s())};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[s,t.isOpen]);let E=(0,Z.jsxs)(q,{type:`button`,"aria-label":t.isOpen?m(`planningAgentSidebar.actions.closeAriaLabel`):m(`planningAgentSidebar.actions.openAriaLabel`),"aria-pressed":t.isOpen,onClick:s,variant:`outline`,className:`relative flex h-14 w-11 flex-col items-center justify-center gap-1 p-0`,children:[(0,Z.jsx)(Kd,{className:`size-5`}),(0,Z.jsx)(hw,{"aria-hidden":`true`,children:`A`}),(0,Z.jsx)(`span`,{className:`absolute top-1 right-1 h-2.5 w-2.5 rounded-full ring-2 ring-card ${cY[x]}`})]});return(0,Z.jsxs)(`aside`,{"aria-label":m(`planningAgentSidebar.ariaLabel`),className:`relative z-20 h-full w-16 shrink-0 overflow-visible border-r border-border bg-background`,children:[(0,Z.jsx)(`div`,{"data-testid":`planning-agent-rail`,className:`relative z-40 flex h-full w-16 shrink-0 flex-col items-center border-r border-border bg-background py-4`,children:t.isOpen?E:(0,Z.jsx)(xc,{content:m(`planningAgentSidebar.tooltip`),children:E})}),(0,Z.jsx)(`div`,{"data-testid":`planning-agent-drawer`,"aria-hidden":!t.isOpen,inert:!t.isOpen||void 0,className:K(`absolute inset-y-0 left-16 z-30 w-[min(36rem,calc(100vw-5rem))] overflow-hidden transition-transform duration-200 ease-out motion-reduce:transition-none`,t.isOpen?`pointer-events-auto translate-x-0`:`pointer-events-none -translate-x-full`),children:(0,Z.jsxs)(`div`,{className:`flex h-full w-[min(36rem,calc(100vw-5rem))] flex-col border-r border-border bg-background`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-start justify-between gap-4 border-b border-border px-6 py-5`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold text-foreground`,children:m(`planningAgentSidebar.title`)}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs leading-5 text-muted-foreground`,children:m(`planningAgentSidebar.description`)})]}),(0,Z.jsx)(q,{type:`button`,"aria-label":m(`planningAgentSidebar.actions.closePanelAriaLabel`),onClick:s,variant:`ghost`,size:`icon-sm`,className:`shrink-0 text-muted-foreground hover:text-foreground`,children:(0,Z.jsx)(Ve,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{"data-testid":`planning-agent-scroll-body`,className:`min-h-0 flex-1 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`space-y-5 px-6 py-5`,children:[(0,Z.jsx)(tP,{jiraImportState:g,onImportFromJira:_,onImported:e=>{c(e.description)},inputId:`planning-agent-jira-import`}),(0,Z.jsx)(Cu,{label:m(`planningAgentSidebar.descriptionLabel`),htmlFor:`planning-agent-description`,className:`gap-2`,children:(0,Z.jsx)(`div`,{className:`relative`,children:(0,Z.jsx)($p,{ref:v,projectId:e,suggestionAnchor:`caret`,id:`planning-agent-description`,"aria-label":m(`planningAgentSidebar.descriptionAriaLabel`),value:t.composer.description,onValueChange:c,rows:14,className:`min-h-[18rem] resize-y text-sm leading-6`,placeholder:m(`planningAgentSidebar.descriptionPlaceholder`)})})}),(0,Z.jsxs)(`div`,{className:`flex items-end gap-3`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Z.jsx)(nP,{bundles:n,value:t.composer.worktreeBundleId,onChange:f,selectId:`planning-agent-bundle`,emptyLabel:m(`planningAgentSidebar.autoCreateBundle`),hideProjectRootBundles:!0,label:``})}),o&&(0,Z.jsx)(q,{type:`button`,onClick:o,variant:`outline`,size:`sm`,className:`shrink-0 whitespace-nowrap border-sky-500/30 bg-sky-500/10 text-sky-200 hover:border-sky-400 hover:bg-sky-500/20 hover:text-sky-100`,children:m(`planningAgentSidebar.actions.manageBundles`)})]}),(0,Z.jsx)(`div`,{className:`space-y-3`,children:(0,Z.jsx)(QN,{model:t.composer.model,variant:t.composer.variant,skills:t.composer.skills,showModelSelector:r,showSkillsSelector:r,availableModels:i,availableSkills:a,selectedModel:h,onModelChange:l,onVariantChange:u,onSkillsChange:d,modelSelectId:`planning-agent-model`,variantSelectId:`planning-agent-variant`,skillsSelectId:`planning-agent-skills`,layout:`stacked`})}),(0,Z.jsx)(`div`,{"data-testid":`planning-agent-runs`,className:`border-t border-border/80 px-0 pt-5`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Z.jsx)(fY,{heading:m(`planningAgentSidebar.activeRuns`),runs:S}),(0,Z.jsx)(fY,{heading:m(`planningAgentSidebar.recentRuns`),runs:C})]})})]})}),(0,Z.jsx)(`div`,{className:`shrink-0 border-t border-border px-6 py-4`,children:(0,Z.jsx)(q,{type:`button`,onClick:p,disabled:!w,className:`w-full`,children:T})})]})})]})},mY=({className:e=``})=>{let{setNodeRef:t,isOver:n}=nw({id:`trash`});return(0,Z.jsxs)(`div`,{ref:t,"data-testid":`delete-drop-zone`,className:`${e} flex min-w-[13rem] select-none items-center justify-between gap-4 rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all duration-150 ${n?`scale-[1.02] border-red-400/70 bg-destructive/35 text-red-100 shadow-lg shadow-red-950/30`:`border-red-500/30 bg-background/82 text-red-200/85`}`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(U,{variant:`destructive`,className:`text-[11px] uppercase tracking-[0.28em]`,children:`Delete`}),(0,Z.jsx)(`div`,{className:`mt-1 text-sm font-medium`,children:n?`Release to delete`:`Drop here to delete`})]}),(0,Z.jsx)(`div`,{className:`rounded-xl border p-2 transition-colors ${n?`border-red-400/60 bg-red-500/20`:`border-red-500/20 bg-background/60`}`,children:(0,Z.jsx)(wu,{className:`h-5 w-5 transition-colors ${n?`text-red-100`:`text-red-300/70`}`})})]})},hY=(e,t)=>H(tt(`/ticket-dependencies`,e),{signal:t}),gY=(e,t)=>H(tt(`/ticket-dependencies`,e),{method:`POST`,body:t,fallbackErrorMessage:`Unable to create the dependency right now.`}),_Y=(e,t,n)=>l(tt(`/ticket-dependencies/${t}/${n}`,e),{method:`DELETE`,fallbackErrorMessage:`Unable to remove the dependency right now.`}),vY=(e,t)=>{let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n){let n=e[r],i=t[r];if(!n||!i||n.left!==i.left||n.top!==i.top||n.width!==i.width||n.height!==i.height)return!1}return!0},yY=(e,t)=>e===t?!0:!e||!t?!1:e.projectId===t.projectId&&e.blockerTicketId===t.blockerTicketId&&e.hoveredTicketId===t.hoveredTicketId&&e.pointer.x===t.pointer.x&&e.pointer.y===t.pointer.y,bY=({activeProjectId:e,tickets:t,dependencies:n,setDependencies:r,activeTicket:i,activeOverlayNode:a,dragOffset:o})=>{let[s,c]=(0,Y.useState)({}),[l,u]=(0,Y.useState)({width:0,height:0}),[d,f]=(0,Y.useState)(null),[p,m]=(0,Y.useState)(null),h=(0,Y.useRef)(null),g=(0,Y.useRef)(null),_=(0,Y.useRef)(null),v=(0,Y.useRef)(new Map),y=(0,Y.useRef)({}),b=(0,Y.useRef)(null),x=(0,Y.useRef)(null),S=(0,Y.useRef)(null),C=(0,Y.useRef)(null),w=(0,Y.useRef)(null),T=(0,Y.useRef)(null),E=(0,Y.useMemo)(()=>new Map(t.map(e=>[e.id,e])),[t]);(0,Y.useEffect)(()=>{C.current=p},[p]),(0,Y.useLayoutEffect)(()=>{if(!i||!a||!g.current)return;let e=window.requestAnimationFrame(()=>{let e=g.current?.getBoundingClientRect(),t=a.getBoundingClientRect();e&&f({ticketId:i.id,rect:{left:t.left-e.left,top:t.top-e.top,width:t.width,height:t.height}})});return()=>{window.cancelAnimationFrame(e)}},[a,i,o.x,o.y]);let D=(0,Y.useCallback)(()=>{b.current===null&&(b.current=window.requestAnimationFrame(()=>{b.current=null;let e=g.current;if(!e){_.current=null,y.current={},c({}),u({width:0,height:0});return}let t=e.getBoundingClientRect(),n={};_.current={left:t.left,top:t.top},u(e=>e.width===t.width&&e.height===t.height?e:{width:t.width,height:t.height});for(let[e,r]of v.current){let i=r.getBoundingClientRect();n[e]={left:i.left-t.left,top:i.top-t.top,width:i.width,height:i.height}}y.current=n,c(e=>vY(e,n)?e:n)}))},[]);(0,Y.useEffect)(()=>{let e=h.current;if(!e)return;let t=()=>{D()};return e.addEventListener(`scroll`,t,!0),window.addEventListener(`resize`,t),()=>{e.removeEventListener(`scroll`,t,!0),window.removeEventListener(`resize`,t)}},[D]),(0,Y.useEffect)(()=>{if(typeof ResizeObserver!=`function`)return;let e=new ResizeObserver(()=>{D()});x.current=e;for(let t of v.current.values())e.observe(t);return()=>{e.disconnect(),x.current===e&&(x.current=null)}},[D]),(0,Y.useEffect)(()=>{let e=h.current,t=g.current;if(!e&&!t)return;let n=new ResizeObserver(()=>{D()});return e&&n.observe(e),t&&t!==e&&n.observe(t),()=>{n.disconnect()}},[D]),(0,Y.useEffect)(()=>(D(),()=>{b.current!==null&&(window.cancelAnimationFrame(b.current),b.current=null)}),[n,D,t]);let O=(0,Y.useCallback)((e,t)=>{let n=v.current.get(e);if(t){if(n===t)return;v.current.set(e,t),x.current?.observe(t)}else{if(!n)return;v.current.delete(e),x.current?.unobserve(n)}D()},[D]),k=(0,Y.useCallback)(e=>{yY(C.current,e)||(C.current=e,m(e))},[]),A=(0,Y.useCallback)(()=>{w.current!==null&&(window.cancelAnimationFrame(w.current),w.current=null),T.current=null},[]),j=(0,Y.useCallback)(e=>{T.current=e,w.current===null&&(w.current=window.requestAnimationFrame(()=>{w.current=null;let e=T.current;T.current=null,k(e)}))},[k]),M=(0,Y.useCallback)((e,t)=>{let n=_.current;if(!n&&g.current){let e=g.current.getBoundingClientRect();n={left:e.left,top:e.top},_.current=n}return n?{x:e-n.left,y:t-n.top}:{x:e,y:t}},[]),N=(0,Y.useCallback)((e,t,n)=>{for(let[r,i]of Object.entries(y.current))if(r!==n&&e>=i.left&&e<=i.left+i.width&&t>=i.top&&t<=i.top+i.height)return r;return null},[]),P=(0,Y.useCallback)(async t=>{if(e)try{await _Y(e,t.blocker_ticket_id,t.dependent_ticket_id),r(e=>Uw(e,t.blocker_ticket_id,t.dependent_ticket_id))}catch(e){Q.error(e instanceof I?e.message:`Unable to remove the dependency right now.`,{id:`board-dependency-error`})}},[e,r]),F=(0,Y.useCallback)((t,i)=>{if(!e)return;i.preventDefault(),S.current?.();let a=(n,r,i=!1)=>{let a=M(n,r),o={projectId:e,blockerTicketId:t,hoveredTicketId:N(a.x,a.y,t),pointer:a};if(i){A(),k(o);return}j(o)};a(i.clientX,i.clientY,!0);let o=e=>{a(e.clientX,e.clientY)},s=async i=>{let a=M(i.clientX,i.clientY),o=N(a.x,a.y,t),s=o?Gw(n,t,o):null;if(S.current?.(),S.current=null,k(null),!(!o||!s)){if(!s.valid){Q.error(Kw(s.reason),{id:`board-dependency-error`});return}try{let n=await gY(e,{blocker_ticket_id:t,dependent_ticket_id:o});r(e=>Hw(e,n))}catch(e){Q.error(e instanceof I?e.message:`Unable to create the dependency right now.`,{id:`board-dependency-error`})}}};S.current=()=>{window.removeEventListener(`pointermove`,o),window.removeEventListener(`pointerup`,s),A()},window.addEventListener(`pointermove`,o),window.addEventListener(`pointerup`,s,{once:!0})},[e,A,n,N,M,j,r,k]);(0,Y.useEffect)(()=>{S.current?.(),S.current=null,A(),C.current=null},[e,A]),(0,Y.useEffect)(()=>()=>{S.current?.(),w.current!==null&&(window.cancelAnimationFrame(w.current),w.current=null)},[]);let L=(0,Y.useMemo)(()=>{let r=p?.blockerTicketId;if(!r||p.projectId!==e||!E.has(r))return null;let i=new Map;for(let e of t){if(e.id===r){i.set(e.id,`source`);continue}let t=Gw(n,r,e.id);i.set(e.id,t.valid?`valid`:`idle`)}return i},[e,n,p,E,t]),R=(0,Y.useCallback)(e=>{if(!L||!p)return`idle`;let t=L.get(e)??`idle`;return e===p.hoveredTicketId&&t===`idle`?`invalid`:t},[L,p]),z=(0,Y.useMemo)(()=>!p||p.projectId!==e||!E.has(p.blockerTicketId)?null:{blockerTicketId:p.blockerTicketId,hoveredTicketId:p.hoveredTicketId,pointer:p.pointer},[e,p,E]);return{boardViewportRef:h,boardContentRef:g,registerTicketNode:O,measuredCardRects:(0,Y.useMemo)(()=>{if(!i)return s;let e=s[i.id];return e?d?.ticketId===i.id?{...s,[i.id]:d.rect}:{...s,[i.id]:{...e,left:e.left+o.x,top:e.top+o.y}}:s},[d,i,s,o.x,o.y]),overlayPreview:z,overlaySize:l,getDependencyTargetState:R,handleDependencyStart:F,handleDeleteDependency:P}},xY=e=>{if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e,n=typeof t.id==`string`?t.id:``,r=typeof t.name==`string`?t.name:``,i=typeof t.command==`string`?t.command:``,a=typeof t.cwd==`string`?t.cwd:``,o=t.runner===`vitest`||t.runner===`jest`||t.runner===`unknown`?t.runner:`auto`;return n.trim()===``||r.trim()===``&&i.trim()===``&&a.trim()===``?[]:[{id:n,name:r,command:i,cwd:a,runner:o}]}):[]}catch{return[]}},SY=`[data-terminal-pane="true"]`,CY=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName.toLowerCase();return t===`input`||t===`textarea`||e.isContentEditable},wY=e=>e instanceof HTMLElement?e.closest(SY)!==null:!1,TY=e=>CY(e)||wY(e),EY=(e,t={})=>{let{isBlocked:n}=t;(0,Y.useEffect)(()=>{let t=t=>{if(t.defaultPrevented||t.repeat)return;let r=e.find(e=>!e.disabled&&e.key.toLowerCase()===t.key.toLowerCase()&&(e.ctrlKey??!1)===t.ctrlKey&&(e.altKey??!1)===t.altKey&&(e.metaKey??!1)===t.metaKey&&(e.shiftKey===void 0||e.shiftKey===t.shiftKey));r&&(n?.(document.activeElement)||(t.preventDefault(),r.onKeyDown()))};return window.addEventListener(`keydown`,t),()=>{window.removeEventListener(`keydown`,t)}},[e,n])},DY=e=>({...e,messages:void 0,agent_log:void 0,streaming_response:void 0}),OY=(e,t)=>e?e.state!==t.state||e.parked_at!==t.parked_at||e.worktree_bundle_id!==t.worktree_bundle_id:!0,kY=(e,t)=>{if(!e)return t;let n=t.worktree_bundle_id!==null&&e.worktree_bundle_id===t.worktree_bundle_id,r=t.bundle??(n&&e.bundle?.id===t.worktree_bundle_id?e.bundle:null),i=t.bundle_execution_position??(n?e.bundle_execution_position??null:null);return{...e,...t,bundle:r,bundle_execution_position:i}},AY=(e,t)=>{let n=e=>Ow(t)?Ow(e):e.state===t.state&&!Ow(e),r=e.findIndex(e=>n(e));if(r===-1)return[...e,t];let i=[...e];return i.splice(r,0,t),i},jY=(e,t)=>{let n=e.find(e=>e.id===t.id);return[n&&n.pull_request!==void 0&&t.pull_request===void 0?{...n,...t,pull_request:n.pull_request}:t,...e.filter(e=>e.id!==t.id)]},MY=(e,t)=>{let n=e.find(e=>e.id===t.id);if(!n)return[...e,t];let r=kY(n,t);return e.map(e=>e.id===t.id?r:e)},NY=(e,t)=>{let n=kY(e.find(e=>e.id===t.id),t);return AY(FY(e,t.id),n)},PY=(e,t)=>{if(e.length===0)return[...t];let n=[...e];for(let e of t)n=OY(n.find(t=>t.id===e.id),e)?NY(n,e):MY(n,e);let r=new Set(t.map(e=>e.id));return n.filter(e=>r.has(e.id))},FY=(e,t)=>e.filter(e=>e.id!==t),IY=(e,t,n,r={},i={})=>{let a=e.findIndex(e=>e.id===t);if(a===-1)return e;let o={...e[a],state:n,...r},s=FY(e,t);if(i.preferredIndex!==void 0){let e=Math.max(0,Math.min(i.preferredIndex,s.length));return s.splice(e,0,o),s}return AY(s,o)},LY=async(e,t)=>{`Notification`in window&&Notification.permission!==`denied`&&(Notification.permission===`default`&&await Notification.requestPermission(),Notification.permission===`granted`&&new Notification(e,{body:t}))},RY=(0,Y.createContext)(UW),zY=()=>(0,Y.useContext)(RY),BY=(0,Y.createContext)(null),VY=15*1e3,HY=1e3,UY=async e=>LY(`Ticket done`,e),WY=e=>DY(e),GY=(e,t)=>t===`running`&&e.agent_status===`done`?`Finished ${e.state} for "${e.title}"`:t===`running`&&e.agent_status===`error`?`Failed ${e.state} for "${e.title}"`:t!==`running`&&e.agent_status===`running`?`Running ${e.state} for "${e.title}"`:null,KY=({activeProjectId:e,refreshKey:t=0,onLoadedProjectIdChange:n,onProjectUsageChange:r,onBundlesChange:i,onBundlesLoadingChange:a,children:o})=>{let s=zY(),[c,l]=(0,Y.useState)([]),[u,d]=(0,Y.useState)([]),[f,p]=(0,Y.useState)([]),[m,h]=(0,Y.useState)(null),[g,_]=(0,Y.useState)(null),[v,y]=(0,Y.useState)(null),[b,x]=(0,Y.useState)(null),[S,C]=(0,Y.useState)(null),w=(0,Y.useRef)(0),T=(0,Y.useRef)(0),E=(0,Y.useRef)(new Map),D=(0,Y.useRef)(new Map),O=(0,Y.useRef)(e),k=(0,Y.useRef)(new Map),A=(0,Y.useRef)(new Map),j=(0,Y.useRef)(new Map),M=(0,Y.useCallback)((e,t)=>{let n=A.current.get(t.id);return!n||!e||t.state===n?t:e},[]),N=(0,Y.useCallback)((e,t)=>{if(e.length===0)return;let n=new Map(A.current);for(let r of e)n.set(r,t);A.current=n},[]),P=(0,Y.useCallback)(e=>{if(e.length===0||A.current.size===0)return;let t=new Map(A.current);for(let n of e)t.delete(n);A.current=t},[]),F=(0,Y.useCallback)((e,t)=>{if(e.length===0)return;let n=new Map(j.current);for(let r of e)n.set(r,t);j.current=n},[]),I=(0,Y.useCallback)(e=>{if(e.length===0||j.current.size===0)return;let t=new Map(j.current);for(let n of e)t.delete(n);j.current=t},[]),L=(0,Y.useCallback)((e,t)=>{if(k.current.has(t.id))return null;let n=M(e,t);return j.current.has(t.id)?{...n,parked_at:j.current.get(t.id)??null}:n},[M]),R=(0,Y.useCallback)((e,t)=>{if(k.current.size===0&&A.current.size===0&&j.current.size===0)return t;let n=new Map(e.map(e=>[e.id,e]));return t.flatMap(e=>{let t=L(n.get(e.id),e);return t?[t]:[]})},[L]),ee=(0,Y.useCallback)(async(e,t)=>{let n=await Kt(e,t,{detail:`board`});return Array.isArray(n)?(!t?.aborted&&O.current===e&&l(e=>PY(e,R(e,n).map(WY))),n):null},[R]),te=(0,Y.useCallback)(async(e,t)=>{await ee(e,t)},[ee]),ne=(0,Y.useCallback)(async(e,t)=>{let n=++T.current,r=await qt(e,t);if(!Array.isArray(r)||t?.aborted||O.current!==e||T.current!==n)return;let i=new Map(r.map(e=>[e.id,e]));l(e=>e.map(e=>{let t=i.get(e.id);return t?{...e,diff_stats:t.diff_stats??null,is_stale:t.is_stale}:e}))},[]),re=(0,Y.useCallback)(e=>e.some(e=>e.is_stale===void 0),[]),B=(0,Y.useCallback)(async e=>{let t=O.current;if(!t)return null;try{let n=await Jt(e,t);if(O.current!==t)return null;let r=D.current.get(n.id),i=L(r,n);if(!i)return null;let a=WY(i),o=OY(r,a);return l(e=>o?NY(e,a):MY(e,a)),n}catch{return null}},[L]),ie=(0,Y.useCallback)(async t=>{if(!e){p([]);return}p(await Tt(e,t))},[e]),V=(0,Y.useMemo)(()=>new Map(c.map(e=>[e.id,e])),[c]),H=(0,Y.useMemo)(()=>{let e=c.filter(e=>e.agent_status===`running`),t=new Set(e.map(e=>e.worktree_bundle_id).filter(e=>typeof e==`string`&&e.trim().length>0));return{total_running:e.length,running_plan_count:e.filter(e=>e.state===`plan`).length,running_build_count:e.filter(e=>e.state===`build`).length,running_review_count:e.filter(e=>e.state===`review`).length,active_bundle_count:t.size,latest_message:S}},[S,c]);(0,Y.useEffect)(()=>{D.current=V},[V]),(0,Y.useEffect)(()=>{O.current=e,k.current.clear(),A.current.clear(),j.current.clear(),C(null),h(null),E.current.clear()},[e]),(0,Y.useEffect)(()=>{n?.(v?null:g)},[g,v,n]),(0,Y.useEffect)(()=>{if(i){if(!e){i(null,[]);return}if(g!==e){i(e,[]);return}i(e,f)}},[e,f,g,i]),(0,Y.useEffect)(()=>{if(a){if(!e){a(null,!1);return}a(e,b===e)}},[e,b,a]),(0,Y.useEffect)(()=>{let t=new AbortController,n=++w.current,r=null,i=async()=>{try{if(!e){l([]),d([]),p([]),_(null),y(null);return}l([]),d([]),p([]),_(null),y(e),x(e);let[n,i,a]=await Promise.allSettled([ee(e,t.signal),hY(e,t.signal),Tt(e,t.signal)]);if(t.signal.aborted)return;n.status!==`fulfilled`&&!z(n.reason)&&l([]),i.status===`fulfilled`?d(i.value):z(i.reason)||d([]),a.status===`fulfilled`?p(a.value):z(a.reason)||p([]),_(n.status===`fulfilled`&&i.status===`fulfilled`&&a.status===`fulfilled`?e:null),n.status===`fulfilled`&&n.value!==null&&re(n.value)&&(r=window.setTimeout(()=>{t.signal.aborted||ne(e,t.signal)},HY))}finally{!t.signal.aborted&&w.current===n&&(y(null),x(null))}},a=t=>{t.project_id===e&&(h(t),!k.current.has(t.id)&&(t.bundle&&p(e=>jY(e,t.bundle)),l(e=>NY(e,WY(t)))))},o=t=>{if(t.project_id===e&&h(t),l(n=>{if(t.project_id!==e)return FY(n,t.id);let r=n.find(e=>e.id===t.id),i=L(r,t);if(!i)return n;let a=WY(i);return OY(r,a)?NY(n,a):MY(n,a)}),t.project_id!==e){d(e=>Vw(e,t.id));return}t.bundle&&p(e=>jY(e,t.bundle))},c=({id:e})=>{k.current.delete(e),j.current.delete(e),A.current.delete(e),l(t=>FY(t,e)),d(t=>Vw(t,e))},u=e=>{if(!e)return;let t=D.current.get(e.blocker_ticket_id),n=D.current.get(e.dependent_ticket_id);!t||!n||t.project_id!==O.current||n.project_id!==O.current||d(t=>Hw(t,e))},f=e=>{d(t=>Uw(t,e.blocker_ticket_id,e.dependent_ticket_id))};return i(),s.on(`ticket:created`,a),s.on(`ticket:updated`,o),s.on(`ticket:deleted`,c),s.on(`ticket-dependency:created`,u),s.on(`ticket-dependency:deleted`,f),()=>{t.abort(),r!==null&&window.clearTimeout(r),s.off(`ticket:created`,a),s.off(`ticket:updated`,o),s.off(`ticket:deleted`,c),s.off(`ticket-dependency:created`,u),s.off(`ticket-dependency:deleted`,f)}},[e,ne,t,re,ee,L,s]),(0,Y.useEffect)(()=>{if(!e)return;let t=new AbortController,n=()=>{document.visibilityState===`visible`&&Promise.allSettled([ee(e,t.signal),ie(t.signal)]).then(n=>{n[0]?.status===`fulfilled`&&n[0].value!==null&&re(n[0].value)&&ne(e,t.signal)}).catch(()=>{})},r=window.setInterval(n,VY),i=aq(n);return()=>{t.abort(),window.clearInterval(r),i()}},[e,ie,ne,re,ee]),(0,Y.useEffect)(()=>{if(!e||!r||g!==e)return;let t=c.filter(e=>{let t=e.bundle?.branch??e.branch;return typeof t==`string`&&t.trim()!==``}).length;r({projectId:e,ticketCount:c.length,worktreeCount:t,repoPathLocked:c.length>0||t>0||f.length>0})},[e,f.length,g,r,c]),(0,Y.useEffect)(()=>{for(let e of c){let t=E.current.get(e.id),n=GY(e,t);n&&C(n),t!==void 0&&t===`running`&&e.agent_status===`done`&&(e.state===`plan`||e.state===`build`||e.state===`review`)&&UY(e.title),E.current.set(e.id,e.agent_status)}},[c]);let ae=(0,Y.useCallback)(()=>{h(null)},[]),oe=(0,Y.useMemo)(()=>({tickets:c,setTickets:l,dependencies:u,setDependencies:d,bundles:f,setBundles:p,latestDetailedTicketUpdate:m,clearLatestDetailedTicketUpdate:ae,loadedProjectId:g,loadingProjectId:v,activeProjectIdRef:O,pendingDeletedTicketsRef:k,pendingOptimisticMovesRef:A,pendingParkedTicketsRef:j,refreshTickets:te,requestSingleTicketRefresh:B,refreshBundles:ie,resolvePendingTicket:L,resolvePendingTickets:R,markPendingOptimisticMoves:N,clearPendingOptimisticMoves:P,markPendingParkedTickets:F,clearPendingParkedTickets:I,liveActivity:H}),[f,ae,P,I,u,H,g,m,v,N,F,ie,te,B,L,R,c]);return(0,Z.jsx)(BY.Provider,{value:oe,children:o})},qY=()=>{let e=(0,Y.useContext)(BY);if(!e)throw Error(`useProjectWorkspace must be used inside ProjectWorkspaceProvider`);return e},JY=(0,Y.lazy)(()=>tG(()=>import(`./TestsDialog-ditcW5bX.js`).then(e=>({default:e.TestsDialog})),__vite__mapDeps([0,1,2]))),YY=`archon.last-model-selection`,XY=`archon.last-variant-selection`,ZY=`archon.last-skills-selection`,QY=()=>{try{let e=window.localStorage.getItem(ZY),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}},$Y=e=>[e.title,e.description,e.bundle?.name??``,e.bundle?.branch??``,e.branch??``].map(e=>e.toLowerCase()),eX=(e,t)=>{let n=e.bundle_execution_position??2**53-1,r=t.bundle_execution_position??2**53-1;if(n!==r)return n-r;if(e.created_at!==t.created_at)return e.created_at.localeCompare(t.created_at);let i=e.title.localeCompare(t.title,void 0,{sensitivity:`base`});return i===0?e.id.localeCompare(t.id):i},tX=(e,t)=>t?{...e,...t,messages:t.messages===void 0?e.messages:t.messages,agent_log:t.agent_log===void 0?e.agent_log:t.agent_log,streaming_response:t.streaming_response===void 0?e.streaming_response:t.streaming_response}:e,nX=(e,t)=>{let n=e.toLowerCase().trim().split(/\s+/).filter(Boolean);if(n.length===0)return!0;let r=$Y(t);return n.every(e=>r.some(t=>t.includes(e)))},rX=[`plan`,`build`,`review`],iX=`done`,aX=()=>({build:!1,stopBuild:!1,resumeBuild:!1,review:!1,undoReview:!1,run:!1,stop:!1,followUp:!1,bundleRefresh:!1}),oX=({bundleId:e,activeRunContextKey:t,isProjectRootRunActive:n})=>n?!0:t!==null&&t!==e,sX=(e,t)=>{if(!e)return null;let n=t.find(t=>t.id===e.ticket_id);return n?Ew(n):e.ticket_id},cX=()=>({description:``,model:window.localStorage.getItem(YY)??``,variant:window.localStorage.getItem(XY)??``,skills:QY(),worktreeBundleId:``}),lX=()=>({isOpen:!1,composer:cX(),runs:[]}),uX=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`planning-run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,dX=e=>({ticketCount:e.tickets.length,dependencyCount:e.dependencies.length,ticketsWithOpenQuestions:e.tickets.filter(e=>(e.planning_context?.open_questions.length??0)>0).length,ticketTitles:e.tickets.map(e=>e.title),ticketIds:e.tickets.map(e=>e.id)}),fX=(e,t,n)=>e.map(e=>e.id===t?n(e):e),pX=(e,t,n)=>{e?window.localStorage.setItem(YY,e):window.localStorage.removeItem(YY),t?window.localStorage.setItem(XY,t):window.localStorage.removeItem(XY),n.length>0?window.localStorage.setItem(ZY,JSON.stringify(n)):window.localStorage.removeItem(ZY)},mX=(e,t={})=>xl(e,t),hX=()=>({model:window.localStorage.getItem(YY)??``,variant:window.localStorage.getItem(XY)??``,skills:QY()}),gX=(e,t)=>{let n=FY(e,t.ticket.id),r=Math.max(0,Math.min(t.index,n.length));return n.splice(r,0,t.ticket),n},_X=e=>e.tickets.length>0&&e.tickets.every(e=>Fw(e,`trash`)),vX=e=>e.tickets.length>0&&e.tickets.every(e=>Fw(e,iX)),yX=e=>e.column===iX&&e.tickets.length>0&&e.tickets.every(e=>e.state!==`plan`),bX=(e,t,n,r)=>n||t!==null&&t!==Ew(e)?r:Yw(e),xX=(e,t)=>t===`build`?{agent_status:null,agent_log:null,streaming_response:null,build_completed_at:null,planning_context:e.planning_context?{...e.planning_context,open_questions:[]}:null}:t===`review`?{agent_status:null,agent_log:null,streaming_response:null}:{},SX=(e,t)=>e===`plan`&&t===`build`?`build`:e===`build`&&t===`review`?`review`:e===`review`&&t===`build`?`undoReview`:null,CX=(e,t,n)=>t===`review`&&n===`build`?{}:xX(e,n),wX=({activeProjectId:e,activeProject:t=null,activeProjectBranchState:n=null,activeRun:r,activeTool:i,onPreviewReviewCapabilityChange:a,onRunStopped:o,onRunStatusChange:s,refreshKey:c=0})=>{let{t:l}=X(`common`),u=Yx(Jx(ZS,{activationConstraint:{distance:5}})),{tickets:d,setTickets:f,dependencies:p,setDependencies:m,bundles:h,setBundles:g,latestDetailedTicketUpdate:_,clearLatestDetailedTicketUpdate:v,loadedProjectId:y,loadingProjectId:b,activeProjectIdRef:x,pendingDeletedTicketsRef:S,requestSingleTicketRefresh:C,refreshBundles:w,resolvePendingTicket:T,markPendingOptimisticMoves:E,clearPendingOptimisticMoves:D,markPendingParkedTickets:O,clearPendingParkedTickets:k}=qY(),[A,j]=(0,Y.useState)(null),[M,N]=(0,Y.useState)(null),[P,F]=(0,Y.useState)(null),[L,R]=(0,Y.useState)({x:0,y:0}),[ee,te]=(0,Y.useState)(null),[ne,re]=(0,Y.useState)(!1),[B,ie]=(0,Y.useState)([]),[V,H]=(0,Y.useState)([]),[ae,oe]=(0,Y.useState)(!1),[se,ce]=(0,Y.useState)({}),[le,ue]=(0,Y.useState)(!1),[de,U]=(0,Y.useState)(!1),[fe,pe]=(0,Y.useState)(null),[me,W]=(0,Y.useState)(null),[he,G]=(0,Y.useState)(null),[ge,_e]=(0,Y.useState)(null),[ve,ye]=(0,Y.useState)(null),[be,xe]=(0,Y.useState)(null),[Se,Ce]=(0,Y.useState)(null),[we,Te]=(0,Y.useState)(null),[Ee,De]=(0,Y.useState)(null),[Oe,ke]=(0,Y.useState)(null),[Ae,je]=(0,Y.useState)(!1),[Me,Ne]=(0,Y.useState)(aX()),[Pe,Fe]=(0,Y.useState)(0),[Ie,Le]=(0,Y.useState)(``),[Re,ze]=(0,Y.useState)(!1),Be=i===`opencode`||he?.tool===`opencode`||!!be?.tickets.some(e=>e.tool===`opencode`),He=i===`opencode`&&B.length>0,Ue=he?.tool===`opencode`&&B.length>0,We=!!be?.tickets.some(e=>e.tool===`opencode`)&&B.length>0,Ke=(0,Y.useRef)(e),qe=(0,Y.useRef)(null),Je=(0,Y.useRef)(null),[Ye,Xe]=(0,Y.useState)(null),Ze=d.find(e=>e.is_running)??null,Qe=Ze?Ew(Ze):null,$e=r?.context_key??null,et=r?.kind===`ticket`?sX(r,d)??Qe:Qe,J=r?.kind===`project`,tt=et??Ye,nt=(0,Y.useCallback)(e=>oX({bundleId:e,activeRunContextKey:tt,isProjectRootRunActive:J}),[tt,J]),rt=A!==null&&Fw(A,`trash`)||M!==null&&_X(M),it=b===e,at=(0,Y.useMemo)(()=>xY(t?.test_commands??null),[t?.test_commands]),ot=(0,Y.useCallback)(async e=>LY(l(`board.notifications.planningDoneTitle`),l(`board.notifications.planningDoneBody`,{count:e})),[l]),st=at.length>0,ct=(0,Y.useMemo)(()=>new Map(d.map(e=>[e.id,e])),[d]);(0,Y.useEffect)(()=>{Xe(null)},[e]),(0,Y.useEffect)(()=>{Ye!==null&&(J||et!==null)&&Xe(null)},[et,J,Ye]),(0,Y.useEffect)(()=>{if(!me){G(null);return}let e=ct.get(me)??null;e&&G(t=>!t||t.id!==me?e:tX(t,e))},[me,ct]),(0,Y.useEffect)(()=>{_&&(G(e=>!e||e.id!==_.id?e:tX(e,_)),xe(e=>{if(!e)return e;let t=_.worktree_bundle_id;if(!t||e.bundle.id!==t)return e;let n=e.tickets.some(e=>e.id===_.id)?e.tickets.map(e=>e.id===_.id?tX(e,_):e):[...e.tickets,_];return{...e,tickets:n}}))},[_]),(0,Y.useEffect)(()=>{_===null||me!==null||ge!==null||v()},[v,_,ge,me]);let lt=(0,Y.useCallback)(async e=>{let t=await C(e);if(!t)return null;let n=ct.get(e),r=n?tX(t,n):t;return G(t=>t&&t.id!==e||me&&me!==e?t:r),r},[C,me,ct]),ut=(0,Y.useCallback)(e=>{G(e),W(e.id),lt(e.id)},[lt]),dt=(0,Y.useMemo)(()=>new Map(h.map(e=>[e.id,e])),[h]),ft=(0,Y.useMemo)(()=>{if(!be)return null;let e=be.bundle.id,t=_?.worktree_bundle_id===e?_:null,n=d.filter(t=>t.worktree_bundle_id===e),r=new Map(n.map(e=>[e.id,e])),i=be.tickets.filter(e=>!S.current.has(e.id)).map(e=>t&&e.id===t.id?tX(e,t):e);t&&!i.some(e=>e.id===t.id)&&!S.current.has(t.id)&&i.push(t);let a=i.map(e=>tX(e,r.get(e.id)));for(let e of n)a.some(t=>t.id===e.id)||a.push(e);a.sort(eX);let o=be.execution_order_ticket_ids??[],s=a.map(e=>e.id),c=[...o,...s].filter((e,t,n)=>s.includes(e)&&n.indexOf(e)===t),l=n.some(e=>e.can_re_review!==void 0||e.has_completed_review!==void 0||e.has_follow_up_since_last_review!==void 0),u=n.some(e=>e.agent_status===`running`),f={has_completed_review:n.some(e=>e.has_completed_review===!0),has_follow_up_since_last_review:n.some(e=>e.has_follow_up_since_last_review===!0),can_re_review:!u&&n.some(e=>e.can_re_review===!0)},p=vl(a),m=a.find(e=>e.id===be.review_owner_ticket_id&&e.state===`review`)??a.find(e=>e.state===`review`)??null,h=xl(a,{targetTicketId:be.target_ticket_id,reviewOwnerTicketId:m?.id??be.review_owner_ticket_id,latestSessionTicketId:p?.id??be.latest_session_ticket_id});return{...be,bundle:dt.get(e)??be.bundle,tickets:a,execution_order_ticket_ids:c,latest_session_ticket_id:p?.id??null,latest_session_id:p?.session_id??null,review_owner_ticket_id:m?.id??null,target_ticket_id:h?.id??null,has_completed_review:l?f.has_completed_review:be.has_completed_review,has_follow_up_since_last_review:l?f.has_follow_up_since_last_review:be.has_follow_up_since_last_review,can_re_review:l?f.can_re_review:be.can_re_review}},[dt,_,S,be,d]),pt=(0,Y.useMemo)(()=>d.filter(e=>Re&&Aw(e)?!1:nX(Ie,e)),[Re,Ie,d]),mt=(0,Y.useMemo)(()=>pt.filter(e=>Ow(e)),[pt]),ht=(0,Y.useMemo)(()=>Sl(mt,h,iX),[h,mt]),{boardViewportRef:gt,boardContentRef:_t,registerTicketNode:vt,measuredCardRects:yt,overlayPreview:bt,overlaySize:xt,getDependencyTargetState:St,handleDependencyStart:Ct,handleDeleteDependency:wt}=bY({activeProjectId:e,tickets:d,dependencies:p,setDependencies:m,activeTicket:A,activeOverlayNode:P,dragOffset:L}),Tt=e?se[e]??lX():lX(),kt=Tt.composer.worktreeBundleId&&h.some(e=>e.id===Tt.composer.worktreeBundleId)?Tt.composer.worktreeBundleId:``,At=kt===Tt.composer.worktreeBundleId?Tt:{...Tt,composer:{...Tt.composer,worktreeBundleId:kt}},jt=hX(),It=!!t?.run_ide?.trim(),Lt=At.runs.filter(e=>e.boardVisible),Rt=(0,Y.useCallback)((e,t,n=d)=>{let r=Sl(n,h,t).find(t=>t.kind===`bundle`&&t.group.bundle.id===e);return r?.kind===`bundle`?r.group:null},[h,d]),Ht=(0,Y.useCallback)(e=>(0,Z.jsx)(dG,{ticket:e,allTickets:d,dependencies:p,bundles:h,projectMemoryEnabled:!!t?.memory_enabled,overlay:!0,showModelSelector:e.tool===`opencode`&&B.length>0,availableModels:B,runDisabled:!0,hideBundleScopedControls:!0}),[t?.memory_enabled,B,h,p,d]),Ut=Lt.length>0?(0,Z.jsx)(`div`,{className:`mb-0.5 flex flex-col gap-2.5`,children:Lt.map(e=>(0,Z.jsx)(sY,{run:e},e.id))}):null,Wt=(0,Y.useCallback)(t=>bl(t)?t.project_id===e?It:!!t.has_run_ide:!1,[It,e]),Gt=(0,Y.useCallback)(e=>!!e.project_id&&!!(e.bundle?.branch??e.branch)&&bl(e),[]),Kt=(0,Y.useCallback)(e=>{let t=e?.tickets.find(t=>t.id===e.target_ticket_id)??e?.tickets.find(e=>e.has_worktree)??null;return t?Wt(t):!1},[Wt]),qt=(0,Y.useCallback)(e=>{let t=d.filter(t=>t.worktree_bundle_id===e).sort(eX);return be?.bundle.id===e?mX(be.tickets.map(e=>t.find(t=>t.id===e.id)??e).sort(eX),{targetTicketId:be.target_ticket_id,reviewOwnerTicketId:be.review_owner_ticket_id,latestSessionTicketId:be.latest_session_ticket_id}):mX(t)},[be,d]),Jt=(0,Y.useCallback)((e,t)=>{ce(n=>({...n,[e]:t(n[e]??lX())}))},[]);(0,Y.useEffect)(()=>{ue(!1),U(!1),Ce(null),ke(null),Ke.current!==e&&(qe.current=e),e||(qe.current=null,Le(``)),Ke.current=e},[e,c]),(0,Y.useLayoutEffect)(()=>{!e||y!==e||qe.current===e&&(qe.current=null,Le(``))},[e,y]),(0,Y.useEffect)(()=>{if(!Be){H([]);return}let t=new AbortController;return(async()=>{try{ie(await wn(`opencode`,t.signal))}catch(e){z(e)||ie(e=>e)}})(),(async()=>{try{H(await gw(`opencode`,t.signal,e))}catch(e){z(e)||H([])}})(),()=>{t.abort()}},[e,Be]);let Zt=({active:e})=>{oe(!1),F(null),R({x:0,y:0});let t=wl(String(e.id));if(t){N(Rt(t.bundleId,t.column)),j(null);return}N(null),j(d.find(t=>t.id===e.id)??null)},$t=()=>{oe(!1),F(null),R({x:0,y:0}),j(null),N(null)},en=(0,Y.useCallback)(e=>{f(t=>e.reduce((e,t)=>NY(e,t),t))},[f]),tn=(0,Y.useCallback)((e,t)=>{if(e.length===0)return;let n=e[0]?.state;n&&f(r=>e.reduce((e,r)=>IY(e,r.id,t,CX(r,n,t)),r))},[f]),nn=(0,Y.useCallback)((e,t=d)=>!e.worktree_bundle_id||!e.project_id||e.state!==`build`?[]:t.filter(t=>t.project_id===e.project_id&&t.worktree_bundle_id===e.worktree_bundle_id&&t.state===`build`&&t.parked_at===null).sort(eX),[d]),rn=async({active:e,over:t})=>{let n=wl(String(e.id)),r=d.find(t=>t.id===e.id),i=n?Rt(n.bundleId,n.column):null,a=t?.id===`trash`&&(r!==void 0&&Fw(r,`trash`)||i!==null&&_X(i)),o=t?.id&&rX.includes(t.id)?t.id:null;if(oe(a),F(null),R({x:0,y:0}),j(null),N(null),t){if(n){if(t.id===`trash`){if(!i||!_X(i))return;await Pn(i);return}if(t.id===iX){if(!i||!vX(i))return;await jn(i);return}if(o){if(n.column===iX){if(!i||!yX(i))return;await Mn(i);return}await lr(n.bundleId,n.column,o)}return}if(t.id===`trash`){if(!r||!Fw(r,`trash`))return;Ln(e.id);return}if(t.id===iX){if(!r||!Fw(r,iX))return;await kn(e.id);return}if(o){if(r&&Pw(r,o)){await An(e.id);return}if(!(!r||!Fw(r,o)))try{await Dn(r,o,{optimistic:!0})}catch(e){Q.error(e instanceof I?e.message:l(`board.errors.moveTicket`),{id:`board-move-error`})}}}},an=async(t,n,r,a,o,s,c)=>{let u=await Yt({title:t,description:n,tool:i,model:a,variant:o,skills:s,project_id:e,...c});if(pX(a,o,s),f(e=>NY(e,DY(u))),u.bundle&&g(e=>jY(e,u.bundle)),r===`build`)try{await Dn(u,`build`)}catch(e){Q.error(e instanceof I?e.message:l(`board.errors.moveTicket`),{id:`board-move-error`})}r===`plan`&&Cn(u.id,u.project_id)},on=async t=>{if(!e)throw Error(l(`board.errors.createBundleWithoutProject`));let n=await Et(e,{name:t,prepare:!0});return g(e=>jY(e,n)),n},Tn=e=>{f(t=>[...e.tickets].reverse().reduce((e,t)=>NY(e,DY(t)),t)),m(t=>e.dependencies.reduce((e,t)=>Hw(e,t),t));for(let t of e.tickets)t.bundle&&g(e=>jY(e,t.bundle))},En=(0,Y.useCallback)((e,t={})=>{let n=DY(e);f(e=>t.reorderInState?NY(e,n):MY(e,n)),G(t=>!t||t.id!==e.id?t:tX(e,n)),e.bundle&&g(t=>jY(t,e.bundle))},[g,f]),Dn=async(e,t,n={})=>{let r=d.findIndex(t=>t.id===e.id),i=t===`review`?nn(e):[],a=t===`review`&&i.length>1,o=n.optimistic?a?i.map(e=>e.id):[e.id]:[];n.optimistic&&(E(o,t),a?tn(i,t):f(n=>IY(n,e.id,t,xX(e,t))));try{if(a&&e.project_id&&e.worktree_bundle_id){let t=await Nt(e.project_id,e.worktree_bundle_id);Qn(t);let n=t.tickets.find(t=>t.id===e.id);if(!n)throw Error(l(`board.errors.missingBundleReviewTicket`));return D(o),n}let n=await Qt(e.id,e.project_id,t);return f(r=>{let i=r.find(t=>t.id===e.id);return i?.state===t&&n.state===t&&i.agent_status!==n.agent_status&&n.agent_status===e.agent_status?r:OY(i,n)?NY(r,n):MY(r,n)}),n.bundle&&g(e=>jY(e,n.bundle)),D(o),n}catch(t){throw n.optimistic&&(a?en(i):f(t=>IY(t,e.id,e.state,{agent_status:e.agent_status,agent_log:e.agent_log,build_completed_at:e.build_completed_at},{preferredIndex:r})),D(o)),t}},On=(e,t)=>{f(n=>n.map(n=>n.id===e?{...n,...t}:n))},kn=async t=>{let n=d.find(e=>e.id===t);if(n)try{let r=new Date().toISOString();O([t],r),On(t,{parked_at:r}),En(await dn(t,n.project_id??e),{reorderInState:!0}),k([t])}catch(e){k([t]),On(t,{parked_at:n.parked_at}),Q.error(e instanceof I?e.message:l(`board.errors.parkTicket`),{id:`board-park-error`})}},An=async t=>{let n=d.find(e=>e.id===t);if(n)try{O([t],null),On(t,{parked_at:null}),En(await fn(t,n.project_id??e),{reorderInState:!0}),k([t])}catch(e){k([t]),On(t,{parked_at:n.parked_at}),Q.error(e instanceof I?e.message:l(`board.errors.returnTicket`),{id:`board-unpark-error`})}},jn=(0,Y.useCallback)(async e=>{let t=new Set(e.tickets.map(e=>e.id)),n=e.tickets.map(e=>({id:e.id,parked_at:e.parked_at})),r=new Date().toISOString();O(e.tickets.map(e=>e.id),r),f(e=>e.map(e=>t.has(e.id)?{...e,parked_at:r}:e));let i=await Promise.allSettled(e.tickets.map(e=>dn(e.id,e.project_id??x.current))),a=new Set;if(i.forEach((t,n)=>{if(t.status===`fulfilled`){k([t.value.id]),En(t.value,{reorderInState:!0});return}let r=e.tickets[n];r&&a.add(r.id)}),a.size===0)return;k([...a]),f(e=>e.map(e=>{if(!a.has(e.id))return e;let t=n.find(t=>t.id===e.id);return t?{...e,parked_at:t.parked_at}:e}));let o=i.find(e=>e.status===`rejected`),s=a.size===e.tickets.length?o?.reason instanceof I?o.reason.message:l(`board.errors.moveBundleToDone`):l(`board.toasts.movedBundleToDonePartial`,{movedCount:e.tickets.length-a.size,totalCount:e.tickets.length});Q.error(s,{id:`board-bundle-park-error`})},[x,En,k,O,f,l]),Mn=(0,Y.useCallback)(async e=>{let t=new Set(e.tickets.map(e=>e.id)),n=e.tickets.map(e=>({id:e.id,parked_at:e.parked_at}));O(e.tickets.map(e=>e.id),null),f(e=>e.map(e=>t.has(e.id)?{...e,parked_at:null}:e));let r=await Promise.allSettled(e.tickets.map(e=>fn(e.id,e.project_id??x.current))),i=new Set;if(r.forEach((t,n)=>{if(t.status===`fulfilled`){k([t.value.id]),En(t.value,{reorderInState:!0});return}let r=e.tickets[n];r&&i.add(r.id)}),i.size===0)return;k([...i]),f(e=>e.map(e=>{if(!i.has(e.id))return e;let t=n.find(t=>t.id===e.id);return t?{...e,parked_at:t.parked_at}:e}));let a=r.find(e=>e.status===`rejected`),o=i.size===e.tickets.length?a?.reason instanceof I?a.reason.message:l(`board.errors.restoreBundle`):l(`board.toasts.restoredBundlePartial`,{restoredCount:e.tickets.length-i.size,totalCount:e.tickets.length});Q.error(o,{id:`board-bundle-unpark-error`})},[x,En,k,O,f,l]),Nn=async t=>{e&&(await Vt(e,t),g(e=>e.filter(e=>e.id!==t)))},Pn=(0,Y.useCallback)(async t=>{let n=t.tickets.map(e=>({ticket:e,index:d.findIndex(t=>t.id===e.id)})).filter(e=>e.index!==-1);if(n.length===0)return;for(let e of n)S.current.set(e.ticket.id,e);let r=new Set(n.map(e=>e.ticket.id));f(e=>e.filter(e=>!r.has(e.id))),m(e=>e.filter(e=>!r.has(e.blocker_ticket_id)&&!r.has(e.dependent_ticket_id)));let i=await Promise.allSettled(n.map(async t=>(await ln(t.ticket.id,t.ticket.project_id??e),S.current.delete(t.ticket.id),t.ticket.id)));t.tickets.some(e=>e.project_id===x.current)&&w().catch(()=>{});let a=n.filter((e,t)=>i[t]?.status===`rejected`);if(a.length===0)return;for(let e of a)S.current.delete(e.ticket.id);a.some(e=>e.ticket.project_id===x.current)&&f(e=>[...a].sort((e,t)=>e.index-t.index).reduce((e,t)=>gX(e,t),e));let o=i.find(e=>e.status===`rejected`),s=a.length===n.length?o?.reason instanceof I?o.reason.message:l(`board.errors.deleteBundleTickets`):l(`board.toasts.deletedBundleTicketsPartial`,{deletedCount:n.length-a.length,totalCount:n.length});Q.error(s,{id:`board-delete-bundle-wrapper-error`})},[e,x,S,w,m,f,d,l]),Fn=e=>{let t=ct.get(e.id);En(e,{reorderInState:t?t.state!==e.state||t.parked_at!==e.parked_at||t.worktree_bundle_id!==e.worktree_bundle_id:!1}),t?.worktree_bundle_id&&t.worktree_bundle_id!==e.worktree_bundle_id&&t.bundle?.ticket_count===1&&g(e=>e.filter(e=>e.id!==t.worktree_bundle_id)),(t?.worktree_bundle_id!==e.worktree_bundle_id||t?.bundle?.ticket_count!==e.bundle?.ticket_count)&&e.project_id===x.current&&w().catch(()=>{})},In=async()=>{if(!e)return;let t=e,n=Tt.composer.description.trim();if(!n)return;let r=uX(),a=He?Tt.composer.model.trim():``,o=He&&a?Tt.composer.variant.trim():``,s=He?Tt.composer.skills:[],c=Date.now();Jt(t,e=>({...e,isOpen:!1,composer:{...e.composer,description:``,worktreeBundleId:``},runs:[{id:r,description:n,model:a,variant:o,skills:s,worktreeBundleId:kt,status:`running`,error:null,submittedAt:c,completedAt:null,boardVisible:!0,boardState:`visible`,summary:null},...e.runs]}));try{let e=await Xt({description:n,tool:i,model:a||null,variant:a&&o||null,skills:s,project_id:t,worktree_bundle_id:kt||null});pX(a||null,a&&o||null,s);let c=dX(e);Jt(t,e=>({...e,runs:fX(e.runs,r,e=>({...e,status:`done`,error:null,completedAt:Date.now(),summary:c,boardVisible:!1}))})),Q.success(l(`board.toasts.planningAgentCardsCreated`,{count:c.ticketCount}),{id:`planning-agent-success-${r}`}),ot(e.tickets.length),x.current===t&&Tn(e)}catch(e){let n=e instanceof I?e.message:l(`board.errors.generateTickets`);Jt(t,e=>({...e,runs:fX(e.runs,r,e=>({...e,status:`error`,error:n,completedAt:Date.now()}))})),Q.error(n,{id:`planning-agent-error`})}},Ln=async t=>{let n=d.find(e=>e.id===t),r=d.findIndex(e=>e.id===t);if(!(!n||r===-1)){S.current.set(t,{ticket:n,index:r}),f(e=>FY(e,t)),m(e=>Vw(e,t));try{await ln(t,n.project_id??e),n.project_id===x.current&&w().catch(()=>{}),S.current.delete(t)}catch(e){let n=S.current.get(t);S.current.delete(t),n&&n.ticket.project_id===x.current&&(f(e=>gX(e,n)),Q.error(e instanceof I?e.message:l(`board.errors.deleteTicket`),{id:`board-delete-error`}))}}},Rn=async t=>{let n=d.find(e=>e.id===t);if(!n)return;let r=n.state===`review`?`review`:`build`;try{if(pe(r),n.project_id&&n.worktree_bundle_id&&n.state===`review`){Qn(await Pt(n.project_id,n.worktree_bundle_id));return}En(await un(t,n.project_id??e),{reorderInState:!0})}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.undoTicket`),{id:`board-undo-error`}),e}finally{pe(e=>e===r?null:e)}},zn=t=>{mn(t,d.find(e=>e.id===t)?.project_id??e)},Bn=async t=>{let n=d.find(e=>e.id===t),r=n?Ew(n):t;try{Xe(r),await hn(t,n?.project_id??e),s?.()}catch(e){Xe(e=>e===r?null:e),Q.error(e instanceof I?e.message:l(`board.errors.startRun`),{id:`board-run-error`})}},Vn=(0,Y.useCallback)(async t=>{let n=d.find(e=>e.id===t);try{await gn(t,n?.project_id??e)}catch(e){Q.error(e instanceof I?e.message:l(`board.errors.openIde`),{id:`board-open-ide-error`})}},[e,l,d]),Hn=async t=>{let n=d.find(e=>e.id===t),i=r?.kind===`ticket`&&n&&et===Ew(n)?$e:null;try{await _n(t,n?.project_id??e),o?.(i),s?.()}catch{}},Un=t=>{vn(t,d.find(e=>e.id===t)?.project_id??e).then(()=>{f(e=>e.map(e=>e.id===t?{...e,agent_status:`stopped`,is_running:!1}:e))})},Wn=t=>{yn(t,d.find(e=>e.id===t)?.project_id??e).then(()=>{f(e=>e.map(e=>e.id===t?{...e,agent_status:`running`}:e))})},Gn=(0,Y.useCallback)(e=>{let t=qt(e);!t||!Wt(t)||Vn(t.id)},[Wt,qt,Vn]),Kn=(0,Y.useCallback)(e=>{let t=qt(e);t&&De({bundleId:e,ticketId:t.id,projectId:t.project_id,title:t.bundle?Dl(t.bundle):t.title})},[qt]),qn=(0,Y.useCallback)(e=>{if(!st)return;let t=qt(e);!t?.project_id||!bl(t)||ke(e)},[qt,st]),Jn=(0,Y.useCallback)(e=>{let t=d.find(t=>t.id===e);!t||!Gt(t)||Te({ticketId:t.id,projectId:t.project_id,title:t.title})},[Gt,d]),Yn=(0,Y.useCallback)(e=>{if(!st)return;let t=d.find(t=>t.id===e);!t?.project_id||!bl(t)||Ce({ticketId:t.id,projectId:t.project_id})},[st,d]),Xn=(0,Y.useCallback)(async(t,n)=>{let r=d.find(e=>e.id===t);if(r)try{En(r.state===`plan`?await Sn(t,r.project_id??e,n):await bn(t,r.project_id??e,n))}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.sendFollowUp`),{id:`board-follow-up-error`}),e}},[e,En,l,d]),Zn=(0,Y.useCallback)(e=>{f(t=>e.reduce((e,t)=>{let n=e.find(e=>e.id===t.id),r=T(n,t);if(!r)return e;let i=DY(n&&n.state===r.state&&n.agent_status===`running`&&r.agent_status===null?{...r,agent_status:n.agent_status,session_id:n.session_id,is_running:n.is_running}:r);return OY(n,i)?NY(e,i):MY(e,i)},t))},[T,f]),Qn=(0,Y.useCallback)(e=>{xe(e),g(t=>jY(t,e.bundle)),Zn(e.tickets)},[Zn,g]),$n=(0,Y.useCallback)((e,t)=>{Array.isArray(t.tickets)&&xe(n=>!n||n.bundle.id!==e?n:{...n,tickets:t.tickets,execution_order_ticket_ids:t.execution_order_ticket_ids,latest_session_ticket_id:t.latest_session_ticket_id,latest_session_id:t.latest_session_id,review_owner_ticket_id:t.review_owner_ticket_id,target_ticket_id:t.target_ticket_id})},[]),er=(0,Y.useCallback)(async e=>{let t=x.current;if(!t)return null;let n=await Dt(t,e);return x.current===t?(Qn(n),n):null},[x,Qn]),tr=(0,Y.useCallback)(async e=>{let t=x.current;if(!t)return null;let n=await Ot(t,e);return x.current===t?($n(e,n),n):null},[x,$n]),nr=(0,Y.useCallback)(async(e,t=null)=>{let n=x.current;if(!n)return;W(null),G(null),_e(e),ye(t),Ne(aX());let r=dt.get(e)??null,i=d.filter(t=>t.worktree_bundle_id===e);if(r&&i.length>0){let e=vl(i),t=xl(i,{reviewOwnerTicketId:i.find(e=>e.state===`review`)?.id??null,latestSessionTicketId:e?.id??null});xe({bundle:r,tickets:i,latest_session_ticket_id:e?.id??null,latest_session_id:e?.session_id??null,review_owner_ticket_id:i.find(e=>e.state===`review`)?.id??null,target_ticket_id:t?.id??null})}else xe(null);je(!0);try{await tr(e)}catch{}finally{x.current===n&&je(!1)}},[x,dt,tr,d]),rr=(0,Y.useCallback)(async(e,t)=>{Ne(t=>({...t,[e]:!0}));try{return await t()}finally{Ne(t=>({...t,[e]:!1}))}},[]),ir=(0,Y.useCallback)(async t=>{await rr(`stopBuild`,async()=>{let n=d.find(e=>e.id===t);await vn(t,n?.project_id??e),f(e=>e.map(e=>e.id===t?{...e,agent_status:`stopped`,is_running:!1}:e)),n?.worktree_bundle_id&&await er(n.worktree_bundle_id)})},[e,er,rr,f,d]),ar=(0,Y.useCallback)(async t=>{await rr(`resumeBuild`,async()=>{let n=d.find(e=>e.id===t);await yn(t,n?.project_id??e),f(e=>e.map(e=>e.id===t?{...e,agent_status:`running`}:e)),n?.worktree_bundle_id&&await er(n.worktree_bundle_id)})},[e,er,rr,f,d]),or=(0,Y.useCallback)(async t=>{if(e)try{Qn(await rr(`build`,()=>Mt(e,t))),ge===t&&ye(`build`),s?.()}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.buildBundle`),{id:`board-bundle-build-error`}),e}},[e,Qn,s,rr,ge,l]),sr=(0,Y.useCallback)(async t=>{if(e)try{Qn(await rr(`review`,()=>Nt(e,t))),ge===t&&ye(`review`)}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.reviewBundle`),{id:`board-bundle-review-error`}),e}},[e,Qn,rr,ge,l]),cr=(0,Y.useCallback)(async t=>{if(e)try{pe(`review`),Qn(await rr(`undoReview`,()=>Pt(e,t))),ge===t&&ye(`build`)}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.undoBundleReview`),{id:`board-bundle-undo-review-error`}),e}finally{pe(e=>e===`review`?null:e)}},[e,Qn,rr,ge,l]),lr=(0,Y.useCallback)(async(e,t,n)=>{if(t===iX||n===iX)return;let r=SX(t,n);if(!r)return;let i=d.filter(n=>n.worktree_bundle_id===e&&n.state===t&&n.parked_at===null);if(i.length===0)return;let a=i.map(e=>e.id);E(a,n),tn(i,n);try{if(r===`build`){await or(e),D(a);return}if(r===`review`){await sr(e),D(a);return}await cr(e),D(a)}catch(e){en(i),D(a),Q.error(e instanceof I?e.message:l(`board.errors.moveBundle`),{id:`board-bundle-move-error`})}},[D,or,sr,cr,E,tn,en,d,l]),ur=async t=>{e&&(Qn(await rr(`run`,()=>zt(e,t))),s?.())},dr=async t=>{if(!e)return;let n=r?.kind===`ticket`&&et===t?$e:null,i=await rr(`stop`,()=>Bt(e,t));o?.(n),Qn(i),s?.()},fr=(0,Y.useCallback)(async(t,n)=>{e&&Qn(await rr(`followUp`,()=>Ft(e,t,n)))},[e,Qn,rr]);(0,Y.useEffect)(()=>()=>{a?.(null)},[a]),(0,Y.useEffect)(()=>{if(!a)return;if(!r){a(null);return}if(r.kind===`project`){a({target:null,canSelect:!1,disabledReason:l(`board.preview.disabledProjectRoot`),submitPrompt:null});return}let e=d.find(e=>e.id===r.ticket_id);if(!e){a({target:null,canSelect:!1,disabledReason:l(`board.preview.disabledBuildCapable`),submitPrompt:null});return}if(e.state===`plan`){a({target:{kind:`ticket`,id:e.id},canSelect:!1,disabledReason:l(`board.preview.disabledPlanMode`),submitPrompt:null});return}if(e.worktree_bundle_id){a({target:{kind:`bundle`,id:e.worktree_bundle_id,ticket_id:e.id},canSelect:!0,disabledReason:null,promptPlaceholder:l(`board.preview.followUpBundlePlaceholder`),submitPrompt:t=>fr(e.worktree_bundle_id,t)});return}a({target:{kind:`ticket`,id:e.id},canSelect:!0,disabledReason:null,promptPlaceholder:l(`board.preview.followUpTicketPlaceholder`),submitPrompt:t=>Xn(e.id,t)})},[r,Xn,fr,a,l,d]);let pr=async t=>{let n=d.find(e=>e.id===t),r=n?ww(n.state):null;if(n)try{if(n.state===`review`&&n.can_re_review&&n.agent_status!==`running`){let t=await xn(n.id,n.project_id??e);En(t),t.worktree_bundle_id&&await er(t.worktree_bundle_id);return}if(!r)return;if(n.worktree_bundle_id&&r===`review`){await sr(n.worktree_bundle_id);return}await Dn(n,r)}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.moveTicket`),{id:`board-move-error`}),e}},mr=async t=>{let n=d.find(e=>e.id===t);try{En(await sn(t,n?.project_id??e))}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.startBuildChain`),{id:`board-build-chain-error`}),e}},hr=async t=>{let n=d.find(e=>e.id===t);try{await cn(t,n?.project_id??e)}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.stopBuildChain`),{id:`board-stop-build-chain-error`}),e}},gr=async()=>{if(!(!e||de)){U(!0);try{let t=await pn(e);f(e=>e.filter(e=>!t.deleted_ticket_ids.includes(e.id))),m(e=>t.deleted_ticket_ids.reduce(Vw,e)),await w(),ue(!1),t.failed_count>0?Q.error(l(`board.toasts.deleteDonePartial`,{count:t.deleted_count,deletedCount:t.deleted_count,failedCount:t.failed_count}),{id:`board-delete-parked-error`}):Q.success(l(`board.toasts.deleteDoneSuccess`,{count:t.deleted_count}),{id:`board-delete-parked-success`})}catch(e){Q.error(e instanceof I?e.message:l(`board.errors.emptyDone`),{id:`board-delete-parked-error`})}finally{U(!1)}}},_r=({delta:e})=>{R(e)},vr=(0,Y.useCallback)((t=null)=>{e&&te({initialWorktreeBundleId:t})},[e]),yr=(0,Y.useCallback)(()=>{e&&Jt(e,e=>e.isOpen?e:{...e,isOpen:!0})},[e,Jt]),br=(0,Y.useCallback)(()=>{Je.current?.focus({preventScroll:!0})},[]);return EY([{key:`n`,onKeyDown:vr,disabled:!e},{key:`a`,onKeyDown:yr,disabled:!e},{key:`k`,ctrlKey:!0,onKeyDown:br}],{isBlocked:TY}),(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(JC,{sensors:u,collisionDetection:oS,onDragStart:Zt,onDragMove:_r,onDragCancel:$t,onDragEnd:rn,children:[(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 overflow-hidden`,children:[(0,Z.jsx)(pY,{projectId:e,state:At,bundles:h,projectBranchState:n,showModelSelector:He,availableModels:B,availableSkills:V,onManageBundles:e?()=>{(async()=>{try{await w()}catch{}re(!0)})()}:void 0,onToggle:()=>{e&&Jt(e,e=>({...e,isOpen:!e.isOpen}))},onDescriptionChange:t=>{e&&Jt(e,e=>({...e,composer:{...e.composer,description:t}}))},onModelChange:t=>{if(!e)return;let n=B.find(e=>e.id===t)??null;Jt(e,e=>({...e,composer:{...e.composer,model:t,variant:n?.variants.includes(e.composer.variant)?e.composer.variant:``}}))},onSkillsChange:t=>{e&&Jt(e,e=>({...e,composer:{...e.composer,skills:t}}))},onVariantChange:t=>{e&&Jt(e,e=>({...e,composer:{...e.composer,variant:t}}))},onBundleChange:t=>{e&&Jt(e,e=>({...e,composer:{...e.composer,worktreeBundleId:t}}))},onGenerate:()=>{In()}}),(0,Z.jsx)(`div`,{"aria-hidden":`true`,className:K(`absolute inset-y-0 left-16 right-0 z-10 bg-black/60 transition-opacity duration-200 ease-out motion-reduce:transition-none`,At.isOpen?`opacity-100`:`pointer-events-none opacity-0`)}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-4 overflow-hidden p-6`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col items-start gap-3 sm:flex-row sm:items-center`,children:[(0,Z.jsxs)(`div`,{className:`relative w-full max-w-sm`,children:[(0,Z.jsx)(Ge,{id:`board-ticket-search`,ref:Je,type:`search`,value:Ie,onChange:e=>Le(e.target.value),placeholder:l(`board.search.placeholder`),"aria-label":l(`board.search.ariaLabel`),className:`pr-32`}),Ie.length>0?(0,Z.jsx)(q,{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":l(`board.search.clearAriaLabel`),className:`absolute right-1 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,onClick:()=>{Le(``),Je.current?.focus()},children:(0,Z.jsx)(Ve,{className:`size-4`})}):(0,Z.jsxs)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute right-2 top-1/2 flex -translate-y-1/2 items-center gap-0.5 text-[10px] leading-none`,children:[(0,Z.jsx)(hw,{children:`CTRL`}),(0,Z.jsx)(`span`,{children:`+`}),(0,Z.jsx)(hw,{children:`K`})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Gd,{id:`board-hide-stale-tickets`,checked:Re,onCheckedChange:ze,"aria-label":l(`board.search.hideStaleAriaLabel`)}),(0,Z.jsx)(Qs,{htmlFor:`board-hide-stale-tickets`,className:`text-sm text-muted-foreground`,children:l(`board.search.hideStaleLabel`)})]})]}),(0,Z.jsx)(`div`,{ref:gt,className:`flex min-h-0 flex-1 overflow-x-auto overflow-y-hidden`,children:(0,Z.jsxs)(`div`,{ref:_t,className:`relative flex min-h-0 w-max min-w-full gap-4`,children:[(0,Z.jsx)(rY,{dependencies:p,cardRects:yt,preview:bt,ticketsById:ct,overlaySize:xt}),rX.map(t=>{let n=d.filter(e=>e.state===t&&!Ow(e)),r=pt.filter(e=>e.state===t&&!Ow(e)),i=Sl(r,h,t),a=it&&n.length===0?t===`plan`?1:t===`build`?2:0:0;return(0,Z.jsx)(pG,{id:t,title:l(`card.columnLabels.${t}`),pinnedContent:t===`plan`?Ut:null,items:i,ticketCount:r.length,allTickets:d,dependencies:p,showModelSelector:He,availableModels:B,bundles:h,activeRunContextKey:tt,isProjectRootRunActive:J,isBundleRunDisabled:nt,getDependencyTargetState:St,onDependencyStart:Ct,onDeleteDependency:wt,onRegisterTicketNode:vt,onAddTicket:t===`plan`&&e?vr:void 0,onCreateBundle:t===`plan`&&e?on:void 0,onDeleteBundle:t===`plan`&&e?Nn:void 0,onDeleteBundleWrapper:Pn,onRefreshBundles:t===`plan`&&e?w:void 0,onUpdateTicket:Fn,onDeleteTicket:Ln,onUndoTicket:Rn,undoingColumn:fe,onRetryTicket:zn,onAdvanceTicket:pr,onParkTicket:kn,onUnparkTicket:An,onBuildChainTicket:mr,onRunTicket:Bn,onOpenTestsTicket:st?Yn:void 0,canOpenChangesForTicket:Gt,onOpenChangesTicket:Jn,canOpenIdeForTicket:Wt,onOpenIdeTicket:Vn,onStopTicket:Hn,onStopBuildTicket:Un,onStopBuildChainTicket:hr,onResumeBuildTicket:Wn,onOpenBundleChanges:Kn,onOpenBundleTests:st?qn:void 0,onOpenBundleIde:Gn,onAddTicketToBundle:vr,onFollowUpTicket:Xn,bundleActionState:Me,onBuildBundle:or,onReviewBundle:sr,onUndoBundleReview:cr,onRunBundle:ur,onStopBundle:dr,onParkBundleWrapper:jn,onUnparkBundleWrapper:Mn,onOpenTicketDetails:ut,onOpenBundleDetails:(e,t)=>{nr(e,t)},onRequestBundleRefresh:e=>{rr(`bundleRefresh`,()=>er(e))},onRequestTicketRefresh:C,loadingSkeletonCount:a},t)}),(0,Z.jsx)(pG,{id:iX,title:l(`card.columnLabels.done`),items:ht,ticketCount:mt.length,allTickets:d,dependencies:p,showModelSelector:He,availableModels:B,bundles:h,activeRunContextKey:tt,isProjectRootRunActive:J,isBundleRunDisabled:nt,getDependencyTargetState:St,onDependencyStart:Ct,onDeleteDependency:wt,onRegisterTicketNode:vt,onUpdateTicket:Fn,onDeleteTicket:Ln,onUndoTicket:Rn,undoingColumn:fe,onRetryTicket:zn,onAdvanceTicket:pr,onParkTicket:kn,onUnparkTicket:An,onBuildChainTicket:mr,onRunTicket:Bn,onOpenTestsTicket:st?Yn:void 0,canOpenChangesForTicket:Gt,onOpenChangesTicket:Jn,canOpenIdeForTicket:Wt,onOpenIdeTicket:Vn,onStopTicket:Hn,onStopBuildTicket:Un,onStopBuildChainTicket:hr,onResumeBuildTicket:Wn,onOpenBundleChanges:Kn,onOpenBundleTests:st?qn:void 0,onOpenBundleIde:Gn,onAddTicketToBundle:vr,onFollowUpTicket:Xn,bundleActionState:Me,onBuildBundle:or,onReviewBundle:sr,onUndoBundleReview:cr,onRunBundle:ur,onStopBundle:dr,onParkBundleWrapper:jn,onUnparkBundleWrapper:Mn,onOpenTicketDetails:ut,onOpenBundleDetails:(e,t)=>{nr(e,t)},onRequestBundleRefresh:e=>{rr(`bundleRefresh`,()=>er(e))},onRequestTicketRefresh:C,className:`min-w-[272px] max-w-[272px] flex-[0.98] bg-card/65`,headerAccessory:(0,Z.jsxs)(q,{type:`button`,variant:`destructive`,size:`xs`,className:`gap-1.5`,disabled:mt.length===0||de,onClick:()=>ue(!0),children:[(0,Z.jsx)(wu,{className:`h-3.5 w-3.5`}),(0,Z.jsx)(`span`,{children:l(`board.doneColumn.emptyAction`)})]})})]})})]})]}),(0,Z.jsxs)(mw,{zIndex:5,dropAnimation:ae?null:void 0,children:[A&&(0,Z.jsx)(dG,{ticket:A,allTickets:d,dependencies:p,bundles:h,projectMemoryEnabled:!!t?.memory_enabled,overlay:!0,showModelSelector:A.tool===`opencode`&&B.length>0,availableModels:B,runDisabled:bX(A,tt,J,l(`board.errors.runBlockedByActive`))!==void 0,runDisabledReason:bX(A,tt,J,l(`board.errors.runBlockedByActive`)),onDependencyStart:Ct,onDeleteDependency:wt,onRegisterOverlayNode:F,onCreateBundle:on,onDeleteBundle:Nn,onRefreshBundles:w,onUpdate:Fn,onDelete:()=>Ln(A.id),onUndo:()=>Rn(A.id),undoInProgress:fe===A.state&&(A.state===`build`||A.state===`review`),onRetry:()=>zn(A.id),onAdvance:()=>pr(A.id),onPark:()=>kn(A.id),onUnpark:()=>An(A.id),onBuildChain:()=>mr(A.id),onRun:A.worktree_bundle_id===null&&bl(A)&&A.has_run_config?()=>Bn(A.id):void 0,onOpenIde:A.worktree_bundle_id===null&&Wt(A)?()=>Vn(A.id):void 0,onStop:A.worktree_bundle_id===null?()=>Hn(A.id):void 0,onStopBuild:()=>Un(A.id),onStopBuildChain:()=>hr(A.id),onResumeBuild:()=>Wn(A.id),onFollowUp:e=>Xn(A.id,e),onRequestTicketRefresh:C}),!A&&M&&(0,Z.jsx)(gT,{group:M,overlay:!0,renderTicket:Ht})]}),rt&&(0,Z.jsx)(mY,{className:`pointer-events-auto fixed left-1/2 top-4 z-20 w-[min(14rem,calc(100vw-2rem))] -translate-x-1/2`})]}),ee&&(0,Z.jsx)(iY,{onSubmit:an,bundles:h,projectId:e,projectBranchState:n,tool:i,showModelSelector:He,availableModels:B,availableSkills:V,initialModel:He?jt.model:``,initialVariant:He&&jt.model?jt.variant:``,initialSkills:He?jt.skills:[],initialWorktreeBundleId:ee.initialWorktreeBundleId,onCreateBundle:on,onDeleteBundle:Nn,onRefreshBundles:w,onClose:()=>te(null)}),ne&&e&&(0,Z.jsx)(Eu,{bundles:h,selectedBundleId:At.composer.worktreeBundleId||null,onSelectBundle:t=>{Jt(e,e=>({...e,composer:{...e.composer,worktreeBundleId:t??``}}))},onCreateBundle:on,onDeleteBundle:Nn,onClose:()=>re(!1)}),le&&(0,Z.jsx)(mG,{ticketCount:mt.length,isDeleting:de,onCancel:()=>ue(!1),onConfirm:()=>{gr()}}),he&&(0,Z.jsx)(uG,{ticket:he,allTickets:d,dependencies:p,bundles:h,projectMemoryEnabled:!!t?.memory_enabled,projectBranchState:n,onClose:()=>{let e=he.id;W(null),G(null),f(t=>t.map(t=>t.id===e?DY(t):t))},showModelSelector:Ue,availableModels:B,availableSkills:V,runDisabled:bX(he,tt,J,l(`board.errors.runBlockedByActive`))!==void 0,runDisabledReason:bX(he,tt,J,l(`board.errors.runBlockedByActive`)),onDeleteDependency:wt,onCreateBundle:on,onDeleteBundle:Nn,onRefreshBundles:w,onUpdate:Fn,onAdvance:()=>pr(he.id),onBuildChain:()=>mr(he.id),onRun:bl(he)&&he.has_run_config?()=>Bn(he.id):void 0,onOpenIde:Wt(he)?()=>Vn(he.id):void 0,onStop:()=>Hn(he.id),onStopBuild:()=>Un(he.id),onStopBuildChain:()=>hr(he.id),onResumeBuild:()=>Wn(he.id),onFollowUp:e=>Xn(he.id,e),onProjectMemorySuggestionsChanged:()=>{Fe(e=>e+1)},onRequestTicketRefresh:e=>{lt(e)}}),Se&&(0,Z.jsx)(Y.Suspense,{fallback:null,children:(0,Z.jsx)(JY,{scope:`ticket`,ticketId:Se.ticketId,projectId:Se.projectId,testCommands:at,onClose:()=>Ce(null)})}),Ee&&(0,Z.jsx)(UJ,{ticketId:Ee.ticketId,projectId:Ee.projectId,reviewCommentsBundleId:Ee.bundleId,title:Ee.title,onSubmitReviewPrompt:e=>fr(Ee.bundleId,e),canSubmitReviewPrompt:!d.some(e=>e.worktree_bundle_id===Ee.bundleId&&e.agent_status===`running`),reviewSubmitDisabledReason:d.some(e=>e.worktree_bundle_id===Ee.bundleId&&e.agent_status===`running`)?l(`board.changes.reviewPromptDisabledReason`):void 0,canAddReviewComments:!d.some(e=>e.worktree_bundle_id===Ee.bundleId&&e.agent_status===`running`),canModifyChanges:!d.some(e=>e.worktree_bundle_id===Ee.bundleId&&e.agent_status===`running`),changesDisabledReason:d.some(e=>e.worktree_bundle_id===Ee.bundleId&&e.agent_status===`running`)?l(`board.changes.modifyChangesDisabledReason`):void 0,onClose:()=>{let{bundleId:e}=Ee;De(null),er(e)},onTicketUpdate:Fn,onRequestTicketRefresh:C}),we&&(0,Z.jsx)(UJ,{ticketId:we.ticketId,projectId:we.projectId,title:we.title,onClose:()=>{let{ticketId:e}=we;Te(null),lt(e)},onTicketUpdate:Fn,onRequestTicketRefresh:e=>{lt(e)}}),Oe&&e&&t&&(0,Z.jsx)(Y.Suspense,{fallback:null,children:(0,Z.jsx)(JY,{scope:`project`,projectId:e,targetKind:`bundle`,targetBundleId:Oe,testCommands:at,onClose:()=>ke(null)})}),ge&&ft&&(0,Z.jsx)(PG,{details:ft,activeColumn:ve,isLoading:Ae||Me.bundleRefresh,actionState:Me,canOpenIde:Kt(ft),projectMemoryEnabled:!!t?.memory_enabled,memorySuggestionsRefreshKey:Pe,runDisabled:nt(ft.bundle.id),showModelSelector:We,availableModels:B,availableSkills:V,onClose:()=>{let e=ft.bundle.id;_e(null),ye(null),xe(null),je(!1),Ne(aX()),f(t=>t.map(t=>t.worktree_bundle_id===e&&t.id!==me?DY(t):t))},onOpenTicketDetails:ut,onUpdateTicket:Fn,onOpenIde:()=>{let e=ft.tickets.find(e=>e.id===ft.target_ticket_id)??ft.tickets.find(e=>e.has_worktree);e&&Vn(e.id)},onOpenTests:st?()=>{qn(ft.bundle.id)}:void 0,onRefresh:e=>{rr(`bundleRefresh`,()=>er(e))},onBuildBundle:or,onStopBuildTicket:ir,onResumeBuildTicket:ar,onReviewBundle:sr,onUndoBundleReview:cr,onRunBundle:ur,onStopBundle:dr,onFollowUpBundle:fr})]})},TX=({className:e})=>(0,Z.jsx)(jo,{"aria-hidden":`true`,className:e}),EX=({className:e})=>(0,Z.jsx)(So,{"aria-hidden":`true`,className:e}),DX=({className:e})=>(0,Z.jsx)(Co,{"aria-hidden":`true`,className:e}),OX=4,kX=5e3,AX=(e,t)=>Pe.t(`common:chatChangesPanel.${e}`,t),jX=e=>e.replace(/^[ab]\//,``),MX=e=>{let t=`oldPath`in e&&typeof e.oldPath==`string`?jX(e.oldPath):``,n=`newPath`in e&&typeof e.newPath==`string`?jX(e.newPath):``;return[...new Set([n,t].filter(e=>e&&e!==`/dev/null`))]},NX=e=>{let[t,n]=MX(e);return!t&&!n?AX(`unknownFile`):t&&n&&t!==n?`${n} -> ${t}`:t??n??AX(`unknownFile`)},PX=e=>{let t=eq((()=>{let[t,n]=MX(e);return t??n??null})());if(!t)return null;try{return Yy(e.hunks,{highlight:!0,refractor:eJ.default,language:t,enhancers:[qy(e.hunks)]})}catch{return null}},FX=(e,t)=>e instanceof Error?e.message:t,IX=(e,t)=>{if(!t)return e;let n=NX(t);return[t,...e.filter(e=>NX(e)!==n)]},LX=e=>[...e].sort((e,t)=>{if(e.filePath!==t.filePath)return e.filePath.localeCompare(t.filePath);let n=e.newLineNumber??e.oldLineNumber??2**53-1,r=t.newLineNumber??t.oldLineNumber??2**53-1;return n===r?e.changeKey.localeCompare(t.changeKey):n-r}),RX=({diffResponse:e,gitStatus:t})=>{let n=new Map;for(let t of e?.files??[])n.set(t.path,t);return t?t.files.map(e=>{let t=n.get(e.path)??(e.original_path?n.get(e.original_path):void 0);return{path:e.path,originalPath:e.original_path,status:e.status,staged:e.staged,unstaged:e.unstaged,conflicted:e.conflicted,additions:t?.additions??0,deletions:t?.deletions??0}}):(e?.files??[]).map(e=>({path:e.path,originalPath:null,status:null,staged:!1,unstaged:!1,conflicted:!1,additions:e.additions,deletions:e.deletions}))},zX=e=>{let t=e.split(/[\\/]/);return t[t.length-1]||e},BX={modified:`border-amber-500/40 bg-amber-500/10 text-amber-200`,added:`border-emerald-500/40 bg-emerald-500/10 text-emerald-200`,deleted:`border-rose-500/40 bg-rose-500/10 text-rose-200`,renamed:`border-sky-500/40 bg-sky-500/10 text-sky-200`,untracked:`border-violet-500/40 bg-violet-500/10 text-violet-200`,typechanged:`border-slate-500/40 bg-slate-500/10 text-slate-200`},VX=e=>AX(`fileStatus.${e}`),HX=({selectedDiffPath:e,sidebarFiles:t,diffStats:n,triggerMode:r=`full`,onSelectDiffPath:i})=>{let[a,o]=(0,Y.useState)(!1),s=t.find(t=>t.path===e)??null,c=r===`compact`?e===`all`?AX(`picker.diff`):s?zX(s.path):AX(`picker.file`):e===`all`?AX(`picker.allChanges`):s?zX(s.path):e;return(0,Z.jsxs)($s,{open:a,onOpenChange:o,children:[(0,Z.jsx)(ec,{asChild:!0,children:(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`outline`,className:K(`max-w-full gap-2`,r===`full`?`min-w-0 max-w-[18rem]`:`min-w-0 px-2.5`),"aria-label":AX(`picker.openChangedFilesAriaLabel`),title:e===`all`?void 0:s?.path??e,children:[(0,Z.jsx)(`span`,{className:`truncate`,children:c}),r===`full`&&(0,Z.jsx)(U,{variant:`outline`,className:`shrink-0 text-[10px] uppercase tracking-wide`,children:AX(`picker.fileCount`,{count:t.length})}),(0,Z.jsx)(ke,{className:`h-4 w-4 shrink-0 text-muted-foreground`})]})}),(0,Z.jsxs)(tc,{align:`start`,className:`z-[90] w-[28rem] max-w-[calc(100vw-2rem)] p-0`,children:[(0,Z.jsx)(`div`,{className:`border-b border-border/80 px-4 py-3`,children:(0,Z.jsx)(`div`,{className:`text-sm font-semibold text-foreground`,children:AX(`picker.title`)})}),(0,Z.jsx)(`div`,{className:`max-h-[min(28rem,calc(100vh-10rem))] overflow-y-auto p-3`,children:(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{i(`all`),o(!1)},className:K(`flex w-full cursor-pointer items-start gap-3 rounded-xl border px-3 py-2.5 text-left transition-colors`,RK(e===`all`),`justify-between`),children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium text-foreground`,children:AX(`picker.allChanges`)}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground transition-colors group-hover:text-foreground/70`,children:AX(`picker.allChangesDescription`)})]}),n&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3 text-[11px]`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground transition-colors group-hover:text-foreground/70`,children:AX(`picker.fileCount`,{count:n.files_changed})}),(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-emerald-400`,children:[`+`,n.additions]}),(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-rose-400`,children:[`-`,n.deletions]})]})]}),t.map(t=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{i(t.path),o(!1)},className:K(`flex w-full cursor-pointer items-start gap-3 rounded-xl border px-3 py-2.5 text-left transition-colors`,RK(e===t.path)),children:(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium text-foreground`,children:zX(t.path)}),(0,Z.jsx)(`div`,{className:`mt-0.5 break-all font-mono text-[11px] text-muted-foreground transition-colors group-hover:text-foreground/70`,children:t.path})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3 text-[11px]`,children:[(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-emerald-400`,children:[`+`,t.additions]}),(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-rose-400`,children:[`-`,t.deletions]})]})]}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-1.5 text-[11px]`,children:[t.status&&(0,Z.jsx)(U,{variant:`outline`,className:BX[t.status],children:VX(t.status)}),t.staged&&(0,Z.jsx)(U,{variant:`outline`,children:AX(`fileStatus.staged`)}),t.unstaged&&(0,Z.jsx)(U,{variant:`outline`,children:AX(`fileStatus.unstaged`)}),t.conflicted&&(0,Z.jsx)(U,{variant:`destructive`,children:AX(`fileStatus.conflicted`)}),t.originalPath&&(0,Z.jsx)(`span`,{className:`break-all font-mono text-[11px] text-muted-foreground transition-colors group-hover:text-foreground/70`,children:t.status===`renamed`?AX(`fileStatus.renamedFrom`,{path:t.originalPath}):t.originalPath})]})]})},`${t.path}:${t.originalPath??``}`))]})})]})]})},UX=(0,Y.memo)(({projectId:e,chatSessionId:t=null,canSubmitReviewPrompt:n,reviewSubmitDisabledReason:r,onSubmitReviewPrompt:i,state:a,onStateChange:o,isResizing:s=!1,onClose:c,desktopWidth:l,panelElementRef:u})=>{let[d,f]=(0,Y.useState)(null),[p,m]=(0,Y.useState)(null),[h,g]=(0,Y.useState)(null),[_,v]=(0,Y.useState)(!1),[,y]=(0,Y.useState)(!1),[b,x]=(0,Y.useState)(new Map),[S,C]=(0,Y.useState)(!1),w=(0,Y.useRef)(0),T=(0,Y.useRef)(0),E=(0,Y.useRef)(null),D=(0,Y.useRef)(null),O=a.selectedDiffPath,k=a.activeReviewTarget,A=a.editingReviewCommentKey,j=k?.commentKey??A??`chat`,M=a.reviewDraftInput,N=(0,Y.useMemo)(()=>new Map(a.reviewComments.map(e=>[lb(e.filePath,e.changeKey),e])),[a.reviewComments]),P=(0,Y.useCallback)(async()=>{if(!e)throw Error(`Project id is required`);return t?await ox(e,t):await Ae(e)},[t,e]),F=(0,Y.useCallback)(async()=>{if(!e)throw Error(`Project id is required`);return t?await sx(e,t):await ge(e)},[t,e]);(0,Y.useEffect)(()=>{E.current=d},[d]),(0,Y.useEffect)(()=>{D.current=p},[p]);let I=(0,Y.useCallback)(async()=>{if(!e){T.current+=1,f(null),m(null),g(null),v(!1),y(!1);return}let t=w.current+1,n=T.current+1;w.current=t,T.current=n,v(!0),y(!0);let[r,i]=await Promise.allSettled([P(),F()]);w.current===t&&(r.status===`fulfilled`?(E.current=r.value,f(r.value),g(null)):g(FX(r.reason,AX(`errors.loadDiff`))),i.status===`fulfilled`&&(D.current=i.value,m(i.value)),T.current===n&&v(!1),y(!1))},[P,F,e]),L=(0,Y.useCallback)(async(t={})=>{if(!e)return;let{broadcastOnSignatureChange:n=!1}=t,r=w.current+1;w.current=r,y(!0);try{let t=await F();if(w.current!==r)return;let i=D.current?.workspace_signature??null,a=t.workspace_signature??null,o=!E.current||i!==a;if(D.current=t,m(t),!o){T.current+=1,v(!1);return}let s=!E.current,c=T.current+1;T.current=c,s&&v(!0);try{let t=await P();if(w.current!==r)return;E.current=t,f(t),g(null),n&&i!==a&&nq(e)}catch(e){if(w.current!==r)return;E.current||g(FX(e,AX(`errors.loadDiff`)))}finally{s&&T.current===c&&v(!1)}}catch{E.current||(T.current+=1,v(!1));return}finally{w.current===r&&y(!1)}},[P,F,e]);(0,Y.useEffect)(()=>{I()},[I]),(0,Y.useEffect)(()=>{if(e)return rq(t=>{t===e&&L()})},[e,L]),(0,Y.useEffect)(()=>{if(!e)return;let t=aq(()=>{document.visibilityState===`visible`&&L({broadcastOnSignatureChange:!0})});return()=>{t()}},[e,L]),(0,Y.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>{document.visibilityState===`visible`&&L({broadcastOnSignatureChange:!0})},kX);return()=>{window.clearInterval(t)}},[e,L]);let R=(0,Y.useMemo)(()=>{let e=typeof d?.diff==`string`?d.diff:``;return e.trim()?Bm(e,{nearbySequences:`zip`}).map(e=>({...e,pathCandidates:MX(e)})):[]},[d]),z=(0,Y.useMemo)(()=>{let e=new Map;for(let t of R)for(let n of t.pathCandidates)e.has(n)||e.set(n,t);return e},[R]),ee=(0,Y.useMemo)(()=>RX({diffResponse:d,gitStatus:p}),[d,p]);(0,Y.useEffect)(()=>{if(O!==`all`&&!(!d&&!p)){if(ee.length===0){o(e=>({...e,selectedDiffPath:`all`}));return}ee.some(e=>e.path===O)||o(e=>({...e,selectedDiffPath:`all`}))}},[d,p,o,O,ee]);let te=O===`all`?null:z.get(O)??null,ne=(0,Y.useMemo)(()=>IX(R,te),[R,te]),re=(0,Y.useMemo)(()=>O===`all`?R:te?[te]:[],[R,O,te]);(0,Y.useEffect)(()=>{x(new Map)},[R]),(0,Y.useEffect)(()=>{if(ne.length===0)return;let e=!1,t=null,n=0,r=()=>{if(e)return;let i=ne.slice(n,n+OX);i.length!==0&&(x(e=>{let t=new Map(e);for(let e of i){let n=NX(e);t.has(n)||t.set(n,PX(e))}return t}),n+=OX,n<ne.length&&(t=window.setTimeout(r,0)))};return t=window.setTimeout(r,0),()=>{e=!0,t!==null&&window.clearTimeout(t)}},[ne]);let B=(0,Y.useMemo)(()=>{let e=new Map;for(let t of ne.slice(0,OX))e.set(NX(t),PX(t));return e},[ne]),ie=(0,Y.useMemo)(()=>re.map(e=>({...e,tokens:b.get(NX(e))??B.get(NX(e))??null})),[B,b,re]),V=(0,Y.useMemo)(()=>R.map(e=>({...e,tokens:null})),[R]),H=(0,Y.useMemo)(()=>LX(a.reviewComments),[a.reviewComments]),ae=H.length,oe=n&&!S&&ae>0,se=(0,Y.useCallback)(()=>{o(e=>({...e,activeReviewTarget:null,editingReviewCommentKey:null,reviewDraftInput:``,reviewComments:[]}))},[o]),ce=(0,Y.useCallback)(({filePath:e,changeKey:t,commentKey:r})=>{let i=N.get(r);if(i){o(e=>({...e,selectedDiffPath:i.filePath,activeReviewTarget:null,editingReviewCommentKey:r,reviewDraftInput:i.comment}));return}n&&o(n=>({...n,activeReviewTarget:{filePath:e,changeKey:t,commentKey:r},editingReviewCommentKey:null,reviewDraftInput:``}))},[n,o,N]),le=(0,Y.useCallback)(()=>{o(e=>({...e,activeReviewTarget:null,editingReviewCommentKey:null,reviewDraftInput:``}))},[o]),ue=(0,Y.useCallback)(e=>{let t=N.has(e.commentKey);if(!n&&!t)return;let r=M.trim();if(!r)return;let i=e.change.type===`insert`?null:`oldLineNumber`in e.change?e.change.oldLineNumber:e.change.lineNumber,a=e.change.type===`delete`?null:`newLineNumber`in e.change?e.change.newLineNumber:e.change.lineNumber;o(t=>{let n=new Map(t.reviewComments.map(e=>[lb(e.filePath,e.changeKey),e]));return n.set(e.commentKey,{scope:`uncommitted`,filePath:e.filePath,changeKey:e.changeKey,changeType:e.change.type,oldLineNumber:i,newLineNumber:a,hunkHeader:e.hunk.content,lineContent:e.change.content,diffSnippet:ub(e.hunk,e.change),comment:r}),{...t,activeReviewTarget:null,editingReviewCommentKey:null,reviewDraftInput:``,reviewComments:[...n.values()]}})},[n,o,N,M]),de=(0,Y.useCallback)(e=>{let t=N.get(e);t&&o(n=>({...n,selectedDiffPath:t.filePath,activeReviewTarget:null,editingReviewCommentKey:e,reviewDraftInput:t.comment}))},[o,N]),U=(0,Y.useCallback)(e=>{o(t=>({...t,activeReviewTarget:t.activeReviewTarget?.commentKey===e?null:t.activeReviewTarget,editingReviewCommentKey:t.editingReviewCommentKey===e?null:t.editingReviewCommentKey,reviewDraftInput:t.activeReviewTarget?.commentKey===e||t.editingReviewCommentKey===e?``:t.reviewDraftInput,reviewComments:t.reviewComments.filter(t=>lb(t.filePath,t.changeKey)!==e)}))},[o]),fe=(0,Y.useCallback)(async()=>{if(!oe)return;C(!0);let e=yb({drafts:H,findings:[],githubComments:[],uncommittedFiles:R});try{await i(e),se(),Q.success(AX(`toasts.sendChangesSuccess`),{id:`chat-diff-review-submit-success`})}catch(e){Q.error(FX(e,AX(`errors.sendChanges`)),{id:`chat-diff-review-submit-error`})}finally{C(!1)}},[oe,se,i,R,H]),pe=(0,Y.useCallback)(e=>(0,Z.jsx)(WG,{reviewComments:H,pendingFixCount:ae,triggerMode:e===`wide`?`full`:`compact`,canSendReview:oe,isSubmittingReview:S,reviewSubmitDisabledReason:r??void 0,onClearPendingFixes:se,onSubmitReview:()=>{fe()}}),[oe,se,fe,S,ae,H,r]),me=c?(0,Z.jsx)(q,{type:`button`,size:`icon-sm`,variant:`ghost`,"aria-label":AX(`closeAriaLabel`),className:`text-muted-foreground hover:text-foreground`,onClick:c,children:(0,Z.jsx)(Ve,{className:`h-4 w-4`})}):null,W=l?{"--chat-changes-panel-width":`${l}px`}:void 0;return(0,Z.jsx)(`aside`,{"data-testid":`chat-changes-panel`,"data-desktop-width":l?String(l):void 0,ref:u,style:W,className:K(`flex h-[26rem] min-h-0 w-full shrink-0 flex-col overflow-hidden border-t border-border/70 bg-background/20 xl:h-full xl:border-l xl:border-t-0`,l?`xl:w-[var(--chat-changes-panel-width)]`:`xl:w-[32rem]`),children:(0,Z.jsx)(LK,{selectedDiffPath:O,sidebarFiles:ee,diffResponse:d,isDiffLoading:_,diffError:h,allDiffFiles:V,renderedFiles:ie,viewType:`unified`,onViewTypeChange:()=>{},onRetry:()=>{I()},activeReviewTarget:k,editingReviewCommentKey:A,reviewDraftInstanceKey:j,reviewDraftInput:M,reviewComments:H,reviewFindings:[],githubComments:[],selectedReviewFindingIds:[],selectedGitHubCommentIds:[],canSelectReviewTarget:n,canEditActiveReviewDraft:n,reviewFindingsError:null,gitHubCommentsError:null,hasStaleReviewFindings:!1,onSelectReviewTarget:ce,onToggleReviewFindingSelection:()=>{},onToggleGitHubCommentSelection:()=>{},onReviewDraftInputChange:e=>{o(t=>({...t,reviewDraftInput:e}))},onCancelReviewDraft:le,onEditReviewDraft:de,onRemoveReviewDraft:U,onSaveReviewDraft:ue,diffThemeClassName:UK,resolveFilePath:NX,normalizeDiffPath:jX,emptyStateTitle:AX(`emptyStateTitle`),emptyStateDescription:AX(`emptyStateDescription`),filePickerControl:e=>(0,Z.jsx)(HX,{selectedDiffPath:O,sidebarFiles:ee,diffStats:d?.stats??null,triggerMode:e===`wide`?`full`:`compact`,onSelectDiffPath:e=>{o(t=>({...t,selectedDiffPath:e}))}}),reviewSummaryControl:pe,extraHeaderControl:me,surfaceVariant:`flat`,showViewTypeToggle:!1,gutterVariant:`compact`,isResizing:s,resizePlaceholderLineThreshold:200})})});UX.displayName=`ChatChangesPanel`;var WX=({projectId:e,messages:t,internalLog:n,currentThinkingMessageId:r=null,previousThinkingLog:i=null,previousThinkingMessageId:a=null,pendingAgentTitle:o,streamingResponse:s,isRunning:c,isLoading:l=!1,canShowComposer:u,cardClassName:d,isExternallyResizing:f=!1,pendingAgentRevealKey:p=null,pendingAgentRevealDelayMs:m=0,composerFocusNonce:h=0,blurComposerOnSendStart:g=!1,hidePendingAgentTitle:_=!1,forceScrollToBottomKey:v,header:y,composerControls:b,composerInlineControls:x,composerTheme:S=`default`,layoutKey:C,scrollLayoutKey:w,followUpPrompt:T,draftAttachments:E=[],followUpPlaceholder:D,emptyStateText:O=null,renderMessageFooter:k,isSendingFollowUp:A,isUploadingAttachments:j=!1,canAttachImages:M=!1,followUpDisabledReason:N,onFollowUpPromptChange:P,onFollowUpKeyDown:F,onFollowUpPaste:I,onUploadAttachments:L,onRemoveAttachment:R,onFollowUpSubmit:z})=>(0,Z.jsx)(UN,{projectId:e,messages:t,internalLog:n,currentThinkingMessageId:r,previousThinkingLog:i,previousThinkingMessageId:a,pendingAgentTitle:o,streamingResponse:s,isRunning:c,isLoading:l,autoScrollBehavior:`sticky`,surfaceVariant:`chat`,canShowComposer:u,cardClassName:d,header:y,composerControls:b,composerInlineControls:x,composerTheme:S,composerSize:`compact-on-laptop`,showThinkingPlacement:`header`,pinComposerToBottom:!0,isExternallyResizing:f,pendingAgentRevealKey:p,pendingAgentRevealDelayMs:m,composerFocusNonce:h,blurComposerOnSendStart:g,forceScrollToBottomKey:v,layoutKey:C,scrollLayoutKey:w,followUpPrompt:T,draftAttachments:E,followUpPlaceholder:D,emptyStateText:O,autoFocusComposer:!0,renderMessageFooter:k,isSendingFollowUp:A,isUploadingAttachments:j,canAttachImages:M,followUpDisabledReason:N,hidePendingAgentTitle:_,onFollowUpPromptChange:P,onFollowUpKeyDown:F,onFollowUpPaste:I,onUploadAttachments:L,onRemoveAttachment:R,onFollowUpSubmit:z}),GX=({value:e,disabled:t=!1,onChange:n,planInactiveTooltip:r,buildInactiveTooltip:i})=>(0,Z.jsx)(Sc,{value:e,items:[{value:`plan`,label:`Plan`,activeVariant:`ghost`,activeClassName:`border-transparent bg-sky-300 text-[#07111a] shadow-[0_10px_30px_rgba(125,211,252,0.24)] hover:bg-sky-200 hover:text-[#07111a]`,inactiveClassName:`border-transparent text-white/85 hover:bg-white/8 hover:text-white`,inactiveTooltip:r},{value:`build`,label:`Build`,activeVariant:`ghost`,activeClassName:`border-transparent bg-emerald-400 text-[#07130d] shadow-[0_10px_30px_rgba(16,185,129,0.28)] hover:bg-emerald-300 hover:text-[#07130d]`,inactiveClassName:`border-transparent text-white/85 hover:bg-white/8 hover:text-white`,inactiveTooltip:i}],disabled:t,onChange:n}),KX={default:`h-5 rounded-md border-amber-500/40 bg-amber-500/10 px-1.5 text-[10px] uppercase tracking-[0.16em] text-amber-200`,muted:`h-5 rounded-md border-amber-500/40 bg-amber-500/10 px-1.5 text-[10px] uppercase tracking-[0.16em] text-amber-100`},qX=({tone:e=`default`,className:t,children:n,...r})=>(0,Z.jsx)(U,{variant:`outline`,className:K(KX[e],t),...r,children:n}),JX=(e,t)=>Pe.t(`projects:memory.${e}`,t),YX=e=>JX(`stageLabels.${e}`),XX=e=>JX(`priorityLabels.${e}`),ZX=()=>({kind:`decision`,title:``,scope:``,content:``,rationale:``,implications:``,stages:``,priority:`normal`}),QX=e=>e.kind===`convention`?{kind:`convention`,title:e.title,scope:e.scope??``,content:e.instruction,rationale:e.rationale??``,implications:``,stages:e.stages.join(`
|
|
146
|
+
`),[o,N]),fe=dK({count:le?o.length:0,getScrollElement:()=>H.current,estimateSize:()=>pK,overscan:mK,getItemKey:e=>{let t=o[e];return t?`${N(t)}:${t.type??`modify`}`:e},initialRect:{width:0,height:900}}),pe=(0,Y.useMemo)(()=>new Map(n?.files.map(e=>[e.path,e])??[]),[n?.files]),me=(0,Y.useMemo)(()=>NK({allDiffFiles:a,resolveFilePath:N,normalizeDiffPath:P,reviewFindings:C?[]:h}),[a,C,P,N,h]),W=(0,Y.useMemo)(()=>PK({allDiffFiles:a,resolveFilePath:N,normalizeDiffPath:P,githubComments:g}),[a,g,P,N]);(0,Y.useEffect)(()=>{let e=H.current;e&&(e.scrollTop=0)},[e]),(0,Y.useEffect)(()=>{let e=H.current;return()=>{window.getSelection()?.removeAllRanges(),e&&(e.scrollTop=0)}},[de]);let he=fe.getVirtualItems(),G=(0,Y.useMemo)(()=>le?he.map(e=>N(o[e.index])):o.map(e=>N(e)),[o,N,le,he]);(0,Y.useEffect)(()=>{V?.(G)},[V,G]);let ge=le&&he.length>0?he[0]?.start??0:0,_e=le&&he.length>0?Math.max(0,fe.getTotalSize()-(he[he.length-1]?.end??0)):0,ve=le?he.map(e=>({file:o[e.index],virtualItem:e})):o.map(e=>({file:e,virtualItem:null})),ye=e===`all`?null:t.find(t=>t.path===e)??null,be=e===`all`?_K({additions:n?.stats?.additions??0,deletions:n?.stats?.deletions??0,fileCount:n?.stats?.files_changed??null}):ye?_K({additions:ye.additions,deletions:ye.deletions,fileCount:null}):[],xe=(0,Y.useMemo)(()=>ne?(0,Z.jsxs)(LG,{type:`single`,size:`sm`,variant:`outline`,value:s,onValueChange:e=>{(e===`split`||e===`unified`)&&c(e)},children:[(0,Z.jsx)(RG,{value:`unified`,children:hK(`viewType.unified`)}),(0,Z.jsx)(RG,{value:`split`,children:hK(`viewType.split`)})]}):null,[c,ne,s]),Se=(0,Y.useMemo)(()=>[vK({control:L,mode:ae}),vK({control:R,mode:ae})].filter(Boolean),[L,ae,R]),Ce=xe||Se.length>0||z;return(0,Z.jsxs)(`section`,{className:K(`flex min-h-0 flex-1 flex-col overflow-hidden`,te===`default`?`rounded-2xl border border-border bg-background/30`:`bg-transparent`),children:[(0,Z.jsx)(`div`,{ref:oe,"data-responsive-mode":ae,"data-testid":`ticket-diff-header`,className:K(`grid min-w-0 items-start gap-x-3 gap-y-2 border-b px-4 py-3`,te===`default`?`border-border`:`border-border/70 px-3`,ee===`stacked`?z?`grid-cols-[minmax(0,1fr)_auto]`:`grid-cols-[minmax(0,1fr)]`:Ce?`grid-cols-[minmax(0,1fr)_auto]`:`grid-cols-[minmax(0,1fr)]`),children:ee===`stacked`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{"data-testid":`ticket-diff-header-left`,className:`grid min-w-0 gap-2`,children:[(0,Z.jsxs)(`div`,{"data-testid":`ticket-diff-header-info`,className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:e===`all`?hK(`header.allChanges`):e}),be.length>0&&(0,Z.jsx)(`div`,{className:`mt-1 flex items-center gap-3 whitespace-nowrap text-xs`,children:be.map(e=>(0,Z.jsx)(`span`,{className:e.className,children:e.content},e.key))})]}),xe||Se.length>0?(0,Z.jsxs)(`div`,{"data-testid":`ticket-diff-header-controls`,className:`flex min-w-0 flex-wrap items-center gap-2 justify-start`,children:[xe?(0,Z.jsx)(`div`,{"data-testid":`ticket-diff-header-primary-controls`,className:`shrink-0`,children:xe}):null,Se.length>0?(0,Z.jsx)(`div`,{"data-testid":`ticket-diff-header-secondary-controls`,className:`flex min-w-0 items-center gap-2 justify-start`,children:Se.map((e,t)=>(0,Z.jsx)(`div`,{className:`min-w-0 shrink-0`,children:e},`header-secondary-control-${t+1}`))}):null]}):null]}),z?(0,Z.jsx)(`div`,{"data-testid":`ticket-diff-header-close`,className:`flex shrink-0 items-start justify-end`,children:z}):null]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{"data-testid":`ticket-diff-header-info`,className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:e===`all`?hK(`header.allChanges`):e}),be.length>0&&(0,Z.jsx)(`div`,{className:`mt-1 flex items-center gap-3 whitespace-nowrap text-xs`,children:be.map(e=>(0,Z.jsx)(`span`,{className:e.className,children:e.content},e.key))})]}),Ce?(0,Z.jsxs)(`div`,{"data-testid":`ticket-diff-header-inline-controls`,className:`flex min-w-0 flex-wrap items-start justify-end gap-2`,children:[xe?(0,Z.jsx)(`div`,{"data-testid":`ticket-diff-header-primary-controls`,className:`shrink-0`,children:xe}):null,Se.length>0?(0,Z.jsx)(`div`,{"data-testid":`ticket-diff-header-secondary-controls`,className:`flex min-w-0 flex-wrap items-center justify-end gap-2`,children:Se.map((e,t)=>(0,Z.jsx)(`div`,{className:`min-w-0 shrink-0`,children:e},`header-secondary-control-${t+1}`))}):null,z?(0,Z.jsx)(`div`,{"data-testid":`ticket-diff-header-close`,className:`flex shrink-0 items-start justify-end`,children:z}):null]}):null]})}),(0,Z.jsx)(`div`,{ref:H,"data-testid":`ticket-diff-scroll-region`,className:`min-h-0 flex-1 overflow-auto`,children:(0,Z.jsxs)(`div`,{className:K(`min-h-full pb-4 pt-4`,te===`default`?`px-4`:`px-0`),children:[r&&(0,Z.jsx)(`div`,{className:`flex h-full min-h-48 items-center justify-center text-sm text-muted-foreground`,children:hK(`states.loading`)}),!r&&i&&(0,Z.jsxs)(`div`,{className:`flex h-full min-h-48 flex-col items-center justify-center gap-4 text-center`,children:[(0,Z.jsx)(`p`,{className:`max-w-md text-sm text-rose-300`,children:i}),(0,Z.jsx)(q,{type:`button`,variant:`outline`,onClick:l,children:hK(`states.retry`)})]}),!r&&!i&&n&&!se&&(0,Z.jsxs)(`div`,{className:`flex h-full min-h-48 flex-col items-center justify-center gap-2 text-center`,children:[(0,Z.jsx)(`div`,{className:`text-sm text-foreground`,children:F}),I&&(0,Z.jsx)(`div`,{className:`max-w-md text-xs text-muted-foreground`,children:I})]}),!r&&!i&&n&&se&&e!==`all`&&o.length===0&&(0,Z.jsxs)(`div`,{className:`flex h-full min-h-48 flex-col items-center justify-center gap-3 text-center`,children:[(0,Z.jsx)(`div`,{className:`text-sm text-foreground`,children:hK(`states.noRenderableFileTitle`)}),(0,Z.jsx)(`div`,{className:`max-w-md text-xs text-muted-foreground`,children:e})]}),!r&&!i&&n&&se&&o.length>0&&ue&&(0,Z.jsx)(gK,{}),!r&&!i&&n&&se&&o.length>0&&!ue&&(0,Z.jsxs)(`div`,{className:K(`archon-diff-viewer`,re===`compact`&&`archon-diff-viewer--compact-gutter`,e===`all`&&te===`default`&&`space-y-6`,e===`all`&&te===`flat`&&`space-y-0`,M),children:[x&&(0,Z.jsx)(`div`,{className:`rounded-xl border border-dashed border-border bg-background/40 px-4 py-3 text-xs text-muted-foreground`,children:x}),S&&(0,Z.jsx)(`div`,{className:`rounded-xl border border-dashed border-border bg-background/40 px-4 py-3 text-xs text-muted-foreground`,children:S}),me.globalFindings.length>0&&(0,Z.jsxs)(`section`,{className:`rounded-xl border border-border bg-card/70 p-3`,children:[(0,Z.jsx)(`div`,{className:`mb-3 text-sm font-semibold text-foreground`,children:hK(`reviewFinding.sectionTitle`)}),(0,Z.jsx)(`div`,{className:`space-y-3`,children:me.globalFindings.map(e=>(0,Z.jsx)(OK,{finding:e,isSelected:_.includes(e.id),onToggle:()=>{T(e.id)}},e.id))})]}),e===`all`&&W.fallbackComments.length>0&&(0,Z.jsxs)(`section`,{className:`rounded-xl border border-border bg-card/70 p-3`,children:[(0,Z.jsx)(`div`,{className:`mb-3 text-sm font-semibold text-foreground`,children:hK(`githubComment.sectionTitle`)}),(0,Z.jsx)(`div`,{className:`space-y-3`,children:W.fallbackComments.map(e=>(0,Z.jsx)(MK,{comment:e,isSelected:v.includes(e.id),onToggle:()=>{E(e.id)}},e.id))})]}),ge>0&&(0,Z.jsx)(`div`,{style:{height:ge}}),ve.map(({file:t,virtualItem:n})=>{let r=N(t),i=pe.get(r),a=IK(t.hunks),o=me.inlineByFilePath.get(r)??new Map,c=W.inlineByFilePath.get(r)??new Map,l=me.fileLevelByFilePath.get(r)??[],h=W.fileLevelByFilePath.get(r)??[],g=d?m.find(e=>lb(e.filePath,e.changeKey)===d)??null:null,x=[...m.filter(e=>e.filePath===r).map(e=>e.changeKey),...u?.filePath===r?[u.changeKey]:[],...g?.filePath===r?[g.changeKey]:[]],S=FK({filePath:r,hunks:t.hunks,activeReviewTarget:u,editingReviewCommentKey:d,reviewDraftInstanceKey:f,reviewDraftInput:p,reviewComments:m,reviewFindingsByChangeKey:o,githubCommentsByChangeKey:c,selectedReviewFindingIds:_,selectedGitHubCommentIds:v,canEditActiveReviewDraft:b,onToggleReviewFindingSelection:T,onToggleGitHubCommentSelection:E,onReviewDraftInputChange:D,onCancelReviewDraft:O,onEditReviewDraft:k,onRemoveReviewDraft:A,onSaveReviewDraft:j}),C=(0,Z.jsx)(Yv,{diffType:t.type,hunks:t.hunks,tokens:t.tokens,viewType:s,selectedChanges:[...new Set(x)],widgets:S,renderGutter:({change:e,side:t,renderDefault:n,wrapInAnchor:i,inHoverState:o})=>{if(!e)return i(n());let c=lv(e),l=t===`new`,u=y&&t===`new`,d=s===`unified`&&e.type===`normal`&&t===`new`?null:i(n());return(0,Z.jsxs)(`div`,{className:K(`flex items-center justify-end pr-1`,re===`compact`?`gap-1 pr-0.5`:`gap-2`),children:[d,l&&(0,Z.jsx)(`span`,{"data-diff-gutter-action-slot":`true`,className:[re===`compact`?`flex size-5 shrink-0 items-center justify-center rounded-md border border-emerald-300/80 bg-emerald-400 text-[#07130d] shadow-[0_8px_20px_rgba(16,185,129,0.22)] transition-all`:`flex size-6 shrink-0 items-center justify-center rounded-md border border-emerald-300/80 bg-emerald-400 text-[#07130d] shadow-[0_8px_20px_rgba(16,185,129,0.22)] transition-all`,u&&o?`border-emerald-200 bg-emerald-300 opacity-100`:`opacity-0 pointer-events-none`].join(` `),"aria-hidden":`true`,onClick:t=>{if(t.stopPropagation(),!y||!e)return;let n=a.get(c);n&&w({filePath:r,changeKey:c,commentKey:lb(r,c),hunk:n.hunk,change:n.change})},children:(0,Z.jsx)(zl,{className:re===`compact`?`h-3 w-3`:`h-3.5 w-3.5`})}),(0,Z.jsx)(`span`,{className:`sr-only`,children:c})]})},children:e=>e.map(e=>(0,Z.jsx)(Wv,{hunk:e},`${r}-${e.content}`))});return e===`all`?(0,Z.jsx)(`div`,{"data-index":n?.index,ref:n?fe.measureElement:void 0,children:(0,Z.jsxs)(`section`,{className:K(te===`default`?`rounded-xl border border-border bg-card/70`:`border-t border-border/70 bg-transparent first:border-t-0`),children:[(0,Z.jsxs)(`div`,{className:K(`sticky top-0 z-20 border-b text-xs font-medium text-foreground`,te===`default`?`rounded-t-xl border-border bg-card px-4 py-3`:`border-border/70 bg-background/95 px-3 py-2.5 backdrop-blur-sm`),children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[`oldPath`in t&&typeof t.oldPath==`string`&&P(t.oldPath)===`/dev/null`&&(0,Z.jsx)(U,{variant:`success`,className:`shrink-0`,children:hK(`fileBadge.newFile`)}),(0,Z.jsx)(`span`,{children:r})]}),i&&(0,Z.jsxs)(`div`,{className:`mt-1 flex items-center gap-2 text-xs`,children:[(0,Z.jsxs)(`span`,{className:`font-mono text-emerald-400`,children:[`+`,i.additions]}),(0,Z.jsxs)(`span`,{className:`font-mono text-rose-400`,children:[`-`,i.deletions]})]})]}),(0,Z.jsxs)(`div`,{className:K(`overflow-x-auto`,te===`default`?`p-3`:`px-0 py-3`),children:[l.length>0&&(0,Z.jsx)(`div`,{className:K(`mb-3 space-y-3`,te===`flat`&&`px-3`),children:l.map(e=>(0,Z.jsx)(OK,{finding:e,isSelected:_.includes(e.id),onToggle:()=>{T(e.id)}},e.id))}),h.length>0&&(0,Z.jsx)(`div`,{className:K(`mb-3 space-y-3`,te===`flat`&&`px-3`),children:h.map(e=>(0,Z.jsx)(MK,{comment:e,isSelected:v.includes(e.id),onToggle:()=>{E(e.id)}},e.id))}),C]})]})},`${r}-${t.type??`modify`}`):(0,Z.jsxs)(`div`,{"data-index":n?.index,ref:n?fe.measureElement:void 0,children:[l.length>0&&(0,Z.jsx)(`div`,{className:`mb-3 space-y-3`,children:l.map(e=>(0,Z.jsx)(OK,{finding:e,isSelected:_.includes(e.id),onToggle:()=>{T(e.id)}},e.id))}),h.length>0&&(0,Z.jsx)(`div`,{className:`mb-3 space-y-3`,children:h.map(e=>(0,Z.jsx)(MK,{comment:e,isSelected:v.includes(e.id),onToggle:()=>{E(e.id)}},e.id))}),C]},`${r}-${t.type??`modify`}`)}),_e>0&&(0,Z.jsx)(`div`,{style:{height:_e}})]})]})})]})});LK.displayName=`TicketChangesDiffPanel`;var RK=e=>K(`group`,e?`border-sky-700 bg-card/95 shadow-sm`:`border-border/50 bg-transparent text-muted-foreground hover:border-border/80 hover:bg-accent/60 hover:text-accent-foreground hover:shadow-sm`),zK={modified:`border-amber-500/40 bg-amber-500/10 text-amber-200`,added:`border-emerald-500/40 bg-emerald-500/10 text-emerald-200`,deleted:`border-rose-500/40 bg-rose-500/10 text-rose-200`,renamed:`border-sky-500/40 bg-sky-500/10 text-sky-200`,untracked:`border-violet-500/40 bg-violet-500/10 text-violet-200`,typechanged:`border-slate-500/40 bg-slate-500/10 text-slate-200`},BK={modified:`Modified`,added:`Added`,deleted:`Deleted`,renamed:`Renamed`,untracked:`Untracked`,typechanged:`Type changed`},VK=e=>{let t=e.split(/[\\/]/);return t[t.length-1]||e},HK=({selectionWarning:e,gitError:t,sidebarFiles:n,commentCountByPath:r,commentCountTone:i,isGitStatusLoading:a,selectedPaths:o,selectedDiffPath:s,allFilesSelected:c,diffStats:l,title:u=`Changed files`,allChangesDescription:d=`Review the full workspace diff.`,enableSelection:f=!0,onToggleSelectAll:p,onSelectDiffPath:m,onTogglePath:h})=>{let g=i===`bundle_diff`?`rounded-full border border-violet-400/40 bg-violet-400/12 px-1.5 py-0.5 text-[10px] font-semibold leading-none text-violet-100`:`rounded-full border border-sky-400/40 bg-sky-400/12 px-1.5 py-0.5 text-[10px] font-semibold leading-none text-sky-100`;return(0,Z.jsxs)(`aside`,{className:`flex min-h-0 h-full flex-col between overflow-hidden rounded-2xl border border-border bg-background/40`,children:[(e||t)&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 border-b border-border p-4`,children:[e&&(0,Z.jsx)(`div`,{className:`rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm text-amber-100`,children:e}),t&&(0,Z.jsx)(`div`,{className:`rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm text-amber-100`,children:t})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-sm font-semibold text-foreground`,children:u}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[n.length,` file`,n.length===1?``:`s`,` changed`]})]}),f&&(0,Z.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:p,disabled:n.length===0,children:c?`Unselect all`:`Select all`})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto p-3`,children:[a&&(0,Z.jsx)(`div`,{className:`flex h-full min-h-48 items-center justify-center text-sm text-muted-foreground`,children:`Loading file list...`}),!a&&n.length===0&&(0,Z.jsx)(`div`,{className:`flex h-full min-h-48 items-center justify-center text-sm text-muted-foreground`,children:`No changes to review.`}),!a&&n.length>0&&(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{m(`all`)},className:K(`flex w-full cursor-pointer items-start justify-between gap-3 rounded-xl border px-2.5 py-2 text-left transition-colors`,RK(s===`all`)),children:(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-semibold text-foreground`,children:`All changes`}),l&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3 text-[11px]`,children:[(0,Z.jsxs)(`span`,{className:`text-muted-foreground transition-colors group-hover:text-foreground/70`,children:[l.files_changed,` file`,l.files_changed===1?``:`s`]}),(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-emerald-400`,children:[`+`,l.additions]}),(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-rose-400`,children:[`-`,l.deletions]})]})]}),(0,Z.jsx)(`div`,{className:`mt-1 flex w-full flex-1 text-xs text-muted-foreground transition-colors group-hover:text-foreground/70`,children:d})]})}),n.map(e=>{let t=f&&o.has(e.path),n=s===e.path,i=r.get(e.path)??0;return(0,Z.jsxs)(`div`,{className:K(`relative flex cursor-pointer items-start gap-2.5 rounded-xl border px-2.5 py-2 transition-colors`,RK(n)),children:[(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Open diff for ${e.path}`,onClick:()=>{m(e.path)},className:`absolute inset-0 cursor-pointer rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background`}),f&&(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":e.path,checked:t,onChange:()=>{h(e.path)},className:`relative z-10 mt-0.5 h-4 w-4 rounded border-border bg-background text-primary`}),(0,Z.jsxs)(`div`,{className:`relative z-10 min-w-0 flex-1 cursor-pointer text-left pointer-events-none`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex flex-1 items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 truncate font-mono text-xs text-foreground`,children:VK(e.path)}),i>0&&(0,Z.jsx)(`span`,{"aria-label":`${i} comment${i===1?``:`s`} in ${e.path}`,className:g,children:i})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3 text-[11px]`,children:[(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-emerald-400`,children:[`+`,e.additions]}),(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-rose-400`,children:[`-`,e.deletions]})]})]}),(0,Z.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap items-center gap-1.5 text-[11px]`,children:[e.status&&(0,Z.jsx)(U,{variant:`outline`,className:zK[e.status],children:BK[e.status]}),e.staged&&(0,Z.jsx)(U,{variant:`outline`,children:`Staged`}),e.unstaged&&(0,Z.jsx)(U,{variant:`outline`,children:`Unstaged`}),e.conflicted&&(0,Z.jsx)(U,{variant:`destructive`,children:`Conflicted`}),e.originalPath&&(0,Z.jsx)(`span`,{className:`break-all font-mono text-[11px] text-muted-foreground transition-colors group-hover:text-foreground/70`,children:e.status===`renamed`?`from ${e.originalPath}`:e.originalPath})]})]})]},`${e.path}:${e.originalPath??``}`)})]})]})]})},UK=[`[--diff-background-color:transparent]`,`[--diff-text-color:rgb(226_232_240)]`,`[--diff-selection-background-color:rgba(148,163,184,0.2)]`,`[--diff-gutter-insert-background-color:rgba(34,197,94,0.16)]`,`[--diff-gutter-delete-background-color:rgba(244,63,94,0.16)]`,`[--diff-gutter-selected-background-color:rgba(148,163,184,0.12)]`,`[--diff-code-insert-background-color:rgba(34,197,94,0.08)]`,`[--diff-code-delete-background-color:rgba(244,63,94,0.08)]`,`[--diff-code-insert-edit-background-color:rgba(34,197,94,0.22)]`,`[--diff-code-delete-edit-background-color:rgba(244,63,94,0.22)]`,`[--diff-code-selected-background-color:rgba(148,163,184,0.12)]`,`[--diff-font-family:var(--font-mono)]`,`[&_.diff]:w-full`,`[&_.diff]:border-collapse`,`[&_.diff]:font-mono`,`[&_.diff-code]:whitespace-pre-wrap`,`[&_.diff-code]:break-words`,`[&_.diff-gutter]:select-none`].join(` `),WK=25e4,GK=2e3,KK=new Map,qK=e=>e?e.split(`
|
|
147
|
+
`).length:0,JK=e=>{let t=e.diff??``;return t?t.length<=WK&&qK(t)<=GK:!0},YK=({scope:e,projectId:t,ticketId:n,projectTargetBundleId:r=null})=>e===`project_root`?t?`project_root:${t}:${r??`repo_root`}`:null:n?`ticket:${t??`none`}:${n}`:null,XK=e=>e?KK.get(e)??null:null,ZK=({cacheKey:e,diffResponse:t,gitStatus:n})=>{let r=n.workspace_signature?.trim();if(!(!e||!r)){if(!JK(t)){KK.delete(e);return}KK.set(e,{diffResponse:t,gitStatus:n,workspaceSignature:r})}},QK=e=>{e&&KK.delete(e)},$K={css:`css`,html:`markup`,htm:`markup`,js:`javascript`,jsx:`jsx`,json:`json`,md:`markdown`,markdown:`markdown`,sh:`bash`,ts:`typescript`,tsx:`tsx`,yaml:`yaml`,yml:`yaml`},eq=e=>{if(!e)return null;let t=e.split(` -> `),n=t[t.length-1]??e,r=n.split(`/`),i=r[r.length-1]??n,a=``;if(i.includes(`.`)){let e=i.split(`.`);a=e[e.length-1]?.toLowerCase()??``}return $K[a]??null},tq=new Set,nq=e=>{e&&tq.forEach(t=>t(e))},rq=e=>(tq.add(e),()=>{tq.delete(e)}),iq=300,aq=(e,t={})=>{let n=t.dedupeMs??iq,r=0,i=()=>{if(document.visibilityState!==`visible`)return;let t=Date.now();t-r<n||(r=t,e())};return window.addEventListener(`focus`,i),document.addEventListener(`visibilitychange`,i),()=>{window.removeEventListener(`focus`,i),document.removeEventListener(`visibilitychange`,i)}},oq=i(((e,t)=>{t.exports=r;var n=Object.prototype.hasOwnProperty;function r(){for(var e={},t=0;t<arguments.length;t++){var r=arguments[t];for(var i in r)n.call(r,i)&&(e[i]=r[i])}return e}})),sq=i(((e,t)=>{t.exports=r;var n=r.prototype;n.space=null,n.normal={},n.property={};function r(e,t,n){this.property=e,this.normal=t,n&&(this.space=n)}})),cq=i(((e,t)=>{var n=oq(),r=sq();t.exports=i;function i(e){for(var t=e.length,i=[],a=[],o=-1,s,c;++o<t;)s=e[o],i.push(s.property),a.push(s.normal),c=s.space;return new r(n.apply(null,i),n.apply(null,a),c)}})),lq=i(((e,t)=>{t.exports=n;function n(e){return e.toLowerCase()}})),uq=i(((e,t)=>{t.exports=r;var n=r.prototype;n.space=null,n.attribute=null,n.property=null,n.boolean=!1,n.booleanish=!1,n.overloadedBoolean=!1,n.number=!1,n.commaSeparated=!1,n.spaceSeparated=!1,n.commaOrSpaceSeparated=!1,n.mustUseProperty=!1,n.defined=!1;function r(e,t){this.property=e,this.attribute=t}})),dq=i((e=>{var t=0;e.boolean=n(),e.booleanish=n(),e.overloadedBoolean=n(),e.number=n(),e.spaceSeparated=n(),e.commaSeparated=n(),e.commaOrSpaceSeparated=n();function n(){return 2**++t}})),fq=i(((e,t)=>{var n=uq(),r=dq();t.exports=o,o.prototype=new n,o.prototype.defined=!0;var i=[`boolean`,`booleanish`,`overloadedBoolean`,`number`,`commaSeparated`,`spaceSeparated`,`commaOrSpaceSeparated`],a=i.length;function o(e,t,o,c){var l=-1,u;for(s(this,`space`,c),n.call(this,e,t);++l<a;)u=i[l],s(this,u,(o&r[u])===r[u])}function s(e,t,n){n&&(e[t]=n)}})),pq=i(((e,t)=>{var n=lq(),r=sq(),i=fq();t.exports=a;function a(e){var t=e.space,a=e.mustUseProperty||[],o=e.attributes||{},s=e.properties,c=e.transform,l={},u={},d,f;for(d in s)f=new i(d,c(o,d),s[d],t),a.indexOf(d)!==-1&&(f.mustUseProperty=!0),l[d]=f,u[n(d)]=d,u[n(f.attribute)]=d;return new r(l,u,t)}})),mq=i(((e,t)=>{t.exports=pq()({space:`xlink`,transform:n,properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null}});function n(e,t){return`xlink:`+t.slice(5).toLowerCase()}})),hq=i(((e,t)=>{t.exports=pq()({space:`xml`,transform:n,properties:{xmlLang:null,xmlBase:null,xmlSpace:null}});function n(e,t){return`xml:`+t.slice(3).toLowerCase()}})),gq=i(((e,t)=>{t.exports=n;function n(e,t){return t in e?e[t]:t}})),_q=i(((e,t)=>{var n=gq();t.exports=r;function r(e,t){return n(e,t.toLowerCase())}})),vq=i(((e,t)=>{t.exports=pq()({space:`xmlns`,attributes:{xmlnsxlink:`xmlns:xlink`},transform:_q(),properties:{xmlns:null,xmlnsXLink:null}})})),yq=i(((e,t)=>{var n=dq(),r=pq(),i=n.booleanish,a=n.number,o=n.spaceSeparated;t.exports=r({transform:s,properties:{ariaActiveDescendant:null,ariaAtomic:i,ariaAutoComplete:null,ariaBusy:i,ariaChecked:i,ariaColCount:a,ariaColIndex:a,ariaColSpan:a,ariaControls:o,ariaCurrent:null,ariaDescribedBy:o,ariaDetails:null,ariaDisabled:i,ariaDropEffect:o,ariaErrorMessage:null,ariaExpanded:i,ariaFlowTo:o,ariaGrabbed:i,ariaHasPopup:null,ariaHidden:i,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:o,ariaLevel:a,ariaLive:null,ariaModal:i,ariaMultiLine:i,ariaMultiSelectable:i,ariaOrientation:null,ariaOwns:o,ariaPlaceholder:null,ariaPosInSet:a,ariaPressed:i,ariaReadOnly:i,ariaRelevant:null,ariaRequired:i,ariaRoleDescription:o,ariaRowCount:a,ariaRowIndex:a,ariaRowSpan:a,ariaSelected:i,ariaSetSize:a,ariaSort:null,ariaValueMax:a,ariaValueMin:a,ariaValueNow:a,ariaValueText:null,role:null}});function s(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}})),bq=i(((e,t)=>{var n=dq(),r=pq(),i=_q(),a=n.boolean,o=n.overloadedBoolean,s=n.booleanish,c=n.number,l=n.spaceSeparated,u=n.commaSeparated;t.exports=r({space:`html`,attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},transform:i,mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:u,acceptCharset:l,accessKey:l,action:null,allow:null,allowFullScreen:a,allowPaymentRequest:a,allowUserMedia:a,alt:null,as:null,async:a,autoCapitalize:null,autoComplete:l,autoFocus:a,autoPlay:a,capture:a,charSet:null,checked:a,cite:null,className:l,cols:c,colSpan:null,content:null,contentEditable:s,controls:a,controlsList:l,coords:c|u,crossOrigin:null,data:null,dateTime:null,decoding:null,default:a,defer:a,dir:null,dirName:null,disabled:a,download:o,draggable:s,encType:null,enterKeyHint:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:a,formTarget:null,headers:l,height:c,hidden:a,high:c,href:null,hrefLang:null,htmlFor:l,httpEquiv:l,id:null,imageSizes:null,imageSrcSet:u,inputMode:null,integrity:null,is:null,isMap:a,itemId:null,itemProp:l,itemRef:l,itemScope:a,itemType:l,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:a,low:c,manifest:null,max:null,maxLength:c,media:null,method:null,min:null,minLength:c,multiple:a,muted:a,name:null,nonce:null,noModule:a,noValidate:a,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforePrint:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextMenu:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:a,optimum:c,pattern:null,ping:l,placeholder:null,playsInline:a,poster:null,preload:null,readOnly:a,referrerPolicy:null,rel:l,required:a,reversed:a,rows:c,rowSpan:c,sandbox:l,scope:null,scoped:a,seamless:a,selected:a,shape:null,size:c,sizes:null,slot:null,span:c,spellCheck:s,src:null,srcDoc:null,srcLang:null,srcSet:u,start:c,step:null,style:null,tabIndex:c,target:null,title:null,translate:null,type:null,typeMustMatch:a,useMap:null,value:s,width:c,wrap:null,align:null,aLink:null,archive:l,axis:null,background:null,bgColor:null,border:c,borderColor:null,bottomMargin:c,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:a,declare:a,event:null,face:null,frame:null,frameBorder:null,hSpace:c,leftMargin:c,link:null,longDesc:null,lowSrc:null,marginHeight:c,marginWidth:c,noResize:a,noHref:a,noShade:a,noWrap:a,object:null,profile:null,prompt:null,rev:null,rightMargin:c,rules:null,scheme:null,scrolling:s,standby:null,summary:null,text:null,topMargin:c,valueType:null,version:null,vAlign:null,vLink:null,vSpace:c,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:a,disableRemotePlayback:a,prefix:null,property:null,results:c,security:null,unselectable:null}})})),xq=i(((e,t)=>{var n=cq(),r=mq();t.exports=n([hq(),r,vq(),yq(),bq()])})),Sq=i(((e,t)=>{var n=lq(),r=fq(),i=uq(),a=`data`;t.exports=l;var o=/^data[-\w.:]+$/i,s=/-[a-z]/g,c=/[A-Z]/g;function l(e,t){var s=n(t),c=t,l=i;return s in e.normal?e.property[e.normal[s]]:(s.length>4&&s.slice(0,4)===a&&o.test(t)&&(t.charAt(4)===`-`?c=u(t):t=d(t),l=r),new l(c,t))}function u(e){var t=e.slice(5).replace(s,p);return a+t.charAt(0).toUpperCase()+t.slice(1)}function d(e){var t=e.slice(4);return s.test(t)?e:(t=t.replace(c,f),t.charAt(0)!==`-`&&(t=`-`+t),a+t)}function f(e){return`-`+e.toLowerCase()}function p(e){return e.charAt(1).toUpperCase()}})),Cq=i(((e,t)=>{t.exports=r;var n=/[#.]/g;function r(e,t){for(var r=e||``,i=t||`div`,a={},o=0,s,c,l;o<r.length;)n.lastIndex=o,l=n.exec(r),s=r.slice(o,l?l.index:r.length),s&&(c?c===`#`?a.id=s:a.className?a.className.push(s):a.className=[s]:i=s,o+=s.length),l&&(c=l[0],o++);return{type:`element`,tagName:i,properties:a,children:[]}}})),wq=i((e=>{e.parse=i,e.stringify=a;var t=``,n=` `,r=/[ \t\n\r\f]+/g;function i(e){var n=String(e||t).trim();return n===t?[]:n.split(r)}function a(e){return e.join(n).trim()}})),Tq=i((e=>{e.parse=i,e.stringify=a;var t=`,`,n=` `,r=``;function i(e){for(var n=[],i=String(e||r),a=i.indexOf(t),o=0,s=!1,c;!s;)a===-1&&(a=i.length,s=!0),c=i.slice(o,a).trim(),(c||!s)&&n.push(c),o=a+1,a=i.indexOf(t,o);return n}function a(e,i){var a=i||{},o=a.padLeft===!1?r:n,s=a.padRight?n:r;return e[e.length-1]===r&&(e=e.concat(r)),e.join(s+t+o).trim()}})),Eq=i(((e,t)=>{var n=Sq(),r=lq(),i=Cq(),a=wq().parse,o=Tq().parse;t.exports=c;var s={}.hasOwnProperty;function c(e,t,r){var c=r?h(r):null;return u;function u(e,n){var r=i(e,t),a=Array.prototype.slice.call(arguments,2),o=r.tagName.toLowerCase(),u;if(r.tagName=c&&s.call(c,o)?c[o]:o,n&&l(n,r)&&(a.unshift(n),n=null),n)for(u in n)p(r.properties,u,n[u]);return d(r.children,a),r.tagName===`template`&&(r.content={type:`root`,children:r.children},r.children=[]),r}function p(t,r,i){var s,c,l;i==null||i!==i||(s=n(e,r),c=s.property,l=i,typeof l==`string`&&(s.spaceSeparated?l=a(l):s.commaSeparated?l=o(l):s.commaOrSpaceSeparated&&(l=a(o(l).join(` `)))),c===`style`&&typeof i!=`string`&&(l=m(l)),c===`className`&&t.className&&(l=t.className.concat(l)),t[c]=f(s,c,l))}}function l(e,t){return typeof e==`string`||`length`in e||u(t.tagName,e)}function u(e,t){var n=t.type;return e===`input`||!n||typeof n!=`string`?!1:typeof t.children==`object`&&`length`in t.children?!0:(n=n.toLowerCase(),e===`button`?n!==`menu`&&n!==`submit`&&n!==`reset`&&n!==`button`:`value`in t)}function d(e,t){var n,r;if(typeof t==`string`||typeof t==`number`){e.push({type:`text`,value:String(t)});return}if(typeof t==`object`&&`length`in t){for(n=-1,r=t.length;++n<r;)d(e,t[n]);return}if(typeof t!=`object`||!(`type`in t))throw Error("Expected node, nodes, or string, got `"+t+"`");e.push(t)}function f(e,t,n){var r,i,a;if(typeof n!=`object`||!(`length`in n))return p(e,t,n);for(i=n.length,r=-1,a=[];++r<i;)a[r]=p(e,t,n[r]);return a}function p(e,t,n){var i=n;return e.number||e.positiveNumber?!isNaN(i)&&i!==``&&(i=Number(i)):(e.boolean||e.overloadedBoolean)&&typeof i==`string`&&(i===``||r(n)===r(t))&&(i=!0),i}function m(e){var t=[],n;for(n in e)t.push([n,e[n]].join(`: `));return t.join(`; `)}function h(e){for(var t=e.length,n=-1,r={},i;++n<t;)i=e[n],r[i.toLowerCase()]=i;return r}})),Dq=i(((e,t)=>{var n=xq(),r=Eq()(n,`div`);r.displayName=`html`,t.exports=r})),Oq=i(((e,t)=>{t.exports=Dq()})),kq=r({AElig:()=>`Æ`,AMP:()=>`&`,Aacute:()=>`Á`,Acirc:()=>`Â`,Agrave:()=>`À`,Aring:()=>`Å`,Atilde:()=>`Ã`,Auml:()=>`Ä`,COPY:()=>`©`,Ccedil:()=>`Ç`,ETH:()=>`Ð`,Eacute:()=>`É`,Ecirc:()=>`Ê`,Egrave:()=>`È`,Euml:()=>`Ë`,GT:()=>`>`,Iacute:()=>`Í`,Icirc:()=>`Î`,Igrave:()=>`Ì`,Iuml:()=>`Ï`,LT:()=>`<`,Ntilde:()=>`Ñ`,Oacute:()=>`Ó`,Ocirc:()=>`Ô`,Ograve:()=>`Ò`,Oslash:()=>`Ø`,Otilde:()=>`Õ`,Ouml:()=>`Ö`,QUOT:()=>`"`,REG:()=>`®`,THORN:()=>`Þ`,Uacute:()=>`Ú`,Ucirc:()=>`Û`,Ugrave:()=>`Ù`,Uuml:()=>`Ü`,Yacute:()=>`Ý`,aacute:()=>`á`,acirc:()=>`â`,acute:()=>`´`,aelig:()=>`æ`,agrave:()=>`à`,amp:()=>`&`,aring:()=>`å`,atilde:()=>`ã`,auml:()=>`ä`,brvbar:()=>`¦`,ccedil:()=>`ç`,cedil:()=>`¸`,cent:()=>`¢`,copy:()=>`©`,curren:()=>`¤`,default:()=>Aq,deg:()=>`°`,divide:()=>`÷`,eacute:()=>`é`,ecirc:()=>`ê`,egrave:()=>`è`,eth:()=>`ð`,euml:()=>`ë`,frac12:()=>`½`,frac14:()=>`¼`,frac34:()=>`¾`,gt:()=>`>`,iacute:()=>`í`,icirc:()=>`î`,iexcl:()=>`¡`,igrave:()=>`ì`,iquest:()=>`¿`,iuml:()=>`ï`,laquo:()=>`«`,lt:()=>`<`,macr:()=>`¯`,micro:()=>`µ`,middot:()=>`·`,nbsp:()=>`\xA0`,not:()=>`¬`,ntilde:()=>`ñ`,oacute:()=>`ó`,ocirc:()=>`ô`,ograve:()=>`ò`,ordf:()=>`ª`,ordm:()=>`º`,oslash:()=>`ø`,otilde:()=>`õ`,ouml:()=>`ö`,para:()=>`¶`,plusmn:()=>`±`,pound:()=>`£`,quot:()=>`"`,raquo:()=>`»`,reg:()=>`®`,sect:()=>`§`,shy:()=>``,sup1:()=>`¹`,sup2:()=>`²`,sup3:()=>`³`,szlig:()=>`ß`,thorn:()=>`þ`,times:()=>`×`,uacute:()=>`ú`,ucirc:()=>`û`,ugrave:()=>`ù`,uml:()=>`¨`,uuml:()=>`ü`,yacute:()=>`ý`,yen:()=>`¥`,yuml:()=>`ÿ`}),Aq,jq=n((()=>{Aq={AElig:`Æ`,AMP:`&`,Aacute:`Á`,Acirc:`Â`,Agrave:`À`,Aring:`Å`,Atilde:`Ã`,Auml:`Ä`,COPY:`©`,Ccedil:`Ç`,ETH:`Ð`,Eacute:`É`,Ecirc:`Ê`,Egrave:`È`,Euml:`Ë`,GT:`>`,Iacute:`Í`,Icirc:`Î`,Igrave:`Ì`,Iuml:`Ï`,LT:`<`,Ntilde:`Ñ`,Oacute:`Ó`,Ocirc:`Ô`,Ograve:`Ò`,Oslash:`Ø`,Otilde:`Õ`,Ouml:`Ö`,QUOT:`"`,REG:`®`,THORN:`Þ`,Uacute:`Ú`,Ucirc:`Û`,Ugrave:`Ù`,Uuml:`Ü`,Yacute:`Ý`,aacute:`á`,acirc:`â`,acute:`´`,aelig:`æ`,agrave:`à`,amp:`&`,aring:`å`,atilde:`ã`,auml:`ä`,brvbar:`¦`,ccedil:`ç`,cedil:`¸`,cent:`¢`,copy:`©`,curren:`¤`,deg:`°`,divide:`÷`,eacute:`é`,ecirc:`ê`,egrave:`è`,eth:`ð`,euml:`ë`,frac12:`½`,frac14:`¼`,frac34:`¾`,gt:`>`,iacute:`í`,icirc:`î`,iexcl:`¡`,igrave:`ì`,iquest:`¿`,iuml:`ï`,laquo:`«`,lt:`<`,macr:`¯`,micro:`µ`,middot:`·`,nbsp:`\xA0`,not:`¬`,ntilde:`ñ`,oacute:`ó`,ocirc:`ô`,ograve:`ò`,ordf:`ª`,ordm:`º`,oslash:`ø`,otilde:`õ`,ouml:`ö`,para:`¶`,plusmn:`±`,pound:`£`,quot:`"`,raquo:`»`,reg:`®`,sect:`§`,shy:``,sup1:`¹`,sup2:`²`,sup3:`³`,szlig:`ß`,thorn:`þ`,times:`×`,uacute:`ú`,ucirc:`û`,ugrave:`ù`,uml:`¨`,uuml:`ü`,yacute:`ý`,yen:`¥`,yuml:`ÿ`}})),Mq=r({default:()=>Nq}),Nq,Pq=n((()=>{Nq={0:`�`,128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`}})),Fq=i(((e,t)=>{t.exports=n;function n(e){var t=typeof e==`string`?e.charCodeAt(0):e;return t>=48&&t<=57}})),Iq=i(((e,t)=>{t.exports=n;function n(e){var t=typeof e==`string`?e.charCodeAt(0):e;return t>=97&&t<=102||t>=65&&t<=70||t>=48&&t<=57}})),Lq=i(((e,t)=>{t.exports=n;function n(e){var t=typeof e==`string`?e.charCodeAt(0):e;return t>=97&&t<=122||t>=65&&t<=90}})),Rq=i(((e,t)=>{var n=Lq(),r=Fq();t.exports=i;function i(e){return n(e)||r(e)}})),zq=i(((e,t)=>{var n,r=59;t.exports=i;function i(e){var t=`&`+e+`;`,i;return n||=document.createElement(`i`),n.innerHTML=t,i=n.textContent,i.charCodeAt(i.length-1)===r&&e!==`semi`||i===t?!1:i}})),Bq=i(((e,n)=>{var r=(jq(),t(kq).default),i=(Pq(),t(Mq).default),a=Fq(),o=Iq(),s=Rq(),c=zq();n.exports=R;var l={}.hasOwnProperty,u=String.fromCharCode,d=Function.prototype,f={warning:null,reference:null,text:null,warningContext:null,referenceContext:null,textContext:null,position:{},additional:null,attribute:!1,nonTerminated:!0},p=9,m=10,h=12,g=32,_=38,v=59,y=60,b=61,x=35,S=88,C=120,w=65533,T=`named`,E=`hexadecimal`,D=`decimal`,O={};O[E]=16,O[D]=10;var k={};k[T]=s,k[D]=a,k[E]=o;var A=1,j=2,M=3,N=4,P=5,F=6,I=7,L={};L[A]=`Named character references must be terminated by a semicolon`,L[j]=`Numeric character references must be terminated by a semicolon`,L[M]=`Named character references cannot be empty`,L[N]=`Numeric character references cannot be empty`,L[P]=`Named character references must be known`,L[F]=`Numeric character references cannot be disallowed`,L[I]=`Numeric character references cannot be outside the permissible Unicode range`;function R(e,t){var n={},r,i;for(i in t||={},f)r=t[i],n[i]=r??f[i];return(n.position.indent||n.position.start)&&(n.indent=n.position.indent||[],n.position=n.position.start),z(e,n)}function z(e,t){var n=t.additional,a=t.nonTerminated,o=t.text,f=t.reference,R=t.warning,z=t.textContext,ne=t.referenceContext,re=t.warningContext,B=t.position,ie=t.indent||[],V=e.length,H=0,ae=-1,oe=B.column||1,se=B.line||1,ce=``,le=[],ue,de,U,fe,pe,me,W,he,G,ge,_e,ve,ye,be,xe,K,Se,Ce,we;for(typeof n==`string`&&(n=n.charCodeAt(0)),K=Te(),he=R?Ee:d,H--,V++;++H<V;)if(pe===m&&(oe=ie[ae]||1),pe=e.charCodeAt(H),pe===_){if(W=e.charCodeAt(H+1),W===p||W===m||W===h||W===g||W===_||W===y||W!==W||n&&W===n){ce+=u(pe),oe++;continue}for(ye=H+1,ve=ye,we=ye,W===x?(we=++ve,W=e.charCodeAt(we),W===S||W===C?(be=E,we=++ve):be=D):be=T,ue=``,_e=``,fe=``,xe=k[be],we--;++we<V&&(W=e.charCodeAt(we),xe(W));)fe+=u(W),be===T&&l.call(r,fe)&&(ue=fe,_e=r[fe]);U=e.charCodeAt(we)===v,U&&(we++,de=be===T?c(fe):!1,de&&(ue=fe,_e=de)),Ce=1+we-ye,!U&&!a||(fe?be===T?(U&&!_e?he(P,1):(ue!==fe&&(we=ve+ue.length,Ce=1+we-ve,U=!1),U||(G=ue?A:M,t.attribute?(W=e.charCodeAt(we),W===b?(he(G,Ce),_e=null):s(W)?_e=null:he(G,Ce)):he(G,Ce))),me=_e):(U||he(j,Ce),me=parseInt(fe,O[be]),ee(me)?(he(I,Ce),me=u(w)):me in i?(he(F,Ce),me=i[me]):(ge=``,te(me)&&he(F,Ce),me>65535&&(me-=65536,ge+=u(me>>>10|55296),me=56320|me&1023),me=ge+u(me))):be!==T&&he(N,Ce)),me?(De(),K=Te(),H=we-1,oe+=we-ye+1,le.push(me),Se=Te(),Se.offset++,f&&f.call(ne,me,{start:K,end:Se},e.slice(ye-1,we)),K=Se):(fe=e.slice(ye-1,we),ce+=fe,oe+=fe.length,H=we-1)}else pe===10&&(se++,ae++,oe=0),pe===pe?(ce+=u(pe),oe++):De();return le.join(``);function Te(){return{line:se,column:oe,offset:H+(B.offset||0)}}function Ee(e,t){var n=Te();n.column+=t,n.offset+=t,R.call(re,L[e],n,e)}function De(){ce&&=(le.push(ce),o&&o.call(z,ce,{start:K,end:Te()}),``)}}function ee(e){return e>=55296&&e<=57343||e>1114111}function te(e){return e>=1&&e<=8||e===11||e>=13&&e<=31||e>=127&&e<=159||e>=64976&&e<=65007||(e&65535)==65535||(e&65535)==65534}})),Vq=i(((e,t)=>{var n=function(e){var t=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,n=0,r={},i={manual:e.Prism&&e.Prism.manual,disableWorkerMessageHandler:e.Prism&&e.Prism.disableWorkerMessageHandler,util:{encode:function e(t){return t instanceof a?new a(t.type,e(t.content),t.alias):Array.isArray(t)?t.map(e):t.replace(/&/g,`&`).replace(/</g,`<`).replace(/\u00a0/g,` `)},type:function(e){return Object.prototype.toString.call(e).slice(8,-1)},objId:function(e){return e.__id||Object.defineProperty(e,`__id`,{value:++n}),e.__id},clone:function e(t,n){n||={};var r,a;switch(i.util.type(t)){case`Object`:if(a=i.util.objId(t),n[a])return n[a];for(var o in r={},n[a]=r,t)t.hasOwnProperty(o)&&(r[o]=e(t[o],n));return r;case`Array`:return a=i.util.objId(t),n[a]?n[a]:(r=[],n[a]=r,t.forEach(function(t,i){r[i]=e(t,n)}),r);default:return t}},getLanguage:function(e){for(;e;){var n=t.exec(e.className);if(n)return n[1].toLowerCase();e=e.parentElement}return`none`},setLanguage:function(e,n){e.className=e.className.replace(RegExp(t,`gi`),``),e.classList.add(`language-`+n)},currentScript:function(){if(typeof document>`u`)return null;if(`currentScript`in document)return document.currentScript;try{throw Error()}catch(r){var e=(/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(r.stack)||[])[1];if(e){var t=document.getElementsByTagName(`script`);for(var n in t)if(t[n].src==e)return t[n]}return null}},isActive:function(e,t,n){for(var r=`no-`+t;e;){var i=e.classList;if(i.contains(t))return!0;if(i.contains(r))return!1;e=e.parentElement}return!!n}},languages:{plain:r,plaintext:r,text:r,txt:r,extend:function(e,t){var n=i.util.clone(i.languages[e]);for(var r in t)n[r]=t[r];return n},insertBefore:function(e,t,n,r){r||=i.languages;var a=r[e],o={};for(var s in a)if(a.hasOwnProperty(s)){if(s==t)for(var c in n)n.hasOwnProperty(c)&&(o[c]=n[c]);n.hasOwnProperty(s)||(o[s]=a[s])}var l=r[e];return r[e]=o,i.languages.DFS(i.languages,function(t,n){n===l&&t!=e&&(this[t]=o)}),o},DFS:function e(t,n,r,a){a||={};var o=i.util.objId;for(var s in t)if(t.hasOwnProperty(s)){n.call(t,s,t[s],r||s);var c=t[s],l=i.util.type(c);l===`Object`&&!a[o(c)]?(a[o(c)]=!0,e(c,n,null,a)):l===`Array`&&!a[o(c)]&&(a[o(c)]=!0,e(c,n,s,a))}}},plugins:{},highlightAll:function(e,t){i.highlightAllUnder(document,e,t)},highlightAllUnder:function(e,t,n){var r={callback:n,container:e,selector:`code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code`};i.hooks.run(`before-highlightall`,r),r.elements=Array.prototype.slice.apply(r.container.querySelectorAll(r.selector)),i.hooks.run(`before-all-elements-highlight`,r);for(var a=0,o;o=r.elements[a++];)i.highlightElement(o,t===!0,r.callback)},highlightElement:function(t,n,r){var a=i.util.getLanguage(t),o=i.languages[a];i.util.setLanguage(t,a);var s=t.parentElement;s&&s.nodeName.toLowerCase()===`pre`&&i.util.setLanguage(s,a);var c={element:t,language:a,grammar:o,code:t.textContent};function l(e){c.highlightedCode=e,i.hooks.run(`before-insert`,c),c.element.innerHTML=c.highlightedCode,i.hooks.run(`after-highlight`,c),i.hooks.run(`complete`,c),r&&r.call(c.element)}if(i.hooks.run(`before-sanity-check`,c),s=c.element.parentElement,s&&s.nodeName.toLowerCase()===`pre`&&!s.hasAttribute(`tabindex`)&&s.setAttribute(`tabindex`,`0`),!c.code){i.hooks.run(`complete`,c),r&&r.call(c.element);return}if(i.hooks.run(`before-highlight`,c),!c.grammar){l(i.util.encode(c.code));return}if(n&&e.Worker){var u=new Worker(i.filename);u.onmessage=function(e){l(e.data)},u.postMessage(JSON.stringify({language:c.language,code:c.code,immediateClose:!0}))}else l(i.highlight(c.code,c.grammar,c.language))},highlight:function(e,t,n){var r={code:e,grammar:t,language:n};if(i.hooks.run(`before-tokenize`,r),!r.grammar)throw Error(`The language "`+r.language+`" has no grammar.`);return r.tokens=i.tokenize(r.code,r.grammar),i.hooks.run(`after-tokenize`,r),a.stringify(i.util.encode(r.tokens),r.language)},tokenize:function(e,t){var n=t.rest;if(n){for(var r in n)t[r]=n[r];delete t.rest}var i=new c;return l(i,i.head,e),s(e,i,t,i.head,0),d(i)},hooks:{all:{},add:function(e,t){var n=i.hooks.all;n[e]=n[e]||[],n[e].push(t)},run:function(e,t){var n=i.hooks.all[e];if(!(!n||!n.length))for(var r=0,a;a=n[r++];)a(t)}},Token:a};e.Prism=i;function a(e,t,n,r){this.type=e,this.content=t,this.alias=n,this.length=(r||``).length|0}a.stringify=function e(t,n){if(typeof t==`string`)return t;if(Array.isArray(t)){var r=``;return t.forEach(function(t){r+=e(t,n)}),r}var a={type:t.type,content:e(t.content,n),tag:`span`,classes:[`token`,t.type],attributes:{},language:n},o=t.alias;o&&(Array.isArray(o)?Array.prototype.push.apply(a.classes,o):a.classes.push(o)),i.hooks.run(`wrap`,a);var s=``;for(var c in a.attributes)s+=` `+c+`="`+(a.attributes[c]||``).replace(/"/g,`"`)+`"`;return`<`+a.tag+` class="`+a.classes.join(` `)+`"`+s+`>`+a.content+`</`+a.tag+`>`};function o(e,t,n,r){e.lastIndex=t;var i=e.exec(n);if(i&&r&&i[1]){var a=i[1].length;i.index+=a,i[0]=i[0].slice(a)}return i}function s(e,t,n,r,c,d){for(var f in n)if(!(!n.hasOwnProperty(f)||!n[f])){var p=n[f];p=Array.isArray(p)?p:[p];for(var m=0;m<p.length;++m){if(d&&d.cause==f+`,`+m)return;var h=p[m],g=h.inside,_=!!h.lookbehind,v=!!h.greedy,y=h.alias;if(v&&!h.pattern.global){var b=h.pattern.toString().match(/[imsuy]*$/)[0];h.pattern=RegExp(h.pattern.source,b+`g`)}for(var x=h.pattern||h,S=r.next,C=c;S!==t.tail&&!(d&&C>=d.reach);C+=S.value.length,S=S.next){var w=S.value;if(t.length>e.length)return;if(!(w instanceof a)){var T=1,E;if(v){if(E=o(x,C,e,_),!E||E.index>=e.length)break;var D=E.index,O=E.index+E[0].length,k=C;for(k+=S.value.length;D>=k;)S=S.next,k+=S.value.length;if(k-=S.value.length,C=k,S.value instanceof a)continue;for(var A=S;A!==t.tail&&(k<O||typeof A.value==`string`);A=A.next)T++,k+=A.value.length;T--,w=e.slice(C,k),E.index-=C}else if(E=o(x,0,w,_),!E)continue;var D=E.index,j=E[0],M=w.slice(0,D),N=w.slice(D+j.length),P=C+w.length;d&&P>d.reach&&(d.reach=P);var F=S.prev;M&&(F=l(t,F,M),C+=M.length),u(t,F,T);var I=new a(f,g?i.tokenize(j,g):j,y,j);if(S=l(t,F,I),N&&l(t,S,N),T>1){var L={cause:f+`,`+m,reach:P};s(e,t,n,S.prev,C,L),d&&L.reach>d.reach&&(d.reach=L.reach)}}}}}}function c(){var e={value:null,prev:null,next:null},t={value:null,prev:e,next:null};e.next=t,this.head=e,this.tail=t,this.length=0}function l(e,t,n){var r=t.next,i={value:n,prev:t,next:r};return t.next=i,r.prev=i,e.length++,i}function u(e,t,n){for(var r=t.next,i=0;i<n&&r!==e.tail;i++)r=r.next;t.next=r,r.prev=t,e.length-=i}function d(e){for(var t=[],n=e.head.next;n!==e.tail;)t.push(n.value),n=n.next;return t}if(!e.document)return e.addEventListener&&(i.disableWorkerMessageHandler||e.addEventListener(`message`,function(t){var n=JSON.parse(t.data),r=n.language,a=n.code,o=n.immediateClose;e.postMessage(i.highlight(a,i.languages[r],r)),o&&e.close()},!1)),i;var f=i.util.currentScript();f&&(i.filename=f.src,f.hasAttribute(`data-manual`)&&(i.manual=!0));function p(){i.manual||i.highlightAll()}if(!i.manual){var m=document.readyState;m===`loading`||m===`interactive`&&f&&f.defer?document.addEventListener(`DOMContentLoaded`,p):window.requestAnimationFrame?window.requestAnimationFrame(p):window.setTimeout(p,16)}return i}(typeof window<`u`?window:typeof WorkerGlobalScope<`u`&&self instanceof WorkerGlobalScope?self:{});t!==void 0&&t.exports&&(t.exports=n),typeof global<`u`&&(global.Prism=n)})),Hq=i(((e,t)=>{t.exports=n,n.displayName=`markup`,n.aliases=[`html`,`mathml`,`svg`,`xml`,`ssml`,`atom`,`rss`];function n(e){e.languages.markup={comment:{pattern:/<!--(?:(?!<!--)[\s\S])*?-->/,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^<!|>$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:`attr-equals`},/"|'/]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:`named-entity`},/&#x?[\da-f]{1,8};/i]},e.languages.markup.tag.inside[`attr-value`].inside.entity=e.languages.markup.entity,e.languages.markup.doctype.inside[`internal-subset`].inside=e.languages.markup,e.hooks.add(`wrap`,function(e){e.type===`entity`&&(e.attributes.title=e.content.value.replace(/&/,`&`))}),Object.defineProperty(e.languages.markup.tag,`addInlined`,{value:function(t,n){var r={};r[`language-`+n]={pattern:/(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,lookbehind:!0,inside:e.languages[n]},r.cdata=/^<!\[CDATA\[|\]\]>$/i;var i={"included-cdata":{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,inside:r}};i[`language-`+n]={pattern:/[\s\S]+/,inside:e.languages[n]};var a={};a[t]={pattern:RegExp(`(<__[^>]*>)(?:<!\\[CDATA\\[(?:[^\\]]|\\](?!\\]>))*\\]\\]>|(?!<!\\[CDATA\\[)[\\s\\S])*?(?=<\\/__>)`.replace(/__/g,function(){return t}),`i`),lookbehind:!0,greedy:!0,inside:i},e.languages.insertBefore(`markup`,`cdata`,a)}}),Object.defineProperty(e.languages.markup.tag,`addAttribute`,{value:function(t,n){e.languages.markup.tag.inside[`special-attr`].push({pattern:RegExp(`(^|["'\\s])(?:`+t+`)\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s'">=]+(?=[\\s>]))`,`i`),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[n,`language-`+n],inside:e.languages[n]},punctuation:[{pattern:/^=/,alias:`attr-equals`},/"|'/]}}}})}}),e.languages.html=e.languages.markup,e.languages.mathml=e.languages.markup,e.languages.svg=e.languages.markup,e.languages.xml=e.languages.extend(`markup`,{}),e.languages.ssml=e.languages.xml,e.languages.atom=e.languages.xml,e.languages.rss=e.languages.xml}})),Uq=i(((e,t)=>{t.exports=n,n.displayName=`css`,n.aliases=[];function n(e){(function(e){var t=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;e.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:/@[\w-](?:[^;{\s]|\s+(?![\s{]))*(?:;|(?=\s*\{))/,inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:`selector`},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp(`\\burl\\((?:`+t.source+`|(?:[^\\\\\\r\\n()"']|\\\\[\\s\\S])*)\\)`,`i`),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp(`^`+t.source+`$`),alias:`url`}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+t.source+`)*(?=\\s*\\{)`),lookbehind:!0},string:{pattern:t,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},e.languages.css.atrule.inside.rest=e.languages.css;var n=e.languages.markup;n&&(n.tag.addInlined(`style`,`css`),n.tag.addAttribute(`style`,`css`))})(e)}})),Wq=i(((e,t)=>{t.exports=n,n.displayName=`clike`,n.aliases=[];function n(e){e.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/}}})),Gq=i(((e,t)=>{t.exports=n,n.displayName=`javascript`,n.aliases=[`js`];function n(e){e.languages.javascript=e.languages.extend(`clike`,{"class-name":[e.languages.clike[`class-name`],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp(`(^|[^\\w$])(?:NaN|Infinity|0[bB][01]+(?:_[01]+)*n?|0[oO][0-7]+(?:_[0-7]+)*n?|0[xX][\\dA-Fa-f]+(?:_[\\dA-Fa-f]+)*n?|\\d+(?:_\\d+)*n|(?:\\d+(?:_\\d+)*(?:\\.(?:\\d+(?:_\\d+)*)?)?|\\.\\d+(?:_\\d+)*)(?:[Ee][+-]?\\d+(?:_\\d+)*)?)(?![\\w$])`),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/}),e.languages.javascript[`class-name`][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/,e.languages.insertBefore(`javascript`,`keyword`,{regex:{pattern:/((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)\/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/,lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:`language-regex`,inside:e.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:`function`},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:e.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:e.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:e.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:e.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),e.languages.insertBefore(`javascript`,`string`,{hashbang:{pattern:/^#!.*/,greedy:!0,alias:`comment`},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:`string`},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:`punctuation`},rest:e.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:`property`}}),e.languages.insertBefore(`javascript`,`operator`,{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:`property`}}),e.languages.markup&&(e.languages.markup.tag.addInlined(`script`,`javascript`),e.languages.markup.tag.addAttribute(`on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)`,`javascript`)),e.languages.js=e.languages.javascript}})),Kq=i(((e,t)=>{var n=typeof globalThis==`object`?globalThis:typeof self==`object`?self:typeof window==`object`?window:typeof global==`object`?global:{},r=C();n.Prism={manual:!0,disableWorkerMessageHandler:!0};var i=Oq(),a=Bq(),o=Vq(),s=Hq(),c=Uq(),l=Wq(),u=Gq();r();var d={}.hasOwnProperty;function f(){}f.prototype=o;var p=new f;t.exports=p,p.highlight=g,p.register=m,p.alias=h,p.registered=_,p.listLanguages=v,m(s),m(c),m(l),m(u),p.util.encode=x,p.Token.stringify=y;function m(e){if(typeof e!=`function`||!e.displayName)throw Error("Expected `function` for `grammar`, got `"+e+"`");p.languages[e.displayName]===void 0&&e(p)}function h(e,t){var n=p.languages,r=e,i,a,o,s;for(i in t&&(r={},r[e]=t),r)for(a=r[i],a=typeof a==`string`?[a]:a,o=a.length,s=-1;++s<o;)n[a[s]]=n[i]}function g(e,t){var n=o.highlight,r;if(typeof e!=`string`)throw Error("Expected `string` for `value`, got `"+e+"`");if(p.util.type(t)===`Object`)r=t,t=null;else{if(typeof t!=`string`)throw Error("Expected `string` for `name`, got `"+t+"`");if(d.call(p.languages,t))r=p.languages[t];else throw Error("Unknown language: `"+t+"` is not registered")}return n.call(this,e,r,t)}function _(e){if(typeof e!=`string`)throw Error("Expected `string` for `language`, got `"+e+"`");return d.call(p.languages,e)}function v(){var e=p.languages,t=[],n;for(n in e)d.call(e,n)&&typeof e[n]==`object`&&t.push(n);return t}function y(e,t,n){var r;return typeof e==`string`?{type:`text`,value:e}:p.util.type(e)===`Array`?b(e,t):(r={type:e.type,content:p.Token.stringify(e.content,t,n),tag:`span`,classes:[`token`,e.type],attributes:{},language:t,parent:n},e.alias&&(r.classes=r.classes.concat(e.alias)),p.hooks.run(`wrap`,r),i(r.tag+`.`+r.classes.join(`.`),S(r.attributes),r.content))}function b(e,t){for(var n=[],r=e.length,i=-1,a;++i<r;)a=e[i],a!==``&&a!=null&&n.push(a);for(i=-1,r=n.length;++i<r;)a=n[i],n[i]=p.Token.stringify(a,t,n);return n}function x(e){return e}function S(e){for(var t in e)e[t]=a(e[t]);return e}function C(){var e=`Prism`in n,t=e?n.Prism:void 0;return r;function r(){e?n.Prism=t:delete n.Prism,e=void 0,t=void 0}}})),qq=i(((e,t)=>{t.exports=n,n.displayName=`bash`,n.aliases=[`shell`];function n(e){(function(e){var t=`\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b`,n={pattern:/(^(["']?)\w+\2)[ \t]+\S.*/,lookbehind:!0,alias:`punctuation`,inside:null},r={bash:n,environment:{pattern:RegExp(`\\$`+t),alias:`constant`},variable:[{pattern:/\$?\(\([\s\S]+?\)\)/,greedy:!0,inside:{variable:[{pattern:/(^\$\(\([\s\S]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,operator:/--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp(`(\\{)`+t),lookbehind:!0,alias:`constant`}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/};e.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:`important`},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:`function`},{pattern:/\b[\w-]+(?=\s*\(\s*\)\s*\{)/,alias:`function`}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:`variable`,lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?=\+?=)/,inside:{environment:{pattern:RegExp(`(^|[\\s;|&]|[<>]\\()`+t),lookbehind:!0,alias:`constant`}},alias:`variable`,lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:r},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0,inside:{bash:n}},{pattern:/(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,lookbehind:!0,greedy:!0,inside:r},{pattern:/(^|[^$\\])'[^']*'/,lookbehind:!0,greedy:!0},{pattern:/\$'(?:[^'\\]|\\[\s\S])*'/,greedy:!0,inside:{entity:r.entity}}],environment:{pattern:RegExp(`\\$?`+t),alias:`constant`},variable:r.variable,function:{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,lookbehind:!0,alias:`class-name`},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:`important`},operator:{pattern:/\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,inside:{"file-descriptor":{pattern:/^\d/,alias:`important`}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}},n.inside=e.languages.bash;for(var i=[`comment`,`function-name`,`for-or-select`,`assign-left`,`string`,`environment`,`function`,`keyword`,`builtin`,`boolean`,`file-descriptor`,`operator`,`punctuation`,`number`],a=r.variable[1].inside,o=0;o<i.length;o++)a[i[o]]=e.languages.bash[i[o]];e.languages.shell=e.languages.bash})(e)}})),Jq=i(((e,t)=>{t.exports=n,n.displayName=`json`,n.aliases=[`webmanifest`];function n(e){e.languages.json={property:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,lookbehind:!0,greedy:!0},string:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,lookbehind:!0,greedy:!0},comment:{pattern:/\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},number:/-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,punctuation:/[{}[\],]/,operator:/:/,boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:`keyword`}},e.languages.webmanifest=e.languages.json}})),Yq=i(((e,t)=>{t.exports=n,n.displayName=`jsx`,n.aliases=[];function n(e){(function(e){var t=e.util.clone(e.languages.javascript),n=`(?:\\s|\\/\\/.*(?!.)|\\/\\*(?:[^*]|\\*(?!\\/))\\*\\/)`,r=`(?:\\{(?:\\{(?:\\{[^{}]*\\}|[^{}])*\\}|[^{}])*\\})`,i=`(?:\\{<S>*\\.{3}(?:[^{}]|<BRACES>)*\\})`;function a(e,t){return e=e.replace(/<S>/g,function(){return n}).replace(/<BRACES>/g,function(){return r}).replace(/<SPREAD>/g,function(){return i}),RegExp(e,t)}i=a(i).source,e.languages.jsx=e.languages.extend(`markup`,t),e.languages.jsx.tag.pattern=a(`<\\/?(?:[\\w.:-]+(?:<S>+(?:[\\w.:$-]+(?:=(?:"(?:\\\\[\\s\\S]|[^\\\\"])*"|'(?:\\\\[\\s\\S]|[^\\\\'])*'|[^\\s{'"/>=]+|<BRACES>))?|<SPREAD>))*<S>*\\/?)?>`),e.languages.jsx.tag.inside.tag.pattern=/^<\/?[^\s>\/]*/,e.languages.jsx.tag.inside[`attr-value`].pattern=/=(?!\{)(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s'">]+)/,e.languages.jsx.tag.inside.tag.inside[`class-name`]=/^[A-Z]\w*(?:\.[A-Z]\w*)*$/,e.languages.jsx.tag.inside.comment=t.comment,e.languages.insertBefore(`inside`,`attr-name`,{spread:{pattern:a(`<SPREAD>`),inside:e.languages.jsx}},e.languages.jsx.tag),e.languages.insertBefore(`inside`,`special-attr`,{script:{pattern:a(`=<BRACES>`),alias:`language-javascript`,inside:{"script-punctuation":{pattern:/^=(?=\{)/,alias:`punctuation`},rest:e.languages.jsx}}},e.languages.jsx.tag);var o=function(e){return e?typeof e==`string`?e:typeof e.content==`string`?e.content:e.content.map(o).join(``):``},s=function(t){for(var n=[],r=0;r<t.length;r++){var i=t[r],a=!1;if(typeof i!=`string`&&(i.type===`tag`&&i.content[0]&&i.content[0].type===`tag`?i.content[0].content[0].content===`</`?n.length>0&&n[n.length-1].tagName===o(i.content[0].content[1])&&n.pop():i.content[i.content.length-1].content===`/>`||n.push({tagName:o(i.content[0].content[1]),openedBraces:0}):n.length>0&&i.type===`punctuation`&&i.content===`{`?n[n.length-1].openedBraces++:n.length>0&&n[n.length-1].openedBraces>0&&i.type===`punctuation`&&i.content===`}`?n[n.length-1].openedBraces--:a=!0),(a||typeof i==`string`)&&n.length>0&&n[n.length-1].openedBraces===0){var c=o(i);r<t.length-1&&(typeof t[r+1]==`string`||t[r+1].type===`plain-text`)&&(c+=o(t[r+1]),t.splice(r+1,1)),r>0&&(typeof t[r-1]==`string`||t[r-1].type===`plain-text`)&&(c=o(t[r-1])+c,t.splice(r-1,1),r--),t[r]=new e.Token(`plain-text`,c,null,c)}i.content&&typeof i.content!=`string`&&s(i.content)}};e.hooks.add(`after-tokenize`,function(e){e.language!==`jsx`&&e.language!==`tsx`||s(e.tokens)})})(e)}})),Xq=i(((e,t)=>{t.exports=n,n.displayName=`markdown`,n.aliases=[`md`];function n(e){(function(e){var t=`(?:\\\\.|[^\\\\\\n\\r]|(?:\\n|\\r\\n?)(?![\\r\\n]))`;function n(e){return e=e.replace(/<inner>/g,function(){return t}),RegExp(`((?:^|[^\\\\])(?:\\\\{2})*)(?:`+e+`)`)}var r="(?:\\\\.|``(?:[^`\\r\\n]|`(?!`))+``|`[^`\\r\\n]+`|[^\\\\|\\r\\n`])+",i=`\\|?__(?:\\|__)+\\|?(?:(?:\\n|\\r\\n?)|(?![\\s\\S]))`.replace(/__/g,function(){return r}),a=`\\|?[ \\t]*:?-{3,}:?[ \\t]*(?:\\|[ \\t]*:?-{3,}:?[ \\t]*)+\\|?(?:\\n|\\r\\n?)`;e.languages.markdown=e.languages.extend(`markup`,{}),e.languages.insertBefore(`markdown`,`prolog`,{"front-matter-block":{pattern:/(^(?:\s*[\r\n])?)---(?!.)[\s\S]*?[\r\n]---(?!.)/,lookbehind:!0,greedy:!0,inside:{punctuation:/^---|---$/,"front-matter":{pattern:/\S+(?:\s+\S+)*/,alias:[`yaml`,`language-yaml`],inside:e.languages.yaml}}},blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:`punctuation`},table:{pattern:RegExp(`^`+i+a+`(?:`+i+`)*`,`m`),inside:{"table-data-rows":{pattern:RegExp(`^(`+i+a+`)(?:`+i+`)*$`),lookbehind:!0,inside:{"table-data":{pattern:RegExp(r),inside:e.languages.markdown},punctuation:/\|/}},"table-line":{pattern:RegExp(`^(`+i+`)`+a+`$`),lookbehind:!0,inside:{punctuation:/\||:?-{3,}:?/}},"table-header-row":{pattern:RegExp(`^`+i+`$`),inside:{"table-header":{pattern:RegExp(r),alias:`important`,inside:e.languages.markdown},punctuation:/\|/}}}},code:[{pattern:/((?:^|\n)[ \t]*\n|(?:^|\r\n?)[ \t]*\r\n?)(?: {4}|\t).+(?:(?:\n|\r\n?)(?: {4}|\t).+)*/,lookbehind:!0,alias:`keyword`},{pattern:/^```[\s\S]*?^```$/m,greedy:!0,inside:{"code-block":{pattern:/^(```.*(?:\n|\r\n?))[\s\S]+?(?=(?:\n|\r\n?)^```$)/m,lookbehind:!0},"code-language":{pattern:/^(```).+/,lookbehind:!0},punctuation:/```/}}],title:[{pattern:/\S.*(?:\n|\r\n?)(?:==+|--+)(?=[ \t]*$)/m,alias:`important`,inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#.+/m,lookbehind:!0,alias:`important`,inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])(?:[\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:`punctuation`},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:`punctuation`},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:`url`},bold:{pattern:n(`\\b__(?:(?!_)<inner>|_(?:(?!_)<inner>)+_)+__\\b|\\*\\*(?:(?!\\*)<inner>|\\*(?:(?!\\*)<inner>)+\\*)+\\*\\*`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^..)[\s\S]+(?=..$)/,lookbehind:!0,inside:{}},punctuation:/\*\*|__/}},italic:{pattern:n(`\\b_(?:(?!_)<inner>|__(?:(?!_)<inner>)+__)+_\\b|\\*(?:(?!\\*)<inner>|\\*\\*(?:(?!\\*)<inner>)+\\*\\*)+\\*`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^.)[\s\S]+(?=.$)/,lookbehind:!0,inside:{}},punctuation:/[*_]/}},strike:{pattern:n(`(~~?)(?:(?!~)<inner>)+\\2`),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^~~?)[\s\S]+(?=\1$)/,lookbehind:!0,inside:{}},punctuation:/~~?/}},"code-snippet":{pattern:/(^|[^\\`])(?:``[^`\r\n]+(?:`[^`\r\n]+)*``(?!`)|`[^`\r\n]+`(?!`))/,lookbehind:!0,greedy:!0,alias:[`code`,`keyword`]},url:{pattern:n(`!?\\[(?:(?!\\])<inner>)+\\](?:\\([^\\s)]+(?:[\\t ]+"(?:\\\\.|[^"\\\\])*")?\\)|[ \\t]?\\[(?:(?!\\])<inner>)+\\])`),lookbehind:!0,greedy:!0,inside:{operator:/^!/,content:{pattern:/(^\[)[^\]]+(?=\])/,lookbehind:!0,inside:{}},variable:{pattern:/(^\][ \t]?\[)[^\]]+(?=\]$)/,lookbehind:!0},url:{pattern:/(^\]\()[^\s)]+/,lookbehind:!0},string:{pattern:/(^[ \t]+)"(?:\\.|[^"\\])*"(?=\)$)/,lookbehind:!0}}}}),[`url`,`bold`,`italic`,`strike`].forEach(function(t){[`url`,`bold`,`italic`,`strike`,`code-snippet`].forEach(function(n){t!==n&&(e.languages.markdown[t].inside.content.inside[n]=e.languages.markdown[n])})}),e.hooks.add(`after-tokenize`,function(e){if(e.language!==`markdown`&&e.language!==`md`)return;function t(e){if(!(!e||typeof e==`string`))for(var n=0,r=e.length;n<r;n++){var i=e[n];if(i.type!==`code`){t(i.content);continue}var a=i.content[1],o=i.content[3];if(a&&o&&a.type===`code-language`&&o.type===`code-block`&&typeof a.content==`string`){var s=a.content.replace(/\b#/g,`sharp`).replace(/\b\+\+/g,`pp`);s=(/[a-z][\w-]*/i.exec(s)||[``])[0].toLowerCase();var c=`language-`+s;o.alias?typeof o.alias==`string`?o.alias=[o.alias,c]:o.alias.push(c):o.alias=[c]}}}t(e.tokens)}),e.hooks.add(`wrap`,function(t){if(t.type===`code-block`){for(var n=``,r=0,i=t.classes.length;r<i;r++){var a=t.classes[r],o=/language-(.+)/.exec(a);if(o){n=o[1];break}}var s=e.languages[n];if(s)t.content=e.highlight(l(t.content.value),s,n);else if(n&&n!==`none`&&e.plugins.autoloader){var c=`md-`+new Date().valueOf()+`-`+Math.floor(Math.random()*0x2386f26fc10000);t.attributes.id=c,e.plugins.autoloader.loadLanguages(n,function(){var t=document.getElementById(c);t&&(t.innerHTML=e.highlight(t.textContent,e.languages[n],n))})}}});var o=RegExp(e.languages.markup.tag.pattern.source,`gi`),s={amp:`&`,lt:`<`,gt:`>`,quot:`"`},c=String.fromCodePoint||String.fromCharCode;function l(e){var t=e.replace(o,``);return t=t.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi,function(e,t){return t=t.toLowerCase(),t[0]===`#`?c(t[1]===`x`?parseInt(t.slice(2),16):Number(t.slice(1))):s[t]||e}),t}e.languages.md=e.languages.markdown})(e)}})),Zq=i(((e,t)=>{t.exports=n,n.displayName=`typescript`,n.aliases=[`ts`];function n(e){(function(e){e.languages.typescript=e.languages.extend(`javascript`,{"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,lookbehind:!0,greedy:!0,inside:null},builtin:/\b(?:Array|Function|Promise|any|boolean|console|never|number|string|symbol|unknown)\b/}),e.languages.typescript.keyword.push(/\b(?:abstract|declare|is|keyof|readonly|require)\b/,/\b(?:asserts|infer|interface|module|namespace|type)\b(?=\s*(?:[{_$a-zA-Z\xA0-\uFFFF]|$))/,/\btype\b(?=\s*(?:[\{*]|$))/),delete e.languages.typescript.parameter,delete e.languages.typescript[`literal-property`];var t=e.languages.extend(`typescript`,{});delete t[`class-name`],e.languages.typescript[`class-name`].inside=t,e.languages.insertBefore(`typescript`,`function`,{decorator:{pattern:/@[$\w\xA0-\uFFFF]+/,inside:{at:{pattern:/^@/,alias:`operator`},function:/^[\s\S]+/}},"generic-function":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,greedy:!0,inside:{function:/^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,generic:{pattern:/<[\s\S]+/,alias:`class-name`,inside:t}}}}),e.languages.ts=e.languages.typescript})(e)}})),Qq=i(((e,t)=>{var n=Yq(),r=Zq();t.exports=i,i.displayName=`tsx`,i.aliases=[];function i(e){e.register(n),e.register(r),(function(e){var t=e.util.clone(e.languages.typescript);e.languages.tsx=e.languages.extend(`jsx`,t),delete e.languages.tsx.parameter,delete e.languages.tsx[`literal-property`];var n=e.languages.tsx.tag;n.pattern=RegExp(`(^|[^\\w$]|(?=<\\/))(?:`+n.pattern.source+`)`,n.pattern.flags),n.lookbehind=!0})(e)}})),$q=i(((e,t)=>{t.exports=n,n.displayName=`yaml`,n.aliases=[`yml`];function n(e){(function(e){var t=/[*&][^\s[\]{},]+/,n=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,r=`(?:`+n.source+`(?:[ ]+`+t.source+`)?|`+t.source+`(?:[ ]+`+n.source+`)?)`,i=`(?:[^\\s\\x00-\\x08\\x0e-\\x1f!"#%&'*,\\-:>?@[\\]\`{|}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]|[?:-]<PLAIN>)(?:[ \\t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*`.replace(/<PLAIN>/g,function(){return`[^\\s\\x00-\\x08\\x0e-\\x1f,[\\]{}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]`}),a=`"(?:[^"\\\\\\r\\n]|\\\\.)*"|'(?:[^'\\\\\\r\\n]|\\\\.)*'`;function o(e,t){t=(t||``).replace(/m/g,``)+`m`;var n=`([:\\-,[{]\\s*(?:\\s<<prop>>[ \\t]+)?)(?:<<value>>)(?=[ \\t]*(?:$|,|\\]|\\}|(?:[\\r\\n]\\s*)?#))`.replace(/<<prop>>/g,function(){return r}).replace(/<<value>>/g,function(){return e});return RegExp(n,t)}e.languages.yaml={scalar:{pattern:RegExp(`([\\-:]\\s*(?:\\s<<prop>>[ \\t]+)?[|>])[ \\t]*(?:((?:\\r?\\n|\\r)[ \\t]+)\\S[^\\r\\n]*(?:\\2[^\\r\\n]+)*)`.replace(/<<prop>>/g,function(){return r})),lookbehind:!0,alias:`string`},comment:/#.*/,key:{pattern:RegExp(`((?:^|[:\\-,[{\\r\\n?])[ \\t]*(?:<<prop>>[ \\t]+)?)<<key>>(?=\\s*:\\s)`.replace(/<<prop>>/g,function(){return r}).replace(/<<key>>/g,function(){return`(?:`+i+`|`+a+`)`})),lookbehind:!0,greedy:!0,alias:`atrule`},directive:{pattern:/(^[ \t]*)%.+/m,lookbehind:!0,alias:`important`},datetime:{pattern:o(`\\d{4}-\\d\\d?-\\d\\d?(?:[tT]|[ \\t]+)\\d\\d?:\\d{2}:\\d{2}(?:\\.\\d*)?(?:[ \\t]*(?:Z|[-+]\\d\\d?(?::\\d{2})?))?|\\d{4}-\\d{2}-\\d{2}|\\d\\d?:\\d{2}(?::\\d{2}(?:\\.\\d*)?)?`),lookbehind:!0,alias:`number`},boolean:{pattern:o(`false|true`,`i`),lookbehind:!0,alias:`important`},null:{pattern:o(`null|~`,`i`),lookbehind:!0,alias:`important`},string:{pattern:o(a),lookbehind:!0,greedy:!0},number:{pattern:o(`[+-]?(?:0x[\\da-f]+|0o[0-7]+|(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?|\\.inf|\\.nan)`,`i`),lookbehind:!0},tag:n,important:t,punctuation:/---|[:[\]{}\-,|>?]|\.\.\./},e.languages.yml=e.languages.yaml})(e)}})),eJ=e(Kq(),1),tJ=e(qq(),1),nJ=e(Uq(),1),rJ=e(Gq(),1),iJ=e(Jq(),1),aJ=e(Yq(),1),oJ=e(Xq(),1),sJ=e(Hq(),1),cJ=e(Qq(),1),lJ=e(Zq(),1),uJ=e($q(),1),dJ=e=>{let t=e.displayName;!t||eJ.default.registered(t)||eJ.default.register(e)};dJ(sJ.default),dJ(nJ.default),dJ(rJ.default),dJ(lJ.default),dJ(cJ.default),dJ(iJ.default),dJ(aJ.default),dJ(oJ.default),dJ(uJ.default),dJ(tJ.default);var fJ=r({TicketChangesModal:()=>UJ}),pJ=(e,t)=>Pe.t(`common:ticketChangesModal.${e}`,t),mJ=4,hJ=1500,gJ=`archon.ticket-changes.review-comments`,_J=[],vJ=[],yJ=[],bJ=e=>new Set(e.map(e=>e.path)),xJ=(e,t)=>{if(!e)return null;if(e.blocked_reason)return e.blocked_reason;let n=e.files.find(e=>!t.has(e.path)&&e.staged);return n?`"${n.path}" already has staged changes. Finish that commit in the terminal first.`:null},SJ=e=>e.replace(/^[ab]\//,``),CJ=e=>{let t=`oldPath`in e&&typeof e.oldPath==`string`?SJ(e.oldPath):``,n=`newPath`in e&&typeof e.newPath==`string`?SJ(e.newPath):``;return[...new Set([n,t].filter(e=>e&&e!==`/dev/null`))]},wJ=e=>{let[t,n]=CJ(e);return!t&&!n?`Unknown file`:t&&n&&t!==n?`${n} -> ${t}`:t??n??`Unknown file`},TJ=e=>{let[t,n]=CJ(e);return t??n??null},EJ=e=>e.hunks.reduce((e,t)=>e+t.changes.length,0),DJ=e=>{if(EJ(e)>hJ)return null;let t=eq(TJ(e));if(!t)return null;try{return Yy(e.hunks,{highlight:!0,refractor:eJ.default,language:t,enhancers:[qy(e.hunks)]})}catch{return null}},OJ=(e,t)=>e instanceof Error?e.message:t,kJ=(e,t)=>`${gJ}:${e}:${t}`,AJ=()=>({activeTarget:null,editingCommentKey:null,draftInput:``,comments:new Map,signature:null}),jJ=()=>({uncommitted:AJ(),bundle_diff:AJ()}),MJ=e=>({uncommitted:e(),bundle_diff:e()}),NJ=()=>MJ(()=>new Map),PJ=e=>{let t=5381;for(let n=0;n<e.length;n+=1)t=(t<<5)+t^e.charCodeAt(n);return`${e.length}:${t>>>0}`},FJ=e=>{if(!e||typeof e!=`object`)return!1;let t=e;return(t.scope===void 0||t.scope===`uncommitted`||t.scope===`bundle_diff`)&&typeof t.filePath==`string`&&typeof t.changeKey==`string`&&typeof t.changeType==`string`&&(typeof t.oldLineNumber==`number`||t.oldLineNumber===null)&&(typeof t.newLineNumber==`number`||t.newLineNumber===null)&&typeof t.hunkHeader==`string`&&typeof t.lineContent==`string`&&typeof t.diffSnippet==`string`&&typeof t.comment==`string`},IJ=e=>{try{let t=JSON.parse(e);if(!t||typeof t!=`object`)return null;let n=t;if(typeof n.diffSignature!=`string`||!Array.isArray(n.comments))return null;let r=n.comments.filter(FJ).map(e=>({scope:e.scope??`uncommitted`,filePath:e.filePath,changeKey:e.changeKey,changeType:e.changeType,oldLineNumber:e.oldLineNumber,newLineNumber:e.newLineNumber,hunkHeader:e.hunkHeader,lineContent:e.lineContent,diffSnippet:e.diffSnippet,comment:e.comment}));return r.length===n.comments.length?{diffSignature:n.diffSignature,comments:r}:null}catch{return null}},LJ=e=>new Map(e.map(e=>[lb(e.filePath,e.changeKey),e])),RJ=(e,t)=>{e.set(t,(e.get(t)??0)+1)},zJ=e=>e.find(e=>e.trim())||``,BJ=({gitStatus:e,isProjectTargetRepoRoot:t,isGitHubConnected:n,effectiveDefaultBaseBranch:r})=>t&&!!e?.branch&&e?.has_upstream===!0&&(e?.ahead??0)===0&&!!r&&e?.branch!==r&&n,VJ=({pullRequest:e,isLoading:t,isOpen:n,canCreate:r,disabledReason:i,isCreating:a,isSyncing:o,isGeneratingDescription:s,title:c,body:l,baseBranch:u,onOpenChange:d,onTitleChange:f,onBodyChange:p,onBaseBranchChange:m,showGenerateDescription:h,onGenerateDescription:g,onCreate:_})=>t?(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,disabled:!0,className:`gap-2`,children:pJ(`loadingPullRequest`)}):o?(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`outline`,disabled:!0,className:`gap-2`,children:[(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}),pJ(`checkingPullRequest`)]}):e?(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 rounded-xl border border-border/80 bg-background/50 px-3 py-2`,children:[(0,Z.jsx)(yw,{pullRequest:e}),(0,Z.jsxs)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,className:`text-xs font-medium text-sky-300 underline underline-offset-2 hover:text-sky-200`,children:[`PR #`,e.number]})]}):(0,Z.jsxs)($s,{open:n,onOpenChange:d,children:[(0,Z.jsx)(ec,{asChild:!0,children:(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`default`,disabled:!r,title:i,className:`gap-2`,children:[a?(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}):(0,Z.jsx)(Pc,{className:`h-4 w-4`}),pJ(a?`creatingPullRequest`:`createPullRequest`)]})}),(0,Z.jsxs)(tc,{align:`end`,className:`z-[90] w-[36rem] max-w-[calc(100vw-2rem)] p-4`,children:[(0,Z.jsx)(nc,{children:(0,Z.jsx)(rc,{children:pJ(`createPullRequestTitle`)})}),(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(Cu,{label:pJ(`pullRequestFieldTitle`),htmlFor:`bundle-pr-title`,children:(0,Z.jsx)(Ge,{id:`bundle-pr-title`,value:c,onChange:e=>f(e.target.value),placeholder:pJ(`pullRequestTitlePlaceholder`),disabled:a})}),(0,Z.jsx)(Cu,{label:pJ(`pullRequestFieldBaseBranch`),htmlFor:`bundle-pr-base-branch`,description:pJ(`pullRequestBaseBranchDescription`),children:(0,Z.jsx)(Ge,{id:`bundle-pr-base-branch`,value:u,onChange:e=>m(e.target.value),placeholder:pJ(`pullRequestBaseBranchPlaceholder`),disabled:a})}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium uppercase tracking-[0.22em] text-muted-foreground`,htmlFor:`bundle-pr-body`,children:pJ(`pullRequestFieldDescription`)}),h&&(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`outline`,className:`gap-2`,disabled:a||s,onClick:g,children:[s?(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}):null,pJ(s?`generatingDescription`:`generateDescription`)]})]}),(0,Z.jsx)(zs,{id:`bundle-pr-body`,value:l,onChange:e=>p(e.target.value),placeholder:pJ(`pullRequestDescriptionPlaceholder`),className:`min-h-40`,disabled:a})]}),(0,Z.jsx)(`div`,{className:`flex justify-end`,children:(0,Z.jsx)(q,{type:`button`,size:`sm`,disabled:!c.trim()||a,onClick:_,children:pJ(a?`creating`:`createPullRequest`)})})]})]})]}),HJ=(e,t,n)=>{if(n)return bJ(t);let r=new Set(t.map(e=>e.path));return new Set([...e].filter(e=>r.has(e)))},UJ=e=>{let{projectId:t,reviewCommentsBundleId:n=null,targetKind:r,repoRootDefaultBranch:i=null,title:a,hasHelperModel:o=!1,onClose:s,onSubmitReviewPrompt:c,canSubmitReviewPrompt:l=!1,reviewSubmitDisabledReason:u,canAddReviewComments:d=!0,canModifyChanges:f=!0,changesDisabledReason:m}=e,h=e.scope??`ticket`,{isGitHubConnected:g,defaultBaseBranch:_}=mf(t),v=e.scope===`project_root`?null:e.ticketId,y=e.scope===`project_root`?void 0:e.onTicketUpdate,b=e.scope===`project_root`?void 0:e.onRequestTicketRefresh,x=h===`project_root`,S=!!(t&&n),C=r??(S?`bundle`:`repo_root`),w=x&&C===`repo_root`,T=_??i,[E,D]=(0,Y.useState)(`uncommitted`),[O,k]=(0,Y.useState)(null),[A,j]=(0,Y.useState)(null),[M,N]=(0,Y.useState)(null),[P,F]=(0,Y.useState)([]),[I,L]=(0,Y.useState)(new Set),[R,z]=(0,Y.useState)(`all`),[ee,ne]=(0,Y.useState)(``),[re,B]=(0,Y.useState)(null),[ie,V]=(0,Y.useState)(null),[H,ae]=(0,Y.useState)(null),[oe,se]=(0,Y.useState)(null),[ce,ue]=(0,Y.useState)(!0),[de,pe]=(0,Y.useState)(!1),[me,he]=(0,Y.useState)(!0),[G,_e]=(0,Y.useState)(!1),[ve,ye]=(0,Y.useState)(!1),[be,xe]=(0,Y.useState)(!1),[K,Se]=(0,Y.useState)(null),[we,Te]=(0,Y.useState)(!1),[Ee,De]=(0,Y.useState)(`unified`),[Oe,je]=(0,Y.useState)(new Map),[Ne,Pe]=(0,Y.useState)(yJ),[Ie,Le]=(0,Y.useState)(jJ),[Re,Be]=(0,Y.useState)(null),[Ve,He]=(0,Y.useState)([]),[Ge,qe]=(0,Y.useState)(null),[Je,Ye]=(0,Y.useState)(null),[Xe,Ze]=(0,Y.useState)(new Set),[Qe,$e]=(0,Y.useState)(new Set),[et,J]=(0,Y.useState)(!1),[tt,nt]=(0,Y.useState)(null),[rt,it]=(0,Y.useState)(null),[at,ot]=(0,Y.useState)(!1),[st,ct]=(0,Y.useState)(!1),[lt,ut]=(0,Y.useState)(``),[dt,ft]=(0,Y.useState)(``),[pt,mt]=(0,Y.useState)(``),[ht,gt]=(0,Y.useState)([]),[_t,vt]=(0,Y.useState)(!1),[yt,bt]=(0,Y.useState)(!1),[X,xt]=(0,Y.useState)(!1),St=(0,Y.useRef)(null),Ct=(0,Y.useRef)(!1),wt=(0,Y.useRef)(null),Tt=(0,Y.useRef)(null),Et=(0,Y.useRef)(0),Ot=(0,Y.useRef)(0),Mt=(0,Y.useRef)(!1),Nt=(0,Y.useRef)(MJ(()=>null)),Pt=(0,Y.useRef)(NJ()),Ft=(0,Y.useRef)(`idle`),zt=(0,Y.useRef)(0),Bt=(0,Y.useRef)(null),Vt=(0,Y.useMemo)(()=>YK({scope:h,projectId:t,ticketId:v,projectTargetBundleId:x?n:null}),[t,n,h,v,x]),Ht=(0,Y.useCallback)(()=>{if(!v)throw Error(`Ticket changes require a ticket id.`);return v},[v]),Ut=(0,Y.useCallback)(e=>{wt.current=e,k(e),B(null)},[]),Wt=(0,Y.useCallback)((e,t)=>{ZK({cacheKey:Vt,diffResponse:e,gitStatus:t})},[Vt]),Gt=(0,Y.useCallback)(e=>{wt.current&&ZK({cacheKey:Vt,diffResponse:wt.current,gitStatus:e})},[Vt]),Kt=(0,Y.useCallback)(async()=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await Ae(t)}return await $t(Ht(),t)},[t,Ht,h]),qt=(0,Y.useCallback)(async()=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await ge(t)}return await en(Ht(),t,{refreshRemote:!1})},[t,Ht,h]),Jt=(0,Y.useCallback)(async()=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await Ke(t)}return await an(Ht(),t)},[t,Ht,h]),Yt=(0,Y.useCallback)(async e=>!n||!t?null:await It(t,n,e),[t,n]),Xt=(0,Y.useCallback)(async e=>!n||!t?null:await Dt(t,n,e),[t,n]),Zt=(0,Y.useCallback)(async e=>!n||!t?null:await Lt(t,n,e),[t,n]),Qt=(0,Y.useCallback)(async e=>!n||!t?null:await Rt(t,n,e),[t,n]),sn=(0,Y.useCallback)(function e({silent:r}){if(!n||!t||!tt?.bundle.pull_request||!g||Ft.current===`loaded`)return Promise.resolve();if(Ft.current===`loading`){let t=Bt.current;return t?t.then(()=>{if(!r&&Ft.current===`idle`)return e({silent:!1})}):Promise.resolve()}r||Ye(null),Ft.current=`loading`;let i=zt.current,a=Qt().then(e=>{if(i===zt.current){if(!e){Ft.current=`idle`;return}if(e.error){r||(He(e.comments),Ye(e.error),$e(t=>{let n=new Set(e.comments.map(e=>e.id));return new Set([...t].filter(e=>n.has(e)))})),Ft.current=`idle`;return}He(e.comments),Ye(null),$e(t=>{let n=new Set(e.comments.map(e=>e.id));return new Set([...t].filter(e=>n.has(e)))}),Ft.current=`loaded`}}).catch(e=>{i===zt.current&&(Ft.current=`idle`,!r&&(He([]),Ye(OJ(e,`Unable to load GitHub review comments right now.`)),$e(new Set)))}).finally(()=>{i===zt.current&&Bt.current===a&&(Bt.current=null)});return Bt.current=a,a},[tt?.bundle.pull_request,g,t,Qt,n]),cn=(0,Y.useCallback)((e,t)=>{Le(n=>({...n,[e]:t(n[e])}))},[]),ln=(0,Y.useCallback)(async e=>{if(S&&n&&t)return await At(t,n,e);if(x){if(!t)throw Error(`Project changes require a project id.`);return await Fe(t,e)}throw Error(`Pull request description generation requires a supported target context.`)},[S,t,n,x]),un=(0,Y.useCallback)(async e=>{if(!t)throw Error(`Project changes require a project id.`);return await We(t,e)},[t]),dn=(0,Y.useCallback)(async e=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await le(t,e)}return await tn(Ht(),t,e)},[t,Ht,h]),fn=(0,Y.useCallback)(async e=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await fe(t,e)}return await nn(Ht(),t,e)},[t,Ht,h]),pn=(0,Y.useCallback)(async(e={})=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await te(t,e)}return await rn(Ht(),t,e)},[t,Ht,h]),mn=(0,Y.useCallback)(async()=>{if(h===`project_root`){if(!t)throw Error(`Project changes require a project id.`);return await p(t)}return await on(Ht(),t)},[t,Ht,h]),hn=(0,Y.useCallback)(async(e,t={})=>{let n=t.preserveContent??!1,r=Et.current+1;Et.current=r,_e(!0),n||se(null);try{let t=await Jt();if(!e()||Et.current!==r)return;F(t.commits),se(null)}catch(t){if(!e()||Et.current!==r)return;se(OJ(t,`Unable to load local commits right now.`)),n||F([])}finally{e()&&Et.current===r&&_e(!1)}},[Jt]),gn=(0,Y.useCallback)(()=>{Et.current+=1,F([]),se(null),_e(!1)},[]),_n=(0,Y.useCallback)((e,t={})=>{let n=t.resetSelection??!1;Tt.current=e,N(e),ae(null),L(t=>{let r=HJ(t,e.files,n||!Ct.current);return Ct.current=!0,r})},[]),vn=(0,Y.useCallback)(async(e={})=>{let t=e.preserveContent??!1,n=e.gitStatusForCache??null;t||B(null),ue(!0);try{let e=await Kt();Ut(e),n&&Wt(e,n)}catch(e){n&&QK(Vt),(!t||!wt.current)&&B(OJ(e,`Unable to load the diff right now.`))}finally{ue(!1)}},[Ut,Vt,Kt,Wt]),yn=(0,Y.useCallback)(async(e={})=>{let t=e.preserveContent??!1;if(!S){j(null),V(null),pe(!1);return}t||V(null),pe(!0);try{j(await Zt()),V(null)}catch(e){(!t||!A)&&V(OJ(e,`Unable to load the branch diff right now.`))}finally{pe(!1)}},[A,S,Zt]),bn=(0,Y.useCallback)(async(e,t={})=>{let n=t.preserveContent??!1,r=t.resetSelection??!1,i=t.allowCache??!0?XK(Vt):null;if(n||(B(null),ae(null)),he(!0),i){Ut(i.diffResponse),_n(i.gitStatus,{resetSelection:r}),ue(!1);try{let t=await qt();if(!e())return;_n(t,{resetSelection:r}),he(!1),(t.ahead??0)>0?hn(e,{preserveContent:!0}):gn();let n=t.workspace_signature??null;if(n&&n===i.workspaceSignature){Wt(i.diffResponse,t);return}QK(Vt),await vn({preserveContent:!0,gitStatusForCache:t});return}catch(t){if(!e())return;ae(OJ(t,`Unable to load git status right now.`)),N(null),he(!1),gn();return}}ue(!0),Kt().then(t=>{e()&&(Ut(t),Tt.current&&Wt(t,Tt.current))}).catch(t=>{e()&&(!n||!wt.current)&&B(OJ(t,`Unable to load the diff right now.`))}).finally(()=>{e()&&ue(!1)});try{let t=await qt();if(!e())return;_n(t,{resetSelection:r}),he(!1),wt.current&&Wt(wt.current,t),(t.ahead??0)>0?hn(e,{preserveContent:n}):gn()}catch(t){if(!e())return;ae(OJ(t,`Unable to load git status right now.`)),n||N(null),he(!1),gn()}},[Ut,_n,Vt,gn,hn,vn,Kt,qt,Wt]),xn=(0,Y.useCallback)(async()=>{if(!t)return;let e=Ot.current+1;Ot.current=e,he(!0);try{let t=await qt();if(Ot.current!==e)return;let n=Tt.current?.workspace_signature??null,r=t.workspace_signature??null,i=!wt.current||n!==r;if(_n(t),(t.ahead??0)>0?hn(()=>Ot.current===e,{preserveContent:!0}):gn(),!i){Gt(t);return}await vn({preserveContent:!0,gitStatusForCache:t})}catch{return}finally{Ot.current===e&&he(!1)}},[_n,gn,hn,vn,t,qt,Gt]);(0,Y.useEffect)(()=>{wt.current=O},[O]),(0,Y.useEffect)(()=>{Tt.current=M},[M]),(0,Y.useEffect)(()=>{let e=!0;return bn(()=>e,{resetSelection:!0}),()=>{e=!1}},[bn]),(0,Y.useEffect)(()=>{if(t)return rq(e=>{if(e===t){if(Mt.current){Mt.current=!1;return}xn()}})},[t,xn]),(0,Y.useEffect)(()=>{if(!t)return;let e=aq(()=>{document.visibilityState===`visible`&&xn()});return()=>{e()}},[t,xn]),(0,Y.useEffect)(()=>{if(!S){Be(null),qe(null),Ze(new Set);return}if(!O?.diff?.trim()){Be(null),qe(null),Ze(new Set);return}let e=new AbortController,t=!0;return qe(null),Yt(e.signal).then(e=>{t&&(Be(e),Ze(t=>{let n=new Set((e?.findings??[]).map(e=>e.id));return new Set([...t].filter(e=>n.has(e)))}))}).catch(n=>{!t||e.signal.aborted||(qe(OJ(n,`Unable to load review findings right now.`)),Be(null),Ze(new Set))}),()=>{t=!1,e.abort()}},[O?.diff,S,Yt]),(0,Y.useEffect)(()=>{D(`uncommitted`),Nt.current=MJ(()=>null),Pt.current=NJ(),Le(jJ()),j(null),V(null),pe(!1),zt.current+=1,Ft.current=`idle`,Bt.current=null,He([]),Ye(null),$e(new Set),nt(null),it(null),ot(!1),ct(!1),ut(``),ft(``),mt(``),gt([]),vt(!1),bt(!1),xt(!1)},[n,C]),(0,Y.useEffect)(()=>{if(!S){nt(null),ot(!1);return}if(O===null&&!re){ot(!1);return}let e=new AbortController,t=!0;return ot(!0),Xt(e.signal).then(e=>{t&&(nt(e),ut(t=>t.trim()?t:e?.bundle?Dl(e.bundle):a),ft(t=>t.trim()?t:zJ(e?.recent_commit_subjects??ht)),mt(t=>t.trim()?t:e?.bundle.pull_request?.base_branch??``))}).catch(()=>{!t||e.signal.aborted||nt(null)}).finally(()=>{t&&ot(!1)}),()=>{t=!1,e.abort()}},[re,O,ht,t,Xt,S,a]),(0,Y.useEffect)(()=>{w&&(ut(e=>e.trim()&&e!==a?e:M?.branch??a),ft(e=>e.trim()?e:zJ(ht)))},[M?.branch,w,ht,a]),(0,Y.useEffect)(()=>{if(!S){j(null),V(null),pe(!1);return}if(E!==`bundle_diff`){pe(!1);return}let e=new AbortController,t=!0;return pe(!0),V(null),Zt(e.signal).then(e=>{t&&(j(e),V(null))}).catch(n=>{!t||e.signal.aborted||(V(OJ(n,`Unable to load the branch diff right now.`)),j(null))}).finally(()=>{t&&pe(!1)}),()=>{t=!1,e.abort()}},[E,S,Zt]),(0,Y.useEffect)(()=>{let e=tt?.bundle.pull_request??null;if(!S||!e){zt.current+=1,Ft.current=`idle`,Bt.current=null,He([]),Ye(null),$e(new Set);return}if(!g){zt.current+=1,Ft.current=`idle`,Bt.current=null,He([]),Ye(null),$e(new Set);return}sn({silent:!0})},[tt?.bundle.pull_request,sn,g,S]),(0,Y.useEffect)(()=>{E===`bundle_diff`&&sn({silent:!1})},[E,tt?.bundle.pull_request,sn,g]),(0,Y.useEffect)(()=>{me&&M===null||St.current?.focus()},[M,me]);let Sn=(0,Y.useMemo)(()=>{let e=typeof O?.diff==`string`?O.diff:``;return e.trim()?Bm(e).map(e=>({...e,pathCandidates:CJ(e)})):[]},[O]),Cn=(0,Y.useMemo)(()=>{let e=typeof A?.diff==`string`?A.diff:``;return e.trim()?Bm(e).map(e=>({...e,pathCandidates:CJ(e)})):[]},[A]),wn=(0,Y.useMemo)(()=>{let e=O?.diff??``;return e?PJ(e):null},[O?.diff]),Tn=(0,Y.useMemo)(()=>{let e=A?.diff??``;return e?PJ(e):null},[A?.diff]),En=E===`bundle_diff`?A:O,Dn=E===`bundle_diff`?Cn:Sn,On=(0,Y.useMemo)(()=>n?{uncommitted:kJ(n,`uncommitted`),bundle_diff:kJ(n,`bundle_diff`)}:{uncommitted:null,bundle_diff:null},[n]),kn=(0,Y.useMemo)(()=>({uncommitted:wn,bundle_diff:Tn}),[Tn,wn]),An=(0,Y.useMemo)(()=>{let e=new Map;for(let t of En?.files??[])e.set(t.path,t);return e},[En]),jn=(0,Y.useMemo)(()=>{let e=new Map;for(let t of Dn)for(let n of t.pathCandidates)e.has(n)||e.set(n,t);return e},[Dn]),Mn=(0,Y.useCallback)(e=>{Pe(t=>t.length===e.length&&t.every((t,n)=>t===e[n])?t:e)},[]),Nn=(0,Y.useMemo)(()=>E===`bundle_diff`?(A?.files??[]).map(e=>({path:e.path,originalPath:null,status:null,staged:!1,unstaged:!1,conflicted:!1,additions:e.additions,deletions:e.deletions})):M?(M.files??[]).map(e=>{let t=An.get(e.path)??(e.original_path?An.get(e.original_path):void 0);return{path:e.path,originalPath:e.original_path,status:e.status,staged:e.staged,unstaged:e.unstaged,conflicted:e.conflicted,additions:t?.additions??0,deletions:t?.deletions??0}}):(O?.files??[]).map(e=>({path:e.path,originalPath:null,status:null,staged:!1,unstaged:!1,conflicted:!1,additions:e.additions,deletions:e.deletions})),[E,A?.files,An,O?.files,M]);(0,Y.useEffect)(()=>{R!==`all`&&(Nn.some(e=>e.path===R)||z(`all`))},[R,Nn]);let Pn=E===`bundle_diff`?0:I.size,Fn=K!==null,In=K===`force`,Ln=E===`bundle_diff`?Nn.length:M?.files?.length??Nn.length,Rn=Ln>0&&Pn===Ln,zn=(0,Y.useMemo)(()=>E===`bundle_diff`?null:xJ(M,I),[E,M,I]),Bn=E===`uncommitted`&&!me&&!ve&&f&&!!M&&Pn>0&&ee.trim().length>0&&zn===null,Vn=E===`uncommitted`&&!me&&!ce&&!be&&!ve&&!Fn&&f&&!et&&!!M&&Pn>0,Hn=!me&&(Fn||!!M?.can_push&&(M?.ahead??0)>0),Un=Hn&&!!M?.can_force_push_with_lease,Wn=Hn&&f&&!Fn&&!ve,Gn=Un&&f&&!Fn&&!ve,Kn=f&&!G&&!we&&!ve&&!Fn&&(P?.length??0)>0,qn=(M?.ahead??0)>0?`${M?.ahead??0} to push`:`Up to date`,Jn=(M?.behind??0)>0?`${M?.behind??0} behind`:`In sync`,Yn=M?.branch??null,Xn=R===`all`?null:jn.get(R)??null,Zn=(0,Y.useMemo)(()=>R===`all`?Dn:Xn?[Xn]:[],[Dn,R,Xn]);(0,Y.useEffect)(()=>{je(new Map),Pe(yJ)},[E,Dn]),(0,Y.useEffect)(()=>{let e={uncommitted:On.uncommitted&&kn.uncommitted?`${On.uncommitted}:${kn.uncommitted}`:null,bundle_diff:On.bundle_diff&&kn.bundle_diff?`${On.bundle_diff}:${kn.bundle_diff}`:null},t=Nt.current;t.uncommitted===e.uncommitted&&t.bundle_diff===e.bundle_diff||(Nt.current=e,Le(n=>{let r={...n};return[`uncommitted`,`bundle_diff`].forEach(i=>{if(t[i]===e[i])return;let a=kn[i],o=On[i],s=n[i];if(t[i]===null&&a&&(s.activeTarget||s.editingCommentKey||s.draftInput.trim()||s.comments.size>0)){r[i]={...s,signature:a};return}if(!a){Pt.current[i]=new Map,r[i]=AJ();return}let c=new Map;if(o){let e=window.localStorage.getItem(o),t=e?IJ(e):null;t?.diffSignature===a?c=LJ(t.comments.map(e=>({...e,scope:i}))):e!==null&&window.localStorage.removeItem(o)}Pt.current[i]=new Map,r[i]={activeTarget:null,editingCommentKey:null,draftInput:``,comments:c,signature:a}}),r}))},[kn,On]),(0,Y.useEffect)(()=>{[`uncommitted`,`bundle_diff`].forEach(e=>{let t=On[e],n=kn[e],r=Ie[e];if(!t||!n||r.signature!==n)return;if(r.comments.size===0){window.localStorage.removeItem(t);return}let i={diffSignature:n,comments:[...r.comments.values()]};window.localStorage.setItem(t,JSON.stringify(i))})},[kn,On,Ie]),(0,Y.useEffect)(()=>{if(Dn.length===0)return;let e=!1,t=null,n=(()=>{if(!Xn){let e=[],t=new Set;for(let n of Ne){let r=jn.get(n);if(!r)continue;let i=wJ(r);t.has(i)||(t.add(i),e.push(r))}return e.length>0?e:Dn.slice(0,mJ)}return[Xn]})(),r=0,i=()=>{if(e)return;let a=n.slice(r,r+mJ);a.length!==0&&(je(e=>{let t=new Map(e);for(let e of a){let n=wJ(e);t.has(n)||t.set(n,DJ(e))}return t}),r+=mJ,r<n.length&&(t=window.setTimeout(i,0)))};return n.length<=mJ?i():t=window.setTimeout(i,0),()=>{e=!0,t!==null&&window.clearTimeout(t)}},[Dn,jn,Xn,Ne]);let Qn=(0,Y.useMemo)(()=>Zn.map(e=>({...e,tokens:Oe.get(wJ(e))??null})),[Oe,Zn]),$n=(0,Y.useMemo)(()=>Dn.map(e=>({...e,tokens:null})),[Dn]),er=(0,Y.useMemo)(()=>{let e=new Map;for(let t of Dn){let n=wJ(t);e.set(n,n);for(let r of CJ(t))e.set(r,n)}return e},[Dn]),tr=(0,Y.useMemo)(()=>[...Ie.uncommitted.comments.values()],[Ie.uncommitted.comments]),nr=(0,Y.useMemo)(()=>[...Ie.bundle_diff.comments.values()],[Ie.bundle_diff.comments]),rr=Ie[E],ir=rr.activeTarget,ar=rr.editingCommentKey,or=ir?.commentKey??ar,sr=or?`${E}:${or}`:E,cr=or?Pt.current[E].get(or)??rr.draftInput:rr.draftInput,lr=E===`bundle_diff`?nr:tr,ur=(0,Y.useMemo)(()=>[...tr,...nr],[nr,tr]),dr=(0,Y.useMemo)(()=>Re?.findings??[],[Re]),fr=(0,Y.useMemo)(()=>Re?.is_current_diff?dr.filter(e=>Xe.has(e.id)):[],[dr,Re?.is_current_diff,Xe]),pr=(0,Y.useMemo)(()=>[...Xe],[Xe]),mr=(0,Y.useMemo)(()=>Ve.filter(e=>Qe.has(e.id)),[Ve,Qe]),hr=(0,Y.useMemo)(()=>[...Qe],[Qe]),gr=ur.length+fr.length+mr.length,_r=!!(Re?.review_run&&dr.length>0&&!Re.is_current_diff),vr=tt?.bundle.pull_request??null,yr=vr??rt,br=(0,Y.useMemo)(()=>ht.length>0?ht:tt?.recent_commit_subjects??[],[tt?.recent_commit_subjects,ht]),xr=tt?.has_helper_model===!0||o,Sr=S,Cr=E===`bundle_diff`?ie:re,wr=ce&&O===null,Tr=de&&A===null,Er=me&&M===null,Dr=at&&tt===null,Or=E===`bundle_diff`?Tr:wr,kr=E===`uncommitted`?dr:_J,Ar=E===`uncommitted`?pr:yJ,jr=E===`bundle_diff`?Ve:vJ,Mr=E===`bundle_diff`?hr:yJ,Nr=E===`bundle_diff`?`bundle_diff`:`uncommitted`,Pr=(0,Y.useMemo)(()=>{let e=new Map,t=e=>e?er.get(e)??e:null;for(let n of lr){let r=t(n.filePath);r&&RJ(e,r)}if(E===`uncommitted`){if(_r)return e;for(let n of dr){let r=t(n.file_path);r&&RJ(e,r)}return e}for(let n of Ve){let r=t(n.file_path);r&&RJ(e,r)}return e},[E,er,lr,Ve,_r,dr]),Fr=(_r?0:dr.length)+tr.length,Ir=Ve.length+nr.length,Lr=E===`bundle_diff`?`No branch diff to show.`:`No uncommitted changes to show.`,Rr=E===`uncommitted`&&Sr?`Switch to Branch diff to review the full branch diff.`:null,zr=Sr&&!Dr&&!!tt&&tt?.bundle.kind!==`project_root`&&M?.has_upstream===!0&&g,Br=BJ({gitStatus:M,isProjectTargetRepoRoot:w,isGitHubConnected:g,effectiveDefaultBaseBranch:T}),Vr=zr||Br,Hr=Vr&&!vr&&!rt&&!_t&&!yt&&!X&&!et&&!Fn&&!ve&&!we&&(M?.ahead??0)===0&&!!M?.branch,Ur=(0,Y.useCallback)(e=>{if(!e){ct(!1);return}if(!S){ct(e);return}if(!t||!n||!zr||vr||yt){ct(e);return}bt(!0),jt(t,n).then(e=>{nt(e),mt(t=>t.trim()?t:e.bundle.pull_request?.base_branch??``),ct(!e.bundle.pull_request)}).catch(e=>{Q.error(OJ(e,`Unable to check for an existing pull request right now.`),{id:`ticket-changes-sync-pr-error`}),ct(!0)}).finally(()=>{bt(!1)})},[vr,S,yt,t,n,zr]),Wr=(0,Y.useMemo)(()=>{if(Vr)return(M?.ahead??0)>0?`Push the branch before creating a pull request.`:M?.branch?m:pJ(`branchUnavailable`)},[m,M?.ahead,M?.branch,Vr]),Gr=d&&!Or&&(E===`bundle_diff`||!Er)&&!ve&&!Fn&&!we,Kr=ir?Gr||rr.comments.has(ir.commentKey):Gr,qr=!!c&&l&&gr>0&&!et,Jr=(0,Y.useCallback)(e=>{Ze(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Yr=(0,Y.useCallback)(e=>{$e(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Xr=(0,Y.useCallback)(()=>{Pt.current=NJ(),Le(e=>({uncommitted:{...e.uncommitted,activeTarget:null,editingCommentKey:null,draftInput:``,comments:new Map},bundle_diff:{...e.bundle_diff,activeTarget:null,editingCommentKey:null,draftInput:``,comments:new Map}}))},[]),Zr=(0,Y.useCallback)(()=>{Xr(),Ze(new Set),$e(new Set)},[Xr]),Qr=(0,Y.useCallback)(async()=>{if(!(!t||!Hr)){vt(!0);try{if(S&&n){let e=await kt(t,n,{title:lt.trim(),body:dt.trim(),base_branch:pt.trim()||null});nt(e),mt(e.bundle.pull_request?.base_branch??pt.trim())}else{let e=await un({title:lt.trim(),body:dt.trim(),base_branch:pt.trim()||null});it(e.pull_request),mt(e.pull_request.base_branch||pt.trim())}ct(!1),Q.success(pJ(`pullRequestCreated`),{id:`ticket-changes-create-pr-success`})}catch(e){Q.error(OJ(e,pJ(`createPullRequestFallbackError`)),{id:`ticket-changes-create-pr-error`})}finally{vt(!1)}}},[Hr,t,pt,dt,lt,un,n,S]),$r=(0,Y.useCallback)(async()=>{if(!(!t||!Vr||X)){xt(!0);try{ft((await ln({title:lt.trim(),commit_subjects:br})).description)}catch(e){Q.error(OJ(e,`Unable to generate the pull request description right now.`),{id:`ticket-changes-generate-pr-description-error`})}finally{xt(!1)}}},[X,t,br,lt,ln,Vr]),ei=(0,Y.useCallback)(({filePath:e,changeKey:t,commentKey:n})=>{let r=rr.comments.get(n),i=Pt.current[E].get(n)??r?.comment??``;if(r){z(r.filePath),cn(E,e=>({...e,activeTarget:null,editingCommentKey:n,draftInput:i}));return}Gr&&cn(E,r=>({...r,activeTarget:{filePath:e,changeKey:t,commentKey:n},editingCommentKey:null,draftInput:i}))},[E,rr.comments,Gr,cn]),ti=(0,Y.useCallback)(()=>{or&&Pt.current[E].delete(or),cn(E,e=>({...e,activeTarget:null,editingCommentKey:null,draftInput:``}))},[E,or,cn]),ni=(0,Y.useCallback)(e=>{or&&Pt.current[E].set(or,e)},[E,or]),ri=(0,Y.useCallback)((e,t)=>{let n=rr.comments.has(e.commentKey);if(!Gr&&!n)return;let r=t.trim();if(!r)return;let i=e.change.type===`insert`?null:`oldLineNumber`in e.change?e.change.oldLineNumber:e.change.lineNumber,a=e.change.type===`delete`?null:`newLineNumber`in e.change?e.change.newLineNumber:e.change.lineNumber;cn(E,t=>{let n=new Map(t.comments);return n.set(e.commentKey,{scope:E,filePath:e.filePath,changeKey:e.changeKey,changeType:e.change.type,oldLineNumber:i,newLineNumber:a,hunkHeader:e.hunk.content,lineContent:e.change.content,diffSnippet:ub(e.hunk,e.change),comment:r}),{...t,activeTarget:null,editingCommentKey:null,draftInput:``,comments:n}}),Pt.current[E].delete(e.commentKey)},[E,rr.comments,Gr,cn]),ii=(0,Y.useCallback)(e=>{let t=rr.comments.get(e);if(!t)return;z(t.filePath);let n=Pt.current[E].get(e)??t.comment;cn(E,t=>({...t,activeTarget:null,editingCommentKey:e,draftInput:n}))},[E,rr.comments,cn]),ai=(0,Y.useCallback)(e=>{Pt.current[E].delete(e),cn(E,t=>{let n=new Map(t.comments);return n.delete(e),{...t,activeTarget:t.activeTarget?.commentKey===e?null:t.activeTarget,editingCommentKey:t.editingCommentKey===e?null:t.editingCommentKey,draftInput:t.activeTarget?.commentKey===e||t.editingCommentKey===e?``:t.draftInput,comments:n}})},[E,cn]),oi=(0,Y.useCallback)(async()=>{if(!c||!qr)return;J(!0);let e=yb({drafts:ur,findings:fr,githubComments:mr,uncommittedFiles:Sn,bundleFiles:Cn});try{await c(e),Xr(),Ze(new Set),$e(new Set),Be(e=>e&&{...e,findings:[],is_current_diff:!1}),Q.success(`Fixes submitted.`,{id:`ticket-diff-review-submit-success`}),s()}catch(e){Q.error(OJ(e,`Unable to submit the review right now.`),{id:`ticket-diff-review-submit-error`})}finally{J(!1)}},[ur,Cn,qr,Xr,s,c,mr,fr,Sn]),si=(0,Y.useCallback)(()=>{if(E===`bundle_diff`){yn();return}bn(()=>!0,{allowCache:!1,resetSelection:!Ct.current})},[E,yn,bn]),ci=(0,Y.useMemo)(()=>c?(0,Z.jsx)(WG,{reviewComments:ur,reviewFindings:fr,githubComments:mr,pendingFixCount:gr,canSendReview:qr,isSubmittingReview:et,reviewSubmitDisabledReason:u,onClearPendingFixes:Zr,onSubmitReview:()=>{oi()}}):null,[ur,qr,Zr,oi,et,c,gr,u,mr,fr]),li=e=>{L(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},ui=()=>{M&&L(Rn?new Set:bJ(M.files))},di=async()=>{if(Bn){ye(!0);try{let e=await dn({message:ee.trim(),selected_paths:[...I]});e.ticket&&y?.(e.ticket),_n(e.git_status,{resetSelection:!0}),ne(``),t&&(Mt.current=!0,nq(t)),v&&b?.(v),await vn({preserveContent:!0,gitStatusForCache:e.git_status}),await yn({preserveContent:!0}),(e.git_status.ahead??0)>0?await hn(()=>!0):gn(),Q.success(`Commit created.`,{id:`ticket-git-commit-success`})}catch(e){Q.error(OJ(e,`Unable to create the commit right now.`),{id:`ticket-git-commit-error`})}finally{ye(!1)}}},fi=async()=>{if(Vn){xe(!0);try{ne((await fn({selected_paths:[...I]})).message),St.current?.focus()}catch(e){Q.error(OJ(e,`Unable to generate a commit message right now.`),{id:`ticket-git-commit-message-error`})}finally{xe(!1)}}},pi=async(e=`normal`)=>{if(!(e===`force`?!Gn:!Wn)){Se(e);try{let r=P.map(e=>e.subject.trim()).filter(Boolean),i=await pn({forceWithLease:e===`force`});if(i.ticket&&y?.(i.ticket),_n(i.git_status,{resetSelection:!0}),Gt(i.git_status),gt(r),gn(),t&&(Mt.current=!0,nq(t)),v&&b?.(v),Q.success(e===`force`?i.git_status.ahead===0?pJ(`branchForcePushed`):pJ(`forcePushCompleted`):i.git_status.ahead===0?pJ(`branchPushed`):pJ(`pushCompleted`),{id:`ticket-git-push-success`}),i.git_status.ahead===0)if(S&&t&&n)try{let e=await Dt(t,n);nt(e),ut(t=>t.trim()?t:Dl(e.bundle)),ft(e=>e.trim()?e:zJ(r)),mt(t=>t.trim()?t:e.bundle.pull_request?.base_branch??``)}catch{}else BJ({gitStatus:i.git_status,isProjectTargetRepoRoot:w,isGitHubConnected:g,effectiveDefaultBaseBranch:T})||s()}catch(t){Q.error(OJ(t,pJ(e===`force`?`forcePushFallbackError`:`pushFallbackError`)),{id:`ticket-git-push-error`})}finally{Se(null)}}},mi=async()=>{if(Kn){Te(!0);try{let e=await mn();e.ticket&&y?.(e.ticket),_n(e.git_status,{resetSelection:!0}),F(e.commits),se(null),_e(!1),t&&(Mt.current=!0,nq(t)),v&&b?.(v),await vn({preserveContent:!0,gitStatusForCache:e.git_status}),await yn({preserveContent:!0}),Q.success(`Latest local commit undone.`,{id:`ticket-git-undo-success`})}catch(e){Q.error(OJ(e,`Unable to undo the latest local commit right now.`),{id:`ticket-git-undo-error`})}finally{Te(!1)}}};return(0,Z.jsx)(pu,{onClose:s,overlayClassName:`z-[70] bg-black/30 p-[5vh]`,panelClassName:`flex h-[92vh] w-full max-w-none flex-col overflow-hidden rounded-2xl border border-border bg-card p-6 shadow-2xl`,renderContent:({closeButton:e})=>(0,Z.jsxs)(Z.Fragment,{children:[Fn&&(0,Z.jsx)(`div`,{className:`absolute inset-0 z-10 flex items-center justify-center rounded-2xl bg-black/45 backdrop-blur-sm`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 rounded-xl border border-border bg-card/95 px-4 py-3 text-sm text-foreground shadow-xl`,children:[(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}),(0,Z.jsx)(`span`,{children:`Pushing branch...`})]})}),(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-4 overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-semibold uppercase tracking-widest text-muted-foreground`,children:`Changes`}),Yn?(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`h2`,{className:`max-w-full truncate font-mono text-lg font-semibold text-foreground`,children:Yn}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(U,{variant:(M?.ahead??0)>0?`info`:`outline`,children:qn}),(0,Z.jsx)(U,{variant:(M?.behind??0)>0?`warning`:`outline`,children:Jn}),(0,Z.jsx)(U,{variant:M?.is_dirty?`warning`:`success`,children:M?.is_dirty?`Dirty`:`Clean`})]})]}):(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`h-7 w-56 animate-pulse rounded-md bg-muted/70`,"aria-hidden":`true`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsx)(`div`,{className:`h-6 w-32 animate-pulse rounded-full bg-muted/60`,"aria-hidden":`true`}),(0,Z.jsx)(`div`,{className:`h-6 w-20 animate-pulse rounded-full bg-muted/60`,"aria-hidden":`true`}),(0,Z.jsx)(`div`,{className:`h-6 w-20 animate-pulse rounded-full bg-muted/60`,"aria-hidden":`true`})]})]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-2 text-xs text-muted-foreground`,children:[(yr||Vr)&&(0,Z.jsx)(VJ,{pullRequest:yr,isLoading:Dr,isOpen:st,canCreate:Hr,disabledReason:Wr,isCreating:_t,isSyncing:yt,isGeneratingDescription:X,title:lt,body:dt,baseBranch:pt,onOpenChange:Ur,onTitleChange:ut,onBodyChange:ft,onBaseBranchChange:mt,showGenerateDescription:xr,onGenerateDescription:()=>{$r()},onCreate:()=>{Qr()}}),(0,Z.jsx)(KG,{isCommitsLoading:G,commitsError:oe,unpushedCommits:P,canUndoLatestCommit:Kn,isUndoing:we,aheadCount:M?.ahead??0,onUndoLatestCommit:()=>{mi()}}),Hn&&(Un?(0,Z.jsxs)(`div`,{className:`flex items-stretch`,children:[(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`default`,onClick:()=>{pi()},disabled:!Wn,title:m,className:`gap-2 rounded-r-none`,children:[Fn?(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}):(0,Z.jsx)(Pc,{className:`h-4 w-4`}),pJ(In?`forcePushing`:Fn?`pushing`:`pushBranch`)]}),(0,Z.jsxs)(Ue,{children:[(0,Z.jsx)(Ce,{asChild:!0,children:(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`default`,disabled:!Gn,"aria-label":pJ(`morePushActions`),className:`rounded-l-none border-l border-primary-foreground/20 px-2`,children:(0,Z.jsx)(ke,{className:`h-4 w-4`})})}),(0,Z.jsx)(Me,{align:`end`,className:`w-56`,children:(0,Z.jsx)(ze,{disabled:!Gn,onSelect:()=>{pi(`force`)},children:pJ(`forcePushWithLease`)})})]})]}):(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`default`,onClick:()=>{pi()},disabled:!Wn,title:m,className:`gap-2`,children:[Fn?(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}):(0,Z.jsx)(Pc,{className:`h-4 w-4`}),pJ(Fn?`pushing`:`pushBranch`)]})),e]})]}),(0,Z.jsxs)(`div`,{"data-testid":`ticket-changes-layout`,className:`grid min-h-0 flex-1 gap-4 lg:grid-cols-[18rem_minmax(0,1fr)] xl:grid-cols-[20rem_minmax(0,1fr)]`,children:[(0,Z.jsxs)(`aside`,{className:`flex min-h-0 flex-col`,children:[Sr&&(0,Z.jsxs)(LG,{type:`single`,size:`sm`,variant:`outline`,value:E,onValueChange:e=>{(e===`uncommitted`||e===`bundle_diff`)&&D(e)},className:`mb-3 self-start`,children:[(0,Z.jsxs)(RG,{value:`uncommitted`,className:`gap-2`,children:[(0,Z.jsx)(`span`,{children:`Uncommitted`}),Fr>0&&(0,Z.jsx)(`span`,{className:`rounded-full border border-sky-400/40 bg-sky-400/12 px-1.5 py-0.5 text-[10px] font-semibold leading-none text-sky-100`,children:Fr})]}),(0,Z.jsxs)(RG,{value:`bundle_diff`,className:`gap-2`,children:[(0,Z.jsx)(`span`,{children:`Branch diff`}),Ir>0&&(0,Z.jsx)(`span`,{className:`rounded-full border border-violet-400/40 bg-violet-400/12 px-1.5 py-0.5 text-[10px] font-semibold leading-none text-violet-100`,children:Ir})]})]}),(0,Z.jsx)(HK,{selectionWarning:E===`uncommitted`?zn:null,gitError:E===`uncommitted`?H:ie,sidebarFiles:Nn,commentCountByPath:Pr,commentCountTone:Nr,isGitStatusLoading:E===`bundle_diff`?Tr:Er&&Nn.length===0,selectedPaths:I,selectedDiffPath:R,allFilesSelected:Rn,diffStats:En?.stats??null,title:E===`bundle_diff`?`Branch diff files`:`Changed files`,allChangesDescription:E===`bundle_diff`?`Review the full branch diff against the review base.`:`Review the full workspace diff.`,enableSelection:E===`uncommitted`&&!Er,onToggleSelectAll:ui,onSelectDiffPath:z,onTogglePath:li})]}),(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-col gap-3`,children:[(0,Z.jsx)(LK,{selectedDiffPath:R,sidebarFiles:Nn,diffResponse:En,isDiffLoading:Or,diffError:Cr,allDiffFiles:$n,renderedFiles:Qn,viewType:Ee,onViewTypeChange:De,onRetry:si,activeReviewTarget:ir,editingReviewCommentKey:ar,reviewDraftInstanceKey:sr,reviewDraftInput:cr,reviewComments:lr,reviewFindings:kr,githubComments:jr,selectedReviewFindingIds:Ar,selectedGitHubCommentIds:Mr,canSelectReviewTarget:Gr,canEditActiveReviewDraft:Kr,reviewFindingsError:E===`uncommitted`?Ge:null,gitHubCommentsError:E===`bundle_diff`?Je:null,hasStaleReviewFindings:E===`uncommitted`?_r:!1,onSelectReviewTarget:ei,onToggleReviewFindingSelection:Jr,onToggleGitHubCommentSelection:Yr,onReviewDraftInputChange:ni,onCancelReviewDraft:ti,onEditReviewDraft:ii,onRemoveReviewDraft:ai,onSaveReviewDraft:ri,diffThemeClassName:UK,resolveFilePath:wJ,normalizeDiffPath:SJ,onVisibleFilePathsChange:Mn,emptyStateTitle:Lr,emptyStateDescription:Rr,reviewSummaryControl:ci,headerLayout:`inline-controls`}),E===`uncommitted`&&(0,Z.jsx)(`div`,{className:`mt-auto shrink-0`,children:(0,Z.jsx)(GG,{commitMessage:ee,onCommitMessageChange:ne,commitMessageRef:St,selectedFileCount:Pn,changesDisabledReason:m,canEditCommitMessage:f&&!et,canGenerateCommitMessage:Vn,canCommit:Bn,isGeneratingCommitMessage:be,isCommitting:ve,onGenerateCommitMessage:()=>{fi()},onCommit:()=>{di()}})})]})]})]})]})})},WJ={blocked:{className:`stroke-red-400/80`,markerId:`dependency-arrowhead-blocked`},ready:{className:`stroke-emerald-400/80`,markerId:`dependency-arrowhead-ready`},preview:{className:`stroke-amber-300/80`,markerId:`dependency-arrowhead-preview`}},GJ=e=>qw(e)?`ready`:`blocked`,KJ=180,qJ=560,JJ=88,YJ=12,XJ=18,ZJ=(e,t,n)=>Math.min(Math.max(e,t),n),QJ=(e,t,n)=>n&&n.width>0&&n.height>0?n:Object.values(e).reduce((e,t)=>({width:Math.max(e.width,t.left+t.width),height:Math.max(e.height,t.top+t.height)}),{width:t.x,height:t.y}),$J=(e,t)=>{let n=ZJ(Math.round(e.length*7.2)+24,KJ,qJ),r=Math.max(KJ,t-YJ*2);return Math.min(n,r)},eY=(e,t,n,r,i)=>{let a=n.get(e.blockerTicketId);if(!a)return null;let o=e.hoveredTicketId&&e.hoveredTicketId!==e.blockerTicketId?r[e.hoveredTicketId]:null,s=e.hoveredTicketId&&e.hoveredTicketId!==e.blockerTicketId?n.get(e.hoveredTicketId):null,c=s?`${a.title} is blocking ${s.title}`:`${a.title} is blocking...`,{start:l,end:u}=tT(t,o??{left:e.pointer.x,top:e.pointer.y,width:0,height:0}),d=QJ(r,e.pointer,i),f=o&&s?{x:l.x+(u.x-l.x)*.6,y:l.y+(u.y-l.y)*.6-28}:{x:u.x,y:u.y-28},p=$J(c,d.width);return{text:c,x:o&&s?ZJ(f.x-p/2,YJ,Math.max(YJ,d.width-p-YJ)):(()=>{let e=f.x+XJ,t=f.x-XJ-p;return e+p<=d.width-YJ?e:t>=YJ?t:ZJ(e,YJ,Math.max(YJ,d.width-p-YJ))})(),y:ZJ(f.y,YJ,Math.max(YJ,d.height-JJ-YJ)),width:p}},tY=({blockerRect:e,dependentRect:t,className:n,testId:r,markerEnd:i})=>{let{start:a,end:o}=tT(e,t),{path:s}=nT(a,o);return(0,Z.jsx)(`g`,{"data-testid":r,children:(0,Z.jsx)(`path`,{d:s,className:n,fill:`none`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,markerEnd:i})})},nY=({preview:e,cardRects:t,ticketsById:n,overlaySize:r})=>{if(!e)return null;let i=t[e.blockerTicketId];if(!i)return null;let a=(e.hoveredTicketId&&e.hoveredTicketId!==e.blockerTicketId&&t[e.hoveredTicketId]?t[e.hoveredTicketId]:null)??{left:e.pointer.x,top:e.pointer.y,width:0,height:0},o=eY(e,i,n,t,r);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(tY,{blockerRect:i,dependentRect:a,className:WJ.preview.className,testId:`dependency-preview`,markerEnd:`url(#${WJ.preview.markerId})`}),(e=>o?(0,Z.jsx)(`foreignObject`,{x:o.x,y:o.y,width:o.width,height:JJ,"data-testid":`dependency-preview-label`,children:e}):null)((0,Z.jsx)(`div`,{className:`pointer-events-none flex h-full w-full items-start`,children:(0,Z.jsx)(`div`,{className:`max-w-full rounded-md border border-amber-300/60 bg-stone-950/85 px-3 py-1.5 text-xs font-medium leading-5 text-amber-100 shadow-lg shadow-stone-950/20 whitespace-normal break-words`,children:o?.text})}))]})},rY=({dependencies:e,cardRects:t,preview:n,ticketsById:r,overlaySize:i})=>(0,Z.jsxs)(`svg`,{className:`pointer-events-none absolute inset-0 z-10 h-full w-full overflow-visible`,children:[(0,Z.jsx)(`defs`,{children:Object.values(WJ).map(e=>(0,Z.jsx)(`marker`,{id:e.markerId,markerWidth:`8`,markerHeight:`8`,refX:`7`,refY:`4`,orient:`auto`,markerUnits:`userSpaceOnUse`,children:(0,Z.jsx)(`path`,{d:`M 0 0 L 8 4 L 0 8`,className:e.className,fill:`none`,strokeWidth:`1.6`,strokeLinecap:`round`,strokeLinejoin:`round`})},e.markerId))}),e.map(e=>{let n=r.get(e.blocker_ticket_id),i=r.get(e.dependent_ticket_id),a=t[e.blocker_ticket_id],o=t[e.dependent_ticket_id];if(n?.parked_at||i?.parked_at)return null;let s=WJ[GJ(n)];return!a||!o?null:(0,Z.jsx)(tY,{blockerRect:a,dependentRect:o,className:s.className,testId:`dependency-edge-${e.blocker_ticket_id}-${e.dependent_ticket_id}`,markerEnd:`url(#${s.markerId})`},`${e.blocker_ticket_id}:${e.dependent_ticket_id}`)}),(0,Z.jsx)(nY,{preview:n,cardRects:t,ticketsById:r,overlaySize:i})]}),iY=({onSubmit:e,bundles:t,projectId:n=null,projectBranchState:r=null,tool:i,showModelSelector:a=!1,availableModels:o=[],availableSkills:s=[],initialModel:c=``,initialVariant:l=``,initialSkills:u=[],initialWorktreeBundleId:d=null,onCreateBundle:f,onDeleteBundle:p,onRefreshBundles:m,onClose:h})=>{let{t:g}=X(`common`),{jiraImportState:_,importFromJira:v}=_f(n);return(0,Z.jsx)(pu,{onClose:h,overlayClassName:`bg-black/60`,panelClassName:`h-[92vh] w-[96vw] max-w-6xl overflow-y-auto rounded-2xl border border-border bg-card p-4 shadow-2xl sm:p-5 lg:p-6`,renderContent:({closeButton:y})=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`absolute right-4 top-4 z-10 sm:right-5 sm:top-5 lg:right-6 lg:top-6`,children:y}),(0,Z.jsx)(aP,{heading:g(`newTicketModal.heading`),bundles:t,showModelSelector:a,availableModels:o,availableSkills:s,projectId:n,initialModel:c,initialVariant:l,initialSkills:u,initialWorktreeBundleId:d,projectBranchState:r,jiraImportState:_,onImportFromJira:v,onCancel:h,onCreateBundle:f,onDeleteBundle:p,onRefreshBundles:m,titleInputId:`title`,descriptionInputId:`description`,bundleSelectId:`new-ticket-bundle`,modelSelectId:`new-model`,variantSelectId:`new-variant`,skillsSelectId:`new-skills`,showEmptyBundleOption:!0,planAction:i?{label:g(`newTicketModal.actions.plan`),onClick:async({title:t,description:n,model:r,variant:i,skills:a,worktree_bundle_id:o,external_source:s})=>{await e(t,n,`plan`,r,i,a,{worktree_bundle_id:o??void 0,...s?{external_source:s}:{}}),h()}}:void 0,primaryAction:{label:g(`newTicketModal.actions.createTicket`),variant:`subtle`,onClick:async({title:t,description:n,model:r,variant:i,skills:a,worktree_bundle_id:o,external_source:s})=>{await e(t,n,`create`,r,i,a,{worktree_bundle_id:o??void 0,...s?{external_source:s}:{}}),h()}},secondaryAction:{label:g(`newTicketModal.actions.createAndBuild`),variant:`brand`,showAdvanceIcon:!0,onClick:async({title:t,description:n,model:r,variant:i,skills:a,worktree_bundle_id:o,external_source:s})=>{await e(t,n,`build`,r,i,a,{worktree_bundle_id:o??void 0,...s?{external_source:s}:{}}),h()}}})]})})},aY=e=>{let t=Math.max(0,Date.now()-e),n=Math.floor(t/1e3);return n<60?`${n}s`:`${Math.floor(n/60)}m ${n%60}s`},oY=e=>e.status===`error`?`border-red-500/35 bg-red-500/10`:e.status===`done`?e.boardState===`fading`?`border-emerald-500/25 bg-emerald-500/10 opacity-0 transition-opacity duration-700`:`border-emerald-500/35 bg-emerald-500/10`:`border-violet-500/30 bg-card/60`,sY=({run:e})=>(0,Z.jsxs)(gu,{"data-testid":`planning-run-card-${e.id}`,className:`relative overflow-hidden rounded-xl border shadow-none ${oY(e)}`,children:[e.status===`running`&&(0,Z.jsx)(`div`,{"aria-hidden":`true`,className:`absolute inset-x-0 top-0 h-1 animate-pulse bg-gradient-to-r from-violet-500/0 via-violet-300/80 to-violet-500/0`}),(0,Z.jsxs)(xu,{className:`space-y-3 p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[e.status===`running`?(0,Z.jsx)(aT,{label:`Planning...`}):e.status===`done`?(0,Z.jsx)(aT,{label:`Done`,className:`bg-emerald-500/85 text-emerald-50`}):(0,Z.jsx)(aT,{label:`Planning failed`,className:`bg-red-500/85 text-red-50`}),(0,Z.jsx)(`span`,{className:`text-[11px] uppercase tracking-[0.16em] text-muted-foreground`,children:aY(e.submittedAt)})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`line-clamp-2 text-sm font-medium text-foreground`,children:e.description}),e.status===`done`&&e.summary&&(0,Z.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[`Created `,e.summary.ticketCount,` tickets, `,e.summary.dependencyCount,` dependencies`,e.summary.ticketsWithOpenQuestions>0?`, ${e.summary.ticketsWithOpenQuestions} open question${e.summary.ticketsWithOpenQuestions===1?``:`s`}`:``]}),e.status===`error`&&e.error&&(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-red-200`,children:e.error})]})]})]}),cY={idle:`bg-secondary`,running:`bg-sky-400`,done:`bg-emerald-400`,error:`bg-red-400`},lY=e=>e.some(e=>e.status===`running`)?`running`:e.some(e=>e.status===`error`)?`error`:e.some(e=>e.status===`done`)?`done`:`idle`,uY=e=>{let t=Math.max(0,Date.now()-e),n=Math.floor(t/1e3);return n<60?`${n}s`:`${Math.floor(n/60)}m ${n%60}s`},dY=({status:e})=>{let{t}=X(`common`);return e===`running`?(0,Z.jsx)(aT,{label:t(`planningAgentSidebar.runStatus.planning`),className:`px-2.5 py-0.5 text-[11px]`}):e===`done`?(0,Z.jsx)(U,{className:`bg-emerald-500/85 px-2.5 py-0.5 text-[11px] text-emerald-50`,children:t(`planningAgentSidebar.runStatus.done`)}):(0,Z.jsx)(U,{className:`bg-red-500/85 px-2.5 py-0.5 text-[11px] text-red-50`,children:t(`planningAgentSidebar.runStatus.failed`)})},fY=({heading:e,runs:t})=>{let{t:n}=X(`common`);return t.length===0?null:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2.5`,children:[(0,Z.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-[0.16em] text-muted-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`flex flex-col gap-2.5`,children:t.map(e=>(0,Z.jsx)(gu,{className:`rounded-2xl border-border bg-card/70 shadow-none`,children:(0,Z.jsxs)(xu,{className:`space-y-2 p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsx)(`p`,{className:`line-clamp-2 text-sm font-medium text-foreground`,children:e.description}),(0,Z.jsx)(dY,{status:e.status})]}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:uY(e.submittedAt)}),e.summary&&(0,Z.jsxs)(`span`,{children:[n(`planningAgentSidebar.runSummary.tickets`,{count:e.summary.ticketCount}),`, `,n(`planningAgentSidebar.runSummary.dependencies`,{count:e.summary.dependencyCount}),e.summary.ticketsWithOpenQuestions>0?`, ${n(`planningAgentSidebar.runSummary.openQuestions`,{count:e.summary.ticketsWithOpenQuestions})}`:``]})]}),e.error&&(0,Z.jsx)(`div`,{className:`rounded-xl border border-red-500/30 bg-destructive/15 px-3 py-2 text-xs text-red-200`,children:e.error})]})},e.id))})]})},pY=({projectId:e=null,state:t,bundles:n,showModelSelector:r,availableModels:i,availableSkills:a,onManageBundles:o,onToggle:s,onDescriptionChange:c,onModelChange:l,onVariantChange:u,onSkillsChange:d,onBundleChange:f,onGenerate:p})=>{let{t:m}=X(`common`),h=i.find(e=>e.id===t.composer.model)??null,{jiraImportState:g,importFromJira:_}=_f(t.isOpen?e:null),v=(0,Y.useRef)(null),y=(0,Y.useRef)(t.isOpen),b=(0,Y.useRef)(t.isOpen),x=lY(t.runs),S=t.runs.filter(e=>e.status===`running`),C=t.runs.filter(e=>e.status!==`running`),w=t.composer.description.trim().length>0,T=m(`planningAgentSidebar.actions.planTickets`);(0,Y.useEffect)(()=>{if(t.isOpen&&!y.current&&(b.current=!0),t.isOpen||(b.current=!1),y.current=t.isOpen,!t.isOpen||!b.current)return;let e=window.requestAnimationFrame(()=>{let e=document.activeElement,t=e instanceof HTMLElement&&e.closest(`[data-testid="planning-agent-rail"]`)!==null;if(e instanceof HTMLElement&&e!==document.body&&e!==v.current&&!t){b.current=!1;return}v.current?.focus({preventScroll:!0}),b.current=!1});return()=>{window.cancelAnimationFrame(e)}},[t.isOpen]),(0,Y.useEffect)(()=>{if(!t.isOpen)return;let e=e=>{e.key!==`Escape`||e.defaultPrevented||(e.preventDefault(),s())};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[s,t.isOpen]);let E=(0,Z.jsxs)(q,{type:`button`,"aria-label":t.isOpen?m(`planningAgentSidebar.actions.closeAriaLabel`):m(`planningAgentSidebar.actions.openAriaLabel`),"aria-pressed":t.isOpen,onClick:s,variant:`outline`,className:`relative flex h-14 w-11 flex-col items-center justify-center gap-1 p-0`,children:[(0,Z.jsx)(Kd,{className:`size-5`}),(0,Z.jsx)(hw,{"aria-hidden":`true`,children:`A`}),(0,Z.jsx)(`span`,{className:`absolute top-1 right-1 h-2.5 w-2.5 rounded-full ring-2 ring-card ${cY[x]}`})]});return(0,Z.jsxs)(`aside`,{"aria-label":m(`planningAgentSidebar.ariaLabel`),className:`relative z-20 h-full w-16 shrink-0 overflow-visible border-r border-border bg-background`,children:[(0,Z.jsx)(`div`,{"data-testid":`planning-agent-rail`,className:`relative z-40 flex h-full w-16 shrink-0 flex-col items-center border-r border-border bg-background py-4`,children:t.isOpen?E:(0,Z.jsx)(xc,{content:m(`planningAgentSidebar.tooltip`),children:E})}),(0,Z.jsx)(`div`,{"data-testid":`planning-agent-drawer`,"aria-hidden":!t.isOpen,inert:!t.isOpen||void 0,className:K(`absolute inset-y-0 left-16 z-30 w-[min(36rem,calc(100vw-5rem))] overflow-hidden transition-transform duration-200 ease-out motion-reduce:transition-none`,t.isOpen?`pointer-events-auto translate-x-0`:`pointer-events-none -translate-x-full`),children:(0,Z.jsxs)(`div`,{className:`flex h-full w-[min(36rem,calc(100vw-5rem))] flex-col border-r border-border bg-background`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-start justify-between gap-4 border-b border-border px-6 py-5`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold text-foreground`,children:m(`planningAgentSidebar.title`)}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs leading-5 text-muted-foreground`,children:m(`planningAgentSidebar.description`)})]}),(0,Z.jsx)(q,{type:`button`,"aria-label":m(`planningAgentSidebar.actions.closePanelAriaLabel`),onClick:s,variant:`ghost`,size:`icon-sm`,className:`shrink-0 text-muted-foreground hover:text-foreground`,children:(0,Z.jsx)(Ve,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{"data-testid":`planning-agent-scroll-body`,className:`min-h-0 flex-1 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`space-y-5 px-6 py-5`,children:[(0,Z.jsx)(tP,{jiraImportState:g,onImportFromJira:_,onImported:e=>{c(e.description)},inputId:`planning-agent-jira-import`}),(0,Z.jsx)(Cu,{label:m(`planningAgentSidebar.descriptionLabel`),htmlFor:`planning-agent-description`,className:`gap-2`,children:(0,Z.jsx)(`div`,{className:`relative`,children:(0,Z.jsx)($p,{ref:v,projectId:e,suggestionAnchor:`caret`,id:`planning-agent-description`,"aria-label":m(`planningAgentSidebar.descriptionAriaLabel`),value:t.composer.description,onValueChange:c,rows:14,className:`min-h-[18rem] resize-y text-sm leading-6`,placeholder:m(`planningAgentSidebar.descriptionPlaceholder`)})})}),(0,Z.jsxs)(`div`,{className:`flex items-end gap-3`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Z.jsx)(nP,{bundles:n,value:t.composer.worktreeBundleId,onChange:f,selectId:`planning-agent-bundle`,emptyLabel:m(`planningAgentSidebar.autoCreateBundle`),hideProjectRootBundles:!0,label:``})}),o&&(0,Z.jsx)(q,{type:`button`,onClick:o,variant:`outline`,size:`sm`,className:`shrink-0 whitespace-nowrap border-sky-500/30 bg-sky-500/10 text-sky-200 hover:border-sky-400 hover:bg-sky-500/20 hover:text-sky-100`,children:m(`planningAgentSidebar.actions.manageBundles`)})]}),(0,Z.jsx)(`div`,{className:`space-y-3`,children:(0,Z.jsx)(QN,{model:t.composer.model,variant:t.composer.variant,skills:t.composer.skills,showModelSelector:r,showSkillsSelector:r,availableModels:i,availableSkills:a,selectedModel:h,onModelChange:l,onVariantChange:u,onSkillsChange:d,modelSelectId:`planning-agent-model`,variantSelectId:`planning-agent-variant`,skillsSelectId:`planning-agent-skills`,layout:`stacked`})}),(0,Z.jsx)(`div`,{"data-testid":`planning-agent-runs`,className:`border-t border-border/80 px-0 pt-5`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Z.jsx)(fY,{heading:m(`planningAgentSidebar.activeRuns`),runs:S}),(0,Z.jsx)(fY,{heading:m(`planningAgentSidebar.recentRuns`),runs:C})]})})]})}),(0,Z.jsx)(`div`,{className:`shrink-0 border-t border-border px-6 py-4`,children:(0,Z.jsx)(q,{type:`button`,onClick:p,disabled:!w,className:`w-full`,children:T})})]})})]})},mY=({className:e=``})=>{let{setNodeRef:t,isOver:n}=nw({id:`trash`});return(0,Z.jsxs)(`div`,{ref:t,"data-testid":`delete-drop-zone`,className:`${e} flex min-w-[13rem] select-none items-center justify-between gap-4 rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all duration-150 ${n?`scale-[1.02] border-red-400/70 bg-destructive/35 text-red-100 shadow-lg shadow-red-950/30`:`border-red-500/30 bg-background/82 text-red-200/85`}`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(U,{variant:`destructive`,className:`text-[11px] uppercase tracking-[0.28em]`,children:`Delete`}),(0,Z.jsx)(`div`,{className:`mt-1 text-sm font-medium`,children:n?`Release to delete`:`Drop here to delete`})]}),(0,Z.jsx)(`div`,{className:`rounded-xl border p-2 transition-colors ${n?`border-red-400/60 bg-red-500/20`:`border-red-500/20 bg-background/60`}`,children:(0,Z.jsx)(wu,{className:`h-5 w-5 transition-colors ${n?`text-red-100`:`text-red-300/70`}`})})]})},hY=(e,t)=>H(tt(`/ticket-dependencies`,e),{signal:t}),gY=(e,t)=>H(tt(`/ticket-dependencies`,e),{method:`POST`,body:t,fallbackErrorMessage:`Unable to create the dependency right now.`}),_Y=(e,t,n)=>l(tt(`/ticket-dependencies/${t}/${n}`,e),{method:`DELETE`,fallbackErrorMessage:`Unable to remove the dependency right now.`}),vY=(e,t)=>{let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n){let n=e[r],i=t[r];if(!n||!i||n.left!==i.left||n.top!==i.top||n.width!==i.width||n.height!==i.height)return!1}return!0},yY=(e,t)=>e===t?!0:!e||!t?!1:e.projectId===t.projectId&&e.blockerTicketId===t.blockerTicketId&&e.hoveredTicketId===t.hoveredTicketId&&e.pointer.x===t.pointer.x&&e.pointer.y===t.pointer.y,bY=({activeProjectId:e,tickets:t,dependencies:n,setDependencies:r,activeTicket:i,activeOverlayNode:a,dragOffset:o})=>{let[s,c]=(0,Y.useState)({}),[l,u]=(0,Y.useState)({width:0,height:0}),[d,f]=(0,Y.useState)(null),[p,m]=(0,Y.useState)(null),h=(0,Y.useRef)(null),g=(0,Y.useRef)(null),_=(0,Y.useRef)(null),v=(0,Y.useRef)(new Map),y=(0,Y.useRef)({}),b=(0,Y.useRef)(null),x=(0,Y.useRef)(null),S=(0,Y.useRef)(null),C=(0,Y.useRef)(null),w=(0,Y.useRef)(null),T=(0,Y.useRef)(null),E=(0,Y.useMemo)(()=>new Map(t.map(e=>[e.id,e])),[t]);(0,Y.useEffect)(()=>{C.current=p},[p]),(0,Y.useLayoutEffect)(()=>{if(!i||!a||!g.current)return;let e=window.requestAnimationFrame(()=>{let e=g.current?.getBoundingClientRect(),t=a.getBoundingClientRect();e&&f({ticketId:i.id,rect:{left:t.left-e.left,top:t.top-e.top,width:t.width,height:t.height}})});return()=>{window.cancelAnimationFrame(e)}},[a,i,o.x,o.y]);let D=(0,Y.useCallback)(()=>{b.current===null&&(b.current=window.requestAnimationFrame(()=>{b.current=null;let e=g.current;if(!e){_.current=null,y.current={},c({}),u({width:0,height:0});return}let t=e.getBoundingClientRect(),n={};_.current={left:t.left,top:t.top},u(e=>e.width===t.width&&e.height===t.height?e:{width:t.width,height:t.height});for(let[e,r]of v.current){let i=r.getBoundingClientRect();n[e]={left:i.left-t.left,top:i.top-t.top,width:i.width,height:i.height}}y.current=n,c(e=>vY(e,n)?e:n)}))},[]);(0,Y.useEffect)(()=>{let e=h.current;if(!e)return;let t=()=>{D()};return e.addEventListener(`scroll`,t,!0),window.addEventListener(`resize`,t),()=>{e.removeEventListener(`scroll`,t,!0),window.removeEventListener(`resize`,t)}},[D]),(0,Y.useEffect)(()=>{if(typeof ResizeObserver!=`function`)return;let e=new ResizeObserver(()=>{D()});x.current=e;for(let t of v.current.values())e.observe(t);return()=>{e.disconnect(),x.current===e&&(x.current=null)}},[D]),(0,Y.useEffect)(()=>{let e=h.current,t=g.current;if(!e&&!t)return;let n=new ResizeObserver(()=>{D()});return e&&n.observe(e),t&&t!==e&&n.observe(t),()=>{n.disconnect()}},[D]),(0,Y.useEffect)(()=>(D(),()=>{b.current!==null&&(window.cancelAnimationFrame(b.current),b.current=null)}),[n,D,t]);let O=(0,Y.useCallback)((e,t)=>{let n=v.current.get(e);if(t){if(n===t)return;v.current.set(e,t),x.current?.observe(t)}else{if(!n)return;v.current.delete(e),x.current?.unobserve(n)}D()},[D]),k=(0,Y.useCallback)(e=>{yY(C.current,e)||(C.current=e,m(e))},[]),A=(0,Y.useCallback)(()=>{w.current!==null&&(window.cancelAnimationFrame(w.current),w.current=null),T.current=null},[]),j=(0,Y.useCallback)(e=>{T.current=e,w.current===null&&(w.current=window.requestAnimationFrame(()=>{w.current=null;let e=T.current;T.current=null,k(e)}))},[k]),M=(0,Y.useCallback)((e,t)=>{let n=_.current;if(!n&&g.current){let e=g.current.getBoundingClientRect();n={left:e.left,top:e.top},_.current=n}return n?{x:e-n.left,y:t-n.top}:{x:e,y:t}},[]),N=(0,Y.useCallback)((e,t,n)=>{for(let[r,i]of Object.entries(y.current))if(r!==n&&e>=i.left&&e<=i.left+i.width&&t>=i.top&&t<=i.top+i.height)return r;return null},[]),P=(0,Y.useCallback)(async t=>{if(e)try{await _Y(e,t.blocker_ticket_id,t.dependent_ticket_id),r(e=>Uw(e,t.blocker_ticket_id,t.dependent_ticket_id))}catch(e){Q.error(e instanceof I?e.message:`Unable to remove the dependency right now.`,{id:`board-dependency-error`})}},[e,r]),F=(0,Y.useCallback)((t,i)=>{if(!e)return;i.preventDefault(),S.current?.();let a=(n,r,i=!1)=>{let a=M(n,r),o={projectId:e,blockerTicketId:t,hoveredTicketId:N(a.x,a.y,t),pointer:a};if(i){A(),k(o);return}j(o)};a(i.clientX,i.clientY,!0);let o=e=>{a(e.clientX,e.clientY)},s=async i=>{let a=M(i.clientX,i.clientY),o=N(a.x,a.y,t),s=o?Gw(n,t,o):null;if(S.current?.(),S.current=null,k(null),!(!o||!s)){if(!s.valid){Q.error(Kw(s.reason),{id:`board-dependency-error`});return}try{let n=await gY(e,{blocker_ticket_id:t,dependent_ticket_id:o});r(e=>Hw(e,n))}catch(e){Q.error(e instanceof I?e.message:`Unable to create the dependency right now.`,{id:`board-dependency-error`})}}};S.current=()=>{window.removeEventListener(`pointermove`,o),window.removeEventListener(`pointerup`,s),A()},window.addEventListener(`pointermove`,o),window.addEventListener(`pointerup`,s,{once:!0})},[e,A,n,N,M,j,r,k]);(0,Y.useEffect)(()=>{S.current?.(),S.current=null,A(),C.current=null},[e,A]),(0,Y.useEffect)(()=>()=>{S.current?.(),w.current!==null&&(window.cancelAnimationFrame(w.current),w.current=null)},[]);let L=(0,Y.useMemo)(()=>{let r=p?.blockerTicketId;if(!r||p.projectId!==e||!E.has(r))return null;let i=new Map;for(let e of t){if(e.id===r){i.set(e.id,`source`);continue}let t=Gw(n,r,e.id);i.set(e.id,t.valid?`valid`:`idle`)}return i},[e,n,p,E,t]),R=(0,Y.useCallback)(e=>{if(!L||!p)return`idle`;let t=L.get(e)??`idle`;return e===p.hoveredTicketId&&t===`idle`?`invalid`:t},[L,p]),z=(0,Y.useMemo)(()=>!p||p.projectId!==e||!E.has(p.blockerTicketId)?null:{blockerTicketId:p.blockerTicketId,hoveredTicketId:p.hoveredTicketId,pointer:p.pointer},[e,p,E]);return{boardViewportRef:h,boardContentRef:g,registerTicketNode:O,measuredCardRects:(0,Y.useMemo)(()=>{if(!i)return s;let e=s[i.id];return e?d?.ticketId===i.id?{...s,[i.id]:d.rect}:{...s,[i.id]:{...e,left:e.left+o.x,top:e.top+o.y}}:s},[d,i,s,o.x,o.y]),overlayPreview:z,overlaySize:l,getDependencyTargetState:R,handleDependencyStart:F,handleDeleteDependency:P}},xY=e=>{if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e,n=typeof t.id==`string`?t.id:``,r=typeof t.name==`string`?t.name:``,i=typeof t.command==`string`?t.command:``,a=typeof t.cwd==`string`?t.cwd:``,o=t.runner===`vitest`||t.runner===`jest`||t.runner===`unknown`?t.runner:`auto`;return n.trim()===``||r.trim()===``&&i.trim()===``&&a.trim()===``?[]:[{id:n,name:r,command:i,cwd:a,runner:o}]}):[]}catch{return[]}},SY=`[data-terminal-pane="true"]`,CY=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName.toLowerCase();return t===`input`||t===`textarea`||e.isContentEditable},wY=e=>e instanceof HTMLElement?e.closest(SY)!==null:!1,TY=e=>CY(e)||wY(e),EY=(e,t={})=>{let{isBlocked:n}=t;(0,Y.useEffect)(()=>{let t=t=>{if(t.defaultPrevented||t.repeat)return;let r=e.find(e=>!e.disabled&&e.key.toLowerCase()===t.key.toLowerCase()&&(e.ctrlKey??!1)===t.ctrlKey&&(e.altKey??!1)===t.altKey&&(e.metaKey??!1)===t.metaKey&&(e.shiftKey===void 0||e.shiftKey===t.shiftKey));r&&(n?.(document.activeElement)||(t.preventDefault(),r.onKeyDown()))};return window.addEventListener(`keydown`,t),()=>{window.removeEventListener(`keydown`,t)}},[e,n])},DY=e=>({...e,messages:void 0,agent_log:void 0,streaming_response:void 0}),OY=(e,t)=>e?e.state!==t.state||e.parked_at!==t.parked_at||e.worktree_bundle_id!==t.worktree_bundle_id:!0,kY=(e,t)=>{if(!e)return t;let n=t.worktree_bundle_id!==null&&e.worktree_bundle_id===t.worktree_bundle_id,r=t.bundle??(n&&e.bundle?.id===t.worktree_bundle_id?e.bundle:null),i=t.bundle_execution_position??(n?e.bundle_execution_position??null:null);return{...e,...t,bundle:r,bundle_execution_position:i}},AY=(e,t)=>{let n=e=>Ow(t)?Ow(e):e.state===t.state&&!Ow(e),r=e.findIndex(e=>n(e));if(r===-1)return[...e,t];let i=[...e];return i.splice(r,0,t),i},jY=(e,t)=>{let n=e.find(e=>e.id===t.id);return[n&&n.pull_request!==void 0&&t.pull_request===void 0?{...n,...t,pull_request:n.pull_request}:t,...e.filter(e=>e.id!==t.id)]},MY=(e,t)=>{let n=e.find(e=>e.id===t.id);if(!n)return[...e,t];let r=kY(n,t);return e.map(e=>e.id===t.id?r:e)},NY=(e,t)=>{let n=kY(e.find(e=>e.id===t.id),t);return AY(FY(e,t.id),n)},PY=(e,t)=>{if(e.length===0)return[...t];let n=[...e];for(let e of t)n=OY(n.find(t=>t.id===e.id),e)?NY(n,e):MY(n,e);let r=new Set(t.map(e=>e.id));return n.filter(e=>r.has(e.id))},FY=(e,t)=>e.filter(e=>e.id!==t),IY=(e,t,n,r={},i={})=>{let a=e.findIndex(e=>e.id===t);if(a===-1)return e;let o={...e[a],state:n,...r},s=FY(e,t);if(i.preferredIndex!==void 0){let e=Math.max(0,Math.min(i.preferredIndex,s.length));return s.splice(e,0,o),s}return AY(s,o)},LY=async(e,t)=>{`Notification`in window&&Notification.permission!==`denied`&&(Notification.permission===`default`&&await Notification.requestPermission(),Notification.permission===`granted`&&new Notification(e,{body:t}))},RY=(0,Y.createContext)(UW),zY=()=>(0,Y.useContext)(RY),BY=(0,Y.createContext)(null),VY=15*1e3,HY=1e3,UY=async e=>LY(`Ticket done`,e),WY=e=>DY(e),GY=(e,t)=>t===`running`&&e.agent_status===`done`?`Finished ${e.state} for "${e.title}"`:t===`running`&&e.agent_status===`error`?`Failed ${e.state} for "${e.title}"`:t!==`running`&&e.agent_status===`running`?`Running ${e.state} for "${e.title}"`:null,KY=({activeProjectId:e,refreshKey:t=0,onLoadedProjectIdChange:n,onProjectUsageChange:r,onBundlesChange:i,onBundlesLoadingChange:a,children:o})=>{let s=zY(),[c,l]=(0,Y.useState)([]),[u,d]=(0,Y.useState)([]),[f,p]=(0,Y.useState)([]),[m,h]=(0,Y.useState)(null),[g,_]=(0,Y.useState)(null),[v,y]=(0,Y.useState)(null),[b,x]=(0,Y.useState)(null),[S,C]=(0,Y.useState)(null),w=(0,Y.useRef)(0),T=(0,Y.useRef)(0),E=(0,Y.useRef)(new Map),D=(0,Y.useRef)(new Map),O=(0,Y.useRef)(e),k=(0,Y.useRef)(new Map),A=(0,Y.useRef)(new Map),j=(0,Y.useRef)(new Map),M=(0,Y.useCallback)((e,t)=>{let n=A.current.get(t.id);return!n||!e||t.state===n?t:e},[]),N=(0,Y.useCallback)((e,t)=>{if(e.length===0)return;let n=new Map(A.current);for(let r of e)n.set(r,t);A.current=n},[]),P=(0,Y.useCallback)(e=>{if(e.length===0||A.current.size===0)return;let t=new Map(A.current);for(let n of e)t.delete(n);A.current=t},[]),F=(0,Y.useCallback)((e,t)=>{if(e.length===0)return;let n=new Map(j.current);for(let r of e)n.set(r,t);j.current=n},[]),I=(0,Y.useCallback)(e=>{if(e.length===0||j.current.size===0)return;let t=new Map(j.current);for(let n of e)t.delete(n);j.current=t},[]),L=(0,Y.useCallback)((e,t)=>{if(k.current.has(t.id))return null;let n=M(e,t);return j.current.has(t.id)?{...n,parked_at:j.current.get(t.id)??null}:n},[M]),R=(0,Y.useCallback)((e,t)=>{if(k.current.size===0&&A.current.size===0&&j.current.size===0)return t;let n=new Map(e.map(e=>[e.id,e]));return t.flatMap(e=>{let t=L(n.get(e.id),e);return t?[t]:[]})},[L]),ee=(0,Y.useCallback)(async(e,t)=>{let n=await Kt(e,t,{detail:`board`});return Array.isArray(n)?(!t?.aborted&&O.current===e&&l(e=>PY(e,R(e,n).map(WY))),n):null},[R]),te=(0,Y.useCallback)(async(e,t)=>{await ee(e,t)},[ee]),ne=(0,Y.useCallback)(async(e,t)=>{let n=++T.current,r=await qt(e,t);if(!Array.isArray(r)||t?.aborted||O.current!==e||T.current!==n)return;let i=new Map(r.map(e=>[e.id,e]));l(e=>e.map(e=>{let t=i.get(e.id);return t?{...e,diff_stats:t.diff_stats??null,is_stale:t.is_stale}:e}))},[]),re=(0,Y.useCallback)(e=>e.some(e=>e.is_stale===void 0),[]),B=(0,Y.useCallback)(async e=>{let t=O.current;if(!t)return null;try{let n=await Jt(e,t);if(O.current!==t)return null;let r=D.current.get(n.id),i=L(r,n);if(!i)return null;let a=WY(i),o=OY(r,a);return l(e=>o?NY(e,a):MY(e,a)),n}catch{return null}},[L]),ie=(0,Y.useCallback)(async t=>{if(!e){p([]);return}p(await Tt(e,t))},[e]),V=(0,Y.useMemo)(()=>new Map(c.map(e=>[e.id,e])),[c]),H=(0,Y.useMemo)(()=>{let e=c.filter(e=>e.agent_status===`running`),t=new Set(e.map(e=>e.worktree_bundle_id).filter(e=>typeof e==`string`&&e.trim().length>0));return{total_running:e.length,running_plan_count:e.filter(e=>e.state===`plan`).length,running_build_count:e.filter(e=>e.state===`build`).length,running_review_count:e.filter(e=>e.state===`review`).length,active_bundle_count:t.size,latest_message:S}},[S,c]);(0,Y.useEffect)(()=>{D.current=V},[V]),(0,Y.useEffect)(()=>{O.current=e,k.current.clear(),A.current.clear(),j.current.clear(),C(null),h(null),E.current.clear()},[e]),(0,Y.useEffect)(()=>{n?.(v?null:g)},[g,v,n]),(0,Y.useEffect)(()=>{if(i){if(!e){i(null,[]);return}if(g!==e){i(e,[]);return}i(e,f)}},[e,f,g,i]),(0,Y.useEffect)(()=>{if(a){if(!e){a(null,!1);return}a(e,b===e)}},[e,b,a]),(0,Y.useEffect)(()=>{let t=new AbortController,n=++w.current,r=null,i=async()=>{try{if(!e){l([]),d([]),p([]),_(null),y(null);return}l([]),d([]),p([]),_(null),y(e),x(e);let[n,i,a]=await Promise.allSettled([ee(e,t.signal),hY(e,t.signal),Tt(e,t.signal)]);if(t.signal.aborted)return;n.status!==`fulfilled`&&!z(n.reason)&&l([]),i.status===`fulfilled`?d(i.value):z(i.reason)||d([]),a.status===`fulfilled`?p(a.value):z(a.reason)||p([]),_(n.status===`fulfilled`&&i.status===`fulfilled`&&a.status===`fulfilled`?e:null),n.status===`fulfilled`&&n.value!==null&&re(n.value)&&(r=window.setTimeout(()=>{t.signal.aborted||ne(e,t.signal)},HY))}finally{!t.signal.aborted&&w.current===n&&(y(null),x(null))}},a=t=>{t.project_id===e&&(h(t),!k.current.has(t.id)&&(t.bundle&&p(e=>jY(e,t.bundle)),l(e=>NY(e,WY(t)))))},o=t=>{if(t.project_id===e&&h(t),l(n=>{if(t.project_id!==e)return FY(n,t.id);let r=n.find(e=>e.id===t.id),i=L(r,t);if(!i)return n;let a=WY(i);return OY(r,a)?NY(n,a):MY(n,a)}),t.project_id!==e){d(e=>Vw(e,t.id));return}t.bundle&&p(e=>jY(e,t.bundle))},c=({id:e})=>{k.current.delete(e),j.current.delete(e),A.current.delete(e),l(t=>FY(t,e)),d(t=>Vw(t,e))},u=e=>{if(!e)return;let t=D.current.get(e.blocker_ticket_id),n=D.current.get(e.dependent_ticket_id);!t||!n||t.project_id!==O.current||n.project_id!==O.current||d(t=>Hw(t,e))},f=e=>{d(t=>Uw(t,e.blocker_ticket_id,e.dependent_ticket_id))};return i(),s.on(`ticket:created`,a),s.on(`ticket:updated`,o),s.on(`ticket:deleted`,c),s.on(`ticket-dependency:created`,u),s.on(`ticket-dependency:deleted`,f),()=>{t.abort(),r!==null&&window.clearTimeout(r),s.off(`ticket:created`,a),s.off(`ticket:updated`,o),s.off(`ticket:deleted`,c),s.off(`ticket-dependency:created`,u),s.off(`ticket-dependency:deleted`,f)}},[e,ne,t,re,ee,L,s]),(0,Y.useEffect)(()=>{if(!e)return;let t=new AbortController,n=()=>{document.visibilityState===`visible`&&Promise.allSettled([ee(e,t.signal),ie(t.signal)]).then(n=>{n[0]?.status===`fulfilled`&&n[0].value!==null&&re(n[0].value)&&ne(e,t.signal)}).catch(()=>{})},r=window.setInterval(n,VY),i=aq(n);return()=>{t.abort(),window.clearInterval(r),i()}},[e,ie,ne,re,ee]),(0,Y.useEffect)(()=>{if(!e||!r||g!==e)return;let t=c.filter(e=>{let t=e.bundle?.branch??e.branch;return typeof t==`string`&&t.trim()!==``}).length;r({projectId:e,ticketCount:c.length,worktreeCount:t,repoPathLocked:c.length>0||t>0||f.length>0})},[e,f.length,g,r,c]),(0,Y.useEffect)(()=>{for(let e of c){let t=E.current.get(e.id),n=GY(e,t);n&&C(n),t!==void 0&&t===`running`&&e.agent_status===`done`&&(e.state===`plan`||e.state===`build`||e.state===`review`)&&UY(e.title),E.current.set(e.id,e.agent_status)}},[c]);let ae=(0,Y.useCallback)(()=>{h(null)},[]),oe=(0,Y.useMemo)(()=>({tickets:c,setTickets:l,dependencies:u,setDependencies:d,bundles:f,setBundles:p,latestDetailedTicketUpdate:m,clearLatestDetailedTicketUpdate:ae,loadedProjectId:g,loadingProjectId:v,activeProjectIdRef:O,pendingDeletedTicketsRef:k,pendingOptimisticMovesRef:A,pendingParkedTicketsRef:j,refreshTickets:te,requestSingleTicketRefresh:B,refreshBundles:ie,resolvePendingTicket:L,resolvePendingTickets:R,markPendingOptimisticMoves:N,clearPendingOptimisticMoves:P,markPendingParkedTickets:F,clearPendingParkedTickets:I,liveActivity:H}),[f,ae,P,I,u,H,g,m,v,N,F,ie,te,B,L,R,c]);return(0,Z.jsx)(BY.Provider,{value:oe,children:o})},qY=()=>{let e=(0,Y.useContext)(BY);if(!e)throw Error(`useProjectWorkspace must be used inside ProjectWorkspaceProvider`);return e},JY=(0,Y.lazy)(()=>tG(()=>import(`./TestsDialog-CzG_2qwn.js`).then(e=>({default:e.TestsDialog})),__vite__mapDeps([0,1,2]))),YY=`archon.last-model-selection`,XY=`archon.last-variant-selection`,ZY=`archon.last-skills-selection`,QY=()=>{try{let e=window.localStorage.getItem(ZY),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}},$Y=e=>[e.title,e.description,e.bundle?.name??``,e.bundle?.branch??``,e.branch??``].map(e=>e.toLowerCase()),eX=(e,t)=>{let n=e.bundle_execution_position??2**53-1,r=t.bundle_execution_position??2**53-1;if(n!==r)return n-r;if(e.created_at!==t.created_at)return e.created_at.localeCompare(t.created_at);let i=e.title.localeCompare(t.title,void 0,{sensitivity:`base`});return i===0?e.id.localeCompare(t.id):i},tX=(e,t)=>t?{...e,...t,messages:t.messages===void 0?e.messages:t.messages,agent_log:t.agent_log===void 0?e.agent_log:t.agent_log,streaming_response:t.streaming_response===void 0?e.streaming_response:t.streaming_response}:e,nX=(e,t)=>{let n=e.toLowerCase().trim().split(/\s+/).filter(Boolean);if(n.length===0)return!0;let r=$Y(t);return n.every(e=>r.some(t=>t.includes(e)))},rX=[`plan`,`build`,`review`],iX=`done`,aX=()=>({build:!1,stopBuild:!1,resumeBuild:!1,review:!1,undoReview:!1,run:!1,stop:!1,followUp:!1,bundleRefresh:!1}),oX=({bundleId:e,activeRunContextKey:t,isProjectRootRunActive:n})=>n?!0:t!==null&&t!==e,sX=(e,t)=>{if(!e)return null;let n=t.find(t=>t.id===e.ticket_id);return n?Ew(n):e.ticket_id},cX=()=>({description:``,model:window.localStorage.getItem(YY)??``,variant:window.localStorage.getItem(XY)??``,skills:QY(),worktreeBundleId:``}),lX=()=>({isOpen:!1,composer:cX(),runs:[]}),uX=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`planning-run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,dX=e=>({ticketCount:e.tickets.length,dependencyCount:e.dependencies.length,ticketsWithOpenQuestions:e.tickets.filter(e=>(e.planning_context?.open_questions.length??0)>0).length,ticketTitles:e.tickets.map(e=>e.title),ticketIds:e.tickets.map(e=>e.id)}),fX=(e,t,n)=>e.map(e=>e.id===t?n(e):e),pX=(e,t,n)=>{e?window.localStorage.setItem(YY,e):window.localStorage.removeItem(YY),t?window.localStorage.setItem(XY,t):window.localStorage.removeItem(XY),n.length>0?window.localStorage.setItem(ZY,JSON.stringify(n)):window.localStorage.removeItem(ZY)},mX=(e,t={})=>xl(e,t),hX=()=>({model:window.localStorage.getItem(YY)??``,variant:window.localStorage.getItem(XY)??``,skills:QY()}),gX=(e,t)=>{let n=FY(e,t.ticket.id),r=Math.max(0,Math.min(t.index,n.length));return n.splice(r,0,t.ticket),n},_X=e=>e.tickets.length>0&&e.tickets.every(e=>Fw(e,`trash`)),vX=e=>e.tickets.length>0&&e.tickets.every(e=>Fw(e,iX)),yX=e=>e.column===iX&&e.tickets.length>0&&e.tickets.every(e=>e.state!==`plan`),bX=(e,t,n,r)=>n||t!==null&&t!==Ew(e)?r:Yw(e),xX=(e,t)=>t===`build`?{agent_status:null,agent_log:null,streaming_response:null,build_completed_at:null,planning_context:e.planning_context?{...e.planning_context,open_questions:[]}:null}:t===`review`?{agent_status:null,agent_log:null,streaming_response:null}:{},SX=(e,t)=>e===`plan`&&t===`build`?`build`:e===`build`&&t===`review`?`review`:e===`review`&&t===`build`?`undoReview`:null,CX=(e,t,n)=>t===`review`&&n===`build`?{}:xX(e,n),wX=({activeProjectId:e,activeProject:t=null,activeProjectBranchState:n=null,activeRun:r,activeTool:i,onPreviewReviewCapabilityChange:a,onRunStopped:o,onRunStatusChange:s,refreshKey:c=0})=>{let{t:l}=X(`common`),u=Yx(Jx(ZS,{activationConstraint:{distance:5}})),{tickets:d,setTickets:f,dependencies:p,setDependencies:m,bundles:h,setBundles:g,latestDetailedTicketUpdate:_,clearLatestDetailedTicketUpdate:v,loadedProjectId:y,loadingProjectId:b,activeProjectIdRef:x,pendingDeletedTicketsRef:S,requestSingleTicketRefresh:C,refreshBundles:w,resolvePendingTicket:T,markPendingOptimisticMoves:E,clearPendingOptimisticMoves:D,markPendingParkedTickets:O,clearPendingParkedTickets:k}=qY(),[A,j]=(0,Y.useState)(null),[M,N]=(0,Y.useState)(null),[P,F]=(0,Y.useState)(null),[L,R]=(0,Y.useState)({x:0,y:0}),[ee,te]=(0,Y.useState)(null),[ne,re]=(0,Y.useState)(!1),[B,ie]=(0,Y.useState)([]),[V,H]=(0,Y.useState)([]),[ae,oe]=(0,Y.useState)(!1),[se,ce]=(0,Y.useState)({}),[le,ue]=(0,Y.useState)(!1),[de,U]=(0,Y.useState)(!1),[fe,pe]=(0,Y.useState)(null),[me,W]=(0,Y.useState)(null),[he,G]=(0,Y.useState)(null),[ge,_e]=(0,Y.useState)(null),[ve,ye]=(0,Y.useState)(null),[be,xe]=(0,Y.useState)(null),[Se,Ce]=(0,Y.useState)(null),[we,Te]=(0,Y.useState)(null),[Ee,De]=(0,Y.useState)(null),[Oe,ke]=(0,Y.useState)(null),[Ae,je]=(0,Y.useState)(!1),[Me,Ne]=(0,Y.useState)(aX()),[Pe,Fe]=(0,Y.useState)(0),[Ie,Le]=(0,Y.useState)(``),[Re,ze]=(0,Y.useState)(!1),Be=i===`opencode`||he?.tool===`opencode`||!!be?.tickets.some(e=>e.tool===`opencode`),He=i===`opencode`&&B.length>0,Ue=he?.tool===`opencode`&&B.length>0,We=!!be?.tickets.some(e=>e.tool===`opencode`)&&B.length>0,Ke=(0,Y.useRef)(e),qe=(0,Y.useRef)(null),Je=(0,Y.useRef)(null),[Ye,Xe]=(0,Y.useState)(null),Ze=d.find(e=>e.is_running)??null,Qe=Ze?Ew(Ze):null,$e=r?.context_key??null,et=r?.kind===`ticket`?sX(r,d)??Qe:Qe,J=r?.kind===`project`,tt=et??Ye,nt=(0,Y.useCallback)(e=>oX({bundleId:e,activeRunContextKey:tt,isProjectRootRunActive:J}),[tt,J]),rt=A!==null&&Fw(A,`trash`)||M!==null&&_X(M),it=b===e,at=(0,Y.useMemo)(()=>xY(t?.test_commands??null),[t?.test_commands]),ot=(0,Y.useCallback)(async e=>LY(l(`board.notifications.planningDoneTitle`),l(`board.notifications.planningDoneBody`,{count:e})),[l]),st=at.length>0,ct=(0,Y.useMemo)(()=>new Map(d.map(e=>[e.id,e])),[d]);(0,Y.useEffect)(()=>{Xe(null)},[e]),(0,Y.useEffect)(()=>{Ye!==null&&(J||et!==null)&&Xe(null)},[et,J,Ye]),(0,Y.useEffect)(()=>{if(!me){G(null);return}let e=ct.get(me)??null;e&&G(t=>!t||t.id!==me?e:tX(t,e))},[me,ct]),(0,Y.useEffect)(()=>{_&&(G(e=>!e||e.id!==_.id?e:tX(e,_)),xe(e=>{if(!e)return e;let t=_.worktree_bundle_id;if(!t||e.bundle.id!==t)return e;let n=e.tickets.some(e=>e.id===_.id)?e.tickets.map(e=>e.id===_.id?tX(e,_):e):[...e.tickets,_];return{...e,tickets:n}}))},[_]),(0,Y.useEffect)(()=>{_===null||me!==null||ge!==null||v()},[v,_,ge,me]);let lt=(0,Y.useCallback)(async e=>{let t=await C(e);if(!t)return null;let n=ct.get(e),r=n?tX(t,n):t;return G(t=>t&&t.id!==e||me&&me!==e?t:r),r},[C,me,ct]),ut=(0,Y.useCallback)(e=>{G(e),W(e.id),lt(e.id)},[lt]),dt=(0,Y.useMemo)(()=>new Map(h.map(e=>[e.id,e])),[h]),ft=(0,Y.useMemo)(()=>{if(!be)return null;let e=be.bundle.id,t=_?.worktree_bundle_id===e?_:null,n=d.filter(t=>t.worktree_bundle_id===e),r=new Map(n.map(e=>[e.id,e])),i=be.tickets.filter(e=>!S.current.has(e.id)).map(e=>t&&e.id===t.id?tX(e,t):e);t&&!i.some(e=>e.id===t.id)&&!S.current.has(t.id)&&i.push(t);let a=i.map(e=>tX(e,r.get(e.id)));for(let e of n)a.some(t=>t.id===e.id)||a.push(e);a.sort(eX);let o=be.execution_order_ticket_ids??[],s=a.map(e=>e.id),c=[...o,...s].filter((e,t,n)=>s.includes(e)&&n.indexOf(e)===t),l=n.some(e=>e.can_re_review!==void 0||e.has_completed_review!==void 0||e.has_follow_up_since_last_review!==void 0),u=n.some(e=>e.agent_status===`running`),f={has_completed_review:n.some(e=>e.has_completed_review===!0),has_follow_up_since_last_review:n.some(e=>e.has_follow_up_since_last_review===!0),can_re_review:!u&&n.some(e=>e.can_re_review===!0)},p=vl(a),m=a.find(e=>e.id===be.review_owner_ticket_id&&e.state===`review`)??a.find(e=>e.state===`review`)??null,h=xl(a,{targetTicketId:be.target_ticket_id,reviewOwnerTicketId:m?.id??be.review_owner_ticket_id,latestSessionTicketId:p?.id??be.latest_session_ticket_id});return{...be,bundle:dt.get(e)??be.bundle,tickets:a,execution_order_ticket_ids:c,latest_session_ticket_id:p?.id??null,latest_session_id:p?.session_id??null,review_owner_ticket_id:m?.id??null,target_ticket_id:h?.id??null,has_completed_review:l?f.has_completed_review:be.has_completed_review,has_follow_up_since_last_review:l?f.has_follow_up_since_last_review:be.has_follow_up_since_last_review,can_re_review:l?f.can_re_review:be.can_re_review}},[dt,_,S,be,d]),pt=(0,Y.useMemo)(()=>d.filter(e=>Re&&Aw(e)?!1:nX(Ie,e)),[Re,Ie,d]),mt=(0,Y.useMemo)(()=>pt.filter(e=>Ow(e)),[pt]),ht=(0,Y.useMemo)(()=>Sl(mt,h,iX),[h,mt]),{boardViewportRef:gt,boardContentRef:_t,registerTicketNode:vt,measuredCardRects:yt,overlayPreview:bt,overlaySize:xt,getDependencyTargetState:St,handleDependencyStart:Ct,handleDeleteDependency:wt}=bY({activeProjectId:e,tickets:d,dependencies:p,setDependencies:m,activeTicket:A,activeOverlayNode:P,dragOffset:L}),Tt=e?se[e]??lX():lX(),kt=Tt.composer.worktreeBundleId&&h.some(e=>e.id===Tt.composer.worktreeBundleId)?Tt.composer.worktreeBundleId:``,At=kt===Tt.composer.worktreeBundleId?Tt:{...Tt,composer:{...Tt.composer,worktreeBundleId:kt}},jt=hX(),It=!!t?.run_ide?.trim(),Lt=At.runs.filter(e=>e.boardVisible),Rt=(0,Y.useCallback)((e,t,n=d)=>{let r=Sl(n,h,t).find(t=>t.kind===`bundle`&&t.group.bundle.id===e);return r?.kind===`bundle`?r.group:null},[h,d]),Ht=(0,Y.useCallback)(e=>(0,Z.jsx)(dG,{ticket:e,allTickets:d,dependencies:p,bundles:h,projectMemoryEnabled:!!t?.memory_enabled,overlay:!0,showModelSelector:e.tool===`opencode`&&B.length>0,availableModels:B,runDisabled:!0,hideBundleScopedControls:!0}),[t?.memory_enabled,B,h,p,d]),Ut=Lt.length>0?(0,Z.jsx)(`div`,{className:`mb-0.5 flex flex-col gap-2.5`,children:Lt.map(e=>(0,Z.jsx)(sY,{run:e},e.id))}):null,Wt=(0,Y.useCallback)(t=>bl(t)?t.project_id===e?It:!!t.has_run_ide:!1,[It,e]),Gt=(0,Y.useCallback)(e=>!!e.project_id&&!!(e.bundle?.branch??e.branch)&&bl(e),[]),Kt=(0,Y.useCallback)(e=>{let t=e?.tickets.find(t=>t.id===e.target_ticket_id)??e?.tickets.find(e=>e.has_worktree)??null;return t?Wt(t):!1},[Wt]),qt=(0,Y.useCallback)(e=>{let t=d.filter(t=>t.worktree_bundle_id===e).sort(eX);return be?.bundle.id===e?mX(be.tickets.map(e=>t.find(t=>t.id===e.id)??e).sort(eX),{targetTicketId:be.target_ticket_id,reviewOwnerTicketId:be.review_owner_ticket_id,latestSessionTicketId:be.latest_session_ticket_id}):mX(t)},[be,d]),Jt=(0,Y.useCallback)((e,t)=>{ce(n=>({...n,[e]:t(n[e]??lX())}))},[]);(0,Y.useEffect)(()=>{ue(!1),U(!1),Ce(null),ke(null),Ke.current!==e&&(qe.current=e),e||(qe.current=null,Le(``)),Ke.current=e},[e,c]),(0,Y.useLayoutEffect)(()=>{!e||y!==e||qe.current===e&&(qe.current=null,Le(``))},[e,y]),(0,Y.useEffect)(()=>{if(!Be){H([]);return}let t=new AbortController;return(async()=>{try{ie(await wn(`opencode`,t.signal))}catch(e){z(e)||ie(e=>e)}})(),(async()=>{try{H(await gw(`opencode`,t.signal,e))}catch(e){z(e)||H([])}})(),()=>{t.abort()}},[e,Be]);let Zt=({active:e})=>{oe(!1),F(null),R({x:0,y:0});let t=wl(String(e.id));if(t){N(Rt(t.bundleId,t.column)),j(null);return}N(null),j(d.find(t=>t.id===e.id)??null)},$t=()=>{oe(!1),F(null),R({x:0,y:0}),j(null),N(null)},en=(0,Y.useCallback)(e=>{f(t=>e.reduce((e,t)=>NY(e,t),t))},[f]),tn=(0,Y.useCallback)((e,t)=>{if(e.length===0)return;let n=e[0]?.state;n&&f(r=>e.reduce((e,r)=>IY(e,r.id,t,CX(r,n,t)),r))},[f]),nn=(0,Y.useCallback)((e,t=d)=>!e.worktree_bundle_id||!e.project_id||e.state!==`build`?[]:t.filter(t=>t.project_id===e.project_id&&t.worktree_bundle_id===e.worktree_bundle_id&&t.state===`build`&&t.parked_at===null).sort(eX),[d]),rn=async({active:e,over:t})=>{let n=wl(String(e.id)),r=d.find(t=>t.id===e.id),i=n?Rt(n.bundleId,n.column):null,a=t?.id===`trash`&&(r!==void 0&&Fw(r,`trash`)||i!==null&&_X(i)),o=t?.id&&rX.includes(t.id)?t.id:null;if(oe(a),F(null),R({x:0,y:0}),j(null),N(null),t){if(n){if(t.id===`trash`){if(!i||!_X(i))return;await Pn(i);return}if(t.id===iX){if(!i||!vX(i))return;await jn(i);return}if(o){if(n.column===iX){if(!i||!yX(i))return;await Mn(i);return}await lr(n.bundleId,n.column,o)}return}if(t.id===`trash`){if(!r||!Fw(r,`trash`))return;Ln(e.id);return}if(t.id===iX){if(!r||!Fw(r,iX))return;await kn(e.id);return}if(o){if(r&&Pw(r,o)){await An(e.id);return}if(!(!r||!Fw(r,o)))try{await Dn(r,o,{optimistic:!0})}catch(e){Q.error(e instanceof I?e.message:l(`board.errors.moveTicket`),{id:`board-move-error`})}}}},an=async(t,n,r,a,o,s,c)=>{let u=await Yt({title:t,description:n,tool:i,model:a,variant:o,skills:s,project_id:e,...c});if(pX(a,o,s),f(e=>NY(e,DY(u))),u.bundle&&g(e=>jY(e,u.bundle)),r===`build`)try{await Dn(u,`build`)}catch(e){Q.error(e instanceof I?e.message:l(`board.errors.moveTicket`),{id:`board-move-error`})}r===`plan`&&Cn(u.id,u.project_id)},on=async t=>{if(!e)throw Error(l(`board.errors.createBundleWithoutProject`));let n=await Et(e,{name:t,prepare:!0});return g(e=>jY(e,n)),n},Tn=e=>{f(t=>[...e.tickets].reverse().reduce((e,t)=>NY(e,DY(t)),t)),m(t=>e.dependencies.reduce((e,t)=>Hw(e,t),t));for(let t of e.tickets)t.bundle&&g(e=>jY(e,t.bundle))},En=(0,Y.useCallback)((e,t={})=>{let n=DY(e);f(e=>t.reorderInState?NY(e,n):MY(e,n)),G(t=>!t||t.id!==e.id?t:tX(e,n)),e.bundle&&g(t=>jY(t,e.bundle))},[g,f]),Dn=async(e,t,n={})=>{let r=d.findIndex(t=>t.id===e.id),i=t===`review`?nn(e):[],a=t===`review`&&i.length>1,o=n.optimistic?a?i.map(e=>e.id):[e.id]:[];n.optimistic&&(E(o,t),a?tn(i,t):f(n=>IY(n,e.id,t,xX(e,t))));try{if(a&&e.project_id&&e.worktree_bundle_id){let t=await Nt(e.project_id,e.worktree_bundle_id);Qn(t);let n=t.tickets.find(t=>t.id===e.id);if(!n)throw Error(l(`board.errors.missingBundleReviewTicket`));return D(o),n}let n=await Qt(e.id,e.project_id,t);return f(r=>{let i=r.find(t=>t.id===e.id);return i?.state===t&&n.state===t&&i.agent_status!==n.agent_status&&n.agent_status===e.agent_status?r:OY(i,n)?NY(r,n):MY(r,n)}),n.bundle&&g(e=>jY(e,n.bundle)),D(o),n}catch(t){throw n.optimistic&&(a?en(i):f(t=>IY(t,e.id,e.state,{agent_status:e.agent_status,agent_log:e.agent_log,build_completed_at:e.build_completed_at},{preferredIndex:r})),D(o)),t}},On=(e,t)=>{f(n=>n.map(n=>n.id===e?{...n,...t}:n))},kn=async t=>{let n=d.find(e=>e.id===t);if(n)try{let r=new Date().toISOString();O([t],r),On(t,{parked_at:r}),En(await dn(t,n.project_id??e),{reorderInState:!0}),k([t])}catch(e){k([t]),On(t,{parked_at:n.parked_at}),Q.error(e instanceof I?e.message:l(`board.errors.parkTicket`),{id:`board-park-error`})}},An=async t=>{let n=d.find(e=>e.id===t);if(n)try{O([t],null),On(t,{parked_at:null}),En(await fn(t,n.project_id??e),{reorderInState:!0}),k([t])}catch(e){k([t]),On(t,{parked_at:n.parked_at}),Q.error(e instanceof I?e.message:l(`board.errors.returnTicket`),{id:`board-unpark-error`})}},jn=(0,Y.useCallback)(async e=>{let t=new Set(e.tickets.map(e=>e.id)),n=e.tickets.map(e=>({id:e.id,parked_at:e.parked_at})),r=new Date().toISOString();O(e.tickets.map(e=>e.id),r),f(e=>e.map(e=>t.has(e.id)?{...e,parked_at:r}:e));let i=await Promise.allSettled(e.tickets.map(e=>dn(e.id,e.project_id??x.current))),a=new Set;if(i.forEach((t,n)=>{if(t.status===`fulfilled`){k([t.value.id]),En(t.value,{reorderInState:!0});return}let r=e.tickets[n];r&&a.add(r.id)}),a.size===0)return;k([...a]),f(e=>e.map(e=>{if(!a.has(e.id))return e;let t=n.find(t=>t.id===e.id);return t?{...e,parked_at:t.parked_at}:e}));let o=i.find(e=>e.status===`rejected`),s=a.size===e.tickets.length?o?.reason instanceof I?o.reason.message:l(`board.errors.moveBundleToDone`):l(`board.toasts.movedBundleToDonePartial`,{movedCount:e.tickets.length-a.size,totalCount:e.tickets.length});Q.error(s,{id:`board-bundle-park-error`})},[x,En,k,O,f,l]),Mn=(0,Y.useCallback)(async e=>{let t=new Set(e.tickets.map(e=>e.id)),n=e.tickets.map(e=>({id:e.id,parked_at:e.parked_at}));O(e.tickets.map(e=>e.id),null),f(e=>e.map(e=>t.has(e.id)?{...e,parked_at:null}:e));let r=await Promise.allSettled(e.tickets.map(e=>fn(e.id,e.project_id??x.current))),i=new Set;if(r.forEach((t,n)=>{if(t.status===`fulfilled`){k([t.value.id]),En(t.value,{reorderInState:!0});return}let r=e.tickets[n];r&&i.add(r.id)}),i.size===0)return;k([...i]),f(e=>e.map(e=>{if(!i.has(e.id))return e;let t=n.find(t=>t.id===e.id);return t?{...e,parked_at:t.parked_at}:e}));let a=r.find(e=>e.status===`rejected`),o=i.size===e.tickets.length?a?.reason instanceof I?a.reason.message:l(`board.errors.restoreBundle`):l(`board.toasts.restoredBundlePartial`,{restoredCount:e.tickets.length-i.size,totalCount:e.tickets.length});Q.error(o,{id:`board-bundle-unpark-error`})},[x,En,k,O,f,l]),Nn=async t=>{e&&(await Vt(e,t),g(e=>e.filter(e=>e.id!==t)))},Pn=(0,Y.useCallback)(async t=>{let n=t.tickets.map(e=>({ticket:e,index:d.findIndex(t=>t.id===e.id)})).filter(e=>e.index!==-1);if(n.length===0)return;for(let e of n)S.current.set(e.ticket.id,e);let r=new Set(n.map(e=>e.ticket.id));f(e=>e.filter(e=>!r.has(e.id))),m(e=>e.filter(e=>!r.has(e.blocker_ticket_id)&&!r.has(e.dependent_ticket_id)));let i=await Promise.allSettled(n.map(async t=>(await ln(t.ticket.id,t.ticket.project_id??e),S.current.delete(t.ticket.id),t.ticket.id)));t.tickets.some(e=>e.project_id===x.current)&&w().catch(()=>{});let a=n.filter((e,t)=>i[t]?.status===`rejected`);if(a.length===0)return;for(let e of a)S.current.delete(e.ticket.id);a.some(e=>e.ticket.project_id===x.current)&&f(e=>[...a].sort((e,t)=>e.index-t.index).reduce((e,t)=>gX(e,t),e));let o=i.find(e=>e.status===`rejected`),s=a.length===n.length?o?.reason instanceof I?o.reason.message:l(`board.errors.deleteBundleTickets`):l(`board.toasts.deletedBundleTicketsPartial`,{deletedCount:n.length-a.length,totalCount:n.length});Q.error(s,{id:`board-delete-bundle-wrapper-error`})},[e,x,S,w,m,f,d,l]),Fn=e=>{let t=ct.get(e.id);En(e,{reorderInState:t?t.state!==e.state||t.parked_at!==e.parked_at||t.worktree_bundle_id!==e.worktree_bundle_id:!1}),t?.worktree_bundle_id&&t.worktree_bundle_id!==e.worktree_bundle_id&&t.bundle?.ticket_count===1&&g(e=>e.filter(e=>e.id!==t.worktree_bundle_id)),(t?.worktree_bundle_id!==e.worktree_bundle_id||t?.bundle?.ticket_count!==e.bundle?.ticket_count)&&e.project_id===x.current&&w().catch(()=>{})},In=async()=>{if(!e)return;let t=e,n=Tt.composer.description.trim();if(!n)return;let r=uX(),a=He?Tt.composer.model.trim():``,o=He&&a?Tt.composer.variant.trim():``,s=He?Tt.composer.skills:[],c=Date.now();Jt(t,e=>({...e,isOpen:!1,composer:{...e.composer,description:``,worktreeBundleId:``},runs:[{id:r,description:n,model:a,variant:o,skills:s,worktreeBundleId:kt,status:`running`,error:null,submittedAt:c,completedAt:null,boardVisible:!0,boardState:`visible`,summary:null},...e.runs]}));try{let e=await Xt({description:n,tool:i,model:a||null,variant:a&&o||null,skills:s,project_id:t,worktree_bundle_id:kt||null});pX(a||null,a&&o||null,s);let c=dX(e);Jt(t,e=>({...e,runs:fX(e.runs,r,e=>({...e,status:`done`,error:null,completedAt:Date.now(),summary:c,boardVisible:!1}))})),Q.success(l(`board.toasts.planningAgentCardsCreated`,{count:c.ticketCount}),{id:`planning-agent-success-${r}`}),ot(e.tickets.length),x.current===t&&Tn(e)}catch(e){let n=e instanceof I?e.message:l(`board.errors.generateTickets`);Jt(t,e=>({...e,runs:fX(e.runs,r,e=>({...e,status:`error`,error:n,completedAt:Date.now()}))})),Q.error(n,{id:`planning-agent-error`})}},Ln=async t=>{let n=d.find(e=>e.id===t),r=d.findIndex(e=>e.id===t);if(!(!n||r===-1)){S.current.set(t,{ticket:n,index:r}),f(e=>FY(e,t)),m(e=>Vw(e,t));try{await ln(t,n.project_id??e),n.project_id===x.current&&w().catch(()=>{}),S.current.delete(t)}catch(e){let n=S.current.get(t);S.current.delete(t),n&&n.ticket.project_id===x.current&&(f(e=>gX(e,n)),Q.error(e instanceof I?e.message:l(`board.errors.deleteTicket`),{id:`board-delete-error`}))}}},Rn=async t=>{let n=d.find(e=>e.id===t);if(!n)return;let r=n.state===`review`?`review`:`build`;try{if(pe(r),n.project_id&&n.worktree_bundle_id&&n.state===`review`){Qn(await Pt(n.project_id,n.worktree_bundle_id));return}En(await un(t,n.project_id??e),{reorderInState:!0})}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.undoTicket`),{id:`board-undo-error`}),e}finally{pe(e=>e===r?null:e)}},zn=t=>{mn(t,d.find(e=>e.id===t)?.project_id??e)},Bn=async t=>{let n=d.find(e=>e.id===t),r=n?Ew(n):t;try{Xe(r),await hn(t,n?.project_id??e),s?.()}catch(e){Xe(e=>e===r?null:e),Q.error(e instanceof I?e.message:l(`board.errors.startRun`),{id:`board-run-error`})}},Vn=(0,Y.useCallback)(async t=>{let n=d.find(e=>e.id===t);try{await gn(t,n?.project_id??e)}catch(e){Q.error(e instanceof I?e.message:l(`board.errors.openIde`),{id:`board-open-ide-error`})}},[e,l,d]),Hn=async t=>{let n=d.find(e=>e.id===t),i=r?.kind===`ticket`&&n&&et===Ew(n)?$e:null;try{await _n(t,n?.project_id??e),o?.(i),s?.()}catch{}},Un=t=>{vn(t,d.find(e=>e.id===t)?.project_id??e).then(()=>{f(e=>e.map(e=>e.id===t?{...e,agent_status:`stopped`,is_running:!1}:e))})},Wn=t=>{yn(t,d.find(e=>e.id===t)?.project_id??e).then(()=>{f(e=>e.map(e=>e.id===t?{...e,agent_status:`running`}:e))})},Gn=(0,Y.useCallback)(e=>{let t=qt(e);!t||!Wt(t)||Vn(t.id)},[Wt,qt,Vn]),Kn=(0,Y.useCallback)(e=>{let t=qt(e);t&&De({bundleId:e,ticketId:t.id,projectId:t.project_id,title:t.bundle?Dl(t.bundle):t.title})},[qt]),qn=(0,Y.useCallback)(e=>{if(!st)return;let t=qt(e);!t?.project_id||!bl(t)||ke(e)},[qt,st]),Jn=(0,Y.useCallback)(e=>{let t=d.find(t=>t.id===e);!t||!Gt(t)||Te({ticketId:t.id,projectId:t.project_id,title:t.title})},[Gt,d]),Yn=(0,Y.useCallback)(e=>{if(!st)return;let t=d.find(t=>t.id===e);!t?.project_id||!bl(t)||Ce({ticketId:t.id,projectId:t.project_id})},[st,d]),Xn=(0,Y.useCallback)(async(t,n)=>{let r=d.find(e=>e.id===t);if(r)try{En(r.state===`plan`?await Sn(t,r.project_id??e,n):await bn(t,r.project_id??e,n))}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.sendFollowUp`),{id:`board-follow-up-error`}),e}},[e,En,l,d]),Zn=(0,Y.useCallback)(e=>{f(t=>e.reduce((e,t)=>{let n=e.find(e=>e.id===t.id),r=T(n,t);if(!r)return e;let i=DY(n&&n.state===r.state&&n.agent_status===`running`&&r.agent_status===null?{...r,agent_status:n.agent_status,session_id:n.session_id,is_running:n.is_running}:r);return OY(n,i)?NY(e,i):MY(e,i)},t))},[T,f]),Qn=(0,Y.useCallback)(e=>{xe(e),g(t=>jY(t,e.bundle)),Zn(e.tickets)},[Zn,g]),$n=(0,Y.useCallback)((e,t)=>{Array.isArray(t.tickets)&&xe(n=>!n||n.bundle.id!==e?n:{...n,tickets:t.tickets,execution_order_ticket_ids:t.execution_order_ticket_ids,latest_session_ticket_id:t.latest_session_ticket_id,latest_session_id:t.latest_session_id,review_owner_ticket_id:t.review_owner_ticket_id,target_ticket_id:t.target_ticket_id})},[]),er=(0,Y.useCallback)(async e=>{let t=x.current;if(!t)return null;let n=await Dt(t,e);return x.current===t?(Qn(n),n):null},[x,Qn]),tr=(0,Y.useCallback)(async e=>{let t=x.current;if(!t)return null;let n=await Ot(t,e);return x.current===t?($n(e,n),n):null},[x,$n]),nr=(0,Y.useCallback)(async(e,t=null)=>{let n=x.current;if(!n)return;W(null),G(null),_e(e),ye(t),Ne(aX());let r=dt.get(e)??null,i=d.filter(t=>t.worktree_bundle_id===e);if(r&&i.length>0){let e=vl(i),t=xl(i,{reviewOwnerTicketId:i.find(e=>e.state===`review`)?.id??null,latestSessionTicketId:e?.id??null});xe({bundle:r,tickets:i,latest_session_ticket_id:e?.id??null,latest_session_id:e?.session_id??null,review_owner_ticket_id:i.find(e=>e.state===`review`)?.id??null,target_ticket_id:t?.id??null})}else xe(null);je(!0);try{await tr(e)}catch{}finally{x.current===n&&je(!1)}},[x,dt,tr,d]),rr=(0,Y.useCallback)(async(e,t)=>{Ne(t=>({...t,[e]:!0}));try{return await t()}finally{Ne(t=>({...t,[e]:!1}))}},[]),ir=(0,Y.useCallback)(async t=>{await rr(`stopBuild`,async()=>{let n=d.find(e=>e.id===t);await vn(t,n?.project_id??e),f(e=>e.map(e=>e.id===t?{...e,agent_status:`stopped`,is_running:!1}:e)),n?.worktree_bundle_id&&await er(n.worktree_bundle_id)})},[e,er,rr,f,d]),ar=(0,Y.useCallback)(async t=>{await rr(`resumeBuild`,async()=>{let n=d.find(e=>e.id===t);await yn(t,n?.project_id??e),f(e=>e.map(e=>e.id===t?{...e,agent_status:`running`}:e)),n?.worktree_bundle_id&&await er(n.worktree_bundle_id)})},[e,er,rr,f,d]),or=(0,Y.useCallback)(async t=>{if(e)try{Qn(await rr(`build`,()=>Mt(e,t))),ge===t&&ye(`build`),s?.()}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.buildBundle`),{id:`board-bundle-build-error`}),e}},[e,Qn,s,rr,ge,l]),sr=(0,Y.useCallback)(async t=>{if(e)try{Qn(await rr(`review`,()=>Nt(e,t))),ge===t&&ye(`review`)}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.reviewBundle`),{id:`board-bundle-review-error`}),e}},[e,Qn,rr,ge,l]),cr=(0,Y.useCallback)(async t=>{if(e)try{pe(`review`),Qn(await rr(`undoReview`,()=>Pt(e,t))),ge===t&&ye(`build`)}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.undoBundleReview`),{id:`board-bundle-undo-review-error`}),e}finally{pe(e=>e===`review`?null:e)}},[e,Qn,rr,ge,l]),lr=(0,Y.useCallback)(async(e,t,n)=>{if(t===iX||n===iX)return;let r=SX(t,n);if(!r)return;let i=d.filter(n=>n.worktree_bundle_id===e&&n.state===t&&n.parked_at===null);if(i.length===0)return;let a=i.map(e=>e.id);E(a,n),tn(i,n);try{if(r===`build`){await or(e),D(a);return}if(r===`review`){await sr(e),D(a);return}await cr(e),D(a)}catch(e){en(i),D(a),Q.error(e instanceof I?e.message:l(`board.errors.moveBundle`),{id:`board-bundle-move-error`})}},[D,or,sr,cr,E,tn,en,d,l]),ur=async t=>{e&&(Qn(await rr(`run`,()=>zt(e,t))),s?.())},dr=async t=>{if(!e)return;let n=r?.kind===`ticket`&&et===t?$e:null,i=await rr(`stop`,()=>Bt(e,t));o?.(n),Qn(i),s?.()},fr=(0,Y.useCallback)(async(t,n)=>{e&&Qn(await rr(`followUp`,()=>Ft(e,t,n)))},[e,Qn,rr]);(0,Y.useEffect)(()=>()=>{a?.(null)},[a]),(0,Y.useEffect)(()=>{if(!a)return;if(!r){a(null);return}if(r.kind===`project`){a({target:null,canSelect:!1,disabledReason:l(`board.preview.disabledProjectRoot`),submitPrompt:null});return}let e=d.find(e=>e.id===r.ticket_id);if(!e){a({target:null,canSelect:!1,disabledReason:l(`board.preview.disabledBuildCapable`),submitPrompt:null});return}if(e.state===`plan`){a({target:{kind:`ticket`,id:e.id},canSelect:!1,disabledReason:l(`board.preview.disabledPlanMode`),submitPrompt:null});return}if(e.worktree_bundle_id){a({target:{kind:`bundle`,id:e.worktree_bundle_id,ticket_id:e.id},canSelect:!0,disabledReason:null,promptPlaceholder:l(`board.preview.followUpBundlePlaceholder`),submitPrompt:t=>fr(e.worktree_bundle_id,t)});return}a({target:{kind:`ticket`,id:e.id},canSelect:!0,disabledReason:null,promptPlaceholder:l(`board.preview.followUpTicketPlaceholder`),submitPrompt:t=>Xn(e.id,t)})},[r,Xn,fr,a,l,d]);let pr=async t=>{let n=d.find(e=>e.id===t),r=n?ww(n.state):null;if(n)try{if(n.state===`review`&&n.can_re_review&&n.agent_status!==`running`){let t=await xn(n.id,n.project_id??e);En(t),t.worktree_bundle_id&&await er(t.worktree_bundle_id);return}if(!r)return;if(n.worktree_bundle_id&&r===`review`){await sr(n.worktree_bundle_id);return}await Dn(n,r)}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.moveTicket`),{id:`board-move-error`}),e}},mr=async t=>{let n=d.find(e=>e.id===t);try{En(await sn(t,n?.project_id??e))}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.startBuildChain`),{id:`board-build-chain-error`}),e}},hr=async t=>{let n=d.find(e=>e.id===t);try{await cn(t,n?.project_id??e)}catch(e){throw Q.error(e instanceof I?e.message:l(`board.errors.stopBuildChain`),{id:`board-stop-build-chain-error`}),e}},gr=async()=>{if(!(!e||de)){U(!0);try{let t=await pn(e);f(e=>e.filter(e=>!t.deleted_ticket_ids.includes(e.id))),m(e=>t.deleted_ticket_ids.reduce(Vw,e)),await w(),ue(!1),t.failed_count>0?Q.error(l(`board.toasts.deleteDonePartial`,{count:t.deleted_count,deletedCount:t.deleted_count,failedCount:t.failed_count}),{id:`board-delete-parked-error`}):Q.success(l(`board.toasts.deleteDoneSuccess`,{count:t.deleted_count}),{id:`board-delete-parked-success`})}catch(e){Q.error(e instanceof I?e.message:l(`board.errors.emptyDone`),{id:`board-delete-parked-error`})}finally{U(!1)}}},_r=({delta:e})=>{R(e)},vr=(0,Y.useCallback)((t=null)=>{e&&te({initialWorktreeBundleId:t})},[e]),yr=(0,Y.useCallback)(()=>{e&&Jt(e,e=>e.isOpen?e:{...e,isOpen:!0})},[e,Jt]),br=(0,Y.useCallback)(()=>{Je.current?.focus({preventScroll:!0})},[]);return EY([{key:`n`,onKeyDown:vr,disabled:!e},{key:`a`,onKeyDown:yr,disabled:!e},{key:`k`,ctrlKey:!0,onKeyDown:br}],{isBlocked:TY}),(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(JC,{sensors:u,collisionDetection:oS,onDragStart:Zt,onDragMove:_r,onDragCancel:$t,onDragEnd:rn,children:[(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 overflow-hidden`,children:[(0,Z.jsx)(pY,{projectId:e,state:At,bundles:h,projectBranchState:n,showModelSelector:He,availableModels:B,availableSkills:V,onManageBundles:e?()=>{(async()=>{try{await w()}catch{}re(!0)})()}:void 0,onToggle:()=>{e&&Jt(e,e=>({...e,isOpen:!e.isOpen}))},onDescriptionChange:t=>{e&&Jt(e,e=>({...e,composer:{...e.composer,description:t}}))},onModelChange:t=>{if(!e)return;let n=B.find(e=>e.id===t)??null;Jt(e,e=>({...e,composer:{...e.composer,model:t,variant:n?.variants.includes(e.composer.variant)?e.composer.variant:``}}))},onSkillsChange:t=>{e&&Jt(e,e=>({...e,composer:{...e.composer,skills:t}}))},onVariantChange:t=>{e&&Jt(e,e=>({...e,composer:{...e.composer,variant:t}}))},onBundleChange:t=>{e&&Jt(e,e=>({...e,composer:{...e.composer,worktreeBundleId:t}}))},onGenerate:()=>{In()}}),(0,Z.jsx)(`div`,{"aria-hidden":`true`,className:K(`absolute inset-y-0 left-16 right-0 z-10 bg-black/60 transition-opacity duration-200 ease-out motion-reduce:transition-none`,At.isOpen?`opacity-100`:`pointer-events-none opacity-0`)}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-4 overflow-hidden p-6`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col items-start gap-3 sm:flex-row sm:items-center`,children:[(0,Z.jsxs)(`div`,{className:`relative w-full max-w-sm`,children:[(0,Z.jsx)(Ge,{id:`board-ticket-search`,ref:Je,type:`search`,value:Ie,onChange:e=>Le(e.target.value),placeholder:l(`board.search.placeholder`),"aria-label":l(`board.search.ariaLabel`),className:`pr-32`}),Ie.length>0?(0,Z.jsx)(q,{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":l(`board.search.clearAriaLabel`),className:`absolute right-1 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,onClick:()=>{Le(``),Je.current?.focus()},children:(0,Z.jsx)(Ve,{className:`size-4`})}):(0,Z.jsxs)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute right-2 top-1/2 flex -translate-y-1/2 items-center gap-0.5 text-[10px] leading-none`,children:[(0,Z.jsx)(hw,{children:`CTRL`}),(0,Z.jsx)(`span`,{children:`+`}),(0,Z.jsx)(hw,{children:`K`})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Gd,{id:`board-hide-stale-tickets`,checked:Re,onCheckedChange:ze,"aria-label":l(`board.search.hideStaleAriaLabel`)}),(0,Z.jsx)(Qs,{htmlFor:`board-hide-stale-tickets`,className:`text-sm text-muted-foreground`,children:l(`board.search.hideStaleLabel`)})]})]}),(0,Z.jsx)(`div`,{ref:gt,className:`flex min-h-0 flex-1 overflow-x-auto overflow-y-hidden`,children:(0,Z.jsxs)(`div`,{ref:_t,className:`relative flex min-h-0 w-max min-w-full gap-4`,children:[(0,Z.jsx)(rY,{dependencies:p,cardRects:yt,preview:bt,ticketsById:ct,overlaySize:xt}),rX.map(t=>{let n=d.filter(e=>e.state===t&&!Ow(e)),r=pt.filter(e=>e.state===t&&!Ow(e)),i=Sl(r,h,t),a=it&&n.length===0?t===`plan`?1:t===`build`?2:0:0;return(0,Z.jsx)(pG,{id:t,title:l(`card.columnLabels.${t}`),pinnedContent:t===`plan`?Ut:null,items:i,ticketCount:r.length,allTickets:d,dependencies:p,showModelSelector:He,availableModels:B,bundles:h,activeRunContextKey:tt,isProjectRootRunActive:J,isBundleRunDisabled:nt,getDependencyTargetState:St,onDependencyStart:Ct,onDeleteDependency:wt,onRegisterTicketNode:vt,onAddTicket:t===`plan`&&e?vr:void 0,onCreateBundle:t===`plan`&&e?on:void 0,onDeleteBundle:t===`plan`&&e?Nn:void 0,onDeleteBundleWrapper:Pn,onRefreshBundles:t===`plan`&&e?w:void 0,onUpdateTicket:Fn,onDeleteTicket:Ln,onUndoTicket:Rn,undoingColumn:fe,onRetryTicket:zn,onAdvanceTicket:pr,onParkTicket:kn,onUnparkTicket:An,onBuildChainTicket:mr,onRunTicket:Bn,onOpenTestsTicket:st?Yn:void 0,canOpenChangesForTicket:Gt,onOpenChangesTicket:Jn,canOpenIdeForTicket:Wt,onOpenIdeTicket:Vn,onStopTicket:Hn,onStopBuildTicket:Un,onStopBuildChainTicket:hr,onResumeBuildTicket:Wn,onOpenBundleChanges:Kn,onOpenBundleTests:st?qn:void 0,onOpenBundleIde:Gn,onAddTicketToBundle:vr,onFollowUpTicket:Xn,bundleActionState:Me,onBuildBundle:or,onReviewBundle:sr,onUndoBundleReview:cr,onRunBundle:ur,onStopBundle:dr,onParkBundleWrapper:jn,onUnparkBundleWrapper:Mn,onOpenTicketDetails:ut,onOpenBundleDetails:(e,t)=>{nr(e,t)},onRequestBundleRefresh:e=>{rr(`bundleRefresh`,()=>er(e))},onRequestTicketRefresh:C,loadingSkeletonCount:a},t)}),(0,Z.jsx)(pG,{id:iX,title:l(`card.columnLabels.done`),items:ht,ticketCount:mt.length,allTickets:d,dependencies:p,showModelSelector:He,availableModels:B,bundles:h,activeRunContextKey:tt,isProjectRootRunActive:J,isBundleRunDisabled:nt,getDependencyTargetState:St,onDependencyStart:Ct,onDeleteDependency:wt,onRegisterTicketNode:vt,onUpdateTicket:Fn,onDeleteTicket:Ln,onUndoTicket:Rn,undoingColumn:fe,onRetryTicket:zn,onAdvanceTicket:pr,onParkTicket:kn,onUnparkTicket:An,onBuildChainTicket:mr,onRunTicket:Bn,onOpenTestsTicket:st?Yn:void 0,canOpenChangesForTicket:Gt,onOpenChangesTicket:Jn,canOpenIdeForTicket:Wt,onOpenIdeTicket:Vn,onStopTicket:Hn,onStopBuildTicket:Un,onStopBuildChainTicket:hr,onResumeBuildTicket:Wn,onOpenBundleChanges:Kn,onOpenBundleTests:st?qn:void 0,onOpenBundleIde:Gn,onAddTicketToBundle:vr,onFollowUpTicket:Xn,bundleActionState:Me,onBuildBundle:or,onReviewBundle:sr,onUndoBundleReview:cr,onRunBundle:ur,onStopBundle:dr,onParkBundleWrapper:jn,onUnparkBundleWrapper:Mn,onOpenTicketDetails:ut,onOpenBundleDetails:(e,t)=>{nr(e,t)},onRequestBundleRefresh:e=>{rr(`bundleRefresh`,()=>er(e))},onRequestTicketRefresh:C,className:`min-w-[272px] max-w-[272px] flex-[0.98] bg-card/65`,headerAccessory:(0,Z.jsxs)(q,{type:`button`,variant:`destructive`,size:`xs`,className:`gap-1.5`,disabled:mt.length===0||de,onClick:()=>ue(!0),children:[(0,Z.jsx)(wu,{className:`h-3.5 w-3.5`}),(0,Z.jsx)(`span`,{children:l(`board.doneColumn.emptyAction`)})]})})]})})]})]}),(0,Z.jsxs)(mw,{zIndex:5,dropAnimation:ae?null:void 0,children:[A&&(0,Z.jsx)(dG,{ticket:A,allTickets:d,dependencies:p,bundles:h,projectMemoryEnabled:!!t?.memory_enabled,overlay:!0,showModelSelector:A.tool===`opencode`&&B.length>0,availableModels:B,runDisabled:bX(A,tt,J,l(`board.errors.runBlockedByActive`))!==void 0,runDisabledReason:bX(A,tt,J,l(`board.errors.runBlockedByActive`)),onDependencyStart:Ct,onDeleteDependency:wt,onRegisterOverlayNode:F,onCreateBundle:on,onDeleteBundle:Nn,onRefreshBundles:w,onUpdate:Fn,onDelete:()=>Ln(A.id),onUndo:()=>Rn(A.id),undoInProgress:fe===A.state&&(A.state===`build`||A.state===`review`),onRetry:()=>zn(A.id),onAdvance:()=>pr(A.id),onPark:()=>kn(A.id),onUnpark:()=>An(A.id),onBuildChain:()=>mr(A.id),onRun:A.worktree_bundle_id===null&&bl(A)&&A.has_run_config?()=>Bn(A.id):void 0,onOpenIde:A.worktree_bundle_id===null&&Wt(A)?()=>Vn(A.id):void 0,onStop:A.worktree_bundle_id===null?()=>Hn(A.id):void 0,onStopBuild:()=>Un(A.id),onStopBuildChain:()=>hr(A.id),onResumeBuild:()=>Wn(A.id),onFollowUp:e=>Xn(A.id,e),onRequestTicketRefresh:C}),!A&&M&&(0,Z.jsx)(gT,{group:M,overlay:!0,renderTicket:Ht})]}),rt&&(0,Z.jsx)(mY,{className:`pointer-events-auto fixed left-1/2 top-4 z-20 w-[min(14rem,calc(100vw-2rem))] -translate-x-1/2`})]}),ee&&(0,Z.jsx)(iY,{onSubmit:an,bundles:h,projectId:e,projectBranchState:n,tool:i,showModelSelector:He,availableModels:B,availableSkills:V,initialModel:He?jt.model:``,initialVariant:He&&jt.model?jt.variant:``,initialSkills:He?jt.skills:[],initialWorktreeBundleId:ee.initialWorktreeBundleId,onCreateBundle:on,onDeleteBundle:Nn,onRefreshBundles:w,onClose:()=>te(null)}),ne&&e&&(0,Z.jsx)(Eu,{bundles:h,selectedBundleId:At.composer.worktreeBundleId||null,onSelectBundle:t=>{Jt(e,e=>({...e,composer:{...e.composer,worktreeBundleId:t??``}}))},onCreateBundle:on,onDeleteBundle:Nn,onClose:()=>re(!1)}),le&&(0,Z.jsx)(mG,{ticketCount:mt.length,isDeleting:de,onCancel:()=>ue(!1),onConfirm:()=>{gr()}}),he&&(0,Z.jsx)(uG,{ticket:he,allTickets:d,dependencies:p,bundles:h,projectMemoryEnabled:!!t?.memory_enabled,projectBranchState:n,onClose:()=>{let e=he.id;W(null),G(null),f(t=>t.map(t=>t.id===e?DY(t):t))},showModelSelector:Ue,availableModels:B,availableSkills:V,runDisabled:bX(he,tt,J,l(`board.errors.runBlockedByActive`))!==void 0,runDisabledReason:bX(he,tt,J,l(`board.errors.runBlockedByActive`)),onDeleteDependency:wt,onCreateBundle:on,onDeleteBundle:Nn,onRefreshBundles:w,onUpdate:Fn,onAdvance:()=>pr(he.id),onBuildChain:()=>mr(he.id),onRun:bl(he)&&he.has_run_config?()=>Bn(he.id):void 0,onOpenIde:Wt(he)?()=>Vn(he.id):void 0,onStop:()=>Hn(he.id),onStopBuild:()=>Un(he.id),onStopBuildChain:()=>hr(he.id),onResumeBuild:()=>Wn(he.id),onFollowUp:e=>Xn(he.id,e),onProjectMemorySuggestionsChanged:()=>{Fe(e=>e+1)},onRequestTicketRefresh:e=>{lt(e)}}),Se&&(0,Z.jsx)(Y.Suspense,{fallback:null,children:(0,Z.jsx)(JY,{scope:`ticket`,ticketId:Se.ticketId,projectId:Se.projectId,testCommands:at,onClose:()=>Ce(null)})}),Ee&&(0,Z.jsx)(UJ,{ticketId:Ee.ticketId,projectId:Ee.projectId,reviewCommentsBundleId:Ee.bundleId,title:Ee.title,onSubmitReviewPrompt:e=>fr(Ee.bundleId,e),canSubmitReviewPrompt:!d.some(e=>e.worktree_bundle_id===Ee.bundleId&&e.agent_status===`running`),reviewSubmitDisabledReason:d.some(e=>e.worktree_bundle_id===Ee.bundleId&&e.agent_status===`running`)?l(`board.changes.reviewPromptDisabledReason`):void 0,canAddReviewComments:!d.some(e=>e.worktree_bundle_id===Ee.bundleId&&e.agent_status===`running`),canModifyChanges:!d.some(e=>e.worktree_bundle_id===Ee.bundleId&&e.agent_status===`running`),changesDisabledReason:d.some(e=>e.worktree_bundle_id===Ee.bundleId&&e.agent_status===`running`)?l(`board.changes.modifyChangesDisabledReason`):void 0,onClose:()=>{let{bundleId:e}=Ee;De(null),er(e)},onTicketUpdate:Fn,onRequestTicketRefresh:C}),we&&(0,Z.jsx)(UJ,{ticketId:we.ticketId,projectId:we.projectId,title:we.title,onClose:()=>{let{ticketId:e}=we;Te(null),lt(e)},onTicketUpdate:Fn,onRequestTicketRefresh:e=>{lt(e)}}),Oe&&e&&t&&(0,Z.jsx)(Y.Suspense,{fallback:null,children:(0,Z.jsx)(JY,{scope:`project`,projectId:e,targetKind:`bundle`,targetBundleId:Oe,testCommands:at,onClose:()=>ke(null)})}),ge&&ft&&(0,Z.jsx)(PG,{details:ft,activeColumn:ve,isLoading:Ae||Me.bundleRefresh,actionState:Me,canOpenIde:Kt(ft),projectMemoryEnabled:!!t?.memory_enabled,memorySuggestionsRefreshKey:Pe,runDisabled:nt(ft.bundle.id),showModelSelector:We,availableModels:B,availableSkills:V,onClose:()=>{let e=ft.bundle.id;_e(null),ye(null),xe(null),je(!1),Ne(aX()),f(t=>t.map(t=>t.worktree_bundle_id===e&&t.id!==me?DY(t):t))},onOpenTicketDetails:ut,onUpdateTicket:Fn,onOpenIde:()=>{let e=ft.tickets.find(e=>e.id===ft.target_ticket_id)??ft.tickets.find(e=>e.has_worktree);e&&Vn(e.id)},onOpenTests:st?()=>{qn(ft.bundle.id)}:void 0,onRefresh:e=>{rr(`bundleRefresh`,()=>er(e))},onBuildBundle:or,onStopBuildTicket:ir,onResumeBuildTicket:ar,onReviewBundle:sr,onUndoBundleReview:cr,onRunBundle:ur,onStopBundle:dr,onFollowUpBundle:fr})]})},TX=({className:e})=>(0,Z.jsx)(jo,{"aria-hidden":`true`,className:e}),EX=({className:e})=>(0,Z.jsx)(So,{"aria-hidden":`true`,className:e}),DX=({className:e})=>(0,Z.jsx)(Co,{"aria-hidden":`true`,className:e}),OX=4,kX=5e3,AX=(e,t)=>Pe.t(`common:chatChangesPanel.${e}`,t),jX=e=>e.replace(/^[ab]\//,``),MX=e=>{let t=`oldPath`in e&&typeof e.oldPath==`string`?jX(e.oldPath):``,n=`newPath`in e&&typeof e.newPath==`string`?jX(e.newPath):``;return[...new Set([n,t].filter(e=>e&&e!==`/dev/null`))]},NX=e=>{let[t,n]=MX(e);return!t&&!n?AX(`unknownFile`):t&&n&&t!==n?`${n} -> ${t}`:t??n??AX(`unknownFile`)},PX=e=>{let t=eq((()=>{let[t,n]=MX(e);return t??n??null})());if(!t)return null;try{return Yy(e.hunks,{highlight:!0,refractor:eJ.default,language:t,enhancers:[qy(e.hunks)]})}catch{return null}},FX=(e,t)=>e instanceof Error?e.message:t,IX=(e,t)=>{if(!t)return e;let n=NX(t);return[t,...e.filter(e=>NX(e)!==n)]},LX=e=>[...e].sort((e,t)=>{if(e.filePath!==t.filePath)return e.filePath.localeCompare(t.filePath);let n=e.newLineNumber??e.oldLineNumber??2**53-1,r=t.newLineNumber??t.oldLineNumber??2**53-1;return n===r?e.changeKey.localeCompare(t.changeKey):n-r}),RX=({diffResponse:e,gitStatus:t})=>{let n=new Map;for(let t of e?.files??[])n.set(t.path,t);return t?t.files.map(e=>{let t=n.get(e.path)??(e.original_path?n.get(e.original_path):void 0);return{path:e.path,originalPath:e.original_path,status:e.status,staged:e.staged,unstaged:e.unstaged,conflicted:e.conflicted,additions:t?.additions??0,deletions:t?.deletions??0}}):(e?.files??[]).map(e=>({path:e.path,originalPath:null,status:null,staged:!1,unstaged:!1,conflicted:!1,additions:e.additions,deletions:e.deletions}))},zX=e=>{let t=e.split(/[\\/]/);return t[t.length-1]||e},BX={modified:`border-amber-500/40 bg-amber-500/10 text-amber-200`,added:`border-emerald-500/40 bg-emerald-500/10 text-emerald-200`,deleted:`border-rose-500/40 bg-rose-500/10 text-rose-200`,renamed:`border-sky-500/40 bg-sky-500/10 text-sky-200`,untracked:`border-violet-500/40 bg-violet-500/10 text-violet-200`,typechanged:`border-slate-500/40 bg-slate-500/10 text-slate-200`},VX=e=>AX(`fileStatus.${e}`),HX=({selectedDiffPath:e,sidebarFiles:t,diffStats:n,triggerMode:r=`full`,onSelectDiffPath:i})=>{let[a,o]=(0,Y.useState)(!1),s=t.find(t=>t.path===e)??null,c=r===`compact`?e===`all`?AX(`picker.diff`):s?zX(s.path):AX(`picker.file`):e===`all`?AX(`picker.allChanges`):s?zX(s.path):e;return(0,Z.jsxs)($s,{open:a,onOpenChange:o,children:[(0,Z.jsx)(ec,{asChild:!0,children:(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`outline`,className:K(`max-w-full gap-2`,r===`full`?`min-w-0 max-w-[18rem]`:`min-w-0 px-2.5`),"aria-label":AX(`picker.openChangedFilesAriaLabel`),title:e===`all`?void 0:s?.path??e,children:[(0,Z.jsx)(`span`,{className:`truncate`,children:c}),r===`full`&&(0,Z.jsx)(U,{variant:`outline`,className:`shrink-0 text-[10px] uppercase tracking-wide`,children:AX(`picker.fileCount`,{count:t.length})}),(0,Z.jsx)(ke,{className:`h-4 w-4 shrink-0 text-muted-foreground`})]})}),(0,Z.jsxs)(tc,{align:`start`,className:`z-[90] w-[28rem] max-w-[calc(100vw-2rem)] p-0`,children:[(0,Z.jsx)(`div`,{className:`border-b border-border/80 px-4 py-3`,children:(0,Z.jsx)(`div`,{className:`text-sm font-semibold text-foreground`,children:AX(`picker.title`)})}),(0,Z.jsx)(`div`,{className:`max-h-[min(28rem,calc(100vh-10rem))] overflow-y-auto p-3`,children:(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{i(`all`),o(!1)},className:K(`flex w-full cursor-pointer items-start gap-3 rounded-xl border px-3 py-2.5 text-left transition-colors`,RK(e===`all`),`justify-between`),children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium text-foreground`,children:AX(`picker.allChanges`)}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground transition-colors group-hover:text-foreground/70`,children:AX(`picker.allChangesDescription`)})]}),n&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3 text-[11px]`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground transition-colors group-hover:text-foreground/70`,children:AX(`picker.fileCount`,{count:n.files_changed})}),(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-emerald-400`,children:[`+`,n.additions]}),(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-rose-400`,children:[`-`,n.deletions]})]})]}),t.map(t=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{i(t.path),o(!1)},className:K(`flex w-full cursor-pointer items-start gap-3 rounded-xl border px-3 py-2.5 text-left transition-colors`,RK(e===t.path)),children:(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium text-foreground`,children:zX(t.path)}),(0,Z.jsx)(`div`,{className:`mt-0.5 break-all font-mono text-[11px] text-muted-foreground transition-colors group-hover:text-foreground/70`,children:t.path})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3 text-[11px]`,children:[(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-emerald-400`,children:[`+`,t.additions]}),(0,Z.jsxs)(`span`,{className:`font-mono tabular-nums text-rose-400`,children:[`-`,t.deletions]})]})]}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-1.5 text-[11px]`,children:[t.status&&(0,Z.jsx)(U,{variant:`outline`,className:BX[t.status],children:VX(t.status)}),t.staged&&(0,Z.jsx)(U,{variant:`outline`,children:AX(`fileStatus.staged`)}),t.unstaged&&(0,Z.jsx)(U,{variant:`outline`,children:AX(`fileStatus.unstaged`)}),t.conflicted&&(0,Z.jsx)(U,{variant:`destructive`,children:AX(`fileStatus.conflicted`)}),t.originalPath&&(0,Z.jsx)(`span`,{className:`break-all font-mono text-[11px] text-muted-foreground transition-colors group-hover:text-foreground/70`,children:t.status===`renamed`?AX(`fileStatus.renamedFrom`,{path:t.originalPath}):t.originalPath})]})]})},`${t.path}:${t.originalPath??``}`))]})})]})]})},UX=(0,Y.memo)(({projectId:e,chatSessionId:t=null,canSubmitReviewPrompt:n,reviewSubmitDisabledReason:r,onSubmitReviewPrompt:i,state:a,onStateChange:o,isResizing:s=!1,onClose:c,desktopWidth:l,panelElementRef:u})=>{let[d,f]=(0,Y.useState)(null),[p,m]=(0,Y.useState)(null),[h,g]=(0,Y.useState)(null),[_,v]=(0,Y.useState)(!1),[,y]=(0,Y.useState)(!1),[b,x]=(0,Y.useState)(new Map),[S,C]=(0,Y.useState)(!1),w=(0,Y.useRef)(0),T=(0,Y.useRef)(0),E=(0,Y.useRef)(null),D=(0,Y.useRef)(null),O=a.selectedDiffPath,k=a.activeReviewTarget,A=a.editingReviewCommentKey,j=k?.commentKey??A??`chat`,M=a.reviewDraftInput,N=(0,Y.useMemo)(()=>new Map(a.reviewComments.map(e=>[lb(e.filePath,e.changeKey),e])),[a.reviewComments]),P=(0,Y.useCallback)(async()=>{if(!e)throw Error(`Project id is required`);return t?await ox(e,t):await Ae(e)},[t,e]),F=(0,Y.useCallback)(async()=>{if(!e)throw Error(`Project id is required`);return t?await sx(e,t):await ge(e)},[t,e]);(0,Y.useEffect)(()=>{E.current=d},[d]),(0,Y.useEffect)(()=>{D.current=p},[p]);let I=(0,Y.useCallback)(async()=>{if(!e){T.current+=1,f(null),m(null),g(null),v(!1),y(!1);return}let t=w.current+1,n=T.current+1;w.current=t,T.current=n,v(!0),y(!0);let[r,i]=await Promise.allSettled([P(),F()]);w.current===t&&(r.status===`fulfilled`?(E.current=r.value,f(r.value),g(null)):g(FX(r.reason,AX(`errors.loadDiff`))),i.status===`fulfilled`&&(D.current=i.value,m(i.value)),T.current===n&&v(!1),y(!1))},[P,F,e]),L=(0,Y.useCallback)(async(t={})=>{if(!e)return;let{broadcastOnSignatureChange:n=!1}=t,r=w.current+1;w.current=r,y(!0);try{let t=await F();if(w.current!==r)return;let i=D.current?.workspace_signature??null,a=t.workspace_signature??null,o=!E.current||i!==a;if(D.current=t,m(t),!o){T.current+=1,v(!1);return}let s=!E.current,c=T.current+1;T.current=c,s&&v(!0);try{let t=await P();if(w.current!==r)return;E.current=t,f(t),g(null),n&&i!==a&&nq(e)}catch(e){if(w.current!==r)return;E.current||g(FX(e,AX(`errors.loadDiff`)))}finally{s&&T.current===c&&v(!1)}}catch{E.current||(T.current+=1,v(!1));return}finally{w.current===r&&y(!1)}},[P,F,e]);(0,Y.useEffect)(()=>{I()},[I]),(0,Y.useEffect)(()=>{if(e)return rq(t=>{t===e&&L()})},[e,L]),(0,Y.useEffect)(()=>{if(!e)return;let t=aq(()=>{document.visibilityState===`visible`&&L({broadcastOnSignatureChange:!0})});return()=>{t()}},[e,L]),(0,Y.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>{document.visibilityState===`visible`&&L({broadcastOnSignatureChange:!0})},kX);return()=>{window.clearInterval(t)}},[e,L]);let R=(0,Y.useMemo)(()=>{let e=typeof d?.diff==`string`?d.diff:``;return e.trim()?Bm(e,{nearbySequences:`zip`}).map(e=>({...e,pathCandidates:MX(e)})):[]},[d]),z=(0,Y.useMemo)(()=>{let e=new Map;for(let t of R)for(let n of t.pathCandidates)e.has(n)||e.set(n,t);return e},[R]),ee=(0,Y.useMemo)(()=>RX({diffResponse:d,gitStatus:p}),[d,p]);(0,Y.useEffect)(()=>{if(O!==`all`&&!(!d&&!p)){if(ee.length===0){o(e=>({...e,selectedDiffPath:`all`}));return}ee.some(e=>e.path===O)||o(e=>({...e,selectedDiffPath:`all`}))}},[d,p,o,O,ee]);let te=O===`all`?null:z.get(O)??null,ne=(0,Y.useMemo)(()=>IX(R,te),[R,te]),re=(0,Y.useMemo)(()=>O===`all`?R:te?[te]:[],[R,O,te]);(0,Y.useEffect)(()=>{x(new Map)},[R]),(0,Y.useEffect)(()=>{if(ne.length===0)return;let e=!1,t=null,n=0,r=()=>{if(e)return;let i=ne.slice(n,n+OX);i.length!==0&&(x(e=>{let t=new Map(e);for(let e of i){let n=NX(e);t.has(n)||t.set(n,PX(e))}return t}),n+=OX,n<ne.length&&(t=window.setTimeout(r,0)))};return t=window.setTimeout(r,0),()=>{e=!0,t!==null&&window.clearTimeout(t)}},[ne]);let B=(0,Y.useMemo)(()=>{let e=new Map;for(let t of ne.slice(0,OX))e.set(NX(t),PX(t));return e},[ne]),ie=(0,Y.useMemo)(()=>re.map(e=>({...e,tokens:b.get(NX(e))??B.get(NX(e))??null})),[B,b,re]),V=(0,Y.useMemo)(()=>R.map(e=>({...e,tokens:null})),[R]),H=(0,Y.useMemo)(()=>LX(a.reviewComments),[a.reviewComments]),ae=H.length,oe=n&&!S&&ae>0,se=(0,Y.useCallback)(()=>{o(e=>({...e,activeReviewTarget:null,editingReviewCommentKey:null,reviewDraftInput:``,reviewComments:[]}))},[o]),ce=(0,Y.useCallback)(({filePath:e,changeKey:t,commentKey:r})=>{let i=N.get(r);if(i){o(e=>({...e,selectedDiffPath:i.filePath,activeReviewTarget:null,editingReviewCommentKey:r,reviewDraftInput:i.comment}));return}n&&o(n=>({...n,activeReviewTarget:{filePath:e,changeKey:t,commentKey:r},editingReviewCommentKey:null,reviewDraftInput:``}))},[n,o,N]),le=(0,Y.useCallback)(()=>{o(e=>({...e,activeReviewTarget:null,editingReviewCommentKey:null,reviewDraftInput:``}))},[o]),ue=(0,Y.useCallback)(e=>{let t=N.has(e.commentKey);if(!n&&!t)return;let r=M.trim();if(!r)return;let i=e.change.type===`insert`?null:`oldLineNumber`in e.change?e.change.oldLineNumber:e.change.lineNumber,a=e.change.type===`delete`?null:`newLineNumber`in e.change?e.change.newLineNumber:e.change.lineNumber;o(t=>{let n=new Map(t.reviewComments.map(e=>[lb(e.filePath,e.changeKey),e]));return n.set(e.commentKey,{scope:`uncommitted`,filePath:e.filePath,changeKey:e.changeKey,changeType:e.change.type,oldLineNumber:i,newLineNumber:a,hunkHeader:e.hunk.content,lineContent:e.change.content,diffSnippet:ub(e.hunk,e.change),comment:r}),{...t,activeReviewTarget:null,editingReviewCommentKey:null,reviewDraftInput:``,reviewComments:[...n.values()]}})},[n,o,N,M]),de=(0,Y.useCallback)(e=>{let t=N.get(e);t&&o(n=>({...n,selectedDiffPath:t.filePath,activeReviewTarget:null,editingReviewCommentKey:e,reviewDraftInput:t.comment}))},[o,N]),U=(0,Y.useCallback)(e=>{o(t=>({...t,activeReviewTarget:t.activeReviewTarget?.commentKey===e?null:t.activeReviewTarget,editingReviewCommentKey:t.editingReviewCommentKey===e?null:t.editingReviewCommentKey,reviewDraftInput:t.activeReviewTarget?.commentKey===e||t.editingReviewCommentKey===e?``:t.reviewDraftInput,reviewComments:t.reviewComments.filter(t=>lb(t.filePath,t.changeKey)!==e)}))},[o]),fe=(0,Y.useCallback)(async()=>{if(!oe)return;C(!0);let e=yb({drafts:H,findings:[],githubComments:[],uncommittedFiles:R});try{await i(e),se(),Q.success(AX(`toasts.sendChangesSuccess`),{id:`chat-diff-review-submit-success`})}catch(e){Q.error(FX(e,AX(`errors.sendChanges`)),{id:`chat-diff-review-submit-error`})}finally{C(!1)}},[oe,se,i,R,H]),pe=(0,Y.useCallback)(e=>(0,Z.jsx)(WG,{reviewComments:H,pendingFixCount:ae,triggerMode:e===`wide`?`full`:`compact`,canSendReview:oe,isSubmittingReview:S,reviewSubmitDisabledReason:r??void 0,onClearPendingFixes:se,onSubmitReview:()=>{fe()}}),[oe,se,fe,S,ae,H,r]),me=c?(0,Z.jsx)(q,{type:`button`,size:`icon-sm`,variant:`ghost`,"aria-label":AX(`closeAriaLabel`),className:`text-muted-foreground hover:text-foreground`,onClick:c,children:(0,Z.jsx)(Ve,{className:`h-4 w-4`})}):null,W=l?{"--chat-changes-panel-width":`${l}px`}:void 0;return(0,Z.jsx)(`aside`,{"data-testid":`chat-changes-panel`,"data-desktop-width":l?String(l):void 0,ref:u,style:W,className:K(`flex h-[26rem] min-h-0 w-full shrink-0 flex-col overflow-hidden border-t border-border/70 bg-background/20 xl:h-full xl:border-l xl:border-t-0`,l?`xl:w-[var(--chat-changes-panel-width)]`:`xl:w-[32rem]`),children:(0,Z.jsx)(LK,{selectedDiffPath:O,sidebarFiles:ee,diffResponse:d,isDiffLoading:_,diffError:h,allDiffFiles:V,renderedFiles:ie,viewType:`unified`,onViewTypeChange:()=>{},onRetry:()=>{I()},activeReviewTarget:k,editingReviewCommentKey:A,reviewDraftInstanceKey:j,reviewDraftInput:M,reviewComments:H,reviewFindings:[],githubComments:[],selectedReviewFindingIds:[],selectedGitHubCommentIds:[],canSelectReviewTarget:n,canEditActiveReviewDraft:n,reviewFindingsError:null,gitHubCommentsError:null,hasStaleReviewFindings:!1,onSelectReviewTarget:ce,onToggleReviewFindingSelection:()=>{},onToggleGitHubCommentSelection:()=>{},onReviewDraftInputChange:e=>{o(t=>({...t,reviewDraftInput:e}))},onCancelReviewDraft:le,onEditReviewDraft:de,onRemoveReviewDraft:U,onSaveReviewDraft:ue,diffThemeClassName:UK,resolveFilePath:NX,normalizeDiffPath:jX,emptyStateTitle:AX(`emptyStateTitle`),emptyStateDescription:AX(`emptyStateDescription`),filePickerControl:e=>(0,Z.jsx)(HX,{selectedDiffPath:O,sidebarFiles:ee,diffStats:d?.stats??null,triggerMode:e===`wide`?`full`:`compact`,onSelectDiffPath:e=>{o(t=>({...t,selectedDiffPath:e}))}}),reviewSummaryControl:pe,extraHeaderControl:me,surfaceVariant:`flat`,showViewTypeToggle:!1,gutterVariant:`compact`,isResizing:s,resizePlaceholderLineThreshold:200})})});UX.displayName=`ChatChangesPanel`;var WX=({projectId:e,messages:t,internalLog:n,currentThinkingMessageId:r=null,previousThinkingLog:i=null,previousThinkingMessageId:a=null,pendingAgentTitle:o,streamingResponse:s,isRunning:c,isLoading:l=!1,canShowComposer:u,cardClassName:d,isExternallyResizing:f=!1,pendingAgentRevealKey:p=null,pendingAgentRevealDelayMs:m=0,composerFocusNonce:h=0,blurComposerOnSendStart:g=!1,hidePendingAgentTitle:_=!1,forceScrollToBottomKey:v,header:y,composerControls:b,composerInlineControls:x,composerTheme:S=`default`,layoutKey:C,scrollLayoutKey:w,followUpPrompt:T,draftAttachments:E=[],followUpPlaceholder:D,emptyStateText:O=null,renderMessageFooter:k,isSendingFollowUp:A,isUploadingAttachments:j=!1,canAttachImages:M=!1,followUpDisabledReason:N,onFollowUpPromptChange:P,onFollowUpKeyDown:F,onFollowUpPaste:I,onUploadAttachments:L,onRemoveAttachment:R,onFollowUpSubmit:z})=>(0,Z.jsx)(UN,{projectId:e,messages:t,internalLog:n,currentThinkingMessageId:r,previousThinkingLog:i,previousThinkingMessageId:a,pendingAgentTitle:o,streamingResponse:s,isRunning:c,isLoading:l,autoScrollBehavior:`sticky`,surfaceVariant:`chat`,canShowComposer:u,cardClassName:d,header:y,composerControls:b,composerInlineControls:x,composerTheme:S,composerSize:`compact-on-laptop`,showThinkingPlacement:`header`,pinComposerToBottom:!0,isExternallyResizing:f,pendingAgentRevealKey:p,pendingAgentRevealDelayMs:m,composerFocusNonce:h,blurComposerOnSendStart:g,forceScrollToBottomKey:v,layoutKey:C,scrollLayoutKey:w,followUpPrompt:T,draftAttachments:E,followUpPlaceholder:D,emptyStateText:O,autoFocusComposer:!0,renderMessageFooter:k,isSendingFollowUp:A,isUploadingAttachments:j,canAttachImages:M,followUpDisabledReason:N,hidePendingAgentTitle:_,onFollowUpPromptChange:P,onFollowUpKeyDown:F,onFollowUpPaste:I,onUploadAttachments:L,onRemoveAttachment:R,onFollowUpSubmit:z}),GX=({value:e,disabled:t=!1,onChange:n,planInactiveTooltip:r,buildInactiveTooltip:i})=>(0,Z.jsx)(Sc,{value:e,items:[{value:`plan`,label:`Plan`,activeVariant:`ghost`,activeClassName:`border-transparent bg-sky-300 text-[#07111a] shadow-[0_10px_30px_rgba(125,211,252,0.24)] hover:bg-sky-200 hover:text-[#07111a]`,inactiveClassName:`border-transparent text-white/85 hover:bg-white/8 hover:text-white`,inactiveTooltip:r},{value:`build`,label:`Build`,activeVariant:`ghost`,activeClassName:`border-transparent bg-emerald-400 text-[#07130d] shadow-[0_10px_30px_rgba(16,185,129,0.28)] hover:bg-emerald-300 hover:text-[#07130d]`,inactiveClassName:`border-transparent text-white/85 hover:bg-white/8 hover:text-white`,inactiveTooltip:i}],disabled:t,onChange:n}),KX={default:`h-5 rounded-md border-amber-500/40 bg-amber-500/10 px-1.5 text-[10px] uppercase tracking-[0.16em] text-amber-200`,muted:`h-5 rounded-md border-amber-500/40 bg-amber-500/10 px-1.5 text-[10px] uppercase tracking-[0.16em] text-amber-100`},qX=({tone:e=`default`,className:t,children:n,...r})=>(0,Z.jsx)(U,{variant:`outline`,className:K(KX[e],t),...r,children:n}),JX=(e,t)=>Pe.t(`projects:memory.${e}`,t),YX=e=>JX(`stageLabels.${e}`),XX=e=>JX(`priorityLabels.${e}`),ZX=()=>({kind:`decision`,title:``,scope:``,content:``,rationale:``,implications:``,stages:``,priority:`normal`}),QX=e=>e.kind===`convention`?{kind:`convention`,title:e.title,scope:e.scope??``,content:e.instruction,rationale:e.rationale??``,implications:``,stages:e.stages.join(`
|
|
148
148
|
`),priority:e.priority}:{kind:`decision`,title:e.title,scope:e.scope??``,content:e.decision,rationale:e.rationale??``,implications:e.implications.join(`
|
|
149
149
|
`),stages:``,priority:`normal`},$X=e=>e.split(`
|
|
150
|
-
`).map(e=>e.trim()).filter(Boolean).filter((e,t,n)=>n.indexOf(e)===t),eZ=e=>{let t=[`plan`,`build`,`review`,`follow_up`,`plan_follow_up`,`chat`];return e.split(/\n|,/).map(e=>e.trim()).filter(e=>t.includes(e)).filter((e,t,n)=>n.indexOf(e)===t)},tZ=({suggestion:e,isPending:t,onReview:n,onAccept:r,onDismiss:i})=>{let a=e.kind===`decision`?e.duplicate_match?.decision??null:null,o=JX(a?`suggested.saveAsNewDecision`:`suggested.accept`),s=e.kind===`decision`?e.decision:e.instruction;return(0,Z.jsx)(`li`,{className:`rounded-xl border border-border/60 bg-background/40`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 p-3`,children:[(0,Z.jsx)(`div`,{className:`flex items-start justify-between gap-3`,children:(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-semibold text-foreground`,children:e.title}),(0,Z.jsx)(qX,{children:JX(`suggested.badge`,{kind:e.kind})}),a?(0,Z.jsx)(qX,{tone:`muted`,children:JX(`suggested.duplicateBadge`)}):null]}),(0,Z.jsx)(`p`,{className:`line-clamp-2 text-sm text-muted-foreground`,children:s})]})}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,disabled:t,onClick:()=>n(e),children:JX(`suggested.review`)}),(0,Z.jsx)(q,{type:`button`,size:`sm`,disabled:t,onClick:()=>void r(e),children:o}),(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,disabled:t,onClick:()=>void i(e),children:JX(`suggested.dismiss`)})]})]})})},nZ=({suggestion:e,isOpen:t,isEditing:n,isPending:r,draft:i,onOpenChange:a,onStartEdit:o,onDraftChange:s,onCancelEdit:c,onAccept:l,onDismiss:u})=>{if(!e)return null;let d=e.kind===`decision`?e.duplicate_match?.decision??null:null,f=d?JX(`suggested.saveAsNewDecision`):JX(`suggested.acceptAs`,{kind:e.kind});return(0,Z.jsx)(As,{open:t,onOpenChange:a,children:(0,Z.jsxs)(Ps,{className:`max-h-[85vh] overflow-y-auto sm:max-w-2xl`,children:[(0,Z.jsxs)(Fs,{children:[(0,Z.jsx)(Ls,{children:e.title}),(0,Z.jsx)(Rs,{children:JX(`suggested.reviewDescription`,{kind:e.kind})})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[d?(0,Z.jsxs)(`div`,{className:`rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs leading-5 text-amber-100`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-amber-50`,children:JX(`suggested.duplicateTitle`)}),(0,Z.jsxs)(`p`,{children:[(0,Z.jsxs)(`span`,{className:`font-medium`,children:[d.title,`:`]}),` `,d.decision]})]}):null,n?(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground sm:col-span-2`,children:[(0,Z.jsx)(`span`,{children:JX(`editor.titleLabel`)}),(0,Z.jsx)(`input`,{"aria-label":JX(`editor.titleAriaLabel`),value:i.title,onChange:e=>s({...i,title:e.target.value}),className:`h-10 rounded-lg border border-border bg-background px-3 text-sm text-foreground outline-none transition focus:border-primary/60`})]}),(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground sm:col-span-2`,children:[(0,Z.jsx)(`span`,{children:JX(`editor.scopeLabel`)}),(0,Z.jsx)(`input`,{"aria-label":JX(`editor.scopeAriaLabel`),value:i.scope,onChange:e=>s({...i,scope:e.target.value}),className:`h-10 rounded-lg border border-border bg-background px-3 text-sm text-foreground outline-none transition focus:border-primary/60`})]}),(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground sm:col-span-2`,children:[(0,Z.jsx)(`span`,{children:i.kind===`decision`?JX(`suggested.decision`):JX(`suggested.instruction`)}),(0,Z.jsx)(`textarea`,{"aria-label":i.kind===`decision`?JX(`suggested.decision`):JX(`suggested.instruction`),value:i.content,onChange:e=>s({...i,content:e.target.value}),rows:5,className:`min-h-32 rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none transition focus:border-primary/60`})]}),(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground sm:col-span-2`,children:[(0,Z.jsx)(`span`,{children:JX(`editor.rationaleLabel`)}),(0,Z.jsx)(`textarea`,{"aria-label":JX(`editor.rationaleAriaLabel`),value:i.rationale,onChange:e=>s({...i,rationale:e.target.value}),rows:3,className:`rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none transition focus:border-primary/60`})]}),i.kind===`decision`?(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground sm:col-span-2`,children:[(0,Z.jsx)(`span`,{children:JX(`suggested.implicationsMultiline`)}),(0,Z.jsx)(`textarea`,{"aria-label":JX(`editor.implicationsAriaLabel`),value:i.implications,onChange:e=>s({...i,implications:e.target.value}),rows:3,className:`rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none transition focus:border-primary/60`})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:JX(`suggested.stagesMultiline`)}),(0,Z.jsx)(`textarea`,{"aria-label":JX(`editor.stagesLabel`),value:i.stages,onChange:e=>s({...i,stages:e.target.value}),rows:3,className:`rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none transition focus:border-primary/60`})]}),(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:JX(`editor.priorityLabel`)}),(0,Z.jsxs)(`select`,{"aria-label":JX(`editor.priorityAriaLabel`),value:i.priority,onChange:e=>s({...i,priority:e.target.value}),className:`h-10 rounded-lg border border-border bg-background px-3 text-sm text-foreground outline-none transition focus:border-primary/60`,children:[(0,Z.jsx)(`option`,{value:`low`,children:JX(`priorityLabels.low`)}),(0,Z.jsx)(`option`,{value:`normal`,children:JX(`priorityLabels.normal`)}),(0,Z.jsx)(`option`,{value:`high`,children:JX(`priorityLabels.high`)})]})]})]})]}):(0,Z.jsxs)(`div`,{className:`space-y-4 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground`,children:e.kind===`decision`?JX(`suggested.decision`):JX(`suggested.instruction`)}),(0,Z.jsx)(`p`,{className:`whitespace-pre-wrap text-foreground`,children:e.kind===`decision`?e.decision:e.instruction})]}),e.rationale?(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground`,children:JX(`editor.rationaleLabel`)}),(0,Z.jsx)(`p`,{className:`whitespace-pre-wrap text-muted-foreground`,children:e.rationale})]}):null,e.kind===`decision`&&e.implications.length>0?(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground`,children:JX(`editor.implicationsLabel`)}),(0,Z.jsx)(`ul`,{className:`list-disc space-y-1 pl-5 text-muted-foreground`,children:e.implications.map(e=>(0,Z.jsx)(`li`,{children:e},e))})]}):null,e.kind===`convention`?(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground`,children:JX(`editor.stagesLabel`)}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:e.stages.map(e=>YX(e)).join(`, `)||JX(`suggested.noneSpecified`)})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground`,children:JX(`editor.priorityLabel`)}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:XX(e.priority)})]})]}):null]})]}),(0,Z.jsxs)(Is,{className:`flex flex-wrap gap-2 sm:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[n?(0,Z.jsx)(q,{type:`button`,variant:`ghost`,disabled:r,onClick:c,children:JX(`suggested.cancelEdits`)}):(0,Z.jsx)(q,{type:`button`,variant:`outline`,disabled:r,onClick:()=>o(e),children:JX(`suggested.edit`)}),(0,Z.jsx)(q,{type:`button`,variant:`ghost`,disabled:r,onClick:()=>void u(e),children:JX(`suggested.dismiss`)})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[d?(0,Z.jsx)(q,{type:`button`,variant:`outline`,disabled:r,onClick:()=>void l(e,!0),children:JX(`suggested.updateExistingDecision`)}):null,(0,Z.jsx)(q,{type:`button`,disabled:r,onClick:()=>void l(e,!1),children:f})]})]})]})})},rZ=({projectId:e,suggestions:t,title:n,description:r,emptyState:i=null,onSuggestionsChanged:a})=>{let[o,s]=(0,Y.useState)(null),[c,l]=(0,Y.useState)(null),[u,d]=(0,Y.useState)(ZX),[f,p]=(0,Y.useState)(null);(0,Y.useEffect)(()=>{l(e=>e&&!t.some(t=>t.id===e)?null:e),s(e=>e&&!t.some(t=>t.id===e)?null:e)},[t]);let m=o?t.find(e=>e.id===o)??null:null,h=()=>{l(null),d(ZX())},g=e=>{s(e.id),l(e.id),d(QX(e))},_=e=>{c&&c!==e.id&&h(),s(e.id)},v=e=>{e||(s(null),c&&h())},y=async(t,n)=>{let r=c===t.id?u:QX(t),i=r.kind===`decision`?{title:r.title.trim(),scope:r.scope.trim()||null,decision:r.content.trim(),rationale:r.rationale.trim()||null,implications:$X(r.implications)}:{title:r.title.trim(),scope:r.scope.trim()||null,instruction:r.content.trim(),rationale:r.rationale.trim()||null,stages:eZ(r.stages),priority:r.priority};p(t.id);try{if(n){if(t.kind!==`decision`)throw Error(JX(`messages.onlyDecisionSuggestionsCanUpdate`));let n=t.duplicate_match?.decision;if(!n)throw Error(JX(`messages.noExistingDecision`));await Re(e,t.id,n.id,i)}else await T(e,t.id,i);h(),s(null),a?.()}catch(e){Q.error(e instanceof Error?e.message:JX(`messages.saveSuggestionError`),{id:`project-memory-suggestion-error`})}finally{p(null)}},b=async t=>{p(t.id);try{await Be(e,t.id),c===t.id&&h(),o===t.id&&s(null),a?.()}catch(e){Q.error(e instanceof Error?e.message:JX(`messages.dismissSuggestionError`),{id:`project-memory-suggestion-error`})}finally{p(null)}};return(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[n||r?(0,Z.jsx)(`div`,{className:`flex items-center justify-between gap-3`,children:(0,Z.jsxs)(`div`,{children:[n?(0,Z.jsx)(`h4`,{className:`text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground`,children:n}):null,r?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:r}):null]})}):null,t.length>0?(0,Z.jsx)(`ul`,{className:`space-y-2`,children:t.map(e=>(0,Z.jsx)(tZ,{suggestion:e,isPending:f===e.id,onReview:_,onAccept:e=>y(e,!1),onDismiss:b},e.id))}):i?(0,Z.jsx)(`div`,{className:`rounded-lg border border-dashed border-border/70 px-3 py-4 text-sm text-muted-foreground`,children:i}):null,(0,Z.jsx)(nZ,{suggestion:m,isOpen:!!m,isEditing:c===m?.id,isPending:f===m?.id,draft:c===m?.id?u:m?QX(m):u,onOpenChange:v,onStartEdit:g,onDraftChange:d,onCancelEdit:h,onAccept:y,onDismiss:b})]})},iZ=()=>({selectedDiffPath:`all`,activeReviewTarget:null,editingReviewCommentKey:null,reviewDraftInput:``,reviewComments:[]}),aZ=[{key:`today`,label:`Today`},{key:`yesterday`,label:`Yesterday`},{key:`last_7_days`,label:`Last 7 Days`},{key:`older`,label:`Older`}],oZ=e=>{if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t},sZ=e=>e.activity_at??e.last_user_message_at??e.created_at,cZ=(e,t)=>{let n=sZ(e),r=sZ(t);return n===r?e.created_at===t.created_at?t.id.localeCompare(e.id):t.created_at.localeCompare(e.created_at):r.localeCompare(n)},lZ=e=>[...e].sort(cZ),uZ=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()),dZ=(e,t=new Date)=>{let n=oZ(sZ(e));if(!n)return`older`;let r=uZ(t),i=new Date(r);i.setDate(i.getDate()-1);let a=new Date(r);return a.setDate(a.getDate()-6),n>=r?`today`:n>=i?`yesterday`:n>=a?`last_7_days`:`older`},fZ=(e,t=new Date)=>{let n=new Map;for(let r of lZ(e)){let e=dZ(r,t);n.set(e,[...n.get(e)??[],r])}return aZ.flatMap(e=>{let t=n.get(e.key)??[];return t.length===0?[]:[{key:e.key,label:e.label,sessions:t}]})},pZ=e=>{let t={...e};return delete t.messages,t.agent_log=null,t.agent_message_id=null,t.previous_agent_log=null,t.previous_agent_message_id=null,t.streaming_response=null,t},mZ=(e,t)=>Pe.t(`chatView.${e}`,t),hZ=1500,gZ=`archon.chat-run-config`,_Z=`archon.chat-changes-panel-layout`,vZ=`archon.chat-session-list-layout`,yZ=`archon.chat-draft`,bZ=512,xZ=360,SZ=.6,CZ=6,wZ=`.`,TZ=`/`,EZ=`Slash`,DZ=`NumpadDivide`,OZ=600,kZ=4,AZ=`mt-1 flex min-h-5 flex-wrap items-center gap-2 text-xs text-muted-foreground`,jZ=(e,t)=>{let n=Number.isFinite(e)?Math.round(e):bZ;if(!Number.isFinite(t))return Math.max(xZ,n);let r=Math.max(xZ,Math.round(t*SZ));return Math.max(xZ,Math.min(r,n))},MZ=e=>mZ(e===`claude`?`tool.claude`:`tool.opencode`),NZ=({availableModelsById:e,model:t})=>t?e.get(t)??t:null,PZ=e=>mZ(e===`plan`?`mode.plan`:`mode.build`),FZ=e=>mZ(e===`plan`?`placeholders.plan`:`placeholders.build`),IZ=e=>mZ(`pendingMemorySuggestions`,{count:e}),LZ=e=>e===`plan`?`build`:`plan`,RZ=e=>!e.defaultPrevented&&!e.altKey&&!e.shiftKey&&!e.repeat&&(e.ctrlKey||e.metaKey)&&e.key===wZ,zZ=e=>!e.defaultPrevented&&!e.altKey&&!e.repeat&&(e.ctrlKey||e.metaKey)&&(e.key===TZ||e.code===EZ||e.code===DZ),BZ=()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??navigator.userAgent;return/mac/i.test(e)},VZ=()=>BZ()?mZ(`shortcuts.modifierMac`):mZ(`shortcuts.modifierDefault`),HZ=({modifierLabel:e,keys:t,ariaHidden:n=!1})=>(0,Z.jsxs)(`span`,{"aria-hidden":n,className:`flex items-center gap-0.5 text-[10px] leading-none`,children:[(0,Z.jsx)(hw,{"aria-hidden":n,children:e}),t.map(e=>(0,Z.jsxs)(`span`,{className:`contents`,children:[(0,Z.jsx)(`span`,{children:`+`}),(0,Z.jsx)(hw,{"aria-hidden":n,children:e})]},e))]}),UZ=({label:e,modifierLabel:t,keys:n})=>(0,Z.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{children:e}),(0,Z.jsx)(HZ,{modifierLabel:t,keys:n,ariaHidden:!0})]}),WZ=({modelLabel:e,tool:t})=>e??MZ(t),GZ=()=>mZ(`user.you`),KZ=e=>{if(!Number.isFinite(e))return`0`;if(e>=1e6){let t=e/1e6,n=t<10?2:1;return`${t.toFixed(n)}M`}return e>=1e3?`${(e/1e3).toFixed(1)}K`:`${Math.round(e)}`},qZ=({totalTokens:e,contextWindow:t})=>!Number.isFinite(e)||!Number.isFinite(t)||t<=0?null:Math.round(e/t*100),JZ=({tool:e,model:t,availableModels:n,fallbackContextWindow:r})=>e===`opencode`?(n.find(e=>e.id===t)??null)?.context_window??r:r,YZ=({projectId:e,tool:t})=>`${gZ}:${e}:${t}`,XZ=({projectId:e,tool:t,chatSessionId:n})=>n?`${yZ}:${e}:session:${n}`:`${yZ}:${e}:draft:${t}`,ZZ=e=>`${_Z}:${e}`,QZ=e=>`${vZ}:${e}`,$Z=e=>{if(!e)return``;try{return window.localStorage.getItem(e)??``}catch{return``}},eQ=({storageKey:e,value:t})=>{if(e)try{if(t){window.localStorage.setItem(e,t);return}window.localStorage.removeItem(e)}catch{}},tQ=e=>{if(!e)return{isOpen:!0,width:bZ};try{let t=window.localStorage.getItem(ZZ(e));if(!t)return{isOpen:!0,width:bZ};let n=JSON.parse(t),r=typeof n.width==`number`&&Number.isFinite(n.width)?Math.max(xZ,Math.round(n.width)):bZ;return{isOpen:n.isOpen!==!1,width:r}}catch{return{isOpen:!0,width:bZ}}},nQ=e=>{if(!e)return{isOpen:!0};try{let t=window.localStorage.getItem(QZ(e));return t?{isOpen:JSON.parse(t).isOpen!==!1}:{isOpen:!0}}catch{return{isOpen:!0}}},rQ=({projectId:e,isOpen:t,width:n})=>{if(e)try{window.localStorage.setItem(ZZ(e),JSON.stringify({isOpen:t,width:n}))}catch{}},iQ=({projectId:e,isOpen:t})=>{if(e)try{window.localStorage.setItem(QZ(e),JSON.stringify({isOpen:t}))}catch{}},aQ=({projectId:e,tool:t})=>{if(!e||t!==`opencode`)return null;try{let n=window.localStorage.getItem(YZ({projectId:e,tool:t}));if(!n)return null;let r=JSON.parse(n),i=(typeof r.model==`string`?r.model.trim():``)||null,a=r.mode===`plan`||r.mode===`build`?r.mode:null;return!i&&!a?null:{model:i,variant:i&&typeof r.variant==`string`&&r.variant.trim()||null,mode:a}}catch{return null}},oQ=({projectId:e,tool:t,model:n,variant:r,mode:i})=>{if(!(!e||t!==`opencode`||!n&&!i))try{window.localStorage.setItem(YZ({projectId:e,tool:t}),JSON.stringify({model:n,variant:n?r:null,mode:i}))}catch{}},sQ=({projectId:e,tool:t})=>aQ({projectId:e,tool:t})?.mode??`plan`,cQ=({activeProjectId:e,helperModel:t,helperVariant:n,activeTool:r,availableModels:i})=>{let a=aQ({projectId:e,tool:r}),o=new Set(i.map(e=>e.id)),s=e=>e?o.size===0?!0:o.has(e):!1,c=t??``,l=a?.model??``,u=s(l)?l:s(c)?c:``,d=u===l?a?.variant??null:u&&u===c?n??null:null,f=i.find(e=>e.id===u)??null;return{model:u,variant:f?f.variants.includes(d??``)?d??``:``:u?d??``:``,mode:a?.mode??`plan`}},lQ=e=>e&&e.replace(/\s+/g,` `).trim()||null,uQ=e=>{let t=lQ(e.first_user_message_preview);if(t)return t;let n=e.messages?.find(e=>e.role===`user`)?.content;return lQ(n)},dQ=({chatSessionId:e,instruction:t,attachments:n,createdAt:r})=>({id:`optimistic:${e}:${r}`,chat_session_id:e,role:`user`,kind:`prompt`,content:t,attachments:n,created_at:r}),fQ=({session:e,instruction:t,attachments:n,createdAt:r})=>({...e,messages:[...e.messages??[],dQ({chatSessionId:e.id,instruction:t,attachments:n,createdAt:r})],activity_at:r,last_user_message_at:r,updated_at:r}),pQ=e=>!!(e.first_user_message_preview||e.last_user_message_at||e.messages?.some(e=>e.role===`user`)),mQ=({activeProject:e,activeProjectBranchState:t,session:n})=>!e||n.target_available===!1?!1:n.target_kind===`bundle`?e.active_target_kind===`bundle`&&!!n.target_bundle_id&&e.active_target_bundle_id===n.target_bundle_id:e.active_target_kind===`bundle`?!1:!t||!n.target_branch_snapshot?!0:t?.status!==`ready`||!t.branch?!1:t.branch===n.target_branch_snapshot,hQ=({session:e,activeProject:t,activeProjectBranchState:n})=>e.target_kind===`bundle`?e.target_label_snapshot||mZ(`targets.bundleFallback`):!t||t.active_target_kind===`bundle`||n?.status!==`ready`||!n.branch||!e.target_branch_snapshot||n.branch===e.target_branch_snapshot?null:mZ(`targets.repoRootWithBranch`,{branch:e.target_branch_snapshot}),gQ=e=>e.target_kind===`bundle`?e.target_label_snapshot||mZ(`targets.bundleFallback`):e.target_branch_snapshot?mZ(`targets.repoRootWithBranch`,{branch:e.target_branch_snapshot}):mZ(`targets.repoRoot`),_Q=({activeProject:e,activeProjectBranchState:t})=>e?e.active_target_kind===`bundle`?mZ(`targets.selectedBundleTarget`):t?.branch?mZ(`targets.repoRootWithBranch`,{branch:t.branch}):mZ(`targets.repoRoot`):mZ(`targets.currentTarget`),vQ=e=>e.agent_status===`running`?mZ(`sidebar.deleteDisabledReason`):null,yQ=({count:e,title:t,isDeleting:n,onConfirm:r,onCancel:i})=>{let a=e>1;return(0,Z.jsxs)(pu,{onClose:i,overlayClassName:`bg-black/60`,panelClassName:`max-w-sm rounded-2xl border border-border bg-card p-6 shadow-2xl`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold uppercase tracking-widest text-muted-foreground`,children:mZ(a?`deleteSessionModal.bulkTitle`:`deleteSessionModal.title`)}),t?(0,Z.jsx)(`p`,{className:`mb-1 text-sm text-foreground`,children:t}):null,(0,Z.jsx)(`p`,{className:`mb-6 text-xs text-muted-foreground`,children:a?mZ(`deleteSessionModal.bulkDescription`,{count:e}):mZ(`deleteSessionModal.description`)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(q,{type:`button`,variant:`ghost`,onClick:i,disabled:n,children:mZ(`deleteSessionModal.cancel`)}),(0,Z.jsx)(q,{type:`button`,variant:`destructive`,onClick:r,disabled:n,children:mZ(n?`deleteSessionModal.deleting`:`deleteSessionModal.delete`)})]})]})},bQ=({activeProject:e,activeProjectBranchState:t,activeSessionId:n,chatModeShortcutModifierLabel:r,deletingSessionIds:i,finishedBackgroundSessionIds:a,hasDeletableSessions:o,isCreatingSession:s,isSelectionMode:c,isDraftOpen:l,isLoadingSessions:u,isOpen:d,isSendingPrompt:f,selectedSessionCount:p,selectedSessionIds:m,sessionGroups:h,sessions:g,onConfirmDeleteSelectedSessions:_,onConfirmDeleteSession:v,onDraftOpen:y,onEnterSelectionMode:b,onExitSelectionMode:x,onSetSessionSelection:S,onSessionSelect:C,onToggleSessionSelection:w,onToggleOpen:T})=>{let E=(0,Y.useMemo)(()=>new Set(g.filter(e=>!vQ(e)&&!i.has(e.id)).map(e=>e.id)),[i,g]),D=(0,Y.useRef)(null),O=(0,Y.useRef)(!1),k=(0,Y.useRef)(null),A=(0,Y.useCallback)(()=>{k.current!==null&&(window.clearTimeout(k.current),k.current=null)},[]),j=(0,Y.useCallback)(()=>{A(),k.current=window.setTimeout(()=>{O.current=!1,k.current=null},0)},[A]),M=(0,Y.useCallback)(()=>{D.current&&(D.current=null,j())},[j]),N=(0,Y.useCallback)(e=>{let t=D.current;!t||t.visitedSessionIds.has(e)||!E.has(e)||(t.visitedSessionIds.add(e),S(e,t.mode===`select`))},[S,E]),P=(0,Y.useCallback)(e=>{let t=D.current;!t||e.pointerId!==t.pointerId||M()},[M]);return(0,Y.useEffect)(()=>{if(!c){M();return}return window.addEventListener(`pointerup`,P),window.addEventListener(`pointercancel`,P),()=>{window.removeEventListener(`pointerup`,P),window.removeEventListener(`pointercancel`,P),M(),A()}},[A,P,c,M]),(0,Z.jsx)(`aside`,{"data-testid":`chat-sessions-sidebar`,"data-state":d?`expanded`:`collapsed`,"aria-label":mZ(`sidebar.ariaLabel`),className:K(`relative z-20 flex h-full shrink-0 flex-col overflow-hidden border-r border-border/70 bg-background/40 transition-[width] duration-200 ease-out motion-reduce:transition-none`,d?`w-72`:`w-16`),children:d?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-start gap-2 border-b border-border/70 px-4 py-3.5`,children:[(0,Z.jsxs)(q,{type:`button`,size:`sm`,className:`gap-2`,onClick:y,disabled:s||f,children:[(0,Z.jsx)(zl,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:mZ(`sidebar.newSession`)}),(0,Z.jsx)(HZ,{modifierLabel:r,keys:[TZ],ariaHidden:!0})]}),(0,Z.jsx)(q,{type:`button`,size:`icon-sm`,variant:`ghost`,"aria-label":mZ(`sidebar.collapseAriaLabel`),"aria-expanded":d,className:`ml-auto`,onClick:T,children:(0,Z.jsx)(EX,{className:`h-4 w-4`})})]}),g.length>0?(0,Z.jsx)(`div`,{className:`px-4 py-2.5`,children:c?(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`h-7 px-2 text-xs`,onClick:x,disabled:i.size>0,children:mZ(`sidebar.cancelSelection`)}),(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`destructive`,className:`h-7 px-2 text-xs`,onClick:_,disabled:p===0||i.size>0,children:mZ(`sidebar.deleteSelected`)})]}),(0,Z.jsx)(`div`,{className:`flex justify-end text-xs font-medium text-muted-foreground`,children:mZ(`sidebar.selectedCount`,{count:p})})]}):o?(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`h-7 gap-1.5 px-2 text-xs`,onClick:b,children:[(0,Z.jsx)(TX,{className:`h-3.5 w-3.5`}),mZ(`sidebar.select`)]}):null}):null,(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-2`,children:u&&g.length===0?(0,Z.jsx)(`div`,{className:`px-2 py-4 text-sm text-muted-foreground`,children:mZ(`sidebar.loadingSessions`)}):g.length===0?(0,Z.jsx)(`div`,{className:`rounded-lg border border-dashed border-border/70 px-3 py-4 text-sm text-muted-foreground`,children:mZ(`sidebar.noSessions`)}):(0,Z.jsx)(`div`,{className:`flex flex-col gap-3`,children:h.map(r=>(0,Z.jsxs)(`section`,{"aria-label":r.label,className:`flex flex-col gap-1.5`,children:[(0,Z.jsx)(`div`,{className:`px-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground/80`,children:r.label}),r.sessions.map(r=>{let o=!l&&r.id===n,s=uQ(r),u=hQ({session:r,activeProject:e,activeProjectBranchState:t}),d=vQ(r),f=i.has(r.id),p=!!d||f,h=m.has(r.id),g=r.agent_status===`running`?`running`:r.agent_status===`stopped`?`interrupted`:!o&&a.has(r.id)?`finished`:null,_=g===`interrupted`?null:g;return(0,Z.jsxs)(`div`,{"data-chat-session-id":r.id,"data-chat-session-selectable":p?`false`:`true`,className:K(`group relative rounded-xl border transition-colors`,o?`border-sky-400/40 bg-sky-500/10 text-foreground ring-1 ring-sky-400/40`:`border-border/50 bg-card/35 text-muted-foreground hover:border-border/80 hover:bg-card/60 hover:text-foreground`),onPointerDownCapture:e=>{!c||p||e.pointerType&&e.pointerType!==`mouse`||typeof e.button==`number`&&e.button!==0||(e.preventDefault(),A(),O.current=!0,D.current={pointerId:e.pointerId,mode:h?`deselect`:`select`,visitedSessionIds:new Set},N(r.id))},onPointerMove:e=>{let t=D.current;!t||t.pointerId!==e.pointerId||N(r.id)},children:[(0,Z.jsx)(`button`,{type:`button`,"aria-label":[r.title,PZ(r.mode),MZ(r.tool),e?.memory_enabled&&r.pending_memory_suggestion_count>0?IZ(r.pending_memory_suggestion_count):null,g===`running`?mZ(`sidebar.running`):g===`interrupted`?mZ(`sidebar.interrupted`):g===`finished`?mZ(`sidebar.finished`):null].filter(Boolean).join(` `),className:`flex w-full min-w-0 cursor-pointer items-start gap-2 rounded-xl px-3 py-2 pr-11 text-left transition-colors focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none`,onClick:()=>{if(c){if(O.current){O.current=!1;return}if(p)return;w(r.id);return}C(r)},children:(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[u?(0,Z.jsx)(`div`,{className:`mb-1 truncate text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground/75`,children:u}):null,(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`truncate text-[13px] font-medium leading-5`,children:r.title}),e?.memory_enabled&&r.pending_memory_suggestion_count>0?(0,Z.jsx)(qX,{tone:o?`default`:`muted`,className:`shrink-0`,"aria-label":IZ(r.pending_memory_suggestion_count),title:IZ(r.pending_memory_suggestion_count),children:r.pending_memory_suggestion_count}):null]}),s?(0,Z.jsx)(`div`,{className:K(`mt-0.5 line-clamp-1 text-xs leading-4`,o?`text-foreground/70`:`text-muted-foreground`),children:s}):null,r.target_available===!1?(0,Z.jsx)(`div`,{className:`mt-1 line-clamp-1 text-[11px] leading-4 text-amber-200/90`,children:r.target_unavailable_reason??mZ(`sidebar.targetUnavailable`)}):null]}),(0,Z.jsx)(Rl,{state:_,className:`mt-1`})]})}),c?(0,Z.jsx)(`div`,{className:`absolute top-2 right-2 flex h-7 w-7 items-center justify-center`,title:d??mZ(`sidebar.selectSessionTitle`,{title:r.title}),children:(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":mZ(`sidebar.selectSessionAriaLabel`,{title:r.title}),checked:h,disabled:p,onClick:e=>{e.stopPropagation()},onChange:()=>{O.current||w(r.id)},className:`h-4 w-4 rounded border-border bg-background text-primary`})}):(0,Z.jsx)(q,{type:`button`,size:`icon-sm`,variant:`ghost`,"aria-label":mZ(`sidebar.deleteSessionAriaLabel`),className:K(`absolute top-2 right-2 h-7 w-7 shrink-0 rounded-md border border-transparent text-muted-foreground transition-all duration-150 hover:border-border/70 hover:bg-card/80 hover:text-foreground focus-visible:border-border/70 focus-visible:bg-card/80 focus-visible:text-foreground`,`opacity-100 sm:opacity-0 sm:pointer-events-none sm:group-hover:pointer-events-auto sm:group-focus-within:pointer-events-auto sm:group-hover:opacity-100 sm:group-focus-within:opacity-100`,p&&`sm:disabled:opacity-0 sm:group-hover:disabled:opacity-50 sm:group-focus-within:disabled:opacity-50`,(o||f)&&`sm:pointer-events-auto sm:opacity-100 sm:disabled:opacity-50`,d&&`cursor-not-allowed text-muted-foreground/50 hover:border-transparent hover:bg-transparent hover:text-muted-foreground/50 focus-visible:border-transparent focus-visible:bg-transparent focus-visible:text-muted-foreground/50`),title:d??mZ(`sidebar.deleteSessionTitle`,{title:r.title}),disabled:p,onClick:e=>{e.stopPropagation(),v(r.id)},children:(0,Z.jsx)(wu,{className:`h-4 w-4`})})]},r.id)})]},r.key))})})]}):(0,Z.jsxs)(`div`,{"data-testid":`chat-sessions-rail`,className:`flex h-full w-full flex-col items-center gap-2 bg-background/80 py-3`,children:[(0,Z.jsx)(xc,{content:(0,Z.jsx)(UZ,{label:mZ(`shortcuts.startNewSession`),modifierLabel:r,keys:[TZ]}),side:`right`,children:(0,Z.jsx)(q,{type:`button`,size:`icon-sm`,"aria-label":mZ(`sidebar.newSession`),className:`h-9 w-9`,onClick:y,disabled:s||f,children:(0,Z.jsx)(zl,{className:`h-4 w-4`})})}),(0,Z.jsx)(q,{type:`button`,size:`icon-sm`,variant:`ghost`,"aria-label":mZ(`sidebar.openAriaLabel`),"aria-expanded":d,className:`h-9 w-9`,onClick:T,children:(0,Z.jsx)(DX,{className:`h-4 w-4`})})]})})},xQ=({proposals:e,isApplying:t,onApply:n})=>e.status===`applied`?(0,Z.jsxs)(`div`,{className:`w-full rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3 py-3 text-sm`,children:[(0,Z.jsx)(`div`,{className:`font-medium text-foreground`,children:mZ(`ticketProposal.createdTitle`)}),(0,Z.jsx)(`div`,{className:`mt-1 text-muted-foreground`,children:mZ(`ticketProposal.createdDescription`,{count:e.created_tickets.length})}),e.created_tickets.length>0?(0,Z.jsx)(`ul`,{className:`mt-3 space-y-1 text-foreground`,children:e.created_tickets.map(e=>(0,Z.jsx)(`li`,{children:e.title},e.ticket_id))}):null]}):(0,Z.jsxs)(`div`,{className:`w-full rounded-md border border-sky-500/30 bg-sky-500/10 px-3 py-3 text-sm`,children:[(0,Z.jsx)(`div`,{className:`font-medium text-foreground`,children:mZ(`ticketProposal.proposedTitle`)}),(0,Z.jsx)(`div`,{className:`mt-1 text-muted-foreground`,children:mZ(`ticketProposal.proposedDescription`)}),(0,Z.jsx)(`ul`,{className:`mt-3 space-y-3`,children:e.tickets.map(e=>(0,Z.jsxs)(`li`,{className:`rounded border border-border/60 bg-background/80 px-3 py-2`,children:[(0,Z.jsx)(`div`,{className:`font-medium text-foreground`,children:e.title}),(0,Z.jsx)(`div`,{className:`mt-1 whitespace-pre-wrap text-muted-foreground`,children:e.description})]},e.key))}),e.dependencies.length>0?(0,Z.jsx)(`div`,{className:`mt-3 text-muted-foreground`,children:mZ(`ticketProposal.dependenciesLabel`,{value:e.dependencies.map(e=>`${e.blocker_key} -> ${e.dependent_key}`).join(`, `)})}):null,(0,Z.jsx)(`div`,{className:`mt-3`,children:(0,Z.jsx)(q,{type:`button`,size:`sm`,onClick:n,disabled:t,children:mZ(t?`ticketProposal.creating`:`ticketProposal.create`)})})]}),SQ=({activeProjectId:e,activeProject:t,activeProjectBranchState:n=null,activeTool:r,onRestoreSessionTarget:i,onReviewCapabilityChange:a,isExternallyResizing:o=!1,showChangesPanel:s=!0})=>{let c=zY(),[l,u]=(0,Y.useState)([]),[d,f]=(0,Y.useState)(null),[p,m]=(0,Y.useState)(null),[h,g]=(0,Y.useState)(null),[_,v]=(0,Y.useState)(!1),[y,b]=(0,Y.useState)(()=>sQ({projectId:e,tool:r})),[x,S]=(0,Y.useState)({}),[C,w]=(0,Y.useState)({}),[T,E]=(0,Y.useState)({}),[D,O]=(0,Y.useState)([]),[k,A]=(0,Y.useState)([]),[j,M]=(0,Y.useState)(``),[N,P]=(0,Y.useState)(``),[F,I]=(0,Y.useState)([]),[L,R]=(0,Y.useState)(!1),[ee,te]=(0,Y.useState)(!1),[ne,re]=(0,Y.useState)(!1),[B,ie]=(0,Y.useState)(!1),[V,H]=(0,Y.useState)(!1),[ae,oe]=(0,Y.useState)(null),[se,ce]=(0,Y.useState)([]),[le,ue]=(0,Y.useState)(()=>new Set),[de,U]=(0,Y.useState)(!1),[fe,pe]=(0,Y.useState)(()=>new Set),[me,he]=(0,Y.useState)(!1),[G,ge]=(0,Y.useState)(!1),[_e,ve]=(0,Y.useState)(null),[ye,be]=(0,Y.useState)([]),[xe,Se]=(0,Y.useState)(!1),[Ce,we]=(0,Y.useState)(!1),[Te,Ee]=(0,Y.useState)(0),[De,Oe]=(0,Y.useState)(iZ),[ke,Ae]=(0,Y.useState)(()=>nQ(e).isOpen),[je,Me]=(0,Y.useState)(()=>tQ(e).isOpen),[Ne,Pe]=(0,Y.useState)(!1),[Fe,Ie]=(0,Y.useState)(!1),[Le,Re]=(0,Y.useState)(()=>tQ(e).width),[ze,Be]=(0,Y.useState)(0),[Ve,He]=(0,Y.useState)(null),[Ue,We]=(0,Y.useState)(()=>new Set),Ge=(0,Y.useRef)({model:``,variant:``,skills:[],showModelSelector:!1}),Ke=(0,Y.useRef)(!1),qe=(0,Y.useRef)(null),Ye=(0,Y.useRef)(0),Xe=(0,Y.useRef)(0),Ze=(0,Y.useRef)(null),Qe=(0,Y.useRef)(null),$e=(0,Y.useRef)(null),et=(0,Y.useRef)(null),J=(0,Y.useRef)(null),tt=(0,Y.useRef)(null),nt=(0,Y.useRef)(!1),rt=(0,Y.useRef)(!1),it=(0,Y.useRef)(0),at=(0,Y.useRef)(bZ),ot=(0,Y.useRef)(bZ),st=(0,Y.useRef)(!1),ct=(0,Y.useRef)(0),lt=(0,Y.useRef)({id:null,status:null}),ut=(0,Y.useRef)(new Map),dt=(0,Y.useRef)({}),ft=(0,Y.useRef)({}),pt=(0,Y.useRef)(new Set),mt=(0,Y.useRef)(!1),ht=e?XZ({projectId:e,tool:_?r:p?.tool??r,chatSessionId:_?null:d}):null,gt=ht?x[ht]??``:``,_t=_?r:p?.tool??r,vt=p?C[p.id]??[]:[],yt=(p?T[p.id]??0:0)>0;(0,Y.useEffect)(()=>{Ke.current=_},[_]),(0,Y.useEffect)(()=>{dt.current=x},[x]),(0,Y.useEffect)(()=>{ft.current=C},[C]),(0,Y.useEffect)(()=>{if(!ht||pt.current.has(ht))return;pt.current.add(ht);let e=$Z(ht);e&&S(t=>Object.prototype.hasOwnProperty.call(t,ht)?t:{...t,[ht]:e})},[ht]),(0,Y.useEffect)(()=>{!ht||!Object.prototype.hasOwnProperty.call(x,ht)||eQ({storageKey:ht,value:x[ht]??``})},[ht,x]),(0,Y.useEffect)(()=>{qe.current=d},[d]);let bt=(0,Y.useCallback)(()=>{Xe.current+=1},[]),X=(0,Y.useCallback)(e=>{bt(),m(e)},[bt]);(0,Y.useEffect)(()=>{if(!mt.current){mt.current=!0;return}let t=tQ(e),n=nQ(e);Ke.current=!1,st.current=!1,pt.current=new Set,f(null),X(null),v(!1),S({}),w({}),E({}),oe(null),ce([]),ue(new Set),U(!1),pe(new Set),He(null),be([]),we(!1),te(!1),Oe(iZ()),We(new Set),ut.current=new Map,ot.current=t.width,Ae(n.isOpen),Re(t.width),Me(t.isOpen)},[e,X]),(0,Y.useEffect)(()=>{Ne||(ot.current=Le,$e.current&&($e.current.style.setProperty(`--chat-changes-panel-width`,`${Le}px`),$e.current.setAttribute(`data-desktop-width`,String(Le))))},[Le,Ne]),(0,Y.useEffect)(()=>{if(!s||!Ze.current)return;let e=Ze.current.getBoundingClientRect().width;if(e<=0)return;let t=jZ(Le,e);t!==Le&&(ot.current=t,Re(t))},[Le,s]),(0,Y.useEffect)(()=>{iQ({projectId:e,isOpen:ke})},[e,ke]),(0,Y.useEffect)(()=>{s&&rQ({projectId:e,isOpen:je,width:Le})},[e,Le,je,s]),(0,Y.useEffect)(()=>{we(!1)},[d,_]);let xt=(0,Y.useCallback)(e=>{let t=pZ(e);u(e=>{let n=e.findIndex(e=>e.id===t.id);if(n===-1)return lZ([...e,t]);let r=[...e];return r[n]=t,lZ(r)})},[]),St=(0,Y.useCallback)(t=>{let n=Array.from(new Set(t));if(n.length===0)return;let i=new Set(n),a=qe.current,o=e?n.map(t=>XZ({projectId:e,tool:r,chatSessionId:t})):[];S(e=>{let t=o.filter(t=>Object.prototype.hasOwnProperty.call(e,t));if(t.length===0)return e;let n={...e};for(let e of t)delete n[e];return n}),w(e=>{let t={...e},r=!1;for(let e of n)Object.prototype.hasOwnProperty.call(t,e)&&(delete t[e],r=!0);return r?t:e}),E(e=>{let t={...e},r=!1;for(let e of n)Object.prototype.hasOwnProperty.call(t,e)&&(delete t[e],r=!0);return r?t:e});for(let e of o)eQ({storageKey:e,value:``});u(e=>{let t=e.filter(e=>!i.has(e.id));if(a&&i.has(a)){let e=t[0]??null;f(e?.id??null),X(null),v(e===null),be([]),Se(!1),we(!1)}return t}),We(e=>{let t=new Set(e),r=!1;for(let e of n)t.delete(e)&&(r=!0);return r?t:e}),He(e=>e?.sessionId&&i.has(e.sessionId)?null:e),oe(e=>e&&i.has(e)?null:e),ce(e=>e.filter(e=>!i.has(e))),ue(e=>{let t=new Set(e),r=!1;for(let e of n)t.delete(e)&&(r=!0);return r?t:e}),pe(e=>{let t=new Set(e),r=!1;for(let e of n)t.delete(e)&&(r=!0);return r?t:e})},[e,r,X]),Ct=(0,Y.useCallback)(e=>{St([e])},[St]),wt=(0,Y.useCallback)((e,t)=>{e&&S(n=>n[e]===t?n:{...n,[e]:t})},[]),Tt=(0,Y.useCallback)(e=>{e&&(S(t=>t[e]===``?t:{...t,[e]:``}),eQ({storageKey:e,value:``}))},[]),Et=(0,Y.useCallback)((e,t)=>{w(n=>{if(t.length===0){if(!Object.prototype.hasOwnProperty.call(n,e))return n;let t={...n};return delete t[e],t}return{...n,[e]:t}})},[]),Dt=(0,Y.useCallback)(e=>{w(t=>{if(!Object.prototype.hasOwnProperty.call(t,e))return t;let n={...t};return delete n[e],n}),E(t=>{if(!Object.prototype.hasOwnProperty.call(t,e))return t;let n={...t};return delete n[e],n})},[]),Ot=(0,Y.useCallback)((e,t)=>{E(n=>{let r=Math.max(0,(n[e]??0)+t);if(r===0){if(!Object.prototype.hasOwnProperty.call(n,e))return n;let t={...n};return delete t[e],t}return{...n,[e]:r}})},[]),kt=(0,Y.useCallback)(({fromStorageKey:e,toStorageKey:t})=>{if(!e||!t||e===t)return;let n=Object.prototype.hasOwnProperty.call(dt.current,e)?dt.current[e]??``:$Z(e);S(r=>{let i={...r,[t]:n};return delete i[e],i}),eQ({storageKey:t,value:n}),eQ({storageKey:e,value:``})},[]),At=(0,Y.useCallback)((e,t)=>{u(n=>{let r=n.findIndex(t=>t.id===e);if(r===-1)return n;let i=n[r];if(i.pending_memory_suggestion_count===t)return n;let a=[...n];return a[r]={...i,pending_memory_suggestion_count:t},a}),m(n=>!n||n.id!==e||n.pending_memory_suggestion_count===t?n:(Xe.current+=1,{...n,pending_memory_suggestion_count:t}))},[]),jt=(0,Y.useCallback)(async r=>{if(!e){u([]),f(null),X(null),v(!1),te(!1);return}R(!0);try{let i=await Zb(e,r);if(r?.aborted)return;let a=lZ(i.map(pZ)),o=a[0]??null,s=t?.active_target_kind===`bundle`||n?.status!==`loading`;u(a),f(e=>Ke.current?null:e&&a.some(t=>t.id===e)?e:e?a[0]?.id??null:st.current?null:o?s?(st.current=!0,mQ({activeProject:t,activeProjectBranchState:n,session:o})?o.id:null):null:(st.current=!0,null)),a.length===0&&v(!0)}catch(e){z(e)||Q.error(e instanceof Error?e.message:mZ(`errors.loadSessions`))}finally{r?.aborted||(R(!1),te(!0))}},[t,n,e,X]),Mt=(0,Y.useCallback)(async(t,n)=>{if(!e){X(null);return}re(!0);let r=Ye.current+1;Ye.current=r;let i=Xe.current;try{let a=await $b(e,t,n);if(n?.aborted)return;let o=Xe.current!==i,s=Ye.current===r,c=qe.current===t&&!Ke.current;if(!s||o||!c)return;X(a),xt(a)}catch(e){z(e)||Q.error(e instanceof Error?e.message:mZ(`errors.loadSession`))}finally{n?.aborted||re(!1)}},[e,X,xt]),Nt=(0,Y.useCallback)(async(n,r)=>{if(!e||!t?.memory_enabled){be([]),Se(!1);return}Se(!0);try{let t=await Je(e,null,r,n);if(r?.aborted)return;be(t.suggestions),At(n,t.suggestions.length)}catch(e){z(e)||Q.error(e instanceof Error?e.message:mZ(`errors.loadMemorySuggestions`))}finally{r?.aborted||Se(!1)}},[t?.memory_enabled,e,At]),Pt=(0,Y.useCallback)(()=>{be(e=>{let t=e.length>0?e.slice(0,-1):e;return d&&At(d,t.length),t}),Ee(e=>e+1),jt(),d&&Mt(d)},[d,Mt,jt,At]);(0,Y.useEffect)(()=>{let e=new AbortController;return jt(e.signal),()=>{e.abort()}},[jt]),(0,Y.useEffect)(()=>{if(Ke.current||_||d||st.current||l.length===0||t?.active_target_kind!==`bundle`&&n?.status===`loading`)return;st.current=!0;let e=l[0]??null;e&&mQ({activeProject:t,activeProjectBranchState:n,session:e})&&f(e.id)},[t,n,d,_,l]),(0,Y.useEffect)(()=>{if(_t!==`opencode`){O([]),A([]),ge(!1);return}let t=new AbortController;return(async()=>{ge(!0);try{let[n,r]=await Promise.all([wn(_t,t.signal),gw(_t,t.signal,e)]);O(n),A(r)}catch(e){z(e)||(O(e=>e),A(e=>e))}finally{t.signal.aborted||ge(!1)}})(),()=>{t.abort()}},[e,_t]),(0,Y.useEffect)(()=>{if(_||!d){X(null);return}if(p?.id===d)return;X(null);let e=new AbortController;return Mt(d,e.signal),()=>{e.abort()}},[p,d,_,Mt,X]),(0,Y.useEffect)(()=>{if(!t?.memory_enabled||_||!d){be([]),Se(!1);return}let e=new AbortController;return Nt(d,e.signal),()=>{e.abort()}},[t?.memory_enabled,d,_,Nt,Te]),(0,Y.useEffect)(()=>{!Ce||xe||ye.length>0||we(!1)},[xe,Ce,ye.length]),(0,Y.useEffect)(()=>{if(!d||p?.agent_status!==`running`)return;let e=new AbortController,t=window.setInterval(()=>{Promise.all([jt(e.signal),Mt(d,e.signal)])},hZ);return()=>{e.abort(),window.clearInterval(t)}},[p?.agent_status,d,Mt,jt]),(0,Y.useEffect)(()=>{if(!e)return;let t=t=>{!t||t.project_id!==e||(t.id===d&&X(t),pQ(t)&&xt(t))},n=t=>{!t||t.project_id!==e||Ct(t.id)};return c.on(`chat-session:created`,t),c.on(`chat-session:updated`,t),c.on(`chat-session:deleted`,n),()=>{c.off(`chat-session:created`,t),c.off(`chat-session:updated`,t),c.off(`chat-session:deleted`,n)}},[e,d,Ct,X,c,xt]),(0,Y.useEffect)(()=>{_&&b(sQ({projectId:e,tool:r}))},[e,r,_]),(0,Y.useEffect)(()=>{if(_t!==`opencode`){M(``),P(``),I([]);return}if(_){let n=cQ({activeProjectId:e,helperModel:t?.helper_model??null,helperVariant:t?.helper_variant??null,activeTool:_t,availableModels:D});M(n.model),P(n.variant),I([]);return}M(p?.model??t?.helper_model??``),P(p?.variant??t?.helper_variant??``),I(p?.skills??[])},[e,t?.helper_model,t?.helper_variant,p?.id,p?.model,p?.skills,p?.variant,D,_t,_]),(0,Y.useEffect)(()=>{let e=D.find(e=>e.id===j)??null;P(t=>e?e.variants.includes(t)?t:``:t)},[D,j]),(0,Y.useEffect)(()=>{if(_t!==`opencode`||!_||!j||N)return;let n=cQ({activeProjectId:e,helperModel:t?.helper_model??null,helperVariant:t?.helper_variant??null,activeTool:_t,availableModels:D});n.model===j&&n.variant&&P(n.variant)},[e,t?.helper_model,t?.helper_variant,_t,D,_,j,N]),(0,Y.useEffect)(()=>{if(!ae)return;let e=p?.id===ae?p:l.find(e=>e.id===ae)??null;(!e||e.agent_status!==`running`)&&oe(null)},[p,ae,l]),(0,Y.useEffect)(()=>{let e=lt.current,n=p?.id??null,r=p?.agent_status??null;e.id===n&&e.status===`running`&&r===`done`&&t?.memory_enabled&&n&&Ee(e=>e+1),lt.current={id:n,status:r}},[t?.memory_enabled,e,p?.agent_status,p?.id,p?.title]),(0,Y.useEffect)(()=>{d&&We(e=>{if(!e.has(d))return e;let t=new Set(e);return t.delete(d),t})},[d]),(0,Y.useEffect)(()=>{Ve&&Ve.sessionId!==d&&He(null)},[d,Ve]),(0,Y.useEffect)(()=>{let e=ut.current,t=new Map,n=[];for(let r of l){let i=e.get(r.id)??null,a=r.agent_status??null;i===`running`&&a===`done`&&r.id!==d&&n.push(r),t.set(r.id,a)}ut.current=t,We(e=>{let t=new Set(e),r=!1,i=new Set(l.map(e=>e.id));for(let e of t)i.has(e)||(t.delete(e),r=!0);for(let e of l){let i=e.agent_status??null,a=n.some(t=>t.id===e.id);if((e.id===d||i!==`done`)&&t.delete(e.id)){r=!0;continue}a&&!t.has(e.id)&&(t.add(e.id),r=!0)}return r?t:e})},[e,d,l]);let Ft=(0,Y.useMemo)(()=>new Map(D.map(e=>[e.id,e.label])),[D]),It=(0,Y.useMemo)(()=>fZ(l),[l]),Lt=(0,Y.useMemo)(()=>se.length===0?[]:se.flatMap(e=>{let t=l.find(t=>t.id===e)??(p?.id===e?p:null);return t?[t]:[]}),[p,se,l]),Rt=Lt.length===1?Lt[0]?.title??null:null;(0,Y.useEffect)(()=>{se.length>0&&Lt.length!==se.length&&ce(Lt.map(e=>e.id))},[se,Lt]),(0,Y.useEffect)(()=>{let e=new Set(l.filter(e=>!vQ(e)&&!le.has(e.id)).map(e=>e.id));pe(t=>{let n=new Set(Array.from(t).filter(t=>e.has(t)));return n.size===t.size?t:n})},[le,l]),(0,Y.useEffect)(()=>{!de||ke||(U(!1),pe(new Set))},[ke,de]);let zt=(0,Y.useMemo)(()=>p?WZ({modelLabel:NZ({availableModelsById:Ft,model:p.model}),tool:p.tool}):null,[p,Ft]),Bt=(0,Y.useMemo)(()=>p?(p.messages??[]).map(e=>({id:e.id,role:e.role,kind:e.kind,content:e.content,attachments:e.attachments??[],ticket_proposals:e.ticket_proposals??null,created_at:e.created_at,displayTitle:e.role===`assistant`?zt??MZ(p.tool):GZ()})):[],[p,zt]),Vt=p?.id&&p.agent_status===`running`&&Ve?.sessionId===p.id?Ve.turnKey:null,Ht=_t===`opencode`&&D.length>0,Ut=_t===`opencode`&&!Ht&&G;(0,Y.useEffect)(()=>{Ge.current={model:j,variant:N,skills:F,showModelSelector:Ht}},[j,F,N,Ht]);let Wt=(0,Y.useMemo)(()=>D.find(e=>e.id===j)??null,[D,j]),Gt=_?y:p?.mode??`build`,Kt=_?mZ(`composer.newChatTitle`):p?.title??mZ(`composer.chatTitle`),qt=_?r:p?.tool??r,Jt=(0,Y.useMemo)(()=>VZ(),[]),Yt=Ht?j||null:p?.model??null,Xt=qt===`opencode`,Zt=NZ({availableModelsById:Ft,model:Yt}),Qt=(0,Y.useMemo)(()=>{let e=p?.usage_snapshot_total_tokens??null;if(e===null)return null;let t=JZ({tool:qt,model:Yt,availableModels:D,fallbackContextWindow:p?.usage_snapshot_context_window??null});if(t===null)return null;let n=qZ({totalTokens:e,contextWindow:t});return n===null?null:`${KZ(e)} (${n}%)`},[p?.usage_snapshot_context_window,p?.usage_snapshot_total_tokens,D,Yt,qt]),$t=_?`draft:${e??`none`}:${r}`:p?.id,en=(0,Y.useCallback)(()=>{Ke.current=!0,v(!0),b(sQ({projectId:e,tool:r})),g(null),f(null),X(null),oe(null),U(!1),pe(new Set),He(null)},[e,r,X]),tn=(0,Y.useCallback)((e,t=null)=>{Ke.current=!1,v(!1),g(null),f(e),X(t)},[X]),nn=(0,Y.useCallback)(async()=>{if(!(!p||!i)){g(p.id);try{await i(p)}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.restoreTarget`))}finally{g(e=>e===p.id?null:e)}}},[p,i]),rn=!!(p&&p.target_available!==!1&&!_&&!mQ({activeProject:t,activeProjectBranchState:n,session:p})),an=rn&&p?mZ(`review.mismatchReason`,{sessionTarget:gQ(p),currentTarget:_Q({activeProject:t,activeProjectBranchState:n})}):null,on=rn&&h===null,sn=(0,Y.useCallback)(async r=>{g(r.id);let a=r;if(e)try{let t=await $b(e,r.id);a=t,xt(t)}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.loadSession`)),g(e=>e===r.id?null:e);return}if(a.target_available===!1){tn(a.id,a);return}if(!mQ({activeProject:t,activeProjectBranchState:n,session:a})&&i)try{if(!await i(a)){g(e=>e===a.id?null:e);return}}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.restoreTarget`)),g(e=>e===a.id?null:e);return}tn(a.id,a)},[t,n,e,i,tn,xt]),cn=(0,Y.useCallback)(()=>{Be(e=>e+1)},[]),ln=(0,Y.useCallback)(async t=>{if(_){let n=Ge.current;b(t),oQ({projectId:e,tool:r,model:n.showModelSelector&&n.model||null,variant:n.showModelSelector&&n.model&&n.variant||null,mode:t}),cn();return}if(!(!e||!p||p.mode===t||me)){he(!0);try{let n=await ex(e,p.id,{mode:t});oQ({projectId:e,tool:n.tool,model:n.model,variant:n.variant,mode:n.mode}),X(n),xt(n),cn()}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.updateMode`))}finally{he(!1)}}},[e,p,r,cn,_,me,X,xt]),un=(0,Y.useCallback)(async({instruction:t,attachments:n,targetSession:r})=>{if(!e)return null;let i=Ge.current;ct.current+=1;let a={sessionId:r.id,turnKey:`${r.id}:${ct.current}`};He(a);try{let a=await tx(e,r.id,{instruction:t,...n.length>0?{attachment_ids:n.map(e=>e.id)}:{},tool:r.tool,model:i.showModelSelector&&i.model||null,variant:i.showModelSelector&&i.model&&i.variant||null,skills:i.showModelSelector?i.skills:[]});return oQ({projectId:e,tool:a.tool,model:a.model,variant:a.variant,mode:a.mode}),Ke.current=!1,X(a),f(a.id),v(!1),xt(a),a}catch(e){throw He(e=>e?.turnKey===a.turnKey?null:e),e}},[e,X,xt]),dn=(0,Y.useCallback)(async({fromStorageKey:t})=>{if(!e)return null;let n=Ge.current,i=await Qb(e,{mode:Gt,tool:r,model:n.showModelSelector&&n.model||null,variant:n.showModelSelector&&n.model&&n.variant||null,skills:n.showModelSelector?n.skills:[]});Ke.current=!1,v(!1),f(i.id),X(i);let a=XZ({projectId:e,tool:i.tool,chatSessionId:i.id});return kt({fromStorageKey:t,toStorageKey:a}),{session:i,storageKey:a}},[e,r,Gt,kt,X]),fn=(0,Y.useCallback)(async t=>{if(!e||V||B||yt||p?.agent_status===`running`||p?.target_available===!1||on)return!1;let n=t.trim(),r=p?ft.current[p.id]??[]:[];if(!n&&r.length===0)return!1;H(!0);let i=null,a=p,o=e&&p?XZ({projectId:e,tool:p.tool,chatSessionId:p.id}):null,s=r;try{let t=p;if(!t){ie(!0);let e=await dn({fromStorageKey:ht});i=e?.session??null,t=i,o=e?.storageKey??null,s=i?ft.current[i.id]??[]:[]}if(!t)return!1;Tt(o??ht);let r=fQ({session:t,instruction:n,attachments:s,createdAt:new Date().toISOString()});X(r),f(r.id),xt(r);let a=await un({instruction:n,attachments:s,targetSession:t});return Tt(a&&e?XZ({projectId:e,tool:a.tool,chatSessionId:a.id}):o),a&&Dt(a.id),!0}catch(e){throw wt(o??ht,n),i?(X(i),f(i.id),v(!1),xt(i)):a&&(X(a),xt(a)),e}finally{ie(!1),H(!1)}},[e,p,Dt,Tt,dn,ht,B,V,yt,X,un,wt,on,xt]),pn=(0,Y.useCallback)(e=>{Ke.current=!0,v(!0),b(e),g(null),f(null),X(null),oe(null),He(null)},[X]),mn=(0,Y.useCallback)(async t=>{if(!e||t.length===0||_t!==`opencode`)return;let n=t.slice(0,kZ);if(n.length===0)return;let r=null,i=p;try{if(i||=(ie(!0),r=await dn({fromStorageKey:ht}),r?.session??null),!i)return;if((ft.current[i.id]??[]).length+n.length>kZ){Q.error(`You can attach up to 4 images per turn.`);return}Ot(i.id,1);let t=await nx(e,i.id,n),a=ft.current[i.id]??[];Et(i.id,[...a,...t.attachments])}catch(t){if(r&&!gt.trim())try{await ax(e,r.session.id),Ct(r.session.id),pn(r.session.mode)}catch{}Q.error(t instanceof Error?t.message:mZ(`errors.uploadAttachments`))}finally{i&&Ot(i.id,-1),ie(!1)}},[e,p,dn,gt,ht,Ot,pn,Ct,Et,_t]),hn=(0,Y.useCallback)(async t=>{if(!e||!p)return;let n=(ft.current[p.id]??[]).filter(e=>e.id!==t);try{await rx(e,p.id,t),Et(p.id,n),n.length===0&&!gt.trim()&&(p.messages?.length??0)===0&&(await ax(e,p.id),Ct(p.id),pn(p.mode))}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.removeAttachment`))}},[e,p,gt,pn,Ct,Et]),gn=(0,Y.useCallback)(e=>{if(_t!==`opencode`)return;let t=Array.from(e.clipboardData.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).map(e=>e.getAsFile()).filter(e=>e!==null);t.length!==0&&(e.preventDefault(),mn(t))},[_t,mn]),_n=(0,Y.useCallback)(async e=>{await fn(e)},[fn]),vn=!!(e&&(_||p&&p.target_available!==!1&&!on)),yn=p?.agent_status===`running`,bn=p?.agent_status===`stopped`,xn=yn&&ae===p?.id,Sn=vn&&!yn&&!V&&!B&&!yt,Cn=vn?p?.target_available===!1?p.target_unavailable_reason??mZ(`review.unavailableTarget`):on?an??mZ(`review.restoreTargetFallback`):yn?mZ(`review.waitTurn`):yt?mZ(`review.waitUpload`):B||V?mZ(`review.waitPrompt`):null:mZ(`review.missingTarget`),Tn=(0,Y.useCallback)(async()=>{if(!(!e||!p||p.agent_status!==`running`||xn)){oe(p.id);try{await ix(e,p.id)}catch(e){oe(e=>e===p.id?null:e),Q.error(e instanceof Error?e.message:mZ(`errors.interruptResponse`))}}},[e,p,xn]),En=(0,Y.useCallback)(async()=>{if(!e||se.length===0||le.size>0)return;let t=Array.from(new Set(se)),n=de||t.length>1;ue(new Set(t));let r=await Promise.allSettled(t.map(async t=>(await ax(e,t),t))),i=[],a=[];for(let[e,n]of r.entries()){if(n.status===`fulfilled`){i.push(n.value);continue}a.push({sessionId:t[e]??``,message:n.reason instanceof Error?n.reason.message:null})}if(i.length>0&&St(i),ue(new Set),a.length===0){ce([]),n&&(U(!1),pe(new Set),Q.success(mZ(`toasts.deleteSelectedSuccess`,{count:i.length})));return}let o=a.map(e=>e.sessionId);if(ce(o),n&&pe(new Set(o)),i.length>0){Q.error(mZ(`toasts.deleteSelectedPartial`,{count:i.length,deletedCount:i.length,failedCount:a.length}));return}Q.error(a[0]?.message??mZ(`errors.deleteSession`))},[e,se,le,de,St]),Dn=(0,Y.useMemo)(()=>l.some(e=>!vQ(e)),[l]),On=(0,Y.useCallback)((e,t)=>{pe(n=>{if(n.has(e)===t)return n;let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),kn=(0,Y.useMemo)(()=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(GX,{value:Gt,planInactiveTooltip:(0,Z.jsx)(UZ,{label:mZ(`shortcuts.switchToPlan`),modifierLabel:Jt,keys:[wZ]}),buildInactiveTooltip:(0,Z.jsx)(UZ,{label:mZ(`shortcuts.switchToBuild`),modifierLabel:Jt,keys:[wZ]}),disabled:me,onChange:e=>{ln(e)}}),yn?(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`outline`,className:`gap-2`,disabled:xn,onClick:()=>{Tn()},children:[xn?(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}):(0,Z.jsx)(Fc,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:mZ(xn?`review.interrupting`:`review.interrupt`)})]}):null]}),[Jt,Gt,Tn,ln,xn,yn,me]),An=(0,Y.useMemo)(()=>Ht?(0,Z.jsx)(CP,{model:j,variant:N,skills:F,showModelSelector:!0,showSkillsSelector:!0,availableModels:D,availableSkills:k,selectedModel:Wt,onModelChange:e=>{let t=D.find(t=>t.id===e)??null;M(e),P(e=>t&&t.variants.includes(e)?e:``)},onVariantChange:P,onSkillsChange:I,modelSelectId:`project-chat-model-selector`,variantSelectId:`project-chat-variant-selector`,skillsSelectId:`project-chat-skills-selector`,disabled:V||B||p?.agent_status===`running`}):Ut?(0,Z.jsx)(SP,{dataTestId:`chat-model-selector-skeleton`}):null,[p?.agent_status,D,k,B,V,Wt,j,F,N,Ht,Ut]);(0,Y.useEffect)(()=>{if(a)return()=>{a(null)}},[a]),(0,Y.useEffect)(()=>{if(a){if(!e||!vn){a(null);return}a({chatSessionId:p?.id??null,canSubmitReviewPrompt:Sn,reviewSubmitDisabledReason:Cn,mode:Gt,onModeChange:ln,isUpdatingMode:me,promptPlaceholder:FZ(Gt),promptComposerControls:kn,promptComposerInlineControls:An,submitPrompt:_n})}},[e,p,Sn,Gt,ln,_n,vn,me,a,kn,An,Cn]);let jn=async()=>{if(!(!gt.trim()&&vt.length===0||yt))try{if(!await fn(gt))return}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.sendPrompt`))}},Mn=e=>{e.key!==`Enter`||e.shiftKey||p?.agent_status===`running`||B||V||yt||(e.preventDefault(),jn())};(0,Y.useEffect)(()=>{let t=t=>{if(zZ(t)){if(!e||B||V)return;t.preventDefault(),en(),cn();return}RZ(t)&&(!e||!_&&!p||(t.preventDefault(),ln(LZ(Gt))))};return window.addEventListener(`keydown`,t),()=>{window.removeEventListener(`keydown`,t)}},[e,p,Gt,cn,en,ln,B,_,V]);let Nn=(0,Y.useCallback)(async t=>{if(!(!e||!p)){ve(t);try{let n=await cx(e,p.id,t);X(n.chatSession),xt(n.chatSession),Q.success(mZ(`ticketProposal.createdFromChat`,{count:n.created_tickets.length}))}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.createTickets`))}finally{ve(e=>e===t?null:e)}}},[e,p,X,xt]),Pn=(0,Y.useCallback)(e=>{if(!Ze.current)return;let t=Ze.current.getBoundingClientRect().width,n=jZ(e,t);ot.current=n,$e.current&&($e.current.style.setProperty(`--chat-changes-panel-width`,`${n}px`),$e.current.setAttribute(`data-desktop-width`,String(n)))},[]),Fn=(0,Y.useCallback)(()=>{tt.current?.(),tt.current=null},[]),In=(0,Y.useCallback)(e=>{let t=et.current,n=J.current,r=nt.current;if(t!==null){if(et.current=null,J.current=null,nt.current=!1,Pe(!1),Ie(!1),Fn(),e!==null&&typeof Qe.current?.hasPointerCapture==`function`&&Qe.current.hasPointerCapture(e)&&typeof Qe.current.releasePointerCapture==`function`&&Qe.current.releasePointerCapture(e),n===`collapsed`){if(!r)return;Re(ot.current),Me(!0);return}Re(ot.current)}},[Fn]),Ln=(0,Y.useCallback)((e,t)=>{if(et.current!==e)return;let n=t-it.current,r=at.current-n;if(J.current===`collapsed`){if(!nt.current&&r<CZ)return;nt.current||(nt.current=!0,rt.current=!0,Ie(!0),Pe(!0))}Pn(r)},[Pn]),Rn=(0,Y.useCallback)((e,t)=>{if(et.current===e){if(t!==null&&(J.current===`inline`||nt.current)){let e=t-it.current;Pn(at.current-e)}In(e)}},[In,Pn]),zn=(0,Y.useCallback)(e=>{if(!s)return;e.preventDefault(),et.current=e.pointerId,J.current=je?`inline`:`collapsed`,nt.current=!1,rt.current=!1,it.current=e.clientX,at.current=je?ot.current:0,Pe(je),Fn(),typeof e.currentTarget.setPointerCapture==`function`&&e.currentTarget.setPointerCapture(e.pointerId);let t=e=>{Ln(e.pointerId,e.clientX)},n=e=>{Rn(e.pointerId,e.clientX)},r=e=>{Rn(e.pointerId,e.clientX)};window.addEventListener(`pointermove`,t),window.addEventListener(`pointerup`,n),window.addEventListener(`pointercancel`,r),tt.current=()=>{window.removeEventListener(`pointermove`,t),window.removeEventListener(`pointerup`,n),window.removeEventListener(`pointercancel`,r)}},[Rn,Ln,je,s,Fn]),Bn=(0,Y.useCallback)(e=>{Ln(e.pointerId,e.clientX)},[Ln]),Vn=(0,Y.useCallback)(e=>{Rn(e.pointerId,e.clientX)},[Rn]),Hn=(0,Y.useCallback)(e=>{Rn(e.pointerId,e.clientX)},[Rn]),Un=(0,Y.useCallback)(e=>{et.current===e.pointerId&&In(e.pointerId)},[In]),Wn=(0,Y.useCallback)(()=>{if(rt.current){rt.current=!1;return}Me(!0)},[]),Gn=(0,Y.useCallback)(()=>{Me(!1)},[]),Kn=(0,Y.useCallback)(e=>{e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),Wn())},[Wn]);(0,Y.useEffect)(()=>{s||(et.current=null,J.current=null,nt.current=!1,rt.current=!1,Pe(!1),Ie(!1),Fn())},[s,Fn]),(0,Y.useEffect)(()=>()=>{Fn()},[Fn]);let qn=!!d,Jn=p?.target_available===!1,Yn=Jn?p?.target_unavailable_reason??mZ(`review.unavailableTarget`):null,Xn=_||!!(p&&p.target_available!==!1&&!on),Zn=!!(t?.memory_enabled&&p&&(ye.length>0||xe)),Qn=s&&(_||qn)&&!Jn&&!on,$n=Qn&&!je&&!Fe,er=Qn&&(je||Fe),tr=`${$t??`none`}:${Qn?`changes-enabled`:`changes-disabled`}:${er?`panel-visible`:`panel-hidden`}`,nr=p||_?(0,Z.jsx)(Z.Fragment,{children:(0,Z.jsx)(WX,{projectId:e,messages:p?Bt:[],internalLog:p?.agent_log??null,currentThinkingMessageId:p?.agent_message_id??null,previousThinkingLog:p?.previous_agent_log??null,previousThinkingMessageId:p?.previous_agent_message_id??null,pendingAgentTitle:zt,streamingResponse:p?.streaming_response??null,isRunning:p?.agent_status===`running`,isLoading:!_&&ne,canShowComposer:Xn,cardClassName:`border-t-0`,isExternallyResizing:o||Ne,pendingAgentRevealKey:Vt,pendingAgentRevealDelayMs:OZ,composerFocusNonce:ze,header:(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`h3`,{className:`truncate text-sm font-semibold text-foreground`,children:Kt}),(0,Z.jsxs)(`div`,{className:AZ,children:[_?null:(0,Z.jsx)(DT,{tool:p?.tool,className:`text-[11px]`}),Zt?(0,Z.jsx)(`p`,{children:Zt}):null,bn?(0,Z.jsx)(`div`,{className:`inline-flex items-center rounded-full border border-amber-500/30 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-100`,children:mZ(`sidebar.interrupted`)}):null,Qt?(0,Z.jsx)(`div`,{"data-testid":`chat-context-usage-badge`,className:`inline-flex items-center rounded-full border border-border/80 bg-muted/40 px-2 py-0.5 text-[11px] font-medium text-foreground`,children:Qt}):null]})]}),Zn?(0,Z.jsx)(q,{type:`button`,size:`xs`,variant:`outline`,className:`gap-2`,onClick:()=>we(!0),children:xe?mZ(`composer.loadingMemory`):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{children:mZ(`composer.memorySuggestions`)}),(0,Z.jsx)(qX,{children:ye.length})]})}):null]}),on&&an?(0,Z.jsx)(`div`,{className:`w-fit max-w-md rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-50`,children:(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`div`,{children:an}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`secondary`,onClick:()=>{nn()},children:mZ(`composer.switchBack`)}),(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,onClick:en,children:mZ(`composer.startNewSession`)})]})]})}):null,Jn&&Yn?(0,Z.jsx)(`div`,{className:`w-fit max-w-md rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-50`,children:Yn}):null]}),composerControls:kn,composerInlineControls:An,composerTheme:Gt,layoutKey:$t,scrollLayoutKey:tr,followUpPrompt:gt,draftAttachments:vt,followUpPlaceholder:FZ(Gt),emptyStateText:null,renderMessageFooter:e=>e.ticket_proposals?(0,Z.jsx)(xQ,{proposals:e.ticket_proposals,isApplying:_e===e.id,onApply:()=>{Nn(e.id)}}):null,isSendingFollowUp:V||B,isUploadingAttachments:yt,canAttachImages:Xt,followUpDisabledReason:Jn?Yn??void 0:p?.agent_status===`running`?mZ(`review.waitTurnShort`):yt?mZ(`review.waitUpload`):void 0,onFollowUpPromptChange:e=>{wt(ht,e)},onFollowUpKeyDown:Mn,onFollowUpPaste:gn,onUploadAttachments:e=>{mn(e)},onRemoveAttachment:e=>{hn(e)},onFollowUpSubmit:()=>{jn()}})}):qn?(0,Z.jsx)(`div`,{className:`flex flex-1 items-center justify-center px-6 text-sm text-muted-foreground`,children:mZ(`composer.loadingSession`)}):!ee||L?(0,Z.jsx)(`div`,{className:`flex flex-1 items-center justify-center px-6 text-sm text-muted-foreground`,children:mZ(`sidebar.loadingSessions`)}):(0,Z.jsx)(`div`,{className:`flex flex-1 items-center justify-center px-6`,children:(0,Z.jsxs)(gu,{className:`w-full max-w-lg border-dashed border-border/70 bg-card/40`,children:[(0,Z.jsxs)(_u,{children:[(0,Z.jsx)(vu,{children:mZ(`composer.noSessionSelectedTitle`)}),(0,Z.jsx)(yu,{children:mZ(`composer.noSessionSelectedDescription`)})]}),(0,Z.jsx)(xu,{children:(0,Z.jsx)(q,{type:`button`,onClick:en,disabled:!e||B||V,children:mZ(`composer.startNewSession`)})})]})}),rr=Qn?(0,Z.jsx)(`div`,{ref:Qe,"aria-label":mZ($n?`composer.openDiff`:`composer.resizeDiffPanel`),"aria-orientation":$n?void 0:`vertical`,className:K($n?`group flex h-8 w-full shrink-0 touch-none select-none items-center justify-center border-t border-border/70 bg-background/90 text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground xl:h-auto xl:w-7 xl:cursor-col-resize xl:border-l xl:border-t-0`:`group hidden w-5 shrink-0 cursor-col-resize touch-none select-none items-center justify-center border-l border-border/70 bg-background/80 transition-colors xl:flex`,Ne&&!$n&&`bg-background`),"data-testid":$n?`collapsed-changes-rail`:void 0,onLostPointerCapture:Un,onPointerCancel:Hn,onPointerDown:zn,onPointerMove:Bn,onPointerUp:Vn,onClick:$n?Wn:void 0,onKeyDown:$n?Kn:void 0,role:$n?`button`:`separator`,tabIndex:$n?0:void 0,children:$n?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`hidden h-full w-full items-center justify-center xl:flex`,children:(0,Z.jsxs)(`span`,{className:`relative flex h-full w-full items-center justify-center`,children:[(0,Z.jsx)(`span`,{className:`absolute top-1/2 left-1/2 flex -translate-x-1/2 -translate-y-[2.65rem] items-center justify-center text-sky-400/80 transition-colors group-hover:text-sky-300`,children:(0,Z.jsx)(jc,{className:`h-3 w-3 shrink-0`})}),(0,Z.jsx)(`span`,{className:`absolute top-1/2 left-1/2 h-14 w-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-muted-foreground/70 transition-colors group-hover:bg-sky-300/90`})]})}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-xs font-medium xl:hidden`,children:[(0,Z.jsx)(jc,{className:`h-3.5 w-3.5`}),(0,Z.jsx)(`span`,{children:mZ(`composer.diff`)})]})]}):(0,Z.jsx)(`div`,{className:K(`h-14 w-1.5 rounded-full transition-colors`,Ne?`bg-sky-300/90`:`bg-muted-foreground/70 group-hover:bg-sky-300/90`)})}):null,ir=Ce&&e&&t?.memory_enabled?(0,Z.jsx)(pu,{onClose:()=>we(!1),overlayClassName:`bg-background/45 p-4 backdrop-blur-sm`,panelClassName:`w-full max-w-3xl`,renderContent:({closeButton:t})=>(0,Z.jsxs)(gu,{size:`sm`,className:`max-h-[calc(100vh-2rem)] w-full gap-0 overflow-hidden border-border/80 bg-card/95 shadow-2xl`,children:[(0,Z.jsxs)(_u,{className:`border-b border-border/80 pb-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(vu,{children:mZ(`composer.memorySuggestionsTitle`)}),(0,Z.jsx)(yu,{children:mZ(`composer.memorySuggestionsDescription`)})]}),(0,Z.jsx)(bu,{children:t})]}),(0,Z.jsx)(xu,{className:`min-h-0 flex-1 overflow-y-auto pt-4`,children:(0,Z.jsx)(rZ,{projectId:e,suggestions:ye,emptyState:mZ(`composer.memorySuggestionsEmpty`),onSuggestionsChanged:Pt})})]}),closeButtonLabel:mZ(`composer.closeMemorySuggestions`)}):null,ar=Lt.length>0?(0,Z.jsx)(yQ,{count:Lt.length,title:Rt,isDeleting:le.size>0,onConfirm:()=>{En()},onCancel:()=>{le.size>0||ce([])}}):null;return(0,Z.jsxs)(`div`,{"data-testid":`chat-view-shell`,className:`relative flex min-h-0 flex-1 overflow-hidden border-t border-border/70`,children:[(0,Z.jsx)(bQ,{activeProject:t,activeProjectBranchState:n,activeSessionId:d,chatModeShortcutModifierLabel:Jt,deletingSessionIds:le,finishedBackgroundSessionIds:Ue,hasDeletableSessions:Dn,isCreatingSession:B||!e,isSelectionMode:de,isDraftOpen:_,isLoadingSessions:L,isOpen:ke,isSendingPrompt:V,selectedSessionCount:fe.size,selectedSessionIds:fe,sessionGroups:It,sessions:l,onConfirmDeleteSelectedSessions:()=>{ce(Array.from(fe))},onConfirmDeleteSession:e=>{ce([e])},onDraftOpen:en,onEnterSelectionMode:()=>{U(!0),pe(new Set)},onExitSelectionMode:()=>{U(!1),pe(new Set)},onSetSessionSelection:On,onSessionSelect:e=>{sn(e)},onToggleSessionSelection:e=>{pe(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},onToggleOpen:()=>{Ae(e=>!e)}}),(0,Z.jsxs)(`div`,{ref:Ze,className:`relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden xl:flex-row`,children:[(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:nr}),Qn?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(xc,{content:mZ(`composer.openDiff`),disabled:!$n,side:`left`,children:rr}),er?(0,Z.jsx)(UX,{projectId:e,chatSessionId:_?null:d,canSubmitReviewPrompt:Sn,reviewSubmitDisabledReason:Cn,onSubmitReviewPrompt:_n,state:De,onStateChange:Oe,isResizing:Ne,onClose:Gn,desktopWidth:Le,panelElementRef:$e}):null]}):null]}),ir,ar]})},CQ=({className:e})=>(0,Z.jsx)(xo,{"aria-hidden":`true`,className:e}),wQ=({activeProject:e})=>e?(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto px-6 py-6`,children:(0,Z.jsxs)(`div`,{className:`mx-auto flex w-full max-w-7xl flex-col gap-5`,children:[(0,Z.jsx)(`div`,{className:`border-b border-border/60 pb-4`,children:(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-[10px] font-semibold uppercase tracking-[0.24em] text-muted-foreground`,children:`Memory archive`}),(0,Z.jsx)(`h2`,{className:`text-xl font-semibold text-foreground`,children:e.name})]})}),(0,Z.jsx)(pp,{mode:`edit`,projectId:e.id,memoryEnabled:e.memory_enabled,persistedMemoryEnabled:e.memory_enabled,onMemoryEnabledChange:()=>{},showActivationControls:!1,archiveLayout:!0})]})}):(0,Z.jsx)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center text-sm text-muted-foreground`,children:`Select a project to view memory.`}),TQ=()=>({hasRunning:!1,hasFinishedUnseen:!1,hasErrorUnseen:!1}),EQ=()=>({board:TQ(),memory:TQ(),chat:TQ()}),DQ=(e,t)=>{let n=e[t];return!n.hasFinishedUnseen&&!n.hasErrorUnseen?e:{...e,[t]:{...n,hasFinishedUnseen:!1,hasErrorUnseen:!1}}},OQ=e=>({hasRunning:e.board.hasRunning||e.chat.hasRunning,hasFinishedUnseen:e.board.hasFinishedUnseen||e.chat.hasFinishedUnseen,hasErrorUnseen:e.board.hasErrorUnseen||e.chat.hasErrorUnseen}),kQ=e=>e.hasErrorUnseen?`error`:e.hasRunning?`running`:e.hasFinishedUnseen?`finished`:null,AQ=(e,t)=>t?null:kQ(e),jQ=320,MQ=.7,NQ=28,PQ=6,FQ=(e,t)=>{let n=Math.max(jQ,Math.round(t*MQ));return Math.max(jQ,Math.min(n,Math.round(e)))},IQ=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n===-1)return[...e,t];let r=e.slice();return r[n]=t,r},LQ=(e,t)=>{if(t.type===`reset`)return EQ();if(t.type===`mark-workspace-visible`)return DQ(e,t.workspace);let n=e[t.workspace],r={...n,hasRunning:t.activity.hasRunning,hasFinishedUnseen:t.visibleWorkspace===t.workspace?!1:n.hasFinishedUnseen||t.activity.didFinish,hasErrorUnseen:t.visibleWorkspace===t.workspace?!1:n.hasErrorUnseen||t.activity.didError};return n.hasRunning===r.hasRunning&&n.hasFinishedUnseen===r.hasFinishedUnseen&&n.hasErrorUnseen===r.hasErrorUnseen?e:{...e,[t.workspace]:r}},RQ=({activeProjectId:e,onActivity:t})=>{let{tickets:n}=qY(),r=(0,Y.useRef)(new Map);return(0,Y.useEffect)(()=>{r.current=new Map},[e]),(0,Y.useEffect)(()=>{let e=r.current,i=new Map,a=!1,o=!1;for(let t of n){let n=e.get(t.id)??null,r=t.agent_status??null;n===`running`&&r===`done`&&(a=!0),n===`running`&&r===`error`&&(o=!0),i.set(t.id,r)}r.current=i,t({hasRunning:n.some(e=>e.agent_status===`running`),didFinish:a,didError:o})},[t,n]),null},zQ=({activeProjectId:e,onActivity:t})=>{let n=zY(),[r,i]=(0,Y.useState)([]),a=(0,Y.useRef)(new Map);return(0,Y.useEffect)(()=>{if(!e)return;let t=new AbortController;return(async()=>{try{let n=await Zb(e,t.signal);if(t.signal.aborted)return;i(n)}catch(e){z(e)}})(),()=>{t.abort()}},[e,n]),(0,Y.useEffect)(()=>{if(!e)return;let t=new AbortController,n=aq(()=>{document.visibilityState===`visible`&&Zb(e,t.signal).then(e=>{t.signal.aborted||i(e)}).catch(e=>{z(e)})});return()=>{t.abort(),n()}},[e,n]),(0,Y.useEffect)(()=>{if(!e)return;let t=t=>{!t||t.project_id!==e||i(e=>IQ(e,t))},r=t=>{!t||t.project_id!==e||i(e=>e.filter(e=>e.id!==t.id))};return n.on(`chat-session:created`,t),n.on(`chat-session:updated`,t),n.on(`chat-session:deleted`,r),()=>{n.off(`chat-session:created`,t),n.off(`chat-session:updated`,t),n.off(`chat-session:deleted`,r)}},[e,n]),(0,Y.useEffect)(()=>{let n=a.current,i=new Map,o=[],s=!1;for(let e of r){let t=n.get(e.id)??null,r=e.agent_status??null;t===`running`&&r===`done`&&o.push(e),t===`running`&&r===`error`&&(s=!0),i.set(e.id,r)}a.current=i;for(let e of o)e.title&&LY(`Chat response ready`,e.title);o.length>0&&e&&nq(e),t({hasRunning:r.some(e=>e.agent_status===`running`),didFinish:o.length>0,didError:s})},[e,t,r]),null},BQ=({activeProjectId:e,activeProject:t=null,activeProjectBranchState:n=null,activeRun:r,activeTool:i,onRestoreChatSessionTarget:a,onChatReviewCapabilityChange:o,onPreviewReviewCapabilityChange:s,previewDisplayMode:c=`hidden`,previewPane:l=null,previewPaneWidth:u=480,isPreviewButtonDisabled:d=!1,previewButtonTitle:f,visibleWorkspace:p,onProjectUsageChange:m,onBundlesChange:h,onBundlesLoadingChange:g,onBoardLoadedProjectIdChange:_,onPreviewToggle:v,onPreviewPaneWidthChange:y,onRunStopped:b,onRunStatusChange:x,onWorkspaceActivityChange:S,onWorkspaceActivityEvent:C,refreshKey:w=0})=>{let T=(0,Y.useRef)(null),E=(0,Y.useRef)(null),D=(0,Y.useRef)(null),O=(0,Y.useRef)(null),k=(0,Y.useRef)(!1),A=(0,Y.useRef)(!1),j=(0,Y.useRef)(0),M=(0,Y.useRef)(u),N=(0,Y.useRef)(u),P=p===`board`||p===`chat`,F=l!==null,[I,L]=(0,Y.useState)(!1),[R,z]=(0,Y.useState)(!1),[ee,te]=(0,Y.useState)(u),[ne,re]=(0,Y.useReducer)(LQ,void 0,EQ),B=P&&F&&c===`expanded`,ie=P&&F&&c===`inline`,V=P&&F&&c===`hidden`&&!R,H=(ie||R)&&!B,ae=B||H,oe=P&&F&&!B,se=I?ee:u,ce=p!==`chat`||!H,le=e=>{let t=D.current,n=O.current,r=k.current;if(t!==null){if(D.current=null,O.current=null,k.current=!1,L(!1),z(!1),e!==null&&E.current?.hasPointerCapture(e)&&E.current.releasePointerCapture(e),n===`collapsed`){if(!r)return;y?.(N.current),v?.();return}y?.(N.current)}},ue=e=>{if(!T.current)return;let t=T.current.getBoundingClientRect().width,n=FQ(e,t);N.current=n,te(n)},de=e=>{y&&(V&&d||(e.preventDefault(),D.current=e.pointerId,O.current=V?`collapsed`:`inline`,k.current=!1,A.current=!1,j.current=e.clientX,M.current=V?0:N.current,L(!V),e.currentTarget.setPointerCapture(e.pointerId)))},U=e=>{if(D.current!==e.pointerId)return;let t=e.clientX-j.current,n=M.current-t;if(O.current===`collapsed`){if(!k.current&&n<PQ)return;k.current||(k.current=!0,A.current=!0,z(!0),L(!0))}ue(n)},fe=e=>{if(D.current===e.pointerId){if(O.current===`inline`||k.current){let t=e.clientX-j.current;ue(M.current-t)}le(e.pointerId)}},pe=e=>{D.current===e.pointerId&&le(e.pointerId)},me=(0,Y.useCallback)((e,t)=>{C?.(e,t),re({type:`update-workspace`,workspace:e,activity:t,visibleWorkspace:p})},[C,p]);(0,Y.useEffect)(()=>{re({type:`reset`})},[e]),(0,Y.useEffect)(()=>{p!==`memory`&&re({type:`mark-workspace-visible`,workspace:p})},[p]),(0,Y.useEffect)(()=>{S?.(ne)},[S,ne]),(0,Y.useEffect)(()=>{I||(N.current=u),!F&&(D.current=null,O.current=null,k.current=!1,A.current=!1,N.current=u)},[F,I,u]);let W=()=>{if(A.current){A.current=!1;return}d||v?.()};return(0,Z.jsx)(KY,{activeProjectId:e,refreshKey:w,onLoadedProjectIdChange:_,onProjectUsageChange:m,onBundlesChange:h,onBundlesLoadingChange:g,children:(0,Z.jsxs)(`div`,{ref:T,className:`flex min-h-0 flex-1 flex-col`,children:[(0,Z.jsx)(RQ,{activeProjectId:e,onActivity:e=>{me(`board`,e)}}),(0,Z.jsx)(zQ,{activeProjectId:e,onActivity:e=>{me(`chat`,e)}}),p===`memory`?(0,Z.jsx)(`div`,{id:`project-workspace-panel-memory`,role:`tabpanel`,"aria-labelledby":`project-workspace-tab-memory`,className:`flex min-h-0 flex-1 flex-col`,children:(0,Z.jsx)(wQ,{activeProject:t})}):(0,Z.jsxs)(`div`,{id:p===`chat`?`project-workspace-panel-chat`:`project-workspace-panel-board`,role:`tabpanel`,"aria-labelledby":p===`chat`?`project-workspace-tab-chat`:`project-workspace-tab-board`,className:`flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:[(0,Z.jsx)(`div`,{className:`flex min-h-0 min-w-0 flex-1 flex-col`,children:p===`chat`?(0,Z.jsx)(SQ,{activeProjectId:e,activeProject:t,activeProjectBranchState:n,activeTool:i,isExternallyResizing:I,onRestoreSessionTarget:a,onReviewCapabilityChange:o,showChangesPanel:ce}):(0,Z.jsx)(wX,{activeProjectId:e,activeProject:t,activeProjectBranchState:n,activeRun:r,activeTool:i,onPreviewReviewCapabilityChange:s,onRunStopped:b,onRunStatusChange:x,refreshKey:w})}),[oe?(0,Z.jsx)(xc,{content:d?f??`Preview unavailable`:`Open preview`,disabled:!V,side:`left`,children:(0,Z.jsx)(`div`,{"aria-label":V?f??`Show preview`:`Resize preview pane`,"aria-orientation":V?void 0:`vertical`,className:V?`group flex shrink-0 touch-none select-none items-center justify-center border-l border-border/70 bg-background/90 transition-colors ${d?`cursor-not-allowed text-muted-foreground/60`:`cursor-col-resize text-muted-foreground hover:bg-muted/50 hover:text-foreground`}`:`group flex w-5 shrink-0 cursor-col-resize touch-none select-none items-center justify-center border-l border-border/70 bg-background/80 ${I?`bg-background`:``}`,"data-preview-divider":`true`,"data-testid":V?`collapsed-preview-rail`:void 0,onLostPointerCapture:pe,onPointerCancel:fe,onPointerDown:de,onPointerMove:U,onPointerUp:fe,onClick:V?W:void 0,onKeyDown:V?e=>{e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),W())}:void 0,ref:E,role:V?`button`:`separator`,style:V?{width:`${NQ}px`}:void 0,tabIndex:V?d?-1:0:void 0,children:V?(0,Z.jsxs)(`span`,{className:`relative flex h-full w-full items-center justify-center`,children:[(0,Z.jsx)(`span`,{className:`absolute top-1/2 left-1/2 flex -translate-x-1/2 -translate-y-[2.65rem] items-center justify-center text-sky-400/80 transition-colors group-hover:text-sky-300`,children:(0,Z.jsx)(CQ,{className:`h-3 w-3 shrink-0`})}),(0,Z.jsx)(`span`,{className:`absolute top-1/2 left-1/2 h-14 w-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-muted-foreground/70 transition-colors group-hover:bg-sky-300/90`})]}):(0,Z.jsx)(`div`,{className:`h-14 w-1.5 rounded-full transition-colors ${I?`bg-sky-300/90`:`bg-muted-foreground/70 group-hover:bg-sky-300/90`}`})})},`preview-divider`):null,ae?(0,Z.jsx)(`div`,{className:B?`fixed inset-0 z-50 bg-black/70 p-4 sm:p-6`:`min-h-0 shrink-0 border-l border-border/70 bg-[#11131a]`,style:B?void 0:{width:`${se}px`},children:(0,Z.jsx)(`div`,{className:`h-full w-full`,children:l})},`preview-container`):null]]})]})})},VQ=({isExpanded:e,isVisible:t,project:n,onClose:r,onToggleExpanded:i})=>(0,Z.jsx)(`div`,{className:[`fixed inset-x-4 bottom-24 z-40`,e?`top-20`:`h-[min(28rem,calc(100vh-8rem))]`,t?`block`:`hidden`].join(` `),children:(0,Z.jsx)(KW,{createSession:()=>CT(n.id),isExpanded:e,isVisible:t,ariaLabel:`Project terminal for ${n.name}`,title:n.name,closeLabel:`Close terminal`,className:e?`h-full w-full rounded-2xl shadow-2xl`:`mx-auto h-full max-w-6xl shadow-2xl`,onClose:r,onToggleExpanded:i})}),HQ=({activeWorkspace:e,activityByWorkspace:t,memoryEnabled:n=!1,onWorkspaceChange:r})=>(0,Z.jsx)(`div`,{role:`tablist`,"aria-label":`Project workspace`,className:`inline-flex items-end gap-1 border-b border-border/70`,children:(n?[`board`,`chat`,`memory`]:[`board`,`chat`]).map(n=>{let i=e===n,a=AQ(t[n],i),o=n===`board`?`border-sky-300/70 bg-sky-500/8 text-sky-200`:n===`memory`?`border-amber-300/70 bg-amber-500/8 text-amber-200`:`border-emerald-300/70 bg-emerald-500/8 text-emerald-200`;return(0,Z.jsx)(`button`,{id:`project-workspace-tab-${n}`,type:`button`,role:`tab`,"aria-selected":i,"aria-controls":`project-workspace-panel-${n}`,tabIndex:i?0:-1,className:K(`cursor-pointer rounded-t-lg border-b-2 px-4 py-2.5 text-[15px] font-medium transition-colors duration-150 ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60`,i?o:`border-transparent text-muted-foreground hover:border-border hover:bg-background/35 hover:text-foreground`),onClick:()=>r(n),children:(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{children:n===`board`?`Board`:n===`memory`?`Memory`:`Chat`}),(0,Z.jsx)(Rl,{state:a,className:`mt-0`})]})},n)})}),UQ=32,WQ=5.5,GQ=2,KQ=24,qQ=8,JQ=new Map,YQ={running:{fill:`#fcd34d`,stroke:`#f59e0b`},finished:{fill:`#34d399`,stroke:`#059669`},error:{fill:`#fb7185`,stroke:`#e11d48`}},XQ=e=>e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`).replaceAll(`>`,`>`),ZQ=e=>{if(!e)return null;let t=e.trim().match(/^([0-9]+(?:\.[0-9]+)?)/);return t?Number(t[1]):null},QQ=e=>{let t=new DOMParser().parseFromString(e,`image/svg+xml`);if(t.querySelector(`parsererror`))return null;let n=t.documentElement;if(n.nodeName.toLowerCase()!==`svg`)return null;let r=n.getAttribute(`viewBox`)?.trim(),i=ZQ(n.getAttribute(`width`)),a=ZQ(n.getAttribute(`height`)),o=r??(i&&a?`0 0 ${i} ${a}`:`0 0 ${UQ} ${UQ}`);return`<svg ${[Array.from(n.attributes).filter(e=>![`width`,`height`,`viewBox`,`x`,`y`,`preserveAspectRatio`].includes(e.name)).map(e=>`${e.name}="${XQ(e.value)}"`).join(` `),`x="0"`,`y="0"`,`width="${UQ}"`,`height="${UQ}"`,`viewBox="${XQ(o)}"`,`preserveAspectRatio="xMidYMid meet"`].filter(e=>e.length>0).join(` `)}>${n.innerHTML}</svg>`},$Q=async e=>{if(!e)return null;let t=JQ.get(e);if(t)return t;let n=(async()=>{try{if(e.startsWith(`data:image/svg+xml,`))return QQ(decodeURIComponent(e.slice(19)));if(e.startsWith(`data:image/svg+xml;base64,`))return QQ(atob(e.slice(26)));let t=await fetch(e);return t.ok?QQ(await t.text()):null}catch{return null}})();return JQ.set(e,n),n},e$=async(e,t)=>{let{fill:n,stroke:r}=YQ[e],i=await $Q(t);return i?[`<svg xmlns="http://www.w3.org/2000/svg" width="${UQ}" height="${UQ}" viewBox="0 0 ${UQ} ${UQ}">`,i,`<circle cx="${KQ}" cy="${qQ}" r="${WQ}" fill="${n}" stroke="${r}" stroke-width="${GQ}"/>`,`</svg>`].join(``):null},t$=async(e,t)=>{if(!e)return t;let n=await e$(e,t);return n?`data:image/svg+xml,${encodeURIComponent(n)}`:t},n$=()=>{let e=document.querySelector(`link[rel="icon"]`);if(e)return e;let t=document.createElement(`link`);return t.rel=`icon`,document.head.appendChild(t),t},r$=({defaultHref:e,state:t})=>{let n=n$(),r=Number(n.dataset.browserTabActivityRequestId??`0`)+1;if(n.dataset.browserTabActivityState=t??`default`,n.dataset.browserTabActivityRequestId=String(r),!t){if(e){n.href=e;return}n.removeAttribute(`href`);return}t$(t,e).then(e=>{if(n.dataset.browserTabActivityRequestId===String(r)){if(e){n.href=e;return}n.removeAttribute(`href`)}})},i$=(e,t)=>Pe.t(`common:projectFooter.${e}`,t),a$=1e3,o$=`archon.active-project-id`,s$=`archon.workspace-by-project`,c$=`archon.preview-mode-by-project`,l$=`archon.dismissed-preview-run-context-by-project`,u$=5e3,d$=`archon.preview-pane-width`,f$=`archon.preview-viewport-preset`,p$=`archon.preview-zoom`,m$=480,h$=`responsive`,g$=1,_$={hasMounted:!1,isOpen:!1,isExpanded:!1},v$=`hidden`,y$=(0,Y.lazy)(()=>tG(()=>Promise.resolve().then(()=>fJ).then(e=>({default:e.TicketChangesModal})),void 0)),b$=(0,Y.lazy)(()=>tG(()=>import(`./TestsDialog-ditcW5bX.js`).then(e=>({default:e.TestsDialog})),__vite__mapDeps([0,1,2]))),x$=e=>{if(!e)return null;try{return JSON.parse(e)}catch{return null}},S$=e=>{let t=x$(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(e=>e.length>0):[]},C$=e=>{let t=x$(e);return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e,n=typeof t.name==`string`?t.name:``,r=typeof t.cmd==`string`?t.cmd:``,i=typeof t.cwd==`string`?t.cwd:``;return n.trim()===``&&r.trim()===``&&i.trim()===``?[]:[{name:n,cmd:r,cwd:i}]}):[]},w$=e=>{let t=x$(e);return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e,n=typeof t.source==`string`?t.source:``,r=typeof t.target==`string`?t.target:``,i=t.mode===`copy`||t.mode===`symlink`?t.mode:`copy`;return n.trim()===``&&r.trim()===``?[]:[{source:n,target:r,mode:i}]}):[]},T$=e=>({name:e.name,repoPath:e.repo_path,linkedProjectIds:e.linked_project_ids,runSetup:S$(e.run_setup),runServices:C$(e.run_services),testCommands:xY(e.test_commands),runIde:e.run_ide??``,previewServiceName:e.preview_service_name??``,previewPath:e.preview_path??``,previewCapabilityMode:e.preview_capability_mode??`auto`,helperModel:e.helper_model??``,helperVariant:e.helper_variant??``,commitMessageRules:e.commit_message_rules??``,autoParkStaleTickets:e.auto_park_stale_tickets,memoryEnabled:e.memory_enabled,worktreeSync:w$(e.worktree_sync)}),E$=e=>{let t=e.testCommands??[],n=e.previewServiceName?.trim()||null,r=e.previewPath?.trim()||``,i=r===``||r===`/`?null:r,a=n||i||e.previewCapabilityMode===`force_web`||e.previewCapabilityMode===`force_disabled`?e.previewCapabilityMode??`auto`:null;return{name:e.name,repo_path:e.repoPath,linked_project_ids:e.linkedProjectIds,run_setup:e.runSetup.length>0?e.runSetup:null,run_services:e.runServices.length>0?e.runServices.map(e=>({...e.name?{name:e.name}:{},cmd:e.cmd,...e.cwd?{cwd:e.cwd}:{}})):null,...t.length>0?{test_commands:t.map(e=>({id:e.id,name:e.name,command:e.command,runner:e.runner,...e.cwd?{cwd:e.cwd}:{}}))}:{},run_ide:e.runIde||null,preview_service_name:n,preview_path:i,preview_capability_mode:a,helper_model:e.helperModel||null,helper_variant:e.helperModel&&e.helperVariant||null,commit_message_rules:e.commitMessageRules||null,auto_park_stale_tickets:e.autoParkStaleTickets,memory_enabled:e.memoryEnabled,worktree_sync:e.worktreeSync.length>0?e.worktreeSync.map(e=>({source:e.source,...e.target?{target:e.target}:{},mode:e.mode})):null}},D$=e=>e?S$(e.run_setup).length>0||C$(e.run_services).length>0||(e.run_ide?.trim().length??0)>0:!1,O$=(e,t,n)=>`${e} ${e===1?t:n}`,k$=e=>{if(!e.repo_path_locked)return null;let t=[];return e.ticket_count>0&&t.push(O$(e.ticket_count,`ticket is attached`,`tickets are attached`)),e.worktree_count>0&&t.push(O$(e.worktree_count,`worktree exists`,`worktrees exist`)),t.length===0?`Repository path is locked for this project.`:`Repository path is locked because ${t.join(` and `)}.`},A$=(e,t)=>{if(t.length<=1)return`Keep at least one project in Archon.`;let n=[];e.ticket_count>0&&n.push(O$(e.ticket_count,`ticket is attached`,`tickets are attached`)),e.worktree_count>0&&n.push(O$(e.worktree_count,`worktree exists`,`worktrees exist`));let r=t.filter(t=>t.linked_project_ids.includes(e.id)).length;return r>0&&n.push(O$(r,`project links to it`,`projects link to it`)),n.length===0?null:`This project can't be deleted while ${n.join(` and `)}.`},j$=(e,t)=>e.id!==t.projectId||e.ticket_count===t.ticketCount&&e.worktree_count===t.worktreeCount&&e.repo_path_locked===t.repoPathLocked?e:{...e,ticket_count:t.ticketCount,worktree_count:t.worktreeCount,repo_path_locked:t.repoPathLocked},M$=(e,t)=>({projectId:e,branch:t.branch,status:t.status,ahead:t.ahead??0,behind:t.behind??0,hasUpstream:t.has_upstream??!1,canPull:t.can_pull??!1,diffStats:t.diff_stats??null}),N$=e=>({projectId:e,branch:null,status:`loading`,ahead:0,behind:0,hasUpstream:!1,canPull:!1,diffStats:null}),P$=(e,t)=>t?e[t]??_$:_$,F$=(e,t)=>t?e[t]??v$:v$,I$=()=>{let e=window.localStorage.getItem(d$),t=Number(e);return Number.isFinite(t)&&t>=320?t:m$},L$=()=>{let e=window.localStorage.getItem(f$);return e===`phone`||e===`tablet`||e===`laptop`||e===`responsive`?e:h$},R$=()=>{let e=Number(window.localStorage.getItem(p$));return Number.isFinite(e)&&e>0?e:g$},z$=()=>{let e=x$(window.localStorage.getItem(s$));return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>e===`board`||e===`chat`||e===`memory`))},B$=()=>{let e=x$(window.localStorage.getItem(c$));return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>e===`hidden`||e===`inline`||e===`expanded`))},V$=()=>{let e=x$(window.localStorage.getItem(l$));return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>typeof e==`string`||e===null))},H$=e=>!!e?.preview_service_name?.trim()&&e?.preview_capability_mode!==`force_disabled`,U$=({activeRun:e,project:t})=>{if(!e||e.kind!==`project`||!t)return!1;let n=t.active_target_kind??`repo_root`,r=t.active_target_bundle_id??null;return e.project_id===t.id&&(e.target_kind??`repo_root`)===n&&((e.target_kind??`repo_root`)!==`bundle`||e.target_bundle_id===r)},W$=({activeRun:e,project:t,projectId:n})=>!e||!n?null:e.kind===`ticket`?e.project_id===n?e:null:U$({activeRun:e,project:t})?e:null,G$=`Project root has uncommitted changes. Confirm branch switch to continue.`,K$=({activeProject:e,activeProjectBranchState:t,nextTarget:n})=>e?n.kind===`bundle`?e.active_target_kind!==`bundle`||e.active_target_bundle_id!==n.bundleId:e.active_target_kind===`bundle`?!0:n.branch?t?.branch!==n.branch:!1:!1,q$=()=>{let[e,t]=(0,Y.useState)(`opencode`),[n,r]=(0,Y.useState)(!1),[i,o]=(0,Y.useState)([]),[c,l]=(0,Y.useState)(()=>window.localStorage.getItem(o$)),[u,f]=(0,Y.useState)(null),[p,m]=(0,Y.useState)(null),[h,g]=(0,Y.useState)(null),[_,y]=(0,Y.useState)({}),[b,x]=(0,Y.useState)({}),[S,C]=(0,Y.useState)({}),[w,T]=(0,Y.useState)({}),[E,D]=(0,Y.useState)({}),[O,k]=(0,Y.useState)(B$),[A,j]=(0,Y.useState)(V$),[M,N]=(0,Y.useState)(I$),[F,R]=(0,Y.useState)(L$),[ee,te]=(0,Y.useState)(R$),[ne,re]=(0,Y.useState)(null),[B,ie]=(0,Y.useState)([]),[V,H]=(0,Y.useState)(!1),[ae,oe]=(0,Y.useState)(``),[le,ue]=(0,Y.useState)(``),[de,U]=(0,Y.useState)(!1),[fe,pe]=(0,Y.useState)(null),[W,he]=(0,Y.useState)(null),[G,_e]=(0,Y.useState)(null),[ve,ye]=(0,Y.useState)(!1),[be,xe]=(0,Y.useState)({}),[K,Se]=(0,Y.useState)(z$),[Ce,we]=(0,Y.useState)(()=>EQ()),[Te,De]=(0,Y.useState)(()=>TQ()),[Oe,ke]=(0,Y.useState)(0),[Ae,q]=(0,Y.useState)(null),[Me,Pe]=(0,Y.useState)(null),[Fe,Ie]=(0,Y.useState)({}),[Le,Re]=(0,Y.useState)({}),[ze,Be]=(0,Y.useState)({}),[Ve,Ue]=(0,Y.useState)({}),[We,Ge]=(0,Y.useState)(!1),[Ke,qe]=(0,Y.useState)(!1),[Je,Ye]=(0,Y.useState)(null),Xe=(0,Y.useRef)(null),Ze=(0,Y.useRef)(null),$e=(0,Y.useRef)(null),J=i.find(e=>e.id===c)??null,tt=!!J?.memory_enabled,nt=c?K[c]??`board`:`board`,rt=nt===`memory`?tt?`memory`:`board`:nt,it=J!==null,at=D$(J),ot=!!J?.run_ide?.trim(),st=c!==null&&p===c,ct=c!==null&&(!at||h===c),lt=c?_[c]??N$(c):null,ut=c?b[c]??null:null,dt=c?!!S[c]:!1,ft=c?w[c]??null:null,pt=c?Fe[c]??[]:[],mt=c?!!Le[c]:!1,ht=c?ze[c]??{current_branch:null,default_branch:null,previous_branch:null}:{current_branch:null,default_branch:null,previous_branch:null},gt=c?!!Ve[c]:!1,_t=c?E[c]??null:null,vt=F$(O,c),yt=vt!==`hidden`,bt=W$({activeRun:u,project:J,projectId:c}),X=bt?.context_key??null,xt=c?A[c]??null:null,St=H$(J),Ct=X===ne,wt=(0,Y.useMemo)(()=>OQ(Ce),[Ce]),Tt=(0,Y.useMemo)(()=>kQ({hasRunning:wt.hasRunning,hasFinishedUnseen:Te.hasFinishedUnseen,hasErrorUnseen:Te.hasErrorUnseen}),[wt.hasRunning,Te.hasErrorUnseen,Te.hasFinishedUnseen]);(0,Y.useEffect)(()=>{q(null),Pe(null),Ze.current=null},[c]),(0,Y.useEffect)(()=>{Pe(null)},[rt]),(0,Y.useEffect)(()=>{yt||(Ze.current=null)},[yt]),(0,Y.useEffect)(()=>{let e=Ae?.target?.kind??null;if(e===`ticket`||e===`bundle`){Ze.current=Ae;return}(rt===`board`||!yt)&&(Ze.current=Ae)},[yt,Ae,rt]),(0,Y.useEffect)(()=>{we(EQ())},[c]),(0,Y.useEffect)(()=>{De(TQ())},[c]);let Dt=(0,Y.useCallback)((e,t)=>{document.visibilityState!==`visible`&&(!t.didFinish&&!t.didError||De(e=>{let n={...e,hasFinishedUnseen:e.hasFinishedUnseen||t.didFinish,hasErrorUnseen:e.hasErrorUnseen||t.didError};return e.hasFinishedUnseen===n.hasFinishedUnseen&&e.hasErrorUnseen===n.hasErrorUnseen?e:n}))},[]);(0,Y.useEffect)(()=>{let e=()=>{document.visibilityState===`visible`&&De(e=>!e.hasFinishedUnseen&&!e.hasErrorUnseen?e:{...e,hasFinishedUnseen:!1,hasErrorUnseen:!1})};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[]),(0,Y.useEffect)(()=>(Xe.current===null&&(Xe.current=document.querySelector(`link[rel="icon"]`)?.getAttribute(`href`)??`/favicon.svg`),r$({defaultHref:Xe.current,state:Tt}),()=>{r$({defaultHref:Xe.current,state:null})}),[Tt]);let Ot=(0,Y.useCallback)(async(e,t={})=>{let{refreshRemote:n=!1,signal:r}=t;try{let t=await He(e,r,{refreshRemote:n});if(r?.aborted)return;y(n=>({...n,[e]:M$(e,t)}))}catch(t){if(z(t))return;if(t instanceof I&&t.status===404){y(t=>({...t,[e]:{...N$(e),status:`unknown`}}));return}y(t=>({...t,[e]:{projectId:e,branch:t[e]?.branch??null,status:`unknown`,ahead:t[e]?.ahead??0,behind:t[e]?.behind??0,hasUpstream:t[e]?.hasUpstream??!1,canPull:t[e]?.canPull??!1,diffStats:t[e]?.diffStats??null}}))}},[]),kt=(0,Y.useCallback)(async(e,t={})=>{let{refreshRemote:n=!1,signal:r,suppressLoading:i=!1}=t;i||C(t=>({...t,[e]:!0}));try{let t=await ge(e,{refreshRemote:n,signal:r});if(r?.aborted)return;x(n=>({...n,[e]:t}))}catch(t){if(z(t))return;t instanceof I&&t.status===404&&x(t=>({...t,[e]:null}))}finally{!r?.aborted&&!i&&C(t=>({...t,[e]:!1}))}},[]),At=(0,Y.useCallback)((e,t)=>{T(n=>({...n,[e]:t}))},[]),jt=(0,Y.useCallback)(async(e,t)=>{x(n=>({...n,[e.id]:t})),e.active_target_kind!==`bundle`&&await Ot(e.id),nq(e.id)},[Ot]);(0,Y.useEffect)(()=>{let e=new AbortController;return(async()=>{try{let{tool:n}=await Tn(e.signal);t(n)}catch(e){z(e)}finally{e.signal.aborted||r(!0)}})(),()=>{e.abort()}},[]),(0,Y.useEffect)(()=>{if(!de||i.length>0&&fe===null||V)return;let e=new AbortController;return(async()=>{try{ie(await wn(`opencode`,e.signal))}catch(e){z(e)||ie(e=>e)}finally{e.signal.aborted||H(!0)}})(),()=>{e.abort()}},[V,fe,i.length,de]),(0,Y.useEffect)(()=>{let e=new AbortController,t=window.localStorage.getItem(o$);return(async()=>{try{let n=await et(e.signal);if(e.signal.aborted)return;o(n);let r=n[0]?.id??null;l(n.some(e=>e.id===t)?t:r)}catch(e){z(e)||o([])}finally{e.signal.aborted||U(!0)}})(),()=>{e.abort()}},[]),(0,Y.useEffect)(()=>{if(de){if(c){window.localStorage.setItem(o$,c);return}window.localStorage.removeItem(o$)}},[c,de]),(0,Y.useEffect)(()=>{window.localStorage.setItem(s$,JSON.stringify(K))},[K]),(0,Y.useEffect)(()=>{window.localStorage.setItem(c$,JSON.stringify(O))},[O]),(0,Y.useEffect)(()=>{window.localStorage.setItem(l$,JSON.stringify(A))},[A]),(0,Y.useEffect)(()=>{y(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)}),x(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)}),C(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)})},[i]),(0,Y.useEffect)(()=>{xe(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)})},[i]),(0,Y.useEffect)(()=>{let e=new Set(i.map(e=>e.id));Ie(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(t)))),Re(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(t)))),Be(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(t)))),Ue(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(t))))},[i]),(0,Y.useEffect)(()=>{de&&(D(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)}),k(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)}),j(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)}))},[i,de]),(0,Y.useEffect)(()=>{de&&Se(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)})},[i,de]),(0,Y.useEffect)(()=>{if(!de||!c||!it)return;let e=!1,t=null,n=null;y(e=>e[c]?e:{...e,[c]:N$(c)});let r=async(r=!1)=>{let i=r?`remote`:`local`;if(t){if(n===`remote`||n===i)return;t.abort()}let a=new AbortController;t=a,n=i;try{await Promise.all([Ot(c,{refreshRemote:r,signal:a.signal}),kt(c,{refreshRemote:r,signal:a.signal})])}catch{if(e||a.signal.aborted)return}finally{t===a&&(t=null,n=null)}};r(!1);let i=aq(()=>{document.visibilityState===`visible`&&r(!1)});return()=>{e=!0,t?.abort(),i()}},[c,it,de,Ot,kt]),(0,Y.useEffect)(()=>{if(c)return rq(e=>{e===c&&(Ot(e),kt(e))})},[c,Ot,kt]),(0,Y.useEffect)(()=>{if(!c||!it)return;let e=ut?.operation_state??`idle`;if(!(ft===`rebase`||e!==`idle`))return;let t=!1,n=null,r=null,i=async()=>{r?.abort(),r=new AbortController;try{await kt(c,{signal:r.signal,suppressLoading:!0})}catch{}finally{t||(n=window.setTimeout(()=>{i()},a$))}};return i(),()=>{t=!0,r?.abort(),n!==null&&window.clearTimeout(n)}},[ft,c,ut?.operation_state,it,kt]);let Mt=(0,Y.useCallback)(async e=>{let t=c;if(!t){f(null),g(null);return}try{let n=await Ut(t,e);e?.aborted||(f(n.active_run),g(t))}catch(e){z(e)}},[c]),Nt=(0,Y.useCallback)(async e=>{let t=c;if(t)try{let n=await Ht(t,e);e?.aborted||D(e=>({...e,[t]:n}))}catch(e){z(e)}},[c]);(0,Y.useEffect)(()=>{if(!de)return;if(!at){f(null),g(null);return}if(!st)return;let e=new AbortController;g(null),Mt(e.signal);let t=window.setInterval(()=>{Mt(e.signal)},u$),n=aq(()=>{document.visibilityState===`visible`&&Mt(e.signal)});return()=>{e.abort(),window.clearInterval(t),n()}},[st,at,de,Mt]),(0,Y.useEffect)(()=>{if(!de||!c||!st||!St)return;let e=new AbortController;Nt(e.signal);let t=window.setInterval(()=>{Nt(e.signal)},u$),n=aq(()=>{document.visibilityState===`visible`&&Nt(e.signal)});return()=>{e.abort(),window.clearInterval(t),n()}},[c,st,St,de,Nt]),(0,Y.useEffect)(()=>{window.localStorage.setItem(d$,String(M))},[M]),(0,Y.useEffect)(()=>{window.localStorage.setItem(f$,F)},[F]),(0,Y.useEffect)(()=>{window.localStorage.setItem(p$,String(ee))},[ee]),(0,Y.useEffect)(()=>{c&&X&&j(e=>{let t=e[c]??null;return!t||t===X?e:{...e,[c]:null}})},[c,X]),(0,Y.useEffect)(()=>{!c||!bt||!H$(J)||xt!==bt.context_key&&k(e=>F$(e,c)===`hidden`?{...e,[c]:`inline`}:e)},[J,c,xt,bt]);let Pt=async e=>{try{t((await En(e)).tool)}catch{}},Ft=(0,Y.useCallback)(e=>{o(t=>t.map(t=>t.id===e.id?e:t))},[]),It=(0,Y.useCallback)((e,t)=>{Ie(n=>{let r=[t,...(n[e]??[]).filter(e=>e.id!==t.id)];return{...n,[e]:r}})},[]),Lt=(0,Y.useCallback)(async e=>{Ue(t=>({...t,[e]:!0}));try{let t=await je(e);Be(n=>({...n,[e]:t}))}catch(e){Q.error(e instanceof I?e.message:`Unable to load the project target options right now.`,{id:`project-target-selector-load-error`})}finally{Ue(t=>({...t,[e]:!1}))}},[]),Rt=async e=>{try{let t=await L(E$(e));return o(e=>[...e,t]),l(t.id),pe(null),null}catch(e){return e instanceof I?e.message:`Unable to create the project right now.`}},zt=async e=>{if(!J)return`Select a project before editing settings.`;try{let t=await P(J.id,E$(e));return o(e=>e.map(e=>e.id===t.id?t:e)),ke(e=>e+1),pe(null),null}catch(e){return e instanceof I?e.message:`Unable to update the project right now.`}},Bt=async()=>{if(!J)return`Select a project before deleting it.`;try{await Ne(J.id);let e=i.filter(e=>e.id!==J.id);return o(e),l(e[0]?.id??null),pe(null),null}catch(e){return e instanceof I?e.message:`Unable to delete the project right now.`}},Kt=(0,Y.useCallback)(e=>{o(t=>t.map(t=>j$(t,e)))},[]),qt=(0,Y.useCallback)((e,t)=>{e&&Ie(n=>({...n,[e]:t}))},[]),Jt=(0,Y.useCallback)((e,t)=>{e&&Re(n=>({...n,[e]:t}))},[]),Yt=async(e,t,n)=>await ce({repo_path:e,helper_model:t||null,helper_variant:t&&n||null}),Xt=async()=>(await se()).repo_path,Zt=(0,Y.useCallback)(async e=>{let t=await Ee({repo_path:e});return{valid:t.valid,repoRoot:t.repo_root,error:t.error,willInitialize:t.will_initialize,hasInitialCommit:t.has_initial_commit}},[]),Qt=(0,Y.useCallback)(async()=>{if(!(!J||ve)){ye(!0);try{let e=await a(J.id);o(t=>t.map(t=>t.id===e.id?e:t)),Q.success(`Initial commit created.`,{id:`project-initial-commit-success`}),Ot(e.id),kt(e.id)}catch(e){Q.error(e instanceof I?e.message:`Unable to create the initial commit right now.`,{id:`project-initial-commit-error`})}finally{ye(!1)}}},[J,ve,Ot,kt]),$t=(0,Y.useCallback)((e,t)=>{k(t=>({...t,[e]:`hidden`})),t&&j(n=>({...n,[e]:t}))},[]),en=(0,Y.useCallback)(()=>{c&&$t(c,X)},[c,$t,X]),tn=(0,Y.useCallback)(e=>{c&&(k(e=>({...e,[c]:`hidden`})),e&&f(t=>t?.context_key===e?null:t))},[c]),nn=(0,Y.useCallback)(async()=>{if(!bt||ne===bt.context_key)return;let{context_key:e}=bt;re(e);try{bt.kind===`ticket`?await _n(bt.ticket_id,bt.project_id):f((await Gt(bt.project_id)).active_run),tn(e),await Promise.all([Mt(),Nt()])}catch(e){Q.error(e instanceof I?e.message:`Unable to stop the preview run right now.`,{id:`app-preview-run-stop-error`})}finally{re(t=>t===e?null:t)}},[tn,bt,Nt,Mt,ne]),rn=(0,Y.useCallback)(e=>{!e||!c||Lt(c)},[c,Lt]),an=(0,Y.useCallback)(e=>new Promise(t=>{$e.current=t,Ye(e)}),[]),on=(0,Y.useCallback)(e=>{let t=$e.current;$e.current=null,Ye(null),t?.(e)},[]),sn=(0,Y.useCallback)(async e=>{if(!J||!c)throw Error(`Select a project first.`);if(!K$({activeProject:J,activeProjectBranchState:lt,nextTarget:e})||!u||u.kind!==`project`||u.project_id!==J.id)return!0;if(!await an({title:`Stop current run and switch target?`,description:`Switching targets will stop the current run and close its preview.`,confirmLabel:`Stop and switch`,cancelLabel:`Keep current target`,confirmVariant:`destructive`}))return!1;try{let e=u.context_key,t=await Gt(J.id);return tn(e),f(t.active_run),await Nt(),!0}catch(e){return Q.error(e instanceof I?e.message:`Unable to stop the project run right now.`,{id:`project-target-switch-stop-run-error`}),!1}},[J,lt,c,u,tn,Nt,an]),cn=(0,Y.useCallback)(async e=>{if(!c)throw Error(`Select a project first.`);return await sn({kind:`bundle`,bundleId:e})?(Ft(await s(c,{kind:`bundle`,bundle_id:e})),x(e=>({...e,[c]:null})),await Promise.all([Ot(c),kt(c)]),!0):!1},[c,sn,Ot,kt,Ft]),ln=(0,Y.useCallback)(async(e,t={})=>{if(!c)throw Error(`Select a project first.`);if(!await sn({kind:`repo_root`,branch:e}))return!1;let n=n=>s(c,{kind:`repo_root`,...e?{branch:e}:{},...t.createBranch===!1?{create_branch:!1}:{},...n?{confirm_dirty_switch:!0}:{}}),r;try{r=await n(t.confirmDirtySwitch===!0)}catch(e){if(!t.confirmDirtySwitch&&e instanceof I&&e.status===409&&e.message===G$){if(!await an({title:`Switch repo root branch?`,description:`${G$}\n\nSwitch anyway?`,confirmLabel:`Switch anyway`,cancelLabel:`Keep current branch`}))return!1;r=await n(!0)}else throw e}return Ft(r),x(e=>({...e,[c]:null})),await Promise.all([Ot(c),kt(c),Lt(c)]),!0},[c,sn,Lt,Ot,kt,Ft,an]),un=(0,Y.useCallback)(async e=>!e.target_kind||e.target_available===!1?!0:e.target_kind===`bundle`?e.target_bundle_id?await cn(e.target_bundle_id):!1:await ln(e.target_branch_snapshot??null,{createBranch:!1}),[cn,ln]),dn=(0,Y.useCallback)(()=>{Ge(!0)},[]),fn=(0,Y.useCallback)(()=>{Ge(!1)},[]),pn=(0,Y.useCallback)(e=>{if(e){cn(e);return}ln(null)},[cn,ln]),mn=(0,Y.useCallback)(async e=>{if(!c)throw Error(`Select a project first.`);let t=await Et(c,{name:e,prepare:!0});return It(c,t),ke(e=>e+1),t},[c,It]),hn=(0,Y.useCallback)(async e=>{if(!c)throw Error(`Select a project first.`);await Vt(c,e),Ie(t=>({...t,[c]:(t[c]??[]).filter(t=>t.id!==e)})),ke(e=>e+1)},[c]),gn=(0,Y.useCallback)(async()=>{if(!J)return;let e=J.active_target_kind??`repo_root`,t=J.active_target_bundle_id??null,n=u?.kind===`project`&&u.project_id===J.id&&(u.target_kind??`repo_root`)===e&&((u.target_kind??`repo_root`)!==`bundle`||u.target_bundle_id===t),r=n?u?.context_key??null:null,i=!n&&H$(J)&&vt===`hidden`;i&&(k(e=>({...e,[J.id]:`inline`})),j(e=>({...e,[J.id]:null})));try{let e=n?await Gt(J.id):await Wt(J.id);n&&tn(r),f(e.active_run),Nt()}catch(e){i&&k(e=>({...e,[J.id]:`hidden`})),Q.error(e instanceof I?e.message:`Unable to update the project run right now.`,{id:`app-project-run-error`})}},[vt,J,u,tn,Nt]),vn=(0,Y.useCallback)(async()=>{if(!(!J||!ot))try{await me(J.id)}catch(e){Q.error(e instanceof Error?e.message:`Unable to open the IDE right now.`,{id:`app-project-open-ide-error`})}},[J,ot]),yn=(0,Y.useCallback)(async()=>{if(J){At(J.id,`pull`);try{let e=await Qe(J.id);await jt(J,e),Q.success(e.behind===0?i$(`branchSynced`):i$(`branchUpdated`),{id:`app-project-pull-success`})}catch(e){Q.error(e instanceof I?e.message:i$(`syncFallbackError`),{id:`app-project-pull-error`})}finally{At(J.id,null)}}},[J,jt,At]),bn=(0,Y.useCallback)(async()=>{if(!J)return;let e=ut?.base_branch??null;At(J.id,`rebase`);try{let t=await d(J.id);await jt(J,t);let n=t.base_branch??e;Q.success(n?i$(`branchRebasedOnto`,{branch:n}):i$(`branchRebased`),{id:`app-project-rebase-success`})}catch(e){await Promise.allSettled([Ot(J.id),kt(J.id,{suppressLoading:!0})]),Q.error(e instanceof I?e.message:i$(`rebaseFallbackError`),{id:`app-project-rebase-error`})}finally{At(J.id,null)}},[J,ut?.base_branch,jt,Ot,kt,At]),xn=(0,Y.useCallback)(async()=>{if(J){At(J.id,`abort`);try{await jt(J,await v(J.id)),Q.success(i$(`gitOperationAborted`),{id:`app-project-abort-success`})}catch(e){Q.error(e instanceof I?e.message:i$(`abortFallbackError`),{id:`app-project-abort-error`})}finally{At(J.id,null)}}},[J,jt,At]),Sn=(0,Y.useCallback)(()=>{J&&he({projectId:J.id,title:J.name,targetKind:J.active_target_kind??`repo_root`,targetBundleId:J.active_target_bundle_id??null,hasHelperModel:!!J.helper_model,repoRootDefaultBranch:ht.default_branch})},[J,ht.default_branch]),Cn=(0,Y.useCallback)(()=>{if(!W)return;let{projectId:e}=W;he(null),Ot(e),kt(e)},[Ot,kt,W]),Dn=(0,Y.useCallback)(()=>{J&&_e({projectId:J.id,targetKind:J.active_target_kind??`repo_root`,targetBundleId:J.active_target_bundle_id??null})},[J]),On=(0,Y.useCallback)(()=>{_e(null)},[]),kn=P$(be,c),An=J?xY(J.test_commands).length>0:!1,jn=rt===`chat`?Me:null,Mn=Ze.current,Nn=Mn?.target?.kind??null,Pn=rt===`chat`?Nn===`ticket`||Nn===`bundle`?{target:Mn?.target??null,canSelect:!1,disabledReason:`This preview belongs to a ticket run. Return to Board to send preview comments.`,promptMode:Mn?.promptMode??null,onPromptModeChange:Mn?.onPromptModeChange??null,isUpdatingPromptMode:Mn?.isUpdatingPromptMode??!1,promptPlaceholder:Mn?.promptPlaceholder??null,promptComposerControls:Mn?.promptComposerControls,promptComposerInlineControls:Mn?.promptComposerInlineControls,submitPrompt:null}:jn?{target:{kind:`chat_session`,id:jn.chatSessionId??`draft:${c}`},canSelect:jn.canSubmitReviewPrompt,disabledReason:jn.canSubmitReviewPrompt?null:jn.reviewSubmitDisabledReason??`Wait for the current chat turn to finish before sending preview comments.`,promptMode:jn.mode,onPromptModeChange:jn.onModeChange,isUpdatingPromptMode:jn.isUpdatingMode,promptPlaceholder:jn.promptPlaceholder,promptComposerControls:jn.promptComposerControls,promptComposerInlineControls:jn.promptComposerInlineControls,submitPrompt:jn.canSubmitReviewPrompt?jn.submitPrompt:null}:{target:null,canSelect:!1,disabledReason:`Select a chat session to send preview comments.`,submitPrompt:null}:Ae,Fn=jn?.canSubmitReviewPrompt??!1,In=rt===`chat`?jn?jn.reviewSubmitDisabledReason:`Select a chat session to send review comments.`:void 0,Ln=(0,Y.useCallback)(()=>{c&&xe(e=>{let t=e[c]??_$;return{...e,[c]:{hasMounted:!0,isOpen:!t.isOpen,isExpanded:t.isExpanded}}})},[c]),Rn=(0,Y.useCallback)(e=>{xe(t=>{let n=t[e]??_$;return!n.hasMounted||!n.isOpen?t:{...t,[e]:_$}})},[]),zn=(0,Y.useCallback)(e=>{xe(t=>{let n=t[e]??_$;return{...t,[e]:{hasMounted:!0,isOpen:n.isOpen,isExpanded:!n.isExpanded}}})},[]),Bn=(0,Y.useCallback)(()=>{pe(`create`)},[]),Vn=(0,Y.useCallback)(()=>{if(c){if(yt){en();return}k(e=>({...e,[c]:`inline`})),j(e=>({...e,[c]:null}))}},[c,en,yt]),Hn=(0,Y.useCallback)(()=>{c&&k(e=>{let t=F$(e,c);return{...e,[c]:t===`expanded`?`inline`:`expanded`}})},[c]),Un=J?J.preview_service_name?.trim()?J.preview_capability_mode===`force_disabled`?`Preview is disabled for this project.`:_t?.state===`unsupported`?_t.message??`Preview is unavailable for this project.`:yt?`Hide preview`:`Show preview`:`Choose a named preview service in project settings first.`:`Select a project first.`,Wn=!J||!J.preview_service_name?.trim()||J.preview_capability_mode===`force_disabled`||_t?.state===`unsupported`,Gn=J&&J.preview_service_name?.trim()?(0,Z.jsx)(Xb,{project:J,mode:vt===`expanded`?`expanded`:`inline`,status:_t,viewportPreset:F,zoom:ee,activeRun:bt,reviewCapability:Pn,isStoppingActiveRun:Ct,onHide:en,onStopActiveRun:()=>{nn()},onToggleExpanded:Hn,onViewportPresetChange:R,onZoomChange:te}):null;return(0,Z.jsxs)(`div`,{className:`flex h-screen flex-col overflow-hidden bg-[linear-gradient(180deg,_rgba(15,16,21,1),_rgba(9,10,14,1))] text-foreground`,children:[(0,Z.jsx)(ou,{}),i.length>0&&(0,Z.jsx)(`header`,{className:`border-b border-border bg-background/95 px-6 py-3 backdrop-blur`,children:(0,Z.jsxs)(`div`,{className:`grid gap-2 lg:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] lg:items-center`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 lg:justify-self-start`,children:(0,Z.jsx)(`div`,{className:`min-w-0 w-full sm:min-w-[20rem] sm:max-w-[30rem]`,children:(0,Z.jsx)(Ec,{activeProjectId:c,projects:i,onEditProject:()=>pe(`edit`),onProjectChange:l})})}),c&&(0,Z.jsx)(`div`,{className:`flex justify-start lg:col-start-2 lg:row-start-1 lg:justify-center`,children:(0,Z.jsx)(HQ,{activeWorkspace:rt,activityByWorkspace:Ce,memoryEnabled:tt,onWorkspaceChange:e=>{c&&(Se(t=>({...t,[c]:e})),we(t=>DQ(t,e)))}})}),(0,Z.jsx)(`div`,{className:`w-full lg:col-start-3 lg:row-start-1 lg:w-auto lg:justify-self-end`,children:(0,Z.jsx)(au,{activeTool:e,onCreateProject:Bn,onMobileAccessOpen:()=>qe(!0),onToolChange:Pt})})]})}),de?i.length===0?(0,Z.jsx)(wc,{activeTool:e,availableHelperModels:B,helperModel:ae,helperVariant:le,isHelperModelsLoaded:V,isToolLoaded:n,onCreateProject:Bn,onHelperModelChange:e=>{oe(e),ue(``)},onHelperVariantChange:ue,onToolChange:Pt}):(0,Z.jsxs)(Z.Fragment,{children:[J?.has_initial_commit===!1&&(0,Z.jsx)(hu,{isSubmitting:ve,onCreateInitialCommit:()=>{Qt()}}),(0,Z.jsx)(BQ,{activeProjectId:c,activeProject:J,activeProjectBranchState:lt,activeRun:u,activeTool:e,onRestoreChatSessionTarget:un,onChatReviewCapabilityChange:Pe,isPreviewButtonDisabled:Wn,onPreviewReviewCapabilityChange:q,onPreviewToggle:Vn,onRunStopped:tn,onWorkspaceActivityChange:we,onWorkspaceActivityEvent:Dt,previewDisplayMode:vt,previewPane:Gn,previewPaneWidth:M,previewButtonTitle:Un,visibleWorkspace:rt,refreshKey:Oe,onBoardLoadedProjectIdChange:m,onBundlesChange:qt,onBundlesLoadingChange:Jt,onPreviewPaneWidthChange:N,onProjectUsageChange:Kt,onRunStatusChange:()=>{Mt(),Nt()}},c??`no-project`)]}):(0,Z.jsx)(`div`,{className:`flex flex-1 items-center justify-center text-sm text-muted-foreground`,children:`Loading projects...`}),i.length>0&&(0,Z.jsx)(Ll,{activeProject:J,activeRun:u,branchState:lt,targetGitStatus:ut,isBoardLoadedForActiveProject:st,activeProjectBranchAction:ft,isProjectIdeAvailable:ot,isProjectRunAvailable:at,isRunStatusLoadedForActiveProject:ct,isTerminalOpen:kn.isOpen,targetBundles:pt,targetBranchSuggestions:ht,isTargetBundleLoading:mt,isTargetSelectorLoading:gt,isTargetGitStatusLoading:dt,hasConfiguredTests:An,onProjectIdeOpen:()=>{vn()},onProjectPull:()=>{yn()},onProjectRebase:bn,onProjectAbortGitOperation:xn,onProjectRunToggle:()=>{gn()},onProjectChangesOpen:Sn,onProjectTestsOpen:Dn,onTerminalToggle:Ln,onTargetSelectorOpenChange:rn,onSelectBundleTarget:cn,onSelectRepoRootTarget:ln,onManageBundles:dn}),(0,Z.jsx)(Pd,{activeProjectId:c,open:Ke,onOpenChange:qe}),We&&J&&(0,Z.jsx)(Eu,{bundles:pt,selectedBundleId:J.active_target_kind===`bundle`?J.active_target_bundle_id??null:null,activeTargetBundleId:J.active_target_kind===`bundle`?J.active_target_bundle_id??null:null,onSelectBundle:pn,onCreateBundle:mn,onDeleteBundle:hn,onClose:fn}),Je&&(0,Z.jsx)(mu,{title:Je.title,description:Je.description,confirmLabel:Je.confirmLabel,cancelLabel:Je.cancelLabel,confirmVariant:Je.confirmVariant,onConfirm:()=>on(!0),onCancel:()=>on(!1)}),i.map(e=>{let t=P$(be,e.id);return t.hasMounted?(0,Z.jsx)(VQ,{project:e,isExpanded:t.isExpanded,isVisible:e.id===c&&t.isOpen,onClose:()=>Rn(e.id),onToggleExpanded:()=>zn(e.id)},e.id):null}),fe&&(0,Z.jsx)(Rp,{mode:fe,projectId:fe===`edit`&&J?J.id:null,availableHelperModels:B,isLoadingHelperModels:!V,isAutoConfigReady:n,initialValues:fe===`edit`&&J?T$(J):i.length===0?{name:``,repoPath:``,linkedProjectIds:[],runSetup:[],runServices:[],testCommands:[],runIde:``,previewServiceName:``,previewPath:``,previewCapabilityMode:`auto`,helperModel:ae,helperVariant:le,commitMessageRules:``,autoParkStaleTickets:!1,memoryEnabled:!1,worktreeSync:[]}:void 0,linkedProjectOptions:i.filter(e=>e.id!==J?.id).map(e=>({id:e.id,name:e.name})),repoPathLocked:fe===`edit`&&J?J.repo_path_locked:!1,repoPathLockedMessage:fe===`edit`&&J?k$(J):null,deleteBlockedMessage:fe===`edit`&&J?A$(J,i):null,onDelete:fe===`edit`?Bt:void 0,onAutoConfig:Yt,onBrowseRepoPath:Xt,onValidateRepoPath:Zt,onClose:()=>pe(null),onSubmit:fe===`edit`?zt:Rt}),W&&W.projectId===c&&(0,Z.jsx)(Y.Suspense,{fallback:null,children:(0,Z.jsx)(y$,{scope:`project_root`,projectId:W.projectId,targetKind:W.targetKind,reviewCommentsBundleId:W.targetKind===`bundle`?W.targetBundleId:null,title:W.title,hasHelperModel:W.hasHelperModel,repoRootDefaultBranch:W.repoRootDefaultBranch,onSubmitReviewPrompt:jn?.submitPrompt,canSubmitReviewPrompt:Fn,reviewSubmitDisabledReason:In??void 0,canAddReviewComments:Fn,canModifyChanges:!0,onClose:Cn})}),G&&G.projectId===c&&J&&(0,Z.jsx)(Y.Suspense,{fallback:null,children:(0,Z.jsx)(b$,{scope:`project`,projectId:G.projectId,targetKind:G.targetKind,targetBundleId:G.targetBundleId,testCommands:xY(J.test_commands),onClose:On})})]})},J$=({className:e})=>(0,Z.jsx)(mo,{"aria-hidden":`true`,className:e}),Y$=({className:e})=>(0,Z.jsx)(_o,{"aria-hidden":`true`,className:e}),X$=({className:e})=>(0,Z.jsx)(Ao,{"aria-hidden":`true`,className:e}),Z$=`X-Archon-Mobile-CSRF`,Q$=async(e,t={})=>{let n=await fetch(e,{credentials:`include`,...t});if(!n.ok)throw new I(await O(n,`Mobile request failed.`),n.status);return n},$$=async(e,t={})=>await(await Q$(e,t)).json(),e1=e=>$$(`/mobile/projects`,{signal:e}),t1=(e,t)=>$$(`/mobile/projects/${encodeURIComponent(e)}/summary`,{signal:t}),n1=(e,t)=>$$(`/mobile/projects/${encodeURIComponent(e)}/target-options`,{signal:t}),r1=(e,t)=>$$(`/mobile/projects/${encodeURIComponent(e)}/chat-sessions`,{signal:t}),i1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/chat-sessions/${encodeURIComponent(t)}`,{signal:n}),a1=(e,t)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets`,{signal:t}),o1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}`,{signal:n}),s1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/bundles/${encodeURIComponent(t)}`,{signal:n}),c1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/bundles/${encodeURIComponent(t)}/build`,u1(n)),l1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/bundles/${encodeURIComponent(t)}/review`,u1(n)),u1=(e,t,n=`POST`)=>({method:n,headers:{"Content-Type":`application/json`,[Z$]:e},body:t===void 0?void 0:JSON.stringify(t)}),d1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/chat-sessions`,u1(t,n)),f1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/chat-sessions/${encodeURIComponent(t)}/messages`,u1(n,r)),p1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/chat-sessions/${encodeURIComponent(t)}`,u1(n,r,`PATCH`)),m1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/chat-sessions/${encodeURIComponent(t)}/stop`,u1(n)),h1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/state`,u1(n,{state:r},`PATCH`)),g1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/run`,u1(n)),_1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/stop`,u1(n)),v1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/stop-build`,u1(n)),y1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/resume-build`,u1(n)),b1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}`,u1(n,r,`PATCH`)),x1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/plan-follow-up`,u1(n,{instruction:r})),S1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/follow-up`,u1(n,{instruction:r})),C1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/bundles/${encodeURIComponent(t)}/follow-up`,u1(n,{instruction:r})),w1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/target`,u1(t,n)),T1=(e,t)=>$$(`/mobile/models?tool=${encodeURIComponent(e)}`,{signal:t}),E1=(e,t,n)=>{let r=new URLSearchParams({tool:e});return t&&r.set(`project_id`,t),$$(`/mobile/skills?${r.toString()}`,{signal:n})},D1=e=>$$(`/mobile-auth/status`,{signal:e}),O1=(e,t)=>$$(`/mobile-auth/pair/preview`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t}),k1=e=>$$(`/mobile-auth/pair`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)}),A1=e=>$$(`/mobile-auth/logout`,{method:`POST`,headers:{[Z$]:e}}),j1=()=>HW(window.location.origin,{withCredentials:!0}),M1=e=>Pe.t(`common:mobileApp.${e}`),N1={key:`overview`,label:M1(`navigation.overview`),Icon:J$},P1={key:`tickets`,label:M1(`navigation.tickets`),Icon:X$,ctaAriaLabel:M1(`overviewActions.ticketsAriaLabel`)},F1={key:`chats`,label:M1(`navigation.chats`),Icon:nm,ctaAriaLabel:M1(`overviewActions.chatsAriaLabel`)},I1=[N1,P1,F1],L1=`Project root has uncommitted changes. Confirm branch switch to continue.`,R1=e=>e?`Repo root (${e})`:`Repo root`,z1=e=>{if(!e)return`Repo root`;if(e.length<=20)return e;let t=e.split(`/`).filter(Boolean),n=t[t.length-1]??e;return n.length<=17?`.../${n}`:`${n.slice(0,16)}...`},B1=(e,t)=>{if(!e)return`Target`;if(e.active_target_kind===`bundle`&&e.active_target_bundle_id){let n=t?.bundles.find(t=>t.id===e.active_target_bundle_id)??null;return n?Dl(n):`Selected bundle`}return z1(t?.current_branch??null)},V1=({children:e})=>(0,Z.jsx)(`main`,{className:`min-h-screen bg-background text-foreground`,children:(0,Z.jsx)(`div`,{className:`mx-auto flex min-h-screen w-full max-w-lg items-center px-4 py-8`,children:(0,Z.jsx)(`div`,{className:`w-full`,children:e})})}),H1=({title:e,description:t,children:n})=>(0,Z.jsx)(V1,{children:(0,Z.jsxs)(gu,{className:`w-full border-border/80 bg-card/90 shadow-2xl shadow-black/20`,children:[(0,Z.jsxs)(_u,{children:[(0,Z.jsx)(vu,{children:e}),(0,Z.jsx)(yu,{children:t})]}),n?(0,Z.jsx)(xu,{className:`space-y-4`,children:n}):null]})}),U1=e=>e===`connected`?{label:`Connected`,variant:`success`,indicatorState:`finished`}:e===`reconnecting`?{label:`Reconnecting`,variant:`warning`,indicatorState:`running`}:e===`unavailable`?{label:`Offline`,variant:`destructive`,indicatorState:`error`}:{label:`Connecting`,variant:`outline`,indicatorState:`running`},W1=({status:e})=>{let t=U1(e);return(0,Z.jsxs)(U,{variant:t.variant,className:`gap-1.5 px-2.5 py-1 text-[11px] uppercase tracking-[0.14em]`,children:[(0,Z.jsx)(Rl,{state:t.indicatorState,className:`mt-0`}),t.label]})},G1=()=>{let[e,t]=(0,Y.useState)(()=>typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(`(min-width: 1024px)`).matches);return(0,Y.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(min-width: 1024px)`),n=n=>{t(n?.matches??e.matches)};return n(),typeof e.addEventListener==`function`?(e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)):(e.addListener(n),()=>e.removeListener(n))},[]),e},K1=({status:e,onRetry:t})=>e===`connected`?null:e===`unavailable`?(0,Z.jsx)(gu,{className:`border-red-500/25 bg-destructive/10 shadow-none`,children:(0,Z.jsxs)(xu,{className:`flex flex-col gap-3 pt-5`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium text-red-100`,children:`Desktop Archon is currently unreachable.`}),(0,Z.jsx)(`p`,{className:`text-sm text-red-200/85`,children:`Mobile access may have been disabled, the backend may have restarted, or this phone lost network access.`})]}),(0,Z.jsx)(`div`,{children:(0,Z.jsx)(q,{variant:`warning`,onClick:t,children:`Retry connection`})})]})}):(0,Z.jsx)(gu,{className:`border-amber-500/25 bg-amber-500/10 shadow-none`,children:(0,Z.jsx)(xu,{className:`pt-5 text-sm text-amber-100`,children:e===`connecting`?`Connecting to live updates from desktop Archon...`:`Reconnecting to desktop Archon. Existing content stays visible while this phone reconnects.`})}),q1=({title:e,description:t,children:n})=>(0,Z.jsxs)(`div`,{className:`flex max-h-[80vh] flex-col overflow-hidden`,children:[(0,Z.jsxs)(Fs,{className:`border-b border-border/70 px-4 py-4`,children:[(0,Z.jsx)(Ls,{children:e}),t?(0,Z.jsx)(Rs,{children:t}):null]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto px-4 py-4`,children:n})]}),J1=({projects:e,selectedProjectId:t,error:n,onSelectProject:r,onRetry:i})=>n?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(`p`,{className:`text-sm text-red-200`,children:n}),(0,Z.jsx)(q,{variant:`warning`,onClick:i,children:`Retry projects`})]}):e?e.length===0?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No projects are available on the desktop instance yet.`}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>{let n=e.id===t;return(0,Z.jsxs)(`button`,{type:`button`,className:K(`w-full rounded-2xl border px-4 py-3 text-left transition-colors`,n?`border-primary/50 bg-primary/10`:`border-border/80 bg-card/60 hover:border-primary/30 hover:bg-accent/60`),onClick:()=>r(e.id),children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:e.repo_path})]}),n&&(0,Z.jsx)(U,{variant:`info`,children:`Current`})]}),(0,Z.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-2 text-[11px] uppercase tracking-[0.14em] text-muted-foreground`,children:(0,Z.jsxs)(`span`,{children:[e.ticket_count,` tickets`]})})]},e.id)})}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading projects...`}),Y1=({open:e,projects:t,selectedProjectId:n,error:r,onOpenChange:i,onSelectProject:a,onRetry:o})=>(0,Z.jsx)(As,{open:e,onOpenChange:i,children:(0,Z.jsx)(Ps,{showCloseButton:!1,"aria-describedby":void 0,className:`top-auto right-0 bottom-0 left-0 max-w-none translate-x-0 translate-y-0 overflow-hidden rounded-t-3xl rounded-b-none border-x-0 border-b-0 p-0 sm:top-1/2 sm:right-auto sm:bottom-auto sm:left-1/2 sm:max-w-md sm:-translate-x-1/2 sm:-translate-y-1/2 sm:rounded-2xl sm:border sm:p-0`,children:(0,Z.jsx)(q1,{title:`Projects`,children:(0,Z.jsx)(J1,{projects:t,selectedProjectId:n,error:r,onSelectProject:e=>{a(e),i(!1)},onRetry:o})})})}),X1=({open:e,project:t,targetOptions:n,error:r,isLoading:i,isSubmitting:a,onOpenChange:o,onRetry:s,onSelectBundle:c,onSelectRepoRoot:l})=>{let[u,d]=(0,Y.useState)(``);(0,Y.useEffect)(()=>{e&&d(n?.current_branch??``)},[e,n?.current_branch]);let f=t?.active_target_kind!==`bundle`,p=_l(n?.bundles??[]),m=[{key:`default`,label:`Default branch`,branch:n?.default_branch??null},{key:`previous`,label:`Previous branch`,branch:n?.previous_branch??null}].filter(e=>e.branch&&e.branch!==n?.current_branch).filter((e,t,n)=>n.findIndex(t=>t.branch===e.branch)===t),h=t?r?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(`p`,{className:`text-sm text-red-200`,children:r}),(0,Z.jsx)(q,{variant:`warning`,onClick:s,children:`Retry target options`})]}):n?(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-sm font-semibold text-foreground`,children:`Project target`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Choose the repo root or a prepared bundle for new chats and desktop work launched from this phone.`})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Qs,{className:`text-xs font-medium text-muted-foreground`,children:`Target`}),(0,Z.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border/70 bg-background/40 p-2`,children:[(0,Z.jsx)(q,{type:`button`,variant:f?`secondary`:`ghost`,className:`w-full justify-start`,disabled:a,onClick:()=>l(null),children:R1(n.current_branch)}),(0,Z.jsxs)(`div`,{className:`relative min-h-10`,"data-testid":`mobile-target-options`,children:[i&&(0,Z.jsx)(`div`,{className:`pointer-events-none absolute right-2 top-2 z-10 text-muted-foreground`,"data-testid":`mobile-target-options-spinner`,children:(0,Z.jsx)(W,{className:`h-3.5 w-3.5 animate-spin`})}),(0,Z.jsx)(`div`,{className:`max-h-40 overflow-y-auto pr-7`,children:p.length===0&&!i?(0,Z.jsx)(`p`,{className:`px-2 py-2 text-xs text-muted-foreground`,children:`No prepared bundles are available yet.`}):p.map(e=>(0,Z.jsx)(q,{type:`button`,variant:t.active_target_kind===`bundle`&&t.active_target_bundle_id===e.id?`secondary`:`ghost`,className:`w-full justify-start`,disabled:a,onClick:()=>c(e.id),children:(0,Z.jsx)(`span`,{className:`truncate`,children:Dl(e)})},e.id))})]})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Qs,{className:`text-xs font-medium text-muted-foreground`,children:`Repo root branch`}),(0,Z.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border/70 bg-background/40 p-3`,children:[(0,Z.jsx)(`div`,{className:`space-y-2`,children:m.length>0?m.map(({key:e,label:t,branch:n})=>(0,Z.jsxs)(q,{type:`button`,variant:`outline`,className:`w-full justify-between gap-3`,disabled:!f||a||!n,onClick:()=>l(n),children:[(0,Z.jsx)(`span`,{children:t}),(0,Z.jsx)(`span`,{className:`truncate text-xs text-muted-foreground`,children:n})]},e)):(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i?`Loading branch suggestions...`:`No suggested branches available.`})}),(0,Z.jsxs)(`div`,{className:`flex items-end gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1`,children:[(0,Z.jsx)(Qs,{htmlFor:`mobile-project-target-branch-input`,className:`text-xs text-muted-foreground`,children:`Switch or create branch`}),(0,Z.jsx)(Ge,{id:`mobile-project-target-branch-input`,value:u,disabled:!f||a,onChange:e=>d(e.target.value),placeholder:`feature/quick-fix`})]}),(0,Z.jsx)(q,{type:`button`,disabled:!f||!u.trim()||a,onClick:()=>l(u.trim()),children:`Switch`})]}),f?null:(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Switch to repo root to choose a branch.`})]})]})]}):(0,Z.jsx)(t0,{text:`Loading target options...`}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Select a project before choosing a target.`});return(0,Z.jsx)(As,{open:e,onOpenChange:o,children:(0,Z.jsx)(Ps,{showCloseButton:!1,"aria-describedby":void 0,className:`top-auto right-0 bottom-0 left-0 max-w-none translate-x-0 translate-y-0 overflow-hidden rounded-t-3xl rounded-b-none border-x-0 border-b-0 p-0 sm:top-1/2 sm:right-auto sm:bottom-auto sm:left-1/2 sm:max-w-md sm:-translate-x-1/2 sm:-translate-y-1/2 sm:rounded-2xl sm:border sm:p-0`,children:(0,Z.jsx)(q1,{title:`Target`,description:t?B1(t,n):void 0,children:h})})})},Z1=({selectedProject:e,targetLabel:t,isTargetLoading:n,isTargetDisabled:r,connectionState:i,onOpenProjects:a,onOpenTargetSelector:o})=>(0,Z.jsx)(`header`,{className:`sticky top-0 z-20 border-b border-border/70 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85`,children:(0,Z.jsxs)(`div`,{className:`mx-auto flex w-full max-w-6xl items-center justify-between gap-3 px-3 pb-3 pt-4 sm:px-4`,children:[(0,Z.jsxs)(`button`,{type:`button`,"aria-label":`Choose project`,className:`min-w-0 flex-1 text-left`,onClick:a,children:[(0,Z.jsx)(`div`,{className:`truncate text-base font-medium text-foreground`,children:e?.name??`Choose a project`}),(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:e?.repo_path??`Select a desktop project to continue`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Z.jsx)(W1,{status:i}),(0,Z.jsxs)(q,{variant:`outline`,size:`sm`,"aria-label":`Choose target`,"data-testid":`mobile-target-trigger`,className:`h-8 max-w-32 gap-2 px-2.5 sm:max-w-40`,disabled:r,onClick:o,children:[(0,Z.jsx)(kl,{className:`h-3.5 w-3.5 shrink-0`}),n?(0,Z.jsx)(Oc,{className:`h-3.5 w-16`}):(0,Z.jsx)(`span`,{className:`truncate text-xs sm:text-sm`,children:t})]}),(0,Z.jsx)(q,{variant:`outline`,size:`icon-sm`,"aria-label":`Choose project`,onClick:a,children:(0,Z.jsx)(cf,{className:`h-4 w-4`})})]})]})}),Q1=({activeSection:e,onChange:t})=>(0,Z.jsx)(`nav`,{className:`fixed inset-x-0 bottom-0 z-20 border-t border-border/70 bg-background/95 px-3 pb-[calc(env(safe-area-inset-bottom)+0.75rem)] pt-2 backdrop-blur supports-[backdrop-filter]:bg-background/85 sm:px-4 lg:hidden`,children:(0,Z.jsx)(`div`,{className:`mx-auto flex max-w-6xl gap-2`,children:I1.map(n=>{let r=n.key===e,i=n.Icon;return(0,Z.jsxs)(q,{type:`button`,variant:r?`secondary`:`ghost`,className:`h-11 flex-1 gap-2`,"aria-current":r?`page`:void 0,onClick:()=>t(n.key),children:[(0,Z.jsx)(i,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:n.label})]},n.key)})})}),$1=({title:e,description:t,action:n})=>(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:[(0,Z.jsxs)(_u,{children:[(0,Z.jsx)(vu,{children:e}),(0,Z.jsx)(yu,{children:t})]}),n?(0,Z.jsx)(xu,{children:n}):null]}),e0=({label:e,value:t,accentClassName:n})=>(0,Z.jsxs)(`div`,{className:`rounded-2xl border border-border/70 bg-card/70 p-3`,children:[(0,Z.jsx)(`div`,{className:K(`text-xl font-semibold text-foreground`,n),children:t}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs uppercase tracking-[0.14em] text-muted-foreground`,children:e})]}),t0=({text:e})=>(0,Z.jsxs)(`div`,{"aria-live":`polite`,className:`flex items-center gap-2 px-1 py-3 text-sm text-muted-foreground`,role:`status`,children:[(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}),(0,Z.jsx)(`span`,{children:e})]}),n0=()=>(0,Z.jsxs)(`div`,{className:`space-y-3`,"data-testid":`mobile-overview-skeleton`,children:[(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:[(0,Z.jsx)(_u,{className:`border-b border-border/70 pb-4`,children:(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.jsx)(Oc,{className:`h-6 w-28`}),(0,Z.jsx)(Oc,{className:`h-6 w-28 rounded-full`})]})}),(0,Z.jsxs)(xu,{className:`space-y-4 pt-5`,children:[(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3`,children:Array.from({length:6},(e,t)=>(0,Z.jsxs)(`div`,{className:`rounded-2xl border border-border/70 bg-card/70 p-3`,children:[(0,Z.jsx)(Oc,{className:`h-6 w-10`}),(0,Z.jsx)(Oc,{className:`mt-2 h-3 w-16`})]},t))}),(0,Z.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:[(0,Z.jsx)(Oc,{className:`h-10 w-full rounded-xl`}),(0,Z.jsx)(Oc,{className:`h-10 w-full rounded-xl`})]})]})]}),(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:[(0,Z.jsx)(_u,{children:(0,Z.jsx)(Oc,{className:`h-6 w-20`})}),(0,Z.jsx)(xu,{children:(0,Z.jsx)(Oc,{className:`h-10 w-40 rounded-xl`})})]})]}),r0=({isLoggingOut:e,onLogout:t})=>(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:[(0,Z.jsx)(_u,{children:(0,Z.jsx)(vu,{children:`Session`})}),(0,Z.jsx)(xu,{children:(0,Z.jsxs)(q,{variant:`destructive`,className:`gap-2`,disabled:e,onClick:t,children:[(0,Z.jsx)(Y$,{className:`h-4 w-4`}),e?`Logging out...`:`Log out this phone`]})})]}),i0=({activeRun:e,tickets:t,chatSessions:n,chatSessionDetail:r})=>{let i=r?.agent_status===`running`||!!n?.some(e=>e.agent_status===`running`);if(e?.kind===`ticket`)return{label:`Ticket run active`,variant:`success`};if(i)return{label:`Chat active`,variant:`success`};if(e)return{label:`Project run active`,variant:`success`};let a=t?.filter(e=>e.agent_status===`running`&&e.parked_at===null)??[];return a.some(e=>e.state===`review`)?{label:`Reviewing`,variant:`warning`}:a.some(e=>e.state===`build`)?{label:`Building`,variant:`success`}:a.some(e=>e.state===`plan`)?{label:`Planning`,variant:`info`}:{label:`Idle`,variant:`outline`}},a0=({activeRun:e,tickets:t,chatSessions:n,chatSessionDetail:r})=>{let i=i0({activeRun:e,tickets:t,chatSessions:n,chatSessionDetail:r});return(0,Z.jsx)(U,{variant:i.variant,children:i.label})},o0=({selectedProjectId:e,summary:t,tickets:n,error:r,chatSessions:i,chatSessionDetail:a,onRetry:o,onOpenTickets:s,onOpenChats:c})=>{let l=P1.Icon,u=F1.Icon;return r?(0,Z.jsx)($1,{title:`Project summary unavailable`,description:r,action:(0,Z.jsx)(q,{variant:`warning`,onClick:o,children:`Retry summary`})}):e?!t||t.project.id!==e?(0,Z.jsx)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:(0,Z.jsx)(xu,{className:`pt-5 text-sm text-muted-foreground`,children:`Loading project summary...`})}):(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:[(0,Z.jsxs)(_u,{className:`border-b border-border/70 pb-4`,children:[(0,Z.jsx)(vu,{children:`Overview`}),(0,Z.jsx)(bu,{children:(0,Z.jsx)(a0,{activeRun:t.active_run,tickets:n,chatSessions:i,chatSessionDetail:a})})]}),(0,Z.jsxs)(xu,{className:`space-y-4 pt-5`,children:[(0,Z.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3`,children:[(0,Z.jsx)(e0,{label:`Tickets`,value:t.tickets.total}),(0,Z.jsx)(e0,{label:`Plan`,value:t.tickets.plan,accentClassName:`text-sky-200`}),(0,Z.jsx)(e0,{label:`Build`,value:t.tickets.build,accentClassName:`text-emerald-200`}),(0,Z.jsx)(e0,{label:`Review`,value:t.tickets.review,accentClassName:`text-amber-200`}),(0,Z.jsx)(e0,{label:`Done`,value:t.tickets.parked}),(0,Z.jsx)(e0,{label:`Bundles`,value:t.project.bundle_count??0})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:[(0,Z.jsxs)(q,{variant:`outline`,className:`gap-2`,"aria-label":P1.ctaAriaLabel,onClick:s,children:[(0,Z.jsx)(l,{className:`h-4 w-4`}),P1.label]}),(0,Z.jsxs)(q,{variant:`outline`,className:`gap-2`,"aria-label":F1.ctaAriaLabel,onClick:c,children:[(0,Z.jsx)(u,{className:`h-4 w-4`}),F1.label]})]})]})]}):(0,Z.jsx)($1,{title:`Choose a project`,description:`Select a desktop project before opening tickets or chats from this phone.`})},s0=e=>e.parked_at?`parked`:e.state,c0=e=>{let t=s0(e);return t===`parked`?`Done`:`${t.slice(0,1).toUpperCase()}${t.slice(1)}`},l0=e=>e===`plan`?`info`:e===`build`?`success`:e===`review`?`warning`:`outline`,u0=({ticket:e,isSelected:t,onSelectTicket:n,className:r})=>(0,Z.jsxs)(`button`,{type:`button`,className:K(`w-full rounded-2xl border px-4 py-3 text-left transition-colors`,t?`border-primary/50 bg-primary/10`:`border-border/70 bg-card/40 hover:border-primary/30 hover:bg-accent/50`,r),onClick:()=>n(e.id),children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Z.jsx)(`div`,{className:`text-sm font-medium text-foreground`,children:e.title})}),(0,Z.jsx)(U,{variant:l0(s0(e)),children:c0(e)})]}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2 text-[11px] uppercase tracking-[0.14em] text-muted-foreground`,children:[e.agent_status?(0,Z.jsx)(`span`,{children:e.agent_status}):null,e.branch?(0,Z.jsx)(`span`,{children:e.branch}):null,e.bundle?.name?(0,Z.jsx)(`span`,{children:e.bundle.name}):null]})]}),d0=({group:e,selectedBundleId:t,selectedTicketId:n,onSelectBundle:r,onSelectTicket:i})=>{let a=e.bundle.id===t,o=e.tickets.some(e=>e.id===n),[s,c]=(0,Y.useState)(o),l=Dl(e.bundle)||e.bundle.branch||e.bundle.name||`Bundle`,u=e.tickets.filter(e=>e.agent_status===`running`).length,d=a||o;return(0,Y.useEffect)(()=>{o&&c(!0)},[o]),(0,Z.jsxs)(td,{open:s,onOpenChange:c,children:[(0,Z.jsxs)(`div`,{className:K(`flex items-start gap-2 rounded-2xl border px-4 py-3 transition-colors`,d?`border-primary/50 bg-primary/10`:`border-border/70 bg-card/40 hover:border-primary/30 hover:bg-accent/50`),children:[(0,Z.jsx)(`button`,{type:`button`,className:`min-w-0 flex-1 text-left`,"aria-label":`Open bundle ${l}`,onClick:()=>r(e.bundle.id),children:(0,Z.jsx)(`div`,{className:`flex items-start justify-between gap-3`,children:(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(U,{variant:`outline`,children:`Bundle`}),(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium text-foreground`,children:l})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2 text-[11px] uppercase tracking-[0.14em] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[e.tickets.length,` ticket`,e.tickets.length===1?``:`s`]}),u>0?(0,Z.jsxs)(`span`,{children:[u,` running`]}):null,e.bundle.branch?(0,Z.jsx)(`span`,{children:e.bundle.branch}):null]})]})})}),(0,Z.jsx)(nd,{asChild:!0,children:(0,Z.jsx)(q,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`mt-0.5 shrink-0`,"aria-label":`Toggle bundle tickets for ${l}`,children:(0,Z.jsx)(ke,{className:K(`h-4 w-4 transition-transform`,s&&`rotate-180`)})})})]}),(0,Z.jsx)(rd,{className:`pt-2`,children:(0,Z.jsx)(`div`,{className:`space-y-2 pl-3`,children:e.tickets.map(t=>(0,Z.jsx)(u0,{ticket:t,isSelected:t.id===n,onSelectTicket:t=>i(t,e.bundle.id),className:`rounded-xl`},t.id))})})]})},f0=(e,t)=>Sl(e,[],t),p0=e=>[{key:`plan`,label:`Plan`,tickets:e.filter(e=>!e.parked_at&&e.state===`plan`),items:f0(e.filter(e=>!e.parked_at&&e.state===`plan`),`plan`)},{key:`build`,label:`Build`,tickets:e.filter(e=>!e.parked_at&&e.state===`build`),items:f0(e.filter(e=>!e.parked_at&&e.state===`build`),`build`)},{key:`review`,label:`Review`,tickets:e.filter(e=>!e.parked_at&&e.state===`review`),items:f0(e.filter(e=>!e.parked_at&&e.state===`review`),`review`)},{key:`parked`,label:`Done`,tickets:e.filter(e=>e.parked_at),items:f0(e.filter(e=>e.parked_at),`done`)}].filter(e=>e.tickets.length>0),m0=(e,t)=>{if(!e)return e;let n=new Map(t.tickets.map(e=>[e.id,e]));return e.map(e=>n.get(e.id)??e)},h0=({selectedProjectId:e,tickets:t,selectedBundleId:n,selectedTicketId:r,error:i,onRetry:a,onSelectBundle:o,onSelectTicket:s})=>{if(!e)return(0,Z.jsx)($1,{title:`Choose a project`,description:`Select a project before browsing tickets from this phone.`});if(i)return(0,Z.jsx)($1,{title:`Tickets unavailable`,description:i,action:(0,Z.jsx)(q,{variant:`warning`,onClick:a,children:`Retry tickets`})});if(!t)return(0,Z.jsx)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:(0,Z.jsx)(xu,{className:`pt-5 text-sm text-muted-foreground`,children:`Loading tickets...`})});if(t.length===0)return(0,Z.jsx)($1,{title:`No tickets`,description:`This project does not have any tickets yet.`});let c=p0(t);return(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none lg:flex lg:min-h-0 lg:flex-col`,children:[(0,Z.jsxs)(_u,{className:`border-b border-border/70 pb-4`,children:[(0,Z.jsx)(vu,{children:`Tickets`}),(0,Z.jsxs)(yu,{children:[t.length,` total`]})]}),(0,Z.jsx)(xu,{className:`space-y-4 pt-5 lg:min-h-0 lg:flex-1 lg:overflow-y-auto`,children:c.map(e=>(0,Z.jsxs)(`section`,{className:`space-y-2`,"aria-label":`${e.label} tickets`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:e.label}),(0,Z.jsx)(`span`,{children:e.tickets.length})]}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.items.map(e=>e.kind===`bundle`?(0,Z.jsx)(d0,{group:e.group,selectedBundleId:n,selectedTicketId:r,onSelectBundle:o,onSelectTicket:s},e.group.id):(0,Z.jsx)(u0,{ticket:e.ticket,isSelected:e.ticket.id===r,onSelectTicket:e=>s(e,null)},e.ticket.id))})]},e.key))})]})},g0=({selectedProjectId:e,chatSessions:t,selectedChatSessionId:n,error:r,onRetry:i,onOpenNewChat:a,onSelectChat:o})=>e?r?(0,Z.jsx)($1,{title:`Chats unavailable`,description:r,action:(0,Z.jsx)(q,{variant:`warning`,onClick:i,children:`Retry chats`})}):(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none lg:flex lg:min-h-0 lg:flex-col`,children:[(0,Z.jsxs)(_u,{className:`border-b border-border/70 pb-4`,children:[(0,Z.jsx)(vu,{children:`Chats`}),(0,Z.jsx)(yu,{children:t?`${t.length} recent`:`Loading chats...`}),(0,Z.jsx)(bu,{children:(0,Z.jsx)(q,{variant:`outline`,size:`sm`,onClick:a,children:`New chat`})})]}),(0,Z.jsx)(xu,{className:`space-y-2 pt-5 lg:min-h-0 lg:flex-1 lg:overflow-y-auto`,children:t?t.length===0?(0,Z.jsx)($1,{title:`No chats`,description:`Start a new chat to plan or build from this project.`,action:(0,Z.jsx)(q,{onClick:a,children:`Start a chat`})}):t.map(e=>(0,Z.jsx)(`button`,{type:`button`,className:K(`w-full rounded-xl border px-3 py-2.5 text-left transition-colors`,e.id===n?`border-primary/50 bg-primary/10`:`border-border/70 bg-card/40 hover:border-primary/30 hover:bg-accent/50`),onClick:()=>o(e.id),children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 pr-2 text-sm font-medium text-foreground line-clamp-2 break-words`,children:e.title}),(0,Z.jsx)(U,{variant:e.agent_status===`running`?`warning`:e.mode===`plan`?`info`:`success`,children:e.agent_status??e.mode})]})},e.id)):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading chats...`})})]}):(0,Z.jsx)($1,{title:`Choose a project`,description:`Select a project before browsing chats from this phone.`}),_0=({label:e,disabled:t,onClick:n})=>(0,Z.jsx)(q,{type:`button`,variant:`outline`,disabled:t,onClick:n,children:e}),v0=e=>{let t=e.tickets.filter(e=>!e.parked_at),n=t.filter(e=>e.state===`plan`),r=t.filter(e=>e.state===`build`),i=t.filter(e=>e.state===`review`),a=t.some(e=>e.agent_status===`running`),o=t.find(e=>Dw(e)&&e.agent_status===`running`&&!!e.session_id)??null,s=t.find(e=>Dw(e)&&e.agent_status===`stopped`&&!!e.session_id)??null,c=[];n.length>0&&c.push({id:`build`,label:`Build Bundle`,pendingLabel:`Building Bundle...`,ariaLabel:`Build Bundle`,disabled:!1,disabledReason:null});let l=r.length>0&&r.every(e=>e.agent_status===`done`),u=r.length===0&&i.length>0&&e.can_re_review===!0&&!a;return(l||u)&&c.push({id:`review`,label:u?`Re-run review`:`Review Bundle`,pendingLabel:`Reviewing Bundle...`,ariaLabel:u?`Re-run review`:`Review Bundle`,disabled:!1,disabledReason:null}),o&&c.push({id:`pause-build`,label:`Pause Build`,pendingLabel:`Pausing Build...`,ariaLabel:`Pause Build`,title:`Pause the build session. You can resume it later.`,disabled:!1,disabledReason:null}),!o&&s&&c.push({id:`resume-build`,label:`Resume`,pendingLabel:`Resuming...`,ariaLabel:`Resume`,disabled:!1,disabledReason:null}),{actions:c,runningBuildTicketId:o?.id??null,resumableBuildTicketId:s?.id??null}},y0=({ticket:e,actionState:t,actionError:n,onAction:r})=>{let i=YW(e,{reviewLabel:e.worktree_bundle_id===null?`Review`:`Review Bundle`}),a=e.worktree_bundle_id===null&&e.state===`review`&&e.can_re_review===!0&&e.agent_status!==`running`&&!e.parked_at?[{id:`review`,label:`Re-run review`,pendingLabel:`Re-running review...`,ariaLabel:`Re-run review`,disabled:!1,disabledReason:null},...i]:i;return a.length===0?null:(0,Z.jsx)(qW,{actions:a,activeAction:t,disableWhenActive:!0,className:`space-y-3`,heading:`Actions`,headingClassName:`text-[11px] font-semibold uppercase tracking-[0.14em] text-muted-foreground`,actionsClassName:`flex flex-wrap gap-2`,showDisabledReason:!0,disabledReasonClassName:`text-sm text-amber-200`,error:n,errorClassName:`text-sm text-red-200`,renderAction:({action:e,label:t,disabled:n})=>(0,Z.jsx)(_0,{label:t,disabled:n,onClick:()=>r(e.id)},e.id)})},b0=({bundleDetail:e,actionState:t,actionError:n,onAction:r})=>{let{actions:i}=v0(e);return i.length===0?null:(0,Z.jsx)(qW,{actions:i,activeAction:t,disableWhenActive:!0,className:`space-y-3`,heading:`Actions`,headingClassName:`text-[11px] font-semibold uppercase tracking-[0.14em] text-muted-foreground`,actionsClassName:`flex flex-wrap gap-2`,error:n,errorClassName:`text-sm text-red-200`,renderAction:({action:e,label:t,disabled:n})=>(0,Z.jsx)(_0,{label:t,disabled:n,onClick:()=>r(e.id)},e.id)})},x0=(e,t)=>(e??[]).map(e=>({id:e.id,role:e.role,kind:e.kind,content:e.content,created_at:e.created_at,ticket_id:t??null,ticket_proposals:`ticket_proposals`in e?e.ticket_proposals??null:null})),S0=({title:e,subtitle:t,badges:n,backLabel:r,onBack:i,action:a})=>(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-2`,children:[i?(0,Z.jsxs)(q,{variant:`ghost`,size:`sm`,className:`h-8 px-2.5 lg:hidden`,"aria-label":r,onClick:i,children:[(0,Z.jsx)(iT,{className:`h-4 w-4`}),`Back`]}):null,(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium text-foreground`,children:e}),t?(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:t}):null]})]}),a?(0,Z.jsx)(`div`,{className:`shrink-0`,children:a}):null]}),n?(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:n}):null]}),C0=({title:e,backLabel:t,onBack:n,action:r})=>(0,Z.jsxs)(`div`,{className:`-mx-3 flex shrink-0 items-center justify-between gap-3 border-b border-border/80 bg-background/95 px-3 py-2.5 backdrop-blur supports-[backdrop-filter]:bg-background/85 sm:-mx-4 sm:px-4 lg:hidden`,children:[(0,Z.jsxs)(q,{variant:`ghost`,size:`sm`,className:`h-8 px-2.5`,"aria-label":t,onClick:n,children:[(0,Z.jsx)(iT,{className:`h-4 w-4`}),`Back`]}),(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 truncate text-sm font-medium text-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`shrink-0`,children:r})]}),w0=({title:e,backLabel:t,onBack:n,action:r,subheader:i,children:a})=>(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:[(0,Z.jsx)(C0,{title:e,backLabel:t,onBack:n,action:r}),i?(0,Z.jsx)(`div`,{className:`shrink-0 border-b border-border/70 py-2 lg:hidden`,children:i}):null,(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:a})]}),T0=({value:e,onTranscript:t,onDetails:n})=>(0,Z.jsxs)(`div`,{className:`flex gap-2 px-3 sm:px-0`,children:[(0,Z.jsx)(q,{type:`button`,variant:e===`transcript`?`secondary`:`ghost`,className:`h-9 flex-1`,"aria-pressed":e===`transcript`,onClick:t,children:`Transcript`}),(0,Z.jsx)(q,{type:`button`,variant:e===`details`?`secondary`:`ghost`,className:`h-9 flex-1`,"aria-pressed":e===`details`,onClick:n,children:`Details`})]}),E0=({controls:e})=>{let[t,n]=(0,Y.useState)(!1);return(0,Z.jsxs)(td,{open:t,onOpenChange:n,children:[(0,Z.jsx)(`div`,{className:`px-1 pb-1`,children:(0,Z.jsx)(nd,{asChild:!0,children:(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`h-7 gap-1.5 px-2 text-xs text-muted-foreground`,children:[`Options`,(0,Z.jsx)(ke,{className:K(`h-3.5 w-3.5 transition-transform`,t&&`rotate-180`)})]})})}),(0,Z.jsx)(rd,{className:`px-1 pb-1`,children:(0,Z.jsx)(`div`,{className:`rounded-lg border border-border/70 bg-background/35 p-2`,children:e})})]})},D0=({ticket:e})=>{let t=[{label:`State`,value:c0(e)},{label:`Tool`,value:e.tool},{label:`Agent`,value:e.agent_status},{label:`Branch`,value:e.branch},{label:`Bundle`,value:e.bundle?.name??null},{label:`Model`,value:e.model},{label:`Variant`,value:e.variant}].filter(e=>!!e.value);return t.length===0?null:(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-2 rounded-xl border border-border/70 bg-background/40 px-3 py-3`,children:[(0,Z.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-[0.14em] text-muted-foreground`,children:`Details`}),(0,Z.jsx)(`dl`,{className:`grid gap-2 text-sm sm:grid-cols-2`,children:t.map(e=>(0,Z.jsxs)(`div`,{className:`space-y-1 rounded-lg border border-border/60 bg-background/50 px-3 py-2`,children:[(0,Z.jsx)(`dt`,{className:`text-[11px] font-semibold uppercase tracking-[0.14em] text-muted-foreground`,children:e.label}),(0,Z.jsx)(`dd`,{className:`break-words text-foreground`,children:e.value})]},e.label))})]})},O0=({ticket:e,badges:t,actionState:n,actionError:r,onAction:i,className:a})=>(0,Z.jsxs)(gu,{className:K(`flex min-h-0 min-w-0 flex-col border-border/80 bg-card/70 shadow-none`,a),children:[(0,Z.jsx)(_u,{className:`min-w-0 pb-3`,children:(0,Z.jsx)(S0,{title:e.title,badges:t})}),(0,Z.jsxs)(xu,{className:`min-h-0 min-w-0 flex-1 space-y-3 overflow-y-auto pt-0`,children:[(0,Z.jsx)(y0,{ticket:e,actionState:n,actionError:r,onAction:i}),e.description?(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-2 rounded-xl border border-border/70 bg-background/40 px-3 py-3`,children:[(0,Z.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-[0.14em] text-muted-foreground`,children:`Description`}),(0,Z.jsx)(WM,{content:e.description,className:`min-w-0 text-foreground`})]}):null,(0,Z.jsx)(D0,{ticket:e})]})]}),k0=({bundleDetail:e,title:t,subtitle:n,badges:r,actionState:i,actionError:a,onAction:o,orderedTickets:s,highlightedTicketId:c,isTicketListOpen:l,onTicketListOpenChange:u,onSelectTicket:d,className:f})=>(0,Z.jsxs)(gu,{className:K(`flex min-h-0 min-w-0 flex-col border-border/80 bg-card/70 shadow-none`,f),children:[(0,Z.jsx)(_u,{className:`min-w-0 pb-3`,children:(0,Z.jsx)(S0,{title:t,subtitle:n,badges:r})}),(0,Z.jsxs)(xu,{className:`min-h-0 min-w-0 flex-1 space-y-3 overflow-y-auto pt-0`,children:[(0,Z.jsx)(b0,{bundleDetail:e,actionState:i,actionError:a,onAction:o}),(0,Z.jsxs)(td,{open:l,onOpenChange:u,children:[(0,Z.jsx)(nd,{asChild:!0,children:(0,Z.jsxs)(q,{type:`button`,variant:`ghost`,className:`h-8 gap-1.5 px-2 text-xs text-muted-foreground`,children:[`Tickets`,(0,Z.jsx)(ke,{className:K(`h-3.5 w-3.5 transition-transform`,l&&`rotate-180`)})]})}),(0,Z.jsx)(rd,{className:`pt-2`,children:(0,Z.jsx)(`div`,{className:`rounded-xl border border-border/70 bg-background/35 p-3`,children:(0,Z.jsx)(vG,{tickets:s,highlightedTicketId:c,onOpenTicketDetails:e=>d(e.id,e.worktree_bundle_id)})})})]})]})]}),A0=({selectedProjectId:e,bundleId:t,bundleDetail:n,openNonce:r,mobileDetailView:i,error:a,actionState:o,actionError:s,followUpPrompt:c,isSendingFollowUp:l,followUpError:u,availableModels:d,onBack:f,onRetry:p,onAction:m,onDetailViewChange:h,onSelectTicket:g,onFollowUpPromptChange:_,onFollowUpKeyDown:v,onFollowUpSubmit:y,isLargeScreen:b})=>{let[x,S]=(0,Y.useState)(!0);if((0,Y.useEffect)(()=>{S(!0)},[t,r]),!e)return(0,Z.jsx)($1,{title:`Choose a project`,description:`Select a project before opening bundle details from this phone.`});if(!t)return(0,Z.jsx)($1,{title:`Choose a bundle`,description:`Open a bundle to review its transcript and grouped ticket progress.`});if(a)return(0,Z.jsx)(w0,{title:`Bundle unavailable`,backLabel:`Back to tickets`,onBack:f,children:(0,Z.jsx)($1,{title:`Bundle unavailable`,description:a,action:(0,Z.jsx)(q,{variant:`warning`,onClick:p,children:`Retry bundle`})})});if(!n||n.bundle.id!==t)return(0,Z.jsx)(w0,{title:`Loading bundle`,backLabel:`Back to tickets`,onBack:f,children:(0,Z.jsx)(t0,{text:`Loading bundle details...`})});let C=Dl(n.bundle)||n.bundle.branch||n.bundle.name||`Bundle`,w=new Map(d.map(e=>[e.id,e.label])),T=CG(n.tickets,w),E=EG(n),D=wG(n.tickets,n.execution_order_ticket_ids),O=TG(n.tickets,w,T,n.execution_order_ticket_ids),k=dT(n.tickets,E?.state??null),A=n.tickets.find(e=>e.agent_status===`running`)??E,j=A??E??n.tickets[0]??null,M=A?.agent_status===`running`?T[A.id]??A.model??`Agent`:null,N=!!(E&&E.state!==`plan`&&bl(E)),P=n.tickets.some(e=>e.agent_status===`running`)?`Wait for all bundle tickets to finish building before sending a follow-up prompt.`:void 0,F=`mobile-bundle:${n.bundle.id}:${r}`,I=`${n.tickets.length} ticket${n.tickets.length===1?``:`s`}`,L=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(oT,{status:k}),(0,Z.jsx)(U,{variant:`outline`,children:I}),j?(0,Z.jsxs)(U,{variant:`outline`,children:[`Target: `,j.title]}):null]});return(0,Z.jsx)(w0,{title:C,backLabel:`Back to tickets`,onBack:f,subheader:b?void 0:(0,Z.jsx)(T0,{value:i,onTranscript:()=>h(`transcript`),onDetails:()=>h(`details`)}),children:b?(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 flex-col gap-3 overflow-hidden pt-3`,children:[(0,Z.jsx)(k0,{bundleDetail:n,title:C,subtitle:n.bundle.branch,badges:L,actionState:o,actionError:s,onAction:m,orderedTickets:D,highlightedTicketId:n.target_ticket_id,isTicketListOpen:x,onTicketListOpenChange:S,onSelectTicket:g,className:`shrink-0`}),(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:(0,Z.jsx)(hG,{projectId:e,followUpTicketId:n.target_ticket_id,messages:O,internalLog:A?.agent_log??null,currentThinkingMessageId:A?.agent_message_id??E?.agent_message_id??null,legacyThinkingTicketId:A?.id??E?.id??null,previousThinkingLog:A?.previous_agent_log??E?.previous_agent_log??null,previousThinkingMessageId:A?.previous_agent_message_id??E?.previous_agent_message_id??null,pendingAgentTitle:M,streamingResponse:A?.streaming_response??null,isRunning:n.tickets.some(e=>e.agent_status===`running`),canShowComposer:N,composerTheme:Tw(E?.state??null),layoutKey:F,scrollLayoutKey:F,followUpPrompt:c,followUpPlaceholder:j?`Follow up on: ${j.title}`:`Follow up on this bundle`,isSendingFollowUp:l,followUpDisabledReason:P,onFollowUpPromptChange:_,onFollowUpKeyDown:v,onFollowUpSubmit:y},F)}),u?(0,Z.jsx)(`p`,{className:`shrink-0 text-sm text-red-200`,children:u}):null]}):i===`details`?(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:(0,Z.jsx)(k0,{bundleDetail:n,title:C,subtitle:n.bundle.branch,badges:L,actionState:o,actionError:s,onAction:m,orderedTickets:D,highlightedTicketId:n.target_ticket_id,isTicketListOpen:x,onTicketListOpenChange:S,onSelectTicket:g,className:`h-full`})}):(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:[(0,Z.jsx)(hG,{projectId:e,followUpTicketId:n.target_ticket_id,messages:O,internalLog:A?.agent_log??null,currentThinkingMessageId:A?.agent_message_id??E?.agent_message_id??null,legacyThinkingTicketId:A?.id??E?.id??null,previousThinkingLog:A?.previous_agent_log??E?.previous_agent_log??null,previousThinkingMessageId:A?.previous_agent_message_id??E?.previous_agent_message_id??null,pendingAgentTitle:M,streamingResponse:A?.streaming_response??null,isRunning:n.tickets.some(e=>e.agent_status===`running`),canShowComposer:N,composerTheme:Tw(E?.state??null),layoutKey:F,scrollLayoutKey:F,followUpPrompt:c,followUpPlaceholder:j?`Follow up on: ${j.title}`:`Follow up on this bundle`,isSendingFollowUp:l,followUpDisabledReason:P,onFollowUpPromptChange:_,onFollowUpKeyDown:v,onFollowUpSubmit:y},F),u?(0,Z.jsx)(`p`,{className:`shrink-0 px-1 pt-2 text-sm text-red-200`,children:u}):null]})})},j0=({selectedProjectId:e,chatSession:t,chatSessionId:n,openNonce:r,error:i,isStopping:a,composerMode:o,composerTool:s,prompt:c,selectedModel:l,selectedVariant:u,selectedSkills:d,availableModels:f,availableSkills:p,isLoadingAgentSettings:m,isSending:h,isUpdatingMode:g,composerDisabledReason:_,onBack:v,onRetry:y,onStop:b,onModeChange:x,onPromptChange:S,onModelChange:C,onVariantChange:w,onSkillsChange:T,onPromptKeyDown:E,onSubmit:D,isLargeScreen:O})=>{if(!e)return(0,Z.jsx)($1,{title:`Choose a project`,description:`Select a project before opening the chat workspace.`});if(n&&i)return(0,Z.jsx)($1,{title:`Chat unavailable`,description:i,action:(0,Z.jsx)(q,{variant:`warning`,onClick:y,children:`Retry chat`})});if(n&&(!t||t.id!==n))return(0,Z.jsx)(w0,{title:`Loading chat`,backLabel:`Back to chats`,onBack:v,children:(0,Z.jsx)(t0,{text:`Loading chat transcript...`})});let k=t?.mode??o,A=s===`opencode`&&f.length>0,j=f.find(e=>e.id===l)??null,M=x0(t?.messages),N=t?.agent_status===`running`?(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`outline`,className:`gap-2`,disabled:a,onClick:b,children:[a?(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}):(0,Z.jsx)(Fc,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:a?`Interrupting...`:`Interrupt`})]}):null,P=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(U,{variant:k===`plan`?`info`:`success`,children:k}),(0,Z.jsx)(U,{variant:`outline`,children:t?.tool??s}),t?.agent_status?(0,Z.jsx)(U,{variant:`outline`,children:t.agent_status}):null]}),F=A?(0,Z.jsx)(CP,{model:l,variant:u,skills:d,showModelSelector:!0,showSkillsSelector:!0,availableModels:f,availableSkills:p,selectedModel:j,onModelChange:C,onVariantChange:w,onSkillsChange:T,modelSelectId:`mobile-chat-model-selector`,variantSelectId:`mobile-chat-variant-selector`,skillsSelectId:`mobile-chat-skills-selector`,disabled:!!_||h}):s===`opencode`&&m?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading model controls...`}):null,I=!O&&F?(0,Z.jsx)(E0,{controls:F}):F,L=(0,Z.jsx)(`div`,{className:`flex flex-wrap items-center gap-2`,children:(0,Z.jsx)(GX,{value:k,disabled:!!_||h||g,onChange:x})}),R=O?void 0:({showThinkingControl:e})=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 py-1`,children:[L,(0,Z.jsx)(`div`,{className:`ml-auto`,children:e})]}),z=`mobile-chat:${n??`new`}:${r}`;return(0,Z.jsx)(w0,{title:t?.title??`New chat`,backLabel:`Back to chats`,onBack:v,action:N,children:(0,Z.jsx)(WX,{projectId:e,messages:M,internalLog:t?.agent_log??null,currentThinkingMessageId:t?.agent_message_id??null,previousThinkingLog:t?.previous_agent_log??null,previousThinkingMessageId:t?.previous_agent_message_id??null,pendingAgentTitle:t?.title??`Archon`,streamingResponse:t?.streaming_response??null,isRunning:t?.agent_status===`running`,canShowComposer:!0,header:O?(0,Z.jsx)(S0,{title:t?.title??`New chat`,subtitle:t?.target_label_snapshot??`Project root`,badges:P}):R,composerControls:O?L:void 0,composerInlineControls:I,composerTheme:k,forceScrollToBottomKey:z,layoutKey:z,scrollLayoutKey:z,composerFocusNonce:r,blurComposerOnSendStart:!O,followUpPrompt:c,followUpPlaceholder:n?`Continue this chat`:k===`plan`?`Ask Archon to scope or reason through project work`:`Ask Archon to build or verify something in this project`,emptyStateText:n?`No messages yet.`:`Start a new project chat from this phone.`,isSendingFollowUp:h,followUpDisabledReason:_??void 0,hidePendingAgentTitle:!O,onFollowUpPromptChange:S,onFollowUpKeyDown:E,onFollowUpSubmit:D},z)})},M0=({selectedProjectId:e,ticketId:t,ticket:n,openNonce:r,error:i,actionState:a,actionError:o,followUpPrompt:s,followUpSelectedModel:c,followUpSelectedVariant:l,followUpSelectedSkills:u,availableModels:d,availableSkills:f,isLoadingAgentSettings:p,isSendingFollowUp:m,followUpError:h,onBack:g,onRetry:_,onAction:v,onFollowUpPromptChange:y,onFollowUpModelChange:b,onFollowUpVariantChange:x,onFollowUpSkillsChange:S,onFollowUpKeyDown:C,onFollowUpSubmit:w,isLargeScreen:T})=>{let[E,D]=(0,Y.useState)(`transcript`);if((0,Y.useEffect)(()=>{D(`transcript`)},[r,t]),!e)return(0,Z.jsx)($1,{title:`Choose a project`,description:`Select a project before opening ticket details from this phone.`});if(!t)return(0,Z.jsx)($1,{title:`Choose a ticket`,description:`Open a ticket to review its transcript and continue the workflow.`});if(i)return(0,Z.jsx)($1,{title:`Ticket unavailable`,description:i,action:(0,Z.jsx)(q,{variant:`warning`,onClick:_,children:`Retry ticket`})});if(!n||n.id!==t)return(0,Z.jsx)(w0,{title:`Loading ticket`,backLabel:`Back to tickets`,onBack:g,children:(0,Z.jsx)(t0,{text:`Loading ticket details...`})});let O=XW(n,{requireWorktree:!0}),k=x0(n.messages,n.id),A=d.find(e=>e.id===c)??null,j=n.tool===`opencode`&&d.length>0?(0,Z.jsx)(CP,{model:c,variant:l,skills:u,showModelSelector:!0,showSkillsSelector:!0,availableModels:d,availableSkills:f,selectedModel:A,onModelChange:b,onVariantChange:x,onSkillsChange:S,modelSelectId:`mobile-ticket-follow-up-model-selector`,variantSelectId:`mobile-ticket-follow-up-variant-selector`,skillsSelectId:`mobile-ticket-follow-up-skills-selector`,disabled:!!O.disabledReason||m}):n.tool===`opencode`&&p?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading model controls...`}):null,M=!T&&j?(0,Z.jsx)(E0,{controls:j}):j,N=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(U,{variant:l0(s0(n)),children:c0(n)}),n.tool?(0,Z.jsx)(U,{variant:`outline`,children:n.tool}):null,n.agent_status?(0,Z.jsx)(U,{variant:`outline`,children:n.agent_status}):null,n.branch?(0,Z.jsx)(U,{variant:`outline`,children:n.branch}):null,n.bundle?.name?(0,Z.jsx)(U,{variant:`outline`,children:n.bundle.name}):null]}),P=`mobile-ticket:${n.id}:${r}`,F=(0,Z.jsx)(T0,{value:E,onTranscript:()=>D(`transcript`),onDetails:()=>D(`details`)});return(0,Z.jsx)(w0,{title:n.title,backLabel:`Back to tickets`,onBack:g,subheader:T?void 0:F,children:T?(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 flex-col gap-3 overflow-hidden pt-3`,children:[(0,Z.jsx)(O0,{ticket:n,badges:N,actionState:a,actionError:o,onAction:v,className:`shrink-0`}),(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:(0,Z.jsx)(WN,{projectId:e,followUpTicketId:n.id,messages:k,internalLog:n.agent_log??null,currentThinkingMessageId:n.agent_message_id??null,previousThinkingLog:n.previous_agent_log??null,previousThinkingMessageId:n.previous_agent_message_id??null,pendingAgentTitle:n.title,streamingResponse:n.streaming_response??null,isRunning:n.agent_status===`running`,canShowComposer:!0,followUpComposerControls:j,composerTheme:n.state,forceScrollToBottomKey:P,layoutKey:P,scrollLayoutKey:P,followUpPrompt:s,followUpPlaceholder:O.placeholder,emptyStateText:`No follow-up messages yet.`,isSendingFollowUp:m,followUpDisabledReason:O.disabledReason??void 0,onFollowUpPromptChange:y,onFollowUpKeyDown:C,onFollowUpSubmit:w},P)}),h?(0,Z.jsx)(`p`,{className:`shrink-0 text-sm text-red-200`,children:h}):null]}):E===`details`?(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:(0,Z.jsx)(O0,{ticket:n,badges:N,actionState:a,actionError:o,onAction:v,className:`h-full`})}):(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:[(0,Z.jsx)(WN,{projectId:e,followUpTicketId:n.id,messages:k,internalLog:n.agent_log??null,currentThinkingMessageId:n.agent_message_id??null,previousThinkingLog:n.previous_agent_log??null,previousThinkingMessageId:n.previous_agent_message_id??null,pendingAgentTitle:n.title,streamingResponse:n.streaming_response??null,isRunning:n.agent_status===`running`,canShowComposer:!0,followUpComposerControls:M,composerTheme:n.state,surfaceVariant:`chat`,composerSize:`compact-on-laptop`,forceScrollToBottomKey:P,layoutKey:P,scrollLayoutKey:P,followUpPrompt:s,followUpPlaceholder:O.placeholder,emptyStateText:`No follow-up messages yet.`,isSendingFollowUp:m,followUpDisabledReason:O.disabledReason??void 0,onFollowUpPromptChange:y,onFollowUpKeyDown:C,onFollowUpSubmit:w},P),h?(0,Z.jsx)(`p`,{className:`shrink-0 px-1 pt-2 text-sm text-red-200`,children:h}):null]})})},N0=()=>{let e=new URLSearchParams(window.location.search),t=new URLSearchParams(window.location.hash.slice(1)),n=e.get(`mobileAccessId`)??``,r=e.get(`pairingId`)??``,i=t.get(`pairingSecret`)??``;return!n||!r||!i?null:{mobileAccessId:n,pairingId:r,pairingSecret:i}},P0=()=>{window.history.replaceState({},``,`/mobile`)},F0=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},I0=(e,t)=>e instanceof I&&e.message?e.message:t,L0=e=>({status:`authenticated`,csrfToken:e,projects:null,selectedProjectId:null,projectError:null,projectSummary:null,projectSummaryError:null,chatSessions:null,chatSessionsError:null,selectedChatSessionId:null,chatSessionDetail:null,chatSessionDetailError:null,tickets:null,ticketsError:null,selectedBundleId:null,bundleDetail:null,bundleDetailError:null,selectedTicketId:null,ticketDetail:null,ticketDetailError:null}),R0=(e=`pairing_required`)=>({status:`unauthenticated`,reason:e}),z0=e=>e instanceof I&&(e.status===401||e.status===403),B0=()=>{let[e,t]=(0,Y.useState)({status:`checking`}),[n,r]=(0,Y.useState)(`connecting`),[i,a]=(0,Y.useState)(`overview`),[o,s]=(0,Y.useState)(!1),[c,l]=(0,Y.useState)(!1),[u,d]=(0,Y.useState)(!1),[f,p]=(0,Y.useState)(!1),[m,h]=(0,Y.useState)(!1),[g,_]=(0,Y.useState)(!1),[v,y]=(0,Y.useState)(``),[b,x]=(0,Y.useState)(`build`),[S,C]=(0,Y.useState)(``),[w,T]=(0,Y.useState)(``),[E,D]=(0,Y.useState)([]),[O,k]=(0,Y.useState)([]),[A,j]=(0,Y.useState)([]),[M,N]=(0,Y.useState)(!1),[P,F]=(0,Y.useState)(!1),[L,R]=(0,Y.useState)(!1),[ee,te]=(0,Y.useState)(null),[ne,re]=(0,Y.useState)(null),[B,ie]=(0,Y.useState)(null),[V,H]=(0,Y.useState)(null),[ae,oe]=(0,Y.useState)(null),[se,ce]=(0,Y.useState)(null),[le,ue]=(0,Y.useState)(``),[de,U]=(0,Y.useState)(``),[fe,pe]=(0,Y.useState)(``),[me,W]=(0,Y.useState)([]),[he,G]=(0,Y.useState)(!1),[ge,_e]=(0,Y.useState)(null),[ve,ye]=(0,Y.useState)(``),[be,xe]=(0,Y.useState)(!1),[Se,Ce]=(0,Y.useState)(null),[we,Te]=(0,Y.useState)(0),[Ee,De]=(0,Y.useState)(0),[Oe,ke]=(0,Y.useState)(0),[Ae,je]=(0,Y.useState)(`transcript`),[Me,Ne]=(0,Y.useState)(null),[Pe,Fe]=(0,Y.useState)(null),[Ie,Le]=(0,Y.useState)(!1),[Re,ze]=(0,Y.useState)(!1),[Be,Ve]=(0,Y.useState)(!1),[He,Ue]=(0,Y.useState)(null),[We,Ge]=(0,Y.useState)(null),Ke=(0,Y.useRef)(null),qe=(0,Y.useRef)(null),Je=(0,Y.useRef)(null),Ye=(0,Y.useRef)(null),Xe=(0,Y.useCallback)(e=>z0(e)?(t(R0(`session_revoked`)),r(`unavailable`),s(!1),l(!1),d(!1),p(!1),!0):!1,[]),Ze=(0,Y.useCallback)(async(e,n,r,i)=>{try{let a=await o1(n,r,i);t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n||t.selectedTicketId!==r?t:{...t,ticketDetail:a,ticketDetailError:null})}catch(i){if(!z(i)){if(Xe(i))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n||t.selectedTicketId!==r?t:{...t,ticketDetail:null,ticketDetailError:I0(i,`Unable to load ticket details.`)})}}},[Xe]),Qe=(0,Y.useCallback)(async(e,n,r,i)=>{try{let a=await s1(n,r,i);t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n||t.selectedBundleId!==r?t:{...t,bundleDetail:a,bundleDetailError:null,tickets:m0(t.tickets,a)})}catch(i){if(!z(i)){if(Xe(i))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n||t.selectedBundleId!==r?t:{...t,bundleDetail:null,bundleDetailError:I0(i,`Unable to load bundle details.`)})}}},[Xe]),$e=(0,Y.useCallback)(async(e,n,r)=>{try{let i=await a1(n,r);t(t=>{if(t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n)return t;let r=t.selectedTicketId&&i.some(e=>e.id===t.selectedTicketId)?t.selectedTicketId:null,a=t.selectedBundleId&&i.some(e=>e.worktree_bundle_id===t.selectedBundleId)?t.selectedBundleId:null;return{...t,tickets:i,ticketsError:null,selectedBundleId:a,bundleDetail:a?t.bundleDetail:null,bundleDetailError:a?t.bundleDetailError:null,selectedTicketId:r,ticketDetail:r?t.ticketDetail:null,ticketDetailError:r?t.ticketDetailError:null}})}catch(r){if(!z(r)){if(Xe(r))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n?t:{...t,tickets:null,ticketsError:I0(r,`Unable to load project tickets.`),selectedBundleId:null,bundleDetail:null,bundleDetailError:null,selectedTicketId:null,ticketDetail:null,ticketDetailError:null})}}},[Xe]),et=(0,Y.useCallback)(async(e,n,r,i)=>{try{let a=await i1(n,r,i);t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n||t.selectedChatSessionId!==r?t:{...t,chatSessionDetail:a,chatSessionDetailError:null})}catch(i){if(!z(i)){if(Xe(i))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n||t.selectedChatSessionId!==r?t:{...t,chatSessionDetail:null,chatSessionDetailError:I0(i,`Unable to load chat transcript.`)})}}},[Xe]),J=(0,Y.useCallback)(async(e,n,r)=>{try{let i=await r1(n,r);t(t=>{if(t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n)return t;let r=t.selectedChatSessionId&&i.some(e=>e.id===t.selectedChatSessionId)?t.selectedChatSessionId:null;return{...t,chatSessions:i,chatSessionsError:null,selectedChatSessionId:r,chatSessionDetail:r?t.chatSessionDetail:null,chatSessionDetailError:r?t.chatSessionDetailError:null}})}catch(r){if(!z(r)){if(Xe(r))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n?t:{...t,chatSessions:null,chatSessionsError:I0(r,`Unable to load project chats.`),selectedChatSessionId:null,chatSessionDetail:null,chatSessionDetailError:null})}}},[Xe]),tt=(0,Y.useCallback)(async(e,n,r)=>{try{let i=await t1(n,r);t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n?t:{...t,projectSummary:i,projectSummaryError:null})}catch(r){if(!z(r)){if(Xe(r))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n?t:{...t,projectSummary:null,projectSummaryError:I0(r,`Unable to load the project summary.`)})}}},[Xe]),nt=(0,Y.useCallback)(async(e,t,n)=>{ze(!0);try{let e=await n1(t,n),r=Ke.current;if(r&&r!==t)return;Ne(e),Fe(null),Ue(null)}catch(e){if(!z(e)){if(Xe(e))return;let n=Ke.current;if(n&&n!==t)return;Ne(null),Fe(I0(e,`Unable to load project target options.`))}}finally{n?.aborted||ze(!1)}},[Xe]),rt=(0,Y.useCallback)(e=>{t(t=>t.status===`authenticated`?{...t,projects:t.projects?.map(t=>t.id===e.id?e:t)??t.projects,projectSummary:t.projectSummary?.project.id===e.id?{...t.projectSummary,project:e}:t.projectSummary}:t)},[]),it=(0,Y.useCallback)(async(e,n,r)=>{try{let i=await e1(n),a=r&&i.some(e=>e.id===r)?r:i[0]?.id??null;t(t=>{if(t.status!==`authenticated`||t.csrfToken!==e)return t;let n=!!(t.selectedProjectId&&a&&t.selectedProjectId===a);return{...t,projects:i,selectedProjectId:a,projectError:null,projectSummary:n?t.projectSummary:null,projectSummaryError:n?t.projectSummaryError:null,chatSessions:n?t.chatSessions:null,chatSessionsError:n?t.chatSessionsError:null,selectedChatSessionId:n?t.selectedChatSessionId:null,chatSessionDetail:n?t.chatSessionDetail:null,chatSessionDetailError:n?t.chatSessionDetailError:null,tickets:n?t.tickets:null,ticketsError:n?t.ticketsError:null,selectedBundleId:n?t.selectedBundleId:null,bundleDetail:n?t.bundleDetail:null,bundleDetailError:n?t.bundleDetailError:null,selectedTicketId:n?t.selectedTicketId:null,ticketDetail:n?t.ticketDetail:null,ticketDetailError:n?t.ticketDetailError:null}});let o=a?i.find(e=>e.id===a)??null:null;a&&(tt(e,a,n),o?.active_target_kind===`bundle`&&nt(e,a,n),J(e,a,n),$e(e,a,n))}catch(n){if(!z(n)){if(Xe(n))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e?t:{...t,projects:t.projects??[],projectError:I0(n,`Unable to load projects from desktop Archon.`)})}}},[Xe,J,tt,nt,$e]),at=(0,Y.useCallback)(async e=>{t({status:`checking`}),r(`connecting`);try{let n=await D1(e);if(n.authenticated&&n.csrf_token){r(`connecting`),t(L0(n.csrf_token)),it(n.csrf_token,e,n.preferred_project_id);return}t(R0())}catch(e){z(e)||t({status:`error`,message:I0(e,`Mobile access is unavailable. Make sure it is still enabled on desktop Archon.`)})}},[it]),ot=(0,Y.useCallback)((e,n,i)=>{r(`connecting`),t(L0(e)),it(e,i,n)},[it]);(0,Y.useEffect)(()=>{let e=new AbortController;if(window.location.pathname===`/mobile/pair`){let n=N0();return P0(),n?(t({status:`pairing`}),O1(n,e.signal).then(e=>{t({status:`pairing_confirmation`,payload:n,displayCode:e.display_code,expiresAt:e.expires_at,error:null})}).catch(e=>{t({status:`error`,message:I0(e,`Pairing failed. Regenerate the pairing link from desktop Archon and try again.`)})}),()=>e.abort()):(t({status:`error`,message:`Pairing link is missing required pairing details.`}),()=>e.abort())}return at(e.signal),()=>e.abort()},[ot,at]);let st=e.status===`authenticated`?e.csrfToken:null,ct=e.status===`authenticated`?e.selectedProjectId:null,lt=e.status===`authenticated`?e.selectedChatSessionId:null,ut=e.status===`authenticated`?e.selectedBundleId:null,dt=e.status===`authenticated`?e.selectedTicketId:null,ft=e.status===`authenticated`?e.projects?.find(t=>t.id===e.selectedProjectId)??null:null,pt=e.status===`authenticated`?e.chatSessionDetail:null,mt=e.status===`authenticated`?e.bundleDetail:null,ht=e.status===`authenticated`?e.ticketDetail:null,gt=B1(ft,Me),_t=Re&&(!ft||ft.active_target_kind===`bundle`),vt=G1(),yt=pt?.tool??`opencode`,bt=e.status!==`authenticated`||!e.selectedProjectId?`Choose a project before sending a prompt.`:L?`Wait for the chat mode change before sending another prompt.`:pt?.agent_status===`running`?`Stop or wait for the current response before sending another prompt.`:null,X=!vt&&(i===`tickets`&&(u&&!!dt||c&&!!ut)||i===`chats`&&f);(0,Y.useEffect)(()=>{Ke.current=ct},[ct]),(0,Y.useEffect)(()=>{ct||(Ne(null),Fe(null),Ue(null),Le(!1),ze(!1),Ve(!1))},[ct]),(0,Y.useEffect)(()=>{qe.current=lt},[lt]),(0,Y.useEffect)(()=>{Je.current=ut},[ut]),(0,Y.useEffect)(()=>{Ye.current=dt},[dt]),(0,Y.useEffect)(()=>{if(!st||!ct){k([]),j([]),N(!1);return}if(!(yt===`opencode`||ht?.tool===`opencode`)){k([]),j([]),N(!1);return}let e=new AbortController;return N(!0),Promise.all([T1(`opencode`,e.signal),E1(`opencode`,ct,e.signal)]).then(([e,t])=>{k(e),j(t)}).catch(e=>{Xe(e)||z(e)||(k([]),j([]))}).finally(()=>{e.signal.aborted||N(!1)}),()=>e.abort()},[st,yt,Xe,ct,ht?.tool]),(0,Y.useEffect)(()=>{if(yt!==`opencode`){C(``),T(``),D([]);return}C(pt?.model??ft?.helper_model??``),T(pt?.variant??ft?.helper_variant??``),D(pt?.skills??[])},[yt,pt?.id,pt?.model,pt?.skills,pt?.variant,ft?.helper_model,ft?.helper_variant]),(0,Y.useEffect)(()=>{pt?.mode&&x(pt.mode)},[pt?.id,pt?.mode]),(0,Y.useEffect)(()=>{let e=O.find(e=>e.id===S)??null;T(t=>e?e.variants.includes(t)?t:``:t)},[O,S]),(0,Y.useEffect)(()=>{ue(``),_e(null),U(ht?.model??``),pe(ht?.variant??``),W(ht?.skills??[])},[ht?.id,ht?.model,ht?.skills,ht?.variant]),(0,Y.useEffect)(()=>{ye(``),Ce(null)},[mt?.bundle.id]),(0,Y.useEffect)(()=>{let e=O.find(e=>e.id===de)??null;pe(t=>e?e.variants.includes(t)?t:``:t)},[O,de]),(0,Y.useEffect)(()=>{if(!st)return;let e=j1();r(`connecting`);let t=()=>{let e=Ke.current,t=qe.current,n=Je.current,r=Ye.current;it(st,void 0,e),e&&(tt(st,e),J(st,e),$e(st,e)),e&&t&&et(st,e,t),e&&n&&Qe(st,e,n),e&&r&&Ze(st,e,r)},n=()=>{r(`connected`),t()},i=()=>{r(`reconnecting`)},a=()=>{r(`unavailable`)},o=()=>{it(st,void 0,Ke.current)},s=(e=null)=>{let t=Ke.current;t&&(e?.project_id&&e.project_id!==t||tt(st,t))},c=(e=null)=>{let t=Ke.current;t&&(e?.project_id&&e.project_id!==t||J(st,t))},l=(e=null)=>{let t=Ke.current;t&&(e?.project_id&&e.project_id!==t||$e(st,t))},u=(e=null)=>{let t=Ke.current,n=qe.current;!t||!n||e?.project_id&&e.project_id!==t||e?.id&&e.id!==n||et(st,t,n)},d=(e=null)=>{let t=Ke.current,n=Ye.current;!t||!n||e?.project_id&&e.project_id!==t||e?.id&&e.id!==n||Ze(st,t,n)},f=(e=null)=>{let t=Ke.current,n=Je.current;!t||!n||e?.project_id&&e.project_id!==t||Qe(st,t,n)};return e.on(`connect`,n),e.on(`disconnect`,i),e.on(`connect_error`,a),e.on(`ticket:created`,s),e.on(`ticket:created`,l),e.on(`ticket:updated`,s),e.on(`ticket:updated`,l),e.on(`ticket:updated`,f),e.on(`ticket:updated`,d),e.on(`ticket:deleted`,o),e.on(`ticket:deleted`,l),e.on(`ticket:deleted`,f),e.on(`ticket-dependency:created`,s),e.on(`ticket-dependency:deleted`,s),e.on(`chat-session:created`,c),e.on(`chat-session:updated`,c),e.on(`chat-session:updated`,u),e.on(`chat-session:deleted`,c),()=>{e.off(`connect`,n),e.off(`disconnect`,i),e.off(`connect_error`,a),e.off(`ticket:created`,s),e.off(`ticket:created`,l),e.off(`ticket:updated`,s),e.off(`ticket:updated`,l),e.off(`ticket:updated`,f),e.off(`ticket:updated`,d),e.off(`ticket:deleted`,o),e.off(`ticket:deleted`,l),e.off(`ticket:deleted`,f),e.off(`ticket-dependency:created`,s),e.off(`ticket-dependency:deleted`,s),e.off(`chat-session:created`,c),e.off(`chat-session:updated`,c),e.off(`chat-session:updated`,u),e.off(`chat-session:deleted`,c),e.disconnect()}},[st,Qe,et,J,tt,it,Ze,$e]),(0,Y.useEffect)(()=>{ut||l(!1)},[ut]),(0,Y.useEffect)(()=>{dt||d(!1)},[dt]);let xt=()=>{at()},St=e=>{a(e),l(!1),d(!1),p(!1),Ge(null)},Ct=()=>{s(!0)},wt=()=>{e.status!==`authenticated`||!e.selectedProjectId||(Ue(null),Le(!0),!Me&&!Re&&nt(e.csrfToken,e.selectedProjectId))},Tt=()=>{e.status===`authenticated`&&(h(!0),A1(e.csrfToken).then(()=>t(R0())).catch(e=>{Xe(e)||t({status:`error`,message:I0(e,`Logout failed. Mobile access may have already been revoked from desktop Archon.`)})}).finally(()=>h(!1)))},Et=()=>{if(e.status!==`pairing_confirmation`||g)return;let n=e.payload;_(!0),t({...e,error:null}),k1(n).then(e=>{if(e.authenticated&&e.csrf_token){window.history.replaceState({},``,`/mobile`),ot(e.csrf_token,e.preferred_project_id);return}t(R0())}).catch(e=>{t(t=>t.status===`pairing_confirmation`?{...t,error:I0(e,`Pairing failed. Regenerate the pairing link from desktop Archon and try again.`)}:t)}).finally(()=>_(!1))},Dt=()=>{window.history.replaceState({},``,`/mobile`),t(R0())},Ot=()=>{e.status===`authenticated`&&(t({...e,projects:null,projectError:null}),it(e.csrfToken))},kt=()=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,projectSummary:null,projectSummaryError:null}),tt(e.csrfToken,e.selectedProjectId))},At=()=>{e.status!==`authenticated`||!e.selectedProjectId||(Ne(null),Fe(null),Ue(null),nt(e.csrfToken,e.selectedProjectId))},jt=()=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,chatSessions:null,chatSessionsError:null,selectedChatSessionId:null,chatSessionDetail:null,chatSessionDetailError:null}),J(e.csrfToken,e.selectedProjectId))},Mt=()=>{e.status!==`authenticated`||!e.selectedProjectId||!e.selectedChatSessionId||(t({...e,chatSessionDetail:null,chatSessionDetailError:null}),et(e.csrfToken,e.selectedProjectId,e.selectedChatSessionId))},Nt=()=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,tickets:null,ticketsError:null,selectedBundleId:null,bundleDetail:null,bundleDetailError:null,selectedTicketId:null,ticketDetail:null,ticketDetailError:null}),$e(e.csrfToken,e.selectedProjectId))},Pt=()=>{e.status!==`authenticated`||!e.selectedProjectId||!e.selectedTicketId||(t({...e,ticketDetail:null,ticketDetailError:null}),Ze(e.csrfToken,e.selectedProjectId,e.selectedTicketId))},Ft=()=>{e.status!==`authenticated`||!e.selectedProjectId||!e.selectedBundleId||(t({...e,bundleDetail:null,bundleDetailError:null}),Qe(e.csrfToken,e.selectedProjectId,e.selectedBundleId))},It=n=>{if(e.status!==`authenticated`)return;let r=e.projects?.find(e=>e.id===n)??null;Ke.current=n,t({...e,selectedProjectId:n,projectSummary:null,projectSummaryError:null,chatSessions:null,chatSessionsError:null,selectedChatSessionId:null,chatSessionDetail:null,chatSessionDetailError:null,tickets:null,ticketsError:null,selectedBundleId:null,bundleDetail:null,bundleDetailError:null,selectedTicketId:null,ticketDetail:null,ticketDetailError:null}),ie(null),H(null),oe(null),ce(null),re(null),ce(null),setStopRunError(null),Ce(null),Ne(null),Fe(null),Ue(null),s(!1),Le(!1),l(!1),d(!1),p(!1),je(`transcript`),Ge(null),a(`overview`),tt(e.csrfToken,n),r?.active_target_kind===`bundle`&&nt(e.csrfToken,n),J(e.csrfToken,n),$e(e.csrfToken,n)},Lt=async t=>{if(!(e.status!==`authenticated`||!e.selectedProjectId)){Ve(!0),Ue(null);try{rt(await w1(e.selectedProjectId,e.csrfToken,{kind:`bundle`,bundle_id:t})),Le(!1),tt(e.csrfToken,e.selectedProjectId),nt(e.csrfToken,e.selectedProjectId)}catch(e){if(Xe(e))return;Ue(I0(e,`Unable to update the project target right now.`))}finally{Ve(!1)}}},Rt=async(t,n={})=>{if(e.status!==`authenticated`||!e.selectedProjectId)return;Ve(!0),Ue(null);let r=r=>w1(e.selectedProjectId??``,e.csrfToken,{kind:`repo_root`,...t?{branch:t}:{},...n.createBranch===!1?{create_branch:!1}:{},...r?{confirm_dirty_switch:!0}:{}});try{let t;try{t=await r(n.confirmDirtySwitch===!0)}catch(e){if(!n.confirmDirtySwitch&&e instanceof I&&e.status===409&&e.message===L1){if(!window.confirm(`${L1}\n\nSwitch anyway?`))return;t=await r(!0)}else throw e}rt(t),Le(!1),tt(e.csrfToken,e.selectedProjectId),nt(e.csrfToken,e.selectedProjectId)}catch(e){if(Xe(e))return;Ue(I0(e,`Unable to update the project target right now.`))}finally{Ve(!1)}},zt=n=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,selectedChatSessionId:n,chatSessionDetail:null,chatSessionDetailError:null}),re(null),Te(e=>e+1),p(!0),a(`chats`),et(e.csrfToken,e.selectedProjectId,n))},Bt=()=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,selectedChatSessionId:null,chatSessionDetail:null,chatSessionDetailError:null}),re(null),y(``),Te(e=>e+1),p(!0),a(`chats`))},Vt=n=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,selectedBundleId:n,bundleDetail:null,bundleDetailError:null,selectedTicketId:null,ticketDetail:null,ticketDetailError:null}),ie(null),H(null),ce(null),Ce(null),Ge(null),je(`transcript`),De(e=>e+1),l(!0),d(!1),a(`tickets`),Qe(e.csrfToken,e.selectedProjectId,n))},Ht=(n,r)=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,selectedTicketId:n,ticketDetail:null,ticketDetailError:null}),Ge(r),ke(e=>e+1),l(r!==null),d(!0),a(`tickets`),Ze(e.csrfToken,e.selectedProjectId,n))},Ut=()=>{p(!1)},Wt=n=>{if(e.status!==`authenticated`||!e.selectedProjectId)return;if(!e.chatSessionDetail||!e.selectedChatSessionId){x(n);return}if(e.chatSessionDetail.mode===n||L)return;let r=e.selectedProjectId,i=e.selectedChatSessionId,a=e.csrfToken;R(!0),re(null),p1(r,i,a,{mode:n}).then(e=>{x(e.mode),t(t=>{if(t.status!==`authenticated`||t.selectedProjectId!==r||t.selectedChatSessionId!==i)return t;let n=t.chatSessions?.map(t=>t.id===e.id?e:t)??t.chatSessions;return{...t,chatSessions:n,chatSessionDetail:e,chatSessionDetailError:null}})}).catch(e=>{Xe(e)||re(I0(e,`Unable to update the chat mode right now.`))}).finally(()=>R(!1))},Gt=()=>{if(e.status===`authenticated`&&We&&e.selectedBundleId===We){t({...e,selectedTicketId:null,ticketDetail:null,ticketDetailError:null}),d(!1),l(!0),Ge(null);return}Ge(null),d(!1)},Kt=()=>{l(!1)},qt=e=>{let t=O.find(t=>t.id===e)??null;C(e),T(e=>t&&t.variants.includes(e)?e:``)},Jt=e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),Yt())},Yt=()=>{if(e.status!==`authenticated`||!e.selectedProjectId||P||bt)return;let n=v.trim();if(!n)return;let r=e.selectedProjectId,i=e.csrfToken,a=yt===`opencode`&&S?S:null,o=yt===`opencode`&&S&&w?w:null,s=yt===`opencode`?E:[];re(null),F(!0);let c=e=>f1(r,e.id,i,{instruction:n,tool:e.tool,model:a,variant:o,skills:s});(e.chatSessionDetail?c(e.chatSessionDetail):d1(r,i,{mode:b,tool:yt,model:a,variant:o,skills:s}).then(c)).then(e=>{y(``),p(!0),t(t=>{if(t.status!==`authenticated`||t.selectedProjectId!==r)return t;let n=t.chatSessions??[],i=n.some(t=>t.id===e.id)?n.map(t=>t.id===e.id?e:t):[e,...n];return{...t,chatSessions:i,selectedChatSessionId:e.id,chatSessionDetail:e,chatSessionDetailError:null}}),J(i,r)}).catch(e=>{Xe(e)||re(I0(e,`Unable to send the chat prompt.`))}).finally(()=>F(!1))},Xt=()=>{if(e.status!==`authenticated`||!e.selectedProjectId||!e.selectedChatSessionId||ee)return;let t=e.selectedProjectId,n=e.selectedChatSessionId;re(null),te(n),m1(t,n,e.csrfToken).then(()=>et(e.csrfToken,t,n)).catch(e=>{Xe(e)||re(I0(e,`Unable to stop the chat response.`))}).finally(()=>te(null))},Zt=n=>{if(e.status!==`authenticated`||!e.selectedProjectId||!e.selectedTicketId||ae||(n===`stop-run`||n===`pause-build`)&&!window.confirm(`Stop this ticket action on the desktop machine?`))return;let r=e.selectedProjectId,i=e.selectedTicketId,a=e.csrfToken,o=n===`build`?h1(r,i,a,`build`):n===`review`?h1(r,i,a,`review`):n===`run`?g1(r,i,a):n===`stop-run`?_1(r,i,a):n===`pause-build`?v1(r,i,a):y1(r,i,a);oe(n),ce(null),o.then(e=>{t(t=>{if(t.status!==`authenticated`||t.selectedProjectId!==r||t.selectedTicketId!==i)return t;let n=t.tickets?.map(t=>t.id===e.id?e:t)??t.tickets;return{...t,tickets:n,ticketDetail:e,ticketDetailError:null}}),tt(a,r),$e(a,r),Ze(a,r,i)}).catch(e=>{Xe(e)||ce(I0(e,`Unable to update this ticket from mobile.`))}).finally(()=>oe(null))},Qt=n=>{if(e.status!==`authenticated`||!e.selectedProjectId||!e.selectedBundleId||!e.bundleDetail||B)return;let r=e.selectedProjectId,i=e.selectedBundleId,a=e.csrfToken,o=e.bundleDetail,{runningBuildTicketId:s,resumableBuildTicketId:c}=v0(o);if(n===`pause-build`&&!window.confirm(`Pause this bundle build on the desktop machine?`))return;let l=e=>{t(t=>t.status!==`authenticated`||t.selectedProjectId!==r||t.selectedBundleId!==i?t:{...t,tickets:m0(t.tickets,e),bundleDetail:e,bundleDetailError:null})},u=e=>{t(t=>t.status!==`authenticated`||t.selectedProjectId!==r||t.selectedBundleId!==i?t:{...t,tickets:t.tickets?.map(t=>t.id===e.id?e:t)??t.tickets,bundleDetail:t.bundleDetail?{...t.bundleDetail,tickets:t.bundleDetail.tickets.map(t=>t.id===e.id?e:t)}:t.bundleDetail,bundleDetailError:null})},d=n===`build`?c1(r,i,a):n===`review`?l1(r,i,a):n===`pause-build`?s?v1(r,s,a):null:c?y1(r,c,a):null;d&&(ie(n),H(null),d.then(e=>{`tickets`in e?l(e):u(e),tt(a,r),$e(a,r),Qe(a,r,i)}).catch(e=>{Xe(e)||H(I0(e,`Unable to update this bundle from mobile.`))}).finally(()=>ie(null)))},$t=e=>{let t=O.find(t=>t.id===e)??null;U(e),pe(e=>t&&t.variants.includes(e)?e:``)},en=e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),tn())},tn=()=>{if(e.status!==`authenticated`||!e.selectedProjectId||!e.selectedTicketId||!e.ticketDetail||he)return;let n=le.trim();if(!n)return;let r=e.selectedProjectId,i=e.ticketDetail,a=e.csrfToken,o=ZW(i,{model:de||null,variant:fe||null,skills:me}),s=()=>i.state===`plan`?x1(r,i.id,a,n):S1(r,i.id,a,n),c=e=>{t(t=>{if(t.status!==`authenticated`||t.selectedProjectId!==r||t.selectedTicketId!==i.id)return t;let n=t.tickets?.map(t=>t.id===e.id?e:t)??t.tickets;return{...t,tickets:n,ticketDetail:e,ticketDetailError:null}})};G(!0),_e(null),(async()=>{o.shouldPersist&&c(await b1(r,i.id,a,{model:o.model,variant:o.variant,skills:o.skills})),c(await s()),ue(``),$e(a,r),Ze(a,r,i.id)})().catch(e=>{Xe(e)||_e(I0(e,`Unable to send the ticket follow-up.`))}).finally(()=>G(!1))},nn=e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),rn())},rn=()=>{if(e.status!==`authenticated`||!e.selectedProjectId||!e.selectedBundleId||!e.bundleDetail||be)return;let n=ve.trim();if(!n)return;let r=e.selectedProjectId,i=e.selectedBundleId,a=e.csrfToken,o=e=>{t(t=>t.status!==`authenticated`||t.selectedProjectId!==r||t.selectedBundleId!==i?t:{...t,tickets:m0(t.tickets,e),bundleDetail:e,bundleDetailError:null})};xe(!0),Ce(null),C1(r,i,a,n).then(e=>{o(e),ye(``),$e(a,r),Qe(a,r,i)}).catch(e=>{Xe(e)||Ce(I0(e,`Unable to send the bundle follow-up.`))}).finally(()=>xe(!1))};return e.status===`checking`?(0,Z.jsx)(H1,{title:`Checking mobile session`,description:`Archon is validating this browser before showing project controls.`}):e.status===`pairing`?(0,Z.jsx)(H1,{title:`Checking pairing link`,description:`Keep this page open while Archon verifies the one-time pairing link.`}):e.status===`pairing_confirmation`?(0,Z.jsxs)(H1,{title:`Compare pairing code`,description:`Confirm this code matches the desktop dialog before pairing this phone.`,children:[(0,Z.jsx)(gu,{className:`border-primary/25 bg-primary/10 shadow-none`,children:(0,Z.jsxs)(xu,{className:`space-y-2 pt-5 text-center`,children:[(0,Z.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-[0.18em] text-foreground`,children:`Verification code`}),(0,Z.jsx)(`div`,{className:`font-mono text-3xl font-semibold tracking-[0.18em] text-foreground`,children:e.displayCode}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[`Expires at `,F0(e.expiresAt)]})]})}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`If this code does not match the desktop dialog, cancel and regenerate the pairing link from desktop Archon.`}),e.error?(0,Z.jsx)(`p`,{className:`text-sm text-red-200`,children:e.error}):null,(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row`,children:[(0,Z.jsx)(q,{size:`lg`,disabled:g,onClick:Et,children:g?`Pairing...`:`Pair this phone`}),(0,Z.jsx)(q,{variant:`outline`,size:`lg`,disabled:g,onClick:Dt,children:`Cancel`})]})]}):e.status===`unauthenticated`?(0,Z.jsx)(H1,{title:e.reason===`session_revoked`?`Mobile session revoked`:`Pairing required`,description:e.reason===`session_revoked`?`This mobile session is no longer valid. Scan the QR code or open the pairing link from desktop Archon to continue.`:`This browser is not paired. Scan the QR code or open the pairing link from desktop Archon.`,children:(0,Z.jsx)(q,{onClick:xt,children:`Retry`})}):e.status===`error`?(0,Z.jsx)(H1,{title:`Mobile access unavailable`,description:e.message,children:(0,Z.jsx)(q,{onClick:xt,children:`Retry`})}):(0,Z.jsxs)(`main`,{className:K(`bg-background text-foreground`,X?`flex h-[100dvh] flex-col overflow-hidden`:`min-h-screen`),children:[(0,Z.jsx)(Y1,{open:o,projects:e.projects,selectedProjectId:e.selectedProjectId,error:e.projectError,onOpenChange:s,onSelectProject:It,onRetry:Ot}),(0,Z.jsx)(X1,{open:Ie,project:ft,targetOptions:Me,error:He??Pe,isLoading:Re,isSubmitting:Be,onOpenChange:Le,onRetry:At,onSelectBundle:e=>{Lt(e)},onSelectRepoRoot:(e,t)=>{Rt(e,t)}}),(0,Z.jsx)(Z1,{selectedProject:ft,targetLabel:gt,isTargetLoading:_t,isTargetDisabled:!ct,connectionState:n,onOpenProjects:Ct,onOpenTargetSelector:wt}),X?(0,Z.jsxs)(`div`,{className:`mx-auto flex min-h-0 w-full max-w-6xl flex-1 flex-col overflow-hidden px-3 py-3 sm:px-4`,children:[i===`tickets`?(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:u&&e.selectedTicketId?(0,Z.jsx)(M0,{selectedProjectId:e.selectedProjectId,ticketId:e.selectedTicketId,ticket:e.ticketDetail,openNonce:Oe,error:e.ticketDetailError,actionState:ae,actionError:se,followUpPrompt:le,followUpSelectedModel:de,followUpSelectedVariant:fe,followUpSelectedSkills:me,availableModels:O,availableSkills:A,isLoadingAgentSettings:M,isSendingFollowUp:he,followUpError:ge,onBack:Gt,onRetry:Pt,onAction:Zt,onFollowUpPromptChange:ue,onFollowUpModelChange:$t,onFollowUpVariantChange:pe,onFollowUpSkillsChange:W,onFollowUpKeyDown:en,onFollowUpSubmit:tn,isLargeScreen:!1}):(0,Z.jsx)(A0,{selectedProjectId:e.selectedProjectId,bundleId:e.selectedBundleId,bundleDetail:e.bundleDetail,openNonce:Ee,mobileDetailView:Ae,error:e.bundleDetailError,actionState:B,actionError:V,followUpPrompt:ve,isSendingFollowUp:be,followUpError:Se,availableModels:O,onBack:Kt,onRetry:Ft,onAction:Qt,onDetailViewChange:je,onSelectTicket:Ht,onFollowUpPromptChange:ye,onFollowUpKeyDown:nn,onFollowUpSubmit:rn,isLargeScreen:!1})}):null,i===`chats`?(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:[(0,Z.jsx)(j0,{selectedProjectId:e.selectedProjectId,chatSession:e.chatSessionDetail,chatSessionId:e.selectedChatSessionId,openNonce:we,error:e.chatSessionDetailError,isStopping:ee===e.selectedChatSessionId,composerMode:e.chatSessionDetail?.mode??b,composerTool:yt,prompt:v,selectedModel:S,selectedVariant:w,selectedSkills:E,availableModels:O,availableSkills:A,isLoadingAgentSettings:M,isSending:P,isUpdatingMode:L,composerDisabledReason:bt,onBack:Ut,onRetry:Mt,onStop:Xt,onModeChange:Wt,onPromptChange:y,onModelChange:qt,onVariantChange:T,onSkillsChange:D,onPromptKeyDown:Jt,onSubmit:Yt,isLargeScreen:!1}),ne?(0,Z.jsx)(`p`,{className:`mt-3 text-sm text-red-200`,children:ne}):null]}):null]}):(0,Z.jsx)(`div`,{className:`mx-auto w-full max-w-6xl px-3 py-3 pb-[calc(env(safe-area-inset-bottom)+5rem)] sm:px-4 lg:flex lg:min-h-[calc(100dvh-4.5rem)] lg:flex-col lg:overflow-hidden lg:pb-4`,children:(0,Z.jsxs)(`div`,{className:`space-y-3 lg:flex lg:min-h-0 lg:flex-1 lg:flex-col`,children:[(0,Z.jsx)(K1,{status:n,onRetry:xt}),i===`overview`?(0,Z.jsx)(`div`,{className:`space-y-3 lg:flex lg:min-h-0 lg:flex-1 lg:flex-col`,children:e.projectError?(0,Z.jsx)($1,{title:`Projects unavailable`,description:e.projectError,action:(0,Z.jsx)(q,{variant:`warning`,onClick:Ot,children:`Retry projects`})}):e.selectedProjectId&&!e.projectSummary&&!e.projectSummaryError?(0,Z.jsx)(n0,{}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(o0,{selectedProjectId:e.selectedProjectId,summary:e.projectSummary,tickets:e.tickets,error:e.projectSummaryError,chatSessions:e.chatSessions,chatSessionDetail:e.chatSessionDetail,onRetry:kt,onOpenTickets:()=>St(`tickets`),onOpenChats:()=>St(`chats`)}),(0,Z.jsx)(r0,{isLoggingOut:m,onLogout:Tt})]})}):null,i===`tickets`?vt?(0,Z.jsxs)(`div`,{className:`grid min-h-0 flex-1 gap-3 overflow-hidden lg:grid-cols-[minmax(15rem,18rem)_minmax(0,1fr)]`,children:[(0,Z.jsx)(`div`,{className:`min-h-0`,children:(0,Z.jsx)(h0,{selectedProjectId:e.selectedProjectId,tickets:e.tickets,selectedBundleId:e.selectedBundleId,selectedTicketId:e.selectedTicketId,error:e.ticketsError,onRetry:Nt,onSelectBundle:Vt,onSelectTicket:Ht})}),(0,Z.jsx)(`div`,{className:`hidden min-h-0 lg:flex lg:flex-col lg:overflow-hidden`,children:u&&e.selectedTicketId?(0,Z.jsx)(M0,{selectedProjectId:e.selectedProjectId,ticketId:e.selectedTicketId,ticket:e.ticketDetail,openNonce:Oe,error:e.ticketDetailError,actionState:ae,actionError:se,followUpPrompt:le,followUpSelectedModel:de,followUpSelectedVariant:fe,followUpSelectedSkills:me,availableModels:O,availableSkills:A,isLoadingAgentSettings:M,isSendingFollowUp:he,followUpError:ge,onBack:Gt,onRetry:Pt,onAction:Zt,onFollowUpPromptChange:ue,onFollowUpModelChange:$t,onFollowUpVariantChange:pe,onFollowUpSkillsChange:W,onFollowUpKeyDown:en,onFollowUpSubmit:tn,isLargeScreen:!0}):(0,Z.jsx)(A0,{selectedProjectId:e.selectedProjectId,bundleId:e.selectedBundleId,bundleDetail:e.bundleDetail,openNonce:Ee,mobileDetailView:Ae,error:e.bundleDetailError,actionState:B,actionError:V,followUpPrompt:ve,isSendingFollowUp:be,followUpError:Se,availableModels:O,onBack:Kt,onRetry:Ft,onAction:Qt,onDetailViewChange:je,onSelectTicket:Ht,onFollowUpPromptChange:ye,onFollowUpKeyDown:nn,onFollowUpSubmit:rn,isLargeScreen:!0})})]}):(0,Z.jsx)(h0,{selectedProjectId:e.selectedProjectId,tickets:e.tickets,selectedBundleId:e.selectedBundleId,selectedTicketId:e.selectedTicketId,error:e.ticketsError,onRetry:Nt,onSelectBundle:Vt,onSelectTicket:Ht}):null,i===`chats`?vt?(0,Z.jsxs)(`div`,{className:`grid min-h-0 flex-1 gap-3 overflow-hidden lg:grid-cols-[minmax(15rem,18rem)_minmax(0,1fr)]`,children:[(0,Z.jsx)(`div`,{className:`min-h-0`,children:(0,Z.jsx)(g0,{selectedProjectId:e.selectedProjectId,chatSessions:e.chatSessions,selectedChatSessionId:e.selectedChatSessionId,error:e.chatSessionsError,onRetry:jt,onOpenNewChat:Bt,onSelectChat:zt})}),(0,Z.jsxs)(`div`,{className:`hidden min-h-0 lg:flex lg:flex-col lg:overflow-hidden`,children:[(0,Z.jsx)(j0,{selectedProjectId:e.selectedProjectId,chatSession:e.chatSessionDetail,chatSessionId:e.selectedChatSessionId,openNonce:we,error:e.chatSessionDetailError,isStopping:ee===e.selectedChatSessionId,composerMode:e.chatSessionDetail?.mode??b,composerTool:yt,prompt:v,selectedModel:S,selectedVariant:w,selectedSkills:E,availableModels:O,availableSkills:A,isLoadingAgentSettings:M,isSending:P,isUpdatingMode:L,composerDisabledReason:bt,onBack:Ut,onRetry:Mt,onStop:Xt,onModeChange:Wt,onPromptChange:y,onModelChange:qt,onVariantChange:T,onSkillsChange:D,onPromptKeyDown:Jt,onSubmit:Yt,isLargeScreen:!0}),ne?(0,Z.jsx)(`p`,{className:`mt-3 text-sm text-red-200`,children:ne}):null]})]}):(0,Z.jsx)(g0,{selectedProjectId:e.selectedProjectId,chatSessions:e.chatSessions,selectedChatSessionId:e.selectedChatSessionId,error:e.chatSessionsError,onRetry:jt,onOpenNewChat:Bt,onSelectChat:zt}):null]})}),X?null:(0,Z.jsx)(Q1,{activeSection:i,onChange:St})]})},V0=({socket:e=UW,children:t})=>(0,Z.jsx)(RY.Provider,{value:e,children:t}),H0=()=>typeof window<`u`&&window.location.pathname.startsWith(`/mobile`),U0=()=>{let e=H0();return tu(e?null:UW),(0,Z.jsx)(xt,{i18n:Pe,children:(0,Z.jsx)(wt,{children:(0,Z.jsxs)(V0,{children:[e&&(0,Z.jsx)(B0,{}),!e&&(0,Z.jsx)(q$,{})]})})})};document.documentElement.classList.add(`dark`),document.documentElement.style.colorScheme=`dark`,(0,at.createRoot)(document.getElementById(`root`)).render((0,Z.jsx)(U0,{}));export{nd as a,Ac as c,Ps as d,Rs as f,Ls as h,rd as i,As as l,Fs as m,cf as n,Fc as o,Is as p,td as r,Nc as s,UW as t,Ms as u};
|
|
150
|
+
`).map(e=>e.trim()).filter(Boolean).filter((e,t,n)=>n.indexOf(e)===t),eZ=e=>{let t=[`plan`,`build`,`review`,`follow_up`,`plan_follow_up`,`chat`];return e.split(/\n|,/).map(e=>e.trim()).filter(e=>t.includes(e)).filter((e,t,n)=>n.indexOf(e)===t)},tZ=({suggestion:e,isPending:t,onReview:n,onAccept:r,onDismiss:i})=>{let a=e.kind===`decision`?e.duplicate_match?.decision??null:null,o=JX(a?`suggested.saveAsNewDecision`:`suggested.accept`),s=e.kind===`decision`?e.decision:e.instruction;return(0,Z.jsx)(`li`,{className:`rounded-xl border border-border/60 bg-background/40`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 p-3`,children:[(0,Z.jsx)(`div`,{className:`flex items-start justify-between gap-3`,children:(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-semibold text-foreground`,children:e.title}),(0,Z.jsx)(qX,{children:JX(`suggested.badge`,{kind:e.kind})}),a?(0,Z.jsx)(qX,{tone:`muted`,children:JX(`suggested.duplicateBadge`)}):null]}),(0,Z.jsx)(`p`,{className:`line-clamp-2 text-sm text-muted-foreground`,children:s})]})}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,disabled:t,onClick:()=>n(e),children:JX(`suggested.review`)}),(0,Z.jsx)(q,{type:`button`,size:`sm`,disabled:t,onClick:()=>void r(e),children:o}),(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,disabled:t,onClick:()=>void i(e),children:JX(`suggested.dismiss`)})]})]})})},nZ=({suggestion:e,isOpen:t,isEditing:n,isPending:r,draft:i,onOpenChange:a,onStartEdit:o,onDraftChange:s,onCancelEdit:c,onAccept:l,onDismiss:u})=>{if(!e)return null;let d=e.kind===`decision`?e.duplicate_match?.decision??null:null,f=d?JX(`suggested.saveAsNewDecision`):JX(`suggested.acceptAs`,{kind:e.kind});return(0,Z.jsx)(As,{open:t,onOpenChange:a,children:(0,Z.jsxs)(Ps,{className:`max-h-[85vh] overflow-y-auto sm:max-w-2xl`,children:[(0,Z.jsxs)(Fs,{children:[(0,Z.jsx)(Ls,{children:e.title}),(0,Z.jsx)(Rs,{children:JX(`suggested.reviewDescription`,{kind:e.kind})})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[d?(0,Z.jsxs)(`div`,{className:`rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs leading-5 text-amber-100`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-amber-50`,children:JX(`suggested.duplicateTitle`)}),(0,Z.jsxs)(`p`,{children:[(0,Z.jsxs)(`span`,{className:`font-medium`,children:[d.title,`:`]}),` `,d.decision]})]}):null,n?(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground sm:col-span-2`,children:[(0,Z.jsx)(`span`,{children:JX(`editor.titleLabel`)}),(0,Z.jsx)(`input`,{"aria-label":JX(`editor.titleAriaLabel`),value:i.title,onChange:e=>s({...i,title:e.target.value}),className:`h-10 rounded-lg border border-border bg-background px-3 text-sm text-foreground outline-none transition focus:border-primary/60`})]}),(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground sm:col-span-2`,children:[(0,Z.jsx)(`span`,{children:JX(`editor.scopeLabel`)}),(0,Z.jsx)(`input`,{"aria-label":JX(`editor.scopeAriaLabel`),value:i.scope,onChange:e=>s({...i,scope:e.target.value}),className:`h-10 rounded-lg border border-border bg-background px-3 text-sm text-foreground outline-none transition focus:border-primary/60`})]}),(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground sm:col-span-2`,children:[(0,Z.jsx)(`span`,{children:i.kind===`decision`?JX(`suggested.decision`):JX(`suggested.instruction`)}),(0,Z.jsx)(`textarea`,{"aria-label":i.kind===`decision`?JX(`suggested.decision`):JX(`suggested.instruction`),value:i.content,onChange:e=>s({...i,content:e.target.value}),rows:5,className:`min-h-32 rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none transition focus:border-primary/60`})]}),(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground sm:col-span-2`,children:[(0,Z.jsx)(`span`,{children:JX(`editor.rationaleLabel`)}),(0,Z.jsx)(`textarea`,{"aria-label":JX(`editor.rationaleAriaLabel`),value:i.rationale,onChange:e=>s({...i,rationale:e.target.value}),rows:3,className:`rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none transition focus:border-primary/60`})]}),i.kind===`decision`?(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground sm:col-span-2`,children:[(0,Z.jsx)(`span`,{children:JX(`suggested.implicationsMultiline`)}),(0,Z.jsx)(`textarea`,{"aria-label":JX(`editor.implicationsAriaLabel`),value:i.implications,onChange:e=>s({...i,implications:e.target.value}),rows:3,className:`rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none transition focus:border-primary/60`})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:JX(`suggested.stagesMultiline`)}),(0,Z.jsx)(`textarea`,{"aria-label":JX(`editor.stagesLabel`),value:i.stages,onChange:e=>s({...i,stages:e.target.value}),rows:3,className:`rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none transition focus:border-primary/60`})]}),(0,Z.jsxs)(`label`,{className:`flex flex-col gap-1 text-xs font-medium text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:JX(`editor.priorityLabel`)}),(0,Z.jsxs)(`select`,{"aria-label":JX(`editor.priorityAriaLabel`),value:i.priority,onChange:e=>s({...i,priority:e.target.value}),className:`h-10 rounded-lg border border-border bg-background px-3 text-sm text-foreground outline-none transition focus:border-primary/60`,children:[(0,Z.jsx)(`option`,{value:`low`,children:JX(`priorityLabels.low`)}),(0,Z.jsx)(`option`,{value:`normal`,children:JX(`priorityLabels.normal`)}),(0,Z.jsx)(`option`,{value:`high`,children:JX(`priorityLabels.high`)})]})]})]})]}):(0,Z.jsxs)(`div`,{className:`space-y-4 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground`,children:e.kind===`decision`?JX(`suggested.decision`):JX(`suggested.instruction`)}),(0,Z.jsx)(`p`,{className:`whitespace-pre-wrap text-foreground`,children:e.kind===`decision`?e.decision:e.instruction})]}),e.rationale?(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground`,children:JX(`editor.rationaleLabel`)}),(0,Z.jsx)(`p`,{className:`whitespace-pre-wrap text-muted-foreground`,children:e.rationale})]}):null,e.kind===`decision`&&e.implications.length>0?(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground`,children:JX(`editor.implicationsLabel`)}),(0,Z.jsx)(`ul`,{className:`list-disc space-y-1 pl-5 text-muted-foreground`,children:e.implications.map(e=>(0,Z.jsx)(`li`,{children:e},e))})]}):null,e.kind===`convention`?(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground`,children:JX(`editor.stagesLabel`)}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:e.stages.map(e=>YX(e)).join(`, `)||JX(`suggested.noneSpecified`)})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium uppercase tracking-[0.16em] text-muted-foreground`,children:JX(`editor.priorityLabel`)}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:XX(e.priority)})]})]}):null]})]}),(0,Z.jsxs)(Is,{className:`flex flex-wrap gap-2 sm:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[n?(0,Z.jsx)(q,{type:`button`,variant:`ghost`,disabled:r,onClick:c,children:JX(`suggested.cancelEdits`)}):(0,Z.jsx)(q,{type:`button`,variant:`outline`,disabled:r,onClick:()=>o(e),children:JX(`suggested.edit`)}),(0,Z.jsx)(q,{type:`button`,variant:`ghost`,disabled:r,onClick:()=>void u(e),children:JX(`suggested.dismiss`)})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[d?(0,Z.jsx)(q,{type:`button`,variant:`outline`,disabled:r,onClick:()=>void l(e,!0),children:JX(`suggested.updateExistingDecision`)}):null,(0,Z.jsx)(q,{type:`button`,disabled:r,onClick:()=>void l(e,!1),children:f})]})]})]})})},rZ=({projectId:e,suggestions:t,title:n,description:r,emptyState:i=null,onSuggestionsChanged:a})=>{let[o,s]=(0,Y.useState)(null),[c,l]=(0,Y.useState)(null),[u,d]=(0,Y.useState)(ZX),[f,p]=(0,Y.useState)(null);(0,Y.useEffect)(()=>{l(e=>e&&!t.some(t=>t.id===e)?null:e),s(e=>e&&!t.some(t=>t.id===e)?null:e)},[t]);let m=o?t.find(e=>e.id===o)??null:null,h=()=>{l(null),d(ZX())},g=e=>{s(e.id),l(e.id),d(QX(e))},_=e=>{c&&c!==e.id&&h(),s(e.id)},v=e=>{e||(s(null),c&&h())},y=async(t,n)=>{let r=c===t.id?u:QX(t),i=r.kind===`decision`?{title:r.title.trim(),scope:r.scope.trim()||null,decision:r.content.trim(),rationale:r.rationale.trim()||null,implications:$X(r.implications)}:{title:r.title.trim(),scope:r.scope.trim()||null,instruction:r.content.trim(),rationale:r.rationale.trim()||null,stages:eZ(r.stages),priority:r.priority};p(t.id);try{if(n){if(t.kind!==`decision`)throw Error(JX(`messages.onlyDecisionSuggestionsCanUpdate`));let n=t.duplicate_match?.decision;if(!n)throw Error(JX(`messages.noExistingDecision`));await Re(e,t.id,n.id,i)}else await T(e,t.id,i);h(),s(null),a?.()}catch(e){Q.error(e instanceof Error?e.message:JX(`messages.saveSuggestionError`),{id:`project-memory-suggestion-error`})}finally{p(null)}},b=async t=>{p(t.id);try{await Be(e,t.id),c===t.id&&h(),o===t.id&&s(null),a?.()}catch(e){Q.error(e instanceof Error?e.message:JX(`messages.dismissSuggestionError`),{id:`project-memory-suggestion-error`})}finally{p(null)}};return(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[n||r?(0,Z.jsx)(`div`,{className:`flex items-center justify-between gap-3`,children:(0,Z.jsxs)(`div`,{children:[n?(0,Z.jsx)(`h4`,{className:`text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground`,children:n}):null,r?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:r}):null]})}):null,t.length>0?(0,Z.jsx)(`ul`,{className:`space-y-2`,children:t.map(e=>(0,Z.jsx)(tZ,{suggestion:e,isPending:f===e.id,onReview:_,onAccept:e=>y(e,!1),onDismiss:b},e.id))}):i?(0,Z.jsx)(`div`,{className:`rounded-lg border border-dashed border-border/70 px-3 py-4 text-sm text-muted-foreground`,children:i}):null,(0,Z.jsx)(nZ,{suggestion:m,isOpen:!!m,isEditing:c===m?.id,isPending:f===m?.id,draft:c===m?.id?u:m?QX(m):u,onOpenChange:v,onStartEdit:g,onDraftChange:d,onCancelEdit:h,onAccept:y,onDismiss:b})]})},iZ=()=>({selectedDiffPath:`all`,activeReviewTarget:null,editingReviewCommentKey:null,reviewDraftInput:``,reviewComments:[]}),aZ=[{key:`today`,label:`Today`},{key:`yesterday`,label:`Yesterday`},{key:`last_7_days`,label:`Last 7 Days`},{key:`older`,label:`Older`}],oZ=e=>{if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t},sZ=e=>e.activity_at??e.last_user_message_at??e.created_at,cZ=(e,t)=>{let n=sZ(e),r=sZ(t);return n===r?e.created_at===t.created_at?t.id.localeCompare(e.id):t.created_at.localeCompare(e.created_at):r.localeCompare(n)},lZ=e=>[...e].sort(cZ),uZ=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()),dZ=(e,t=new Date)=>{let n=oZ(sZ(e));if(!n)return`older`;let r=uZ(t),i=new Date(r);i.setDate(i.getDate()-1);let a=new Date(r);return a.setDate(a.getDate()-6),n>=r?`today`:n>=i?`yesterday`:n>=a?`last_7_days`:`older`},fZ=(e,t=new Date)=>{let n=new Map;for(let r of lZ(e)){let e=dZ(r,t);n.set(e,[...n.get(e)??[],r])}return aZ.flatMap(e=>{let t=n.get(e.key)??[];return t.length===0?[]:[{key:e.key,label:e.label,sessions:t}]})},pZ=e=>{let t={...e};return delete t.messages,t.agent_log=null,t.agent_message_id=null,t.previous_agent_log=null,t.previous_agent_message_id=null,t.streaming_response=null,t},mZ=(e,t)=>Pe.t(`chatView.${e}`,t),hZ=1500,gZ=`archon.chat-run-config`,_Z=`archon.chat-changes-panel-layout`,vZ=`archon.chat-session-list-layout`,yZ=`archon.chat-draft`,bZ=512,xZ=360,SZ=.6,CZ=6,wZ=`.`,TZ=`/`,EZ=`Slash`,DZ=`NumpadDivide`,OZ=600,kZ=4,AZ=`mt-1 flex min-h-5 flex-wrap items-center gap-2 text-xs text-muted-foreground`,jZ=(e,t)=>{let n=Number.isFinite(e)?Math.round(e):bZ;if(!Number.isFinite(t))return Math.max(xZ,n);let r=Math.max(xZ,Math.round(t*SZ));return Math.max(xZ,Math.min(r,n))},MZ=e=>mZ(e===`claude`?`tool.claude`:`tool.opencode`),NZ=({availableModelsById:e,model:t})=>t?e.get(t)??t:null,PZ=e=>mZ(e===`plan`?`mode.plan`:`mode.build`),FZ=e=>mZ(e===`plan`?`placeholders.plan`:`placeholders.build`),IZ=e=>mZ(`pendingMemorySuggestions`,{count:e}),LZ=e=>e===`plan`?`build`:`plan`,RZ=e=>!e.defaultPrevented&&!e.altKey&&!e.shiftKey&&!e.repeat&&(e.ctrlKey||e.metaKey)&&e.key===wZ,zZ=e=>!e.defaultPrevented&&!e.altKey&&!e.repeat&&(e.ctrlKey||e.metaKey)&&(e.key===TZ||e.code===EZ||e.code===DZ),BZ=()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??navigator.userAgent;return/mac/i.test(e)},VZ=()=>BZ()?mZ(`shortcuts.modifierMac`):mZ(`shortcuts.modifierDefault`),HZ=({modifierLabel:e,keys:t,ariaHidden:n=!1})=>(0,Z.jsxs)(`span`,{"aria-hidden":n,className:`flex items-center gap-0.5 text-[10px] leading-none`,children:[(0,Z.jsx)(hw,{"aria-hidden":n,children:e}),t.map(e=>(0,Z.jsxs)(`span`,{className:`contents`,children:[(0,Z.jsx)(`span`,{children:`+`}),(0,Z.jsx)(hw,{"aria-hidden":n,children:e})]},e))]}),UZ=({label:e,modifierLabel:t,keys:n})=>(0,Z.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{children:e}),(0,Z.jsx)(HZ,{modifierLabel:t,keys:n,ariaHidden:!0})]}),WZ=({modelLabel:e,tool:t})=>e??MZ(t),GZ=()=>mZ(`user.you`),KZ=e=>{if(!Number.isFinite(e))return`0`;if(e>=1e6){let t=e/1e6,n=t<10?2:1;return`${t.toFixed(n)}M`}return e>=1e3?`${(e/1e3).toFixed(1)}K`:`${Math.round(e)}`},qZ=({totalTokens:e,contextWindow:t})=>!Number.isFinite(e)||!Number.isFinite(t)||t<=0?null:Math.round(e/t*100),JZ=({tool:e,model:t,availableModels:n,fallbackContextWindow:r})=>e===`opencode`?(n.find(e=>e.id===t)??null)?.context_window??r:r,YZ=({projectId:e,tool:t})=>`${gZ}:${e}:${t}`,XZ=({projectId:e,tool:t,chatSessionId:n})=>n?`${yZ}:${e}:session:${n}`:`${yZ}:${e}:draft:${t}`,ZZ=e=>`${_Z}:${e}`,QZ=e=>`${vZ}:${e}`,$Z=e=>{if(!e)return``;try{return window.localStorage.getItem(e)??``}catch{return``}},eQ=({storageKey:e,value:t})=>{if(e)try{if(t){window.localStorage.setItem(e,t);return}window.localStorage.removeItem(e)}catch{}},tQ=e=>{if(!e)return{isOpen:!0,width:bZ};try{let t=window.localStorage.getItem(ZZ(e));if(!t)return{isOpen:!0,width:bZ};let n=JSON.parse(t),r=typeof n.width==`number`&&Number.isFinite(n.width)?Math.max(xZ,Math.round(n.width)):bZ;return{isOpen:n.isOpen!==!1,width:r}}catch{return{isOpen:!0,width:bZ}}},nQ=e=>{if(!e)return{isOpen:!0};try{let t=window.localStorage.getItem(QZ(e));return t?{isOpen:JSON.parse(t).isOpen!==!1}:{isOpen:!0}}catch{return{isOpen:!0}}},rQ=({projectId:e,isOpen:t,width:n})=>{if(e)try{window.localStorage.setItem(ZZ(e),JSON.stringify({isOpen:t,width:n}))}catch{}},iQ=({projectId:e,isOpen:t})=>{if(e)try{window.localStorage.setItem(QZ(e),JSON.stringify({isOpen:t}))}catch{}},aQ=({projectId:e,tool:t})=>{if(!e||t!==`opencode`)return null;try{let n=window.localStorage.getItem(YZ({projectId:e,tool:t}));if(!n)return null;let r=JSON.parse(n),i=(typeof r.model==`string`?r.model.trim():``)||null,a=r.mode===`plan`||r.mode===`build`?r.mode:null;return!i&&!a?null:{model:i,variant:i&&typeof r.variant==`string`&&r.variant.trim()||null,mode:a}}catch{return null}},oQ=({projectId:e,tool:t,model:n,variant:r,mode:i})=>{if(!(!e||t!==`opencode`||!n&&!i))try{window.localStorage.setItem(YZ({projectId:e,tool:t}),JSON.stringify({model:n,variant:n?r:null,mode:i}))}catch{}},sQ=({projectId:e,tool:t})=>aQ({projectId:e,tool:t})?.mode??`plan`,cQ=({activeProjectId:e,helperModel:t,helperVariant:n,activeTool:r,availableModels:i})=>{let a=aQ({projectId:e,tool:r}),o=new Set(i.map(e=>e.id)),s=e=>e?o.size===0?!0:o.has(e):!1,c=t??``,l=a?.model??``,u=s(l)?l:s(c)?c:``,d=u===l?a?.variant??null:u&&u===c?n??null:null,f=i.find(e=>e.id===u)??null;return{model:u,variant:f?f.variants.includes(d??``)?d??``:``:u?d??``:``,mode:a?.mode??`plan`}},lQ=e=>e&&e.replace(/\s+/g,` `).trim()||null,uQ=e=>{let t=lQ(e.first_user_message_preview);if(t)return t;let n=e.messages?.find(e=>e.role===`user`)?.content;return lQ(n)},dQ=({chatSessionId:e,instruction:t,attachments:n,createdAt:r})=>({id:`optimistic:${e}:${r}`,chat_session_id:e,role:`user`,kind:`prompt`,content:t,attachments:n,created_at:r}),fQ=({session:e,instruction:t,attachments:n,createdAt:r})=>({...e,messages:[...e.messages??[],dQ({chatSessionId:e.id,instruction:t,attachments:n,createdAt:r})],activity_at:r,last_user_message_at:r,updated_at:r}),pQ=e=>!!(e.first_user_message_preview||e.last_user_message_at||e.messages?.some(e=>e.role===`user`)),mQ=({activeProject:e,activeProjectBranchState:t,session:n})=>!e||n.target_available===!1?!1:n.target_kind===`bundle`?e.active_target_kind===`bundle`&&!!n.target_bundle_id&&e.active_target_bundle_id===n.target_bundle_id:e.active_target_kind===`bundle`?!1:!t||!n.target_branch_snapshot?!0:t?.status!==`ready`||!t.branch?!1:t.branch===n.target_branch_snapshot,hQ=({session:e,activeProject:t,activeProjectBranchState:n})=>e.target_kind===`bundle`?e.target_label_snapshot||mZ(`targets.bundleFallback`):!t||t.active_target_kind===`bundle`||n?.status!==`ready`||!n.branch||!e.target_branch_snapshot||n.branch===e.target_branch_snapshot?null:mZ(`targets.repoRootWithBranch`,{branch:e.target_branch_snapshot}),gQ=e=>e.target_kind===`bundle`?e.target_label_snapshot||mZ(`targets.bundleFallback`):e.target_branch_snapshot?mZ(`targets.repoRootWithBranch`,{branch:e.target_branch_snapshot}):mZ(`targets.repoRoot`),_Q=({activeProject:e,activeProjectBranchState:t})=>e?e.active_target_kind===`bundle`?mZ(`targets.selectedBundleTarget`):t?.branch?mZ(`targets.repoRootWithBranch`,{branch:t.branch}):mZ(`targets.repoRoot`):mZ(`targets.currentTarget`),vQ=e=>e.agent_status===`running`?mZ(`sidebar.deleteDisabledReason`):null,yQ=({count:e,title:t,isDeleting:n,onConfirm:r,onCancel:i})=>{let a=e>1;return(0,Z.jsxs)(pu,{onClose:i,overlayClassName:`bg-black/60`,panelClassName:`max-w-sm rounded-2xl border border-border bg-card p-6 shadow-2xl`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold uppercase tracking-widest text-muted-foreground`,children:mZ(a?`deleteSessionModal.bulkTitle`:`deleteSessionModal.title`)}),t?(0,Z.jsx)(`p`,{className:`mb-1 text-sm text-foreground`,children:t}):null,(0,Z.jsx)(`p`,{className:`mb-6 text-xs text-muted-foreground`,children:a?mZ(`deleteSessionModal.bulkDescription`,{count:e}):mZ(`deleteSessionModal.description`)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(q,{type:`button`,variant:`ghost`,onClick:i,disabled:n,children:mZ(`deleteSessionModal.cancel`)}),(0,Z.jsx)(q,{type:`button`,variant:`destructive`,onClick:r,disabled:n,children:mZ(n?`deleteSessionModal.deleting`:`deleteSessionModal.delete`)})]})]})},bQ=({activeProject:e,activeProjectBranchState:t,activeSessionId:n,chatModeShortcutModifierLabel:r,deletingSessionIds:i,finishedBackgroundSessionIds:a,hasDeletableSessions:o,isCreatingSession:s,isSelectionMode:c,isDraftOpen:l,isLoadingSessions:u,isOpen:d,isSendingPrompt:f,selectedSessionCount:p,selectedSessionIds:m,sessionGroups:h,sessions:g,onConfirmDeleteSelectedSessions:_,onConfirmDeleteSession:v,onDraftOpen:y,onEnterSelectionMode:b,onExitSelectionMode:x,onSetSessionSelection:S,onSessionSelect:C,onToggleSessionSelection:w,onToggleOpen:T})=>{let E=(0,Y.useMemo)(()=>new Set(g.filter(e=>!vQ(e)&&!i.has(e.id)).map(e=>e.id)),[i,g]),D=(0,Y.useRef)(null),O=(0,Y.useRef)(!1),k=(0,Y.useRef)(null),A=(0,Y.useCallback)(()=>{k.current!==null&&(window.clearTimeout(k.current),k.current=null)},[]),j=(0,Y.useCallback)(()=>{A(),k.current=window.setTimeout(()=>{O.current=!1,k.current=null},0)},[A]),M=(0,Y.useCallback)(()=>{D.current&&(D.current=null,j())},[j]),N=(0,Y.useCallback)(e=>{let t=D.current;!t||t.visitedSessionIds.has(e)||!E.has(e)||(t.visitedSessionIds.add(e),S(e,t.mode===`select`))},[S,E]),P=(0,Y.useCallback)(e=>{let t=D.current;!t||e.pointerId!==t.pointerId||M()},[M]);return(0,Y.useEffect)(()=>{if(!c){M();return}return window.addEventListener(`pointerup`,P),window.addEventListener(`pointercancel`,P),()=>{window.removeEventListener(`pointerup`,P),window.removeEventListener(`pointercancel`,P),M(),A()}},[A,P,c,M]),(0,Z.jsx)(`aside`,{"data-testid":`chat-sessions-sidebar`,"data-state":d?`expanded`:`collapsed`,"aria-label":mZ(`sidebar.ariaLabel`),className:K(`relative z-20 flex h-full shrink-0 flex-col overflow-hidden border-r border-border/70 bg-background/40 transition-[width] duration-200 ease-out motion-reduce:transition-none`,d?`w-72`:`w-16`),children:d?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-start gap-2 border-b border-border/70 px-4 py-3.5`,children:[(0,Z.jsxs)(q,{type:`button`,size:`sm`,className:`gap-2`,onClick:y,disabled:s||f,children:[(0,Z.jsx)(zl,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:mZ(`sidebar.newSession`)}),(0,Z.jsx)(HZ,{modifierLabel:r,keys:[TZ],ariaHidden:!0})]}),(0,Z.jsx)(q,{type:`button`,size:`icon-sm`,variant:`ghost`,"aria-label":mZ(`sidebar.collapseAriaLabel`),"aria-expanded":d,className:`ml-auto`,onClick:T,children:(0,Z.jsx)(EX,{className:`h-4 w-4`})})]}),g.length>0?(0,Z.jsx)(`div`,{className:`px-4 py-2.5`,children:c?(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`h-7 px-2 text-xs`,onClick:x,disabled:i.size>0,children:mZ(`sidebar.cancelSelection`)}),(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`destructive`,className:`h-7 px-2 text-xs`,onClick:_,disabled:p===0||i.size>0,children:mZ(`sidebar.deleteSelected`)})]}),(0,Z.jsx)(`div`,{className:`flex justify-end text-xs font-medium text-muted-foreground`,children:mZ(`sidebar.selectedCount`,{count:p})})]}):o?(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`h-7 gap-1.5 px-2 text-xs`,onClick:b,children:[(0,Z.jsx)(TX,{className:`h-3.5 w-3.5`}),mZ(`sidebar.select`)]}):null}):null,(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-2`,children:u&&g.length===0?(0,Z.jsx)(`div`,{className:`px-2 py-4 text-sm text-muted-foreground`,children:mZ(`sidebar.loadingSessions`)}):g.length===0?(0,Z.jsx)(`div`,{className:`rounded-lg border border-dashed border-border/70 px-3 py-4 text-sm text-muted-foreground`,children:mZ(`sidebar.noSessions`)}):(0,Z.jsx)(`div`,{className:`flex flex-col gap-3`,children:h.map(r=>(0,Z.jsxs)(`section`,{"aria-label":r.label,className:`flex flex-col gap-1.5`,children:[(0,Z.jsx)(`div`,{className:`px-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground/80`,children:r.label}),r.sessions.map(r=>{let o=!l&&r.id===n,s=uQ(r),u=hQ({session:r,activeProject:e,activeProjectBranchState:t}),d=vQ(r),f=i.has(r.id),p=!!d||f,h=m.has(r.id),g=r.agent_status===`running`?`running`:r.agent_status===`stopped`?`interrupted`:!o&&a.has(r.id)?`finished`:null,_=g===`interrupted`?null:g;return(0,Z.jsxs)(`div`,{"data-chat-session-id":r.id,"data-chat-session-selectable":p?`false`:`true`,className:K(`group relative rounded-xl border transition-colors`,o?`border-sky-400/40 bg-sky-500/10 text-foreground ring-1 ring-sky-400/40`:`border-border/50 bg-card/35 text-muted-foreground hover:border-border/80 hover:bg-card/60 hover:text-foreground`),onPointerDownCapture:e=>{!c||p||e.pointerType&&e.pointerType!==`mouse`||typeof e.button==`number`&&e.button!==0||(e.preventDefault(),A(),O.current=!0,D.current={pointerId:e.pointerId,mode:h?`deselect`:`select`,visitedSessionIds:new Set},N(r.id))},onPointerMove:e=>{let t=D.current;!t||t.pointerId!==e.pointerId||N(r.id)},children:[(0,Z.jsx)(`button`,{type:`button`,"aria-label":[r.title,PZ(r.mode),MZ(r.tool),e?.memory_enabled&&r.pending_memory_suggestion_count>0?IZ(r.pending_memory_suggestion_count):null,g===`running`?mZ(`sidebar.running`):g===`interrupted`?mZ(`sidebar.interrupted`):g===`finished`?mZ(`sidebar.finished`):null].filter(Boolean).join(` `),className:`flex w-full min-w-0 cursor-pointer items-start gap-2 rounded-xl px-3 py-2 pr-11 text-left transition-colors focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none`,onClick:()=>{if(c){if(O.current){O.current=!1;return}if(p)return;w(r.id);return}C(r)},children:(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[u?(0,Z.jsx)(`div`,{className:`mb-1 truncate text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground/75`,children:u}):null,(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`truncate text-[13px] font-medium leading-5`,children:r.title}),e?.memory_enabled&&r.pending_memory_suggestion_count>0?(0,Z.jsx)(qX,{tone:o?`default`:`muted`,className:`shrink-0`,"aria-label":IZ(r.pending_memory_suggestion_count),title:IZ(r.pending_memory_suggestion_count),children:r.pending_memory_suggestion_count}):null]}),s?(0,Z.jsx)(`div`,{className:K(`mt-0.5 line-clamp-1 text-xs leading-4`,o?`text-foreground/70`:`text-muted-foreground`),children:s}):null,r.target_available===!1?(0,Z.jsx)(`div`,{className:`mt-1 line-clamp-1 text-[11px] leading-4 text-amber-200/90`,children:r.target_unavailable_reason??mZ(`sidebar.targetUnavailable`)}):null]}),(0,Z.jsx)(Rl,{state:_,className:`mt-1`})]})}),c?(0,Z.jsx)(`div`,{className:`absolute top-2 right-2 flex h-7 w-7 items-center justify-center`,title:d??mZ(`sidebar.selectSessionTitle`,{title:r.title}),children:(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":mZ(`sidebar.selectSessionAriaLabel`,{title:r.title}),checked:h,disabled:p,onClick:e=>{e.stopPropagation()},onChange:()=>{O.current||w(r.id)},className:`h-4 w-4 rounded border-border bg-background text-primary`})}):(0,Z.jsx)(q,{type:`button`,size:`icon-sm`,variant:`ghost`,"aria-label":mZ(`sidebar.deleteSessionAriaLabel`),className:K(`absolute top-2 right-2 h-7 w-7 shrink-0 rounded-md border border-transparent text-muted-foreground transition-all duration-150 hover:border-border/70 hover:bg-card/80 hover:text-foreground focus-visible:border-border/70 focus-visible:bg-card/80 focus-visible:text-foreground`,`opacity-100 sm:opacity-0 sm:pointer-events-none sm:group-hover:pointer-events-auto sm:group-focus-within:pointer-events-auto sm:group-hover:opacity-100 sm:group-focus-within:opacity-100`,p&&`sm:disabled:opacity-0 sm:group-hover:disabled:opacity-50 sm:group-focus-within:disabled:opacity-50`,(o||f)&&`sm:pointer-events-auto sm:opacity-100 sm:disabled:opacity-50`,d&&`cursor-not-allowed text-muted-foreground/50 hover:border-transparent hover:bg-transparent hover:text-muted-foreground/50 focus-visible:border-transparent focus-visible:bg-transparent focus-visible:text-muted-foreground/50`),title:d??mZ(`sidebar.deleteSessionTitle`,{title:r.title}),disabled:p,onClick:e=>{e.stopPropagation(),v(r.id)},children:(0,Z.jsx)(wu,{className:`h-4 w-4`})})]},r.id)})]},r.key))})})]}):(0,Z.jsxs)(`div`,{"data-testid":`chat-sessions-rail`,className:`flex h-full w-full flex-col items-center gap-2 bg-background/80 py-3`,children:[(0,Z.jsx)(xc,{content:(0,Z.jsx)(UZ,{label:mZ(`shortcuts.startNewSession`),modifierLabel:r,keys:[TZ]}),side:`right`,children:(0,Z.jsx)(q,{type:`button`,size:`icon-sm`,"aria-label":mZ(`sidebar.newSession`),className:`h-9 w-9`,onClick:y,disabled:s||f,children:(0,Z.jsx)(zl,{className:`h-4 w-4`})})}),(0,Z.jsx)(q,{type:`button`,size:`icon-sm`,variant:`ghost`,"aria-label":mZ(`sidebar.openAriaLabel`),"aria-expanded":d,className:`h-9 w-9`,onClick:T,children:(0,Z.jsx)(DX,{className:`h-4 w-4`})})]})})},xQ=({proposals:e,isApplying:t,onApply:n})=>e.status===`applied`?(0,Z.jsxs)(`div`,{className:`w-full rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3 py-3 text-sm`,children:[(0,Z.jsx)(`div`,{className:`font-medium text-foreground`,children:mZ(`ticketProposal.createdTitle`)}),(0,Z.jsx)(`div`,{className:`mt-1 text-muted-foreground`,children:mZ(`ticketProposal.createdDescription`,{count:e.created_tickets.length})}),e.created_tickets.length>0?(0,Z.jsx)(`ul`,{className:`mt-3 space-y-1 text-foreground`,children:e.created_tickets.map(e=>(0,Z.jsx)(`li`,{children:e.title},e.ticket_id))}):null]}):(0,Z.jsxs)(`div`,{className:`w-full rounded-md border border-sky-500/30 bg-sky-500/10 px-3 py-3 text-sm`,children:[(0,Z.jsx)(`div`,{className:`font-medium text-foreground`,children:mZ(`ticketProposal.proposedTitle`)}),(0,Z.jsx)(`div`,{className:`mt-1 text-muted-foreground`,children:mZ(`ticketProposal.proposedDescription`)}),(0,Z.jsx)(`ul`,{className:`mt-3 space-y-3`,children:e.tickets.map(e=>(0,Z.jsxs)(`li`,{className:`rounded border border-border/60 bg-background/80 px-3 py-2`,children:[(0,Z.jsx)(`div`,{className:`font-medium text-foreground`,children:e.title}),(0,Z.jsx)(`div`,{className:`mt-1 whitespace-pre-wrap text-muted-foreground`,children:e.description})]},e.key))}),e.dependencies.length>0?(0,Z.jsx)(`div`,{className:`mt-3 text-muted-foreground`,children:mZ(`ticketProposal.dependenciesLabel`,{value:e.dependencies.map(e=>`${e.blocker_key} -> ${e.dependent_key}`).join(`, `)})}):null,(0,Z.jsx)(`div`,{className:`mt-3`,children:(0,Z.jsx)(q,{type:`button`,size:`sm`,onClick:n,disabled:t,children:mZ(t?`ticketProposal.creating`:`ticketProposal.create`)})})]}),SQ=({activeProjectId:e,activeProject:t,activeProjectBranchState:n=null,activeTool:r,onRestoreSessionTarget:i,onReviewCapabilityChange:a,isExternallyResizing:o=!1,showChangesPanel:s=!0})=>{let c=zY(),[l,u]=(0,Y.useState)([]),[d,f]=(0,Y.useState)(null),[p,m]=(0,Y.useState)(null),[h,g]=(0,Y.useState)(null),[_,v]=(0,Y.useState)(!1),[y,b]=(0,Y.useState)(()=>sQ({projectId:e,tool:r})),[x,S]=(0,Y.useState)({}),[C,w]=(0,Y.useState)({}),[T,E]=(0,Y.useState)({}),[D,O]=(0,Y.useState)([]),[k,A]=(0,Y.useState)([]),[j,M]=(0,Y.useState)(``),[N,P]=(0,Y.useState)(``),[F,I]=(0,Y.useState)([]),[L,R]=(0,Y.useState)(!1),[ee,te]=(0,Y.useState)(!1),[ne,re]=(0,Y.useState)(!1),[B,ie]=(0,Y.useState)(!1),[V,H]=(0,Y.useState)(!1),[ae,oe]=(0,Y.useState)(null),[se,ce]=(0,Y.useState)([]),[le,ue]=(0,Y.useState)(()=>new Set),[de,U]=(0,Y.useState)(!1),[fe,pe]=(0,Y.useState)(()=>new Set),[me,he]=(0,Y.useState)(!1),[G,ge]=(0,Y.useState)(!1),[_e,ve]=(0,Y.useState)(null),[ye,be]=(0,Y.useState)([]),[xe,Se]=(0,Y.useState)(!1),[Ce,we]=(0,Y.useState)(!1),[Te,Ee]=(0,Y.useState)(0),[De,Oe]=(0,Y.useState)(iZ),[ke,Ae]=(0,Y.useState)(()=>nQ(e).isOpen),[je,Me]=(0,Y.useState)(()=>tQ(e).isOpen),[Ne,Pe]=(0,Y.useState)(!1),[Fe,Ie]=(0,Y.useState)(!1),[Le,Re]=(0,Y.useState)(()=>tQ(e).width),[ze,Be]=(0,Y.useState)(0),[Ve,He]=(0,Y.useState)(null),[Ue,We]=(0,Y.useState)(()=>new Set),Ge=(0,Y.useRef)({model:``,variant:``,skills:[],showModelSelector:!1}),Ke=(0,Y.useRef)(!1),qe=(0,Y.useRef)(null),Ye=(0,Y.useRef)(0),Xe=(0,Y.useRef)(0),Ze=(0,Y.useRef)(null),Qe=(0,Y.useRef)(null),$e=(0,Y.useRef)(null),et=(0,Y.useRef)(null),J=(0,Y.useRef)(null),tt=(0,Y.useRef)(null),nt=(0,Y.useRef)(!1),rt=(0,Y.useRef)(!1),it=(0,Y.useRef)(0),at=(0,Y.useRef)(bZ),ot=(0,Y.useRef)(bZ),st=(0,Y.useRef)(!1),ct=(0,Y.useRef)(0),lt=(0,Y.useRef)({id:null,status:null}),ut=(0,Y.useRef)(new Map),dt=(0,Y.useRef)({}),ft=(0,Y.useRef)({}),pt=(0,Y.useRef)(new Set),mt=(0,Y.useRef)(!1),ht=e?XZ({projectId:e,tool:_?r:p?.tool??r,chatSessionId:_?null:d}):null,gt=ht?x[ht]??``:``,_t=_?r:p?.tool??r,vt=p?C[p.id]??[]:[],yt=(p?T[p.id]??0:0)>0;(0,Y.useEffect)(()=>{Ke.current=_},[_]),(0,Y.useEffect)(()=>{dt.current=x},[x]),(0,Y.useEffect)(()=>{ft.current=C},[C]),(0,Y.useEffect)(()=>{if(!ht||pt.current.has(ht))return;pt.current.add(ht);let e=$Z(ht);e&&S(t=>Object.prototype.hasOwnProperty.call(t,ht)?t:{...t,[ht]:e})},[ht]),(0,Y.useEffect)(()=>{!ht||!Object.prototype.hasOwnProperty.call(x,ht)||eQ({storageKey:ht,value:x[ht]??``})},[ht,x]),(0,Y.useEffect)(()=>{qe.current=d},[d]);let bt=(0,Y.useCallback)(()=>{Xe.current+=1},[]),X=(0,Y.useCallback)(e=>{bt(),m(e)},[bt]);(0,Y.useEffect)(()=>{if(!mt.current){mt.current=!0;return}let t=tQ(e),n=nQ(e);Ke.current=!1,st.current=!1,pt.current=new Set,f(null),X(null),v(!1),S({}),w({}),E({}),oe(null),ce([]),ue(new Set),U(!1),pe(new Set),He(null),be([]),we(!1),te(!1),Oe(iZ()),We(new Set),ut.current=new Map,ot.current=t.width,Ae(n.isOpen),Re(t.width),Me(t.isOpen)},[e,X]),(0,Y.useEffect)(()=>{Ne||(ot.current=Le,$e.current&&($e.current.style.setProperty(`--chat-changes-panel-width`,`${Le}px`),$e.current.setAttribute(`data-desktop-width`,String(Le))))},[Le,Ne]),(0,Y.useEffect)(()=>{if(!s||!Ze.current)return;let e=Ze.current.getBoundingClientRect().width;if(e<=0)return;let t=jZ(Le,e);t!==Le&&(ot.current=t,Re(t))},[Le,s]),(0,Y.useEffect)(()=>{iQ({projectId:e,isOpen:ke})},[e,ke]),(0,Y.useEffect)(()=>{s&&rQ({projectId:e,isOpen:je,width:Le})},[e,Le,je,s]),(0,Y.useEffect)(()=>{we(!1)},[d,_]);let xt=(0,Y.useCallback)(e=>{let t=pZ(e);u(e=>{let n=e.findIndex(e=>e.id===t.id);if(n===-1)return lZ([...e,t]);let r=[...e];return r[n]=t,lZ(r)})},[]),St=(0,Y.useCallback)(t=>{let n=Array.from(new Set(t));if(n.length===0)return;let i=new Set(n),a=qe.current,o=e?n.map(t=>XZ({projectId:e,tool:r,chatSessionId:t})):[];S(e=>{let t=o.filter(t=>Object.prototype.hasOwnProperty.call(e,t));if(t.length===0)return e;let n={...e};for(let e of t)delete n[e];return n}),w(e=>{let t={...e},r=!1;for(let e of n)Object.prototype.hasOwnProperty.call(t,e)&&(delete t[e],r=!0);return r?t:e}),E(e=>{let t={...e},r=!1;for(let e of n)Object.prototype.hasOwnProperty.call(t,e)&&(delete t[e],r=!0);return r?t:e});for(let e of o)eQ({storageKey:e,value:``});u(e=>{let t=e.filter(e=>!i.has(e.id));if(a&&i.has(a)){let e=t[0]??null;f(e?.id??null),X(null),v(e===null),be([]),Se(!1),we(!1)}return t}),We(e=>{let t=new Set(e),r=!1;for(let e of n)t.delete(e)&&(r=!0);return r?t:e}),He(e=>e?.sessionId&&i.has(e.sessionId)?null:e),oe(e=>e&&i.has(e)?null:e),ce(e=>e.filter(e=>!i.has(e))),ue(e=>{let t=new Set(e),r=!1;for(let e of n)t.delete(e)&&(r=!0);return r?t:e}),pe(e=>{let t=new Set(e),r=!1;for(let e of n)t.delete(e)&&(r=!0);return r?t:e})},[e,r,X]),Ct=(0,Y.useCallback)(e=>{St([e])},[St]),wt=(0,Y.useCallback)((e,t)=>{e&&S(n=>n[e]===t?n:{...n,[e]:t})},[]),Tt=(0,Y.useCallback)(e=>{e&&(S(t=>t[e]===``?t:{...t,[e]:``}),eQ({storageKey:e,value:``}))},[]),Et=(0,Y.useCallback)((e,t)=>{w(n=>{if(t.length===0){if(!Object.prototype.hasOwnProperty.call(n,e))return n;let t={...n};return delete t[e],t}return{...n,[e]:t}})},[]),Dt=(0,Y.useCallback)(e=>{w(t=>{if(!Object.prototype.hasOwnProperty.call(t,e))return t;let n={...t};return delete n[e],n}),E(t=>{if(!Object.prototype.hasOwnProperty.call(t,e))return t;let n={...t};return delete n[e],n})},[]),Ot=(0,Y.useCallback)((e,t)=>{E(n=>{let r=Math.max(0,(n[e]??0)+t);if(r===0){if(!Object.prototype.hasOwnProperty.call(n,e))return n;let t={...n};return delete t[e],t}return{...n,[e]:r}})},[]),kt=(0,Y.useCallback)(({fromStorageKey:e,toStorageKey:t})=>{if(!e||!t||e===t)return;let n=Object.prototype.hasOwnProperty.call(dt.current,e)?dt.current[e]??``:$Z(e);S(r=>{let i={...r,[t]:n};return delete i[e],i}),eQ({storageKey:t,value:n}),eQ({storageKey:e,value:``})},[]),At=(0,Y.useCallback)((e,t)=>{u(n=>{let r=n.findIndex(t=>t.id===e);if(r===-1)return n;let i=n[r];if(i.pending_memory_suggestion_count===t)return n;let a=[...n];return a[r]={...i,pending_memory_suggestion_count:t},a}),m(n=>!n||n.id!==e||n.pending_memory_suggestion_count===t?n:(Xe.current+=1,{...n,pending_memory_suggestion_count:t}))},[]),jt=(0,Y.useCallback)(async r=>{if(!e){u([]),f(null),X(null),v(!1),te(!1);return}R(!0);try{let i=await Zb(e,r);if(r?.aborted)return;let a=lZ(i.map(pZ)),o=a[0]??null,s=t?.active_target_kind===`bundle`||n?.status!==`loading`;u(a),f(e=>Ke.current?null:e&&a.some(t=>t.id===e)?e:e?a[0]?.id??null:st.current?null:o?s?(st.current=!0,mQ({activeProject:t,activeProjectBranchState:n,session:o})?o.id:null):null:(st.current=!0,null)),a.length===0&&v(!0)}catch(e){z(e)||Q.error(e instanceof Error?e.message:mZ(`errors.loadSessions`))}finally{r?.aborted||(R(!1),te(!0))}},[t,n,e,X]),Mt=(0,Y.useCallback)(async(t,n)=>{if(!e){X(null);return}re(!0);let r=Ye.current+1;Ye.current=r;let i=Xe.current;try{let a=await $b(e,t,n);if(n?.aborted)return;let o=Xe.current!==i,s=Ye.current===r,c=qe.current===t&&!Ke.current;if(!s||o||!c)return;X(a),xt(a)}catch(e){z(e)||Q.error(e instanceof Error?e.message:mZ(`errors.loadSession`))}finally{n?.aborted||re(!1)}},[e,X,xt]),Nt=(0,Y.useCallback)(async(n,r)=>{if(!e||!t?.memory_enabled){be([]),Se(!1);return}Se(!0);try{let t=await Je(e,null,r,n);if(r?.aborted)return;be(t.suggestions),At(n,t.suggestions.length)}catch(e){z(e)||Q.error(e instanceof Error?e.message:mZ(`errors.loadMemorySuggestions`))}finally{r?.aborted||Se(!1)}},[t?.memory_enabled,e,At]),Pt=(0,Y.useCallback)(()=>{be(e=>{let t=e.length>0?e.slice(0,-1):e;return d&&At(d,t.length),t}),Ee(e=>e+1),jt(),d&&Mt(d)},[d,Mt,jt,At]);(0,Y.useEffect)(()=>{let e=new AbortController;return jt(e.signal),()=>{e.abort()}},[jt]),(0,Y.useEffect)(()=>{if(Ke.current||_||d||st.current||l.length===0||t?.active_target_kind!==`bundle`&&n?.status===`loading`)return;st.current=!0;let e=l[0]??null;e&&mQ({activeProject:t,activeProjectBranchState:n,session:e})&&f(e.id)},[t,n,d,_,l]),(0,Y.useEffect)(()=>{if(_t!==`opencode`){O([]),A([]),ge(!1);return}let t=new AbortController;return(async()=>{ge(!0);try{let[n,r]=await Promise.all([wn(_t,t.signal),gw(_t,t.signal,e)]);O(n),A(r)}catch(e){z(e)||(O(e=>e),A(e=>e))}finally{t.signal.aborted||ge(!1)}})(),()=>{t.abort()}},[e,_t]),(0,Y.useEffect)(()=>{if(_||!d){X(null);return}if(p?.id===d)return;X(null);let e=new AbortController;return Mt(d,e.signal),()=>{e.abort()}},[p,d,_,Mt,X]),(0,Y.useEffect)(()=>{if(!t?.memory_enabled||_||!d){be([]),Se(!1);return}let e=new AbortController;return Nt(d,e.signal),()=>{e.abort()}},[t?.memory_enabled,d,_,Nt,Te]),(0,Y.useEffect)(()=>{!Ce||xe||ye.length>0||we(!1)},[xe,Ce,ye.length]),(0,Y.useEffect)(()=>{if(!d||p?.agent_status!==`running`)return;let e=new AbortController,t=window.setInterval(()=>{Promise.all([jt(e.signal),Mt(d,e.signal)])},hZ);return()=>{e.abort(),window.clearInterval(t)}},[p?.agent_status,d,Mt,jt]),(0,Y.useEffect)(()=>{if(!e)return;let t=t=>{!t||t.project_id!==e||(t.id===d&&X(t),pQ(t)&&xt(t))},n=t=>{!t||t.project_id!==e||Ct(t.id)};return c.on(`chat-session:created`,t),c.on(`chat-session:updated`,t),c.on(`chat-session:deleted`,n),()=>{c.off(`chat-session:created`,t),c.off(`chat-session:updated`,t),c.off(`chat-session:deleted`,n)}},[e,d,Ct,X,c,xt]),(0,Y.useEffect)(()=>{_&&b(sQ({projectId:e,tool:r}))},[e,r,_]),(0,Y.useEffect)(()=>{if(_t!==`opencode`){M(``),P(``),I([]);return}if(_){let n=cQ({activeProjectId:e,helperModel:t?.helper_model??null,helperVariant:t?.helper_variant??null,activeTool:_t,availableModels:D});M(n.model),P(n.variant),I([]);return}M(p?.model??t?.helper_model??``),P(p?.variant??t?.helper_variant??``),I(p?.skills??[])},[e,t?.helper_model,t?.helper_variant,p?.id,p?.model,p?.skills,p?.variant,D,_t,_]),(0,Y.useEffect)(()=>{let e=D.find(e=>e.id===j)??null;P(t=>e?e.variants.includes(t)?t:``:t)},[D,j]),(0,Y.useEffect)(()=>{if(_t!==`opencode`||!_||!j||N)return;let n=cQ({activeProjectId:e,helperModel:t?.helper_model??null,helperVariant:t?.helper_variant??null,activeTool:_t,availableModels:D});n.model===j&&n.variant&&P(n.variant)},[e,t?.helper_model,t?.helper_variant,_t,D,_,j,N]),(0,Y.useEffect)(()=>{if(!ae)return;let e=p?.id===ae?p:l.find(e=>e.id===ae)??null;(!e||e.agent_status!==`running`)&&oe(null)},[p,ae,l]),(0,Y.useEffect)(()=>{let e=lt.current,n=p?.id??null,r=p?.agent_status??null;e.id===n&&e.status===`running`&&r===`done`&&t?.memory_enabled&&n&&Ee(e=>e+1),lt.current={id:n,status:r}},[t?.memory_enabled,e,p?.agent_status,p?.id,p?.title]),(0,Y.useEffect)(()=>{d&&We(e=>{if(!e.has(d))return e;let t=new Set(e);return t.delete(d),t})},[d]),(0,Y.useEffect)(()=>{Ve&&Ve.sessionId!==d&&He(null)},[d,Ve]),(0,Y.useEffect)(()=>{let e=ut.current,t=new Map,n=[];for(let r of l){let i=e.get(r.id)??null,a=r.agent_status??null;i===`running`&&a===`done`&&r.id!==d&&n.push(r),t.set(r.id,a)}ut.current=t,We(e=>{let t=new Set(e),r=!1,i=new Set(l.map(e=>e.id));for(let e of t)i.has(e)||(t.delete(e),r=!0);for(let e of l){let i=e.agent_status??null,a=n.some(t=>t.id===e.id);if((e.id===d||i!==`done`)&&t.delete(e.id)){r=!0;continue}a&&!t.has(e.id)&&(t.add(e.id),r=!0)}return r?t:e})},[e,d,l]);let Ft=(0,Y.useMemo)(()=>new Map(D.map(e=>[e.id,e.label])),[D]),It=(0,Y.useMemo)(()=>fZ(l),[l]),Lt=(0,Y.useMemo)(()=>se.length===0?[]:se.flatMap(e=>{let t=l.find(t=>t.id===e)??(p?.id===e?p:null);return t?[t]:[]}),[p,se,l]),Rt=Lt.length===1?Lt[0]?.title??null:null;(0,Y.useEffect)(()=>{se.length>0&&Lt.length!==se.length&&ce(Lt.map(e=>e.id))},[se,Lt]),(0,Y.useEffect)(()=>{let e=new Set(l.filter(e=>!vQ(e)&&!le.has(e.id)).map(e=>e.id));pe(t=>{let n=new Set(Array.from(t).filter(t=>e.has(t)));return n.size===t.size?t:n})},[le,l]),(0,Y.useEffect)(()=>{!de||ke||(U(!1),pe(new Set))},[ke,de]);let zt=(0,Y.useMemo)(()=>p?WZ({modelLabel:NZ({availableModelsById:Ft,model:p.model}),tool:p.tool}):null,[p,Ft]),Bt=(0,Y.useMemo)(()=>p?(p.messages??[]).map(e=>({id:e.id,role:e.role,kind:e.kind,content:e.content,attachments:e.attachments??[],ticket_proposals:e.ticket_proposals??null,created_at:e.created_at,displayTitle:e.role===`assistant`?zt??MZ(p.tool):GZ()})):[],[p,zt]),Vt=p?.id&&p.agent_status===`running`&&Ve?.sessionId===p.id?Ve.turnKey:null,Ht=_t===`opencode`&&D.length>0,Ut=_t===`opencode`&&!Ht&&G;(0,Y.useEffect)(()=>{Ge.current={model:j,variant:N,skills:F,showModelSelector:Ht}},[j,F,N,Ht]);let Wt=(0,Y.useMemo)(()=>D.find(e=>e.id===j)??null,[D,j]),Gt=_?y:p?.mode??`build`,Kt=_?mZ(`composer.newChatTitle`):p?.title??mZ(`composer.chatTitle`),qt=_?r:p?.tool??r,Jt=(0,Y.useMemo)(()=>VZ(),[]),Yt=Ht?j||null:p?.model??null,Xt=qt===`opencode`,Zt=NZ({availableModelsById:Ft,model:Yt}),Qt=(0,Y.useMemo)(()=>{let e=p?.usage_snapshot_total_tokens??null;if(e===null)return null;let t=JZ({tool:qt,model:Yt,availableModels:D,fallbackContextWindow:p?.usage_snapshot_context_window??null});if(t===null)return null;let n=qZ({totalTokens:e,contextWindow:t});return n===null?null:`${KZ(e)} (${n}%)`},[p?.usage_snapshot_context_window,p?.usage_snapshot_total_tokens,D,Yt,qt]),$t=_?`draft:${e??`none`}:${r}`:p?.id,en=(0,Y.useCallback)(()=>{Ke.current=!0,v(!0),b(sQ({projectId:e,tool:r})),g(null),f(null),X(null),oe(null),U(!1),pe(new Set),He(null)},[e,r,X]),tn=(0,Y.useCallback)((e,t=null)=>{Ke.current=!1,v(!1),g(null),f(e),X(t)},[X]),nn=(0,Y.useCallback)(async()=>{if(!(!p||!i)){g(p.id);try{await i(p)}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.restoreTarget`))}finally{g(e=>e===p.id?null:e)}}},[p,i]),rn=!!(p&&p.target_available!==!1&&!_&&!mQ({activeProject:t,activeProjectBranchState:n,session:p})),an=rn&&p?mZ(`review.mismatchReason`,{sessionTarget:gQ(p),currentTarget:_Q({activeProject:t,activeProjectBranchState:n})}):null,on=rn&&h===null,sn=(0,Y.useCallback)(async r=>{g(r.id);let a=r;if(e)try{let t=await $b(e,r.id);a=t,xt(t)}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.loadSession`)),g(e=>e===r.id?null:e);return}if(a.target_available===!1){tn(a.id,a);return}if(!mQ({activeProject:t,activeProjectBranchState:n,session:a})&&i)try{if(!await i(a)){g(e=>e===a.id?null:e);return}}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.restoreTarget`)),g(e=>e===a.id?null:e);return}tn(a.id,a)},[t,n,e,i,tn,xt]),cn=(0,Y.useCallback)(()=>{Be(e=>e+1)},[]),ln=(0,Y.useCallback)(async t=>{if(_){let n=Ge.current;b(t),oQ({projectId:e,tool:r,model:n.showModelSelector&&n.model||null,variant:n.showModelSelector&&n.model&&n.variant||null,mode:t}),cn();return}if(!(!e||!p||p.mode===t||me)){he(!0);try{let n=await ex(e,p.id,{mode:t});oQ({projectId:e,tool:n.tool,model:n.model,variant:n.variant,mode:n.mode}),X(n),xt(n),cn()}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.updateMode`))}finally{he(!1)}}},[e,p,r,cn,_,me,X,xt]),un=(0,Y.useCallback)(async({instruction:t,attachments:n,targetSession:r})=>{if(!e)return null;let i=Ge.current;ct.current+=1;let a={sessionId:r.id,turnKey:`${r.id}:${ct.current}`};He(a);try{let a=await tx(e,r.id,{instruction:t,...n.length>0?{attachment_ids:n.map(e=>e.id)}:{},tool:r.tool,model:i.showModelSelector&&i.model||null,variant:i.showModelSelector&&i.model&&i.variant||null,skills:i.showModelSelector?i.skills:[]});return oQ({projectId:e,tool:a.tool,model:a.model,variant:a.variant,mode:a.mode}),Ke.current=!1,X(a),f(a.id),v(!1),xt(a),a}catch(e){throw He(e=>e?.turnKey===a.turnKey?null:e),e}},[e,X,xt]),dn=(0,Y.useCallback)(async({fromStorageKey:t})=>{if(!e)return null;let n=Ge.current,i=await Qb(e,{mode:Gt,tool:r,model:n.showModelSelector&&n.model||null,variant:n.showModelSelector&&n.model&&n.variant||null,skills:n.showModelSelector?n.skills:[]});Ke.current=!1,v(!1),f(i.id),X(i);let a=XZ({projectId:e,tool:i.tool,chatSessionId:i.id});return kt({fromStorageKey:t,toStorageKey:a}),{session:i,storageKey:a}},[e,r,Gt,kt,X]),fn=(0,Y.useCallback)(async t=>{if(!e||V||B||yt||p?.agent_status===`running`||p?.target_available===!1||on)return!1;let n=t.trim(),r=p?ft.current[p.id]??[]:[];if(!n&&r.length===0)return!1;H(!0);let i=null,a=p,o=e&&p?XZ({projectId:e,tool:p.tool,chatSessionId:p.id}):null,s=r;try{let t=p;if(!t){ie(!0);let e=await dn({fromStorageKey:ht});i=e?.session??null,t=i,o=e?.storageKey??null,s=i?ft.current[i.id]??[]:[]}if(!t)return!1;Tt(o??ht);let r=fQ({session:t,instruction:n,attachments:s,createdAt:new Date().toISOString()});X(r),f(r.id),xt(r);let a=await un({instruction:n,attachments:s,targetSession:t});return Tt(a&&e?XZ({projectId:e,tool:a.tool,chatSessionId:a.id}):o),a&&Dt(a.id),!0}catch(e){throw wt(o??ht,n),i?(X(i),f(i.id),v(!1),xt(i)):a&&(X(a),xt(a)),e}finally{ie(!1),H(!1)}},[e,p,Dt,Tt,dn,ht,B,V,yt,X,un,wt,on,xt]),pn=(0,Y.useCallback)(e=>{Ke.current=!0,v(!0),b(e),g(null),f(null),X(null),oe(null),He(null)},[X]),mn=(0,Y.useCallback)(async t=>{if(!e||t.length===0||_t!==`opencode`)return;let n=t.slice(0,kZ);if(n.length===0)return;let r=null,i=p;try{if(i||=(ie(!0),r=await dn({fromStorageKey:ht}),r?.session??null),!i)return;if((ft.current[i.id]??[]).length+n.length>kZ){Q.error(`You can attach up to 4 images per turn.`);return}Ot(i.id,1);let t=await nx(e,i.id,n),a=ft.current[i.id]??[];Et(i.id,[...a,...t.attachments])}catch(t){if(r&&!gt.trim())try{await ax(e,r.session.id),Ct(r.session.id),pn(r.session.mode)}catch{}Q.error(t instanceof Error?t.message:mZ(`errors.uploadAttachments`))}finally{i&&Ot(i.id,-1),ie(!1)}},[e,p,dn,gt,ht,Ot,pn,Ct,Et,_t]),hn=(0,Y.useCallback)(async t=>{if(!e||!p)return;let n=(ft.current[p.id]??[]).filter(e=>e.id!==t);try{await rx(e,p.id,t),Et(p.id,n),n.length===0&&!gt.trim()&&(p.messages?.length??0)===0&&(await ax(e,p.id),Ct(p.id),pn(p.mode))}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.removeAttachment`))}},[e,p,gt,pn,Ct,Et]),gn=(0,Y.useCallback)(e=>{if(_t!==`opencode`)return;let t=Array.from(e.clipboardData.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).map(e=>e.getAsFile()).filter(e=>e!==null);t.length!==0&&(e.preventDefault(),mn(t))},[_t,mn]),_n=(0,Y.useCallback)(async e=>{await fn(e)},[fn]),vn=!!(e&&(_||p&&p.target_available!==!1&&!on)),yn=p?.agent_status===`running`,bn=p?.agent_status===`stopped`,xn=yn&&ae===p?.id,Sn=vn&&!yn&&!V&&!B&&!yt,Cn=vn?p?.target_available===!1?p.target_unavailable_reason??mZ(`review.unavailableTarget`):on?an??mZ(`review.restoreTargetFallback`):yn?mZ(`review.waitTurn`):yt?mZ(`review.waitUpload`):B||V?mZ(`review.waitPrompt`):null:mZ(`review.missingTarget`),Tn=(0,Y.useCallback)(async()=>{if(!(!e||!p||p.agent_status!==`running`||xn)){oe(p.id);try{await ix(e,p.id)}catch(e){oe(e=>e===p.id?null:e),Q.error(e instanceof Error?e.message:mZ(`errors.interruptResponse`))}}},[e,p,xn]),En=(0,Y.useCallback)(async()=>{if(!e||se.length===0||le.size>0)return;let t=Array.from(new Set(se)),n=de||t.length>1;ue(new Set(t));let r=await Promise.allSettled(t.map(async t=>(await ax(e,t),t))),i=[],a=[];for(let[e,n]of r.entries()){if(n.status===`fulfilled`){i.push(n.value);continue}a.push({sessionId:t[e]??``,message:n.reason instanceof Error?n.reason.message:null})}if(i.length>0&&St(i),ue(new Set),a.length===0){ce([]),n&&(U(!1),pe(new Set),Q.success(mZ(`toasts.deleteSelectedSuccess`,{count:i.length})));return}let o=a.map(e=>e.sessionId);if(ce(o),n&&pe(new Set(o)),i.length>0){Q.error(mZ(`toasts.deleteSelectedPartial`,{count:i.length,deletedCount:i.length,failedCount:a.length}));return}Q.error(a[0]?.message??mZ(`errors.deleteSession`))},[e,se,le,de,St]),Dn=(0,Y.useMemo)(()=>l.some(e=>!vQ(e)),[l]),On=(0,Y.useCallback)((e,t)=>{pe(n=>{if(n.has(e)===t)return n;let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),kn=(0,Y.useMemo)(()=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(GX,{value:Gt,planInactiveTooltip:(0,Z.jsx)(UZ,{label:mZ(`shortcuts.switchToPlan`),modifierLabel:Jt,keys:[wZ]}),buildInactiveTooltip:(0,Z.jsx)(UZ,{label:mZ(`shortcuts.switchToBuild`),modifierLabel:Jt,keys:[wZ]}),disabled:me,onChange:e=>{ln(e)}}),yn?(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`outline`,className:`gap-2`,disabled:xn,onClick:()=>{Tn()},children:[xn?(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}):(0,Z.jsx)(Fc,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:mZ(xn?`review.interrupting`:`review.interrupt`)})]}):null]}),[Jt,Gt,Tn,ln,xn,yn,me]),An=(0,Y.useMemo)(()=>Ht?(0,Z.jsx)(CP,{model:j,variant:N,skills:F,showModelSelector:!0,showSkillsSelector:!0,availableModels:D,availableSkills:k,selectedModel:Wt,onModelChange:e=>{let t=D.find(t=>t.id===e)??null;M(e),P(e=>t&&t.variants.includes(e)?e:``)},onVariantChange:P,onSkillsChange:I,modelSelectId:`project-chat-model-selector`,variantSelectId:`project-chat-variant-selector`,skillsSelectId:`project-chat-skills-selector`,disabled:V||B||p?.agent_status===`running`}):Ut?(0,Z.jsx)(SP,{dataTestId:`chat-model-selector-skeleton`}):null,[p?.agent_status,D,k,B,V,Wt,j,F,N,Ht,Ut]);(0,Y.useEffect)(()=>{if(a)return()=>{a(null)}},[a]),(0,Y.useEffect)(()=>{if(a){if(!e||!vn){a(null);return}a({chatSessionId:p?.id??null,canSubmitReviewPrompt:Sn,reviewSubmitDisabledReason:Cn,mode:Gt,onModeChange:ln,isUpdatingMode:me,promptPlaceholder:FZ(Gt),promptComposerControls:kn,promptComposerInlineControls:An,submitPrompt:_n})}},[e,p,Sn,Gt,ln,_n,vn,me,a,kn,An,Cn]);let jn=async()=>{if(!(!gt.trim()&&vt.length===0||yt))try{if(!await fn(gt))return}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.sendPrompt`))}},Mn=e=>{e.key!==`Enter`||e.shiftKey||p?.agent_status===`running`||B||V||yt||(e.preventDefault(),jn())};(0,Y.useEffect)(()=>{let t=t=>{if(zZ(t)){if(!e||B||V)return;t.preventDefault(),en(),cn();return}RZ(t)&&(!e||!_&&!p||(t.preventDefault(),ln(LZ(Gt))))};return window.addEventListener(`keydown`,t),()=>{window.removeEventListener(`keydown`,t)}},[e,p,Gt,cn,en,ln,B,_,V]);let Nn=(0,Y.useCallback)(async t=>{if(!(!e||!p)){ve(t);try{let n=await cx(e,p.id,t);X(n.chatSession),xt(n.chatSession),Q.success(mZ(`ticketProposal.createdFromChat`,{count:n.created_tickets.length}))}catch(e){Q.error(e instanceof Error?e.message:mZ(`errors.createTickets`))}finally{ve(e=>e===t?null:e)}}},[e,p,X,xt]),Pn=(0,Y.useCallback)(e=>{if(!Ze.current)return;let t=Ze.current.getBoundingClientRect().width,n=jZ(e,t);ot.current=n,$e.current&&($e.current.style.setProperty(`--chat-changes-panel-width`,`${n}px`),$e.current.setAttribute(`data-desktop-width`,String(n)))},[]),Fn=(0,Y.useCallback)(()=>{tt.current?.(),tt.current=null},[]),In=(0,Y.useCallback)(e=>{let t=et.current,n=J.current,r=nt.current;if(t!==null){if(et.current=null,J.current=null,nt.current=!1,Pe(!1),Ie(!1),Fn(),e!==null&&typeof Qe.current?.hasPointerCapture==`function`&&Qe.current.hasPointerCapture(e)&&typeof Qe.current.releasePointerCapture==`function`&&Qe.current.releasePointerCapture(e),n===`collapsed`){if(!r)return;Re(ot.current),Me(!0);return}Re(ot.current)}},[Fn]),Ln=(0,Y.useCallback)((e,t)=>{if(et.current!==e)return;let n=t-it.current,r=at.current-n;if(J.current===`collapsed`){if(!nt.current&&r<CZ)return;nt.current||(nt.current=!0,rt.current=!0,Ie(!0),Pe(!0))}Pn(r)},[Pn]),Rn=(0,Y.useCallback)((e,t)=>{if(et.current===e){if(t!==null&&(J.current===`inline`||nt.current)){let e=t-it.current;Pn(at.current-e)}In(e)}},[In,Pn]),zn=(0,Y.useCallback)(e=>{if(!s)return;e.preventDefault(),et.current=e.pointerId,J.current=je?`inline`:`collapsed`,nt.current=!1,rt.current=!1,it.current=e.clientX,at.current=je?ot.current:0,Pe(je),Fn(),typeof e.currentTarget.setPointerCapture==`function`&&e.currentTarget.setPointerCapture(e.pointerId);let t=e=>{Ln(e.pointerId,e.clientX)},n=e=>{Rn(e.pointerId,e.clientX)},r=e=>{Rn(e.pointerId,e.clientX)};window.addEventListener(`pointermove`,t),window.addEventListener(`pointerup`,n),window.addEventListener(`pointercancel`,r),tt.current=()=>{window.removeEventListener(`pointermove`,t),window.removeEventListener(`pointerup`,n),window.removeEventListener(`pointercancel`,r)}},[Rn,Ln,je,s,Fn]),Bn=(0,Y.useCallback)(e=>{Ln(e.pointerId,e.clientX)},[Ln]),Vn=(0,Y.useCallback)(e=>{Rn(e.pointerId,e.clientX)},[Rn]),Hn=(0,Y.useCallback)(e=>{Rn(e.pointerId,e.clientX)},[Rn]),Un=(0,Y.useCallback)(e=>{et.current===e.pointerId&&In(e.pointerId)},[In]),Wn=(0,Y.useCallback)(()=>{if(rt.current){rt.current=!1;return}Me(!0)},[]),Gn=(0,Y.useCallback)(()=>{Me(!1)},[]),Kn=(0,Y.useCallback)(e=>{e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),Wn())},[Wn]);(0,Y.useEffect)(()=>{s||(et.current=null,J.current=null,nt.current=!1,rt.current=!1,Pe(!1),Ie(!1),Fn())},[s,Fn]),(0,Y.useEffect)(()=>()=>{Fn()},[Fn]);let qn=!!d,Jn=p?.target_available===!1,Yn=Jn?p?.target_unavailable_reason??mZ(`review.unavailableTarget`):null,Xn=_||!!(p&&p.target_available!==!1&&!on),Zn=!!(t?.memory_enabled&&p&&(ye.length>0||xe)),Qn=s&&(_||qn)&&!Jn&&!on,$n=Qn&&!je&&!Fe,er=Qn&&(je||Fe),tr=`${$t??`none`}:${Qn?`changes-enabled`:`changes-disabled`}:${er?`panel-visible`:`panel-hidden`}`,nr=p||_?(0,Z.jsx)(Z.Fragment,{children:(0,Z.jsx)(WX,{projectId:e,messages:p?Bt:[],internalLog:p?.agent_log??null,currentThinkingMessageId:p?.agent_message_id??null,previousThinkingLog:p?.previous_agent_log??null,previousThinkingMessageId:p?.previous_agent_message_id??null,pendingAgentTitle:zt,streamingResponse:p?.streaming_response??null,isRunning:p?.agent_status===`running`,isLoading:!_&&ne,canShowComposer:Xn,cardClassName:`border-t-0`,isExternallyResizing:o||Ne,pendingAgentRevealKey:Vt,pendingAgentRevealDelayMs:OZ,composerFocusNonce:ze,header:(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`h3`,{className:`truncate text-sm font-semibold text-foreground`,children:Kt}),(0,Z.jsxs)(`div`,{className:AZ,children:[_?null:(0,Z.jsx)(DT,{tool:p?.tool,className:`text-[11px]`}),Zt?(0,Z.jsx)(`p`,{children:Zt}):null,bn?(0,Z.jsx)(`div`,{className:`inline-flex items-center rounded-full border border-amber-500/30 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-100`,children:mZ(`sidebar.interrupted`)}):null,Qt?(0,Z.jsx)(`div`,{"data-testid":`chat-context-usage-badge`,className:`inline-flex items-center rounded-full border border-border/80 bg-muted/40 px-2 py-0.5 text-[11px] font-medium text-foreground`,children:Qt}):null]})]}),Zn?(0,Z.jsx)(q,{type:`button`,size:`xs`,variant:`outline`,className:`gap-2`,onClick:()=>we(!0),children:xe?mZ(`composer.loadingMemory`):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{children:mZ(`composer.memorySuggestions`)}),(0,Z.jsx)(qX,{children:ye.length})]})}):null]}),on&&an?(0,Z.jsx)(`div`,{className:`w-fit max-w-md rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-50`,children:(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`div`,{children:an}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`secondary`,onClick:()=>{nn()},children:mZ(`composer.switchBack`)}),(0,Z.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,onClick:en,children:mZ(`composer.startNewSession`)})]})]})}):null,Jn&&Yn?(0,Z.jsx)(`div`,{className:`w-fit max-w-md rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-50`,children:Yn}):null]}),composerControls:kn,composerInlineControls:An,composerTheme:Gt,layoutKey:$t,scrollLayoutKey:tr,followUpPrompt:gt,draftAttachments:vt,followUpPlaceholder:FZ(Gt),emptyStateText:null,renderMessageFooter:e=>e.ticket_proposals?(0,Z.jsx)(xQ,{proposals:e.ticket_proposals,isApplying:_e===e.id,onApply:()=>{Nn(e.id)}}):null,isSendingFollowUp:V||B,isUploadingAttachments:yt,canAttachImages:Xt,followUpDisabledReason:Jn?Yn??void 0:p?.agent_status===`running`?mZ(`review.waitTurnShort`):yt?mZ(`review.waitUpload`):void 0,onFollowUpPromptChange:e=>{wt(ht,e)},onFollowUpKeyDown:Mn,onFollowUpPaste:gn,onUploadAttachments:e=>{mn(e)},onRemoveAttachment:e=>{hn(e)},onFollowUpSubmit:()=>{jn()}})}):qn?(0,Z.jsx)(`div`,{className:`flex flex-1 items-center justify-center px-6 text-sm text-muted-foreground`,children:mZ(`composer.loadingSession`)}):!ee||L?(0,Z.jsx)(`div`,{className:`flex flex-1 items-center justify-center px-6 text-sm text-muted-foreground`,children:mZ(`sidebar.loadingSessions`)}):(0,Z.jsx)(`div`,{className:`flex flex-1 items-center justify-center px-6`,children:(0,Z.jsxs)(gu,{className:`w-full max-w-lg border-dashed border-border/70 bg-card/40`,children:[(0,Z.jsxs)(_u,{children:[(0,Z.jsx)(vu,{children:mZ(`composer.noSessionSelectedTitle`)}),(0,Z.jsx)(yu,{children:mZ(`composer.noSessionSelectedDescription`)})]}),(0,Z.jsx)(xu,{children:(0,Z.jsx)(q,{type:`button`,onClick:en,disabled:!e||B||V,children:mZ(`composer.startNewSession`)})})]})}),rr=Qn?(0,Z.jsx)(`div`,{ref:Qe,"aria-label":mZ($n?`composer.openDiff`:`composer.resizeDiffPanel`),"aria-orientation":$n?void 0:`vertical`,className:K($n?`group flex h-8 w-full shrink-0 touch-none select-none items-center justify-center border-t border-border/70 bg-background/90 text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground xl:h-auto xl:w-7 xl:cursor-col-resize xl:border-l xl:border-t-0`:`group hidden w-5 shrink-0 cursor-col-resize touch-none select-none items-center justify-center border-l border-border/70 bg-background/80 transition-colors xl:flex`,Ne&&!$n&&`bg-background`),"data-testid":$n?`collapsed-changes-rail`:void 0,onLostPointerCapture:Un,onPointerCancel:Hn,onPointerDown:zn,onPointerMove:Bn,onPointerUp:Vn,onClick:$n?Wn:void 0,onKeyDown:$n?Kn:void 0,role:$n?`button`:`separator`,tabIndex:$n?0:void 0,children:$n?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`hidden h-full w-full items-center justify-center xl:flex`,children:(0,Z.jsxs)(`span`,{className:`relative flex h-full w-full items-center justify-center`,children:[(0,Z.jsx)(`span`,{className:`absolute top-1/2 left-1/2 flex -translate-x-1/2 -translate-y-[2.65rem] items-center justify-center text-sky-400/80 transition-colors group-hover:text-sky-300`,children:(0,Z.jsx)(jc,{className:`h-3 w-3 shrink-0`})}),(0,Z.jsx)(`span`,{className:`absolute top-1/2 left-1/2 h-14 w-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-muted-foreground/70 transition-colors group-hover:bg-sky-300/90`})]})}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-xs font-medium xl:hidden`,children:[(0,Z.jsx)(jc,{className:`h-3.5 w-3.5`}),(0,Z.jsx)(`span`,{children:mZ(`composer.diff`)})]})]}):(0,Z.jsx)(`div`,{className:K(`h-14 w-1.5 rounded-full transition-colors`,Ne?`bg-sky-300/90`:`bg-muted-foreground/70 group-hover:bg-sky-300/90`)})}):null,ir=Ce&&e&&t?.memory_enabled?(0,Z.jsx)(pu,{onClose:()=>we(!1),overlayClassName:`bg-background/45 p-4 backdrop-blur-sm`,panelClassName:`w-full max-w-3xl`,renderContent:({closeButton:t})=>(0,Z.jsxs)(gu,{size:`sm`,className:`max-h-[calc(100vh-2rem)] w-full gap-0 overflow-hidden border-border/80 bg-card/95 shadow-2xl`,children:[(0,Z.jsxs)(_u,{className:`border-b border-border/80 pb-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(vu,{children:mZ(`composer.memorySuggestionsTitle`)}),(0,Z.jsx)(yu,{children:mZ(`composer.memorySuggestionsDescription`)})]}),(0,Z.jsx)(bu,{children:t})]}),(0,Z.jsx)(xu,{className:`min-h-0 flex-1 overflow-y-auto pt-4`,children:(0,Z.jsx)(rZ,{projectId:e,suggestions:ye,emptyState:mZ(`composer.memorySuggestionsEmpty`),onSuggestionsChanged:Pt})})]}),closeButtonLabel:mZ(`composer.closeMemorySuggestions`)}):null,ar=Lt.length>0?(0,Z.jsx)(yQ,{count:Lt.length,title:Rt,isDeleting:le.size>0,onConfirm:()=>{En()},onCancel:()=>{le.size>0||ce([])}}):null;return(0,Z.jsxs)(`div`,{"data-testid":`chat-view-shell`,className:`relative flex min-h-0 flex-1 overflow-hidden border-t border-border/70`,children:[(0,Z.jsx)(bQ,{activeProject:t,activeProjectBranchState:n,activeSessionId:d,chatModeShortcutModifierLabel:Jt,deletingSessionIds:le,finishedBackgroundSessionIds:Ue,hasDeletableSessions:Dn,isCreatingSession:B||!e,isSelectionMode:de,isDraftOpen:_,isLoadingSessions:L,isOpen:ke,isSendingPrompt:V,selectedSessionCount:fe.size,selectedSessionIds:fe,sessionGroups:It,sessions:l,onConfirmDeleteSelectedSessions:()=>{ce(Array.from(fe))},onConfirmDeleteSession:e=>{ce([e])},onDraftOpen:en,onEnterSelectionMode:()=>{U(!0),pe(new Set)},onExitSelectionMode:()=>{U(!1),pe(new Set)},onSetSessionSelection:On,onSessionSelect:e=>{sn(e)},onToggleSessionSelection:e=>{pe(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},onToggleOpen:()=>{Ae(e=>!e)}}),(0,Z.jsxs)(`div`,{ref:Ze,className:`relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden xl:flex-row`,children:[(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:nr}),Qn?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(xc,{content:mZ(`composer.openDiff`),disabled:!$n,side:`left`,children:rr}),er?(0,Z.jsx)(UX,{projectId:e,chatSessionId:_?null:d,canSubmitReviewPrompt:Sn,reviewSubmitDisabledReason:Cn,onSubmitReviewPrompt:_n,state:De,onStateChange:Oe,isResizing:Ne,onClose:Gn,desktopWidth:Le,panelElementRef:$e}):null]}):null]}),ir,ar]})},CQ=({className:e})=>(0,Z.jsx)(xo,{"aria-hidden":`true`,className:e}),wQ=({activeProject:e})=>e?(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto px-6 py-6`,children:(0,Z.jsxs)(`div`,{className:`mx-auto flex w-full max-w-7xl flex-col gap-5`,children:[(0,Z.jsx)(`div`,{className:`border-b border-border/60 pb-4`,children:(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-[10px] font-semibold uppercase tracking-[0.24em] text-muted-foreground`,children:`Memory archive`}),(0,Z.jsx)(`h2`,{className:`text-xl font-semibold text-foreground`,children:e.name})]})}),(0,Z.jsx)(pp,{mode:`edit`,projectId:e.id,memoryEnabled:e.memory_enabled,persistedMemoryEnabled:e.memory_enabled,onMemoryEnabledChange:()=>{},showActivationControls:!1,archiveLayout:!0})]})}):(0,Z.jsx)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center text-sm text-muted-foreground`,children:`Select a project to view memory.`}),TQ=()=>({hasRunning:!1,hasFinishedUnseen:!1,hasErrorUnseen:!1}),EQ=()=>({board:TQ(),memory:TQ(),chat:TQ()}),DQ=(e,t)=>{let n=e[t];return!n.hasFinishedUnseen&&!n.hasErrorUnseen?e:{...e,[t]:{...n,hasFinishedUnseen:!1,hasErrorUnseen:!1}}},OQ=e=>({hasRunning:e.board.hasRunning||e.chat.hasRunning,hasFinishedUnseen:e.board.hasFinishedUnseen||e.chat.hasFinishedUnseen,hasErrorUnseen:e.board.hasErrorUnseen||e.chat.hasErrorUnseen}),kQ=e=>e.hasErrorUnseen?`error`:e.hasRunning?`running`:e.hasFinishedUnseen?`finished`:null,AQ=(e,t)=>t?null:kQ(e),jQ=320,MQ=.7,NQ=28,PQ=6,FQ=(e,t)=>{let n=Math.max(jQ,Math.round(t*MQ));return Math.max(jQ,Math.min(n,Math.round(e)))},IQ=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n===-1)return[...e,t];let r=e.slice();return r[n]=t,r},LQ=(e,t)=>{if(t.type===`reset`)return EQ();if(t.type===`mark-workspace-visible`)return DQ(e,t.workspace);let n=e[t.workspace],r={...n,hasRunning:t.activity.hasRunning,hasFinishedUnseen:t.visibleWorkspace===t.workspace?!1:n.hasFinishedUnseen||t.activity.didFinish,hasErrorUnseen:t.visibleWorkspace===t.workspace?!1:n.hasErrorUnseen||t.activity.didError};return n.hasRunning===r.hasRunning&&n.hasFinishedUnseen===r.hasFinishedUnseen&&n.hasErrorUnseen===r.hasErrorUnseen?e:{...e,[t.workspace]:r}},RQ=({activeProjectId:e,onActivity:t})=>{let{tickets:n}=qY(),r=(0,Y.useRef)(new Map);return(0,Y.useEffect)(()=>{r.current=new Map},[e]),(0,Y.useEffect)(()=>{let e=r.current,i=new Map,a=!1,o=!1;for(let t of n){let n=e.get(t.id)??null,r=t.agent_status??null;n===`running`&&r===`done`&&(a=!0),n===`running`&&r===`error`&&(o=!0),i.set(t.id,r)}r.current=i,t({hasRunning:n.some(e=>e.agent_status===`running`),didFinish:a,didError:o})},[t,n]),null},zQ=({activeProjectId:e,onActivity:t})=>{let n=zY(),[r,i]=(0,Y.useState)([]),a=(0,Y.useRef)(new Map);return(0,Y.useEffect)(()=>{if(!e)return;let t=new AbortController;return(async()=>{try{let n=await Zb(e,t.signal);if(t.signal.aborted)return;i(n)}catch(e){z(e)}})(),()=>{t.abort()}},[e,n]),(0,Y.useEffect)(()=>{if(!e)return;let t=new AbortController,n=aq(()=>{document.visibilityState===`visible`&&Zb(e,t.signal).then(e=>{t.signal.aborted||i(e)}).catch(e=>{z(e)})});return()=>{t.abort(),n()}},[e,n]),(0,Y.useEffect)(()=>{if(!e)return;let t=t=>{!t||t.project_id!==e||i(e=>IQ(e,t))},r=t=>{!t||t.project_id!==e||i(e=>e.filter(e=>e.id!==t.id))};return n.on(`chat-session:created`,t),n.on(`chat-session:updated`,t),n.on(`chat-session:deleted`,r),()=>{n.off(`chat-session:created`,t),n.off(`chat-session:updated`,t),n.off(`chat-session:deleted`,r)}},[e,n]),(0,Y.useEffect)(()=>{let n=a.current,i=new Map,o=[],s=!1;for(let e of r){let t=n.get(e.id)??null,r=e.agent_status??null;t===`running`&&r===`done`&&o.push(e),t===`running`&&r===`error`&&(s=!0),i.set(e.id,r)}a.current=i;for(let e of o)e.title&&LY(`Chat response ready`,e.title);o.length>0&&e&&nq(e),t({hasRunning:r.some(e=>e.agent_status===`running`),didFinish:o.length>0,didError:s})},[e,t,r]),null},BQ=({activeProjectId:e,activeProject:t=null,activeProjectBranchState:n=null,activeRun:r,activeTool:i,onRestoreChatSessionTarget:a,onChatReviewCapabilityChange:o,onPreviewReviewCapabilityChange:s,previewDisplayMode:c=`hidden`,previewPane:l=null,previewPaneWidth:u=480,isPreviewButtonDisabled:d=!1,previewButtonTitle:f,visibleWorkspace:p,onProjectUsageChange:m,onBundlesChange:h,onBundlesLoadingChange:g,onBoardLoadedProjectIdChange:_,onPreviewToggle:v,onPreviewPaneWidthChange:y,onRunStopped:b,onRunStatusChange:x,onWorkspaceActivityChange:S,onWorkspaceActivityEvent:C,refreshKey:w=0})=>{let T=(0,Y.useRef)(null),E=(0,Y.useRef)(null),D=(0,Y.useRef)(null),O=(0,Y.useRef)(null),k=(0,Y.useRef)(!1),A=(0,Y.useRef)(!1),j=(0,Y.useRef)(0),M=(0,Y.useRef)(u),N=(0,Y.useRef)(u),P=p===`board`||p===`chat`,F=l!==null,[I,L]=(0,Y.useState)(!1),[R,z]=(0,Y.useState)(!1),[ee,te]=(0,Y.useState)(u),[ne,re]=(0,Y.useReducer)(LQ,void 0,EQ),B=P&&F&&c===`expanded`,ie=P&&F&&c===`inline`,V=P&&F&&c===`hidden`&&!R,H=(ie||R)&&!B,ae=B||H,oe=P&&F&&!B,se=I?ee:u,ce=p!==`chat`||!H,le=e=>{let t=D.current,n=O.current,r=k.current;if(t!==null){if(D.current=null,O.current=null,k.current=!1,L(!1),z(!1),e!==null&&E.current?.hasPointerCapture(e)&&E.current.releasePointerCapture(e),n===`collapsed`){if(!r)return;y?.(N.current),v?.();return}y?.(N.current)}},ue=e=>{if(!T.current)return;let t=T.current.getBoundingClientRect().width,n=FQ(e,t);N.current=n,te(n)},de=e=>{y&&(V&&d||(e.preventDefault(),D.current=e.pointerId,O.current=V?`collapsed`:`inline`,k.current=!1,A.current=!1,j.current=e.clientX,M.current=V?0:N.current,L(!V),e.currentTarget.setPointerCapture(e.pointerId)))},U=e=>{if(D.current!==e.pointerId)return;let t=e.clientX-j.current,n=M.current-t;if(O.current===`collapsed`){if(!k.current&&n<PQ)return;k.current||(k.current=!0,A.current=!0,z(!0),L(!0))}ue(n)},fe=e=>{if(D.current===e.pointerId){if(O.current===`inline`||k.current){let t=e.clientX-j.current;ue(M.current-t)}le(e.pointerId)}},pe=e=>{D.current===e.pointerId&&le(e.pointerId)},me=(0,Y.useCallback)((e,t)=>{C?.(e,t),re({type:`update-workspace`,workspace:e,activity:t,visibleWorkspace:p})},[C,p]);(0,Y.useEffect)(()=>{re({type:`reset`})},[e]),(0,Y.useEffect)(()=>{p!==`memory`&&re({type:`mark-workspace-visible`,workspace:p})},[p]),(0,Y.useEffect)(()=>{S?.(ne)},[S,ne]),(0,Y.useEffect)(()=>{I||(N.current=u),!F&&(D.current=null,O.current=null,k.current=!1,A.current=!1,N.current=u)},[F,I,u]);let W=()=>{if(A.current){A.current=!1;return}d||v?.()};return(0,Z.jsx)(KY,{activeProjectId:e,refreshKey:w,onLoadedProjectIdChange:_,onProjectUsageChange:m,onBundlesChange:h,onBundlesLoadingChange:g,children:(0,Z.jsxs)(`div`,{ref:T,className:`flex min-h-0 flex-1 flex-col`,children:[(0,Z.jsx)(RQ,{activeProjectId:e,onActivity:e=>{me(`board`,e)}}),(0,Z.jsx)(zQ,{activeProjectId:e,onActivity:e=>{me(`chat`,e)}}),p===`memory`?(0,Z.jsx)(`div`,{id:`project-workspace-panel-memory`,role:`tabpanel`,"aria-labelledby":`project-workspace-tab-memory`,className:`flex min-h-0 flex-1 flex-col`,children:(0,Z.jsx)(wQ,{activeProject:t})}):(0,Z.jsxs)(`div`,{id:p===`chat`?`project-workspace-panel-chat`:`project-workspace-panel-board`,role:`tabpanel`,"aria-labelledby":p===`chat`?`project-workspace-tab-chat`:`project-workspace-tab-board`,className:`flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:[(0,Z.jsx)(`div`,{className:`flex min-h-0 min-w-0 flex-1 flex-col`,children:p===`chat`?(0,Z.jsx)(SQ,{activeProjectId:e,activeProject:t,activeProjectBranchState:n,activeTool:i,isExternallyResizing:I,onRestoreSessionTarget:a,onReviewCapabilityChange:o,showChangesPanel:ce}):(0,Z.jsx)(wX,{activeProjectId:e,activeProject:t,activeProjectBranchState:n,activeRun:r,activeTool:i,onPreviewReviewCapabilityChange:s,onRunStopped:b,onRunStatusChange:x,refreshKey:w})}),[oe?(0,Z.jsx)(xc,{content:d?f??`Preview unavailable`:`Open preview`,disabled:!V,side:`left`,children:(0,Z.jsx)(`div`,{"aria-label":V?f??`Show preview`:`Resize preview pane`,"aria-orientation":V?void 0:`vertical`,className:V?`group flex shrink-0 touch-none select-none items-center justify-center border-l border-border/70 bg-background/90 transition-colors ${d?`cursor-not-allowed text-muted-foreground/60`:`cursor-col-resize text-muted-foreground hover:bg-muted/50 hover:text-foreground`}`:`group flex w-5 shrink-0 cursor-col-resize touch-none select-none items-center justify-center border-l border-border/70 bg-background/80 ${I?`bg-background`:``}`,"data-preview-divider":`true`,"data-testid":V?`collapsed-preview-rail`:void 0,onLostPointerCapture:pe,onPointerCancel:fe,onPointerDown:de,onPointerMove:U,onPointerUp:fe,onClick:V?W:void 0,onKeyDown:V?e=>{e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),W())}:void 0,ref:E,role:V?`button`:`separator`,style:V?{width:`${NQ}px`}:void 0,tabIndex:V?d?-1:0:void 0,children:V?(0,Z.jsxs)(`span`,{className:`relative flex h-full w-full items-center justify-center`,children:[(0,Z.jsx)(`span`,{className:`absolute top-1/2 left-1/2 flex -translate-x-1/2 -translate-y-[2.65rem] items-center justify-center text-sky-400/80 transition-colors group-hover:text-sky-300`,children:(0,Z.jsx)(CQ,{className:`h-3 w-3 shrink-0`})}),(0,Z.jsx)(`span`,{className:`absolute top-1/2 left-1/2 h-14 w-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-muted-foreground/70 transition-colors group-hover:bg-sky-300/90`})]}):(0,Z.jsx)(`div`,{className:`h-14 w-1.5 rounded-full transition-colors ${I?`bg-sky-300/90`:`bg-muted-foreground/70 group-hover:bg-sky-300/90`}`})})},`preview-divider`):null,ae?(0,Z.jsx)(`div`,{className:B?`fixed inset-0 z-50 bg-black/70 p-4 sm:p-6`:`min-h-0 shrink-0 border-l border-border/70 bg-[#11131a]`,style:B?void 0:{width:`${se}px`},children:(0,Z.jsx)(`div`,{className:`h-full w-full`,children:l})},`preview-container`):null]]})]})})},VQ=({isExpanded:e,isVisible:t,project:n,onClose:r,onToggleExpanded:i})=>(0,Z.jsx)(`div`,{className:[`fixed inset-x-4 bottom-24 z-40`,e?`top-20`:`h-[min(28rem,calc(100vh-8rem))]`,t?`block`:`hidden`].join(` `),children:(0,Z.jsx)(KW,{createSession:()=>CT(n.id),isExpanded:e,isVisible:t,ariaLabel:`Project terminal for ${n.name}`,title:n.name,closeLabel:`Close terminal`,className:e?`h-full w-full rounded-2xl shadow-2xl`:`mx-auto h-full max-w-6xl shadow-2xl`,onClose:r,onToggleExpanded:i})}),HQ=({activeWorkspace:e,activityByWorkspace:t,memoryEnabled:n=!1,onWorkspaceChange:r})=>(0,Z.jsx)(`div`,{role:`tablist`,"aria-label":`Project workspace`,className:`inline-flex items-end gap-1 border-b border-border/70`,children:(n?[`board`,`chat`,`memory`]:[`board`,`chat`]).map(n=>{let i=e===n,a=AQ(t[n],i),o=n===`board`?`border-sky-300/70 bg-sky-500/8 text-sky-200`:n===`memory`?`border-amber-300/70 bg-amber-500/8 text-amber-200`:`border-emerald-300/70 bg-emerald-500/8 text-emerald-200`;return(0,Z.jsx)(`button`,{id:`project-workspace-tab-${n}`,type:`button`,role:`tab`,"aria-selected":i,"aria-controls":`project-workspace-panel-${n}`,tabIndex:i?0:-1,className:K(`cursor-pointer rounded-t-lg border-b-2 px-4 py-2.5 text-[15px] font-medium transition-colors duration-150 ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60`,i?o:`border-transparent text-muted-foreground hover:border-border hover:bg-background/35 hover:text-foreground`),onClick:()=>r(n),children:(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{children:n===`board`?`Board`:n===`memory`?`Memory`:`Chat`}),(0,Z.jsx)(Rl,{state:a,className:`mt-0`})]})},n)})}),UQ=32,WQ=5.5,GQ=2,KQ=24,qQ=8,JQ=new Map,YQ={running:{fill:`#fcd34d`,stroke:`#f59e0b`},finished:{fill:`#34d399`,stroke:`#059669`},error:{fill:`#fb7185`,stroke:`#e11d48`}},XQ=e=>e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`).replaceAll(`>`,`>`),ZQ=e=>{if(!e)return null;let t=e.trim().match(/^([0-9]+(?:\.[0-9]+)?)/);return t?Number(t[1]):null},QQ=e=>{let t=new DOMParser().parseFromString(e,`image/svg+xml`);if(t.querySelector(`parsererror`))return null;let n=t.documentElement;if(n.nodeName.toLowerCase()!==`svg`)return null;let r=n.getAttribute(`viewBox`)?.trim(),i=ZQ(n.getAttribute(`width`)),a=ZQ(n.getAttribute(`height`)),o=r??(i&&a?`0 0 ${i} ${a}`:`0 0 ${UQ} ${UQ}`);return`<svg ${[Array.from(n.attributes).filter(e=>![`width`,`height`,`viewBox`,`x`,`y`,`preserveAspectRatio`].includes(e.name)).map(e=>`${e.name}="${XQ(e.value)}"`).join(` `),`x="0"`,`y="0"`,`width="${UQ}"`,`height="${UQ}"`,`viewBox="${XQ(o)}"`,`preserveAspectRatio="xMidYMid meet"`].filter(e=>e.length>0).join(` `)}>${n.innerHTML}</svg>`},$Q=async e=>{if(!e)return null;let t=JQ.get(e);if(t)return t;let n=(async()=>{try{if(e.startsWith(`data:image/svg+xml,`))return QQ(decodeURIComponent(e.slice(19)));if(e.startsWith(`data:image/svg+xml;base64,`))return QQ(atob(e.slice(26)));let t=await fetch(e);return t.ok?QQ(await t.text()):null}catch{return null}})();return JQ.set(e,n),n},e$=async(e,t)=>{let{fill:n,stroke:r}=YQ[e],i=await $Q(t);return i?[`<svg xmlns="http://www.w3.org/2000/svg" width="${UQ}" height="${UQ}" viewBox="0 0 ${UQ} ${UQ}">`,i,`<circle cx="${KQ}" cy="${qQ}" r="${WQ}" fill="${n}" stroke="${r}" stroke-width="${GQ}"/>`,`</svg>`].join(``):null},t$=async(e,t)=>{if(!e)return t;let n=await e$(e,t);return n?`data:image/svg+xml,${encodeURIComponent(n)}`:t},n$=()=>{let e=document.querySelector(`link[rel="icon"]`);if(e)return e;let t=document.createElement(`link`);return t.rel=`icon`,document.head.appendChild(t),t},r$=({defaultHref:e,state:t})=>{let n=n$(),r=Number(n.dataset.browserTabActivityRequestId??`0`)+1;if(n.dataset.browserTabActivityState=t??`default`,n.dataset.browserTabActivityRequestId=String(r),!t){if(e){n.href=e;return}n.removeAttribute(`href`);return}t$(t,e).then(e=>{if(n.dataset.browserTabActivityRequestId===String(r)){if(e){n.href=e;return}n.removeAttribute(`href`)}})},i$=(e,t)=>Pe.t(`common:projectFooter.${e}`,t),a$=1e3,o$=`archon.active-project-id`,s$=`archon.workspace-by-project`,c$=`archon.preview-mode-by-project`,l$=`archon.dismissed-preview-run-context-by-project`,u$=5e3,d$=`archon.preview-pane-width`,f$=`archon.preview-viewport-preset`,p$=`archon.preview-zoom`,m$=480,h$=`responsive`,g$=1,_$={hasMounted:!1,isOpen:!1,isExpanded:!1},v$=`hidden`,y$=(0,Y.lazy)(()=>tG(()=>Promise.resolve().then(()=>fJ).then(e=>({default:e.TicketChangesModal})),void 0)),b$=(0,Y.lazy)(()=>tG(()=>import(`./TestsDialog-CzG_2qwn.js`).then(e=>({default:e.TestsDialog})),__vite__mapDeps([0,1,2]))),x$=e=>{if(!e)return null;try{return JSON.parse(e)}catch{return null}},S$=e=>{let t=x$(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(e=>e.length>0):[]},C$=e=>{let t=x$(e);return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e,n=typeof t.name==`string`?t.name:``,r=typeof t.cmd==`string`?t.cmd:``,i=typeof t.cwd==`string`?t.cwd:``;return n.trim()===``&&r.trim()===``&&i.trim()===``?[]:[{name:n,cmd:r,cwd:i}]}):[]},w$=e=>{let t=x$(e);return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e,n=typeof t.source==`string`?t.source:``,r=typeof t.target==`string`?t.target:``,i=t.mode===`copy`||t.mode===`symlink`?t.mode:`copy`;return n.trim()===``&&r.trim()===``?[]:[{source:n,target:r,mode:i}]}):[]},T$=e=>({name:e.name,repoPath:e.repo_path,linkedProjectIds:e.linked_project_ids,runSetup:S$(e.run_setup),runServices:C$(e.run_services),testCommands:xY(e.test_commands),runIde:e.run_ide??``,previewServiceName:e.preview_service_name??``,previewPath:e.preview_path??``,previewCapabilityMode:e.preview_capability_mode??`auto`,helperModel:e.helper_model??``,helperVariant:e.helper_variant??``,commitMessageRules:e.commit_message_rules??``,autoParkStaleTickets:e.auto_park_stale_tickets,memoryEnabled:e.memory_enabled,worktreeSync:w$(e.worktree_sync)}),E$=e=>{let t=e.testCommands??[],n=e.previewServiceName?.trim()||null,r=e.previewPath?.trim()||``,i=r===``||r===`/`?null:r,a=n||i||e.previewCapabilityMode===`force_web`||e.previewCapabilityMode===`force_disabled`?e.previewCapabilityMode??`auto`:null;return{name:e.name,repo_path:e.repoPath,linked_project_ids:e.linkedProjectIds,run_setup:e.runSetup.length>0?e.runSetup:null,run_services:e.runServices.length>0?e.runServices.map(e=>({...e.name?{name:e.name}:{},cmd:e.cmd,...e.cwd?{cwd:e.cwd}:{}})):null,...t.length>0?{test_commands:t.map(e=>({id:e.id,name:e.name,command:e.command,runner:e.runner,...e.cwd?{cwd:e.cwd}:{}}))}:{},run_ide:e.runIde||null,preview_service_name:n,preview_path:i,preview_capability_mode:a,helper_model:e.helperModel||null,helper_variant:e.helperModel&&e.helperVariant||null,commit_message_rules:e.commitMessageRules||null,auto_park_stale_tickets:e.autoParkStaleTickets,memory_enabled:e.memoryEnabled,worktree_sync:e.worktreeSync.length>0?e.worktreeSync.map(e=>({source:e.source,...e.target?{target:e.target}:{},mode:e.mode})):null}},D$=e=>e?S$(e.run_setup).length>0||C$(e.run_services).length>0||(e.run_ide?.trim().length??0)>0:!1,O$=(e,t,n)=>`${e} ${e===1?t:n}`,k$=e=>{if(!e.repo_path_locked)return null;let t=[];return e.ticket_count>0&&t.push(O$(e.ticket_count,`ticket is attached`,`tickets are attached`)),e.worktree_count>0&&t.push(O$(e.worktree_count,`worktree exists`,`worktrees exist`)),t.length===0?`Repository path is locked for this project.`:`Repository path is locked because ${t.join(` and `)}.`},A$=(e,t)=>{if(t.length<=1)return`Keep at least one project in Archon.`;let n=[];e.ticket_count>0&&n.push(O$(e.ticket_count,`ticket is attached`,`tickets are attached`)),e.worktree_count>0&&n.push(O$(e.worktree_count,`worktree exists`,`worktrees exist`));let r=t.filter(t=>t.linked_project_ids.includes(e.id)).length;return r>0&&n.push(O$(r,`project links to it`,`projects link to it`)),n.length===0?null:`This project can't be deleted while ${n.join(` and `)}.`},j$=(e,t)=>e.id!==t.projectId||e.ticket_count===t.ticketCount&&e.worktree_count===t.worktreeCount&&e.repo_path_locked===t.repoPathLocked?e:{...e,ticket_count:t.ticketCount,worktree_count:t.worktreeCount,repo_path_locked:t.repoPathLocked},M$=(e,t)=>({projectId:e,branch:t.branch,status:t.status,ahead:t.ahead??0,behind:t.behind??0,hasUpstream:t.has_upstream??!1,canPull:t.can_pull??!1,diffStats:t.diff_stats??null}),N$=e=>({projectId:e,branch:null,status:`loading`,ahead:0,behind:0,hasUpstream:!1,canPull:!1,diffStats:null}),P$=(e,t)=>t?e[t]??_$:_$,F$=(e,t)=>t?e[t]??v$:v$,I$=()=>{let e=window.localStorage.getItem(d$),t=Number(e);return Number.isFinite(t)&&t>=320?t:m$},L$=()=>{let e=window.localStorage.getItem(f$);return e===`phone`||e===`tablet`||e===`laptop`||e===`responsive`?e:h$},R$=()=>{let e=Number(window.localStorage.getItem(p$));return Number.isFinite(e)&&e>0?e:g$},z$=()=>{let e=x$(window.localStorage.getItem(s$));return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>e===`board`||e===`chat`||e===`memory`))},B$=()=>{let e=x$(window.localStorage.getItem(c$));return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>e===`hidden`||e===`inline`||e===`expanded`))},V$=()=>{let e=x$(window.localStorage.getItem(l$));return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>typeof e==`string`||e===null))},H$=e=>!!e?.preview_service_name?.trim()&&e?.preview_capability_mode!==`force_disabled`,U$=({activeRun:e,project:t})=>{if(!e||e.kind!==`project`||!t)return!1;let n=t.active_target_kind??`repo_root`,r=t.active_target_bundle_id??null;return e.project_id===t.id&&(e.target_kind??`repo_root`)===n&&((e.target_kind??`repo_root`)!==`bundle`||e.target_bundle_id===r)},W$=({activeRun:e,project:t,projectId:n})=>!e||!n?null:e.kind===`ticket`?e.project_id===n?e:null:U$({activeRun:e,project:t})?e:null,G$=`Project root has uncommitted changes. Confirm branch switch to continue.`,K$=({activeProject:e,activeProjectBranchState:t,nextTarget:n})=>e?n.kind===`bundle`?e.active_target_kind!==`bundle`||e.active_target_bundle_id!==n.bundleId:e.active_target_kind===`bundle`?!0:n.branch?t?.branch!==n.branch:!1:!1,q$=()=>{let[e,t]=(0,Y.useState)(`opencode`),[n,r]=(0,Y.useState)(!1),[i,o]=(0,Y.useState)([]),[c,l]=(0,Y.useState)(()=>window.localStorage.getItem(o$)),[u,f]=(0,Y.useState)(null),[p,m]=(0,Y.useState)(null),[h,g]=(0,Y.useState)(null),[_,y]=(0,Y.useState)({}),[b,x]=(0,Y.useState)({}),[S,C]=(0,Y.useState)({}),[w,T]=(0,Y.useState)({}),[E,D]=(0,Y.useState)({}),[O,k]=(0,Y.useState)(B$),[A,j]=(0,Y.useState)(V$),[M,N]=(0,Y.useState)(I$),[F,R]=(0,Y.useState)(L$),[ee,te]=(0,Y.useState)(R$),[ne,re]=(0,Y.useState)(null),[B,ie]=(0,Y.useState)([]),[V,H]=(0,Y.useState)(!1),[ae,oe]=(0,Y.useState)(``),[le,ue]=(0,Y.useState)(``),[de,U]=(0,Y.useState)(!1),[fe,pe]=(0,Y.useState)(null),[W,he]=(0,Y.useState)(null),[G,_e]=(0,Y.useState)(null),[ve,ye]=(0,Y.useState)(!1),[be,xe]=(0,Y.useState)({}),[K,Se]=(0,Y.useState)(z$),[Ce,we]=(0,Y.useState)(()=>EQ()),[Te,De]=(0,Y.useState)(()=>TQ()),[Oe,ke]=(0,Y.useState)(0),[Ae,q]=(0,Y.useState)(null),[Me,Pe]=(0,Y.useState)(null),[Fe,Ie]=(0,Y.useState)({}),[Le,Re]=(0,Y.useState)({}),[ze,Be]=(0,Y.useState)({}),[Ve,Ue]=(0,Y.useState)({}),[We,Ge]=(0,Y.useState)(!1),[Ke,qe]=(0,Y.useState)(!1),[Je,Ye]=(0,Y.useState)(null),Xe=(0,Y.useRef)(null),Ze=(0,Y.useRef)(null),$e=(0,Y.useRef)(null),J=i.find(e=>e.id===c)??null,tt=!!J?.memory_enabled,nt=c?K[c]??`board`:`board`,rt=nt===`memory`?tt?`memory`:`board`:nt,it=J!==null,at=D$(J),ot=!!J?.run_ide?.trim(),st=c!==null&&p===c,ct=c!==null&&(!at||h===c),lt=c?_[c]??N$(c):null,ut=c?b[c]??null:null,dt=c?!!S[c]:!1,ft=c?w[c]??null:null,pt=c?Fe[c]??[]:[],mt=c?!!Le[c]:!1,ht=c?ze[c]??{current_branch:null,default_branch:null,previous_branch:null}:{current_branch:null,default_branch:null,previous_branch:null},gt=c?!!Ve[c]:!1,_t=c?E[c]??null:null,vt=F$(O,c),yt=vt!==`hidden`,bt=W$({activeRun:u,project:J,projectId:c}),X=bt?.context_key??null,xt=c?A[c]??null:null,St=H$(J),Ct=X===ne,wt=(0,Y.useMemo)(()=>OQ(Ce),[Ce]),Tt=(0,Y.useMemo)(()=>kQ({hasRunning:wt.hasRunning,hasFinishedUnseen:Te.hasFinishedUnseen,hasErrorUnseen:Te.hasErrorUnseen}),[wt.hasRunning,Te.hasErrorUnseen,Te.hasFinishedUnseen]);(0,Y.useEffect)(()=>{q(null),Pe(null),Ze.current=null},[c]),(0,Y.useEffect)(()=>{Pe(null)},[rt]),(0,Y.useEffect)(()=>{yt||(Ze.current=null)},[yt]),(0,Y.useEffect)(()=>{let e=Ae?.target?.kind??null;if(e===`ticket`||e===`bundle`){Ze.current=Ae;return}(rt===`board`||!yt)&&(Ze.current=Ae)},[yt,Ae,rt]),(0,Y.useEffect)(()=>{we(EQ())},[c]),(0,Y.useEffect)(()=>{De(TQ())},[c]);let Dt=(0,Y.useCallback)((e,t)=>{document.visibilityState!==`visible`&&(!t.didFinish&&!t.didError||De(e=>{let n={...e,hasFinishedUnseen:e.hasFinishedUnseen||t.didFinish,hasErrorUnseen:e.hasErrorUnseen||t.didError};return e.hasFinishedUnseen===n.hasFinishedUnseen&&e.hasErrorUnseen===n.hasErrorUnseen?e:n}))},[]);(0,Y.useEffect)(()=>{let e=()=>{document.visibilityState===`visible`&&De(e=>!e.hasFinishedUnseen&&!e.hasErrorUnseen?e:{...e,hasFinishedUnseen:!1,hasErrorUnseen:!1})};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[]),(0,Y.useEffect)(()=>(Xe.current===null&&(Xe.current=document.querySelector(`link[rel="icon"]`)?.getAttribute(`href`)??`/favicon.svg`),r$({defaultHref:Xe.current,state:Tt}),()=>{r$({defaultHref:Xe.current,state:null})}),[Tt]);let Ot=(0,Y.useCallback)(async(e,t={})=>{let{refreshRemote:n=!1,signal:r}=t;try{let t=await He(e,r,{refreshRemote:n});if(r?.aborted)return;y(n=>({...n,[e]:M$(e,t)}))}catch(t){if(z(t))return;if(t instanceof I&&t.status===404){y(t=>({...t,[e]:{...N$(e),status:`unknown`}}));return}y(t=>({...t,[e]:{projectId:e,branch:t[e]?.branch??null,status:`unknown`,ahead:t[e]?.ahead??0,behind:t[e]?.behind??0,hasUpstream:t[e]?.hasUpstream??!1,canPull:t[e]?.canPull??!1,diffStats:t[e]?.diffStats??null}}))}},[]),kt=(0,Y.useCallback)(async(e,t={})=>{let{refreshRemote:n=!1,signal:r,suppressLoading:i=!1}=t;i||C(t=>({...t,[e]:!0}));try{let t=await ge(e,{refreshRemote:n,signal:r});if(r?.aborted)return;x(n=>({...n,[e]:t}))}catch(t){if(z(t))return;t instanceof I&&t.status===404&&x(t=>({...t,[e]:null}))}finally{!r?.aborted&&!i&&C(t=>({...t,[e]:!1}))}},[]),At=(0,Y.useCallback)((e,t)=>{T(n=>({...n,[e]:t}))},[]),jt=(0,Y.useCallback)(async(e,t)=>{x(n=>({...n,[e.id]:t})),e.active_target_kind!==`bundle`&&await Ot(e.id),nq(e.id)},[Ot]);(0,Y.useEffect)(()=>{let e=new AbortController;return(async()=>{try{let{tool:n}=await Tn(e.signal);t(n)}catch(e){z(e)}finally{e.signal.aborted||r(!0)}})(),()=>{e.abort()}},[]),(0,Y.useEffect)(()=>{if(!de||i.length>0&&fe===null||V)return;let e=new AbortController;return(async()=>{try{ie(await wn(`opencode`,e.signal))}catch(e){z(e)||ie(e=>e)}finally{e.signal.aborted||H(!0)}})(),()=>{e.abort()}},[V,fe,i.length,de]),(0,Y.useEffect)(()=>{let e=new AbortController,t=window.localStorage.getItem(o$);return(async()=>{try{let n=await et(e.signal);if(e.signal.aborted)return;o(n);let r=n[0]?.id??null;l(n.some(e=>e.id===t)?t:r)}catch(e){z(e)||o([])}finally{e.signal.aborted||U(!0)}})(),()=>{e.abort()}},[]),(0,Y.useEffect)(()=>{if(de){if(c){window.localStorage.setItem(o$,c);return}window.localStorage.removeItem(o$)}},[c,de]),(0,Y.useEffect)(()=>{window.localStorage.setItem(s$,JSON.stringify(K))},[K]),(0,Y.useEffect)(()=>{window.localStorage.setItem(c$,JSON.stringify(O))},[O]),(0,Y.useEffect)(()=>{window.localStorage.setItem(l$,JSON.stringify(A))},[A]),(0,Y.useEffect)(()=>{y(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)}),x(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)}),C(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)})},[i]),(0,Y.useEffect)(()=>{xe(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)})},[i]),(0,Y.useEffect)(()=>{let e=new Set(i.map(e=>e.id));Ie(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(t)))),Re(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(t)))),Be(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(t)))),Ue(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(t))))},[i]),(0,Y.useEffect)(()=>{de&&(D(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)}),k(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)}),j(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)}))},[i,de]),(0,Y.useEffect)(()=>{de&&Se(e=>{let t=new Set(i.map(e=>e.id)),n=Object.entries(e).filter(([e])=>t.has(e));return n.length===Object.keys(e).length?e:Object.fromEntries(n)})},[i,de]),(0,Y.useEffect)(()=>{if(!de||!c||!it)return;let e=!1,t=null,n=null;y(e=>e[c]?e:{...e,[c]:N$(c)});let r=async(r=!1)=>{let i=r?`remote`:`local`;if(t){if(n===`remote`||n===i)return;t.abort()}let a=new AbortController;t=a,n=i;try{await Promise.all([Ot(c,{refreshRemote:r,signal:a.signal}),kt(c,{refreshRemote:r,signal:a.signal})])}catch{if(e||a.signal.aborted)return}finally{t===a&&(t=null,n=null)}};r(!1);let i=aq(()=>{document.visibilityState===`visible`&&r(!1)});return()=>{e=!0,t?.abort(),i()}},[c,it,de,Ot,kt]),(0,Y.useEffect)(()=>{if(c)return rq(e=>{e===c&&(Ot(e),kt(e))})},[c,Ot,kt]),(0,Y.useEffect)(()=>{if(!c||!it)return;let e=ut?.operation_state??`idle`;if(!(ft===`rebase`||e!==`idle`))return;let t=!1,n=null,r=null,i=async()=>{r?.abort(),r=new AbortController;try{await kt(c,{signal:r.signal,suppressLoading:!0})}catch{}finally{t||(n=window.setTimeout(()=>{i()},a$))}};return i(),()=>{t=!0,r?.abort(),n!==null&&window.clearTimeout(n)}},[ft,c,ut?.operation_state,it,kt]);let Mt=(0,Y.useCallback)(async e=>{let t=c;if(!t){f(null),g(null);return}try{let n=await Ut(t,e);e?.aborted||(f(n.active_run),g(t))}catch(e){z(e)}},[c]),Nt=(0,Y.useCallback)(async e=>{let t=c;if(t)try{let n=await Ht(t,e);e?.aborted||D(e=>({...e,[t]:n}))}catch(e){z(e)}},[c]);(0,Y.useEffect)(()=>{if(!de)return;if(!at){f(null),g(null);return}if(!st)return;let e=new AbortController;g(null),Mt(e.signal);let t=window.setInterval(()=>{Mt(e.signal)},u$),n=aq(()=>{document.visibilityState===`visible`&&Mt(e.signal)});return()=>{e.abort(),window.clearInterval(t),n()}},[st,at,de,Mt]),(0,Y.useEffect)(()=>{if(!de||!c||!st||!St)return;let e=new AbortController;Nt(e.signal);let t=window.setInterval(()=>{Nt(e.signal)},u$),n=aq(()=>{document.visibilityState===`visible`&&Nt(e.signal)});return()=>{e.abort(),window.clearInterval(t),n()}},[c,st,St,de,Nt]),(0,Y.useEffect)(()=>{window.localStorage.setItem(d$,String(M))},[M]),(0,Y.useEffect)(()=>{window.localStorage.setItem(f$,F)},[F]),(0,Y.useEffect)(()=>{window.localStorage.setItem(p$,String(ee))},[ee]),(0,Y.useEffect)(()=>{c&&X&&j(e=>{let t=e[c]??null;return!t||t===X?e:{...e,[c]:null}})},[c,X]),(0,Y.useEffect)(()=>{!c||!bt||!H$(J)||xt!==bt.context_key&&k(e=>F$(e,c)===`hidden`?{...e,[c]:`inline`}:e)},[J,c,xt,bt]);let Pt=async e=>{try{t((await En(e)).tool)}catch{}},Ft=(0,Y.useCallback)(e=>{o(t=>t.map(t=>t.id===e.id?e:t))},[]),It=(0,Y.useCallback)((e,t)=>{Ie(n=>{let r=[t,...(n[e]??[]).filter(e=>e.id!==t.id)];return{...n,[e]:r}})},[]),Lt=(0,Y.useCallback)(async e=>{Ue(t=>({...t,[e]:!0}));try{let t=await je(e);Be(n=>({...n,[e]:t}))}catch(e){Q.error(e instanceof I?e.message:`Unable to load the project target options right now.`,{id:`project-target-selector-load-error`})}finally{Ue(t=>({...t,[e]:!1}))}},[]),Rt=async e=>{try{let t=await L(E$(e));return o(e=>[...e,t]),l(t.id),pe(null),null}catch(e){return e instanceof I?e.message:`Unable to create the project right now.`}},zt=async e=>{if(!J)return`Select a project before editing settings.`;try{let t=await P(J.id,E$(e));return o(e=>e.map(e=>e.id===t.id?t:e)),ke(e=>e+1),pe(null),null}catch(e){return e instanceof I?e.message:`Unable to update the project right now.`}},Bt=async()=>{if(!J)return`Select a project before deleting it.`;try{await Ne(J.id);let e=i.filter(e=>e.id!==J.id);return o(e),l(e[0]?.id??null),pe(null),null}catch(e){return e instanceof I?e.message:`Unable to delete the project right now.`}},Kt=(0,Y.useCallback)(e=>{o(t=>t.map(t=>j$(t,e)))},[]),qt=(0,Y.useCallback)((e,t)=>{e&&Ie(n=>({...n,[e]:t}))},[]),Jt=(0,Y.useCallback)((e,t)=>{e&&Re(n=>({...n,[e]:t}))},[]),Yt=async(e,t,n)=>await ce({repo_path:e,helper_model:t||null,helper_variant:t&&n||null}),Xt=async()=>(await se()).repo_path,Zt=(0,Y.useCallback)(async e=>{let t=await Ee({repo_path:e});return{valid:t.valid,repoRoot:t.repo_root,error:t.error,willInitialize:t.will_initialize,hasInitialCommit:t.has_initial_commit}},[]),Qt=(0,Y.useCallback)(async()=>{if(!(!J||ve)){ye(!0);try{let e=await a(J.id);o(t=>t.map(t=>t.id===e.id?e:t)),Q.success(`Initial commit created.`,{id:`project-initial-commit-success`}),Ot(e.id),kt(e.id)}catch(e){Q.error(e instanceof I?e.message:`Unable to create the initial commit right now.`,{id:`project-initial-commit-error`})}finally{ye(!1)}}},[J,ve,Ot,kt]),$t=(0,Y.useCallback)((e,t)=>{k(t=>({...t,[e]:`hidden`})),t&&j(n=>({...n,[e]:t}))},[]),en=(0,Y.useCallback)(()=>{c&&$t(c,X)},[c,$t,X]),tn=(0,Y.useCallback)(e=>{c&&(k(e=>({...e,[c]:`hidden`})),e&&f(t=>t?.context_key===e?null:t))},[c]),nn=(0,Y.useCallback)(async()=>{if(!bt||ne===bt.context_key)return;let{context_key:e}=bt;re(e);try{bt.kind===`ticket`?await _n(bt.ticket_id,bt.project_id):f((await Gt(bt.project_id)).active_run),tn(e),await Promise.all([Mt(),Nt()])}catch(e){Q.error(e instanceof I?e.message:`Unable to stop the preview run right now.`,{id:`app-preview-run-stop-error`})}finally{re(t=>t===e?null:t)}},[tn,bt,Nt,Mt,ne]),rn=(0,Y.useCallback)(e=>{!e||!c||Lt(c)},[c,Lt]),an=(0,Y.useCallback)(e=>new Promise(t=>{$e.current=t,Ye(e)}),[]),on=(0,Y.useCallback)(e=>{let t=$e.current;$e.current=null,Ye(null),t?.(e)},[]),sn=(0,Y.useCallback)(async e=>{if(!J||!c)throw Error(`Select a project first.`);if(!K$({activeProject:J,activeProjectBranchState:lt,nextTarget:e})||!u||u.kind!==`project`||u.project_id!==J.id)return!0;if(!await an({title:`Stop current run and switch target?`,description:`Switching targets will stop the current run and close its preview.`,confirmLabel:`Stop and switch`,cancelLabel:`Keep current target`,confirmVariant:`destructive`}))return!1;try{let e=u.context_key,t=await Gt(J.id);return tn(e),f(t.active_run),await Nt(),!0}catch(e){return Q.error(e instanceof I?e.message:`Unable to stop the project run right now.`,{id:`project-target-switch-stop-run-error`}),!1}},[J,lt,c,u,tn,Nt,an]),cn=(0,Y.useCallback)(async e=>{if(!c)throw Error(`Select a project first.`);return await sn({kind:`bundle`,bundleId:e})?(Ft(await s(c,{kind:`bundle`,bundle_id:e})),x(e=>({...e,[c]:null})),await Promise.all([Ot(c),kt(c)]),!0):!1},[c,sn,Ot,kt,Ft]),ln=(0,Y.useCallback)(async(e,t={})=>{if(!c)throw Error(`Select a project first.`);if(!await sn({kind:`repo_root`,branch:e}))return!1;let n=n=>s(c,{kind:`repo_root`,...e?{branch:e}:{},...t.createBranch===!1?{create_branch:!1}:{},...n?{confirm_dirty_switch:!0}:{}}),r;try{r=await n(t.confirmDirtySwitch===!0)}catch(e){if(!t.confirmDirtySwitch&&e instanceof I&&e.status===409&&e.message===G$){if(!await an({title:`Switch repo root branch?`,description:`${G$}\n\nSwitch anyway?`,confirmLabel:`Switch anyway`,cancelLabel:`Keep current branch`}))return!1;r=await n(!0)}else throw e}return Ft(r),x(e=>({...e,[c]:null})),await Promise.all([Ot(c),kt(c),Lt(c)]),!0},[c,sn,Lt,Ot,kt,Ft,an]),un=(0,Y.useCallback)(async e=>!e.target_kind||e.target_available===!1?!0:e.target_kind===`bundle`?e.target_bundle_id?await cn(e.target_bundle_id):!1:await ln(e.target_branch_snapshot??null,{createBranch:!1}),[cn,ln]),dn=(0,Y.useCallback)(()=>{Ge(!0)},[]),fn=(0,Y.useCallback)(()=>{Ge(!1)},[]),pn=(0,Y.useCallback)(e=>{if(e){cn(e);return}ln(null)},[cn,ln]),mn=(0,Y.useCallback)(async e=>{if(!c)throw Error(`Select a project first.`);let t=await Et(c,{name:e,prepare:!0});return It(c,t),ke(e=>e+1),t},[c,It]),hn=(0,Y.useCallback)(async e=>{if(!c)throw Error(`Select a project first.`);await Vt(c,e),Ie(t=>({...t,[c]:(t[c]??[]).filter(t=>t.id!==e)})),ke(e=>e+1)},[c]),gn=(0,Y.useCallback)(async()=>{if(!J)return;let e=J.active_target_kind??`repo_root`,t=J.active_target_bundle_id??null,n=u?.kind===`project`&&u.project_id===J.id&&(u.target_kind??`repo_root`)===e&&((u.target_kind??`repo_root`)!==`bundle`||u.target_bundle_id===t),r=n?u?.context_key??null:null,i=!n&&H$(J)&&vt===`hidden`;i&&(k(e=>({...e,[J.id]:`inline`})),j(e=>({...e,[J.id]:null})));try{let e=n?await Gt(J.id):await Wt(J.id);n&&tn(r),f(e.active_run),Nt()}catch(e){i&&k(e=>({...e,[J.id]:`hidden`})),Q.error(e instanceof I?e.message:`Unable to update the project run right now.`,{id:`app-project-run-error`})}},[vt,J,u,tn,Nt]),vn=(0,Y.useCallback)(async()=>{if(!(!J||!ot))try{await me(J.id)}catch(e){Q.error(e instanceof Error?e.message:`Unable to open the IDE right now.`,{id:`app-project-open-ide-error`})}},[J,ot]),yn=(0,Y.useCallback)(async()=>{if(J){At(J.id,`pull`);try{let e=await Qe(J.id);await jt(J,e),Q.success(e.behind===0?i$(`branchSynced`):i$(`branchUpdated`),{id:`app-project-pull-success`})}catch(e){Q.error(e instanceof I?e.message:i$(`syncFallbackError`),{id:`app-project-pull-error`})}finally{At(J.id,null)}}},[J,jt,At]),bn=(0,Y.useCallback)(async()=>{if(!J)return;let e=ut?.base_branch??null;At(J.id,`rebase`);try{let t=await d(J.id);await jt(J,t);let n=t.base_branch??e;Q.success(n?i$(`branchRebasedOnto`,{branch:n}):i$(`branchRebased`),{id:`app-project-rebase-success`})}catch(e){await Promise.allSettled([Ot(J.id),kt(J.id,{suppressLoading:!0})]),Q.error(e instanceof I?e.message:i$(`rebaseFallbackError`),{id:`app-project-rebase-error`})}finally{At(J.id,null)}},[J,ut?.base_branch,jt,Ot,kt,At]),xn=(0,Y.useCallback)(async()=>{if(J){At(J.id,`abort`);try{await jt(J,await v(J.id)),Q.success(i$(`gitOperationAborted`),{id:`app-project-abort-success`})}catch(e){Q.error(e instanceof I?e.message:i$(`abortFallbackError`),{id:`app-project-abort-error`})}finally{At(J.id,null)}}},[J,jt,At]),Sn=(0,Y.useCallback)(()=>{J&&he({projectId:J.id,title:J.name,targetKind:J.active_target_kind??`repo_root`,targetBundleId:J.active_target_bundle_id??null,hasHelperModel:!!J.helper_model,repoRootDefaultBranch:ht.default_branch})},[J,ht.default_branch]),Cn=(0,Y.useCallback)(()=>{if(!W)return;let{projectId:e}=W;he(null),Ot(e),kt(e)},[Ot,kt,W]),Dn=(0,Y.useCallback)(()=>{J&&_e({projectId:J.id,targetKind:J.active_target_kind??`repo_root`,targetBundleId:J.active_target_bundle_id??null})},[J]),On=(0,Y.useCallback)(()=>{_e(null)},[]),kn=P$(be,c),An=J?xY(J.test_commands).length>0:!1,jn=rt===`chat`?Me:null,Mn=Ze.current,Nn=Mn?.target?.kind??null,Pn=rt===`chat`?Nn===`ticket`||Nn===`bundle`?{target:Mn?.target??null,canSelect:!1,disabledReason:`This preview belongs to a ticket run. Return to Board to send preview comments.`,promptMode:Mn?.promptMode??null,onPromptModeChange:Mn?.onPromptModeChange??null,isUpdatingPromptMode:Mn?.isUpdatingPromptMode??!1,promptPlaceholder:Mn?.promptPlaceholder??null,promptComposerControls:Mn?.promptComposerControls,promptComposerInlineControls:Mn?.promptComposerInlineControls,submitPrompt:null}:jn?{target:{kind:`chat_session`,id:jn.chatSessionId??`draft:${c}`},canSelect:jn.canSubmitReviewPrompt,disabledReason:jn.canSubmitReviewPrompt?null:jn.reviewSubmitDisabledReason??`Wait for the current chat turn to finish before sending preview comments.`,promptMode:jn.mode,onPromptModeChange:jn.onModeChange,isUpdatingPromptMode:jn.isUpdatingMode,promptPlaceholder:jn.promptPlaceholder,promptComposerControls:jn.promptComposerControls,promptComposerInlineControls:jn.promptComposerInlineControls,submitPrompt:jn.canSubmitReviewPrompt?jn.submitPrompt:null}:{target:null,canSelect:!1,disabledReason:`Select a chat session to send preview comments.`,submitPrompt:null}:Ae,Fn=jn?.canSubmitReviewPrompt??!1,In=rt===`chat`?jn?jn.reviewSubmitDisabledReason:`Select a chat session to send review comments.`:void 0,Ln=(0,Y.useCallback)(()=>{c&&xe(e=>{let t=e[c]??_$;return{...e,[c]:{hasMounted:!0,isOpen:!t.isOpen,isExpanded:t.isExpanded}}})},[c]),Rn=(0,Y.useCallback)(e=>{xe(t=>{let n=t[e]??_$;return!n.hasMounted||!n.isOpen?t:{...t,[e]:_$}})},[]),zn=(0,Y.useCallback)(e=>{xe(t=>{let n=t[e]??_$;return{...t,[e]:{hasMounted:!0,isOpen:n.isOpen,isExpanded:!n.isExpanded}}})},[]),Bn=(0,Y.useCallback)(()=>{pe(`create`)},[]),Vn=(0,Y.useCallback)(()=>{if(c){if(yt){en();return}k(e=>({...e,[c]:`inline`})),j(e=>({...e,[c]:null}))}},[c,en,yt]),Hn=(0,Y.useCallback)(()=>{c&&k(e=>{let t=F$(e,c);return{...e,[c]:t===`expanded`?`inline`:`expanded`}})},[c]),Un=J?J.preview_service_name?.trim()?J.preview_capability_mode===`force_disabled`?`Preview is disabled for this project.`:_t?.state===`unsupported`?_t.message??`Preview is unavailable for this project.`:yt?`Hide preview`:`Show preview`:`Choose a named preview service in project settings first.`:`Select a project first.`,Wn=!J||!J.preview_service_name?.trim()||J.preview_capability_mode===`force_disabled`||_t?.state===`unsupported`,Gn=J&&J.preview_service_name?.trim()?(0,Z.jsx)(Xb,{project:J,mode:vt===`expanded`?`expanded`:`inline`,status:_t,viewportPreset:F,zoom:ee,activeRun:bt,reviewCapability:Pn,isStoppingActiveRun:Ct,onHide:en,onStopActiveRun:()=>{nn()},onToggleExpanded:Hn,onViewportPresetChange:R,onZoomChange:te}):null;return(0,Z.jsxs)(`div`,{className:`flex h-screen flex-col overflow-hidden bg-[linear-gradient(180deg,_rgba(15,16,21,1),_rgba(9,10,14,1))] text-foreground`,children:[(0,Z.jsx)(ou,{}),i.length>0&&(0,Z.jsx)(`header`,{className:`border-b border-border bg-background/95 px-6 py-3 backdrop-blur`,children:(0,Z.jsxs)(`div`,{className:`grid gap-2 lg:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] lg:items-center`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 lg:justify-self-start`,children:(0,Z.jsx)(`div`,{className:`min-w-0 w-full sm:min-w-[20rem] sm:max-w-[30rem]`,children:(0,Z.jsx)(Ec,{activeProjectId:c,projects:i,onEditProject:()=>pe(`edit`),onProjectChange:l})})}),c&&(0,Z.jsx)(`div`,{className:`flex justify-start lg:col-start-2 lg:row-start-1 lg:justify-center`,children:(0,Z.jsx)(HQ,{activeWorkspace:rt,activityByWorkspace:Ce,memoryEnabled:tt,onWorkspaceChange:e=>{c&&(Se(t=>({...t,[c]:e})),we(t=>DQ(t,e)))}})}),(0,Z.jsx)(`div`,{className:`w-full lg:col-start-3 lg:row-start-1 lg:w-auto lg:justify-self-end`,children:(0,Z.jsx)(au,{activeTool:e,onCreateProject:Bn,onMobileAccessOpen:()=>qe(!0),onToolChange:Pt})})]})}),de?i.length===0?(0,Z.jsx)(wc,{activeTool:e,availableHelperModels:B,helperModel:ae,helperVariant:le,isHelperModelsLoaded:V,isToolLoaded:n,onCreateProject:Bn,onHelperModelChange:e=>{oe(e),ue(``)},onHelperVariantChange:ue,onToolChange:Pt}):(0,Z.jsxs)(Z.Fragment,{children:[J?.has_initial_commit===!1&&(0,Z.jsx)(hu,{isSubmitting:ve,onCreateInitialCommit:()=>{Qt()}}),(0,Z.jsx)(BQ,{activeProjectId:c,activeProject:J,activeProjectBranchState:lt,activeRun:u,activeTool:e,onRestoreChatSessionTarget:un,onChatReviewCapabilityChange:Pe,isPreviewButtonDisabled:Wn,onPreviewReviewCapabilityChange:q,onPreviewToggle:Vn,onRunStopped:tn,onWorkspaceActivityChange:we,onWorkspaceActivityEvent:Dt,previewDisplayMode:vt,previewPane:Gn,previewPaneWidth:M,previewButtonTitle:Un,visibleWorkspace:rt,refreshKey:Oe,onBoardLoadedProjectIdChange:m,onBundlesChange:qt,onBundlesLoadingChange:Jt,onPreviewPaneWidthChange:N,onProjectUsageChange:Kt,onRunStatusChange:()=>{Mt(),Nt()}},c??`no-project`)]}):(0,Z.jsx)(`div`,{className:`flex flex-1 items-center justify-center text-sm text-muted-foreground`,children:`Loading projects...`}),i.length>0&&(0,Z.jsx)(Ll,{activeProject:J,activeRun:u,branchState:lt,targetGitStatus:ut,isBoardLoadedForActiveProject:st,activeProjectBranchAction:ft,isProjectIdeAvailable:ot,isProjectRunAvailable:at,isRunStatusLoadedForActiveProject:ct,isTerminalOpen:kn.isOpen,targetBundles:pt,targetBranchSuggestions:ht,isTargetBundleLoading:mt,isTargetSelectorLoading:gt,isTargetGitStatusLoading:dt,hasConfiguredTests:An,onProjectIdeOpen:()=>{vn()},onProjectPull:()=>{yn()},onProjectRebase:bn,onProjectAbortGitOperation:xn,onProjectRunToggle:()=>{gn()},onProjectChangesOpen:Sn,onProjectTestsOpen:Dn,onTerminalToggle:Ln,onTargetSelectorOpenChange:rn,onSelectBundleTarget:cn,onSelectRepoRootTarget:ln,onManageBundles:dn}),(0,Z.jsx)(Pd,{activeProjectId:c,open:Ke,onOpenChange:qe}),We&&J&&(0,Z.jsx)(Eu,{bundles:pt,selectedBundleId:J.active_target_kind===`bundle`?J.active_target_bundle_id??null:null,activeTargetBundleId:J.active_target_kind===`bundle`?J.active_target_bundle_id??null:null,onSelectBundle:pn,onCreateBundle:mn,onDeleteBundle:hn,onClose:fn}),Je&&(0,Z.jsx)(mu,{title:Je.title,description:Je.description,confirmLabel:Je.confirmLabel,cancelLabel:Je.cancelLabel,confirmVariant:Je.confirmVariant,onConfirm:()=>on(!0),onCancel:()=>on(!1)}),i.map(e=>{let t=P$(be,e.id);return t.hasMounted?(0,Z.jsx)(VQ,{project:e,isExpanded:t.isExpanded,isVisible:e.id===c&&t.isOpen,onClose:()=>Rn(e.id),onToggleExpanded:()=>zn(e.id)},e.id):null}),fe&&(0,Z.jsx)(Rp,{mode:fe,projectId:fe===`edit`&&J?J.id:null,availableHelperModels:B,isLoadingHelperModels:!V,isAutoConfigReady:n,initialValues:fe===`edit`&&J?T$(J):i.length===0?{name:``,repoPath:``,linkedProjectIds:[],runSetup:[],runServices:[],testCommands:[],runIde:``,previewServiceName:``,previewPath:``,previewCapabilityMode:`auto`,helperModel:ae,helperVariant:le,commitMessageRules:``,autoParkStaleTickets:!1,memoryEnabled:!1,worktreeSync:[]}:void 0,linkedProjectOptions:i.filter(e=>e.id!==J?.id).map(e=>({id:e.id,name:e.name})),repoPathLocked:fe===`edit`&&J?J.repo_path_locked:!1,repoPathLockedMessage:fe===`edit`&&J?k$(J):null,deleteBlockedMessage:fe===`edit`&&J?A$(J,i):null,onDelete:fe===`edit`?Bt:void 0,onAutoConfig:Yt,onBrowseRepoPath:Xt,onValidateRepoPath:Zt,onClose:()=>pe(null),onSubmit:fe===`edit`?zt:Rt}),W&&W.projectId===c&&(0,Z.jsx)(Y.Suspense,{fallback:null,children:(0,Z.jsx)(y$,{scope:`project_root`,projectId:W.projectId,targetKind:W.targetKind,reviewCommentsBundleId:W.targetKind===`bundle`?W.targetBundleId:null,title:W.title,hasHelperModel:W.hasHelperModel,repoRootDefaultBranch:W.repoRootDefaultBranch,onSubmitReviewPrompt:jn?.submitPrompt,canSubmitReviewPrompt:Fn,reviewSubmitDisabledReason:In??void 0,canAddReviewComments:Fn,canModifyChanges:!0,onClose:Cn})}),G&&G.projectId===c&&J&&(0,Z.jsx)(Y.Suspense,{fallback:null,children:(0,Z.jsx)(b$,{scope:`project`,projectId:G.projectId,targetKind:G.targetKind,targetBundleId:G.targetBundleId,testCommands:xY(J.test_commands),onClose:On})})]})},J$=({className:e})=>(0,Z.jsx)(mo,{"aria-hidden":`true`,className:e}),Y$=({className:e})=>(0,Z.jsx)(_o,{"aria-hidden":`true`,className:e}),X$=({className:e})=>(0,Z.jsx)(Ao,{"aria-hidden":`true`,className:e}),Z$=`X-Archon-Mobile-CSRF`,Q$=async(e,t={})=>{let n=await fetch(e,{credentials:`include`,...t});if(!n.ok)throw new I(await O(n,`Mobile request failed.`),n.status);return n},$$=async(e,t={})=>await(await Q$(e,t)).json(),e1=e=>$$(`/mobile/projects`,{signal:e}),t1=(e,t)=>$$(`/mobile/projects/${encodeURIComponent(e)}/summary`,{signal:t}),n1=(e,t)=>$$(`/mobile/projects/${encodeURIComponent(e)}/target-options`,{signal:t}),r1=(e,t)=>$$(`/mobile/projects/${encodeURIComponent(e)}/chat-sessions`,{signal:t}),i1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/chat-sessions/${encodeURIComponent(t)}`,{signal:n}),a1=(e,t)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets`,{signal:t}),o1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}`,{signal:n}),s1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/bundles/${encodeURIComponent(t)}`,{signal:n}),c1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/bundles/${encodeURIComponent(t)}/build`,u1(n)),l1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/bundles/${encodeURIComponent(t)}/review`,u1(n)),u1=(e,t,n=`POST`)=>({method:n,headers:{"Content-Type":`application/json`,[Z$]:e},body:t===void 0?void 0:JSON.stringify(t)}),d1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/chat-sessions`,u1(t,n)),f1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/chat-sessions/${encodeURIComponent(t)}/messages`,u1(n,r)),p1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/chat-sessions/${encodeURIComponent(t)}`,u1(n,r,`PATCH`)),m1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/chat-sessions/${encodeURIComponent(t)}/stop`,u1(n)),h1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/state`,u1(n,{state:r},`PATCH`)),g1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/run`,u1(n)),_1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/stop`,u1(n)),v1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/stop-build`,u1(n)),y1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/resume-build`,u1(n)),b1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}`,u1(n,r,`PATCH`)),x1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/plan-follow-up`,u1(n,{instruction:r})),S1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/tickets/${encodeURIComponent(t)}/follow-up`,u1(n,{instruction:r})),C1=(e,t,n,r)=>$$(`/mobile/projects/${encodeURIComponent(e)}/bundles/${encodeURIComponent(t)}/follow-up`,u1(n,{instruction:r})),w1=(e,t,n)=>$$(`/mobile/projects/${encodeURIComponent(e)}/target`,u1(t,n)),T1=(e,t)=>$$(`/mobile/models?tool=${encodeURIComponent(e)}`,{signal:t}),E1=(e,t,n)=>{let r=new URLSearchParams({tool:e});return t&&r.set(`project_id`,t),$$(`/mobile/skills?${r.toString()}`,{signal:n})},D1=e=>$$(`/mobile-auth/status`,{signal:e}),O1=(e,t)=>$$(`/mobile-auth/pair/preview`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t}),k1=e=>$$(`/mobile-auth/pair`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)}),A1=e=>$$(`/mobile-auth/logout`,{method:`POST`,headers:{[Z$]:e}}),j1=()=>HW(window.location.origin,{withCredentials:!0}),M1=e=>Pe.t(`common:mobileApp.${e}`),N1={key:`overview`,label:M1(`navigation.overview`),Icon:J$},P1={key:`tickets`,label:M1(`navigation.tickets`),Icon:X$,ctaAriaLabel:M1(`overviewActions.ticketsAriaLabel`)},F1={key:`chats`,label:M1(`navigation.chats`),Icon:nm,ctaAriaLabel:M1(`overviewActions.chatsAriaLabel`)},I1=[N1,P1,F1],L1=`Project root has uncommitted changes. Confirm branch switch to continue.`,R1=e=>e?`Repo root (${e})`:`Repo root`,z1=e=>{if(!e)return`Repo root`;if(e.length<=20)return e;let t=e.split(`/`).filter(Boolean),n=t[t.length-1]??e;return n.length<=17?`.../${n}`:`${n.slice(0,16)}...`},B1=(e,t)=>{if(!e)return`Target`;if(e.active_target_kind===`bundle`&&e.active_target_bundle_id){let n=t?.bundles.find(t=>t.id===e.active_target_bundle_id)??null;return n?Dl(n):`Selected bundle`}return z1(t?.current_branch??null)},V1=({children:e})=>(0,Z.jsx)(`main`,{className:`min-h-screen bg-background text-foreground`,children:(0,Z.jsx)(`div`,{className:`mx-auto flex min-h-screen w-full max-w-lg items-center px-4 py-8`,children:(0,Z.jsx)(`div`,{className:`w-full`,children:e})})}),H1=({title:e,description:t,children:n})=>(0,Z.jsx)(V1,{children:(0,Z.jsxs)(gu,{className:`w-full border-border/80 bg-card/90 shadow-2xl shadow-black/20`,children:[(0,Z.jsxs)(_u,{children:[(0,Z.jsx)(vu,{children:e}),(0,Z.jsx)(yu,{children:t})]}),n?(0,Z.jsx)(xu,{className:`space-y-4`,children:n}):null]})}),U1=e=>e===`connected`?{label:`Connected`,variant:`success`,indicatorState:`finished`}:e===`reconnecting`?{label:`Reconnecting`,variant:`warning`,indicatorState:`running`}:e===`unavailable`?{label:`Offline`,variant:`destructive`,indicatorState:`error`}:{label:`Connecting`,variant:`outline`,indicatorState:`running`},W1=({status:e})=>{let t=U1(e);return(0,Z.jsxs)(U,{variant:t.variant,className:`gap-1.5 px-2.5 py-1 text-[11px] uppercase tracking-[0.14em]`,children:[(0,Z.jsx)(Rl,{state:t.indicatorState,className:`mt-0`}),t.label]})},G1=()=>{let[e,t]=(0,Y.useState)(()=>typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(`(min-width: 1024px)`).matches);return(0,Y.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(min-width: 1024px)`),n=n=>{t(n?.matches??e.matches)};return n(),typeof e.addEventListener==`function`?(e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)):(e.addListener(n),()=>e.removeListener(n))},[]),e},K1=({status:e,onRetry:t})=>e===`connected`?null:e===`unavailable`?(0,Z.jsx)(gu,{className:`border-red-500/25 bg-destructive/10 shadow-none`,children:(0,Z.jsxs)(xu,{className:`flex flex-col gap-3 pt-5`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium text-red-100`,children:`Desktop Archon is currently unreachable.`}),(0,Z.jsx)(`p`,{className:`text-sm text-red-200/85`,children:`Mobile access may have been disabled, the backend may have restarted, or this phone lost network access.`})]}),(0,Z.jsx)(`div`,{children:(0,Z.jsx)(q,{variant:`warning`,onClick:t,children:`Retry connection`})})]})}):(0,Z.jsx)(gu,{className:`border-amber-500/25 bg-amber-500/10 shadow-none`,children:(0,Z.jsx)(xu,{className:`pt-5 text-sm text-amber-100`,children:e===`connecting`?`Connecting to live updates from desktop Archon...`:`Reconnecting to desktop Archon. Existing content stays visible while this phone reconnects.`})}),q1=({title:e,description:t,children:n})=>(0,Z.jsxs)(`div`,{className:`flex max-h-[80vh] flex-col overflow-hidden`,children:[(0,Z.jsxs)(Fs,{className:`border-b border-border/70 px-4 py-4`,children:[(0,Z.jsx)(Ls,{children:e}),t?(0,Z.jsx)(Rs,{children:t}):null]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto px-4 py-4`,children:n})]}),J1=({projects:e,selectedProjectId:t,error:n,onSelectProject:r,onRetry:i})=>n?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(`p`,{className:`text-sm text-red-200`,children:n}),(0,Z.jsx)(q,{variant:`warning`,onClick:i,children:`Retry projects`})]}):e?e.length===0?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No projects are available on the desktop instance yet.`}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>{let n=e.id===t;return(0,Z.jsxs)(`button`,{type:`button`,className:K(`w-full rounded-2xl border px-4 py-3 text-left transition-colors`,n?`border-primary/50 bg-primary/10`:`border-border/80 bg-card/60 hover:border-primary/30 hover:bg-accent/60`),onClick:()=>r(e.id),children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:e.repo_path})]}),n&&(0,Z.jsx)(U,{variant:`info`,children:`Current`})]}),(0,Z.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-2 text-[11px] uppercase tracking-[0.14em] text-muted-foreground`,children:(0,Z.jsxs)(`span`,{children:[e.ticket_count,` tickets`]})})]},e.id)})}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading projects...`}),Y1=({open:e,projects:t,selectedProjectId:n,error:r,onOpenChange:i,onSelectProject:a,onRetry:o})=>(0,Z.jsx)(As,{open:e,onOpenChange:i,children:(0,Z.jsx)(Ps,{showCloseButton:!1,"aria-describedby":void 0,className:`top-auto right-0 bottom-0 left-0 max-w-none translate-x-0 translate-y-0 overflow-hidden rounded-t-3xl rounded-b-none border-x-0 border-b-0 p-0 sm:top-1/2 sm:right-auto sm:bottom-auto sm:left-1/2 sm:max-w-md sm:-translate-x-1/2 sm:-translate-y-1/2 sm:rounded-2xl sm:border sm:p-0`,children:(0,Z.jsx)(q1,{title:`Projects`,children:(0,Z.jsx)(J1,{projects:t,selectedProjectId:n,error:r,onSelectProject:e=>{a(e),i(!1)},onRetry:o})})})}),X1=({open:e,project:t,targetOptions:n,error:r,isLoading:i,isSubmitting:a,onOpenChange:o,onRetry:s,onSelectBundle:c,onSelectRepoRoot:l})=>{let[u,d]=(0,Y.useState)(``);(0,Y.useEffect)(()=>{e&&d(n?.current_branch??``)},[e,n?.current_branch]);let f=t?.active_target_kind!==`bundle`,p=_l(n?.bundles??[]),m=[{key:`default`,label:`Default branch`,branch:n?.default_branch??null},{key:`previous`,label:`Previous branch`,branch:n?.previous_branch??null}].filter(e=>e.branch&&e.branch!==n?.current_branch).filter((e,t,n)=>n.findIndex(t=>t.branch===e.branch)===t),h=t?r?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(`p`,{className:`text-sm text-red-200`,children:r}),(0,Z.jsx)(q,{variant:`warning`,onClick:s,children:`Retry target options`})]}):n?(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-sm font-semibold text-foreground`,children:`Project target`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Choose the repo root or a prepared bundle for new chats and desktop work launched from this phone.`})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Qs,{className:`text-xs font-medium text-muted-foreground`,children:`Target`}),(0,Z.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border/70 bg-background/40 p-2`,children:[(0,Z.jsx)(q,{type:`button`,variant:f?`secondary`:`ghost`,className:`w-full justify-start`,disabled:a,onClick:()=>l(null),children:R1(n.current_branch)}),(0,Z.jsxs)(`div`,{className:`relative min-h-10`,"data-testid":`mobile-target-options`,children:[i&&(0,Z.jsx)(`div`,{className:`pointer-events-none absolute right-2 top-2 z-10 text-muted-foreground`,"data-testid":`mobile-target-options-spinner`,children:(0,Z.jsx)(W,{className:`h-3.5 w-3.5 animate-spin`})}),(0,Z.jsx)(`div`,{className:`max-h-40 overflow-y-auto pr-7`,children:p.length===0&&!i?(0,Z.jsx)(`p`,{className:`px-2 py-2 text-xs text-muted-foreground`,children:`No prepared bundles are available yet.`}):p.map(e=>(0,Z.jsx)(q,{type:`button`,variant:t.active_target_kind===`bundle`&&t.active_target_bundle_id===e.id?`secondary`:`ghost`,className:`w-full justify-start`,disabled:a,onClick:()=>c(e.id),children:(0,Z.jsx)(`span`,{className:`truncate`,children:Dl(e)})},e.id))})]})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Qs,{className:`text-xs font-medium text-muted-foreground`,children:`Repo root branch`}),(0,Z.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border/70 bg-background/40 p-3`,children:[(0,Z.jsx)(`div`,{className:`space-y-2`,children:m.length>0?m.map(({key:e,label:t,branch:n})=>(0,Z.jsxs)(q,{type:`button`,variant:`outline`,className:`w-full justify-between gap-3`,disabled:!f||a||!n,onClick:()=>l(n),children:[(0,Z.jsx)(`span`,{children:t}),(0,Z.jsx)(`span`,{className:`truncate text-xs text-muted-foreground`,children:n})]},e)):(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i?`Loading branch suggestions...`:`No suggested branches available.`})}),(0,Z.jsxs)(`div`,{className:`flex items-end gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1`,children:[(0,Z.jsx)(Qs,{htmlFor:`mobile-project-target-branch-input`,className:`text-xs text-muted-foreground`,children:`Switch or create branch`}),(0,Z.jsx)(Ge,{id:`mobile-project-target-branch-input`,value:u,disabled:!f||a,onChange:e=>d(e.target.value),placeholder:`feature/quick-fix`})]}),(0,Z.jsx)(q,{type:`button`,disabled:!f||!u.trim()||a,onClick:()=>l(u.trim()),children:`Switch`})]}),f?null:(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Switch to repo root to choose a branch.`})]})]})]}):(0,Z.jsx)(t0,{text:`Loading target options...`}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Select a project before choosing a target.`});return(0,Z.jsx)(As,{open:e,onOpenChange:o,children:(0,Z.jsx)(Ps,{showCloseButton:!1,"aria-describedby":void 0,className:`top-auto right-0 bottom-0 left-0 max-w-none translate-x-0 translate-y-0 overflow-hidden rounded-t-3xl rounded-b-none border-x-0 border-b-0 p-0 sm:top-1/2 sm:right-auto sm:bottom-auto sm:left-1/2 sm:max-w-md sm:-translate-x-1/2 sm:-translate-y-1/2 sm:rounded-2xl sm:border sm:p-0`,children:(0,Z.jsx)(q1,{title:`Target`,description:t?B1(t,n):void 0,children:h})})})},Z1=({selectedProject:e,targetLabel:t,isTargetLoading:n,isTargetDisabled:r,connectionState:i,onOpenProjects:a,onOpenTargetSelector:o})=>(0,Z.jsx)(`header`,{className:`sticky top-0 z-20 border-b border-border/70 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85`,children:(0,Z.jsxs)(`div`,{className:`mx-auto flex w-full max-w-6xl items-center justify-between gap-3 px-3 pb-3 pt-4 sm:px-4`,children:[(0,Z.jsxs)(`button`,{type:`button`,"aria-label":`Choose project`,className:`min-w-0 flex-1 text-left`,onClick:a,children:[(0,Z.jsx)(`div`,{className:`truncate text-base font-medium text-foreground`,children:e?.name??`Choose a project`}),(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:e?.repo_path??`Select a desktop project to continue`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Z.jsx)(W1,{status:i}),(0,Z.jsxs)(q,{variant:`outline`,size:`sm`,"aria-label":`Choose target`,"data-testid":`mobile-target-trigger`,className:`h-8 max-w-32 gap-2 px-2.5 sm:max-w-40`,disabled:r,onClick:o,children:[(0,Z.jsx)(kl,{className:`h-3.5 w-3.5 shrink-0`}),n?(0,Z.jsx)(Oc,{className:`h-3.5 w-16`}):(0,Z.jsx)(`span`,{className:`truncate text-xs sm:text-sm`,children:t})]}),(0,Z.jsx)(q,{variant:`outline`,size:`icon-sm`,"aria-label":`Choose project`,onClick:a,children:(0,Z.jsx)(cf,{className:`h-4 w-4`})})]})]})}),Q1=({activeSection:e,onChange:t})=>(0,Z.jsx)(`nav`,{className:`fixed inset-x-0 bottom-0 z-20 border-t border-border/70 bg-background/95 px-3 pb-[calc(env(safe-area-inset-bottom)+0.75rem)] pt-2 backdrop-blur supports-[backdrop-filter]:bg-background/85 sm:px-4 lg:hidden`,children:(0,Z.jsx)(`div`,{className:`mx-auto flex max-w-6xl gap-2`,children:I1.map(n=>{let r=n.key===e,i=n.Icon;return(0,Z.jsxs)(q,{type:`button`,variant:r?`secondary`:`ghost`,className:`h-11 flex-1 gap-2`,"aria-current":r?`page`:void 0,onClick:()=>t(n.key),children:[(0,Z.jsx)(i,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:n.label})]},n.key)})})}),$1=({title:e,description:t,action:n})=>(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:[(0,Z.jsxs)(_u,{children:[(0,Z.jsx)(vu,{children:e}),(0,Z.jsx)(yu,{children:t})]}),n?(0,Z.jsx)(xu,{children:n}):null]}),e0=({label:e,value:t,accentClassName:n})=>(0,Z.jsxs)(`div`,{className:`rounded-2xl border border-border/70 bg-card/70 p-3`,children:[(0,Z.jsx)(`div`,{className:K(`text-xl font-semibold text-foreground`,n),children:t}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs uppercase tracking-[0.14em] text-muted-foreground`,children:e})]}),t0=({text:e})=>(0,Z.jsxs)(`div`,{"aria-live":`polite`,className:`flex items-center gap-2 px-1 py-3 text-sm text-muted-foreground`,role:`status`,children:[(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}),(0,Z.jsx)(`span`,{children:e})]}),n0=()=>(0,Z.jsxs)(`div`,{className:`space-y-3`,"data-testid":`mobile-overview-skeleton`,children:[(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:[(0,Z.jsx)(_u,{className:`border-b border-border/70 pb-4`,children:(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.jsx)(Oc,{className:`h-6 w-28`}),(0,Z.jsx)(Oc,{className:`h-6 w-28 rounded-full`})]})}),(0,Z.jsxs)(xu,{className:`space-y-4 pt-5`,children:[(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3`,children:Array.from({length:6},(e,t)=>(0,Z.jsxs)(`div`,{className:`rounded-2xl border border-border/70 bg-card/70 p-3`,children:[(0,Z.jsx)(Oc,{className:`h-6 w-10`}),(0,Z.jsx)(Oc,{className:`mt-2 h-3 w-16`})]},t))}),(0,Z.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:[(0,Z.jsx)(Oc,{className:`h-10 w-full rounded-xl`}),(0,Z.jsx)(Oc,{className:`h-10 w-full rounded-xl`})]})]})]}),(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:[(0,Z.jsx)(_u,{children:(0,Z.jsx)(Oc,{className:`h-6 w-20`})}),(0,Z.jsx)(xu,{children:(0,Z.jsx)(Oc,{className:`h-10 w-40 rounded-xl`})})]})]}),r0=({isLoggingOut:e,onLogout:t})=>(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:[(0,Z.jsx)(_u,{children:(0,Z.jsx)(vu,{children:`Session`})}),(0,Z.jsx)(xu,{children:(0,Z.jsxs)(q,{variant:`destructive`,className:`gap-2`,disabled:e,onClick:t,children:[(0,Z.jsx)(Y$,{className:`h-4 w-4`}),e?`Logging out...`:`Log out this phone`]})})]}),i0=({activeRun:e,tickets:t,chatSessions:n,chatSessionDetail:r})=>{let i=r?.agent_status===`running`||!!n?.some(e=>e.agent_status===`running`);if(e?.kind===`ticket`)return{label:`Ticket run active`,variant:`success`};if(i)return{label:`Chat active`,variant:`success`};if(e)return{label:`Project run active`,variant:`success`};let a=t?.filter(e=>e.agent_status===`running`&&e.parked_at===null)??[];return a.some(e=>e.state===`review`)?{label:`Reviewing`,variant:`warning`}:a.some(e=>e.state===`build`)?{label:`Building`,variant:`success`}:a.some(e=>e.state===`plan`)?{label:`Planning`,variant:`info`}:{label:`Idle`,variant:`outline`}},a0=({activeRun:e,tickets:t,chatSessions:n,chatSessionDetail:r})=>{let i=i0({activeRun:e,tickets:t,chatSessions:n,chatSessionDetail:r});return(0,Z.jsx)(U,{variant:i.variant,children:i.label})},o0=({selectedProjectId:e,summary:t,tickets:n,error:r,chatSessions:i,chatSessionDetail:a,onRetry:o,onOpenTickets:s,onOpenChats:c})=>{let l=P1.Icon,u=F1.Icon;return r?(0,Z.jsx)($1,{title:`Project summary unavailable`,description:r,action:(0,Z.jsx)(q,{variant:`warning`,onClick:o,children:`Retry summary`})}):e?!t||t.project.id!==e?(0,Z.jsx)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:(0,Z.jsx)(xu,{className:`pt-5 text-sm text-muted-foreground`,children:`Loading project summary...`})}):(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:[(0,Z.jsxs)(_u,{className:`border-b border-border/70 pb-4`,children:[(0,Z.jsx)(vu,{children:`Overview`}),(0,Z.jsx)(bu,{children:(0,Z.jsx)(a0,{activeRun:t.active_run,tickets:n,chatSessions:i,chatSessionDetail:a})})]}),(0,Z.jsxs)(xu,{className:`space-y-4 pt-5`,children:[(0,Z.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3`,children:[(0,Z.jsx)(e0,{label:`Tickets`,value:t.tickets.total}),(0,Z.jsx)(e0,{label:`Plan`,value:t.tickets.plan,accentClassName:`text-sky-200`}),(0,Z.jsx)(e0,{label:`Build`,value:t.tickets.build,accentClassName:`text-emerald-200`}),(0,Z.jsx)(e0,{label:`Review`,value:t.tickets.review,accentClassName:`text-amber-200`}),(0,Z.jsx)(e0,{label:`Done`,value:t.tickets.parked}),(0,Z.jsx)(e0,{label:`Bundles`,value:t.project.bundle_count??0})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:[(0,Z.jsxs)(q,{variant:`outline`,className:`gap-2`,"aria-label":P1.ctaAriaLabel,onClick:s,children:[(0,Z.jsx)(l,{className:`h-4 w-4`}),P1.label]}),(0,Z.jsxs)(q,{variant:`outline`,className:`gap-2`,"aria-label":F1.ctaAriaLabel,onClick:c,children:[(0,Z.jsx)(u,{className:`h-4 w-4`}),F1.label]})]})]})]}):(0,Z.jsx)($1,{title:`Choose a project`,description:`Select a desktop project before opening tickets or chats from this phone.`})},s0=e=>e.parked_at?`parked`:e.state,c0=e=>{let t=s0(e);return t===`parked`?`Done`:`${t.slice(0,1).toUpperCase()}${t.slice(1)}`},l0=e=>e===`plan`?`info`:e===`build`?`success`:e===`review`?`warning`:`outline`,u0=({ticket:e,isSelected:t,onSelectTicket:n,className:r})=>(0,Z.jsxs)(`button`,{type:`button`,className:K(`w-full rounded-2xl border px-4 py-3 text-left transition-colors`,t?`border-primary/50 bg-primary/10`:`border-border/70 bg-card/40 hover:border-primary/30 hover:bg-accent/50`,r),onClick:()=>n(e.id),children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Z.jsx)(`div`,{className:`text-sm font-medium text-foreground`,children:e.title})}),(0,Z.jsx)(U,{variant:l0(s0(e)),children:c0(e)})]}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2 text-[11px] uppercase tracking-[0.14em] text-muted-foreground`,children:[e.agent_status?(0,Z.jsx)(`span`,{children:e.agent_status}):null,e.branch?(0,Z.jsx)(`span`,{children:e.branch}):null,e.bundle?.name?(0,Z.jsx)(`span`,{children:e.bundle.name}):null]})]}),d0=({group:e,selectedBundleId:t,selectedTicketId:n,onSelectBundle:r,onSelectTicket:i})=>{let a=e.bundle.id===t,o=e.tickets.some(e=>e.id===n),[s,c]=(0,Y.useState)(o),l=Dl(e.bundle)||e.bundle.branch||e.bundle.name||`Bundle`,u=e.tickets.filter(e=>e.agent_status===`running`).length,d=a||o;return(0,Y.useEffect)(()=>{o&&c(!0)},[o]),(0,Z.jsxs)(td,{open:s,onOpenChange:c,children:[(0,Z.jsxs)(`div`,{className:K(`flex items-start gap-2 rounded-2xl border px-4 py-3 transition-colors`,d?`border-primary/50 bg-primary/10`:`border-border/70 bg-card/40 hover:border-primary/30 hover:bg-accent/50`),children:[(0,Z.jsx)(`button`,{type:`button`,className:`min-w-0 flex-1 text-left`,"aria-label":`Open bundle ${l}`,onClick:()=>r(e.bundle.id),children:(0,Z.jsx)(`div`,{className:`flex items-start justify-between gap-3`,children:(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(U,{variant:`outline`,children:`Bundle`}),(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium text-foreground`,children:l})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2 text-[11px] uppercase tracking-[0.14em] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[e.tickets.length,` ticket`,e.tickets.length===1?``:`s`]}),u>0?(0,Z.jsxs)(`span`,{children:[u,` running`]}):null,e.bundle.branch?(0,Z.jsx)(`span`,{children:e.bundle.branch}):null]})]})})}),(0,Z.jsx)(nd,{asChild:!0,children:(0,Z.jsx)(q,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`mt-0.5 shrink-0`,"aria-label":`Toggle bundle tickets for ${l}`,children:(0,Z.jsx)(ke,{className:K(`h-4 w-4 transition-transform`,s&&`rotate-180`)})})})]}),(0,Z.jsx)(rd,{className:`pt-2`,children:(0,Z.jsx)(`div`,{className:`space-y-2 pl-3`,children:e.tickets.map(t=>(0,Z.jsx)(u0,{ticket:t,isSelected:t.id===n,onSelectTicket:t=>i(t,e.bundle.id),className:`rounded-xl`},t.id))})})]})},f0=(e,t)=>Sl(e,[],t),p0=e=>[{key:`plan`,label:`Plan`,tickets:e.filter(e=>!e.parked_at&&e.state===`plan`),items:f0(e.filter(e=>!e.parked_at&&e.state===`plan`),`plan`)},{key:`build`,label:`Build`,tickets:e.filter(e=>!e.parked_at&&e.state===`build`),items:f0(e.filter(e=>!e.parked_at&&e.state===`build`),`build`)},{key:`review`,label:`Review`,tickets:e.filter(e=>!e.parked_at&&e.state===`review`),items:f0(e.filter(e=>!e.parked_at&&e.state===`review`),`review`)},{key:`parked`,label:`Done`,tickets:e.filter(e=>e.parked_at),items:f0(e.filter(e=>e.parked_at),`done`)}].filter(e=>e.tickets.length>0),m0=(e,t)=>{if(!e)return e;let n=new Map(t.tickets.map(e=>[e.id,e]));return e.map(e=>n.get(e.id)??e)},h0=({selectedProjectId:e,tickets:t,selectedBundleId:n,selectedTicketId:r,error:i,onRetry:a,onSelectBundle:o,onSelectTicket:s})=>{if(!e)return(0,Z.jsx)($1,{title:`Choose a project`,description:`Select a project before browsing tickets from this phone.`});if(i)return(0,Z.jsx)($1,{title:`Tickets unavailable`,description:i,action:(0,Z.jsx)(q,{variant:`warning`,onClick:a,children:`Retry tickets`})});if(!t)return(0,Z.jsx)(gu,{className:`border-border/80 bg-card/70 shadow-none`,children:(0,Z.jsx)(xu,{className:`pt-5 text-sm text-muted-foreground`,children:`Loading tickets...`})});if(t.length===0)return(0,Z.jsx)($1,{title:`No tickets`,description:`This project does not have any tickets yet.`});let c=p0(t);return(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none lg:flex lg:min-h-0 lg:flex-col`,children:[(0,Z.jsxs)(_u,{className:`border-b border-border/70 pb-4`,children:[(0,Z.jsx)(vu,{children:`Tickets`}),(0,Z.jsxs)(yu,{children:[t.length,` total`]})]}),(0,Z.jsx)(xu,{className:`space-y-4 pt-5 lg:min-h-0 lg:flex-1 lg:overflow-y-auto`,children:c.map(e=>(0,Z.jsxs)(`section`,{className:`space-y-2`,"aria-label":`${e.label} tickets`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:e.label}),(0,Z.jsx)(`span`,{children:e.tickets.length})]}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.items.map(e=>e.kind===`bundle`?(0,Z.jsx)(d0,{group:e.group,selectedBundleId:n,selectedTicketId:r,onSelectBundle:o,onSelectTicket:s},e.group.id):(0,Z.jsx)(u0,{ticket:e.ticket,isSelected:e.ticket.id===r,onSelectTicket:e=>s(e,null)},e.ticket.id))})]},e.key))})]})},g0=({selectedProjectId:e,chatSessions:t,selectedChatSessionId:n,error:r,onRetry:i,onOpenNewChat:a,onSelectChat:o})=>e?r?(0,Z.jsx)($1,{title:`Chats unavailable`,description:r,action:(0,Z.jsx)(q,{variant:`warning`,onClick:i,children:`Retry chats`})}):(0,Z.jsxs)(gu,{className:`border-border/80 bg-card/70 shadow-none lg:flex lg:min-h-0 lg:flex-col`,children:[(0,Z.jsxs)(_u,{className:`border-b border-border/70 pb-4`,children:[(0,Z.jsx)(vu,{children:`Chats`}),(0,Z.jsx)(yu,{children:t?`${t.length} recent`:`Loading chats...`}),(0,Z.jsx)(bu,{children:(0,Z.jsx)(q,{variant:`outline`,size:`sm`,onClick:a,children:`New chat`})})]}),(0,Z.jsx)(xu,{className:`space-y-2 pt-5 lg:min-h-0 lg:flex-1 lg:overflow-y-auto`,children:t?t.length===0?(0,Z.jsx)($1,{title:`No chats`,description:`Start a new chat to plan or build from this project.`,action:(0,Z.jsx)(q,{onClick:a,children:`Start a chat`})}):t.map(e=>(0,Z.jsx)(`button`,{type:`button`,className:K(`w-full rounded-xl border px-3 py-2.5 text-left transition-colors`,e.id===n?`border-primary/50 bg-primary/10`:`border-border/70 bg-card/40 hover:border-primary/30 hover:bg-accent/50`),onClick:()=>o(e.id),children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 pr-2 text-sm font-medium text-foreground line-clamp-2 break-words`,children:e.title}),(0,Z.jsx)(U,{variant:e.agent_status===`running`?`warning`:e.mode===`plan`?`info`:`success`,children:e.agent_status??e.mode})]})},e.id)):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading chats...`})})]}):(0,Z.jsx)($1,{title:`Choose a project`,description:`Select a project before browsing chats from this phone.`}),_0=({label:e,disabled:t,onClick:n})=>(0,Z.jsx)(q,{type:`button`,variant:`outline`,disabled:t,onClick:n,children:e}),v0=e=>{let t=e.tickets.filter(e=>!e.parked_at),n=t.filter(e=>e.state===`plan`),r=t.filter(e=>e.state===`build`),i=t.filter(e=>e.state===`review`),a=t.some(e=>e.agent_status===`running`),o=t.find(e=>Dw(e)&&e.agent_status===`running`&&!!e.session_id)??null,s=t.find(e=>Dw(e)&&e.agent_status===`stopped`&&!!e.session_id)??null,c=[];n.length>0&&c.push({id:`build`,label:`Build Bundle`,pendingLabel:`Building Bundle...`,ariaLabel:`Build Bundle`,disabled:!1,disabledReason:null});let l=r.length>0&&r.every(e=>e.agent_status===`done`),u=r.length===0&&i.length>0&&e.can_re_review===!0&&!a;return(l||u)&&c.push({id:`review`,label:u?`Re-run review`:`Review Bundle`,pendingLabel:`Reviewing Bundle...`,ariaLabel:u?`Re-run review`:`Review Bundle`,disabled:!1,disabledReason:null}),o&&c.push({id:`pause-build`,label:`Pause Build`,pendingLabel:`Pausing Build...`,ariaLabel:`Pause Build`,title:`Pause the build session. You can resume it later.`,disabled:!1,disabledReason:null}),!o&&s&&c.push({id:`resume-build`,label:`Resume`,pendingLabel:`Resuming...`,ariaLabel:`Resume`,disabled:!1,disabledReason:null}),{actions:c,runningBuildTicketId:o?.id??null,resumableBuildTicketId:s?.id??null}},y0=({ticket:e,actionState:t,actionError:n,onAction:r})=>{let i=YW(e,{reviewLabel:e.worktree_bundle_id===null?`Review`:`Review Bundle`}),a=e.worktree_bundle_id===null&&e.state===`review`&&e.can_re_review===!0&&e.agent_status!==`running`&&!e.parked_at?[{id:`review`,label:`Re-run review`,pendingLabel:`Re-running review...`,ariaLabel:`Re-run review`,disabled:!1,disabledReason:null},...i]:i;return a.length===0?null:(0,Z.jsx)(qW,{actions:a,activeAction:t,disableWhenActive:!0,className:`space-y-3`,heading:`Actions`,headingClassName:`text-[11px] font-semibold uppercase tracking-[0.14em] text-muted-foreground`,actionsClassName:`flex flex-wrap gap-2`,showDisabledReason:!0,disabledReasonClassName:`text-sm text-amber-200`,error:n,errorClassName:`text-sm text-red-200`,renderAction:({action:e,label:t,disabled:n})=>(0,Z.jsx)(_0,{label:t,disabled:n,onClick:()=>r(e.id)},e.id)})},b0=({bundleDetail:e,actionState:t,actionError:n,onAction:r})=>{let{actions:i}=v0(e);return i.length===0?null:(0,Z.jsx)(qW,{actions:i,activeAction:t,disableWhenActive:!0,className:`space-y-3`,heading:`Actions`,headingClassName:`text-[11px] font-semibold uppercase tracking-[0.14em] text-muted-foreground`,actionsClassName:`flex flex-wrap gap-2`,error:n,errorClassName:`text-sm text-red-200`,renderAction:({action:e,label:t,disabled:n})=>(0,Z.jsx)(_0,{label:t,disabled:n,onClick:()=>r(e.id)},e.id)})},x0=(e,t)=>(e??[]).map(e=>({id:e.id,role:e.role,kind:e.kind,content:e.content,created_at:e.created_at,ticket_id:t??null,ticket_proposals:`ticket_proposals`in e?e.ticket_proposals??null:null})),S0=({title:e,subtitle:t,badges:n,backLabel:r,onBack:i,action:a})=>(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-2`,children:[i?(0,Z.jsxs)(q,{variant:`ghost`,size:`sm`,className:`h-8 px-2.5 lg:hidden`,"aria-label":r,onClick:i,children:[(0,Z.jsx)(iT,{className:`h-4 w-4`}),`Back`]}):null,(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium text-foreground`,children:e}),t?(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:t}):null]})]}),a?(0,Z.jsx)(`div`,{className:`shrink-0`,children:a}):null]}),n?(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:n}):null]}),C0=({title:e,backLabel:t,onBack:n,action:r})=>(0,Z.jsxs)(`div`,{className:`-mx-3 flex shrink-0 items-center justify-between gap-3 border-b border-border/80 bg-background/95 px-3 py-2.5 backdrop-blur supports-[backdrop-filter]:bg-background/85 sm:-mx-4 sm:px-4 lg:hidden`,children:[(0,Z.jsxs)(q,{variant:`ghost`,size:`sm`,className:`h-8 px-2.5`,"aria-label":t,onClick:n,children:[(0,Z.jsx)(iT,{className:`h-4 w-4`}),`Back`]}),(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 truncate text-sm font-medium text-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`shrink-0`,children:r})]}),w0=({title:e,backLabel:t,onBack:n,action:r,subheader:i,children:a})=>(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:[(0,Z.jsx)(C0,{title:e,backLabel:t,onBack:n,action:r}),i?(0,Z.jsx)(`div`,{className:`shrink-0 border-b border-border/70 py-2 lg:hidden`,children:i}):null,(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:a})]}),T0=({value:e,onTranscript:t,onDetails:n})=>(0,Z.jsxs)(`div`,{className:`flex gap-2 px-3 sm:px-0`,children:[(0,Z.jsx)(q,{type:`button`,variant:e===`transcript`?`secondary`:`ghost`,className:`h-9 flex-1`,"aria-pressed":e===`transcript`,onClick:t,children:`Transcript`}),(0,Z.jsx)(q,{type:`button`,variant:e===`details`?`secondary`:`ghost`,className:`h-9 flex-1`,"aria-pressed":e===`details`,onClick:n,children:`Details`})]}),E0=({controls:e})=>{let[t,n]=(0,Y.useState)(!1);return(0,Z.jsxs)(td,{open:t,onOpenChange:n,children:[(0,Z.jsx)(`div`,{className:`px-1 pb-1`,children:(0,Z.jsx)(nd,{asChild:!0,children:(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`h-7 gap-1.5 px-2 text-xs text-muted-foreground`,children:[`Options`,(0,Z.jsx)(ke,{className:K(`h-3.5 w-3.5 transition-transform`,t&&`rotate-180`)})]})})}),(0,Z.jsx)(rd,{className:`px-1 pb-1`,children:(0,Z.jsx)(`div`,{className:`rounded-lg border border-border/70 bg-background/35 p-2`,children:e})})]})},D0=({ticket:e})=>{let t=[{label:`State`,value:c0(e)},{label:`Tool`,value:e.tool},{label:`Agent`,value:e.agent_status},{label:`Branch`,value:e.branch},{label:`Bundle`,value:e.bundle?.name??null},{label:`Model`,value:e.model},{label:`Variant`,value:e.variant}].filter(e=>!!e.value);return t.length===0?null:(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-2 rounded-xl border border-border/70 bg-background/40 px-3 py-3`,children:[(0,Z.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-[0.14em] text-muted-foreground`,children:`Details`}),(0,Z.jsx)(`dl`,{className:`grid gap-2 text-sm sm:grid-cols-2`,children:t.map(e=>(0,Z.jsxs)(`div`,{className:`space-y-1 rounded-lg border border-border/60 bg-background/50 px-3 py-2`,children:[(0,Z.jsx)(`dt`,{className:`text-[11px] font-semibold uppercase tracking-[0.14em] text-muted-foreground`,children:e.label}),(0,Z.jsx)(`dd`,{className:`break-words text-foreground`,children:e.value})]},e.label))})]})},O0=({ticket:e,badges:t,actionState:n,actionError:r,onAction:i,className:a})=>(0,Z.jsxs)(gu,{className:K(`flex min-h-0 min-w-0 flex-col border-border/80 bg-card/70 shadow-none`,a),children:[(0,Z.jsx)(_u,{className:`min-w-0 pb-3`,children:(0,Z.jsx)(S0,{title:e.title,badges:t})}),(0,Z.jsxs)(xu,{className:`min-h-0 min-w-0 flex-1 space-y-3 overflow-y-auto pt-0`,children:[(0,Z.jsx)(y0,{ticket:e,actionState:n,actionError:r,onAction:i}),e.description?(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-2 rounded-xl border border-border/70 bg-background/40 px-3 py-3`,children:[(0,Z.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-[0.14em] text-muted-foreground`,children:`Description`}),(0,Z.jsx)(WM,{content:e.description,className:`min-w-0 text-foreground`})]}):null,(0,Z.jsx)(D0,{ticket:e})]})]}),k0=({bundleDetail:e,title:t,subtitle:n,badges:r,actionState:i,actionError:a,onAction:o,orderedTickets:s,highlightedTicketId:c,isTicketListOpen:l,onTicketListOpenChange:u,onSelectTicket:d,className:f})=>(0,Z.jsxs)(gu,{className:K(`flex min-h-0 min-w-0 flex-col border-border/80 bg-card/70 shadow-none`,f),children:[(0,Z.jsx)(_u,{className:`min-w-0 pb-3`,children:(0,Z.jsx)(S0,{title:t,subtitle:n,badges:r})}),(0,Z.jsxs)(xu,{className:`min-h-0 min-w-0 flex-1 space-y-3 overflow-y-auto pt-0`,children:[(0,Z.jsx)(b0,{bundleDetail:e,actionState:i,actionError:a,onAction:o}),(0,Z.jsxs)(td,{open:l,onOpenChange:u,children:[(0,Z.jsx)(nd,{asChild:!0,children:(0,Z.jsxs)(q,{type:`button`,variant:`ghost`,className:`h-8 gap-1.5 px-2 text-xs text-muted-foreground`,children:[`Tickets`,(0,Z.jsx)(ke,{className:K(`h-3.5 w-3.5 transition-transform`,l&&`rotate-180`)})]})}),(0,Z.jsx)(rd,{className:`pt-2`,children:(0,Z.jsx)(`div`,{className:`rounded-xl border border-border/70 bg-background/35 p-3`,children:(0,Z.jsx)(vG,{tickets:s,highlightedTicketId:c,onOpenTicketDetails:e=>d(e.id,e.worktree_bundle_id)})})})]})]})]}),A0=({selectedProjectId:e,bundleId:t,bundleDetail:n,openNonce:r,mobileDetailView:i,error:a,actionState:o,actionError:s,followUpPrompt:c,isSendingFollowUp:l,followUpError:u,availableModels:d,onBack:f,onRetry:p,onAction:m,onDetailViewChange:h,onSelectTicket:g,onFollowUpPromptChange:_,onFollowUpKeyDown:v,onFollowUpSubmit:y,isLargeScreen:b})=>{let[x,S]=(0,Y.useState)(!0);if((0,Y.useEffect)(()=>{S(!0)},[t,r]),!e)return(0,Z.jsx)($1,{title:`Choose a project`,description:`Select a project before opening bundle details from this phone.`});if(!t)return(0,Z.jsx)($1,{title:`Choose a bundle`,description:`Open a bundle to review its transcript and grouped ticket progress.`});if(a)return(0,Z.jsx)(w0,{title:`Bundle unavailable`,backLabel:`Back to tickets`,onBack:f,children:(0,Z.jsx)($1,{title:`Bundle unavailable`,description:a,action:(0,Z.jsx)(q,{variant:`warning`,onClick:p,children:`Retry bundle`})})});if(!n||n.bundle.id!==t)return(0,Z.jsx)(w0,{title:`Loading bundle`,backLabel:`Back to tickets`,onBack:f,children:(0,Z.jsx)(t0,{text:`Loading bundle details...`})});let C=Dl(n.bundle)||n.bundle.branch||n.bundle.name||`Bundle`,w=new Map(d.map(e=>[e.id,e.label])),T=CG(n.tickets,w),E=EG(n),D=wG(n.tickets,n.execution_order_ticket_ids),O=TG(n.tickets,w,T,n.execution_order_ticket_ids),k=dT(n.tickets,E?.state??null),A=n.tickets.find(e=>e.agent_status===`running`)??E,j=A??E??n.tickets[0]??null,M=A?.agent_status===`running`?T[A.id]??A.model??`Agent`:null,N=!!(E&&E.state!==`plan`&&bl(E)),P=n.tickets.some(e=>e.agent_status===`running`)?`Wait for all bundle tickets to finish building before sending a follow-up prompt.`:void 0,F=`mobile-bundle:${n.bundle.id}:${r}`,I=`${n.tickets.length} ticket${n.tickets.length===1?``:`s`}`,L=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(oT,{status:k}),(0,Z.jsx)(U,{variant:`outline`,children:I}),j?(0,Z.jsxs)(U,{variant:`outline`,children:[`Target: `,j.title]}):null]});return(0,Z.jsx)(w0,{title:C,backLabel:`Back to tickets`,onBack:f,subheader:b?void 0:(0,Z.jsx)(T0,{value:i,onTranscript:()=>h(`transcript`),onDetails:()=>h(`details`)}),children:b?(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 flex-col gap-3 overflow-hidden pt-3`,children:[(0,Z.jsx)(k0,{bundleDetail:n,title:C,subtitle:n.bundle.branch,badges:L,actionState:o,actionError:s,onAction:m,orderedTickets:D,highlightedTicketId:n.target_ticket_id,isTicketListOpen:x,onTicketListOpenChange:S,onSelectTicket:g,className:`shrink-0`}),(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:(0,Z.jsx)(hG,{projectId:e,followUpTicketId:n.target_ticket_id,messages:O,internalLog:A?.agent_log??null,currentThinkingMessageId:A?.agent_message_id??E?.agent_message_id??null,legacyThinkingTicketId:A?.id??E?.id??null,previousThinkingLog:A?.previous_agent_log??E?.previous_agent_log??null,previousThinkingMessageId:A?.previous_agent_message_id??E?.previous_agent_message_id??null,pendingAgentTitle:M,streamingResponse:A?.streaming_response??null,isRunning:n.tickets.some(e=>e.agent_status===`running`),canShowComposer:N,composerTheme:Tw(E?.state??null),layoutKey:F,scrollLayoutKey:F,followUpPrompt:c,followUpPlaceholder:j?`Follow up on: ${j.title}`:`Follow up on this bundle`,isSendingFollowUp:l,followUpDisabledReason:P,onFollowUpPromptChange:_,onFollowUpKeyDown:v,onFollowUpSubmit:y},F)}),u?(0,Z.jsx)(`p`,{className:`shrink-0 text-sm text-red-200`,children:u}):null]}):i===`details`?(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:(0,Z.jsx)(k0,{bundleDetail:n,title:C,subtitle:n.bundle.branch,badges:L,actionState:o,actionError:s,onAction:m,orderedTickets:D,highlightedTicketId:n.target_ticket_id,isTicketListOpen:x,onTicketListOpenChange:S,onSelectTicket:g,className:`h-full`})}):(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:[(0,Z.jsx)(hG,{projectId:e,followUpTicketId:n.target_ticket_id,messages:O,internalLog:A?.agent_log??null,currentThinkingMessageId:A?.agent_message_id??E?.agent_message_id??null,legacyThinkingTicketId:A?.id??E?.id??null,previousThinkingLog:A?.previous_agent_log??E?.previous_agent_log??null,previousThinkingMessageId:A?.previous_agent_message_id??E?.previous_agent_message_id??null,pendingAgentTitle:M,streamingResponse:A?.streaming_response??null,isRunning:n.tickets.some(e=>e.agent_status===`running`),canShowComposer:N,composerTheme:Tw(E?.state??null),layoutKey:F,scrollLayoutKey:F,followUpPrompt:c,followUpPlaceholder:j?`Follow up on: ${j.title}`:`Follow up on this bundle`,isSendingFollowUp:l,followUpDisabledReason:P,onFollowUpPromptChange:_,onFollowUpKeyDown:v,onFollowUpSubmit:y},F),u?(0,Z.jsx)(`p`,{className:`shrink-0 px-1 pt-2 text-sm text-red-200`,children:u}):null]})})},j0=({selectedProjectId:e,chatSession:t,chatSessionId:n,openNonce:r,error:i,isStopping:a,composerMode:o,composerTool:s,prompt:c,selectedModel:l,selectedVariant:u,selectedSkills:d,availableModels:f,availableSkills:p,isLoadingAgentSettings:m,isSending:h,isUpdatingMode:g,composerDisabledReason:_,onBack:v,onRetry:y,onStop:b,onModeChange:x,onPromptChange:S,onModelChange:C,onVariantChange:w,onSkillsChange:T,onPromptKeyDown:E,onSubmit:D,isLargeScreen:O})=>{if(!e)return(0,Z.jsx)($1,{title:`Choose a project`,description:`Select a project before opening the chat workspace.`});if(n&&i)return(0,Z.jsx)($1,{title:`Chat unavailable`,description:i,action:(0,Z.jsx)(q,{variant:`warning`,onClick:y,children:`Retry chat`})});if(n&&(!t||t.id!==n))return(0,Z.jsx)(w0,{title:`Loading chat`,backLabel:`Back to chats`,onBack:v,children:(0,Z.jsx)(t0,{text:`Loading chat transcript...`})});let k=t?.mode??o,A=s===`opencode`&&f.length>0,j=f.find(e=>e.id===l)??null,M=x0(t?.messages),N=t?.agent_status===`running`?(0,Z.jsxs)(q,{type:`button`,size:`sm`,variant:`outline`,className:`gap-2`,disabled:a,onClick:b,children:[a?(0,Z.jsx)(W,{className:`h-4 w-4 animate-spin`}):(0,Z.jsx)(Fc,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{children:a?`Interrupting...`:`Interrupt`})]}):null,P=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(U,{variant:k===`plan`?`info`:`success`,children:k}),(0,Z.jsx)(U,{variant:`outline`,children:t?.tool??s}),t?.agent_status?(0,Z.jsx)(U,{variant:`outline`,children:t.agent_status}):null]}),F=A?(0,Z.jsx)(CP,{model:l,variant:u,skills:d,showModelSelector:!0,showSkillsSelector:!0,availableModels:f,availableSkills:p,selectedModel:j,onModelChange:C,onVariantChange:w,onSkillsChange:T,modelSelectId:`mobile-chat-model-selector`,variantSelectId:`mobile-chat-variant-selector`,skillsSelectId:`mobile-chat-skills-selector`,disabled:!!_||h}):s===`opencode`&&m?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading model controls...`}):null,I=!O&&F?(0,Z.jsx)(E0,{controls:F}):F,L=(0,Z.jsx)(`div`,{className:`flex flex-wrap items-center gap-2`,children:(0,Z.jsx)(GX,{value:k,disabled:!!_||h||g,onChange:x})}),R=O?void 0:({showThinkingControl:e})=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 py-1`,children:[L,(0,Z.jsx)(`div`,{className:`ml-auto`,children:e})]}),z=`mobile-chat:${n??`new`}:${r}`;return(0,Z.jsx)(w0,{title:t?.title??`New chat`,backLabel:`Back to chats`,onBack:v,action:N,children:(0,Z.jsx)(WX,{projectId:e,messages:M,internalLog:t?.agent_log??null,currentThinkingMessageId:t?.agent_message_id??null,previousThinkingLog:t?.previous_agent_log??null,previousThinkingMessageId:t?.previous_agent_message_id??null,pendingAgentTitle:t?.title??`Archon`,streamingResponse:t?.streaming_response??null,isRunning:t?.agent_status===`running`,canShowComposer:!0,header:O?(0,Z.jsx)(S0,{title:t?.title??`New chat`,subtitle:t?.target_label_snapshot??`Project root`,badges:P}):R,composerControls:O?L:void 0,composerInlineControls:I,composerTheme:k,forceScrollToBottomKey:z,layoutKey:z,scrollLayoutKey:z,composerFocusNonce:r,blurComposerOnSendStart:!O,followUpPrompt:c,followUpPlaceholder:n?`Continue this chat`:k===`plan`?`Ask Archon to scope or reason through project work`:`Ask Archon to build or verify something in this project`,emptyStateText:n?`No messages yet.`:`Start a new project chat from this phone.`,isSendingFollowUp:h,followUpDisabledReason:_??void 0,hidePendingAgentTitle:!O,onFollowUpPromptChange:S,onFollowUpKeyDown:E,onFollowUpSubmit:D},z)})},M0=({selectedProjectId:e,ticketId:t,ticket:n,openNonce:r,error:i,actionState:a,actionError:o,followUpPrompt:s,followUpSelectedModel:c,followUpSelectedVariant:l,followUpSelectedSkills:u,availableModels:d,availableSkills:f,isLoadingAgentSettings:p,isSendingFollowUp:m,followUpError:h,onBack:g,onRetry:_,onAction:v,onFollowUpPromptChange:y,onFollowUpModelChange:b,onFollowUpVariantChange:x,onFollowUpSkillsChange:S,onFollowUpKeyDown:C,onFollowUpSubmit:w,isLargeScreen:T})=>{let[E,D]=(0,Y.useState)(`transcript`);if((0,Y.useEffect)(()=>{D(`transcript`)},[r,t]),!e)return(0,Z.jsx)($1,{title:`Choose a project`,description:`Select a project before opening ticket details from this phone.`});if(!t)return(0,Z.jsx)($1,{title:`Choose a ticket`,description:`Open a ticket to review its transcript and continue the workflow.`});if(i)return(0,Z.jsx)($1,{title:`Ticket unavailable`,description:i,action:(0,Z.jsx)(q,{variant:`warning`,onClick:_,children:`Retry ticket`})});if(!n||n.id!==t)return(0,Z.jsx)(w0,{title:`Loading ticket`,backLabel:`Back to tickets`,onBack:g,children:(0,Z.jsx)(t0,{text:`Loading ticket details...`})});let O=XW(n,{requireWorktree:!0}),k=x0(n.messages,n.id),A=d.find(e=>e.id===c)??null,j=n.tool===`opencode`&&d.length>0?(0,Z.jsx)(CP,{model:c,variant:l,skills:u,showModelSelector:!0,showSkillsSelector:!0,availableModels:d,availableSkills:f,selectedModel:A,onModelChange:b,onVariantChange:x,onSkillsChange:S,modelSelectId:`mobile-ticket-follow-up-model-selector`,variantSelectId:`mobile-ticket-follow-up-variant-selector`,skillsSelectId:`mobile-ticket-follow-up-skills-selector`,disabled:!!O.disabledReason||m}):n.tool===`opencode`&&p?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading model controls...`}):null,M=!T&&j?(0,Z.jsx)(E0,{controls:j}):j,N=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(U,{variant:l0(s0(n)),children:c0(n)}),n.tool?(0,Z.jsx)(U,{variant:`outline`,children:n.tool}):null,n.agent_status?(0,Z.jsx)(U,{variant:`outline`,children:n.agent_status}):null,n.branch?(0,Z.jsx)(U,{variant:`outline`,children:n.branch}):null,n.bundle?.name?(0,Z.jsx)(U,{variant:`outline`,children:n.bundle.name}):null]}),P=`mobile-ticket:${n.id}:${r}`,F=(0,Z.jsx)(T0,{value:E,onTranscript:()=>D(`transcript`),onDetails:()=>D(`details`)});return(0,Z.jsx)(w0,{title:n.title,backLabel:`Back to tickets`,onBack:g,subheader:T?void 0:F,children:T?(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 flex-col gap-3 overflow-hidden pt-3`,children:[(0,Z.jsx)(O0,{ticket:n,badges:N,actionState:a,actionError:o,onAction:v,className:`shrink-0`}),(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:(0,Z.jsx)(WN,{projectId:e,followUpTicketId:n.id,messages:k,internalLog:n.agent_log??null,currentThinkingMessageId:n.agent_message_id??null,previousThinkingLog:n.previous_agent_log??null,previousThinkingMessageId:n.previous_agent_message_id??null,pendingAgentTitle:n.title,streamingResponse:n.streaming_response??null,isRunning:n.agent_status===`running`,canShowComposer:!0,followUpComposerControls:j,composerTheme:n.state,forceScrollToBottomKey:P,layoutKey:P,scrollLayoutKey:P,followUpPrompt:s,followUpPlaceholder:O.placeholder,emptyStateText:`No follow-up messages yet.`,isSendingFollowUp:m,followUpDisabledReason:O.disabledReason??void 0,onFollowUpPromptChange:y,onFollowUpKeyDown:C,onFollowUpSubmit:w},P)}),h?(0,Z.jsx)(`p`,{className:`shrink-0 text-sm text-red-200`,children:h}):null]}):E===`details`?(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:(0,Z.jsx)(O0,{ticket:n,badges:N,actionState:a,actionError:o,onAction:v,className:`h-full`})}):(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:[(0,Z.jsx)(WN,{projectId:e,followUpTicketId:n.id,messages:k,internalLog:n.agent_log??null,currentThinkingMessageId:n.agent_message_id??null,previousThinkingLog:n.previous_agent_log??null,previousThinkingMessageId:n.previous_agent_message_id??null,pendingAgentTitle:n.title,streamingResponse:n.streaming_response??null,isRunning:n.agent_status===`running`,canShowComposer:!0,followUpComposerControls:M,composerTheme:n.state,surfaceVariant:`chat`,composerSize:`compact-on-laptop`,forceScrollToBottomKey:P,layoutKey:P,scrollLayoutKey:P,followUpPrompt:s,followUpPlaceholder:O.placeholder,emptyStateText:`No follow-up messages yet.`,isSendingFollowUp:m,followUpDisabledReason:O.disabledReason??void 0,onFollowUpPromptChange:y,onFollowUpKeyDown:C,onFollowUpSubmit:w},P),h?(0,Z.jsx)(`p`,{className:`shrink-0 px-1 pt-2 text-sm text-red-200`,children:h}):null]})})},N0=()=>{let e=new URLSearchParams(window.location.search),t=new URLSearchParams(window.location.hash.slice(1)),n=e.get(`mobileAccessId`)??``,r=e.get(`pairingId`)??``,i=t.get(`pairingSecret`)??``;return!n||!r||!i?null:{mobileAccessId:n,pairingId:r,pairingSecret:i}},P0=()=>{window.history.replaceState({},``,`/mobile`)},F0=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},I0=(e,t)=>e instanceof I&&e.message?e.message:t,L0=e=>({status:`authenticated`,csrfToken:e,projects:null,selectedProjectId:null,projectError:null,projectSummary:null,projectSummaryError:null,chatSessions:null,chatSessionsError:null,selectedChatSessionId:null,chatSessionDetail:null,chatSessionDetailError:null,tickets:null,ticketsError:null,selectedBundleId:null,bundleDetail:null,bundleDetailError:null,selectedTicketId:null,ticketDetail:null,ticketDetailError:null}),R0=(e=`pairing_required`)=>({status:`unauthenticated`,reason:e}),z0=e=>e instanceof I&&(e.status===401||e.status===403),B0=()=>{let[e,t]=(0,Y.useState)({status:`checking`}),[n,r]=(0,Y.useState)(`connecting`),[i,a]=(0,Y.useState)(`overview`),[o,s]=(0,Y.useState)(!1),[c,l]=(0,Y.useState)(!1),[u,d]=(0,Y.useState)(!1),[f,p]=(0,Y.useState)(!1),[m,h]=(0,Y.useState)(!1),[g,_]=(0,Y.useState)(!1),[v,y]=(0,Y.useState)(``),[b,x]=(0,Y.useState)(`build`),[S,C]=(0,Y.useState)(``),[w,T]=(0,Y.useState)(``),[E,D]=(0,Y.useState)([]),[O,k]=(0,Y.useState)([]),[A,j]=(0,Y.useState)([]),[M,N]=(0,Y.useState)(!1),[P,F]=(0,Y.useState)(!1),[L,R]=(0,Y.useState)(!1),[ee,te]=(0,Y.useState)(null),[ne,re]=(0,Y.useState)(null),[B,ie]=(0,Y.useState)(null),[V,H]=(0,Y.useState)(null),[ae,oe]=(0,Y.useState)(null),[se,ce]=(0,Y.useState)(null),[le,ue]=(0,Y.useState)(``),[de,U]=(0,Y.useState)(``),[fe,pe]=(0,Y.useState)(``),[me,W]=(0,Y.useState)([]),[he,G]=(0,Y.useState)(!1),[ge,_e]=(0,Y.useState)(null),[ve,ye]=(0,Y.useState)(``),[be,xe]=(0,Y.useState)(!1),[Se,Ce]=(0,Y.useState)(null),[we,Te]=(0,Y.useState)(0),[Ee,De]=(0,Y.useState)(0),[Oe,ke]=(0,Y.useState)(0),[Ae,je]=(0,Y.useState)(`transcript`),[Me,Ne]=(0,Y.useState)(null),[Pe,Fe]=(0,Y.useState)(null),[Ie,Le]=(0,Y.useState)(!1),[Re,ze]=(0,Y.useState)(!1),[Be,Ve]=(0,Y.useState)(!1),[He,Ue]=(0,Y.useState)(null),[We,Ge]=(0,Y.useState)(null),Ke=(0,Y.useRef)(null),qe=(0,Y.useRef)(null),Je=(0,Y.useRef)(null),Ye=(0,Y.useRef)(null),Xe=(0,Y.useCallback)(e=>z0(e)?(t(R0(`session_revoked`)),r(`unavailable`),s(!1),l(!1),d(!1),p(!1),!0):!1,[]),Ze=(0,Y.useCallback)(async(e,n,r,i)=>{try{let a=await o1(n,r,i);t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n||t.selectedTicketId!==r?t:{...t,ticketDetail:a,ticketDetailError:null})}catch(i){if(!z(i)){if(Xe(i))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n||t.selectedTicketId!==r?t:{...t,ticketDetail:null,ticketDetailError:I0(i,`Unable to load ticket details.`)})}}},[Xe]),Qe=(0,Y.useCallback)(async(e,n,r,i)=>{try{let a=await s1(n,r,i);t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n||t.selectedBundleId!==r?t:{...t,bundleDetail:a,bundleDetailError:null,tickets:m0(t.tickets,a)})}catch(i){if(!z(i)){if(Xe(i))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n||t.selectedBundleId!==r?t:{...t,bundleDetail:null,bundleDetailError:I0(i,`Unable to load bundle details.`)})}}},[Xe]),$e=(0,Y.useCallback)(async(e,n,r)=>{try{let i=await a1(n,r);t(t=>{if(t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n)return t;let r=t.selectedTicketId&&i.some(e=>e.id===t.selectedTicketId)?t.selectedTicketId:null,a=t.selectedBundleId&&i.some(e=>e.worktree_bundle_id===t.selectedBundleId)?t.selectedBundleId:null;return{...t,tickets:i,ticketsError:null,selectedBundleId:a,bundleDetail:a?t.bundleDetail:null,bundleDetailError:a?t.bundleDetailError:null,selectedTicketId:r,ticketDetail:r?t.ticketDetail:null,ticketDetailError:r?t.ticketDetailError:null}})}catch(r){if(!z(r)){if(Xe(r))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n?t:{...t,tickets:null,ticketsError:I0(r,`Unable to load project tickets.`),selectedBundleId:null,bundleDetail:null,bundleDetailError:null,selectedTicketId:null,ticketDetail:null,ticketDetailError:null})}}},[Xe]),et=(0,Y.useCallback)(async(e,n,r,i)=>{try{let a=await i1(n,r,i);t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n||t.selectedChatSessionId!==r?t:{...t,chatSessionDetail:a,chatSessionDetailError:null})}catch(i){if(!z(i)){if(Xe(i))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n||t.selectedChatSessionId!==r?t:{...t,chatSessionDetail:null,chatSessionDetailError:I0(i,`Unable to load chat transcript.`)})}}},[Xe]),J=(0,Y.useCallback)(async(e,n,r)=>{try{let i=await r1(n,r);t(t=>{if(t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n)return t;let r=t.selectedChatSessionId&&i.some(e=>e.id===t.selectedChatSessionId)?t.selectedChatSessionId:null;return{...t,chatSessions:i,chatSessionsError:null,selectedChatSessionId:r,chatSessionDetail:r?t.chatSessionDetail:null,chatSessionDetailError:r?t.chatSessionDetailError:null}})}catch(r){if(!z(r)){if(Xe(r))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n?t:{...t,chatSessions:null,chatSessionsError:I0(r,`Unable to load project chats.`),selectedChatSessionId:null,chatSessionDetail:null,chatSessionDetailError:null})}}},[Xe]),tt=(0,Y.useCallback)(async(e,n,r)=>{try{let i=await t1(n,r);t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n?t:{...t,projectSummary:i,projectSummaryError:null})}catch(r){if(!z(r)){if(Xe(r))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e||t.selectedProjectId!==n?t:{...t,projectSummary:null,projectSummaryError:I0(r,`Unable to load the project summary.`)})}}},[Xe]),nt=(0,Y.useCallback)(async(e,t,n)=>{ze(!0);try{let e=await n1(t,n),r=Ke.current;if(r&&r!==t)return;Ne(e),Fe(null),Ue(null)}catch(e){if(!z(e)){if(Xe(e))return;let n=Ke.current;if(n&&n!==t)return;Ne(null),Fe(I0(e,`Unable to load project target options.`))}}finally{n?.aborted||ze(!1)}},[Xe]),rt=(0,Y.useCallback)(e=>{t(t=>t.status===`authenticated`?{...t,projects:t.projects?.map(t=>t.id===e.id?e:t)??t.projects,projectSummary:t.projectSummary?.project.id===e.id?{...t.projectSummary,project:e}:t.projectSummary}:t)},[]),it=(0,Y.useCallback)(async(e,n,r)=>{try{let i=await e1(n),a=r&&i.some(e=>e.id===r)?r:i[0]?.id??null;t(t=>{if(t.status!==`authenticated`||t.csrfToken!==e)return t;let n=!!(t.selectedProjectId&&a&&t.selectedProjectId===a);return{...t,projects:i,selectedProjectId:a,projectError:null,projectSummary:n?t.projectSummary:null,projectSummaryError:n?t.projectSummaryError:null,chatSessions:n?t.chatSessions:null,chatSessionsError:n?t.chatSessionsError:null,selectedChatSessionId:n?t.selectedChatSessionId:null,chatSessionDetail:n?t.chatSessionDetail:null,chatSessionDetailError:n?t.chatSessionDetailError:null,tickets:n?t.tickets:null,ticketsError:n?t.ticketsError:null,selectedBundleId:n?t.selectedBundleId:null,bundleDetail:n?t.bundleDetail:null,bundleDetailError:n?t.bundleDetailError:null,selectedTicketId:n?t.selectedTicketId:null,ticketDetail:n?t.ticketDetail:null,ticketDetailError:n?t.ticketDetailError:null}});let o=a?i.find(e=>e.id===a)??null:null;a&&(tt(e,a,n),o?.active_target_kind===`bundle`&&nt(e,a,n),J(e,a,n),$e(e,a,n))}catch(n){if(!z(n)){if(Xe(n))return;t(t=>t.status!==`authenticated`||t.csrfToken!==e?t:{...t,projects:t.projects??[],projectError:I0(n,`Unable to load projects from desktop Archon.`)})}}},[Xe,J,tt,nt,$e]),at=(0,Y.useCallback)(async e=>{t({status:`checking`}),r(`connecting`);try{let n=await D1(e);if(n.authenticated&&n.csrf_token){r(`connecting`),t(L0(n.csrf_token)),it(n.csrf_token,e,n.preferred_project_id);return}t(R0())}catch(e){z(e)||t({status:`error`,message:I0(e,`Mobile access is unavailable. Make sure it is still enabled on desktop Archon.`)})}},[it]),ot=(0,Y.useCallback)((e,n,i)=>{r(`connecting`),t(L0(e)),it(e,i,n)},[it]);(0,Y.useEffect)(()=>{let e=new AbortController;if(window.location.pathname===`/mobile/pair`){let n=N0();return P0(),n?(t({status:`pairing`}),O1(n,e.signal).then(e=>{t({status:`pairing_confirmation`,payload:n,displayCode:e.display_code,expiresAt:e.expires_at,error:null})}).catch(e=>{t({status:`error`,message:I0(e,`Pairing failed. Regenerate the pairing link from desktop Archon and try again.`)})}),()=>e.abort()):(t({status:`error`,message:`Pairing link is missing required pairing details.`}),()=>e.abort())}return at(e.signal),()=>e.abort()},[ot,at]);let st=e.status===`authenticated`?e.csrfToken:null,ct=e.status===`authenticated`?e.selectedProjectId:null,lt=e.status===`authenticated`?e.selectedChatSessionId:null,ut=e.status===`authenticated`?e.selectedBundleId:null,dt=e.status===`authenticated`?e.selectedTicketId:null,ft=e.status===`authenticated`?e.projects?.find(t=>t.id===e.selectedProjectId)??null:null,pt=e.status===`authenticated`?e.chatSessionDetail:null,mt=e.status===`authenticated`?e.bundleDetail:null,ht=e.status===`authenticated`?e.ticketDetail:null,gt=B1(ft,Me),_t=Re&&(!ft||ft.active_target_kind===`bundle`),vt=G1(),yt=pt?.tool??`opencode`,bt=e.status!==`authenticated`||!e.selectedProjectId?`Choose a project before sending a prompt.`:L?`Wait for the chat mode change before sending another prompt.`:pt?.agent_status===`running`?`Stop or wait for the current response before sending another prompt.`:null,X=!vt&&(i===`tickets`&&(u&&!!dt||c&&!!ut)||i===`chats`&&f);(0,Y.useEffect)(()=>{Ke.current=ct},[ct]),(0,Y.useEffect)(()=>{ct||(Ne(null),Fe(null),Ue(null),Le(!1),ze(!1),Ve(!1))},[ct]),(0,Y.useEffect)(()=>{qe.current=lt},[lt]),(0,Y.useEffect)(()=>{Je.current=ut},[ut]),(0,Y.useEffect)(()=>{Ye.current=dt},[dt]),(0,Y.useEffect)(()=>{if(!st||!ct){k([]),j([]),N(!1);return}if(!(yt===`opencode`||ht?.tool===`opencode`)){k([]),j([]),N(!1);return}let e=new AbortController;return N(!0),Promise.all([T1(`opencode`,e.signal),E1(`opencode`,ct,e.signal)]).then(([e,t])=>{k(e),j(t)}).catch(e=>{Xe(e)||z(e)||(k([]),j([]))}).finally(()=>{e.signal.aborted||N(!1)}),()=>e.abort()},[st,yt,Xe,ct,ht?.tool]),(0,Y.useEffect)(()=>{if(yt!==`opencode`){C(``),T(``),D([]);return}C(pt?.model??ft?.helper_model??``),T(pt?.variant??ft?.helper_variant??``),D(pt?.skills??[])},[yt,pt?.id,pt?.model,pt?.skills,pt?.variant,ft?.helper_model,ft?.helper_variant]),(0,Y.useEffect)(()=>{pt?.mode&&x(pt.mode)},[pt?.id,pt?.mode]),(0,Y.useEffect)(()=>{let e=O.find(e=>e.id===S)??null;T(t=>e?e.variants.includes(t)?t:``:t)},[O,S]),(0,Y.useEffect)(()=>{ue(``),_e(null),U(ht?.model??``),pe(ht?.variant??``),W(ht?.skills??[])},[ht?.id,ht?.model,ht?.skills,ht?.variant]),(0,Y.useEffect)(()=>{ye(``),Ce(null)},[mt?.bundle.id]),(0,Y.useEffect)(()=>{let e=O.find(e=>e.id===de)??null;pe(t=>e?e.variants.includes(t)?t:``:t)},[O,de]),(0,Y.useEffect)(()=>{if(!st)return;let e=j1();r(`connecting`);let t=()=>{let e=Ke.current,t=qe.current,n=Je.current,r=Ye.current;it(st,void 0,e),e&&(tt(st,e),J(st,e),$e(st,e)),e&&t&&et(st,e,t),e&&n&&Qe(st,e,n),e&&r&&Ze(st,e,r)},n=()=>{r(`connected`),t()},i=()=>{r(`reconnecting`)},a=()=>{r(`unavailable`)},o=()=>{it(st,void 0,Ke.current)},s=(e=null)=>{let t=Ke.current;t&&(e?.project_id&&e.project_id!==t||tt(st,t))},c=(e=null)=>{let t=Ke.current;t&&(e?.project_id&&e.project_id!==t||J(st,t))},l=(e=null)=>{let t=Ke.current;t&&(e?.project_id&&e.project_id!==t||$e(st,t))},u=(e=null)=>{let t=Ke.current,n=qe.current;!t||!n||e?.project_id&&e.project_id!==t||e?.id&&e.id!==n||et(st,t,n)},d=(e=null)=>{let t=Ke.current,n=Ye.current;!t||!n||e?.project_id&&e.project_id!==t||e?.id&&e.id!==n||Ze(st,t,n)},f=(e=null)=>{let t=Ke.current,n=Je.current;!t||!n||e?.project_id&&e.project_id!==t||Qe(st,t,n)};return e.on(`connect`,n),e.on(`disconnect`,i),e.on(`connect_error`,a),e.on(`ticket:created`,s),e.on(`ticket:created`,l),e.on(`ticket:updated`,s),e.on(`ticket:updated`,l),e.on(`ticket:updated`,f),e.on(`ticket:updated`,d),e.on(`ticket:deleted`,o),e.on(`ticket:deleted`,l),e.on(`ticket:deleted`,f),e.on(`ticket-dependency:created`,s),e.on(`ticket-dependency:deleted`,s),e.on(`chat-session:created`,c),e.on(`chat-session:updated`,c),e.on(`chat-session:updated`,u),e.on(`chat-session:deleted`,c),()=>{e.off(`connect`,n),e.off(`disconnect`,i),e.off(`connect_error`,a),e.off(`ticket:created`,s),e.off(`ticket:created`,l),e.off(`ticket:updated`,s),e.off(`ticket:updated`,l),e.off(`ticket:updated`,f),e.off(`ticket:updated`,d),e.off(`ticket:deleted`,o),e.off(`ticket:deleted`,l),e.off(`ticket:deleted`,f),e.off(`ticket-dependency:created`,s),e.off(`ticket-dependency:deleted`,s),e.off(`chat-session:created`,c),e.off(`chat-session:updated`,c),e.off(`chat-session:updated`,u),e.off(`chat-session:deleted`,c),e.disconnect()}},[st,Qe,et,J,tt,it,Ze,$e]),(0,Y.useEffect)(()=>{ut||l(!1)},[ut]),(0,Y.useEffect)(()=>{dt||d(!1)},[dt]);let xt=()=>{at()},St=e=>{a(e),l(!1),d(!1),p(!1),Ge(null)},Ct=()=>{s(!0)},wt=()=>{e.status!==`authenticated`||!e.selectedProjectId||(Ue(null),Le(!0),!Me&&!Re&&nt(e.csrfToken,e.selectedProjectId))},Tt=()=>{e.status===`authenticated`&&(h(!0),A1(e.csrfToken).then(()=>t(R0())).catch(e=>{Xe(e)||t({status:`error`,message:I0(e,`Logout failed. Mobile access may have already been revoked from desktop Archon.`)})}).finally(()=>h(!1)))},Et=()=>{if(e.status!==`pairing_confirmation`||g)return;let n=e.payload;_(!0),t({...e,error:null}),k1(n).then(e=>{if(e.authenticated&&e.csrf_token){window.history.replaceState({},``,`/mobile`),ot(e.csrf_token,e.preferred_project_id);return}t(R0())}).catch(e=>{t(t=>t.status===`pairing_confirmation`?{...t,error:I0(e,`Pairing failed. Regenerate the pairing link from desktop Archon and try again.`)}:t)}).finally(()=>_(!1))},Dt=()=>{window.history.replaceState({},``,`/mobile`),t(R0())},Ot=()=>{e.status===`authenticated`&&(t({...e,projects:null,projectError:null}),it(e.csrfToken))},kt=()=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,projectSummary:null,projectSummaryError:null}),tt(e.csrfToken,e.selectedProjectId))},At=()=>{e.status!==`authenticated`||!e.selectedProjectId||(Ne(null),Fe(null),Ue(null),nt(e.csrfToken,e.selectedProjectId))},jt=()=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,chatSessions:null,chatSessionsError:null,selectedChatSessionId:null,chatSessionDetail:null,chatSessionDetailError:null}),J(e.csrfToken,e.selectedProjectId))},Mt=()=>{e.status!==`authenticated`||!e.selectedProjectId||!e.selectedChatSessionId||(t({...e,chatSessionDetail:null,chatSessionDetailError:null}),et(e.csrfToken,e.selectedProjectId,e.selectedChatSessionId))},Nt=()=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,tickets:null,ticketsError:null,selectedBundleId:null,bundleDetail:null,bundleDetailError:null,selectedTicketId:null,ticketDetail:null,ticketDetailError:null}),$e(e.csrfToken,e.selectedProjectId))},Pt=()=>{e.status!==`authenticated`||!e.selectedProjectId||!e.selectedTicketId||(t({...e,ticketDetail:null,ticketDetailError:null}),Ze(e.csrfToken,e.selectedProjectId,e.selectedTicketId))},Ft=()=>{e.status!==`authenticated`||!e.selectedProjectId||!e.selectedBundleId||(t({...e,bundleDetail:null,bundleDetailError:null}),Qe(e.csrfToken,e.selectedProjectId,e.selectedBundleId))},It=n=>{if(e.status!==`authenticated`)return;let r=e.projects?.find(e=>e.id===n)??null;Ke.current=n,t({...e,selectedProjectId:n,projectSummary:null,projectSummaryError:null,chatSessions:null,chatSessionsError:null,selectedChatSessionId:null,chatSessionDetail:null,chatSessionDetailError:null,tickets:null,ticketsError:null,selectedBundleId:null,bundleDetail:null,bundleDetailError:null,selectedTicketId:null,ticketDetail:null,ticketDetailError:null}),ie(null),H(null),oe(null),ce(null),re(null),ce(null),setStopRunError(null),Ce(null),Ne(null),Fe(null),Ue(null),s(!1),Le(!1),l(!1),d(!1),p(!1),je(`transcript`),Ge(null),a(`overview`),tt(e.csrfToken,n),r?.active_target_kind===`bundle`&&nt(e.csrfToken,n),J(e.csrfToken,n),$e(e.csrfToken,n)},Lt=async t=>{if(!(e.status!==`authenticated`||!e.selectedProjectId)){Ve(!0),Ue(null);try{rt(await w1(e.selectedProjectId,e.csrfToken,{kind:`bundle`,bundle_id:t})),Le(!1),tt(e.csrfToken,e.selectedProjectId),nt(e.csrfToken,e.selectedProjectId)}catch(e){if(Xe(e))return;Ue(I0(e,`Unable to update the project target right now.`))}finally{Ve(!1)}}},Rt=async(t,n={})=>{if(e.status!==`authenticated`||!e.selectedProjectId)return;Ve(!0),Ue(null);let r=r=>w1(e.selectedProjectId??``,e.csrfToken,{kind:`repo_root`,...t?{branch:t}:{},...n.createBranch===!1?{create_branch:!1}:{},...r?{confirm_dirty_switch:!0}:{}});try{let t;try{t=await r(n.confirmDirtySwitch===!0)}catch(e){if(!n.confirmDirtySwitch&&e instanceof I&&e.status===409&&e.message===L1){if(!window.confirm(`${L1}\n\nSwitch anyway?`))return;t=await r(!0)}else throw e}rt(t),Le(!1),tt(e.csrfToken,e.selectedProjectId),nt(e.csrfToken,e.selectedProjectId)}catch(e){if(Xe(e))return;Ue(I0(e,`Unable to update the project target right now.`))}finally{Ve(!1)}},zt=n=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,selectedChatSessionId:n,chatSessionDetail:null,chatSessionDetailError:null}),re(null),Te(e=>e+1),p(!0),a(`chats`),et(e.csrfToken,e.selectedProjectId,n))},Bt=()=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,selectedChatSessionId:null,chatSessionDetail:null,chatSessionDetailError:null}),re(null),y(``),Te(e=>e+1),p(!0),a(`chats`))},Vt=n=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,selectedBundleId:n,bundleDetail:null,bundleDetailError:null,selectedTicketId:null,ticketDetail:null,ticketDetailError:null}),ie(null),H(null),ce(null),Ce(null),Ge(null),je(`transcript`),De(e=>e+1),l(!0),d(!1),a(`tickets`),Qe(e.csrfToken,e.selectedProjectId,n))},Ht=(n,r)=>{e.status!==`authenticated`||!e.selectedProjectId||(t({...e,selectedTicketId:n,ticketDetail:null,ticketDetailError:null}),Ge(r),ke(e=>e+1),l(r!==null),d(!0),a(`tickets`),Ze(e.csrfToken,e.selectedProjectId,n))},Ut=()=>{p(!1)},Wt=n=>{if(e.status!==`authenticated`||!e.selectedProjectId)return;if(!e.chatSessionDetail||!e.selectedChatSessionId){x(n);return}if(e.chatSessionDetail.mode===n||L)return;let r=e.selectedProjectId,i=e.selectedChatSessionId,a=e.csrfToken;R(!0),re(null),p1(r,i,a,{mode:n}).then(e=>{x(e.mode),t(t=>{if(t.status!==`authenticated`||t.selectedProjectId!==r||t.selectedChatSessionId!==i)return t;let n=t.chatSessions?.map(t=>t.id===e.id?e:t)??t.chatSessions;return{...t,chatSessions:n,chatSessionDetail:e,chatSessionDetailError:null}})}).catch(e=>{Xe(e)||re(I0(e,`Unable to update the chat mode right now.`))}).finally(()=>R(!1))},Gt=()=>{if(e.status===`authenticated`&&We&&e.selectedBundleId===We){t({...e,selectedTicketId:null,ticketDetail:null,ticketDetailError:null}),d(!1),l(!0),Ge(null);return}Ge(null),d(!1)},Kt=()=>{l(!1)},qt=e=>{let t=O.find(t=>t.id===e)??null;C(e),T(e=>t&&t.variants.includes(e)?e:``)},Jt=e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),Yt())},Yt=()=>{if(e.status!==`authenticated`||!e.selectedProjectId||P||bt)return;let n=v.trim();if(!n)return;let r=e.selectedProjectId,i=e.csrfToken,a=yt===`opencode`&&S?S:null,o=yt===`opencode`&&S&&w?w:null,s=yt===`opencode`?E:[];re(null),F(!0);let c=e=>f1(r,e.id,i,{instruction:n,tool:e.tool,model:a,variant:o,skills:s});(e.chatSessionDetail?c(e.chatSessionDetail):d1(r,i,{mode:b,tool:yt,model:a,variant:o,skills:s}).then(c)).then(e=>{y(``),p(!0),t(t=>{if(t.status!==`authenticated`||t.selectedProjectId!==r)return t;let n=t.chatSessions??[],i=n.some(t=>t.id===e.id)?n.map(t=>t.id===e.id?e:t):[e,...n];return{...t,chatSessions:i,selectedChatSessionId:e.id,chatSessionDetail:e,chatSessionDetailError:null}}),J(i,r)}).catch(e=>{Xe(e)||re(I0(e,`Unable to send the chat prompt.`))}).finally(()=>F(!1))},Xt=()=>{if(e.status!==`authenticated`||!e.selectedProjectId||!e.selectedChatSessionId||ee)return;let t=e.selectedProjectId,n=e.selectedChatSessionId;re(null),te(n),m1(t,n,e.csrfToken).then(()=>et(e.csrfToken,t,n)).catch(e=>{Xe(e)||re(I0(e,`Unable to stop the chat response.`))}).finally(()=>te(null))},Zt=n=>{if(e.status!==`authenticated`||!e.selectedProjectId||!e.selectedTicketId||ae||(n===`stop-run`||n===`pause-build`)&&!window.confirm(`Stop this ticket action on the desktop machine?`))return;let r=e.selectedProjectId,i=e.selectedTicketId,a=e.csrfToken,o=n===`build`?h1(r,i,a,`build`):n===`review`?h1(r,i,a,`review`):n===`run`?g1(r,i,a):n===`stop-run`?_1(r,i,a):n===`pause-build`?v1(r,i,a):y1(r,i,a);oe(n),ce(null),o.then(e=>{t(t=>{if(t.status!==`authenticated`||t.selectedProjectId!==r||t.selectedTicketId!==i)return t;let n=t.tickets?.map(t=>t.id===e.id?e:t)??t.tickets;return{...t,tickets:n,ticketDetail:e,ticketDetailError:null}}),tt(a,r),$e(a,r),Ze(a,r,i)}).catch(e=>{Xe(e)||ce(I0(e,`Unable to update this ticket from mobile.`))}).finally(()=>oe(null))},Qt=n=>{if(e.status!==`authenticated`||!e.selectedProjectId||!e.selectedBundleId||!e.bundleDetail||B)return;let r=e.selectedProjectId,i=e.selectedBundleId,a=e.csrfToken,o=e.bundleDetail,{runningBuildTicketId:s,resumableBuildTicketId:c}=v0(o);if(n===`pause-build`&&!window.confirm(`Pause this bundle build on the desktop machine?`))return;let l=e=>{t(t=>t.status!==`authenticated`||t.selectedProjectId!==r||t.selectedBundleId!==i?t:{...t,tickets:m0(t.tickets,e),bundleDetail:e,bundleDetailError:null})},u=e=>{t(t=>t.status!==`authenticated`||t.selectedProjectId!==r||t.selectedBundleId!==i?t:{...t,tickets:t.tickets?.map(t=>t.id===e.id?e:t)??t.tickets,bundleDetail:t.bundleDetail?{...t.bundleDetail,tickets:t.bundleDetail.tickets.map(t=>t.id===e.id?e:t)}:t.bundleDetail,bundleDetailError:null})},d=n===`build`?c1(r,i,a):n===`review`?l1(r,i,a):n===`pause-build`?s?v1(r,s,a):null:c?y1(r,c,a):null;d&&(ie(n),H(null),d.then(e=>{`tickets`in e?l(e):u(e),tt(a,r),$e(a,r),Qe(a,r,i)}).catch(e=>{Xe(e)||H(I0(e,`Unable to update this bundle from mobile.`))}).finally(()=>ie(null)))},$t=e=>{let t=O.find(t=>t.id===e)??null;U(e),pe(e=>t&&t.variants.includes(e)?e:``)},en=e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),tn())},tn=()=>{if(e.status!==`authenticated`||!e.selectedProjectId||!e.selectedTicketId||!e.ticketDetail||he)return;let n=le.trim();if(!n)return;let r=e.selectedProjectId,i=e.ticketDetail,a=e.csrfToken,o=ZW(i,{model:de||null,variant:fe||null,skills:me}),s=()=>i.state===`plan`?x1(r,i.id,a,n):S1(r,i.id,a,n),c=e=>{t(t=>{if(t.status!==`authenticated`||t.selectedProjectId!==r||t.selectedTicketId!==i.id)return t;let n=t.tickets?.map(t=>t.id===e.id?e:t)??t.tickets;return{...t,tickets:n,ticketDetail:e,ticketDetailError:null}})};G(!0),_e(null),(async()=>{o.shouldPersist&&c(await b1(r,i.id,a,{model:o.model,variant:o.variant,skills:o.skills})),c(await s()),ue(``),$e(a,r),Ze(a,r,i.id)})().catch(e=>{Xe(e)||_e(I0(e,`Unable to send the ticket follow-up.`))}).finally(()=>G(!1))},nn=e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),rn())},rn=()=>{if(e.status!==`authenticated`||!e.selectedProjectId||!e.selectedBundleId||!e.bundleDetail||be)return;let n=ve.trim();if(!n)return;let r=e.selectedProjectId,i=e.selectedBundleId,a=e.csrfToken,o=e=>{t(t=>t.status!==`authenticated`||t.selectedProjectId!==r||t.selectedBundleId!==i?t:{...t,tickets:m0(t.tickets,e),bundleDetail:e,bundleDetailError:null})};xe(!0),Ce(null),C1(r,i,a,n).then(e=>{o(e),ye(``),$e(a,r),Qe(a,r,i)}).catch(e=>{Xe(e)||Ce(I0(e,`Unable to send the bundle follow-up.`))}).finally(()=>xe(!1))};return e.status===`checking`?(0,Z.jsx)(H1,{title:`Checking mobile session`,description:`Archon is validating this browser before showing project controls.`}):e.status===`pairing`?(0,Z.jsx)(H1,{title:`Checking pairing link`,description:`Keep this page open while Archon verifies the one-time pairing link.`}):e.status===`pairing_confirmation`?(0,Z.jsxs)(H1,{title:`Compare pairing code`,description:`Confirm this code matches the desktop dialog before pairing this phone.`,children:[(0,Z.jsx)(gu,{className:`border-primary/25 bg-primary/10 shadow-none`,children:(0,Z.jsxs)(xu,{className:`space-y-2 pt-5 text-center`,children:[(0,Z.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-[0.18em] text-foreground`,children:`Verification code`}),(0,Z.jsx)(`div`,{className:`font-mono text-3xl font-semibold tracking-[0.18em] text-foreground`,children:e.displayCode}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[`Expires at `,F0(e.expiresAt)]})]})}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`If this code does not match the desktop dialog, cancel and regenerate the pairing link from desktop Archon.`}),e.error?(0,Z.jsx)(`p`,{className:`text-sm text-red-200`,children:e.error}):null,(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row`,children:[(0,Z.jsx)(q,{size:`lg`,disabled:g,onClick:Et,children:g?`Pairing...`:`Pair this phone`}),(0,Z.jsx)(q,{variant:`outline`,size:`lg`,disabled:g,onClick:Dt,children:`Cancel`})]})]}):e.status===`unauthenticated`?(0,Z.jsx)(H1,{title:e.reason===`session_revoked`?`Mobile session revoked`:`Pairing required`,description:e.reason===`session_revoked`?`This mobile session is no longer valid. Scan the QR code or open the pairing link from desktop Archon to continue.`:`This browser is not paired. Scan the QR code or open the pairing link from desktop Archon.`,children:(0,Z.jsx)(q,{onClick:xt,children:`Retry`})}):e.status===`error`?(0,Z.jsx)(H1,{title:`Mobile access unavailable`,description:e.message,children:(0,Z.jsx)(q,{onClick:xt,children:`Retry`})}):(0,Z.jsxs)(`main`,{className:K(`bg-background text-foreground`,X?`flex h-[100dvh] flex-col overflow-hidden`:`min-h-screen`),children:[(0,Z.jsx)(Y1,{open:o,projects:e.projects,selectedProjectId:e.selectedProjectId,error:e.projectError,onOpenChange:s,onSelectProject:It,onRetry:Ot}),(0,Z.jsx)(X1,{open:Ie,project:ft,targetOptions:Me,error:He??Pe,isLoading:Re,isSubmitting:Be,onOpenChange:Le,onRetry:At,onSelectBundle:e=>{Lt(e)},onSelectRepoRoot:(e,t)=>{Rt(e,t)}}),(0,Z.jsx)(Z1,{selectedProject:ft,targetLabel:gt,isTargetLoading:_t,isTargetDisabled:!ct,connectionState:n,onOpenProjects:Ct,onOpenTargetSelector:wt}),X?(0,Z.jsxs)(`div`,{className:`mx-auto flex min-h-0 w-full max-w-6xl flex-1 flex-col overflow-hidden px-3 py-3 sm:px-4`,children:[i===`tickets`?(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:u&&e.selectedTicketId?(0,Z.jsx)(M0,{selectedProjectId:e.selectedProjectId,ticketId:e.selectedTicketId,ticket:e.ticketDetail,openNonce:Oe,error:e.ticketDetailError,actionState:ae,actionError:se,followUpPrompt:le,followUpSelectedModel:de,followUpSelectedVariant:fe,followUpSelectedSkills:me,availableModels:O,availableSkills:A,isLoadingAgentSettings:M,isSendingFollowUp:he,followUpError:ge,onBack:Gt,onRetry:Pt,onAction:Zt,onFollowUpPromptChange:ue,onFollowUpModelChange:$t,onFollowUpVariantChange:pe,onFollowUpSkillsChange:W,onFollowUpKeyDown:en,onFollowUpSubmit:tn,isLargeScreen:!1}):(0,Z.jsx)(A0,{selectedProjectId:e.selectedProjectId,bundleId:e.selectedBundleId,bundleDetail:e.bundleDetail,openNonce:Ee,mobileDetailView:Ae,error:e.bundleDetailError,actionState:B,actionError:V,followUpPrompt:ve,isSendingFollowUp:be,followUpError:Se,availableModels:O,onBack:Kt,onRetry:Ft,onAction:Qt,onDetailViewChange:je,onSelectTicket:Ht,onFollowUpPromptChange:ye,onFollowUpKeyDown:nn,onFollowUpSubmit:rn,isLargeScreen:!1})}):null,i===`chats`?(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:[(0,Z.jsx)(j0,{selectedProjectId:e.selectedProjectId,chatSession:e.chatSessionDetail,chatSessionId:e.selectedChatSessionId,openNonce:we,error:e.chatSessionDetailError,isStopping:ee===e.selectedChatSessionId,composerMode:e.chatSessionDetail?.mode??b,composerTool:yt,prompt:v,selectedModel:S,selectedVariant:w,selectedSkills:E,availableModels:O,availableSkills:A,isLoadingAgentSettings:M,isSending:P,isUpdatingMode:L,composerDisabledReason:bt,onBack:Ut,onRetry:Mt,onStop:Xt,onModeChange:Wt,onPromptChange:y,onModelChange:qt,onVariantChange:T,onSkillsChange:D,onPromptKeyDown:Jt,onSubmit:Yt,isLargeScreen:!1}),ne?(0,Z.jsx)(`p`,{className:`mt-3 text-sm text-red-200`,children:ne}):null]}):null]}):(0,Z.jsx)(`div`,{className:`mx-auto w-full max-w-6xl px-3 py-3 pb-[calc(env(safe-area-inset-bottom)+5rem)] sm:px-4 lg:flex lg:min-h-[calc(100dvh-4.5rem)] lg:flex-col lg:overflow-hidden lg:pb-4`,children:(0,Z.jsxs)(`div`,{className:`space-y-3 lg:flex lg:min-h-0 lg:flex-1 lg:flex-col`,children:[(0,Z.jsx)(K1,{status:n,onRetry:xt}),i===`overview`?(0,Z.jsx)(`div`,{className:`space-y-3 lg:flex lg:min-h-0 lg:flex-1 lg:flex-col`,children:e.projectError?(0,Z.jsx)($1,{title:`Projects unavailable`,description:e.projectError,action:(0,Z.jsx)(q,{variant:`warning`,onClick:Ot,children:`Retry projects`})}):e.selectedProjectId&&!e.projectSummary&&!e.projectSummaryError?(0,Z.jsx)(n0,{}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(o0,{selectedProjectId:e.selectedProjectId,summary:e.projectSummary,tickets:e.tickets,error:e.projectSummaryError,chatSessions:e.chatSessions,chatSessionDetail:e.chatSessionDetail,onRetry:kt,onOpenTickets:()=>St(`tickets`),onOpenChats:()=>St(`chats`)}),(0,Z.jsx)(r0,{isLoggingOut:m,onLogout:Tt})]})}):null,i===`tickets`?vt?(0,Z.jsxs)(`div`,{className:`grid min-h-0 flex-1 gap-3 overflow-hidden lg:grid-cols-[minmax(15rem,18rem)_minmax(0,1fr)]`,children:[(0,Z.jsx)(`div`,{className:`min-h-0`,children:(0,Z.jsx)(h0,{selectedProjectId:e.selectedProjectId,tickets:e.tickets,selectedBundleId:e.selectedBundleId,selectedTicketId:e.selectedTicketId,error:e.ticketsError,onRetry:Nt,onSelectBundle:Vt,onSelectTicket:Ht})}),(0,Z.jsx)(`div`,{className:`hidden min-h-0 lg:flex lg:flex-col lg:overflow-hidden`,children:u&&e.selectedTicketId?(0,Z.jsx)(M0,{selectedProjectId:e.selectedProjectId,ticketId:e.selectedTicketId,ticket:e.ticketDetail,openNonce:Oe,error:e.ticketDetailError,actionState:ae,actionError:se,followUpPrompt:le,followUpSelectedModel:de,followUpSelectedVariant:fe,followUpSelectedSkills:me,availableModels:O,availableSkills:A,isLoadingAgentSettings:M,isSendingFollowUp:he,followUpError:ge,onBack:Gt,onRetry:Pt,onAction:Zt,onFollowUpPromptChange:ue,onFollowUpModelChange:$t,onFollowUpVariantChange:pe,onFollowUpSkillsChange:W,onFollowUpKeyDown:en,onFollowUpSubmit:tn,isLargeScreen:!0}):(0,Z.jsx)(A0,{selectedProjectId:e.selectedProjectId,bundleId:e.selectedBundleId,bundleDetail:e.bundleDetail,openNonce:Ee,mobileDetailView:Ae,error:e.bundleDetailError,actionState:B,actionError:V,followUpPrompt:ve,isSendingFollowUp:be,followUpError:Se,availableModels:O,onBack:Kt,onRetry:Ft,onAction:Qt,onDetailViewChange:je,onSelectTicket:Ht,onFollowUpPromptChange:ye,onFollowUpKeyDown:nn,onFollowUpSubmit:rn,isLargeScreen:!0})})]}):(0,Z.jsx)(h0,{selectedProjectId:e.selectedProjectId,tickets:e.tickets,selectedBundleId:e.selectedBundleId,selectedTicketId:e.selectedTicketId,error:e.ticketsError,onRetry:Nt,onSelectBundle:Vt,onSelectTicket:Ht}):null,i===`chats`?vt?(0,Z.jsxs)(`div`,{className:`grid min-h-0 flex-1 gap-3 overflow-hidden lg:grid-cols-[minmax(15rem,18rem)_minmax(0,1fr)]`,children:[(0,Z.jsx)(`div`,{className:`min-h-0`,children:(0,Z.jsx)(g0,{selectedProjectId:e.selectedProjectId,chatSessions:e.chatSessions,selectedChatSessionId:e.selectedChatSessionId,error:e.chatSessionsError,onRetry:jt,onOpenNewChat:Bt,onSelectChat:zt})}),(0,Z.jsxs)(`div`,{className:`hidden min-h-0 lg:flex lg:flex-col lg:overflow-hidden`,children:[(0,Z.jsx)(j0,{selectedProjectId:e.selectedProjectId,chatSession:e.chatSessionDetail,chatSessionId:e.selectedChatSessionId,openNonce:we,error:e.chatSessionDetailError,isStopping:ee===e.selectedChatSessionId,composerMode:e.chatSessionDetail?.mode??b,composerTool:yt,prompt:v,selectedModel:S,selectedVariant:w,selectedSkills:E,availableModels:O,availableSkills:A,isLoadingAgentSettings:M,isSending:P,isUpdatingMode:L,composerDisabledReason:bt,onBack:Ut,onRetry:Mt,onStop:Xt,onModeChange:Wt,onPromptChange:y,onModelChange:qt,onVariantChange:T,onSkillsChange:D,onPromptKeyDown:Jt,onSubmit:Yt,isLargeScreen:!0}),ne?(0,Z.jsx)(`p`,{className:`mt-3 text-sm text-red-200`,children:ne}):null]})]}):(0,Z.jsx)(g0,{selectedProjectId:e.selectedProjectId,chatSessions:e.chatSessions,selectedChatSessionId:e.selectedChatSessionId,error:e.chatSessionsError,onRetry:jt,onOpenNewChat:Bt,onSelectChat:zt}):null]})}),X?null:(0,Z.jsx)(Q1,{activeSection:i,onChange:St})]})},V0=({socket:e=UW,children:t})=>(0,Z.jsx)(RY.Provider,{value:e,children:t}),H0=()=>typeof window<`u`&&window.location.pathname.startsWith(`/mobile`),U0=()=>{let e=H0();return tu(e?null:UW),(0,Z.jsx)(xt,{i18n:Pe,children:(0,Z.jsx)(wt,{children:(0,Z.jsxs)(V0,{children:[e&&(0,Z.jsx)(B0,{}),!e&&(0,Z.jsx)(q$,{})]})})})};document.documentElement.classList.add(`dark`),document.documentElement.style.colorScheme=`dark`,(0,at.createRoot)(document.getElementById(`root`)).render((0,Z.jsx)(U0,{}));export{nd as a,Ac as c,Ps as d,Rs as f,Ls as h,rd as i,As as l,Fs as m,cf as n,Fc as o,Is as p,td as r,Nc as s,UW as t,Ms as u};
|