Merge pull request #466 from irisitymichaelgrundberg/feat/pane-exit-reporting

feat(tmux): report that a pane's agent has exited (#446, part 1)
This commit is contained in:
Codeman maintainer
2026-09-23 11:32:02 +02:00
15 changed files with 1799 additions and 33 deletions
+61 -1
View File
@@ -325,6 +325,55 @@ function parseSessionPrefix(name) {
return null;
}
// ═══════════════════════════════════════════════════════════════
// Exited-agent tab label (Ark0N/Codeman#446)
// ═══════════════════════════════════════════════════════════════
// The server publishes session.paneExit when the agent inside a local tmux
// pane has exited while remain-on-exit kept the pane. The field is tri-state
// and its third state is absence, which means Codeman does not know — that
// renders as nothing here and must never read as alive.
//
// status and signal are each optional, because tmux can know the pane died
// without reporting how (a SIGKILLed pane on tmux 3.2a reports neither). So an
// absent status shows a bare "exited" rather than "exited (0)": a clean exit
// and an unexplained one must not look the same.
function paneExitLabel(paneExit) {
if (!paneExit || typeof paneExit !== 'object') return '';
if (typeof paneExit.signal === 'number' && paneExit.signal > 0) return `exited (signal ${paneExit.signal})`;
if (typeof paneExit.status === 'number') return `exited (${paneExit.status})`;
return 'exited';
}
// Add, update or remove one tab's exited-agent badge in place. Separate from
// the render loop so it can be exercised directly: this is the only path a
// session going live-to-exited ever takes, since that transition adds and
// removes no tab and so never reaches the full rebuild.
function applyPaneExitBadge(tab, paneExit) {
const label = paneExitLabel(paneExit);
const existing = tab.querySelector('.tab-exited-badge');
// Quiets the status dot too. That dot reports `status`, which stays `idle` or
// `busy` for an exited pane by design, so without this a green or pulsing dot
// sits next to a badge saying the agent is gone.
tab.classList.toggle('tab-agent-exited', !!label);
if (!label) {
existing?.remove();
return;
}
if (!existing) {
const badge = document.createElement('span');
badge.className = 'tab-exited-badge';
// Generated status text, like the status pills: it carries data-i18n-skip
// rather than a dictionary entry. Without it the translator would rewrite
// the badge and the next render pass would rewrite it back, because the
// comparison below is against the English string.
badge.setAttribute('data-i18n-skip', '');
badge.textContent = label;
tab.querySelector('.tab-name')?.insertAdjacentElement('afterend', badge);
return;
}
if (existing.textContent !== label) existing.textContent = label;
}
const DEFAULT_SHORTCUTS = [
{
id: 'show-shortcuts',
@@ -4968,6 +5017,11 @@ class CodemanApp {
statusEl.className = `tab-status ${status}`;
}
// The exited-agent badge (Ark0N/Codeman#446). A session going from live
// to exited changes no tab count, so the full rebuild below never runs
// for it and this is the only path that ever draws the badge.
applyPaneExitBadge(tab, session.paneExit);
// Rich sidebar meta ("created 3d ago · working 12m" + pill). The stamps
// themselves move on _tickSidebarRichTimes(); this is here for the parts
// a tick cannot see — the state flipping, and with it the pill, the row
@@ -5268,10 +5322,15 @@ class CodemanApp {
? ` data-tab-state="${richRow.state}" data-tab-meta-sig="${richRow.state}:${richRow.since ? richRow.since.at : 0}:${richRow.createdAt}"`
: '';
// '' whenever the server said nothing about this pane's agent, which covers
// a running pane and every session shape the field never applies to
// (direct-PTY, remote SSH, docker). See paneExitLabel().
const paneExitBadge = paneExitLabel(session.paneExit);
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">&#x2699;</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">&#x29C9;</span><span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession(${escapeHtml(JSON.stringify(id))})" title="Close session" aria-label="Close session" tabindex="0">&times;</span><button type="button" class="tab-more" onclick="event.stopPropagation(); app.openTabRailActionMenu(event, ${escapeHtml(JSON.stringify(id))})" title="Session actions" aria-label="Session actions">&#x22EF;</button></span>`;
parts.push(`<div class="session-tab ${isActive ? 'active' : ''}${alertClass}${richClass}${loadState ? ' tab-loading' : ''}${this.hasTabDetachOverride(id) ? ' tab-show-detach' : ''}"${richData}${railOrderStyle} 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)}"` : ''}>
parts.push(`<div class="session-tab ${isActive ? 'active' : ''}${alertClass}${richClass}${paneExitBadge ? ' tab-agent-exited' : ''}${loadState ? ' tab-loading' : ''}${this.hasTabDetachOverride(id) ? ' tab-show-detach' : ''}"${richData}${railOrderStyle} 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>' : ''}
<span class="tab-status ${status}" aria-hidden="true"></span>
@@ -5279,6 +5338,7 @@ class CodemanApp {
<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>' : mode === 'deepseek' ? '<span class="tab-mode deepseek" aria-hidden="true">ds</span>' : mode === 'omp' ? '<span class="tab-mode omp" aria-hidden="true">om</span>' : ''}
<span class="tab-name" data-session-id="${id}" data-full-name="${escapeHtml(name)}">${tabLabel}</span>
${paneExitBadge ? `<span class="tab-exited-badge" data-i18n-skip>${escapeHtml(paneExitBadge)}</span>` : ''}
${inlineSessionActions ? tabActionsHtml : ''}
<span class="tab-detached-badge" aria-hidden="true">detached</span>
</span>
+16
View File
@@ -694,6 +694,22 @@ html.mobile-init .file-browser-panel {
display: none;
}
/* The exited-agent mute, a third time, for the phone (Ark0N/Codeman#446).
The rule above enlarges the working dot and gives it a green glow with
!important, and `status` deliberately stays `busy` for a pane whose agent
died mid-turn — so without this a phone renders a 9px grey dot still
wearing the green halo, beside a badge reading "exited". Measured; the
desktop rules cannot reach it, since they declare no box-shadow and lose
to !important anyway. !important here for the reason the glow needs it:
the skin block in styles.css outranks any plain class rule in this file.
⚠ The alert classes and the error state are excluded exactly as they are
on desktop — a colour that means "this needs you" outranks "it exited". */
.session-tab.tab-agent-exited:not(.tab-alert-action):not(.tab-alert-idle) .tab-status:not(.error) {
background: var(--text-muted) !important;
box-shadow: none !important;
opacity: 0.5;
}
/* Truncate tab names more aggressively on mobile */
.session-tab .tab-name {
max-width: 50px;
+65
View File
@@ -2433,6 +2433,51 @@ html[data-tab-orientation='vertical'] .tab-rail .session-tab .tab-name-prefix {
display: inline-flex;
}
/* The agent inside the pane has exited (Ark0N/Codeman#446). Unlike the badge
above this one carries text the server computed, so it is added and removed
by the renderer rather than toggled by a class. */
.session-tab .tab-exited-badge {
display: inline-flex;
align-items: center;
flex: 0 0 auto;
font-size: 0.55rem;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
padding: 1px 4px;
margin-left: 4px;
border-radius: 3px;
white-space: nowrap;
background: rgba(248, 113, 113, 0.16);
color: var(--danger);
}
/* An exited agent quiets the status dot, which otherwise reports `status` and
so stays green (or pulses, for a session the exit caught mid-turn) beside a
badge saying the agent is gone. `status` itself is deliberately untouched —
`error` is the PTY-exit breaker's value and makes the browser offer a restart
— so this is a rendering rule only, and it matches `.tab-status.ended`.
⚠ Three states are excluded BY HAND rather than by cascade, the same way the
rich-rail dot rules below do it: a dot turning red or yellow because a
session is blocked on a human outranks "the agent exited", and this selector
is specific enough (0,5,0) to have beaten those (0,3,0) rules otherwise. The
third is `.tab-status.error` (0,2,0), which is the PTY-exit breaker's state
and the one the browser answers with a "restart it?" confirm — the same
argument that protects the two alert classes, and it reaches the dot rather
than the tab, which is why the `:not()` sits on `.tab-status` here and on
`.session-tab` there. The spinner ring is a pseudo-element the skin blocks
cannot reach, so it needs hiding explicitly rather than by unsetting the
animation. */
.session-tab.tab-agent-exited:not(.tab-alert-action):not(.tab-alert-idle) .tab-status:not(.error) {
background: var(--text-muted);
opacity: 0.5;
animation: none;
}
.session-tab.tab-agent-exited:not(.tab-alert-action):not(.tab-alert-idle) .tab-status:not(.error)::after {
display: none;
}
/* ===== Tab action icons: active tab only =================================
All three per-tab icons live in a .tab-actions wrapper (in flow; it adds
no width of its own while the children keep the width:0 collapse above).
@@ -18477,6 +18522,26 @@ html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail
border-width: 2px;
}
/* The exited-agent mute, again, for the rich rail (Ark0N/Codeman#446).
The strip's rule is (0,5,0) and the three state rules above are (0,9,1), so
on this rail an exited session kept a full green dot and the working halo
beside a badge reading "exited" — measured, the contradiction the mute
exists to remove. This twin matches their (0,9,1) exactly and therefore MUST
stay below them in source order; moving it above silently restores the green
dot. It also clears the halo, which is a box-shadow the strip's rule never
had to think about.
⚠ The alert exclusions are repeated by hand for the same reason they are on
the rules above: a dot turning red or yellow because a session is blocked on
a human outranks "the agent exited". */
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact)
.tab-rail
.session-tab.tab-agent-exited:not(.tab-alert-action):not(.tab-alert-idle)
.tab-status:not(.error) {
background: var(--text-muted);
opacity: 0.5;
box-shadow: none;
}
/* Card accents: the same three colours as every other session surface, and the
same two blinks the home rail runs. `tab-alert-*` draws its own ::before ring
on top of this for the sessions that are genuinely blocked on a human; these
+9
View File
@@ -1583,6 +1583,12 @@ export function registerSessionRoutes(
name: session.name,
mode: session.mode,
});
// Persist, not just broadcast. Starting a command in the pane changes
// `pid` and retracts any `paneExit` (Ark0N/Codeman#446), and the pane-exit
// watcher cannot write that retraction to disk for us: its next tick finds
// the in-memory field already cleared, reports no change and persists
// nothing, so `state.json` would keep saying the agent had exited.
ctx.persistSessionState(session);
ctx.broadcast(SseEvent.SessionInteractive, { id });
ctx.broadcast(SseEvent.SessionUpdated, { session: ctx.getSessionStateWithRespawn(session) });
@@ -1612,6 +1618,9 @@ export function registerSessionRoutes(
name: session.name,
mode: 'shell',
});
// Persist for the same reason /interactive does: a started pane retracts
// `paneExit`, and the watcher's next tick cannot write that retraction.
ctx.persistSessionState(session);
ctx.broadcast(SseEvent.SessionInteractive, { id, mode: 'shell' });
ctx.broadcast(SseEvent.SessionUpdated, { session: ctx.getSessionStateWithRespawn(session) });
return {};
+53
View File
@@ -463,6 +463,11 @@ export class WebServer extends EventEmitter {
this.mux.on('statsUpdated', (sessions) => {
this.broadcast(SseEvent.MuxStatsUpdated, sessions);
});
// Ark0N/Codeman#446 — a pane read finished. Internal only: the field reaches
// the browser on `session:updated`, and no SSE event was added for it.
this.mux.on('paneExitsUpdated', () => {
this.applyPaneExits();
});
// COD-108 — remote-session auto-reconnect. The TmuxManager watcher detects a
// dead remote pane and emits `remoteSessionDropped`; the session owner (here)
@@ -2455,6 +2460,36 @@ export class WebServer extends EventEmitter {
this.sse.broadcastSessionStateDebounced(sessionId);
}
/**
* Fold the latest pane readings into the sessions they belong to
* (Ark0N/Codeman#446). A reading that changes a session's answer persists the
* record and pushes a `session:updated`, which is how the tab learns; a read
* that repeats what the last one said costs nothing.
*
* The answer is pulled per session from the mux rather than taken off a
* broadcast payload. The mux reports the RAW pane reading, which for a remote
* or docker session is the death of an ssh client or a `docker exec` rather
* than of the agent, so it must not travel to a browser at all;
* `Session.setPaneExit()` is where that scoping is applied.
*
* Nothing here touches `status` or `pid`. `status: 'error'` belongs to the
* PTY-exit breaker and makes the browser offer a restart, and a null `pid` is
* what makes the browser re-attach and launch a fresh CLI.
*/
private applyPaneExits(): void {
const getPaneExit = this.mux.getPaneExit?.bind(this.mux);
if (!getPaneExit) return;
for (const session of this.sessions.values()) {
const muxName = session.muxName;
// No pane, so nothing to report — and `setPaneExit()` would force UNKNOWN
// for such a session anyway.
if (!muxName) continue;
if (!session.setPaneExit(getPaneExit(muxName))) continue;
this.persistSessionState(session);
this.broadcastSessionStateDebounced(session.id);
}
}
// ========== Web Push ==========
/** Map SSE event names to push notification payloads */
@@ -3336,6 +3371,15 @@ export class WebServer extends EventEmitter {
// the conversation the CLI was on when the server stopped, which is
// what a re-attach must point the viewer at instead of the launch id.
claudeSessionChain: savedState?.claudeSessionChain,
// What the previous run last observed of this pane's agent. Carried
// over so the first persist after boot does not blank a record that
// says the agent exited; the attach below drops it, and the
// pane-exit watcher's own tick replaces it with a first-hand
// reading (not the stats collector — see `startPaneExitWatcher`).
paneExit: savedState?.paneExit,
// A record rebuilt from the socket has no provenance, so its
// apparent locality is a guess (see `MuxSession.discovered`).
discoveredMuxSession: muxSession.discovered,
// The pane's last output, previous run's value. Without it every
// restart restamped all sessions "now" (constructor + the attach
// repaint within the same second), flattening the home screens'
@@ -3545,6 +3589,15 @@ export class WebServer extends EventEmitter {
(this.mux as { startMouseModeSync: (ms?: number) => void }).startMouseModeSync();
}
// Ark0N/Codeman#446 — poll every pane for an exited agent. Always start,
// even with no sessions, for the same reason as the two watchers around
// it: sessions arrive later. Deliberately NOT folded into the stats
// collector above, which the browser arms and disarms with the Monitor
// panel and which boot skips entirely when nothing was recovered.
if ('startPaneExitWatcher' in this.mux) {
(this.mux as { startPaneExitWatcher: (ms?: number) => void }).startPaneExitWatcher();
}
// COD-108 — start the remote-session auto-reconnect watcher (tmux only).
// Always-on (D3) with a `remoteAutoReconnect` kill-switch the watcher reads
// each tick. Start even with no sessions — remote sessions may arrive later.