mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-04 14:39:42 +02:00
Merge remote-tracking branch 'origin/master' into worktree-grok-mode
# Conflicts: # src/web/public/app.js
This commit is contained in:
@@ -14,3 +14,4 @@ export type { InfraPort, ScheduledRun } from './infra-port.js';
|
||||
export type { AuthPort } from './auth-port.js';
|
||||
export type { OrchestratorPort } from './orchestrator-port.js';
|
||||
export type { CronPort } from './cron-port.js';
|
||||
export type { TabLayoutPort } from './tab-layout-port.js';
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { Session } from '../../session.js';
|
||||
|
||||
export interface SessionPort {
|
||||
readonly sessions: ReadonlyMap<string, Session>;
|
||||
addSession(session: Session): void;
|
||||
addSession(session: Session): Promise<void>;
|
||||
cleanupSession(sessionId: string, killMux?: boolean, reason?: string): Promise<void>;
|
||||
setupSessionListeners(session: Session): Promise<void>;
|
||||
persistSessionState(session: Session): void;
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
/** @fileoverview Owner-scoped tab-layout capabilities exposed to route modules. */
|
||||
import type { TabLayoutService } from '../../tab-layout-service.js';
|
||||
|
||||
export type { LegacyOrderActor, LegacyOrderPutResult, SessionOrderProjectionChange } from '../../tab-layout-service.js';
|
||||
|
||||
export interface TabLayoutPort {
|
||||
readonly tabLayouts: TabLayoutService;
|
||||
}
|
||||
+68
-10
@@ -919,6 +919,8 @@ class CodemanApp {
|
||||
// Calls applyTabWrapSettings() itself (it owns tabs-two-rows / tabs-show-folder)
|
||||
// and then applies the sidebar variant on top — do not call both.
|
||||
this.applySessionListLayout();
|
||||
this.applyTabOrientation();
|
||||
this.initTabRailResize?.();
|
||||
this.applyMonitorVisibility();
|
||||
this.applyLineageLineSettings?.();
|
||||
this._installLineageStripScrollListener?.();
|
||||
@@ -3758,6 +3760,18 @@ class CodemanApp {
|
||||
return layout === 'sidebar' || layout === 'sidebar-rich' ? layout : 'header';
|
||||
}
|
||||
|
||||
resolveSessionSidebarFontSize(value) {
|
||||
const size = Number(value);
|
||||
return Number.isInteger(size) && size >= 11 && size <= 18 ? size : 14;
|
||||
}
|
||||
|
||||
applySessionSidebarFontSize(settings = null) {
|
||||
const resolvedSettings = settings ?? this.loadAppSettingsFromStorage();
|
||||
const size = this.resolveSessionSidebarFontSize(resolvedSettings?.sessionSidebarFontSize);
|
||||
document.documentElement.style.setProperty('--session-sidebar-name-font-size', `${size}px`);
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the APPLIED layout off <html>, not the settings blob: this is called
|
||||
* per dragover event and per tab in render loops, and getSessionListLayout()
|
||||
@@ -3769,6 +3783,15 @@ class CodemanApp {
|
||||
return document.documentElement.dataset.sessionList === 'sidebar';
|
||||
}
|
||||
|
||||
_tabOrientation() {
|
||||
return document.documentElement.getAttribute('data-tab-orientation') === 'vertical' ? 'vertical' : 'horizontal';
|
||||
}
|
||||
|
||||
shouldInlineSessionActions() {
|
||||
if (this.isSessionSidebarActive()) return !this.isSessionSidebarCollapsed();
|
||||
return this._tabOrientation() === 'vertical' && !document.documentElement.classList.contains('tab-rail-compact');
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the sidebar is showing the DETAILED rows: the home screen's
|
||||
* per-session line ("created 3d ago · working 12m") plus a status pill.
|
||||
@@ -3861,17 +3884,22 @@ class CodemanApp {
|
||||
*/
|
||||
applySessionListLayout() {
|
||||
const mode = this.getSessionListLayout();
|
||||
this.applySessionSidebarFontSize();
|
||||
// 'sidebar' and 'sidebar-rich' are the same column; only row detail differs.
|
||||
const sidebar = mode === 'sidebar' || mode === 'sidebar-rich';
|
||||
const collapsed = this.isSessionSidebarCollapsed();
|
||||
const prevMode = document.documentElement.dataset.sessionList;
|
||||
const prevDetail = document.documentElement.dataset.sidebarDetail;
|
||||
const prevCollapsed = document.documentElement.dataset.sidebar;
|
||||
const tabsEl = document.getElementById('sessionTabs');
|
||||
const headerHost = document.getElementById('sessionTabsHost');
|
||||
const sidebarList = document.getElementById('sessionSidebarList');
|
||||
if (!tabsEl || !headerHost || !sidebarList) return;
|
||||
|
||||
const host = sidebar ? sidebarList : headerHost;
|
||||
const rail = document.getElementById('tabRail');
|
||||
const railOwnsTabs =
|
||||
!sidebar && document.documentElement.getAttribute('data-tab-orientation') === 'vertical';
|
||||
const host = sidebar ? sidebarList : railOwnsTabs && rail ? rail : headerHost;
|
||||
if (tabsEl.parentElement !== host) host.appendChild(tabsEl);
|
||||
|
||||
document.documentElement.dataset.sessionList = sidebar ? 'sidebar' : 'header';
|
||||
@@ -3880,7 +3908,7 @@ class CodemanApp {
|
||||
// would let the sidebar CSS style a strip that has nothing to style.
|
||||
document.documentElement.dataset.sidebarDetail = mode === 'sidebar-rich' ? 'rich' : 'simple';
|
||||
document.documentElement.dataset.sidebar = collapsed ? 'collapsed' : 'expanded';
|
||||
tabsEl.setAttribute('aria-orientation', sidebar ? 'vertical' : 'horizontal');
|
||||
tabsEl.setAttribute('aria-orientation', host === headerHost ? 'horizontal' : 'vertical');
|
||||
|
||||
const btn = document.getElementById('sidebarToggleBtn');
|
||||
if (btn) {
|
||||
@@ -3933,7 +3961,8 @@ class CodemanApp {
|
||||
const layoutChanged =
|
||||
prevMode !== document.documentElement.dataset.sessionList ||
|
||||
prevDetail !== document.documentElement.dataset.sidebarDetail;
|
||||
if (layoutChanged && prevTall === this._tallTabsEnabled) {
|
||||
const collapseChanged = prevCollapsed !== document.documentElement.dataset.sidebar;
|
||||
if ((layoutChanged || collapseChanged) && prevTall === this._tallTabsEnabled) {
|
||||
this._fullRenderSessionTabs();
|
||||
}
|
||||
// tabs-auto-wrap is measured, not derived from settings — updateTabOverflowMode()
|
||||
@@ -4476,9 +4505,17 @@ class CodemanApp {
|
||||
const nameEl = tab.querySelector('.tab-name');
|
||||
if (nameEl) {
|
||||
const _p = parseSessionPrefix(name);
|
||||
const _label = _p && _p.suffix ? _p.suffix : name;
|
||||
if (nameEl.textContent !== _label) {
|
||||
nameEl.textContent = _label;
|
||||
if (nameEl.dataset.fullName !== name) {
|
||||
nameEl.replaceChildren();
|
||||
if (_p && _p.suffix) {
|
||||
const prefix = document.createElement('span');
|
||||
prefix.className = 'tab-name-prefix';
|
||||
prefix.textContent = `${_p.prefix}: `;
|
||||
nameEl.append(prefix, document.createTextNode(_p.suffix));
|
||||
} else {
|
||||
nameEl.textContent = name;
|
||||
}
|
||||
nameEl.dataset.fullName = name;
|
||||
tab.title = _p && _p.suffix
|
||||
? (session.workingDir ? `${_p.prefix} (${session.workingDir})` : _p.prefix)
|
||||
: (session.workingDir || '');
|
||||
@@ -4529,9 +4566,11 @@ class CodemanApp {
|
||||
// Need to add badge - insert before the action-icon overlay so the
|
||||
// badge stays a direct child of the tab (outside .tab-actions)
|
||||
const badgeHtml = this.renderSubagentTabBadge(id, minimizedAgents);
|
||||
const actionsEl = tab.querySelector('.tab-actions');
|
||||
const actionsEl = tab.querySelector(':scope > .tab-actions');
|
||||
if (actionsEl) {
|
||||
actionsEl.insertAdjacentHTML('beforebegin', badgeHtml);
|
||||
} else {
|
||||
tab.insertAdjacentHTML('beforeend', badgeHtml);
|
||||
}
|
||||
} else if (minimizedCount === 0 && subagentBadgeEl) {
|
||||
// Count went to 0 - remove badge
|
||||
@@ -4589,6 +4628,17 @@ class CodemanApp {
|
||||
const defaults = this.getDefaultSettings();
|
||||
const manualTwoRows = deviceType === 'desktop' ? (settings.tabTwoRows ?? defaults.tabTwoRows ?? false) : false;
|
||||
|
||||
const orientation = window.CodemanTabOverflow?.resolveTabOrientation
|
||||
? window.CodemanTabOverflow.resolveTabOrientation({
|
||||
deviceType,
|
||||
setting: settings.tabOrientation ?? defaults.tabOrientation ?? 'horizontal',
|
||||
})
|
||||
: 'horizontal';
|
||||
if (orientation === 'vertical') {
|
||||
container.classList.remove('tabs-auto-wrap');
|
||||
return;
|
||||
}
|
||||
|
||||
if (manualTwoRows || deviceType !== 'desktop') {
|
||||
container.classList.remove('tabs-auto-wrap');
|
||||
return;
|
||||
@@ -4629,6 +4679,7 @@ class CodemanApp {
|
||||
}
|
||||
|
||||
_fullRenderSessionTabs() {
|
||||
this.closeTabRailActionMenu?.();
|
||||
if (this._inlineRenameActive) return;
|
||||
const container = this.$('sessionTabs');
|
||||
|
||||
@@ -4706,7 +4757,9 @@ class CodemanApp {
|
||||
// JUST the description on the tab; the generated w<n>-<case> id moves to the
|
||||
// tooltip and stays visible in the session settings modal.
|
||||
const parsedName = parseSessionPrefix(name);
|
||||
const tabLabel = parsedName && parsedName.suffix ? parsedName.suffix : name;
|
||||
const tabLabel = parsedName && parsedName.suffix
|
||||
? `<span class="tab-name-prefix">${escapeHtml(parsedName.prefix)}: </span>${escapeHtml(parsedName.suffix)}`
|
||||
: escapeHtml(name);
|
||||
const tabTooltip = parsedName && parsedName.suffix
|
||||
? (session.workingDir ? `${parsedName.prefix} (${session.workingDir})` : parsedName.prefix)
|
||||
: (session.workingDir || '');
|
||||
@@ -4721,6 +4774,9 @@ class CodemanApp {
|
||||
? ` data-tab-state="${richRow.state}" data-tab-meta-sig="${richRow.state}:${richRow.since ? richRow.since.at : 0}:${richRow.createdAt}"`
|
||||
: '';
|
||||
|
||||
const inlineSessionActions = this.shouldInlineSessionActions();
|
||||
const tabActionsHtml = `<span class="tab-actions"><span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions(${escapeHtml(JSON.stringify(id))})" title="Session options" aria-label="Session options" tabindex="0">⚙</span><span class="tab-detach" onclick="event.stopPropagation(); app.detachSession(${escapeHtml(JSON.stringify(id))})" title="Open in a new window" aria-label="Open session in a new window" tabindex="0">⧉</span><span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession(${escapeHtml(JSON.stringify(id))})" title="Close session" aria-label="Close session" tabindex="0">×</span><button type="button" class="tab-more" onclick="event.stopPropagation(); app.openTabRailActionMenu(event, ${escapeHtml(JSON.stringify(id))})" title="Session actions" aria-label="Session actions">⋯</button></span>`;
|
||||
|
||||
parts.push(`<div class="session-tab ${isActive ? 'active' : ''}${alertClass}${richClass}${loadState ? ' tab-loading' : ''}${this.hasTabDetachOverride(id) ? ' tab-show-detach' : ''}"${richData} data-id="${id}" data-color="${color}" ${loadState ? `data-load-phase="${escapeHtml(loadState.phase)}"` : ''} onclick="app.handleSessionTabClick(event, ${escapeHtml(JSON.stringify(id))})" oncontextmenu="event.preventDefault(); app.startInlineRename(${escapeHtml(JSON.stringify(id))})" tabindex="0" role="tab" aria-selected="${isActive ? 'true' : 'false'}" aria-busy="${loadState ? 'true' : 'false'}" aria-label="${escapeHtml(name)} session" ${tabTooltip ? `title="${escapeHtml(tabTooltip)}"` : ''}>
|
||||
${_tabIdx < 9 ? '<span class="tab-number">' + (_tabIdx + 1) + '</span>' : ''}
|
||||
${loadState ? '<span class="tab-load-spinner" aria-hidden="true"></span>' : ''}
|
||||
@@ -4728,7 +4784,8 @@ class CodemanApp {
|
||||
<span class="tab-info">
|
||||
<span class="tab-name-row">
|
||||
${mode === 'shell' ? '<span class="tab-mode shell" aria-hidden="true">sh</span>' : mode === 'opencode' ? '<span class="tab-mode opencode" aria-hidden="true">oc</span>' : mode === 'codex' ? '<span class="tab-mode codex" aria-hidden="true">cx</span>' : mode === 'gemini' ? '<span class="tab-mode gemini" aria-hidden="true">gm</span>' : mode === 'antigravity' ? '<span class="tab-mode antigravity" aria-hidden="true">ag</span>' : mode === 'pi' ? '<span class="tab-mode pi" aria-hidden="true">pi</span>' : mode === 'grok' ? '<span class="tab-mode grok" aria-hidden="true">gk</span>' : ''}
|
||||
<span class="tab-name" data-session-id="${id}">${escapeHtml(tabLabel)}</span>
|
||||
<span class="tab-name" data-session-id="${id}" data-full-name="${escapeHtml(name)}">${tabLabel}</span>
|
||||
${inlineSessionActions ? tabActionsHtml : ''}
|
||||
<span class="tab-detached-badge" aria-hidden="true">detached</span>
|
||||
</span>
|
||||
${showFolder ? `<span class="tab-folder">\u{1F4C1} ${escapeHtml(folderName)}</span>` : ''}
|
||||
@@ -4737,7 +4794,7 @@ class CodemanApp {
|
||||
${hasRunningTasks ? `<span class="tab-badge" onclick="event.stopPropagation(); app.toggleTaskPanel()" aria-label="${taskStats.running} running tasks">${taskStats.running}</span>` : ''}
|
||||
${subagentBadge}
|
||||
${ultracodeBadge}
|
||||
<span class="tab-actions"><span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions(${escapeHtml(JSON.stringify(id))})" title="Session options" aria-label="Session options" tabindex="0">⚙</span><span class="tab-detach" onclick="event.stopPropagation(); app.detachSession(${escapeHtml(JSON.stringify(id))})" title="Open in a new window" aria-label="Open session in a new window" tabindex="0">⧉</span><span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession(${escapeHtml(JSON.stringify(id))})" title="Close session" aria-label="Close session" tabindex="0">×</span></span>
|
||||
${inlineSessionActions ? '' : tabActionsHtml}
|
||||
</div>`);
|
||||
_tabIdx++;
|
||||
}
|
||||
@@ -6027,6 +6084,7 @@ class CodemanApp {
|
||||
|
||||
// Shared cleanup for all session data — called from both closeSession() and session:deleted handler
|
||||
_cleanupSessionData(sessionId) {
|
||||
this.closeTabRailActionMenu?.();
|
||||
// If the deleted session is currently being renamed, abort the rename
|
||||
// so the inline <input> doesn't ghost as a stale tab on screen.
|
||||
if (this._activeRename?.sessionId === sessionId) {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
* @globals {function} scheduleBackground - scheduler.postTask wrapper (background priority)
|
||||
* @globals {function} getEventCoords - Unified mouse/touch coordinate extractor
|
||||
* @globals {function} escapeHtml - XSS-safe HTML escaping
|
||||
* @globals {object} SSE_EVENTS - Centralized SSE event type constants (120 event types; must match backend src/web/sse-events.ts)
|
||||
* @globals {object} SSE_EVENTS - Centralized SSE event type constants (156 event types; must match backend src/web/sse-events.ts)
|
||||
* @globals {Array} BUILTIN_RESPAWN_PRESETS - Built-in respawn configuration presets
|
||||
*
|
||||
* @dependency None (first in load order)
|
||||
@@ -156,6 +156,43 @@ function shouldAutoWrapTabs(input) {
|
||||
return scrollWidth > clientWidth + 1;
|
||||
}
|
||||
|
||||
function resolveTabOrientation(input) {
|
||||
if (!input || input.setting !== 'vertical') return 'horizontal';
|
||||
if (input.deviceType === 'mobile') return 'horizontal';
|
||||
return 'vertical';
|
||||
}
|
||||
|
||||
const TAB_RAIL_MIN_WIDTH = 208;
|
||||
const TAB_RAIL_DEFAULT_WIDTH = 256;
|
||||
const TAB_RAIL_MAX_WIDTH = 360;
|
||||
|
||||
function resolveTabRailWidth(input = {}) {
|
||||
const viewportWidth = Number(input.viewportWidth);
|
||||
const mainWidth = Number(input.mainWidth);
|
||||
const minTerminalWidth = Number(input.minTerminalWidth);
|
||||
const limits = [TAB_RAIL_MAX_WIDTH];
|
||||
if (Number.isFinite(viewportWidth) && viewportWidth > 0) limits.push(Math.floor(viewportWidth * 0.4));
|
||||
if (Number.isFinite(mainWidth) && mainWidth > 0 && Number.isFinite(minTerminalWidth) && minTerminalWidth > 0) {
|
||||
limits.push(Math.floor(mainWidth - minTerminalWidth));
|
||||
}
|
||||
const effectiveMax = Math.max(TAB_RAIL_MIN_WIDTH, Math.min(...limits));
|
||||
const requested = Number(input.width);
|
||||
const width = Number.isFinite(requested) ? requested : TAB_RAIL_DEFAULT_WIDTH;
|
||||
return Math.round(Math.min(effectiveMax, Math.max(TAB_RAIL_MIN_WIDTH, width)));
|
||||
}
|
||||
|
||||
function resolveTabRailKeyboardWidth(input = {}) {
|
||||
let width;
|
||||
if (input.key === 'Home') width = TAB_RAIL_MIN_WIDTH;
|
||||
else if (input.key === 'End') width = TAB_RAIL_MAX_WIDTH;
|
||||
else if (input.key === 'Enter') width = TAB_RAIL_DEFAULT_WIDTH;
|
||||
else if (input.key === 'ArrowLeft' || input.key === 'ArrowRight') {
|
||||
const direction = input.key === 'ArrowLeft' ? -1 : 1;
|
||||
width = (Number(input.currentWidth) || TAB_RAIL_DEFAULT_WIDTH) + direction * (input.shiftKey ? 32 : 8);
|
||||
} else return null;
|
||||
return resolveTabRailWidth({ ...input, width });
|
||||
}
|
||||
|
||||
// Sliver of the neighbouring tab left visible when the strip scrolls a tab into
|
||||
// view. Landing a tab flush against the edge reads as "this is the last one";
|
||||
// the gap is what tells the user there is more strip to swipe to.
|
||||
@@ -243,6 +280,9 @@ const LINEAGE_DIP_MAX_PX = 64;
|
||||
// apart bled into one thick band instead of reading as three separate lines.
|
||||
const LINEAGE_SIBLING_STEP_PX = 8;
|
||||
const LINEAGE_STRIP_TOLERANCE_PX = 4;
|
||||
const LINEAGE_VERTICAL_TRACK_INSET_PX = 6;
|
||||
const LINEAGE_VERTICAL_SIBLING_STEP_PX = 3;
|
||||
const LINEAGE_VERTICAL_ANCHOR_CLEARANCE_PX = 4;
|
||||
// Lineage palette, assigned per SPAWNING TAB in first-seen order and cycled
|
||||
// (session-lineage.js). Every arc leaving one tab shares its colour however many
|
||||
// workers it spawns; a child that spawns in turn gets its own for the arcs below it.
|
||||
@@ -265,21 +305,44 @@ function computeLineagePath(input) {
|
||||
const ch = Number(child.height) || 0;
|
||||
if (pw <= 0 || ph <= 0 || cw <= 0 || ch <= 0) return null;
|
||||
|
||||
const px = Number(parent.left) + pw / 2;
|
||||
const cx = Number(child.left) + cw / 2;
|
||||
if (!Number.isFinite(px) || !Number.isFinite(cx)) return null;
|
||||
|
||||
const orientation = input?.orientation === 'vertical' ? 'vertical' : 'horizontal';
|
||||
const strip = input?.strip;
|
||||
const depth = Math.max(0, Math.min(6, Number(input?.depth) || 0));
|
||||
const pLeft = Number(parent.left);
|
||||
const cLeft = Number(child.left);
|
||||
const pTop = Number(parent.top);
|
||||
const cTop = Number(child.top);
|
||||
if (![pLeft, cLeft, pTop, cTop].every(Number.isFinite)) return null;
|
||||
|
||||
if (orientation === 'vertical') {
|
||||
const py = pTop + ph / 2;
|
||||
const cy = cTop + ch / 2;
|
||||
if (strip && Number(strip.height) > 0) {
|
||||
const min = Number(strip.top) - LINEAGE_STRIP_TOLERANCE_PX;
|
||||
const max = Number(strip.top) + Number(strip.height) + LINEAGE_STRIP_TOLERANCE_PX;
|
||||
if (py < min || py > max || cy < min || cy > max) return null;
|
||||
}
|
||||
|
||||
const stripLeft =
|
||||
strip && Number.isFinite(Number(strip.left))
|
||||
? Number(strip.left)
|
||||
: Math.min(pLeft, cLeft) - LINEAGE_VERTICAL_TRACK_INSET_PX * 2;
|
||||
const requestedTrack =
|
||||
stripLeft + LINEAGE_VERTICAL_TRACK_INSET_PX + depth * LINEAGE_VERTICAL_SIBLING_STEP_PX;
|
||||
const trackX = Math.min(requestedTrack, Math.min(pLeft, cLeft) - LINEAGE_VERTICAL_ANCHOR_CLEARANCE_PX);
|
||||
const d = `M ${r1(pLeft)} ${r1(py)} H ${r1(trackX)} V ${r1(cy)} H ${r1(cLeft)}`;
|
||||
return { d, endX: cLeft, endY: cy, sameRow: false };
|
||||
}
|
||||
|
||||
const px = pLeft + pw / 2;
|
||||
const cx = cLeft + cw / 2;
|
||||
if (strip && Number(strip.width) > 0) {
|
||||
const min = Number(strip.left) - LINEAGE_STRIP_TOLERANCE_PX;
|
||||
const max = Number(strip.left) + Number(strip.width) + LINEAGE_STRIP_TOLERANCE_PX;
|
||||
if (px < min || px > max || cx < min || cx > max) return null;
|
||||
}
|
||||
|
||||
const depth = Math.max(0, Math.min(6, Number(input?.depth) || 0));
|
||||
const pTop = Number(parent.top);
|
||||
const pBottom = pTop + ph;
|
||||
const cTop = Number(child.top);
|
||||
const cBottom = cTop + ch;
|
||||
const sameRow = Math.abs(pTop + ph / 2 - (cTop + ch / 2)) <= Math.min(ph, ch) / 2;
|
||||
|
||||
@@ -617,9 +680,17 @@ if (typeof window !== 'undefined') {
|
||||
window.shouldSkipWebGL = shouldSkipWebGL;
|
||||
window.CodemanTabOverflow = {
|
||||
shouldAutoWrapTabs,
|
||||
resolveTabOrientation,
|
||||
computeTabScrollLeft,
|
||||
TAB_SCROLL_REVEAL_PX,
|
||||
};
|
||||
window.CodemanTabRail = {
|
||||
DEFAULT_WIDTH: TAB_RAIL_DEFAULT_WIDTH,
|
||||
MIN_WIDTH: TAB_RAIL_MIN_WIDTH,
|
||||
MAX_WIDTH: TAB_RAIL_MAX_WIDTH,
|
||||
resolveWidth: resolveTabRailWidth,
|
||||
resolveKeyboardWidth: resolveTabRailKeyboardWidth,
|
||||
};
|
||||
window.CodemanWsReconnect = {
|
||||
plan: planWsReconnect,
|
||||
};
|
||||
@@ -628,6 +699,8 @@ if (typeof window !== 'undefined') {
|
||||
DIP_MIN_PX: LINEAGE_DIP_MIN_PX,
|
||||
DIP_MAX_PX: LINEAGE_DIP_MAX_PX,
|
||||
SIBLING_STEP_PX: LINEAGE_SIBLING_STEP_PX,
|
||||
VERTICAL_TRACK_INSET_PX: LINEAGE_VERTICAL_TRACK_INSET_PX,
|
||||
VERTICAL_SIBLING_STEP_PX: LINEAGE_VERTICAL_SIBLING_STEP_PX,
|
||||
COLORS: LINEAGE_COLORS,
|
||||
};
|
||||
window.CodemanConnectionLoss = {
|
||||
@@ -969,6 +1042,7 @@ const SSE_EVENTS = {
|
||||
|
||||
// Web tabs (dashboard URLs)
|
||||
WEBVIEW_CHANGED: 'webview:changed',
|
||||
TAB_LAYOUT_CHANGED: 'tab:layoutChanged',
|
||||
};
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -88,12 +88,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
/**
|
||||
* Width-driven, like every other layout decision in the app. Explicitly yields
|
||||
* to the phone overview: that surface already lists the same sessions, and two
|
||||
* lists of the same thing on one screen is worse than none.
|
||||
* to the phone overview and persistent vertical tab rail: those surfaces already
|
||||
* list the same sessions, and two lists of the same thing on one screen is worse
|
||||
* than none.
|
||||
*/
|
||||
shouldShowHomeSessions() {
|
||||
if (this.isSoloWindow) return false;
|
||||
if (this.shouldUseMobileOverview?.()) return false;
|
||||
if (document.documentElement.getAttribute('data-tab-orientation') === 'vertical') return false;
|
||||
// The sidebar layout already docks the full session list flush left at full
|
||||
// height — the rail would render the same list right next to it (and z-wise
|
||||
// UNDER it: sidebar 11, welcome overlay 10, rail inside the overlay).
|
||||
|
||||
@@ -233,6 +233,8 @@
|
||||
'Redraw Terminal Button': '重绘终端按钮',
|
||||
'Tab Bar': '标签栏',
|
||||
'Session List Layout': '会话列表布局',
|
||||
'Session Name Font Size': '会话名称字体大小',
|
||||
'Adjust only session names in the vertical sidebar.': '仅调整垂直侧边栏中的会话名称。',
|
||||
'Header tab strip': '顶栏标签条',
|
||||
'Left sidebar': '左侧边栏',
|
||||
'Left sidebar simple': '左侧边栏(简洁)',
|
||||
|
||||
@@ -65,7 +65,7 @@
|
||||
app.js, NOT the handheld storage-key test `m`. Use a different predicate
|
||||
here and boot will contradict this value, animating the drawer open by
|
||||
itself on every load between 768 and 1023px. -->
|
||||
<script>try{var m=window.innerWidth<768||(('ontouchstart' in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024);var k=m?'codeman-app-settings-mobile':'codeman-app-settings';var L=JSON.parse(localStorage.getItem(k)||'{}').sessionListLayout;var solo=/^\/session\//.test(location.pathname);var C=localStorage.getItem('codeman-sidebar-collapsed');var S=(L==='sidebar'||L==='sidebar-rich')&&!solo;document.documentElement.dataset.sessionList=S?'sidebar':'header';document.documentElement.dataset.sidebarDetail=(S&&L==='sidebar-rich')?'rich':'simple';document.documentElement.dataset.sidebar=(C===null?window.innerWidth<1024:C==='1')?'collapsed':'expanded';}catch(e){document.documentElement.dataset.sessionList='header';document.documentElement.dataset.sidebarDetail='simple';document.documentElement.dataset.sidebar='expanded';}</script>
|
||||
<script>try{var m=window.innerWidth<768||(('ontouchstart' in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024);var k=m?'codeman-app-settings-mobile':'codeman-app-settings';var A=JSON.parse(localStorage.getItem(k)||'{}');var L=A.sessionListLayout;var F=Number(A.sessionSidebarFontSize);var solo=/^\/session\//.test(location.pathname);var C=localStorage.getItem('codeman-sidebar-collapsed');var S=(L==='sidebar'||L==='sidebar-rich')&&!solo;document.documentElement.dataset.sessionList=S?'sidebar':'header';document.documentElement.dataset.sidebarDetail=(S&&L==='sidebar-rich')?'rich':'simple';document.documentElement.dataset.sidebar=(C===null?window.innerWidth<1024:C==='1')?'collapsed':'expanded';if(Number.isInteger(F)&&F>=11&&F<=18)document.documentElement.style.setProperty('--session-sidebar-name-font-size',F+'px');}catch(e){document.documentElement.dataset.sessionList='header';document.documentElement.dataset.sidebarDetail='simple';document.documentElement.dataset.sidebar='expanded';}</script>
|
||||
<!-- Inline critical CSS for instant skeleton paint (before styles.css loads) -->
|
||||
<style>
|
||||
.loading-skeleton{display:flex;flex-direction:column;height:100vh;height:100dvh;background:var(--bg-dark,#11151c)}
|
||||
@@ -358,6 +358,20 @@
|
||||
|
||||
<!-- Main Terminal Area -->
|
||||
<main class="main">
|
||||
<aside class="tab-rail" id="tabRail" aria-label="Session navigation">
|
||||
<div
|
||||
id="tabRailResizeHandle"
|
||||
class="tab-rail-resize-handle"
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label="Resize session rail"
|
||||
aria-valuemin="208"
|
||||
aria-valuemax="360"
|
||||
aria-valuenow="256"
|
||||
tabindex="0"
|
||||
></div>
|
||||
</aside>
|
||||
|
||||
<!-- Collapsible session sidebar (opt-in layout). Deliberately EMPTY in
|
||||
markup: applySessionListLayout() moves #sessionTabs in here, so the
|
||||
vertical list is the exact same DOM node as the header strip and every
|
||||
@@ -513,6 +527,7 @@
|
||||
desktop (which never loads mobile.css) can never render it. -->
|
||||
<div class="mobile-overview" id="mobileOverview" hidden></div>
|
||||
</main>
|
||||
<div class="tab-rail-resize-shield" id="tabRailResizeShield" aria-hidden="true" hidden></div>
|
||||
|
||||
<!-- Project Insights Panel (shows file-viewing Bash commands) -->
|
||||
<div class="project-insights-panel" id="projectInsightsPanel">
|
||||
@@ -1877,6 +1892,29 @@
|
||||
<div class="set-group">
|
||||
<div class="set-group-head"><h4>Tabs</h4><span class="set-scope">device</span></div>
|
||||
<div class="set-group-body">
|
||||
<div class="set-row has-field" data-search="tab orientation horizontal vertical side rail">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Tab Orientation</span>
|
||||
<span class="set-row-desc">Keep tabs in the header or place them beside the terminal. Phones stay horizontal.</span>
|
||||
</div>
|
||||
<select id="appSettingsTabOrientation" class="set-select">
|
||||
<option value="horizontal">Horizontal (top)</option>
|
||||
<option value="vertical">Vertical (side rail)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="set-row has-field" data-search="tab rail width resize compact wide maximum">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Vertical Rail Width</span>
|
||||
<span class="set-row-desc">Set the preferred rail width for this device.</span>
|
||||
</div>
|
||||
<select id="appSettingsTabRailWidth" class="set-select">
|
||||
<option value="208">Compact (208px)</option>
|
||||
<option value="256">Default (256px)</option>
|
||||
<option value="320">Wide (320px)</option>
|
||||
<option value="360">Maximum (360px)</option>
|
||||
<option value="custom" disabled>Custom</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="set-row has-field" data-search="session list layout sidebar tab strip vertical">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Session List Layout</span>
|
||||
@@ -1888,6 +1926,18 @@
|
||||
<option value="sidebar-rich">Left sidebar</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="set-row has-field" data-search="session sidebar name font size text">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label" id="appSettingsSessionSidebarFontSizeLabel">Session Name Font Size</span>
|
||||
<span class="set-row-desc">Adjust only session names in the vertical sidebar.</span>
|
||||
</div>
|
||||
<label class="set-range-field" for="appSettingsSessionSidebarFontSize">
|
||||
<input type="range" id="appSettingsSessionSidebarFontSize" min="11" max="18" step="1" value="14"
|
||||
aria-labelledby="appSettingsSessionSidebarFontSizeLabel"
|
||||
oninput="document.getElementById('appSettingsSessionSidebarFontSizeValue').textContent=this.value+' px'">
|
||||
<output id="appSettingsSessionSidebarFontSizeValue" for="appSettingsSessionSidebarFontSize">14 px</output>
|
||||
</label>
|
||||
</div>
|
||||
<div class="set-row" data-search="tall tabs folder name two rows">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Tall Tabs</span>
|
||||
@@ -3332,6 +3382,7 @@
|
||||
<!-- Hardened markdown HTML sanitizer (wires DOMPurify). Must precede app.js. -->
|
||||
<script defer src="sanitize-html.js"></script>
|
||||
<script defer src="app.js"></script>
|
||||
<script defer src="tab-rail-resize.js"></script>
|
||||
<script defer src="terminal-ui.js"></script>
|
||||
<script defer src="respawn-ui.js"></script>
|
||||
<script defer src="ralph-panel.js"></script>
|
||||
|
||||
@@ -160,6 +160,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
const strip = document.getElementById('sessionTabs');
|
||||
if (!strip) return;
|
||||
const stripRect = strip.getBoundingClientRect();
|
||||
const orientation =
|
||||
document.documentElement.getAttribute('data-tab-orientation') === 'vertical' ? 'vertical' : 'horizontal';
|
||||
for (const edge of edges) {
|
||||
for (const id of [edge.parentId, edge.childId]) {
|
||||
const key = 'tab:' + id;
|
||||
@@ -175,7 +177,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
const childRect = rects.get('tab:' + edge.childId);
|
||||
if (!parentRect || !childRect) continue;
|
||||
|
||||
const geom = compute({ parent: parentRect, child: childRect, strip: stripRect, depth: edge.depth });
|
||||
const geom = compute({
|
||||
parent: parentRect,
|
||||
child: childRect,
|
||||
strip: stripRect,
|
||||
depth: edge.depth,
|
||||
orientation,
|
||||
});
|
||||
if (!geom) continue; // scrolled out of the strip, or a degenerate rect
|
||||
|
||||
const line = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||||
|
||||
@@ -1851,15 +1851,22 @@ Object.assign(CodemanApp.prototype, {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
|
||||
this._activeRename?.cancel();
|
||||
|
||||
const tabName = document.querySelector(`.tab-name[data-session-id="${sessionId}"]`);
|
||||
if (!tabName) return;
|
||||
|
||||
// Prevent tab re-renders from destroying the input while renaming
|
||||
this._inlineRenameActive = true;
|
||||
tabName.classList.add('tab-name-renaming');
|
||||
|
||||
const currentName = this.getSessionName(session);
|
||||
const parsed = parseSessionPrefix(session.name);
|
||||
const originalContent = tabName.textContent;
|
||||
const originalChildren = [...tabName.childNodes].map((node) => node.cloneNode(true));
|
||||
const restoreOriginalChildren = () => {
|
||||
tabName.replaceChildren(...originalChildren.map((node) => node.cloneNode(true)));
|
||||
};
|
||||
// Clear existing content to make room for the input element
|
||||
tabName.textContent = '';
|
||||
while (tabName.firstChild) tabName.removeChild(tabName.firstChild);
|
||||
@@ -1867,6 +1874,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// If prefix detected, show it as non-editable label
|
||||
if (parsed) {
|
||||
const prefixLabel = document.createElement('span');
|
||||
prefixLabel.className = 'tab-rename-prefix';
|
||||
prefixLabel.textContent = parsed.prefix + ': ';
|
||||
prefixLabel.style.cssText = 'color: var(--text-muted); font-size: 0.75rem; white-space: nowrap;';
|
||||
tabName.appendChild(prefixLabel);
|
||||
@@ -1879,36 +1887,67 @@ Object.assign(CodemanApp.prototype, {
|
||||
input.className = 'tab-rename-input';
|
||||
// 80px is tuned for the narrow header tab; a full-width sidebar row can and
|
||||
// should give the whole line to the input.
|
||||
const renameWidth = this.isSessionSidebarActive?.() ? '100%' : '80px';
|
||||
const renameWidth = tabName.closest('.tab-rail') ? 'auto' : this.isSessionSidebarActive?.() ? '100%' : '80px';
|
||||
input.style.cssText = `width: ${renameWidth}; min-width: 0; font-size: 0.75rem; padding: 2px 4px; background: var(--bg-input); border: 1px solid var(--accent); border-radius: 3px; color: var(--text); outline: none;`;
|
||||
|
||||
tabName.appendChild(input);
|
||||
input.focus();
|
||||
input.select();
|
||||
|
||||
const finishRename = async ({ commit }) => {
|
||||
if (!this._inlineRenameActive) return; // prevent double-fire
|
||||
let editSettled = false;
|
||||
let invalidated = false;
|
||||
let completed = false;
|
||||
|
||||
const releaseRenderGuard = () => {
|
||||
if (this._activeRename !== renameHandle) return;
|
||||
this._inlineRenameActive = false;
|
||||
};
|
||||
|
||||
const completeCurrentRename = () => {
|
||||
if (this._activeRename !== renameHandle) return;
|
||||
completed = true;
|
||||
releaseRenderGuard();
|
||||
this._activeRename = null;
|
||||
this.renderSessionTabs();
|
||||
};
|
||||
|
||||
const cancelRename = () => {
|
||||
if (invalidated || completed) return;
|
||||
invalidated = true;
|
||||
editSettled = true;
|
||||
tabName.classList.remove('tab-name-renaming');
|
||||
restoreOriginalChildren();
|
||||
completeCurrentRename();
|
||||
};
|
||||
|
||||
const finishRename = async ({ commit }) => {
|
||||
if (editSettled || invalidated) return;
|
||||
editSettled = true;
|
||||
tabName.classList.remove('tab-name-renaming');
|
||||
|
||||
// Aborted (e.g. the session was deleted mid-rename, or Escape): re-render
|
||||
// so any ghost DOM is replaced with the canonical tab list, and skip the
|
||||
// API call — a cancel must not fire a stale rename PUT.
|
||||
if (!commit) {
|
||||
this.renderSessionTabs();
|
||||
cancelRename();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._activeRename !== renameHandle) return;
|
||||
releaseRenderGuard();
|
||||
|
||||
const suffix = input.value.trim();
|
||||
const fullName = parsed ? parsed.prefix + (suffix ? ': ' + suffix : '') : suffix;
|
||||
tabName.textContent = fullName || originalContent;
|
||||
if (fullName === session.name) restoreOriginalChildren();
|
||||
else tabName.textContent = fullName || originalContent;
|
||||
|
||||
// Skip the API call if the session vanished between focus and blur.
|
||||
const stillExists = this.sessions.has(sessionId);
|
||||
if (stillExists && fullName !== session.name) {
|
||||
const confirmed = await this._putSessionName(sessionId, fullName);
|
||||
if (invalidated || this._activeRename !== renameHandle || !this.sessions.has(sessionId)) return;
|
||||
if (confirmed === null) {
|
||||
tabName.textContent = originalContent;
|
||||
restoreOriginalChildren();
|
||||
this.showToast('Failed to rename', 'error');
|
||||
} else {
|
||||
// The re-render below repaints from this.sessions, so the new name has
|
||||
@@ -1917,14 +1956,15 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
}
|
||||
// Re-render tabs to restore full tab structure
|
||||
this.renderSessionTabs();
|
||||
completeCurrentRename();
|
||||
};
|
||||
|
||||
// Register only after the input is wired so a throw above can't strand state.
|
||||
this._activeRename = {
|
||||
const renameHandle = {
|
||||
sessionId,
|
||||
cancel: () => finishRename({ commit: false }),
|
||||
cancel: cancelRename,
|
||||
};
|
||||
this._activeRename = renameHandle;
|
||||
|
||||
input.addEventListener('blur', () => finishRename({ commit: true }));
|
||||
input.addEventListener('keydown', (e) => {
|
||||
|
||||
@@ -400,9 +400,20 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.getElementById('appSettingsCjkInput').checked = settings.cjkInputEnabled ?? defaults.cjkInputEnabled ?? false;
|
||||
document.getElementById('appSettingsExtendedKeyboardBar').checked = settings.extendedKeyboardBar ?? false;
|
||||
document.getElementById('appSettingsTabTwoRows').checked = settings.tabTwoRows ?? defaults.tabTwoRows ?? false;
|
||||
document.getElementById('appSettingsTabOrientation').value =
|
||||
settings.tabOrientation ?? defaults.tabOrientation ?? 'horizontal';
|
||||
const tabRailWidth = window.CodemanTabRail?.resolveWidth({
|
||||
width: settings.tabRailWidth ?? defaults.tabRailWidth ?? 256,
|
||||
}) ?? 256;
|
||||
this.syncTabRailWidthSetting?.(tabRailWidth);
|
||||
document.getElementById('appSettingsShowTabDetachButton').checked = settings.showTabDetachButton ?? defaults.showTabDetachButton ?? false;
|
||||
document.getElementById('appSettingsSessionListLayout').value =
|
||||
settings.sessionListLayout ?? defaults.sessionListLayout ?? 'header';
|
||||
const sessionSidebarFontSize = this.resolveSessionSidebarFontSize(
|
||||
settings.sessionSidebarFontSize ?? defaults.sessionSidebarFontSize
|
||||
);
|
||||
document.getElementById('appSettingsSessionSidebarFontSize').value = String(sessionSidebarFontSize);
|
||||
document.getElementById('appSettingsSessionSidebarFontSizeValue').textContent = `${sessionSidebarFontSize} px`;
|
||||
// Claude CLI settings
|
||||
const claudeModeSelect = document.getElementById('appSettingsClaudeMode');
|
||||
const allowedToolsRow = document.getElementById('allowedToolsRow');
|
||||
@@ -2028,8 +2039,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
webglRendererEnabled: document.getElementById('appSettingsWebglRenderer').checked,
|
||||
extendedKeyboardBar: document.getElementById('appSettingsExtendedKeyboardBar').checked,
|
||||
tabTwoRows: document.getElementById('appSettingsTabTwoRows').checked,
|
||||
tabOrientation: document.getElementById('appSettingsTabOrientation').value,
|
||||
tabRailWidth: this.readTabRailWidthSetting?.() ?? 256,
|
||||
showTabDetachButton: document.getElementById('appSettingsShowTabDetachButton').checked,
|
||||
sessionListLayout: document.getElementById('appSettingsSessionListLayout').value,
|
||||
sessionSidebarFontSize: this.resolveSessionSidebarFontSize(
|
||||
document.getElementById('appSettingsSessionSidebarFontSize').value
|
||||
),
|
||||
skin: document.getElementById('appSettingsSkin').value,
|
||||
// Claude CLI settings
|
||||
claudeMode: document.getElementById('appSettingsClaudeMode').value,
|
||||
@@ -2179,6 +2195,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Re-parents #sessionTabs between header host and sidebar if the layout
|
||||
// changed, then calls applyTabWrapSettings() itself — do not call both.
|
||||
this.applySessionListLayout();
|
||||
this.applyTabOrientation({ settleRailWidth: true });
|
||||
this.applyLineageLineSettings?.();
|
||||
this._updateTokensImmediate(); // Re-render token display (picks up showCost change)
|
||||
this.applyMonitorVisibility();
|
||||
@@ -2424,7 +2441,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
imageWatcherEnabled: false,
|
||||
ralphTrackerEnabled: false,
|
||||
tabTwoRows: false,
|
||||
tabOrientation: 'horizontal',
|
||||
tabRailWidth: 256,
|
||||
sessionListLayout: 'header',
|
||||
sessionSidebarFontSize: 14,
|
||||
cjkInputEnabled: false,
|
||||
terminalWheelLocalScrollback: false, // mobile scrolls via touch, not wheel
|
||||
webglRendererEnabled: false, // mobile always uses the DOM renderer
|
||||
@@ -2665,6 +2685,48 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
applyTabOrientation(options = {}) {
|
||||
const settings = this.loadAppSettingsFromStorage();
|
||||
const defaults = this.getDefaultSettings();
|
||||
const sidebarOwnsTabs = this.isSessionSidebarActive?.() === true;
|
||||
const orientation =
|
||||
!this.isSoloWindow && !sidebarOwnsTabs && window.CodemanTabOverflow?.resolveTabOrientation
|
||||
? window.CodemanTabOverflow.resolveTabOrientation({
|
||||
deviceType: MobileDetection.getDeviceType(),
|
||||
setting: settings.tabOrientation ?? defaults.tabOrientation ?? 'horizontal',
|
||||
})
|
||||
: 'horizontal';
|
||||
|
||||
const root = document.documentElement;
|
||||
const previous = root.getAttribute('data-tab-orientation') || 'horizontal';
|
||||
root.setAttribute('data-tab-orientation', orientation);
|
||||
|
||||
const tabsEl = document.getElementById('sessionTabs');
|
||||
const rail = document.getElementById('tabRail');
|
||||
const headerHost = document.getElementById('sessionTabsHost');
|
||||
if (!sidebarOwnsTabs && tabsEl && rail && headerHost) {
|
||||
if (orientation === 'vertical') {
|
||||
if (tabsEl.parentElement !== rail) rail.appendChild(tabsEl);
|
||||
} else if (tabsEl.parentElement !== headerHost) {
|
||||
headerHost.appendChild(tabsEl);
|
||||
}
|
||||
}
|
||||
if (tabsEl) {
|
||||
tabsEl.setAttribute('aria-orientation', sidebarOwnsTabs || orientation === 'vertical' ? 'vertical' : 'horizontal');
|
||||
}
|
||||
|
||||
const settleRailWidth =
|
||||
options.settleRailWidth === true && (orientation === 'vertical' || previous !== orientation);
|
||||
this.applyTabRailWidth?.({ settle: settleRailWidth });
|
||||
if (previous !== orientation) {
|
||||
this.updateTabOverflowMode?.();
|
||||
if (!settleRailWidth) this.fitAddon?.fit();
|
||||
this._fullRenderSessionTabs?.();
|
||||
this._updateConnectionLinesImmediate?.();
|
||||
this._refreshHomeSessionsIfVisible?.();
|
||||
}
|
||||
},
|
||||
|
||||
applyTabWrapSettings() {
|
||||
const settings = this.loadAppSettingsFromStorage();
|
||||
const defaults = this.getDefaultSettings();
|
||||
@@ -2898,7 +2960,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
'showFontControls', 'showSystemStats', 'showTokenCount', 'showCost',
|
||||
'showLifecycleLog', 'showResponseViewer', 'showRedrawButton',
|
||||
'showMonitor', 'showProjectInsights', 'showFileBrowser', 'showSubagents',
|
||||
'subagentActiveTabOnly', 'tabTwoRows', 'sessionListLayout', 'localEchoEnabled', 'cjkInputEnabled', 'extendedKeyboardBar',
|
||||
'subagentActiveTabOnly', 'tabTwoRows', 'tabOrientation', 'tabRailWidth', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'cjkInputEnabled', 'extendedKeyboardBar',
|
||||
'skin', 'showPlanUsageLimits', 'showAttachmentsButton', 'showFileViewerButton', 'webglRendererEnabled',
|
||||
'terminalFontFamily',
|
||||
'language',
|
||||
|
||||
@@ -62,6 +62,7 @@
|
||||
--ring-glow: 0 0 12px -2px rgba(56, 182, 240, 0.55);
|
||||
--header-height: 36px;
|
||||
--toolbar-height: 42px;
|
||||
--tab-rail-width: 256px;
|
||||
--sidebar-width: 260px;
|
||||
--sidebar-width-rich: 300px; /* detailed rows carry a stamps line as well */
|
||||
--sidebar-width-collapsed: 44px; /* == --touch-target-min */
|
||||
@@ -575,6 +576,99 @@ body {
|
||||
background: var(--border-light);
|
||||
}
|
||||
|
||||
.tab-rail {
|
||||
display: none;
|
||||
flex: 0 0 var(--tab-rail-width);
|
||||
width: var(--tab-rail-width);
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
background: var(--glass-bg);
|
||||
border-right: 1px solid var(--glass-border);
|
||||
position: relative;
|
||||
z-index: 11;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .tab-rail {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .tab-rail .session-tabs {
|
||||
--lineage-vertical-gutter: 24px;
|
||||
flex-direction: column;
|
||||
flex-wrap: nowrap;
|
||||
align-items: stretch;
|
||||
gap: 2px;
|
||||
padding: 0.35rem;
|
||||
padding-left: calc(0.35rem + var(--lineage-vertical-gutter));
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
max-height: none;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .tab-rail .session-tab {
|
||||
width: 100%;
|
||||
max-width: none;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .tab-rail .session-tab > * {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .tab-rail .session-tab .tab-info {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .header-right {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.tab-rail-resize-handle {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 16px;
|
||||
cursor: ew-resize;
|
||||
touch-action: none;
|
||||
transition: background-color 0.15s ease;
|
||||
}
|
||||
|
||||
.tab-rail-resize-handle:hover,
|
||||
.tab-rail-resize-handle:focus-visible {
|
||||
background: color-mix(in srgb, var(--accent) 24%, transparent);
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
html:not([data-tab-orientation='vertical']) .tab-rail-resize-handle {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.tab-rail-resize-shield:not([hidden]) {
|
||||
display: block;
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 10000;
|
||||
cursor: ew-resize;
|
||||
}
|
||||
|
||||
body.tab-rail-resizing,
|
||||
body.tab-rail-resizing * {
|
||||
cursor: ew-resize !important;
|
||||
user-select: none !important;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.tab-rail,
|
||||
.tab-rail-resize-handle {
|
||||
transition: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
.session-tab {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1422,6 +1516,44 @@ html[data-line-anim="packet"] .connection-line.line-enter {
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.session-tab .tab-name-prefix {
|
||||
display: none;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .tab-rail .session-tab .tab-name {
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
line-clamp: 2;
|
||||
overflow: hidden;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: normal;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .tab-rail .session-tab .tab-name-prefix {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .tab-rail .session-tab .tab-name.tab-name-renaming {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
-webkit-box-orient: initial;
|
||||
-webkit-line-clamp: unset;
|
||||
line-clamp: unset;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .tab-name-renaming .tab-rename-prefix {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .tab-name-renaming .tab-rename-input {
|
||||
flex: 1 1 0;
|
||||
width: auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* Tab folder path — hidden by default, shown via .tabs-show-folder on container */
|
||||
.session-tab .tab-folder {
|
||||
font-size: 0.6rem;
|
||||
@@ -2153,6 +2285,123 @@ html[data-line-anim="packet"] .connection-line.line-enter {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.session-tab .tab-more {
|
||||
display: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.75rem;
|
||||
height: 1.5rem;
|
||||
padding: 0;
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
font: 700 1rem/1 monospace;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
html[data-session-list='sidebar'][data-sidebar='expanded'] .session-sidebar .tab-name-row > .tab-actions > .tab-more,
|
||||
html[data-tab-orientation='vertical']:not(.tab-rail-compact) .tab-rail .tab-name-row > .tab-actions > .tab-more,
|
||||
html[data-tab-orientation='vertical'].tab-rail-compact .session-tab.active > .tab-actions > .tab-more {
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
.session-tab:hover > .tab-actions > .tab-more,
|
||||
.session-tab:focus-within > .tab-actions > .tab-more,
|
||||
.session-tab.active > .tab-actions > .tab-more,
|
||||
html[data-session-list='sidebar'][data-sidebar='expanded'] .session-sidebar
|
||||
:is(.session-tab:hover, .session-tab:focus-within, .session-tab.active)
|
||||
.tab-name-row
|
||||
> .tab-actions
|
||||
> .tab-more,
|
||||
html[data-tab-orientation='vertical']:not(.tab-rail-compact) .tab-rail
|
||||
:is(.session-tab:hover, .session-tab:focus-within, .session-tab.active)
|
||||
.tab-name-row
|
||||
> .tab-actions
|
||||
> .tab-more {
|
||||
visibility: visible;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'].tab-rail-compact .session-tab .tab-actions > :is(.tab-gear, .tab-detach, .tab-close) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (pointer: coarse) {
|
||||
.session-tab > .tab-actions > .tab-more,
|
||||
html[data-session-list='sidebar'][data-sidebar='expanded']
|
||||
.session-sidebar
|
||||
.session-tab
|
||||
.tab-name-row
|
||||
> .tab-actions
|
||||
> .tab-more,
|
||||
html[data-tab-orientation='vertical']:not(.tab-rail-compact)
|
||||
.tab-rail
|
||||
.session-tab
|
||||
.tab-name-row
|
||||
> .tab-actions
|
||||
> .tab-more {
|
||||
visibility: visible;
|
||||
pointer-events: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.tab-rail-action-menu {
|
||||
position: fixed;
|
||||
z-index: 2000;
|
||||
display: grid;
|
||||
min-width: 180px;
|
||||
padding: 0.3rem;
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: var(--btn-radius);
|
||||
background: var(--floating-bg);
|
||||
box-shadow: var(--elevated-shadow);
|
||||
}
|
||||
|
||||
.tab-rail-action-menu button {
|
||||
padding: 0.45rem 0.6rem;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.tab-rail-action-menu button:hover,
|
||||
.tab-rail-action-menu button:focus-visible {
|
||||
background: var(--control-bg-hover);
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.tab-rail-action-menu .danger {
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
:is(#appSettingsModal, #sessionOptionsModal, #createCaseModal) .set-range-field {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(112px, 1fr) 44px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: min(220px, 44vw);
|
||||
}
|
||||
|
||||
:is(#appSettingsModal, #sessionOptionsModal, #createCaseModal) .set-range-field input {
|
||||
width: 100%;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
:is(#appSettingsModal, #sessionOptionsModal, #createCaseModal) .set-range-field output {
|
||||
color: var(--text);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.7rem;
|
||||
font-variant-numeric: tabular-nums;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
/* Pop-out button is opt-in (App Settings → Tab Bar, default off; per-device).
|
||||
settings-ui.js mirrors the setting as the tabs-show-detach class on <html>.
|
||||
A tab that is ALREADY detached keeps its icon regardless: it is the
|
||||
@@ -14806,6 +15055,10 @@ html[data-skin="daylight-blue"] .welcome-btn-tunnel.active:hover {
|
||||
display: none;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .home-sessions {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Belt and braces with shouldShowHomeSessions(): a resize that outruns the
|
||||
matchMedia listener must never leave the column overlapping the content. */
|
||||
@media (max-width: 1179px) {
|
||||
@@ -16582,6 +16835,13 @@ html[data-skin="daylight-blue"] .welcome-btn-tunnel.active:hover {
|
||||
padding: 0 22px 22px;
|
||||
}
|
||||
|
||||
#sessionOptionsModal #context-tab {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 0.25rem 1rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
#sessionOptionsModal .set-section {
|
||||
padding-top: 18px;
|
||||
}
|
||||
@@ -16599,6 +16859,22 @@ html[data-skin="daylight-blue"] .welcome-btn-tunnel.active:hover {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
@media (min-width: 1200px) {
|
||||
#sessionOptionsModal .modal-content.modal-lg {
|
||||
width: min(1120px, 96vw);
|
||||
max-width: min(1120px, 96vw);
|
||||
}
|
||||
|
||||
#sessionOptionsModal #context-tab {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
#sessionOptionsModal #context-tab > .set-section-head,
|
||||
#sessionOptionsModal #context-tab > .set-section-blurb {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
|
||||
#sessionOptionsModal .set-group + .set-group {
|
||||
margin-top: 16px;
|
||||
}
|
||||
@@ -16888,10 +17164,27 @@ html[data-session-list="sidebar"] .session-sidebar .tab-info {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
html[data-session-list="sidebar"] .session-sidebar .tab-name-row,
|
||||
html[data-session-list="sidebar"] .session-sidebar .tab-name {
|
||||
min-width: 0;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
html[data-session-list='sidebar'] .session-sidebar .tab-name {
|
||||
flex: 0 1 auto;
|
||||
white-space: nowrap;
|
||||
font-size: var(--session-sidebar-name-font-size, 14px);
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .tab-rail .session-tab .tab-name {
|
||||
font-size: var(--session-sidebar-name-font-size, 14px);
|
||||
}
|
||||
|
||||
html[data-session-list='sidebar'] .session-sidebar .tab-actions,
|
||||
html[data-tab-orientation='vertical'] .tab-rail .session-tab .tab-name-row > .tab-actions {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* Reveal-on-hover reads badly on a 40px-tall full-width row, so keep the row
|
||||
actions permanently visible on the active session — no layout jitter when
|
||||
the pointer crosses the list. */
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
/** @fileoverview Accessible, device-local vertical session-rail sizing. */
|
||||
|
||||
Object.assign(CodemanApp.prototype, {
|
||||
_getTabRailMinimumTerminalWidth() {
|
||||
const cellWidth = this.terminal?._core?._renderService?.dimensions?.css?.cell?.width;
|
||||
if (Number.isFinite(cellWidth) && cellWidth > 0) return Math.ceil(cellWidth * 40 + 24);
|
||||
return 420;
|
||||
},
|
||||
|
||||
_getTabRailBounds() {
|
||||
const main = document.querySelector('.main');
|
||||
return {
|
||||
viewportWidth: window.innerWidth,
|
||||
mainWidth: main?.clientWidth || window.innerWidth,
|
||||
minTerminalWidth: this._getTabRailMinimumTerminalWidth(),
|
||||
};
|
||||
},
|
||||
|
||||
_getCurrentTabRailWidth() {
|
||||
const fromCss = Number.parseFloat(document.documentElement.style.getPropertyValue('--tab-rail-width'));
|
||||
if (Number.isFinite(fromCss)) return fromCss;
|
||||
const measured = document.getElementById('tabRail')?.getBoundingClientRect?.().width;
|
||||
return Number.isFinite(measured) && measured > 0 ? measured : window.CodemanTabRail?.DEFAULT_WIDTH || 256;
|
||||
},
|
||||
|
||||
readTabRailWidthSetting() {
|
||||
const select = document.getElementById('appSettingsTabRailWidth');
|
||||
if (!select) return this._getCurrentTabRailWidth();
|
||||
if (select.value === 'custom') return Number(select.dataset.currentWidth) || this._getCurrentTabRailWidth();
|
||||
return Number(select.value) || window.CodemanTabRail?.DEFAULT_WIDTH || 256;
|
||||
},
|
||||
|
||||
syncTabRailWidthSetting(width) {
|
||||
const select = document.getElementById('appSettingsTabRailWidth');
|
||||
if (!select) return;
|
||||
const rounded = Math.round(width);
|
||||
select.dataset.currentWidth = String(rounded);
|
||||
const preset = select.querySelector(`option[value="${rounded}"]`);
|
||||
if (preset) {
|
||||
select.value = String(rounded);
|
||||
return;
|
||||
}
|
||||
const custom = select.querySelector('option[value="custom"]');
|
||||
if (custom) custom.textContent = `Custom (${rounded}px)`;
|
||||
select.value = 'custom';
|
||||
},
|
||||
|
||||
_setTabRailWidth(width) {
|
||||
const policy = window.CodemanTabRail;
|
||||
if (!policy) return 256;
|
||||
const preferred = policy.resolveWidth({ width });
|
||||
const bounds = this._getTabRailBounds();
|
||||
const resolved = policy.resolveWidth({ width: preferred, ...bounds });
|
||||
const effectiveMax = policy.resolveWidth({ width: policy.MAX_WIDTH, ...bounds });
|
||||
const root = document.documentElement;
|
||||
root.style.setProperty('--tab-rail-width', `${resolved}px`);
|
||||
const wasCompact = root.classList.contains('tab-rail-compact');
|
||||
const compact = resolved < 240;
|
||||
root.classList.toggle('tab-rail-compact', compact);
|
||||
if (wasCompact !== compact) this._fullRenderSessionTabs?.();
|
||||
const handle = document.getElementById('tabRailResizeHandle');
|
||||
if (handle) {
|
||||
handle.setAttribute('aria-valuemax', String(effectiveMax));
|
||||
handle.setAttribute('aria-valuenow', String(resolved));
|
||||
}
|
||||
this.syncTabRailWidthSetting(preferred);
|
||||
return resolved;
|
||||
},
|
||||
|
||||
_persistTabRailWidth(width) {
|
||||
const settings = this.loadAppSettingsFromStorage();
|
||||
if (settings.tabRailWidth === width) return;
|
||||
settings.tabRailWidth = width;
|
||||
this.saveAppSettingsToStorage(settings);
|
||||
},
|
||||
|
||||
_claimTabRailResize() {
|
||||
this._tabRailResizeOwnsObserver = true;
|
||||
clearTimeout(this._tabRailResizeWatchdog);
|
||||
clearTimeout(this._tabRailReleaseTimer);
|
||||
if (this._tabRailReleaseRaf) cancelAnimationFrame(this._tabRailReleaseRaf);
|
||||
this._armTabRailResizeWatchdog();
|
||||
if (this._resizeRaf) cancelAnimationFrame(this._resizeRaf);
|
||||
if (this._resizeTimeout) clearTimeout(this._resizeTimeout);
|
||||
this._resizeRaf = null;
|
||||
this._resizeTimeout = null;
|
||||
},
|
||||
|
||||
_armTabRailResizeWatchdog() {
|
||||
this._tabRailResizeWatchdog = setTimeout(() => {
|
||||
this._tabRailResizeWatchdog = null;
|
||||
if (document.body.classList.contains('tab-rail-resizing')) {
|
||||
this._armTabRailResizeWatchdog();
|
||||
return;
|
||||
}
|
||||
this._tabRailResizeOwnsObserver = false;
|
||||
}, 1000);
|
||||
},
|
||||
|
||||
_releaseTabRailResize() {
|
||||
clearTimeout(this._tabRailResizeWatchdog);
|
||||
this._tabRailResizeWatchdog = null;
|
||||
const release = () => {
|
||||
clearTimeout(this._tabRailReleaseTimer);
|
||||
this._tabRailReleaseTimer = null;
|
||||
this._tabRailReleaseRaf = null;
|
||||
this._tabRailResizeOwnsObserver = false;
|
||||
};
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
this._tabRailReleaseRaf = requestAnimationFrame(() => {
|
||||
this._tabRailReleaseRaf = requestAnimationFrame(release);
|
||||
});
|
||||
this._tabRailReleaseTimer = setTimeout(release, 250);
|
||||
} else release();
|
||||
},
|
||||
|
||||
_scheduleTabRailSettle(effective, preferred = effective) {
|
||||
clearTimeout(this._tabRailSettleTimer);
|
||||
this._tabRailSettleTimer = setTimeout(async () => {
|
||||
this._tabRailSettleTimer = null;
|
||||
this._persistTabRailWidth(preferred);
|
||||
try {
|
||||
if (this.activeSessionId && this.sendResize) await this.sendResize(this.activeSessionId);
|
||||
else this.fitAddon?.fit();
|
||||
this._updateConnectionLinesImmediate?.();
|
||||
} catch (error) {
|
||||
console.warn('Failed to resize terminal after rail resize:', error);
|
||||
} finally {
|
||||
this._releaseTabRailResize();
|
||||
}
|
||||
}, 150);
|
||||
},
|
||||
|
||||
applyTabRailWidth(options = {}) {
|
||||
const settings = this.loadAppSettingsFromStorage();
|
||||
const requested = settings.tabRailWidth ?? window.CodemanTabRail?.DEFAULT_WIDTH ?? 256;
|
||||
const preferred = window.CodemanTabRail?.resolveWidth({ width: requested }) ?? 256;
|
||||
if (options.settle) this._claimTabRailResize();
|
||||
const resolved = this._setTabRailWidth(preferred);
|
||||
if (options.persist !== false && requested !== preferred) this._persistTabRailWidth(preferred);
|
||||
if (options.settle) this._scheduleTabRailSettle(resolved, preferred);
|
||||
return resolved;
|
||||
},
|
||||
|
||||
_applyTabRailPointerWidth(clientX) {
|
||||
const main = document.querySelector('.main');
|
||||
if (!main) return this._getCurrentTabRailWidth();
|
||||
const previous = this._getCurrentTabRailWidth();
|
||||
const width = this._setTabRailWidth(clientX - main.getBoundingClientRect().left);
|
||||
let proposed = null;
|
||||
try {
|
||||
proposed = this.fitAddon?.proposeDimensions?.();
|
||||
} catch {}
|
||||
return proposed && proposed.cols < 40 ? this._setTabRailWidth(previous) : width;
|
||||
},
|
||||
|
||||
_queueTabRailPointerWidth(clientX) {
|
||||
this._tabRailPendingClientX = clientX;
|
||||
if (this._tabRailPointerRaf) return;
|
||||
this._tabRailPointerRaf = requestAnimationFrame(() => {
|
||||
this._tabRailPointerRaf = null;
|
||||
this._tabRailDragWidth = this._applyTabRailPointerWidth(this._tabRailPendingClientX);
|
||||
});
|
||||
},
|
||||
|
||||
_finishTabRailDrag(handle, pointerId) {
|
||||
if (!document.body.classList.contains('tab-rail-resizing')) return;
|
||||
if (this._tabRailPointerRaf) {
|
||||
cancelAnimationFrame(this._tabRailPointerRaf);
|
||||
this._tabRailPointerRaf = null;
|
||||
this._tabRailDragWidth = this._applyTabRailPointerWidth(this._tabRailPendingClientX);
|
||||
}
|
||||
document.body.classList.remove('tab-rail-resizing');
|
||||
const shield = document.getElementById('tabRailResizeShield');
|
||||
if (shield) shield.hidden = true;
|
||||
try {
|
||||
if (handle.hasPointerCapture?.(pointerId)) handle.releasePointerCapture(pointerId);
|
||||
} catch {}
|
||||
const preferred = window.CodemanTabRail?.resolveWidth({ width: this._tabRailDragWidth }) ?? this._tabRailDragWidth;
|
||||
this._scheduleTabRailSettle(this._tabRailDragWidth || this._getCurrentTabRailWidth(), preferred);
|
||||
},
|
||||
|
||||
_onTabRailKeyDown(event) {
|
||||
const width = window.CodemanTabRail?.resolveKeyboardWidth({
|
||||
key: event.key,
|
||||
shiftKey: event.shiftKey,
|
||||
currentWidth: this._getCurrentTabRailWidth(),
|
||||
...this._getTabRailBounds(),
|
||||
});
|
||||
if (width === null || width === undefined) return;
|
||||
event.preventDefault();
|
||||
this._claimTabRailResize();
|
||||
const effective = this._setTabRailWidth(width);
|
||||
this._scheduleTabRailSettle(effective, window.CodemanTabRail.resolveWidth({ width }));
|
||||
},
|
||||
|
||||
initTabRailResize() {
|
||||
const handle = document.getElementById('tabRailResizeHandle');
|
||||
if (!handle || handle.dataset.ready === '1') return;
|
||||
handle.dataset.ready = '1';
|
||||
this.applyTabRailWidth();
|
||||
handle.addEventListener('pointerdown', (event) => {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
this.closeTabRailActionMenu();
|
||||
this._claimTabRailResize();
|
||||
this._tabRailDragWidth = this._getCurrentTabRailWidth();
|
||||
this._tabRailPendingClientX = event.clientX;
|
||||
document.body.classList.add('tab-rail-resizing');
|
||||
const shield = document.getElementById('tabRailResizeShield');
|
||||
if (shield) shield.hidden = false;
|
||||
try {
|
||||
handle.setPointerCapture(event.pointerId);
|
||||
} catch {
|
||||
document.body.classList.remove('tab-rail-resizing');
|
||||
if (shield) shield.hidden = true;
|
||||
this._releaseTabRailResize();
|
||||
}
|
||||
});
|
||||
handle.addEventListener('pointermove', (event) => {
|
||||
if (handle.hasPointerCapture?.(event.pointerId)) this._queueTabRailPointerWidth(event.clientX);
|
||||
});
|
||||
handle.addEventListener('pointerup', (event) => this._finishTabRailDrag(handle, event.pointerId));
|
||||
handle.addEventListener('pointercancel', (event) => this._finishTabRailDrag(handle, event.pointerId));
|
||||
handle.addEventListener('lostpointercapture', (event) => this._finishTabRailDrag(handle, event.pointerId));
|
||||
handle.addEventListener('keydown', (event) => this._onTabRailKeyDown(event));
|
||||
handle.addEventListener('dblclick', (event) => {
|
||||
event.preventDefault();
|
||||
this._claimTabRailResize();
|
||||
const preferred = window.CodemanTabRail?.DEFAULT_WIDTH || 256;
|
||||
const effective = this._setTabRailWidth(preferred);
|
||||
this._scheduleTabRailSettle(effective, preferred);
|
||||
});
|
||||
|
||||
let resizeTimer = null;
|
||||
window.addEventListener('resize', () => {
|
||||
clearTimeout(resizeTimer);
|
||||
resizeTimer = setTimeout(() => {
|
||||
this.applyTabOrientation?.();
|
||||
this.applyTabRailWidth({ persist: false });
|
||||
}, 100);
|
||||
});
|
||||
},
|
||||
|
||||
closeTabRailActionMenu(options = {}) {
|
||||
const menu = document.querySelector('.tab-rail-action-menu');
|
||||
const trigger = this._tabRailActionMenuTrigger;
|
||||
menu?.remove();
|
||||
if (this._tabRailActionMenuOutside) {
|
||||
document.removeEventListener('pointerdown', this._tabRailActionMenuOutside, true);
|
||||
this._tabRailActionMenuOutside = null;
|
||||
}
|
||||
if (this._tabRailActionMenuViewport) {
|
||||
window.removeEventListener('resize', this._tabRailActionMenuViewport);
|
||||
this._tabRailActionMenuViewport = null;
|
||||
}
|
||||
this._tabRailActionMenuTrigger = null;
|
||||
if (options.restoreFocus) trigger?.focus?.();
|
||||
},
|
||||
|
||||
openTabRailActionMenu(event, sessionId) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this.closeTabRailActionMenu();
|
||||
const trigger = event.currentTarget;
|
||||
const menu = document.createElement('div');
|
||||
menu.className = 'tab-rail-action-menu';
|
||||
menu.setAttribute('role', 'menu');
|
||||
menu.setAttribute('aria-label', 'Session actions');
|
||||
const settings = this.loadAppSettingsFromStorage();
|
||||
const actions = [
|
||||
{ label: 'Session options', run: () => this.openSessionOptions(sessionId) },
|
||||
...(settings.showTabDetachButton || this.detachedSessions?.has(sessionId)
|
||||
? [{ label: 'Open in a new window', run: () => this.detachSession(sessionId) }]
|
||||
: []),
|
||||
{ label: 'Close session', className: 'danger', run: () => this.requestCloseSession(sessionId) },
|
||||
];
|
||||
for (const action of actions) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.setAttribute('role', 'menuitem');
|
||||
button.textContent = action.label;
|
||||
if (action.className) button.className = action.className;
|
||||
button.addEventListener('click', () => {
|
||||
this.closeTabRailActionMenu();
|
||||
action.run();
|
||||
});
|
||||
menu.appendChild(button);
|
||||
}
|
||||
document.body.appendChild(menu);
|
||||
const rect = trigger.getBoundingClientRect();
|
||||
const menuRect = menu.getBoundingClientRect();
|
||||
menu.style.left = `${Math.max(8, Math.min(rect.right - menuRect.width, window.innerWidth - menuRect.width - 8))}px`;
|
||||
menu.style.top = `${Math.max(8, Math.min(rect.bottom + 4, window.innerHeight - menuRect.height - 8))}px`;
|
||||
this._tabRailActionMenuTrigger = trigger;
|
||||
this._tabRailActionMenuOutside = (pointerEvent) => {
|
||||
if (!menu.contains(pointerEvent.target) && pointerEvent.target !== trigger) this.closeTabRailActionMenu();
|
||||
};
|
||||
document.addEventListener('pointerdown', this._tabRailActionMenuOutside, true);
|
||||
this._tabRailActionMenuViewport = () => this.closeTabRailActionMenu();
|
||||
window.addEventListener('resize', this._tabRailActionMenuViewport, { once: true });
|
||||
menu.addEventListener('keydown', (keyEvent) => {
|
||||
const buttons = [...menu.querySelectorAll('button')];
|
||||
const index = buttons.indexOf(document.activeElement);
|
||||
if (keyEvent.key === 'Escape') {
|
||||
keyEvent.preventDefault();
|
||||
this.closeTabRailActionMenu({ restoreFocus: true });
|
||||
} else if (keyEvent.key === 'ArrowDown' || keyEvent.key === 'ArrowUp') {
|
||||
keyEvent.preventDefault();
|
||||
const direction = keyEvent.key === 'ArrowDown' ? 1 : -1;
|
||||
buttons[(index + direction + buttons.length) % buttons.length]?.focus();
|
||||
}
|
||||
});
|
||||
menu.querySelector('button')?.focus();
|
||||
},
|
||||
});
|
||||
@@ -901,6 +901,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
const MIN_ROWS = 10;
|
||||
|
||||
const throttledResize = () => {
|
||||
if (this._tabRailResizeOwnsObserver) return;
|
||||
// Trailing-edge debounce: ALL resize work (fit + clear + SIGWINCH) happens
|
||||
// once after the user stops resizing. During active resize, the terminal
|
||||
// stays at its old dimensions for up to 300ms.
|
||||
|
||||
@@ -26,3 +26,4 @@ export { registerAdminRoutes } from './admin-routes.js';
|
||||
export { registerWsRoutes } from './ws-routes.js';
|
||||
export { registerVoiceRoutes } from './voice-routes.js';
|
||||
export { registerWebviewRoutes, tryWebviewRefererFallback } from './webview-routes.js';
|
||||
export { registerTabLayoutRoutes } from './tab-layout-routes.js';
|
||||
|
||||
@@ -411,7 +411,7 @@ export function registerRalphRoutes(
|
||||
writeFileSync(promptPath, fullPrompt, 'utf-8');
|
||||
|
||||
// Register session
|
||||
ctx.addSession(session);
|
||||
await ctx.addSession(session);
|
||||
ctx.store.incrementSessionsCreated();
|
||||
ctx.persistSessionState(session);
|
||||
await ctx.setupSessionListeners(session);
|
||||
|
||||
@@ -48,7 +48,8 @@ import {
|
||||
SessionWaitQuerySchema,
|
||||
SessionWaitOutputQuerySchema,
|
||||
} from '../schemas.js';
|
||||
import { mergeSessionOrder } from '../../session-order.js';
|
||||
import { ownerLayoutKey } from '../../tab-layout-persistence.js';
|
||||
import { TabLayoutValidationError } from '../../tab-layout.js';
|
||||
import {
|
||||
sessionWaits,
|
||||
resolveWaitSignals,
|
||||
@@ -108,7 +109,7 @@ import {
|
||||
setHistoryIndexRefresher,
|
||||
setHistorySessionIndex,
|
||||
} from '../session-history-index.js';
|
||||
import type { SessionPort, EventPort, ConfigPort, InfraPort, AuthPort } from '../ports/index.js';
|
||||
import type { SessionPort, EventPort, ConfigPort, InfraPort, AuthPort, TabLayoutPort } from '../ports/index.js';
|
||||
import { RunSummaryTracker } from '../../run-summary.js';
|
||||
|
||||
import { MAX_INPUT_LENGTH, MAX_SESSION_NAME_LENGTH } from '../../config/terminal-limits.js';
|
||||
@@ -650,7 +651,7 @@ async function injectAgentSkill(casePath: string): Promise<void> {
|
||||
|
||||
export function registerSessionRoutes(
|
||||
app: FastifyInstance,
|
||||
ctx: SessionPort & EventPort & ConfigPort & InfraPort & AuthPort
|
||||
ctx: SessionPort & EventPort & ConfigPort & InfraPort & AuthPort & TabLayoutPort
|
||||
): void {
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Auth
|
||||
@@ -682,16 +683,23 @@ export function registerSessionRoutes(
|
||||
return (list as Array<{ owner?: string }>).filter((s) => canAccessOwned(user, s.owner));
|
||||
});
|
||||
|
||||
// ========== Session Tab Order (global sync, COD-131) ==========
|
||||
// ========== Legacy Session Tab Order (temporary synchronized compatibility bridge) ==========
|
||||
|
||||
app.put('/api/session-order', async (req): Promise<ApiResponse<{ order: string[] }>> => {
|
||||
const { order } = parseBody(SessionOrderUpdateSchema, req.body, 'Invalid session order');
|
||||
// Server is authoritative but never drops ids it knows about that the
|
||||
// pushing device hadn't loaded yet — those fall to the end (mergeSessionOrder).
|
||||
const merged = mergeSessionOrder(order, ctx.store.getSessionOrder());
|
||||
ctx.store.setSessionOrder(merged);
|
||||
ctx.broadcast(SseEvent.SessionOrderChanged, { order: merged });
|
||||
return { success: true, data: { order: merged } };
|
||||
app.put('/api/session-order', async (req, reply): Promise<ApiResponse<{ order: string[] }>> => {
|
||||
try {
|
||||
const { order } = parseBody(SessionOrderUpdateSchema, req.body, 'Invalid session order');
|
||||
const user = getAuthUser(req);
|
||||
const result = await ctx.tabLayouts.putLegacyOrder(
|
||||
{ owner: ownerLayoutKey(ownerFor(req)), isAdmin: user.role === 'admin' },
|
||||
order
|
||||
);
|
||||
return { success: true, data: { order: result.order } };
|
||||
} catch (error) {
|
||||
if (error instanceof TabLayoutValidationError) {
|
||||
return reply.code(400).send(createErrorResponse(ApiErrorCode.INVALID_INPUT, error.message));
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
// ========== Session Creation ==========
|
||||
@@ -951,7 +959,7 @@ export function registerSessionRoutes(
|
||||
parentSessionId: resolveParentSessionId(ctx, req, body.parentSessionId, owner),
|
||||
});
|
||||
|
||||
ctx.addSession(session);
|
||||
await ctx.addSession(session);
|
||||
ctx.store.incrementSessionsCreated();
|
||||
ctx.persistSessionState(session);
|
||||
await ctx.setupSessionListeners(session);
|
||||
@@ -2665,7 +2673,7 @@ export function registerSessionRoutes(
|
||||
allowedTools: runClaudeModeConfig.allowedTools,
|
||||
owner: runOwner,
|
||||
});
|
||||
ctx.addSession(session);
|
||||
await ctx.addSession(session);
|
||||
ctx.store.incrementSessionsCreated();
|
||||
ctx.persistSessionState(session);
|
||||
await ctx.setupSessionListeners(session);
|
||||
@@ -3102,7 +3110,7 @@ export function registerSessionRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
ctx.addSession(session);
|
||||
await ctx.addSession(session);
|
||||
ctx.store.incrementSessionsCreated();
|
||||
ctx.persistSessionState(session);
|
||||
await ctx.setupSessionListeners(session);
|
||||
|
||||
@@ -49,7 +49,7 @@ import {
|
||||
import { SseEvent } from '../sse-events.js';
|
||||
import { getInstallInfo, checkForUpdate, startUpdate, getUpdateStatusForApi } from '../self-update.js';
|
||||
import { getRepositoryStatus } from '../repo-status.js';
|
||||
import type { SessionPort, EventPort, ConfigPort, InfraPort, AuthPort } from '../ports/index.js';
|
||||
import type { SessionPort, EventPort, ConfigPort, InfraPort, AuthPort, TabLayoutPort } from '../ports/index.js';
|
||||
import { AUTH_COOKIE_NAME } from '../middleware/auth.js';
|
||||
import { QR_AUTH_FAILURE_MAX } from '../../config/tunnel-config.js';
|
||||
import { AUTH_SESSION_TTL_MS } from '../../config/auth-config.js';
|
||||
@@ -129,7 +129,7 @@ export function resolveSpanUrl(hostHeader: string | undefined, fallbackPort = '3
|
||||
|
||||
export function registerSystemRoutes(
|
||||
app: FastifyInstance,
|
||||
ctx: SessionPort & EventPort & ConfigPort & InfraPort & AuthPort
|
||||
ctx: SessionPort & EventPort & ConfigPort & InfraPort & AuthPort & TabLayoutPort
|
||||
): void {
|
||||
const windowStatesPath = dataPath('subagent-window-states.json');
|
||||
const parentMapPath = dataPath('subagent-parents.json');
|
||||
@@ -469,7 +469,9 @@ export function registerSystemRoutes(
|
||||
|
||||
app.post('/api/cleanup-state', async () => {
|
||||
const activeSessionIds = new Set(ctx.sessions.keys());
|
||||
const result = ctx.store.cleanupStaleSessions(activeSessionIds);
|
||||
const result = await ctx.tabLayouts.runStaleSessionCleanup(activeSessionIds, (ids) =>
|
||||
ctx.store.cleanupSessionsByIds(ids)
|
||||
);
|
||||
const lifecycleLog = getLifecycleLog();
|
||||
for (const s of result.cleaned) {
|
||||
lifecycleLog.log({ event: 'stale_cleaned', sessionId: s.id, name: s.name });
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/** @fileoverview Authenticated owner-scoped tab-layout read/write API. */
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { ownerLayoutKey } from '../../tab-layout-persistence.js';
|
||||
import { TabLayoutValidationError } from '../../tab-layout.js';
|
||||
import { ApiErrorCode, createErrorResponse } from '../../types.js';
|
||||
import { ownerFor } from '../route-helpers.js';
|
||||
import type { TabLayoutPort } from '../ports/index.js';
|
||||
|
||||
export const TAB_LAYOUT_BODY_LIMIT = 128 * 1024;
|
||||
|
||||
function parseWriteBody(body: unknown): { baseVersion: number; layout: unknown } {
|
||||
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
|
||||
throw new TabLayoutValidationError('body must be an object');
|
||||
}
|
||||
const keys = Object.keys(body);
|
||||
if (keys.length !== 2 || !Object.hasOwn(body, 'baseVersion') || !Object.hasOwn(body, 'layout')) {
|
||||
throw new TabLayoutValidationError('body must contain exactly baseVersion and layout');
|
||||
}
|
||||
const input = body as { baseVersion?: unknown; layout?: unknown };
|
||||
if (!Number.isSafeInteger(input.baseVersion) || (input.baseVersion as number) < 0 || input.layout === undefined) {
|
||||
throw new TabLayoutValidationError('baseVersion must be a non-negative safe integer and layout is required');
|
||||
}
|
||||
return { baseVersion: input.baseVersion as number, layout: input.layout };
|
||||
}
|
||||
|
||||
export function registerTabLayoutRoutes(app: FastifyInstance, ctx: TabLayoutPort): void {
|
||||
app.get('/api/tab-layout', async (req) => ({
|
||||
success: true,
|
||||
data: { layout: await ctx.tabLayouts.get(ownerLayoutKey(ownerFor(req))) },
|
||||
}));
|
||||
|
||||
app.put('/api/tab-layout', { bodyLimit: TAB_LAYOUT_BODY_LIMIT }, async (req, reply) => {
|
||||
try {
|
||||
const { baseVersion, layout } = parseWriteBody(req.body);
|
||||
const result = await ctx.tabLayouts.put(ownerLayoutKey(ownerFor(req)), layout, baseVersion);
|
||||
if (result.status === 'conflict') {
|
||||
return reply.code(409).send({
|
||||
...createErrorResponse(ApiErrorCode.CONFLICT, 'Tab layout version conflict'),
|
||||
data: { layout: result.layout },
|
||||
});
|
||||
}
|
||||
return { success: true, data: { layout: result.layout } };
|
||||
} catch (error) {
|
||||
if (error instanceof TabLayoutValidationError) {
|
||||
return reply.code(400).send(createErrorResponse(ApiErrorCode.INVALID_INPUT, error.message));
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -53,7 +53,8 @@ import { AUTH_COOKIE_NAME } from '../middleware/auth.js';
|
||||
import { canAccessOwned, getAuthUser, ownerFor, parseBody } from '../route-helpers.js';
|
||||
import { WebviewCreateSchema, WebviewProbeSchema, WebviewUpdateSchema } from '../schemas.js';
|
||||
import { SseEvent } from '../sse-events.js';
|
||||
import type { EventPort } from '../ports/index.js';
|
||||
import type { EventPort, TabLayoutPort } from '../ports/index.js';
|
||||
import { ownerLayoutKey } from '../../tab-layout-persistence.js';
|
||||
import {
|
||||
buildDownstreamResponseHeaders,
|
||||
buildProxyCorsHeaders,
|
||||
@@ -98,14 +99,14 @@ function withWebviews<T>(fn: (list: Webview[]) => Promise<T> | T): Promise<T> {
|
||||
return next;
|
||||
}
|
||||
|
||||
export function registerWebviewRoutes(app: FastifyInstance, ctx: EventPort): void {
|
||||
export function registerWebviewRoutes(app: FastifyInstance, ctx: EventPort & TabLayoutPort): void {
|
||||
registerCrudRoutes(app, ctx);
|
||||
registerProxyRoutes(app);
|
||||
}
|
||||
|
||||
// ───────────────────────────── CRUD ─────────────────────────────
|
||||
|
||||
function registerCrudRoutes(app: FastifyInstance, ctx: EventPort): void {
|
||||
function registerCrudRoutes(app: FastifyInstance, ctx: EventPort & TabLayoutPort): void {
|
||||
app.get('/api/webviews', async (req) => {
|
||||
const user = getAuthUser(req);
|
||||
const all = await readWebviews(configDir());
|
||||
@@ -145,6 +146,21 @@ function registerCrudRoutes(app: FastifyInstance, ctx: EventPort): void {
|
||||
.send(createErrorResponse(ApiErrorCode.INVALID_INPUT, `Webview limit reached (max ${MAX_WEBVIEWS})`));
|
||||
}
|
||||
|
||||
try {
|
||||
await ctx.tabLayouts.webviewCreated(ownerLayoutKey(created.owner));
|
||||
} catch (error) {
|
||||
// The saved webview and its layout ref are one logical creation. If the
|
||||
// layout rejects the new ref (for example at MAX_TAB_REFS), roll back the
|
||||
// already-written JSON record and publish neither creation event.
|
||||
await withWebviews(async (list) => {
|
||||
const index = list.findIndex((webview) => webview.id === created.id);
|
||||
if (index >= 0) {
|
||||
list.splice(index, 1);
|
||||
await writeWebviews(configDir(), list);
|
||||
}
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
ctx.broadcast(SseEvent.WebviewChanged, { action: 'created', id: created.id });
|
||||
return { success: true, data: created };
|
||||
});
|
||||
@@ -187,9 +203,19 @@ function registerCrudRoutes(app: FastifyInstance, ctx: EventPort): void {
|
||||
const index = list.findIndex((w) => w.id === id);
|
||||
if (index === -1) return 'not-found' as const;
|
||||
if (!canAccessOwned(user, list[index].owner)) return 'forbidden' as const;
|
||||
const removed = list[index];
|
||||
list.splice(index, 1);
|
||||
await writeWebviews(configDir(), list);
|
||||
return 'deleted' as const;
|
||||
try {
|
||||
await ctx.tabLayouts.webviewDeleted(ownerLayoutKey(removed.owner), id);
|
||||
} catch (error) {
|
||||
// Still inside withWebviews' mutex: restore the exact record at its
|
||||
// original position without overwriting any concurrent mutation.
|
||||
list.splice(index, 0, removed);
|
||||
await writeWebviews(configDir(), list);
|
||||
throw error;
|
||||
}
|
||||
return { status: 'deleted' as const, owner: removed.owner };
|
||||
});
|
||||
|
||||
if (result === 'not-found') {
|
||||
|
||||
@@ -995,6 +995,8 @@ export const SettingsUpdateSchema = z
|
||||
// CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK env var. Stripped before persisting.
|
||||
acknowledgeUnauthTunnel: z.boolean().optional(),
|
||||
tabTwoRows: z.boolean().optional(),
|
||||
tabOrientation: z.enum(['horizontal', 'vertical']).optional(),
|
||||
tabRailWidth: z.number().int().min(208).max(360).optional(),
|
||||
/**
|
||||
* Session list layout. Display key (per-device).
|
||||
* 'header' = horizontal tab strip
|
||||
@@ -1006,6 +1008,8 @@ export const SettingsUpdateSchema = z
|
||||
* on data-sidebar-detail. See applySessionListLayout() in app.js.
|
||||
*/
|
||||
sessionListLayout: z.enum(['header', 'sidebar', 'sidebar-rich']).optional(),
|
||||
/** Session-name text size in vertical navigation. Display key (per-device). */
|
||||
sessionSidebarFontSize: z.number().int().min(11).max(18).optional(),
|
||||
agentTeamsEnabled: z.boolean().optional(),
|
||||
/** Model for new Claude sessions (e.g. "claude-fable-5[1m]", "opus[1m]"); takes precedence over opusContext1mEnabled */
|
||||
claudeModel: z.string().max(50).optional(),
|
||||
|
||||
+88
-25
@@ -50,6 +50,8 @@ import { RespawnController, RespawnConfig } from '../respawn-controller.js';
|
||||
import type { TerminalMultiplexer } from '../mux-interface.js';
|
||||
import { createMultiplexer } from '../mux-factory.js';
|
||||
import { getStore } from '../state-store.js';
|
||||
import { TabLayoutService } from '../tab-layout-service.js';
|
||||
import { readWebviews } from '../webview-store.js';
|
||||
import { extractCompletionPhrase } from '../ralph-config.js';
|
||||
import { fileStreamManager } from '../file-stream-manager.js';
|
||||
import {
|
||||
@@ -81,6 +83,7 @@ import { applyWorkspaceHooks } from '../hooks-config.js';
|
||||
import { PushSubscriptionStore } from '../push-store.js';
|
||||
import webpush from 'web-push';
|
||||
import { SseStreamManager } from './sse-stream-manager.js';
|
||||
import { deriveTabLayoutSseHint } from './tab-layout-sse.js';
|
||||
import {
|
||||
type SessionListenerRefs,
|
||||
createSessionListeners,
|
||||
@@ -170,6 +173,7 @@ import {
|
||||
registerWsRoutes,
|
||||
registerVoiceRoutes,
|
||||
registerWebviewRoutes,
|
||||
registerTabLayoutRoutes,
|
||||
tryWebviewRefererFallback,
|
||||
} from './routes/index.js';
|
||||
import { CronService } from '../cron/cron-service.js';
|
||||
@@ -247,6 +251,7 @@ export class WebServer extends EventEmitter {
|
||||
private cronService!: CronService;
|
||||
private sse: SseStreamManager;
|
||||
private store = getStore();
|
||||
private tabLayouts!: TabLayoutService;
|
||||
private port: number;
|
||||
private host: string;
|
||||
private https: boolean;
|
||||
@@ -350,6 +355,17 @@ export class WebServer extends EventEmitter {
|
||||
},
|
||||
this.cleanup
|
||||
);
|
||||
this.tabLayouts = new TabLayoutService({
|
||||
store: this.store,
|
||||
sessions: this.sessions,
|
||||
readWebviews: () => readWebviews(getDataDir()),
|
||||
broadcast: this.broadcast.bind(this),
|
||||
broadcastSessionOrder: (change) => {
|
||||
this.cachedLightState = null;
|
||||
this.sse.broadcastSessionOrder(change);
|
||||
},
|
||||
});
|
||||
if (this.testMode) this.tabLayouts.markRestorationSkipped();
|
||||
|
||||
// Approvals Inbox → SSE. The singleton has no server reference; these
|
||||
// callbacks are its only way out. Broadcasts carry sessionId, so the
|
||||
@@ -595,6 +611,17 @@ export class WebServer extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/** Add a tentative session only after its owner layout accepts the creation. */
|
||||
private async registerSessionWithLayout(session: Session): Promise<void> {
|
||||
this.sessions.set(session.id, session);
|
||||
try {
|
||||
await this.tabLayouts.sessionCreated(session.owner ?? '@single');
|
||||
} catch (error) {
|
||||
this.sessions.delete(session.id);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a route context object satisfying all 5 port interfaces.
|
||||
* Single object with zero runtime cost — ISP enforced at the type level.
|
||||
@@ -605,9 +632,8 @@ export class WebServer extends EventEmitter {
|
||||
return {
|
||||
// SessionPort
|
||||
sessions: this.sessions as ReadonlyMap<string, Session>,
|
||||
addSession: (session: Session) => {
|
||||
this.sessions.set(session.id, session);
|
||||
},
|
||||
addSession: this.registerSessionWithLayout.bind(this),
|
||||
tabLayouts: this.tabLayouts,
|
||||
cleanupSession: this.cleanupSession.bind(this),
|
||||
setupSessionListeners: this.setupSessionListeners.bind(this),
|
||||
persistSessionState: this.persistSessionState.bind(this),
|
||||
@@ -991,6 +1017,7 @@ export class WebServer extends EventEmitter {
|
||||
registerAdminRoutes(this.app, ctx);
|
||||
registerOrchestratorRoutes(this.app, ctx);
|
||||
registerWebviewRoutes(this.app, ctx);
|
||||
registerTabLayoutRoutes(this.app, ctx);
|
||||
|
||||
// Cron: build the service from the same context, recompute
|
||||
// due times for any persisted jobs, then expose it to its routes.
|
||||
@@ -1154,8 +1181,19 @@ export class WebServer extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
private async _doCleanupSession(sessionId: string, killMux: boolean, reason?: string): Promise<void> {
|
||||
private async _doCleanupSession(
|
||||
sessionId: string,
|
||||
killMux: boolean,
|
||||
reason?: string,
|
||||
coordinateLayout = true
|
||||
): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
const pinned = session?.pinned === true || this.store.getSession(sessionId)?.pinned === true;
|
||||
if (coordinateLayout && session && killMux && !pinned) {
|
||||
return this.tabLayouts.runSessionDeletion([{ id: sessionId, owner: session.owner }], () =>
|
||||
this._doCleanupSession(sessionId, killMux, reason, false)
|
||||
);
|
||||
}
|
||||
const lifecycleLog = getLifecycleLog();
|
||||
lifecycleLog.log({
|
||||
event: killMux ? 'deleted' : 'detached',
|
||||
@@ -1860,7 +1898,7 @@ export class WebServer extends EventEmitter {
|
||||
// mode) so the flag-off path stays byte-identical.
|
||||
session = new Session({ workingDir: run.workingDir });
|
||||
}
|
||||
this.sessions.set(session.id, session);
|
||||
await this.registerSessionWithLayout(session);
|
||||
this.store.incrementSessionsCreated();
|
||||
this.persistSessionState(session);
|
||||
await this.setupSessionListeners(session);
|
||||
@@ -1990,9 +2028,11 @@ export class WebServer extends EventEmitter {
|
||||
* Called on startup and can be called via API endpoint.
|
||||
* @returns Number of sessions cleaned up
|
||||
*/
|
||||
private cleanupStaleSessions(): number {
|
||||
private async cleanupStaleSessions(): Promise<number> {
|
||||
const activeSessionIds = new Set(this.sessions.keys());
|
||||
const result = this.store.cleanupStaleSessions(activeSessionIds);
|
||||
const result = await this.tabLayouts.runStaleSessionCleanup(activeSessionIds, (ids) =>
|
||||
this.store.cleanupSessionsByIds(ids)
|
||||
);
|
||||
const lifecycleLog = getLifecycleLog();
|
||||
for (const s of result.cleaned) {
|
||||
lifecycleLog.log({ event: 'stale_cleaned', sessionId: s.id, name: s.name });
|
||||
@@ -2016,11 +2056,13 @@ export class WebServer extends EventEmitter {
|
||||
|
||||
/** Shallow-filter the light-state blob to what a non-admin user may see. */
|
||||
private filterLightStateForUser(base: Record<string, unknown>, username: string): Record<string, unknown> {
|
||||
const ownedIds = new Set<string>();
|
||||
const authoritativeOwners = new Map<string, string | undefined>();
|
||||
for (const [id, session] of Object.entries(this.store.getSessions())) authoritativeOwners.set(id, session.owner);
|
||||
for (const [id, session] of this.sessions) authoritativeOwners.set(id, session.owner);
|
||||
const ownedIds = new Set([...authoritativeOwners].filter(([, owner]) => owner === username).map(([id]) => id));
|
||||
const ownedClaudeIds = new Set<string>();
|
||||
for (const [id, s] of this.sessions) {
|
||||
for (const s of this.sessions.values()) {
|
||||
if (s.owner === username) {
|
||||
ownedIds.add(id);
|
||||
if (s.claudeSessionId) ownedClaudeIds.add(s.claudeSessionId);
|
||||
}
|
||||
}
|
||||
@@ -2038,6 +2080,9 @@ export class WebServer extends EventEmitter {
|
||||
const filtered: Record<string, unknown> = {
|
||||
...base,
|
||||
sessions,
|
||||
sessionOrder: Array.isArray(base.sessionOrder)
|
||||
? (base.sessionOrder as string[]).filter((id) => ownedIds.has(id))
|
||||
: [],
|
||||
respawnStatus,
|
||||
scheduledRuns: [], // legacy ScheduledRun has no owner yet → admin-only
|
||||
subagents: bySession(base.subagents, 'sessionId'),
|
||||
@@ -2074,6 +2119,7 @@ export class WebServer extends EventEmitter {
|
||||
const result = {
|
||||
version: APP_VERSION,
|
||||
sessions: this.getLightSessionsState(),
|
||||
sessionOrder: this.store.getSessionOrder(),
|
||||
scheduledRuns: Array.from(this.scheduledRuns.values()),
|
||||
respawnStatus,
|
||||
globalStats: this.store.getAggregateStats(activeSessionTokens),
|
||||
@@ -2082,7 +2128,6 @@ export class WebServer extends EventEmitter {
|
||||
timestamp: now,
|
||||
inputCjkForm: process.env.INPUT_CJK_FORM?.toUpperCase() === 'ON',
|
||||
planUsage: getLatestPlanUsage(), // last-known plan-usage telemetry, for the header chip on fresh load
|
||||
sessionOrder: this.store.getSessionOrder(), // global tab order, synced across devices (COD-131)
|
||||
};
|
||||
|
||||
this.cachedLightState = { data: result, timestamp: now };
|
||||
@@ -2121,6 +2166,11 @@ export class WebServer extends EventEmitter {
|
||||
) {
|
||||
return { adminOnly: true };
|
||||
}
|
||||
// Layout payloads contain only trusted routing metadata. Route them to that
|
||||
// exact owner plus admins, never by resolving a client-supplied ref.
|
||||
if (event.startsWith('tab:')) {
|
||||
return deriveTabLayoutSseHint(data);
|
||||
}
|
||||
// Session-scoped families: resolve the owner from the payload's session id.
|
||||
const SESSION_PREFIXES = [
|
||||
'session:',
|
||||
@@ -2366,26 +2416,26 @@ export class WebServer extends EventEmitter {
|
||||
// This prevents race conditions where clients connect before state is ready
|
||||
// CRITICAL: Skip in test mode to prevent tests from picking up user sessions
|
||||
if (!this.testMode) {
|
||||
await this.restoreMuxSessions();
|
||||
const restored = await this.restoreMuxSessions();
|
||||
await this.finalizeRestoredState(restored);
|
||||
|
||||
// Instance-scoped reaper: after restore, `docker rm -f` managed containers of
|
||||
// THIS instance whose case is gone from docker-cases.json (best-effort, never
|
||||
// touches another instance's containers). Runs after restore so containers
|
||||
// still referenced by a restored session are preserved.
|
||||
void import('../docker-hosts.js')
|
||||
.then(({ reapOrphanedDockerContainers }) => reapOrphanedDockerContainers(getDataDir(), CODEMAN_INSTANCE))
|
||||
.then((reaped) => {
|
||||
if (reaped.length > 0)
|
||||
console.log(`[Docker] reaped ${reaped.length} orphaned container(s): ${reaped.join(', ')}`);
|
||||
})
|
||||
.catch(() => {
|
||||
/* best-effort — daemon may be absent */
|
||||
});
|
||||
if (restored) {
|
||||
void import('../docker-hosts.js')
|
||||
.then(({ reapOrphanedDockerContainers }) => reapOrphanedDockerContainers(getDataDir(), CODEMAN_INSTANCE))
|
||||
.then((reaped) => {
|
||||
if (reaped.length > 0)
|
||||
console.log(`[Docker] reaped ${reaped.length} orphaned container(s): ${reaped.join(', ')}`);
|
||||
})
|
||||
.catch(() => {
|
||||
/* best-effort — daemon may be absent */
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up stale sessions from state file that don't have active mux sessions
|
||||
this.cleanupStaleSessions();
|
||||
|
||||
// Bound disk use under heavy paste-image traffic: delete `paste-*` files
|
||||
// older than 7 days from each live session's .claude-images/ hourly.
|
||||
if (!this.testMode) {
|
||||
@@ -2621,7 +2671,7 @@ export class WebServer extends EventEmitter {
|
||||
return false;
|
||||
}
|
||||
|
||||
private async restoreMuxSessions(): Promise<void> {
|
||||
private async restoreMuxSessions(): Promise<boolean> {
|
||||
try {
|
||||
// Reconcile mux sessions to find which ones are still alive (also discovers unknown ones)
|
||||
const { alive, dead, discovered } = await this.mux.reconcileSessions();
|
||||
@@ -2901,11 +2951,24 @@ export class WebServer extends EventEmitter {
|
||||
if (dead.length > 0) {
|
||||
console.log(`[Server] Cleaned up ${dead.length} dead mux session(s)`);
|
||||
}
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('[Server] Failed to restore mux sessions:', err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Unlock destructive reconciliation only after mux restoration fully succeeds. */
|
||||
private async finalizeRestoredState(restored: boolean): Promise<void> {
|
||||
if (!restored) {
|
||||
this.tabLayouts.markRestorationFailed();
|
||||
return;
|
||||
}
|
||||
this.tabLayouts.markRestorationComplete();
|
||||
await this.cleanupStaleSessions();
|
||||
await this.tabLayouts.reconcileAfterRestoration();
|
||||
}
|
||||
|
||||
/**
|
||||
* Install Codeman's hooks into the workspaces of the sessions just recovered.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
/** @fileoverview Trusted per-recipient payload selection for legacy session-order invalidations. */
|
||||
import type { SessionOrderProjectionChange } from '../tab-layout-service.js';
|
||||
import type { AuthUser } from '../types.js';
|
||||
|
||||
export function sessionOrderPayloadFor(
|
||||
identity: AuthUser | undefined,
|
||||
change: SessionOrderProjectionChange
|
||||
): { order: string[] } | undefined {
|
||||
if (!identity || identity.role === 'admin') {
|
||||
return change.globalChanged ? { order: [...change.globalOrder] } : undefined;
|
||||
}
|
||||
if (!Object.hasOwn(change.changedOwnerOrders, identity.username)) return undefined;
|
||||
const order = change.changedOwnerOrders[identity.username];
|
||||
return Array.isArray(order) ? { order: [...order] } : undefined;
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
* and referenced by the frontend (`SSE_EVENTS` in `constants.js`).
|
||||
* Both files MUST be kept in sync.
|
||||
*
|
||||
* 155 event constants organized by category:
|
||||
* 156 event constants organized by category:
|
||||
* - **Core** (1): init
|
||||
* - **Transport** (1): sse:heartbeat
|
||||
* - **Session lifecycle** (23): created, updated, deleted, terminal, idle, working, ...
|
||||
@@ -25,14 +25,14 @@
|
||||
* - **Plan orchestration** (5): started, progress, subagent, completed, cancelled
|
||||
* - **Tunnel** (7): started, stopped, progress, error, qrRotated, qrRegenerated, qrAuthUsed
|
||||
* - **Image / attachments** (2): image:detected, attachment:detected
|
||||
* - **Hooks** (8): idle_prompt, permission_prompt, elicitation_dialog, elicitation_complete, elicitation_response, stop, teammate_idle, task_completed
|
||||
* - **Hooks** (9): idle_prompt, permission_prompt, elicitation_dialog, elicitation_complete, elicitation_response, stop, teammate_idle, task_completed, suppressed
|
||||
* - **Approvals** (3): pending, updated, resolved (cross-session Approvals Inbox)
|
||||
* - **Orchestrator** (12): stateChanged, planProgress, planReady, phase*, verification, task*, completed, error
|
||||
* - **Clipboard** (1): write
|
||||
* - **Cases** (4): created, linked, deleted, order-changed
|
||||
* - **Docker cases** (8): exportComplete/Failed, importComplete, imageBuild*, containerRecreated
|
||||
* - **Multi-user** (3): admin:usersChanged, auth:passwordChangeRequired, session:orderChanged
|
||||
* - **Web tabs** (1): webview:changed
|
||||
* - **Web tabs** (2): webview:changed, tab:layoutChanged
|
||||
*
|
||||
* Naming convention: `domain:action` (e.g., `session:created`, `respawn:stateChanged`)
|
||||
*
|
||||
@@ -449,6 +449,8 @@ export const SessionOrderChanged = 'session:orderChanged' as const;
|
||||
* Payload: `{ action: 'created' | 'updated' | 'deleted', id }`. The client
|
||||
* re-fetches the list rather than patching from the payload. */
|
||||
export const WebviewChanged = 'webview:changed' as const;
|
||||
/** Owner-scoped layout invalidation. Payload contains only `{ owner, version }`. */
|
||||
export const TabLayoutChanged = 'tab:layoutChanged' as const;
|
||||
|
||||
// ─── Namespace Re-export ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -665,4 +667,5 @@ export const SseEvent = {
|
||||
|
||||
// Web tabs (dashboard URLs)
|
||||
WebviewChanged,
|
||||
TabLayoutChanged,
|
||||
} as const;
|
||||
|
||||
@@ -17,9 +17,11 @@
|
||||
|
||||
import type { FastifyReply } from 'fastify';
|
||||
import type { BackgroundTask } from '../session.js';
|
||||
import type { SessionOrderProjectionChange } from '../tab-layout-service.js';
|
||||
import type { AuthUser } from '../types.js';
|
||||
import { CleanupManager, StaleExpirationMap } from '../utils/index.js';
|
||||
import { SseEvent } from './sse-events.js';
|
||||
import { sessionOrderPayloadFor } from './session-order-sse.js';
|
||||
import {
|
||||
TERMINAL_BATCH_INTERVAL,
|
||||
TASK_UPDATE_BATCH_INTERVAL,
|
||||
@@ -34,6 +36,7 @@ import {
|
||||
// Appending SSE comment padding (ignored by EventSource) forces the proxy to flush.
|
||||
// Pre-computed once at startup to avoid repeated string allocation.
|
||||
const SSE_PADDING = ':' + 'p'.repeat(SSE_PADDING_SIZE) + '\n';
|
||||
const UNROUTED_TAB_LAYOUT = Symbol('unrouted-tab-layout');
|
||||
|
||||
/** Dependencies injected by WebServer — keeps SseStreamManager decoupled from session/respawn state. */
|
||||
interface SseStreamManagerDeps {
|
||||
@@ -77,6 +80,10 @@ export class SseStreamManager {
|
||||
private remoteSseClients: Set<FastifyReply> = new Set();
|
||||
/** Clients with backpressure — skip writes until 'drain' fires */
|
||||
private backpressuredClients: Set<FastifyReply> = new Set();
|
||||
/** Latest already recipient-filtered legacy order frame awaiting a client's drain. */
|
||||
private pendingSessionOrderFrames: Map<FastifyReply, string> = new Map();
|
||||
/** Latest owner-filtered tab-layout invalidation per affected owner awaiting a client's drain. */
|
||||
private pendingTabLayoutFrames: Map<FastifyReply, Map<string | symbol, string>> = new Map();
|
||||
|
||||
// ─── Tunnel State ───────────────────────────────────────
|
||||
/** Cached tunnel active state — updated on TunnelStarted/TunnelStopped to avoid getUrl() on every broadcast */
|
||||
@@ -144,10 +151,7 @@ export class SseStreamManager {
|
||||
// If a previous reply registered the same id (reconnect), drop the old one.
|
||||
const prev = this.sseClientsById.get(clientId);
|
||||
if (prev && prev !== reply) {
|
||||
this.sseClients.delete(prev);
|
||||
this.remoteSseClients.delete(prev);
|
||||
this.backpressuredClients.delete(prev);
|
||||
this.sseClientIdentity.delete(prev);
|
||||
this.removeClient(prev);
|
||||
}
|
||||
this.sseClientsById.set(clientId, reply);
|
||||
}
|
||||
@@ -157,6 +161,8 @@ export class SseStreamManager {
|
||||
this.sseClients.delete(reply);
|
||||
this.remoteSseClients.delete(reply);
|
||||
this.backpressuredClients.delete(reply);
|
||||
this.pendingSessionOrderFrames.delete(reply);
|
||||
this.pendingTabLayoutFrames.delete(reply);
|
||||
this.sseClientIdentity.delete(reply);
|
||||
// Clear any clientId mappings pointing at this reply
|
||||
for (const [id, r] of this.sseClientsById) {
|
||||
@@ -199,8 +205,7 @@ export class SseStreamManager {
|
||||
try {
|
||||
reply.raw.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
||||
} catch {
|
||||
this.sseClients.delete(reply);
|
||||
this.remoteSseClients.delete(reply);
|
||||
this.removeClient(reply);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,7 +215,44 @@ export class SseStreamManager {
|
||||
try {
|
||||
reply.raw.write(SSE_PADDING);
|
||||
} catch {
|
||||
/* client gone */
|
||||
this.removeClient(reply);
|
||||
}
|
||||
}
|
||||
|
||||
private markBackpressured(reply: FastifyReply): void {
|
||||
this.backpressuredClients.add(reply);
|
||||
reply.raw.once('drain', () => this.flushBackpressuredClient(reply));
|
||||
}
|
||||
|
||||
private flushBackpressuredClient(reply: FastifyReply): void {
|
||||
if (!this.sseClients.has(reply)) return;
|
||||
this.backpressuredClients.delete(reply);
|
||||
try {
|
||||
const drainPadding = this._isTunnelActive ? SSE_PADDING : '';
|
||||
const recovered = reply.raw.write(`event: ${SseEvent.SessionNeedsRefresh}\ndata: {}\n\n${drainPadding}`);
|
||||
if (!recovered) {
|
||||
this.markBackpressured(reply);
|
||||
return;
|
||||
}
|
||||
const pendingLayouts = this.pendingTabLayoutFrames.get(reply);
|
||||
if (pendingLayouts) {
|
||||
for (const [owner, pendingLayout] of pendingLayouts) {
|
||||
pendingLayouts.delete(owner);
|
||||
this.sendSSEPreformatted(reply, pendingLayout);
|
||||
if (!this.sseClients.has(reply)) return;
|
||||
if (this.backpressuredClients.has(reply)) {
|
||||
if (pendingLayouts.size === 0) this.pendingTabLayoutFrames.delete(reply);
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.pendingTabLayoutFrames.delete(reply);
|
||||
}
|
||||
const pendingOrder = this.pendingSessionOrderFrames.get(reply);
|
||||
if (!pendingOrder) return;
|
||||
this.pendingSessionOrderFrames.delete(reply);
|
||||
this.sendSSEPreformatted(reply, pendingOrder);
|
||||
} catch {
|
||||
this.removeClient(reply);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -224,24 +266,11 @@ export class SseStreamManager {
|
||||
try {
|
||||
const ok = reply.raw.write(message);
|
||||
if (!ok) {
|
||||
// Buffer is full — mark as backpressured, resume on drain
|
||||
this.backpressuredClients.add(reply);
|
||||
reply.raw.once('drain', () => {
|
||||
this.backpressuredClients.delete(reply);
|
||||
// Client may have missed terminal data during backpressure.
|
||||
// Tell it to reload the active session's buffer to recover.
|
||||
try {
|
||||
const drainPadding = this._isTunnelActive ? SSE_PADDING : '';
|
||||
reply.raw.write(`event: ${SseEvent.SessionNeedsRefresh}\ndata: {}\n\n${drainPadding}`);
|
||||
} catch {
|
||||
/* client gone */
|
||||
}
|
||||
});
|
||||
// Buffer is full — mark as backpressured, resume on drain.
|
||||
this.markBackpressured(reply);
|
||||
}
|
||||
} catch {
|
||||
this.sseClients.delete(reply);
|
||||
this.remoteSseClients.delete(reply);
|
||||
this.backpressuredClients.delete(reply);
|
||||
this.removeClient(reply);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +305,36 @@ export class SseStreamManager {
|
||||
for (const [client] of this.sseClients) {
|
||||
// Multi-user ownership routing (no-op for identity-less single-user clients).
|
||||
if (!this.canDeliver(client, hint)) continue;
|
||||
if (event === SseEvent.TabLayoutChanged && this.backpressuredClients.has(client)) {
|
||||
const owner =
|
||||
data !== null &&
|
||||
typeof data === 'object' &&
|
||||
Object.hasOwn(data, 'owner') &&
|
||||
typeof (data as { owner?: unknown }).owner === 'string'
|
||||
? (data as { owner: string }).owner
|
||||
: (hint?.username ?? hint?.owner ?? UNROUTED_TAB_LAYOUT);
|
||||
let pending = this.pendingTabLayoutFrames.get(client);
|
||||
if (!pending) {
|
||||
pending = new Map();
|
||||
this.pendingTabLayoutFrames.set(client, pending);
|
||||
}
|
||||
pending.set(owner, message);
|
||||
continue;
|
||||
}
|
||||
this.sendSSEPreformatted(client, message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Dispatch the legacy order projection selected from each trusted client identity. */
|
||||
broadcastSessionOrder(change: SessionOrderProjectionChange): void {
|
||||
for (const [client] of this.sseClients) {
|
||||
const payload = sessionOrderPayloadFor(this.sseClientIdentity.get(client), change);
|
||||
if (!payload) continue;
|
||||
const message = `event: ${SseEvent.SessionOrderChanged}\ndata: ${JSON.stringify(payload)}\n\n`;
|
||||
if (this.backpressuredClients.has(client)) {
|
||||
this.pendingSessionOrderFrames.set(client, message);
|
||||
continue;
|
||||
}
|
||||
this.sendSSEPreformatted(client, message);
|
||||
}
|
||||
}
|
||||
@@ -504,9 +563,7 @@ export class SseStreamManager {
|
||||
|
||||
// Remove dead clients
|
||||
for (const client of deadClients) {
|
||||
this.sseClients.delete(client);
|
||||
this.remoteSseClients.delete(client);
|
||||
this.backpressuredClients.delete(client);
|
||||
this.removeClient(client);
|
||||
}
|
||||
|
||||
if (deadClients.length > 0) {
|
||||
@@ -553,6 +610,8 @@ export class SseStreamManager {
|
||||
this.sseClients.clear();
|
||||
this.remoteSseClients.clear();
|
||||
this.backpressuredClients.clear();
|
||||
this.pendingSessionOrderFrames.clear();
|
||||
this.pendingTabLayoutFrames.clear();
|
||||
|
||||
// Clear per-session batch timers
|
||||
for (const timer of this.terminalBatchTimers.values()) {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
/** @fileoverview Trusted owner routing metadata for tab-layout invalidations. */
|
||||
import type { SseRoutingHint } from './sse-stream-manager.js';
|
||||
|
||||
export function deriveTabLayoutSseHint(data: unknown): SseRoutingHint {
|
||||
return { username: (data as { owner?: string }).owner, sessionScoped: true };
|
||||
}
|
||||
Reference in New Issue
Block a user