aicodeman 1.50.0 → 1.50.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -2
- package/dist/config-backup.js +1 -1
- package/dist/config-backup.js.map +1 -1
- package/dist/local-model/install-job.d.ts.map +1 -1
- package/dist/local-model/install-job.js +10 -2
- package/dist/local-model/install-job.js.map +1 -1
- package/dist/types/common.d.ts +5 -0
- package/dist/types/common.d.ts.map +1 -1
- package/dist/web/case-state-sync.d.ts +28 -0
- package/dist/web/case-state-sync.d.ts.map +1 -0
- package/dist/web/case-state-sync.js +41 -0
- package/dist/web/case-state-sync.js.map +1 -0
- 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.8719143d.js → app.07398d90.js} +1 -1
- package/dist/web/public/app.07398d90.js.br +0 -0
- package/dist/web/public/app.07398d90.js.gz +0 -0
- package/dist/web/public/approvals-ui.js.gz +0 -0
- package/dist/web/public/constants.782170e1.js.gz +0 -0
- package/dist/web/public/cron-ui.js.gz +0 -0
- package/dist/web/public/edit-history-ui.js.gz +0 -0
- package/dist/web/public/entrance-animations.js.gz +0 -0
- package/dist/web/public/foreign-sessions.js.gz +0 -0
- package/dist/web/public/git-status-ui.js.gz +0 -0
- package/dist/web/public/header-divider.eb2d2463.js.gz +0 -0
- package/dist/web/public/home-sessions.js +38 -18
- package/dist/web/public/home-sessions.js.br +0 -0
- package/dist/web/public/home-sessions.js.gz +0 -0
- package/dist/web/public/host-wake-ui.js.gz +0 -0
- package/dist/web/public/{i18n.1e96a258.js → i18n.519d025e.js} +2 -2
- package/dist/web/public/i18n.519d025e.js.br +0 -0
- package/dist/web/public/{i18n.1e96a258.js.gz → i18n.519d025e.js.gz} +0 -0
- package/dist/web/public/image-input.a5d0f8f3.js.gz +0 -0
- package/dist/web/public/index.html +30 -9
- package/dist/web/public/index.html.br +0 -0
- package/dist/web/public/index.html.gz +0 -0
- package/dist/web/public/input-cjk.8bc46081.js.gz +0 -0
- package/dist/web/public/{keyboard-accessory.b941676c.js → keyboard-accessory.0800fc44.js} +160 -2
- package/dist/web/public/keyboard-accessory.0800fc44.js.br +0 -0
- package/dist/web/public/keyboard-accessory.0800fc44.js.gz +0 -0
- package/dist/web/public/local-model-ui.js.gz +0 -0
- package/dist/web/public/mobile-handlers.f7c3f692.js.gz +0 -0
- package/dist/web/public/mobile-ime-preview.2dbaf262.js.gz +0 -0
- package/dist/web/public/mobile-overview.js +30 -14
- package/dist/web/public/mobile-overview.js.br +0 -0
- package/dist/web/public/mobile-overview.js.gz +0 -0
- package/dist/web/public/mobile.4dfd5c55.css.gz +0 -0
- package/dist/web/public/notification-manager.feb82c04.js.gz +0 -0
- package/dist/web/public/orchestrator-panel.js.gz +0 -0
- package/dist/web/public/{panels-ui.d3f4f1c4.js → panels-ui.9ba2683e.js} +99 -97
- package/dist/web/public/panels-ui.9ba2683e.js.br +0 -0
- package/dist/web/public/panels-ui.9ba2683e.js.gz +0 -0
- package/dist/web/public/ralph-panel.b350e2ef.js.gz +0 -0
- package/dist/web/public/ralph-wizard.b6c0dd19.js.gz +0 -0
- package/dist/web/public/readmymind-ui.js.gz +0 -0
- package/dist/web/public/reboot-restore-ui.js.gz +0 -0
- package/dist/web/public/respawn-ui.304ba0d4.js.gz +0 -0
- package/dist/web/public/sanitize-html.e7147e76.js.gz +0 -0
- package/dist/web/public/session-lineage.js.gz +0 -0
- package/dist/web/public/{session-ui.a7c8c095.js → session-ui.8f300b14.js} +21 -21
- package/dist/web/public/session-ui.8f300b14.js.br +0 -0
- package/dist/web/public/session-ui.8f300b14.js.gz +0 -0
- package/dist/web/public/{settings-ui.11da6f15.js → settings-ui.8b37cf07.js} +14 -14
- package/dist/web/public/settings-ui.8b37cf07.js.br +0 -0
- package/dist/web/public/settings-ui.8b37cf07.js.gz +0 -0
- package/dist/web/public/spreadsheet-preview-worker.js.gz +0 -0
- package/dist/web/public/spreadsheet-preview.75c751de.js.gz +0 -0
- package/dist/web/public/spreadsheet-xlsx-core.js.gz +0 -0
- package/dist/web/public/{styles.63382d6e.css → styles.21b93520.css} +1 -1
- package/dist/web/public/styles.21b93520.css.br +0 -0
- package/dist/web/public/{styles.63382d6e.css.gz → styles.21b93520.css.gz} +0 -0
- package/dist/web/public/subagent-windows.07277a58.js.gz +0 -0
- package/dist/web/public/sw.js +2 -2
- package/dist/web/public/sw.js.br +0 -0
- package/dist/web/public/sw.js.gz +0 -0
- package/dist/web/public/tab-layout-browser.2d6189f7.js.gz +0 -0
- package/dist/web/public/tab-rail-resize.b5cdceaf.js.gz +0 -0
- package/dist/web/public/terminal-keycode229-recovery.98843069.js.gz +0 -0
- package/dist/web/public/terminal-split.js.gz +0 -0
- package/dist/web/public/terminal-tile.js.gz +0 -0
- package/dist/web/public/terminal-ui.f92eae28.js.gz +0 -0
- package/dist/web/public/tile-grid.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/vendor/dompurify.min.js.gz +0 -0
- package/dist/web/public/vendor/exceljs.min.js.gz +0 -0
- package/dist/web/public/vendor/fflate.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.276b11d9.js.gz +0 -0
- package/dist/web/public/vendor/xterm-zerolag-input.1be42307.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.2342c37b.js → voice-input.d0580528.js} +232 -137
- package/dist/web/public/voice-input.d0580528.js.br +0 -0
- package/dist/web/public/voice-input.d0580528.js.gz +0 -0
- package/dist/web/public/voice-pcm-worklet.js.gz +0 -0
- package/dist/web/public/webview-tabs.js.gz +0 -0
- package/dist/web/public/whats-new.json +9 -9
- package/dist/web/routes/case-routes.d.ts.map +1 -1
- package/dist/web/routes/case-routes.js +31 -5
- package/dist/web/routes/case-routes.js.map +1 -1
- package/dist/web/routes/file-routes.d.ts +4 -2
- package/dist/web/routes/file-routes.d.ts.map +1 -1
- package/dist/web/routes/file-routes.js +92 -2
- package/dist/web/routes/file-routes.js.map +1 -1
- package/dist/web/routes/system-routes.d.ts +2 -2
- package/dist/web/routes/system-routes.d.ts.map +1 -1
- package/dist/web/routes/system-routes.js +23 -4
- package/dist/web/routes/system-routes.js.map +1 -1
- package/dist/web/schemas.d.ts +7 -0
- package/dist/web/schemas.d.ts.map +1 -1
- package/dist/web/schemas.js +14 -0
- package/dist/web/schemas.js.map +1 -1
- package/dist/web/voice-stream.d.ts +4 -3
- package/dist/web/voice-stream.d.ts.map +1 -1
- package/dist/web/voice-stream.js +5 -4
- package/dist/web/voice-stream.js.map +1 -1
- package/package.json +1 -1
- package/dist/web/public/app.8719143d.js.br +0 -0
- package/dist/web/public/app.8719143d.js.gz +0 -0
- package/dist/web/public/i18n.1e96a258.js.br +0 -0
- package/dist/web/public/keyboard-accessory.b941676c.js.br +0 -0
- package/dist/web/public/keyboard-accessory.b941676c.js.gz +0 -0
- package/dist/web/public/panels-ui.d3f4f1c4.js.br +0 -0
- package/dist/web/public/panels-ui.d3f4f1c4.js.gz +0 -0
- package/dist/web/public/session-ui.a7c8c095.js.br +0 -0
- package/dist/web/public/session-ui.a7c8c095.js.gz +0 -0
- package/dist/web/public/settings-ui.11da6f15.js.br +0 -0
- package/dist/web/public/settings-ui.11da6f15.js.gz +0 -0
- package/dist/web/public/styles.63382d6e.css.br +0 -0
- package/dist/web/public/voice-input.2342c37b.js.br +0 -0
- package/dist/web/public/voice-input.2342c37b.js.gz +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"case-state-sync.d.ts","sourceRoot":"","sources":["../../src/web/case-state-sync.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,WAAW,cAAc;IAC7B,UAAU,EAAE,OAAO,CAAC;IACpB,aAAa,EAAE,OAAO,CAAC;CACxB;AAED,4GAA4G;AAC5G,eAAO,MAAM,gBAAgB,MAAM,CAAC;AAEpC,qBAAa,oBAAqB,SAAQ,KAAK;;CAK9C;AAMD,qGAAqG;AACrG,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC;;EAI3F;AAED,gFAAgF;AAChF,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;;SAK5E;AAED,mEAAmE;AACnE,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM;;SAK9D"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Pure helpers for the opt-in shared per-case run options (`caseSettings` in
|
|
3
|
+
* settings.json, written while `syncCaseState` is on). They run inside `mutateSettingsFile()`, so
|
|
4
|
+
* every change is serialised with the file's other writers: two devices saving different cases
|
|
5
|
+
* both land, where a replacement map would let the second discard the first.
|
|
6
|
+
*/
|
|
7
|
+
/** Most cases the shared map holds, counted after a merge (the schema bounds one request, not the file). */
|
|
8
|
+
export const MAX_SHARED_CASES = 500;
|
|
9
|
+
export class SharedCaseLimitError extends Error {
|
|
10
|
+
constructor() {
|
|
11
|
+
super(`Shared case options are limited to ${MAX_SHARED_CASES} cases`);
|
|
12
|
+
this.name = 'SharedCaseLimitError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function asMap(value) {
|
|
16
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
17
|
+
}
|
|
18
|
+
/** The stored map with `incoming` merged in per case. Throws SharedCaseLimitError past the limit. */
|
|
19
|
+
export function mergeCaseSettings(current, incoming) {
|
|
20
|
+
const merged = { ...asMap(current), ...incoming };
|
|
21
|
+
if (Object.keys(merged).length > MAX_SHARED_CASES)
|
|
22
|
+
throw new SharedCaseLimitError();
|
|
23
|
+
return merged;
|
|
24
|
+
}
|
|
25
|
+
/** The map with `from` moved to `to`, or null when there is nothing to move. */
|
|
26
|
+
export function renameCaseSettings(current, from, to) {
|
|
27
|
+
const map = asMap(current);
|
|
28
|
+
if (!Object.hasOwn(map, from))
|
|
29
|
+
return null;
|
|
30
|
+
const { [from]: moved, ...rest } = map;
|
|
31
|
+
return { ...rest, [to]: moved };
|
|
32
|
+
}
|
|
33
|
+
/** The map without `name`, or null when it has no entry for it. */
|
|
34
|
+
export function dropCaseSettings(current, name) {
|
|
35
|
+
const map = asMap(current);
|
|
36
|
+
if (!Object.hasOwn(map, name))
|
|
37
|
+
return null;
|
|
38
|
+
const { [name]: _gone, ...rest } = map;
|
|
39
|
+
return rest;
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=case-state-sync.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"case-state-sync.js","sourceRoot":"","sources":["../../src/web/case-state-sync.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAOH,4GAA4G;AAC5G,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAEpC,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IAC7C;QACE,KAAK,CAAC,sCAAsC,gBAAgB,QAAQ,CAAC,CAAC;QACtE,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;IACrC,CAAC;CACF;AAED,SAAS,KAAK,CAAC,KAAc;IAC3B,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAE,KAAwC,CAAC,CAAC,CAAC,EAAE,CAAC;AACtH,CAAC;AAED,qGAAqG;AACrG,MAAM,UAAU,iBAAiB,CAAC,OAAgB,EAAE,QAAwC;IAC1F,MAAM,MAAM,GAAG,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC,EAAE,GAAG,QAAQ,EAAE,CAAC;IAClD,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG,gBAAgB;QAAE,MAAM,IAAI,oBAAoB,EAAE,CAAC;IACpF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,kBAAkB,CAAC,OAAgB,EAAE,IAAY,EAAE,EAAU;IAC3E,MAAM,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC;IAC3B,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IAC3C,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,GAAG,GAAG,CAAC;IACvC,OAAO,EAAE,GAAG,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC;AAClC,CAAC;AAED,mEAAmE;AACnE,MAAM,UAAU,gBAAgB,CAAC,OAAgB,EAAE,IAAY;IAC7D,MAAM,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC;IAC3B,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IAC3C,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,GAAG,GAAG,CAAC;IACvC,OAAO,IAAI,CAAC;AACd,CAAC"}
|
|
Binary file
|
|
Binary file
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
`),id:_crashDiag._pageId}))}catch{}}if(setInterval(()=>{try{localStorage.setItem("codeman-crash-heartbeat",String(Date.now()))}catch{}_crashDiagBeacon()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&_crashDiagBeacon()}),window.addEventListener("error",m=>{_crashDiag.log(`ERROR: ${m.message} at ${m.filename}:${m.lineno}`),console.error("[CRASH-DIAG] Uncaught error:",m.message,`
|
|
5
5
|
File:`,m.filename,":",m.lineno,":",m.colno,`
|
|
6
6
|
Stack:`,m.error?.stack)}),window.addEventListener("unhandledrejection",m=>{_crashDiag.log(`UNHANDLED: ${m.reason?.message||m.reason}`),console.error("[CRASH-DIAG] Unhandled promise rejection:",m.reason?.message||m.reason,`
|
|
7
|
-
Stack:`,m.reason?.stack)}),typeof PerformanceObserver<"u")try{new PerformanceObserver(e=>{for(const t of e.getEntries())t.duration>200&&(_crashDiag.log(`LONG_TASK: ${t.duration.toFixed(0)}ms`),console.warn(`[CRASH-DIAG] Long task: ${t.duration.toFixed(0)}ms (type: ${t.entryType}, name: ${t.name})`))}).observe({type:"longtask",buffered:!0})}catch{}const _origGetContext=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(m,...e){const t=_origGetContext.call(this,m,...e);return(m==="webgl2"||m==="webgl")&&(this.addEventListener("webglcontextlost",s=>{_crashDiag.log(`WEBGL_LOST: ${this.width}x${this.height}`),console.error("[CRASH-DIAG] WebGL context LOST on canvas",this.width,"x",this.height,"\u2014 prevented:",s.defaultPrevented)}),this.addEventListener("webglcontextrestored",()=>{_crashDiag.log("WEBGL_RESTORED"),console.warn("[CRASH-DIAG] WebGL context restored")})),t};const _SSE_HANDLER_MAP=[[SSE_EVENTS.INIT,"_onInit"],[SSE_EVENTS.SESSION_CREATED,"_onSessionCreated"],[SSE_EVENTS.SESSION_UPDATED,"_onSessionUpdated"],[SSE_EVENTS.SESSION_DELETED,"_onSessionDeleted"],[SSE_EVENTS.SESSION_TERMINAL,"_onSSETerminal"],[SSE_EVENTS.SESSION_NEEDS_REFRESH,"_onSSENeedsRefresh"],[SSE_EVENTS.SESSION_CLEAR_TERMINAL,"_onSSEClearTerminal"],[SSE_EVENTS.SESSION_COMPLETION,"_onSessionCompletion"],[SSE_EVENTS.SESSION_ERROR,"_onSessionError"],[SSE_EVENTS.SESSION_EXIT,"_onSessionExit"],[SSE_EVENTS.SESSION_IDLE,"_onSessionIdle"],[SSE_EVENTS.SESSION_WORKING,"_onSessionWorking"],[SSE_EVENTS.SESSION_AUTO_CLEAR,"_onSessionAutoClear"],[SSE_EVENTS.SESSION_LIMIT_PAUSE_SCHEDULED,"_onSessionLimitPauseScheduled"],[SSE_EVENTS.SESSION_LIMIT_RESUME,"_onSessionLimitResume"],[SSE_EVENTS.SESSION_LIMIT_RESUME_CANCELLED,"_onSessionLimitResumeCancelled"],[SSE_EVENTS.SESSION_RESPAWN_BREAKER_TRIPPED,"_onSessionRespawnBreakerTripped"],[SSE_EVENTS.SESSION_CLI_INFO,"_onSessionCliInfo"],[SSE_EVENTS.SESSION_STATUS_TELEMETRY,"_onSessionStatusTelemetry"],[SSE_EVENTS.SESSION_PROMPT_CACHE,"_onSessionPromptCache"],[SSE_EVENTS.SESSION_KEEP_WARM,"_onSessionKeepWarm"],[SSE_EVENTS.SCHEDULED_CREATED,"_onScheduledCreated"],[SSE_EVENTS.SCHEDULED_UPDATED,"_onScheduledUpdated"],[SSE_EVENTS.SCHEDULED_COMPLETED,"_onScheduledCompleted"],[SSE_EVENTS.SCHEDULED_STOPPED,"_onScheduledStopped"],[SSE_EVENTS.CRON_JOBS_CHANGED,"_onCronJobsChanged"],[SSE_EVENTS.CRON_JOB_DELETED,"_onCronJobsChanged"],[SSE_EVENTS.CRON_RUN_CREATED,"_onCronRunChanged"],[SSE_EVENTS.CRON_RUN_UPDATED,"_onCronRunChanged"],[SSE_EVENTS.RESPAWN_STARTED,"_onRespawnStarted"],[SSE_EVENTS.RESPAWN_STOPPED,"_onRespawnStopped"],[SSE_EVENTS.RESPAWN_STATE_CHANGED,"_onRespawnStateChanged"],[SSE_EVENTS.RESPAWN_CYCLE_STARTED,"_onRespawnCycleStarted"],[SSE_EVENTS.RESPAWN_BLOCKED,"_onRespawnBlocked"],[SSE_EVENTS.RESPAWN_AUTO_ACCEPT_SENT,"_onRespawnAutoAcceptSent"],[SSE_EVENTS.RESPAWN_DETECTION_UPDATE,"_onRespawnDetectionUpdate"],[SSE_EVENTS.RESPAWN_TIMER_STARTED,"_onRespawnTimerStarted"],[SSE_EVENTS.RESPAWN_TIMER_CANCELLED,"_onRespawnTimerCancelled"],[SSE_EVENTS.RESPAWN_TIMER_COMPLETED,"_onRespawnTimerCompleted"],[SSE_EVENTS.RESPAWN_ERROR,"_onRespawnError"],[SSE_EVENTS.RESPAWN_ACTION_LOG,"_onRespawnActionLog"],[SSE_EVENTS.TASK_CREATED,"_onTaskCreated"],[SSE_EVENTS.TASK_COMPLETED,"_onTaskCompleted"],[SSE_EVENTS.TASK_FAILED,"_onTaskFailed"],[SSE_EVENTS.TASK_UPDATED,"_onTaskUpdated"],[SSE_EVENTS.MUX_CREATED,"_onMuxCreated"],[SSE_EVENTS.MUX_KILLED,"_onMuxKilled"],[SSE_EVENTS.MUX_DIED,"_onMuxDied"],[SSE_EVENTS.MUX_STATS_UPDATED,"_onMuxStatsUpdated"],[SSE_EVENTS.REMOTE_SESSION_RECONNECTED,"_onRemoteSessionReconnected"],[SSE_EVENTS.REMOTE_RECONNECT_EXHAUSTED,"_onRemoteReconnectExhausted"],[SSE_EVENTS.REMOTE_HOST_WAKING,"_onRemoteHostWaking"],[SSE_EVENTS.REMOTE_HOST_WAKE_FAILED,"_onRemoteHostWakeFailed"],[SSE_EVENTS.SESSION_RALPH_LOOP_UPDATE,"_onRalphLoopUpdate"],[SSE_EVENTS.SESSION_RALPH_TODO_UPDATE,"_onRalphTodoUpdate"],[SSE_EVENTS.SESSION_RALPH_COMPLETION_DETECTED,"_onRalphCompletionDetected"],[SSE_EVENTS.SESSION_RALPH_STATUS_UPDATE,"_onRalphStatusUpdate"],[SSE_EVENTS.SESSION_CIRCUIT_BREAKER_UPDATE,"_onCircuitBreakerUpdate"],[SSE_EVENTS.SESSION_EXIT_GATE_MET,"_onExitGateMet"],[SSE_EVENTS.SESSION_BASH_TOOL_START,"_onBashToolStart"],[SSE_EVENTS.SESSION_BASH_TOOL_END,"_onBashToolEnd"],[SSE_EVENTS.SESSION_BASH_TOOLS_UPDATE,"_onBashToolsUpdate"],[SSE_EVENTS.HOOK_IDLE_PROMPT,"_onHookIdlePrompt"],[SSE_EVENTS.HOOK_PERMISSION_PROMPT,"_onHookPermissionPrompt"],[SSE_EVENTS.HOOK_ELICITATION_DIALOG,"_onHookElicitationDialog"],[SSE_EVENTS.HOOK_ELICITATION_COMPLETE,"_onHookElicitationComplete"],[SSE_EVENTS.HOOK_ELICITATION_RESPONSE,"_onHookElicitationResponse"],[SSE_EVENTS.HOOK_STOP,"_onHookStop"],[SSE_EVENTS.HOOK_AGENT_WORKING,"_onHookAgentWorking"],[SSE_EVENTS.HOOK_TEAMMATE_IDLE,"_onHookTeammateIdle"],[SSE_EVENTS.HOOK_TASK_COMPLETED,"_onHookTaskCompleted"],[SSE_EVENTS.APPROVAL_PENDING,"_onApprovalPending"],[SSE_EVENTS.APPROVAL_UPDATED,"_onApprovalUpdated"],[SSE_EVENTS.APPROVAL_RESOLVED,"_onApprovalResolved"],[SSE_EVENTS.SUBAGENT_DISCOVERED,"_onSubagentDiscovered"],[SSE_EVENTS.SUBAGENT_UPDATED,"_onSubagentUpdated"],[SSE_EVENTS.SUBAGENT_TOOL_CALL,"_onSubagentToolCall"],[SSE_EVENTS.SUBAGENT_PROGRESS,"_onSubagentProgress"],[SSE_EVENTS.SUBAGENT_MESSAGE,"_onSubagentMessage"],[SSE_EVENTS.SUBAGENT_TOOL_RESULT,"_onSubagentToolResult"],[SSE_EVENTS.SUBAGENT_COMPLETED,"_onSubagentCompleted"],[SSE_EVENTS.WORKFLOW_RUN_DISCOVERED,"_onWorkflowRunDiscovered"],[SSE_EVENTS.WORKFLOW_RUN_UPDATED,"_onWorkflowRunUpdated"],[SSE_EVENTS.WORKFLOW_RUN_REMOVED,"_onWorkflowRunRemoved"],[SSE_EVENTS.IMAGE_DETECTED,"_onImageDetected"],[SSE_EVENTS.ATTACHMENT_DETECTED,"_onAttachmentDetected"],[SSE_EVENTS.TRANSCRIPT_TOOL_END,"_onEditHistoryTranscriptEvent"],[SSE_EVENTS.TUNNEL_STARTED,"_onTunnelStarted"],[SSE_EVENTS.TUNNEL_STOPPED,"_onTunnelStopped"],[SSE_EVENTS.TUNNEL_PROGRESS,"_onTunnelProgress"],[SSE_EVENTS.TUNNEL_ERROR,"_onTunnelError"],[SSE_EVENTS.TUNNEL_QR_ROTATED,"_onTunnelQrRotated"],[SSE_EVENTS.TUNNEL_QR_REGENERATED,"_onTunnelQrRegenerated"],[SSE_EVENTS.TUNNEL_QR_AUTH_USED,"_onTunnelQrAuthUsed"],[SSE_EVENTS.PLAN_SUBAGENT,"_onPlanSubagent"],[SSE_EVENTS.PLAN_PROGRESS,"_onPlanProgress"],[SSE_EVENTS.PLAN_STARTED,"_onPlanStarted"],[SSE_EVENTS.PLAN_CANCELLED,"_onPlanCancelled"],[SSE_EVENTS.PLAN_COMPLETED,"_onPlanCompleted"],[SSE_EVENTS.ORCHESTRATOR_STATE_CHANGED,"_onOrchestratorStateChanged"],[SSE_EVENTS.ORCHESTRATOR_PLAN_PROGRESS,"_onOrchestratorPlanProgress"],[SSE_EVENTS.ORCHESTRATOR_PLAN_READY,"_onOrchestratorPlanReady"],[SSE_EVENTS.ORCHESTRATOR_PHASE_STARTED,"_onOrchestratorPhaseStarted"],[SSE_EVENTS.ORCHESTRATOR_PHASE_COMPLETED,"_onOrchestratorPhaseCompleted"],[SSE_EVENTS.ORCHESTRATOR_PHASE_FAILED,"_onOrchestratorPhaseFailed"],[SSE_EVENTS.ORCHESTRATOR_VERIFICATION,"_onOrchestratorVerification"],[SSE_EVENTS.ORCHESTRATOR_TASK_ASSIGNED,"_onOrchestratorTaskAssigned"],[SSE_EVENTS.ORCHESTRATOR_TASK_COMPLETED,"_onOrchestratorTaskCompleted"],[SSE_EVENTS.ORCHESTRATOR_TASK_FAILED,"_onOrchestratorTaskFailed"],[SSE_EVENTS.ORCHESTRATOR_COMPLETED,"_onOrchestratorCompleted"],[SSE_EVENTS.ORCHESTRATOR_ERROR,"_onOrchestratorError"],[SSE_EVENTS.CLIPBOARD_WRITE,"_onClipboardWrite"],[SSE_EVENTS.SESSION_ORDER_CHANGED,"_onSessionOrderChanged"],[SSE_EVENTS.TAB_LAYOUT_CHANGED,"_onTabLayoutChanged"],[SSE_EVENTS.WEBVIEW_CHANGED,"_onWebviewChanged"]];function parseSessionPrefix(m){if(!m)return null;const e=m.match(/^(w\d+-[a-zA-Z0-9_-]+|s\d+-[a-zA-Z0-9_-]+)/);if(!e)return null;const t=e[1],s=m.slice(t.length);return s===""?{prefix:t,suffix:""}:s.startsWith(": ")?{prefix:t,suffix:s.slice(2)}:null}function paneExitLabel(m){return!m||typeof m!="object"?"":typeof m.signal=="number"&&m.signal>0?`exited (signal ${m.signal})`:typeof m.status=="number"?`exited (${m.status})`:"exited"}function paneExitAriaLabel(m,e){return e?`${m} session, agent ${e}`:`${m} session`}function applyPaneExitBadge(m,e){const t=paneExitLabel(e),s=m.querySelector(".tab-exited-badge");m.classList.toggle("tab-agent-exited",!!t);const i=m.querySelector(".tab-name")?.dataset?.fullName;if(i){const n=paneExitAriaLabel(i,t);m.dataset.ariaSource!==n&&(m.dataset.ariaSource=n,m.setAttribute("aria-label",n))}if(!t){s?.remove();return}if(!s){const n=document.createElement("span");n.className="tab-exited-badge",n.setAttribute("aria-hidden","true"),n.dataset.label=t,n.textContent=t,m.querySelector(".tab-name")?.insertAdjacentElement("afterend",n);return}s.dataset.label!==t&&(s.dataset.label=t,s.textContent=t)}const DEFAULT_SHORTCUTS=[{id:"show-shortcuts",group:"Panels",label:"Show Shortcuts",bindings:[{modifiers:["ctrl"],key:"?",code:"Slash"},{modifiers:["ctrl","shift"],key:"?"},{modifiers:["alt"],key:"?",code:"Slash"}],action:"showShortcutOverlay"},{id:"close-session",group:"Session",label:"Close Session",bindings:[],action:"killActiveSession"},{id:"next-session",group:"Session",label:"Next Session",bindings:[{modifiers:["ctrl"],key:"Tab"}],action:"nextSession"},{id:"clear-terminal",group:"Terminal",label:"Clear Terminal",bindings:[{modifiers:["ctrl"],key:"l"}],action:"clearTerminal"},{id:"copy-selection",group:"Terminal",label:"Copy Selection",bindings:[{modifiers:["ctrl"],key:"c"},{modifiers:["ctrl","shift"],key:"C"}],action:"copyTerminalSelection"},{id:"increase-font",group:"Terminal",label:"Increase Font",bindings:[{modifiers:["ctrl"],key:"=",code:"Equal"},{modifiers:["ctrl"],key:"+",code:"Equal"}],action:"increaseFontSize"},{id:"decrease-font",group:"Terminal",label:"Decrease Font",bindings:[{modifiers:["ctrl"],key:"-",code:"Minus"}],action:"decreaseFontSize"},{id:"voice-input",group:"Terminal",label:"Voice Input",bindings:[{modifiers:["ctrl","shift"],key:"V"}],action:"toggleVoiceInput"},{id:"restore-terminal-size",group:"Terminal",label:"Restore Terminal Size",bindings:[{modifiers:["ctrl","shift"],key:"R"}],action:"restoreTerminalSize"},{id:"move-tab-left",group:"Tabs",label:"Move Active Tab Left",bindings:[{modifiers:["ctrl","shift"],key:"{",code:"BracketLeft"}],action:"moveActiveTabLeft"},{id:"move-tab-right",group:"Tabs",label:"Move Active Tab Right",bindings:[{modifiers:["ctrl","shift"],key:"}",code:"BracketRight"}],action:"moveActiveTabRight"},{id:"command-palette",group:"Session",label:"Find Open Session",bindings:[{modifiers:["ctrl"],key:"k",code:"KeyK"},{modifiers:["meta"],key:"k",code:"KeyK"},{modifiers:["alt"],key:"k",code:"KeyK"}],action:"openCommandPalette"},{id:"toggle-session-sidebar",group:"Session",label:"Toggle Session Sidebar",bindings:[{modifiers:["alt"],key:"b",code:"KeyB"}],action:"toggleSessionSidebar"},{id:"toggle-tile-grid",group:"Tiles",label:"Toggle Tile Grid",bindings:[{modifiers:["ctrl","shift"],key:"G",code:"KeyG"}],action:"toggleTileGrid"},{id:"focus-tile-left",group:"Tiles",label:"Focus Tile Left",bindings:[{modifiers:["alt","shift"],key:"ArrowLeft"}],action:"focusTileLeft"},{id:"focus-tile-right",group:"Tiles",label:"Focus Tile Right",bindings:[{modifiers:["alt","shift"],key:"ArrowRight"}],action:"focusTileRight"},{id:"focus-tile-up",group:"Tiles",label:"Focus Tile Up",bindings:[{modifiers:["alt","shift"],key:"ArrowUp"}],action:"focusTileUp"},{id:"focus-tile-down",group:"Tiles",label:"Focus Tile Down",bindings:[{modifiers:["alt","shift"],key:"ArrowDown"}],action:"focusTileDown"},{id:"move-tile-left",group:"Tiles",label:"Move Tile Left",bindings:[{modifiers:["ctrl","shift"],key:"ArrowLeft"}],action:"moveTileLeft"},{id:"move-tile-right",group:"Tiles",label:"Move Tile Right",bindings:[{modifiers:["ctrl","shift"],key:"ArrowRight"}],action:"moveTileRight"},{id:"move-tile-up",group:"Tiles",label:"Move Tile Up",bindings:[{modifiers:["ctrl","shift"],key:"ArrowUp"}],action:"moveTileUp"},{id:"move-tile-down",group:"Tiles",label:"Move Tile Down",bindings:[{modifiers:["ctrl","shift"],key:"ArrowDown"}],action:"moveTileDown"},{id:"zoom-tile",group:"Tiles",label:"Zoom Focused Tile",bindings:[{modifiers:["alt","shift"],key:"Enter"}],action:"zoomTile"},{id:"remove-tile",group:"Tiles",label:"Remove Focused Tile",bindings:[],action:"removeTile"},{id:"previous-session",group:"Session",label:"Previous Session",displayBindings:["Alt/Option+["],bindings:[{modifiers:["alt"],code:"BracketLeft"}],action:"previousSession"},{id:"next-session-alt",group:"Session",label:"Next Session (alternate)",displayBindings:["Alt/Option+]"],bindings:[{modifiers:["alt"],code:"BracketRight"}],action:"nextSession"},{id:"switch-tab-n",group:"Session",label:"Switch to Tab N",displayBindings:["Alt/Option+1-9"]},{id:"focus-tabs",group:"Tabs",label:"Focus Tabs",displayBindings:["ArrowLeft","ArrowRight","Home","End"]},{id:"activate-focused-tab",group:"Tabs",label:"Activate Focused Tab",displayBindings:["Enter","Space"]},{id:"insert-newline",group:"Terminal",label:"Insert Newline",displayBindings:["Shift+Enter","Ctrl+Enter"]},{id:"close-panels",group:"Panels",label:"Close Panels",displayBindings:["Escape"]},{id:"file-preview-history",group:"Panels",label:"File Viewer Back / Forward",displayBindings:["Alt/Option+ArrowLeft","Alt/Option+ArrowRight"]}],SIDEBAR_RICH_CLOCK_MS=2e4,CONNECTION_BACKLOG_HINT_BYTES=4,CONNECTION_BACKLOG_HOLD_MS=1200,URL_SESSION_WAIT_MS=3e4,TAB_LAYOUT_PENDING_MAX_AGE_MS=6e4,TAB_GROUP_ARRIVAL_MS=2e3;class CodemanApp{constructor(){this.sessions=new Map,this._shortIdCache=new Map,this.sessionOrder=[],this.draggedTabId=null,this.tabLayout=null,this.collapsedTabGroupIds=new Set,this._hiddenTabGroupByRef=new Map,this._lastTabGroupStructureKey=null,this._tabRailSearch="",this.cases=[],this.currentRun=null,this.totalTokens=0,this.globalStats=null,this.eventSource=null,this._clientId=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"c-"+Math.random().toString(36).slice(2)+Date.now().toString(36),this._wsTabNonce=this._clientId,this.terminal=null,this.fitAddon=null,this.activeSessionId=null,this.soloSessionId=this._detectSoloSessionId(),this.isSoloWindow=!!this.soloSessionId,this._urlSessionId=this.isSoloWindow?null:this._takeUrlSession(),this._urlSessionWaitTimer=null,this.detachedSessions=new Set,this.detachedWindows=new Map,this._detachWatchTimers=new Map,this.windowChannel=null,this._redockGrace=new Map,this._detachPingPending=null,this._detachLivenessTimer=null,this._detachOrphanStrikes=new Map,this._initGeneration=0,this._initFallbackTimer=null,this._selectGeneration=0,this._fullHistoryLoaded=new Set,this._paneHistoryLines=new Map,this._fullHistoryRepullAt=new Map,this._fullHistoryRepullInFlight=!1,this._fullHistoryRepullUseless=new Set,this._geometryRetryUseless=new Set,this.terminalLoadStates=new Map,this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},this.timerCountdownInterval=null,this.terminalBuffers=new Map,this.editingSessionId=null,this.pendingCloseSessionId=null,this.muxSessions=[],this.ralphStates=new Map,this.subagents=new Map,this.subagentActivity=new Map,this.subagentToolResults=new Map,this.activeSubagentId=null,this.subagentPanelVisible=!1,this.workflowRuns=new Map,this.workflowRunDetails=new Map,this.activeWorkflowRunId=null,this.activeWorkflowPhaseIndex=null,this.ultracodeWindows=new Map,this.ultracodeWindowsClosed=new Set,this.ultracodeWindowCloseTimers=new Map,this.ultracodeWindowZIndex=1e3,this.subagentWindows=new Map,this.subagentWindowZIndex=ZINDEX_SUBAGENT_BASE,this.minimizedSubagents=new Map,this._subagentHideTimeout=null,this.subagentParentMap=new Map,this.teams=new Map,this.teamTasks=new Map,this.teammateMap=new Map,this.teammatePanesByName=new Map,this.teammateTerminals=new Map,this.terminalBufferCache=new Map,this.ralphStatePanelCollapsed=!0,this.ralphClosedSessions=new Set,this.planSubagents=new Map,this.planSubagentWindowZIndex=ZINDEX_PLAN_SUBAGENT_BASE,this.planGenerationStopped=!1,this.planAgentsMinimized=!1,this.wizardDragState=null,this.wizardDragListeners=null,this.wizardPosition=null,this.projectInsights=new Map,this.logViewerWindows=new Map,this.logViewerWindowZIndex=ZINDEX_LOG_VIEWER_BASE,this.projectInsightsPanelVisible=!1,this.orchestratorState=null,this.orchestratorPanelVisible=!1,this.currentSessionWorkingDir=null,this.imagePopups=new Map,this.imagePopupZIndex=ZINDEX_IMAGE_POPUP_BASE,this.attachmentCards=new Map,this.attachmentCardStack=null,this.attachmentHistoryCounts=new Map,this.attachmentHistoryItems=[],this.attachmentHistoryDrawerOpen=!1,this.fileBrowserData=null,this.fileBrowserExpandedDirs=new Set,this.fileBrowserFilter="",this.fileBrowserAllExpanded=!1,this.fileBrowserDragListeners=null,this.fileBrowserShowHidden=this._loadFileBrowserShowHidden?.()??!1,this.filePreviewContent="",this._toastContainer=null,this._tunnelUrl=null,this.tabAlerts=new Map,this.pendingHooks=new Map,this._closingSessions=new Set,this.approvals=new Map,this._ws=null,this._wsSessionId=null,this._wsReady=!1,this._wsState="disconnected",this._wsLastRecvAt=0,this._wsOutputGapSession=null,this.pendingWrites=[],this.writeFrameScheduled=!1,this._terminalWriteInFlight=!1,this._terminalWriteInFlightBytes=0,this._wasAtBottomBeforeWrite=!0,this.syncWaitTimeout=null,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._bufferLoadSeq=0,this._bufferLoadOwner=null,this._terminalRefreshOwner=null,this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.flickerFilterTimeout=null,this._debounceTimers=Object.create(null),this.systemStatsInterval=null,this.sseReconnectTimeout=null,this._sseListenerCleanup=null,this.reconnectAttempts=0,this.maxReconnectAttempts=10,this.isOnline=navigator.onLine,this._sseLastMessageAt=0,this._sseStaleTimeoutMs=window.CodemanSseStale?.TIMEOUT_MS??45e3,this._sseStaleWatchdog=null,this._sseConnectTimeout=null,this._sseConnectTimeoutMs=window.CodemanSseStale?.CONNECT_TIMEOUT_MS??15e3,this._connDownSince=null,this._nextSseRetryAt=null,this._offlineOverlayDismissed=!1,this._offlineRetryPending=!1,this._offlineUiTicker=null,this._lastOfflineUiKey="",this._connectionStatus="connected",this._clientId="",this._seqCounters=new Map,this._pendingDeliveries=new Map,this._lastIndicatorDescriptor=null,this._lastIndicatorLanguage=null,this._postDraining=new Set,this._extraInputSockets=new Map,this._persistReliableTimer=null,this._reliableAckTimeoutMs=4e3,this._reliableMaxBytes=256*1024,this._loadReliableState(),this._reliableSweepTimer=setInterval(()=>this._redeliverSweep(),2e3),window.addEventListener("pagehide",()=>this._persistReliableNow()),window.addEventListener("pagehide",()=>this._persistPendingTabLayoutEdits()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this._persistReliableNow():this._checkSseStale()}),this._localEchoOverlay=null,this._localEchoEnabled=!1,this._predictiveEcho=null,this._localEchoPolicy="off",this._restoringFlushedState=!1,this.activeFocusTrap=null,this.notificationManager=new NotificationManager(this),this.idleTimers=new Map,this._elemCache={},this.init()}$(e){return this._elemCache[e]||(this._elemCache[e]=document.getElementById(e)),this._elemCache[e]}_clearTimer(e){this[e]&&(clearTimeout(this[e]),this[e]=null)}_isStaleSelect(e){return e!==this._selectGeneration?(this._isLoadingBuffer&&this._finishBufferLoad(e),this._restoringFlushedState=!1,!0):!1}formatTokens(e){if(e>=1e6){const t=e/1e6;return t>=10?`${t.toFixed(1)}m`:`${t.toFixed(2)}m`}else if(e>=1e3){const t=e/1e3;return t>=100?`${t.toFixed(0)}k`:`${t.toFixed(1)}k`}return String(e)}estimateCost(e,t){const s=e/1e6*15,i=t/1e6*75;return s+i}setPendingHook(e,t){this.pendingHooks.has(e)||this.pendingHooks.set(e,new Set),this.pendingHooks.get(e).add(t),this.updateTabAlertFromHooks(e)}clearPendingHooks(e,t=null){const s=this.pendingHooks.get(e);s&&(t?s.delete(t):s.clear(),s.size===0&&this.pendingHooks.delete(e),this.updateTabAlertFromHooks(e))}markIdleAlertSeen(e){this.pendingHooks?.get(e)?.has("idle_prompt")&&(this.clearPendingHooks(e,"idle_prompt"),this.acknowledgeIdleApprovalOnView?.(e))}updateTabAlertFromHooks(e){const t=this.pendingHooks.get(e);!t||t.size===0?this.tabAlerts.delete(e):t.has("permission_prompt")||t.has("elicitation_dialog")?this.tabAlerts.set(e,"action"):t.has("idle_prompt")&&this.tabAlerts.set(e,"idle"),this.renderSessionTabs()}init(){MobileDetection.init(),this._initWindowChannel(),this.isSoloWindow&&document.body.classList.add("solo-mode"),this.isSoloWindow||window.addEventListener("hashchange",()=>{const s=this._takeUrlSession();s&&(this._retireUrlSession(),this._urlSessionId=s,this._selectUrlSession())}),document.documentElement.classList.toggle("host-windows",this.hasHostWindows()),KeyboardHandler.init(),SwipeHandler.init(),VoiceInput.init(),KeyboardAccessoryBar.init();const e=this.loadAppSettingsFromStorage();KeyboardAccessoryBar.setMode(e.extendedKeyboardBar?"extended":"simple"),this.applyHeaderVisibilitySettings(),this.restorePlanUsageChip(),this.applySkin(),this.applyLocalization(),this.applySessionListLayout(),this.applyTabOrientation(),this.initTabRailResize?.(),this.applyMonitorVisibility(),this.applyLineageLineSettings?.(),this._installLineageStripScrollListener?.(),this._setupTabMiddleClickClose(),this.initEntranceAnimations?.(),document.documentElement.classList.remove("mobile-init"),requestAnimationFrame(()=>{this.initTerminal(),this.loadFontSize(),this.connectSSE(),this._initFallbackTimer=setTimeout(()=>{this._initGeneration===0&&this.loadState()},3e3)}),this.registerServiceWorker(),this.loadTunnelStatus(),this.initRebootRestoreBanner?.();const t=fetch("/api/settings").then(s=>s.ok?s.json():null).then(s=>s?.data??null).catch(()=>null);if(this.loadQuickStartCases(null,t),this._initRunMode(),this.initWebviews?.(),this.setupEventListeners(),MobileDetection.isTouchDevice()){const s=i=>{i&&i.addEventListener("touchstart",n=>{if(!KeyboardHandler.keyboardVisible)return;const o=n.target.closest("button");o&&(n.preventDefault(),o.click(),typeof app<"u"&&app.terminal&&app.terminal.focus())},{passive:!1})};s(document.querySelector(".toolbar")),s(document.querySelector(".welcome-overlay"))}this.setupOnlineDetection(),this.loadAppSettingsFromServer(t).then(()=>{this.applyHeaderVisibilitySettings(),this.applySkin(),this.applyLocalization(),this.applySessionListLayout(),this.applyTabOrientation?.(),this.applyMonitorVisibility(),this.applyLineageLineSettings?.(),typeof this.syncAllUltracodeFloatingWindows=="function"&&this.syncAllUltracodeFloatingWindows()}),document.body.classList.add("app-loaded")}_initWebGL(){if(!(typeof WebglAddon>"u"))try{this._webglAddon=new WebglAddon.WebglAddon,this._webglAddon.onContextLoss(()=>{console.error("[CRASH-DIAG] WebGL context LOST \u2014 falling back to canvas renderer"),_crashDiag.log("WEBGL_LOST"),this._disableWebGLSticky("context-lost"),this._disposeWebGLObserver(),this._webglAddon?.dispose(),this._webglAddon=null,this._scheduleTerminalRepaint()}),this.terminal.loadAddon(this._webglAddon),console.log("[CRASH-DIAG] WebGL renderer enabled"),this._installWebGLLongTaskGuard()}catch{}}_installWebGLLongTaskGuard(){if(typeof PerformanceObserver>"u"||this._webglLongTaskObserver)return;const e=performance.now(),t=[];try{this._webglLongTaskObserver=new PerformanceObserver(s=>{if(!this._webglAddon||this._tilesOwnTerminal?.())return;const i=performance.now();i-e<WEBGL_FALLBACK.GRACE_MS||evaluateWebGLLongTaskTrip(t,s.getEntries(),i)&&(console.warn(`[CRASH-DIAG] WebGL long-task threshold (${t.length} stalls/${WEBGL_FALLBACK.WINDOW_MS}ms) \u2014 falling back to canvas renderer`),_crashDiag.log(`WEBGL_FALLBACK: ${t.length}`),this._disableWebGLSticky("long-tasks"),this._disposeWebGLObserver(),this._webglAddon?.dispose(),this._webglAddon=null,this._scheduleTerminalRepaint())}),this._webglLongTaskObserver.observe({type:"longtask",buffered:!1})}catch{}}_disposeWebGLObserver(){if(this._webglLongTaskObserver){try{this._webglLongTaskObserver.disconnect()}catch{}this._webglLongTaskObserver=null}}_scheduleTerminalRepaint(){if(this._terminalRepaintScheduled)return;this._terminalRepaintScheduled=!0,(typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,0))(()=>{this._terminalRepaintScheduled=!1;try{this.terminal?.refresh(0,this.terminal.rows-1)}catch{}})}_disableWebGLSticky(e){try{localStorage.setItem("codeman-webgl-disabled",JSON.stringify({reason:e,at:Date.now()}))}catch{}}setupEventListeners(){const e=this._shortcutActions();document.addEventListener("keydown",s=>{if(s.target?.closest?.("[data-raw-keys]")||s.isComposing||s.keyCode===229)return;if(this.shouldOpenCommandPaletteFromShortcut?.(s)){s.preventDefault(),this.openCommandPalette();return}if(s.key==="Escape"){if(this._tabGroupMenu&&this._tabGroupMenuKeydown){this._tabGroupMenuKeydown(s);return}if(this._tabLayoutDrag?.active&&this._tabLayoutDragKeydown){this._tabLayoutDragKeydown(s);return}if(this._tileCountMenu){this.closeTileCountMenu({refocus:!0});return}if(s.target?.id==="tabRailSearch"&&this._tabRailSearch){this.handleTabRailSearchKeydown(s);return}if(this.isLocalModelWindowOpen?.()){this.closeLocalModelWindow();return}this.closeAllPanels(),this.closeHelp(),this.attachmentHistoryDrawerOpen&&this.closeAttachmentHistory(),this.closeWorktreeModal?.(),this.closeSessionManager(),this.closeCommandPalette?.(),this.closeShortcutOverlay?.(),this._isSessionSidebarOverlay()&&this.isSessionSidebarActive()&&!this.isSessionSidebarCollapsed()&&(this.toggleSessionSidebar(),document.getElementById("sidebarToggleBtn")?.focus())}if(s.altKey&&!s.ctrlKey&&!s.shiftKey){const o=(s.code||"").match(/^Digit([1-9])$/);if(o){const a=parseInt(o[1],10)-1,r=this.sessionOrder.filter(l=>this.sessions.has(l));if(a<r.length)s.preventDefault(),this.selectSession(r[a]);else{const l=a-r.length,c=(this.webviewOrder||[])[l];c&&(s.preventDefault(),this.openWebview(c))}return}}const i=this.tileShortcutFor?.(s);if(i){s.preventDefault(),this.runTileShortcut(i);return}if(!(!s.ctrlKey&&!s.metaKey&&!s.altKey))for(const n of this.getShortcutRegistry()){if(n.disabled||!n.action)continue;const o=e[n.action];if(o&&this.matchesShortcutEvent(s,n)){s.preventDefault(),o();return}}},!0);const t=this.$("headerTokens");t&&!t._statsHandlerAttached&&(t.classList.add("clickable"),t._statsHandlerAttached=!0,t.addEventListener("click",()=>this.openTokenStats())),this.setupColorPicker()}_sseFilterSessionId(e){return this._tilesOwnTerminal?.()&&window.CodemanTileGrid?.TILE_GRID_SSE_FILTER||e}_updateSseSubscription(e){try{const t=this._sseFilterSessionId(e),s=JSON.stringify({clientId:this._clientId,sessions:t?[t]:null});fetch("/api/events/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:s,keepalive:!0}).catch(()=>{})}catch{}}_detectSoloSessionId(){try{if(typeof window<"u"&&typeof window.__CODEMAN_SOLO__=="string"&&window.__CODEMAN_SOLO__)return window.__CODEMAN_SOLO__;const e=window.CodemanBase?.base||"";let t=location.pathname;e&&t.startsWith(e)&&(t=t.slice(e.length)||"/");const s=t.match(/^\/session\/([^/]+)\/?$/);return s?decodeURIComponent(s[1]):null}catch{return null}}_takeUrlSession(){const e=window.CodemanUrlSession?.sessionIdFromFragment(location.hash)??null;if(e)try{history.replaceState(history.state,"",location.pathname+location.search)}catch{}return e}_selectUrlSession(){const e=this._urlSessionId;return e?this.sessions.has(e)?(this._retireUrlSession(),this.selectSession(e,{auto:!0,leaveTiles:!0}),!0):(this._armUrlSessionWait(e),!1):!1}_armUrlSessionWait(e){this._urlSessionWaitTimer||(this._urlSessionWaitTimer=setTimeout(()=>{if(this._urlSessionWaitTimer=null,this._urlSessionId===e){if(this.sessions.has(e)){this._selectUrlSession();return}this._retireUrlSession(),this.showToast?.("Session not found","warning")}},URL_SESSION_WAIT_MS))}_retireUrlSession(){this._urlSessionId=null,this._urlSessionWaitTimer&&(clearTimeout(this._urlSessionWaitTimer),this._urlSessionWaitTimer=null)}detachSession(e,t=null){if(this.isSoloWindow||!this.sessions.has(e)||this.detachedSessions.has(e)&&this._raiseDetached(e))return;const s=this.hasHostWindows()&&!this.windowChannel?!1:this.openInHostWindow(CodemanBase.url("/session/"+encodeURIComponent(e)));if(s!==null){if(!s){this.showToast?.("Could not open a new window for this session","error");return}this._markDetached(e,!0),this._postWindowMessage({type:"detached",id:e});return}const i=this._detachWindowFeatures(t);let n=null;try{n=window.open(CodemanBase.url("/session/"+encodeURIComponent(e)),"codeman-session-"+e,i)}catch{}if(!n){this.showToast?.("Pop-out blocked \u2014 allow popups for this site to detach a session","error");return}this.detachedWindows.set(e,n),this._markDetached(e,!0),this._watchDetachedWindow(e,n),this._postWindowMessage({type:"detached",id:e});try{n.focus()}catch{}}_detachWindowFeatures(e){const t=r=>Number.isFinite(r)?Math.round(r):null,s=t(e?.width)??960,i=t(e?.height)??680,n=t(e?.left),o=t(e?.top),a=n!==null&&o!==null?`,left=${n},top=${o}`:"";return`width=${s},height=${i}${a},menubar=no,toolbar=no,location=no,status=no`}hasHostWindows(){try{return typeof window<"u"&&typeof window.CodemanHost?.openWindow=="function"}catch{return!1}}tabDetachButtonEnabled(e,t={}){return e?.showTabDetachButton??(this.hasHostWindows()||(t?.showTabDetachButton??!1))}openInHostWindow(e){if(!this.hasHostWindows())return null;try{return window.CodemanHost.openWindow(new URL(e,location.href).href)!==!1}catch{return!1}}_raiseDetached(e){const t=this.detachedWindows.get(e);if(t&&!t.closed){try{t.focus()}catch{}return!0}return t&&t.closed?(this._redock(e),!1):(this._postWindowMessage({type:"focus-request",id:e}),!0)}redockSession(e){const t=this.detachedWindows.get(e);if(t&&!t.closed)try{t.close()}catch{}this._postWindowMessage({type:"close-request",id:e}),this._redock(e)}_redock(e){const t=this._detachWatchTimers.get(e);t&&(clearInterval(t),this._detachWatchTimers.delete(e)),this._cancelPendingRedock(e),this._detachOrphanStrikes.delete(e),this.detachedWindows.delete(e),this._markDetached(e,!1),this._lastResizeDims=null,this.sessions.has(e)&&e===this.activeSessionId&&this.sendResize(e,{force:!0})?.catch?.(()=>{})}_scheduleRedock(e){if(this._redockGrace.has(e))return;const t=setTimeout(()=>{this._redockGrace.delete(e),this._redock(e)},1500);this._redockGrace.set(e,t)}_cancelPendingRedock(e){const t=this._redockGrace.get(e);t&&(clearTimeout(t),this._redockGrace.delete(e))}_markDetached(e,t){t?this.detachedSessions.add(e):this.detachedSessions.delete(e),t&&this._tileGrid?.has(e)&&this.removeTile(e,{gone:!0});const s=this.$("sessionTabs"),i=s&&s.querySelector(`.session-tab[data-id="${e}"]`);i&&i.classList.toggle("detached",t)}_watchDetachedWindow(e,t){const s=this._detachWatchTimers.get(e);s&&clearInterval(s);const i=setInterval(()=>{(!t||t.closed)&&(clearInterval(i),this._detachWatchTimers.delete(e),this._redock(e))},800);this._detachWatchTimers.set(e,i)}_initWindowChannel(){if(!(typeof BroadcastChannel>"u")){try{this.windowChannel=new BroadcastChannel("codeman-windows")}catch{this.windowChannel=null;return}if(this.windowChannel.onmessage=e=>this._onWindowMessage(e.data),this.isSoloWindow){this._postWindowMessage({type:"detached",id:this.soloSessionId});const e=()=>this._postWindowMessage({type:"redocked",id:this.soloSessionId});window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}else this._postWindowMessage({type:"roll-call"}),this._startDetachLiveness()}}_postWindowMessage(e){try{this.windowChannel&&this.windowChannel.postMessage(e)}catch{}}_onWindowMessage(e){if(!(!e||typeof e!="object")){if(this.isSoloWindow){if(e.type==="roll-call"){this._soloReleased||this._postWindowMessage({type:"detached",id:this.soloSessionId});return}if(e.id!==this.soloSessionId)return;if(e.type==="close-request")this._releaseSoloWindow();else if(e.type==="focus-request")try{typeof window.CodemanHost?.focusWindow=="function"?window.CodemanHost.focusWindow():window.focus()}catch{}return}if(e.type==="detached"&&e.id){if(this._tileDockedRecently?.(e.id))return;this._cancelPendingRedock(e.id),this._detachPingPending?.delete(e.id),this._detachOrphanStrikes.delete(e.id),this._markDetached(e.id,!0)}else e.type==="redocked"&&e.id?this._scheduleRedock(e.id):e.type==="detach-request"&&e.id?this.detachSession(e.id):e.type==="tile-adopted"&&e.id&&e.by!==this._wsTabNonce&&this._onTileAdoptedElsewhere?.(e.id)}}_startDetachLiveness(){this._detachLivenessTimer||(this._detachLivenessTimer=setInterval(()=>this._pingDetached(),5e3))}_pingDetached(){const e=[];for(const t of this.detachedSessions){const s=this.detachedWindows.get(t);s?s.closed&&this._redock(t):e.push(t)}e.length&&(this._detachPingPending=new Set(e),this._postWindowMessage({type:"roll-call"}),setTimeout(()=>{if(this._detachPingPending){for(const t of this._detachPingPending){const s=(this._detachOrphanStrikes.get(t)||0)+1;s>=2?(this._detachOrphanStrikes.delete(t),this._redock(t)):this._detachOrphanStrikes.set(t,s)}this._detachPingPending=null}},1200))}_closeSoloWindow(){try{typeof window.CodemanHost?.closeWindow=="function"?window.CodemanHost.closeWindow():window.close()}catch{}}_releaseSoloWindow(){this._soloReleased||(this._soloReleased=!0,this._postWindowMessage({type:"redocked",id:this.soloSessionId}),this._closeSoloWindow(),setTimeout(()=>{window.closed||this._showSoloReleased()},300))}_showSoloReleased(){if(document.querySelector(".solo-gone-overlay"))return;const e=document.createElement("div");e.className="solo-gone-overlay";const t=document.createElement("h2");t.textContent="Session moved";const s=document.createElement("p");s.textContent="This session is back in a Codeman window. This one can be closed.";const i=document.createElement("button");i.className="btn-primary",i.textContent="Close window",i.addEventListener("click",()=>this._closeSoloWindow()),e.append(t,s,i),document.body.appendChild(e)}_applySoloMode(){document.body.classList.add("solo-mode");const e=this.sessions.get(this.soloSessionId);if(!e){this._showSoloSessionGone();return}this.activeSessionId=null,this.selectSession(this.soloSessionId,{auto:!0});const t=this.getSessionName(e)||"Session",s=document.getElementById("soloSessionTitle");s&&(s.textContent=t,s.style.display="");const i=document.getElementById("soloRedockBtn");i&&(i.style.display=""),this._installSoloTileHandle?.(),document.title=t+" \u2014 "+(window.CodemanI18n?.displayName||"Codeman"),this.notificationManager&&(this.notificationManager.originalTitle=document.title);const n=document.querySelector(".header-brand .logo");n&&(n.onclick=o=>{o.preventDefault()})}_showSoloSessionGone(){if(document.body.classList.add("solo-mode"),document.querySelector(".solo-gone-overlay"))return;const e=document.createElement("div");e.className="solo-gone-overlay",e.innerHTML='<h2>Session unavailable</h2><p>This session has ended or is no longer available.</p><button class="btn-primary" onclick="app._closeSoloWindow()">Close window</button>',document.body.appendChild(e),document.title=(window.codemanT?.("Session ended")||"Session ended")+" \u2014 "+(window.CodemanI18n?.displayName||"Codeman")}connectSSE(){if(this._clearTimer("_sseConnectTimeout"),!navigator.onLine){this.setConnectionStatus("offline");return}this._clearTimer("sseReconnectTimeout"),this._sseStaleWatchdog&&(clearInterval(this._sseStaleWatchdog),this._sseStaleWatchdog=null),this._sseListenerCleanup&&(this._sseListenerCleanup(),this._sseListenerCleanup=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.reconnectAttempts===0?this.setConnectionStatus("connecting"):this.setConnectionStatus("reconnecting");const e=new URLSearchParams({clientId:this._clientId}),t=this._sseFilterSessionId(this.activeSessionId);t&&e.set("sessions",t);const s=new EventSource(CodemanBase.url(`/api/events?${e.toString()}`));this.eventSource=s;const i=setTimeout(()=>{this._sseConnectTimeout===i&&(this._sseConnectTimeout=null,!(this.eventSource!==s||s.readyState===EventSource.OPEN)&&(console.warn(`[SSE] connection did not open within ${this._sseConnectTimeoutMs}ms, retrying`),this._handleSseConnectionFailure(s)))},this._sseConnectTimeoutMs);this._sseConnectTimeout=i;const n=[],o=(a,r)=>{const l=c=>{this._sseLastMessageAt=Date.now(),r(c)};this.eventSource.addEventListener(a,l),n.push({event:a,handler:l})};if(this._sseListenerCleanup=()=>{for(const{event:a,handler:r}of n)this.eventSource&&this.eventSource.removeEventListener(a,r);n.length=0},this.eventSource.onopen=()=>{this._clearTimer("_sseConnectTimeout"),this.reconnectAttempts=0,this._sseLastMessageAt=Date.now(),this.setConnectionStatus("connected")},this.eventSource.onerror=()=>this._handleSseConnectionFailure(s),!this._sseHandlerWrappers){this._sseHandlerWrappers=new Map;for(const[a,r]of _SSE_HANDLER_MAP){const l=this[r],c=r==="_onSSETerminal"||r==="_onSSENeedsRefresh"||r==="_onSSEClearTerminal";this._sseHandlerWrappers.set(a,h=>{if(!(c&&this._wsReady))try{l.call(this,h.data?JSON.parse(h.data):{})}catch(d){console.error(`[SSE] Error handling ${a}:`,d)}})}}for(const[a]of _SSE_HANDLER_MAP)o(a,this._sseHandlerWrappers.get(a));for(const a of[SSE_EVENTS.SESSION_CREATED,SSE_EVENTS.SESSION_DELETED])o(a,()=>this._onSessionListMaybeChanged());o(SSE_EVENTS.DOCKER_EXPORT_COMPLETE,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Docker export ready: ${r.bundle} (${Math.round((r.sizeBytes||0)/1e6)} MB)`,"success"),this.refreshDockerExports?.()}catch(r){console.error("[SSE] docker export complete:",r)}}),o(SSE_EVENTS.DOCKER_EXPORT_FAILED,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Docker export failed: ${r.error||"unknown error"}`,"error")}catch(r){console.error("[SSE] docker export failed:",r)}}),o(SSE_EVENTS.DOCKER_IMPORT_COMPLETE,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Docker bundle imported as case "${r.name}"`,"success"),this.loadQuickStartCases?.(),this.refreshDockerExports?.()}catch(r){console.error("[SSE] docker import complete:",r)}}),o(SSE_EVENTS.DOCKER_CONTAINER_RECREATED,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Container for "${r.name}" removed \u2014 next launch recreates it with the new config`,"info")}catch(r){console.error("[SSE] docker container recreated:",r)}}),o(SSE_EVENTS.CUSTOM_MODEL_SWAPPED_OUT,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`${r.sessionName||r.sessionId}'s model (${r.previousModel}) was swapped out on llama-swap by another session \u2014 currently loaded: ${r.currentlyLoadedModel}. Sending a message there will reload it.`,"warning",{duration:0})}catch(r){console.error("[SSE] custom model swapped out:",r)}}),o(SSE_EVENTS.ADMIN_USERS_CHANGED,()=>{window.codemanAdmin?.onUsersChanged?.()}),o(SSE_EVENTS.DOCKER_IMAGE_BUILD_STARTED,()=>{this.showToast("Building the Codeman agent image (first Docker case, a few minutes)...","info",{duration:8e3})}),o(SSE_EVENTS.DOCKER_IMAGE_BUILD_COMPLETE,a=>{try{const r=a.data?JSON.parse(a.data):{};r.error?this.showToast(`Agent image build failed: ${r.error}`,"error"):this.showToast("Agent image ready. Starting the container...","success")}catch(r){console.error("[SSE] docker image build complete:",r)}}),o(SSE_EVENTS.DOCKER_IMAGE_BUILD_FAILED,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Agent image build failed: ${r.error||"unknown error"}`,"error")}catch(r){console.error("[SSE] docker image build failed:",r)}}),o(SSE_EVENTS.SESSION_PINNED,a=>{let r=null;try{r=JSON.parse(a.data)}catch{}if(r&&r.id){const l=this.sessions.get(r.id);l&&(l.pinned=r.pinned===!0,l.pinnedAt=r.pinned?r.pinnedAt:void 0)}this._onSessionListMaybeChanged()}),o(SSE_EVENTS.HEARTBEAT,()=>{}),this._sseStaleWatchdog=setInterval(()=>this._checkSseStale(),5e3)}_handleSseConnectionFailure(e){if(this.eventSource!==e)return;this._clearTimer("_sseConnectTimeout"),this.reconnectAttempts++,this.reconnectAttempts>=this.maxReconnectAttempts?this.setConnectionStatus("disconnected"):this.setConnectionStatus("reconnecting"),this.eventSource=null,e.close(),this._clearTimer("sseReconnectTimeout");const t=this.reconnectAttempts<=1?200:Math.min(500*Math.pow(2,this.reconnectAttempts-2),3e4);this._nextSseRetryAt=Date.now()+t,this._updateConnectionLossUi(),this.sseReconnectTimeout=setTimeout(()=>this.connectSSE(),t)}_checkSseStale(){const e=window.CodemanSseStale;if(!e)return;const t=Date.now();e.compute({lastMessageAt:this._sseLastMessageAt,now:t,status:this._connectionStatus,isOnline:this.isOnline,timeoutMs:this._sseStaleTimeoutMs})&&(console.log(`[SSE] stream stale: no frame for ${t-this._sseLastMessageAt}ms (threshold ${this._sseStaleTimeoutMs}ms), forcing reconnect`),this.connectSSE())}_onInit(e){_crashDiag.log(`INIT: ${e.sessions?.length||0} sessions`),this.handleInit(e),this._ensureHostWakePoller?.()}_onSessionCreated(e){this._closingSessions?.has(e.id)||(this.sessions.set(e.id,e),this.sessionOrder.includes(e.id)||this.syncSessionOrder(),this.markSessionTabEntering?.(e.id),this.markTerminalEntering?.(e.id),e.parentSessionId&&this.markConnectionLineEntering?.("lineage:"+e.id),this.renderSessionTabs(),this.updateCost(),this._urlSessionId===e.id&&this._selectUrlSession())}_onSessionUpdated(e){const t=e.session||e;if(this._closingSessions?.has(t.id))return;const s=this.sessions.get(t.id),i=t.claudeSessionId&&(!s||!s.claudeSessionId);this.sessions.set(t.id,t),this.renderSessionTabs(),this.updateCost(),t.id===this.activeSessionId&&t.tokens&&this.updateRespawnTokens(t.tokens),t.id===this.activeSessionId&&this._reconcileKeyboardHold?.(),t.id===this.activeSessionId&&this._followFileBrowserWorktree?.(t),this.updateSubagentParentNames(t.id),this.editingSessionId===t.id&&this.updateGitFetchStatus(t.id),i&&(this.recheckOrphanSubagents(),requestAnimationFrame(()=>{this.updateConnectionLines()}))}_onSessionDeleted(e){if(this._wsSessionId===e.id&&this._disconnectWs(),this.isSoloWindow&&e.id===this.soloSessionId&&this._showSoloSessionGone(),this.detachedSessions.has(e.id)&&this._redock(e.id),this._cleanupSessionData(e.id),this.activeSessionId===e.id&&!this._closingSessions.has(e.id)){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome()}this.renderSessionTabs(),this.renderRalphStatePanel(),this.renderProjectInsightsPanel()}_onSSETerminal(e){this._wsReady||this._onSessionTerminal(e)}_onSSENeedsRefresh(e){this._wsReady||this._onSessionNeedsRefresh(e)}_onSSEClearTerminal(e){this._wsReady||this._onSessionClearTerminal(e)}_bufferLoadFinishOpts(e,t){return{flushQueued:e?.source==="mux-visible"||e?.source==="mux-full-history",since:t}}_onSessionTerminal(e){if(!this._tilesOwnTerminal?.()&&e.id===this.activeSessionId){e.data.length>32768&&_crashDiag.log(`TERMINAL: ${(e.data.length/1024).toFixed(0)}KB`);const t=(this.pendingWrites?.reduce((s,i)=>s+i.length,0)||0)+(this.flickerFilterBuffer?.length||0)+(this._loadBufferQueue?.reduce((s,i)=>s+i.data.length,0)||0)+(this._terminalWriteInFlightBytes||0);if(t+e.data.length>131072){this._scheduleDroppedOutputRecovery(e.id,0,t);return}this.batchTerminalWrite(e.data)}}_scheduleDroppedOutputRecovery(e,t=0,s){!e||this._clientDropRecoveryTimer||this._tilesOwnTerminal?.()||(Number.isFinite(s)&&_crashDiag.log(`TERMINAL DROP: ${(s/1024).toFixed(0)}KB queued`),this._clientDropRecoveryTimer=setTimeout(async()=>{this._clientDropRecoveryTimer=null;let i=!1,n=!1;try{const a=await this._onSessionNeedsRefresh({id:e});i=a===!0,n=a==="deadline"}catch{}window.CodemanDroppedOutput.shouldRetryDroppedOutputRecovery({repainted:i,timedOut:n,attempt:t,stillActive:this.activeSessionId===e})&&(_crashDiag.log(`DROP RECOVERY: attempt ${t+1} did not repaint, retrying`),this._scheduleDroppedOutputRecovery(e,t+1))},window.CodemanDroppedOutput.DROP_RECOVERY_DELAY_MS))}_sanitizeHtml(e){return typeof window<"u"&&typeof window.sanitizeMarkdownHtml=="function"?window.sanitizeMarkdownHtml(e):String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}_cleanTerminalBuffer(e){const t=e.replace(/\x1b\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[PX^_][^\x1b]*\x1b\\/g,"").replace(/\x1b[NO()][A-Z0-9]?/g,"").replace(/\x1b[>=<78cDEHM]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").replace(/\r\n/g,`
|
|
7
|
+
Stack:`,m.reason?.stack)}),typeof PerformanceObserver<"u")try{new PerformanceObserver(e=>{for(const t of e.getEntries())t.duration>200&&(_crashDiag.log(`LONG_TASK: ${t.duration.toFixed(0)}ms`),console.warn(`[CRASH-DIAG] Long task: ${t.duration.toFixed(0)}ms (type: ${t.entryType}, name: ${t.name})`))}).observe({type:"longtask",buffered:!0})}catch{}const _origGetContext=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(m,...e){const t=_origGetContext.call(this,m,...e);return(m==="webgl2"||m==="webgl")&&(this.addEventListener("webglcontextlost",s=>{_crashDiag.log(`WEBGL_LOST: ${this.width}x${this.height}`),console.error("[CRASH-DIAG] WebGL context LOST on canvas",this.width,"x",this.height,"\u2014 prevented:",s.defaultPrevented)}),this.addEventListener("webglcontextrestored",()=>{_crashDiag.log("WEBGL_RESTORED"),console.warn("[CRASH-DIAG] WebGL context restored")})),t};const _SSE_HANDLER_MAP=[[SSE_EVENTS.INIT,"_onInit"],[SSE_EVENTS.SESSION_CREATED,"_onSessionCreated"],[SSE_EVENTS.SESSION_UPDATED,"_onSessionUpdated"],[SSE_EVENTS.SESSION_DELETED,"_onSessionDeleted"],[SSE_EVENTS.SESSION_TERMINAL,"_onSSETerminal"],[SSE_EVENTS.SESSION_NEEDS_REFRESH,"_onSSENeedsRefresh"],[SSE_EVENTS.SESSION_CLEAR_TERMINAL,"_onSSEClearTerminal"],[SSE_EVENTS.SESSION_COMPLETION,"_onSessionCompletion"],[SSE_EVENTS.SESSION_ERROR,"_onSessionError"],[SSE_EVENTS.SESSION_EXIT,"_onSessionExit"],[SSE_EVENTS.SESSION_IDLE,"_onSessionIdle"],[SSE_EVENTS.SESSION_WORKING,"_onSessionWorking"],[SSE_EVENTS.SESSION_AUTO_CLEAR,"_onSessionAutoClear"],[SSE_EVENTS.SESSION_LIMIT_PAUSE_SCHEDULED,"_onSessionLimitPauseScheduled"],[SSE_EVENTS.SESSION_LIMIT_RESUME,"_onSessionLimitResume"],[SSE_EVENTS.SESSION_LIMIT_RESUME_CANCELLED,"_onSessionLimitResumeCancelled"],[SSE_EVENTS.SESSION_RESPAWN_BREAKER_TRIPPED,"_onSessionRespawnBreakerTripped"],[SSE_EVENTS.SESSION_CLI_INFO,"_onSessionCliInfo"],[SSE_EVENTS.SESSION_STATUS_TELEMETRY,"_onSessionStatusTelemetry"],[SSE_EVENTS.SESSION_PROMPT_CACHE,"_onSessionPromptCache"],[SSE_EVENTS.SESSION_KEEP_WARM,"_onSessionKeepWarm"],[SSE_EVENTS.SCHEDULED_CREATED,"_onScheduledCreated"],[SSE_EVENTS.SCHEDULED_UPDATED,"_onScheduledUpdated"],[SSE_EVENTS.SCHEDULED_COMPLETED,"_onScheduledCompleted"],[SSE_EVENTS.SCHEDULED_STOPPED,"_onScheduledStopped"],[SSE_EVENTS.CRON_JOBS_CHANGED,"_onCronJobsChanged"],[SSE_EVENTS.CRON_JOB_DELETED,"_onCronJobsChanged"],[SSE_EVENTS.CRON_RUN_CREATED,"_onCronRunChanged"],[SSE_EVENTS.CRON_RUN_UPDATED,"_onCronRunChanged"],[SSE_EVENTS.RESPAWN_STARTED,"_onRespawnStarted"],[SSE_EVENTS.RESPAWN_STOPPED,"_onRespawnStopped"],[SSE_EVENTS.RESPAWN_STATE_CHANGED,"_onRespawnStateChanged"],[SSE_EVENTS.RESPAWN_CYCLE_STARTED,"_onRespawnCycleStarted"],[SSE_EVENTS.RESPAWN_BLOCKED,"_onRespawnBlocked"],[SSE_EVENTS.RESPAWN_AUTO_ACCEPT_SENT,"_onRespawnAutoAcceptSent"],[SSE_EVENTS.RESPAWN_DETECTION_UPDATE,"_onRespawnDetectionUpdate"],[SSE_EVENTS.RESPAWN_TIMER_STARTED,"_onRespawnTimerStarted"],[SSE_EVENTS.RESPAWN_TIMER_CANCELLED,"_onRespawnTimerCancelled"],[SSE_EVENTS.RESPAWN_TIMER_COMPLETED,"_onRespawnTimerCompleted"],[SSE_EVENTS.RESPAWN_ERROR,"_onRespawnError"],[SSE_EVENTS.RESPAWN_ACTION_LOG,"_onRespawnActionLog"],[SSE_EVENTS.TASK_CREATED,"_onTaskCreated"],[SSE_EVENTS.TASK_COMPLETED,"_onTaskCompleted"],[SSE_EVENTS.TASK_FAILED,"_onTaskFailed"],[SSE_EVENTS.TASK_UPDATED,"_onTaskUpdated"],[SSE_EVENTS.MUX_CREATED,"_onMuxCreated"],[SSE_EVENTS.MUX_KILLED,"_onMuxKilled"],[SSE_EVENTS.MUX_DIED,"_onMuxDied"],[SSE_EVENTS.MUX_STATS_UPDATED,"_onMuxStatsUpdated"],[SSE_EVENTS.REMOTE_SESSION_RECONNECTED,"_onRemoteSessionReconnected"],[SSE_EVENTS.REMOTE_RECONNECT_EXHAUSTED,"_onRemoteReconnectExhausted"],[SSE_EVENTS.REMOTE_HOST_WAKING,"_onRemoteHostWaking"],[SSE_EVENTS.REMOTE_HOST_WAKE_FAILED,"_onRemoteHostWakeFailed"],[SSE_EVENTS.SESSION_RALPH_LOOP_UPDATE,"_onRalphLoopUpdate"],[SSE_EVENTS.SESSION_RALPH_TODO_UPDATE,"_onRalphTodoUpdate"],[SSE_EVENTS.SESSION_RALPH_COMPLETION_DETECTED,"_onRalphCompletionDetected"],[SSE_EVENTS.SESSION_RALPH_STATUS_UPDATE,"_onRalphStatusUpdate"],[SSE_EVENTS.SESSION_CIRCUIT_BREAKER_UPDATE,"_onCircuitBreakerUpdate"],[SSE_EVENTS.SESSION_EXIT_GATE_MET,"_onExitGateMet"],[SSE_EVENTS.SESSION_BASH_TOOL_START,"_onBashToolStart"],[SSE_EVENTS.SESSION_BASH_TOOL_END,"_onBashToolEnd"],[SSE_EVENTS.SESSION_BASH_TOOLS_UPDATE,"_onBashToolsUpdate"],[SSE_EVENTS.HOOK_IDLE_PROMPT,"_onHookIdlePrompt"],[SSE_EVENTS.HOOK_PERMISSION_PROMPT,"_onHookPermissionPrompt"],[SSE_EVENTS.HOOK_ELICITATION_DIALOG,"_onHookElicitationDialog"],[SSE_EVENTS.HOOK_ELICITATION_COMPLETE,"_onHookElicitationComplete"],[SSE_EVENTS.HOOK_ELICITATION_RESPONSE,"_onHookElicitationResponse"],[SSE_EVENTS.HOOK_STOP,"_onHookStop"],[SSE_EVENTS.HOOK_AGENT_WORKING,"_onHookAgentWorking"],[SSE_EVENTS.HOOK_TEAMMATE_IDLE,"_onHookTeammateIdle"],[SSE_EVENTS.HOOK_TASK_COMPLETED,"_onHookTaskCompleted"],[SSE_EVENTS.APPROVAL_PENDING,"_onApprovalPending"],[SSE_EVENTS.APPROVAL_UPDATED,"_onApprovalUpdated"],[SSE_EVENTS.APPROVAL_RESOLVED,"_onApprovalResolved"],[SSE_EVENTS.SUBAGENT_DISCOVERED,"_onSubagentDiscovered"],[SSE_EVENTS.SUBAGENT_UPDATED,"_onSubagentUpdated"],[SSE_EVENTS.SUBAGENT_TOOL_CALL,"_onSubagentToolCall"],[SSE_EVENTS.SUBAGENT_PROGRESS,"_onSubagentProgress"],[SSE_EVENTS.SUBAGENT_MESSAGE,"_onSubagentMessage"],[SSE_EVENTS.SUBAGENT_TOOL_RESULT,"_onSubagentToolResult"],[SSE_EVENTS.SUBAGENT_COMPLETED,"_onSubagentCompleted"],[SSE_EVENTS.WORKFLOW_RUN_DISCOVERED,"_onWorkflowRunDiscovered"],[SSE_EVENTS.WORKFLOW_RUN_UPDATED,"_onWorkflowRunUpdated"],[SSE_EVENTS.WORKFLOW_RUN_REMOVED,"_onWorkflowRunRemoved"],[SSE_EVENTS.IMAGE_DETECTED,"_onImageDetected"],[SSE_EVENTS.ATTACHMENT_DETECTED,"_onAttachmentDetected"],[SSE_EVENTS.TRANSCRIPT_TOOL_END,"_onEditHistoryTranscriptEvent"],[SSE_EVENTS.TUNNEL_STARTED,"_onTunnelStarted"],[SSE_EVENTS.TUNNEL_STOPPED,"_onTunnelStopped"],[SSE_EVENTS.TUNNEL_PROGRESS,"_onTunnelProgress"],[SSE_EVENTS.TUNNEL_ERROR,"_onTunnelError"],[SSE_EVENTS.TUNNEL_QR_ROTATED,"_onTunnelQrRotated"],[SSE_EVENTS.TUNNEL_QR_REGENERATED,"_onTunnelQrRegenerated"],[SSE_EVENTS.TUNNEL_QR_AUTH_USED,"_onTunnelQrAuthUsed"],[SSE_EVENTS.PLAN_SUBAGENT,"_onPlanSubagent"],[SSE_EVENTS.PLAN_PROGRESS,"_onPlanProgress"],[SSE_EVENTS.PLAN_STARTED,"_onPlanStarted"],[SSE_EVENTS.PLAN_CANCELLED,"_onPlanCancelled"],[SSE_EVENTS.PLAN_COMPLETED,"_onPlanCompleted"],[SSE_EVENTS.ORCHESTRATOR_STATE_CHANGED,"_onOrchestratorStateChanged"],[SSE_EVENTS.ORCHESTRATOR_PLAN_PROGRESS,"_onOrchestratorPlanProgress"],[SSE_EVENTS.ORCHESTRATOR_PLAN_READY,"_onOrchestratorPlanReady"],[SSE_EVENTS.ORCHESTRATOR_PHASE_STARTED,"_onOrchestratorPhaseStarted"],[SSE_EVENTS.ORCHESTRATOR_PHASE_COMPLETED,"_onOrchestratorPhaseCompleted"],[SSE_EVENTS.ORCHESTRATOR_PHASE_FAILED,"_onOrchestratorPhaseFailed"],[SSE_EVENTS.ORCHESTRATOR_VERIFICATION,"_onOrchestratorVerification"],[SSE_EVENTS.ORCHESTRATOR_TASK_ASSIGNED,"_onOrchestratorTaskAssigned"],[SSE_EVENTS.ORCHESTRATOR_TASK_COMPLETED,"_onOrchestratorTaskCompleted"],[SSE_EVENTS.ORCHESTRATOR_TASK_FAILED,"_onOrchestratorTaskFailed"],[SSE_EVENTS.ORCHESTRATOR_COMPLETED,"_onOrchestratorCompleted"],[SSE_EVENTS.ORCHESTRATOR_ERROR,"_onOrchestratorError"],[SSE_EVENTS.CLIPBOARD_WRITE,"_onClipboardWrite"],[SSE_EVENTS.SESSION_ORDER_CHANGED,"_onSessionOrderChanged"],[SSE_EVENTS.TAB_LAYOUT_CHANGED,"_onTabLayoutChanged"],[SSE_EVENTS.WEBVIEW_CHANGED,"_onWebviewChanged"]];function parseSessionPrefix(m){if(!m)return null;const e=m.match(/^(w\d+-[a-zA-Z0-9_-]+|s\d+-[a-zA-Z0-9_-]+)/);if(!e)return null;const t=e[1],s=m.slice(t.length);return s===""?{prefix:t,suffix:""}:s.startsWith(": ")?{prefix:t,suffix:s.slice(2)}:null}function paneExitLabel(m){return!m||typeof m!="object"?"":typeof m.signal=="number"&&m.signal>0?`exited (signal ${m.signal})`:typeof m.status=="number"?`exited (${m.status})`:"exited"}function paneExitAriaLabel(m,e){return e?`${m} session, agent ${e}`:`${m} session`}function applyPaneExitBadge(m,e){const t=paneExitLabel(e),s=m.querySelector(".tab-exited-badge");m.classList.toggle("tab-agent-exited",!!t);const i=m.querySelector(".tab-name")?.dataset?.fullName;if(i){const n=paneExitAriaLabel(i,t);m.dataset.ariaSource!==n&&(m.dataset.ariaSource=n,m.setAttribute("aria-label",n))}if(!t){s?.remove();return}if(!s){const n=document.createElement("span");n.className="tab-exited-badge",n.setAttribute("aria-hidden","true"),n.dataset.label=t,n.textContent=t,m.querySelector(".tab-name")?.insertAdjacentElement("afterend",n);return}s.dataset.label!==t&&(s.dataset.label=t,s.textContent=t)}const DEFAULT_SHORTCUTS=[{id:"show-shortcuts",group:"Panels",label:"Show Shortcuts",bindings:[{modifiers:["ctrl"],key:"?",code:"Slash"},{modifiers:["ctrl","shift"],key:"?"},{modifiers:["alt"],key:"?",code:"Slash"}],action:"showShortcutOverlay"},{id:"close-session",group:"Session",label:"Close Session",bindings:[],action:"killActiveSession"},{id:"next-session",group:"Session",label:"Next Session",bindings:[{modifiers:["ctrl"],key:"Tab"}],action:"nextSession"},{id:"clear-terminal",group:"Terminal",label:"Clear Terminal",bindings:[{modifiers:["ctrl"],key:"l"}],action:"clearTerminal"},{id:"copy-selection",group:"Terminal",label:"Copy Selection",bindings:[{modifiers:["ctrl"],key:"c"},{modifiers:["ctrl","shift"],key:"C"}],action:"copyTerminalSelection"},{id:"increase-font",group:"Terminal",label:"Increase Font",bindings:[{modifiers:["ctrl"],key:"=",code:"Equal"},{modifiers:["ctrl"],key:"+",code:"Equal"}],action:"increaseFontSize"},{id:"decrease-font",group:"Terminal",label:"Decrease Font",bindings:[{modifiers:["ctrl"],key:"-",code:"Minus"}],action:"decreaseFontSize"},{id:"voice-input",group:"Terminal",label:"Voice Input",bindings:[{modifiers:["ctrl","shift"],key:"V"}],action:"toggleVoiceInput"},{id:"restore-terminal-size",group:"Terminal",label:"Restore Terminal Size",bindings:[{modifiers:["ctrl","shift"],key:"R"}],action:"restoreTerminalSize"},{id:"move-tab-left",group:"Tabs",label:"Move Active Tab Left",bindings:[{modifiers:["ctrl","shift"],key:"{",code:"BracketLeft"}],action:"moveActiveTabLeft"},{id:"move-tab-right",group:"Tabs",label:"Move Active Tab Right",bindings:[{modifiers:["ctrl","shift"],key:"}",code:"BracketRight"}],action:"moveActiveTabRight"},{id:"command-palette",group:"Session",label:"Find Open Session",bindings:[{modifiers:["ctrl"],key:"k",code:"KeyK"},{modifiers:["meta"],key:"k",code:"KeyK"},{modifiers:["alt"],key:"k",code:"KeyK"}],action:"openCommandPalette"},{id:"toggle-session-sidebar",group:"Session",label:"Toggle Session Sidebar",bindings:[{modifiers:["alt"],key:"b",code:"KeyB"}],action:"toggleSessionSidebar"},{id:"toggle-tile-grid",group:"Tiles",label:"Toggle Tile Grid",bindings:[{modifiers:["ctrl","shift"],key:"G",code:"KeyG"}],action:"toggleTileGrid"},{id:"focus-tile-left",group:"Tiles",label:"Focus Tile Left",bindings:[{modifiers:["alt","shift"],key:"ArrowLeft"}],action:"focusTileLeft"},{id:"focus-tile-right",group:"Tiles",label:"Focus Tile Right",bindings:[{modifiers:["alt","shift"],key:"ArrowRight"}],action:"focusTileRight"},{id:"focus-tile-up",group:"Tiles",label:"Focus Tile Up",bindings:[{modifiers:["alt","shift"],key:"ArrowUp"}],action:"focusTileUp"},{id:"focus-tile-down",group:"Tiles",label:"Focus Tile Down",bindings:[{modifiers:["alt","shift"],key:"ArrowDown"}],action:"focusTileDown"},{id:"move-tile-left",group:"Tiles",label:"Move Tile Left",bindings:[{modifiers:["ctrl","shift"],key:"ArrowLeft"}],action:"moveTileLeft"},{id:"move-tile-right",group:"Tiles",label:"Move Tile Right",bindings:[{modifiers:["ctrl","shift"],key:"ArrowRight"}],action:"moveTileRight"},{id:"move-tile-up",group:"Tiles",label:"Move Tile Up",bindings:[{modifiers:["ctrl","shift"],key:"ArrowUp"}],action:"moveTileUp"},{id:"move-tile-down",group:"Tiles",label:"Move Tile Down",bindings:[{modifiers:["ctrl","shift"],key:"ArrowDown"}],action:"moveTileDown"},{id:"zoom-tile",group:"Tiles",label:"Zoom Focused Tile",bindings:[{modifiers:["alt","shift"],key:"Enter"}],action:"zoomTile"},{id:"remove-tile",group:"Tiles",label:"Remove Focused Tile",bindings:[],action:"removeTile"},{id:"previous-session",group:"Session",label:"Previous Session",displayBindings:["Alt/Option+["],bindings:[{modifiers:["alt"],code:"BracketLeft"}],action:"previousSession"},{id:"next-session-alt",group:"Session",label:"Next Session (alternate)",displayBindings:["Alt/Option+]"],bindings:[{modifiers:["alt"],code:"BracketRight"}],action:"nextSession"},{id:"switch-tab-n",group:"Session",label:"Switch to Tab N",displayBindings:["Alt/Option+1-9"]},{id:"focus-tabs",group:"Tabs",label:"Focus Tabs",displayBindings:["ArrowLeft","ArrowRight","Home","End"]},{id:"activate-focused-tab",group:"Tabs",label:"Activate Focused Tab",displayBindings:["Enter","Space"]},{id:"insert-newline",group:"Terminal",label:"Insert Newline",displayBindings:["Shift+Enter","Ctrl+Enter"]},{id:"close-panels",group:"Panels",label:"Close Panels",displayBindings:["Escape"]},{id:"file-preview-history",group:"Panels",label:"File Viewer Back / Forward",displayBindings:["Alt/Option+ArrowLeft","Alt/Option+ArrowRight"]}],SIDEBAR_RICH_CLOCK_MS=2e4,CONNECTION_BACKLOG_HINT_BYTES=4,CONNECTION_BACKLOG_HOLD_MS=1200,URL_SESSION_WAIT_MS=3e4,TAB_LAYOUT_PENDING_MAX_AGE_MS=6e4,TAB_GROUP_ARRIVAL_MS=2e3;class CodemanApp{constructor(){this.sessions=new Map,this._shortIdCache=new Map,this.sessionOrder=[],this.draggedTabId=null,this.tabLayout=null,this.collapsedTabGroupIds=new Set,this._hiddenTabGroupByRef=new Map,this._lastTabGroupStructureKey=null,this._tabRailSearch="",this.cases=[],this.currentRun=null,this.totalTokens=0,this.globalStats=null,this.eventSource=null,this._clientId=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"c-"+Math.random().toString(36).slice(2)+Date.now().toString(36),this._wsTabNonce=this._clientId,this.terminal=null,this.fitAddon=null,this.activeSessionId=null,this.soloSessionId=this._detectSoloSessionId(),this.isSoloWindow=!!this.soloSessionId,this._urlSessionId=this.isSoloWindow?null:this._takeUrlSession(),this._urlSessionWaitTimer=null,this.detachedSessions=new Set,this.detachedWindows=new Map,this._detachWatchTimers=new Map,this.windowChannel=null,this._redockGrace=new Map,this._detachPingPending=null,this._detachLivenessTimer=null,this._detachOrphanStrikes=new Map,this._initGeneration=0,this._initFallbackTimer=null,this._selectGeneration=0,this._fullHistoryLoaded=new Set,this._paneHistoryLines=new Map,this._fullHistoryRepullAt=new Map,this._fullHistoryRepullInFlight=!1,this._fullHistoryRepullUseless=new Set,this._geometryRetryUseless=new Set,this.terminalLoadStates=new Map,this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},this.timerCountdownInterval=null,this.terminalBuffers=new Map,this.editingSessionId=null,this.pendingCloseSessionId=null,this.muxSessions=[],this.ralphStates=new Map,this.subagents=new Map,this.subagentActivity=new Map,this.subagentToolResults=new Map,this.activeSubagentId=null,this.subagentPanelVisible=!1,this.workflowRuns=new Map,this.workflowRunDetails=new Map,this.activeWorkflowRunId=null,this.activeWorkflowPhaseIndex=null,this.ultracodeWindows=new Map,this.ultracodeWindowsClosed=new Set,this.ultracodeWindowCloseTimers=new Map,this.ultracodeWindowZIndex=1e3,this.subagentWindows=new Map,this.subagentWindowZIndex=ZINDEX_SUBAGENT_BASE,this.minimizedSubagents=new Map,this._subagentHideTimeout=null,this.subagentParentMap=new Map,this.teams=new Map,this.teamTasks=new Map,this.teammateMap=new Map,this.teammatePanesByName=new Map,this.teammateTerminals=new Map,this.terminalBufferCache=new Map,this.ralphStatePanelCollapsed=!0,this.ralphClosedSessions=new Set,this.planSubagents=new Map,this.planSubagentWindowZIndex=ZINDEX_PLAN_SUBAGENT_BASE,this.planGenerationStopped=!1,this.planAgentsMinimized=!1,this.wizardDragState=null,this.wizardDragListeners=null,this.wizardPosition=null,this.projectInsights=new Map,this.logViewerWindows=new Map,this.logViewerWindowZIndex=ZINDEX_LOG_VIEWER_BASE,this.projectInsightsPanelVisible=!1,this.orchestratorState=null,this.orchestratorPanelVisible=!1,this.currentSessionWorkingDir=null,this.imagePopups=new Map,this.imagePopupZIndex=ZINDEX_IMAGE_POPUP_BASE,this.attachmentCards=new Map,this.attachmentCardStack=null,this.attachmentHistoryCounts=new Map,this.attachmentHistoryItems=[],this.attachmentHistoryDrawerOpen=!1,this.fileBrowserData=null,this.fileBrowserExpandedDirs=new Set,this.fileBrowserFilter="",this.fileBrowserAllExpanded=!1,this.fileBrowserDragListeners=null,this.fileBrowserShowHidden=this._loadFileBrowserShowHidden?.()??!1,this.filePreviewContent="",this._toastContainer=null,this._tunnelUrl=null,this.tabAlerts=new Map,this.pendingHooks=new Map,this._closingSessions=new Set,this.approvals=new Map,this._ws=null,this._wsSessionId=null,this._wsReady=!1,this._wsState="disconnected",this._wsLastRecvAt=0,this._wsOutputGapSession=null,this.pendingWrites=[],this.writeFrameScheduled=!1,this._terminalWriteInFlight=!1,this._terminalWriteInFlightBytes=0,this._wasAtBottomBeforeWrite=!0,this.syncWaitTimeout=null,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._bufferLoadSeq=0,this._bufferLoadOwner=null,this._terminalRefreshOwner=null,this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.flickerFilterTimeout=null,this._debounceTimers=Object.create(null),this.systemStatsInterval=null,this.sseReconnectTimeout=null,this._sseListenerCleanup=null,this.reconnectAttempts=0,this.maxReconnectAttempts=10,this.isOnline=navigator.onLine,this._sseLastMessageAt=0,this._sseStaleTimeoutMs=window.CodemanSseStale?.TIMEOUT_MS??45e3,this._sseStaleWatchdog=null,this._sseConnectTimeout=null,this._sseConnectTimeoutMs=window.CodemanSseStale?.CONNECT_TIMEOUT_MS??15e3,this._connDownSince=null,this._nextSseRetryAt=null,this._offlineOverlayDismissed=!1,this._offlineRetryPending=!1,this._offlineUiTicker=null,this._lastOfflineUiKey="",this._connectionStatus="connected",this._clientId="",this._seqCounters=new Map,this._pendingDeliveries=new Map,this._lastIndicatorDescriptor=null,this._lastIndicatorLanguage=null,this._postDraining=new Set,this._extraInputSockets=new Map,this._persistReliableTimer=null,this._reliableAckTimeoutMs=4e3,this._reliableMaxBytes=256*1024,this._loadReliableState(),this._reliableSweepTimer=setInterval(()=>this._redeliverSweep(),2e3),window.addEventListener("pagehide",()=>this._persistReliableNow()),window.addEventListener("pagehide",()=>this._persistPendingTabLayoutEdits()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this._persistReliableNow():this._checkSseStale()}),this._localEchoOverlay=null,this._localEchoEnabled=!1,this._predictiveEcho=null,this._localEchoPolicy="off",this._restoringFlushedState=!1,this.activeFocusTrap=null,this.notificationManager=new NotificationManager(this),this.idleTimers=new Map,this._elemCache={},this.init()}$(e){return this._elemCache[e]||(this._elemCache[e]=document.getElementById(e)),this._elemCache[e]}_clearTimer(e){this[e]&&(clearTimeout(this[e]),this[e]=null)}_isStaleSelect(e){return e!==this._selectGeneration?(this._isLoadingBuffer&&this._finishBufferLoad(e),this._restoringFlushedState=!1,!0):!1}formatTokens(e){if(e>=1e6){const t=e/1e6;return t>=10?`${t.toFixed(1)}m`:`${t.toFixed(2)}m`}else if(e>=1e3){const t=e/1e3;return t>=100?`${t.toFixed(0)}k`:`${t.toFixed(1)}k`}return String(e)}estimateCost(e,t){const s=e/1e6*15,i=t/1e6*75;return s+i}setPendingHook(e,t){this.pendingHooks.has(e)||this.pendingHooks.set(e,new Set),this.pendingHooks.get(e).add(t),this.updateTabAlertFromHooks(e)}clearPendingHooks(e,t=null){const s=this.pendingHooks.get(e);s&&(t?s.delete(t):s.clear(),s.size===0&&this.pendingHooks.delete(e),this.updateTabAlertFromHooks(e))}markIdleAlertSeen(e){this.pendingHooks?.get(e)?.has("idle_prompt")&&(this.clearPendingHooks(e,"idle_prompt"),this.acknowledgeIdleApprovalOnView?.(e))}updateTabAlertFromHooks(e){const t=this.pendingHooks.get(e);!t||t.size===0?this.tabAlerts.delete(e):t.has("permission_prompt")||t.has("elicitation_dialog")?this.tabAlerts.set(e,"action"):t.has("idle_prompt")&&this.tabAlerts.set(e,"idle"),this.renderSessionTabs()}init(){MobileDetection.init(),this._initWindowChannel(),this.isSoloWindow&&document.body.classList.add("solo-mode"),this.isSoloWindow||window.addEventListener("hashchange",()=>{const s=this._takeUrlSession();s&&(this._retireUrlSession(),this._urlSessionId=s,this._selectUrlSession())}),document.documentElement.classList.toggle("host-windows",this.hasHostWindows()),KeyboardHandler.init(),SwipeHandler.init(),VoiceInput.init(),KeyboardAccessoryBar.init();const e=this.loadAppSettingsFromStorage();KeyboardAccessoryBar.setMode(e.extendedKeyboardBar?"extended":"simple"),this.applyHeaderVisibilitySettings(),this.restorePlanUsageChip(),this.applySkin(),this.applyLocalization(),this.applySessionListLayout(),this.applyTabOrientation(),this._wireMobileOverviewBreakpoint?.(),this._wireHomeSessionsBreakpoint?.(),this.initTabRailResize?.(),this.applyMonitorVisibility(),this.applyLineageLineSettings?.(),this._installLineageStripScrollListener?.(),this._setupTabMiddleClickClose(),this.initEntranceAnimations?.(),document.documentElement.classList.remove("mobile-init"),requestAnimationFrame(()=>{this.initTerminal(),this.loadFontSize(),this.connectSSE(),this._initFallbackTimer=setTimeout(()=>{this._initGeneration===0&&this.loadState()},3e3)}),this.registerServiceWorker(),this.loadTunnelStatus(),this.initRebootRestoreBanner?.();const t=fetch("/api/settings").then(s=>s.ok?s.json():null).then(s=>s?.data??null).catch(()=>null);if(this.loadQuickStartCases(null,t),this._initRunMode(),this.initWebviews?.(),this.setupEventListeners(),MobileDetection.isTouchDevice()){const s=i=>{i&&i.addEventListener("touchstart",n=>{if(!KeyboardHandler.keyboardVisible)return;const o=n.target.closest("button");o&&(n.preventDefault(),o.click(),typeof app<"u"&&app.terminal&&app.terminal.focus())},{passive:!1})};s(document.querySelector(".toolbar")),s(document.querySelector(".welcome-overlay"))}this.setupOnlineDetection(),this.loadAppSettingsFromServer(t).then(()=>{this.applyHeaderVisibilitySettings(),this.applySkin(),this.applyLocalization(),this.applySessionListLayout(),this.applyTabOrientation?.(),this.applyMonitorVisibility(),this.applyLineageLineSettings?.(),typeof this.syncAllUltracodeFloatingWindows=="function"&&this.syncAllUltracodeFloatingWindows()}),document.body.classList.add("app-loaded")}_initWebGL(){if(!(typeof WebglAddon>"u"))try{this._webglAddon=new WebglAddon.WebglAddon,this._webglAddon.onContextLoss(()=>{console.error("[CRASH-DIAG] WebGL context LOST \u2014 falling back to canvas renderer"),_crashDiag.log("WEBGL_LOST"),this._disableWebGLSticky("context-lost"),this._disposeWebGLObserver(),this._webglAddon?.dispose(),this._webglAddon=null,this._scheduleTerminalRepaint()}),this.terminal.loadAddon(this._webglAddon),console.log("[CRASH-DIAG] WebGL renderer enabled"),this._installWebGLLongTaskGuard()}catch{}}_installWebGLLongTaskGuard(){if(typeof PerformanceObserver>"u"||this._webglLongTaskObserver)return;const e=performance.now(),t=[];try{this._webglLongTaskObserver=new PerformanceObserver(s=>{if(!this._webglAddon||this._tilesOwnTerminal?.())return;const i=performance.now();i-e<WEBGL_FALLBACK.GRACE_MS||evaluateWebGLLongTaskTrip(t,s.getEntries(),i)&&(console.warn(`[CRASH-DIAG] WebGL long-task threshold (${t.length} stalls/${WEBGL_FALLBACK.WINDOW_MS}ms) \u2014 falling back to canvas renderer`),_crashDiag.log(`WEBGL_FALLBACK: ${t.length}`),this._disableWebGLSticky("long-tasks"),this._disposeWebGLObserver(),this._webglAddon?.dispose(),this._webglAddon=null,this._scheduleTerminalRepaint())}),this._webglLongTaskObserver.observe({type:"longtask",buffered:!1})}catch{}}_disposeWebGLObserver(){if(this._webglLongTaskObserver){try{this._webglLongTaskObserver.disconnect()}catch{}this._webglLongTaskObserver=null}}_scheduleTerminalRepaint(){if(this._terminalRepaintScheduled)return;this._terminalRepaintScheduled=!0,(typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,0))(()=>{this._terminalRepaintScheduled=!1;try{this.terminal?.refresh(0,this.terminal.rows-1)}catch{}})}_disableWebGLSticky(e){try{localStorage.setItem("codeman-webgl-disabled",JSON.stringify({reason:e,at:Date.now()}))}catch{}}setupEventListeners(){const e=this._shortcutActions();document.addEventListener("keydown",s=>{if(s.target?.closest?.("[data-raw-keys]")||s.isComposing||s.keyCode===229)return;if(this.shouldOpenCommandPaletteFromShortcut?.(s)){s.preventDefault(),this.openCommandPalette();return}if(s.key==="Escape"){if(this._tabGroupMenu&&this._tabGroupMenuKeydown){this._tabGroupMenuKeydown(s);return}if(this._tabLayoutDrag?.active&&this._tabLayoutDragKeydown){this._tabLayoutDragKeydown(s);return}if(this._tileCountMenu){this.closeTileCountMenu({refocus:!0});return}if(s.target?.id==="tabRailSearch"&&this._tabRailSearch){this.handleTabRailSearchKeydown(s);return}if(this.isLocalModelWindowOpen?.()){this.closeLocalModelWindow();return}this.closeAllPanels(),this.closeHelp(),this.attachmentHistoryDrawerOpen&&this.closeAttachmentHistory(),this.closeWorktreeModal?.(),this.closeSessionManager(),this.closeCommandPalette?.(),this.closeShortcutOverlay?.(),this._isSessionSidebarOverlay()&&this.isSessionSidebarActive()&&!this.isSessionSidebarCollapsed()&&(this.toggleSessionSidebar(),document.getElementById("sidebarToggleBtn")?.focus())}if(s.altKey&&!s.ctrlKey&&!s.shiftKey){const o=(s.code||"").match(/^Digit([1-9])$/);if(o){const a=parseInt(o[1],10)-1,r=this.sessionOrder.filter(l=>this.sessions.has(l));if(a<r.length)s.preventDefault(),this.selectSession(r[a]);else{const l=a-r.length,c=(this.webviewOrder||[])[l];c&&(s.preventDefault(),this.openWebview(c))}return}}const i=this.tileShortcutFor?.(s);if(i){s.preventDefault(),this.runTileShortcut(i);return}if(!(!s.ctrlKey&&!s.metaKey&&!s.altKey))for(const n of this.getShortcutRegistry()){if(n.disabled||!n.action)continue;const o=e[n.action];if(o&&this.matchesShortcutEvent(s,n)){s.preventDefault(),o();return}}},!0);const t=this.$("headerTokens");t&&!t._statsHandlerAttached&&(t.classList.add("clickable"),t._statsHandlerAttached=!0,t.addEventListener("click",()=>this.openTokenStats())),this.setupColorPicker()}_sseFilterSessionId(e){return this._tilesOwnTerminal?.()&&window.CodemanTileGrid?.TILE_GRID_SSE_FILTER||e}_updateSseSubscription(e){try{const t=this._sseFilterSessionId(e),s=JSON.stringify({clientId:this._clientId,sessions:t?[t]:null});fetch("/api/events/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:s,keepalive:!0}).catch(()=>{})}catch{}}_detectSoloSessionId(){try{if(typeof window<"u"&&typeof window.__CODEMAN_SOLO__=="string"&&window.__CODEMAN_SOLO__)return window.__CODEMAN_SOLO__;const e=window.CodemanBase?.base||"";let t=location.pathname;e&&t.startsWith(e)&&(t=t.slice(e.length)||"/");const s=t.match(/^\/session\/([^/]+)\/?$/);return s?decodeURIComponent(s[1]):null}catch{return null}}_takeUrlSession(){const e=window.CodemanUrlSession?.sessionIdFromFragment(location.hash)??null;if(e)try{history.replaceState(history.state,"",location.pathname+location.search)}catch{}return e}_selectUrlSession(){const e=this._urlSessionId;return e?this.sessions.has(e)?(this._retireUrlSession(),this.selectSession(e,{auto:!0,leaveTiles:!0}),!0):(this._armUrlSessionWait(e),!1):!1}_armUrlSessionWait(e){this._urlSessionWaitTimer||(this._urlSessionWaitTimer=setTimeout(()=>{if(this._urlSessionWaitTimer=null,this._urlSessionId===e){if(this.sessions.has(e)){this._selectUrlSession();return}this._retireUrlSession(),this.showToast?.("Session not found","warning")}},URL_SESSION_WAIT_MS))}_retireUrlSession(){this._urlSessionId=null,this._urlSessionWaitTimer&&(clearTimeout(this._urlSessionWaitTimer),this._urlSessionWaitTimer=null)}detachSession(e,t=null){if(this.isSoloWindow||!this.sessions.has(e)||this.detachedSessions.has(e)&&this._raiseDetached(e))return;const s=this.hasHostWindows()&&!this.windowChannel?!1:this.openInHostWindow(CodemanBase.url("/session/"+encodeURIComponent(e)));if(s!==null){if(!s){this.showToast?.("Could not open a new window for this session","error");return}this._markDetached(e,!0),this._postWindowMessage({type:"detached",id:e});return}const i=this._detachWindowFeatures(t);let n=null;try{n=window.open(CodemanBase.url("/session/"+encodeURIComponent(e)),"codeman-session-"+e,i)}catch{}if(!n){this.showToast?.("Pop-out blocked \u2014 allow popups for this site to detach a session","error");return}this.detachedWindows.set(e,n),this._markDetached(e,!0),this._watchDetachedWindow(e,n),this._postWindowMessage({type:"detached",id:e});try{n.focus()}catch{}}_detachWindowFeatures(e){const t=r=>Number.isFinite(r)?Math.round(r):null,s=t(e?.width)??960,i=t(e?.height)??680,n=t(e?.left),o=t(e?.top),a=n!==null&&o!==null?`,left=${n},top=${o}`:"";return`width=${s},height=${i}${a},menubar=no,toolbar=no,location=no,status=no`}hasHostWindows(){try{return typeof window<"u"&&typeof window.CodemanHost?.openWindow=="function"}catch{return!1}}tabDetachButtonEnabled(e,t={}){return e?.showTabDetachButton??(this.hasHostWindows()||(t?.showTabDetachButton??!1))}openInHostWindow(e){if(!this.hasHostWindows())return null;try{return window.CodemanHost.openWindow(new URL(e,location.href).href)!==!1}catch{return!1}}_raiseDetached(e){const t=this.detachedWindows.get(e);if(t&&!t.closed){try{t.focus()}catch{}return!0}return t&&t.closed?(this._redock(e),!1):(this._postWindowMessage({type:"focus-request",id:e}),!0)}redockSession(e){const t=this.detachedWindows.get(e);if(t&&!t.closed)try{t.close()}catch{}this._postWindowMessage({type:"close-request",id:e}),this._redock(e)}_redock(e){const t=this._detachWatchTimers.get(e);t&&(clearInterval(t),this._detachWatchTimers.delete(e)),this._cancelPendingRedock(e),this._detachOrphanStrikes.delete(e),this.detachedWindows.delete(e),this._markDetached(e,!1),this._lastResizeDims=null,this.sessions.has(e)&&e===this.activeSessionId&&this.sendResize(e,{force:!0})?.catch?.(()=>{})}_scheduleRedock(e){if(this._redockGrace.has(e))return;const t=setTimeout(()=>{this._redockGrace.delete(e),this._redock(e)},1500);this._redockGrace.set(e,t)}_cancelPendingRedock(e){const t=this._redockGrace.get(e);t&&(clearTimeout(t),this._redockGrace.delete(e))}_markDetached(e,t){t?this.detachedSessions.add(e):this.detachedSessions.delete(e),t&&this._tileGrid?.has(e)&&this.removeTile(e,{gone:!0});const s=this.$("sessionTabs"),i=s&&s.querySelector(`.session-tab[data-id="${e}"]`);i&&i.classList.toggle("detached",t)}_watchDetachedWindow(e,t){const s=this._detachWatchTimers.get(e);s&&clearInterval(s);const i=setInterval(()=>{(!t||t.closed)&&(clearInterval(i),this._detachWatchTimers.delete(e),this._redock(e))},800);this._detachWatchTimers.set(e,i)}_initWindowChannel(){if(!(typeof BroadcastChannel>"u")){try{this.windowChannel=new BroadcastChannel("codeman-windows")}catch{this.windowChannel=null;return}if(this.windowChannel.onmessage=e=>this._onWindowMessage(e.data),this.isSoloWindow){this._postWindowMessage({type:"detached",id:this.soloSessionId});const e=()=>this._postWindowMessage({type:"redocked",id:this.soloSessionId});window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}else this._postWindowMessage({type:"roll-call"}),this._startDetachLiveness()}}_postWindowMessage(e){try{this.windowChannel&&this.windowChannel.postMessage(e)}catch{}}_onWindowMessage(e){if(!(!e||typeof e!="object")){if(this.isSoloWindow){if(e.type==="roll-call"){this._soloReleased||this._postWindowMessage({type:"detached",id:this.soloSessionId});return}if(e.id!==this.soloSessionId)return;if(e.type==="close-request")this._releaseSoloWindow();else if(e.type==="focus-request")try{typeof window.CodemanHost?.focusWindow=="function"?window.CodemanHost.focusWindow():window.focus()}catch{}return}if(e.type==="detached"&&e.id){if(this._tileDockedRecently?.(e.id))return;this._cancelPendingRedock(e.id),this._detachPingPending?.delete(e.id),this._detachOrphanStrikes.delete(e.id),this._markDetached(e.id,!0)}else e.type==="redocked"&&e.id?this._scheduleRedock(e.id):e.type==="detach-request"&&e.id?this.detachSession(e.id):e.type==="tile-adopted"&&e.id&&e.by!==this._wsTabNonce&&this._onTileAdoptedElsewhere?.(e.id)}}_startDetachLiveness(){this._detachLivenessTimer||(this._detachLivenessTimer=setInterval(()=>this._pingDetached(),5e3))}_pingDetached(){const e=[];for(const t of this.detachedSessions){const s=this.detachedWindows.get(t);s?s.closed&&this._redock(t):e.push(t)}e.length&&(this._detachPingPending=new Set(e),this._postWindowMessage({type:"roll-call"}),setTimeout(()=>{if(this._detachPingPending){for(const t of this._detachPingPending){const s=(this._detachOrphanStrikes.get(t)||0)+1;s>=2?(this._detachOrphanStrikes.delete(t),this._redock(t)):this._detachOrphanStrikes.set(t,s)}this._detachPingPending=null}},1200))}_closeSoloWindow(){try{typeof window.CodemanHost?.closeWindow=="function"?window.CodemanHost.closeWindow():window.close()}catch{}}_releaseSoloWindow(){this._soloReleased||(this._soloReleased=!0,this._postWindowMessage({type:"redocked",id:this.soloSessionId}),this._closeSoloWindow(),setTimeout(()=>{window.closed||this._showSoloReleased()},300))}_showSoloReleased(){if(document.querySelector(".solo-gone-overlay"))return;const e=document.createElement("div");e.className="solo-gone-overlay";const t=document.createElement("h2");t.textContent="Session moved";const s=document.createElement("p");s.textContent="This session is back in a Codeman window. This one can be closed.";const i=document.createElement("button");i.className="btn-primary",i.textContent="Close window",i.addEventListener("click",()=>this._closeSoloWindow()),e.append(t,s,i),document.body.appendChild(e)}_applySoloMode(){document.body.classList.add("solo-mode");const e=this.sessions.get(this.soloSessionId);if(!e){this._showSoloSessionGone();return}this.activeSessionId=null,this.selectSession(this.soloSessionId,{auto:!0});const t=this.getSessionName(e)||"Session",s=document.getElementById("soloSessionTitle");s&&(s.textContent=t,s.style.display="");const i=document.getElementById("soloRedockBtn");i&&(i.style.display=""),this._installSoloTileHandle?.(),document.title=t+" \u2014 "+(window.CodemanI18n?.displayName||"Codeman"),this.notificationManager&&(this.notificationManager.originalTitle=document.title);const n=document.querySelector(".header-brand .logo");n&&(n.onclick=o=>{o.preventDefault()})}_showSoloSessionGone(){if(document.body.classList.add("solo-mode"),document.querySelector(".solo-gone-overlay"))return;const e=document.createElement("div");e.className="solo-gone-overlay",e.innerHTML='<h2>Session unavailable</h2><p>This session has ended or is no longer available.</p><button class="btn-primary" onclick="app._closeSoloWindow()">Close window</button>',document.body.appendChild(e),document.title=(window.codemanT?.("Session ended")||"Session ended")+" \u2014 "+(window.CodemanI18n?.displayName||"Codeman")}connectSSE(){if(this._clearTimer("_sseConnectTimeout"),!navigator.onLine){this.setConnectionStatus("offline");return}this._clearTimer("sseReconnectTimeout"),this._sseStaleWatchdog&&(clearInterval(this._sseStaleWatchdog),this._sseStaleWatchdog=null),this._sseListenerCleanup&&(this._sseListenerCleanup(),this._sseListenerCleanup=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.reconnectAttempts===0?this.setConnectionStatus("connecting"):this.setConnectionStatus("reconnecting");const e=new URLSearchParams({clientId:this._clientId}),t=this._sseFilterSessionId(this.activeSessionId);t&&e.set("sessions",t);const s=new EventSource(CodemanBase.url(`/api/events?${e.toString()}`));this.eventSource=s;const i=setTimeout(()=>{this._sseConnectTimeout===i&&(this._sseConnectTimeout=null,!(this.eventSource!==s||s.readyState===EventSource.OPEN)&&(console.warn(`[SSE] connection did not open within ${this._sseConnectTimeoutMs}ms, retrying`),this._handleSseConnectionFailure(s)))},this._sseConnectTimeoutMs);this._sseConnectTimeout=i;const n=[],o=(a,r)=>{const l=c=>{this._sseLastMessageAt=Date.now(),r(c)};this.eventSource.addEventListener(a,l),n.push({event:a,handler:l})};if(this._sseListenerCleanup=()=>{for(const{event:a,handler:r}of n)this.eventSource&&this.eventSource.removeEventListener(a,r);n.length=0},this.eventSource.onopen=()=>{this._clearTimer("_sseConnectTimeout"),this.reconnectAttempts=0,this._sseLastMessageAt=Date.now(),this.setConnectionStatus("connected")},this.eventSource.onerror=()=>this._handleSseConnectionFailure(s),!this._sseHandlerWrappers){this._sseHandlerWrappers=new Map;for(const[a,r]of _SSE_HANDLER_MAP){const l=this[r],c=r==="_onSSETerminal"||r==="_onSSENeedsRefresh"||r==="_onSSEClearTerminal";this._sseHandlerWrappers.set(a,h=>{if(!(c&&this._wsReady))try{l.call(this,h.data?JSON.parse(h.data):{})}catch(d){console.error(`[SSE] Error handling ${a}:`,d)}})}}for(const[a]of _SSE_HANDLER_MAP)o(a,this._sseHandlerWrappers.get(a));for(const a of[SSE_EVENTS.SESSION_CREATED,SSE_EVENTS.SESSION_DELETED])o(a,()=>this._onSessionListMaybeChanged());o(SSE_EVENTS.DOCKER_EXPORT_COMPLETE,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Docker export ready: ${r.bundle} (${Math.round((r.sizeBytes||0)/1e6)} MB)`,"success"),this.refreshDockerExports?.()}catch(r){console.error("[SSE] docker export complete:",r)}}),o(SSE_EVENTS.DOCKER_EXPORT_FAILED,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Docker export failed: ${r.error||"unknown error"}`,"error")}catch(r){console.error("[SSE] docker export failed:",r)}}),o(SSE_EVENTS.DOCKER_IMPORT_COMPLETE,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Docker bundle imported as case "${r.name}"`,"success"),this.loadQuickStartCases?.(),this.refreshDockerExports?.()}catch(r){console.error("[SSE] docker import complete:",r)}}),o(SSE_EVENTS.DOCKER_CONTAINER_RECREATED,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Container for "${r.name}" removed \u2014 next launch recreates it with the new config`,"info")}catch(r){console.error("[SSE] docker container recreated:",r)}}),o(SSE_EVENTS.CUSTOM_MODEL_SWAPPED_OUT,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`${r.sessionName||r.sessionId}'s model (${r.previousModel}) was swapped out on llama-swap by another session \u2014 currently loaded: ${r.currentlyLoadedModel}. Sending a message there will reload it.`,"warning",{duration:0})}catch(r){console.error("[SSE] custom model swapped out:",r)}}),o(SSE_EVENTS.ADMIN_USERS_CHANGED,()=>{window.codemanAdmin?.onUsersChanged?.()}),o(SSE_EVENTS.DOCKER_IMAGE_BUILD_STARTED,()=>{this.showToast("Building the Codeman agent image (first Docker case, a few minutes)...","info",{duration:8e3})}),o(SSE_EVENTS.DOCKER_IMAGE_BUILD_COMPLETE,a=>{try{const r=a.data?JSON.parse(a.data):{};r.error?this.showToast(`Agent image build failed: ${r.error}`,"error"):this.showToast("Agent image ready. Starting the container...","success")}catch(r){console.error("[SSE] docker image build complete:",r)}}),o(SSE_EVENTS.DOCKER_IMAGE_BUILD_FAILED,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Agent image build failed: ${r.error||"unknown error"}`,"error")}catch(r){console.error("[SSE] docker image build failed:",r)}}),o(SSE_EVENTS.SESSION_PINNED,a=>{let r=null;try{r=JSON.parse(a.data)}catch{}if(r&&r.id){const l=this.sessions.get(r.id);l&&(l.pinned=r.pinned===!0,l.pinnedAt=r.pinned?r.pinnedAt:void 0)}this._onSessionListMaybeChanged()}),o(SSE_EVENTS.HEARTBEAT,()=>{}),this._sseStaleWatchdog=setInterval(()=>this._checkSseStale(),5e3)}_handleSseConnectionFailure(e){if(this.eventSource!==e)return;this._clearTimer("_sseConnectTimeout"),this.reconnectAttempts++,this.reconnectAttempts>=this.maxReconnectAttempts?this.setConnectionStatus("disconnected"):this.setConnectionStatus("reconnecting"),this.eventSource=null,e.close(),this._clearTimer("sseReconnectTimeout");const t=this.reconnectAttempts<=1?200:Math.min(500*Math.pow(2,this.reconnectAttempts-2),3e4);this._nextSseRetryAt=Date.now()+t,this._updateConnectionLossUi(),this.sseReconnectTimeout=setTimeout(()=>this.connectSSE(),t)}_checkSseStale(){const e=window.CodemanSseStale;if(!e)return;const t=Date.now();e.compute({lastMessageAt:this._sseLastMessageAt,now:t,status:this._connectionStatus,isOnline:this.isOnline,timeoutMs:this._sseStaleTimeoutMs})&&(console.log(`[SSE] stream stale: no frame for ${t-this._sseLastMessageAt}ms (threshold ${this._sseStaleTimeoutMs}ms), forcing reconnect`),this.connectSSE())}_onInit(e){_crashDiag.log(`INIT: ${e.sessions?.length||0} sessions`),this.handleInit(e),this._ensureHostWakePoller?.()}_onSessionCreated(e){this._closingSessions?.has(e.id)||(this.sessions.set(e.id,e),this.sessionOrder.includes(e.id)||this.syncSessionOrder(),this.markSessionTabEntering?.(e.id),this.markTerminalEntering?.(e.id),e.parentSessionId&&this.markConnectionLineEntering?.("lineage:"+e.id),this.renderSessionTabs(),this.updateCost(),this._urlSessionId===e.id&&this._selectUrlSession())}_onSessionUpdated(e){const t=e.session||e;if(this._closingSessions?.has(t.id))return;const s=this.sessions.get(t.id),i=t.claudeSessionId&&(!s||!s.claudeSessionId);this.sessions.set(t.id,t),this.renderSessionTabs(),this.updateCost(),t.id===this.activeSessionId&&t.tokens&&this.updateRespawnTokens(t.tokens),t.id===this.activeSessionId&&this._reconcileKeyboardHold?.(),t.id===this.activeSessionId&&this._followFileBrowserWorktree?.(t),this.updateSubagentParentNames(t.id),this.editingSessionId===t.id&&this.updateGitFetchStatus(t.id),i&&(this.recheckOrphanSubagents(),requestAnimationFrame(()=>{this.updateConnectionLines()}))}_onSessionDeleted(e){if(this._wsSessionId===e.id&&this._disconnectWs(),this.isSoloWindow&&e.id===this.soloSessionId&&this._showSoloSessionGone(),this.detachedSessions.has(e.id)&&this._redock(e.id),this._cleanupSessionData(e.id),this.activeSessionId===e.id&&!this._closingSessions.has(e.id)){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome()}this.renderSessionTabs(),this.renderRalphStatePanel(),this.renderProjectInsightsPanel()}_onSSETerminal(e){this._wsReady||this._onSessionTerminal(e)}_onSSENeedsRefresh(e){this._wsReady||this._onSessionNeedsRefresh(e)}_onSSEClearTerminal(e){this._wsReady||this._onSessionClearTerminal(e)}_bufferLoadFinishOpts(e,t){return{flushQueued:e?.source==="mux-visible"||e?.source==="mux-full-history",since:t}}_onSessionTerminal(e){if(!this._tilesOwnTerminal?.()&&e.id===this.activeSessionId){e.data.length>32768&&_crashDiag.log(`TERMINAL: ${(e.data.length/1024).toFixed(0)}KB`);const t=(this.pendingWrites?.reduce((s,i)=>s+i.length,0)||0)+(this.flickerFilterBuffer?.length||0)+(this._loadBufferQueue?.reduce((s,i)=>s+i.data.length,0)||0)+(this._terminalWriteInFlightBytes||0);if(t+e.data.length>131072){this._scheduleDroppedOutputRecovery(e.id,0,t);return}this.batchTerminalWrite(e.data)}}_scheduleDroppedOutputRecovery(e,t=0,s){!e||this._clientDropRecoveryTimer||this._tilesOwnTerminal?.()||(Number.isFinite(s)&&_crashDiag.log(`TERMINAL DROP: ${(s/1024).toFixed(0)}KB queued`),this._clientDropRecoveryTimer=setTimeout(async()=>{this._clientDropRecoveryTimer=null;let i=!1,n=!1;try{const a=await this._onSessionNeedsRefresh({id:e});i=a===!0,n=a==="deadline"}catch{}window.CodemanDroppedOutput.shouldRetryDroppedOutputRecovery({repainted:i,timedOut:n,attempt:t,stillActive:this.activeSessionId===e})&&(_crashDiag.log(`DROP RECOVERY: attempt ${t+1} did not repaint, retrying`),this._scheduleDroppedOutputRecovery(e,t+1))},window.CodemanDroppedOutput.DROP_RECOVERY_DELAY_MS))}_sanitizeHtml(e){return typeof window<"u"&&typeof window.sanitizeMarkdownHtml=="function"?window.sanitizeMarkdownHtml(e):String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}_cleanTerminalBuffer(e){const t=e.replace(/\x1b\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[PX^_][^\x1b]*\x1b\\/g,"").replace(/\x1b[NO()][A-Z0-9]?/g,"").replace(/\x1b[>=<78cDEHM]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").replace(/\r\n/g,`
|
|
8
8
|
`).replace(/\r/g,`
|
|
9
9
|
`),s=[/^\s*❯\s*/,/^\s*[⏵⏺⏸⏹]+\s*/,/^\s*✻\s*(Crunching|Crunched|Thinking)/i,/bypass permissions/i,/\bshift\+tab to cycle\b/i,/^\s*focus\s*$/,/^\s*new task\?/i,/\/clear to save/i,/^\s*─{5,}\s*$/,/\[(Opus|Sonnet|Haiku|GPT|Claude)[\s\S]*(tokens?|\$|¥|%|↑|↓)/i,/^\s*\[\d+[km]?\/\d+[km]?\]/i,/[█░▓▒]{3,}/,/^\s*\(.*\s*(tokens?|context).*\)\s*$/i];return t.split(`
|
|
10
10
|
`).filter(o=>o.trim()?!s.some(r=>r.test(o)):!0).join(`
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -126,20 +126,31 @@ Object.assign(CodemanApp.prototype, {
|
|
|
126
126
|
this._stopHomeSessionsClock();
|
|
127
127
|
},
|
|
128
128
|
|
|
129
|
-
/**
|
|
129
|
+
/**
|
|
130
|
+
* Re-render only when showing (called from the tab renderer's tail). Asked
|
|
131
|
+
* again when the debounce fires: `renderHomeSessions()` unhides the column,
|
|
132
|
+
* so a render queued just before a fold to phone width hid it (#702) would
|
|
133
|
+
* otherwise bring it back behind the phone overview.
|
|
134
|
+
*/
|
|
130
135
|
_refreshHomeSessionsIfVisible() {
|
|
131
136
|
if (!this.isHomeSessionsVisible()) return;
|
|
132
|
-
this._debouncedCall(
|
|
137
|
+
this._debouncedCall(
|
|
138
|
+
'homeSessions',
|
|
139
|
+
() => {
|
|
140
|
+
if (this.isHomeSessionsVisible() && this.shouldShowHomeSessions()) this.renderHomeSessions();
|
|
141
|
+
},
|
|
142
|
+
150
|
|
143
|
+
);
|
|
133
144
|
},
|
|
134
145
|
|
|
135
146
|
/**
|
|
136
|
-
* One delegated click listener for every row
|
|
137
|
-
*
|
|
138
|
-
* instead of leaving it overlapping the content it was sized to clear.
|
|
147
|
+
* One delegated click listener for every row. The width listener lives in
|
|
148
|
+
* `_wireHomeSessionsBreakpoint()`, installed at startup.
|
|
139
149
|
*/
|
|
140
150
|
_wireHomeSessions(el) {
|
|
141
151
|
if (this._homeSessionsWired) return;
|
|
142
152
|
this._homeSessionsWired = true;
|
|
153
|
+
this._wireHomeSessionsBreakpoint();
|
|
143
154
|
|
|
144
155
|
el.addEventListener('click', (event) => {
|
|
145
156
|
const target = event.target?.closest?.('[data-hs-action]');
|
|
@@ -150,20 +161,29 @@ Object.assign(CodemanApp.prototype, {
|
|
|
150
161
|
void this.openWebview?.(target.dataset.hsWebview);
|
|
151
162
|
}
|
|
152
163
|
});
|
|
164
|
+
},
|
|
153
165
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
166
|
+
/**
|
|
167
|
+
* Add or drop the column when the window crosses its width gate, so it never
|
|
168
|
+
* overlaps the content it was sized to clear. Installed ONCE at startup
|
|
169
|
+
* (`init()` in app.js) like the phone overview's breakpoint listener, so a
|
|
170
|
+
* page that loads on a phone and is unfolded to desktop width gets it too
|
|
171
|
+
* (#702). Idempotent.
|
|
172
|
+
*/
|
|
173
|
+
_wireHomeSessionsBreakpoint() {
|
|
174
|
+
if (this._homeSessionsBreakpointWired || !window.matchMedia) return;
|
|
175
|
+
this._homeSessionsBreakpointWired = true;
|
|
176
|
+
const mq = window.matchMedia(`(min-width: ${HOME_SESSIONS_MIN_WIDTH}px)`);
|
|
177
|
+
const onChange = () => {
|
|
178
|
+
// Only relevant while the welcome screen is up; entering a session
|
|
179
|
+
// re-decides through hideWelcome()/showWelcome() anyway.
|
|
180
|
+
if (this.activeSessionId) return;
|
|
181
|
+
const overlay = document.getElementById('welcomeOverlay');
|
|
182
|
+
if (!overlay || !overlay.classList.contains('visible')) return;
|
|
183
|
+
this.showHomeSessions();
|
|
184
|
+
};
|
|
185
|
+
if (mq.addEventListener) mq.addEventListener('change', onChange);
|
|
186
|
+
else if (mq.addListener) mq.addListener(onChange);
|
|
167
187
|
},
|
|
168
188
|
|
|
169
189
|
// ═══════════════════════════════════════════════════════════════
|
|
Binary file
|
|
Binary file
|
|
Binary file
|