aicodeman 1.26.2 → 1.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/cli-registry/stock.d.ts.map +1 -1
- package/dist/config/cli-registry/stock.js +13 -2
- package/dist/config/cli-registry/stock.js.map +1 -1
- package/dist/session-cli-builder.d.ts.map +1 -1
- package/dist/session-cli-builder.js +31 -5
- package/dist/session-cli-builder.js.map +1 -1
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +19 -0
- package/dist/session.js.map +1 -1
- package/dist/tmux-manager.d.ts +3 -0
- package/dist/tmux-manager.d.ts.map +1 -1
- package/dist/tmux-manager.js +65 -8
- package/dist/tmux-manager.js.map +1 -1
- package/dist/types/common.d.ts +2 -0
- package/dist/types/common.d.ts.map +1 -1
- package/dist/utils/omp-session-resolver.d.ts +14 -0
- package/dist/utils/omp-session-resolver.d.ts.map +1 -1
- package/dist/utils/omp-session-resolver.js +21 -2
- package/dist/utils/omp-session-resolver.js.map +1 -1
- package/dist/web/public/admin-ui.js.gz +0 -0
- package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
- package/dist/web/public/app.78bf0bf8.js +38 -0
- package/dist/web/public/app.78bf0bf8.js.br +0 -0
- package/dist/web/public/app.78bf0bf8.js.gz +0 -0
- package/dist/web/public/approvals-ui.js.gz +0 -0
- package/dist/web/public/{constants.e6d48776.js → constants.9cd8ed69.js} +7 -1
- package/dist/web/public/constants.9cd8ed69.js.br +0 -0
- package/dist/web/public/constants.9cd8ed69.js.gz +0 -0
- package/dist/web/public/cron-ui.js.gz +0 -0
- package/dist/web/public/entrance-animations.js.gz +0 -0
- package/dist/web/public/home-sessions.js.gz +0 -0
- package/dist/web/public/i18n.9db8c4e0.js.gz +0 -0
- package/dist/web/public/image-input.cd4b97c4.js.gz +0 -0
- package/dist/web/public/index.html +22 -10
- package/dist/web/public/index.html.br +0 -0
- package/dist/web/public/index.html.gz +0 -0
- package/dist/web/public/input-cjk.87f14251.js.gz +0 -0
- package/dist/web/public/{keyboard-accessory.daf18302.js → keyboard-accessory.1d0dda9b.js} +182 -13
- package/dist/web/public/keyboard-accessory.1d0dda9b.js.br +0 -0
- package/dist/web/public/keyboard-accessory.1d0dda9b.js.gz +0 -0
- package/dist/web/public/mobile-handlers.2e9c214a.js.gz +0 -0
- package/dist/web/public/mobile-overview.js.gz +0 -0
- package/dist/web/public/mobile.65176832.css.gz +0 -0
- package/dist/web/public/notification-manager.36ea4624.js.gz +0 -0
- package/dist/web/public/orchestrator-panel.js.gz +0 -0
- package/dist/web/public/{panels-ui.9eb5b235.js → panels-ui.4e9ea307.js} +1 -1
- package/dist/web/public/panels-ui.4e9ea307.js.br +0 -0
- package/dist/web/public/panels-ui.4e9ea307.js.gz +0 -0
- package/dist/web/public/ralph-panel.6de2d0f8.js.gz +0 -0
- package/dist/web/public/ralph-wizard.13a1831e.js.gz +0 -0
- package/dist/web/public/readmymind-ui.js.gz +0 -0
- package/dist/web/public/respawn-ui.ff0dae4c.js.gz +0 -0
- package/dist/web/public/sanitize-html.bc7078d6.js.gz +0 -0
- package/dist/web/public/session-lineage.js.gz +0 -0
- package/dist/web/public/session-ui.cd222710.js.gz +0 -0
- package/dist/web/public/settings-ui.c175db9a.js +67 -0
- package/dist/web/public/settings-ui.c175db9a.js.br +0 -0
- package/dist/web/public/settings-ui.c175db9a.js.gz +0 -0
- package/dist/web/public/{styles.89069bbc.css → styles.0d41361c.css} +1 -1
- package/dist/web/public/styles.0d41361c.css.br +0 -0
- package/dist/web/public/styles.0d41361c.css.gz +0 -0
- package/dist/web/public/subagent-windows.e6ca799f.js.gz +0 -0
- package/dist/web/public/sw.js.gz +0 -0
- package/dist/web/public/tab-rail-resize.42c24949.js.gz +0 -0
- package/dist/web/public/terminal-keycode229-recovery.6ea8fe37.js +1 -0
- package/dist/web/public/terminal-keycode229-recovery.6ea8fe37.js.br +0 -0
- package/dist/web/public/terminal-keycode229-recovery.6ea8fe37.js.gz +0 -0
- package/dist/web/public/terminal-ui.89e4eb1a.js +2 -0
- package/dist/web/public/terminal-ui.89e4eb1a.js.br +0 -0
- package/dist/web/public/terminal-ui.89e4eb1a.js.gz +0 -0
- package/dist/web/public/ultracode-panel.js.gz +0 -0
- package/dist/web/public/ultracode-windows.js.gz +0 -0
- package/dist/web/public/upload.html.gz +0 -0
- package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
- package/dist/web/public/vendor/marked.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-predictive-echo.bd6882b8.js.gz +0 -0
- package/dist/web/public/vendor/xterm-zerolag-input.6fee72f2.js.gz +0 -0
- package/dist/web/public/vendor/xterm.css.gz +0 -0
- package/dist/web/public/vendor/xterm.min.js.gz +0 -0
- package/dist/web/public/voice-input.c4b51eb6.js.gz +0 -0
- package/dist/web/public/voice-pcm-worklet.js.gz +0 -0
- package/dist/web/public/webview-tabs.js +199 -9
- package/dist/web/public/webview-tabs.js.br +0 -0
- package/dist/web/public/webview-tabs.js.gz +0 -0
- package/dist/web/response-viewer-transcript.d.ts +20 -0
- package/dist/web/response-viewer-transcript.d.ts.map +1 -1
- package/dist/web/response-viewer-transcript.js +27 -0
- package/dist/web/response-viewer-transcript.js.map +1 -1
- package/dist/web/routes/file-routes.d.ts.map +1 -1
- package/dist/web/routes/file-routes.js +11 -3
- package/dist/web/routes/file-routes.js.map +1 -1
- package/dist/web/routes/session-routes.d.ts.map +1 -1
- package/dist/web/routes/session-routes.js +16 -4
- package/dist/web/routes/session-routes.js.map +1 -1
- package/dist/web/schemas.d.ts +4 -0
- package/dist/web/schemas.d.ts.map +1 -1
- package/dist/web/schemas.js +9 -0
- package/dist/web/schemas.js.map +1 -1
- package/package.json +1 -1
- package/skills/codeman/reference/endpoints.md +1 -0
- package/dist/web/public/app.c4dbfcfb.js +0 -38
- package/dist/web/public/app.c4dbfcfb.js.br +0 -0
- package/dist/web/public/app.c4dbfcfb.js.gz +0 -0
- package/dist/web/public/constants.e6d48776.js.br +0 -0
- package/dist/web/public/constants.e6d48776.js.gz +0 -0
- package/dist/web/public/keyboard-accessory.daf18302.js.br +0 -0
- package/dist/web/public/keyboard-accessory.daf18302.js.gz +0 -0
- package/dist/web/public/panels-ui.9eb5b235.js.br +0 -0
- package/dist/web/public/panels-ui.9eb5b235.js.gz +0 -0
- package/dist/web/public/settings-ui.554f9cdd.js +0 -67
- package/dist/web/public/settings-ui.554f9cdd.js.br +0 -0
- package/dist/web/public/settings-ui.554f9cdd.js.gz +0 -0
- package/dist/web/public/styles.89069bbc.css.br +0 -0
- package/dist/web/public/styles.89069bbc.css.gz +0 -0
- package/dist/web/public/terminal-ui.1547ce5e.js +0 -2
- package/dist/web/public/terminal-ui.1547ce5e.js.br +0 -0
- package/dist/web/public/terminal-ui.1547ce5e.js.gz +0 -0
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
"use strict";Object.assign(CodemanApp.prototype,{_onHookIdlePrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this._notifySession(e.sessionId,"warning","hook-idle","Waiting for Input",e.message||"Claude is idle and waiting for a prompt")},_onHookPermissionPrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const t=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this._notifySession(e.sessionId,"critical","hook-permission","Permission Required",t||"Claude needs tool approval to continue")},_onHookElicitationDialog(e){e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this._notifySession(e.sessionId,"critical","hook-elicitation","Question Asked",e.question||"Claude is asking a question and waiting for your answer")},_onHookElicitationComplete(e){e.sessionId&&(this.clearPendingHooks(e.sessionId,"elicitation_dialog"),this.clearPendingHooks(e.sessionId,"permission_prompt"))},_onHookElicitationResponse(e){this._onHookElicitationComplete(e)},_onHookStop(e){e.sessionId&&this.clearPendingHooks(e.sessionId),this._notifySession(e.sessionId,"info","hook-stop","Response Complete",e.reason||"Claude has finished responding")},_onHookAgentWorking(e){e.sessionId&&(this.clearPendingHooks(e.sessionId,"elicitation_dialog"),this.clearPendingHooks(e.sessionId,"permission_prompt"),this.clearPendingHooks(e.sessionId,"idle_prompt"))},_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"warning","hook-teammate-idle","Teammate Idle",`A teammate is idle in ${t?.name||e.sessionId}`)},_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"info","hook-task-completed","Task Completed",`A team task completed in ${t?.name||e.sessionId}`)},_onTunnelStarted(e){console.log("[Tunnel] Started:",e.url),this._tunnelUrl=e.url,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(e.url),this._updateTunnelIndicator(!0),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,e.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,e.url),this.showToast(`Tunnel active: ${e.url}`,"success"),this.showTunnelQR())},_onTunnelStopped(){console.log("[Tunnel] Stopped"),this._tunnelUrl=null,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1),this.closeTunnelPanel(),this.closeTunnelQR()},_onTunnelProgress(e){console.log("[Tunnel] Progress:",e.message);const t=document.getElementById("tunnelConnectingToast");t&&(t.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`);const n=document.getElementById("welcomeTunnelBtn");n?.classList.contains("connecting")&&(n.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`)},_onTunnelError(e){console.warn("[Tunnel] Error:",e.message),this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${e.message}`,"error");const t=document.getElementById("welcomeTunnelBtn");t&&(t.disabled=!1,t.classList.remove("connecting"))},_onTunnelQrRotated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrRegenerated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrAuthUsed(e){const n=(e.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${n}, ${e.ip}). Not you?`,"warning",{duration:1e4,action:{label:"Revoke All",onClick:()=>{fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(()=>this.showToast("All sessions revoked","success")).catch(()=>this.showToast("Failed to revoke sessions","error"))}}})},registerServiceWorker(){if(!("serviceWorker"in navigator))return;const e=window.CodemanBase?.base||"";navigator.serviceWorker.register(e+"/sw.js",{scope:e+"/"}).then(t=>{this._swRegistration=t,navigator.serviceWorker.addEventListener("message",n=>{if(n.data?.type==="notification-click"){const{sessionId:s,action:o,approvalId:i}=n.data;o?this.handleNotificationAction?.(o,i,s):s&&this.sessions.has(s)&&this.selectSession(s),window.focus()}}),t.pushManager.getSubscription().then(n=>{n&&(this._pushSubscription=n,this._updatePushUI(!0))})}).catch(()=>{})},async subscribeToPush(){if(!this._swRegistration){this.showToast("Service worker not available. HTTPS or localhost required.","error");return}try{const e=await this._apiJson("/api/push/vapid-key");if(!e)throw new Error("Failed to get VAPID key");const t=urlBase64ToUint8Array(e.publicKey),n=await this._swRegistration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),s=n.toJSON(),o=await this._apiJson("/api/push/subscribe",{method:"POST",body:{endpoint:s.endpoint,keys:s.keys,userAgent:navigator.userAgent,pushPreferences:this._buildPushPreferences()}});if(!o)throw new Error("Failed to register subscription");this._pushSubscription=n,this._pushSubscriptionId=o.id,localStorage.setItem("codeman-push-subscription-id",o.id),this._updatePushUI(!0),this.showToast("Push notifications enabled","success")}catch(e){this.showToast("Push subscription failed: "+(e.message||e),"error")}},async unsubscribeFromPush(){try{this._pushSubscription&&await this._pushSubscription.unsubscribe();const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");e&&await fetch(`/api/push/subscribe/${e}`,{method:"DELETE"}).catch(()=>{}),this._pushSubscription=null,this._pushSubscriptionId=null,localStorage.removeItem("codeman-push-subscription-id"),this._updatePushUI(!1),this.showToast("Push notifications disabled","success")}catch(e){this.showToast("Failed to unsubscribe: "+(e.message||e),"error")}},async togglePushSubscription(){this._pushSubscription?await this.unsubscribeFromPush():await this.subscribeToPush()},async _syncPushPreferences(){const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");if(e)try{await fetch(`/api/push/subscribe/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pushPreferences:this._buildPushPreferences()})})}catch{}},_buildPushPreferences(){const e={},t={"hook:permission_prompt":"eventPermissionPush","hook:elicitation_dialog":"eventQuestionPush","hook:idle_prompt":"eventIdlePush","hook:stop":"eventStopPush","respawn:blocked":"eventRespawnPush","session:ralphCompletionDetected":"eventRalphPush"};for(const[n,s]of Object.entries(t)){const o=document.getElementById(s);e[n]=o?o.checked:!0}return e["session:error"]=!0,e},_updatePushUI(e){const t=document.getElementById("pushSubscribeBtn"),n=document.getElementById("pushSubscriptionStatus");t&&(t.textContent=e?"Unsubscribe":"Subscribe"),n&&(n.textContent=e?"active":"off",n.classList.remove("granted","denied"),e&&n.classList.add("granted"))},openAppSettings(){const e=this.loadAppSettingsFromStorage();document.getElementById("appSettingsDisplayName").value=e.displayName||"Codeman",document.getElementById("appSettingsLanguage").value=e.language==="zh-CN"?"zh-CN":"en",document.getElementById("appSettingsClaudeMdPath").value=e.defaultClaudeMdPath||"",document.getElementById("appSettingsDefaultDir").value=e.defaultWorkingDir||"";const t=this.getDefaultSettings();document.getElementById("appSettingsRalphEnabled").checked=e.ralphTrackerEnabled??t.ralphTrackerEnabled??!1,document.getElementById("appSettingsShowFontControls").checked=e.showFontControls??t.showFontControls??!1,document.getElementById("appSettingsShowSystemStats").checked=e.showSystemStats??t.showSystemStats??!0,document.getElementById("appSettingsShowLifecycleLog").checked=e.showLifecycleLog??t.showLifecycleLog??!1,document.getElementById("appSettingsShowResponseViewer").checked=e.showResponseViewer??t.showResponseViewer??!1,document.getElementById("appSettingsShowFileViewerButton").checked=e.showFileViewerButton??t.showFileViewerButton??!0,document.getElementById("appSettingsShowAttachmentsButton").checked=e.showAttachmentsButton??t.showAttachmentsButton??!1,document.getElementById("appSettingsSkin").value=e.skin??t.skin??"daylight-blue",this._syncEntranceAnimSetting?.(),document.getElementById("appSettingsWebglRenderer").checked=e.webglRendererEnabled??t.webglRendererEnabled??!0;const n=document.getElementById("appSettingsWebglRendererItem");n&&(n.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsShowMonitor").checked=e.showMonitor??t.showMonitor??!1,document.getElementById("appSettingsShowProjectInsights").checked=e.showProjectInsights??t.showProjectInsights??!1,document.getElementById("appSettingsShowFileBrowser").checked=e.showFileBrowser??t.showFileBrowser??!1,document.getElementById("appSettingsShowSubagents").checked=e.showSubagents??t.showSubagents??!1,document.getElementById("appSettingsShowUltracodeAgents").checked=e.showUltracodeAgents??t.showUltracodeAgents??!1,document.getElementById("appSettingsApprovalsInbox").checked=e.approvalsInboxEnabled===!0,document.getElementById("appSettingsReadMyMind").checked=e.readMyMindEnabled===!0,document.getElementById("appSettingsUltracodeFloatingWindows").checked=e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1,document.getElementById("appSettingsShowMultiMonitorButton").checked=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,document.getElementById("appSettingsShowPlanUsageLimits").checked=this.planUsageChipEnabled(e),document.getElementById("appSettingsShowRedrawButton").checked=e.showRedrawButton??t.showRedrawButton??!1,document.getElementById("appSettingsLineageLines").checked=e.sessionLineageLines??t.sessionLineageLines??!0;const s=document.getElementById("appSettingsLineageLinesItem");s&&(s.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsMobileOverview").checked=e.mobileOverviewEnabled??t.mobileOverviewEnabled??!1;const o=document.getElementById("appSettingsMobileOverviewItem");o&&(o.style.display=MobileDetection.getDeviceType()==="mobile"?"":"none"),document.getElementById("appSettingsShowSessionButton").checked=e.showSessionButton??t.showSessionButton??!1,document.getElementById("appSettingsShowAwayDigestButton").checked=e.showAwayDigestButton??t.showAwayDigestButton??!1,document.getElementById("appSettingsShowCronButton").checked=e.showCronButton??t.showCronButton??!1;const i=document.getElementById("appSettingsGestureControlItem");i&&(i.style.display=window.__codemanGestureAvailable?"":"none"),document.getElementById("appSettingsGestureControl").checked=e.gestureControlEnabled??t.gestureControlEnabled??!1,document.getElementById("appSettingsSubagentTracking").checked=e.subagentTrackingEnabled??t.subagentTrackingEnabled??!0,document.getElementById("appSettingsSubagentActiveTabOnly").checked=e.subagentActiveTabOnly??t.subagentActiveTabOnly??!0,document.getElementById("appSettingsImageWatcherEnabled").checked=e.imageWatcherEnabled??t.imageWatcherEnabled??!1,document.getElementById("appSettingsTunnelEnabled").checked=e.tunnelEnabled??!1,this.loadTunnelStatus(),document.getElementById("appSettingsLocalEcho").checked=e.localEchoEnabled??MobileDetection.isTouchDevice(),document.getElementById("appSettingsAutoCopySelection").checked=e.autoCopySelection===!0,document.getElementById("appSettingsTerminalFont").value=e.terminalFontFamily||"",document.getElementById("appSettingsTerminalWheelLocal").checked=e.terminalWheelLocalScrollback??t.terminalWheelLocalScrollback??!1,document.getElementById("appSettingsCjkInput").checked=e.cjkInputEnabled??t.cjkInputEnabled??!1,document.getElementById("appSettingsExtendedKeyboardBar").checked=e.extendedKeyboardBar??!1,document.getElementById("appSettingsTabTwoRows").checked=e.tabTwoRows??t.tabTwoRows??!1,document.getElementById("appSettingsTabOrientation").value=e.tabOrientation??t.tabOrientation??"horizontal";const a=window.CodemanTabRail?.resolveWidth({width:e.tabRailWidth??this._defaultTabRailWidth?.()??t.tabRailWidth??256})??256;this.syncTabRailWidthSetting?.(a),document.getElementById("appSettingsTabRailDetail").value=e.tabRailDetail??t.tabRailDetail??"rich",document.getElementById("appSettingsShowTabDetachButton").checked=e.showTabDetachButton??t.showTabDetachButton??!1,document.getElementById("appSettingsSessionListLayout").value=e.sessionListLayout??t.sessionListLayout??"header";const l=this.resolveSessionSidebarFontSize(e.sessionSidebarFontSize??t.sessionSidebarFontSize);document.getElementById("appSettingsSessionSidebarFontSize").value=String(l),document.getElementById("appSettingsSessionSidebarFontSizeValue").textContent=`${l} px`;const c=document.getElementById("appSettingsClaudeMode"),d=document.getElementById("allowedToolsRow");c.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",d.style.display=c.value==="allowedTools"?"":"none",c.onchange=()=>{d.style.display=c.value==="allowedTools"?"":"none"},document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked=e.codexDangerouslyBypassApprovals??!1,document.getElementById("appSettingsCodexAnimations").checked=e.codexAnimationsEnabled??!1,this._applyCodexSettingsVisibility(),document.getElementById("appSettingsAgentTeams").checked=e.agentTeamsEnabled??!1,document.getElementById("appSettingsAgentSkill").checked=e.agentSkillEnabled??!1,document.getElementById("appSettingsWorkspaceHooks").checked=e.workspaceHooksEnabled!==!1,document.getElementById("appSettingsClaudeModel").value=e.claudeModel??"",document.getElementById("appSettingsOpusContext1m").checked=e.opusContext1mEnabled??!1,document.getElementById("appSettingsRemoteAutoReconnect").checked=e.remoteAutoReconnect??!0,document.getElementById("appSettingsThinkingEffort").value=e.thinkingEffort??"";const r=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=r.enabled??!1,document.getElementById("appSettingsNiceValue").value=r.niceValue??10,this.loadModelConfigForSettings();const u=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=u.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=u.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=u.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((u.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!u.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!u.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!u.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const p=u.eventTypes||{},h=p.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=h.enabled??!0,document.getElementById("eventPermissionBrowser").checked=h.browser??!0,document.getElementById("eventPermissionPush").checked=h.push??!1,document.getElementById("eventPermissionAudio").checked=h.audio??!0;const m=p.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=m.enabled??!0,document.getElementById("eventQuestionBrowser").checked=m.browser??!0,document.getElementById("eventQuestionPush").checked=m.push??!1,document.getElementById("eventQuestionAudio").checked=m.audio??!0;const g=p.idle_prompt||{};document.getElementById("eventIdleEnabled").checked=g.enabled??!0,document.getElementById("eventIdleBrowser").checked=g.browser??!0,document.getElementById("eventIdlePush").checked=g.push??!1,document.getElementById("eventIdleAudio").checked=g.audio??!1;const S=p.stop||{};document.getElementById("eventStopEnabled").checked=S.enabled??!1,document.getElementById("eventStopBrowser").checked=S.browser??!1,document.getElementById("eventStopPush").checked=S.push??!1,document.getElementById("eventStopAudio").checked=S.audio??!1;const b=p.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=b.enabled??!0,document.getElementById("eventRespawnBrowser").checked=b.browser??!1,document.getElementById("eventRespawnPush").checked=b.push??!1,document.getElementById("eventRespawnAudio").checked=b.audio??!1;const E=p.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=E.enabled??!0,document.getElementById("eventRalphBrowser").checked=E.browser??!0,document.getElementById("eventRalphPush").checked=E.push??!1,document.getElementById("eventRalphAudio").checked=E.audio??!0;const w=p.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=w.enabled??!1,document.getElementById("eventSubagentBrowser").checked=w.browser??!1,document.getElementById("eventSubagentPush").checked=w.push??!1,document.getElementById("eventSubagentAudio").checked=w.audio??!1;const v=document.getElementById("notifPermissionStatus");if(v&&typeof Notification<"u"){const f=Notification.permission;v.textContent=f==="granted"?"\u2713":f==="denied"?"\u2717":"?",v.classList.remove("granted","denied"),f==="granted"?v.classList.add("granted"):f==="denied"&&v.classList.add("denied")}const y=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=y.apiKey||"",document.getElementById("voiceLanguage").value=y.language||"en-US",document.getElementById("voiceKeyterms").value=y.keyterms||DEFAULT_VOICE_KEYTERMS,document.getElementById("voiceInsertMode").value=y.insertMode||"direct",document.getElementById("voiceProvider").value=y.provider||"auto",document.getElementById("appSettingsClaudeVoice").checked=e.claudeVoiceEnabled??!1;const B=document.getElementById("voiceDeepgramKey");B.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show",this._renderVoiceProviderStatus(),VoiceInput.refreshClaudeStatus().then(()=>this._renderVoiceProviderStatus()),this._initUpdatesSection(),this._initSettingsNav(),this._syncSettingsChips(),this._syncModelCards(),this._syncEffortSegment(),this.switchSettingsTab("settings-updates");const I=document.getElementById("appSettingsModal");I.classList.add("active"),this.activeFocusTrap=new FocusTrap(I),this.activeFocusTrap.activate()},_applyCodexSettingsVisibility(){const e=document.getElementById("appSettingsCodexGroup");e&&(e.style.display=window.__codemanCliAvailable?.codex===!0?"":"none")},switchSettingsTab(e){e==="settings-shortcuts"&&this.renderShortcutSettingsList?.();const t=document.getElementById("appSettingsDoc"),n=document.getElementById(e);if(t&&n&&typeof n.offsetTop=="number"){const s=document.getElementById("appSettingsJump"),o=s&&s.offsetParent?s.offsetHeight+16:6;t.scrollTop=Math.max(0,n.offsetTop-o)}this._setActiveSettingsSection(e)},_setActiveSettingsSection(e){const t=document.getElementById("appSettingsModal");if(!t||typeof t.querySelectorAll!="function")return;let n=null;t.querySelectorAll(".set-rail-item").forEach(a=>{const l=a.dataset.section===e;a.classList.toggle("active",l),l&&(n=a)}),t.querySelectorAll(".set-jump-row").forEach(a=>{a.classList.toggle("active",a.dataset.section===e)});const s=document.getElementById("appSettingsJump")?.querySelector(".set-jump-label");s&&n&&(s.textContent=n.textContent.trim());const o=document.getElementById("appSettingsJump")?.querySelector(".set-jump-ico"),i=n?.querySelector("svg");o&&i&&(o.innerHTML=i.innerHTML)},_initSettingsNav(){const e=document.getElementById("appSettingsModal"),t=document.getElementById("appSettingsDoc");if(!e||!t||typeof e.querySelectorAll!="function"||(this._buildModelCards(),this._buildEffortSegment(),this._buildSettingsJumpMenu(),e.dataset.navReady==="1"))return;e.dataset.navReady="1",e.querySelector(".set-rail-items")?.addEventListener("click",i=>{const a=i.target.closest?.(".set-rail-item");a?.dataset.section&&this.switchSettingsTab(a.dataset.section)}),document.getElementById("appSettingsJumpMenu")?.addEventListener("click",i=>{const a=i.target.closest?.(".set-jump-row");a?.dataset.section&&(this._toggleSettingsJump(!1),this.switchSettingsTab(a.dataset.section))}),document.getElementById("appSettingsJump")?.addEventListener("click",()=>this._toggleSettingsJump()),document.getElementById("appSettingsJumpVeil")?.addEventListener("click",()=>this._toggleSettingsJump(!1)),t.addEventListener("scroll",()=>{this._settingsSpyQueued||(this._settingsSpyQueued=!0,requestAnimationFrame(()=>{this._settingsSpyQueued=!1;const i=[...t.querySelectorAll(".set-section")].filter(l=>l.offsetParent!==null);if(!i.length)return;let a=i[0].id;for(const l of i)l.offsetTop-t.scrollTop<=140&&(a=l.id);this._setActiveSettingsSection(a)}))});const n=document.getElementById("appSettingsSearch");n?.addEventListener("input",()=>this._filterSettings(n.value)),e.querySelectorAll(".set-chip input").forEach(i=>{i.addEventListener("change",()=>this._syncSettingsChips())});const s=e.querySelector(".set-group-head-toggle"),o=s?.closest(".set-group-advanced");if(s&&o){const i=()=>{const a=o.classList.toggle("open");s.setAttribute("aria-expanded",a?"true":"false")};s.addEventListener("click",i),s.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),i())})}document.getElementById("appSettingsOpusContext1m")?.addEventListener("change",()=>this._applyModelSelection())},_buildSettingsJumpMenu(){const e=document.getElementById("appSettingsModal"),t=document.getElementById("appSettingsJumpMenu");!e||!t||(t.innerHTML="",e.querySelectorAll(".set-rail-item").forEach(n=>{const s=document.createElement("button");s.type="button",s.className="set-jump-row",s.dataset.section=n.dataset.section,s.innerHTML=n.innerHTML;const o=document.getElementById(n.dataset.section),i=o?o.querySelectorAll("input, select").length:0;if(i){const a=document.createElement("span");a.className="set-jump-count",a.textContent=String(i),s.appendChild(a)}t.appendChild(s)}))},_toggleSettingsJump(e){const t=document.getElementById("appSettingsModal");if(!t)return;const n=e===void 0?!t.classList.contains("jump-open"):e;t.classList.toggle("jump-open",n),document.getElementById("appSettingsJump")?.setAttribute("aria-expanded",n?"true":"false")},_syncSettingsChips(){document.querySelectorAll("#appSettingsModal .set-chip, #sessionOptionsModal .set-chip").forEach(e=>{e.classList.toggle("is-on",!!e.querySelector("input")?.checked)}),this._syncLayoutPreview()},_syncLayoutPreview(){const e=document.getElementById("appSettingsModal");if(!e||typeof e.querySelectorAll!="function")return;const t={header:document.getElementById("appSettingsPreviewHeader"),panel:document.getElementById("appSettingsPreviewPanels"),toolbar:document.getElementById("appSettingsPreviewToolbar"),float:document.getElementById("appSettingsPreviewFloats")};if(!t.header)return;Object.values(t).forEach(i=>{i&&(i.innerHTML="")});const n=[...e.querySelectorAll(".set-chip[data-preview]")].filter(i=>i.querySelector("input")?.checked).sort((i,a)=>(Number(i.dataset.previewOrder)||0)-(Number(a.dataset.previewOrder)||0));let s=0;for(const i of n){const a=i.dataset.preview,l=t[a];if(!l)continue;const c=i.querySelectorAll("span"),d=(c[c.length-1]?.textContent||"").trim(),r=document.createElement("span");if(r.title=d,a==="header"){const u=i.dataset.previewText;r.className=u?"set-preview-chip":"set-preview-btn",u?r.textContent=u:this._appendPreviewIcon(r,i)}else{r.className=`set-preview-${a}`,this._appendPreviewIcon(r,i);const u=document.createElement("span");u.textContent=d,r.appendChild(u)}l.appendChild(r),s++}const o=document.getElementById("appSettingsPreviewEmpty");o&&(o.hidden=s>0)},_appendPreviewIcon(e,t){const n=t.querySelector(".set-chip-ico");if(!n)return;const s=n.cloneNode(!0);s.classList.remove("set-chip-ico"),s.classList.add("set-preview-ico"),e.appendChild(s)},_buildModelCards(){const e=document.getElementById("appSettingsClaudeModel"),t=document.getElementById("appSettingsModelCards");!e||!t||t.dataset.built==="1"||!e.options||(t.innerHTML="",[...e.options].filter(n=>n.dataset.variant!=="1m").forEach(n=>{const s=document.createElement("button");s.type="button",s.className="set-modelcard",s.setAttribute("role","radio"),s.dataset.value=n.value,n.dataset.ctx==="1"&&(s.dataset.ctx="1");const o=document.createElement("span");o.className="set-mc-top";const i=document.createElement("span");i.className="set-mc-name",i.textContent=n.textContent,o.appendChild(i);const a=document.createElement("span");a.className="set-mc-dot",o.appendChild(a),s.appendChild(o);const l=document.createElement("span");if(l.className="set-mc-meta",l.textContent=n.dataset.meta||"",s.appendChild(l),n.dataset.ctx==="1"){const c=document.createElement("span");c.className="set-mc-ctx",c.textContent="1M capable",s.appendChild(c)}s.addEventListener("click",()=>{this._settingsModelBase=n.value,this._applyModelSelection()}),t.appendChild(s)}),t.dataset.built="1")},_syncModelCards(){const e=document.getElementById("appSettingsClaudeModel");if(!e)return;const t=e.value||"";if(this._settingsModelBase=t.endsWith("[1m]")?t.slice(0,-4):t,t.endsWith("[1m]")){const n=document.getElementById("appSettingsOpusContext1m");n&&(n.checked=!0)}this._applyModelSelection()},_applyModelSelection(){const e=document.getElementById("appSettingsClaudeModel"),t=document.getElementById("appSettingsModelCards");if(!e||!t)return;const n=this._settingsModelBase||"";let s=!1;t.querySelectorAll(".set-modelcard").forEach(c=>{const d=c.dataset.value===n;c.classList.toggle("selected",d),c.setAttribute("aria-checked",d?"true":"false"),d&&(s=c.dataset.ctx==="1")});const o=!!document.getElementById("appSettingsOpusContext1m")?.checked;e.value=n&&s&&o?`${n}[1m]`:n;const i=document.getElementById("appSettingsContextRow"),a=document.getElementById("appSettingsContextDesc"),l=!!n&&!s;i?.classList.toggle("set-row-disabled",l),a&&(a.textContent=l?"The selected model has no 1M variant.":n?"Available for Fable 5.1, Fable 5, Opus and Opus 4.6.":"With no model pinned, this starts new sessions on Opus with a 1M window.")},_buildEffortSegment(){const e=document.getElementById("appSettingsThinkingEffort"),t=document.getElementById("appSettingsEffortSegment");!e||!t||t.dataset.built==="1"||!e.options||(t.innerHTML="",[...e.options].forEach(n=>{const s=document.createElement("button");s.type="button",s.setAttribute("role","radio"),s.dataset.value=n.value,s.textContent=n.textContent,s.addEventListener("click",()=>{e.value=n.value,this._syncEffortSegment()}),t.appendChild(s)}),t.dataset.built="1")},_syncEffortSegment(){const e=document.getElementById("appSettingsThinkingEffort"),t=document.getElementById("appSettingsEffortSegment");!e||!t||t.querySelectorAll("button").forEach(n=>{const s=n.dataset.value===(e.value||"");n.classList.toggle("selected",s),n.setAttribute("aria-checked",s?"true":"false")})},_filterSettings(e){const t=document.getElementById("appSettingsDoc");if(!t)return;const n=(e||"").trim().toLowerCase(),s=".set-row, .set-chip, .set-modelgrid, .set-minigrid, .event-type-grid, #appSettingsShortcutsList",o=[...t.querySelectorAll(s)];let i=!1;o.forEach(l=>{if(!n){l.classList.remove("set-hit-hidden");return}const d=`${l.dataset?.search||""} ${l.textContent||""}`.toLowerCase().includes(n);l.classList.toggle("set-hit-hidden",!d),d&&(i=!0)}),t.querySelectorAll(".set-chips").forEach(l=>{const c=[...l.querySelectorAll(".set-chip")].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c)}),t.querySelectorAll(".set-group").forEach(l=>{const c=[...l.querySelectorAll(s)].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c),n&&c&&l.classList.add("open")}),t.querySelectorAll(".set-section").forEach(l=>{const c=[...l.querySelectorAll(".set-group")].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c)}),t.querySelectorAll(".set-preview").forEach(l=>l.classList.toggle("set-hit-hidden",!!n));const a=document.getElementById("appSettingsSearchEmpty");a&&(a.hidden=!n||i),n||t.querySelectorAll(".set-group-advanced").forEach(l=>l.classList.remove("open"))},closeAppSettings(){this._toggleSettingsJump(!1),document.getElementById("appSettingsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},_updatePhaseText(e){return{queued:"Queued\u2026",preparing:"Preparing\u2026",stashing:"Stashing local changes\u2026",fetching:"Fetching release\u2026",checkout:"Checking out release\u2026",installing:"Installing dependencies\u2026",building:"Building\u2026",restarting:"Restarting Codeman\u2026"}[e]||e},_initUpdatesSection(){const e=this.$("updateCurrentVersion");e&&(e.textContent=(this.$("versionDisplay")?.textContent||"").trim()||"\u2014");for(const t of["updateResult","updateActionRow","updateNotes","updateProgress"]){const n=this.$(t);n&&(n.style.display="none")}this._updateCheck=null},_setUpdateResult(e){const t=this.$("updateResult");t&&(t.style.display="block",t.innerHTML=e)},_setUpdateProgress(e){const t=this.$("updateProgress");t&&(t.style.display="block",t.innerHTML=e)},async checkForUpdate(){const e=this.$("updateCheckBtn");e&&(e.disabled=!0,e.textContent="Checking\u2026");const t=await this._apiJson("/api/system/update/check");e&&(e.disabled=!1,e.textContent="Check now");const n=this.$("updateActionRow"),s=this.$("updateNotes");if(n&&(n.style.display="none"),s&&(s.style.display="none"),!t){this._setUpdateResult("Could not check for updates. Try again later.");return}this._updateCheck=t;const o=this.$("updateCurrentVersion");if(o&&t.currentVersion&&(o.textContent=`v${t.currentVersion}`),t.installKind&&t.installKind!=="git"&&t.installKind!=="docker-compose"){const a=t.supervisor==="docker-compose"?"Update from the Docker host with <code>docker/Start-Codeman.sh</code>.":"Update with <code>npm i -g aicodeman@latest</code>.";this._setUpdateResult(`This install can't update itself (${escapeHtml(t.installKind)}). ${a}`);return}if(t.selfUpdateEnabled===!1){this._setUpdateResult("In-app updates are disabled on this server (CODEMAN_DISABLE_SELF_UPDATE=1).");return}if(t.error&&!t.updateAvailable){this._setUpdateResult(escapeHtml(t.error));return}const i=t.environment?.blockers||[];if(t.updateAvailable&&i.length>0){const a=i.map(l=>{const c=l.details?.length?`<br><code>${escapeHtml(l.details.join(" "))}</code>`:"";return`<li>${escapeHtml(l.message)}${c}</li>`}).join("");this._setUpdateResult(`<strong>v${escapeHtml(t.latestVersion||"")}</strong> needs a rebuild on the Docker host (current v${escapeHtml(t.currentVersion||"")}):<ul>${a}</ul>Run <code>${escapeHtml(t.environment?.hostCommand||"docker/Start-Codeman.sh")}</code> there to apply it.`),s&&t.notes&&(s.style.display="block",s.textContent=t.notes);return}if(t.updateAvailable&&t.latestVersion){this._setUpdateResult(`Update available: <strong>v${escapeHtml(t.latestVersion)}</strong> (current v${escapeHtml(t.currentVersion||"")})`);const a=this.$("updateActionLabel");a&&(a.textContent=`Update to v${t.latestVersion}`),n&&(n.style.display="flex");const l=this.$("updateNowBtn");l&&(l.disabled=!1,l.textContent="Update now"),s&&t.notes&&(s.style.display="block",s.textContent=t.notes)}else this._setUpdateResult(`You're up to date (v${escapeHtml(t.currentVersion||"")}).`)},async startSelfUpdate(){const e=this._updateCheck?.latestVersion?`v${this._updateCheck.latestVersion}`:"the latest release";if(!confirm(`Update Codeman to ${e}? The server will restart and this page will reload.`))return;const t=this.$("updateNowBtn");t&&(t.disabled=!0,t.textContent="Starting\u2026");const n=await this._apiPost("/api/system/update",{});if(!n||!n.ok){let i="Failed to start the update.";try{const a=await n.json();typeof a?.error=="string"&&a.error&&(i=a.error)}catch{}this._setUpdateProgress(`<span style="color:var(--danger,#e5534b)">${escapeHtml(i)}</span>`),t&&(t.disabled=!1,t.textContent="Update now");return}const s=this.$("updateActionRow");s&&(s.style.display="none");const o=this.$("updateNotes");o&&(o.style.display="none"),this._setUpdateProgress("Starting update\u2026"),this._pollUpdateStatus()},_stopUpdatePolling(){this._updatePollTimer&&(clearInterval(this._updatePollTimer),this._updatePollTimer=null)},_pollUpdateStatus(){this._stopUpdatePolling();const e=new Set(["completed","completed-needs-manual-restart","failed","idle"]),t=async()=>{let n=null;try{const s=await fetch("/api/system/update/status");if(s.ok){const o=await s.json();n=o&&o.success===!0?o.data:o}}catch{}if(!n){this._setUpdateProgress("\u21BB Restarting Codeman\u2026");return}if(!e.has(n.phase)){const s=n.message&&n.message.trim()?n.message.trim():this._updatePhaseText(n.phase);let o="";n.startedAt&&(o=` <span style="color:var(--text-secondary)">\xB7 ${Math.max(0,Math.round((Date.now()-n.startedAt)/1e3))}s</span>`),this._setUpdateProgress(`<span class="tunnel-spinner"></span> ${escapeHtml(s)}${o}`);return}if(this._stopUpdatePolling(),n.phase==="completed"){let s=`<span style="color:var(--success,#3fb950)">\u2713 Updated to v${escapeHtml(n.toVersion||"")}. Reloading\u2026</span>`;n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code> \u2014 run <code>git stash pop</code> to restore.</span>`),this._setUpdateProgress(s),setTimeout(()=>location.reload(),2500)}else if(n.phase==="completed-needs-manual-restart")this._setUpdateProgress(`Update staged. Restart Codeman to apply:<br><code>${escapeHtml(n.manualRestartCommand||"restart codeman web")}</code>`);else if(n.phase==="failed"){let s=`<span style="color:var(--danger,#e5534b)">\u2717 ${escapeHtml(n.message||"Update failed")}.</span>`;n.error&&(s+=`<br><span style="color:var(--text-secondary)">${escapeHtml(n.error)}</span>`),s+='<br><span style="color:var(--text-secondary)">The previous version is still running.</span>',n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code>.</span>`),this._setUpdateProgress(s);const o=this.$("updateNowBtn"),i=this.$("updateActionRow");o&&(o.disabled=!1,o.textContent="Try again"),i&&(i.style.display="flex")}};t(),this._updatePollTimer=setInterval(t,1500)},isCliAvailable(e){const t=window.__codemanCliAvailable;return!t||typeof t!="object"?!0:t[e]!==!1},applyWelcomeCliVisibility(){const e=[["welcomeClaudeBtn","claude"],["welcomeOpencodeBtn","opencode"],["welcomeAntigravityBtn","antigravity"],["welcomeOmpBtn","omp"],["welcomeGeminiBtn","gemini"],["welcomePiBtn","pi"],["welcomeGrokBtn","grok"],["welcomeDeepSeekBtn","deepseek"],["welcomeTunnelBtn","cloudflared"]];for(const[t,n]of e){const s=document.getElementById(t);s&&(s.style.display=this.isCliAvailable(n)?"flex":"none")}},async loadTunnelStatus(){try{const t=await(await fetch("/api/tunnel/status")).json(),n=t?.success===!0?t.data:t,s=n.running&&n.url;this._tunnelUrl=s?n.url:null,this._updateTunnelUrlDisplay(this._tunnelUrl),this._updateWelcomeTunnelBtn(!!s,this._tunnelUrl),this._updateTunnelIndicator(!!s)}catch{this._tunnelUrl=null,this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1)}},_updateTunnelUrlRow(e,t,n,s=""){const o=document.getElementById(e),i=document.getElementById(t);if(!(!o||!i))if(n){const a=n+s;o.style.display="",i.textContent=a,i.onclick=()=>{navigator.clipboard.writeText(a).then(()=>{this.showToast(`${s?"Upload":"Tunnel"} URL copied`,"success")})}}else o.style.display="none",i.textContent="",i.onclick=null},_updateTunnelUrlDisplay(e){this._updateTunnelUrlRow("tunnelUrlRow","tunnelUrlDisplay",e),this._updateTunnelUrlRow("tunnelUploadUrlRow","tunnelUploadUrlDisplay",e,"/upload.html")},showTunnelQR(){this.closeTunnelQR();const e=document.createElement("div");e.id="tunnelQrOverlay",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:5000;display:flex;align-items:center;justify-content:center;cursor:pointer",e.onclick=n=>{n.target===e&&this.closeTunnelQR()};const t=document.createElement("div");t.style.cssText="background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;text-align:center;max-width:340px;width:90vw;box-shadow:var(--shadow-lg);cursor:default",t.innerHTML=`
|
|
2
|
-
<div style="font-size:14px;font-weight:600;color:var(--text-primary);margin-bottom:16px">Scan to connect</div>
|
|
3
|
-
<div id="tunnelQrContainer" style="background:#fff;border-radius:8px;padding:16px;display:inline-block">
|
|
4
|
-
<div style="color:#666;font-size:12px">Loading...</div>
|
|
5
|
-
</div>
|
|
6
|
-
<div id="tunnelQrUrl" style="margin-top:12px;font-family:monospace;font-size:11px;color:var(--text-muted);word-break:break-all;cursor:pointer" title="Click to copy"></div>
|
|
7
|
-
<button onclick="app.closeTunnelQR()" style="margin-top:16px;padding:6px 20px;background:var(--bg-elevated);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);cursor:pointer;font-size:13px">Close</button>
|
|
8
|
-
`,e.appendChild(t),document.body.appendChild(e),fetch("/api/tunnel/qr").then(n=>{if(!n.ok)throw new Error("Tunnel not running");return n.json()}).then(n=>{const s=n?.success===!0?n.data:n,o=document.getElementById("tunnelQrContainer");if(o&&s.svg&&(o.innerHTML=s.svg),s.authEnabled){const i=document.createElement("div");i.id="tunnelQrBadge",i.style.cssText="margin-top:8px;font-size:11px;color:var(--text-muted)",i.textContent="Single-use auth \xB7 expires in 60s";const a=document.createElement("button");a.textContent="Regenerate QR",a.style.cssText="margin-top:8px;padding:4px 12px;background:var(--bg-elevated);border:1px solid var(--border);border-radius:4px;color:var(--text-secondary);cursor:pointer;font-size:11px",a.onclick=()=>{fetch("/api/tunnel/qr/regenerate",{method:"POST"}).then(()=>this.showToast("QR code regenerated","success")).catch(()=>this.showToast("Failed to regenerate QR","error"))};const l=o.parentElement;l&&(l.appendChild(i),l.appendChild(a)),this._resetQrCountdown()}}).catch(()=>{const n=document.getElementById("tunnelQrContainer");n&&(n.innerHTML='<div style="color:#c00;font-size:12px;padding:20px">Tunnel not active</div>')}),fetch("/api/tunnel/status").then(n=>n.json()).then(n=>{const s=n?.success===!0?n.data:n,o=document.getElementById("tunnelQrUrl");o&&s.url&&(o.textContent=s.url,o.onclick=()=>{navigator.clipboard.writeText(s.url).then(()=>{this.showToast("Tunnel URL copied","success")})})}).catch(()=>{}),this._tunnelQrEscHandler=n=>{n.key==="Escape"&&this.closeTunnelQR()},document.addEventListener("keydown",this._tunnelQrEscHandler)},closeTunnelQR(){const e=document.getElementById("tunnelQrOverlay");e&&e.remove(),this._tunnelQrEscHandler&&(document.removeEventListener("keydown",this._tunnelQrEscHandler),this._tunnelQrEscHandler=null),this._clearQrCountdown()},_refreshTunnelQrFromApi(){fetch("/api/tunnel/qr").then(e=>e.ok?e.json():null).then(e=>{const t=e?.success===!0?e.data:e;if(!t?.svg)return;const n=document.getElementById("tunnelQrContainer");n&&(n.innerHTML=t.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=t.svg)}).catch(()=>{})},_resetQrCountdown(){this._clearQrCountdown(),this._qrCountdownSec=60,this._updateQrCountdownText(),this._qrCountdownTimer=setInterval(()=>{if(this._qrCountdownSec--,this._qrCountdownSec<=0){this._clearQrCountdown();return}this._updateQrCountdownText()},1e3)},_updateQrCountdownText(){const e=document.getElementById("tunnelQrBadge");e&&(e.textContent=`Single-use auth \xB7 expires in ${this._qrCountdownSec}s`)},_clearQrCountdown(){this._qrCountdownTimer&&(clearInterval(this._qrCountdownTimer),this._qrCountdownTimer=null)},async toggleTunnelFromWelcome(){const e=document.getElementById("welcomeTunnelBtn");if(!e)return;const t=e.classList.contains("active");e.disabled=!0;try{const n=!t,s=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:n})});if(n&&await this._handleTunnelEnableRefusal(s)){this._dismissTunnelConnecting(),this._updateWelcomeTunnelBtn(!1),e.disabled=!1;return}n?(this._showTunnelConnecting(),this._pollTunnelStatus()):(this._dismissTunnelConnecting(),this.showToast("Tunnel stopped","info"),this._updateWelcomeTunnelBtn(!1),e.disabled=!1)}catch{this._dismissTunnelConnecting(),this.showToast("Failed to toggle tunnel","error"),e.disabled=!1}},_showTunnelConnecting(){const e=document.getElementById("tunnelConnectingToast");e&&e.remove();const t=document.getElementById("welcomeTunnelBtn");t&&(t.classList.add("connecting"),t.innerHTML=`
|
|
9
|
-
<span class="tunnel-spinner"></span>
|
|
10
|
-
Connecting...`);const n=document.createElement("div");n.className="toast toast-info show",n.id="tunnelConnectingToast",n.innerHTML='<span class="tunnel-spinner"></span> Cloudflare Tunnel connecting...',n.style.pointerEvents="auto",this._toastContainer||(this._toastContainer=document.querySelector(".toast-container"),this._toastContainer||(this._toastContainer=document.createElement("div"),this._toastContainer.className="toast-container",document.body.appendChild(this._toastContainer))),this._toastContainer.appendChild(n)},_dismissTunnelConnecting(){clearTimeout(this._tunnelPollTimer),this._tunnelPollTimer=null;const e=document.getElementById("tunnelConnectingToast");e&&(e.classList.remove("show"),setTimeout(()=>e.remove(),200));const t=document.getElementById("welcomeTunnelBtn");t&&t.classList.remove("connecting")},_pollTunnelStatus(e=0){e>15||(this._tunnelPollTimer=setTimeout(async()=>{try{const n=await(await fetch("/api/tunnel/status")).json(),s=n?.success===!0?n.data:n;if(s.running&&s.url){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(s.url),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,s.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,s.url),this.showToast(`Tunnel active: ${s.url}`,"success"),this.showTunnelQR());return}}catch{}this._pollTunnelStatus(e+1)},2e3))},_updateWelcomeTunnelBtn(e,t,n=!1){const s=document.getElementById("welcomeTunnelBtn");s&&(s.disabled=!1,e?(s.classList.remove("connecting"),s.classList.add("active"),s.innerHTML=`
|
|
11
|
-
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
|
|
12
|
-
Tunnel Active`):(s.classList.remove("active","connecting"),s.innerHTML=`
|
|
13
|
-
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
|
|
14
|
-
Cloudflare Tunnel`));const o=document.getElementById("welcomeQr"),i=document.getElementById("welcomeQrInner"),a=document.getElementById("welcomeQrUrl");!o||!i||(e?(o.classList.add("visible"),n&&(o.classList.add("expanded"),clearTimeout(this._welcomeQrShrinkTimer),this._welcomeQrShrinkTimer=setTimeout(()=>{o.classList.remove("expanded")},8e3)),t&&(a.textContent=t,a.title="Click QR to enlarge"),fetch("/api/tunnel/qr").then(l=>{if(!l.ok)throw new Error;return l.json()}).then(l=>{const c=l?.success===!0?l.data:l;c.svg&&(i.innerHTML=c.svg)}).catch(()=>{i.innerHTML='<div style="color:#999;font-size:11px;padding:20px">QR unavailable</div>'})):(clearTimeout(this._welcomeQrShrinkTimer),o.classList.remove("visible","expanded"),i.innerHTML="",a&&(a.textContent="")))},toggleWelcomeQrSize(){const e=document.getElementById("welcomeQr");e&&(clearTimeout(this._welcomeQrShrinkTimer),e.classList.toggle("expanded"))},_updateTunnelIndicator(e){if(MobileDetection.getDeviceType()==="mobile")return;const t=document.getElementById("tunnelIndicator");t&&(t.style.display=e?"flex":"none",t.classList.remove("connecting"))},toggleTunnelPanel(){if(document.getElementById("tunnelPanel")){this.closeTunnelPanel();return}this._openTunnelPanel()},async _openTunnelPanel(){const e=document.createElement("div");e.className="tunnel-panel",e.id="tunnelPanel",e.innerHTML=`
|
|
15
|
-
<div class="tunnel-panel-header">
|
|
16
|
-
<h3>
|
|
17
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
|
|
18
|
-
Cloudflare Tunnel
|
|
19
|
-
<span class="tunnel-panel-status" id="tunnelPanelStatus">Loading...</span>
|
|
20
|
-
</h3>
|
|
21
|
-
</div>
|
|
22
|
-
<div class="tunnel-panel-body" id="tunnelPanelBody">
|
|
23
|
-
<div style="font-size:12px;color:var(--text-muted);padding:8px 0">Loading...</div>
|
|
24
|
-
</div>
|
|
25
|
-
`,document.body.appendChild(e),this._tunnelPanelClickHandler=t=>{!e.contains(t.target)&&t.target.id!=="tunnelIndicator"&&!t.target.closest(".tunnel-indicator")&&this.closeTunnelPanel()},setTimeout(()=>document.addEventListener("click",this._tunnelPanelClickHandler),0),this._tunnelPanelEscHandler=t=>{t.key==="Escape"&&this.closeTunnelPanel()},document.addEventListener("keydown",this._tunnelPanelEscHandler);try{const n=await(await fetch("/api/tunnel/info")).json(),s=n?.success===!0?n.data:n;this._renderTunnelPanel(s)}catch{const t=document.getElementById("tunnelPanelBody");t&&(t.innerHTML='<div style="font-size:12px;color:var(--red);padding:8px 0">Failed to load tunnel info</div>')}},_renderTunnelPanel(e){const t=document.getElementById("tunnelPanelStatus"),n=document.getElementById("tunnelPanelBody");if(!t||!n)return;t.textContent=e.running?"Connected":"Offline",t.className="tunnel-panel-status"+(e.running?"":" offline");let s="";if(e.url&&(s+=`
|
|
26
|
-
<div class="tunnel-panel-section">
|
|
27
|
-
<div class="tunnel-panel-label">URL</div>
|
|
28
|
-
<div class="tunnel-panel-url" id="tunnelPanelUrl" title="Click to copy">${escapeHtml(e.url)}</div>
|
|
29
|
-
</div>`),s+=`
|
|
30
|
-
<div class="tunnel-panel-section">
|
|
31
|
-
<div class="tunnel-panel-label">Connections</div>
|
|
32
|
-
<div class="tunnel-panel-stat">
|
|
33
|
-
<span>Remote Clients</span>
|
|
34
|
-
<span class="tunnel-panel-stat-value">${e.sseClients}</span>
|
|
35
|
-
</div>`,e.authEnabled&&(s+=`
|
|
36
|
-
<div class="tunnel-panel-stat">
|
|
37
|
-
<span>Auth Sessions</span>
|
|
38
|
-
<span class="tunnel-panel-stat-value">${e.authSessions.length}</span>
|
|
39
|
-
</div>`),s+="</div>",e.authEnabled&&e.authSessions.length>0){s+='<div class="tunnel-panel-section"><div class="tunnel-panel-label">Authenticated Devices</div>';for(const i of e.authSessions){const a=i.ua||"Unknown",l=a.match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser",c=this._formatTimeAgo(i.createdAt);s+=`
|
|
40
|
-
<div class="tunnel-panel-session">
|
|
41
|
-
<span class="tunnel-panel-session-dot"></span>
|
|
42
|
-
<span class="tunnel-panel-session-info" title="${escapeHtml(a)}">${escapeHtml(l)} · ${escapeHtml(i.ip)} · ${c}</span>
|
|
43
|
-
<span class="tunnel-panel-session-method">${i.method}</span>
|
|
44
|
-
</div>`}s+="</div>"}s+='<div class="tunnel-panel-actions">',e.running?s+=`
|
|
45
|
-
<button class="tunnel-panel-btn btn-qr" onclick="app.showTunnelQR();app.closeTunnelPanel()">QR Code</button>
|
|
46
|
-
<button class="tunnel-panel-btn btn-stop" onclick="app._tunnelPanelToggle(false)">Stop Tunnel</button>`:s+='<button class="tunnel-panel-btn btn-start" onclick="app._tunnelPanelToggle(true)">Start Tunnel</button>',s+="</div>",e.authEnabled&&e.authSessions.length>0&&(s+=`
|
|
47
|
-
<div style="padding-top:8px">
|
|
48
|
-
<button class="tunnel-panel-btn btn-revoke" style="width:100%" onclick="app._tunnelPanelRevokeAll()">Revoke All Sessions</button>
|
|
49
|
-
</div>`),n.innerHTML=s;const o=document.getElementById("tunnelPanelUrl");o&&(o.onclick=()=>{navigator.clipboard.writeText(e.url).then(()=>this.showToast("Tunnel URL copied","success"))})},_formatTimeAgo(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const s=Math.floor(n/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`},async _handleTunnelEnableRefusal(e){if(!e||e.ok)return!1;let t="Tunnel refused: set CODEMAN_PASSWORD before exposing Codeman publicly.";try{const n=await e.json();n&&n.error&&(t=n.error)}catch{}if(e.status===403){if(!confirm(`\u26A0\uFE0F SECURITY WARNING \u2014 no password set
|
|
50
|
-
|
|
51
|
-
Enabling the Cloudflare tunnel will publish THIS machine to a public URL with NO login. Anyone who gets the URL has full terminal control \u2014 effectively remote code execution on your computer.
|
|
52
|
-
|
|
53
|
-
Strongly recommended: set CODEMAN_PASSWORD instead.
|
|
54
|
-
|
|
55
|
-
Enable the unauthenticated public tunnel anyway?`))return this._dismissTunnelConnecting?.(),this.showToast("Tunnel not enabled","info"),!0;try{const s=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:!0,acknowledgeUnauthTunnel:!0})});if(s.ok)return this.showToast("Public tunnel enabling \u2014 no password set \u26A0\uFE0F","warning"),!1;let o="Failed to enable tunnel.";try{const i=await s.json();i&&i.error&&(o=i.error)}catch{}return this._dismissTunnelConnecting?.(),this.showToast(o,"error"),!0}catch{return this._dismissTunnelConnecting?.(),this.showToast("Failed to enable tunnel","error"),!0}}return this._dismissTunnelConnecting?.(),this.showToast(t,"error"),!0},async _tunnelPanelToggle(e){try{const t=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:e})});if(e&&await this._handleTunnelEnableRefusal(t)){this.closeTunnelPanel();return}if(e){this._updateTunnelIndicator(!1);const n=document.getElementById("tunnelIndicator");n&&(n.style.display="flex",n.classList.add("connecting")),this.showToast("Tunnel starting...","info"),this._showTunnelConnecting(),this._pollTunnelStatus()}else this.showToast("Tunnel stopped","info");this.closeTunnelPanel()}catch{this.showToast("Failed to toggle tunnel","error")}},async _tunnelPanelRevokeAll(){try{await fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),this.showToast("All sessions revoked","success");const t=await(await fetch("/api/tunnel/info")).json(),n=t?.success===!0?t.data:t;this._renderTunnelPanel(n)}catch{this.showToast("Failed to revoke sessions","error")}},closeTunnelPanel(){const e=document.getElementById("tunnelPanel");e&&e.remove(),this._tunnelPanelClickHandler&&(document.removeEventListener("click",this._tunnelPanelClickHandler),this._tunnelPanelClickHandler=null),this._tunnelPanelEscHandler&&(document.removeEventListener("keydown",this._tunnelPanelEscHandler),this._tunnelPanelEscHandler=null)},toggleDeepgramKeyVisibility(){const e=document.getElementById("voiceDeepgramKey"),t=document.getElementById("voiceKeyToggleBtn");e.type==="password"?(e.type="text",t.textContent="Hide"):(e.type="password",t.textContent="Show")},openLifecycleLog(){const e=document.getElementById("lifecycleWindow");e.style.display="block",e._dragInitialized||(e.style.left="50%",e.style.transform="translateX(-50%)",this._initLifecycleDrag(e),e._dragInitialized=!0),this.loadLifecycleLog()},closeLifecycleLog(){document.getElementById("lifecycleWindow").style.display="none"},_initLifecycleDrag(e){const t=document.getElementById("lifecycleWindowHeader");let n=!1,s,o,i,a;t.addEventListener("mousedown",l=>{if(l.target.tagName==="SELECT"||l.target.tagName==="INPUT"||l.target.tagName==="BUTTON")return;n=!0;const c=e.getBoundingClientRect();e.style.transform="none",e.style.left=c.left+"px",e.style.top=c.top+"px",s=l.clientX,o=l.clientY,i=c.left,a=c.top,l.preventDefault()}),document.addEventListener("mousemove",l=>{n&&(e.style.left=i+l.clientX-s+"px",e.style.top=a+l.clientY-o+"px")}),document.addEventListener("mouseup",()=>{n=!1})},async loadLifecycleLog(){const e=document.getElementById("lifecycleFilterEvent").value,t=document.getElementById("lifecycleFilterSession").value.trim(),n=new URLSearchParams;e&&n.set("event",e),t&&n.set("sessionId",t),n.set("limit","300");try{const o=await(await fetch(`/api/session-lifecycle?${n}`)).json(),i=o?.success===!0?o.data:o,a=document.getElementById("lifecycleTableBody"),l=document.getElementById("lifecycleEmpty");if(!i.entries||i.entries.length===0){a.innerHTML="",l.style.display="";return}l.style.display="none";const c={created:"#4ade80",started:"#4ade80",recovered:"#4ade80",exit:"#fbbf24",mux_died:"#f87171",deleted:"#f87171",stale_cleaned:"#f87171",server_started:"#666",server_stopped:"#666"};a.innerHTML=i.entries.map(d=>{const r=new Date(d.ts).toLocaleString(),u=c[d.event]||"#888",p=d.name||(d.sessionId==="*"?"\u2014":this.getShortId(d.sessionId)),h=[];return d.exitCode!==void 0&&d.exitCode!==null&&h.push(`code=${d.exitCode}`),d.mode&&h.push(d.mode),`<tr style="border-bottom:1px solid #1a1a2e">
|
|
56
|
-
<td style="padding:3px 8px;color:#888;white-space:nowrap">${r}</td>
|
|
57
|
-
<td style="padding:3px 8px;color:${u};font-weight:600">${d.event}</td>
|
|
58
|
-
<td style="padding:3px 8px;color:#e0e0e0" title="${d.sessionId}">${p}</td>
|
|
59
|
-
<td style="padding:3px 8px;color:#aaa">${d.reason||""}</td>
|
|
60
|
-
<td style="padding:3px 8px;color:#666">${h.join(", ")}</td>
|
|
61
|
-
</tr>`}).join("")}catch(s){console.error("Failed to load lifecycle log:",s)}},_renderVoiceProviderStatus(){const e=document.getElementById("voiceProviderStatus");if(e){const o=VoiceInput.getActiveProviderName();e.textContent=o;const i=o.startsWith("Deepgram Nova")||o.startsWith("Claude (this");e.className="voice-provider-status"+(i?" active":"")}const t=document.getElementById("voiceClaudeStatus");if(!t)return;const n=VoiceInput._claudeStatus,s=n?n.available?`Ready${n.subscriptionType?` (${n.subscriptionType})`:""}`:n.reason==="expired"?"Login expired - run a Claude session to refresh":n.reason==="no-credentials"?"No Claude Code login on the server":n.reason==="malformed"?"Claude credentials unreadable":"Off - enable it above":"Checking...";t.textContent=s,t.className="voice-provider-status"+(n?.available?" active":"")},async saveAppSettings(){const e=this.loadAppSettingsFromStorage(),t=(e.gestureControlEnabled??!1)===!0,n=(e.webglRendererEnabled??!0)===!0,s={displayName:window.CodemanI18n?.normalizeDisplayName(document.getElementById("appSettingsDisplayName").value)||"Codeman",language:window.CodemanI18n?.normalizeLanguage(document.getElementById("appSettingsLanguage").value)||"en",defaultClaudeMdPath:document.getElementById("appSettingsClaudeMdPath").value.trim(),defaultWorkingDir:document.getElementById("appSettingsDefaultDir").value.trim(),ralphTrackerEnabled:document.getElementById("appSettingsRalphEnabled").checked,showFontControls:document.getElementById("appSettingsShowFontControls").checked,showSystemStats:document.getElementById("appSettingsShowSystemStats").checked,showLifecycleLog:document.getElementById("appSettingsShowLifecycleLog").checked,showResponseViewer:document.getElementById("appSettingsShowResponseViewer").checked,showFileViewerButton:document.getElementById("appSettingsShowFileViewerButton").checked,showAttachmentsButton:document.getElementById("appSettingsShowAttachmentsButton").checked,showMonitor:document.getElementById("appSettingsShowMonitor").checked,showProjectInsights:document.getElementById("appSettingsShowProjectInsights").checked,showFileBrowser:document.getElementById("appSettingsShowFileBrowser").checked,showSubagents:document.getElementById("appSettingsShowSubagents").checked,showUltracodeAgents:document.getElementById("appSettingsShowUltracodeAgents").checked,approvalsInboxEnabled:document.getElementById("appSettingsApprovalsInbox").checked,readMyMindEnabled:document.getElementById("appSettingsReadMyMind").checked,ultracodeFloatingWindows:document.getElementById("appSettingsUltracodeFloatingWindows").checked,showMultiMonitorButton:document.getElementById("appSettingsShowMultiMonitorButton").checked,showPlanUsageLimits:document.getElementById("appSettingsShowPlanUsageLimits").checked,showRedrawButton:document.getElementById("appSettingsShowRedrawButton").checked,mobileOverviewEnabled:document.getElementById("appSettingsMobileOverview").checked,sessionLineageLines:document.getElementById("appSettingsLineageLines").checked,showSessionButton:document.getElementById("appSettingsShowSessionButton").checked,showAwayDigestButton:document.getElementById("appSettingsShowAwayDigestButton").checked,showCronButton:document.getElementById("appSettingsShowCronButton").checked,gestureControlEnabled:document.getElementById("appSettingsGestureControl").checked,subagentTrackingEnabled:document.getElementById("appSettingsSubagentTracking").checked,subagentActiveTabOnly:document.getElementById("appSettingsSubagentActiveTabOnly").checked,imageWatcherEnabled:document.getElementById("appSettingsImageWatcherEnabled").checked,tunnelEnabled:document.getElementById("appSettingsTunnelEnabled").checked,localEchoEnabled:document.getElementById("appSettingsLocalEcho").checked,autoCopySelection:document.getElementById("appSettingsAutoCopySelection").checked,terminalFontFamily:document.getElementById("appSettingsTerminalFont").value.trim(),terminalWheelLocalScrollback:document.getElementById("appSettingsTerminalWheelLocal").checked,cjkInputEnabled:document.getElementById("appSettingsCjkInput").checked,webglRendererEnabled:document.getElementById("appSettingsWebglRenderer").checked,extendedKeyboardBar:document.getElementById("appSettingsExtendedKeyboardBar").checked,tabTwoRows:document.getElementById("appSettingsTabTwoRows").checked,tabOrientation:document.getElementById("appSettingsTabOrientation").value,tabRailWidth:this.readTabRailWidthSetting?.()??256,tabRailDetail:document.getElementById("appSettingsTabRailDetail").value,showTabDetachButton:document.getElementById("appSettingsShowTabDetachButton").checked,sessionListLayout:document.getElementById("appSettingsSessionListLayout").value,sessionSidebarFontSize:this.resolveSessionSidebarFontSize(document.getElementById("appSettingsSessionSidebarFontSize").value),skin:document.getElementById("appSettingsSkin").value,claudeMode:document.getElementById("appSettingsClaudeMode").value,allowedTools:document.getElementById("appSettingsAllowedTools").value.trim(),codexDangerouslyBypassApprovals:document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked,codexAnimationsEnabled:document.getElementById("appSettingsCodexAnimations").checked,agentTeamsEnabled:document.getElementById("appSettingsAgentTeams").checked,agentSkillEnabled:document.getElementById("appSettingsAgentSkill").checked,workspaceHooksEnabled:document.getElementById("appSettingsWorkspaceHooks").checked,claudeVoiceEnabled:document.getElementById("appSettingsClaudeVoice").checked,claudeModel:document.getElementById("appSettingsClaudeModel").value,opusContext1mEnabled:document.getElementById("appSettingsOpusContext1m").checked,remoteAutoReconnect:document.getElementById("appSettingsRemoteAutoReconnect").checked,thinkingEffort:document.getElementById("appSettingsThinkingEffort").value,nice:{enabled:document.getElementById("appSettingsNiceEnabled").checked,niceValue:parseInt(document.getElementById("appSettingsNiceValue").value)||10}};if(e.showTokenCount!==void 0&&(s.showTokenCount=e.showTokenCount),e.showCost!==void 0&&(s.showCost=e.showCost),e.shortcutOverrides!==void 0&&(s.shortcutOverrides=e.shortcutOverrides),this.saveAppSettingsToStorage(s),this._updateLocalEchoState(),this.applyTerminalFontFamily?.(s.terminalFontFamily),!n&&s.webglRendererEnabled)try{localStorage.removeItem("codeman-webgl-disabled")}catch{}const o={provider:document.getElementById("voiceProvider").value,apiKey:document.getElementById("voiceDeepgramKey").value.trim(),language:document.getElementById("voiceLanguage").value,keyterms:document.getElementById("voiceKeyterms").value.trim(),insertMode:document.getElementById("voiceInsertMode").value};VoiceInput._saveDeepgramConfig(o);const i={enabled:document.getElementById("appSettingsNotifEnabled").checked,browserNotifications:document.getElementById("appSettingsNotifBrowser").checked,audioAlerts:document.getElementById("appSettingsNotifAudio").checked,stuckThresholdMs:(parseInt(document.getElementById("appSettingsNotifStuckMins").value)||10)*6e4,muteCritical:!document.getElementById("appSettingsNotifCritical").checked,muteWarning:!document.getElementById("appSettingsNotifWarning").checked,muteInfo:!document.getElementById("appSettingsNotifInfo").checked,eventTypes:{permission_prompt:{enabled:document.getElementById("eventPermissionEnabled").checked,browser:document.getElementById("eventPermissionBrowser").checked,push:document.getElementById("eventPermissionPush").checked,audio:document.getElementById("eventPermissionAudio").checked},elicitation_dialog:{enabled:document.getElementById("eventQuestionEnabled").checked,browser:document.getElementById("eventQuestionBrowser").checked,push:document.getElementById("eventQuestionPush").checked,audio:document.getElementById("eventQuestionAudio").checked},idle_prompt:{enabled:document.getElementById("eventIdleEnabled").checked,browser:document.getElementById("eventIdleBrowser").checked,push:document.getElementById("eventIdlePush").checked,audio:document.getElementById("eventIdleAudio").checked},stop:{enabled:document.getElementById("eventStopEnabled").checked,browser:document.getElementById("eventStopBrowser").checked,push:document.getElementById("eventStopPush").checked,audio:document.getElementById("eventStopAudio").checked},session_error:{enabled:!0,browser:this.notificationManager?.preferences?.eventTypes?.session_error?.browser??!0,push:this.notificationManager?.preferences?.eventTypes?.session_error?.push??!1,audio:!1},respawn_cycle:{enabled:document.getElementById("eventRespawnEnabled").checked,browser:document.getElementById("eventRespawnBrowser").checked,push:document.getElementById("eventRespawnPush").checked,audio:document.getElementById("eventRespawnAudio").checked},token_milestone:{enabled:!0,browser:!1,push:!1,audio:!1},ralph_complete:{enabled:document.getElementById("eventRalphEnabled").checked,browser:document.getElementById("eventRalphBrowser").checked,push:document.getElementById("eventRalphPush").checked,audio:document.getElementById("eventRalphAudio").checked},subagent_spawn:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked},subagent_complete:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked}},_version:5};this.notificationManager&&(this.notificationManager.preferences=i,this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applySkin(),this.applyLocalization(),this.applySessionListLayout(),this.applyTabOrientation({settleRailWidth:!0}),this.applyLineageLineSettings?.(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderApprovals?.(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this._updateCjkInputState(),this.activeSessionId||this.showWelcome(),KeyboardAccessoryBar.setMode(s.extendedKeyboardBar?"extended":"simple");const{localEchoEnabled:a,cjkInputEnabled:l,extendedKeyboardBar:c,skin:d,language:r,showPlanUsageLimits:u,showAttachmentsButton:p,showFileViewerButton:h,webglRendererEnabled:m,terminalWheelLocalScrollback:g,autoCopySelection:S,terminalFontFamily:b,showSessionButton:E,showAwayDigestButton:w,showCronButton:v,showTabDetachButton:y,mobileOverviewEnabled:B,sessionLineageLines:I,...f}=s;try{const k=await this._apiPut("/api/settings",{...f,...s.showPlanUsageLimits?{statusLineTelemetry:!0}:{},notificationPreferences:i,voiceSettings:o});if(s.tunnelEnabled&&await this._handleTunnelEnableRefusal(k)){s.tunnelEnabled=!1,this.saveAppSettingsToStorage(s);const T=document.getElementById("appSettingsTunnelEnabled");T&&(T.checked=!1),this.closeAppSettings();return}await this.saveModelConfigFromSettings(),this.showToast("Settings saved","success"),s.tunnelEnabled&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}this.closeAppSettings(),VoiceInput.refreshClaudeStatus(),s.gestureControlEnabled!==t&&(this.showToast(s.gestureControlEnabled?"Enabling gesture control \u2014 reloading\u2026":"Disabling gesture control \u2014 reloading\u2026","info"),setTimeout(()=>location.reload(),400))},async loadModelConfigForSettings(){try{const t=await(await fetch("/api/execution/model-config")).json();if(t.success&&t.data){const n=t.data,s=document.getElementById("appSettingsDefaultModel");s&&(s.value=n.defaultModel||"");const o=document.getElementById("appSettingsShowModelRecommendations");o&&(o.checked=n.showRecommendations??!0);const i=n.agentTypeOverrides||{},a=document.getElementById("appSettingsModelExplore"),l=document.getElementById("appSettingsModelImplement"),c=document.getElementById("appSettingsModelTest"),d=document.getElementById("appSettingsModelReview");a&&(a.value=i.explore||""),l&&(l.value=i.implement||""),c&&(c.value=i.test||""),d&&(d.value=i.review||"")}}catch(e){console.warn("Failed to load model config:",e)}},async saveModelConfigFromSettings(){const e=document.getElementById("appSettingsDefaultModel"),t=document.getElementById("appSettingsShowModelRecommendations"),n=document.getElementById("appSettingsModelExplore"),s=document.getElementById("appSettingsModelImplement"),o=document.getElementById("appSettingsModelTest"),i=document.getElementById("appSettingsModelReview"),a={};n?.value&&(a.explore=n.value),s?.value&&(a.implement=s.value),o?.value&&(a.test=o.value),i?.value&&(a.review=i.value);const l={defaultModel:e?.value||"",showRecommendations:t?.checked??!0,agentTypeOverrides:a};try{await fetch("/api/execution/model-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})}catch(c){console.warn("Failed to save model config:",c)}},isRalphTrackerEnabledByDefault(){return this.loadAppSettingsFromStorage().ralphTrackerEnabled??!1},getSettingsStorageKey(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?"codeman-app-settings-mobile":"codeman-app-settings"},getDefaultSettings(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?{showFontControls:!1,showSystemStats:!1,showTokenCount:!1,showCost:!1,showMonitor:!1,showProjectInsights:!1,showFileBrowser:!1,showSubagents:!1,showUltracodeAgents:!1,ultracodeFloatingWindows:!1,showMultiMonitorButton:!1,showPlanUsageLimits:!1,showAttachmentsButton:!1,showFileViewerButton:!1,showRedrawButton:!1,showSessionButton:!1,showAwayDigestButton:!1,showCronButton:!1,mobileOverviewEnabled:!0,remoteAutoReconnect:!0,gestureControlEnabled:!1,subagentTrackingEnabled:!0,subagentActiveTabOnly:!0,imageWatcherEnabled:!1,ralphTrackerEnabled:!1,tabTwoRows:!1,tabOrientation:"horizontal",tabRailWidth:256,tabRailDetail:"rich",sessionListLayout:"header",sessionSidebarFontSize:12,cjkInputEnabled:!1,terminalWheelLocalScrollback:!1,webglRendererEnabled:!1,skin:"daylight-blue"}:{}},loadAppSettingsFromStorage(){if(this._cachedAppSettings)return this._cachedAppSettings;try{const e=this.getSettingsStorageKey(),t=localStorage.getItem(e);if(t)return this._cachedAppSettings=JSON.parse(t),this._cachedAppSettings}catch(e){console.error("Failed to load app settings:",e)}return this._cachedAppSettings=this.getDefaultSettings(),this._cachedAppSettings},saveAppSettingsToStorage(e){this._cachedAppSettings=e;try{const t=this.getSettingsStorageKey();localStorage.setItem(t,JSON.stringify(e))}catch(t){console.error("Failed to save app settings:",t)}},applySkin(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.skin??t.skin??"daylight-blue";document.documentElement.setAttribute("data-skin",n),window.__codemanSkin=n;const s=getComputedStyle(document.documentElement).getPropertyValue("--bg-dark").trim();s&&document.querySelector('meta[name="theme-color"]')?.setAttribute("content",s);try{localStorage.setItem("codeman:skin",n)}catch{}typeof this.applyTerminalSkin=="function"&&this.applyTerminalSkin(n)},applyLocalization(){const e=this.loadAppSettingsFromStorage();window.CodemanI18n?.configure({language:e.language,displayName:e.displayName})&&this.notificationManager&&(this.notificationManager.originalTitle=document.title)},planUsageChipEnabled(e=null){return(e??this.loadAppSettingsFromStorage()).showPlanUsageLimits??this.getDefaultSettings().showPlanUsageLimits??!0},applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.showTabDetachButton??t.showTabDetachButton??!1;document.documentElement.classList.toggle("tabs-show-detach",n);const s=MobileDetection.getDeviceType()!=="desktop",o=s?!1:e.showFontControls??t.showFontControls??!1,i=s?!1:e.showSystemStats??t.showSystemStats??!0,a=s?!1:e.showTokenCount??t.showTokenCount??!1,l=document.querySelector(".header-font-controls"),c=document.getElementById("headerSystemStats"),d=document.getElementById("headerTokens");l&&(l.style.display=o?"":"none"),c&&(c.style.display=i?"":"none"),d&&(d.style.display=a?"":"none");const r=e.showLifecycleLog??t.showLifecycleLog??!1,u=document.querySelector(".btn-lifecycle-log");u&&(u.style.display=r?"":"none");const p=e.showResponseViewer??t.showResponseViewer??!1,h=document.querySelector(".btn-response-viewer-header");h&&h.classList.toggle("btn-response-viewer-header--hidden",!p);const m=e.showAttachmentsButton??t.showAttachmentsButton??!1,g=document.getElementById("attachmentsHistoryBtn");g&&g.classList.toggle("btn-attachments-history--hidden",!m);const S=e.showFileViewerButton??t.showFileViewerButton??!0,b=document.querySelector(".btn-file-viewer");b&&b.classList.toggle("btn-file-viewer--hidden",!S);const E=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,w=document.querySelector(".btn-multimonitor");w&&w.classList.toggle("btn-multimonitor--hidden",!E);const v=e.showUltracodeAgents??t.showUltracodeAgents??!1,y=document.querySelector(".btn-ultracode-agents");y&&y.classList.toggle("btn-ultracode-agents--hidden",!v);const B=document.querySelector(".btn-readmymind");B&&B.classList.toggle("btn-readmymind--hidden",e.readMyMindEnabled!==!0),typeof KeyboardAccessoryBar<"u"&&KeyboardAccessoryBar.syncReadMyMind?.();const I=this.planUsageChipEnabled(e),f=document.getElementById("planUsageChip");f&&f.classList.toggle("header-plan-usage--hidden",!I);const k=e.showRedrawButton??t.showRedrawButton??!1,T=document.querySelector(".btn-redraw-terminal");T&&T.classList.toggle("btn-redraw-terminal--hidden",!k);const M=e.showSessionButton??t.showSessionButton??!1,_=document.querySelector(".btn-session-manager");_&&_.classList.toggle("btn-session-manager--hidden",!M);const x=e.showAwayDigestButton??t.showAwayDigestButton??!1,C=document.querySelector(".btn-away-digest");C&&C.classList.toggle("btn-away-digest--hidden",!x);const R=e.showCronButton??t.showCronButton??!1,L=document.querySelector(".btn-cron");L&&L.classList.toggle("btn-cron--hidden",!R);const P=document.querySelector(".btn-notifications");if(P&&(P.style.display="none"),!(this.notificationManager?.preferences?.enabled??!0)){const A=document.getElementById("notifDrawer");A&&A.classList.remove("open")}},applyTabOrientation(e={}){const t=this.loadAppSettingsFromStorage(),n=this.getDefaultSettings(),s=this.isSessionSidebarActive?.()===!0,o=!this.isSoloWindow&&!s&&window.CodemanTabOverflow?.resolveTabOrientation?window.CodemanTabOverflow.resolveTabOrientation({deviceType:MobileDetection.getDeviceType(),setting:t.tabOrientation??n.tabOrientation??"horizontal"}):"horizontal",i=document.documentElement,a=i.getAttribute("data-tab-orientation")||"horizontal";i.setAttribute("data-tab-orientation",o);const l=i.dataset.tabRailDetail||"rich",c=(t.tabRailDetail??n.tabRailDetail??"rich")==="simple"?"simple":"rich";i.dataset.tabRailDetail=c;const d=document.getElementById("sessionTabs"),r=document.getElementById("tabRail"),u=document.getElementById("sessionTabsHost");!s&&d&&r&&u&&(o==="vertical"?d.parentElement!==r&&r.appendChild(d):d.parentElement!==u&&u.appendChild(d)),d&&d.setAttribute("aria-orientation",s||o==="vertical"?"vertical":"horizontal");const p=e.settleRailWidth===!0&&(o==="vertical"||a!==o);this.applyTabRailWidth?.({settle:p});const h=a!==o,m=h||l!==c;h&&(this.updateTabOverflowMode?.(),p||this.fitAddon?.fit());const g=this._tallTabsEnabled;m&&this.applyTabWrapSettings?.(),m&&(g!==void 0&&g!==this._tallTabsEnabled||this._fullRenderSessionTabs?.(),this._updateConnectionLinesImmediate?.(),this._refreshHomeSessionsIfVisible?.()),this.isRichTabRows?.()?this._startSidebarRichClock?.():this._stopSidebarRichClock?.()},applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=MobileDetection.getDeviceType(),s=this.isSessionSidebarActive?.()===!0,o=!s&&n==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,i=this.isTabRailRich?.()===!0,a=s||o||i,l=this._tallTabsEnabled;this._tallTabsEnabled=a;const c=document.getElementById("sessionTabs");c&&(c.classList.toggle("tabs-two-rows",o),c.classList.toggle("tabs-show-folder",a)),l!==void 0&&l!==a&&this._fullRenderSessionTabs()},applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.showMonitor??t.showMonitor??!1,s=e.showSubagents??t.showSubagents??!1,o=e.showFileBrowser??t.showFileBrowser??!1,i=document.getElementById("monitorPanel");i&&(i.style.display=n?"":"none",n?i.classList.add("open"):i.classList.remove("open"));const a=document.getElementById("subagentsPanel");a&&(s?a.classList.remove("hidden"):a.classList.add("hidden"));const l=e.showUltracodeAgents??t.showUltracodeAgents??!1,c=document.getElementById("ultracodeAgentsPanel");c&&(l?c.classList.remove("hidden"):(c.classList.remove("open"),c.classList.add("hidden"))),e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1?typeof this.syncAllUltracodeFloatingWindows=="function"&&this.syncAllUltracodeFloatingWindows():typeof this.removeAllUltracodeWindows=="function"&&this.removeAllUltracodeWindows();const r=document.getElementById("fileBrowserPanel");if(r)if(o&&this.activeSessionId){if(r.classList.add("visible"),this.loadFileBrowser(this.activeSessionId),!this.fileBrowserDragListeners){const u=r.querySelector(".file-browser-header");if(u){const p=()=>{if(!r.style.left){const h=r.getBoundingClientRect();r.style.left=`${h.left}px`,r.style.top=`${h.top}px`,r.style.right="auto"}};u.addEventListener("mousedown",p),u.addEventListener("touchstart",p,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(r,u),this.fileBrowserDragListeners._onFirstDrag=p}}}else r.classList.contains("visible")&&(this._resetFileBrowserForHide?.(),r.classList.remove("visible"))},closeMonitor(){const e=document.getElementById("monitorPanel");e&&(e.classList.remove("open"),e.style.display="none");const t=this.loadAppSettingsFromStorage();t.showMonitor=!1,this.saveAppSettingsToStorage(t)},closeSubagentsPanel(){const e=document.getElementById("subagentsPanel");e&&(e.classList.remove("open"),e.classList.add("hidden")),this.subagentPanelVisible=!1;const t=this.loadAppSettingsFromStorage();t.showSubagents=!1,this.saveAppSettingsToStorage(t)},async clearAllSubagents(){const e=this.subagents.size;if(e===0){this.showToast("No subagents to clear","info");return}if(confirm(`Clear all ${e} tracked subagent(s)? This removes them from the UI but does not affect running processes.`))try{const n=await(await fetch("/api/subagents",{method:"DELETE"})).json();n.success?(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),this.cleanupAllFloatingWindows(),this.renderSubagentPanel(),this.renderMonitorSubagents(),this.updateSubagentBadge(),this.showToast(`Cleared ${n.data.cleared} subagent(s)`,"success")):this.showToast("Failed to clear subagents: "+n.error,"error")}catch{this.showToast("Failed to clear subagents","error")}},toggleSubagentsPanel(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsToggleBtn");if(e){if(e.classList.contains("hidden")){e.classList.remove("hidden");const n=this.loadAppSettingsFromStorage();n.showSubagents=!0,this.saveAppSettingsToStorage(n)}e.classList.toggle("open"),this.subagentPanelVisible=e.classList.contains("open"),t&&(t.innerHTML=this.subagentPanelVisible?"▼":"▲"),this.subagentPanelVisible&&this.renderSubagentPanel()}},async loadAppSettingsFromServer(e=null){try{if((MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile")&&!localStorage.getItem("codeman:planUsagePerDeviceMigrated")){const t=this.loadAppSettingsFromStorage();t&&t.showPlanUsageLimits&&(t.showPlanUsageLimits=!1,this.saveAppSettingsToStorage(t)),localStorage.setItem("codeman:planUsagePerDeviceMigrated","1")}}catch{}try{const t=e?await e:await fetch("/api/settings").then(n=>n.ok?n.json():null).then(n=>n?.success===!0?n.data:n);if(t){const{notificationPreferences:n,voiceSettings:s,respawnPresets:o,runMode:i,...a}=t,l=new Set(["showFontControls","showSystemStats","showTokenCount","showCost","showLifecycleLog","showResponseViewer","showRedrawButton","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","tabOrientation","tabRailWidth","tabRailDetail","sessionListLayout","sessionSidebarFontSize","localEchoEnabled","cjkInputEnabled","extendedKeyboardBar","skin","showPlanUsageLimits","showAttachmentsButton","showFileViewerButton","webglRendererEnabled","terminalFontFamily","language","terminalWheelLocalScrollback","autoCopySelection","showSessionButton","showAwayDigestButton","showCronButton","showTabDetachButton","mobileOverviewEnabled","sessionLineageLines"]);delete a.showPlanUsageLimits;const c=this.loadAppSettingsFromStorage(),d={...c};for(const[r,u]of Object.entries(a))l.has(r)&&r in c||(d[r]=u);if(this.saveAppSettingsToStorage(d),n&&this.notificationManager&&(localStorage.getItem(this.notificationManager.getStorageKey())||(this.notificationManager.preferences=this.notificationManager.normalizePreferences(n),this.notificationManager.savePreferences())),s){const r=localStorage.getItem("codeman-voice-settings");(!r||!JSON.parse(r).apiKey)&&VoiceInput._saveDeepgramConfig(s)}if(o&&Array.isArray(o))this._serverRespawnPresets=o,localStorage.setItem("codeman-respawn-presets",JSON.stringify(o));else{const r=localStorage.getItem("codeman-respawn-presets");if(r){const u=JSON.parse(r);u.length>0&&(this._serverRespawnPresets=u,this._apiPut("/api/settings",{respawnPresets:u}).catch(()=>{}))}}if(i){this.runMode=i;try{localStorage.setItem("codeman_runMode",i)}catch{}this._applyRunMode()}return d}}catch(t){console.error("Failed to load settings from server:",t)}return this.loadAppSettingsFromStorage()},async loadSubagentWindowStates(){let e=null;try{const t=await fetch("/api/subagent-window-states");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-window-states",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent window states from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-window-states");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent window states from localStorage:",t)}return e||{minimized:{},open:[]}},async saveSubagentParentMap(){const e=Object.fromEntries(this.subagentParentMap);try{localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}catch(t){console.error("Failed to save subagent parents to localStorage:",t)}try{await fetch("/api/subagent-parents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(t){console.error("Failed to save subagent parents to server:",t)}},async loadSubagentParentMap(){let e=null;try{const t=await fetch("/api/subagent-parents");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent parents from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-parents");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent parents from localStorage:",t)}if(e&&typeof e=="object")for(const[t,n]of Object.entries(e))this.sessions.has(n)&&this.subagents.has(t)&&this.subagentParentMap.set(t,n)},getAgentParentSessionId(e){return this.subagentParentMap.get(e)||null},setAgentParentSessionId(e,t){if(!e||!t||this.subagentParentMap.has(e))return;this.subagentParentMap.set(e,t),this.saveSubagentParentMap();const n=this.subagents.get(e);if(n){n.parentSessionId=t;const s=this.sessions.get(t);s&&(n.parentSessionName=this.getSessionName(s)),this.subagents.set(e,n)}},showHelp(){const e=document.getElementById("helpModal");e.classList.add("active"),this.activeFocusTrap=new FocusTrap(e),this.activeFocusTrap.activate()},closeHelp(){document.getElementById("helpModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},renderShortcutSettingsList(){const e=document.getElementById("appSettingsShortcutsList");if(!e)return;const t=this.getShortcutRegistry?this.getShortcutRegistry():typeof DEFAULT_SHORTCUTS<"u"?DEFAULT_SHORTCUTS:[],n=this.readShortcutOverridesFromSettings();e.innerHTML=t.map(s=>{const o=s.displayBindings?s.displayBindings.join(" / "):(s.bindings||[]).map(c=>[...c.modifiers||[],c.key||c.code||""].join("+")).join(" / "),i=!!s.action&&Array.isArray(s.bindings),a=!!n[s.id],l=i?`<button type="button" class="shortcut-capture-btn" data-shortcut-action="capture" title="Capture new binding">Edit</button>
|
|
62
|
-
<button type="button" class="shortcut-reset-btn" data-shortcut-action="reset" title="Reset to default"${a?"":" disabled"}>Reset</button>
|
|
63
|
-
<input class="shortcut-enabled-checkbox" type="checkbox" ${s.disabled?"":"checked"} data-shortcut-action="toggle" title="Enable/disable">`:"";return`<div class="shortcut-setting-row${i?"":" shortcut-setting-row--fixed"}" data-shortcut-id="${escapeHtml(s.id)}">
|
|
64
|
-
<label class="shortcut-setting-label">${escapeHtml(s.label)}</label>
|
|
65
|
-
<input class="shortcut-binding-input" type="text" readonly value="${escapeHtml(o)}" placeholder="(none)" data-id="${escapeHtml(s.id)}">
|
|
66
|
-
${l}
|
|
67
|
-
</div>`}).join(""),this._wireShortcutSettingsList(e)},_wireShortcutSettingsList(e){e.dataset.shortcutListenersAdded||(e.dataset.shortcutListenersAdded="true",e.addEventListener("click",t=>{const n=t.target?.closest?.("[data-shortcut-action]");if(!n)return;const s=n.closest?.("[data-shortcut-id]")?.dataset?.shortcutId;s&&(n.dataset.shortcutAction==="capture"?this.startShortcutCapture(s):n.dataset.shortcutAction==="reset"&&this.resetShortcutOverride(s))}),e.addEventListener("change",t=>{const n=t.target;if(!n?.matches?.('[data-shortcut-action="toggle"]'))return;const s=n.closest?.("[data-shortcut-id]")?.dataset?.shortcutId;s&&this.toggleShortcutEnabled(s,n.checked)}))},readShortcutOverridesFromSettings(){return this.loadAppSettingsFromStorage().shortcutOverrides||{}},startShortcutCapture(e){const t=document.querySelector(`.shortcut-binding-input[data-id="${e}"]`);if(!t)return;t.value="Press keys\u2026",t.focus(),this._capturingShortcutId=e;const n=s=>{s.preventDefault(),s.stopPropagation(),!(s.key==="Control"||s.key==="Shift"||s.key==="Alt"||s.key==="Meta")&&(t.removeEventListener("keydown",n),this.onShortcutCaptureKeydown(s,e))};t.addEventListener("keydown",n)},onShortcutCaptureKeydown(e,t){if(e.preventDefault(),e.stopPropagation(),this._capturingShortcutId=null,e.key==="Escape"){this.renderShortcutSettingsList();return}if(!e.ctrlKey&&!e.metaKey&&!e.altKey){this.renderShortcutSettingsList(),this.showToast?.("Shortcut must include Ctrl, Cmd, or Alt","error");return}const n=[];e.ctrlKey&&n.push("ctrl"),e.metaKey&&n.push("meta"),e.shiftKey&&n.push("shift"),e.altKey&&n.push("alt");const s=this.loadAppSettingsFromStorage(),o={...s.shortcutOverrides||{}};o[t]={...o[t]||{},bindings:[{modifiers:n,key:e.key,code:e.code}]},s.shortcutOverrides=o,this.saveAppSettingsToStorage(s),this.renderShortcutSettingsList()},resetShortcutOverride(e){const t=this.loadAppSettingsFromStorage(),n={...t.shortcutOverrides||{}};delete n[e],t.shortcutOverrides=n,this.saveAppSettingsToStorage(t),this.renderShortcutSettingsList()},toggleShortcutEnabled(e,t){const n=this.loadAppSettingsFromStorage(),s={...n.shortcutOverrides||{}};s[e]={...s[e]||{},disabled:!t},n.shortcutOverrides=s,this.saveAppSettingsToStorage(n),this.renderShortcutSettingsList()},closeAllPanels(){this.closeSessionOptions(),this.closeAppSettings(),this.cancelCloseSession(),this.closeTokenStats(),document.getElementById("monitorPanel").classList.remove("open");const e=document.getElementById("subagentsPanel");e&&e.classList.remove("open"),this.subagentPanelVisible=!1}});
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";(function(e){const t=/^\x1b\[[\?>=]?[\d;]*[cnR]$/,i=/^\x1b\][\d;]*[^\x07\x1b]*(?:\x07|\x1b\\)$/,s=/^\x1b\[<\d+;\d+;\d+[Mm]$/,n=/^\x1b\[M[\s\S]{3}$/,o=/^\x1b\[[IO]$/,c=["input","textarea","select","button","a[href]",'[contenteditable=""]','[contenteditable="true"]','[tabindex]:not([tabindex="-1"])',".keyboard-accessory-bar",".path-picker-overlay"].join(","),f=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?<>=!]*[ -/]*[@-~]|\x1b[()#][0-9A-Za-z]|\x1b[=>78M]/g,E="\x1B[5~",T="\x1B[6~",y=.5,l=3,p=4,d=/^\x1b(?:\[(?:[ABCDHF]|1;[2-8][ABCDHF]|[1-8](?:;[2-8])?~)|O[ABCDHF])$/,S="\x1B[200~";function g(v){return d.test(v)}const _=/^› /;function C(v){const I=Array.from(v);if(I.length===1){const x=I[0].codePointAt(0);return x===127?"backspace":x>=32?"char":"clear"}return v.charCodeAt(0)===27?"clear":v.charCodeAt(0)>=32?"text":"clear"}function w(v){try{const I=v.buffer.active,x=I.getLine(I.baseY+I.cursorY);return!!x&&_.test(x.translateToString(!0))}catch{return!1}}function L(v){return t.test(v)||i.test(v)}function M(v){return L(v)}function k(v){return o.test(v)||s.test(v)||n.test(v)}const R={og:{background:"#0d0d0d",foreground:"#e0e0e0",cursor:"#e0e0e0",cursorAccent:"#0d0d0d",selection:"rgba(255,255,255,0.3)",black:"#0d0d0d",red:"#ff6b6b",green:"#51cf66",yellow:"#ffd43b",blue:"#339af0",magenta:"#cc5de8",cyan:"#22b8cf",white:"#e0e0e0",brightBlack:"#495057",brightRed:"#ff8787",brightGreen:"#69db7c",brightYellow:"#ffe066",brightBlue:"#5c7cfa",brightMagenta:"#da77f2",brightCyan:"#66d9e8",brightWhite:"#ffffff"},"daylight-green":{background:"#161b23",foreground:"#dfe6ef",cursor:"#2fd3aa",cursorAccent:"#161b23",selection:"rgba(47,211,170,0.22)",black:"#161b23",red:"#ff8585",green:"#34d8a0",yellow:"#f0c25a",blue:"#5cc6e8",magenta:"#c79af2",cyan:"#2bcbbb",white:"#dfe6ef",brightBlack:"#5b6675",brightRed:"#ffa0a0",brightGreen:"#5fe6b8",brightYellow:"#ffd884",brightBlue:"#82d4ee",brightMagenta:"#d6b3f7",brightCyan:"#5ee0d4",brightWhite:"#f3f6fa"},"daylight-blue":{background:"#161b23",foreground:"#dfe6ef",cursor:"#38b6f0",cursorAccent:"#161b23",selection:"rgba(56,182,240,0.22)",black:"#161b23",red:"#ff8585",green:"#34d8a0",yellow:"#f0c25a",blue:"#5cc6e8",magenta:"#c79af2",cyan:"#2bcbbb",white:"#dfe6ef",brightBlack:"#5b6675",brightRed:"#ffa0a0",brightGreen:"#5fe6b8",brightYellow:"#ffd884",brightBlue:"#82d4ee",brightMagenta:"#d6b3f7",brightCyan:"#5ee0d4",brightWhite:"#f3f6fa"},"paper-gray":{background:"#f6f8fa",foreground:"#1f2328",cursor:"#0969da",cursorAccent:"#ffffff",selection:"rgba(9,105,218,0.2)",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#59636e",brightBlack:"#6e7781",brightRed:"#a40e26",brightGreen:"#116329",brightYellow:"#7d4e00",brightBlue:"#0550ae",brightMagenta:"#6639ba",brightCyan:"#116b75",brightWhite:"#1f2328"},"solarized-light":{background:"#fdf6e3",foreground:"#586e75",cursor:"#147ba3",cursorAccent:"#fdf6e3",selection:"rgba(38,139,210,0.2)",black:"#eee8d5",red:"#dc322f",green:"#758600",yellow:"#9b7800",blue:"#147ba3",magenta:"#d33682",cyan:"#2a9189",white:"#073642",brightBlack:"#93a1a1",brightRed:"#cb4b16",brightGreen:"#657b83",brightYellow:"#586e75",brightBlue:"#268bd2",brightMagenta:"#6c71c4",brightCyan:"#2aa198",brightWhite:"#002b36"},"catppuccin-latte":{background:"#eff1f5",foreground:"#4c4f69",cursor:"#1e66f5",cursorAccent:"#ffffff",selection:"rgba(30,102,245,0.18)",black:"#5c5f77",red:"#d20f39",green:"#3b8f2b",yellow:"#a86605",blue:"#1e66f5",magenta:"#8839ef",cyan:"#177f86",white:"#6c6f85",brightBlack:"#7c7f93",brightRed:"#b50930",brightGreen:"#2f7622",brightYellow:"#8b5604",brightBlue:"#174fbf",brightMagenta:"#6f2bc5",brightCyan:"#116b71",brightWhite:"#4c4f69"},"rose-pine-dawn":{background:"#faf4ed",foreground:"#575279",cursor:"#286983",cursorAccent:"#fffaf3",selection:"rgba(40,105,131,0.2)",black:"#575279",red:"#b4637a",green:"#286983",yellow:"#96681f",blue:"#477f91",magenta:"#907aa9",cyan:"#3f7f8b",white:"#6e6a86",brightBlack:"#797593",brightRed:"#984d66",brightGreen:"#1f5266",brightYellow:"#7d5417",brightBlue:"#386b7c",brightMagenta:"#765f90",brightCyan:"#326b76",brightWhite:"#575279"}},P=new Set(["paper-gray","solarized-light","catppuccin-latte","rose-pine-dawn"]);function F(){return typeof document<"u"&&document.documentElement.dataset.skin||"daylight-blue"}function A(){const v=F();return R[v]||R["daylight-blue"]}function b(v=F()){return P.has(v)}e.CodemanTerminalInput={isTerminalQueryResponse:L,shouldSuppressTerminalQueryResponse:M,isTerminalFocusOrMouseReport:k,isComposerNavKey:g,classifyPredictInput:C,isCodexComposerRow:w,CODEX_COMPOSER_ROW_RE:_,BRACKETED_PASTE_START:S,USER_SCROLL_STICKY_SUPPRESS_MS:1500,TOUCH_COMPAT_MOUSE_SUPPRESS_MS:450,REPLAY_ESCAPE_RE:f,KEY_PAGE_UP:E,KEY_PAGE_DOWN:T,PAGE_KEY_SCREEN_FRACTION:y,PAGE_KEY_MAX_PER_BATCH:l,TUI_PROMPT_DEFAULT_ROWS_FROM_BOTTOM:p,MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR:c,MOBILE_KEYBOARD_DISMISS_TAP_SLOP:8,TOUCH_SELECT_LONG_PRESS_MS:350,TOUCH_SELECT_FOCUS_GUARD_MS:800},e.CODEMAN_XTERM_THEMES=R,e.codemanCurrentXtermTheme=A,e.codemanCurrentSkinIsLight=b})(window),Object.assign(CodemanApp.prototype,{initTerminal(){const e=parseInt(localStorage.getItem("codeman-scrollback")),t=Number.isFinite(e)&&e>0?Math.max(e,DEFAULT_SCROLLBACK):DEFAULT_SCROLLBACK;if(this.terminal=new Terminal({theme:{...window.codemanCurrentXtermTheme()},fontFamily:window.CodemanTerminalFont.resolve(this.loadAppSettingsFromStorage?.().terminalFontFamily),fontSize:MobileDetection.getDeviceType()==="mobile"?10:14,lineHeight:1.2,cursorBlink:!1,cursorStyle:"block",minimumContrastRatio:window.codemanCurrentSkinIsLight()?4.5:1,scrollback:t,allowTransparency:!0,allowProposedApi:!0}),this.fitAddon=new FitAddon.FitAddon,this.terminal.loadAddon(this.fitAddon),this._xtermSnapshots=new Map,typeof SerializeAddon<"u")try{this._serializeAddon=new SerializeAddon.SerializeAddon,this.terminal.loadAddon(this._serializeAddon)}catch{this._serializeAddon=null}if(typeof Unicode11Addon<"u")try{const l=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(l),this.terminal.unicode.activeVersion="11"}catch{}const i=document.getElementById("terminalContainer");this.terminal.open(i),this._installMobileTapMouseGuard(),this._installTouchSelectionFocusGuard(),this.terminal.attachCustomKeyEventHandler(l=>{if(l.isComposing||l.key==="Process"||l.keyCode===229)return!0;if(l.altKey&&!l.ctrlKey&&!l.shiftKey&&/^(Digit[1-9]|BracketLeft|BracketRight|KeyK)$/.test(l.code||"")||l.type==="keydown"&&this.shouldOpenCommandPaletteFromShortcut?.(l))return!1;if(this.shouldCopyTerminalSelectionFromShortcut?.(l)){const p=this.terminal.hasSelection?.()?this.terminal.getSelection():"";return p?(l.preventDefault(),this.copyTerminalSelection(p),!1):l.shiftKey?(l.preventDefault(),!1):!0}if(l.type==="keydown"&&this.shouldToggleSessionSidebarFromShortcut?.(l))return!1;if((l.ctrlKey||l.metaKey)&&l.key==="v"&&l.type==="keydown")return this.activeSessionId&&this._handleImagePaste&&this._handleImagePaste(),!1;if(l.key==="Enter"&&(l.shiftKey||l.ctrlKey)&&l.type==="keydown"){if(this.activeSessionId)if(this._localEchoEnabled){const p=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),p&&(this._pendingInput+=p,y()),setTimeout(()=>{fetch(`/api/sessions/${this.activeSessionId}/send-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:l.ctrlKey?"C-Enter":"S-Enter"})})},p?80:0)}else fetch(`/api/sessions/${this.activeSessionId}/send-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:l.ctrlKey?"C-Enter":"S-Enter"})});return!1}return!0}),this._webglAddon=null;const s=new URLSearchParams(location.search),n=(()=>{try{const l=localStorage.getItem("codeman-webgl-disabled");if(!l)return!1;const{at:p}=JSON.parse(l);return Date.now()-p>WEBGL_FALLBACK.STICKY_EXPIRY_MS?(localStorage.removeItem("codeman-webgl-disabled"),!1):!0}catch{return!1}})(),o=this.loadAppSettingsFromStorage(),r=this.getDefaultSettings(),a=o.webglRendererEnabled??r.webglRendererEnabled,{skip:h,clearSticky:u}=shouldSkipWebGL({deviceType:MobileDetection.getDeviceType(),noWebglParam:s.has("nowebgl"),forceParam:s.get("webgl")==="force",stickyDisabled:n,userPrefEnabled:a});if(u)try{localStorage.removeItem("codeman-webgl-disabled")}catch{}if(h&&n&&console.log("[CRASH-DIAG] WebGL sticky-disabled from prior stalls \u2014 DOM renderer in use. Re-enable: ?webgl=force"),!h)if(typeof WebglAddon<"u")this._initWebGL();else{const l=document.createElement("script");l.src="vendor/xterm-addon-webgl.min.js",l.onload=()=>this._initWebGL(),l.onerror=()=>console.warn("[CRASH-DIAG] Failed to load WebGL addon \u2014 using canvas renderer"),document.head.appendChild(l)}this._localEchoOverlay=new LocalEchoOverlay(this.terminal),this._predictiveEcho=typeof PredictiveEchoOverlay<"u"?new PredictiveEchoOverlay(this.terminal):null,this._predictiveEcho?.setPredictWhen(l=>window.CodemanTerminalInput.isCodexComposerRow(l)),MobileDetection.isTouchDevice()&&(this.terminal.onCursorMove(()=>this._syncMobileHelperTextareaToCursor()),this.terminal.onRender(()=>this._syncMobileHelperTextareaToCursor())),this._cjkInput=null,typeof CjkInput<"u"&&(this._cjkInput=CjkInput.init({send:l=>{this._handleCjkInput(l)}}));const m=this.terminal.focus.bind(this.terminal);this.terminal.focus=()=>{const l=document.getElementById("cjkInput");l?.classList.contains("cjk-input-visible")?l.focus():m()},MobileDetection.getDeviceType()==="mobile"&&document.body.classList.contains("safari-browser")?requestAnimationFrame(()=>{this.fitAddon.fit(),requestAnimationFrame(()=>this.fitAddon.fit())}):this.fitAddon.fit(),this._terminalFontReady=this._awaitTerminalFont(),this.registerFilePathLinkProvider(),this.terminal.onSelectionChange?.(()=>{if(!this.terminal?.hasSelection?.()){this._touchSelecting=!1,this._touchSelectionActive=!1,this._touchSelectionAnchor=null,this._hideTouchSelectionBar(),this._autoCopyPending=!1;return}this._autoCopyPending=!0}),this._autoCopyListenerInstalled||(this._autoCopyListenerInstalled=!0,document.addEventListener("mouseup",()=>this._flushAutoCopySelection())),i.addEventListener("wheel",l=>{const p=this.terminal?.modes?.mouseTrackingMode;if(p&&p!=="none"||this.terminal?.buffer?.active?.type==="alternate")return;if(l.preventDefault(),l.stopPropagation(),this._shouldForwardWheelToApp(l)){this._logScrollRouting("forward-sgr"),this._forwardScrollToApp(l.clientX,l.clientY,this._wheelScrollLines(l));return}const d=this._wheelScrollLinesFloat(l);this._maybePageCliTranscript(l,d)||(this._logScrollRouting("local-scrollback"),this._noteTerminalUserScroll(d),this._smoothScrollBy(d))},{passive:!1,capture:!0});{const l=()=>this.terminal._core?._renderService?.dimensions?.css?.cell?.height||13;let p=0,d=0,S=0,g=0,_=null,C=!1;const w=I=>{const x=g?(I-g)/16.67:1;if(g=I,!C&&Math.abs(S)>.3){const O=Math.round(S/l());O!==0&&(this._shouldForwardWheelToApp({shiftKey:!1})?this._forwardScrollToApp(p,d,O):this._maybePageCliTranscript({shiftKey:!1},O)||(this.terminal.scrollLines(O),this._maybeLoadMoreHistoryOnScroll(O))),S*=.92,_=requestAnimationFrame(w)}else C?_=requestAnimationFrame(w):(_=null,S=0)};let L=0,M=!1,k=null,R=0,P=0,F=0,A=!1,b=null;const v=window.CodemanTerminalInput.MOBILE_KEYBOARD_DISMISS_TAP_SLOP;i.addEventListener("touchstart",I=>{if(!I.target?.closest?.(".term-select-bar")&&(I.touches.length!==1&&(clearTimeout(k),k=null),I.touches.length===1)){p=I.touches[0].clientX,d=I.touches[0].clientY,F=d,S=0,L=0,C=!0,M=!1,A=this._isMobileTerminalInputFocused();const x=this._classifyMobileTerminalTap(p,d);b={x:p,y:d,intent:x},x==="content"&&(I.preventDefault(),this._blurMobileTerminalInput()),R=p,P=d,clearTimeout(k),k=setTimeout(()=>{k=null,this._beginTouchSelection(R,P)},window.CodemanTerminalInput.TOUCH_SELECT_LONG_PRESS_MS),g=0,_&&(cancelAnimationFrame(_),_=null)}},{passive:!1}),i.addEventListener("touchmove",I=>{if(this._touchSelecting){I.preventDefault();const x=I.touches[0];x&&this._extendTouchSelection(x.clientX,x.clientY);return}if(k&&I.touches.length===1){const x=I.touches[0];(Math.abs(x.clientX-R)>v||Math.abs(x.clientY-P)>v)&&(clearTimeout(k),k=null)}if(I.touches.length===1&&C){const x=I.touches[0].clientY;if(!M&&Math.abs(x-F)>=v&&(M=!0),!M)return;I.preventDefault();const O=d-x;L+=O,S=O*1.2,p=I.touches[0].clientX,d=x;const D=l(),B=Math.trunc(L/D);B!==0&&(this._shouldForwardWheelToApp({shiftKey:!1})?(this._logScrollRouting("forward-sgr"),this._forwardScrollToApp(p,d,B)):this._maybePageCliTranscript({shiftKey:!1},B)||(this._logScrollRouting("local-scrollback"),this._noteTerminalUserScroll(B),this.terminal.scrollLines(B),this._maybeLoadMoreHistoryOnScroll(B)),L-=B*D)}},{passive:!1}),i.addEventListener("touchend",I=>{if(!I.target?.closest?.(".term-select-bar")){if(clearTimeout(k),k=null,C=!1,this._touchSelecting){I.preventDefault(),S=0,this._endTouchSelectionGesture(),A=!1;return}if(!_&&Math.abs(S)>.3&&(_=requestAnimationFrame(w)),!M&&this.terminal){const x=I.changedTouches&&I.changedTouches[0];if(x){this._suppressTrustedTapMouseEvents();const O=b&&b.x===x.clientX&&b.y===x.clientY?b.intent:null;this._handleMobileTerminalTap(x,A,O)}}A=!1}},{passive:!1}),i.addEventListener("contextmenu",I=>{(k!==null||this._touchSelecting||this._touchSelectionActive)&&I.preventDefault()}),i.addEventListener("touchcancel",()=>{clearTimeout(k),k=null,C=!1,this._touchSelecting=!1,S=0,L=0,A=!1},{passive:!0})}i.addEventListener("click",l=>this._handleDesktopTerminalClick(l)),this._installMobileKeyboardDismiss(),this.showWelcome(),this.initImageInput(),this._chunkedWriteGen=0,this._bufferLoadSeq=0,this._bufferLoadOwner=null,this._lastUserScrollUpAt=null,this._resizeTimeout=null,this._lastResizeDims=null;const f=40,E=10,T=()=>{this._tabRailResizeOwnsObserver||(this._resizeTimeout&&clearTimeout(this._resizeTimeout),this._resizeTimeout=setTimeout(()=>{this._resizeTimeout=null,this.fitAddon&&this.fitAddon.fit(),this.flickerFilterBuffer&&(this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flushFlickerBuffer());const l=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible,p=!this.isSoloWindow&&this.detachedSessions?.has(this.activeSessionId);if(this.activeSessionId&&!l&&!p){const d=this.fitAddon.proposeDimensions(),S=d?Math.max(d.cols,f):f,g=d?Math.max(d.rows,E):E;if(!this._lastResizeDims||S!==this._lastResizeDims.cols||g!==this._lastResizeDims.rows){const _=this.activeSessionId?this.sessions.get(this.activeSessionId):null;_&&_.mode!=="shell"&&this.terminal&&this.isTerminalAtBottom()&&this.terminal.write("\x1B[3J\x1B[H\x1B[2J"),this._lastResizeDims={cols:S,rows:g};const C=typeof MobileDetection<"u"&&MobileDetection.getDeviceType?MobileDetection.getDeviceType():"desktop";let w=!1;if(this._wsReady&&this._wsSessionId===this.activeSessionId)try{this._ws.send(JSON.stringify({t:"z",c:S,r:g,v:C})),w=!0}catch{}w||fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:S,rows:g,viewportType:C})}).catch(()=>{})}}this.applyLineageLineSettings?.(),this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},300))};window.addEventListener("resize",T),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(T),this.terminalResizeObserver.observe(i),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const y=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const l=this._pendingInput,p=this.activeSessionId;this._pendingInput="",this._sendInputAsync(p,l)}};this.terminal.onData(l=>{if(!/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(l)&&(window.cjkActive||document.activeElement?.id==="cjkInput")){const d=document.getElementById("cjkInput");d?.classList.contains("cjk-input-visible")&&document.activeElement===this.terminal.textarea&&!window.CodemanTerminalInput?.shouldSuppressTerminalQueryResponse(l)&&(_crashDiag.log("CJK regain-focus (onData swallowed input)"),d.focus());return}if(this.activeSessionId){if(window.CodemanTerminalInput?.shouldSuppressTerminalQueryResponse(l))return;typeof KeyboardAccessoryBar<"u"&&KeyboardAccessoryBar.isCtrlArmed?.()&&!window.CodemanTerminalInput?.isTerminalFocusOrMouseReport(l)&&(l=KeyboardAccessoryBar.consumeCtrl(l)),this._lastTerminalData={data:l,time:performance.now()};const d=this._localEchoEnabled&&this._echoPassthroughSessions?.has(this.activeSessionId);if(d&&(l==="\r"||l==="")&&this._echoPassthroughSessions.delete(this.activeSessionId),this._localEchoEnabled&&!d){if(l==="\x7F"){const g=this._localEchoOverlay?.removeChar();if(g==="flushed"){const{count:_,text:C}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(_===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,_),this._flushedTexts?.set(this.activeSessionId,C))),this._pendingInput+=l,y()}else g===!1&&(this._pendingInput+=l,y());return}if(/^[\r\n]+$/.test(l)){const g=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),g&&(this._pendingInput+=g,y()),setTimeout(()=>{this._pendingInput+="\r",y()},80);return}if(l.length>1&&l.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(l);return}if(l.charCodeAt(0)<32){if(l.length>1&&l.charCodeAt(0)===27){if(l.startsWith(window.CodemanTerminalInput.BRACKETED_PASTE_START)){const _=!!this._localEchoOverlay?.pendingText;this._flushLocalEchoPending(),_?(y(),setTimeout(()=>{this._pendingInput+=l,y()},80)):(this._pendingInput+=l,y());return}if(window.CodemanTerminalInput.isComposerNavKey(l)){this._flushLocalEchoPending(),this._echoPassthroughSessions||(this._echoPassthroughSessions=new Set),this._echoPassthroughSessions.add(this.activeSessionId),this._pendingInput+=l,y();return}this._pendingInput+=l,y();return}if(this._restoringFlushedState){this._pendingInput+=l,y();return}if(l===" "){const _=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),_&&(this._pendingInput+=_),this._pendingInput+=l,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let C="";try{const L=this._localEchoOverlay?.findPrompt?.();if(L){const M=this.terminal.buffer.active,k=M.getLine(M.viewportY+L.row);k&&(C=k.translateToString(!0).slice(L.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=C,y(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const w=this;this._tabCompletionFallback=setTimeout(()=>{if(w._tabCompletionFallback=null,!w._tabCompletionSessionId||w._tabCompletionSessionId!==w.activeSessionId)return;const L=w._localEchoOverlay;!L||L.pendingText||w.terminal.write("",()=>{if(!w._tabCompletionSessionId)return;L.resetBufferDetection();const M=L.detectBufferText();M&&M!==w._tabCompletionBaseText&&(w._tabCompletionSessionId=null,w._tabCompletionRetries=0,w._tabCompletionBaseText=null,L.rerender())})},300);return}const g=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),g&&(this._pendingInput+=g),this._pendingInput+=l,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),y();return}if(l.length===1&&l.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(l);return}}if(this._predictHookOnData(l),this._pendingInput+=l,l.charCodeAt(0)<32||l.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),y();return}const S=performance.now();S-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=S,y()):(this._lastKeystrokeTime=S,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(y,0)))}})},registerFilePathLinkProvider(){const e=this;let t=-1;const i={provideLinks(s,n){s!==t&&(t=s,console.debug("[LinkProvider] Checking line:",s));const o=e.terminal.buffer.active;if(!o.getLine(s-1)){n(void 0);return}const h=window.CodemanTerminalLines?.terminalLogicalLine(o,s-1,e.terminal.cols,12);if(!h){n(void 0);return}const u=h.text,m=S=>{const g=h.offsetToCell(S);return{x:g.col+1,y:g.row+1}};if(!u||!u.includes("/")){n(void 0);return}const c=[],f=/https?:\/\/(?:[^\s"'<>|;&)\]\x00-\x1f]|&(?!&))+/g,E=(S,g)=>{const _=S.replace(/[.,;:!?)&]+$/,""),C=u.indexOf(_,g);if(C===-1)return;const w=m(C),L=m(C+_.length);c.some(M=>M.range.start.x===w.x&&M.range.start.y===w.y)||c.push({text:_,range:{start:w,end:L},decorations:{pointerCursor:!0,underline:!0},activate(M,k){window.open(k,"_blank","noopener,noreferrer")},hover(){e._linkHovered=!0},leave(){e._linkHovered=!1}})},T=/\b(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]+\s+){0,4}(\/[^\s"'<>|;&\n\x00-\x1f]+)/g,y=absoluteFilePathPattern(),l=/Bash\([^)]*?(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\)\n\x00-\x1f]+)/g,p=(S,g)=>{const _=u.indexOf(S,g);if(_===-1)return;const C=m(_),w=m(_+S.length);c.some(L=>L.range.start.x===C.x&&L.range.start.y===C.y)||c.push({text:S,range:{start:C,end:w},decorations:{pointerCursor:!0,underline:!0},activate(L,M){if(previewsInFileViewer(M)||e._isExternalPreviewPath(M,e.activeSessionId)){e.openFilePreview(M,e.activeSessionId);return}e.openLogViewerWindow(M,e.activeSessionId)},hover(){e._linkHovered=!0},leave(){e._linkHovered=!1}})};let d;for(f.lastIndex=0;(d=f.exec(u))!==null;)E(d[0],d.index);for(T.lastIndex=0;(d=T.exec(u))!==null;)p(d[2],d.index);for(y.lastIndex=0;(d=y.exec(u))!==null;)p(d[1],d.index);for(l.lastIndex=0;(d=l.exec(u))!==null;)p(d[1],d.index);c.length>0&&console.debug("[LinkProvider] Found links:",c.map(S=>S.text)),n(c.length>0?c:void 0)}};this._terminalLinkProvider=i,this.terminal.registerLinkProvider(i),console.log("[LinkProvider] File path link provider registered")},_terminalLinkAtPoint(e,t){const i=this._terminalLinkProvider,s=this.terminal?.buffer?.active;if(!i||!s)return null;const n=this._clientPointToCell(e,t);if(!n)return null;const o=(s.viewportY||0)+n.row;let r=null;try{i.provideLinks(o,u=>{r=u||[]})}catch{return null}if(!r||r.length===0)return null;const a=Math.max(1,this.terminal.cols||1),h=o*a+n.col;return r.find(u=>{const m=u?.range?.start,c=u?.range?.end;return!m||!c?!1:m.y*a+m.x<=h&&h<=c.y*a+c.x})||null},_tapIsOnCaretLine(e,t){const i=this.terminal?.buffer?.active;if(!i?.getLine)return!1;const s=this._clientPointToCell(e,t);if(!s)return!1;const n=Math.max(1,this.terminal.rows||1),o=Math.max(0,Math.min(n-1,i.cursorY||0)),r=s.row-1;if(r===o)return!0;let a=o;for(;a>0&&i.getLine(i.viewportY+a)?.isWrapped;)a--;let h=o;for(;h+1<n&&i.getLine(i.viewportY+h+1)?.isWrapped;)h++;return r>=a&&r<=h},_activateTerminalLinkAtPoint(e,t){const i=this._terminalLinkAtPoint(e,t);if(!i||typeof i.activate!="function")return!1;try{i.activate(null,i.text)}catch(s){return console.warn("[LinkProvider] tap activation failed:",s),!1}return!0},_installTouchSelectionFocusGuard(){const e=this.terminal?.textarea;!e||e._codemanSelectionFocusGuard||(e._codemanSelectionFocusGuard=!0,e.addEventListener("focus",()=>{this._touchSelectionFocusGuarded()&&this._blurMobileTerminalInput()}))},_touchSelectionFocusGuarded(){return this._touchSelecting?!0:performance.now()<(this._touchSelectionFocusGuardUntil||0)},_armTouchSelectionFocusGuard(){this._touchSelectionFocusGuardUntil=performance.now()+(window.CodemanTerminalInput?.TOUCH_SELECT_FOCUS_GUARD_MS||800)},_touchSelectionCellAt(e,t){const i=this._clientPointToCell(e,t),s=this.terminal?.buffer?.active;return!i||!s?null:{col:i.col-1,row:(s.viewportY||0)+i.row-1}},_touchSelectionLogicalLine(e){const t=this.terminal?.buffer?.active,i=Math.max(1,this.terminal?.cols||1);return!t||typeof window.CodemanTerminalLines?.terminalLogicalLine!="function"?null:window.CodemanTerminalLines.terminalLogicalLine(t,e,i)},_touchSelectionWordAt(e){const t=Math.max(1,this.terminal?.cols||1),i=this._touchSelectionLogicalLine(e.row);if(!i)return null;const s=i.cellToOffset(e.row,e.col);if(s<0)return null;const n=i.text[s];if(!n||!n.trim())return null;let o=s;for(;o>0&&i.text[o-1]&&i.text[o-1].trim();)o--;let r=s;for(;r+1<i.text.length&&i.text[r+1]&&i.text[r+1].trim();)r++;const a=i.offsetToCell(o),h=i.offsetToCell(r),u=a.row*t+a.col,m=h.row*t+h.col-u+1;return m>0?{index:u,length:m}:null},_applyTouchSelection(e,t){const i=Math.max(1,this.terminal?.cols||1);t<=0||this.terminal?.select?.(e%i,Math.floor(e/i),t)},_beginTouchSelection(e,t){const i=this._touchSelectionCellAt(e,t);if(!i)return!1;const s=this._touchSelectionWordAt(i);if(!s)return!1;this._blurMobileTerminalInput(),this._touchSelectionAnchor=s,this._touchSelecting=!0,this._touchSelectionActive=!0,this._suppressTrustedTapMouseEvents(),this._armTouchSelectionFocusGuard(),this._applyTouchSelection(s.index,s.length);try{navigator.vibrate?.(15)}catch{}return this._showTouchSelectionBar(),!0},_extendTouchSelection(e,t){const i=this._touchSelectionAnchor,s=this._touchSelectionCellAt(e,t);if(!i||!s)return;const n=Math.max(1,this.terminal?.cols||1),o=s.row*n+s.col,r=Math.min(i.index,o),a=Math.max(i.index+i.length,o+1);this._applyTouchSelection(r,a-r),this._armTouchSelectionFocusGuard(),this._positionTouchSelectionBar()},_endTouchSelectionGesture(){this._touchSelecting=!1,this._suppressTrustedTapMouseEvents(),this._armTouchSelectionFocusGuard(),this._positionTouchSelectionBar(),this._flushAutoCopySelection()},_selectTouchSelectionLine(){const e=this._touchSelectionAnchor,t=Math.max(1,this.terminal?.cols||1);if(!e)return;const i=this._touchSelectionLogicalLine(Math.floor(e.index/t));if(!i)return;const n=(this.terminal?.buffer?.active?.getLine(i.endRow)?.translateToString(!0)||"").length,o=i.startRow*t,r=i.endRow*t+Math.max(0,n-1)-o+1;r<=0||(this._touchSelectionAnchor={index:o,length:r},this._applyTouchSelection(o,r),this._positionTouchSelectionBar(),this._flushAutoCopySelection())},async _copyTouchSelection(){const e=await this.copyTerminalSelection();return this._clearTouchSelection(),typeof MobileDetection<"u"&&MobileDetection.isTouchDevice?.()&&this._blurMobileTerminalInput(),e},_clearTouchSelection(){this._touchSelecting=!1,this._touchSelectionActive=!1,this._touchSelectionAnchor=null,this.terminal?.clearSelection?.(),this._hideTouchSelectionBar()},_ensureTouchSelectionBar(){if(this._touchSelectionBar?.isConnected)return this._touchSelectionBar;const e=document.getElementById("terminalContainer");if(!e)return null;const t=document.createElement("div");return t.className="term-select-bar",t.setAttribute("role","toolbar"),t.innerHTML='<button type="button" class="term-select-btn" data-act="copy">Copy</button><button type="button" class="term-select-btn" data-act="line">Line</button><button type="button" class="term-select-btn term-select-btn--close" data-act="close" aria-label="Clear selection">\u2715</button>',t.addEventListener("click",i=>{const s=i.target?.closest?.("[data-act]")?.dataset?.act;s&&(i.preventDefault(),i.stopPropagation(),s==="copy"?this._copyTouchSelection():s==="line"?this._selectTouchSelectionLine():this._clearTouchSelection())}),e.appendChild(t),this._touchSelectionBar=t,t},_showTouchSelectionBar(){const e=this._ensureTouchSelectionBar();e&&(e.classList.add("visible"),this._positionTouchSelectionBar())},_hideTouchSelectionBar(){this._touchSelectionBar?.classList.remove("visible")},_positionTouchSelectionBar(){const e=this._touchSelectionBar,t=document.getElementById("terminalContainer"),i=this.terminal?.element?.querySelector(".xterm-screen"),s=this.terminal?._core?._renderService?.dimensions?.css?.cell,n=this.terminal?.getSelectionPosition?.(),o=this.terminal?.buffer?.active;if(!e||!t||!i||!s?.height||!n||!o)return;const r=i.getBoundingClientRect(),a=t.getBoundingClientRect(),h=l=>l-(o.viewportY||0),u=r.top-a.top+h(n.start.y)*s.height,m=r.top-a.top+(h(n.end.y)+1)*s.height,c=e.offsetHeight||36,f=6;let E=u-c-f;E<0&&(E=m+f),E=Math.max(0,Math.min(E,a.height-c));const T=r.left-a.left+n.start.x*(s.width||8),y=e.offsetWidth||150;e.style.top=`${Math.round(E)}px`,e.style.left=`${Math.round(Math.max(0,Math.min(T,a.width-y)))}px`},showWelcome(){if(this.shouldUseMobileOverview?.()){const t=document.getElementById("welcomeOverlay");t&&t.classList.remove("visible"),this.hideHomeSessions?.(),this.showMobileOverview(),this._updateCjkInputState?.();return}this.hideMobileOverview?.();const e=document.getElementById("welcomeOverlay");e&&(e.classList.add("visible"),this.loadTunnelStatus(),this.applyWelcomeCliVisibility(),this.loadHistorySessions(),this.initSearchPanel(),this.showHomeSessions?.()),this._updateCjkInputState?.()},hideWelcome(){this.hideMobileOverview?.(),this.hideHomeSessions?.();const e=document.getElementById("welcomeOverlay");e&&e.classList.remove("visible");const t=document.getElementById("welcomeQr");t&&(clearTimeout(this._welcomeQrShrinkTimer),t.classList.remove("expanded")),this._updateCjkInputState?.()},async _fetchHistorySessions(){const i=(await(await fetch("/api/history/sessions")).json()).data?.sessions||[];if(i.length===0)return[];const s=new Map;for(const o of i){const r=o.projectKey||o.workingDir;s.has(r)||s.set(r,[]),s.get(r).push(o)}const n=[];for(const[,o]of s)n.push(...o.slice(0,3));return n.sort((o,r)=>new Date(r.lastModified)-new Date(o.lastModified)),n},async _fetchUnifiedSessions(e=60){const t=await fetch("/api/sessions/unified?limit="+e),i=await t.json().catch(()=>null);if(!t.ok||!i||i.success===!1||!i.data)throw new Error(i?.error||`unified sessions request failed (HTTP ${t.status})`);return i.data.sessions||[]},_worktreeLabel(e){const t=e&&e.worktreeName;if(!t)return"";let i=e.gitBranch||"";return(i===t||i===`worktree-${t}`)&&(i=""),i.length>24&&(i=i.slice(0,23)+"\u2026"),"\u2442 "+[t,i].filter(Boolean).join(" \xB7 ")},_resolveCaseLabel(e,t){if(!e)return"";let i=null;for(const s of t||[])if(!(!s||!s.path)){if(e===s.path)return`#${s.name}`;if(e.startsWith(s.path+"/")){const n=s.path.length;(!i||n>i.len)&&(i={name:s.name,suffix:e.slice(n),len:n})}}return i?`#${i.name}${i.suffix}`:e.split("/").pop()||e},_shortenHomePath(e){return(e||"").replace(/^\/(?:home|Users)\/[^/]+(?=\/|$)/,"~")},_buildHistoryItem(e,t,i){const s=i?.showViewAll!==!1,n=typeof e.sizeBytes=="number",o=n?e.sizeBytes<1024?`${e.sizeBytes}B`:e.sizeBytes<1048576?`${(e.sizeBytes/1024).toFixed(0)}K`:`${(e.sizeBytes/1048576).toFixed(1)}M`:"",r=typeof e.lastActivityAt=="number"?e.lastActivityAt:e.lastModified?Date.parse(e.lastModified):NaN;let a="";if(!Number.isNaN(r)){const b=new Date(r);a=b.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+b.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1})}const h=this._shortenHomePath(e.workingDir),u=this._resolveCaseLabel(e.workingDir,t),m=Array.isArray(e.sources)&&e.sources.includes("live"),c=e.pinned===!0,f=document.createElement("div");f.className="history-item"+(c?" is-pinned":""),f.title=e.workingDir||"";const E=document.createElement("div");E.className="history-item-main",E.addEventListener("click",i?.onActivate||(()=>{m&&this.sessions.has(e.sessionId)?this.selectSession(e.sessionId):this.resumeHistorySession(e.claudeSessionId||e.sessionId,e.workingDir||"",e.name,e.mode,e.resumeId)}));const T=document.createElement("div");T.className="history-item-text";const y=document.createElement("span");if(y.className="history-item-title",c){const b=document.createElement("span");b.className="history-item-pin",b.textContent="\u{1F4CC}",b.setAttribute("aria-label","Pinned"),b.title="Pinned",y.appendChild(b)}y.appendChild(document.createTextNode(this._historyRowLabel(e,h)));const l=document.createElement("div");if(l.className="history-item-badges",e.mode){const b=document.createElement("span");b.className="history-item-badge history-item-badge-mode",b.textContent=e.mode,l.appendChild(b)}const p=this._worktreeLabel(e);if(p){const b=document.createElement("span");b.className="history-item-badge history-item-badge-worktree",b.textContent=p,b.title=e.worktreeRepo?`worktree of ${e.worktreeRepo}`:p,l.appendChild(b)}if(m){const b=document.createElement("span");b.className="history-item-badge history-item-badge-live",b.textContent="LIVE",l.appendChild(b)}const d=document.createElement("span");d.className="history-item-subtitle",u.startsWith("#")&&d.classList.add("is-case"),d.textContent=u,T.append(y),l.childElementCount>0&&T.append(l),T.append(d);const S=document.createElement("span");S.className="history-item-meta",S.textContent=a;const g=document.createElement("button");g.className="history-item-expand",g.type="button",g.setAttribute("aria-haspopup","menu"),g.setAttribute("aria-label","Session actions"),g.setAttribute("aria-expanded","false"),g.textContent="\u22EF",E.append(T,S,g);const _=document.createElement("div");_.className="history-item-detail",_.hidden=!0;const C=document.createElement("div");C.className="history-detail-row";const w=document.createElement("span");w.className="history-detail-label",w.textContent="Prompt";const L=document.createElement("span");L.className="history-detail-value history-detail-prompt",L.textContent=e.firstPrompt||"(no prompt captured)",C.append(w,L);let M=null;if(e.lastPrompt&&e.lastPrompt!==e.firstPrompt){M=document.createElement("div"),M.className="history-detail-row";const b=document.createElement("span");b.className="history-detail-label",b.textContent="Last prompt";const v=document.createElement("span");v.className="history-detail-value history-detail-prompt",v.textContent=e.lastPrompt,M.append(b,v)}const k=document.createElement("div");k.className="history-detail-row";const R=document.createElement("span");R.className="history-detail-label",R.textContent="Path";const P=document.createElement("span");P.className="history-detail-value history-detail-path",P.textContent=h,k.append(R,P);const F=document.createElement("div");F.className="history-detail-row history-detail-meta";const A=[];if(a&&A.push(a),n&&A.push(o),A.push(e.sessionId.slice(0,8)),F.textContent=A.join(" \xB7 "),_.append(C),M&&_.append(M),_.append(k,F),s&&e.projectKey){const b=document.createElement("div");b.className="history-detail-row history-detail-actions";const v=document.createElement("button");v.type="button",v.className="history-view-all-btn",v.textContent="View all in this folder",v.addEventListener("click",I=>{I.stopPropagation(),this.openFolderHistoryModal(e.projectKey,e.workingDir,t)}),b.appendChild(v),_.appendChild(b)}return g.addEventListener("click",b=>{b.stopPropagation(),b.preventDefault(),this._openSessionRowMenu(b.currentTarget,e,t,f,_)}),f.append(E,_),f},_openSessionRowMenu(e,t,i,s,n){if(this._openRowMenuClose)try{this._openRowMenuClose()}catch{}const o=Array.isArray(t.sources)&&t.sources.includes("live")&&this.sessions.has(t.sessionId),r=document.createElement("div");r.className="session-row-menu",r.setAttribute("role","menu");let a=null,h=null,u=null;const m=()=>{document.removeEventListener("mousedown",a,!0),document.removeEventListener("keydown",h,!0),window.removeEventListener("scroll",u,!0),window.removeEventListener("resize",u,!0);try{r.remove()}catch{}this._openRowMenuEl===r&&(this._openRowMenuEl=null,this._openRowMenuClose=null)},c=(d,S,g)=>{const _=document.createElement("button");_.type="button",_.className="session-row-menu-item",_.setAttribute("role","menuitem");const C=document.createElement("span");if(C.className="session-row-menu-label",C.textContent=d,_.appendChild(C),g&&g.sublabel){const w=document.createElement("span");w.className="session-row-menu-sublabel",w.textContent=g.sublabel,_.appendChild(w)}_.addEventListener("click",async w=>{w.stopPropagation(),w.preventDefault(),await S()}),r.appendChild(_)};c(o?"Switch to session":"Resume session",()=>{o?this.selectSession(t.sessionId):this.resumeHistorySession(t.claudeSessionId||t.sessionId,t.workingDir||"",t.name,t.mode,t.resumeId),this.closeSessionManager?.(),m()});const f=t.pinned===!0;c(f?"Unpin session":"Pin to top",async()=>{await this._setSessionPinned(t.sessionId,!f)?(t.pinned=!f,this.showToast(f?"Unpinned":"Pinned to top","success")):this.showToast("Pin failed","error"),m()}),o&&c("Open folder",()=>{this.selectSession(t.sessionId),this.loadFileBrowser?.(t.sessionId),this.closeSessionManager?.(),m()}),t.workingDir&&c("Copy path",async()=>{const d=await this._copyText(t.workingDir);this.showToast(d?"Path copied":"Copy failed",d?"success":"error"),m()}),c("Show details",()=>{const d=s.classList.toggle("expanded");n.hidden=!d,e.setAttribute("aria-expanded",d?"true":"false"),m()}),document.body.appendChild(r);const E=e.getBoundingClientRect(),T=r.getBoundingClientRect(),y=4;let l=E.bottom+y;l+T.height>window.innerHeight&&E.top-y-T.height>=0&&(l=E.top-y-T.height);let p=E.right-T.width;p<y&&(p=y),p+T.width>window.innerWidth-y&&(p=Math.max(y,window.innerWidth-y-T.width)),r.style.top=`${Math.max(y,l)}px`,r.style.left=`${p}px`,a=d=>{r.contains(d.target)||e.contains(d.target)||m()},h=d=>{d.key==="Escape"&&(d.stopPropagation(),m())},u=()=>m(),document.addEventListener("mousedown",a,!0),document.addEventListener("keydown",h,!0),window.addEventListener("scroll",u,!0),window.addEventListener("resize",u,!0),this._openRowMenuEl=r,this._openRowMenuClose=m},async _setSessionPinned(e,t){try{const i=await fetch(`/api/sessions/${encodeURIComponent(e)}/pin`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({pinned:t})});return i.ok?(await i.json())?.success===!0:!1}catch(i){return console.error("[_setSessionPinned]",i),!1}},_HISTORY_INITIAL_COUNT:10,_HISTORY_FETCH_LIMIT:200,_HISTORY_SORT_KEY:"codeman:historySort",async loadHistorySessions(){const e=document.getElementById("historySessions"),t=document.getElementById("historyList");if(!(!e||!t))try{const i=Array.isArray(this.cases)&&this.cases.length>0?Promise.resolve(this.cases):fetch("/api/cases").then(o=>o.ok?o.json():null).then(o=>o?.data||[]).catch(()=>[]),[s,n]=await Promise.all([this._fetchUnifiedSessions(this._HISTORY_FETCH_LIMIT),i]);if(s.length===0){e.style.display="none";return}this._historyAll=s,this._historyCases=n,this._wireHistoryControls(),this._renderHistoryList(),e.style.display=""}catch(i){console.error("[loadHistorySessions]",i),e.style.display="none"}},_wireHistoryControls(){if(this._historyControlsWired)return;const e=document.getElementById("historyFilter"),t=document.getElementById("historySort");if(!(!e&&!t)){if(this._historyControlsWired=!0,t)try{const i=localStorage.getItem(this._HISTORY_SORT_KEY);i&&Array.from(t.options).some(s=>s.value===i)&&(t.value=i)}catch{}e&&(e.addEventListener("input",()=>this._renderHistoryList()),e.addEventListener("keydown",i=>{i.key==="Escape"&&e.value&&(i.stopPropagation(),e.value="",this._renderHistoryList())})),t&&t.addEventListener("change",()=>{try{localStorage.setItem(this._HISTORY_SORT_KEY,t.value)}catch{}this._renderHistoryList()})}},_historyRowMatches(e,t,i){return[e.name,e.workingDir,this._resolveCaseLabel(e.workingDir,i),e.firstPrompt,e.lastPrompt,e.sessionId].some(n=>typeof n=="string"&&n.toLowerCase().includes(t))},_historyRowLabel(e,t){return e.name||e.firstPrompt||t||""},_sortHistoryRows(e,t){const n=t==="name"?a=>this._historyRowLabel(a,this._shortenHomePath(a.workingDir)).toLowerCase():a=>((a.workingDir||"").split("/").pop()||"").toLowerCase(),o=t==="recent"?e.slice():e.slice().sort((a,h)=>n(a).localeCompare(n(h),void 0,{sensitivity:"base",numeric:!0})),r=o.filter(a=>a.pinned);return r.length===0?o:r.concat(o.filter(a=>!a.pinned))},_renderHistoryList(){const e=document.getElementById("historyList");if(!e)return;const t=this._historyAll||[],i=this._historyCases||[],s=document.getElementById("historyCount"),n=(document.getElementById("historyFilter")?.value||"").trim().toLowerCase(),o=document.getElementById("historySort")?.value||"recent",r=n?t.filter(c=>this._historyRowMatches(c,n,i)):t,a=this._sortHistoryRows(r,o),h=!!this._historyExpanded||n.length>0,u=h?a:a.slice(0,this._HISTORY_INITIAL_COUNT);if(e.replaceChildren(),e.classList.toggle("expanded",h),a.length===0){const c=document.createElement("div");c.className="history-empty",c.textContent=`No conversations match "${n}"`,e.appendChild(c)}for(const c of u)e.appendChild(this._buildHistoryItem(c,i));const m=a.length-u.length;if(m>0){const c=document.createElement("button");c.className="history-show-more",c.textContent=`Show ${m} more`,c.addEventListener("click",()=>{this._historyExpanded=!0,this._renderHistoryList()}),e.appendChild(c)}else if(h&&!n&&a.length>this._HISTORY_INITIAL_COUNT){const c=document.createElement("button");c.className="history-show-more",c.textContent="Show less",c.addEventListener("click",()=>{this._historyExpanded=!1,this._renderHistoryList(),e.scrollTop=0}),e.appendChild(c)}s&&(s.textContent=n?`${a.length} of ${t.length}`:a.length>u.length?`${u.length} of ${a.length}`:String(a.length))},_FOLDER_HISTORY_PAGE_SIZE:20,openFolderHistoryModal(e,t,i){this._closeFolderHistoryModal();const s=document.createElement("div");s.className="modal active folder-history-modal",s.id="folderHistoryModal";const n=document.createElement("div");n.className="modal-backdrop",n.addEventListener("click",()=>this._closeFolderHistoryModal());const o=document.createElement("div");o.className="modal-content modal-lg";const r=document.createElement("div");r.className="modal-header";const a=document.createElement("h3");a.textContent="Folder History";const h=document.createElement("div");h.className="folder-history-subtitle",h.textContent=this._shortenHomePath(t);const u=document.createElement("button");u.className="modal-close",u.setAttribute("aria-label","Close"),u.innerHTML="×",u.addEventListener("click",()=>this._closeFolderHistoryModal()),r.append(a,u);const m=document.createElement("div");m.className="modal-body";const c=document.createElement("div");c.className="folder-history-list",c.setAttribute("data-loading","true"),c.textContent="Loading...",m.append(h,c),o.append(r,m),s.append(n,o),document.body.appendChild(s),this._folderHistoryState={projectKey:e,workingDir:t,cases:i||[],offset:0,total:null,list:c},this._folderHistoryEscHandler=f=>{f.key==="Escape"&&this._closeFolderHistoryModal()},document.addEventListener("keydown",this._folderHistoryEscHandler),this._loadFolderHistoryPage()},async _loadFolderHistoryPage(){const e=this._folderHistoryState;if(!e)return;const{projectKey:t,cases:i,list:s}=e,n=this._FOLDER_HISTORY_PAGE_SIZE,o=e.offset,r=s.querySelector(".folder-history-more");r&&r.remove(),o===0&&(s.replaceChildren(),s.removeAttribute("data-loading"));try{const a=`/api/history/sessions?projectKey=${encodeURIComponent(t)}&offset=${o}&limit=${n}`,u=await(await fetch(a)).json(),m=u.data?.sessions||[];if(e.total=typeof u.data?.total=="number"?u.data.total:m.length+o,o===0&&m.length===0){const c=document.createElement("div");c.className="folder-history-empty",c.textContent="No conversations found in this folder.",s.appendChild(c);return}for(const c of m)s.appendChild(this._buildHistoryItem(c,i,{showViewAll:!1}));if(e.offset=o+m.length,e.offset<e.total){const c=e.total-e.offset,f=document.createElement("button");f.className="history-show-more folder-history-more",f.textContent=`Show ${Math.min(n,c)} more (${c} remaining)`,f.addEventListener("click",()=>this._loadFolderHistoryPage()),s.appendChild(f)}}catch(a){console.error("[loadFolderHistoryPage]",a);const h=document.createElement("div");h.className="folder-history-empty",h.textContent="Failed to load folder history.",s.appendChild(h)}},_closeFolderHistoryModal(){const e=document.getElementById("folderHistoryModal");e&&e.remove(),this._folderHistoryEscHandler&&(document.removeEventListener("keydown",this._folderHistoryEscHandler),this._folderHistoryEscHandler=null),this._folderHistoryState=null},_resolveResumeName(e,t){if(typeof e=="string"&&e.trim())return e;const i=(t||"").split("/").pop()||"session";let s=1;for(const[,n]of this.sessions){const o=n.name&&n.name.match(/^w(\d+)-/);if(o){const r=parseInt(o[1]);r>=s&&(s=r+1)}}return`w${s}-${i}`},async resumeHistorySession(e,t,i,s,n){document.getElementById("runModeMenu")?.classList.remove("active"),this._closeFolderHistoryModal();try{this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Resuming conversation ${e.slice(0,8)}...\x1B[0m`);const o=this._resolveResumeName(i,t),a=(this.cases||[]).find(S=>S.path===t)?.name||t.split("/").pop()||"",h=this.loadAppSettingsFromStorage(),u=this.buildEnvOverrides(this.getCaseSettings(a),h),m=this.getEffortSetting(h),c=s||"claude",f={opencode:"openCodeConfig",pi:"piConfig",grok:"grokConfig",omp:"ompConfig"}[c],E=c==="codex"?n:void 0,T=f?{[f]:{continueSession:!0}}:c==="deepseek"?{deepSeekConfig:{resumeSession:!0}}:E?{codexConfig:{resumeSessionId:E}}:{},y=!!f||c==="deepseek"||!!E,p=await(await fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:t,name:o,mode:c,...c==="claude"?{resumeSessionId:e}:{},...T,...Object.keys(u).length>0?{envOverrides:u}:{},...m?{effort:m}:{}})})).json();if(!p.success)throw new Error(p.error);const d=p.data.session.id;await fetch(`/api/sessions/${d}/interactive`,{method:"POST"}),c!=="claude"&&y&&e!==d&&fetch(`/api/sessions/${e}?killMux=true`,{method:"DELETE"}).catch(()=>{}),this.terminal.writeln(`\x1B[90m Session ${o} ready\x1B[0m`),await this.selectSession(d),this.terminal.focus()}catch(o){this.terminal.writeln(`\x1B[1;31m Error: ${o.message}\x1B[0m`)}},isTerminalAtBottom(){if(!this.terminal)return!0;const e=this.terminal.buffer.active;return e.viewportY>=e.baseY-2},_noteTerminalUserScroll(e){e<0?this._lastUserScrollUpAt=performance.now():this.isTerminalAtBottom()&&(this._lastUserScrollUpAt=null)},_maybeLoadMoreHistoryOnScroll(e){e>=0||this.terminal?.buffer?.active?.viewportY===0&&this._maybeRefetchFullHistory?.()},_estimateReplayRows(e,t){if(typeof e!="string"||!e)return 0;const i=t>0?t:80,s=e.replace(window.CodemanTerminalInput.REPLAY_ESCAPE_RE,"");let n=0;for(const o of s.split(`
|
|
2
|
-
`)){const r=o.endsWith("\r")?o.length-1:o.length;n+=r>i?Math.ceil(r/i):1}return n},_replayWouldShrinkBuffer(e){const t=this.terminal,i=t?.buffer?.active?.length||0;if(!i)return!1;const s=t?.rows||24;return this._estimateReplayRows(e,t?.cols)+s<i},_smoothScrollBy(e){if(!e||(this._smoothScrollPending=(this._smoothScrollPending||0)+e,this._smoothScrollSession=this.activeSessionId,this._smoothScrollFrame))return;const t=()=>{this._smoothScrollFrame=null;const i=this._smoothScrollPending||0;if(!i)return;if(this.activeSessionId!==this._smoothScrollSession){this._smoothScrollPending=0;return}if(Math.abs(i)<1)return;const s=i*.22,n=i>0?Math.max(1,Math.floor(s)):Math.min(-1,Math.ceil(s));this._smoothScrollPending=i-n,this.terminal.scrollLines(n),this._maybeLoadMoreHistoryOnScroll(n),Math.abs(this._smoothScrollPending)>=1&&(this._smoothScrollFrame=requestAnimationFrame(t))};this._smoothScrollFrame=requestAnimationFrame(t)},_forwardScrollToApp(e,t,i){this._terminalViewportAtBottom()||this.terminal.scrollToBottom(),this._sendSyntheticSgrWheel(e,t,i)},_hasRecentUserScrollUp(){return typeof this._lastUserScrollUpAt!="number"?!1:performance.now()-this._lastUserScrollUpAt<window.CodemanTerminalInput.USER_SCROLL_STICKY_SUPPRESS_MS},batchTerminalWrite(e){if(this._isLoadingBuffer){this._loadBufferQueue&&this._loadBufferQueue.push(e);return}if(this.writeFrameScheduled||(this._wasAtBottomBeforeWrite=this.isTerminalAtBottom()),(this.activeSessionId?this.sessions.get(this.activeSessionId):null)?.flickerFilterEnabled??!1){if(e.includes("\x1B[2J")||e.includes("\x1B[H\x1B[J")||e.includes("\x1B[H")&&e.includes("\x1B[?25l")){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(this.flickerFilterActive){this.flickerFilterBuffer+=e;return}}this.pendingWrites.push(e),this._scheduleTerminalWriteFlush()},_scheduleTerminalWriteFlush(){this._terminalWriteInFlight||this.writeFrameScheduled||this.pendingWrites.length===0||(this.writeFrameScheduled=!0,this._safeYield(()=>{this.writeFrameScheduled=!1,this.flushPendingWrites()}))},flushFlickerBuffer(){this.flickerFilterBuffer&&(this.pendingWrites.push(this.flickerFilterBuffer),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this._scheduleTerminalWriteFlush())},_flushLocalEchoPending(){const e=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),e&&(this._pendingInput+=e)},_updateLocalEchoState(){const e=this.loadAppSettingsFromStorage(),t=this.activeSessionId?this.sessions.get(this.activeSessionId):null,i=e.localEchoEnabled??MobileDetection.isTouchDevice(),s=!!(i&&t);this._localEchoEnabled&&!s&&this._localEchoOverlay?.clear(),this._localEchoEnabled=s,this._localEchoOverlay&&t&&(t.mode==="opencode"?this._localEchoOverlay.setPrompt({type:"custom",offset:3,find:o=>{try{const r=o.buffer.active,a=r.cursorY,h=r.getLine(r.viewportY+a);if(!h)return null;const m=h.translateToString(!0).indexOf("\u2503");return m>=0?{row:a,col:m}:null}catch{return null}}}):t.mode==="shell"||t.mode==="codex"?(this._localEchoOverlay.clear(),this._localEchoEnabled=!1):this._localEchoOverlay.setPrompt({type:"custom",offset:0,find:o=>{try{const r=o.buffer.active;for(let a=o.rows-1;a>=0;a--){const h=r.getLine(r.viewportY+a);if(!h)continue;const m=h.translateToString(!0).lastIndexOf("\u276F");if(m>=0)return{row:a,col:m+2}}return{row:Math.max(0,Math.min(o.rows-1,r.cursorY)),col:Math.max(0,Math.min(o.cols-1,r.cursorX))}}catch{return null}}}));let n="off";t&&i&&(t.mode==="codex"?n="predict":t.mode!=="shell"&&(n="buffer")),this._localEchoPolicy=n,n!=="predict"&&this._predictiveEcho?.clearPredictions()},_predictHookOnData(e){if(!(this._localEchoPolicy!=="predict"||!this._predictiveEcho))try{const t=window.CodemanTerminalInput.classifyPredictInput(e);t==="char"?this._predictiveEcho.predictChar(e):t==="backspace"?this._predictiveEcho.predictBackspace():this._predictiveEcho.clearPredictions()}catch{}},_handleCjkInput(e){if(!this.activeSessionId){_crashDiag.log(`CJK send DROP no-session len=${e.length}`);return}typeof KeyboardAccessoryBar<"u"&&KeyboardAccessoryBar.isCtrlArmed?.()&&(e=KeyboardAccessoryBar.consumeCtrl(e)),this._localEchoPolicy==="predict"&&this._predictiveEcho?.clearPredictions(),_crashDiag.log(`CJK send\u2192${this.activeSessionId.slice(0,8)} len=${e.length}`),this._sendInputAsync(this.activeSessionId,e)},flushPendingWrites(){if(this._terminalWriteInFlight||this.pendingWrites.length===0||!this.terminal)return;const e=performance.now(),t=this.pendingWrites.join("");this.pendingWrites=[];const i=t.length;i>16384&&_crashDiag.log(`FLUSH: ${(i/1024).toFixed(0)}KB`);const n=(this.activeSessionId&&this.sessions?this.sessions.get(this.activeSessionId):null)?.mode==="codex"?32768:65536;let o=!1;const r=this.terminal.buffer?.active&&!this.isTerminalAtBottom()?this.terminal.buffer.active.viewportY:null,a=t.slice(0,n);i>n&&(this.pendingWrites.push(t.slice(n)),o=!0),this._terminalWriteInFlight=!0,this._terminalWriteInFlightBytes=a.length;try{this.terminal.write(a,()=>{this._terminalWriteInFlight=!1,this._terminalWriteInFlightBytes=0,this._scheduleTerminalWriteFlush()})}catch(m){throw this._terminalWriteInFlight=!1,this._terminalWriteInFlightBytes=0,m}r!==null&&this.terminal.buffer?.active?.viewportY!==r&&typeof this.terminal.scrollToLine=="function"&&this.terminal.scrollToLine(r);const h=o?n:i,u=performance.now()-e;if((u>100||o)&&console.warn(`[CRASH-DIAG] flushPendingWrites: ${u.toFixed(0)}ms, ${(h/1024).toFixed(0)}KB written${o?", rest deferred":""} (total ${(i/1024).toFixed(0)}KB)`),this._wasAtBottomBeforeWrite&&!this._hasRecentUserScrollUp()&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const m=this._localEchoOverlay,c=this;this.terminal.write("",()=>{if(!c._tabCompletionSessionId)return;m.resetBufferDetection();const f=m.detectBufferText();f?f===c._tabCompletionBaseText?(m.undoDetection(),c._tabCompletionRetries=(c._tabCompletionRetries||0)+1,c._tabCompletionRetries>60&&(c._tabCompletionSessionId=null,c._tabCompletionRetries=0)):(c._tabCompletionSessionId=null,c._tabCompletionRetries=0,c._tabCompletionBaseText=null,c._tabCompletionFallback&&(clearTimeout(c._tabCompletionFallback),c._tabCompletionFallback=null),m.rerender()):(c._tabCompletionRetries=(c._tabCompletionRetries||0)+1,c._tabCompletionRetries>60&&(c._tabCompletionSessionId=null,c._tabCompletionRetries=0))})}},_safeYield(e){let t=!1;const i=()=>{t||(t=!0,e())};requestAnimationFrame(i),setTimeout(i,50),this._workerYield(i)},_workerYield(e){try{if(this._yieldWorker===void 0){const t="onmessage=()=>setTimeout(()=>postMessage(0),0);",i=new Blob([t],{type:"application/javascript"}),s=URL.createObjectURL(i);this._yieldWorker=new Worker(s),URL.revokeObjectURL(s),this._yieldQueue=[],this._yieldWorker.onmessage=()=>{const n=this._yieldQueue.shift();n&&n()}}if(!this._yieldWorker)return;this._yieldQueue.push(e),this._yieldWorker.postMessage(0)}catch{this._yieldWorker=null}},scrollToLastNonEmptyLine(){if(!this.terminal?.buffer?.active){this.terminal?.scrollToBottom?.();return}const e=this.terminal.buffer.active,t=e.length;let i=-1;for(let s=t-1;s>=0;s--)if(e.getLine(s)?.translateToString(!0).trim()){i=s;break}if(i>=0&&typeof this.terminal.scrollToLine=="function"){let s=Math.max(0,i-this.terminal.rows+2);const n=Math.max(0,i);for(;s<n&&!e.getLine(s)?.translateToString(!0).trim();)s++;this.terminal.scrollToLine(s)}else this.terminal.scrollToBottom()},chunkedTerminalWrite(e,t=TERMINAL_CHUNK_SIZE,i){const s=++this._chunkedWriteGen,n=this._beginBufferLoad(i);return new Promise(o=>{const r=(f=this._chunkedWriteGen===s)=>({parsedAt:performance.now(),bufferLength:this.terminal?.buffer?.active?.length??0,completed:f});if(!e||e.length===0){this._finishBufferLoad(n),o(r());return}const a=e.replace(DEC_SYNC_STRIP_RE,"");if(a.length<=t){this.terminal.write(a,()=>o(r())),this._finishBufferLoad(n);return}let h=0;const u=performance.now();let m=0;const c=()=>{if(this._chunkedWriteGen!==s){o(r(!1));return}const f=a.slice(h,h+t);if(h+=f.length,m++,this.terminal.write(f),h>=a.length){this.terminal.write("",()=>{const E=r(),T=E.parsedAt-u;console.log(`[CRASH-DIAG] chunkedTerminalWrite complete: ${a.length} bytes in ${m} chunks, ${T.toFixed(0)}ms parsed`),o(E)}),this._finishBufferLoad(n);return}this._safeYield(c)};this._safeYield(c)})},_beginBufferLoad(e){this._bufferLoadSeq===void 0&&(this._bufferLoadSeq=0);const t=e===void 0?`buffer-${++this._bufferLoadSeq}`:e;return this._bufferLoadOwner=t,this._isLoadingBuffer=!0,this._loadBufferQueue=[],t},_finishBufferLoad(e,t){if(e!==void 0&&this._bufferLoadOwner!==e)return!1;const i=this._loadBufferQueue;if(this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._bufferLoadOwner=null,t?.flushQueued&&i&&i.length)for(const s of i)this.batchTerminalWrite(s);return!0},clearTerminal(){this.terminal.clear()},insertTerminalText(e){!this.activeSessionId||!e||(this._localEchoPolicy==="predict"&&this._predictiveEcho?.clearPredictions(),this._localEchoEnabled&&this._localEchoOverlay&&!this._echoPassthroughSessions?.has(this.activeSessionId)?this._localEchoOverlay.appendText(e):this.sendInput(e).catch(()=>{}),this.terminal?.focus())},clearTerminalInput(){if(this.activeSessionId){if(typeof CjkInput<"u"&&CjkInput.clear(),this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._pendingInput="",this._localEchoPolicy==="predict"&&this._predictiveEcho?.clearPredictions(),this._localEchoEnabled&&this._localEchoOverlay){const e=this._localEchoOverlay.getFlushed?.()||{count:0,text:""};this._localEchoOverlay.clear(),this._localEchoOverlay.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),e.count>0&&this.sendInput("\x7F".repeat(e.count)).catch(()=>{})}else this.sendInput("").catch(()=>{});this.showToast?.("Input cleared","success"),this.terminal?.focus()}},async restoreTerminalSize(){if(!this.activeSessionId){this.showToast("No active session","warning");return}if(!this.isSoloWindow&&this.detachedSessions?.has(this.activeSessionId)){this.showToast("This session is sized by its own window","warning");return}const e=this.getTerminalDimensions();if(!e){this.showToast("Could not determine terminal size","error");return}try{await this.sendResize(this.activeSessionId,{force:!0}),this.showToast(`Terminal restored to ${e.cols}x${e.rows}`,"success")}catch(t){console.error("Failed to restore terminal size:",t),this.showToast("Failed to restore terminal size","error")}},sendPendingCtrlL(e){},shouldCopyTerminalSelectionFromShortcut(e){if(!e||e.type!=="keydown"||!e.ctrlKey&&!e.metaKey&&!e.altKey)return!1;const i=typeof this.getShortcutRegistry=="function"&&typeof this.matchesShortcutEvent=="function"?this.getShortcutRegistry().find(s=>s.id==="copy-selection"):null;return i?!i.disabled&&this.matchesShortcutEvent(e,i):!e.altKey&&(e.key||"").toLowerCase()==="c"},async copyTerminalSelection(e){const t=e??(this.terminal.hasSelection?.()?this.terminal.getSelection():"");if(!t)return!1;const i=await this._copyText(t);return i?(this.terminal.clearSelection?.(),this.showToast("Copied to clipboard","success")):this.showToast("Failed to copy","error"),this.terminal.focus(),i},_autoCopySelectionEnabled(){try{return this.loadAppSettingsFromStorage?.()?.autoCopySelection===!0}catch{return!1}},async _flushAutoCopySelection(){const e=window.CodemanAutoCopy?.decide;if(!e||!this.terminal)return;const t=this.terminal.hasSelection?.()?this.terminal.getSelection():"",i=e({enabled:this._autoCopySelectionEnabled(),text:t,lastCopied:this._autoCopyLastText,pending:!!this._autoCopyPending});if(this._autoCopyPending=!1,i==="skip")return;if(i==="too-large"){this._autoCopyNotify("Selection too large to copy automatically. Press Ctrl+C.","warning");return}this._autoCopyLastText=t;const s=document.activeElement,n=await this._copyText(t);if(s&&s!==document.activeElement&&s.isConnected&&typeof s.focus=="function")try{s.focus()}catch{}if(!n){this._autoCopyLastText="",this._autoCopyNotify("Auto Copy failed: the browser blocked clipboard access","error");return}this._autoCopyHintShown||(this._autoCopyHintShown=!0,this.showToast("Auto Copy: selection copied","success"))},_autoCopyNotify(e,t){const i=Date.now(),s=this._autoCopyNotifiedAt;s!==void 0&&i-s<1e4||(this._autoCopyNotifiedAt=i,this.showToast(e,t))},_syncMobileHelperTextareaToCursor(){if(!(!MobileDetection.isTouchDevice()||!this.terminal?.element))try{const e=this.terminal.element,t=this.terminal.element.querySelector(".xterm-cursor"),i=this.terminal.element.querySelector(".xterm-screen");if(!(e instanceof HTMLElement)||!(t instanceof HTMLElement)||!(i instanceof HTMLElement))return;const s=t.getBoundingClientRect(),n=i.getBoundingClientRect();if(!s.width&&!s.height)return;const o=Math.max(0,Math.round(s.left-n.left)),r=Math.max(0,Math.round(s.top-n.top));e.style.setProperty("--xterm-helper-left",`${o}px`),e.style.setProperty("--xterm-helper-top",`${r}px`)}catch{}},_isMobileTerminalInputFocused(){const e=document.activeElement;return e===this.terminal?.textarea||e?.classList?.contains("xterm-helper-textarea")||e?.id==="cjkInput"},_classifyMobileTerminalTap(e,t){if(!this._terminalViewportAtBottom())return"history";const i=this._clientPointToCell(e,t);if(!i||!this.terminal)return"input";const s=this.terminal.modes?.mouseTrackingMode;if(!(!!s&&s!=="none")&&!this._shouldReportMouseToCli())return"input";const o=this.terminal.buffer?.active;if(!o?.getLine)return"input";const r=Math.max(1,this.terminal.rows||1),a=[],h=[];let u=!1;for(let d=0;d<r;d++){const S=o.getLine(o.viewportY+d),g=S?.translateToString?.(!0)||"";a.push(g),h.push(!!S?.isWrapped),g.trim()&&(u=!0)}if(!u)return"input";const m=Math.max(0,Math.min(r-1,o.cursorY||0)),c=this.sessions?.get(this.activeSessionId)?.mode||"claude";let f=-1,E=!1;if(c==="opencode")a[m]?.includes("\u2503")&&(f=m);else for(let d=r-1;d>=0;d--){const S=a[d].match(/^\s*[❯›]/);if(!S)continue;const g=a[d].slice(S[0].length).trim(),_=a.some((C,w)=>w!==d&&/^\s+\d+[.)]\s/.test(C));if(/^\d+[.)]\s/.test(g)&&_){E=!0;break}f=d;break}const T=i.row-1;let y=T;for(;y>0&&h[y];)y--;let l=T;for(;l+1<r&&h[l+1];)l++;const p=a.slice(y,l+1).join("");if(c==="claude"&&/\b(?:esc to interrupt|background)\b/i.test(p)||E)return"content";if(f>=0){const d=m>=f?m:f;if(T>=f&&T<=d)return"input"}else if(T===m||T>=Math.max(0,r-window.CodemanTerminalInput.TUI_PROMPT_DEFAULT_ROWS_FROM_BOTTOM))return"input";return"content"},_blurMobileTerminalInput(){const e=document.activeElement;(e===this.terminal?.textarea||e?.classList?.contains("xterm-helper-textarea")||e?.id==="cjkInput")&&e.blur?.()},_installMobileKeyboardDismiss(){if(this._mobileKeyboardDismissHandler)return;let e=0,t=0,i=!1;this._mobileKeyboardDismissStart=s=>{if(s.touches.length!==1){i=!0;return}e=s.touches[0].clientX,t=s.touches[0].clientY,i=!1},this._mobileKeyboardDismissMove=s=>{if(i||!s.touches.length)return;const n=s.touches[0].clientX-e,o=s.touches[0].clientY-t,r=window.CodemanTerminalInput.MOBILE_KEYBOARD_DISMISS_TAP_SLOP;(Math.abs(n)>r||Math.abs(o)>r)&&(i=!0)},this._mobileKeyboardDismissHandler=s=>{if(i||!this._isMobileTerminalInputFocused())return;const n=s.target;!n||typeof n.closest!="function"||n.closest("#terminalContainer")||n.closest(window.CodemanTerminalInput.MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR)||this._blurMobileTerminalInput()},document.addEventListener("touchstart",this._mobileKeyboardDismissStart,{passive:!0}),document.addEventListener("touchmove",this._mobileKeyboardDismissMove,{passive:!0}),document.addEventListener("touchend",this._mobileKeyboardDismissHandler,{passive:!0})},_isActionableMobileTerminalTap(e,t){const i=this._clientPointToCell(e,t),s=this.terminal?.buffer?.active;if(!i||!s?.getLine)return!1;const n=Math.max(1,this.terminal.rows||1),o=[],r=[];for(let l=0;l<n;l++){const p=s.getLine(s.viewportY+l);o.push(p?.translateToString?.(!0)||""),r.push(!!p?.isWrapped)}const a=i.row-1;let h=a;for(;h>0&&r[h];)h--;let u=a;for(;u+1<n&&r[u+1];)u++;const m=o.slice(h,u+1).join(""),c=/\b(?:ctrl\+\w+|shift\+\w+|esc|enter|tab|tap)\s+to\s+(?:expand|collapse|view|open|interrupt|see)\b/i,f=Math.max(0,h-1),E=Math.min(n-1,u+1);for(let l=f;l<=E;l++)if(c.test(o[l]))return!0;const T=o.some(l=>/^\s*[❯›]\s+\d+[.)]\s/.test(l)),y=o.some(l=>/^\s+\d+[.)]\s/.test(l));return T&&y&&/^\s*(?:[❯›]\s*)?\d+[.)]\s/.test(m)},_focusMobileTerminalInput(){this._syncMobileHelperTextareaToCursor();const e=document.getElementById("cjkInput");e?.classList.contains("cjk-input-visible")?e.focus():this.terminal?.focus()},_handleMobileTerminalTap(e,t,i=null){if(!e||!this.terminal)return null;if(this._touchSelectionActive)return this._extendTouchSelection(e.clientX,e.clientY),"select";const s=i??this._classifyMobileTerminalTap(e.clientX,e.clientY),n=this._isActionableMobileTerminalTap(e.clientX,e.clientY);if(!n&&!this._tapIsOnCaretLine(e.clientX,e.clientY)&&this._activateTerminalLinkAtPoint(e.clientX,e.clientY))return"link";if(s==="history")return this._focusMobileTerminalInput(),s;const o=this.terminal.modes?.mouseTrackingMode,r=!!o&&o!=="none",a=s==="content"||t;return a&&r?this._dispatchSyntheticTerminalClick(e.clientX,e.clientY):a&&this._shouldReportMouseToCli()&&this._sendSyntheticSgrTap(e.clientX,e.clientY),s==="content"&&n?this._blurMobileTerminalInput():s==="content"&&t?this._blurMobileTerminalInput():this._focusMobileTerminalInput(),s},_dispatchSyntheticTerminalClick(e,t){const i=this.terminal?.element;if(!i||!Number.isFinite(e)||!Number.isFinite(t))return;const s={bubbles:!0,cancelable:!0,view:window,clientX:e,clientY:t,screenX:e,screenY:t,button:0,detail:1};try{i.dispatchEvent(new MouseEvent("mousedown",{...s,buttons:1})),i.dispatchEvent(new MouseEvent("mouseup",{...s,buttons:0}))}catch{}},_shouldReportMouseToCli(){const e=this.sessions?.get(this.activeSessionId),t=e?.mode||"claude";return t!=="claude"&&t!=="codex"&&t!=="gemini"?!1:e?.cliMouseTracking===!0},_terminalViewportAtBottom(){const e=this.terminal?.buffer?.active;return!e||e.viewportY>=e.baseY},_clientPointToCell(e,t){if(!this.terminal||!Number.isFinite(e)||!Number.isFinite(t))return null;const i=this.terminal.element?.querySelector(".xterm-screen"),s=this.terminal._core?._renderService?.dimensions?.css?.cell;if(!i||!s?.width||!s?.height)return null;const n=i.getBoundingClientRect(),o=Math.max(1,Math.min(this.terminal.cols,Math.floor((e-n.left)/s.width)+1)),r=Math.max(1,Math.min(this.terminal.rows,Math.floor((t-n.top)/s.height)+1));return{col:o,row:r}},_sendSyntheticSgrTap(e,t){if(!this.activeSessionId||!this._terminalViewportAtBottom())return;const i=this._clientPointToCell(e,t);i&&this._sendInputAsync(this.activeSessionId,`\x1B[<0;${i.col};${i.row}M\x1B[<0;${i.col};${i.row}m`)},_cliVersionAtLeast(e,t){if(typeof e!="string")return!1;const i=e.trim().replace(/^v/,"").split(".").map(Number);if(i.length!==3||i.some(n=>!Number.isFinite(n)))return!1;const s=t.split(".").map(Number);for(let n=0;n<3;n++)if(i[n]!==s[n])return i[n]>s[n];return!0},_wheelScrollLines(e){const t=this._wheelScrollLinesFloat(e);return t?Math.round(t)||(t>0?1:-1):0},_wheelScrollLinesFloat(e){const t=e.shiftKey&&Math.abs(e.deltaX)>Math.abs(e.deltaY)?e.deltaX:e.deltaY;return t?e.deltaMode===1?t:e.deltaMode===2?t*(this.terminal?.rows||24):t/25:0},_shouldForwardWheelToApp(e){if(e.shiftKey||this.loadAppSettingsFromStorage?.()?.terminalWheelLocalScrollback)return!1;const t=this.terminal?.modes?.mouseTrackingMode;if(t&&t!=="none")return!1;const i=this.sessions?.get(this.activeSessionId);return!((i?.mode||"claude")!=="claude"||!this._cliVersionAtLeast(i?.cliVersion,"2.1.187"))},_sendSyntheticSgrWheel(e,t,i){if(!this.activeSessionId||!i)return;const s=this._clientPointToCell(e,t);if(!s)return;const n=i<0?64:65,o=Math.min(Math.abs(i),5);this._queueScrollBytes(`\x1B[<${n};${s.col};${s.row}M`.repeat(o))},_queueScrollBytes(e){if(!e||!this.activeSessionId)return;const t=this._wheelSgrQueue||"";t.length>512||(this._wheelSgrQueue=t+e,!this._wheelSgrFlushTimer&&(this._wheelSgrFlushTimer=setTimeout(()=>this._flushWheelSgrQueue(),40)))},_localScrollbackIsHollow(){if((this.sessions?.get(this.activeSessionId)?.mode||"claude")!=="claude")return!1;const t=this.terminal?.buffer?.active;return!t||t.type==="alternate"?!1:(t.baseY||0)===0},_maybePageCliTranscript(e,t){if(!t||e?.shiftKey||!this.activeSessionId||!this._localScrollbackIsHollow())return!1;this._pageKeySession!==this.activeSessionId&&(this._pageKeySession=this.activeSessionId,this._pageKeyPending=0);const i=window.CodemanTerminalInput,s=Math.max(2,Math.round((this.terminal?.rows||24)*i.PAGE_KEY_SCREEN_FRACTION)),n=(this._pageKeyPending||0)+t,o=Math.trunc(n/s);if(this._pageKeyPending=n-o*s,o){const r=o<0?i.KEY_PAGE_UP:i.KEY_PAGE_DOWN;this._queueScrollBytes(r.repeat(Math.min(Math.abs(o),i.PAGE_KEY_MAX_PER_BATCH)))}return this._logScrollRouting("page-keys"),!0},_logScrollRouting(e){const t=this.activeSessionId||"(none)",i=this.sessions?.get(t),s=!!this.loadAppSettingsFromStorage?.()?.terminalWheelLocalScrollback,n=this.terminal?.modes?.mouseTrackingMode||"none",o=this.terminal?.buffer?.active?.baseY??-1,r=`${e}|${i?.mode}|${i?.cliVersion}|${s}|${n}|${o>0}`;this._scrollRoutingLogged||(this._scrollRoutingLogged=new Map),this._scrollRoutingLogged.get(t)!==r&&(this._scrollRoutingLogged.set(t,r),console.log(`[scroll] ${t} \u2192 ${e} (mode=${i?.mode||"?"}, cliVersion=${i?.cliVersion||"unknown"}, localScrollbackOptOut=${s}, mouseTracking=${n}, localScrollbackRows=${o})`))},_flushWheelSgrQueue(){this._wheelSgrFlushTimer=null;const e=this._wheelSgrQueue;this._wheelSgrQueue="",e&&this.activeSessionId&&this._sendInputEphemeral(this.activeSessionId,e)},_handleDesktopTerminalClick(e){if(!this.terminal||!e?.isTrusted||e.button!==0||e.detail!==1||e.shiftKey||e.altKey||e.ctrlKey||e.metaKey)return;const t=this.terminal.modes?.mouseTrackingMode;t&&t!=="none"||this._shouldReportMouseToCli()&&(this.terminal.hasSelection?.()||this._linkHovered||performance.now()<=(this._trustedTapMouseSuppressUntil||0)||e.target?.closest?.(".xterm-screen")&&this._sendSyntheticSgrTap(e.clientX,e.clientY))},_installMobileTapMouseGuard(){const e=this.terminal?.element;if(!e||e._codemanTapMouseGuardInstalled||typeof MobileDetection<"u"&&MobileDetection.isTouchDevice&&!MobileDetection.isTouchDevice())return;e._codemanTapMouseGuardInstalled=!0;const t=i=>{const s=this._trustedTapMouseSuppressUntil||0;!i.isTrusted||performance.now()>s||(i.preventDefault(),i.stopImmediatePropagation())};e.addEventListener("mousedown",t,!0),e.addEventListener("mouseup",t,!0)},_suppressTrustedTapMouseEvents(){const e=window.CodemanTerminalInput?.TOUCH_COMPAT_MOUSE_SUPPRESS_MS||450;this._trustedTapMouseSuppressUntil=performance.now()+e},increaseFontSize(){const e=this.terminal.options.fontSize||14;this.setFontSize(Math.min(e+2,24))},decreaseFontSize(){const e=this.terminal.options.fontSize||14;this.setFontSize(Math.max(e-2,10))},setFontSize(e){this.terminal.options.fontSize=e,document.getElementById("fontSizeDisplay").textContent=e,this.fitAddon.fit(),localStorage.setItem("codeman-font-size",e),this._localEchoOverlay?.refreshFont(),this._predictiveEcho?.refreshFont()},applyTerminalFontFamily(e){const t=window.CodemanTerminalFont.resolve(e);!this.terminal||this.terminal.options.fontFamily===t||(this.terminal.options.fontFamily=t,this._terminalFontReady=this._awaitTerminalFont().then(()=>{this.terminal?.options?.fontFamily===t&&this.fitAddon?.fit()}),this.fitAddon?.fit(),this._localEchoOverlay?.refreshFont(),this._predictiveEcho?.refreshFont())},loadFontSize(){const e=localStorage.getItem("codeman-font-size");if(e){const t=parseInt(e,10);t>=10&&t<=24&&(this.terminal.options.fontSize=t,document.getElementById("fontSizeDisplay").textContent=t)}},async _awaitTerminalFont(){try{if(typeof document>"u"||!document.fonts?.load)return;const e=this.terminal?.options?.fontSize||14,t=String(this.terminal?.options?.fontFamily||"").split(",").map(s=>s.trim().replace(/^["']|["']$/g,"")).filter(Boolean).filter(s=>!TERMINAL_FONT_UNMEASURED.has(s.toLowerCase())),i=Promise.all(t.map(s=>document.fonts.load(`${e}px "${s}"`).catch(()=>{}))).then(()=>document.fonts.ready);await Promise.race([i,new Promise(s=>setTimeout(s,TERMINAL_FONT_WAIT_MS))])}catch{}try{this.terminal?._core?._charSizeService?.measure()}catch{}},getTerminalDimensions(){const i=this.fitAddon?.proposeDimensions();return i?{cols:Math.max(i.cols,40),rows:Math.max(i.rows,10)}:null},async sendResize(e,t={}){if(this.fitAddon&&this.fitAddon.fit(),!this.isSoloWindow&&this.detachedSessions?.has(e))return!1;const i=this.getTerminalDimensions();if(!i)return!1;const s=this._lastResizeDims,n=!s||s.cols!==i.cols||s.rows!==i.rows;this._lastResizeDims={cols:i.cols,rows:i.rows};const o=typeof MobileDetection<"u"&&MobileDetection.getDeviceType?MobileDetection.getDeviceType():window.innerWidth<430?"mobile":window.innerWidth<768?"tablet":"desktop";if(!t.forceHttp&&this._wsReady&&this._wsSessionId===e)try{const a={t:"z",c:i.cols,r:i.rows,v:o};return t.force&&(a.f=!0),this._ws.send(JSON.stringify(a)),n}catch{}const r={...i,viewportType:o};return t.force&&(r.force=!0),await fetch(`/api/sessions/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),n},async sendInput(e){!this.activeSessionId||!e||this._sendInputAsync(this.activeSessionId,e,{useMux:!0})},toggleDirInput(){const e=document.querySelector("#dirDisplay").parentElement,t=document.getElementById("dirInput");t.classList.contains("hidden")&&(t.classList.remove("hidden"),e.style.display="none",t.focus())},hideDirInput(){const e=document.querySelector("#dirDisplay").parentElement,t=document.getElementById("dirInput");setTimeout(()=>{t.classList.add("hidden"),e.style.display="";const i=t.value.trim();document.getElementById("dirDisplay").textContent=i||"No directory"},100)},applyTerminalSkin(e){const t={...window.CODEMAN_XTERM_THEMES[e]||window.CODEMAN_XTERM_THEMES["daylight-blue"]},i=window.codemanCurrentSkinIsLight(e)?4.5:1;if(this.terminal){this.terminal.options.minimumContrastRatio=i,this.terminal.options.theme=t,this._localEchoOverlay?.refreshFont(),this._predictiveEcho?.refreshFont();try{this.terminal.refresh(0,this.terminal.rows-1)}catch{}}if(this.teammateTerminals){for(const[,s]of this.teammateTerminals)if(s&&s.terminal){s.terminal.options.minimumContrastRatio=i,s.terminal.options.theme={...t};try{s.terminal.refresh(0,s.terminal.rows-1)}catch{}}}}}),(function(e){const s={session:"Sessions",event:"Events",file:"Files"};function n(o){if(!Number.isFinite(o))return"";const r=new Date(o);return r.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+r.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1})}e.CodemanSearch={SEARCH_DEBOUNCE_MS:250,SEARCH_LIMIT:60,SOURCE_LABELS:s,formatSearchTime:n}})(window),Object.assign(CodemanApp.prototype,{initSearchPanel(){const e=document.getElementById("searchInput");if(!e||this._searchPanelWired){this._searchPanelWired&&this._populateSearchCaseFilter();return}this._searchPanelWired=!0,this._searchTypes=new Set(["session","event","file"]),this._searchSecondary={caseLabel:"",status:"",days:""},this._searchDebounceTimer=null,this._searchSeq=0,this._searchLastData=null;const t=document.getElementById("searchClearBtn"),i=document.getElementById("searchResults");e.addEventListener("input",()=>{t&&(t.hidden=e.value.length===0),this._scheduleSearch()}),e.addEventListener("keydown",r=>{r.key==="Escape"&&e.value&&(r.stopPropagation(),this._clearSearch())}),t&&t.addEventListener("click",()=>this._clearSearch()),document.querySelectorAll("#searchFilters .search-filter-chip").forEach(r=>{r.addEventListener("click",()=>{const a=r.dataset.typeFilter;this._searchTypes.has(a)&&this._searchTypes.size===1||(this._searchTypes.has(a)?(this._searchTypes.delete(a),r.classList.remove("active")):(this._searchTypes.add(a),r.classList.add("active")),this._runSearch())})});const s=document.getElementById("searchCaseFilter"),n=document.getElementById("searchStatusFilter"),o=document.getElementById("searchDateFilter");s&&s.addEventListener("change",()=>{this._searchSecondary.caseLabel=s.value,this._renderSearch(this._searchLastData)}),n&&n.addEventListener("change",()=>{this._searchSecondary.status=n.value,this._renderSearch(this._searchLastData)}),o&&o.addEventListener("change",()=>{this._searchSecondary.days=o.value,this._renderSearch(this._searchLastData)}),this._populateSearchCaseFilter(),i&&(i.hidden=!0)},_populateSearchCaseFilter(){const e=document.getElementById("searchCaseFilter");if(!e)return;const t=Array.isArray(this.cases)?this.cases:[],i=Array.from(new Set(t.map(o=>o&&o.name).filter(Boolean))).sort(),s=e.value;e.innerHTML="";const n=document.createElement("option");n.value="",n.textContent="All cases",e.appendChild(n);for(const o of i){const r=document.createElement("option");r.value=o,r.textContent="#"+o,e.appendChild(r)}s&&i.includes(s)&&(e.value=s)},_scheduleSearch(){clearTimeout(this._searchDebounceTimer),this._searchDebounceTimer=setTimeout(()=>this._runSearch(),window.CodemanSearch.SEARCH_DEBOUNCE_MS)},_clearSearch(){const e=document.getElementById("searchInput"),t=document.getElementById("searchClearBtn");e&&(e.value=""),t&&(t.hidden=!0),this._searchLastData=null,this._renderSearch(null)},async _runSearch(){const e=document.getElementById("searchInput");if(!e)return;const t=e.value.trim();if(t.length===0){this._searchLastData=null,this._renderSearch(null);return}const i=Array.from(this._searchTypes),s=new URLSearchParams;s.set("q",t.slice(0,200)),i.length>0&&i.length<3&&s.set("types",i.join(",")),s.set("limit",String(window.CodemanSearch.SEARCH_LIMIT));const n=++this._searchSeq,o=await this._apiJson("/api/search?"+s.toString());n===this._searchSeq&&(o?this._searchLastData=o:this._searchLastData={query:t,groups:[],totalResults:0,truncated:!1,_error:!0},this._renderSearch(this._searchLastData))},_applySecondaryFilters(e){const{caseLabel:t,status:i,days:s}=this._searchSecondary;let n=e;if(t){const o="#"+t;n=n.filter(r=>(r.sessionName||"").includes(o)||r.sessionName===t)}if(i){const o=new Set((this.sessionOrder||[]).concat(Object.keys(this.sessions||{})));n=n.filter(r=>{const a=o.has(r.sessionId);return i==="active"?a:!a})}if(s){const o=Date.now()-Number(s)*24*60*60*1e3;n=n.filter(r=>Number.isFinite(r.timestamp)&&r.timestamp>=o)}return n},_renderSearch(e){const t=document.getElementById("searchResults"),i=document.getElementById("historyHeader")||document.getElementById("historyTitle"),s=document.getElementById("historyList");if(!t)return;const n=!!e;if(i&&(i.style.display=n?"none":""),s&&(s.style.display=n?"none":""),t.innerHTML="",!e){t.hidden=!0;return}if(t.hidden=!1,e._error){const a=document.createElement("div");a.className="search-empty",a.textContent="Search unavailable \u2014 check the query and try again.",t.appendChild(a);return}const o=(e.groups||[]).map(a=>({type:a.type,results:this._applySecondaryFilters(a.results||[])})).filter(a=>a.results.length>0);if(o.reduce((a,h)=>a+h.results.length,0)===0){const a=document.createElement("div");a.className="search-empty",a.textContent='No results for "'+(e.query||"")+'"',t.appendChild(a);return}for(const a of o){const h=document.createElement("div");h.className="search-group-header";const u=document.createElement("span");u.className="search-group-label",u.textContent=window.CodemanSearch.SOURCE_LABELS[a.type]||a.type;const m=document.createElement("span");m.className="search-group-count",m.textContent=String(a.results.length),h.append(u,m),t.appendChild(h);for(const c of a.results)t.appendChild(this._buildSearchResultCard(c))}if(e.truncated){const a=document.createElement("div");a.className="search-truncated",a.textContent="Showing the top matches \u2014 refine your search to narrow results.",t.appendChild(a)}},_buildSearchResultCard(e){const t=document.createElement("div");t.className="search-result-card",t.dataset.type=e.type,t.tabIndex=0,t.setAttribute("role","button");const i=document.createElement("div");i.className="search-result-top";const s=e.jumpTo&&e.jumpTo.kind==="resume-session",n=document.createElement("span");n.className="search-result-badge search-badge-"+e.type+(s?" search-badge-past":""),n.textContent=s?"Resume":(window.CodemanSearch.SOURCE_LABELS[e.type]||e.type).replace(/s$/,"");const o=document.createElement("span");o.className="search-result-name",o.textContent=e.sessionName||e.sessionId||"(session)";const r=document.createElement("span");r.className="search-result-time",r.textContent=window.CodemanSearch.formatSearchTime(e.timestamp),i.append(n,o,r);const a=document.createElement("div");a.className="search-result-snippet",a.textContent=e.snippet||"",t.append(i,a);const h=()=>this._jumpToSearchResult(e);return t.addEventListener("click",h),t.addEventListener("keydown",u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),h())}),t},_jumpToSearchResult(e){const t=e&&e.jumpTo;if(t){if(t.kind==="resume-session"){this.resumeHistorySession(t.claudeSessionId||t.sessionId,t.workingDir||"",e.sessionName);return}typeof this.hideWelcome=="function"&&this.hideWelcome();try{t.kind==="run-summary"?this.openRunSummary(t.sessionId):t.kind==="file-preview"?this.openFilePreview(t.relativePath||"",t.sessionId,t.targetId||null):this.selectSession(t.sessionId)}catch(i){console.error("[search] jump failed",i)}}}});
|
|
Binary file
|
|
Binary file
|