var Ue=Object.defineProperty;var qe=($,e,t)=>e in $?Ue($,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):$[e]=t;var b=($,e,t)=>qe($,typeof e!="symbol"?e+"":e,t);import{g as oe,u as je,s as Ke}from"./main.js";import{l as u,d as Xe,o as Ye,w as Ge,a as Ze,m as Fe,c as We,f as h,t as R,u as Ae,e as Je,Y as Qe,k as et,j as T,P as tt}from"./index.js";import"./_plugin-vue_export-helper.js";import"./useMarkdownRenderer.js";import"./CloseButton.js";const J=360,De=2e3,_e=4e3,He=180,st=34,nt=26,it=30,rt=32,H=(...$)=>{},G=(...$)=>{},O=(...$)=>{},re=(...$)=>{},X=(...$)=>{},U=(...$)=>{console.warn("[TerminalMenu]",...$)},ot=[{id:"browser",labelKey:"monitor.appBrowser",assetKey:"browser"},{id:"terminal",labelKey:"monitor.appTerminal",assetKey:"terminal"},{id:"command",labelKey:"monitor.appCommand",assetKey:"command"},{id:"python",labelKey:"monitor.appPython",assetKey:"python"},{id:"memory",labelKey:"monitor.appMemory",assetKey:"memory"},{id:"todo",labelKey:"monitor.appTodo",assetKey:"todo"},{id:"subagent",labelKey:"monitor.appSubagent",assetKey:"subagent"}],K=18,Q=120,lt=5,Y={x:8,y:6},ee=12,Oe=26,Ne=24,le=32,ze="manual-interactive",m=$=>new Promise(e=>setTimeout(e,$));class at{constructor(e,t){b(this,"elements");b(this,"assets");b(this,"desktopRoots",[]);b(this,"screenRect");b(this,"pointerBase",{x:60,y:120});b(this,"pendingPointerTransform",null);b(this,"screenObserver",null);b(this,"bubbleTimer",null);b(this,"windowAnchors",new Map);b(this,"destroyFns",[]);b(this,"appIcons",new Map);b(this,"folderIcons",new Map);b(this,"editorSpeedBoost",1);b(this,"pythonRunToken",0);b(this,"pendingDesktopFolders",new Set);b(this,"pendingCreateEntries",new Set);b(this,"fileIcons",new Map);b(this,"browserResultMap",new Map);b(this,"folderEntries",new Map);b(this,"activeFolder",null);b(this,"sceneHandlers",{});b(this,"windowOrder",[]);b(this,"maxVisibleWindows",lt);b(this,"extractionAnchor",{x:.6,y:.04});b(this,"extractionWindows",new Map);b(this,"extractionTemplate",null);b(this,"terminalSessions",new Map);b(this,"terminalSessionTitleMap",new Map);b(this,"terminalRawNameMap",new Map);b(this,"terminalSessionNames",new Map);b(this,"terminalHistories",new Map);b(this,"terminalContextSessionId",null);b(this,"activeTerminalSessionId",null);b(this,"manualInteractionEnabled",!1);b(this,"manualListenersAttached",!1);b(this,"manualPositions",new Map);b(this,"manualDragState",null);b(this,"editorScene",{lines:[],placeholder:!1});b(this,"editorSnapshots",new Map);b(this,"commandCurrentText","");b(this,"progressBubbleTimer",null);b(this,"progressBubbleBase",null);b(this,"progressSceneName",null);b(this,"latestMemoryScroll",0);b(this,"desktopRenderLocked",!1);b(this,"pendingDesktopRoots",null);b(this,"thinkingBubbleTimer",null);b(this,"thinkingBubblePhase",0);b(this,"waitingBubbleTimer",null);b(this,"waitingBubbleBase",null);b(this,"progressBubbleActive",!1);b(this,"secondaryMenu",null);b(this,"waitDigits",[]);b(this,"waitOverlayTimer",null);b(this,"playbackLagging",!1);b(this,"latestPythonExecutionId",null);b(this,"lastTerminalSessionId",null);b(this,"terminalLastFocusedAt",0);b(this,"handleTerminalAddClick",e=>{if(!this.manualInteractionEnabled)return;e.preventDefault();const t=this.createSession();this.activateSession(t)});b(this,"handleTerminalTabClick",e=>{var n;if(!this.manualInteractionEnabled)return;const t=(n=e.target)==null?void 0:n.closest(".terminal-tab");if(!t||t.classList.contains("add-tab"))return;const s=t.getAttribute("data-session-id");s&&(e.preventDefault(),this.activateSession(s))});b(this,"handleTerminalTabContext",e=>{var o;if(!this.manualInteractionEnabled)return;const t=(o=e.target)==null?void 0:o.closest(".terminal-tab");if(!t||t.classList.contains("add-tab"))return;const s=t.getAttribute("data-session-id");if(!s)return;e.preventDefault(),this.terminalContextSessionId=s;const n=this.elements.screen.getBoundingClientRect(),i=e.clientX-n.left,r=e.clientY-n.top;this.showContextMenu("terminal",{x:i,y:r})});b(this,"handleTerminalMenuClick",e=>{if(!this.manualInteractionEnabled)return;const t=e.target;if(!t||t.tagName.toLowerCase()!=="button")return;const s=t.getAttribute("data-action"),n=this.terminalContextSessionId||this.activeTerminalSessionId;if(!s||!n){this.hideContextMenus();return}e.preventDefault(),s==="snapshot"?(this.appendTerminalNote(n,"[Snapshot Captured]"),this.ensurePromptLine(n)):s==="reset"?(this.terminalHistories.set(n,[{text:"➜ ",role:"prompt"}]),this.renderTerminalHistory(n),this.appendTerminalNote(n,u("monitor.terminalReset")),this.ensurePromptLine(n)):s==="close"&&this.closeTerminalSession(n),this.hideContextMenus()});b(this,"handleManualPointerDown",e=>{if(!this.manualInteractionEnabled)return;const t=e.target||null;if(!t||t.closest(".traffic-dot"))return;const s=t.closest(".window-header");if(!s)return;const n=s.closest(".window");!n||!n.classList.contains("visible")||(e.preventDefault(),this.beginManualDrag(n,e))});b(this,"handleManualPointerMove",e=>{!this.manualInteractionEnabled||!this.manualDragState||e.pointerId===this.manualDragState.pointerId&&(e.preventDefault(),this.updateManualDragPosition(e))});b(this,"handleManualPointerUp",e=>{if(!this.manualDragState||e.pointerId!==this.manualDragState.pointerId)return;const{target:t,pointerId:s}=this.manualDragState;t&&t.hasPointerCapture(s)&&t.releasePointerCapture(s),t==null||t.classList.remove("manual-dragging"),this.manualDragState=null});b(this,"handleManualCloseClick",e=>{if(!this.manualInteractionEnabled)return;const t=e.target||null;if(!t)return;const s=t.closest(".traffic-dot.red");if(!s)return;const n=s.closest(".window");if(n){if(e.preventDefault(),e.stopPropagation(),this.manualPositions.delete(n),this.cancelManualDrag(),this.closeWindow(n,{animate:!0}),this.windowOrder=this.windowOrder.filter(i=>i&&i!==n&&i.classList.contains("visible")),n===this.elements.terminalWindow){this.activeTerminalSessionId=null;return}n.dataset.extractId&&this.purgeExtractionWindowByElement(n)}});this.elements=e,this.assets=t,this.screenRect=e.screen.getBoundingClientRect(),this.setupAnchors(),this.setupScenes(),this.bindTerminalInteractions(),this.populateDesktop(),this.setupScreenObserver(),this.extractionAnchor=this.windowAnchors.get(this.elements.extractionWindow)||this.extractionAnchor,this.prepareExtractionTemplate(),this.layoutFloatingWindows(),window.__TERMINAL_MENU_DEBUG_BUILD="2025-12-13-1",U("constructor:init",{build:window.__TERMINAL_MENU_DEBUG_BUILD});const s=()=>{this.refreshScreenRect(),this.layoutFloatingWindows(),this.flushPendingPointerTransform()};window.addEventListener("resize",s,{passive:!0}),this.destroyFns.push(()=>window.removeEventListener("resize",s))}refreshScreenRect(){const e=this.screenRect,t=this.elements.screen.getBoundingClientRect();if(!(t.width<1||t.height<1)&&(this.screenRect=t,e&&e.width>0&&e.height>0)){const s=this.pointerBase.x/e.width,n=this.pointerBase.y/e.height;this.pointerBase={x:s*t.width,y:n*t.height}}}applySceneStatus(e,t,s){if(!e||typeof e.setStatus!="function")return;const n=oe(t)||s;try{e.setStatus(n)}catch(i){console.warn("[MonitorDirector] failed to set scene status",t,i)}}destroy(){this.setManualInteractionEnabled(!1),this.destroyFns.forEach(e=>e()),this.destroyFns=[],this.stopBubbleTimers()}resetScene(e){this.pendingPointerTransform=null;const t=!!(e!=null&&e.preserveWindows),s=(e==null?void 0:e.preservePointer)!==!1;this.cancelManualDrag(),t?this.windowOrder=this.windowOrder.filter(n=>n&&n.classList.contains("visible")):(this.resetManualPositions(),this.manualPositions.clear(),this.hideAllWindows(),this.activeFolder=null,this.refreshFolderIconStates()),this.hideContextMenus(),e!=null&&e.preserveBubble?this.stopBubbleTimers():this.dismissBubble(!0,{force:!0}),s||(this.pointerBase={x:60,y:120},this.elements.mousePointer.style.transform="translate3d(60px, 120px, 0)"),t||(this.elements.browserSearchText.textContent="",this.elements.browserStatus.textContent=u("monitor.browserReady"),this.elements.browserResults.innerHTML="",this.browserResultMap.clear(),this.elements.extractionSummary.innerHTML="",this.elements.extractionState.textContent=u("monitor.extractWaiting"),this.elements.folderBody.innerHTML="",this.elements.editorBody.innerHTML="",this.elements.terminalBody.innerHTML="",this.terminalHistories.clear(),this.terminalSessions.clear(),this.terminalSessionNames.clear(),this.terminalSessionTitleMap.clear(),this.terminalContextSessionId=null,this.activeTerminalSessionId=null,this.terminalLastFocusedAt=0,this.elements.readerLines.innerHTML="",this.elements.readerOcr.innerHTML="",this.elements.todoSummary.textContent="",this.elements.todoList.innerHTML="",this.folderIcons.clear(),this.fileIcons.clear()),Array.isArray(e==null?void 0:e.desktopRoots)&&(e!=null&&e.desktopRoots.length)?this.setDesktopRoots(e.desktopRoots,{immediate:!0}):this.desktopRoots.length&&this.setDesktopRoots(this.desktopRoots,{immediate:!0}),this.renderTerminalTabs()}setDesktopRoots(e,t){if(this.desktopRenderLocked){this.pendingDesktopRoots=Array.isArray(e)?[...e]:[],X("setDesktopRoots:locked",{pending:this.pendingDesktopRoots.length});return}const s=Array.isArray(e)?[...e]:[],n=[...this.desktopRoots];if(this.desktopRoots=s,!this.desktopRoots.length)this.folderEntries.clear();else{const i=new Map;this.folderEntries.forEach((r,o)=>{const l=o.split("/")[0];this.desktopRoots.includes(l)&&i.set(o,r)}),this.desktopRoots.forEach(r=>{i.has(r)||i.set(r,[])}),this.folderEntries=i}if(t!=null&&t.immediate)this.pendingDesktopFolders.clear();else{const i=new Set(n);this.desktopRoots.forEach(r=>{if(!i.has(r)){const o=this.folderIcons.get(r);if(o&&!o.classList.contains("pending-reveal"))return;this.pendingDesktopFolders.add(r)}}),Array.from(this.pendingDesktopFolders).forEach(r=>{this.desktopRoots.includes(r)||this.pendingDesktopFolders.delete(r)})}this.renderDesktopFolders(),this.refreshFolderIconStates()}setManualInteractionEnabled(e){if(e!==this.manualInteractionEnabled){if(e){this.manualInteractionEnabled=!0,this.elements.screen.classList.add(ze),this.bindManualInteractionListeners();return}this.manualInteractionEnabled=!1,this.elements.screen.classList.remove(ze),this.cancelManualDrag(),this.unbindManualInteractionListeners()}}showSpeechBubble(e,t={}){const{variant:s="info",iconSvg:n=null,icon:i=null,duration:r}=t,o=typeof r=="number"?r:0;this.dismissBubble(!0,{force:!0});const l=this.elements.speechBubble;if(l.classList.remove("thinking","error","info"),l.classList.add(s),this.elements.bubbleTextSlot.textContent=e,this.elements.bubbleIconSlot.innerHTML="",s==="thinking"&&n){const a=document.createElement("img");a.src=n,a.alt="",this.elements.bubbleIconSlot.appendChild(a),this.elements.bubbleIconSlot.classList.add("show")}else s==="error"&&i?(this.elements.bubbleIconSlot.textContent=i,this.elements.bubbleIconSlot.classList.add("show")):this.elements.bubbleIconSlot.classList.remove("show");this.positionBubble(),requestAnimationFrame(()=>{l.classList.add("visible"),l.style.visibility="visible"}),this.elements.bubbleTextSlot.scrollTop=this.elements.bubbleTextSlot.scrollHeight,this.stopBubbleTimers(),o>0&&(this.bubbleTimer=window.setTimeout(()=>{l.classList.remove("visible"),l.style.visibility=""},o))}showThinkingBubble(){this.stopBubbleTimers(),this.dismissBubble(!0,{force:!0});const e=this.elements.speechBubble;e.classList.remove("error","thinking","progress"),e.classList.add("info"),this.elements.bubbleIconSlot.classList.remove("show"),this.elements.bubbleIconSlot.innerHTML="",this.startThinkingBubble(u("monitor.thinkLabel")),this.positionBubble(),requestAnimationFrame(()=>{e.classList.add("visible"),e.style.visibility="visible"})}hideBubble(){this.dismissBubble(!0,{force:!0})}previewSceneProgress(e){this.stopProgressBubble();const t=oe(e);t&&(this.progressSceneName=e,this.startProgressBubble(t))}async playScene(e,t,s){var M,B,F,I,k,A,N,_,z,q,P;const n=this.sceneHandlers[e]||this.sceneHandlers.genericTool,i=oe(e),r=!!this.progressBubbleBase&&this.progressSceneName===e,o=(s==null?void 0:s.statusPhase)==="playback",l=s.waitForResult||(()=>Promise.resolve(null));let a=!1,c=null;const d=async W=>(a||(a=!0,c=await l(W)),c),w=String((t==null?void 0:t.status)||((M=t==null?void 0:t.result)==null?void 0:M.status)||"").toLowerCase(),g=["failed","error"].includes(w)||(t==null?void 0:t.error)||(t==null?void 0:t.success)===!1||((B=t==null?void 0:t.result)==null?void 0:B.success)===!1||typeof((F=t==null?void 0:t.result)==null?void 0:F.error)=="string"&&t.result.error;if(X("playScene:prefail-check",{scene:e,preStatus:w,preFailed:g,statusPhase:s==null?void 0:s.statusPhase,hasPreviewForScene:r}),g){const W=((I=t==null?void 0:t.result)==null?void 0:I.error)||(t==null?void 0:t.error)||((k=t==null?void 0:t.result)==null?void 0:k.message)||(t==null?void 0:t.message)||u("monitor.toolError");this.stopProgressBubble(),this.showSpeechBubble(W,{variant:"error",duration:2600});return}X("playScene:start",{scene:e,progressLabel:i,hasPreviewForScene:r,statusPhase:s==null?void 0:s.statusPhase}),e.startsWith("terminal")&&U("playScene:enter",{scene:e,payload:t}),r?o&&this.stopProgressBubble():this.dismissBubble(!0,{force:!0});let v=r&&!o;const x=()=>{!i||v||o||(v=!0,this.progressSceneName=e,this.startProgressBubble(i))},p=()=>{v&&(v=!1,this.stopProgressBubble())};if(i&&!o&&x(),o){const W=(t==null?void 0:t.executionId)??(t==null?void 0:t.id)??((A=t==null?void 0:t.arguments)==null?void 0:A.id)??null;try{const S=await d(W),y=String((S==null?void 0:S.status)||((N=S==null?void 0:S.result)==null?void 0:N.status)||"").toLowerCase(),V=["failed","error"].includes(y)||(S==null?void 0:S.success)===!1||((_=S==null?void 0:S.result)==null?void 0:_.success)===!1||(S==null?void 0:S.error)||typeof((z=S==null?void 0:S.result)==null?void 0:z.error)=="string"&&S.result.error;if(X("playScene:prefetch-result",{scene:e,waitKey:W,preResultStatus:y,preResultFailed:V}),V){const j=((q=S==null?void 0:S.result)==null?void 0:q.error)||(S==null?void 0:S.error)||((P=t==null?void 0:t.result)==null?void 0:P.error)||(t==null?void 0:t.error)||u("monitor.toolError");this.stopProgressBubble(),this.showSpeechBubble(j,{variant:"error",duration:2600}),X("playScene:skip-after-prefetch-error",{scene:e,message:j});return}}catch{this.stopProgressBubble(),this.showSpeechBubble(u("monitor.toolError"),{variant:"error",duration:2600});return}}o?this.playbackLagging=!0:this.playbackLagging=!1;const C={...s,waitForResult:async W=>{var y,V,j,Z,D;!o&&!this.playbackLagging&&x();const S=W??(t==null?void 0:t.executionId)??(t==null?void 0:t.id);try{const L=await d(W);re("playScene:waitForResult:resolved",{scene:e,id:S}),this.playbackLagging=!1;const te=String((L==null?void 0:L.status)||((y=L==null?void 0:L.result)==null?void 0:y.status)||"").toLowerCase(),se=["failed","error"].includes(te)||(L==null?void 0:L.success)===!1||((V=L==null?void 0:L.result)==null?void 0:V.success)===!1||(L==null?void 0:L.error)||typeof((j=L==null?void 0:L.result)==null?void 0:j.error)=="string"&&L.result.error;if(X("playScene:waitForResult:status",{scene:e,id:S,resultStatus:te,failed:se}),se){const ie=((Z=L==null?void 0:L.result)==null?void 0:Z.error)||(L==null?void 0:L.error)||((D=t==null?void 0:t.result)==null?void 0:D.error)||(t==null?void 0:t.error)||u("monitor.toolError");throw this.stopProgressBubble(),this.showSpeechBubble(ie,{variant:"error",duration:2600}),new Error("tool-failed")}return L}finally{p()}}};try{await n(t,C)}finally{p(),this.playbackLagging=!1}}stopBubbleTimers(){this.bubbleTimer&&(clearTimeout(this.bubbleTimer),this.bubbleTimer=null),this.clearThinkingBubbleTimer(),this.waitingBubbleTimer&&(clearTimeout(this.waitingBubbleTimer),this.waitingBubbleTimer=null)}dismissBubble(e=!1,t){if(this.progressBubbleActive&&!(t!=null&&t.force))return;const s=this.elements.speechBubble;if(this.stopBubbleTimers(),t!=null&&t.force&&(this.progressBubbleTimer&&(window.clearTimeout(this.progressBubbleTimer),this.progressBubbleTimer=null),this.progressBubbleBase=null,this.progressSceneName=null,this.progressBubbleActive=!1,this.clearThinkingBubbleTimer(),this.waitingBubbleTimer&&(clearTimeout(this.waitingBubbleTimer),this.waitingBubbleTimer=null,this.waitingBubbleBase=null),s.classList.remove("progress"),s.removeAttribute("data-progress")),!s.classList.contains("visible")){e&&(s.classList.remove("thinking","error","info"),s.style.visibility="");return}s.classList.remove("visible","thinking","error","info"),e&&(s.style.visibility="")}startProgressBubble(e){re("startProgressBubble",{text:e,scene:this.progressSceneName}),this.progressBubbleTimer&&(window.clearTimeout(this.progressBubbleTimer),this.progressBubbleTimer=null),this.progressBubbleBase=e,this.progressBubbleActive=!0;let t=0;const s=()=>{const n=".".repeat(t),i=`${e}${n}`;this.renderProgressBubble(i),t=(t+1)%4,this.progressBubbleTimer=window.setTimeout(s,520)};s()}renderProgressBubble(e){const t=this.elements.speechBubble;t.classList.remove("thinking","error"),t.classList.add("info"),t.classList.add("progress"),t.setAttribute("data-progress","1"),this.elements.bubbleIconSlot.classList.remove("show"),this.elements.bubbleIconSlot.innerHTML="",this.elements.bubbleTextSlot.textContent=e,this.positionBubble(),this.elements.bubbleTextSlot.scrollTop=this.elements.bubbleTextSlot.scrollHeight,t.classList.contains("visible")||(t.style.visibility="visible",requestAnimationFrame(()=>t.classList.add("visible")))}startThinkingBubble(e){this.clearThinkingBubbleTimer(),this.showWaitingBubble(e||u("monitor.thinkLabel")),this.thinkingBubbleTimer=this.waitingBubbleTimer}clearThinkingBubbleTimer(){this.thinkingBubbleTimer&&(clearInterval(this.thinkingBubbleTimer),this.thinkingBubbleTimer=null),this.thinkingBubblePhase=0}showWaitingBubble(e=u("monitor.waitingReply")){this.dismissBubble(!0,{force:!0});const t=this.elements.speechBubble;t.classList.remove("error","thinking","progress"),t.classList.add("info"),this.elements.bubbleIconSlot.classList.remove("show"),this.elements.bubbleIconSlot.innerHTML="",this.waitingBubbleBase=e;let s=0;const n=()=>{const i=".".repeat(s);this.elements.bubbleTextSlot.textContent=`${e}${i}`,this.positionBubble(),s=(s+1)%4,this.waitingBubbleTimer=window.setTimeout(n,520)};n(),requestAnimationFrame(()=>{t.classList.add("visible"),t.style.visibility="visible"})}stopProgressBubble(e){re("stopProgressBubble",{label:this.progressBubbleBase,scene:this.progressSceneName,preserve:!!(e!=null&&e.preserveBubble)}),this.progressBubbleTimer&&(window.clearTimeout(this.progressBubbleTimer),this.progressBubbleTimer=null);const t=this.elements.speechBubble,s=this.progressBubbleActive&&!(e!=null&&e.preserveBubble)&&t.classList.contains("progress");this.progressBubbleBase=null,this.progressSceneName=null,this.progressBubbleActive=!1,t.classList.remove("progress"),t.removeAttribute("data-progress"),s&&this.dismissBubble(!0,{force:!0})}positionBubble(){if(this.elements.screen.clientWidth<1||this.elements.screen.clientHeight<1)return;const e=this.elements.speechBubble,t=e.getBoundingClientRect(),s=t.width||220,n=t.height||120,i=this.getPointerTip(),r=i.x-le,o=i.y-n-Oe,l=Math.max(ee,this.elements.screen.clientWidth-s-ee),a=Math.max(ee,this.elements.screen.clientHeight-n-ee),c=Math.min(Math.max(ee,r),l),d=Math.min(Math.max(ee,o),a),w=c+le-Y.x,g=d+n+Oe-Y.y;this.updatePointerTransform(w,g,200),e.style.left=`${c}px`,e.style.top=`${d}px`;const v=Math.min(Math.max(le,Ne),s-Ne);e.style.setProperty("--arrow-offset",`${v}px`)}normalizePathSegments(e){return e?e.replace(/\\/g,"/").split("/").map(t=>t.trim()).filter(Boolean):[]}composePath(e){return e.filter(Boolean).join("/")}normalizeEntryPath(e){return this.composePath(this.normalizePathSegments(e||""))}markPendingCreation(e){const t=this.normalizeEntryPath(e||"");if(t){this.pendingCreateEntries.add(t),this.applyPendingCreationState(t,!0);const s=this.normalizePathSegments(t);if(s.length===1)this.renderDesktopFolders();else if(s.length>1){const n=this.composePath(s.slice(0,-1));this.activeFolder===n&&this.renderFolderEntries(n,!1)}}}releasePendingCreation(e){const t=this.normalizeEntryPath(e||"");if(!t)return;this.pendingCreateEntries.has(t)&&this.pendingCreateEntries.delete(t),this.applyPendingCreationState(t,!1);const s=this.normalizePathSegments(t);if(s.length===1)this.renderDesktopFolders();else if(s.length>1){const n=this.composePath(s.slice(0,-1));this.activeFolder===n&&this.renderFolderEntries(n,!1)}}isCreationPending(e){const t=this.normalizeEntryPath(e||"");return t?this.pendingCreateEntries.has(t):!1}applyPendingCreationState(e,t){const s=this.normalizePathSegments(e),n=s.length===1?s[0]:null,i=this.findFolderEntryElement(e),r=n&&(this.folderIcons.get(n)||this.fileIcons.get(n))||null,o=l=>{l&&(t?(l.classList.remove("visible"),l.classList.add("pending-reveal"),l.style.opacity="0"):(l.classList.remove("pending-reveal"),l.style.opacity="1",requestAnimationFrame(()=>l.classList.add("visible"))))};o(i),o(r)}preparePendingCreation(e){this.markPendingCreation(e)}lockDesktopRender(){this.desktopRenderLocked=!0}unlockDesktopRender(){var e;if(this.desktopRenderLocked&&(this.desktopRenderLocked=!1,X("desktopRender:unlock",{pending:((e=this.pendingDesktopRoots)==null?void 0:e.length)||0}),this.pendingDesktopRoots)){const t=this.pendingDesktopRoots;this.pendingDesktopRoots=null,this.setDesktopRoots(t,{immediate:!0})}}ensureFolderKey(e){e&&(this.folderEntries.has(e)||this.folderEntries.set(e,[]))}refreshFolderIconStates(){this.folderIcons.forEach((e,t)=>{this.setFolderIconState(t)})}async loadFolderEntries(e){var s;const t=e||"";try{const i=await(await fetch(`/api/gui/files/entries?path=${encodeURIComponent(t)}`,{method:"GET",credentials:"include",headers:{Accept:"application/json"}})).json().catch(()=>null);if(!(i!=null&&i.success))return;const o=(Array.isArray((s=i==null?void 0:i.data)==null?void 0:s.items)?i.data.items:[]).map(l=>{const a=(l==null?void 0:l.path)||this.composePath([t,l==null?void 0:l.name].filter(Boolean));return{name:(l==null?void 0:l.name)||"",path:this.normalizeEntryPath(a),type:(l==null?void 0:l.type)==="directory"?"folder":"file"}});this.folderEntries.set(t,o)}catch(n){console.warn("[MonitorDirector] loadFolderEntries failed",t,n)}}renderFolderEntries(e,t=!0){this.ensureFolderKey(e);const s=this.folderEntries.get(e)||[];this.elements.folderBody.innerHTML="",s.forEach(n=>{const i=document.createElement("div");i.className="folder-entry",i.dataset.entryName=n.name,i.dataset.entryPath=n.path;const r=document.createElement("img");r.src=n.type==="folder"?this.assets.folderIcon:this.assets.fileIcon,r.alt=n.name;const o=document.createElement("span");o.textContent=n.name,i.appendChild(r),i.appendChild(o),this.elements.folderBody.appendChild(i);const l=this.isCreationPending(n.path);if(l&&(i.classList.add("pending-reveal"),i.style.opacity="0"),!t||l){l||i.classList.add("visible");return}requestAnimationFrame(()=>{l||i.classList.add("visible")})})}upsertFolderEntry(e,t,s={}){if(!e)return;this.ensureFolderKey(e);const n=this.composePath([e,t.name].filter(Boolean)),i=this.folderEntries.get(e)||[],r=i.findIndex(o=>o.name===t.name&&o.type===t.type);r>=0?i[r]={...t,path:n}:i.push({...t,path:n}),this.folderEntries.set(e,i),this.activeFolder===e&&this.renderFolderEntries(e,s.animate!==!1)}findFolderEntryElement(e){return e?this.elements.folderBody.querySelector(`[data-entry-path="${e}"]`):null}async doubleClickDesktopFolder(e){let t=this.folderIcons.get(e);t||(t=this.spawnDesktopFolder(e)),t&&(this.ensureFolderKey(e),await this.movePointerToElement(t,{duration:720}),await this.click({count:2}),await m(180),await this.openFolder(e,e),await m(60))}async doubleClickFolderEntry(e){const t=this.findFolderEntryElement(e);t&&(await this.movePointerToElement(t,{duration:620}),await this.click({count:2}),await m(200))}async revealFileTarget(e,t={}){const s=this.normalizePathSegments(e),n=s.pop()||e;if(!n)return null;if(s.length){const r=await this.openFolderChain(s);if(!r)return null;this.upsertFolderEntry(r,{name:n,type:"file"},{animate:!1}),await this.openFolder(r,r),await m(40);const o=this.composePath([r,n]),l=this.findFolderEntryElement(o);return l?(await this.movePointerToElement(l,{duration:620}),t.doubleClick&&(await this.click({count:2}),await m(200)),{element:l,entryPath:o,parentKey:r}):null}let i=this.fileIcons.get(n);return!i&&t.spawnDesktopFile&&(i=this.spawnDesktopFile(n)),i?(await this.movePointerToElement(i,{duration:620}),t.doubleClick&&(await this.click({count:2}),await m(200)),{element:i,entryPath:n,parentKey:null}):null}async openFileMenuAction(e,t){if(!e)return!1;await this.movePointerToElement(e,{duration:540}),await this.click(),this.showContextMenu("file"),await m(160);const s=await this.highlightMenu("file",t);return s&&await this.click(),this.hideContextMenus(),s}async openFolderChain(e){if(!e.length)return null;const t=e.slice();let s=null,n=0;const i=this.isWindowVisible(this.elements.folderWindow),r=this.activeFolder?this.normalizePathSegments(this.activeFolder):[],o=r.length&&r.length<=t.length&&r.every((l,a)=>l===t[a]);if(!i||!o){const l=t[0];await this.doubleClickDesktopFolder(l),s=l,n=1}else s=this.composePath(r),n=r.length,await this.openFolder(s,s),await m(40);for(let l=n;l{const t=document.createElement("div");t.className="desktop-icon app",t.dataset.appId=e.id;const s=document.createElement("img");s.src=this.assets.apps[e.assetKey]||this.assets.apps.browser,s.alt=u(e.labelKey),t.appendChild(s);const n=document.createElement("span");n.textContent=u(e.labelKey),t.appendChild(n),this.elements.appsGrid.appendChild(t),this.appIcons.set(e.id,t)}),this.renderDesktopFolders()}renderDesktopFolders(){const e=this.elements.desktopGrid;if(!e)return;const t=this.desktopRoots.filter(r=>!this.pendingDesktopFolders.has(r)&&!this.isCreationPending(r)),s=new Set(this.desktopRoots);Array.from(this.folderIcons.entries()).forEach(([r,o])=>{(!s.has(r)||this.isCreationPending(r))&&(o.parentElement===e&&e.removeChild(o),this.folderIcons.delete(r))}),this.desktopRoots.forEach(r=>{let o=this.folderIcons.get(r)||null;o||(o=this.createDesktopFolderIcon(r),this.folderIcons.set(r,o)),this.pendingDesktopFolders.has(r)||this.isCreationPending(r)?(o.classList.remove("visible"),o.classList.add("pending-reveal"),o.parentElement===e&&e.removeChild(o)):o.classList.remove("pending-reveal")});const n=Array.from(e.querySelectorAll("[data-folder-name]")).map(r=>r.dataset.folderName||"");let i=t.length!==n.length;if(!i){for(let r=0;ra.remove());const o=Array.from(e.children).find(a=>a instanceof HTMLElement?!a.dataset.folderName:!1)||null;let l=null;t.forEach(a=>{const c=this.folderIcons.get(a);if(!c)return;const d=l?l.nextSibling:o;d?e.insertBefore(c,d):e.appendChild(c),!c.classList.contains("visible")&&!this.isCreationPending(a)&&requestAnimationFrame(()=>c.classList.add("visible")),l=c})}}prepareExtractionTemplate(){const e=this.elements.extractionWindow;!e||this.extractionTemplate||(e.classList.add("extraction-template"),e.style.display="none",e.classList.remove("visible","closing"),this.extractionTemplate={id:"template",element:e,urlEl:this.elements.extractionUrl,stateEl:this.elements.extractionState,summaryEl:this.elements.extractionSummary,titleEl:e.querySelector(".window-title")},this.windowAnchors.delete(e))}createExtractionWindowDom(){let e;this.extractionTemplate?e=this.extractionTemplate.element.cloneNode(!0):e=this.buildExtractionWindowDom(),e.classList.remove("extraction-template"),e.style.display="",e.classList.remove("visible","closing");const t=e.querySelector(".extraction-body")||e;let s=e.querySelector(".extract-url");s||(s=document.createElement("div"),s.className="extract-url",t.appendChild(s));let n=e.querySelector(".extract-status");n||(n=document.createElement("div"),n.className="extract-status",t.appendChild(n));let i=e.querySelector(".extract-summary");i||(i=document.createElement("div"),i.className="extract-summary",t.appendChild(i));const r=e.querySelector(".window-title");return{id:"",element:e,urlEl:s,stateEl:n,summaryEl:i,titleEl:r}}buildExtractionWindowDom(){const e=document.createElement("div");e.className="window extraction-window";const t=document.createElement("div");t.className="window-header",["red","yellow","green"].forEach(l=>{const a=document.createElement("span");a.className=`traffic-dot ${l}`,t.appendChild(a)});const s=document.createElement("span");s.className="window-title",s.textContent=u("monitor.extractTitle"),t.appendChild(s),e.appendChild(t);const n=document.createElement("div");n.className="extraction-body";const i=document.createElement("div");i.className="extract-url",n.appendChild(i);const r=document.createElement("div");r.className="extract-status",r.textContent=u("monitor.extractWaiting"),n.appendChild(r);const o=document.createElement("div");return o.className="extract-summary",n.appendChild(o),e.appendChild(n),e}ensureExtractionWindowInstance(e,t){const s=e||this.nextExtractionId();if(this.extractionWindows.has(s))return this.extractionWindows.get(s);const n=this.createExtractionWindowDom();n.id=s,n.element.dataset.extractId=s,this.elements.screen.appendChild(n.element);const i=this.computeExtractionAnchor(this.extractionWindows.size);this.windowAnchors.set(n.element,i),this.positionWindow(n.element,i),this.extractionWindows.set(s,n);const r=this.extractionWindows.size;if(n.titleEl){const o=t!=null&&t.title&&t.title.trim().length?t.title.trim():u("monitor.extractTitle");n.titleEl.textContent=r>1?`${o} #${r}`:o}return t!=null&&t.url&&(n.element.dataset.extractUrl=t.url),n}computeExtractionAnchor(e){const s=Math.floor(e/2),n=e%2,i=.2,r=.3,o=Math.min(.92,this.extractionAnchor.x+s*i),l=Math.min(.9,this.extractionAnchor.y+n*r);return{x:o,y:l}}clearExtractionWindows(){this.extractionWindows.forEach(e=>{this.closeWindow(e.element,{animate:!1}),this.windowAnchors.delete(e.element),this.manualPositions.delete(e.element),e.element.remove()}),this.extractionWindows.clear()}clearTerminalSessions(){this.terminalSessions.clear(),this.terminalSessionTitleMap.clear(),this.terminalSessionNames.clear(),this.terminalHistories.clear(),this.activeTerminalSessionId=null,this.lastTerminalSessionId=null,this.terminalContextSessionId=null,this.terminalLastFocusedAt=0,this.elements.terminalBody&&(this.elements.terminalBody.innerHTML=""),this.renderTerminalTabs()}purgeExtractionWindowByElement(e){for(const[t,s]of this.extractionWindows.entries())if(s.element===e){this.extractionWindows.delete(t),this.windowAnchors.delete(s.element),this.manualPositions.delete(s.element),setTimeout(()=>{s.element.remove()},340);break}}generateNewSessionId(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}isTerminalWindowOnTop(e){return e!=null&&e.element?(this.windowOrder[this.windowOrder.length-1]||null)===e.element:!1}resetCommandWindow(e=u("monitor.commandTitle"),t={}){this.elements.commandTitle&&(this.elements.commandTitle.textContent=e),this.elements.commandInput&&(this.elements.commandInput.textContent=""),t.clearOutput&&this.elements.commandOutput&&(this.elements.commandOutput.innerHTML=""),this.commandCurrentText=""}async revealCommandWindow(e=u("monitor.commandTitle"),t={}){const{reset:s=!0,focusInput:n=!1}=t;this.isWindowVisible(this.elements.commandWindow)||(await this.movePointerToApp("command"),await this.click()),s?this.resetCommandWindow(e,{clearOutput:!0}):this.elements.commandTitle&&(this.elements.commandTitle.textContent=e),this.showWindow(this.elements.commandWindow),n&&await this.focusCommandInput()}async focusCommandInput(){this.elements.commandInput&&(await this.movePointerToElement(this.elements.commandInput,{duration:360}),await this.click())}async typeCommandText(e){if(!this.elements.commandInput)return;const t=this.elements.commandInput;await this.focusCommandInput();const s=this.commandCurrentText;if(s){const n=s.length,i=1+Math.min(n/40,6),r=Math.max(6,Math.floor(18/i));for(let o=n;o>0;o-=1)t.textContent=s.slice(0,o-1),await m(r);this.commandCurrentText=""}await this.typeSmartText(t,e),this.commandCurrentText=e}appendCommandOutput(e){if(!this.elements.commandOutput)return;const t=document.createDocumentFragment();e.forEach(s=>{const n=document.createElement("div");n.className="command-line",n.textContent=s,t.appendChild(n)}),this.elements.commandOutput.appendChild(t),this.elements.commandOutput.scrollTop=this.elements.commandOutput.scrollHeight}resetPythonWindow(e="Python"){this.elements.pythonTitle&&(this.elements.pythonTitle.textContent=e),this.elements.pythonInput&&(this.elements.pythonInput.textContent=""),this.elements.pythonOutput&&(this.elements.pythonOutput.innerHTML="")}appendPythonOutput(e,t){if(!this.elements.pythonOutput)return;const s=document.createElement("div");s.className="python-block output";const n=document.createElement("div");n.className="python-block-title",n.textContent=e;const i=document.createElement("pre");i.textContent=t,s.appendChild(n),s.appendChild(i),this.elements.pythonOutput.innerHTML="",this.elements.pythonOutput.appendChild(s),this.scrollPythonToResult()}async revealPythonWindow(e="Python"){await this.movePointerToApp("python"),await this.click(),this.resetPythonWindow(e),this.showWindow(this.elements.pythonWindow)}async focusPythonInput(){this.elements.pythonInput&&(await this.movePointerToElement(this.elements.pythonInput,{duration:360}),await this.click())}async typePythonCode(e,t={}){if(!this.elements.pythonInput)return;const{deletePrevious:s=!0,animate:n=!0}=t,i=this.elements.pythonInput;if(s&&(i.textContent=""),await this.focusPythonInput(),!n){i.textContent=e;return}await this.typeSmartText(i,e)}async typeSmartText(e,t,s=!1){const n=t.split(` `),i=s||n.length>2||t.length>120,r=32;if(i){e.textContent="";for(let l=0;l0?` `:"")+n[l],await m(Math.max(12,r-Math.min(l,6)*3));return}const o=Array.from(t);for(const l of o)e.textContent=(e.textContent||"")+l,await m(18)}scrollPythonToTop(){this.elements.pythonBody&&this.elements.pythonBody.scrollTo({top:0,behavior:"smooth"})}scrollPythonToResult(){if(this.elements.pythonBody&&this.elements.pythonOutput){const e=this.elements.pythonOutput.offsetTop-this.elements.pythonBody.offsetTop;this.elements.pythonBody.scrollTo({top:e,behavior:"smooth"})}}async ensureMemoryWindowVisible(e={}){const{initialEntries:t,snapshotProvided:s=!1,memoryType:n="main"}=e,i=async()=>{if(s){this.renderMemoryEntries(t||[]);return}this.getMemoryItems().length||await this.loadMemoryEntries(n)};if(this.isWindowVisible(this.elements.memoryWindow)){this.showWindow(this.elements.memoryWindow),(!this.getMemoryItems().length||s)&&await i();return}await this.movePointerToApp("memory"),await this.click(),this.showWindow(this.elements.memoryWindow),await i()}getMemoryItems(){return this.elements.memoryList?Array.from(this.elements.memoryList.children):[]}extractMemorySnapshotEntries(e,t="before"){const s=t==="after"?"monitor_snapshot_after":"monitor_snapshot",n=e==null?void 0:e[s],i=n==null?void 0:n.entries;return Array.isArray(i)?{entries:i.map(r=>String(r??"")),provided:!0}:{entries:[],provided:!!n}}getMemoryItemByIndex(e){const t=this.getMemoryItems();return!e||e<1||e>t.length?null:t[e-1]}async waitForScrollSettled(e,t,s=600){const n=Date.now();return new Promise(i=>{const r=()=>{const o=Math.abs(e.scrollTop-t)<2,l=Date.now()-n>s;if(o||l){i();return}requestAnimationFrame(r)};requestAnimationFrame(r)})}async scrollMemoryToBottom(e=200){const t=this.elements.memoryList;if(!t)return;const s=t.scrollHeight;t.scrollTo({top:s,behavior:"smooth"}),await this.waitForScrollSettled(t,s),this.latestMemoryScroll=Date.now(),e>0&&await m(e)}async scrollMemoryItemIntoView(e,t=200){if(!e)return;const s=this.elements.memoryList;if(!s)return;const n=e.offsetTop-s.clientHeight*.35,i=Math.max(0,n);s.scrollTo({top:i,behavior:"smooth"}),await this.waitForScrollSettled(s,i),this.latestMemoryScroll=Date.now(),t>0&&await m(t)}ensureMemoryTypingVisible(e){if(!e)return;const t=this.elements.memoryList;if(!t)return;const s=t.scrollTop,n=s+t.clientHeight,i=e.offsetTop,r=i+e.offsetHeight;if(r>n-4){const o=r-n+12;t.scrollTop=s+o,this.latestMemoryScroll=Date.now()}else i0;l--)n.textContent=o.slice(0,l-1),await m(18)}const i=Array.from(t);let r=0;for(const o of i)r+=1,n.textContent=(n.textContent||"")+o,r%4===0&&this.ensureMemoryTypingVisible(e),await m(18);this.ensureMemoryTypingVisible(e)}async animateMemoryAppend(e){if(!this.elements.memoryList)return;await this.scrollMemoryToBottom();const t=this.createMemoryCard("");this.elements.memoryList.appendChild(t),requestAnimationFrame(()=>t.classList.add("visible")),await m(160),await this.scrollMemoryToBottom(),await this.movePointerToElement(t,{duration:420}),await this.click(),this.highlightMemoryCard(t,!0),await this.typeIntoMemoryCard(t,e,{clearFirst:!0}),await this.scrollMemoryItemIntoView(t),this.highlightMemoryCard(t,!1)}async animateMemoryReplace(e,t){const s=this.getMemoryItemByIndex(e);if(!s){await this.animateMemoryAppend(t);return}await this.scrollMemoryItemIntoView(s),await this.movePointerToElement(s,{duration:420}),await this.click(),this.highlightMemoryCard(s,!0),await this.typeIntoMemoryCard(s,t,{clearFirst:!0}),await this.scrollMemoryItemIntoView(s),this.highlightMemoryCard(s,!1)}async animateMemoryDelete(e){const t=this.getMemoryItemByIndex(e);!t||!this.elements.memoryList||(await this.scrollMemoryItemIntoView(t),await this.movePointerToElement(t,{duration:360}),await this.click(),this.highlightMemoryCard(t,!0),t.classList.add("swipe-out"),await this.movePointerToElement(t,{offsetX:t.clientWidth*.45,duration:240}),await m(200),t.remove(),this.highlightMemoryCard(t,!1))}async loadMemoryEntries(e="main"){try{const s=await(await fetch(`/api/memory?type=${encodeURIComponent(e)}`)).json();if(!(s!=null&&s.success)||!Array.isArray(s.entries))return;this.renderMemoryEntries(s.entries)}catch(t){console.warn("loadMemoryEntries failed",t)}}renderMemoryEntries(e){this.elements.memoryList&&(this.elements.memoryList.innerHTML="",e.forEach(t=>{const s=this.createMemoryCard(t);s.classList.add("visible"),this.elements.memoryList.appendChild(s)}),this.updateMemoryMeta())}async revealTerminalWindow(e){await this.movePointerToApp("terminal"),await this.click(),this.showWindow(e.element),e.titleEl&&(e.titleEl.textContent=u("monitor.terminalTitle")),this.terminalLastFocusedAt=Date.now()}async focusTerminalHeader(e,t={}){if(!(e!=null&&e.element))return;const s=e.element.querySelector(".window-header"),n=t.force||!this.isTerminalWindowOnTop(e);if(s&&n){await this.movePointerToElement(s,{duration:360}),await this.click(),this.terminalLastFocusedAt=Date.now();return}this.raiseWindowForTarget(e.element)}async focusTerminalPrompt(e,t){var n;this.ensurePromptLine(e);const s=((n=t==null?void 0:t.bodyEl)==null?void 0:n.lastElementChild)||null;return s&&(await this.movePointerToElement(s,{duration:520,offsetX:-6}),await this.click(),this.terminalLastFocusedAt=Date.now()),s}getTerminalHistory(e){return this.terminalHistories.has(e)||this.terminalHistories.set(e,[]),this.terminalHistories.get(e)}renderTerminalHistory(e){const t=this.getTerminalHistory(e),{bodyEl:s}=this.getTerminalInstance();s.innerHTML="",t.forEach(n=>{const i=document.createElement("pre");i.textContent=n.text,n.role==="prompt"?i.className="session-terminal-prompt-line":n.role==="note"&&(i.className="session-terminal-note-line"),s.appendChild(i)}),s.scrollTop=s.scrollHeight}ensurePromptLine(e){const t=this.getTerminalHistory(e);(!t.length||t[t.length-1].role!=="prompt")&&t.push({text:"➜ ",role:"prompt"}),this.renderTerminalHistory(e)}updatePromptText(e,t){const s=this.getTerminalHistory(e);!s.length||s[s.length-1].role!=="prompt"?s.push({text:t,role:"prompt"}):s[s.length-1].text=t,this.renderTerminalHistory(e)}appendTerminalOutputs(e,t,s){const n=this.getTerminalHistory(e);!n.length||n[n.length-1].role!=="prompt"?n.push({text:`➜ ${t}`.trimEnd(),role:"prompt"}):n[n.length-1].text=`➜ ${t}`.trimEnd(),s.forEach(i=>n.push({text:i,role:"output"})),n.push({text:"➜ ",role:"prompt"}),this.renderTerminalHistory(e)}appendTerminalNote(e,t){this.getTerminalHistory(e).push({text:t,role:"note"}),this.renderTerminalHistory(e)}closeTerminalSession(e){this.terminalSessions.delete(e);for(const[s,n]of this.terminalSessionTitleMap.entries())n===e&&this.terminalSessionTitleMap.delete(s);this.terminalSessionNames.delete(e),this.terminalHistories.delete(e),this.activeTerminalSessionId===e&&(this.activeTerminalSessionId=null),this.lastTerminalSessionId===e&&(this.lastTerminalSessionId=null),this.terminalContextSessionId===e&&(this.terminalContextSessionId=null);const t=this.terminalSessions.size?Array.from(this.terminalSessions.keys())[0]:null;if(t)this.activateSession(t);else{this.renderTerminalTabs();const{bodyEl:s}=this.getTerminalInstance();s.innerHTML="";const n=document.createElement("pre");n.textContent=u("monitor.terminalEmptyHint"),n.className="session-terminal-note-line",s.appendChild(n)}}async typeSessionCommand(e,t){this.ensurePromptLine(e);const s=this.getTerminalHistory(e),n=s[s.length-1];n.text="➜ ",this.renderTerminalHistory(e);const{bodyEl:i}=this.getTerminalInstance(),r=i.lastElementChild;if(t.length>80||t.split(` `).length>1){n.text=`➜ ${t}`,r&&(r.textContent=n.text,this.scrollPromptIntoView(this.getTerminalInstance())),await m(50);return}let l=0;const a=t.split("");for(const c of a)l+=1,n.text+=c,r&&(r.textContent=n.text),r&&(l%6===0||l===a.length)&&this.scrollPromptIntoView(this.getTerminalInstance()),await m(32)}getTerminalInstance(){return{element:this.elements.terminalWindow,bodyEl:this.elements.terminalBody,titleEl:this.elements.terminalHeaderText}}nextTerminalName(){const e=Array.from(this.terminalSessions.values()).map(n=>n.name);let t=e.length+1,s=u("monitor.terminalName",{n:t});for(;e.includes(s);)t+=1,s=u("monitor.terminalName",{n:t});return s}ensureSessionRecord(e,t,s){const n=(t||s||this.terminalSessionNames.get(e)||"").trim()||this.nextTerminalName();return this.terminalSessions.set(e,{id:e,name:n,rawName:s||t}),this.terminalSessionNames.set(e,n),this.terminalSessionTitleMap.set(n,e),s&&this.terminalRawNameMap.set(s,e),this.terminalHistories.has(e)||this.terminalHistories.set(e,[{text:"➜ ",role:"prompt"}]),this.renderTerminalTabs(),this.terminalSessions.get(e)}createSession(e,t){const s=this.generateNewSessionId();return this.ensureSessionRecord(s,(e||"").trim(),t),s}getTabElement(e){return this.elements.terminalTabList.querySelector(`[data-session-id="${e}"]`)}renderTerminalTabs(){if(!this.elements.terminalTabList||!this.elements.terminalAddButton)return;this.elements.terminalTabList.innerHTML="";const e=Array.from(this.terminalSessions.values()).map(t=>({id:t.id,name:t.name}));if(!e.length){this.elements.terminalAddButton.classList.add("lonely"),this.elements.terminalTabs.appendChild(this.elements.terminalAddButton);return}this.elements.terminalAddButton.classList.remove("lonely"),e.forEach(t=>{const s=document.createElement("button");s.className="terminal-tab",s.dataset.sessionId=t.id,s.textContent=t.name,this.activeTerminalSessionId&&t.id===this.activeTerminalSessionId&&s.classList.add("active"),this.elements.terminalTabList.appendChild(s)}),this.elements.terminalTabs.appendChild(this.elements.terminalAddButton)}activateSession(e){const t=this.terminalSessions.get(e)||this.ensureSessionRecord(e),{element:s,bodyEl:n,titleEl:i}=this.getTerminalInstance();return i&&(i.textContent=u("monitor.terminalTitle")),this.activeTerminalSessionId=e,this.lastTerminalSessionId=e,this.renderTerminalTabs(),this.renderTerminalHistory(e),this.showWindow(s),n.scrollTop=n.scrollHeight,this.terminalLastFocusedAt=Date.now(),t}async ensureTerminalSessionReady(e,t={}){var p,C,M,B,F,I,k,A,N,_;const{focusPrompt:s=!1,createIfMissing:n=!0,forceNew:i=!1,activate:r=!0}=t,o=((p=e==null?void 0:e.arguments)==null?void 0:p.create_new)===!0||((C=e==null?void 0:e.arguments)==null?void 0:C.new_session)===!0||((M=e==null?void 0:e.arguments)==null?void 0:M.force_new)===!0||((B=e==null?void 0:e.arguments)==null?void 0:B.new)===!0,l=((F=e==null?void 0:e.arguments)==null?void 0:F.session_name)||((I=e==null?void 0:e.arguments)==null?void 0:I.session)||((k=e==null?void 0:e.arguments)==null?void 0:k.name)||((A=e==null?void 0:e.arguments)==null?void 0:A.title)||((N=e==null?void 0:e.result)==null?void 0:N.session)||((_=e==null?void 0:e.result)==null?void 0:_.name)||(e==null?void 0:e.title)||null,a=this.resolveSessionMeta(e,{persist:!0,createIfMissing:n,forceNewIfAbsent:i||o,preferExisting:!(i||o||l)});let c=a.sessionId;const d=i||o||!c||!this.terminalSessions.has(c),w=this.getTerminalInstance(),g=this.isWindowVisible(w.element);g?this.showWindow(w.element):await this.revealTerminalWindow(w);let v=!1;if(d&&this.elements.terminalAddButton?(await this.movePointerToElement(this.elements.terminalAddButton,{duration:520}),await this.click(),c=this.createSession(a.title,a.rawName||void 0),v=!0):c&&this.ensureSessionRecord(c,a.title,a.rawName||void 0),!c&&this.terminalSessions.size&&(c=Array.from(this.terminalSessions.keys())[0]),c||(c=this.createSession(a.title,a.rawName||void 0),v=!0),r&&(v||this.activeTerminalSessionId!==c)){const z=this.getTabElement(c);z&&(await this.movePointerToElement(z,{duration:420}),await this.click())}let x=null;return r?(this.activateSession(c),x=this.elements.terminalBody.lastElementChild,s&&x&&(await this.movePointerToElement(x,{duration:520,offsetX:-6}),await this.click())):this.renderTerminalTabs(),{sessionId:c,title:a.title,instance:this.getTerminalInstance(),prompt:x,created:v,reopened:!g}}scrollPromptIntoView(e){e.bodyEl&&(e.bodyEl.scrollTop=e.bodyEl.scrollHeight)}sanitizeTerminalOutput(e){const t=/^root@[\w.-]+:.*[#$]\s*/;return e.map(s=>s==null?"":String(s)).filter(s=>!t.test(s.trim())).map(s=>s.replace(/\r$/,""))}resolveSessionMeta(e,{persist:t=!1,createIfMissing:s=!1,forceNewIfAbsent:n=!1,preferExisting:i=!0}={}){var w,g,v,x,p,C,M,B,F,I,k;const o=[(w=e==null?void 0:e.arguments)==null?void 0:w.session_name,(g=e==null?void 0:e.arguments)==null?void 0:g.session,(v=e==null?void 0:e.arguments)==null?void 0:v.name,(x=e==null?void 0:e.arguments)==null?void 0:x.title,(p=e==null?void 0:e.result)==null?void 0:p.session,(C=e==null?void 0:e.result)==null?void 0:C.session_name,(M=e==null?void 0:e.result)==null?void 0:M.name,(B=e==null?void 0:e.result)==null?void 0:B.title,e==null?void 0:e.name,e==null?void 0:e.title].filter(Boolean).find(Boolean)||null;let a=((F=e==null?void 0:e.arguments)==null?void 0:F.session_id)||((I=e==null?void 0:e.arguments)==null?void 0:I.connection_id)||((k=e==null?void 0:e.result)==null?void 0:k.session_id)||(e==null?void 0:e.session_id)||null;const c=(o||"").trim()||null;!a&&c&&this.terminalRawNameMap.has(c)&&(a=this.terminalRawNameMap.get(c)),!a&&c&&this.terminalSessionTitleMap.has(c)&&(a=this.terminalSessionTitleMap.get(c)),i&&(!a&&this.activeTerminalSessionId&&(a=this.activeTerminalSessionId),!a&&this.lastTerminalSessionId&&(a=this.lastTerminalSessionId),!a&&this.terminalSessions.size&&(a=Array.from(this.terminalSessions.keys())[0]));let d;return a&&this.terminalSessionNames.has(a)?d=this.terminalSessionNames.get(a):d=(o||"").trim()||this.nextTerminalName(),!a&&(s||n)&&(a=this.generateNewSessionId()),t&&a&&(this.lastTerminalSessionId=a),c&&a&&(this.terminalSessionTitleMap.set(c,a),this.terminalRawNameMap.set(c,a)),{sessionId:a,title:d,rawName:o}}resolveExistingSessionId(e){var n,i,r,o,l,a,c,d;const s=([(n=e==null?void 0:e.arguments)==null?void 0:n.session_name,(i=e==null?void 0:e.arguments)==null?void 0:i.session,(r=e==null?void 0:e.arguments)==null?void 0:r.name,(o=e==null?void 0:e.arguments)==null?void 0:o.title,(l=e==null?void 0:e.result)==null?void 0:l.session,(a=e==null?void 0:e.result)==null?void 0:a.session_name,(c=e==null?void 0:e.result)==null?void 0:c.name,(d=e==null?void 0:e.result)==null?void 0:d.title,e==null?void 0:e.name,e==null?void 0:e.title].filter(Boolean).find(Boolean)||"").trim();if(s){if(this.terminalRawNameMap.has(s))return this.terminalRawNameMap.get(s);if(this.terminalSessionTitleMap.has(s))return this.terminalSessionTitleMap.get(s)}return this.activeTerminalSessionId?this.activeTerminalSessionId:this.lastTerminalSessionId?this.lastTerminalSessionId:this.terminalSessions.size?Array.from(this.terminalSessions.keys())[0]:null}nextExtractionId(){return`extract-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}createDesktopFolderIcon(e){const t=document.createElement("div");t.className="desktop-icon",t.dataset.folderName=e;const s=document.createElement("img");s.src=this.assets.folderIcon,s.alt=e,t.appendChild(s);const n=document.createElement("span");return n.textContent=e,t.appendChild(n),t}hideAllWindows(){[this.elements.browserWindow,this.elements.extractionWindow,this.elements.folderWindow,this.elements.editorWindow,this.elements.terminalWindow,this.elements.readerWindow,this.elements.memoryWindow,this.elements.todoWindow,this.elements.waitWindow].forEach(e=>this.closeWindow(e,{animate:!1})),this.clearExtractionWindows(),this.clearTerminalSessions(),this.windowOrder=[],this.manualPositions.clear()}setupAnchors(){this.windowAnchors.set(this.elements.browserWindow,{x:.02,y:.02}),this.windowAnchors.set(this.elements.extractionWindow,{x:.6,y:.04}),this.windowAnchors.set(this.elements.folderWindow,{x:.68,y:.26}),this.windowAnchors.set(this.elements.editorWindow,{x:.62,y:.58}),this.windowAnchors.set(this.elements.terminalWindow,{x:.18,y:.42}),this.windowAnchors.set(this.elements.commandWindow,{x:.2,y:.7}),this.windowAnchors.set(this.elements.pythonWindow,{x:.52,y:.16}),this.windowAnchors.set(this.elements.readerWindow,{x:.42,y:.05}),this.windowAnchors.set(this.elements.memoryWindow,{x:.28,y:.32}),this.windowAnchors.set(this.elements.todoWindow,{x:.5,y:.32}),this.windowAnchors.set(this.elements.waitWindow,{x:.74,y:.24})}layoutFloatingWindows(){this.windowAnchors.forEach((e,t)=>this.positionWindow(t,e)),this.hideWaitOverlay()}positionWindow(e,t){if(!e)return;const s=e.offsetWidth,n=e.offsetHeight;if(!s||!n)return;if(this.manualPositions.has(e)){const g=this.manualPositions.get(e),{left:v,top:x}=this.clampWindowPosition(e,g.left,g.top);e.style.left=`${v}px`,e.style.top=`${x}px`,this.manualPositions.set(e,{left:v,top:x});return}const i=Math.max(0,this.elements.screen.clientWidth-K*2-s),r=Math.max(0,this.elements.screen.clientHeight-K-Q-K-n),o=K+i*t.x,l=Q+r*t.y,a=this.elements.screen.clientWidth-s-K,c=Math.max(Q,this.elements.screen.clientHeight-n-K),d=Math.min(Math.max(K,o),Math.max(K,a)),w=Math.min(Math.max(Q,l),c);e.style.left=`${d}px`,e.style.top=`${w}px`}setupScenes(){this.sceneHandlers.browserSearch=async(e,t)=>{var l,a,c;this.applySceneStatus(t,"browserSearch",u("monitor.searchStatus")),this.isWindowVisible(this.elements.browserWindow)||(await this.movePointerToApp("browser"),await this.click({count:2})),this.showWindow(this.elements.browserWindow),await m(400);const n=this.elements.browserSearchText.parentElement;n&&(await this.movePointerToElement(n,{offsetX:-40}),await this.click());const i=((l=e==null?void 0:e.arguments)==null?void 0:l.query)||((a=e==null?void 0:e.argumentSnapshot)==null?void 0:a.query)||u("monitor.defaultSearchQuery");await this.typeSearchQuery(i),this.elements.browserStatus.textContent=u("monitor.browserSearching");const r=await t.waitForResult(e.executionId||e.id);if(!this.ensureSuccessOrErrorBubble(r,e,u("monitor.searchFailed")))return;const o=Array.isArray((c=r==null?void 0:r.result)==null?void 0:c.results)?r.result.results:[];this.renderSearchResults(o),this.elements.browserStatus.textContent=(r==null?void 0:r.status)==="completed"?u("monitor.searchCompleted"):u("monitor.searchIncomplete"),await m(320),await this.simulateResultBrowsing(),this.pushWindowToStack(this.elements.browserWindow)},this.sceneHandlers.webExtract=async(e,t)=>{var v,x,p,C,M,B,F,I,k,A,N;this.applySceneStatus(t,"webExtract",u("monitor.statusExtracting"));const s=((v=e==null?void 0:e.arguments)==null?void 0:v.url)||((x=e==null?void 0:e.arguments)==null?void 0:x.target_url)||((p=e==null?void 0:e.result)==null?void 0:p.url)||((C=e==null?void 0:e.result)==null?void 0:C.source)||"";let n=!1;if(s){const _=await this.focusSearchResultByUrl(s);_&&(n=!0,this.showWindow(this.elements.browserWindow),await this.movePointerToElement(_,{duration:700}),await this.click({count:2}),setTimeout(()=>_.classList.remove("target"),800),await m(380))}if(!n){this.isWindowVisible(this.elements.browserWindow)||(await this.movePointerToApp("browser"),await this.click({count:2})),this.showWindow(this.elements.browserWindow);const z=this.elements.browserSearchText.parentElement;z&&(await m(240),await this.movePointerToElement(z,{offsetX:-40}),await this.click());const q=s||((M=e==null?void 0:e.arguments)==null?void 0:M.query)||((B=e==null?void 0:e.arguments)==null?void 0:B.title)||"https://example.com";await this.typeSearchQuery(q),this.elements.browserStatus.textContent=s?u("monitor.browserOpening"):u("monitor.browserSearching"),await m(900)}const i=String((e==null?void 0:e.executionId)||(e==null?void 0:e.id)||this.nextExtractionId()),r=this.ensureExtractionWindowInstance(i,{title:((F=e==null?void 0:e.arguments)==null?void 0:F.title)||((I=e==null?void 0:e.result)==null?void 0:I.title),url:s});this.showWindow(r.element);const o=s||((k=e==null?void 0:e.arguments)==null?void 0:k.url)||((A=e==null?void 0:e.result)==null?void 0:A.url)||((N=e==null?void 0:e.result)==null?void 0:N.source)||"";r.urlEl.textContent=o,r.stateEl.textContent=u("monitor.extractInProgress"),r.stateEl.classList.remove("complete"),r.summaryEl.innerHTML="";let l=null;try{l=await t.waitForResult(e.executionId||e.id)}catch(_){console.warn("[MonitorDirector] webExtract waitForResult error",_)}if(!this.ensureSuccessOrErrorBubble(l,e,u("monitor.extractFailed")))return;const a=(l==null?void 0:l.result)??(e==null?void 0:e.result)??null,{hasContent:c,hasError:d}=this.renderExtractionSummary(r.summaryEl,a);(this.resolveExtractionStatus(l,e,a)||(d?"failed":c?"completed":null))==="failed"?(r.stateEl.textContent=u("monitor.extractStateFailed"),r.stateEl.classList.remove("complete")):(r.stateEl.textContent=u("monitor.extractStateComplete"),r.stateEl.classList.add("complete")),await m(400)},this.sceneHandlers.createFolder=async(e,t)=>{var a,c;this.applySceneStatus(t,"createFolder",u("monitor.statusCreatingFolder")),this.lockDesktopRender();const s=((a=e==null?void 0:e.arguments)==null?void 0:a.path)||((c=e==null?void 0:e.arguments)==null?void 0:c.target_path)||u("monitor.defaultFolderName"),n=this.normalizePathSegments(s),i=n.pop()||u("monitor.defaultFolderName"),r=this.composePath(n),o=this.composePath([r,i].filter(Boolean));this.markPendingCreation(o);let l=null;try{let d=null;if(!n.length)d=this.folderIcons.get(i)||null;else{const p=this.composePath([r,i]);d=this.findFolderEntryElement(p)}d&&(d.style.opacity="0",d.classList.add("pending-reveal"));const w=t.waitForResult(e.executionId||e.id).catch(p=>(console.warn("[MonitorDirector] createFolder waitForResult error",p),null));if(n.length?await this.openFolderChain(n)&&(await this.movePointerToElement(this.elements.folderBody,{offsetX:40,offsetY:40,duration:720}),await this.click({right:!0}),this.showContextMenu("folder"),await m(200),await this.highlightMenu("folder","folder"),await this.click(),this.hideContextMenus()):(await this.movePointerToDesktop(),await this.click({right:!0}),this.showContextMenu("desktop"),await m(240),await this.highlightMenu("desktop","folder"),await this.click(),this.hideContextMenus()),l=await w,!this.ensureSuccessOrErrorBubble(l,e,u("monitor.createFolderFailed")))return;const g=this.resolveResultPath(l,s);this.releasePendingCreation(g);const v=this.normalizePathSegments(g),x=v.pop()||i;if(v.length){const p=this.composePath(v);this.upsertFolderEntry(p,{name:x,type:"folder"}),await this.openFolder(p,p);const C=this.composePath([p,x]),M=this.findFolderEntryElement(C);M&&(M.classList.add("visible"),M.style.opacity="1")}else{this.ensureFolderKey(x),this.desktopRoots.includes(x)||this.desktopRoots.push(x),this.setDesktopRoots(this.desktopRoots,{immediate:!0});const p=await this.revealDesktopFolderIcon(x,{fallbackSpawn:!0});p&&(p.style.opacity="1",await this.movePointerToElement(p,{duration:420}))}await m(600)}finally{this.releasePendingCreation(o),this.unlockDesktopRender()}},this.sceneHandlers.createFile=async(e,t)=>{var a,c;this.applySceneStatus(t,"createFile",u("monitor.statusCreatingFile")),this.lockDesktopRender();const s=((a=e==null?void 0:e.arguments)==null?void 0:a.path)||((c=e==null?void 0:e.arguments)==null?void 0:c.target_path)||"new-file.txt",n=this.normalizePathSegments(s),i=n.pop()||u("monitor.defaultFileName"),r=this.composePath(n),o=this.composePath([r,i].filter(Boolean));this.markPendingCreation(o);let l=null;try{let d=null;if(!n.length)d=this.fileIcons.get(i)||null;else{const p=this.composePath([r,i]);d=this.findFolderEntryElement(p)}d&&(d.style.opacity="0",d.classList.add("pending-reveal"));const w=t.waitForResult(e.executionId||e.id).catch(p=>(console.warn("[MonitorDirector] createFile waitForResult error",p),null));if(n.length?await this.openFolderChain(n)&&(await this.movePointerToElement(this.elements.folderBody,{offsetX:30,offsetY:20,duration:720}),await this.click({right:!0}),this.showContextMenu("folder"),await m(200),await this.highlightMenu("folder","file"),await this.click(),this.hideContextMenus()):(await this.movePointerToDesktop(),await this.click({right:!0}),this.showContextMenu("desktop"),await m(200),await this.highlightMenu("desktop","file"),await this.click(),this.hideContextMenus()),l=await w,!this.ensureSuccessOrErrorBubble(l,e,u("monitor.createFileFailed")))return;const g=this.resolveResultPath(l,s);this.releasePendingCreation(g);const v=this.normalizePathSegments(g),x=v.pop()||i;if(v.length){const p=this.composePath(v);this.upsertFolderEntry(p,{name:x,type:"file"});const C=this.composePath([p,x]),M=this.findFolderEntryElement(C);M&&(M.classList.add("visible"),M.style.opacity="1")}else{let p=this.fileIcons.get(x);p||(p=this.spawnDesktopFile(x)),p&&(p.style.opacity="1",await this.movePointerToElement(p,{duration:520}))}await m(400)}finally{this.releasePendingCreation(o),this.unlockDesktopRender()}},this.sceneHandlers.renameFile=async(e,t)=>{var d,w,g,v,x,p,C,M,B,F,I,k,A,N,_,z,q;this.applySceneStatus(t,"renameFile",u("monitor.statusRenaming")),this.lockDesktopRender();const s=((d=e==null?void 0:e.arguments)==null?void 0:d.path)||((w=e==null?void 0:e.arguments)==null?void 0:w.target_path)||((g=e==null?void 0:e.arguments)==null?void 0:g.old_path)||((v=e==null?void 0:e.arguments)==null?void 0:v.source_path)||((x=e==null?void 0:e.arguments)==null?void 0:x.from_path)||((p=e==null?void 0:e.argumentSnapshot)==null?void 0:p.old_path)||((C=e==null?void 0:e.argumentSnapshot)==null?void 0:C.path)||((M=e==null?void 0:e.result)==null?void 0:M.old_path)||((B=e==null?void 0:e.result)==null?void 0:B.path),n=((F=e==null?void 0:e.arguments)==null?void 0:F.new_path)||((I=e==null?void 0:e.arguments)==null?void 0:I.destination_path)||((k=e==null?void 0:e.arguments)==null?void 0:k.target_path)||((A=e==null?void 0:e.argumentSnapshot)==null?void 0:A.new_path)||((N=e==null?void 0:e.argumentSnapshot)==null?void 0:N.path)||((_=e==null?void 0:e.result)==null?void 0:_.new_path)||((z=e==null?void 0:e.result)==null?void 0:z.destination_path);if(G("scene:start",{sourcePath:s,targetPath:n,status:e==null?void 0:e.status,resultStatus:(q=e==null?void 0:e.result)==null?void 0:q.status}),!s||!n){await m(400),this.unlockDesktopRender();return}let i=null;try{i=await t.waitForResult(e.executionId||e.id)}catch(P){console.warn("[MonitorDirector] renameFile waitForResult error",P),i=null}if(!this.ensureSuccessOrErrorBubble(i,e,u("monitor.renameFailed"))){this.unlockDesktopRender();return}const r=this.normalizePathSegments(s),o=this.normalizePathSegments(n),l=r.pop()||"",a=o.pop()||"";G("scene:resolved-names",{fromName:l,toName:a,sourceSegments:[...r],targetSegments:[...o]});const c=async()=>{if(this.showContextMenu("file"),await this.waitForMenuVisible(this.elements.fileMenu,240),!await this.highlightMenu("file","rename")){const W=this.elements.fileMenu.querySelector('button[data-action="rename"]');W&&(await this.movePointerToElement(W,{duration:300}),W.classList.add("active"),await m(180),W.classList.remove("active"))}await this.click(),this.hideContextMenus()};try{if(r.length){const P=await this.openFolderChain(r);if(P){const W=(this.folderEntries.get(P)||[]).find(j=>j.name===l),S=(W==null?void 0:W.type)||"file";this.upsertFolderEntry(P,{name:l,type:S},{animate:!1}),await this.openFolder(P,P),await m(40);const y=this.composePath([P,l]),V=this.findFolderEntryElement(y);G("scene:folder-target",{entryPath:y,found:!!V}),V?(await this.movePointerToElement(V,{duration:620}),await this.click({right:!0}),await c(),await this.animateRenameLabel(V,a),G("scene:folder-rename-animated",{entryPath:y,toName:a})):G("scene:folder-missing-target",{entryPath:y}),this.renameFolderEntry(P,l,a,{skipRender:!0})}}else{const P=this.fileIcons.get(l)||this.folderIcons.get(l)||null;G("scene:desktop-target",{fromName:l,found:!!P}),P?(await this.movePointerToElement(P,{duration:600}),await this.click({right:!0}),await c(),await this.animateRenameLabel(P,a),this.renameDesktopEntry(P,a),G("scene:desktop-rename-animated",{fromName:l,toName:a}),this.fileIcons.has(l)&&(this.fileIcons.delete(l),this.fileIcons.set(a,P)),this.folderIcons.has(l)&&this.renameDesktopRoot(l,a,{skipRender:!0})):G("scene:desktop-missing-target",{fromName:l})}await m(400)}catch(P){console.error("[MonitorRename] scene error",P)}finally{this.unlockDesktopRender()}},this.sceneHandlers.deleteFile=async(e,t)=>{var o,l;this.applySceneStatus(t,"deleteFile",u("monitor.statusDeletingFile"));const s=((o=e==null?void 0:e.arguments)==null?void 0:o.path)||((l=e==null?void 0:e.arguments)==null?void 0:l.target_path),n=this.normalizePathSegments(s),i=n.pop();if(!i){await m(300);return}const r=async(a,c="file")=>{if(!a)return!1;if(await this.movePointerToElement(a,{duration:600}),await this.click({right:!0}),this.showContextMenu(c),await m(160),!await this.highlightMenu("file","delete")){const w=this.elements.fileMenu.querySelector('button[data-action="delete"]');w&&await this.movePointerToElement(w,{duration:320})}return await this.click(),this.hideContextMenus(),!0};if(n.length){const a=await this.openFolderChain(n);if(a){const c=(this.folderEntries.get(a)||[]).find(x=>x.name===i),d=(c==null?void 0:c.type)||"file";this.upsertFolderEntry(a,{name:i,type:d},{animate:!1}),await this.openFolder(a,a),await m(40);const w=this.composePath([a,i]),g=this.findFolderEntryElement(w);if(!await r(g,"file")){this.removeFolderEntry(a,i);return}g==null||g.classList.add("removing"),setTimeout(()=>this.removeFolderEntry(a,i),260)}}else{const a=this.fileIcons.get(i)||this.folderIcons.get(i);if(a&&(await r(a,"file"),a.classList.add("removing"),setTimeout(()=>a.remove(),320),this.fileIcons.delete(i),this.folderIcons.has(i))){this.folderIcons.delete(i),this.folderEntries.delete(i);const c=this.desktopRoots.indexOf(i);c>=0&&this.desktopRoots.splice(c,1)}}await m(400)},this.sceneHandlers.wait=async(e,t)=>{var r,o;this.applySceneStatus(t,"wait",u("monitor.statusWaiting"));const s=Number(((r=e==null?void 0:e.arguments)==null?void 0:r.duration)||((o=e==null?void 0:e.arguments)==null?void 0:o.seconds)||(e==null?void 0:e.seconds)||(e==null?void 0:e.duration))||5;if(await this.movePointerToDesktop(),await this.click({right:!0}),this.showContextMenu("desktop"),await m(200),!await this.highlightMenu("desktop","wait")){const l=this.elements.desktopMenu.querySelector('button[data-action="wait"]');l&&await this.movePointerToElement(l,{duration:320})}await this.click(),this.hideContextMenus(),await m(140);const i=t.waitForResult(e.executionId||e.id).catch(()=>null);await this.playWaitCountdown(s,i)},this.sceneHandlers.appendFile=async(e,t)=>{var N,_,z,q,P,W,S,y,V,j,Z;this.applySceneStatus(t,"appendFile",u("monitor.statusEditing"));const s=((N=e==null?void 0:e.arguments)==null?void 0:N.path)||((_=e==null?void 0:e.argumentSnapshot)==null?void 0:_.path)||"file.txt",n=this.normalizePathSegments(s),i=n.pop()||"file.txt",o=typeof((z=e==null?void 0:e.monitor_snapshot)==null?void 0:z.path)=="string"&&e.monitor_snapshot.path||typeof((q=e==null?void 0:e.monitor_snapshot_after)==null?void 0:q.path)=="string"&&e.monitor_snapshot_after.path||null||this.composePath([...n,i]),l=o||s;if(O("scene:appendFile:start",{execution:(e==null?void 0:e.executionId)||(e==null?void 0:e.id),path:s}),!this.isWindowVisible(this.elements.editorWindow)){const D=await this.revealFileTarget(s,{spawnDesktopFile:!0});D!=null&&D.element?await this.openFileMenuAction(D.element,"edit"):await this.movePointerToDesktop()}this.openEditorWindow(i),this.renderEditorPlaceholder(u("monitor.readingContent"));const c=this.resolveEditorBeforeLines(e),d=typeof((P=e==null?void 0:e.monitor_snapshot)==null?void 0:P.content)=="string"?e.monitor_snapshot.content:(W=e==null?void 0:e.monitor_snapshot)==null?void 0:W.before,w=this.normalizeLines(d);let g=null;const v=(e==null?void 0:e.executionId)||(e==null?void 0:e.execution_id)||(e==null?void 0:e.id);!w.length&&l&&(g=await this.fetchEditorFileLines(l));let x=c.length?c:w.length?w:g||[];if(!x.length&&v){const D=await this.fetchMonitorSnapshotById(v,"before");D!=null&&D.length&&(x=D)}!x.length&&o&&this.editorSnapshots.has(o)&&(x=this.editorSnapshots.get(o).slice()),O("scene:appendFile:beforeLines",{count:x.length,remote:!!(g!=null&&g.length)}),this.prepareEditorScene(x);const p=await t.waitForResult(e.executionId||e.id).catch(D=>(console.warn("[MonitorDirector] appendFile waitForResult error",D),null));if(!this.ensureSuccessOrErrorBubble(p,e,u("monitor.editFailed")))return;const C=this.resolveEditorAfterLines(e,p),M=typeof((S=p==null?void 0:p.monitor_snapshot_after)==null?void 0:S.content)=="string"?p.monitor_snapshot_after.content:typeof((y=e==null?void 0:e.monitor_snapshot_after)==null?void 0:y.content)=="string"?e.monitor_snapshot_after.content:(V=e==null?void 0:e.monitor_snapshot_after)==null?void 0:V.after,B=this.normalizeLines(M);let F=null;!B.length&&l&&(F=await this.fetchEditorFileLines(l));let I=C.length?C:B.length?B:F||[];if(!I.length&&v){const D=await this.fetchMonitorSnapshotById(v,"after");D!=null&&D.length&&(I=D)}!I.length&&o&&this.editorSnapshots.has(o)&&(I=this.editorSnapshots.get(o).slice());const k=this.normalizeLines(((j=e==null?void 0:e.arguments)==null?void 0:j.content)||((Z=e==null?void 0:e.result)==null?void 0:Z.content)||""),A=I.length?I:k;O("scene:appendFile:nextLines",{after:I.length,fallback:k.length,remote:!!(F!=null&&F.length)}),await m(260),await this.animateEditorTransition(A),o&&A.length&&this.editorSnapshots.set(o,A.slice(0,J)),await m(400)},this.sceneHandlers.modifyFile=this.sceneHandlers.appendFile,this.sceneHandlers.runCommand=async(e,t)=>{var a,c,d,w;const s=(e==null?void 0:e.name)||(e==null?void 0:e.tool)||"run_command";this.applySceneStatus(t,"runCommand",u("monitor.statusCallingTool",{tool:s}));const n=((a=e==null?void 0:e.arguments)==null?void 0:a.command)||((c=e==null?void 0:e.result)==null?void 0:c.command)||'echo "Hello"';this.isWindowVisible(this.elements.commandWindow)?(this.showWindow(this.elements.commandWindow),await this.focusCommandInput(),this.elements.commandOutput&&(this.elements.commandOutput.innerHTML="")):await this.revealCommandWindow(u("monitor.commandTitle"),{reset:!0,focusInput:!0}),await this.typeCommandText(n);const r=await t.waitForResult(e.executionId||e.id);if(!this.ensureSuccessOrErrorBubble(r,e,u("monitor.commandFailed")))return;const o=((d=r==null?void 0:r.result)==null?void 0:d.output)||((w=r==null?void 0:r.result)==null?void 0:w.stdout)||u("monitor.commandDone"),l=this.sanitizeTerminalOutput(typeof o=="string"?o.split(` `):Array.isArray(o)?o.map(String):[String(o||"")]);this.appendCommandOutput(l.length?l:[u("monitor.commandDone")]),await m(500)},this.sceneHandlers.reader=async(e,t)=>{var d,w,g,v,x;const s=((d=e==null?void 0:e.arguments)==null?void 0:d.path)||((w=e==null?void 0:e.result)==null?void 0:w.path)||u("monitor.defaultDocPath"),n=String(((g=e==null?void 0:e.arguments)==null?void 0:g.type)||((v=e==null?void 0:e.result)==null?void 0:v.type)||"read").toLowerCase(),i={search:u("monitor.readerModeSearch"),extract:u("monitor.readerModeExtract")};t.setStatus(i[n]||u("monitor.statusReading")),H("readerScene:start",{executionId:(e==null?void 0:e.executionId)||(e==null?void 0:e.id),targetPath:s,readMode:n}),await this.revealFileTarget(s,{doubleClick:!0,spawnDesktopFile:!0})||await this.movePointerToDesktop(),this.showWindow(this.elements.readerWindow),this.elements.readerTitle.textContent=s,this.renderReaderMessage(u("monitor.readingContent"));let o=null;try{o=await t.waitForResult(e.executionId||e.id),H("readerScene:waitForResult resolved",{executionId:(e==null?void 0:e.executionId)||(e==null?void 0:e.id),hasCompletion:!!o,status:o==null?void 0:o.status,keys:o?Object.keys(o):[]})}catch(p){console.warn("[MonitorDirector] reader waitForResult error",p)}if(!this.ensureSuccessOrErrorBubble(o,e,u("monitor.readFailed")))return;const{source:l,label:a}=this.resolveReaderPayload(e,o);H("readerScene:payload resolved",{executionId:(e==null?void 0:e.executionId)||(e==null?void 0:e.id),payloadSource:a,hasPayload:!!l});const c=l?this.extractReaderLines(l):[];if(H("readerScene:extracted lines",{executionId:(e==null?void 0:e.executionId)||(e==null?void 0:e.id),count:c.length}),c.length)this.renderReaderLines(l),H("readerScene:render lines",{executionId:(e==null?void 0:e.executionId)||(e==null?void 0:e.id),count:c.length});else{const p=(o==null?void 0:o.message)||((x=e==null?void 0:e.result)==null?void 0:x.message)||u("monitor.noDisplayContent");this.renderReaderMessage(p),H("readerScene:fallback message",{executionId:(e==null?void 0:e.executionId)||(e==null?void 0:e.id),fallbackMessage:p})}await m(500)},this.sceneHandlers.focus=async(e,t)=>{var o,l;this.applySceneStatus(t,"focus",u("monitor.statusFocusingFile"));const s=((o=e==null?void 0:e.arguments)==null?void 0:o.path)||((l=e==null?void 0:e.result)==null?void 0:l.path)||u("monitor.defaultFilePath"),n=await this.revealFileTarget(s,{spawnDesktopFile:!0});n!=null&&n.element?(await this.click({right:!0}),this.showContextMenu("focus"),await m(160),await this.highlightMenu("focus","focus"),await this.click(),this.hideContextMenus()):await this.movePointerToDesktop();const i=await t.waitForResult(e.executionId||e.id).catch(a=>(console.warn("[MonitorDirector] focus waitForResult error",a),null));if(!this.ensureSuccessOrErrorBubble(i,e,u("monitor.focusFailed")))return;this.showWindow(this.elements.readerWindow),this.elements.readerTitle.textContent=s,this.renderReaderMessage(u("monitor.loadingContent"));let r=!1;if(i!=null&&i.result&&this.extractReaderLines(i.result).length&&(this.renderReaderLines(i.result),r=!0),!r&&s){const a=await this.fetchEditorFileLines(s);a!=null&&a.length&&(this.renderReaderLines(a),r=!0)}r||this.renderReaderMessage(u("monitor.focusedReady")),this.elements.readerWindow.classList.add("focused"),await m(400)},this.sceneHandlers.unfocus=async(e,t)=>{var i,r;this.applySceneStatus(t,"unfocus",u("monitor.statusProcessing"));const s=((i=e==null?void 0:e.arguments)==null?void 0:i.path)||((r=e==null?void 0:e.result)==null?void 0:r.path)||u("monitor.defaultFilePath"),n=await this.revealFileTarget(s,{spawnDesktopFile:!0});n!=null&&n.element?(await this.click({right:!0}),this.showContextMenu("focus"),await m(160),await this.highlightMenu("focus","unfocus"),await this.click(),this.hideContextMenus()):await this.movePointerToDesktop(),await t.waitForResult(e.executionId||e.id).catch(o=>(console.warn("[MonitorDirector] unfocus waitForResult error",o),null)),this.ensureSuccessOrErrorBubble(null,e,u("monitor.unfocusFailed"))&&(this.showWindow(this.elements.readerWindow),this.elements.readerTitle.textContent=s,this.elements.readerWindow.classList.remove("focused"),this.renderReaderMessage(u("monitor.unfocused")),await m(400))},this.sceneHandlers.ocr=async(e,t)=>{var i,r;await this.sceneHandlers.reader(e,t),this.applySceneStatus(t,"ocr",u("monitor.statusExtracting"));const s=await t.waitForResult(e.executionId||e.id);if(!this.ensureSuccessOrErrorBubble(s,e,u("monitor.ocrFailed")))return;const n=((i=s==null?void 0:s.result)==null?void 0:i.text)||((r=s==null?void 0:s.result)==null?void 0:r.lines)||[];this.renderReaderOcr(n),await m(400)},this.sceneHandlers.memoryUpdate=async(e,t)=>{var a,c,d,w,g,v,x,p;this.applySceneStatus(t,"memoryUpdate",u("monitor.statusSyncingMemory"));const{entries:s,provided:n}=this.extractMemorySnapshotEntries(e,"before"),i=(((a=e==null?void 0:e.arguments)==null?void 0:a.memory_type)||((c=e==null?void 0:e.result)==null?void 0:c.memory_type)||"main").toString().toLowerCase();await this.ensureMemoryWindowVisible({initialEntries:s,snapshotProvided:n,memoryType:i});const r=(((d=e==null?void 0:e.arguments)==null?void 0:d.operation)||((w=e==null?void 0:e.result)==null?void 0:w.operation)||"append").toLowerCase(),o=((g=e==null?void 0:e.arguments)==null?void 0:g.content)||((v=e==null?void 0:e.result)==null?void 0:v.content)||"",l=Number(((x=e==null?void 0:e.arguments)==null?void 0:x.index)||((p=e==null?void 0:e.result)==null?void 0:p.index)||0)||0;r==="replace"?await this.animateMemoryReplace(l,o||""):r==="delete"?await this.animateMemoryDelete(l):await this.animateMemoryAppend(o||u("monitor.defaultMemory")),this.updateMemoryMeta(),await m(360)},this.sceneHandlers.todoCreate=async(e,t)=>{var i,r,o,l,a;this.applySceneStatus(t,"todoCreate",u("monitor.statusUpdatingTodo"));const s=((i=e==null?void 0:e.arguments)==null?void 0:i.summary)||((r=e==null?void 0:e.arguments)==null?void 0:r.overview)||((o=e==null?void 0:e.arguments)==null?void 0:o.title)||((l=e==null?void 0:e.arguments)==null?void 0:l.task)||u("monitor.defaultTodoSummary"),n=this.normalizeTodoTasks(((a=e==null?void 0:e.arguments)==null?void 0:a.tasks)||s);await this.ensureTodoWindowVisible(),this.resetTodoBoard({summary:!0,list:!0}),await this.typeTodoSummary(s);for(const c of n)await this.animateTodoAppend(c,{scrollIntoView:!1});this.elements.todoList&&(this.elements.todoList.scrollTop=0),await m(320)},this.sceneHandlers.todoUpdate=async(e,t)=>{var r,o,l,a,c,d,w;this.applySceneStatus(t,"todoUpdate",u("monitor.statusAdjustingTodo")),await this.ensureTodoWindowVisible();const s=((r=e==null?void 0:e.arguments)==null?void 0:r.title)||((o=e==null?void 0:e.arguments)==null?void 0:o.task)||null,n=Number(((l=e==null?void 0:e.arguments)==null?void 0:l.task_index)||((a=e==null?void 0:e.arguments)==null?void 0:a.index)||0)||null,i=((c=e==null?void 0:e.arguments)==null?void 0:c.completed)??((d=e==null?void 0:e.arguments)==null?void 0:d.done)??((w=e==null?void 0:e.arguments)==null?void 0:w.checked)??!0;await this.toggleTodoItem(s,!!i,n),await m(260)},this.sceneHandlers.todoFinish=async(e,t)=>{this.applySceneStatus(t,"todoFinish",u("monitor.statusFinishingTask"));const s=this.elements.todoWindow.querySelector(".traffic-dot.red");s&&(await this.movePointerToElement(s,{duration:420}),await this.click()),this.closeWindow(this.elements.todoWindow),this.resetTodoBoard({summary:!0,list:!0}),await m(320)},this.sceneHandlers.todoFinishConfirm=this.sceneHandlers.todoFinish,this.sceneHandlers.todoDelete=async(e,t)=>{var i,r;this.applySceneStatus(t,"todoDelete",u("monitor.statusRemovingTodo"));const s=((i=e==null?void 0:e.arguments)==null?void 0:i.title)||((r=e==null?void 0:e.arguments)==null?void 0:r.task)||null,n=this.findTodoItemByText(s);n&&(await this.scrollTodoItemIntoView(n),n.classList.add("removing"),await this.movePointerToElement(n,{duration:420}),await this.click({right:!0}),setTimeout(()=>n.remove(),260)),await m(280)},this.sceneHandlers.terminalSession=async(e,t)=>{var l,a,c,d,w,g,v,x,p,C,M,B,F,I;const s=(((l=e==null?void 0:e.arguments)==null?void 0:l.action)||(e==null?void 0:e.action)||"").toLowerCase();if(s==="reset"?this.applySceneStatus(t,"terminalSession",u("monitor.statusResettingTerminal")):this.applySceneStatus(t,"terminalSession",u("monitor.statusOpeningTerminal")),s==="close"||s==="reset"){U("terminalSession:action",{action:s,payload:e});const k=this.resolveExistingSessionId(e);if(!k){U("terminalSession:action:no-session",{action:s});return}const A=this.getTerminalInstance();if(this.isWindowVisible(A.element)?this.showWindow(A.element):await this.revealTerminalWindow(A),s==="reset"){await this.openTerminalContextMenu(k),await this.chooseTerminalMenuAction("reset"),this.terminalHistories.set(k,[{text:"➜ ",role:"prompt"}]),this.renderTerminalHistory(k),this.appendTerminalNote(k,u("monitor.terminalReset")),this.ensurePromptLine(k),await m(300);return}await this.openTerminalContextMenu(k),await this.chooseTerminalMenuAction("close"),this.closeTerminalSession(k),this.terminalSessions.size||this.closeWindow(this.elements.terminalWindow,{animate:!0}),await m(320);return}const n=((a=e==null?void 0:e.arguments)==null?void 0:a.session_id)||((c=e==null?void 0:e.arguments)==null?void 0:c.connection_id)||((d=e==null?void 0:e.arguments)==null?void 0:d.session)||((w=e==null?void 0:e.arguments)==null?void 0:w.session_name),i=((g=e==null?void 0:e.arguments)==null?void 0:g.session_name)||((v=e==null?void 0:e.arguments)==null?void 0:v.session)||((x=e==null?void 0:e.arguments)==null?void 0:x.name)||((p=e==null?void 0:e.arguments)==null?void 0:p.title)||((C=e==null?void 0:e.result)==null?void 0:C.session)||((M=e==null?void 0:e.result)==null?void 0:M.name)||(e==null?void 0:e.title)||null,r=i&&(this.terminalRawNameMap.has(i)||this.terminalSessionTitleMap.has(i)),o=((B=e==null?void 0:e.arguments)==null?void 0:B.create_new)===!0||((F=e==null?void 0:e.arguments)==null?void 0:F.new_session)===!0||((I=e==null?void 0:e.arguments)==null?void 0:I.force_new)===!0||!n&&this.terminalSessions.size>0&&!r;await this.ensureTerminalSessionReady(e,{focusPrompt:!1,forceNew:o,createIfMissing:!0,activate:!0}),await m(200)},this.sceneHandlers.terminalInput=async(e,t)=>{var l,a,c,d,w,g,v;this.applySceneStatus(t,"terminalInput",u("monitor.statusCallingTerminalInput"));const{sessionId:s}=await this.ensureTerminalSessionReady(e,{focusPrompt:!0,activate:!0}),n=((l=e==null?void 0:e.arguments)==null?void 0:l.command)||((a=e==null?void 0:e.arguments)==null?void 0:a.input)||((c=e==null?void 0:e.result)==null?void 0:c.command)||((d=e==null?void 0:e.result)==null?void 0:d.input)||"";await this.typeSessionCommand(s,n);const i=await t.waitForResult(e.executionId||e.id).catch(x=>(console.warn("[MonitorDirector] terminalInput waitForResult error",x),null)),r=((w=i==null?void 0:i.result)==null?void 0:w.output)||((g=i==null?void 0:i.result)==null?void 0:g.stdout)||((v=i==null?void 0:i.result)==null?void 0:v.content)||(i==null?void 0:i.result)||"",o=this.sanitizeTerminalOutput(typeof r=="string"?r.split(` `):Array.isArray(r)?r.map(String):[String(r||"")]);this.appendTerminalOutputs(s,n,o.length?o:[u("monitor.commandSent")]),await m(400)},this.sceneHandlers.terminalSnapshot=async(e,t)=>{this.applySceneStatus(t,"terminalSnapshot",u("monitor.statusGettingTerminal"));const{sessionId:s}=await this.ensureTerminalSessionReady(e,{focusPrompt:!1,activate:!1});U("scene:terminalSnapshot:start",{sessionId:s}),await this.openTerminalContextMenu(s),U("scene:terminalSnapshot:menu-opened",{sessionId:s}),await this.chooseTerminalMenuAction("snapshot"),this.appendTerminalNote(s,"[Snapshot Captured]"),this.ensurePromptLine(s),await m(300)},this.sceneHandlers.terminalSleep=async(e,t)=>{var r,o;this.applySceneStatus(t,"terminalSleep",u("monitor.statusWaiting"));const s=Number(((r=e==null?void 0:e.arguments)==null?void 0:r.duration)||((o=e==null?void 0:e.arguments)==null?void 0:o.seconds)||(e==null?void 0:e.seconds)||(e==null?void 0:e.duration))||5;if(await this.movePointerToDesktop(),await this.click({right:!0}),this.showContextMenu("desktop"),await m(200),!await this.highlightMenu("desktop","wait")){const l=this.elements.desktopMenu.querySelector('button[data-action="wait"]');l&&await this.movePointerToElement(l,{duration:320})}await this.click(),this.hideContextMenus(),await m(140);const i=t.waitForResult(e.executionId||e.id).catch(()=>null);await this.playWaitCountdown(s,i)},this.sceneHandlers.sleep=this.sceneHandlers.wait,this.sceneHandlers.webSave=async(e,t)=>{var r,o,l,a,c;this.applySceneStatus(t,"webSave",u("monitor.statusSavingWeb"));const s=((r=e==null?void 0:e.arguments)==null?void 0:r.url)||((o=e==null?void 0:e.arguments)==null?void 0:o.target_url)||((l=e==null?void 0:e.result)==null?void 0:l.url)||((a=e==null?void 0:e.result)==null?void 0:a.source)||"";let n=null;s&&(n=await this.focusSearchResultByUrl(s)),n||(n=this.elements.browserResults.querySelector("li")),n?(this.showWindow(this.elements.browserWindow),await this.movePointerToElement(n,{duration:620}),await this.click({right:!0}),this.showContextMenu("browser")):(await this.movePointerToElement(this.elements.browserWindow,{offsetX:40,offsetY:-120}),await this.click({right:!0}),this.showContextMenu("browser")),await m(200),await this.highlightMenu("browser","save"),await this.click(),this.hideContextMenus();const i=((c=e==null?void 0:e.arguments)==null?void 0:c.path)||"saved-page.html";this.spawnDesktopFile(i.split("/").pop()||"saved-page.html"),await m(600)},this.sceneHandlers.genericTool=async(e,t)=>{const s=(e==null?void 0:e.name)||(e==null?void 0:e.tool)||"tool";this.applySceneStatus(t,"genericTool",u("monitor.statusCallingTool",{tool:s})),await m(600)}}bindTerminalInteractions(){const e=this.elements.terminalAddButton,t=this.elements.terminalTabList,s=this.elements.terminalMenu;e&&e.addEventListener("click",this.handleTerminalAddClick),t&&(t.addEventListener("click",this.handleTerminalTabClick),t.addEventListener("contextmenu",this.handleTerminalTabContext)),s&&s.addEventListener("click",this.handleTerminalMenuClick),this.destroyFns.push(()=>{e==null||e.removeEventListener("click",this.handleTerminalAddClick),t==null||t.removeEventListener("click",this.handleTerminalTabClick),t==null||t.removeEventListener("contextmenu",this.handleTerminalTabContext),s==null||s.removeEventListener("click",this.handleTerminalMenuClick)})}bindManualInteractionListeners(){this.manualListenersAttached||(this.manualListenersAttached=!0,this.elements.screen.addEventListener("pointerdown",this.handleManualPointerDown),window.addEventListener("pointermove",this.handleManualPointerMove,{passive:!1}),window.addEventListener("pointerup",this.handleManualPointerUp),window.addEventListener("pointercancel",this.handleManualPointerUp),this.elements.screen.addEventListener("click",this.handleManualCloseClick,!0))}unbindManualInteractionListeners(){this.manualListenersAttached&&(this.manualListenersAttached=!1,this.elements.screen.removeEventListener("pointerdown",this.handleManualPointerDown),window.removeEventListener("pointermove",this.handleManualPointerMove),window.removeEventListener("pointerup",this.handleManualPointerUp),window.removeEventListener("pointercancel",this.handleManualPointerUp),this.elements.screen.removeEventListener("click",this.handleManualCloseClick,!0))}resetManualPositions(){this.manualPositions.size&&(this.manualPositions.forEach((e,t)=>{const s=this.windowAnchors.get(t);s&&this.positionWindow(t,s)}),this.manualPositions.clear())}beginManualDrag(e,t){if(!e)return;const s=e.getBoundingClientRect(),n=t.clientX-s.left,i=t.clientY-s.top;this.manualDragState={pointerId:t.pointerId,target:e,offsetX:n,offsetY:i};try{e.setPointerCapture(t.pointerId)}catch(r){console.warn("[MonitorDirector] setPointerCapture failed",r)}e.classList.add("manual-dragging"),this.updateManualDragPosition(t)}updateManualDragPosition(e){if(!this.manualDragState)return;const{target:t,offsetX:s,offsetY:n}=this.manualDragState;if(!t||!t.isConnected)return;const i=this.elements.screen.getBoundingClientRect(),r=e.clientX-i.left-s,o=e.clientY-i.top-n,{left:l,top:a}=this.clampWindowPosition(t,r,o);t.style.left=`${l}px`,t.style.top=`${a}px`,this.manualPositions.set(t,{left:l,top:a})}cancelManualDrag(){if(!this.manualDragState)return;const{target:e,pointerId:t}=this.manualDragState;e&&e.hasPointerCapture(t)&&e.releasePointerCapture(t),e==null||e.classList.remove("manual-dragging"),this.manualDragState=null}clampWindowPosition(e,t,s){const n=e.offsetWidth,i=e.offsetHeight,r=this.elements.screen.clientWidth-n-K,o=Math.max(Q,this.elements.screen.clientHeight-i-K),l=Math.min(Math.max(K,t),Math.max(K,r)),a=Math.min(Math.max(Q,s),o);return{left:l,top:a}}async movePointerToApp(e){this.refreshScreenRect();const t=this.appIcons.get(e);t?await this.movePointerToElement(t):await this.movePointerToDesktop()}async movePointerToDesktop(){return this.refreshScreenRect(),this.movePointerToElement(this.elements.desktopGrid,{offsetX:160,offsetY:120,duration:700})}async movePointerToElement(e,t={}){if(!e||(this.refreshScreenRect(),this.elements.screen.clientWidth<1||this.elements.screen.clientHeight<1))return;this.raiseWindowForTarget(e),this.progressBubbleBase?re("movePointer:preserve-progress",{target:e instanceof HTMLElement?e.className||e.tagName:e==null?void 0:e.toString()}):this.dismissBubble(!0);const{offsetX:s=0,offsetY:n=0,duration:i=900}=t,r=e.getBoundingClientRect();if(r.width<1&&r.height<1)return;const o=r.left-this.screenRect.left+r.width/2+s,l=r.top-this.screenRect.top+r.height/2+n,a=o-Y.x,c=l-Y.y;this.updatePointerTransform(a,c,i),await m(i+60)}isWindowVisible(e){return!!e&&e.classList.contains("visible")}async simulateResultBrowsing(e=2){const t=this.elements.browserResults;if(!t)return;const s=t.scrollHeight-t.clientHeight;if(s<=0)return;const n=Math.max(12,t.clientHeight/2-14),i=520,r=t.getBoundingClientRect(),o=r.left-this.screenRect.left+r.width/2-Y.x,l=r.top-this.screenRect.top+r.height/2+n-Y.y,a=r.top-this.screenRect.top+r.height/2-n-Y.y;for(let c=0;cs.remove(),450)}getPointerTip(){return{x:this.pointerBase.x+Y.x,y:this.pointerBase.y+Y.y}}flushPendingPointerTransform(){if(!this.pendingPointerTransform)return;const e=this.pendingPointerTransform;this.pendingPointerTransform=null,this.updatePointerTransform(e.x,e.y,e.duration)}updatePointerTransform(e,t,s=0){var l,a;if(!Number.isFinite(e)||!Number.isFinite(t))return;const n=this.elements.screen.clientWidth||((l=this.screenRect)==null?void 0:l.width)||0,i=this.elements.screen.clientHeight||((a=this.screenRect)==null?void 0:a.height)||0;if(n<1||i<1)return;const r=Math.min(Math.max(0,e),Math.max(0,n-10)),o=Math.min(Math.max(0,t),Math.max(0,i-10));this.elements.mousePointer.style.setProperty("--mouse-duration",`${Math.max(s,0)}ms`),this.elements.mousePointer.style.transform=`translate3d(${r}px, ${o}px, 0)`,this.pointerBase={x:r,y:o}}clampToScreen(e,t,s,n,i=12){const r=this.elements.screen.clientWidth-s-i,o=this.elements.screen.clientHeight-n-i;return{x:Math.min(Math.max(i,e),Math.max(i,r)),y:Math.min(Math.max(i,t),Math.max(i,o))}}setupScreenObserver(){typeof ResizeObserver>"u"||(this.screenObserver=new ResizeObserver(e=>{var i,r;const t=Array.isArray(e)?e[0]:null,s=((i=t==null?void 0:t.contentRect)==null?void 0:i.width)||this.elements.screen.clientWidth,n=((r=t==null?void 0:t.contentRect)==null?void 0:r.height)||this.elements.screen.clientHeight;s<1||n<1||(this.refreshScreenRect(),this.flushPendingPointerTransform())}),this.screenObserver.observe(this.elements.screen),this.destroyFns.push(()=>{var e;return(e=this.screenObserver)==null?void 0:e.disconnect()}))}showWindow(e){e.classList.remove("closing"),e.classList.add("visible");const t=this.windowAnchors.get(e);t&&this.positionWindow(e,t),this.pushWindowToStack(e),e===this.elements.folderWindow&&this.refreshFolderIconStates()}pushWindowToStack(e){e&&(this.windowOrder=this.windowOrder.filter(t=>t&&t!==e&&t.classList.contains("visible")),this.windowOrder.push(e),this.enforceWindowLimit(),this.updateWindowZIndices())}enforceWindowLimit(){if(this.windowOrder.length){for(this.windowOrder=this.windowOrder.filter(e=>e&&e.classList.contains("visible"));this.windowOrder.length>this.maxVisibleWindows;){const e=this.windowOrder.shift();e&&(this.closeWindow(e,{animate:!0}),this.purgeExtractionWindowByElement(e))}this.updateWindowZIndices()}}updateWindowZIndices(){this.windowOrder.forEach((t,s)=>{t&&t.classList.contains("visible")&&(t.style.zIndex=String(30+s))})}closeWindow(e,t={}){if(!e)return;const s=e===this.elements.folderWindow;if(s&&(this.activeFolder=null),this.windowOrder=this.windowOrder.filter(i=>i&&i!==e),!(t.animate??!1)){e.classList.remove("visible","closing"),this.updateWindowZIndices(),s&&this.refreshFolderIconStates();return}e.classList.contains("closing")||(e.classList.add("closing"),setTimeout(()=>{e.classList.remove("visible","closing"),this.updateWindowZIndices(),s&&this.refreshFolderIconStates()},320))}raiseWindowForTarget(e){const t=this.findWindowAncestor(e);t&&(this.windowOrder=this.windowOrder.filter(s=>s&&s!==t&&s.classList.contains("visible")),this.windowOrder.push(t),this.enforceWindowLimit(),this.updateWindowZIndices())}findWindowAncestor(e){let t=e;for(;t&&t!==this.elements.screen;){if(t instanceof HTMLElement&&t.classList.contains("window"))return t;t=t.parentElement}return null}showContextMenu(e,t){const n={desktop:this.elements.desktopMenu,folder:this.elements.folderMenu,file:this.elements.fileMenu,browser:this.elements.browserMenu,terminal:this.elements.terminalMenu,focus:this.elements.focusMenu}[e];if(!n)return;n.classList.add("visible");const i=this.getPointerTip(),r=typeof(t==null?void 0:t.x)=="number"?t.x:i.x+16,o=typeof(t==null?void 0:t.y)=="number"?t.y:i.y+16,{x:l,y:a}=this.clampToScreen(r,o,n.offsetWidth,n.offsetHeight);n.style.left=`${l}px`,n.style.top=`${a}px`}hideContextMenus(){[this.elements.desktopMenu,this.elements.folderMenu,this.elements.fileMenu,this.elements.focusMenu,this.elements.browserMenu,this.elements.terminalMenu].forEach(e=>{e.classList.remove("visible"),e.querySelectorAll("button").forEach(t=>t.classList.remove("active"))}),this.hideSecondaryMenu(),this.hideWaitOverlay(),this.terminalContextSessionId=null}hideSecondaryMenu(){this.secondaryMenu&&this.secondaryMenu.parentElement&&this.secondaryMenu.parentElement.removeChild(this.secondaryMenu),this.secondaryMenu=null}showSecondaryMenu(e,t){if(this.hideSecondaryMenu(),!e||!t.length)return null;const s=document.createElement("div");s.className="context-menu secondary-menu visible",t.forEach(a=>{const c=document.createElement("button");c.textContent=a.label,c.dataset.action=a.action,s.appendChild(c)}),this.elements.screen.appendChild(s);const n=e.getBoundingClientRect(),i=n.right-this.screenRect.left+10,r=n.top-this.screenRect.top+4,{x:o,y:l}=this.clampToScreen(i,r,s.offsetWidth||180,s.offsetHeight||60);return s.style.left=`${o}px`,s.style.top=`${l}px`,this.secondaryMenu=s,X("secondaryMenu:show",{items:t.map(a=>a.action),anchorRect:{left:n.left,top:n.top,width:n.width,height:n.height},pos:{x:o,y:l}}),s}async chooseSecondaryMenuAction(e){var s;const t=((s=this.secondaryMenu)==null?void 0:s.querySelector(`button[data-action="${e}"]`))||null;return t?(X("secondaryMenu:choose",{action:e,rect:t.getBoundingClientRect().toJSON?t.getBoundingClientRect().toJSON():t.getBoundingClientRect()}),await this.movePointerToElement(t,{duration:320}),t.classList.add("active"),await m(200),t.classList.remove("active"),await this.click(),await m(140),this.hideSecondaryMenu(),!0):(X("secondaryMenu:missing-btn",{action:e,hasMenu:!!this.secondaryMenu}),!1)}async highlightMenu(e,t){const n={desktop:this.elements.desktopMenu,folder:this.elements.folderMenu,file:this.elements.fileMenu,browser:this.elements.browserMenu,terminal:this.elements.terminalMenu,focus:this.elements.focusMenu}[e],i=n==null?void 0:n.querySelector(`button[data-action="${t}"]`);return i?(await this.movePointerToElement(i,{duration:360}),i.classList.add("active"),await m(240),i.classList.remove("active"),!0):!1}async openTerminalContextMenu(e){const t=this.getTabElement(e);let s;if(t){U("openContextMenu:move-to-tab",{sessionId:e,tabText:t.textContent}),await this.movePointerToElement(t,{duration:420}),await this.click({right:!0});const i=t.getBoundingClientRect();s={x:i.left-this.screenRect.left+i.width/2,y:i.top-this.screenRect.top+i.height/2},U("openContextMenu:tab-rect",{sessionId:e,rect:i,coords:s})}else U("openContextMenu:no-tab",{sessionId:e}),await this.movePointerToElement(this.elements.terminalWindow,{offsetX:18,offsetY:0,duration:420}),await this.click({right:!0});this.terminalContextSessionId=e,this.showContextMenu("terminal",s);const n=await this.waitForMenuVisible(this.elements.terminalMenu);U("openContextMenu:visible",{sessionId:e,visible:n}),n&&this.elements.terminalMenu&&this.snapPointerToElement(this.elements.terminalMenu)}async chooseTerminalMenuAction(e){U("chooseMenuAction:start",{action:e});const t=this.elements.terminalMenu,s=(t==null?void 0:t.querySelector(`button[data-action="${e}"]`))||null;if(s)await this.waitForMenuVisible(t),await this.movePointerToElement(s,{duration:320}),this.snapPointerToElement(s),s.classList.add("active"),await m(200),s.classList.remove("active"),U("chooseMenuAction:target",{action:e,rect:s.getBoundingClientRect().toJSON?s.getBoundingClientRect().toJSON():s.getBoundingClientRect()});else{const n=await this.highlightMenu("terminal",e);U("chooseMenuAction:highlight",{action:e,highlighted:n}),!n&&t&&(await this.movePointerToElement(t,{duration:260}),this.snapPointerToElement(t),U("chooseMenuAction:fallback-move",{action:e}))}await this.click(),await m(160),this.hideContextMenus(),U("chooseMenuAction:done",{action:e})}async waitForMenuVisible(e,t=240){if(!e)return!1;const s=performance.now();for(;!e.classList.contains("visible")&&performance.now()-s=60){const t=Math.floor(e/60).toString().padStart(2,"0"),s=(e%60).toString().padStart(2,"0");return`${t}:${s}`}return`${e}s`}async playWaitCountdown(e=5,t){const s=Math.max(1,Math.round(e));if(!this.elements.waitOverlay||!this.elements.waitCountdown)return;const n=this.getPointerTip();this.elements.waitOverlay.style.left=`${n.x+16}px`,this.elements.waitOverlay.style.top=`${n.y-28}px`;const i=performance.now();this.elements.waitCountdown.textContent=this.formatWaitText(s),this.elements.waitOverlay.classList.add("active"),this.waitOverlayTimer&&(clearInterval(this.waitOverlayTimer),this.waitOverlayTimer=null);let r=0;const o=()=>{const c=(performance.now()-i)/1e3,d=s-c;if(this.elements.waitCountdown)if(d>0)this.elements.waitCountdown.textContent=this.formatWaitText(Math.ceil(d));else{const w=Math.ceil(-d),g=".".repeat(r);r=(r+1)%4,this.elements.waitCountdown.textContent=u("monitor.waitOverrun",{n:w,dots:g})}};this.waitOverlayTimer=window.setInterval(o,260);const l=t||Promise.resolve(),a=new Promise(c=>setTimeout(c,s*1e3));try{await Promise.all([l.catch(()=>null),a])}finally{o(),this.hideWaitOverlay()}}snapPointerToElement(e,t=0,s=0){if(!e)return;const n=e.getBoundingClientRect(),i=n.left-this.screenRect.left+n.width/2+t,r=n.top-this.screenRect.top+n.height/2+s,o=i-Y.x,l=r-Y.y;this.updatePointerTransform(o,l,0)}spawnDesktopFolder(e){const t=this.createDesktopFolderIcon(e);return t.classList.add("temporary-shortcut"),this.elements.desktopGrid.appendChild(t),requestAnimationFrame(()=>t.classList.add("visible")),this.folderIcons.set(e,t),this.pendingDesktopFolders.delete(e),this.folderEntries.has(e)||this.folderEntries.set(e,[]),t}async waitForDesktopFolderIcon(e,t=1600){const s=Date.now();let n=this.folderIcons.get(e)||null;for(;!n&&Date.now()-ss.classList.add("visible")),s):null}spawnDesktopFile(e){const t=document.createElement("div");t.className="desktop-icon app";const s=document.createElement("img");s.src=this.assets.fileIcon,s.alt=e,t.appendChild(s);const n=document.createElement("span");return n.textContent=e,t.appendChild(n),t.classList.add("temporary-shortcut"),t.style.opacity="0",this.elements.desktopGrid.appendChild(t),requestAnimationFrame(()=>{t.style.transition="opacity 0.4s ease, transform 0.4s ease",t.style.opacity="1",t.style.transform="translateY(-6px)"}),this.fileIcons.set(e,t),t}async openFolder(e,t){e&&(await this.loadFolderEntries(e),this.activeFolder=e,this.showWindow(this.elements.folderWindow),this.elements.folderHeaderText.textContent=t||e||"workspace",this.renderFolderEntries(e),this.refreshFolderIconStates())}setFolderIconState(e){if(!e)return;const t=this.folderIcons.get(e);if(!t)return;const s=t.querySelector("img");s&&(s.src=this.assets.folderIcon)}removeFolderEntry(e,t){const s=this.folderEntries.get(e);if(!s)return;const n=s.find(r=>r.name===t)||null,i=s.filter(r=>r.name!==t);if(this.folderEntries.set(e,i),(n==null?void 0:n.type)==="folder"){const r=this.composePath([e,t].filter(Boolean));r&&this.folderEntries.has(r)&&this.folderEntries.delete(r)}this.activeFolder===e&&this.renderFolderEntries(e,!1)}closeFolder(){this.activeFolder=null,this.elements.folderWindow.classList.remove("visible"),this.refreshFolderIconStates()}renameFolderEntry(e,t,s,n={}){const i=this.folderEntries.get(e);if(!i)return;const r=i.find(o=>o.name===t);if(r&&(r.name=s,r.path=this.composePath([e,s].filter(Boolean)),r.type==="folder")){const o=this.composePath([e,t].filter(Boolean)),l=this.composePath([e,s].filter(Boolean));if(o&&l&&this.folderEntries.has(o)){const a=this.folderEntries.get(o)||[];this.folderEntries.delete(o),this.folderEntries.set(l,a)}}this.folderEntries.set(e,i),!n.skipRender&&this.activeFolder===e&&this.renderFolderEntries(e,!1)}renameDesktopEntry(e,t){const s=e.querySelector("span");s&&(s.textContent=t)}async animateRenameLabel(e,t){if(!e)return;const s=e.querySelector("span");if(!s)return;const n=s.textContent||"";if(n!==t){for(let i=n.length;i>0;i-=1)s.textContent=n.slice(0,i-1),await m(it);for(let i=0;i{if(l===e||l.startsWith(`${e}/`)){const a=t+l.slice(e.length),c=o.map(d=>{const w=d.path.startsWith(e)?t+d.path.slice(e.length):d.path;return{...d,path:w}});i.set(a,c)}else i.set(l,o)}),this.folderEntries=i;const r=this.desktopRoots.indexOf(e);r>=0&&(this.desktopRoots[r]=t),this.activeFolder&&(this.activeFolder===e?this.activeFolder=t:this.activeFolder.startsWith(`${e}/`)&&(this.activeFolder=t+this.activeFolder.slice(e.length))),s.skipRender||(this.renderDesktopFolders(),this.refreshFolderIconStates())}openEditorWindow(e){this.showWindow(this.elements.editorWindow),this.elements.editorHeaderText.textContent=e,this.elements.editorBody.innerHTML="",this.editorScene.lines=[],this.editorScene.placeholder=!1,this.elements.editorBody.scrollTo({top:0})}renderEditorPlaceholder(e){this.elements.editorBody.innerHTML="";const t=document.createElement("div");t.className="code-line placeholder visible",t.textContent=e,this.elements.editorBody.appendChild(t),this.editorScene.lines=[],this.editorScene.placeholder=!0,this.elements.editorBody.scrollTo({top:0})}async fetchEditorFileLines(e){var i;const t=(e||"").trim();if(!t)return null;const s=typeof AbortController<"u"?new AbortController:null,n=s?window.setTimeout(()=>s.abort(),8e3):null;try{const r=await fetch(`/api/gui/files/text?path=${encodeURIComponent(t)}`,{method:"GET",credentials:"include",headers:{Accept:"application/json"},signal:s==null?void 0:s.signal});if(n&&clearTimeout(n),!r.ok)return O("fetchFileLines:http-error",{path:t,status:r.status}),null;const o=await r.json().catch(()=>null);if(!o)return null;const l=typeof(o==null?void 0:o.content)=="string"?o.content:typeof((i=o==null?void 0:o.data)==null?void 0:i.content)=="string"?o.data.content:null;if(typeof l!="string")return O("fetchFileLines:empty",{path:t}),null;const a=this.normalizeLines(l);return O("fetchFileLines:resolved",{path:t,length:a.length}),a}catch(r){return(r==null?void 0:r.name)==="AbortError"||console.warn("[MonitorDirector] fetchEditorFileLines failed",r),null}finally{n&&clearTimeout(n)}}async fetchMonitorSnapshotById(e,t="before"){var r,o,l;const s=typeof e=="number"?String(e):(e||"").trim();if(!s)return null;const n=typeof AbortController<"u"?new AbortController:null,i=n?window.setTimeout(()=>n.abort(),6e3):null;try{const a=await fetch(`/api/gui/monitor_snapshot?executionId=${encodeURIComponent(s)}&stage=${t}`,{method:"GET",credentials:"include",headers:{Accept:"application/json"},signal:n==null?void 0:n.signal});if(!a.ok)return O("snapshotFetch:http-error",{executionId:s,stage:t,status:a.status}),null;const c=await a.json().catch(()=>null);if(!(c!=null&&c.success)||!(c!=null&&c.snapshot))return O("snapshotFetch:empty",{executionId:s,stage:t}),null;const d=typeof((r=c.snapshot)==null?void 0:r.content)=="string"?c.snapshot.content:typeof((o=c.snapshot)==null?void 0:o.text)=="string"?c.snapshot.text:Array.isArray((l=c.snapshot)==null?void 0:l.lines)?c.snapshot.lines:null;return d===null?(O("snapshotFetch:no-content",{executionId:s,stage:t}),null):this.normalizeLines(d)}catch(a){return(a==null?void 0:a.name)==="AbortError"||console.warn("[MonitorDirector] fetchMonitorSnapshot failed",a),null}finally{i&&clearTimeout(i)}}prepareEditorScene(e){const t=this.sanitizeEditorLines(e);if(O("prepareScene",{normalizedLength:t.length}),!t.length){this.renderEditorPlaceholder(u("monitor.editorEmpty"));return}this.renderEditorSnapshot(t)}sanitizeEditorLines(e){const t=this.normalizeLines(e);return t.length?t.slice(0,J):[]}renderEditorSnapshot(e){const t=this.sanitizeEditorLines(e);if(!t.length){this.renderEditorPlaceholder(u("monitor.editorEmpty"));return}this.editorScene.lines=t.slice(),this.editorScene.placeholder=!1;const s=this.elements.editorBody;s.innerHTML="";const n=document.createDocumentFragment();t.forEach((i,r)=>{n.appendChild(this.buildEditorLineElement(i,r))}),s.appendChild(n),s.scrollTo({top:0}),this.syncEditorIndices(),requestAnimationFrame(()=>{s.querySelectorAll(".code-line").forEach((r,o)=>{setTimeout(()=>r.classList.add("visible"),Math.min(o,10)*30)})})}buildEditorLineElement(e,t,s,n){const i=document.createElement("div"),r=["code-line"];s&&r.push(s),i.className=r.join(" "),i.dataset.index=String(t);const o=(n==null?void 0:n.prefill)!==!1;return i.textContent=o?e||" ":"",i}syncEditorIndices(){Array.from(this.elements.editorBody.children).forEach((e,t)=>{e instanceof HTMLElement&&(e.dataset.index=String(t))})}async focusEditorLine(e){const t=this.elements.editorBody;if(!t)return;const s=t.children[e];if(!s)return;const n=t.getBoundingClientRect(),i=s.getBoundingClientRect(),r=i.top+i.height/2-(n.top+n.height/2),o=Math.abs(r),l=Math.max(0,t.scrollTop+r),a=o<24?"auto":"smooth";try{t.scrollTo({top:l,behavior:a})}catch{t.scrollTop=l}const c=Math.min(700,Math.max(220,o*.8));await m(c)}async animateEditorTransition(e){const t=this.editorScene.lines.slice(),s=this.sanitizeEditorLines(e),n=s.length;if(O("animate:start",{currentLines:t.length,targetLines:n}),!t.length&&!s.length){this.renderEditorPlaceholder(u("monitor.editorEmpty"));return}if(n>30){this.renderEditorSnapshot(s);return}if(n>8){await this.animateEditorLineFill(s);return}if(t.length>De||s.length>De){O("animate:skip-large",{currentLines:t.length,targetLines:s.length}),this.renderEditorSnapshot(s);return}const i=this.buildEditorDiff(t,s),r=this.mergeEditorOperations(i),o=r.reduce((c,d)=>{var w;return d.type==="delete"?c:c+(((w=d.text)==null?void 0:w.length)||0)},0),l=r.length;if(this.editorSpeedBoost=this.computeEditorSpeedBoost(o,l),O("animate:operations",{count:r.length}),!r.length){s.length||this.renderEditorPlaceholder(u("monitor.editorEmpty"));return}const a=r.slice(0,_e);for(const c of a)c.type==="delete"?await this.animateEditorDeletion(c.index):c.type==="replace"?await this.animateEditorReplacement(c.index,c.text||""):await this.animateEditorInsertion(c.index,c.text||"");if(r.length>_e){O("animate:exceed-limit",{total:r.length}),this.renderEditorSnapshot(s);return}if(!s.length){this.renderEditorPlaceholder(u("monitor.editorEmpty"));return}this.editorScene.lines=s.slice(),this.syncEditorIndices(),O("animate:done",{finalLines:this.editorScene.lines.length}),this.editorSpeedBoost=1}async animateEditorLineFill(e){const t=this.sanitizeEditorLines(e);if(!t.length){this.renderEditorPlaceholder(u("monitor.editorEmpty"));return}const s=this.elements.editorBody;s.innerHTML="",t.forEach((r,o)=>{const l=this.buildEditorLineElement("",o,void 0,{prefill:!1});s.appendChild(l)}),s.scrollTo({top:0});const n=28,i=Array.from(s.children);for(let r=0;rnew Array(n+1).fill(0));for(let w=s-1;w>=0;w-=1)for(let g=n-1;g>=0;g-=1)e[w]===t[g]?i[w][g]=i[w+1][g+1]+1:i[w][g]=Math.max(i[w+1][g],i[w][g+1]);const r=[];let o=0,l=0;for(;o=i[o+1][l])){r.push({type:"insert",text:t[l]}),l+=1;continue}o{if(w.type==="keep"){d+=1;return}if(w.type==="insert"){const g=Math.min(d,c.length);a.push({type:"insert",index:g,text:w.text||""}),c.splice(g,0,w.text||""),d+=1;return}if(w.type==="delete"){const g=Math.max(c.length-1,0),v=Math.min(d,g);a.push({type:"delete",index:v}),c.splice(v,1)}}),O("diff",{before:e.length,after:t.length,rawOps:r.length,operations:a.length}),a}mergeEditorOperations(e){const t=[];for(let s=0;sJ){for(this.editorScene.lines=this.editorScene.lines.slice(0,J);s.children.length>J;){const l=s.lastElementChild;if(!l)break;s.removeChild(l)}this.syncEditorIndices(),O("insert:trim",{length:this.editorScene.lines.length})}}async animateEditorDeletion(e){const t=this.elements.editorBody;if(!t.children.length)return;const s=Math.max(0,Math.min(e,t.children.length-1)),n=t.children[s];if(!n){this.renderEditorSnapshot(this.editorScene.lines);return}await this.focusEditorLine(s),n.classList.add("diff-delete"),await this.eraseLineText(n),n.classList.add("removing"),await m(120),n.remove(),this.editorScene.lines.splice(s,1),this.syncEditorIndices()}async animateEditorReplacement(e,t){const s=this.elements.editorBody;if(!s.children.length){await this.animateEditorInsertion(e,t);return}const n=Math.max(0,Math.min(e,s.children.length-1)),i=s.children[n];if(!i){await this.animateEditorInsertion(e,t);return}const r=typeof t=="string"?t:"";await this.focusEditorLine(n),i.classList.add("diff-replace"),await this.eraseLineText(i,{instant:!1}),await this.typeLineText(i,r),i.classList.remove("diff-replace"),this.editorScene.lines[n]=r,this.syncEditorIndices()}adjustEditorScrollForLine(e){const t=this.elements.editorBody;if(!t||!e)return;const s=18,n=t.getBoundingClientRect(),i=e.getBoundingClientRect();let r=0;if(i.bottom>n.bottom-s?r=i.bottom-(n.bottom-s):i.topHe;if(e.textContent="",i){e.textContent=n,this.adjustEditorScrollForLine(e),await m(40);return}const r=1+Math.min(n.length/40,6),o=Math.max(1,r*this.editorSpeedBoost),l=Math.max(4,Math.floor(st/o));for(const a of n.split(""))e.textContent=`${e.textContent||""}${a}`,this.adjustEditorScrollForLine(e),await m(l)}async eraseLineText(e,t={}){if(!e)return;const s=e.textContent||"";if(!s.length){await m(40);return}if(typeof t.instant=="boolean"?t.instant:s.length>He){e.textContent="",await m(60);return}const i=1+Math.min(s.length/40,6),r=Math.max(1,i*this.editorSpeedBoost),o=Math.max(3,Math.floor(nt/r));for(let l=s.length-1;l>=0;l-=1)e.textContent=s.slice(0,l),await m(o);e.textContent=""}resolveEditorBeforeLines(e){const t=(e==null?void 0:e.argumentSnapshot)||(e==null?void 0:e.arguments)||{},s=(e==null?void 0:e.result)||{};return this.pickFirstNonEmptyLines([s.before,s.original,s.previous_content,t.existing_content,t.original_content,t.before])}resolveEditorAfterLines(e,t){const s=(t==null?void 0:t.result)||{},n=(e==null?void 0:e.result)||{},i=(e==null?void 0:e.argumentSnapshot)||(e==null?void 0:e.arguments)||{};return this.pickFirstNonEmptyLines([s.after,s.content,s.text,s.new_content,n.after,n.content,n.text,i.final_content,i.updated_content,i.content])}pickFirstNonEmptyLines(e){for(const t of e){const s=this.normalizeLines(t);if(s.length)return s}return[]}async typeEditorLines(e,t){if((t==null?void 0:t.highlight)==="diff"){await this.animateEditorTransition(e);return}this.prepareEditorScene(e)}computeEditorSpeedBoost(e,t){const s=Math.min(e/400,4),n=Math.min(t/120,2);return 1+s+n}async typeSearchQuery(e){this.elements.browserSearchText.textContent="";for(const t of e.split(""))this.elements.browserSearchText.textContent+=t,await m(70)}normalizeUrl(e){return!e||typeof e!="string"?"":e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}findSearchResultElement(e){const t=this.normalizeUrl(e);if(!t)return null;if(this.browserResultMap.has(t))return this.browserResultMap.get(t)||null;for(const[s,n]of this.browserResultMap.entries())if(s.includes(t)||t.includes(s))return n;return null}async focusSearchResultByUrl(e){const t=this.findSearchResultElement(e);if(!t)return null;this.clearResultTargets();const s=this.elements.browserResults.parentElement;if(s){const n=s.getBoundingClientRect(),i=t.getBoundingClientRect(),r=12;let o=s.scrollTop;const l=i.top-(n.top+r),a=i.bottom-(n.bottom-r);l<0?o=Math.max(0,s.scrollTop+l):a>0&&(o=Math.min(s.scrollHeight-s.clientHeight,s.scrollTop+a)),s.scrollTo({top:o,behavior:"smooth"}),await m(380)}return t.classList.add("target"),t}clearResultTargets(){this.elements.browserResults.querySelectorAll(".target").forEach(e=>e.classList.remove("target"))}renderSearchResults(e){this.clearResultTargets(),this.elements.browserResults.innerHTML="",this.browserResultMap.clear();const t=this.elements.browserResults.parentElement,s=e.slice(0,8);if(s.length)s.forEach(n=>{const i=document.createElement("li"),r=document.createElement("strong"),o=typeof(n==null?void 0:n.url)=="string"?n.url:"";r.textContent=(n==null?void 0:n.title)||o||u("monitor.searchResultFallback");const l=document.createElement("span");l.textContent=o||"agent.local",i.appendChild(r),i.appendChild(l),n!=null&&n.highlight&&i.classList.add("highlight");const a=this.normalizeUrl(o);a&&(i.dataset.url=a,this.browserResultMap.set(a,i)),this.elements.browserResults.appendChild(i)});else{const n=document.createElement("li");n.textContent=u("monitor.noSearchResults"),this.elements.browserResults.appendChild(n)}t&&t.scrollTo({top:0,behavior:"smooth"})}renderExtractionSummary(e,t){if(!e)return{hasContent:!1,hasError:!1};e.innerHTML="";let s=!1,n=!1;const i=(l,a)=>{const c=document.createElement("p");c.textContent=l,e.appendChild(c)};t&&typeof t=="object"&&t.error&&(i(`❌ ${t.error}`),n=!0);const r=this.normalizeExtractionSections(t);r.length?(s=!0,r.forEach(l=>{const a=document.createElement("div");if(a.className="extract-block",l.title||l.url){const d=document.createElement("div");if(d.className="extract-block-header",l.title){const w=document.createElement("strong");w.textContent=l.title,d.appendChild(w)}if(l.url){const w=document.createElement("span");w.textContent=l.url,d.appendChild(w)}a.appendChild(d)}const c=document.createElement("pre");c.textContent=l.text,a.appendChild(c),e.appendChild(a)})):n||i(u("monitor.noExtractionSummary"));const o=Array.isArray(t==null?void 0:t.failed_results)?t.failed_results:[];return o.length&&o.slice(0,2).forEach(l=>{i(u("monitor.extractFailedItem",{url:(l==null?void 0:l.url)||"URL",error:(l==null?void 0:l.error)||u("monitor.extractFailedLabel")}))}),requestAnimationFrame(()=>{e.scrollTo({top:e.scrollHeight,behavior:"smooth"})}),{hasContent:s,hasError:n}}normalizeExtractionSections(e){const t=[],s=(i,r)=>{const o=(i||"").trim();o&&t.push({title:(r==null?void 0:r.title)||void 0,url:(r==null?void 0:r.url)||void 0,text:o})},n=i=>{if(i===null||typeof i>"u")return"";if(typeof i=="string")return i.trim();if(typeof i=="number"||typeof i=="boolean")return String(i);if(Array.isArray(i))return i.map(r=>n(r)).filter(Boolean).join(` `);if(typeof i=="object"){const r=["raw_content","content","summary","paragraphs","paragraph","text","snippets","highlights","lines","chunks","description"];for(const o of r)if(o in i){const l=n(i[o]);if(l)return l}if(Array.isArray(i.sections))return i.sections.map(o=>n(o)).filter(Boolean).join(` `)}return""};if(e&&typeof e=="object"&&e.summary){const i=n(e.summary);i&&s(i,{title:e.title||u("monitor.extractSectionTitle"),url:e.url||e.source})}if(Array.isArray(e==null?void 0:e.results)&&e.results.length&&e.results.forEach((i,r)=>{const o=n(i);o&&s(o,{title:(i==null?void 0:i.title)||u("monitor.extractSectionItem",{n:r+1}),url:(i==null?void 0:i.url)||(i==null?void 0:i.source)})}),!t.length){const i=n(e);i&&s(i,{title:e==null?void 0:e.title,url:(e==null?void 0:e.url)||(e==null?void 0:e.source)})}return t}resolveExtractionStatus(e,t,s){const n=((e==null?void 0:e.status)||(t==null?void 0:t.status)||"").toString().toLowerCase();if(n==="completed")return"completed";if(n==="failed"||n==="error")return"failed";if(s&&typeof s=="object"){if(s.success===!1||s.error)return"failed";if(s.summary||s.paragraphs||s.content||s.raw_content||Array.isArray(s.results)&&s.results.length)return"completed"}return typeof s=="string"&&s.trim()||Array.isArray(s)&&s.length?"completed":null}toolResultSucceeded(e){var n,i,r;if(!e)return!0;const t=String((e==null?void 0:e.status)||((n=e==null?void 0:e.result)==null?void 0:n.status)||"").toLowerCase();return!(t&&!["completed","success","succeeded","ok","done"].includes(t)||((i=e==null?void 0:e.result)==null?void 0:i.success)===!1||(e==null?void 0:e.success)===!1||(r=e==null?void 0:e.result)!=null&&r.error||e!=null&&e.error)}resolveResultPath(e,t){var i,r,o;return e&&[(i=e==null?void 0:e.result)==null?void 0:i.path,e==null?void 0:e.path,(r=e==null?void 0:e.arguments)==null?void 0:r.path,(o=e==null?void 0:e.arguments)==null?void 0:o.target_path,t].find(l=>typeof l=="string"&&l.trim().length)||t}ensureSuccessOrErrorBubble(e,t,s=u("monitor.toolError")){var r,o;if(this.toolResultSucceeded(e??t??null))return!0;const i=((r=e==null?void 0:e.result)==null?void 0:r.error)||(e==null?void 0:e.error)||(t==null?void 0:t.error)||((o=t==null?void 0:t.result)==null?void 0:o.error)||s;return this.showSpeechBubble(i||s,{variant:"error",duration:2600}),!1}normalizeLines(e){if(typeof e=="string"){const t=e.split(/\r?\n/).map(s=>s.replace(/\t/g," "));return t.length?t:[""]}if(typeof e=="number")return[String(e)];if(Array.isArray(e)){const t=[];return e.forEach(s=>{if(typeof s=="string"||typeof s=="number")t.push(String(s));else if(s&&typeof s=="object"){const n=s.content||s.text||(Array.isArray(s.lines)?s.lines.join(` `):"");n&&t.push(...this.normalizeLines(n))}}),t}if(e&&typeof e=="object"){if(typeof e.content=="string")return this.normalizeLines(e.content);if(typeof e.text=="string")return this.normalizeLines(e.text);if(Array.isArray(e.lines))return this.normalizeLines(e.lines)}return[]}renderReaderMessage(e){this.elements.readerLines.innerHTML="";const t=this.buildEditorLineElement(e||u("monitor.readerEmptyFallback"),0);t.classList.add("reading-line","empty"),this.elements.readerLines.appendChild(t)}renderReaderLines(e){const t=this.extractReaderLines(e).slice(0,J);if(!t.length){this.renderReaderMessage(u("monitor.noVisibleContent"));return}this.elements.readerLines.innerHTML="",t.forEach((s,n)=>{const i=this.buildEditorLineElement(s.text||" ",n);i.classList.add("reading-line"),s.highlight&&i.classList.add("highlight"),this.elements.readerLines.appendChild(i),requestAnimationFrame(()=>{setTimeout(()=>i.classList.add("visible"),Math.min(n,30)*60)})})}resolveReaderPayload(e,t){var n,i;const s=[{label:"completion.result",value:t==null?void 0:t.result},{label:"completion.result.tool_payload",value:(n=t==null?void 0:t.result)==null?void 0:n.tool_payload},{label:"completion.payload",value:t==null?void 0:t.payload},{label:"payload.result",value:e==null?void 0:e.result},{label:"payload.result.tool_payload",value:(i=e==null?void 0:e.result)==null?void 0:i.tool_payload},{label:"payload.payload",value:e==null?void 0:e.payload},{label:"payload.arguments",value:e==null?void 0:e.arguments}];for(const r of s){const o=this.normalizeReaderPayloadCandidate(r.value);if(o!==null)return H("resolveReaderPayload hit",r.label),{source:o,label:r.label}}return{source:null,label:null}}normalizeReaderPayloadCandidate(e){if(e==null)return null;if(this.hasRenderableReaderContent(e))return e;if(typeof e=="string"){const t=this.tryParseReaderJson(e);return t&&this.hasRenderableReaderContent(t)?t:e.trim().length?e:null}if(typeof e=="object"){if(typeof e.output=="string"){const t=this.tryParseReaderJson(e.output);if(t&&this.hasRenderableReaderContent(t))return t;if(e.output.trim().length)return e.output}if(typeof e.tool_content=="string"){const t=this.tryParseReaderJson(e.tool_content);if(t&&this.hasRenderableReaderContent(t))return t;if(e.tool_content.trim().length)return e.tool_content}}return null}hasRenderableReaderContent(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:!!(typeof e=="object"&&(typeof e.content=="string"&&e.content.trim().length||typeof e.text=="string"&&e.text.trim().length||Array.isArray(e.lines)&&e.lines.length||Array.isArray(e.matches)&&e.matches.length||Array.isArray(e.segments)&&e.segments.length))}tryParseReaderJson(e){const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;try{return JSON.parse(t)}catch{return null}}renderReaderOcr(e){this.elements.readerOcr.innerHTML="";const t=this.normalizeLines(e);(t.length?t:[u("monitor.ocrReady")]).slice(0,6).forEach(n=>{const i=document.createElement("p");i.textContent=n,this.elements.readerOcr.appendChild(i)})}extractReaderLines(e){let t="";try{t=JSON.stringify(e,null,2)}catch{t="[unserializable source]"}if(!e)return[];if(typeof e=="string"||Array.isArray(e)){const n=this.normalizeLines(e).map((i,r)=>({text:i,lineNumber:r+1}));return H("extractReaderLines:string/array",{count:n.length}),n}if(typeof e!="object")return[];if(e.content!==void 0&&e.content!==null){H("extractReaderLines:try content",{type:typeof e.content});const n=this.normalizeLines(e.content).map((i,r)=>({text:i,lineNumber:r+1}));if(n.length)return H("extractReaderLines:content success",{count:n.length}),n}if(e.text!==void 0&&e.text!==null){H("extractReaderLines:try text",{type:typeof e.text});const n=this.normalizeLines(e.text).map((i,r)=>({text:i,lineNumber:r+1}));if(n.length)return H("extractReaderLines:text success",{count:n.length}),n}if(Array.isArray(e.lines)){H("extractReaderLines:try lines array",{length:e.lines.length});const n=this.normalizeLines(e.lines).map((i,r)=>({text:i,lineNumber:r+1}));if(n.length)return H("extractReaderLines:lines success",{count:n.length}),n}const s=typeof e.type=="string"?e.type.toLowerCase():"";if(s==="search"){const i=(Array.isArray(e.matches)?e.matches:[]).flatMap(r=>{const o=typeof(r==null?void 0:r.snippet)=="string"?r.snippet:r==null?void 0:r.content,l=Number((r==null?void 0:r.line_start)||(r==null?void 0:r.start_line)||0);return this.normalizeLines(o).map((a,c)=>({text:a,lineNumber:l?l+c:void 0,highlight:!0}))});return H("extractReaderLines:search matches",{count:i.length}),i}if(s==="extract"){const i=(Array.isArray(e.segments)?e.segments:[]).flatMap(r=>{const o=Number((r==null?void 0:r.line_start)||(r==null?void 0:r.start_line)||0),l=(r==null?void 0:r.content)||(r==null?void 0:r.text);return this.normalizeLines(l).map((a,c)=>({text:a,lineNumber:o?o+c:void 0}))});return H("extractReaderLines:extract segments",{count:i.length}),i}if(Array.isArray(e.segments)){const n=e.segments.flatMap(i=>{const r=Number((i==null?void 0:i.line_start)||(i==null?void 0:i.start_line)||0),o=(i==null?void 0:i.content)||(i==null?void 0:i.text);return this.normalizeLines(o).map((l,a)=>({text:l,lineNumber:r?r+a:void 0}))});return H("extractReaderLines:segments fallback",{count:n.length}),n}if(Array.isArray(e.matches)){const n=this.extractReaderLines({type:"search",matches:e.matches});return H("extractReaderLines:matches recursive",{count:n.length}),n}if(e.content||e.text){const n=Number(e.line_start||e.start_line||0),i=this.normalizeLines(e.content||e.text).map((r,o)=>({text:r,lineNumber:n?n+o:void 0}));return H("extractReaderLines:content/text fallback",{count:i.length}),i}return[]}addMemoryCard(e){const t=this.createMemoryCard(e);this.elements.memoryList.appendChild(t),requestAnimationFrame(()=>t.classList.add("visible")),this.updateMemoryMeta()}getTodoItems(){return this.elements.todoList?Array.from(this.elements.todoList.children):[]}findTodoItemByText(e){if(!e)return null;const t=(e||"").trim();return this.getTodoItems().find(s=>{var n,i;return((i=(n=s.querySelector(".todo-text"))==null?void 0:n.textContent)==null?void 0:i.trim())===t})||null}findTodoItemByIndex(e){if(!e||e<1)return null;const t=this.getTodoItems();return e>t.length?null:t[e-1]}normalizeTodoTasks(e){return Array.isArray(e)?e.map(t=>{if(typeof t=="string")return{text:t,done:!1};if(t&&typeof t=="object"){const s=String(t.title||t.task||t.text||"").trim(),n=typeof t.completed=="boolean"?t.completed:typeof t.done=="boolean"?t.done:typeof t.checked=="boolean"?t.checked:!1;return s?{text:s,done:n}:null}return null}).filter(Boolean):typeof e=="string"?[{text:e,done:!1}]:[]}createTodoItem(e,t=!1){const s=document.createElement("div");s.className="todo-item fly-in";const n=document.createElement("div");n.className="todo-text",n.textContent=e;const i=document.createElement("div");return i.className="todo-check",t&&(i.classList.add("checked"),s.classList.add("done")),s.appendChild(n),s.appendChild(i),s}renderTodoItems(e){this.elements.todoList&&(this.elements.todoList.innerHTML="",e.forEach(t=>{const s=this.createTodoItem(t.text,!!t.done);s.classList.add("visible"),this.elements.todoList.appendChild(s)}))}resetTodoBoard(e={}){const{summary:t=!0,list:s=!0}=e;t&&this.elements.todoSummary&&(this.elements.todoSummary.textContent=""),s&&this.elements.todoList&&(this.elements.todoList.innerHTML="",this.elements.todoList.scrollTop=0)}async ensureTodoWindowVisible(){if(this.isWindowVisible(this.elements.todoWindow)){this.showWindow(this.elements.todoWindow);return}await this.movePointerToApp("todo"),await this.click({count:2}),this.showWindow(this.elements.todoWindow),this.resetTodoBoard({summary:!0,list:!0})}async typeTodoSummary(e){if(!this.elements.todoSummary)return;await this.movePointerToElement(this.elements.todoSummary,{duration:420}),await this.click(),this.elements.todoSummary.textContent="";const t=Array.from(e||u("monitor.todoEmptySummary"));for(const s of t)this.elements.todoSummary.textContent=(this.elements.todoSummary.textContent||"")+s,await m(20)}async animateTodoAppend(e,t={}){if(!this.elements.todoList)return;const{scrollIntoView:s=!1}=t,n=this.createTodoItem(e.text,!!e.done);this.elements.todoList.appendChild(n),requestAnimationFrame(()=>n.classList.add("visible")),s&&await this.scrollTodoItemIntoView(n),await m(180)}async scrollTodoItemIntoView(e,t={}){if(!e||!this.elements.todoList)return;const s=this.elements.todoList,n=8,i=typeof t.waitMs=="number"?t.waitMs:120,r=()=>{const v=s.getBoundingClientRect(),x=e.getBoundingClientRect(),p=x.top-v.top+s.scrollTop,C=p+x.height,M=s.scrollTop,B=M+s.clientHeight;return{relTop:p,relBottom:C,viewTop:M,viewBottom:B}};let{relTop:o,relBottom:l,viewTop:a,viewBottom:c}=r();if(o>=a+n&&l<=c-n)return;const w=l>c-n?l-s.clientHeight+n:Math.max(0,o-n),g=Math.max(0,w);s.scrollTo({top:g,behavior:"smooth"}),await this.waitForScrollSettled(s,g),i>0&&await m(i),{relTop:o,relBottom:l,viewTop:a,viewBottom:c}=r(),oc-n&&(s.scrollTop=l-s.clientHeight+n,await m(30))}async toggleTodoItem(e,t,s){const n=this.findTodoItemByIndex(s)||this.findTodoItemByText(e)||(!e&&!s?this.getTodoItems()[0]:null);if(!n)return;await this.scrollTodoItemIntoView(n);const i=n.querySelector(".todo-check");if(!i)return;await this.movePointerToElement(i,{duration:420}),await this.click();const r=typeof t=="boolean"?t:!i.classList.contains("checked");i.classList.toggle("checked",r),n.classList.toggle("done",r),await m(200)}}const ct={class:"virtual-monitor-surface"},ht={class:"monitor-stage"},ut={class:"monitor"},mt={class:"monitor-shell"},dt={class:"monitor-top"},ft={class:"status-pill-group"},wt={class:"status-pill"},gt={key:0,class:"progress-pill"},bt={class:"progress-text"},pt={class:"desktop-layer"},vt={class:"desktop-section apps"},Tt={class:"desktop-section files"},xt={class:"window-header"},St={class:"browser-body"},Et={class:"search-bar"},Mt={class:"results-list results-scroll"},kt={class:"window-header"},Lt={class:"window-title"},Ct={class:"extraction-body"},It={class:"window-header"},Pt={class:"window-header"},Rt={class:"window-header"},Bt={class:"terminal-body"},Ft={class:"window-header"},Wt={class:"command-body"},At={class:"window-header"},Dt={class:"window-header"},_t={class:"reader-body"},Ht={class:"window-header"},Ot={class:"window-title"},Nt={class:"memory-body"},zt={class:"memory-footer hidden","aria-hidden":"true"},$t={class:"window-header"},yt={class:"window-title"},Vt={class:"todo-body"},Ut={class:"window-header"},qt={class:"window-title"},jt={class:"wait-body"},Kt={"data-action":"file"},Xt={"data-action":"folder"},Yt={"data-action":"wait"},Gt={"data-action":"file"},Zt={"data-action":"folder"},Jt={"data-action":"read"},Qt={"data-action":"edit"},es={"data-action":"rename"},ts={"data-action":"delete"},ss={"data-action":"focus"},ns={"data-action":"unfocus"},is={"data-action":"save"},rs={"data-action":"snapshot"},os={"data-action":"reset"},ls={"data-action":"close"},as=["src"],ws=Xe({__name:"VirtualMonitorSurface",setup($){const e=je(),{statusLabel:t,progressIndicator:s,lastTreeSnapshot:n}=Ke(e),i=et(()=>{var E;return((E=s.value)==null?void 0:E.label)||""}),r=T(null),o=T(null),l=T(null),a=T(null),c=T(null),d=T(null),w=T(null),g=T(null),v=T(null),x=T(null),p=T(null),C=T(null),M=T(null),B=T(null),F=T(null),I=T(null),k=T(null),A=T(null),N=T(null),_=T(null),z=T(null),q=T(null),P=T(null),W=T(null),S=T(null),y=T(null),V=T(null),j=T(null),Z=T(null),D=T(null),L=T(null),te=T(null),se=T(null),ie=T(null),ae=T(null),ce=T(null),he=T(null),ue=T(null),me=T(null),de=T(null),fe=T(null),we=T(null),ge=T(null),be=T(null),pe=T(null),ve=T(null),Te=T(null),xe=T(null),Se=T(null),Ee=T(null),Me=T(null),ke=T(null),Le=T(null),Ce=T(null),Ie=T(null),Pe=T(null),Re=T(null),Be=T(null),$e=new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2024%2024'%20width='48'%20height='48'%20fill='none'%20stroke='%23000000'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20style='opacity:1;'%3e%3cpath%20d='M4.037%204.688a.495.495%200%200%201%20.651-.651l16%206.5a.5.5%200%200%201-.063.947l-6.124%201.58a2%202%200%200%200-1.438%201.435l-1.579%206.126a.5.5%200%200%201-.947.063z'/%3e%3c/svg%3e",import.meta.url).href,ye={brainIcon:new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20stroke='currentColor'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20%3e%3cpath%20d='M12%2018V5'%20/%3e%3cpath%20d='M15%2013a4.17%204.17%200%200%201-3-4%204.17%204.17%200%200%201-3%204'%20/%3e%3cpath%20d='M17.598%206.5A3%203%200%201%200%2012%205a3%203%200%201%200-5.598%201.5'%20/%3e%3cpath%20d='M17.997%205.125a4%204%200%200%201%202.526%205.77'%20/%3e%3cpath%20d='M18%2018a4%204%200%200%200%202-7.464'%20/%3e%3cpath%20d='M19.967%2017.483A4%204%200%201%201%2012%2018a4%204%200%201%201-7.967-.517'%20/%3e%3cpath%20d='M6%2018a4%204%200%200%201-2-7.464'%20/%3e%3cpath%20d='M6.003%205.125a4%204%200%200%200-2.526%205.77'%20/%3e%3c/svg%3e",import.meta.url).href,folderIcon:new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20stroke='currentColor'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20%3e%3cpath%20d='M20%2020a2%202%200%200%200%202-2V8a2%202%200%200%200-2-2h-7.9a2%202%200%200%201-1.69-.9L9.6%203.9A2%202%200%200%200%207.93%203H4a2%202%200%200%200-2%202v13a2%202%200%200%200%202%202Z'%20/%3e%3c/svg%3e",import.meta.url).href,folderOpenIcon:new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2024%2024'%20width='48'%20height='48'%20fill='none'%20stroke='%23000000'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20style='opacity:1;'%3e%3cpath%20d='m6%2014l1.5-2.9A2%202%200%200%201%209.24%2010H20a2%202%200%200%201%201.94%202.5l-1.54%206a2%202%200%200%201-1.95%201.5H4a2%202%200%200%201-2-2V5a2%202%200%200%201%202-2h3.9a2%202%200%200%201%201.69.9l.81%201.2a2%202%200%200%200%201.67.9H18a2%202%200%200%201%202%202v2'/%3e%3c/svg%3e",import.meta.url).href,fileIcon:new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20stroke='currentColor'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20%3e%3cpath%20d='M6%2022a2%202%200%200%201-2-2V4a2%202%200%200%201%202-2h8a2.4%202.4%200%200%201%201.704.706l3.588%203.588A2.4%202.4%200%200%201%2020%208v12a2%202%200%200%201-2%202z'%20/%3e%3cpath%20d='M14%202v5a1%201%200%200%200%201%201h5'%20/%3e%3c/svg%3e",import.meta.url).href,apps:{browser:new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20stroke='currentColor'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20%3e%3ccircle%20cx='12'%20cy='12'%20r='10'%20/%3e%3cpath%20d='M12%202a14.5%2014.5%200%200%200%200%2020%2014.5%2014.5%200%200%200%200-20'%20/%3e%3cpath%20d='M2%2012h20'%20/%3e%3c/svg%3e",import.meta.url).href,terminal:new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20stroke='currentColor'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20%3e%3cpath%20d='M18%205a2%202%200%200%201%202%202v8.526a2%202%200%200%200%20.212.897l1.068%202.127a1%201%200%200%201-.9%201.45H3.62a1%201%200%200%201-.9-1.45l1.068-2.127A2%202%200%200%200%204%2015.526V7a2%202%200%200%201%202-2z'%20/%3e%3cpath%20d='M20.054%2015.987H3.946'%20/%3e%3c/svg%3e",import.meta.url).href,command:new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20stroke='currentColor'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20%3e%3cpath%20d='M12%2019h8'%20/%3e%3cpath%20d='m4%2017%206-6-6-6'%20/%3e%3c/svg%3e",import.meta.url).href,python:new URL("data:image/svg+xml,%3csvg%20role='img'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3ePython%3c/title%3e%3cpath%20d='M14.25.18l.9.2.73.26.59.3.45.32.34.34.25.34.16.33.1.3.04.26.02.2-.01.13V8.5l-.05.63-.13.55-.21.46-.26.38-.3.31-.33.25-.35.19-.35.14-.33.1-.3.07-.26.04-.21.02H8.77l-.69.05-.59.14-.5.22-.41.27-.33.32-.27.35-.2.36-.15.37-.1.35-.07.32-.04.27-.02.21v3.06H3.17l-.21-.03-.28-.07-.32-.12-.35-.18-.36-.26-.36-.36-.35-.46-.32-.59-.28-.73-.21-.88-.14-1.05-.05-1.23.06-1.22.16-1.04.24-.87.32-.71.36-.57.4-.44.42-.33.42-.24.4-.16.36-.1.32-.05.24-.01h.16l.06.01h8.16v-.83H6.18l-.01-2.75-.02-.37.05-.34.11-.31.17-.28.25-.26.31-.23.38-.2.44-.18.51-.15.58-.12.64-.1.71-.06.77-.04.84-.02%201.27.05zm-6.3%201.98l-.23.33-.08.41.08.41.23.34.33.22.41.09.41-.09.33-.22.23-.34.08-.41-.08-.41-.23-.33-.33-.22-.41-.09-.41.09zm13.09%203.95l.28.06.32.12.35.18.36.27.36.35.35.47.32.59.28.73.21.88.14%201.04.05%201.23-.06%201.23-.16%201.04-.24.86-.32.71-.36.57-.4.45-.42.33-.42.24-.4.16-.36.09-.32.05-.24.02-.16-.01h-8.22v.82h5.84l.01%202.76.02.36-.05.34-.11.31-.17.29-.25.25-.31.24-.38.2-.44.17-.51.15-.58.13-.64.09-.71.07-.77.04-.84.01-1.27-.04-1.07-.14-.9-.2-.73-.25-.59-.3-.45-.33-.34-.34-.25-.34-.16-.33-.1-.3-.04-.25-.02-.2.01-.13v-5.34l.05-.64.13-.54.21-.46.26-.38.3-.32.33-.24.35-.2.35-.14.33-.1.3-.06.26-.04.21-.02.13-.01h5.84l.69-.05.59-.14.5-.21.41-.28.33-.32.27-.35.2-.36.15-.36.1-.35.07-.32.04-.28.02-.21V6.07h2.09l.14.01zm-6.47%2014.25l-.23.33-.08.41.08.41.23.33.33.23.41.08.41-.08.33-.23.23-.33.08-.41-.08-.41-.23-.33-.33-.23-.41-.08-.41.08z'/%3e%3c/svg%3e",import.meta.url).href,memory:new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20stroke='currentColor'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20%3e%3cpath%20d='M21%209a2.4%202.4%200%200%200-.706-1.706l-3.588-3.588A2.4%202.4%200%200%200%2015%203H5a2%202%200%200%200-2%202v14a2%202%200%200%200%202%202h14a2%202%200%200%200%202-2z'%20/%3e%3cpath%20d='M15%203v5a1%201%200%200%200%201%201h5'%20/%3e%3c/svg%3e",import.meta.url).href,todo:new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20stroke='currentColor'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20%3e%3crect%20width='8'%20height='4'%20x='8'%20y='2'%20rx='1'%20ry='1'%20/%3e%3cpath%20d='M16%204h2a2%202%200%200%201%202%202v14a2%202%200%200%201-2%202H6a2%202%200%200%201-2-2V6a2%202%200%200%201%202-2h2'%20/%3e%3c/svg%3e",import.meta.url).href,subagent:new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20stroke='currentColor'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20%3e%3cpath%20d='M12%208V4H8'%20/%3e%3crect%20width='16'%20height='12'%20x='4'%20y='8'%20rx='2'%20/%3e%3cpath%20d='M2%2014h2'%20/%3e%3cpath%20d='M20%2014h2'%20/%3e%3cpath%20d='M15%2013v2'%20/%3e%3cpath%20d='M9%2013v2'%20/%3e%3c/svg%3e",import.meta.url).href}},ne=T(null),Ve=async()=>{if(await tt(),!r.value)return;const E={screen:r.value,appsGrid:o.value,desktopGrid:l.value,browserWindow:a.value,browserSearchText:c.value,browserStatus:d.value,browserResults:w.value,extractionWindow:g.value,extractionUrl:v.value,extractionState:x.value,extractionSummary:p.value,folderWindow:C.value,folderHeaderText:M.value,folderBody:B.value,editorWindow:F.value,editorHeaderText:I.value,editorBody:k.value,terminalWindow:A.value,terminalHeaderText:N.value,terminalTabs:_.value,terminalTabList:z.value,terminalAddButton:q.value,terminalBody:P.value,commandWindow:W.value,commandTitle:S.value,commandInput:y.value,commandOutput:V.value,pythonWindow:j.value,pythonTitle:Z.value,pythonBody:D.value,pythonInput:L.value,pythonOutput:te.value,readerWindow:se.value,readerTitle:ie.value,readerLines:ae.value,readerOcr:ce.value,memoryWindow:he.value,memoryList:ue.value,memoryStatus:me.value,memoryCount:de.value,memoryTime:fe.value,todoWindow:we.value,todoSummary:ge.value,todoList:be.value,waitWindow:pe.value,waitDisplay:ve.value,waitOverlay:Te.value,waitCountdown:xe.value,desktopMenu:Se.value,folderMenu:Ee.value,fileMenu:Me.value,focusMenu:Ce.value,browserMenu:ke.value,terminalMenu:Le.value,speechBubble:Ie.value,bubbleIconSlot:Pe.value,bubbleTextSlot:Re.value,mousePointer:Be.value},f=new at(E,ye);ne.value=f,e.registerDriver(f),Array.isArray(e.lastTreeSnapshot)&&e.lastTreeSnapshot.length&&f.setDesktopRoots(e.lastTreeSnapshot,{immediate:!0})};return Ye(()=>{Ve()}),Ge(n,E=>{ne.value&&Array.isArray(E)&&ne.value.setDesktopRoots(E,{immediate:!0})},{immediate:!0}),Ze(()=>{var E;e.unregisterDriver(),(E=ne.value)==null||E.destroy(),ne.value=null}),(E,f)=>(Fe(),We("div",ct,[h("div",ht,[h("div",ut,[h("div",mt,[h("div",dt,[f[1]||(f[1]=h("div",{class:"monitor-brand"},"Agent Display Surface",-1)),h("div",ft,[h("div",wt,R(Ae(t)),1),i.value?(Fe(),We("div",gt,[f[0]||(f[0]=h("span",{class:"pulse-dot"},null,-1)),h("span",bt,R(i.value),1)])):Je("",!0)])]),h("div",{class:"monitor-screen",ref_key:"screenEl",ref:r},[h("div",pt,[h("div",vt,[h("div",{class:"apps-grid",ref_key:"appsGrid",ref:o},null,512)]),h("div",Tt,[h("div",{class:"desktop-grid",ref_key:"desktopGrid",ref:l},null,512)])]),h("div",{class:"window browser-window",ref_key:"browserWindow",ref:a},[h("div",xt,[f[2]||(f[2]=h("span",{class:"traffic-dot red"},null,-1)),f[3]||(f[3]=h("span",{class:"traffic-dot yellow"},null,-1)),f[4]||(f[4]=h("span",{class:"traffic-dot green"},null,-1)),h("span",null,R(E.$t("chat.vmBrowserTitle")),1)]),h("div",St,[h("div",Et,[h("span",{ref_key:"browserSearchText",ref:c},null,512)]),h("div",{class:"browser-status",ref_key:"browserStatus",ref:d},R(E.$t("chat.vmBrowserReady")),513),h("div",Mt,[h("ul",{ref_key:"browserResults",ref:w},null,512)])])],512),h("div",{class:"window extraction-window",ref_key:"extractionWindow",ref:g},[h("div",kt,[f[5]||(f[5]=h("span",{class:"traffic-dot red"},null,-1)),f[6]||(f[6]=h("span",{class:"traffic-dot yellow"},null,-1)),f[7]||(f[7]=h("span",{class:"traffic-dot green"},null,-1)),h("span",Lt,R(E.$t("chat.vmWebExtract")),1)]),h("div",Ct,[h("div",{class:"extract-url",ref_key:"extractionUrl",ref:v},null,512),h("div",{class:"extract-status",ref_key:"extractionState",ref:x},R(E.$t("chat.vmExtractWait")),513),h("div",{class:"extract-summary",ref_key:"extractionSummary",ref:p},null,512)])],512),h("div",{class:"window folder-window",ref_key:"folderWindow",ref:C},[h("div",It,[f[8]||(f[8]=h("span",{class:"traffic-dot red"},null,-1)),f[9]||(f[9]=h("span",{class:"traffic-dot yellow"},null,-1)),f[10]||(f[10]=h("span",{class:"traffic-dot green"},null,-1)),h("span",{ref_key:"folderHeaderText",ref:M},"workspace",512)]),h("div",{class:"folder-body",ref_key:"folderBody",ref:B},null,512)],512),h("div",{class:"window editor-window",ref_key:"editorWindow",ref:F},[h("div",Pt,[f[11]||(f[11]=h("span",{class:"traffic-dot red"},null,-1)),f[12]||(f[12]=h("span",{class:"traffic-dot yellow"},null,-1)),f[13]||(f[13]=h("span",{class:"traffic-dot green"},null,-1)),h("span",{ref_key:"editorHeaderText",ref:I},R(E.$t("chat.vmFile")),513)]),h("div",{class:"editor-body",ref_key:"editorBody",ref:k},null,512)],512),h("div",{class:"window terminal-window",ref_key:"terminalWindow",ref:A},[h("div",Rt,[f[14]||(f[14]=h("span",{class:"traffic-dot red"},null,-1)),f[15]||(f[15]=h("span",{class:"traffic-dot yellow"},null,-1)),f[16]||(f[16]=h("span",{class:"traffic-dot green"},null,-1)),h("span",{ref_key:"terminalHeaderText",ref:N},R(E.$t("chat.vmTerminal")),513)]),h("div",Bt,[h("div",{class:"terminal-tabs",ref_key:"terminalTabs",ref:_},[h("div",{class:"terminal-tab-list",ref_key:"terminalTabList",ref:z},null,512),h("button",{class:"terminal-tab add-tab",ref_key:"terminalAddButton",ref:q},"+",512)],512),h("div",{class:"terminal-output",ref_key:"terminalBody",ref:P},null,512)])],512),h("div",{class:"window command-window",ref_key:"commandWindow",ref:W},[h("div",Ft,[f[17]||(f[17]=h("span",{class:"traffic-dot red"},null,-1)),f[18]||(f[18]=h("span",{class:"traffic-dot yellow"},null,-1)),f[19]||(f[19]=h("span",{class:"traffic-dot green"},null,-1)),h("span",{ref_key:"commandTitle",ref:S},R(E.$t("chat.vmCommandLine")),513)]),h("div",Wt,[h("div",{class:"command-input",ref_key:"commandInput",ref:y},null,512),h("div",{class:"command-output",ref_key:"commandOutput",ref:V},null,512)])],512),h("div",{class:"window python-window",ref_key:"pythonWindow",ref:j},[h("div",At,[f[20]||(f[20]=h("span",{class:"traffic-dot red"},null,-1)),f[21]||(f[21]=h("span",{class:"traffic-dot yellow"},null,-1)),f[22]||(f[22]=h("span",{class:"traffic-dot green"},null,-1)),h("span",{ref_key:"pythonTitle",ref:Z},"Python",512)]),h("div",{class:"python-body",ref_key:"pythonBody",ref:D},[h("div",{class:"python-input",ref_key:"pythonInput",ref:L},null,512),h("div",{class:"python-output",ref_key:"pythonOutput",ref:te},null,512)],512)],512),h("div",{class:"window reader-window",ref_key:"readerWindow",ref:se},[h("div",Dt,[f[23]||(f[23]=h("span",{class:"traffic-dot red"},null,-1)),f[24]||(f[24]=h("span",{class:"traffic-dot yellow"},null,-1)),f[25]||(f[25]=h("span",{class:"traffic-dot green"},null,-1)),h("span",{ref_key:"readerTitle",ref:ie},R(E.$t("chat.vmReaderTitle")),513)]),h("div",_t,[h("div",{class:"reading-lines",ref_key:"readerLines",ref:ae},null,512),h("div",{class:"ocr-panel",ref_key:"readerOcr",ref:ce},null,512)])],512),h("div",{class:"window memory-window",ref_key:"memoryWindow",ref:he},[h("div",Ht,[f[26]||(f[26]=h("span",{class:"traffic-dot red"},null,-1)),f[27]||(f[27]=h("span",{class:"traffic-dot yellow"},null,-1)),f[28]||(f[28]=h("span",{class:"traffic-dot green"},null,-1)),h("span",Ot,R(E.$t("chat.vmMemory")),1)]),h("div",Nt,[h("div",{class:"memory-list",ref_key:"memoryList",ref:ue},null,512)]),h("div",zt,[h("span",null,[h("strong",{ref_key:"memoryCount",ref:de},null,512)]),h("span",null,[h("strong",{ref_key:"memoryTime",ref:fe},null,512)]),h("span",{ref_key:"memoryStatus",ref:me},null,512)])],512),h("div",{class:"window todo-window",ref_key:"todoWindow",ref:we},[h("div",$t,[f[29]||(f[29]=h("span",{class:"traffic-dot red"},null,-1)),f[30]||(f[30]=h("span",{class:"traffic-dot yellow"},null,-1)),f[31]||(f[31]=h("span",{class:"traffic-dot green"},null,-1)),h("span",yt,R(E.$t("chat.vmTodo")),1)]),h("div",Vt,[h("div",{class:"todo-summary",ref_key:"todoSummary",ref:ge},null,512),h("div",{class:"todo-progress",ref_key:"todoList",ref:be},null,512)])],512),h("div",{class:"window wait-window",ref_key:"waitWindow",ref:pe},[h("div",Ut,[f[32]||(f[32]=h("span",{class:"traffic-dot red"},null,-1)),f[33]||(f[33]=h("span",{class:"traffic-dot yellow"},null,-1)),f[34]||(f[34]=h("span",{class:"traffic-dot green"},null,-1)),h("span",qt,R(E.$t("chat.vmWait")),1)]),h("div",jt,[h("div",{class:"flip-clock",ref_key:"waitDisplay",ref:ve},[...f[35]||(f[35]=[Qe('
00
00
:
00
00
',5)])],512)])],512),h("div",{class:"context-menu",ref_key:"desktopMenu",ref:Se},[h("button",Kt,R(E.$t("chat.vmNewFile")),1),h("button",Xt,R(E.$t("chat.vmNewFolder")),1),h("button",Yt,R(E.$t("chat.vmWait")),1)],512),h("div",{class:"context-menu",ref_key:"folderMenu",ref:Ee},[h("button",Gt,R(E.$t("chat.vmNewFile")),1),h("button",Zt,R(E.$t("chat.vmNewFolder")),1)],512),h("div",{class:"context-menu",ref_key:"fileMenu",ref:Me},[h("button",Jt,R(E.$t("chat.vmReadFile")),1),h("button",Qt,R(E.$t("chat.vmEditFile")),1),h("button",es,R(E.$t("chat.vmRename")),1),h("button",ts,R(E.$t("chat.vmDeleteFile")),1)],512),h("div",{class:"context-menu",ref_key:"focusMenu",ref:Ce},[h("button",ss,R(E.$t("chat.vmFocusFile")),1),h("button",ns,R(E.$t("chat.vmUnfocus")),1)],512),h("div",{class:"context-menu",ref_key:"browserMenu",ref:ke},[h("button",is,R(E.$t("chat.vmSaveWebpage")),1)],512),h("div",{class:"context-menu",ref_key:"terminalMenu",ref:Le},[h("button",rs,R(E.$t("chat.vmSaveSnapshot")),1),h("button",os,R(E.$t("chat.vmResetTerminal")),1),h("button",ls,R(E.$t("chat.vmCloseTerminal")),1)],512),h("div",{class:"speech-bubble",ref_key:"bubbleEl",ref:Ie},[h("div",{class:"bubble-icon-slot",ref_key:"bubbleIconSlot",ref:Pe},null,512),h("div",{class:"bubble-text-slot",ref_key:"bubbleTextSlot",ref:Re},null,512)],512),h("div",{class:"mouse-pointer",ref_key:"mousePointer",ref:Be},[h("img",{src:Ae($e),alt:"pointer"},null,8,as)],512),h("div",{class:"wait-overlay",ref_key:"waitOverlay",ref:Te},[f[36]||(f[36]=h("div",{class:"z z-1"},"Z",-1)),f[37]||(f[37]=h("div",{class:"z z-2"},"Z",-1)),f[38]||(f[38]=h("div",{class:"z z-3"},"Z",-1)),f[39]||(f[39]=h("div",{class:"z z-4"},"Z",-1)),h("div",{class:"wait-countdown",ref_key:"waitCountdown",ref:xe},"5s",512)],512)],512)]),f[40]||(f[40]=h("div",{class:"monitor-stand"},null,-1))])])]))}});export{ws as default};