@vibedeckx/ui-dist 0.3.41 → 0.3.42

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.
@@ -25,13 +25,13 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
25
25
  `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),bH&&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:3===this._activeSelectionMode})}_isClickInSelection(e){let r=this._getMouseBufferCoords(e),s=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!!s&&!!n&&!!r&&this._areCoordsInSelection(r,s,n)}isCellInSelection(e,r){let s=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!!s&&!!n&&this._areCoordsInSelection([e,r],s,n)}_areCoordsInSelection(e,r,s){return e[1]>r[1]&&e[1]<s[1]||r[1]===s[1]&&e[1]===r[1]&&e[0]>=r[0]&&e[0]<s[0]||r[1]<s[1]&&e[1]===s[1]&&e[0]<s[0]||r[1]<s[1]&&e[1]===r[1]&&e[0]>=r[0]}_selectWordAtCursor(e,r){let s=this._linkifier.currentLink?.link?.range;if(s)return this._model.selectionStart=[s.start.x-1,s.start.y-1],this._model.selectionStartLength=b3(s,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let n=this._getMouseBufferCoords(e);return!!n&&(this._selectWordAt(n,r),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,r){this._model.clearSelection(),e=Math.max(e,0),r=Math.min(r,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,r],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let r=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(r)return r[0]--,r[1]--,r[1]+=this._bufferService.buffer.ydisp,r}_getMouseEventScrollAmount(e){let r=bC(this._coreBrowserService.window,e,this._screenElement)[1],s=this._renderService.dimensions.css.canvas.height;return r>=0&&r<=s?0:(r>s&&(r-=s),(r=Math.min(Math.max(r,-50),50)/50)/Math.abs(r)+Math.round(14*r))}shouldForceSelection(e){return bB?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(2===e.button&&this.hasSelection)&&0===e.button){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):1===e.detail?this._handleSingleClick(e):2===e.detail?this._handleDoubleClick(e):3===e.detail&&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(),50)}_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=3*!!this.shouldColumnSelect(e),this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let r=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);r&&r.length!==this._model.selectionStart[0]&&0===r.hasWidth(this._model.selectionStart[0])&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let r=this._getMouseBufferCoords(e);r&&(this._activeSelectionMode=2,this._selectLineAt(r[1]))}shouldColumnSelect(e){return e.altKey&&!(bB&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let r=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd)return void this.refresh(!0);2===this._activeSelectionMode?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:1===this._activeSelectionMode&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),3!==this._activeSelectionMode&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let s=this._bufferService.buffer;if(this._model.selectionEnd[1]<s.lines.length){let e=s.lines.get(this._model.selectionEnd[1]);e&&0===e.hasWidth(this._model.selectionEnd[0])&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}r&&r[0]===this._model.selectionEnd[0]&&r[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?(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let r=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&r<500&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let r=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(r&&void 0!==r[0]&&void 0!==r[1]){let e=function(e,r,s,n){var i,a,o,l,c,d,u,h,f,p,m,g,x,v,y,b,w,_;let S,j=s.buffer.x,k=s.buffer.y;if(!s.buffer.hasScrollback){let w,_,S;return i=j,o=0,(0===bZ(a=k,r,l=s,c=n).length?"":b2(b0(i,a,i,a-bQ(a,l),!1,l).length,b1("D",c)))+bZ(k,r,s,n)+(d=j,u=k,h=e,w=bZ(u,f=r,p=s,m=n).length>0?f-bQ(f,p):u,S=(g=d,x=u,_=bZ(v=h,y=f,b=p,m).length>0?y-bQ(y,b):x,g<v&&_<=y||g>=v&&_<y?"C":"D"),b2(b0(d,w,h,f,"C"===S,p).length,b1(S,m)))}if(k===r)return S=j>e?"D":"C",b2(Math.abs(j-e),b1(S,n));S=k>r?"D":"C";let C=Math.abs(k-r);return b2((w=k>r?e:j,s.cols-w+(C-1)*s.cols+1+(_=0,(k>r?j:e)-1)),b1(S,n))}(r[0]-1,r[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,r=this._model.finalSelectionEnd,s=!!e&&!!r&&(e[0]!==r[0]||e[1]!==r[1]);if(!s){this._oldHasSelection&&this._fireOnSelectionChange(e,r,s);return}!e||!r||this._oldSelectionStart&&this._oldSelectionEnd&&e[0]===this._oldSelectionStart[0]&&e[1]===this._oldSelectionStart[1]&&r[0]===this._oldSelectionEnd[0]&&r[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(e,r,s)}_fireOnSelectionChange(e,r,s){this._oldSelectionStart=e,this._oldSelectionEnd=r,this._oldHasSelection=s,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,r){let s=r;for(let n=0;r>=n;n++){let i=e.loadCell(n,this._workCell).getChars().length;0===this._workCell.getWidth()?s--:i>1&&r!==n&&(s+=i-1)}return s}setSelection(e,r,s){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,r],this._model.selectionStartLength=s,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,r,s=!0,n=!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),l=this._convertViewportColToCharacterIndex(a,e[0]),c=l,d=e[0]-l,u=0,h=0,f=0,p=0;if(" "===o.charAt(l)){for(;l>0&&" "===o.charAt(l-1);)l--;for(;c<o.length&&" "===o.charAt(c+1);)c++}else{let r=e[0],s=e[0];0===a.getWidth(r)&&(u++,r--),2===a.getWidth(s)&&(h++,s++);let n=a.getString(s).length;for(n>1&&(p+=n-1,c+=n-1);r>0&&l>0&&!this._isCharWordSeparator(a.loadCell(r-1,this._workCell));){a.loadCell(r-1,this._workCell);let e=this._workCell.getChars().length;0===this._workCell.getWidth()?(u++,r--):e>1&&(f+=e-1,l-=e-1),l--,r--}for(;s<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(s+1,this._workCell));){a.loadCell(s+1,this._workCell);let e=this._workCell.getChars().length;2===this._workCell.getWidth()?(h++,s++):e>1&&(p+=e-1,c+=e-1),c++,s++}}c++;let m=l+d-u+f,g=Math.min(this._bufferService.cols,c-l+u+h-f-p);if(!(!r&&""===o.slice(l,c).trim())){if(s&&0===m&&32!==a.getCodePoint(0)){let r=i.lines.get(e[1]-1);if(r&&a.isWrapped&&32!==r.getCodePoint(this._bufferService.cols-1)){let r=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(r){let e=this._bufferService.cols-r.start;m-=e,g+=e}}}if(n&&m+g===this._bufferService.cols&&32!==a.getCodePoint(this._bufferService.cols-1)){let r=i.lines.get(e[1]+1);if(r?.isWrapped&&32!==r.getCodePoint(0)){let r=this._getWordAt([0,e[1]+1],!1,!1,!0);r&&(g+=r.length)}}return{start:m,length:g}}}_selectWordAt(e,r){let s=this._getWordAt(e,r);if(s){for(;s.start<0;)s.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[s.start,e[1]],this._model.selectionStartLength=s.length}}_selectToWordAt(e){let r=this._getWordAt(e,!0);if(r){let s=e[1];for(;r.start<0;)r.start+=this._bufferService.cols,s--;if(!this._model.areSelectionValuesReversed())for(;r.start+r.length>this._bufferService.cols;)r.length-=this._bufferService.cols,s++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?r.start:r.start+r.length,s]}}_isCharWordSeparator(e){return 0!==e.getWidth()&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let r=this._bufferService.buffer.getWrappedRangeForLine(e),s={start:{x:0,y:r.first},end:{x:this._bufferService.cols-1,y:r.last}};this._model.selectionStart=[0,r.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=b3(s,this._bufferService.cols)}};b6=g1([g2(3,xc),g2(4,xu),g2(5,x_),g2(6,xm),g2(7,xS),g2(8,xw)],b6);var b7=class{constructor(){this._data={}}set(e,r,s){this._data[e]||(this._data[e]={}),this._data[e][r]=s}get(e,r){return this._data[e]?this._data[e][r]:void 0}clear(){this._data={}}},b8=class{constructor(){this._color=new b7,this._css=new b7}setCss(e,r,s){this._css.set(e,r,s)}getCss(e,r){return this._css.get(e,r)}setColor(e,r,s){this._color.set(e,r,s)}getColor(e,r){return this._color.get(e,r)}clear(){this._color.clear(),this._css.clear()}},b9=Object.freeze((()=>{let e=[wF.toColor("#2e3436"),wF.toColor("#cc0000"),wF.toColor("#4e9a06"),wF.toColor("#c4a000"),wF.toColor("#3465a4"),wF.toColor("#75507b"),wF.toColor("#06989a"),wF.toColor("#d3d7cf"),wF.toColor("#555753"),wF.toColor("#ef2929"),wF.toColor("#8ae234"),wF.toColor("#fce94f"),wF.toColor("#729fcf"),wF.toColor("#ad7fa8"),wF.toColor("#34e2e2"),wF.toColor("#eeeeec")],r=[0,95,135,175,215,255];for(let s=0;s<216;s++){let n=r[s/36%6|0],i=r[s/6%6|0],a=r[s%6];e.push({css:yQ.toCss(n,i,a),rgba:yQ.toRgba(n,i,a)})}for(let r=0;r<24;r++){let s=8+10*r;e.push({css:yQ.toCss(s,s,s),rgba:yQ.toRgba(s,s,s)})}return e})()),we=wF.toColor("#ffffff"),wt=wF.toColor("#000000"),wr=wF.toColor("#ffffff"),ws={css:"rgba(255, 255, 255, 0.3)",rgba:0xffffff4d},wn=class extends xW{constructor(e){super(),this._optionsService=e,this._contrastCache=new b8,this._halfContrastCache=new b8,this._onChangeColors=this._register(new va),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:we,background:wt,cursor:wr,cursorAccent:wt,selectionForeground:void 0,selectionBackgroundTransparent:ws,selectionBackgroundOpaque:wM.blend(wt,ws),selectionInactiveBackgroundTransparent:ws,selectionInactiveBackgroundOpaque:wM.blend(wt,ws),scrollbarSliderBackground:wM.opacity(we,.2),scrollbarSliderHoverBackground:wM.opacity(we,.4),scrollbarSliderActiveBackground:wM.opacity(we,.5),overviewRulerBorder:we,ansi:b9.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 r=this._colors;if(r.foreground=wi(e.foreground,we),r.background=wi(e.background,wt),r.cursor=wM.blend(r.background,wi(e.cursor,wr)),r.cursorAccent=wM.blend(r.background,wi(e.cursorAccent,wt)),r.selectionBackgroundTransparent=wi(e.selectionBackground,ws),r.selectionBackgroundOpaque=wM.blend(r.background,r.selectionBackgroundTransparent),r.selectionInactiveBackgroundTransparent=wi(e.selectionInactiveBackground,r.selectionBackgroundTransparent),r.selectionInactiveBackgroundOpaque=wM.blend(r.background,r.selectionInactiveBackgroundTransparent),r.selectionForeground=e.selectionForeground?wi(e.selectionForeground,y3):void 0,r.selectionForeground===y3&&(r.selectionForeground=void 0),wM.isOpaque(r.selectionBackgroundTransparent)&&(r.selectionBackgroundTransparent=wM.opacity(r.selectionBackgroundTransparent,.3)),wM.isOpaque(r.selectionInactiveBackgroundTransparent)&&(r.selectionInactiveBackgroundTransparent=wM.opacity(r.selectionInactiveBackgroundTransparent,.3)),r.scrollbarSliderBackground=wi(e.scrollbarSliderBackground,wM.opacity(r.foreground,.2)),r.scrollbarSliderHoverBackground=wi(e.scrollbarSliderHoverBackground,wM.opacity(r.foreground,.4)),r.scrollbarSliderActiveBackground=wi(e.scrollbarSliderActiveBackground,wM.opacity(r.foreground,.5)),r.overviewRulerBorder=wi(e.overviewRulerBorder,we),r.ansi=b9.slice(),r.ansi[0]=wi(e.black,b9[0]),r.ansi[1]=wi(e.red,b9[1]),r.ansi[2]=wi(e.green,b9[2]),r.ansi[3]=wi(e.yellow,b9[3]),r.ansi[4]=wi(e.blue,b9[4]),r.ansi[5]=wi(e.magenta,b9[5]),r.ansi[6]=wi(e.cyan,b9[6]),r.ansi[7]=wi(e.white,b9[7]),r.ansi[8]=wi(e.brightBlack,b9[8]),r.ansi[9]=wi(e.brightRed,b9[9]),r.ansi[10]=wi(e.brightGreen,b9[10]),r.ansi[11]=wi(e.brightYellow,b9[11]),r.ansi[12]=wi(e.brightBlue,b9[12]),r.ansi[13]=wi(e.brightMagenta,b9[13]),r.ansi[14]=wi(e.brightCyan,b9[14]),r.ansi[15]=wi(e.brightWhite,b9[15]),e.extendedAnsi){let s=Math.min(r.ansi.length-16,e.extendedAnsi.length);for(let n=0;n<s;n++)r.ansi[n+16]=wi(e.extendedAnsi[n],b9[n+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(void 0===e){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()}}};function wi(e,r){if(void 0!==e)try{return wF.toColor(e)}catch{}return r}wn=g1([g2(0,xm)],wn);var wa=class{constructor(...e){for(let[r,s]of(this._entries=new Map,e))this.set(r,s)}set(e,r){let s=this._entries.get(e);return this._entries.set(e,r),s}forEach(e){for(let[r,s]of this._entries.entries())e(r,s)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},wo=class{constructor(){this._services=new wa,this._services.set(xf,this)}setService(e,r){this._services.set(e,r)}getService(e){return this._services.get(e)}createInstance(e,...r){let s=(e[xa]||[]).sort((e,r)=>e.index-r.index),n=[];for(let r of s){let s=this._services.get(r.id);if(!s)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${r.id._id}.`);n.push(s)}let i=s.length>0?s[0].index:r.length;if(r.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${r.length} static arguments`);return new e(...r,...n)}},wl={trace:0,debug:1,info:2,warn:3,error:4,off:5},wc=class extends xW{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=wl[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let r=0;r<e.length;r++)"function"==typeof e[r]&&(e[r]=e[r]())}_log(e,r,s){this._evalLazyOptionalParams(s),e.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+r,...s)}trace(e,...r){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,r)}debug(e,...r){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,r)}info(e,...r){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,r)}warn(e,...r){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,r)}error(e,...r){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,r)}};wc=g1([g2(0,xm)],wc);var wd=class extends xW{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new va),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new va),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new va),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 r=Array(e);for(let s=0;s<Math.min(e,this.length);s++)r[s]=this._array[this._getCyclicIndex(s)];this._array=r,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let r=this._length;r<e;r++)this._array[r]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,r){this._array[this._getCyclicIndex(e)]=r}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,r,...s){if(r){for(let s=e;s<this._length-r;s++)this._array[this._getCyclicIndex(s)]=this._array[this._getCyclicIndex(s+r)];this._length-=r,this.onDeleteEmitter.fire({index:e,amount:r})}for(let r=this._length-1;r>=e;r--)this._array[this._getCyclicIndex(r+s.length)]=this._array[this._getCyclicIndex(r)];for(let r=0;r<s.length;r++)this._array[this._getCyclicIndex(e+r)]=s[r];if(s.length&&this.onInsertEmitter.fire({index:e,amount:s.length}),this._length+s.length>this._maxLength){let e=this._length+s.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=s.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,r,s){if(!(r<=0)){if(e<0||e>=this._length)throw Error("start argument out of range");if(e+s<0)throw Error("Cannot shift elements in list beyond index 0");if(s>0){for(let n=r-1;n>=0;n--)this.set(e+n+s,this.get(e+n));let n=e+r+s-this._length;if(n>0)for(this._length+=n;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let n=0;n<r;n++)this.set(e+n+s,this.get(e+n))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},wu=Object.freeze(new xr),wh=0,wf=class e{constructor(e,r,s=!1){this.isWrapped=s,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);let n=r||xn.fromCharData([0,"",1,0]);for(let r=0;r<e;++r)this.setCell(r,n);this.length=e}get(e){let r=this._data[3*e+0],s=2097151&r;return[this._data[3*e+1],2097152&r?this._combined[e]:s?g8(s):"",r>>22,2097152&r?this._combined[e].charCodeAt(this._combined[e].length-1):s]}set(e,r){this._data[3*e+1]=r[0],r[1].length>1?(this._combined[e]=r[1],this._data[3*e+0]=2097152|e|r[2]<<22):this._data[3*e+0]=r[1].charCodeAt(0)|r[2]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 0xc00000&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){let r=this._data[3*e+0];return 2097152&r?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&r}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){let r=this._data[3*e+0];return 2097152&r?this._combined[e]:2097151&r?g8(2097151&r):""}isProtected(e){return 0x20000000&this._data[3*e+2]}loadCell(e,r){return wh=3*e,r.content=this._data[wh+0],r.fg=this._data[wh+1],r.bg=this._data[wh+2],2097152&r.content&&(r.combinedData=this._combined[e]),0x10000000&r.bg&&(r.extended=this._extendedAttrs[e]),r}setCell(e,r){2097152&r.content&&(this._combined[e]=r.combinedData),0x10000000&r.bg&&(this._extendedAttrs[e]=r.extended),this._data[3*e+0]=r.content,this._data[3*e+1]=r.fg,this._data[3*e+2]=r.bg}setCellFromCodepoint(e,r,s,n){0x10000000&n.bg&&(this._extendedAttrs[e]=n.extended),this._data[3*e+0]=r|s<<22,this._data[3*e+1]=n.fg,this._data[3*e+2]=n.bg}addCodepointToCell(e,r,s){let n=this._data[3*e+0];2097152&n?this._combined[e]+=g8(r):2097151&n?(this._combined[e]=g8(2097151&n)+g8(r),n&=-2097152,n|=2097152):n=4194304|r,s&&(n&=-0xc00001,n|=s<<22),this._data[3*e+0]=n}insertCells(e,r,s){if((e%=this.length)&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,s),r<this.length-e){let n=new xn;for(let s=this.length-e-r-1;s>=0;--s)this.setCell(e+r+s,this.loadCell(e+s,n));for(let n=0;n<r;++n)this.setCell(e+n,s)}else for(let r=e;r<this.length;++r)this.setCell(r,s);2===this.getWidth(this.length-1)&&this.setCellFromCodepoint(this.length-1,0,1,s)}deleteCells(e,r,s){if(e%=this.length,r<this.length-e){let n=new xn;for(let s=0;s<this.length-e-r;++s)this.setCell(e+s,this.loadCell(e+r+s,n));for(let e=this.length-r;e<this.length;++e)this.setCell(e,s)}else for(let r=e;r<this.length;++r)this.setCell(r,s);e&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,s),0!==this.getWidth(e)||this.hasContent(e)||this.setCellFromCodepoint(e,0,1,s)}replaceCells(e,r,s,n=!1){if(n){for(e&&2===this.getWidth(e-1)&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,s),r<this.length&&2===this.getWidth(r-1)&&!this.isProtected(r)&&this.setCellFromCodepoint(r,0,1,s);e<r&&e<this.length;)this.isProtected(e)||this.setCell(e,s),e++;return}for(e&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,s),r<this.length&&2===this.getWidth(r-1)&&this.setCellFromCodepoint(r,0,1,s);e<r&&e<this.length;)this.setCell(e++,s)}resize(e,r){if(e===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let s=3*e;if(e>this.length){if(this._data.buffer.byteLength>=4*s)this._data=new Uint32Array(this._data.buffer,0,s);else{let e=new Uint32Array(s);e.set(this._data),this._data=e}for(let s=this.length;s<e;++s)this.setCell(s,r)}else{this._data=this._data.subarray(0,s);let r=Object.keys(this._combined);for(let s=0;s<r.length;s++){let n=parseInt(r[s],10);n>=e&&delete this._combined[n]}let n=Object.keys(this._extendedAttrs);for(let r=0;r<n.length;r++){let s=parseInt(n[r],10);s>=e&&delete this._extendedAttrs[s]}}return this.length=e,4*s*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,r=!1){if(r){for(let r=0;r<this.length;++r)this.isProtected(r)||this.setCell(r,e);return}this._combined={},this._extendedAttrs={};for(let r=0;r<this.length;++r)this.setCell(r,e)}copyFrom(e){for(let r in this.length!==e.length?this._data=new Uint32Array(e._data):this._data.set(e._data),this.length=e.length,this._combined={},e._combined)this._combined[r]=e._combined[r];for(let r in this._extendedAttrs={},e._extendedAttrs)this._extendedAttrs[r]=e._extendedAttrs[r];this.isWrapped=e.isWrapped}clone(){let r=new e(0);for(let e in r._data=new Uint32Array(this._data),r.length=this.length,this._combined)r._combined[e]=this._combined[e];for(let e in this._extendedAttrs)r._extendedAttrs[e]=this._extendedAttrs[e];return r.isWrapped=this.isWrapped,r}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||0x3000000&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,r,s,n,i){let a=e._data;if(i)for(let i=n-1;i>=0;i--){for(let e=0;e<3;e++)this._data[(s+i)*3+e]=a[(r+i)*3+e];0x10000000&a[(r+i)*3+2]&&(this._extendedAttrs[s+i]=e._extendedAttrs[r+i])}else for(let i=0;i<n;i++){for(let e=0;e<3;e++)this._data[(s+i)*3+e]=a[(r+i)*3+e];0x10000000&a[(r+i)*3+2]&&(this._extendedAttrs[s+i]=e._extendedAttrs[r+i])}let o=Object.keys(e._combined);for(let n=0;n<o.length;n++){let i=parseInt(o[n],10);i>=r&&(this._combined[i-r+s]=e._combined[i])}}translateToString(e,r,s,n){r=r??0,s=s??this.length,e&&(s=Math.min(s,this.getTrimmedLength())),n&&(n.length=0);let i="";for(;r<s;){let e=this._data[3*r+0],s=2097151&e,a=2097152&e?this._combined[r]:s?g8(s):" ";if(i+=a,n)for(let e=0;e<a.length;++e)n.push(r);r+=e>>22||1}return n&&n.push(r),i}};function wp(e,r,s){if(r===e.length-1)return e[r].getTrimmedLength();let n=!e[r].hasContent(s-1)&&1===e[r].getWidth(s-1),i=2===e[r+1].getWidth(0);return n&&i?s-1:s}var wm=class e{constructor(r){this.line=r,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new va),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),xO(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};wm._nextId=1;var wg={},wx=wg.B;wg[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:"≥","{":"π","|":"≠","}":"£","~":"·"},wg.A={"#":"£"},wg.B=void 0,wg[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},wg.C=wg[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},wg.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},wg.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},wg.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},wg.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},wg.E=wg[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},wg.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},wg.H=wg[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},wg["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var wv=class{constructor(e,r,s){this._hasScrollback=e,this._optionsService=r,this._bufferService=s,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=wu.clone(),this.savedCharset=wx,this.markers=[],this._nullCell=xn.fromCharData([0,"",1,0]),this._whitespaceCell=xn.fromCharData([0," ",1,32]),this._isClearing=!1,this._memoryCleanupQueue=new bX,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new wd(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 xs),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 xs),this._whitespaceCell}getBlankLine(e,r){return new wf(this._bufferService.cols,this.getNullCell(e),r)}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 r=e+this._optionsService.rawOptions.scrollback;return r>0xffffffff?0xffffffff:r}fillViewportRows(e){if(0===this.lines.length){void 0===e&&(e=wu);let r=this._rows;for(;r--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new wd(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,r){let s=this.getNullCell(wu),n=0,i=this._getCorrectBufferLength(r);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let r=0;r<this.lines.length;r++)n+=+this.lines.get(r).resize(e,s);let a=0;if(this._rows<r)for(let n=this._rows;n<r;n++)this.lines.length<r+this.ybase&&(this._optionsService.rawOptions.windowsMode||void 0!==this._optionsService.rawOptions.windowsPty.backend||void 0!==this._optionsService.rawOptions.windowsPty.buildNumber?this.lines.push(new wf(e,s)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new wf(e,s)));else for(let e=this._rows;e>r;e--)this.lines.length>r+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,r-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=r-1,this._isReflowEnabled&&(this._reflow(e,r),this._cols>e))for(let r=0;r<this.lines.length;r++)n+=+this.lines.get(r).resize(e,s);this._cols=e,this._rows=r,this._memoryCleanupQueue.clear(),n>.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 r=0;for(;this._memoryCleanupPosition<this.lines.length;)if((r+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory())>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&"conpty"===e.backend&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,r){this._cols!==e&&(e>this._cols?this._reflowLarger(e,r):this._reflowSmaller(e,r))}_reflowLarger(e,r){let s=this._optionsService.rawOptions.reflowCursorLine,n=function(e,r,s,n,i,a){let o=[];for(let l=0;l<e.length-1;l++){let c=l,d=e.get(++c);if(!d.isWrapped)continue;let u=[e.get(l)];for(;c<e.length&&d.isWrapped;)u.push(d),d=e.get(++c);if(!a&&n>=l&&n<c){l+=u.length-1;continue}let h=0,f=wp(u,0,r),p=1,m=0;for(;p<u.length;){let e=wp(u,p,r),n=Math.min(e-m,s-f);u[h].copyCellsFrom(u[p],m,f,n,!1),(f+=n)===s&&(h++,f=0),(m+=n)===e&&(p++,m=0),0===f&&0!==h&&2===u[h-1].getWidth(s-1)&&(u[h].copyCellsFrom(u[h-1],s-1,f++,1,!1),u[h-1].setCell(s-1,i))}u[h].replaceCells(f,s,i);let g=0;for(let e=u.length-1;e>0&&(e>h||0===u[e].getTrimmedLength());e--)g++;g>0&&(o.push(l+u.length-g),o.push(g)),l+=u.length-1}return o}(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(wu),s);if(n.length>0){let s=function(e,r){let s=[],n=0,i=r[0],a=0;for(let o=0;o<e.length;o++)if(i===o){let s=r[++n];e.onDeleteEmitter.fire({index:o-a,amount:s}),o+=s-1,a+=s,i=r[++n]}else s.push(o);return{layout:s,countRemoved:a}}(this.lines,n);(function(e,r){let s=[];for(let n=0;n<r.length;n++)s.push(e.get(r[n]));for(let r=0;r<s.length;r++)e.set(r,s[r]);e.length=r.length})(this.lines,s.layout),this._reflowLargerAdjustViewport(e,r,s.countRemoved)}}_reflowLargerAdjustViewport(e,r,s){let n=this.getNullCell(wu),i=s;for(;i-- >0;)0===this.ybase?(this.y>0&&this.y--,this.lines.length<r&&this.lines.push(new wf(e,n))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-s,0)}_reflowSmaller(e,r){let s=this._optionsService.rawOptions.reflowCursorLine,n=this.getNullCell(wu),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let l=this.lines.get(o);if(!l||!l.isWrapped&&l.getTrimmedLength()<=e)continue;let c=[l];for(;l.isWrapped&&o>0;)l=this.lines.get(--o),c.unshift(l);if(!s){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let d=c[c.length-1].getTrimmedLength(),u=function(e,r,s){let n=[],i=e.map((s,n)=>wp(e,n,r)).reduce((e,r)=>e+r),a=0,o=0,l=0;for(;l<i;){if(i-l<s){n.push(i-l);break}a+=s;let c=wp(e,o,r);a>c&&(a-=c,o++);let d=2===e[o].getWidth(a-1);d&&a--;let u=d?s-1:s;n.push(u),l+=u}return n}(c,this._cols,e),h=u.length-c.length,f;f=0===this.ybase&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+h):Math.max(0,this.lines.length-this.lines.maxLength+h);let p=[];for(let e=0;e<h;e++){let e=this.getBlankLine(wu,!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,g=u[m];0===g&&(g=u[--m]);let x=c.length-h-1,v=d;for(;x>=0;){let e=Math.min(v,g);if(void 0===c[m])break;c[m].copyCellsFrom(c[x],v-e,g-e,e,!0),0==(g-=e)&&(g=u[--m]),0==(v-=e)&&(v=wp(c,Math.max(--x,0),this._cols))}for(let r=0;r<c.length;r++)u[r]<e&&c[r].setCell(u[r],n);let y=h-f;for(;y-- >0;)0===this.ybase?this.y<r-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-r&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+h,this.ybase+r-1)}if(i.length>0){let e=[],r=[];for(let e=0;e<this.lines.length;e++)r.push(this.lines.get(e));let s=this.lines.length,n=s-1,o=0,l=i[0];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let d=Math.min(this.lines.maxLength-1,s+a-1);d>=0;d--)if(l&&l.start>n+c){for(let e=l.newLines.length-1;e>=0;e--)this.lines.set(d--,l.newLines[e]);d++,e.push({index:n+1,amount:l.newLines.length}),c+=l.newLines.length,l=i[++o]}else this.lines.set(d,r[n--]);let d=0;for(let r=e.length-1;r>=0;r--)e[r].index+=d,this.lines.onInsertEmitter.fire(e[r]),d+=e[r].amount;let u=Math.max(0,s+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,r,s=0,n){let i=this.lines.get(e);return i?i.translateToString(r,s,n):""}getWrappedRangeForLine(e){let r=e,s=e;for(;r>0&&this.lines.get(r).isWrapped;)r--;for(;s+1<this.lines.length&&this.lines.get(s+1).isWrapped;)s++;return{first:r,last:s}}setupTabStops(e){for(null!=e?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(null==e&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(null==e&&(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 r=0;r<this.markers.length;r++)this.markers[r].line===e&&(this.markers[r].dispose(),this.markers.splice(r--,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 r=new wm(e);return this.markers.push(r),r.register(this.lines.onTrim(e=>{r.line-=e,r.line<0&&r.dispose()})),r.register(this.lines.onInsert(e=>{r.line>=e.index&&(r.line+=e.amount)})),r.register(this.lines.onDelete(e=>{r.line>=e.index&&r.line<e.index+e.amount&&r.dispose(),r.line>e.index&&(r.line-=e.amount)})),r.register(r.onDispose(()=>this._removeMarker(r))),r}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},wy=class extends xW{constructor(e,r){super(),this._optionsService=e,this._bufferService=r,this._onBufferActivate=this._register(new va),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 wv(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new wv(!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,r){this._normal.resize(e,r),this._alt.resize(e,r),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},wb=class extends xW{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new va),this.onResize=this._onResize.event,this._onScroll=this._register(new va),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,2),this.rows=Math.max(e.rawOptions.rows||0,1),this.buffers=this._register(new wy(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,r){let s=this.cols!==e,n=this.rows!==r;this.cols=e,this.rows=r,this.buffers.resize(e,r),this._onResize.fire({cols:e,rows:r,colsChanged:s,rowsChanged:n})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,r=!1){let s=this.buffer,n;(n=this._cachedBlankLine)&&n.length===this.cols&&n.getFg(0)===e.fg&&n.getBg(0)===e.bg||(n=s.getBlankLine(e,r),this._cachedBlankLine=n),n.isWrapped=r;let i=s.ybase+s.scrollTop,a=s.ybase+s.scrollBottom;if(0===s.scrollTop){let e=s.lines.isFull;a===s.lines.length-1?e?s.lines.recycle().copyFrom(n):s.lines.push(n.clone()):s.lines.splice(a+1,0,n.clone()),e?this.isUserScrolling&&(s.ydisp=Math.max(s.ydisp-1,0)):(s.ybase++,this.isUserScrolling||s.ydisp++)}else{let e=a-i+1;s.lines.shiftElements(i+1,e-1,-1),s.lines.set(a,n.clone())}this.isUserScrolling||(s.ydisp=s.ybase),this._onScroll.fire(s.ydisp)}scrollLines(e,r){let s=this.buffer;if(e<0){if(0===s.ydisp)return;this.isUserScrolling=!0}else e+s.ydisp>=s.ybase&&(this.isUserScrolling=!1);let n=s.ydisp;s.ydisp=Math.max(Math.min(s.ydisp+e,s.ybase),0),n!==s.ydisp&&(r||this._onScroll.fire(s.ydisp))}};wb=g1([g2(0,xm)],wb);var ww={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:bB,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},w_=["normal","bold","100","200","300","400","500","600","700","800","900"],wS=class extends xW{constructor(e){super(),this._onOptionChange=this._register(new va),this.onOptionChange=this._onOptionChange.event;let r={...ww};for(let s in e)if(s in r)try{let n=e[s];r[s]=this._sanitizeAndValidateOption(s,n)}catch(e){console.error(e)}this.rawOptions=r,this.options={...r},this._setupOptions(),this._register(xB(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,r){return this.onOptionChange(s=>{s===e&&r(this.rawOptions[e])})}onMultipleOptionChange(e,r){return this.onOptionChange(s=>{-1!==e.indexOf(s)&&r()})}_setupOptions(){let e=e=>{if(!(e in ww))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},r=(e,r)=>{if(!(e in ww))throw Error(`No option with key "${e}"`);r=this._sanitizeAndValidateOption(e,r),this.rawOptions[e]!==r&&(this.rawOptions[e]=r,this._onOptionChange.fire(e))};for(let s in this.rawOptions){let n={get:e.bind(this,s),set:r.bind(this,s)};Object.defineProperty(this.options,s,n)}}_sanitizeAndValidateOption(e,r){switch(e){case"cursorStyle":var s;if(r||(r=ww[e]),"block"!==(s=r)&&"underline"!==s&&"bar"!==s)throw Error(`"${r}" is not a valid value for ${e}`);break;case"wordSeparator":r||(r=ww[e]);break;case"fontWeight":case"fontWeightBold":if("number"==typeof r&&1<=r&&r<=1e3)break;r=w_.includes(r)?r:ww[e];break;case"cursorWidth":r=Math.floor(r);case"lineHeight":case"tabStopWidth":if(r<1)throw Error(`${e} cannot be less than 1, value: ${r}`);break;case"minimumContrastRatio":r=Math.max(1,Math.min(21,Math.round(10*r)/10));break;case"scrollback":if((r=Math.min(r,0xffffffff))<0)throw Error(`${e} cannot be less than 0, value: ${r}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(r<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${r}`);break;case"rows":case"cols":if(!r&&0!==r)throw Error(`${e} must be numeric, value: ${r}`);break;case"windowsPty":r=r??{}}return r}};function wj(e,r=5){if("object"!=typeof e)return e;let s=Array.isArray(e)?[]:{};for(let n in e)s[n]=r<=1?e[n]:e[n]&&wj(e[n],r-1);return s}var wk=Object.freeze({insertMode:!1}),wC=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),wN=class extends xW{constructor(e,r,s){super(),this._bufferService=e,this._logService=r,this._optionsService=s,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new va),this.onData=this._onData.event,this._onUserInput=this._register(new va),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new va),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new va),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=wj(wk),this.decPrivateModes=wj(wC)}reset(){this.modes=wj(wk),this.decPrivateModes=wj(wC)}triggerDataEvent(e,r=!1){if(this._optionsService.rawOptions.disableStdin)return;let s=this._bufferService.buffer;r&&this._optionsService.rawOptions.scrollOnUserInput&&s.ybase!==s.ydisp&&this._onRequestScrollToBottom.fire(),r&&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))}};wN=g1([g2(0,xc),g2(1,xp),g2(2,xm)],wN);var wE={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>4!==e.button&&1===e.action&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>32!==e.action},DRAG:{events:23,restrict:e=>32!==e.action||3!==e.button},ANY:{events:31,restrict:e=>!0}};function wD(e,r){let s=16*!!e.ctrl|4*!!e.shift|8*!!e.alt;return 4===e.button?(s|=64,s|=e.action):(s|=3&e.button,4&e.button&&(s|=64),8&e.button&&(s|=128),32===e.action?s|=32:0!==e.action||r||(s|=3)),s}var wR=String.fromCharCode,wT={DEFAULT:e=>{let r=[wD(e,!1)+32,e.col+32,e.row+32];return r[0]>255||r[1]>255||r[2]>255?"":`\x1b[M${wR(r[0])}${wR(r[1])}${wR(r[2])}`},SGR:e=>{let r=0===e.action&&4!==e.button?"m":"M";return`\x1b[<${wD(e,!0)};${e.col};${e.row}${r}`},SGR_PIXELS:e=>{let r=0===e.action&&4!==e.button?"m":"M";return`\x1b[<${wD(e,!0)};${e.x};${e.y}${r}`}},wA=class extends xW{constructor(e,r,s){for(let n of(super(),this._bufferService=e,this._coreService=r,this._optionsService=s,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new va),this.onProtocolChange=this._onProtocolChange.event,Object.keys(wE)))this.addProtocol(n,wE[n]);for(let e of Object.keys(wT))this.addEncoding(e,wT[e]);this.reset()}addProtocol(e,r){this._protocols[e]=r}addEncoding(e,r){this._encodings[e]=r}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return 0!==this._protocols[this._activeProtocol].events}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,r,s){if(0===e.deltaY||e.shiftKey||void 0===r||void 0===s)return 0;let n=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(n/=r/s+0,50>Math.abs(e.deltaY)&&(n*=.3),this._wheelPartialScroll+=n,n=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(n*=this._bufferService.rows),n}_applyScrollModifier(e,r){return r.altKey||r.ctrlKey||r.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||4===e.button&&32===e.action||3===e.button&&32!==e.action||4!==e.button&&(2===e.action||3===e.action)||(e.col++,e.row++,32===e.action&&this._lastEvent&&this._equalEvents(this._lastEvent,e,"SGR_PIXELS"===this._activeEncoding))||!this._protocols[this._activeProtocol].restrict(e))return!1;let r=this._encodings[this._activeEncoding](e);return r&&("DEFAULT"===this._activeEncoding?this._coreService.triggerBinaryEvent(r):this._coreService.triggerDataEvent(r,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}}_equalEvents(e,r,s){if(s){if(e.x!==r.x||e.y!==r.y)return!1}else if(e.col!==r.col||e.row!==r.row)return!1;return e.button===r.button&&e.action===r.action&&e.ctrl===r.ctrl&&e.alt===r.alt&&e.shift===r.shift}};wA=g1([g2(0,xc),g2(1,xu),g2(2,xm)],wA);var wI,wM,wF,wP,wL,wO,wB=[[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]],wz=[[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]],w$=class{constructor(){if(this.version="6",!wO){(wO=new Uint8Array(65536)).fill(1),wO[0]=0,wO.fill(0,1,32),wO.fill(0,127,160),wO.fill(2,4352,4448),wO[9001]=2,wO[9002]=2,wO.fill(2,11904,42192),wO[12351]=1,wO.fill(2,44032,55204),wO.fill(2,63744,64256),wO.fill(2,65040,65050),wO.fill(2,65072,65136),wO.fill(2,65280,65377),wO.fill(2,65504,65511);for(let e=0;e<wB.length;++e)wO.fill(0,wB[e][0],wB[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?wO[e]:!function(e,r){let s=0,n=r.length-1,i;if(e<r[0][0]||e>r[n][1])return!1;for(;n>=s;)if(e>r[i=s+n>>1][1])s=i+1;else{if(!(e<r[i][0]))return!0;n=i-1}return!1}(e,wz)?e>=131072&&e<=196605||e>=196608&&e<=262141?2:1:0}charProperties(e,r){let s=this.wcwidth(e),n=0===s&&0!==r;if(n){let e=wW.extractWidth(r);0===e?n=!1:e>s&&(s=e)}return wW.createPropertyValue(0,s,n)}},wW=class e{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new va,this.onChange=this._onChange.event;let e=new w$;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return(1&e)!=0}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,r,s=!1){return(0xffffff&e)<<3|(3&r)<<1|!!s}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(r){let s=0,n=0,i=r.length;for(let a=0;a<i;++a){let o=r.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return s+this.wcwidth(o);let e=r.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:s+=this.wcwidth(e)}let l=this.charProperties(o,n),c=e.extractWidth(l);e.extractShouldJoin(l)&&(c-=e.extractWidth(n)),s+=c,n=l}return s}charProperties(e,r){return this._activeProvider.charProperties(e,r)}},wH=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,r){this._charsets[e]=r,this.glevel===e&&(this.charset=r)}};function wU(e){let r=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);s&&r&&(s.isWrapped=0!==r[3]&&32!==r[3])}var wq=class e{constructor(e=32,r=32){if(this.maxLength=e,this.maxSubParamsLength=r,r>256)throw Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(r),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(r){let s=new e;if(!r.length)return s;for(let e=+!!Array.isArray(r[0]);e<r.length;++e){let n=r[e];if(Array.isArray(n))for(let e=0;e<n.length;++e)s.addSubParam(n[e]);else s.addParam(n)}return s}clone(){let r=new e(this.maxLength,this.maxSubParamsLength);return r.params.set(this.params),r.length=this.length,r._subParams.set(this._subParams),r._subParamsLength=this._subParamsLength,r._subParamsIdx.set(this._subParamsIdx),r._rejectDigits=this._rejectDigits,r._rejectSubDigits=this._rejectSubDigits,r._digitIsSub=this._digitIsSub,r}toArray(){let e=[];for(let r=0;r<this.length;++r){e.push(this.params[r]);let s=this._subParamsIdx[r]>>8,n=255&this._subParamsIdx[r];n-s>0&&e.push(Array.prototype.slice.call(this._subParams,s,n))}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>0x7fffffff?0x7fffffff: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>0x7fffffff?0x7fffffff:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let r=this._subParamsIdx[e]>>8,s=255&this._subParamsIdx[e];return s-r>0?this._subParams.subarray(r,s):null}getSubParamsAll(){let e={};for(let r=0;r<this.length;++r){let s=this._subParamsIdx[r]>>8,n=255&this._subParamsIdx[r];n-s>0&&(e[r]=this._subParams.slice(s,n))}return e}addDigit(e){let r;if(this._rejectDigits||!(r=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,n=s[r-1];s[r-1]=~n?Math.min(10*n+e,0x7fffffff):e}},wK=[],wV=class{constructor(){this._state=0,this._active=wK,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,r){void 0===this._handlers[e]&&(this._handlers[e]=[]);let s=this._handlers[e];return s.push(r),{dispose:()=>{let e=s.indexOf(r);-1!==e&&s.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=wK}reset(){if(2===this._state)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=wK,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||wK,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].start();else this._handlerFb(this._id,"START")}_put(e,r,s){if(this._active.length)for(let n=this._active.length-1;n>=0;n--)this._active[n].put(e,r,s);else this._handlerFb(this._id,"PUT",g9(e,r,s))}start(){this.reset(),this._state=1}put(e,r,s){if(3!==this._state){if(1===this._state)for(;r<s;){let s=e[r++];if(59===s){this._state=2,this._start();break}if(s<48||57<s){this._state=3;return}-1===this._id&&(this._id=0),this._id=10*this._id+s-48}2===this._state&&s-r>0&&this._put(e,r,s)}}end(e,r=!0){if(0!==this._state){if(3!==this._state)if(1===this._state&&this._start(),this._active.length){let s=!1,n=this._active.length-1,i=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,s=r,i=this._stack.fallThrough,this._stack.paused=!1),!i&&!1===s){for(;n>=0&&!0!==(s=this._active[n].end(e));n--)if(s instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,s;n--}for(;n>=0;n--)if((s=this._active[n].end(!1))instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,s}else this._handlerFb(this._id,"END",e);this._active=wK,this._id=-1,this._state=0}}},wX=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,r,s){this._hitLimit||(this._data+=g9(e,r,s),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let r=!1;if(this._hitLimit)r=!1;else if(e&&(r=this._handler(this._data))instanceof Promise)return r.then(e=>(this._data="",this._hitLimit=!1,e));return this._data="",this._hitLimit=!1,r}},wY=[],wG=class{constructor(){this._handlers=Object.create(null),this._active=wY,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=wY}registerHandler(e,r){void 0===this._handlers[e]&&(this._handlers[e]=[]);let s=this._handlers[e];return s.push(r),{dispose:()=>{let e=s.indexOf(r);-1!==e&&s.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=wY,this._ident=0}hook(e,r){if(this.reset(),this._ident=e,this._active=this._handlers[e]||wY,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(r);else this._handlerFb(this._ident,"HOOK",r)}put(e,r,s){if(this._active.length)for(let n=this._active.length-1;n>=0;n--)this._active[n].put(e,r,s);else this._handlerFb(this._ident,"PUT",g9(e,r,s))}unhook(e,r=!0){if(this._active.length){let s=!1,n=this._active.length-1,i=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,s=r,i=this._stack.fallThrough,this._stack.paused=!1),!i&&!1===s){for(;n>=0&&!0!==(s=this._active[n].unhook(e));n--)if(s instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,s;n--}for(;n>=0;n--)if((s=this._active[n].unhook(!1))instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,s}else this._handlerFb(this._ident,"UNHOOK",e);this._active=wY,this._ident=0}},wJ=new wq;wJ.addParam(0);var wZ=class{constructor(e){this._handler=e,this._data="",this._params=wJ,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():wJ,this._data="",this._hitLimit=!1}put(e,r,s){this._hitLimit||(this._data+=g9(e,r,s),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let r=!1;if(this._hitLimit)r=!1;else if(e&&(r=this._handler(this._data,this._params))instanceof Promise)return r.then(e=>(this._params=wJ,this._data="",this._hitLimit=!1,e));return this._params=wJ,this._data="",this._hitLimit=!1,r}},wQ=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,r){this.table.fill(e<<4|r)}add(e,r,s,n){this.table[r<<8|e]=s<<4|n}addMany(e,r,s,n){for(let i=0;i<e.length;i++)this.table[r<<8|e[i]]=s<<4|n}},w0=function(){let e=new wQ(4095),r=Array.apply(null,Array(256)).map((e,r)=>r),s=(e,s)=>r.slice(e,s),n=s(32,127),i=s(0,24);i.push(25),i.push.apply(i,s(28,32));let a=s(0,14),o;for(o in e.setDefault(1,0),e.addMany(n,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(s(128,144),o,3,0),e.addMany(s(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(n,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(s(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(n,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(s(64,127),3,7,0),e.addMany(s(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(s(48,60),4,8,4),e.addMany(s(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(s(32,64),6,0,6),e.add(127,6,0,6),e.addMany(s(64,127),6,0,0),e.addMany(s(32,48),3,9,5),e.addMany(s(32,48),5,9,5),e.addMany(s(48,64),5,0,6),e.addMany(s(64,127),5,7,0),e.addMany(s(32,48),4,9,5),e.addMany(s(32,48),1,9,2),e.addMany(s(32,48),2,9,2),e.addMany(s(48,127),2,10,0),e.addMany(s(48,80),1,10,0),e.addMany(s(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(s(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(s(28,32),9,0,9),e.addMany(s(32,48),9,9,12),e.addMany(s(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(s(32,128),11,0,11),e.addMany(s(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(s(28,32),10,0,10),e.addMany(s(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(s(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(s(28,32),12,0,12),e.addMany(s(32,48),12,9,12),e.addMany(s(48,64),12,0,11),e.addMany(s(64,127),12,12,13),e.addMany(s(64,127),10,12,13),e.addMany(s(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(n,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(160,0,2,0),e.add(160,8,5,8),e.add(160,6,0,6),e.add(160,11,0,11),e.add(160,13,13,13),e}(),w1=class extends xW{constructor(e=w0){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 wq,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,r,s)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,r)=>{},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(xB(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new wV),this._dcsParser=this._register(new wG),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,r=[64,126]){let s=0;if(e.prefix){if(e.prefix.length>1)throw Error("only one byte as prefix supported");if((s=e.prefix.charCodeAt(0))&&60>s||s>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 r=0;r<e.intermediates.length;++r){let n=e.intermediates.charCodeAt(r);if(32>n||n>47)throw Error("intermediate must be in range 0x20 .. 0x2f");s<<=8,s|=n}}if(1!==e.final.length)throw Error("final must be a single byte");let n=e.final.charCodeAt(0);if(r[0]>n||n>r[1])throw Error(`final must be in range ${r[0]} .. ${r[1]}`);return s<<=8,s|=n}identToString(e){let r=[];for(;e;)r.push(String.fromCharCode(255&e)),e>>=8;return r.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,r){let s=this._identifier(e,[48,126]);void 0===this._escHandlers[s]&&(this._escHandlers[s]=[]);let n=this._escHandlers[s];return n.push(r),{dispose:()=>{let e=n.indexOf(r);-1!==e&&n.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,r){this._executeHandlers[e.charCodeAt(0)]=r}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,r){let s=this._identifier(e);void 0===this._csiHandlers[s]&&(this._csiHandlers[s]=[]);let n=this._csiHandlers[s];return n.push(r),{dispose:()=>{let e=n.indexOf(r);-1!==e&&n.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,r){return this._dcsParser.registerHandler(this._identifier(e),r)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,r){return this._oscParser.registerHandler(e,r)}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,0!==this._parseStack.state&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,r,s,n,i){this._parseStack.state=e,this._parseStack.handlers=r,this._parseStack.handlerPos=s,this._parseStack.transition=n,this._parseStack.chunkPos=i}parse(e,r,s){let n=0,i=0,a=0,o;if(this._parseStack.state)if(2===this._parseStack.state)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(void 0===s||1===this._parseStack.state)throw this._parseStack.state=1,Error("improper continuation due to previous async handler, giving up parsing");let r=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(!1===s&&i>-1){for(;i>=0&&!0!==(o=r[i](this._params));i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(!1===s&&i>-1){for(;i>=0&&!0!==(o=r[i]());i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(n=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(24!==n&&26!==n,s))return o;27===n&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(n=e[this._parseStack.chunkPos],o=this._oscParser.end(24!==n&&26!==n,s))return o;27===n&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let s=a;s<r;++s){switch(n=e[s],(i=this._transitions.table[this.currentState<<8|(n<160?n:160)])>>4){case 2:for(let i=s+1;;++i)if(i>=r||(n=e[i])<32||n>126&&n<160||++i>=r||(n=e[i])<32||n>126&&n<160||++i>=r||(n=e[i])<32||n>126&&n<160||++i>=r||(n=e[i])<32||n>126&&n<160){this._printHandler(e,s,i),s=i-1;break}break;case 3:this._executeHandlers[n]?this._executeHandlers[n]():this._executeHandlerFb(n),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:s,code:n,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|n],l=a?a.length-1:-1;for(;l>=0&&!0!==(o=a[l](this._params));l--)if(o instanceof Promise)return this._preserveStack(3,a,l,i,s),o;l<0&&this._csiHandlerFb(this._collect<<8|n,this._params),this.precedingJoinState=0;break;case 8:do switch(n){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(n-48)}while(++s<r&&(n=e[s])>47&&n<60)s--;break;case 9:this._collect<<=8,this._collect|=n;break;case 10:let c=this._escHandlers[this._collect<<8|n],d=c?c.length-1:-1;for(;d>=0&&!0!==(o=c[d]());d--)if(o instanceof Promise)return this._preserveStack(4,c,d,i,s),o;d<0&&this._escHandlerFb(this._collect<<8|n),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|n,this._params);break;case 13:for(let i=s+1;;++i)if(i>=r||24===(n=e[i])||26===n||27===n||n>127&&n<160){this._dcsParser.put(e,s,i),s=i-1;break}break;case 14:if(o=this._dcsParser.unhook(24!==n&&26!==n))return this._preserveStack(6,[],0,i,s),o;27===n&&(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=s+1;;i++)if(i>=r||(n=e[i])<32||n>127&&n<160){this._oscParser.put(e,s,i),s=i-1;break}break;case 6:if(o=this._oscParser.end(24!==n&&26!==n))return this._preserveStack(5,[],0,i,s),o;27===n&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&i}}},w2=/^([\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})$/,w5=/^[\da-f]+$/;function w3(e){if(!e)return;let r=e.toLowerCase();if(0===r.indexOf("rgb:")){r=r.slice(4);let e=w2.exec(r);if(e){let r=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/r*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/r*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/r*255)]}}else if(0===r.indexOf("#")&&(r=r.slice(1),w5.exec(r)&&[3,6,9,12].includes(r.length))){let e=r.length/3,s=[0,0,0];for(let n=0;n<3;++n){let i=parseInt(r.slice(e*n,e*n+e),16);s[n]=1===e?i<<4:2===e?i:3===e?i>>4:i>>8}return s}}function w4(e,r){let s=e.toString(16),n=s.length<2?"0"+s:s;switch(r){case 4:return s[0];case 8:return n;case 12:return(n+n).slice(0,3);default:return n+n}}var w6={"(":0,")":1,"*":2,"+":3,"-":1,".":2};function w7(e,r){if(e>24)return r.setWinLines||!1;switch(e){case 1:return!!r.restoreWin;case 2:return!!r.minimizeWin;case 3:return!!r.setWinPosition;case 4:return!!r.setWinSizePixels;case 5:return!!r.raiseWin;case 6:return!!r.lowerWin;case 7:return!!r.refreshWin;case 8:return!!r.setWinSizeChars;case 9:return!!r.maximizeWin;case 10:return!!r.fullscreenWin;case 11:return!!r.getWinState;case 13:return!!r.getWinPosition;case 14:return!!r.getWinSizePixels;case 15:return!!r.getScreenSizePixels;case 16:return!!r.getCellSizePixels;case 18:return!!r.getWinSizeChars;case 19:return!!r.getScreenSizeChars;case 20:return!!r.getIconTitle;case 21:return!!r.getWinTitle;case 22:return!!r.pushTitle;case 23:return!!r.popTitle;case 24:return!!r.setWinLines}return!1}var w8=0,w9=class extends xW{constructor(e,r,s,n,i,a,o,l,c=new w1){for(let d in super(),this._bufferService=e,this._charsetService=r,this._coreService=s,this._logService=n,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=l,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new xe,this._utf8Decoder=new xt,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=wu.clone(),this._eraseAttrDataInternal=wu.clone(),this._onRequestBell=this._register(new va),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new va),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new va),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new va),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new va),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new va),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new va),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new va),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new va),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new va),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new va),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new va),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new va),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 _e(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,r)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(e),params:r.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,r,s)=>{this._logService.debug("Unknown OSC code: ",{identifier:e,action:r,data:s})}),this._parser.setDcsHandlerFallback((e,r,s)=>{"HOOK"===r&&(s=s.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(e),action:r,payload:s})}),this._parser.setPrintHandler((e,r,s)=>this.print(e,r,s)),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(yG.BEL,()=>this.bell()),this._parser.setExecuteHandler(yG.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(yG.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(yG.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(yG.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(yG.BS,()=>this.backspace()),this._parser.setExecuteHandler(yG.HT,()=>this.tab()),this._parser.setExecuteHandler(yG.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(yG.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(yJ.IND,()=>this.index()),this._parser.setExecuteHandler(yJ.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(yJ.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new wX(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new wX(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new wX(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new wX(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new wX(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new wX(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new wX(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new wX(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new wX(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new wX(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new wX(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new wX(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()),wg)this._parser.registerEscHandler({intermediates:"(",final:d},()=>this.selectCharset("("+d)),this._parser.registerEscHandler({intermediates:")",final:d},()=>this.selectCharset(")"+d)),this._parser.registerEscHandler({intermediates:"*",final:d},()=>this.selectCharset("*"+d)),this._parser.registerEscHandler({intermediates:"+",final:d},()=>this.selectCharset("+"+d)),this._parser.registerEscHandler({intermediates:"-",final:d},()=>this.selectCharset("-"+d)),this._parser.registerEscHandler({intermediates:".",final:d},()=>this.selectCharset("."+d)),this._parser.registerEscHandler({intermediates:"/",final:d},()=>this.selectCharset("/"+d));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 wZ((e,r)=>this.requestStatusString(e,r)))}getAttrData(){return this._curAttrData}_preserveStack(e,r,s,n){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=r,this._parseStack.decodedLength=s,this._parseStack.position=n}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,r)=>setTimeout(()=>r("#SLOW_TIMEOUT"),5e3))]).catch(e=>{if("#SLOW_TIMEOUT"!==e)throw e;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,r){let s,n=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(s=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,r))return this._logSlowResolvingAsync(s),s;n=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>131072&&(a=this._parseStack.position+131072)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${"string"==typeof e?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join("")}"`}`),0===this._logService.logLevel&&this._logService.trace("parsing data (codes)","string"==typeof e?e.split("").map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<131072&&(this._parseBuffer=new Uint32Array(Math.min(e.length,131072))),o||this._dirtyRowTracker.clearRange(),e.length>131072)for(let r=a;r<e.length;r+=131072){let a=r+131072<e.length?r+131072:e.length,o="string"==typeof e?this._stringDecoder.decode(e.substring(r,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(r,a),this._parseBuffer);if(s=this._parser.parse(this._parseBuffer,o))return this._preserveStack(n,i,o,r),this._logSlowResolvingAsync(s),s}else if(!o){let r="string"==typeof e?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(s=this._parser.parse(this._parseBuffer,r))return this._preserveStack(n,i,r,0),this._logSlowResolvingAsync(s),s}(this._activeBuffer.x!==n||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let l=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(l,this._bufferService.rows-1)})}print(e,r,s){let n,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,l=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,d=this._coreService.modes.insertMode,u=this._curAttrData,h=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&s-r>0&&2===h.getWidth(this._activeBuffer.x-1)&&h.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=r;p<s;++p){if((n=e[p])<127&&a){let e=a[String.fromCharCode(n)];e&&(n=e.charCodeAt(0))}let r=this._unicodeService.charProperties(n,f);i=wW.extractWidth(r);let s=wW.extractShouldJoin(r),m=s?wW.extractWidth(f):0;if(f=r,o&&this._onA11yChar.fire(g8(n)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>l){if(c){let e=h,r=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),h=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&h instanceof wf&&h.copyCellsFrom(e,r,0,m,!1);r<l;)e.setCellFromCodepoint(r++,0,1,u)}else if(this._activeBuffer.x=l-1,2===i)continue}if(s&&this._activeBuffer.x){let e=h.getWidth(this._activeBuffer.x-1)?1:2;h.addCodepointToCell(this._activeBuffer.x-e,n,i);for(let e=i-m;--e>=0;)h.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(d&&(h.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),2===h.getWidth(l-1)&&h.setCellFromCodepoint(l-1,0,1,u)),h.setCellFromCodepoint(this._activeBuffer.x++,n,i,u),i>0)for(;--i;)h.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<l&&s-r>0&&0===h.getWidth(this._activeBuffer.x)&&!h.hasContent(this._activeBuffer.x)&&h.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,r){return"t"!==e.final||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,r):this._parser.registerCsiHandler(e,e=>!w7(e.params[0],this._optionsService.rawOptions.windowOptions)||r(e))}registerDcsHandler(e,r){return this._parser.registerDcsHandler(e,new wZ(r))}registerEscHandler(e,r){return this._parser.registerEscHandler(e,r)}registerOscHandler(e,r){return this._parser.registerOscHandler(e,new wX(r))}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(0===this._activeBuffer.x&&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,r){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+r):(this._activeBuffer.x=e,this._activeBuffer.y=r),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,r){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+r)}cursorUp(e){let r=this._activeBuffer.y-this._activeBuffer.scrollTop;return r>=0?this._moveCursor(0,-Math.min(r,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let r=this._activeBuffer.scrollBottom-this._activeBuffer.y;return r>=0?this._moveCursor(0,Math.min(r,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 r=e.params[0];return 0===r?delete this._activeBuffer.tabs[this._activeBuffer.x]:3===r&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let r=e.params[0]||1;for(;r--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let r=e.params[0]||1;for(;r--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let r=e.params[0];return 1===r&&(this._curAttrData.bg|=0x20000000),(2===r||0===r)&&(this._curAttrData.bg&=-0x20000001),!0}_eraseInBufferLine(e,r,s,n=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(r,s,this._activeBuffer.getNullCell(this._eraseAttrData()),i),n&&(a.isWrapped=!1)}_resetBufferLine(e,r=!1){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s&&(s.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),r),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),s.isWrapped=!1)}eraseInDisplay(e,r=!1){let s;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(s=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s),this._eraseInBufferLine(s++,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,r);s<this._bufferService.rows;s++)this._resetBufferLine(s,r);this._dirtyRowTracker.markDirty(s);break;case 1:for(s=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s),this._eraseInBufferLine(s,0,this._activeBuffer.x+1,!0,r),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(s+1).isWrapped=!1);s--;)this._resetBufferLine(s,r);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(s=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,s-1);s--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+s)?.getTrimmedLength(););for(;s>=0;s--)this._bufferService.scroll(this._eraseAttrData())}else{for(s=this._bufferService.rows,this._dirtyRowTracker.markDirty(s-1);s--;)this._resetBufferLine(s,r);this._dirtyRowTracker.markDirty(0)}break;case 3:let n=this._activeBuffer.lines.length-this._bufferService.rows;n>0&&(this._activeBuffer.lines.trimStart(n),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-n,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-n,0),this._onScroll.fire(0))}return!0}eraseInLine(e,r=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,r);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,r);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,r)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let r=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let s=this._activeBuffer.ybase+this._activeBuffer.y,n=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-n+1;for(;r--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(s,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 r=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let s=this._activeBuffer.ybase+this._activeBuffer.y,n;for(n=this._bufferService.rows-1-this._activeBuffer.scrollBottom,n=this._bufferService.rows-1+this._activeBuffer.ybase-n;r--;)this._activeBuffer.lines.splice(s,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}insertChars(e){this._restrictCursor();let r=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return r&&(r.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 r=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return r&&(r.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let r=e.params[0]||1;for(;r--;)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 r=e.params[0]||1;for(;r--;)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(wu));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 r=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s.deleteCells(0,r,this._activeBuffer.getNullCell(this._eraseAttrData())),s.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 r=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s.insertCells(0,r,this._activeBuffer.getNullCell(this._eraseAttrData())),s.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 r=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s.insertCells(this._activeBuffer.x,r,this._activeBuffer.getNullCell(this._eraseAttrData())),s.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 r=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s.deleteCells(this._activeBuffer.x,r,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let r=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return r&&(r.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 r=this._parser.precedingJoinState;if(!r)return!0;let s=e.params[0]||1,n=wW.extractWidth(r),i=this._activeBuffer.x-n,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*s),l=0;for(let e=0;e<a.length;){let r=a.codePointAt(e)||0;o[l++]=r,e+=r>65535?2:1}let c=l;for(let e=1;e<s;++e)o.copyWithin(c,0,l),c+=l;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(yG.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(yG.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(yG.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(yG.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(yG.ESC+"[>83;40003;0c")),!0}_is(e){return 0===(this._optionsService.rawOptions.termName+"").indexOf(e)}setMode(e){for(let r=0;r<e.length;r++)switch(e.params[r]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let r=0;r<e.length;r++)switch(e.params[r]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,wx),this._charsetService.setgCharset(1,wx),this._charsetService.setgCharset(2,wx),this._charsetService.setgCharset(3,wx);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}return!0}resetMode(e){for(let r=0;r<e.length;r++)switch(e.params[r]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let r=0;r<e.length;r++)switch(e.params[r]){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:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),1049===e.params[r]&&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)}return!0}requestMode(e,r){let s,n,i,a;(n=s||={})[n.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",n[n.SET=1]="SET",n[n.RESET=2]="RESET",n[n.PERMANENTLY_SET=3]="PERMANENTLY_SET",n[n.PERMANENTLY_RESET=4]="PERMANENTLY_RESET";let o=this._coreService.decPrivateModes,{activeProtocol:l,activeEncoding:c}=this._coreMouseService,d=this._coreService,{buffers:u,cols:h}=this._bufferService,{active:f,alt:p}=u,m=this._optionsService.rawOptions,g=e=>e?1:2,x=e.params[0];return i=x,a=r?2===x?4:4===x?g(d.modes.insertMode):12===x?3:20===x?g(m.convertEol):0:1===x?g(o.applicationCursorKeys):3===x?m.windowOptions.setWinLines?80===h?2:+(132===h):0:6===x?g(o.origin):7===x?g(o.wraparound):8===x?3:9===x?g("X10"===l):12===x?g(m.cursorBlink):25===x?g(!d.isCursorHidden):45===x?g(o.reverseWraparound):66===x?g(o.applicationKeypad):67===x?4:1e3===x?g("VT200"===l):1002===x?g("DRAG"===l):1003===x?g("ANY"===l):1004===x?g(o.sendFocus):1005===x?4:1006===x?g("SGR"===c):1015===x?4:1016===x?g("SGR_PIXELS"===c):1048===x?1:47===x||1047===x||1049===x?g(f===p):2004===x?g(o.bracketedPasteMode):2026===x?g(o.synchronizedOutput):0,d.triggerDataEvent(`${yG.ESC}[${r?"":"?"}${i};${a}$y`),!0}_updateAttrColor(e,r,s,n,i){return 2===r?(e|=0x3000000,e&=-0x1000000,e|=xr.fromColorRGB([s,n,i])):5===r&&(e&=-0x3000100,e|=0x2000000|255&s),e}_extractColor(e,r,s){let n=[0,0,-1,0,0,0],i=0,a=0;do{if(n[a+i]=e.params[r+a],e.hasSubParams(r+a)){let s=e.getSubParams(r+a),o=0;do 5===n[1]&&(i=1),n[a+o+1+i]=s[o];while(++o<s.length&&o+a+1+i<n.length)break}if(5===n[1]&&a+i>=2||2===n[1]&&a+i>=5)break;n[1]&&(i=1)}while(++a+r<e.length&&a+i<n.length)for(let e=2;e<n.length;++e)-1===n[e]&&(n[e]=0);switch(n[0]){case 38:s.fg=this._updateAttrColor(s.fg,n[1],n[3],n[4],n[5]);break;case 48:s.bg=this._updateAttrColor(s.bg,n[1],n[3],n[4],n[5]);break;case 58:s.extended=s.extended.clone(),s.extended.underlineColor=this._updateAttrColor(s.extended.underlineColor,n[1],n[3],n[4],n[5])}return a}_processUnderline(e,r){r.extended=r.extended.clone(),(!~e||e>5)&&(e=1),r.extended.underlineStyle=e,r.fg|=0x10000000,0===e&&(r.fg&=-0x10000001),r.updateExtended()}_processSGR0(e){e.fg=wu.fg,e.bg=wu.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-0x4000000,e.updateExtended()}charAttributes(e){if(1===e.length&&0===e.params[0])return this._processSGR0(this._curAttrData),!0;let r=e.length,s,n=this._curAttrData;for(let i=0;i<r;i++)(s=e.params[i])>=30&&s<=37?(n.fg&=-0x3000100,n.fg|=0x1000000|s-30):s>=40&&s<=47?(n.bg&=-0x3000100,n.bg|=0x1000000|s-40):s>=90&&s<=97?(n.fg&=-0x3000100,n.fg|=0x1000000|s-90|8):s>=100&&s<=107?(n.bg&=-0x3000100,n.bg|=0x1000000|s-100|8):0===s?this._processSGR0(n):1===s?n.fg|=0x8000000:3===s?n.bg|=0x4000000:4===s?(n.fg|=0x10000000,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,n)):5===s?n.fg|=0x20000000:7===s?n.fg|=0x4000000:8===s?n.fg|=0x40000000:9===s?n.fg|=0x80000000:2===s?n.bg|=0x8000000:21===s?this._processUnderline(2,n):22===s?(n.fg&=-0x8000001,n.bg&=-0x8000001):23===s?n.bg&=-0x4000001:24===s?(n.fg&=-0x10000001,this._processUnderline(0,n)):25===s?n.fg&=-0x20000001:27===s?n.fg&=-0x4000001:28===s?n.fg&=-0x40000001:29===s?n.fg&=0x7fffffff:39===s?(n.fg&=-0x4000000,n.fg|=0xffffff&wu.fg):49===s?(n.bg&=-0x4000000,n.bg|=0xffffff&wu.bg):38===s||48===s||58===s?i+=this._extractColor(e,i,n):53===s?n.bg|=0x40000000:55===s?n.bg&=-0x40000001:59===s?(n.extended=n.extended.clone(),n.extended.underlineColor=-1,n.updateExtended()):100===s?(n.fg&=-0x4000000,n.fg|=0xffffff&wu.fg,n.bg&=-0x4000000,n.bg|=0xffffff&wu.bg):this._logService.debug("Unknown SGR attribute: %d.",s);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${yG.ESC}[0n`);break;case 6:let r=this._activeBuffer.y+1,s=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${yG.ESC}[${r};${s}R`)}return!0}deviceStatusPrivate(e){if(6===e.params[0]){let e=this._activeBuffer.y+1,r=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${yG.ESC}[?${e};${r}R`)}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=wu.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 r=0===e.length?1:e.params[0];if(0===r)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(r){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"}this._coreService.decPrivateModes.cursorBlink=r%2==1}return!0}setScrollRegion(e){let r=e.params[0]||1,s;return(e.length<2||(s=e.params[1])>this._bufferService.rows||0===s)&&(s=this._bufferService.rows),s>r&&(this._activeBuffer.scrollTop=r-1,this._activeBuffer.scrollBottom=s-1,this._setCursor(0,0)),!0}windowOptions(e){if(!w7(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let r=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:2!==r&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${yG.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(0===r||2===r)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),(0===r||1===r)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:(0===r||2===r)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(0===r||1===r)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}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 r=[],s=e.split(";");for(;s.length>1;){let e=s.shift(),n=s.shift();if(/^\d+$/.exec(e)){let s=parseInt(e);if(_t(s))if("?"===n)r.push({type:0,index:s});else{let e=w3(n);e&&r.push({type:1,index:s,color:e})}}}return r.length&&this._onColor.fire(r),!0}setHyperlink(e){let r=e.indexOf(";");if(-1===r)return!0;let s=e.slice(0,r).trim(),n=e.slice(r+1);return n?this._createHyperlink(s,n):!s.trim()&&this._finishHyperlink()}_createHyperlink(e,r){this._getCurrentLinkId()&&this._finishHyperlink();let s=e.split(":"),n,i=s.findIndex(e=>e.startsWith("id="));return -1!==i&&(n=s[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:n,uri:r}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,r){let s=e.split(";");for(let e=0;e<s.length&&!(r>=this._specialColors.length);++e,++r)if("?"===s[e])this._onColor.fire([{type:0,index:this._specialColors[r]}]);else{let n=w3(s[e]);n&&this._onColor.fire([{type:1,index:this._specialColors[r],color:n}])}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 r=[],s=e.split(";");for(let e=0;e<s.length;++e)if(/^\d+$/.exec(s[e])){let n=parseInt(s[e]);_t(n)&&r.push({type:2,index:n})}return r.length&&this._onColor.fire(r),!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,wx),!0}selectCharset(e){return 2!==e.length?this.selectDefaultCharset():"/"===e[0]||this._charsetService.setgCharset(w6[e[0]],wg[e[1]]||wx),!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=wu.clone(),this._eraseAttrDataInternal=wu.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-0x4000000,this._eraseAttrDataInternal.bg|=0x3ffffff&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new xn;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let r=0;r<this._bufferService.rows;++r){let s=this._activeBuffer.ybase+this._activeBuffer.y+r,n=this._activeBuffer.lines.get(s);n&&(n.fill(e),n.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,r){let s=e=>(this._coreService.triggerDataEvent(`${yG.ESC}${e}${yG.ESC}\\`),!0),n=this._bufferService.buffer,i=this._optionsService.rawOptions;return s('"q'===e?`P1$r${+!!this._curAttrData.isProtected()}"q`:'"p'===e?'P1$r61;1"p':"r"===e?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:"m"===e?"P1$r0m":" q"===e?`P1$r${({block:2,underline:4,bar:6})[i.cursorStyle]-!!i.cursorBlink} q`:"P0$r")}markRangeDirty(e,r){this._dirtyRowTracker.markRangeDirty(e,r)}},_e=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,r){e>r&&(w8=e,e=r,r=w8),e<this.start&&(this.start=e),r>this.end&&(this.end=r)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function _t(e){return 0<=e&&e<256}_e=g1([g2(0,xc)],_e);var _r=class extends xW{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 va),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,r){let s;if(void 0!==r&&this._syncCalls>r){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,!this._isSyncWriting){for(this._isSyncWriting=!0;s=this._writeBuffer.shift();){this._action(s);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=0x7fffffff,this._isSyncWriting=!1,this._syncCalls=0}}write(e,r){if(this._pendingData>5e7)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(r),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(r)}_innerWrite(e=0,r=!0){let s=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],n=this._action(e,r);if(n){let e=e=>performance.now()-s>=12?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(s,e);n.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e);return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-s>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(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()}},_s=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let r=this._bufferService.buffer;if(void 0===e.id){let s=r.addMarker(r.ybase+r.y),n={data:e,id:this._nextId++,lines:[s]};return s.onDispose(()=>this._removeMarkerFromLink(n,s)),this._dataByLinkId.set(n.id,n),n.id}let s=this._getEntryIdKey(e),n=this._entriesWithId.get(s);if(n)return this.addLineToLink(n.id,r.ybase+r.y),n.id;let i=r.addMarker(r.ybase+r.y),a={id:this._nextId++,key:this._getEntryIdKey(e),data:e,lines:[i]};return i.onDispose(()=>this._removeMarkerFromLink(a,i)),this._entriesWithId.set(a.key,a),this._dataByLinkId.set(a.id,a),a.id}addLineToLink(e,r){let s=this._dataByLinkId.get(e);if(s&&s.lines.every(e=>e.line!==r)){let e=this._bufferService.buffer.addMarker(r);s.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(s,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,r){let s=e.lines.indexOf(r);-1!==s&&(e.lines.splice(s,1),0===e.lines.length&&(void 0!==e.data.id&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};_s=g1([g2(0,xc)],_s);var _n=!1,_i=class extends xW{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new xH),this._onBinary=this._register(new va),this.onBinary=this._onBinary.event,this._onData=this._register(new va),this.onData=this._onData.event,this._onLineFeed=this._register(new va),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new va),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new va),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new va),this._instantiationService=new wo,this.optionsService=this._register(new wS(e)),this._instantiationService.setService(xm,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(wb)),this._instantiationService.setService(xc,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(wc)),this._instantiationService.setService(xp,this._logService),this.coreService=this._register(this._instantiationService.createInstance(wN)),this._instantiationService.setService(xu,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(wA)),this._instantiationService.setService(xd,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(wW)),this._instantiationService.setService(xx,this.unicodeService),this._charsetService=this._instantiationService.createInstance(wH),this._instantiationService.setService(xh,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(_s),this._instantiationService.setService(xg,this._oscLinkService),this._inputHandler=this._register(new w9(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(x9.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(x9.forward(this._bufferService.onResize,this._onResize)),this._register(x9.forward(this.coreService.onData,this._onData)),this._register(x9.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 _r((e,r)=>this._inputHandler.parse(e,r))),this._register(x9.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new va),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 r in e)this.optionsService.options[r]=e[r]}write(e,r){this._writeBuffer.write(e,r)}writeSync(e,r){this._logService.logLevel<=3&&!_n&&(this._logService.warn("writeSync is unreliable and will be removed soon."),_n=!0),this._writeBuffer.writeSync(e,r)}input(e,r=!0){this.coreService.triggerDataEvent(e,r)}resize(e,r){isNaN(e)||isNaN(r)||(e=Math.max(e,2),r=Math.max(r,1),this._bufferService.resize(e,r))}scroll(e,r=!1){this._bufferService.scroll(e,r)}scrollLines(e,r){this._bufferService.scrollLines(e,r)}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 r=e-this._bufferService.buffer.ydisp;0!==r&&this.scrollLines(r)}registerEscHandler(e,r){return this._inputHandler.registerEscHandler(e,r)}registerDcsHandler(e,r){return this._inputHandler.registerDcsHandler(e,r)}registerCsiHandler(e,r){return this._inputHandler.registerCsiHandler(e,r)}registerOscHandler(e,r){return this._inputHandler.registerOscHandler(e,r)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,r=this.optionsService.rawOptions.windowsPty;r&&void 0!==r.buildNumber&&void 0!==r.buildNumber?e="conpty"===r.backend&&r.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(wU.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(wU(this._bufferService),!1))),this._windowsWrappingHeuristics.value=xB(()=>{for(let r of e)r.dispose()})}}},_a={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:["'",'"']},_o=0,_l=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new bX,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new bX,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(),0===this._insertedValues.length&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,r)=>this._getKey(e)-this._getKey(r)),r=0,s=0,n=Array(this._array.length+this._insertedValues.length);for(let i=0;i<n.length;i++)s>=this._array.length||this._getKey(e[r])<=this._getKey(this._array[s])?(n[i]=e[r],r++):n[i]=this._array[s++];this._array=n,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),0===this._array.length)return!1;let r=this._getKey(e);if(void 0===r||-1===(_o=this._search(r))||this._getKey(this._array[_o])!==r)return!1;do if(this._array[_o]===e)return 0===this._deletedIndices.length&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(_o),!0;while(++_o<this._array.length&&this._getKey(this._array[_o])===r)return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,r)=>e-r),r=0,s=Array(this._array.length-e.length),n=0;for(let i=0;i<this._array.length;i++)e[r]===i?r++:s[n++]=this._array[i];this._array=s,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),0!==this._array.length&&!((_o=this._search(e))<0||_o>=this._array.length)&&this._getKey(this._array[_o])===e)do yield this._array[_o];while(++_o<this._array.length&&this._getKey(this._array[_o])===e)}forEachByKey(e,r){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),0!==this._array.length&&!((_o=this._search(e))<0||_o>=this._array.length)&&this._getKey(this._array[_o])===e)do r(this._array[_o]);while(++_o<this._array.length&&this._getKey(this._array[_o])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let r=0,s=this._array.length-1;for(;s>=r;){let n=r+s>>1,i=this._getKey(this._array[n]);if(i>e)s=n-1;else if(i<e)r=n+1;else{for(;n>0&&this._getKey(this._array[n-1])===e;)n--;return n}}return r}},_c=0,_d=0,_u=class extends xW{constructor(){super(),this._decorations=new _l(e=>e?.marker.line),this._onDecorationRegistered=this._register(new va),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new va),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(xB(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let r=new _h(e);if(r){let e=r.marker.onDispose(()=>r.dispose()),s=r.onDispose(()=>{s.dispose(),r&&(this._decorations.delete(r)&&this._onDecorationRemoved.fire(r),e.dispose())});this._decorations.insert(r),this._onDecorationRegistered.fire(r)}return r}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,r,s){let n=0,i=0;for(let a of this._decorations.getKeyIterator(r))i=(n=a.options.x??0)+(a.options.width??1),e>=n&&e<i&&(!s||(a.options.layer??"bottom")===s)&&(yield a)}forEachDecorationAtCell(e,r,s,n){this._decorations.forEachByKey(r,r=>{_d=(_c=r.options.x??0)+(r.options.width??1),e>=_c&&e<_d&&(!s||(r.options.layer??"bottom")===s)&&n(r)})}},_h=class extends x${constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new va),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new va),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 null===this._cachedBg&&(this.options.backgroundColor?this._cachedBg=wF.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return null===this._cachedFg&&(this.options.foregroundColor?this._cachedFg=wF.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},_f=class{constructor(e,r=1e3){this._renderCallback=e,this._debounceThresholdMS=r,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,r,s){this._rowCount=s,e=void 0!==e?e:0,r=void 0!==r?r:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,r):r;let n=performance.now();if(n-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=n,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=n-this._lastRefreshMs,r=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},r)}}_innerRefresh(){if(void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return;let e=Math.max(this._rowStart,0),r=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,r)}},_p=class extends xW{constructor(e,r,s,n){super(),this._terminal=e,this._coreBrowserService=s,this._renderService=n,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 _f(this._renderRows.bind(this))),!this._terminal.element)throw Error("Cannot enable accessibility before Terminal.open");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(`
26
26
  `))),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(yd(i,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(xB(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let r=0;r<e;r++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
27
27
  `&&(this._liveRegionLineCount++,21===this._liveRegionLineCount&&(this._liveRegion.textContent+=g3)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,r){this._liveRegionDebouncer.refresh(e,r,this._terminal.rows)}_renderRows(e,r){let s=this._terminal.buffer,n=s.lines.length.toString();for(let i=e;i<=r;i++){let e=s.lines.get(s.ydisp+i),r=[],a=e?.translateToString(!0,void 0,void 0,r)||"",o=(s.ydisp+i+1).toString(),l=this._rowElements[i];l&&(0===a.length?(l.textContent=" ",this._rowColumns.set(l,[0,1])):(l.textContent=a,this._rowColumns.set(l,r)),l.setAttribute("aria-posinset",o),l.setAttribute("aria-setsize",n),this._alignRowWidth(l))}this._announceCharacters()}_announceCharacters(){0!==this._charsToAnnounce.length&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,r){let s,n,i=e.target,a=this._rowElements[0===r?1:this._rowElements.length-2];if(i.getAttribute("aria-posinset")!==(0===r?"1":`${this._terminal.buffer.lines.length}`)&&e.relatedTarget===a){if(0===r?(s=i,n=this._rowElements.pop(),this._rowContainer.removeChild(n)):(s=this._rowElements.shift(),n=i,this._rowContainer.removeChild(s)),s.removeEventListener("focus",this._topBoundaryFocusListener),n.removeEventListener("focus",this._bottomBoundaryFocusListener),0===r){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(0===r?-1:1),this._rowElements[0===r?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}}_handleSelectionChange(){if(0===this._rowElements.length)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)return void console.error("anchorNode and/or focusNode are null");let r={node:e.anchorNode,offset:e.anchorOffset},s={node:e.focusNode,offset:e.focusOffset};if((r.node.compareDocumentPosition(s.node)&Node.DOCUMENT_POSITION_PRECEDING||r.node===s.node&&r.offset>s.offset)&&([r,s]=[s,r]),r.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(r={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(r.node))return;let n=this._rowElements.slice(-1)[0];if(s.node.compareDocumentPosition(n)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(s={node:n,offset:n.textContent?.length??0}),!this._rowContainer.contains(s.node))return;let i=({node:e,offset:r})=>{let s=e instanceof Text?e.parentNode:e,n=parseInt(s?.getAttribute("aria-posinset"),10)-1;if(isNaN(n))return console.warn("row is invalid. Race condition?"),null;let i=this._rowColumns.get(s);if(!i)return console.warn("columns is null. Race condition?"),null;let a=r<i.length?i[r]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++n,a=0),{row:n,column:a}},a=i(r),o=i(s);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 r=e.getBoundingClientRect().width,s=this._rowColumns.get(e)?.slice(-1)?.[0];if(!s)return;let n=s*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${n/r})`}};_p=g1([g2(1,xf),g2(2,xw),g2(3,xS)],_p);var _m=class extends xW{constructor(e,r,s,n,i){super(),this._element=e,this._mouseService=r,this._renderService=s,this._bufferService=n,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new va),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new va),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(xB(()=>{xO(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(yd(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(yd(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(yd(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(yd(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let r=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!r)return;this._isMouseOut=!1;let s=e.composedPath();for(let e=0;e<s.length;e++){let r=s[e];if(r.classList.contains("xterm"))break;if(r.classList.contains("xterm-hover"))return}this._lastBufferCell&&r.x===this._lastBufferCell.x&&r.y===this._lastBufferCell.y||(this._handleHover(r),this._lastBufferCell=r)}_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,r){this._activeProviderReplies&&r||(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let s=!1;for(let[n,i]of this._linkProviderService.linkProviders.entries())r?this._activeProviderReplies?.get(n)&&(s=this._checkLinkProviderResult(n,e,s)):i.provideLinks(e.y,r=>{if(this._isMouseOut)return;let i=r?.map(e=>({link:e}));this._activeProviderReplies?.set(n,i),s=this._checkLinkProviderResult(n,e,s),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,r){let s=new Set;for(let n=0;n<r.size;n++){let i=r.get(n);if(i)for(let r=0;r<i.length;r++){let n=i[r],a=n.link.range.start.y<e?0:n.link.range.start.x,o=n.link.range.end.y>e?this._bufferService.cols:n.link.range.end.x;for(let e=a;e<=o;e++){if(s.has(e)){i.splice(r--,1);break}s.add(e)}}}}_checkLinkProviderResult(e,r,s){if(!this._activeProviderReplies)return s;let n=this._activeProviderReplies.get(e),i=!1;for(let r=0;r<e;r++)(!this._activeProviderReplies.has(r)||this._activeProviderReplies.get(r))&&(i=!0);if(!i&&n){let e=n.find(e=>this._linkAtPosition(e.link,r));e&&(s=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!s)for(let e=0;e<this._activeProviderReplies.size;e++){let n=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,r));if(n){s=!0,this._handleNewLink(n);break}}return s}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){var r,s;if(!this._currentLink)return;let n=this._positionFromMouseEvent(e,this._element,this._mouseService);n&&this._mouseDownLink&&(r=this._mouseDownLink.link,s=this._currentLink.link,r.text===s.text&&r.range.start.x===s.range.start.x&&r.range.start.y===s.range.start.y&&r.range.end.x===s.range.end.x&&r.range.end.y===s.range.end.y)&&this._linkAtPosition(this._currentLink.link,n)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,r){this._currentLink&&this._lastMouseEvent&&(!e||!r||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=r)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,xO(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let r=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);r&&this._linkAtPosition(e.link,r)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:void 0===e.link.decorations||e.link.decorations.underline,pointerCursor:void 0===e.link.decorations||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:r=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==r&&(this._currentLink.state.decorations.underline=r,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,r))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let r=0===e.start?0:e.start+1+this._bufferService.buffer.ydisp,s=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=r&&this._currentLink.link.range.end.y<=s&&(this._clearCurrentLink(r,s),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,r,s){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(r,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),r.hover&&r.hover(s,r.text)}_fireUnderlineEvent(e,r){let s=e.range,n=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(s.start.x-1,s.start.y-n-1,s.end.x,s.end.y-n-1,void 0);(r?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,r,s){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(r,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),r.leave&&r.leave(s,r.text)}_linkAtPosition(e,r){let s=e.range.start.y*this._bufferService.cols+e.range.start.x,n=e.range.end.y*this._bufferService.cols+e.range.end.x,i=r.y*this._bufferService.cols+r.x;return s<=i&&i<=n}_positionFromMouseEvent(e,r,s){let n=s.getCoords(e,r,this._bufferService.cols,this._bufferService.rows);if(n)return{x:n[0],y:n[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,r,s,n,i){return{x1:e,y1:r,x2:s,y2:n,cols:this._bufferService.cols,fg:i}}};_m=g1([g2(1,x_),g2(2,xS),g2(3,xc),g2(4,xN)],_m);var _g=class extends _i{constructor(e={}){super(e),this._linkifier=this._register(new xH),this.browser=bD,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new xH),this._onCursorMove=this._register(new va),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new va),this.onKey=this._onKey.event,this._onRender=this._register(new va),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new va),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new va),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new va),this.onBell=this._onBell.event,this._onFocus=this._register(new va),this._onBlur=this._register(new va),this._onA11yCharEmitter=this._register(new va),this._onA11yTabEmitter=this._register(new va),this._onWillOpen=this._register(new va),this._setup(),this._decorationService=this._instantiationService.createInstance(_u),this._instantiationService.setService(xv,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(bk),this._instantiationService.setService(xN,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(xy)),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(x9.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(x9.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(x9.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(x9.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(xB(()=>{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 r of e){let e,s="";switch(r.index){case 256:e="foreground",s="10";break;case 257:e="background",s="11";break;case 258:e="cursor",s="12";break;default:e="ansi",s="4;"+r.index}switch(r.type){case 0:let n=wM.toColorRGB("ansi"===e?this._themeService.colors.ansi[r.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${yG.ESC}]${s};${function(e,r=16){let[s,n,i]=e;return`rgb:${w4(s,r)}/${w4(n,r)}/${w4(i,r)}`}(n)}${yZ.ST}`);break;case 1:if("ansi"===e)this._themeService.modifyColors(e=>e.ansi[r.index]=yQ.toColor(...r.color));else{let s=e;this._themeService.modifyColors(e=>e[s]=yQ.toColor(...r.color))}break;case 2:this._themeService.restoreColor(r.index)}}}_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(_p,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(yG.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(yG.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,r=this.buffer.lines.get(e);if(!r)return;let s=Math.min(this.buffer.x,this.cols-1),n=this._renderService.dimensions.css.cell.height,i=r.getWidth(s),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,l=s*this._renderService.dimensions.css.cell.width;this.textarea.style.left=l+"px",this.textarea.style.top=o+"px",this.textarea.style.width=a+"px",this.textarea.style.height=n+"px",this.textarea.style.lineHeight=n+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(yd(this.element,"copy",e=>{var r;this.hasSelection()&&(r=this._selectionService,e.clipboardData&&e.clipboardData.setData("text/plain",r.selectionText),e.preventDefault())}));let e=e=>{var r,s,n;return r=this.textarea,s=this.coreService,n=this.optionsService,void(e.stopPropagation(),e.clipboardData&&g4(e.clipboardData.getData("text/plain"),r,s,n))};this._register(yd(this.textarea,"paste",e)),this._register(yd(this.element,"paste",e)),bF?this._register(yd(this.element,"mousedown",e=>{2===e.button&&g7(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(yd(this.element,"contextmenu",e=>{g7(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),bH&&this._register(yd(this.element,"auxclick",e=>{1===e.button&&g6(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(yd(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(yd(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(yd(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(yd(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(yd(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(yd(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(yd(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 r=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),r.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(yd(this.screenElement,"mousemove",e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),r.appendChild(this.screenElement);let s=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",g5),bU||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",()=>s.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(bS,this.textarea,e.ownerDocument.defaultView??window,this._document??"u">typeof window?window.document:null)),this._instantiationService.setService(xw,this._coreBrowserService),this._register(yd(this.textarea,"focus",e=>this._handleTextAreaFocus(e))),this._register(yd(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(by,this._document,this._helperContainer),this._instantiationService.setService(xb,this._charSizeService),this._themeService=this._instantiationService.createInstance(wn),this._instantiationService.setService(xC,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(bi),this._instantiationService.setService(xk,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(bG,this.rows,this.screenElement)),this._instantiationService.setService(xS,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(yU,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(bN),this._instantiationService.setService(x_,this._mouseService);let n=this._linkifier.value=this._register(this._instantiationService.createInstance(_m,this.screenElement));this.element.appendChild(r);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(yL,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(b6,this.element,this.screenElement,n)),this._instantiationService.setService(xj,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(x9.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(yO,this.screenElement)),this._register(yd(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(_p,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(yH,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(yH,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(bv,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,r=this.element;function s(r){let s,n,i=e._mouseService.getMouseReportCoords(r,e.screenElement);if(!i)return!1;switch(r.overrideType||r.type){case"mousemove":n=32,void 0===r.buttons?(s=3,void 0!==r.button&&(s=r.button<3?r.button:3)):s=1&r.buttons?0:4&r.buttons?1:2&r.buttons?2:3;break;case"mouseup":n=0,s=r.button<3?r.button:3;break;case"mousedown":n=1,s=r.button<3?r.button:3;break;case"wheel":if(e._customWheelEventHandler&&!1===e._customWheelEventHandler(r))return!1;let a=r.deltaY;if(0===a||0===e.coreMouseService.consumeWheelEvent(r,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr))return!1;n=a<0?0:1,s=4;break;default:return!1}return void 0!==n&&void 0!==s&&!(s>4)&&e.coreMouseService.triggerMouseEvent({col:i.col,row:i.row,x:i.x,y:i.y,button:s,action:n,ctrl:r.ctrlKey,alt:r.altKey,shift:r.shiftKey})}let n={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i=e=>(s(e),e.buttons||(this._document.removeEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.removeEventListener("mousemove",n.mousedrag)),this.cancel(e)),a=e=>(s(e),this.cancel(e,!0)),o=e=>{e.buttons&&s(e)},l=e=>{e.buttons||s(e)};this._register(this.coreMouseService.onProtocolChange(e=>{e?("debug"===this.optionsService.rawOptions.logLevel&&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()),8&e?n.mousemove||(r.addEventListener("mousemove",l),n.mousemove=l):(r.removeEventListener("mousemove",n.mousemove),n.mousemove=null),16&e?n.wheel||(r.addEventListener("wheel",a,{passive:!1}),n.wheel=a):(r.removeEventListener("wheel",n.wheel),n.wheel=null),2&e?n.mouseup||(n.mouseup=i):(this._document.removeEventListener("mouseup",n.mouseup),n.mouseup=null),4&e?n.mousedrag||(n.mousedrag=o):(this._document.removeEventListener("mousemove",n.mousedrag),n.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(yd(r,"mousedown",e=>{if(e.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(e)))return s(e),n.mouseup&&this._document.addEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.addEventListener("mousemove",n.mousedrag),this.cancel(e)})),this._register(yd(r,"wheel",r=>{if(!n.wheel){if(this._customWheelEventHandler&&!1===this._customWheelEventHandler(r))return!1;if(!this.buffer.hasScrollback){if(0===r.deltaY)return!1;if(0===e.coreMouseService.consumeWheelEvent(r,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr))return this.cancel(r,!0);let s=yG.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(r.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(s,!0),this.cancel(r,!0)}}},{passive:!1}))}refresh(e,r){this._renderService?.refreshRows(e,r)}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,r){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,r),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 r=e-this._bufferService.buffer.ydisp;0!==r&&this.scrollLines(r)}paste(e){g4(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 r=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),r}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}select(e,r,s){this._selectionService.setSelection(e,r,s)}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,r){this._selectionService?.selectLines(e,r)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;let r=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!r&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;r||"Dead"!==e.key&&"AltGraph"!==e.key||(this._unprocessedDeadKey=!0);let s=function(e,r,s,n){let i={type:0,cancel:!1,key:void 0},a=!!e.shiftKey|2*!!e.altKey|4*!!e.ctrlKey|8*!!e.metaKey;switch(e.keyCode){case 0:"UIKeyInputUpArrow"===e.key?r?i.key=yG.ESC+"OA":i.key=yG.ESC+"[A":"UIKeyInputLeftArrow"===e.key?r?i.key=yG.ESC+"OD":i.key=yG.ESC+"[D":"UIKeyInputRightArrow"===e.key?r?i.key=yG.ESC+"OC":i.key=yG.ESC+"[C":"UIKeyInputDownArrow"===e.key&&(r?i.key=yG.ESC+"OB":i.key=yG.ESC+"[B");break;case 8:i.key=e.ctrlKey?"\b":yG.DEL,e.altKey&&(i.key=yG.ESC+i.key);break;case 9:if(e.shiftKey){i.key=yG.ESC+"[Z";break}i.key=yG.HT,i.cancel=!0;break;case 13:i.key=e.altKey?yG.ESC+yG.CR:yG.CR,i.cancel=!0;break;case 27:i.key=yG.ESC,e.altKey&&(i.key=yG.ESC+yG.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;a?i.key=yG.ESC+"[1;"+(a+1)+"D":r?i.key=yG.ESC+"OD":i.key=yG.ESC+"[D";break;case 39:if(e.metaKey)break;a?i.key=yG.ESC+"[1;"+(a+1)+"C":r?i.key=yG.ESC+"OC":i.key=yG.ESC+"[C";break;case 38:if(e.metaKey)break;a?i.key=yG.ESC+"[1;"+(a+1)+"A":r?i.key=yG.ESC+"OA":i.key=yG.ESC+"[A";break;case 40:if(e.metaKey)break;a?i.key=yG.ESC+"[1;"+(a+1)+"B":r?i.key=yG.ESC+"OB":i.key=yG.ESC+"[B";break;case 45:e.shiftKey||e.ctrlKey||(i.key=yG.ESC+"[2~");break;case 46:a?i.key=yG.ESC+"[3;"+(a+1)+"~":i.key=yG.ESC+"[3~";break;case 36:a?i.key=yG.ESC+"[1;"+(a+1)+"H":r?i.key=yG.ESC+"OH":i.key=yG.ESC+"[H";break;case 35:a?i.key=yG.ESC+"[1;"+(a+1)+"F":r?i.key=yG.ESC+"OF":i.key=yG.ESC+"[F";break;case 33:e.shiftKey?i.type=2:e.ctrlKey?i.key=yG.ESC+"[5;"+(a+1)+"~":i.key=yG.ESC+"[5~";break;case 34:e.shiftKey?i.type=3:e.ctrlKey?i.key=yG.ESC+"[6;"+(a+1)+"~":i.key=yG.ESC+"[6~";break;case 112:a?i.key=yG.ESC+"[1;"+(a+1)+"P":i.key=yG.ESC+"OP";break;case 113:a?i.key=yG.ESC+"[1;"+(a+1)+"Q":i.key=yG.ESC+"OQ";break;case 114:a?i.key=yG.ESC+"[1;"+(a+1)+"R":i.key=yG.ESC+"OR";break;case 115:a?i.key=yG.ESC+"[1;"+(a+1)+"S":i.key=yG.ESC+"OS";break;case 116:a?i.key=yG.ESC+"[15;"+(a+1)+"~":i.key=yG.ESC+"[15~";break;case 117:a?i.key=yG.ESC+"[17;"+(a+1)+"~":i.key=yG.ESC+"[17~";break;case 118:a?i.key=yG.ESC+"[18;"+(a+1)+"~":i.key=yG.ESC+"[18~";break;case 119:a?i.key=yG.ESC+"[19;"+(a+1)+"~":i.key=yG.ESC+"[19~";break;case 120:a?i.key=yG.ESC+"[20;"+(a+1)+"~":i.key=yG.ESC+"[20~";break;case 121:a?i.key=yG.ESC+"[21;"+(a+1)+"~":i.key=yG.ESC+"[21~";break;case 122:a?i.key=yG.ESC+"[23;"+(a+1)+"~":i.key=yG.ESC+"[23~";break;case 123:a?i.key=yG.ESC+"[24;"+(a+1)+"~":i.key=yG.ESC+"[24~";break;default:if(!e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)if((!s||n)&&e.altKey&&!e.metaKey){let r=_a[e.keyCode]?.[+!!e.shiftKey];if(r)i.key=yG.ESC+r;else if(e.keyCode>=65&&e.keyCode<=90){let r=String.fromCharCode(e.ctrlKey?e.keyCode-64:e.keyCode+32);e.shiftKey&&(r=r.toUpperCase()),i.key=yG.ESC+r}else if(32===e.keyCode)i.key=yG.ESC+(e.ctrlKey?yG.NUL:" ");else if("Dead"===e.key&&e.code.startsWith("Key")){let r=e.code.slice(3,4);e.shiftKey||(r=r.toLowerCase()),i.key=yG.ESC+r,i.cancel=!0}}else!s||e.altKey||e.ctrlKey||e.shiftKey||!e.metaKey?!e.key||e.ctrlKey||e.altKey||e.metaKey||!(e.keyCode>=48)||1!==e.key.length?e.key&&e.ctrlKey&&("_"===e.key&&(i.key=yG.US),"@"===e.key&&(i.key=yG.NUL)):i.key=e.key:65===e.keyCode&&(i.type=1);else e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):32===e.keyCode?i.key=yG.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):56===e.keyCode?i.key=yG.DEL:219===e.keyCode?i.key=yG.ESC:220===e.keyCode?i.key=yG.FS:221===e.keyCode&&(i.key=yG.GS)}return i}(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),3===s.type||2===s.type){let r=this.rows-1;return this.scrollLines(2===s.type?-r:r),this.cancel(e,!0)}return 1===s.type&&this.selectAll(),!!(this._isThirdLevelShift(this.browser,e)||(s.cancel&&this.cancel(e,!0),!s.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&1===e.key.length&&e.key.charCodeAt(0)>=65&&90>=e.key.charCodeAt(0))||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):((s.key===yG.ETX||s.key===yG.CR)&&(this.textarea.value=""),this._onKey.fire({key:s.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(s.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)?this.cancel(e,!0):void(this._keyDownHandled=!0))}_isThirdLevelShift(e,r){let s=e.isMac&&!this.options.macOptionIsMeta&&r.altKey&&!r.ctrlKey&&!r.metaKey||e.isWindows&&r.altKey&&r.ctrlKey&&!r.metaKey||e.isWindows&&r.getModifierState("AltGraph");return"keypress"===r.type?s:s&&(!r.keyCode||r.keyCode>47)}_keyUp(e){var r;this._keyDownSeen=!1,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e)||(16===(r=e).keyCode||17===r.keyCode||18===r.keyCode||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let r;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;if(this.cancel(e),e.charCode)r=e.charCode;else if(null===e.which||void 0===e.which)r=e.keyCode;else{if(0===e.which||0===e.charCode)return!1;r=e.which}return!!r&&(!e.altKey&&!e.ctrlKey&&!e.metaKey||!!this._isThirdLevelShift(this.browser,e))&&(r=String.fromCharCode(r),this._onKey.fire({key:r,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(r,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&"insertText"===e.inputType&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let r=e.data;return this.coreService.triggerDataEvent(r,!0),this.cancel(e),!0}return!1}resize(e,r){if(e===this.cols&&r===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,r)}_afterResize(e,r){this._charSizeService?.measure()}clear(){if(0!==this.buffer.ybase||0!==this.buffer.y){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(wu));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(yG.ESC+"[I"):this.coreService.triggerDataEvent(yG.ESC+"[O")}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let r=this._renderService.dimensions.css.canvas.width.toFixed(0),s=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${yG.ESC}[4;${s};${r}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),i=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${yG.ESC}[6;${i};${n}t`)}}cancel(e,r){if(!(!this.options.cancelEvents&&!r))return e.preventDefault(),e.stopPropagation(),!1}},_x=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,r){let s={instance:r,dispose:r.dispose,isDisposed:!1};this._addons.push(s),r.dispose=()=>this._wrappedAddonDispose(s),r.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let r=-1;for(let s=0;s<this._addons.length;s++)if(this._addons[s]===e){r=s;break}if(-1===r)throw Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(r,1)}},_v=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,r){if(!(e<0||e>=this._line.length))return r?(this._line.loadCell(e,r),r):this._line.loadCell(e,new xn)}translateToString(e,r,s){return this._line.translateToString(e,r,s)}},_y=class{constructor(e,r){this._buffer=e,this.type=r}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 r=this._buffer.lines.get(e);if(r)return new _v(r)}getNullCell(){return new xn}},_b=class extends xW{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new va),this.onBufferChange=this._onBufferChange.event,this._normal=new _y(this._core.buffers.normal,"normal"),this._alternate=new _y(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)}},_w=class{constructor(e){this._core=e}registerCsiHandler(e,r){return this._core.registerCsiHandler(e,e=>r(e.toArray()))}addCsiHandler(e,r){return this.registerCsiHandler(e,r)}registerDcsHandler(e,r){return this._core.registerDcsHandler(e,(e,s)=>r(e,s.toArray()))}addDcsHandler(e,r){return this.registerDcsHandler(e,r)}registerEscHandler(e,r){return this._core.registerEscHandler(e,r)}addEscHandler(e,r){return this.registerEscHandler(e,r)}registerOscHandler(e,r){return this._core.registerOscHandler(e,r)}addOscHandler(e,r){return this.registerOscHandler(e,r)}},__=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}},_S=["cols","rows"],_j=0,_k=class extends xW{constructor(e){super(),this._core=this._register(new _g(e)),this._addonManager=this._register(new _x),this._publicOptions={...this._core.options};let r=e=>this._core.options[e],s=(e,r)=>{this._checkReadonlyOptions(e),this._core.options[e]=r};for(let e in this._core.options){let n={get:r.bind(this,e),set:s.bind(this,e)};Object.defineProperty(this._publicOptions,e,n)}}_checkReadonlyOptions(e){if(_S.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||(this._parser=new _w(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new __(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._buffer=this._register(new _b(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,r="none";switch(this._core.coreMouseService.activeProtocol){case"X10":r="x10";break;case"VT200":r="vt200";break;case"DRAG":r="drag";break;case"ANY":r="any"}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:r,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 r in e)this._publicOptions[r]=e[r]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,r=!0){this._core.input(e,r)}resize(e,r){this._verifyIntegers(e,r),this._core.resize(e,r)}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,r,s){this._verifyIntegers(e,r,s),this._core.select(e,r,s)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,r){this._verifyIntegers(e,r),this._core.selectLines(e,r)}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,r){this._core.write(e,r)}writeln(e,r){this._core.write(e),this._core.write(`\r
28
- `,r)}paste(e){this._core.paste(e)}refresh(e,r){this._verifyIntegers(e,r),this._core.refresh(e,r)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return g5},set promptLabel(t){g5=t},get tooMuchOutput(){return g3},set tooMuchOutput(t){g3=t}}}_verifyIntegers(...e){for(_j of e)if(_j===1/0||isNaN(_j)||_j%1!=0)throw Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(_j of e)if(_j&&(_j===1/0||isNaN(_j)||_j%1!=0||_j<0))throw Error("This API only accepts positive integers")}},_C=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let r=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(r._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(0===e.css.cell.width||0===e.css.cell.height)return;let r=0===this._terminal.options.scrollback?0:this._terminal.options.overviewRuler?.width||14,s=window.getComputedStyle(this._terminal.element.parentElement),n=parseInt(s.getPropertyValue("height")),i=Math.max(0,parseInt(s.getPropertyValue("width"))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue("padding-top")),bottom:parseInt(a.getPropertyValue("padding-bottom")),right:parseInt(a.getPropertyValue("padding-right")),left:parseInt(a.getPropertyValue("padding-left"))},l=o.top+o.bottom;return{cols:Math.max(2,Math.floor((i-(o.right+o.left)-r)/e.css.cell.width)),rows:Math.max(1,Math.floor((n-l)/e.css.cell.height))}}},_N=class{constructor(e,r,s,n={}){this._terminal=e,this._regex=r,this._handler=s,this._options=n}provideLinks(e,r){let s=_E.computeLink(e,this._regex,this._terminal,this._handler);r(this._addCallbacks(s))}_addCallbacks(e){return e.map(e=>(e.leave=this._options.leave,e.hover=(r,s)=>{if(this._options.hover){let{range:n}=e;this._options.hover(r,s,n)}},e))}},_E=class e{static computeLink(r,s,n,i){let a=RegExp(s.source,(s.flags||"")+"g"),[o,l]=e._getWindowedLineStrings(r-1,n),c=o.join(""),d,u=[];for(;d=a.exec(c);){let r=d[0];if(!function(e){try{let r=new URL(e),s=r.password&&r.username?`${r.protocol}//${r.username}:${r.password}@${r.host}`:r.username?`${r.protocol}//${r.username}@${r.host}`:`${r.protocol}//${r.host}`;return e.toLocaleLowerCase().startsWith(s.toLocaleLowerCase())}catch{return!1}}(r))continue;let[s,a]=e._mapStrIdx(n,l,0,d.index),[o,c]=e._mapStrIdx(n,s,a,r.length);if(-1===s||-1===a||-1===o||-1===c)continue;let h={start:{x:a+1,y:s+1},end:{x:c,y:o+1}};u.push({range:h,text:r,activate:i})}return u}static _getWindowedLineStrings(e,r){let s,n=e,i=e,a=0,o="",l=[];if(s=r.buffer.active.getLine(e)){let e=s.translateToString(!0);if(s.isWrapped&&" "!==e[0]){for(a=0;(s=r.buffer.active.getLine(--n))&&a<2048&&(a+=(o=s.translateToString(!0)).length,l.push(o),!(!s.isWrapped||-1!==o.indexOf(" "))););l.reverse()}for(l.push(e),a=0;(s=r.buffer.active.getLine(++i))&&s.isWrapped&&a<2048&&(a+=(o=s.translateToString(!0)).length,l.push(o),-1===o.indexOf(" ")););}return[l,n]}static _mapStrIdx(e,r,s,n){let i=e.buffer.active,a=i.getNullCell(),o=s;for(;n;){let e=i.getLine(r);if(!e)return[-1,-1];for(let s=o;s<e.length;++s){e.getCell(s,a);let o=a.getChars();if(a.getWidth()&&(n-=o.length||1,s===e.length-1&&""===o)){let e=i.getLine(r+1);e&&e.isWrapped&&(e.getCell(0,a),2===a.getWidth()&&(n+=1))}if(n<0)return[r,s]}r++,o=0}return[r,o]}},_D=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function _R(e,r){let s=window.open();if(s){try{s.opener=null}catch{}s.location.href=r}else console.warn("Opening link blocked as opener could not be cleared")}var _T=class{constructor(e=_R,r={}){this._handler=e,this._options=r}activate(e){this._terminal=e;let r=this._options,s=r.urlRegex||_D;this._linkProvider=this._terminal.registerLinkProvider(new _N(this._terminal,s,this._handler,r))}dispose(){this._linkProvider?.dispose()}};let _A=(0,e_.default)("list-filter",[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]]),_I=(0,e_.default)("maximize-2",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]),_M=(0,e_.default)("minimize-2",[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]]);function _F(e,r){return 0===r.length?[...e]:e.filter(e=>(function(e,r){let s=e.toLowerCase();for(let e of r){let r=s.includes(e.pattern.toLowerCase());if(e.negate?r:!r)return!1}return!0})(e,r))}let _P=(0,e_.default)("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),_L=(0,e_.default)("eye-off",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);function _O({filters:e,inputOpen:r,onAdd:s,onRemove:n,onCloseInput:i,counts:a}){let o=(0,$.useRef)(null),[l,c]=(0,$.useState)(!1);return(0,$.useEffect)(()=>{r&&o.current?.focus()},[r]),(0,z.jsxs)(z.Fragment,{children:[e.map(e=>(0,z.jsxs)("span",{"data-testid":"terminal-filter-chip","data-negate":e.negate||void 0,className:(0,eb.cn)("flex h-6 max-w-48 items-center gap-1 rounded border pl-1.5 pr-0.5 font-mono text-[11px]","bg-zinc-900/80 backdrop-blur-sm",e.negate?"border-red-500/50 text-red-300":"border-sky-500/50 text-sky-200"),title:e.negate?`Hide lines containing "${e.pattern}"`:`Keep lines containing "${e.pattern}"`,children:[(0,z.jsx)("span",{className:"truncate",children:e.pattern}),(0,z.jsx)("button",{type:"button","aria-label":`Remove filter ${e.pattern}`,onClick:()=>n(e.id),className:"flex h-4 w-4 shrink-0 items-center justify-center rounded text-zinc-400 hover:bg-zinc-700 hover:text-zinc-100",children:(0,z.jsx)(t7,{className:"h-3 w-3"})})]},e.id)),r&&(0,z.jsxs)("span",{"data-testid":"terminal-filter-input-group",className:(0,eb.cn)("flex h-6 items-center overflow-hidden rounded border bg-zinc-900/90 backdrop-blur-sm",l?"border-red-500/60":"border-zinc-600 focus-within:border-sky-500/70"),children:[(0,z.jsx)("button",{type:"button","aria-label":l?"Hide mode: chip hides matching lines":"Keep mode: chip keeps matching lines","aria-pressed":l,title:"Toggle between keeping and hiding lines that match",onMouseDown:e=>e.preventDefault(),onClick:()=>c(e=>!e),className:(0,eb.cn)("flex h-full shrink-0 items-center border-r px-1.5",l?"border-red-500/40 bg-red-500/15 text-red-300 hover:bg-red-500/25":"border-zinc-700 text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200"),children:l?(0,z.jsx)(_L,{className:"h-3 w-3"}):(0,z.jsx)(_P,{className:"h-3 w-3"})}),(0,z.jsx)("input",{ref:o,type:"text","aria-label":"Add terminal filter",placeholder:l?"hide lines containing…":"keep lines containing…",spellCheck:!1,autoComplete:"off",onKeyDown:r=>{let a=r.currentTarget;if(!r.nativeEvent.isComposing&&229!==r.keyCode){if("Enter"===r.key){r.preventDefault();let e=function(e){let r=e.trim();if(!r)return null;if(r.startsWith("\\-")||r.startsWith("\\!"))return{pattern:r.slice(1),negate:!1};if(r.startsWith("-")||r.startsWith("!")){let e=r.slice(1).trim();return e?{pattern:e,negate:!0}:null}return{pattern:r,negate:!1}}(a.value);e&&(s(l?{...e,negate:!0}:e),a.value="");return}if("Escape"===r.key){r.preventDefault(),r.stopPropagation(),i();return}"Backspace"===r.key&&""===a.value&&e.length>0&&(r.preventDefault(),n(e[e.length-1].id))}},className:"h-full w-36 bg-transparent px-1.5 font-mono text-[11px] text-zinc-100 outline-none placeholder:text-zinc-500"})]}),a&&(0,z.jsxs)("span",{"data-testid":"terminal-filter-count",className:"select-none font-mono text-[11px] tabular-nums text-zinc-400",title:"matched / total lines",children:[a.matched.toLocaleString()," / ",a.total.toLocaleString()]})]})}function _B(e,r){let s=e.top-r.top-22-4;s<0&&(s=e.bottom-r.top+4);let n=Math.max(0,r.width-64-2);return{top:s,left:Math.min(Math.max(e.left-r.left,2),n)}}function _z({anchor:e,onCopy:r,className:s}){return(0,z.jsxs)("button",{type:"button","data-testid":"selection-copy-button","aria-label":"Copy selection",onMouseDown:e=>e.preventDefault(),onClick:r,style:{top:e.top,left:e.left,height:22},className:(0,eb.cn)("absolute z-20 flex items-center gap-1 rounded border border-zinc-600 bg-zinc-800 px-2","text-[11px] text-zinc-100 shadow-md hover:bg-zinc-700 hover:border-zinc-500",s),children:[(0,z.jsx)(me.Copy,{className:"h-3 w-3"}),"Copy"]})}function _$({lines:e,fontSize:r,fontFamily:s,isPty:n,className:i}){let a=(0,$.useRef)(null),o=(0,$.useRef)(null),l=(0,$.useRef)(!0),[c,d]=(0,$.useState)(null),u=(0,$.useRef)(!1),h=(0,$.useCallback)(()=>{let e=a.current,r=document.getSelection();if(u.current||!e||!r||r.isCollapsed||0===r.rangeCount||!e.contains(r.anchorNode))return void d(null);let s=e.getBoundingClientRect(),n=Array.from(r.getRangeAt(0).getClientRects()).find(e=>(e.width>0||e.height>0)&&e.bottom>s.top&&e.top<s.bottom);n?d(_B(n,s)):d(null)},[]),f=(0,$.useCallback)(()=>{u.current=!0,d(null),window.addEventListener("mouseup",()=>{u.current=!1,h()},{once:!0})},[h]);(0,$.useEffect)(()=>{let e=()=>{let e=document.getSelection();(!e||e.isCollapsed)&&d(null)};return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[]);let p=async()=>{let e=document.getSelection()?.toString()??"";if(d(null),e)try{await navigator.clipboard.writeText(e),gS.toast.success("Copied selection")}catch{gS.toast.error("Failed to copy to clipboard")}};return(0,$.useLayoutEffect)(()=>{let e=o.current;e&&l.current&&(e.scrollTop=e.scrollHeight)},[e]),(0,z.jsxs)("div",{ref:a,"data-testid":"terminal-filter-view",className:(0,eb.cn)("absolute inset-0 flex flex-col bg-zinc-950",i),children:[c&&(0,z.jsx)(_z,{anchor:c,onCopy:p}),(0,z.jsx)("div",{ref:o,"data-testid":"terminal-filter-scroller",onScroll:()=>{let e=o.current;e&&(l.current=e.scrollHeight-e.scrollTop-e.clientHeight<4,h())},onMouseDown:f,className:"min-h-0 flex-1 overflow-y-auto overflow-x-hidden px-2 pb-2 pt-9",children:0===e.length?(0,z.jsx)("div",{className:"select-none py-4 text-center text-xs text-zinc-500",children:"No lines match"}):(0,z.jsx)("pre",{className:"m-0 whitespace-pre-wrap break-all text-zinc-100",style:{fontSize:r,fontFamily:s,lineHeight:1.2},children:e.map((e,r)=>(0,z.jsx)("div",{children:""===e?" ":e},r))})}),n&&(0,z.jsx)("div",{className:"select-none border-t border-zinc-800 px-2 py-1 text-[11px] text-zinc-500",children:"Filtered view — clear filters to type into the shell"})]})}let _W=/\x1B(?:\][^\x07]*(?:\x07|\x1B\\)|[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;function _H({logs:e,isPty:r,className:s,onInput:n,onResize:i,muteInput:a,focusHandle:o,processId:l,executorId:c,target:d,status:u,exitCode:h}){let f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=(0,$.useRef)(null),g=(0,$.useRef)(0),x=(0,$.useRef)(0),v=(0,$.useRef)(!1),y=(0,$.useRef)(""),b=(0,$.useRef)(""),[w,_]=(0,$.useState)(!1),[S,j]=(0,$.useState)(!1),[k,C]=(0,$.useState)([]),[N,E]=(0,$.useState)(!1),[D,R]=(0,$.useState)(null),[T,A]=(0,$.useState)(0),I=k.length>0,M=(0,$.useRef)(I);(0,$.useEffect)(()=>{M.current=I},[I]);let[F,P]=(0,$.useState)(null),L=(0,$.useRef)(!1),O=(0,$.useRef)(null),B=(0,$.useRef)(l);(0,$.useEffect)(()=>{B.current=l},[l]);let W=(0,$.useRef)(a);W.current!==a&&console.log(`[ExecutorOutput] muteInput changed: ${W.current} → ${a}`),W.current=a;let{settings:H}=(0,m1.useTerminalSettings)(),U=(0,$.useRef)(H),[q,K]=(0,$.useState)(!1),V=(0,$.useRef)(0),X=(0,$.useRef)(e);X.current=e;let Y=async()=>{if(!q){V.current=X.current.length,K(!0);return}let e=X.current,r=Math.min(V.current,e.length),s=e.slice(r).map(e=>"stdout"===e.type||"stderr"===e.type||"pty"===e.type?e.data:"").join("");K(!1);let n=s.replace(_W,""),i=k.length>0?_F(n.split(/\r?\n/),k).join("\n"):n;if(!i)return void gS.toast.info(k.length>0?"Capture stopped — no output matched the filters":"Capture stopped — no output to copy");try{await navigator.clipboard.writeText(i),gS.toast.success(k.length>0?"Copied filtered captured output to clipboard":"Copied captured output to clipboard")}catch{gS.toast.error("Failed to copy to clipboard")}},G=(0,$.useCallback)((e,r)=>{let s=f.current;console.log(`[ExecutorOutput] resize → PTY ${e}x${r} process=${B.current??"?"} container=${s?.clientWidth??0}x${s?.clientHeight??0}px viewport=${window.innerWidth}x${window.innerHeight}px`)},[]),J=(0,$.useCallback)((e,r,s)=>{let n=p.current;if(!n)return void s?.();if(e){x.current++;try{n.write(e,()=>{x.current=Math.max(0,x.current-1),r||s?.()})}catch(e){x.current=Math.max(0,x.current-1),console.error("[ExecutorOutput] terminal write failed",e),r||s?.()}}else r||s?.();if(r)try{n.write(r,()=>s?.())}catch(e){console.error("[ExecutorOutput] terminal write failed",e),s?.()}},[]),Z=(0,$.useCallback)(()=>{v.current=!0;let e=y.current,r=b.current;y.current="",b.current="",e||r?J(e,r,()=>{p.current?.scrollToBottom(),_(!0)}):_(!0)},[J]),Q=(0,$.useRef)(null),ee=(0,$.useCallback)(()=>{let e=f.current,r=m.current;if(!e||!r||0===e.clientWidth||0===e.clientHeight)return!1;let s=r.proposeDimensions();if(!s||!Number.isFinite(s.cols)||!Number.isFinite(s.rows)||s.cols<=0||s.rows<=0)return!1;try{r.fit()}catch{return!1}return Z(),!0},[Z]),et=(0,$.useCallback)(()=>{if(null!==Q.current)return;let e=()=>{if(Q.current=null,v.current||!p.current)return;let r=f.current;r&&0!==r.clientWidth&&0!==r.clientHeight&&(ee()||(Q.current=requestAnimationFrame(e)))};Q.current=requestAnimationFrame(e)},[ee]),er=(0,$.useCallback)(()=>{let e=p.current,r=O.current;if(!e||!r||L.current)return void P(null);let s=e.getSelectionPosition();if(!s)return void P(null);let n=e.buffer.active.viewportY,i=s.start.y-n;if(s.end.y-n<0||i>=e.rows)return void P(null);let a=Math.max(i,0),o=a===i?s.start.x:0,l=e.element?.querySelectorAll(".xterm-rows > div")[a],c=l?.getBoundingClientRect();if(!c||0===c.width)return void P(null);let d=c.width/e.cols;P(_B({top:c.top,bottom:c.bottom,left:c.left+o*d},r.getBoundingClientRect()))},[]),es=(0,$.useCallback)(()=>{L.current=!0,P(null),window.addEventListener("pointerup",()=>{L.current=!1,er()},{once:!0})},[er]),en=async()=>{let e=p.current?.getSelection()??"";if(P(null),e)try{await navigator.clipboard.writeText(e),gS.toast.success("Copied selection")}catch{gS.toast.error("Failed to copy to clipboard")}};(0,$.useEffect)(()=>{if(!f.current||p.current)return;let e=U.current,s=new _k({cursorBlink:r,cursorStyle:r?"block":"underline",disableStdin:!r,convertEol:!0,fontSize:e.fontSize,fontFamily:e.fontFamily,scrollback:e.scrollback,theme:{background:"#09090b",foreground:"#fafafa",cursor:r?"#fafafa":"#09090b",cursorAccent:"#09090b",selectionBackground:"#3f3f46",black:"#09090b",red:"#f87171",green:"#4ade80",yellow:"#facc15",blue:"#60a5fa",magenta:"#c084fc",cyan:"#22d3ee",white:"#fafafa",brightBlack:"#71717a",brightRed:"#fca5a5",brightGreen:"#86efac",brightYellow:"#fde047",brightBlue:"#93c5fd",brightMagenta:"#d8b4fe",brightCyan:"#67e8f9",brightWhite:"#ffffff"},allowProposedApi:!0}),a=new _C,o=new _T;s.loadAddon(a),s.loadAddon(o),s.attachCustomKeyEventHandler(e=>null===fS(e)),s.open(f.current);let l=setTimeout(()=>{try{let e=f.current;if(!e||0===e.clientWidth||0===e.clientHeight)return;ee()?r&&(G(s.cols,s.rows),i?.(s.cols,s.rows)):et()}catch{}},0);return p.current=s,m.current=a,A(e=>e+1),r&&n&&s.onData(e=>{W.current||0!==x.current||M.current||n(e)}),s.onSelectionChange(er),s.onScroll(er),r&&i&&s.onResize(({cols:e,rows:r})=>{G(e,r),i(e,r)}),()=>{clearTimeout(l),null!==Q.current&&(cancelAnimationFrame(Q.current),Q.current=null),s.dispose(),p.current=null,m.current=null,g.current=0,x.current=0,v.current=!1,y.current="",b.current=""}},[r,n,i,ee,et,G,er]),(0,$.useEffect)(()=>{if(!p.current)return;e.length<g.current&&(p.current.reset(),A(e=>e+1),g.current=0,y.current="",b.current="");let s="",n="";for(let r=g.current;r<e.length;r++){let i=e[r];("pty"===i.type||"stdout"===i.type||"stderr"===i.type)&&(i.historical?s+=i.data:n+=i.data)}if(g.current=e.length,r&&!v.current){y.current=(y.current+s).slice(-1e6),b.current=(b.current+n).slice(-1e6);return}(s||n)&&J(s,n)},[e,r,J]),(0,$.useEffect)(()=>{let e=p.current;if(e){e.options.fontSize=H.fontSize,e.options.fontFamily=H.fontFamily,e.options.scrollback=H.scrollback;try{m.current?.fit()}catch{}}},[H.fontSize,H.fontFamily,H.scrollback]),(0,$.useEffect)(()=>{S&&r&&!I&&!N&&p.current?.focus()},[S,r,I,N]),(0,$.useEffect)(()=>{if(!I)return void R(null);let e=p.current;if(!e)return;let r=null,s=()=>{r=null;let s=function(e){let r=[];for(let s=0;s<e.length;s++){let n=e.getLine(s);if(!n)continue;let i=n.translateToString(!0);n.isWrapped&&r.length>0?r[r.length-1]+=i:r.push(i)}let s=r.length;for(;s>0&&""===r[s-1];)s--;return r.slice(0,s)}(e.buffer.active);R({lines:_F(s,k),total:s.length})};s();let n=e.onWriteParsed(()=>{null===r&&(r=requestAnimationFrame(s))});return()=>{n.dispose(),null!==r&&cancelAnimationFrame(r)}},[k,I,T]);let ei=(0,$.useCallback)(e=>{C(r=>[...r,{...e,id:`${Date.now()}-${r.length}`}])},[]),ea=(0,$.useCallback)(e=>{C(r=>r.filter(r=>r.id!==e))},[]),eo=(0,$.useCallback)(()=>{E(!1),r&&0===k.length&&p.current?.focus()},[r,k.length]),el=async()=>{let e=D?.lines.join("\n")??"";if(!e)return void gS.toast.info("No filtered lines to copy");try{await navigator.clipboard.writeText(e),gS.toast.success(`Copied ${D.lines.length} filtered lines`)}catch{gS.toast.error("Failed to copy to clipboard")}};(0,$.useImperativeHandle)(o,()=>({focus:()=>{r&&!M.current&&p.current?.focus()}}),[r]),(0,$.useEffect)(()=>{if(!f.current||!m.current)return;let e=new ResizeObserver(()=>{try{let e=f.current;if(!e||0===e.clientWidth||0===e.clientHeight)return;v.current?m.current?.fit():ee()||et()}catch{}});return e.observe(f.current),()=>{e.disconnect()}},[ee,et]);let ec=[{label:"Process",value:l??null},{label:"Executor",value:c??null},{label:"Target",value:d??null},{label:"Status",value:"closed"===u&&null!==h?`closed \xb7 exit ${h}`:u??null}],ed=(0,eb.cn)("flex h-6 w-6 items-center justify-center rounded","bg-zinc-900/70 backdrop-blur-sm border border-zinc-700/60","text-zinc-400 hover:text-zinc-100 hover:border-zinc-500 transition-colors");return(0,z.jsxs)("div",{className:(0,eb.cn)("relative h-[300px] rounded-md border bg-zinc-950 overflow-hidden",s),children:[S&&(0,z.jsx)("div",{className:"flex h-full select-none items-center justify-center text-xs text-zinc-500",children:"Terminal is maximized"}),(0,z.jsx)("div",{"data-testid":"executor-output-layer","data-maximized":S||void 0,role:S?"dialog":void 0,"aria-modal":S||void 0,"aria-label":S?"Maximized terminal":void 0,className:S?"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 sm:p-10 lg:p-16":"absolute inset-0",onMouseDown:S?e=>{e.target===e.currentTarget&&j(!1)}:void 0,children:(0,z.jsxs)("div",{ref:O,className:(0,eb.cn)("relative h-full w-full",S&&"max-h-[85vh] max-w-6xl overflow-hidden rounded-md border border-zinc-700 bg-zinc-950 shadow-2xl"),children:[(0,z.jsx)("div",{ref:f,onPointerDown:es,className:(0,eb.cn)("h-full w-full",!w&&"opacity-0")}),F&&!D&&(0,z.jsx)(_z,{anchor:F,onCopy:en}),D&&(0,z.jsx)(_$,{lines:D.lines,fontSize:H.fontSize,fontFamily:H.fontFamily,isPty:r}),(0,z.jsxs)("div",{className:"absolute top-2 right-3 z-10 flex max-w-[calc(100%-1.5rem)] flex-wrap items-center justify-end gap-1.5",children:[(0,z.jsx)(_O,{filters:k,inputOpen:N,onAdd:ei,onRemove:ea,onCloseInput:eo,counts:D?{matched:D.lines.length,total:D.total}:null}),D&&(0,z.jsx)("button",{type:"button",onClick:el,title:"Copy filtered lines","aria-label":"Copy filtered lines",className:ed,children:(0,z.jsx)(me.Copy,{className:"h-3 w-3"})}),(0,z.jsx)("button",{type:"button",onClick:()=>N?eo():E(!0),title:N?"Close filter input":"Filter output lines","aria-label":N?"Close filter input":"Filter output lines","aria-pressed":I,className:(0,eb.cn)(ed,I&&"text-sky-300 border-sky-500/70 hover:text-sky-200"),children:(0,z.jsx)(_A,{className:"h-3 w-3"})}),(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)("button",{type:"button",title:"Process info","aria-label":"Show process info",className:ed,children:(0,z.jsx)(hv,{className:"h-3 w-3"})})}),(0,z.jsxs)(o1,{align:"end",className:"w-72",children:[(0,z.jsx)(o6,{className:"text-xs text-muted-foreground",children:"Process info"}),ec.map(e=>(0,z.jsxs)(o2,{disabled:!e.value,onSelect:r=>{var s,n;r.preventDefault(),s=e.label,(n=e.value)&&(navigator.clipboard.writeText(n),gS.toast.success(`${s} copied`))},className:"flex items-center justify-between gap-3 font-mono text-xs",children:[(0,z.jsx)("span",{className:"shrink-0 text-muted-foreground",children:e.label}),(0,z.jsxs)("span",{className:"flex min-w-0 items-center gap-1.5",children:[(0,z.jsx)("span",{className:"truncate",children:e.value??"—"}),e.value&&(0,z.jsx)(me.Copy,{className:"h-3 w-3 shrink-0 opacity-60"})]})]},e.label))]})]}),(0,z.jsx)("button",{type:"button",onClick:Y,title:q?I?"Stop capture & copy filtered output":"Stop capture & copy to clipboard":"Start capturing output","aria-label":q?"Stop capture and copy":"Start capturing output",className:(0,eb.cn)(ed,q&&"text-red-400 border-red-500/70 hover:text-red-300"),children:q?(0,z.jsx)(lG,{className:"h-3 w-3 fill-current"}):(0,z.jsx)(sQ,{className:"h-3 w-3"})}),(0,z.jsx)("button",{type:"button",onClick:()=>j(e=>!e),title:S?"Restore size":"Maximize terminal","aria-label":S?"Restore terminal size":"Maximize terminal","aria-pressed":S,className:ed,children:S?(0,z.jsx)(_M,{className:"h-3 w-3"}):(0,z.jsx)(_I,{className:"h-3 w-3"})})]})]})})]})}let _U=[{name:"Dev Server",command:"pnpm dev",executor_type:"command",pty:!0,description:"Start the development server with hot reload"},{name:"Build",command:"pnpm build",executor_type:"command",pty:!0,description:"Build the project for production"},{name:"Lint",command:"pnpm lint",executor_type:"command",pty:!0,description:"Run the linter to check code quality"},{name:"Type Check",command:"npx tsc --noEmit",executor_type:"command",pty:!0,description:"Run TypeScript type checking without emitting files"},{name:"Test",command:"pnpm test",executor_type:"command",pty:!0,description:"Run the test suite"},{name:"Rebase on and merge into main",command:"Our goal is to sync the current local branch with the local branch/worktree `main`. The two branches may have diverged.\n\nPlease do the following in order. Only proceed to the next step if the previous step succeeds:\n\n1. Rebase the current local branch onto the local branch `main`, and resolve any conflicts if needed.\n2. If, after the rebase, `main` does not yet contain the current branch's commits, switch to the `main` branch/worktree and merge the current branch into `main` using `git merge`. Do not use `git branch -f`.\n3. If the current branch is already fully contained in `main`, and `main` has newer commits, update the current branch so it includes the latest commits from `main`.\n4. Push both the current local branch and the local branch `main` to the remote.",executor_type:"prompt",pty:!1,description:"Rebase current branch onto main, merge into main, and push both branches"},{name:"Reset to main",command:"git reset --hard main",executor_type:"command",pty:!0,description:"Hard reset the current branch to match main"},{name:"Push to remote",command:"git push --force-with-lease",executor_type:"command",pty:!0,description:"Force push to remote with lease safety check"},{name:"Git commit",command:"Inspect the modified and untracked and deleted files in the current repository, generate an appropriate commit message, and commit all relevant files.\n\nCommit message rules:\n- Use Conventional Commits format (feat:, fix:, chore:, refactor:, docs:, test:, ci:, build:, perf:, style:, etc.)\n- Choose the type that best matches the main purpose of the changes\n- Make the message specific to the actual changes\n- Keep it within 50 characters if possible\n- Use lowercase\n- Do not end with a period\n- Do not wrap the message in quotes, backticks, or markdown\n\nCommit requirements:\n- Include all relevant modified and untracked files\n- Do not include unrelated files\n- If there are no meaningful changes to commit, do not create a commit\n- Do not run tests, builds, type checks, or linters; only inspect the changes and commit\n\nWhen finished, output only the final commit message.",executor_type:"prompt",pty:!1,description:"Inspect changes, generate a conventional commit message, and commit"},{name:"Tag and push",command:"Find the latest SemVer tag in the repository, increase the patch number by 1, create the new tag from the current commit, and push it to origin.",executor_type:"prompt",pty:!1,description:"Bump the patch version tag and push it to origin"}];function _q({open:e,onOpenChange:r,executor:s,onSubmit:n}){let[i,a]=(0,$.useState)(s?.name??""),[o,l]=(0,$.useState)(s?.executor_type??"command"),[c,d]=(0,$.useState)(s?.prompt_provider??"claude"),[u,h]=(0,$.useState)(s?.command??""),[f,p]=(0,$.useState)(s?.cwd??""),[m,g]=(0,$.useState)(s?.pty??!0),[x,v]=(0,$.useState)(!1),[y,b]=(0,$.useState)(!1),[w,_]=(0,$.useState)(null),[S,j]=(0,$.useState)(null),[k,C]=(0,$.useState)(""),N=!!s;(0,$.useEffect)(()=>{e&&(b(!1),_(null),j(null),C(""),s&&(a(s.name),l(s.executor_type??"command"),d(s.prompt_provider??"claude"),h(s.command),p(s.cwd??""),g(s.pty)))},[e]);let E=async e=>{if(e.preventDefault(),i.trim()&&u.trim()){v(!0);try{await n({name:i.trim(),command:u.trim(),executor_type:o,prompt_provider:"prompt"===o?c:null,cwd:f.trim()||void 0,pty:"prompt"===o||m}),r(!1),N||(a(""),l("command"),d("claude"),h(""),p(""),g(!0))}finally{v(!1)}}};return(0,z.jsx)(t8,{open:e,onOpenChange:r,children:(0,z.jsxs)(rs,{children:[(0,z.jsx)(rn,{children:(0,z.jsxs)("div",{className:"flex items-center justify-between pr-6",children:[(0,z.jsx)(ra,{children:y?"Select Preset":N?"Edit Executor":"Add Executor"}),!N&&!y&&(0,z.jsx)("button",{type:"button",className:"text-sm text-muted-foreground hover:text-foreground transition-colors",onClick:()=>b(!0),children:"Select from presets"})]})}),(0,z.jsxs)("div",{className:"h-[420px] flex flex-col",children:[!y&&(0,z.jsxs)("form",{onSubmit:E,className:"space-y-4 flex-1 flex flex-col",children:[(0,z.jsxs)("div",{className:"space-y-2",children:[(0,z.jsx)("label",{className:"text-sm font-medium",children:"Name"}),(0,z.jsx)(rl,{placeholder:"e.g., Dev Server",value:i,onChange:e=>a(e.target.value),required:!0})]}),(0,z.jsxs)("div",{className:"space-y-2",children:[(0,z.jsx)("label",{className:"text-sm font-medium",children:"Type"}),(0,z.jsxs)("div",{className:"flex rounded-md border border-input overflow-hidden",children:[(0,z.jsx)("button",{type:"button",className:(0,eb.cn)("flex-1 px-3 py-1.5 text-sm font-medium transition-colors","command"===o?"bg-primary text-primary-foreground":"bg-background text-muted-foreground hover:bg-muted"),onClick:()=>l("command"),children:"Command"}),(0,z.jsx)("button",{type:"button",className:(0,eb.cn)("flex-1 px-3 py-1.5 text-sm font-medium transition-colors border-l border-input","prompt"===o?"bg-primary text-primary-foreground":"bg-background text-muted-foreground hover:bg-muted"),onClick:()=>l("prompt"),children:"Prompt"})]})]}),"prompt"===o&&(0,z.jsxs)("div",{className:"flex gap-3",children:[(0,z.jsxs)("div",{className:"w-[140px] shrink-0 space-y-2",children:[(0,z.jsx)("label",{className:"text-sm font-medium",children:"Provider"}),(0,z.jsxs)(fd,{value:c,onValueChange:e=>d(e),children:[(0,z.jsx)(fh,{className:"w-full",children:(0,z.jsx)(fu,{})}),(0,z.jsxs)(ff,{children:[(0,z.jsx)(fp,{value:"claude",children:"Claude"}),(0,z.jsx)(fp,{value:"codex",children:"Codex"})]})]})]}),(0,z.jsxs)("div",{className:"flex-1 space-y-2",children:[(0,z.jsxs)("label",{className:"text-sm font-medium",children:["Working Directory"," ",(0,z.jsx)("span",{className:"text-muted-foreground",children:"(optional)"})]}),(0,z.jsx)(rl,{placeholder:"Relative to worktree root",value:f,onChange:e=>p(e.target.value)})]})]}),(0,z.jsxs)("div",{className:"space-y-2",children:[(0,z.jsx)("label",{className:"text-sm font-medium",children:"prompt"===o?"Prompt":"Command"}),"prompt"===o?(0,z.jsx)("textarea",{className:"flex min-h-[90px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 resize-y",placeholder:"e.g., Review the code and suggest improvements",value:u,onChange:e=>h(e.target.value),required:!0}):(0,z.jsx)(rl,{placeholder:"e.g., npm run dev",value:u,onChange:e=>h(e.target.value),required:!0})]}),"command"===o&&(0,z.jsxs)("div",{className:"space-y-2",children:[(0,z.jsxs)("label",{className:"text-sm font-medium",children:["Working Directory"," ",(0,z.jsx)("span",{className:"text-muted-foreground",children:"(optional)"})]}),(0,z.jsx)(rl,{placeholder:"Relative to worktree root (leave empty for root)",value:f,onChange:e=>p(e.target.value)})]}),"command"===o&&(0,z.jsxs)("div",{className:"flex items-center justify-between",children:[(0,z.jsxs)("div",{className:"space-y-0.5",children:[(0,z.jsx)("label",{className:"text-sm font-medium",children:"Terminal Mode (PTY)"}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:"Enable for interactive commands like top, vim, htop"})]}),(0,z.jsx)("button",{type:"button",role:"switch","aria-checked":m,onClick:()=>g(!m),className:(0,eb.cn)("relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",m?"bg-primary":"bg-input"),children:(0,z.jsx)("span",{className:(0,eb.cn)("pointer-events-none inline-block h-5 w-5 transform rounded-full bg-background shadow-lg ring-0 transition-transform",m?"translate-x-5":"translate-x-0")})})]}),(0,z.jsx)("div",{className:"flex-1"}),(0,z.jsxs)(ri,{children:[(0,z.jsx)(W.Button,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),(0,z.jsx)(W.Button,{type:"submit",disabled:x||!i.trim()||!u.trim(),children:x?"Saving...":N?"Save":"Add"})]})]}),y&&(0,z.jsxs)("div",{className:"space-y-4 flex-1 flex flex-col min-h-0",children:[(0,z.jsx)(rl,{placeholder:"Search presets...",value:k,onChange:e=>C(e.target.value),autoFocus:!0}),(0,z.jsx)("div",{className:"flex-1 overflow-y-auto min-h-0 space-y-1",children:_U.filter(e=>{if(!k.trim())return!0;let r=k.toLowerCase();return e.name.toLowerCase().includes(r)||e.command.toLowerCase().includes(r)||(e.description?.toLowerCase().includes(r)??!1)}).map(e=>{let r=w?.command===e.command,s=S===e.command;return(0,z.jsxs)("div",{className:"rounded-md overflow-hidden",children:[(0,z.jsxs)("button",{type:"button",className:(0,eb.cn)("w-full flex items-center gap-2 px-3 py-2 text-sm transition-colors",r?"bg-primary/10 text-primary":"hover:bg-muted"),onClick:()=>_(e),children:["command"===e.executor_type?(0,z.jsx)(gM,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):(0,z.jsx)(sR,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),(0,z.jsx)("span",{className:"font-medium flex-1 text-left",children:e.name}),(0,z.jsx)("button",{type:"button",className:"shrink-0 p-0.5 rounded hover:bg-muted-foreground/10 transition-colors",onClick:r=>{r.stopPropagation(),j(s?null:e.command)},children:s?(0,z.jsx)(n6,{className:"h-4 w-4 text-muted-foreground"}):(0,z.jsx)(nV,{className:"h-4 w-4 text-muted-foreground"})})]}),s&&(0,z.jsxs)("div",{className:(0,eb.cn)("px-3 pb-2 pt-1 text-xs text-muted-foreground space-y-1 border-t border-border/50",r?"bg-primary/5":"bg-muted/50"),children:[e.description&&(0,z.jsx)("p",{children:e.description}),(0,z.jsx)("pre",{className:"whitespace-pre-wrap break-all bg-muted/50 rounded px-2 py-1 font-mono",children:e.command}),(0,z.jsxs)("div",{className:"flex gap-3",children:[(0,z.jsxs)("span",{children:["Type: ",(0,z.jsx)("span",{className:"font-medium text-foreground/70",children:e.executor_type})]}),(0,z.jsxs)("span",{children:["PTY: ",(0,z.jsx)("span",{className:"font-medium text-foreground/70",children:e.pty?"on":"off"})]})]})]})]},e.command)})}),(0,z.jsxs)(ri,{children:[(0,z.jsx)(W.Button,{type:"button",variant:"outline",onClick:()=>{b(!1),_(null),j(null)},children:"Cancel"}),(0,z.jsx)(W.Button,{type:"button",disabled:!w,onClick:()=>{w&&(a(w.name),h(w.command),l(w.executor_type),g(w.pty),b(!1),_(null),j(null))},children:"Select"})]})]})]})]})})}let _K={logs:[],status:"connecting",exitCode:null,isPty:!1,replayingHistory:!0},_V=(0,$.createContext)(null);function _X({projectId:e,children:r}){let s=(0,$.useRef)(new Map),n=(0,$.useRef)(new Map),i=(0,$.useRef)(new Set),a=(0,$.useRef)(null),o=(0,$.useRef)(0),l=(0,$.useRef)(null),c=(0,$.useCallback)(e=>{n.current.get(e)?.forEach(e=>e())},[]),d=(0,$.useCallback)((e,r)=>{let n=s.current.get(e)??_K;s.current.set(e,{...n,...r}),c(e)},[c]),u=(0,$.useRef)(new Map),h=(0,$.useRef)(new Map),f=(0,$.useCallback)(e=>{a.current?.readyState===WebSocket.OPEN&&a.current.send(JSON.stringify(e))},[]),p=(0,$.useCallback)(e=>{let r=u.current.get(e);r&&clearTimeout(r),u.current.delete(e),h.current.delete(e)},[]),m=(0,$.useCallback)(e=>{let r=u.current.get(e);r&&clearTimeout(r);let s=h.current.get(e)??0;if(s>=12){u.current.delete(e),d(e,{status:"error"});return}h.current.set(e,s+1);let n=Math.min(15e3,1e3*2**s),a=n+n*Math.random()*.25;d(e,{status:"connecting"});let o=setTimeout(()=>{u.current.delete(e),i.current.has(e)&&f({type:"subscribe",processId:e})},a);u.current.set(e,o)},[f,d]),g=(0,$.useCallback)(e=>{let{processId:r}=e;if(i.current.has(r))if("error"===e.type?e.message:"finished"===e.type?e.exitCode:"init"===e.type?e.isPty:"history_end"===e.type||e.data.length,"init"===e.type)p(r),d(r,{isPty:e.isPty,replayingHistory:!0,logs:[],status:"connected"});else if("history_end"===e.type)d(r,{replayingHistory:!1});else if("finished"===e.type)console.log(`[diag:remote-stop] ${new Date().toISOString()} mux received FINISHED processId=${r} exitCode=${e.exitCode} — will trigger markProcessFinished → button flips to Start`),d(r,{exitCode:e.exitCode,status:"closed"});else if("error"===e.type)console.log(`[diag:remote-stop] ${new Date().toISOString()} mux received ERROR processId=${r} retryable=${!!e.retryable} — does NOT flip isRunning`),e.retryable?m(r):(p(r),d(r,{status:"error"}));else{let n=s.current.get(r)??_K,{processId:i,...a}=e;d(r,{logs:[...n.logs,{...a,historical:n.replayingHistory}]})}},[d,p,m]);(0,$.useEffect)(()=>{if(!e)return;let r=!1;o.current=0;let n=()=>{r||(0,ry.getFreshToken)().then(()=>{r||(()=>{if(r)return;let c=new WebSocket((0,ry.getWebSocketUrl)(`/api/executor-logs/stream?projectId=${encodeURIComponent(e)}`));a.current=c,c.onopen=()=>{if(!r)for(let e of(o.current=0,console.log("[diag:mux] WS open, resubscribing",[...i.current]),i.current))p(e),c.send(JSON.stringify({type:"subscribe",processId:e}))},c.onmessage=e=>{if(!r)try{g(JSON.parse(e.data))}catch(e){console.error("[ExecutorLogs] parse error:",e)}},c.onclose=()=>{if(a.current=null,console.log("[diag:mux] WS close, reconnectAttempt=",o.current,"cancelled=",r),r)return;let e=e=>{let r=s.current.get(e);return r?.status==="closed"||r?.status==="error"};if(o.current<8){let s=o.current++,a=Math.min(15e3,1e3*2**s),c=a+a*Math.random()*.25;for(let r of i.current)e(r)||d(r,{status:"connecting"});l.current=setTimeout(()=>{l.current=null,r||n()},c)}else for(let r of i.current)e(r)||d(r,{status:"error"})}})()})};n();let c=u.current,f=h.current;return()=>{for(let e of(r=!0,l.current&&clearTimeout(l.current),l.current=null,c.values()))clearTimeout(e);c.clear(),f.clear(),a.current?.close(),a.current=null}},[e,g,d,p]);let x=(0,$.useMemo)(()=>({subscribeProcess:e=>{i.current.has(e)||(i.current.add(e),s.current.set(e,{..._K}),c(e),console.log("[diag:mux] send subscribe",e,"(state reset to EMPTY)"),f({type:"subscribe",processId:e}))},unsubscribeProcess:e=>{i.current.has(e)&&(i.current.delete(e),p(e),console.log("[diag:mux] send unsubscribe",e),f({type:"unsubscribe",processId:e}))},sendInput:(e,r)=>f({type:"input",processId:e,data:r}),sendResize:(e,r,s)=>f({type:"resize",processId:e,cols:r,rows:s}),onProcessChange:(e,r)=>{let s=n.current.get(e);return s||(s=new Set,n.current.set(e,s)),s.add(r),()=>{s?.delete(r)}},getProcessState:e=>s.current.get(e)??_K}),[c,f,p]);return(0,z.jsx)(_V.Provider,{value:x,children:r})}let _Y="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement;function _G(e){let r=Object.prototype.toString.call(e);return"[object Window]"===r||"[object global]"===r}function _J(e){return"nodeType"in e}function _Z(e){var r,s;return e?_G(e)?e:_J(e)&&null!=(r=null==(s=e.ownerDocument)?void 0:s.defaultView)?r:window:window}function _Q(e){let{Document:r}=_Z(e);return e instanceof r}function _0(e){return!_G(e)&&e instanceof _Z(e).HTMLElement}function _1(e){return e instanceof _Z(e).SVGElement}function _2(e){return e?_G(e)?e.document:_J(e)?_Q(e)?e:_0(e)||_1(e)?e.ownerDocument:document:document:document}let _5=_Y?$.useLayoutEffect:$.useEffect;function _3(e){let r=(0,$.useRef)(e);return _5(()=>{r.current=e}),(0,$.useCallback)(function(){for(var e=arguments.length,s=Array(e),n=0;n<e;n++)s[n]=arguments[n];return null==r.current?void 0:r.current(...s)},[])}function _4(e,r){void 0===r&&(r=[e]);let s=(0,$.useRef)(e);return _5(()=>{s.current!==e&&(s.current=e)},r),s}function _6(e,r){let s=(0,$.useRef)();return(0,$.useMemo)(()=>{let r=e(s.current);return s.current=r,r},[...r])}function _7(e){let r=_3(e),s=(0,$.useRef)(null),n=(0,$.useCallback)(e=>{e!==s.current&&(null==r||r(e,s.current)),s.current=e},[]);return[s,n]}function _8(e){let r=(0,$.useRef)();return(0,$.useEffect)(()=>{r.current=e},[e]),r.current}let _9={};function Se(e,r){return(0,$.useMemo)(()=>{if(r)return r;let s=null==_9[e]?0:_9[e]+1;return _9[e]=s,e+"-"+s},[e,r])}function St(e){return function(r){for(var s=arguments.length,n=Array(s>1?s-1:0),i=1;i<s;i++)n[i-1]=arguments[i];return n.reduce((r,s)=>{for(let[n,i]of Object.entries(s)){let s=r[n];null!=s&&(r[n]=s+e*i)}return r},{...r})}}let Sr=St(1),Ss=St(-1);function Sn(e){if(!e)return!1;let{KeyboardEvent:r}=_Z(e.target);return r&&e instanceof r}function Si(e){if(function(e){if(!e)return!1;let{TouchEvent:r}=_Z(e.target);return r&&e instanceof r}(e)){if(e.touches&&e.touches.length){let{clientX:r,clientY:s}=e.touches[0];return{x:r,y:s}}else if(e.changedTouches&&e.changedTouches.length){let{clientX:r,clientY:s}=e.changedTouches[0];return{x:r,y:s}}}return"clientX"in e&&"clientY"in e?{x:e.clientX,y:e.clientY}:null}let Sa=Object.freeze({Translate:{toString(e){if(!e)return;let{x:r,y:s}=e;return"translate3d("+(r?Math.round(r):0)+"px, "+(s?Math.round(s):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;let{scaleX:r,scaleY:s}=e;return"scaleX("+r+") scaleY("+s+")"}},Transform:{toString(e){if(e)return[Sa.Translate.toString(e),Sa.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:r,duration:s,easing:n}=e;return r+" "+s+"ms "+n}}}),So="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]",Sl={display:"none"};function Sc(e){let{id:r,value:s}=e;return $.default.createElement("div",{id:r,style:Sl},s)}function Sd(e){let{id:r,announcement:s,ariaLiveType:n="assertive"}=e;return $.default.createElement("div",{id:r,style:{position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"},role:"status","aria-live":n,"aria-atomic":!0},s)}let Su=(0,$.createContext)(null),Sh={draggable:"\n To pick up a draggable item, press the space bar.\n While dragging, use the arrow keys to move the item.\n Press space again to drop the item in its new position, or press escape to cancel.\n "},Sf={onDragStart(e){let{active:r}=e;return"Picked up draggable item "+r.id+"."},onDragOver(e){let{active:r,over:s}=e;return s?"Draggable item "+r.id+" was moved over droppable area "+s.id+".":"Draggable item "+r.id+" is no longer over a droppable area."},onDragEnd(e){let{active:r,over:s}=e;return s?"Draggable item "+r.id+" was dropped over droppable area "+s.id:"Draggable item "+r.id+" was dropped."},onDragCancel(e){let{active:r}=e;return"Dragging was cancelled. Draggable item "+r.id+" was dropped."}};function Sp(e){var r;let s,{announcements:n=Sf,container:i,hiddenTextDescribedById:a,screenReaderInstructions:o=Sh}=e,{announce:l,announcement:c}=function(){let[e,r]=(0,$.useState)("");return{announce:(0,$.useCallback)(e=>{null!=e&&r(e)},[]),announcement:e}}(),d=Se("DndLiveRegion"),[u,h]=(0,$.useState)(!1);if((0,$.useEffect)(()=>{h(!0)},[]),r=(0,$.useMemo)(()=>({onDragStart(e){let{active:r}=e;l(n.onDragStart({active:r}))},onDragMove(e){let{active:r,over:s}=e;n.onDragMove&&l(n.onDragMove({active:r,over:s}))},onDragOver(e){let{active:r,over:s}=e;l(n.onDragOver({active:r,over:s}))},onDragEnd(e){let{active:r,over:s}=e;l(n.onDragEnd({active:r,over:s}))},onDragCancel(e){let{active:r,over:s}=e;l(n.onDragCancel({active:r,over:s}))}}),[l,n]),s=(0,$.useContext)(Su),(0,$.useEffect)(()=>{if(!s)throw Error("useDndMonitor must be used within a children of <DndContext>");return s(r)},[r,s]),!u)return null;let f=$.default.createElement($.default.Fragment,null,$.default.createElement(Sc,{id:a,value:o.draggable}),$.default.createElement(Sd,{id:d,announcement:c}));return i?(0,ee.createPortal)(f,i):f}function Sm(){}function Sg(e,r){return(0,$.useMemo)(()=>({sensor:e,options:null!=r?r:{}}),[e,r])}(y=E||(E={})).DragStart="dragStart",y.DragMove="dragMove",y.DragEnd="dragEnd",y.DragCancel="dragCancel",y.DragOver="dragOver",y.RegisterDroppable="registerDroppable",y.SetDroppableDisabled="setDroppableDisabled",y.UnregisterDroppable="unregisterDroppable";let Sx=Object.freeze({x:0,y:0});function Sv(e,r){return Math.sqrt(Math.pow(e.x-r.x,2)+Math.pow(e.y-r.y,2))}function Sy(e,r){let{data:{value:s}}=e,{data:{value:n}}=r;return s-n}function Sb(e,r){let{data:{value:s}}=e,{data:{value:n}}=r;return n-s}function Sw(e){let{left:r,top:s,height:n,width:i}=e;return[{x:r,y:s},{x:r+i,y:s},{x:r,y:s+n},{x:r+i,y:s+n}]}function S_(e,r){if(!e||0===e.length)return null;let[s]=e;return r?s[r]:s}function SS(e,r,s){return void 0===r&&(r=e.left),void 0===s&&(s=e.top),{x:r+.5*e.width,y:s+.5*e.height}}let Sj=e=>{let{collisionRect:r,droppableRects:s,droppableContainers:n}=e,i=[];for(let e of n){let{id:n}=e,a=s.get(n);if(a){let s=function(e,r){let s=Math.max(r.top,e.top),n=Math.max(r.left,e.left),i=Math.min(r.left+r.width,e.left+e.width),a=Math.min(r.top+r.height,e.top+e.height);if(n<i&&s<a){let o=r.width*r.height,l=e.width*e.height,c=(i-n)*(a-s);return Number((c/(o+l-c)).toFixed(4))}return 0}(a,r);s>0&&i.push({id:n,data:{droppableContainer:e,value:s}})}}return i.sort(Sb)};function Sk(e,r){return e&&r?{x:e.left-r.left,y:e.top-r.top}:Sx}let SC=function(e){for(var r=arguments.length,s=Array(r>1?r-1:0),n=1;n<r;n++)s[n-1]=arguments[n];return s.reduce((e,r)=>({...e,top:e.top+ +r.y,bottom:e.bottom+ +r.y,left:e.left+ +r.x,right:e.right+ +r.x}),{...e})},SN={ignoreTransform:!1};function SE(e,r){void 0===r&&(r=SN);let s=e.getBoundingClientRect();if(r.ignoreTransform){let{transform:r,transformOrigin:n}=_Z(e).getComputedStyle(e);r&&(s=function(e,r,s){let n=function(e){if(e.startsWith("matrix3d(")){let r=e.slice(9,-1).split(/, /);return{x:+r[12],y:+r[13],scaleX:+r[0],scaleY:+r[5]}}if(e.startsWith("matrix(")){let r=e.slice(7,-1).split(/, /);return{x:+r[4],y:+r[5],scaleX:+r[0],scaleY:+r[3]}}return null}(r);if(!n)return e;let{scaleX:i,scaleY:a,x:o,y:l}=n,c=e.left-o-(1-i)*parseFloat(s),d=e.top-l-(1-a)*parseFloat(s.slice(s.indexOf(" ")+1)),u=i?e.width/i:e.width,h=a?e.height/a:e.height;return{width:u,height:h,top:d,right:c+u,bottom:d+h,left:c}}(s,r,n))}let{top:n,left:i,width:a,height:o,bottom:l,right:c}=s;return{top:n,left:i,width:a,height:o,bottom:l,right:c}}function SD(e){return SE(e,{ignoreTransform:!0})}function SR(e,r){let s=[];return e?function n(i){var a,o;let l;if(null!=r&&s.length>=r||!i)return s;if(_Q(i)&&null!=i.scrollingElement&&!s.includes(i.scrollingElement))return s.push(i.scrollingElement),s;if(!_0(i)||_1(i)||s.includes(i))return s;let c=_Z(e).getComputedStyle(i);return(i!==e&&(void 0===(a=c)&&(a=_Z(i).getComputedStyle(i)),l=/(auto|scroll|overlay)/,["overflow","overflowX","overflowY"].some(e=>{let r=a[e];return"string"==typeof r&&l.test(r)}))&&s.push(i),void 0===(o=c)&&(o=_Z(i).getComputedStyle(i)),"fixed"===o.position)?s:n(i.parentNode)}(e):s}function ST(e){let[r]=SR(e,1);return null!=r?r:null}function SA(e){return _Y&&e?_G(e)?e:_J(e)?_Q(e)||e===_2(e).scrollingElement?window:_0(e)?e:null:null:null}function SI(e){return _G(e)?e.scrollX:e.scrollLeft}function SM(e){return _G(e)?e.scrollY:e.scrollTop}function SF(e){return{x:SI(e),y:SM(e)}}function SP(e){return!!_Y&&!!e&&e===document.scrollingElement}function SL(e){let r={x:0,y:0},s=SP(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},n={x:e.scrollWidth-s.width,y:e.scrollHeight-s.height},i=e.scrollTop<=r.y,a=e.scrollLeft<=r.x;return{isTop:i,isLeft:a,isBottom:e.scrollTop>=n.y,isRight:e.scrollLeft>=n.x,maxScroll:n,minScroll:r}}(b=D||(D={}))[b.Forward=1]="Forward",b[b.Backward=-1]="Backward";let SO={x:.2,y:.2};function SB(e){return e.reduce((e,r)=>Sr(e,SF(r)),Sx)}let Sz=[["x",["left","right"],function(e){return e.reduce((e,r)=>e+SI(r),0)}],["y",["top","bottom"],function(e){return e.reduce((e,r)=>e+SM(r),0)}]];class S${constructor(e,r){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const s=SR(r),n=SB(s);for(const[r,i,a]of(this.rect={...e},this.width=e.width,this.height=e.height,Sz))for(const e of i)Object.defineProperty(this,e,{get:()=>{let i=a(s),o=n[r]-i;return this.rect[e]+o},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class SW{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(e=>{var r;return null==(r=this.target)?void 0:r.removeEventListener(...e)})},this.target=e}add(e,r,s){var n;null==(n=this.target)||n.addEventListener(e,r,s),this.listeners.push([e,r,s])}}function SH(e,r){let s=Math.abs(e.x),n=Math.abs(e.y);return"number"==typeof r?Math.sqrt(s**2+n**2)>r:"x"in r&&"y"in r?s>r.x&&n>r.y:"x"in r?s>r.x:"y"in r&&n>r.y}function SU(e){e.preventDefault()}function Sq(e){e.stopPropagation()}(w=R||(R={})).Click="click",w.DragStart="dragstart",w.Keydown="keydown",w.ContextMenu="contextmenu",w.Resize="resize",w.SelectionChange="selectionchange",w.VisibilityChange="visibilitychange",(_=T||(T={})).Space="Space",_.Down="ArrowDown",_.Right="ArrowRight",_.Left="ArrowLeft",_.Up="ArrowUp",_.Esc="Escape",_.Enter="Enter",_.Tab="Tab";let SK={start:[T.Space,T.Enter],cancel:[T.Esc],end:[T.Space,T.Enter,T.Tab]},SV=(e,r)=>{let{currentCoordinates:s}=r;switch(e.code){case T.Right:return{...s,x:s.x+25};case T.Left:return{...s,x:s.x-25};case T.Down:return{...s,y:s.y+25};case T.Up:return{...s,y:s.y-25}}};class SX{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:r}}=e;this.props=e,this.listeners=new SW(_2(r)),this.windowListeners=new SW(_Z(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(R.Resize,this.handleCancel),this.windowListeners.add(R.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(R.Keydown,this.handleKeyDown))}handleStart(){let{activeNode:e,onStart:r}=this.props,s=e.node.current;s&&function(e,r){if(void 0===r&&(r=SE),!e)return;let{top:s,left:n,bottom:i,right:a}=r(e);ST(e)&&(i<=0||a<=0||s>=window.innerHeight||n>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}(s),r(Sx)}handleKeyDown(e){if(Sn(e)){let{active:r,context:s,options:n}=this.props,{keyboardCodes:i=SK,coordinateGetter:a=SV,scrollBehavior:o="smooth"}=n,{code:l}=e;if(i.end.includes(l))return void this.handleEnd(e);if(i.cancel.includes(l))return void this.handleCancel(e);let{collisionRect:c}=s.current,d=c?{x:c.left,y:c.top}:Sx;this.referenceCoordinates||(this.referenceCoordinates=d);let u=a(e,{active:r,context:s.current,currentCoordinates:d});if(u){let r=Ss(u,d),n={x:0,y:0},{scrollableAncestors:i}=s.current;for(let s of i){let i=e.code,{isTop:a,isRight:l,isLeft:c,isBottom:d,maxScroll:h,minScroll:f}=SL(s),p=function(e){if(e===document.scrollingElement){let{innerWidth:e,innerHeight:r}=window;return{top:0,left:0,right:e,bottom:r,width:e,height:r}}let{top:r,left:s,right:n,bottom:i}=e.getBoundingClientRect();return{top:r,left:s,right:n,bottom:i,width:e.clientWidth,height:e.clientHeight}}(s),m={x:Math.min(i===T.Right?p.right-p.width/2:p.right,Math.max(i===T.Right?p.left:p.left+p.width/2,u.x)),y:Math.min(i===T.Down?p.bottom-p.height/2:p.bottom,Math.max(i===T.Down?p.top:p.top+p.height/2,u.y))},g=i===T.Right&&!l||i===T.Left&&!c,x=i===T.Down&&!d||i===T.Up&&!a;if(g&&m.x!==u.x){let e=s.scrollLeft+r.x,a=i===T.Right&&e<=h.x||i===T.Left&&e>=f.x;if(a&&!r.y)return void s.scrollTo({left:e,behavior:o});a?n.x=s.scrollLeft-e:n.x=i===T.Right?s.scrollLeft-h.x:s.scrollLeft-f.x,n.x&&s.scrollBy({left:-n.x,behavior:o});break}if(x&&m.y!==u.y){let e=s.scrollTop+r.y,a=i===T.Down&&e<=h.y||i===T.Up&&e>=f.y;if(a&&!r.x)return void s.scrollTo({top:e,behavior:o});a?n.y=s.scrollTop-e:n.y=i===T.Down?s.scrollTop-h.y:s.scrollTop-f.y,n.y&&s.scrollBy({top:-n.y,behavior:o});break}}this.handleMove(e,Sr(Ss(u,this.referenceCoordinates),n))}}}handleMove(e,r){let{onMove:s}=this.props;e.preventDefault(),s(r)}handleEnd(e){let{onEnd:r}=this.props;e.preventDefault(),this.detach(),r()}handleCancel(e){let{onCancel:r}=this.props;e.preventDefault(),this.detach(),r()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}function SY(e){return!!(e&&"distance"in e)}function SG(e){return!!(e&&"delay"in e)}SX.activators=[{eventName:"onKeyDown",handler:(e,r,s)=>{let{keyboardCodes:n=SK,onActivation:i}=r,{active:a}=s,{code:o}=e.nativeEvent;if(n.start.includes(o)){let r=a.activatorNode.current;return(!r||e.target===r)&&(e.preventDefault(),null==i||i({event:e.nativeEvent}),!0)}return!1}}];class SJ{constructor(e,r,s){var n;void 0===s&&(s=function(e){let{EventTarget:r}=_Z(e);return e instanceof r?e:_2(e)}(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=r;const{event:i}=e,{target:a}=i;this.props=e,this.events=r,this.document=_2(a),this.documentListeners=new SW(this.document),this.listeners=new SW(s),this.windowListeners=new SW(_Z(a)),this.initialCoordinates=null!=(n=Si(i))?n:Sx,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){let{events:e,props:{options:{activationConstraint:r,bypassActivationConstraint:s}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(R.Resize,this.handleCancel),this.windowListeners.add(R.DragStart,SU),this.windowListeners.add(R.VisibilityChange,this.handleCancel),this.windowListeners.add(R.ContextMenu,SU),this.documentListeners.add(R.Keydown,this.handleKeydown),r){if(null!=s&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(SG(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if(SY(r))return void this.handlePending(r)}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,r){let{active:s,onPending:n}=this.props;n(s,e,this.initialCoordinates,r)}handleStart(){let{initialCoordinates:e}=this,{onStart:r}=this.props;e&&(this.activated=!0,this.documentListeners.add(R.Click,Sq,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(R.SelectionChange,this.removeTextSelection),r(e))}handleMove(e){var r;let{activated:s,initialCoordinates:n,props:i}=this,{onMove:a,options:{activationConstraint:o}}=i;if(!n)return;let l=null!=(r=Si(e))?r:Sx,c=Ss(n,l);if(!s&&o){if(SY(o)){if(null!=o.tolerance&&SH(c,o.tolerance))return this.handleCancel();if(SH(c,o.distance))return this.handleStart()}return SG(o)&&SH(c,o.tolerance)?this.handleCancel():void this.handlePending(o,c)}e.cancelable&&e.preventDefault(),a(l)}handleEnd(){let{onAbort:e,onEnd:r}=this.props;this.detach(),this.activated||e(this.props.active),r()}handleCancel(){let{onAbort:e,onCancel:r}=this.props;this.detach(),this.activated||e(this.props.active),r()}handleKeydown(e){e.code===T.Esc&&this.handleCancel()}removeTextSelection(){var e;null==(e=this.document.getSelection())||e.removeAllRanges()}}let SZ={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class SQ extends SJ{constructor(e){const{event:r}=e;super(e,SZ,_2(r.target))}}SQ.activators=[{eventName:"onPointerDown",handler:(e,r)=>{let{nativeEvent:s}=e,{onActivation:n}=r;return!!s.isPrimary&&0===s.button&&(null==n||n({event:s}),!0)}}];(S=A||(A={}))[S.RightClick=2]="RightClick";(j=I||(I={}))[j.Pointer=0]="Pointer",j[j.DraggableRect=1]="DraggableRect",(k=M||(M={}))[k.TreeOrder=0]="TreeOrder",k[k.ReversedTreeOrder=1]="ReversedTreeOrder";let S0={x:{[D.Backward]:!1,[D.Forward]:!1},y:{[D.Backward]:!1,[D.Forward]:!1}};(C=F||(F={}))[C.Always=0]="Always",C[C.BeforeDragging=1]="BeforeDragging",C[C.WhileDragging=2]="WhileDragging",(P||(P={})).Optimized="optimized";let S1=new Map;function S2(e,r){return _6(s=>e?s||("function"==typeof r?r(e):e):null,[r,e])}function S5(e){let{callback:r,disabled:s}=e,n=_3(r),i=(0,$.useMemo)(()=>{if(s||"undefined"==typeof window||void 0===window.ResizeObserver)return;let{ResizeObserver:e}=window;return new e(n)},[s]);return(0,$.useEffect)(()=>()=>null==i?void 0:i.disconnect(),[i]),i}function S3(e){return new S$(SE(e),e)}function S4(e,r,s){void 0===r&&(r=S3);let[n,i]=(0,$.useState)(null);function a(){i(n=>{if(!e)return null;if(!1===e.isConnected){var i;return null!=(i=null!=n?n:s)?i:null}let a=r(e);return JSON.stringify(n)===JSON.stringify(a)?n:a})}let o=function(e){let{callback:r,disabled:s}=e,n=_3(r),i=(0,$.useMemo)(()=>{if(s||"undefined"==typeof window||void 0===window.MutationObserver)return;let{MutationObserver:e}=window;return new e(n)},[n,s]);return(0,$.useEffect)(()=>()=>null==i?void 0:i.disconnect(),[i]),i}({callback(r){if(e)for(let s of r){let{type:r,target:n}=s;if("childList"===r&&n instanceof HTMLElement&&n.contains(e)){a();break}}}}),l=S5({callback:a});return _5(()=>{a(),e?(null==l||l.observe(e),null==o||o.observe(document.body,{childList:!0,subtree:!0})):(null==l||l.disconnect(),null==o||o.disconnect())},[e]),n}let S6=[];function S7(e,r){void 0===r&&(r=[]);let s=(0,$.useRef)(null);return(0,$.useEffect)(()=>{s.current=null},r),(0,$.useEffect)(()=>{let r=e!==Sx;r&&!s.current&&(s.current=e),!r&&s.current&&(s.current=null)},[e]),s.current?Ss(e,s.current):Sx}function S8(e){return(0,$.useMemo)(()=>{let r,s;return e?(r=e.innerWidth,{top:0,left:0,right:r,bottom:s=e.innerHeight,width:r,height:s}):null},[e])}let S9=[],je=[{sensor:SQ,options:{}},{sensor:SX,options:{}}],jt={current:{}},jr={draggable:{measure:SD},droppable:{measure:SD,strategy:F.WhileDragging,frequency:P.Optimized},dragOverlay:{measure:SE}};class js extends Map{get(e){var r;return null!=e&&null!=(r=super.get(e))?r:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:r}=e;return!r})}getNodeFor(e){var r,s;return null!=(r=null==(s=this.get(e))?void 0:s.node.current)?r:void 0}}let jn={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new js,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Sm},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:jr,measureDroppableContainers:Sm,windowRect:null,measuringScheduled:!1},ji={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Sm,draggableNodes:new Map,over:null,measureDroppableContainers:Sm},ja=(0,$.createContext)(ji),jo=(0,$.createContext)(jn);function jl(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new js}}}function jc(e,r){switch(r.type){case E.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:r.initialCoordinates,active:r.active}};case E.DragMove:if(null==e.draggable.active)return e;return{...e,draggable:{...e.draggable,translate:{x:r.coordinates.x-e.draggable.initialCoordinates.x,y:r.coordinates.y-e.draggable.initialCoordinates.y}}};case E.DragEnd:case E.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case E.RegisterDroppable:{let{element:s}=r,{id:n}=s,i=new js(e.droppable.containers);return i.set(n,s),{...e,droppable:{...e.droppable,containers:i}}}case E.SetDroppableDisabled:{let{id:s,key:n,disabled:i}=r,a=e.droppable.containers.get(s);if(!a||n!==a.key)return e;let o=new js(e.droppable.containers);return o.set(s,{...a,disabled:i}),{...e,droppable:{...e.droppable,containers:o}}}case E.UnregisterDroppable:{let{id:s,key:n}=r,i=e.droppable.containers.get(s);if(!i||n!==i.key)return e;let a=new js(e.droppable.containers);return a.delete(s),{...e,droppable:{...e.droppable,containers:a}}}default:return e}}function jd(e){let{disabled:r}=e,{active:s,activatorEvent:n,draggableNodes:i}=(0,$.useContext)(ja),a=_8(n),o=_8(null==s?void 0:s.id);return(0,$.useEffect)(()=>{if(!r&&!n&&a&&null!=o){if(!Sn(a)||document.activeElement===a.target)return;let e=i.get(o);if(!e)return;let{activatorNode:r,node:s}=e;(r.current||s.current)&&requestAnimationFrame(()=>{for(let e of[r.current,s.current]){if(!e)continue;let r=e.matches(So)?e:e.querySelector(So);if(r){r.focus();break}}})}},[n,r,i,o,a]),null}let ju=(0,$.createContext)({...Sx,scaleX:1,scaleY:1});(N=L||(L={}))[N.Uninitialized=0]="Uninitialized",N[N.Initializing=1]="Initializing",N[N.Initialized=2]="Initialized";let jh=(0,$.memo)(function(e){var r,s,n,i,a,o,l,c;let d,u,h,f,p,m,g,x,{id:v,accessibility:y,autoScroll:b=!0,children:w,sensors:_=je,collisionDetection:S=Sj,measuring:j,modifiers:k,...C}=e,[N,R]=(0,$.useReducer)(jc,void 0,jl),[T,A]=function(){let[e]=(0,$.useState)(()=>new Set),r=(0,$.useCallback)(r=>(e.add(r),()=>e.delete(r)),[e]);return[(0,$.useCallback)(r=>{let{type:s,event:n}=r;e.forEach(e=>{var r;return null==(r=e[s])?void 0:r.call(e,n)})},[e]),r]}(),[P,O]=(0,$.useState)(L.Uninitialized),B=P===L.Initialized,{draggable:{active:z,nodes:W,translate:H},droppable:{containers:U}}=N,q=null!=z?W.get(z):null,K=(0,$.useRef)({initial:null,translated:null}),V=(0,$.useMemo)(()=>{var e;return null!=z?{id:z,data:null!=(e=null==q?void 0:q.data)?e:jt,rect:K}:null},[z,q]),X=(0,$.useRef)(null),[Y,G]=(0,$.useState)(null),[J,Z]=(0,$.useState)(null),Q=_4(C,Object.values(C)),et=Se("DndDescribedBy",v),er=(0,$.useMemo)(()=>U.getEnabled(),[U]),es=(0,$.useMemo)(()=>({draggable:{...jr.draggable,...null==j?void 0:j.draggable},droppable:{...jr.droppable,...null==j?void 0:j.droppable},dragOverlay:{...jr.dragOverlay,...null==j?void 0:j.dragOverlay}}),[null==j?void 0:j.draggable,null==j?void 0:j.droppable,null==j?void 0:j.dragOverlay]),{droppableRects:en,measureDroppableContainers:ei,measuringScheduled:ea}=function(e,r){let{dragging:s,dependencies:n,config:i}=r,[a,o]=(0,$.useState)(null),{frequency:l,measure:c,strategy:d}=i,u=(0,$.useRef)(e),h=function(){switch(d){case F.Always:return!1;case F.BeforeDragging:return s;default:return!s}}(),f=_4(h),p=(0,$.useCallback)(function(e){void 0===e&&(e=[]),f.current||o(r=>null===r?e:r.concat(e.filter(e=>!r.includes(e))))},[f]),m=(0,$.useRef)(null),g=_6(r=>{if(h&&!s)return S1;if(!r||r===S1||u.current!==e||null!=a){let r=new Map;for(let s of e){if(!s)continue;if(a&&a.length>0&&!a.includes(s.id)&&s.rect.current){r.set(s.id,s.rect.current);continue}let e=s.node.current,n=e?new S$(c(e),e):null;s.rect.current=n,n&&r.set(s.id,n)}return r}return r},[e,a,s,h,c]);return(0,$.useEffect)(()=>{u.current=e},[e]),(0,$.useEffect)(()=>{h||p()},[s,h]),(0,$.useEffect)(()=>{a&&a.length>0&&o(null)},[JSON.stringify(a)]),(0,$.useEffect)(()=>{h||"number"!=typeof l||null!==m.current||(m.current=setTimeout(()=>{p(),m.current=null},l))},[l,h,p,...n]),{droppableRects:g,measureDroppableContainers:p,measuringScheduled:null!=a}}(er,{dragging:B,dependencies:[H.x,H.y],config:es.droppable}),eo=_6(e=>{var r;return null==z?null:null!=(r=null!=p?p:e)?r:null},[p=(f=null!=z?W.get(z):void 0)?f.node.current:null,z]),el=(0,$.useMemo)(()=>J?Si(J):null,[J]),ec=(d=(null==Y?void 0:Y.autoScrollEnabled)===!1,u="object"==typeof b?!1===b.enabled:!1===b,h=B&&!d&&!u,"object"==typeof b?{...b,enabled:h}:{enabled:h}),ed=S2(eo,es.draggable.measure);!function(e){let{activeNode:r,measure:s,initialRect:n,config:i=!0}=e,a=(0,$.useRef)(!1),{x:o,y:l}="boolean"==typeof i?{x:i,y:i}:i;_5(()=>{if(!o&&!l||!r){a.current=!1;return}if(a.current||!n)return;let e=null==r?void 0:r.node.current;if(!e||!1===e.isConnected)return;let i=Sk(s(e),n);if(o||(i.x=0),l||(i.y=0),a.current=!0,Math.abs(i.x)>0||Math.abs(i.y)>0){let r=ST(e);r&&r.scrollBy({top:i.y,left:i.x})}},[r,o,l,n,s])}({activeNode:null!=z?W.get(z):null,config:ec.layoutShiftCompensation,initialRect:ed,measure:es.draggable.measure});let eu=S4(eo,es.draggable.measure,ed),eh=S4(eo?eo.parentElement:null),ef=(0,$.useRef)({activatorEvent:null,active:null,activeNode:eo,collisionRect:null,collisions:null,droppableRects:en,draggableNodes:W,draggingNode:null,draggingNodeRect:null,droppableContainers:U,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ep=U.getNodeFor(null==(r=ef.current.over)?void 0:r.id),em=function(e){let{measure:r}=e,[s,n]=(0,$.useState)(null),i=S5({callback:(0,$.useCallback)(e=>{for(let{target:s}of e)if(_0(s)){n(e=>{let n=r(s);return e?{...e,width:n.width,height:n.height}:n});break}},[r])}),[a,o]=_7((0,$.useCallback)(e=>{let s=function(e){if(!e)return null;if(e.children.length>1)return e;let r=e.children[0];return _0(r)?r:e}(e);null==i||i.disconnect(),s&&(null==i||i.observe(s)),n(s?r(s):null)},[r,i]));return(0,$.useMemo)(()=>({nodeRef:a,rect:s,setRef:o}),[s,a,o])}({measure:es.dragOverlay.measure}),eg=null!=(s=em.nodeRef.current)?s:eo,ex=B?null!=(n=em.rect)?n:eu:null,ev=!!(em.nodeRef.current&&em.rect),ey=(m=S2(a=ev?null:eu),Sk(a,m)),eb=S8(eg?_Z(eg):null),ew=(o=B?null!=ep?ep:eo:null,g=(0,$.useRef)(o),x=_6(e=>o?e&&e!==S6&&o&&g.current&&o.parentNode===g.current.parentNode?e:SR(o):S6,[o]),(0,$.useEffect)(()=>{g.current=o},[o]),x),e_=function(e,r){void 0===r&&(r=SE);let[s]=e,n=S8(s?_Z(s):null),[i,a]=(0,$.useState)(S9);function o(){a(()=>e.length?e.map(e=>SP(e)?n:new S$(r(e),e)):S9)}let l=S5({callback:o});return _5(()=>{null==l||l.disconnect(),o(),e.forEach(e=>null==l?void 0:l.observe(e))},[e]),i}(ew),eS=function(e,r){let{transform:s,...n}=r;return null!=e&&e.length?e.reduce((e,r)=>r({transform:e,...n}),s):s}(k,{transform:{x:H.x-ey.x,y:H.y-ey.y,scaleX:1,scaleY:1},activatorEvent:J,active:V,activeNodeRect:eu,containerNodeRect:eh,draggingNodeRect:ex,over:ef.current.over,overlayNodeRect:em.rect,scrollableAncestors:ew,scrollableAncestorRects:e_,windowRect:eb}),ej=el?Sr(el,H):null,ek=function(e){let[r,s]=(0,$.useState)(null),n=(0,$.useRef)(e),i=(0,$.useCallback)(e=>{let r=SA(e.target);r&&s(e=>e?(e.set(r,SF(r)),new Map(e)):null)},[]);return(0,$.useEffect)(()=>{let r=n.current;if(e!==r){a(r);let o=e.map(e=>{let r=SA(e);return r?(r.addEventListener("scroll",i,{passive:!0}),[r,SF(r)]):null}).filter(e=>null!=e);s(o.length?new Map(o):null),n.current=e}return()=>{a(e),a(r)};function a(e){e.forEach(e=>{let r=SA(e);null==r||r.removeEventListener("scroll",i)})}},[i,e]),(0,$.useMemo)(()=>e.length?r?Array.from(r.values()).reduce((e,r)=>Sr(e,r),Sx):SB(e):Sx,[e,r])}(ew),eC=S7(ek),eN=S7(ek,[eu]),eE=Sr(eS,eC),eD=ex?SC(ex,eS):null,eR=V&&eD?S({active:V,collisionRect:eD,droppableRects:en,droppableContainers:er,pointerCoordinates:ej}):null,eT=S_(eR,"id"),[eA,eI]=(0,$.useState)(null),eM=(l=ev?eS:Sr(eS,eN),c=null!=(i=null==eA?void 0:eA.rect)?i:null,{...l,scaleX:c&&eu?c.width/eu.width:1,scaleY:c&&eu?c.height/eu.height:1}),eF=(0,$.useRef)(null),eP=(0,$.useCallback)((e,r)=>{let{sensor:s,options:n}=r;if(null==X.current)return;let i=W.get(X.current);if(!i)return;let a=e.nativeEvent,o=new s({active:X.current,activeNode:i,event:a,options:n,context:ef,onAbort(e){if(!W.get(e))return;let{onDragAbort:r}=Q.current,s={id:e};null==r||r(s),T({type:"onDragAbort",event:s})},onPending(e,r,s,n){if(!W.get(e))return;let{onDragPending:i}=Q.current,a={id:e,constraint:r,initialCoordinates:s,offset:n};null==i||i(a),T({type:"onDragPending",event:a})},onStart(e){let r=X.current;if(null==r)return;let s=W.get(r);if(!s)return;let{onDragStart:n}=Q.current,i={activatorEvent:a,active:{id:r,data:s.data,rect:K}};(0,ee.unstable_batchedUpdates)(()=>{null==n||n(i),O(L.Initializing),R({type:E.DragStart,initialCoordinates:e,active:r}),T({type:"onDragStart",event:i}),G(eF.current),Z(a)})},onMove(e){R({type:E.DragMove,coordinates:e})},onEnd:l(E.DragEnd),onCancel:l(E.DragCancel)});function l(e){return async function(){let{active:r,collisions:s,over:n,scrollAdjustedTranslate:i}=ef.current,o=null;if(r&&i){let{cancelDrop:l}=Q.current;o={activatorEvent:a,active:r,collisions:s,delta:i,over:n},e===E.DragEnd&&"function"==typeof l&&await Promise.resolve(l(o))&&(e=E.DragCancel)}X.current=null,(0,ee.unstable_batchedUpdates)(()=>{R({type:e}),O(L.Uninitialized),eI(null),G(null),Z(null),eF.current=null;let r=e===E.DragEnd?"onDragEnd":"onDragCancel";if(o){let e=Q.current[r];null==e||e(o),T({type:r,event:o})}})}}eF.current=o},[W]),eL=(0,$.useCallback)((e,r)=>(s,n)=>{let i=s.nativeEvent,a=W.get(n);null!==X.current||!a||i.dndKit||i.defaultPrevented||!0===e(s,r.options,{active:a})&&(i.dndKit={capturedBy:r.sensor},X.current=n,eP(s,r))},[W,eP]),eO=(0,$.useMemo)(()=>_.reduce((e,r)=>{let{sensor:s}=r;return[...e,...s.activators.map(e=>({eventName:e.eventName,handler:eL(e.handler,r)}))]},[]),[_,eL]);(0,$.useEffect)(()=>{if(!_Y)return;let e=_.map(e=>{let{sensor:r}=e;return null==r.setup?void 0:r.setup()});return()=>{for(let r of e)null==r||r()}},_.map(e=>{let{sensor:r}=e;return r})),_5(()=>{eu&&P===L.Initializing&&O(L.Initialized)},[eu,P]),(0,$.useEffect)(()=>{let{onDragMove:e}=Q.current,{active:r,activatorEvent:s,collisions:n,over:i}=ef.current;if(!r||!s)return;let a={active:r,activatorEvent:s,collisions:n,delta:{x:eE.x,y:eE.y},over:i};(0,ee.unstable_batchedUpdates)(()=>{null==e||e(a),T({type:"onDragMove",event:a})})},[eE.x,eE.y]),(0,$.useEffect)(()=>{let{active:e,activatorEvent:r,collisions:s,droppableContainers:n,scrollAdjustedTranslate:i}=ef.current;if(!e||null==X.current||!r||!i)return;let{onDragOver:a}=Q.current,o=n.get(eT),l=o&&o.rect.current?{id:o.id,rect:o.rect.current,data:o.data,disabled:o.disabled}:null,c={active:e,activatorEvent:r,collisions:s,delta:{x:i.x,y:i.y},over:l};(0,ee.unstable_batchedUpdates)(()=>{eI(l),null==a||a(c),T({type:"onDragOver",event:c})})},[eT]),_5(()=>{ef.current={activatorEvent:J,active:V,activeNode:eo,collisionRect:eD,collisions:eR,droppableRects:en,draggableNodes:W,draggingNode:eg,draggingNodeRect:ex,droppableContainers:U,over:eA,scrollableAncestors:ew,scrollAdjustedTranslate:eE},K.current={initial:ex,translated:eD}},[V,eo,eR,eD,W,eg,ex,en,U,eA,ew,eE]),function(e){let r,{acceleration:s,activator:n=I.Pointer,canScroll:i,draggingRect:a,enabled:o,interval:l=5,order:c=M.TreeOrder,pointerCoordinates:d,scrollableAncestors:u,scrollableAncestorRects:h,delta:f,threshold:p}=e,m=function(e){let{delta:r,disabled:s}=e,n=_8(r);return _6(e=>{if(s||!n||!e)return S0;let i={x:Math.sign(r.x-n.x),y:Math.sign(r.y-n.y)};return{x:{[D.Backward]:e.x[D.Backward]||-1===i.x,[D.Forward]:e.x[D.Forward]||1===i.x},y:{[D.Backward]:e.y[D.Backward]||-1===i.y,[D.Forward]:e.y[D.Forward]||1===i.y}}},[s,r,n])}({delta:f,disabled:!o}),[g,x]=(r=(0,$.useRef)(null),[(0,$.useCallback)((e,s)=>{r.current=setInterval(e,s)},[]),(0,$.useCallback)(()=>{null!==r.current&&(clearInterval(r.current),r.current=null)},[])]),v=(0,$.useRef)({x:0,y:0}),y=(0,$.useRef)({x:0,y:0}),b=(0,$.useMemo)(()=>{switch(n){case I.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case I.DraggableRect:return a}},[n,a,d]),w=(0,$.useRef)(null),_=(0,$.useCallback)(()=>{let e=w.current;if(!e)return;let r=v.current.x*y.current.x,s=v.current.y*y.current.y;e.scrollBy(r,s)},[]),S=(0,$.useMemo)(()=>c===M.TreeOrder?[...u].reverse():u,[c,u]);(0,$.useEffect)(()=>{if(!o||!u.length||!b)return void x();for(let e of S){if((null==i?void 0:i(e))===!1)continue;let r=h[u.indexOf(e)];if(!r)continue;let{direction:n,speed:a}=function(e,r,s,n,i){let{top:a,left:o,right:l,bottom:c}=s;void 0===n&&(n=10),void 0===i&&(i=SO);let{isTop:d,isBottom:u,isLeft:h,isRight:f}=SL(e),p={x:0,y:0},m={x:0,y:0},g={height:r.height*i.y,width:r.width*i.x};return!d&&a<=r.top+g.height?(p.y=D.Backward,m.y=n*Math.abs((r.top+g.height-a)/g.height)):!u&&c>=r.bottom-g.height&&(p.y=D.Forward,m.y=n*Math.abs((r.bottom-g.height-c)/g.height)),!f&&l>=r.right-g.width?(p.x=D.Forward,m.x=n*Math.abs((r.right-g.width-l)/g.width)):!h&&o<=r.left+g.width&&(p.x=D.Backward,m.x=n*Math.abs((r.left+g.width-o)/g.width)),{direction:p,speed:m}}(e,r,b,s,p);for(let e of["x","y"])m[e][n[e]]||(a[e]=0,n[e]=0);if(a.x>0||a.y>0){x(),w.current=e,g(_,l),v.current=a,y.current=n;return}}v.current={x:0,y:0},y.current={x:0,y:0},x()},[s,_,i,x,o,l,JSON.stringify(b),JSON.stringify(m),g,u,S,h,JSON.stringify(p)])}({...ec,delta:H,draggingRect:eD,pointerCoordinates:ej,scrollableAncestors:ew,scrollableAncestorRects:e_});let eB=(0,$.useMemo)(()=>({active:V,activeNode:eo,activeNodeRect:eu,activatorEvent:J,collisions:eR,containerNodeRect:eh,dragOverlay:em,draggableNodes:W,droppableContainers:U,droppableRects:en,over:eA,measureDroppableContainers:ei,scrollableAncestors:ew,scrollableAncestorRects:e_,measuringConfiguration:es,measuringScheduled:ea,windowRect:eb}),[V,eo,eu,J,eR,eh,em,W,U,en,eA,ei,ew,e_,es,ea,eb]),ez=(0,$.useMemo)(()=>({activatorEvent:J,activators:eO,active:V,activeNodeRect:eu,ariaDescribedById:{draggable:et},dispatch:R,draggableNodes:W,over:eA,measureDroppableContainers:ei}),[J,eO,V,eu,R,et,W,eA,ei]);return $.default.createElement(Su.Provider,{value:A},$.default.createElement(ja.Provider,{value:ez},$.default.createElement(jo.Provider,{value:eB},$.default.createElement(ju.Provider,{value:eM},w)),$.default.createElement(jd,{disabled:(null==y?void 0:y.restoreFocus)===!1})),$.default.createElement(Sp,{...y,hiddenTextDescribedById:et}))}),jf=(0,$.createContext)(null),jp="button",jm={timeout:25},jg={position:"fixed",touchAction:"none"},jx=e=>Sn(e)?"transform 250ms ease":void 0;function jv(e,r,s){let n=e.slice();return n.splice(s<0?n.length+s:s,0,n.splice(r,1)[0]),n}function jy(e){return null!==e&&e>=0}(e,r)=>{let{as:s,activatorEvent:n,adjustScale:i,children:a,className:o,rect:l,style:c,transform:d,transition:u=jx}=e;if(!l)return null;let h=i?d:{...d,scaleX:1,scaleY:1},f={...jg,width:l.width,height:l.height,top:l.top,left:l.left,transform:Sa.Transform.toString(h),transformOrigin:i&&n?function(e,r){let s=Si(e);if(!s)return"0 0";let n={x:(s.x-r.left)/r.width*100,y:(s.y-r.top)/r.height*100};return n.x+"% "+n.y+"%"}(n,l):void 0,transition:"function"==typeof u?u(n):u,...c};return $.default.createElement(s,{className:o,style:f,ref:r},a)},x={styles:{active:{opacity:"0"}}};let jb=e=>{let{rects:r,activeIndex:s,overIndex:n,index:i}=e,a=jv(r,n,s),o=r[i],l=a[i];return l&&o?{x:l.left-o.left,y:l.top-o.top,scaleX:l.width/o.width,scaleY:l.height/o.height}:null},jw={scaleX:1,scaleY:1},j_=e=>{var r,s,n,i;let a,o,l,{activeIndex:c,activeNodeRect:d,index:u,rects:h,overIndex:f}=e,p=null!=(r=h[c])?r:d;if(!p)return null;if(u===c){let e=h[f];return e?{x:0,y:c<f?e.top+e.height-(p.top+p.height):e.top-p.top,...jw}:null}let m=(s=h,n=u,i=c,a=s[n],o=s[n-1],l=s[n+1],a?i<n?o?a.top-(o.top+o.height):l?l.top-(a.top+a.height):0:l?l.top-(a.top+a.height):o?a.top-(o.top+o.height):0:0);return u>c&&u<=f?{x:0,y:-p.height-m,...jw}:u<c&&u>=f?{x:0,y:p.height+m,...jw}:{x:0,y:0,...jw}},jS="Sortable",jj=$.default.createContext({activeIndex:-1,containerId:jS,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:jb,disabled:{draggable:!1,droppable:!1}});function jk(e){let{children:r,id:s,items:n,strategy:i=jb,disabled:a=!1}=e,{active:o,dragOverlay:l,droppableRects:c,over:d,measureDroppableContainers:u}=(0,$.useContext)(jo),h=Se(jS,s),f=null!==l.rect,p=(0,$.useMemo)(()=>n.map(e=>"object"==typeof e&&"id"in e?e.id:e),[n]),m=null!=o,g=o?p.indexOf(o.id):-1,x=d?p.indexOf(d.id):-1,v=(0,$.useRef)(p),y=!function(e,r){if(e===r)return!0;if(e.length!==r.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==r[s])return!1;return!0}(p,v.current),b=-1!==x&&-1===g||y,w="boolean"==typeof a?{draggable:a,droppable:a}:a;_5(()=>{y&&m&&u(p)},[y,p,m,u]),(0,$.useEffect)(()=>{v.current=p},[p]);let _=(0,$.useMemo)(()=>({activeIndex:g,containerId:h,disabled:w,disableTransforms:b,items:p,overIndex:x,useDragOverlay:f,sortedRects:p.reduce((e,r,s)=>{let n=c.get(r);return n&&(e[s]=n),e},Array(p.length)),strategy:i}),[g,h,w.draggable,w.droppable,b,p,x,c,f,i]);return $.default.createElement(jj.Provider,{value:_},r)}let jC=e=>{let{id:r,items:s,activeIndex:n,overIndex:i}=e;return jv(s,n,i).indexOf(r)},jN=e=>{let{containerId:r,isSorting:s,wasDragging:n,index:i,items:a,newIndex:o,previousItems:l,previousContainerId:c,transition:d}=e;return!!d&&!!n&&(l===a||i!==o)&&(!!s||o!==i&&r===c)},jE={duration:200,easing:"ease"},jD="transform",jR=Sa.Transition.toString({property:jD,duration:0,easing:"linear"}),jT={roleDescription:"sortable"};function jA(e){if(!e)return!1;let r=e.data.current;return!!r&&"sortable"in r&&"object"==typeof r.sortable&&"containerId"in r.sortable&&"items"in r.sortable&&"index"in r.sortable}let jI=[T.Down,T.Right,T.Up,T.Left],jM=(e,r)=>{let{context:{active:s,collisionRect:n,droppableRects:i,droppableContainers:a,over:o,scrollableAncestors:l}}=r;if(jI.includes(e.code)){if(e.preventDefault(),!s||!n)return;let r=[];a.getEnabled().forEach(s=>{if(!s||null!=s&&s.disabled)return;let a=i.get(s.id);if(a)switch(e.code){case T.Down:n.top<a.top&&r.push(s);break;case T.Up:n.top>a.top&&r.push(s);break;case T.Left:n.left>a.left&&r.push(s);break;case T.Right:n.left<a.left&&r.push(s)}});let u=(e=>{let{collisionRect:r,droppableRects:s,droppableContainers:n}=e,i=Sw(r),a=[];for(let e of n){let{id:r}=e,n=s.get(r);if(n){let s=Sw(n),o=Number((i.reduce((e,r,n)=>e+Sv(s[n],r),0)/4).toFixed(4));a.push({id:r,data:{droppableContainer:e,value:o}})}}return a.sort(Sy)})({active:s,collisionRect:n,droppableRects:i,droppableContainers:r,pointerCoordinates:null}),h=S_(u,"id");if(h===(null==o?void 0:o.id)&&u.length>1&&(h=u[1].id),null!=h){let e=a.get(s.id),r=a.get(h),o=r?i.get(r.id):null,u=null==r?void 0:r.node.current;if(u&&o&&e&&r){var c,d;let s=SR(u).some((e,r)=>l[r]!==e),i=jF(e,r),a=(c=e,d=r,!!jA(c)&&!!jA(d)&&!!jF(c,d)&&c.data.current.sortable.index<d.data.current.sortable.index),h=s||!i?{x:0,y:0}:{x:a?n.width-o.width:0,y:a?n.height-o.height:0},f={x:o.left,y:o.top};return h.x&&h.y?f:Ss(f,h)}}}};function jF(e,r){return!!jA(e)&&!!jA(r)&&e.data.current.sortable.containerId===r.data.current.sortable.containerId}function jP({executor:e,executorMode:r,locateQuery:s=null,locateMatch:n=!1,keyboardSelected:i=!1,isOpen:a,onOpenChange:o,onStart:l,onStop:c,onUpdate:d,onDelete:u,onProcessFinished:h}){let f,p,m,g,x,v,y,[b,w]=(0,$.useState)(!1),[_,S]=(0,$.useState)(e.currentProcessId??e.lastProcessId),j=(0,$.useRef)(!1),k=(0,$.useRef)(e.currentProcessId),{attributes:C,listeners:N,setNodeRef:D,transform:R,transition:T,isDragging:A}=function(e){var r,s,n,i;let{animateLayoutChanges:a=jN,attributes:o,disabled:l,data:c,getNewIndex:d=jC,id:u,strategy:h,resizeObserverConfig:f,transition:p=jE}=e,{items:m,containerId:g,activeIndex:x,disabled:v,disableTransforms:y,sortedRects:b,overIndex:w,useDragOverlay:_,strategy:S}=(0,$.useContext)(jj),j=(r=l,s=v,"boolean"==typeof r?{draggable:r,droppable:!1}:{draggable:null!=(n=null==r?void 0:r.draggable)?n:s.draggable,droppable:null!=(i=null==r?void 0:r.droppable)?i:s.droppable}),k=m.indexOf(u),C=(0,$.useMemo)(()=>({sortable:{containerId:g,index:k,items:m},...c}),[g,c,k,m]),N=(0,$.useMemo)(()=>m.slice(m.indexOf(u)),[m,u]),{rect:D,node:R,isOver:T,setNodeRef:A}=function(e){let{data:r,disabled:s=!1,id:n,resizeObserverConfig:i}=e,a=Se("Droppable"),{active:o,dispatch:l,over:c,measureDroppableContainers:d}=(0,$.useContext)(ja),u=(0,$.useRef)({disabled:s}),h=(0,$.useRef)(!1),f=(0,$.useRef)(null),p=(0,$.useRef)(null),{disabled:m,updateMeasurementsFor:g,timeout:x}={...jm,...i},v=_4(null!=g?g:n),y=S5({callback:(0,$.useCallback)(()=>{if(!h.current){h.current=!0;return}null!=p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{d(Array.isArray(v.current)?v.current:[v.current]),p.current=null},x)},[x]),disabled:m||!o}),[b,w]=_7((0,$.useCallback)((e,r)=>{y&&(r&&(y.unobserve(r),h.current=!1),e&&y.observe(e))},[y])),_=_4(r);return(0,$.useEffect)(()=>{y&&b.current&&(y.disconnect(),h.current=!1,y.observe(b.current))},[b,y]),(0,$.useEffect)(()=>(l({type:E.RegisterDroppable,element:{id:n,key:a,disabled:s,node:b,rect:f,data:_}}),()=>l({type:E.UnregisterDroppable,key:a,id:n})),[n]),(0,$.useEffect)(()=>{s!==u.current.disabled&&(l({type:E.SetDroppableDisabled,id:n,key:a,disabled:s}),u.current.disabled=s)},[n,a,s,l]),{active:o,rect:f,isOver:(null==c?void 0:c.id)===n,node:b,over:c,setNodeRef:w}}({id:u,data:C,disabled:j.droppable,resizeObserverConfig:{updateMeasurementsFor:N,...f}}),{active:I,activatorEvent:M,activeNodeRect:F,attributes:P,setNodeRef:L,listeners:O,isDragging:B,over:z,setActivatorNodeRef:W,transform:H}=function(e){let{id:r,data:s,disabled:n=!1,attributes:i}=e,a=Se("Draggable"),{activators:o,activatorEvent:l,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:f}=(0,$.useContext)(ja),{role:p=jp,roleDescription:m="draggable",tabIndex:g=0}=null!=i?i:{},x=(null==c?void 0:c.id)===r,v=(0,$.useContext)(x?ju:jf),[y,b]=_7(),[w,_]=_7(),S=(0,$.useMemo)(()=>o.reduce((e,s)=>{let{eventName:n,handler:i}=s;return e[n]=e=>{i(e,r)},e},{}),[o,r]),j=_4(s);return _5(()=>(h.set(r,{id:r,key:a,node:y,activatorNode:w,data:j}),()=>{let e=h.get(r);e&&e.key===a&&h.delete(r)}),[h,r]),{active:c,activatorEvent:l,activeNodeRect:d,attributes:(0,$.useMemo)(()=>({role:p,tabIndex:g,"aria-disabled":n,"aria-pressed":!!x&&p===jp||void 0,"aria-roledescription":m,"aria-describedby":u.draggable}),[n,p,g,x,m,u.draggable]),isDragging:x,listeners:n?void 0:S,node:y,over:f,setNodeRef:b,setActivatorNodeRef:_,transform:v}}({id:u,data:C,attributes:{...jT,...o},disabled:j.draggable}),U=function(){for(var e=arguments.length,r=Array(e),s=0;s<e;s++)r[s]=arguments[s];return(0,$.useMemo)(()=>e=>{r.forEach(r=>r(e))},r)}(A,L),q=!!I,K=q&&!y&&jy(x)&&jy(w),V=!_&&B,X=V&&K?H:null,Y=K?null!=X?X:(null!=h?h:S)({rects:b,activeNodeRect:F,activeIndex:x,overIndex:w,index:k}):null,G=jy(x)&&jy(w)?d({id:u,items:m,activeIndex:x,overIndex:w}):k,J=null==I?void 0:I.id,Z=(0,$.useRef)({activeId:J,items:m,newIndex:G,containerId:g}),Q=m!==Z.current.items,ee=a({active:I,containerId:g,isDragging:B,isSorting:q,id:u,index:k,items:m,newIndex:Z.current.newIndex,previousItems:Z.current.items,previousContainerId:Z.current.containerId,transition:p,wasDragging:null!=Z.current.activeId}),et=function(e){let{disabled:r,index:s,node:n,rect:i}=e,[a,o]=(0,$.useState)(null),l=(0,$.useRef)(s);return _5(()=>{if(!r&&s!==l.current&&n.current){let e=i.current;if(e){let r=SE(n.current,{ignoreTransform:!0}),s={x:e.left-r.left,y:e.top-r.top,scaleX:e.width/r.width,scaleY:e.height/r.height};(s.x||s.y)&&o(s)}}s!==l.current&&(l.current=s)},[r,s,n,i]),(0,$.useEffect)(()=>{a&&o(null)},[a]),a}({disabled:!ee,index:k,node:R,rect:D});return(0,$.useEffect)(()=>{q&&Z.current.newIndex!==G&&(Z.current.newIndex=G),g!==Z.current.containerId&&(Z.current.containerId=g),m!==Z.current.items&&(Z.current.items=m)},[q,G,g,m]),(0,$.useEffect)(()=>{if(J===Z.current.activeId)return;if(null!=J&&null==Z.current.activeId){Z.current.activeId=J;return}let e=setTimeout(()=>{Z.current.activeId=J},50);return()=>clearTimeout(e)},[J]),{active:I,activeIndex:x,attributes:P,data:C,rect:D,index:k,newIndex:G,items:m,isOver:T,isSorting:q,isDragging:B,listeners:O,node:R,overIndex:w,over:z,setNodeRef:U,setActivatorNodeRef:W,setDroppableNodeRef:A,setDraggableNodeRef:L,transform:null!=et?et:Y,transition:et||Q&&Z.current.newIndex===k?jR:(!V||Sn(M))&&p&&(q||ee)?Sa.Transition.toString({...p,property:jD}):void 0}}({id:e.id}),I={transform:Sa.Translate.toString(R),transition:T,zIndex:A?50:void 0,position:A?"relative":void 0,opacity:A?1:void 0},{logs:M,status:F,exitCode:P,isPty:L,replayingHistory:O,sendInput:B,sendResize:H}=(f=function(){let e=(0,$.useContext)(_V);if(!e)throw Error("useExecutorLogsStore must be used within ExecutorLogsProvider");return e}(),p=(0,$.useCallback)(e=>{if(!_)return()=>{};f.subscribeProcess(_);let r=f.onProcessChange(_,e);return()=>{r(),f.unsubscribeProcess(_)}},[_,r,f]),m=(0,$.useCallback)(()=>_?f.getProcessState(_):null,[_,f]),g=(0,$.useSyncExternalStore)(p,m,m),x=(0,$.useCallback)(()=>{},[]),v=(0,$.useCallback)(e=>{_&&f.sendInput(_,e)},[_,f]),y=(0,$.useCallback)((e,r)=>{_&&f.sendResize(_,e,r)},[_,f]),{logs:g?.logs??[],status:g?.status??"closed",exitCode:g?.exitCode??null,isPty:g?.isPty??!1,replayingHistory:g?.replayingHistory??!0,clearLogs:x,sendInput:v,sendResize:y});(0,$.useEffect)(()=>(console.log("[diag:mux] ExecutorItem MOUNT",e.id,"localProcessId=",_),()=>console.log("[diag:mux] ExecutorItem UNMOUNT",e.id)),[]),(0,$.useEffect)(()=>{console.log("[diag:mux] localProcessId →",_,"executor=",e.id)},[_,e.id]),(0,$.useEffect)(()=>{let r=k.current;k.current=e.currentProcessId,e.currentProcessId&&e.currentProcessId!==r&&(S(e.currentProcessId),j.current=!1,o(!0))},[e.currentProcessId,o]),(0,$.useEffect)(()=>{e.currentProcessId||e.lastProcessId&&S(r=>r??e.lastProcessId)},[e.currentProcessId,e.lastProcessId]),(0,$.useEffect)(()=>{"closed"!==F||null===P||j.current||(j.current=!0,console.log(`[diag:remote-stop] ${new Date().toISOString()} executor-item marking finished executorId=${e.id} processId=${_} exitCode=${P} — removing from runningProcesses (button → Start)`),h(_))},[F,P,_,h]);let U=async()=>{console.log(`[ExecutorItem] Starting executor ${e.id}`),j.current=!1;let r=await l();console.log(`[ExecutorItem] Got processId: ${r}`),r&&(S(r),o(!0))},q=async()=>{await c(_||void 0)},K=e.isRunning,V=e.isDisabled,X=e.lastStartedAt?new Date(e.lastStartedAt).toLocaleString(void 0,{dateStyle:"short",timeStyle:"short"}):null;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(gV,{open:a,onOpenChange:o,children:(0,z.jsxs)("div",{ref:D,style:I,"data-locate-id":e.id,className:(0,eb.cn)("border rounded-lg",A&&"shadow-lg bg-background",null!==s&&!n&&"opacity-40",null!==s&&n&&"bg-muted/50",i&&"border-primary/60"),children:[(0,z.jsx)(gX,{asChild:!0,children:(0,z.jsxs)("div",{className:"group flex items-center justify-between p-3 cursor-pointer hover:bg-muted/50",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)("button",{type:"button",className:"cursor-grab touch-none text-muted-foreground hover:text-foreground",...C,...N,onClick:e=>e.stopPropagation(),children:(0,z.jsx)(dW,{className:"h-4 w-4"})}),a?(0,z.jsx)(n6,{className:"h-4 w-4"}):(0,z.jsx)(nV,{className:"h-4 w-4"}),(0,z.jsx)("span",{className:(0,eb.cn)("font-medium",V&&"text-muted-foreground line-through"),children:null!==s&&n?(0,z.jsx)(dN,{text:e.name,query:s}):e.name}),V?(0,z.jsxs)(so,{variant:"outline",className:"text-muted-foreground border-muted-foreground/40 gap-1",children:[(0,z.jsx)(gJ,{className:"h-3 w-3"}),"Disabled"]}):(0,z.jsx)(so,{variant:K?"default":"secondary",className:(0,eb.cn)(K&&"bg-green-600 hover:bg-green-600"),children:K?"Running":null!==P?0===P?"Completed":"Failed":"Stopped"})]}),(0,z.jsxs)("div",{className:"flex items-center gap-2",onClick:e=>e.stopPropagation(),children:[X&&(0,z.jsxs)("span",{className:"text-xs text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity",title:new Date(e.lastStartedAt).toLocaleString(),children:["Last run: ",X]}),K?(0,z.jsxs)(W.Button,{size:"sm",variant:"destructive",onClick:q,"data-locate-action":!0,className:"w-20 border border-destructive",children:[(0,z.jsx)(lG,{className:"h-3 w-3 mr-1"}),"Stop"]}):(0,z.jsxs)(W.Button,{size:"sm",onClick:U,disabled:V,title:V?"Executor is disabled":void 0,"data-locate-action":!0,className:"w-20",children:[(0,z.jsx)(rf,{className:"h-3 w-3 mr-1"}),"Start"]}),(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)(W.Button,{size:"icon",variant:"ghost",className:"h-8 w-8",children:(0,z.jsx)(gG,{className:"h-4 w-4"})})}),(0,z.jsxs)(o1,{align:"end",children:[(0,z.jsxs)(o2,{onClick:()=>w(!0),children:[(0,z.jsx)(rx,{className:"h-4 w-4 mr-2"}),"Edit"]}),(0,z.jsx)(o2,{onClick:()=>d({target:r??"local",disabled:!V}),children:V?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(sZ,{className:"h-4 w-4 mr-2"}),"Enable"]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(gJ,{className:"h-4 w-4 mr-2"}),"Disable"]})}),(0,z.jsxs)(o2,{onClick:u,className:"text-destructive",children:[(0,z.jsx)(rd,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})]})}),(0,z.jsx)(gY,{children:(0,z.jsxs)("div",{className:"px-3 pb-3",children:[(0,z.jsx)("div",{className:"text-xs text-muted-foreground mb-2 font-mono",children:"prompt"===e.executor_type?`${e.prompt_provider??"claude"} → ${e.command}`:`$ ${e.command}`}),(0,z.jsx)(_H,{logs:M,isPty:L,onInput:B,onResize:H,muteInput:O,processId:_,executorId:e.id,target:r??"local",status:F,exitCode:P})]})})]})}),(0,z.jsx)(_q,{open:b,onOpenChange:w,executor:e,onSubmit:async e=>{await d(e)}})]})}function jL({targets:e,activeTarget:r,onTargetChange:s,onAddRemote:n,disabled:i}){if(e.length<=2)return(0,z.jsx)("div",{className:"inline-flex items-center rounded-md border bg-muted/50 px-0.5 text-xs",children:e.map(e=>{let n=e.icon;return(0,z.jsxs)("button",{onClick:()=>s(e.id),disabled:i,className:(0,eb.cn)("inline-flex items-center gap-1 rounded-sm px-2 py-0.5 transition-colors",r===e.id?"bg-primary text-primary-foreground font-medium shadow-sm":"text-muted-foreground hover:text-foreground",i&&"opacity-50 cursor-not-allowed"),children:[n&&(0,z.jsx)(n,{className:"h-3 w-3"}),e.label]},e.id)})});let a=e.find(e=>e.id===r)??e[0],o=a?.icon;return(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsxs)("button",{disabled:i,className:(0,eb.cn)("inline-flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-0.5 text-xs font-medium transition-colors hover:bg-muted",i&&"opacity-50 cursor-not-allowed"),children:[o&&(0,z.jsx)(o,{className:"h-3 w-3"}),a?.label??"Local",(0,z.jsx)(n6,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,z.jsxs)(o1,{align:"start",children:[(0,z.jsx)(o3,{value:r,onValueChange:s,children:e.map(e=>{let r=e.icon;return(0,z.jsxs)(o4,{value:e.id,className:"text-xs",children:[r&&(0,z.jsx)(r,{className:"h-3 w-3"}),e.label]},e.id)})}),n&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(o7,{}),(0,z.jsxs)(o2,{onClick:n,className:"text-xs",children:[(0,z.jsx)(eS,{className:"h-3 w-3"}),"Add Remote"]})]})]})]})}let jO=new WeakMap,jB=e=>{let{droppableContainers:r,pointerCoordinates:s}=e;if(!s)return(e=>{let{collisionRect:r,droppableRects:s,droppableContainers:n}=e,i=SS(r,r.left,r.top),a=[];for(let e of n){let{id:r}=e,n=s.get(r);if(n){let s=Sv(SS(n),i);a.push({id:r,data:{droppableContainer:e,value:s}})}}return a.sort(Sy)})(e);let n=[];for(let e of r){let r=e.rect.current;if(!r)continue;let i=r.top,a=r.top+52;s.x>=r.left&&s.x<=r.right&&s.y>=i&&s.y<=a&&n.push({id:e.id,data:{droppableContainer:e}})}if(n.length>0)return n;let i=null;for(let e of r){let r=e.rect.current;if(!r)continue;let n=r.top+26,a=r.left+r.width/2,o=Math.sqrt(Math.pow(s.x-a,2)+Math.pow(s.y-n,2));(!i||o<i.distance)&&(i={id:e.id,distance:o,data:{droppableContainer:e}})}return i?[{id:i.id,data:i.data}]:[]};function jz({projectId:e,selectedBranch:r,project:s,onExecutorModeChange:n,locateActive:i}){let[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(new Set),{remotes:d}=g_(),{region:u}=dD(),h=[];for(let e of(s?.path&&h.push({id:"local",label:"Local",icon:hy}),d))h.push({id:e.remote_server_id,label:e.server_name,icon:sy(e)});let{executors:f,loading:p,createExecutor:m,updateExecutor:g,deleteExecutor:x,startExecutor:v,stopExecutor:y,markProcessFinished:b,reorderExecutors:w}=function(e,r,s){let n=r??"",[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)(new Map),[c,d]=(0,$.useState)(new Map),[u,h]=(0,$.useState)(!0),f=(0,$.useCallback)(async()=>{if(!e){a([]),h(!1);return}try{let r=await ry.api.getExecutors(e,n);a(r)}catch(e){console.error("Failed to fetch executors:",e)}finally{h(!1)}},[e,n]),p=(0,$.useCallback)(async()=>{try{let e=await ry.api.getRunningProcesses();console.log(`[useExecutors] fetchRunningProcesses: ${e.length} running`,e.map(e=>`${e.executor_id}/${e.id}/${e.target??"local"}`));let{runningProcesses:r,lastStartedProcess:s}=function(e){let r=new Map,s=new Map;for(let n of e){let e={processId:n.id,target:n.target??"local"},i=r.get(n.executor_id);i?i.push(e):r.set(n.executor_id,[e]),s.set(n.executor_id,e)}return{runningProcesses:r,lastStartedProcess:s}}(e);l(r),d(e=>{let n=function(e,r){let s=new Map;for(let[n,i]of e)r.get(n)?.some(e=>e.processId===i.processId&&e.target===i.target)&&s.set(n,i);return s}(e,r);for(let[e,r]of s)n.set(e,r);return n})}catch(e){console.error("Failed to fetch running processes:",e)}},[]);(0,$.useEffect)(()=>{f()},[f]),(0,$.useEffect)(()=>{e&&p()},[e,p]),(0,$.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&p()};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[p]);let m=(0,$.useRef)(new Set);(0,$.useEffect)(()=>{m.current=new Set(i.map(e=>e.id))},[i]),(0,sx.useGlobalEventStream)(r=>{if(("executor:started"===r.type||"executor:stopped"===r.type)&&console.log(`[useExecutors] SSE received: ${r.type} executor=${r.executorId} process=${r.processId} target=${r.target??"local"} project=${r.projectId}`),!e||r.projectId!==e){("executor:started"===r.type||"executor:stopped"===r.type)&&console.log(`[useExecutors] SSE filtered: projectId mismatch (event=${r.projectId}, hook=${e})`);return}if(!m.current.has(r.executorId)){("executor:started"===r.type||"executor:stopped"===r.type)&&console.log(`[useExecutors] SSE filtered: executorId ${r.executorId} not in current group (known: ${Array.from(m.current).join(",")})`);return}"executor:started"===r.type?(console.log("[useExecutors] Processing executor:started, adding to runningProcesses"),l(e=>{let s=e.get(r.executorId)??[];if(s.some(e=>e.processId===r.processId))return e;let n=new Map(e);return n.set(r.executorId,[...s,{processId:r.processId,target:r.target??"local"}]),n}),d(e=>{let s=new Map(e);return s.set(r.executorId,{processId:r.processId,target:r.target??"local"}),s}),a(e=>e.map(e=>{if(e.id!==r.executorId)return e;let s=r.target??"local";return{...e,last_runs:{...e.last_runs??{},[s]:{started_at:new Date().toISOString(),process_id:r.processId}}}}))):"executor:stopped"===r.type&&(console.log("[useExecutors] Processing executor:stopped, removing from runningProcesses"),console.log(`[diag:remote-stop] ${new Date().toISOString()} SSE executor:stopped executor=${r.executorId} process=${r.processId} target=${r.target??"local"} — flips button via SSE (NOT the mux finished path)`),l(e=>{let s=e.get(r.executorId);if(!s)return e;let n=s.filter(e=>e.processId!==r.processId),i=new Map(e);return 0===n.length?i.delete(r.executorId):i.set(r.executorId,n),i}),d(e=>{let s=e.get(r.executorId);if(!s||s.processId!==r.processId)return e;let n=new Map(e);return n.delete(r.executorId),n}))});let g=(0,$.useCallback)(async r=>{if(!e)return null;try{let s=await ry.api.createExecutor(e,{...r,branch:n});return a(e=>[...e,s]),s}catch(e){return console.error("Failed to create executor:",e),null}},[e,n]),x=(0,$.useCallback)(async(e,r)=>{try{let s=await ry.api.updateExecutor(e,r);return a(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update executor:",e),gS.toast.error("Failed to update executor",{description:e instanceof Error?e.message:void 0}),null}},[]),v=(0,$.useCallback)(async e=>{try{await ry.api.deleteExecutor(e),a(r=>r.filter(r=>r.id!==e))}catch(e){console.error("Failed to delete executor:",e)}},[]),y=(0,$.useCallback)(async e=>{let r=s??"local",n=s=>{l(n=>{let i=n.get(e)??[];if(i.some(e=>e.processId===s))return n;let a=new Map(n);return a.set(e,[...i,{processId:s,target:r}]),a}),d(n=>{let i=new Map(n);return i.set(e,{processId:s,target:r}),i})};try{let i=await ry.api.startExecutor(e,s);return n(i),a(s=>s.map(s=>s.id!==e?s:{...s,last_runs:{...s.last_runs??{},[r]:{started_at:new Date().toISOString(),process_id:i}}})),i}catch(r){console.error("Failed to start executor:",r);let e=function(e){if(!(e instanceof ry.ExecutorProcessRequestError)||409!==e.status)return null;let{code:r,processId:s}=e.body;return"already_running"===r&&"string"==typeof s?s:null}(r);return e?(n(e),gS.toast.info("Executor is already running",{description:"Stop it before starting again."})):r instanceof ry.ExecutorProcessRequestError&&("starting"===r.body.code||"start_unknown"===r.body.code)&&gS.toast.error("Executor not started",{description:r.message}),null}},[s]),b=(0,$.useCallback)(async(e,r)=>{let n=o.get(e),i=n?.find(e=>e.target===(s??"local")),a=r||i?.processId;if(a){try{await ry.api.stopProcess(a)}catch(e){if(console.error("Failed to stop executor:",e),!(e instanceof ry.ExecutorProcessRequestError&&404===e.status)){gS.toast.error("Failed to stop executor",{description:`${e instanceof Error?e.message:String(e)}. The process may still be running.`}),p();return}}l(r=>{let s=r.get(e);if(!s)return r;let n=s.filter(e=>e.processId!==a),i=new Map(r);return 0===n.length?i.delete(e):i.set(e,n),i}),d(r=>{let s=r.get(e);if(!s||s.processId!==a)return r;let n=new Map(r);return n.delete(e),n})}},[o,s,p]),w=(0,$.useCallback)((e,r)=>{l(s=>{let n=s.get(e);if(!n)return s;if(r){let i=n.filter(e=>e.processId!==r);if(i.length===n.length)return s;let a=new Map(s);return 0===i.length?a.delete(e):a.set(e,i),a}let i=new Map(s);return i.delete(e),i}),d(s=>{if(!r){if(!s.has(e))return s;let r=new Map(s);return r.delete(e),r}let n=s.get(e);if(!n||n.processId!==r)return s;let i=new Map(s);return i.delete(e),i})},[]),_=(0,$.useCallback)(async r=>{if(e){a(r.map(e=>i.find(r=>r.id===e)).filter(e=>void 0!==e));try{await ry.api.reorderExecutors(e,r,n)}catch(e){console.error("Failed to reorder executors:",e),a(i)}}},[e,n,i]);return{executors:i.map(e=>{let r=o.get(e.id),n=s??"local",i=r?.find(e=>e.target===n),a=c.get(e.id),l=a?.target===n?a:void 0,d=e.last_runs?.[n];return{...e,currentProcessId:i?.processId??l?.processId??null,isRunning:!!i,lastProcessId:d?.process_id??null,lastStartedAt:d?.started_at??null,isDisabled:e.disabled_targets.includes(n)}}),loading:u,createExecutor:g,updateExecutor:x,deleteExecutor:v,startExecutor:y,stopExecutor:b,markProcessFinished:w,reorderExecutors:_,refetch:f}}(e,r,s?.executor_mode),_=!!(i&&f.length>0),S=_&&"right-panel"===u,j=(0,$.useCallback)(e=>{document.querySelector(`[data-locate-id="${CSS.escape(e)}"]`)?.scrollIntoView({block:"nearest"})},[]),k=(0,$.useRef)(null),C=(0,$.useCallback)(e=>{let r=k.current,s=r?.querySelector(`[data-locate-id="${CSS.escape(e)}"]`);if(!r||!s)return;let n=s.getBoundingClientRect(),i=r.getBoundingClientRect(),a=0;if(n.height>i.height?a=n.top-i.top:n.bottom>i.bottom?a=Math.max(0,Math.min(n.bottom+12-i.bottom,n.top-i.top)):n.top<i.top&&(a=n.top-12-i.top),1>Math.abs(a))return;let o=r.scrollTop+a;"function"==typeof r.scrollTo?r.scrollTo({top:o,behavior:"smooth"}):r.scrollTop=o},[]),N=(0,$.useRef)(l);(0,$.useEffect)(()=>{let e=N.current;N.current=l;let r=[...l].filter(r=>!e.has(r));if(r.length>0)return void C(r[r.length-1]);let s=[...e].filter(e=>!l.has(e));s.length>0&&j(s[s.length-1])},[l,C,j]);let E=(0,$.useCallback)(e=>{let r=document.querySelector(`[data-locate-id="${CSS.escape(e)}"]`);r?.scrollIntoView({block:"nearest"});let s=r?.querySelector("[data-locate-action]");s&&function(e){if(!(e instanceof HTMLButtonElement&&e.disabled)){let r=jO.get(e);void 0!==r&&window.clearTimeout(r),e.dataset.pressed="true",jO.set(e,window.setTimeout(()=>{jO.delete(e),delete e.dataset.pressed},160))}e.click()}(s)},[]),D=(0,$.useCallback)(e=>{let r=l.has(e);c(r=>new Set(r).add(e)),r&&C(e)},[l,C]),R=(0,$.useCallback)(e=>{c(r=>{let s=new Set(r);return s.delete(e)||s.add(e),s})},[]),[T,A]=(0,$.useState)(null),I=(0,$.useMemo)(()=>0===f.length?null:T&&f.some(e=>e.id===T)?T:f[0].id,[T,f]),M=dC("executors");dk({id:"executors",label:"Executors",priority:10,getItems:()=>f.map(e=>({id:e.id,text:e.name})),onCommit:e=>E(e.id),onSecondaryCommit:e=>D(e.id)},S);let F=M?.selectedId??null,[P,L]=(0,$.useState)(null);F!==P&&(L(F),null!==F&&A(F)),(0,$.useEffect)(()=>{null!==F&&j(F)},[F,j]);let O=M?M.selectedId:_?I:null,B=(0,$.useMemo)(()=>[...s?.path?["local"]:[],...d.map(e=>e.remote_server_id)],[s?.path,d]),H=s?.executor_mode??"local",U=null!==M;(0,$.useEffect)(()=>{if(!S||U)return;let e=e=>{if(e.defaultPrevented||e.metaKey||e.ctrlKey||e.altKey||e.shiftKey||dv(e.target)||dw(e.target))return;if("ArrowLeft"===e.key||"ArrowRight"===e.key){if(B.length<2||!n)return;e.preventDefault();let r=B.indexOf(H);n(B[(r+("ArrowRight"===e.key?1:-1)+B.length)%B.length]);return}if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault();let r=f.findIndex(e=>e.id===I),s=f[(r+("ArrowDown"===e.key?1:-1)+f.length)%f.length];A(s.id),j(s.id);return}let r=e.target instanceof Element&&null!==e.target.closest("button,a,[role='button']");if(" "===e.key&&I){if(r)return;e.preventDefault(),R(I);return}if("Enter"===e.key&&I){if(r)return;e.preventDefault(),E(I)}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[S,U,B,H,n,f,I,j,E,R]),(0,$.useEffect)(()=>{if(!S)return;let e=document.activeElement;if(!(e instanceof HTMLElement)||!q.current?.contains(e))return;let r=e.closest("[data-locate-id]");r&&r.getAttribute("data-locate-id")!==O&&e.blur()},[S,O]);let q=(0,$.useRef)(null),K=(0,$.useCallback)(e=>{let r=e.target instanceof Element?e.target.closest("[data-locate-id]"):null,s=r?.getAttribute("data-locate-id");s&&A(s)},[]),V=function(){for(var e=arguments.length,r=Array(e),s=0;s<e;s++)r[s]=arguments[s];return(0,$.useMemo)(()=>[...r].filter(e=>null!=e),[...r])}(Sg(SQ,{activationConstraint:{distance:8}}),Sg(SX,{coordinateGetter:jM}));return e?(0,z.jsx)(_X,{projectId:e,children:(0,z.jsxs)("div",{className:"h-full flex flex-col",children:[(0,z.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border/60 h-10",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsxs)("h2",{className:"text-xs font-semibold flex items-center gap-2 text-foreground",children:[(0,z.jsx)(gM,{className:"h-3.5 w-3.5"}),"Executors"]}),h.length>1&&n&&(0,z.jsx)(jL,{targets:h,activeTarget:s?.executor_mode??"local",onTargetChange:n})]}),(0,z.jsxs)(W.Button,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>o(!0),children:[(0,z.jsx)(eS,{className:"h-3 w-3 mr-1"}),"Add"]})]}),(0,z.jsx)("div",{className:"flex-1 overflow-y-auto",ref:k,children:(0,z.jsx)("div",{className:"p-4 space-y-3",ref:q,onPointerDown:K,children:p?(0,z.jsx)("div",{className:"text-center text-muted-foreground py-8",children:"Loading executors..."}):0===f.length?(0,z.jsxs)("div",{className:"text-center text-muted-foreground py-8",children:[(0,z.jsx)("p",{children:"No executors configured"}),(0,z.jsx)("p",{className:"text-sm mt-1",children:'Add an executor to run commands like "npm run dev"'})]}):(0,z.jsx)(jh,{sensors:V,collisionDetection:jB,onDragEnd:e=>{let{active:r,over:s}=e;if(s&&r.id!==s.id){let e=f.findIndex(e=>e.id===r.id),n=f.findIndex(e=>e.id===s.id),i=[...f],[a]=i.splice(e,1);i.splice(n,0,a),w(i.map(e=>e.id))}},children:(0,z.jsx)(jk,{items:f.map(e=>e.id),strategy:j_,children:f.map(e=>(0,z.jsx)(jP,{executor:e,executorMode:s?.executor_mode??"local",locateQuery:M?.query??null,locateMatch:M?.matchSet.has(e.id)??!1,keyboardSelected:O===e.id,isOpen:l.has(e.id),onOpenChange:r=>c(s=>{let n=new Set(s);return r?n.add(e.id):n.delete(e.id),n}),onStart:()=>v(e.id),onStop:r=>y(e.id,r||e.currentProcessId||void 0),onUpdate:r=>g(e.id,r),onDelete:()=>x(e.id),onProcessFinished:r=>b(e.id,r)},`${e.id}-${s?.executor_mode??"local"}`))})})})}),(0,z.jsx)(_q,{open:a,onOpenChange:o,onSubmit:async e=>{await m(e)}})]})},`${e??"none"}-${s?.executor_mode??"local"}`):(0,z.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(gM,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to manage executors"})]})})}let j$=(0,e_.default)("chevrons-up-down",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);function jW({line:e}){let r="add"===e.type?"+":"delete"===e.type?"-":" ",s="add"===e.type,n="delete"===e.type,i=s?"bg-emerald-500/[0.07]":n?"bg-rose-500/[0.07]":"",a=s?"bg-emerald-500/[0.10]":n?"bg-rose-500/[0.10]":"bg-secondary",o=s?"text-emerald-600":n?"text-rose-600":"text-muted-foreground/70";return(0,z.jsxs)("div",{className:"flex font-mono text-[11.5px] leading-[1.55]",children:[(0,z.jsx)("span",{className:(0,eb.cn)("w-9 flex-shrink-0 text-right pr-2 select-none border-r border-border/60",a,o),children:e.oldLineNo??""}),(0,z.jsx)("span",{className:(0,eb.cn)("w-9 flex-shrink-0 text-right pr-2 select-none border-r border-border/60",a,o),children:e.newLineNo??""}),(0,z.jsx)("span",{className:(0,eb.cn)("w-5 flex-shrink-0 text-center select-none",i,o),children:r}),(0,z.jsx)("span",{className:(0,eb.cn)("whitespace-pre-wrap break-all pr-4 flex-1 min-w-0 pl-2",i,(s||n)&&"text-foreground"),children:e.content})]})}let jH={modified:"bg-yellow-500/20 text-yellow-500",added:"bg-green-500/20 text-green-500",deleted:"bg-red-500/20 text-red-500",renamed:"bg-blue-500/20 text-blue-500"},jU={modified:"Modified",added:"Added",deleted:"Deleted",renamed:"Renamed"};function jq({file:e,defaultOpen:r=!0}){let[s,n]=(0,$.useState)(r),i=function(e,r){if(!r||r===e){let r,{dir:s,base:n}=-1===(r=e.lastIndexOf("/"))?{dir:"",base:e}:{dir:e.slice(0,r),base:e.slice(r+1)};return{dir:s,from:null,to:n,suffix:""}}let s=r.split("/"),n=e.split("/"),i=0;for(;i<s.length-1&&i<n.length-1&&s[i]===n[i];)i++;let a=0;for(;a<s.length-i-1&&a<n.length-i-1&&s[s.length-1-a]===n[n.length-1-a];)a++;return{dir:s.slice(0,i).join("/"),from:s.slice(i,s.length-a).join("/"),to:n.slice(i,n.length-a).join("/"),suffix:0===a?"":s.slice(s.length-a).join("/")}}(e.path,"renamed"===e.status?e.oldPath:void 0);return(0,z.jsxs)(gV,{open:s,onOpenChange:n,className:"border border-border rounded-lg overflow-hidden",children:[(0,z.jsxs)(gX,{className:"grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 px-4 py-2 bg-secondary border-b border-border w-full cursor-pointer hover:bg-muted transition-colors",children:[s?(0,z.jsx)(n6,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,z.jsx)(nV,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,z.jsxs)("span",{className:"font-mono text-[11.5px] flex min-w-0 overflow-hidden text-left text-foreground font-medium",title:null!==i.from?`${e.oldPath} → ${e.path}`:e.path,children:[i.dir&&(0,z.jsxs)("span",{className:"min-w-0 shrink-[9999] truncate text-muted-foreground font-normal",children:[i.dir,"/"]}),(0,z.jsxs)("span",{className:"min-w-0 truncate",children:[null!==i.from&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"text-muted-foreground font-normal",children:i.from}),(0,z.jsx)("span",{className:"mx-1.5 text-muted-foreground",children:"→"})]}),i.to,i.suffix&&(0,z.jsxs)("span",{className:"text-muted-foreground font-normal",children:["/",i.suffix]})]})]}),(0,z.jsx)(so,{variant:"secondary",className:jH[e.status],children:jU[e.status]})]}),(0,z.jsx)(gY,{children:(0,z.jsx)("div",{children:e.hunks.map((e,r)=>(0,z.jsxs)("div",{children:[(0,z.jsxs)("div",{className:"px-4 py-0.5 bg-accent text-accent-foreground text-[11px] font-mono font-medium sticky top-0",children:["@@ -",e.oldStart,",",e.oldLines," +",e.newStart,",",e.newLines," @@"]}),e.lines.map((e,r)=>(0,z.jsx)(jW,{line:e},r))]},r))})})]})}let jK=(0,e_.default)("git-commit-horizontal",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]]),jV="__head__",jX="__compare__";function jY({commits:e,selectedCommit:r,onSelectCommit:s,compareTarget:n,compareSelected:i,onSelectCompare:a,loading:o,disabled:l}){return(0,z.jsxs)(fd,{value:i?jX:r??jV,onValueChange:e=>{e===jX?a?.():s(e===jV?null:e)},disabled:l||o,children:[(0,z.jsxs)(fh,{size:"sm",className:"w-[200px]",children:[(0,z.jsx)(jK,{className:"h-3.5 w-3.5 shrink-0"}),(0,z.jsx)(fu,{placeholder:"Select commit..."})]}),(0,z.jsxs)(ff,{children:[(0,z.jsx)(fp,{value:jV,children:"HEAD (uncommitted)"}),n&&(0,z.jsxs)(fp,{value:jX,children:["vs ",(0,z.jsx)("span",{className:"font-mono text-xs",children:n})]}),e.map(e=>(0,z.jsxs)(fp,{value:e.hash,children:[(0,z.jsx)("span",{className:"font-mono text-xs",children:e.shortHash})," ",(0,z.jsx)("span",{className:"truncate",children:e.message.length>40?e.message.slice(0,40)+"...":e.message})]},e.hash))]})]})}function jG({projectId:e,selectedBranch:r,onMergeRequest:s,project:n,mergeTarget:i,compareRequestNonce:a}){let[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(a),[f,p]=(0,$.useState)(r),m=void 0!==a&&a!==u;m&&(h(a),d(!0),l(null)),r!==f&&(p(r),l(null),m||d(!1));let{remotes:g,loaded:x}=g_(),v=[];for(let e of(n?.path&&v.push({id:"local",label:"Local",icon:hy}),g))v.push({id:e.remote_server_id,label:e.server_name,icon:sm});let y=n?.path?"local":g.length>0?g[0].remote_server_id:"local",[b,w]=(0,$.useState)(null),_=null!==b&&v.some(e=>e.id===b)?b:y,[S,j]=(0,$.useState)(!0),[k,C]=(0,$.useState)(0),N=!!n?.path||x,E="local"===_?n?.path?"local":void 0:"remote",{diff:D,loading:R,error:T,refresh:A}=function(e,r,s,n,i){let[a,o]=(0,$.useState)(null),[l,c]=(0,$.useState)(!1),[d,u]=(0,$.useState)(null),h=(0,$.useCallback)(async()=>{if(!e)return void o(null);c(!0),u(null);try{let a=await ry.api.getDiff(e,r,s,n,i);o(a)}catch(e){u(e instanceof Error?e.message:"Failed to load diff"),o(null)}finally{c(!1)}},[e,r,s,n,i]);return{diff:a,loading:l,error:d,refresh:h}}(e,r,o,E,c&&i?i:null),{commits:I,loading:M,refetch:F}=function(e,r,s,n){let[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)(!1);return{commits:i,loading:o,refetch:(0,$.useCallback)(async()=>{if(!e)return void a([]);l(!0);try{let i=await ry.api.getCommits(e,r,s,n);a(i)}catch{a([])}finally{l(!1)}},[e,r,s,n])}}(e,r,void 0,E);if((0,$.useEffect)(()=>{N&&A()},[A,N]),(0,$.useEffect)(()=>{N&&F()},[F,N]),!e)return(0,z.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(sq,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to view changes"})]})});let P=D?.files.length??0;return(0,z.jsxs)("div",{className:"h-full flex flex-col",children:[(0,z.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border/60 h-10",children:[(0,z.jsx)("div",{className:"flex items-center gap-4",children:P>0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)("span",{className:"text-xs text-muted-foreground",children:[P," file",1!==P?"s":""," changed"]}),(0,z.jsxs)(W.Button,{size:"sm",variant:"ghost",onClick:()=>{j(e=>!e),C(e=>e+1)},title:S?"Collapse all":"Expand all",children:[(0,z.jsx)(j$,{className:"h-4 w-4 mr-1"}),S?"Collapse all":"Expand all"]})]})}),(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[v.length>1&&(0,z.jsx)(jL,{targets:v,activeTarget:_,onTargetChange:w,disabled:R}),(0,z.jsx)("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Commit:"}),(0,z.jsx)(jY,{commits:I,selectedCommit:o,onSelectCommit:e=>{d(!1),l(e)},compareTarget:i,compareSelected:c,onSelectCompare:()=>{d(!0),l(null)},loading:M,disabled:R}),(0,z.jsxs)(W.Button,{size:"sm",variant:"outline",onClick:s,disabled:R||0===P,children:[(0,z.jsx)(df,{className:"h-4 w-4 mr-1"}),"Merge"]}),(0,z.jsxs)(W.Button,{size:"sm",variant:"outline",onClick:A,disabled:R,children:[(0,z.jsx)(mt,{className:`h-4 w-4 mr-1 ${R?"animate-spin":""}`}),"Refresh"]})]})]}),(0,z.jsx)(nH,{className:"flex-1 overflow-hidden",children:(0,z.jsx)("div",{className:"p-4 space-y-4",children:R&&!D?(0,z.jsx)("div",{className:"text-center text-muted-foreground py-8",children:"Loading changes..."}):T?(0,z.jsx)("div",{className:"text-center text-red-400 py-8",children:T}):0===P?(0,z.jsx)("div",{className:"text-center text-muted-foreground py-8",children:(0,z.jsx)("p",{children:c&&i?`No changes vs ${i}`:o?"No changes in this commit":"No uncommitted changes"})}):D?.files.map((e,r)=>(0,z.jsx)(jq,{file:e,defaultOpen:S},`${r}-${k}`))})})]})}function jJ({terminalId:e,onExit:r,focusHandle:s}){let{logs:n,sendInput:i,sendResize:a,exitCode:o,replayingHistory:l}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)("closed"),[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(!0),f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=(0,$.useRef)(0),g=(0,$.useRef)(null),x=(0,$.useRef)(!1),v=(0,$.useCallback)(()=>{n([]),l(null),d(!1)},[]),y=(0,$.useCallback)(e=>{f.current?.readyState===WebSocket.OPEN&&f.current.send(JSON.stringify({type:"input",data:e}))},[]),b=(0,$.useCallback)((e,r)=>{f.current?.readyState===WebSocket.OPEN?f.current.send(JSON.stringify({type:"resize",cols:e,rows:r})):p.current={cols:e,rows:r}},[]);return(0,$.useEffect)(()=>{if(!e)return;n([]),l(null),d(!1),x.current=!1,m.current=0;let r=!1;return function s(){r||x.current||(0,ry.getFreshToken)().then(()=>{r||x.current||function(){if(r||x.current)return;a("connecting");let i=(0,ry.getWebSocketUrl)(`/api/executor-processes/${e}/logs`);console.log(`[useExecutorLogs] Connecting to WebSocket: ${i}`);let o=new WebSocket(i);f.current=o;let c=!1,u=!1;o.onopen=()=>{if(!r&&(console.log("[useExecutorLogs] WebSocket connected"),a("connected"),n([]),p.current)){let{cols:e,rows:r}=p.current;o.send(JSON.stringify({type:"resize",cols:e,rows:r})),p.current=null}},o.onmessage=e=>{if(!r)try{let r=JSON.parse(e.data);if("init"===r.type)d(r.isPty),h(!0),console.log("[useExecutorLogs] init received, setReplayingHistory(true)");else if("history_end"===r.type)u=!0,h(!1),console.log("[useExecutorLogs] history_end received, setReplayingHistory(false)");else if("finished"===r.type)x.current=!0,l(r.exitCode),a("closed");else if("error"===r.type)x.current=!0,a("error");else{u&&(c=!0,m.current=0);let e="stdout"===r.type||"stderr"===r.type||"pty"===r.type?{...r,historical:!u}:r;n(r=>[...r,e])}}catch(e){console.error("Failed to parse WebSocket message:",e)}},o.onerror=e=>{r||console.error("[useExecutorLogs] WebSocket error:",e)},o.onclose=e=>{if(console.log("[useExecutorLogs] WebSocket closed:",e.code,e.reason),f.current=null,x.current||r)return void a("closed");if(u&&!c){console.log(`[useExecutorLogs] Server closed after history with no live data — treating as terminal`),x.current=!0,a("closed");return}if(m.current<8){let e=m.current,n=Math.min(15e3,1e3*Math.pow(2,e)),i=n*Math.random()*.25,o=n+i;console.log(`[useExecutorLogs] Scheduling reconnect in ${Math.round(o)}ms (attempt ${e+1}/8)`),a("connecting"),m.current=e+1,g.current=setTimeout(()=>{g.current=null,r||s()},o)}else console.log("[useExecutorLogs] Max reconnect attempts reached"),a("error")}}()})}(),()=>{r=!0,g.current&&(clearTimeout(g.current),g.current=null),f.current&&(f.current.close(),f.current=null)}},[e,void 0]),{logs:s,status:i,exitCode:o,isPty:c,replayingHistory:u,clearLogs:v,sendInput:y,sendResize:b}}(e);return(0,$.useEffect)(()=>{null!==o&&r(e)},[o,r,e]),(0,z.jsx)(_H,{logs:n,isPty:!0,className:"h-full rounded-none border-0",onInput:i,onResize:a,muteInput:l,focusHandle:s})}function jZ({projectId:e,selectedBranch:r,project:s,active:n=!0,createRequest:i}){let{terminals:a,activeTerminalId:o,createTerminal:l,closeTerminal:c,setActiveTerminal:d,removeTerminal:u}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(null),o=`${e??""}::${r??""}`,l=(0,$.useRef)(o),c=(0,$.useRef)([]);(0,$.useEffect)(()=>{if(l.current=o,c.current=[],!e){n([]),a(null);return}ry.api.getTerminals(e,r).then(e=>{if(l.current!==o)return;let r=c.current;c.current=[];let s=0===r.length?e:[...e.filter(e=>!r.some(r=>r.id===e.id)),...r];n(s),a(r.length>0?r[r.length-1].id:s.length>0?s[0].id:null)})},[e,r,o]);let d=(0,$.useCallback)(async(s,i)=>{if(!e)return;let o=l.current;try{let d=await ry.api.createTerminal(e,r,s,i);if(l.current!==o)return;c.current=[...c.current,d],n(e=>[...e,d]),a(d.id)}catch(e){console.error("[useTerminals] Failed to create terminal:",e)}},[e,r]),u=(0,$.useCallback)(e=>{c.current=c.current.filter(r=>r.id!==e)},[]),h=(0,$.useCallback)(async e=>{await ry.api.closeTerminal(e),u(e),n(r=>{let s=r.filter(r=>r.id!==e);return a(r=>r===e?s.length>0?s[s.length-1].id:null:r),s})},[u]);return{terminals:s,activeTerminalId:i,createTerminal:d,closeTerminal:h,setActiveTerminal:(0,$.useCallback)(e=>{a(e)},[]),removeTerminal:(0,$.useCallback)(e=>{u(e),n(r=>{let s=r.filter(r=>r.id!==e);return a(r=>r===e?s.length>0?s[s.length-1].id:null:r),s})},[u])}}(e,r),{remotes:h}=g_(),f=(0,$.useRef)(null);(0,$.useEffect)(()=>{n&&o&&f.current?.focus()},[n,o]);let[p,m]=(0,$.useState)(!1),g=(0,$.useRef)(null),x=!!s?.path,v=h.length>0,y=x&&v||h.length>1,b=x?"local":"remote",w=(0,$.useCallback)(()=>{l(b)},[l,b]),_=(0,$.useCallback)((e,r)=>{m(!1),l(e,r)},[l]),S=(0,$.useRef)(null);(0,$.useEffect)(()=>{i&&S.current!==i.nonce&&(S.current=i.nonce,"local"===i.targetId?l("local"):l("remote",i.targetId))},[i,l]),(0,$.useEffect)(()=>{if(p)return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e);function e(e){g.current&&!g.current.contains(e.target)&&m(!1)}},[p]);let j=(0,$.useCallback)(e=>{u(e)},[u]);return e?(0,z.jsxs)("div",{className:"h-full flex flex-col",children:[(0,z.jsxs)("div",{className:"flex items-center h-10 border-b border-border/60 px-2 gap-1 shrink-0 bg-muted/20",children:[(0,z.jsx)("div",{className:"flex-1 min-w-0 flex items-center gap-1 overflow-hidden",children:a.map(e=>{let r="remote"===e.location||e.id.startsWith("remote-"),s=y?r?sm:hy:gM,n=o===e.id;return(0,z.jsxs)("button",{onClick:()=>d(e.id),title:e.name,className:(0,eb.cn)("group flex items-center gap-1.5 px-2 py-1 rounded-md text-xs transition-all duration-150 border flex-1 min-w-0 basis-0 max-w-[180px]",n?"bg-background text-foreground border-border shadow-sm":"text-muted-foreground hover:text-foreground bg-muted/40 hover:bg-background/60 border-border/30 hover:border-border/60"),children:[(0,z.jsx)(s,{className:"h-3 w-3 shrink-0"}),(0,z.jsx)("span",{className:"truncate flex-1 text-left",children:e.name}),(0,z.jsx)("span",{role:"button",onClick:r=>{r.stopPropagation(),c(e.id)},className:(0,eb.cn)("shrink-0 rounded-sm p-0.5 hover:bg-destructive/10 hover:text-destructive",n?"opacity-80 hover:opacity-100":"opacity-0 group-hover:opacity-80 hover:!opacity-100"),children:(0,z.jsx)(t7,{className:"h-3 w-3"})})]},e.id)})}),(0,z.jsxs)("div",{className:"relative shrink-0",ref:g,children:[(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:y?()=>m(e=>!e):w,children:(0,z.jsx)(eS,{className:"h-3.5 w-3.5"})}),y&&p&&(0,z.jsxs)("div",{className:"absolute right-0 top-full mt-1 z-50 min-w-[160px] rounded-md border bg-popover p-1 shadow-md",children:[x&&(0,z.jsxs)("button",{className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground transition-colors",onClick:()=>_("local"),children:[(0,z.jsx)(hy,{className:"h-3.5 w-3.5"}),"Local Terminal"]}),h.map(e=>(0,z.jsxs)("button",{className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground transition-colors",onClick:()=>_("remote",e.remote_server_id),children:[(0,z.jsx)(sm,{className:"h-3.5 w-3.5"}),e.server_name," Terminal"]},e.remote_server_id))]})]})]}),(0,z.jsx)("div",{className:"flex-1 overflow-hidden bg-zinc-950",children:o?(0,z.jsx)(jJ,{terminalId:o,onExit:j,focusHandle:f},o):(0,z.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,z.jsx)(gM,{className:"h-10 w-10 text-muted-foreground/70"})})})]}):(0,z.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(gM,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to use the terminal"})]})})}let jQ=(0,$.createContext)(null),j0=({className:e,children:r,defaultUrl:s="",onUrlChange:n,...i})=>{let[a,o]=(0,$.useState)(s),[l,c]=(0,$.useState)(!1);return(0,z.jsx)(jQ.Provider,{value:{url:a,setUrl:e=>{o(e),n?.(e)},consoleOpen:l,setConsoleOpen:c},children:(0,z.jsx)("div",{className:(0,eb.cn)("flex size-full flex-col bg-card",e),...i,children:r})})},j1=({className:e,children:r,...s})=>(0,z.jsx)("div",{className:(0,eb.cn)("flex items-center gap-1 border-b p-2 h-14",e),...s,children:r}),j2=({onClick:e,disabled:r,tooltip:s,children:n,...i})=>(0,z.jsx)(cb,{children:(0,z.jsxs)(cw,{children:[(0,z.jsx)(c_,{asChild:!0,children:(0,z.jsx)(W.Button,{className:"h-8 w-8 p-0 hover:text-foreground",disabled:r,onClick:e,size:"sm",variant:"ghost",...i,children:n})}),(0,z.jsx)(cS,{children:(0,z.jsx)("p",{children:s})})]})}),j5=({value:e,onChange:r,onKeyDown:s,...n})=>{let{url:i,setUrl:a}=(()=>{let e=(0,$.useContext)(jQ);if(!e)throw Error("WebPreview components must be used within a WebPreview");return e})(),[o,l]=(0,$.useState)(i);return(0,$.useEffect)(()=>{l(i)},[i]),(0,z.jsx)(rl,{className:"h-8 flex-1 text-sm",onChange:r??(e=>{l(e.target.value),r?.(e)}),onKeyDown:e=>{"Enter"===e.key&&a(e.target.value),s?.(e)},placeholder:"Enter URL...",value:e??o,...n})};var j3=e.i(254824);function j4({projectId:e}){let r=(0,$.useRef)(null),s=(0,$.useRef)(null),{addFrame:n,updateFrameUrl:i,refreshFrame:a,hasFrame:o,claimFrame:l,getFrameUrl:c}=(0,j3.useBrowserFrames)(),d=e?c(e):void 0;(0,$.useEffect)(()=>{if(e&&d&&r.current){let n=setTimeout(()=>{r.current&&(s.current?.(),s.current=l(e,r.current))},50);return()=>{clearTimeout(n),s.current?.(),s.current=null}}return()=>{s.current?.(),s.current=null}},[e,d,l]);let u=(0,$.useCallback)(()=>{e&&a(e)},[e,a]),h=(0,$.useCallback)(()=>{d&&window.open(d,"_blank")},[d]),f=(0,$.useCallback)(r=>{e&&(o(e)?i(e,r):n(e,r))},[e,o,i,n]);return(0,z.jsx)("div",{className:"h-full flex flex-col",children:(0,z.jsxs)(j0,{defaultUrl:d??"",onUrlChange:f,className:"h-full",children:[(0,z.jsxs)(j1,{className:"h-10 p-1.5 gap-0.5",children:[(0,z.jsx)(j2,{tooltip:"Refresh",onClick:u,disabled:!d,children:(0,z.jsx)(mt,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(j2,{tooltip:"Open in browser",onClick:h,disabled:!d,children:(0,z.jsx)(s8,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(j5,{className:"h-7 text-xs"})]}),d?(0,z.jsx)("div",{ref:r,className:"flex-1 bg-white"}):(0,z.jsx)("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:(0,z.jsxs)("div",{className:"flex flex-col items-center gap-2",children:[(0,z.jsx)(rw,{className:"h-8 w-8 opacity-40"}),(0,z.jsx)("p",{className:"text-sm",children:"Enter a URL above to preview"})]})})]})})}let j6=(0,e_.default)("panel-left-close",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]),j7=(0,e_.default)("panel-left-open",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]),j8=(0,e_.default)("arrow-right",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);function j9({className:e,...r}){return(0,z.jsx)("div",{"data-slot":"input-group",role:"group",className:(0,eb.cn)("group/input-group border-input dark:bg-input/30 relative flex w-full items-center rounded-md border shadow-xs transition-[color,box-shadow] outline-none","h-9 min-w-0 has-[textarea]:h-auto","has-[>[data-align=inline-start]]:[&>input]:pl-2","has-[>[data-align=inline-end]]:[&>input]:pr-2","has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3","has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3","has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot=input-group-control]:focus-visible]:ring-[3px]","has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40",e),...r})}let ke=(0,si.cva)("text-muted-foreground flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium select-none [&>svg:not([class*='size-'])]:size-4 [&>kbd]:rounded-[calc(var(--radius)-5px)] group-data-[disabled=true]/input-group:opacity-50",{variants:{align:{"inline-start":"order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]","inline-end":"order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]","block-start":"order-first w-full justify-start px-3 pt-3 [.border-b]:pb-3 group-has-[>input]/input-group:pt-2.5","block-end":"order-last w-full justify-start px-3 pb-3 [.border-t]:pt-3 group-has-[>input]/input-group:pb-2.5"}},defaultVariants:{align:"inline-start"}});function kt({className:e,align:r="inline-start",...s}){return(0,z.jsx)("div",{role:"group","data-slot":"input-group-addon","data-align":r,className:(0,eb.cn)(ke({align:r}),e),onClick:e=>{e.target.closest("button")||e.currentTarget.parentElement?.querySelector("input")?.focus()},...s})}let kr=(0,si.cva)("text-sm shadow-none flex gap-2 items-center",{variants:{size:{xs:"h-6 gap-1 px-2 rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-3.5 has-[>svg]:px-2",sm:"h-8 px-2.5 gap-1.5 rounded-md has-[>svg]:px-2.5","icon-xs":"size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0","icon-sm":"size-8 p-0 has-[>svg]:p-0"}},defaultVariants:{size:"xs"}});function ks({className:e,type:r="button",variant:s="ghost",size:n="xs",...i}){return(0,z.jsx)(W.Button,{type:r,"data-size":n,variant:s,className:(0,eb.cn)(kr({size:n}),e),...i})}function kn({className:e,...r}){return(0,z.jsx)(rl,{"data-slot":"input-group-control",className:(0,eb.cn)("flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",e),...r})}function ki({className:e,...r}){return(0,z.jsx)(rc,{"data-slot":"input-group-control",className:(0,eb.cn)("flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent",e),...r})}let ka=(0,e_.default)("file",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]]),ko=(0,e_.default)("file-code",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]]),kl=(0,e_.default)("file-text",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]),kc=new Set(["ts","tsx","js","jsx","py","rb","go","rs","java","c","cpp","h","css","scss","html","vue","svelte","php","swift","kt","sh","bash","yaml","yml","toml","json","xml","sql","graphql","proto"]),kd=new Set(["md","txt","log","csv","env","gitignore","dockerignore","editorconfig"]);function ku(e){return Array.from(e.dataTransfer.types).includes("Files")}function kh(e){let r=e.dataTransfer.items;if(r&&r.length>0&&"function"==typeof r[0].webkitGetAsEntry){let e=[];for(let s of Array.from(r)){if("file"!==s.kind)continue;let r=s.webkitGetAsEntry();if(r?.isDirectory)continue;let n=s.getAsFile();n&&e.push(n)}return e}return Array.from(e.dataTransfer.files)}function kf({path:e}){let[r,s]=(0,$.useState)(!1),n=(0,$.useCallback)(r=>{r.stopPropagation(),navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)},[e]);return(0,z.jsx)("button",{onClick:n,className:"p-0.5 rounded hover:bg-muted-foreground/20 transition-colors",title:`Copy path: ${e}`,children:r?(0,z.jsx)(rp.Check,{className:"h-3 w-3 text-green-500"}):(0,z.jsx)(me.Copy,{className:"h-3 w-3 text-muted-foreground"})})}function kp({entryPath:e,type:r,deleting:s,onRequestDelete:n}){return s?(0,z.jsx)(sC,{className:"h-3 w-3 animate-spin text-muted-foreground"}):(0,z.jsx)("button",{onClick:s=>{s.stopPropagation(),n(e,r)},className:"p-0.5 rounded hover:bg-destructive/20 transition-colors",title:`Delete ${e}`,"aria-label":`Delete ${e}`,children:(0,z.jsx)(rd,{className:"h-3 w-3 text-muted-foreground hover:text-destructive"})})}function km({entry:e,path:r,depth:s,expandedDirs:n,directoryContents:i,loadingDirs:a,selectedFile:o,uploadingDirs:l,dragOverPath:c,deletingPaths:d,onToggleDirectory:u,onSelectFile:h,onUploadFiles:f,onSetDragOverPath:p,onRequestDelete:m}){var g,x,v;let y,b,w,_,S,j=n.has(r),k=a.has(r),C=i.get(r),N=e.name.startsWith(".");if("directory"===e.type){let g=j?n6:nV,x=c===r,v=l.has(r),y=d.has(r);return(0,z.jsxs)("div",{children:[(0,z.jsxs)("div",{className:(0,eb.cn)("group flex items-center w-full px-2 py-2 rounded-sm transition-colors cursor-pointer",x?"bg-primary/15 outline-2 -outline-offset-2 outline-dashed outline-primary/60":"hover:bg-accent"),style:{paddingLeft:`${16*s+8}px`},onClick:()=>u(r),onDragOver:e=>{ku(e)&&(e.preventDefault(),e.stopPropagation(),p(r))},onDrop:e=>{if(!ku(e))return;e.preventDefault(),e.stopPropagation(),p(null);let s=kh(e);s.length&&f(r,s)},children:[(0,z.jsxs)("div",{className:"flex items-center gap-1 min-w-0 flex-1",children:[v||k?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):(0,z.jsx)(g,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,z.jsx)(j?rb:nq,{className:(0,eb.cn)("h-4 w-4 shrink-0 text-blue-500",N&&"opacity-60")}),(0,z.jsx)("span",{className:(0,eb.cn)("truncate",N&&"text-muted-foreground"),children:e.name})]}),(0,z.jsxs)("div",{className:(0,eb.cn)("shrink-0 ml-1 items-center gap-1",y?"flex":"hidden group-hover:flex"),children:[(0,z.jsx)(kf,{path:r}),(0,z.jsx)(kp,{entryPath:r,type:"directory",deleting:y,onRequestDelete:m})]})]}),j&&C&&(0,z.jsx)("div",{children:C.map(e=>{let g=r?`${r}/${e.name}`:e.name;return(0,z.jsx)(km,{entry:e,path:g,depth:s+1,expandedDirs:n,directoryContents:i,loadingDirs:a,selectedFile:o,uploadingDirs:l,dragOverPath:c,deletingPaths:d,onToggleDirectory:u,onSelectFile:h,onUploadFiles:f,onSetDragOverPath:p,onRequestDelete:m},g)})})]})}let E=(g=e.name,y=g.split(".").pop()?.toLowerCase()??"",kc.has(y)?ko:kd.has(y)?kl:ka),D=o===r,R=r.includes("/")?r.slice(0,r.lastIndexOf("/")):"",T=d.has(r);return(0,z.jsxs)("div",{className:(0,eb.cn)("group flex items-center w-full px-2 py-2 rounded-sm transition-colors cursor-pointer",D?"bg-accent text-accent-foreground":"hover:bg-accent/50"),style:{paddingLeft:`${16*s+8+18}px`},onClick:()=>h(r),onDragOver:e=>{ku(e)&&(e.preventDefault(),e.stopPropagation(),p(R))},onDrop:e=>{if(!ku(e))return;e.preventDefault(),e.stopPropagation(),p(null);let r=kh(e);r.length&&f(R,r)},children:[(0,z.jsxs)("div",{className:"flex items-center gap-1 min-w-0 flex-1",children:[(0,z.jsx)(E,{className:(0,eb.cn)("h-4 w-4 shrink-0 text-muted-foreground",N&&"opacity-60")}),(0,z.jsx)("span",{className:(0,eb.cn)("truncate",N&&"text-muted-foreground"),children:e.name})]}),(0,z.jsxs)("div",{className:"shrink-0 flex items-center gap-2 ml-1",children:[(0,z.jsx)("span",{className:"text-[11px] text-muted-foreground/70 group-hover:hidden whitespace-nowrap w-[52px] text-right tabular-nums",children:e.mtime&&(x=e.mtime,b=Date.now(),S=Math.floor((_=Math.floor((w=Math.floor(Math.floor((b-new Date(x).getTime())/1e3)/60))/60))/24),w<1?"just now":w<60?`${w}m ago`:_<24?`${_}h ago`:S<30?`${S}d ago`:new Date(x).toLocaleDateString(void 0,{month:"short",day:"numeric"}))}),(0,z.jsx)("span",{className:"text-[11px] text-muted-foreground/70 group-hover:hidden whitespace-nowrap w-[52px] text-right tabular-nums",children:null!=e.size&&((v=e.size)<1024?`${v} B`:v<1048576?`${(v/1024).toFixed(1)} KB`:`${(v/1048576).toFixed(1)} MB`)}),(0,z.jsxs)("div",{className:(0,eb.cn)("items-center gap-1",T?"flex":"hidden group-hover:flex"),children:[(0,z.jsx)(kf,{path:r}),(0,z.jsx)(kp,{entryPath:r,type:"file",deleting:T,onRequestDelete:m})]})]})]})}function kg({entries:e,expandedDirs:r,directoryContents:s,loadingDirs:n,selectedFile:i,uploadingDirs:a,rootLoading:o,deletingPaths:l,onToggleDirectory:c,onSelectFile:d,onUploadFiles:u,onDeleteEntry:h}){let[f,p]=(0,$.useState)(null),[m,g]=(0,$.useState)(null),x=""===f,v=a.has(""),y=(0,$.useCallback)((e,r)=>{g({path:e,type:r})},[]),b=m?m.path.includes("/")?m.path.slice(m.path.lastIndexOf("/")+1):m.path:"";return(0,z.jsxs)("div",{className:(0,eb.cn)("h-full transition-colors",x&&"bg-accent/30 outline-2 -outline-offset-2 outline-dashed outline-primary/50"),style:{fontSize:"var(--files-tree-font-size, 14px)"},onDragOver:e=>{ku(e)&&(e.preventDefault(),p(""))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||p(null)},onDrop:e=>{if(!ku(e))return;e.preventDefault(),p(null);let r=kh(e);r.length&&u("",r)},children:[(0,z.jsx)(nH,{className:"h-full",children:(0,z.jsxs)("div",{className:"py-1",children:[v&&(0,z.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1 text-xs text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-3.5 w-3.5 animate-spin"}),"Uploading…"]}),o&&0===e.length?(0,z.jsx)("div",{className:"flex items-center justify-center py-12 text-muted-foreground text-sm",children:"Loading files..."}):0===e.length?(0,z.jsx)("div",{className:"flex items-center justify-center py-8 text-muted-foreground text-sm",children:x?"Drop files to upload":"No files found. Drop files here to upload."}):e.map(e=>{let o=e.name;return(0,z.jsx)(km,{entry:e,path:o,depth:0,expandedDirs:r,directoryContents:s,loadingDirs:n,selectedFile:i,uploadingDirs:a,dragOverPath:f,deletingPaths:l,onToggleDirectory:c,onSelectFile:d,onUploadFiles:u,onSetDragOverPath:p,onRequestDelete:y},o)})]})}),(0,z.jsx)(lL,{open:null!==m,onOpenChange:e=>{e||g(null)},children:(0,z.jsxs)(lz,{children:[(0,z.jsxs)(l$,{children:[(0,z.jsxs)(lH,{children:["Delete ",m?.type==="directory"?"folder":"file","?"]}),(0,z.jsx)(lU,{children:m?.type==="directory"?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"font-medium text-foreground",children:b})," and all its contents will be permanently deleted. This can't be undone."]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"font-medium text-foreground",children:b})," will be permanently deleted. This can't be undone."]})})]}),(0,z.jsxs)(lW,{children:[(0,z.jsx)(lK,{children:"Cancel"}),(0,z.jsx)(lq,{className:(0,eb.cn)((0,W.buttonVariants)({variant:"destructive"}),"border-transparent"),onClick:()=>{m&&h(m.path,m.type)},children:"Delete"})]})]})})]})}let kx=(0,e_.default)("download",[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]]),kv=(0,e_.default)("file-exclamation-point",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),ky=(0,e_.default)("code",[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]]),kb=(0,e_.default)("list-collapse",[["path",{d:"M10 5h11",key:"1hkqpe"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 19h11",key:"14g2nv"}],["path",{d:"m3 10 3-3-3-3",key:"i7pm08"}],["path",{d:"m3 20 3-3-3-3",key:"20gx1n"}]]),kw=(0,e_.default)("list-tree",[["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"M3 10a2 2 0 0 0 2 2h3",key:"1npucw"}],["path",{d:"M3 5v12a2 2 0 0 0 2 2h3",key:"x1gjn2"}]]),k_=/[\0-\x1F!-,\.\/:-@\[-\^`\{-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0378\u0379\u037E\u0380-\u0385\u0387\u038B\u038D\u03A2\u03F6\u0482\u0530\u0557\u0558\u055A-\u055F\u0589-\u0590\u05BE\u05C0\u05C3\u05C6\u05C8-\u05CF\u05EB-\u05EE\u05F3-\u060F\u061B-\u061F\u066A-\u066D\u06D4\u06DD\u06DE\u06E9\u06FD\u06FE\u0700-\u070F\u074B\u074C\u07B2-\u07BF\u07F6-\u07F9\u07FB\u07FC\u07FE\u07FF\u082E-\u083F\u085C-\u085F\u086B-\u089F\u08B5\u08C8-\u08D2\u08E2\u0964\u0965\u0970\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA\u09BB\u09C5\u09C6\u09C9\u09CA\u09CF-\u09D6\u09D8-\u09DB\u09DE\u09E4\u09E5\u09F2-\u09FB\u09FD\u09FF\u0A00\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A\u0A3B\u0A3D\u0A43-\u0A46\u0A49\u0A4A\u0A4E-\u0A50\u0A52-\u0A58\u0A5D\u0A5F-\u0A65\u0A76-\u0A80\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA\u0ABB\u0AC6\u0ACA\u0ACE\u0ACF\u0AD1-\u0ADF\u0AE4\u0AE5\u0AF0-\u0AF8\u0B00\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A\u0B3B\u0B45\u0B46\u0B49\u0B4A\u0B4E-\u0B54\u0B58-\u0B5B\u0B5E\u0B64\u0B65\u0B70\u0B72-\u0B81\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BBD\u0BC3-\u0BC5\u0BC9\u0BCE\u0BCF\u0BD1-\u0BD6\u0BD8-\u0BE5\u0BF0-\u0BFF\u0C0D\u0C11\u0C29\u0C3A-\u0C3C\u0C45\u0C49\u0C4E-\u0C54\u0C57\u0C5B-\u0C5F\u0C64\u0C65\u0C70-\u0C7F\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA\u0CBB\u0CC5\u0CC9\u0CCE-\u0CD4\u0CD7-\u0CDD\u0CDF\u0CE4\u0CE5\u0CF0\u0CF3-\u0CFF\u0D0D\u0D11\u0D45\u0D49\u0D4F-\u0D53\u0D58-\u0D5E\u0D64\u0D65\u0D70-\u0D79\u0D80\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DC9\u0DCB-\u0DCE\u0DD5\u0DD7\u0DE0-\u0DE5\u0DF0\u0DF1\u0DF4-\u0E00\u0E3B-\u0E3F\u0E4F\u0E5A-\u0E80\u0E83\u0E85\u0E8B\u0EA4\u0EA6\u0EBE\u0EBF\u0EC5\u0EC7\u0ECE\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F01-\u0F17\u0F1A-\u0F1F\u0F2A-\u0F34\u0F36\u0F38\u0F3A-\u0F3D\u0F48\u0F6D-\u0F70\u0F85\u0F98\u0FBD-\u0FC5\u0FC7-\u0FFF\u104A-\u104F\u109E\u109F\u10C6\u10C8-\u10CC\u10CE\u10CF\u10FB\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B\u135C\u1360-\u137F\u1390-\u139F\u13F6\u13F7\u13FE-\u1400\u166D\u166E\u1680\u169B-\u169F\u16EB-\u16ED\u16F9-\u16FF\u170D\u1715-\u171F\u1735-\u173F\u1754-\u175F\u176D\u1771\u1774-\u177F\u17D4-\u17D6\u17D8-\u17DB\u17DE\u17DF\u17EA-\u180A\u180E\u180F\u181A-\u181F\u1879-\u187F\u18AB-\u18AF\u18F6-\u18FF\u191F\u192C-\u192F\u193C-\u1945\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DA-\u19FF\u1A1C-\u1A1F\u1A5F\u1A7D\u1A7E\u1A8A-\u1A8F\u1A9A-\u1AA6\u1AA8-\u1AAF\u1AC1-\u1AFF\u1B4C-\u1B4F\u1B5A-\u1B6A\u1B74-\u1B7F\u1BF4-\u1BFF\u1C38-\u1C3F\u1C4A-\u1C4C\u1C7E\u1C7F\u1C89-\u1C8F\u1CBB\u1CBC\u1CC0-\u1CCF\u1CD3\u1CFB-\u1CFF\u1DFA\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FBD\u1FBF-\u1FC1\u1FC5\u1FCD-\u1FCF\u1FD4\u1FD5\u1FDC-\u1FDF\u1FED-\u1FF1\u1FF5\u1FFD-\u203E\u2041-\u2053\u2055-\u2070\u2072-\u207E\u2080-\u208F\u209D-\u20CF\u20F1-\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F-\u215F\u2189-\u24B5\u24EA-\u2BFF\u2C2F\u2C5F\u2CE5-\u2CEA\u2CF4-\u2CFF\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D70-\u2D7E\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF\u2E00-\u2E2E\u2E30-\u3004\u3008-\u3020\u3030\u3036\u3037\u303D-\u3040\u3097\u3098\u309B\u309C\u30A0\u30FB\u3100-\u3104\u3130\u318F-\u319F\u31C0-\u31EF\u3200-\u33FF\u4DC0-\u4DFF\u9FFD-\u9FFF\uA48D-\uA4CF\uA4FE\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA673\uA67E\uA6F2-\uA716\uA720\uA721\uA789\uA78A\uA7C0\uA7C1\uA7CB-\uA7F4\uA828-\uA82B\uA82D-\uA83F\uA874-\uA87F\uA8C6-\uA8CF\uA8DA-\uA8DF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA954-\uA95F\uA97D-\uA97F\uA9C1-\uA9CE\uA9DA-\uA9DF\uA9FF\uAA37-\uAA3F\uAA4E\uAA4F\uAA5A-\uAA5F\uAA77-\uAA79\uAAC3-\uAADA\uAADE\uAADF\uAAF0\uAAF1\uAAF7-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F\uAB5B\uAB6A-\uAB6F\uABEB\uABEE\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uD7FF\uE000-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB29\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFC-\uFDFF\uFE10-\uFE1F\uFE30-\uFE32\uFE35-\uFE4C\uFE50-\uFE6F\uFE75\uFEFD-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF3E\uFF40\uFF5B-\uFF65\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFFF]|\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDD3F\uDD75-\uDDFC\uDDFE-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEDF\uDEE1-\uDEFF\uDF20-\uDF2C\uDF4B-\uDF4F\uDF7B-\uDF7F\uDF9E\uDF9F\uDFC4-\uDFC7\uDFD0\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56-\uDC5F\uDC77-\uDC7F\uDC9F-\uDCDF\uDCF3\uDCF6-\uDCFF\uDD16-\uDD1F\uDD3A-\uDD7F\uDDB8-\uDDBD\uDDC0-\uDDFF\uDE04\uDE07-\uDE0B\uDE14\uDE18\uDE36\uDE37\uDE3B-\uDE3E\uDE40-\uDE5F\uDE7D-\uDE7F\uDE9D-\uDEBF\uDEC8\uDEE7-\uDEFF\uDF36-\uDF3F\uDF56-\uDF5F\uDF73-\uDF7F\uDF92-\uDFFF]|\uD803[\uDC49-\uDC7F\uDCB3-\uDCBF\uDCF3-\uDCFF\uDD28-\uDD2F\uDD3A-\uDE7F\uDEAA\uDEAD-\uDEAF\uDEB2-\uDEFF\uDF1D-\uDF26\uDF28-\uDF2F\uDF51-\uDFAF\uDFC5-\uDFDF\uDFF7-\uDFFF]|\uD804[\uDC47-\uDC65\uDC70-\uDC7E\uDCBB-\uDCCF\uDCE9-\uDCEF\uDCFA-\uDCFF\uDD35\uDD40-\uDD43\uDD48-\uDD4F\uDD74\uDD75\uDD77-\uDD7F\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDFF\uDE12\uDE38-\uDE3D\uDE3F-\uDE7F\uDE87\uDE89\uDE8E\uDE9E\uDEA9-\uDEAF\uDEEB-\uDEEF\uDEFA-\uDEFF\uDF04\uDF0D\uDF0E\uDF11\uDF12\uDF29\uDF31\uDF34\uDF3A\uDF45\uDF46\uDF49\uDF4A\uDF4E\uDF4F\uDF51-\uDF56\uDF58-\uDF5C\uDF64\uDF65\uDF6D-\uDF6F\uDF75-\uDFFF]|\uD805[\uDC4B-\uDC4F\uDC5A-\uDC5D\uDC62-\uDC7F\uDCC6\uDCC8-\uDCCF\uDCDA-\uDD7F\uDDB6\uDDB7\uDDC1-\uDDD7\uDDDE-\uDDFF\uDE41-\uDE43\uDE45-\uDE4F\uDE5A-\uDE7F\uDEB9-\uDEBF\uDECA-\uDEFF\uDF1B\uDF1C\uDF2C-\uDF2F\uDF3A-\uDFFF]|\uD806[\uDC3B-\uDC9F\uDCEA-\uDCFE\uDD07\uDD08\uDD0A\uDD0B\uDD14\uDD17\uDD36\uDD39\uDD3A\uDD44-\uDD4F\uDD5A-\uDD9F\uDDA8\uDDA9\uDDD8\uDDD9\uDDE2\uDDE5-\uDDFF\uDE3F-\uDE46\uDE48-\uDE4F\uDE9A-\uDE9C\uDE9E-\uDEBF\uDEF9-\uDFFF]|\uD807[\uDC09\uDC37\uDC41-\uDC4F\uDC5A-\uDC71\uDC90\uDC91\uDCA8\uDCB7-\uDCFF\uDD07\uDD0A\uDD37-\uDD39\uDD3B\uDD3E\uDD48-\uDD4F\uDD5A-\uDD5F\uDD66\uDD69\uDD8F\uDD92\uDD99-\uDD9F\uDDAA-\uDEDF\uDEF7-\uDFAF\uDFB1-\uDFFF]|\uD808[\uDF9A-\uDFFF]|\uD809[\uDC6F-\uDC7F\uDD44-\uDFFF]|[\uD80A\uD80B\uD80E-\uD810\uD812-\uD819\uD824-\uD82B\uD82D\uD82E\uD830-\uD833\uD837\uD839\uD83D\uD83F\uD87B-\uD87D\uD87F\uD885-\uDB3F\uDB41-\uDBFF][\uDC00-\uDFFF]|\uD80D[\uDC2F-\uDFFF]|\uD811[\uDE47-\uDFFF]|\uD81A[\uDE39-\uDE3F\uDE5F\uDE6A-\uDECF\uDEEE\uDEEF\uDEF5-\uDEFF\uDF37-\uDF3F\uDF44-\uDF4F\uDF5A-\uDF62\uDF78-\uDF7C\uDF90-\uDFFF]|\uD81B[\uDC00-\uDE3F\uDE80-\uDEFF\uDF4B-\uDF4E\uDF88-\uDF8E\uDFA0-\uDFDF\uDFE2\uDFE5-\uDFEF\uDFF2-\uDFFF]|\uD821[\uDFF8-\uDFFF]|\uD823[\uDCD6-\uDCFF\uDD09-\uDFFF]|\uD82C[\uDD1F-\uDD4F\uDD53-\uDD63\uDD68-\uDD6F\uDEFC-\uDFFF]|\uD82F[\uDC6B-\uDC6F\uDC7D-\uDC7F\uDC89-\uDC8F\uDC9A-\uDC9C\uDC9F-\uDFFF]|\uD834[\uDC00-\uDD64\uDD6A-\uDD6C\uDD73-\uDD7A\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDE41\uDE45-\uDFFF]|\uD835[\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3\uDFCC\uDFCD]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85-\uDE9A\uDEA0\uDEB0-\uDFFF]|\uD838[\uDC07\uDC19\uDC1A\uDC22\uDC25\uDC2B-\uDCFF\uDD2D-\uDD2F\uDD3E\uDD3F\uDD4A-\uDD4D\uDD4F-\uDEBF\uDEFA-\uDFFF]|\uD83A[\uDCC5-\uDCCF\uDCD7-\uDCFF\uDD4C-\uDD4F\uDD5A-\uDFFF]|\uD83B[\uDC00-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDFFF]|\uD83C[\uDC00-\uDD2F\uDD4A-\uDD4F\uDD6A-\uDD6F\uDD8A-\uDFFF]|\uD83E[\uDC00-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEDE-\uDEFF]|\uD86D[\uDF35-\uDF3F]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEA2-\uDEAF]|\uD87A[\uDFE1-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDFFF]|\uDB40[\uDC00-\uDCFF\uDDF0-\uDFFF]/g,kS=Object.hasOwnProperty;var kj=e.i(216920);let kk={},kC=new class{constructor(){this.occurrences,this.reset()}slug(e,r){var s,n;let i=(s=e,n=!0===r,"string"!=typeof s?"":(n||(s=s.toLowerCase()),s.replace(k_,"").replace(/ /g,"-"))),a=i;for(;kS.call(this.occurrences,i);)this.occurrences[a]++,i=a+"-"+this.occurrences[a];return this.occurrences[i]=0,i}reset(){this.occurrences=Object.create(null)}};function kN(e){let r=(e||kk).prefix||"";return function(e){kC.reset(),(0,kj.visit)(e,"element",function(e){let s,n;((n=2===(s="element"===e.type?e.tagName.toLowerCase():"").length&&104===s.charCodeAt(0)?s.charCodeAt(1):0)>48&&n<55?n-48:void 0)&&!e.properties.id&&(e.properties.id=r+kC.slug("children"in e?function e(r){let s=-1,n=[];for(;++s<r.children.length;){var i;n[s]="text"===(i=r.children[s]).type?i.value:"children"in i?e(i):""}return n.join("")}(e):"value"in e?e.value:""))})}}var kE=cj,H=H,kD=e.i(829692),kD=kD;let kR={bash:()=>e.A(350825),c:()=>e.A(637078),cpp:()=>e.A(802318),csharp:()=>e.A(129951),css:()=>e.A(756163),dockerfile:()=>e.A(253540),go:()=>e.A(703741),graphql:()=>e.A(920758),html:()=>e.A(488168),java:()=>e.A(832431),javascript:()=>e.A(857908),json:()=>e.A(699038),jsx:()=>e.A(475799),kotlin:()=>e.A(476532),lua:()=>e.A(930588),makefile:()=>e.A(809849),markdown:()=>e.A(198794),mdx:()=>e.A(186622),php:()=>e.A(931135),python:()=>e.A(435385),r:()=>e.A(995633),ruby:()=>e.A(62790),rust:()=>e.A(733588),scala:()=>e.A(710477),scss:()=>e.A(742937),sql:()=>e.A(546234),svelte:()=>e.A(645265),swift:()=>e.A(993701),toml:()=>e.A(880929),tsx:()=>e.A(427335),typescript:()=>e.A(59512),vue:()=>e.A(945589),xml:()=>e.A(298220),yaml:()=>e.A(405971),zig:()=>e.A(681653)},kT="one-light",kA=null,kI=new Map;async function kM(r){let s=await (kA??=(async()=>{let[{createHighlighterCore:r},{createJavaScriptRegexEngine:s},n,i]=await Promise.all([e.A(733022),e.A(158048),e.A(905359),e.A(617706)]);return r({themes:[n.default,i.default],langs:[],engine:s({forgiving:!0})})})().catch(e=>{throw kA=null,e}));if("text"===r)return s;let n=kI.get(r);return n||(n=kR[r]().then(e=>s.loadLanguage(e.default)).catch(e=>{throw kI.delete(r),e}),kI.set(r,n)),await n,s}let kF=(0,$.createContext)({code:""}),kP={name:"line-data",line(e,r){e.properties["data-line"]=String(r)}},kL={name:"line-numbers",line(e,r){e.children.unshift({type:"element",tagName:"span",properties:{className:["inline-block","min-w-10","mr-2","text-right","select-none","text-muted-foreground"]},children:[{type:"text",value:String(r)}]})}};async function kO(e,r,s=!1,n){let i=[kP];n&&n.size>0&&i.push({name:"fold-gutter",line(e,r){e.children.unshift({type:"element",tagName:"span",properties:n.has(r)?{className:["code-fold-toggle"],"data-fold-start":String(r)}:{className:["code-fold-spacer"]},children:[]})}}),s&&i.push(kL);let a=await kM(r);return[a.codeToHtml(e,{lang:r,theme:kT,transformers:i}),a.codeToHtml(e,{lang:r,theme:"one-dark-pro",transformers:i})]}let kB=(0,$.forwardRef)(function({code:e,language:r,showLineNumbers:s=!1,scrollToLine:n,scrollKey:i,foldable:a=!1,className:o,children:l,...c},d){let[u,h]=(0,$.useState)(""),[f,p]=(0,$.useState)(""),m=(0,$.useRef)(!1),g=(0,$.useRef)(null),x=(0,$.useMemo)(()=>a?function(e,r={}){return function(...e){let r=new Map;for(let s of e.flat())!(s.endLine<=s.startLine)&&(r.has(s.startLine)||r.set(s.startLine,s));let s=[...r.values()].sort((e,r)=>e.startLine-r.startLine||r.endLine-e.endLine),n=[],i=[];for(let e of s){for(;i.length&&i[i.length-1].endLine<e.startLine;)i.pop();let r=i[i.length-1];r&&e.endLine>r.endLine||(n.push(e),i.push(e))}return n}((r.tokenIndex,[]),function(e){let r=e.split("\n"),s=[],n=[],i=0,a=e=>{i>e.line&&s.push({startLine:e.line+1,endLine:i+1})};for(let e=0;e<r.length;e++){let s=function(e){let r=e.match(/^[ \t]*/),s=r?r[0].length:0;return s===e.length?null:s}(r[e]);if(null!==s){for(;n.length&&n[n.length-1].indent>=s;)a(n.pop());n.push({indent:s,line:e}),i=e}}for(;n.length;)a(n.pop());return s}(e))}(e):[],[a,e]),v=(0,$.useMemo)(()=>new Set(x.map(e=>e.startLine)),[x]),[y,b]=(0,$.useState)(new Set),[w,_]=(0,$.useState)(e),[S,j]=(0,$.useState)({line:n,key:i});if((0,$.useImperativeHandle)(d,()=>({foldAll:()=>b(new Set(x.map(e=>e.startLine))),expandAll:()=>b(new Set)}),[x]),(0,$.useEffect)(()=>(kO(e,r,s,v).then(([e,r])=>{m.current||(h(e),p(r),m.current=!0)}),()=>{m.current=!1}),[e,r,s,v]),(0,$.useEffect)(()=>{let e=g.current;if(!e)return;let r=new Map(x.map(e=>[e.startLine,e])),s=new Set;for(let e of y){let n=r.get(e);if(n)for(let e=n.startLine+1;e<=n.endLine;e++)s.add(e)}for(let r of e.querySelectorAll("[data-line]")){let e=Number(r.getAttribute("data-line"));r.style.display=s.has(e)?"none":"",r.classList.toggle("code-line-collapsed",y.has(e))}},[y,x,u,f]),(0,$.useEffect)(()=>{if(!a)return;let e=g.current;if(!e)return;let r=e=>{let r=e.target?.closest?.("[data-fold-start]");if(!r)return;e.stopPropagation(),e.preventDefault();let s=Number(r.getAttribute("data-fold-start"));b(e=>{let r=new Set(e);return r.has(s)?r.delete(s):r.add(s),r})};return e.addEventListener("click",r),()=>e.removeEventListener("click",r)},[a]),(0,$.useEffect)(()=>{if(null==n)return;let e=g.current;if(!e||!u&&!f)return;let r=Array.from(e.querySelectorAll(`[data-line="${n}"]`));if(0===r.length)return;let s=r.find(e=>null!==e.offsetParent)??r[0],i=requestAnimationFrame(()=>{s.scrollIntoView({block:"center",behavior:"auto"}),r.forEach(e=>e.classList.add("code-line-highlight"))}),a=window.setTimeout(()=>r.forEach(e=>e.classList.remove("code-line-highlight")),1600);return()=>{cancelAnimationFrame(i),window.clearTimeout(a),r.forEach(e=>e.classList.remove("code-line-highlight"))}},[n,i,u,f]),e!==w&&(_(e),b(new Set)),(S.line!==n||S.key!==i)&&(j({line:n,key:i}),null!=n&&y.size>0)){let e=!1,r=new Set(y);for(let s of x)r.has(s.startLine)&&n>s.startLine&&n<=s.endLine&&(r.delete(s.startLine),e=!0);e&&b(r)}return(0,z.jsx)(kF.Provider,{value:{code:e},children:(0,z.jsx)("div",{ref:g,className:(0,eb.cn)("group relative w-full overflow-hidden rounded-md border bg-background text-foreground",o),...c,children:(0,z.jsxs)("div",{className:"relative",children:[(0,z.jsx)("div",{className:"overflow-auto dark:hidden [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:grid [&_code]:font-mono [&_code]:text-sm",dangerouslySetInnerHTML:{__html:u}}),(0,z.jsx)("div",{className:"hidden overflow-auto dark:block [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:grid [&_code]:font-mono [&_code]:text-sm",dangerouslySetInnerHTML:{__html:f}}),l&&(0,z.jsx)("div",{className:"absolute top-2 right-2 flex items-center gap-2",children:l})]})})})}),kz=({onCopy:e,onError:r,timeout:s=2e3,children:n,className:i,...a})=>{let[o,l]=(0,$.useState)(!1),{code:c}=(0,$.useContext)(kF),d=async()=>{if(!navigator?.clipboard?.writeText)return void r?.(Error("Clipboard API not available"));try{await navigator.clipboard.writeText(c),l(!0),e?.(),setTimeout(()=>l(!1),s)}catch(e){r?.(e)}},u=o?H.default:kD.default;return(0,z.jsx)(W.Button,{className:(0,eb.cn)("shrink-0",i),onClick:d,size:"icon",variant:"ghost",...a,children:n??(0,z.jsx)(u,{size:14})})};function k$({className:e,...r}){return(0,z.jsx)("div",{"data-slot":"skeleton",className:(0,eb.cn)("bg-accent animate-pulse rounded-md",e),...r})}let kW=/^remote-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-/i;function kH(e){return e?kW.exec(e)?.[1]??null:null}function kU({projectId:e,symbol:r,branch:s,target:n,currentFile:i,anchor:a,onJump:o,onClose:l}){let[c,d]=(0,$.useState)(!0),[u,h]=(0,$.useState)([]),[f,p]=(0,$.useState)(!1),m=(0,$.useRef)(null);(0,$.useEffect)(()=>{let i=!0;return d(!0),ry.api.searchSymbol(e,r,s,n).then(e=>{i&&(h(e.hits),p(e.truncated))}).catch(()=>{i&&h([])}).finally(()=>{i&&d(!1)}),()=>{i=!1}},[e,r,s,n]),(0,$.useEffect)(()=>{let e=e=>{e.detail>=2||m.current&&!m.current.contains(e.target)&&l()},s=e=>{if("Escape"===e.key)return void l();if((e.metaKey||e.ctrlKey)&&("c"===e.key||"C"===e.key)){let s=window.getSelection();if(s&&s.rangeCount>0&&!s.isCollapsed)return;e.preventDefault(),navigator.clipboard?.writeText(r)}};return document.addEventListener("mousedown",e),document.addEventListener("keydown",s),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",s)}},[l,r]);let g=(e,r)=>Number(r.file===i)-Number(e.file===i),x=u.filter(e=>"definition"===e.kind).sort(g),v=u.filter(e=>"reference"===e.kind).sort(g),y=Math.max(8,Math.min(a.x,window.innerWidth-440-8)),b=window.innerHeight-8-(a.y+18),w=a.y-18-8,_=b>=340||b>=w,S=Math.max(120,Math.min(340,_?b:w)),j=_?{top:a.y+18}:{bottom:window.innerHeight-(a.y-18)},k=({hit:e})=>(0,z.jsxs)("button",{type:"button",onClick:()=>{o(e.file,e.line),l()},className:"flex w-full flex-col items-start gap-0.5 rounded px-2 py-1.5 text-left hover:bg-accent",children:[(0,z.jsxs)("span",{className:"flex w-full items-baseline justify-between gap-2",children:[(0,z.jsxs)("span",{className:"truncate font-mono text-xs",children:[e.file.split("/").pop(),(0,z.jsxs)("span",{className:"text-muted-foreground",children:[":",e.line]})]}),e.file===i&&(0,z.jsx)("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:"this file"})]}),(0,z.jsx)("code",{className:"w-full truncate text-xs text-muted-foreground",children:e.text.trim()})]}),C=({title:e,children:r})=>(0,z.jsxs)("div",{className:"mb-1",children:[(0,z.jsx)("div",{className:"px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:e}),r]});return(0,ee.createPortal)((0,z.jsxs)("div",{ref:m,style:{left:y,...j,width:440,maxHeight:S},className:"fixed z-50 flex flex-col overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-lg select-none",children:[(0,z.jsx)("div",{className:"border-b px-3 py-1.5 text-xs font-medium",children:(0,z.jsx)("span",{className:"font-mono",children:r})}),(0,z.jsx)("div",{className:"flex-1 overflow-auto p-1",children:c?(0,z.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"})," Searching…"]}):0===u.length?(0,z.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No results."}):(0,z.jsxs)(z.Fragment,{children:[x.length>0&&(0,z.jsx)(C,{title:`Definitions (${x.length})`,children:x.map((e,r)=>(0,z.jsx)(k,{hit:e},`d-${r}`))}),v.length>0&&(0,z.jsx)(C,{title:`References (${v.length})`,children:v.map((e,r)=>(0,z.jsx)(k,{hit:e},`r-${r}`))}),f&&(0,z.jsx)("div",{className:"px-2 py-1.5 text-[11px] text-muted-foreground",children:"Showing first matches — results truncated."})]})})]}),document.body)}let kq=(0,e_.default)("image-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]);function kK({projectId:e,filePath:r,branch:s,target:n,sessionId:i,onDownload:a}){let[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(!1);return((0,$.useEffect)(()=>{let a=null,o=!1;return ry.api.getFileBlob(e,r,s,n,i).then(({blob:e})=>{o||l(a=URL.createObjectURL(e))}).catch(()=>{o||d(!0)}),()=>{o=!0,a&&URL.revokeObjectURL(a)}},[e,r,s,n,i]),c)?(0,z.jsxs)("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[(0,z.jsx)(kq,{className:"h-10 w-10"}),(0,z.jsx)("p",{className:"text-sm",children:"Couldn't load image"}),(0,z.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:a,children:[(0,z.jsx)(kx,{className:"h-4 w-4 mr-2"}),"Download"]})]}):o?(0,z.jsx)("div",{className:"flex items-center justify-center h-full p-4 bg-muted/30",children:(0,z.jsx)("img",{src:o,alt:r.split("/").pop()??"image",className:"max-w-full max-h-full object-contain",onError:()=>d(!0)})}):(0,z.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,z.jsx)(sC,{className:"h-6 w-6 animate-spin"})})}async function kV(e,r){let s=(await kM(r)).codeToTokensBase(e,{lang:r,theme:kT,includeExplanation:"scopeName"}),n=new Map;return s.forEach((e,r)=>{let s=0,i=[];for(let r of e){let e=(r.explanation??[]).flatMap(e=>e.scopes.map(e=>e.scopeName)),n=s+r.content.length;i.push({start:s,end:n,kind:e.some(e=>e.startsWith("comment"))?"comment":e.some(e=>e.startsWith("string")||e.startsWith("constant.character"))?"string":e.some(e=>e.startsWith("keyword")||e.startsWith("storage")||e.startsWith("constant.language")||e.startsWith("variable.language"))?"keyword":"code"}),s=n}n.set(r+1,i)}),n}let kX=new Set(["png","jpg","jpeg","gif","webp","bmp","ico","avif","svg"]);function kY(e){let r=e.split("/").pop()?.split(".").pop()?.toLowerCase()??"";return kX.has(r)}let kG=/^[A-Za-z_$][A-Za-z0-9_$]*$/,kJ="symbol-nav";function kZ(e,r,s){let n=document.createRange();return n.selectNodeContents(e),n.setEnd(r,s),n.toString().length}function kQ(e,r){let s,n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),i=0;for(;s=n.nextNode();){let e=(s.textContent??"").length;if(r<=i+e)return{node:s,offset:r-i};i+=e}return null}function k0(e){let r=Array.from(document.querySelectorAll(`[data-line="${CSS.escape(e.line)}"]`)),s=r.find(e=>null!==e.offsetParent)??r[0];if(!s)return null;let n=kQ(s,e.start),i=kQ(s,e.end);if(!n||!i)return null;let a=document.createRange();return a.setStart(n.node,n.offset),a.setEnd(i.node,i.offset),a}let k1=/[A-Za-z0-9_$]/;function k2(e,r,s){let n=document,i=null,a=0;if(n.caretRangeFromPoint){let s=n.caretRangeFromPoint(e,r);s&&(i=s.startContainer,a=s.startOffset)}else if(n.caretPositionFromPoint){let s=n.caretPositionFromPoint(e,r);s&&(i=s.offsetNode,a=s.offset)}if(!i||i.nodeType!==Node.TEXT_NODE)return null;let o=i.textContent??"",l=a,c=a;for(;l>0&&k1.test(o[l-1]);)l--;for(;c<o.length&&k1.test(o[c]);)c++;if(l>=c)return null;let d=o.slice(l,c);if(!kG.test(d))return null;let u=document.createRange();u.setStart(i,l),u.setEnd(i,c);let h=function(e){let r=e.startContainer.nodeType===Node.ELEMENT_NODE?e.startContainer:e.startContainer.parentElement,s=r?.closest("[data-line]");if(!s||!s.contains(e.endContainer))return null;let n=s.getAttribute("data-line");if(null===n)return null;let i=kZ(s,e.startContainer,e.startOffset),a=kZ(s,e.endContainer,e.endOffset);return i>=a?null:{line:n,start:i,end:a}}(u);if(!h)return null;if(s){let e=h.start-h.line.length,r=function(e,r,s){let n=e.get(r);if(!n)return null;for(let e of n)if(s>=e.start&&s<e.end)return e.kind;return null}(s,Number(h.line),e);if(r&&"code"!==r)return null}return{word:d,anchor:h}}function k5(){return"undefined"!=typeof CSS&&"highlights"in CSS&&"undefined"!=typeof Highlight}let k3=!1;function k4(){k5()&&CSS.highlights.delete(kJ)}let k6={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",css:"css",scss:"scss",html:"html",vue:"vue",svelte:"svelte",php:"php",swift:"swift",kt:"kotlin",sh:"bash",bash:"bash",zsh:"bash",yaml:"yaml",yml:"yaml",toml:"toml",json:"json",xml:"xml",sql:"sql",graphql:"graphql",md:"markdown",mdx:"mdx",dockerfile:"dockerfile",makefile:"makefile",lua:"lua",r:"r",scala:"scala",zig:"zig"};function k7(e){let r=e.split("/").pop()?.toLowerCase()??"";return"dockerfile"===r?"dockerfile":"makefile"===r?"makefile":k6[r.split(".").pop()?.toLowerCase()??""]??"text"}function k8(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function k9({filePath:e,fileContent:r,loading:s,downloadUrl:n,projectId:i,branch:a,target:o,sessionId:l,scrollToLine:c,scrollKey:d,onJump:u,restoreScrollTop:h,restoreScrollKey:f,onScroll:p}){let m,g=r?.serverId??null,{label:x}=gf(g&&g!==kH(l)?g:null),[v,y]=(0,$.useState)("rendered"),[b,w]=(0,$.useState)(e),[_,S]=(0,$.useState)(null),j=(0,$.useRef)(null),k=(0,$.useRef)(null),C=(0,$.useRef)(!1);(0,$.useEffect)(()=>{C.current=null!==_},[_]);let N=(0,$.useCallback)(e=>{if(e.detail>=2){let r=window.getSelection();if(C.current){r?.removeAllRanges(),S(e=>e?{...e,selectWord:!0}:e);return}let s=k2(e.clientX,e.clientY),n=s?k0(s.anchor):null;n&&(r?.removeAllRanges(),r?.addRange(n));return}let r=window.getSelection();if(r&&!r.isCollapsed)return;let s=k2(e.clientX,e.clientY,j.current);s&&(r?.removeAllRanges(),S({symbol:s.word,x:e.clientX,y:e.clientY,anchor:s.anchor,selectWord:!1}))},[]),E=(0,$.useCallback)(e=>{e.detail>=2&&e.preventDefault()},[]);(0,$.useEffect)(()=>{if(!_?.anchor)return void k4();let e=k0(_.anchor);if(!e)return void k4();if(_.selectWord){k4();let r=window.getSelection();r?.removeAllRanges(),r?.addRange(e);return}return k5()?(!function(){if(k3||"undefined"==typeof document)return;k3=!0;let e=document.createElement("style");e.textContent=`::highlight(${kJ}){background-color:rgba(255, 196, 0, 0.32);}`,document.head.appendChild(e)}(),CSS.highlights.set(kJ,new Highlight(e)),k4):void k4()},[_]),(0,$.useEffect)(()=>{j.current=null;let s=r?.content;if(!e||null==s||r?.binary||r?.tooLarge)return;let n=!1;return kV(s,k7(e)).then(e=>{n||(j.current=e)}).catch(()=>{}),()=>{n=!0}},[e,r]);let D=(0,$.useRef)(null),R=(0,$.useRef)(null),T=(0,$.useCallback)(e=>{let r=D.current;if(!r)return;let s=r.querySelector(`[id="${CSS.escape(e)}"]`);if(!s)return;R.current?.();let n=()=>s.scrollIntoView({block:"start",behavior:"auto"});n();let i=new ResizeObserver(n);i.observe(r);let a=()=>{i.disconnect(),window.clearTimeout(o),window.removeEventListener("wheel",a),window.removeEventListener("touchmove",a),window.removeEventListener("keydown",a),R.current=null},o=window.setTimeout(a,1e3);window.addEventListener("wheel",a,{passive:!0}),window.addEventListener("touchmove",a,{passive:!0}),window.addEventListener("keydown",a),R.current=a},[]);(0,$.useEffect)(()=>()=>R.current?.(),[]);let A=(0,$.useRef)(null),I=(0,$.useRef)(!1),M=(0,$.useRef)(p);M.current=p;let F=(0,$.useRef)(null),P=(0,$.useRef)(null),L=(0,$.useCallback)(e=>{if(I.current)return;let r=e.currentTarget.scrollTop;F.current&&clearTimeout(F.current),F.current=setTimeout(()=>M.current?.(r),200)},[]);(0,$.useEffect)(()=>{void 0!==f&&(P.current=h??0)},[f,h]),(0,$.useEffect)(()=>{let e=A.current;e&&(e.scrollTop=0)},[e]),(0,$.useEffect)(()=>{let e=P.current;if(null==e)return;let r=A.current;if(!r||(P.current=null,!e))return;I.current=!0;let s=()=>{r.scrollTop=e};s();let n=new ResizeObserver(s);n.observe(r.firstElementChild??r);let i=()=>{I.current=!1,n.disconnect(),window.clearTimeout(a),r.removeEventListener("wheel",i),r.removeEventListener("touchmove",i),r.removeEventListener("keydown",i)},a=window.setTimeout(i,1500);return r.addEventListener("wheel",i,{passive:!0}),r.addEventListener("touchmove",i,{passive:!0}),r.addEventListener("keydown",i),i},[r]);let O=(0,$.useMemo)(()=>[...Object.values(kE.e),kN],[]),B=(0,$.useMemo)(()=>({a:({href:e,children:r,className:s,node:n,...i})=>{let a="string"==typeof e&&e.startsWith("#");return(0,z.jsx)("a",{href:e,className:(0,eb.cn)("wrap-anywhere font-medium text-primary underline",s),"data-streamdown":"link",...a?{onClick:r=>{r.preventDefault(),T(decodeURIComponent(e.slice(1)))}}:{target:"_blank",rel:"noreferrer"},...i,children:r})}}),[T]);if(e!==b&&(w(e),y("rendered"),S(null)),!e)return(0,z.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:"Select a file to preview."});if(s)return(0,z.jsxs)("div",{className:"flex flex-col h-full",children:[(0,z.jsx)("div",{className:"flex items-center justify-between px-4 py-2 border-b flex-shrink-0",children:(0,z.jsx)(k$,{className:"h-4 w-48"})}),(0,z.jsxs)("div",{className:"flex-1 p-4",children:[(0,z.jsx)(k$,{className:"h-4 w-full mb-2"}),(0,z.jsx)(k$,{className:"h-4 w-3/4 mb-2"}),(0,z.jsx)(k$,{className:"h-4 w-5/6 mb-2"}),(0,z.jsx)(k$,{className:"h-4 w-2/3"})]})]});if(!r)return(0,z.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:"Failed to load file."});let H=()=>{e&&ry.api.downloadFile(i,e,a,o,l).catch(e=>{console.error("Failed to download file",e)})},U=("markdown"===(m=k7(e))||"mdx"===m)&&!r.tooLarge&&!r.binary&&!!r.content,q=U&&"rendered"===v,K=!r.tooLarge&&!r.binary&&!q&&null!==r.content;return(0,z.jsxs)("div",{className:"flex flex-col h-full",children:[(0,z.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b flex-shrink-0 gap-2",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,z.jsx)("span",{className:"text-sm font-mono truncate",children:e}),(0,z.jsx)("span",{className:"text-xs text-muted-foreground shrink-0",children:k8(r.size)}),x&&(0,z.jsxs)("span",{className:"text-xs text-muted-foreground shrink-0",children:["on ",(0,z.jsx)("span",{className:"text-foreground",children:x})]})]}),(0,z.jsxs)("div",{className:"flex items-center gap-1 shrink-0",children:[U&&(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>y(e=>"rendered"===e?"source":"rendered"),title:q?"View source":"View rendered",children:q?(0,z.jsx)(ky,{className:"h-3.5 w-3.5"}):(0,z.jsx)(_P,{className:"h-3.5 w-3.5"})}),K&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>k.current?.foldAll(),title:"Fold all",children:(0,z.jsx)(kb,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>k.current?.expandAll(),title:"Expand all",children:(0,z.jsx)(kw,{className:"h-3.5 w-3.5"})})]}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{navigator.clipboard.writeText(e)},title:"Copy path",children:(0,z.jsx)(me.Copy,{className:"h-3.5 w-3.5"})}),n&&(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:H,title:"Download",children:(0,z.jsx)(kx,{className:"h-3.5 w-3.5"})})]})]}),(0,z.jsx)("div",{className:"flex-1 overflow-auto",ref:A,onScroll:L,children:r.tooLarge?(0,z.jsxs)("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[(0,z.jsx)(kv,{className:"h-10 w-10"}),(0,z.jsxs)("p",{className:"text-sm",children:["File too large to preview (",k8(r.size),")"]}),n&&(0,z.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:H,children:[(0,z.jsx)(kx,{className:"h-4 w-4 mr-2"}),"Download"]})]}):r.binary&&kY(e)&&r.size<=0xa00000?(0,z.jsx)(kK,{projectId:i,filePath:e,branch:a,target:o,sessionId:l,onDownload:H},e):r.binary?(0,z.jsxs)("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[(0,z.jsx)(kv,{className:"h-10 w-10"}),(0,z.jsx)("p",{className:"text-sm",children:kY(e)?`Image too large to preview (${k8(r.size)})`:`Binary file (${k8(r.size)})`}),n&&(0,z.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:H,children:[(0,z.jsx)(kx,{className:"h-4 w-4 mr-2"}),"Download"]})]}):q?(0,z.jsx)("div",{className:"p-4",style:{fontSize:"var(--files-content-font-size, 14px)"},ref:D,children:(0,z.jsx)(cE,{components:B,rehypePlugins:O,children:r.content??""})}):null!==r.content?(0,z.jsx)("div",{className:"h-full [&_pre]:text-[length:var(--files-content-font-size,14px)]! [&_code]:text-[length:var(--files-content-font-size,14px)]!",onMouseDown:E,onClick:N,children:(0,z.jsx)(kB,{ref:k,code:r.content,language:k7(e),showLineNumbers:!0,foldable:!0,scrollToLine:c,scrollKey:d,className:"border-0 rounded-none",children:(0,z.jsx)(kz,{})})}):(0,z.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:"Empty file."})}),_&&(0,z.jsx)(kU,{projectId:i,symbol:_.symbol,branch:a,target:o,currentFile:e,anchor:{x:_.x,y:_.y},onJump:u,onClose:()=>S(null)})]})}class Ce{capacity;map;constructor(e){if(this.capacity=e,this.map=new Map,e<1)throw Error("LRUCache capacity must be at least 1")}get(e){if(!this.map.has(e))return;let r=this.map.get(e);return this.map.delete(e),this.map.set(e,r),r}has(e){return this.map.has(e)}set(e,r){for(this.map.has(e)&&this.map.delete(e),this.map.set(e,r);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(void 0===e)break;this.map.delete(e)}}delete(e){return this.map.delete(e)}deleteWhere(e){for(let r of[...this.map.keys()])e(r)&&this.map.delete(r)}clear(){this.map.clear()}get size(){return this.map.size}}let Ct="vibedeckx:files:views";function Cr(){return{v:1,views:{}}}function Cs(){try{let e=localStorage.getItem(Ct);if(!e)return Cr();let r=JSON.parse(e);if(!r||1!==r.v||!r.views||"object"!=typeof r.views)return Cr();return r}catch{return Cr()}}function Cn(e){try{localStorage.setItem(Ct,JSON.stringify(e))}catch{}}function Ci(e){return e.slice(e.lastIndexOf("\0")+1)}function Ca({projectId:e,project:r,selectedBranch:s,navRequest:n,sessionId:i,active:a=!0}){let o=r&&!r.path?"remote":void 0,[l,c]=(0,$.useState)(!1),{settings:d}=(0,mo.useConversationSettings)(),u=(0,$.useRef)(null),[h,f]=(0,$.useState)(!1),p=(0,$.useCallback)(()=>{let e=u.current;e&&(e.isCollapsed()?e.expand():e.collapse())},[]),{rootEntries:m,directoryContents:g,expandedDirs:x,selectedFile:v,fileContent:y,fileLoading:b,rootLoading:w,loadingDirs:_,uploadingDirs:S,deletingPaths:j,jumpTarget:k,canGoBack:C,canGoForward:N,fetchRoot:E,refresh:D,reportScroll:R,restoreScroll:T,toggleDirectory:A,navigate:I,jumpTo:M,goBack:F,goForward:P,uploadFiles:L,deleteEntry:O}=function({projectId:e,branch:r,target:s,sessionId:n,showHidden:i=!1}){let[a,o]=(0,$.useState)([]),[l,c]=(0,$.useState)(new Map),[d,u]=(0,$.useState)(new Set),[h,f]=(0,$.useState)(null),[p,m]=(0,$.useState)(null),[g,x]=(0,$.useState)(null),v=(0,$.useRef)(0),[y,b]=(0,$.useState)({entries:[],index:-1}),w=(0,$.useRef)(y);w.current=y;let[_,S]=(0,$.useState)(!1),[j,k]=(0,$.useState)(!1),[C,N]=(0,$.useState)(new Set),[E,D]=(0,$.useState)(new Set),[R,T]=(0,$.useState)(new Set),A=(0,$.useRef)(0),I=(0,$.useRef)(0),M=(0,$.useRef)(new Ce(50)),F=e?[e,r??"",s??""].join("|"):null,P=(0,$.useRef)(F);P.current=F;let L=(0,$.useRef)(h);L.current=h;let O=(0,$.useRef)(0),B=(0,$.useRef)(null),z=(0,$.useRef)(0),[W,H]=(0,$.useState)(null),U=(0,$.useRef)(null),q=(0,$.useCallback)(i=>[e,r??"",s??"",i.startsWith("/")||i.startsWith("~")?n??"":"",i].join("\0"),[e,r,s,n]),K=(0,$.useCallback)(()=>{let e,r,s=P.current;if(!s||B.current!==s)return;let n={selectedFile:L.current,history:w.current,scrollTop:O.current};(e=Cs()).views[s]={...n,updatedAt:Date.now()},(r=Object.keys(e.views)).length>30&&r.sort((r,s)=>e.views[r].updatedAt-e.views[s].updatedAt).slice(0,r.length-30).forEach(r=>delete e.views[r]),Cn(e)},[]),V=(0,$.useCallback)(()=>{U.current&&clearTimeout(U.current),U.current=setTimeout(()=>{U.current=null,K()},300)},[K]),X=(0,$.useCallback)(e=>{O.current=e,V()},[V]);(0,$.useEffect)(()=>{V()},[h,y,V]);let Y=(0,$.useCallback)(async n=>{if(e&&(u(e=>{let r=new Set(e);return r.has(n)?r.delete(n):r.add(n),r}),!l.has(n))){N(e=>new Set(e).add(n));try{let a=await ry.api.browseProjectDirectory(e,n,r,s,i);c(e=>{let r=new Map(e);return r.set(n,a.items),r})}catch(e){console.error("Failed to browse directory:",e),gS.toast.error(`Failed to open ${n}`,{description:e instanceof Error?e.message:String(e)})}finally{N(e=>{let r=new Set(e);return r.delete(n),r})}}},[e,r,s,i,l]),G=(0,$.useCallback)(async i=>{if(!e)return"failed";let a=q(i),o=M.current.get(a);if(o)return m(o),S(!1),"loaded";let l=++I.current;S(!0),m(null);try{let o=await ry.api.getFileContent(e,i,r,s,n);if(l!==I.current)return"stale";return M.current.set(a,o),m(o),"loaded"}catch(e){if(l!==I.current)return"stale";return console.error("Failed to get file content:",e),m(null),"failed"}finally{l===I.current&&S(!1)}},[e,r,s,n,q]),J=(0,$.useCallback)(async r=>{e&&(f(r),await G(r))},[e,G]),Z=(0,$.useCallback)(async()=>{if(!e)return!1;k(!0);let n=++A.current;try{let a=await ry.api.browseProjectDirectory(e,void 0,r,s,i);if(n!==A.current)return!1;return o(a.items),c(new Map),u(new Set),!0}catch(e){if(console.error("Failed to browse root directory:",e),n!==A.current)return!1;return o([]),gS.toast.error("Failed to browse files",{description:e instanceof Error?e.message:String(e)}),!1}finally{n===A.current&&k(!1)}},[e,r,s,i]),Q=(0,$.useCallback)(async()=>{let r;if(!e||!await Z())return;let s=P.current,n=s?(r=Cs().views[s])&&"object"==typeof r&&(null===r.selectedFile||"string"==typeof r.selectedFile)&&r.history&&"object"==typeof r.history&&Array.isArray(r.history.entries)&&"number"==typeof r.history.index?{selectedFile:r.selectedFile,history:r.history,scrollTop:"number"==typeof r.scrollTop&&Number.isFinite(r.scrollTop)?r.scrollTop:0}:null:null;if(s&&n&&n.selectedFile){if(b(n.history.entries.length?n.history:{entries:[{path:n.selectedFile,line:null}],index:0}),O.current=n.scrollTop,H({top:n.scrollTop,nonce:++z.current}),f(n.selectedFile),B.current=s,"failed"===await G(n.selectedFile)){let e;f(null),b({entries:[],index:-1}),O.current=0,(e=Cs()).views[s]&&(delete e.views[s],Cn(e))}}else f(null),m(null),b({entries:[],index:-1}),O.current=0,B.current=s},[e,Z,G]),ee=(0,$.useCallback)(async()=>{if(!e||(M.current.clear(),!await Z()))return;let r=L.current;r&&await G(r)},[e,Z,G]),et=(0,$.useCallback)(async(e,r=null)=>{b(({entries:s,index:n})=>{let i=s[n];if(i&&i.path===e){let i=s.slice();return i[n]={path:e,line:r},{entries:i,index:n}}let a=s.slice(0,n+1);return{entries:[...a,{path:e,line:r}],index:a.length}}),await J(e),null!=r&&x({line:r,nonce:++v.current})},[J]),er=(0,$.useCallback)((e,r)=>et(e,r),[et]),es=(0,$.useCallback)(()=>{let{entries:e,index:r}=w.current;if(r<=0)return;let s=e[r-1];b(e=>({...e,index:e.index-1})),J(s.path),null!=s.line&&x({line:s.line,nonce:++v.current})},[J]),en=(0,$.useCallback)(()=>{let{entries:e,index:r}=w.current;if(r>=e.length-1)return;let s=e[r+1];b(e=>({...e,index:e.index+1})),J(s.path),null!=s.line&&x({line:s.line,nonce:++v.current})},[J]),ei=(0,$.useCallback)(async n=>{if(e)if(""===n)o((await ry.api.browseProjectDirectory(e,void 0,r,s,i)).items);else{let a=await ry.api.browseProjectDirectory(e,n,r,s,i);c(e=>{let r=new Map(e);return r.set(n,a.items),r})}},[e,r,s,i]),ea=(0,$.useCallback)(async(n,i)=>{if(e&&0!==i.length){D(e=>new Set(e).add(n));try{let{uploaded:a}=await ry.api.uploadFiles(e,i,n,r,s),o=new Set(a.map(e=>n?`${n}/${e}`:e));M.current.deleteWhere(e=>o.has(Ci(e))),""!==n&&u(e=>new Set(e).add(n)),await ei(n),gS.toast.success(`Uploaded ${a.length} file${1===a.length?"":"s"}`)}catch(e){console.error("Failed to upload files:",e),gS.toast.error("Upload failed",{description:e instanceof Error?e.message:String(e)})}finally{D(e=>{let r=new Set(e);return r.delete(n),r})}}},[e,r,s,ei]),eo=(0,$.useCallback)(async n=>{if(e&&n){T(e=>new Set(e).add(n));try{await ry.api.deleteFile(e,n,r,s),M.current.deleteWhere(e=>{let r=Ci(e);return r===n||r.startsWith(`${n}/`)}),f(e=>e===n||e&&e.startsWith(`${n}/`)?(m(null),null):e);let i=n.includes("/")?n.slice(0,n.lastIndexOf("/")):"";await ei(i),gS.toast.success("Deleted")}catch(e){console.error("Failed to delete:",e),gS.toast.error("Delete failed",{description:e instanceof Error?e.message:String(e)})}finally{T(e=>{let r=new Set(e);return r.delete(n),r})}}},[e,r,s,ei]);return{rootEntries:a,directoryContents:l,expandedDirs:d,selectedFile:h,fileContent:p,fileLoading:_,rootLoading:j,loadingDirs:C,uploadingDirs:E,deletingPaths:R,jumpTarget:g,canGoBack:y.index>0,canGoForward:y.index<y.entries.length-1,fetchRoot:Q,refresh:ee,reportScroll:X,restoreScroll:W,toggleDirectory:Y,selectFile:J,navigate:et,jumpTo:er,goBack:es,goForward:en,uploadFiles:ea,refreshDirectory:ei,deleteEntry:eo}}({projectId:e,branch:s,target:o,sessionId:i,showHidden:l}),B=function({projectId:e,branch:r,target:s}){let[n,i]=(0,$.useState)([]),[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(!1),[d,u]=(0,$.useState)(!1),[h,f]=(0,$.useState)(""),p=(0,$.useRef)(0);(0,$.useEffect)(()=>{i([]),o(!1),u(!1),c(!1),f(""),p.current++},[e,r,s]);let m=(0,$.useCallback)(async()=>{if(!e)return;c(!0);let n=++p.current;try{let a=await ry.api.listProjectFiles(e,r,s);if(n!==p.current)return;i(a.files),o(a.truncated),u(!0)}catch(e){if(n!==p.current)return;i([]),u(!1),gS.toast.error("Failed to load file list",{description:e instanceof Error?e.message:String(e)})}finally{n===p.current&&c(!1)}},[e,r,s]),g=(0,$.useCallback)(()=>{d||l||m()},[d,l,m]),x=(0,$.useCallback)(()=>{u(!1),p.current++,h&&m()},[h,m]),v=(0,$.useDeferredValue)(h);return{query:h,setQuery:f,results:(0,$.useMemo)(()=>(function(e,r,s){if(!r.trim())return[];let n=[];for(let s of e){let e=dx(r,s);null!==e&&n.push({path:s,score:e})}return n.sort((e,r)=>r.score-e.score||e.path.length-r.path.length),n.slice(0,50)})(n,v,0),[n,v]),truncated:a,loading:l,loaded:d,ensureLoaded:g,refresh:x}}({projectId:e,branch:s,target:o});(0,$.useEffect)(()=>{E()},[E]),(0,$.useEffect)(()=>{n&&(null!=n.line?M(n.path,n.line):I(n.path))},[n?.nonce]);let H=(0,$.useCallback)(()=>{D(),B.refresh()},[D,B]),U=(0,$.useCallback)(e=>{I(e),B.setQuery("")},[I,B]);if(!e)return(0,z.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(mt,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to browse files."})]})});let q=v&&e?ry.api.getFileDownloadUrl(e,v,s,o,i):null;return(0,z.jsxs)("div",{className:"flex flex-col h-full",style:{"--files-tree-font-size":`${d.filesTreeFontSize}px`,"--files-content-font-size":`${d.filesContentFontSize}px`},children:[(0,z.jsx)(dB,{title:"Files",actions:(0,z.jsxs)("div",{className:"flex items-center gap-1",children:[(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:p,title:h?"Show file tree":"Hide file tree","aria-pressed":!h,children:h?(0,z.jsx)(j7,{className:"h-3.5 w-3.5"}):(0,z.jsx)(j6,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:`h-7 w-7 hover:text-foreground ${l?"text-foreground":"text-muted-foreground"}`,onClick:()=>c(e=>!e),title:l?"Hide hidden files":"Show hidden files","aria-pressed":l,children:l?(0,z.jsx)(_P,{className:"h-3.5 w-3.5"}):(0,z.jsx)(_L,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:F,disabled:!C,title:"Back",children:(0,z.jsx)(n4.ArrowLeft,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:P,disabled:!N,title:"Forward",children:(0,z.jsx)(j8,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:H,title:"Refresh",children:(0,z.jsx)(mt,{className:`h-3.5 w-3.5 ${w?"animate-spin":""}`})})]})}),(0,z.jsxs)(uZ,{direction:"horizontal",autoSaveId:"files-panels",className:"flex-1",children:[(0,z.jsx)(d0,{ref:u,collapsible:!0,collapsedSize:0,defaultSize:33,minSize:20,onCollapse:()=>f(!0),onExpand:()=>f(!1),children:(0,z.jsxs)(p_,{shouldFilter:!1,className:"flex h-full flex-col bg-transparent",children:[(0,z.jsx)("div",{className:"border-b p-2",children:(0,z.jsxs)(j9,{children:[(0,z.jsx)(kt,{children:(0,z.jsx)(sA,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(kn,{type:"search",name:"files-search",autoComplete:"off","data-1p-ignore":!0,"data-lpignore":"true","data-form-type":"other",readOnly:!0,onFocus:e=>{e.currentTarget.removeAttribute("readonly"),B.ensureLoaded()},placeholder:"Search files...",value:B.query,onChange:e=>B.setQuery(e.target.value)}),B.query&&(0,z.jsx)(kt,{align:"inline-end",children:(0,z.jsx)(ks,{size:"icon-xs","aria-label":"Clear search",onClick:()=>B.setQuery(""),children:(0,z.jsx)(t7,{className:"h-3.5 w-3.5"})})})]})}),B.query?(0,z.jsx)(pk,{className:"max-h-none flex-1",children:B.loading&&0===B.results.length?(0,z.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"}),"Loading files…"]}):0===B.results.length?(0,z.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No matching files."}):(0,z.jsxs)(z.Fragment,{children:[B.results.map(e=>{let r=e.path.lastIndexOf("/"),s=r>=0?e.path.slice(0,r+1):"",n=r>=0?e.path.slice(r+1):e.path;return(0,z.jsxs)(pE,{value:e.path,onSelect:()=>U(e.path),className:"flex-col items-start gap-0 text-[length:var(--files-tree-font-size,14px)]!",children:[(0,z.jsx)("span",{className:"font-medium",children:n}),s&&(0,z.jsx)("span",{className:"w-full truncate text-xs text-muted-foreground",children:s})]},e.path)}),B.truncated&&(0,z.jsx)("div",{className:"px-2 py-2 text-xs text-muted-foreground",children:"Showing first 50,000 files — refine your search to narrow results."})]})}):(0,z.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,z.jsx)(kg,{entries:m,expandedDirs:x,directoryContents:g,loadingDirs:_,selectedFile:v,uploadingDirs:S,rootLoading:w,deletingPaths:j,onToggleDirectory:A,onSelectFile:I,onUploadFiles:L,onDeleteEntry:O})})]})}),(0,z.jsx)(uQ,{withHandle:!0,disabled:!a}),(0,z.jsx)(d0,{defaultSize:67,minSize:25,children:(0,z.jsx)("div",{className:"h-full overflow-hidden",children:(0,z.jsx)(k9,{filePath:v,fileContent:y,loading:b,downloadUrl:q,projectId:e,branch:s,target:o,sessionId:i,scrollToLine:k?.line??null,scrollKey:k?.nonce,onJump:M,restoreScrollTop:T?.top??null,restoreScrollKey:T?.nonce,onScroll:R})})})]})]})}let Co=(0,$.createContext)(null),Cl={openFile:()=>{},index:null,scope:null};function Cc(){return(0,$.useContext)(Co)??Cl}let Cd=Co.Provider,Cu=0;function Ch(e){let r=e.lastIndexOf("/");return r>=0?e.slice(r+1):e}function Cf(e,r){let s=`idx-${++Cu}`,n=new Set(e),i=r?r.replace(/\/+$/,"")+"/":null,a=new Map;for(let r of e){let e=Ch(r),s=a.get(e);s?s.push(r):a.set(e,[r])}return{version:s,resolve(e){if(!e)return[];if(i&&(e.startsWith("/")||e.startsWith("~/"))){if(!e.startsWith(i))return[];let r=e.slice(i.length);return n.has(r)?[r]:[]}let r=e.replace(/^\/+/,"");if(!r)return[];if(r.includes("/")){if(n.has(r))return[r];let e=Ch(r);return(a.get(e)??[]).filter(e=>e===r||e.endsWith("/"+r)||r.endsWith("/"+e))}return a.get(r)??[]}}}let Cp=[500,1e3,2e3,4e3,8e3];async function Cm(e,r={}){let s=r.delaysMs??Cp,n=r.sleep??(e=>new Promise(r=>setTimeout(r,e))),i=r.cancelled??(()=>!1);for(let r=0;;r++){if(i())return null;let a=null;try{a=await e()}catch{a=null}if(i())return null;if(a&&a.files.length>0||r>=s.length)return a;await n(s[r])}}let Cg=(0,$.createContext)({active:!1,requestNonce:0}),Cx=Cg.Provider,Cv={agent:sS,executors:gM,diff:sq,terminal:p9,preview:rw,files:rb},Cy=fv.map(e=>({...e,icon:Cv[e.id]})),Cb=()=>()=>{},Cw=$.useLayoutEffect;function C_({projectId:e,selectedBranch:r,onMergeRequest:s,project:n,onExecutorModeChange:i,agentSlot:a,activateAgentTabNonce:o,diffCompareNonce:l,terminalRequest:c,mergeTarget:d,forceAgentTab:u=!1,active:h=!0,agentSessionId:f=null}){let[p,m]=function(e,r){let s=`vibedeckx:activeTab:${e??"none"}:${r??"main"}`,[n,i]=(0,$.useState)(()=>localStorage.getItem(s)??"agent");return Cw(()=>{i(localStorage.getItem(s)??"agent")},[s]),[n,(0,$.useCallback)(e=>{i(e),localStorage.setItem(s,e)},[s])]}(e,r),g=u?"agent":p,x=(0,$.useRef)(o);Cw(()=>{void 0===o||x.current!==o&&(x.current=o,m("agent"))},[o,m]);let v=(0,$.useRef)(l);Cw(()=>{void 0===l||v.current!==l&&(v.current=l,m("diff"))},[l,m]);let y=(0,$.useRef)(c?.nonce);Cw(()=>{null==c||y.current!==c.nonce&&(y.current=c.nonce,m("terminal"))},[c,m]);let[b,w]=(0,$.useState)(0),_=(0,$.useCallback)(()=>w(e=>e+1),[]),S=(0,$.useRef)(null),j=(0,$.useRef)(!1),[k,C]=(0,$.useState)(0),N=(0,$.useCallback)(()=>{j.current=!0,C(e=>e+1)},[]);Cw(()=>{!j.current||(j.current=!1,h&&null!==e&&"executors"===g&&S.current?.focus({preventScroll:!0}))},[h,g,k,e]);let{region:E,setRegion:D}=dD(),R="right-panel"===E;(0,$.useEffect)(()=>{if(!h)return;let e=e=>{let r=fS(e);r&&(e.preventDefault(),m(r),D("right-panel"),"agent"===r&&_(),"executors"===r&&N())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[h,m,D,_,N]);let T=(0,$.useSyncExternalStore)(Cb,fb,()=>!1),A=n&&!n.path?"remote":void 0,I=function({projectId:e,branch:r,target:s,enabled:n=!0}){let[i,a]=(0,$.useState)(null),o=(0,$.useRef)(0),l=(0,$.useRef)(0),c=(0,$.useRef)(null);return(0,$.useEffect)(()=>{if(a(null),!n||!e)return;let i=++o.current;return Cm(()=>ry.api.listProjectFiles(e,r,s),{cancelled:()=>i!==o.current}).then(e=>{i===o.current&&a(e?Cf(e.files,e.root):Cf([]))}),()=>{null!==c.current&&(clearTimeout(c.current),c.current=null)}},[e,r,s,n]),(0,sx.useGlobalEventStream)(i=>{if(!n||!e)return;let d="session:taskCompleted"===i.type||"session:finished"===i.type,u="files:changed"===i.type;if(!d&&!u||i.projectId!==e||(i.branch??null)!==(r??null))return;null!==c.current&&clearTimeout(c.current);let h=o.current;c.current=setTimeout(()=>{c.current=null;let n=++l.current;ry.api.listProjectFiles(e,r,s).then(e=>{h===o.current&&n===l.current&&a(Cf(e.files,e.root))}).catch(()=>{})},250)}),i}({projectId:e,branch:r,target:A,enabled:h}),M=(0,$.useRef)(0),[F,P]=(0,$.useState)(null),L=(0,$.useCallback)((e,r=null)=>{m("files"),P({path:e,line:r,nonce:++M.current})},[m]),O=(0,$.useMemo)(()=>e?{projectId:e,branch:r??null,target:A,sessionId:f}:null,[e,r,A,f]),B=(0,$.useMemo)(()=>({openFile:L,index:I,scope:O}),[L,I,O]),W=(0,$.useMemo)(()=>({active:h&&null!==e&&"agent"===g,requestNonce:b}),[h,e,g,b]);return(0,z.jsx)(Cd,{value:B,children:(0,z.jsxs)("div",{"data-focus-region":"right-panel",className:"h-full flex flex-col",children:[(0,z.jsx)("div",{className:"flex items-center px-3 gap-4 border-b border-border",children:Cy.map(({id:e,icon:r,label:s,code:n})=>(0,z.jsxs)($.Fragment,{children:[(0,z.jsxs)("button",{onClick:()=>{m(e),"agent"===e&&_(),"executors"===e&&N()},title:`${s} (${fj(T,n)})`,className:(0,eb.cn)("flex items-center gap-0.5 py-2.5 text-xs font-medium border-b-2 transition-colors",g===e?(0,eb.cn)("text-foreground",R?"border-primary":"border-foreground/25"):"text-muted-foreground border-transparent hover:text-foreground/70"),children:[(0,z.jsx)(r,{className:"h-3.5 w-3.5"}),s]}),"agent"===e&&(0,z.jsx)("span",{className:"h-4 w-px bg-border/60 mx-1.5","aria-hidden":!0})]},e))}),(0,z.jsxs)("div",{className:"relative flex-1 overflow-hidden",children:[(0,z.jsx)("div",{className:(0,eb.cn)("absolute inset-0 overflow-hidden","agent"!==g&&"invisible pointer-events-none"),children:(0,z.jsx)(Cx,{value:W,children:a})}),(0,z.jsx)("div",{ref:S,tabIndex:-1,className:(0,eb.cn)("absolute inset-0 overflow-hidden outline-hidden","executors"!==g&&"hidden"),children:(0,z.jsx)(jz,{projectId:e,selectedBranch:r,project:n,onExecutorModeChange:i,locateActive:h&&"executors"===g})}),(0,z.jsx)("div",{className:(0,eb.cn)("absolute inset-0 overflow-hidden","diff"!==g&&"hidden"),children:(0,z.jsx)(jG,{projectId:e,selectedBranch:r,onMergeRequest:s,project:n,mergeTarget:d,compareRequestNonce:l})}),(0,z.jsx)("div",{className:(0,eb.cn)("absolute inset-0 overflow-hidden","terminal"!==g&&"hidden"),children:(0,z.jsx)(jZ,{projectId:e,selectedBranch:r,project:n,active:h&&"terminal"===g,createRequest:c})}),(0,z.jsx)("div",{className:(0,eb.cn)("absolute inset-0 overflow-hidden","preview"!==g&&"hidden"),children:(0,z.jsx)(j4,{projectId:e,selectedBranch:r,project:n})}),(0,z.jsx)("div",{className:(0,eb.cn)("absolute inset-0 overflow-hidden","files"!==g&&"hidden"),children:(0,z.jsx)(Ca,{projectId:e,project:n,selectedBranch:r,navRequest:F,sessionId:f,active:"files"===g})})]})]})})}var CS=Symbol.for("immer-nothing"),Cj=Symbol.for("immer-draftable"),Ck=Symbol.for("immer-state");function CC(e){throw Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var CN=Object.getPrototypeOf;function CE(e){return!!e&&!!e[Ck]}function CD(e){return!!e&&(CA(e)||Array.isArray(e)||!!e[Cj]||!!e.constructor?.[Cj]||CL(e)||CO(e))}var CR=Object.prototype.constructor.toString(),CT=new WeakMap;function CA(e){if(!e||"object"!=typeof e)return!1;let r=Object.getPrototypeOf(e);if(null===r||r===Object.prototype)return!0;let s=Object.hasOwnProperty.call(r,"constructor")&&r.constructor;if(s===Object)return!0;if("function"!=typeof s)return!1;let n=CT.get(s);return void 0===n&&(n=Function.toString.call(s),CT.set(s,n)),n===CR}function CI(e,r,s=!0){0===CM(e)?(s?Reflect.ownKeys(e):Object.keys(e)).forEach(s=>{r(s,e[s],e)}):e.forEach((s,n)=>r(n,s,e))}function CM(e){let r=e[Ck];return r?r.type_:Array.isArray(e)?1:CL(e)?2:3*!!CO(e)}function CF(e,r){return 2===CM(e)?e.has(r):Object.prototype.hasOwnProperty.call(e,r)}function CP(e,r,s){let n=CM(e);2===n?e.set(r,s):3===n?e.add(s):e[r]=s}function CL(e){return e instanceof Map}function CO(e){return e instanceof Set}function CB(e){return e.copy_||e.base_}function Cz(e,r){if(CL(e))return new Map(e);if(CO(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let s=CA(e);if(!0!==r&&("class_only"!==r||s)){let r=CN(e);return null!==r&&s?{...e}:Object.assign(Object.create(r),e)}{let r=Object.getOwnPropertyDescriptors(e);delete r[Ck];let s=Reflect.ownKeys(r);for(let n=0;n<s.length;n++){let i=s[n],a=r[i];!1===a.writable&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[i]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[i]})}return Object.create(CN(e),r)}}function C$(e,r=!1){return CH(e)||CE(e)||!CD(e)||(CM(e)>1&&Object.defineProperties(e,{set:CW,add:CW,clear:CW,delete:CW}),Object.freeze(e),r&&Object.values(e).forEach(e=>C$(e,!0))),e}var CW={value:function(){CC(2)}};function CH(e){return null===e||"object"!=typeof e||Object.isFrozen(e)}var CU={};function Cq(e){let r=CU[e];return r||CC(0,e),r}function CK(e,r){r&&(Cq("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=r)}function CV(e){CX(e),e.drafts_.forEach(CG),e.drafts_=null}function CX(e){e===O&&(O=e.parent_)}function CY(e){return O={drafts_:[],parent_:O,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function CG(e){let r=e[Ck];0===r.type_||1===r.type_?r.revoke_():r.revoked_=!0}function CJ(e,r){r.unfinalizedDrafts_=r.drafts_.length;let s=r.drafts_[0];return void 0!==e&&e!==s?(s[Ck].modified_&&(CV(r),CC(4)),CD(e)&&(e=CZ(r,e),r.parent_||C0(r,e)),r.patches_&&Cq("Patches").generateReplacementPatches_(s[Ck].base_,e,r.patches_,r.inversePatches_)):e=CZ(r,s,[]),CV(r),r.patches_&&r.patchListener_(r.patches_,r.inversePatches_),e!==CS?e:void 0}function CZ(e,r,s){if(CH(r))return r;let n=e.immer_.shouldUseStrictIteration(),i=r[Ck];if(!i)return CI(r,(n,a)=>CQ(e,i,r,n,a,s),n),r;if(i.scope_!==e)return r;if(!i.modified_)return C0(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;let r=i.copy_,a=r,o=!1;3===i.type_&&(a=new Set(r),r.clear(),o=!0),CI(a,(n,a)=>CQ(e,i,r,n,a,s,o),n),C0(e,r,!1),s&&e.patches_&&Cq("Patches").generatePatches_(i,s,e.patches_,e.inversePatches_)}return i.copy_}function CQ(e,r,s,n,i,a,o){if(null==i||"object"!=typeof i&&!o)return;let l=CH(i);if(!l||o){if(CE(i)){let o=CZ(e,i,a&&r&&3!==r.type_&&!CF(r.assigned_,n)?a.concat(n):void 0);if(CP(s,n,o),!CE(o))return;e.canAutoFreeze_=!1}else o&&s.add(i);if(CD(i)&&!l){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||r&&r.base_&&r.base_[n]===i&&l)return;CZ(e,i),(!r||!r.scope_.parent_)&&"symbol"!=typeof n&&(CL(s)?s.has(n):Object.prototype.propertyIsEnumerable.call(s,n))&&C0(e,i)}}}function C0(e,r,s=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&C$(r,s)}var C1={get(e,r){if(r===Ck)return e;let s=CB(e);if(!CF(s,r)){var n;let i;return n=e,(i=C3(s,r))?"value"in i?i.value:i.get?.call(n.draft_):void 0}let i=s[r];return e.finalized_||!CD(i)?i:i===C5(e.base_,r)?(C6(e),e.copy_[r]=C7(i,e)):i},has:(e,r)=>r in CB(e),ownKeys:e=>Reflect.ownKeys(CB(e)),set(e,r,s){let n=C3(CB(e),r);if(n?.set)return n.set.call(e.draft_,s),!0;if(!e.modified_){let n=C5(CB(e),r),i=n?.[Ck];if(i&&i.base_===s)return e.copy_[r]=s,e.assigned_[r]=!1,!0;if((s===n?0!==s||1/s==1/n:s!=s&&n!=n)&&(void 0!==s||CF(e.base_,r)))return!0;C6(e),C4(e)}return!!(e.copy_[r]===s&&(void 0!==s||r in e.copy_)||Number.isNaN(s)&&Number.isNaN(e.copy_[r]))||(e.copy_[r]=s,e.assigned_[r]=!0,!0)},deleteProperty:(e,r)=>(void 0!==C5(e.base_,r)||r in e.base_?(e.assigned_[r]=!1,C6(e),C4(e)):delete e.assigned_[r],e.copy_&&delete e.copy_[r],!0),getOwnPropertyDescriptor(e,r){let s=CB(e),n=Reflect.getOwnPropertyDescriptor(s,r);return n?{writable:!0,configurable:1!==e.type_||"length"!==r,enumerable:n.enumerable,value:s[r]}:n},defineProperty(){CC(11)},getPrototypeOf:e=>CN(e.base_),setPrototypeOf(){CC(12)}},C2={};function C5(e,r){let s=e[Ck];return(s?CB(s):e)[r]}function C3(e,r){if(!(r in e))return;let s=CN(e);for(;s;){let e=Object.getOwnPropertyDescriptor(s,r);if(e)return e;s=CN(s)}}function C4(e){!e.modified_&&(e.modified_=!0,e.parent_&&C4(e.parent_))}function C6(e){e.copy_||(e.copy_=Cz(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function C7(e,r){let s=CL(e)?Cq("MapSet").proxyMap_(e,r):CO(e)?Cq("MapSet").proxySet_(e,r):function(e,r){let s=Array.isArray(e),n={type_:+!!s,scope_:r?r.scope_:O,modified_:!1,finalized_:!1,assigned_:{},parent_:r,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},i=n,a=C1;s&&(i=[n],a=C2);let{revoke:o,proxy:l}=Proxy.revocable(i,a);return n.draft_=l,n.revoke_=o,l}(e,r);return(r?r.scope_:O).drafts_.push(s),s}CI(C1,(e,r)=>{C2[e]=function(){return arguments[0]=arguments[0][0],r.apply(this,arguments)}}),C2.deleteProperty=function(e,r){return C2.set.call(this,e,r,void 0)},C2.set=function(e,r,s){return C1.set.call(this,e[0],r,s,e[0])};var C8=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(e,r,s)=>{let n;if("function"==typeof e&&"function"!=typeof r){let s=r;r=e;let n=this;return function(e=s,...i){return n.produce(e,e=>r.call(this,e,...i))}}if("function"!=typeof r&&CC(6),void 0!==s&&"function"!=typeof s&&CC(7),CD(e)){let i=CY(this),a=C7(e,void 0),o=!0;try{n=r(a),o=!1}finally{o?CV(i):CX(i)}return CK(i,s),CJ(n,i)}if(e&&"object"==typeof e)CC(1,e);else{if(void 0===(n=r(e))&&(n=e),n===CS&&(n=void 0),this.autoFreeze_&&C$(n,!0),s){let r=[],i=[];Cq("Patches").generateReplacementPatches_(e,n,r,i),s(r,i)}return n}},this.produceWithPatches=(e,r)=>{let s,n;return"function"==typeof e?(r,...s)=>this.produceWithPatches(r,r=>e(r,...s)):[this.produce(e,r,(e,r)=>{s=e,n=r}),s,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),"boolean"==typeof e?.useStrictIteration&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){var r;CD(e)||CC(8),CE(e)&&(CE(r=e)||CC(10,r),e=function e(r){let s;if(!CD(r)||CH(r))return r;let n=r[Ck],i=!0;if(n){if(!n.modified_)return n.base_;n.finalized_=!0,s=Cz(r,n.scope_.immer_.useStrictShallowCopy_),i=n.scope_.immer_.shouldUseStrictIteration()}else s=Cz(r,!0);return CI(s,(r,n)=>{CP(s,r,e(n))},i),n&&(n.finalized_=!1),s}(r));let s=CY(this),n=C7(e,void 0);return n[Ck].isManual_=!0,CX(s),n}finishDraft(e,r){let s=e&&e[Ck];s&&s.isManual_||CC(9);let{scope_:n}=s;return CK(n,r),CJ(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,r){let s;for(s=r.length-1;s>=0;s--){let n=r[s];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}s>-1&&(r=r.slice(s+1));let n=Cq("Patches").applyPatches_;return CE(e)?n(e,r):this.produce(e,e=>n(e,r))}}().produce;let C9="vibedeckx:pending-submissions";function Ne(){try{let e=window.sessionStorage.getItem(C9);if(!e)return new Map;let r=JSON.parse(e);if(!Array.isArray(r))return new Map;let s=new Map;for(let e of r)e&&"object"==typeof e&&"string"==typeof e.workspaceKey&&"string"==typeof e.operationId&&s.set(e.workspaceKey,e);return s}catch{return new Map}}function Nt(e){try{0===e.size?window.sessionStorage.removeItem(C9):window.sessionStorage.setItem(C9,JSON.stringify([...e.values()]))}catch{}}function Nr(e){return Ne().get(e)??null}function Ns(e){let r=Ne(),s=r.get(e.workspaceKey)??null;return r.set(e.workspaceKey,e),Nt(r),s&&s.operationId!==e.operationId?s:null}function Nn(e,r){let s=Ne(),n=s.get(e);return!!n&&n.operationId===r&&(s.delete(e),Nt(s),!0)}let Ni="vibedeckx:placeholder-workspaces";function Na(e){try{window.localStorage.setItem(Ni,JSON.stringify([...e]))}catch{}}let No=function(){try{let e=window.localStorage.getItem(Ni);if(!e)return new Map;let r=JSON.parse(e);if(!Array.isArray(r))return new Map;let s=new Map;for(let e of r)if(Array.isArray(e)&&"string"==typeof e[0]&&"number"==typeof e[1]){let r=e[0].endsWith(":")?`${e[0]}local`:e[0];s.set(r,e[1])}else if("string"==typeof e){let r=e.endsWith(":")?`${e}local`:e;s.set(r,Date.now())}return s}catch{return new Map}}(),Nl=new Set,Nc=new Map;function Nd(){for(let e of Nl)e()}function Nu(e){return Nl.add(e),()=>{Nl.delete(e)}}function Nh(){return No}function Nf(){return Nc}function Np(e,r,s){return`${e}:${r??""}:${s||"local"}`}function Nm(e){return No.has(e)}function Ng(e){let r=new Map(No);r.set(e,Date.now()),Na(No=r),Nd()}function Nx(e){if(!No.has(e))return!1;let r=new Map(No);return r.delete(e),Na(No=r),Nd(),!0}function Nv(e,r,s,n){return e?{projectId:e,branch:r,agentMode:s||"local",explicitSessionId:n??null}:null}function Ny(e,r){return e.projectId===r.projectId&&e.branch===r.branch&&e.agentMode===r.agentMode&&e.explicitSessionId===r.explicitSessionId}function Nb(){return"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}async function Nw(e,r,s,n){let i=await (0,ry.authFetch)(`${Nb()}/api/projects/${e}/agent-sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:r,permissionMode:s,agentType:n,historyTurns:5})});if(!i.ok)throw Error("Failed to load session");return i.json()}async function N_(e,r,s){let n=await (0,ry.authFetch)(`${Nb()}/api/agent-sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r,...s?{grantedRemoteIds:s}:{}})});if(!n.ok){let r="";try{let e=await n.json();if(e.errorCode){let s=[`${e.errorCode}`];e.attempts&&s.push(`${e.attempts} attempts`),e.totalDurationMs&&s.push(`${(e.totalDurationMs/1e3).toFixed(1)}s`),r=` (${s.join(", ")})`}else e.error&&(r=` — ${e.error}`)}catch{}throw console.error(`[AgentSession] /message failed: status=${n.status}, sessionId=${e}, detail=${r}`),Error(`Failed to send message [${n.status}]${r}`)}}async function NS(e){let r=await (0,ry.authFetch)(`${Nb()}/api/agent-sessions/${e}/discard-if-empty`,{method:"POST"});if(r.ok)return!0;if(404===r.status||409===r.status)return!1;throw Error(`Failed to discard empty session [${r.status}]`)}async function Nj(e,r){let s=await (0,ry.authFetch)(`${Nb()}/api/agent-sessions/${e}/paste`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r})});if(!s.ok){let r="";try{let e=await s.json();if(e.errorCode){let s=[`${e.errorCode}`];e.attempts&&s.push(`${e.attempts} attempts`),e.totalDurationMs&&s.push(`${(e.totalDurationMs/1e3).toFixed(1)}s`),r=` (${s.join(", ")})`}else e.error&&(r=` — ${e.error}`)}catch{}throw console.error(`[AgentSession] /paste failed: status=${s.status}, sessionId=${e}, detail=${r}`),Error(`Failed to upload paste [${s.status}]${r}`)}return s.json()}async function Nk(e,r,s){let n=`${Nb()}/api/agent-sessions/${e}/attachment`,i=JSON.stringify(r),a=e=>new Promise((a,o)=>{let l=new XMLHttpRequest;l.open("POST",n),l.setRequestHeader("Content-Type","application/json"),e&&l.setRequestHeader("Authorization",`Bearer ${e}`),l.upload.onprogress=e=>{e.lengthComputable&&e.total>0&&s?.(Math.min(1,e.loaded/e.total))},l.onload=()=>a({status:l.status,text:l.responseText}),l.onerror=()=>o(Error(`Failed to upload ${r.name}`)),l.onabort=()=>o(Error(`Upload of ${r.name} was cancelled`)),l.send(i)}),o=await a(await (0,ry.getFreshToken)());if(401===o.status&&(o=await a(await (0,ry.getFreshToken)({skipCache:!0}))),o.status<200||o.status>=300){let s=`Failed to upload ${r.name} [${o.status}]`;try{let e=JSON.parse(o.text);"string"==typeof e?.error&&e.error&&(s=e.error)}catch{}throw console.error(`[AgentSession] /attachment failed: status=${o.status}, sessionId=${e}, name=${r.name}`),Error(s)}return s?.(1),JSON.parse(o.text)}async function NC(e,r){if(!(await (0,ry.authFetch)(`${Nb()}/api/agent-sessions/${e}/restart`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentType:r})})).ok)throw Error("Failed to restart session")}async function NN(e,r){let s=await (0,ry.authFetch)(`${Nb()}/api/agent-sessions/${e}/agent-type`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentType:r})});if(!s.ok){let e="";try{let r=await s.json();r.error&&(e=r.error)}catch{}throw Error(e||`Failed to switch agent [${s.status}]`)}}async function NE(e,r){let s=await (0,ry.authFetch)(`${Nb()}/api/agent-sessions/${e}/model`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r})});if(!s.ok){let e="";try{let r=await s.json();r.error&&(e=r.error)}catch{}throw Error(e||`Failed to set model [${s.status}]`)}return(await s.json().catch(()=>({}))).model??null}async function ND(e){if(!(await (0,ry.authFetch)(`${Nb()}/api/agent-sessions/${e}/stop`,{method:"POST"})).ok)throw Error("Failed to stop session")}async function NR(e,r){if(!(await (0,ry.authFetch)(`${Nb()}/api/agent-sessions/${e}/switch-mode`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:r})})).ok)throw Error("Failed to switch mode")}async function NT(e,r){if(!(await (0,ry.authFetch)(`${Nb()}/api/agent-sessions/${e}/accept-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planContent:r})})).ok)throw Error("Failed to accept plan")}let NA=new Map,NI=new Map;function NM(e,r,s){return`${e}:${r??""}:${s??"latest"}`}function NF(e){let r=NA.get(e);if(r){NA.delete(e),NA.set(e,r);if(void 0===r.session.processAlive)return r;let s={...r.session};return delete s.processAlive,{session:s,history:r.history.session?{...r.history,session:s}:r.history}}}function NP(e,r){for(NA.delete(e),NA.set(e,r);NA.size>16;){let e=NA.keys().next().value;if(void 0===e)break;NA.delete(e)}}function NL(e,r,s,n,i){let a={session:n,history:{...i,entries:[...i.entries]}};NP(NM(e,r,s),a),NP(NM(e,r,n.id),a)}function NO(e,r,s,n){let i=NM(e,r,s);NA.get(i)?.session.id===n&&NA.delete(i),NA.delete(NM(e,r,n))}function NB(e,r,s,n){let i=NF(NM(e,r,n.id))??NF(NM(e,r,s));i&&NL(e,r,s,n,i.history)}async function Nz(e,r){let s=new URLSearchParams({turns:String(5)});null!=r&&s.set("before",String(r));let n=await (0,ry.authFetch)(`${Nb()}/api/agent-sessions/${e}/history-window?${s}`);if(!n.ok)throw Error(`Session ${e} not found`);let i=await n.json();if(Array.isArray(i.entries))return i;let a=i.messages??[];return{historyEpoch:0,latestEntryIndex:a.length>0?a.length-1:null,lastTurnEndEntryIndex:a.reduce((e,r,s)=>"turn_end"===r.type?s:e,null),entries:a.map((e,r)=>({entryIndex:r,message:e})),previousCursor:null,hasMore:!1,status:i.session?.status??"stopped",session:i.session}}function N$(e){let r=NI.get(e);if(r)return r;let s=Nz(e).finally(()=>NI.delete(e));return NI.set(e,s),s}async function NW(e){let r=await (0,ry.authFetch)(`${Nb()}/api/agent-sessions/${e}/history-head`);if(!r.ok)throw Error(`Session ${e} not found`);let s=await r.json();if("number"==typeof s.historyEpoch)return s;let n=s.messages??[];return{historyEpoch:0,latestEntryIndex:n.length>0?n.length-1:null,lastTurnEndEntryIndex:n.reduce((e,r,s)=>"turn_end"===r.type?s:e,null),status:s.session?.status??"stopped"}}function NH(e){return Object.fromEntries(e.map(({entryIndex:e,message:r})=>[e,r]))}function NU(e){return Object.entries(e.entries).map(([e,r])=>({entryIndex:Number(e),message:r})).sort((e,r)=>e.entryIndex-r.entryIndex)}function Nq(e){return{historyEpoch:0,latestEntryIndex:null,lastTurnEndEntryIndex:null,entries:[],previousCursor:null,hasMore:!1,status:e.status,session:e}}let NK=(0,e_.default)("user",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]),NV=(0,e_.default)("wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]]),NX=(0,e_.default)("brain",[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]]),NY=(0,e_.default)("file-check",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m9 15 2 2 4-4",key:"1grp1n"}]]),NG=(0,e_.default)("folder-search",[["path",{d:"M10.7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]]),NJ=(0,e_.default)("workflow",[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]]),NZ=(0,e_.default)("file-pen-line",[["path",{d:"m18.226 5.226-2.52-2.52A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-.351",key:"1k2beg"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}],["path",{d:"M8 18h1",key:"13wk12"}]]),NQ=(0,e_.default)("file-plus-corner",[["path",{d:"M11.35 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v5.35",key:"17jvcc"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M14 19h6",key:"bvotb8"}],["path",{d:"M17 16v6",key:"18yu1i"}]]),N0=(0,e_.default)("earth",[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),N1=(0,e_.default)("shield-alert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);var ck=cj,kE=cj;let N2=RegExp("(?<![\\w./-])((?:~?\\/)?[\\w-]+(?:[./][\\w-]+)+)(?::(\\d+)(?::\\d+)?|#L(\\d+)(?:-L?\\d+)?)?","g"),N5=/\[([^\]\n]*)\]\(\s*([^)\s]+?)\s*\)/g;function N3(e){return e.includes("/")||/\.[A-Za-z0-9]+$/.test(e)}function N4(e){let r=e.trim();if(!r)return null;let s=/^(.*?)(?::(\d+)(?::\d+)?|#L(\d+)(?:-L?\d+)?)?$/.exec(r);if(!s||!s[1])return null;let n=s[1];return/^[a-z][a-z0-9+.-]*:/i.test(n)||n.startsWith("//")||n.startsWith("#")?null:{rawPath:n,line:s[2]?Number(s[2]):s[3]?Number(s[3]):null}}var N6="HoverCard",[N7,N8]=q(N6,[ax]),N9=ax(),[Ee,Et]=N7(N6),Er=e=>{let{__scopeHoverCard:r,children:s,open:n,defaultOpen:i,onOpenChange:a,openDelay:o=700,closeDelay:l=300}=e,c=N9(r),d=$.useRef(0),u=$.useRef(0),h=$.useRef(!1),f=$.useRef(!1),[p,m]=Y({prop:n,defaultProp:i??!1,onChange:a,caller:N6}),g=$.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>m(!0),o)},[o,m]),x=$.useCallback(()=>{clearTimeout(d.current),h.current||f.current||(u.current=window.setTimeout(()=>m(!1),l))},[l,m]),v=$.useCallback(()=>m(!1),[m]);return $.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),(0,z.jsx)(Ee,{scope:r,open:p,onOpenChange:m,onOpen:g,onClose:x,onDismiss:v,hasSelectionRef:h,isPointerDownOnContentRef:f,children:(0,z.jsx)(ab,{...c,children:s})})};Er.displayName=N6;var Es="HoverCardTrigger",En=$.forwardRef((e,r)=>{let{__scopeHoverCard:s,...n}=e,i=Et(Es,s),a=N9(s);return(0,z.jsx)(a_,{asChild:!0,...a,children:(0,z.jsx)(er.a,{"data-state":i.open?"open":"closed",...n,ref:r,onPointerEnter:K(e.onPointerEnter,Eh(i.onOpen)),onPointerLeave:K(e.onPointerLeave,Eh(i.onClose)),onFocus:K(e.onFocus,i.onOpen),onBlur:K(e.onBlur,i.onClose),onTouchStart:K(e.onTouchStart,e=>e.preventDefault())})})});En.displayName=Es;var Ei="HoverCardPortal",[Ea,Eo]=N7(Ei,{forceMount:void 0}),El=e=>{let{__scopeHoverCard:r,forceMount:s,children:n,container:i}=e,a=Et(Ei,r);return(0,z.jsx)(Ea,{scope:r,forceMount:s,children:(0,z.jsx)(Z,{present:s||a.open,children:(0,z.jsx)(eW,{asChild:!0,container:i,children:n})})})};El.displayName=Ei;var Ec="HoverCardContent",Ed=$.forwardRef((e,r)=>{let s=Eo(Ec,e.__scopeHoverCard),{forceMount:n=s.forceMount,...i}=e,a=Et(Ec,e.__scopeHoverCard);return(0,z.jsx)(Z,{present:n||a.open,children:(0,z.jsx)(Eu,{"data-state":a.open?"open":"closed",...i,onPointerEnter:K(e.onPointerEnter,Eh(a.onOpen)),onPointerLeave:K(e.onPointerLeave,Eh(a.onClose)),ref:r})})});Ed.displayName=Ec;var Eu=$.forwardRef((e,r)=>{let{__scopeHoverCard:s,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:a,onInteractOutside:o,...l}=e,c=Et(Ec,s),d=N9(s),u=$.useRef(null),h=(0,U.useComposedRefs)(r,u),[f,p]=$.useState(!1);return $.useEffect(()=>{if(f){let e=document.body;return B=e.style.userSelect||e.style.webkitUserSelect,e.style.userSelect="none",e.style.webkitUserSelect="none",()=>{e.style.userSelect=B,e.style.webkitUserSelect=B}}},[f]),$.useEffect(()=>{if(u.current){let e=()=>{p(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{document.getSelection()?.toString()!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",e),()=>{document.removeEventListener("pointerup",e),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),$.useEffect(()=>{u.current&&(function(e){let r=[],s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();)r.push(s.currentNode);return r})(u.current).forEach(e=>e.setAttribute("tabindex","-1"))}),(0,z.jsx)(eR,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:o,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:K(a,e=>{e.preventDefault()}),onDismiss:c.onDismiss,children:(0,z.jsx)(aC,{...d,...l,onPointerDown:K(l.onPointerDown,e=>{e.currentTarget.contains(e.target)&&p(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:h,style:{...l.style,userSelect:f?"text":void 0,WebkitUserSelect:f?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})});function Eh(e){return r=>"touch"===r.pointerType?void 0:e()}function Ef({...e}){return(0,z.jsx)(Er,{"data-slot":"hover-card",...e})}function Ep({...e}){return(0,z.jsx)(En,{"data-slot":"hover-card-trigger",...e})}function Em({className:e,align:r="center",sideOffset:s=4,...n}){return(0,z.jsx)(El,{"data-slot":"hover-card-portal",children:(0,z.jsx)(Ed,{"data-slot":"hover-card-content",align:r,sideOffset:s,className:(0,eb.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...n})})}$.forwardRef((e,r)=>{let{__scopeHoverCard:s,...n}=e,i=N9(s);return(0,z.jsx)(aD,{...i,...n,ref:r})}).displayName="HoverCardArrow";let Eg="text-primary underline decoration-dotted underline-offset-2 cursor-pointer hover:decoration-solid",Ex="wrap-anywhere font-medium text-primary underline decoration-primary/60 underline-offset-2 transition-colors hover:text-primary/80 hover:decoration-primary",Ev="text-primary/80 underline decoration-dotted underline-offset-2 cursor-pointer hover:decoration-solid",Ey=new Set(["png","jpg","jpeg","gif","webp","bmp","ico","avif","svg"]);function Eb({paths:e,line:r,children:s}){let{openFile:n}=Cc();return(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)("a",{href:"#",className:Eg,onClick:e=>e.preventDefault(),children:s})}),(0,z.jsxs)(o1,{align:"start",className:"max-w-md",children:[(0,z.jsxs)(o6,{children:[e.length," matching files"]}),e.map(e=>(0,z.jsx)(o2,{className:"font-mono text-xs",onSelect:()=>n(e,r),children:e},e))]})]})}function Ew({scope:e,filePath:r}){let[s,n]=(0,$.useState)(null),[i,a]=(0,$.useState)(null),[o,l]=(0,$.useState)(null),{label:c}=gf(null!==o&&o!==kH(e.sessionId)?o:null);return((0,$.useEffect)(()=>{let s=null,i=!1;return ry.api.getFileBlob(e.projectId,r,e.branch,e.target,e.sessionId).then(({blob:e,serverId:r})=>{if(!i){if(e.size>0xa00000)return void a("Too large to preview — click to open");l(r),n(s=URL.createObjectURL(e))}}).catch(e=>{if(i)return;let r=e instanceof Error?e.message:"";a(/not found/i.test(r)?"File not found":"Couldn't load image")}),()=>{i=!0,s&&URL.revokeObjectURL(s)}},[e.projectId,e.branch,e.target,e.sessionId,r]),i)?(0,z.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1.5 text-xs text-muted-foreground",children:[(0,z.jsx)(kq,{className:"h-3.5 w-3.5"}),i]}):s?(0,z.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,z.jsx)("img",{src:s,alt:r,className:"block max-h-64 max-w-[22rem] rounded object-contain"}),c&&(0,z.jsxs)("p",{className:"px-0.5 text-xs text-muted-foreground",children:["on ",(0,z.jsx)("span",{className:"text-foreground",children:c})]})]}):(0,z.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1.5 text-xs text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-3.5 w-3.5 animate-spin"}),"Loading preview…"]})}let{harden:E_,...ES}=kE.e,Ej=[...Object.values(ES),function(){function e(e,r,s){return{type:"element",tagName:"a",properties:{className:["file-ref"],href:"#file-ref",dataFileRaw:e,...null!=r?{dataFileLine:String(r)}:{}},children:s}}return r=>{!function r(s,n=!1){if(!s.children)return;let i=n||"pre"===s.tagName,a=[];for(let n of s.children)"text"===n.type?i?a.push(n):a.push(...function(r){let s=function(e){let r,s=[],n=[];for(N5.lastIndex=0;null!==(r=N5.exec(e));){let e=N4(r[2]);if(!e||!N3(e.rawPath))continue;let i=r.index,a=r.index+r[0].length;s.push({start:i,end:a,rawPath:e.rawPath,line:e.line,display:r[1]||void 0}),n.push([i,a])}for(N2.lastIndex=0;null!==(r=N2.exec(e));){let e=r.index;if(n.some(([r,s])=>e>=r&&e<s))continue;let i=r[1];if(!N3(i))continue;let a=r[2]?Number(r[2]):r[3]?Number(r[3]):null;s.push({start:e,end:e+r[0].length,rawPath:i,line:a})}return s.sort((e,r)=>e.start-r.start),s}(r);if(0===s.length)return[{type:"text",value:r}];let n=[],i=0;for(let a of s){a.start>i&&n.push({type:"text",value:r.slice(i,a.start)});let s=a.display??r.slice(a.start,a.end);n.push(e(a.rawPath,a.line,[{type:"text",value:s}])),i=a.end}return i<r.length&&n.push({type:"text",value:r.slice(i)}),n}(n.value??"")):"element"===n.type&&"pre"===n.tagName?(r(n,!0),a.push(n)):"element"!==n.type||"a"!==n.tagName||i?(r(n,i),a.push(n)):a.push(...function(r){let s=N4(String(r.properties?.href??""));return s?[e(s.rawPath,s.line,r.children??[])]:[r]}(n));s.children=a}(r)}},...E_?[E_]:[]],Ek={a:function({node:e,children:r,href:s,className:n,...i}){let{openFile:a,index:o,scope:l}=Cc(),c=e?.properties?.dataFileRaw;if(!c)return"string"==typeof s&&s.startsWith("#")?(0,z.jsx)("a",{href:s,className:(0,eb.cn)(Ex,n),...i,children:r}):(0,z.jsx)("a",{href:s,className:(0,eb.cn)(Ex,n),target:"_blank",rel:"noreferrer noopener",...i,children:r});let d=e?.properties?.dataFileLine,u=null!=d?Number(d):null,h=o?o.resolve(c):[];if(0===h.length){let e=o&&l?function(e){let r,s;if(!(e.startsWith("/")||e.startsWith("~/")))return null;let n=(s=(r=e.slice(e.lastIndexOf("/")+1)).lastIndexOf("."))>0?r.slice(s+1).toLowerCase():"";return n?Ey.has(n)?"image":"file":null}(c):null;if(!e||!l)return(0,z.jsx)(z.Fragment,{children:r});let s=e=>{e.preventDefault(),a(c,u)};return"file"===e?(0,z.jsx)("a",{href:"#",className:Ev,onClick:s,children:r}):(0,z.jsxs)(Ef,{openDelay:300,closeDelay:100,children:[(0,z.jsx)(Ep,{asChild:!0,children:(0,z.jsx)("a",{href:"#",className:Ev,onClick:s,children:r})}),(0,z.jsx)(Em,{side:"top",align:"start",className:"w-auto max-w-sm p-1.5",children:(0,z.jsx)(Ew,{scope:l,filePath:c})})]})}return 1===h.length?(0,z.jsx)("a",{href:"#",className:Eg,onClick:e=>{e.preventDefault(),a(h[0],u)},children:r}):(0,z.jsx)(Eb,{paths:h,line:u,children:r})}},EC=(0,$.memo)(function({children:e,streaming:r=!1}){return(0,z.jsx)(ck.i,{className:"size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",mode:r?"streaming":"static",rehypePlugins:Ej,components:Ek,children:e})});function EN({input:e,messageIndex:r}){let{sendMessage:s,messages:n}=Tx(),i=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&Array.isArray(r.questions)&&r.questions.length>0&&r.questions.every(e=>"string"==typeof e.question&&"string"==typeof e.header&&Array.isArray(e.options)))return r}catch{}return null}(e),a=n[r+1],o=a?.type==="user",l=o?a.content:"",c="string"==typeof l?l:l.filter(e=>"text"===e.type).map(e=>e.text).join("\n");if(!i){let r="string"==typeof e?e:JSON.stringify(e,null,2);return(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>500?r.substring(0,500)+"...":r})}return o?(0,z.jsx)(EE,{questions:i.questions,answeredText:c}):(0,z.jsx)(ED,{questions:i.questions,sendMessage:s})}function EE({questions:e,answeredText:r}){return(0,z.jsx)("div",{className:"space-y-3 mt-2",children:e.map((e,s)=>(0,z.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-3",children:[(0,z.jsx)("div",{className:"flex items-center gap-2 mb-1.5",children:(0,z.jsx)(so,{variant:"secondary",className:"text-[10px]",children:e.header})}),(0,z.jsx)("p",{className:"text-sm text-muted-foreground mb-2",children:e.question}),(0,z.jsxs)("div",{className:"flex items-center gap-2 text-sm text-green-600 dark:text-green-400",children:[(0,z.jsx)(sZ,{className:"h-4 w-4"}),(0,z.jsx)("span",{className:"font-medium",children:r})]})]},s))})}function ED({questions:e,sendMessage:r}){let[s,n]=(0,$.useState)(new Map),[i,a]=(0,$.useState)(new Map),[o,l]=(0,$.useState)(new Set),[c,d]=(0,$.useState)(!1);async function u(){let n=[];for(let r=0;r<e.length;r++)if(o.has(r)){let e=i.get(r)?.trim();e&&n.push(e)}else{let e=s.get(r);e&&e.size>0&&n.push(Array.from(e).join(", "))}if(n.length>0){d(!0);try{await r(n.join("\n"))}finally{d(!1)}}}let h=e.some((e,r)=>{if(o.has(r))return!!i.get(r)?.trim();let n=s.get(r);return n&&n.size>0});return(0,z.jsxs)("div",{className:"space-y-4 mt-2",children:[e.map((e,r)=>{let c=s.get(r)||new Set,d=i.get(r)||"",u=o.has(r);return(0,z.jsxs)("div",{className:"rounded-lg border bg-card p-3",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 mb-1.5",children:[(0,z.jsx)(dc,{className:"h-3.5 w-3.5 text-violet-500"}),(0,z.jsx)(so,{variant:"secondary",className:"text-[10px]",children:e.header})]}),(0,z.jsx)("p",{className:"text-sm font-medium mb-3",children:e.question}),(0,z.jsxs)("div",{className:"grid gap-2",children:[e.options.map(s=>{let i=c.has(s.label)&&!u;return(0,z.jsx)(W.Button,{variant:i?"default":"outline",className:(0,eb.cn)("h-auto py-2 px-3 justify-start text-left whitespace-normal",i&&"ring-2 ring-primary/50"),onClick:()=>{var i,a;return i=s.label,a=e.multiSelect,void(n(e=>{let s=new Map(e),n=new Set(s.get(r)||[]);return a?n.has(i)?n.delete(i):n.add(i):n.has(i)?n.clear():(n.clear(),n.add(i)),s.set(r,n),s}),l(e=>{let s=new Set(e);return s.delete(r),s}))},children:(0,z.jsxs)("div",{children:[(0,z.jsx)("span",{className:"font-medium text-sm",children:s.label}),s.description&&(0,z.jsx)("span",{className:"block text-xs text-muted-foreground mt-0.5",children:s.description})]})},s.label)}),(0,z.jsx)("div",{className:"flex items-center gap-2 mt-1",children:(0,z.jsx)(rl,{placeholder:"Other...",value:d,onChange:e=>{var s;return s=e.target.value,void(a(e=>new Map(e).set(r,s)),s&&(n(e=>{let s=new Map(e);return s.set(r,new Set),s}),l(e=>new Set(e).add(r))))},className:"text-sm"})})]})]},r)}),(0,z.jsxs)(W.Button,{onClick:u,disabled:!h||c,size:"sm",className:"active:scale-95 transition-transform",children:[c&&(0,z.jsx)(sC,{className:"h-3.5 w-3.5 animate-spin"}),c?"Submitting...":"Submit"]})]})}function ER(e){try{return JSON.parse(e)}catch{return null}}function ET({input:e,messageIndex:r}){let{messages:s,acceptPlan:n,permissionMode:i,agentType:a}=Tx(),[o,l]=(0,$.useState)(!0),[c,d]=(0,$.useState)(!1),u=function(e,r,s){let n="string"==typeof e?ER(e):e;if(n&&"object"==typeof n&&"plan"in n){let e=n.plan;if(e)return e}if("claude-code"===s)for(let e=r.length-1;e>=0;e--){let s=r[e];if("tool_use"===s.type&&"Write"===s.tool){let e="string"==typeof s.input?ER(s.input):s.input;if(e&&"object"==typeof e&&e.file_path?.includes(".claude/plans/")&&e.content)return e.content}}return"Plan written to file"}(e,s,a),h=(0,$.useCallback)(async()=>{d(!0);try{await n(u)}catch{d(!1)}},[n,u]),f="edit"===i,p=!1,m="";for(let e=r+1;e<s.length;e++){let r=s[e];if(r?.type==="user"){p=!0;let e=r.content??"";m="string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n");break}}return(f&&!p&&(p=!0),f||p)?(0,z.jsxs)("div",{className:"space-y-2 mt-2",children:[f?(0,z.jsxs)(so,{variant:"default",className:"bg-green-600 hover:bg-green-700 text-white",children:[(0,z.jsx)(sZ,{className:"h-3 w-3 mr-1"}),"Plan Accepted"]}):(0,z.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,z.jsx)(sR,{className:"h-3.5 w-3.5"}),(0,z.jsxs)("span",{children:["Feedback sent: ",m.length>100?m.substring(0,100)+"...":m]})]}),(0,z.jsxs)("details",{open:!f,children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"View Plan"}),(0,z.jsx)("div",{className:"mt-2 rounded-lg border p-3 bg-muted/30",children:(0,z.jsx)("div",{className:"prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,z.jsx)(cE,{mode:"static",children:u})})})]})]}):(0,z.jsxs)("div",{className:"space-y-3 mt-2",children:[(0,z.jsxs)("div",{className:"rounded-lg border p-3 bg-card",children:[(0,z.jsxs)("button",{onClick:()=>l(!o),className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground mb-2 block",children:[o?"Collapse":"Expand"," Plan"]}),o&&(0,z.jsx)("div",{className:"prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words max-h-96 overflow-y-auto",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,z.jsx)(cE,{mode:"static",children:u})})]}),(0,z.jsxs)(W.Button,{onClick:h,disabled:c,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:[c?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):(0,z.jsx)(rf,{className:"h-3.5 w-3.5 mr-1.5"}),c?"Accepting Plan...":"Accept Plan & Start Editing"]})]})}function EA({requestId:e,command:r,cwd:s,messageIndex:n}){let{messages:i,sessionId:a}=Tx(),[o,l]=(0,$.useState)(!1),[c,d]=(0,$.useState)(null),u=!1;for(let e=n+1;e<i.length;e++)if(i[e]?.type==="user"){u=!0;break}c&&(u=!0);let h=(0,$.useCallback)(async r=>{if(a){l(!0),d(r);try{await (0,ry.sendApprovalResponse)(a,e,r)}catch{d(null),l(!1)}}},[a,e]);return u?(0,z.jsxs)("div",{className:"space-y-2 mt-2",children:[(0,z.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-3",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,z.jsx)(gM,{className:"h-3.5 w-3.5 text-muted-foreground"}),(0,z.jsx)("span",{className:"text-xs text-muted-foreground",children:"Command"})]}),(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r||"(empty)"}),s&&(0,z.jsxs)("p",{className:"text-xs text-muted-foreground mt-1",children:["cwd: ",s]})]}),(0,z.jsxs)(so,{variant:"default",className:"decline"===c?"bg-red-600 hover:bg-red-700 text-white":"bg-green-600 hover:bg-green-700 text-white",children:[(0,z.jsx)(sZ,{className:"h-3 w-3 mr-1"}),"decline"===c?"Denied":"Allowed"]})]}):(0,z.jsxs)("div",{className:"space-y-2 mt-2",children:[(0,z.jsxs)("div",{className:"rounded-lg border bg-card p-3",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,z.jsx)(gM,{className:"h-3.5 w-3.5 text-muted-foreground"}),(0,z.jsx)("span",{className:"text-xs text-muted-foreground",children:"Command"})]}),(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r||"(empty)"}),s&&(0,z.jsxs)("p",{className:"text-xs text-muted-foreground mt-1",children:["cwd: ",s]})]}),(0,z.jsxs)("div",{className:"flex gap-2",children:[(0,z.jsxs)(W.Button,{onClick:()=>h("accept"),disabled:o,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:[o&&"accept"===c?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,z.jsx)(sZ,{className:"h-3.5 w-3.5 mr-1"}),"Allow"]}),(0,z.jsxs)(W.Button,{onClick:()=>h("decline"),disabled:o,variant:"destructive",size:"sm",children:[o&&"decline"===c?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,z.jsx)(s1,{className:"h-3.5 w-3.5 mr-1"}),"Deny"]})]})]})}function EI({requestId:e,changes:r,messageIndex:s}){let{messages:n,sessionId:i}=Tx(),[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(null),d=!1;for(let e=s+1;e<n.length;e++)if(n[e]?.type==="user"){d=!0;break}l&&(d=!0);let u=(0,$.useCallback)(async r=>{if(i){o(!0),c(r);try{await (0,ry.sendApprovalResponse)(i,e,r)}catch{c(null),o(!1)}}},[i,e]),h=r??[],f=()=>(0,z.jsx)("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:0===h.length?(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:"No file changes"}):h.map((e,r)=>(0,z.jsxs)("div",{children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)(kl,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),(0,z.jsx)("code",{className:"text-xs break-all",children:e.path}),(0,z.jsx)(so,{variant:"secondary",className:`text-[10px] ${function(e){switch(e){case"added":case"add":return"bg-green-500/10 text-green-600";case"deleted":case"delete":return"bg-red-500/10 text-red-600";default:return"bg-blue-500/10 text-blue-600"}}(e.kind)}`,children:function(e){switch(e){case"added":case"add":return"added";case"deleted":case"delete":return"deleted";default:return"modified"}}(e.kind)})]}),e.diff&&(0,z.jsxs)("details",{className:"mt-1",children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"View diff"}),(0,z.jsx)("pre",{className:"mt-1 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.diff.split("\n").map((e,r)=>{let s="";return e.startsWith("+")?s="bg-green-500/10 text-green-700 dark:text-green-400":e.startsWith("-")&&(s="bg-red-500/10 text-red-700 dark:text-red-400"),(0,z.jsx)("div",{className:s,children:e},r)})})]})]},r))});return d?(0,z.jsxs)("div",{className:"space-y-2 mt-2",children:[f(),(0,z.jsxs)(so,{variant:"default",className:"decline"===l?"bg-red-600 hover:bg-red-700 text-white":"bg-green-600 hover:bg-green-700 text-white",children:[(0,z.jsx)(sZ,{className:"h-3 w-3 mr-1"}),"decline"===l?"Denied":"Allowed"]})]}):(0,z.jsxs)("div",{className:"space-y-2 mt-2",children:[f(),(0,z.jsxs)("div",{className:"flex gap-2",children:[(0,z.jsxs)(W.Button,{onClick:()=>u("accept"),disabled:a,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:[a&&"accept"===l?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,z.jsx)(sZ,{className:"h-3.5 w-3.5 mr-1"}),"Allow"]}),(0,z.jsxs)(W.Button,{onClick:()=>u("decline"),disabled:a,variant:"destructive",size:"sm",children:[a&&"decline"===l?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,z.jsx)(s1,{className:"h-3.5 w-3.5 mr-1"}),"Deny"]})]})]})}let EM=(0,e_.default)("circle-plus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]),EF=(0,e_.default)("badge",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}]]);function EP({status:e,className:r}){switch(e){case"completed":return(0,z.jsx)(sZ,{className:(0,eb.cn)("h-4 w-4 text-green-500",r)});case"in_progress":return(0,z.jsx)(sC,{className:(0,eb.cn)("h-4 w-4 text-cyan-500 animate-spin",r)});case"pending":default:return(0,z.jsx)(sQ,{className:(0,eb.cn)("h-4 w-4 text-muted-foreground",r)});case"deleted":return(0,z.jsx)(s1,{className:(0,eb.cn)("h-4 w-4 text-red-400",r)})}}function EL(e,r){try{let s="string"==typeof e?JSON.parse(e):e;if(s&&"object"==typeof s&&r(s))return s}catch{}return null}function EO({input:e}){let r="string"==typeof e?e:JSON.stringify(e,null,2);return(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>500?r.substring(0,500)+"...":r})}function EB({input:e}){let r=EL(e,e=>Array.isArray(e.todos)&&e.todos.length>0);return r?(0,z.jsx)("div",{className:"mt-2 space-y-1",children:r.todos.map((e,r)=>(0,z.jsxs)("div",{className:"flex items-start gap-2 py-0.5",children:[(0,z.jsx)(EP,{status:e.status,className:"mt-0.5 flex-shrink-0"}),(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)("span",{className:(0,eb.cn)("text-sm break-words","completed"===e.status&&"line-through text-muted-foreground"),children:e.subject??e.content??"Untitled task"}),"in_progress"===e.status&&e.activeForm&&(0,z.jsx)("span",{className:"block text-xs italic text-cyan-500",children:e.activeForm})]})]},e.id??r))}):(0,z.jsx)(EO,{input:e})}function Ez({input:e}){let r=EL(e,e=>"string"==typeof e.subject);return r?(0,z.jsxs)("div",{className:"mt-2 flex items-start gap-2",children:[(0,z.jsx)(EM,{className:"h-4 w-4 text-cyan-500 mt-0.5 flex-shrink-0"}),(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)("span",{className:"text-sm font-medium break-words",children:r.subject}),r.description&&(0,z.jsx)("span",{className:"block text-xs text-muted-foreground mt-0.5 break-words",children:r.description.length>200?r.description.substring(0,200)+"...":r.description})]})]}):(0,z.jsx)(EO,{input:e})}function E$({input:e}){let r=EL(e,e=>"string"==typeof e.taskId);return r?(0,z.jsxs)("div",{className:"mt-2 flex items-start gap-2 flex-wrap",children:[r.status?(0,z.jsx)(EP,{status:r.status,className:"mt-0.5 flex-shrink-0"}):(0,z.jsx)(j8,{className:"h-4 w-4 text-cyan-500 mt-0.5 flex-shrink-0"}),(0,z.jsxs)("span",{className:"text-sm break-words",children:["Task #",r.taskId,r.status&&(0,z.jsxs)(z.Fragment,{children:[" ",(0,z.jsx)(j8,{className:"inline h-3 w-3 text-muted-foreground mx-0.5"})," ",r.status]}),r.subject&&(0,z.jsxs)("span",{className:"text-muted-foreground",children:[" — ",r.subject]})]}),r.addBlockedBy&&r.addBlockedBy.length>0&&(0,z.jsx)("div",{className:"flex gap-1 mt-1 w-full pl-6",children:r.addBlockedBy.map(e=>(0,z.jsxs)(so,{variant:"outline",className:"text-[10px]",children:[(0,z.jsx)(EF,{className:"h-2.5 w-2.5 mr-0.5"}),"blocked by #",e]},e))}),r.addBlocks&&r.addBlocks.length>0&&(0,z.jsx)("div",{className:"flex gap-1 mt-1 w-full pl-6",children:r.addBlocks.map(e=>(0,z.jsxs)(so,{variant:"outline",className:"text-[10px]",children:[(0,z.jsx)(EF,{className:"h-2.5 w-2.5 mr-0.5"}),"blocks #",e]},e))})]}):(0,z.jsx)(EO,{input:e})}function EW(){return(0,z.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin text-cyan-500"}),(0,z.jsx)("span",{children:"Listing tasks..."})]})}function EH({input:e}){let r=EL(e,e=>"string"==typeof e.taskId);return r?(0,z.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin text-cyan-500"}),(0,z.jsxs)("span",{children:["Fetching task #",r.taskId,"..."]})]}):(0,z.jsx)(EO,{input:e})}function EU({output:e}){let r=function(e){try{let r=JSON.parse(e);if(Array.isArray(r))return r.filter(e=>e.id&&e.subject).map(e=>({id:String(e.id),subject:String(e.subject),status:e.status||"pending",owner:e.owner?String(e.owner):void 0,blockedBy:Array.isArray(e.blockedBy)?e.blockedBy.map(String):void 0}));let s=r.tasks??r.items??r.data;if(Array.isArray(s))return s.filter(e=>e.id&&e.subject).map(e=>({id:String(e.id),subject:String(e.subject),status:e.status||"pending",owner:e.owner?String(e.owner):void 0,blockedBy:Array.isArray(e.blockedBy)?e.blockedBy.map(String):void 0}))}catch{let r=e.trim().split("\n").filter(Boolean),s=[];for(let e of r){let r=e.match(/^#?(\d+)[\s.:\-]+\[?(completed|in_progress|pending|deleted)\]?\s+(.+)/i);r&&s.push({id:r[1],status:r[2].toLowerCase(),subject:r[3].trim()})}if(s.length>0)return s}return null}(e);return r?(0,z.jsx)("div",{className:"mt-1 space-y-1",children:r.map(e=>(0,z.jsxs)("div",{className:"flex items-start gap-2 py-0.5",children:[(0,z.jsx)(EP,{status:e.status,className:"mt-0.5 flex-shrink-0"}),(0,z.jsxs)("div",{className:"min-w-0 flex items-center gap-1.5 flex-wrap",children:[(0,z.jsxs)("span",{className:"text-xs text-muted-foreground",children:["#",e.id]}),(0,z.jsx)("span",{className:(0,eb.cn)("text-sm break-words","completed"===e.status&&"line-through text-muted-foreground"),children:e.subject}),e.blockedBy&&e.blockedBy.length>0&&(0,z.jsx)(so,{variant:"outline",className:"text-[10px]",children:"blocked"})]})]},e.id))}):null}function Eq({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.file_path)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{file_path:s,offset:n,limit:i}=r,a=s.split("/"),o=a.pop()||s,l=a.join("/"),c=null!=n||null!=i,d="";if(c){let e=n??1;d=null!=i?`Lines ${e}\u2013${e+i-1}`:`From line ${e}`}return(0,z.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)("span",{className:"text-sm font-medium break-all",children:o}),l&&(0,z.jsx)("p",{className:"text-xs text-muted-foreground truncate",title:s,children:l})]}),c&&(0,z.jsx)(so,{variant:"outline",className:"text-xs shrink-0",children:d})]})}function EK({images:e}){return(0,z.jsx)("div",{className:"flex flex-wrap gap-2",children:e.map((e,r)=>(0,z.jsx)("img",{src:`data:${e.mediaType};base64,${e.data}`,alt:"Image viewed by the agent",className:"max-w-sm max-h-80 rounded-lg border border-border object-contain"},r))})}function EV({output:e}){let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["File contents (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function EX({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.file_path)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{file_path:s,content:n}=r,i=s.split("/"),a=i.pop()||s,o=i.join("/"),l=n.split("\n").length;return(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)("span",{className:"text-sm font-medium break-all",children:a}),o&&(0,z.jsx)("p",{className:"text-xs text-muted-foreground truncate",title:s,children:o})]}),(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Content (",l," ",1===l?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:n.length>1e3?n.substring(0,1e3)+"...":n})]})]})}function EY({output:e}){return e&&""!==e.trim()?(0,z.jsxs)("details",{children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Result"}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]}):(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"File written"})}function EG({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.command)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{command:s,description:n,timeout:i}=r;return(0,z.jsxs)("div",{className:"space-y-1",children:[n&&(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:n}),(0,z.jsxs)("div",{className:"flex items-start gap-2",children:[(0,z.jsxs)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{className:"text-muted-foreground select-none",children:"$ "}),s]}),null!=i&&(0,z.jsx)(so,{variant:"outline",className:"text-xs shrink-0 mt-1",children:function(e){if(e>=6e4){let r=e/6e4;return`${r%1==0?r:r.toFixed(1)}m`}return`${e/1e3}s`}(i)})]})]})}function EJ({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Output (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function EZ({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.pattern)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let s=[];return r.path&&s.push({label:r.path}),r.glob&&s.push({label:r.glob}),r.type&&s.push({label:`.${r.type}`}),r.output_mode&&"files_with_matches"!==r.output_mode&&s.push({label:r.output_mode}),null!=r.context&&s.push({label:`context: ${r.context}`}),null!=r["-C"]&&s.push({label:`context: ${r["-C"]}`}),null!=r["-B"]&&s.push({label:`before: ${r["-B"]}`}),null!=r["-A"]&&s.push({label:`after: ${r["-A"]}`}),r["-i"]&&s.push({label:"case-insensitive"}),r.multiline&&s.push({label:"multiline"}),null!=r.head_limit&&s.push({label:`limit: ${r.head_limit}`}),null!=r.offset&&s.push({label:`offset: ${r.offset}`}),(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsx)("div",{className:"flex items-start gap-2",children:(0,z.jsxs)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{className:"text-muted-foreground select-none",children:"/ "}),r.pattern]})}),s.length>0&&(0,z.jsx)("div",{className:"flex items-center gap-1.5 flex-wrap",children:s.map((e,r)=>(0,z.jsx)(so,{variant:"outline",className:"text-xs",children:e.label},r))})]})}function EQ({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No matches"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Results (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function E0({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.pattern)return r;return null}catch{return null}}(e);return r?(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsx)("div",{className:"flex items-start gap-2",children:(0,z.jsx)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.pattern})}),r.path&&(0,z.jsx)("div",{className:"flex items-center gap-1.5 flex-wrap",children:(0,z.jsx)(so,{variant:"outline",className:"text-xs",children:r.path})})]}):(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)})}function E1({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No matches"});let r=e.trim().split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:[r," ",1===r?"file":"files"," found"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}let E2={Explore:"Explore",Bash:"Bash",Plan:"Plan","general-purpose":"General","code-simplifier":"Simplify","superpowers:code-reviewer":"Review","memory-leak-detector":"Memory","directory-structure-validator":"Structure","tech-docs-finder":"Docs","claude-code-guide":"Guide","statusline-setup":"Status"};function E5({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.description&&"string"==typeof r.subagent_type)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{description:s,subagent_type:n,prompt:i,model:a,max_turns:o,resume:l,run_in_background:c}=r,d=[];return d.push({label:E2[n]||n}),a&&d.push({label:a}),null!=o&&d.push({label:`${o} turns`}),c&&d.push({label:"background"}),l&&d.push({label:"resume"}),(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,z.jsx)("span",{className:"text-sm",children:s}),d.map((e,r)=>(0,z.jsx)(so,{variant:"outline",className:"text-xs shrink-0",children:e.label},r))]}),i&&(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Prompt (",i.length>1e3?`${Math.round(i.length/1e3)}k chars`:`${i.length} chars`,")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:i.length>1e3?i.substring(0,1e3)+"...":i})]})]})}function E3({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Agent result (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function E4(e,r){return e.length>r?e.substring(0,r)+"...":e}function E6({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.file_path&&"string"==typeof r.old_string&&"string"==typeof r.new_string)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{file_path:s,old_string:n,new_string:i,replace_all:a}=r,o=s.split("/"),l=o.pop()||s,c=o.join("/"),d=n.split("\n").length,u=i.split("\n").length;return(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)("span",{className:"text-sm font-medium break-all",children:l}),c&&(0,z.jsx)("p",{className:"text-xs text-muted-foreground truncate",title:s,children:c})]}),(0,z.jsx)(so,{variant:"outline",className:"text-xs shrink-0",children:d===u?`${d} ${1===d?"line":"lines"}`:`${d}\u2192${u} lines`}),a&&(0,z.jsx)(so,{variant:"outline",className:"text-xs shrink-0",children:"replace all"})]}),(0,z.jsxs)("details",{children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Diff"}),(0,z.jsxs)("div",{className:"mt-1 text-xs rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full",children:[(0,z.jsxs)("pre",{className:"bg-red-500/10 p-1.5 rounded-t whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{className:"text-red-500 select-none",children:"- "}),E4(n,500)]}),(0,z.jsxs)("pre",{className:"bg-green-500/10 p-1.5 rounded-b whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{className:"text-green-500 select-none",children:"+ "}),E4(i,500)]})]})]})]})}function E7({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});if(e.length<=200)return(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:e});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Result (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function E8({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.url&&"string"==typeof r.prompt)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{display:s,href:n}=function(e){try{let r=new URL(e),s="/"===r.pathname?"":r.pathname,n=r.hostname+s;return{display:n.length>80?n.substring(0,77)+"...":n,href:e}}catch{return{display:e.length>80?e.substring(0,77)+"...":e,href:e}}}(r.url),i=r.prompt.length>150?r.prompt.substring(0,147)+"...":r.prompt;return(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsx)("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"block text-xs font-mono text-blue-500 hover:underline truncate",children:s}),(0,z.jsxs)("p",{className:"text-xs text-muted-foreground",children:['"',i,'"']})]})}function E9({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No content fetched"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Response (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function De({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.query)return r;return null}catch{return null}}(e);return r?(0,z.jsxs)("div",{className:"space-y-1.5",children:[(0,z.jsx)("p",{className:"text-xs font-mono bg-muted/50 px-2 py-1 rounded break-words",children:r.query}),r.allowed_domains&&r.allowed_domains.length>0&&(0,z.jsxs)("div",{className:"flex items-center gap-1 flex-wrap",children:[(0,z.jsx)("span",{className:"text-xs text-muted-foreground",children:"only:"}),r.allowed_domains.map(e=>(0,z.jsx)(so,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:e},e))]}),r.blocked_domains&&r.blocked_domains.length>0&&(0,z.jsxs)("div",{className:"flex items-center gap-1 flex-wrap",children:[(0,z.jsx)("span",{className:"text-xs text-muted-foreground",children:"exclude:"}),r.blocked_domains.map(e=>(0,z.jsx)(so,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:e},e))]})]}):(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)})}function Dt({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No search results"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Results (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function Dr({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.skill)return r;return null}catch{return null}}(e);return r?(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsx)("p",{className:"text-xs font-mono text-pink-500",children:r.skill}),r.args&&(0,z.jsxs)("p",{className:"text-xs text-muted-foreground truncate",children:["args: ",r.args]})]}):(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)})}function Ds({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Loaded (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function Dn({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.task_id)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{task_id:s,block:n,timeout:i}=r,a=[];return a.push({label:!1===n?"non-blocking":"blocking"}),null!=i&&a.push({label:`${Math.round(i/1e3)}s`}),(0,z.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,z.jsx)("code",{className:"text-sm bg-muted/50 px-1.5 py-0.5 rounded",children:s}),a.map((e,r)=>(0,z.jsx)(so,{variant:"outline",className:"text-xs shrink-0",children:e.label},r))]})}function Di({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Task output (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function Da({input:e}){let r="string"==typeof e?function(e){try{return JSON.parse(e)}catch{return null}}(e):e,s=r?.changes??[];return 0===s.length?(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:"No file changes"}):(0,z.jsx)("div",{className:"space-y-2 mt-1",children:s.map((e,r)=>(0,z.jsxs)("div",{children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)(kl,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),(0,z.jsx)("code",{className:"text-xs break-all",children:e.path}),(0,z.jsx)(so,{variant:"secondary",className:`text-[10px] ${function(e){switch(e){case"added":case"add":return"bg-green-500/10 text-green-600";case"deleted":case"delete":return"bg-red-500/10 text-red-600";default:return"bg-blue-500/10 text-blue-600"}}(e.kind)}`,children:function(e){switch(e){case"added":case"add":return"added";case"deleted":case"delete":return"deleted";default:return"modified"}}(e.kind)})]}),e.diff&&(0,z.jsxs)("details",{className:"mt-1",children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"View diff"}),(0,z.jsx)("pre",{className:"mt-1 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.diff.split("\n").map((e,r)=>{let s="";return e.startsWith("+")?s="bg-green-500/10 text-green-700 dark:text-green-400":e.startsWith("-")&&(s="bg-red-500/10 text-red-700 dark:text-red-400"),(0,z.jsx)("div",{className:s,children:e},r)})})]})]},r))})}function Do({output:e}){let r=e.toLowerCase(),s="text-muted-foreground";return r.includes("completed")||r.includes("success")?s="text-green-600 dark:text-green-400":r.includes("failed")||r.includes("error")?s="text-red-600 dark:text-red-400":(r.includes("declined")||r.includes("denied"))&&(s="text-amber-600 dark:text-amber-400"),(0,z.jsx)("p",{className:`text-xs ${s}`,children:e})}let Dl=new Map,Dc=new Map,Dd=new Map;function Du(e){for(let r of Dd.get(e)??[])r()}async function Dh(e,r){if(!r){let r=Dl.get(e);if(r)return r;let s=Dc.get(e);if(s)return s}let s=ry.api.getSchedules(e).then(r=>(Dl.set(e,r),Du(e),r)).finally(()=>{Dc.get(e)===s&&Dc.delete(e)});return Dc.set(e,s),s}let Df="mcp__vibedeckx__propose_schedule";function Dp({input:e,toolUseId:r}){let s,{sessionId:n,projectId:i,branch:a,target:o,targetLabel:l,agentType:c,openSchedule:d}=Tx(),u=(0,$.useMemo)(()=>{let r,s,n,i,a,o;return s=(r="string"==typeof e?function(e){try{return JSON.parse(e)}catch{return null}}(e):e)&&"object"==typeof r?r:{},i=(n=e=>"string"==typeof e?e:"")(s.prompt),a=n(s.command),o=i.trim()||!a.trim()?"prompt":"command",{name:n(s.name).trim(),cronExpr:n(s.cron_expr).trim(),runType:o,content:"prompt"===o?i:a,timezone:n(s.timezone).trim()||function(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}}()}},[e]),[h,f]=(0,$.useState)(u),[p,m]=(0,$.useState)(a??""),[g,x]=(0,$.useState)(!1),[v,y]=(0,$.useState)(null),{schedule:b,loading:w}=(s=(0,$.useSyncExternalStore)((0,$.useCallback)(e=>{let r;return i?((r=Dd.get(i)??new Set).add(e),Dd.set(i,r),()=>{r.delete(e),0===r.size&&Dd.delete(i)}):()=>{}},[i]),(0,$.useCallback)(()=>i?Dl.get(i)??null:null,[i]),()=>null),(0,$.useEffect)(()=>{i&&Dh(i,!1).catch(e=>{console.error("Failed to load schedules for proposal lookup:",e)})},[i]),(0,sx.useGlobalEventStream)((0,$.useCallback)(e=>{!e.type?.startsWith("schedule:")||i&&e.projectId===i&&Dh(i,!0).catch(()=>{})},[i])),{schedule:r&&n&&s?s.find(e=>e.source_tool_use_id===r&&e.source_session_id===n)??null:null,loading:null===s}),_="command"===h.runType,S=!!i&&!!n&&!!r,j=async()=>{if(S&&!g){x(!0),y(null);try{let e,s=await ry.api.createSchedule(i,{name:h.name||"Scheduled check",cron_expr:h.cronExpr,timezone:h.timezone,target:o,run_type:h.runType,prompt_provider:"command"===h.runType?null:"codex"===c?"codex":"claude",content:h.content,cwd_mode:"branch",branch:p.trim()?p.trim():null,source:{session_id:n,tool_use_id:r}});e=Dl.get(i)??[],Dl.set(i,[...e.filter(e=>e.id!==s.id),s]),Du(i)}catch(e){y(e instanceof Error?e.message:"Failed to create schedule")}finally{x(!1)}}};return b?(0,z.jsx)("div",{className:"rounded-lg border border-emerald-500/30 bg-emerald-500/5 p-3",children:(0,z.jsxs)("div",{className:"flex items-start gap-2",children:[(0,z.jsx)(sZ,{className:"mt-0.5 h-4 w-4 flex-shrink-0 text-emerald-500"}),(0,z.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-foreground break-words",children:b.name}),(0,z.jsxs)("p",{className:"mt-0.5 font-mono text-xs text-muted-foreground break-all",children:[b.cron_expr," · ",b.timezone,"command"===b.run_type?" · command":"",b.branch?` \xb7 ${b.branch}`:""]})]}),d&&(0,z.jsxs)(W.Button,{variant:"ghost",size:"sm",className:"flex-shrink-0",onClick:()=>d(b.id),children:[(0,z.jsx)(s8,{className:"mr-1 h-3.5 w-3.5"}),"View"]})]})}):(0,z.jsxs)("div",{className:"rounded-lg border border-border bg-muted/30 p-3",children:[(0,z.jsxs)("div",{className:"space-y-2",children:[(0,z.jsx)(rl,{value:h.name,onChange:e=>f(r=>({...r,name:e.target.value})),placeholder:"Name",className:"h-8 text-sm","aria-label":"Schedule name",disabled:g}),(0,z.jsxs)("div",{className:"flex gap-2",children:[(0,z.jsx)(rl,{value:h.cronExpr,onChange:e=>f(r=>({...r,cronExpr:e.target.value})),placeholder:"0 9 * * *",className:"h-8 font-mono text-xs","aria-label":"Cron expression",disabled:g}),(0,z.jsx)(rl,{value:p,onChange:e=>m(e.target.value),placeholder:"main worktree",className:"h-8 font-mono text-xs","aria-label":"Branch",disabled:g})]}),(0,z.jsx)(rc,{value:h.content,onChange:e=>f(r=>({...r,content:e.target.value})),placeholder:_?"Command to run":"What the scheduled agent should check",className:(0,eb.cn)("text-xs",_?"min-h-16 font-mono":"min-h-24"),"aria-label":_?"Check command":"Check prompt",disabled:g})]}),(0,z.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:[_?"Runs as a command":"Runs as an agent"," on ",l," · ",h.timezone]}),v&&(0,z.jsx)("p",{className:"mt-2 text-xs text-red-500 break-words",children:v}),(0,z.jsxs)("div",{className:"mt-3 flex items-center gap-2",children:[(0,z.jsxs)(W.Button,{size:"sm",onClick:j,disabled:!S||g||w,children:[g?(0,z.jsx)(sC,{className:"mr-1 h-3.5 w-3.5 animate-spin"}):(0,z.jsx)(sj,{className:"mr-1 h-3.5 w-3.5"}),v?"Retry":"Create schedule"]}),d&&(0,z.jsx)(W.Button,{variant:"ghost",size:"sm",onClick:()=>d(null),disabled:g,children:"View existing schedules"})]})]})}let Dm="cross-remote",Dg={remote_bash:"Run Command",remote_read_file:"Read File",remote_list_dir:"List Directory",remote_stat_path:"Stat Path",remote_process_list:"List Processes",list_accessible_remotes:"List Remotes",remote_mcp_open:"Open MCP Server",remote_mcp_list_tools:"List MCP Tools",remote_mcp_call:"Call MCP Tool",remote_mcp_ping:"Ping MCP Server",remote_mcp_close:"Close MCP Server"},Dx=[`mcp__${Dm}__`,`${Dm}__`,`${Dm}.`,`${Dm}/`];function Dv(e){let r=e.trim();for(let e of Dx)if(r.startsWith(e)){let s=r.slice(e.length);return s in Dg?s:null}return r in Dg?r:null}function Dy({value:e,limit:r}){let s="string"==typeof e?e:JSON.stringify(e,null,2);return(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:s.length>r?s.substring(0,r)+"...":s})}function Db({bare:e,parsed:r,raw:s}){return r?"remote_bash"===e&&r.command?(0,z.jsxs)("div",{className:"flex items-start gap-2",children:[(0,z.jsxs)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{className:"text-muted-foreground select-none",children:"$ "}),r.command]}),(0,z.jsxs)("div",{className:"flex flex-col gap-1 shrink-0 mt-1",children:[r.cwd&&(0,z.jsx)(so,{variant:"outline",className:"text-xs max-w-40 truncate",title:r.cwd,children:r.cwd}),null!=r.timeoutSec&&(0,z.jsxs)(so,{variant:"outline",className:"text-xs",children:[r.timeoutSec,"s"]})]})]}):r.path?(0,z.jsx)("p",{className:"font-mono text-muted-foreground break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.path}):"remote_process_list"===e||"list_accessible_remotes"===e?null:(0,z.jsx)(Dy,{value:s,limit:500}):(0,z.jsx)(Dy,{value:s,limit:500})}function Dw({tool:e,input:r}){let s=Dv(e)??e,n=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(!r||"object"!=typeof r)return null;let s=e=>"string"==typeof r[e]?r[e]:void 0;return{remoteId:s("remoteId"),command:s("command"),cwd:s("cwd"),path:s("path"),tool:s("tool"),timeoutSec:"number"==typeof r.timeoutSec?r.timeoutSec:void 0}}catch{return null}}(r),{label:i}=gf(n?.remoteId);return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-violet-500/10 flex items-center justify-center",children:(0,z.jsx)(sm,{className:"w-4 h-4 text-violet-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsxs)("p",{className:"text-sm font-medium text-violet-500 mb-1 break-words",children:[Dg[s]??s,i&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"font-normal text-muted-foreground",children:" on "}),(0,z.jsx)("span",{className:"text-foreground",title:n?.remoteId,children:i})]})]}),(0,z.jsx)(Db,{bare:s,parsed:n,raw:r})]})]})}function D_(e){try{return{ok:!0,value:JSON.parse(e)}}catch{return{ok:!1}}}function DS({text:e}){return(0,z.jsx)("p",{className:"text-xs text-muted-foreground break-words whitespace-pre-wrap",children:e})}function Dj({output:e}){var r;let s=D_(e);if(!s.ok)return(0,z.jsx)(DS,{text:e});let n=s.value,i=function(e){let r=e?.content;if(!Array.isArray(r))return null;let s=r.filter(e=>!!e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text);return s.length>0?s.join("\n"):null}(n);if(null!==i){let e=D_(i);if(!e.ok)return(0,z.jsx)(DS,{text:i});n=e.value}let a=(r=n)&&"object"==typeof r?"string"!=typeof r.stdout||"string"!=typeof r.stderr?null:{stdout:r.stdout,stderr:r.stderr,exitCode:"number"==typeof r.exitCode?r.exitCode:null,timedOut:!0===r.timedOut,truncated:!0===r.truncated}:null;if(a){let e=[a.stdout,a.stderr].filter(e=>""!==e.trim()).join("\n"),r=null!==a.exitCode&&0!==a.exitCode;return(0,z.jsxs)("div",{className:"space-y-1",children:[(r||a.timedOut||a.truncated)&&(0,z.jsxs)("div",{className:"flex flex-wrap gap-1",children:[a.timedOut&&(0,z.jsx)(so,{variant:"destructive",className:"text-xs",children:"timed out"}),r&&(0,z.jsxs)(so,{variant:"outline",className:"text-xs",children:["exit ",a.exitCode]}),a.truncated&&(0,z.jsx)(so,{variant:"outline",className:"text-xs",children:"truncated"})]}),(0,z.jsx)(EJ,{output:e})]})}let o=n?.content;return"string"==typeof o?(0,z.jsx)(EJ,{output:o}):(0,z.jsx)(Dy,{value:n,limit:1e3})}let Dk=(0,e_.default)("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);function DC({names:e}){return(0,z.jsxs)("span",{className:"flex min-w-0 items-baseline gap-1 text-xs font-normal text-muted-foreground",title:`Remote access: ${e}`,children:[(0,z.jsx)(no,{className:"w-3 h-3 shrink-0 self-center"}),(0,z.jsx)("span",{className:"truncate",children:e})]})}function DN(e){let r={names:null},s=e.replace(RegExp(DD.source,"g"),(e,s)=>(r.names=s,""));return null===r.names?{text:e,names:null}:{text:s.trimEnd(),names:r.names}}function DE({path:e,size:r,name:s}){let n;return(0,z.jsxs)("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-border bg-muted/60 px-1.5 py-0.5 text-xs font-mono align-baseline",title:e,children:[(0,z.jsx)(void 0===s?kl:Dk,{className:"w-3 h-3 text-muted-foreground shrink-0"}),(0,z.jsx)("span",{className:"truncate max-w-[18ch]",children:s??((n=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")))>=0?e.slice(n+1):e)}),(0,z.jsx)("span",{className:"text-muted-foreground",children:function(e){if(e<1024)return`${e} B`;let r=e/1024;return r<10?`${r.toFixed(1)} KB`:r<1024?`${Math.round(r)} KB`:`${(r/1024).toFixed(1)} MB`}(r)})]})}let DD=/<vremotes names="([^"]*)">[\s\S]*?<\/vremotes>/g,DR=RegExp(`${/<vpaste path="([^"]+)" size="(\d+)" \/>/g.source}|${/<vfile path="([^"]+)" name="([^"]*)" size="(\d+)" \/>/g.source}|${DD.source}`,"g");function DT({message:e,messageIndex:r,streaming:s=!1}){let n=function(e,r,s){switch(e.type){case"user":return(0,z.jsx)(DI,{content:e.content,origin:e.origin});case"assistant":return(0,z.jsx)(DM,{content:e.content,agentType:e.agentType,streaming:s});case"tool_use":return(0,z.jsx)(DF,{tool:e.tool,input:e.input,messageIndex:r,toolUseId:e.toolUseId});case"tool_result":return(0,z.jsx)(DP,{tool:e.tool,output:e.output});case"thinking":return(0,z.jsx)(DL,{content:e.content});case"error":return(0,z.jsx)(DO,{message:e.message});case"system":return(0,z.jsx)(DB,{content:e.content});case"approval_request":return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-amber-500/10 flex items-center justify-center",children:(0,z.jsx)(N1,{className:"w-4 h-4 text-amber-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-amber-500 mb-1",children:"command"===e.requestType?"Command Approval":"File Change Approval"}),"command"===e.requestType?(0,z.jsx)(EA,{requestId:e.requestId,command:e.command,cwd:e.cwd,messageIndex:r}):(0,z.jsx)(EI,{requestId:e.requestId,changes:e.changes,messageIndex:r})]})]});default:return null}}(e,r,s);return n?(0,z.jsxs)("div",{className:"group relative",children:[n,(0,z.jsx)("span",{className:"pointer-events-none absolute right-0 top-3 text-xs tabular-nums text-muted-foreground opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:function(e){let r=new Date(e),s=new Date,n=r.getFullYear()===s.getFullYear()&&r.getMonth()===s.getMonth()&&r.getDate()===s.getDate(),i=r.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});if(n)return i;let a=r.toLocaleDateString(void 0,{year:"numeric",month:"2-digit",day:"2-digit"});return`${a} ${i}`}(e.timestamp)})]}):null}function DA(e){let r=function(e){let r,s=[],n=0,i=RegExp(DR.source,"g");for(;null!==(r=i.exec(e));)r.index>n&&s.push({kind:"text",text:e.slice(n,r.index)}),void 0!==r[1]?s.push({kind:"chip",path:r[1],size:Number(r[2])}):void 0!==r[3]?s.push({kind:"chip",path:r[3],name:r[4],size:Number(r[5])}):s.push({kind:"remotes",names:r[6]}),n=r.index+r[0].length;return n<e.length&&s.push({kind:"text",text:e.slice(n)}),s}(e);return 1===r.length&&"text"===r[0].kind?(0,z.jsx)("span",{className:"whitespace-pre-wrap break-words",children:e??""}):(0,z.jsx)("div",{className:"text-foreground max-w-none break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:r.map((e,r)=>"text"===e.kind?(0,z.jsx)("span",{className:"whitespace-pre-wrap break-words",children:e.text},r):"remotes"===e.kind?null:(0,z.jsx)(DE,{path:e.path,size:e.size,name:e.name},r))})}function DI({content:e,origin:r}){let s;if("workflow"===r&&"string"==typeof e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,z.jsx)(NJ,{className:"w-3.5 h-3.5 text-sky-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Workflow"}),(0,z.jsx)("div",{className:"text-foreground prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,z.jsx)(EC,{children:e})})]})]});let n=null;if("string"==typeof e){let r=DN(e);n=r.names,s=r.text}else for(let r of(s=[],e)){if("text"!==r.type){s.push(r);continue}let e=DN(r.text);null!==e.names&&(n=e.names),(null===e.names||e.text.length>0)&&s.push({...r,text:e.text})}return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-primary/10 flex items-center justify-center",children:(0,z.jsx)(NK,{className:"w-3.5 h-3.5 text-primary"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsxs)("p",{className:"flex min-w-0 items-baseline gap-1.5 text-sm font-medium text-foreground mb-1",children:[(0,z.jsx)("span",{className:"shrink-0",children:"You"}),n&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"shrink-0 text-muted-foreground/60","aria-hidden":!0,children:"·"}),(0,z.jsx)(DC,{names:n})]})]}),(0,z.jsx)("div",{className:"text-foreground max-w-none break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:"string"==typeof s?DA(s):s.map((e,r)=>"text"===e.type?(0,z.jsx)($.Fragment,{children:DA(e.text)},r):(0,z.jsx)("img",{src:`data:${e.mediaType};base64,${e.data}`,alt:"Attached image",className:"max-w-sm rounded-lg mt-2"},r))})]})]})}function DM({content:e,agentType:r,streaming:s=!1}){let n=function(){try{return Tx().agentType}catch{return"claude-code"}}(),i="codex"===(r??n),[a,o]=(0,$.useState)(!1);return(0,z.jsxs)("div",{className:"group flex gap-3 py-3",children:[(0,z.jsx)("div",{className:`flex-shrink-0 w-7 h-7 rounded-lg ${i?"bg-green-500/10":"bg-violet-500/10"} flex items-center justify-center`,children:(0,z.jsx)(sS,{className:`w-3.5 h-3.5 ${i?"text-green-500":"text-violet-500"}`})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,z.jsx)("p",{className:`text-sm font-medium ${i?"text-green-500":"text-violet-500"}`,children:i?"Codex":"Claude"}),(0,z.jsx)("button",{type:"button",onClick:()=>o(e=>!e),title:a?"View rendered":"View source","aria-label":a?"View rendered":"View source","aria-pressed":a,className:"opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity text-muted-foreground hover:text-foreground",children:a?(0,z.jsx)(_P,{className:"w-3.5 h-3.5"}):(0,z.jsx)(ky,{className:"w-3.5 h-3.5"})})]}),a?(0,z.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-words bg-muted/50 rounded-md p-3 overflow-x-auto text-foreground select-text",children:e??""}):(0,z.jsx)("div",{className:"text-foreground prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,z.jsx)(EC,{streaming:s,children:e??""})})]})]})}function DF({tool:e,input:r,messageIndex:s,toolUseId:n}){if(e===Df)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-amber-500/10 flex items-center justify-center",children:(0,z.jsx)(sj,{className:"w-4 h-4 text-amber-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-amber-500 mb-1",children:"Suggested scheduled check"}),(0,z.jsx)(Dp,{input:r,toolUseId:n})]})]});if("ImageView"===e){let e="object"==typeof r&&null!==r&&"path"in r&&"string"==typeof r.path?r.path:"";return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,z.jsx)(_P,{className:"w-4 h-4 text-sky-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"View Image"}),(0,z.jsx)("p",{className:"font-mono text-muted-foreground break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e})]})]})}if("AskUserQuestion"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-violet-500/10 flex items-center justify-center",children:(0,z.jsx)(dc,{className:"w-4 h-4 text-violet-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-violet-500 mb-1",children:"Question"}),(0,z.jsx)(EN,{input:r,messageIndex:s})]})]});if("ExitPlanMode"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-green-500/10 flex items-center justify-center",children:(0,z.jsx)(NY,{className:"w-4 h-4 text-green-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-green-500 mb-1",children:"Plan Ready"}),(0,z.jsx)(ET,{input:r,messageIndex:s})]})]});let i={TodoWrite:{label:"Tasks",ui:(0,z.jsx)(EB,{input:r})},TaskCreate:{label:"Create Task",ui:(0,z.jsx)(Ez,{input:r})},TaskUpdate:{label:"Update Task",ui:(0,z.jsx)(E$,{input:r})},TaskList:{label:"Task List",ui:(0,z.jsx)(EW,{})},TaskGet:{label:"Get Task",ui:(0,z.jsx)(EH,{input:r})}}[e];if(i)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-cyan-500/10 flex items-center justify-center",children:(0,z.jsx)(s0,{className:"w-4 h-4 text-cyan-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-cyan-500 mb-1",children:i.label}),i.ui]})]});if("Read"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,z.jsx)(kl,{className:"w-4 h-4 text-sky-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Read File"}),(0,z.jsx)(Eq,{input:r})]})]});if("Edit"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,z.jsx)(NZ,{className:"w-4 h-4 text-sky-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Edit File"}),(0,z.jsx)(E6,{input:r})]})]});if("Write"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,z.jsx)(NQ,{className:"w-4 h-4 text-sky-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Write File"}),(0,z.jsx)(EX,{input:r})]})]});if("Bash"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-emerald-500/10 flex items-center justify-center",children:(0,z.jsx)(gM,{className:"w-4 h-4 text-emerald-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-emerald-500 mb-1",children:"Run Command"}),(0,z.jsx)(EG,{input:r})]})]});if("Grep"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-orange-500/10 flex items-center justify-center",children:(0,z.jsx)(sA,{className:"w-4 h-4 text-orange-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-orange-500 mb-1",children:"Search"}),(0,z.jsx)(EZ,{input:r})]})]});if("Glob"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-teal-500/10 flex items-center justify-center",children:(0,z.jsx)(NG,{className:"w-4 h-4 text-teal-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-teal-500 mb-1",children:"Glob"}),(0,z.jsx)(E0,{input:r})]})]});if("Task"===e||"Agent"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-purple-500/10 flex items-center justify-center",children:(0,z.jsx)(NJ,{className:"w-4 h-4 text-purple-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-purple-500 mb-1",children:"Agent"}),(0,z.jsx)(E5,{input:r})]})]});if("TaskOutput"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-purple-500/10 flex items-center justify-center",children:(0,z.jsx)(NJ,{className:"w-4 h-4 text-purple-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-purple-500 mb-1",children:"Task Output"}),(0,z.jsx)(Dn,{input:r})]})]});if("WebFetch"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-blue-500/10 flex items-center justify-center",children:(0,z.jsx)(rw,{className:"w-4 h-4 text-blue-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-blue-500 mb-1",children:"Fetch Web Page"}),(0,z.jsx)(E8,{input:r})]})]});if("WebSearch"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-indigo-500/10 flex items-center justify-center",children:(0,z.jsx)(N0,{className:"w-4 h-4 text-indigo-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-indigo-500 mb-1",children:"Web Search"}),(0,z.jsx)(De,{input:r})]})]});if("Skill"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-pink-500/10 flex items-center justify-center",children:(0,z.jsx)(p8,{className:"w-4 h-4 text-pink-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-pink-500 mb-1",children:"Skill"}),(0,z.jsx)(Dr,{input:r})]})]});if("FileChange"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,z.jsx)(NZ,{className:"w-4 h-4 text-sky-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"File Changes"}),(0,z.jsx)(Da,{input:r})]})]});if(null!==Dv(e))return(0,z.jsx)(Dw,{tool:e,input:r});let a="string"==typeof r?r:JSON.stringify(r,null,2);return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-amber-500/10 flex items-center justify-center",children:(0,z.jsx)(NV,{className:"w-4 h-4 text-amber-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsxs)("p",{className:"text-sm font-medium text-amber-500 mb-1 break-words",children:["Tool: ",e]}),(0,z.jsxs)("details",{open:!0,children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Input"}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:a.length>500?a.substring(0,500)+"...":a})]})]})]})}function DP({tool:e,output:r}){if(e===Df)return null;let s=function(e){if(!e.startsWith("[")||!e.includes('"type":"image"'))return null;try{let r=JSON.parse(e);if(!Array.isArray(r))return null;let s=[];for(let e of r){if(!e||"image"!==e.type)continue;let r=e.source;r?.type==="base64"&&"string"==typeof r.data&&s.push({mediaType:r.media_type??"image/png",data:r.data})}return s.length>0?s:null}catch{return null}}(r);if(s)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(EK,{images:s})})});if(["TodoWrite","TaskCreate","TaskUpdate","TaskList","TaskGet"].includes(e)){let s="TaskList"===e?(0,z.jsx)(EU,{output:r}):null;return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsxs)("p",{className:"text-xs text-muted-foreground mb-1",children:["Result (",e,")"]}),s||(0,z.jsxs)("details",{children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Output"}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>1e3?r.substring(0,1e3)+"...":r})]})]})})}if("Read"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(EV,{output:r})})});if("Edit"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(E7,{output:r})})});if("Write"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(EY,{output:r})})});if("Bash"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(EJ,{output:r})})});if("Grep"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(EQ,{output:r})})});if("Glob"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(E1,{output:r})})});if("Task"===e||"Agent"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(E3,{output:r})})});if("TaskOutput"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(Di,{output:r})})});if("WebFetch"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(E9,{output:r})})});if("WebSearch"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(Dt,{output:r})})});if("Skill"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(Ds,{output:r})})});if("FileChange"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(Do,{output:r})})});if(null!==Dv(e))return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(Dj,{output:r})})});let n=r.length>200;return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsxs)("p",{className:"text-xs text-muted-foreground mb-1",children:["Result",e?` (${e})`:""]}),(0,z.jsxs)("details",{className:(0,eb.cn)(!n&&"open"),children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Output"}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>1e3?r.substring(0,1e3)+"...":r})]})]})})}function DL({content:e}){let r=e??"",s=r.trim().length>0,n=s?r.length>500?r.substring(0,500)+"...":r:"Reasoning unavailable — this model does not expose its thinking content.";return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-blue-500/10 flex items-center justify-center",children:(0,z.jsx)(NX,{className:"w-3.5 h-3.5 text-blue-500"})}),(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsxs)("details",{children:[(0,z.jsx)("summary",{className:"text-xs font-medium text-blue-500 cursor-pointer hover:underline",children:"Thinking..."}),(0,z.jsx)("div",{className:`mt-2 whitespace-pre-wrap break-words bg-blue-500/5 p-2 rounded-md overflow-hidden ${s?"text-muted-foreground":"text-muted-foreground/70 italic"}`,style:{fontSize:"var(--conv-font-size, 12px)"},children:n})]})})]})}function DO({message:e}){return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-red-500/10 flex items-center justify-center",children:(0,z.jsx)(s_,{className:"w-3.5 h-3.5 text-red-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-red-500 mb-1",children:"Error"}),(0,z.jsx)("p",{className:"text-red-500/80 break-words whitespace-pre-wrap",style:{fontSize:"var(--conv-font-size, 14px)"},children:e})]})]})}function DB({content:e}){return(0,z.jsxs)("div",{className:"flex gap-3 py-2",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-gray-500/10 flex items-center justify-center",children:(0,z.jsx)(hv,{className:"w-3.5 h-3.5 text-gray-500"})}),(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)("p",{className:"text-muted-foreground break-words",style:{fontSize:"var(--conv-font-size, 12px)"},children:e??""})})]})}let Dz=/^data:[^;,]*(?:;[^;,]*)*;base64,(.+)$/;async function D$(e){if(!e)return null;if(e.startsWith("data:"))return e;try{let r=await fetch(e),s=await r.blob();return await new Promise(e=>{let r=new FileReader;r.onload=()=>e("string"==typeof r.result?r.result:null),r.onerror=()=>e(null),r.readAsDataURL(s)})}catch{return null}}let DW=(0,e_.default)("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]),DH=(0,e_.default)("file-plus",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]]);(0,e_.default)("mic",[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]]);let DU=(e=21)=>{let r="",s=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)r+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&s[e]];return r},Dq=(0,$.createContext)(null),DK=(0,$.createContext)(null),DV=()=>(0,$.useContext)(Dq),DX=(0,$.createContext)(null),DY=()=>{let e=(0,$.useContext)(DK),r=(0,$.useContext)(DX),s=e??r;if(!s)throw Error("usePromptInputAttachments must be used within a PromptInput or PromptInputProvider");return s};function DG({data:e,className:r,status:s,onRetry:n,...i}){let a=DY(),o=e.filename||"",l=s?.phase==="reading"||s?.phase==="uploading",c=s?.phase==="error",d="image"==(e.mediaType?.startsWith("image/")&&e.url?"image":"file"),u=o||(d?"Image":"Attachment");return(0,z.jsxs)(D9,{children:[(0,z.jsx)(Ep,{asChild:!0,children:(0,z.jsxs)("div",{className:(0,eb.cn)("group relative flex h-8 cursor-pointer select-none items-center gap-1.5 overflow-hidden rounded-md border border-border px-1.5 font-medium text-sm transition-all hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",c&&"border-destructive text-destructive",r),onClick:c?n:void 0,...i,children:[(0,z.jsxs)("div",{className:"relative size-5 shrink-0",children:[(0,z.jsx)("div",{className:"absolute inset-0 flex size-5 items-center justify-center overflow-hidden rounded bg-background transition-opacity group-hover:opacity-0",children:d?(0,z.jsx)("img",{alt:o||"attachment",className:"size-5 object-cover",height:20,src:e.url,width:20}):(0,z.jsx)("div",{className:"flex size-5 items-center justify-center text-muted-foreground",children:(0,z.jsx)(Dk,{className:"size-3"})})}),(0,z.jsxs)(W.Button,{"aria-label":"Remove attachment",className:"absolute inset-0 size-5 cursor-pointer rounded p-0 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 [&>svg]:size-2.5",onClick:r=>{r.stopPropagation(),a.remove(e.id)},type:"button",variant:"ghost",children:[(0,z.jsx)(t7,{}),(0,z.jsx)("span",{className:"sr-only",children:"Remove"})]})]}),(0,z.jsx)("span",{className:(0,eb.cn)("flex-1 truncate",l&&"opacity-60"),children:u}),l&&(0,z.jsx)(sC,{className:"size-3 shrink-0 animate-spin text-muted-foreground"}),c&&(0,z.jsx)(s_,{className:"size-3 shrink-0"}),s?.phase==="uploading"&&(0,z.jsx)("span",{"aria-hidden":!0,className:"absolute inset-x-0 bottom-0 h-0.5 bg-primary transition-[width] duration-150","data-testid":"attachment-progress",style:{width:`${Math.round((s.progress??0)*100)}%`}})]},e.id)}),(0,z.jsx)(Re,{className:"w-auto p-2",children:(0,z.jsxs)("div",{className:"w-auto space-y-3",children:[d&&(0,z.jsx)("div",{className:"flex max-h-96 w-96 items-center justify-center overflow-hidden rounded-md border",children:(0,z.jsx)("img",{alt:o||"attachment preview",className:"max-h-full max-w-full object-contain",height:384,src:e.url,width:448})}),(0,z.jsx)("div",{className:"flex items-center gap-2.5",children:(0,z.jsxs)("div",{className:"min-w-0 flex-1 space-y-1 px-0.5",children:[(0,z.jsx)("h4",{className:"truncate font-semibold text-sm leading-none",children:o||(d?"Image":"Attachment")}),c?(0,z.jsxs)("p",{className:"text-destructive text-xs",children:[s?.message??"Upload failed",n?" — click to retry":""]}):l?(0,z.jsx)("p",{className:"text-muted-foreground text-xs",children:s?.phase==="reading"?"Reading…":`Uploading… ${Math.round((s?.progress??0)*100)}%`}):e.mediaType&&(0,z.jsx)("p",{className:"truncate font-mono text-muted-foreground text-xs",children:e.mediaType})]})})]})})]})}function DJ({children:e,className:r,...s}){let n=DY();return n.files.length?(0,z.jsx)("div",{className:(0,eb.cn)("flex flex-wrap items-center gap-2 p-3 w-full",r),...s,children:n.files.map(r=>(0,z.jsx)($.Fragment,{children:e(r)},r.id))}):null}let DZ=({label:e="Add photos or files",...r})=>{let s=DY(),n=(0,$.useContext)(D5);return(0,z.jsxs)(o2,{...r,onSelect:e=>{e.preventDefault(),s.openFileDialog(),setTimeout(()=>n?.(),0)},children:[(0,z.jsx)(DH,{className:"mr-2 size-4"})," ",e]})},DQ=({className:e,accept:r,multiple:s,globalDrop:n,syncHiddenInput:i,maxFiles:a,maxFileSize:o,skipAttachmentConversion:l,onError:c,onSubmit:d,children:u,...h})=>{let f=DV(),p=!!f,m=(0,$.useRef)(null),g=(0,$.useRef)(null),[x,v]=(0,$.useState)([]),y=p?f.attachments.files:x,b=(0,$.useRef)(y);b.current=y;let w=(0,$.useCallback)(()=>{m.current?.click()},[]),_=(0,$.useCallback)(e=>!r||""===r.trim()||r.split(",").map(e=>e.trim()).filter(Boolean).some(r=>{if(r.endsWith("/*")){let s=r.slice(0,-1);return e.type.startsWith(s)}return e.type===r}),[r]),S=(0,$.useCallback)(e=>{let r=Array.from(e),s=r.filter(e=>_(e));if(r.length&&0===s.length)return void c?.({code:"accept",message:"No files match the accepted types."});let n=e=>!o||e.size<=o,i=s.filter(n),l=s.filter(e=>!n(e));l.length>0&&(c?.({code:"max_file_size",message:0===i.length?"All files exceed the maximum size.":`Skipped ${l.length} file${1===l.length?"":"s"} over the maximum size: ${l.map(e=>e.name).join(", ")}`,files:l}),0===i.length)||v(e=>{let r="number"==typeof a?Math.max(0,a-e.length):void 0,s="number"==typeof r?i.slice(0,r):i;"number"==typeof r&&i.length>r&&c?.({code:"max_files",message:"Too many files. Some were not added."});let n=[];for(let e of s)n.push({id:DU(),type:"file",url:URL.createObjectURL(e),mediaType:e.type,filename:e.name});return e.concat(n)})},[_,a,o,c]),j=(0,$.useCallback)(e=>v(r=>{let s=r.find(r=>r.id===e);return s?.url&&URL.revokeObjectURL(s.url),r.filter(r=>r.id!==e)}),[]),k=(0,$.useCallback)(()=>v(e=>{for(let r of e)r.url&&URL.revokeObjectURL(r.url);return[]}),[]),C=(0,$.useCallback)(()=>{let e=b.current;return v([]),e},[]),N=(0,$.useCallback)(e=>{v(r=>{let s=new Set(r.map(e=>e.id));return r.concat(e.filter(e=>!s.has(e.id)))})},[]),E=p?f.attachments.add:S,D=p?f.attachments.remove:j,R=p?f.attachments.clear:k,T=p?f.attachments.detach:C,A=p?f.attachments.restore:N,I=p?f.attachments.openFileDialog:w;(0,$.useEffect)(()=>{p&&f.__registerFileInput(m,()=>m.current?.click())},[p,f]),(0,$.useEffect)(()=>{i&&m.current&&0===y.length&&(m.current.value="")},[y,i]),(0,$.useEffect)(()=>{let e=g.current;if(!e||n)return;let r=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault()},s=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault(),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&E(e.dataTransfer.files)};return e.addEventListener("dragover",r),e.addEventListener("drop",s),()=>{e.removeEventListener("dragover",r),e.removeEventListener("drop",s)}},[E,n]),(0,$.useEffect)(()=>{if(!n)return;let e=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault()},r=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault(),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&E(e.dataTransfer.files)};return document.addEventListener("dragover",e),document.addEventListener("drop",r),()=>{document.removeEventListener("dragover",e),document.removeEventListener("drop",r)}},[E,n]),(0,$.useEffect)(()=>()=>{if(!p)for(let e of b.current)e.url&&URL.revokeObjectURL(e.url)},[p]);let M=(0,$.useMemo)(()=>({files:y.map(e=>({...e,id:e.id})),add:E,remove:D,clear:R,detach:T,restore:A,openFileDialog:I,fileInputRef:m}),[y,E,D,R,T,A,I]),F=(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("input",{accept:r,"aria-label":"Upload files",className:"hidden",multiple:s,onChange:e=>{e.currentTarget.files&&E(e.currentTarget.files),e.currentTarget.value=""},ref:m,title:"Upload files",type:"file"}),(0,z.jsx)("form",{className:(0,eb.cn)("w-full",e),onSubmit:e=>{e.preventDefault();let r=e.currentTarget,s=p?f.textInput.value:new FormData(r).get("message")||"";p||r.reset(),Promise.all(y.map(async e=>{if(!l&&e.url&&e.url.startsWith("blob:")){let r=await D$(e.url);return{...e,url:r??e.url}}return e})).then(r=>{try{let n=d({text:s,files:r},e);n instanceof Promise?n.then(()=>{R(),p&&f.textInput.clear()}).catch(()=>{}):(R(),p&&f.textInput.clear())}catch{}}).catch(()=>{})},ref:g,...h,children:(0,z.jsx)(j9,{className:"overflow-hidden border-[#dedede] bg-card shadow-none dark:border-input dark:bg-card focus-within:border-foreground has-[[data-slot=input-group-control]:focus-visible]:border-foreground has-[[data-slot=input-group-control]:focus-visible]:ring-0",children:u})})]});return p?F:(0,z.jsx)(DX.Provider,{value:M,children:F})},D0=({onChange:e,onKeyDown:r,onPasteText:s,className:n,placeholder:i="What would you like to know?",...a})=>{let o=DV(),l=DY(),[c,d]=(0,$.useState)(!1),u=o?{value:o.textInput.value,onChange:r=>{o.textInput.setInput(r.currentTarget.value),e?.(r)}}:{onChange:e};return(0,z.jsx)(ki,{className:(0,eb.cn)("field-sizing-content max-h-48 min-h-9",n),name:"message",onCompositionEnd:()=>d(!1),onCompositionStart:()=>d(!0),onKeyDown:e=>{if(r?.(e),!e.defaultPrevented){if("Enter"===e.key){if(c||e.nativeEvent.isComposing||e.shiftKey)return;e.preventDefault();let r=e.currentTarget.form,s=r?.querySelector('button[type="submit"]');if(s?.disabled)return;r?.requestSubmit()}if("Backspace"===e.key&&""===e.currentTarget.value&&l.files.length>0){e.preventDefault();let r=l.files.at(-1);r&&l.remove(r.id)}}},onPaste:e=>{let r=e.clipboardData?.items;if(!r)return;let n=[];for(let e of r)if("file"===e.kind){let r=e.getAsFile();r&&n.push(r)}if(n.length>0){e.preventDefault(),l.add(n);return}if(s){let r=e.clipboardData.getData("text");r.length>0&&s(e,r)}},placeholder:i,...a,...u})},D1=({className:e,...r})=>(0,z.jsx)(kt,{align:"block-end",className:(0,eb.cn)("order-first flex-wrap gap-1",e),...r}),D2=({variant:e="ghost",className:r,size:s,...n})=>{let i=s??($.Children.count(n.children)>1?"sm":"icon-sm");return(0,z.jsx)(ks,{className:(0,eb.cn)(r),size:i,type:"button",variant:e,...n})},D5=(0,$.createContext)(null),D3=({open:e,defaultOpen:r,onOpenChange:s,...n})=>{let[i,a]=(0,$.useState)(r??!1),o=void 0!==e,l=(0,$.useCallback)(e=>{o||a(e),s?.(e)},[o,s]),c=(0,$.useCallback)(()=>l(!1),[l]);return(0,z.jsx)(D5.Provider,{value:c,children:(0,z.jsx)(oQ,{open:o?e:i,onOpenChange:l,...n})})},D4=({className:e,children:r,...s})=>(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)(D2,{className:e,...s,children:r??(0,z.jsx)(eS,{className:"size-4"})})}),D6=({className:e,...r})=>(0,z.jsx)(o1,{align:"start",className:(0,eb.cn)(e),...r}),D7=({className:e,...r})=>(0,z.jsx)(o2,{className:(0,eb.cn)(e),...r}),D8=({className:e,variant:r="default",size:s="icon-sm",status:n,children:i,...a})=>{let o=(0,z.jsx)(DW,{className:"size-4"});return"submitted"===n?o=(0,z.jsx)(sC,{className:"size-4 animate-spin"}):"streaming"===n?o=(0,z.jsx)(lG,{className:"size-4"}):"error"===n&&(o=(0,z.jsx)(t7,{className:"size-4"})),(0,z.jsx)(ks,{"aria-label":"Submit",className:(0,eb.cn)("rounded-full",e),size:s,type:"submit",variant:r,...a,children:i??o})},D9=({openDelay:e=0,closeDelay:r=0,...s})=>(0,z.jsx)(Ef,{closeDelay:r,openDelay:e,...s}),Re=({align:e="start",...r})=>(0,z.jsx)(Em,{align:e,...r}),Rt=({size:e=16})=>(0,z.jsxs)("svg",{height:e,strokeLinejoin:"round",style:{color:"currentcolor"},viewBox:"0 0 16 16",width:e,children:[(0,z.jsx)("title",{children:"Loader"}),(0,z.jsxs)("g",{clipPath:"url(#clip0_2393_1490)",children:[(0,z.jsx)("path",{d:"M8 0V4",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M8 16V12",opacity:"0.5",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M3.29773 1.52783L5.64887 4.7639",opacity:"0.9",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M12.7023 1.52783L10.3511 4.7639",opacity:"0.1",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M12.7023 14.472L10.3511 11.236",opacity:"0.4",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M3.29773 14.472L5.64887 11.236",opacity:"0.6",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M15.6085 5.52783L11.8043 6.7639",opacity:"0.2",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M0.391602 10.472L4.19583 9.23598",opacity:"0.7",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M15.6085 10.4722L11.8043 9.2361",opacity:"0.3",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M0.391602 5.52783L4.19583 6.7639",opacity:"0.8",stroke:"currentColor",strokeWidth:"1.5"})]}),(0,z.jsx)("defs",{children:(0,z.jsx)("clipPath",{id:"clip0_2393_1490",children:(0,z.jsx)("rect",{fill:"white",height:"16",width:"16"})})})]}),Rr=({className:e,size:r=16,...s})=>(0,z.jsx)("div",{className:(0,eb.cn)("inline-flex animate-spin items-center justify-center",e),...s,children:(0,z.jsx)(Rt,{size:r})}),Rs=new Map;function Rn(e,r){return`${e}\u0000${r??""}`}let Ri=null,Ra=new Map,Ro=new Set;function Rl(e){return Ro.add(e),()=>{Ro.delete(e)}}function Rc(e,r,s){if(!e||!s)return;let n=Ra.get(Rn(e,r));return n?n.has(s):void 0}function Rd(e,r,s){let n=Rn(e,r),i=function(){if(null===Ri){let e={};Ri=e,queueMicrotask(()=>{Ri===e&&(Ri=null)})}return Ri}(),a=Rs.get(n);if(a&&(!s?.force||a.tick===i))return{request:a.request,issuedAt:a.issuedAt};let o=Date.now(),l=ry.api.getActiveWorkflowRuns(e,r).then(e=>(!function(e,r){if(!r)return;let s=Ra.get(e);if(s&&r.every(e=>s.has(e)))return;let n=new Set(s??[]);r.forEach(e=>n.add(e)),Ra.set(e,n),Ro.forEach(e=>e())}(n,e.reviewedSessionIds),e.runs)),c={request:l,tick:i,issuedAt:o};return Rs.set(n,c),l.finally(()=>{Rs.get(n)===c&&Rs.delete(n)}).catch(()=>{}),{request:l,issuedAt:o}}function Ru(e,r,s){return Rd(e,r,s).request}let Rh=(0,e_.default)("wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]),Rf=(0,e_.default)("square-pen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]),Rp=(0,e_.default)("languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]),Rm=(0,e_.default)("split",[["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M8 3H3v5",key:"15dfkv"}],["path",{d:"M12 22v-8.3a4 4 0 0 0-1.172-2.872L3 3",key:"1qrqzj"}],["path",{d:"m15 9 6-6",key:"ko1vev"}]]),Rg=e=>(0,eb.cn)("flex h-5 w-5 shrink-0 items-center justify-center rounded-full","codex"===e?"bg-emerald-500/10 text-emerald-600":"bg-violet-500/10 text-violet-600");function Rx({agentType:e,currentAgentName:r,alternateProviders:s,onBranch:n,disabled:i,emphasis:a="normal"}){return(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:(0,eb.cn)("h-7 w-7 rounded-md transition-colors hover:bg-muted hover:text-foreground","subtle"===a?"text-muted-foreground/50 group-hover:text-muted-foreground group-focus-within:text-muted-foreground":"text-muted-foreground"),disabled:i,"aria-label":"Branch conversation",children:i?(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"}):(0,z.jsx)(Rm,{className:"h-4 w-4"})})}),(0,z.jsxs)(o1,{align:"start",className:"w-44 p-1.5",children:[(0,z.jsx)(o6,{className:"px-2 py-1.5",children:(0,z.jsx)("div",{className:"text-xs font-medium",children:"Branch conversation"})}),(0,z.jsxs)(o2,{className:"h-8 cursor-pointer items-center gap-2 rounded-md px-2 text-xs",onSelect:()=>n(),children:[(0,z.jsx)("div",{className:Rg(e),children:(0,z.jsx)(sS,{className:"h-3 w-3"})}),(0,z.jsx)("span",{className:"min-w-0 flex-1 truncate",children:r}),(0,z.jsx)("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:"current"})]}),s.length>0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(o7,{className:"my-1"}),s.map(e=>(0,z.jsxs)(o2,{className:"h-8 cursor-pointer items-center gap-2 rounded-md px-2 text-xs",onSelect:()=>n(e.type),children:[(0,z.jsx)("div",{className:Rg(e.type),children:(0,z.jsx)(sS,{className:"h-3 w-3"})}),(0,z.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.displayName})]},e.type))]})]})]})}let Rv=(0,e_.default)("corner-up-left",[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]]),Ry=e=>(0,eb.cn)("h-7 w-7 shrink-0 rounded-md transition-colors hover:bg-muted hover:text-foreground","subtle"===e?"text-muted-foreground/50 group-hover:text-muted-foreground group-focus-within:text-muted-foreground":"text-muted-foreground");function Rb({sendBack:e,emphasis:r}){let s=e.available?e.sent?"Sent — click to send again":"Send this answer back to the source session":"Source session no longer exists",n=(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:Ry(r),"aria-label":"Send back to source session",disabled:!e.available||e.busy,onClick:e.onSend,children:e.busy?(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"}):e.sent?(0,z.jsx)(rp.Check,{className:"h-4 w-4"}):(0,z.jsx)(Rv,{className:"h-4 w-4"})});return(0,z.jsx)(cb,{children:(0,z.jsxs)(cw,{children:[(0,z.jsx)(c_,{asChild:!0,children:e.available?n:(0,z.jsx)("span",{tabIndex:-1,children:n})}),(0,z.jsx)(cS,{children:s})]})})}function Rw({durationMs:e,outcome:r,emphasis:s,agentType:n,currentAgentName:i,alternateProviders:a,onBranch:o,disabled:l,showFinalize:c,finalizeBusy:d,onFinalize:u,sendBack:h}){let f=void 0!==e?fx(e):"server_restart"===r?"interrupted":null;return(0,z.jsxs)("div",{className:"group flex items-center gap-2 py-0.5","data-turn-end":!0,children:[(0,z.jsx)("div",{className:"h-px flex-1 bg-border/60"}),null!==f&&(0,z.jsx)("span",{className:(0,eb.cn)("shrink-0 text-[11px] tabular-nums transition-colors","subtle"===s?"text-muted-foreground/50 group-hover:text-muted-foreground group-focus-within:text-muted-foreground":"text-muted-foreground"),children:f}),c&&(0,z.jsx)(cb,{children:(0,z.jsxs)(cw,{children:[(0,z.jsx)(c_,{asChild:!0,children:(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:Ry(s),"aria-label":"生成 review 终稿",onClick:u,disabled:l||d,children:d?(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"}):(0,z.jsx)(NY,{className:"h-4 w-4"})})}),(0,z.jsx)(cS,{children:"生成 review 终稿"})]})}),h&&(0,z.jsx)(Rb,{sendBack:h,emphasis:s}),(0,z.jsx)(Rx,{agentType:n,currentAgentName:i,alternateProviders:a,onBranch:o,disabled:l,emphasis:s}),(0,z.jsx)("div",{className:"h-px flex-1 bg-border/60"})]})}let R_=(e,r)=>Math.max(0,e-r),RS=["process","agent","other"],Rj={process:"Process",agent:"Subagent",other:"Task"},Rk={process:["background process","background processes"],agent:["background subagent","background subagents"],other:["background task","background tasks"]};function RC(e){return"local_bash"===e.taskType?"process":"local_agent"===e.taskType||"codex_subagent"===e.taskType?"agent":"other"}function RN({kind:e}){let r="h-3.5 w-3.5";return"process"===e?(0,z.jsx)(gM,{className:r,"aria-hidden":"true"}):"agent"===e?(0,z.jsx)(sS,{className:r,"aria-hidden":"true"}):(0,z.jsx)(s0,{className:r,"aria-hidden":"true"})}function RE({sessionId:e,tasks:r,turnParked:s,parkDeadlineAt:n,canStopTasks:i,agentWorking:a}){let o,l,[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(new Set),f=function(e){let[r,s]=(0,$.useState)(()=>Date.now());return(0,$.useEffect)(()=>{if(!e)return;let r=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(r)},[e]),r}(r.length>0);if(0===r.length)return null;let p=r.reduce((e,r)=>Math.max(e,R_(f,r.startedAt)),0),m=null===n||(o=Math.round((n-f)/1e3))<=0?null:`${Math.floor(o/60)}:${String(o%60).padStart(2,"0")}`,g=r.some(e=>e.sanctioned),x=s||a,v=m?`${m} until this turn closes automatically`:s&&g?"Waiting for these tasks":s?"Response complete":a?"Running alongside the agent":"This turn has closed",y=async(r,s)=>{if(e){h(e=>new Set(e).add(r));try{return await s(r)}finally{h(e=>{let s=new Set(e);return s.delete(r),s})}}};return(0,z.jsxs)("div",{className:(0,eb.cn)("mb-2 rounded-lg border text-xs",x?"border-amber-500/40 bg-amber-500/5":"border-border/60 bg-muted/30"),children:[(0,z.jsxs)("button",{type:"button",onClick:()=>d(e=>!e),"aria-expanded":c,className:"flex w-full items-center gap-2 px-3 py-2 text-left text-muted-foreground transition-colors hover:text-foreground",children:[(0,z.jsxs)("span",{className:"relative flex h-1.5 w-1.5 shrink-0",children:[(0,z.jsx)("span",{className:(0,eb.cn)("absolute inline-flex h-full w-full animate-ping rounded-full",x?"bg-amber-500/60":"bg-muted-foreground/40")}),(0,z.jsx)("span",{className:(0,eb.cn)("relative inline-flex h-1.5 w-1.5 rounded-full",x?"bg-amber-500":"bg-muted-foreground/70")})]}),(0,z.jsxs)("span",{className:"truncate",children:[(l=RS.flatMap(e=>{let s=r.filter(r=>RC(r)===e).length;return s?[`${s} ${Rk[e][+(1!==s)]}`]:[]}),`${l.join(" · ")} running`),(0,z.jsxs)("span",{className:"tabular-nums",children:[" · ",fx(p)]})]}),(0,z.jsx)("span",{className:(0,eb.cn)("shrink-0",m?"text-amber-600 dark:text-amber-500":"text-muted-foreground/70"),children:v}),(0,z.jsx)(n6,{className:(0,eb.cn)("ml-auto h-3.5 w-3.5 shrink-0 transition-transform",c&&"rotate-180")})]}),c&&(0,z.jsxs)("ul",{className:"border-t border-border/60 px-3 py-2",children:[r.map(r=>{let s=RC(r),n=Rj[s];return(0,z.jsxs)("li",{className:"flex items-baseline gap-2 py-1",children:[(0,z.jsx)("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center self-center text-muted-foreground","aria-label":n,title:n,children:(0,z.jsx)(RN,{kind:s})}),(0,z.jsx)("span",{className:"min-w-0 flex-1 truncate text-foreground/90",children:r.description||r.taskId}),(0,z.jsx)("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:fx(R_(f,r.startedAt))}),e&&(0,z.jsxs)("span",{className:"flex shrink-0 gap-1",children:[m&&!r.sanctioned&&(0,z.jsx)("button",{type:"button",onClick:()=>y(r.taskId,r=>(0,ry.keepBackgroundTaskRunning)(e,r)),disabled:u.has(r.taskId),title:"Keep this turn open until this task finishes, instead of closing it when the timer runs out",className:"rounded border border-border/60 px-1.5 py-px text-[11px] text-muted-foreground transition-colors hover:text-foreground disabled:opacity-50",children:"Keep waiting"}),i&&(0,z.jsx)("button",{type:"button",onClick:()=>y(r.taskId,r=>(0,ry.stopBackgroundTask)(e,r)),disabled:u.has(r.taskId),title:"End this background task now",className:"rounded border border-border/60 px-1.5 py-px text-[11px] text-muted-foreground transition-colors hover:text-foreground disabled:opacity-50",children:"Stop task"})]})]},r.taskId)}),(0,z.jsx)("li",{className:"pt-1.5 text-muted-foreground/70",children:m?"The agent has already answered — these tasks are the only thing keeping this turn open. When the timer runs out the turn closes on its own, and the tasks keep running in the background.":s&&g?"You chose to keep waiting for these tasks, so this turn stays open until they finish.":s?"The agent has already answered — these tasks are the only thing keeping this turn open.":a?"The agent is still working. These tasks are running alongside it.":"This turn has closed, but these tasks are still running. Stopping them will not affect the completed turn."}),!i&&(0,z.jsx)("li",{className:"pt-1 text-muted-foreground/70",children:"This agent cannot stop individual background tasks. Stop the session to end them all."})]})]})}function RD({candidates:e,className:r,children:s}){let n=Array.from(new Set(e));return(0,z.jsxs)("span",{className:(0,eb.cn)("grid overflow-hidden text-left",r),children:[n.map(e=>(0,z.jsx)("span",{"aria-hidden":!0,className:"col-start-1 row-start-1 invisible whitespace-nowrap",children:e},e)),(0,z.jsx)("span",{className:"col-start-1 row-start-1 min-w-0 truncate",children:s})]})}let RR="Default",RT="Runs whatever model the CLI is currently set to, which may not be its built-in default.",RA="inline-flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-0.5 text-xs font-medium";function RI({models:e,widthCandidates:r,value:s,onChange:n,locked:i}){let a,[o,l]=(0,$.useState)(!1),[c,d]=(0,$.useState)(""),[u,h]=(0,$.useState)(!1),f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=(0,$.useRef)(0);(0,$.useLayoutEffect)(()=>{let e=f.current,r=p.current;if(e&&r){var s;u||(m.current=e.clientWidth),h((s={textWidth:r.offsetWidth,narrowFieldWidth:m.current,wide:u}).narrowFieldWidth<=0?s.wide:s.textWidth>s.narrowFieldWidth)}},[o,c,u]);let g=s??RR,x=[RR,...r??e];if(i)return(0,z.jsxs)("span",{className:(0,eb.cn)(RA,"text-muted-foreground cursor-default"),title:`${g} — fixed while the agent is running, changeable once the turn ends`,children:[(0,z.jsx)(RD,{candidates:x,className:"max-w-40",children:g}),(0,z.jsx)(n6,{className:"h-3 w-3"})]});let v=c.trim(),y=(a=c.trim()).length>0&&!e.includes(a),b=e=>{n(e),d(""),l(!1)};return(0,z.jsxs)(fJ,{open:o,onOpenChange:l,children:[(0,z.jsx)(fZ,{asChild:!0,children:(0,z.jsxs)("button",{className:(0,eb.cn)(RA,"transition-colors hover:bg-muted"),title:g,children:[(0,z.jsx)(RD,{candidates:x,className:"max-w-40",children:g}),(0,z.jsx)(n6,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,z.jsxs)(fQ,{className:u?"w-56":"w-[var(--radix-popover-trigger-width)]",children:[(0,z.jsx)("span",{ref:p,"aria-hidden":!0,className:"pointer-events-none invisible absolute whitespace-pre text-sm",children:c}),(0,z.jsxs)(p_,{shouldFilter:!0,children:[(0,z.jsx)(pj,{ref:f,className:"min-w-0",value:c,onValueChange:d}),(0,z.jsxs)(pk,{children:[(0,z.jsx)(pC,{children:"No match."}),(0,z.jsxs)(pN,{children:[(0,z.jsxs)(pE,{value:RR,onSelect:()=>b(null),className:"text-xs",children:[RR,(0,z.jsx)(cb,{delayDuration:200,children:(0,z.jsxs)(cw,{children:[(0,z.jsx)(c_,{asChild:!0,children:(0,z.jsx)("span",{onClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),className:"ml-auto flex cursor-help items-center text-muted-foreground",children:(0,z.jsx)(hv,{"aria-hidden":!0,className:"size-3"})})}),(0,z.jsx)(cS,{side:"right",className:"max-w-56",children:RT})]})}),(0,z.jsx)("span",{className:"sr-only",children:RT})]}),e.map(e=>(0,z.jsx)(pE,{value:e,onSelect:()=>b(e),className:"text-xs",children:e},e))]}),y&&(0,z.jsx)(pN,{heading:"Custom",children:(0,z.jsx)(pE,{value:v,onSelect:()=>b(v),className:"text-xs [&>span]:truncate",title:v,children:(0,z.jsxs)("span",{children:['Use "',v,'"']})})})]})]})]})]})}let RM=(0,e_.default)("settings-2",[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]),RF=new Set(["workspace","tasks","schedules","remote-servers","settings","project-info","project-chat"]),RP="tasks";function RL(e){return e.length>0&&e.trim()===e&&!/[\u0000-\u001f\u007f/\\]/.test(e)}function RO(){let e=window.location.pathname,r=new URLSearchParams(window.location.search),s=r.get("project");if(s){let e=r.get("tab");return{projectId:s,tab:e&&RF.has(e)?e:RP,branch:r.get("branch"),threadId:null}}let n=e.split("/").filter(Boolean);if(1===n.length&&RF.has(n[0])){let e=n[0];if("remote-servers"===e||"settings"===e)return{projectId:null,tab:e,branch:null,threadId:null}}let i=null,a=RP,o=null;if("p"===n[0]&&n[1]){i=n[1];let e=n[2];if("chat"===e&&4===n.length&&n[3])try{let e=decodeURIComponent(n[3]);RL(e)?(o=e,a="project-chat"):a="project-info"}catch{a="project-info",o=null}else"chat"===e?a="project-info":e&&RF.has(e)&&"project-chat"!==e&&(a=e)}return{projectId:i,tab:a,branch:r.get("branch"),threadId:o}}function RB(e){let{projectId:r,tab:s,branch:n,threadId:i}=e;if("remote-servers"===s||"settings"===s)return`/${s}`;if(!r)return"/";if("project-chat"===s)return i&&RL(i)?`/p/${r}/chat/${encodeURIComponent(i)}`:`/p/${r}/project-info`;let a=`/p/${r}/${s??RP}`;return n&&(a+=`?branch=${encodeURIComponent(n)}`),a}function Rz({granted:e,onToggle:r,sourceRemoteId:s,disabled:n}){let[i,a]=(0,$.useState)(null),[o,l]=(0,$.useState)(!1),c=(0,$.useCallback)(()=>{l(!1),ry.api.getRemoteServers().then(e=>a([...e].sort((e,r)=>Number("online"===r.status)-Number("online"===e.status)))).catch(()=>l(!0))},[]),d=(i??[]).filter(e=>"off"!==e.cross_remote_access).filter(e=>e.id!==s);return(0,z.jsxs)(o8,{onOpenChange:e=>{e&&c()},children:[(0,z.jsxs)(o9,{disabled:n,children:[(0,z.jsx)(no,{className:"mr-2 size-4"}),"Remote access"]}),(0,z.jsxs)(le,{className:"w-64 p-1",children:[(0,z.jsxs)("div",{className:"px-2 pt-1.5 pb-2",children:[(0,z.jsx)("div",{className:"text-sm font-medium",children:"Remote access"}),(0,z.jsx)("div",{className:"text-xs text-muted-foreground",children:s?"Other machines this agent can reach":"Machines this agent can reach"})]}),(0,z.jsx)(o7,{}),(0,z.jsxs)("div",{className:"max-h-72 overflow-y-auto",children:[null===i&&!o&&(0,z.jsxs)("div",{className:"flex items-center gap-2 px-2 py-3 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"size-3.5 animate-spin"})," Loading machines…"]}),o&&(0,z.jsx)("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:"Could not load remote machines."}),null!==i&&!o&&0===d.length&&(0,z.jsxs)("div",{className:"flex flex-col items-center gap-2 px-4 py-5 text-center",children:[(0,z.jsx)("div",{className:"flex size-9 items-center justify-center rounded-full bg-muted",children:(0,z.jsx)(no,{className:"size-4 text-muted-foreground"})}),(0,z.jsx)("div",{className:"text-sm font-medium",children:"No machines available"}),(0,z.jsx)("div",{className:"text-xs text-muted-foreground",children:"Enable cross-remote access for another machine in Remote Servers."})]}),d.map(s=>{let n=e.some(e=>e.id===s.id),i="online"===s.status,a="exec"===s.cross_remote_access;return(0,z.jsxs)(o2,{role:"menuitemcheckbox","aria-checked":n,onSelect:e=>{e.preventDefault(),r({id:s.id,name:s.name,access:s.cross_remote_access,online:i},!n)},className:"gap-3 py-2",children:[(0,z.jsxs)("span",{className:"relative flex size-8 shrink-0 items-center justify-center rounded-md border bg-muted/40",children:[(0,z.jsx)(no,{className:"size-4"}),(0,z.jsx)("span",{className:(0,eb.cn)("absolute -right-0.5 -bottom-0.5 size-2.5 rounded-full ring-2 ring-popover",i?"bg-emerald-500":"bg-muted-foreground/50"),title:i?"Online":"Offline"})]}),(0,z.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col",children:[(0,z.jsx)("span",{className:"truncate font-medium",children:s.name}),(0,z.jsx)("span",{className:"flex min-w-0 items-center gap-1 whitespace-nowrap text-xs text-muted-foreground",children:a?(0,z.jsxs)("span",{className:"flex min-w-0 items-center gap-1 text-amber-600 dark:text-amber-400",children:[(0,z.jsx)(p9,{className:"size-3"}),(0,z.jsx)("span",{className:"truncate",children:"Run commands"})]}):(0,z.jsxs)("span",{className:"flex min-w-0 items-center gap-1",children:[(0,z.jsx)(_P,{className:"size-3"}),(0,z.jsx)("span",{className:"truncate",children:"Read only"})]})})]}),(0,z.jsx)("span",{"aria-hidden":!0,className:(0,eb.cn)("relative inline-flex h-4.5 w-8 shrink-0 items-center rounded-full transition-colors",n?"bg-emerald-500":"bg-muted-foreground/25"),children:(0,z.jsx)("span",{className:(0,eb.cn)("size-3.5 rounded-full bg-white shadow-sm transition-transform",n?"translate-x-4":"translate-x-0.5")})})]},s.id)})]}),(0,z.jsx)(o7,{}),(0,z.jsxs)(o2,{onSelect:()=>{window.history.pushState(null,"",RB({tab:"remote-servers"})),window.dispatchEvent(new PopStateEvent("popstate"))},className:"text-muted-foreground",children:[(0,z.jsx)(RM,{className:"size-4"}),"Manage machines…"]})]})]})}function R$({granted:e,onRevoke:r}){return 0===e.length?null:(0,z.jsx)("div",{className:"flex flex-wrap items-center gap-1.5 pl-12 pr-2 pt-1.5 pb-0.5",children:e.map(e=>(0,z.jsxs)("button",{type:"button",onClick:()=>r(e),title:`Cross-remote ${e.access} access \xb7 ${e.online?"online":"offline"}`,className:(0,eb.cn)("inline-flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium transition-colors","bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 hover:bg-emerald-500/20"),children:[(0,z.jsxs)("span",{className:"relative flex",children:[(0,z.jsx)(no,{className:"size-3"}),(0,z.jsx)("span",{className:(0,eb.cn)("absolute -right-0.5 -bottom-0.5 size-1.5 rounded-full ring-1 ring-background",e.online?"bg-emerald-500":"bg-muted-foreground/60")})]}),e.name,(0,z.jsx)(t7,{className:"size-3"})]},e.id))})}let RW="vibedeckx:remote-grant-declarations",RH=(e,r)=>e?`s:${e}`:`w:${r}`;function RU(){try{let e=window.localStorage.getItem(RW),r=e?JSON.parse(e):null;return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}catch{return{}}}function Rq(e){try{0===Object.keys(e).length?window.localStorage.removeItem(RW):window.localStorage.setItem(RW,JSON.stringify(e))}catch{}}function RK(e){let r=RU()[e];return Array.isArray(r)?r:[]}let RV=(0,e_.default)("clipboard-list",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);function RX({mode:e,onModeChange:r,disabled:s}){return(0,z.jsxs)("div",{className:"inline-flex items-center rounded-md border bg-muted/50 px-0.5 text-xs",children:[(0,z.jsxs)("button",{onClick:()=>r("plan"),disabled:s,className:(0,eb.cn)("inline-flex items-center gap-1 rounded-sm px-2 py-0.5 transition-colors","plan"===e?"bg-primary text-primary-foreground font-medium shadow-sm":"text-muted-foreground hover:text-foreground",s&&"opacity-50 cursor-not-allowed"),children:[(0,z.jsx)(RV,{className:"h-3 w-3"}),"Plan"]}),(0,z.jsxs)("button",{onClick:()=>r("edit"),disabled:s,className:(0,eb.cn)("inline-flex items-center gap-1 rounded-sm px-2 py-0.5 transition-colors","edit"===e?"bg-primary text-primary-foreground font-medium shadow-sm":"text-muted-foreground hover:text-foreground",s&&"opacity-50 cursor-not-allowed"),children:[(0,z.jsx)(rx,{className:"h-3 w-3"}),"Edit"]})]})}function RY({type:e,className:r}){return(0,z.jsx)(sS,{className:(0,eb.cn)("h-3 w-3 shrink-0","codex"===e?"text-green-500":"text-violet-500",r)})}function RG(e){if(!e)return[];try{let r=window.localStorage.getItem(e);if(!r)return[];let s=JSON.parse(r);if(!Array.isArray(s))return[];return s.filter(e=>"string"==typeof e)}catch{return[]}}let RJ=new Set(["preparing","waiting_reviewer","waiting_feedback","discussing","sending_feedback"]);function RZ(e){if(!e)return"";try{return window.localStorage.getItem(e)??""}catch{return""}}function RQ(e){let r=e.parentElement;for(;r;){let{overflowY:e}=getComputedStyle(r);if("auto"===e||"scroll"===e)return r;r=r.parentElement}return null}function R0({messages:e,contentRef:r}){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(null),c=(0,$.useRef)(null),d=(0,$.useCallback)(()=>{let s=r.current;if(!s)return;c.current||(c.current=RQ(s));let i=c.current;if(!i)return;let o=i.scrollHeight>i.clientHeight;if(a(o),!o)return void n([]);let l=s.querySelectorAll("[data-user-msg-idx]"),d=i.getBoundingClientRect(),u=[];l.forEach(r=>{let s=parseInt(r.dataset.userMsgIdx,10),n=e[s];if(!n)return;let a=(r.getBoundingClientRect().top-d.top+i.scrollTop)/i.scrollHeight;u.push({index:s,position:Math.max(0,Math.min(1,a)),preview:function(e){if("user"!==e.type)return"";let r=e.content,s="string"==typeof r?r:r.filter(e=>"text"===e.type).map(e=>e.text).join(" "),n="string"!=typeof r&&r.some(e=>"image"===e.type),i=s.replace(DD,"").trim().split("\n")[0]??"";return(i.length>80?i.slice(0,77)+"...":i)||(n?"(Image)":"")}(n)})}),n(u)},[e,r]);(0,$.useEffect)(()=>{let e=r.current;if(!e){c.current=null,n([]),a(!1);return}let s=RQ(e);if(!s)return;c.current=s,d();let i=new ResizeObserver(d);return i.observe(s),i.observe(e),()=>{i.disconnect()}},[e,d,r]);let u=(0,$.useCallback)(e=>{let s=r.current;if(!s)return;let n=s.querySelector(`[data-user-msg-idx="${e}"]`);n&&n.scrollIntoView({block:"start",behavior:"smooth"})},[r]);return i&&0!==s.length?(0,z.jsx)("div",{className:"absolute right-0 top-0 bottom-0 w-6 z-20 pointer-events-none",children:s.map(e=>(0,z.jsxs)("div",{className:"absolute right-0.5 -translate-y-1/2 pointer-events-auto",style:{top:`${100*e.position}%`},children:[(0,z.jsx)("div",{className:"w-3 h-[3px] rounded-sm bg-primary/50 hover:bg-primary cursor-pointer transition-colors",onClick:()=>u(e.index),onMouseEnter:()=>l(e.index),onMouseLeave:()=>l(null)}),o===e.index&&e.preview&&(0,z.jsxs)("div",{className:"absolute right-full mr-2 top-1/2 -translate-y-1/2 max-w-64 px-2.5 py-1.5 bg-popover border border-border rounded-md shadow-md text-xs text-popover-foreground whitespace-nowrap overflow-hidden text-ellipsis pointer-events-none",children:[e.preview,(0,z.jsx)("div",{className:"absolute top-1/2 -translate-y-1/2 -right-1 w-2 h-2 bg-popover border-r border-t border-border rotate-45"})]})]},e.index))}):null}function R1(e,r){return`${e}:${r??""}`}function R2({projectId:e,branch:r,currentSessionId:s,refreshKey:n,pendingTitleSessionId:i,aiTitleOverride:a,onSwitch:o,onDelete:l}){let[c,d]=(0,$.useState)([]),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(""),[m,g]=(0,$.useState)(!1),[x,v]=(0,$.useState)(null),[y,b]=(0,$.useState)(null),[w,_]=(0,$.useState)(0),S=(0,$.useCallback)(()=>_(e=>e+1),[]),[j,k]=(0,$.useState)(null),C=R1(e,r);(0,$.useEffect)(()=>{let s=!1;return(0,ry.listBranchSessions)(e,r).then(n=>{s||(d(n.sessions),k(R1(e,r)))}).catch(n=>{s||(console.error("[SessionHistoryDropdown] refresh failed:",n),k(R1(e,r)))}),()=>{s=!0}},[e,r,n,w]);let N=(0,$.useRef)(null);(0,$.useEffect)(()=>{if(!s||j!==C)return;if(c.some(e=>e.id===s)){N.current=null;return}if(N.current===s)return;N.current=s;let n=!1;return(0,ry.listBranchSessions)(e,r).then(i=>{if(n)return;d(i.sessions),k(R1(e,r));let o=i.sessions.find(e=>e.id===s),l=!!o&&(a?.sessionId===o.id||!!(o.title&&o.title.trim().length>0));o&&!l&&b(s)}).catch(e=>{n||console.error("[SessionHistoryDropdown] missing-session refresh failed:",e)}),()=>{n=!0}},[s,c,e,r,C,j,a]),(0,$.useEffect)(()=>{if(!y)return;let e=setTimeout(()=>{b(e=>e===y?null:e)},3e4);return()=>clearTimeout(e)},[y]),(0,$.useEffect)(()=>{if(!y)return;let e=setTimeout(()=>{b(e=>e===y?null:e)},3e4);return()=>clearTimeout(e)},[y]);let E=async(e,r)=>{let s=r.trim().length>0?r.trim():null;try{await (0,ry.renameSession)(e,s),d(r=>r.map(r=>r.id===e?{...r,title:s}:r)),h(null),gS.toast.success("Renamed")}catch(e){gS.toast.error("Rename failed"),console.error(e)}},D=async(e,r)=>{let s=null==r,n=s?Date.now():null;d(r=>r.map(r=>r.id===e?{...r,favorited_at:n}:r));try{await (0,ry.setSessionFavorited)(e,s)}catch(n){d(s=>s.map(s=>s.id===e?{...s,favorited_at:r}:s)),gS.toast.error(s?"Favorite failed":"Unfavorite failed"),console.error(n)}},R=async e=>{try{await (0,ry.deleteSession)(e);let r=c.filter(r=>r.id!==e);d(r),l?.(e,r),gS.toast.success("Deleted")}catch(e){gS.toast.error("Delete failed"),console.error(e)}},T=e=>a&&a.sessionId===e.id?a.title:e.title&&e.title.trim().length>0?e.title:e.updated_at?new Date(e.updated_at).toLocaleString():new Date(e.created_at).toLocaleString(),A=e=>{let r;return a?.sessionId!==e.id&&(!e.title||!(e.title.trim().length>0))&&(r=e.id,null!==i&&i===r||y===e.id)},I=c.find(e=>e.id===s),M=null!==s&&(!I||A(I)),F=I?T(I):null===s?"New Session":"History",P=M?"Generating title…":F;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(oQ,{open:m,onOpenChange:e=>{g(e),e&&S()},children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsxs)(W.Button,{variant:"ghost",size:"sm",className:"h-7 text-xs gap-1 w-[200px] justify-start",title:P,children:[M?(0,z.jsx)("span",{className:"block h-3 flex-1 rounded-sm bg-accent animate-pulse",role:"status","aria-label":"Generating title"}):(0,z.jsx)("span",{className:"truncate flex-1 text-left",children:F}),(0,z.jsx)(n6,{className:"h-3 w-3 flex-shrink-0"})]})}),(0,z.jsxs)(o1,{align:"start",className:"w-80 max-h-96 overflow-y-auto",children:[0===c.length&&(0,z.jsx)("div",{className:"px-2 py-3 text-xs text-muted-foreground",children:"No history yet."}),c.map(e=>{let r=e.id===s,n=u===e.id;return(0,z.jsxs)(o2,{onSelect:s=>{n?s.preventDefault():r||o(e.id)},onPointerMove:null!==u?e=>e.preventDefault():void 0,className:`flex items-center gap-2 group ${r?"bg-accent text-accent-foreground":""}`,children:[(0,z.jsx)("div",{className:"flex-1 min-w-0",children:n?(0,z.jsxs)("div",{className:"flex items-center gap-1",children:[(0,z.jsx)(rl,{value:f,onChange:e=>p(e.target.value),onKeyDown:r=>{r.stopPropagation(),"Enter"===r.key&&E(e.id,f),"Escape"===r.key&&h(null)},autoFocus:!0,className:"h-6 text-xs"}),(0,z.jsx)("button",{type:"button","aria-label":"Save rename",onClick:r=>{r.stopPropagation(),E(e.id,f)},children:(0,z.jsx)(rp.Check,{className:"h-3 w-3"})}),(0,z.jsx)("button",{type:"button","aria-label":"Cancel rename",onClick:e=>{e.stopPropagation(),h(null)},children:(0,z.jsx)(t7,{className:"h-3 w-3"})})]}):A(e)?(0,z.jsx)("div",{className:"py-0.5",title:"Generating title…",children:(0,z.jsx)("span",{className:"block h-3 w-40 rounded-sm bg-accent animate-pulse",role:"status","aria-label":"Generating title"})}):(0,z.jsx)("div",{className:"truncate text-xs",title:`${e.updated_at?new Date(e.updated_at).toLocaleString():new Date(e.created_at).toLocaleString()} • ${e.entry_count??0} messages • status: ${e.status} • model: ${e.model??"Default"}`,children:T(e)})}),!n&&(0,z.jsxs)("div",{className:"flex items-center gap-1",children:[(0,z.jsxs)("div",{className:"opacity-0 group-hover:opacity-100 flex items-center gap-1",children:[(0,z.jsx)("button",{type:"button","aria-label":"Rename conversation",onClick:r=>{r.stopPropagation(),h(e.id),p(e.title??"")},className:"p-1 hover:bg-muted rounded",children:(0,z.jsx)(rx,{className:"h-3 w-3"})}),(0,z.jsx)("button",{type:"button","aria-label":"Delete conversation",onClick:r=>{r.stopPropagation(),g(!1),v(e)},className:"p-1 hover:bg-muted rounded text-destructive",children:(0,z.jsx)(rd,{className:"h-3 w-3"})})]}),(0,z.jsx)("button",{type:"button","aria-label":null!=e.favorited_at?"Unfavorite conversation":"Favorite conversation",title:null!=e.favorited_at?"Unfavorite":"Favorite",onClick:r=>{r.stopPropagation(),D(e.id,e.favorited_at??null)},className:`p-1 hover:bg-muted rounded ${null!=e.favorited_at?"opacity-100 text-yellow-500":"opacity-0 group-hover:opacity-100 text-muted-foreground"}`,children:(0,z.jsx)(nt,{className:`h-3 w-3 ${null!=e.favorited_at?"fill-current":""}`})})]})]},e.id)}),c.length>0&&(0,z.jsx)(o7,{}),(0,z.jsx)(o2,{onSelect:()=>S(),className:"text-xs text-muted-foreground",children:"Refresh"})]})]}),(0,z.jsx)(lL,{open:null!==x,onOpenChange:e=>{e||v(null)},children:(0,z.jsxs)(lz,{children:[(0,z.jsxs)(l$,{children:[(0,z.jsx)(lH,{children:"Delete conversation?"}),(0,z.jsx)(lU,{children:x?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"font-medium text-foreground",children:T(x)})," ","and its message history will be permanently deleted. This cannot be undone."]}):null})]}),(0,z.jsxs)(lW,{children:[(0,z.jsx)(lK,{children:"Cancel"}),(0,z.jsx)(lq,{className:(0,eb.cn)((0,W.buttonVariants)({variant:"destructive"}),"border-transparent"),onClick:()=>{x&&R(x.id),v(null)},children:"Delete"})]})]})})]})}let R5=[];function R3(e,r={}){R5.push({t:Math.round(performance.now()),ev:e,...r}),R5.length>200&&R5.shift()}function R4({messageCount:e,turnInFlight:r,sessionId:s}){let{scrollToBottom:n,scrollRef:i,contentRef:a}=cB(),{index:o}=Cc(),l=o?.version??null,c=(0,$.useRef)({turnInFlight:r,settleDeadline:0,settleHardCap:0,prevScrollHeight:0,prevClientHeight:0});c.current.turnInFlight=r;let d=()=>{let e=performance.now();c.current.settleDeadline=e+600,c.current.settleHardCap=e+8e3},u=(0,$.useRef)(!0),h=(0,$.useRef)(l),f=(0,$.useRef)(s);return(0,$.useLayoutEffect)(()=>{let r=s!==f.current,a=u.current&&e>0;if(f.current=s,u.current=0===e,!a&&!(r&&e>0))return;d(),R3(a?"fill":"session-switch",{sessionId:s,messageCount:e});let o=i.current;o&&(o.scrollTop=o.scrollHeight),n({animation:"instant"})},[e,s,n,i]),(0,$.useLayoutEffect)(()=>{l!==h.current&&(h.current=l,R3("index-version",{version:l,messageCount:e}),e>0&&d())},[l,e]),(0,$.useEffect)(()=>{let e=i.current,r=a.current;if(!e||!r||"undefined"==typeof ResizeObserver)return;c.current.prevScrollHeight=e.scrollHeight,c.current.prevClientHeight=e.clientHeight;let s=null,n=e.scrollTop,o=()=>{let i=e.scrollTop;for(let e of(Math.abs(i-n)>40&&R3("scroll-jump",{from:Math.round(n),to:Math.round(i)}),n=i,s=null,r.querySelectorAll("[data-message-idx]")))if(e.offsetTop+e.offsetHeight>i){s={el:e,offset:e.offsetTop-i};break}};o(),e.addEventListener("scroll",o,{passive:!0});let l=new Map,u=new ResizeObserver(()=>{let n,i,a=c.current,o=a.prevScrollHeight,u=e.scrollHeight,h=a.prevClientHeight,f=e.clientHeight;a.prevScrollHeight=u,a.prevClientHeight=f;let p=Math.abs(u-o)>1;if(Math.abs(f-h)>1&&!p){let r=function({scrollTop:e,scrollHeight:r,prevClientHeight:s}){return e+s>=r-6}({scrollTop:e.scrollTop,scrollHeight:u,prevClientHeight:h});r&&(e.scrollTop=u),R3("viewport-resize",{prevClient:h,client:f,scrollTop:Math.round(e.scrollTop),pinned:r});return}if(!p)return;let m=(n=c.current,(i=performance.now())<n.settleDeadline&&i<n.settleHardCap);m&&d();let g=e.scrollTop+h>=o-6,x=function({settling:e,turnInFlight:r,wasAtBottom:s}){return!!s&&(e||!r)}({settling:m,turnInFlight:a.turnInFlight,wasAtBottom:g});x?e.scrollTop=u:!g&&m&&s?.el.isConnected&&(e.scrollTop=s.el.offsetTop-s.offset);let v=u-e.clientHeight-e.scrollTop;R3("resize",{prev:o,next:u,clientH:e.clientHeight,scrollTop:Math.round(e.scrollTop),settling:m,turnInFlight:a.turnInFlight,wasAtBottom:g,action:x?"hold-bottom":"none",distAfter:Math.round(v),grew:(()=>{let e=[];for(let s of r.querySelectorAll("[data-message-idx]")){let r=s.getAttribute("data-message-idx")??"?",n=s.offsetHeight,i=l.get(r);void 0!==i&&Math.abs(i-n)>2&&e.push({idx:r,from:i,to:n}),l.set(r,n)}return e.sort((e,r)=>Math.abs(r.to-r.from)-Math.abs(e.to-e.from)),e.slice(0,4)})()}),g&&v>50&&!(a.turnInFlight&&!m)&&console.warn("[vdx-scroll] displaced while pinned — recent timeline:",R5.slice(-30))});return u.observe(r),u.observe(e),()=>{u.disconnect(),e.removeEventListener("scroll",o)}},[i,a]),null}window.__vdxScrollDiag={buf:R5,dump:()=>console.table(R5)};let R6=(0,e_.default)("quote",[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"rib7q0"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"1ymkrd"}]]);function R7(e,r){let s=e;for(;s&&s!==r;){if(s.nodeType===Node.ELEMENT_NODE){let e=s.getAttribute("data-message-idx");if(null!==e)return e}s=s.parentNode}return null}function R8({containerRef:e,onQuote:r}){let[s,n]=(0,$.useState)(null);if((0,$.useEffect)(()=>{function r(){let r=e.current;if(!r)return void n(null);let s=window.getSelection();if(!s||s.isCollapsed||0===s.rangeCount)return void n(null);let i=s.toString();if(!i.trim())return void n(null);let{anchorNode:a,focusNode:o}=s;if(!a||!o||!r.contains(a)||!r.contains(o))return void n(null);let l=R7(a,r),c=R7(o,r);if(null===l||null===c||l!==c)return void n(null);let d=s.getRangeAt(0).getBoundingClientRect();0===d.width&&0===d.height?n(null):n({text:i,rect:{top:d.top,bottom:d.bottom,left:d.left,width:d.width}})}function s(){let e=window.getSelection();e&&!e.isCollapsed&&e.toString().trim()||n(null)}return document.addEventListener("mouseup",r),document.addEventListener("keyup",r),document.addEventListener("touchend",r),document.addEventListener("selectionchange",s),window.addEventListener("scroll",r,!0),window.addEventListener("resize",r),()=>{document.removeEventListener("mouseup",r),document.removeEventListener("keyup",r),document.removeEventListener("touchend",r),document.removeEventListener("selectionchange",s),window.removeEventListener("scroll",r,!0),window.removeEventListener("resize",r)}},[e]),!s||"undefined"==typeof document)return null;let i=s.rect.top-8-30<8?s.rect.bottom+8:s.rect.top-8-30,a=s.rect.left+s.rect.width/2,o=Math.max(8,Math.min(window.innerWidth-8,a));return(0,ee.createPortal)((0,z.jsxs)("button",{type:"button",onMouseDown:e=>{e.preventDefault(),r(s.text),window.getSelection()?.removeAllRanges(),n(null)},style:{position:"fixed",top:i,left:o,transform:"translateX(-50%)",zIndex:50},className:"inline-flex items-center gap-1.5 rounded-md border border-border bg-popover px-3 py-1.5 text-xs font-medium text-popover-foreground shadow-2xl hover:bg-accent",children:[(0,z.jsx)(R6,{className:"h-3 w-3"}),"Quote"]}),document.body)}let R9=(0,e_.default)("search-check",[["path",{d:"m8 11 2 2 4-4",key:"1sed1v"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);function Te(e){let r=Math.round(Number(e));return Number.isFinite(r)?Math.min(ry.REVIEW_LOOP_MAX_ROUNDS,Math.max(1,r)):ry.REVIEW_LOOP_DEFAULT_ROUNDS}let Tt=()=>()=>{},Tr=[{type:"claude-code",displayName:"Claude Code",available:!0},{type:"codex",displayName:"Codex",available:!0}];function Ts({tone:e,children:r}){return(0,z.jsx)("span",{className:(0,eb.cn)("rounded-full border px-1.5 py-px font-mono text-[9.5px] leading-[1.5] font-medium","rec"===e?"border-primary/25 bg-accent text-accent-foreground":"border-amber-500/35 bg-amber-500/10 text-amber-700 dark:text-amber-300"),children:r})}function Tn({selected:e,title:r,meta:s,trailing:n,onSelect:i}){return(0,z.jsxs)("button",{type:"button",role:"radio","aria-checked":e,onClick:i,className:(0,eb.cn)("flex min-w-0 items-start gap-2.5 rounded-lg border px-2.5 py-2 text-left transition-colors",e?"border-primary bg-accent ring-[3px] ring-accent":"bg-card opacity-75 hover:bg-muted hover:opacity-100"),children:[(0,z.jsx)("span",{className:(0,eb.cn)("mt-[3px] grid size-3.5 shrink-0 place-items-center rounded-full border",e?"border-primary bg-primary":"border-input bg-card"),children:e&&(0,z.jsx)("span",{className:"size-[5px] rounded-full bg-primary-foreground"})}),(0,z.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,z.jsxs)("span",{className:"flex min-w-0 items-center gap-2 text-[12.5px] font-medium",children:[(0,z.jsx)("span",{className:"flex shrink-0 flex-wrap items-center gap-2",children:r}),n&&(0,z.jsx)("span",{className:"ml-auto flex min-w-0 items-center gap-1.5 font-mono text-[10.5px] font-normal text-muted-foreground",children:n})]}),s&&(0,z.jsx)("span",{className:"mt-0.5 flex flex-wrap items-center gap-2 font-mono text-[10.5px] text-muted-foreground",children:s})]})]})}function Ti({children:e,note:r}){return(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)("span",{className:"text-[10px] font-semibold tracking-[0.07em] text-muted-foreground/80 uppercase",children:e}),(0,z.jsx)("span",{className:"flex-1"}),r&&(0,z.jsx)("span",{className:"text-[10.5px] text-muted-foreground/80",children:r})]})}function Ta({projectId:e,branch:r,sessionId:s,currentAgentType:n,providers:i,shortcutEnabled:a=!1,onStarted:o}){let l=(0,$.useSyncExternalStore)(Tt,fb,()=>!1),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(""),[f,p]=(0,$.useState)("claude-code"),[m,g]=(0,$.useState)("this_turn"),[x,v]=(0,$.useState)("briefed"),[y,b]=(0,$.useState)(!1),[w,_]=(0,$.useState)(String(ry.REVIEW_LOOP_DEFAULT_ROUNDS)),[S,j]=(0,$.useState)(null),[k,C]=(0,$.useState)(null),[N,E]=(0,$.useState)(!1),[D,R]=(0,$.useState)(null),[T,A]=(0,$.useState)(!1),I=(0,$.useRef)(null),M=(0,$.useRef)(null),F=(0,$.useSyncExternalStore)(Rl,()=>Rc(e,r,s),()=>void 0),P=!1===F,L=s?`${e}\u0000${s}`:null,O=k?.key===L?k:null,B=S?.key===L?S.mode:null,H=O?.candidate??null,U=O?.notice??null,q=null!==O||P,K=c&&null!==L&&!q,V=i?.length?i:Tr;if((0,$.useEffect)(()=>{if(c){var e;let r;p((e=n??null,r=V.filter(e=>e.available),r.find(r=>r.type!==e)?.type??r[0]?.type??"claude-code")),g("this_turn"),v("briefed")}},[c]),(0,$.useEffect)(()=>{if(!c||!s)return;let n=`${e}\u0000${s}`;if(P){M.current=null;return}let i=!1,a=ry.api.getReviewerCandidate(e,s);return M.current={projectId:e,sessionId:s,result:a},a.then(a=>{if(i)return;let o=!!(a?.available&&a.sessionId),l=null!==a||!0===Rc(e,r,s);C({key:n,candidate:a,notice:!o&&l?"The last reviewer is no longer available — a new session will be created.":null})}).catch(()=>{i||C({key:n,candidate:null,notice:"Could not load the last reviewer — a new session will be created."})}),()=>{i=!0}},[c,e,r,s,P]),(0,$.useEffect)(()=>{if(!c){I.current=null;return}if(!s)return;let r=I.current;if(r&&r.projectId===e&&r.sessionId===s)return;A(!1);let n=ry.api.generateReviewIntentBrief(e,s).then(e=>({reached:!0,brief:e})).catch(()=>({reached:!1,brief:null}));I.current={projectId:e,sessionId:s,result:n},n.then(()=>{I.current?.result===n&&A(!0)})},[c,e,s]),(0,$.useEffect)(()=>{if(!s||!a)return;let e=e=>{f_(e)&&e.code===fw&&(e.preventDefault(),d(!0))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[s,a]),!s)return null;let X=e=>{d(e),e||(j(null),C(null))},Y=async()=>{E(!0),R(null);try{let n=H;if("reuse"===Z&&!q&&L){let r=M.current;n=r?.projectId===e&&r?.sessionId===s?await r.result.catch(()=>null):null,C({key:L,candidate:n,notice:null})}if("reuse"===Z&&!(n?.available&&n.sessionId)){L&&C({key:L,candidate:n,notice:"The last reviewer is no longer available — a new session will be created."}),j(L?{key:L,mode:"new"}:null);return}let i="reuse"===Z&&n?.sessionId?{reviewerSessionId:n.sessionId}:{reviewerAgentType:f},a="blind"===x&&"reviewerAgentType"in i,l=I.current,c=!a&&"reviewerAgentType"in i&&l?.projectId===e&&l?.sessionId===s?l:null,d=c&&T?await c.result:null,p=d?.reached?{intentBrief:d.brief??""}:{},g=await ry.api.createWorkflowRun({projectId:e,branch:r,sourceSessionId:s,reviewFocus:u.trim()||void 0,reviewSpan:m,...a?{reviewContextMode:"blind"}:{},...y?{loop:{maxRounds:Te(w)}}:{},...i,...p});y&&!g.loop_id&&gS.toast.info("This machine's worker doesn't support review loops yet — started a single-pass review."),X(!1),h(""),o?.(g)}catch(r){R(r instanceof Error?r.message:String(r)),ry.api.getReviewerCandidate(e,s).then(r=>{let n=!r?.available||!r.sessionId;C({key:`${e}\u0000${s}`,candidate:r,notice:n?"The last reviewer is no longer available — a new session will be created.":null}),n&&j(L?{key:L,mode:"new"}:null)}).catch(()=>void 0)}finally{E(!1)}},G=!!(H?.available&&H.sessionId),J=q?G:!0===F,Z=J?B??"reuse":"new",Q="reuse"===Z,ee=Q?"briefed":x,et=e=>V.find(r=>r.type===e)?.displayName??e??"—",er=N||K&&void 0===F,es=N?{Icon:hv,text:"Setup continues in the background"}:Q?{Icon:hv,text:"Reuses context — no re-distillation"}:"blind"===x?{Icon:hv,text:y?"Blind applies to round 1 — later rounds see the author's replies":"Blind review — no conversation context is sent"}:T?{Icon:lY.Clock,text:"Intent summary ready"}:{Icon:lY.Clock,text:"Intent summary finishes in the background"};return(0,z.jsxs)(t8,{open:c,onOpenChange:X,children:[(0,z.jsx)(t9,{asChild:!0,children:(0,z.jsx)(W.Button,{variant:"ghost",size:"sm",title:`让另一个 agent review 这个 session 的最新成果 (${fj(l,fw)})`,children:(0,z.jsx)(R9,{className:"h-4 w-4"})})}),(0,z.jsxs)(rs,{showCloseButton:!1,className:"bg-card w-[calc(100%-2rem)] min-w-0 gap-0 overflow-hidden p-0 sm:w-full sm:max-w-md",onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&!er&&(e.preventDefault(),Y())},children:[(0,z.jsxs)("div",{className:"flex items-start gap-3 border-b bg-secondary px-4 py-3.5",children:[(0,z.jsx)("span",{className:"grid size-7 shrink-0 place-items-center rounded-lg border border-primary/20 bg-accent text-accent-foreground",children:(0,z.jsx)(R9,{className:"size-[15px]"})}),(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)(ra,{className:"text-[14.5px] font-semibold tracking-tight",children:"Start Review"}),(0,z.jsx)(ro,{className:"mt-0.5 max-w-[40ch] text-[11.5px] leading-snug",children:"Another agent reviews this session’s latest work; you confirm the feedback before it returns here."})]}),(0,z.jsxs)(rt,{className:"ml-auto grid size-6 shrink-0 place-items-center rounded-md border border-transparent text-muted-foreground/70 transition-colors hover:border-border hover:bg-muted hover:text-foreground",children:[(0,z.jsx)(t7,{className:"size-3.5"}),(0,z.jsx)("span",{className:"sr-only",children:"Close"})]})]}),(0,z.jsxs)("div",{className:"min-w-0 flex flex-col gap-3.5 px-4 pt-3.5 pb-1",children:[U&&(0,z.jsxs)("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-2.5 py-2 text-[11.5px] text-amber-700 dark:text-amber-300",children:[(0,z.jsx)(s7,{className:"mt-px size-3.5 shrink-0"}),(0,z.jsx)("span",{children:U})]}),(0,z.jsxs)("div",{className:"min-w-0 flex flex-col gap-1.5",children:[(0,z.jsx)(Ti,{note:K?"Checking last reviewer…":J?"Last reviewer still available":void 0,children:"Reviewer"}),(0,z.jsxs)("div",{className:"grid gap-2",role:"radiogroup","aria-label":"Reviewer",children:[J&&(0,z.jsx)(Tn,{selected:Q,onSelect:()=>L&&j({key:L,mode:"reuse"}),title:"Continue last reviewer",trailing:q&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"shrink-0",children:et(H?.agentType)}),"number"==typeof H?.lastActiveAt&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"shrink-0 text-muted-foreground/60",children:"·"}),(0,z.jsx)("span",{className:"shrink-0",children:function(e){let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return"just now";let s=Math.round(r/60);if(s<60)return`${s}m ago`;let n=Math.round(s/60);return n<24?`${n}h ago`:`${Math.round(n/24)}d ago`}(H.lastActiveAt)})]})]}),meta:q?(0,z.jsx)("span",{className:"min-w-0 truncate",children:H?.title??"Review session"}):(0,z.jsx)("span",{className:"text-muted-foreground/60",children:"Loading details…"})}),(0,z.jsx)(Tn,{selected:!Q,onSelect:()=>L&&j({key:L,mode:"new"}),title:(0,z.jsxs)(z.Fragment,{children:["New reviewer session",U&&(0,z.jsx)(Ts,{tone:"warn",children:"Only option"})]}),meta:J?"Starts fresh, without the last context":"Independent second opinion, from zero context"})]}),(0,z.jsxs)("div",{className:"mt-0.5 min-w-0 flex flex-col gap-2",children:[(0,z.jsxs)("div",{className:"min-w-0 flex items-center gap-2.5",children:[(0,z.jsx)("span",{className:"w-[92px] shrink-0 text-[11.5px] text-muted-foreground",children:"Agent"}),Q?(0,z.jsxs)("span",{className:"flex h-8 flex-1 items-center gap-2 rounded-md border bg-secondary px-2.5 text-xs text-muted-foreground",children:[(0,z.jsx)("span",{className:"truncate",children:q?et(H?.agentType):"Loading…"}),(0,z.jsx)("span",{className:"flex-1"}),(0,z.jsx)("span",{className:"font-mono text-[10px] text-muted-foreground/70",children:"same as last reviewer"}),(0,z.jsx)(gv,{className:"size-3 shrink-0"})]}):(0,z.jsxs)(fd,{value:f,onValueChange:e=>p(e),children:[(0,z.jsxs)(fh,{size:"sm",className:"min-w-0 flex-1 text-xs",children:[(0,z.jsx)(fu,{}),(0,z.jsx)("span",{className:"ml-auto font-mono text-[10px] text-muted-foreground/70",children:f===n?"same as current agent":"differs from current agent"})]}),(0,z.jsx)(ff,{children:V.map(e=>(0,z.jsxs)(fp,{value:e.type,disabled:!e.available,children:[e.displayName,e.type===n?" (current agent)":""]},e.type))})]})]}),(0,z.jsxs)("div",{className:"min-w-0 flex items-center gap-2.5",children:[(0,z.jsx)("span",{className:"w-[92px] shrink-0 text-[11.5px] text-muted-foreground",children:"Scope"}),(0,z.jsx)("div",{className:"min-w-0 flex h-8 flex-1 items-center gap-0.5 rounded-lg border bg-secondary p-0.5",children:[["this_turn","This turn only"],["session_start","Whole session"]].map(([e,r])=>(0,z.jsx)("button",{type:"button","aria-pressed":m===e,onClick:()=>g(e),className:(0,eb.cn)("h-full flex-1 rounded-md px-2 text-[11.5px] whitespace-nowrap transition-colors",m===e?"border bg-card font-medium text-foreground shadow-sm":"border border-transparent text-muted-foreground hover:text-foreground"),children:r},e))})]}),(0,z.jsxs)("div",{className:"min-w-0 flex items-center gap-2.5",children:[(0,z.jsx)("span",{className:"w-[92px] shrink-0 text-[11.5px] text-muted-foreground",children:"Context"}),(0,z.jsx)("div",{className:"min-w-0 flex h-8 flex-1 items-center gap-0.5 rounded-lg border bg-secondary p-0.5",children:[["briefed","With context"],["blind","Blind"]].map(([e,r])=>(0,z.jsx)("button",{type:"button",disabled:Q,"aria-pressed":ee===e,onClick:()=>v(e),className:(0,eb.cn)("h-full min-w-0 flex-1 rounded-md px-2 text-[11.5px] whitespace-nowrap transition-colors disabled:cursor-not-allowed",ee===e?"border bg-card font-medium text-foreground shadow-sm disabled:text-muted-foreground":"border border-transparent text-muted-foreground hover:text-foreground disabled:opacity-45"),children:r},e))})]}),(0,z.jsxs)("div",{className:"min-w-0 flex items-center gap-2.5",children:[(0,z.jsx)("span",{className:"w-[92px] shrink-0 text-[11.5px] text-muted-foreground",children:"Rounds"}),(0,z.jsx)("div",{className:"min-w-0 flex h-8 flex-1 items-center gap-0.5 rounded-lg border bg-secondary p-0.5",children:[[!1,"Single pass"],[!0,"Loop"]].map(([e,r])=>(0,z.jsx)("button",{type:"button","aria-pressed":y===e,onClick:()=>b(e),className:(0,eb.cn)("h-full min-w-0 flex-1 rounded-md px-2 text-[11.5px] whitespace-nowrap transition-colors",y===e?"border bg-card font-medium text-foreground shadow-sm":"border border-transparent text-muted-foreground hover:text-foreground"),children:r},r))}),(0,z.jsxs)("label",{className:(0,eb.cn)("flex shrink-0 items-center gap-1.5 text-[11.5px] text-muted-foreground",!y&&"opacity-45"),children:["up to",(0,z.jsx)("input",{type:"number",min:1,max:ry.REVIEW_LOOP_MAX_ROUNDS,"aria-label":"Maximum review rounds",disabled:!y,value:w,onChange:e=>_(e.target.value),onBlur:()=>_(String(Te(w))),className:"h-7 w-11 rounded-md border bg-card px-1.5 text-center text-[11.5px] text-foreground outline-none disabled:cursor-not-allowed"})]})]})]})]}),(0,z.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,z.jsx)(Ti,{note:"Optional",children:"Review focus"}),(0,z.jsx)("div",{className:"focus-within:border-ring focus-within:ring-ring/40 flex h-[34px] items-center overflow-hidden rounded-lg border bg-card px-3 transition-[color,box-shadow] focus-within:ring-[3px]",children:(0,z.jsx)("input",{className:"min-w-0 flex-1 bg-transparent text-[12.5px] outline-none placeholder:text-muted-foreground/70",placeholder:"What to focus on, e.g. is the lock granularity too coarse…",value:u,onChange:e=>h(e.target.value)})})]}),D&&(0,z.jsxs)("div",{className:"border-destructive/30 bg-destructive/10 text-destructive flex items-start gap-2 rounded-lg border px-2.5 py-2 text-[11.5px]",children:[(0,z.jsx)(s7,{className:"mt-px size-3.5 shrink-0"}),(0,z.jsx)("span",{className:"min-w-0",children:D})]})]}),(0,z.jsxs)("div",{className:"mt-2.5 min-w-0 flex w-full items-center gap-2.5 overflow-hidden border-t bg-secondary px-4 py-2.5",children:[(0,z.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden text-[11px] text-muted-foreground",children:[(0,z.jsx)(es.Icon,{className:"size-3 shrink-0 text-muted-foreground/70"}),(0,z.jsx)("span",{className:"truncate",children:es.text})]}),(0,z.jsx)(rt,{asChild:!0,children:(0,z.jsx)(W.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",children:"Cancel"})}),(0,z.jsx)(W.Button,{size:"sm",className:"h-7 w-28 gap-1.5 text-xs","aria-label":"Start",onClick:Y,disabled:er,children:N?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(sC,{className:"size-3 animate-spin"}),"Starting…"]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(sT,{className:"size-3"}),"Start",(0,z.jsx)("kbd",{className:"rounded border border-primary-foreground/30 bg-primary-foreground/15 px-1 font-mono text-[10px] leading-[1.4] text-primary-foreground/90",title:l?"Command+Enter":"Ctrl+Enter",children:l?"⌘⏎":"Ctrl⏎"})]})})]})]})]})}function To({phase:e="distilling",children:r}){return(0,z.jsxs)("div",{className:"text-center py-16",children:[(0,z.jsx)(Rr,{className:"h-6 w-6 mx-auto mb-4"}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Preparing review…"}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"starting"===e?"The reviewer is starting. This view switches to the review conversation as soon as it is ready.":"Summarizing the source conversation and briefing the reviewer. The review will start here automatically — you can leave this window in the meantime."}),r]})}function Tl({error:e,title:r="Review setup failed",children:s}){return(0,z.jsxs)("div",{className:"text-center py-16",children:[(0,z.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-destructive/10 flex items-center justify-center mb-4",children:(0,z.jsx)(s_,{className:"h-6 w-6 text-destructive/70"})}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:r}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:e??"The reviewer could not be started."}),s]})}function Tc({status:e,children:r}){let s="completed"===e?sZ:gJ;return(0,z.jsxs)("div",{className:"text-center py-16",children:[(0,z.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-muted flex items-center justify-center mb-4",children:(0,z.jsx)(s,{className:"h-6 w-6 text-muted-foreground"})}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"completed"===e?"Review completed":"cancelled"===e?"Review cancelled":"Review no longer available"}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"completed"===e?"The reviewer finished before this view could open it.":"cancelled"===e?"The review was ended before the reviewer started.":"The server no longer has this review run."}),r]})}let Td=[137,80,78,71,13,10,26,10],Tu=[71,73,70,56],Th=[82,73,70,70],Tf=[87,69,66,80];function Tp(e,r,s=0){if(e.length<s+r.length)return!1;for(let n=0;n<r.length;n++)if(e[s+n]!==r[n])return!1;return!0}function Tm({uploads:e,workspaceKey:r,apiRef:s}){let n=DY(),i=n.files,{track:a}=e,{clear:o,detach:l,restore:c}=n;(0,$.useEffect)(()=>(s.current={detach:l,restore:c},()=>{s.current=null}),[s,l,c]);let d=(0,$.useRef)(r);return((0,$.useEffect)(()=>{d.current!==r&&(d.current=r,o())},[r,o]),(0,$.useEffect)(()=>{a(i)},[i,a]),0===i.length)?null:(0,z.jsx)(D1,{className:"pt-3 pb-0 pl-12 pr-2",children:(0,z.jsx)(DJ,{className:"p-0",children:r=>(0,z.jsx)(DG,{data:r,status:e.statusOf(r.id),onRetry:()=>e.retry(r)})})})}let Tg=(0,$.createContext)(null);function Tx(){let e=(0,$.useContext)(Tg);if(!e)throw Error("useAgentConversation must be used within AgentConversationContext");return e}let Tv=/\[📎 paste #(\d+) \([^)]+\)\]/g;function Ty(e){return"system"===e.type||"error"===e.type}function Tb(e,r){return`[📎 paste #${e} (${function(e){if(e<1024)return`${e}B`;let r=e/1024;return r<10?`${r.toFixed(1)}KB`:`${Math.round(r)}KB`}(r)})]`}let Tw=(0,$.forwardRef)(function({projectId:e,branch:r,sessionId:s,navPending:n,setSessionUrlParam:i,project:a,onAgentModeChange:o,onTaskCompleted:l,onSessionStarted:c,onSessionTitleUpdated:d,onSessionSelected:u,onStatusChange:h,onNewConversation:f,onActiveSessionChange:p,onOpenSchedule:m,preparingReviews:g,onReviewStarted:x,onViewPreparingReview:v},y){var b;let w,_,S,j,[k,C]=function(e,r){let s=e&&r?`vibedeckx:agent-draft:${e}:${r}`:null,[n,i]=(0,$.useState)(()=>RZ(s)),[a,o]=(0,$.useState)(s);return a!==s&&(o(s),i(RZ(s))),[n,(0,$.useCallback)(e=>{i(e);if(s)try{e?window.localStorage.setItem(s,e):window.localStorage.removeItem(s)}catch{}},[s])]}(e,r),[N,E]=(0,$.useState)([]),[D,R]=(0,$.useState)(1),[T,A]=(0,$.useState)("edit"),[I,M]=(0,$.useState)(!1),[F,P]=(0,$.useState)(!1),[L,O]=(0,$.useState)(!1),B=(0,$.useRef)(null),[H,U]=(0,$.useState)("claude-code"),[q,K]=(0,$.useState)([]),[V,X]=(0,$.useState)(null),[Y,G]=(0,$.useState)(0),[J,Z]=(0,$.useState)(null),[Q,ee]=(0,$.useState)(null),et=(0,$.useRef)(null),er=(0,$.useCallback)(e=>{if("ArrowUp"!==e.key&&"ArrowDown"!==e.key||!e.shiftKey||e.ctrlKey||e.metaKey||e.altKey)return;let r=et.current;if(!r)return;let s=RQ(r);if(!s)return;let n=s.getBoundingClientRect(),i=s.scrollTop,a="ArrowUp"===e.key,o=null,l=a?-1/0:1/0;r.querySelectorAll("[data-user-msg-idx]").forEach(e=>{let r=e.getBoundingClientRect().top-n.top+s.scrollTop;a?r<i-12&&r>l&&(l=r,o=e):r>i+12&&r<l&&(l=r,o=e)}),o&&(e.preventDefault(),o.scrollIntoView({block:"start",behavior:"smooth"}))},[et]),es=(0,$.useRef)(null),en=function(e,r,s){let n=r&&s?`vibedeckx:agent-input-history:${r}:${s}`:null,i=(0,$.useRef)(RG(n)),a=(0,$.useRef)(-1),o=(0,$.useRef)(""),[l,c]=(0,$.useState)(n);return l!==n&&(c(n),i.current=RG(n),a.current=-1,o.current=""),{push:(0,$.useCallback)(e=>{let r=e.trim();if(!r)return;let s=i.current;if(s.length>0&&s[s.length-1]===r){a.current=-1;return}s.push(r),s.length>50&&s.shift(),a.current=-1;if(n)try{0===s.length?window.localStorage.removeItem(n):window.localStorage.setItem(n,JSON.stringify(s))}catch{}},[n]),handleKeyDown:(0,$.useCallback)(r=>{let s=r.currentTarget,n=i.current;if(0!==n.length)if("ArrowUp"===r.key){if(0!==s.selectionStart||0!==s.selectionEnd)return;if(r.preventDefault(),-1===a.current)o.current=s.value,a.current=n.length-1;else{if(!(a.current>0))return;a.current--}e(n[a.current])}else if("ArrowDown"===r.key){if(-1===a.current)return;let i=s.value.length;if(s.selectionStart!==i||s.selectionEnd!==i)return;r.preventDefault(),a.current<n.length-1?(a.current++,e(n[a.current])):(a.current=-1,e(o.current))}else -1!==a.current&&(a.current=-1)},[e])}}(C,e,r),{remotes:ei}=g_(),ea=[];for(let e of(a?.path&&ea.push({id:"local",label:"Local",icon:hy}),ei))ea.push({id:e.remote_server_id,label:e.server_name,icon:sy(e)});let eo=a?.agent_mode??"local",el=ea.find(e=>e.id===eo)?.label??("local"===eo?"Local":eo),ec=(0,$.useRef)(null);ec.current=Nv(e,r,eo,s);let ed=(0,$.useCallback)(e=>{let r=ec.current;return null!==r&&Ny(e,r)},[]),eu=(0,$.useCallback)(e=>{let r=ec.current;return null!==r&&e.projectId===r.projectId&&e.branch===r.branch},[]),{session:eh,messages:ef,status:ep,isConnected:em,isInitialized:eg,isLoading:ex,isCachePreview:ev,error:ey,remoteStatus:ew,workflowRunUpdate:e_,backgroundTasks:eS,streamEpoch:ej,messageEntryIndices:ek,hasEarlierHistory:eC,isLoadingEarlier:eN,loadEarlierHistory:eE,sendMessage:eD,sendEnsuredMessage:eR,discardEnsuredSessionIfEmpty:eT,startConversation:eA,prepareConversation:eI,activateConversation:eM,cancelPreparedConversation:eF,uploadPaste:eP,uploadAttachment:eL,stopSession:eO,switchAgentType:eB,setModel:ez,startNewConversation:e$,ensureSession:eW,switchMode:eH,acceptPlan:eU,residentLimitPrompt:eq}=function(e,r,s,n,i){let a=i?.sessionId??null,o=i?.suspended??!1,[l,c]=(0,$.useState)(null),[d,u]=(0,$.useState)([]),[h,f]=(0,$.useState)("stopped"),[p,m]=(0,$.useState)(!1),[g,x]=(0,$.useState)(!1),[v,y]=(0,$.useState)(!1),[b,w]=(0,$.useState)(!1),[_,S]=(0,$.useState)(null),[j,k]=(0,$.useState)(null),[C,N]=(0,$.useState)(null),[E,D]=(0,$.useState)({tasks:[],turnParked:!1,parkDeadlineAt:null,canStopTasks:!1}),[R,T]=(0,$.useState)(0),A=(0,$.useRef)(null),I=(0,$.useRef)(null),M=(0,$.useRef)(null),F=(0,$.useRef)(new WeakSet),P=(0,$.useRef)(()=>{}),L=(0,$.useRef)(()=>{}),O=(0,$.useRef)(null),B=(0,$.useRef)(0),z=(0,$.useRef)({sessionId:null,entries:{},status:"stopped"}),W=(0,$.useRef)(null),[H,U]=(0,$.useState)(!1),[q,K]=(0,$.useState)(!1),V=(0,$.useRef)(null),X=(0,$.useRef)(!1),Y=(0,$.useRef)(!0),G=(0,$.useRef)(null),J=(0,$.useRef)(null),Z=(0,$.useRef)(0),Q=(0,$.useRef)(!1),ee=(0,$.useRef)(null),et=(0,$.useRef)(0),er=(0,$.useRef)(!1),es=(0,$.useRef)(!1),en=(0,$.useRef)(!1),ei=(0,$.useRef)(o),ea=(0,$.useRef)(Promise.resolve()),eo=(0,$.useRef)(i?.onTaskCompleted),el=(0,$.useRef)(i?.onSessionStarted),ec=(0,$.useRef)(i?.onTitleUpdated),ed=(0,$.useRef)(e),eu=(0,$.useRef)(r),eh=(0,$.useRef)(a),ef=(0,$.useRef)(Nv(e,r,s,a));ef.current=Nv(e,r,s,a),(0,$.useEffect)(()=>{eo.current=i?.onTaskCompleted,el.current=i?.onSessionStarted,ec.current=i?.onTitleUpdated,ed.current=e,eu.current=r,eh.current=a,V.current=l,ei.current=o}),(0,sx.useGlobalEventStream)(e=>{if("notification:created"!==e.type)return;let r=e.notification,s=r?.session_id;if(!s||"session_result_ready"!==r.kind&&"session_failed"!==r.kind)return;let n=[...NA.entries()].filter(([,e])=>e.session.id===s);0!==n.length&&N$(s).then(e=>{for(let[r,s]of n)NP(r,{session:e.session??{...s.session,status:e.status},history:e})}).catch(e=>console.warn(`[AgentSession] completion prefetch failed for ${s}:`,e))});let ep=(0,$.useCallback)(()=>{ee.current&&(clearTimeout(ee.current),ee.current=null)},[]),em=(0,$.useCallback)(e=>{ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{ee.current=null,e.readyState===WebSocket.OPEN&&(console.warn(`[AgentSession] No frames for 95000ms — assuming dead socket, forcing reconnect`),L.current(e))},95e3)},[]),eg=(0,$.useCallback)((e,r=!1)=>{M.current=e,A.current&&I.current!==e&&(console.log(`[AgentSession] Retiring WS for ${I.current}, claiming ${e}`),A.current.close(1e3,"session-switch"),A.current=null,I.current=null),Promise.race([(0,ry.getFreshToken)(r?{skipCache:!0}:void 0),new Promise(e=>setTimeout(e,5e3))]).catch(()=>void 0).then(()=>{M.current!==e?console.log(`[AgentSession] Dropping stale connect for ${e} (now ${M.current})`):P.current(e)})},[]),ex=(0,$.useCallback)(e=>{let r=()=>{let e=ed.current;if(!e)return;let r=eu.current;NA.delete(NM(e,r,eh.current));let s=I.current;s&&NA.delete(NM(e,r,s)),NA.delete(NM(e,r,null))},s=()=>{let r=ed.current,s=V.current;if(!r||!s||s.id!==e)return;let n=s.status===z.current.status?s:{...s,status:z.current.status};V.current=n;let i=W.current;if(!i)return;let a=NU(z.current),o=a.at(-1)?.entryIndex??null,l=[...a].reverse().find(e=>"turn_end"===e.message.type)?.entryIndex??i.lastTurnEndEntryIndex,c={...i,status:z.current.status,latestEntryIndex:o,lastTurnEndEntryIndex:l,entries:a};W.current=c,NL(r,eu.current,eh.current,n,c)};if(A.current&&I.current!==e&&(console.log(`[AgentSession] Closing stale WS for ${I.current}, switching to ${e}`),A.current.close(1e3,"session-switch"),A.current=null,I.current=null),A.current?.readyState===WebSocket.OPEN||A.current?.readyState===WebSocket.CONNECTING)return;z.current.sessionId!==e&&(z.current={sessionId:e,entries:{},status:"running"}),X.current=!1,Q.current=!0;let n=W.current,i=new URLSearchParams;n?.lastTurnEndEntryIndex!==null&&n?.lastTurnEndEntryIndex!==void 0&&(i.set("after",String(n.lastTurnEndEntryIndex)),i.set("epoch",String(n.historyEpoch)));let a=i.size>0?`?${i}`:"",o=(0,ry.getWebSocketUrl)(`/api/agent-sessions/${e}/stream${a}`);console.log("[AgentSession] Connecting to WebSocket:",o);let l=new WebSocket(o);A.current=l,I.current=e,l.onopen=()=>{A.current===l&&(console.log("[AgentSession] WebSocket connected"),m(!0),S(null),k(null),G.current=Date.now(),em(l),J.current&&clearTimeout(J.current),J.current=setTimeout(()=>{A.current===l&&(console.log("[AgentSession] Connection stable, resetting backoff counter"),B.current=0,Z.current=0)},5e3))},l.onmessage=n=>{if(A.current!==l||z.current.sessionId!==e){F.current.has(l)||(F.current.add(l),console.warn(`[AgentSession] Dropping frames from retired socket for ${e}`+(z.current.sessionId===e?"":`; buffer holds ${z.current.sessionId}`)));return}em(l);try{let a=JSON.parse(n.data);if("keepalive"in a)return;if("HistorySync"in a){(a.HistorySync.reset||W.current&&W.current.historyEpoch!==a.HistorySync.historyEpoch)&&(z.current={sessionId:e,entries:{},status:z.current.status},W.current=W.current?{...W.current,historyEpoch:a.HistorySync.historyEpoch,latestEntryIndex:null,lastTurnEndEntryIndex:null,entries:[],previousCursor:null,hasMore:!1}:null,U(!1));return}if("JsonPatch"in a){var i;let e=a.JsonPatch;if(i=z.current,z.current=C8(i,r=>{for(let s of e){let{op:e,path:n,value:i}=s;if("/entries"===n&&"replace"===e&&i?.type==="ENTRY"&&i.content?.type==="system"&&i.content?.content==="__CLEAR_ALL__"){console.log("[JsonPatch] Received clearAll signal - clearing all entries"),r.entries={};continue}if(n.startsWith("/entries/")){let s=parseInt(n.replace("/entries/",""),10);if(isNaN(s)){console.warn(`[JsonPatch] Invalid index in path: ${n}`);continue}if(i?.type!=="ENTRY"){console.warn("[JsonPatch] Expected ENTRY type for entries path");continue}switch(e){case"add":r.entries[s]=i.content;break;case"replace":void 0!==r.entries[s]?r.entries[s]=i.content:console.warn(`[JsonPatch] Replace index out of bounds: ${s}`);break;case"remove":delete r.entries[s]}}else"/status"===n&&i?.type==="STATUS"&&(console.log("[AgentSession] /status patch →",i.content),r.status=i.content)}}),Q.current)console.log("[AgentSession] /status patch applied during replay (no setStatus), container.status =",z.current.status);else{let e=NU(z.current).map(e=>e.message);u(e),console.log("[AgentSession] setStatus(live) →",z.current.status),f(z.current.status),s()}return}if("Ready"in a){console.log(`[AgentSession] Received Ready signal for ${e} - history complete, status=${z.current.status}, tail=${NU(z.current).at(-1)?.entryIndex??"-"}`),Q.current=!1,u(NU(z.current).map(e=>e.message)),f(z.current.status),x(!0),s(),T(e=>e+1);return}if("finished"in a){console.log("[AgentSession] Received finished signal, preserving cached snapshot"),X.current=!0,s(),l.close(1e3,"finished");return}if("taskCompleted"in a){if(Q.current)return;let{duration_ms:e,cost_usd:r,input_tokens:s,output_tokens:n}=a.taskCompleted,i=[];if(null!=e){let r=(e/1e3).toFixed(1);i.push(`${r}s`)}if(null!=r)i.push(`$${r.toFixed(4)}`);else if(null!=s||null!=n){let e=(s??0)+(n??0),r=e>1e3?`${(e/1e3).toFixed(1)}K`:String(e);i.push(`${r} tokens`)}gS.toast.success("Task completed",{description:i.length>0?i.join(" · "):void 0}),eo.current?.();return}if("remoteStatus"in a)return void k(a.remoteStatus);if("processAlive"in a){let r=V.current;if(r?.id===e&&r.processAlive!==a.processAlive.alive){let e={...r,processAlive:a.processAlive.alive};V.current=e,c(e)}return}if("titleUpdated"in a)return void ec.current?.(a.titleUpdated.title,e);if("backgroundTasks"in a){let{tasks:e,turnParked:r,parkDeadlineAt:s,canStopTasks:n}=a.backgroundTasks;D({tasks:e,turnParked:r,parkDeadlineAt:s??null,canStopTasks:n??!1});return}if("workflowRunUpdated"in a&&N(a.workflowRunUpdated),"error"in a){console.error("[AgentSession] Server error:",a.error),S(a.error),"Session not found"===a.error&&(console.log("[AgentSession] Session invalid, invalidating cache, will create new session"),r(),X.current=!0,c(null),f("stopped"),x(!1),Y.current=!0);return}}catch(e){console.error("[AgentSession] Failed to parse message:",e)}},l.onclose=e=>{let s,n;if(A.current!==l)return;console.log("[AgentSession] WebSocket disconnected",e.code,e.reason),A.current=null,m(!1),ep(),J.current&&(clearTimeout(J.current),J.current=null);let i=G.current?Date.now()-G.current:0;if(G.current=null,i>0&&i<5e3){if(Z.current++,console.log(`[AgentSession] Short-lived connection (${i}ms), count: ${Z.current}, backoff attempt: ${B.current}`),Z.current>=3){if(console.log("[AgentSession] Multiple short-lived connections detected, session likely invalid - will recreate"),er.current){console.log("[AgentSession] Skipping auto-restart: last session creation failed"),S("Unable to connect to remote server. Please check the server configuration.");return}r(),c(null),S(null),B.current=0,Z.current=0,Y.current=!0;return}}else i>=5e3&&(Z.current=0);if(X.current||1e3===e.code)return;if(B.current>=10){console.log("[AgentSession] Max reconnect attempts reached"),S("Unable to connect to server. Please check if the backend is running.");return}let a=(n=(s=Math.min(3e4,1e3*Math.pow(2,B.current)))*Math.random()*.25,s+n);console.log(`[AgentSession] Reconnecting in ${Math.round(a)}ms (attempt ${B.current+1})`),B.current++,O.current=setTimeout(()=>{let e=I.current;e&&!X.current&&eg(e,!0)},a)},l.onerror=e=>{A.current===l&&console.error("[AgentSession] WebSocket error:",e)}},[eg,em,ep]);(0,$.useEffect)(()=>{P.current=ex},[ex]),(0,$.useEffect)(()=>(L.current=e=>{if(A.current!==e)return;let r=I.current;A.current=null,m(!1),J.current&&(clearTimeout(J.current),J.current=null),G.current=null;try{e.close(4e3,"silence watchdog")}catch{}r&&!X.current&&eg(r,!0)},()=>{L.current=()=>{}}),[eg]);let ev=(0,$.useCallback)(async i=>{if(!e)return null;if(es.current)return console.log("[AgentSession] startSession already in progress, skipping"),null;es.current=!0;let o=et.current;S(null),k(null),en.current||x(!1),er.current=!1;let l=NF(NM(e,r,a));y(!0);let d=()=>{console.log(`[AgentSession] No existing session for ${e}/${r??"<null>"} — placeholder`),c(null),f("stopped"),u([]),z.current={sessionId:null,entries:{},status:"stopped"},W.current=null,U(!1),x(!0)};try{let h,p,m;if(!a){let n=Np(e,r,s),i=Nr(n);if(i?.content){let e=await eV.current?.(i,o);if(e?.adopted)return e.session;if(et.current!==o)return null;if(Nm(n))return d(),null}}if(console.log(`[AgentSession] Starting REST call: projectId=${e}, branch=${r}, sessionId=${a??"latest"}, agentType=${n}, generation=${o}`),a){let e=l?await NW(a):null;h=(m=l&&e&&"stopped"===e.status&&e.historyEpoch===l.history.historyEpoch&&e.lastTurnEndEntryIndex===l.history.lastTurnEndEntryIndex?{...l.history,status:e.status,latestEntryIndex:e.latestEntryIndex}:await N$(a)).session??l?.session??null,p=m.entries.map(e=>e.message)}else if(l){let s=await NW(l.session.id).catch(()=>null);if(s&&"stopped"===s.status&&s.historyEpoch===l.history.historyEpoch&&s.lastTurnEndEntryIndex===l.history.lastTurnEndEntryIndex)m={...l.history,status:s.status,latestEntryIndex:s.latestEntryIndex},h={...l.session,status:s.status},p=m.entries.map(e=>e.message);else{let s=await Nw(e,r,i,n);h=s.session,p=s.messages,m=s.historyWindow}}else{let s=await Nw(e,r,i,n);h=s.session,p=s.messages,m=s.historyWindow}if(et.current!==o)return console.log("[AgentSession] Discarding stale session response (generation mismatch)"),null;if(!h)return d(),null;console.log(`[AgentSession] REST response: sessionId=${h.id}, msgCount=${p?.length??0}, status=${h.status}, explicitSessionIdRequested=${a??"<null>"}, window=[${m?.entries[0]?.entryIndex??"-"}..${m?.latestEntryIndex??"-"}], streamTail=${NU(z.current).at(-1)?.entryIndex??"-"}`);let g=m?{...m,status:h.status,session:h}:{historyEpoch:0,latestEntryIndex:p.length>0?p.length-1:null,lastTurnEndEntryIndex:p.reduce((e,r,s)=>"turn_end"===r.type?s:e,null),entries:p.map((e,r)=>({entryIndex:r,message:e})),previousCursor:null,hasMore:!1,status:h.status,session:h},v=z.current.sessionId===h.id&&W.current?.historyEpoch===g.historyEpoch,y=function(e,r,s){if(!s)return e;let n=NU(r),i=n.at(-1)?.entryIndex??null;if(null===i||null!==e.latestEntryIndex&&e.latestEntryIndex>=i)return e;let a=new Map;for(let r of e.entries)a.set(r.entryIndex,r.message);for(let e of n)a.set(e.entryIndex,e.message);let o=[...a].sort((e,r)=>e[0]-r[0]).map(([e,r])=>({entryIndex:e,message:r}));return{...e,entries:o,latestEntryIndex:o.at(-1)?.entryIndex??null,lastTurnEndEntryIndex:[...o].reverse().find(e=>"turn_end"===e.message.type)?.entryIndex??null}}(g,z.current,v);return y!==g&&console.warn(`[AgentSession] Stale history window for ${h.id}: window ends at ${g.latestEntryIndex}, stream already at ${y.latestEntryIndex} — keeping live tail`),NL(e,r,a,h,y),c(h),V.current=h,W.current=y,U(y.hasMore),f(h.status),y.entries.length>0&&(u(y.entries.map(e=>e.message)),z.current={sessionId:h.id,entries:NH(y.entries),status:h.status}),x(!0),eg(h.id),el.current?.(h),h}catch(e){if(console.error("[AgentSession] startSession error:",e),et.current!==o)return console.log("[AgentSession] Discarding error (generation mismatch)"),null;return S(e instanceof Error?e.message:"Failed to start session"),er.current=!0,null}finally{es.current=!1,et.current===o&&(y(!1),w(!1),en.current=!1)}},[e,r,s,n,a,eg]),ey=(0,$.useCallback)(async(s,n,i)=>{let o=n||l?.id;if(!o)return void console.warn("[AgentSession] sendMessage: no session ID available (sessionId param:",n,", session?.id:",l?.id,")");if(("string"!=typeof s||s.trim())&&(!Array.isArray(s)||0!==s.length)){console.log(`[AgentSession] sendMessage: targetSessionId=${o}, source=${n?"explicit":"state"}`);try{let e="string"==typeof s?s.trim():s;await N_(o,e,i)}catch(n){let s=n instanceof Error?n.message:"Failed to send message";console.error("[AgentSession] Failed to send message:",s),s.includes("[404]")&&(e&&(NA.delete(NM(e,r,a)),l?.id&&NA.delete(NM(e,r,l.id))),c(null),f("stopped"),x(!1),Y.current=!0),S(s),gS.toast.error("Failed to send message",{description:s})}}},[l?.id,e,r,a]),eb=(0,$.useCallback)(async(e,r)=>{try{let s="string"==typeof r?r.trim():r;return await N_(e.session.id,s),!0}catch(n){let r=n instanceof Error?n.message:"Failed to send message";console.error(`[AgentSession] Failed first-send for ${e.session.id}:`,r);let s=ef.current;if(!s||!Ny(e.origin,s))return!1;return r.includes("[404]")&&(NO(e.origin.projectId,e.origin.branch,e.origin.explicitSessionId,e.session.id),V.current?.id===e.session.id&&(c(null),V.current=null,W.current=null,f("stopped"),x(!1),Y.current=!0)),S(r),gS.toast.error("Failed to send message",{description:r}),!1}},[]),ew=(0,$.useCallback)(async e=>{let r;try{r=await NS(e.session.id)}catch(r){return console.error(`[AgentSession] Failed to discard empty session ${e.session.id}:`,r),!1}if(!r)return!1;NO(e.origin.projectId,e.origin.branch,e.origin.explicitSessionId,e.session.id);let s=Np(e.origin.projectId,e.origin.branch,e.origin.agentMode);eP.current.get(s)===e.session.id&&(eP.current.delete(s),Ng(s));let n=ef.current;return n&&Ny(e.origin,n)&&V.current?.id===e.session.id&&(I.current===e.session.id&&(A.current?.close(1e3,"discard-empty-session"),A.current=null,I.current=null),M.current=null,c(null),V.current=null,W.current=null,f("stopped"),x(!0),u([]),z.current={sessionId:null,entries:{},status:"stopped"}),!0},[]),e_=(0,$.useCallback)(async(e,r)=>{let s=r||l?.id;if(!s)throw Error("No session id available for paste upload");return Nj(s,e)},[l?.id]),eS=(0,$.useCallback)(async(e,r,s)=>{let n=r||l?.id;if(!n)throw Error("No session id available for attachment upload");return Nk(n,e,s)},[l?.id]),ej=(0,$.useCallback)(async()=>{if(l?.id)try{await ND(l.id)}catch(e){e instanceof Error&&e.message,console.error("[AgentSession] Failed to stop session:",e),gS.toast.error("Failed to stop session")}},[l?.id]),ek=(0,$.useCallback)(async s=>{if(l?.id){e&&(NA.delete(NM(e,r,a)),NA.delete(NM(e,r,l.id))),y(!0),S(null);try{await NC(l.id,s),s&&c(e=>e?{...e,agentType:s}:null)}catch(e){S(e instanceof Error?e.message:"Failed to restart session"),console.error("[AgentSession] Failed to restart session:",e)}finally{y(!1)}}},[l?.id,e,r,a]),eC=(0,$.useCallback)(async s=>{if(!l?.id)return"No active session";S(null);try{return await NN(l.id,s),c(n=>{if(!n)return n;let i={...n,agentType:s,model:null};return e&&NB(e,r,a,i),i}),null}catch(r){let e=r instanceof Error?r.message:"Failed to switch agent";return console.error("[AgentSession] Failed to switch agent:",r),e}},[l?.id,e,r,a]),eN=(0,$.useCallback)(async s=>{let n=l?.id;if(!n)return"No active session";S(null);let i=ea.current.then(()=>NE(n,s));ea.current=i.then(()=>void 0,()=>void 0);try{let s=await i;return c(i=>{if(!i||i.id!==n)return i;let o={...i,model:s};return e&&NB(e,r,a,o),o}),null}catch(r){let e=r instanceof Error?r.message:"Failed to set model";return console.error("[AgentSession] Failed to set model:",r),e}},[l?.id,e,r,a]),eE=(0,$.useCallback)(async s=>{if(l?.id){S(null);try{await NR(l.id,s),c(n=>{if(!n)return n;let i={...n,permissionMode:s};return e&&NB(e,r,a,i),i})}catch(e){S(e instanceof Error?e.message:"Failed to switch mode"),console.error("[AgentSession] Failed to switch mode:",e)}}},[l?.id,e,r,a]),eD=(0,$.useCallback)(async s=>{if(l?.id){S(null);try{await NT(l.id,s),c(s=>{if(!s)return s;let n={...s,permissionMode:"edit"};return e&&NB(e,r,a,n),n})}catch(e){S(e instanceof Error?e.message:"Failed to accept plan"),console.error("[AgentSession] Failed to accept plan:",e)}}},[l?.id,e,r,a]),eR=(0,$.useCallback)(async()=>(e&&(l?.id&&NA.delete(NM(e,r,l.id)),NA.delete(NM(e,r,a)),A.current&&(A.current.close(1e3,"new-conversation"),A.current=null,I.current=null),M.current=null,O.current&&(clearTimeout(O.current),O.current=null),J.current&&(clearTimeout(J.current),J.current=null),X.current=!1,Q.current=!1,m(!1),c(null),f("stopped"),x(!0),S(null),k(null),D({tasks:[],turnParked:!1,parkDeadlineAt:null,canStopTasks:!1}),u([]),z.current={sessionId:null,entries:{},status:"stopped"},W.current=null,U(!1),Ng(Np(e,r,s))),null),[e,r,s,l?.id,a]),[eT,eA]=(0,$.useState)(null),eI=(0,$.useRef)(null),eM=(0,$.useCallback)(()=>{eI.current?.resolve(!1),eI.current=null,eA(null)},[]),eF=(0,$.useRef)(new Map),eP=(0,$.useRef)(new Map),eL=(0,$.useCallback)(async(e,r)=>{let s,n=new Promise(e=>{s=e}),i={maxResidentAgentProcesses:e.maxResidentAgentProcesses??0,runningSessions:e.runningSessions??[],resolve:s};eI.current=i,eA(i);let a=await n;return eI.current===i&&(eI.current=null),eA(e=>e===i?null:e),et.current===r&&a},[]),eO=(0,$.useCallback)(e=>{z.current.sessionId!==e.id&&(console.log(`[AgentSession] Adopting ${e.id} over ${z.current.sessionId} — dropping its entries`),u([]),z.current={sessionId:e.id,entries:{},status:e.status},U(!1))},[]),eB=(0,$.useCallback)((e,r)=>{let s=e.session,n={id:s.id,projectId:s.projectId,branch:s.branch,status:s.status,permissionMode:s.permissionMode??"edit",agentType:s.agentType??"claude-code",model:s.model??null,processAlive:s.processAlive??!0},i=Nq(n);NL(r.projectId,r.branch,r.explicitSessionId,n,i);let a=Np(r.projectId,r.branch,r.agentMode);Nx(a),eP.current.set(a,n.id);let o=ef.current,l=null!==o&&Ny(r,o);if(l){et.current+=1,y(!1),eO(n),c(n),V.current=n,W.current=i,f(n.status),x(!0);try{eg(n.id)}catch(e){console.error(`[AgentSession] Failed to connect activated session ${n.id}:`,e)}try{el.current?.(n)}catch(e){console.error(`[AgentSession] onSessionStarted failed for ${n.id}:`,e)}"uncertain"===e.kind&&gS.toast.warning("First message delivery could not be confirmed",{description:"The session exists, but the agent may not have received your message. Check the conversation before resending."})}else console.log(`[AgentSession] Activated session ${n.id} for a background workspace; not adopting it into the current view`);return{session:n,origin:r,adopted:l}},[eg,eO]),ez=(0,$.useCallback)(async(e,r,s,n)=>{let i=!1,a=0,o=s;for(;;){let l;try{l=await n(i)}catch(n){let e=n instanceof Error?n.message:"Failed to start session";return console.error(`[AgentSession] first send transport failure for ${s.operationId}:`,e),et.current===r&&(S(e),gS.toast.error("Failed to send message",{description:`${e}. Sending again will retry the same request.`})),null}if((0,ry.lifecycleSessionReady)(l.kind)&&l.session)return Nn(o.workspaceKey,o.operationId),eB(l,e);if(et.current!==r)return null;switch(!o.sessionId&&l.lifecycle?.sessionId&&Ns(o={...o,sessionId:l.lifecycle.sessionId}),l.kind){case"resident_limit":if(!await eL(l,r))return null;i=!0;continue;case"in_progress":if(a++>=15)return S("Activation is still in progress; try again in a moment"),null;if(await new Promise(e=>setTimeout(e,1e3)),et.current!==r)return null;continue;case"retryable_failure":case"remote_unreachable":{let e=l.error??`Failed to start session (${l.kind})`;return S(e),gS.toast.error("Failed to send message",{description:`${e}. Sending again will retry the same request.`}),null}default:{Nn(o.workspaceKey,o.operationId);let e=l.error??`Failed to start session (${l.kind})`;return S(e),gS.toast.error("Failed to send message",{description:e}),null}}}},[eB,eL]),e$=(0,$.useRef)(new Map),eW=(0,$.useCallback)(()=>{if(!e)return null;let n=Nv(e,r,s,a);return{origin:n,key:Np(n.projectId,n.branch,n.agentMode)}},[e,r,s,a]),eH=(0,$.useCallback)((e,r,s,i)=>{let a=eW();if(!a)return Promise.resolve(null);if(l)return Promise.resolve({session:l,origin:a.origin,adopted:!0});let{origin:o,key:c}=a,d=et.current,u=e$.current.get(c);if(u)return u.then(async r=>r?(await ey(e,r.session.id),r):null);let h=(async()=>{y(!0),S(null);try{var a;let l=Nr(c),u=null!==l&&(a=l.content,null!==a&&null!==e&&("string"==typeof a||"string"==typeof e?"string"==typeof a&&"string"==typeof e&&a.trim()===e.trim():JSON.stringify(a)===JSON.stringify(e)))?{...l,content:e,grantedRemoteIds:i??l.grantedRemoteIds}:{workspaceKey:c,projectId:o.projectId,branch:o.branch,agentMode:o.agentMode??"local",operationId:crypto.randomUUID(),sessionId:null,content:e,permissionMode:r,model:s??null,grantedRemoteIds:i,createdAt:Date.now()},h=Ns(u);return h?.sessionId&&(0,ry.cancelPreparedAgentSession)(h.sessionId).catch(()=>void 0),await ez(o,d,u,a=>u.sessionId?(0,ry.activateAgentSession)(u.sessionId,{activationKey:u.operationId,instruction:e,force:a}):(0,ry.startAgentSession)(o.projectId,{operationId:u.operationId,branch:o.branch,permissionMode:u.permissionMode??r,agentType:n,model:u.model??s,instruction:e,force:a,grantedRemoteIds:u.grantedRemoteIds??i}))}finally{e$.current.get(c)===h&&e$.current.delete(c),et.current===d&&y(!1)}})();return e$.current.set(c,h),h},[l,eW,n,ez,ey]),eU=(0,$.useCallback)(async(e,r,s)=>{let i=eW();if(!i)return null;let{origin:a,key:o}=i,l=et.current;S(null);let c=Nr(o),d=c&&null===c.content?c:{workspaceKey:o,projectId:a.projectId,branch:a.branch,agentMode:a.agentMode??"local",operationId:crypto.randomUUID(),sessionId:null,content:null,permissionMode:e,model:r??null,grantedRemoteIds:s,createdAt:Date.now()},u=Ns(d);u?.sessionId&&(0,ry.cancelPreparedAgentSession)(u.sessionId).catch(()=>void 0);for(let i=0;i<2;i++){let i;try{i=await (0,ry.prepareAgentSession)(a.projectId,{operationId:d.operationId,branch:a.branch,permissionMode:d.permissionMode??e,agentType:n,model:d.model??r,purpose:"interactive_upload",grantedRemoteIds:d.grantedRemoteIds??s})}catch(r){let e=r instanceof Error?r.message:"Failed to prepare session";et.current===l&&(S(e),gS.toast.error("Failed to send message",{description:e}));break}if(et.current!==l)break;if(("prepared"===i.kind||"replayed"===i.kind)&&i.lifecycle)return Ns(d={...d,sessionId:i.lifecycle.sessionId}),{operationId:d.operationId,sessionId:i.lifecycle.sessionId,origin:a,legacy:!0===i.lifecycle.legacy};if("expired"===i.kind){Nn(o,d.operationId),Ns(d={...d,operationId:crypto.randomUUID(),sessionId:null});continue}Nn(o,d.operationId);let c=i.error??`Failed to prepare session (${i.kind})`;S(c),gS.toast.error("Failed to send message",{description:c});break}return null},[eW,n]),eq=(0,$.useCallback)((e,r,s)=>{let n=Np(e.origin.projectId,e.origin.branch,e.origin.agentMode),i=et.current,a=Nr(n),o=a&&a.operationId===e.operationId?{...a,sessionId:e.sessionId,content:r,grantedRemoteIds:s}:{workspaceKey:n,projectId:e.origin.projectId,branch:e.origin.branch,agentMode:e.origin.agentMode??"local",operationId:e.operationId,sessionId:e.sessionId,content:r,grantedRemoteIds:s,createdAt:Date.now()};Ns(o);let l=(async()=>{y(!0),S(null);try{return await ez(e.origin,i,o,n=>(0,ry.activateAgentSession)(e.sessionId,{activationKey:e.operationId,instruction:r,force:n,grantedRemoteIds:s}))}finally{e$.current.get(n)===l&&e$.current.delete(n),et.current===i&&y(!1)}})();return e$.current.set(n,l),l},[ez]),eK=(0,$.useCallback)(async e=>{Nn(Np(e.origin.projectId,e.origin.branch,e.origin.agentMode),e.operationId);try{let r=await (0,ry.cancelPreparedAgentSession)(e.sessionId);e.legacy&&"cancelled"===r.kind&&NO(e.origin.projectId,e.origin.branch,e.origin.explicitSessionId,e.sessionId)}catch(r){console.warn(`[AgentSession] cancel prepared session ${e.sessionId} failed:`,r)}},[]),eV=(0,$.useRef)(null);eV.current=async(e,r)=>{let s=Nv(e.projectId,e.branch,e.agentMode,null),i=e.content;return console.log(`[AgentSession] Replaying pending first send ${e.operationId} for ${e.workspaceKey}`),ez(s,r,e,r=>e.sessionId?(0,ry.activateAgentSession)(e.sessionId,{activationKey:e.operationId,instruction:i,force:r,grantedRemoteIds:e.grantedRemoteIds}):(0,ry.startAgentSession)(e.projectId,{operationId:e.operationId,branch:e.branch,permissionMode:e.permissionMode,agentType:n,model:e.model,instruction:i,force:r,grantedRemoteIds:e.grantedRemoteIds}))};let eX=(0,$.useCallback)((i,o)=>{if(!e)return Promise.resolve(null);let d=Nv(e,r,s,a);if(l)return Promise.resolve({session:l,origin:d,adopted:!0});let u=et.current,h=`${u}:${o??null}`,p=eF.current.get(h);if(p)return p;let m=(async()=>{y(!0),S(null);try{let s;try{s=await (0,ry.createNewAgentSession)(e,r,i,n,void 0,o)}catch(h){let a;if(!(h instanceof ry.ResidentLimitError))throw h;let l=new Promise(e=>{a=e}),c={maxResidentAgentProcesses:h.maxResidentAgentProcesses,runningSessions:h.runningSessions,resolve:a};eI.current=c,eA(c);let d=await l;if(eI.current===c&&(eI.current=null),eA(e=>e===c?null:e),et.current!==u)return null;if(!d)throw h;s=await (0,ry.createNewAgentSession)(e,r,i,n,!0,o)}let a={id:s.session.id,projectId:s.session.projectId,branch:s.session.branch,status:s.session.status,permissionMode:s.session.permissionMode??"edit",agentType:s.session.agentType??"claude-code",model:s.session.model??null,processAlive:s.session.processAlive??!0},l=Nq(a);NL(d.projectId,d.branch,d.explicitSessionId,a,l),Nx(Np(d.projectId,d.branch,d.agentMode)),eP.current.set(Np(d.projectId,d.branch,d.agentMode),a.id);let h=ef.current,p=null!==h&&Ny(d,h);if(p){et.current+=1,y(!1),eO(a),c(a),V.current=a,W.current=l,f(a.status),x(!0);try{eg(a.id)}catch(e){console.error(`[AgentSession] Failed to connect created session ${a.id}:`,e)}try{el.current?.(a)}catch(e){console.error(`[AgentSession] onSessionStarted failed for ${a.id}:`,e)}}else console.log(`[AgentSession] Created session ${a.id} for a background workspace; not adopting it into the current view`);return{session:a,origin:d,adopted:p}}catch(e){if(console.error("[AgentSession] ensureSession:",e),et.current!==u)return null;return S(e instanceof Error?e.message:"Failed to create session"),null}finally{eF.current.get(h)===m&&eF.current.delete(h),et.current===u&&y(!1)}})();return eF.current.set(h,m),m},[e,r,s,n,l,a,eg,eO]),eY=(0,$.useCallback)(async()=>{let s=V.current,n=W.current;if(s&&n?.hasMore&&null!==n.previousCursor&&!q){K(!0);try{let i=await Nz(s.id,n.previousCursor);if(V.current?.id!==s.id)return;if(i.historyEpoch!==n.historyEpoch)W.current=i,z.current={sessionId:s.id,entries:NH(i.entries),status:i.status};else{let e=new Map;for(let r of i.entries)e.set(r.entryIndex,r.message);for(let r of NU(z.current))e.set(r.entryIndex,r.message);let r=[...e].sort((e,r)=>e[0]-r[0]).map(([e,r])=>({entryIndex:e,message:r}));W.current={...n,entries:r,previousCursor:i.previousCursor,hasMore:i.hasMore},z.current={sessionId:z.current.sessionId,entries:NH(r),status:z.current.status}}let o=W.current;u(o.entries.map(e=>e.message)),U(o.hasMore),e&&NL(e,r,a,s,o)}catch(e){gS.toast.error("Failed to load earlier conversation",{description:e instanceof Error?e.message:String(e)})}finally{K(!1)}}},[e,r,a,q]);(0,$.useEffect)(()=>()=>{A.current&&(X.current=!0,A.current.close(),I.current=null),M.current=null,O.current&&clearTimeout(O.current),J.current&&clearTimeout(J.current),ep(),et.current+=1,eM(),NA.clear()},[eM,ep]);let eG=(0,$.useCallback)((e,r,s)=>{let n=NF(NM(e,r,s))??(s?void 0:function(e,r){let s,n=`${e}:${r??""}:`;for(let e of NA.keys())e.startsWith(n)&&(s=e);return s?NF(s):void 0}(e,r));if(!n)return!1;let i=n.history.lastTurnEndEntryIndex??null,a="running"===n.session.status?n.history.entries.filter(e=>null!==i&&e.entryIndex<=i):n.history.entries,o={...n.history,entries:a,latestEntryIndex:a.at(-1)?.entryIndex??null};return c(n.session),V.current=n.session,f(n.session.status),x(!0),w(!0),en.current=!0,u(a.map(e=>e.message)),z.current={sessionId:n.session.id,entries:NH(a),status:n.session.status},W.current=o,U(o.hasMore??!1),!0},[]);return(0,$.useEffect)(()=>{A.current&&(A.current.close(1e3,"branch-switch"),A.current=null,I.current=null),M.current=null,O.current&&(clearTimeout(O.current),O.current=null),J.current&&(clearTimeout(J.current),J.current=null),ep(),et.current+=1,eM();let n=e?Np(e,r,s):null;n&&a&&Nx(n);let i=!a&&null!==n&&Nm(n)&&!Nr(n)?.content;!i&&e&&!ei.current&&eG(e,r,a)||(c(null),V.current=null,f("stopped"),x(i),w(!1),en.current=!1,u([]),z.current={sessionId:null,entries:NH([]),status:"stopped"},W.current=null,U(!1)),m(!1),S(null),y(!1),k(null),D({tasks:[],turnParked:!1,parkDeadlineAt:null,canStopTasks:!1}),X.current=!1,B.current=0,G.current=null,Z.current=0,er.current=!1,es.current=!1,Y.current=!i},[e,r,s,a,eG,eM,ep]),(0,$.useEffect)(()=>{o||!e||!Y.current||en.current||V.current||Nm(Np(e,r,s))||eG(e,r,a)},[o,e,r,s,a,eG]),(0,$.useEffect)(()=>{if(o)return;let n=null!==e?Np(e,r,s):null,i=null!==n&&Nm(n)&&!Nr(n)?.content;!Y.current||!e||l&&!en.current||v||er.current||i||(Y.current=!1,console.log(`[AgentSession] Auto-start: projectId=${e}, branch=${r}, agentMode=${s}`),ev())},[e,r,s,l,v,ev,o]),(0,$.useEffect)(()=>{let e=()=>{if("visible"===document.visibilityState&&l?.id&&!X.current){let e=A.current;e&&e.readyState!==WebSocket.CLOSED&&e.readyState!==WebSocket.CLOSING||(console.log("[AgentSession] Tab visible, WebSocket disconnected - reconnecting"),B.current=0,Z.current=0,O.current&&(clearTimeout(O.current),O.current=null),eg(l.id))}};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[l?.id,eg]),(0,$.useEffect)(()=>{l?.id&&!X.current&&eg(l.id)},[l?.id,eg]),{session:l,messages:d,status:h,isConnected:p,isInitialized:g,isLoading:v,isCachePreview:b,error:_,remoteStatus:j,workflowRunUpdate:C,backgroundTasks:E,streamEpoch:R,messageEntryIndices:NU(z.current).map(e=>e.entryIndex),hasEarlierHistory:H,isLoadingEarlier:q,loadEarlierHistory:eY,startSession:ev,sendMessage:ey,sendEnsuredMessage:eb,discardEnsuredSessionIfEmpty:ew,uploadPaste:e_,uploadAttachment:eS,stopSession:ej,restartSession:ek,switchAgentType:eC,setModel:eN,startNewConversation:eR,ensureSession:eX,startConversation:eH,prepareConversation:eU,activateConversation:eq,cancelPreparedConversation:eK,switchMode:eE,acceptPlan:eD,residentLimitPrompt:eT}}(e,r,a?.agent_mode,H,{sessionId:s,suspended:n,onTaskCompleted:l,onSessionStarted:c,onTitleUpdated:(e,r)=>{let s=r??eh?.id;s&&e&&(ee({sessionId:s,title:e}),d?.(s,e)),G(e=>e+1),Z(null)}}),eK=ek??ef.map((e,r)=>r);b=eh?.id??null,(0,sx.useGlobalEventStream)(s=>{"session:status"!==s.type||"running"!==s.status||!e||s.projectId!==e||(s.branch??null)!==(r??null)||s.sessionId&&s.sessionId!==b&&(s=>{e&&Ru(e,r).then(e=>{e.some(e=>e.reviewer_session_id===s)||i?.(s)}).catch(()=>i?.(s))})(s.sessionId)});let eV=eh?.id??null;(0,$.useEffect)(()=>{p?.(eV)},[eV,p]);let{config:eX}=(0,p2.useAppConfig)(),eY=eX?.crossRemoteSessionGrants===!0,eG=function(e,r,s=!0){let[n,i]=(0,$.useState)([]);(0,$.useEffect)(()=>{s?i(RK(RH(e,r))):i([])},[e,r,s]);let a=(0,$.useCallback)((n,a)=>{s&&i(s=>{var i;let o,l=a?s.some(e=>e.id===n.id)?s:[...s,n]:s.filter(e=>e.id!==n.id);return i=RH(e,r),o=RU(),0===l.length?delete o[i]:o[i]=l,Rq(o),l})},[e,r,s]),o=(0,$.useCallback)(e=>{if(s){let s,n,a,o;s=RH(null,r),n=RH(e,r),(o=(a=RU())[s])&&!a[n]&&(a[n]=o,delete a[s],Rq(a)),i(RK(RH(e,r)))}},[r,s]);return{granted:n,selectedIds:s?n.map(e=>e.id):void 0,toggle:a,adoptInto:o}}(eV,`${e??""}::${r??""}`,eY),eJ=a?.agent_mode&&"local"!==a.agent_mode?a.agent_mode:void 0,eZ=(0,$.useRef)(p);eZ.current=p,(0,$.useEffect)(()=>()=>eZ.current?.(null),[]),(0,$.useEffect)(()=>{(0,ry.getAgentProviders)().then(K).catch(()=>{})},[]);let eQ=eh?.id??null,e0=eh?.permissionMode??null;(0,$.useEffect)(()=>{null===eQ?A("edit"):e0&&A(e0)},[eQ,e0]),(0,$.useEffect)(()=>{eh?.agentType&&U(eh.agentType)},[eh?.agentType]),(0,$.useEffect)(()=>{B.current=null,tP(),E([]),R(1),X(null),P(!1),O(!1)},[e,r]);let e1=(0,$.useRef)({sessionId:null,count:0});(0,$.useEffect)(()=>{let e=eh?.id??null,r=e1.current;e&&r.sessionId===e&&0===r.count&&ef.length>0&&Z(e),e1.current={sessionId:e,count:ef.length}},[eh?.id,ef.length]),(0,$.useEffect)(()=>{J&&eh?.id!==J&&Z(null)},[eh?.id,J]),(0,$.useEffect)(()=>{Q&&eh?.id!==Q.sessionId&&ee(null)},[eh?.id,Q]),(0,$.useEffect)(()=>{if(!Q)return;let e=setTimeout(()=>{ee(e=>e===Q?null:e)},5e3);return()=>clearTimeout(e)},[Q]),(0,$.useEffect)(()=>{if(!J)return;let e=setTimeout(()=>{Z(e=>e===J?null:e)},3e4);return()=>clearTimeout(e)},[J]);let[e2,e5]=(0,$.useState)(!1);(0,$.useEffect)(()=>{e5(!1)},[eh?.id]),(0,$.useEffect)(()=>{em&&e5(!0)},[em]);let e3=async e=>{A(e),eh&&await eH(e)},e4=async e=>{let r=await ez(e);r&&gS.toast.error("Failed to change model",{description:r})},e6=async e=>{await eU(e),A("edit"),h?.()},[e7,e8]=(0,$.useState)(!1),e9=async(e,r)=>{if(eh&&!e7){e8(!0);try{let s=await (0,ry.branchAgentSession)(eh.id,e,r);G(e=>e+1),i?.(s.session.id)}catch(r){let e=r instanceof Error?r.message:"Failed to branch conversation";gS.toast.error("Branch failed",{description:e})}finally{e8(!1)}}},te=q.find(e=>e.type===H)?.displayName??("codex"===H?"Codex":"Claude Code"),tt=q.filter(e=>e.available).filter(e=>e.type!==H),tr=eh?.branchedFromSessionId??null,ts=eh?.branchedFromEntryIndex??-1,[tn,ti]=(0,$.useState)(()=>new Set),[ta,to]=(0,$.useState)(null),[tl,tc]=(0,$.useState)(!1);(0,$.useEffect)(()=>{ti(new Set),to(null),tc(!1)},[eh?.id]);let td=(0,$.useCallback)(e=>{let r=function(e,r){for(let s=r-1;s>=0;s--){let r=e[s];if(r){if("assistant"===r.type&&r.content.trim())return r.content.trim();if("turn_end"===r.type)break}}return null}(ef,e);return null===r?null:`以下是另一个 agent(${te})在分支会话中给出的意见,非用户本人观点,请自行判断是否采纳:
28
+ `,r)}paste(e){this._core.paste(e)}refresh(e,r){this._verifyIntegers(e,r),this._core.refresh(e,r)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return g5},set promptLabel(t){g5=t},get tooMuchOutput(){return g3},set tooMuchOutput(t){g3=t}}}_verifyIntegers(...e){for(_j of e)if(_j===1/0||isNaN(_j)||_j%1!=0)throw Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(_j of e)if(_j&&(_j===1/0||isNaN(_j)||_j%1!=0||_j<0))throw Error("This API only accepts positive integers")}},_C=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let r=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(r._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(0===e.css.cell.width||0===e.css.cell.height)return;let r=0===this._terminal.options.scrollback?0:this._terminal.options.overviewRuler?.width||14,s=window.getComputedStyle(this._terminal.element.parentElement),n=parseInt(s.getPropertyValue("height")),i=Math.max(0,parseInt(s.getPropertyValue("width"))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue("padding-top")),bottom:parseInt(a.getPropertyValue("padding-bottom")),right:parseInt(a.getPropertyValue("padding-right")),left:parseInt(a.getPropertyValue("padding-left"))},l=o.top+o.bottom;return{cols:Math.max(2,Math.floor((i-(o.right+o.left)-r)/e.css.cell.width)),rows:Math.max(1,Math.floor((n-l)/e.css.cell.height))}}},_N=class{constructor(e,r,s,n={}){this._terminal=e,this._regex=r,this._handler=s,this._options=n}provideLinks(e,r){let s=_E.computeLink(e,this._regex,this._terminal,this._handler);r(this._addCallbacks(s))}_addCallbacks(e){return e.map(e=>(e.leave=this._options.leave,e.hover=(r,s)=>{if(this._options.hover){let{range:n}=e;this._options.hover(r,s,n)}},e))}},_E=class e{static computeLink(r,s,n,i){let a=RegExp(s.source,(s.flags||"")+"g"),[o,l]=e._getWindowedLineStrings(r-1,n),c=o.join(""),d,u=[];for(;d=a.exec(c);){let r=d[0];if(!function(e){try{let r=new URL(e),s=r.password&&r.username?`${r.protocol}//${r.username}:${r.password}@${r.host}`:r.username?`${r.protocol}//${r.username}@${r.host}`:`${r.protocol}//${r.host}`;return e.toLocaleLowerCase().startsWith(s.toLocaleLowerCase())}catch{return!1}}(r))continue;let[s,a]=e._mapStrIdx(n,l,0,d.index),[o,c]=e._mapStrIdx(n,s,a,r.length);if(-1===s||-1===a||-1===o||-1===c)continue;let h={start:{x:a+1,y:s+1},end:{x:c,y:o+1}};u.push({range:h,text:r,activate:i})}return u}static _getWindowedLineStrings(e,r){let s,n=e,i=e,a=0,o="",l=[];if(s=r.buffer.active.getLine(e)){let e=s.translateToString(!0);if(s.isWrapped&&" "!==e[0]){for(a=0;(s=r.buffer.active.getLine(--n))&&a<2048&&(a+=(o=s.translateToString(!0)).length,l.push(o),!(!s.isWrapped||-1!==o.indexOf(" "))););l.reverse()}for(l.push(e),a=0;(s=r.buffer.active.getLine(++i))&&s.isWrapped&&a<2048&&(a+=(o=s.translateToString(!0)).length,l.push(o),-1===o.indexOf(" ")););}return[l,n]}static _mapStrIdx(e,r,s,n){let i=e.buffer.active,a=i.getNullCell(),o=s;for(;n;){let e=i.getLine(r);if(!e)return[-1,-1];for(let s=o;s<e.length;++s){e.getCell(s,a);let o=a.getChars();if(a.getWidth()&&(n-=o.length||1,s===e.length-1&&""===o)){let e=i.getLine(r+1);e&&e.isWrapped&&(e.getCell(0,a),2===a.getWidth()&&(n+=1))}if(n<0)return[r,s]}r++,o=0}return[r,o]}},_D=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function _R(e,r){let s=window.open();if(s){try{s.opener=null}catch{}s.location.href=r}else console.warn("Opening link blocked as opener could not be cleared")}var _T=class{constructor(e=_R,r={}){this._handler=e,this._options=r}activate(e){this._terminal=e;let r=this._options,s=r.urlRegex||_D;this._linkProvider=this._terminal.registerLinkProvider(new _N(this._terminal,s,this._handler,r))}dispose(){this._linkProvider?.dispose()}};let _A=(0,e_.default)("list-filter",[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]]),_I=(0,e_.default)("maximize-2",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]),_M=(0,e_.default)("minimize-2",[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]]);function _F(e,r){return 0===r.length?[...e]:e.filter(e=>(function(e,r){let s=e.toLowerCase();for(let e of r){let r=s.includes(e.pattern.toLowerCase());if(e.negate?r:!r)return!1}return!0})(e,r))}let _P=(0,e_.default)("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),_L=(0,e_.default)("eye-off",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);function _O({filters:e,inputOpen:r,onAdd:s,onRemove:n,onCloseInput:i,counts:a}){let o=(0,$.useRef)(null),[l,c]=(0,$.useState)(!1);return(0,$.useEffect)(()=>{r&&o.current?.focus()},[r]),(0,z.jsxs)(z.Fragment,{children:[e.map(e=>(0,z.jsxs)("span",{"data-testid":"terminal-filter-chip","data-negate":e.negate||void 0,className:(0,eb.cn)("flex h-6 max-w-48 items-center gap-1 rounded border pl-1.5 pr-0.5 font-mono text-[11px]","bg-zinc-900/80 backdrop-blur-sm",e.negate?"border-red-500/50 text-red-300":"border-sky-500/50 text-sky-200"),title:e.negate?`Hide lines containing "${e.pattern}"`:`Keep lines containing "${e.pattern}"`,children:[(0,z.jsx)("span",{className:"truncate",children:e.pattern}),(0,z.jsx)("button",{type:"button","aria-label":`Remove filter ${e.pattern}`,onClick:()=>n(e.id),className:"flex h-4 w-4 shrink-0 items-center justify-center rounded text-zinc-400 hover:bg-zinc-700 hover:text-zinc-100",children:(0,z.jsx)(t7,{className:"h-3 w-3"})})]},e.id)),r&&(0,z.jsxs)("span",{"data-testid":"terminal-filter-input-group",className:(0,eb.cn)("flex h-6 items-center overflow-hidden rounded border bg-zinc-900/90 backdrop-blur-sm",l?"border-red-500/60":"border-zinc-600 focus-within:border-sky-500/70"),children:[(0,z.jsx)("button",{type:"button","aria-label":l?"Hide mode: chip hides matching lines":"Keep mode: chip keeps matching lines","aria-pressed":l,title:"Toggle between keeping and hiding lines that match",onMouseDown:e=>e.preventDefault(),onClick:()=>c(e=>!e),className:(0,eb.cn)("flex h-full shrink-0 items-center border-r px-1.5",l?"border-red-500/40 bg-red-500/15 text-red-300 hover:bg-red-500/25":"border-zinc-700 text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200"),children:l?(0,z.jsx)(_L,{className:"h-3 w-3"}):(0,z.jsx)(_P,{className:"h-3 w-3"})}),(0,z.jsx)("input",{ref:o,type:"text","aria-label":"Add terminal filter",placeholder:l?"hide lines containing…":"keep lines containing…",spellCheck:!1,autoComplete:"off",onKeyDown:r=>{let a=r.currentTarget;if(!r.nativeEvent.isComposing&&229!==r.keyCode){if("Enter"===r.key){r.preventDefault();let e=function(e){let r=e.trim();if(!r)return null;if(r.startsWith("\\-")||r.startsWith("\\!"))return{pattern:r.slice(1),negate:!1};if(r.startsWith("-")||r.startsWith("!")){let e=r.slice(1).trim();return e?{pattern:e,negate:!0}:null}return{pattern:r,negate:!1}}(a.value);e&&(s(l?{...e,negate:!0}:e),a.value="");return}if("Escape"===r.key){r.preventDefault(),r.stopPropagation(),i();return}"Backspace"===r.key&&""===a.value&&e.length>0&&(r.preventDefault(),n(e[e.length-1].id))}},className:"h-full w-36 bg-transparent px-1.5 font-mono text-[11px] text-zinc-100 outline-none placeholder:text-zinc-500"})]}),a&&(0,z.jsxs)("span",{"data-testid":"terminal-filter-count",className:"select-none font-mono text-[11px] tabular-nums text-zinc-400",title:"matched / total lines",children:[a.matched.toLocaleString()," / ",a.total.toLocaleString()]})]})}function _B(e,r){let s=e.top-r.top-22-4;s<0&&(s=e.bottom-r.top+4);let n=Math.max(0,r.width-64-2);return{top:s,left:Math.min(Math.max(e.left-r.left,2),n)}}function _z({anchor:e,onCopy:r,className:s}){return(0,z.jsxs)("button",{type:"button","data-testid":"selection-copy-button","aria-label":"Copy selection",onMouseDown:e=>e.preventDefault(),onClick:r,style:{top:e.top,left:e.left,height:22},className:(0,eb.cn)("absolute z-20 flex items-center gap-1 rounded border border-zinc-600 bg-zinc-800 px-2","text-[11px] text-zinc-100 shadow-md hover:bg-zinc-700 hover:border-zinc-500",s),children:[(0,z.jsx)(me.Copy,{className:"h-3 w-3"}),"Copy"]})}function _$({lines:e,fontSize:r,fontFamily:s,isPty:n,className:i}){let a=(0,$.useRef)(null),o=(0,$.useRef)(null),l=(0,$.useRef)(!0),[c,d]=(0,$.useState)(null),u=(0,$.useRef)(!1),h=(0,$.useCallback)(()=>{let e=a.current,r=document.getSelection();if(u.current||!e||!r||r.isCollapsed||0===r.rangeCount||!e.contains(r.anchorNode))return void d(null);let s=e.getBoundingClientRect(),n=Array.from(r.getRangeAt(0).getClientRects()).find(e=>(e.width>0||e.height>0)&&e.bottom>s.top&&e.top<s.bottom);n?d(_B(n,s)):d(null)},[]),f=(0,$.useCallback)(()=>{u.current=!0,d(null),window.addEventListener("mouseup",()=>{u.current=!1,h()},{once:!0})},[h]);(0,$.useEffect)(()=>{let e=()=>{let e=document.getSelection();(!e||e.isCollapsed)&&d(null)};return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[]);let p=async()=>{let e=document.getSelection()?.toString()??"";if(d(null),e)try{await navigator.clipboard.writeText(e),gS.toast.success("Copied selection")}catch{gS.toast.error("Failed to copy to clipboard")}};return(0,$.useLayoutEffect)(()=>{let e=o.current;e&&l.current&&(e.scrollTop=e.scrollHeight)},[e]),(0,z.jsxs)("div",{ref:a,"data-testid":"terminal-filter-view",className:(0,eb.cn)("absolute inset-0 flex flex-col bg-zinc-950",i),children:[c&&(0,z.jsx)(_z,{anchor:c,onCopy:p}),(0,z.jsx)("div",{ref:o,"data-testid":"terminal-filter-scroller",onScroll:()=>{let e=o.current;e&&(l.current=e.scrollHeight-e.scrollTop-e.clientHeight<4,h())},onMouseDown:f,className:"min-h-0 flex-1 overflow-y-auto overflow-x-hidden px-2 pb-2 pt-9",children:0===e.length?(0,z.jsx)("div",{className:"select-none py-4 text-center text-xs text-zinc-500",children:"No lines match"}):(0,z.jsx)("pre",{className:"m-0 whitespace-pre-wrap break-all text-zinc-100",style:{fontSize:r,fontFamily:s,lineHeight:1.2},children:e.map((e,r)=>(0,z.jsx)("div",{children:""===e?" ":e},r))})}),n&&(0,z.jsx)("div",{className:"select-none border-t border-zinc-800 px-2 py-1 text-[11px] text-zinc-500",children:"Filtered view — clear filters to type into the shell"})]})}let _W=/\x1B(?:\][^\x07]*(?:\x07|\x1B\\)|[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;function _H({logs:e,isPty:r,className:s,onInput:n,onResize:i,muteInput:a,focusHandle:o,processId:l,executorId:c,target:d,status:u,exitCode:h}){let f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=(0,$.useRef)(null),g=(0,$.useRef)(0),x=(0,$.useRef)(0),v=(0,$.useRef)(!1),y=(0,$.useRef)(""),b=(0,$.useRef)(""),[w,_]=(0,$.useState)(!1),[S,j]=(0,$.useState)(!1),[k,C]=(0,$.useState)([]),[N,E]=(0,$.useState)(!1),[D,R]=(0,$.useState)(null),[T,A]=(0,$.useState)(0),I=k.length>0,M=(0,$.useRef)(I);(0,$.useEffect)(()=>{M.current=I},[I]);let[F,P]=(0,$.useState)(null),L=(0,$.useRef)(!1),O=(0,$.useRef)(null),B=(0,$.useRef)(l);(0,$.useEffect)(()=>{B.current=l},[l]);let W=(0,$.useRef)(a);W.current!==a&&console.log(`[ExecutorOutput] muteInput changed: ${W.current} → ${a}`),W.current=a;let{settings:H}=(0,m1.useTerminalSettings)(),U=(0,$.useRef)(H),[q,K]=(0,$.useState)(!1),V=(0,$.useRef)(0),X=(0,$.useRef)(e);X.current=e;let Y=async()=>{if(!q){V.current=X.current.length,K(!0);return}let e=X.current,r=Math.min(V.current,e.length),s=e.slice(r).map(e=>"stdout"===e.type||"stderr"===e.type||"pty"===e.type?e.data:"").join("");K(!1);let n=s.replace(_W,""),i=k.length>0?_F(n.split(/\r?\n/),k).join("\n"):n;if(!i)return void gS.toast.info(k.length>0?"Capture stopped — no output matched the filters":"Capture stopped — no output to copy");try{await navigator.clipboard.writeText(i),gS.toast.success(k.length>0?"Copied filtered captured output to clipboard":"Copied captured output to clipboard")}catch{gS.toast.error("Failed to copy to clipboard")}},G=(0,$.useCallback)((e,r)=>{let s=f.current;console.log(`[ExecutorOutput] resize → PTY ${e}x${r} process=${B.current??"?"} container=${s?.clientWidth??0}x${s?.clientHeight??0}px viewport=${window.innerWidth}x${window.innerHeight}px`)},[]),J=(0,$.useCallback)((e,r,s)=>{let n=p.current;if(!n)return void s?.();if(e){x.current++;try{n.write(e,()=>{x.current=Math.max(0,x.current-1),r||s?.()})}catch(e){x.current=Math.max(0,x.current-1),console.error("[ExecutorOutput] terminal write failed",e),r||s?.()}}else r||s?.();if(r)try{n.write(r,()=>s?.())}catch(e){console.error("[ExecutorOutput] terminal write failed",e),s?.()}},[]),Z=(0,$.useCallback)(()=>{v.current=!0;let e=y.current,r=b.current;y.current="",b.current="",e||r?J(e,r,()=>{p.current?.scrollToBottom(),_(!0)}):_(!0)},[J]),Q=(0,$.useRef)(null),ee=(0,$.useCallback)(()=>{let e=f.current,r=m.current;if(!e||!r||0===e.clientWidth||0===e.clientHeight)return!1;let s=r.proposeDimensions();if(!s||!Number.isFinite(s.cols)||!Number.isFinite(s.rows)||s.cols<=0||s.rows<=0)return!1;try{r.fit()}catch{return!1}return Z(),!0},[Z]),et=(0,$.useCallback)(()=>{if(null!==Q.current)return;let e=()=>{if(Q.current=null,v.current||!p.current)return;let r=f.current;r&&0!==r.clientWidth&&0!==r.clientHeight&&(ee()||(Q.current=requestAnimationFrame(e)))};Q.current=requestAnimationFrame(e)},[ee]),er=(0,$.useCallback)(()=>{let e=p.current,r=O.current;if(!e||!r||L.current)return void P(null);let s=e.getSelectionPosition();if(!s)return void P(null);let n=e.buffer.active.viewportY,i=s.start.y-n;if(s.end.y-n<0||i>=e.rows)return void P(null);let a=Math.max(i,0),o=a===i?s.start.x:0,l=e.element?.querySelectorAll(".xterm-rows > div")[a],c=l?.getBoundingClientRect();if(!c||0===c.width)return void P(null);let d=c.width/e.cols;P(_B({top:c.top,bottom:c.bottom,left:c.left+o*d},r.getBoundingClientRect()))},[]),es=(0,$.useCallback)(()=>{L.current=!0,P(null),window.addEventListener("pointerup",()=>{L.current=!1,er()},{once:!0})},[er]),en=async()=>{let e=p.current?.getSelection()??"";if(P(null),e)try{await navigator.clipboard.writeText(e),gS.toast.success("Copied selection")}catch{gS.toast.error("Failed to copy to clipboard")}};(0,$.useEffect)(()=>{if(!f.current||p.current)return;let e=U.current,s=new _k({cursorBlink:r,cursorStyle:r?"block":"underline",disableStdin:!r,convertEol:!0,fontSize:e.fontSize,fontFamily:e.fontFamily,scrollback:e.scrollback,theme:{background:"#09090b",foreground:"#fafafa",cursor:r?"#fafafa":"#09090b",cursorAccent:"#09090b",selectionBackground:"#3f3f46",black:"#09090b",red:"#f87171",green:"#4ade80",yellow:"#facc15",blue:"#60a5fa",magenta:"#c084fc",cyan:"#22d3ee",white:"#fafafa",brightBlack:"#71717a",brightRed:"#fca5a5",brightGreen:"#86efac",brightYellow:"#fde047",brightBlue:"#93c5fd",brightMagenta:"#d8b4fe",brightCyan:"#67e8f9",brightWhite:"#ffffff"},allowProposedApi:!0}),a=new _C,o=new _T;s.loadAddon(a),s.loadAddon(o),s.attachCustomKeyEventHandler(e=>null===fS(e)),s.open(f.current);let l=setTimeout(()=>{try{let e=f.current;if(!e||0===e.clientWidth||0===e.clientHeight)return;ee()?r&&(G(s.cols,s.rows),i?.(s.cols,s.rows)):et()}catch{}},0);return p.current=s,m.current=a,A(e=>e+1),r&&n&&s.onData(e=>{W.current||0!==x.current||M.current||n(e)}),s.onSelectionChange(er),s.onScroll(er),r&&i&&s.onResize(({cols:e,rows:r})=>{G(e,r),i(e,r)}),()=>{clearTimeout(l),null!==Q.current&&(cancelAnimationFrame(Q.current),Q.current=null),s.dispose(),p.current=null,m.current=null,g.current=0,x.current=0,v.current=!1,y.current="",b.current=""}},[r,n,i,ee,et,G,er]),(0,$.useEffect)(()=>{if(!p.current)return;e.length<g.current&&(p.current.reset(),A(e=>e+1),g.current=0,y.current="",b.current="");let s="",n="";for(let r=g.current;r<e.length;r++){let i=e[r];("pty"===i.type||"stdout"===i.type||"stderr"===i.type)&&(i.historical?s+=i.data:n+=i.data)}if(g.current=e.length,r&&!v.current){y.current=(y.current+s).slice(-1e6),b.current=(b.current+n).slice(-1e6);return}(s||n)&&J(s,n)},[e,r,J]),(0,$.useEffect)(()=>{let e=p.current;if(e){e.options.fontSize=H.fontSize,e.options.fontFamily=H.fontFamily,e.options.scrollback=H.scrollback;try{m.current?.fit()}catch{}}},[H.fontSize,H.fontFamily,H.scrollback]),(0,$.useEffect)(()=>{S&&r&&!I&&!N&&p.current?.focus()},[S,r,I,N]),(0,$.useEffect)(()=>{if(!I)return void R(null);let e=p.current;if(!e)return;let r=null,s=()=>{r=null;let s=function(e){let r=[];for(let s=0;s<e.length;s++){let n=e.getLine(s);if(!n)continue;let i=n.translateToString(!0);n.isWrapped&&r.length>0?r[r.length-1]+=i:r.push(i)}let s=r.length;for(;s>0&&""===r[s-1];)s--;return r.slice(0,s)}(e.buffer.active);R({lines:_F(s,k),total:s.length})};s();let n=e.onWriteParsed(()=>{null===r&&(r=requestAnimationFrame(s))});return()=>{n.dispose(),null!==r&&cancelAnimationFrame(r)}},[k,I,T]);let ei=(0,$.useCallback)(e=>{C(r=>[...r,{...e,id:`${Date.now()}-${r.length}`}])},[]),ea=(0,$.useCallback)(e=>{C(r=>r.filter(r=>r.id!==e))},[]),eo=(0,$.useCallback)(()=>{E(!1),r&&0===k.length&&p.current?.focus()},[r,k.length]),el=async()=>{let e=D?.lines.join("\n")??"";if(!e)return void gS.toast.info("No filtered lines to copy");try{await navigator.clipboard.writeText(e),gS.toast.success(`Copied ${D.lines.length} filtered lines`)}catch{gS.toast.error("Failed to copy to clipboard")}};(0,$.useImperativeHandle)(o,()=>({focus:()=>{r&&!M.current&&p.current?.focus()}}),[r]),(0,$.useEffect)(()=>{if(!f.current||!m.current)return;let e=new ResizeObserver(()=>{try{let e=f.current;if(!e||0===e.clientWidth||0===e.clientHeight)return;v.current?m.current?.fit():ee()||et()}catch{}});return e.observe(f.current),()=>{e.disconnect()}},[ee,et]);let ec=[{label:"Process",value:l??null},{label:"Executor",value:c??null},{label:"Target",value:d??null},{label:"Status",value:"closed"===u&&null!==h?`closed \xb7 exit ${h}`:u??null}],ed=(0,eb.cn)("flex h-6 w-6 items-center justify-center rounded","bg-zinc-900/70 backdrop-blur-sm border border-zinc-700/60","text-zinc-400 hover:text-zinc-100 hover:border-zinc-500 transition-colors");return(0,z.jsxs)("div",{className:(0,eb.cn)("relative h-[300px] rounded-md border bg-zinc-950 overflow-hidden",s),children:[S&&(0,z.jsx)("div",{className:"flex h-full select-none items-center justify-center text-xs text-zinc-500",children:"Terminal is maximized"}),(0,z.jsx)("div",{"data-testid":"executor-output-layer","data-maximized":S||void 0,role:S?"dialog":void 0,"aria-modal":S||void 0,"aria-label":S?"Maximized terminal":void 0,className:S?"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 sm:p-10 lg:p-16":"absolute inset-0",onMouseDown:S?e=>{e.target===e.currentTarget&&j(!1)}:void 0,children:(0,z.jsxs)("div",{ref:O,className:(0,eb.cn)("relative h-full w-full",S&&"max-h-[85vh] max-w-6xl overflow-hidden rounded-md border border-zinc-700 bg-zinc-950 shadow-2xl"),children:[(0,z.jsx)("div",{ref:f,onPointerDown:es,className:(0,eb.cn)("h-full w-full",!w&&"opacity-0")}),F&&!D&&(0,z.jsx)(_z,{anchor:F,onCopy:en}),D&&(0,z.jsx)(_$,{lines:D.lines,fontSize:H.fontSize,fontFamily:H.fontFamily,isPty:r}),(0,z.jsxs)("div",{className:"absolute top-2 right-3 z-10 flex max-w-[calc(100%-1.5rem)] flex-wrap items-center justify-end gap-1.5",children:[(0,z.jsx)(_O,{filters:k,inputOpen:N,onAdd:ei,onRemove:ea,onCloseInput:eo,counts:D?{matched:D.lines.length,total:D.total}:null}),D&&(0,z.jsx)("button",{type:"button",onClick:el,title:"Copy filtered lines","aria-label":"Copy filtered lines",className:ed,children:(0,z.jsx)(me.Copy,{className:"h-3 w-3"})}),(0,z.jsx)("button",{type:"button",onClick:()=>N?eo():E(!0),title:N?"Close filter input":"Filter output lines","aria-label":N?"Close filter input":"Filter output lines","aria-pressed":I,className:(0,eb.cn)(ed,I&&"text-sky-300 border-sky-500/70 hover:text-sky-200"),children:(0,z.jsx)(_A,{className:"h-3 w-3"})}),(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)("button",{type:"button",title:"Process info","aria-label":"Show process info",className:ed,children:(0,z.jsx)(hv,{className:"h-3 w-3"})})}),(0,z.jsxs)(o1,{align:"end",className:"w-72",children:[(0,z.jsx)(o6,{className:"text-xs text-muted-foreground",children:"Process info"}),ec.map(e=>(0,z.jsxs)(o2,{disabled:!e.value,onSelect:r=>{var s,n;r.preventDefault(),s=e.label,(n=e.value)&&(navigator.clipboard.writeText(n),gS.toast.success(`${s} copied`))},className:"flex items-center justify-between gap-3 font-mono text-xs",children:[(0,z.jsx)("span",{className:"shrink-0 text-muted-foreground",children:e.label}),(0,z.jsxs)("span",{className:"flex min-w-0 items-center gap-1.5",children:[(0,z.jsx)("span",{className:"truncate",children:e.value??"—"}),e.value&&(0,z.jsx)(me.Copy,{className:"h-3 w-3 shrink-0 opacity-60"})]})]},e.label))]})]}),(0,z.jsx)("button",{type:"button",onClick:Y,title:q?I?"Stop capture & copy filtered output":"Stop capture & copy to clipboard":"Start capturing output","aria-label":q?"Stop capture and copy":"Start capturing output",className:(0,eb.cn)(ed,q&&"text-red-400 border-red-500/70 hover:text-red-300"),children:q?(0,z.jsx)(lG,{className:"h-3 w-3 fill-current"}):(0,z.jsx)(sQ,{className:"h-3 w-3"})}),(0,z.jsx)("button",{type:"button",onClick:()=>j(e=>!e),title:S?"Restore size":"Maximize terminal","aria-label":S?"Restore terminal size":"Maximize terminal","aria-pressed":S,className:ed,children:S?(0,z.jsx)(_M,{className:"h-3 w-3"}):(0,z.jsx)(_I,{className:"h-3 w-3"})})]})]})})]})}let _U=[{name:"Dev Server",command:"pnpm dev",executor_type:"command",pty:!0,description:"Start the development server with hot reload"},{name:"Build",command:"pnpm build",executor_type:"command",pty:!0,description:"Build the project for production"},{name:"Lint",command:"pnpm lint",executor_type:"command",pty:!0,description:"Run the linter to check code quality"},{name:"Type Check",command:"npx tsc --noEmit",executor_type:"command",pty:!0,description:"Run TypeScript type checking without emitting files"},{name:"Test",command:"pnpm test",executor_type:"command",pty:!0,description:"Run the test suite"},{name:"Rebase on and merge into main",command:"Our goal is to sync the current local branch with the local branch/worktree `main`. The two branches may have diverged.\n\nPlease do the following in order. Only proceed to the next step if the previous step succeeds:\n\n1. Rebase the current local branch onto the local branch `main`, and resolve any conflicts if needed.\n2. If, after the rebase, `main` does not yet contain the current branch's commits, switch to the `main` branch/worktree and merge the current branch into `main` using `git merge`. Do not use `git branch -f`.\n3. If the current branch is already fully contained in `main`, and `main` has newer commits, update the current branch so it includes the latest commits from `main`.\n4. Push both the current local branch and the local branch `main` to the remote.",executor_type:"prompt",pty:!1,description:"Rebase current branch onto main, merge into main, and push both branches"},{name:"Reset to main",command:"git reset --hard main",executor_type:"command",pty:!0,description:"Hard reset the current branch to match main"},{name:"Push to remote",command:"git push --force-with-lease",executor_type:"command",pty:!0,description:"Force push to remote with lease safety check"},{name:"Git commit",command:"Inspect the modified and untracked and deleted files in the current repository, generate an appropriate commit message, and commit all relevant files.\n\nCommit message rules:\n- Use Conventional Commits format (feat:, fix:, chore:, refactor:, docs:, test:, ci:, build:, perf:, style:, etc.)\n- Choose the type that best matches the main purpose of the changes\n- Make the message specific to the actual changes\n- Keep it within 50 characters if possible\n- Use lowercase\n- Do not end with a period\n- Do not wrap the message in quotes, backticks, or markdown\n\nCommit requirements:\n- Include all relevant modified and untracked files\n- Do not include unrelated files\n- If there are no meaningful changes to commit, do not create a commit\n- Do not run tests, builds, type checks, or linters; only inspect the changes and commit\n\nWhen finished, output only the final commit message.",executor_type:"prompt",pty:!1,description:"Inspect changes, generate a conventional commit message, and commit"},{name:"Tag and push",command:"Find the latest SemVer tag in the repository, increase the patch number by 1, create the new tag from the current commit, and push it to origin.",executor_type:"prompt",pty:!1,description:"Bump the patch version tag and push it to origin"}];function _q({open:e,onOpenChange:r,executor:s,onSubmit:n}){let[i,a]=(0,$.useState)(s?.name??""),[o,l]=(0,$.useState)(s?.executor_type??"command"),[c,d]=(0,$.useState)(s?.prompt_provider??"claude"),[u,h]=(0,$.useState)(s?.command??""),[f,p]=(0,$.useState)(s?.cwd??""),[m,g]=(0,$.useState)(s?.pty??!0),[x,v]=(0,$.useState)(!1),[y,b]=(0,$.useState)(!1),[w,_]=(0,$.useState)(null),[S,j]=(0,$.useState)(null),[k,C]=(0,$.useState)(""),N=!!s;(0,$.useEffect)(()=>{e&&(b(!1),_(null),j(null),C(""),s&&(a(s.name),l(s.executor_type??"command"),d(s.prompt_provider??"claude"),h(s.command),p(s.cwd??""),g(s.pty)))},[e]);let E=async e=>{if(e.preventDefault(),i.trim()&&u.trim()){v(!0);try{await n({name:i.trim(),command:u.trim(),executor_type:o,prompt_provider:"prompt"===o?c:null,cwd:f.trim()||void 0,pty:"prompt"===o||m}),r(!1),N||(a(""),l("command"),d("claude"),h(""),p(""),g(!0))}finally{v(!1)}}};return(0,z.jsx)(t8,{open:e,onOpenChange:r,children:(0,z.jsxs)(rs,{children:[(0,z.jsx)(rn,{children:(0,z.jsxs)("div",{className:"flex items-center justify-between pr-6",children:[(0,z.jsx)(ra,{children:y?"Select Preset":N?"Edit Executor":"Add Executor"}),!N&&!y&&(0,z.jsx)("button",{type:"button",className:"text-sm text-muted-foreground hover:text-foreground transition-colors",onClick:()=>b(!0),children:"Select from presets"})]})}),(0,z.jsxs)("div",{className:"h-[420px] flex flex-col",children:[!y&&(0,z.jsxs)("form",{onSubmit:E,className:"space-y-4 flex-1 flex flex-col",children:[(0,z.jsxs)("div",{className:"space-y-2",children:[(0,z.jsx)("label",{className:"text-sm font-medium",children:"Name"}),(0,z.jsx)(rl,{placeholder:"e.g., Dev Server",value:i,onChange:e=>a(e.target.value),required:!0})]}),(0,z.jsxs)("div",{className:"space-y-2",children:[(0,z.jsx)("label",{className:"text-sm font-medium",children:"Type"}),(0,z.jsxs)("div",{className:"flex rounded-md border border-input overflow-hidden",children:[(0,z.jsx)("button",{type:"button",className:(0,eb.cn)("flex-1 px-3 py-1.5 text-sm font-medium transition-colors","command"===o?"bg-primary text-primary-foreground":"bg-background text-muted-foreground hover:bg-muted"),onClick:()=>l("command"),children:"Command"}),(0,z.jsx)("button",{type:"button",className:(0,eb.cn)("flex-1 px-3 py-1.5 text-sm font-medium transition-colors border-l border-input","prompt"===o?"bg-primary text-primary-foreground":"bg-background text-muted-foreground hover:bg-muted"),onClick:()=>l("prompt"),children:"Prompt"})]})]}),"prompt"===o&&(0,z.jsxs)("div",{className:"flex gap-3",children:[(0,z.jsxs)("div",{className:"w-[140px] shrink-0 space-y-2",children:[(0,z.jsx)("label",{className:"text-sm font-medium",children:"Provider"}),(0,z.jsxs)(fd,{value:c,onValueChange:e=>d(e),children:[(0,z.jsx)(fh,{className:"w-full",children:(0,z.jsx)(fu,{})}),(0,z.jsxs)(ff,{children:[(0,z.jsx)(fp,{value:"claude",children:"Claude"}),(0,z.jsx)(fp,{value:"codex",children:"Codex"})]})]})]}),(0,z.jsxs)("div",{className:"flex-1 space-y-2",children:[(0,z.jsxs)("label",{className:"text-sm font-medium",children:["Working Directory"," ",(0,z.jsx)("span",{className:"text-muted-foreground",children:"(optional)"})]}),(0,z.jsx)(rl,{placeholder:"Relative to worktree root",value:f,onChange:e=>p(e.target.value)})]})]}),(0,z.jsxs)("div",{className:"space-y-2",children:[(0,z.jsx)("label",{className:"text-sm font-medium",children:"prompt"===o?"Prompt":"Command"}),"prompt"===o?(0,z.jsx)("textarea",{className:"flex min-h-[90px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 resize-y",placeholder:"e.g., Review the code and suggest improvements",value:u,onChange:e=>h(e.target.value),required:!0}):(0,z.jsx)(rl,{placeholder:"e.g., npm run dev",value:u,onChange:e=>h(e.target.value),required:!0})]}),"command"===o&&(0,z.jsxs)("div",{className:"space-y-2",children:[(0,z.jsxs)("label",{className:"text-sm font-medium",children:["Working Directory"," ",(0,z.jsx)("span",{className:"text-muted-foreground",children:"(optional)"})]}),(0,z.jsx)(rl,{placeholder:"Relative to worktree root (leave empty for root)",value:f,onChange:e=>p(e.target.value)})]}),"command"===o&&(0,z.jsxs)("div",{className:"flex items-center justify-between",children:[(0,z.jsxs)("div",{className:"space-y-0.5",children:[(0,z.jsx)("label",{className:"text-sm font-medium",children:"Terminal Mode (PTY)"}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:"Enable for interactive commands like top, vim, htop"})]}),(0,z.jsx)("button",{type:"button",role:"switch","aria-checked":m,onClick:()=>g(!m),className:(0,eb.cn)("relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",m?"bg-primary":"bg-input"),children:(0,z.jsx)("span",{className:(0,eb.cn)("pointer-events-none inline-block h-5 w-5 transform rounded-full bg-background shadow-lg ring-0 transition-transform",m?"translate-x-5":"translate-x-0")})})]}),(0,z.jsx)("div",{className:"flex-1"}),(0,z.jsxs)(ri,{children:[(0,z.jsx)(W.Button,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),(0,z.jsx)(W.Button,{type:"submit",disabled:x||!i.trim()||!u.trim(),children:x?"Saving...":N?"Save":"Add"})]})]}),y&&(0,z.jsxs)("div",{className:"space-y-4 flex-1 flex flex-col min-h-0",children:[(0,z.jsx)(rl,{placeholder:"Search presets...",value:k,onChange:e=>C(e.target.value),autoFocus:!0}),(0,z.jsx)("div",{className:"flex-1 overflow-y-auto min-h-0 space-y-1",children:_U.filter(e=>{if(!k.trim())return!0;let r=k.toLowerCase();return e.name.toLowerCase().includes(r)||e.command.toLowerCase().includes(r)||(e.description?.toLowerCase().includes(r)??!1)}).map(e=>{let r=w?.command===e.command,s=S===e.command;return(0,z.jsxs)("div",{className:"rounded-md overflow-hidden",children:[(0,z.jsxs)("button",{type:"button",className:(0,eb.cn)("w-full flex items-center gap-2 px-3 py-2 text-sm transition-colors",r?"bg-primary/10 text-primary":"hover:bg-muted"),onClick:()=>_(e),children:["command"===e.executor_type?(0,z.jsx)(gM,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):(0,z.jsx)(sR,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),(0,z.jsx)("span",{className:"font-medium flex-1 text-left",children:e.name}),(0,z.jsx)("button",{type:"button",className:"shrink-0 p-0.5 rounded hover:bg-muted-foreground/10 transition-colors",onClick:r=>{r.stopPropagation(),j(s?null:e.command)},children:s?(0,z.jsx)(n6,{className:"h-4 w-4 text-muted-foreground"}):(0,z.jsx)(nV,{className:"h-4 w-4 text-muted-foreground"})})]}),s&&(0,z.jsxs)("div",{className:(0,eb.cn)("px-3 pb-2 pt-1 text-xs text-muted-foreground space-y-1 border-t border-border/50",r?"bg-primary/5":"bg-muted/50"),children:[e.description&&(0,z.jsx)("p",{children:e.description}),(0,z.jsx)("pre",{className:"whitespace-pre-wrap break-all bg-muted/50 rounded px-2 py-1 font-mono",children:e.command}),(0,z.jsxs)("div",{className:"flex gap-3",children:[(0,z.jsxs)("span",{children:["Type: ",(0,z.jsx)("span",{className:"font-medium text-foreground/70",children:e.executor_type})]}),(0,z.jsxs)("span",{children:["PTY: ",(0,z.jsx)("span",{className:"font-medium text-foreground/70",children:e.pty?"on":"off"})]})]})]})]},e.command)})}),(0,z.jsxs)(ri,{children:[(0,z.jsx)(W.Button,{type:"button",variant:"outline",onClick:()=>{b(!1),_(null),j(null)},children:"Cancel"}),(0,z.jsx)(W.Button,{type:"button",disabled:!w,onClick:()=>{w&&(a(w.name),h(w.command),l(w.executor_type),g(w.pty),b(!1),_(null),j(null))},children:"Select"})]})]})]})]})})}let _K={logs:[],status:"connecting",exitCode:null,isPty:!1,replayingHistory:!0},_V=(0,$.createContext)(null);function _X({projectId:e,children:r}){let s=(0,$.useRef)(new Map),n=(0,$.useRef)(new Map),i=(0,$.useRef)(new Set),a=(0,$.useRef)(null),o=(0,$.useRef)(0),l=(0,$.useRef)(null),c=(0,$.useCallback)(e=>{n.current.get(e)?.forEach(e=>e())},[]),d=(0,$.useCallback)((e,r)=>{let n=s.current.get(e)??_K;s.current.set(e,{...n,...r}),c(e)},[c]),u=(0,$.useRef)(new Map),h=(0,$.useRef)(new Map),f=(0,$.useCallback)(e=>{a.current?.readyState===WebSocket.OPEN&&a.current.send(JSON.stringify(e))},[]),p=(0,$.useCallback)(e=>{let r=u.current.get(e);r&&clearTimeout(r),u.current.delete(e),h.current.delete(e)},[]),m=(0,$.useCallback)(e=>{let r=u.current.get(e);r&&clearTimeout(r);let s=h.current.get(e)??0;if(s>=12){u.current.delete(e),d(e,{status:"error"});return}h.current.set(e,s+1);let n=Math.min(15e3,1e3*2**s),a=n+n*Math.random()*.25;d(e,{status:"connecting"});let o=setTimeout(()=>{u.current.delete(e),i.current.has(e)&&f({type:"subscribe",processId:e})},a);u.current.set(e,o)},[f,d]),g=(0,$.useCallback)(e=>{let{processId:r}=e;if(i.current.has(r))if("init"===e.type)p(r),d(r,{isPty:e.isPty,replayingHistory:!0,logs:[],status:"connected"});else if("history_end"===e.type)d(r,{replayingHistory:!1});else if("finished"===e.type)d(r,{exitCode:e.exitCode,status:"closed"});else if("error"===e.type)e.retryable?m(r):(p(r),d(r,{status:"error"}));else{let n=s.current.get(r)??_K,{processId:i,...a}=e;d(r,{logs:[...n.logs,{...a,historical:n.replayingHistory}]})}},[d,p,m]);(0,$.useEffect)(()=>{if(!e)return;let r=!1;o.current=0;let n=()=>{r||(0,ry.getFreshToken)().then(()=>{r||(()=>{if(r)return;let c=new WebSocket((0,ry.getWebSocketUrl)(`/api/executor-logs/stream?projectId=${encodeURIComponent(e)}`));a.current=c,c.onopen=()=>{if(!r)for(let e of(o.current=0,i.current))p(e),c.send(JSON.stringify({type:"subscribe",processId:e}))},c.onmessage=e=>{if(!r)try{g(JSON.parse(e.data))}catch(e){console.error("[ExecutorLogs] parse error:",e)}},c.onclose=()=>{if(a.current=null,r)return;let e=e=>{let r=s.current.get(e);return r?.status==="closed"||r?.status==="error"};if(o.current<8){let s=o.current++,a=Math.min(15e3,1e3*2**s),c=a+a*Math.random()*.25;for(let r of i.current)e(r)||d(r,{status:"connecting"});l.current=setTimeout(()=>{l.current=null,r||n()},c)}else for(let r of i.current)e(r)||d(r,{status:"error"})}})()})};n();let c=u.current,f=h.current;return()=>{for(let e of(r=!0,l.current&&clearTimeout(l.current),l.current=null,c.values()))clearTimeout(e);c.clear(),f.clear(),a.current?.close(),a.current=null}},[e,g,d,p]);let x=(0,$.useMemo)(()=>({subscribeProcess:e=>{i.current.has(e)||(i.current.add(e),s.current.set(e,{..._K}),c(e),f({type:"subscribe",processId:e}))},unsubscribeProcess:e=>{i.current.has(e)&&(i.current.delete(e),p(e),f({type:"unsubscribe",processId:e}))},sendInput:(e,r)=>f({type:"input",processId:e,data:r}),sendResize:(e,r,s)=>f({type:"resize",processId:e,cols:r,rows:s}),onProcessChange:(e,r)=>{let s=n.current.get(e);return s||(s=new Set,n.current.set(e,s)),s.add(r),()=>{s?.delete(r)}},getProcessState:e=>s.current.get(e)??_K}),[c,f,p]);return(0,z.jsx)(_V.Provider,{value:x,children:r})}let _Y="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement;function _G(e){let r=Object.prototype.toString.call(e);return"[object Window]"===r||"[object global]"===r}function _J(e){return"nodeType"in e}function _Z(e){var r,s;return e?_G(e)?e:_J(e)&&null!=(r=null==(s=e.ownerDocument)?void 0:s.defaultView)?r:window:window}function _Q(e){let{Document:r}=_Z(e);return e instanceof r}function _0(e){return!_G(e)&&e instanceof _Z(e).HTMLElement}function _1(e){return e instanceof _Z(e).SVGElement}function _2(e){return e?_G(e)?e.document:_J(e)?_Q(e)?e:_0(e)||_1(e)?e.ownerDocument:document:document:document}let _5=_Y?$.useLayoutEffect:$.useEffect;function _3(e){let r=(0,$.useRef)(e);return _5(()=>{r.current=e}),(0,$.useCallback)(function(){for(var e=arguments.length,s=Array(e),n=0;n<e;n++)s[n]=arguments[n];return null==r.current?void 0:r.current(...s)},[])}function _4(e,r){void 0===r&&(r=[e]);let s=(0,$.useRef)(e);return _5(()=>{s.current!==e&&(s.current=e)},r),s}function _6(e,r){let s=(0,$.useRef)();return(0,$.useMemo)(()=>{let r=e(s.current);return s.current=r,r},[...r])}function _7(e){let r=_3(e),s=(0,$.useRef)(null),n=(0,$.useCallback)(e=>{e!==s.current&&(null==r||r(e,s.current)),s.current=e},[]);return[s,n]}function _8(e){let r=(0,$.useRef)();return(0,$.useEffect)(()=>{r.current=e},[e]),r.current}let _9={};function Se(e,r){return(0,$.useMemo)(()=>{if(r)return r;let s=null==_9[e]?0:_9[e]+1;return _9[e]=s,e+"-"+s},[e,r])}function St(e){return function(r){for(var s=arguments.length,n=Array(s>1?s-1:0),i=1;i<s;i++)n[i-1]=arguments[i];return n.reduce((r,s)=>{for(let[n,i]of Object.entries(s)){let s=r[n];null!=s&&(r[n]=s+e*i)}return r},{...r})}}let Sr=St(1),Ss=St(-1);function Sn(e){if(!e)return!1;let{KeyboardEvent:r}=_Z(e.target);return r&&e instanceof r}function Si(e){if(function(e){if(!e)return!1;let{TouchEvent:r}=_Z(e.target);return r&&e instanceof r}(e)){if(e.touches&&e.touches.length){let{clientX:r,clientY:s}=e.touches[0];return{x:r,y:s}}else if(e.changedTouches&&e.changedTouches.length){let{clientX:r,clientY:s}=e.changedTouches[0];return{x:r,y:s}}}return"clientX"in e&&"clientY"in e?{x:e.clientX,y:e.clientY}:null}let Sa=Object.freeze({Translate:{toString(e){if(!e)return;let{x:r,y:s}=e;return"translate3d("+(r?Math.round(r):0)+"px, "+(s?Math.round(s):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;let{scaleX:r,scaleY:s}=e;return"scaleX("+r+") scaleY("+s+")"}},Transform:{toString(e){if(e)return[Sa.Translate.toString(e),Sa.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:r,duration:s,easing:n}=e;return r+" "+s+"ms "+n}}}),So="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]",Sl={display:"none"};function Sc(e){let{id:r,value:s}=e;return $.default.createElement("div",{id:r,style:Sl},s)}function Sd(e){let{id:r,announcement:s,ariaLiveType:n="assertive"}=e;return $.default.createElement("div",{id:r,style:{position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"},role:"status","aria-live":n,"aria-atomic":!0},s)}let Su=(0,$.createContext)(null),Sh={draggable:"\n To pick up a draggable item, press the space bar.\n While dragging, use the arrow keys to move the item.\n Press space again to drop the item in its new position, or press escape to cancel.\n "},Sf={onDragStart(e){let{active:r}=e;return"Picked up draggable item "+r.id+"."},onDragOver(e){let{active:r,over:s}=e;return s?"Draggable item "+r.id+" was moved over droppable area "+s.id+".":"Draggable item "+r.id+" is no longer over a droppable area."},onDragEnd(e){let{active:r,over:s}=e;return s?"Draggable item "+r.id+" was dropped over droppable area "+s.id:"Draggable item "+r.id+" was dropped."},onDragCancel(e){let{active:r}=e;return"Dragging was cancelled. Draggable item "+r.id+" was dropped."}};function Sp(e){var r;let s,{announcements:n=Sf,container:i,hiddenTextDescribedById:a,screenReaderInstructions:o=Sh}=e,{announce:l,announcement:c}=function(){let[e,r]=(0,$.useState)("");return{announce:(0,$.useCallback)(e=>{null!=e&&r(e)},[]),announcement:e}}(),d=Se("DndLiveRegion"),[u,h]=(0,$.useState)(!1);if((0,$.useEffect)(()=>{h(!0)},[]),r=(0,$.useMemo)(()=>({onDragStart(e){let{active:r}=e;l(n.onDragStart({active:r}))},onDragMove(e){let{active:r,over:s}=e;n.onDragMove&&l(n.onDragMove({active:r,over:s}))},onDragOver(e){let{active:r,over:s}=e;l(n.onDragOver({active:r,over:s}))},onDragEnd(e){let{active:r,over:s}=e;l(n.onDragEnd({active:r,over:s}))},onDragCancel(e){let{active:r,over:s}=e;l(n.onDragCancel({active:r,over:s}))}}),[l,n]),s=(0,$.useContext)(Su),(0,$.useEffect)(()=>{if(!s)throw Error("useDndMonitor must be used within a children of <DndContext>");return s(r)},[r,s]),!u)return null;let f=$.default.createElement($.default.Fragment,null,$.default.createElement(Sc,{id:a,value:o.draggable}),$.default.createElement(Sd,{id:d,announcement:c}));return i?(0,ee.createPortal)(f,i):f}function Sm(){}function Sg(e,r){return(0,$.useMemo)(()=>({sensor:e,options:null!=r?r:{}}),[e,r])}(y=E||(E={})).DragStart="dragStart",y.DragMove="dragMove",y.DragEnd="dragEnd",y.DragCancel="dragCancel",y.DragOver="dragOver",y.RegisterDroppable="registerDroppable",y.SetDroppableDisabled="setDroppableDisabled",y.UnregisterDroppable="unregisterDroppable";let Sx=Object.freeze({x:0,y:0});function Sv(e,r){return Math.sqrt(Math.pow(e.x-r.x,2)+Math.pow(e.y-r.y,2))}function Sy(e,r){let{data:{value:s}}=e,{data:{value:n}}=r;return s-n}function Sb(e,r){let{data:{value:s}}=e,{data:{value:n}}=r;return n-s}function Sw(e){let{left:r,top:s,height:n,width:i}=e;return[{x:r,y:s},{x:r+i,y:s},{x:r,y:s+n},{x:r+i,y:s+n}]}function S_(e,r){if(!e||0===e.length)return null;let[s]=e;return r?s[r]:s}function SS(e,r,s){return void 0===r&&(r=e.left),void 0===s&&(s=e.top),{x:r+.5*e.width,y:s+.5*e.height}}let Sj=e=>{let{collisionRect:r,droppableRects:s,droppableContainers:n}=e,i=[];for(let e of n){let{id:n}=e,a=s.get(n);if(a){let s=function(e,r){let s=Math.max(r.top,e.top),n=Math.max(r.left,e.left),i=Math.min(r.left+r.width,e.left+e.width),a=Math.min(r.top+r.height,e.top+e.height);if(n<i&&s<a){let o=r.width*r.height,l=e.width*e.height,c=(i-n)*(a-s);return Number((c/(o+l-c)).toFixed(4))}return 0}(a,r);s>0&&i.push({id:n,data:{droppableContainer:e,value:s}})}}return i.sort(Sb)};function Sk(e,r){return e&&r?{x:e.left-r.left,y:e.top-r.top}:Sx}let SC=function(e){for(var r=arguments.length,s=Array(r>1?r-1:0),n=1;n<r;n++)s[n-1]=arguments[n];return s.reduce((e,r)=>({...e,top:e.top+ +r.y,bottom:e.bottom+ +r.y,left:e.left+ +r.x,right:e.right+ +r.x}),{...e})},SN={ignoreTransform:!1};function SE(e,r){void 0===r&&(r=SN);let s=e.getBoundingClientRect();if(r.ignoreTransform){let{transform:r,transformOrigin:n}=_Z(e).getComputedStyle(e);r&&(s=function(e,r,s){let n=function(e){if(e.startsWith("matrix3d(")){let r=e.slice(9,-1).split(/, /);return{x:+r[12],y:+r[13],scaleX:+r[0],scaleY:+r[5]}}if(e.startsWith("matrix(")){let r=e.slice(7,-1).split(/, /);return{x:+r[4],y:+r[5],scaleX:+r[0],scaleY:+r[3]}}return null}(r);if(!n)return e;let{scaleX:i,scaleY:a,x:o,y:l}=n,c=e.left-o-(1-i)*parseFloat(s),d=e.top-l-(1-a)*parseFloat(s.slice(s.indexOf(" ")+1)),u=i?e.width/i:e.width,h=a?e.height/a:e.height;return{width:u,height:h,top:d,right:c+u,bottom:d+h,left:c}}(s,r,n))}let{top:n,left:i,width:a,height:o,bottom:l,right:c}=s;return{top:n,left:i,width:a,height:o,bottom:l,right:c}}function SD(e){return SE(e,{ignoreTransform:!0})}function SR(e,r){let s=[];return e?function n(i){var a,o;let l;if(null!=r&&s.length>=r||!i)return s;if(_Q(i)&&null!=i.scrollingElement&&!s.includes(i.scrollingElement))return s.push(i.scrollingElement),s;if(!_0(i)||_1(i)||s.includes(i))return s;let c=_Z(e).getComputedStyle(i);return(i!==e&&(void 0===(a=c)&&(a=_Z(i).getComputedStyle(i)),l=/(auto|scroll|overlay)/,["overflow","overflowX","overflowY"].some(e=>{let r=a[e];return"string"==typeof r&&l.test(r)}))&&s.push(i),void 0===(o=c)&&(o=_Z(i).getComputedStyle(i)),"fixed"===o.position)?s:n(i.parentNode)}(e):s}function ST(e){let[r]=SR(e,1);return null!=r?r:null}function SA(e){return _Y&&e?_G(e)?e:_J(e)?_Q(e)||e===_2(e).scrollingElement?window:_0(e)?e:null:null:null}function SI(e){return _G(e)?e.scrollX:e.scrollLeft}function SM(e){return _G(e)?e.scrollY:e.scrollTop}function SF(e){return{x:SI(e),y:SM(e)}}function SP(e){return!!_Y&&!!e&&e===document.scrollingElement}function SL(e){let r={x:0,y:0},s=SP(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},n={x:e.scrollWidth-s.width,y:e.scrollHeight-s.height},i=e.scrollTop<=r.y,a=e.scrollLeft<=r.x;return{isTop:i,isLeft:a,isBottom:e.scrollTop>=n.y,isRight:e.scrollLeft>=n.x,maxScroll:n,minScroll:r}}(b=D||(D={}))[b.Forward=1]="Forward",b[b.Backward=-1]="Backward";let SO={x:.2,y:.2};function SB(e){return e.reduce((e,r)=>Sr(e,SF(r)),Sx)}let Sz=[["x",["left","right"],function(e){return e.reduce((e,r)=>e+SI(r),0)}],["y",["top","bottom"],function(e){return e.reduce((e,r)=>e+SM(r),0)}]];class S${constructor(e,r){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const s=SR(r),n=SB(s);for(const[r,i,a]of(this.rect={...e},this.width=e.width,this.height=e.height,Sz))for(const e of i)Object.defineProperty(this,e,{get:()=>{let i=a(s),o=n[r]-i;return this.rect[e]+o},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class SW{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(e=>{var r;return null==(r=this.target)?void 0:r.removeEventListener(...e)})},this.target=e}add(e,r,s){var n;null==(n=this.target)||n.addEventListener(e,r,s),this.listeners.push([e,r,s])}}function SH(e,r){let s=Math.abs(e.x),n=Math.abs(e.y);return"number"==typeof r?Math.sqrt(s**2+n**2)>r:"x"in r&&"y"in r?s>r.x&&n>r.y:"x"in r?s>r.x:"y"in r&&n>r.y}function SU(e){e.preventDefault()}function Sq(e){e.stopPropagation()}(w=R||(R={})).Click="click",w.DragStart="dragstart",w.Keydown="keydown",w.ContextMenu="contextmenu",w.Resize="resize",w.SelectionChange="selectionchange",w.VisibilityChange="visibilitychange",(_=T||(T={})).Space="Space",_.Down="ArrowDown",_.Right="ArrowRight",_.Left="ArrowLeft",_.Up="ArrowUp",_.Esc="Escape",_.Enter="Enter",_.Tab="Tab";let SK={start:[T.Space,T.Enter],cancel:[T.Esc],end:[T.Space,T.Enter,T.Tab]},SV=(e,r)=>{let{currentCoordinates:s}=r;switch(e.code){case T.Right:return{...s,x:s.x+25};case T.Left:return{...s,x:s.x-25};case T.Down:return{...s,y:s.y+25};case T.Up:return{...s,y:s.y-25}}};class SX{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:r}}=e;this.props=e,this.listeners=new SW(_2(r)),this.windowListeners=new SW(_Z(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(R.Resize,this.handleCancel),this.windowListeners.add(R.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(R.Keydown,this.handleKeyDown))}handleStart(){let{activeNode:e,onStart:r}=this.props,s=e.node.current;s&&function(e,r){if(void 0===r&&(r=SE),!e)return;let{top:s,left:n,bottom:i,right:a}=r(e);ST(e)&&(i<=0||a<=0||s>=window.innerHeight||n>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}(s),r(Sx)}handleKeyDown(e){if(Sn(e)){let{active:r,context:s,options:n}=this.props,{keyboardCodes:i=SK,coordinateGetter:a=SV,scrollBehavior:o="smooth"}=n,{code:l}=e;if(i.end.includes(l))return void this.handleEnd(e);if(i.cancel.includes(l))return void this.handleCancel(e);let{collisionRect:c}=s.current,d=c?{x:c.left,y:c.top}:Sx;this.referenceCoordinates||(this.referenceCoordinates=d);let u=a(e,{active:r,context:s.current,currentCoordinates:d});if(u){let r=Ss(u,d),n={x:0,y:0},{scrollableAncestors:i}=s.current;for(let s of i){let i=e.code,{isTop:a,isRight:l,isLeft:c,isBottom:d,maxScroll:h,minScroll:f}=SL(s),p=function(e){if(e===document.scrollingElement){let{innerWidth:e,innerHeight:r}=window;return{top:0,left:0,right:e,bottom:r,width:e,height:r}}let{top:r,left:s,right:n,bottom:i}=e.getBoundingClientRect();return{top:r,left:s,right:n,bottom:i,width:e.clientWidth,height:e.clientHeight}}(s),m={x:Math.min(i===T.Right?p.right-p.width/2:p.right,Math.max(i===T.Right?p.left:p.left+p.width/2,u.x)),y:Math.min(i===T.Down?p.bottom-p.height/2:p.bottom,Math.max(i===T.Down?p.top:p.top+p.height/2,u.y))},g=i===T.Right&&!l||i===T.Left&&!c,x=i===T.Down&&!d||i===T.Up&&!a;if(g&&m.x!==u.x){let e=s.scrollLeft+r.x,a=i===T.Right&&e<=h.x||i===T.Left&&e>=f.x;if(a&&!r.y)return void s.scrollTo({left:e,behavior:o});a?n.x=s.scrollLeft-e:n.x=i===T.Right?s.scrollLeft-h.x:s.scrollLeft-f.x,n.x&&s.scrollBy({left:-n.x,behavior:o});break}if(x&&m.y!==u.y){let e=s.scrollTop+r.y,a=i===T.Down&&e<=h.y||i===T.Up&&e>=f.y;if(a&&!r.x)return void s.scrollTo({top:e,behavior:o});a?n.y=s.scrollTop-e:n.y=i===T.Down?s.scrollTop-h.y:s.scrollTop-f.y,n.y&&s.scrollBy({top:-n.y,behavior:o});break}}this.handleMove(e,Sr(Ss(u,this.referenceCoordinates),n))}}}handleMove(e,r){let{onMove:s}=this.props;e.preventDefault(),s(r)}handleEnd(e){let{onEnd:r}=this.props;e.preventDefault(),this.detach(),r()}handleCancel(e){let{onCancel:r}=this.props;e.preventDefault(),this.detach(),r()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}function SY(e){return!!(e&&"distance"in e)}function SG(e){return!!(e&&"delay"in e)}SX.activators=[{eventName:"onKeyDown",handler:(e,r,s)=>{let{keyboardCodes:n=SK,onActivation:i}=r,{active:a}=s,{code:o}=e.nativeEvent;if(n.start.includes(o)){let r=a.activatorNode.current;return(!r||e.target===r)&&(e.preventDefault(),null==i||i({event:e.nativeEvent}),!0)}return!1}}];class SJ{constructor(e,r,s){var n;void 0===s&&(s=function(e){let{EventTarget:r}=_Z(e);return e instanceof r?e:_2(e)}(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=r;const{event:i}=e,{target:a}=i;this.props=e,this.events=r,this.document=_2(a),this.documentListeners=new SW(this.document),this.listeners=new SW(s),this.windowListeners=new SW(_Z(a)),this.initialCoordinates=null!=(n=Si(i))?n:Sx,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){let{events:e,props:{options:{activationConstraint:r,bypassActivationConstraint:s}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(R.Resize,this.handleCancel),this.windowListeners.add(R.DragStart,SU),this.windowListeners.add(R.VisibilityChange,this.handleCancel),this.windowListeners.add(R.ContextMenu,SU),this.documentListeners.add(R.Keydown,this.handleKeydown),r){if(null!=s&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(SG(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if(SY(r))return void this.handlePending(r)}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,r){let{active:s,onPending:n}=this.props;n(s,e,this.initialCoordinates,r)}handleStart(){let{initialCoordinates:e}=this,{onStart:r}=this.props;e&&(this.activated=!0,this.documentListeners.add(R.Click,Sq,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(R.SelectionChange,this.removeTextSelection),r(e))}handleMove(e){var r;let{activated:s,initialCoordinates:n,props:i}=this,{onMove:a,options:{activationConstraint:o}}=i;if(!n)return;let l=null!=(r=Si(e))?r:Sx,c=Ss(n,l);if(!s&&o){if(SY(o)){if(null!=o.tolerance&&SH(c,o.tolerance))return this.handleCancel();if(SH(c,o.distance))return this.handleStart()}return SG(o)&&SH(c,o.tolerance)?this.handleCancel():void this.handlePending(o,c)}e.cancelable&&e.preventDefault(),a(l)}handleEnd(){let{onAbort:e,onEnd:r}=this.props;this.detach(),this.activated||e(this.props.active),r()}handleCancel(){let{onAbort:e,onCancel:r}=this.props;this.detach(),this.activated||e(this.props.active),r()}handleKeydown(e){e.code===T.Esc&&this.handleCancel()}removeTextSelection(){var e;null==(e=this.document.getSelection())||e.removeAllRanges()}}let SZ={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class SQ extends SJ{constructor(e){const{event:r}=e;super(e,SZ,_2(r.target))}}SQ.activators=[{eventName:"onPointerDown",handler:(e,r)=>{let{nativeEvent:s}=e,{onActivation:n}=r;return!!s.isPrimary&&0===s.button&&(null==n||n({event:s}),!0)}}];(S=A||(A={}))[S.RightClick=2]="RightClick";(j=I||(I={}))[j.Pointer=0]="Pointer",j[j.DraggableRect=1]="DraggableRect",(k=M||(M={}))[k.TreeOrder=0]="TreeOrder",k[k.ReversedTreeOrder=1]="ReversedTreeOrder";let S0={x:{[D.Backward]:!1,[D.Forward]:!1},y:{[D.Backward]:!1,[D.Forward]:!1}};(C=F||(F={}))[C.Always=0]="Always",C[C.BeforeDragging=1]="BeforeDragging",C[C.WhileDragging=2]="WhileDragging",(P||(P={})).Optimized="optimized";let S1=new Map;function S2(e,r){return _6(s=>e?s||("function"==typeof r?r(e):e):null,[r,e])}function S5(e){let{callback:r,disabled:s}=e,n=_3(r),i=(0,$.useMemo)(()=>{if(s||"undefined"==typeof window||void 0===window.ResizeObserver)return;let{ResizeObserver:e}=window;return new e(n)},[s]);return(0,$.useEffect)(()=>()=>null==i?void 0:i.disconnect(),[i]),i}function S3(e){return new S$(SE(e),e)}function S4(e,r,s){void 0===r&&(r=S3);let[n,i]=(0,$.useState)(null);function a(){i(n=>{if(!e)return null;if(!1===e.isConnected){var i;return null!=(i=null!=n?n:s)?i:null}let a=r(e);return JSON.stringify(n)===JSON.stringify(a)?n:a})}let o=function(e){let{callback:r,disabled:s}=e,n=_3(r),i=(0,$.useMemo)(()=>{if(s||"undefined"==typeof window||void 0===window.MutationObserver)return;let{MutationObserver:e}=window;return new e(n)},[n,s]);return(0,$.useEffect)(()=>()=>null==i?void 0:i.disconnect(),[i]),i}({callback(r){if(e)for(let s of r){let{type:r,target:n}=s;if("childList"===r&&n instanceof HTMLElement&&n.contains(e)){a();break}}}}),l=S5({callback:a});return _5(()=>{a(),e?(null==l||l.observe(e),null==o||o.observe(document.body,{childList:!0,subtree:!0})):(null==l||l.disconnect(),null==o||o.disconnect())},[e]),n}let S6=[];function S7(e,r){void 0===r&&(r=[]);let s=(0,$.useRef)(null);return(0,$.useEffect)(()=>{s.current=null},r),(0,$.useEffect)(()=>{let r=e!==Sx;r&&!s.current&&(s.current=e),!r&&s.current&&(s.current=null)},[e]),s.current?Ss(e,s.current):Sx}function S8(e){return(0,$.useMemo)(()=>{let r,s;return e?(r=e.innerWidth,{top:0,left:0,right:r,bottom:s=e.innerHeight,width:r,height:s}):null},[e])}let S9=[],je=[{sensor:SQ,options:{}},{sensor:SX,options:{}}],jt={current:{}},jr={draggable:{measure:SD},droppable:{measure:SD,strategy:F.WhileDragging,frequency:P.Optimized},dragOverlay:{measure:SE}};class js extends Map{get(e){var r;return null!=e&&null!=(r=super.get(e))?r:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:r}=e;return!r})}getNodeFor(e){var r,s;return null!=(r=null==(s=this.get(e))?void 0:s.node.current)?r:void 0}}let jn={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new js,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Sm},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:jr,measureDroppableContainers:Sm,windowRect:null,measuringScheduled:!1},ji={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Sm,draggableNodes:new Map,over:null,measureDroppableContainers:Sm},ja=(0,$.createContext)(ji),jo=(0,$.createContext)(jn);function jl(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new js}}}function jc(e,r){switch(r.type){case E.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:r.initialCoordinates,active:r.active}};case E.DragMove:if(null==e.draggable.active)return e;return{...e,draggable:{...e.draggable,translate:{x:r.coordinates.x-e.draggable.initialCoordinates.x,y:r.coordinates.y-e.draggable.initialCoordinates.y}}};case E.DragEnd:case E.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case E.RegisterDroppable:{let{element:s}=r,{id:n}=s,i=new js(e.droppable.containers);return i.set(n,s),{...e,droppable:{...e.droppable,containers:i}}}case E.SetDroppableDisabled:{let{id:s,key:n,disabled:i}=r,a=e.droppable.containers.get(s);if(!a||n!==a.key)return e;let o=new js(e.droppable.containers);return o.set(s,{...a,disabled:i}),{...e,droppable:{...e.droppable,containers:o}}}case E.UnregisterDroppable:{let{id:s,key:n}=r,i=e.droppable.containers.get(s);if(!i||n!==i.key)return e;let a=new js(e.droppable.containers);return a.delete(s),{...e,droppable:{...e.droppable,containers:a}}}default:return e}}function jd(e){let{disabled:r}=e,{active:s,activatorEvent:n,draggableNodes:i}=(0,$.useContext)(ja),a=_8(n),o=_8(null==s?void 0:s.id);return(0,$.useEffect)(()=>{if(!r&&!n&&a&&null!=o){if(!Sn(a)||document.activeElement===a.target)return;let e=i.get(o);if(!e)return;let{activatorNode:r,node:s}=e;(r.current||s.current)&&requestAnimationFrame(()=>{for(let e of[r.current,s.current]){if(!e)continue;let r=e.matches(So)?e:e.querySelector(So);if(r){r.focus();break}}})}},[n,r,i,o,a]),null}let ju=(0,$.createContext)({...Sx,scaleX:1,scaleY:1});(N=L||(L={}))[N.Uninitialized=0]="Uninitialized",N[N.Initializing=1]="Initializing",N[N.Initialized=2]="Initialized";let jh=(0,$.memo)(function(e){var r,s,n,i,a,o,l,c;let d,u,h,f,p,m,g,x,{id:v,accessibility:y,autoScroll:b=!0,children:w,sensors:_=je,collisionDetection:S=Sj,measuring:j,modifiers:k,...C}=e,[N,R]=(0,$.useReducer)(jc,void 0,jl),[T,A]=function(){let[e]=(0,$.useState)(()=>new Set),r=(0,$.useCallback)(r=>(e.add(r),()=>e.delete(r)),[e]);return[(0,$.useCallback)(r=>{let{type:s,event:n}=r;e.forEach(e=>{var r;return null==(r=e[s])?void 0:r.call(e,n)})},[e]),r]}(),[P,O]=(0,$.useState)(L.Uninitialized),B=P===L.Initialized,{draggable:{active:z,nodes:W,translate:H},droppable:{containers:U}}=N,q=null!=z?W.get(z):null,K=(0,$.useRef)({initial:null,translated:null}),V=(0,$.useMemo)(()=>{var e;return null!=z?{id:z,data:null!=(e=null==q?void 0:q.data)?e:jt,rect:K}:null},[z,q]),X=(0,$.useRef)(null),[Y,G]=(0,$.useState)(null),[J,Z]=(0,$.useState)(null),Q=_4(C,Object.values(C)),et=Se("DndDescribedBy",v),er=(0,$.useMemo)(()=>U.getEnabled(),[U]),es=(0,$.useMemo)(()=>({draggable:{...jr.draggable,...null==j?void 0:j.draggable},droppable:{...jr.droppable,...null==j?void 0:j.droppable},dragOverlay:{...jr.dragOverlay,...null==j?void 0:j.dragOverlay}}),[null==j?void 0:j.draggable,null==j?void 0:j.droppable,null==j?void 0:j.dragOverlay]),{droppableRects:en,measureDroppableContainers:ei,measuringScheduled:ea}=function(e,r){let{dragging:s,dependencies:n,config:i}=r,[a,o]=(0,$.useState)(null),{frequency:l,measure:c,strategy:d}=i,u=(0,$.useRef)(e),h=function(){switch(d){case F.Always:return!1;case F.BeforeDragging:return s;default:return!s}}(),f=_4(h),p=(0,$.useCallback)(function(e){void 0===e&&(e=[]),f.current||o(r=>null===r?e:r.concat(e.filter(e=>!r.includes(e))))},[f]),m=(0,$.useRef)(null),g=_6(r=>{if(h&&!s)return S1;if(!r||r===S1||u.current!==e||null!=a){let r=new Map;for(let s of e){if(!s)continue;if(a&&a.length>0&&!a.includes(s.id)&&s.rect.current){r.set(s.id,s.rect.current);continue}let e=s.node.current,n=e?new S$(c(e),e):null;s.rect.current=n,n&&r.set(s.id,n)}return r}return r},[e,a,s,h,c]);return(0,$.useEffect)(()=>{u.current=e},[e]),(0,$.useEffect)(()=>{h||p()},[s,h]),(0,$.useEffect)(()=>{a&&a.length>0&&o(null)},[JSON.stringify(a)]),(0,$.useEffect)(()=>{h||"number"!=typeof l||null!==m.current||(m.current=setTimeout(()=>{p(),m.current=null},l))},[l,h,p,...n]),{droppableRects:g,measureDroppableContainers:p,measuringScheduled:null!=a}}(er,{dragging:B,dependencies:[H.x,H.y],config:es.droppable}),eo=_6(e=>{var r;return null==z?null:null!=(r=null!=p?p:e)?r:null},[p=(f=null!=z?W.get(z):void 0)?f.node.current:null,z]),el=(0,$.useMemo)(()=>J?Si(J):null,[J]),ec=(d=(null==Y?void 0:Y.autoScrollEnabled)===!1,u="object"==typeof b?!1===b.enabled:!1===b,h=B&&!d&&!u,"object"==typeof b?{...b,enabled:h}:{enabled:h}),ed=S2(eo,es.draggable.measure);!function(e){let{activeNode:r,measure:s,initialRect:n,config:i=!0}=e,a=(0,$.useRef)(!1),{x:o,y:l}="boolean"==typeof i?{x:i,y:i}:i;_5(()=>{if(!o&&!l||!r){a.current=!1;return}if(a.current||!n)return;let e=null==r?void 0:r.node.current;if(!e||!1===e.isConnected)return;let i=Sk(s(e),n);if(o||(i.x=0),l||(i.y=0),a.current=!0,Math.abs(i.x)>0||Math.abs(i.y)>0){let r=ST(e);r&&r.scrollBy({top:i.y,left:i.x})}},[r,o,l,n,s])}({activeNode:null!=z?W.get(z):null,config:ec.layoutShiftCompensation,initialRect:ed,measure:es.draggable.measure});let eu=S4(eo,es.draggable.measure,ed),eh=S4(eo?eo.parentElement:null),ef=(0,$.useRef)({activatorEvent:null,active:null,activeNode:eo,collisionRect:null,collisions:null,droppableRects:en,draggableNodes:W,draggingNode:null,draggingNodeRect:null,droppableContainers:U,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ep=U.getNodeFor(null==(r=ef.current.over)?void 0:r.id),em=function(e){let{measure:r}=e,[s,n]=(0,$.useState)(null),i=S5({callback:(0,$.useCallback)(e=>{for(let{target:s}of e)if(_0(s)){n(e=>{let n=r(s);return e?{...e,width:n.width,height:n.height}:n});break}},[r])}),[a,o]=_7((0,$.useCallback)(e=>{let s=function(e){if(!e)return null;if(e.children.length>1)return e;let r=e.children[0];return _0(r)?r:e}(e);null==i||i.disconnect(),s&&(null==i||i.observe(s)),n(s?r(s):null)},[r,i]));return(0,$.useMemo)(()=>({nodeRef:a,rect:s,setRef:o}),[s,a,o])}({measure:es.dragOverlay.measure}),eg=null!=(s=em.nodeRef.current)?s:eo,ex=B?null!=(n=em.rect)?n:eu:null,ev=!!(em.nodeRef.current&&em.rect),ey=(m=S2(a=ev?null:eu),Sk(a,m)),eb=S8(eg?_Z(eg):null),ew=(o=B?null!=ep?ep:eo:null,g=(0,$.useRef)(o),x=_6(e=>o?e&&e!==S6&&o&&g.current&&o.parentNode===g.current.parentNode?e:SR(o):S6,[o]),(0,$.useEffect)(()=>{g.current=o},[o]),x),e_=function(e,r){void 0===r&&(r=SE);let[s]=e,n=S8(s?_Z(s):null),[i,a]=(0,$.useState)(S9);function o(){a(()=>e.length?e.map(e=>SP(e)?n:new S$(r(e),e)):S9)}let l=S5({callback:o});return _5(()=>{null==l||l.disconnect(),o(),e.forEach(e=>null==l?void 0:l.observe(e))},[e]),i}(ew),eS=function(e,r){let{transform:s,...n}=r;return null!=e&&e.length?e.reduce((e,r)=>r({transform:e,...n}),s):s}(k,{transform:{x:H.x-ey.x,y:H.y-ey.y,scaleX:1,scaleY:1},activatorEvent:J,active:V,activeNodeRect:eu,containerNodeRect:eh,draggingNodeRect:ex,over:ef.current.over,overlayNodeRect:em.rect,scrollableAncestors:ew,scrollableAncestorRects:e_,windowRect:eb}),ej=el?Sr(el,H):null,ek=function(e){let[r,s]=(0,$.useState)(null),n=(0,$.useRef)(e),i=(0,$.useCallback)(e=>{let r=SA(e.target);r&&s(e=>e?(e.set(r,SF(r)),new Map(e)):null)},[]);return(0,$.useEffect)(()=>{let r=n.current;if(e!==r){a(r);let o=e.map(e=>{let r=SA(e);return r?(r.addEventListener("scroll",i,{passive:!0}),[r,SF(r)]):null}).filter(e=>null!=e);s(o.length?new Map(o):null),n.current=e}return()=>{a(e),a(r)};function a(e){e.forEach(e=>{let r=SA(e);null==r||r.removeEventListener("scroll",i)})}},[i,e]),(0,$.useMemo)(()=>e.length?r?Array.from(r.values()).reduce((e,r)=>Sr(e,r),Sx):SB(e):Sx,[e,r])}(ew),eC=S7(ek),eN=S7(ek,[eu]),eE=Sr(eS,eC),eD=ex?SC(ex,eS):null,eR=V&&eD?S({active:V,collisionRect:eD,droppableRects:en,droppableContainers:er,pointerCoordinates:ej}):null,eT=S_(eR,"id"),[eA,eI]=(0,$.useState)(null),eM=(l=ev?eS:Sr(eS,eN),c=null!=(i=null==eA?void 0:eA.rect)?i:null,{...l,scaleX:c&&eu?c.width/eu.width:1,scaleY:c&&eu?c.height/eu.height:1}),eF=(0,$.useRef)(null),eP=(0,$.useCallback)((e,r)=>{let{sensor:s,options:n}=r;if(null==X.current)return;let i=W.get(X.current);if(!i)return;let a=e.nativeEvent,o=new s({active:X.current,activeNode:i,event:a,options:n,context:ef,onAbort(e){if(!W.get(e))return;let{onDragAbort:r}=Q.current,s={id:e};null==r||r(s),T({type:"onDragAbort",event:s})},onPending(e,r,s,n){if(!W.get(e))return;let{onDragPending:i}=Q.current,a={id:e,constraint:r,initialCoordinates:s,offset:n};null==i||i(a),T({type:"onDragPending",event:a})},onStart(e){let r=X.current;if(null==r)return;let s=W.get(r);if(!s)return;let{onDragStart:n}=Q.current,i={activatorEvent:a,active:{id:r,data:s.data,rect:K}};(0,ee.unstable_batchedUpdates)(()=>{null==n||n(i),O(L.Initializing),R({type:E.DragStart,initialCoordinates:e,active:r}),T({type:"onDragStart",event:i}),G(eF.current),Z(a)})},onMove(e){R({type:E.DragMove,coordinates:e})},onEnd:l(E.DragEnd),onCancel:l(E.DragCancel)});function l(e){return async function(){let{active:r,collisions:s,over:n,scrollAdjustedTranslate:i}=ef.current,o=null;if(r&&i){let{cancelDrop:l}=Q.current;o={activatorEvent:a,active:r,collisions:s,delta:i,over:n},e===E.DragEnd&&"function"==typeof l&&await Promise.resolve(l(o))&&(e=E.DragCancel)}X.current=null,(0,ee.unstable_batchedUpdates)(()=>{R({type:e}),O(L.Uninitialized),eI(null),G(null),Z(null),eF.current=null;let r=e===E.DragEnd?"onDragEnd":"onDragCancel";if(o){let e=Q.current[r];null==e||e(o),T({type:r,event:o})}})}}eF.current=o},[W]),eL=(0,$.useCallback)((e,r)=>(s,n)=>{let i=s.nativeEvent,a=W.get(n);null!==X.current||!a||i.dndKit||i.defaultPrevented||!0===e(s,r.options,{active:a})&&(i.dndKit={capturedBy:r.sensor},X.current=n,eP(s,r))},[W,eP]),eO=(0,$.useMemo)(()=>_.reduce((e,r)=>{let{sensor:s}=r;return[...e,...s.activators.map(e=>({eventName:e.eventName,handler:eL(e.handler,r)}))]},[]),[_,eL]);(0,$.useEffect)(()=>{if(!_Y)return;let e=_.map(e=>{let{sensor:r}=e;return null==r.setup?void 0:r.setup()});return()=>{for(let r of e)null==r||r()}},_.map(e=>{let{sensor:r}=e;return r})),_5(()=>{eu&&P===L.Initializing&&O(L.Initialized)},[eu,P]),(0,$.useEffect)(()=>{let{onDragMove:e}=Q.current,{active:r,activatorEvent:s,collisions:n,over:i}=ef.current;if(!r||!s)return;let a={active:r,activatorEvent:s,collisions:n,delta:{x:eE.x,y:eE.y},over:i};(0,ee.unstable_batchedUpdates)(()=>{null==e||e(a),T({type:"onDragMove",event:a})})},[eE.x,eE.y]),(0,$.useEffect)(()=>{let{active:e,activatorEvent:r,collisions:s,droppableContainers:n,scrollAdjustedTranslate:i}=ef.current;if(!e||null==X.current||!r||!i)return;let{onDragOver:a}=Q.current,o=n.get(eT),l=o&&o.rect.current?{id:o.id,rect:o.rect.current,data:o.data,disabled:o.disabled}:null,c={active:e,activatorEvent:r,collisions:s,delta:{x:i.x,y:i.y},over:l};(0,ee.unstable_batchedUpdates)(()=>{eI(l),null==a||a(c),T({type:"onDragOver",event:c})})},[eT]),_5(()=>{ef.current={activatorEvent:J,active:V,activeNode:eo,collisionRect:eD,collisions:eR,droppableRects:en,draggableNodes:W,draggingNode:eg,draggingNodeRect:ex,droppableContainers:U,over:eA,scrollableAncestors:ew,scrollAdjustedTranslate:eE},K.current={initial:ex,translated:eD}},[V,eo,eR,eD,W,eg,ex,en,U,eA,ew,eE]),function(e){let r,{acceleration:s,activator:n=I.Pointer,canScroll:i,draggingRect:a,enabled:o,interval:l=5,order:c=M.TreeOrder,pointerCoordinates:d,scrollableAncestors:u,scrollableAncestorRects:h,delta:f,threshold:p}=e,m=function(e){let{delta:r,disabled:s}=e,n=_8(r);return _6(e=>{if(s||!n||!e)return S0;let i={x:Math.sign(r.x-n.x),y:Math.sign(r.y-n.y)};return{x:{[D.Backward]:e.x[D.Backward]||-1===i.x,[D.Forward]:e.x[D.Forward]||1===i.x},y:{[D.Backward]:e.y[D.Backward]||-1===i.y,[D.Forward]:e.y[D.Forward]||1===i.y}}},[s,r,n])}({delta:f,disabled:!o}),[g,x]=(r=(0,$.useRef)(null),[(0,$.useCallback)((e,s)=>{r.current=setInterval(e,s)},[]),(0,$.useCallback)(()=>{null!==r.current&&(clearInterval(r.current),r.current=null)},[])]),v=(0,$.useRef)({x:0,y:0}),y=(0,$.useRef)({x:0,y:0}),b=(0,$.useMemo)(()=>{switch(n){case I.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case I.DraggableRect:return a}},[n,a,d]),w=(0,$.useRef)(null),_=(0,$.useCallback)(()=>{let e=w.current;if(!e)return;let r=v.current.x*y.current.x,s=v.current.y*y.current.y;e.scrollBy(r,s)},[]),S=(0,$.useMemo)(()=>c===M.TreeOrder?[...u].reverse():u,[c,u]);(0,$.useEffect)(()=>{if(!o||!u.length||!b)return void x();for(let e of S){if((null==i?void 0:i(e))===!1)continue;let r=h[u.indexOf(e)];if(!r)continue;let{direction:n,speed:a}=function(e,r,s,n,i){let{top:a,left:o,right:l,bottom:c}=s;void 0===n&&(n=10),void 0===i&&(i=SO);let{isTop:d,isBottom:u,isLeft:h,isRight:f}=SL(e),p={x:0,y:0},m={x:0,y:0},g={height:r.height*i.y,width:r.width*i.x};return!d&&a<=r.top+g.height?(p.y=D.Backward,m.y=n*Math.abs((r.top+g.height-a)/g.height)):!u&&c>=r.bottom-g.height&&(p.y=D.Forward,m.y=n*Math.abs((r.bottom-g.height-c)/g.height)),!f&&l>=r.right-g.width?(p.x=D.Forward,m.x=n*Math.abs((r.right-g.width-l)/g.width)):!h&&o<=r.left+g.width&&(p.x=D.Backward,m.x=n*Math.abs((r.left+g.width-o)/g.width)),{direction:p,speed:m}}(e,r,b,s,p);for(let e of["x","y"])m[e][n[e]]||(a[e]=0,n[e]=0);if(a.x>0||a.y>0){x(),w.current=e,g(_,l),v.current=a,y.current=n;return}}v.current={x:0,y:0},y.current={x:0,y:0},x()},[s,_,i,x,o,l,JSON.stringify(b),JSON.stringify(m),g,u,S,h,JSON.stringify(p)])}({...ec,delta:H,draggingRect:eD,pointerCoordinates:ej,scrollableAncestors:ew,scrollableAncestorRects:e_});let eB=(0,$.useMemo)(()=>({active:V,activeNode:eo,activeNodeRect:eu,activatorEvent:J,collisions:eR,containerNodeRect:eh,dragOverlay:em,draggableNodes:W,droppableContainers:U,droppableRects:en,over:eA,measureDroppableContainers:ei,scrollableAncestors:ew,scrollableAncestorRects:e_,measuringConfiguration:es,measuringScheduled:ea,windowRect:eb}),[V,eo,eu,J,eR,eh,em,W,U,en,eA,ei,ew,e_,es,ea,eb]),ez=(0,$.useMemo)(()=>({activatorEvent:J,activators:eO,active:V,activeNodeRect:eu,ariaDescribedById:{draggable:et},dispatch:R,draggableNodes:W,over:eA,measureDroppableContainers:ei}),[J,eO,V,eu,R,et,W,eA,ei]);return $.default.createElement(Su.Provider,{value:A},$.default.createElement(ja.Provider,{value:ez},$.default.createElement(jo.Provider,{value:eB},$.default.createElement(ju.Provider,{value:eM},w)),$.default.createElement(jd,{disabled:(null==y?void 0:y.restoreFocus)===!1})),$.default.createElement(Sp,{...y,hiddenTextDescribedById:et}))}),jf=(0,$.createContext)(null),jp="button",jm={timeout:25},jg={position:"fixed",touchAction:"none"},jx=e=>Sn(e)?"transform 250ms ease":void 0;function jv(e,r,s){let n=e.slice();return n.splice(s<0?n.length+s:s,0,n.splice(r,1)[0]),n}function jy(e){return null!==e&&e>=0}(e,r)=>{let{as:s,activatorEvent:n,adjustScale:i,children:a,className:o,rect:l,style:c,transform:d,transition:u=jx}=e;if(!l)return null;let h=i?d:{...d,scaleX:1,scaleY:1},f={...jg,width:l.width,height:l.height,top:l.top,left:l.left,transform:Sa.Transform.toString(h),transformOrigin:i&&n?function(e,r){let s=Si(e);if(!s)return"0 0";let n={x:(s.x-r.left)/r.width*100,y:(s.y-r.top)/r.height*100};return n.x+"% "+n.y+"%"}(n,l):void 0,transition:"function"==typeof u?u(n):u,...c};return $.default.createElement(s,{className:o,style:f,ref:r},a)},x={styles:{active:{opacity:"0"}}};let jb=e=>{let{rects:r,activeIndex:s,overIndex:n,index:i}=e,a=jv(r,n,s),o=r[i],l=a[i];return l&&o?{x:l.left-o.left,y:l.top-o.top,scaleX:l.width/o.width,scaleY:l.height/o.height}:null},jw={scaleX:1,scaleY:1},j_=e=>{var r,s,n,i;let a,o,l,{activeIndex:c,activeNodeRect:d,index:u,rects:h,overIndex:f}=e,p=null!=(r=h[c])?r:d;if(!p)return null;if(u===c){let e=h[f];return e?{x:0,y:c<f?e.top+e.height-(p.top+p.height):e.top-p.top,...jw}:null}let m=(s=h,n=u,i=c,a=s[n],o=s[n-1],l=s[n+1],a?i<n?o?a.top-(o.top+o.height):l?l.top-(a.top+a.height):0:l?l.top-(a.top+a.height):o?a.top-(o.top+o.height):0:0);return u>c&&u<=f?{x:0,y:-p.height-m,...jw}:u<c&&u>=f?{x:0,y:p.height+m,...jw}:{x:0,y:0,...jw}},jS="Sortable",jj=$.default.createContext({activeIndex:-1,containerId:jS,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:jb,disabled:{draggable:!1,droppable:!1}});function jk(e){let{children:r,id:s,items:n,strategy:i=jb,disabled:a=!1}=e,{active:o,dragOverlay:l,droppableRects:c,over:d,measureDroppableContainers:u}=(0,$.useContext)(jo),h=Se(jS,s),f=null!==l.rect,p=(0,$.useMemo)(()=>n.map(e=>"object"==typeof e&&"id"in e?e.id:e),[n]),m=null!=o,g=o?p.indexOf(o.id):-1,x=d?p.indexOf(d.id):-1,v=(0,$.useRef)(p),y=!function(e,r){if(e===r)return!0;if(e.length!==r.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==r[s])return!1;return!0}(p,v.current),b=-1!==x&&-1===g||y,w="boolean"==typeof a?{draggable:a,droppable:a}:a;_5(()=>{y&&m&&u(p)},[y,p,m,u]),(0,$.useEffect)(()=>{v.current=p},[p]);let _=(0,$.useMemo)(()=>({activeIndex:g,containerId:h,disabled:w,disableTransforms:b,items:p,overIndex:x,useDragOverlay:f,sortedRects:p.reduce((e,r,s)=>{let n=c.get(r);return n&&(e[s]=n),e},Array(p.length)),strategy:i}),[g,h,w.draggable,w.droppable,b,p,x,c,f,i]);return $.default.createElement(jj.Provider,{value:_},r)}let jC=e=>{let{id:r,items:s,activeIndex:n,overIndex:i}=e;return jv(s,n,i).indexOf(r)},jN=e=>{let{containerId:r,isSorting:s,wasDragging:n,index:i,items:a,newIndex:o,previousItems:l,previousContainerId:c,transition:d}=e;return!!d&&!!n&&(l===a||i!==o)&&(!!s||o!==i&&r===c)},jE={duration:200,easing:"ease"},jD="transform",jR=Sa.Transition.toString({property:jD,duration:0,easing:"linear"}),jT={roleDescription:"sortable"};function jA(e){if(!e)return!1;let r=e.data.current;return!!r&&"sortable"in r&&"object"==typeof r.sortable&&"containerId"in r.sortable&&"items"in r.sortable&&"index"in r.sortable}let jI=[T.Down,T.Right,T.Up,T.Left],jM=(e,r)=>{let{context:{active:s,collisionRect:n,droppableRects:i,droppableContainers:a,over:o,scrollableAncestors:l}}=r;if(jI.includes(e.code)){if(e.preventDefault(),!s||!n)return;let r=[];a.getEnabled().forEach(s=>{if(!s||null!=s&&s.disabled)return;let a=i.get(s.id);if(a)switch(e.code){case T.Down:n.top<a.top&&r.push(s);break;case T.Up:n.top>a.top&&r.push(s);break;case T.Left:n.left>a.left&&r.push(s);break;case T.Right:n.left<a.left&&r.push(s)}});let u=(e=>{let{collisionRect:r,droppableRects:s,droppableContainers:n}=e,i=Sw(r),a=[];for(let e of n){let{id:r}=e,n=s.get(r);if(n){let s=Sw(n),o=Number((i.reduce((e,r,n)=>e+Sv(s[n],r),0)/4).toFixed(4));a.push({id:r,data:{droppableContainer:e,value:o}})}}return a.sort(Sy)})({active:s,collisionRect:n,droppableRects:i,droppableContainers:r,pointerCoordinates:null}),h=S_(u,"id");if(h===(null==o?void 0:o.id)&&u.length>1&&(h=u[1].id),null!=h){let e=a.get(s.id),r=a.get(h),o=r?i.get(r.id):null,u=null==r?void 0:r.node.current;if(u&&o&&e&&r){var c,d;let s=SR(u).some((e,r)=>l[r]!==e),i=jF(e,r),a=(c=e,d=r,!!jA(c)&&!!jA(d)&&!!jF(c,d)&&c.data.current.sortable.index<d.data.current.sortable.index),h=s||!i?{x:0,y:0}:{x:a?n.width-o.width:0,y:a?n.height-o.height:0},f={x:o.left,y:o.top};return h.x&&h.y?f:Ss(f,h)}}}};function jF(e,r){return!!jA(e)&&!!jA(r)&&e.data.current.sortable.containerId===r.data.current.sortable.containerId}function jP({executor:e,executorMode:r,locateQuery:s=null,locateMatch:n=!1,keyboardSelected:i=!1,isOpen:a,onOpenChange:o,onStart:l,onStop:c,onUpdate:d,onDelete:u,onProcessFinished:h}){let f,p,m,g,x,v,y,[b,w]=(0,$.useState)(!1),[_,S]=(0,$.useState)(e.currentProcessId??e.lastProcessId),j=(0,$.useRef)(!1),k=(0,$.useRef)(e.currentProcessId),{attributes:C,listeners:N,setNodeRef:D,transform:R,transition:T,isDragging:A}=function(e){var r,s,n,i;let{animateLayoutChanges:a=jN,attributes:o,disabled:l,data:c,getNewIndex:d=jC,id:u,strategy:h,resizeObserverConfig:f,transition:p=jE}=e,{items:m,containerId:g,activeIndex:x,disabled:v,disableTransforms:y,sortedRects:b,overIndex:w,useDragOverlay:_,strategy:S}=(0,$.useContext)(jj),j=(r=l,s=v,"boolean"==typeof r?{draggable:r,droppable:!1}:{draggable:null!=(n=null==r?void 0:r.draggable)?n:s.draggable,droppable:null!=(i=null==r?void 0:r.droppable)?i:s.droppable}),k=m.indexOf(u),C=(0,$.useMemo)(()=>({sortable:{containerId:g,index:k,items:m},...c}),[g,c,k,m]),N=(0,$.useMemo)(()=>m.slice(m.indexOf(u)),[m,u]),{rect:D,node:R,isOver:T,setNodeRef:A}=function(e){let{data:r,disabled:s=!1,id:n,resizeObserverConfig:i}=e,a=Se("Droppable"),{active:o,dispatch:l,over:c,measureDroppableContainers:d}=(0,$.useContext)(ja),u=(0,$.useRef)({disabled:s}),h=(0,$.useRef)(!1),f=(0,$.useRef)(null),p=(0,$.useRef)(null),{disabled:m,updateMeasurementsFor:g,timeout:x}={...jm,...i},v=_4(null!=g?g:n),y=S5({callback:(0,$.useCallback)(()=>{if(!h.current){h.current=!0;return}null!=p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{d(Array.isArray(v.current)?v.current:[v.current]),p.current=null},x)},[x]),disabled:m||!o}),[b,w]=_7((0,$.useCallback)((e,r)=>{y&&(r&&(y.unobserve(r),h.current=!1),e&&y.observe(e))},[y])),_=_4(r);return(0,$.useEffect)(()=>{y&&b.current&&(y.disconnect(),h.current=!1,y.observe(b.current))},[b,y]),(0,$.useEffect)(()=>(l({type:E.RegisterDroppable,element:{id:n,key:a,disabled:s,node:b,rect:f,data:_}}),()=>l({type:E.UnregisterDroppable,key:a,id:n})),[n]),(0,$.useEffect)(()=>{s!==u.current.disabled&&(l({type:E.SetDroppableDisabled,id:n,key:a,disabled:s}),u.current.disabled=s)},[n,a,s,l]),{active:o,rect:f,isOver:(null==c?void 0:c.id)===n,node:b,over:c,setNodeRef:w}}({id:u,data:C,disabled:j.droppable,resizeObserverConfig:{updateMeasurementsFor:N,...f}}),{active:I,activatorEvent:M,activeNodeRect:F,attributes:P,setNodeRef:L,listeners:O,isDragging:B,over:z,setActivatorNodeRef:W,transform:H}=function(e){let{id:r,data:s,disabled:n=!1,attributes:i}=e,a=Se("Draggable"),{activators:o,activatorEvent:l,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:f}=(0,$.useContext)(ja),{role:p=jp,roleDescription:m="draggable",tabIndex:g=0}=null!=i?i:{},x=(null==c?void 0:c.id)===r,v=(0,$.useContext)(x?ju:jf),[y,b]=_7(),[w,_]=_7(),S=(0,$.useMemo)(()=>o.reduce((e,s)=>{let{eventName:n,handler:i}=s;return e[n]=e=>{i(e,r)},e},{}),[o,r]),j=_4(s);return _5(()=>(h.set(r,{id:r,key:a,node:y,activatorNode:w,data:j}),()=>{let e=h.get(r);e&&e.key===a&&h.delete(r)}),[h,r]),{active:c,activatorEvent:l,activeNodeRect:d,attributes:(0,$.useMemo)(()=>({role:p,tabIndex:g,"aria-disabled":n,"aria-pressed":!!x&&p===jp||void 0,"aria-roledescription":m,"aria-describedby":u.draggable}),[n,p,g,x,m,u.draggable]),isDragging:x,listeners:n?void 0:S,node:y,over:f,setNodeRef:b,setActivatorNodeRef:_,transform:v}}({id:u,data:C,attributes:{...jT,...o},disabled:j.draggable}),U=function(){for(var e=arguments.length,r=Array(e),s=0;s<e;s++)r[s]=arguments[s];return(0,$.useMemo)(()=>e=>{r.forEach(r=>r(e))},r)}(A,L),q=!!I,K=q&&!y&&jy(x)&&jy(w),V=!_&&B,X=V&&K?H:null,Y=K?null!=X?X:(null!=h?h:S)({rects:b,activeNodeRect:F,activeIndex:x,overIndex:w,index:k}):null,G=jy(x)&&jy(w)?d({id:u,items:m,activeIndex:x,overIndex:w}):k,J=null==I?void 0:I.id,Z=(0,$.useRef)({activeId:J,items:m,newIndex:G,containerId:g}),Q=m!==Z.current.items,ee=a({active:I,containerId:g,isDragging:B,isSorting:q,id:u,index:k,items:m,newIndex:Z.current.newIndex,previousItems:Z.current.items,previousContainerId:Z.current.containerId,transition:p,wasDragging:null!=Z.current.activeId}),et=function(e){let{disabled:r,index:s,node:n,rect:i}=e,[a,o]=(0,$.useState)(null),l=(0,$.useRef)(s);return _5(()=>{if(!r&&s!==l.current&&n.current){let e=i.current;if(e){let r=SE(n.current,{ignoreTransform:!0}),s={x:e.left-r.left,y:e.top-r.top,scaleX:e.width/r.width,scaleY:e.height/r.height};(s.x||s.y)&&o(s)}}s!==l.current&&(l.current=s)},[r,s,n,i]),(0,$.useEffect)(()=>{a&&o(null)},[a]),a}({disabled:!ee,index:k,node:R,rect:D});return(0,$.useEffect)(()=>{q&&Z.current.newIndex!==G&&(Z.current.newIndex=G),g!==Z.current.containerId&&(Z.current.containerId=g),m!==Z.current.items&&(Z.current.items=m)},[q,G,g,m]),(0,$.useEffect)(()=>{if(J===Z.current.activeId)return;if(null!=J&&null==Z.current.activeId){Z.current.activeId=J;return}let e=setTimeout(()=>{Z.current.activeId=J},50);return()=>clearTimeout(e)},[J]),{active:I,activeIndex:x,attributes:P,data:C,rect:D,index:k,newIndex:G,items:m,isOver:T,isSorting:q,isDragging:B,listeners:O,node:R,overIndex:w,over:z,setNodeRef:U,setActivatorNodeRef:W,setDroppableNodeRef:A,setDraggableNodeRef:L,transform:null!=et?et:Y,transition:et||Q&&Z.current.newIndex===k?jR:(!V||Sn(M))&&p&&(q||ee)?Sa.Transition.toString({...p,property:jD}):void 0}}({id:e.id}),I={transform:Sa.Translate.toString(R),transition:T,zIndex:A?50:void 0,position:A?"relative":void 0,opacity:A?1:void 0},{logs:M,status:F,exitCode:P,isPty:L,replayingHistory:O,sendInput:B,sendResize:H}=(f=function(){let e=(0,$.useContext)(_V);if(!e)throw Error("useExecutorLogsStore must be used within ExecutorLogsProvider");return e}(),p=(0,$.useCallback)(e=>{if(!_)return()=>{};f.subscribeProcess(_);let r=f.onProcessChange(_,e);return()=>{r(),f.unsubscribeProcess(_)}},[_,r,f]),m=(0,$.useCallback)(()=>_?f.getProcessState(_):null,[_,f]),g=(0,$.useSyncExternalStore)(p,m,m),x=(0,$.useCallback)(()=>{},[]),v=(0,$.useCallback)(e=>{_&&f.sendInput(_,e)},[_,f]),y=(0,$.useCallback)((e,r)=>{_&&f.sendResize(_,e,r)},[_,f]),{logs:g?.logs??[],status:g?.status??"closed",exitCode:g?.exitCode??null,isPty:g?.isPty??!1,replayingHistory:g?.replayingHistory??!0,clearLogs:x,sendInput:v,sendResize:y});(0,$.useEffect)(()=>{let r=k.current;k.current=e.currentProcessId,e.currentProcessId&&e.currentProcessId!==r&&(S(e.currentProcessId),j.current=!1,o(!0))},[e.currentProcessId,o]),(0,$.useEffect)(()=>{e.currentProcessId||e.lastProcessId&&S(r=>r??e.lastProcessId)},[e.currentProcessId,e.lastProcessId]),(0,$.useEffect)(()=>{"closed"!==F||null===P||j.current||(j.current=!0,h(_))},[F,P,_,h]);let U=async()=>{console.log(`[ExecutorItem] Starting executor ${e.id}`),j.current=!1;let r=await l();console.log(`[ExecutorItem] Got processId: ${r}`),r&&(S(r),o(!0))},q=async()=>{await c(_||void 0)},K=e.isRunning,V=e.isDisabled,X=e.lastStartedAt?new Date(e.lastStartedAt).toLocaleString(void 0,{dateStyle:"short",timeStyle:"short"}):null;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(gV,{open:a,onOpenChange:o,children:(0,z.jsxs)("div",{ref:D,style:I,"data-locate-id":e.id,className:(0,eb.cn)("border rounded-lg",A&&"shadow-lg bg-background",null!==s&&!n&&"opacity-40",null!==s&&n&&"bg-muted/50",i&&"border-primary/60"),children:[(0,z.jsx)(gX,{asChild:!0,children:(0,z.jsxs)("div",{className:"group flex items-center justify-between p-3 cursor-pointer hover:bg-muted/50",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)("button",{type:"button",className:"cursor-grab touch-none text-muted-foreground hover:text-foreground",...C,...N,onClick:e=>e.stopPropagation(),children:(0,z.jsx)(dW,{className:"h-4 w-4"})}),a?(0,z.jsx)(n6,{className:"h-4 w-4"}):(0,z.jsx)(nV,{className:"h-4 w-4"}),(0,z.jsx)("span",{className:(0,eb.cn)("font-medium",V&&"text-muted-foreground line-through"),children:null!==s&&n?(0,z.jsx)(dN,{text:e.name,query:s}):e.name}),V?(0,z.jsxs)(so,{variant:"outline",className:"text-muted-foreground border-muted-foreground/40 gap-1",children:[(0,z.jsx)(gJ,{className:"h-3 w-3"}),"Disabled"]}):(0,z.jsx)(so,{variant:K?"default":"secondary",className:(0,eb.cn)(K&&"bg-green-600 hover:bg-green-600"),children:K?"Running":null!==P?0===P?"Completed":"Failed":"Stopped"})]}),(0,z.jsxs)("div",{className:"flex items-center gap-2",onClick:e=>e.stopPropagation(),children:[X&&(0,z.jsxs)("span",{className:"text-xs text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity",title:new Date(e.lastStartedAt).toLocaleString(),children:["Last run: ",X]}),K?(0,z.jsxs)(W.Button,{size:"sm",variant:"destructive",onClick:q,"data-locate-action":!0,className:"w-20 border border-destructive",children:[(0,z.jsx)(lG,{className:"h-3 w-3 mr-1"}),"Stop"]}):(0,z.jsxs)(W.Button,{size:"sm",onClick:U,disabled:V,title:V?"Executor is disabled":void 0,"data-locate-action":!0,className:"w-20",children:[(0,z.jsx)(rf,{className:"h-3 w-3 mr-1"}),"Start"]}),(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)(W.Button,{size:"icon",variant:"ghost",className:"h-8 w-8",children:(0,z.jsx)(gG,{className:"h-4 w-4"})})}),(0,z.jsxs)(o1,{align:"end",children:[(0,z.jsxs)(o2,{onClick:()=>w(!0),children:[(0,z.jsx)(rx,{className:"h-4 w-4 mr-2"}),"Edit"]}),(0,z.jsx)(o2,{onClick:()=>d({target:r??"local",disabled:!V}),children:V?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(sZ,{className:"h-4 w-4 mr-2"}),"Enable"]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(gJ,{className:"h-4 w-4 mr-2"}),"Disable"]})}),(0,z.jsxs)(o2,{onClick:u,className:"text-destructive",children:[(0,z.jsx)(rd,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})]})}),(0,z.jsx)(gY,{children:(0,z.jsxs)("div",{className:"px-3 pb-3",children:[(0,z.jsx)("div",{className:"text-xs text-muted-foreground mb-2 font-mono",children:"prompt"===e.executor_type?`${e.prompt_provider??"claude"} → ${e.command}`:`$ ${e.command}`}),(0,z.jsx)(_H,{logs:M,isPty:L,onInput:B,onResize:H,muteInput:O,processId:_,executorId:e.id,target:r??"local",status:F,exitCode:P})]})})]})}),(0,z.jsx)(_q,{open:b,onOpenChange:w,executor:e,onSubmit:async e=>{await d(e)}})]})}let jL=[];function jO({targets:e,activeTarget:r,onTargetChange:s,onAddRemote:n,disabled:i}){if(e.length<=2)return(0,z.jsx)("div",{className:"inline-flex items-center rounded-md border bg-muted/50 px-0.5 text-xs",children:e.map(e=>{let n=e.icon;return(0,z.jsxs)("button",{onClick:()=>s(e.id),disabled:i,className:(0,eb.cn)("inline-flex items-center gap-1 rounded-sm px-2 py-0.5 transition-colors",r===e.id?"bg-primary text-primary-foreground font-medium shadow-sm":"text-muted-foreground hover:text-foreground",i&&"opacity-50 cursor-not-allowed"),children:[n&&(0,z.jsx)(n,{className:"h-3 w-3"}),e.label]},e.id)})});let a=e.find(e=>e.id===r)??e[0],o=a?.icon;return(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsxs)("button",{disabled:i,className:(0,eb.cn)("inline-flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-0.5 text-xs font-medium transition-colors hover:bg-muted",i&&"opacity-50 cursor-not-allowed"),children:[o&&(0,z.jsx)(o,{className:"h-3 w-3"}),a?.label??"Local",(0,z.jsx)(n6,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,z.jsxs)(o1,{align:"start",children:[(0,z.jsx)(o3,{value:r,onValueChange:s,children:e.map(e=>{let r=e.icon;return(0,z.jsxs)(o4,{value:e.id,className:"text-xs",children:[r&&(0,z.jsx)(r,{className:"h-3 w-3"}),e.label]},e.id)})}),n&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(o7,{}),(0,z.jsxs)(o2,{onClick:n,className:"text-xs",children:[(0,z.jsx)(eS,{className:"h-3 w-3"}),"Add Remote"]})]})]})]})}let jB=new WeakMap,jz=e=>{let{droppableContainers:r,pointerCoordinates:s}=e;if(!s)return(e=>{let{collisionRect:r,droppableRects:s,droppableContainers:n}=e,i=SS(r,r.left,r.top),a=[];for(let e of n){let{id:r}=e,n=s.get(r);if(n){let s=Sv(SS(n),i);a.push({id:r,data:{droppableContainer:e,value:s}})}}return a.sort(Sy)})(e);let n=[];for(let e of r){let r=e.rect.current;if(!r)continue;let i=r.top,a=r.top+52;s.x>=r.left&&s.x<=r.right&&s.y>=i&&s.y<=a&&n.push({id:e.id,data:{droppableContainer:e}})}if(n.length>0)return n;let i=null;for(let e of r){let r=e.rect.current;if(!r)continue;let n=r.top+26,a=r.left+r.width/2,o=Math.sqrt(Math.pow(s.x-a,2)+Math.pow(s.y-n,2));(!i||o<i.distance)&&(i={id:e.id,distance:o,data:{droppableContainer:e}})}return i?[{id:i.id,data:i.data}]:[]};function j$({projectId:e,selectedBranch:r,project:s,onExecutorModeChange:n,locateActive:i}){let[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(new Set),{remotes:d}=g_(),{region:u}=dD(),h=[];for(let e of(s?.path&&h.push({id:"local",label:"Local",icon:hy}),d))h.push({id:e.remote_server_id,label:e.server_name,icon:sy(e)});let{executors:f,loading:p,createExecutor:m,updateExecutor:g,deleteExecutor:x,startExecutor:v,stopExecutor:y,markProcessFinished:b,reorderExecutors:w}=function(e,r,s){let n=r??"",i=e?`${e}::${n}`:null,[a,o]=(0,$.useState)(()=>new Map),l=(null!==i?a.get(i):void 0)??jL,c=null!==i&&!a.has(i),d=(0,$.useCallback)((e,r)=>{o(s=>new Map(s).set(e,r))},[]),u=(0,$.useRef)(new Map),h=(0,$.useCallback)(e=>{let r=u.current;for(let[s,n]of r)r.set(s,e(n));o(r=>{let s=new Map;for(let[n,i]of r)s.set(n,e(i));return s})},[]),[f,p]=(0,$.useState)(new Map),[m,g]=(0,$.useState)(new Map),x=(0,$.useCallback)(async()=>{if(!e||null===i)return;let r=u.current;r.set(i,[]);try{let s=await ry.api.getExecutors(e,n),a=r.get(i)??[];r.delete(i),d(i,[...s,...a.filter(e=>!s.some(r=>r.id===e.id))])}catch(e){console.error("Failed to fetch executors:",e),r.delete(i),o(e=>e.has(i)?e:new Map(e).set(i,[]))}},[e,n,i,d]),v=(0,$.useCallback)(async()=>{try{let e=await ry.api.getRunningProcesses();console.log(`[useExecutors] fetchRunningProcesses: ${e.length} running`,e.map(e=>`${e.executor_id}/${e.id}/${e.target??"local"}`));let{runningProcesses:r,lastStartedProcess:s}=function(e){let r=new Map,s=new Map;for(let n of e){let e={processId:n.id,target:n.target??"local"},i=r.get(n.executor_id);i?i.push(e):r.set(n.executor_id,[e]),s.set(n.executor_id,e)}return{runningProcesses:r,lastStartedProcess:s}}(e);p(r),g(e=>{let n=function(e,r){let s=new Map;for(let[n,i]of e)r.get(n)?.some(e=>e.processId===i.processId&&e.target===i.target)&&s.set(n,i);return s}(e,r);for(let[e,r]of s)n.set(e,r);return n})}catch(e){console.error("Failed to fetch running processes:",e)}},[]);(0,$.useEffect)(()=>{x()},[x]),(0,$.useEffect)(()=>{e&&v()},[e,v]),(0,$.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&v()};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[v]);let y=(0,$.useRef)(new Set);(0,$.useEffect)(()=>{y.current=new Set(l.map(e=>e.id))},[l]),(0,sx.useGlobalEventStream)(r=>{if(("executor:started"===r.type||"executor:stopped"===r.type)&&console.log(`[useExecutors] SSE received: ${r.type} executor=${r.executorId} process=${r.processId} target=${r.target??"local"} project=${r.projectId}`),!e||r.projectId!==e){("executor:started"===r.type||"executor:stopped"===r.type)&&console.log(`[useExecutors] SSE filtered: projectId mismatch (event=${r.projectId}, hook=${e})`);return}if(!y.current.has(r.executorId)){("executor:started"===r.type||"executor:stopped"===r.type)&&console.log(`[useExecutors] SSE filtered: executorId ${r.executorId} not in current group (known: ${Array.from(y.current).join(",")})`);return}"executor:started"===r.type?(console.log("[useExecutors] Processing executor:started, adding to runningProcesses"),p(e=>{let s=e.get(r.executorId)??[];if(s.some(e=>e.processId===r.processId))return e;let n=new Map(e);return n.set(r.executorId,[...s,{processId:r.processId,target:r.target??"local"}]),n}),g(e=>{let s=new Map(e);return s.set(r.executorId,{processId:r.processId,target:r.target??"local"}),s}),h(e=>e.map(e=>{if(e.id!==r.executorId)return e;let s=r.target??"local";return{...e,last_runs:{...e.last_runs??{},[s]:{started_at:new Date().toISOString(),process_id:r.processId}}}}))):"executor:stopped"===r.type&&(console.log("[useExecutors] Processing executor:stopped, removing from runningProcesses"),p(e=>{let s=e.get(r.executorId);if(!s)return e;let n=s.filter(e=>e.processId!==r.processId),i=new Map(e);return 0===n.length?i.delete(r.executorId):i.set(r.executorId,n),i}),g(e=>{let s=e.get(r.executorId);if(!s||s.processId!==r.processId)return e;let n=new Map(e);return n.delete(r.executorId),n}))});let b=(0,$.useCallback)(async r=>{if(!e||null===i)return null;try{let s=await ry.api.createExecutor(e,{...r,branch:n});return u.current.get(i)?.push(s),o(e=>new Map(e).set(i,[...e.get(i)??[],s])),s}catch(e){return console.error("Failed to create executor:",e),null}},[e,n,i]),w=(0,$.useCallback)(async(e,r)=>{try{let s=await ry.api.updateExecutor(e,r);return h(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update executor:",e),gS.toast.error("Failed to update executor",{description:e instanceof Error?e.message:void 0}),null}},[h]),_=(0,$.useCallback)(async e=>{try{await ry.api.deleteExecutor(e),h(r=>r.filter(r=>r.id!==e))}catch(e){console.error("Failed to delete executor:",e)}},[h]),S=(0,$.useCallback)(async e=>{let r=s??"local",n=s=>{p(n=>{let i=n.get(e)??[];if(i.some(e=>e.processId===s))return n;let a=new Map(n);return a.set(e,[...i,{processId:s,target:r}]),a}),g(n=>{let i=new Map(n);return i.set(e,{processId:s,target:r}),i})};try{let i=await ry.api.startExecutor(e,s);return n(i),h(s=>s.map(s=>s.id!==e?s:{...s,last_runs:{...s.last_runs??{},[r]:{started_at:new Date().toISOString(),process_id:i}}})),i}catch(r){console.error("Failed to start executor:",r);let e=function(e){if(!(e instanceof ry.ExecutorProcessRequestError)||409!==e.status)return null;let{code:r,processId:s}=e.body;return"already_running"===r&&"string"==typeof s?s:null}(r);return e?(n(e),gS.toast.info("Executor is already running",{description:"Stop it before starting again."})):r instanceof ry.ExecutorProcessRequestError&&("starting"===r.body.code||"start_unknown"===r.body.code)&&gS.toast.error("Executor not started",{description:r.message}),null}},[s,h]),j=(0,$.useCallback)(async(e,r)=>{let n=f.get(e),i=n?.find(e=>e.target===(s??"local")),a=r||i?.processId;if(a){try{await ry.api.stopProcess(a)}catch(e){if(console.error("Failed to stop executor:",e),!(e instanceof ry.ExecutorProcessRequestError&&404===e.status)){gS.toast.error("Failed to stop executor",{description:`${e instanceof Error?e.message:String(e)}. The process may still be running.`}),v();return}}p(r=>{let s=r.get(e);if(!s)return r;let n=s.filter(e=>e.processId!==a),i=new Map(r);return 0===n.length?i.delete(e):i.set(e,n),i}),g(r=>{let s=r.get(e);if(!s||s.processId!==a)return r;let n=new Map(r);return n.delete(e),n})}},[f,s,v]),k=(0,$.useCallback)((e,r)=>{p(s=>{let n=s.get(e);if(!n)return s;if(r){let i=n.filter(e=>e.processId!==r);if(i.length===n.length)return s;let a=new Map(s);return 0===i.length?a.delete(e):a.set(e,i),a}let i=new Map(s);return i.delete(e),i}),g(s=>{if(!r){if(!s.has(e))return s;let r=new Map(s);return r.delete(e),r}let n=s.get(e);if(!n||n.processId!==r)return s;let i=new Map(s);return i.delete(e),i})},[]),C=(0,$.useCallback)(async r=>{if(e&&null!==i){d(i,r.map(e=>l.find(r=>r.id===e)).filter(e=>void 0!==e));try{await ry.api.reorderExecutors(e,r,n)}catch(e){console.error("Failed to reorder executors:",e),d(i,l)}}},[e,n,i,l,d]);return{executors:l.map(e=>{let r=f.get(e.id),n=s??"local",i=r?.find(e=>e.target===n),a=m.get(e.id),o=a?.target===n?a:void 0,l=e.last_runs?.[n];return{...e,currentProcessId:i?.processId??o?.processId??null,isRunning:!!i,lastProcessId:l?.process_id??null,lastStartedAt:l?.started_at??null,isDisabled:e.disabled_targets.includes(n)}}),loading:c,createExecutor:b,updateExecutor:w,deleteExecutor:_,startExecutor:S,stopExecutor:j,markProcessFinished:k,reorderExecutors:C,refetch:x}}(e,r,s?.executor_mode),_=!!(i&&f.length>0),S=_&&"right-panel"===u,j=(0,$.useCallback)(e=>{document.querySelector(`[data-locate-id="${CSS.escape(e)}"]`)?.scrollIntoView({block:"nearest"})},[]),k=(0,$.useRef)(null),C=(0,$.useCallback)(e=>{let r=k.current,s=r?.querySelector(`[data-locate-id="${CSS.escape(e)}"]`);if(!r||!s)return;let n=s.getBoundingClientRect(),i=r.getBoundingClientRect(),a=0;if(n.height>i.height?a=n.top-i.top:n.bottom>i.bottom?a=Math.max(0,Math.min(n.bottom+12-i.bottom,n.top-i.top)):n.top<i.top&&(a=n.top-12-i.top),1>Math.abs(a))return;let o=r.scrollTop+a;"function"==typeof r.scrollTo?r.scrollTo({top:o,behavior:"smooth"}):r.scrollTop=o},[]),N=(0,$.useRef)(l);(0,$.useEffect)(()=>{let e=N.current;N.current=l;let r=[...l].filter(r=>!e.has(r));if(r.length>0)return void C(r[r.length-1]);let s=[...e].filter(e=>!l.has(e));s.length>0&&j(s[s.length-1])},[l,C,j]);let E=(0,$.useCallback)(e=>{let r=document.querySelector(`[data-locate-id="${CSS.escape(e)}"]`);r?.scrollIntoView({block:"nearest"});let s=r?.querySelector("[data-locate-action]");s&&function(e){if(!(e instanceof HTMLButtonElement&&e.disabled)){let r=jB.get(e);void 0!==r&&window.clearTimeout(r),e.dataset.pressed="true",jB.set(e,window.setTimeout(()=>{jB.delete(e),delete e.dataset.pressed},160))}e.click()}(s)},[]),D=(0,$.useCallback)(e=>{let r=l.has(e);c(r=>new Set(r).add(e)),r&&C(e)},[l,C]),R=(0,$.useCallback)(e=>{c(r=>{let s=new Set(r);return s.delete(e)||s.add(e),s})},[]),[T,A]=(0,$.useState)(null),I=(0,$.useMemo)(()=>0===f.length?null:T&&f.some(e=>e.id===T)?T:f[0].id,[T,f]),M=dC("executors");dk({id:"executors",label:"Executors",priority:10,getItems:()=>f.map(e=>({id:e.id,text:e.name})),onCommit:e=>E(e.id),onSecondaryCommit:e=>D(e.id)},S);let F=M?.selectedId??null,[P,L]=(0,$.useState)(null);F!==P&&(L(F),null!==F&&A(F)),(0,$.useEffect)(()=>{null!==F&&j(F)},[F,j]);let O=M?M.selectedId:_?I:null,B=(0,$.useMemo)(()=>[...s?.path?["local"]:[],...d.map(e=>e.remote_server_id)],[s?.path,d]),H=s?.executor_mode??"local",U=null!==M;(0,$.useEffect)(()=>{if(!S||U)return;let e=e=>{if(e.defaultPrevented||e.metaKey||e.ctrlKey||e.altKey||e.shiftKey||dv(e.target)||dw(e.target))return;if("ArrowLeft"===e.key||"ArrowRight"===e.key){if(B.length<2||!n)return;e.preventDefault();let r=B.indexOf(H);n(B[(r+("ArrowRight"===e.key?1:-1)+B.length)%B.length]);return}if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault();let r=f.findIndex(e=>e.id===I),s=f[(r+("ArrowDown"===e.key?1:-1)+f.length)%f.length];A(s.id),j(s.id);return}let r=e.target instanceof Element&&null!==e.target.closest("button,a,[role='button']");if(" "===e.key&&I){if(r)return;e.preventDefault(),R(I);return}if("Enter"===e.key&&I){if(r)return;e.preventDefault(),E(I)}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[S,U,B,H,n,f,I,j,E,R]),(0,$.useEffect)(()=>{if(!S)return;let e=document.activeElement;if(!(e instanceof HTMLElement)||!q.current?.contains(e))return;let r=e.closest("[data-locate-id]");r&&r.getAttribute("data-locate-id")!==O&&e.blur()},[S,O]);let q=(0,$.useRef)(null),K=(0,$.useCallback)(e=>{let r=e.target instanceof Element?e.target.closest("[data-locate-id]"):null,s=r?.getAttribute("data-locate-id");s&&A(s)},[]),V=function(){for(var e=arguments.length,r=Array(e),s=0;s<e;s++)r[s]=arguments[s];return(0,$.useMemo)(()=>[...r].filter(e=>null!=e),[...r])}(Sg(SQ,{activationConstraint:{distance:8}}),Sg(SX,{coordinateGetter:jM}));return e?(0,z.jsx)(_X,{projectId:e,children:(0,z.jsxs)("div",{className:"h-full flex flex-col",children:[(0,z.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border/60 h-10",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsxs)("h2",{className:"text-xs font-semibold flex items-center gap-2 text-foreground",children:[(0,z.jsx)(gM,{className:"h-3.5 w-3.5"}),"Executors"]}),h.length>1&&n&&(0,z.jsx)(jO,{targets:h,activeTarget:s?.executor_mode??"local",onTargetChange:n})]}),(0,z.jsxs)(W.Button,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>o(!0),children:[(0,z.jsx)(eS,{className:"h-3 w-3 mr-1"}),"Add"]})]}),(0,z.jsx)("div",{className:"flex-1 overflow-y-auto",ref:k,children:(0,z.jsx)("div",{className:"p-4 space-y-3",ref:q,onPointerDown:K,children:p?(0,z.jsx)("div",{className:"text-center text-muted-foreground py-8",children:"Loading executors..."}):0===f.length?(0,z.jsxs)("div",{className:"text-center text-muted-foreground py-8",children:[(0,z.jsx)("p",{children:"No executors configured"}),(0,z.jsx)("p",{className:"text-sm mt-1",children:'Add an executor to run commands like "npm run dev"'})]}):(0,z.jsx)(jh,{sensors:V,collisionDetection:jz,onDragEnd:e=>{let{active:r,over:s}=e;if(s&&r.id!==s.id){let e=f.findIndex(e=>e.id===r.id),n=f.findIndex(e=>e.id===s.id),i=[...f],[a]=i.splice(e,1);i.splice(n,0,a),w(i.map(e=>e.id))}},children:(0,z.jsx)(jk,{items:f.map(e=>e.id),strategy:j_,children:f.map(e=>(0,z.jsx)(jP,{executor:e,executorMode:s?.executor_mode??"local",locateQuery:M?.query??null,locateMatch:M?.matchSet.has(e.id)??!1,keyboardSelected:O===e.id,isOpen:l.has(e.id),onOpenChange:r=>c(s=>{let n=new Set(s);return r?n.add(e.id):n.delete(e.id),n}),onStart:()=>v(e.id),onStop:r=>y(e.id,r||e.currentProcessId||void 0),onUpdate:r=>g(e.id,r),onDelete:()=>x(e.id),onProcessFinished:r=>b(e.id,r)},`${e.id}-${s?.executor_mode??"local"}`))})})})}),(0,z.jsx)(_q,{open:a,onOpenChange:o,onSubmit:async e=>{await m(e)}})]})},`${e??"none"}-${s?.executor_mode??"local"}`):(0,z.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(gM,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to manage executors"})]})})}let jW=(0,e_.default)("chevrons-up-down",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);function jH({line:e}){let r="add"===e.type?"+":"delete"===e.type?"-":" ",s="add"===e.type,n="delete"===e.type,i=s?"bg-emerald-500/[0.07]":n?"bg-rose-500/[0.07]":"",a=s?"bg-emerald-500/[0.10]":n?"bg-rose-500/[0.10]":"bg-secondary",o=s?"text-emerald-600":n?"text-rose-600":"text-muted-foreground/70";return(0,z.jsxs)("div",{className:"flex font-mono text-[11.5px] leading-[1.55]",children:[(0,z.jsx)("span",{className:(0,eb.cn)("w-9 flex-shrink-0 text-right pr-2 select-none border-r border-border/60",a,o),children:e.oldLineNo??""}),(0,z.jsx)("span",{className:(0,eb.cn)("w-9 flex-shrink-0 text-right pr-2 select-none border-r border-border/60",a,o),children:e.newLineNo??""}),(0,z.jsx)("span",{className:(0,eb.cn)("w-5 flex-shrink-0 text-center select-none",i,o),children:r}),(0,z.jsx)("span",{className:(0,eb.cn)("whitespace-pre-wrap break-all pr-4 flex-1 min-w-0 pl-2",i,(s||n)&&"text-foreground"),children:e.content})]})}let jU={modified:"bg-yellow-500/20 text-yellow-500",added:"bg-green-500/20 text-green-500",deleted:"bg-red-500/20 text-red-500",renamed:"bg-blue-500/20 text-blue-500"},jq={modified:"Modified",added:"Added",deleted:"Deleted",renamed:"Renamed"};function jK({file:e,defaultOpen:r=!0}){let[s,n]=(0,$.useState)(r),i=function(e,r){if(!r||r===e){let r,{dir:s,base:n}=-1===(r=e.lastIndexOf("/"))?{dir:"",base:e}:{dir:e.slice(0,r),base:e.slice(r+1)};return{dir:s,from:null,to:n,suffix:""}}let s=r.split("/"),n=e.split("/"),i=0;for(;i<s.length-1&&i<n.length-1&&s[i]===n[i];)i++;let a=0;for(;a<s.length-i-1&&a<n.length-i-1&&s[s.length-1-a]===n[n.length-1-a];)a++;return{dir:s.slice(0,i).join("/"),from:s.slice(i,s.length-a).join("/"),to:n.slice(i,n.length-a).join("/"),suffix:0===a?"":s.slice(s.length-a).join("/")}}(e.path,"renamed"===e.status?e.oldPath:void 0);return(0,z.jsxs)(gV,{open:s,onOpenChange:n,className:"border border-border rounded-lg overflow-hidden",children:[(0,z.jsxs)(gX,{className:"grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 px-4 py-2 bg-secondary border-b border-border w-full cursor-pointer hover:bg-muted transition-colors",children:[s?(0,z.jsx)(n6,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,z.jsx)(nV,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,z.jsxs)("span",{className:"font-mono text-[11.5px] flex min-w-0 overflow-hidden text-left text-foreground font-medium",title:null!==i.from?`${e.oldPath} → ${e.path}`:e.path,children:[i.dir&&(0,z.jsxs)("span",{className:"min-w-0 shrink-[9999] truncate text-muted-foreground font-normal",children:[i.dir,"/"]}),(0,z.jsxs)("span",{className:"min-w-0 truncate",children:[null!==i.from&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"text-muted-foreground font-normal",children:i.from}),(0,z.jsx)("span",{className:"mx-1.5 text-muted-foreground",children:"→"})]}),i.to,i.suffix&&(0,z.jsxs)("span",{className:"text-muted-foreground font-normal",children:["/",i.suffix]})]})]}),(0,z.jsx)(so,{variant:"secondary",className:jU[e.status],children:jq[e.status]})]}),(0,z.jsx)(gY,{children:(0,z.jsxs)("div",{children:[e.binary&&(0,z.jsx)("div",{className:"px-4 py-2 text-[11.5px] text-muted-foreground",children:"Binary file — contents not shown"}),e.hunks.map((e,r)=>(0,z.jsxs)("div",{children:[(0,z.jsxs)("div",{className:"px-4 py-0.5 bg-accent text-accent-foreground text-[11px] font-mono font-medium sticky top-0",children:["@@ -",e.oldStart,",",e.oldLines," +",e.newStart,",",e.newLines," @@"]}),e.lines.map((e,r)=>(0,z.jsx)(jH,{line:e},r))]},r))]})})]})}let jV=(0,e_.default)("git-commit-horizontal",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]]),jX="__head__",jY="__compare__";function jG({commits:e,selectedCommit:r,onSelectCommit:s,compareTarget:n,compareSelected:i,onSelectCompare:a,loading:o,disabled:l}){return(0,z.jsxs)(fd,{value:i?jY:r??jX,onValueChange:e=>{e===jY?a?.():s(e===jX?null:e)},disabled:l||o,children:[(0,z.jsxs)(fh,{size:"sm",className:"w-[200px]",children:[(0,z.jsx)(jV,{className:"h-3.5 w-3.5 shrink-0"}),(0,z.jsx)(fu,{placeholder:"Select commit..."})]}),(0,z.jsxs)(ff,{children:[(0,z.jsx)(fp,{value:jX,children:"HEAD (uncommitted)"}),n&&(0,z.jsxs)(fp,{value:jY,children:["vs ",(0,z.jsx)("span",{className:"font-mono text-xs",children:n})]}),e.map(e=>(0,z.jsxs)(fp,{value:e.hash,children:[(0,z.jsx)("span",{className:"font-mono text-xs",children:e.shortHash})," ",(0,z.jsx)("span",{className:"truncate",children:e.message.length>40?e.message.slice(0,40)+"...":e.message})]},e.hash))]})]})}let jJ=[];function jZ({projectId:e,selectedBranch:r,onMergeRequest:s,project:n,mergeTarget:i,compareRequestNonce:a}){let[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(a),[f,p]=(0,$.useState)(r),m=void 0!==a&&a!==u;m&&(h(a),d(!0),l(null)),r!==f&&(p(r),l(null),m||d(!1));let{remotes:g,loaded:x}=g_(),v=[];for(let e of(n?.path&&v.push({id:"local",label:"Local",icon:hy}),g))v.push({id:e.remote_server_id,label:e.server_name,icon:sm});let y=n?.path?"local":g.length>0?g[0].remote_server_id:"local",[b,w]=(0,$.useState)(null),_=null!==b&&v.some(e=>e.id===b)?b:y,[S,j]=(0,$.useState)(!0),[k,C]=(0,$.useState)(0),N=!!n?.path||x,E="local"===_?n?.path?"local":void 0:"remote",{diff:D,loading:R,error:T,refresh:A}=function(e,r,s,n,i){let a=`${e??""}::${r??""}`,[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(!1),u=(0,$.useRef)(0),h=(0,$.useCallback)(async()=>{let o=++u.current;if(!e){l({workspace:a,diff:null,error:null}),d(!1);return}d(!0);try{let c=await ry.api.getDiff(e,r,s,n,i);if(o!==u.current)return;l({workspace:a,diff:c,error:null})}catch(e){if(o!==u.current)return;l({workspace:a,diff:null,error:e instanceof Error?e.message:"Failed to load diff"})}finally{o===u.current&&d(!1)}},[e,r,s,n,i,a]),f=o?.workspace===a?o:null;return{diff:f?.diff??null,loading:c||null===f,error:f?.error??null,refresh:h}}(e,r,o,E,c&&i?i:null),{commits:I,loading:M,refetch:F}=function(e,r,s,n){let i=`${e??""}::${r??""}`,[a,o]=(0,$.useState)(null),[l,c]=(0,$.useState)(!1),d=(0,$.useRef)(0),u=(0,$.useCallback)(async()=>{let a=++d.current;if(!e){o({workspace:i,commits:jJ}),c(!1);return}c(!0);try{let l=await ry.api.getCommits(e,r,s,n);if(a!==d.current)return;o({workspace:i,commits:l})}catch{if(a!==d.current)return;o({workspace:i,commits:jJ})}finally{a===d.current&&c(!1)}},[e,r,s,n,i]);return{commits:a?.workspace===i?a.commits:jJ,loading:l,refetch:u}}(e,r,void 0,E);if((0,$.useEffect)(()=>{N&&A()},[A,N]),(0,$.useEffect)(()=>{N&&F()},[F,N]),!e)return(0,z.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(sq,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to view changes"})]})});let P=D?.files.length??0;return(0,z.jsxs)("div",{className:"h-full flex flex-col",children:[(0,z.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border/60 h-10",children:[(0,z.jsx)("div",{className:"flex items-center gap-4",children:P>0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)("span",{className:"text-xs text-muted-foreground",children:[P," file",1!==P?"s":""," changed"]}),(0,z.jsxs)(W.Button,{size:"sm",variant:"ghost",onClick:()=>{j(e=>!e),C(e=>e+1)},title:S?"Collapse all":"Expand all",children:[(0,z.jsx)(jW,{className:"h-4 w-4 mr-1"}),S?"Collapse all":"Expand all"]})]})}),(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[v.length>1&&(0,z.jsx)(jO,{targets:v,activeTarget:_,onTargetChange:w,disabled:R}),(0,z.jsx)("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Commit:"}),(0,z.jsx)(jG,{commits:I,selectedCommit:o,onSelectCommit:e=>{d(!1),l(e)},compareTarget:i,compareSelected:c,onSelectCompare:()=>{d(!0),l(null)},loading:M,disabled:R}),(0,z.jsxs)(W.Button,{size:"sm",variant:"outline",onClick:s,disabled:R||0===P,children:[(0,z.jsx)(df,{className:"h-4 w-4 mr-1"}),"Merge"]}),(0,z.jsxs)(W.Button,{size:"sm",variant:"outline",onClick:A,disabled:R,children:[(0,z.jsx)(mt,{className:`h-4 w-4 mr-1 ${R?"animate-spin":""}`}),"Refresh"]})]})]}),(0,z.jsx)(nH,{className:"flex-1 overflow-hidden",children:(0,z.jsx)("div",{className:"p-4 space-y-4",children:R&&!D?(0,z.jsx)("div",{className:"text-center text-muted-foreground py-8",children:"Loading changes..."}):T?(0,z.jsx)("div",{className:"text-center text-red-400 py-8",children:T}):0===P?(0,z.jsx)("div",{className:"text-center text-muted-foreground py-8",children:(0,z.jsx)("p",{children:c&&i?`No changes vs ${i}`:o?"No changes in this commit":"No uncommitted changes"})}):D?.files.map((e,r)=>(0,z.jsx)(jK,{file:e,defaultOpen:S},`${r}-${k}`))})})]})}let jQ=[];function j0({terminalId:e,onExit:r,focusHandle:s}){let{logs:n,sendInput:i,sendResize:a,exitCode:o,replayingHistory:l}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)("closed"),[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(!0),f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=(0,$.useRef)(0),g=(0,$.useRef)(null),x=(0,$.useRef)(!1),v=(0,$.useCallback)(()=>{n([]),l(null),d(!1)},[]),y=(0,$.useCallback)(e=>{f.current?.readyState===WebSocket.OPEN&&f.current.send(JSON.stringify({type:"input",data:e}))},[]),b=(0,$.useCallback)((e,r)=>{f.current?.readyState===WebSocket.OPEN?f.current.send(JSON.stringify({type:"resize",cols:e,rows:r})):p.current={cols:e,rows:r}},[]);return(0,$.useEffect)(()=>{if(!e)return;n([]),l(null),d(!1),x.current=!1,m.current=0;let r=!1;return function s(){r||x.current||(0,ry.getFreshToken)().then(()=>{r||x.current||function(){if(r||x.current)return;a("connecting");let i=`/api/executor-processes/${e}/logs`;console.log(`[useExecutorLogs] Connecting to WebSocket: ${i}`);let o=new WebSocket((0,ry.getWebSocketUrl)(i));f.current=o;let c=!1,u=!1;o.onopen=()=>{if(!r&&(console.log("[useExecutorLogs] WebSocket connected"),a("connected"),n([]),p.current)){let{cols:e,rows:r}=p.current;o.send(JSON.stringify({type:"resize",cols:e,rows:r})),p.current=null}},o.onmessage=e=>{if(!r)try{let r=JSON.parse(e.data);if("init"===r.type)d(r.isPty),h(!0),console.log("[useExecutorLogs] init received, setReplayingHistory(true)");else if("history_end"===r.type)u=!0,h(!1),console.log("[useExecutorLogs] history_end received, setReplayingHistory(false)");else if("finished"===r.type)x.current=!0,l(r.exitCode),a("closed");else if("error"===r.type)x.current=!0,a("error");else{u&&(c=!0,m.current=0);let e="stdout"===r.type||"stderr"===r.type||"pty"===r.type?{...r,historical:!u}:r;n(r=>[...r,e])}}catch(e){console.error("Failed to parse WebSocket message:",e)}},o.onerror=e=>{r||console.error("[useExecutorLogs] WebSocket error:",e)},o.onclose=e=>{if(console.log("[useExecutorLogs] WebSocket closed:",e.code,e.reason),f.current=null,x.current||r)return void a("closed");if(u&&!c){console.log(`[useExecutorLogs] Server closed after history with no live data — treating as terminal`),x.current=!0,a("closed");return}if(m.current<8){let e=m.current,n=Math.min(15e3,1e3*Math.pow(2,e)),i=n*Math.random()*.25,o=n+i;console.log(`[useExecutorLogs] Scheduling reconnect in ${Math.round(o)}ms (attempt ${e+1}/8)`),a("connecting"),m.current=e+1,g.current=setTimeout(()=>{g.current=null,r||s()},o)}else console.log("[useExecutorLogs] Max reconnect attempts reached"),a("error")}}()})}(),()=>{r=!0,g.current&&(clearTimeout(g.current),g.current=null),f.current&&(f.current.close(),f.current=null)}},[e,void 0]),{logs:s,status:i,exitCode:o,isPty:c,replayingHistory:u,clearLogs:v,sendInput:y,sendResize:b}}(e);return(0,$.useEffect)(()=>{null!==o&&r(e)},[o,r,e]),(0,z.jsx)(_H,{logs:n,isPty:!0,className:"h-full rounded-none border-0",onInput:i,onResize:a,muteInput:l,focusHandle:s})}function j1({projectId:e,selectedBranch:r,project:s,active:n=!0,createRequest:i}){let{terminals:a,activeTerminalId:o,createTerminal:l,closeTerminal:c,setActiveTerminal:d,removeTerminal:u}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(null),o=`${e??""}::${r??""}`,l=(0,$.useRef)(o),c=(0,$.useRef)([]),[d,u]=(0,$.useState)(null),h=(0,$.useRef)(null);(0,$.useEffect)(()=>{if(l.current=o,c.current=[],!e){n([]),a(null);return}ry.api.getTerminals(e,r).then(e=>{if(l.current!==o)return;let r=c.current;c.current=[];let s=0===r.length?e:[...e.filter(e=>!r.some(r=>r.id===e.id)),...r];n(s),h.current=o,u(o),a(r.length>0?r[r.length-1].id:s.length>0?s[0].id:null)})},[e,r,o]);let f=(0,$.useCallback)(async(s,i)=>{if(!e)return;let o=l.current;try{let d=await ry.api.createTerminal(e,r,s,i);if(l.current!==o)return;c.current=[...c.current,d];let f=c.current,p=h.current===o;n(e=>p?[...e,d]:f),h.current=o,u(o),a(d.id)}catch(e){console.error("[useTerminals] Failed to create terminal:",e)}},[e,r]),p=(0,$.useCallback)(e=>{c.current=c.current.filter(r=>r.id!==e)},[]),m=(0,$.useCallback)(async e=>{await ry.api.closeTerminal(e),p(e),n(r=>{let s=r.filter(r=>r.id!==e);return a(r=>r===e?s.length>0?s[s.length-1].id:null:r),s})},[p]),g=(0,$.useCallback)(e=>{a(e)},[]),x=(0,$.useCallback)(e=>{p(e),n(r=>{let s=r.filter(r=>r.id!==e);return a(r=>r===e?s.length>0?s[s.length-1].id:null:r),s})},[p]),v=null!==e&&d===o;return{terminals:v?s:jQ,activeTerminalId:v?i:null,createTerminal:f,closeTerminal:m,setActiveTerminal:g,removeTerminal:x}}(e,r),{remotes:h}=g_(),f=(0,$.useRef)(null);(0,$.useEffect)(()=>{n&&o&&f.current?.focus()},[n,o]);let[p,m]=(0,$.useState)(!1),g=(0,$.useRef)(null),x=!!s?.path,v=h.length>0,y=x&&v||h.length>1,b=x?"local":"remote",w=(0,$.useCallback)(()=>{l(b)},[l,b]),_=(0,$.useCallback)((e,r)=>{m(!1),l(e,r)},[l]),S=(0,$.useRef)(null);(0,$.useEffect)(()=>{i&&S.current!==i.nonce&&(S.current=i.nonce,"local"===i.targetId?l("local"):l("remote",i.targetId))},[i,l]),(0,$.useEffect)(()=>{if(p)return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e);function e(e){g.current&&!g.current.contains(e.target)&&m(!1)}},[p]);let j=(0,$.useCallback)(e=>{u(e)},[u]);return e?(0,z.jsxs)("div",{className:"h-full flex flex-col",children:[(0,z.jsxs)("div",{className:"flex items-center h-10 border-b border-border/60 px-2 gap-1 shrink-0 bg-muted/20",children:[(0,z.jsx)("div",{className:"flex-1 min-w-0 flex items-center gap-1 overflow-hidden",children:a.map(e=>{let r="remote"===e.location||e.id.startsWith("remote-"),s=y?r?sm:hy:gM,n=o===e.id;return(0,z.jsxs)("button",{onClick:()=>d(e.id),title:e.name,className:(0,eb.cn)("group flex items-center gap-1.5 px-2 py-1 rounded-md text-xs transition-all duration-150 border flex-1 min-w-0 basis-0 max-w-[180px]",n?"bg-background text-foreground border-border shadow-sm":"text-muted-foreground hover:text-foreground bg-muted/40 hover:bg-background/60 border-border/30 hover:border-border/60"),children:[(0,z.jsx)(s,{className:"h-3 w-3 shrink-0"}),(0,z.jsx)("span",{className:"truncate flex-1 text-left",children:e.name}),(0,z.jsx)("span",{role:"button",onClick:r=>{r.stopPropagation(),c(e.id)},className:(0,eb.cn)("shrink-0 rounded-sm p-0.5 hover:bg-destructive/10 hover:text-destructive",n?"opacity-80 hover:opacity-100":"opacity-0 group-hover:opacity-80 hover:!opacity-100"),children:(0,z.jsx)(t7,{className:"h-3 w-3"})})]},e.id)})}),(0,z.jsxs)("div",{className:"relative shrink-0",ref:g,children:[(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:y?()=>m(e=>!e):w,children:(0,z.jsx)(eS,{className:"h-3.5 w-3.5"})}),y&&p&&(0,z.jsxs)("div",{className:"absolute right-0 top-full mt-1 z-50 min-w-[160px] rounded-md border bg-popover p-1 shadow-md",children:[x&&(0,z.jsxs)("button",{className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground transition-colors",onClick:()=>_("local"),children:[(0,z.jsx)(hy,{className:"h-3.5 w-3.5"}),"Local Terminal"]}),h.map(e=>(0,z.jsxs)("button",{className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground transition-colors",onClick:()=>_("remote",e.remote_server_id),children:[(0,z.jsx)(sm,{className:"h-3.5 w-3.5"}),e.server_name," Terminal"]},e.remote_server_id))]})]})]}),(0,z.jsx)("div",{className:"flex-1 overflow-hidden bg-zinc-950",children:o?(0,z.jsx)(j0,{terminalId:o,onExit:j,focusHandle:f},o):(0,z.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,z.jsx)(gM,{className:"h-10 w-10 text-muted-foreground/70"})})})]}):(0,z.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(gM,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to use the terminal"})]})})}let j2=(0,$.createContext)(null),j5=({className:e,children:r,defaultUrl:s="",onUrlChange:n,...i})=>{let[a,o]=(0,$.useState)(s),[l,c]=(0,$.useState)(!1);return(0,z.jsx)(j2.Provider,{value:{url:a,setUrl:e=>{o(e),n?.(e)},consoleOpen:l,setConsoleOpen:c},children:(0,z.jsx)("div",{className:(0,eb.cn)("flex size-full flex-col bg-card",e),...i,children:r})})},j3=({className:e,children:r,...s})=>(0,z.jsx)("div",{className:(0,eb.cn)("flex items-center gap-1 border-b p-2 h-14",e),...s,children:r}),j4=({onClick:e,disabled:r,tooltip:s,children:n,...i})=>(0,z.jsx)(cb,{children:(0,z.jsxs)(cw,{children:[(0,z.jsx)(c_,{asChild:!0,children:(0,z.jsx)(W.Button,{className:"h-8 w-8 p-0 hover:text-foreground",disabled:r,onClick:e,size:"sm",variant:"ghost",...i,children:n})}),(0,z.jsx)(cS,{children:(0,z.jsx)("p",{children:s})})]})}),j6=({value:e,onChange:r,onKeyDown:s,...n})=>{let{url:i,setUrl:a}=(()=>{let e=(0,$.useContext)(j2);if(!e)throw Error("WebPreview components must be used within a WebPreview");return e})(),[o,l]=(0,$.useState)(i);return(0,$.useEffect)(()=>{l(i)},[i]),(0,z.jsx)(rl,{className:"h-8 flex-1 text-sm",onChange:r??(e=>{l(e.target.value),r?.(e)}),onKeyDown:e=>{"Enter"===e.key&&a(e.target.value),s?.(e)},placeholder:"Enter URL...",value:e??o,...n})};var j7=e.i(254824);function j8({projectId:e}){let r=(0,$.useRef)(null),s=(0,$.useRef)(null),{addFrame:n,updateFrameUrl:i,refreshFrame:a,hasFrame:o,claimFrame:l,getFrameUrl:c}=(0,j7.useBrowserFrames)(),d=e?c(e):void 0;(0,$.useEffect)(()=>{if(e&&d&&r.current){let n=setTimeout(()=>{r.current&&(s.current?.(),s.current=l(e,r.current))},50);return()=>{clearTimeout(n),s.current?.(),s.current=null}}return()=>{s.current?.(),s.current=null}},[e,d,l]);let u=(0,$.useCallback)(()=>{e&&a(e)},[e,a]),h=(0,$.useCallback)(()=>{d&&window.open(d,"_blank")},[d]),f=(0,$.useCallback)(r=>{e&&(o(e)?i(e,r):n(e,r))},[e,o,i,n]);return(0,z.jsx)("div",{className:"h-full flex flex-col",children:(0,z.jsxs)(j5,{defaultUrl:d??"",onUrlChange:f,className:"h-full",children:[(0,z.jsxs)(j3,{className:"h-10 p-1.5 gap-0.5",children:[(0,z.jsx)(j4,{tooltip:"Refresh",onClick:u,disabled:!d,children:(0,z.jsx)(mt,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(j4,{tooltip:"Open in browser",onClick:h,disabled:!d,children:(0,z.jsx)(s8,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(j6,{className:"h-7 text-xs"})]}),d?(0,z.jsx)("div",{ref:r,className:"flex-1 bg-white"}):(0,z.jsx)("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:(0,z.jsxs)("div",{className:"flex flex-col items-center gap-2",children:[(0,z.jsx)(rw,{className:"h-8 w-8 opacity-40"}),(0,z.jsx)("p",{className:"text-sm",children:"Enter a URL above to preview"})]})})]})})}let j9=(0,e_.default)("panel-left-close",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]),ke=(0,e_.default)("panel-left-open",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]),kt=(0,e_.default)("arrow-right",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);function kr({className:e,...r}){return(0,z.jsx)("div",{"data-slot":"input-group",role:"group",className:(0,eb.cn)("group/input-group border-input dark:bg-input/30 relative flex w-full items-center rounded-md border shadow-xs transition-[color,box-shadow] outline-none","h-9 min-w-0 has-[textarea]:h-auto","has-[>[data-align=inline-start]]:[&>input]:pl-2","has-[>[data-align=inline-end]]:[&>input]:pr-2","has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3","has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3","has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot=input-group-control]:focus-visible]:ring-[3px]","has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40",e),...r})}let ks=(0,si.cva)("text-muted-foreground flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium select-none [&>svg:not([class*='size-'])]:size-4 [&>kbd]:rounded-[calc(var(--radius)-5px)] group-data-[disabled=true]/input-group:opacity-50",{variants:{align:{"inline-start":"order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]","inline-end":"order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]","block-start":"order-first w-full justify-start px-3 pt-3 [.border-b]:pb-3 group-has-[>input]/input-group:pt-2.5","block-end":"order-last w-full justify-start px-3 pb-3 [.border-t]:pt-3 group-has-[>input]/input-group:pb-2.5"}},defaultVariants:{align:"inline-start"}});function kn({className:e,align:r="inline-start",...s}){return(0,z.jsx)("div",{role:"group","data-slot":"input-group-addon","data-align":r,className:(0,eb.cn)(ks({align:r}),e),onClick:e=>{e.target.closest("button")||e.currentTarget.parentElement?.querySelector("input")?.focus()},...s})}let ki=(0,si.cva)("text-sm shadow-none flex gap-2 items-center",{variants:{size:{xs:"h-6 gap-1 px-2 rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-3.5 has-[>svg]:px-2",sm:"h-8 px-2.5 gap-1.5 rounded-md has-[>svg]:px-2.5","icon-xs":"size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0","icon-sm":"size-8 p-0 has-[>svg]:p-0"}},defaultVariants:{size:"xs"}});function ka({className:e,type:r="button",variant:s="ghost",size:n="xs",...i}){return(0,z.jsx)(W.Button,{type:r,"data-size":n,variant:s,className:(0,eb.cn)(ki({size:n}),e),...i})}function ko({className:e,...r}){return(0,z.jsx)(rl,{"data-slot":"input-group-control",className:(0,eb.cn)("flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",e),...r})}function kl({className:e,...r}){return(0,z.jsx)(rc,{"data-slot":"input-group-control",className:(0,eb.cn)("flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent",e),...r})}let kc=(0,e_.default)("file",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]]),kd=(0,e_.default)("file-code",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]]),ku=(0,e_.default)("file-text",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]),kh=new Set(["ts","tsx","js","jsx","py","rb","go","rs","java","c","cpp","h","css","scss","html","vue","svelte","php","swift","kt","sh","bash","yaml","yml","toml","json","xml","sql","graphql","proto"]),kf=new Set(["md","txt","log","csv","env","gitignore","dockerignore","editorconfig"]);function kp(e){return Array.from(e.dataTransfer.types).includes("Files")}function km(e){let r=e.dataTransfer.items;if(r&&r.length>0&&"function"==typeof r[0].webkitGetAsEntry){let e=[];for(let s of Array.from(r)){if("file"!==s.kind)continue;let r=s.webkitGetAsEntry();if(r?.isDirectory)continue;let n=s.getAsFile();n&&e.push(n)}return e}return Array.from(e.dataTransfer.files)}function kg({path:e}){let[r,s]=(0,$.useState)(!1),n=(0,$.useCallback)(r=>{r.stopPropagation(),navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)},[e]);return(0,z.jsx)("button",{onClick:n,className:"p-0.5 rounded hover:bg-muted-foreground/20 transition-colors",title:`Copy path: ${e}`,children:r?(0,z.jsx)(rp.Check,{className:"h-3 w-3 text-green-500"}):(0,z.jsx)(me.Copy,{className:"h-3 w-3 text-muted-foreground"})})}function kx({entryPath:e,type:r,deleting:s,onRequestDelete:n}){return s?(0,z.jsx)(sC,{className:"h-3 w-3 animate-spin text-muted-foreground"}):(0,z.jsx)("button",{onClick:s=>{s.stopPropagation(),n(e,r)},className:"p-0.5 rounded hover:bg-destructive/20 transition-colors",title:`Delete ${e}`,"aria-label":`Delete ${e}`,children:(0,z.jsx)(rd,{className:"h-3 w-3 text-muted-foreground hover:text-destructive"})})}function kv({entry:e,path:r,depth:s,expandedDirs:n,directoryContents:i,loadingDirs:a,selectedFile:o,uploadingDirs:l,dragOverPath:c,deletingPaths:d,onToggleDirectory:u,onSelectFile:h,onUploadFiles:f,onSetDragOverPath:p,onRequestDelete:m}){var g,x,v;let y,b,w,_,S,j=n.has(r),k=a.has(r),C=i.get(r),N=e.name.startsWith(".");if("directory"===e.type){let g=j?n6:nV,x=c===r,v=l.has(r),y=d.has(r);return(0,z.jsxs)("div",{children:[(0,z.jsxs)("div",{className:(0,eb.cn)("group flex items-center w-full px-2 py-2 rounded-sm transition-colors cursor-pointer",x?"bg-primary/15 outline-2 -outline-offset-2 outline-dashed outline-primary/60":"hover:bg-accent"),style:{paddingLeft:`${16*s+8}px`},onClick:()=>u(r),onDragOver:e=>{kp(e)&&(e.preventDefault(),e.stopPropagation(),p(r))},onDrop:e=>{if(!kp(e))return;e.preventDefault(),e.stopPropagation(),p(null);let s=km(e);s.length&&f(r,s)},children:[(0,z.jsxs)("div",{className:"flex items-center gap-1 min-w-0 flex-1",children:[v||k?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):(0,z.jsx)(g,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,z.jsx)(j?rb:nq,{className:(0,eb.cn)("h-4 w-4 shrink-0 text-blue-500",N&&"opacity-60")}),(0,z.jsx)("span",{className:(0,eb.cn)("truncate",N&&"text-muted-foreground"),children:e.name})]}),(0,z.jsxs)("div",{className:(0,eb.cn)("shrink-0 ml-1 items-center gap-1",y?"flex":"hidden group-hover:flex"),children:[(0,z.jsx)(kg,{path:r}),(0,z.jsx)(kx,{entryPath:r,type:"directory",deleting:y,onRequestDelete:m})]})]}),j&&C&&(0,z.jsx)("div",{children:C.map(e=>{let g=r?`${r}/${e.name}`:e.name;return(0,z.jsx)(kv,{entry:e,path:g,depth:s+1,expandedDirs:n,directoryContents:i,loadingDirs:a,selectedFile:o,uploadingDirs:l,dragOverPath:c,deletingPaths:d,onToggleDirectory:u,onSelectFile:h,onUploadFiles:f,onSetDragOverPath:p,onRequestDelete:m},g)})})]})}let E=(g=e.name,y=g.split(".").pop()?.toLowerCase()??"",kh.has(y)?kd:kf.has(y)?ku:kc),D=o===r,R=r.includes("/")?r.slice(0,r.lastIndexOf("/")):"",T=d.has(r);return(0,z.jsxs)("div",{className:(0,eb.cn)("group flex items-center w-full px-2 py-2 rounded-sm transition-colors cursor-pointer",D?"bg-accent text-accent-foreground":"hover:bg-accent/50"),style:{paddingLeft:`${16*s+8+18}px`},onClick:()=>h(r),onDragOver:e=>{kp(e)&&(e.preventDefault(),e.stopPropagation(),p(R))},onDrop:e=>{if(!kp(e))return;e.preventDefault(),e.stopPropagation(),p(null);let r=km(e);r.length&&f(R,r)},children:[(0,z.jsxs)("div",{className:"flex items-center gap-1 min-w-0 flex-1",children:[(0,z.jsx)(E,{className:(0,eb.cn)("h-4 w-4 shrink-0 text-muted-foreground",N&&"opacity-60")}),(0,z.jsx)("span",{className:(0,eb.cn)("truncate",N&&"text-muted-foreground"),children:e.name})]}),(0,z.jsxs)("div",{className:"shrink-0 flex items-center gap-2 ml-1",children:[(0,z.jsx)("span",{className:"text-[11px] text-muted-foreground/70 group-hover:hidden whitespace-nowrap w-[52px] text-right tabular-nums",children:e.mtime&&(x=e.mtime,b=Date.now(),S=Math.floor((_=Math.floor((w=Math.floor(Math.floor((b-new Date(x).getTime())/1e3)/60))/60))/24),w<1?"just now":w<60?`${w}m ago`:_<24?`${_}h ago`:S<30?`${S}d ago`:new Date(x).toLocaleDateString(void 0,{month:"short",day:"numeric"}))}),(0,z.jsx)("span",{className:"text-[11px] text-muted-foreground/70 group-hover:hidden whitespace-nowrap w-[52px] text-right tabular-nums",children:null!=e.size&&((v=e.size)<1024?`${v} B`:v<1048576?`${(v/1024).toFixed(1)} KB`:`${(v/1048576).toFixed(1)} MB`)}),(0,z.jsxs)("div",{className:(0,eb.cn)("items-center gap-1",T?"flex":"hidden group-hover:flex"),children:[(0,z.jsx)(kg,{path:r}),(0,z.jsx)(kx,{entryPath:r,type:"file",deleting:T,onRequestDelete:m})]})]})]})}function ky({entries:e,expandedDirs:r,directoryContents:s,loadingDirs:n,selectedFile:i,uploadingDirs:a,rootLoading:o,deletingPaths:l,onToggleDirectory:c,onSelectFile:d,onUploadFiles:u,onDeleteEntry:h}){let[f,p]=(0,$.useState)(null),[m,g]=(0,$.useState)(null),x=""===f,v=a.has(""),y=(0,$.useCallback)((e,r)=>{g({path:e,type:r})},[]),b=m?m.path.includes("/")?m.path.slice(m.path.lastIndexOf("/")+1):m.path:"";return(0,z.jsxs)("div",{className:(0,eb.cn)("h-full transition-colors",x&&"bg-accent/30 outline-2 -outline-offset-2 outline-dashed outline-primary/50"),style:{fontSize:"var(--files-tree-font-size, 14px)"},onDragOver:e=>{kp(e)&&(e.preventDefault(),p(""))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||p(null)},onDrop:e=>{if(!kp(e))return;e.preventDefault(),p(null);let r=km(e);r.length&&u("",r)},children:[(0,z.jsx)(nH,{className:"h-full",children:(0,z.jsxs)("div",{className:"py-1",children:[v&&(0,z.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1 text-xs text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-3.5 w-3.5 animate-spin"}),"Uploading…"]}),o&&0===e.length?(0,z.jsx)("div",{className:"flex items-center justify-center py-12 text-muted-foreground text-sm",children:"Loading files..."}):0===e.length?(0,z.jsx)("div",{className:"flex items-center justify-center py-8 text-muted-foreground text-sm",children:x?"Drop files to upload":"No files found. Drop files here to upload."}):e.map(e=>{let o=e.name;return(0,z.jsx)(kv,{entry:e,path:o,depth:0,expandedDirs:r,directoryContents:s,loadingDirs:n,selectedFile:i,uploadingDirs:a,dragOverPath:f,deletingPaths:l,onToggleDirectory:c,onSelectFile:d,onUploadFiles:u,onSetDragOverPath:p,onRequestDelete:y},o)})]})}),(0,z.jsx)(lL,{open:null!==m,onOpenChange:e=>{e||g(null)},children:(0,z.jsxs)(lz,{children:[(0,z.jsxs)(l$,{children:[(0,z.jsxs)(lH,{children:["Delete ",m?.type==="directory"?"folder":"file","?"]}),(0,z.jsx)(lU,{children:m?.type==="directory"?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"font-medium text-foreground",children:b})," and all its contents will be permanently deleted. This can't be undone."]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"font-medium text-foreground",children:b})," will be permanently deleted. This can't be undone."]})})]}),(0,z.jsxs)(lW,{children:[(0,z.jsx)(lK,{children:"Cancel"}),(0,z.jsx)(lq,{className:(0,eb.cn)((0,W.buttonVariants)({variant:"destructive"}),"border-transparent"),onClick:()=>{m&&h(m.path,m.type)},children:"Delete"})]})]})})]})}let kb=(0,e_.default)("download",[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]]),kw=(0,e_.default)("file-exclamation-point",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),k_=(0,e_.default)("code",[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]]),kS=(0,e_.default)("list-collapse",[["path",{d:"M10 5h11",key:"1hkqpe"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 19h11",key:"14g2nv"}],["path",{d:"m3 10 3-3-3-3",key:"i7pm08"}],["path",{d:"m3 20 3-3-3-3",key:"20gx1n"}]]),kj=(0,e_.default)("list-tree",[["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"M3 10a2 2 0 0 0 2 2h3",key:"1npucw"}],["path",{d:"M3 5v12a2 2 0 0 0 2 2h3",key:"x1gjn2"}]]),kk=/[\0-\x1F!-,\.\/:-@\[-\^`\{-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0378\u0379\u037E\u0380-\u0385\u0387\u038B\u038D\u03A2\u03F6\u0482\u0530\u0557\u0558\u055A-\u055F\u0589-\u0590\u05BE\u05C0\u05C3\u05C6\u05C8-\u05CF\u05EB-\u05EE\u05F3-\u060F\u061B-\u061F\u066A-\u066D\u06D4\u06DD\u06DE\u06E9\u06FD\u06FE\u0700-\u070F\u074B\u074C\u07B2-\u07BF\u07F6-\u07F9\u07FB\u07FC\u07FE\u07FF\u082E-\u083F\u085C-\u085F\u086B-\u089F\u08B5\u08C8-\u08D2\u08E2\u0964\u0965\u0970\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA\u09BB\u09C5\u09C6\u09C9\u09CA\u09CF-\u09D6\u09D8-\u09DB\u09DE\u09E4\u09E5\u09F2-\u09FB\u09FD\u09FF\u0A00\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A\u0A3B\u0A3D\u0A43-\u0A46\u0A49\u0A4A\u0A4E-\u0A50\u0A52-\u0A58\u0A5D\u0A5F-\u0A65\u0A76-\u0A80\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA\u0ABB\u0AC6\u0ACA\u0ACE\u0ACF\u0AD1-\u0ADF\u0AE4\u0AE5\u0AF0-\u0AF8\u0B00\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A\u0B3B\u0B45\u0B46\u0B49\u0B4A\u0B4E-\u0B54\u0B58-\u0B5B\u0B5E\u0B64\u0B65\u0B70\u0B72-\u0B81\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BBD\u0BC3-\u0BC5\u0BC9\u0BCE\u0BCF\u0BD1-\u0BD6\u0BD8-\u0BE5\u0BF0-\u0BFF\u0C0D\u0C11\u0C29\u0C3A-\u0C3C\u0C45\u0C49\u0C4E-\u0C54\u0C57\u0C5B-\u0C5F\u0C64\u0C65\u0C70-\u0C7F\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA\u0CBB\u0CC5\u0CC9\u0CCE-\u0CD4\u0CD7-\u0CDD\u0CDF\u0CE4\u0CE5\u0CF0\u0CF3-\u0CFF\u0D0D\u0D11\u0D45\u0D49\u0D4F-\u0D53\u0D58-\u0D5E\u0D64\u0D65\u0D70-\u0D79\u0D80\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DC9\u0DCB-\u0DCE\u0DD5\u0DD7\u0DE0-\u0DE5\u0DF0\u0DF1\u0DF4-\u0E00\u0E3B-\u0E3F\u0E4F\u0E5A-\u0E80\u0E83\u0E85\u0E8B\u0EA4\u0EA6\u0EBE\u0EBF\u0EC5\u0EC7\u0ECE\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F01-\u0F17\u0F1A-\u0F1F\u0F2A-\u0F34\u0F36\u0F38\u0F3A-\u0F3D\u0F48\u0F6D-\u0F70\u0F85\u0F98\u0FBD-\u0FC5\u0FC7-\u0FFF\u104A-\u104F\u109E\u109F\u10C6\u10C8-\u10CC\u10CE\u10CF\u10FB\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B\u135C\u1360-\u137F\u1390-\u139F\u13F6\u13F7\u13FE-\u1400\u166D\u166E\u1680\u169B-\u169F\u16EB-\u16ED\u16F9-\u16FF\u170D\u1715-\u171F\u1735-\u173F\u1754-\u175F\u176D\u1771\u1774-\u177F\u17D4-\u17D6\u17D8-\u17DB\u17DE\u17DF\u17EA-\u180A\u180E\u180F\u181A-\u181F\u1879-\u187F\u18AB-\u18AF\u18F6-\u18FF\u191F\u192C-\u192F\u193C-\u1945\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DA-\u19FF\u1A1C-\u1A1F\u1A5F\u1A7D\u1A7E\u1A8A-\u1A8F\u1A9A-\u1AA6\u1AA8-\u1AAF\u1AC1-\u1AFF\u1B4C-\u1B4F\u1B5A-\u1B6A\u1B74-\u1B7F\u1BF4-\u1BFF\u1C38-\u1C3F\u1C4A-\u1C4C\u1C7E\u1C7F\u1C89-\u1C8F\u1CBB\u1CBC\u1CC0-\u1CCF\u1CD3\u1CFB-\u1CFF\u1DFA\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FBD\u1FBF-\u1FC1\u1FC5\u1FCD-\u1FCF\u1FD4\u1FD5\u1FDC-\u1FDF\u1FED-\u1FF1\u1FF5\u1FFD-\u203E\u2041-\u2053\u2055-\u2070\u2072-\u207E\u2080-\u208F\u209D-\u20CF\u20F1-\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F-\u215F\u2189-\u24B5\u24EA-\u2BFF\u2C2F\u2C5F\u2CE5-\u2CEA\u2CF4-\u2CFF\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D70-\u2D7E\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF\u2E00-\u2E2E\u2E30-\u3004\u3008-\u3020\u3030\u3036\u3037\u303D-\u3040\u3097\u3098\u309B\u309C\u30A0\u30FB\u3100-\u3104\u3130\u318F-\u319F\u31C0-\u31EF\u3200-\u33FF\u4DC0-\u4DFF\u9FFD-\u9FFF\uA48D-\uA4CF\uA4FE\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA673\uA67E\uA6F2-\uA716\uA720\uA721\uA789\uA78A\uA7C0\uA7C1\uA7CB-\uA7F4\uA828-\uA82B\uA82D-\uA83F\uA874-\uA87F\uA8C6-\uA8CF\uA8DA-\uA8DF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA954-\uA95F\uA97D-\uA97F\uA9C1-\uA9CE\uA9DA-\uA9DF\uA9FF\uAA37-\uAA3F\uAA4E\uAA4F\uAA5A-\uAA5F\uAA77-\uAA79\uAAC3-\uAADA\uAADE\uAADF\uAAF0\uAAF1\uAAF7-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F\uAB5B\uAB6A-\uAB6F\uABEB\uABEE\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uD7FF\uE000-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB29\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFC-\uFDFF\uFE10-\uFE1F\uFE30-\uFE32\uFE35-\uFE4C\uFE50-\uFE6F\uFE75\uFEFD-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF3E\uFF40\uFF5B-\uFF65\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFFF]|\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDD3F\uDD75-\uDDFC\uDDFE-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEDF\uDEE1-\uDEFF\uDF20-\uDF2C\uDF4B-\uDF4F\uDF7B-\uDF7F\uDF9E\uDF9F\uDFC4-\uDFC7\uDFD0\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56-\uDC5F\uDC77-\uDC7F\uDC9F-\uDCDF\uDCF3\uDCF6-\uDCFF\uDD16-\uDD1F\uDD3A-\uDD7F\uDDB8-\uDDBD\uDDC0-\uDDFF\uDE04\uDE07-\uDE0B\uDE14\uDE18\uDE36\uDE37\uDE3B-\uDE3E\uDE40-\uDE5F\uDE7D-\uDE7F\uDE9D-\uDEBF\uDEC8\uDEE7-\uDEFF\uDF36-\uDF3F\uDF56-\uDF5F\uDF73-\uDF7F\uDF92-\uDFFF]|\uD803[\uDC49-\uDC7F\uDCB3-\uDCBF\uDCF3-\uDCFF\uDD28-\uDD2F\uDD3A-\uDE7F\uDEAA\uDEAD-\uDEAF\uDEB2-\uDEFF\uDF1D-\uDF26\uDF28-\uDF2F\uDF51-\uDFAF\uDFC5-\uDFDF\uDFF7-\uDFFF]|\uD804[\uDC47-\uDC65\uDC70-\uDC7E\uDCBB-\uDCCF\uDCE9-\uDCEF\uDCFA-\uDCFF\uDD35\uDD40-\uDD43\uDD48-\uDD4F\uDD74\uDD75\uDD77-\uDD7F\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDFF\uDE12\uDE38-\uDE3D\uDE3F-\uDE7F\uDE87\uDE89\uDE8E\uDE9E\uDEA9-\uDEAF\uDEEB-\uDEEF\uDEFA-\uDEFF\uDF04\uDF0D\uDF0E\uDF11\uDF12\uDF29\uDF31\uDF34\uDF3A\uDF45\uDF46\uDF49\uDF4A\uDF4E\uDF4F\uDF51-\uDF56\uDF58-\uDF5C\uDF64\uDF65\uDF6D-\uDF6F\uDF75-\uDFFF]|\uD805[\uDC4B-\uDC4F\uDC5A-\uDC5D\uDC62-\uDC7F\uDCC6\uDCC8-\uDCCF\uDCDA-\uDD7F\uDDB6\uDDB7\uDDC1-\uDDD7\uDDDE-\uDDFF\uDE41-\uDE43\uDE45-\uDE4F\uDE5A-\uDE7F\uDEB9-\uDEBF\uDECA-\uDEFF\uDF1B\uDF1C\uDF2C-\uDF2F\uDF3A-\uDFFF]|\uD806[\uDC3B-\uDC9F\uDCEA-\uDCFE\uDD07\uDD08\uDD0A\uDD0B\uDD14\uDD17\uDD36\uDD39\uDD3A\uDD44-\uDD4F\uDD5A-\uDD9F\uDDA8\uDDA9\uDDD8\uDDD9\uDDE2\uDDE5-\uDDFF\uDE3F-\uDE46\uDE48-\uDE4F\uDE9A-\uDE9C\uDE9E-\uDEBF\uDEF9-\uDFFF]|\uD807[\uDC09\uDC37\uDC41-\uDC4F\uDC5A-\uDC71\uDC90\uDC91\uDCA8\uDCB7-\uDCFF\uDD07\uDD0A\uDD37-\uDD39\uDD3B\uDD3E\uDD48-\uDD4F\uDD5A-\uDD5F\uDD66\uDD69\uDD8F\uDD92\uDD99-\uDD9F\uDDAA-\uDEDF\uDEF7-\uDFAF\uDFB1-\uDFFF]|\uD808[\uDF9A-\uDFFF]|\uD809[\uDC6F-\uDC7F\uDD44-\uDFFF]|[\uD80A\uD80B\uD80E-\uD810\uD812-\uD819\uD824-\uD82B\uD82D\uD82E\uD830-\uD833\uD837\uD839\uD83D\uD83F\uD87B-\uD87D\uD87F\uD885-\uDB3F\uDB41-\uDBFF][\uDC00-\uDFFF]|\uD80D[\uDC2F-\uDFFF]|\uD811[\uDE47-\uDFFF]|\uD81A[\uDE39-\uDE3F\uDE5F\uDE6A-\uDECF\uDEEE\uDEEF\uDEF5-\uDEFF\uDF37-\uDF3F\uDF44-\uDF4F\uDF5A-\uDF62\uDF78-\uDF7C\uDF90-\uDFFF]|\uD81B[\uDC00-\uDE3F\uDE80-\uDEFF\uDF4B-\uDF4E\uDF88-\uDF8E\uDFA0-\uDFDF\uDFE2\uDFE5-\uDFEF\uDFF2-\uDFFF]|\uD821[\uDFF8-\uDFFF]|\uD823[\uDCD6-\uDCFF\uDD09-\uDFFF]|\uD82C[\uDD1F-\uDD4F\uDD53-\uDD63\uDD68-\uDD6F\uDEFC-\uDFFF]|\uD82F[\uDC6B-\uDC6F\uDC7D-\uDC7F\uDC89-\uDC8F\uDC9A-\uDC9C\uDC9F-\uDFFF]|\uD834[\uDC00-\uDD64\uDD6A-\uDD6C\uDD73-\uDD7A\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDE41\uDE45-\uDFFF]|\uD835[\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3\uDFCC\uDFCD]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85-\uDE9A\uDEA0\uDEB0-\uDFFF]|\uD838[\uDC07\uDC19\uDC1A\uDC22\uDC25\uDC2B-\uDCFF\uDD2D-\uDD2F\uDD3E\uDD3F\uDD4A-\uDD4D\uDD4F-\uDEBF\uDEFA-\uDFFF]|\uD83A[\uDCC5-\uDCCF\uDCD7-\uDCFF\uDD4C-\uDD4F\uDD5A-\uDFFF]|\uD83B[\uDC00-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDFFF]|\uD83C[\uDC00-\uDD2F\uDD4A-\uDD4F\uDD6A-\uDD6F\uDD8A-\uDFFF]|\uD83E[\uDC00-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEDE-\uDEFF]|\uD86D[\uDF35-\uDF3F]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEA2-\uDEAF]|\uD87A[\uDFE1-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDFFF]|\uDB40[\uDC00-\uDCFF\uDDF0-\uDFFF]/g,kC=Object.hasOwnProperty;var kN=e.i(216920);let kE={},kD=new class{constructor(){this.occurrences,this.reset()}slug(e,r){var s,n;let i=(s=e,n=!0===r,"string"!=typeof s?"":(n||(s=s.toLowerCase()),s.replace(kk,"").replace(/ /g,"-"))),a=i;for(;kC.call(this.occurrences,i);)this.occurrences[a]++,i=a+"-"+this.occurrences[a];return this.occurrences[i]=0,i}reset(){this.occurrences=Object.create(null)}};function kR(e){let r=(e||kE).prefix||"";return function(e){kD.reset(),(0,kN.visit)(e,"element",function(e){let s,n;((n=2===(s="element"===e.type?e.tagName.toLowerCase():"").length&&104===s.charCodeAt(0)?s.charCodeAt(1):0)>48&&n<55?n-48:void 0)&&!e.properties.id&&(e.properties.id=r+kD.slug("children"in e?function e(r){let s=-1,n=[];for(;++s<r.children.length;){var i;n[s]="text"===(i=r.children[s]).type?i.value:"children"in i?e(i):""}return n.join("")}(e):"value"in e?e.value:""))})}}var kT=cj,H=H,kA=e.i(829692),kA=kA;let kI={bash:()=>e.A(350825),c:()=>e.A(637078),cpp:()=>e.A(802318),csharp:()=>e.A(129951),css:()=>e.A(756163),dockerfile:()=>e.A(253540),go:()=>e.A(703741),graphql:()=>e.A(920758),html:()=>e.A(488168),java:()=>e.A(832431),javascript:()=>e.A(857908),json:()=>e.A(699038),jsx:()=>e.A(475799),kotlin:()=>e.A(476532),lua:()=>e.A(930588),makefile:()=>e.A(809849),markdown:()=>e.A(198794),mdx:()=>e.A(186622),php:()=>e.A(931135),python:()=>e.A(435385),r:()=>e.A(995633),ruby:()=>e.A(62790),rust:()=>e.A(733588),scala:()=>e.A(710477),scss:()=>e.A(742937),sql:()=>e.A(546234),svelte:()=>e.A(645265),swift:()=>e.A(993701),toml:()=>e.A(880929),tsx:()=>e.A(427335),typescript:()=>e.A(59512),vue:()=>e.A(945589),xml:()=>e.A(298220),yaml:()=>e.A(405971),zig:()=>e.A(681653)},kM="one-light",kF=null,kP=new Map;async function kL(r){let s=await (kF??=(async()=>{let[{createHighlighterCore:r},{createJavaScriptRegexEngine:s},n,i]=await Promise.all([e.A(733022),e.A(158048),e.A(905359),e.A(617706)]);return r({themes:[n.default,i.default],langs:[],engine:s({forgiving:!0})})})().catch(e=>{throw kF=null,e}));if("text"===r)return s;let n=kP.get(r);return n||(n=kI[r]().then(e=>s.loadLanguage(e.default)).catch(e=>{throw kP.delete(r),e}),kP.set(r,n)),await n,s}let kO=(0,$.createContext)({code:""}),kB={name:"line-data",line(e,r){e.properties["data-line"]=String(r)}},kz={name:"line-numbers",line(e,r){e.children.unshift({type:"element",tagName:"span",properties:{className:["inline-block","min-w-10","mr-2","text-right","select-none","text-muted-foreground"]},children:[{type:"text",value:String(r)}]})}};async function k$(e,r,s=!1,n){let i=[kB];n&&n.size>0&&i.push({name:"fold-gutter",line(e,r){e.children.unshift({type:"element",tagName:"span",properties:n.has(r)?{className:["code-fold-toggle"],"data-fold-start":String(r)}:{className:["code-fold-spacer"]},children:[]})}}),s&&i.push(kz);let a=await kL(r);return[a.codeToHtml(e,{lang:r,theme:kM,transformers:i}),a.codeToHtml(e,{lang:r,theme:"one-dark-pro",transformers:i})]}let kW=(0,$.forwardRef)(function({code:e,language:r,showLineNumbers:s=!1,scrollToLine:n,scrollKey:i,foldable:a=!1,className:o,children:l,...c},d){let[u,h]=(0,$.useState)(""),[f,p]=(0,$.useState)(""),m=(0,$.useRef)(!1),g=(0,$.useRef)(null),x=(0,$.useMemo)(()=>a?function(e,r={}){return function(...e){let r=new Map;for(let s of e.flat())!(s.endLine<=s.startLine)&&(r.has(s.startLine)||r.set(s.startLine,s));let s=[...r.values()].sort((e,r)=>e.startLine-r.startLine||r.endLine-e.endLine),n=[],i=[];for(let e of s){for(;i.length&&i[i.length-1].endLine<e.startLine;)i.pop();let r=i[i.length-1];r&&e.endLine>r.endLine||(n.push(e),i.push(e))}return n}((r.tokenIndex,[]),function(e){let r=e.split("\n"),s=[],n=[],i=0,a=e=>{i>e.line&&s.push({startLine:e.line+1,endLine:i+1})};for(let e=0;e<r.length;e++){let s=function(e){let r=e.match(/^[ \t]*/),s=r?r[0].length:0;return s===e.length?null:s}(r[e]);if(null!==s){for(;n.length&&n[n.length-1].indent>=s;)a(n.pop());n.push({indent:s,line:e}),i=e}}for(;n.length;)a(n.pop());return s}(e))}(e):[],[a,e]),v=(0,$.useMemo)(()=>new Set(x.map(e=>e.startLine)),[x]),[y,b]=(0,$.useState)(new Set),[w,_]=(0,$.useState)(e),[S,j]=(0,$.useState)({line:n,key:i});if((0,$.useImperativeHandle)(d,()=>({foldAll:()=>b(new Set(x.map(e=>e.startLine))),expandAll:()=>b(new Set)}),[x]),(0,$.useEffect)(()=>(k$(e,r,s,v).then(([e,r])=>{m.current||(h(e),p(r),m.current=!0)}),()=>{m.current=!1}),[e,r,s,v]),(0,$.useEffect)(()=>{let e=g.current;if(!e)return;let r=new Map(x.map(e=>[e.startLine,e])),s=new Set;for(let e of y){let n=r.get(e);if(n)for(let e=n.startLine+1;e<=n.endLine;e++)s.add(e)}for(let r of e.querySelectorAll("[data-line]")){let e=Number(r.getAttribute("data-line"));r.style.display=s.has(e)?"none":"",r.classList.toggle("code-line-collapsed",y.has(e))}},[y,x,u,f]),(0,$.useEffect)(()=>{if(!a)return;let e=g.current;if(!e)return;let r=e=>{let r=e.target?.closest?.("[data-fold-start]");if(!r)return;e.stopPropagation(),e.preventDefault();let s=Number(r.getAttribute("data-fold-start"));b(e=>{let r=new Set(e);return r.has(s)?r.delete(s):r.add(s),r})};return e.addEventListener("click",r),()=>e.removeEventListener("click",r)},[a]),(0,$.useEffect)(()=>{if(null==n)return;let e=g.current;if(!e||!u&&!f)return;let r=Array.from(e.querySelectorAll(`[data-line="${n}"]`));if(0===r.length)return;let s=r.find(e=>null!==e.offsetParent)??r[0],i=requestAnimationFrame(()=>{s.scrollIntoView({block:"center",behavior:"auto"}),r.forEach(e=>e.classList.add("code-line-highlight"))}),a=window.setTimeout(()=>r.forEach(e=>e.classList.remove("code-line-highlight")),1600);return()=>{cancelAnimationFrame(i),window.clearTimeout(a),r.forEach(e=>e.classList.remove("code-line-highlight"))}},[n,i,u,f]),e!==w&&(_(e),b(new Set)),(S.line!==n||S.key!==i)&&(j({line:n,key:i}),null!=n&&y.size>0)){let e=!1,r=new Set(y);for(let s of x)r.has(s.startLine)&&n>s.startLine&&n<=s.endLine&&(r.delete(s.startLine),e=!0);e&&b(r)}return(0,z.jsx)(kO.Provider,{value:{code:e},children:(0,z.jsx)("div",{ref:g,className:(0,eb.cn)("group relative w-full overflow-hidden rounded-md border bg-background text-foreground",o),...c,children:(0,z.jsxs)("div",{className:"relative",children:[(0,z.jsx)("div",{className:"overflow-auto dark:hidden [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:grid [&_code]:font-mono [&_code]:text-sm",dangerouslySetInnerHTML:{__html:u}}),(0,z.jsx)("div",{className:"hidden overflow-auto dark:block [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:grid [&_code]:font-mono [&_code]:text-sm",dangerouslySetInnerHTML:{__html:f}}),l&&(0,z.jsx)("div",{className:"absolute top-2 right-2 flex items-center gap-2",children:l})]})})})}),kH=({onCopy:e,onError:r,timeout:s=2e3,children:n,className:i,...a})=>{let[o,l]=(0,$.useState)(!1),{code:c}=(0,$.useContext)(kO),d=async()=>{if(!navigator?.clipboard?.writeText)return void r?.(Error("Clipboard API not available"));try{await navigator.clipboard.writeText(c),l(!0),e?.(),setTimeout(()=>l(!1),s)}catch(e){r?.(e)}},u=o?H.default:kA.default;return(0,z.jsx)(W.Button,{className:(0,eb.cn)("shrink-0",i),onClick:d,size:"icon",variant:"ghost",...a,children:n??(0,z.jsx)(u,{size:14})})};function kU({className:e,...r}){return(0,z.jsx)("div",{"data-slot":"skeleton",className:(0,eb.cn)("bg-accent animate-pulse rounded-md",e),...r})}let kq=/^remote-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-/i;function kK(e){return e?kq.exec(e)?.[1]??null:null}function kV({projectId:e,symbol:r,branch:s,target:n,currentFile:i,anchor:a,onJump:o,onClose:l}){let[c,d]=(0,$.useState)(!0),[u,h]=(0,$.useState)([]),[f,p]=(0,$.useState)(!1),m=(0,$.useRef)(null);(0,$.useEffect)(()=>{let i=!0;return d(!0),ry.api.searchSymbol(e,r,s,n).then(e=>{i&&(h(e.hits),p(e.truncated))}).catch(()=>{i&&h([])}).finally(()=>{i&&d(!1)}),()=>{i=!1}},[e,r,s,n]),(0,$.useEffect)(()=>{let e=e=>{e.detail>=2||m.current&&!m.current.contains(e.target)&&l()},s=e=>{if("Escape"===e.key)return void l();if((e.metaKey||e.ctrlKey)&&("c"===e.key||"C"===e.key)){let s=window.getSelection();if(s&&s.rangeCount>0&&!s.isCollapsed)return;e.preventDefault(),navigator.clipboard?.writeText(r)}};return document.addEventListener("mousedown",e),document.addEventListener("keydown",s),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",s)}},[l,r]);let g=(e,r)=>Number(r.file===i)-Number(e.file===i),x=u.filter(e=>"definition"===e.kind).sort(g),v=u.filter(e=>"reference"===e.kind).sort(g),y=Math.max(8,Math.min(a.x,window.innerWidth-440-8)),b=window.innerHeight-8-(a.y+18),w=a.y-18-8,_=b>=340||b>=w,S=Math.max(120,Math.min(340,_?b:w)),j=_?{top:a.y+18}:{bottom:window.innerHeight-(a.y-18)},k=({hit:e})=>(0,z.jsxs)("button",{type:"button",onClick:()=>{o(e.file,e.line),l()},className:"flex w-full flex-col items-start gap-0.5 rounded px-2 py-1.5 text-left hover:bg-accent",children:[(0,z.jsxs)("span",{className:"flex w-full items-baseline justify-between gap-2",children:[(0,z.jsxs)("span",{className:"truncate font-mono text-xs",children:[e.file.split("/").pop(),(0,z.jsxs)("span",{className:"text-muted-foreground",children:[":",e.line]})]}),e.file===i&&(0,z.jsx)("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:"this file"})]}),(0,z.jsx)("code",{className:"w-full truncate text-xs text-muted-foreground",children:e.text.trim()})]}),C=({title:e,children:r})=>(0,z.jsxs)("div",{className:"mb-1",children:[(0,z.jsx)("div",{className:"px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:e}),r]});return(0,ee.createPortal)((0,z.jsxs)("div",{ref:m,style:{left:y,...j,width:440,maxHeight:S},className:"fixed z-50 flex flex-col overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-lg select-none",children:[(0,z.jsx)("div",{className:"border-b px-3 py-1.5 text-xs font-medium",children:(0,z.jsx)("span",{className:"font-mono",children:r})}),(0,z.jsx)("div",{className:"flex-1 overflow-auto p-1",children:c?(0,z.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"})," Searching…"]}):0===u.length?(0,z.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No results."}):(0,z.jsxs)(z.Fragment,{children:[x.length>0&&(0,z.jsx)(C,{title:`Definitions (${x.length})`,children:x.map((e,r)=>(0,z.jsx)(k,{hit:e},`d-${r}`))}),v.length>0&&(0,z.jsx)(C,{title:`References (${v.length})`,children:v.map((e,r)=>(0,z.jsx)(k,{hit:e},`r-${r}`))}),f&&(0,z.jsx)("div",{className:"px-2 py-1.5 text-[11px] text-muted-foreground",children:"Showing first matches — results truncated."})]})})]}),document.body)}let kX=(0,e_.default)("image-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]);function kY({projectId:e,filePath:r,branch:s,target:n,sessionId:i,onDownload:a}){let[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(!1);return((0,$.useEffect)(()=>{let a=null,o=!1;return ry.api.getFileBlob(e,r,s,n,i).then(({blob:e})=>{o||l(a=URL.createObjectURL(e))}).catch(()=>{o||d(!0)}),()=>{o=!0,a&&URL.revokeObjectURL(a)}},[e,r,s,n,i]),c)?(0,z.jsxs)("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[(0,z.jsx)(kX,{className:"h-10 w-10"}),(0,z.jsx)("p",{className:"text-sm",children:"Couldn't load image"}),(0,z.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:a,children:[(0,z.jsx)(kb,{className:"h-4 w-4 mr-2"}),"Download"]})]}):o?(0,z.jsx)("div",{className:"flex items-center justify-center h-full p-4 bg-muted/30",children:(0,z.jsx)("img",{src:o,alt:r.split("/").pop()??"image",className:"max-w-full max-h-full object-contain",onError:()=>d(!0)})}):(0,z.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,z.jsx)(sC,{className:"h-6 w-6 animate-spin"})})}async function kG(e,r){let s=(await kL(r)).codeToTokensBase(e,{lang:r,theme:kM,includeExplanation:"scopeName"}),n=new Map;return s.forEach((e,r)=>{let s=0,i=[];for(let r of e){let e=(r.explanation??[]).flatMap(e=>e.scopes.map(e=>e.scopeName)),n=s+r.content.length;i.push({start:s,end:n,kind:e.some(e=>e.startsWith("comment"))?"comment":e.some(e=>e.startsWith("string")||e.startsWith("constant.character"))?"string":e.some(e=>e.startsWith("keyword")||e.startsWith("storage")||e.startsWith("constant.language")||e.startsWith("variable.language"))?"keyword":"code"}),s=n}n.set(r+1,i)}),n}let kJ=new Set(["png","jpg","jpeg","gif","webp","bmp","ico","avif","svg"]);function kZ(e){let r=e.split("/").pop()?.split(".").pop()?.toLowerCase()??"";return kJ.has(r)}let kQ=/^[A-Za-z_$][A-Za-z0-9_$]*$/,k0="symbol-nav";function k1(e,r,s){let n=document.createRange();return n.selectNodeContents(e),n.setEnd(r,s),n.toString().length}function k2(e,r){let s,n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),i=0;for(;s=n.nextNode();){let e=(s.textContent??"").length;if(r<=i+e)return{node:s,offset:r-i};i+=e}return null}function k5(e){let r=Array.from(document.querySelectorAll(`[data-line="${CSS.escape(e.line)}"]`)),s=r.find(e=>null!==e.offsetParent)??r[0];if(!s)return null;let n=k2(s,e.start),i=k2(s,e.end);if(!n||!i)return null;let a=document.createRange();return a.setStart(n.node,n.offset),a.setEnd(i.node,i.offset),a}let k3=/[A-Za-z0-9_$]/;function k4(e,r,s){let n=document,i=null,a=0;if(n.caretRangeFromPoint){let s=n.caretRangeFromPoint(e,r);s&&(i=s.startContainer,a=s.startOffset)}else if(n.caretPositionFromPoint){let s=n.caretPositionFromPoint(e,r);s&&(i=s.offsetNode,a=s.offset)}if(!i||i.nodeType!==Node.TEXT_NODE)return null;let o=i.textContent??"",l=a,c=a;for(;l>0&&k3.test(o[l-1]);)l--;for(;c<o.length&&k3.test(o[c]);)c++;if(l>=c)return null;let d=o.slice(l,c);if(!kQ.test(d))return null;let u=document.createRange();u.setStart(i,l),u.setEnd(i,c);let h=function(e){let r=e.startContainer.nodeType===Node.ELEMENT_NODE?e.startContainer:e.startContainer.parentElement,s=r?.closest("[data-line]");if(!s||!s.contains(e.endContainer))return null;let n=s.getAttribute("data-line");if(null===n)return null;let i=k1(s,e.startContainer,e.startOffset),a=k1(s,e.endContainer,e.endOffset);return i>=a?null:{line:n,start:i,end:a}}(u);if(!h)return null;if(s){let e=h.start-h.line.length,r=function(e,r,s){let n=e.get(r);if(!n)return null;for(let e of n)if(s>=e.start&&s<e.end)return e.kind;return null}(s,Number(h.line),e);if(r&&"code"!==r)return null}return{word:d,anchor:h}}function k6(){return"undefined"!=typeof CSS&&"highlights"in CSS&&"undefined"!=typeof Highlight}let k7=!1;function k8(){k6()&&CSS.highlights.delete(k0)}let k9={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",css:"css",scss:"scss",html:"html",vue:"vue",svelte:"svelte",php:"php",swift:"swift",kt:"kotlin",sh:"bash",bash:"bash",zsh:"bash",yaml:"yaml",yml:"yaml",toml:"toml",json:"json",xml:"xml",sql:"sql",graphql:"graphql",md:"markdown",mdx:"mdx",dockerfile:"dockerfile",makefile:"makefile",lua:"lua",r:"r",scala:"scala",zig:"zig"};function Ce(e){let r=e.split("/").pop()?.toLowerCase()??"";return"dockerfile"===r?"dockerfile":"makefile"===r?"makefile":k9[r.split(".").pop()?.toLowerCase()??""]??"text"}function Ct(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function Cr({filePath:e,fileContent:r,loading:s,downloadUrl:n,projectId:i,branch:a,target:o,sessionId:l,scrollToLine:c,scrollKey:d,onJump:u,restoreScrollTop:h,restoreScrollKey:f,onScroll:p}){let m,g=r?.serverId??null,{label:x}=gf(g&&g!==kK(l)?g:null),[v,y]=(0,$.useState)("rendered"),[b,w]=(0,$.useState)(e),[_,S]=(0,$.useState)(null),j=(0,$.useRef)(null),k=(0,$.useRef)(null),C=(0,$.useRef)(!1);(0,$.useEffect)(()=>{C.current=null!==_},[_]);let N=(0,$.useCallback)(e=>{if(e.detail>=2){let r=window.getSelection();if(C.current){r?.removeAllRanges(),S(e=>e?{...e,selectWord:!0}:e);return}let s=k4(e.clientX,e.clientY),n=s?k5(s.anchor):null;n&&(r?.removeAllRanges(),r?.addRange(n));return}let r=window.getSelection();if(r&&!r.isCollapsed)return;let s=k4(e.clientX,e.clientY,j.current);s&&(r?.removeAllRanges(),S({symbol:s.word,x:e.clientX,y:e.clientY,anchor:s.anchor,selectWord:!1}))},[]),E=(0,$.useCallback)(e=>{e.detail>=2&&e.preventDefault()},[]);(0,$.useEffect)(()=>{if(!_?.anchor)return void k8();let e=k5(_.anchor);if(!e)return void k8();if(_.selectWord){k8();let r=window.getSelection();r?.removeAllRanges(),r?.addRange(e);return}return k6()?(!function(){if(k7||"undefined"==typeof document)return;k7=!0;let e=document.createElement("style");e.textContent=`::highlight(${k0}){background-color:rgba(255, 196, 0, 0.32);}`,document.head.appendChild(e)}(),CSS.highlights.set(k0,new Highlight(e)),k8):void k8()},[_]),(0,$.useEffect)(()=>{j.current=null;let s=r?.content;if(!e||null==s||r?.binary||r?.tooLarge)return;let n=!1;return kG(s,Ce(e)).then(e=>{n||(j.current=e)}).catch(()=>{}),()=>{n=!0}},[e,r]);let D=(0,$.useRef)(null),R=(0,$.useRef)(null),T=(0,$.useCallback)(e=>{let r=D.current;if(!r)return;let s=r.querySelector(`[id="${CSS.escape(e)}"]`);if(!s)return;R.current?.();let n=()=>s.scrollIntoView({block:"start",behavior:"auto"});n();let i=new ResizeObserver(n);i.observe(r);let a=()=>{i.disconnect(),window.clearTimeout(o),window.removeEventListener("wheel",a),window.removeEventListener("touchmove",a),window.removeEventListener("keydown",a),R.current=null},o=window.setTimeout(a,1e3);window.addEventListener("wheel",a,{passive:!0}),window.addEventListener("touchmove",a,{passive:!0}),window.addEventListener("keydown",a),R.current=a},[]);(0,$.useEffect)(()=>()=>R.current?.(),[]);let A=(0,$.useRef)(null),I=(0,$.useRef)(!1),M=(0,$.useRef)(p);M.current=p;let F=(0,$.useRef)(null),P=(0,$.useRef)(null),L=(0,$.useCallback)(e=>{if(I.current)return;let r=e.currentTarget.scrollTop;F.current&&clearTimeout(F.current),F.current=setTimeout(()=>M.current?.(r),200)},[]);(0,$.useEffect)(()=>{void 0!==f&&(P.current=h??0)},[f,h]),(0,$.useEffect)(()=>{let e=A.current;e&&(e.scrollTop=0)},[e]),(0,$.useEffect)(()=>{let e=P.current;if(null==e)return;let r=A.current;if(!r||(P.current=null,!e))return;I.current=!0;let s=()=>{r.scrollTop=e};s();let n=new ResizeObserver(s);n.observe(r.firstElementChild??r);let i=()=>{I.current=!1,n.disconnect(),window.clearTimeout(a),r.removeEventListener("wheel",i),r.removeEventListener("touchmove",i),r.removeEventListener("keydown",i)},a=window.setTimeout(i,1500);return r.addEventListener("wheel",i,{passive:!0}),r.addEventListener("touchmove",i,{passive:!0}),r.addEventListener("keydown",i),i},[r]);let O=(0,$.useMemo)(()=>[...Object.values(kT.e),kR],[]),B=(0,$.useMemo)(()=>({a:({href:e,children:r,className:s,node:n,...i})=>{let a="string"==typeof e&&e.startsWith("#");return(0,z.jsx)("a",{href:e,className:(0,eb.cn)("wrap-anywhere font-medium text-primary underline",s),"data-streamdown":"link",...a?{onClick:r=>{r.preventDefault(),T(decodeURIComponent(e.slice(1)))}}:{target:"_blank",rel:"noreferrer"},...i,children:r})}}),[T]);if(e!==b&&(w(e),y("rendered"),S(null)),!e)return(0,z.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:"Select a file to preview."});if(s)return(0,z.jsxs)("div",{className:"flex flex-col h-full",children:[(0,z.jsx)("div",{className:"flex items-center justify-between px-4 py-2 border-b flex-shrink-0",children:(0,z.jsx)(kU,{className:"h-4 w-48"})}),(0,z.jsxs)("div",{className:"flex-1 p-4",children:[(0,z.jsx)(kU,{className:"h-4 w-full mb-2"}),(0,z.jsx)(kU,{className:"h-4 w-3/4 mb-2"}),(0,z.jsx)(kU,{className:"h-4 w-5/6 mb-2"}),(0,z.jsx)(kU,{className:"h-4 w-2/3"})]})]});if(!r)return(0,z.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:"Failed to load file."});let H=()=>{e&&ry.api.downloadFile(i,e,a,o,l).catch(e=>{console.error("Failed to download file",e)})},U=("markdown"===(m=Ce(e))||"mdx"===m)&&!r.tooLarge&&!r.binary&&!!r.content,q=U&&"rendered"===v,K=!r.tooLarge&&!r.binary&&!q&&null!==r.content;return(0,z.jsxs)("div",{className:"flex flex-col h-full",children:[(0,z.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b flex-shrink-0 gap-2",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,z.jsx)("span",{className:"text-sm font-mono truncate",children:e}),(0,z.jsx)("span",{className:"text-xs text-muted-foreground shrink-0",children:Ct(r.size)}),x&&(0,z.jsxs)("span",{className:"text-xs text-muted-foreground shrink-0",children:["on ",(0,z.jsx)("span",{className:"text-foreground",children:x})]})]}),(0,z.jsxs)("div",{className:"flex items-center gap-1 shrink-0",children:[U&&(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>y(e=>"rendered"===e?"source":"rendered"),title:q?"View source":"View rendered",children:q?(0,z.jsx)(k_,{className:"h-3.5 w-3.5"}):(0,z.jsx)(_P,{className:"h-3.5 w-3.5"})}),K&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>k.current?.foldAll(),title:"Fold all",children:(0,z.jsx)(kS,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>k.current?.expandAll(),title:"Expand all",children:(0,z.jsx)(kj,{className:"h-3.5 w-3.5"})})]}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{navigator.clipboard.writeText(e)},title:"Copy path",children:(0,z.jsx)(me.Copy,{className:"h-3.5 w-3.5"})}),n&&(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:H,title:"Download",children:(0,z.jsx)(kb,{className:"h-3.5 w-3.5"})})]})]}),(0,z.jsx)("div",{className:"flex-1 overflow-auto",ref:A,onScroll:L,children:r.tooLarge?(0,z.jsxs)("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[(0,z.jsx)(kw,{className:"h-10 w-10"}),(0,z.jsxs)("p",{className:"text-sm",children:["File too large to preview (",Ct(r.size),")"]}),n&&(0,z.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:H,children:[(0,z.jsx)(kb,{className:"h-4 w-4 mr-2"}),"Download"]})]}):r.binary&&kZ(e)&&r.size<=0xa00000?(0,z.jsx)(kY,{projectId:i,filePath:e,branch:a,target:o,sessionId:l,onDownload:H},e):r.binary?(0,z.jsxs)("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[(0,z.jsx)(kw,{className:"h-10 w-10"}),(0,z.jsx)("p",{className:"text-sm",children:kZ(e)?`Image too large to preview (${Ct(r.size)})`:`Binary file (${Ct(r.size)})`}),n&&(0,z.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:H,children:[(0,z.jsx)(kb,{className:"h-4 w-4 mr-2"}),"Download"]})]}):q?(0,z.jsx)("div",{className:"p-4",style:{fontSize:"var(--files-content-font-size, 14px)"},ref:D,children:(0,z.jsx)(cE,{components:B,rehypePlugins:O,children:r.content??""})}):null!==r.content?(0,z.jsx)("div",{className:"h-full [&_pre]:text-[length:var(--files-content-font-size,14px)]! [&_code]:text-[length:var(--files-content-font-size,14px)]!",onMouseDown:E,onClick:N,children:(0,z.jsx)(kW,{ref:k,code:r.content,language:Ce(e),showLineNumbers:!0,foldable:!0,scrollToLine:c,scrollKey:d,className:"border-0 rounded-none",children:(0,z.jsx)(kH,{})})}):(0,z.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:"Empty file."})}),_&&(0,z.jsx)(kV,{projectId:i,symbol:_.symbol,branch:a,target:o,currentFile:e,anchor:{x:_.x,y:_.y},onJump:u,onClose:()=>S(null)})]})}class Cs{capacity;map;constructor(e){if(this.capacity=e,this.map=new Map,e<1)throw Error("LRUCache capacity must be at least 1")}get(e){if(!this.map.has(e))return;let r=this.map.get(e);return this.map.delete(e),this.map.set(e,r),r}has(e){return this.map.has(e)}set(e,r){for(this.map.has(e)&&this.map.delete(e),this.map.set(e,r);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(void 0===e)break;this.map.delete(e)}}delete(e){return this.map.delete(e)}deleteWhere(e){for(let r of[...this.map.keys()])e(r)&&this.map.delete(r)}clear(){this.map.clear()}get size(){return this.map.size}}let Cn="vibedeckx:files:views";function Ci(){return{v:1,views:{}}}function Ca(){try{let e=localStorage.getItem(Cn);if(!e)return Ci();let r=JSON.parse(e);if(!r||1!==r.v||!r.views||"object"!=typeof r.views)return Ci();return r}catch{return Ci()}}function Co(e){try{localStorage.setItem(Cn,JSON.stringify(e))}catch{}}let Cl=[],Cc=new Map,Cd=new Set;function Cu(e){return e.slice(e.lastIndexOf("\0")+1)}function Ch({projectId:e,project:r,selectedBranch:s,navRequest:n,sessionId:i,active:a=!0}){let o=r&&!r.path?"remote":void 0,[l,c]=(0,$.useState)(!1),{settings:d}=(0,mo.useConversationSettings)(),u=(0,$.useRef)(null),[h,f]=(0,$.useState)(!1),p=(0,$.useCallback)(()=>{let e=u.current;e&&(e.isCollapsed()?e.expand():e.collapse())},[]),{rootEntries:m,directoryContents:g,expandedDirs:x,selectedFile:v,fileContent:y,fileLoading:b,rootLoading:w,loadingDirs:_,uploadingDirs:S,deletingPaths:j,jumpTarget:k,canGoBack:C,canGoForward:N,fetchRoot:E,refresh:D,reportScroll:R,restoreScroll:T,toggleDirectory:A,navigate:I,jumpTo:M,goBack:F,goForward:P,uploadFiles:L,deleteEntry:O}=function({projectId:e,branch:r,target:s,sessionId:n,showHidden:i=!1}){let[a,o]=(0,$.useState)([]),[l,c]=(0,$.useState)(new Map),[d,u]=(0,$.useState)(new Set),[h,f]=(0,$.useState)(null),[p,m]=(0,$.useState)(null),[g,x]=(0,$.useState)(null),v=(0,$.useRef)(0),[y,b]=(0,$.useState)({entries:[],index:-1}),w=(0,$.useRef)(y);w.current=y;let[_,S]=(0,$.useState)(!1),[j,k]=(0,$.useState)(!1),[C,N]=(0,$.useState)(new Set),[E,D]=(0,$.useState)(new Set),[R,T]=(0,$.useState)(new Set),A=(0,$.useRef)(0),I=(0,$.useRef)(0),M=(0,$.useRef)(new Cs(50)),F=e?[e,r??"",s??""].join("|"):null,P=(0,$.useRef)(F);P.current=F;let L=(0,$.useRef)(h);L.current=h;let O=(0,$.useRef)(0),B=(0,$.useRef)(null),z=(0,$.useRef)(0),[W,H]=(0,$.useState)(null),[U,q]=(0,$.useState)(null),K=(0,$.useRef)(null),V=(0,$.useCallback)(i=>[e,r??"",s??"",i.startsWith("/")||i.startsWith("~")?n??"":"",i].join("\0"),[e,r,s,n]),X=(0,$.useCallback)(()=>{let e,r,s=P.current;if(!s||B.current!==s)return;let n={selectedFile:L.current,history:w.current,scrollTop:O.current};(e=Ca()).views[s]={...n,updatedAt:Date.now()},(r=Object.keys(e.views)).length>30&&r.sort((r,s)=>e.views[r].updatedAt-e.views[s].updatedAt).slice(0,r.length-30).forEach(r=>delete e.views[r]),Co(e)},[]),Y=(0,$.useCallback)(()=>{K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{K.current=null,X()},300)},[X]),G=(0,$.useCallback)(e=>{O.current=e,Y()},[Y]);(0,$.useEffect)(()=>{Y()},[h,y,Y]);let J=(0,$.useCallback)(async n=>{if(e&&(u(e=>{let r=new Set(e);return r.has(n)?r.delete(n):r.add(n),r}),!l.has(n))){let a=P.current;N(e=>new Set(e).add(n));try{let o=await ry.api.browseProjectDirectory(e,n,r,s,i);if(P.current!==a)return;c(e=>{let r=new Map(e);return r.set(n,o.items),r})}catch(e){console.error("Failed to browse directory:",e),gS.toast.error(`Failed to open ${n}`,{description:e instanceof Error?e.message:String(e)})}finally{N(e=>{let r=new Set(e);return r.delete(n),r})}}},[e,r,s,i,l]),Z=(0,$.useCallback)(async i=>{if(!e)return"failed";let a=V(i),o=++I.current,l=M.current.get(a);if(l)return m(l),S(!1),"loaded";S(!0),m(null);try{let l=await ry.api.getFileContent(e,i,r,s,n);if(o!==I.current)return"stale";return M.current.set(a,l),m(l),"loaded"}catch(e){if(o!==I.current)return"stale";return console.error("Failed to get file content:",e),m(null),"failed"}finally{o===I.current&&S(!1)}},[e,r,s,n,V]),Q=(0,$.useCallback)(async r=>{e&&(f(r),await Z(r))},[e,Z]),ee=(0,$.useCallback)(async()=>{if(!e)return"stale";k(!0);let n=++A.current;try{let a=await ry.api.browseProjectDirectory(e,void 0,r,s,i);if(n!==A.current)return"stale";return o(a.items),c(new Map),u(new Set),"loaded"}catch(e){if(console.error("Failed to browse root directory:",e),n!==A.current)return"stale";return o([]),gS.toast.error("Failed to browse files",{description:e instanceof Error?e.message:String(e)}),"failed"}finally{n===A.current&&k(!1)}},[e,r,s,i]),et=(0,$.useCallback)(async()=>{let r;if(!e)return;let s=await ee();if("stale"===s)return;let n=P.current;if("failed"===s){B.current!==n&&(++I.current,S(!1),f(null),m(null),b({entries:[],index:-1}),O.current=0),q(n);return}let i=n?(r=Ca().views[n])&&"object"==typeof r&&(null===r.selectedFile||"string"==typeof r.selectedFile)&&r.history&&"object"==typeof r.history&&Array.isArray(r.history.entries)&&"number"==typeof r.history.index?{selectedFile:r.selectedFile,history:r.history,scrollTop:"number"==typeof r.scrollTop&&Number.isFinite(r.scrollTop)?r.scrollTop:0}:null:null;if(n&&i&&i.selectedFile){if(b(i.history.entries.length?i.history:{entries:[{path:i.selectedFile,line:null}],index:0}),O.current=i.scrollTop,H({top:i.scrollTop,nonce:++z.current}),f(i.selectedFile),B.current=n,q(n),"failed"===await Z(i.selectedFile)){let e;f(null),b({entries:[],index:-1}),O.current=0,(e=Ca()).views[n]&&(delete e.views[n],Co(e))}}else++I.current,S(!1),f(null),m(null),b({entries:[],index:-1}),O.current=0,B.current=n,q(n)},[e,ee,Z]),er=(0,$.useCallback)(async()=>{if(!e||(M.current.clear(),"loaded"!==await ee()))return;let r=L.current;r&&await Z(r)},[e,ee,Z]),es=(0,$.useCallback)(async(e,r=null)=>{b(({entries:s,index:n})=>{let i=s[n];if(i&&i.path===e){let i=s.slice();return i[n]={path:e,line:r},{entries:i,index:n}}let a=s.slice(0,n+1);return{entries:[...a,{path:e,line:r}],index:a.length}}),await Q(e),null!=r&&x({line:r,nonce:++v.current})},[Q]),en=(0,$.useCallback)((e,r)=>es(e,r),[es]),ei=(0,$.useCallback)(()=>{let{entries:e,index:r}=w.current;if(r<=0)return;let s=e[r-1];b(e=>({...e,index:e.index-1})),Q(s.path),null!=s.line&&x({line:s.line,nonce:++v.current})},[Q]),ea=(0,$.useCallback)(()=>{let{entries:e,index:r}=w.current;if(r>=e.length-1)return;let s=e[r+1];b(e=>({...e,index:e.index+1})),Q(s.path),null!=s.line&&x({line:s.line,nonce:++v.current})},[Q]),eo=(0,$.useCallback)(async n=>{if(!e)return;let a=P.current;if(""===n){let n=await ry.api.browseProjectDirectory(e,void 0,r,s,i);if(P.current!==a)return;o(n.items)}else{let o=await ry.api.browseProjectDirectory(e,n,r,s,i);if(P.current!==a)return;c(e=>{let r=new Map(e);return r.set(n,o.items),r})}},[e,r,s,i]),el=(0,$.useCallback)(async(n,i)=>{if(!e||0===i.length)return;let a=P.current;D(e=>new Set(e).add(n));try{let{uploaded:o}=await ry.api.uploadFiles(e,i,n,r,s),l=new Set(o.map(e=>n?`${n}/${e}`:e));M.current.deleteWhere(e=>l.has(Cu(e))),P.current===a&&(""!==n&&u(e=>new Set(e).add(n)),await eo(n)),gS.toast.success(`Uploaded ${o.length} file${1===o.length?"":"s"}`)}catch(e){console.error("Failed to upload files:",e),gS.toast.error("Upload failed",{description:e instanceof Error?e.message:String(e)})}finally{D(e=>{let r=new Set(e);return r.delete(n),r})}},[e,r,s,eo]),ec=(0,$.useCallback)(async n=>{if(!e||!n)return;let i=P.current;T(e=>new Set(e).add(n));try{if(await ry.api.deleteFile(e,n,r,s),M.current.deleteWhere(e=>{let r=Cu(e);return r===n||r.startsWith(`${n}/`)}),P.current===i){f(e=>e===n||e&&e.startsWith(`${n}/`)?(m(null),null):e);let e=n.includes("/")?n.slice(0,n.lastIndexOf("/")):"";await eo(e)}gS.toast.success("Deleted")}catch(e){console.error("Failed to delete:",e),gS.toast.error("Delete failed",{description:e instanceof Error?e.message:String(e)})}finally{T(e=>{let r=new Set(e);return r.delete(n),r})}},[e,r,s,eo]),ed=null!==F&&U===F;return{rootEntries:ed?a:Cl,directoryContents:ed?l:Cc,expandedDirs:ed?d:Cd,selectedFile:ed?h:null,fileContent:ed?p:null,fileLoading:ed&&_,rootLoading:j||null!==e&&!ed,loadingDirs:C,uploadingDirs:E,deletingPaths:R,jumpTarget:ed?g:null,canGoBack:ed&&y.index>0,canGoForward:ed&&y.index<y.entries.length-1,fetchRoot:et,refresh:er,reportScroll:G,restoreScroll:ed?W:null,toggleDirectory:J,selectFile:Q,navigate:es,jumpTo:en,goBack:ei,goForward:ea,uploadFiles:el,refreshDirectory:eo,deleteEntry:ec}}({projectId:e,branch:s,target:o,sessionId:i,showHidden:l}),B=function({projectId:e,branch:r,target:s}){let[n,i]=(0,$.useState)([]),[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(!1),[d,u]=(0,$.useState)(!1),[h,f]=(0,$.useState)(""),p=(0,$.useRef)(0);(0,$.useEffect)(()=>{i([]),o(!1),u(!1),c(!1),f(""),p.current++},[e,r,s]);let m=(0,$.useCallback)(async()=>{if(!e)return;c(!0);let n=++p.current;try{let a=await ry.api.listProjectFiles(e,r,s);if(n!==p.current)return;i(a.files),o(a.truncated),u(!0)}catch(e){if(n!==p.current)return;i([]),u(!1),gS.toast.error("Failed to load file list",{description:e instanceof Error?e.message:String(e)})}finally{n===p.current&&c(!1)}},[e,r,s]),g=(0,$.useCallback)(()=>{d||l||m()},[d,l,m]),x=(0,$.useCallback)(()=>{u(!1),p.current++,h&&m()},[h,m]),v=(0,$.useDeferredValue)(h);return{query:h,setQuery:f,results:(0,$.useMemo)(()=>(function(e,r,s){if(!r.trim())return[];let n=[];for(let s of e){let e=dx(r,s);null!==e&&n.push({path:s,score:e})}return n.sort((e,r)=>r.score-e.score||e.path.length-r.path.length),n.slice(0,50)})(n,v,0),[n,v]),truncated:a,loading:l,loaded:d,ensureLoaded:g,refresh:x}}({projectId:e,branch:s,target:o});(0,$.useEffect)(()=>{E()},[E]),(0,$.useEffect)(()=>{n&&(null!=n.line?M(n.path,n.line):I(n.path))},[n?.nonce]);let H=(0,$.useCallback)(()=>{D(),B.refresh()},[D,B]),U=(0,$.useCallback)(e=>{I(e),B.setQuery("")},[I,B]);if(!e)return(0,z.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(mt,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to browse files."})]})});let q=v&&e?ry.api.getFileDownloadUrl(e,v,s,o,i):null;return(0,z.jsxs)("div",{className:"flex flex-col h-full",style:{"--files-tree-font-size":`${d.filesTreeFontSize}px`,"--files-content-font-size":`${d.filesContentFontSize}px`},children:[(0,z.jsx)(dB,{title:"Files",actions:(0,z.jsxs)("div",{className:"flex items-center gap-1",children:[(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:p,title:h?"Show file tree":"Hide file tree","aria-pressed":!h,children:h?(0,z.jsx)(ke,{className:"h-3.5 w-3.5"}):(0,z.jsx)(j9,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:`h-7 w-7 hover:text-foreground ${l?"text-foreground":"text-muted-foreground"}`,onClick:()=>c(e=>!e),title:l?"Hide hidden files":"Show hidden files","aria-pressed":l,children:l?(0,z.jsx)(_P,{className:"h-3.5 w-3.5"}):(0,z.jsx)(_L,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:F,disabled:!C,title:"Back",children:(0,z.jsx)(n4.ArrowLeft,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:P,disabled:!N,title:"Forward",children:(0,z.jsx)(kt,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:H,title:"Refresh",children:(0,z.jsx)(mt,{className:`h-3.5 w-3.5 ${w?"animate-spin":""}`})})]})}),(0,z.jsxs)(uZ,{direction:"horizontal",autoSaveId:"files-panels",className:"flex-1",children:[(0,z.jsx)(d0,{ref:u,collapsible:!0,collapsedSize:0,defaultSize:33,minSize:20,onCollapse:()=>f(!0),onExpand:()=>f(!1),children:(0,z.jsxs)(p_,{shouldFilter:!1,className:"flex h-full flex-col bg-transparent",children:[(0,z.jsx)("div",{className:"border-b p-2",children:(0,z.jsxs)(kr,{children:[(0,z.jsx)(kn,{children:(0,z.jsx)(sA,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(ko,{type:"search",name:"files-search",autoComplete:"off","data-1p-ignore":!0,"data-lpignore":"true","data-form-type":"other",readOnly:!0,onFocus:e=>{e.currentTarget.removeAttribute("readonly"),B.ensureLoaded()},placeholder:"Search files...",value:B.query,onChange:e=>B.setQuery(e.target.value)}),B.query&&(0,z.jsx)(kn,{align:"inline-end",children:(0,z.jsx)(ka,{size:"icon-xs","aria-label":"Clear search",onClick:()=>B.setQuery(""),children:(0,z.jsx)(t7,{className:"h-3.5 w-3.5"})})})]})}),B.query?(0,z.jsx)(pk,{className:"max-h-none flex-1",children:B.loading&&0===B.results.length?(0,z.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"}),"Loading files…"]}):0===B.results.length?(0,z.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No matching files."}):(0,z.jsxs)(z.Fragment,{children:[B.results.map(e=>{let r=e.path.lastIndexOf("/"),s=r>=0?e.path.slice(0,r+1):"",n=r>=0?e.path.slice(r+1):e.path;return(0,z.jsxs)(pE,{value:e.path,onSelect:()=>U(e.path),className:"flex-col items-start gap-0 text-[length:var(--files-tree-font-size,14px)]!",children:[(0,z.jsx)("span",{className:"font-medium",children:n}),s&&(0,z.jsx)("span",{className:"w-full truncate text-xs text-muted-foreground",children:s})]},e.path)}),B.truncated&&(0,z.jsx)("div",{className:"px-2 py-2 text-xs text-muted-foreground",children:"Showing first 50,000 files — refine your search to narrow results."})]})}):(0,z.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,z.jsx)(ky,{entries:m,expandedDirs:x,directoryContents:g,loadingDirs:_,selectedFile:v,uploadingDirs:S,rootLoading:w,deletingPaths:j,onToggleDirectory:A,onSelectFile:I,onUploadFiles:L,onDeleteEntry:O})})]})}),(0,z.jsx)(uQ,{withHandle:!0,disabled:!a}),(0,z.jsx)(d0,{defaultSize:67,minSize:25,children:(0,z.jsx)("div",{className:"h-full overflow-hidden",children:(0,z.jsx)(Cr,{filePath:v,fileContent:y,loading:b,downloadUrl:q,projectId:e,branch:s,target:o,sessionId:i,scrollToLine:k?.line??null,scrollKey:k?.nonce,onJump:M,restoreScrollTop:T?.top??null,restoreScrollKey:T?.nonce,onScroll:R})})})]})]})}let Cf=(0,$.createContext)(null),Cp={openFile:()=>{},index:null,scope:null};function Cm(){return(0,$.useContext)(Cf)??Cp}let Cg=Cf.Provider,Cx=0;function Cv(e){let r=e.lastIndexOf("/");return r>=0?e.slice(r+1):e}function Cy(e,r){let s=`idx-${++Cx}`,n=new Set(e),i=r?r.replace(/\/+$/,"")+"/":null,a=new Map;for(let r of e){let e=Cv(r),s=a.get(e);s?s.push(r):a.set(e,[r])}return{version:s,resolve(e){if(!e)return[];if(i&&(e.startsWith("/")||e.startsWith("~/"))){if(!e.startsWith(i))return[];let r=e.slice(i.length);return n.has(r)?[r]:[]}let r=e.replace(/^\/+/,"");if(!r)return[];if(r.includes("/")){if(n.has(r))return[r];let e=Cv(r);return(a.get(e)??[]).filter(e=>e===r||e.endsWith("/"+r)||r.endsWith("/"+e))}return a.get(r)??[]}}}let Cb=[500,1e3,2e3,4e3,8e3];async function Cw(e,r={}){let s=r.delaysMs??Cb,n=r.sleep??(e=>new Promise(r=>setTimeout(r,e))),i=r.cancelled??(()=>!1);for(let r=0;;r++){if(i())return null;let a=null;try{a=await e()}catch{a=null}if(i())return null;if(a&&a.files.length>0||r>=s.length)return a;await n(s[r])}}let C_=(0,$.createContext)({active:!1,requestNonce:0}),CS=C_.Provider,Cj={agent:sS,executors:gM,diff:sq,terminal:p9,preview:rw,files:rb},Ck=fv.map(e=>({...e,icon:Cj[e.id]})),CC=()=>()=>{},CN=$.useLayoutEffect;function CE({projectId:e,selectedBranch:r,onMergeRequest:s,project:n,onExecutorModeChange:i,agentSlot:a,activateAgentTabNonce:o,diffCompareNonce:l,terminalRequest:c,mergeTarget:d,forceAgentTab:u=!1,active:h=!0,agentSessionId:f=null}){let[p,m]=function(e,r){let s=`vibedeckx:activeTab:${e??"none"}:${r??"main"}`,[n,i]=(0,$.useState)(()=>localStorage.getItem(s)??"agent");return CN(()=>{i(localStorage.getItem(s)??"agent")},[s]),[n,(0,$.useCallback)(e=>{i(e),localStorage.setItem(s,e)},[s])]}(e,r),g=u?"agent":p,x=(0,$.useRef)(o);CN(()=>{void 0===o||x.current!==o&&(x.current=o,m("agent"))},[o,m]);let v=(0,$.useRef)(l);CN(()=>{void 0===l||v.current!==l&&(v.current=l,m("diff"))},[l,m]);let y=(0,$.useRef)(c?.nonce);CN(()=>{null==c||y.current!==c.nonce&&(y.current=c.nonce,m("terminal"))},[c,m]);let[b,w]=(0,$.useState)(0),_=(0,$.useCallback)(()=>w(e=>e+1),[]),S=(0,$.useRef)(null),j=(0,$.useRef)(!1),[k,C]=(0,$.useState)(0),N=(0,$.useCallback)(()=>{j.current=!0,C(e=>e+1)},[]);CN(()=>{!j.current||(j.current=!1,h&&null!==e&&"executors"===g&&S.current?.focus({preventScroll:!0}))},[h,g,k,e]);let{region:E,setRegion:D}=dD(),R="right-panel"===E;(0,$.useEffect)(()=>{if(!h)return;let e=e=>{let r=fS(e);r&&(e.preventDefault(),m(r),D("right-panel"),"agent"===r&&_(),"executors"===r&&N())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[h,m,D,_,N]);let T=(0,$.useSyncExternalStore)(CC,fb,()=>!1),A=n&&!n.path?"remote":void 0,I=function({projectId:e,branch:r,target:s,enabled:n=!0}){let[i,a]=(0,$.useState)(null),o=(0,$.useRef)(0),l=(0,$.useRef)(0),c=(0,$.useRef)(null);return(0,$.useEffect)(()=>{if(a(null),!n||!e)return;let i=++o.current;return Cw(()=>ry.api.listProjectFiles(e,r,s),{cancelled:()=>i!==o.current}).then(e=>{i===o.current&&a(e?Cy(e.files,e.root):Cy([]))}),()=>{null!==c.current&&(clearTimeout(c.current),c.current=null)}},[e,r,s,n]),(0,sx.useGlobalEventStream)(i=>{if(!n||!e)return;let d="session:taskCompleted"===i.type||"session:finished"===i.type,u="files:changed"===i.type;if(!d&&!u||i.projectId!==e||(i.branch??null)!==(r??null))return;null!==c.current&&clearTimeout(c.current);let h=o.current;c.current=setTimeout(()=>{c.current=null;let n=++l.current;ry.api.listProjectFiles(e,r,s).then(e=>{h===o.current&&n===l.current&&a(Cy(e.files,e.root))}).catch(()=>{})},250)}),i}({projectId:e,branch:r,target:A,enabled:h}),M=(0,$.useRef)(0),[F,P]=(0,$.useState)(null),L=(0,$.useCallback)((e,r=null)=>{m("files"),P({path:e,line:r,nonce:++M.current})},[m]),O=(0,$.useMemo)(()=>e?{projectId:e,branch:r??null,target:A,sessionId:f}:null,[e,r,A,f]),B=(0,$.useMemo)(()=>({openFile:L,index:I,scope:O}),[L,I,O]),W=(0,$.useMemo)(()=>({active:h&&null!==e&&"agent"===g,requestNonce:b}),[h,e,g,b]);return(0,z.jsx)(Cg,{value:B,children:(0,z.jsxs)("div",{"data-focus-region":"right-panel",className:"h-full flex flex-col",children:[(0,z.jsx)("div",{className:"flex items-center px-3 gap-4 border-b border-border",children:Ck.map(({id:e,icon:r,label:s,code:n})=>(0,z.jsxs)($.Fragment,{children:[(0,z.jsxs)("button",{onClick:()=>{m(e),"agent"===e&&_(),"executors"===e&&N()},title:`${s} (${fj(T,n)})`,className:(0,eb.cn)("flex items-center gap-0.5 py-2.5 text-xs font-medium border-b-2 transition-colors",g===e?(0,eb.cn)("text-foreground",R?"border-primary":"border-foreground/25"):"text-muted-foreground border-transparent hover:text-foreground/70"),children:[(0,z.jsx)(r,{className:"h-3.5 w-3.5"}),s]}),"agent"===e&&(0,z.jsx)("span",{className:"h-4 w-px bg-border/60 mx-1.5","aria-hidden":!0})]},e))}),(0,z.jsxs)("div",{className:"relative flex-1 overflow-hidden",children:[(0,z.jsx)("div",{className:(0,eb.cn)("absolute inset-0 overflow-hidden","agent"!==g&&"invisible pointer-events-none"),children:(0,z.jsx)(CS,{value:W,children:a})}),(0,z.jsx)("div",{ref:S,tabIndex:-1,className:(0,eb.cn)("absolute inset-0 overflow-hidden outline-hidden","executors"!==g&&"hidden"),children:(0,z.jsx)(j$,{projectId:e,selectedBranch:r,project:n,onExecutorModeChange:i,locateActive:h&&"executors"===g})}),(0,z.jsx)("div",{className:(0,eb.cn)("absolute inset-0 overflow-hidden","diff"!==g&&"hidden"),children:(0,z.jsx)(jZ,{projectId:e,selectedBranch:r,onMergeRequest:s,project:n,mergeTarget:d,compareRequestNonce:l})}),(0,z.jsx)("div",{className:(0,eb.cn)("absolute inset-0 overflow-hidden","terminal"!==g&&"hidden"),children:(0,z.jsx)(j1,{projectId:e,selectedBranch:r,project:n,active:h&&"terminal"===g,createRequest:c})}),(0,z.jsx)("div",{className:(0,eb.cn)("absolute inset-0 overflow-hidden","preview"!==g&&"hidden"),children:(0,z.jsx)(j8,{projectId:e,selectedBranch:r,project:n})}),(0,z.jsx)("div",{className:(0,eb.cn)("absolute inset-0 overflow-hidden","files"!==g&&"hidden"),children:(0,z.jsx)(Ch,{projectId:e,project:n,selectedBranch:r,navRequest:F,sessionId:f,active:"files"===g})})]})]})})}var CD=Symbol.for("immer-nothing"),CR=Symbol.for("immer-draftable"),CT=Symbol.for("immer-state");function CA(e){throw Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var CI=Object.getPrototypeOf;function CM(e){return!!e&&!!e[CT]}function CF(e){return!!e&&(CO(e)||Array.isArray(e)||!!e[CR]||!!e.constructor?.[CR]||CH(e)||CU(e))}var CP=Object.prototype.constructor.toString(),CL=new WeakMap;function CO(e){if(!e||"object"!=typeof e)return!1;let r=Object.getPrototypeOf(e);if(null===r||r===Object.prototype)return!0;let s=Object.hasOwnProperty.call(r,"constructor")&&r.constructor;if(s===Object)return!0;if("function"!=typeof s)return!1;let n=CL.get(s);return void 0===n&&(n=Function.toString.call(s),CL.set(s,n)),n===CP}function CB(e,r,s=!0){0===Cz(e)?(s?Reflect.ownKeys(e):Object.keys(e)).forEach(s=>{r(s,e[s],e)}):e.forEach((s,n)=>r(n,s,e))}function Cz(e){let r=e[CT];return r?r.type_:Array.isArray(e)?1:CH(e)?2:3*!!CU(e)}function C$(e,r){return 2===Cz(e)?e.has(r):Object.prototype.hasOwnProperty.call(e,r)}function CW(e,r,s){let n=Cz(e);2===n?e.set(r,s):3===n?e.add(s):e[r]=s}function CH(e){return e instanceof Map}function CU(e){return e instanceof Set}function Cq(e){return e.copy_||e.base_}function CK(e,r){if(CH(e))return new Map(e);if(CU(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let s=CO(e);if(!0!==r&&("class_only"!==r||s)){let r=CI(e);return null!==r&&s?{...e}:Object.assign(Object.create(r),e)}{let r=Object.getOwnPropertyDescriptors(e);delete r[CT];let s=Reflect.ownKeys(r);for(let n=0;n<s.length;n++){let i=s[n],a=r[i];!1===a.writable&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[i]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[i]})}return Object.create(CI(e),r)}}function CV(e,r=!1){return CY(e)||CM(e)||!CF(e)||(Cz(e)>1&&Object.defineProperties(e,{set:CX,add:CX,clear:CX,delete:CX}),Object.freeze(e),r&&Object.values(e).forEach(e=>CV(e,!0))),e}var CX={value:function(){CA(2)}};function CY(e){return null===e||"object"!=typeof e||Object.isFrozen(e)}var CG={};function CJ(e){let r=CG[e];return r||CA(0,e),r}function CZ(e,r){r&&(CJ("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=r)}function CQ(e){C0(e),e.drafts_.forEach(C2),e.drafts_=null}function C0(e){e===O&&(O=e.parent_)}function C1(e){return O={drafts_:[],parent_:O,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function C2(e){let r=e[CT];0===r.type_||1===r.type_?r.revoke_():r.revoked_=!0}function C5(e,r){r.unfinalizedDrafts_=r.drafts_.length;let s=r.drafts_[0];return void 0!==e&&e!==s?(s[CT].modified_&&(CQ(r),CA(4)),CF(e)&&(e=C3(r,e),r.parent_||C6(r,e)),r.patches_&&CJ("Patches").generateReplacementPatches_(s[CT].base_,e,r.patches_,r.inversePatches_)):e=C3(r,s,[]),CQ(r),r.patches_&&r.patchListener_(r.patches_,r.inversePatches_),e!==CD?e:void 0}function C3(e,r,s){if(CY(r))return r;let n=e.immer_.shouldUseStrictIteration(),i=r[CT];if(!i)return CB(r,(n,a)=>C4(e,i,r,n,a,s),n),r;if(i.scope_!==e)return r;if(!i.modified_)return C6(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;let r=i.copy_,a=r,o=!1;3===i.type_&&(a=new Set(r),r.clear(),o=!0),CB(a,(n,a)=>C4(e,i,r,n,a,s,o),n),C6(e,r,!1),s&&e.patches_&&CJ("Patches").generatePatches_(i,s,e.patches_,e.inversePatches_)}return i.copy_}function C4(e,r,s,n,i,a,o){if(null==i||"object"!=typeof i&&!o)return;let l=CY(i);if(!l||o){if(CM(i)){let o=C3(e,i,a&&r&&3!==r.type_&&!C$(r.assigned_,n)?a.concat(n):void 0);if(CW(s,n,o),!CM(o))return;e.canAutoFreeze_=!1}else o&&s.add(i);if(CF(i)&&!l){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||r&&r.base_&&r.base_[n]===i&&l)return;C3(e,i),(!r||!r.scope_.parent_)&&"symbol"!=typeof n&&(CH(s)?s.has(n):Object.prototype.propertyIsEnumerable.call(s,n))&&C6(e,i)}}}function C6(e,r,s=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&CV(r,s)}var C7={get(e,r){if(r===CT)return e;let s=Cq(e);if(!C$(s,r)){var n;let i;return n=e,(i=Ne(s,r))?"value"in i?i.value:i.get?.call(n.draft_):void 0}let i=s[r];return e.finalized_||!CF(i)?i:i===C9(e.base_,r)?(Nr(e),e.copy_[r]=Ns(i,e)):i},has:(e,r)=>r in Cq(e),ownKeys:e=>Reflect.ownKeys(Cq(e)),set(e,r,s){let n=Ne(Cq(e),r);if(n?.set)return n.set.call(e.draft_,s),!0;if(!e.modified_){let n=C9(Cq(e),r),i=n?.[CT];if(i&&i.base_===s)return e.copy_[r]=s,e.assigned_[r]=!1,!0;if((s===n?0!==s||1/s==1/n:s!=s&&n!=n)&&(void 0!==s||C$(e.base_,r)))return!0;Nr(e),Nt(e)}return!!(e.copy_[r]===s&&(void 0!==s||r in e.copy_)||Number.isNaN(s)&&Number.isNaN(e.copy_[r]))||(e.copy_[r]=s,e.assigned_[r]=!0,!0)},deleteProperty:(e,r)=>(void 0!==C9(e.base_,r)||r in e.base_?(e.assigned_[r]=!1,Nr(e),Nt(e)):delete e.assigned_[r],e.copy_&&delete e.copy_[r],!0),getOwnPropertyDescriptor(e,r){let s=Cq(e),n=Reflect.getOwnPropertyDescriptor(s,r);return n?{writable:!0,configurable:1!==e.type_||"length"!==r,enumerable:n.enumerable,value:s[r]}:n},defineProperty(){CA(11)},getPrototypeOf:e=>CI(e.base_),setPrototypeOf(){CA(12)}},C8={};function C9(e,r){let s=e[CT];return(s?Cq(s):e)[r]}function Ne(e,r){if(!(r in e))return;let s=CI(e);for(;s;){let e=Object.getOwnPropertyDescriptor(s,r);if(e)return e;s=CI(s)}}function Nt(e){!e.modified_&&(e.modified_=!0,e.parent_&&Nt(e.parent_))}function Nr(e){e.copy_||(e.copy_=CK(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function Ns(e,r){let s=CH(e)?CJ("MapSet").proxyMap_(e,r):CU(e)?CJ("MapSet").proxySet_(e,r):function(e,r){let s=Array.isArray(e),n={type_:+!!s,scope_:r?r.scope_:O,modified_:!1,finalized_:!1,assigned_:{},parent_:r,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},i=n,a=C7;s&&(i=[n],a=C8);let{revoke:o,proxy:l}=Proxy.revocable(i,a);return n.draft_=l,n.revoke_=o,l}(e,r);return(r?r.scope_:O).drafts_.push(s),s}CB(C7,(e,r)=>{C8[e]=function(){return arguments[0]=arguments[0][0],r.apply(this,arguments)}}),C8.deleteProperty=function(e,r){return C8.set.call(this,e,r,void 0)},C8.set=function(e,r,s){return C7.set.call(this,e[0],r,s,e[0])};var Nn=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(e,r,s)=>{let n;if("function"==typeof e&&"function"!=typeof r){let s=r;r=e;let n=this;return function(e=s,...i){return n.produce(e,e=>r.call(this,e,...i))}}if("function"!=typeof r&&CA(6),void 0!==s&&"function"!=typeof s&&CA(7),CF(e)){let i=C1(this),a=Ns(e,void 0),o=!0;try{n=r(a),o=!1}finally{o?CQ(i):C0(i)}return CZ(i,s),C5(n,i)}if(e&&"object"==typeof e)CA(1,e);else{if(void 0===(n=r(e))&&(n=e),n===CD&&(n=void 0),this.autoFreeze_&&CV(n,!0),s){let r=[],i=[];CJ("Patches").generateReplacementPatches_(e,n,r,i),s(r,i)}return n}},this.produceWithPatches=(e,r)=>{let s,n;return"function"==typeof e?(r,...s)=>this.produceWithPatches(r,r=>e(r,...s)):[this.produce(e,r,(e,r)=>{s=e,n=r}),s,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),"boolean"==typeof e?.useStrictIteration&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){var r;CF(e)||CA(8),CM(e)&&(CM(r=e)||CA(10,r),e=function e(r){let s;if(!CF(r)||CY(r))return r;let n=r[CT],i=!0;if(n){if(!n.modified_)return n.base_;n.finalized_=!0,s=CK(r,n.scope_.immer_.useStrictShallowCopy_),i=n.scope_.immer_.shouldUseStrictIteration()}else s=CK(r,!0);return CB(s,(r,n)=>{CW(s,r,e(n))},i),n&&(n.finalized_=!1),s}(r));let s=C1(this),n=Ns(e,void 0);return n[CT].isManual_=!0,C0(s),n}finishDraft(e,r){let s=e&&e[CT];s&&s.isManual_||CA(9);let{scope_:n}=s;return CZ(n,r),C5(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,r){let s;for(s=r.length-1;s>=0;s--){let n=r[s];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}s>-1&&(r=r.slice(s+1));let n=CJ("Patches").applyPatches_;return CM(e)?n(e,r):this.produce(e,e=>n(e,r))}}().produce;let Ni="vibedeckx:pending-submissions";function Na(){try{let e=window.sessionStorage.getItem(Ni);if(!e)return new Map;let r=JSON.parse(e);if(!Array.isArray(r))return new Map;let s=new Map;for(let e of r)e&&"object"==typeof e&&"string"==typeof e.workspaceKey&&"string"==typeof e.operationId&&s.set(e.workspaceKey,e);return s}catch{return new Map}}function No(e){try{0===e.size?window.sessionStorage.removeItem(Ni):window.sessionStorage.setItem(Ni,JSON.stringify([...e.values()]))}catch{}}function Nl(e){return Na().get(e)??null}function Nc(e){let r=Na(),s=r.get(e.workspaceKey)??null;return r.set(e.workspaceKey,e),No(r),s&&s.operationId!==e.operationId?s:null}function Nd(e,r){let s=Na(),n=s.get(e);return!!n&&n.operationId===r&&(s.delete(e),No(s),!0)}let Nu="vibedeckx:placeholder-workspaces";function Nh(e){try{window.localStorage.setItem(Nu,JSON.stringify([...e]))}catch{}}let Nf=function(){try{let e=window.localStorage.getItem(Nu);if(!e)return new Map;let r=JSON.parse(e);if(!Array.isArray(r))return new Map;let s=new Map;for(let e of r)if(Array.isArray(e)&&"string"==typeof e[0]&&"number"==typeof e[1]){let r=e[0].endsWith(":")?`${e[0]}local`:e[0];s.set(r,e[1])}else if("string"==typeof e){let r=e.endsWith(":")?`${e}local`:e;s.set(r,Date.now())}return s}catch{return new Map}}(),Np=new Set,Nm=new Map;function Ng(){for(let e of Np)e()}function Nx(e){return Np.add(e),()=>{Np.delete(e)}}function Nv(){return Nf}function Ny(){return Nm}function Nb(e,r,s){return`${e}:${r??""}:${s||"local"}`}function Nw(e){return Nf.has(e)}function N_(e){let r=new Map(Nf);r.set(e,Date.now()),Nh(Nf=r),Ng()}function NS(e){if(!Nf.has(e))return!1;let r=new Map(Nf);return r.delete(e),Nh(Nf=r),Ng(),!0}function Nj(e,r,s,n){return e?{projectId:e,branch:r,agentMode:s||"local",explicitSessionId:n??null}:null}function Nk(e,r){return e.projectId===r.projectId&&e.branch===r.branch&&e.agentMode===r.agentMode&&e.explicitSessionId===r.explicitSessionId}function NC(){return"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}async function NN(e,r,s,n){let i=await (0,ry.authFetch)(`${NC()}/api/projects/${e}/agent-sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:r,permissionMode:s,agentType:n,historyTurns:5})});if(!i.ok)throw Error("Failed to load session");return i.json()}async function NE(e,r,s){let n=await (0,ry.authFetch)(`${NC()}/api/agent-sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r,...s?{grantedRemoteIds:s}:{}})});if(!n.ok){let r="";try{let e=await n.json();if(e.errorCode){let s=[`${e.errorCode}`];e.attempts&&s.push(`${e.attempts} attempts`),e.totalDurationMs&&s.push(`${(e.totalDurationMs/1e3).toFixed(1)}s`),r=` (${s.join(", ")})`}else e.error&&(r=` — ${e.error}`)}catch{}throw console.error(`[AgentSession] /message failed: status=${n.status}, sessionId=${e}, detail=${r}`),Error(`Failed to send message [${n.status}]${r}`)}}async function ND(e){let r=await (0,ry.authFetch)(`${NC()}/api/agent-sessions/${e}/discard-if-empty`,{method:"POST"});if(r.ok)return!0;if(404===r.status||409===r.status)return!1;throw Error(`Failed to discard empty session [${r.status}]`)}async function NR(e,r){let s=await (0,ry.authFetch)(`${NC()}/api/agent-sessions/${e}/paste`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r})});if(!s.ok){let r="";try{let e=await s.json();if(e.errorCode){let s=[`${e.errorCode}`];e.attempts&&s.push(`${e.attempts} attempts`),e.totalDurationMs&&s.push(`${(e.totalDurationMs/1e3).toFixed(1)}s`),r=` (${s.join(", ")})`}else e.error&&(r=` — ${e.error}`)}catch{}throw console.error(`[AgentSession] /paste failed: status=${s.status}, sessionId=${e}, detail=${r}`),Error(`Failed to upload paste [${s.status}]${r}`)}return s.json()}async function NT(e,r,s){let n=`${NC()}/api/agent-sessions/${e}/attachment`,i=JSON.stringify(r),a=e=>new Promise((a,o)=>{let l=new XMLHttpRequest;l.open("POST",n),l.setRequestHeader("Content-Type","application/json"),e&&l.setRequestHeader("Authorization",`Bearer ${e}`),l.upload.onprogress=e=>{e.lengthComputable&&e.total>0&&s?.(Math.min(1,e.loaded/e.total))},l.onload=()=>a({status:l.status,text:l.responseText}),l.onerror=()=>o(Error(`Failed to upload ${r.name}`)),l.onabort=()=>o(Error(`Upload of ${r.name} was cancelled`)),l.send(i)}),o=await a(await (0,ry.getFreshToken)());if(401===o.status&&(o=await a(await (0,ry.getFreshToken)({skipCache:!0}))),o.status<200||o.status>=300){let s=`Failed to upload ${r.name} [${o.status}]`;try{let e=JSON.parse(o.text);"string"==typeof e?.error&&e.error&&(s=e.error)}catch{}throw console.error(`[AgentSession] /attachment failed: status=${o.status}, sessionId=${e}, name=${r.name}`),Error(s)}return s?.(1),JSON.parse(o.text)}async function NA(e,r){if(!(await (0,ry.authFetch)(`${NC()}/api/agent-sessions/${e}/restart`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentType:r})})).ok)throw Error("Failed to restart session")}async function NI(e,r){let s=await (0,ry.authFetch)(`${NC()}/api/agent-sessions/${e}/agent-type`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentType:r})});if(!s.ok){let e="";try{let r=await s.json();r.error&&(e=r.error)}catch{}throw Error(e||`Failed to switch agent [${s.status}]`)}}async function NM(e,r){let s=await (0,ry.authFetch)(`${NC()}/api/agent-sessions/${e}/model`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r})});if(!s.ok){let e="";try{let r=await s.json();r.error&&(e=r.error)}catch{}throw Error(e||`Failed to set model [${s.status}]`)}return(await s.json().catch(()=>({}))).model??null}async function NF(e){if(!(await (0,ry.authFetch)(`${NC()}/api/agent-sessions/${e}/stop`,{method:"POST"})).ok)throw Error("Failed to stop session")}async function NP(e,r){if(!(await (0,ry.authFetch)(`${NC()}/api/agent-sessions/${e}/switch-mode`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:r})})).ok)throw Error("Failed to switch mode")}async function NL(e,r){if(!(await (0,ry.authFetch)(`${NC()}/api/agent-sessions/${e}/accept-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planContent:r})})).ok)throw Error("Failed to accept plan")}let NO=new Map,NB=new Map;function Nz(e,r,s){return`${e}:${r??""}:${s??"latest"}`}function N$(e){let r=NO.get(e);if(r){NO.delete(e),NO.set(e,r);if(void 0===r.session.processAlive)return r;let s={...r.session};return delete s.processAlive,{session:s,history:r.history.session?{...r.history,session:s}:r.history}}}function NW(e,r){for(NO.delete(e),NO.set(e,r);NO.size>16;){let e=NO.keys().next().value;if(void 0===e)break;NO.delete(e)}}function NH(e,r,s,n,i){let a={session:n,history:{...i,entries:[...i.entries]}};NW(Nz(e,r,s),a),NW(Nz(e,r,n.id),a)}function NU(e,r,s,n){let i=Nz(e,r,s);NO.get(i)?.session.id===n&&NO.delete(i),NO.delete(Nz(e,r,n))}function Nq(e,r,s,n){let i=N$(Nz(e,r,n.id))??N$(Nz(e,r,s));i&&NH(e,r,s,n,i.history)}async function NK(e,r){let s=new URLSearchParams({turns:String(5)});null!=r&&s.set("before",String(r));let n=await (0,ry.authFetch)(`${NC()}/api/agent-sessions/${e}/history-window?${s}`);if(!n.ok)throw Error(`Session ${e} not found`);let i=await n.json();if(Array.isArray(i.entries))return i;let a=i.messages??[];return{historyEpoch:0,latestEntryIndex:a.length>0?a.length-1:null,lastTurnEndEntryIndex:a.reduce((e,r,s)=>"turn_end"===r.type?s:e,null),entries:a.map((e,r)=>({entryIndex:r,message:e})),previousCursor:null,hasMore:!1,status:i.session?.status??"stopped",session:i.session}}function NV(e){let r=NB.get(e);if(r)return r;let s=NK(e).finally(()=>NB.delete(e));return NB.set(e,s),s}async function NX(e){let r=await (0,ry.authFetch)(`${NC()}/api/agent-sessions/${e}/history-head`);if(!r.ok)throw Error(`Session ${e} not found`);let s=await r.json();if("number"==typeof s.historyEpoch)return s;let n=s.messages??[];return{historyEpoch:0,latestEntryIndex:n.length>0?n.length-1:null,lastTurnEndEntryIndex:n.reduce((e,r,s)=>"turn_end"===r.type?s:e,null),status:s.session?.status??"stopped"}}function NY(e){return Object.fromEntries(e.map(({entryIndex:e,message:r})=>[e,r]))}function NG(e){return Object.entries(e.entries).map(([e,r])=>({entryIndex:Number(e),message:r})).sort((e,r)=>e.entryIndex-r.entryIndex)}function NJ(e){return{historyEpoch:0,latestEntryIndex:null,lastTurnEndEntryIndex:null,entries:[],previousCursor:null,hasMore:!1,status:e.status,session:e}}let NZ=(0,e_.default)("user",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]),NQ=(0,e_.default)("wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]]),N0=(0,e_.default)("brain",[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]]),N1=(0,e_.default)("file-check",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m9 15 2 2 4-4",key:"1grp1n"}]]),N2=(0,e_.default)("folder-search",[["path",{d:"M10.7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]]),N5=(0,e_.default)("workflow",[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]]),N3=(0,e_.default)("file-pen-line",[["path",{d:"m18.226 5.226-2.52-2.52A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-.351",key:"1k2beg"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}],["path",{d:"M8 18h1",key:"13wk12"}]]),N4=(0,e_.default)("file-plus-corner",[["path",{d:"M11.35 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v5.35",key:"17jvcc"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M14 19h6",key:"bvotb8"}],["path",{d:"M17 16v6",key:"18yu1i"}]]),N6=(0,e_.default)("earth",[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),N7=(0,e_.default)("shield-alert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);var ck=cj,kT=cj;let N8=RegExp("(?<![\\w./-])((?:~?\\/)?[\\w-]+(?:[./][\\w-]+)+)(?::(\\d+)(?::\\d+)?|#L(\\d+)(?:-L?\\d+)?)?","g"),N9=/\[([^\]\n]*)\]\(\s*([^)\s]+?)\s*\)/g;function Ee(e){return e.includes("/")||/\.[A-Za-z0-9]+$/.test(e)}function Et(e){let r=e.trim();if(!r)return null;let s=/^(.*?)(?::(\d+)(?::\d+)?|#L(\d+)(?:-L?\d+)?)?$/.exec(r);if(!s||!s[1])return null;let n=s[1];return/^[a-z][a-z0-9+.-]*:/i.test(n)||n.startsWith("//")||n.startsWith("#")?null:{rawPath:n,line:s[2]?Number(s[2]):s[3]?Number(s[3]):null}}var Er="HoverCard",[Es,En]=q(Er,[ax]),Ei=ax(),[Ea,Eo]=Es(Er),El=e=>{let{__scopeHoverCard:r,children:s,open:n,defaultOpen:i,onOpenChange:a,openDelay:o=700,closeDelay:l=300}=e,c=Ei(r),d=$.useRef(0),u=$.useRef(0),h=$.useRef(!1),f=$.useRef(!1),[p,m]=Y({prop:n,defaultProp:i??!1,onChange:a,caller:Er}),g=$.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>m(!0),o)},[o,m]),x=$.useCallback(()=>{clearTimeout(d.current),h.current||f.current||(u.current=window.setTimeout(()=>m(!1),l))},[l,m]),v=$.useCallback(()=>m(!1),[m]);return $.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),(0,z.jsx)(Ea,{scope:r,open:p,onOpenChange:m,onOpen:g,onClose:x,onDismiss:v,hasSelectionRef:h,isPointerDownOnContentRef:f,children:(0,z.jsx)(ab,{...c,children:s})})};El.displayName=Er;var Ec="HoverCardTrigger",Ed=$.forwardRef((e,r)=>{let{__scopeHoverCard:s,...n}=e,i=Eo(Ec,s),a=Ei(s);return(0,z.jsx)(a_,{asChild:!0,...a,children:(0,z.jsx)(er.a,{"data-state":i.open?"open":"closed",...n,ref:r,onPointerEnter:K(e.onPointerEnter,Ev(i.onOpen)),onPointerLeave:K(e.onPointerLeave,Ev(i.onClose)),onFocus:K(e.onFocus,i.onOpen),onBlur:K(e.onBlur,i.onClose),onTouchStart:K(e.onTouchStart,e=>e.preventDefault())})})});Ed.displayName=Ec;var Eu="HoverCardPortal",[Eh,Ef]=Es(Eu,{forceMount:void 0}),Ep=e=>{let{__scopeHoverCard:r,forceMount:s,children:n,container:i}=e,a=Eo(Eu,r);return(0,z.jsx)(Eh,{scope:r,forceMount:s,children:(0,z.jsx)(Z,{present:s||a.open,children:(0,z.jsx)(eW,{asChild:!0,container:i,children:n})})})};Ep.displayName=Eu;var Em="HoverCardContent",Eg=$.forwardRef((e,r)=>{let s=Ef(Em,e.__scopeHoverCard),{forceMount:n=s.forceMount,...i}=e,a=Eo(Em,e.__scopeHoverCard);return(0,z.jsx)(Z,{present:n||a.open,children:(0,z.jsx)(Ex,{"data-state":a.open?"open":"closed",...i,onPointerEnter:K(e.onPointerEnter,Ev(a.onOpen)),onPointerLeave:K(e.onPointerLeave,Ev(a.onClose)),ref:r})})});Eg.displayName=Em;var Ex=$.forwardRef((e,r)=>{let{__scopeHoverCard:s,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:a,onInteractOutside:o,...l}=e,c=Eo(Em,s),d=Ei(s),u=$.useRef(null),h=(0,U.useComposedRefs)(r,u),[f,p]=$.useState(!1);return $.useEffect(()=>{if(f){let e=document.body;return B=e.style.userSelect||e.style.webkitUserSelect,e.style.userSelect="none",e.style.webkitUserSelect="none",()=>{e.style.userSelect=B,e.style.webkitUserSelect=B}}},[f]),$.useEffect(()=>{if(u.current){let e=()=>{p(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{document.getSelection()?.toString()!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",e),()=>{document.removeEventListener("pointerup",e),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),$.useEffect(()=>{u.current&&(function(e){let r=[],s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();)r.push(s.currentNode);return r})(u.current).forEach(e=>e.setAttribute("tabindex","-1"))}),(0,z.jsx)(eR,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:o,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:K(a,e=>{e.preventDefault()}),onDismiss:c.onDismiss,children:(0,z.jsx)(aC,{...d,...l,onPointerDown:K(l.onPointerDown,e=>{e.currentTarget.contains(e.target)&&p(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:h,style:{...l.style,userSelect:f?"text":void 0,WebkitUserSelect:f?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})});function Ev(e){return r=>"touch"===r.pointerType?void 0:e()}function Ey({...e}){return(0,z.jsx)(El,{"data-slot":"hover-card",...e})}function Eb({...e}){return(0,z.jsx)(Ed,{"data-slot":"hover-card-trigger",...e})}function Ew({className:e,align:r="center",sideOffset:s=4,...n}){return(0,z.jsx)(Ep,{"data-slot":"hover-card-portal",children:(0,z.jsx)(Eg,{"data-slot":"hover-card-content",align:r,sideOffset:s,className:(0,eb.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...n})})}$.forwardRef((e,r)=>{let{__scopeHoverCard:s,...n}=e,i=Ei(s);return(0,z.jsx)(aD,{...i,...n,ref:r})}).displayName="HoverCardArrow";let E_="text-primary underline decoration-dotted underline-offset-2 cursor-pointer hover:decoration-solid",ES="wrap-anywhere font-medium text-primary underline decoration-primary/60 underline-offset-2 transition-colors hover:text-primary/80 hover:decoration-primary",Ej="text-primary/80 underline decoration-dotted underline-offset-2 cursor-pointer hover:decoration-solid",Ek=new Set(["png","jpg","jpeg","gif","webp","bmp","ico","avif","svg"]);function EC({paths:e,line:r,children:s}){let{openFile:n}=Cm();return(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)("a",{href:"#",className:E_,onClick:e=>e.preventDefault(),children:s})}),(0,z.jsxs)(o1,{align:"start",className:"max-w-md",children:[(0,z.jsxs)(o6,{children:[e.length," matching files"]}),e.map(e=>(0,z.jsx)(o2,{className:"font-mono text-xs",onSelect:()=>n(e,r),children:e},e))]})]})}function EN({scope:e,filePath:r}){let[s,n]=(0,$.useState)(null),[i,a]=(0,$.useState)(null),[o,l]=(0,$.useState)(null),{label:c}=gf(null!==o&&o!==kK(e.sessionId)?o:null);return((0,$.useEffect)(()=>{let s=null,i=!1;return ry.api.getFileBlob(e.projectId,r,e.branch,e.target,e.sessionId).then(({blob:e,serverId:r})=>{if(!i){if(e.size>0xa00000)return void a("Too large to preview — click to open");l(r),n(s=URL.createObjectURL(e))}}).catch(e=>{if(i)return;let r=e instanceof Error?e.message:"";a(/not found/i.test(r)?"File not found":"Couldn't load image")}),()=>{i=!0,s&&URL.revokeObjectURL(s)}},[e.projectId,e.branch,e.target,e.sessionId,r]),i)?(0,z.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1.5 text-xs text-muted-foreground",children:[(0,z.jsx)(kX,{className:"h-3.5 w-3.5"}),i]}):s?(0,z.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,z.jsx)("img",{src:s,alt:r,className:"block max-h-64 max-w-[22rem] rounded object-contain"}),c&&(0,z.jsxs)("p",{className:"px-0.5 text-xs text-muted-foreground",children:["on ",(0,z.jsx)("span",{className:"text-foreground",children:c})]})]}):(0,z.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1.5 text-xs text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-3.5 w-3.5 animate-spin"}),"Loading preview…"]})}let{harden:EE,...ED}=kT.e,ER=[...Object.values(ED),function(){function e(e,r,s){return{type:"element",tagName:"a",properties:{className:["file-ref"],href:"#file-ref",dataFileRaw:e,...null!=r?{dataFileLine:String(r)}:{}},children:s}}return r=>{!function r(s,n=!1){if(!s.children)return;let i=n||"pre"===s.tagName,a=[];for(let n of s.children)"text"===n.type?i?a.push(n):a.push(...function(r){let s=function(e){let r,s=[],n=[];for(N9.lastIndex=0;null!==(r=N9.exec(e));){let e=Et(r[2]);if(!e||!Ee(e.rawPath))continue;let i=r.index,a=r.index+r[0].length;s.push({start:i,end:a,rawPath:e.rawPath,line:e.line,display:r[1]||void 0}),n.push([i,a])}for(N8.lastIndex=0;null!==(r=N8.exec(e));){let e=r.index;if(n.some(([r,s])=>e>=r&&e<s))continue;let i=r[1];if(!Ee(i))continue;let a=r[2]?Number(r[2]):r[3]?Number(r[3]):null;s.push({start:e,end:e+r[0].length,rawPath:i,line:a})}return s.sort((e,r)=>e.start-r.start),s}(r);if(0===s.length)return[{type:"text",value:r}];let n=[],i=0;for(let a of s){a.start>i&&n.push({type:"text",value:r.slice(i,a.start)});let s=a.display??r.slice(a.start,a.end);n.push(e(a.rawPath,a.line,[{type:"text",value:s}])),i=a.end}return i<r.length&&n.push({type:"text",value:r.slice(i)}),n}(n.value??"")):"element"===n.type&&"pre"===n.tagName?(r(n,!0),a.push(n)):"element"!==n.type||"a"!==n.tagName||i?(r(n,i),a.push(n)):a.push(...function(r){let s=Et(String(r.properties?.href??""));return s?[e(s.rawPath,s.line,r.children??[])]:[r]}(n));s.children=a}(r)}},...EE?[EE]:[]],ET={a:function({node:e,children:r,href:s,className:n,...i}){let{openFile:a,index:o,scope:l}=Cm(),c=e?.properties?.dataFileRaw;if(!c)return"string"==typeof s&&s.startsWith("#")?(0,z.jsx)("a",{href:s,className:(0,eb.cn)(ES,n),...i,children:r}):(0,z.jsx)("a",{href:s,className:(0,eb.cn)(ES,n),target:"_blank",rel:"noreferrer noopener",...i,children:r});let d=e?.properties?.dataFileLine,u=null!=d?Number(d):null,h=o?o.resolve(c):[];if(0===h.length){let e=o&&l?function(e){let r,s;if(!(e.startsWith("/")||e.startsWith("~/")))return null;let n=(s=(r=e.slice(e.lastIndexOf("/")+1)).lastIndexOf("."))>0?r.slice(s+1).toLowerCase():"";return n?Ek.has(n)?"image":"file":null}(c):null;if(!e||!l)return(0,z.jsx)(z.Fragment,{children:r});let s=e=>{e.preventDefault(),a(c,u)};return"file"===e?(0,z.jsx)("a",{href:"#",className:Ej,onClick:s,children:r}):(0,z.jsxs)(Ey,{openDelay:300,closeDelay:100,children:[(0,z.jsx)(Eb,{asChild:!0,children:(0,z.jsx)("a",{href:"#",className:Ej,onClick:s,children:r})}),(0,z.jsx)(Ew,{side:"top",align:"start",className:"w-auto max-w-sm p-1.5",children:(0,z.jsx)(EN,{scope:l,filePath:c})})]})}return 1===h.length?(0,z.jsx)("a",{href:"#",className:E_,onClick:e=>{e.preventDefault(),a(h[0],u)},children:r}):(0,z.jsx)(EC,{paths:h,line:u,children:r})}},EA=(0,$.memo)(function({children:e,streaming:r=!1}){return(0,z.jsx)(ck.i,{className:"size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",mode:r?"streaming":"static",rehypePlugins:ER,components:ET,children:e})});function EI({input:e,messageIndex:r}){let{sendMessage:s,messages:n}=TS(),i=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&Array.isArray(r.questions)&&r.questions.length>0&&r.questions.every(e=>"string"==typeof e.question&&"string"==typeof e.header&&Array.isArray(e.options)))return r}catch{}return null}(e),a=n[r+1],o=a?.type==="user",l=o?a.content:"",c="string"==typeof l?l:l.filter(e=>"text"===e.type).map(e=>e.text).join("\n");if(!i){let r="string"==typeof e?e:JSON.stringify(e,null,2);return(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>500?r.substring(0,500)+"...":r})}return o?(0,z.jsx)(EM,{questions:i.questions,answeredText:c}):(0,z.jsx)(EF,{questions:i.questions,sendMessage:s})}function EM({questions:e,answeredText:r}){return(0,z.jsx)("div",{className:"space-y-3 mt-2",children:e.map((e,s)=>(0,z.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-3",children:[(0,z.jsx)("div",{className:"flex items-center gap-2 mb-1.5",children:(0,z.jsx)(so,{variant:"secondary",className:"text-[10px]",children:e.header})}),(0,z.jsx)("p",{className:"text-sm text-muted-foreground mb-2",children:e.question}),(0,z.jsxs)("div",{className:"flex items-center gap-2 text-sm text-green-600 dark:text-green-400",children:[(0,z.jsx)(sZ,{className:"h-4 w-4"}),(0,z.jsx)("span",{className:"font-medium",children:r})]})]},s))})}function EF({questions:e,sendMessage:r}){let[s,n]=(0,$.useState)(new Map),[i,a]=(0,$.useState)(new Map),[o,l]=(0,$.useState)(new Set),[c,d]=(0,$.useState)(!1);async function u(){let n=[];for(let r=0;r<e.length;r++)if(o.has(r)){let e=i.get(r)?.trim();e&&n.push(e)}else{let e=s.get(r);e&&e.size>0&&n.push(Array.from(e).join(", "))}if(n.length>0){d(!0);try{await r(n.join("\n"))}finally{d(!1)}}}let h=e.some((e,r)=>{if(o.has(r))return!!i.get(r)?.trim();let n=s.get(r);return n&&n.size>0});return(0,z.jsxs)("div",{className:"space-y-4 mt-2",children:[e.map((e,r)=>{let c=s.get(r)||new Set,d=i.get(r)||"",u=o.has(r);return(0,z.jsxs)("div",{className:"rounded-lg border bg-card p-3",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 mb-1.5",children:[(0,z.jsx)(dc,{className:"h-3.5 w-3.5 text-violet-500"}),(0,z.jsx)(so,{variant:"secondary",className:"text-[10px]",children:e.header})]}),(0,z.jsx)("p",{className:"text-sm font-medium mb-3",children:e.question}),(0,z.jsxs)("div",{className:"grid gap-2",children:[e.options.map(s=>{let i=c.has(s.label)&&!u;return(0,z.jsx)(W.Button,{variant:i?"default":"outline",className:(0,eb.cn)("h-auto py-2 px-3 justify-start text-left whitespace-normal",i&&"ring-2 ring-primary/50"),onClick:()=>{var i,a;return i=s.label,a=e.multiSelect,void(n(e=>{let s=new Map(e),n=new Set(s.get(r)||[]);return a?n.has(i)?n.delete(i):n.add(i):n.has(i)?n.clear():(n.clear(),n.add(i)),s.set(r,n),s}),l(e=>{let s=new Set(e);return s.delete(r),s}))},children:(0,z.jsxs)("div",{children:[(0,z.jsx)("span",{className:"font-medium text-sm",children:s.label}),s.description&&(0,z.jsx)("span",{className:"block text-xs text-muted-foreground mt-0.5",children:s.description})]})},s.label)}),(0,z.jsx)("div",{className:"flex items-center gap-2 mt-1",children:(0,z.jsx)(rl,{placeholder:"Other...",value:d,onChange:e=>{var s;return s=e.target.value,void(a(e=>new Map(e).set(r,s)),s&&(n(e=>{let s=new Map(e);return s.set(r,new Set),s}),l(e=>new Set(e).add(r))))},className:"text-sm"})})]})]},r)}),(0,z.jsxs)(W.Button,{onClick:u,disabled:!h||c,size:"sm",className:"active:scale-95 transition-transform",children:[c&&(0,z.jsx)(sC,{className:"h-3.5 w-3.5 animate-spin"}),c?"Submitting...":"Submit"]})]})}function EP(e){try{return JSON.parse(e)}catch{return null}}function EL({input:e,messageIndex:r}){let{messages:s,acceptPlan:n,permissionMode:i,agentType:a}=TS(),[o,l]=(0,$.useState)(!0),[c,d]=(0,$.useState)(!1),u=function(e,r,s){let n="string"==typeof e?EP(e):e;if(n&&"object"==typeof n&&"plan"in n){let e=n.plan;if(e)return e}if("claude-code"===s)for(let e=r.length-1;e>=0;e--){let s=r[e];if("tool_use"===s.type&&"Write"===s.tool){let e="string"==typeof s.input?EP(s.input):s.input;if(e&&"object"==typeof e&&e.file_path?.includes(".claude/plans/")&&e.content)return e.content}}return"Plan written to file"}(e,s,a),h=(0,$.useCallback)(async()=>{d(!0);try{await n(u)}catch{d(!1)}},[n,u]),f="edit"===i,p=!1,m="";for(let e=r+1;e<s.length;e++){let r=s[e];if(r?.type==="user"){p=!0;let e=r.content??"";m="string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n");break}}return(f&&!p&&(p=!0),f||p)?(0,z.jsxs)("div",{className:"space-y-2 mt-2",children:[f?(0,z.jsxs)(so,{variant:"default",className:"bg-green-600 hover:bg-green-700 text-white",children:[(0,z.jsx)(sZ,{className:"h-3 w-3 mr-1"}),"Plan Accepted"]}):(0,z.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,z.jsx)(sR,{className:"h-3.5 w-3.5"}),(0,z.jsxs)("span",{children:["Feedback sent: ",m.length>100?m.substring(0,100)+"...":m]})]}),(0,z.jsxs)("details",{open:!f,children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"View Plan"}),(0,z.jsx)("div",{className:"mt-2 rounded-lg border p-3 bg-muted/30",children:(0,z.jsx)("div",{className:"prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,z.jsx)(cE,{mode:"static",children:u})})})]})]}):(0,z.jsxs)("div",{className:"space-y-3 mt-2",children:[(0,z.jsxs)("div",{className:"rounded-lg border p-3 bg-card",children:[(0,z.jsxs)("button",{onClick:()=>l(!o),className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground mb-2 block",children:[o?"Collapse":"Expand"," Plan"]}),o&&(0,z.jsx)("div",{className:"prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words max-h-96 overflow-y-auto",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,z.jsx)(cE,{mode:"static",children:u})})]}),(0,z.jsxs)(W.Button,{onClick:h,disabled:c,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:[c?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):(0,z.jsx)(rf,{className:"h-3.5 w-3.5 mr-1.5"}),c?"Accepting Plan...":"Accept Plan & Start Editing"]})]})}function EO({requestId:e,command:r,cwd:s,messageIndex:n}){let{messages:i,sessionId:a}=TS(),[o,l]=(0,$.useState)(!1),[c,d]=(0,$.useState)(null),u=!1;for(let e=n+1;e<i.length;e++)if(i[e]?.type==="user"){u=!0;break}c&&(u=!0);let h=(0,$.useCallback)(async r=>{if(a){l(!0),d(r);try{await (0,ry.sendApprovalResponse)(a,e,r)}catch{d(null),l(!1)}}},[a,e]);return u?(0,z.jsxs)("div",{className:"space-y-2 mt-2",children:[(0,z.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-3",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,z.jsx)(gM,{className:"h-3.5 w-3.5 text-muted-foreground"}),(0,z.jsx)("span",{className:"text-xs text-muted-foreground",children:"Command"})]}),(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r||"(empty)"}),s&&(0,z.jsxs)("p",{className:"text-xs text-muted-foreground mt-1",children:["cwd: ",s]})]}),(0,z.jsxs)(so,{variant:"default",className:"decline"===c?"bg-red-600 hover:bg-red-700 text-white":"bg-green-600 hover:bg-green-700 text-white",children:[(0,z.jsx)(sZ,{className:"h-3 w-3 mr-1"}),"decline"===c?"Denied":"Allowed"]})]}):(0,z.jsxs)("div",{className:"space-y-2 mt-2",children:[(0,z.jsxs)("div",{className:"rounded-lg border bg-card p-3",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,z.jsx)(gM,{className:"h-3.5 w-3.5 text-muted-foreground"}),(0,z.jsx)("span",{className:"text-xs text-muted-foreground",children:"Command"})]}),(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r||"(empty)"}),s&&(0,z.jsxs)("p",{className:"text-xs text-muted-foreground mt-1",children:["cwd: ",s]})]}),(0,z.jsxs)("div",{className:"flex gap-2",children:[(0,z.jsxs)(W.Button,{onClick:()=>h("accept"),disabled:o,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:[o&&"accept"===c?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,z.jsx)(sZ,{className:"h-3.5 w-3.5 mr-1"}),"Allow"]}),(0,z.jsxs)(W.Button,{onClick:()=>h("decline"),disabled:o,variant:"destructive",size:"sm",children:[o&&"decline"===c?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,z.jsx)(s1,{className:"h-3.5 w-3.5 mr-1"}),"Deny"]})]})]})}function EB({requestId:e,changes:r,messageIndex:s}){let{messages:n,sessionId:i}=TS(),[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(null),d=!1;for(let e=s+1;e<n.length;e++)if(n[e]?.type==="user"){d=!0;break}l&&(d=!0);let u=(0,$.useCallback)(async r=>{if(i){o(!0),c(r);try{await (0,ry.sendApprovalResponse)(i,e,r)}catch{c(null),o(!1)}}},[i,e]),h=r??[],f=()=>(0,z.jsx)("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:0===h.length?(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:"No file changes"}):h.map((e,r)=>(0,z.jsxs)("div",{children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)(ku,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),(0,z.jsx)("code",{className:"text-xs break-all",children:e.path}),(0,z.jsx)(so,{variant:"secondary",className:`text-[10px] ${function(e){switch(e){case"added":case"add":return"bg-green-500/10 text-green-600";case"deleted":case"delete":return"bg-red-500/10 text-red-600";default:return"bg-blue-500/10 text-blue-600"}}(e.kind)}`,children:function(e){switch(e){case"added":case"add":return"added";case"deleted":case"delete":return"deleted";default:return"modified"}}(e.kind)})]}),e.diff&&(0,z.jsxs)("details",{className:"mt-1",children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"View diff"}),(0,z.jsx)("pre",{className:"mt-1 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.diff.split("\n").map((e,r)=>{let s="";return e.startsWith("+")?s="bg-green-500/10 text-green-700 dark:text-green-400":e.startsWith("-")&&(s="bg-red-500/10 text-red-700 dark:text-red-400"),(0,z.jsx)("div",{className:s,children:e},r)})})]})]},r))});return d?(0,z.jsxs)("div",{className:"space-y-2 mt-2",children:[f(),(0,z.jsxs)(so,{variant:"default",className:"decline"===l?"bg-red-600 hover:bg-red-700 text-white":"bg-green-600 hover:bg-green-700 text-white",children:[(0,z.jsx)(sZ,{className:"h-3 w-3 mr-1"}),"decline"===l?"Denied":"Allowed"]})]}):(0,z.jsxs)("div",{className:"space-y-2 mt-2",children:[f(),(0,z.jsxs)("div",{className:"flex gap-2",children:[(0,z.jsxs)(W.Button,{onClick:()=>u("accept"),disabled:a,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:[a&&"accept"===l?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,z.jsx)(sZ,{className:"h-3.5 w-3.5 mr-1"}),"Allow"]}),(0,z.jsxs)(W.Button,{onClick:()=>u("decline"),disabled:a,variant:"destructive",size:"sm",children:[a&&"decline"===l?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,z.jsx)(s1,{className:"h-3.5 w-3.5 mr-1"}),"Deny"]})]})]})}let Ez=(0,e_.default)("circle-plus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]),E$=(0,e_.default)("badge",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}]]);function EW({status:e,className:r}){switch(e){case"completed":return(0,z.jsx)(sZ,{className:(0,eb.cn)("h-4 w-4 text-green-500",r)});case"in_progress":return(0,z.jsx)(sC,{className:(0,eb.cn)("h-4 w-4 text-cyan-500 animate-spin",r)});case"pending":default:return(0,z.jsx)(sQ,{className:(0,eb.cn)("h-4 w-4 text-muted-foreground",r)});case"deleted":return(0,z.jsx)(s1,{className:(0,eb.cn)("h-4 w-4 text-red-400",r)})}}function EH(e,r){try{let s="string"==typeof e?JSON.parse(e):e;if(s&&"object"==typeof s&&r(s))return s}catch{}return null}function EU({input:e}){let r="string"==typeof e?e:JSON.stringify(e,null,2);return(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>500?r.substring(0,500)+"...":r})}function Eq({input:e}){let r=EH(e,e=>Array.isArray(e.todos)&&e.todos.length>0);return r?(0,z.jsx)("div",{className:"mt-2 space-y-1",children:r.todos.map((e,r)=>(0,z.jsxs)("div",{className:"flex items-start gap-2 py-0.5",children:[(0,z.jsx)(EW,{status:e.status,className:"mt-0.5 flex-shrink-0"}),(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)("span",{className:(0,eb.cn)("text-sm break-words","completed"===e.status&&"line-through text-muted-foreground"),children:e.subject??e.content??"Untitled task"}),"in_progress"===e.status&&e.activeForm&&(0,z.jsx)("span",{className:"block text-xs italic text-cyan-500",children:e.activeForm})]})]},e.id??r))}):(0,z.jsx)(EU,{input:e})}function EK({input:e}){let r=EH(e,e=>"string"==typeof e.subject);return r?(0,z.jsxs)("div",{className:"mt-2 flex items-start gap-2",children:[(0,z.jsx)(Ez,{className:"h-4 w-4 text-cyan-500 mt-0.5 flex-shrink-0"}),(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)("span",{className:"text-sm font-medium break-words",children:r.subject}),r.description&&(0,z.jsx)("span",{className:"block text-xs text-muted-foreground mt-0.5 break-words",children:r.description.length>200?r.description.substring(0,200)+"...":r.description})]})]}):(0,z.jsx)(EU,{input:e})}function EV({input:e}){let r=EH(e,e=>"string"==typeof e.taskId);return r?(0,z.jsxs)("div",{className:"mt-2 flex items-start gap-2 flex-wrap",children:[r.status?(0,z.jsx)(EW,{status:r.status,className:"mt-0.5 flex-shrink-0"}):(0,z.jsx)(kt,{className:"h-4 w-4 text-cyan-500 mt-0.5 flex-shrink-0"}),(0,z.jsxs)("span",{className:"text-sm break-words",children:["Task #",r.taskId,r.status&&(0,z.jsxs)(z.Fragment,{children:[" ",(0,z.jsx)(kt,{className:"inline h-3 w-3 text-muted-foreground mx-0.5"})," ",r.status]}),r.subject&&(0,z.jsxs)("span",{className:"text-muted-foreground",children:[" — ",r.subject]})]}),r.addBlockedBy&&r.addBlockedBy.length>0&&(0,z.jsx)("div",{className:"flex gap-1 mt-1 w-full pl-6",children:r.addBlockedBy.map(e=>(0,z.jsxs)(so,{variant:"outline",className:"text-[10px]",children:[(0,z.jsx)(E$,{className:"h-2.5 w-2.5 mr-0.5"}),"blocked by #",e]},e))}),r.addBlocks&&r.addBlocks.length>0&&(0,z.jsx)("div",{className:"flex gap-1 mt-1 w-full pl-6",children:r.addBlocks.map(e=>(0,z.jsxs)(so,{variant:"outline",className:"text-[10px]",children:[(0,z.jsx)(E$,{className:"h-2.5 w-2.5 mr-0.5"}),"blocks #",e]},e))})]}):(0,z.jsx)(EU,{input:e})}function EX(){return(0,z.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin text-cyan-500"}),(0,z.jsx)("span",{children:"Listing tasks..."})]})}function EY({input:e}){let r=EH(e,e=>"string"==typeof e.taskId);return r?(0,z.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin text-cyan-500"}),(0,z.jsxs)("span",{children:["Fetching task #",r.taskId,"..."]})]}):(0,z.jsx)(EU,{input:e})}function EG({output:e}){let r=function(e){try{let r=JSON.parse(e);if(Array.isArray(r))return r.filter(e=>e.id&&e.subject).map(e=>({id:String(e.id),subject:String(e.subject),status:e.status||"pending",owner:e.owner?String(e.owner):void 0,blockedBy:Array.isArray(e.blockedBy)?e.blockedBy.map(String):void 0}));let s=r.tasks??r.items??r.data;if(Array.isArray(s))return s.filter(e=>e.id&&e.subject).map(e=>({id:String(e.id),subject:String(e.subject),status:e.status||"pending",owner:e.owner?String(e.owner):void 0,blockedBy:Array.isArray(e.blockedBy)?e.blockedBy.map(String):void 0}))}catch{let r=e.trim().split("\n").filter(Boolean),s=[];for(let e of r){let r=e.match(/^#?(\d+)[\s.:\-]+\[?(completed|in_progress|pending|deleted)\]?\s+(.+)/i);r&&s.push({id:r[1],status:r[2].toLowerCase(),subject:r[3].trim()})}if(s.length>0)return s}return null}(e);return r?(0,z.jsx)("div",{className:"mt-1 space-y-1",children:r.map(e=>(0,z.jsxs)("div",{className:"flex items-start gap-2 py-0.5",children:[(0,z.jsx)(EW,{status:e.status,className:"mt-0.5 flex-shrink-0"}),(0,z.jsxs)("div",{className:"min-w-0 flex items-center gap-1.5 flex-wrap",children:[(0,z.jsxs)("span",{className:"text-xs text-muted-foreground",children:["#",e.id]}),(0,z.jsx)("span",{className:(0,eb.cn)("text-sm break-words","completed"===e.status&&"line-through text-muted-foreground"),children:e.subject}),e.blockedBy&&e.blockedBy.length>0&&(0,z.jsx)(so,{variant:"outline",className:"text-[10px]",children:"blocked"})]})]},e.id))}):null}function EJ({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.file_path)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{file_path:s,offset:n,limit:i}=r,a=s.split("/"),o=a.pop()||s,l=a.join("/"),c=null!=n||null!=i,d="";if(c){let e=n??1;d=null!=i?`Lines ${e}\u2013${e+i-1}`:`From line ${e}`}return(0,z.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)("span",{className:"text-sm font-medium break-all",children:o}),l&&(0,z.jsx)("p",{className:"text-xs text-muted-foreground truncate",title:s,children:l})]}),c&&(0,z.jsx)(so,{variant:"outline",className:"text-xs shrink-0",children:d})]})}function EZ({images:e}){return(0,z.jsx)("div",{className:"flex flex-wrap gap-2",children:e.map((e,r)=>(0,z.jsx)("img",{src:`data:${e.mediaType};base64,${e.data}`,alt:"Image viewed by the agent",className:"max-w-sm max-h-80 rounded-lg border border-border object-contain"},r))})}function EQ({output:e}){let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["File contents (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function E0({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.file_path)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{file_path:s,content:n}=r,i=s.split("/"),a=i.pop()||s,o=i.join("/"),l=n.split("\n").length;return(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)("span",{className:"text-sm font-medium break-all",children:a}),o&&(0,z.jsx)("p",{className:"text-xs text-muted-foreground truncate",title:s,children:o})]}),(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Content (",l," ",1===l?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:n.length>1e3?n.substring(0,1e3)+"...":n})]})]})}function E1({output:e}){return e&&""!==e.trim()?(0,z.jsxs)("details",{children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Result"}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]}):(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"File written"})}function E2({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.command)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{command:s,description:n,timeout:i}=r;return(0,z.jsxs)("div",{className:"space-y-1",children:[n&&(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:n}),(0,z.jsxs)("div",{className:"flex items-start gap-2",children:[(0,z.jsxs)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{className:"text-muted-foreground select-none",children:"$ "}),s]}),null!=i&&(0,z.jsx)(so,{variant:"outline",className:"text-xs shrink-0 mt-1",children:function(e){if(e>=6e4){let r=e/6e4;return`${r%1==0?r:r.toFixed(1)}m`}return`${e/1e3}s`}(i)})]})]})}function E5({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Output (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function E3({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.pattern)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let s=[];return r.path&&s.push({label:r.path}),r.glob&&s.push({label:r.glob}),r.type&&s.push({label:`.${r.type}`}),r.output_mode&&"files_with_matches"!==r.output_mode&&s.push({label:r.output_mode}),null!=r.context&&s.push({label:`context: ${r.context}`}),null!=r["-C"]&&s.push({label:`context: ${r["-C"]}`}),null!=r["-B"]&&s.push({label:`before: ${r["-B"]}`}),null!=r["-A"]&&s.push({label:`after: ${r["-A"]}`}),r["-i"]&&s.push({label:"case-insensitive"}),r.multiline&&s.push({label:"multiline"}),null!=r.head_limit&&s.push({label:`limit: ${r.head_limit}`}),null!=r.offset&&s.push({label:`offset: ${r.offset}`}),(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsx)("div",{className:"flex items-start gap-2",children:(0,z.jsxs)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{className:"text-muted-foreground select-none",children:"/ "}),r.pattern]})}),s.length>0&&(0,z.jsx)("div",{className:"flex items-center gap-1.5 flex-wrap",children:s.map((e,r)=>(0,z.jsx)(so,{variant:"outline",className:"text-xs",children:e.label},r))})]})}function E4({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No matches"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Results (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function E6({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.pattern)return r;return null}catch{return null}}(e);return r?(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsx)("div",{className:"flex items-start gap-2",children:(0,z.jsx)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.pattern})}),r.path&&(0,z.jsx)("div",{className:"flex items-center gap-1.5 flex-wrap",children:(0,z.jsx)(so,{variant:"outline",className:"text-xs",children:r.path})})]}):(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)})}function E7({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No matches"});let r=e.trim().split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:[r," ",1===r?"file":"files"," found"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}let E8={Explore:"Explore",Bash:"Bash",Plan:"Plan","general-purpose":"General","code-simplifier":"Simplify","superpowers:code-reviewer":"Review","memory-leak-detector":"Memory","directory-structure-validator":"Structure","tech-docs-finder":"Docs","claude-code-guide":"Guide","statusline-setup":"Status"};function E9({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.description&&"string"==typeof r.subagent_type)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{description:s,subagent_type:n,prompt:i,model:a,max_turns:o,resume:l,run_in_background:c}=r,d=[];return d.push({label:E8[n]||n}),a&&d.push({label:a}),null!=o&&d.push({label:`${o} turns`}),c&&d.push({label:"background"}),l&&d.push({label:"resume"}),(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,z.jsx)("span",{className:"text-sm",children:s}),d.map((e,r)=>(0,z.jsx)(so,{variant:"outline",className:"text-xs shrink-0",children:e.label},r))]}),i&&(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Prompt (",i.length>1e3?`${Math.round(i.length/1e3)}k chars`:`${i.length} chars`,")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:i.length>1e3?i.substring(0,1e3)+"...":i})]})]})}function De({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Agent result (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function Dt(e,r){return e.length>r?e.substring(0,r)+"...":e}function Dr({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.file_path&&"string"==typeof r.old_string&&"string"==typeof r.new_string)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{file_path:s,old_string:n,new_string:i,replace_all:a}=r,o=s.split("/"),l=o.pop()||s,c=o.join("/"),d=n.split("\n").length,u=i.split("\n").length;return(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)("span",{className:"text-sm font-medium break-all",children:l}),c&&(0,z.jsx)("p",{className:"text-xs text-muted-foreground truncate",title:s,children:c})]}),(0,z.jsx)(so,{variant:"outline",className:"text-xs shrink-0",children:d===u?`${d} ${1===d?"line":"lines"}`:`${d}\u2192${u} lines`}),a&&(0,z.jsx)(so,{variant:"outline",className:"text-xs shrink-0",children:"replace all"})]}),(0,z.jsxs)("details",{children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Diff"}),(0,z.jsxs)("div",{className:"mt-1 text-xs rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full",children:[(0,z.jsxs)("pre",{className:"bg-red-500/10 p-1.5 rounded-t whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{className:"text-red-500 select-none",children:"- "}),Dt(n,500)]}),(0,z.jsxs)("pre",{className:"bg-green-500/10 p-1.5 rounded-b whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{className:"text-green-500 select-none",children:"+ "}),Dt(i,500)]})]})]})]})}function Ds({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});if(e.length<=200)return(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:e});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Result (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function Dn({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.url&&"string"==typeof r.prompt)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{display:s,href:n}=function(e){try{let r=new URL(e),s="/"===r.pathname?"":r.pathname,n=r.hostname+s;return{display:n.length>80?n.substring(0,77)+"...":n,href:e}}catch{return{display:e.length>80?e.substring(0,77)+"...":e,href:e}}}(r.url),i=r.prompt.length>150?r.prompt.substring(0,147)+"...":r.prompt;return(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsx)("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"block text-xs font-mono text-blue-500 hover:underline truncate",children:s}),(0,z.jsxs)("p",{className:"text-xs text-muted-foreground",children:['"',i,'"']})]})}function Di({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No content fetched"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Response (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function Da({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.query)return r;return null}catch{return null}}(e);return r?(0,z.jsxs)("div",{className:"space-y-1.5",children:[(0,z.jsx)("p",{className:"text-xs font-mono bg-muted/50 px-2 py-1 rounded break-words",children:r.query}),r.allowed_domains&&r.allowed_domains.length>0&&(0,z.jsxs)("div",{className:"flex items-center gap-1 flex-wrap",children:[(0,z.jsx)("span",{className:"text-xs text-muted-foreground",children:"only:"}),r.allowed_domains.map(e=>(0,z.jsx)(so,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:e},e))]}),r.blocked_domains&&r.blocked_domains.length>0&&(0,z.jsxs)("div",{className:"flex items-center gap-1 flex-wrap",children:[(0,z.jsx)("span",{className:"text-xs text-muted-foreground",children:"exclude:"}),r.blocked_domains.map(e=>(0,z.jsx)(so,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:e},e))]})]}):(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)})}function Do({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No search results"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Results (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function Dl({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.skill)return r;return null}catch{return null}}(e);return r?(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsx)("p",{className:"text-xs font-mono text-pink-500",children:r.skill}),r.args&&(0,z.jsxs)("p",{className:"text-xs text-muted-foreground truncate",children:["args: ",r.args]})]}):(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)})}function Dc({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Loaded (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function Dd({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.task_id)return r;return null}catch{return null}}(e);if(!r)return(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{task_id:s,block:n,timeout:i}=r,a=[];return a.push({label:!1===n?"non-blocking":"blocking"}),null!=i&&a.push({label:`${Math.round(i/1e3)}s`}),(0,z.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,z.jsx)("code",{className:"text-sm bg-muted/50 px-1.5 py-0.5 rounded",children:s}),a.map((e,r)=>(0,z.jsx)(so,{variant:"outline",className:"text-xs shrink-0",children:e.label},r))]})}function Du({output:e}){if(!e||""===e.trim())return(0,z.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,z.jsxs)("details",{children:[(0,z.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Task output (",r," ",1===r?"line":"lines",")"]}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function Dh({input:e}){let r="string"==typeof e?function(e){try{return JSON.parse(e)}catch{return null}}(e):e,s=r?.changes??[];return 0===s.length?(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:"No file changes"}):(0,z.jsx)("div",{className:"space-y-2 mt-1",children:s.map((e,r)=>(0,z.jsxs)("div",{children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)(ku,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),(0,z.jsx)("code",{className:"text-xs break-all",children:e.path}),(0,z.jsx)(so,{variant:"secondary",className:`text-[10px] ${function(e){switch(e){case"added":case"add":return"bg-green-500/10 text-green-600";case"deleted":case"delete":return"bg-red-500/10 text-red-600";default:return"bg-blue-500/10 text-blue-600"}}(e.kind)}`,children:function(e){switch(e){case"added":case"add":return"added";case"deleted":case"delete":return"deleted";default:return"modified"}}(e.kind)})]}),e.diff&&(0,z.jsxs)("details",{className:"mt-1",children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"View diff"}),(0,z.jsx)("pre",{className:"mt-1 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.diff.split("\n").map((e,r)=>{let s="";return e.startsWith("+")?s="bg-green-500/10 text-green-700 dark:text-green-400":e.startsWith("-")&&(s="bg-red-500/10 text-red-700 dark:text-red-400"),(0,z.jsx)("div",{className:s,children:e},r)})})]})]},r))})}function Df({output:e}){let r=e.toLowerCase(),s="text-muted-foreground";return r.includes("completed")||r.includes("success")?s="text-green-600 dark:text-green-400":r.includes("failed")||r.includes("error")?s="text-red-600 dark:text-red-400":(r.includes("declined")||r.includes("denied"))&&(s="text-amber-600 dark:text-amber-400"),(0,z.jsx)("p",{className:`text-xs ${s}`,children:e})}let Dp=new Map,Dm=new Map,Dg=new Map;function Dx(e){for(let r of Dg.get(e)??[])r()}async function Dv(e,r){if(!r){let r=Dp.get(e);if(r)return r;let s=Dm.get(e);if(s)return s}let s=ry.api.getSchedules(e).then(r=>(Dp.set(e,r),Dx(e),r)).finally(()=>{Dm.get(e)===s&&Dm.delete(e)});return Dm.set(e,s),s}let Dy="mcp__vibedeckx__propose_schedule";function Db({input:e,toolUseId:r}){let s,{sessionId:n,projectId:i,branch:a,target:o,targetLabel:l,agentType:c,openSchedule:d}=TS(),u=(0,$.useMemo)(()=>{let r,s,n,i,a,o;return s=(r="string"==typeof e?function(e){try{return JSON.parse(e)}catch{return null}}(e):e)&&"object"==typeof r?r:{},i=(n=e=>"string"==typeof e?e:"")(s.prompt),a=n(s.command),o=i.trim()||!a.trim()?"prompt":"command",{name:n(s.name).trim(),cronExpr:n(s.cron_expr).trim(),runType:o,content:"prompt"===o?i:a,timezone:n(s.timezone).trim()||function(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}}()}},[e]),[h,f]=(0,$.useState)(u),[p,m]=(0,$.useState)(a??""),[g,x]=(0,$.useState)(!1),[v,y]=(0,$.useState)(null),{schedule:b,loading:w}=(s=(0,$.useSyncExternalStore)((0,$.useCallback)(e=>{let r;return i?((r=Dg.get(i)??new Set).add(e),Dg.set(i,r),()=>{r.delete(e),0===r.size&&Dg.delete(i)}):()=>{}},[i]),(0,$.useCallback)(()=>i?Dp.get(i)??null:null,[i]),()=>null),(0,$.useEffect)(()=>{i&&Dv(i,!1).catch(e=>{console.error("Failed to load schedules for proposal lookup:",e)})},[i]),(0,sx.useGlobalEventStream)((0,$.useCallback)(e=>{!e.type?.startsWith("schedule:")||i&&e.projectId===i&&Dv(i,!0).catch(()=>{})},[i])),{schedule:r&&n&&s?s.find(e=>e.source_tool_use_id===r&&e.source_session_id===n)??null:null,loading:null===s}),_="command"===h.runType,S=!!i&&!!n&&!!r,j=async()=>{if(S&&!g){x(!0),y(null);try{let e,s=await ry.api.createSchedule(i,{name:h.name||"Scheduled check",cron_expr:h.cronExpr,timezone:h.timezone,target:o,run_type:h.runType,prompt_provider:"command"===h.runType?null:"codex"===c?"codex":"claude",content:h.content,cwd_mode:"branch",branch:p.trim()?p.trim():null,source:{session_id:n,tool_use_id:r}});e=Dp.get(i)??[],Dp.set(i,[...e.filter(e=>e.id!==s.id),s]),Dx(i)}catch(e){y(e instanceof Error?e.message:"Failed to create schedule")}finally{x(!1)}}};return b?(0,z.jsx)("div",{className:"rounded-lg border border-emerald-500/30 bg-emerald-500/5 p-3",children:(0,z.jsxs)("div",{className:"flex items-start gap-2",children:[(0,z.jsx)(sZ,{className:"mt-0.5 h-4 w-4 flex-shrink-0 text-emerald-500"}),(0,z.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-foreground break-words",children:b.name}),(0,z.jsxs)("p",{className:"mt-0.5 font-mono text-xs text-muted-foreground break-all",children:[b.cron_expr," · ",b.timezone,"command"===b.run_type?" · command":"",b.branch?` \xb7 ${b.branch}`:""]})]}),d&&(0,z.jsxs)(W.Button,{variant:"ghost",size:"sm",className:"flex-shrink-0",onClick:()=>d(b.id),children:[(0,z.jsx)(s8,{className:"mr-1 h-3.5 w-3.5"}),"View"]})]})}):(0,z.jsxs)("div",{className:"rounded-lg border border-border bg-muted/30 p-3",children:[(0,z.jsxs)("div",{className:"space-y-2",children:[(0,z.jsx)(rl,{value:h.name,onChange:e=>f(r=>({...r,name:e.target.value})),placeholder:"Name",className:"h-8 text-sm","aria-label":"Schedule name",disabled:g}),(0,z.jsxs)("div",{className:"flex gap-2",children:[(0,z.jsx)(rl,{value:h.cronExpr,onChange:e=>f(r=>({...r,cronExpr:e.target.value})),placeholder:"0 9 * * *",className:"h-8 font-mono text-xs","aria-label":"Cron expression",disabled:g}),(0,z.jsx)(rl,{value:p,onChange:e=>m(e.target.value),placeholder:"main worktree",className:"h-8 font-mono text-xs","aria-label":"Branch",disabled:g})]}),(0,z.jsx)(rc,{value:h.content,onChange:e=>f(r=>({...r,content:e.target.value})),placeholder:_?"Command to run":"What the scheduled agent should check",className:(0,eb.cn)("text-xs",_?"min-h-16 font-mono":"min-h-24"),"aria-label":_?"Check command":"Check prompt",disabled:g})]}),(0,z.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:[_?"Runs as a command":"Runs as an agent"," on ",l," · ",h.timezone]}),v&&(0,z.jsx)("p",{className:"mt-2 text-xs text-red-500 break-words",children:v}),(0,z.jsxs)("div",{className:"mt-3 flex items-center gap-2",children:[(0,z.jsxs)(W.Button,{size:"sm",onClick:j,disabled:!S||g||w,children:[g?(0,z.jsx)(sC,{className:"mr-1 h-3.5 w-3.5 animate-spin"}):(0,z.jsx)(sj,{className:"mr-1 h-3.5 w-3.5"}),v?"Retry":"Create schedule"]}),d&&(0,z.jsx)(W.Button,{variant:"ghost",size:"sm",onClick:()=>d(null),disabled:g,children:"View existing schedules"})]})]})}let Dw="cross-remote",D_={remote_bash:"Run Command",remote_read_file:"Read File",remote_list_dir:"List Directory",remote_stat_path:"Stat Path",remote_process_list:"List Processes",list_accessible_remotes:"List Remotes",remote_mcp_open:"Open MCP Server",remote_mcp_list_tools:"List MCP Tools",remote_mcp_call:"Call MCP Tool",remote_mcp_ping:"Ping MCP Server",remote_mcp_close:"Close MCP Server"},DS=[`mcp__${Dw}__`,`${Dw}__`,`${Dw}.`,`${Dw}/`];function Dj(e){let r=e.trim();for(let e of DS)if(r.startsWith(e)){let s=r.slice(e.length);return s in D_?s:null}return r in D_?r:null}function Dk({value:e,limit:r}){let s="string"==typeof e?e:JSON.stringify(e,null,2);return(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:s.length>r?s.substring(0,r)+"...":s})}function DC({bare:e,parsed:r,raw:s}){return r?"remote_bash"===e&&r.command?(0,z.jsxs)("div",{className:"flex items-start gap-2",children:[(0,z.jsxs)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{className:"text-muted-foreground select-none",children:"$ "}),r.command]}),(0,z.jsxs)("div",{className:"flex flex-col gap-1 shrink-0 mt-1",children:[r.cwd&&(0,z.jsx)(so,{variant:"outline",className:"text-xs max-w-40 truncate",title:r.cwd,children:r.cwd}),null!=r.timeoutSec&&(0,z.jsxs)(so,{variant:"outline",className:"text-xs",children:[r.timeoutSec,"s"]})]})]}):r.path?(0,z.jsx)("p",{className:"font-mono text-muted-foreground break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.path}):"remote_process_list"===e||"list_accessible_remotes"===e?null:(0,z.jsx)(Dk,{value:s,limit:500}):(0,z.jsx)(Dk,{value:s,limit:500})}function DN({tool:e,input:r}){let s=Dj(e)??e,n=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(!r||"object"!=typeof r)return null;let s=e=>"string"==typeof r[e]?r[e]:void 0;return{remoteId:s("remoteId"),command:s("command"),cwd:s("cwd"),path:s("path"),tool:s("tool"),timeoutSec:"number"==typeof r.timeoutSec?r.timeoutSec:void 0}}catch{return null}}(r),{label:i}=gf(n?.remoteId);return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-violet-500/10 flex items-center justify-center",children:(0,z.jsx)(sm,{className:"w-4 h-4 text-violet-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsxs)("p",{className:"text-sm font-medium text-violet-500 mb-1 break-words",children:[D_[s]??s,i&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"font-normal text-muted-foreground",children:" on "}),(0,z.jsx)("span",{className:"text-foreground",title:n?.remoteId,children:i})]})]}),(0,z.jsx)(DC,{bare:s,parsed:n,raw:r})]})]})}function DE(e){try{return{ok:!0,value:JSON.parse(e)}}catch{return{ok:!1}}}function DD({text:e}){return(0,z.jsx)("p",{className:"text-xs text-muted-foreground break-words whitespace-pre-wrap",children:e})}function DR({output:e}){var r;let s=DE(e);if(!s.ok)return(0,z.jsx)(DD,{text:e});let n=s.value,i=function(e){let r=e?.content;if(!Array.isArray(r))return null;let s=r.filter(e=>!!e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text);return s.length>0?s.join("\n"):null}(n);if(null!==i){let e=DE(i);if(!e.ok)return(0,z.jsx)(DD,{text:i});n=e.value}let a=(r=n)&&"object"==typeof r?"string"!=typeof r.stdout||"string"!=typeof r.stderr?null:{stdout:r.stdout,stderr:r.stderr,exitCode:"number"==typeof r.exitCode?r.exitCode:null,timedOut:!0===r.timedOut,truncated:!0===r.truncated}:null;if(a){let e=[a.stdout,a.stderr].filter(e=>""!==e.trim()).join("\n"),r=null!==a.exitCode&&0!==a.exitCode;return(0,z.jsxs)("div",{className:"space-y-1",children:[(r||a.timedOut||a.truncated)&&(0,z.jsxs)("div",{className:"flex flex-wrap gap-1",children:[a.timedOut&&(0,z.jsx)(so,{variant:"destructive",className:"text-xs",children:"timed out"}),r&&(0,z.jsxs)(so,{variant:"outline",className:"text-xs",children:["exit ",a.exitCode]}),a.truncated&&(0,z.jsx)(so,{variant:"outline",className:"text-xs",children:"truncated"})]}),(0,z.jsx)(E5,{output:e})]})}let o=n?.content;return"string"==typeof o?(0,z.jsx)(E5,{output:o}):(0,z.jsx)(Dk,{value:n,limit:1e3})}let DT=(0,e_.default)("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);function DA({names:e}){return(0,z.jsxs)("span",{className:"flex min-w-0 items-baseline gap-1 text-xs font-normal text-muted-foreground",title:`Remote access: ${e}`,children:[(0,z.jsx)(no,{className:"w-3 h-3 shrink-0 self-center"}),(0,z.jsx)("span",{className:"truncate",children:e})]})}function DI(e){let r={names:null},s=e.replace(RegExp(DF.source,"g"),(e,s)=>(r.names=s,""));return null===r.names?{text:e,names:null}:{text:s.trimEnd(),names:r.names}}function DM({path:e,size:r,name:s}){let n;return(0,z.jsxs)("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-border bg-muted/60 px-1.5 py-0.5 text-xs font-mono align-baseline",title:e,children:[(0,z.jsx)(void 0===s?ku:DT,{className:"w-3 h-3 text-muted-foreground shrink-0"}),(0,z.jsx)("span",{className:"truncate max-w-[18ch]",children:s??((n=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")))>=0?e.slice(n+1):e)}),(0,z.jsx)("span",{className:"text-muted-foreground",children:function(e){if(e<1024)return`${e} B`;let r=e/1024;return r<10?`${r.toFixed(1)} KB`:r<1024?`${Math.round(r)} KB`:`${(r/1024).toFixed(1)} MB`}(r)})]})}let DF=/<vremotes names="([^"]*)">[\s\S]*?<\/vremotes>/g,DP=RegExp(`${/<vpaste path="([^"]+)" size="(\d+)" \/>/g.source}|${/<vfile path="([^"]+)" name="([^"]*)" size="(\d+)" \/>/g.source}|${DF.source}`,"g");function DL({message:e,messageIndex:r,streaming:s=!1}){let n=function(e,r,s){switch(e.type){case"user":return(0,z.jsx)(DB,{content:e.content,origin:e.origin});case"assistant":return(0,z.jsx)(Dz,{content:e.content,agentType:e.agentType,streaming:s});case"tool_use":return(0,z.jsx)(D$,{tool:e.tool,input:e.input,messageIndex:r,toolUseId:e.toolUseId});case"tool_result":return(0,z.jsx)(DW,{tool:e.tool,output:e.output});case"thinking":return(0,z.jsx)(DH,{content:e.content});case"error":return(0,z.jsx)(DU,{message:e.message});case"system":return(0,z.jsx)(Dq,{content:e.content});case"approval_request":return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-amber-500/10 flex items-center justify-center",children:(0,z.jsx)(N7,{className:"w-4 h-4 text-amber-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-amber-500 mb-1",children:"command"===e.requestType?"Command Approval":"File Change Approval"}),"command"===e.requestType?(0,z.jsx)(EO,{requestId:e.requestId,command:e.command,cwd:e.cwd,messageIndex:r}):(0,z.jsx)(EB,{requestId:e.requestId,changes:e.changes,messageIndex:r})]})]});default:return null}}(e,r,s);return n?(0,z.jsxs)("div",{className:"group relative",children:[n,(0,z.jsx)("span",{className:"pointer-events-none absolute right-0 top-3 text-xs tabular-nums text-muted-foreground opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:function(e){let r=new Date(e),s=new Date,n=r.getFullYear()===s.getFullYear()&&r.getMonth()===s.getMonth()&&r.getDate()===s.getDate(),i=r.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});if(n)return i;let a=r.toLocaleDateString(void 0,{year:"numeric",month:"2-digit",day:"2-digit"});return`${a} ${i}`}(e.timestamp)})]}):null}function DO(e){let r=function(e){let r,s=[],n=0,i=RegExp(DP.source,"g");for(;null!==(r=i.exec(e));)r.index>n&&s.push({kind:"text",text:e.slice(n,r.index)}),void 0!==r[1]?s.push({kind:"chip",path:r[1],size:Number(r[2])}):void 0!==r[3]?s.push({kind:"chip",path:r[3],name:r[4],size:Number(r[5])}):s.push({kind:"remotes",names:r[6]}),n=r.index+r[0].length;return n<e.length&&s.push({kind:"text",text:e.slice(n)}),s}(e);return 1===r.length&&"text"===r[0].kind?(0,z.jsx)("span",{className:"whitespace-pre-wrap break-words",children:e??""}):(0,z.jsx)("div",{className:"text-foreground max-w-none break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:r.map((e,r)=>"text"===e.kind?(0,z.jsx)("span",{className:"whitespace-pre-wrap break-words",children:e.text},r):"remotes"===e.kind?null:(0,z.jsx)(DM,{path:e.path,size:e.size,name:e.name},r))})}function DB({content:e,origin:r}){let s;if("workflow"===r&&"string"==typeof e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,z.jsx)(N5,{className:"w-3.5 h-3.5 text-sky-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Workflow"}),(0,z.jsx)("div",{className:"text-foreground prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,z.jsx)(EA,{children:e})})]})]});let n=null;if("string"==typeof e){let r=DI(e);n=r.names,s=r.text}else for(let r of(s=[],e)){if("text"!==r.type){s.push(r);continue}let e=DI(r.text);null!==e.names&&(n=e.names),(null===e.names||e.text.length>0)&&s.push({...r,text:e.text})}return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-primary/10 flex items-center justify-center",children:(0,z.jsx)(NZ,{className:"w-3.5 h-3.5 text-primary"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsxs)("p",{className:"flex min-w-0 items-baseline gap-1.5 text-sm font-medium text-foreground mb-1",children:[(0,z.jsx)("span",{className:"shrink-0",children:"You"}),n&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"shrink-0 text-muted-foreground/60","aria-hidden":!0,children:"·"}),(0,z.jsx)(DA,{names:n})]})]}),(0,z.jsx)("div",{className:"text-foreground max-w-none break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:"string"==typeof s?DO(s):s.map((e,r)=>"text"===e.type?(0,z.jsx)($.Fragment,{children:DO(e.text)},r):(0,z.jsx)("img",{src:`data:${e.mediaType};base64,${e.data}`,alt:"Attached image",className:"max-w-sm rounded-lg mt-2"},r))})]})]})}function Dz({content:e,agentType:r,streaming:s=!1}){let n=function(){try{return TS().agentType}catch{return"claude-code"}}(),i="codex"===(r??n),[a,o]=(0,$.useState)(!1);return(0,z.jsxs)("div",{className:"group flex gap-3 py-3",children:[(0,z.jsx)("div",{className:`flex-shrink-0 w-7 h-7 rounded-lg ${i?"bg-green-500/10":"bg-violet-500/10"} flex items-center justify-center`,children:(0,z.jsx)(sS,{className:`w-3.5 h-3.5 ${i?"text-green-500":"text-violet-500"}`})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,z.jsx)("p",{className:`text-sm font-medium ${i?"text-green-500":"text-violet-500"}`,children:i?"Codex":"Claude"}),(0,z.jsx)("button",{type:"button",onClick:()=>o(e=>!e),title:a?"View rendered":"View source","aria-label":a?"View rendered":"View source","aria-pressed":a,className:"opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity text-muted-foreground hover:text-foreground",children:a?(0,z.jsx)(_P,{className:"w-3.5 h-3.5"}):(0,z.jsx)(k_,{className:"w-3.5 h-3.5"})})]}),a?(0,z.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-words bg-muted/50 rounded-md p-3 overflow-x-auto text-foreground select-text",children:e??""}):(0,z.jsx)("div",{className:"text-foreground prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,z.jsx)(EA,{streaming:s,children:e??""})})]})]})}function D$({tool:e,input:r,messageIndex:s,toolUseId:n}){if(e===Dy)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-amber-500/10 flex items-center justify-center",children:(0,z.jsx)(sj,{className:"w-4 h-4 text-amber-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-amber-500 mb-1",children:"Suggested scheduled check"}),(0,z.jsx)(Db,{input:r,toolUseId:n})]})]});if("ImageView"===e){let e="object"==typeof r&&null!==r&&"path"in r&&"string"==typeof r.path?r.path:"";return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,z.jsx)(_P,{className:"w-4 h-4 text-sky-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"View Image"}),(0,z.jsx)("p",{className:"font-mono text-muted-foreground break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e})]})]})}if("AskUserQuestion"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-violet-500/10 flex items-center justify-center",children:(0,z.jsx)(dc,{className:"w-4 h-4 text-violet-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-violet-500 mb-1",children:"Question"}),(0,z.jsx)(EI,{input:r,messageIndex:s})]})]});if("ExitPlanMode"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-green-500/10 flex items-center justify-center",children:(0,z.jsx)(N1,{className:"w-4 h-4 text-green-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-green-500 mb-1",children:"Plan Ready"}),(0,z.jsx)(EL,{input:r,messageIndex:s})]})]});let i={TodoWrite:{label:"Tasks",ui:(0,z.jsx)(Eq,{input:r})},TaskCreate:{label:"Create Task",ui:(0,z.jsx)(EK,{input:r})},TaskUpdate:{label:"Update Task",ui:(0,z.jsx)(EV,{input:r})},TaskList:{label:"Task List",ui:(0,z.jsx)(EX,{})},TaskGet:{label:"Get Task",ui:(0,z.jsx)(EY,{input:r})}}[e];if(i)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-cyan-500/10 flex items-center justify-center",children:(0,z.jsx)(s0,{className:"w-4 h-4 text-cyan-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-cyan-500 mb-1",children:i.label}),i.ui]})]});if("Read"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,z.jsx)(ku,{className:"w-4 h-4 text-sky-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Read File"}),(0,z.jsx)(EJ,{input:r})]})]});if("Edit"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,z.jsx)(N3,{className:"w-4 h-4 text-sky-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Edit File"}),(0,z.jsx)(Dr,{input:r})]})]});if("Write"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,z.jsx)(N4,{className:"w-4 h-4 text-sky-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Write File"}),(0,z.jsx)(E0,{input:r})]})]});if("Bash"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-emerald-500/10 flex items-center justify-center",children:(0,z.jsx)(gM,{className:"w-4 h-4 text-emerald-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-emerald-500 mb-1",children:"Run Command"}),(0,z.jsx)(E2,{input:r})]})]});if("Grep"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-orange-500/10 flex items-center justify-center",children:(0,z.jsx)(sA,{className:"w-4 h-4 text-orange-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-orange-500 mb-1",children:"Search"}),(0,z.jsx)(E3,{input:r})]})]});if("Glob"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-teal-500/10 flex items-center justify-center",children:(0,z.jsx)(N2,{className:"w-4 h-4 text-teal-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-teal-500 mb-1",children:"Glob"}),(0,z.jsx)(E6,{input:r})]})]});if("Task"===e||"Agent"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-purple-500/10 flex items-center justify-center",children:(0,z.jsx)(N5,{className:"w-4 h-4 text-purple-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-purple-500 mb-1",children:"Agent"}),(0,z.jsx)(E9,{input:r})]})]});if("TaskOutput"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-purple-500/10 flex items-center justify-center",children:(0,z.jsx)(N5,{className:"w-4 h-4 text-purple-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-purple-500 mb-1",children:"Task Output"}),(0,z.jsx)(Dd,{input:r})]})]});if("WebFetch"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-blue-500/10 flex items-center justify-center",children:(0,z.jsx)(rw,{className:"w-4 h-4 text-blue-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-blue-500 mb-1",children:"Fetch Web Page"}),(0,z.jsx)(Dn,{input:r})]})]});if("WebSearch"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-indigo-500/10 flex items-center justify-center",children:(0,z.jsx)(N6,{className:"w-4 h-4 text-indigo-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-indigo-500 mb-1",children:"Web Search"}),(0,z.jsx)(Da,{input:r})]})]});if("Skill"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-pink-500/10 flex items-center justify-center",children:(0,z.jsx)(p8,{className:"w-4 h-4 text-pink-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-pink-500 mb-1",children:"Skill"}),(0,z.jsx)(Dl,{input:r})]})]});if("FileChange"===e)return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,z.jsx)(N3,{className:"w-4 h-4 text-sky-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"File Changes"}),(0,z.jsx)(Dh,{input:r})]})]});if(null!==Dj(e))return(0,z.jsx)(DN,{tool:e,input:r});let a="string"==typeof r?r:JSON.stringify(r,null,2);return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-amber-500/10 flex items-center justify-center",children:(0,z.jsx)(NQ,{className:"w-4 h-4 text-amber-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsxs)("p",{className:"text-sm font-medium text-amber-500 mb-1 break-words",children:["Tool: ",e]}),(0,z.jsxs)("details",{open:!0,children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Input"}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:a.length>500?a.substring(0,500)+"...":a})]})]})]})}function DW({tool:e,output:r}){if(e===Dy)return null;let s=function(e){if(!e.startsWith("[")||!e.includes('"type":"image"'))return null;try{let r=JSON.parse(e);if(!Array.isArray(r))return null;let s=[];for(let e of r){if(!e||"image"!==e.type)continue;let r=e.source;r?.type==="base64"&&"string"==typeof r.data&&s.push({mediaType:r.media_type??"image/png",data:r.data})}return s.length>0?s:null}catch{return null}}(r);if(s)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(EZ,{images:s})})});if(["TodoWrite","TaskCreate","TaskUpdate","TaskList","TaskGet"].includes(e)){let s="TaskList"===e?(0,z.jsx)(EG,{output:r}):null;return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsxs)("p",{className:"text-xs text-muted-foreground mb-1",children:["Result (",e,")"]}),s||(0,z.jsxs)("details",{children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Output"}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>1e3?r.substring(0,1e3)+"...":r})]})]})})}if("Read"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(EQ,{output:r})})});if("Edit"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(Ds,{output:r})})});if("Write"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(E1,{output:r})})});if("Bash"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(E5,{output:r})})});if("Grep"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(E4,{output:r})})});if("Glob"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(E7,{output:r})})});if("Task"===e||"Agent"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(De,{output:r})})});if("TaskOutput"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(Du,{output:r})})});if("WebFetch"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(Di,{output:r})})});if("WebSearch"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(Do,{output:r})})});if("Skill"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(Dc,{output:r})})});if("FileChange"===e)return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(Df,{output:r})})});if(null!==Dj(e))return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)(DR,{output:r})})});let n=r.length>200;return(0,z.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsxs)("p",{className:"text-xs text-muted-foreground mb-1",children:["Result",e?` (${e})`:""]}),(0,z.jsxs)("details",{className:(0,eb.cn)(!n&&"open"),children:[(0,z.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Output"}),(0,z.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>1e3?r.substring(0,1e3)+"...":r})]})]})})}function DH({content:e}){let r=e??"",s=r.trim().length>0,n=s?r.length>500?r.substring(0,500)+"...":r:"Reasoning unavailable — this model does not expose its thinking content.";return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-blue-500/10 flex items-center justify-center",children:(0,z.jsx)(N0,{className:"w-3.5 h-3.5 text-blue-500"})}),(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsxs)("details",{children:[(0,z.jsx)("summary",{className:"text-xs font-medium text-blue-500 cursor-pointer hover:underline",children:"Thinking..."}),(0,z.jsx)("div",{className:`mt-2 whitespace-pre-wrap break-words bg-blue-500/5 p-2 rounded-md overflow-hidden ${s?"text-muted-foreground":"text-muted-foreground/70 italic"}`,style:{fontSize:"var(--conv-font-size, 12px)"},children:n})]})})]})}function DU({message:e}){return(0,z.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-red-500/10 flex items-center justify-center",children:(0,z.jsx)(s_,{className:"w-3.5 h-3.5 text-red-500"})}),(0,z.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-red-500 mb-1",children:"Error"}),(0,z.jsx)("p",{className:"text-red-500/80 break-words whitespace-pre-wrap",style:{fontSize:"var(--conv-font-size, 14px)"},children:e})]})]})}function Dq({content:e}){return(0,z.jsxs)("div",{className:"flex gap-3 py-2",children:[(0,z.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-gray-500/10 flex items-center justify-center",children:(0,z.jsx)(hv,{className:"w-3.5 h-3.5 text-gray-500"})}),(0,z.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,z.jsx)("p",{className:"text-muted-foreground break-words",style:{fontSize:"var(--conv-font-size, 12px)"},children:e??""})})]})}let DK=/^data:[^;,]*(?:;[^;,]*)*;base64,(.+)$/;async function DV(e){if(!e)return null;if(e.startsWith("data:"))return e;try{let r=await fetch(e),s=await r.blob();return await new Promise(e=>{let r=new FileReader;r.onload=()=>e("string"==typeof r.result?r.result:null),r.onerror=()=>e(null),r.readAsDataURL(s)})}catch{return null}}let DX=(0,e_.default)("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]),DY=(0,e_.default)("file-plus",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]]);(0,e_.default)("mic",[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]]);let DG=(e=21)=>{let r="",s=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)r+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&s[e]];return r},DJ=(0,$.createContext)(null),DZ=(0,$.createContext)(null),DQ=()=>(0,$.useContext)(DJ),D0=(0,$.createContext)(null),D1=()=>{let e=(0,$.useContext)(DZ),r=(0,$.useContext)(D0),s=e??r;if(!s)throw Error("usePromptInputAttachments must be used within a PromptInput or PromptInputProvider");return s};function D2({data:e,className:r,status:s,onRetry:n,...i}){let a=D1(),o=e.filename||"",l=s?.phase==="reading"||s?.phase==="uploading",c=s?.phase==="error",d="image"==(e.mediaType?.startsWith("image/")&&e.url?"image":"file"),u=o||(d?"Image":"Attachment");return(0,z.jsxs)(Ri,{children:[(0,z.jsx)(Eb,{asChild:!0,children:(0,z.jsxs)("div",{className:(0,eb.cn)("group relative flex h-8 cursor-pointer select-none items-center gap-1.5 overflow-hidden rounded-md border border-border px-1.5 font-medium text-sm transition-all hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",c&&"border-destructive text-destructive",r),onClick:c?n:void 0,...i,children:[(0,z.jsxs)("div",{className:"relative size-5 shrink-0",children:[(0,z.jsx)("div",{className:"absolute inset-0 flex size-5 items-center justify-center overflow-hidden rounded bg-background transition-opacity group-hover:opacity-0",children:d?(0,z.jsx)("img",{alt:o||"attachment",className:"size-5 object-cover",height:20,src:e.url,width:20}):(0,z.jsx)("div",{className:"flex size-5 items-center justify-center text-muted-foreground",children:(0,z.jsx)(DT,{className:"size-3"})})}),(0,z.jsxs)(W.Button,{"aria-label":"Remove attachment",className:"absolute inset-0 size-5 cursor-pointer rounded p-0 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 [&>svg]:size-2.5",onClick:r=>{r.stopPropagation(),a.remove(e.id)},type:"button",variant:"ghost",children:[(0,z.jsx)(t7,{}),(0,z.jsx)("span",{className:"sr-only",children:"Remove"})]})]}),(0,z.jsx)("span",{className:(0,eb.cn)("flex-1 truncate",l&&"opacity-60"),children:u}),l&&(0,z.jsx)(sC,{className:"size-3 shrink-0 animate-spin text-muted-foreground"}),c&&(0,z.jsx)(s_,{className:"size-3 shrink-0"}),s?.phase==="uploading"&&(0,z.jsx)("span",{"aria-hidden":!0,className:"absolute inset-x-0 bottom-0 h-0.5 bg-primary transition-[width] duration-150","data-testid":"attachment-progress",style:{width:`${Math.round((s.progress??0)*100)}%`}})]},e.id)}),(0,z.jsx)(Ra,{className:"w-auto p-2",children:(0,z.jsxs)("div",{className:"w-auto space-y-3",children:[d&&(0,z.jsx)("div",{className:"flex max-h-96 w-96 items-center justify-center overflow-hidden rounded-md border",children:(0,z.jsx)("img",{alt:o||"attachment preview",className:"max-h-full max-w-full object-contain",height:384,src:e.url,width:448})}),(0,z.jsx)("div",{className:"flex items-center gap-2.5",children:(0,z.jsxs)("div",{className:"min-w-0 flex-1 space-y-1 px-0.5",children:[(0,z.jsx)("h4",{className:"truncate font-semibold text-sm leading-none",children:o||(d?"Image":"Attachment")}),c?(0,z.jsxs)("p",{className:"text-destructive text-xs",children:[s?.message??"Upload failed",n?" — click to retry":""]}):l?(0,z.jsx)("p",{className:"text-muted-foreground text-xs",children:s?.phase==="reading"?"Reading…":`Uploading… ${Math.round((s?.progress??0)*100)}%`}):e.mediaType&&(0,z.jsx)("p",{className:"truncate font-mono text-muted-foreground text-xs",children:e.mediaType})]})})]})})]})}function D5({children:e,className:r,...s}){let n=D1();return n.files.length?(0,z.jsx)("div",{className:(0,eb.cn)("flex flex-wrap items-center gap-2 p-3 w-full",r),...s,children:n.files.map(r=>(0,z.jsx)($.Fragment,{children:e(r)},r.id))}):null}let D3=({label:e="Add photos or files",...r})=>{let s=D1(),n=(0,$.useContext)(D9);return(0,z.jsxs)(o2,{...r,onSelect:e=>{e.preventDefault(),s.openFileDialog(),setTimeout(()=>n?.(),0)},children:[(0,z.jsx)(DY,{className:"mr-2 size-4"})," ",e]})},D4=({className:e,accept:r,multiple:s,globalDrop:n,syncHiddenInput:i,maxFiles:a,maxFileSize:o,skipAttachmentConversion:l,onError:c,onSubmit:d,children:u,...h})=>{let f=DQ(),p=!!f,m=(0,$.useRef)(null),g=(0,$.useRef)(null),[x,v]=(0,$.useState)([]),y=p?f.attachments.files:x,b=(0,$.useRef)(y);b.current=y;let w=(0,$.useCallback)(()=>{m.current?.click()},[]),_=(0,$.useCallback)(e=>!r||""===r.trim()||r.split(",").map(e=>e.trim()).filter(Boolean).some(r=>{if(r.endsWith("/*")){let s=r.slice(0,-1);return e.type.startsWith(s)}return e.type===r}),[r]),S=(0,$.useCallback)(e=>{let r=Array.from(e),s=r.filter(e=>_(e));if(r.length&&0===s.length)return void c?.({code:"accept",message:"No files match the accepted types."});let n=e=>!o||e.size<=o,i=s.filter(n),l=s.filter(e=>!n(e));l.length>0&&(c?.({code:"max_file_size",message:0===i.length?"All files exceed the maximum size.":`Skipped ${l.length} file${1===l.length?"":"s"} over the maximum size: ${l.map(e=>e.name).join(", ")}`,files:l}),0===i.length)||v(e=>{let r="number"==typeof a?Math.max(0,a-e.length):void 0,s="number"==typeof r?i.slice(0,r):i;"number"==typeof r&&i.length>r&&c?.({code:"max_files",message:"Too many files. Some were not added."});let n=[];for(let e of s)n.push({id:DG(),type:"file",url:URL.createObjectURL(e),mediaType:e.type,filename:e.name});return e.concat(n)})},[_,a,o,c]),j=(0,$.useCallback)(e=>v(r=>{let s=r.find(r=>r.id===e);return s?.url&&URL.revokeObjectURL(s.url),r.filter(r=>r.id!==e)}),[]),k=(0,$.useCallback)(()=>v(e=>{for(let r of e)r.url&&URL.revokeObjectURL(r.url);return[]}),[]),C=(0,$.useCallback)(()=>{let e=b.current;return v([]),e},[]),N=(0,$.useCallback)(e=>{v(r=>{let s=new Set(r.map(e=>e.id));return r.concat(e.filter(e=>!s.has(e.id)))})},[]),E=p?f.attachments.add:S,D=p?f.attachments.remove:j,R=p?f.attachments.clear:k,T=p?f.attachments.detach:C,A=p?f.attachments.restore:N,I=p?f.attachments.openFileDialog:w;(0,$.useEffect)(()=>{p&&f.__registerFileInput(m,()=>m.current?.click())},[p,f]),(0,$.useEffect)(()=>{i&&m.current&&0===y.length&&(m.current.value="")},[y,i]),(0,$.useEffect)(()=>{let e=g.current;if(!e||n)return;let r=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault()},s=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault(),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&E(e.dataTransfer.files)};return e.addEventListener("dragover",r),e.addEventListener("drop",s),()=>{e.removeEventListener("dragover",r),e.removeEventListener("drop",s)}},[E,n]),(0,$.useEffect)(()=>{if(!n)return;let e=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault()},r=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault(),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&E(e.dataTransfer.files)};return document.addEventListener("dragover",e),document.addEventListener("drop",r),()=>{document.removeEventListener("dragover",e),document.removeEventListener("drop",r)}},[E,n]),(0,$.useEffect)(()=>()=>{if(!p)for(let e of b.current)e.url&&URL.revokeObjectURL(e.url)},[p]);let M=(0,$.useMemo)(()=>({files:y.map(e=>({...e,id:e.id})),add:E,remove:D,clear:R,detach:T,restore:A,openFileDialog:I,fileInputRef:m}),[y,E,D,R,T,A,I]),F=(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("input",{accept:r,"aria-label":"Upload files",className:"hidden",multiple:s,onChange:e=>{e.currentTarget.files&&E(e.currentTarget.files),e.currentTarget.value=""},ref:m,title:"Upload files",type:"file"}),(0,z.jsx)("form",{className:(0,eb.cn)("w-full",e),onSubmit:e=>{e.preventDefault();let r=e.currentTarget,s=p?f.textInput.value:new FormData(r).get("message")||"";p||r.reset(),Promise.all(y.map(async e=>{if(!l&&e.url&&e.url.startsWith("blob:")){let r=await DV(e.url);return{...e,url:r??e.url}}return e})).then(r=>{try{let n=d({text:s,files:r},e);n instanceof Promise?n.then(()=>{R(),p&&f.textInput.clear()}).catch(()=>{}):(R(),p&&f.textInput.clear())}catch{}}).catch(()=>{})},ref:g,...h,children:(0,z.jsx)(kr,{className:"overflow-hidden border-[#dedede] bg-card shadow-none dark:border-input dark:bg-card focus-within:border-foreground has-[[data-slot=input-group-control]:focus-visible]:border-foreground has-[[data-slot=input-group-control]:focus-visible]:ring-0",children:u})})]});return p?F:(0,z.jsx)(D0.Provider,{value:M,children:F})},D6=({onChange:e,onKeyDown:r,onPasteText:s,className:n,placeholder:i="What would you like to know?",...a})=>{let o=DQ(),l=D1(),[c,d]=(0,$.useState)(!1),u=o?{value:o.textInput.value,onChange:r=>{o.textInput.setInput(r.currentTarget.value),e?.(r)}}:{onChange:e};return(0,z.jsx)(kl,{className:(0,eb.cn)("field-sizing-content max-h-48 min-h-9",n),name:"message",onCompositionEnd:()=>d(!1),onCompositionStart:()=>d(!0),onKeyDown:e=>{if(r?.(e),!e.defaultPrevented){if("Enter"===e.key){if(c||e.nativeEvent.isComposing||e.shiftKey)return;e.preventDefault();let r=e.currentTarget.form,s=r?.querySelector('button[type="submit"]');if(s?.disabled)return;r?.requestSubmit()}if("Backspace"===e.key&&""===e.currentTarget.value&&l.files.length>0){e.preventDefault();let r=l.files.at(-1);r&&l.remove(r.id)}}},onPaste:e=>{let r=e.clipboardData?.items;if(!r)return;let n=[];for(let e of r)if("file"===e.kind){let r=e.getAsFile();r&&n.push(r)}if(n.length>0){e.preventDefault(),l.add(n);return}if(s){let r=e.clipboardData.getData("text");r.length>0&&s(e,r)}},placeholder:i,...a,...u})},D7=({className:e,...r})=>(0,z.jsx)(kn,{align:"block-end",className:(0,eb.cn)("order-first flex-wrap gap-1",e),...r}),D8=({variant:e="ghost",className:r,size:s,...n})=>{let i=s??($.Children.count(n.children)>1?"sm":"icon-sm");return(0,z.jsx)(ka,{className:(0,eb.cn)(r),size:i,type:"button",variant:e,...n})},D9=(0,$.createContext)(null),Re=({open:e,defaultOpen:r,onOpenChange:s,...n})=>{let[i,a]=(0,$.useState)(r??!1),o=void 0!==e,l=(0,$.useCallback)(e=>{o||a(e),s?.(e)},[o,s]),c=(0,$.useCallback)(()=>l(!1),[l]);return(0,z.jsx)(D9.Provider,{value:c,children:(0,z.jsx)(oQ,{open:o?e:i,onOpenChange:l,...n})})},Rt=({className:e,children:r,...s})=>(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)(D8,{className:e,...s,children:r??(0,z.jsx)(eS,{className:"size-4"})})}),Rr=({className:e,...r})=>(0,z.jsx)(o1,{align:"start",className:(0,eb.cn)(e),...r}),Rs=({className:e,...r})=>(0,z.jsx)(o2,{className:(0,eb.cn)(e),...r}),Rn=({className:e,variant:r="default",size:s="icon-sm",status:n,children:i,...a})=>{let o=(0,z.jsx)(DX,{className:"size-4"});return"submitted"===n?o=(0,z.jsx)(sC,{className:"size-4 animate-spin"}):"streaming"===n?o=(0,z.jsx)(lG,{className:"size-4"}):"error"===n&&(o=(0,z.jsx)(t7,{className:"size-4"})),(0,z.jsx)(ka,{"aria-label":"Submit",className:(0,eb.cn)("rounded-full",e),size:s,type:"submit",variant:r,...a,children:i??o})},Ri=({openDelay:e=0,closeDelay:r=0,...s})=>(0,z.jsx)(Ey,{closeDelay:r,openDelay:e,...s}),Ra=({align:e="start",...r})=>(0,z.jsx)(Ew,{align:e,...r}),Ro=({size:e=16})=>(0,z.jsxs)("svg",{height:e,strokeLinejoin:"round",style:{color:"currentcolor"},viewBox:"0 0 16 16",width:e,children:[(0,z.jsx)("title",{children:"Loader"}),(0,z.jsxs)("g",{clipPath:"url(#clip0_2393_1490)",children:[(0,z.jsx)("path",{d:"M8 0V4",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M8 16V12",opacity:"0.5",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M3.29773 1.52783L5.64887 4.7639",opacity:"0.9",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M12.7023 1.52783L10.3511 4.7639",opacity:"0.1",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M12.7023 14.472L10.3511 11.236",opacity:"0.4",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M3.29773 14.472L5.64887 11.236",opacity:"0.6",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M15.6085 5.52783L11.8043 6.7639",opacity:"0.2",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M0.391602 10.472L4.19583 9.23598",opacity:"0.7",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M15.6085 10.4722L11.8043 9.2361",opacity:"0.3",stroke:"currentColor",strokeWidth:"1.5"}),(0,z.jsx)("path",{d:"M0.391602 5.52783L4.19583 6.7639",opacity:"0.8",stroke:"currentColor",strokeWidth:"1.5"})]}),(0,z.jsx)("defs",{children:(0,z.jsx)("clipPath",{id:"clip0_2393_1490",children:(0,z.jsx)("rect",{fill:"white",height:"16",width:"16"})})})]}),Rl=({className:e,size:r=16,...s})=>(0,z.jsx)("div",{className:(0,eb.cn)("inline-flex animate-spin items-center justify-center",e),...s,children:(0,z.jsx)(Ro,{size:r})}),Rc=new Map;function Rd(e,r){return`${e}\u0000${r??""}`}let Ru=null,Rh=new Map,Rf=new Set;function Rp(e){return Rf.add(e),()=>{Rf.delete(e)}}function Rm(e,r,s){if(!e||!s)return;let n=Rh.get(Rd(e,r));return n?n.has(s):void 0}function Rg(e,r,s){let n=Rd(e,r),i=function(){if(null===Ru){let e={};Ru=e,queueMicrotask(()=>{Ru===e&&(Ru=null)})}return Ru}(),a=Rc.get(n);if(a&&(!s?.force||a.tick===i))return{request:a.request,issuedAt:a.issuedAt};let o=Date.now(),l=ry.api.getActiveWorkflowRuns(e,r).then(e=>(!function(e,r){if(!r)return;let s=Rh.get(e);if(s&&r.every(e=>s.has(e)))return;let n=new Set(s??[]);r.forEach(e=>n.add(e)),Rh.set(e,n),Rf.forEach(e=>e())}(n,e.reviewedSessionIds),e.runs)),c={request:l,tick:i,issuedAt:o};return Rc.set(n,c),l.finally(()=>{Rc.get(n)===c&&Rc.delete(n)}).catch(()=>{}),{request:l,issuedAt:o}}function Rx(e,r,s){return Rg(e,r,s).request}let Rv=(0,e_.default)("wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]),Ry=(0,e_.default)("square-pen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]),Rb=(0,e_.default)("languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]),Rw=(0,e_.default)("split",[["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M8 3H3v5",key:"15dfkv"}],["path",{d:"M12 22v-8.3a4 4 0 0 0-1.172-2.872L3 3",key:"1qrqzj"}],["path",{d:"m15 9 6-6",key:"ko1vev"}]]),R_=e=>(0,eb.cn)("flex h-5 w-5 shrink-0 items-center justify-center rounded-full","codex"===e?"bg-emerald-500/10 text-emerald-600":"bg-violet-500/10 text-violet-600");function RS({agentType:e,currentAgentName:r,alternateProviders:s,onBranch:n,disabled:i,emphasis:a="normal"}){return(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:(0,eb.cn)("h-7 w-7 rounded-md transition-colors hover:bg-muted hover:text-foreground","subtle"===a?"text-muted-foreground/50 group-hover:text-muted-foreground group-focus-within:text-muted-foreground":"text-muted-foreground"),disabled:i,"aria-label":"Branch conversation",children:i?(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"}):(0,z.jsx)(Rw,{className:"h-4 w-4"})})}),(0,z.jsxs)(o1,{align:"start",className:"w-44 p-1.5",children:[(0,z.jsx)(o6,{className:"px-2 py-1.5",children:(0,z.jsx)("div",{className:"text-xs font-medium",children:"Branch conversation"})}),(0,z.jsxs)(o2,{className:"h-8 cursor-pointer items-center gap-2 rounded-md px-2 text-xs",onSelect:()=>n(),children:[(0,z.jsx)("div",{className:R_(e),children:(0,z.jsx)(sS,{className:"h-3 w-3"})}),(0,z.jsx)("span",{className:"min-w-0 flex-1 truncate",children:r}),(0,z.jsx)("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:"current"})]}),s.length>0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(o7,{className:"my-1"}),s.map(e=>(0,z.jsxs)(o2,{className:"h-8 cursor-pointer items-center gap-2 rounded-md px-2 text-xs",onSelect:()=>n(e.type),children:[(0,z.jsx)("div",{className:R_(e.type),children:(0,z.jsx)(sS,{className:"h-3 w-3"})}),(0,z.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.displayName})]},e.type))]})]})]})}let Rj=(0,e_.default)("corner-up-left",[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]]),Rk=e=>(0,eb.cn)("h-7 w-7 shrink-0 rounded-md transition-colors hover:bg-muted hover:text-foreground","subtle"===e?"text-muted-foreground/50 group-hover:text-muted-foreground group-focus-within:text-muted-foreground":"text-muted-foreground");function RC({sendBack:e,emphasis:r}){let s=e.available?e.sent?"Sent — click to send again":"Send this answer back to the source session":"Source session no longer exists",n=(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:Rk(r),"aria-label":"Send back to source session",disabled:!e.available||e.busy,onClick:e.onSend,children:e.busy?(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"}):e.sent?(0,z.jsx)(rp.Check,{className:"h-4 w-4"}):(0,z.jsx)(Rj,{className:"h-4 w-4"})});return(0,z.jsx)(cb,{children:(0,z.jsxs)(cw,{children:[(0,z.jsx)(c_,{asChild:!0,children:e.available?n:(0,z.jsx)("span",{tabIndex:-1,children:n})}),(0,z.jsx)(cS,{children:s})]})})}function RN({durationMs:e,outcome:r,emphasis:s,agentType:n,currentAgentName:i,alternateProviders:a,onBranch:o,disabled:l,showFinalize:c,finalizeBusy:d,onFinalize:u,sendBack:h}){let f=void 0!==e?fx(e):"server_restart"===r?"interrupted":null;return(0,z.jsxs)("div",{className:"group flex items-center gap-2 py-0.5","data-turn-end":!0,children:[(0,z.jsx)("div",{className:"h-px flex-1 bg-border/60"}),null!==f&&(0,z.jsx)("span",{className:(0,eb.cn)("shrink-0 text-[11px] tabular-nums transition-colors","subtle"===s?"text-muted-foreground/50 group-hover:text-muted-foreground group-focus-within:text-muted-foreground":"text-muted-foreground"),children:f}),c&&(0,z.jsx)(cb,{children:(0,z.jsxs)(cw,{children:[(0,z.jsx)(c_,{asChild:!0,children:(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:Rk(s),"aria-label":"生成 review 终稿",onClick:u,disabled:l||d,children:d?(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"}):(0,z.jsx)(N1,{className:"h-4 w-4"})})}),(0,z.jsx)(cS,{children:"生成 review 终稿"})]})}),h&&(0,z.jsx)(RC,{sendBack:h,emphasis:s}),(0,z.jsx)(RS,{agentType:n,currentAgentName:i,alternateProviders:a,onBranch:o,disabled:l,emphasis:s}),(0,z.jsx)("div",{className:"h-px flex-1 bg-border/60"})]})}let RE=(e,r)=>Math.max(0,e-r),RD=["process","agent","other"],RR={process:"Process",agent:"Subagent",other:"Task"},RT={process:["background process","background processes"],agent:["background subagent","background subagents"],other:["background task","background tasks"]};function RA(e){return"local_bash"===e.taskType?"process":"local_agent"===e.taskType||"codex_subagent"===e.taskType?"agent":"other"}function RI({kind:e}){let r="h-3.5 w-3.5";return"process"===e?(0,z.jsx)(gM,{className:r,"aria-hidden":"true"}):"agent"===e?(0,z.jsx)(sS,{className:r,"aria-hidden":"true"}):(0,z.jsx)(s0,{className:r,"aria-hidden":"true"})}function RM({sessionId:e,tasks:r,turnParked:s,parkDeadlineAt:n,canStopTasks:i,agentWorking:a}){let o,l,[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(new Set),f=function(e){let[r,s]=(0,$.useState)(()=>Date.now());return(0,$.useEffect)(()=>{if(!e)return;let r=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(r)},[e]),r}(r.length>0);if(0===r.length)return null;let p=r.reduce((e,r)=>Math.max(e,RE(f,r.startedAt)),0),m=null===n||(o=Math.round((n-f)/1e3))<=0?null:`${Math.floor(o/60)}:${String(o%60).padStart(2,"0")}`,g=r.some(e=>e.sanctioned),x=s||a,v=m?`${m} until this turn closes automatically`:s&&g?"Waiting for these tasks":s?"Response complete":a?"Running alongside the agent":"This turn has closed",y=async(r,s)=>{if(e){h(e=>new Set(e).add(r));try{return await s(r)}finally{h(e=>{let s=new Set(e);return s.delete(r),s})}}};return(0,z.jsxs)("div",{className:(0,eb.cn)("mb-2 rounded-lg border text-xs",x?"border-amber-500/40 bg-amber-500/5":"border-border/60 bg-muted/30"),children:[(0,z.jsxs)("button",{type:"button",onClick:()=>d(e=>!e),"aria-expanded":c,className:"flex w-full items-center gap-2 px-3 py-2 text-left text-muted-foreground transition-colors hover:text-foreground",children:[(0,z.jsxs)("span",{className:"relative flex h-1.5 w-1.5 shrink-0",children:[(0,z.jsx)("span",{className:(0,eb.cn)("absolute inline-flex h-full w-full animate-ping rounded-full",x?"bg-amber-500/60":"bg-muted-foreground/40")}),(0,z.jsx)("span",{className:(0,eb.cn)("relative inline-flex h-1.5 w-1.5 rounded-full",x?"bg-amber-500":"bg-muted-foreground/70")})]}),(0,z.jsxs)("span",{className:"truncate",children:[(l=RD.flatMap(e=>{let s=r.filter(r=>RA(r)===e).length;return s?[`${s} ${RT[e][+(1!==s)]}`]:[]}),`${l.join(" · ")} running`),(0,z.jsxs)("span",{className:"tabular-nums",children:[" · ",fx(p)]})]}),(0,z.jsx)("span",{className:(0,eb.cn)("shrink-0",m?"text-amber-600 dark:text-amber-500":"text-muted-foreground/70"),children:v}),(0,z.jsx)(n6,{className:(0,eb.cn)("ml-auto h-3.5 w-3.5 shrink-0 transition-transform",c&&"rotate-180")})]}),c&&(0,z.jsxs)("ul",{className:"border-t border-border/60 px-3 py-2",children:[r.map(r=>{let s=RA(r),n=RR[s];return(0,z.jsxs)("li",{className:"flex items-baseline gap-2 py-1",children:[(0,z.jsx)("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center self-center text-muted-foreground","aria-label":n,title:n,children:(0,z.jsx)(RI,{kind:s})}),(0,z.jsx)("span",{className:"min-w-0 flex-1 truncate text-foreground/90",children:r.description||r.taskId}),(0,z.jsx)("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:fx(RE(f,r.startedAt))}),e&&(0,z.jsxs)("span",{className:"flex shrink-0 gap-1",children:[m&&!r.sanctioned&&(0,z.jsx)("button",{type:"button",onClick:()=>y(r.taskId,r=>(0,ry.keepBackgroundTaskRunning)(e,r)),disabled:u.has(r.taskId),title:"Keep this turn open until this task finishes, instead of closing it when the timer runs out",className:"rounded border border-border/60 px-1.5 py-px text-[11px] text-muted-foreground transition-colors hover:text-foreground disabled:opacity-50",children:"Keep waiting"}),i&&(0,z.jsx)("button",{type:"button",onClick:()=>y(r.taskId,r=>(0,ry.stopBackgroundTask)(e,r)),disabled:u.has(r.taskId),title:"End this background task now",className:"rounded border border-border/60 px-1.5 py-px text-[11px] text-muted-foreground transition-colors hover:text-foreground disabled:opacity-50",children:"Stop task"})]})]},r.taskId)}),(0,z.jsx)("li",{className:"pt-1.5 text-muted-foreground/70",children:m?"The agent has already answered — these tasks are the only thing keeping this turn open. When the timer runs out the turn closes on its own, and the tasks keep running in the background.":s&&g?"You chose to keep waiting for these tasks, so this turn stays open until they finish.":s?"The agent has already answered — these tasks are the only thing keeping this turn open.":a?"The agent is still working. These tasks are running alongside it.":"This turn has closed, but these tasks are still running. Stopping them will not affect the completed turn."}),!i&&(0,z.jsx)("li",{className:"pt-1 text-muted-foreground/70",children:"This agent cannot stop individual background tasks. Stop the session to end them all."})]})]})}function RF({candidates:e,className:r,children:s}){let n=Array.from(new Set(e));return(0,z.jsxs)("span",{className:(0,eb.cn)("grid overflow-hidden text-left",r),children:[n.map(e=>(0,z.jsx)("span",{"aria-hidden":!0,className:"col-start-1 row-start-1 invisible whitespace-nowrap",children:e},e)),(0,z.jsx)("span",{className:"col-start-1 row-start-1 min-w-0 truncate",children:s})]})}let RP="Default",RL="Runs whatever model the CLI is currently set to, which may not be its built-in default.",RO="inline-flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-0.5 text-xs font-medium";function RB({models:e,widthCandidates:r,value:s,onChange:n,locked:i}){let a,[o,l]=(0,$.useState)(!1),[c,d]=(0,$.useState)(""),[u,h]=(0,$.useState)(!1),f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=(0,$.useRef)(0);(0,$.useLayoutEffect)(()=>{let e=f.current,r=p.current;if(e&&r){var s;u||(m.current=e.clientWidth),h((s={textWidth:r.offsetWidth,narrowFieldWidth:m.current,wide:u}).narrowFieldWidth<=0?s.wide:s.textWidth>s.narrowFieldWidth)}},[o,c,u]);let g=s??RP,x=[RP,...r??e];if(i)return(0,z.jsxs)("span",{className:(0,eb.cn)(RO,"text-muted-foreground cursor-default"),title:`${g} — fixed while the agent is running, changeable once the turn ends`,children:[(0,z.jsx)(RF,{candidates:x,className:"max-w-40",children:g}),(0,z.jsx)(n6,{className:"h-3 w-3"})]});let v=c.trim(),y=(a=c.trim()).length>0&&!e.includes(a),b=e=>{n(e),d(""),l(!1)};return(0,z.jsxs)(fJ,{open:o,onOpenChange:l,children:[(0,z.jsx)(fZ,{asChild:!0,children:(0,z.jsxs)("button",{className:(0,eb.cn)(RO,"transition-colors hover:bg-muted"),title:g,children:[(0,z.jsx)(RF,{candidates:x,className:"max-w-40",children:g}),(0,z.jsx)(n6,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,z.jsxs)(fQ,{className:u?"w-56":"w-[var(--radix-popover-trigger-width)]",children:[(0,z.jsx)("span",{ref:p,"aria-hidden":!0,className:"pointer-events-none invisible absolute whitespace-pre text-sm",children:c}),(0,z.jsxs)(p_,{shouldFilter:!0,children:[(0,z.jsx)(pj,{ref:f,className:"min-w-0",value:c,onValueChange:d}),(0,z.jsxs)(pk,{children:[(0,z.jsx)(pC,{children:"No match."}),(0,z.jsxs)(pN,{children:[(0,z.jsxs)(pE,{value:RP,onSelect:()=>b(null),className:"text-xs",children:[RP,(0,z.jsx)(cb,{delayDuration:200,children:(0,z.jsxs)(cw,{children:[(0,z.jsx)(c_,{asChild:!0,children:(0,z.jsx)("span",{onClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),className:"ml-auto flex cursor-help items-center text-muted-foreground",children:(0,z.jsx)(hv,{"aria-hidden":!0,className:"size-3"})})}),(0,z.jsx)(cS,{side:"right",className:"max-w-56",children:RL})]})}),(0,z.jsx)("span",{className:"sr-only",children:RL})]}),e.map(e=>(0,z.jsx)(pE,{value:e,onSelect:()=>b(e),className:"text-xs",children:e},e))]}),y&&(0,z.jsx)(pN,{heading:"Custom",children:(0,z.jsx)(pE,{value:v,onSelect:()=>b(v),className:"text-xs [&>span]:truncate",title:v,children:(0,z.jsxs)("span",{children:['Use "',v,'"']})})})]})]})]})]})}let Rz=(0,e_.default)("settings-2",[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]),R$=new Set(["workspace","tasks","schedules","remote-servers","settings","project-info","project-chat"]),RW="tasks";function RH(e){return e.length>0&&e.trim()===e&&!/[\u0000-\u001f\u007f/\\]/.test(e)}function RU(){let e=window.location.pathname,r=new URLSearchParams(window.location.search),s=r.get("project");if(s){let e=r.get("tab");return{projectId:s,tab:e&&R$.has(e)?e:RW,branch:r.get("branch"),threadId:null}}let n=e.split("/").filter(Boolean);if(1===n.length&&R$.has(n[0])){let e=n[0];if("remote-servers"===e||"settings"===e)return{projectId:null,tab:e,branch:null,threadId:null}}let i=null,a=RW,o=null;if("p"===n[0]&&n[1]){i=n[1];let e=n[2];if("chat"===e&&4===n.length&&n[3])try{let e=decodeURIComponent(n[3]);RH(e)?(o=e,a="project-chat"):a="project-info"}catch{a="project-info",o=null}else"chat"===e?a="project-info":e&&R$.has(e)&&"project-chat"!==e&&(a=e)}return{projectId:i,tab:a,branch:r.get("branch"),threadId:o}}function Rq(e){let{projectId:r,tab:s,branch:n,threadId:i}=e;if("remote-servers"===s||"settings"===s)return`/${s}`;if(!r)return"/";if("project-chat"===s)return i&&RH(i)?`/p/${r}/chat/${encodeURIComponent(i)}`:`/p/${r}/project-info`;let a=`/p/${r}/${s??RW}`;return n&&(a+=`?branch=${encodeURIComponent(n)}`),a}function RK({granted:e,onToggle:r,sourceRemoteId:s,disabled:n}){let[i,a]=(0,$.useState)(null),[o,l]=(0,$.useState)(!1),c=(0,$.useCallback)(()=>{l(!1),ry.api.getRemoteServers().then(e=>a([...e].sort((e,r)=>Number("online"===r.status)-Number("online"===e.status)))).catch(()=>l(!0))},[]),d=(i??[]).filter(e=>"off"!==e.cross_remote_access).filter(e=>e.id!==s);return(0,z.jsxs)(o8,{onOpenChange:e=>{e&&c()},children:[(0,z.jsxs)(o9,{disabled:n,children:[(0,z.jsx)(no,{className:"mr-2 size-4"}),"Remote access"]}),(0,z.jsxs)(le,{className:"w-64 p-1",children:[(0,z.jsxs)("div",{className:"px-2 pt-1.5 pb-2",children:[(0,z.jsx)("div",{className:"text-sm font-medium",children:"Remote access"}),(0,z.jsx)("div",{className:"text-xs text-muted-foreground",children:s?"Other machines this agent can reach":"Machines this agent can reach"})]}),(0,z.jsx)(o7,{}),(0,z.jsxs)("div",{className:"max-h-72 overflow-y-auto",children:[null===i&&!o&&(0,z.jsxs)("div",{className:"flex items-center gap-2 px-2 py-3 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"size-3.5 animate-spin"})," Loading machines…"]}),o&&(0,z.jsx)("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:"Could not load remote machines."}),null!==i&&!o&&0===d.length&&(0,z.jsxs)("div",{className:"flex flex-col items-center gap-2 px-4 py-5 text-center",children:[(0,z.jsx)("div",{className:"flex size-9 items-center justify-center rounded-full bg-muted",children:(0,z.jsx)(no,{className:"size-4 text-muted-foreground"})}),(0,z.jsx)("div",{className:"text-sm font-medium",children:"No machines available"}),(0,z.jsx)("div",{className:"text-xs text-muted-foreground",children:"Enable cross-remote access for another machine in Remote Servers."})]}),d.map(s=>{let n=e.some(e=>e.id===s.id),i="online"===s.status,a="exec"===s.cross_remote_access;return(0,z.jsxs)(o2,{role:"menuitemcheckbox","aria-checked":n,onSelect:e=>{e.preventDefault(),r({id:s.id,name:s.name,access:s.cross_remote_access,online:i},!n)},className:"gap-3 py-2",children:[(0,z.jsxs)("span",{className:"relative flex size-8 shrink-0 items-center justify-center rounded-md border bg-muted/40",children:[(0,z.jsx)(no,{className:"size-4"}),(0,z.jsx)("span",{className:(0,eb.cn)("absolute -right-0.5 -bottom-0.5 size-2.5 rounded-full ring-2 ring-popover",i?"bg-emerald-500":"bg-muted-foreground/50"),title:i?"Online":"Offline"})]}),(0,z.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col",children:[(0,z.jsx)("span",{className:"truncate font-medium",children:s.name}),(0,z.jsx)("span",{className:"flex min-w-0 items-center gap-1 whitespace-nowrap text-xs text-muted-foreground",children:a?(0,z.jsxs)("span",{className:"flex min-w-0 items-center gap-1 text-amber-600 dark:text-amber-400",children:[(0,z.jsx)(p9,{className:"size-3"}),(0,z.jsx)("span",{className:"truncate",children:"Run commands"})]}):(0,z.jsxs)("span",{className:"flex min-w-0 items-center gap-1",children:[(0,z.jsx)(_P,{className:"size-3"}),(0,z.jsx)("span",{className:"truncate",children:"Read only"})]})})]}),(0,z.jsx)("span",{"aria-hidden":!0,className:(0,eb.cn)("relative inline-flex h-4.5 w-8 shrink-0 items-center rounded-full transition-colors",n?"bg-emerald-500":"bg-muted-foreground/25"),children:(0,z.jsx)("span",{className:(0,eb.cn)("size-3.5 rounded-full bg-white shadow-sm transition-transform",n?"translate-x-4":"translate-x-0.5")})})]},s.id)})]}),(0,z.jsx)(o7,{}),(0,z.jsxs)(o2,{onSelect:()=>{window.history.pushState(null,"",Rq({tab:"remote-servers"})),window.dispatchEvent(new PopStateEvent("popstate"))},className:"text-muted-foreground",children:[(0,z.jsx)(Rz,{className:"size-4"}),"Manage machines…"]})]})]})}function RV({granted:e,onRevoke:r}){return 0===e.length?null:(0,z.jsx)("div",{className:"flex flex-wrap items-center gap-1.5 pl-12 pr-2 pt-1.5 pb-0.5",children:e.map(e=>(0,z.jsxs)("button",{type:"button",onClick:()=>r(e),title:`Cross-remote ${e.access} access \xb7 ${e.online?"online":"offline"}`,className:(0,eb.cn)("inline-flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium transition-colors","bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 hover:bg-emerald-500/20"),children:[(0,z.jsxs)("span",{className:"relative flex",children:[(0,z.jsx)(no,{className:"size-3"}),(0,z.jsx)("span",{className:(0,eb.cn)("absolute -right-0.5 -bottom-0.5 size-1.5 rounded-full ring-1 ring-background",e.online?"bg-emerald-500":"bg-muted-foreground/60")})]}),e.name,(0,z.jsx)(t7,{className:"size-3"})]},e.id))})}let RX="vibedeckx:remote-grant-declarations",RY=(e,r)=>e?`s:${e}`:`w:${r}`;function RG(){try{let e=window.localStorage.getItem(RX),r=e?JSON.parse(e):null;return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}catch{return{}}}function RJ(e){try{0===Object.keys(e).length?window.localStorage.removeItem(RX):window.localStorage.setItem(RX,JSON.stringify(e))}catch{}}function RZ(e){let r=RG()[e];return Array.isArray(r)?r:[]}let RQ=(0,e_.default)("clipboard-list",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);function R0({mode:e,onModeChange:r,disabled:s}){return(0,z.jsxs)("div",{className:"inline-flex items-center rounded-md border bg-muted/50 px-0.5 text-xs",children:[(0,z.jsxs)("button",{onClick:()=>r("plan"),disabled:s,className:(0,eb.cn)("inline-flex items-center gap-1 rounded-sm px-2 py-0.5 transition-colors","plan"===e?"bg-primary text-primary-foreground font-medium shadow-sm":"text-muted-foreground hover:text-foreground",s&&"opacity-50 cursor-not-allowed"),children:[(0,z.jsx)(RQ,{className:"h-3 w-3"}),"Plan"]}),(0,z.jsxs)("button",{onClick:()=>r("edit"),disabled:s,className:(0,eb.cn)("inline-flex items-center gap-1 rounded-sm px-2 py-0.5 transition-colors","edit"===e?"bg-primary text-primary-foreground font-medium shadow-sm":"text-muted-foreground hover:text-foreground",s&&"opacity-50 cursor-not-allowed"),children:[(0,z.jsx)(rx,{className:"h-3 w-3"}),"Edit"]})]})}function R1({type:e,className:r}){return(0,z.jsx)(sS,{className:(0,eb.cn)("h-3 w-3 shrink-0","codex"===e?"text-green-500":"text-violet-500",r)})}function R2(e){if(!e)return[];try{let r=window.localStorage.getItem(e);if(!r)return[];let s=JSON.parse(r);if(!Array.isArray(s))return[];return s.filter(e=>"string"==typeof e)}catch{return[]}}let R5=new Set(["preparing","waiting_reviewer","waiting_feedback","discussing","sending_feedback"]);function R3(e){if(!e)return"";try{return window.localStorage.getItem(e)??""}catch{return""}}function R4(e){let r=e.parentElement;for(;r;){let{overflowY:e}=getComputedStyle(r);if("auto"===e||"scroll"===e)return r;r=r.parentElement}return null}function R6({messages:e,contentRef:r}){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(null),c=(0,$.useRef)(null),d=(0,$.useCallback)(()=>{let s=r.current;if(!s)return;c.current||(c.current=R4(s));let i=c.current;if(!i)return;let o=i.scrollHeight>i.clientHeight;if(a(o),!o)return void n([]);let l=s.querySelectorAll("[data-user-msg-idx]"),d=i.getBoundingClientRect(),u=[];l.forEach(r=>{let s=parseInt(r.dataset.userMsgIdx,10),n=e[s];if(!n)return;let a=(r.getBoundingClientRect().top-d.top+i.scrollTop)/i.scrollHeight;u.push({index:s,position:Math.max(0,Math.min(1,a)),preview:function(e){if("user"!==e.type)return"";let r=e.content,s="string"==typeof r?r:r.filter(e=>"text"===e.type).map(e=>e.text).join(" "),n="string"!=typeof r&&r.some(e=>"image"===e.type),i=s.replace(DF,"").trim().split("\n")[0]??"";return(i.length>80?i.slice(0,77)+"...":i)||(n?"(Image)":"")}(n)})}),n(u)},[e,r]);(0,$.useEffect)(()=>{let e=r.current;if(!e){c.current=null,n([]),a(!1);return}let s=R4(e);if(!s)return;c.current=s,d();let i=new ResizeObserver(d);return i.observe(s),i.observe(e),()=>{i.disconnect()}},[e,d,r]);let u=(0,$.useCallback)(e=>{let s=r.current;if(!s)return;let n=s.querySelector(`[data-user-msg-idx="${e}"]`);n&&n.scrollIntoView({block:"start",behavior:"smooth"})},[r]);return i&&0!==s.length?(0,z.jsx)("div",{className:"absolute right-0 top-0 bottom-0 w-6 z-20 pointer-events-none",children:s.map(e=>(0,z.jsxs)("div",{className:"absolute right-0.5 -translate-y-1/2 pointer-events-auto",style:{top:`${100*e.position}%`},children:[(0,z.jsx)("div",{className:"w-3 h-[3px] rounded-sm bg-primary/50 hover:bg-primary cursor-pointer transition-colors",onClick:()=>u(e.index),onMouseEnter:()=>l(e.index),onMouseLeave:()=>l(null)}),o===e.index&&e.preview&&(0,z.jsxs)("div",{className:"absolute right-full mr-2 top-1/2 -translate-y-1/2 max-w-64 px-2.5 py-1.5 bg-popover border border-border rounded-md shadow-md text-xs text-popover-foreground whitespace-nowrap overflow-hidden text-ellipsis pointer-events-none",children:[e.preview,(0,z.jsx)("div",{className:"absolute top-1/2 -translate-y-1/2 -right-1 w-2 h-2 bg-popover border-r border-t border-border rotate-45"})]})]},e.index))}):null}function R7(e,r){return`${e}:${r??""}`}function R8({projectId:e,branch:r,currentSessionId:s,refreshKey:n,pendingTitleSessionId:i,aiTitleOverride:a,onSwitch:o,onDelete:l}){let[c,d]=(0,$.useState)([]),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(""),[m,g]=(0,$.useState)(!1),[x,v]=(0,$.useState)(null),[y,b]=(0,$.useState)(null),[w,_]=(0,$.useState)(0),S=(0,$.useCallback)(()=>_(e=>e+1),[]),[j,k]=(0,$.useState)(null),C=R7(e,r);(0,$.useEffect)(()=>{let s=!1;return(0,ry.listBranchSessions)(e,r).then(n=>{s||(d(n.sessions),k(R7(e,r)))}).catch(n=>{s||(console.error("[SessionHistoryDropdown] refresh failed:",n),k(R7(e,r)))}),()=>{s=!0}},[e,r,n,w]);let N=(0,$.useRef)(null);(0,$.useEffect)(()=>{if(!s||j!==C)return;if(c.some(e=>e.id===s)){N.current=null;return}if(N.current===s)return;N.current=s;let n=!1;return(0,ry.listBranchSessions)(e,r).then(i=>{if(n)return;d(i.sessions),k(R7(e,r));let o=i.sessions.find(e=>e.id===s),l=!!o&&(a?.sessionId===o.id||!!(o.title&&o.title.trim().length>0));o&&!l&&b(s)}).catch(e=>{n||console.error("[SessionHistoryDropdown] missing-session refresh failed:",e)}),()=>{n=!0}},[s,c,e,r,C,j,a]),(0,$.useEffect)(()=>{if(!y)return;let e=setTimeout(()=>{b(e=>e===y?null:e)},3e4);return()=>clearTimeout(e)},[y]),(0,$.useEffect)(()=>{if(!y)return;let e=setTimeout(()=>{b(e=>e===y?null:e)},3e4);return()=>clearTimeout(e)},[y]);let E=async(e,r)=>{let s=r.trim().length>0?r.trim():null;try{await (0,ry.renameSession)(e,s),d(r=>r.map(r=>r.id===e?{...r,title:s}:r)),h(null),gS.toast.success("Renamed")}catch(e){gS.toast.error("Rename failed"),console.error(e)}},D=async(e,r)=>{let s=null==r,n=s?Date.now():null;d(r=>r.map(r=>r.id===e?{...r,favorited_at:n}:r));try{await (0,ry.setSessionFavorited)(e,s)}catch(n){d(s=>s.map(s=>s.id===e?{...s,favorited_at:r}:s)),gS.toast.error(s?"Favorite failed":"Unfavorite failed"),console.error(n)}},R=async e=>{try{await (0,ry.deleteSession)(e);let r=c.filter(r=>r.id!==e);d(r),l?.(e,r),gS.toast.success("Deleted")}catch(e){gS.toast.error("Delete failed"),console.error(e)}},T=e=>a&&a.sessionId===e.id?a.title:e.title&&e.title.trim().length>0?e.title:e.updated_at?new Date(e.updated_at).toLocaleString():new Date(e.created_at).toLocaleString(),A=e=>{let r;return a?.sessionId!==e.id&&(!e.title||!(e.title.trim().length>0))&&(r=e.id,null!==i&&i===r||y===e.id)},I=c.find(e=>e.id===s),M=null!==s&&(!I||A(I)),F=I?T(I):null===s?"New Session":"History",P=M?"Generating title…":F;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(oQ,{open:m,onOpenChange:e=>{g(e),e&&S()},children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsxs)(W.Button,{variant:"ghost",size:"sm",className:"h-7 text-xs gap-1 w-[200px] justify-start",title:P,children:[M?(0,z.jsx)("span",{className:"block h-3 flex-1 rounded-sm bg-accent animate-pulse",role:"status","aria-label":"Generating title"}):(0,z.jsx)("span",{className:"truncate flex-1 text-left",children:F}),(0,z.jsx)(n6,{className:"h-3 w-3 flex-shrink-0"})]})}),(0,z.jsxs)(o1,{align:"start",className:"w-80 max-h-96 overflow-y-auto",children:[0===c.length&&(0,z.jsx)("div",{className:"px-2 py-3 text-xs text-muted-foreground",children:"No history yet."}),c.map(e=>{let r=e.id===s,n=u===e.id;return(0,z.jsxs)(o2,{onSelect:s=>{n?s.preventDefault():r||o(e.id)},onPointerMove:null!==u?e=>e.preventDefault():void 0,className:`flex items-center gap-2 group ${r?"bg-accent text-accent-foreground":""}`,children:[(0,z.jsx)("div",{className:"flex-1 min-w-0",children:n?(0,z.jsxs)("div",{className:"flex items-center gap-1",children:[(0,z.jsx)(rl,{value:f,onChange:e=>p(e.target.value),onKeyDown:r=>{r.stopPropagation(),"Enter"===r.key&&E(e.id,f),"Escape"===r.key&&h(null)},autoFocus:!0,className:"h-6 text-xs"}),(0,z.jsx)("button",{type:"button","aria-label":"Save rename",onClick:r=>{r.stopPropagation(),E(e.id,f)},children:(0,z.jsx)(rp.Check,{className:"h-3 w-3"})}),(0,z.jsx)("button",{type:"button","aria-label":"Cancel rename",onClick:e=>{e.stopPropagation(),h(null)},children:(0,z.jsx)(t7,{className:"h-3 w-3"})})]}):A(e)?(0,z.jsx)("div",{className:"py-0.5",title:"Generating title…",children:(0,z.jsx)("span",{className:"block h-3 w-40 rounded-sm bg-accent animate-pulse",role:"status","aria-label":"Generating title"})}):(0,z.jsx)("div",{className:"truncate text-xs",title:`${e.updated_at?new Date(e.updated_at).toLocaleString():new Date(e.created_at).toLocaleString()} • ${e.entry_count??0} messages • status: ${e.status} • model: ${e.model??"Default"}`,children:T(e)})}),!n&&(0,z.jsxs)("div",{className:"flex items-center gap-1",children:[(0,z.jsxs)("div",{className:"opacity-0 group-hover:opacity-100 flex items-center gap-1",children:[(0,z.jsx)("button",{type:"button","aria-label":"Rename conversation",onClick:r=>{r.stopPropagation(),h(e.id),p(e.title??"")},className:"p-1 hover:bg-muted rounded",children:(0,z.jsx)(rx,{className:"h-3 w-3"})}),(0,z.jsx)("button",{type:"button","aria-label":"Delete conversation",onClick:r=>{r.stopPropagation(),g(!1),v(e)},className:"p-1 hover:bg-muted rounded text-destructive",children:(0,z.jsx)(rd,{className:"h-3 w-3"})})]}),(0,z.jsx)("button",{type:"button","aria-label":null!=e.favorited_at?"Unfavorite conversation":"Favorite conversation",title:null!=e.favorited_at?"Unfavorite":"Favorite",onClick:r=>{r.stopPropagation(),D(e.id,e.favorited_at??null)},className:`p-1 hover:bg-muted rounded ${null!=e.favorited_at?"opacity-100 text-yellow-500":"opacity-0 group-hover:opacity-100 text-muted-foreground"}`,children:(0,z.jsx)(nt,{className:`h-3 w-3 ${null!=e.favorited_at?"fill-current":""}`})})]})]},e.id)}),c.length>0&&(0,z.jsx)(o7,{}),(0,z.jsx)(o2,{onSelect:()=>S(),className:"text-xs text-muted-foreground",children:"Refresh"})]})]}),(0,z.jsx)(lL,{open:null!==x,onOpenChange:e=>{e||v(null)},children:(0,z.jsxs)(lz,{children:[(0,z.jsxs)(l$,{children:[(0,z.jsx)(lH,{children:"Delete conversation?"}),(0,z.jsx)(lU,{children:x?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"font-medium text-foreground",children:T(x)})," ","and its message history will be permanently deleted. This cannot be undone."]}):null})]}),(0,z.jsxs)(lW,{children:[(0,z.jsx)(lK,{children:"Cancel"}),(0,z.jsx)(lq,{className:(0,eb.cn)((0,W.buttonVariants)({variant:"destructive"}),"border-transparent"),onClick:()=>{x&&R(x.id),v(null)},children:"Delete"})]})]})})]})}let R9=[];function Te(e,r={}){R9.push({t:Math.round(performance.now()),ev:e,...r}),R9.length>200&&R9.shift()}function Tt({messageCount:e,turnInFlight:r,sessionId:s}){let{scrollToBottom:n,scrollRef:i,contentRef:a,state:o}=cB(),{index:l}=Cm(),c=l?.version??null,d=(0,$.useRef)({turnInFlight:r,settleDeadline:0,settleHardCap:0,prevScrollHeight:0,prevClientHeight:0});d.current.turnInFlight=r;let u=()=>{let e=performance.now();d.current.settleDeadline=e+600,d.current.settleHardCap=e+8e3},h=(0,$.useRef)(!0),f=(0,$.useRef)(c),p=(0,$.useRef)(s);return(0,$.useLayoutEffect)(()=>{let r=s!==p.current,a=h.current&&e>0;if(p.current=s,h.current=0===e,!a&&!(r&&e>0))return;u(),Te(a?"fill":"session-switch",{sessionId:s,messageCount:e});let o=i.current;o&&(o.scrollTop=o.scrollHeight),n({animation:"instant"})},[e,s,n,i]),(0,$.useLayoutEffect)(()=>{c!==f.current&&(f.current=c,Te("index-version",{version:c,messageCount:e}),e>0&&u())},[c,e]),(0,$.useEffect)(()=>{let e=i.current,r=a.current;if(!e||!r||"undefined"==typeof ResizeObserver)return;d.current.prevScrollHeight=e.scrollHeight,d.current.prevClientHeight=e.clientHeight;let s=null,n=e.scrollTop,l=()=>{let i=e.scrollTop;for(let e of(Math.abs(i-n)>40&&Te("scroll-jump",{from:Math.round(n),to:Math.round(i)}),n=i,s=null,r.querySelectorAll("[data-message-idx]")))if(e.offsetTop+e.offsetHeight>i){s={el:e,offset:e.offsetTop-i};break}};l(),e.addEventListener("scroll",l,{passive:!0});let c=r=>{r.target===e&&(o.lastScrollTop=function({lastScrollTop:e,scrollTop:r,maxScrollTop:s}){return void 0===e||e<=s?e:r>=s-1?r:s}({lastScrollTop:o.lastScrollTop,scrollTop:e.scrollTop,maxScrollTop:e.scrollHeight-e.clientHeight}))},h=e.parentElement;h?.addEventListener("scroll",c,{capture:!0,passive:!0});let f=new Map,p=new ResizeObserver(()=>{let n,i,a=d.current,o=a.prevScrollHeight,l=e.scrollHeight,c=a.prevClientHeight,h=e.clientHeight;a.prevScrollHeight=l,a.prevClientHeight=h;let p=Math.abs(l-o)>1;if(Math.abs(h-c)>1&&!p){let r=function({scrollTop:e,scrollHeight:r,prevClientHeight:s}){return e+s>=r-6}({scrollTop:e.scrollTop,scrollHeight:l,prevClientHeight:c});r&&(e.scrollTop=l),Te("viewport-resize",{prevClient:c,client:h,scrollTop:Math.round(e.scrollTop),pinned:r});return}if(!p)return;let m=(n=d.current,(i=performance.now())<n.settleDeadline&&i<n.settleHardCap);m&&u();let g=e.scrollTop+c>=o-6,x=function({settling:e,turnInFlight:r,wasAtBottom:s}){return!!s&&(e||!r)}({settling:m,turnInFlight:a.turnInFlight,wasAtBottom:g});x?e.scrollTop=l:!g&&m&&s?.el.isConnected&&(e.scrollTop=s.el.offsetTop-s.offset);let v=l-e.clientHeight-e.scrollTop;Te("resize",{prev:o,next:l,clientH:e.clientHeight,scrollTop:Math.round(e.scrollTop),settling:m,turnInFlight:a.turnInFlight,wasAtBottom:g,action:x?"hold-bottom":"none",distAfter:Math.round(v),grew:(()=>{let e=[];for(let s of r.querySelectorAll("[data-message-idx]")){let r=s.getAttribute("data-message-idx")??"?",n=s.offsetHeight,i=f.get(r);void 0!==i&&Math.abs(i-n)>2&&e.push({idx:r,from:i,to:n}),f.set(r,n)}return e.sort((e,r)=>Math.abs(r.to-r.from)-Math.abs(e.to-e.from)),e.slice(0,4)})()}),g&&v>50&&!(a.turnInFlight&&!m)&&console.warn("[vdx-scroll] displaced while pinned — recent timeline:",R9.slice(-30))});return p.observe(r),p.observe(e),()=>{p.disconnect(),e.removeEventListener("scroll",l),h?.removeEventListener("scroll",c,{capture:!0})}},[i,a,o]),null}window.__vdxScrollDiag={buf:R9,dump:()=>console.table(R9)};let Tr=(0,e_.default)("quote",[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"rib7q0"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"1ymkrd"}]]);function Ts(e,r){let s=e;for(;s&&s!==r;){if(s.nodeType===Node.ELEMENT_NODE){let e=s.getAttribute("data-message-idx");if(null!==e)return e}s=s.parentNode}return null}function Tn({containerRef:e,onQuote:r}){let[s,n]=(0,$.useState)(null);if((0,$.useEffect)(()=>{function r(){let r=e.current;if(!r)return void n(null);let s=window.getSelection();if(!s||s.isCollapsed||0===s.rangeCount)return void n(null);let i=s.toString();if(!i.trim())return void n(null);let{anchorNode:a,focusNode:o}=s;if(!a||!o||!r.contains(a)||!r.contains(o))return void n(null);let l=Ts(a,r),c=Ts(o,r);if(null===l||null===c||l!==c)return void n(null);let d=s.getRangeAt(0).getBoundingClientRect();0===d.width&&0===d.height?n(null):n({text:i,rect:{top:d.top,bottom:d.bottom,left:d.left,width:d.width}})}function s(){let e=window.getSelection();e&&!e.isCollapsed&&e.toString().trim()||n(null)}return document.addEventListener("mouseup",r),document.addEventListener("keyup",r),document.addEventListener("touchend",r),document.addEventListener("selectionchange",s),window.addEventListener("scroll",r,!0),window.addEventListener("resize",r),()=>{document.removeEventListener("mouseup",r),document.removeEventListener("keyup",r),document.removeEventListener("touchend",r),document.removeEventListener("selectionchange",s),window.removeEventListener("scroll",r,!0),window.removeEventListener("resize",r)}},[e]),!s||"undefined"==typeof document)return null;let i=s.rect.top-8-30<8?s.rect.bottom+8:s.rect.top-8-30,a=s.rect.left+s.rect.width/2,o=Math.max(8,Math.min(window.innerWidth-8,a));return(0,ee.createPortal)((0,z.jsxs)("button",{type:"button",onMouseDown:e=>{e.preventDefault(),r(s.text),window.getSelection()?.removeAllRanges(),n(null)},style:{position:"fixed",top:i,left:o,transform:"translateX(-50%)",zIndex:50},className:"inline-flex items-center gap-1.5 rounded-md border border-border bg-popover px-3 py-1.5 text-xs font-medium text-popover-foreground shadow-2xl hover:bg-accent",children:[(0,z.jsx)(Tr,{className:"h-3 w-3"}),"Quote"]}),document.body)}let Ti=(0,e_.default)("search-check",[["path",{d:"m8 11 2 2 4-4",key:"1sed1v"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);function Ta(e){let r=Math.round(Number(e));return Number.isFinite(r)?Math.min(ry.REVIEW_LOOP_MAX_ROUNDS,Math.max(1,r)):ry.REVIEW_LOOP_DEFAULT_ROUNDS}let To=()=>()=>{},Tl=[{type:"claude-code",displayName:"Claude Code",available:!0},{type:"codex",displayName:"Codex",available:!0}];function Tc({tone:e,children:r}){return(0,z.jsx)("span",{className:(0,eb.cn)("rounded-full border px-1.5 py-px font-mono text-[9.5px] leading-[1.5] font-medium","rec"===e?"border-primary/25 bg-accent text-accent-foreground":"border-amber-500/35 bg-amber-500/10 text-amber-700 dark:text-amber-300"),children:r})}function Td({selected:e,title:r,meta:s,trailing:n,onSelect:i}){return(0,z.jsxs)("button",{type:"button",role:"radio","aria-checked":e,onClick:i,className:(0,eb.cn)("flex min-w-0 items-start gap-2.5 rounded-lg border px-2.5 py-2 text-left transition-colors",e?"border-primary bg-accent ring-[3px] ring-accent":"bg-card opacity-75 hover:bg-muted hover:opacity-100"),children:[(0,z.jsx)("span",{className:(0,eb.cn)("mt-[3px] grid size-3.5 shrink-0 place-items-center rounded-full border",e?"border-primary bg-primary":"border-input bg-card"),children:e&&(0,z.jsx)("span",{className:"size-[5px] rounded-full bg-primary-foreground"})}),(0,z.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,z.jsxs)("span",{className:"flex min-w-0 items-center gap-2 text-[12.5px] font-medium",children:[(0,z.jsx)("span",{className:"flex shrink-0 flex-wrap items-center gap-2",children:r}),n&&(0,z.jsx)("span",{className:"ml-auto flex min-w-0 items-center gap-1.5 font-mono text-[10.5px] font-normal text-muted-foreground",children:n})]}),s&&(0,z.jsx)("span",{className:"mt-0.5 flex flex-wrap items-center gap-2 font-mono text-[10.5px] text-muted-foreground",children:s})]})]})}function Tu({children:e,note:r}){return(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)("span",{className:"text-[10px] font-semibold tracking-[0.07em] text-muted-foreground/80 uppercase",children:e}),(0,z.jsx)("span",{className:"flex-1"}),r&&(0,z.jsx)("span",{className:"text-[10.5px] text-muted-foreground/80",children:r})]})}function Th({projectId:e,branch:r,sessionId:s,currentAgentType:n,providers:i,shortcutEnabled:a=!1,onStarted:o}){let l=(0,$.useSyncExternalStore)(To,fb,()=>!1),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(""),[f,p]=(0,$.useState)("claude-code"),[m,g]=(0,$.useState)("this_turn"),[x,v]=(0,$.useState)("briefed"),[y,b]=(0,$.useState)(!1),[w,_]=(0,$.useState)(String(ry.REVIEW_LOOP_DEFAULT_ROUNDS)),[S,j]=(0,$.useState)(null),[k,C]=(0,$.useState)(null),[N,E]=(0,$.useState)(!1),[D,R]=(0,$.useState)(null),[T,A]=(0,$.useState)(!1),I=(0,$.useRef)(null),M=(0,$.useRef)(null),F=(0,$.useSyncExternalStore)(Rp,()=>Rm(e,r,s),()=>void 0),P=!1===F,L=s?`${e}\u0000${s}`:null,O=k?.key===L?k:null,B=S?.key===L?S.mode:null,H=O?.candidate??null,U=O?.notice??null,q=null!==O||P,K=c&&null!==L&&!q,V=i?.length?i:Tl;if((0,$.useEffect)(()=>{if(c){var e;let r;p((e=n??null,r=V.filter(e=>e.available),r.find(r=>r.type!==e)?.type??r[0]?.type??"claude-code")),g("this_turn"),v("briefed")}},[c]),(0,$.useEffect)(()=>{if(!c||!s)return;let n=`${e}\u0000${s}`;if(P){M.current=null;return}let i=!1,a=ry.api.getReviewerCandidate(e,s);return M.current={projectId:e,sessionId:s,result:a},a.then(a=>{if(i)return;let o=!!(a?.available&&a.sessionId),l=null!==a||!0===Rm(e,r,s);C({key:n,candidate:a,notice:!o&&l?"The last reviewer is no longer available — a new session will be created.":null})}).catch(()=>{i||C({key:n,candidate:null,notice:"Could not load the last reviewer — a new session will be created."})}),()=>{i=!0}},[c,e,r,s,P]),(0,$.useEffect)(()=>{if(!c){I.current=null;return}if(!s)return;let r=I.current;if(r&&r.projectId===e&&r.sessionId===s)return;A(!1);let n=ry.api.generateReviewIntentBrief(e,s).then(e=>({reached:!0,brief:e})).catch(()=>({reached:!1,brief:null}));I.current={projectId:e,sessionId:s,result:n},n.then(()=>{I.current?.result===n&&A(!0)})},[c,e,s]),(0,$.useEffect)(()=>{if(!s||!a)return;let e=e=>{f_(e)&&e.code===fw&&(e.preventDefault(),d(!0))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[s,a]),!s)return null;let X=e=>{d(e),e||(j(null),C(null))},Y=async()=>{E(!0),R(null);try{let n=H;if("reuse"===Z&&!q&&L){let r=M.current;n=r?.projectId===e&&r?.sessionId===s?await r.result.catch(()=>null):null,C({key:L,candidate:n,notice:null})}if("reuse"===Z&&!(n?.available&&n.sessionId)){L&&C({key:L,candidate:n,notice:"The last reviewer is no longer available — a new session will be created."}),j(L?{key:L,mode:"new"}:null);return}let i="reuse"===Z&&n?.sessionId?{reviewerSessionId:n.sessionId}:{reviewerAgentType:f},a="blind"===x&&"reviewerAgentType"in i,l=I.current,c=!a&&"reviewerAgentType"in i&&l?.projectId===e&&l?.sessionId===s?l:null,d=c&&T?await c.result:null,p=d?.reached?{intentBrief:d.brief??""}:{},g=await ry.api.createWorkflowRun({projectId:e,branch:r,sourceSessionId:s,reviewFocus:u.trim()||void 0,reviewSpan:m,...a?{reviewContextMode:"blind"}:{},...y?{loop:{maxRounds:Ta(w)}}:{},...i,...p});y&&!g.loop_id&&gS.toast.info("This machine's worker doesn't support review loops yet — started a single-pass review."),X(!1),h(""),o?.(g)}catch(r){R(r instanceof Error?r.message:String(r)),ry.api.getReviewerCandidate(e,s).then(r=>{let n=!r?.available||!r.sessionId;C({key:`${e}\u0000${s}`,candidate:r,notice:n?"The last reviewer is no longer available — a new session will be created.":null}),n&&j(L?{key:L,mode:"new"}:null)}).catch(()=>void 0)}finally{E(!1)}},G=!!(H?.available&&H.sessionId),J=q?G:!0===F,Z=J?B??"reuse":"new",Q="reuse"===Z,ee=Q?"briefed":x,et=e=>V.find(r=>r.type===e)?.displayName??e??"—",er=N||K&&void 0===F,es=N?{Icon:hv,text:"Setup continues in the background"}:Q?{Icon:hv,text:"Reuses context — no re-distillation"}:"blind"===x?{Icon:hv,text:y?"Blind applies to round 1 — later rounds see the author's replies":"Blind review — no conversation context is sent"}:T?{Icon:lY.Clock,text:"Intent summary ready"}:{Icon:lY.Clock,text:"Intent summary finishes in the background"};return(0,z.jsxs)(t8,{open:c,onOpenChange:X,children:[(0,z.jsx)(t9,{asChild:!0,children:(0,z.jsx)(W.Button,{variant:"ghost",size:"sm",title:`让另一个 agent review 这个 session 的最新成果 (${fj(l,fw)})`,children:(0,z.jsx)(Ti,{className:"h-4 w-4"})})}),(0,z.jsxs)(rs,{showCloseButton:!1,className:"bg-card w-[calc(100%-2rem)] min-w-0 gap-0 overflow-hidden p-0 sm:w-full sm:max-w-md",onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&!er&&(e.preventDefault(),Y())},children:[(0,z.jsxs)("div",{className:"flex items-start gap-3 border-b bg-secondary px-4 py-3.5",children:[(0,z.jsx)("span",{className:"grid size-7 shrink-0 place-items-center rounded-lg border border-primary/20 bg-accent text-accent-foreground",children:(0,z.jsx)(Ti,{className:"size-[15px]"})}),(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)(ra,{className:"text-[14.5px] font-semibold tracking-tight",children:"Start Review"}),(0,z.jsx)(ro,{className:"mt-0.5 max-w-[40ch] text-[11.5px] leading-snug",children:"Another agent reviews this session’s latest work; you confirm the feedback before it returns here."})]}),(0,z.jsxs)(rt,{className:"ml-auto grid size-6 shrink-0 place-items-center rounded-md border border-transparent text-muted-foreground/70 transition-colors hover:border-border hover:bg-muted hover:text-foreground",children:[(0,z.jsx)(t7,{className:"size-3.5"}),(0,z.jsx)("span",{className:"sr-only",children:"Close"})]})]}),(0,z.jsxs)("div",{className:"min-w-0 flex flex-col gap-3.5 px-4 pt-3.5 pb-1",children:[U&&(0,z.jsxs)("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-2.5 py-2 text-[11.5px] text-amber-700 dark:text-amber-300",children:[(0,z.jsx)(s7,{className:"mt-px size-3.5 shrink-0"}),(0,z.jsx)("span",{children:U})]}),(0,z.jsxs)("div",{className:"min-w-0 flex flex-col gap-1.5",children:[(0,z.jsx)(Tu,{note:K?"Checking last reviewer…":J?"Last reviewer still available":void 0,children:"Reviewer"}),(0,z.jsxs)("div",{className:"grid gap-2",role:"radiogroup","aria-label":"Reviewer",children:[J&&(0,z.jsx)(Td,{selected:Q,onSelect:()=>L&&j({key:L,mode:"reuse"}),title:"Continue last reviewer",trailing:q&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"shrink-0",children:et(H?.agentType)}),"number"==typeof H?.lastActiveAt&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("span",{className:"shrink-0 text-muted-foreground/60",children:"·"}),(0,z.jsx)("span",{className:"shrink-0",children:function(e){let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return"just now";let s=Math.round(r/60);if(s<60)return`${s}m ago`;let n=Math.round(s/60);return n<24?`${n}h ago`:`${Math.round(n/24)}d ago`}(H.lastActiveAt)})]})]}),meta:q?(0,z.jsx)("span",{className:"min-w-0 truncate",children:H?.title??"Review session"}):(0,z.jsx)("span",{className:"text-muted-foreground/60",children:"Loading details…"})}),(0,z.jsx)(Td,{selected:!Q,onSelect:()=>L&&j({key:L,mode:"new"}),title:(0,z.jsxs)(z.Fragment,{children:["New reviewer session",U&&(0,z.jsx)(Tc,{tone:"warn",children:"Only option"})]}),meta:J?"Starts fresh, without the last context":"Independent second opinion, from zero context"})]}),(0,z.jsxs)("div",{className:"mt-0.5 min-w-0 flex flex-col gap-2",children:[(0,z.jsxs)("div",{className:"min-w-0 flex items-center gap-2.5",children:[(0,z.jsx)("span",{className:"w-[92px] shrink-0 text-[11.5px] text-muted-foreground",children:"Agent"}),Q?(0,z.jsxs)("span",{className:"flex h-8 flex-1 items-center gap-2 rounded-md border bg-secondary px-2.5 text-xs text-muted-foreground",children:[(0,z.jsx)("span",{className:"truncate",children:q?et(H?.agentType):"Loading…"}),(0,z.jsx)("span",{className:"flex-1"}),(0,z.jsx)("span",{className:"font-mono text-[10px] text-muted-foreground/70",children:"same as last reviewer"}),(0,z.jsx)(gv,{className:"size-3 shrink-0"})]}):(0,z.jsxs)(fd,{value:f,onValueChange:e=>p(e),children:[(0,z.jsxs)(fh,{size:"sm",className:"min-w-0 flex-1 text-xs",children:[(0,z.jsx)(fu,{}),(0,z.jsx)("span",{className:"ml-auto font-mono text-[10px] text-muted-foreground/70",children:f===n?"same as current agent":"differs from current agent"})]}),(0,z.jsx)(ff,{children:V.map(e=>(0,z.jsxs)(fp,{value:e.type,disabled:!e.available,children:[e.displayName,e.type===n?" (current agent)":""]},e.type))})]})]}),(0,z.jsxs)("div",{className:"min-w-0 flex items-center gap-2.5",children:[(0,z.jsx)("span",{className:"w-[92px] shrink-0 text-[11.5px] text-muted-foreground",children:"Scope"}),(0,z.jsx)("div",{className:"min-w-0 flex h-8 flex-1 items-center gap-0.5 rounded-lg border bg-secondary p-0.5",children:[["this_turn","This turn only"],["session_start","Whole session"]].map(([e,r])=>(0,z.jsx)("button",{type:"button","aria-pressed":m===e,onClick:()=>g(e),className:(0,eb.cn)("h-full flex-1 rounded-md px-2 text-[11.5px] whitespace-nowrap transition-colors",m===e?"border bg-card font-medium text-foreground shadow-sm":"border border-transparent text-muted-foreground hover:text-foreground"),children:r},e))})]}),(0,z.jsxs)("div",{className:"min-w-0 flex items-center gap-2.5",children:[(0,z.jsx)("span",{className:"w-[92px] shrink-0 text-[11.5px] text-muted-foreground",children:"Context"}),(0,z.jsx)("div",{className:"min-w-0 flex h-8 flex-1 items-center gap-0.5 rounded-lg border bg-secondary p-0.5",children:[["briefed","With context"],["blind","Blind"]].map(([e,r])=>(0,z.jsx)("button",{type:"button",disabled:Q,"aria-pressed":ee===e,onClick:()=>v(e),className:(0,eb.cn)("h-full min-w-0 flex-1 rounded-md px-2 text-[11.5px] whitespace-nowrap transition-colors disabled:cursor-not-allowed",ee===e?"border bg-card font-medium text-foreground shadow-sm disabled:text-muted-foreground":"border border-transparent text-muted-foreground hover:text-foreground disabled:opacity-45"),children:r},e))})]}),(0,z.jsxs)("div",{className:"min-w-0 flex items-center gap-2.5",children:[(0,z.jsx)("span",{className:"w-[92px] shrink-0 text-[11.5px] text-muted-foreground",children:"Rounds"}),(0,z.jsx)("div",{className:"min-w-0 flex h-8 flex-1 items-center gap-0.5 rounded-lg border bg-secondary p-0.5",children:[[!1,"Single pass"],[!0,"Loop"]].map(([e,r])=>(0,z.jsx)("button",{type:"button","aria-pressed":y===e,onClick:()=>b(e),className:(0,eb.cn)("h-full min-w-0 flex-1 rounded-md px-2 text-[11.5px] whitespace-nowrap transition-colors",y===e?"border bg-card font-medium text-foreground shadow-sm":"border border-transparent text-muted-foreground hover:text-foreground"),children:r},r))}),(0,z.jsxs)("label",{className:(0,eb.cn)("flex shrink-0 items-center gap-1.5 text-[11.5px] text-muted-foreground",!y&&"opacity-45"),children:["up to",(0,z.jsx)("input",{type:"number",min:1,max:ry.REVIEW_LOOP_MAX_ROUNDS,"aria-label":"Maximum review rounds",disabled:!y,value:w,onChange:e=>_(e.target.value),onBlur:()=>_(String(Ta(w))),className:"h-7 w-11 rounded-md border bg-card px-1.5 text-center text-[11.5px] text-foreground outline-none disabled:cursor-not-allowed"})]})]})]})]}),(0,z.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,z.jsx)(Tu,{note:"Optional",children:"Review focus"}),(0,z.jsx)("div",{className:"focus-within:border-ring focus-within:ring-ring/40 flex h-[34px] items-center overflow-hidden rounded-lg border bg-card px-3 transition-[color,box-shadow] focus-within:ring-[3px]",children:(0,z.jsx)("input",{className:"min-w-0 flex-1 bg-transparent text-[12.5px] outline-none placeholder:text-muted-foreground/70",placeholder:"What to focus on, e.g. is the lock granularity too coarse…",value:u,onChange:e=>h(e.target.value)})})]}),D&&(0,z.jsxs)("div",{className:"border-destructive/30 bg-destructive/10 text-destructive flex items-start gap-2 rounded-lg border px-2.5 py-2 text-[11.5px]",children:[(0,z.jsx)(s7,{className:"mt-px size-3.5 shrink-0"}),(0,z.jsx)("span",{className:"min-w-0",children:D})]})]}),(0,z.jsxs)("div",{className:"mt-2.5 min-w-0 flex w-full items-center gap-2.5 overflow-hidden border-t bg-secondary px-4 py-2.5",children:[(0,z.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden text-[11px] text-muted-foreground",children:[(0,z.jsx)(es.Icon,{className:"size-3 shrink-0 text-muted-foreground/70"}),(0,z.jsx)("span",{className:"truncate",children:es.text})]}),(0,z.jsx)(rt,{asChild:!0,children:(0,z.jsx)(W.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",children:"Cancel"})}),(0,z.jsx)(W.Button,{size:"sm",className:"h-7 w-28 gap-1.5 text-xs","aria-label":"Start",onClick:Y,disabled:er,children:N?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(sC,{className:"size-3 animate-spin"}),"Starting…"]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(sT,{className:"size-3"}),"Start",(0,z.jsx)("kbd",{className:"rounded border border-primary-foreground/30 bg-primary-foreground/15 px-1 font-mono text-[10px] leading-[1.4] text-primary-foreground/90",title:l?"Command+Enter":"Ctrl+Enter",children:l?"⌘⏎":"Ctrl⏎"})]})})]})]})]})}function Tf({phase:e="distilling",children:r}){return(0,z.jsxs)("div",{className:"text-center py-16",children:[(0,z.jsx)(Rl,{className:"h-6 w-6 mx-auto mb-4"}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Preparing review…"}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"starting"===e?"The reviewer is starting. This view switches to the review conversation as soon as it is ready.":"Summarizing the source conversation and briefing the reviewer. The review will start here automatically — you can leave this window in the meantime."}),r]})}function Tp({error:e,title:r="Review setup failed",children:s}){return(0,z.jsxs)("div",{className:"text-center py-16",children:[(0,z.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-destructive/10 flex items-center justify-center mb-4",children:(0,z.jsx)(s_,{className:"h-6 w-6 text-destructive/70"})}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:r}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:e??"The reviewer could not be started."}),s]})}function Tm({status:e,children:r}){let s="completed"===e?sZ:gJ;return(0,z.jsxs)("div",{className:"text-center py-16",children:[(0,z.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-muted flex items-center justify-center mb-4",children:(0,z.jsx)(s,{className:"h-6 w-6 text-muted-foreground"})}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"completed"===e?"Review completed":"cancelled"===e?"Review cancelled":"Review no longer available"}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"completed"===e?"The reviewer finished before this view could open it.":"cancelled"===e?"The review was ended before the reviewer started.":"The server no longer has this review run."}),r]})}let Tg=[137,80,78,71,13,10,26,10],Tx=[71,73,70,56],Tv=[82,73,70,70],Ty=[87,69,66,80];function Tb(e,r,s=0){if(e.length<s+r.length)return!1;for(let n=0;n<r.length;n++)if(e[s+n]!==r[n])return!1;return!0}function Tw({uploads:e,workspaceKey:r,apiRef:s}){let n=D1(),i=n.files,{track:a}=e,{clear:o,detach:l,restore:c}=n;(0,$.useEffect)(()=>(s.current={detach:l,restore:c},()=>{s.current=null}),[s,l,c]);let d=(0,$.useRef)(r);return((0,$.useEffect)(()=>{d.current!==r&&(d.current=r,o())},[r,o]),(0,$.useEffect)(()=>{a(i)},[i,a]),0===i.length)?null:(0,z.jsx)(D7,{className:"pt-3 pb-0 pl-12 pr-2",children:(0,z.jsx)(D5,{className:"p-0",children:r=>(0,z.jsx)(D2,{data:r,status:e.statusOf(r.id),onRetry:()=>e.retry(r)})})})}let T_=(0,$.createContext)(null);function TS(){let e=(0,$.useContext)(T_);if(!e)throw Error("useAgentConversation must be used within AgentConversationContext");return e}let Tj=/\[📎 paste #(\d+) \([^)]+\)\]/g;function Tk(e){return"system"===e.type||"error"===e.type}function TC(e,r){return`[📎 paste #${e} (${function(e){if(e<1024)return`${e}B`;let r=e/1024;return r<10?`${r.toFixed(1)}KB`:`${Math.round(r)}KB`}(r)})]`}let TN=(0,$.forwardRef)(function({projectId:e,branch:r,sessionId:s,navPending:n,setSessionUrlParam:i,project:a,onAgentModeChange:o,onTaskCompleted:l,onSessionStarted:c,onSessionTitleUpdated:d,onSessionSelected:u,onStatusChange:h,onNewConversation:f,onActiveSessionChange:p,onOpenSchedule:m,preparingReviews:g,onReviewStarted:x,onViewPreparingReview:v},y){var b;let w,_,S,j,[k,C]=function(e,r){let s=e&&r?`vibedeckx:agent-draft:${e}:${r}`:null,[n,i]=(0,$.useState)(()=>R3(s)),[a,o]=(0,$.useState)(s);return a!==s&&(o(s),i(R3(s))),[n,(0,$.useCallback)(e=>{i(e);if(s)try{e?window.localStorage.setItem(s,e):window.localStorage.removeItem(s)}catch{}},[s])]}(e,r),[N,E]=(0,$.useState)([]),[D,R]=(0,$.useState)(1),[T,A]=(0,$.useState)("edit"),[I,M]=(0,$.useState)(!1),[F,P]=(0,$.useState)(!1),[L,O]=(0,$.useState)(!1),B=(0,$.useRef)(null),[H,U]=(0,$.useState)("claude-code"),[q,K]=(0,$.useState)([]),[V,X]=(0,$.useState)(null),[Y,G]=(0,$.useState)(0),[J,Z]=(0,$.useState)(null),[Q,ee]=(0,$.useState)(null),et=(0,$.useRef)(null),er=(0,$.useCallback)(e=>{if("ArrowUp"!==e.key&&"ArrowDown"!==e.key||!e.shiftKey||e.ctrlKey||e.metaKey||e.altKey)return;let r=et.current;if(!r)return;let s=R4(r);if(!s)return;let n=s.getBoundingClientRect(),i=s.scrollTop,a="ArrowUp"===e.key,o=null,l=a?-1/0:1/0;r.querySelectorAll("[data-user-msg-idx]").forEach(e=>{let r=e.getBoundingClientRect().top-n.top+s.scrollTop;a?r<i-12&&r>l&&(l=r,o=e):r>i+12&&r<l&&(l=r,o=e)}),o&&(e.preventDefault(),o.scrollIntoView({block:"start",behavior:"smooth"}))},[et]),es=(0,$.useRef)(null),en=function(e,r,s){let n=r&&s?`vibedeckx:agent-input-history:${r}:${s}`:null,i=(0,$.useRef)(R2(n)),a=(0,$.useRef)(-1),o=(0,$.useRef)(""),[l,c]=(0,$.useState)(n);return l!==n&&(c(n),i.current=R2(n),a.current=-1,o.current=""),{push:(0,$.useCallback)(e=>{let r=e.trim();if(!r)return;let s=i.current;if(s.length>0&&s[s.length-1]===r){a.current=-1;return}s.push(r),s.length>50&&s.shift(),a.current=-1;if(n)try{0===s.length?window.localStorage.removeItem(n):window.localStorage.setItem(n,JSON.stringify(s))}catch{}},[n]),handleKeyDown:(0,$.useCallback)(r=>{let s=r.currentTarget,n=i.current;if(0!==n.length)if("ArrowUp"===r.key){if(0!==s.selectionStart||0!==s.selectionEnd)return;if(r.preventDefault(),-1===a.current)o.current=s.value,a.current=n.length-1;else{if(!(a.current>0))return;a.current--}e(n[a.current])}else if("ArrowDown"===r.key){if(-1===a.current)return;let i=s.value.length;if(s.selectionStart!==i||s.selectionEnd!==i)return;r.preventDefault(),a.current<n.length-1?(a.current++,e(n[a.current])):(a.current=-1,e(o.current))}else -1!==a.current&&(a.current=-1)},[e])}}(C,e,r),{remotes:ei}=g_(),ea=[];for(let e of(a?.path&&ea.push({id:"local",label:"Local",icon:hy}),ei))ea.push({id:e.remote_server_id,label:e.server_name,icon:sy(e)});let eo=a?.agent_mode??"local",el=ea.find(e=>e.id===eo)?.label??("local"===eo?"Local":eo),ec=(0,$.useRef)(null);ec.current=Nj(e,r,eo,s);let ed=(0,$.useCallback)(e=>{let r=ec.current;return null!==r&&Nk(e,r)},[]),eu=(0,$.useCallback)(e=>{let r=ec.current;return null!==r&&e.projectId===r.projectId&&e.branch===r.branch},[]),{session:eh,messages:ef,status:ep,isConnected:em,isInitialized:eg,isLoading:ex,isCachePreview:ev,error:ey,remoteStatus:ew,workflowRunUpdate:e_,backgroundTasks:eS,streamEpoch:ej,messageEntryIndices:ek,hasEarlierHistory:eC,isLoadingEarlier:eN,loadEarlierHistory:eE,sendMessage:eD,sendEnsuredMessage:eR,discardEnsuredSessionIfEmpty:eT,startConversation:eA,prepareConversation:eI,activateConversation:eM,cancelPreparedConversation:eF,uploadPaste:eP,uploadAttachment:eL,stopSession:eO,switchAgentType:eB,setModel:ez,startNewConversation:e$,ensureSession:eW,switchMode:eH,acceptPlan:eU,residentLimitPrompt:eq}=function(e,r,s,n,i){let a=i?.sessionId??null,o=i?.suspended??!1,[l,c]=(0,$.useState)(null),[d,u]=(0,$.useState)([]),[h,f]=(0,$.useState)("stopped"),[p,m]=(0,$.useState)(!1),[g,x]=(0,$.useState)(!1),[v,y]=(0,$.useState)(!1),[b,w]=(0,$.useState)(!1),[_,S]=(0,$.useState)(null),[j,k]=(0,$.useState)(null),[C,N]=(0,$.useState)(null),[E,D]=(0,$.useState)({tasks:[],turnParked:!1,parkDeadlineAt:null,canStopTasks:!1}),[R,T]=(0,$.useState)(0),A=(0,$.useRef)(null),I=(0,$.useRef)(null),M=(0,$.useRef)(null),F=(0,$.useRef)(new WeakSet),P=(0,$.useRef)(()=>{}),L=(0,$.useRef)(()=>{}),O=(0,$.useRef)(null),B=(0,$.useRef)(0),z=(0,$.useRef)({sessionId:null,entries:{},status:"stopped"}),W=(0,$.useRef)(null),[H,U]=(0,$.useState)(!1),[q,K]=(0,$.useState)(!1),V=(0,$.useRef)(null),X=(0,$.useRef)(!1),Y=(0,$.useRef)(!0),G=(0,$.useRef)(null),J=(0,$.useRef)(null),Z=(0,$.useRef)(0),Q=(0,$.useRef)(!1),ee=(0,$.useRef)(null),et=(0,$.useRef)(0),er=(0,$.useRef)(!1),es=(0,$.useRef)(!1),en=(0,$.useRef)(!1),ei=(0,$.useRef)(o),ea=(0,$.useRef)(Promise.resolve()),eo=(0,$.useRef)(i?.onTaskCompleted),el=(0,$.useRef)(i?.onSessionStarted),ec=(0,$.useRef)(i?.onTitleUpdated),ed=(0,$.useRef)(e),eu=(0,$.useRef)(r),eh=(0,$.useRef)(a),ef=(0,$.useRef)(Nj(e,r,s,a));ef.current=Nj(e,r,s,a),(0,$.useEffect)(()=>{eo.current=i?.onTaskCompleted,el.current=i?.onSessionStarted,ec.current=i?.onTitleUpdated,ed.current=e,eu.current=r,eh.current=a,V.current=l,ei.current=o}),(0,sx.useGlobalEventStream)(e=>{if("notification:created"!==e.type)return;let r=e.notification,s=r?.session_id;if(!s||"session_result_ready"!==r.kind&&"session_failed"!==r.kind)return;let n=[...NO.entries()].filter(([,e])=>e.session.id===s);0!==n.length&&NV(s).then(e=>{for(let[r,s]of n)NW(r,{session:e.session??{...s.session,status:e.status},history:e})}).catch(e=>console.warn(`[AgentSession] completion prefetch failed for ${s}:`,e))});let ep=(0,$.useCallback)(()=>{ee.current&&(clearTimeout(ee.current),ee.current=null)},[]),em=(0,$.useCallback)(e=>{ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{ee.current=null,e.readyState===WebSocket.OPEN&&(console.warn(`[AgentSession] No frames for 95000ms — assuming dead socket, forcing reconnect`),L.current(e))},95e3)},[]),eg=(0,$.useCallback)((e,r=!1)=>{M.current=e,A.current&&I.current!==e&&(console.log(`[AgentSession] Retiring WS for ${I.current}, claiming ${e}`),A.current.close(1e3,"session-switch"),A.current=null,I.current=null),Promise.race([(0,ry.getFreshToken)(r?{skipCache:!0}:void 0),new Promise(e=>setTimeout(e,5e3))]).catch(()=>void 0).then(()=>{M.current!==e?console.log(`[AgentSession] Dropping stale connect for ${e} (now ${M.current})`):P.current(e)})},[]),ex=(0,$.useCallback)(e=>{let r=()=>{let e=ed.current;if(!e)return;let r=eu.current;NO.delete(Nz(e,r,eh.current));let s=I.current;s&&NO.delete(Nz(e,r,s)),NO.delete(Nz(e,r,null))},s=()=>{let r=ed.current,s=V.current;if(!r||!s||s.id!==e)return;let n=s.status===z.current.status?s:{...s,status:z.current.status};V.current=n;let i=W.current;if(!i)return;let a=NG(z.current),o=a.at(-1)?.entryIndex??null,l=[...a].reverse().find(e=>"turn_end"===e.message.type)?.entryIndex??i.lastTurnEndEntryIndex,c={...i,status:z.current.status,latestEntryIndex:o,lastTurnEndEntryIndex:l,entries:a};W.current=c,NH(r,eu.current,eh.current,n,c)};if(A.current&&I.current!==e&&(console.log(`[AgentSession] Closing stale WS for ${I.current}, switching to ${e}`),A.current.close(1e3,"session-switch"),A.current=null,I.current=null),A.current?.readyState===WebSocket.OPEN||A.current?.readyState===WebSocket.CONNECTING)return;z.current.sessionId!==e&&(z.current={sessionId:e,entries:{},status:"running"}),X.current=!1,Q.current=!0;let n=W.current,i=new URLSearchParams;n?.lastTurnEndEntryIndex!==null&&n?.lastTurnEndEntryIndex!==void 0&&(i.set("after",String(n.lastTurnEndEntryIndex)),i.set("epoch",String(n.historyEpoch)));let a=i.size>0?`?${i}`:"",o=`/api/agent-sessions/${e}/stream${a}`;console.log("[AgentSession] Connecting to WebSocket:",o);let l=new WebSocket((0,ry.getWebSocketUrl)(o));A.current=l,I.current=e,l.onopen=()=>{A.current===l&&(console.log("[AgentSession] WebSocket connected"),m(!0),S(null),k(null),G.current=Date.now(),em(l),J.current&&clearTimeout(J.current),J.current=setTimeout(()=>{A.current===l&&(console.log("[AgentSession] Connection stable, resetting backoff counter"),B.current=0,Z.current=0)},5e3))},l.onmessage=n=>{if(A.current!==l||z.current.sessionId!==e){F.current.has(l)||(F.current.add(l),console.warn(`[AgentSession] Dropping frames from retired socket for ${e}`+(z.current.sessionId===e?"":`; buffer holds ${z.current.sessionId}`)));return}em(l);try{let a=JSON.parse(n.data);if("keepalive"in a)return;if("HistorySync"in a){(a.HistorySync.reset||W.current&&W.current.historyEpoch!==a.HistorySync.historyEpoch)&&(z.current={sessionId:e,entries:{},status:z.current.status},W.current=W.current?{...W.current,historyEpoch:a.HistorySync.historyEpoch,latestEntryIndex:null,lastTurnEndEntryIndex:null,entries:[],previousCursor:null,hasMore:!1}:null,U(!1));return}if("JsonPatch"in a){var i;let e=a.JsonPatch;if(i=z.current,z.current=Nn(i,r=>{for(let s of e){let{op:e,path:n,value:i}=s;if("/entries"===n&&"replace"===e&&i?.type==="ENTRY"&&i.content?.type==="system"&&i.content?.content==="__CLEAR_ALL__"){console.log("[JsonPatch] Received clearAll signal - clearing all entries"),r.entries={};continue}if(n.startsWith("/entries/")){let s=parseInt(n.replace("/entries/",""),10);if(isNaN(s)){console.warn(`[JsonPatch] Invalid index in path: ${n}`);continue}if(i?.type!=="ENTRY"){console.warn("[JsonPatch] Expected ENTRY type for entries path");continue}switch(e){case"add":r.entries[s]=i.content;break;case"replace":void 0!==r.entries[s]?r.entries[s]=i.content:console.warn(`[JsonPatch] Replace index out of bounds: ${s}`);break;case"remove":delete r.entries[s]}}else"/status"===n&&i?.type==="STATUS"&&(console.log("[AgentSession] /status patch →",i.content),r.status=i.content)}}),Q.current)console.log("[AgentSession] /status patch applied during replay (no setStatus), container.status =",z.current.status);else{let e=NG(z.current).map(e=>e.message);u(e),console.log("[AgentSession] setStatus(live) →",z.current.status),f(z.current.status),s()}return}if("Ready"in a){console.log(`[AgentSession] Received Ready signal for ${e} - history complete, status=${z.current.status}, tail=${NG(z.current).at(-1)?.entryIndex??"-"}`),Q.current=!1,u(NG(z.current).map(e=>e.message)),f(z.current.status),x(!0),s(),T(e=>e+1);return}if("finished"in a){console.log("[AgentSession] Received finished signal, preserving cached snapshot"),X.current=!0,s(),l.close(1e3,"finished");return}if("taskCompleted"in a){if(Q.current)return;let{duration_ms:e,cost_usd:r,input_tokens:s,output_tokens:n}=a.taskCompleted,i=[];if(null!=e){let r=(e/1e3).toFixed(1);i.push(`${r}s`)}if(null!=r)i.push(`$${r.toFixed(4)}`);else if(null!=s||null!=n){let e=(s??0)+(n??0),r=e>1e3?`${(e/1e3).toFixed(1)}K`:String(e);i.push(`${r} tokens`)}gS.toast.success("Task completed",{description:i.length>0?i.join(" · "):void 0}),eo.current?.();return}if("remoteStatus"in a)return void k(a.remoteStatus);if("processAlive"in a){let r=V.current;if(r?.id===e&&r.processAlive!==a.processAlive.alive){let e={...r,processAlive:a.processAlive.alive};V.current=e,c(e)}return}if("titleUpdated"in a)return void ec.current?.(a.titleUpdated.title,e);if("backgroundTasks"in a){let{tasks:e,turnParked:r,parkDeadlineAt:s,canStopTasks:n}=a.backgroundTasks;D({tasks:e,turnParked:r,parkDeadlineAt:s??null,canStopTasks:n??!1});return}if("workflowRunUpdated"in a&&N(a.workflowRunUpdated),"error"in a){console.error("[AgentSession] Server error:",a.error),S(a.error),"Session not found"===a.error&&(console.log("[AgentSession] Session invalid, invalidating cache, will create new session"),r(),X.current=!0,c(null),f("stopped"),x(!1),Y.current=!0);return}}catch(e){console.error("[AgentSession] Failed to parse message:",e)}},l.onclose=e=>{let s,n;if(A.current!==l)return;console.log("[AgentSession] WebSocket disconnected",e.code,e.reason),A.current=null,m(!1),ep(),J.current&&(clearTimeout(J.current),J.current=null);let i=G.current?Date.now()-G.current:0;if(G.current=null,i>0&&i<5e3){if(Z.current++,console.log(`[AgentSession] Short-lived connection (${i}ms), count: ${Z.current}, backoff attempt: ${B.current}`),Z.current>=3){if(console.log("[AgentSession] Multiple short-lived connections detected, session likely invalid - will recreate"),er.current){console.log("[AgentSession] Skipping auto-restart: last session creation failed"),S("Unable to connect to remote server. Please check the server configuration.");return}r(),c(null),S(null),B.current=0,Z.current=0,Y.current=!0;return}}else i>=5e3&&(Z.current=0);if(X.current||1e3===e.code)return;if(B.current>=10){console.log("[AgentSession] Max reconnect attempts reached"),S("Unable to connect to server. Please check if the backend is running.");return}let a=(n=(s=Math.min(3e4,1e3*Math.pow(2,B.current)))*Math.random()*.25,s+n);console.log(`[AgentSession] Reconnecting in ${Math.round(a)}ms (attempt ${B.current+1})`),B.current++,O.current=setTimeout(()=>{let e=I.current;e&&!X.current&&eg(e,!0)},a)},l.onerror=e=>{A.current===l&&console.error("[AgentSession] WebSocket error:",e)}},[eg,em,ep]);(0,$.useEffect)(()=>{P.current=ex},[ex]),(0,$.useEffect)(()=>(L.current=e=>{if(A.current!==e)return;let r=I.current;A.current=null,m(!1),J.current&&(clearTimeout(J.current),J.current=null),G.current=null;try{e.close(4e3,"silence watchdog")}catch{}r&&!X.current&&eg(r,!0)},()=>{L.current=()=>{}}),[eg]);let ev=(0,$.useCallback)(async i=>{if(!e)return null;if(es.current)return console.log("[AgentSession] startSession already in progress, skipping"),null;es.current=!0;let o=et.current;S(null),k(null),en.current||x(!1),er.current=!1;let l=N$(Nz(e,r,a));y(!0);let d=()=>{console.log(`[AgentSession] No existing session for ${e}/${r??"<null>"} — placeholder`),c(null),f("stopped"),u([]),z.current={sessionId:null,entries:{},status:"stopped"},W.current=null,U(!1),x(!0)};try{let h,p,m;if(!a){let n=Nb(e,r,s),i=Nl(n);if(i?.content){let e=await eV.current?.(i,o);if(e?.adopted)return e.session;if(et.current!==o)return null;if(Nw(n))return d(),null}}if(console.log(`[AgentSession] Starting REST call: projectId=${e}, branch=${r}, sessionId=${a??"latest"}, agentType=${n}, generation=${o}`),a){let e=l?await NX(a):null;h=(m=l&&e&&"stopped"===e.status&&e.historyEpoch===l.history.historyEpoch&&e.lastTurnEndEntryIndex===l.history.lastTurnEndEntryIndex?{...l.history,status:e.status,latestEntryIndex:e.latestEntryIndex}:await NV(a)).session??l?.session??null,p=m.entries.map(e=>e.message)}else if(l){let s=await NX(l.session.id).catch(()=>null);if(s&&"stopped"===s.status&&s.historyEpoch===l.history.historyEpoch&&s.lastTurnEndEntryIndex===l.history.lastTurnEndEntryIndex)m={...l.history,status:s.status,latestEntryIndex:s.latestEntryIndex},h={...l.session,status:s.status},p=m.entries.map(e=>e.message);else{let s=await NN(e,r,i,n);h=s.session,p=s.messages,m=s.historyWindow}}else{let s=await NN(e,r,i,n);h=s.session,p=s.messages,m=s.historyWindow}if(et.current!==o)return console.log("[AgentSession] Discarding stale session response (generation mismatch)"),null;if(!h)return d(),null;console.log(`[AgentSession] REST response: sessionId=${h.id}, msgCount=${p?.length??0}, status=${h.status}, explicitSessionIdRequested=${a??"<null>"}, window=[${m?.entries[0]?.entryIndex??"-"}..${m?.latestEntryIndex??"-"}], streamTail=${NG(z.current).at(-1)?.entryIndex??"-"}`);let g=m?{...m,status:h.status,session:h}:{historyEpoch:0,latestEntryIndex:p.length>0?p.length-1:null,lastTurnEndEntryIndex:p.reduce((e,r,s)=>"turn_end"===r.type?s:e,null),entries:p.map((e,r)=>({entryIndex:r,message:e})),previousCursor:null,hasMore:!1,status:h.status,session:h},v=z.current.sessionId===h.id&&W.current?.historyEpoch===g.historyEpoch,y=function(e,r,s){if(!s)return e;let n=NG(r),i=n.at(-1)?.entryIndex??null;if(null===i||null!==e.latestEntryIndex&&e.latestEntryIndex>=i)return e;let a=new Map;for(let r of e.entries)a.set(r.entryIndex,r.message);for(let e of n)a.set(e.entryIndex,e.message);let o=[...a].sort((e,r)=>e[0]-r[0]).map(([e,r])=>({entryIndex:e,message:r}));return{...e,entries:o,latestEntryIndex:o.at(-1)?.entryIndex??null,lastTurnEndEntryIndex:[...o].reverse().find(e=>"turn_end"===e.message.type)?.entryIndex??null}}(g,z.current,v);return y!==g&&console.warn(`[AgentSession] Stale history window for ${h.id}: window ends at ${g.latestEntryIndex}, stream already at ${y.latestEntryIndex} — keeping live tail`),NH(e,r,a,h,y),c(h),V.current=h,W.current=y,U(y.hasMore),f(h.status),y.entries.length>0&&(u(y.entries.map(e=>e.message)),z.current={sessionId:h.id,entries:NY(y.entries),status:h.status}),x(!0),eg(h.id),el.current?.(h),h}catch(e){if(console.error("[AgentSession] startSession error:",e),et.current!==o)return console.log("[AgentSession] Discarding error (generation mismatch)"),null;return S(e instanceof Error?e.message:"Failed to start session"),er.current=!0,null}finally{es.current=!1,et.current===o&&(y(!1),w(!1),en.current=!1)}},[e,r,s,n,a,eg]),ey=(0,$.useCallback)(async(s,n,i)=>{let o=n||l?.id;if(!o)return void console.warn("[AgentSession] sendMessage: no session ID available (sessionId param:",n,", session?.id:",l?.id,")");if(("string"!=typeof s||s.trim())&&(!Array.isArray(s)||0!==s.length)){console.log(`[AgentSession] sendMessage: targetSessionId=${o}, source=${n?"explicit":"state"}`);try{let e="string"==typeof s?s.trim():s;await NE(o,e,i)}catch(n){let s=n instanceof Error?n.message:"Failed to send message";console.error("[AgentSession] Failed to send message:",s),s.includes("[404]")&&(e&&(NO.delete(Nz(e,r,a)),l?.id&&NO.delete(Nz(e,r,l.id))),c(null),f("stopped"),x(!1),Y.current=!0),S(s),gS.toast.error("Failed to send message",{description:s})}}},[l?.id,e,r,a]),eb=(0,$.useCallback)(async(e,r)=>{try{let s="string"==typeof r?r.trim():r;return await NE(e.session.id,s),!0}catch(n){let r=n instanceof Error?n.message:"Failed to send message";console.error(`[AgentSession] Failed first-send for ${e.session.id}:`,r);let s=ef.current;if(!s||!Nk(e.origin,s))return!1;return r.includes("[404]")&&(NU(e.origin.projectId,e.origin.branch,e.origin.explicitSessionId,e.session.id),V.current?.id===e.session.id&&(c(null),V.current=null,W.current=null,f("stopped"),x(!1),Y.current=!0)),S(r),gS.toast.error("Failed to send message",{description:r}),!1}},[]),ew=(0,$.useCallback)(async e=>{let r;try{r=await ND(e.session.id)}catch(r){return console.error(`[AgentSession] Failed to discard empty session ${e.session.id}:`,r),!1}if(!r)return!1;NU(e.origin.projectId,e.origin.branch,e.origin.explicitSessionId,e.session.id);let s=Nb(e.origin.projectId,e.origin.branch,e.origin.agentMode);eP.current.get(s)===e.session.id&&(eP.current.delete(s),N_(s));let n=ef.current;return n&&Nk(e.origin,n)&&V.current?.id===e.session.id&&(I.current===e.session.id&&(A.current?.close(1e3,"discard-empty-session"),A.current=null,I.current=null),M.current=null,c(null),V.current=null,W.current=null,f("stopped"),x(!0),u([]),z.current={sessionId:null,entries:{},status:"stopped"}),!0},[]),e_=(0,$.useCallback)(async(e,r)=>{let s=r||l?.id;if(!s)throw Error("No session id available for paste upload");return NR(s,e)},[l?.id]),eS=(0,$.useCallback)(async(e,r,s)=>{let n=r||l?.id;if(!n)throw Error("No session id available for attachment upload");return NT(n,e,s)},[l?.id]),ej=(0,$.useCallback)(async()=>{if(l?.id)try{await NF(l.id)}catch(e){e instanceof Error&&e.message,console.error("[AgentSession] Failed to stop session:",e),gS.toast.error("Failed to stop session")}},[l?.id]),ek=(0,$.useCallback)(async s=>{if(l?.id){e&&(NO.delete(Nz(e,r,a)),NO.delete(Nz(e,r,l.id))),y(!0),S(null);try{await NA(l.id,s),s&&c(e=>e?{...e,agentType:s}:null)}catch(e){S(e instanceof Error?e.message:"Failed to restart session"),console.error("[AgentSession] Failed to restart session:",e)}finally{y(!1)}}},[l?.id,e,r,a]),eC=(0,$.useCallback)(async s=>{if(!l?.id)return"No active session";S(null);try{return await NI(l.id,s),c(n=>{if(!n)return n;let i={...n,agentType:s,model:null};return e&&Nq(e,r,a,i),i}),null}catch(r){let e=r instanceof Error?r.message:"Failed to switch agent";return console.error("[AgentSession] Failed to switch agent:",r),e}},[l?.id,e,r,a]),eN=(0,$.useCallback)(async s=>{let n=l?.id;if(!n)return"No active session";S(null);let i=ea.current.then(()=>NM(n,s));ea.current=i.then(()=>void 0,()=>void 0);try{let s=await i;return c(i=>{if(!i||i.id!==n)return i;let o={...i,model:s};return e&&Nq(e,r,a,o),o}),null}catch(r){let e=r instanceof Error?r.message:"Failed to set model";return console.error("[AgentSession] Failed to set model:",r),e}},[l?.id,e,r,a]),eE=(0,$.useCallback)(async s=>{if(l?.id){S(null);try{await NP(l.id,s),c(n=>{if(!n)return n;let i={...n,permissionMode:s};return e&&Nq(e,r,a,i),i})}catch(e){S(e instanceof Error?e.message:"Failed to switch mode"),console.error("[AgentSession] Failed to switch mode:",e)}}},[l?.id,e,r,a]),eD=(0,$.useCallback)(async s=>{if(l?.id){S(null);try{await NL(l.id,s),c(s=>{if(!s)return s;let n={...s,permissionMode:"edit"};return e&&Nq(e,r,a,n),n})}catch(e){S(e instanceof Error?e.message:"Failed to accept plan"),console.error("[AgentSession] Failed to accept plan:",e)}}},[l?.id,e,r,a]),eR=(0,$.useCallback)(async()=>(e&&(l?.id&&NO.delete(Nz(e,r,l.id)),NO.delete(Nz(e,r,a)),A.current&&(A.current.close(1e3,"new-conversation"),A.current=null,I.current=null),M.current=null,O.current&&(clearTimeout(O.current),O.current=null),J.current&&(clearTimeout(J.current),J.current=null),X.current=!1,Q.current=!1,m(!1),c(null),f("stopped"),x(!0),S(null),k(null),D({tasks:[],turnParked:!1,parkDeadlineAt:null,canStopTasks:!1}),u([]),z.current={sessionId:null,entries:{},status:"stopped"},W.current=null,U(!1),N_(Nb(e,r,s))),null),[e,r,s,l?.id,a]),[eT,eA]=(0,$.useState)(null),eI=(0,$.useRef)(null),eM=(0,$.useCallback)(()=>{eI.current?.resolve(!1),eI.current=null,eA(null)},[]),eF=(0,$.useRef)(new Map),eP=(0,$.useRef)(new Map),eL=(0,$.useCallback)(async(e,r)=>{let s,n=new Promise(e=>{s=e}),i={maxResidentAgentProcesses:e.maxResidentAgentProcesses??0,runningSessions:e.runningSessions??[],resolve:s};eI.current=i,eA(i);let a=await n;return eI.current===i&&(eI.current=null),eA(e=>e===i?null:e),et.current===r&&a},[]),eO=(0,$.useCallback)(e=>{z.current.sessionId!==e.id&&(console.log(`[AgentSession] Adopting ${e.id} over ${z.current.sessionId} — dropping its entries`),u([]),z.current={sessionId:e.id,entries:{},status:e.status},U(!1))},[]),eB=(0,$.useCallback)((e,r,s)=>{let n=e.session,i={id:n.id,projectId:n.projectId,branch:n.branch,status:n.status,permissionMode:n.permissionMode??"edit",agentType:n.agentType??"claude-code",model:n.model??null,processAlive:n.processAlive??!0},a=NJ(i);NH(r.projectId,r.branch,r.explicitSessionId,i,a);let o=Nb(r.projectId,r.branch,r.agentMode);NS(o),eP.current.set(o,i.id);try{s?.(i.id)}catch(e){console.error(`[AgentSession] onCreated failed for ${i.id}:`,e)}let l=ef.current,d=null!==l&&Nk(r,l);if(d){et.current+=1,y(!1),eO(i),c(i),V.current=i,W.current=a,f(i.status),x(!0);try{eg(i.id)}catch(e){console.error(`[AgentSession] Failed to connect activated session ${i.id}:`,e)}try{el.current?.(i)}catch(e){console.error(`[AgentSession] onSessionStarted failed for ${i.id}:`,e)}"uncertain"===e.kind&&gS.toast.warning("First message delivery could not be confirmed",{description:"The session exists, but the agent may not have received your message. Check the conversation before resending."})}else console.log(`[AgentSession] Activated session ${i.id} for a background workspace; not adopting it into the current view`);return{session:i,origin:r,adopted:d}},[eg,eO]),ez=(0,$.useCallback)(async(e,r,s,n,i)=>{let a=!1,o=0,l=s;for(;;){let c;try{c=await n(a)}catch(n){let e=n instanceof Error?n.message:"Failed to start session";return console.error(`[AgentSession] first send transport failure for ${s.operationId}:`,e),et.current===r&&(S(e),gS.toast.error("Failed to send message",{description:`${e}. Sending again will retry the same request.`})),null}if((0,ry.lifecycleSessionReady)(c.kind)&&c.session)return Nd(l.workspaceKey,l.operationId),eB(c,e,i);if(et.current!==r)return null;switch(!l.sessionId&&c.lifecycle?.sessionId&&Nc(l={...l,sessionId:c.lifecycle.sessionId}),c.kind){case"resident_limit":if(!await eL(c,r))return null;a=!0;continue;case"in_progress":if(o++>=15)return S("Activation is still in progress; try again in a moment"),null;if(await new Promise(e=>setTimeout(e,1e3)),et.current!==r)return null;continue;case"retryable_failure":case"remote_unreachable":{let e=c.error??`Failed to start session (${c.kind})`;return S(e),gS.toast.error("Failed to send message",{description:`${e}. Sending again will retry the same request.`}),null}default:{Nd(l.workspaceKey,l.operationId);let e=c.error??`Failed to start session (${c.kind})`;return S(e),gS.toast.error("Failed to send message",{description:e}),null}}}},[eB,eL]),e$=(0,$.useRef)(new Map),eW=(0,$.useCallback)(()=>{if(!e)return null;let n=Nj(e,r,s,a);return{origin:n,key:Nb(n.projectId,n.branch,n.agentMode)}},[e,r,s,a]),eH=(0,$.useCallback)((e,r,s,i,a)=>{let o=eW();if(!o)return Promise.resolve(null);if(l)return Promise.resolve({session:l,origin:o.origin,adopted:!0});let{origin:c,key:d}=o,u=et.current,h=e$.current.get(d);if(h)return h.then(async r=>r?(await ey(e,r.session.id),r):null);let f=(async()=>{y(!0),S(null);try{var o;let l=Nl(d),h=null!==l&&(o=l.content,null!==o&&null!==e&&("string"==typeof o||"string"==typeof e?"string"==typeof o&&"string"==typeof e&&o.trim()===e.trim():JSON.stringify(o)===JSON.stringify(e)))?{...l,content:e,grantedRemoteIds:i??l.grantedRemoteIds}:{workspaceKey:d,projectId:c.projectId,branch:c.branch,agentMode:c.agentMode??"local",operationId:crypto.randomUUID(),sessionId:null,content:e,permissionMode:r,model:s??null,grantedRemoteIds:i,createdAt:Date.now()},f=Nc(h);return f?.sessionId&&(0,ry.cancelPreparedAgentSession)(f.sessionId).catch(()=>void 0),await ez(c,u,h,a=>h.sessionId?(0,ry.activateAgentSession)(h.sessionId,{activationKey:h.operationId,instruction:e,force:a}):(0,ry.startAgentSession)(c.projectId,{operationId:h.operationId,branch:c.branch,permissionMode:h.permissionMode??r,agentType:n,model:h.model??s,instruction:e,force:a,grantedRemoteIds:h.grantedRemoteIds??i}),a)}finally{e$.current.get(d)===f&&e$.current.delete(d),et.current===u&&y(!1)}})();return e$.current.set(d,f),f},[l,eW,n,ez,ey]),eU=(0,$.useCallback)(async(e,r,s)=>{let i=eW();if(!i)return null;let{origin:a,key:o}=i,l=et.current;S(null);let c=Nl(o),d=c&&null===c.content?c:{workspaceKey:o,projectId:a.projectId,branch:a.branch,agentMode:a.agentMode??"local",operationId:crypto.randomUUID(),sessionId:null,content:null,permissionMode:e,model:r??null,grantedRemoteIds:s,createdAt:Date.now()},u=Nc(d);u?.sessionId&&(0,ry.cancelPreparedAgentSession)(u.sessionId).catch(()=>void 0);for(let i=0;i<2;i++){let i;try{i=await (0,ry.prepareAgentSession)(a.projectId,{operationId:d.operationId,branch:a.branch,permissionMode:d.permissionMode??e,agentType:n,model:d.model??r,purpose:"interactive_upload",grantedRemoteIds:d.grantedRemoteIds??s})}catch(r){let e=r instanceof Error?r.message:"Failed to prepare session";et.current===l&&(S(e),gS.toast.error("Failed to send message",{description:e}));break}if(et.current!==l)break;if(("prepared"===i.kind||"replayed"===i.kind)&&i.lifecycle)return Nc(d={...d,sessionId:i.lifecycle.sessionId}),{operationId:d.operationId,sessionId:i.lifecycle.sessionId,origin:a,legacy:!0===i.lifecycle.legacy};if("expired"===i.kind){Nd(o,d.operationId),Nc(d={...d,operationId:crypto.randomUUID(),sessionId:null});continue}Nd(o,d.operationId);let c=i.error??`Failed to prepare session (${i.kind})`;S(c),gS.toast.error("Failed to send message",{description:c});break}return null},[eW,n]),eq=(0,$.useCallback)((e,r,s,n)=>{let i=Nb(e.origin.projectId,e.origin.branch,e.origin.agentMode),a=et.current,o=Nl(i),l=o&&o.operationId===e.operationId?{...o,sessionId:e.sessionId,content:r,grantedRemoteIds:s}:{workspaceKey:i,projectId:e.origin.projectId,branch:e.origin.branch,agentMode:e.origin.agentMode??"local",operationId:e.operationId,sessionId:e.sessionId,content:r,grantedRemoteIds:s,createdAt:Date.now()};Nc(l);let c=(async()=>{y(!0),S(null);try{return await ez(e.origin,a,l,n=>(0,ry.activateAgentSession)(e.sessionId,{activationKey:e.operationId,instruction:r,force:n,grantedRemoteIds:s}),n)}finally{e$.current.get(i)===c&&e$.current.delete(i),et.current===a&&y(!1)}})();return e$.current.set(i,c),c},[ez]),eK=(0,$.useCallback)(async e=>{Nd(Nb(e.origin.projectId,e.origin.branch,e.origin.agentMode),e.operationId);try{let r=await (0,ry.cancelPreparedAgentSession)(e.sessionId);e.legacy&&"cancelled"===r.kind&&NU(e.origin.projectId,e.origin.branch,e.origin.explicitSessionId,e.sessionId)}catch(r){console.warn(`[AgentSession] cancel prepared session ${e.sessionId} failed:`,r)}},[]),eV=(0,$.useRef)(null);eV.current=async(e,r)=>{let s=Nj(e.projectId,e.branch,e.agentMode,null),i=e.content;return console.log(`[AgentSession] Replaying pending first send ${e.operationId} for ${e.workspaceKey}`),ez(s,r,e,r=>e.sessionId?(0,ry.activateAgentSession)(e.sessionId,{activationKey:e.operationId,instruction:i,force:r,grantedRemoteIds:e.grantedRemoteIds}):(0,ry.startAgentSession)(e.projectId,{operationId:e.operationId,branch:e.branch,permissionMode:e.permissionMode,agentType:n,model:e.model,instruction:i,force:r,grantedRemoteIds:e.grantedRemoteIds}))};let eX=(0,$.useCallback)((i,o)=>{if(!e)return Promise.resolve(null);let d=Nj(e,r,s,a);if(l)return Promise.resolve({session:l,origin:d,adopted:!0});let u=et.current,h=`${u}:${o??null}`,p=eF.current.get(h);if(p)return p;let m=(async()=>{y(!0),S(null);try{let s;try{s=await (0,ry.createNewAgentSession)(e,r,i,n,void 0,o)}catch(h){let a;if(!(h instanceof ry.ResidentLimitError))throw h;let l=new Promise(e=>{a=e}),c={maxResidentAgentProcesses:h.maxResidentAgentProcesses,runningSessions:h.runningSessions,resolve:a};eI.current=c,eA(c);let d=await l;if(eI.current===c&&(eI.current=null),eA(e=>e===c?null:e),et.current!==u)return null;if(!d)throw h;s=await (0,ry.createNewAgentSession)(e,r,i,n,!0,o)}let a={id:s.session.id,projectId:s.session.projectId,branch:s.session.branch,status:s.session.status,permissionMode:s.session.permissionMode??"edit",agentType:s.session.agentType??"claude-code",model:s.session.model??null,processAlive:s.session.processAlive??!0},l=NJ(a);NH(d.projectId,d.branch,d.explicitSessionId,a,l),NS(Nb(d.projectId,d.branch,d.agentMode)),eP.current.set(Nb(d.projectId,d.branch,d.agentMode),a.id);let h=ef.current,p=null!==h&&Nk(d,h);if(p){et.current+=1,y(!1),eO(a),c(a),V.current=a,W.current=l,f(a.status),x(!0);try{eg(a.id)}catch(e){console.error(`[AgentSession] Failed to connect created session ${a.id}:`,e)}try{el.current?.(a)}catch(e){console.error(`[AgentSession] onSessionStarted failed for ${a.id}:`,e)}}else console.log(`[AgentSession] Created session ${a.id} for a background workspace; not adopting it into the current view`);return{session:a,origin:d,adopted:p}}catch(e){if(console.error("[AgentSession] ensureSession:",e),et.current!==u)return null;return S(e instanceof Error?e.message:"Failed to create session"),null}finally{eF.current.get(h)===m&&eF.current.delete(h),et.current===u&&y(!1)}})();return eF.current.set(h,m),m},[e,r,s,n,l,a,eg,eO]),eY=(0,$.useCallback)(async()=>{let s=V.current,n=W.current;if(s&&n?.hasMore&&null!==n.previousCursor&&!q){K(!0);try{let i=await NK(s.id,n.previousCursor);if(V.current?.id!==s.id)return;if(i.historyEpoch!==n.historyEpoch)W.current=i,z.current={sessionId:s.id,entries:NY(i.entries),status:i.status};else{let e=new Map;for(let r of i.entries)e.set(r.entryIndex,r.message);for(let r of NG(z.current))e.set(r.entryIndex,r.message);let r=[...e].sort((e,r)=>e[0]-r[0]).map(([e,r])=>({entryIndex:e,message:r}));W.current={...n,entries:r,previousCursor:i.previousCursor,hasMore:i.hasMore},z.current={sessionId:z.current.sessionId,entries:NY(r),status:z.current.status}}let o=W.current;u(o.entries.map(e=>e.message)),U(o.hasMore),e&&NH(e,r,a,s,o)}catch(e){gS.toast.error("Failed to load earlier conversation",{description:e instanceof Error?e.message:String(e)})}finally{K(!1)}}},[e,r,a,q]);(0,$.useEffect)(()=>()=>{A.current&&(X.current=!0,A.current.close(),I.current=null),M.current=null,O.current&&clearTimeout(O.current),J.current&&clearTimeout(J.current),ep(),et.current+=1,eM(),NO.clear()},[eM,ep]);let eG=(0,$.useCallback)((e,r,s)=>{let n=N$(Nz(e,r,s))??(s?void 0:function(e,r){let s,n=`${e}:${r??""}:`;for(let e of NO.keys())e.startsWith(n)&&(s=e);return s?N$(s):void 0}(e,r));if(!n)return!1;let i=n.history.lastTurnEndEntryIndex??null,a="running"===n.session.status?n.history.entries.filter(e=>null!==i&&e.entryIndex<=i):n.history.entries,o={...n.history,entries:a,latestEntryIndex:a.at(-1)?.entryIndex??null};return c(n.session),V.current=n.session,f(n.session.status),x(!0),w(!0),en.current=!0,u(a.map(e=>e.message)),z.current={sessionId:n.session.id,entries:NY(a),status:n.session.status},W.current=o,U(o.hasMore??!1),!0},[]);return(0,$.useEffect)(()=>{A.current&&(A.current.close(1e3,"branch-switch"),A.current=null,I.current=null),M.current=null,O.current&&(clearTimeout(O.current),O.current=null),J.current&&(clearTimeout(J.current),J.current=null),ep(),et.current+=1,eM();let n=e?Nb(e,r,s):null;n&&a&&NS(n);let i=!a&&null!==n&&Nw(n)&&!Nl(n)?.content;!i&&e&&!ei.current&&eG(e,r,a)||(c(null),V.current=null,f("stopped"),x(i),w(!1),en.current=!1,u([]),z.current={sessionId:null,entries:NY([]),status:"stopped"},W.current=null,U(!1)),m(!1),S(null),y(!1),k(null),D({tasks:[],turnParked:!1,parkDeadlineAt:null,canStopTasks:!1}),X.current=!1,B.current=0,G.current=null,Z.current=0,er.current=!1,es.current=!1,Y.current=!i},[e,r,s,a,eG,eM,ep]),(0,$.useEffect)(()=>{o||!e||!Y.current||en.current||V.current||Nw(Nb(e,r,s))||eG(e,r,a)},[o,e,r,s,a,eG]),(0,$.useEffect)(()=>{if(o)return;let n=null!==e?Nb(e,r,s):null,i=null!==n&&Nw(n)&&!Nl(n)?.content;!Y.current||!e||l&&!en.current||v||er.current||i||(Y.current=!1,console.log(`[AgentSession] Auto-start: projectId=${e}, branch=${r}, agentMode=${s}`),ev())},[e,r,s,l,v,ev,o]),(0,$.useEffect)(()=>{let e=()=>{if("visible"===document.visibilityState&&l?.id&&!X.current){let e=A.current;e&&e.readyState!==WebSocket.CLOSED&&e.readyState!==WebSocket.CLOSING||(console.log("[AgentSession] Tab visible, WebSocket disconnected - reconnecting"),B.current=0,Z.current=0,O.current&&(clearTimeout(O.current),O.current=null),eg(l.id))}};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[l?.id,eg]),(0,$.useEffect)(()=>{l?.id&&!X.current&&eg(l.id)},[l?.id,eg]),{session:l,messages:d,status:h,isConnected:p,isInitialized:g,isLoading:v,isCachePreview:b,error:_,remoteStatus:j,workflowRunUpdate:C,backgroundTasks:E,streamEpoch:R,messageEntryIndices:NG(z.current).map(e=>e.entryIndex),hasEarlierHistory:H,isLoadingEarlier:q,loadEarlierHistory:eY,startSession:ev,sendMessage:ey,sendEnsuredMessage:eb,discardEnsuredSessionIfEmpty:ew,uploadPaste:e_,uploadAttachment:eS,stopSession:ej,restartSession:ek,switchAgentType:eC,setModel:eN,startNewConversation:eR,ensureSession:eX,startConversation:eH,prepareConversation:eU,activateConversation:eq,cancelPreparedConversation:eK,switchMode:eE,acceptPlan:eD,residentLimitPrompt:eT}}(e,r,a?.agent_mode,H,{sessionId:s,suspended:n,onTaskCompleted:l,onSessionStarted:c,onTitleUpdated:(e,r)=>{let s=r??eh?.id;s&&e&&(ee({sessionId:s,title:e}),d?.(s,e)),G(e=>e+1),Z(null)}}),eK=ek??ef.map((e,r)=>r);b=eh?.id??null,(0,sx.useGlobalEventStream)(s=>{"session:status"!==s.type||"running"!==s.status||!e||s.projectId!==e||(s.branch??null)!==(r??null)||s.sessionId&&s.sessionId!==b&&(s=>{e&&Rx(e,r).then(e=>{e.some(e=>e.reviewer_session_id===s)||i?.(s)}).catch(()=>i?.(s))})(s.sessionId)});let eV=eh?.id??null;(0,$.useEffect)(()=>{p?.(eV)},[eV,p]);let{config:eX}=(0,p2.useAppConfig)(),eY=eX?.crossRemoteSessionGrants===!0,eG=function(e,r,s=!0){let[n,i]=(0,$.useState)([]),a=(0,$.useRef)(null);(0,$.useEffect)(()=>{(a.current=e,s)?i(RZ(RY(e,r))):i([])},[e,r,s]);let o=(0,$.useCallback)((n,a)=>{s&&i(s=>{var i;let o,l=a?s.some(e=>e.id===n.id)?s:[...s,n]:s.filter(e=>e.id!==n.id);return i=RY(e,r),o=RG(),0===l.length?delete o[i]:o[i]=l,RJ(o),l})},[e,r,s]),l=(0,$.useCallback)(e=>{if(s){let s,n,o,l;s=RY(null,r),n=RY(e,r),(l=(o=RG())[s])&&!o[n]&&(o[n]=l,delete o[s],RJ(o)),a.current===e&&i(RZ(RY(e,r)))}},[r,s]);return{granted:n,selectedIds:s?n.map(e=>e.id):void 0,toggle:o,adoptInto:l}}(eV,`${e??""}::${r??""}`,eY),eJ=a?.agent_mode&&"local"!==a.agent_mode?a.agent_mode:void 0,eZ=(0,$.useRef)(p);eZ.current=p,(0,$.useEffect)(()=>()=>eZ.current?.(null),[]),(0,$.useEffect)(()=>{(0,ry.getAgentProviders)().then(K).catch(()=>{})},[]);let eQ=eh?.id??null,e0=eh?.permissionMode??null;(0,$.useEffect)(()=>{null===eQ?A("edit"):e0&&A(e0)},[eQ,e0]),(0,$.useEffect)(()=>{eh?.agentType&&U(eh.agentType)},[eh?.agentType]),(0,$.useEffect)(()=>{B.current=null,tP(),E([]),R(1),X(null),P(!1),O(!1)},[e,r]);let e1=(0,$.useRef)({sessionId:null,count:0});(0,$.useEffect)(()=>{let e=eh?.id??null,r=e1.current;e&&r.sessionId===e&&0===r.count&&ef.length>0&&Z(e),e1.current={sessionId:e,count:ef.length}},[eh?.id,ef.length]),(0,$.useEffect)(()=>{J&&eh?.id!==J&&Z(null)},[eh?.id,J]),(0,$.useEffect)(()=>{Q&&eh?.id!==Q.sessionId&&ee(null)},[eh?.id,Q]),(0,$.useEffect)(()=>{if(!Q)return;let e=setTimeout(()=>{ee(e=>e===Q?null:e)},5e3);return()=>clearTimeout(e)},[Q]),(0,$.useEffect)(()=>{if(!J)return;let e=setTimeout(()=>{Z(e=>e===J?null:e)},3e4);return()=>clearTimeout(e)},[J]);let[e2,e5]=(0,$.useState)(!1);(0,$.useEffect)(()=>{e5(!1)},[eh?.id]),(0,$.useEffect)(()=>{em&&e5(!0)},[em]);let e3=async e=>{A(e),eh&&await eH(e)},e4=async e=>{let r=await ez(e);r&&gS.toast.error("Failed to change model",{description:r})},e6=async e=>{await eU(e),A("edit"),h?.()},[e7,e8]=(0,$.useState)(!1),e9=async(e,r)=>{if(eh&&!e7){e8(!0);try{let s=await (0,ry.branchAgentSession)(eh.id,e,r);G(e=>e+1),i?.(s.session.id)}catch(r){let e=r instanceof Error?r.message:"Failed to branch conversation";gS.toast.error("Branch failed",{description:e})}finally{e8(!1)}}},te=q.find(e=>e.type===H)?.displayName??("codex"===H?"Codex":"Claude Code"),tt=q.filter(e=>e.available).filter(e=>e.type!==H),tr=eh?.branchedFromSessionId??null,ts=eh?.branchedFromEntryIndex??-1,[tn,ti]=(0,$.useState)(()=>new Set),[ta,to]=(0,$.useState)(null),[tl,tc]=(0,$.useState)(!1);(0,$.useEffect)(()=>{ti(new Set),to(null),tc(!1)},[eh?.id]);let td=(0,$.useCallback)(e=>{let r=function(e,r){for(let s=r-1;s>=0;s--){let r=e[s];if(r){if("assistant"===r.type&&r.content.trim())return r.content.trim();if("turn_end"===r.type)break}}return null}(ef,e);return null===r?null:`以下是另一个 agent(${te})在分支会话中给出的意见,非用户本人观点,请自行判断是否采纳:
29
29
 
30
- ${r}`},[ef,te]),tu=(0,$.useCallback)(async(e,r)=>{if(!tr||null!==ta)return;let s=td(r);if(null===s)return void gS.toast.error("This turn has no text answer to send back");to(e);try{await (0,ry.sendAgentSessionMessage)(tr,s),ti(r=>new Set(r).add(e)),gS.toast.success("Sent back to source session"),i?.(tr)}catch(s){let e=s instanceof Error?s.message:String(s),r=e.includes("404");r&&tc(!0),gS.toast.error("Send back failed",{description:r?"The source session no longer exists":e})}finally{to(null)}},[tr,ta,td,i]),th=(0,$.useMemo)(()=>{for(let e=ef.length-1;e>=0;e--)if(ef[e]?.type==="turn_end")return e;return -1},[ef]),tf="running"===ep&&ef.length>0&&"turn_end"!==ef[ef.length-1].type,tp=function(e,r,s,n,i){let a=s&&s.projectId===e&&s.branch===r?s.id:null,[o,l]=(0,$.useState)(null),c=(0,$.useRef)(0),d=(0,$.useRef)(null),[u,h]=(0,$.useState)({runUpdate:null,sessionId:null});(u.runUpdate!==n||u.sessionId!==a)&&(h({runUpdate:n,sessionId:a}),n&&n.reviewer_session_id===a&&l(RJ.has(n.status)?n:null)),(0,$.useLayoutEffect)(()=>{n&&n.reviewer_session_id===a&&c.current++},[n,a]);let[f,p]=(0,$.useState)({projectId:null,sessionId:null});return(f.projectId!==e||f.sessionId!==a)&&(p({projectId:e,sessionId:a}),l(null)),(0,$.useEffect)(()=>{if(!e||!a)return;let s=!1,n=c.current,o=null!==d.current&&d.current!==i;return d.current=i,Ru(e,r,{force:o}).then(e=>{s||c.current!==n||l(e.find(e=>e.reviewer_session_id===a)??null)}).catch(()=>{}),()=>{s=!0}},[e,r,a,i]),o}(e,r,eh,e_,ej),tm=e_&&eh&&e_.reviewer_session_id===eh.id&&"failed"===e_.status?e_:null,tg=ef.flatMap((e,r)=>Ty(e)?[{message:e,index:r}]:[]),tx=ef.every(Ty),tv=!!(eh&&tp?.status==="preparing"&&tx),ty=!!(eh&&tm&&tx),tb=eh?g?.find(e=>e.sourceSessionId===eh.id&&"preparing"===e.run.status):void 0,tw=Q&&eh&&Q.sessionId===eh.id?Q.title:null,t_=tg.length>0?(0,z.jsx)("div",{className:"mt-6 space-y-1 text-left",children:tg.map(({message:e,index:r})=>(0,z.jsx)("div",{"data-message-idx":r,className:"scroll-mt-2",children:(0,z.jsx)(DT,{message:e,messageIndex:r,streaming:!1})},eK[r]??r))}):null,[tS,tj]=(0,$.useState)(!1),tk=(0,$.useCallback)(async()=>{if(tp){tj(!0);try{await ry.api.workflowRunGate(tp.id,"finalize")}catch(e){gS.toast.error(e instanceof Error?e.message:"生成终稿失败")}finally{tj(!1)}}},[tp]),tC=(0,$.useCallback)(()=>{es.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]),{active:tN,requestNonce:tE}=(0,$.useContext)(Cg);(0,$.useEffect)(()=>{tN&&tC()},[tN,tE,tC]);let tD=(0,$.useCallback)(e=>{var r,s;let n;C((r=k,s=e,n=0===r.length||r.endsWith("\n\n")?"":r.endsWith("\n")?"\n":"\n\n",r+n+(s.replace(/\r?\n/g,"\n").split("\n").map(e=>`> ${e}`).join("\n")+"\n\n"))),requestAnimationFrame(()=>{let e=es.current?.querySelector("textarea");if(!e)return;e.focus();let r=e.value.length;try{e.setSelectionRange(r,r)}catch{}})},[C,k]),tR=(0,$.useCallback)(async()=>{!ex&&eh&&(await e$(),X(null),f?.(),i?.(null),tC())},[ex,eh,e$,f,i,tC]);(0,$.useImperativeHandle)(y,()=>({startNewConversation:tR,submitMessage:async e=>{if(h?.(),eh)await eD(e,void 0,eG.selectedIds);else{let r=await eA(e,T,V,eG.selectedIds);r&&eG.adoptInto(r.session.id),r&&ed(r.origin)&&Z(r.session.id)}}}),[tR,eh,eA,eD,T,V,h,ed,eG]);let tT=(0,$.useCallback)((e,r)=>{if(r.length<=2e3)return;e.preventDefault();let s=e.currentTarget,n=s.selectionStart??k.length,i=s.selectionEnd??k.length,a=new TextEncoder().encode(r).length,o=Tb(D,a);C(k.slice(0,n)+o+k.slice(i)),E(e=>[...e,{id:D,content:r,size:a}]),R(D+1);let l=n+o.length;requestAnimationFrame(()=>{try{s.setSelectionRange(l,l)}catch{}})},[k,D,C]);async function tA(e,r,s,n){let i=new Set;for(let r of e.matchAll(Tv))i.add(Number(r[1]));let a=r.filter(e=>i.has(e.id));if(0===a.length)return e;let o=e;for(let e of a){let r=await s(e.content,n),i=Tb(e.id,e.size),a=`<vpaste path="${r.path}" size="${r.size}" />`;o=o.split(i).join(a)}return o}let tI=(0,$.useRef)(null),tM=s=>!!s&&s.projectId===e&&s.branch===r&&s.agentType===H&&s.permissionMode===T&&s.model===V&&Date.now()-s.createdAt<6e5,tF=async()=>{let s=await eI(T,V,eG.selectedIds);if(!s)throw Error("Failed to prepare session");return{prepared:s,projectId:e,branch:r??null,agentType:H,permissionMode:T,model:V,createdAt:Date.now()}},tP=async()=>{let e=tI.current;e&&(tI.current=null,await eF(e.prepared))},tL=function(e){let r=(0,$.useRef)(e);r.current=e;let s=(0,$.useRef)(new Map),n=(0,$.useRef)(new Set),[i,a]=(0,$.useState)(new Map),o=(0,$.useCallback)((e,r)=>{a(s=>{let n=s.get(e);if(n&&n.phase===r.phase&&n.progress===r.progress&&n.message===r.message)return s;let i=new Map(s);return i.set(e,r),i})},[]),l=(0,$.useCallback)(async(e,s)=>{var n;let i,a=e.filename||"attachment";s?.({phase:"reading",progress:0});let o=(n=await D$(e.url)??void 0,n?.match(Dz)?.[1]??null);if(!o)throw Error(`Could not read ${a}`);let l=(i=function(e){let r=e.slice(0,24).replace(/[^A-Za-z0-9+/=]/g,"");try{let e=atob(r.length%4==0?r:r.slice(0,r.length-r.length%4)),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s}catch{return new Uint8Array(0)}}(o)).length>=3&&255===i[0]&&216===i[1]&&255===i[2]?"image/jpeg":Tp(i,Td)?"image/png":Tp(i,Tu)?"image/gif":Tp(i,Th)&&Tp(i,Tf,8)?"image/webp":null;if(l&&5242880>=function(e){let r=e.length;if(0===r)return 0;let s=0;return e.endsWith("==")?s=2:e.endsWith("=")&&(s=1),Math.floor(3*r/4)-s}(o))return s?.({phase:"inline",progress:1}),{kind:"image",mediaType:l,data:o};s?.({phase:"uploading",progress:0});let c=await r.current.getUploadTarget(),d=await r.current.upload({name:a,mediaType:e.mediaType||void 0,contentBase64:o},c,e=>s?.({phase:"uploading",progress:e}));return s?.({phase:"done",progress:1}),{kind:"file",marker:`<vfile path="${d.path}" name="${d.name}" size="${d.size}" />`}},[]),c=(0,$.useCallback)((e,r)=>{let n=l(e,e=>o(r,e));n.catch(e=>{o(r,{phase:"error",progress:0,message:e instanceof Error?e.message:"Upload failed"})}),s.current.set(r,{name:e.filename||"attachment",promise:n})},[l,o]),d=(0,$.useCallback)(e=>{let r=new Set;for(let n of e)n.id&&(r.add(n.id),s.current.has(n.id)||c(n,n.id));let i=e=>r.has(e)||n.current.has(e);for(let e of Array.from(s.current.keys()))i(e)||s.current.delete(e);a(e=>{if(0===e.size)return e;let r=new Map;for(let[s,n]of e)i(s)&&r.set(s,n);return r.size===e.size?e:r})},[c]),u=(0,$.useCallback)(e=>{for(let r of e)n.current.add(r)},[]),h=(0,$.useCallback)((e,r)=>{for(let i of e)n.current.delete(i),r&&s.current.delete(i);r&&a(r=>{let s=new Map(r);for(let r of e)s.delete(r);return s.size===r.size?r:s})},[]),f=(0,$.useCallback)(e=>{e.id&&(s.current.delete(e.id),c(e,e.id))},[c]),p=(0,$.useCallback)(e=>e?i.get(e):void 0,[i]);return{track:d,retry:f,retain:u,release:h,statusOf:p,resolve:(0,$.useCallback)(async e=>{let r=[],n=[];for(let i of e){let e=i.id?s.current.get(i.id):void 0,a=e?await e.promise:await l(i);"image"===a.kind?r.push({mediaType:a.mediaType,data:a.data}):n.push(a.marker)}return{images:r,markers:n}},[l]),pending:(0,$.useMemo)(()=>Array.from(i.values()).some(e=>"reading"===e.phase||"uploading"===e.phase),[i])}}({upload:eL,getUploadTarget:(0,$.useCallback)(async()=>eh?eh.id:(tM(tI.current)||(await tP(),tI.current=await tF()),tI.current.prepared.sessionId),[eh,e,r,H,T,V,eI,eF])}),tO=(0,$.useRef)(null),tB=(0,$.useCallback)(e=>{if("max_file_size"===e.code){let r=e.files?.map(e=>e.name).join(", ");gS.toast.error(`Files must be ${Math.floor(20)}MB or smaller`,{description:r?`Not attached: ${r}`:e.message});return}gS.toast.error("Could not attach files",{description:e.message})},[]),tz=async e=>{let r=ec.current;if(!r)return;let s=e.text,n=e.files.length>0,i=N.length>0,a=s.trim();if(!a&&!n)return;let o=Symbol("agent-submission");B.current=o,O(!0);try{let l,c,d;C(""),en.push(a),h?.();let u=null,f=async()=>{if(u){let e=u;u=null,await eF(e.prepared);return}eu(r)&&await tP()},p=[],m=()=>{for(let e of p)e.url?.startsWith("blob:")&&URL.revokeObjectURL(e.url)},g=()=>{if(0===p.length)return;let e=p.map(e=>e.id);eu(r)?(tO.current?.restore(p),tL.release(e,!1)):(m(),tL.release(e,!0)),p=[]},x=()=>{0!==p.length&&(m(),tL.release(p.map(e=>e.id),!0),p=[])},v=async(e,n)=>{let i=n instanceof Error?n:Error(e);throw await f(),eu(r)&&(gS.toast.error(e,{description:i.message}),C(s)),g(),i};try{({images:l,markers:c}=await tL.resolve(e.files))}catch(e){return await v("Attachment upload failed",e)}let y=l.length>0;!eh&&eu(r)&&tM(tI.current)&&(u=tI.current,tI.current=null),eu(r)&&(p=tO.current?.detach()??[],tL.retain(p.map(e=>e.id)));let b=async()=>eh?eh.id:(u||(eu(r)&&await tP(),u=await tF()),u.prepared.sessionId),w=a;if(i)try{w=(await tA(s,N,eP,await b())).trim()}catch(e){return await v("Paste upload failed",e)}if(w.length>2e3)try{let e=await eP(w,await b());w=`<vpaste path="${e.path}" size="${e.size}" />`}catch(e){return await v("Paste upload failed",e)}if(c.length>0&&(w=[w,...c].filter(Boolean).join("\n")),eu(r)&&(E([]),R(1)),y){let e=[];for(let r of(w&&e.push({type:"text",text:w}),l))e.push({type:"image",mediaType:r.mediaType,data:r.data});d=e}else d=w;if(I){let e="string"==typeof d?d:d.filter(e=>"text"===e.type).map(e=>e.text).join("\n");if(e.trim()){B.current===o&&eu(r)&&P(!0);let s=null;try{let r=await (0,ry.translateText)(e);r.error||(s=r.translatedText)}catch{s=null}finally{B.current===o&&P(!1)}if(null===s)return eu(r)&&(E(N),R(D)),await v("Translation failed",Error("Disable translation to send the original text."));d="string"==typeof d?s:d.map(e=>"text"===e.type?{...e,text:s}:e)}}if(eh){console.log(`[AgentConversation] handleSubmit: existing session ${eh.id}, status=${ep}`);try{await eD(d,void 0,eG.selectedIds)}catch(e){return await v("Failed to send message",e)}x()}else{tM(u??tI.current)||await f();let e=u?.prepared??null;u=null;let i=eG.selectedIds,a=e?await eM(e,d,i):await eA(d,T,V,i);if(a)x(),eG.adoptInto(a.session.id),console.log(`[AgentConversation] handleSubmit: started session ${a.session.id}`),ed(r)&&Z(a.session.id);else if(eu(r)&&(C(s),E(N),R(D)),g(),n)throw Error("Failed to start session")}}finally{B.current===o&&(B.current=null,P(!1),O(!1))}},{settings:t$}=(0,mo.useConversationSettings)();return e?(0,z.jsxs)("div",{className:"h-full flex flex-col min-h-0",style:{"--conv-font-size":`${t$.agentFontSize}px`},children:[(0,z.jsxs)("div",{className:"flex-shrink-0 flex items-center justify-between px-4 h-10 border-b border-border/60 bg-muted/20",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[q.length>1?(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsxs)("button",{disabled:ex||"running"===ep&&ef.length>0,className:(0,eb.cn)("inline-flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-0.5 text-xs font-medium transition-colors hover:bg-muted",(ex||"running"===ep&&ef.length>0)&&"opacity-50 cursor-not-allowed"),children:[(0,z.jsx)(RY,{type:H}),(0,z.jsx)(RD,{candidates:q.map(e=>e.displayName),children:te}),(0,z.jsx)(n6,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,z.jsx)(o1,{align:"start",className:"min-w-[var(--radix-dropdown-menu-trigger-width)]",children:(0,z.jsx)(o3,{value:H,onValueChange:async e=>{if(!eh){e!==H&&X(null),U(e);return}let r=await eB(e);r?gS.toast.error("Failed to switch agent",{description:r}):U(e)},children:q.map(e=>(0,z.jsxs)(o4,{value:e.type,disabled:!e.available,className:"text-xs pl-2 [&>span:first-child]:hidden data-[state=checked]:bg-accent data-[state=checked]:text-accent-foreground",children:[(0,z.jsx)(RY,{type:e.type}),e.displayName]},e.type))})})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(RY,{type:H,className:"h-4 w-4"}),(0,z.jsx)("span",{className:"text-sm font-medium",children:te})]}),(0,z.jsx)(RI,{models:q.find(e=>e.type===H)?.models??[],widthCandidates:q.flatMap(e=>e.models??[]),value:eh?eh.model??null:V,onChange:eh?e4:X,locked:null!=eh&&"running"===ep&&ef.length>0}),(0,z.jsx)(RX,{mode:T,onModeChange:e3}),ea.length>=1&&o&&(0,z.jsx)(jL,{targets:ea,activeTarget:a?.agent_mode??"local",onTargetChange:o}),eh&&(w=eh.id.startsWith("remote-"),_="text-muted-foreground",S=(0,z.jsx)(dr,{className:"h-3 w-3"}),j="Disconnected",ev?(_="text-muted-foreground",S=(0,z.jsx)(sC,{className:"h-3 w-3 animate-spin"}),j="Checking for newer output..."):em?w&&"connected"!==ew&&null!==ew?"reconnecting"===ew?(_="text-amber-500",S=(0,z.jsx)(Rh,{className:"h-3 w-3 animate-pulse"}),j="Reconnecting..."):"disconnected"===ew&&(_="text-red-500",S=(0,z.jsx)(dr,{className:"h-3 w-3"}),j="Remote disconnected"):(_="text-green-500",S=(0,z.jsx)(Rh,{className:"h-3 w-3"}),j="Connected"):e2||(_="text-amber-500",S=(0,z.jsx)(Rh,{className:"h-3 w-3 animate-pulse"}),j="Connecting..."),(0,z.jsx)("span",{className:`flex items-center ${_}`,title:j,children:S}))]}),(0,z.jsxs)("div",{className:"flex items-center gap-1",children:[e&&(0,z.jsx)(Ta,{projectId:e,branch:r,sessionId:eh?.id??null,currentAgentType:H,providers:q,shortcutEnabled:tN,onStarted:e=>x?.(e,tw)}),e&&(0,z.jsx)(R2,{projectId:e,branch:r,currentSessionId:eh?.id??null,refreshKey:Y,pendingTitleSessionId:J,aiTitleOverride:Q,onSwitch:e=>{u?.(e),i?.(e)},onDelete:(e,r)=>{if(e===eh?.id){let e=r[0];i?.(e?e.id:null)}}}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:tR,disabled:ex||!eh,className:"h-7 w-7",title:"New Conversation (⌘⇧O / Ctrl+Shift+O)",children:(0,z.jsx)(Rf,{className:"h-3.5 w-3.5"})}),(0,z.jsxs)(W.Button,{variant:"ghost",size:"sm",onClick:()=>eO(),disabled:"running"!==ep,className:"h-7 text-xs",children:[(0,z.jsx)(lG,{className:"h-3 w-3 mr-1"}),"Stop"]})]})]}),tb&&(0,z.jsxs)("div",{className:"flex items-center gap-2 px-4 py-1.5 border-b bg-muted/40 text-xs text-muted-foreground shrink-0","data-testid":"source-preparing-review",children:[(0,z.jsx)(sC,{className:"h-3 w-3 animate-spin shrink-0"}),(0,z.jsx)("span",{className:"flex-1 truncate",children:"Preparing review — summarizing this conversation and starting the reviewer"}),v&&(0,z.jsx)("button",{type:"button",className:"shrink-0 font-medium text-foreground/80 hover:text-foreground underline-offset-2 hover:underline",onClick:()=>v(tb.runId),children:"View"})]}),(0,z.jsxs)("div",{className:"flex-1 min-h-0 relative",children:[(0,z.jsxs)(cz,{className:"h-full",initial:"instant",resize:tf?"smooth":"instant",children:[(0,z.jsxs)(c$,{className:"gap-1 p-4",scrollClassName:"edge-scrollbar will-change-transform",children:[tv?(0,z.jsx)(To,{children:t_}):ty?(0,z.jsx)(Tl,{error:tm?.error,children:t_}):eh||0!==ef.length?(0,z.jsx)(Tg.Provider,{value:{sendMessage:eD,messages:ef,acceptPlan:e6,permissionMode:eh?.permissionMode??T,agentType:eh?.agentType??H,sessionId:eh?.id??null,projectId:e,branch:r,target:eo,targetLabel:el,openSchedule:m},children:(0,z.jsxs)("div",{className:"space-y-1 outline-none",ref:et,tabIndex:-1,onKeyDown:er,children:[eh?.lifecycleState==="activation_uncertain"&&(0,z.jsxs)("div",{className:"flex items-start gap-2 p-3 mb-2 rounded-lg border border-amber-500/40 bg-amber-500/10 text-sm text-amber-700 dark:text-amber-400",children:[(0,z.jsx)(s_,{className:"h-4 w-4 mt-0.5 shrink-0"}),(0,z.jsx)("span",{children:"First message delivery could not be confirmed for this session. Check whether the agent actually responded before resending — a resend may duplicate the task."})]}),eC&&(0,z.jsx)("div",{className:"flex justify-center pb-3",children:(0,z.jsxs)(W.Button,{type:"button",variant:"ghost",size:"sm",disabled:eN,onClick:()=>void eE(),children:[eN?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 animate-spin"}):(0,z.jsx)(n6,{className:"h-3.5 w-3.5 rotate-180"}),"Load earlier turns"]})}),ef.map((e,r)=>e?.type==="turn_end"?(0,z.jsx)(Rw,{durationMs:e.durationMs,outcome:e.outcome,emphasis:r===th?"normal":"subtle",agentType:H,currentAgentName:te,alternateProviders:tt,onBranch:e=>e9(e,eK[r]??r),disabled:e7,showFinalize:r===th&&tp?.status==="discussing",finalizeBusy:tS,onFinalize:tk,sendBack:tr&&(eK[r]??r)>ts?{available:!tl&&eh?.branchedFromAvailable!==!1,sent:tn.has(eK[r]??r),busy:ta===(eK[r]??r),onSend:()=>void tu(eK[r]??r,r)}:void 0},eK[r]??r):(0,z.jsx)("div",{"data-message-idx":r,..."user"===e.type?{"data-user-msg-idx":r}:{},className:"scroll-mt-2",children:(0,z.jsx)(DT,{message:e,messageIndex:r,streaming:"assistant"===e.type&&tf&&r===ef.length-1})},eK[r]??r)),ex&&!ev&&(0,z.jsxs)("div",{className:"flex items-center gap-2 py-4 text-muted-foreground",children:[(0,z.jsx)(Rr,{className:"h-4 w-4"}),(0,z.jsx)("span",{className:"text-sm",children:"Connecting to agent..."})]})]})}):(0,z.jsx)("div",{className:"text-center py-16",children:ex||e&&!eg?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Rr,{className:"h-6 w-6 mx-auto mb-4"}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Connecting to agent..."}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Setting up the session for this worktree"})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mb-4",children:(0,z.jsx)(sS,{className:"h-6 w-6 text-primary/60"})}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Start a conversation"}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Ask the agent to help you with coding tasks in this worktree"})]})}),ey&&(0,z.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-red-500/10 rounded-lg text-red-500 text-sm mt-4",children:[(0,z.jsx)(s_,{className:"h-4 w-4"}),ey]})]}),(0,z.jsx)(cW,{}),(0,z.jsx)(R4,{messageCount:ef.length,turnInFlight:tf,sessionId:eh?.id??null})]}),(0,z.jsx)(R0,{messages:ef,contentRef:et}),(0,z.jsx)(R8,{containerRef:et,onQuote:tD})]}),(0,z.jsxs)("div",{className:"flex-shrink-0 py-3 px-[30px]",children:[(0,z.jsx)(RE,{sessionId:eV,tasks:eS.tasks,turnParked:eS.turnParked,parkDeadlineAt:eS.parkDeadlineAt,canStopTasks:eS.canStopTasks,agentWorking:"running"===ep}),(0,z.jsxs)(DQ,{onSubmit:tz,maxFileSize:0x1400000,onError:tB,skipAttachmentConversion:!0,className:"w-full",children:[(0,z.jsx)(Tm,{uploads:tL,workspaceKey:`${e}::${r}`,apiRef:tO}),(0,z.jsxs)("div",{className:"relative flex w-full flex-col",children:[eY&&(0,z.jsx)(R$,{granted:eG.granted,onRevoke:e=>eG.toggle(e,!1)}),I&&(0,z.jsx)("div",{className:"flex items-center pl-12 pr-2 pt-1.5 pb-0.5",children:(0,z.jsxs)("button",{type:"button",onClick:()=>M(!1),className:"inline-flex shrink-0 items-center gap-1.5 rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400 px-2.5 py-0.5 text-xs font-medium hover:bg-blue-500/20 transition-colors",children:[F?(0,z.jsx)(sC,{className:"size-3 animate-spin"}):(0,z.jsx)(Rp,{className:"size-3"}),"Translate",(0,z.jsx)(t7,{className:"size-3"})]})}),(0,z.jsxs)("div",{className:"flex w-full items-center",children:[(0,z.jsxs)(D3,{children:[(0,z.jsx)(D4,{className:"ml-1"}),(0,z.jsxs)(D6,{children:[(0,z.jsx)(DZ,{label:"Add files"}),eY&&(0,z.jsx)(Rz,{granted:eG.granted,onToggle:eG.toggle,sourceRemoteId:eJ}),(0,z.jsxs)(D7,{onSelect:()=>{M(!I)},children:[(0,z.jsx)(Rp,{className:"mr-2 size-4"}),I?"Disable translation":"Translate"]})]})]}),(0,z.jsx)("div",{ref:es,className:"contents",children:(0,z.jsx)(D0,{value:k,onChange:e=>C(e.target.value),onPasteText:tT,onKeyDown:en.handleKeyDown,placeholder:eh?"Ask the agent to help with your code...":"Type your first message to start...",className:"pr-12",style:{fontSize:"var(--conv-font-size, 14px)"}})}),(0,z.jsx)("div",{className:"pointer-events-none absolute bottom-0 right-2 flex items-center text-base md:text-sm",style:{fontSize:"var(--conv-font-size, 14px)",height:"calc(1lh + 1.5rem)"},children:(0,z.jsx)(D8,{className:"pointer-events-auto",disabled:!k.trim()&&!ex||F||L||tL.pending,status:L||F||tL.pending?"submitted":ex?"streaming":"ready"})})]})]})]})]}),(0,z.jsx)(lL,{open:null!==eq,onOpenChange:e=>{e||eq?.resolve(!1)},children:(0,z.jsxs)(lz,{children:[(0,z.jsxs)(l$,{children:[(0,z.jsx)(lH,{children:"Agent process limit reached"}),(0,z.jsxs)(lU,{children:["All ",eq?.maxResidentAgentProcesses," resident agent processes for this workspace branch are running. Starting a new conversation will stop the least recently active running session in this branch."]})]}),(0,z.jsxs)(lW,{children:[(0,z.jsx)(lK,{children:"Cancel"}),(0,z.jsx)(lq,{onClick:()=>eq?.resolve(!0),children:"Stop & start new"})]})]})})]}):(0,z.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(sS,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to start coding"})]})})});function T_({runId:e,entry:r,title:s,onOpenSource:n}){let i,[a,o]=(0,$.useState)(null),[l,c]=(0,$.useState)(0);(0,$.useEffect)(()=>{if(r)return;let s=!1;return ry.api.getWorkflowRun(e).then(r=>{s||o({runId:e,attempt:l,run:r})}).catch(r=>{s||o({runId:e,attempt:l,error:r instanceof Error?r.message:String(r)})}),()=>{s=!0}},[r,e,l]);let d=a?.runId===e&&a.attempt===l?a:null,u=!d||"error"in d?null:d,h=r?.run??u?.run??null;return i=r?(0,z.jsx)(To,{phase:"preparing"===r.run.status?"distilling":"starting"}):d&&"error"in d?(0,z.jsx)(Tl,{error:d.error,title:"Could not read the review status",children:(0,z.jsx)(W.Button,{variant:"outline",size:"sm",className:"mt-4",onClick:()=>c(e=>e+1),children:"Retry"})}):u?u.run?"failed"===u.run.status?(0,z.jsx)(Tl,{error:u.run.error}):"cancelled"===u.run.status||"completed"===u.run.status?(0,z.jsx)(Tc,{status:u.run.status}):(0,z.jsx)(To,{phase:"starting"}):(0,z.jsx)(Tc,{status:"gone"}):(0,z.jsxs)("div",{className:"text-center py-16",children:[(0,z.jsx)(Rr,{className:"h-6 w-6 mx-auto mb-4"}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Checking review status…"})]}),(0,z.jsxs)("div",{className:"flex flex-col h-full","data-testid":"preparing-review-view",children:[(0,z.jsxs)("div",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b shrink-0",children:[(0,z.jsx)("span",{className:"text-sm font-medium truncate",title:s,children:s}),h&&(0,z.jsxs)(W.Button,{variant:"ghost",size:"sm",className:"h-7 text-xs shrink-0",onClick:()=>n(h.source_session_id,h.branch),children:[(0,z.jsx)(n4.ArrowLeft,{className:"h-3 w-3 mr-1"}),"Source conversation"]})]}),(0,z.jsx)("div",{className:"flex-1 min-h-0 overflow-auto px-4",children:i})]})}function TS(e){return e.title?.trim()||"New Session"}async function Tj(e){let r=await (0,ry.listAliveSessions)(e);return r.complete?r.sessions.map(r=>({id:r.id,projectId:e,branch:r.branch,title:TS(r),status:r.status,processAlive:!0})):"incomplete"}async function Tk(e,r){return 0===r.length?null:(await Promise.all(r.map(async r=>(await (0,ry.listBranchSessions)(e,r)).sessions.filter(e=>e.processAlive).map(s=>({id:s.id,projectId:e,branch:r,title:TS(s),status:s.status,processAlive:!0,updated_at:s.updated_at}))))).flat()}function TC(e,r,s){return"live"===r&&s&&"live"!==e}let TN=new Map,TE="preparing-review",TD={preparing:0,waiting_reviewer:1,waiting_feedback:2,discussing:3,sending_feedback:4,waiting_rereview:1,completed:9,cancelled:9,failed:9};function TR(e){return 9===TD[e]}function TT(e){let r=Date.parse(e.updated_at);return(TD[e.status]??0)*1e13+(Number.isFinite(r)?r:0)}function TA(e){return{projectId:e,entries:new Map,tombstones:new Map}}function TI(e,r,s){let n=new Map(e.entries),i=new Map(e.tombstones);for(let e of r)n.delete(e),i.set(e,s+6e4);return{...e,entries:n,tombstones:i}}function TM(e,r,s,n){if(!e.projectId||r.project_id!==e.projectId)return e;let i=e.tombstones.get(r.id);if(void 0!==i&&i>s)return e;let a=e.entries.get(r.id);if(TR(r.status))return a?TI(e,[r.id],s):e;if(!a){if("preparing"!==r.status||!r.reviewer_session_id)return e;let i=new Map(e.entries);return i.set(r.id,{kind:TE,runId:r.id,projectId:r.project_id,branch:r.branch??null,reviewerSessionId:r.reviewer_session_id,sourceSessionId:r.source_session_id,run:r,version:TT(r),titleHint:n??null,insertedAt:s,appearedAt:null}),{...e,entries:i}}let o=TT(r);if(o<a.version)return e;let l=new Map(e.entries);return l.set(r.id,{...a,branch:r.branch??null,reviewerSessionId:r.reviewer_session_id??a.reviewerSessionId,run:r,version:o,titleHint:n??a.titleHint}),{...e,entries:l}}function TF(e,r,s){let n=null;for(let i of e.entries.values())null===i.appearedAt&&r.has(i.reviewerSessionId)&&(n??=new Map(e.entries)).set(i.runId,{...i,appearedAt:s});return n?{...e,entries:n}:e}function TP(e,r){let s=(e.titleHint??r??"").trim();return s&&"New Session"!==s?`Review - ${s}`:"Review"}let TL=Object.freeze({session:null,messages:[],status:"stopped",isConnected:!1,isInitialized:!1,isLoading:!1,error:null,workflowRunUpdate:null,streamEpoch:0,draft:""});function TO(){return"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}async function TB(e,r){let s=await (0,ry.authFetch)(`${TO()}/api/projects/${e}/chat-sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:r})});if(!s.ok)throw Error("Failed to create chat session");return s.json()}async function Tz(e,r){if(!(await (0,ry.authFetch)(`${TO()}/api/chat-sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r})})).ok)throw Error("Failed to send message")}async function T$(e){if(!(await (0,ry.authFetch)(`${TO()}/api/chat-sessions/${e}/stop`,{method:"POST"})).ok)throw Error("Failed to stop generation")}function TW(e,r){return`chat:${e}:${r??""}`}let TH=new Map,TU=new Map;function Tq(e,r){for(TU.delete(e),TU.set(e,r);TU.size>20;){let e=TU.keys().next().value;if(void 0===e)break;TU.delete(e)}}let TK=new Map;class TV{projectId;branch;key;state;listeners;active;epoch;ws;container;replaying;finished;reconnectTimer;stabilityTimer;silenceTimer;reconnectAttempt;shortLivedConnections;connectionStartedAt;lastStartFailed;metadataWrites;constructor(e,r){this.projectId=e,this.branch=r,this.listeners=new Set,this.active=!1,this.epoch=0,this.ws=null,this.container={entries:[],status:"stopped"},this.replaying=!1,this.finished=!1,this.reconnectTimer=null,this.stabilityTimer=null,this.silenceTimer=null,this.reconnectAttempt=0,this.shortLivedConnections=0,this.connectionStartedAt=null,this.lastStartFailed=!1,this.metadataWrites=0,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.getSnapshot=()=>this.state,this.onVisibilityChange=()=>{if("visible"!==document.visibilityState||!this.state.session?.id||this.finished)return;let e=this.ws;e&&e.readyState===WebSocket.OPEN&&e.close(4e3,"visibility-recovery")},this.setDraft=e=>{e!==this.state.draft&&(TK.set(this.key,e),this.set({draft:e}))},this.setEventListening=async e=>{let r=this.state.session;r&&(await ry.api.setChatEventListening(r.id,e),this.metadataWrites+=1,this.state.session?.id===r.id&&this.adoptSession({...r,eventListeningEnabled:e}))},this.sendMessage=async e=>{let r=this.state.session?.id,s=e.trim();if(r&&s)try{await Tz(r,s)}catch(r){let e=r instanceof Error?r.message:"Failed to send message";this.set({error:e}),gS.toast.error("Failed to send message",{description:e})}},this.stopGeneration=async()=>{let e=this.state.session?.id;if(e)try{await T$(e)}catch(e){console.error("[ChatSession] Failed to stop generation:",e)}},this.restartSession=async()=>{let e=this.state.session?.id;if(e)try{await ry.api.resetChatSession(e),this.container={entries:[],status:"stopped"},this.flush()}catch(e){console.error("[ChatSession] Failed to reset session:",e),gS.toast.error("Failed to start new conversation")}},this.key=TW(e,r);const s=TU.get(this.key),n=TK.get(this.key)??"",i=s?.session??TH.get(this.key)??null;this.state=s?{...TL,session:i,messages:s.messages,status:s.status,isInitialized:!0,draft:n}:{...TL,session:i,draft:n}}subscribe;getSnapshot;set(e){for(let r of(this.state={...this.state,...e},this.listeners))r()}start(){this.active||(this.active=!0,this.finished=!1,"undefined"!=typeof document&&document.addEventListener("visibilitychange",this.onVisibilityChange),this.startSession())}stop(){if(!this.active)return;this.active=!1,this.epoch+=1,"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.onVisibilityChange);let e=this.ws;if(this.ws=null,e)try{e.close(1e3,"branch-switch")}catch{}this.clearTimers(),this.connectionStartedAt=null,this.state.isConnected&&this.set({isConnected:!1})}clearTimers(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stabilityTimer&&(clearTimeout(this.stabilityTimer),this.stabilityTimer=null),this.clearSilenceTimer()}async startSession(){if(!this.active)return;let e=this.epoch;this.lastStartFailed=!1,this.set({error:null});let r=TH.get(this.key);if(r){this.set({session:r}),this.connect(),this.refreshSessionMetadata(e);return}this.set({isLoading:!0});try{let{session:r,messages:s}=await TB(this.projectId,this.branch);if(e!==this.epoch)return;TH.set(this.key,r),this.set({session:r,status:r.status,messages:s??[],isInitialized:!0}),this.connect()}catch(r){if(e!==this.epoch)return;this.lastStartFailed=!0,this.set({error:r instanceof Error?r.message:"Failed to start session"})}finally{e===this.epoch&&this.set({isLoading:!1})}}async refreshSessionMetadata(e){let r=this.metadataWrites;try{let{session:s,messages:n}=await TB(this.projectId,this.branch);if(e!==this.epoch||r!==this.metadataWrites||s.id!==this.state.session?.id)return;this.adoptSession(s),this.state.isInitialized||this.set({messages:n??[],isInitialized:!0})}catch{}}adoptSession(e){TH.set(this.key,e);let r=TU.get(this.key);r&&r.session.id===e.id&&Tq(this.key,{...r,session:e}),this.set({session:e})}connect(e=!1){if(!this.active||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;let r=this.epoch;(0,ry.getFreshToken)(e?{skipCache:!0}:void 0).then(()=>{r===this.epoch&&this.active&&this.openSocket()})}openSocket(){if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;let e=this.state.session?.id;if(!e)return;this.container={entries:[],status:"stopped"},this.finished=!1,this.replaying=!0;let r=new WebSocket((0,ry.getWebSocketUrl)(`/api/chat-sessions/${e}/stream`));this.ws=r;let s=()=>this.ws===r;r.onopen=()=>{s()&&(this.set({isConnected:!0,error:null}),this.connectionStartedAt=Date.now(),this.armSilenceTimer(r),this.stabilityTimer&&clearTimeout(this.stabilityTimer),this.stabilityTimer=setTimeout(()=>{this.reconnectAttempt=0,this.shortLivedConnections=0},5e3))},r.onmessage=e=>{if(s()){this.armSilenceTimer(r);try{this.handleFrame(r,JSON.parse(e.data))}catch(e){console.error("[ChatSession] Failed to parse message:",e)}}},r.onclose=e=>{let r;if(!s())return;this.ws=null,this.set({isConnected:!1}),this.clearSilenceTimer(),this.stabilityTimer&&(clearTimeout(this.stabilityTimer),this.stabilityTimer=null);let n=4e3===e.code,i=this.connectionStartedAt?Date.now()-this.connectionStartedAt:0;if(this.connectionStartedAt=null,!n&&i>0&&i<5e3){if(this.shortLivedConnections++,this.shortLivedConnections>=3)return this.lastStartFailed?void this.set({error:"Unable to connect to remote server. Please check the server configuration."}):(TH.delete(this.key),this.reconnectAttempt=0,this.shortLivedConnections=0,this.set({session:null,error:null}),void this.startSession())}else i>=5e3&&(this.shortLivedConnections=0);if(this.finished||1e3===e.code)return;if(this.reconnectAttempt>=10)return void this.set({error:"Unable to connect to server."});let a=(r=Math.min(3e4,1e3*Math.pow(2,this.reconnectAttempt)))+r*Math.random()*.25;this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.state.session?.id&&!this.finished&&this.connect(!0)},a)},r.onerror=()=>{}}handleFrame(e,r){if(!("keepalive"in r)){if("JsonPatch"in r){var s,n;this.container=(s=this.container,n=r.JsonPatch,C8(s,e=>{for(let r of n){let{op:s,path:n,value:i}=r;if("/entries"===n&&"replace"===s&&i?.type==="ENTRY"&&i.content?.type==="system"&&i.content?.content==="__CLEAR_ALL__"){e.entries=[];continue}if(n.startsWith("/entries/")){let r=parseInt(n.replace("/entries/",""),10);if(isNaN(r)||i?.type!=="ENTRY")continue;switch(s){case"add":for(;e.entries.length<=r;)e.entries.push(null);e.entries[r]=i.content;break;case"replace":r<e.entries.length&&(e.entries[r]=i.content);break;case"remove":r<e.entries.length&&e.entries.splice(r,1)}}else"/status"===n&&i?.type==="STATUS"&&(e.status=i.content)}})),this.replaying||this.flush();return}if("Ready"in r){this.replaying=!1,this.flush(),this.set({isInitialized:!0,streamEpoch:this.state.streamEpoch+1});return}if("finished"in r){this.finished=!0,e.close(1e3,"finished");return}if("openPreviewFrame"in r)return void(0,j3.openPreviewFrame)(r.openPreviewFrame.projectId,r.openPreviewFrame.url);if("WorkflowRunUpdated"in r)return void this.set({workflowRunUpdate:r.WorkflowRunUpdated});if("browserCommand"in r){let s=r.browserCommand;(0,j3.sendCommandToIframe)(this.projectId,{type:"vibedeckx-command",...s}).then(r=>{r&&e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"browser_result",result:{id:s.id,success:r.success??!1,error:r.error,content:r.content,found:r.found,tag:r.tag,text:r.text}}))});return}"error"in r&&(this.set({error:r.error}),"Session not found"===r.error&&(TH.delete(this.key),TU.delete(this.key),this.finished=!0))}}flush(){let e=this.container.entries.filter(Boolean),r=this.container.status;this.set({messages:e,status:r}),this.state.session&&Tq(this.key,{session:this.state.session,messages:e,status:r})}clearSilenceTimer(){this.silenceTimer&&(clearTimeout(this.silenceTimer),this.silenceTimer=null)}armSilenceTimer(e){this.silenceTimer&&clearTimeout(this.silenceTimer),this.silenceTimer=setTimeout(()=>{this.silenceTimer=null,e.readyState===WebSocket.OPEN&&(console.warn(`[ChatSession] No frames for 95000ms — assuming dead socket, forcing reconnect`),this.replaceSilentSocket(e))},95e3)}replaceSilentSocket(e){if(this.ws===e){this.ws=null,this.set({isConnected:!1}),this.stabilityTimer&&(clearTimeout(this.stabilityTimer),this.stabilityTimer=null),this.connectionStartedAt=null;try{e.close(4e3,"silence watchdog")}catch{}this.finished||this.connect(!0)}}onVisibilityChange;setDraft;setEventListening;sendMessage;stopGeneration;restartSession}let TX=()=>()=>{},TY=()=>TL,TG=async()=>{},TJ=()=>{};function TZ({sessionId:e,approvalId:r,tool:s,input:n,resolved:i}){let[a,o]=(0,$.useState)(null),l=function(e){if(null!==e&&"object"==typeof e){if("string"==typeof e.message)return e.message;if("string"==typeof e.prompt)return e.prompt}return JSON.stringify(e)}(n),c=async s=>{if(!a&&!i){o(s?"approve":"deny");try{await ry.api.chatToolApproval(e,r,s)}finally{o(null)}}};return(0,z.jsx)("div",{className:"mx-4 my-1",children:(0,z.jsxs)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 space-y-2",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)(sS,{className:"h-3.5 w-3.5 text-amber-500 shrink-0"}),(0,z.jsxs)("span",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:["Approval needed · ","spawnAgentSession"===s?"Start a new coding agent":"Send to the coding agent"]})]}),(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all text-foreground/80",style:{fontSize:"var(--conv-font-size, 12px)"},children:l}),i?(0,z.jsxs)(so,{variant:"default",className:"approved"===i?"bg-green-600 hover:bg-green-700 text-white":"bg-red-600 hover:bg-red-700 text-white",children:["approved"===i?(0,z.jsx)(sZ,{className:"h-3 w-3 mr-1"}):(0,z.jsx)(s1,{className:"h-3 w-3 mr-1"}),"approved"===i?"Approved — sent.":"Denied — not sent."]}):(0,z.jsxs)("div",{className:"flex gap-2",children:[(0,z.jsxs)(W.Button,{onClick:()=>c(!0),disabled:null!==a,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:["approve"===a?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,z.jsx)(sZ,{className:"h-3.5 w-3.5 mr-1"}),"Approve"]}),(0,z.jsxs)(W.Button,{onClick:()=>c(!1),disabled:null!==a,variant:"destructive",size:"sm",children:["deny"===a?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,z.jsx)(s1,{className:"h-3.5 w-3.5 mr-1"}),"Deny"]})]})]})})}let TQ=(0,$.createContext)({markReviewRunRead:()=>{}}),T0=TQ.Provider,T1=new Set(["preparing","waiting_reviewer","waiting_feedback","discussing","sending_feedback","waiting_rereview"]),T2={ship:{text:"ship",className:"border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400"},"needs-changes":{text:"needs-changes",className:"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-400"},"cannot-verify":{text:"cannot-verify",className:"border-border bg-muted text-muted-foreground"}};function T5(e){if(!e.loop_id)return null;let r=e.round??1;return e.max_rounds?`第 ${r} / ${e.max_rounds} 轮`:`第 ${r} 轮`}function T3(e){return null!=e.max_rounds&&(e.round??1)>e.max_rounds}function T4(e){return e.map(e=>e.id).sort().join(",")}function T6({projectId:e,branch:r,runUpdate:s,streamEpoch:n,onRunsChange:i}){let[a,o]=(0,$.useState)([]),[l,c]=(0,$.useState)({}),[d,u]=(0,$.useState)({}),[h,f]=(0,$.useState)(null),[p,m]=(0,$.useState)(null),g=(0,$.useRef)(0),{markReviewRunRead:x}=(0,$.useContext)(TQ),[v,y]=(0,$.useState)(()=>({projectId:e,branch:r}));(v.projectId!==e||v.branch!==r)&&(y({projectId:e,branch:r}),m(null));let b=(0,$.useRef)(0),w=(0,$.useRef)(null),_=(0,$.useRef)({projectId:e,branch:r});(0,$.useEffect)(()=>{_.current={projectId:e,branch:r}},[e,r]);let S=(0,$.useCallback)(async s=>{if(!e)return;let n=++b.current,a=Rd(e,r,s);try{let e=await a.request;if(n!==b.current)return;w.current={at:a.issuedAt,runs:e},o(e),i?.(e),m(r=>{if(!r)return r;let s=e.find(e=>e.id===r.runId)??null;return(s?.status??null)===r.status&&(s||T4(e)===r.signature)?r:null})}catch{}},[e,r,i]),j=(0,$.useRef)(null);(0,$.useEffect)(()=>{let e=null!==j.current&&j.current!==n;j.current=n,S({force:e})},[S,n]),(0,$.useEffect)(()=>{s&&S({force:!0})},[s,S]),(0,$.useEffect)(()=>{if(0===a.length)return;let e=setInterval(()=>void S({force:!0}),5e3);return()=>clearInterval(e)},[a.length,S]),(0,$.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&S({force:!0})};return document.addEventListener("visibilitychange",e),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("online",e)}},[S]);let k=async(s,n,i)=>{let a=++g.current;f(s),m(null);let o=null;try{await i()}catch(e){o=e instanceof Error?e.message:String(e)}finally{f(null),S({force:!0})}if(!o)return void x(s,{runEnded:"finalize"!==n&&"rereview"!==n});let l=null;if(e){let s=Rd(e,r,{force:!0}),n=await s.request.catch(()=>null),i=w.current;l=i&&i.at>=s.issuedAt?i.runs:n}if(_.current.projectId!==e||_.current.branch!==r||a!==g.current)return;let c=l?.find(e=>e.id===s)??null;m({runId:s,status:c?.status??null,message:(l?function(e,r){if("cancel"===e)return null;if(!r)return"这次 review 已经结束了 —— 反馈可能已经发出,或者 run 已被取消。";if("approve"===e){if("discussing"===r.status)return"reviewer 已进入讨论:先点「生成终稿」拿到新的结论,再发送反馈。";if("waiting_reviewer"===r.status)return"reviewer 正在重新出稿,等它完成后再发送。";if("sending_feedback"===r.status)return"反馈正在发送中。"}if("finalize"===e){if("waiting_feedback"===r.status)return"终稿已经出来了,直接发送反馈即可。";if("waiting_reviewer"===r.status)return"reviewer 正在出稿,稍候再试。"}if("accept"===e){if("discussing"===r.status)return"reviewer 已进入讨论:先点「生成终稿」拿到新的结论。";if("waiting_reviewer"===r.status)return"reviewer 正在重新出稿,等它完成后再决定。";if("sending_feedback"===r.status)return"反馈正在发送中。"}if("rereview"===e){if("waiting_rereview"===r.status)return null;if("waiting_reviewer"===r.status)return"复审已经发起,reviewer 正在审查。";if("waiting_feedback"===r.status)return"这一轮复审已经出结论了。"}return null}(n,c):null)??o,signature:T4(l??[])})},C=a.filter(e=>T1.has(e.status)),N=p&&!C.some(e=>e.id===p.runId)?p:null;return 0!==C.length||N?(0,z.jsxs)("div",{className:"shrink-0 border-b bg-muted/30 px-4 py-2 space-y-2 max-h-[50vh] overflow-y-auto",children:[N&&(0,z.jsxs)("div",{className:"flex items-start justify-between gap-2 text-destructive",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{children:N.message}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon-sm","aria-label":"关闭提示",onClick:()=>m(null),children:(0,z.jsx)(t7,{className:"h-3 w-3"})})]}),C.map(e=>(0,z.jsxs)("div",{className:"space-y-2",style:{fontSize:"var(--conv-font-size, 14px)"},children:[(0,z.jsxs)("div",{className:"flex items-center justify-between",children:[(0,z.jsxs)("span",{className:"font-medium",children:["Review",e.review_focus?` — ${e.review_focus}`:"",(0,z.jsxs)("span",{className:"ml-2 text-muted-foreground",children:["preparing"===e.status&&"准备中…","waiting_reviewer"===e.status&&"reviewer 审查中…","waiting_feedback"===e.status&&"等你确认反馈","discussing"===e.status&&"讨论中","sending_feedback"===e.status&&"发送中…","waiting_rereview"===e.status&&"等你确认复审"]}),T5(e)&&(0,z.jsx)("span",{className:"ml-2 text-muted-foreground",children:T5(e)})]}),(0,z.jsxs)(W.Button,{variant:"ghost",size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"cancel",()=>ry.api.cancelWorkflowRun(e.id)),children:[(0,z.jsx)(t7,{className:"h-3 w-3 mr-1"}),"结束"]})]}),e.error&&(0,z.jsx)("div",{className:"text-amber-600",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.error}),"preparing"===e.status&&(0,z.jsxs)("div",{className:"flex items-center text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)(sC,{className:"h-3 w-3 mr-1 animate-spin"})," 正在蒸馏上下文并启动 reviewer"]}),"waiting_reviewer"===e.status&&(0,z.jsxs)("div",{className:"flex items-center text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)(sC,{className:"h-3 w-3 mr-1 animate-spin"})," reviewer session 正在工作"]}),"discussing"===e.status&&(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)("span",{className:"text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:"与 reviewer 讨论后,生成终稿再发送"}),(0,z.jsx)(W.Button,{size:"icon-sm",variant:"outline","aria-label":"生成 review 终稿",disabled:h===e.id,onClick:()=>k(e.id,"finalize",()=>ry.api.workflowRunGate(e.id,"finalize")),children:(0,z.jsx)(NY,{className:"h-3 w-3"})})]}),"waiting_rereview"===e.status&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("div",{className:"text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:T3(e)?`source 已按反馈完成修改。已达上限 ${e.max_rounds} 轮——要再加一轮吗?`:"source 已按反馈完成修改。由同一个 reviewer 复审这次修改?"}),(0,z.jsxs)("div",{className:"flex gap-2",children:[(0,z.jsx)(W.Button,{size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"rereview",()=>ry.api.workflowRunGate(e.id,"rereview",void 0,{extend:T3(e)})),children:T3(e)?"再加一轮":`发起第 ${e.round??2} 轮复审`}),(0,z.jsx)(W.Button,{variant:"outline",size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"cancel",()=>ry.api.cancelWorkflowRun(e.id)),children:"结束循环"})]})]}),"waiting_feedback"===e.status&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{className:"text-muted-foreground",children:"reviewer 结论"}),e.verdict?(0,z.jsx)("span",{className:`rounded border px-1.5 py-px font-mono ${T2[e.verdict].className}`,children:T2[e.verdict].text}):(0,z.jsx)("span",{className:"rounded border border-dashed px-1.5 py-px text-muted-foreground",children:"未识别,请自行判断"})]}),d[e.id]?(0,z.jsx)(rc,{className:"font-mono min-h-28 max-h-72",style:{fontSize:"var(--conv-font-size, 12px)"},value:l[e.id]??e.feedback_snapshot??"",onChange:r=>c(s=>({...s,[e.id]:r.target.value}))}):(0,z.jsx)("div",{className:"border rounded-md bg-background px-3 py-2 max-h-72 overflow-y-auto",style:{fontSize:"var(--conv-font-size, 12px)"},children:(0,z.jsx)(cE,{children:l[e.id]??e.feedback_snapshot??""})}),(0,z.jsxs)("div",{className:"flex gap-2",children:["ship"===e.verdict&&(0,z.jsx)(W.Button,{size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"accept",()=>ry.api.workflowRunGate(e.id,"accept")),children:"接受并结束"}),(0,z.jsx)(W.Button,{size:"sm",variant:"ship"===e.verdict?"outline":"default",disabled:h===e.id,onClick:()=>k(e.id,"approve",()=>ry.api.workflowRunGate(e.id,"approve",l[e.id]??void 0)),children:"ship"===e.verdict?"仍发送反馈":"发送反馈给原 session"}),(0,z.jsx)(W.Button,{variant:"outline",size:"sm",disabled:h===e.id,onClick:()=>u(r=>({...r,[e.id]:!r[e.id]})),children:d[e.id]?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(_P,{className:"h-3 w-3 mr-1"}),"预览"]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(rx,{className:"h-3 w-3 mr-1"}),"编辑"]})})]})]}),p?.runId===e.id&&(0,z.jsx)("div",{className:"text-destructive",style:{fontSize:"var(--conv-font-size, 12px)"},children:p.message})]},e.id))]}):null}let T7=(0,e_.default)("radio",[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);function T8({messages:e}){let{scrollToBottom:r}=cB(),s=(0,$.useRef)(e.length);return(0,$.useEffect)(()=>{let n=s.current;if(s.current=e.length,!(e.length<=n))for(let s=n;s<e.length;s++){let n=e[s];if("user"===n.type&&n.content.startsWith("[Executor Event:"))return void r({animation:"instant"})}},[e,r]),null}let T9=(0,$.forwardRef)(function({projectId:e,branch:r},s){let{session:n,messages:i,status:a,isInitialized:o,isLoading:l,error:c,sendMessage:d,stopGeneration:u,restartSession:h,workflowRunUpdate:f,streamEpoch:p,draft:m,setDraft:g,setEventListening:x}=function(e,r){let s=e?TW(e,r):null,[n,i]=(0,$.useState)(()=>e?new TV(e,r):null);return(n?.key??null)!==s&&i(e?new TV(e,r):null),(0,$.useEffect)(()=>{if(n)return n.start(),()=>n.stop()},[n]),{...(0,$.useSyncExternalStore)(n?.subscribe??TX,n?.getSnapshot??TY,n?.getSnapshot??TY),sendMessage:n?.sendMessage??TG,stopGeneration:n?.stopGeneration??TG,restartSession:n?.restartSession??TG,setDraft:n?.setDraft??TJ,setEventListening:n?.setEventListening??TG}}(e,r),{settings:v}=(0,mo.useConversationSettings)(),[y,b]=(0,$.useState)([]);(0,$.useImperativeHandle)(s,()=>({sendMessage:async e=>{let r=e.trim();r&&await d(r)}}),[d]);let w=n?.eventListeningEnabled??!1,_="running"===a,S=(0,$.useCallback)(async e=>{let r=e.text.trim();r&&(g(""),await d(r))},[d,g]);return e?(0,z.jsxs)("div",{className:"h-full flex flex-col min-h-0",style:{"--conv-font-size":`${v.chatFontSize}px`},children:[(0,z.jsxs)("div",{className:"flex-shrink-0 flex items-center justify-between px-4 h-10 border-b border-border/60 bg-muted/20",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)(sR,{className:"h-3.5 w-3.5 text-primary"}),(0,z.jsx)("span",{className:"text-xs font-medium text-foreground",children:"Main Chat"}),_&&(0,z.jsx)(sC,{className:"h-3 w-3 animate-spin text-primary/60"})]}),n&&(0,z.jsxs)("div",{className:"flex items-center gap-1",children:[(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:async()=>{try{await x(!w)}catch{gS.toast.error("Failed to toggle event listening")}},className:`h-7 w-7 ${w?"text-amber-500":""}`,title:w?"Listening to executor events (click to disable)":"Listen to executor events (click to enable)",children:(0,z.jsx)(T7,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:()=>h(),disabled:_,className:"h-7 w-7",title:"New Conversation",children:(0,z.jsx)(Rf,{className:"h-3.5 w-3.5"})})]})]}),(0,z.jsx)(T6,{projectId:e,branch:r,runUpdate:f,streamEpoch:p,onRunsChange:b}),(0,z.jsxs)(cz,{className:"flex-1 min-h-0",initial:"instant",children:[(0,z.jsx)(T8,{messages:i}),(0,z.jsxs)(c$,{className:"gap-4 p-4",children:[l&&0===i.length&&(0,z.jsx)("div",{className:"flex items-center justify-center py-8",children:(0,z.jsx)(sC,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),!l&&o&&0===i.length&&(0,z.jsxs)("div",{className:"text-center py-16",children:[(0,z.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mb-4",children:(0,z.jsx)(sR,{className:"h-6 w-6 text-primary/60"})}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Start a conversation"}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Chat with the AI assistant about your project"})]}),i.map((s,i)=>{if("turn_end"===s.type)return(0,z.jsxs)("div",{className:"mx-4 my-3 flex items-center gap-2","aria-hidden":!0,children:[(0,z.jsx)("div",{className:"h-px flex-1 bg-border"}),(0,z.jsx)("div",{className:"h-1 w-1 shrink-0 rounded-full bg-border"}),(0,z.jsx)("div",{className:"h-px flex-1 bg-border"})]},i);if("user"===s.type&&s.content.startsWith("[System Invariant Violation]")){let e=s.content.replace(/^\[System Invariant Violation\]\n?/,"");return(0,z.jsxs)("div",{className:"mx-4 my-2 flex gap-2 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2",children:[(0,z.jsx)(s7,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)("div",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:"System invariant correction"}),(0,z.jsx)("div",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:e})]})]},i)}if("user"===s.type){let n=s.event,a=n?.kind==="agent_task_completed"&&y.some(e=>e.source_session_id===n.sessionId||e.reviewer_session_id===n.sessionId);return(0,z.jsxs)("div",{children:[(0,z.jsx)(cC,{from:"user",children:(0,z.jsx)(cN,{style:{fontSize:"var(--conv-font-size, 14px)"},children:s.content})}),n?.kind==="agent_task_completed"&&(0,z.jsx)("div",{className:"mt-1 flex justify-end",children:(0,z.jsx)(W.Button,{variant:"outline",size:"sm",disabled:a,title:a?"该 session 已在一个进行中的 review 里":void 0,onClick:async()=>{if(e)try{await ry.api.createWorkflowRun({projectId:e,branch:r,sourceSessionId:n.sessionId,sourceTurnEndIndex:n.turnEndEntryIndex})}catch(e){alert(e instanceof Error?e.message:String(e))}},children:"Review"})})]},i)}return"assistant"===s.type?(0,z.jsx)(cC,{from:"assistant",children:(0,z.jsx)(cN,{style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,z.jsx)(cE,{children:s.content})})},i):"tool_use"===s.type?(0,z.jsxs)("div",{className:"flex items-center gap-2 px-4 py-2 text-xs text-muted-foreground",children:[(0,z.jsx)(sA,{className:"w-3.5 h-3.5 animate-pulse"}),(0,z.jsx)("span",{children:function(e){switch(e){case"getExecutorStatus":return"Checking executor status...";case"getAgentConversation":return"Checking agent conversation...";case"listTerminals":return"Listing terminals...";case"runInTerminal":return"Sending command to terminal...";case"spawnAgentSession":return"Starting a coding agent...";case"sendToAgentSession":return"Sending a message to the agent...";default:return`Running ${e}...`}}(s.tool)})]},i):"tool_result"===s.type?(0,z.jsx)("div",{className:"px-4 py-2",children:(0,z.jsxs)("details",{className:"text-xs text-muted-foreground",children:[(0,z.jsx)("summary",{className:"cursor-pointer hover:text-foreground",children:"Tool result"}),(0,z.jsx)("pre",{className:"mt-1 p-2 bg-muted/50 rounded overflow-x-auto whitespace-pre-wrap",style:{fontSize:"var(--conv-font-size, 12px)"},children:s.output})]})},i):"tool_approval_request"===s.type?n?(0,z.jsx)(TZ,{sessionId:n.id,approvalId:s.approvalId,tool:s.tool,input:s.input,resolved:s.resolved},i):null:"error"===s.type?(0,z.jsx)("div",{className:"mx-auto max-w-[90%] rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-destructive",style:{fontSize:"var(--conv-font-size, 14px)"},children:s.message},i):null}),c&&(0,z.jsx)("div",{className:"mx-auto max-w-[90%] rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:c})]}),(0,z.jsx)(cW,{})]}),(0,z.jsxs)("div",{className:"flex-shrink-0 py-3 px-[22px]",children:[_&&(0,z.jsx)("div",{className:"flex justify-center mb-2",children:(0,z.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:u,className:"gap-1.5",children:[(0,z.jsx)(lG,{className:"h-3 w-3"}),"Stop generating"]})}),(0,z.jsxs)(DQ,{onSubmit:S,className:"w-full",children:[(0,z.jsx)(D0,{disabled:!o||_,placeholder:o?_?"Waiting for response...":"Type a message...":"Connecting...",className:"pr-12",style:{fontSize:"var(--conv-font-size, 14px)"},value:m,onChange:e=>g(e.currentTarget.value)}),(0,z.jsx)("div",{className:"pointer-events-none absolute bottom-0 right-2 flex items-center text-base md:text-sm",style:{fontSize:"var(--conv-font-size, 14px)",height:"calc(1lh + 1.5rem)"},children:(0,z.jsx)(D8,{className:"pointer-events-auto",disabled:!o||_||!m.trim()})})]})]})]}):(0,z.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(sR,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to start chatting"})]})})}),Ae=(0,e_.default)("archive-restore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);function At({task:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,onClick:o,worktrees:l,assignedBranches:c,onAssign:d}){let[u,h]=(0,$.useState)(!1),[f,p]=(0,$.useState)(e.title),m=(0,$.useRef)(null);(0,$.useEffect)(()=>{u&&(m.current?.focus(),m.current?.select())},[u]),(0,$.useEffect)(()=>{p(e.title)},[e.title]);let g=()=>{h(!1);let s=f.trim();s&&s!==e.title?r(e.id,{title:s}):p(e.title)},x="done"===e.status||"cancelled"===e.status;return(0,z.jsxs)(u5,{className:"group cursor-pointer",onClick:()=>o?.(e),children:[(0,z.jsx)(u4,{className:"w-10",onClick:e=>e.stopPropagation(),children:(0,z.jsx)(ew,{checked:"done"===e.status,onCheckedChange:s=>{r(e.id,{status:s?"done":"todo"})}})}),(0,z.jsx)(u4,{className:"font-medium",children:u?(0,z.jsx)("input",{ref:m,className:"w-full bg-transparent border-b border-primary outline-none text-sm py-0.5",value:f,onChange:e=>p(e.target.value),onBlur:g,onClick:e=>e.stopPropagation(),onKeyDown:r=>{"Enter"===r.key&&g(),"Escape"===r.key&&(p(e.title),h(!1))}}):(0,z.jsxs)("div",{children:[(0,z.jsx)("span",{className:`cursor-pointer hover:underline text-sm ${x?"line-through text-muted-foreground":""}`,onClick:e=>{e.stopPropagation(),h(!0)},children:e.title}),e.description&&(0,z.jsx)("p",{className:"text-xs text-muted-foreground truncate max-w-[400px] mt-0.5",children:e.description.length>80?e.description.slice(0,80)+"...":e.description})]})}),(0,z.jsx)(u4,{onClick:e=>e.stopPropagation(),children:(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)("button",{className:"focus:outline-none",children:(0,z.jsx)(so,{variant:"outline",className:`cursor-pointer text-xs ${sl[e.status].color}`,children:sl[e.status].label})})}),(0,z.jsx)(o1,{align:"start",children:sd.map(s=>(0,z.jsxs)(o2,{onClick:()=>r(e.id,{status:s}),children:[(0,z.jsx)("span",{className:`inline-block w-2 h-2 rounded-full mr-2 ${sl[s].color}`}),sl[s].label]},s))})]})}),(0,z.jsx)(u4,{onClick:e=>e.stopPropagation(),children:(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)("button",{className:"focus:outline-none",children:(0,z.jsx)(so,{variant:"outline",className:`cursor-pointer text-xs ${sc[e.priority].color}`,children:sc[e.priority].label})})}),(0,z.jsx)(o1,{align:"start",children:su.map(s=>(0,z.jsxs)(o2,{onClick:()=>r(e.id,{priority:s}),children:[(0,z.jsx)("span",{className:`inline-block w-2 h-2 rounded-full mr-2 ${sc[s].color}`}),sc[s].label]},s))})]})}),(0,z.jsx)(u4,{onClick:e=>e.stopPropagation(),children:(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)("button",{className:"focus:outline-none",children:(0,z.jsxs)(so,{variant:"outline",className:`cursor-pointer text-xs font-mono ${null!==e.assigned_branch?"bg-accent text-accent-foreground border-transparent":"text-muted-foreground"}`,children:[(0,z.jsx)(sq,{className:"h-3 w-3 mr-1"}),null!==e.assigned_branch?""===e.assigned_branch?"main":e.assigned_branch:"Unassigned"]})})}),(0,z.jsxs)(o1,{align:"start",children:[null!==e.assigned_branch&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(o2,{onClick:()=>d(e.id,null),children:"Unassign"}),(0,z.jsx)(o7,{})]}),l.filter(r=>{let s=null===r.branch?"":r.branch;return!(e.assigned_branch===s||c.has(s))}).map(r=>{let s=null===r.branch?"":r.branch,n=r.branch??"main";return(0,z.jsxs)(o2,{onClick:()=>d(e.id,s),children:[(0,z.jsx)(sq,{className:"h-3 w-3 mr-2"}),n]},s)})]})]})}),(0,z.jsx)(u4,{className:"text-muted-foreground text-[10.5px] font-mono",children:new Date(e.created_at).toLocaleDateString()}),(0,z.jsx)(u4,{className:"w-10",onClick:e=>e.stopPropagation(),children:(0,z.jsxs)("div",{className:"flex items-center gap-0.5",children:[a?(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",title:"Unarchive",onClick:()=>i(e.id),children:(0,z.jsx)(Ae,{className:"h-3.5 w-3.5 text-muted-foreground"})}):(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",onClick:()=>n(e.id),children:(0,z.jsx)(sE,{className:"h-3.5 w-3.5 text-muted-foreground"})}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",title:"Delete",onClick:()=>s(e.id),children:(0,z.jsx)(rd,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})})]})}let Ar={todo:0,in_progress:1,done:2,cancelled:3},As={urgent:0,high:1,medium:2,low:3};function An({tasks:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,worktrees:o,onAssign:l}){let[c,d]=(0,$.useState)(null),[u,h]=(0,$.useState)("asc"),[f,p]=(0,$.useState)(null),[m,g]=(0,$.useState)(!1),x=e=>{c===e?h(e=>"asc"===e?"desc":"asc"):(d(e),h("asc"))},v=(0,$.useMemo)(()=>{if(!c)return e;let r="asc"===u?1:-1;return[...e].sort((e,s)=>{switch(c){case"title":return r*e.title.localeCompare(s.title);case"status":return r*(Ar[e.status]-Ar[s.status]);case"priority":return r*(As[e.priority]-As[s.priority]);case"created_at":return r*(new Date(e.created_at).getTime()-new Date(s.created_at).getTime());default:return 0}})},[e,c,u]),y=e=>c!==e?null:"asc"===u?" ↑":" ↓",b=(0,$.useMemo)(()=>new Set(e.filter(e=>null!==e.assigned_branch).map(e=>e.assigned_branch)),[e]);return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(u0,{children:[(0,z.jsx)(u1,{children:(0,z.jsxs)(u5,{children:[(0,z.jsx)(u3,{className:"w-10"}),(0,z.jsxs)(u3,{className:"cursor-pointer select-none",onClick:()=>x("title"),children:["Title",y("title")]}),(0,z.jsxs)(u3,{className:"cursor-pointer select-none w-32",onClick:()=>x("status"),children:["Status",y("status")]}),(0,z.jsxs)(u3,{className:"cursor-pointer select-none w-28",onClick:()=>x("priority"),children:["Priority",y("priority")]}),(0,z.jsx)(u3,{className:"w-32",children:"Assign"}),(0,z.jsxs)(u3,{className:"cursor-pointer select-none w-28",onClick:()=>x("created_at"),children:["Created",y("created_at")]}),(0,z.jsx)(u3,{className:"w-10"})]})}),(0,z.jsxs)(u2,{children:[v.map(e=>(0,z.jsx)(At,{task:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,onClick:e=>{p(e),g(!0)},worktrees:o,assignedBranches:b,onAssign:l},e.id)),0===e.length&&(0,z.jsx)(u5,{children:(0,z.jsx)("td",{colSpan:7,className:"text-center text-muted-foreground py-12 text-sm",children:(0,z.jsxs)("div",{className:"flex flex-col items-center gap-1",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-foreground/60",children:"No tasks yet"}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:"Create one to get started."})]})})})]})]}),(0,z.jsx)(sh,{task:f,open:m,onOpenChange:g})]})}function Ai({open:e,onOpenChange:r,onSubmit:s}){let[n,i]=(0,$.useState)(""),[a,o]=(0,$.useState)("todo"),[l,c]=(0,$.useState)("medium");return(0,z.jsx)(t8,{open:e,onOpenChange:r,children:(0,z.jsxs)(rs,{className:"sm:max-w-md max-h-[85vh] flex flex-col",children:[(0,z.jsx)(rn,{children:(0,z.jsx)(ra,{children:"Create Task"})}),(0,z.jsxs)("form",{onSubmit:e=>{e.preventDefault(),n.trim()&&(s({description:n.trim(),status:a,priority:l}),i(""),o("todo"),c("medium"),r(!1))},className:"space-y-4 overflow-y-auto min-h-0 px-0.5",children:[(0,z.jsx)("div",{className:"space-y-2",children:(0,z.jsx)(rc,{placeholder:"Describe the task...",value:n,onChange:e=>i(e.target.value),className:"max-h-[40vh] focus-visible:border-input focus-visible:ring-0",rows:3,autoFocus:!0})}),(0,z.jsxs)("div",{className:"flex gap-3",children:[(0,z.jsxs)("div",{className:"flex-1 space-y-1",children:[(0,z.jsx)("label",{className:"text-xs text-muted-foreground",children:"Status"}),(0,z.jsxs)(fd,{value:a,onValueChange:e=>o(e),children:[(0,z.jsx)(fh,{children:(0,z.jsx)(fu,{})}),(0,z.jsx)(ff,{children:sd.map(e=>(0,z.jsx)(fp,{value:e,children:sl[e].label},e))})]})]}),(0,z.jsxs)("div",{className:"flex-1 space-y-1",children:[(0,z.jsx)("label",{className:"text-xs text-muted-foreground",children:"Priority"}),(0,z.jsxs)(fd,{value:l,onValueChange:e=>c(e),children:[(0,z.jsx)(fh,{children:(0,z.jsx)(fu,{})}),(0,z.jsx)(ff,{children:su.map(e=>(0,z.jsx)(fp,{value:e,children:sc[e].label},e))})]})]})]}),(0,z.jsxs)(ri,{children:[(0,z.jsx)(W.Button,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),(0,z.jsx)(W.Button,{type:"submit",disabled:!n.trim(),children:"Create"})]})]})]})})}let Aa=[{value:"all",label:"All"},{value:"todo",label:"Todo"},{value:"in_progress",label:"Doing"},{value:"done",label:"Done"},{value:"cancelled",label:"Cancelled"},{value:"archived",label:"Archived"}];function Ao({projectId:e,tasks:r,loading:s,worktrees:n,onCreateTask:i,onUpdateTask:a,onDeleteTask:o,onArchiveTask:l,onUnarchiveTask:c}){let[d,u]=(0,$.useState)(!1),[h,f]=(0,$.useState)("all"),p=(0,$.useMemo)(()=>r.filter(e=>null===e.archived_at),[r]),m=(0,$.useMemo)(()=>r.filter(e=>null!==e.archived_at),[r]),g=(0,$.useMemo)(()=>{let e={all:p.length,todo:0,in_progress:0,done:0,cancelled:0,archived:m.length};for(let r of p)e[r.status]++;return e},[p,m]),x=(0,$.useMemo)(()=>"archived"===h?m:"all"===h?p:p.filter(e=>e.status===h),[p,m,h]),v="archived"===h;return e?(0,z.jsxs)("div",{className:"flex flex-col h-full",children:[(0,z.jsx)(dB,{title:"Tasks",count:p.length,actions:(0,z.jsxs)(W.Button,{size:"sm",onClick:()=>u(!0),className:"shadow-sm",children:[(0,z.jsx)(eS,{className:"h-3.5 w-3.5 mr-1.5"}),"New Task"]})}),(0,z.jsx)(dz,{children:Aa.map(e=>(0,z.jsx)(d$,{active:h===e.value,count:g[e.value],onClick:()=>f(e.value),children:e.label},e.value))}),(0,z.jsx)("div",{className:"flex-1 overflow-auto px-5 edge-scrollbar",children:s?(0,z.jsx)("div",{className:"flex items-center justify-center py-12 text-muted-foreground text-sm",children:"Loading tasks..."}):(0,z.jsx)(An,{tasks:x,onUpdate:a,onDelete:o,onArchive:l,onUnarchive:c,archivedView:v,worktrees:n,onAssign:(e,r)=>{a(e,{assigned_branch:r})}})}),(0,z.jsx)(Ai,{open:d,onOpenChange:u,onSubmit:i})]}):(0,z.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(eS,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to view tasks."})]})})}var Al=e.i(115796);function Ac({open:e,onOpenChange:r,onNavigateProject:s,onNavigateWorkspace:n,onNavigateSession:i}){let[a,o]=(0,$.useState)(""),[l,c]=(0,$.useState)(null),[d,u]=(0,$.useState)(!1),h=(0,$.useRef)(null),f=(0,$.useRef)(null),p=(0,$.useRef)("");(0,$.useLayoutEffect)(()=>{p.current=a},[a]),(0,sx.useGlobalEventStream)(e=>{if("session:title"!==e.type||"string"!=typeof e.sessionId)return;let r="string"==typeof e.title?e.title.trim():"";(0,Al.updateCachedSessionTitle)(e.sessionId,r||null)});let[m,g]=(0,$.useState)(e);e!==m&&(g(e),e&&(o(""),c((0,Al.getCachedEmptyResults)()),u(!1)));let x=(0,$.useCallback)(async e=>{h.current?.abort();let r=new AbortController;h.current=r;let s=""===e?(0,Al.beginEmptyQuerySearch)():null;try{let n=await (0,ry.searchAll)(e,{signal:r.signal});r.signal.aborted||(null!==s&&(0,Al.commitEmptyQueryResults)(s,n),c(n),u(!1))}catch{r.signal.aborted||u(!0)}},[]),v=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let r=e&&!v.current;if(v.current=e,e)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>void x(a),150*!r),()=>{f.current&&clearTimeout(f.current)}},[a,e,x]),(0,$.useEffect)(()=>{if(!e)return;let r=!1;return(0,ry.refreshSearchCache)().then(()=>{r||x(p.current)}).catch(()=>{}),()=>{r=!0,h.current?.abort()}},[e,x]);let y=l?a.trim()?{sessions:l.sessions,favorites:l.favorites}:(0,Al.overlayRecents)(l):null,b=null===l,w=!!y&&0===l.projects.length&&0===l.workspaces.length&&0===y.sessions.length&&0===y.favorites.length,_=l?.cacheState==="cold",S=e=>(0,z.jsxs)(pE,{value:`session-${e.sessionId}`,onSelect:()=>i(e),children:[(0,z.jsx)(sR,{}),(0,z.jsx)("span",{className:"truncate",children:e.title??"Untitled session"}),e.favoritedAt&&(0,z.jsx)(nt,{className:"h-3.5 w-3.5 shrink-0 fill-current text-amber-500"}),(0,z.jsxs)("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:[e.projectName," · ",e.branch??"main"," · ",function(e){if(!e)return"";let r=Date.now()-e;return r<6e4?"just now":r<36e5?`${Math.floor(r/6e4)}m ago`:r<864e5?`${Math.floor(r/36e5)}h ago`:`${Math.floor(r/864e5)}d ago`}(e.lastActiveAt)]})]},e.sessionId);return(0,z.jsxs)(pS,{open:e,onOpenChange:r,title:"Quick Switcher",description:"Search projects, workspaces, and sessions",shouldFilter:!1,instantClose:!0,className:"top-[max(1rem,calc(50%_-_175px))] translate-y-0",children:[(0,z.jsx)(pj,{placeholder:"Search projects, workspaces, sessions…",value:a,onValueChange:o}),(0,z.jsxs)(pk,{children:[d&&(0,z.jsxs)("div",{className:"flex items-center justify-between gap-2 px-4 py-3 text-sm text-destructive",children:[(0,z.jsx)("span",{children:"Search failed."}),(0,z.jsx)(W.Button,{variant:"link",size:"sm",className:"h-auto p-0 text-destructive",onClick:()=>void x(p.current),children:"Retry"})]}),!d&&b&&(0,z.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"}),"Searching…"]}),!d&&!b&&w&&_&&(0,z.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"}),"Syncing history…"]}),!d&&!b&&w&&!_&&(0,z.jsx)(pC,{children:"No results found."}),l&&l.projects.length>0&&(0,z.jsx)(pN,{heading:"Projects",children:l.projects.map(e=>(0,z.jsxs)(pE,{value:`project-${e.id}`,onSelect:()=>s(e.id),children:[(0,z.jsx)(dn,{name:e.name,size:"md"}),(0,z.jsx)("span",{children:e.name}),e.path&&(0,z.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:e.path})]},e.id))}),l&&l.workspaces.length>0&&(0,z.jsx)(pN,{heading:"Workspaces",children:l.workspaces.map(e=>(0,z.jsxs)(pE,{value:`ws-${e.projectId}-${e.targetId}-${e.branch??""}`,onSelect:()=>n(e),children:[(0,z.jsx)(sq,{}),(0,z.jsx)("span",{children:e.branch??"main"}),(0,z.jsx)("span",{className:"text-xs text-muted-foreground",children:e.projectName})]},`${e.projectId}-${e.targetId}-${e.branch??""}`))}),y&&y.sessions.length>0&&(0,z.jsx)(pN,{heading:a.trim()?"Sessions":"Recent",children:y.sessions.map(S)}),y&&y.favorites.length>0&&(0,z.jsx)(pN,{heading:"Favorites",children:y.favorites.map(S)})]})]})}let Ad={session_result_ready:"/sounds/sound1.mp3",review_ready:"/sounds/sound2.mp3",session_failed:"/sounds/failure.mp3",workflow_failed:"/sounds/failure.mp3",cross_remote_token_expired:"/sounds/sound2.mp3"};function Au(e,r){let s=[...e.filter(e=>e.id!==r.id),r];return s.sort((e,r)=>r.created_at-e.created_at||(e.id<r.id?1:-1)),s}let Ah=new Set(["session_result_ready","session_failed"]);function Af(e){return Ah.has(e.kind)&&e.session_id?`${e.kind}:${e.session_id}`:e.id}function Ap(e){let r=new Map;for(let s of e){let e=null===s.read_at,n=r.get(Af(s));n?(n.ids.push(s.id),n.count+=1,e&&(n.unreadCount+=1,n.unread=!0)):r.set(Af(s),{latest:s,ids:[s.id],count:1,unreadCount:+!!e,unread:e})}return[...r.values()]}let Am=new Map,Ag=new Set,Ax=(0,e_.default)("bell",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]]),Av={session_result_ready:{label:"Session result is ready",dot:"bg-lime-400"},review_ready:{label:"Review feedback is ready",dot:"bg-emerald-500"},session_failed:{label:"Session failed",dot:"bg-destructive"},workflow_failed:{label:"Workflow needs attention",dot:"bg-destructive"},cross_remote_token_expired:{label:"Cross-remote expired — stop & send a message to renew",dot:"bg-amber-500"}};function Ay({notifications:e,unreadCount:r,projects:s,onNavigate:n,markRead:i,markAllRead:a,remove:o,clear:l}){let[c,d]=(0,$.useState)(!1);return(0,$.useEffect)(()=>{let e=e=>{"j"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),d(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),(0,z.jsxs)(oQ,{open:c,onOpenChange:d,children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsxs)(W.Button,{variant:"ghost",size:"icon-sm",className:"relative",title:"Notifications (⌘J)","aria-label":r>0?`${r} unread notifications`:"Notifications",children:[(0,z.jsx)(Ax,{className:"h-4 w-4"}),r>0&&(0,z.jsx)("span",{className:"absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[9px] font-semibold leading-none text-primary-foreground",children:r>9?"9+":r})]})}),(0,z.jsxs)(o1,{align:"end",className:"w-80 p-0",children:[(0,z.jsxs)("div",{className:"flex items-center justify-between px-3 py-2",children:[(0,z.jsx)("span",{className:"text-[12.5px] font-semibold text-foreground",children:"Notifications"}),e.length>0&&(0,z.jsxs)("div",{className:"flex items-center gap-1",children:[(0,z.jsxs)("button",{onClick:a,disabled:0===r,className:"flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40",title:"Mark all read",children:[(0,z.jsx)(di,{className:"h-3 w-3"}),"Mark all read"]}),(0,z.jsx)("button",{onClick:l,className:"rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",title:"Dismiss all (marks them read)",children:"Clear"})]})]}),(0,z.jsx)("div",{className:"max-h-[60vh] overflow-y-auto border-t border-border",children:0===e.length?(0,z.jsx)("div",{className:"px-3 py-8 text-center text-[12px] text-muted-foreground/70",children:"Nothing needs your attention."}):Ap(e).map(e=>{let r,a=e.latest,l=Av[a.kind],c=e.unread;return(0,z.jsxs)(o2,{onSelect:()=>{for(let r of e.ids)i(r);n(a.project_id,a.branch,a.session_id)},className:(0,eb.cn)("group flex flex-col items-start gap-0.5 rounded-none px-3 py-2",c&&"bg-primary/[0.08]"),children:[(0,z.jsxs)("div",{className:"flex w-full items-center gap-2",children:[(0,z.jsx)("span",{className:(0,eb.cn)("h-[7px] w-[7px] shrink-0 rounded-full",l?.dot)}),(0,z.jsx)("span",{className:(0,eb.cn)("min-w-0 flex-1 truncate text-[12.5px]",c?"font-medium text-foreground":"text-foreground/70"),children:a.body??(r=a.project_id,s.find(e=>e.id===r)?.name??"Unknown project")}),e.unreadCount>1&&(0,z.jsxs)("span",{className:"shrink-0 rounded-full bg-muted px-1.5 text-[10px] font-medium leading-4 text-muted-foreground",title:`${e.unreadCount} new notifications, showing the latest`,children:["×",e.unreadCount]}),(0,z.jsx)("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:function(e){let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return"just now";let s=Math.round(r/60);if(s<60)return`${s}m ago`;let n=Math.round(s/60);if(n<24)return`${n}h ago`;let i=Math.round(n/24);return`${i}d ago`}(a.created_at)}),(0,z.jsx)("button",{onClick:r=>{for(let s of(r.stopPropagation(),e.ids))o(s)},className:"shrink-0 rounded p-0.5 text-muted-foreground/60 opacity-0 transition-all hover:bg-muted hover:text-foreground group-hover:opacity-100",title:"Dismiss (marks it read)",children:(0,z.jsx)(t7,{className:"h-3 w-3"})})]}),(0,z.jsxs)("div",{className:"flex w-full items-center gap-1.5 pl-[15px] text-[11px] text-muted-foreground",children:[(0,z.jsx)("span",{className:"font-mono truncate",children:a.branch??"main"}),(0,z.jsx)("span",{className:"text-muted-foreground/50",children:"·"}),(0,z.jsx)("span",{className:"shrink-0",children:l?.label??a.title})]})]},a.id)})})]})]})}let Ab=(0,e_.default)("keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]),Aw=(e,r)=>e?`⌘${r}`:`Ctrl+${r}`,A_=()=>()=>{};function AS(){let[e,r]=(0,$.useState)(!1),s=(0,$.useSyncExternalStore)(A_,fb,()=>!1);return(0,$.useEffect)(()=>{let e=e=>{let s="/"===e.key&&(e.metaKey||e.ctrlKey)&&!e.shiftKey&&!e.altKey,n="?"===e.key&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!dv(e.target);(s||n)&&(e.preventDefault(),r(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(W.Button,{variant:"ghost",size:"icon-sm","aria-label":"Keyboard shortcuts",title:"Keyboard shortcuts (?)",onClick:()=>r(!0),children:(0,z.jsx)(Ab,{className:"h-4 w-4"})}),(0,z.jsx)(t8,{open:e,onOpenChange:r,children:(0,z.jsxs)(rs,{className:"sm:max-w-xl",children:[(0,z.jsx)(rn,{children:(0,z.jsx)(ra,{children:"Keyboard shortcuts"})}),(0,z.jsx)("div",{className:"grid gap-x-8 gap-y-5 sm:grid-cols-2",children:[{title:"Global",entries:[{hints:[Aw(s,"K")],description:"Quick switcher"},{hints:[Aw(s,"J")],description:"Notifications"},{hints:[Aw(s,"B")],description:"Toggle sidebar"},{hints:[s?`⌘⇧O`:"Ctrl+Shift+O"],description:"New agent conversation"},{hints:[fj(s,fw)],description:"Start review of this session"},{hints:["a…z"],description:"Locate workspace (type, ↑↓ cycle, ↵ jump)"},{hints:["Esc"],description:"Clear locate query / unfocus right panel"},{hints:["?",Aw(s,"/")],description:"This dialog"}]},{title:"Workspace tabs",entries:[...fv.map(e=>({hints:[fj(s,e.code)],description:`Open ${e.label}`})),{hints:["←","→"],description:"Switch executor target (Executors focused)"}]}].map(e=>(0,z.jsxs)("section",{children:[(0,z.jsx)("h3",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:e.title}),(0,z.jsx)("ul",{className:"space-y-1.5",children:e.entries.map(e=>(0,z.jsxs)("li",{className:"flex items-center justify-between gap-3 text-[13px]",children:[(0,z.jsx)("span",{className:"text-foreground/90",children:e.description}),(0,z.jsx)("span",{className:"flex shrink-0 items-center gap-1",children:e.hints.map(e=>(0,z.jsx)("kbd",{className:"rounded-md border border-border bg-muted px-1.5 py-0.5 font-mono text-[11px] leading-none text-foreground/80",children:e},e))})]},e.description))})]},e.title))})]})})]})}function Aj(e){if(null===e)return"尚未连接";let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return`${r} 秒前`;let s=Math.floor(r/60);return s<60?`${s} 分钟前`:`${Math.floor(s/60)} 小时前`}function Ak(){let{state:e,lastEventAt:r,updateAvailable:s,reconnect:n}=(0,sx.useConnectionStatus)(),[,i]=(0,$.useState)(0);if((0,$.useEffect)(()=>{let e=setInterval(()=>i(e=>e+1),5e3);return()=>clearInterval(e)},[]),"stale"===e)return(0,z.jsxs)("button",{type:"button",onClick:n,title:`实时更新已断开 \xb7 上次更新 ${Aj(r)} \xb7 点击重新连接`,className:"flex items-center gap-1.5 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-600 transition-colors hover:bg-amber-500/20",children:[(0,z.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500"}),"实时更新已断开"]});if(s)return(0,z.jsxs)("button",{type:"button",onClick:()=>window.location.reload(),title:"服务器已更新到新版本 · 点击刷新页面加载",className:"flex items-center gap-1.5 rounded-full border border-sky-500/40 bg-sky-500/10 px-2 py-0.5 text-[11px] font-medium text-sky-600 transition-colors hover:bg-sky-500/20",children:[(0,z.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-sky-500"}),"有新版本 · 点击刷新"]});let a="live"===e;return(0,z.jsx)("span",{title:a?`实时更新正常 \xb7 上次更新 ${Aj(r)}`:"正在连接实时更新…",className:"flex items-center px-1","aria-label":a?"实时更新正常":"正在连接实时更新",children:(0,z.jsx)("span",{className:a?"h-1.5 w-1.5 rounded-full bg-emerald-500":"h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground/40"})})}function AC(e){return null===e?"":e}function AN(){var e,r,s,n,i,a,o,l,c;let d,u,h,f,p,m,g,x,v,y,b,w,_,S,j,k,C,{projectId:N,tab:E,branch:D,threadId:R}=function(){let[e,r]=(0,$.useState)(RO);return(0,$.useEffect)(()=>{let e=()=>r(RO());return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]),e}(),{config:T}=(0,p2.useAppConfig)(),[A,I]=(0,$.useState)(()=>({branch:D,sessionId:new URLSearchParams(window.location.search).get("session")})),M=A.branch,F=A.sessionId,P=(0,$.useCallback)(e=>{I({branch:e,sessionId:null}),Z(null)},[]),L=(0,$.useCallback)(e=>{I(r=>r.sessionId===e?r:{...r,sessionId:e})},[]),[O,B]=(0,$.useState)(null),[H,U]=(0,$.useState)(null),[q,K]=(0,$.useState)(void 0),[V,X]=(0,$.useState)(void 0),[Y,G]=(0,$.useState)(null),[J,Z]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search).get("session");I(r=>r.sessionId===e?r:{...r,sessionId:e})};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]),(0,$.useEffect)(()=>{if(new URLSearchParams(window.location.search).has("project")){let e=RB({projectId:N,tab:E,branch:D,threadId:R});window.history.replaceState(null,"",e)}},[]);let[Q,ee]=(0,$.useState)(!1),[et,er]=(0,$.useState)(!1),[es,en]=(0,$.useState)(!1),[ei,ea]=(0,$.useState)(null),[eo,el]=(0,$.useState)(E),[ec,ed]=(0,$.useState)(R),[eu,eh]=(0,$.useState)(0),[ef,ep]=(0,$.useState)(0),[em,eg]=(0,$.useState)(!1),[ex,ev]=(0,$.useState)(!1),ey=(0,$.useRef)(null),[eb,ew]=(0,$.useState)(void 0),[e_,ej]=(0,$.useTransition)(),{projects:ek,currentProject:eC,loading:eN,addProject:eE,createProject:eD,updateProject:eR,deleteProject:eT,selectProject:eA,routeProjectPending:eI,routeProjectNotFound:eM}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(null),[a,o]=(0,$.useState)(!0),[l,c]=(0,$.useState)(e),d=(0,$.useRef)(n),u=(0,$.useRef)(e);d.current=n,u.current=e;let h=l!==e,f=a||h,p=!f&&!!e&&!r.some(r=>r.id===e),m=(0,$.useCallback)(async()=>{o(!0);try{let e=await ry.api.getProjects();if(s(e),e.length>0&&!d.current){let r=u.current?e.find(e=>e.id===u.current):e[0];i(r??null)}}finally{o(!1)}},[]);(0,$.useEffect)(()=>{m()},[m]),(0,$.useEffect)(()=>{h&&!a&&(c(e),i(e?r.find(r=>r.id===e)??null:r[0]??null))},[e,a,r,h]);let g=async e=>{let r=await ry.api.createProject(e);return s(e=>[r,...e]),i(r),r},x=(0,$.useCallback)((e,r)=>{let n=e=>"function"==typeof r?r(e):r;s(r=>r.map(r=>r.id===e?n(r):r)),i(r=>r?.id===e?n(r):r)},[]),v=(0,$.useRef)(new Map),y=async(e,s)=>{let n,i={};if(void 0!==s.agentMode&&(i.agent_mode=s.agentMode),void 0!==s.executorMode&&(i.executor_mode=s.executorMode),Object.keys(i).length>0){let s=r.find(r=>r.id===e)??d.current;(n=v.current.get(e))||!s||s.id!==e||(n={seq:0,baseline:s},v.current.set(e,n)),n&&(n.seq+=1),x(e,e=>({...e,...i}))}let a=n?.seq,o=()=>!n||n.seq===a;try{let r=await ry.api.updateProject(e,s);return o()&&(n&&v.current.delete(e),x(e,r)),r}catch(r){throw n&&o()&&(v.current.delete(e),x(e,n.baseline)),r}},b=async e=>{await ry.api.deleteProject(e),s(r=>r.filter(r=>r.id!==e)),n?.id===e&&i(r.find(r=>r.id!==e)??null)};return{projects:r,currentProject:h?null:n,routeProjectPending:f,routeProjectNotFound:p,loading:a,addProject:e=>{s(r=>[e,...r]),i(e)},createProject:g,updateProject:y,deleteProject:b,selectProject:e=>{i(e)},refresh:m}}(N),eF=(0,$.useRef)(void 0);if(eC?.id!==eb){if(void 0!==eb){let s=(e=eF.current,r=eC?.id,e&&void 0!==r&&e.projectId===r?{branch:e.branch,sessionId:e.sessionId}:{branch:null,sessionId:null});I(s),s.sessionId&&eh(e=>e+1)}ew(eC?.id)}let{worktrees:eP,loading:eL,stale:eO,listWarning:eB,refetch:ez}=function(e,r,s){let n=e?`${e}::${s??"local"}`:null,[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)(c1),[c,d]=(0,$.useState)(!0),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(null),m=(0,$.useRef)(null),g=e=>{m.current=e,h(e)},[x,v]=(0,$.useState)(null);if(n!==x){v(n),p(null);let e=n?c0.get(n):void 0;e&&(a(e),g(n),d(!0))}let y=(0,$.useRef)(0),b=(0,$.useRef)(null),w=(0,$.useRef)(0),_=(0,$.useRef)(null),S=(0,$.useRef)(r);S.current=r;let j=(0,$.useCallback)(async(r=!1)=>{if(r&&b.current)return;b.current?.abort();let s=new AbortController;b.current=s,w.current=0;let i=y.current;if(!e||!n){b.current=null,a([]),l(c1),g(null),p(null),d(!1);return}r||d(!0);let o=!1;try{let c=await ry.api.getProjectWorktreeList(e,void 0,s.signal);if(i!==y.current)return;let d=c.worktrees;c0.set(n,d),p(n),l(e=>{let r={staleRemote:c.stale??null,activeRemoteInvalid:!0===c.activeRemoteInvalid};return e.staleRemote?.serverId===r.staleRemote?.serverId&&e.activeRemoteInvalid===r.activeRemoteInvalid?e:r}),o=!0,a(e=>{let s=r?function(e,r,s){if(void 0===s||r.some(e=>e.branch===s))return r;let n=e.findIndex(e=>e.branch===s);if(n<0)return r;let i=[...r];return i.splice(Math.min(n,i.length),0,e[n]),i}(e,d,S.current):d;return e.length===s.length&&e.every((e,r)=>e.branch===s[r].branch&&e.currentBranch===s[r].currentBranch&&e.expectedBranch===s[r].expectedBranch&&cQ(e)===cQ(s[r]))?e:s})}catch(e){if(i!==y.current||e instanceof Error&&"AbortError"===e.name)return;console.error("Failed to fetch worktrees:",e),r||m.current===n||a([{branch:null}])}finally{if(i!==y.current||b.current!==s)return;o&&(w.current=Date.now()),g(n),r||d(!1),b.current=null}},[e,n]),k=(0,$.useCallback)(()=>{Date.now()-w.current<5e3||j(!0)},[j]);return(0,$.useEffect)(()=>(j(),()=>{b.current?.abort(),b.current=null,y.current+=1}),[j]),(0,$.useEffect)(()=>{let e=_.current;_.current={projectId:n,branch:r},e&&e.projectId===n&&e.branch!==r&&j(!0)},[n,r,j]),(0,sx.useGlobalEventStream)(r=>{if(!e||r.projectId!==e)return;let s="session:status"===r.type&&("stopped"===r.status||"error"===r.status);("session:taskCompleted"===r.type||"executor:stopped"===r.type||s)&&j(!0)}),(0,$.useEffect)(()=>{let e=null,r=()=>{null!==e&&(window.clearInterval(e),e=null)},s=()=>{r(),e=window.setInterval(()=>void j(!0),3e5)},n=()=>k(),i=()=>{"visible"===document.visibilityState?(k(),s()):r()};return window.addEventListener("focus",n),document.addEventListener("visibilitychange",i),"visible"===document.visibilityState&&s(),()=>{r(),window.removeEventListener("focus",n),document.removeEventListener("visibilitychange",i)}},[j,k]),{worktrees:i,loading:c||f!==n,stale:u!==n,listWarning:o,refetch:(0,$.useCallback)(()=>j(!1),[j])}}(eC?.id??null,M,eC?.agent_mode??null),{statuses:e$,rootDirty:eW,defaultTarget:eH,repositoryLabel:eU,repositoryServerId:eq,setTarget:eK,refetch:eV}=function(e,r){let[s,n]=(0,$.useState)(new Map),[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(null),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(0),[m,g]=(0,$.useState)(e);e!==m&&(g(e),n(new Map),a(!1),l(null),d(null));let x=(0,$.useCallback)(()=>p(e=>e+1),[]);return(0,$.useEffect)(()=>{let s,i=r.map(e=>e.branch).filter(e=>null!==e),o=new Set(i),c=(s=r.find(e=>null===e.branch))?(void 0===s.currentBranch?s.expectedBranch:s.currentBranch)??null:null,u=i.map(e=>({branch:e}));null===c||o.has(c)||u.push({branch:c});let f=!1;return(async()=>{if(!e||0===u.length){f||(n(new Map),a(!1),l(null),d(null));return}if(c5(e).length>0&&(await function(e){let r=c3.get(e);if(r)return r;let s=(async()=>{let r=new Map;for(;;){let s=c5(e).filter(({key:e,target:s})=>r.get(e)!==s);if(0===s.length)break;for(let{key:n,branch:i,target:a}of s){r.set(n,a);let s=!1;try{s=await ry.api.setMergeTarget(e,i,a,{ifAbsent:!0})}catch{}if(s)try{localStorage.getItem(n)===a&&localStorage.removeItem(n)}catch{}}}})();return c3.set(e,s),s.finally(()=>{c3.get(e)===s&&c3.delete(e)}),s}(e),f))return;let r=await ry.api.getMergeStatus(e,u);f||r.ok&&(n(function(e){let r=new Map;for(let s of e){if("target-not-found"===s.error&&s.requestedTarget){r.set(s.branch,{branch:s.branch,error:s.error,requestedTarget:s.requestedTarget,targetSource:s.targetSource});continue}!s.error&&s.target&&s.status&&r.set(s.branch,{branch:s.branch,status:s.status,unmergedCount:s.unmergedCount??0,dirty:s.dirty??!1,target:s.target})}return r}(r.entries.filter(e=>o.has(e.branch)).map(e=>e.branch===c?{...e,dirty:!1}:e))),a(null!==c&&(r.entries.find(e=>e.branch===c)?.dirty??!1)),l(function(e){for(let r of e)if("default"===r.targetSource&&r.target)return r.target;return null}(r.entries)),d(r.repository.label),h("local"===r.repository.kind?"local":r.repository.remoteServerId))})(),()=>{f=!0}},[e,r,f,x]),{statuses:s,rootDirty:i,defaultTarget:o,repositoryLabel:c,repositoryServerId:u,setTarget:(0,$.useCallback)((r,s)=>{e&&ry.api.setMergeTarget(e,r,s).then(e=>{e&&x()})},[e,x]),refetch:x}}(eC?.id??null,eP),eX=function(e,r){let[s,n]=(0,$.useState)(()=>TA(e));s.projectId!==e&&n(TA(e));let i=(0,$.useRef)(e);(0,$.useEffect)(()=>{i.current=e},[e]);let a=(0,$.useRef)(new Map),o=(0,$.useRef)(new Map),[l,c]=(0,$.useState)(0),d=(0,$.useRef)(new Set),u=(0,$.useCallback)(e=>{n(r=>{let s=Date.now();return TF(e(r,s),d.current,s)})},[]),h=(0,$.useCallback)((e,r)=>{let s=i.current;if(!s)return;let n=`${s}\0${e??""}`,l=(a.current.get(n)??0)+1;a.current.set(n,l);let{request:c,issuedAt:d}=Rd(s,e,{force:r});c.then(r=>{i.current!==s||(o.current.get(n)??0)>=l||(o.current.set(n,l),u((s,n)=>(function(e,r,s,n,i=n){let a=e;for(let e of s)a=TM(a,e,n);let o=new Set(s.map(e=>e.id)),l=[];for(let e of a.entries.values())(e.branch??null)===(r??null)&&(o.has(e.runId)||e.insertedAt>i||l.push(e.runId));return l.length>0?TI(a,l,n):a})(s,e,r,n,d)))}).catch(()=>{})},[u]);(0,$.useEffect)(()=>{e&&h(r,!1)},[e,r,h]);let{state:f}=(0,sx.useConnectionStatus)(),p=(0,$.useRef)(null),m=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let s=p.current;p.current=f;let n=TC(s,f,m.current);"live"===f&&(m.current=!0),n&&e&&h(r,!0)},[f,e,r,h]),(0,sx.useGlobalEventStream)(r=>{if("workflow:run-updated"!==r.type||!e||r.projectId!==e)return;let s=r.run;s&&"string"==typeof s.id&&u((e,r)=>TM(e,s,r))});let g=(0,$.useCallback)((e,r)=>{u((s,n)=>TM(s,e,n,r))},[u]),x=(0,$.useCallback)(e=>{d.current=e,n(r=>TF(r,e,Date.now()))},[]),v=(0,$.useMemo)(()=>[...s.entries.values()],[s]),y=JSON.stringify([...new Set(v.filter(e=>null===e.appearedAt).map(e=>e.branch??""))].sort());(0,$.useEffect)(()=>{let e=JSON.parse(y);if(0===e.length)return;let r=setInterval(()=>{for(let r of(n(e=>(function(e,r){let s=[];for(let n of e.entries.values())n.insertedAt+72e4<=r&&s.push(n.runId);let n=s.length>0?TI(e,s,r):e,i=!1;for(let e of n.tombstones.values())if(e<=r){i=!0;break}if(i){let e=new Map;for(let[s,i]of n.tombstones)i>r&&e.set(s,i);n={...n,tombstones:e}}return n})(e,Date.now())),e))h(""===r?null:r,!0);c(e=>e+1)},5e3);return()=>clearInterval(r)},[y,h]);let b=(0,$.useMemo)(()=>v.filter(e=>null===e.appearedAt&&"preparing"!==e.run.status&&!TR(e.run.status)).map(e=>e.reviewerSessionId),[v]);return(0,$.useMemo)(()=>({entries:v,addRun:g,awaitedSessionIds:b,pollTick:l,markAppeared:x}),[v,g,b,l,x])}(eC?.id??null,M),eY=function(e,r,s,n){let i=JSON.stringify((r??[]).map(e=>e.branch)),a=(0,$.useMemo)(()=>JSON.parse(i),[i]),[o,l]=(0,$.useState)([]),[c,d]=(0,$.useState)(null);e!==c&&(d(e),l(e?TN.get(e)??[]:[]));let u=(0,$.useRef)(e);u.current=e;let h=(0,$.useRef)(new Map),f=(0,$.useRef)(0),p=(0,$.useRef)(0),m=(0,$.useRef)(0),g=(0,$.useCallback)(e=>!(e<m.current)&&(m.current=e,!0),[]);(0,$.useEffect)(()=>{e&&TN.set(e,o)},[e,o]);let[x,v]=(0,$.useState)(null),y=(0,$.useCallback)((e,r,s,n=1/0)=>{if(null===r||u.current!==e)return;let i=r.filter(e=>{let r=h.current.get(e.id);return void 0===r||r<=n});l(e=>{let r,n=(r=new Map(e.map(e=>[e.id,e])),i.map(e=>{let s=r.get(e.id);return s&&"New Session"===e.title&&"New Session"!==s.title?{...e,title:s.title}:e}));if(!s||n.some(e=>e.id===s))return n;let a=e.find(e=>e.id===s);return a?[a,...n]:n})},[]),b=(0,$.useCallback)(async r=>{if(!e)return void l([]);let s=f.current,n=++p.current,i=await Tj(e);if(u.current===e&&g(n)){if("incomplete"===i)return void v(r=>({projectId:e,gen:(r?.gen??0)+1}));v(r=>r?.projectId===e?null:r),y(e,i,r?.keepSessionId,s)}},[e,y,g]);(0,$.useEffect)(()=>{let e=!1;return b().catch(r=>{e||console.warn("[ResidentSessions] refresh failed:",r)}),()=>{e=!0}},[b]),(0,$.useEffect)(()=>{if(!e||x?.projectId!==e)return;let r=!1,s=f.current,n=++p.current;return Tk(e,a).then(i=>{!r&&g(n)&&y(e,i,void 0,s)}).catch(e=>{r||console.warn("[ResidentSessions] fallback refresh failed:",e)}),()=>{r=!0}},[e,x,a,y,g]);let{state:w}=(0,sx.useConnectionStatus)(),_=(0,$.useRef)(null),S=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let e=_.current;_.current=w;let r=TC(e,w,S.current);"live"===w&&(S.current=!0),r&&b().catch(e=>console.warn("[ResidentSessions] reconnect refresh failed:",e))},[w,b]);let j=n&&n.sessionIds.length>0?`${n.tick}#${n.sessionIds.join("\0")}`:"",k=(0,$.useRef)(o);return(0,$.useEffect)(()=>{k.current=o},[o]),(0,$.useEffect)(()=>{!j||j.slice(j.indexOf("#")+1).split("\0").every(e=>k.current.some(r=>r.id===e))||b().catch(e=>console.warn("[ResidentSessions] awaited refresh failed:",e))},[j,b]),(0,$.useEffect)(()=>{if(!s||!s.processAlive||!e||s.projectId!==e||h.current.has(s.id))return;let r=!k.current.some(e=>e.id===s.id);l(e=>(function(e,r){let s=e.findIndex(e=>e.id===r.id);if(-1===s)return[r,...e];let n=e[s],i="New Session"===r.title&&"New Session"!==n.title?n.title:r.title,a=[...e];return a[s]={...r,title:i,status:n.status},a})(e,s)),r&&b({keepSessionId:s.id}).catch(e=>console.warn("[ResidentSessions] seed refresh failed:",e))},[e,s,b]),(0,sx.useGlobalEventStream)(r=>{if(e&&r.projectId===e){if("session:process"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null,s="boolean"==typeof r.alive?r.alive:null,n="string"==typeof r.branch?r.branch:null;if(!e||null===s)return;if(!s){h.current.set(e,++f.current),l(r=>r.filter(r=>r.id!==e));return}h.current.delete(e),b().catch(e=>console.warn("[ResidentSessions] process refresh failed:",e)),null!==n&&l(r=>r.map(r=>r.id===e?{...r,branch:n}:r))}if("session:status"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null,s="string"==typeof r.status?r.status:null;if(!e||!s)return;l(r=>r.map(r=>r.id===e?{...r,status:s}:r))}if("session:title"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null;if(!e)return;l(s=>{var n,i;return i=("string"==typeof(n=r.title)?n.trim():"")||"New Session",s.map(r=>r.id===e?{...r,title:i}:r)})}}}),(0,$.useMemo)(()=>{let e=new Map;for(let r of o){let s=r.branch??"",n=e.get(s)??[];n.push(r),e.set(s,n)}for(let r of e.values())r.sort((e,r)=>(r.updated_at??"").localeCompare(e.updated_at??""));return e},[o])}(eC?.id??null,eP,O,{sessionIds:eX.awaitedSessionIds,tick:eX.pollTick}),eG=(0,$.useMemo)(()=>{let e=new Set;for(let r of eY.values())for(let s of r)e.add(s.id);return e},[eY]),eJ=(0,$.useCallback)(e=>{for(let r of eY.values()){let s=r.find(r=>r.id===e);if(s)return s.title}return null},[eY]),eZ=(0,$.useMemo)(()=>(function(e,r,s){if(0===r.length)return e;let n=new Map(e),i=new Set;for(let r of e.values())for(let e of r)i.add(e.id);for(let e of r){var a;if(null!==e.appearedAt||i.has(e.reviewerSessionId))continue;let r=e.branch??"",o=n.get(r)??[];n.set(r,[(a=s(e.sourceSessionId),{id:e.reviewerSessionId,projectId:e.projectId,branch:e.branch,title:TP(e,a),status:"preparing",processAlive:!1,updated_at:e.run.created_at,kind:TE,runId:e.runId}),...o])}return n})(eY,eX.entries,eJ),[eY,eX.entries,eJ]),eQ=null!==J&&J.projectId===eC?.id,e0=eQ?eX.entries.find(e=>e.runId===J.runId):void 0,{tasks:e1,loading:e2,createTask:e5,updateTask:e3,deleteTask:e4,archive:e6,unarchive:e7,refetch:e8}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(!0),a=(0,$.useCallback)(async()=>{if(!e){s([]),i(!1);return}try{let r=await ry.api.getTasks(e,{includeArchived:!0});s(r)}catch(e){console.error("Failed to fetch tasks:",e)}finally{i(!1)}},[e]);(0,$.useEffect)(()=>{a()},[a]);let o=(0,$.useCallback)(async r=>{if(!e)return null;try{let n=await ry.api.createTask(e,r);return s(e=>[...e,n]),n}catch(e){return console.error("Failed to create task:",e),null}},[e]),l=(0,$.useCallback)(async(e,n)=>{s(r=>r.map(r=>r.id===e?{...r,...n,updated_at:new Date().toISOString()}:r));try{let r=await ry.api.updateTask(e,n);return s(s=>s.map(s=>s.id===e?r:s)),r}catch(e){return console.error("Failed to update task:",e),s(r),null}},[r]),c=(0,$.useCallback)(async e=>{s(r=>r.filter(r=>r.id!==e));try{await ry.api.deleteTask(e)}catch(e){console.error("Failed to delete task:",e),s(r)}},[r]),d=(0,$.useCallback)(async e=>{s(r=>r.map(r=>r.id===e?{...r,archived_at:Date.now()}:r));try{let r=await ry.api.archiveTask(e);s(s=>s.map(s=>s.id===e?r:s))}catch(e){console.error("Failed to archive task:",e),s(r)}},[r]),u=(0,$.useCallback)(async e=>{s(r=>r.map(r=>r.id===e?{...r,archived_at:null}:r));try{let r=await ry.api.unarchiveTask(e);s(s=>s.map(s=>s.id===e?r:s))}catch(e){console.error("Failed to unarchive task:",e),s(r)}},[r]),h=(0,$.useCallback)(async n=>{if(e){s(n.map(e=>r.find(r=>r.id===e)).filter(e=>void 0!==e));try{await ry.api.reorderTasks(e,n)}catch(e){console.error("Failed to reorder tasks:",e),s(r)}}},[e,r]);return{tasks:r,loading:n,createTask:o,updateTask:l,deleteTask:c,archive:d,unarchive:u,reorderTasks:h,refetch:a}}(eC?.id??null),{schedules:e9,loading:te,createSchedule:tt,updateSchedule:tr,deleteSchedule:ts,runNow:tn}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(!1),[a,o]=(0,$.useState)(null);e!==a&&(o(e),s(e?c6.get(e)??[]:[])),(0,$.useEffect)(()=>{e&&c6.set(e,r)},[e,r]);let l=(0,$.useRef)(e),c=(0,$.useRef)(0),d=(0,$.useCallback)(async(e,r,n)=>{if(!e){c.current===r&&(s([]),i(!1));return}n&&i(!0);try{let n=await ry.api.getSchedules(e);c.current===r&&s(n)}catch(e){console.error("Failed to fetch schedules:",e)}finally{n&&c.current===r&&i(!1)}},[]);(0,$.useEffect)(()=>{l.current=e,c.current+=1,d(e,c.current,!0)},[e,d]);let u=(0,$.useCallback)(async()=>{let e=l.current;e&&await d(e,c.current,!1)},[d]),h=(0,$.useRef)(u);(0,$.useEffect)(()=>{h.current=u},[u]),(0,sx.useGlobalEventStream)(e=>{!e.type?.startsWith("schedule:")||l.current&&e.projectId===l.current&&h.current()});let f=(0,$.useCallback)(async r=>{if(!e)throw Error("No project selected");let s=await ry.api.createSchedule(e,r);return await u(),s},[e,u]),p=(0,$.useCallback)(async(e,r)=>{let s=await ry.api.updateSchedule(e,r);return await u(),s},[u]),m=(0,$.useCallback)(async e=>{await ry.api.deleteSchedule(e),await u()},[u]),g=(0,$.useCallback)(async(e,r)=>{let s=r;if(!s){let e=crypto.randomUUID();s={requestId:e,runId:e}}let n=await ry.api.runScheduleNow(e,s);return await u(),n},[u]);return{schedules:r,loading:n,refetch:u,createSchedule:f,updateSchedule:p,deleteSchedule:m,runNow:g}}(eC?.id??null),[ti,ta]=(0,$.useState)(null),[to,tl]=(0,$.useState)(null),[tc,td]=(0,$.useState)(!1),[tu,th]=(0,$.useState)(null),{activity:tf,since:tp,refetch:tm,setOptimisticActivity:tg}=function(e){let[r,s]=(0,$.useState)(new Map),[n,i]=(0,$.useState)(new Map),a=(0,$.useRef)(new Map),o=(0,$.useRef)(new Map),l=(0,$.useRef)(null),c=(0,$.useCallback)(async()=>{if(!e){s(new Map),i(new Map),o.current=new Map,l.current=null,a.current=new Map;return}try{let r=await (0,ry.authFetch)(`${"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}/api/projects/${e}/branches/activity`);if(!r.ok)return;let n=await r.json(),c=l.current!==e,{nextActivity:d,nextSince:u}=function(e,r,s,n){let i=new Map,a=new Map,o=[];for(let l of e){let e=l.branch??"",c=s.get(e)??0;if(!n&&l.since<c){let s=r.get(e);if(void 0!==s){i.set(e,s),a.set(e,c);continue}}i.set(e,l.activity),a.set(e,l.since),n||r.get(e)===l.activity||o.push(l.branch)}return{nextActivity:i,nextSince:a,transitions:o}}(n.branches,o.current,a.current,c);s(d),i(u),o.current=d,l.current=e,a.current=u}catch{}},[e]);return(0,$.useEffect)(()=>{c()},[c]),(0,sx.useGlobalEventStream)(r=>{var n,l,c;let d,u;if("branch:activity"!==r.type||!e||r.projectId!==e)return;let h=(n=r,l=o.current,c=a.current,d=n.branch??"",u=c.get(d)??0,n.since<u?{kind:"stale"}:l.get(d)===n.activity?{kind:"redundant",key:d}:{kind:"transition",key:d});"stale"===h.kind||(a.current.set(h.key,r.since),i(new Map(a.current)),"redundant"!==h.kind&&s(e=>{let s=new Map(e);return s.set(h.key,r.activity),o.current=s,s}))}),{activity:r,since:n,refetch:c,setOptimisticActivity:(0,$.useCallback)((e,r)=>{s(s=>{let n=function(e,r,s){let n=r??"";if(e.get(n)===s)return e;let i=new Map(e);return i.set(n,s),i}(s,e,r);return o.current=n,n})},[])}}(eC?.id??null),{rules:tx,createRule:tv,updateRule:ty,deleteRule:tb}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),o=(0,$.useCallback)(async()=>{if(!e){n([]),a(!1);return}try{let s=await ry.api.getRules(e,r);n(s)}catch(e){console.error("Failed to fetch rules:",e)}finally{a(!1)}},[e,r]);(0,$.useEffect)(()=>{o()},[o]);let l=(0,$.useCallback)(async s=>{if(!e)return null;try{let i=await ry.api.createRule(e,{...s,branch:r});return n(e=>[...e,i]),i}catch(e){return console.error("Failed to create rule:",e),null}},[e,r]),c=(0,$.useCallback)(async(e,r)=>{n(s=>s.map(s=>s.id===e?{...s,...r,enabled:void 0!==r.enabled?+!!r.enabled:s.enabled,updated_at:new Date().toISOString()}:s));try{let s=await ry.api.updateRule(e,r);return n(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update rule:",e),n(s),null}},[s]),d=(0,$.useCallback)(async e=>{n(r=>r.filter(r=>r.id!==e));try{await ry.api.deleteRule(e)}catch(e){console.error("Failed to delete rule:",e),n(s)}},[s]);return{rules:s,loading:i,createRule:l,updateRule:c,deleteRule:d,refetch:o}}(eC?.id??null,M),{commands:tw,createCommand:t_,updateCommand:tS,deleteCommand:tj}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),o=(0,$.useCallback)(async()=>{if(!e){n([]),a(!1);return}try{let s=await ry.api.getCommands(e,r);n(s)}catch(e){console.error("Failed to fetch commands:",e)}finally{a(!1)}},[e,r]);(0,$.useEffect)(()=>{o()},[o]);let l=(0,$.useCallback)(async s=>{if(!e)return null;try{let i=await ry.api.createCommand(e,{...s,branch:r});return n(e=>[...e,i]),i}catch(e){return console.error("Failed to create command:",e),null}},[e,r]),c=(0,$.useCallback)(async(e,r)=>{n(s=>s.map(s=>s.id===e?{...s,...r,updated_at:new Date().toISOString()}:s));try{let s=await ry.api.updateCommand(e,r);return n(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update command:",e),n(s),null}},[s]),d=(0,$.useCallback)(async e=>{n(r=>r.filter(r=>r.id!==e));try{await ry.api.deleteCommand(e)}catch(e){console.error("Failed to delete command:",e),n(s)}},[s]);return{commands:s,loading:i,createCommand:l,updateCommand:c,deleteCommand:d,refetch:o}}(eC?.id??null,M),tk=(0,$.useRef)(null),tC=(0,$.useSyncExternalStore)(Nu,Nh,Nf),tN=eC?.id??null,tE=eC?.agent_mode??null,tD=(0,$.useCallback)(e=>!!tN&&tC.has(Np(tN,e,tE)),[tC,tN,tE]),tR=(0,$.useCallback)(e=>{if(tN)return tC.get(Np(tN,e,tE))},[tC,tN,tE]),tT=(0,$.useCallback)(e=>tp.get(AC(e)),[tp]),tA=(0,$.useMemo)(()=>(function(e,r,s,n){let i=new Map;if(!e)return i;for(let a of e){let e=AC(a.branch),o=r.get(e);if(!s?.(a.branch)){i.set(e,o??"idle");continue}if("main-running"===o)i.set(e,"main-running");else if("main-completed"===o){let r=n?.backendSince?.(a.branch)??0,s=n?.placeholderSince?.(a.branch)??0;i.set(e,s>r?"idle":"main-completed")}else i.set(e,"idle")}return i})(eP,tf,tD,{backendSince:tT,placeholderSince:tR}),[eP,tf,tD,tT,tR]);o=eV,l=tA,c=eC?.id??null,d=(0,$.useRef)(new Set),h=(u=function(e){let r=new Set;if(!e)return r;for(let[s,n]of e)c4.has(n)&&r.add(s);return r}(l)).size>0,f=JSON.stringify(Array.from(u).sort()),(0,$.useEffect)(()=>{let e=new Set(JSON.parse(f)),r=d.current;d.current=e,function(e,r){for(let s of e)if(!r.has(s))return!0;return!1}(r,e)&&o()},[f,o]),(0,$.useEffect)(()=>{let e=()=>o();return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[o]),(0,sx.useGlobalEventStream)(e=>{"executor:stopped"===e.type&&e.projectId===c&&o(),"merge-target:updated"===e.type&&null!==c&&e.projectId===c&&o(),"files:changed"===e.type&&null!==c&&e.projectId===c&&o()}),(0,$.useEffect)(()=>{let e=null,r=()=>{null!==e&&(clearInterval(e),e=null)},s=()=>{r(),e=setInterval(o,h?3e4:6e4)},n=()=>{"visible"===document.visibilityState?s():r()};return"visible"===document.visibilityState&&s(),document.addEventListener("visibilitychange",n),()=>{r(),document.removeEventListener("visibilitychange",n)}},[o,h]);let[tI,tM]=(0,$.useState)(null),{notifications:tF,unreadCount:tP,markRead:tL,markAllRead:tO,remove:tB,clear:tz,markReviewRunRead:t$}=function(e){let[r,s]=(0,$.useState)([]),n=(0,$.useRef)(new Set),i=(0,$.useRef)(new Set),a=(0,$.useRef)(r);(0,$.useEffect)(()=>{a.current=r},[r]);let o=(0,$.useRef)(new Set);(0,$.useEffect)(()=>{for(let e of new Set(Object.values(Ad)))Am.has(e)||Ag.has(e)||(Ag.add(e),(async()=>{try{let r=await fetch(e),s=await r.blob(),n=new Audio(URL.createObjectURL(s));n.preload="auto",n.load(),Am.set(e,n)}catch{}finally{Ag.delete(e)}})())},[]);let l=(0,$.useRef)(e);(0,$.useEffect)(()=>{l.current=e},[e]);let c=(0,$.useCallback)(e=>{if(i.current.has(e))return;i.current.add(e);let r=Date.now();s(s=>s.map(s=>s.id===e&&null===s.read_at?{...s,read_at:r}:s)),(0,ry.markNotificationRead)(e).catch(()=>{s(s=>s.map(s=>s.id===e&&s.read_at===r?{...s,read_at:null}:s))}).finally(()=>{i.current.delete(e)})},[]),d=(0,$.useCallback)(e=>null===e.read_at&&null!==e.workflow_run_id&&o.current.has(e.workflow_run_id)?((0,ry.markNotificationRead)(e.id).catch(()=>{}),{...e,read_at:Date.now()}):e,[]);(0,$.useEffect)(()=>{let e=!1;return(0,ry.getNotifications)({limit:100}).then(r=>{if(e)return;for(let e of r)n.current.add(e.id);let i=r.map(d);s(e=>{let r=[];for(let e of i)r=Au(r,e);for(let s of e)i.some(e=>e.id===s.id)||(r=Au(r,s));return r});try{window.localStorage.removeItem("vibedeckx:completion-notifications")}catch{}}).catch(e=>{console.warn("[notifications] hydration failed:",e)}),()=>{e=!0}},[d]),(0,sx.useGlobalEventStream)(e=>{var r;let i;if("notification:created"!==e.type)return;let a=e.notification;if(!a?.id)return;let c=!n.current.has(a.id);n.current.add(a.id);let d=l.current,u=null!==a.session_id&&a.session_id===d,h=null!==a.workflow_run_id&&o.current.has(a.workflow_run_id);c&&!h&&(r=Ad[a.kind],(i=Am.get(r))||((i=new Audio(r)).preload="auto",Am.set(r,i)),i.currentTime=0,i.play().catch(()=>{}));let f=u||h;s(e=>Au(e,f?{...a,read_at:a.read_at??Date.now()}:a)),f&&null===a.read_at&&(0,ry.markNotificationRead)(a.id).catch(()=>{})}),(0,$.useEffect)(()=>{if(e)for(let n of r){if(n.session_id!==e||null!==n.read_at||i.current.has(n.id))continue;let{id:r}=n;i.current.add(r),(0,ry.markNotificationRead)(r).then(()=>{s(e=>e.map(e=>e.id===r&&null===e.read_at?{...e,read_at:Date.now()}:e))}).catch(()=>{}).finally(()=>{i.current.delete(r)})}},[e,r]);let u=(0,$.useCallback)(e=>c(e),[c]),h=(0,$.useCallback)((e,r)=>{for(let s of(r?.runEnded&&o.current.add(e),a.current))s.workflow_run_id===e&&null===s.read_at&&c(s.id)},[c]),f=(0,$.useCallback)(()=>{let e=Date.now();s(r=>r.some(e=>null===e.read_at)?r.map(r=>null===r.read_at?{...r,read_at:e}:r):r),(0,ry.markAllNotificationsRead)().catch(()=>s(r))},[r]),p=(0,$.useCallback)(e=>{c(e),s(r=>r.filter(r=>r.id!==e))},[c]),m=(0,$.useCallback)(()=>{(0,ry.markAllNotificationsRead)().catch(e=>console.warn("[notifications] read-all failed:",e)),s(e=>e.length?[]:e)},[]),g=Ap(r).reduce((e,r)=>e+ +!!r.unread,0);return{notifications:r,unreadCount:g,markRead:u,markAllRead:f,remove:p,clear:m,markReviewRunRead:h}}("workspace"===eo?tI:null),tW=(0,$.useMemo)(()=>({markReviewRunRead:t$}),[t$]),tH=(0,$.useMemo)(()=>tF.filter(e=>e.project_id===eC?.id&&null===e.read_at).length,[tF,eC?.id]),tU=(0,$.useCallback)(()=>{tg(M,"working")},[M,tg]),tq=(0,$.useCallback)(()=>{e8()},[e8]),tK=(0,$.useCallback)((e,r)=>{I({branch:e,sessionId:r}),Z(null),eh(e=>e+1),eg(!1),(0,Al.touchRecentSessionOpen)(r)},[]),tV=(0,$.useCallback)((e,r,s)=>{Z({projectId:e,runId:r}),I({branch:s,sessionId:null}),eh(e=>e+1),eg(!1),el("workspace")},[]),tX=(0,$.useCallback)(e=>{"preparing-review"===e.kind&&e.runId?tV(e.projectId,e.runId,e.branch):(tK(e.branch,e.id),el("workspace"))},[tK,tV]),tY=(0,$.useCallback)(e=>{let r=eX.entries.find(r=>r.runId===e);r&&tV(r.projectId,r.runId,r.branch)},[eX.entries,tV]),tG=eX.markAppeared;(0,$.useEffect)(()=>{tG(eG)},[eG,tG]),(0,$.useEffect)(()=>{if(!J)return;if(J.projectId!==eC?.id)return void Z(null);let e=e0?null!==e0.appearedAt?{kind:"switch",branch:e0.branch,sessionId:e0.reviewerSessionId}:"preparing"===e0.run.status?{kind:"wait"}:TR(e0.run.status)?{kind:"gone"}:eG.has(e0.reviewerSessionId)?{kind:"switch",branch:e0.branch,sessionId:e0.reviewerSessionId}:{kind:"wait"}:{kind:"gone"};"switch"===e.kind&&tK(e.branch,e.sessionId)},[J,e0,eG,eC?.id,tK]);let tJ=(0,$.useCallback)(e=>{tm();let r=ek.find(r=>r.id===e.projectId);(0,Al.touchSessionStarted)({sessionId:e.id,projectId:e.projectId,projectName:r?.name??"",targetId:r?.agent_mode??"local",branch:e.branch});let s=function(e,r=new Date){return!0!==e.processAlive?null:{id:e.id,projectId:e.projectId,branch:e.branch,title:"New Session",status:e.status,processAlive:!0,updated_at:r.toISOString()}}(e);s&&B(s)},[tm,ek]),tZ=(0,$.useCallback)((e,r)=>{r.trim()&&(0,Al.updateCachedSessionTitle)(e,r.trim())},[]),tQ=(0,$.useCallback)(()=>{tg(M,"idle")},[M,tg]),t0=(0,$.useCallback)(()=>{e8()},[e8]);s=eC?.id??null,n={onTaskChanged:t0},p=(0,$.useRef)(n.onTaskChanged),(0,$.useEffect)(()=>{p.current=n.onTaskChanged}),(0,sx.useGlobalEventStream)(e=>{s&&e.projectId===s&&("task:created"===e.type||"task:updated"===e.type||"task:deleted"===e.type)&&p.current?.()});let t1=(0,$.useMemo)(()=>{let e=AC(M);return e1.find(r=>r.assigned_branch===e)??null},[e1,M]);(0,$.useCallback)(e=>{ej(async()=>{await ey.current?.submitMessage(e.description??e.title)})},[]),(0,$.useCallback)(e=>{e3(e,{assigned_branch:null})},[e3]),(0,$.useEffect)(()=>{let e=eF.current;if(void 0!==e&&e.projectId!==eC?.id&&(eF.current=void 0,eg(!1),ev(!1)),!eO&&0!==eP.length){if(void 0!==e&&e.projectId===eC?.id){if(eP.some(r=>r.branch===e.branch)){eF.current=void 0,M!==e.branch||F!==e.sessionId?e.sessionId?tK(e.branch,e.sessionId):P(e.branch):e.sessionId&&(0,Al.touchRecentSessionOpen)(e.sessionId),ev(!1),eg(!1);return}if(eL)return;eF.current=void 0,eg(!1),ev(!1),gS.toast.warning(`Workspace "${e.branch??"main"}" no longer exists`),P(eP[0].branch);return}!eL&&(eP.some(e=>e.branch===M)||(F&&gS.toast.warning(`Workspace "${M??"main"}" no longer exists`),P(eP[0].branch)))}},[eP,eL,eO,M,F,eC?.id,tK,P]),(0,$.useEffect)(()=>{(em||ex)&&(null===M&&(eL||0!==eP.length)||(eg(!1),ev(!1)))},[em,ex,M,eL,eP]);let t2=(0,$.useCallback)((e,r,s=null)=>{if(el("workspace"),e===eC?.id)return void(s?tK(r,s):P(r));let n=ek.find(r=>r.id===e);n&&(s?eg(!0):ev(!0),eF.current={projectId:e,branch:r,sessionId:s},eA(n))},[eC?.id,ek,eA,tK,P]),[t5,t3]=(0,$.useState)(!1);(0,$.useEffect)(()=>{let e=e=>{if("k"===e.key&&(e.metaKey||e.ctrlKey)){e.preventDefault(),t3(e=>!e);return}"o"===e.key.toLowerCase()&&e.shiftKey&&(e.metaKey||e.ctrlKey)&&"workspace"===eo&&(e.preventDefault(),eh(e=>e+1),ey.current?.startNewConversation())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[eo]);let t4=(0,$.useRef)(!1),t6=(0,$.useCallback)(async(e,r)=>{let s=ek.find(r=>r.id===e);if(!s)return null;let n="local"===r?"local":r;return(s.agent_mode??"local")!==n?eR(s.id,{agentMode:n}):s},[ek,eR]),t7=(i={projectId:eC?.id??null,resolveProjectForTarget:t6,getScheduleRun:ry.api.getScheduleRun,getSchedules:ry.api.getSchedules,runScheduleNow:tn,selectAgentSession:(e,r)=>{el("workspace"),tK(e,r)},openScheduleRun:(e,r)=>{ta(e),tl(r),el("schedules")},onRerunResult:e=>{e.replay&&e.status&&"starting"!==e.status&&"running"!==e.status?"completed"===e.status?gS.toast.success("Schedule run already completed"):gS.toast.error(`Schedule run already ${e.status}`):gS.toast.success("Schedule run started")},onError:(e,r)=>{console.error(`Project activity ${e} failed:`,r),"session-navigation"===e?gS.toast.error("Failed to open agent session"):"schedule-navigation"===e?gS.toast.error("Failed to open schedule run"):gS.toast.error(r instanceof Error?r.message:"Failed to start schedule run")}},(m=(0,$.useRef)(i)).current=i,(g=(0,$.useRef)({projectId:i.projectId,generation:0})).current.projectId!==i.projectId&&(g.current={projectId:i.projectId,generation:g.current.generation+1}),x=(0,$.useRef)(new Map),v=(0,$.useRef)(new Map),y=(0,$.useCallback)(e=>g.current.projectId===e.projectId&&g.current.generation===e.generation,[]),b=(0,$.useCallback)(async(e,r)=>{if(!e.projectId)return null;let s=m.current,n=await s.getScheduleRun(r);if(!y(e))return null;if(n.project_id!==e.projectId)throw Error("Schedule run does not belong to the active project");let i=await s.getSchedules(e.projectId);if(!y(e))return null;let a=i.find(e=>e.id===n.schedule_id);if(!a||a.project_id!==e.projectId)throw Error("Schedule does not belong to the active project");return{run:n,schedule:a}},[y]),w=(0,$.useCallback)(async(e,r,s)=>{let n={...g.current};if(n.projectId)try{let i=await m.current.resolveProjectForTarget(n.projectId,r);if(!y(n)||!i||i.id!==n.projectId)return;m.current.selectAgentSession(s,e,i.id)}catch(e){y(n)&&m.current.onError("session-navigation",e)}},[y]),_=(0,$.useCallback)(async(e,r)=>{let s={...g.current};try{let n=await b(s,e);if(!n||!y(s))return;if(r&&r!==n.schedule.id)throw Error("Schedule run target changed while opening");m.current.openScheduleRun(n.schedule.id,e)}catch(e){y(s)&&m.current.onError("schedule-navigation",e)}},[y,b]),S=(0,$.useCallback)(e=>{let r={...g.current};if(!r.projectId)return Promise.resolve();let s=`${r.projectId}:${e}`,n=v.current.get(s);if(n)return n;let i=(async()=>{try{let n,i=c7(r.projectId,e),a=x.current.get(i)??function(e,r,s){try{let n=window.sessionStorage.getItem(e);if(!n)return;let i=JSON.parse(n);return"string"==typeof i.requestId&&"string"==typeof i.runId&&i.projectId===r&&"string"==typeof i.scheduleId&&i.scheduleId.length>0&&i.sourceRunId===s?i:void 0}catch{return}}(i,r.projectId,e);if(a){let e=await m.current.getSchedules(r.projectId);if(!y(r))return;let s=a.scheduleId,o=e.find(e=>e.id===s);if(!o||o.project_id!==r.projectId)throw Error("Schedule does not belong to the active project");n=o,x.current.set(i,a)}else{let o=await b(r,e);if(!o||!y(r))return;n=o.schedule;let l=crypto.randomUUID();a={projectId:r.projectId,scheduleId:n.id,requestId:l,runId:l,sourceRunId:e},x.current.set(i,a);var s=a;try{window.sessionStorage.setItem(i,JSON.stringify(s))}catch{}}let o={requestId:a.requestId,runId:a.runId,sourceRunId:a.sourceRunId},l=await m.current.runScheduleNow(n.id,o);if(x.current.delete(i),c8(i),!y(r))return;m.current.onRerunResult(l)}catch(s){if(r.projectId&&("object"==typeof s&&null!==s&&"status"in s&&409===s.status||"object"==typeof s&&null!==s&&"durable"in s&&!0===s.durable)){let s=c7(r.projectId,e);x.current.delete(s),c8(s)}throw y(r)&&m.current.onError("schedule-rerun",s),s}})().finally(()=>{v.current.get(s)===i&&v.current.delete(s)});return v.current.set(s,i),i},[y,b]),{openAgentSession:w,openScheduleRun:_,runScheduleAgain:S}),t8=(a={projectId:eC?.id??null,schedules:e9,getTask:ry.api.getTask,resolveProjectForTarget:t6,openTask:th,selectAgentSession:(e,r)=>{el("workspace"),tK(e,r)},selectWorkspace:e=>{P(e),el("workspace")},selectSchedule:e=>{ta(e),el("schedules")},openScheduleRun:t7.openScheduleRun,onError:e=>{gS.toast.error(e instanceof Error?e.message:"Unable to open Context item")}},(j=(0,$.useRef)(a)).current=a,(k=(0,$.useRef)({projectId:a.projectId,generation:0})).current.projectId!==a.projectId&&(k.current={projectId:a.projectId,generation:k.current.generation+1}),C=(0,$.useCallback)(e=>e.projectId===k.current.projectId&&e.generation===k.current.generation,[]),{open:(0,$.useCallback)(async e=>{let r={...k.current},s=e.navigation;if(!r.projectId||e.deleted||!s){C(r)&&j.current.onError(Error("This Context item is no longer available"));return}try{if("task"===s.kind){let e=await j.current.getTask(r.projectId,s.taskId);if(!C(r))return;if(e.id!==s.taskId||e.project_id!==r.projectId)throw Error("Task is no longer available in this project");j.current.openTask(e);return}if("agent_session"===s.kind||"workspace"===s.kind){let e=await j.current.resolveProjectForTarget(r.projectId,s.target);if(!C(r))return;if(!e||e.id!==r.projectId)throw Error("Workspace target is no longer available");"agent_session"===s.kind?j.current.selectAgentSession(s.branch,s.sessionId,e.id):j.current.selectWorkspace(s.branch,e.id);return}if("schedule"===s.kind){let e=j.current.schedules.find(e=>e.id===s.scheduleId&&e.project_id===r.projectId);if(!e)throw Error("Schedule is no longer available in this project");j.current.selectSchedule(e.id);return}await j.current.openScheduleRun(s.runId,s.scheduleId)}catch(e){C(r)&&j.current.onError(e)}},[C])}),t9=(0,$.useCallback)(e=>{ed(e),P(null),el("project-chat")},[P]),re=(0,$.useCallback)(()=>{ed(null),el("project-info")},[]);(0,$.useEffect)(()=>{el(E),ed("project-chat"===E?R:null),"project-chat"===E&&P(null)},[E,R,P]);let rt=(0,$.useCallback)(e=>{tl(r=>r===e?null:r)},[]),rr=(0,$.useCallback)(e=>{if(t4.current)return;let r=ek.find(r=>r.id===e);r&&(t3(!1),eA(r),el("project-info"))},[ek,eA]),rs=(0,$.useCallback)(async e=>{if(!t4.current){t4.current=!0,t3(!1);try{let r=await t6(e.projectId,e.targetId);if(!r)return;el("workspace"),r.id===eC?.id?P(e.branch):(ev(!0),eF.current={projectId:r.id,branch:e.branch,sessionId:null},eA(r))}catch(e){console.error("Quick switcher navigation failed:",e),gS.toast.error("Failed to open workspace")}finally{t4.current=!1}}},[eC?.id,t6,eA,P]),rn=(0,$.useCallback)(async e=>{if(!t4.current){t4.current=!0,t3(!1);try{let r=await t6(e.projectId,e.targetId);if(!r)return;(0,Al.touchRecentSessionOpen)(e.sessionId,e),el("workspace"),r.id===eC?.id?tK(e.branch,e.sessionId):(eg(!0),eF.current={projectId:r.id,branch:e.branch,sessionId:e.sessionId},eA(r))}catch(e){console.error("Quick switcher navigation failed:",e),gS.toast.error("Failed to open session")}finally{t4.current=!1}}},[eC?.id,t6,eA,tK]);(0,$.useEffect)(()=>{if(eN||eI||eM)return;let e=RB({projectId:eC?.id,tab:eo,branch:M,threadId:ec});if(F){let r=new URL(e,window.location.origin);r.searchParams.set("session",F),window.history.replaceState(null,"",r.pathname+r.search)}else window.history.replaceState(null,"",e)},[eC?.id,eo,M,ec,eN,eI,eM,F]);let ri=(0,$.useCallback)(e=>{ez(),P(e)},[ez,P]),ra=(0,$.useCallback)((e,r)=>{e.branch&&(K(e),X(r),er(!0))},[]),ro=(0,$.useCallback)(e=>{let r=null===e?void 0:eP.find(r=>r.branch===e),s=eC?.agent_mode??"local",n=r?.machines?.find(e=>e.serverId===s);r?.branch&&n?.state==="absent"?G({branch:r.branch,current:n,presentOn:r.machines.filter(e=>"present"===e.state)}):(n?.state==="creating"&&gS.toast.info(`'${e}' is still being created on ${n.name}`),P(e))},[eP,eC?.agent_mode,P]),rl=(0,$.useRef)({content:"",at:0}),rc=(0,$.useCallback)(e=>{let r=Date.now(),s=rl.current;s.content===e&&r-s.at<600||(rl.current={content:e,at:r},tk.current?.sendMessage(e))},[]),rd=(0,$.useCallback)(()=>{let e=`Please perform the following git operations for this worktree:
30
+ ${r}`},[ef,te]),tu=(0,$.useCallback)(async(e,r)=>{if(!tr||null!==ta)return;let s=td(r);if(null===s)return void gS.toast.error("This turn has no text answer to send back");to(e);try{await (0,ry.sendAgentSessionMessage)(tr,s),ti(r=>new Set(r).add(e)),gS.toast.success("Sent back to source session"),i?.(tr)}catch(s){let e=s instanceof Error?s.message:String(s),r=e.includes("404");r&&tc(!0),gS.toast.error("Send back failed",{description:r?"The source session no longer exists":e})}finally{to(null)}},[tr,ta,td,i]),th=(0,$.useMemo)(()=>{for(let e=ef.length-1;e>=0;e--)if(ef[e]?.type==="turn_end")return e;return -1},[ef]),tf="running"===ep&&ef.length>0&&"turn_end"!==ef[ef.length-1].type,tp=function(e,r,s,n,i){let a=s&&s.projectId===e&&s.branch===r?s.id:null,[o,l]=(0,$.useState)(null),c=(0,$.useRef)(0),d=(0,$.useRef)(null),[u,h]=(0,$.useState)({runUpdate:null,sessionId:null});(u.runUpdate!==n||u.sessionId!==a)&&(h({runUpdate:n,sessionId:a}),n&&n.reviewer_session_id===a&&l(R5.has(n.status)?n:null)),(0,$.useLayoutEffect)(()=>{n&&n.reviewer_session_id===a&&c.current++},[n,a]);let[f,p]=(0,$.useState)({projectId:null,sessionId:null});return(f.projectId!==e||f.sessionId!==a)&&(p({projectId:e,sessionId:a}),l(null)),(0,$.useEffect)(()=>{if(!e||!a)return;let s=!1,n=c.current,o=null!==d.current&&d.current!==i;return d.current=i,Rx(e,r,{force:o}).then(e=>{s||c.current!==n||l(e.find(e=>e.reviewer_session_id===a)??null)}).catch(()=>{}),()=>{s=!0}},[e,r,a,i]),o}(e,r,eh,e_,ej),tm=e_&&eh&&e_.reviewer_session_id===eh.id&&"failed"===e_.status?e_:null,tg=ef.flatMap((e,r)=>Tk(e)?[{message:e,index:r}]:[]),tx=ef.every(Tk),tv=!!(eh&&tp?.status==="preparing"&&tx),ty=!!(eh&&tm&&tx),tb=eh?g?.find(e=>e.sourceSessionId===eh.id&&"preparing"===e.run.status):void 0,tw=Q&&eh&&Q.sessionId===eh.id?Q.title:null,t_=tg.length>0?(0,z.jsx)("div",{className:"mt-6 space-y-1 text-left",children:tg.map(({message:e,index:r})=>(0,z.jsx)("div",{"data-message-idx":r,className:"scroll-mt-2",children:(0,z.jsx)(DL,{message:e,messageIndex:r,streaming:!1})},eK[r]??r))}):null,[tS,tj]=(0,$.useState)(!1),tk=(0,$.useCallback)(async()=>{if(tp){tj(!0);try{await ry.api.workflowRunGate(tp.id,"finalize")}catch(e){gS.toast.error(e instanceof Error?e.message:"生成终稿失败")}finally{tj(!1)}}},[tp]),tC=(0,$.useCallback)(()=>{es.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]),{active:tN,requestNonce:tE}=(0,$.useContext)(C_);(0,$.useEffect)(()=>{tN&&tC()},[tN,tE,tC]);let tD=(0,$.useCallback)(e=>{var r,s;let n;C((r=k,s=e,n=0===r.length||r.endsWith("\n\n")?"":r.endsWith("\n")?"\n":"\n\n",r+n+(s.replace(/\r?\n/g,"\n").split("\n").map(e=>`> ${e}`).join("\n")+"\n\n"))),requestAnimationFrame(()=>{let e=es.current?.querySelector("textarea");if(!e)return;e.focus();let r=e.value.length;try{e.setSelectionRange(r,r)}catch{}})},[C,k]),tR=(0,$.useCallback)(async()=>{!ex&&eh&&(await e$(),X(null),f?.(),i?.(null),tC())},[ex,eh,e$,f,i,tC]);(0,$.useImperativeHandle)(y,()=>({startNewConversation:tR,submitMessage:async e=>{if(h?.(),eh)await eD(e,void 0,eG.selectedIds);else{let r=await eA(e,T,V,eG.selectedIds,eG.adoptInto);r&&ed(r.origin)&&Z(r.session.id)}}}),[tR,eh,eA,eD,T,V,h,ed,eG]);let tT=(0,$.useCallback)((e,r)=>{if(r.length<=2e3)return;e.preventDefault();let s=e.currentTarget,n=s.selectionStart??k.length,i=s.selectionEnd??k.length,a=new TextEncoder().encode(r).length,o=TC(D,a);C(k.slice(0,n)+o+k.slice(i)),E(e=>[...e,{id:D,content:r,size:a}]),R(D+1);let l=n+o.length;requestAnimationFrame(()=>{try{s.setSelectionRange(l,l)}catch{}})},[k,D,C]);async function tA(e,r,s,n){let i=new Set;for(let r of e.matchAll(Tj))i.add(Number(r[1]));let a=r.filter(e=>i.has(e.id));if(0===a.length)return e;let o=e;for(let e of a){let r=await s(e.content,n),i=TC(e.id,e.size),a=`<vpaste path="${r.path}" size="${r.size}" />`;o=o.split(i).join(a)}return o}let tI=(0,$.useRef)(null),tM=s=>!!s&&s.projectId===e&&s.branch===r&&s.agentType===H&&s.permissionMode===T&&s.model===V&&Date.now()-s.createdAt<6e5,tF=async()=>{let s=await eI(T,V,eG.selectedIds);if(!s)throw Error("Failed to prepare session");return{prepared:s,projectId:e,branch:r??null,agentType:H,permissionMode:T,model:V,createdAt:Date.now()}},tP=async()=>{let e=tI.current;e&&(tI.current=null,await eF(e.prepared))},tL=function(e){let r=(0,$.useRef)(e);r.current=e;let s=(0,$.useRef)(new Map),n=(0,$.useRef)(new Set),[i,a]=(0,$.useState)(new Map),o=(0,$.useCallback)((e,r)=>{a(s=>{let n=s.get(e);if(n&&n.phase===r.phase&&n.progress===r.progress&&n.message===r.message)return s;let i=new Map(s);return i.set(e,r),i})},[]),l=(0,$.useCallback)(async(e,s)=>{var n;let i,a=e.filename||"attachment";s?.({phase:"reading",progress:0});let o=(n=await DV(e.url)??void 0,n?.match(DK)?.[1]??null);if(!o)throw Error(`Could not read ${a}`);let l=(i=function(e){let r=e.slice(0,24).replace(/[^A-Za-z0-9+/=]/g,"");try{let e=atob(r.length%4==0?r:r.slice(0,r.length-r.length%4)),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s}catch{return new Uint8Array(0)}}(o)).length>=3&&255===i[0]&&216===i[1]&&255===i[2]?"image/jpeg":Tb(i,Tg)?"image/png":Tb(i,Tx)?"image/gif":Tb(i,Tv)&&Tb(i,Ty,8)?"image/webp":null;if(l&&5242880>=function(e){let r=e.length;if(0===r)return 0;let s=0;return e.endsWith("==")?s=2:e.endsWith("=")&&(s=1),Math.floor(3*r/4)-s}(o))return s?.({phase:"inline",progress:1}),{kind:"image",mediaType:l,data:o};s?.({phase:"uploading",progress:0});let c=await r.current.getUploadTarget(),d=await r.current.upload({name:a,mediaType:e.mediaType||void 0,contentBase64:o},c,e=>s?.({phase:"uploading",progress:e}));return s?.({phase:"done",progress:1}),{kind:"file",marker:`<vfile path="${d.path}" name="${d.name}" size="${d.size}" />`}},[]),c=(0,$.useCallback)((e,r)=>{let n=l(e,e=>o(r,e));n.catch(e=>{o(r,{phase:"error",progress:0,message:e instanceof Error?e.message:"Upload failed"})}),s.current.set(r,{name:e.filename||"attachment",promise:n})},[l,o]),d=(0,$.useCallback)(e=>{let r=new Set;for(let n of e)n.id&&(r.add(n.id),s.current.has(n.id)||c(n,n.id));let i=e=>r.has(e)||n.current.has(e);for(let e of Array.from(s.current.keys()))i(e)||s.current.delete(e);a(e=>{if(0===e.size)return e;let r=new Map;for(let[s,n]of e)i(s)&&r.set(s,n);return r.size===e.size?e:r})},[c]),u=(0,$.useCallback)(e=>{for(let r of e)n.current.add(r)},[]),h=(0,$.useCallback)((e,r)=>{for(let i of e)n.current.delete(i),r&&s.current.delete(i);r&&a(r=>{let s=new Map(r);for(let r of e)s.delete(r);return s.size===r.size?r:s})},[]),f=(0,$.useCallback)(e=>{e.id&&(s.current.delete(e.id),c(e,e.id))},[c]),p=(0,$.useCallback)(e=>e?i.get(e):void 0,[i]);return{track:d,retry:f,retain:u,release:h,statusOf:p,resolve:(0,$.useCallback)(async e=>{let r=[],n=[];for(let i of e){let e=i.id?s.current.get(i.id):void 0,a=e?await e.promise:await l(i);"image"===a.kind?r.push({mediaType:a.mediaType,data:a.data}):n.push(a.marker)}return{images:r,markers:n}},[l]),pending:(0,$.useMemo)(()=>Array.from(i.values()).some(e=>"reading"===e.phase||"uploading"===e.phase),[i])}}({upload:eL,getUploadTarget:(0,$.useCallback)(async()=>eh?eh.id:(tM(tI.current)||(await tP(),tI.current=await tF()),tI.current.prepared.sessionId),[eh,e,r,H,T,V,eI,eF])}),tO=(0,$.useRef)(null),tB=(0,$.useCallback)(e=>{if("max_file_size"===e.code){let r=e.files?.map(e=>e.name).join(", ");gS.toast.error(`Files must be ${Math.floor(20)}MB or smaller`,{description:r?`Not attached: ${r}`:e.message});return}gS.toast.error("Could not attach files",{description:e.message})},[]),tz=async e=>{let r=ec.current;if(!r)return;let s=e.text,n=e.files.length>0,i=N.length>0,a=s.trim();if(!a&&!n)return;let o=Symbol("agent-submission");B.current=o,O(!0);try{let l,c,d;C(""),en.push(a),h?.();let u=null,f=async()=>{if(u){let e=u;u=null,await eF(e.prepared);return}eu(r)&&await tP()},p=[],m=()=>{for(let e of p)e.url?.startsWith("blob:")&&URL.revokeObjectURL(e.url)},g=()=>{if(0===p.length)return;let e=p.map(e=>e.id);eu(r)?(tO.current?.restore(p),tL.release(e,!1)):(m(),tL.release(e,!0)),p=[]},x=()=>{0!==p.length&&(m(),tL.release(p.map(e=>e.id),!0),p=[])},v=async(e,n)=>{let i=n instanceof Error?n:Error(e);throw await f(),eu(r)&&(gS.toast.error(e,{description:i.message}),C(s)),g(),i};try{({images:l,markers:c}=await tL.resolve(e.files))}catch(e){return await v("Attachment upload failed",e)}let y=l.length>0;!eh&&eu(r)&&tM(tI.current)&&(u=tI.current,tI.current=null),eu(r)&&(p=tO.current?.detach()??[],tL.retain(p.map(e=>e.id)));let b=async()=>eh?eh.id:(u||(eu(r)&&await tP(),u=await tF()),u.prepared.sessionId),w=a;if(i)try{w=(await tA(s,N,eP,await b())).trim()}catch(e){return await v("Paste upload failed",e)}if(w.length>2e3)try{let e=await eP(w,await b());w=`<vpaste path="${e.path}" size="${e.size}" />`}catch(e){return await v("Paste upload failed",e)}if(c.length>0&&(w=[w,...c].filter(Boolean).join("\n")),eu(r)&&(E([]),R(1)),y){let e=[];for(let r of(w&&e.push({type:"text",text:w}),l))e.push({type:"image",mediaType:r.mediaType,data:r.data});d=e}else d=w;if(I){let e="string"==typeof d?d:d.filter(e=>"text"===e.type).map(e=>e.text).join("\n");if(e.trim()){B.current===o&&eu(r)&&P(!0);let s=null;try{let r=await (0,ry.translateText)(e);r.error||(s=r.translatedText)}catch{s=null}finally{B.current===o&&P(!1)}if(null===s)return eu(r)&&(E(N),R(D)),await v("Translation failed",Error("Disable translation to send the original text."));d="string"==typeof d?s:d.map(e=>"text"===e.type?{...e,text:s}:e)}}if(eh){console.log(`[AgentConversation] handleSubmit: existing session ${eh.id}, status=${ep}`);try{await eD(d,void 0,eG.selectedIds)}catch(e){return await v("Failed to send message",e)}x()}else{tM(u??tI.current)||await f();let e=u?.prepared??null;u=null;let i=eG.selectedIds,a=e?await eM(e,d,i,eG.adoptInto):await eA(d,T,V,i,eG.adoptInto);if(a)x(),console.log(`[AgentConversation] handleSubmit: started session ${a.session.id}`),ed(r)&&Z(a.session.id);else if(eu(r)&&(C(s),E(N),R(D)),g(),n)throw Error("Failed to start session")}}finally{B.current===o&&(B.current=null,P(!1),O(!1))}},{settings:t$}=(0,mo.useConversationSettings)();return e?(0,z.jsxs)("div",{className:"h-full flex flex-col min-h-0",style:{"--conv-font-size":`${t$.agentFontSize}px`},children:[(0,z.jsxs)("div",{className:"flex-shrink-0 flex items-center justify-between px-4 h-10 border-b border-border/60 bg-muted/20",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[q.length>1?(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsxs)("button",{disabled:ex||"running"===ep&&ef.length>0,className:(0,eb.cn)("inline-flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-0.5 text-xs font-medium transition-colors hover:bg-muted",(ex||"running"===ep&&ef.length>0)&&"opacity-50 cursor-not-allowed"),children:[(0,z.jsx)(R1,{type:H}),(0,z.jsx)(RF,{candidates:q.map(e=>e.displayName),children:te}),(0,z.jsx)(n6,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,z.jsx)(o1,{align:"start",className:"min-w-[var(--radix-dropdown-menu-trigger-width)]",children:(0,z.jsx)(o3,{value:H,onValueChange:async e=>{if(!eh){e!==H&&X(null),U(e);return}let r=await eB(e);r?gS.toast.error("Failed to switch agent",{description:r}):U(e)},children:q.map(e=>(0,z.jsxs)(o4,{value:e.type,disabled:!e.available,className:"text-xs pl-2 [&>span:first-child]:hidden data-[state=checked]:bg-accent data-[state=checked]:text-accent-foreground",children:[(0,z.jsx)(R1,{type:e.type}),e.displayName]},e.type))})})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(R1,{type:H,className:"h-4 w-4"}),(0,z.jsx)("span",{className:"text-sm font-medium",children:te})]}),(0,z.jsx)(RB,{models:q.find(e=>e.type===H)?.models??[],widthCandidates:q.flatMap(e=>e.models??[]),value:eh?eh.model??null:V,onChange:eh?e4:X,locked:null!=eh&&"running"===ep&&ef.length>0}),(0,z.jsx)(R0,{mode:T,onModeChange:e3}),ea.length>=1&&o&&(0,z.jsx)(jO,{targets:ea,activeTarget:a?.agent_mode??"local",onTargetChange:o}),eh&&(w=eh.id.startsWith("remote-"),_="text-muted-foreground",S=(0,z.jsx)(dr,{className:"h-3 w-3"}),j="Disconnected",ev?(_="text-muted-foreground",S=(0,z.jsx)(sC,{className:"h-3 w-3 animate-spin"}),j="Checking for newer output..."):em?w&&"connected"!==ew&&null!==ew?"reconnecting"===ew?(_="text-amber-500",S=(0,z.jsx)(Rv,{className:"h-3 w-3 animate-pulse"}),j="Reconnecting..."):"disconnected"===ew&&(_="text-red-500",S=(0,z.jsx)(dr,{className:"h-3 w-3"}),j="Remote disconnected"):(_="text-green-500",S=(0,z.jsx)(Rv,{className:"h-3 w-3"}),j="Connected"):e2||(_="text-amber-500",S=(0,z.jsx)(Rv,{className:"h-3 w-3 animate-pulse"}),j="Connecting..."),(0,z.jsx)("span",{className:`flex items-center ${_}`,title:j,children:S}))]}),(0,z.jsxs)("div",{className:"flex items-center gap-1",children:[e&&(0,z.jsx)(Th,{projectId:e,branch:r,sessionId:eh?.id??null,currentAgentType:H,providers:q,shortcutEnabled:tN,onStarted:e=>x?.(e,tw)}),e&&(0,z.jsx)(R8,{projectId:e,branch:r,currentSessionId:eh?.id??null,refreshKey:Y,pendingTitleSessionId:J,aiTitleOverride:Q,onSwitch:e=>{u?.(e),i?.(e)},onDelete:(e,r)=>{if(e===eh?.id){let e=r[0];i?.(e?e.id:null)}}}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:tR,disabled:ex||!eh,className:"h-7 w-7",title:"New Conversation (⌘⇧O / Ctrl+Shift+O)",children:(0,z.jsx)(Ry,{className:"h-3.5 w-3.5"})}),(0,z.jsxs)(W.Button,{variant:"ghost",size:"sm",onClick:()=>eO(),disabled:"running"!==ep,className:"h-7 text-xs",children:[(0,z.jsx)(lG,{className:"h-3 w-3 mr-1"}),"Stop"]})]})]}),tb&&(0,z.jsxs)("div",{className:"flex items-center gap-2 px-4 py-1.5 border-b bg-muted/40 text-xs text-muted-foreground shrink-0","data-testid":"source-preparing-review",children:[(0,z.jsx)(sC,{className:"h-3 w-3 animate-spin shrink-0"}),(0,z.jsx)("span",{className:"flex-1 truncate",children:"Preparing review — summarizing this conversation and starting the reviewer"}),v&&(0,z.jsx)("button",{type:"button",className:"shrink-0 font-medium text-foreground/80 hover:text-foreground underline-offset-2 hover:underline",onClick:()=>v(tb.runId),children:"View"})]}),(0,z.jsxs)("div",{className:"flex-1 min-h-0 relative",children:[(0,z.jsxs)(cz,{className:"h-full",initial:"instant",resize:tf?"smooth":"instant",children:[(0,z.jsxs)(c$,{className:"gap-1 p-4",scrollClassName:"edge-scrollbar will-change-transform",children:[tv?(0,z.jsx)(Tf,{children:t_}):ty?(0,z.jsx)(Tp,{error:tm?.error,children:t_}):eh||0!==ef.length?(0,z.jsx)(T_.Provider,{value:{sendMessage:eD,messages:ef,acceptPlan:e6,permissionMode:eh?.permissionMode??T,agentType:eh?.agentType??H,sessionId:eh?.id??null,projectId:e,branch:r,target:eo,targetLabel:el,openSchedule:m},children:(0,z.jsxs)("div",{className:"space-y-1 outline-none",ref:et,tabIndex:-1,onKeyDown:er,children:[eh?.lifecycleState==="activation_uncertain"&&(0,z.jsxs)("div",{className:"flex items-start gap-2 p-3 mb-2 rounded-lg border border-amber-500/40 bg-amber-500/10 text-sm text-amber-700 dark:text-amber-400",children:[(0,z.jsx)(s_,{className:"h-4 w-4 mt-0.5 shrink-0"}),(0,z.jsx)("span",{children:"First message delivery could not be confirmed for this session. Check whether the agent actually responded before resending — a resend may duplicate the task."})]}),eC&&(0,z.jsx)("div",{className:"flex justify-center pb-3",children:(0,z.jsxs)(W.Button,{type:"button",variant:"ghost",size:"sm",disabled:eN,onClick:()=>void eE(),children:[eN?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 animate-spin"}):(0,z.jsx)(n6,{className:"h-3.5 w-3.5 rotate-180"}),"Load earlier turns"]})}),ef.map((e,r)=>e?.type==="turn_end"?(0,z.jsx)(RN,{durationMs:e.durationMs,outcome:e.outcome,emphasis:r===th?"normal":"subtle",agentType:H,currentAgentName:te,alternateProviders:tt,onBranch:e=>e9(e,eK[r]??r),disabled:e7,showFinalize:r===th&&tp?.status==="discussing",finalizeBusy:tS,onFinalize:tk,sendBack:tr&&(eK[r]??r)>ts?{available:!tl&&eh?.branchedFromAvailable!==!1,sent:tn.has(eK[r]??r),busy:ta===(eK[r]??r),onSend:()=>void tu(eK[r]??r,r)}:void 0},eK[r]??r):(0,z.jsx)("div",{"data-message-idx":r,..."user"===e.type?{"data-user-msg-idx":r}:{},className:"scroll-mt-2",children:(0,z.jsx)(DL,{message:e,messageIndex:r,streaming:"assistant"===e.type&&tf&&r===ef.length-1})},eK[r]??r)),ex&&!ev&&(0,z.jsxs)("div",{className:"flex items-center gap-2 py-4 text-muted-foreground",children:[(0,z.jsx)(Rl,{className:"h-4 w-4"}),(0,z.jsx)("span",{className:"text-sm",children:"Connecting to agent..."})]})]})}):(0,z.jsx)("div",{className:"text-center py-16",children:ex||e&&!eg?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Rl,{className:"h-6 w-6 mx-auto mb-4"}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Connecting to agent..."}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Setting up the session for this worktree"})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mb-4",children:(0,z.jsx)(sS,{className:"h-6 w-6 text-primary/60"})}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Start a conversation"}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Ask the agent to help you with coding tasks in this worktree"})]})}),ey&&(0,z.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-red-500/10 rounded-lg text-red-500 text-sm mt-4",children:[(0,z.jsx)(s_,{className:"h-4 w-4"}),ey]})]}),(0,z.jsx)(cW,{}),(0,z.jsx)(Tt,{messageCount:ef.length,turnInFlight:tf,sessionId:eh?.id??null})]}),(0,z.jsx)(R6,{messages:ef,contentRef:et}),(0,z.jsx)(Tn,{containerRef:et,onQuote:tD})]}),(0,z.jsxs)("div",{className:"flex-shrink-0 py-3 px-[30px]",children:[(0,z.jsx)(RM,{sessionId:eV,tasks:eS.tasks,turnParked:eS.turnParked,parkDeadlineAt:eS.parkDeadlineAt,canStopTasks:eS.canStopTasks,agentWorking:"running"===ep}),(0,z.jsxs)(D4,{onSubmit:tz,maxFileSize:0x1400000,onError:tB,skipAttachmentConversion:!0,className:"w-full",children:[(0,z.jsx)(Tw,{uploads:tL,workspaceKey:`${e}::${r}`,apiRef:tO}),(0,z.jsxs)("div",{className:"relative flex w-full flex-col",children:[eY&&(0,z.jsx)(RV,{granted:eG.granted,onRevoke:e=>eG.toggle(e,!1)}),I&&(0,z.jsx)("div",{className:"flex items-center pl-12 pr-2 pt-1.5 pb-0.5",children:(0,z.jsxs)("button",{type:"button",onClick:()=>M(!1),className:"inline-flex shrink-0 items-center gap-1.5 rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400 px-2.5 py-0.5 text-xs font-medium hover:bg-blue-500/20 transition-colors",children:[F?(0,z.jsx)(sC,{className:"size-3 animate-spin"}):(0,z.jsx)(Rb,{className:"size-3"}),"Translate",(0,z.jsx)(t7,{className:"size-3"})]})}),(0,z.jsxs)("div",{className:"flex w-full items-center",children:[(0,z.jsxs)(Re,{children:[(0,z.jsx)(Rt,{className:"ml-1"}),(0,z.jsxs)(Rr,{children:[(0,z.jsx)(D3,{label:"Add files"}),eY&&(0,z.jsx)(RK,{granted:eG.granted,onToggle:eG.toggle,sourceRemoteId:eJ}),(0,z.jsxs)(Rs,{onSelect:()=>{M(!I)},children:[(0,z.jsx)(Rb,{className:"mr-2 size-4"}),I?"Disable translation":"Translate"]})]})]}),(0,z.jsx)("div",{ref:es,className:"contents",children:(0,z.jsx)(D6,{value:k,onChange:e=>C(e.target.value),onPasteText:tT,onKeyDown:en.handleKeyDown,placeholder:eh?"Ask the agent to help with your code...":"Type your first message to start...",className:"pr-12",style:{fontSize:"var(--conv-font-size, 14px)"}})}),(0,z.jsx)("div",{className:"pointer-events-none absolute bottom-0 right-2 flex items-center text-base md:text-sm",style:{fontSize:"var(--conv-font-size, 14px)",height:"calc(1lh + 1.5rem)"},children:(0,z.jsx)(Rn,{className:"pointer-events-auto",disabled:!k.trim()&&!ex||F||L||tL.pending,status:L||F||tL.pending?"submitted":ex?"streaming":"ready"})})]})]})]})]}),(0,z.jsx)(lL,{open:null!==eq,onOpenChange:e=>{e||eq?.resolve(!1)},children:(0,z.jsxs)(lz,{children:[(0,z.jsxs)(l$,{children:[(0,z.jsx)(lH,{children:"Agent process limit reached"}),(0,z.jsxs)(lU,{children:["All ",eq?.maxResidentAgentProcesses," resident agent processes for this workspace branch are running. Starting a new conversation will stop the least recently active running session in this branch."]})]}),(0,z.jsxs)(lW,{children:[(0,z.jsx)(lK,{children:"Cancel"}),(0,z.jsx)(lq,{onClick:()=>eq?.resolve(!0),children:"Stop & start new"})]})]})})]}):(0,z.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(sS,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to start coding"})]})})});function TE({runId:e,entry:r,title:s,onOpenSource:n}){let i,[a,o]=(0,$.useState)(null),[l,c]=(0,$.useState)(0);(0,$.useEffect)(()=>{if(r)return;let s=!1;return ry.api.getWorkflowRun(e).then(r=>{s||o({runId:e,attempt:l,run:r})}).catch(r=>{s||o({runId:e,attempt:l,error:r instanceof Error?r.message:String(r)})}),()=>{s=!0}},[r,e,l]);let d=a?.runId===e&&a.attempt===l?a:null,u=!d||"error"in d?null:d,h=r?.run??u?.run??null;return i=r?(0,z.jsx)(Tf,{phase:"preparing"===r.run.status?"distilling":"starting"}):d&&"error"in d?(0,z.jsx)(Tp,{error:d.error,title:"Could not read the review status",children:(0,z.jsx)(W.Button,{variant:"outline",size:"sm",className:"mt-4",onClick:()=>c(e=>e+1),children:"Retry"})}):u?u.run?"failed"===u.run.status?(0,z.jsx)(Tp,{error:u.run.error}):"cancelled"===u.run.status||"completed"===u.run.status?(0,z.jsx)(Tm,{status:u.run.status}):(0,z.jsx)(Tf,{phase:"starting"}):(0,z.jsx)(Tm,{status:"gone"}):(0,z.jsxs)("div",{className:"text-center py-16",children:[(0,z.jsx)(Rl,{className:"h-6 w-6 mx-auto mb-4"}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Checking review status…"})]}),(0,z.jsxs)("div",{className:"flex flex-col h-full","data-testid":"preparing-review-view",children:[(0,z.jsxs)("div",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b shrink-0",children:[(0,z.jsx)("span",{className:"text-sm font-medium truncate",title:s,children:s}),h&&(0,z.jsxs)(W.Button,{variant:"ghost",size:"sm",className:"h-7 text-xs shrink-0",onClick:()=>n(h.source_session_id,h.branch),children:[(0,z.jsx)(n4.ArrowLeft,{className:"h-3 w-3 mr-1"}),"Source conversation"]})]}),(0,z.jsx)("div",{className:"flex-1 min-h-0 overflow-auto px-4",children:i})]})}function TD(e){return e.title?.trim()||"New Session"}async function TR(e){let r=await (0,ry.listAliveSessions)(e);return r.complete?r.sessions.map(r=>({id:r.id,projectId:e,branch:r.branch,title:TD(r),status:r.status,processAlive:!0})):"incomplete"}async function TT(e,r){return 0===r.length?null:(await Promise.all(r.map(async r=>(await (0,ry.listBranchSessions)(e,r)).sessions.filter(e=>e.processAlive).map(s=>({id:s.id,projectId:e,branch:r,title:TD(s),status:s.status,processAlive:!0,updated_at:s.updated_at}))))).flat()}function TA(e,r,s){return"live"===r&&s&&"live"!==e}let TI=new Map,TM="preparing-review",TF={preparing:0,waiting_reviewer:1,waiting_feedback:2,discussing:3,sending_feedback:4,waiting_rereview:1,running_task:1,waiting_resume:1,completed:9,cancelled:9,failed:9};function TP(e){return 9===TF[e]}function TL(e){let r=Date.parse(e.updated_at);return(TF[e.status]??0)*1e13+(Number.isFinite(r)?r:0)}function TO(e){return{projectId:e,entries:new Map,tombstones:new Map}}function TB(e,r,s){let n=new Map(e.entries),i=new Map(e.tombstones);for(let e of r)n.delete(e),i.set(e,s+6e4);return{...e,entries:n,tombstones:i}}function Tz(e,r,s,n){if(!e.projectId||r.project_id!==e.projectId)return e;let i=e.tombstones.get(r.id);if(void 0!==i&&i>s)return e;let a=e.entries.get(r.id);if(TP(r.status))return a?TB(e,[r.id],s):e;if(!a){if("preparing"!==r.status||!r.reviewer_session_id)return e;let i=new Map(e.entries);return i.set(r.id,{kind:TM,runId:r.id,projectId:r.project_id,branch:r.branch??null,reviewerSessionId:r.reviewer_session_id,sourceSessionId:r.source_session_id,run:r,version:TL(r),titleHint:n??null,insertedAt:s,appearedAt:null}),{...e,entries:i}}let o=TL(r);if(o<a.version)return e;let l=new Map(e.entries);return l.set(r.id,{...a,branch:r.branch??null,reviewerSessionId:r.reviewer_session_id??a.reviewerSessionId,run:r,version:o,titleHint:n??a.titleHint}),{...e,entries:l}}function T$(e,r,s){let n=null;for(let i of e.entries.values())null===i.appearedAt&&r.has(i.reviewerSessionId)&&(n??=new Map(e.entries)).set(i.runId,{...i,appearedAt:s});return n?{...e,entries:n}:e}function TW(e,r){let s=(e.titleHint??r??"").trim();return s&&"New Session"!==s?`Review - ${s}`:"Review"}let TH=Object.freeze({session:null,messages:[],status:"stopped",isConnected:!1,isInitialized:!1,isLoading:!1,error:null,workflowRunUpdate:null,streamEpoch:0,draft:""});function TU(){return"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}async function Tq(e,r){let s=await (0,ry.authFetch)(`${TU()}/api/projects/${e}/chat-sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:r})});if(!s.ok)throw Error("Failed to create chat session");return s.json()}async function TK(e,r){if(!(await (0,ry.authFetch)(`${TU()}/api/chat-sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r})})).ok)throw Error("Failed to send message")}async function TV(e){if(!(await (0,ry.authFetch)(`${TU()}/api/chat-sessions/${e}/stop`,{method:"POST"})).ok)throw Error("Failed to stop generation")}function TX(e,r){return`chat:${e}:${r??""}`}let TY=new Map,TG=new Map;function TJ(e,r){for(TG.delete(e),TG.set(e,r);TG.size>20;){let e=TG.keys().next().value;if(void 0===e)break;TG.delete(e)}}let TZ=new Map;class TQ{projectId;branch;key;state;listeners;active;epoch;ws;container;replaying;finished;reconnectTimer;stabilityTimer;silenceTimer;reconnectAttempt;shortLivedConnections;connectionStartedAt;lastStartFailed;metadataWrites;constructor(e,r){this.projectId=e,this.branch=r,this.listeners=new Set,this.active=!1,this.epoch=0,this.ws=null,this.container={entries:[],status:"stopped"},this.replaying=!1,this.finished=!1,this.reconnectTimer=null,this.stabilityTimer=null,this.silenceTimer=null,this.reconnectAttempt=0,this.shortLivedConnections=0,this.connectionStartedAt=null,this.lastStartFailed=!1,this.metadataWrites=0,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.getSnapshot=()=>this.state,this.onVisibilityChange=()=>{if("visible"!==document.visibilityState||!this.state.session?.id||this.finished)return;let e=this.ws;e&&e.readyState===WebSocket.OPEN&&e.close(4e3,"visibility-recovery")},this.setDraft=e=>{e!==this.state.draft&&(TZ.set(this.key,e),this.set({draft:e}))},this.setEventListening=async e=>{let r=this.state.session;r&&(await ry.api.setChatEventListening(r.id,e),this.metadataWrites+=1,this.state.session?.id===r.id&&this.adoptSession({...r,eventListeningEnabled:e}))},this.sendMessage=async e=>{let r=this.state.session?.id,s=e.trim();if(r&&s)try{await TK(r,s)}catch(r){let e=r instanceof Error?r.message:"Failed to send message";this.set({error:e}),gS.toast.error("Failed to send message",{description:e})}},this.stopGeneration=async()=>{let e=this.state.session?.id;if(e)try{await TV(e)}catch(e){console.error("[ChatSession] Failed to stop generation:",e)}},this.restartSession=async()=>{let e=this.state.session?.id;if(e)try{await ry.api.resetChatSession(e),this.container={entries:[],status:"stopped"},this.flush()}catch(e){console.error("[ChatSession] Failed to reset session:",e),gS.toast.error("Failed to start new conversation")}},this.key=TX(e,r);const s=TG.get(this.key),n=TZ.get(this.key)??"",i=s?.session??TY.get(this.key)??null;this.state=s?{...TH,session:i,messages:s.messages,status:s.status,isInitialized:!0,draft:n}:{...TH,session:i,draft:n}}subscribe;getSnapshot;set(e){for(let r of(this.state={...this.state,...e},this.listeners))r()}start(){this.active||(this.active=!0,this.finished=!1,"undefined"!=typeof document&&document.addEventListener("visibilitychange",this.onVisibilityChange),this.startSession())}stop(){if(!this.active)return;this.active=!1,this.epoch+=1,"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.onVisibilityChange);let e=this.ws;if(this.ws=null,e)try{e.close(1e3,"branch-switch")}catch{}this.clearTimers(),this.connectionStartedAt=null,this.state.isConnected&&this.set({isConnected:!1})}clearTimers(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stabilityTimer&&(clearTimeout(this.stabilityTimer),this.stabilityTimer=null),this.clearSilenceTimer()}async startSession(){if(!this.active)return;let e=this.epoch;this.lastStartFailed=!1,this.set({error:null});let r=TY.get(this.key);if(r){this.set({session:r}),this.connect(),this.refreshSessionMetadata(e);return}this.set({isLoading:!0});try{let{session:r,messages:s}=await Tq(this.projectId,this.branch);if(e!==this.epoch)return;TY.set(this.key,r),this.set({session:r,status:r.status,messages:s??[],isInitialized:!0}),this.connect()}catch(r){if(e!==this.epoch)return;this.lastStartFailed=!0,this.set({error:r instanceof Error?r.message:"Failed to start session"})}finally{e===this.epoch&&this.set({isLoading:!1})}}async refreshSessionMetadata(e){let r=this.metadataWrites;try{let{session:s,messages:n}=await Tq(this.projectId,this.branch);if(e!==this.epoch||r!==this.metadataWrites||s.id!==this.state.session?.id)return;this.adoptSession(s),this.state.isInitialized||this.set({messages:n??[],isInitialized:!0})}catch{}}adoptSession(e){TY.set(this.key,e);let r=TG.get(this.key);r&&r.session.id===e.id&&TJ(this.key,{...r,session:e}),this.set({session:e})}connect(e=!1){if(!this.active||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;let r=this.epoch;(0,ry.getFreshToken)(e?{skipCache:!0}:void 0).then(()=>{r===this.epoch&&this.active&&this.openSocket()})}openSocket(){if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;let e=this.state.session?.id;if(!e)return;this.container={entries:[],status:"stopped"},this.finished=!1,this.replaying=!0;let r=new WebSocket((0,ry.getWebSocketUrl)(`/api/chat-sessions/${e}/stream`));this.ws=r;let s=()=>this.ws===r;r.onopen=()=>{s()&&(this.set({isConnected:!0,error:null}),this.connectionStartedAt=Date.now(),this.armSilenceTimer(r),this.stabilityTimer&&clearTimeout(this.stabilityTimer),this.stabilityTimer=setTimeout(()=>{this.reconnectAttempt=0,this.shortLivedConnections=0},5e3))},r.onmessage=e=>{if(s()){this.armSilenceTimer(r);try{this.handleFrame(r,JSON.parse(e.data))}catch(e){console.error("[ChatSession] Failed to parse message:",e)}}},r.onclose=e=>{let r;if(!s())return;this.ws=null,this.set({isConnected:!1}),this.clearSilenceTimer(),this.stabilityTimer&&(clearTimeout(this.stabilityTimer),this.stabilityTimer=null);let n=4e3===e.code,i=this.connectionStartedAt?Date.now()-this.connectionStartedAt:0;if(this.connectionStartedAt=null,!n&&i>0&&i<5e3){if(this.shortLivedConnections++,this.shortLivedConnections>=3)return this.lastStartFailed?void this.set({error:"Unable to connect to remote server. Please check the server configuration."}):(TY.delete(this.key),this.reconnectAttempt=0,this.shortLivedConnections=0,this.set({session:null,error:null}),void this.startSession())}else i>=5e3&&(this.shortLivedConnections=0);if(this.finished||1e3===e.code)return;if(this.reconnectAttempt>=10)return void this.set({error:"Unable to connect to server."});let a=(r=Math.min(3e4,1e3*Math.pow(2,this.reconnectAttempt)))+r*Math.random()*.25;this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.state.session?.id&&!this.finished&&this.connect(!0)},a)},r.onerror=()=>{}}handleFrame(e,r){if(!("keepalive"in r)){if("JsonPatch"in r){var s,n;this.container=(s=this.container,n=r.JsonPatch,Nn(s,e=>{for(let r of n){let{op:s,path:n,value:i}=r;if("/entries"===n&&"replace"===s&&i?.type==="ENTRY"&&i.content?.type==="system"&&i.content?.content==="__CLEAR_ALL__"){e.entries=[];continue}if(n.startsWith("/entries/")){let r=parseInt(n.replace("/entries/",""),10);if(isNaN(r)||i?.type!=="ENTRY")continue;switch(s){case"add":for(;e.entries.length<=r;)e.entries.push(null);e.entries[r]=i.content;break;case"replace":r<e.entries.length&&(e.entries[r]=i.content);break;case"remove":r<e.entries.length&&e.entries.splice(r,1)}}else"/status"===n&&i?.type==="STATUS"&&(e.status=i.content)}})),this.replaying||this.flush();return}if("Ready"in r){this.replaying=!1,this.flush(),this.set({isInitialized:!0,streamEpoch:this.state.streamEpoch+1});return}if("finished"in r){this.finished=!0,e.close(1e3,"finished");return}if("openPreviewFrame"in r)return void(0,j7.openPreviewFrame)(r.openPreviewFrame.projectId,r.openPreviewFrame.url);if("WorkflowRunUpdated"in r)return void this.set({workflowRunUpdate:r.WorkflowRunUpdated});if("browserCommand"in r){let s=r.browserCommand;(0,j7.sendCommandToIframe)(this.projectId,{type:"vibedeckx-command",...s}).then(r=>{r&&e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"browser_result",result:{id:s.id,success:r.success??!1,error:r.error,content:r.content,found:r.found,tag:r.tag,text:r.text}}))});return}"error"in r&&(this.set({error:r.error}),"Session not found"===r.error&&(TY.delete(this.key),TG.delete(this.key),this.finished=!0))}}flush(){let e=this.container.entries.filter(Boolean),r=this.container.status;this.set({messages:e,status:r}),this.state.session&&TJ(this.key,{session:this.state.session,messages:e,status:r})}clearSilenceTimer(){this.silenceTimer&&(clearTimeout(this.silenceTimer),this.silenceTimer=null)}armSilenceTimer(e){this.silenceTimer&&clearTimeout(this.silenceTimer),this.silenceTimer=setTimeout(()=>{this.silenceTimer=null,e.readyState===WebSocket.OPEN&&(console.warn(`[ChatSession] No frames for 95000ms — assuming dead socket, forcing reconnect`),this.replaceSilentSocket(e))},95e3)}replaceSilentSocket(e){if(this.ws===e){this.ws=null,this.set({isConnected:!1}),this.stabilityTimer&&(clearTimeout(this.stabilityTimer),this.stabilityTimer=null),this.connectionStartedAt=null;try{e.close(4e3,"silence watchdog")}catch{}this.finished||this.connect(!0)}}onVisibilityChange;setDraft;setEventListening;sendMessage;stopGeneration;restartSession}let T0=()=>()=>{},T1=()=>TH,T2=async()=>{},T5=()=>{};function T3({sessionId:e,approvalId:r,tool:s,input:n,resolved:i}){let[a,o]=(0,$.useState)(null),l=function(e){if(null!==e&&"object"==typeof e){if("string"==typeof e.message)return e.message;if("string"==typeof e.prompt)return e.prompt}return JSON.stringify(e)}(n),c=async s=>{if(!a&&!i){o(s?"approve":"deny");try{await ry.api.chatToolApproval(e,r,s)}finally{o(null)}}};return(0,z.jsx)("div",{className:"mx-4 my-1",children:(0,z.jsxs)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 space-y-2",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)(sS,{className:"h-3.5 w-3.5 text-amber-500 shrink-0"}),(0,z.jsxs)("span",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:["Approval needed · ","spawnAgentSession"===s?"Start a new coding agent":"Send to the coding agent"]})]}),(0,z.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all text-foreground/80",style:{fontSize:"var(--conv-font-size, 12px)"},children:l}),i?(0,z.jsxs)(so,{variant:"default",className:"approved"===i?"bg-green-600 hover:bg-green-700 text-white":"bg-red-600 hover:bg-red-700 text-white",children:["approved"===i?(0,z.jsx)(sZ,{className:"h-3 w-3 mr-1"}):(0,z.jsx)(s1,{className:"h-3 w-3 mr-1"}),"approved"===i?"Approved — sent.":"Denied — not sent."]}):(0,z.jsxs)("div",{className:"flex gap-2",children:[(0,z.jsxs)(W.Button,{onClick:()=>c(!0),disabled:null!==a,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:["approve"===a?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,z.jsx)(sZ,{className:"h-3.5 w-3.5 mr-1"}),"Approve"]}),(0,z.jsxs)(W.Button,{onClick:()=>c(!1),disabled:null!==a,variant:"destructive",size:"sm",children:["deny"===a?(0,z.jsx)(sC,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,z.jsx)(s1,{className:"h-3.5 w-3.5 mr-1"}),"Deny"]})]})]})})}let T4=(0,$.createContext)({markReviewRunRead:()=>{}}),T6=T4.Provider,T7=(0,e_.default)("pause",[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]]),T8=new Set(["preparing","waiting_reviewer","waiting_feedback","discussing","sending_feedback","waiting_rereview","running_task","waiting_resume"]),T9={ship:{text:"ship",className:"border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400"},"needs-changes":{text:"needs-changes",className:"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-400"},"cannot-verify":{text:"cannot-verify",className:"border-border bg-muted text-muted-foreground"}};function Ae(e){if(!e.loop_id)return null;let r=e.round??1;return e.max_rounds?`第 ${r} / ${e.max_rounds} 轮`:`第 ${r} 轮`}function At(e){return null!=e.max_rounds&&(e.round??1)>e.max_rounds}function Ar(e){return e.map(e=>e.id).sort().join(",")}function As({projectId:e,branch:r,runUpdate:s,streamEpoch:n,onRunsChange:i}){let[a,o]=(0,$.useState)([]),[l,c]=(0,$.useState)({}),[d,u]=(0,$.useState)({}),[h,f]=(0,$.useState)(null),[p,m]=(0,$.useState)(null),g=(0,$.useRef)(0),{markReviewRunRead:x}=(0,$.useContext)(T4),[v,y]=(0,$.useState)(()=>({projectId:e,branch:r}));(v.projectId!==e||v.branch!==r)&&(y({projectId:e,branch:r}),m(null));let b=(0,$.useRef)(0),w=(0,$.useRef)(null),_=(0,$.useRef)({projectId:e,branch:r});(0,$.useEffect)(()=>{_.current={projectId:e,branch:r}},[e,r]);let S=(0,$.useCallback)(async s=>{if(!e)return;let n=++b.current,a=Rg(e,r,s);try{let e=await a.request;if(n!==b.current)return;w.current={at:a.issuedAt,runs:e},o(e),i?.(e),m(r=>{if(!r)return r;let s=e.find(e=>e.id===r.runId)??null;return(s?.status??null)===r.status&&(s||Ar(e)===r.signature)?r:null})}catch{}},[e,r,i]),j=(0,$.useRef)(null);(0,$.useEffect)(()=>{let e=null!==j.current&&j.current!==n;j.current=n,S({force:e})},[S,n]),(0,$.useEffect)(()=>{s&&S({force:!0})},[s,S]),(0,$.useEffect)(()=>{if(0===a.length)return;let e=setInterval(()=>void S({force:!0}),5e3);return()=>clearInterval(e)},[a.length,S]),(0,$.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&S({force:!0})};return document.addEventListener("visibilitychange",e),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("online",e)}},[S]);let k=async(s,n,i)=>{let a=++g.current;f(s),m(null);let o=null;try{await i()}catch(e){o=e instanceof Error?e.message:String(e)}finally{f(null),S({force:!0})}if(!o)return void x(s,{runEnded:"finalize"!==n&&"rereview"!==n});let l=null;if(e){let s=Rg(e,r,{force:!0}),n=await s.request.catch(()=>null),i=w.current;l=i&&i.at>=s.issuedAt?i.runs:n}if(_.current.projectId!==e||_.current.branch!==r||a!==g.current)return;let c=l?.find(e=>e.id===s)??null;m({runId:s,status:c?.status??null,message:(l?function(e,r){if("cancel"===e||"pause"===e||"resume"===e)return null;if(!r)return"这次 review 已经结束了 —— 反馈可能已经发出,或者 run 已被取消。";if("approve"===e){if("discussing"===r.status)return"reviewer 已进入讨论:先点「生成终稿」拿到新的结论,再发送反馈。";if("waiting_reviewer"===r.status)return"reviewer 正在重新出稿,等它完成后再发送。";if("sending_feedback"===r.status)return"反馈正在发送中。"}if("finalize"===e){if("waiting_feedback"===r.status)return"终稿已经出来了,直接发送反馈即可。";if("waiting_reviewer"===r.status)return"reviewer 正在出稿,稍候再试。"}if("accept"===e){if("discussing"===r.status)return"reviewer 已进入讨论:先点「生成终稿」拿到新的结论。";if("waiting_reviewer"===r.status)return"reviewer 正在重新出稿,等它完成后再决定。";if("sending_feedback"===r.status)return"反馈正在发送中。"}if("rereview"===e){if("waiting_rereview"===r.status)return null;if("waiting_reviewer"===r.status)return"复审已经发起,reviewer 正在审查。";if("waiting_feedback"===r.status)return"这一轮复审已经出结论了。"}return null}(n,c):null)??o,signature:Ar(l??[])})},C=a.filter(e=>T8.has(e.status)),N=p&&!C.some(e=>e.id===p.runId)?p:null;return 0!==C.length||N?(0,z.jsxs)("div",{className:"shrink-0 border-b bg-muted/30 px-4 py-2 space-y-2 max-h-[50vh] overflow-y-auto",children:[N&&(0,z.jsxs)("div",{className:"flex items-start justify-between gap-2 text-destructive",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{children:N.message}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon-sm","aria-label":"关闭提示",onClick:()=>m(null),children:(0,z.jsx)(t7,{className:"h-3 w-3"})})]}),C.map(e=>"repeat"===e.kind?(0,z.jsx)(An,{run:e,busy:h===e.id,error:p?.runId===e.id?p.message:null,onAction:r=>k(e.id,r,()=>"cancel"===r?ry.api.cancelWorkflowRun(e.id):ry.api.workflowRunGate(e.id,r))},e.id):(0,z.jsxs)("div",{className:"space-y-2",style:{fontSize:"var(--conv-font-size, 14px)"},children:[(0,z.jsxs)("div",{className:"flex items-center justify-between",children:[(0,z.jsxs)("span",{className:"font-medium",children:["Review",e.review_focus?` — ${e.review_focus}`:"",(0,z.jsxs)("span",{className:"ml-2 text-muted-foreground",children:["preparing"===e.status&&"准备中…","waiting_reviewer"===e.status&&"reviewer 审查中…","waiting_feedback"===e.status&&"等你确认反馈","discussing"===e.status&&"讨论中","sending_feedback"===e.status&&"发送中…","waiting_rereview"===e.status&&"等你确认复审"]}),Ae(e)&&(0,z.jsx)("span",{className:"ml-2 text-muted-foreground",children:Ae(e)})]}),(0,z.jsxs)(W.Button,{variant:"ghost",size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"cancel",()=>ry.api.cancelWorkflowRun(e.id)),children:[(0,z.jsx)(t7,{className:"h-3 w-3 mr-1"}),"结束"]})]}),e.error&&(0,z.jsx)("div",{className:"text-amber-600",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.error}),"preparing"===e.status&&(0,z.jsxs)("div",{className:"flex items-center text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)(sC,{className:"h-3 w-3 mr-1 animate-spin"})," 正在蒸馏上下文并启动 reviewer"]}),"waiting_reviewer"===e.status&&(0,z.jsxs)("div",{className:"flex items-center text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)(sC,{className:"h-3 w-3 mr-1 animate-spin"})," reviewer session 正在工作"]}),"discussing"===e.status&&(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)("span",{className:"text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:"与 reviewer 讨论后,生成终稿再发送"}),(0,z.jsx)(W.Button,{size:"icon-sm",variant:"outline","aria-label":"生成 review 终稿",disabled:h===e.id,onClick:()=>k(e.id,"finalize",()=>ry.api.workflowRunGate(e.id,"finalize")),children:(0,z.jsx)(N1,{className:"h-3 w-3"})})]}),"waiting_rereview"===e.status&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("div",{className:"text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:At(e)?`source 已按反馈完成修改。已达上限 ${e.max_rounds} 轮——要再加一轮吗?`:"source 已按反馈完成修改。由同一个 reviewer 复审这次修改?"}),(0,z.jsxs)("div",{className:"flex gap-2",children:[(0,z.jsx)(W.Button,{size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"rereview",()=>ry.api.workflowRunGate(e.id,"rereview",void 0,{extend:At(e)})),children:At(e)?"再加一轮":`发起第 ${e.round??2} 轮复审`}),(0,z.jsx)(W.Button,{variant:"outline",size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"cancel",()=>ry.api.cancelWorkflowRun(e.id)),children:"结束循环"})]})]}),"waiting_feedback"===e.status&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)("span",{className:"text-muted-foreground",children:"reviewer 结论"}),e.verdict?(0,z.jsx)("span",{className:`rounded border px-1.5 py-px font-mono ${T9[e.verdict].className}`,children:T9[e.verdict].text}):(0,z.jsx)("span",{className:"rounded border border-dashed px-1.5 py-px text-muted-foreground",children:"未识别,请自行判断"})]}),d[e.id]?(0,z.jsx)(rc,{className:"font-mono min-h-28 max-h-72",style:{fontSize:"var(--conv-font-size, 12px)"},value:l[e.id]??e.feedback_snapshot??"",onChange:r=>c(s=>({...s,[e.id]:r.target.value}))}):(0,z.jsx)("div",{className:"border rounded-md bg-background px-3 py-2 max-h-72 overflow-y-auto",style:{fontSize:"var(--conv-font-size, 12px)"},children:(0,z.jsx)(cE,{children:l[e.id]??e.feedback_snapshot??""})}),(0,z.jsxs)("div",{className:"flex gap-2",children:["ship"===e.verdict&&(0,z.jsx)(W.Button,{size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"accept",()=>ry.api.workflowRunGate(e.id,"accept")),children:"接受并结束"}),(0,z.jsx)(W.Button,{size:"sm",variant:"ship"===e.verdict?"outline":"default",disabled:h===e.id,onClick:()=>k(e.id,"approve",()=>ry.api.workflowRunGate(e.id,"approve",l[e.id]??void 0)),children:"ship"===e.verdict?"仍发送反馈":"发送反馈给原 session"}),(0,z.jsx)(W.Button,{variant:"outline",size:"sm",disabled:h===e.id,onClick:()=>u(r=>({...r,[e.id]:!r[e.id]})),children:d[e.id]?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(_P,{className:"h-3 w-3 mr-1"}),"预览"]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(rx,{className:"h-3 w-3 mr-1"}),"编辑"]})})]})]}),p?.runId===e.id&&(0,z.jsx)("div",{className:"text-destructive",style:{fontSize:"var(--conv-font-size, 12px)"},children:p.message})]},e.id))]}):null}function An({run:e,busy:r,error:s,onAction:n}){let i=(0,ry.repeatLoopParams)(e),a=e.round??1,o="waiting_resume"===e.status,l=o&&i?.dispatchFailed===!0,c=o&&!l?Math.max(1,a-1):a,d=i?.stopAfterCurrent===!0;return(0,z.jsxs)("div",{className:"space-y-2",style:{fontSize:"var(--conv-font-size, 14px)"},children:[(0,z.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,z.jsxs)("span",{className:"font-medium min-w-0 truncate",children:["Loop — ",i?.name??"Loop",(0,z.jsxs)("span",{className:"ml-2 text-muted-foreground",children:["preparing"===e.status&&"正在启动下一个 session…","running_task"===e.status&&(d?"做完这一项后暂停…":"处理中…"),o&&"已停下,等你决定"]}),(0,z.jsxs)("span",{className:"ml-2 text-muted-foreground",children:["第 ",c,e.max_rounds?` / ${e.max_rounds}`:""," 次"]})]}),(0,z.jsxs)(W.Button,{variant:"ghost",size:"sm",disabled:r,onClick:()=>n("cancel"),title:"立即结束循环,并停掉正在运行的 session",children:[(0,z.jsx)(t7,{className:"h-3 w-3 mr-1"}),"结束"]})]}),(i?.prevItem||i?.remaining)&&(0,z.jsxs)("div",{className:"text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[i.prevItem&&(0,z.jsxs)(z.Fragment,{children:["上一项:",i.prevItem]}),i.prevItem&&i.remaining&&" · ",i.remaining&&(0,z.jsxs)(z.Fragment,{children:["剩余:",i.remaining]})]}),e.error&&(0,z.jsx)("div",{className:"text-amber-600",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.error}),"running_task"===e.status&&(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsxs)("span",{className:"flex items-center text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,z.jsx)(sC,{className:"h-3 w-3 mr-1 animate-spin"})," session「",i?.name??"Loop"," #",a,"」正在工作"]}),!d&&(0,z.jsxs)(W.Button,{size:"sm",variant:"outline",disabled:r,onClick:()=>n("pause"),children:[(0,z.jsx)(T7,{className:"h-3 w-3 mr-1"}),"做完这项后停"]})]}),o&&(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsxs)(W.Button,{size:"sm",disabled:r,onClick:()=>n("resume"),children:[(0,z.jsx)(rf,{className:"h-3 w-3 mr-1"}),"继续循环"]}),(0,z.jsx)("span",{className:"text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:l?`第 ${a} 次迭代没能启动,没有对应的 session`:`相关 session:「${i?.name??"Loop"} #${c}」(见侧栏)`})]}),s&&(0,z.jsx)("div",{className:"text-destructive",style:{fontSize:"var(--conv-font-size, 12px)"},children:s})]})}let Ai=(0,e_.default)("repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]);function Aa(e,r,s){let n=Math.round(Number(e));return Number.isFinite(n)&&""!==e.trim()?Math.min(s,Math.max(1,n)):r}function Ao({projectId:e,branch:r,disabled:s,onStarted:n}){let[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(""),[c,d]=(0,$.useState)(""),[u,h]=(0,$.useState)("claude-code"),[f,p]=(0,$.useState)(String(ry.REPEAT_LOOP_DEFAULT_ITERATIONS)),[m,g]=(0,$.useState)(String(ry.REPEAT_LOOP_DEFAULT_MINUTES)),[x,v]=(0,$.useState)(""),[y,b]=(0,$.useState)(!1),[w,_]=(0,$.useState)(null),S=async()=>{if(e&&c.trim()&&!y){b(!0),_(null);try{let s=await ry.api.createRepeatLoop({projectId:e,branch:r,prompt:c.trim(),agentType:u,...o.trim()?{name:o.trim()}:{},maxIterations:Aa(f,ry.REPEAT_LOOP_DEFAULT_ITERATIONS,ry.REPEAT_LOOP_MAX_ITERATIONS),maxMinutes:Aa(m,ry.REPEAT_LOOP_DEFAULT_MINUTES,ry.REPEAT_LOOP_MAX_MINUTES),...x.trim()?{checkCommand:x.trim()}:{}});n?.(s),a(!1),d(""),l(""),v(""),gS.toast.success("Loop started")}catch(e){_(e instanceof Error?e.message:String(e))}finally{b(!1)}}};return(0,z.jsxs)(t8,{open:i,onOpenChange:a,children:[(0,z.jsx)(t9,{asChild:!0,children:(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:!e||s,title:s?"A loop is already running on this workspace":"New loop — repeat one instruction, a fresh session per item, until done","aria-label":"New loop",children:(0,z.jsx)(Ai,{className:"h-3.5 w-3.5"})})}),(0,z.jsxs)(rs,{className:"sm:max-w-xl",onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),S())},children:[(0,z.jsxs)(rn,{children:[(0,z.jsx)(ra,{children:"New loop"}),(0,z.jsx)(ro,{children:"Runs the same instruction again and again — each time in a fresh agent session that handles one item and is then stopped — until a session reports there is nothing left."})]}),(0,z.jsxs)("div",{className:"space-y-3 text-sm",children:[(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsx)("label",{htmlFor:"loop-prompt",className:"font-medium",children:"Instruction"}),(0,z.jsx)(rc,{id:"loop-prompt",rows:6,value:c,onChange:e=>d(e.target.value),placeholder:"Fetch the unprocessed items from …, pick the first one, handle it, and mark it processed.\nIf none are left, say so."}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:"No session remembers the previous one: say where the next unprocessed item is found, and how an item is marked done. Make handling an item safe to repeat — an interrupted item may be picked up again."})]}),(0,z.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsx)("label",{htmlFor:"loop-name",className:"font-medium",children:"Name"}),(0,z.jsx)(rl,{id:"loop-name",value:o,onChange:e=>l(e.target.value),placeholder:"Loop",maxLength:80})]}),(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsx)("span",{className:"font-medium",children:"Agent"}),(0,z.jsx)("div",{className:"flex gap-1",role:"group","aria-label":"Agent",children:["claude-code","codex"].map(e=>(0,z.jsx)(W.Button,{type:"button",size:"sm",variant:u===e?"default":"outline","aria-pressed":u===e,onClick:()=>h(e),children:"claude-code"===e?"Claude Code":"Codex"},e))})]}),(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsx)("label",{htmlFor:"loop-iterations",className:"font-medium",children:"Stop after (items)"}),(0,z.jsx)(rl,{id:"loop-iterations",inputMode:"numeric",value:f,onChange:e=>p(e.target.value)})]}),(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsx)("label",{htmlFor:"loop-minutes",className:"font-medium",children:"Stop after (minutes)"}),(0,z.jsx)(rl,{id:"loop-minutes",inputMode:"numeric",value:m,onChange:e=>g(e.target.value)})]})]}),(0,z.jsxs)("div",{className:"space-y-1",children:[(0,z.jsxs)("label",{htmlFor:"loop-check",className:"font-medium",children:["Check command ",(0,z.jsx)("span",{className:"font-normal text-muted-foreground",children:"(optional)"})]}),(0,z.jsx)(rl,{id:"loop-check",value:x,onChange:e=>v(e.target.value),placeholder:"npm test",className:"font-mono"}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:"Runs in the worktree after each item; a non-zero exit stops the loop."})]}),(0,z.jsx)("p",{className:"text-xs text-amber-600",children:"Sessions run in edit mode with no confirmation between items. The loop stops on its own when an item is blocked, fails, or a limit is reached — and you can stop it any time."}),w&&(0,z.jsx)("p",{className:"text-xs text-destructive",children:w})]}),(0,z.jsxs)(ri,{children:[(0,z.jsx)(W.Button,{variant:"ghost",onClick:()=>a(!1),children:"Cancel"}),(0,z.jsx)(W.Button,{onClick:()=>void S(),disabled:!c.trim()||y,children:"Start loop"})]})]})]})}let Al=(0,e_.default)("radio",[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);function Ac({messages:e}){let{scrollToBottom:r}=cB(),s=(0,$.useRef)(e.length);return(0,$.useEffect)(()=>{let n=s.current;if(s.current=e.length,!(e.length<=n))for(let s=n;s<e.length;s++){let n=e[s];if("user"===n.type&&n.content.startsWith("[Executor Event:"))return void r({animation:"instant"})}},[e,r]),null}let Ad=(0,$.forwardRef)(function({projectId:e,branch:r},s){let{session:n,messages:i,status:a,isInitialized:o,isLoading:l,error:c,sendMessage:d,stopGeneration:u,restartSession:h,workflowRunUpdate:f,streamEpoch:p,draft:m,setDraft:g,setEventListening:x}=function(e,r){let s=e?TX(e,r):null,[n,i]=(0,$.useState)(()=>e?new TQ(e,r):null);return(n?.key??null)!==s&&i(e?new TQ(e,r):null),(0,$.useEffect)(()=>{if(n)return n.start(),()=>n.stop()},[n]),{...(0,$.useSyncExternalStore)(n?.subscribe??T0,n?.getSnapshot??T1,n?.getSnapshot??T1),sendMessage:n?.sendMessage??T2,stopGeneration:n?.stopGeneration??T2,restartSession:n?.restartSession??T2,setDraft:n?.setDraft??T5,setEventListening:n?.setEventListening??T2}}(e,r),{settings:v}=(0,mo.useConversationSettings)(),[y,b]=(0,$.useState)([]);(0,$.useImperativeHandle)(s,()=>({sendMessage:async e=>{let r=e.trim();r&&await d(r)}}),[d]);let w=n?.eventListeningEnabled??!1,_="running"===a,S=(0,$.useCallback)(async e=>{let r=e.text.trim();r&&(g(""),await d(r))},[d,g]);return e?(0,z.jsxs)("div",{className:"h-full flex flex-col min-h-0",style:{"--conv-font-size":`${v.chatFontSize}px`},children:[(0,z.jsxs)("div",{className:"flex-shrink-0 flex items-center justify-between px-4 h-10 border-b border-border/60 bg-muted/20",children:[(0,z.jsxs)("div",{className:"flex items-center gap-2",children:[(0,z.jsx)(sR,{className:"h-3.5 w-3.5 text-primary"}),(0,z.jsx)("span",{className:"text-xs font-medium text-foreground",children:"Main Chat"}),_&&(0,z.jsx)(sC,{className:"h-3 w-3 animate-spin text-primary/60"})]}),n&&(0,z.jsxs)("div",{className:"flex items-center gap-1",children:[(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:async()=>{try{await x(!w)}catch{gS.toast.error("Failed to toggle event listening")}},className:`h-7 w-7 ${w?"text-amber-500":""}`,title:w?"Listening to executor events (click to disable)":"Listen to executor events (click to enable)",children:(0,z.jsx)(Al,{className:"h-3.5 w-3.5"})}),(0,z.jsx)(Ao,{projectId:e,branch:r,disabled:y.some(e=>"repeat"===e.kind)}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:()=>h(),disabled:_,className:"h-7 w-7",title:"New Conversation",children:(0,z.jsx)(Ry,{className:"h-3.5 w-3.5"})})]})]}),(0,z.jsx)(As,{projectId:e,branch:r,runUpdate:f,streamEpoch:p,onRunsChange:b}),(0,z.jsxs)(cz,{className:"flex-1 min-h-0",initial:"instant",children:[(0,z.jsx)(Ac,{messages:i}),(0,z.jsxs)(c$,{className:"gap-4 p-4",children:[l&&0===i.length&&(0,z.jsx)("div",{className:"flex items-center justify-center py-8",children:(0,z.jsx)(sC,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),!l&&o&&0===i.length&&(0,z.jsxs)("div",{className:"text-center py-16",children:[(0,z.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mb-4",children:(0,z.jsx)(sR,{className:"h-6 w-6 text-primary/60"})}),(0,z.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Start a conversation"}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Chat with the AI assistant about your project"})]}),i.map((s,i)=>{if("turn_end"===s.type)return(0,z.jsxs)("div",{className:"mx-4 my-3 flex items-center gap-2","aria-hidden":!0,children:[(0,z.jsx)("div",{className:"h-px flex-1 bg-border"}),(0,z.jsx)("div",{className:"h-1 w-1 shrink-0 rounded-full bg-border"}),(0,z.jsx)("div",{className:"h-px flex-1 bg-border"})]},i);if("user"===s.type&&s.content.startsWith("[System Invariant Violation]")){let e=s.content.replace(/^\[System Invariant Violation\]\n?/,"");return(0,z.jsxs)("div",{className:"mx-4 my-2 flex gap-2 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2",children:[(0,z.jsx)(s7,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),(0,z.jsxs)("div",{className:"min-w-0",children:[(0,z.jsx)("div",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:"System invariant correction"}),(0,z.jsx)("div",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:e})]})]},i)}if("user"===s.type){let n=s.event,a=n?.kind==="agent_task_completed"&&y.some(e=>e.source_session_id===n.sessionId||e.reviewer_session_id===n.sessionId);return(0,z.jsxs)("div",{children:[(0,z.jsx)(cC,{from:"user",children:(0,z.jsx)(cN,{style:{fontSize:"var(--conv-font-size, 14px)"},children:s.content})}),n?.kind==="agent_task_completed"&&(0,z.jsx)("div",{className:"mt-1 flex justify-end",children:(0,z.jsx)(W.Button,{variant:"outline",size:"sm",disabled:a,title:a?"该 session 已在一个进行中的 review 里":void 0,onClick:async()=>{if(e)try{await ry.api.createWorkflowRun({projectId:e,branch:r,sourceSessionId:n.sessionId,sourceTurnEndIndex:n.turnEndEntryIndex})}catch(e){alert(e instanceof Error?e.message:String(e))}},children:"Review"})})]},i)}return"assistant"===s.type?(0,z.jsx)(cC,{from:"assistant",children:(0,z.jsx)(cN,{style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,z.jsx)(cE,{children:s.content})})},i):"tool_use"===s.type?(0,z.jsxs)("div",{className:"flex items-center gap-2 px-4 py-2 text-xs text-muted-foreground",children:[(0,z.jsx)(sA,{className:"w-3.5 h-3.5 animate-pulse"}),(0,z.jsx)("span",{children:function(e){switch(e){case"getExecutorStatus":return"Checking executor status...";case"getAgentConversation":return"Checking agent conversation...";case"listTerminals":return"Listing terminals...";case"runInTerminal":return"Sending command to terminal...";case"spawnAgentSession":return"Starting a coding agent...";case"sendToAgentSession":return"Sending a message to the agent...";default:return`Running ${e}...`}}(s.tool)})]},i):"tool_result"===s.type?(0,z.jsx)("div",{className:"px-4 py-2",children:(0,z.jsxs)("details",{className:"text-xs text-muted-foreground",children:[(0,z.jsx)("summary",{className:"cursor-pointer hover:text-foreground",children:"Tool result"}),(0,z.jsx)("pre",{className:"mt-1 p-2 bg-muted/50 rounded overflow-x-auto whitespace-pre-wrap",style:{fontSize:"var(--conv-font-size, 12px)"},children:s.output})]})},i):"tool_approval_request"===s.type?n?(0,z.jsx)(T3,{sessionId:n.id,approvalId:s.approvalId,tool:s.tool,input:s.input,resolved:s.resolved},i):null:"error"===s.type?(0,z.jsx)("div",{className:"mx-auto max-w-[90%] rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-destructive",style:{fontSize:"var(--conv-font-size, 14px)"},children:s.message},i):null}),c&&(0,z.jsx)("div",{className:"mx-auto max-w-[90%] rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:c})]}),(0,z.jsx)(cW,{})]}),(0,z.jsxs)("div",{className:"flex-shrink-0 py-3 px-[22px]",children:[_&&(0,z.jsx)("div",{className:"flex justify-center mb-2",children:(0,z.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:u,className:"gap-1.5",children:[(0,z.jsx)(lG,{className:"h-3 w-3"}),"Stop generating"]})}),(0,z.jsxs)(D4,{onSubmit:S,className:"w-full",children:[(0,z.jsx)(D6,{disabled:!o||_,placeholder:o?_?"Waiting for response...":"Type a message...":"Connecting...",className:"pr-12",style:{fontSize:"var(--conv-font-size, 14px)"},value:m,onChange:e=>g(e.currentTarget.value)}),(0,z.jsx)("div",{className:"pointer-events-none absolute bottom-0 right-2 flex items-center text-base md:text-sm",style:{fontSize:"var(--conv-font-size, 14px)",height:"calc(1lh + 1.5rem)"},children:(0,z.jsx)(Rn,{className:"pointer-events-auto",disabled:!o||_||!m.trim()})})]})]})]}):(0,z.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(sR,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to start chatting"})]})})}),Au=(0,e_.default)("archive-restore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);function Ah({task:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,onClick:o,worktrees:l,assignedBranches:c,onAssign:d}){let[u,h]=(0,$.useState)(!1),[f,p]=(0,$.useState)(e.title),m=(0,$.useRef)(null);(0,$.useEffect)(()=>{u&&(m.current?.focus(),m.current?.select())},[u]),(0,$.useEffect)(()=>{p(e.title)},[e.title]);let g=()=>{h(!1);let s=f.trim();s&&s!==e.title?r(e.id,{title:s}):p(e.title)},x="done"===e.status||"cancelled"===e.status;return(0,z.jsxs)(u5,{className:"group cursor-pointer",onClick:()=>o?.(e),children:[(0,z.jsx)(u4,{className:"w-10",onClick:e=>e.stopPropagation(),children:(0,z.jsx)(ew,{checked:"done"===e.status,onCheckedChange:s=>{r(e.id,{status:s?"done":"todo"})}})}),(0,z.jsx)(u4,{className:"font-medium",children:u?(0,z.jsx)("input",{ref:m,className:"w-full bg-transparent border-b border-primary outline-none text-sm py-0.5",value:f,onChange:e=>p(e.target.value),onBlur:g,onClick:e=>e.stopPropagation(),onKeyDown:r=>{"Enter"===r.key&&g(),"Escape"===r.key&&(p(e.title),h(!1))}}):(0,z.jsxs)("div",{children:[(0,z.jsx)("span",{className:`cursor-pointer hover:underline text-sm ${x?"line-through text-muted-foreground":""}`,onClick:e=>{e.stopPropagation(),h(!0)},children:e.title}),e.description&&(0,z.jsx)("p",{className:"text-xs text-muted-foreground truncate max-w-[400px] mt-0.5",children:e.description.length>80?e.description.slice(0,80)+"...":e.description})]})}),(0,z.jsx)(u4,{onClick:e=>e.stopPropagation(),children:(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)("button",{className:"focus:outline-none",children:(0,z.jsx)(so,{variant:"outline",className:`cursor-pointer text-xs ${sl[e.status].color}`,children:sl[e.status].label})})}),(0,z.jsx)(o1,{align:"start",children:sd.map(s=>(0,z.jsxs)(o2,{onClick:()=>r(e.id,{status:s}),children:[(0,z.jsx)("span",{className:`inline-block w-2 h-2 rounded-full mr-2 ${sl[s].color}`}),sl[s].label]},s))})]})}),(0,z.jsx)(u4,{onClick:e=>e.stopPropagation(),children:(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)("button",{className:"focus:outline-none",children:(0,z.jsx)(so,{variant:"outline",className:`cursor-pointer text-xs ${sc[e.priority].color}`,children:sc[e.priority].label})})}),(0,z.jsx)(o1,{align:"start",children:su.map(s=>(0,z.jsxs)(o2,{onClick:()=>r(e.id,{priority:s}),children:[(0,z.jsx)("span",{className:`inline-block w-2 h-2 rounded-full mr-2 ${sc[s].color}`}),sc[s].label]},s))})]})}),(0,z.jsx)(u4,{onClick:e=>e.stopPropagation(),children:(0,z.jsxs)(oQ,{children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsx)("button",{className:"focus:outline-none",children:(0,z.jsxs)(so,{variant:"outline",className:`cursor-pointer text-xs font-mono ${null!==e.assigned_branch?"bg-accent text-accent-foreground border-transparent":"text-muted-foreground"}`,children:[(0,z.jsx)(sq,{className:"h-3 w-3 mr-1"}),null!==e.assigned_branch?""===e.assigned_branch?"main":e.assigned_branch:"Unassigned"]})})}),(0,z.jsxs)(o1,{align:"start",children:[null!==e.assigned_branch&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(o2,{onClick:()=>d(e.id,null),children:"Unassign"}),(0,z.jsx)(o7,{})]}),l.filter(r=>{let s=null===r.branch?"":r.branch;return!(e.assigned_branch===s||c.has(s))}).map(r=>{let s=null===r.branch?"":r.branch,n=r.branch??"main";return(0,z.jsxs)(o2,{onClick:()=>d(e.id,s),children:[(0,z.jsx)(sq,{className:"h-3 w-3 mr-2"}),n]},s)})]})]})}),(0,z.jsx)(u4,{className:"text-muted-foreground text-[10.5px] font-mono",children:new Date(e.created_at).toLocaleDateString()}),(0,z.jsx)(u4,{className:"w-10",onClick:e=>e.stopPropagation(),children:(0,z.jsxs)("div",{className:"flex items-center gap-0.5",children:[a?(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",title:"Unarchive",onClick:()=>i(e.id),children:(0,z.jsx)(Au,{className:"h-3.5 w-3.5 text-muted-foreground"})}):(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",onClick:()=>n(e.id),children:(0,z.jsx)(sE,{className:"h-3.5 w-3.5 text-muted-foreground"})}),(0,z.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",title:"Delete",onClick:()=>s(e.id),children:(0,z.jsx)(rd,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})})]})}let Af={todo:0,in_progress:1,done:2,cancelled:3},Ap={urgent:0,high:1,medium:2,low:3};function Am({tasks:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,worktrees:o,onAssign:l}){let[c,d]=(0,$.useState)(null),[u,h]=(0,$.useState)("asc"),[f,p]=(0,$.useState)(null),[m,g]=(0,$.useState)(!1),x=e=>{c===e?h(e=>"asc"===e?"desc":"asc"):(d(e),h("asc"))},v=(0,$.useMemo)(()=>{if(!c)return e;let r="asc"===u?1:-1;return[...e].sort((e,s)=>{switch(c){case"title":return r*e.title.localeCompare(s.title);case"status":return r*(Af[e.status]-Af[s.status]);case"priority":return r*(Ap[e.priority]-Ap[s.priority]);case"created_at":return r*(new Date(e.created_at).getTime()-new Date(s.created_at).getTime());default:return 0}})},[e,c,u]),y=e=>c!==e?null:"asc"===u?" ↑":" ↓",b=(0,$.useMemo)(()=>new Set(e.filter(e=>null!==e.assigned_branch).map(e=>e.assigned_branch)),[e]);return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(u0,{children:[(0,z.jsx)(u1,{children:(0,z.jsxs)(u5,{children:[(0,z.jsx)(u3,{className:"w-10"}),(0,z.jsxs)(u3,{className:"cursor-pointer select-none",onClick:()=>x("title"),children:["Title",y("title")]}),(0,z.jsxs)(u3,{className:"cursor-pointer select-none w-32",onClick:()=>x("status"),children:["Status",y("status")]}),(0,z.jsxs)(u3,{className:"cursor-pointer select-none w-28",onClick:()=>x("priority"),children:["Priority",y("priority")]}),(0,z.jsx)(u3,{className:"w-32",children:"Assign"}),(0,z.jsxs)(u3,{className:"cursor-pointer select-none w-28",onClick:()=>x("created_at"),children:["Created",y("created_at")]}),(0,z.jsx)(u3,{className:"w-10"})]})}),(0,z.jsxs)(u2,{children:[v.map(e=>(0,z.jsx)(Ah,{task:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,onClick:e=>{p(e),g(!0)},worktrees:o,assignedBranches:b,onAssign:l},e.id)),0===e.length&&(0,z.jsx)(u5,{children:(0,z.jsx)("td",{colSpan:7,className:"text-center text-muted-foreground py-12 text-sm",children:(0,z.jsxs)("div",{className:"flex flex-col items-center gap-1",children:[(0,z.jsx)("p",{className:"text-sm font-medium text-foreground/60",children:"No tasks yet"}),(0,z.jsx)("p",{className:"text-xs text-muted-foreground",children:"Create one to get started."})]})})})]})]}),(0,z.jsx)(sh,{task:f,open:m,onOpenChange:g})]})}function Ag({open:e,onOpenChange:r,onSubmit:s}){let[n,i]=(0,$.useState)(""),[a,o]=(0,$.useState)("todo"),[l,c]=(0,$.useState)("medium");return(0,z.jsx)(t8,{open:e,onOpenChange:r,children:(0,z.jsxs)(rs,{className:"sm:max-w-md max-h-[85vh] flex flex-col",children:[(0,z.jsx)(rn,{children:(0,z.jsx)(ra,{children:"Create Task"})}),(0,z.jsxs)("form",{onSubmit:e=>{e.preventDefault(),n.trim()&&(s({description:n.trim(),status:a,priority:l}),i(""),o("todo"),c("medium"),r(!1))},className:"space-y-4 overflow-y-auto min-h-0 px-0.5",children:[(0,z.jsx)("div",{className:"space-y-2",children:(0,z.jsx)(rc,{placeholder:"Describe the task...",value:n,onChange:e=>i(e.target.value),className:"max-h-[40vh] focus-visible:border-input focus-visible:ring-0",rows:3,autoFocus:!0})}),(0,z.jsxs)("div",{className:"flex gap-3",children:[(0,z.jsxs)("div",{className:"flex-1 space-y-1",children:[(0,z.jsx)("label",{className:"text-xs text-muted-foreground",children:"Status"}),(0,z.jsxs)(fd,{value:a,onValueChange:e=>o(e),children:[(0,z.jsx)(fh,{children:(0,z.jsx)(fu,{})}),(0,z.jsx)(ff,{children:sd.map(e=>(0,z.jsx)(fp,{value:e,children:sl[e].label},e))})]})]}),(0,z.jsxs)("div",{className:"flex-1 space-y-1",children:[(0,z.jsx)("label",{className:"text-xs text-muted-foreground",children:"Priority"}),(0,z.jsxs)(fd,{value:l,onValueChange:e=>c(e),children:[(0,z.jsx)(fh,{children:(0,z.jsx)(fu,{})}),(0,z.jsx)(ff,{children:su.map(e=>(0,z.jsx)(fp,{value:e,children:sc[e].label},e))})]})]})]}),(0,z.jsxs)(ri,{children:[(0,z.jsx)(W.Button,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),(0,z.jsx)(W.Button,{type:"submit",disabled:!n.trim(),children:"Create"})]})]})]})})}let Ax=[{value:"all",label:"All"},{value:"todo",label:"Todo"},{value:"in_progress",label:"Doing"},{value:"done",label:"Done"},{value:"cancelled",label:"Cancelled"},{value:"archived",label:"Archived"}];function Av({projectId:e,tasks:r,loading:s,worktrees:n,onCreateTask:i,onUpdateTask:a,onDeleteTask:o,onArchiveTask:l,onUnarchiveTask:c}){let[d,u]=(0,$.useState)(!1),[h,f]=(0,$.useState)("all"),p=(0,$.useMemo)(()=>r.filter(e=>null===e.archived_at),[r]),m=(0,$.useMemo)(()=>r.filter(e=>null!==e.archived_at),[r]),g=(0,$.useMemo)(()=>{let e={all:p.length,todo:0,in_progress:0,done:0,cancelled:0,archived:m.length};for(let r of p)e[r.status]++;return e},[p,m]),x=(0,$.useMemo)(()=>"archived"===h?m:"all"===h?p:p.filter(e=>e.status===h),[p,m,h]),v="archived"===h;return e?(0,z.jsxs)("div",{className:"flex flex-col h-full",children:[(0,z.jsx)(dB,{title:"Tasks",count:p.length,actions:(0,z.jsxs)(W.Button,{size:"sm",onClick:()=>u(!0),className:"shadow-sm",children:[(0,z.jsx)(eS,{className:"h-3.5 w-3.5 mr-1.5"}),"New Task"]})}),(0,z.jsx)(dz,{children:Ax.map(e=>(0,z.jsx)(d$,{active:h===e.value,count:g[e.value],onClick:()=>f(e.value),children:e.label},e.value))}),(0,z.jsx)("div",{className:"flex-1 overflow-auto px-5 edge-scrollbar",children:s?(0,z.jsx)("div",{className:"flex items-center justify-center py-12 text-muted-foreground text-sm",children:"Loading tasks..."}):(0,z.jsx)(Am,{tasks:x,onUpdate:a,onDelete:o,onArchive:l,onUnarchive:c,archivedView:v,worktrees:n,onAssign:(e,r)=>{a(e,{assigned_branch:r})}})}),(0,z.jsx)(Ag,{open:d,onOpenChange:u,onSubmit:i})]}):(0,z.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,z.jsxs)("div",{className:"text-center",children:[(0,z.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,z.jsx)(eS,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,z.jsx)("p",{className:"text-sm",children:"Select a project to view tasks."})]})})}var Ay=e.i(115796);function Ab({open:e,onOpenChange:r,onNavigateProject:s,onNavigateWorkspace:n,onNavigateSession:i}){let[a,o]=(0,$.useState)(""),[l,c]=(0,$.useState)(null),[d,u]=(0,$.useState)(!1),h=(0,$.useRef)(null),f=(0,$.useRef)(null),p=(0,$.useRef)("");(0,$.useLayoutEffect)(()=>{p.current=a},[a]),(0,sx.useGlobalEventStream)(e=>{if("session:title"!==e.type||"string"!=typeof e.sessionId)return;let r="string"==typeof e.title?e.title.trim():"";(0,Ay.updateCachedSessionTitle)(e.sessionId,r||null)});let[m,g]=(0,$.useState)(e);e!==m&&(g(e),e&&(o(""),c((0,Ay.getCachedEmptyResults)()),u(!1)));let x=(0,$.useCallback)(async e=>{h.current?.abort();let r=new AbortController;h.current=r;let s=""===e?(0,Ay.beginEmptyQuerySearch)():null;try{let n=await (0,ry.searchAll)(e,{signal:r.signal});r.signal.aborted||(null!==s&&(0,Ay.commitEmptyQueryResults)(s,n),c(n),u(!1))}catch{r.signal.aborted||u(!0)}},[]),v=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let r=e&&!v.current;if(v.current=e,e)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>void x(a),150*!r),()=>{f.current&&clearTimeout(f.current)}},[a,e,x]),(0,$.useEffect)(()=>{if(!e)return;let r=!1;return(0,ry.refreshSearchCache)().then(()=>{r||x(p.current)}).catch(()=>{}),()=>{r=!0,h.current?.abort()}},[e,x]);let y=l?a.trim()?{sessions:l.sessions,favorites:l.favorites}:(0,Ay.overlayRecents)(l):null,b=null===l,w=!!y&&0===l.projects.length&&0===l.workspaces.length&&0===y.sessions.length&&0===y.favorites.length,_=l?.cacheState==="cold",S=e=>(0,z.jsxs)(pE,{value:`session-${e.sessionId}`,onSelect:()=>i(e),children:[(0,z.jsx)(sR,{}),(0,z.jsx)("span",{className:"truncate",children:e.title??"Untitled session"}),e.favoritedAt&&(0,z.jsx)(nt,{className:"h-3.5 w-3.5 shrink-0 fill-current text-amber-500"}),(0,z.jsxs)("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:[e.projectName," · ",e.branch??"main"," · ",function(e){if(!e)return"";let r=Date.now()-e;return r<6e4?"just now":r<36e5?`${Math.floor(r/6e4)}m ago`:r<864e5?`${Math.floor(r/36e5)}h ago`:`${Math.floor(r/864e5)}d ago`}(e.lastActiveAt)]})]},e.sessionId);return(0,z.jsxs)(pS,{open:e,onOpenChange:r,title:"Quick Switcher",description:"Search projects, workspaces, and sessions",shouldFilter:!1,instantClose:!0,className:"top-[max(1rem,calc(50%_-_175px))] translate-y-0",children:[(0,z.jsx)(pj,{placeholder:"Search projects, workspaces, sessions…",value:a,onValueChange:o}),(0,z.jsxs)(pk,{children:[d&&(0,z.jsxs)("div",{className:"flex items-center justify-between gap-2 px-4 py-3 text-sm text-destructive",children:[(0,z.jsx)("span",{children:"Search failed."}),(0,z.jsx)(W.Button,{variant:"link",size:"sm",className:"h-auto p-0 text-destructive",onClick:()=>void x(p.current),children:"Retry"})]}),!d&&b&&(0,z.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"}),"Searching…"]}),!d&&!b&&w&&_&&(0,z.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,z.jsx)(sC,{className:"h-4 w-4 animate-spin"}),"Syncing history…"]}),!d&&!b&&w&&!_&&(0,z.jsx)(pC,{children:"No results found."}),l&&l.projects.length>0&&(0,z.jsx)(pN,{heading:"Projects",children:l.projects.map(e=>(0,z.jsxs)(pE,{value:`project-${e.id}`,onSelect:()=>s(e.id),children:[(0,z.jsx)(dn,{name:e.name,size:"md"}),(0,z.jsx)("span",{children:e.name}),e.path&&(0,z.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:e.path})]},e.id))}),l&&l.workspaces.length>0&&(0,z.jsx)(pN,{heading:"Workspaces",children:l.workspaces.map(e=>(0,z.jsxs)(pE,{value:`ws-${e.projectId}-${e.targetId}-${e.branch??""}`,onSelect:()=>n(e),children:[(0,z.jsx)(sq,{}),(0,z.jsx)("span",{children:e.branch??"main"}),(0,z.jsx)("span",{className:"text-xs text-muted-foreground",children:e.projectName})]},`${e.projectId}-${e.targetId}-${e.branch??""}`))}),y&&y.sessions.length>0&&(0,z.jsx)(pN,{heading:a.trim()?"Sessions":"Recent",children:y.sessions.map(S)}),y&&y.favorites.length>0&&(0,z.jsx)(pN,{heading:"Favorites",children:y.favorites.map(S)})]})]})}let Aw={session_result_ready:"/sounds/sound1.mp3",review_ready:"/sounds/sound2.mp3",session_failed:"/sounds/failure.mp3",workflow_failed:"/sounds/failure.mp3",loop_done:"/sounds/sound1.mp3",cross_remote_token_expired:"/sounds/sound2.mp3"};function A_(e,r){let s=[...e.filter(e=>e.id!==r.id),r];return s.sort((e,r)=>r.created_at-e.created_at||(e.id<r.id?1:-1)),s}let AS=new Set(["session_result_ready","session_failed"]);function Aj(e){return AS.has(e.kind)&&e.session_id?`${e.kind}:${e.session_id}`:e.id}function Ak(e){let r=new Map;for(let s of e){let e=null===s.read_at,n=r.get(Aj(s));n?(n.ids.push(s.id),n.count+=1,e&&(n.unreadCount+=1,n.unread=!0)):r.set(Aj(s),{latest:s,ids:[s.id],count:1,unreadCount:+!!e,unread:e})}return[...r.values()]}let AC=new Map,AN=new Set,AE=(0,e_.default)("bell",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]]);async function AD(e,r){let s=e.session_id;if(e.workflow_run_id&&("workflow_failed"===e.kind||"loop_done"===e.kind)){let r=await ry.api.getWorkflowRun(e.workflow_run_id).catch(()=>null);r?.kind==="repeat"&&(s=r.source_session_id)}r(e.project_id,e.branch,s)}let AR={session_result_ready:{label:"Session result is ready",dot:"bg-lime-400"},review_ready:{label:"Review feedback is ready",dot:"bg-emerald-500"},session_failed:{label:"Session failed",dot:"bg-destructive"},workflow_failed:{label:"Workflow needs attention",dot:"bg-destructive"},loop_done:{label:"Loop finished — nothing left to process",dot:"bg-emerald-500"},cross_remote_token_expired:{label:"Cross-remote expired — stop & send a message to renew",dot:"bg-amber-500"}};function AT({notifications:e,unreadCount:r,projects:s,onNavigate:n,markRead:i,markAllRead:a,remove:o,clear:l}){let[c,d]=(0,$.useState)(!1);return(0,$.useEffect)(()=>{let e=e=>{"j"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),d(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),(0,z.jsxs)(oQ,{open:c,onOpenChange:d,children:[(0,z.jsx)(o0,{asChild:!0,children:(0,z.jsxs)(W.Button,{variant:"ghost",size:"icon-sm",className:"relative",title:"Notifications (⌘J)","aria-label":r>0?`${r} unread notifications`:"Notifications",children:[(0,z.jsx)(AE,{className:"h-4 w-4"}),r>0&&(0,z.jsx)("span",{className:"absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[9px] font-semibold leading-none text-primary-foreground",children:r>9?"9+":r})]})}),(0,z.jsxs)(o1,{align:"end",className:"w-80 p-0",children:[(0,z.jsxs)("div",{className:"flex items-center justify-between px-3 py-2",children:[(0,z.jsx)("span",{className:"text-[12.5px] font-semibold text-foreground",children:"Notifications"}),e.length>0&&(0,z.jsxs)("div",{className:"flex items-center gap-1",children:[(0,z.jsxs)("button",{onClick:a,disabled:0===r,className:"flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40",title:"Mark all read",children:[(0,z.jsx)(di,{className:"h-3 w-3"}),"Mark all read"]}),(0,z.jsx)("button",{onClick:l,className:"rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",title:"Dismiss all (marks them read)",children:"Clear"})]})]}),(0,z.jsx)("div",{className:"max-h-[60vh] overflow-y-auto border-t border-border",children:0===e.length?(0,z.jsx)("div",{className:"px-3 py-8 text-center text-[12px] text-muted-foreground/70",children:"Nothing needs your attention."}):Ak(e).map(e=>{let r,a=e.latest,l=AR[a.kind],c=e.unread;return(0,z.jsxs)(o2,{onSelect:()=>{for(let r of e.ids)i(r);AD(a,n)},className:(0,eb.cn)("group flex flex-col items-start gap-0.5 rounded-none px-3 py-2",c&&"bg-primary/[0.08]"),children:[(0,z.jsxs)("div",{className:"flex w-full items-center gap-2",children:[(0,z.jsx)("span",{className:(0,eb.cn)("h-[7px] w-[7px] shrink-0 rounded-full",l?.dot)}),(0,z.jsx)("span",{className:(0,eb.cn)("min-w-0 flex-1 truncate text-[12.5px]",c?"font-medium text-foreground":"text-foreground/70"),children:a.body??(r=a.project_id,s.find(e=>e.id===r)?.name??"Unknown project")}),e.unreadCount>1&&(0,z.jsxs)("span",{className:"shrink-0 rounded-full bg-muted px-1.5 text-[10px] font-medium leading-4 text-muted-foreground",title:`${e.unreadCount} new notifications, showing the latest`,children:["×",e.unreadCount]}),(0,z.jsx)("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:function(e){let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return"just now";let s=Math.round(r/60);if(s<60)return`${s}m ago`;let n=Math.round(s/60);if(n<24)return`${n}h ago`;let i=Math.round(n/24);return`${i}d ago`}(a.created_at)}),(0,z.jsx)("button",{onClick:r=>{for(let s of(r.stopPropagation(),e.ids))o(s)},className:"shrink-0 rounded p-0.5 text-muted-foreground/60 opacity-0 transition-all hover:bg-muted hover:text-foreground group-hover:opacity-100",title:"Dismiss (marks it read)",children:(0,z.jsx)(t7,{className:"h-3 w-3"})})]}),(0,z.jsxs)("div",{className:"flex w-full items-center gap-1.5 pl-[15px] text-[11px] text-muted-foreground",children:[(0,z.jsx)("span",{className:"font-mono truncate",children:a.branch??"main"}),(0,z.jsx)("span",{className:"text-muted-foreground/50",children:"·"}),(0,z.jsx)("span",{className:"shrink-0",children:l?.label??a.title})]})]},a.id)})})]})]})}let AA=(0,e_.default)("keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]),AI=(e,r)=>e?`⌘${r}`:`Ctrl+${r}`,AM=()=>()=>{};function AF(){let[e,r]=(0,$.useState)(!1),s=(0,$.useSyncExternalStore)(AM,fb,()=>!1);return(0,$.useEffect)(()=>{let e=e=>{let s="/"===e.key&&(e.metaKey||e.ctrlKey)&&!e.shiftKey&&!e.altKey,n="?"===e.key&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!dv(e.target);(s||n)&&(e.preventDefault(),r(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(W.Button,{variant:"ghost",size:"icon-sm","aria-label":"Keyboard shortcuts",title:"Keyboard shortcuts (?)",onClick:()=>r(!0),children:(0,z.jsx)(AA,{className:"h-4 w-4"})}),(0,z.jsx)(t8,{open:e,onOpenChange:r,children:(0,z.jsxs)(rs,{className:"sm:max-w-xl",children:[(0,z.jsx)(rn,{children:(0,z.jsx)(ra,{children:"Keyboard shortcuts"})}),(0,z.jsx)("div",{className:"grid gap-x-8 gap-y-5 sm:grid-cols-2",children:[{title:"Global",entries:[{hints:[AI(s,"K")],description:"Quick switcher"},{hints:[AI(s,"J")],description:"Notifications"},{hints:[AI(s,"B")],description:"Toggle sidebar"},{hints:[s?`⌘⇧O`:"Ctrl+Shift+O"],description:"New agent conversation"},{hints:[fj(s,fw)],description:"Start review of this session"},{hints:["a…z"],description:"Locate workspace (type, ↑↓ cycle, ↵ jump)"},{hints:["Esc"],description:"Clear locate query / unfocus right panel"},{hints:["?",AI(s,"/")],description:"This dialog"}]},{title:"Workspace tabs",entries:[...fv.map(e=>({hints:[fj(s,e.code)],description:`Open ${e.label}`})),{hints:["←","→"],description:"Switch executor target (Executors focused)"}]}].map(e=>(0,z.jsxs)("section",{children:[(0,z.jsx)("h3",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:e.title}),(0,z.jsx)("ul",{className:"space-y-1.5",children:e.entries.map(e=>(0,z.jsxs)("li",{className:"flex items-center justify-between gap-3 text-[13px]",children:[(0,z.jsx)("span",{className:"text-foreground/90",children:e.description}),(0,z.jsx)("span",{className:"flex shrink-0 items-center gap-1",children:e.hints.map(e=>(0,z.jsx)("kbd",{className:"rounded-md border border-border bg-muted px-1.5 py-0.5 font-mono text-[11px] leading-none text-foreground/80",children:e},e))})]},e.description))})]},e.title))})]})})]})}function AP(e){if(null===e)return"尚未连接";let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return`${r} 秒前`;let s=Math.floor(r/60);return s<60?`${s} 分钟前`:`${Math.floor(s/60)} 小时前`}function AL(){let{state:e,lastEventAt:r,updateAvailable:s,reconnect:n}=(0,sx.useConnectionStatus)(),[,i]=(0,$.useState)(0);if((0,$.useEffect)(()=>{let e=setInterval(()=>i(e=>e+1),5e3);return()=>clearInterval(e)},[]),"stale"===e)return(0,z.jsxs)("button",{type:"button",onClick:n,title:`实时更新已断开 \xb7 上次更新 ${AP(r)} \xb7 点击重新连接`,className:"flex items-center gap-1.5 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-600 transition-colors hover:bg-amber-500/20",children:[(0,z.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500"}),"实时更新已断开"]});if(s)return(0,z.jsxs)("button",{type:"button",onClick:()=>window.location.reload(),title:"服务器已更新到新版本 · 点击刷新页面加载",className:"flex items-center gap-1.5 rounded-full border border-sky-500/40 bg-sky-500/10 px-2 py-0.5 text-[11px] font-medium text-sky-600 transition-colors hover:bg-sky-500/20",children:[(0,z.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-sky-500"}),"有新版本 · 点击刷新"]});let a="live"===e;return(0,z.jsx)("span",{title:a?`实时更新正常 \xb7 上次更新 ${AP(r)}`:"正在连接实时更新…",className:"flex items-center px-1","aria-label":a?"实时更新正常":"正在连接实时更新",children:(0,z.jsx)("span",{className:a?"h-1.5 w-1.5 rounded-full bg-emerald-500":"h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground/40"})})}function AO(e){return null===e?"":e}function AB(){var e,r,s,n,i,a,o,l,c;let d,u,h,f,p,m,g,x,v,y,b,w,_,S,j,k,C,{projectId:N,tab:E,branch:D,threadId:R}=function(){let[e,r]=(0,$.useState)(RU);return(0,$.useEffect)(()=>{let e=()=>r(RU());return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]),e}(),{config:T}=(0,p2.useAppConfig)(),[A,I]=(0,$.useState)(()=>({branch:D,sessionId:new URLSearchParams(window.location.search).get("session")})),M=A.branch,F=A.sessionId,P=(0,$.useCallback)(e=>{I({branch:e,sessionId:null}),Z(null)},[]),L=(0,$.useCallback)(e=>{I(r=>r.sessionId===e?r:{...r,sessionId:e})},[]),[O,B]=(0,$.useState)(null),[H,U]=(0,$.useState)(null),[q,K]=(0,$.useState)(void 0),[V,X]=(0,$.useState)(void 0),[Y,G]=(0,$.useState)(null),[J,Z]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search).get("session");I(r=>r.sessionId===e?r:{...r,sessionId:e})};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]),(0,$.useEffect)(()=>{if(new URLSearchParams(window.location.search).has("project")){let e=Rq({projectId:N,tab:E,branch:D,threadId:R});window.history.replaceState(null,"",e)}},[]);let[Q,ee]=(0,$.useState)(!1),[et,er]=(0,$.useState)(!1),[es,en]=(0,$.useState)(!1),[ei,ea]=(0,$.useState)(null),[eo,el]=(0,$.useState)(E),[ec,ed]=(0,$.useState)(R),[eu,eh]=(0,$.useState)(0),[ef,ep]=(0,$.useState)(0),[em,eg]=(0,$.useState)(!1),[ex,ev]=(0,$.useState)(!1),ey=(0,$.useRef)(null),[eb,ew]=(0,$.useState)(void 0),[e_,ej]=(0,$.useTransition)(),{projects:ek,currentProject:eC,loading:eN,addProject:eE,createProject:eD,updateProject:eR,deleteProject:eT,selectProject:eA,routeProjectPending:eI,routeProjectNotFound:eM}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(null),[a,o]=(0,$.useState)(!0),[l,c]=(0,$.useState)(e),d=(0,$.useRef)(n),u=(0,$.useRef)(e);d.current=n,u.current=e;let h=l!==e,f=a||h,p=!f&&!!e&&!r.some(r=>r.id===e),m=(0,$.useCallback)(async()=>{o(!0);try{let e=await ry.api.getProjects();if(s(e),e.length>0&&!d.current){let r=u.current?e.find(e=>e.id===u.current):e[0];i(r??null)}}finally{o(!1)}},[]);(0,$.useEffect)(()=>{m()},[m]),(0,$.useEffect)(()=>{h&&!a&&(c(e),i(e?r.find(r=>r.id===e)??null:r[0]??null))},[e,a,r,h]);let g=async e=>{let r=await ry.api.createProject(e);return s(e=>[r,...e]),i(r),r},x=(0,$.useCallback)((e,r)=>{let n=e=>"function"==typeof r?r(e):r;s(r=>r.map(r=>r.id===e?n(r):r)),i(r=>r?.id===e?n(r):r)},[]),v=(0,$.useRef)(new Map),y=async(e,s)=>{let n,i={};if(void 0!==s.agentMode&&(i.agent_mode=s.agentMode),void 0!==s.executorMode&&(i.executor_mode=s.executorMode),Object.keys(i).length>0){let s=r.find(r=>r.id===e)??d.current;(n=v.current.get(e))||!s||s.id!==e||(n={seq:0,baseline:s},v.current.set(e,n)),n&&(n.seq+=1),x(e,e=>({...e,...i}))}let a=n?.seq,o=()=>!n||n.seq===a;try{let r=await ry.api.updateProject(e,s);return o()&&(n&&v.current.delete(e),x(e,r)),r}catch(r){throw n&&o()&&(v.current.delete(e),x(e,n.baseline)),r}},b=async e=>{await ry.api.deleteProject(e),s(r=>r.filter(r=>r.id!==e)),n?.id===e&&i(r.find(r=>r.id!==e)??null)};return{projects:r,currentProject:h?null:n,routeProjectPending:f,routeProjectNotFound:p,loading:a,addProject:e=>{s(r=>[e,...r]),i(e)},createProject:g,updateProject:y,deleteProject:b,selectProject:e=>{i(e)},refresh:m}}(N),eF=(0,$.useRef)(void 0);if(eC?.id!==eb){if(void 0!==eb){let s=(e=eF.current,r=eC?.id,e&&void 0!==r&&e.projectId===r?{branch:e.branch,sessionId:e.sessionId}:{branch:null,sessionId:null});I(s),s.sessionId&&eh(e=>e+1)}ew(eC?.id)}let{worktrees:eP,loading:eL,stale:eO,listWarning:eB,refetch:ez}=function(e,r,s){let n=e?`${e}::${s??"local"}`:null,[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)(c1),[c,d]=(0,$.useState)(!0),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(null),m=(0,$.useRef)(null),g=e=>{m.current=e,h(e)},[x,v]=(0,$.useState)(null);if(n!==x){v(n),p(null);let e=n?c0.get(n):void 0;e&&(a(e),g(n),d(!0))}let y=(0,$.useRef)(0),b=(0,$.useRef)(null),w=(0,$.useRef)(0),_=(0,$.useRef)(null),S=(0,$.useRef)(r);S.current=r;let j=(0,$.useCallback)(async(r=!1)=>{if(r&&b.current)return;b.current?.abort();let s=new AbortController;b.current=s,w.current=0;let i=y.current;if(!e||!n){b.current=null,a([]),l(c1),g(null),p(null),d(!1);return}r||d(!0);let o=!1;try{let c=await ry.api.getProjectWorktreeList(e,void 0,s.signal);if(i!==y.current)return;let d=c.worktrees;c0.set(n,d),p(n),l(e=>{let r={staleRemote:c.stale??null,activeRemoteInvalid:!0===c.activeRemoteInvalid};return e.staleRemote?.serverId===r.staleRemote?.serverId&&e.activeRemoteInvalid===r.activeRemoteInvalid?e:r}),o=!0,a(e=>{let s=r?function(e,r,s){if(void 0===s||r.some(e=>e.branch===s))return r;let n=e.findIndex(e=>e.branch===s);if(n<0)return r;let i=[...r];return i.splice(Math.min(n,i.length),0,e[n]),i}(e,d,S.current):d;return e.length===s.length&&e.every((e,r)=>e.branch===s[r].branch&&e.currentBranch===s[r].currentBranch&&e.expectedBranch===s[r].expectedBranch&&cQ(e)===cQ(s[r]))?e:s})}catch(e){if(i!==y.current||e instanceof Error&&"AbortError"===e.name)return;console.error("Failed to fetch worktrees:",e),r||m.current===n||a([{branch:null}])}finally{if(i!==y.current||b.current!==s)return;o&&(w.current=Date.now()),g(n),r||d(!1),b.current=null}},[e,n]),k=(0,$.useCallback)(()=>{Date.now()-w.current<5e3||j(!0)},[j]);return(0,$.useEffect)(()=>(j(),()=>{b.current?.abort(),b.current=null,y.current+=1}),[j]),(0,$.useEffect)(()=>{let e=_.current;_.current={projectId:n,branch:r},e&&e.projectId===n&&e.branch!==r&&j(!0)},[n,r,j]),(0,sx.useGlobalEventStream)(r=>{if(!e||r.projectId!==e)return;let s="session:status"===r.type&&("stopped"===r.status||"error"===r.status);("session:taskCompleted"===r.type||"executor:stopped"===r.type||s)&&j(!0)}),(0,$.useEffect)(()=>{let e=null,r=()=>{null!==e&&(window.clearInterval(e),e=null)},s=()=>{r(),e=window.setInterval(()=>void j(!0),3e5)},n=()=>k(),i=()=>{"visible"===document.visibilityState?(k(),s()):r()};return window.addEventListener("focus",n),document.addEventListener("visibilitychange",i),"visible"===document.visibilityState&&s(),()=>{r(),window.removeEventListener("focus",n),document.removeEventListener("visibilitychange",i)}},[j,k]),{worktrees:i,loading:c||f!==n,stale:u!==n,listWarning:o,refetch:(0,$.useCallback)(()=>j(!1),[j])}}(eC?.id??null,M,eC?.agent_mode??null),{statuses:e$,rootDirty:eW,defaultTarget:eH,repositoryLabel:eU,repositoryServerId:eq,setTarget:eK,refetch:eV}=function(e,r){let[s,n]=(0,$.useState)(new Map),[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(null),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(0),[m,g]=(0,$.useState)(e);e!==m&&(g(e),n(new Map),a(!1),l(null),d(null));let x=(0,$.useCallback)(()=>p(e=>e+1),[]);return(0,$.useEffect)(()=>{let s,i=r.map(e=>e.branch).filter(e=>null!==e),o=new Set(i),c=(s=r.find(e=>null===e.branch))?(void 0===s.currentBranch?s.expectedBranch:s.currentBranch)??null:null,u=i.map(e=>({branch:e}));null===c||o.has(c)||u.push({branch:c});let f=!1;return(async()=>{if(!e||0===u.length){f||(n(new Map),a(!1),l(null),d(null));return}if(c5(e).length>0&&(await function(e){let r=c3.get(e);if(r)return r;let s=(async()=>{let r=new Map;for(;;){let s=c5(e).filter(({key:e,target:s})=>r.get(e)!==s);if(0===s.length)break;for(let{key:n,branch:i,target:a}of s){r.set(n,a);let s=!1;try{s=await ry.api.setMergeTarget(e,i,a,{ifAbsent:!0})}catch{}if(s)try{localStorage.getItem(n)===a&&localStorage.removeItem(n)}catch{}}}})();return c3.set(e,s),s.finally(()=>{c3.get(e)===s&&c3.delete(e)}),s}(e),f))return;let r=await ry.api.getMergeStatus(e,u);f||r.ok&&(n(function(e){let r=new Map;for(let s of e){if("target-not-found"===s.error&&s.requestedTarget){r.set(s.branch,{branch:s.branch,error:s.error,requestedTarget:s.requestedTarget,targetSource:s.targetSource});continue}!s.error&&s.target&&s.status&&r.set(s.branch,{branch:s.branch,status:s.status,unmergedCount:s.unmergedCount??0,dirty:s.dirty??!1,target:s.target})}return r}(r.entries.filter(e=>o.has(e.branch)).map(e=>e.branch===c?{...e,dirty:!1}:e))),a(null!==c&&(r.entries.find(e=>e.branch===c)?.dirty??!1)),l(function(e){for(let r of e)if("default"===r.targetSource&&r.target)return r.target;return null}(r.entries)),d(r.repository.label),h("local"===r.repository.kind?"local":r.repository.remoteServerId))})(),()=>{f=!0}},[e,r,f,x]),{statuses:s,rootDirty:i,defaultTarget:o,repositoryLabel:c,repositoryServerId:u,setTarget:(0,$.useCallback)((r,s)=>{e&&ry.api.setMergeTarget(e,r,s).then(e=>{e&&x()})},[e,x]),refetch:x}}(eC?.id??null,eP),eX=function(e,r){let[s,n]=(0,$.useState)(()=>TO(e));s.projectId!==e&&n(TO(e));let i=(0,$.useRef)(e);(0,$.useEffect)(()=>{i.current=e},[e]);let a=(0,$.useRef)(new Map),o=(0,$.useRef)(new Map),[l,c]=(0,$.useState)(0),d=(0,$.useRef)(new Set),u=(0,$.useCallback)(e=>{n(r=>{let s=Date.now();return T$(e(r,s),d.current,s)})},[]),h=(0,$.useCallback)((e,r)=>{let s=i.current;if(!s)return;let n=`${s}\0${e??""}`,l=(a.current.get(n)??0)+1;a.current.set(n,l);let{request:c,issuedAt:d}=Rg(s,e,{force:r});c.then(r=>{i.current!==s||(o.current.get(n)??0)>=l||(o.current.set(n,l),u((s,n)=>(function(e,r,s,n,i=n){let a=e;for(let e of s)a=Tz(a,e,n);let o=new Set(s.map(e=>e.id)),l=[];for(let e of a.entries.values())(e.branch??null)===(r??null)&&(o.has(e.runId)||e.insertedAt>i||l.push(e.runId));return l.length>0?TB(a,l,n):a})(s,e,r,n,d)))}).catch(()=>{})},[u]);(0,$.useEffect)(()=>{e&&h(r,!1)},[e,r,h]);let{state:f}=(0,sx.useConnectionStatus)(),p=(0,$.useRef)(null),m=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let s=p.current;p.current=f;let n=TA(s,f,m.current);"live"===f&&(m.current=!0),n&&e&&h(r,!0)},[f,e,r,h]),(0,sx.useGlobalEventStream)(r=>{if("workflow:run-updated"!==r.type||!e||r.projectId!==e)return;let s=r.run;s&&"string"==typeof s.id&&u((e,r)=>Tz(e,s,r))});let g=(0,$.useCallback)((e,r)=>{u((s,n)=>Tz(s,e,n,r))},[u]),x=(0,$.useCallback)(e=>{d.current=e,n(r=>T$(r,e,Date.now()))},[]),v=(0,$.useMemo)(()=>[...s.entries.values()],[s]),y=JSON.stringify([...new Set(v.filter(e=>null===e.appearedAt).map(e=>e.branch??""))].sort());(0,$.useEffect)(()=>{let e=JSON.parse(y);if(0===e.length)return;let r=setInterval(()=>{for(let r of(n(e=>(function(e,r){let s=[];for(let n of e.entries.values())n.insertedAt+72e4<=r&&s.push(n.runId);let n=s.length>0?TB(e,s,r):e,i=!1;for(let e of n.tombstones.values())if(e<=r){i=!0;break}if(i){let e=new Map;for(let[s,i]of n.tombstones)i>r&&e.set(s,i);n={...n,tombstones:e}}return n})(e,Date.now())),e))h(""===r?null:r,!0);c(e=>e+1)},5e3);return()=>clearInterval(r)},[y,h]);let b=(0,$.useMemo)(()=>v.filter(e=>null===e.appearedAt&&"preparing"!==e.run.status&&!TP(e.run.status)).map(e=>e.reviewerSessionId),[v]);return(0,$.useMemo)(()=>({entries:v,addRun:g,awaitedSessionIds:b,pollTick:l,markAppeared:x}),[v,g,b,l,x])}(eC?.id??null,M),eY=function(e,r,s,n){let i=JSON.stringify((r??[]).map(e=>e.branch)),a=(0,$.useMemo)(()=>JSON.parse(i),[i]),[o,l]=(0,$.useState)([]),[c,d]=(0,$.useState)(null);e!==c&&(d(e),l(e?TI.get(e)??[]:[]));let u=(0,$.useRef)(e);u.current=e;let h=(0,$.useRef)(new Map),f=(0,$.useRef)(0),p=(0,$.useRef)(0),m=(0,$.useRef)(0),g=(0,$.useCallback)(e=>!(e<m.current)&&(m.current=e,!0),[]);(0,$.useEffect)(()=>{e&&TI.set(e,o)},[e,o]);let[x,v]=(0,$.useState)(null),y=(0,$.useCallback)((e,r,s,n=1/0)=>{if(null===r||u.current!==e)return;let i=r.filter(e=>{let r=h.current.get(e.id);return void 0===r||r<=n});l(e=>{let r,n=(r=new Map(e.map(e=>[e.id,e])),i.map(e=>{let s=r.get(e.id);return s&&"New Session"===e.title&&"New Session"!==s.title?{...e,title:s.title}:e}));if(!s||n.some(e=>e.id===s))return n;let a=e.find(e=>e.id===s);return a?[a,...n]:n})},[]),b=(0,$.useCallback)(async r=>{if(!e)return void l([]);let s=f.current,n=++p.current,i=await TR(e);if(u.current===e&&g(n)){if("incomplete"===i)return void v(r=>({projectId:e,gen:(r?.gen??0)+1}));v(r=>r?.projectId===e?null:r),y(e,i,r?.keepSessionId,s)}},[e,y,g]);(0,$.useEffect)(()=>{let e=!1;return b().catch(r=>{e||console.warn("[ResidentSessions] refresh failed:",r)}),()=>{e=!0}},[b]),(0,$.useEffect)(()=>{if(!e||x?.projectId!==e)return;let r=!1,s=f.current,n=++p.current;return TT(e,a).then(i=>{!r&&g(n)&&y(e,i,void 0,s)}).catch(e=>{r||console.warn("[ResidentSessions] fallback refresh failed:",e)}),()=>{r=!0}},[e,x,a,y,g]);let{state:w}=(0,sx.useConnectionStatus)(),_=(0,$.useRef)(null),S=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let e=_.current;_.current=w;let r=TA(e,w,S.current);"live"===w&&(S.current=!0),r&&b().catch(e=>console.warn("[ResidentSessions] reconnect refresh failed:",e))},[w,b]);let j=n&&n.sessionIds.length>0?`${n.tick}#${n.sessionIds.join("\0")}`:"",k=(0,$.useRef)(o);return(0,$.useEffect)(()=>{k.current=o},[o]),(0,$.useEffect)(()=>{!j||j.slice(j.indexOf("#")+1).split("\0").every(e=>k.current.some(r=>r.id===e))||b().catch(e=>console.warn("[ResidentSessions] awaited refresh failed:",e))},[j,b]),(0,$.useEffect)(()=>{if(!s||!s.processAlive||!e||s.projectId!==e||h.current.has(s.id))return;let r=!k.current.some(e=>e.id===s.id);l(e=>(function(e,r){let s=e.findIndex(e=>e.id===r.id);if(-1===s)return[r,...e];let n=e[s],i="New Session"===r.title&&"New Session"!==n.title?n.title:r.title,a=[...e];return a[s]={...r,title:i,status:n.status},a})(e,s)),r&&b({keepSessionId:s.id}).catch(e=>console.warn("[ResidentSessions] seed refresh failed:",e))},[e,s,b]),(0,sx.useGlobalEventStream)(r=>{if(e&&r.projectId===e){if("session:process"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null,s="boolean"==typeof r.alive?r.alive:null,n="string"==typeof r.branch?r.branch:null;if(!e||null===s)return;if(!s){h.current.set(e,++f.current),l(r=>r.filter(r=>r.id!==e));return}h.current.delete(e),b().catch(e=>console.warn("[ResidentSessions] process refresh failed:",e)),null!==n&&l(r=>r.map(r=>r.id===e?{...r,branch:n}:r))}if("session:status"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null,s="string"==typeof r.status?r.status:null;if(!e||!s)return;l(r=>r.map(r=>r.id===e?{...r,status:s}:r))}if("session:title"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null;if(!e)return;l(s=>{var n,i;return i=("string"==typeof(n=r.title)?n.trim():"")||"New Session",s.map(r=>r.id===e?{...r,title:i}:r)})}}}),(0,$.useMemo)(()=>{let e=new Map;for(let r of o){let s=r.branch??"",n=e.get(s)??[];n.push(r),e.set(s,n)}for(let r of e.values())r.sort((e,r)=>(r.updated_at??"").localeCompare(e.updated_at??""));return e},[o])}(eC?.id??null,eP,O,{sessionIds:eX.awaitedSessionIds,tick:eX.pollTick}),eG=(0,$.useMemo)(()=>{let e=new Set;for(let r of eY.values())for(let s of r)e.add(s.id);return e},[eY]),eJ=(0,$.useCallback)(e=>{for(let r of eY.values()){let s=r.find(r=>r.id===e);if(s)return s.title}return null},[eY]),eZ=(0,$.useMemo)(()=>(function(e,r,s){if(0===r.length)return e;let n=new Map(e),i=new Set;for(let r of e.values())for(let e of r)i.add(e.id);for(let e of r){var a;if(null!==e.appearedAt||i.has(e.reviewerSessionId))continue;let r=e.branch??"",o=n.get(r)??[];n.set(r,[(a=s(e.sourceSessionId),{id:e.reviewerSessionId,projectId:e.projectId,branch:e.branch,title:TW(e,a),status:"preparing",processAlive:!1,updated_at:e.run.created_at,kind:TM,runId:e.runId}),...o])}return n})(eY,eX.entries,eJ),[eY,eX.entries,eJ]),eQ=null!==J&&J.projectId===eC?.id,e0=eQ?eX.entries.find(e=>e.runId===J.runId):void 0,{tasks:e1,loading:e2,createTask:e5,updateTask:e3,deleteTask:e4,archive:e6,unarchive:e7,refetch:e8}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(!0),a=(0,$.useCallback)(async()=>{if(!e){s([]),i(!1);return}try{let r=await ry.api.getTasks(e,{includeArchived:!0});s(r)}catch(e){console.error("Failed to fetch tasks:",e)}finally{i(!1)}},[e]);(0,$.useEffect)(()=>{a()},[a]);let o=(0,$.useCallback)(async r=>{if(!e)return null;try{let n=await ry.api.createTask(e,r);return s(e=>[...e,n]),n}catch(e){return console.error("Failed to create task:",e),null}},[e]),l=(0,$.useCallback)(async(e,n)=>{s(r=>r.map(r=>r.id===e?{...r,...n,updated_at:new Date().toISOString()}:r));try{let r=await ry.api.updateTask(e,n);return s(s=>s.map(s=>s.id===e?r:s)),r}catch(e){return console.error("Failed to update task:",e),s(r),null}},[r]),c=(0,$.useCallback)(async e=>{s(r=>r.filter(r=>r.id!==e));try{await ry.api.deleteTask(e)}catch(e){console.error("Failed to delete task:",e),s(r)}},[r]),d=(0,$.useCallback)(async e=>{s(r=>r.map(r=>r.id===e?{...r,archived_at:Date.now()}:r));try{let r=await ry.api.archiveTask(e);s(s=>s.map(s=>s.id===e?r:s))}catch(e){console.error("Failed to archive task:",e),s(r)}},[r]),u=(0,$.useCallback)(async e=>{s(r=>r.map(r=>r.id===e?{...r,archived_at:null}:r));try{let r=await ry.api.unarchiveTask(e);s(s=>s.map(s=>s.id===e?r:s))}catch(e){console.error("Failed to unarchive task:",e),s(r)}},[r]),h=(0,$.useCallback)(async n=>{if(e){s(n.map(e=>r.find(r=>r.id===e)).filter(e=>void 0!==e));try{await ry.api.reorderTasks(e,n)}catch(e){console.error("Failed to reorder tasks:",e),s(r)}}},[e,r]);return{tasks:r,loading:n,createTask:o,updateTask:l,deleteTask:c,archive:d,unarchive:u,reorderTasks:h,refetch:a}}(eC?.id??null),{schedules:e9,loading:te,createSchedule:tt,updateSchedule:tr,deleteSchedule:ts,runNow:tn}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(!1),[a,o]=(0,$.useState)(null);e!==a&&(o(e),s(e?c6.get(e)??[]:[])),(0,$.useEffect)(()=>{e&&c6.set(e,r)},[e,r]);let l=(0,$.useRef)(e),c=(0,$.useRef)(0),d=(0,$.useCallback)(async(e,r,n)=>{if(!e){c.current===r&&(s([]),i(!1));return}n&&i(!0);try{let n=await ry.api.getSchedules(e);c.current===r&&s(n)}catch(e){console.error("Failed to fetch schedules:",e)}finally{n&&c.current===r&&i(!1)}},[]);(0,$.useEffect)(()=>{l.current=e,c.current+=1,d(e,c.current,!0)},[e,d]);let u=(0,$.useCallback)(async()=>{let e=l.current;e&&await d(e,c.current,!1)},[d]),h=(0,$.useRef)(u);(0,$.useEffect)(()=>{h.current=u},[u]),(0,sx.useGlobalEventStream)(e=>{!e.type?.startsWith("schedule:")||l.current&&e.projectId===l.current&&h.current()});let f=(0,$.useCallback)(async r=>{if(!e)throw Error("No project selected");let s=await ry.api.createSchedule(e,r);return await u(),s},[e,u]),p=(0,$.useCallback)(async(e,r)=>{let s=await ry.api.updateSchedule(e,r);return await u(),s},[u]),m=(0,$.useCallback)(async e=>{await ry.api.deleteSchedule(e),await u()},[u]),g=(0,$.useCallback)(async(e,r)=>{let s=r;if(!s){let e=crypto.randomUUID();s={requestId:e,runId:e}}let n=await ry.api.runScheduleNow(e,s);return await u(),n},[u]);return{schedules:r,loading:n,refetch:u,createSchedule:f,updateSchedule:p,deleteSchedule:m,runNow:g}}(eC?.id??null),[ti,ta]=(0,$.useState)(null),[to,tl]=(0,$.useState)(null),[tc,td]=(0,$.useState)(!1),[tu,th]=(0,$.useState)(null),{activity:tf,since:tp,refetch:tm,setOptimisticActivity:tg}=function(e){let[r,s]=(0,$.useState)(new Map),[n,i]=(0,$.useState)(new Map),a=(0,$.useRef)(new Map),o=(0,$.useRef)(new Map),l=(0,$.useRef)(null),c=(0,$.useCallback)(async()=>{if(!e){s(new Map),i(new Map),o.current=new Map,l.current=null,a.current=new Map;return}try{let r=await (0,ry.authFetch)(`${"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}/api/projects/${e}/branches/activity`);if(!r.ok)return;let n=await r.json(),c=l.current!==e,{nextActivity:d,nextSince:u}=function(e,r,s,n){let i=new Map,a=new Map,o=[];for(let l of e){let e=l.branch??"",c=s.get(e)??0;if(!n&&l.since<c){let s=r.get(e);if(void 0!==s){i.set(e,s),a.set(e,c);continue}}i.set(e,l.activity),a.set(e,l.since),n||r.get(e)===l.activity||o.push(l.branch)}return{nextActivity:i,nextSince:a,transitions:o}}(n.branches,o.current,a.current,c);s(d),i(u),o.current=d,l.current=e,a.current=u}catch{}},[e]);return(0,$.useEffect)(()=>{c()},[c]),(0,sx.useGlobalEventStream)(r=>{var n,l,c;let d,u;if("branch:activity"!==r.type||!e||r.projectId!==e)return;let h=(n=r,l=o.current,c=a.current,d=n.branch??"",u=c.get(d)??0,n.since<u?{kind:"stale"}:l.get(d)===n.activity?{kind:"redundant",key:d}:{kind:"transition",key:d});"stale"===h.kind||(a.current.set(h.key,r.since),i(new Map(a.current)),"redundant"!==h.kind&&s(e=>{let s=new Map(e);return s.set(h.key,r.activity),o.current=s,s}))}),{activity:r,since:n,refetch:c,setOptimisticActivity:(0,$.useCallback)((e,r)=>{s(s=>{let n=function(e,r,s){let n=r??"";if(e.get(n)===s)return e;let i=new Map(e);return i.set(n,s),i}(s,e,r);return o.current=n,n})},[])}}(eC?.id??null),{rules:tx,createRule:tv,updateRule:ty,deleteRule:tb}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),o=(0,$.useCallback)(async()=>{if(!e){n([]),a(!1);return}try{let s=await ry.api.getRules(e,r);n(s)}catch(e){console.error("Failed to fetch rules:",e)}finally{a(!1)}},[e,r]);(0,$.useEffect)(()=>{o()},[o]);let l=(0,$.useCallback)(async s=>{if(!e)return null;try{let i=await ry.api.createRule(e,{...s,branch:r});return n(e=>[...e,i]),i}catch(e){return console.error("Failed to create rule:",e),null}},[e,r]),c=(0,$.useCallback)(async(e,r)=>{n(s=>s.map(s=>s.id===e?{...s,...r,enabled:void 0!==r.enabled?+!!r.enabled:s.enabled,updated_at:new Date().toISOString()}:s));try{let s=await ry.api.updateRule(e,r);return n(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update rule:",e),n(s),null}},[s]),d=(0,$.useCallback)(async e=>{n(r=>r.filter(r=>r.id!==e));try{await ry.api.deleteRule(e)}catch(e){console.error("Failed to delete rule:",e),n(s)}},[s]);return{rules:s,loading:i,createRule:l,updateRule:c,deleteRule:d,refetch:o}}(eC?.id??null,M),{commands:tw,createCommand:t_,updateCommand:tS,deleteCommand:tj}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),o=(0,$.useCallback)(async()=>{if(!e){n([]),a(!1);return}try{let s=await ry.api.getCommands(e,r);n(s)}catch(e){console.error("Failed to fetch commands:",e)}finally{a(!1)}},[e,r]);(0,$.useEffect)(()=>{o()},[o]);let l=(0,$.useCallback)(async s=>{if(!e)return null;try{let i=await ry.api.createCommand(e,{...s,branch:r});return n(e=>[...e,i]),i}catch(e){return console.error("Failed to create command:",e),null}},[e,r]),c=(0,$.useCallback)(async(e,r)=>{n(s=>s.map(s=>s.id===e?{...s,...r,updated_at:new Date().toISOString()}:s));try{let s=await ry.api.updateCommand(e,r);return n(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update command:",e),n(s),null}},[s]),d=(0,$.useCallback)(async e=>{n(r=>r.filter(r=>r.id!==e));try{await ry.api.deleteCommand(e)}catch(e){console.error("Failed to delete command:",e),n(s)}},[s]);return{commands:s,loading:i,createCommand:l,updateCommand:c,deleteCommand:d,refetch:o}}(eC?.id??null,M),tk=(0,$.useRef)(null),tC=(0,$.useSyncExternalStore)(Nx,Nv,Ny),tN=eC?.id??null,tE=eC?.agent_mode??null,tD=(0,$.useCallback)(e=>!!tN&&tC.has(Nb(tN,e,tE)),[tC,tN,tE]),tR=(0,$.useCallback)(e=>{if(tN)return tC.get(Nb(tN,e,tE))},[tC,tN,tE]),tT=(0,$.useCallback)(e=>tp.get(AO(e)),[tp]),tA=(0,$.useMemo)(()=>(function(e,r,s,n){let i=new Map;if(!e)return i;for(let a of e){let e=AO(a.branch),o=r.get(e);if(!s?.(a.branch)){i.set(e,o??"idle");continue}if("main-running"===o)i.set(e,"main-running");else if("main-completed"===o){let r=n?.backendSince?.(a.branch)??0,s=n?.placeholderSince?.(a.branch)??0;i.set(e,s>r?"idle":"main-completed")}else i.set(e,"idle")}return i})(eP,tf,tD,{backendSince:tT,placeholderSince:tR}),[eP,tf,tD,tT,tR]);o=eV,l=tA,c=eC?.id??null,d=(0,$.useRef)(new Set),h=(u=function(e){let r=new Set;if(!e)return r;for(let[s,n]of e)c4.has(n)&&r.add(s);return r}(l)).size>0,f=JSON.stringify(Array.from(u).sort()),(0,$.useEffect)(()=>{let e=new Set(JSON.parse(f)),r=d.current;d.current=e,function(e,r){for(let s of e)if(!r.has(s))return!0;return!1}(r,e)&&o()},[f,o]),(0,$.useEffect)(()=>{let e=()=>o();return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[o]),(0,sx.useGlobalEventStream)(e=>{"executor:stopped"===e.type&&e.projectId===c&&o(),"merge-target:updated"===e.type&&null!==c&&e.projectId===c&&o(),"files:changed"===e.type&&null!==c&&e.projectId===c&&o()}),(0,$.useEffect)(()=>{let e=null,r=()=>{null!==e&&(clearInterval(e),e=null)},s=()=>{r(),e=setInterval(o,h?3e4:6e4)},n=()=>{"visible"===document.visibilityState?s():r()};return"visible"===document.visibilityState&&s(),document.addEventListener("visibilitychange",n),()=>{r(),document.removeEventListener("visibilitychange",n)}},[o,h]);let[tI,tM]=(0,$.useState)(null),{notifications:tF,unreadCount:tP,markRead:tL,markAllRead:tO,remove:tB,clear:tz,markReviewRunRead:t$}=function(e){let[r,s]=(0,$.useState)([]),n=(0,$.useRef)(new Set),i=(0,$.useRef)(new Set),a=(0,$.useRef)(r);(0,$.useEffect)(()=>{a.current=r},[r]);let o=(0,$.useRef)(new Set);(0,$.useEffect)(()=>{for(let e of new Set(Object.values(Aw)))AC.has(e)||AN.has(e)||(AN.add(e),(async()=>{try{let r=await fetch(e),s=await r.blob(),n=new Audio(URL.createObjectURL(s));n.preload="auto",n.load(),AC.set(e,n)}catch{}finally{AN.delete(e)}})())},[]);let l=(0,$.useRef)(e);(0,$.useEffect)(()=>{l.current=e},[e]);let c=(0,$.useCallback)(e=>{if(i.current.has(e))return;i.current.add(e);let r=Date.now();s(s=>s.map(s=>s.id===e&&null===s.read_at?{...s,read_at:r}:s)),(0,ry.markNotificationRead)(e).catch(()=>{s(s=>s.map(s=>s.id===e&&s.read_at===r?{...s,read_at:null}:s))}).finally(()=>{i.current.delete(e)})},[]),d=(0,$.useCallback)(e=>null===e.read_at&&null!==e.workflow_run_id&&o.current.has(e.workflow_run_id)?((0,ry.markNotificationRead)(e.id).catch(()=>{}),{...e,read_at:Date.now()}):e,[]);(0,$.useEffect)(()=>{let e=!1;return(0,ry.getNotifications)({limit:100}).then(r=>{if(e)return;for(let e of r)n.current.add(e.id);let i=r.map(d);s(e=>{let r=[];for(let e of i)r=A_(r,e);for(let s of e)i.some(e=>e.id===s.id)||(r=A_(r,s));return r});try{window.localStorage.removeItem("vibedeckx:completion-notifications")}catch{}}).catch(e=>{console.warn("[notifications] hydration failed:",e)}),()=>{e=!0}},[d]),(0,sx.useGlobalEventStream)(e=>{var r;let i;if("notification:created"!==e.type)return;let a=e.notification;if(!a?.id)return;let c=!n.current.has(a.id);n.current.add(a.id);let d=l.current,u=null!==a.session_id&&a.session_id===d,h=null!==a.workflow_run_id&&o.current.has(a.workflow_run_id);c&&!h&&(r=Aw[a.kind],(i=AC.get(r))||((i=new Audio(r)).preload="auto",AC.set(r,i)),i.currentTime=0,i.play().catch(()=>{}));let f=u||h;s(e=>A_(e,f?{...a,read_at:a.read_at??Date.now()}:a)),f&&null===a.read_at&&(0,ry.markNotificationRead)(a.id).catch(()=>{})}),(0,$.useEffect)(()=>{if(e)for(let n of r){if(n.session_id!==e||null!==n.read_at||i.current.has(n.id))continue;let{id:r}=n;i.current.add(r),(0,ry.markNotificationRead)(r).then(()=>{s(e=>e.map(e=>e.id===r&&null===e.read_at?{...e,read_at:Date.now()}:e))}).catch(()=>{}).finally(()=>{i.current.delete(r)})}},[e,r]);let u=(0,$.useCallback)(e=>c(e),[c]),h=(0,$.useCallback)((e,r)=>{for(let s of(r?.runEnded&&o.current.add(e),a.current))s.workflow_run_id===e&&null===s.read_at&&c(s.id)},[c]),f=(0,$.useCallback)(()=>{let e=Date.now();s(r=>r.some(e=>null===e.read_at)?r.map(r=>null===r.read_at?{...r,read_at:e}:r):r),(0,ry.markAllNotificationsRead)().catch(()=>s(r))},[r]),p=(0,$.useCallback)(e=>{c(e),s(r=>r.filter(r=>r.id!==e))},[c]),m=(0,$.useCallback)(()=>{(0,ry.markAllNotificationsRead)().catch(e=>console.warn("[notifications] read-all failed:",e)),s(e=>e.length?[]:e)},[]),g=Ak(r).reduce((e,r)=>e+ +!!r.unread,0);return{notifications:r,unreadCount:g,markRead:u,markAllRead:f,remove:p,clear:m,markReviewRunRead:h}}("workspace"===eo?tI:null),tW=(0,$.useMemo)(()=>({markReviewRunRead:t$}),[t$]),tH=(0,$.useMemo)(()=>tF.filter(e=>e.project_id===eC?.id&&null===e.read_at).length,[tF,eC?.id]),tU=(0,$.useCallback)(()=>{tg(M,"working")},[M,tg]),tq=(0,$.useCallback)(()=>{e8()},[e8]),tK=(0,$.useCallback)((e,r)=>{I({branch:e,sessionId:r}),Z(null),eh(e=>e+1),eg(!1),(0,Ay.touchRecentSessionOpen)(r)},[]),tV=(0,$.useCallback)((e,r,s)=>{Z({projectId:e,runId:r}),I({branch:s,sessionId:null}),eh(e=>e+1),eg(!1),el("workspace")},[]),tX=(0,$.useCallback)(e=>{"preparing-review"===e.kind&&e.runId?tV(e.projectId,e.runId,e.branch):(tK(e.branch,e.id),el("workspace"))},[tK,tV]),tY=(0,$.useCallback)(e=>{let r=eX.entries.find(r=>r.runId===e);r&&tV(r.projectId,r.runId,r.branch)},[eX.entries,tV]),tG=eX.markAppeared;(0,$.useEffect)(()=>{tG(eG)},[eG,tG]),(0,$.useEffect)(()=>{if(!J)return;if(J.projectId!==eC?.id)return void Z(null);let e=e0?null!==e0.appearedAt?{kind:"switch",branch:e0.branch,sessionId:e0.reviewerSessionId}:"preparing"===e0.run.status?{kind:"wait"}:TP(e0.run.status)?{kind:"gone"}:eG.has(e0.reviewerSessionId)?{kind:"switch",branch:e0.branch,sessionId:e0.reviewerSessionId}:{kind:"wait"}:{kind:"gone"};"switch"===e.kind&&tK(e.branch,e.sessionId)},[J,e0,eG,eC?.id,tK]);let tJ=(0,$.useCallback)(e=>{tm();let r=ek.find(r=>r.id===e.projectId);(0,Ay.touchSessionStarted)({sessionId:e.id,projectId:e.projectId,projectName:r?.name??"",targetId:r?.agent_mode??"local",branch:e.branch});let s=function(e,r=new Date){return!0!==e.processAlive?null:{id:e.id,projectId:e.projectId,branch:e.branch,title:"New Session",status:e.status,processAlive:!0,updated_at:r.toISOString()}}(e);s&&B(s)},[tm,ek]),tZ=(0,$.useCallback)((e,r)=>{r.trim()&&(0,Ay.updateCachedSessionTitle)(e,r.trim())},[]),tQ=(0,$.useCallback)(()=>{tg(M,"idle")},[M,tg]),t0=(0,$.useCallback)(()=>{e8()},[e8]);s=eC?.id??null,n={onTaskChanged:t0},p=(0,$.useRef)(n.onTaskChanged),(0,$.useEffect)(()=>{p.current=n.onTaskChanged}),(0,sx.useGlobalEventStream)(e=>{s&&e.projectId===s&&("task:created"===e.type||"task:updated"===e.type||"task:deleted"===e.type)&&p.current?.()});let t1=(0,$.useMemo)(()=>{let e=AO(M);return e1.find(r=>r.assigned_branch===e)??null},[e1,M]);(0,$.useCallback)(e=>{ej(async()=>{await ey.current?.submitMessage(e.description??e.title)})},[]),(0,$.useCallback)(e=>{e3(e,{assigned_branch:null})},[e3]),(0,$.useEffect)(()=>{let e=eF.current;if(void 0!==e&&e.projectId!==eC?.id&&(eF.current=void 0,eg(!1),ev(!1)),!eO&&0!==eP.length){if(void 0!==e&&e.projectId===eC?.id){if(eP.some(r=>r.branch===e.branch)){eF.current=void 0,M!==e.branch||F!==e.sessionId?e.sessionId?tK(e.branch,e.sessionId):P(e.branch):e.sessionId&&(0,Ay.touchRecentSessionOpen)(e.sessionId),ev(!1),eg(!1);return}if(eL)return;eF.current=void 0,eg(!1),ev(!1),gS.toast.warning(`Workspace "${e.branch??"main"}" no longer exists`),P(eP[0].branch);return}!eL&&(eP.some(e=>e.branch===M)||(F&&gS.toast.warning(`Workspace "${M??"main"}" no longer exists`),P(eP[0].branch)))}},[eP,eL,eO,M,F,eC?.id,tK,P]),(0,$.useEffect)(()=>{(em||ex)&&(null===M&&(eL||0!==eP.length)||(eg(!1),ev(!1)))},[em,ex,M,eL,eP]);let t2=(0,$.useCallback)((e,r,s=null)=>{if(el("workspace"),e===eC?.id)return void(s?tK(r,s):P(r));let n=ek.find(r=>r.id===e);n&&(s?eg(!0):ev(!0),eF.current={projectId:e,branch:r,sessionId:s},eA(n))},[eC?.id,ek,eA,tK,P]),[t5,t3]=(0,$.useState)(!1);(0,$.useEffect)(()=>{let e=e=>{if("k"===e.key&&(e.metaKey||e.ctrlKey)){e.preventDefault(),t3(e=>!e);return}"o"===e.key.toLowerCase()&&e.shiftKey&&(e.metaKey||e.ctrlKey)&&"workspace"===eo&&(e.preventDefault(),eh(e=>e+1),ey.current?.startNewConversation())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[eo]);let t4=(0,$.useRef)(!1),t6=(0,$.useCallback)(async(e,r)=>{let s=ek.find(r=>r.id===e);if(!s)return null;let n="local"===r?"local":r;return(s.agent_mode??"local")!==n?eR(s.id,{agentMode:n}):s},[ek,eR]),t7=(i={projectId:eC?.id??null,resolveProjectForTarget:t6,getScheduleRun:ry.api.getScheduleRun,getSchedules:ry.api.getSchedules,runScheduleNow:tn,selectAgentSession:(e,r)=>{el("workspace"),tK(e,r)},openScheduleRun:(e,r)=>{ta(e),tl(r),el("schedules")},onRerunResult:e=>{e.replay&&e.status&&"starting"!==e.status&&"running"!==e.status?"completed"===e.status?gS.toast.success("Schedule run already completed"):gS.toast.error(`Schedule run already ${e.status}`):gS.toast.success("Schedule run started")},onError:(e,r)=>{console.error(`Project activity ${e} failed:`,r),"session-navigation"===e?gS.toast.error("Failed to open agent session"):"schedule-navigation"===e?gS.toast.error("Failed to open schedule run"):gS.toast.error(r instanceof Error?r.message:"Failed to start schedule run")}},(m=(0,$.useRef)(i)).current=i,(g=(0,$.useRef)({projectId:i.projectId,generation:0})).current.projectId!==i.projectId&&(g.current={projectId:i.projectId,generation:g.current.generation+1}),x=(0,$.useRef)(new Map),v=(0,$.useRef)(new Map),y=(0,$.useCallback)(e=>g.current.projectId===e.projectId&&g.current.generation===e.generation,[]),b=(0,$.useCallback)(async(e,r)=>{if(!e.projectId)return null;let s=m.current,n=await s.getScheduleRun(r);if(!y(e))return null;if(n.project_id!==e.projectId)throw Error("Schedule run does not belong to the active project");let i=await s.getSchedules(e.projectId);if(!y(e))return null;let a=i.find(e=>e.id===n.schedule_id);if(!a||a.project_id!==e.projectId)throw Error("Schedule does not belong to the active project");return{run:n,schedule:a}},[y]),w=(0,$.useCallback)(async(e,r,s)=>{let n={...g.current};if(n.projectId)try{let i=await m.current.resolveProjectForTarget(n.projectId,r);if(!y(n)||!i||i.id!==n.projectId)return;m.current.selectAgentSession(s,e,i.id)}catch(e){y(n)&&m.current.onError("session-navigation",e)}},[y]),_=(0,$.useCallback)(async(e,r)=>{let s={...g.current};try{let n=await b(s,e);if(!n||!y(s))return;if(r&&r!==n.schedule.id)throw Error("Schedule run target changed while opening");m.current.openScheduleRun(n.schedule.id,e)}catch(e){y(s)&&m.current.onError("schedule-navigation",e)}},[y,b]),S=(0,$.useCallback)(e=>{let r={...g.current};if(!r.projectId)return Promise.resolve();let s=`${r.projectId}:${e}`,n=v.current.get(s);if(n)return n;let i=(async()=>{try{let n,i=c7(r.projectId,e),a=x.current.get(i)??function(e,r,s){try{let n=window.sessionStorage.getItem(e);if(!n)return;let i=JSON.parse(n);return"string"==typeof i.requestId&&"string"==typeof i.runId&&i.projectId===r&&"string"==typeof i.scheduleId&&i.scheduleId.length>0&&i.sourceRunId===s?i:void 0}catch{return}}(i,r.projectId,e);if(a){let e=await m.current.getSchedules(r.projectId);if(!y(r))return;let s=a.scheduleId,o=e.find(e=>e.id===s);if(!o||o.project_id!==r.projectId)throw Error("Schedule does not belong to the active project");n=o,x.current.set(i,a)}else{let o=await b(r,e);if(!o||!y(r))return;n=o.schedule;let l=crypto.randomUUID();a={projectId:r.projectId,scheduleId:n.id,requestId:l,runId:l,sourceRunId:e},x.current.set(i,a);var s=a;try{window.sessionStorage.setItem(i,JSON.stringify(s))}catch{}}let o={requestId:a.requestId,runId:a.runId,sourceRunId:a.sourceRunId},l=await m.current.runScheduleNow(n.id,o);if(x.current.delete(i),c8(i),!y(r))return;m.current.onRerunResult(l)}catch(s){if(r.projectId&&("object"==typeof s&&null!==s&&"status"in s&&409===s.status||"object"==typeof s&&null!==s&&"durable"in s&&!0===s.durable)){let s=c7(r.projectId,e);x.current.delete(s),c8(s)}throw y(r)&&m.current.onError("schedule-rerun",s),s}})().finally(()=>{v.current.get(s)===i&&v.current.delete(s)});return v.current.set(s,i),i},[y,b]),{openAgentSession:w,openScheduleRun:_,runScheduleAgain:S}),t8=(a={projectId:eC?.id??null,schedules:e9,getTask:ry.api.getTask,resolveProjectForTarget:t6,openTask:th,selectAgentSession:(e,r)=>{el("workspace"),tK(e,r)},selectWorkspace:e=>{P(e),el("workspace")},selectSchedule:e=>{ta(e),el("schedules")},openScheduleRun:t7.openScheduleRun,onError:e=>{gS.toast.error(e instanceof Error?e.message:"Unable to open Context item")}},(j=(0,$.useRef)(a)).current=a,(k=(0,$.useRef)({projectId:a.projectId,generation:0})).current.projectId!==a.projectId&&(k.current={projectId:a.projectId,generation:k.current.generation+1}),C=(0,$.useCallback)(e=>e.projectId===k.current.projectId&&e.generation===k.current.generation,[]),{open:(0,$.useCallback)(async e=>{let r={...k.current},s=e.navigation;if(!r.projectId||e.deleted||!s){C(r)&&j.current.onError(Error("This Context item is no longer available"));return}try{if("task"===s.kind){let e=await j.current.getTask(r.projectId,s.taskId);if(!C(r))return;if(e.id!==s.taskId||e.project_id!==r.projectId)throw Error("Task is no longer available in this project");j.current.openTask(e);return}if("agent_session"===s.kind||"workspace"===s.kind){let e=await j.current.resolveProjectForTarget(r.projectId,s.target);if(!C(r))return;if(!e||e.id!==r.projectId)throw Error("Workspace target is no longer available");"agent_session"===s.kind?j.current.selectAgentSession(s.branch,s.sessionId,e.id):j.current.selectWorkspace(s.branch,e.id);return}if("schedule"===s.kind){let e=j.current.schedules.find(e=>e.id===s.scheduleId&&e.project_id===r.projectId);if(!e)throw Error("Schedule is no longer available in this project");j.current.selectSchedule(e.id);return}await j.current.openScheduleRun(s.runId,s.scheduleId)}catch(e){C(r)&&j.current.onError(e)}},[C])}),t9=(0,$.useCallback)(e=>{ed(e),P(null),el("project-chat")},[P]),re=(0,$.useCallback)(()=>{ed(null),el("project-info")},[]);(0,$.useEffect)(()=>{el(E),ed("project-chat"===E?R:null),"project-chat"===E&&P(null)},[E,R,P]);let rt=(0,$.useCallback)(e=>{tl(r=>r===e?null:r)},[]),rr=(0,$.useCallback)(e=>{if(t4.current)return;let r=ek.find(r=>r.id===e);r&&(t3(!1),eA(r),el("project-info"))},[ek,eA]),rs=(0,$.useCallback)(async e=>{if(!t4.current){t4.current=!0,t3(!1);try{let r=await t6(e.projectId,e.targetId);if(!r)return;el("workspace"),r.id===eC?.id?P(e.branch):(ev(!0),eF.current={projectId:r.id,branch:e.branch,sessionId:null},eA(r))}catch(e){console.error("Quick switcher navigation failed:",e),gS.toast.error("Failed to open workspace")}finally{t4.current=!1}}},[eC?.id,t6,eA,P]),rn=(0,$.useCallback)(async e=>{if(!t4.current){t4.current=!0,t3(!1);try{let r=await t6(e.projectId,e.targetId);if(!r)return;(0,Ay.touchRecentSessionOpen)(e.sessionId,e),el("workspace"),r.id===eC?.id?tK(e.branch,e.sessionId):(eg(!0),eF.current={projectId:r.id,branch:e.branch,sessionId:e.sessionId},eA(r))}catch(e){console.error("Quick switcher navigation failed:",e),gS.toast.error("Failed to open session")}finally{t4.current=!1}}},[eC?.id,t6,eA,tK]);(0,$.useEffect)(()=>{if(eN||eI||eM)return;let e=Rq({projectId:eC?.id,tab:eo,branch:M,threadId:ec});if(F){let r=new URL(e,window.location.origin);r.searchParams.set("session",F),window.history.replaceState(null,"",r.pathname+r.search)}else window.history.replaceState(null,"",e)},[eC?.id,eo,M,ec,eN,eI,eM,F]);let ri=(0,$.useCallback)(e=>{ez(),P(e)},[ez,P]),ra=(0,$.useCallback)((e,r)=>{e.branch&&(K(e),X(r),er(!0))},[]),ro=(0,$.useCallback)(e=>{let r=null===e?void 0:eP.find(r=>r.branch===e),s=eC?.agent_mode??"local",n=r?.machines?.find(e=>e.serverId===s);r?.branch&&n?.state==="absent"?G({branch:r.branch,current:n,presentOn:r.machines.filter(e=>"present"===e.state)}):(n?.state==="creating"&&gS.toast.info(`'${e}' is still being created on ${n.name}`),P(e))},[eP,eC?.agent_mode,P]),rl=(0,$.useRef)({content:"",at:0}),rc=(0,$.useCallback)(e=>{let r=Date.now(),s=rl.current;s.content===e&&r-s.at<600||(rl.current={content:e,at:r},tk.current?.sendMessage(e))},[]),rd=(0,$.useCallback)(()=>{let e=`Please perform the following git operations for this worktree:
31
31
 
32
32
  1. Commit all current uncommitted changes with an appropriate commit message
33
33
  2. Fetch the latest changes from the remote main branch
34
34
  3. Rebase the current branch onto main (resolve any conflicts if needed)
35
35
  4. Merge the current branch into main
36
36
 
37
- Please proceed step by step and let me know if there are any issues or conflicts that need manual resolution.`;ey.current?.submitMessage(e)},[]),ru=(0,$.useCallback)(async e=>{if(eC)try{await eR(eC.id,{agentMode:e})}catch(e){console.error("Failed to update agent mode:",e)}},[eC,eR]),rh=(0,$.useCallback)(async e=>{if(eC)try{await eR(eC.id,{executorMode:e})}catch(e){console.error("Failed to update executor mode:",e)}},[eC,eR]),rf=!eC;return(0,z.jsx)(dT,{children:(0,z.jsx)(dj,{children:(0,z.jsx)(T0,{value:tW,children:(0,z.jsx)("div",{className:"h-screen flex flex-col w-full",children:(0,z.jsxs)(gw,{projectId:eC?.id??void 0,children:[(0,z.jsxs)("div",{"data-focus-region":"default",className:"border-b border-border bg-card px-3 h-[44px] flex items-center justify-between sticky top-0 z-10",children:[(0,z.jsxs)("div",{className:"flex items-center gap-[9px]",children:[(0,z.jsx)(gI.Logo,{size:22}),(0,z.jsxs)("h1",{className:"text-[13px] font-semibold tracking-tight text-foreground",children:["VibeDeck",(0,z.jsx)("span",{className:"text-primary font-bold",children:"X"})]})]}),(0,z.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,z.jsx)(W.Button,{variant:"ghost",size:"icon-sm","aria-label":"Search projects, workspaces, and sessions",title:"Search (⌘K / Ctrl+K)",onClick:()=>t3(!0),children:(0,z.jsx)(sA,{className:"h-4 w-4"})}),(0,z.jsx)(AS,{}),(0,z.jsx)(p3,{inviteUrl:T?.discordInviteUrl}),(0,z.jsx)(Ak,{}),(0,z.jsx)(Ay,{notifications:tF,unreadCount:tP,projects:ek,onNavigate:t2,markRead:tL,markAllRead:tO,remove:tB,clear:tz}),(0,z.jsx)(gA,{})]})]}),(0,z.jsxs)("div",{className:"flex-1 flex overflow-hidden",children:[(0,z.jsx)(dO,{activeView:eo,onViewChange:e=>{"project-chat"!==e&&ed(null),el(e)},worktrees:eP,worktreesStale:eO,staleRemoteName:eB.staleRemote?.name??null,activeRemoteInvalid:eB.activeRemoteInvalid,selectedBranch:M,onBranchChange:ro,currentProject:eC,onCreateWorktreeOpen:()=>er(!0),onDeleteWorktree:e=>{ea(e),en(!0)},onManageWorkspaceRemotes:e=>ra(e),onAnchorRootWorkspace:async e=>{if(eC){try{await ry.api.anchorRootWorkspace(eC.id,e),gS.toast.success(`Main workspace anchored to ${e}`)}catch(e){gS.toast.error(e instanceof Error?e.message:"Failed to anchor workspace")}ez()}},onSetRootWorkspaceBranch:async e=>{if(eC){try{await ry.api.setRootWorkspaceBranch(eC.id,e),gS.toast.success(`Main workspace anchored to ${e}`)}catch(e){gS.toast.error(e instanceof Error?e.message:"Failed to change workspace branch")}ez()}},mergeStatuses:e$,mergeRootDirty:eW,mergeDefaultTarget:eH,mergeRepositoryLabel:eU,mergeRepositoryServerId:eq,onMergeTargetChange:eK,onMergeBadgeClick:e=>{P(e),el("workspace"),ep(e=>e+1)},workspaceStatuses:tA,residentSessions:eZ,selectedSessionId:e0?e0.reviewerSessionId:F,onResidentSessionSelect:tX,hasProject:!rf,projects:ek,onSelectProject:eA,onCreateProjectOpen:()=>ee(!0),schedules:e9,selectedScheduleId:ti,onScheduleSelect:e=>{ta(e),el("schedules")},onCreateScheduleOpen:()=>{el("schedules"),td(!0)}}),(0,z.jsx)("div",{className:rf&&("workspace"===eo||"tasks"===eo||"project-info"===eo||"project-chat"===eo)?"flex-1 overflow-hidden":"hidden",children:(0,z.jsx)("div",{className:"h-full flex items-center justify-center bg-background",children:(0,z.jsxs)("div",{className:"text-center space-y-6",children:[(0,z.jsx)("div",{className:"mx-auto w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center",children:eM?(0,z.jsx)(s7,{className:"h-8 w-8 text-destructive"}):(0,z.jsx)(eS,{className:"h-8 w-8 text-primary"})}),(0,z.jsx)("h1",{className:"text-3xl font-bold tracking-tight text-foreground",children:eM?"Project not found":"Welcome to VibeDeckX"}),(0,z.jsx)("p",{className:"text-muted-foreground max-w-sm mx-auto leading-relaxed",role:eM?"alert":void 0,children:eM?"This project does not exist or you do not have access to it.":"Create your first project to get started with AI-powered development."}),eM?(0,z.jsx)(W.Button,{variant:"outline",size:"lg",onClick:()=>{let e=ek[0];e&&eA(e),window.history.replaceState(null,"",e?RB({projectId:e.id,tab:"project-info"}):"/"),window.dispatchEvent(new PopStateEvent("popstate")),el("project-info"),ed(null)},children:"Back to projects"}):(0,z.jsxs)(W.Button,{variant:"accent",size:"lg",onClick:()=>ee(!0),className:"shadow-md",children:[(0,z.jsx)(eS,{className:"h-5 w-5 mr-2"}),"Create Project"]})]})})}),(0,z.jsx)("div",{className:"workspace"!==eo||rf?"hidden":"flex-1 overflow-hidden flex",children:(0,z.jsxs)(uZ,{direction:"horizontal",autoSaveId:"workspace-panels",children:[(0,z.jsx)(d0,{defaultSize:33,minSize:25,children:(0,z.jsxs)("div",{"data-focus-region":"default",className:"h-full flex flex-col overflow-hidden",children:[eC&&(0,z.jsx)("div",{className:"px-4 py-3 border-b border-border/60 flex-shrink-0",children:(0,z.jsx)(rv,{assignedTask:t1,rules:tx,commands:tw,onCreateRule:tv,onUpdateRule:ty,onDeleteRule:tb,onCreateCommand:t_,onUpdateCommand:tS,onDeleteCommand:tj,onExecuteCommand:rc,onUpdateTaskTitle:(e,r)=>e3(e,{title:r}),onCompleteTask:e=>{e3(e,{status:"done",assigned_branch:null})}})}),(0,z.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,z.jsx)(T9,{ref:tk,projectId:eC?.id??null,branch:M},`${eC?.id??""}:${M??""}`)})]})}),(0,z.jsx)(uQ,{withHandle:!0}),(0,z.jsx)(d0,{defaultSize:67,minSize:25,children:(0,z.jsx)("div",{className:"h-full flex flex-col overflow-hidden",children:(0,z.jsx)(C_,{active:"workspace"===eo,agentSessionId:tI,projectId:eC?.id??null,selectedBranch:M,activateAgentTabNonce:eu,diffCompareNonce:ef,terminalRequest:H,forceAgentTab:em,mergeTarget:M?c2(e$.get(M))??eH:null,onMergeRequest:rd,project:eC,onExecutorModeChange:rh,agentSlot:(0,z.jsxs)(z.Fragment,{children:[eQ&&J&&(0,z.jsx)(T_,{runId:J.runId,entry:e0,title:e0?TP(e0,eJ(e0.sourceSessionId)):"Review",onOpenSource:(e,r)=>tK(r,e)}),(0,z.jsx)("div",{className:eQ?"hidden":"contents",children:(0,z.jsx)(Tw,{ref:ey,projectId:eC?.id??null,branch:M,sessionId:F,navPending:em||ex||eQ,preparingReviews:eX.entries,onReviewStarted:eX.addRun,onViewPreparingReview:tY,setSessionUrlParam:L,onActiveSessionChange:tM,project:eC,onAgentModeChange:ru,onTaskCompleted:tq,onSessionStarted:tJ,onSessionTitleUpdated:tZ,onSessionSelected:Al.touchRecentSessionOpen,onStatusChange:tU,onNewConversation:tQ,onOpenSchedule:e=>{ta(e),el("schedules")}})})]})})})})]})}),(0,z.jsx)("div",{className:"tasks"!==eo||rf?"hidden":"flex-1 overflow-hidden",children:(0,z.jsx)(Ao,{projectId:eC?.id??null,tasks:e1,loading:e2,worktrees:eP,onCreateTask:e5,onUpdateTask:e3,onDeleteTask:e4,onArchiveTask:e6,onUnarchiveTask:e7})}),"project-info"===eo&&!rf&&eC&&(0,z.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,z.jsx)(n3,{project:eC,waitingCount:tH,onOpenProjectChatThread:t9,onOpenAgentSession:(e,r,s)=>{t7.openAgentSession(e,r,s)},onOpenScheduleRun:(e,r)=>{t7.openScheduleRun(e,r)},onRunScheduleAgain:t7.runScheduleAgain,onViewAllTasks:()=>el("tasks"),onProjectUpdated:eR})}),"project-chat"===eo&&!rf&&eC&&ec&&(0,z.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,z.jsx)(cZ,{projectId:eC.id,threadId:ec,projectName:eC.name,onBack:re,onSelectThread:t9,onOpenContext:e=>{t8.open(e)},onOpenAgentSession:(e,r,s)=>t7.openAgentSession(e,r,s),onOpenScheduleRun:(e,r)=>t7.openScheduleRun(e,r),onRunScheduleAgain:t7.runScheduleAgain})}),"schedules"===eo&&!rf&&eC&&(0,z.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,z.jsx)(p1,{projectId:eC?.id??"",hasLocal:!!eC?.path,schedules:e9,loading:te,selectedId:ti,onSelect:ta,worktrees:eP,onCreate:tt,onUpdate:tr,onDelete:async e=>{await ts(e),ti===e&&ta(null)},onRunNow:tn,createOpen:tc,onCreateOpenChange:td,openRunId:to,onOpenRunHandled:rt})}),"remote-servers"===eo&&(0,z.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,z.jsxs)("div",{className:"h-full flex flex-col overflow-auto",children:[(0,z.jsx)(dB,{title:"Remote Servers"}),(0,z.jsx)("div",{className:"flex-1 px-6 py-5 flex justify-center",children:(0,z.jsx)("div",{className:"w-full max-w-2xl",children:(0,z.jsx)(gx,{})})})]})}),(0,z.jsx)("div",{className:"settings"!==eo?"hidden":"flex-1 overflow-hidden",children:(0,z.jsx)(gs,{})})]}),eC&&(0,z.jsx)(gE,{projectId:eC.id,project:eC,open:et,onOpenChange:e=>{er(e),e||(K(void 0),X(void 0))},onWorktreeCreated:ri,initialBranchName:q?.branch??void 0,initialMachines:q?.machines,initialTargets:q?.targets,initialSelectedTargets:V}),(0,z.jsx)(gD,{missing:Y,onOpenChange:e=>{e||G(null)},onCreateHere:()=>{if(G(null),!Y)return;let e=eP.find(e=>e.branch===Y.branch);e&&ra(e,[Y.current.serverId])},onOpenAnyway:()=>{G(null),Y&&P(Y.branch)}}),(0,z.jsx)(sh,{task:tu,open:null!==tu,onOpenChange:e=>{e||th(null)}}),(0,z.jsx)(p4,{open:Q,onOpenChange:ee,onProjectCreated:e=>{eE(e),el("project-info")}}),eC&&(0,z.jsx)(gR,{projectId:eC.id,worktree:ei,open:es,onOpenChange:en,onWorktreeDeleted:ez,onOpenTerminal:(e,r)=>{P(e),el("workspace"),U(e=>({targetId:r,nonce:(e?.nonce??0)+1}))}}),(0,z.jsx)(Ac,{open:t5,onOpenChange:t3,onNavigateProject:rr,onNavigateWorkspace:rs,onNavigateSession:rn})]})})})})})}e.s(["default",()=>AN],837031)}]);
37
+ Please proceed step by step and let me know if there are any issues or conflicts that need manual resolution.`;ey.current?.submitMessage(e)},[]),ru=(0,$.useCallback)(async e=>{if(eC)try{await eR(eC.id,{agentMode:e})}catch(e){console.error("Failed to update agent mode:",e)}},[eC,eR]),rh=(0,$.useCallback)(async e=>{if(eC)try{await eR(eC.id,{executorMode:e})}catch(e){console.error("Failed to update executor mode:",e)}},[eC,eR]),rf=!eC;return(0,z.jsx)(dT,{children:(0,z.jsx)(dj,{children:(0,z.jsx)(T6,{value:tW,children:(0,z.jsx)("div",{className:"h-screen flex flex-col w-full",children:(0,z.jsxs)(gw,{projectId:eC?.id??void 0,children:[(0,z.jsxs)("div",{"data-focus-region":"default",className:"border-b border-border bg-card px-3 h-[44px] flex items-center justify-between sticky top-0 z-10",children:[(0,z.jsxs)("div",{className:"flex items-center gap-[9px]",children:[(0,z.jsx)(gI.Logo,{size:22}),(0,z.jsxs)("h1",{className:"text-[13px] font-semibold tracking-tight text-foreground",children:["VibeDeck",(0,z.jsx)("span",{className:"text-primary font-bold",children:"X"})]})]}),(0,z.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,z.jsx)(W.Button,{variant:"ghost",size:"icon-sm","aria-label":"Search projects, workspaces, and sessions",title:"Search (⌘K / Ctrl+K)",onClick:()=>t3(!0),children:(0,z.jsx)(sA,{className:"h-4 w-4"})}),(0,z.jsx)(AF,{}),(0,z.jsx)(p3,{inviteUrl:T?.discordInviteUrl}),(0,z.jsx)(AL,{}),(0,z.jsx)(AT,{notifications:tF,unreadCount:tP,projects:ek,onNavigate:t2,markRead:tL,markAllRead:tO,remove:tB,clear:tz}),(0,z.jsx)(gA,{})]})]}),(0,z.jsxs)("div",{className:"flex-1 flex overflow-hidden",children:[(0,z.jsx)(dO,{activeView:eo,onViewChange:e=>{"project-chat"!==e&&ed(null),el(e)},worktrees:eP,worktreesStale:eO,staleRemoteName:eB.staleRemote?.name??null,activeRemoteInvalid:eB.activeRemoteInvalid,selectedBranch:M,onBranchChange:ro,currentProject:eC,onCreateWorktreeOpen:()=>er(!0),onDeleteWorktree:e=>{ea(e),en(!0)},onManageWorkspaceRemotes:e=>ra(e),onAnchorRootWorkspace:async e=>{if(eC){try{await ry.api.anchorRootWorkspace(eC.id,e),gS.toast.success(`Main workspace anchored to ${e}`)}catch(e){gS.toast.error(e instanceof Error?e.message:"Failed to anchor workspace")}ez()}},onSetRootWorkspaceBranch:async e=>{if(eC){try{await ry.api.setRootWorkspaceBranch(eC.id,e),gS.toast.success(`Main workspace anchored to ${e}`)}catch(e){gS.toast.error(e instanceof Error?e.message:"Failed to change workspace branch")}ez()}},mergeStatuses:e$,mergeRootDirty:eW,mergeDefaultTarget:eH,mergeRepositoryLabel:eU,mergeRepositoryServerId:eq,onMergeTargetChange:eK,onMergeBadgeClick:e=>{P(e),el("workspace"),ep(e=>e+1)},workspaceStatuses:tA,residentSessions:eZ,selectedSessionId:e0?e0.reviewerSessionId:F,onResidentSessionSelect:tX,hasProject:!rf,projects:ek,onSelectProject:eA,onCreateProjectOpen:()=>ee(!0),schedules:e9,selectedScheduleId:ti,onScheduleSelect:e=>{ta(e),el("schedules")},onCreateScheduleOpen:()=>{el("schedules"),td(!0)}}),(0,z.jsx)("div",{className:rf&&("workspace"===eo||"tasks"===eo||"project-info"===eo||"project-chat"===eo)?"flex-1 overflow-hidden":"hidden",children:(0,z.jsx)("div",{className:"h-full flex items-center justify-center bg-background",children:(0,z.jsxs)("div",{className:"text-center space-y-6",children:[(0,z.jsx)("div",{className:"mx-auto w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center",children:eM?(0,z.jsx)(s7,{className:"h-8 w-8 text-destructive"}):(0,z.jsx)(eS,{className:"h-8 w-8 text-primary"})}),(0,z.jsx)("h1",{className:"text-3xl font-bold tracking-tight text-foreground",children:eM?"Project not found":"Welcome to VibeDeckX"}),(0,z.jsx)("p",{className:"text-muted-foreground max-w-sm mx-auto leading-relaxed",role:eM?"alert":void 0,children:eM?"This project does not exist or you do not have access to it.":"Create your first project to get started with AI-powered development."}),eM?(0,z.jsx)(W.Button,{variant:"outline",size:"lg",onClick:()=>{let e=ek[0];e&&eA(e),window.history.replaceState(null,"",e?Rq({projectId:e.id,tab:"project-info"}):"/"),window.dispatchEvent(new PopStateEvent("popstate")),el("project-info"),ed(null)},children:"Back to projects"}):(0,z.jsxs)(W.Button,{variant:"accent",size:"lg",onClick:()=>ee(!0),className:"shadow-md",children:[(0,z.jsx)(eS,{className:"h-5 w-5 mr-2"}),"Create Project"]})]})})}),(0,z.jsx)("div",{className:"workspace"!==eo||rf?"hidden":"flex-1 overflow-hidden flex",children:(0,z.jsxs)(uZ,{direction:"horizontal",autoSaveId:"workspace-panels",children:[(0,z.jsx)(d0,{defaultSize:33,minSize:25,children:(0,z.jsxs)("div",{"data-focus-region":"default",className:"h-full flex flex-col overflow-hidden",children:[eC&&(0,z.jsx)("div",{className:"px-4 py-3 border-b border-border/60 flex-shrink-0",children:(0,z.jsx)(rv,{assignedTask:t1,rules:tx,commands:tw,onCreateRule:tv,onUpdateRule:ty,onDeleteRule:tb,onCreateCommand:t_,onUpdateCommand:tS,onDeleteCommand:tj,onExecuteCommand:rc,onUpdateTaskTitle:(e,r)=>e3(e,{title:r}),onCompleteTask:e=>{e3(e,{status:"done",assigned_branch:null})}})}),(0,z.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,z.jsx)(Ad,{ref:tk,projectId:eC?.id??null,branch:M},`${eC?.id??""}:${M??""}`)})]})}),(0,z.jsx)(uQ,{withHandle:!0}),(0,z.jsx)(d0,{defaultSize:67,minSize:25,children:(0,z.jsx)("div",{className:"h-full flex flex-col overflow-hidden",children:(0,z.jsx)(CE,{active:"workspace"===eo,agentSessionId:tI,projectId:eC?.id??null,selectedBranch:M,activateAgentTabNonce:eu,diffCompareNonce:ef,terminalRequest:H,forceAgentTab:em,mergeTarget:M?c2(e$.get(M))??eH:null,onMergeRequest:rd,project:eC,onExecutorModeChange:rh,agentSlot:(0,z.jsxs)(z.Fragment,{children:[eQ&&J&&(0,z.jsx)(TE,{runId:J.runId,entry:e0,title:e0?TW(e0,eJ(e0.sourceSessionId)):"Review",onOpenSource:(e,r)=>tK(r,e)}),(0,z.jsx)("div",{className:eQ?"hidden":"contents",children:(0,z.jsx)(TN,{ref:ey,projectId:eC?.id??null,branch:M,sessionId:F,navPending:em||ex||eQ,preparingReviews:eX.entries,onReviewStarted:eX.addRun,onViewPreparingReview:tY,setSessionUrlParam:L,onActiveSessionChange:tM,project:eC,onAgentModeChange:ru,onTaskCompleted:tq,onSessionStarted:tJ,onSessionTitleUpdated:tZ,onSessionSelected:Ay.touchRecentSessionOpen,onStatusChange:tU,onNewConversation:tQ,onOpenSchedule:e=>{ta(e),el("schedules")}})})]})})})})]})}),(0,z.jsx)("div",{className:"tasks"!==eo||rf?"hidden":"flex-1 overflow-hidden",children:(0,z.jsx)(Av,{projectId:eC?.id??null,tasks:e1,loading:e2,worktrees:eP,onCreateTask:e5,onUpdateTask:e3,onDeleteTask:e4,onArchiveTask:e6,onUnarchiveTask:e7})}),"project-info"===eo&&!rf&&eC&&(0,z.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,z.jsx)(n3,{project:eC,waitingCount:tH,onOpenProjectChatThread:t9,onOpenAgentSession:(e,r,s)=>{t7.openAgentSession(e,r,s)},onOpenScheduleRun:(e,r)=>{t7.openScheduleRun(e,r)},onRunScheduleAgain:t7.runScheduleAgain,onViewAllTasks:()=>el("tasks"),onProjectUpdated:eR})}),"project-chat"===eo&&!rf&&eC&&ec&&(0,z.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,z.jsx)(cZ,{projectId:eC.id,threadId:ec,projectName:eC.name,onBack:re,onSelectThread:t9,onOpenContext:e=>{t8.open(e)},onOpenAgentSession:(e,r,s)=>t7.openAgentSession(e,r,s),onOpenScheduleRun:(e,r)=>t7.openScheduleRun(e,r),onRunScheduleAgain:t7.runScheduleAgain})}),"schedules"===eo&&!rf&&eC&&(0,z.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,z.jsx)(p1,{projectId:eC?.id??"",hasLocal:!!eC?.path,schedules:e9,loading:te,selectedId:ti,onSelect:ta,worktrees:eP,onCreate:tt,onUpdate:tr,onDelete:async e=>{await ts(e),ti===e&&ta(null)},onRunNow:tn,createOpen:tc,onCreateOpenChange:td,openRunId:to,onOpenRunHandled:rt})}),"remote-servers"===eo&&(0,z.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,z.jsxs)("div",{className:"h-full flex flex-col overflow-auto",children:[(0,z.jsx)(dB,{title:"Remote Servers"}),(0,z.jsx)("div",{className:"flex-1 px-6 py-5 flex justify-center",children:(0,z.jsx)("div",{className:"w-full max-w-2xl",children:(0,z.jsx)(gx,{})})})]})}),(0,z.jsx)("div",{className:"settings"!==eo?"hidden":"flex-1 overflow-hidden",children:(0,z.jsx)(gs,{})})]}),eC&&(0,z.jsx)(gE,{projectId:eC.id,project:eC,open:et,onOpenChange:e=>{er(e),e||(K(void 0),X(void 0))},onWorktreeCreated:ri,initialBranchName:q?.branch??void 0,initialMachines:q?.machines,initialTargets:q?.targets,initialSelectedTargets:V}),(0,z.jsx)(gD,{missing:Y,onOpenChange:e=>{e||G(null)},onCreateHere:()=>{if(G(null),!Y)return;let e=eP.find(e=>e.branch===Y.branch);e&&ra(e,[Y.current.serverId])},onOpenAnyway:()=>{G(null),Y&&P(Y.branch)}}),(0,z.jsx)(sh,{task:tu,open:null!==tu,onOpenChange:e=>{e||th(null)}}),(0,z.jsx)(p4,{open:Q,onOpenChange:ee,onProjectCreated:e=>{eE(e),el("project-info")}}),eC&&(0,z.jsx)(gR,{projectId:eC.id,worktree:ei,open:es,onOpenChange:en,onWorktreeDeleted:ez,onOpenTerminal:(e,r)=>{P(e),el("workspace"),U(e=>({targetId:r,nonce:(e?.nonce??0)+1}))}}),(0,z.jsx)(Ab,{open:t5,onOpenChange:t3,onNavigateProject:rr,onNavigateWorkspace:rs,onNavigateSession:rn})]})})})})})}e.s(["default",()=>AB],837031)}]);