Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

feat(coding-agent): roster subscription push consumed by the agents view and subagents bar (#1900)

Sebastian Müller1d2e91d3b3c1
diff --git a/packages/coding-agent/.changes/eng-5794-agent-roster-push.md b/packages/coding-agent/.changes/eng-5794-agent-roster-push.md
new file mode 100644
index 0000000000..7310f5bed6
--- /dev/null
+++ b/packages/coding-agent/.changes/eng-5794-agent-roster-push.md
@@ -0,0 +1,2 @@
+- Replaced the agents view's 1-second polling with a subscription to the daemon's agent roster: the supervisor pushes coalesced roster updates, scope transitions reuse one shared connection and store without refetching, and rows render the ledger's statuses and lifecycle labels (queued, recovering, failed, last-heard-from staleness). Removed the poll path: the agents view now requires the daemon's agent_roster capability and fails fast against a daemon lacking it (unreachable in practice, since launch replaces daemons on any schema mismatch); the chat subagents bar degrades to snapshot-driven counts.
+- Loaded the saved-session catalog only when a search query needs deep message text, once per view, instead of on every navigation.
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index c0e036cf1d..922136b768 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -10136,6 +10136,11 @@ export class AgentSession {
};
}
+ private _isUnboundTerminalRlmChildRun(run: RlmChildRun): boolean {
+ if (run.session !== undefined || this._rlmChildSessions.has(run.id)) return false;
+ return run.status === "done" || run.status === "error" || run.status === "cancelled";
+ }
+
/** Live recursive child roster from lifecycle state, including nested work under retained parents. */
getRlmChildSnapshots(): RlmChildAgentSnapshot[] {
const snapshots: RlmChildAgentSnapshot[] = [];
@@ -10143,7 +10148,10 @@ export class AgentSession {
const traversed = new Set<string>();
for (const run of this._activeRlmChildRuns.values()) {
const hidden =
- run.detachedDeletion || this._deletingRlmChildren.has(run.id) || this._deletedRlmChildIds.has(run.id);
+ run.detachedDeletion ||
+ this._deletingRlmChildren.has(run.id) ||
+ this._deletedRlmChildIds.has(run.id) ||
+ this._isUnboundTerminalRlmChildRun(run);
const child = run.session;
if (!hidden) {
snapshots.push(this._rlmChildSnapshotForRun(run));
@@ -10664,7 +10672,15 @@ export class AgentSession {
}
run.durationMs = Date.now() - startedAt;
run.activity = undefined;
- emitChildUpdate();
+ if (run.status === "error" && childSession === undefined) {
+ // A pre-bind failure leaves no row: "cancelled" is the wire's removal signal.
+ this._emit({
+ type: "rlm_child_update",
+ child: { ...this._rlmChildSnapshotForRun(run), status: "cancelled" },
+ });
+ } else {
+ emitChildUpdate();
+ }
if (!run.detachedDeletion && !run.suppressTerminalNotice) {
if (run.status === "error") {
await deliverTerminalMessageToParent(
diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
index ef48e75645..4f1f0139dd 100644
--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
@@ -20,6 +20,7 @@ import type { RefinementResult } from "../../core/refinement/index.js";
import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";
import { SessionAlreadyActiveError } from "../../core/session-lease.js";
import type { SessionStats } from "../../core/session-stats.js";
+import { AgentsViewRosterStore, STALE_ROSTER_DAEMON_MESSAGE } from "../agents-view/roster-store.js";
import {
DaemonCapabilityUnavailableError,
type DaemonClient,
@@ -239,6 +240,7 @@ export class DaemonAgentConnection implements AgentConnection {
private readonly pendingReattachActiveSessionIds = new Set<string>();
private readonly snapshotRecoveryPromises = new Map<string, Promise<void>>();
private readonly ignoredSnapshotIds = new Set<string>();
+ private rosterStore: AgentsViewRosterStore | undefined;
private reconnectPromise?: Promise<void>;
private readonly definitiveRequestErrors = new WeakSet<Error>();
private disposing = false;
@@ -377,6 +379,25 @@ export class DaemonAgentConnection implements AgentConnection {
this.latestSnapshot = undefined;
this.latestSnapshotIsFresh = false;
}
+ // The roster bar is an accessory: its subscribe failure must never fail an
+ // otherwise-recovered session. The bar degrades; the next reconnect or rebind
+ // re-attaches through this same seam.
+ if (this.rosterStore) await this.rosterStore.attach(this.client).catch(() => undefined);
+ }
+
+ async subscribeAgentRoster(
+ listener: () => void,
+ ): Promise<{ summaries(): SessionSummary[]; dispose(): Promise<void> }> {
+ this.rosterStore ??= new AgentsViewRosterStore();
+ const store = this.rosterStore;
+ if (!(await store.attach(this.client))) {
+ throw new Error(STALE_ROSTER_DAEMON_MESSAGE);
+ }
+ const unsubscribe = store.onUpdate(listener);
+ return {
+ summaries: () => store.summaries(),
+ dispose: async () => unsubscribe(),
+ };
}
subscribe(listener: AgentConnectionEventListener): () => void {
@@ -1447,6 +1468,8 @@ export class DaemonAgentConnection implements AgentConnection {
this.disposed = true;
this.updateRestartPending = false;
await Promise.allSettled([...this.activeSideQuestionIds].map((id) => this.abortSideQuestion(id)));
+ await this.rosterStore?.dispose().catch(() => undefined);
+ this.rosterStore = undefined;
this.unsubscribeDaemonMessages();
this.unsubscribeDaemonClose();
if (this.options.ownedSession) {
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index bf81de68ad..67408cd347 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -27,6 +27,7 @@ import type {
} from "../../core/session-action-store.js";
import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";
import type { SessionStats } from "../../core/session-stats.js";
+import type { SessionSummary } from "../daemon/daemon-session-list.js";
/**
* Client-side interaction boundary consumed by InteractiveMode.
@@ -692,6 +693,7 @@ export interface AgentConnection {
getToolDefinition(name: string): Promise<AgentConnectionToolDefinition | undefined>;
setSessionEntryLabel(entryId: string, label: string | undefined): Promise<void>;
respondToExtensionUiRequest(requestId: string, response: AgentConnectionExtensionUiResponse): Promise<void>;
+ subscribeAgentRoster?(listener: () => void): Promise<{ summaries(): SessionSummary[]; dispose(): Promise<void> }>;
supportsAcpMcpServers?(): boolean;
replaceAcpMcpServers?(servers: readonly AcpMcpServerConfig[], ownerId: string): Promise<void>;
releaseAcpMcpServers?(ownerId: string, serverNames: readonly string[]): Promise<void>;
diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
index ba650be09b..c474f12275 100644
--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
@@ -96,9 +96,9 @@ import {
type UnifiedSessionIndex,
type UnifiedSessionRecord,
} from "./agents-view-state.js";
+import { AgentsViewRosterStore, STALE_ROSTER_DAEMON_MESSAGE } from "./roster-store.js";
import { matchesSearchText } from "./session-view-search.js";
-const POLL_INTERVAL_MS = 1000;
const HEARTBEAT_POLL_INTERVAL_MS = 15000;
const RECONNECT_TIMEOUT_MS = 120000;
const RECONNECT_RETRY_MS = 1000;
@@ -165,8 +165,11 @@ export type AgentsViewPersistentState = {
startupNotices?: StartupNotices;
startupNoticesPromise?: Promise<StartupNotices>;
query?: string;
+ rosterClient?: DaemonClient;
+ rosterStore?: AgentsViewRosterStore;
savedSessions?: AgentConnectionSavedSessionInfo[];
lastSuccessfulSavedSessions?: AgentConnectionSavedSessionInfo[];
+ savedCatalogLoaded?: boolean;
lastSuccessfulLiveSummaries?: SessionSummary[];
savedCatalogGeneration?: number;
heartbeats?: AgentConnectionHeartbeat[];
@@ -419,6 +422,22 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): Promise
const persistentState = createInitialAgentsViewPersistentState(options);
const promptStashStore = options.promptStashStore ?? new ClientPromptStashStore();
+ try {
+ await runAgentsViewLoop(options, persistentState, promptStashStore);
+ } finally {
+ // Close first: the supervisor drops the subscription with the socket.
+ persistentState.rosterClient?.close();
+ await persistentState.rosterStore?.dispose();
+ persistentState.rosterStore = undefined;
+ persistentState.rosterClient = undefined;
+ }
+}
+
+async function runAgentsViewLoop(
+ options: AgentsViewModeOptions,
+ persistentState: AgentsViewPersistentState,
+ promptStashStore: ClientPromptStashStore,
+): Promise<void> {
while (true) {
const view = new AgentsViewMode(options, persistentState);
const viewResult = await view.run();
@@ -629,7 +648,6 @@ export class AgentsViewMode implements Component, Focusable {
private reconnectTimedOut = false;
private daemonShutdownReceived = false;
private resolveRun: ((result: AgentsViewRunResult) => void) | undefined;
- private pollTimer: NodeJS.Timeout | undefined;
private heartbeatPollTimer: NodeJS.Timeout | undefined;
private animationTimer: NodeJS.Timeout | undefined;
private ctrlCExitHintExpiresAt = 0;
@@ -648,13 +666,9 @@ export class AgentsViewMode implements Component, Focusable {
private scopedRecords: UnifiedSessionRecord[] = [];
private scopeKey: AgentsViewScopeKey | undefined;
private scopeRootSummary: SessionSummary | undefined;
- private liveCatalogReady = false;
private savedCatalogReady = false;
private savedCatalogGeneration = 0;
- private liveCatalogGeneration = 0;
private heartbeatCatalogGeneration = 0;
- private liveCatalogPollPromise: Promise<void> | undefined;
- private liveCatalogRefreshPending = false;
private savedCatalogRefreshPending = false;
private expandedSubagentParents = new Set<string>();
// Agent row identities whose full spawn program is currently shown.
@@ -679,6 +693,9 @@ export class AgentsViewMode implements Component, Focusable {
private renameTarget: { activeSessionId?: string; sessionFile?: string; summary: SessionSummary } | undefined;
private actionModeSearchQuery: string | undefined;
private readonly inactiveAgentIdentities = new Set<string>();
+ private rosterStore: AgentsViewRosterStore | undefined;
+ private unsubscribeRosterUpdate: (() => void) | undefined;
+ private savedSearchFetchStarted = false;
private statusMessage: string | undefined;
private statusMessageTone: "muted" | "error" | "warning" = "muted";
private statusMessageSticky = false;
@@ -704,7 +721,7 @@ export class AgentsViewMode implements Component, Focusable {
this.lastListedSummaries = persistentState.lastSuccessfulLiveSummaries ?? [];
this.savedSessions = persistentState.savedSessions ?? [];
this.lastSuccessfulSavedSessions = persistentState.lastSuccessfulSavedSessions ?? this.savedSessions;
- this.savedCatalogReady = persistentState.lastSuccessfulSavedSessions !== undefined;
+ this.savedCatalogReady = persistentState.savedCatalogLoaded === true;
this.heartbeats = persistentState.heartbeats ?? [];
this.savedCatalogGeneration = persistentState.savedCatalogGeneration ?? 0;
this.expandedSubagentParents = persistentState.expandedSubagentParents ?? new Set();
@@ -830,12 +847,19 @@ export class AgentsViewMode implements Component, Focusable {
}
async run(): Promise<AgentsViewRunResult> {
- this.client = new DaemonClient(this.requireSocketPath());
- await this.client.connect();
- this.subscribeToClientClose(this.client);
- this.unsubscribeClientMessage = this.client.onMessage((message) => {
+ this.persistentState.rosterClient ??= new DaemonClient(this.requireSocketPath());
+ const client = this.persistentState.rosterClient;
+ this.client = client;
+ if (!client.isConnected) await client.reconnect();
+ this.unsubscribeClientMessage = client.onMessage((message) => {
if (message.type === "heartbeats_changed") void this.refreshHeartbeats();
});
+ this.persistentState.rosterStore ??= new AgentsViewRosterStore();
+ this.rosterStore = this.persistentState.rosterStore;
+ if (!(await this.rosterStore.attach(client))) {
+ throw new Error(STALE_ROSTER_DAEMON_MESSAGE);
+ }
+ this.subscribeToClientClose(client);
this.ui.addChild(this);
this.ui.setFocus(this);
@@ -860,17 +884,21 @@ export class AgentsViewMode implements Component, Focusable {
const runPromise = new Promise<AgentsViewRunResult>((resolve) => {
this.resolveRun = resolve;
});
- void this.refreshSessions();
- void this.refreshSavedSessions();
+ this.unsubscribeRosterUpdate = this.rosterStore.onUpdate(() => this.onRosterUpdate());
+ this.applySessionList(this.rosterStore.summaries(), true);
+ this.armSavedSearchFetch();
+ this.resolveMissingSelectionAnchor();
void this.refreshHeartbeats();
this.loadStartupNotices();
- this.pollTimer = setInterval(() => this.pollSessions(), POLL_INTERVAL_MS);
- this.pollTimer.unref?.();
this.heartbeatPollTimer = setInterval(() => void this.refreshHeartbeats(), HEARTBEAT_POLL_INTERVAL_MS);
this.heartbeatPollTimer.unref?.();
this.animationTimer = setInterval(() => {
- if (!this.rows.some((row) => row.section === "running")) return;
- this.workingIconFrame += 1;
+ const hasRunning = this.rows.some((row) => row.section === "running");
+ const hasStaleAge = this.rows.some((row) => row.summary.lastHeardFromAt !== undefined);
+ if (!hasRunning && !hasStaleAge) return;
+ // Age labels are baked into rows at build time; ticking them needs a rebuild.
+ if (hasStaleAge) this.rebuildRows();
+ if (hasRunning) this.workingIconFrame += 1;
this.ui.requestRender();
}, WORKING_ICON_INTERVAL_MS);
this.animationTimer.unref?.();
@@ -1007,8 +1035,6 @@ export class AgentsViewMode implements Component, Focusable {
void promise
.then((notices) => {
this.persistentState.startupNotices = notices;
- // Best-effort immediate paint; a re-entered instance also picks this up on
- // its next poll tick since render reads persistentState directly.
this.ui.requestRender();
})
.catch(() => {});
@@ -1227,8 +1253,21 @@ export class AgentsViewMode implements Component, Focusable {
this.queryChanged();
}
+ private armSavedSearchFetch(options: { duringReconnect?: boolean } = {}): void {
+ if (
+ this.savedSearchFetchStarted ||
+ this.persistentState.savedCatalogLoaded === true ||
+ this.editor.getText().trim().length === 0
+ ) {
+ return;
+ }
+ this.savedSearchFetchStarted = true;
+ void this.refreshSavedSessions({ ...options, preserveStatusOnError: true });
+ }
+
private queryChanged(): void {
this.persistentState.query = this.editor.getText();
+ this.armSavedSearchFetch();
this.rebuildRows();
// Typing must not claim the visible fallback row while the restored
// anchor is still waiting for its catalog row.
@@ -1296,7 +1335,7 @@ export class AgentsViewMode implements Component, Focusable {
this.setReplyTarget(undefined);
}
// Keep the send outcome (or sticky cwd notice) that sendReply just surfaced.
- await this.refreshSessions({ preserveStatusOnError: true });
+ await this.refreshSessions();
} else if (this.replyTarget === target && this.editor.getText().length === 0) {
this.editor.setText(value);
}
@@ -1624,8 +1663,9 @@ export class AgentsViewMode implements Component, Focusable {
this.setStatusMessage("This session cannot be renamed", { tone: "warning" });
return false;
}
- const refreshed = await this.refreshBothCatalogs();
- this.setStatusMessage(refreshed ? `Renamed to ${name}` : `Renamed to ${name}; refresh failed`);
+ await this.refreshSessions();
+ this.refreshSavedSessionsIfLoaded();
+ this.setStatusMessage(`Renamed to ${name}`);
return true;
} catch (error) {
this.setStatusMessage(
@@ -1714,7 +1754,7 @@ export class AgentsViewMode implements Component, Focusable {
return true;
} catch (error) {
this.setStatusMessage(formatError("Failed to send reply", error));
- if (didResume) await this.refreshSessions({ preserveStatusOnError: true });
+ if (didResume) await this.refreshSessions();
return false;
}
}
@@ -1774,7 +1814,9 @@ export class AgentsViewMode implements Component, Focusable {
this.setStatusMessage("Usage: /name <session name>", { tone: "warning" });
return false;
}
- return await this.renameSession(target, name);
+ const renamed = await this.renameSession(target, name);
+ if (renamed) disarmIfUnchanged();
+ return renamed;
}
case "kill": {
if (!target.activeSessionId) {
@@ -1791,7 +1833,7 @@ export class AgentsViewMode implements Component, Focusable {
}
disarmIfUnchanged();
this.setStatusMessage("Agent stopped");
- await this.refreshBothCatalogs();
+ await this.refreshSessions();
return true;
}
}
@@ -1838,10 +1880,10 @@ export class AgentsViewMode implements Component, Focusable {
if (this.pendingDeleteAgent?.identity === identity && this.isDeleteConfirmationVisible()) {
this.clearDeleteConfirmation({ render: false });
try {
+ // Authoritative liveness check; its narrower plain-list verdict stays local.
const latest = expectSessionList(
requireDaemonData(await this.requireClient().request(createAgentsViewListCommand())),
);
- this.lastListedSummaries = latest;
const active = resolveAgentsViewActiveSummaryForPath(row.summary.sessionFile, latest);
if (active) {
this.pendingDeleteAgent = undefined;
@@ -1861,7 +1903,9 @@ export class AgentsViewMode implements Component, Focusable {
return;
}
this.pendingDeleteAgent = undefined;
- const refreshed = await this.refreshSavedSessions({ preserveStatusOnError: true });
+ const refreshed =
+ !this.persistentState.savedCatalogLoaded ||
+ (await this.refreshSavedSessions({ preserveStatusOnError: true }));
const success = result.method === "trash" ? "Session moved to trash" : "Session deleted";
this.setStatusMessage(refreshed ? success : `${success}; refresh failed`);
} catch (error) {
@@ -2047,6 +2091,7 @@ export class AgentsViewMode implements Component, Focusable {
this.selectedActiveSessionId = undefined;
this.setStatusMessage("Agent inactive", { render: false });
await this.refreshSessions();
+ this.refreshSavedSessionsIfLoaded();
} catch (error) {
this.setStatusMessage(formatError("Failed to deactivate agent", error));
}
@@ -2079,55 +2124,20 @@ export class AgentsViewMode implements Component, Focusable {
requireDaemonData(response);
}
- private pollSessions(): void {
- if (this.liveCatalogPollPromise) return;
- const poll = this.refreshSessions().then(() => undefined);
- this.liveCatalogPollPromise = poll;
- void poll.finally(() => {
- if (this.liveCatalogPollPromise === poll) this.liveCatalogPollPromise = undefined;
- });
+ private onRosterUpdate(): void {
+ if (this.stopped || !this.rosterStore) return;
+ this.applySessionList(this.rosterStore.summaries(), true);
+ this.resolveMissingSelectionAnchor();
}
- private async refreshSessions(options: { preserveStatusOnError?: boolean } = {}): Promise<boolean> {
- if (this.reconnectPromise || this.daemonShutdownReceived) return false;
- const generation = ++this.liveCatalogGeneration;
- this.liveCatalogRefreshPending = true;
- try {
- const client = this.requireClient();
- try {
- const response = await client.request(createAgentsViewListCommand());
- if (generation !== this.liveCatalogGeneration) return false;
- this.liveCatalogReady = true;
- this.applySessionList(expectSessionList(requireDaemonData(response)), true);
- return true;
- } catch (error) {
- if (generation === this.liveCatalogGeneration) {
- // A completed failed attempt is still catalog-settled: otherwise a
- // vanished scope can permanently trap an empty view.
- this.liveCatalogReady = true;
- this.reconcileCatalogs();
- if (!options.preserveStatusOnError && !this.reconnectPromise) {
- if (client.isConnected) this.setStatusMessage(formatError("Failed to refresh agents", error));
- else this.startClientReconnect(client, error);
- }
- }
- return false;
- }
- } catch (error) {
- if (generation === this.liveCatalogGeneration) {
- this.liveCatalogReady = true;
- this.reconcileCatalogs();
- if (!options.preserveStatusOnError) {
- this.setStatusMessage(formatError("Failed to refresh current session", error));
- }
- }
- return false;
- } finally {
- if (generation === this.liveCatalogGeneration) {
- this.liveCatalogRefreshPending = false;
- this.resolveMissingSelectionAnchor();
- }
- }
+ private refreshSavedSessionsIfLoaded(): void {
+ if (this.persistentState.savedCatalogLoaded) void this.refreshSavedSessions({ preserveStatusOnError: true });
+ }
+
+ private async refreshSessions(): Promise<void> {
+ if (this.reconnectPromise || this.daemonShutdownReceived || !this.rosterStore) return;
+ this.applySessionList(this.rosterStore.summaries(), true);
+ this.resolveMissingSelectionAnchor();
}
private applySessionList(sessions: SessionSummary[], successful = false): void {
@@ -2148,7 +2158,7 @@ export class AgentsViewMode implements Component, Focusable {
const frames = this.persistentState.scopeFrames ?? [];
const resolution = resolveAgentsViewScopeFrames(this.unifiedRecords, frames, this.unifiedIndex);
- if (shouldApplyScopeResolution(resolution.droppedFrames, this.liveCatalogReady, this.savedCatalogReady)) {
+ if (shouldApplyScopeResolution(resolution.droppedFrames, this.savedCatalogReady)) {
this.persistentState.scopeFrames = resolution.frames;
this.scopeKey = resolution.frames.at(-1)?.scope;
this.scopeRootSummary = resolution.root ? summaryForUnifiedRecord(resolution.root) : undefined;
@@ -2170,19 +2180,17 @@ export class AgentsViewMode implements Component, Focusable {
this.ui.requestRender();
}
- /** A session appears in both catalogs; mutations must refresh both. */
- private async refreshBothCatalogs(): Promise<boolean> {
- const results = await Promise.all([
- this.refreshSessions({ preserveStatusOnError: true }),
- this.refreshSavedSessions({ preserveStatusOnError: true }),
- ]);
- return results.every(Boolean);
+ private rearmSavedSearchFetch(): void {
+ if (this.persistentState.savedCatalogLoaded !== true) this.savedSearchFetchStarted = false;
}
private async refreshSavedSessions(
options: { duringReconnect?: boolean; preserveStatusOnError?: boolean } = {},
): Promise<boolean> {
- if ((!options.duringReconnect && this.reconnectPromise) || this.daemonShutdownReceived) return false;
+ if ((!options.duringReconnect && this.reconnectPromise) || this.daemonShutdownReceived) {
+ this.rearmSavedSearchFetch();
+ return false;
+ }
const generation = ++this.savedCatalogGeneration;
this.persistentState.savedCatalogGeneration = generation;
this.savedCatalogRefreshPending = true;
@@ -2213,6 +2221,7 @@ export class AgentsViewMode implements Component, Focusable {
this.savedCatalogReady = true;
this.persistentState.lastSuccessfulSavedSessions = sessions;
this.persistentState.savedSessions = sessions;
+ this.persistentState.savedCatalogLoaded = true;
this.reconcileCatalogs();
return true;
} catch (error) {
@@ -2221,6 +2230,7 @@ export class AgentsViewMode implements Component, Focusable {
this.persistentState.savedSessions = successfulSessions;
// Treat a terminal failure as settled so scope fallback cannot soft-lock.
this.savedCatalogReady = true;
+ this.rearmSavedSearchFetch();
this.reconcileCatalogs();
if (!options.preserveStatusOnError && !this.reconnectPromise && !this.daemonShutdownReceived) {
this.setStatusMessage(formatError("Failed to load saved sessions", error));
@@ -2247,7 +2257,12 @@ export class AgentsViewMode implements Component, Focusable {
return true;
} catch (error) {
if (generation === this.heartbeatCatalogGeneration && !this.reconnectPromise) {
- this.setStatusMessage(formatError("Failed to refresh heartbeats", error));
+ const client = this.client;
+ if (client && !client.isConnected) {
+ this.startClientReconnect(client, error);
+ } else if (!this.statusMessageSticky) {
+ this.setStatusMessage(formatError("Failed to refresh heartbeats", error));
+ }
}
return false;
}
@@ -2276,11 +2291,9 @@ export class AgentsViewMode implements Component, Focusable {
}
private resolveMissingSelectionAnchor(): void {
- if (!this.selectionAnchorPending || this.liveCatalogRefreshPending || this.savedCatalogRefreshPending) {
+ if (!this.selectionAnchorPending || this.savedCatalogRefreshPending) {
return;
}
- // Unblock the fallback row, but keep the anchor identities: a later poll
- // can still deliver the intended session and re-anchor selection to it.
this.selectionAnchorPending = false;
const row = this.rows[this.selectedIndex];
this.selectedActiveSessionId = row?.selectable ? (row.summary.activeSessionId ?? row.summary.id) : undefined;
@@ -2337,12 +2350,7 @@ export class AgentsViewMode implements Component, Focusable {
}
this.stopped = true;
this.savedCatalogGeneration += 1;
- this.liveCatalogGeneration += 1;
this.heartbeatCatalogGeneration += 1;
- if (this.pollTimer) {
- clearInterval(this.pollTimer);
- this.pollTimer = undefined;
- }
if (this.heartbeatPollTimer) {
clearInterval(this.heartbeatPollTimer);
this.heartbeatPollTimer = undefined;
@@ -2363,7 +2371,8 @@ export class AgentsViewMode implements Component, Focusable {
this.unsubscribeClientClose = undefined;
this.unsubscribeClientMessage?.();
this.unsubscribeClientMessage = undefined;
- this.client?.close();
+ this.unsubscribeRosterUpdate?.();
+ this.unsubscribeRosterUpdate = undefined;
this.client = undefined;
this.resolveRun?.(result);
this.resolveRun = undefined;
@@ -2415,16 +2424,17 @@ export class AgentsViewMode implements Component, Focusable {
try {
await this.options.recoverDaemon?.();
await client.reconnect(1000);
- const response = await client.request(createAgentsViewListCommand());
- const data = requireDaemonData(response);
- const sessions = expectSessionList(data);
+ if (!this.rosterStore || !(await this.rosterStore.attach(client))) {
+ throw new Error("Daemon lost the agent_roster capability during reconnect");
+ }
const heartbeatsRefreshed = await this.refreshHeartbeats({ duringReconnect: true });
if (!heartbeatsRefreshed) throw new Error("Heartbeat catalog did not refresh during reconnect");
+ const sessions = this.rosterStore.summaries();
this.daemonShutdownReceived = false;
this.reconnectTimedOut = false;
this.setStatusMessage("Daemon reconnected", { render: false });
this.applySessionList(sessions, true);
- void this.refreshSavedSessions({ duringReconnect: true, preserveStatusOnError: true });
+ this.armSavedSearchFetch({ duringReconnect: true });
return;
} catch (error) {
lastError = error;
@@ -2556,7 +2566,13 @@ export class AgentsViewMode implements Component, Focusable {
isSubagentSummary(row.summary) && !pendingDelete && !pendingKill && row.summary.model
? `${row.summary.model.provider}/${row.summary.model.id}${row.summary.thinkingLevel && row.summary.thinkingLevel !== "off" ? `:${row.summary.thinkingLevel}` : ""}`
: undefined;
- const suffixes = [modelLabel, summaryText].filter(
+ const statusLabel =
+ !pendingDelete &&
+ !pendingKill &&
+ (row.summary.statusLabel !== undefined || row.summary.lastHeardFromAt !== undefined)
+ ? row.statusLabel
+ : undefined;
+ const suffixes = [statusLabel, modelLabel, summaryText].filter(
(suffix): suffix is string => suffix !== undefined && suffix.length > 0,
);
const titleContent = suffixes.length > 0 ? `${title} ${theme.fg("dim", `· ${suffixes.join(" · ")}`)}` : title;
diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-state.ts b/packages/coding-agent/src/modes/agents-view/agents-view-state.ts
index 1e9fa13103..701f313634 100644
--- a/packages/coding-agent/src/modes/agents-view/agents-view-state.ts
+++ b/packages/coding-agent/src/modes/agents-view/agents-view-state.ts
@@ -1,6 +1,7 @@
import { basename, resolve } from "node:path";
import { canonicalizePath } from "../../utils/paths.js";
import type { AgentConnectionHeartbeat, AgentConnectionSavedSessionInfo } from "../agent-connection/index.js";
+import { rosterAgentIdForSummary } from "../daemon/agent-roster.js";
import { classifySessionRosterStatus, type SessionSummary } from "../daemon/daemon-session-list.js";
export type AgentsViewSection = "running" | "idle" | "inactive";
@@ -90,7 +91,7 @@ export interface AgentsViewRow {
}
export function classifyAgentsViewSession(summary: SessionSummary): AgentsViewSection {
- return classifySessionRosterStatus(summary);
+ return summary.rosterStatus ?? classifySessionRosterStatus(summary);
}
export function classifyUnifiedSession(record: Pick<UnifiedSessionRecord, "daemon" | "heartbeat">): AgentsViewSection {
@@ -125,6 +126,13 @@ export function sectionTitle(section: AgentsViewSection): string {
}
}
+function formatAgeLabel(timestamp: string): string {
+ const seconds = Math.max(0, Math.round((Date.now() - Date.parse(timestamp)) / 1000));
+ if (seconds < 120) return `${seconds}s ago`;
+ const minutes = Math.round(seconds / 60);
+ return minutes < 120 ? `${minutes}m ago` : `${Math.round(minutes / 60)}h ago`;
+}
+
function canonicalSessionPath(path: string): string {
return resolve(canonicalizePath(path));
}
@@ -135,6 +143,9 @@ function fileIdentity(path: string): string {
function summaryIdentityAliases(summary: SessionSummary): string[] {
return [
+ summary.runtimeKind === "subagent" && summary.rlmChildId
+ ? `agent:${rosterAgentIdForSummary(summary)}`
+ : undefined,
summary.sessionFile ? fileIdentity(summary.sessionFile) : undefined,
`session:${summary.sessionId}`,
summary.activeSessionId ? `active:${summary.activeSessionId}` : undefined,
@@ -296,12 +307,8 @@ export function resolveAgentsViewLeftResult(
};
}
-export function shouldApplyScopeResolution(
- droppedFrames: number,
- liveCatalogReady: boolean,
- savedCatalogReady: boolean,
-): boolean {
- return droppedFrames === 0 || (liveCatalogReady && savedCatalogReady);
+export function shouldApplyScopeResolution(droppedFrames: number, savedCatalogReady: boolean): boolean {
+ return droppedFrames === 0 || savedCatalogReady;
}
export function createUnattachableChildOpenResult(
@@ -545,7 +552,21 @@ function getParentKeys(summary: SessionSummary): string[] {
].filter((key): key is string => key !== undefined);
}
+/** Direct-child linkage over getParentKeys, shared by the view tree and the chat subagents bar. */
+export function isDirectAgentChild(
+ child: SessionSummary,
+ parent: { activeSessionId?: string | undefined; sessionId?: string | undefined; sessionFile?: string | undefined },
+): boolean {
+ const parentKeys = new Set(getParentKeys(child));
+ if (parent.activeSessionId !== undefined && parentKeys.has(`active:${parent.activeSessionId}`)) return true;
+ if (parent.sessionId !== undefined && parentKeys.has(`session:${parent.sessionId}`)) return true;
+ return parent.sessionFile !== undefined && parentKeys.has(fileIdentity(parent.sessionFile));
+}
+
export function getAgentsViewSummaryIdentity(summary: SessionSummary): string {
+ if (summary.runtimeKind === "subagent" && summary.rlmChildId) {
+ return `agent:${rosterAgentIdForSummary(summary)}`;
+ }
if (summary.sessionFile) {
return fileIdentity(summary.sessionFile);
}
@@ -959,6 +980,12 @@ function getSessionSubtitle(summary: SessionSummary): string {
}
function getSessionStatusLabel(summary: SessionSummary, hasActiveHeartbeat = summary.hasActiveHeartbeat): string {
+ if (summary.statusLabel !== undefined) {
+ return summary.statusLabel;
+ }
+ if (summary.lastHeardFromAt !== undefined) {
+ return `last heard ${formatAgeLabel(summary.lastHeardFromAt)}`;
+ }
// A non-ready worker cannot report fresh runtime flags; its state is the row's story.
if (summary.workerState !== undefined && summary.workerState !== "ready") {
return summary.workerState;
diff --git a/packages/coding-agent/src/modes/agents-view/roster-store.ts b/packages/coding-agent/src/modes/agents-view/roster-store.ts
new file mode 100644
index 0000000000..694e1cde6f
--- /dev/null
+++ b/packages/coding-agent/src/modes/agents-view/roster-store.ts
@@ -0,0 +1,131 @@
+import type { AgentRosterEntry } from "../daemon/agent-roster.js";
+import { sessionSummaryFromRosterEntry } from "../daemon/agent-roster.js";
+import type { DaemonClient, DaemonHello } from "../daemon/daemon-client.js";
+import type { DaemonOutbound } from "../daemon/daemon-protocol.js";
+import type { SessionSummary } from "../daemon/daemon-session-list.js";
+
+export const STALE_ROSTER_DAEMON_MESSAGE =
+ "Daemon is stale: it does not advertise the agent_roster capability; restart the daemon";
+
+export class AgentsViewRosterStore {
+ private readonly entries = new Map<string, AgentRosterEntry>();
+ private readonly listeners = new Set<() => void>();
+ private client: DaemonClient | undefined;
+ private unsubscribeMessage: (() => void) | undefined;
+ private emitScheduled = false;
+ private subscribed = false;
+ private subscribedHello: DaemonHello | undefined;
+ private attachChain: Promise<unknown> = Promise.resolve();
+
+ async attach(client: DaemonClient): Promise<boolean> {
+ // Serialized: a stale attempt settling late must not detach a newer subscription's listener.
+ const run = () => this.attachToClient(client);
+ const chained = this.attachChain.then(run, run);
+ this.attachChain = chained;
+ return chained;
+ }
+
+ private async attachToClient(client: DaemonClient): Promise<boolean> {
+ if (client.isConnected && client.hello === undefined) await client.waitForHello();
+ if (!client.supportsServerCapability("agent_roster")) {
+ this.detachFromClient();
+ return false;
+ }
+ const hello = client.hello;
+ if (this.subscribed && this.client === client && client.isConnected && hello === this.subscribedHello) {
+ return true;
+ }
+ this.detachFromClient();
+ this.client = client;
+ // Pushes racing the subscribe reply buffer until the snapshot lands.
+ let pendingUpdates: Extract<DaemonOutbound, { type: "roster_update" }>[] | undefined = [];
+ this.unsubscribeMessage = client.onMessage((message) => {
+ if (message.type !== "roster_update") return;
+ if (pendingUpdates) pendingUpdates.push(message);
+ else this.applyUpdate(message.changed, message.removed, message.resync);
+ });
+ let response: Awaited<ReturnType<DaemonClient["request"]>>;
+ try {
+ // Not parkable: the awaiting reconnect loop must see a close as a rejection.
+ response = await client.request({ type: "roster_subscribe" }, 30000, { recoverable: false });
+ } catch (error) {
+ this.detachFromClient();
+ throw error;
+ }
+ if (!response.success || typeof response.data !== "object" || response.data === null) {
+ this.detachFromClient();
+ throw new Error(
+ `roster_subscribe failed: ${response.success ? "invalid roster payload" : (response.error ?? "unknown error")}`,
+ );
+ }
+ const roster = (response.data as { roster?: AgentRosterEntry[] }).roster ?? [];
+ this.applyUpdate(roster, undefined, true);
+ for (const update of pendingUpdates ?? []) {
+ this.applyUpdate(update.changed, update.removed, update.resync);
+ }
+ pendingUpdates = undefined;
+ this.subscribed = true;
+ this.subscribedHello = hello;
+ return true;
+ }
+
+ private applyUpdate(changed: AgentRosterEntry[], removed?: string[], resync?: true): void {
+ if (resync) this.entries.clear();
+ for (const entry of changed) {
+ this.entries.set(entry.agentId, entry);
+ }
+ for (const agentId of removed ?? []) {
+ this.entries.delete(agentId);
+ }
+ this.scheduleEmit();
+ }
+
+ summaries(): SessionSummary[] {
+ return [...this.entries.values()].map((entry) => sessionSummaryFromRosterEntry(entry));
+ }
+
+ onUpdate(listener: () => void): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+
+ private scheduleEmit(): void {
+ if (this.emitScheduled) return;
+ this.emitScheduled = true;
+ queueMicrotask(() => {
+ this.emitScheduled = false;
+ for (const listener of [...this.listeners]) {
+ try {
+ listener();
+ } catch {
+ // One consumer must not interrupt delivery to the others.
+ }
+ }
+ });
+ }
+
+ private detachFromClient(): void {
+ this.unsubscribeMessage?.();
+ this.unsubscribeMessage = undefined;
+ this.subscribed = false;
+ this.subscribedHello = undefined;
+ this.client = undefined;
+ }
+
+ async dispose(): Promise<void> {
+ const run = () => this.disposeNow();
+ const chained = this.attachChain.then(run, run);
+ this.attachChain = chained;
+ return chained;
+ }
+
+ private disposeNow(): void {
+ const client = this.client;
+ this.detachFromClient();
+ this.listeners.clear();
+ // Fire-and-forget: nobody needs the ack, and a closed socket already unsubscribed.
+ if (client?.isConnected) {
+ void client.request({ type: "roster_unsubscribe" }).catch(() => undefined);
+ }
+ }
+}
diff --git a/packages/coding-agent/src/modes/daemon/active-session-state.ts b/packages/coding-agent/src/modes/daemon/active-session-state.ts
index b0f9b3f648..02a5427d4a 100644
--- a/packages/coding-agent/src/modes/daemon/active-session-state.ts
+++ b/packages/coding-agent/src/modes/daemon/active-session-state.ts
@@ -18,6 +18,9 @@ export interface DaemonSocketClient {
/** Delayed retry after transient catch-up snapshot preparation failure. */
catchupRetryTimer?: NodeJS.Timeout;
backpressured?: boolean;
+ rosterSubscribed?: boolean;
+ /** A push hit backpressure; one full-roster resync goes out on drain. */
+ rosterResyncPending?: boolean;
authenticated?: boolean;
transport?: "jsonl" | "private-framed";
snapshotStreaming?: boolean;
diff --git a/packages/coding-agent/src/modes/daemon/agent-roster.ts b/packages/coding-agent/src/modes/daemon/agent-roster.ts
index ea6a8a2130..800c865069 100644
--- a/packages/coding-agent/src/modes/daemon/agent-roster.ts
+++ b/packages/coding-agent/src/modes/daemon/agent-roster.ts
@@ -115,16 +115,29 @@ export function passivatedWorkerRosterEntry(
};
}
-export function sessionSummaryFromRosterEntry(entry: WorkerRosterEntry): SessionSummary {
- return { ...entry.summary, sessionActions: { queuedCount: 0, steering: [], followUps: [] } };
+export function sessionSummaryFromRosterEntry(entry: WorkerRosterEntry | AgentRosterEntry): SessionSummary {
+ const ledger = "status" in entry ? entry : undefined;
+ return {
+ ...entry.summary,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
+ ...(ledger ? { rosterStatus: ledger.status } : {}),
+ ...(ledger?.statusLabel ? { statusLabel: ledger.statusLabel } : {}),
+ ...(ledger?.lastHeardFromAt ? { lastHeardFromAt: ledger.lastHeardFromAt } : {}),
+ };
}
+export type AgentRosterMutation = { type: "write"; agentId: string } | { type: "delete"; agentId: string };
+
+// Supervisor-owned roster store; write() classifies once and its file index converges seed and worker keys.
export class AgentRoster {
private readonly entries = new Map<string, AgentRosterEntry>();
private readonly agentIdByActiveSessionId = new Map<string, string>();
private readonly agentIdBySessionFile = new Map<string, string>();
- constructor(private readonly canonicalPath: (path: string) => string) {}
+ constructor(
+ private readonly canonicalPath: (path: string) => string,
+ private readonly onMutation: (mutation: AgentRosterMutation) => void = () => {},
+ ) {}
values(): IterableIterator<AgentRosterEntry> {
return this.entries.values();
@@ -177,6 +190,7 @@ export class AgentRoster {
this.agentIdByActiveSessionId.set(stored.summary.activeSessionId, entry.agentId);
}
this.entries.set(entry.agentId, stored);
+ this.onMutation({ type: "write", agentId: entry.agentId });
return stored;
}
@@ -185,6 +199,24 @@ export class AgentRoster {
if (!entry) return;
this.dropIndexes(entry);
this.entries.delete(agentId);
+ this.onMutation({ type: "delete", agentId });
+ }
+
+ amend(
+ agentId: string,
+ marks: { statusLabel?: AgentRosterEntry["statusLabel"] | undefined; lastHeardFromAt?: string | undefined },
+ ): void {
+ const entry = this.entries.get(agentId);
+ if (!entry) return;
+ if ("statusLabel" in marks) {
+ if (marks.statusLabel === undefined) delete entry.statusLabel;
+ else entry.statusLabel = marks.statusLabel;
+ }
+ if ("lastHeardFromAt" in marks) {
+ if (marks.lastHeardFromAt === undefined) delete entry.lastHeardFromAt;
+ else entry.lastHeardFromAt = marks.lastHeardFromAt;
+ }
+ this.onMutation({ type: "write", agentId });
}
private dropIndexes(entry: AgentRosterEntry): void {
diff --git a/packages/coding-agent/src/modes/daemon/daemon-client.ts b/packages/coding-agent/src/modes/daemon/daemon-client.ts
index cffdb69782..72101718c9 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-client.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-client.ts
@@ -34,6 +34,8 @@ export type DaemonClientProgressListener = (message: DaemonRequestProgress) => v
export interface DaemonClientRequestOptions {
onProgress?: DaemonClientProgressListener;
+ /** False opts out of reconnect parking: a close rejects so the caller's own retry loop stays live. */
+ recoverable?: boolean;
}
interface PendingDaemonRequest {
@@ -46,6 +48,7 @@ interface PendingDaemonRequest {
wireData: string;
awaitingReconnect: boolean;
acknowledgeResult: boolean;
+ recoverable: boolean;
/** Re-checked against the new hello before a reconnect replay. */
compatibilities: readonly DaemonCommandCompatibility[];
}
@@ -377,6 +380,7 @@ export class DaemonClient {
wireData,
awaitingReconnect: false,
acknowledgeResult,
+ recoverable: options.recoverable !== false,
compatibilities,
};
this.pendingRequests.set(id, pending);
@@ -515,7 +519,7 @@ export class DaemonClient {
private rejectAll(error: Error, preservePendingRequests = false): void {
for (const [id, pending] of this.pendingRequests) {
- if (preservePendingRequests) {
+ if (preservePendingRequests && pending.recoverable) {
if (pending.timeout) {
clearTimeout(pending.timeout);
pending.timeout = undefined;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index cfeac408b4..66da67042a 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -39,6 +39,7 @@ import type {
AgentConnectionSideQuestionTurn,
AgentConnectionState,
} from "../agent-connection/types.js";
+import type { AgentRosterEntry } from "./agent-roster.js";
import type { SessionSummary } from "./daemon-session-list.js";
/**
@@ -67,8 +68,9 @@ export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 7;
// Revision 20 lets cancellation target a prompt the session owns but has not started.
// Revision 21 adds capability-gated, session-scoped ACP MCP server replacement.
// Revision 23 lets workers query the supervisor agent roster on demand.
-export const DAEMON_SCHEMA_REVISION = 23;
-export const DAEMON_SCHEMA_ID = "protocol-7-schema-23-649fe649d15e";
+// Revision 24 adds the capability-gated agent-roster subscription and push.
+export const DAEMON_SCHEMA_REVISION = 24;
+export const DAEMON_SCHEMA_ID = "protocol-7-schema-24-75f88f1a91df";
export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;
export type DaemonProtocolVersion = number;
@@ -105,6 +107,7 @@ export type DaemonServerCapability =
// carry the transient marker and echoed runId so clients correlate runs by
// identity). Clients must check before sending.
| "transient_bash"
+ | "agent_roster"
| "session_input_admission"
| "prompt_admission_cancellation"
| "queue_message_mutation"
@@ -378,6 +381,8 @@ export type DaemonCommand =
}
| DaemonSavedSessionListCommand
| { id?: string; type: "list_agent_peers"; workerToken: string }
+ | { id?: string; type: "roster_subscribe" }
+ | { id?: string; type: "roster_unsubscribe" }
| ({
id?: string;
type: "create";
@@ -771,6 +776,8 @@ export const DAEMON_COMMAND_COMPATIBILITY = {
release_session_input_pause: SESSION_INPUT_PAUSE_COMMAND,
cron_list: LEGACY_DAEMON_COMMAND,
heartbeats_list: { minProtocol: 7, capability: "heartbeat_catalog" },
+ roster_subscribe: { minProtocol: 7, capability: "agent_roster" },
+ roster_unsubscribe: { minProtocol: 7, capability: "agent_roster" },
heartbeat_manage: { minProtocol: 7, capability: "heartbeat_management" },
cron_add: LEGACY_DAEMON_COMMAND,
cron_cancel: LEGACY_DAEMON_COMMAND,
@@ -949,6 +956,7 @@ export type DaemonOutbound =
}
| { type: "daemon_closing"; reason: DaemonClosingReason }
| { type: "heartbeats_changed" }
+ | { type: "roster_update"; changed: AgentRosterEntry[]; removed?: string[]; resync?: true }
| { type: "session_event"; activeSessionId: string; event: AgentConnectionSessionEvent; meta?: DaemonEventMeta }
| { type: "side_question_event"; activeSessionId: string; event: AgentConnectionSideQuestionEvent }
| { type: "session_status"; activeSessionId: string; recap?: string; meta?: DaemonEventMeta }
@@ -1031,6 +1039,7 @@ export const DAEMON_OUTBOUND_COMPATIBILITY = {
daemon_hello: LEGACY_DAEMON_COMMAND,
daemon_closing: LEGACY_DAEMON_COMMAND,
heartbeats_changed: { minProtocol: 7, capability: "heartbeat_catalog" },
+ roster_update: { minProtocol: 7, capability: "agent_roster" },
session_event: LEGACY_DAEMON_COMMAND,
side_question_event: LEGACY_DAEMON_COMMAND,
session_status: LEGACY_DAEMON_COMMAND,
@@ -1112,6 +1121,8 @@ const READ_ONLY_DAEMON_COMMANDS: ReadonlySet<DaemonCommand["type"]> = new Set([
"list_agent_peers",
"attach",
"reattach",
+ "roster_subscribe",
+ "roster_unsubscribe",
"agent_messages_status",
"wait_for_idle",
"get_session_header",
diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
index 5e8e8d4e48..72989daf28 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
@@ -9,7 +9,8 @@ import type { SessionActionSnapshot } from "../../core/session-action-store.js";
import type { AgentTaskState, SessionInfo } from "../../core/session-manager.js";
import type { AgentConnectionRlmChildAgentSnapshot } from "../agent-connection/types.js";
import type { ActiveSessionState } from "./active-session-state.js";
-import { isSessionSummaryBusy } from "./agent-roster.js";
+
+import { type AgentRosterStatus, isSessionSummaryBusy } from "./agent-roster.js";
export { classifySessionRosterStatus, isSessionSummaryBusy } from "./agent-roster.js";
@@ -78,6 +79,10 @@ export interface SessionSummary {
summary?: string;
/** Completion verdict for an idle session; absent while working or unjudged. */
taskState?: AgentTaskState;
+ rosterStatus?: AgentRosterStatus;
+ statusLabel?: "queued" | "recovering" | "failed";
+ /** Set while the owning worker has been silent past the staleness threshold. */
+ lastHeardFromAt?: string;
/** Resident session-host process state, populated by the global supervisor. */
workerState?: "starting" | "ready" | "recovering" | "stopping" | "failed";
/** Diagnostic process identity; clients must not use this as a stable session identifier. */
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index 017164e64c..4462381ab4 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -59,6 +59,7 @@ import { createActiveSessionId, type DaemonSocketClient } from "./active-session
import {
AgentRoster,
type AgentRosterEntry,
+ type AgentRosterMutation,
passivatedWorkerRosterEntry,
rosterAgentIdForSummary,
sessionSummaryFromRosterEntry,
@@ -86,6 +87,7 @@ import {
type DaemonCommand,
type DaemonOutbound,
type DaemonResponse,
+ type DaemonServerCapability,
type DaemonUpdateRestartManifest,
failure,
isDaemonCommandEnvelope,
@@ -159,6 +161,10 @@ const structuredLog = getLogger("coding-agent.daemon-supervisor");
const WORKER_CONNECT_TIMEOUT_MS = 30_000;
const ROSTER_WATCHDOG_INTERVAL_MS = 15_000;
const ROSTER_STALE_AFTER_MS = 3 * ROSTER_HEARTBEAT_INTERVAL_MS;
+const SUPERVISOR_SERVER_CAPABILITIES: readonly DaemonServerCapability[] = [
+ ...DAEMON_DEFAULT_SERVER_CAPABILITIES,
+ "agent_roster",
+];
const WORKER_REQUEST_TIMEOUT_MS = 24 * 60 * 60 * 1000;
const INPUT_PAUSE_CLEANUP_TIMEOUT_MS = 5_000;
const UPDATE_RESTART_MUTATION_DRAIN_TIMEOUT_MS = 80_000;
@@ -189,6 +195,8 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"ack_result",
"list",
"list_agent_peers",
+ "roster_subscribe",
+ "roster_unsubscribe",
"list_saved_sessions",
"create",
"attach",
@@ -648,6 +656,11 @@ export class DaemonSupervisor {
private readonly catalog: DaemonCatalogClient;
private readonly settingsManager: SettingsManager;
private rosterStore?: AgentRoster;
+ private readonly pendingRosterChanged = new Set<string>();
+ private readonly pendingRosterRemoved = new Set<string>();
+ /** Ids declared to subscribers: gates removals to once and keeps owned-only row ids private. */
+ private readonly publishedRosterIds = new Set<string>();
+ private rosterPushScheduled = false;
private rosterWatchdogTimer?: ReturnType<typeof setInterval>;
private rlmSpawnLedgerInstance?: RlmSpawnLedger;
private idleEvictionTimer?: ReturnType<typeof setTimeout>;
@@ -1173,7 +1186,7 @@ export class DaemonSupervisor {
supervisorProcessStartId: this.ownership?.record.processStartId,
supervisorSocketPath: this.ownership?.record.socketPath,
clientId: client.id,
- serverCapabilities: DAEMON_DEFAULT_SERVER_CAPABILITIES,
+ serverCapabilities: SUPERVISOR_SERVER_CAPABILITIES,
});
}
},
@@ -1206,6 +1219,11 @@ export class DaemonSupervisor {
socket.on("error", cleanup);
socket.on("drain", () => {
client.backpressured = false;
+ if (client.rosterResyncPending && client.rosterSubscribed === true) {
+ // socket.write queues even when it reports backpressure: one resync per loss gap.
+ client.rosterResyncPending = false;
+ this.write(client, { type: "roster_update", changed: this.rosterEntriesForClient(), resync: true });
+ }
if (!client.snapshotStreaming) {
void this.catchUpClient(client).catch((error) =>
this.log(`Failed to catch up client ${client.id}: ${String(error)}`),
@@ -1626,6 +1644,13 @@ export class DaemonSupervisor {
return undefined;
case "list":
return this.handleList(client, command);
+ case "roster_subscribe":
+ client.rosterSubscribed = true;
+ return success(command.id, command.type, { roster: this.rosterEntriesForClient() });
+ case "roster_unsubscribe":
+ client.rosterSubscribed = false;
+ client.rosterResyncPending = false;
+ return success(command.id, command.type);
case "list_agent_peers": {
const requester = [...this.workers.values()].find(
(worker) => worker.descriptor.authenticationToken === command.workerToken,
@@ -2652,6 +2677,9 @@ export class DaemonSupervisor {
throw error;
}
worker.promotedOwnerClientId = clientId;
+ for (const entry of this.workerRosterEntries(worker)) {
+ this.roster().amend(entry.agentId, {});
+ }
if (worker.ownerCleanupTimer) {
clearTimeout(worker.ownerCleanupTimer);
worker.ownerCleanupTimer = undefined;
@@ -3682,10 +3710,74 @@ export class DaemonSupervisor {
}
private roster(): AgentRoster {
- this.rosterStore ??= new AgentRoster(canonicalSessionPath);
+ this.rosterStore ??= new AgentRoster(canonicalSessionPath, (mutation) => this.onRosterMutation(mutation));
return this.rosterStore;
}
+ private onRosterMutation(mutation: AgentRosterMutation): void {
+ if (mutation.type === "delete") {
+ this.pendingRosterChanged.delete(mutation.agentId);
+ this.pendingRosterRemoved.add(mutation.agentId);
+ } else {
+ this.pendingRosterRemoved.delete(mutation.agentId);
+ this.pendingRosterChanged.add(mutation.agentId);
+ }
+ this.scheduleRosterPush();
+ }
+
+ private scheduleRosterPush(): void {
+ if (this.rosterPushScheduled || this.shuttingDown) return;
+ this.rosterPushScheduled = true;
+ setImmediate(() => {
+ this.rosterPushScheduled = false;
+ this.flushRosterUpdates();
+ });
+ }
+
+ private flushRosterUpdates(): void {
+ const changed: AgentRosterEntry[] = [];
+ const removed: string[] = [];
+ for (const agentId of this.pendingRosterRemoved) {
+ if (this.publishedRosterIds.delete(agentId)) removed.push(agentId);
+ }
+ for (const agentId of this.pendingRosterChanged) {
+ const entry = this.roster().get(agentId);
+ if (!entry) continue;
+ if (this.isRosterEntryVisibleToClients(entry)) {
+ changed.push(entry);
+ this.publishedRosterIds.add(agentId);
+ } else if (this.publishedRosterIds.delete(agentId)) {
+ removed.push(agentId);
+ }
+ }
+ this.pendingRosterChanged.clear();
+ this.pendingRosterRemoved.clear();
+ if (changed.length === 0 && removed.length === 0) return;
+ for (const client of this.clients) {
+ if (client.rosterSubscribed !== true) continue;
+ if (client.backpressured === true) {
+ client.rosterResyncPending = true;
+ continue;
+ }
+ this.write(client, {
+ type: "roster_update",
+ changed,
+ ...(removed.length > 0 ? { removed } : {}),
+ });
+ }
+ }
+
+ private rosterEntriesForClient(): AgentRosterEntry[] {
+ const entries = [...this.roster().values()].filter((entry) => this.isRosterEntryVisibleToClients(entry));
+ for (const entry of entries) this.publishedRosterIds.add(entry.agentId);
+ return entries;
+ }
+
+ private isRosterEntryVisibleToClients(entry: AgentRosterEntry): boolean {
+ const worker = entry.workerId !== undefined ? this.workers.get(entry.workerId) : undefined;
+ return worker === undefined || this.isVisibleWorker(worker);
+ }
+
private writeRosterEntry(
entry: WorkerRosterEntry,
worker?: ResidentWorker,
@@ -3719,7 +3811,10 @@ export class DaemonSupervisor {
const entry = this.rosterEntryForSpawnLedgerEdge(edge);
if (this.roster().has(entry.agentId)) continue;
if (this.roster().hasSessionFile(canonicalSessionPath(edge.child))) continue;
- this.roster().write({ ...entry, seededCwd: true });
+ const info = await readSessionInfo(edge.child).catch(() => undefined);
+ this.roster().write(
+ info ? { ...entry, summary: { ...entry.summary, cwd: info.cwd } } : { ...entry, seededCwd: true },
+ );
}
} catch (error) {
this.log(`Could not seed the agent roster from the spawn ledger: ${String(error)}`);
@@ -3840,28 +3935,17 @@ export class DaemonSupervisor {
edgesFailed = true;
return [] as RlmLedgerEdge[];
});
- if (!this.isWorkerRosterApplyCurrent(worker, source ?? worker.client ?? worker.pendingClient)) return;
- // Unreadable edges: skip the absentee sweep (it cannot tell registry children from stale rows) and repair by pull.
+ const applySource = source ?? worker.client ?? worker.pendingClient;
+ if (!this.isWorkerRosterApplyCurrent(worker, applySource)) return;
const sent = new Set(delta.entries.map((entry) => entry.agentId));
+ const removed = new Set(delta.removedAgentIds ?? []);
const unclaimed = new Map<string, AgentRosterEntry>();
if (!edgesFailed) {
for (const entry of this.workerRosterEntries(worker)) {
if (sent.has(entry.agentId)) continue;
unclaimed.set(entry.agentId, entry);
- this.roster().delete(entry.agentId);
}
}
- for (const entry of delta.entries) {
- this.writeRosterEntry(entry, worker);
- this.syncRootDescriptorFromRosterEntry(worker, entry);
- }
- for (const agentId of delta.removedAgentIds ?? []) {
- this.roster().delete(agentId);
- }
- if (edgesFailed) {
- this.scheduleRosterRepairPull(worker);
- return;
- }
// A reseed keeps the previous claim and hydrated summary; a synthetic seed would drop
// lastActivityAt (pinning canEvictWorker on NaN) and flap the claim off on every snapshot.
// Only THIS worker's family reseeds: other families' rows are owned by their own workers or
@@ -3882,8 +3966,43 @@ export class DaemonSupervisor {
}
return current;
};
- for (const edge of edges) {
- if (rootPath === undefined || familyRoot(canonicalSessionPath(edge.child)) !== rootPath) continue;
+ const familyEdges = edges.filter(
+ (edge) => rootPath !== undefined && familyRoot(canonicalSessionPath(edge.child)) === rootPath,
+ );
+ const seedInfo = new Map<string, SessionInfo | null | undefined>();
+ for (const edge of familyEdges) {
+ const entry = this.rosterEntryForSpawnLedgerEdge(edge);
+ const childPath = canonicalSessionPath(edge.child);
+ const currentById = this.roster().get(entry.agentId);
+ const currentByFile = this.roster().bySessionFile(childPath);
+ const currentIdSurvives =
+ currentById !== undefined && !unclaimed.has(currentById.agentId) && !removed.has(currentById.agentId);
+ const currentFileSurvives =
+ currentByFile !== undefined && !unclaimed.has(currentByFile.agentId) && !removed.has(currentByFile.agentId);
+ if (
+ unclaimed.has(entry.agentId) ||
+ (sent.has(entry.agentId) && !removed.has(entry.agentId)) ||
+ currentIdSurvives ||
+ currentFileSurvives
+ ) {
+ continue;
+ }
+ seedInfo.set(entry.agentId, await readSessionInfo(edge.child).catch(() => undefined));
+ if (!this.isWorkerRosterApplyCurrent(worker, applySource)) return;
+ }
+
+ // Unreadable edges skip the absentee sweep: it cannot tell registry children from stale rows.
+ for (const entry of unclaimed.values()) this.roster().delete(entry.agentId);
+ for (const entry of delta.entries) {
+ this.writeRosterEntry(entry, worker);
+ this.syncRootDescriptorFromRosterEntry(worker, entry);
+ }
+ for (const agentId of removed) this.roster().delete(agentId);
+ if (edgesFailed) {
+ this.scheduleRosterRepairPull(worker);
+ return;
+ }
+ for (const edge of familyEdges) {
const entry = this.rosterEntryForSpawnLedgerEdge(edge);
if (this.roster().has(entry.agentId)) continue;
if (this.roster().hasSessionFile(canonicalSessionPath(edge.child))) continue;
@@ -3893,7 +4012,10 @@ export class DaemonSupervisor {
this.writeRosterEntry(rest, worker);
continue;
}
- this.roster().write({ ...entry, seededCwd: true });
+ const info = seedInfo.get(entry.agentId);
+ this.roster().write(
+ info ? { ...entry, summary: { ...entry.summary, cwd: info.cwd } } : { ...entry, seededCwd: true },
+ );
}
}
@@ -3929,8 +4051,7 @@ export class DaemonSupervisor {
private markWorkerRosterEntries(worker: ResidentWorker, statusLabel: "recovering" | "failed" | undefined): void {
for (const entry of this.workerRosterEntries(worker)) {
if (!entry.queuedChild && entry.summary.activeSessionId === undefined) continue;
- if (statusLabel === undefined) delete entry.statusLabel;
- else entry.statusLabel = statusLabel;
+ this.roster().amend(entry.agentId, { statusLabel });
}
}
@@ -3954,7 +4075,8 @@ export class DaemonSupervisor {
if (now - worker.lastFrameAt > ROSTER_STALE_AFTER_MS) {
const lastHeardFromAt = new Date(worker.lastFrameAt).toISOString();
for (const entry of this.workerRosterEntries(worker)) {
- entry.lastHeardFromAt = lastHeardFromAt;
+ // write() rebuilds rows without the mark; the sweep owns it and restamps only those.
+ if (entry.lastHeardFromAt !== lastHeardFromAt) this.roster().amend(entry.agentId, { lastHeardFromAt });
}
worker.rosterStale = true;
} else if (worker.rosterStale) {
@@ -3967,7 +4089,7 @@ export class DaemonSupervisor {
if (!worker.rosterStale) return;
worker.rosterStale = false;
for (const entry of this.workerRosterEntries(worker)) {
- delete entry.lastHeardFromAt;
+ this.roster().amend(entry.agentId, { lastHeardFromAt: undefined });
}
}
@@ -4048,11 +4170,12 @@ export class DaemonSupervisor {
assertAgentSessionNameAvailable(
siblings.map((info) => {
const summary = summaryForInactiveSession(info);
+ const ledgerRow = this.roster().bySessionFile(canonicalSessionPath(info.path));
return {
id: summary.sessionId,
...(summary.sessionName ? { name: summary.sessionName } : {}),
depth: setDepth,
- status: classifySessionRosterStatus(summary),
+ status: ledgerRow?.status ?? classifySessionRosterStatus(summary),
...(summary.parentSessionPath
? { parentSessionPath: canonicalSessionPath(summary.parentSessionPath) }
: {}),
@@ -4112,7 +4235,7 @@ export class DaemonSupervisor {
id: summary.sessionId,
...(summary.sessionName ? { name: summary.sessionName } : {}),
depth,
- status: classifySessionRosterStatus(summary),
+ status: summary.rosterStatus ?? classifySessionRosterStatus(summary),
...(depth > 0 && summary.parentSessionId ? { parentSessionId: summary.parentSessionId } : {}),
...(depth > 0 && summary.parentSessionPath
? { parentSessionPath: canonicalSessionPath(summary.parentSessionPath) }
@@ -4139,7 +4262,7 @@ export class DaemonSupervisor {
...(summary.parentSessionPath ? { parentSessionPath: summary.parentSessionPath } : {}),
...(summary.sessionFile ? { sessionPath: summary.sessionFile } : {}),
...(summary.rlmDepth !== undefined ? { rlmDepth: summary.rlmDepth } : {}),
- status: classifySessionRosterStatus(summary),
+ status: summary.rosterStatus ?? classifySessionRosterStatus(summary),
...(summary.rlmChildId ? { rlmChildId: summary.rlmChildId } : {}),
};
}
diff --git a/packages/coding-agent/src/modes/interactive/components/subagent-summary-line.ts b/packages/coding-agent/src/modes/interactive/components/subagent-summary-line.ts
index 73ac870d4b..0d8b7b44b0 100644
--- a/packages/coding-agent/src/modes/interactive/components/subagent-summary-line.ts
+++ b/packages/coding-agent/src/modes/interactive/components/subagent-summary-line.ts
@@ -1,6 +1,8 @@
import { type Component, type Focusable, getKeybindings, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
import type { AgentConnectionRlmChildAgentSnapshot } from "../../agent-connection/index.js";
+import { isDirectAgentChild } from "../../agents-view/agents-view-state.js";
import { type AgentRosterStatus, classifyAgentStatus } from "../../daemon/agent-roster.js";
+import { classifySessionRosterStatus, type SessionSummary } from "../../daemon/daemon-session-list.js";
import { theme } from "../theme/theme.js";
import { keyText } from "./keybinding-hints.js";
@@ -40,6 +42,25 @@ export function countDirectSubagentStatuses(
return counts;
}
+export function countRosterSubagentStatuses(
+ summaries: Iterable<SessionSummary>,
+ parent: { activeSessionId?: string | undefined; sessionId?: string | undefined; sessionFile?: string | undefined },
+ activeHeartbeatSessionIds: ReadonlySet<string>,
+): SubagentSummaryCounts {
+ const counts: SubagentSummaryCounts = { total: 0, running: 0, idle: 0, inactive: 0 };
+ for (const child of summaries) {
+ if (child.runtimeKind !== "subagent" || child.lifecycle !== "live") continue;
+ if (!isDirectAgentChild(child, parent)) continue;
+ counts.total += 1;
+ const status =
+ child.activeSessionId !== undefined && activeHeartbeatSessionIds.has(child.activeSessionId)
+ ? "running"
+ : (child.rosterStatus ?? classifySessionRosterStatus(child));
+ counts[status] += 1;
+ }
+ return counts;
+}
+
/** One-line entry into the current session's scoped agents view. */
export class SubagentSummaryLine implements Component, Focusable {
focused = false;
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index d7ef8c425b..b23ed23735 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -166,6 +166,7 @@ import type {
AgentConnectionToolDefinition,
} from "../agent-connection/index.js";
import { AgentConnectionPromptAdmissionError } from "../agent-connection/index.js";
+import type { SessionSummary } from "../daemon/daemon-session-list.js";
import { getModelArgumentCompletions } from "../model-autocomplete.js";
import {
checkForPackageUpdates,
@@ -222,7 +223,11 @@ import {
styleSlashCommandText,
} from "./components/slash-command-message.js";
import { SlashCommandResultMessageComponent } from "./components/slash-command-result-message.js";
-import { countDirectSubagentStatuses, SubagentSummaryLine } from "./components/subagent-summary-line.js";
+import {
+ countDirectSubagentStatuses,
+ countRosterSubagentStatuses,
+ SubagentSummaryLine,
+} from "./components/subagent-summary-line.js";
import { ThinkingSelectorComponent } from "./components/thinking-selector.js";
import {
selectLatestToolExpandHint,
@@ -974,6 +979,7 @@ export class InteractiveMode {
private subagentSummaryLine: SubagentSummaryLine;
private subagentSnapshots = new Map<string, AgentConnectionRlmChildAgentSnapshot>();
private rlmNodeId: string | undefined;
+ private rosterBar: { summaries(): SessionSummary[]; dispose(): Promise<void> } | undefined;
private toolOutputExpanded = false;
private agentMessagesExpanded = false;
@@ -2790,6 +2796,8 @@ export class InteractiveMode {
private async rebindCurrentSession(): Promise<void> {
this.unsubscribe?.();
this.unsubscribe = undefined;
+ void this.rosterBar?.dispose();
+ this.rosterBar = undefined;
if (this.localSessionHost) {
this.uiServices = this.localSessionHost.createUiServices();
}
@@ -2804,6 +2812,7 @@ export class InteractiveMode {
this.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });
}
this.subscribeToAgent();
+ await this.subscribeToRosterBar();
// A session_action_update in the unsubscribed gap above is lost; re-sync the queue post-subscription.
this.patchConnectionState({ sessionActions: (await this.agentConnection.getState()).sessionActions });
this.refreshQueueSelectionFromState();
@@ -5079,6 +5088,19 @@ export class InteractiveMode {
};
}
+ private async subscribeToRosterBar(): Promise<void> {
+ if (!this.agentConnection.subscribeAgentRoster) return;
+ try {
+ this.rosterBar = await this.agentConnection.subscribeAgentRoster(() => {
+ this.updateSubagentSummaryLine();
+ this.ui.requestRender();
+ });
+ } catch {
+ this.rosterBar = undefined;
+ }
+ this.updateSubagentSummaryLine();
+ }
+
private subscribeToAgent(): void {
this.unsubscribe = this.agentConnection.subscribe(async (event) => {
try {
@@ -5927,6 +5949,7 @@ export class InteractiveMode {
}
private updateSubagentSummary(child: AgentConnectionRlmChildAgentSnapshot): void {
+ // "cancelled" also covers never-bound terminal runs; AgentSession owns that rule.
if (child.status === "cancelled") {
this.removeSubagentSnapshot(child.id);
} else {
@@ -5951,8 +5974,23 @@ export class InteractiveMode {
.filter((heartbeat) => heartbeat.job.status === "active")
.map((heartbeat) => heartbeat.job.activeSessionId),
);
+ const rosterSummaries = this.rosterBar?.summaries();
+ // A client-owned session has no row on the public roster; only then do the
+ // snapshots carry the bar. A public parent with zero roster children shows zero.
+ const sessionOnRoster =
+ rosterSummaries?.some((row) => row.sessionId === this.connectionState?.sessionId) === true;
this.subagentSummaryLine.setSubagentCounts(
- countDirectSubagentStatuses(this.subagentSnapshots.values(), this.rlmNodeId, activeHeartbeatSessionIds),
+ rosterSummaries && sessionOnRoster
+ ? countRosterSubagentStatuses(
+ rosterSummaries,
+ {
+ activeSessionId: this.connectionState?.activeSessionId,
+ sessionId: this.connectionState?.sessionId,
+ sessionFile: this.connectionState?.sessionFile,
+ },
+ activeHeartbeatSessionIds,
+ )
+ : countDirectSubagentStatuses(this.subagentSnapshots.values(), this.rlmNodeId, activeHeartbeatSessionIds),
);
if (!this.subagentSummaryLine.isSelectable() && this.subagentSummaryLine.focused) this.focusEditor();
}
@@ -10023,6 +10061,8 @@ ${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}${shor
if (this.unsubscribe) {
this.unsubscribe();
}
+ void this.rosterBar?.dispose();
+ this.rosterBar = undefined;
if (this.isInitialized) {
this.ui.stop({
preserveAltScreen: options.preserveAltScreen,
diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.ts
index d085d010a2..d492e1bbc4 100644
--- a/packages/coding-agent/test/agent-session-recursion.test.ts
+++ b/packages/coding-agent/test/agent-session-recursion.test.ts
@@ -1255,6 +1255,12 @@ describe("AgentSession rlm recursion", () => {
deleteRlmSubagentRuntime: async () => {},
},
});
+ const childUpdates: Array<{ status: string; error?: string }> = [];
+ root.subscribe((event) => {
+ if (event.type === "rlm_child_update") {
+ childUpdates.push({ status: event.child.status, error: event.child.error });
+ }
+ });
const spawned = await root.runRlmChild("start failing child", { name: "failing-worker" });
await vi.waitFor(async () => {
@@ -1274,6 +1280,10 @@ describe("AgentSession rlm recursion", () => {
expect.objectContaining({ content: expect.stringContaining("kernel startup failed") }),
);
});
+ // A terminal run that never bound a session leaves no row anywhere: the
+ // terminal update is the cancelled removal signal and snapshots skip the run.
+ expect(childUpdates.at(-1)).toEqual({ status: "cancelled", error: "kernel startup failed" });
+ expect(root.getRlmChildSnapshots()).toEqual([]);
});
it("injects exactly one cancellation notice when a child run is cancelled", async () => {
diff --git a/packages/coding-agent/test/agents-view-inactive-reply.test.ts b/packages/coding-agent/test/agents-view-inactive-reply.test.ts
index e1733c40e0..ebe61af653 100644
--- a/packages/coding-agent/test/agents-view-inactive-reply.test.ts
+++ b/packages/coding-agent/test/agents-view-inactive-reply.test.ts
@@ -195,7 +195,7 @@ describe("agents view reply on inactive sessions", () => {
expect(self.replyTarget).toBe(newTarget);
expect(editor.getText()).toBe("new reply");
expect(self.setReplyTarget).not.toHaveBeenCalled();
- expect(self.refreshSessions).toHaveBeenCalledWith({ preserveStatusOnError: true });
+ expect(self.refreshSessions).toHaveBeenCalledWith();
});
it("preserves new text entered while the same reply succeeds", async () => {
@@ -266,7 +266,7 @@ describe("agents view reply on inactive sessions", () => {
expect(inactiveAgentIdentities.has("file:/tmp/sessions/saved-1.jsonl")).toBe(remainsInactive);
expect(self.refreshSessions).toHaveBeenCalledTimes(remainsInactive ? 0 : 1);
if (!remainsInactive) {
- expect(self.refreshSessions).toHaveBeenCalledWith({ preserveStatusOnError: true });
+ expect(self.refreshSessions).toHaveBeenCalledWith();
}
});
@@ -605,32 +605,114 @@ describe("agents view slash commands", () => {
expect(openSelected).toHaveBeenCalledTimes(2);
});
- it("renames a live target via the rename RPC and refreshes both catalogs", async () => {
+ it("renames a live target via the rename RPC and reapplies the pushed roster", async () => {
const live = summary({ activeSessionId: "active-1", lifecycle: "live" });
const request = vi.fn(async () => ({ success: true, data: {} }));
const editor = editorWithText("/name Fresh Name");
+ const setReplyTarget = vi.fn();
const self: Record<string, unknown> = {
options: {},
requireClient: () => ({ request }),
editor,
setStatusMessage: vi.fn(),
+ setReplyTarget,
+ persistentState: {},
refreshSessions: vi.fn(async () => true),
refreshSavedSessions: vi.fn(async () => true),
+ refreshSavedSessionsIfLoaded() {
+ return invoke("refreshSavedSessionsIfLoaded", self);
+ },
renameSession(s: unknown, n: string) {
return invoke("renameSession", self, s, n);
},
- refreshBothCatalogs() {
- return invoke("refreshBothCatalogs", self);
- },
};
+ self.replyTarget = { key: "active-1", summary: live };
await expect(invoke("runAgentsViewCommand", self, { name: "name", args: "Fresh Name" }, live)).resolves.toBe(
true,
);
expect(request).toHaveBeenCalledWith({ type: "rename", activeSessionId: "active-1", name: "Fresh Name" });
- expect(self.refreshSessions).toHaveBeenCalledWith({ preserveStatusOnError: true });
- expect(self.refreshSavedSessions).toHaveBeenCalledWith({ preserveStatusOnError: true });
+ // As in /kill: the completed command returns the composer to the list.
+ expect(setReplyTarget).toHaveBeenCalledWith(undefined);
+ // The push carries renames to the live catalog; the saved catalog refreshes only once it has loaded.
+ expect(self.refreshSessions).toHaveBeenCalledWith();
+ expect(self.refreshSavedSessions).not.toHaveBeenCalled();
+
+ (self.persistentState as { savedCatalogLoaded?: boolean }).savedCatalogLoaded = true;
+ await expect(invoke("renameSession", self, live, "Fresher Name")).resolves.toBe(true);
+ expect(self.refreshSavedSessions).toHaveBeenCalledTimes(1);
+ });
+
+ it("arms the saved-search fetch once and lets only the current fetch re-arm the latch", async () => {
+ const latchHarness = (text: string, responses: unknown[]) => {
+ const request = vi.fn(async () => responses.shift());
+ const persistentState: Record<string, unknown> = {};
+ const self: Record<string, unknown> = {
+ persistentState,
+ reconnectPromise: undefined,
+ daemonShutdownReceived: false,
+ savedCatalogGeneration: 0,
+ savedCatalogRefreshPending: false,
+ savedCatalogReady: false,
+ savedSessions: [],
+ lastSuccessfulSavedSessions: [],
+ savedSearchFetchStarted: false,
+ selectionAnchorPending: false,
+ reconcileCatalogs: vi.fn(),
+ resolveMissingSelectionAnchor: vi.fn(),
+ rebuildRows: vi.fn(),
+ syncSelectedRowState: vi.fn(),
+ ui: { requestRender: vi.fn() },
+ editor: editorWithText(text),
+ requireClient: () => ({ request }),
+ getSavedSessionCatalogContext: () => ({ cwd: "/tmp/project" }),
+ refreshSavedSessions: vi.fn((options?: unknown) => invoke("refreshSavedSessions", self, options)),
+ rearmSavedSearchFetch() {
+ return invoke("rearmSavedSearchFetch", self);
+ },
+ armSavedSearchFetch() {
+ return invoke("armSavedSearchFetch", self);
+ },
+ };
+ const supersede = () =>
+ (self.refreshSavedSessions as (options?: unknown) => Promise<boolean>)({ preserveStatusOnError: true });
+ return { self, persistentState, request, supersede };
+ };
+
+ // An empty query never arms; an already-loaded shared catalog never refetches.
+ const idle = latchHarness(" ", []);
+ invoke("armSavedSearchFetch", idle.self);
+ expect(idle.self.savedSearchFetchStarted).toBe(false);
+ const loaded = latchHarness("needle", []);
+ (loaded.persistentState as { savedCatalogLoaded?: boolean }).savedCatalogLoaded = true;
+ invoke("armSavedSearchFetch", loaded.self);
+ expect(loaded.request).not.toHaveBeenCalled();
+
+ // Failure ordering: a superseded settle may not disarm; only the current fetch re-arms.
+ let rejectFirst: (error: Error) => void = () => {};
+ let rejectSecond: (error: Error) => void = () => {};
+ const failing = latchHarness("deep search text", [
+ new Promise((_resolve, reject) => {
+ rejectFirst = reject;
+ }),
+ new Promise((_resolve, reject) => {
+ rejectSecond = reject;
+ }),
+ ]);
+ invoke("queryChanged", failing.self);
+ invoke("queryChanged", failing.self);
+ expect(failing.request).toHaveBeenCalledTimes(1);
+ const olderFailure = (failing.self.refreshSavedSessions as ReturnType<typeof vi.fn>).mock.results[0]
+ ?.value as Promise<boolean>;
+ const newerFailure = failing.supersede();
+ rejectFirst(new Error("gen1 failed"));
+ await expect(olderFailure).resolves.toBe(false);
+ expect(failing.self.savedSearchFetchStarted).toBe(true);
+ rejectSecond(new Error("gen2 failed"));
+ await expect(newerFailure).resolves.toBe(false);
+ expect(failing.self.savedSearchFetchStarted).toBe(false);
+ expect(failing.persistentState.savedCatalogLoaded).toBeUndefined();
});
it("kills a live target and disarms the composer", async () => {
@@ -643,14 +725,14 @@ describe("agents view slash commands", () => {
setStatusMessage: vi.fn(),
setReplyTarget,
replyTarget: { key: "active-1", summary: live },
- refreshBothCatalogs: vi.fn(async () => true),
+ refreshSessions: vi.fn(async () => true),
};
await invoke("runAgentsViewCommand", self, { name: "kill", args: "" }, live);
expect(request).toHaveBeenCalledWith({ type: "kill", activeSessionId: "active-1" });
expect(setReplyTarget).toHaveBeenCalledWith(undefined);
- expect(self.refreshBothCatalogs).toHaveBeenCalled();
+ expect(self.refreshSessions).toHaveBeenCalled();
// An agent that finished before the RPC still counts as stopped.
self.request = undefined;
@@ -677,7 +759,7 @@ describe("agents view slash commands", () => {
setStatusMessage: vi.fn(),
setReplyTarget,
replyTarget: originalTarget,
- refreshBothCatalogs: vi.fn(async () => true),
+ refreshSessions: vi.fn(async () => true),
};
await invoke("runAgentsViewCommand", self, { name: "kill", args: "" }, live);
diff --git a/packages/coding-agent/test/agents-view-mode.test.ts b/packages/coding-agent/test/agents-view-mode.test.ts
index d04a2b7a73..edffa07817 100644
--- a/packages/coding-agent/test/agents-view-mode.test.ts
+++ b/packages/coding-agent/test/agents-view-mode.test.ts
@@ -12,7 +12,11 @@ import {
createInitialAgentsViewPersistentState,
runAgentsViewMode,
} from "../src/modes/agents-view/agents-view-mode.js";
-import { type AgentsViewRow, resolveAgentsViewLeftResult } from "../src/modes/agents-view/agents-view-state.js";
+import {
+ type AgentsViewRow,
+ buildAgentsViewRows,
+ resolveAgentsViewLeftResult,
+} from "../src/modes/agents-view/agents-view-state.js";
import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
import type { InteractiveModeUiServices } from "../src/modes/interactive/interactive-mode-services.js";
import { stopThemeWatcher } from "../src/modes/interactive/theme/theme.js";
@@ -97,10 +101,14 @@ describe("AgentsViewMode", () => {
const self = {
editor: { getText: () => "matching query" },
persistentState: { query: "" },
+ savedSearchFetchStarted: true,
selectedIndex: 4,
rebuildRows: vi.fn(),
syncSelectedRowState: vi.fn(),
ui: { requestRender: vi.fn() },
+ armSavedSearchFetch(): void {
+ invoke("armSavedSearchFetch", self);
+ },
};
invoke("queryChanged", self);
@@ -431,8 +439,6 @@ describe("AgentsViewMode", () => {
heartbeats: [],
inactiveAgentIdentities: new Set(),
pendingDeleteAgent: undefined,
- liveCatalogReady: true,
- liveCatalogRefreshPending: false,
scopeKey: persistentState.scopeFrames?.[0]?.scope,
expandedSubagentParents: new Set(),
programShownParents: new Set(),
@@ -486,7 +492,6 @@ describe("AgentsViewMode", () => {
heartbeats: [],
inactiveAgentIdentities: new Set(),
pendingDeleteAgent: undefined,
- liveCatalogReady: true,
savedCatalogReady: true,
scopeKey: persistentState.scopeFrames?.[0]?.scope,
expandedSubagentParents: new Set(),
@@ -574,7 +579,6 @@ describe("AgentsViewMode", () => {
heartbeats: [],
inactiveAgentIdentities: new Set(),
pendingDeleteAgent: undefined,
- liveCatalogReady: true,
savedCatalogReady: true,
expandedSubagentParents,
programShownParents: new Set(),
@@ -648,6 +652,26 @@ describe("AgentsViewMode", () => {
expect(programShownParents.size).toBe(0);
expect(self.rebuildRows).toHaveBeenCalledTimes(2);
});
+
+ it("renders roster recovery and stale-worker status labels", () => {
+ const rows = buildAgentsViewRows([
+ summary({ id: "recovering", sessionId: "recovering", statusLabel: "recovering" }),
+ summary({
+ id: "stale",
+ sessionId: "stale",
+ lastHeardFromAt: new Date(Date.now() - 60_000).toISOString(),
+ }),
+ ]);
+ const view = new AgentsViewMode({ config: {}, uiServices: createUiServices() }, {});
+ Reflect.set(view, "rows", rows);
+
+ try {
+ expect(invoke("renderRow", view, rows[0], 160)).toContain("recovering");
+ expect(invoke("renderRow", view, rows[1], 160)).toContain("last heard");
+ } finally {
+ stopThemeWatcher();
+ }
+ });
});
function createUiServices(): InteractiveModeUiServices {
@@ -665,7 +689,19 @@ afterEach(() => {
});
describe("AgentsViewMode persistent catalog state", () => {
- it("keeps an initial handoff scope when the first live poll fails after both catalogs settle", async () => {
+ it("treats only a previously loaded saved catalog as settled on mount", () => {
+ const fresh = new AgentsViewMode({ config: {}, uiServices: createUiServices() }, {});
+ const loaded = new AgentsViewMode({ config: {}, uiServices: createUiServices() }, { savedCatalogLoaded: true });
+
+ try {
+ expect(Reflect.get(fresh, "savedCatalogReady")).toBe(false);
+ expect(Reflect.get(loaded, "savedCatalogReady")).toBe(true);
+ } finally {
+ stopThemeWatcher();
+ }
+ });
+
+ it("applies an initial handoff scope from the first pushed roster refresh", async () => {
const root = summary();
const scope = { sessionId: root.sessionId, activeSessionId: root.activeSessionId };
const persistentState = createInitialAgentsViewPersistentState({
@@ -674,17 +710,11 @@ describe("AgentsViewMode persistent catalog state", () => {
});
persistentState.lastSuccessfulSavedSessions = [];
const view = new AgentsViewMode({ config: {}, uiServices: createUiServices() }, persistentState);
- Reflect.set(view, "client", {
- isConnected: true,
- request: vi.fn(async () => {
- throw new Error("transient list failure");
- }),
- });
+ Reflect.set(view, "rosterStore", { summaries: () => [root] });
+ Reflect.set(view, "savedCatalogReady", true);
try {
- await expect(invoke("refreshSessions", view, { preserveStatusOnError: true })).resolves.toBe(false);
- expect(Reflect.get(view, "liveCatalogReady")).toBe(true);
- expect(Reflect.get(view, "savedCatalogReady")).toBe(true);
+ await expect(invoke("refreshSessions", view)).resolves.toBeUndefined();
expect(persistentState.scopeFrames).toEqual([{ scope, returnChat: root }]);
expect(persistentState.lastSuccessfulLiveSummaries).toEqual([root]);
} finally {
@@ -692,6 +722,37 @@ describe("AgentsViewMode persistent catalog state", () => {
}
});
+ it("re-arms reconnect from the heartbeat poll over a dead socket and never overwrites a sticky notice", async () => {
+ const harness = (isConnected: boolean, statusMessageSticky: boolean) => {
+ const client = {
+ isConnected,
+ request: vi.fn(async () => {
+ throw new Error("heartbeats unavailable");
+ }),
+ };
+ return {
+ client,
+ heartbeatCatalogGeneration: 0,
+ reconnectPromise: undefined,
+ daemonShutdownReceived: false,
+ statusMessageSticky,
+ requireClient: () => client,
+ startClientReconnect: vi.fn(),
+ setStatusMessage: vi.fn(),
+ };
+ };
+
+ const reconnecting = harness(false, false);
+ await expect(invoke("refreshHeartbeats", reconnecting)).resolves.toBe(false);
+ expect(reconnecting.startClientReconnect).toHaveBeenCalledWith(reconnecting.client, expect.any(Error));
+ expect(reconnecting.setStatusMessage).not.toHaveBeenCalled();
+
+ const sticky = harness(true, true);
+ await expect(invoke("refreshHeartbeats", sticky)).resolves.toBe(false);
+ expect(sticky.startClientReconnect).not.toHaveBeenCalled();
+ expect(sticky.setStatusMessage).not.toHaveBeenCalled();
+ });
+
it("keeps a live-only scope after a fresh instance's first live poll fails", async () => {
const root = summary({
id: "root-active",
@@ -715,7 +776,7 @@ describe("AgentsViewMode persistent catalog state", () => {
});
try {
- await expect(invoke("refreshSessions", view, { preserveStatusOnError: true })).resolves.toBe(false);
+ await expect(invoke("refreshSessions", view, { preserveStatusOnError: true })).resolves.toBeUndefined();
expect(persistentState.scopeFrames).toEqual([
{ scope: { sessionId: root.sessionId, activeSessionId: root.activeSessionId } },
]);
@@ -739,7 +800,6 @@ describe("AgentsViewMode persistent catalog state", () => {
);
const client = { isConnected: false, reconnect: vi.fn() };
Reflect.set(view, "client", client);
- Reflect.set(view, "liveCatalogReady", true);
Reflect.set(view, "savedCatalogReady", true);
try {
@@ -747,17 +807,51 @@ describe("AgentsViewMode persistent catalog state", () => {
expect(persistentState.scopeFrames).toEqual([frame]);
expect(Reflect.get(view, "lastListedSummaries")).toEqual([root]);
- Reflect.set(view, "client", {
- isConnected: true,
- request: vi.fn(async () => ({ success: true, data: { sessions: [] } })),
- });
- await expect(invoke("refreshSessions", view)).resolves.toBe(true);
+ Reflect.set(view, "client", { isConnected: true });
+ Reflect.set(view, "rosterStore", { summaries: () => [] });
+ await expect(invoke("refreshSessions", view)).resolves.toBeUndefined();
expect(persistentState.scopeFrames).toEqual([]);
} finally {
vi.useRealTimers();
}
});
+ it("applies the roster snapshot produced during reconnect heartbeat refresh", async () => {
+ const beforeRefresh = summary({ id: "before", sessionId: "before" });
+ const afterRefresh = summary({ id: "after", sessionId: "after" });
+ let current = [beforeRefresh];
+ let finishHeartbeatRefresh: (() => void) | undefined;
+ const heartbeatRefresh = new Promise<void>((resolve) => {
+ finishHeartbeatRefresh = resolve;
+ });
+ const client = { reconnect: vi.fn(async () => undefined) };
+ const self = {
+ options: { recoverDaemon: vi.fn(async () => undefined) },
+ client,
+ rosterStore: {
+ attach: vi.fn(async () => true),
+ summaries: vi.fn(() => current),
+ },
+ refreshHeartbeats: vi.fn(async () => {
+ await heartbeatRefresh;
+ return true;
+ }),
+ daemonShutdownReceived: false,
+ reconnectTimedOut: true,
+ setStatusMessage: vi.fn(),
+ applySessionList: vi.fn(),
+ armSavedSearchFetch: vi.fn(),
+ };
+
+ const reconnect = invoke("reconnectClient", self, client, new Error("disconnected")) as Promise<void>;
+ await vi.waitFor(() => expect(self.refreshHeartbeats).toHaveBeenCalledOnce());
+ current = [afterRefresh];
+ finishHeartbeatRefresh?.();
+ await reconnect;
+
+ expect(self.applySessionList).toHaveBeenCalledWith([afterRefresh], true);
+ });
+
it("keeps a newly pushed scope and the existing live cache when its first poll fails", async () => {
const root = summary();
const other = summary({ id: "other-active", activeSessionId: "other-active", sessionId: "other-session" });
@@ -780,7 +874,7 @@ describe("AgentsViewMode persistent catalog state", () => {
throw new Error("transient list failure");
}),
});
- await expect(invoke("refreshSessions", this, { preserveStatusOnError: true })).resolves.toBe(false);
+ await expect(invoke("refreshSessions", this, { preserveStatusOnError: true })).resolves.toBeUndefined();
expect(persistentState.scopeFrames).toEqual([{ scope, returnChat: returnedRoot }]);
return { type: "exit" };
});
diff --git a/packages/coding-agent/test/agents-view-roster.test.ts b/packages/coding-agent/test/agents-view-roster.test.ts
new file mode 100644
index 0000000000..ac511eea29
--- /dev/null
+++ b/packages/coding-agent/test/agents-view-roster.test.ts
@@ -0,0 +1,589 @@
+import { EventEmitter } from "node:events";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { DaemonAgentConnection } from "../src/modes/agent-connection/daemon-agent-connection.js";
+import { buildAgentsViewRows } from "../src/modes/agents-view/agents-view-state.js";
+import { AgentsViewRosterStore } from "../src/modes/agents-view/roster-store.js";
+import {
+ type AgentRosterEntry,
+ sessionSummaryFromRosterEntry,
+ type WorkerRosterEntry,
+ workerRosterEntryFromSummary,
+} from "../src/modes/daemon/agent-roster.js";
+import { DaemonCatalogClient } from "../src/modes/daemon/daemon-catalog-process.js";
+import { DaemonClient } from "../src/modes/daemon/daemon-client.js";
+import type { DaemonOutbound } from "../src/modes/daemon/daemon-protocol.js";
+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
+import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";
+import { RlmSpawnLedger } from "../src/modes/daemon/rlm-ledger.js";
+import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
+
+const tempDirs: string[] = [];
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const directory of tempDirs.splice(0)) rmSync(directory, { recursive: true, force: true });
+});
+
+function summary(overrides: Partial<SessionSummary> & Pick<SessionSummary, "id" | "sessionId">): SessionSummary {
+ return {
+ lifecycle: "live",
+ activity: "idle",
+ isSessionActive: false,
+ cwd: "/tmp/project",
+ isStreaming: false,
+ isCompacting: false,
+ attachedClients: 0,
+ messageCount: 1,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
+ ...overrides,
+ };
+}
+
+function ledgerEntry(
+ overrides: Partial<SessionSummary> & Pick<SessionSummary, "id" | "sessionId">,
+ roster: Partial<Pick<AgentRosterEntry, "status" | "statusLabel" | "lastHeardFromAt" | "queuedChild">> = {},
+): AgentRosterEntry {
+ const base = workerRosterEntryFromSummary(summary(overrides));
+ return { ...base, status: roster.status ?? "idle", ...roster };
+}
+
+type FakeClient = {
+ supportsServerCapability: (capability: string) => boolean;
+ isConnected: boolean;
+ hello: object;
+ onMessage: (listener: (message: DaemonOutbound) => void) => () => void;
+ request: ReturnType<typeof vi.fn>;
+ emit: (message: DaemonOutbound) => void;
+};
+
+function fakeRosterClient(roster: AgentRosterEntry[], supported = true): FakeClient {
+ const listeners = new Set<(message: DaemonOutbound) => void>();
+ return {
+ supportsServerCapability: () => supported,
+ isConnected: true,
+ hello: { type: "daemon_hello" },
+ onMessage: (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ request: vi.fn(async (command: { type: string }) => {
+ if (command.type === "roster_subscribe") {
+ return { type: "response", command: command.type, success: true, data: { roster } };
+ }
+ return { type: "response", command: command.type, success: true };
+ }),
+ emit: (message) => {
+ for (const listener of listeners) listener(message);
+ },
+ };
+}
+
+describe("agents-view roster store", () => {
+ it("owns the subscription lifecycle: capability miss, raced pushes, hello re-key, attach/dispose races", async () => {
+ const unsupported = fakeRosterClient([], false);
+ await expect(new AgentsViewRosterStore().attach(unsupported as never)).resolves.toBe(false);
+ expect(unsupported.request).not.toHaveBeenCalled();
+
+ const client = fakeRosterClient([ledgerEntry({ id: "a", sessionId: "a" })]);
+ const store = new AgentsViewRosterStore();
+ client.request.mockImplementationOnce(async (command: { type: string }) => {
+ // Newer pushes land while the subscribe reply is still in flight.
+ client.emit({ type: "roster_update", changed: [], removed: ["a"] });
+ client.emit({ type: "roster_update", changed: [ledgerEntry({ id: "b", sessionId: "b" })] });
+ return {
+ type: "response",
+ command: command.type,
+ success: true,
+ data: { roster: [ledgerEntry({ id: "a", sessionId: "a" })] },
+ };
+ });
+ await expect(store.attach(client as never)).resolves.toBe(true);
+ expect(store.summaries().map((entry) => entry.sessionId)).toEqual(["b"]);
+ // A same-hello re-attach is request-free; a new hello re-subscribes.
+ await expect(store.attach(client as never)).resolves.toBe(true);
+ expect(client.request).toHaveBeenCalledTimes(1);
+ client.hello = { type: "daemon_hello" };
+ await expect(store.attach(client as never)).resolves.toBe(true);
+ expect(client.request).toHaveBeenCalledTimes(2);
+ // The re-subscribe resynced from the daemon's snapshot.
+ expect(store.summaries().map((entry) => entry.sessionId)).toEqual(["a"]);
+
+ const listener = vi.fn();
+ // A throwing consumer must not break delivery to the others (or the process).
+ store.onUpdate(() => {
+ throw new Error("consumer exploded");
+ });
+ store.onUpdate(listener);
+ client.emit({
+ type: "roster_update",
+ changed: [ledgerEntry({ id: "c", sessionId: "c" }, { status: "running" })],
+ });
+ client.emit({ type: "roster_update", changed: [], removed: ["a"] });
+ expect(store.summaries().map((entry) => entry.sessionId)).toEqual(["c"]);
+ expect(store.summaries()[0]?.rosterStatus).toBe("running");
+ client.emit({ type: "roster_update", changed: [ledgerEntry({ id: "d", sessionId: "d" })], resync: true });
+ expect(store.summaries().map((entry) => entry.sessionId)).toEqual(["d"]);
+ await Promise.resolve();
+ expect(listener).toHaveBeenCalledTimes(1);
+
+ // Overlapping attaches serialize: a stale failure cannot drop the winner's listener.
+ let releaseStale: (response: unknown) => void = () => {};
+ client.hello = { type: "daemon_hello" };
+ client.request.mockImplementationOnce(
+ () =>
+ new Promise((resolveStale) => {
+ releaseStale = resolveStale;
+ }) as never,
+ );
+ const stale = store.attach(client as never);
+ const winner = store.attach(client as never);
+ await vi.waitFor(() => expect(client.request).toHaveBeenCalledTimes(3));
+ releaseStale({ success: false, error: "stale socket" });
+ await expect(stale).rejects.toThrow("roster_subscribe failed");
+ await expect(winner).resolves.toBe(true);
+ client.emit({ type: "roster_update", changed: [ledgerEntry({ id: "e", sessionId: "e" })] });
+ expect(store.summaries().some((entry) => entry.sessionId === "e")).toBe(true);
+
+ // Dispose detaches the listener and skips the unsubscribe RPC on a closed client.
+ client.isConnected = false;
+ const requests = client.request.mock.calls.length;
+ await store.dispose();
+ expect(client.request.mock.calls.length).toBe(requests);
+ client.emit({ type: "roster_update", changed: [ledgerEntry({ id: "f", sessionId: "f" })] });
+ expect(store.summaries().some((entry) => entry.sessionId === "f")).toBe(false);
+ });
+
+ it("keeps a recovered session attach alive when the roster subscribe fails", async () => {
+ const client = fakeRosterClient([ledgerEntry({ id: "a", sessionId: "a" })]);
+ client.request.mockImplementation(async (command: { type: string }) => {
+ if (command.type === "roster_subscribe") {
+ return { type: "response", command: command.type, success: false, error: "subscribe timed out" };
+ }
+ return {
+ type: "response",
+ command: command.type,
+ success: true,
+ data: { id: "root-active", sessionId: "root", activeSessionId: "root-active" },
+ };
+ });
+ const store = new AgentsViewRosterStore();
+ const connection = Object.assign(Object.create(DaemonAgentConnection.prototype), {
+ options: {},
+ client,
+ rosterStore: store,
+ activeSessionId: "root-active",
+ lastEventSequence: undefined,
+ lastEventCursor: undefined,
+ requestData: vi.fn(async () => ({ id: "root-active", sessionId: "root", activeSessionId: "root-active" })),
+ }) as DaemonAgentConnection;
+
+ // The bar is an accessory: the session recovery must not fail with it.
+ await expect(connection.attach()).resolves.toBeUndefined();
+
+ // The seam self-heals: a later attach through the same store subscribes again.
+ client.request.mockImplementation(async (command: { type: string }) => ({
+ type: "response",
+ command: command.type,
+ success: true,
+ data: { roster: [ledgerEntry({ id: "a", sessionId: "a" })] },
+ }));
+ await expect(store.attach(client as never)).resolves.toBe(true);
+ expect(store.summaries().map((entry) => entry.sessionId)).toEqual(["a"]);
+ });
+});
+
+describe("roster-driven agents view rows", () => {
+ it("labels queued and stale rows from ledger state and keeps one identity across the bind push", () => {
+ const queued = ledgerEntry(
+ {
+ id: "child-1",
+ sessionId: "child-1",
+ runtimeKind: "subagent",
+ rlmChildId: "child-1",
+ parentSessionId: "root-session",
+ messageCount: 0,
+ firstMessage: "review the API",
+ },
+ { status: "running", statusLabel: "queued", queuedChild: true },
+ );
+ const root = ledgerEntry({ id: "root-active", sessionId: "root-session", activeSessionId: "root-active" });
+ const stale = ledgerEntry(
+ { id: "s-active", sessionId: "s", activeSessionId: "s-active" },
+ { status: "idle", lastHeardFromAt: new Date(Date.now() - 60_000).toISOString() },
+ );
+
+ const summaries = [root, queued, stale].map((entry) => sessionSummaryFromRosterEntry(entry));
+ const rootIdentity = buildAgentsViewRows(summaries).find(
+ (row) => row.summary.sessionId === "root-session",
+ )?.identity;
+ if (!rootIdentity) throw new Error("Missing root row");
+ const rows = buildAgentsViewRows(summaries, new Set([rootIdentity]));
+ expect(rows.find((row) => row.summary.rlmChildId === "child-1")).toMatchObject({
+ section: "running",
+ statusLabel: "queued",
+ });
+ expect(rows.find((row) => row.summary.sessionId === "s")?.statusLabel).toMatch(/^last heard \d+(s|m|h) ago$/);
+
+ const bound = sessionSummaryFromRosterEntry(
+ ledgerEntry(
+ {
+ id: "child-active",
+ sessionId: "child-session",
+ activeSessionId: "child-active",
+ sessionFile: "/tmp/artifacts/child.jsonl",
+ runtimeKind: "subagent",
+ rlmChildId: "child-1",
+ parentSessionId: "root-session",
+ },
+ { status: "running" },
+ ),
+ );
+ const queuedOnly = buildAgentsViewRows([sessionSummaryFromRosterEntry(queued)]);
+ const boundOnly = buildAgentsViewRows([bound]);
+ expect(queuedOnly[0]?.identity).toBe(boundOnly[0]?.identity);
+ });
+});
+
+describe("supervisor roster subscription", () => {
+ it("seeds, coalesces, skips unsubscribed clients, and feeds the chat bar over one real socket", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-roster-push-"));
+ tempDirs.push(directory);
+ const socketPath = join(directory, "daemon.sock");
+ const supervisor = new DaemonSupervisor(socketPath, {
+ defaultSessionConfig: { agentDir: directory, cwd: directory },
+ descriptorDir: join(directory, "workers"),
+ });
+ const internals = supervisor as unknown as {
+ start(): Promise<void>;
+ cleanupSupervisorResources(): Promise<void>;
+ writeRosterEntry(entry: WorkerRosterEntry): AgentRosterEntry;
+ roster(): { delete(agentId: string): void };
+ };
+ vi.spyOn(DaemonCatalogClient.prototype, "start").mockResolvedValue();
+ const client = new DaemonClient(socketPath);
+ const bystander = new DaemonClient(socketPath);
+ const barChild = (id: string, overrides: Partial<SessionSummary> = {}) =>
+ workerRosterEntryFromSummary(
+ summary({
+ id,
+ sessionId: id,
+ runtimeKind: "subagent",
+ rlmChildId: id,
+ parentActiveSessionId: "parent-active",
+ ...overrides,
+ }),
+ );
+ try {
+ await internals.start();
+ internals.writeRosterEntry(
+ workerRosterEntryFromSummary(summary({ id: "seeded", sessionId: "seeded", sessionFile: "/tmp/s.jsonl" })),
+ );
+ await client.connect();
+ await client.waitForHello();
+ expect(client.supportsServerCapability("agent_roster")).toBe(true);
+ const updates: Array<Extract<DaemonOutbound, { type: "roster_update" }>> = [];
+ client.onMessage((message) => {
+ if (message.type === "roster_update") updates.push(message);
+ });
+ await bystander.connect();
+ await bystander.waitForHello();
+ const bystanderUpdates: DaemonOutbound["type"][] = [];
+ bystander.onMessage((message) => {
+ if (message.type === "roster_update") bystanderUpdates.push(message.type);
+ });
+
+ const subscribed = await client.request({ type: "roster_subscribe" });
+ if (!subscribed.success) throw new Error(subscribed.error);
+ expect((subscribed.data as { roster: AgentRosterEntry[] }).roster.map((entry) => entry.agentId)).toEqual([
+ "seeded",
+ ]);
+
+ internals.writeRosterEntry(
+ workerRosterEntryFromSummary(
+ summary({ id: "a-active", sessionId: "a", activeSessionId: "a-active", isSessionActive: true }),
+ ),
+ );
+ internals.writeRosterEntry(workerRosterEntryFromSummary(summary({ id: "b", sessionId: "b" })));
+ internals.roster().delete("seeded");
+ await vi.waitFor(() => expect(updates.length).toBeGreaterThan(0));
+ expect(updates).toHaveLength(1);
+ expect(updates[0]?.changed.map((entry) => entry.agentId).sort()).toEqual(["a", "b"]);
+ expect(updates[0]?.changed.find((entry) => entry.agentId === "a")?.status).toBe("running");
+ expect(updates[0]?.removed).toEqual(["seeded"]);
+ expect(bystanderUpdates).toEqual([]);
+
+ // The chat bar rides the same push surface through its own connection; a
+ // public parent has its own roster row alongside its children.
+ internals.writeRosterEntry(
+ workerRosterEntryFromSummary(
+ summary({ id: "parent-active", sessionId: "parent", activeSessionId: "parent-active" }),
+ ),
+ );
+ internals.writeRosterEntry(barChild("child-a", { activeSessionId: "child-a-active", isSessionActive: true }));
+ const barClient = new DaemonClient(socketPath);
+ await barClient.connect();
+ await barClient.waitForHello();
+ const connection = new DaemonAgentConnection(barClient, "parent-active");
+ const setSubagentCounts = vi.fn();
+ const bar = Object.assign(Object.create(InteractiveMode.prototype), {
+ agentConnection: connection,
+ connectionState: { activeSessionId: "parent-active", sessionId: "parent" },
+ // A stale snapshot claims one lone running child; a nonempty roster must win.
+ subagentSnapshots: new Map([
+ ["stale", { id: "stale", label: "stale", status: "running", sessionDir: "/tmp" }],
+ ]),
+ rlmNodeId: undefined,
+ heartbeatCatalog: [],
+ subagentSummaryLine: { setSubagentCounts, isSelectable: () => false, focused: false },
+ scheduleHeartbeatManagerRefresh: vi.fn(),
+ updateWorkingPulse: vi.fn(),
+ syncWorkingLoader: vi.fn(),
+ updateWorkingLoaderMessage: vi.fn(),
+ ui: { requestRender: vi.fn() },
+ }) as unknown as {
+ subscribeToRosterBar(): Promise<void>;
+ updateSubagentSummaryLine(): void;
+ connectionState: object;
+ ui: { requestRender: ReturnType<typeof vi.fn> };
+ };
+ try {
+ await bar.subscribeToRosterBar();
+ expect(setSubagentCounts).toHaveBeenLastCalledWith({ total: 1, running: 1, idle: 0, inactive: 0 });
+ bar.ui.requestRender.mockClear();
+
+ internals.writeRosterEntry(barChild("child-b", { sessionFile: "/tmp/child-b.jsonl" }));
+ await vi.waitFor(() =>
+ expect(setSubagentCounts).toHaveBeenLastCalledWith({ total: 2, running: 1, idle: 0, inactive: 1 }),
+ );
+ // A push with no accompanying session event must still repaint.
+ expect(bar.ui.requestRender).toHaveBeenCalled();
+
+ // A client-owned session has no public roster row: the bar falls back to snapshots.
+ bar.connectionState = { activeSessionId: "owned-active", sessionId: "owned" };
+ bar.updateSubagentSummaryLine();
+ expect(setSubagentCounts).toHaveBeenLastCalledWith({ total: 1, running: 1, idle: 0, inactive: 0 });
+
+ // A public parent whose children all left the roster shows zero, never stale snapshots.
+ bar.connectionState = { activeSessionId: "parent2-active", sessionId: "parent2" };
+ internals.writeRosterEntry(
+ workerRosterEntryFromSummary(
+ summary({ id: "parent2-active", sessionId: "parent2", activeSessionId: "parent2-active" }),
+ ),
+ );
+ await vi.waitFor(() =>
+ expect(setSubagentCounts).toHaveBeenLastCalledWith({ total: 0, running: 0, idle: 0, inactive: 0 }),
+ );
+ } finally {
+ barClient.close();
+ }
+ } finally {
+ client.close();
+ bystander.close();
+ await internals.cleanupSupervisorResources();
+ }
+ });
+});
+
+describe("subscriber push transitions", () => {
+ function makePushSupervisor(extra: Record<string, unknown> = {}) {
+ const pushes: Array<Extract<DaemonOutbound, { type: "roster_update" }>> = [];
+ const write = vi.fn((_client: object, message: DaemonOutbound) => {
+ if (message.type === "roster_update") pushes.push(message);
+ return true;
+ });
+ const subscriber = { id: "sub", rosterSubscribed: true, backpressured: false };
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map(),
+ clients: new Set([subscriber]),
+ pendingRosterChanged: new Set(),
+ publishedRosterIds: new Set(),
+ pendingRosterRemoved: new Set(),
+ rosterPushScheduled: false,
+ persistWorker: vi.fn(),
+ write,
+ log: vi.fn(),
+ ...extra,
+ }) as {
+ workers: Map<string, unknown>;
+ writeRosterEntry(entry: unknown, worker?: unknown): AgentRosterEntry;
+ workerRosterEntries(worker: unknown): AgentRosterEntry[];
+ sweepRosterStaleness(now?: number): void;
+ promoteOwnedWorker(client: object, worker: unknown): Promise<void>;
+ roster(): { delete(agentId: string): void };
+ };
+ const settle = async () => {
+ await new Promise((resolve) => setImmediate(resolve));
+ };
+ return { supervisor, pushes, settle, subscriber };
+ }
+
+ function pushWorker(workerId: string, ownerClientId?: string) {
+ return {
+ descriptor: { workerId, pid: 1, rootActiveSessionId: `${workerId}-root`, lifecycle: "ready", ownerClientId },
+ client: {},
+ intentionalStop: false,
+ };
+ }
+
+ it("restamps last-heard marks that a row-rebuilding write dropped, and clears them on recovery", async () => {
+ const { supervisor, pushes, settle } = makePushSupervisor();
+ const now = Date.parse("2026-08-01T12:00:00.000Z");
+ const worker = { ...pushWorker("w1"), lastFrameAt: now - 60_000 };
+ supervisor.workers.set("w1", worker);
+ const entry = workerRosterEntryFromSummary(
+ summary({ id: "s-active", sessionId: "s", activeSessionId: "s-active" }),
+ );
+ supervisor.writeRosterEntry(entry, worker);
+ supervisor.sweepRosterStaleness(now);
+ await settle();
+ const stamp = new Date(now - 60_000).toISOString();
+ expect(pushes.at(-1)?.changed[0]?.lastHeardFromAt).toBe(stamp);
+
+ // A repeat sweep of an already-stamped row emits nothing.
+ pushes.length = 0;
+ supervisor.sweepRosterStaleness(now + 1000);
+ await settle();
+ expect(pushes).toEqual([]);
+
+ // A gap-fill write rebuilds the row without the mark; the next sweep restamps it.
+ supervisor.writeRosterEntry(entry, worker);
+ await settle();
+ expect(pushes.at(-1)?.changed[0]?.lastHeardFromAt).toBeUndefined();
+ supervisor.sweepRosterStaleness(now + 2000);
+ await settle();
+ expect(pushes.at(-1)?.changed[0]?.lastHeardFromAt).toBe(stamp);
+
+ worker.lastFrameAt = now;
+ supervisor.sweepRosterStaleness(now);
+ await settle();
+ expect(pushes.at(-1)?.changed[0]?.lastHeardFromAt).toBeUndefined();
+ });
+
+ it("removes a claimed row once, stays silent for owned-worker writes, and re-publishes on promotion", async () => {
+ const { supervisor, pushes, settle } = makePushSupervisor({
+ protocolClientIds: new WeakMap(),
+ });
+ const owned = pushWorker("w1", "owner-1");
+ supervisor.workers.set("w1", owned);
+ // A row born to a client-owned worker is never published: no push, no id leak.
+ const bornOwned = workerRosterEntryFromSummary(
+ summary({ id: "p-active", sessionId: "p", activeSessionId: "p-active", sessionFile: "/tmp/p.jsonl" }),
+ );
+ supervisor.writeRosterEntry(bornOwned, owned);
+ await settle();
+ expect(pushes).toEqual([]);
+
+ const entry = workerRosterEntryFromSummary(
+ summary({ id: "o-active", sessionId: "o", activeSessionId: "o-active", sessionFile: "/tmp/o.jsonl" }),
+ );
+ supervisor.writeRosterEntry(entry);
+ await settle();
+ pushes.length = 0;
+
+ supervisor.writeRosterEntry(entry, owned);
+ await settle();
+ expect(pushes.at(-1)?.removed).toEqual([entry.agentId]);
+ expect(pushes.at(-1)?.changed).toEqual([]);
+
+ pushes.length = 0;
+ supervisor.writeRosterEntry(entry, owned);
+ supervisor.writeRosterEntry(bornOwned, owned);
+ await settle();
+ expect(pushes).toEqual([]);
+
+ await supervisor.promoteOwnedWorker({ id: "owner-1" }, owned);
+ await settle();
+ expect(
+ pushes
+ .at(-1)
+ ?.changed.map((changedEntry) => changedEntry.agentId)
+ .sort(),
+ ).toEqual([bornOwned.agentId, entry.agentId].sort());
+ });
+
+ it("never surfaces a live edge as a transient removal during a snapshot apply", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-roster-flicker-"));
+ tempDirs.push(directory);
+ const sessionsDir = join(directory, "sessions");
+ const ledger = new RlmSpawnLedger(directory, sessionsDir);
+ const parentPath = join(sessionsDir, "root.jsonl");
+ const childPath = join(directory, "artifacts", "live-child.jsonl");
+ mkdirSync(sessionsDir, { recursive: true });
+ mkdirSync(join(directory, "artifacts"), { recursive: true });
+ writeFileSync(parentPath, "");
+ writeFileSync(childPath, "");
+ await ledger.appendSpawn({ childId: "live-child", parent: parentPath, child: childPath, depth: 1, name: "c" });
+ const { supervisor, pushes, settle } = makePushSupervisor({
+ rlmSpawnLedger: () => ledger,
+ defaultSessionConfig: { agentDir: directory, cwd: directory },
+ });
+ // Reseeds are family-scoped: the worker must own the family root it snapshots for.
+ const worker = { ...pushWorker("w1"), descriptor: { ...pushWorker("w1").descriptor, sessionFile: parentPath } };
+ supervisor.workers.set("w1", worker);
+ const childEntry = workerRosterEntryFromSummary(
+ summary({
+ id: "live-child",
+ sessionId: "live-child",
+ sessionFile: childPath,
+ runtimeKind: "subagent",
+ rlmChildId: "live-child",
+ parentSessionPath: parentPath,
+ }),
+ );
+ supervisor.writeRosterEntry(childEntry, worker);
+ await settle();
+ pushes.length = 0;
+
+ const internals = supervisor as unknown as {
+ consumeWorkerRosterDelta(worker: object, payload: Buffer): void;
+ };
+ internals.consumeWorkerRosterDelta(
+ worker,
+ Buffer.from(JSON.stringify({ type: "roster_delta", entries: [], snapshot: true })),
+ );
+ await vi.waitFor(() => expect(pushes.length).toBeGreaterThan(0));
+ await settle();
+
+ expect(pushes.some((push) => push.removed?.includes(childEntry.agentId))).toBe(false);
+ expect(
+ pushes.flatMap((push) => push.changed).find((entry) => entry.agentId === childEntry.agentId),
+ ).toBeDefined();
+ });
+
+ it("sends one drain resync per loss gap even when the write reports backpressure", async () => {
+ const { supervisor, pushes, subscriber } = makePushSupervisor({
+ connectionIds: new Map(),
+ sessionInputPauseEpochs: new Map(),
+ detachingInputPauseSessions: new Map(),
+ ready: new Promise(() => {}),
+ catchUpClient: vi.fn(async () => {}),
+ });
+ const internals = supervisor as unknown as {
+ handleConnection(socket: unknown): void;
+ clients: Set<{ rosterSubscribed?: boolean; rosterResyncPending?: boolean; backpressured?: boolean }>;
+ write: ReturnType<typeof vi.fn>;
+ };
+ internals.clients.delete(subscriber as never);
+ const socket = Object.assign(new EventEmitter(), { destroyed: false, write: () => true });
+ internals.handleConnection(socket);
+ const client = [...internals.clients][0];
+ if (!client) throw new Error("Missing connected client");
+ client.rosterSubscribed = true;
+ client.rosterResyncPending = true;
+
+ internals.write.mockImplementationOnce((_client: object, message: DaemonOutbound) => {
+ if (message.type === "roster_update") pushes.push(message);
+ return false;
+ });
+ socket.emit("drain");
+ // socket.write queues the resync even when it reports backpressure; the flag must not re-arm.
+ expect(client.rosterResyncPending).toBe(false);
+ expect(pushes.filter((push) => push.resync)).toHaveLength(1);
+
+ socket.emit("drain");
+ expect(pushes.filter((push) => push.resync)).toHaveLength(1);
+ });
+});
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index 799515b1ef..c0a0303b50 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -1384,11 +1384,10 @@ describe("agents view state", () => {
expect(resolveAgentsViewScopeFrames([], frames)).toEqual({ frames: [], droppedFrames: 2 });
});
- test("settles vanished scopes only after both catalog attempts finish", () => {
- expect(shouldApplyScopeResolution(0, false, false)).toBe(true);
- expect(shouldApplyScopeResolution(1, true, false)).toBe(false);
- expect(shouldApplyScopeResolution(1, false, true)).toBe(false);
- expect(shouldApplyScopeResolution(1, true, true)).toBe(true);
+ test("settles vanished scopes only after the saved catalog attempt finishes", () => {
+ expect(shouldApplyScopeResolution(0, false)).toBe(true);
+ expect(shouldApplyScopeResolution(1, false)).toBe(false);
+ expect(shouldApplyScopeResolution(1, true)).toBe(true);
});
});
diff --git a/packages/coding-agent/test/daemon-agent-roster.test.ts b/packages/coding-agent/test/daemon-agent-roster.test.ts
index 2493778330..d882b0ed19 100644
--- a/packages/coding-agent/test/daemon-agent-roster.test.ts
+++ b/packages/coding-agent/test/daemon-agent-roster.test.ts
@@ -539,6 +539,10 @@ function makeSupervisor(workers: WorkerFixture[], extra: Record<string, unknown>
clients: new Set(),
defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },
catalog: { list: vi.fn(async () => []) },
+ pendingRosterChanged: new Set(),
+ publishedRosterIds: new Set(),
+ pendingRosterRemoved: new Set(),
+ rosterPushScheduled: false,
refreshWorkerSummaries: vi.fn(async () => {}),
persistWorker: vi.fn(),
invalidateWorkerSessionInputPauses: vi.fn(),
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index cee6f9f5af..ef8079c91b 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
+import { isDaemonSessionSummary } from "../src/cli/daemon-launch.js";
import {
createDaemonCommandEnvelope,
createDaemonEventEnvelope,
@@ -353,10 +354,32 @@ describe("daemon protocol helpers", () => {
it("keeps attachment routing out of the durable mutation journal", () => {
expect(isDaemonMutatingCommand({ type: "attach" })).toBe(false);
expect(isDaemonMutatingCommand({ type: "reattach" })).toBe(false);
+ // Journal replays after a reconnect would skip re-subscribing the new socket.
+ expect(isDaemonMutatingCommand({ type: "roster_subscribe" })).toBe(false);
+ expect(isDaemonMutatingCommand({ type: "roster_unsubscribe" })).toBe(false);
expect(isDaemonMutatingCommand({ type: "wait_for_headless_completion" })).toBe(true);
expect(isDaemonMutatingCommand({ type: "switch_session" })).toBe(true);
});
+ it("keeps the roster push additive for pre-roster clients", () => {
+ // Subscription commands and the push are capability-gated; a client that
+ // never sends roster_subscribe is never written a roster_update.
+ expect(DAEMON_COMMAND_COMPATIBILITY.roster_subscribe).toEqual({ minProtocol: 7, capability: "agent_roster" });
+ expect(DAEMON_COMMAND_COMPATIBILITY.roster_unsubscribe).toEqual({ minProtocol: 7, capability: "agent_roster" });
+ expect(DAEMON_OUTBOUND_COMPATIBILITY.roster_update).toEqual({ minProtocol: 7, capability: "agent_roster" });
+ // list responses now carry rosterStatus/statusLabel/lastHeardFromAt; the
+ // summary validator pre-roster clients shipped stays open to additive fields.
+ expect(
+ isDaemonSessionSummary({
+ id: "session-1",
+ activeSessionId: "active-1",
+ rosterStatus: "running",
+ statusLabel: "queued",
+ lastHeardFromAt: "2026-08-01T12:00:00.000Z",
+ }),
+ ).toBe(true);
+ });
+
it("reports replay availability from resume cursors", () => {
expect(createDaemonReplayInfo(undefined, 5, "generation-1")).toEqual({
status: "complete",
diff --git a/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts
index 10b3f9ad29..becf9a98f3 100644
--- a/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts
@@ -110,7 +110,7 @@ describe("daemon supervisor passive subagent topology", () => {
const resident = worker("first", [child]);
seedSupervisorRoster(supervisor, resident);
- expect(supervisor.findSummaryInWorker(resident, "88889999cccc")).toEqual(child);
+ expect(supervisor.findSummaryInWorker(resident, "88889999cccc")).toEqual({ ...child, rosterStatus: "idle" });
});
it("rejects an explicit root name that collides with a saved root", async () => {
diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
index e34e8093b6..17c21a96b9 100644
--- a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
@@ -241,6 +241,10 @@ function createSupervisorSnapshotState() {
clients: new Set<object>(),
sessionInputPauses: new Map(),
pendingReplacementSnapshots: new WeakMap<object, Map<string, unknown>>(),
+ pendingRosterChanged: new Set<string>(),
+ publishedRosterIds: new Set<string>(),
+ pendingRosterRemoved: new Set<string>(),
+ rosterPushScheduled: false,
};
}
diff --git a/packages/coding-agent/test/fixtures/roster-seed.ts b/packages/coding-agent/test/fixtures/roster-seed.ts
index 439f827e22..5645d59893 100644
--- a/packages/coding-agent/test/fixtures/roster-seed.ts
+++ b/packages/coding-agent/test/fixtures/roster-seed.ts
@@ -10,7 +10,16 @@ interface RosterWorkerFixture {
export function seedSupervisorRoster(supervisor: object, ...workers: RosterWorkerFixture[]): void {
const internals = supervisor as {
writeRosterEntry(entry: ReturnType<typeof workerRosterEntryFromSummary>, worker?: RosterWorkerFixture): unknown;
+ clients?: Set<unknown>;
};
+ // Prototype-based fixtures skip field initializers; give the push buffers real containers.
+ Object.assign(internals, {
+ pendingRosterChanged: new Set(),
+ pendingRosterRemoved: new Set(),
+ publishedRosterIds: new Set(),
+ rosterPushScheduled: false,
+ clients: internals.clients ?? new Set(),
+ });
for (const worker of workers) {
for (const summary of worker.summaries.values()) {
internals.writeRosterEntry(workerRosterEntryFromSummary(summary), worker);
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index b23232f6a6..2ffdd91f7c 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -1457,6 +1457,7 @@ describe("InteractiveMode connection events", () => {
).rebindCurrentSession;
const updatePendingMessagesDisplay = vi.fn();
const subscribeToAgent = vi.fn();
+ const subscribeToRosterBar = vi.fn(async () => {});
const getState = vi.fn(async () => createConnectionState());
const harness = {
unsubscribe: undefined,
@@ -1466,6 +1467,7 @@ describe("InteractiveMode connection events", () => {
bindLocalSessionExtensions: true,
bindCurrentSessionExtensions: vi.fn(async () => {}),
subscribeToAgent,
+ subscribeToRosterBar,
agentConnection: { getState },
patchConnectionState: vi.fn(),
refreshQueueSelectionFromState: vi.fn(),
diff --git a/packages/coding-agent/test/rlm-ledger.test.ts b/packages/coding-agent/test/rlm-ledger.test.ts
index 6b86180a8f..86f7b4a747 100644
--- a/packages/coding-agent/test/rlm-ledger.test.ts
+++ b/packages/coding-agent/test/rlm-ledger.test.ts
@@ -35,10 +35,11 @@ import { describe, expect, it, vi } from "vitest";
import type { CreateAgentSessionRuntimeFactory } from "../src/core/agent-session-runtime.js";
import type { CreateRlmSubagentRuntimeOptions, SubagentRuntimeHost } from "../src/core/rlm-runtime.js";
import { canonicalSessionPath } from "../src/core/session-lease.js";
-import { SessionManager } from "../src/core/session-manager.js";
+import * as sessionManagerModule from "../src/core/session-manager.js";
import type { ActiveSessionState } from "../src/modes/daemon/active-session-state.js";
+import type { AgentRosterEntry } from "../src/modes/daemon/agent-roster.js";
import { AgentDaemon } from "../src/modes/daemon/daemon-mode.js";
-import type { DaemonCommand } from "../src/modes/daemon/daemon-protocol.js";
+import type { DaemonCommand, DaemonResponse } from "../src/modes/daemon/daemon-protocol.js";
import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";
import {
RLM_LEDGER_MAX_BYTES,
@@ -49,6 +50,8 @@ import {
rlmLedgerPath,
} from "../src/modes/daemon/rlm-ledger.js";
+const { SessionManager } = sessionManagerModule;
+
function makeRoots(root: string) {
const sessionsDir = join(root, "sessions");
const parent = SessionManager.create(root, sessionsDir);
@@ -1051,11 +1054,137 @@ interface SupervisorLedgerInternals {
rlmSpawnLedger(): RlmSpawnLedger;
rlmLedgerSiblings(sessionPath: string): Promise<Array<{ name?: string; rlmDepth: number; path: string }>>;
assertSupervisorSavedSessionNameAvailable(sessionPath: string, name: string): Promise<void>;
- handleCommand(client: object, command: Record<string, unknown>): Promise<unknown>;
+ seedRosterLedger(): Promise<void>;
+ applyWorkerRosterSnapshot(
+ worker: object,
+ delta: { type: "roster_delta"; snapshot: true; entries: AgentRosterEntry[] },
+ source: object,
+ ): Promise<void>;
+ handleCommand(client: object, command: Record<string, unknown>): Promise<DaemonResponse | undefined>;
+ roster(): {
+ write(entry: AgentRosterEntry, workerId?: string): AgentRosterEntry;
+ delete(agentId: string): void;
+ };
+ workers: Map<string, object>;
catalog: object;
}
describe("rlm spawn ledger supervisor wiring", () => {
+ it("hydrates a ledger-seeded child's cwd before publishing the roster", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-supervisor-cwd-"));
+ try {
+ const { sessionsDir, parent, parentFile } = makeRoots(tempDir);
+ const parentArtifactDir = parent.getSessionArtifactDir();
+ if (!parentArtifactDir) throw new Error("Missing parent artifact directory");
+ const child = makeChildSession(tempDir, join(parentArtifactDir, "sub-11111111"), parentFile, 1, "worker");
+ const supervisor = new DaemonSupervisor(join(tempDir, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir: sessionsDir },
+ descriptorDir: join(tempDir, "workers"),
+ }) as unknown as SupervisorLedgerInternals;
+ Object.assign(supervisor.catalog, { list: vi.fn(async () => []) });
+ await supervisor.rlmSpawnLedger().appendSpawn({
+ childId: "sub-11111111",
+ parent: parentFile,
+ child: child.file,
+ depth: 1,
+ name: "worker",
+ });
+
+ await supervisor.seedRosterLedger();
+ const response = await supervisor.handleCommand({}, { type: "roster_subscribe" });
+ if (!response?.success) throw new Error("Roster subscription failed");
+ const row = (response.data as { roster: AgentRosterEntry[] }).roster.find(
+ (entry) => entry.summary.sessionFile === canonicalSessionPath(child.file),
+ );
+ expect(row?.summary.cwd).toBe(tempDir);
+ expect(row?.seededCwd).toBeUndefined();
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("leaves the roster untouched when a source worker disconnects during cwd hydration", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-supervisor-stale-"));
+ let readSpy: ReturnType<typeof vi.spyOn> | undefined;
+ try {
+ const { sessionsDir, parent, parentFile } = makeRoots(tempDir);
+ const parentArtifactDir = parent.getSessionArtifactDir();
+ if (!parentArtifactDir) throw new Error("Missing parent artifact directory");
+ const missing = makeChildSession(tempDir, join(parentArtifactDir, "sub-11111111"), parentFile, 1, "missing");
+ const existing = makeChildSession(tempDir, join(parentArtifactDir, "sub-22222222"), parentFile, 1, "existing");
+ const missingInfo = await sessionManagerModule.readSessionInfo(missing.file);
+ if (!missingInfo) throw new Error("Missing child session info");
+ const supervisor = new DaemonSupervisor(join(tempDir, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir: sessionsDir },
+ descriptorDir: join(tempDir, "workers"),
+ }) as unknown as SupervisorLedgerInternals;
+ const ledger = supervisor.rlmSpawnLedger();
+ await ledger.appendSpawn({
+ childId: "sub-11111111",
+ parent: parentFile,
+ child: missing.file,
+ depth: 1,
+ name: "missing",
+ });
+ await ledger.appendSpawn({
+ childId: "sub-22222222",
+ parent: parentFile,
+ child: existing.file,
+ depth: 1,
+ name: "existing",
+ });
+ Object.assign(supervisor.catalog, { list: vi.fn(async () => []) });
+ await supervisor.seedRosterLedger();
+ const seeded = await supervisor.handleCommand({}, { type: "roster_subscribe" });
+ if (!seeded?.success) throw new Error("Roster subscription failed");
+ const seededRows = (seeded.data as { roster: AgentRosterEntry[] }).roster;
+ const missingRow = seededRows.find(
+ (entry) => entry.summary.sessionFile === canonicalSessionPath(missing.file),
+ );
+ const existingRow = seededRows.find(
+ (entry) => entry.summary.sessionFile === canonicalSessionPath(existing.file),
+ );
+ if (!missingRow || !existingRow) throw new Error("Missing seeded roster rows");
+ supervisor.roster().delete(missingRow.agentId);
+ supervisor.roster().write(existingRow, "worker-1");
+ const source = {};
+ const replacement = {};
+ const worker = {
+ descriptor: { workerId: "worker-1", sessionFile: parentFile, createCommand: {} },
+ client: source,
+ summaries: new Map(),
+ };
+ supervisor.workers.set("worker-1", worker);
+ let finishRead: (() => void) | undefined;
+ const readBlocked = new Promise<void>((resolve) => {
+ finishRead = resolve;
+ });
+ readSpy = vi.spyOn(sessionManagerModule, "readSessionInfo").mockImplementation(async () => {
+ await readBlocked;
+ return missingInfo;
+ });
+
+ const apply = supervisor.applyWorkerRosterSnapshot(
+ worker,
+ { type: "roster_delta", snapshot: true, entries: [] },
+ source,
+ );
+ await vi.waitFor(() => expect(readSpy).toHaveBeenCalledOnce());
+ worker.client = replacement;
+ finishRead?.();
+ await apply;
+
+ const response = await supervisor.handleCommand({}, { type: "roster_subscribe" });
+ if (!response?.success) throw new Error("Roster subscription failed");
+ expect((response.data as { roster: AgentRosterEntry[] }).roster).toEqual([
+ expect.objectContaining({ agentId: existingRow.agentId, workerId: "worker-1" }),
+ ]);
+ } finally {
+ readSpy?.mockRestore();
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
it("reserves saved-sibling names against ledger-backed siblings", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-supervisor-"));
try {
diff --git a/packages/coding-agent/test/subagent-summary-line.test.ts b/packages/coding-agent/test/subagent-summary-line.test.ts
index 467f393f0f..f7808cd058 100644
--- a/packages/coding-agent/test/subagent-summary-line.test.ts
+++ b/packages/coding-agent/test/subagent-summary-line.test.ts
@@ -3,8 +3,11 @@ import stripAnsi from "strip-ansi";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { KeybindingsManager } from "../src/core/keybindings.js";
import type { AgentConnectionRlmChildAgentSnapshot } from "../src/modes/agent-connection/types.js";
+import { isDirectAgentChild } from "../src/modes/agents-view/agents-view-state.js";
+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
import {
countDirectSubagentStatuses,
+ countRosterSubagentStatuses,
SubagentSummaryLine,
} from "../src/modes/interactive/components/subagent-summary-line.js";
import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
@@ -235,6 +238,84 @@ describe("SubagentSummaryLine", () => {
expect(stripAnsi(line.render(100).join("\n"))).toContain("● 0 running ◐ 0 idle ○ 1 inactive");
});
+ it("removes a run on the producer's cancelled signal and keeps transcript-backed rows through repeated dones", () => {
+ const line = new SubagentSummaryLine();
+ const mode = Object.create(InteractiveMode.prototype) as InteractiveMode & Record<string, unknown>;
+ Object.assign(mode, {
+ subagentSnapshots: new Map<string, AgentConnectionRlmChildAgentSnapshot>(),
+ rlmNodeId: undefined,
+ heartbeatCatalog: [],
+ subagentSummaryLine: line,
+ updateWorkingPulse: vi.fn(),
+ syncWorkingLoader: vi.fn(),
+ updateWorkingLoaderMessage: vi.fn(),
+ ui: { requestRender: vi.fn() },
+ });
+ const update = Reflect.get(InteractiveMode.prototype, "updateSubagentSummary") as (
+ this: typeof mode,
+ value: AgentConnectionRlmChildAgentSnapshot,
+ ) => void;
+ const snapshots = Reflect.get(mode, "subagentSnapshots") as Map<string, AgentConnectionRlmChildAgentSnapshot>;
+
+ // A pre-bind failure arrives as cancelled: the queued row goes, never an inactive phantom.
+ update.call(mode, child("never-bound", "queued"));
+ update.call(mode, child("never-bound", "cancelled", { error: "boom" }));
+ expect(snapshots.has("never-bound")).toBe(false);
+
+ update.call(mode, child("worker", "running", { activeSessionId: "resident-worker" }));
+ update.call(mode, child("worker", "done"));
+ update.call(mode, child("worker", "done"));
+ expect(snapshots.has("worker")).toBe(true);
+ expect(stripAnsi(line.render(100).join("\n"))).toContain("● 0 running ◐ 0 idle ○ 1 inactive");
+ });
+
+ it("counts parentSessionId-only roster children exactly like the agents view", () => {
+ const rosterChild = {
+ id: "c1",
+ sessionId: "c1",
+ lifecycle: "live",
+ runtimeKind: "subagent",
+ rlmChildId: "c1",
+ parentSessionId: "root-session",
+ rosterStatus: "idle",
+ } as SessionSummary;
+ expect(isDirectAgentChild(rosterChild, { sessionId: "root-session" })).toBe(true);
+ expect(countRosterSubagentStatuses([rosterChild], { sessionId: "root-session" }, new Set())).toEqual({
+ total: 1,
+ running: 0,
+ idle: 1,
+ inactive: 0,
+ });
+ });
+
+ it("keeps chat alive with the snapshot-fed bar when the roster subscribe fails", async () => {
+ const line = new SubagentSummaryLine();
+ const mode = Object.create(InteractiveMode.prototype) as InteractiveMode & Record<string, unknown>;
+ Object.assign(mode, {
+ agentConnection: {
+ subscribeAgentRoster: vi.fn(async () => {
+ throw new Error("Daemon is stale");
+ }),
+ },
+ subagentSnapshots: new Map<string, AgentConnectionRlmChildAgentSnapshot>(),
+ rlmNodeId: undefined,
+ heartbeatCatalog: [],
+ subagentSummaryLine: line,
+ connectionState: undefined,
+ scheduleHeartbeatManagerRefresh: vi.fn(),
+ updateWorkingPulse: vi.fn(),
+ syncWorkingLoader: vi.fn(),
+ updateWorkingLoaderMessage: vi.fn(),
+ ui: { requestRender: vi.fn() },
+ });
+ const subscribe = Reflect.get(InteractiveMode.prototype, "subscribeToRosterBar") as (
+ this: typeof mode,
+ ) => Promise<void>;
+
+ await expect(subscribe.call(mode)).resolves.toBeUndefined();
+ expect(Reflect.get(mode, "rosterBar")).toBeUndefined();
+ });
+
it("turns a selection into the scoped agents-view run result", async () => {
const returnToAgentsView = vi.fn(async () => undefined);
const mode = Object.create(InteractiveMode.prototype) as InteractiveMode & Record<string, unknown>;
diff --git a/packages/coding-agent/test/suite/regressions/502-unified-session-view.test.ts b/packages/coding-agent/test/suite/regressions/502-unified-session-view.test.ts
index 7f28073f76..c0b6a4b261 100644
--- a/packages/coding-agent/test/suite/regressions/502-unified-session-view.test.ts
+++ b/packages/coding-agent/test/suite/regressions/502-unified-session-view.test.ts
@@ -51,18 +51,18 @@ function refreshHarness() {
reconnectPromise: undefined,
daemonShutdownReceived: false,
options: {},
- liveCatalogGeneration: 0,
savedCatalogGeneration: 0,
heartbeatCatalogGeneration: 0,
- liveCatalogRefreshPending: false,
savedCatalogRefreshPending: false,
heartbeats: [] as unknown[],
+ savedSearchFetchStarted: false,
persistentState,
applySessionList,
reconcileCatalogs,
resolveMissingSelectionAnchor: vi.fn(),
setStatusMessage: vi.fn(),
startClientReconnect: vi.fn(),
+ rearmSavedSearchFetch: privateMethod<(this: unknown) => void>("rearmSavedSearchFetch"),
};
}
@@ -75,41 +75,29 @@ function privateMethod<T>(name: string): T {
}
describe("#502 unified session view regressions", () => {
- test.each(["live", "heartbeat"] as const)(
- "an older overlapping %s poll cannot overwrite the newer response",
- async (kind) => {
- const old = deferred<unknown>();
- const newer = kind === "live" ? summary("new") : { job: { id: "new" } };
- const client = {
- isConnected: true,
- hello: { protocol: { version: 3 } },
- supportsServerCapability: () => true,
- request: vi
- .fn()
- .mockReturnValueOnce(old.promise)
- .mockResolvedValueOnce({
- success: true,
- data: kind === "live" ? { sessions: [newer] } : { heartbeats: [newer] },
- }),
- };
- const harness = { ...refreshHarness(), requireClient: () => client };
- const refresh = privateMethod<(this: typeof harness) => Promise<unknown>>(
- kind === "live" ? "refreshSessions" : "refreshHeartbeats",
- );
+ test("an older overlapping heartbeat poll cannot overwrite the newer response", async () => {
+ const old = deferred<unknown>();
+ const newer = { job: { id: "new" } };
+ const client = {
+ isConnected: true,
+ hello: { protocol: { version: 3 } },
+ supportsServerCapability: () => true,
+ request: vi
+ .fn()
+ .mockReturnValueOnce(old.promise)
+ .mockResolvedValueOnce({ success: true, data: { heartbeats: [newer] } }),
+ };
+ const harness = { ...refreshHarness(), requireClient: () => client };
+ const refresh = privateMethod<(this: typeof harness) => Promise<unknown>>("refreshHeartbeats");
- const oldPoll = refresh.call(harness);
- await refresh.call(harness);
- old.resolve({
- success: true,
- data: kind === "live" ? { sessions: [summary("old")] } : { heartbeats: [{ job: { id: "old" } }] },
- });
- await oldPoll;
+ const oldPoll = refresh.call(harness);
+ await refresh.call(harness);
+ old.resolve({ success: true, data: { heartbeats: [{ job: { id: "old" } }] } });
+ await oldPoll;
- if (kind === "live") expect(harness.applySessionList).toHaveBeenCalledWith([newer], true);
- else expect(harness.heartbeats).toEqual([newer]);
- expect(kind === "live" ? harness.applySessionList : harness.reconcileCatalogs).toHaveBeenCalledOnce();
- },
- );
+ expect(harness.heartbeats).toEqual([newer]);
+ expect(harness.reconcileCatalogs).toHaveBeenCalledOnce();
+ });
test("overlapping saved scans retain the last complete catalog after the newest scan fails", async () => {
const previous = [savedSession("previous")];
@@ -249,8 +237,10 @@ describe("#502 unified session view regressions", () => {
client,
options: { reconnectTimeoutMs: 10_000 },
requireClient: () => client,
+ rosterStore: { attach: vi.fn(async () => true), summaries: () => [summary("live")] },
refreshSavedSessions: vi.fn(async () => true),
refreshHeartbeats: vi.fn(async (_options?: { duringReconnect?: boolean }) => false),
+ armSavedSearchFetch: vi.fn(),
reconnectClient: vi.fn(async (_reconnectingClient: typeof client, _error: unknown) => {}),
};
const refreshHeartbeats =
@@ -283,6 +273,8 @@ describe("#502 unified session view regressions", () => {
expect(client.reconnect).toHaveBeenCalledTimes(2);
expect(harness.applySessionList).toHaveBeenCalledWith([summary("live")], true);
expect(harness.heartbeats).toEqual([{ job: { id: "healthy" } }]);
+ // A query that outlived the outage re-fetches the saved catalog through the one arm predicate.
+ expect(harness.armSavedSearchFetch).toHaveBeenCalledWith({ duringReconnect: true });
expect(harness.reconnectPromise).toBeUndefined();
} finally {
vi.useRealTimers();
@@ -317,7 +309,6 @@ describe("#502 unified session view regressions", () => {
const fallback = summary("fallback");
const harness = {
selectionAnchorPending: true,
- liveCatalogRefreshPending: false,
savedCatalogRefreshPending: true,
selectedIndex: 0,
selectedActiveSessionId: undefined as string | undefined,
@@ -348,7 +339,7 @@ describe("#502 unified session view regressions", () => {
rows: [],
exitRenameMode: vi.fn(),
setStatusMessage: vi.fn(),
- refreshBothCatalogs: vi.fn(async () => true),
+ refreshSessions: vi.fn(async () => true),
requireClient: () => ({ request }),
renameSession: Reflect.get(AgentsViewMode.prototype, "renameSession"),
};
@@ -379,22 +370,6 @@ describe("#502 unified session view regressions", () => {
).toEqual([]);
});
- test("slow live polls are coalesced instead of repeatedly superseded", async () => {
- const slow = deferred<boolean>();
- const refreshSessions = vi.fn(() => slow.promise);
- const harness = { liveCatalogPollPromise: undefined, refreshSessions };
- const poll = privateMethod<(this: typeof harness) => void>("pollSessions");
-
- poll.call(harness);
- poll.call(harness);
- expect(refreshSessions).toHaveBeenCalledOnce();
- slow.resolve(true);
- await slow.promise;
- await Promise.resolve();
- poll.call(harness);
- expect(refreshSessions).toHaveBeenCalledTimes(2);
- });
-
test.each([
{ mode: "search", prompt: ["prompt top", "prompt input", "prompt bottom"] },
{ mode: "reply", prompt: ["prompt top", "reply header", "reply gap", "prompt input", "prompt bottom"] },