Skip to content

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

Rust

feat(coding-agent): recursive scoped agents view (#586)

Sebastian Müller5e9eb027b7ef
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index fe4826f671..1690e81ae5 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -7,6 +7,7 @@
- Fixed `stop` and `rename` rejecting custom daemon socket options.
- Fixed SIGINT in print mode leaving the session active until liveness reclaim.
- Fixed daemon startup failing permanently when an interrupted supervisor owner directory contained only stray files.
+- Fixed agents-view fallback notices and scoped live sessions surviving transient refresh failures across chat returns.
## [0.5.1] - 2026-08-04
diff --git a/packages/coding-agent/src/core/keybindings.ts b/packages/coding-agent/src/core/keybindings.ts
index 85ad00ead3..03718c5a40 100644
--- a/packages/coding-agent/src/core/keybindings.ts
+++ b/packages/coding-agent/src/core/keybindings.ts
@@ -120,8 +120,8 @@ export const KEYBINDINGS = {
"app.session.tree": { defaultKeys: [], description: "Open session tree" },
"app.session.fork": { defaultKeys: [], description: "Fork current session" },
"app.session.resume": { defaultKeys: [], description: "Resume a session" },
- "app.agents.back": { defaultKeys: "left", description: "Return to session view" },
- "app.agents.open": { defaultKeys: "right", description: "Open chat view for selected agent" },
+ "app.agents.back": { defaultKeys: "left", description: "Return to parent agent scope" },
+ "app.agents.open": { defaultKeys: "right", description: "Drill into selected agent" },
"app.modal.back": { defaultKeys: "left", description: "Go back / close the current dialog" },
"app.agents.reply": { defaultKeys: "space", description: "Reply to selected agent" },
"app.agents.new": { defaultKeys: "ctrl+n", description: "Start a new session from the agents view" },
diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.ts
index 94097c6fa2..57a3257fbc 100644
--- a/packages/coding-agent/src/main.ts
+++ b/packages/coding-agent/src/main.ts
@@ -82,6 +82,7 @@ import {
} from "./modes/daemon/daemon-worker-protocol.js";
import {
type AgentConnection,
+ type AgentsViewScopeKey,
ClientPromptStashStore,
createInteractiveModeLocalSessionHost,
createInteractiveModeUiServicesFromServices,
@@ -1355,7 +1356,7 @@ export async function main(args: string[], options?: MainOptions) {
services,
sessionManager,
});
- const launchAgentsView = async (initialSession?: SessionSummary) => {
+ const launchAgentsView = async (initialSession?: SessionSummary, initialScopeKey?: AgentsViewScopeKey) => {
await runAgentsViewMode({
socketPath: daemonSocketPath,
config: defaultSessionConfig,
@@ -1385,6 +1386,7 @@ export async function main(args: string[], options?: MainOptions) {
promptStashStore,
startupModelId: startupModel.model?.id,
initialSession,
+ initialScopeKey,
verbose: parsed.verbose,
});
};
@@ -1449,6 +1451,11 @@ export async function main(args: string[], options?: MainOptions) {
// view was not rendered here, so we intentionally leave
// agentsViewOwnsStartupNotices unset and let the in-session fallback run.
returnToAgentsView: !parsed.noSession,
+ sessionDepth: summary.rlmDepth,
+ // Direct launch has only the attached summary; the live+passive+saved
+ // unified catalog index is not built until the agents view opens. Retained
+ // child snapshots augment this running-child fallback inside chat.
+ sessionHasChildren: summary.hasRunningRlmChildren === true,
});
await preloadCodeHighlighter();
@@ -1457,11 +1464,19 @@ export async function main(args: string[], options?: MainOptions) {
if (parsed.noSession) {
return;
}
- await launchAgentsView({
+ const returnedSummary = {
...summary,
...interactiveResult.source,
id: interactiveResult.source.activeSessionId ?? summary.id,
- });
+ };
+ const initialScopeKey =
+ interactiveResult.type === "scoped_agents_view"
+ ? {
+ sessionId: interactiveResult.source.sessionId,
+ activeSessionId: interactiveResult.source.activeSessionId,
+ }
+ : undefined;
+ await launchAgentsView(returnedSummary, initialScopeKey);
return;
}
if (useDaemonClient) {
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 6284960408..9f4610d3f9 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
@@ -67,18 +67,31 @@ import {
} from "../shared/startup-notices.js";
import {
type AgentsViewRow,
+ type AgentsViewScopeFrame,
+ type AgentsViewScopeKey,
type AgentsViewSection,
type AgentsViewSelectionKey,
buildAgentsViewRows,
+ buildUnifiedSessionIndex,
+ createUnattachableChildOpenResult,
filterUnifiedSessions,
formatHeartbeatBadge,
getAgentsViewSelectionKey,
+ getAgentsViewSessionTitle,
getAgentsViewSummaryIdentity as getSummaryIdentity,
+ getUnifiedSessionAncestorSessionIds,
+ hasUnifiedSessionChildren,
reconcileUnifiedSessions,
+ resolveAgentsViewLeftResult,
+ resolveAgentsViewScopeFrames,
resolveAgentsViewSelectionState,
+ scopeToSessionSubtree,
sectionTitle,
+ shouldApplyScopeResolution,
shouldShowAgentsViewSession,
summaryForUnifiedRecord,
+ transitionAgentsViewScope,
+ type UnifiedSessionIndex,
type UnifiedSessionRecord,
} from "./agents-view-state.js";
import { matchesSearchText } from "./session-view-search.js";
@@ -113,24 +126,35 @@ export interface AgentsViewModeOptions {
reconnectTimeoutMs?: number;
promptStashStore?: ClientPromptStashStore;
initialSession?: SessionSummary;
+ /** When set, the first view is rooted at this session's direct children. */
+ initialScopeKey?: AgentsViewScopeKey;
}
export type AgentsViewRunResult =
| { type: "exit" }
+ | {
+ type: "scope_back";
+ selection: SessionSummary;
+ expandedAncestorSessionIds: string[];
+ returnChat?: SessionSummary;
+ hasChildren: boolean;
+ }
| {
type: "open";
summary: SessionSummary;
- subagent?: SessionSummary;
- // Session ids of every ancestor that must be expanded to reveal the
- // opened subagent, from the root agent down to its immediate parent.
- subagentAncestorSessionIds?: string[];
+ /** Row restored after chat closes; differs from summary only for an unattachable-child fallback. */
+ selection?: SessionSummary;
+ expandedAncestorSessionIds?: string[];
+ hasChildren?: boolean;
+ statusMessage?: string;
};
export type AgentsViewPersistentState = {
selectedRowIdentity?: string;
backSession?: SessionSummary;
+ scopeFrames?: AgentsViewScopeFrame[];
selectedSessionKey?: AgentsViewSelectionKey;
- // Ancestor chain to re-expand on return to a subagent. Kept by sessionId, not
- // row identity, so it survives a parent's active→persisted identity flip.
+ // Ancestor chain to re-expand on return to a nested agent. Kept by sessionId,
+ // not row identity, so it survives an active→persisted identity flip.
pendingExpandedAncestorSessionIds?: string[];
statusMessage?: string;
// Gathered once and reused across agents-view instances so the notices survive
@@ -140,6 +164,7 @@ export type AgentsViewPersistentState = {
query?: string;
savedSessions?: AgentConnectionSavedSessionInfo[];
lastSuccessfulSavedSessions?: AgentConnectionSavedSessionInfo[];
+ lastSuccessfulLiveSummaries?: SessionSummary[];
savedCatalogGeneration?: number;
heartbeats?: AgentConnectionHeartbeat[];
};
@@ -206,6 +231,13 @@ export function formatAgentsViewStatusLine(text: string): string {
return text.replace(/\s+/g, " ").trim();
}
+export function combineAgentsViewStartupNotices(...notices: readonly (string | undefined)[]): string | undefined {
+ const formatted = notices
+ .map((notice) => (notice ? formatAgentsViewStatusLine(notice) : ""))
+ .filter((notice) => notice.length > 0);
+ return formatted.length > 0 ? formatted.join(" · ") : undefined;
+}
+
export function shouldReconnectAgentsViewDaemon(reason: DaemonClosingReason | undefined): boolean {
return reason !== "shutdown";
}
@@ -217,6 +249,56 @@ export function createAgentsViewReplyHeadline(text: string | undefined): string
.find((line) => line.length > 0);
}
+export function getAgentsViewDepth(scopeRoot: SessionSummary | undefined): number {
+ return scopeRoot ? (scopeRoot.rlmDepth ?? 0) + 1 : 0;
+}
+
+export function createInitialAgentsViewScopeFrames(
+ initialScopeKey: AgentsViewScopeKey | undefined,
+ returnChat: SessionSummary | undefined,
+): AgentsViewScopeFrame[] {
+ if (!initialScopeKey) return [];
+ return [
+ {
+ scope: initialScopeKey,
+ ...(returnChat?.sessionId === initialScopeKey.sessionId ? { returnChat } : {}),
+ },
+ ];
+}
+
+export function createInitialAgentsViewPersistentState(
+ options: Pick<AgentsViewModeOptions, "initialScopeKey" | "initialSession">,
+): AgentsViewPersistentState {
+ const initialSession = options.initialSession;
+ return {
+ ...(initialSession
+ ? {
+ selectedRowIdentity: getSummaryIdentity(initialSession),
+ selectedSessionKey: getAgentsViewSelectionKey(initialSession),
+ backSession: initialSession,
+ }
+ : {}),
+ ...(options.initialScopeKey
+ ? {
+ scopeFrames: createInitialAgentsViewScopeFrames(options.initialScopeKey, initialSession),
+ ...(initialSession ? { lastSuccessfulLiveSummaries: [initialSession] } : {}),
+ }
+ : {}),
+ };
+}
+
+export function createScopeBackReturnChatOpenResult(
+ result: Extract<AgentsViewRunResult, { type: "scope_back" }>,
+): Extract<AgentsViewRunResult, { type: "open" }> | undefined {
+ if (!result.returnChat) return undefined;
+ return {
+ type: "open",
+ summary: result.returnChat,
+ expandedAncestorSessionIds: result.expandedAncestorSessionIds,
+ hasChildren: result.hasChildren,
+ };
+}
+
interface OpenedAgentsViewSession {
connection: DaemonAgentConnection;
summary: SessionSummary;
@@ -329,40 +411,41 @@ function isUnknownActiveSessionError(error: unknown): boolean {
}
export async function runAgentsViewMode(options: AgentsViewModeOptions): Promise<void> {
- const initialSession = options.initialSession;
- const persistentState: AgentsViewPersistentState = initialSession
- ? {
- selectedRowIdentity: getSummaryIdentity(initialSession),
- selectedSessionKey: getAgentsViewSelectionKey(initialSession),
- backSession: initialSession,
- }
- : {};
+ const persistentState = createInitialAgentsViewPersistentState(options);
const promptStashStore = options.promptStashStore ?? new ClientPromptStashStore();
while (true) {
const view = new AgentsViewMode(options, persistentState);
- const result = await view.run();
- if (result.type === "exit") {
- return;
- }
- if (result.subagent) {
- // Returning from a subagent reopens the agents view with every ancestor
- // list expanded and that subagent reselected.
- persistentState.selectedRowIdentity = getSummaryIdentity(result.subagent);
- persistentState.selectedSessionKey = getAgentsViewSelectionKey(result.subagent);
- persistentState.pendingExpandedAncestorSessionIds = result.subagentAncestorSessionIds ?? [];
+ const viewResult = await view.run();
+ if (viewResult.type === "exit") return;
+ let result: Extract<AgentsViewRunResult, { type: "open" }>;
+ if (viewResult.type === "scope_back") {
+ persistentState.scopeFrames = transitionAgentsViewScope(persistentState.scopeFrames ?? [], { type: "back" });
+ persistentState.selectedRowIdentity = getSummaryIdentity(viewResult.selection);
+ persistentState.selectedSessionKey = getAgentsViewSelectionKey(viewResult.selection);
+ persistentState.pendingExpandedAncestorSessionIds = viewResult.expandedAncestorSessionIds;
+ persistentState.query = "";
+ const returnChatResult = createScopeBackReturnChatOpenResult(viewResult);
+ if (!returnChatResult) continue;
+ result = returnChatResult;
} else {
- persistentState.selectedRowIdentity = getSummaryIdentity(result.summary);
- persistentState.selectedSessionKey = getAgentsViewSelectionKey(result.summary);
- persistentState.pendingExpandedAncestorSessionIds = undefined;
+ result = viewResult;
}
+ const selection = result.selection ?? result.summary;
+ persistentState.selectedRowIdentity = getSummaryIdentity(selection);
+ persistentState.selectedSessionKey = getAgentsViewSelectionKey(selection);
+ persistentState.pendingExpandedAncestorSessionIds = result.expandedAncestorSessionIds;
+ if (result.statusMessage) persistentState.statusMessage = result.statusMessage;
+
let opened: OpenedAgentsViewSession | undefined;
try {
opened = await openAgentsViewSession(options, result.summary);
- persistentState.backSession = opened.summary;
if (opened.cwdFallbackNotice) {
- persistentState.statusMessage = opened.cwdFallbackNotice;
+ persistentState.statusMessage = combineAgentsViewStartupNotices(
+ result.statusMessage,
+ opened.cwdFallbackNotice,
+ );
}
const uiServices = await resolveAgentsViewSessionUiServices(options, opened.summary);
const interactiveMode = new InteractiveMode({
@@ -374,39 +457,46 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): Promise
bindLocalSessionExtensions: false,
migratedProviders: options.migratedProviders,
modelFallbackMessage: resolveAttachModelFallbackMessage(opened.summary, options.modelFallbackMessage),
- startupNotice: opened.cwdFallbackNotice,
+ startupNotice: combineAgentsViewStartupNotices(result.statusMessage, opened.cwdFallbackNotice),
verbose: options.verbose,
returnToAgentsView: true,
forceFullscreen: true,
// The agents view renders the global notices itself, so suppress them in-session.
agentsViewOwnsStartupNotices: true,
- // Matches the node id scheme used by snapshot child seeding
- // (rlmChildId, falling back to the child's active session id).
- initialSubagentNodeId: result.subagent
- ? (result.subagent.rlmChildId ?? result.subagent.activeSessionId)
- : undefined,
+ sessionDepth: opened.summary.rlmDepth,
+ sessionHasChildren: result.hasChildren,
});
try {
const interactiveResult = await interactiveMode.run();
const source = interactiveResult.source;
- // A subagent selection was recorded before the chat opened; keep it so
- // the view reselects the subagent instead of its root session.
- if (!result.subagent) {
- persistentState.selectedRowIdentity = source.sessionFile
- ? `file:${resolvePath(canonicalizePath(source.sessionFile))}`
- : source.activeSessionId
- ? `active:${source.activeSessionId}`
- : `session:${source.sessionId}`;
- persistentState.selectedSessionKey = {
- sessionId: source.sessionId,
- activeSessionId: source.activeSessionId,
- };
- }
- persistentState.backSession = {
+ const returnedSession: SessionSummary = {
...opened.summary,
...source,
id: source.activeSessionId ?? opened.summary.id,
};
+ // Preserve an unattachable child's selection while its parent chat was open.
+ if (selection.sessionId === result.summary.sessionId) {
+ persistentState.selectedRowIdentity = getSummaryIdentity(returnedSession);
+ persistentState.selectedSessionKey = getAgentsViewSelectionKey(returnedSession);
+ }
+ if (interactiveResult.type === "scoped_agents_view") {
+ const nextScope = { sessionId: source.sessionId, activeSessionId: source.activeSessionId };
+ persistentState.scopeFrames = transitionAgentsViewScope(persistentState.scopeFrames ?? [], {
+ type: "push",
+ scope: nextScope,
+ returnChat: returnedSession,
+ });
+ const cachedLiveSummaries = persistentState.lastSuccessfulLiveSummaries ?? [];
+ const cachedIndex = cachedLiveSummaries.findIndex(
+ (summary) => summary.sessionId === returnedSession.sessionId,
+ );
+ persistentState.lastSuccessfulLiveSummaries =
+ cachedIndex === -1
+ ? [...cachedLiveSummaries, returnedSession]
+ : cachedLiveSummaries.map((summary, index) => (index === cachedIndex ? returnedSession : summary));
+ persistentState.query = "";
+ }
+ persistentState.backSession = returnedSession;
} catch (error) {
// The session opened fine and then threw while running; label it as a
// runtime crash so it isn't mixed in with true open failures.
@@ -546,6 +636,12 @@ export class AgentsViewMode implements Component, Focusable {
private lastSuccessfulSavedSessions: AgentConnectionSavedSessionInfo[] = [];
private heartbeats: AgentConnectionHeartbeat[] = [];
private unifiedRecords: UnifiedSessionRecord[] = [];
+ private unifiedIndex: UnifiedSessionIndex = buildUnifiedSessionIndex([]);
+ 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;
@@ -585,11 +681,21 @@ export class AgentsViewMode implements Component, Focusable {
private readonly options: AgentsViewModeOptions,
private readonly persistentState: AgentsViewPersistentState = {},
) {
+ const initialFrames =
+ persistentState.scopeFrames ??
+ createInitialAgentsViewScopeFrames(
+ options.initialScopeKey,
+ persistentState.backSession ?? options.initialSession,
+ );
+ persistentState.scopeFrames = initialFrames;
+ this.scopeKey = initialFrames.at(-1)?.scope;
this.selectedRowIdentity = persistentState.selectedRowIdentity;
this.selectedSessionKey = persistentState.selectedSessionKey;
this.selectedActiveSessionId = persistentState.selectedSessionKey?.activeSessionId;
+ this.lastListedSummaries = persistentState.lastSuccessfulLiveSummaries ?? [];
this.savedSessions = persistentState.savedSessions ?? [];
this.lastSuccessfulSavedSessions = persistentState.lastSuccessfulSavedSessions ?? this.savedSessions;
+ this.savedCatalogReady = persistentState.lastSuccessfulSavedSessions !== undefined;
this.heartbeats = persistentState.heartbeats ?? [];
this.savedCatalogGeneration = persistentState.savedCatalogGeneration ?? 0;
this.keybindings = KeybindingsManager.create();
@@ -641,8 +747,26 @@ export class AgentsViewMode implements Component, Focusable {
return true;
}
if (this.editor.getText().length > 0) return false;
- const backSession = this.persistentState.backSession;
- this.finish(backSession ? { type: "open", summary: backSession } : { type: "exit" });
+ const ancestors = this.scopeKey
+ ? getUnifiedSessionAncestorSessionIds(this.unifiedRecords, this.scopeKey, this.unifiedIndex)
+ : [];
+ const scopeRoot = this.scopeRootSummary;
+ const result = resolveAgentsViewLeftResult(
+ scopeRoot,
+ ancestors,
+ this.persistentState.scopeFrames?.at(-1)?.returnChat,
+ );
+ if (result && scopeRoot) {
+ this.finish({
+ ...result,
+ hasChildren: hasUnifiedSessionChildren(
+ this.unifiedRecords,
+ getAgentsViewSelectionKey(scopeRoot),
+ this.unifiedIndex,
+ ),
+ });
+ }
+ // Global view has no hierarchy parent: consume Left without opening chat.
return true;
};
this.editor.onEscape = () => {
@@ -652,7 +776,19 @@ export class AgentsViewMode implements Component, Focusable {
this.setSearchQuery("");
} else {
const backSession = this.persistentState.backSession;
- this.finish(backSession ? { type: "open", summary: backSession } : { type: "exit" });
+ this.finish(
+ backSession
+ ? {
+ type: "open",
+ summary: backSession,
+ hasChildren: hasUnifiedSessionChildren(
+ this.unifiedRecords,
+ getAgentsViewSelectionKey(backSession),
+ this.unifiedIndex,
+ ),
+ }
+ : { type: "exit" },
+ );
}
};
this.fullscreenDock = {
@@ -668,7 +804,14 @@ export class AgentsViewMode implements Component, Focusable {
undefined,
{
topPadding: true,
- getExtraMetadata: () => [{ label: "agents", value: this.getAgentCountsText() }],
+ getExtraMetadata: () => {
+ const root = this.scopeRootSummary;
+ return [
+ { label: "agents", value: this.getAgentCountsText() },
+ { label: "scope", value: root ? getAgentsViewSessionTitle(root) : "global" },
+ { label: "depth", value: String(getAgentsViewDepth(root)) },
+ ];
+ },
},
);
}
@@ -1117,7 +1260,7 @@ export class AgentsViewMode implements Component, Focusable {
private getFilteredRecords(): UnifiedSessionRecord[] {
const query = this.replyTarget || this.renameTarget ? (this.actionModeSearchQuery ?? "") : this.editor.getText();
- return filterUnifiedSessions(this.unifiedRecords, (text) => matchesSearchText(text, query));
+ return filterUnifiedSessions(this.scopedRecords, (text) => matchesSearchText(text, query));
}
/** Rebuild rows from the last fetched summaries, keeping selection on the same row. */
@@ -1127,6 +1270,7 @@ export class AgentsViewMode implements Component, Focusable {
this.getFilteredRecords(),
this.expandedSubagentParents,
this.programShownParents,
+ this.scopeKey,
);
const index =
selectedIdentity === undefined ? -1 : this.rows.findIndex((row) => row.identity === selectedIdentity);
@@ -1223,7 +1367,15 @@ export class AgentsViewMode implements Component, Focusable {
this.setStatusMessage("Cannot open agent without an active runtime or saved session file");
return;
}
- this.finish({ type: "open", summary: row.summary });
+ this.finish({
+ type: "open",
+ summary: row.summary,
+ hasChildren: hasUnifiedSessionChildren(
+ this.unifiedRecords,
+ getAgentsViewSelectionKey(row.summary),
+ this.unifiedIndex,
+ ),
+ });
}
private expandSubagentList(row: AgentsViewRow): void {
@@ -1307,17 +1459,33 @@ export class AgentsViewMode implements Component, Focusable {
}
private openSelectedSubagent(row: AgentsViewRow): void {
+ const expandedAncestorSessionIds = this.collectSubagentAncestorSessionIds(row);
+ if (row.summary.activeSessionId || row.summary.sessionFile) {
+ this.finish({
+ type: "open",
+ summary: row.summary,
+ expandedAncestorSessionIds,
+ hasChildren: hasUnifiedSessionChildren(
+ this.unifiedRecords,
+ getAgentsViewSelectionKey(row.summary),
+ this.unifiedIndex,
+ ),
+ });
+ return;
+ }
const root = this.findSubagentRootRow(row);
if (!root || !(root.summary.activeSessionId || root.summary.sessionFile)) {
- this.setStatusMessage("Cannot open subagent without its parent agent");
+ this.setStatusMessage("Cannot open agent without an active runtime or saved session file");
return;
}
- this.finish({
- type: "open",
- summary: root.summary,
- subagent: row.summary,
- subagentAncestorSessionIds: this.collectSubagentAncestorSessionIds(row),
- });
+ this.finish(
+ createUnattachableChildOpenResult(
+ row.summary,
+ root.summary,
+ expandedAncestorSessionIds,
+ hasUnifiedSessionChildren(this.unifiedRecords, getAgentsViewSelectionKey(root.summary), this.unifiedIndex),
+ ),
+ );
}
/** Session ids of every ancestor of a subagent row, root-most first. */
@@ -1915,18 +2083,29 @@ export class AgentsViewMode implements Component, Focusable {
try {
const response = await client.request(createAgentsViewListCommand());
if (generation !== this.liveCatalogGeneration) return false;
- this.applySessionList(expectSessionList(requireDaemonData(response)));
+ this.liveCatalogReady = true;
+ this.applySessionList(expectSessionList(requireDaemonData(response)), true);
return true;
} catch (error) {
- if (!options.preserveStatusOnError && !this.reconnectPromise) {
- if (client.isConnected) this.setStatusMessage(formatError("Failed to refresh agents", error));
- else this.startClientReconnect(client, 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 && !options.preserveStatusOnError) {
- this.setStatusMessage(formatError("Failed to refresh current session", 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 {
@@ -1937,8 +2116,9 @@ export class AgentsViewMode implements Component, Focusable {
}
}
- private applySessionList(sessions: SessionSummary[]): void {
+ private applySessionList(sessions: SessionSummary[], successful = false): void {
this.lastListedSummaries = sessions;
+ if (successful) this.persistentState.lastSuccessfulLiveSummaries = sessions;
this.reconcileCatalogs();
}
@@ -1948,10 +2128,25 @@ export class AgentsViewMode implements Component, Focusable {
);
this.lastVisibleSummaries = this.withPendingDeleteSession(visibleSessions);
this.unifiedRecords = reconcileUnifiedSessions(this.lastVisibleSummaries, this.savedSessions, this.heartbeats);
+ this.unifiedIndex = buildUnifiedSessionIndex(this.unifiedRecords);
+
+ const frames = this.persistentState.scopeFrames ?? [];
+ const resolution = resolveAgentsViewScopeFrames(this.unifiedRecords, frames, this.unifiedIndex);
+ if (shouldApplyScopeResolution(resolution.droppedFrames, this.liveCatalogReady, this.savedCatalogReady)) {
+ this.persistentState.scopeFrames = resolution.frames;
+ this.scopeKey = resolution.frames.at(-1)?.scope;
+ this.scopeRootSummary = resolution.root ? summaryForUnifiedRecord(resolution.root) : undefined;
+ if (resolution.droppedFrames > 0) {
+ const destination = resolution.root ? "the nearest available parent" : "the global view";
+ this.setStatusMessage(`Scope is no longer available; returned to ${destination}`, { render: false });
+ }
+ }
+ this.scopedRecords = scopeToSessionSubtree(this.unifiedRecords, this.scopeKey, this.unifiedIndex);
this.rows = buildAgentsViewRows(
this.getFilteredRecords(),
this.expandedSubagentParents,
this.programShownParents,
+ this.scopeKey,
);
this.applyPendingAncestorExpansion();
this.restoreSelection();
@@ -1997,6 +2192,7 @@ export class AgentsViewMode implements Component, Focusable {
if (generation !== this.savedCatalogGeneration) return false;
this.savedSessions = sessions;
this.lastSuccessfulSavedSessions = sessions;
+ this.savedCatalogReady = true;
this.persistentState.lastSuccessfulSavedSessions = sessions;
this.persistentState.savedSessions = sessions;
this.reconcileCatalogs();
@@ -2005,6 +2201,8 @@ export class AgentsViewMode implements Component, Focusable {
if (generation === this.savedCatalogGeneration) {
this.savedSessions = successfulSessions;
this.persistentState.savedSessions = successfulSessions;
+ // Treat a terminal failure as settled so scope fallback cannot soft-lock.
+ this.savedCatalogReady = true;
this.reconcileCatalogs();
if (!options.preserveStatusOnError && !this.reconnectPromise && !this.daemonShutdownReceived) {
this.setStatusMessage(formatError("Failed to load saved sessions", error));
@@ -2139,7 +2337,7 @@ export class AgentsViewMode implements Component, Focusable {
this.clearDeleteConfirmation({ render: false });
this.setStatusMessage(undefined, { render: false });
this.ui.stop({
- preserveAltScreen: result.type === "open",
+ preserveAltScreen: result.type !== "exit",
flushFullscreen: false,
});
stopThemeWatcher();
@@ -2207,7 +2405,7 @@ export class AgentsViewMode implements Component, Focusable {
this.daemonShutdownReceived = false;
this.reconnectTimedOut = false;
this.setStatusMessage("Daemon reconnected", { render: false });
- this.applySessionList(sessions);
+ this.applySessionList(sessions, true);
void this.refreshSavedSessions({ duringReconnect: true, preserveStatusOnError: true });
return;
} catch (error) {
@@ -2225,7 +2423,6 @@ export class AgentsViewMode implements Component, Focusable {
sticky: true,
render: false,
});
- this.applySessionList([]);
}
}
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 319bf1b9ee..cfce771dcb 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
@@ -22,6 +22,43 @@ export interface UnifiedSessionRecord {
heartbeat?: UnifiedSessionHeartbeat;
}
+export interface AgentsViewScopeKey {
+ sessionId: string;
+ activeSessionId?: string;
+}
+
+export interface AgentsViewScopeFrame {
+ scope: AgentsViewScopeKey;
+ /** Chat to revisit before returning to the parent agents view. */
+ returnChat?: SessionSummary;
+}
+
+export type AgentsViewScopeAction =
+ | { type: "push"; scope: AgentsViewScopeKey; returnChat?: SessionSummary }
+ | { type: "back" };
+
+export interface AgentsViewScopeResolution {
+ frames: AgentsViewScopeFrame[];
+ root?: UnifiedSessionRecord;
+ droppedFrames: number;
+}
+
+export interface AgentsViewScopeBackResult {
+ type: "scope_back";
+ selection: SessionSummary;
+ expandedAncestorSessionIds: string[];
+ returnChat?: SessionSummary;
+}
+
+export interface UnattachableChildOpenResult {
+ type: "open";
+ summary: SessionSummary;
+ selection: SessionSummary;
+ expandedAncestorSessionIds: string[];
+ hasChildren: boolean;
+ statusMessage: string;
+}
+
export type AgentsViewRowKind = "agent" | "subagent-summary" | "subagent" | "subagent-code";
// Hard cap on spawn-code lines shown so a large program never floods the view.
@@ -206,6 +243,8 @@ export function summaryForUnifiedRecord(record: UnifiedSessionRecord): SessionSu
sessionName: record.daemon.sessionName ?? saved.name,
firstMessage: record.daemon.firstMessage ?? saved.firstMessage,
sessionFile: record.daemon.sessionFile ?? canonicalSessionPath(saved.path),
+ parentSessionPath: record.daemon.parentSessionPath ?? saved.parentSessionPath,
+ rlmDepth: record.daemon.rlmDepth ?? saved.rlmDepth,
created: record.daemon.created ?? saved.created.toISOString(),
modified: record.daemon.modified ?? saved.modified.toISOString(),
};
@@ -217,8 +256,11 @@ export function summaryForUnifiedRecord(record: UnifiedSessionRecord): SessionSu
lifecycle: "archived",
activity: "idle",
isSessionActive: false,
+ runtimeKind: saved.parentSessionPath ? "subagent" : "top-level",
+ rlmDepth: saved.rlmDepth,
sessionId: saved.id,
sessionFile: canonicalSessionPath(saved.path),
+ parentSessionPath: saved.parentSessionPath,
sessionName: saved.name,
cwd: saved.cwd,
isStreaming: false,
@@ -234,22 +276,132 @@ export function summaryForUnifiedRecord(record: UnifiedSessionRecord): SessionSu
};
}
-export function filterUnifiedSessions(
+export function transitionAgentsViewScope(
+ frames: readonly AgentsViewScopeFrame[],
+ action: AgentsViewScopeAction,
+): AgentsViewScopeFrame[] {
+ if (action.type === "back") return frames.slice(0, -1);
+ const nextFrame = { scope: action.scope, ...(action.returnChat ? { returnChat: action.returnChat } : {}) };
+ if (frames.at(-1)?.scope.sessionId !== action.scope.sessionId) return [...frames, nextFrame];
+ return [...frames.slice(0, -1), nextFrame];
+}
+
+export function resolveAgentsViewLeftResult(
+ scopeRoot: SessionSummary | undefined,
+ expandedAncestorSessionIds: string[] = [],
+ returnChat?: SessionSummary,
+): AgentsViewScopeBackResult | undefined {
+ if (!scopeRoot) return undefined;
+ return {
+ type: "scope_back",
+ selection: scopeRoot,
+ expandedAncestorSessionIds,
+ ...(returnChat?.sessionId === scopeRoot.sessionId ? { returnChat: scopeRoot } : {}),
+ };
+}
+
+export function shouldApplyScopeResolution(
+ droppedFrames: number,
+ liveCatalogReady: boolean,
+ savedCatalogReady: boolean,
+): boolean {
+ return droppedFrames === 0 || (liveCatalogReady && savedCatalogReady);
+}
+
+export function createUnattachableChildOpenResult(
+ child: SessionSummary,
+ parent: SessionSummary,
+ expandedAncestorSessionIds: readonly string[],
+ hasChildren: boolean,
+): UnattachableChildOpenResult {
+ return {
+ type: "open",
+ summary: parent,
+ selection: child,
+ expandedAncestorSessionIds: [...expandedAncestorSessionIds],
+ hasChildren,
+ statusMessage: "Child session is unavailable; opened its parent instead",
+ };
+}
+
+export function resolveAgentsViewScopeFrames(
records: readonly UnifiedSessionRecord[],
- matches: (searchableText: string) => boolean,
+ frames: readonly AgentsViewScopeFrame[],
+ index: UnifiedSessionIndex = buildUnifiedSessionIndex(records),
+): AgentsViewScopeResolution {
+ if (frames.length === 0) return { frames: [], droppedFrames: 0 };
+ for (let frameIndex = frames.length - 1; frameIndex >= 0; frameIndex--) {
+ const frame = frames[frameIndex]!;
+ const root = findScopeRecord(frame.scope, index.byKey);
+ if (!root) continue;
+ return {
+ frames: frames.slice(0, frameIndex + 1),
+ root,
+ droppedFrames: frames.length - frameIndex - 1,
+ };
+ }
+ return { frames: [], droppedFrames: frames.length };
+}
+
+/** Restrict records to the scoped root and every descendant of that root. */
+export function scopeToSessionSubtree(
+ records: readonly UnifiedSessionRecord[],
+ scope: AgentsViewScopeKey | undefined,
+ index: UnifiedSessionIndex = buildUnifiedSessionIndex(records),
): UnifiedSessionRecord[] {
- const recordsByKey = new Map<string, UnifiedSessionRecord>();
- for (const record of records) {
- for (const key of record.identityAliases) recordsByKey.set(key, record);
+ if (!scope) return [...records];
+ const root = findScopeRecord(scope, index.byKey);
+ if (!root) return [];
+ const retained = new Set<UnifiedSessionRecord>();
+ const queue = [root];
+ for (let queueIndex = 0; queueIndex < queue.length; queueIndex++) {
+ const current = queue[queueIndex]!;
+ if (retained.has(current)) continue;
+ retained.add(current);
+ queue.push(...(index.childrenByParent.get(current) ?? []));
}
+ return records.filter((record) => retained.has(record));
+}
+
+export function hasUnifiedSessionChildren(
+ records: readonly UnifiedSessionRecord[],
+ scope: AgentsViewScopeKey,
+ index: UnifiedSessionIndex = buildUnifiedSessionIndex(records),
+): boolean {
+ const root = findScopeRecord(scope, index.byKey);
+ return root !== undefined && (index.childrenByParent.get(root)?.length ?? 0) > 0;
+}
+
+export function getUnifiedSessionAncestorSessionIds(
+ records: readonly UnifiedSessionRecord[],
+ scope: AgentsViewScopeKey,
+ index: UnifiedSessionIndex = buildUnifiedSessionIndex(records),
+): string[] {
+ const root = findScopeRecord(scope, index.byKey);
+ if (!root) return [];
+ const ancestors: string[] = [];
+ const visited = new Set<UnifiedSessionRecord>([root]);
+ let current = findParentRecord(root, index.byKey);
+ while (current && !visited.has(current)) {
+ visited.add(current);
+ ancestors.unshift(summaryForUnifiedRecord(current).sessionId);
+ current = findParentRecord(current, index.byKey);
+ }
+ return ancestors;
+}
+export function filterUnifiedSessions(
+ records: readonly UnifiedSessionRecord[],
+ matches: (searchableText: string) => boolean,
+): UnifiedSessionRecord[] {
+ const index = buildUnifiedSessionIndex(records);
const retained = new Set<UnifiedSessionRecord>();
for (const record of records) {
if (!matches(record.searchableText)) continue;
let current: UnifiedSessionRecord | undefined = record;
while (current && !retained.has(current)) {
retained.add(current);
- current = findParentRecord(current, recordsByKey);
+ current = findParentRecord(current, index.byKey);
}
}
// Keep catalog order and the original records so row ranking and sections
@@ -257,13 +409,45 @@ export function filterUnifiedSessions(
return records.filter((record) => retained.has(record));
}
+export interface UnifiedSessionIndex {
+ byKey: Map<string, UnifiedSessionRecord>;
+ childrenByParent: Map<UnifiedSessionRecord, UnifiedSessionRecord[]>;
+}
+
+export function buildUnifiedSessionIndex(records: readonly UnifiedSessionRecord[]): UnifiedSessionIndex {
+ const byKey = new Map<string, UnifiedSessionRecord>();
+ for (const record of records) {
+ for (const key of record.identityAliases) byKey.set(key, record);
+ }
+ const childrenByParent = new Map<UnifiedSessionRecord, UnifiedSessionRecord[]>();
+ for (const record of records) {
+ const parent = findParentRecord(record, byKey);
+ if (!parent || parent === record) continue;
+ const children = childrenByParent.get(parent) ?? [];
+ children.push(record);
+ childrenByParent.set(parent, children);
+ }
+ return { byKey, childrenByParent };
+}
+
+function findScopeRecord(
+ scope: AgentsViewScopeKey,
+ byKey: ReadonlyMap<string, UnifiedSessionRecord>,
+): UnifiedSessionRecord | undefined {
+ if (scope.activeSessionId) {
+ const active = byKey.get(`active:${scope.activeSessionId}`);
+ if (active) return active;
+ }
+ return byKey.get(`session:${scope.sessionId}`);
+}
+
function findParentRecord(
record: UnifiedSessionRecord,
byKey: ReadonlyMap<string, UnifiedSessionRecord>,
): UnifiedSessionRecord | undefined {
- // Only live daemon summaries carry parent links; saved-only rows are roots.
- if (!record.daemon) return undefined;
- for (const key of getParentKeys(record.daemon)) {
+ const daemonKeys = record.daemon ? getParentKeys(record.daemon) : [];
+ const savedKey = record.saved?.parentSessionPath ? fileIdentity(record.saved.parentSessionPath) : undefined;
+ for (const key of savedKey ? [...daemonKeys, savedKey] : daemonKeys) {
const parent = byKey.get(key);
if (parent) return parent;
}
@@ -429,16 +613,29 @@ export function buildAgentsViewRows(
summariesOrRecords: readonly (SessionSummary | UnifiedSessionRecord)[],
expandedSubagentParents: ReadonlySet<string> = new Set(),
programShownParents: ReadonlySet<string> = new Set(),
+ scope?: AgentsViewScopeKey,
): AgentsViewRow[] {
const inputs = summariesOrRecords.map((input) =>
isUnifiedSessionRecord(input) ? { summary: summaryForUnifiedRecord(input), record: input } : { summary: input },
);
+ const scopeRoot = scope
+ ? inputs.find(
+ ({ summary }) =>
+ summary.sessionId === scope.sessionId ||
+ (scope.activeSessionId !== undefined && summary.activeSessionId === scope.activeSessionId),
+ )
+ : undefined;
+ const scopeRootKeys = new Set(
+ scopeRoot ? (scopeRoot.record?.identityAliases ?? getSummaryKeys(scopeRoot.summary)) : [],
+ );
+ const isDirectScopeChild = (summary: SessionSummary): boolean =>
+ scopeRoot !== undefined && getParentKeys(summary).some((key) => scopeRootKeys.has(key));
const baseRows = inputs.map(
({ summary, record }): MutableAgentsViewRow => ({
- kind: isSubagentSummary(summary) ? "subagent" : "agent",
+ kind: isSubagentSummary(summary) && !isDirectScopeChild(summary) ? "subagent" : "agent",
section: record?.section ?? classifyAgentsViewSession(summary),
summary,
- title: getSessionTitle(summary),
+ title: getAgentsViewSessionTitle(summary),
subtitle: getSessionSubtitle(summary),
statusLabel: getSessionStatusLabel(summary),
depth: 0,
@@ -457,11 +654,14 @@ export function buildAgentsViewRows(
if (row.kind !== "subagent") {
continue;
}
- nestedRows.add(row);
const parent = findParentRow(row.summary, rowsByKey);
if (!parent || parent === row) {
+ // Saved catalogs stream progressively, so a child can arrive before its
+ // parent. Keep it reachable as a root until the parent record appears.
+ row.kind = "agent";
continue;
}
+ nestedRows.add(row);
parentByChild.set(row, parent);
if (row.section === "running") {
parent.runningSubagentCount += 1;
@@ -500,7 +700,9 @@ export function buildAgentsViewRows(
flattened.push(createSubagentSummaryRow(row, children, depth + 1, childHasSpawnCode));
}
};
- for (const root of roots.sort(compareAgentsViewRows)) {
+ const scopedRootRow = scopeRoot ? baseRows.find((row) => row.summary === scopeRoot.summary) : undefined;
+ const visibleRoots = scopedRootRow ? roots.filter((row) => row !== scopedRootRow) : roots;
+ for (const root of visibleRoots.sort(compareAgentsViewRows)) {
emit(root, 0);
}
return flattened;
@@ -682,7 +884,11 @@ function isSubagentSummary(summary: SessionSummary): boolean {
// Summaries from daemons that predate runtimeKind still carry subagent
// linkage; never surface those as top-level agents.
return Boolean(
- summary.rlmChildId ?? summary.rlmParentNodeId ?? summary.parentActiveSessionId ?? summary.parentSessionId,
+ summary.rlmChildId ??
+ summary.rlmParentNodeId ??
+ summary.parentActiveSessionId ??
+ summary.parentSessionId ??
+ summary.parentSessionPath,
);
}
@@ -709,7 +915,7 @@ function getTimestamp(value: string | undefined): number {
return Number.isNaN(timestamp) ? 0 : timestamp;
}
-function getSessionTitle(summary: SessionSummary): string {
+export function getAgentsViewSessionTitle(summary: SessionSummary): string {
const candidates = [summary.sessionName, summary.firstMessage, basename(summary.cwd), summary.sessionId, summary.id];
for (const candidate of candidates) {
const normalized = candidate?.replace(/\s+/g, " ").trim();
diff --git a/packages/coding-agent/src/modes/index.ts b/packages/coding-agent/src/modes/index.ts
index 43ebadf4a4..c7a1723a20 100644
--- a/packages/coding-agent/src/modes/index.ts
+++ b/packages/coding-agent/src/modes/index.ts
@@ -22,20 +22,33 @@ export { DaemonAgentConnection, InProcessAgentConnection } from "./agent-connect
export { type AgentsViewModeOptions, runAgentsViewMode } from "./agents-view/agents-view-mode.js";
export {
type AgentsViewRow,
+ type AgentsViewScopeFrame,
+ type AgentsViewScopeKey,
type AgentsViewSection,
type AgentsViewSelectionKey,
aggregateSessionHeartbeats,
buildAgentsViewRows,
+ buildUnifiedSessionIndex,
classifyAgentsViewSession,
+ createUnattachableChildOpenResult,
filterUnifiedSessions,
formatHeartbeatBadge,
getAgentsViewSelectionKey,
+ getAgentsViewSessionTitle,
+ getUnifiedSessionAncestorSessionIds,
+ hasUnifiedSessionChildren,
reconcileUnifiedSessions,
+ resolveAgentsViewLeftResult,
+ resolveAgentsViewScopeFrames,
resolveAgentsViewSelectionIndex,
resolveAgentsViewSelectionState,
+ scopeToSessionSubtree,
sectionTitle,
+ shouldApplyScopeResolution,
shouldShowAgentsViewSession,
+ transitionAgentsViewScope,
type UnifiedSessionHeartbeat,
+ type UnifiedSessionIndex,
type UnifiedSessionRecord,
} from "./agents-view/agents-view-state.js";
export {
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index c1ca3decb3..bd0b173425 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -815,8 +815,10 @@ export interface InteractiveModeOptions {
* which also covers direct daemon attaches where the agents view was never shown.
*/
agentsViewOwnsStartupNotices?: boolean;
- /** Open the read-only detail view for this subagent node right after startup. */
- initialSubagentNodeId?: string;
+ /** Persisted RLM depth supplied by the daemon SessionSummary. */
+ sessionDepth?: number;
+ /** Whether the unified daemon/catalog projection had any direct children. */
+ sessionHasChildren?: boolean;
/** Client-owned stash store shared across chat views in this TUI process. */
promptStashStore?: ClientPromptStashStore;
/** Initial stable session id used to scope prompt stash state. */
@@ -824,10 +826,15 @@ export interface InteractiveModeOptions {
}
export interface InteractiveModeRunResult {
- type: "agents_view";
+ type: "agents_view" | "scoped_agents_view";
source: Pick<AgentConnectionState, "activeSessionId" | "sessionFile" | "sessionId" | "sessionName" | "cwd">;
}
+export function formatAgentDepthLabel(depth: number | undefined, hasChildren: boolean): string | undefined {
+ if (depth === undefined || (depth === 0 && !hasChildren)) return undefined;
+ return `depth ${depth}`;
+}
+
export class InteractiveMode {
private static readonly EXIT_HINT_DURATION_MS = 2000;
private static readonly ESCAPE_REPEAT_WINDOW_MS = 500;
@@ -877,7 +884,7 @@ export class InteractiveMode {
private pendingPromptStashReleases: { sessionId: string; state: PromptStashState }[] = [];
private readonly retainedSubmissionGenerations = new WeakMap<PromptStash, number>();
private admitPendingStartupPrompts: (() => Promise<StartupPromptBarrierOutcome>) | undefined;
- private returnToAgentsViewRequested = false;
+ private agentsViewRequest: InteractiveModeRunResult["type"] | undefined;
private loadingAnimation: Loader | undefined = undefined;
private workingMessage: string | undefined = undefined;
private workingVisible = true;
@@ -963,7 +970,6 @@ export class InteractiveMode {
private childAgentNodes: ChildAgentInspectorNode[] = [];
private childAgentDetailNodeId: string | undefined;
private childAgentPanelMode: "detail" | undefined;
- private enteredSessionViaSubagentDetail = false;
private childAgentWatcher: AgentConnectionSessionWatcher | undefined;
private childAgentWatcherToken = 0;
private childAgentWatcherMessages: AgentMessage[] = [];
@@ -1108,10 +1114,6 @@ export class InteractiveMode {
ui: this.ui,
});
this.childAgentDetail.onCancel = () => {
- if (this.options.returnToAgentsView && this.enteredSessionViaSubagentDetail) {
- void this.returnToAgentsView();
- return;
- }
this.closeChildAgentPanel({ selectNodeId: this.childAgentDetailNodeId });
};
this.childAgentDetail.onToggleToolsExpanded = () => this.toggleToolOutputExpansion();
@@ -1143,9 +1145,9 @@ export class InteractiveMode {
() => this.getTrayContextLabel(),
() => this.getTrayOverrideLabel(),
);
- this.childAgentSummary.onOpenDetail = (nodeId) => this.openChildAgentDetail(nodeId);
- // Fallback for Enter when the list emptied out while focused (no selection).
- this.childAgentSummary.onOpen = () => this.focusEditor();
+ this.childAgentSummary.onOpenDetail = () => void this.openScopedAgentsView();
+ // Fallback for Enter when the list emptied out while focused.
+ this.childAgentSummary.onOpen = () => void this.openScopedAgentsView();
this.childAgentSummary.onCancel = () => this.focusEditor();
this.childAgentSummary.onExit = () => this.handleSubagentSummaryExit();
this.childAgentSummary.onChatAction = (data) => this.handleSubagentSummaryChatAction(data);
@@ -1476,22 +1478,6 @@ export class InteractiveMode {
// Render initial messages AFTER showing loaded resources
await this.renderInitialMessages();
- // Jump straight into a subagent's read-only detail view when the agents
- // view opened this session targeting one of its subagents.
- if (this.options.initialSubagentNodeId) {
- if (this.openChildAgentDetail(this.options.initialSubagentNodeId)) {
- if (this.options.returnToAgentsView) {
- this.enteredSessionViaSubagentDetail = true;
- this.childAgentDetail.setBackHintLabel("back to agents");
- }
- } else {
- // The subagent can finish and get released between the agents view
- // listing it and this session attaching; say so instead of silently
- // landing in the parent chat.
- this.showStatus("Subagent already finished; showing its parent session");
- }
- }
-
// Set up theme file watcher
onThemeChange(() => {
this.ui.invalidate();
@@ -1722,7 +1708,7 @@ export class InteractiveMode {
const state = this.connectionState;
return {
- type: "agents_view",
+ type: this.agentsViewRequest ?? "agents_view",
source: {
activeSessionId: state?.activeSessionId,
sessionFile: state?.sessionFile,
@@ -3955,7 +3941,6 @@ export class InteractiveMode {
// Re-render queued previews cleared on panel entry; the queue may still hold messages.
this.updatePendingMessagesDisplay();
this.childAgentDetailNodeId = undefined;
- this.enteredSessionViaSubagentDetail = false;
this.childAgentDetail.setBackHintLabel("back to chat");
this.childAgentDetail.setNode(undefined);
this.childAgentPanelMode = undefined;
@@ -5017,7 +5002,7 @@ export class InteractiveMode {
if (
submissionOutcome === "lifecycle-cancelled" ||
this.isShuttingDown ||
- this.returnToAgentsViewRequested ||
+ this.agentsViewRequest ||
this.promptStashSessionId !== submissionSessionId
) {
// The editor is already torn down, but its shared session stash outlives
@@ -5039,7 +5024,7 @@ export class InteractiveMode {
const rejectedDraft = submittedDraft ?? { text };
const canRestore =
!this.isShuttingDown &&
- !this.returnToAgentsViewRequested &&
+ !this.agentsViewRequest &&
submissionGeneration === this.inputSubmissionGeneration &&
this.editor.getText().length === 0;
if (canRestore) {
@@ -5062,7 +5047,7 @@ export class InteractiveMode {
this.updatePendingMessagesDisplay();
this.ui.requestRender();
} finally {
- if (this.isShuttingDown || this.returnToAgentsViewRequested) {
+ if (this.isShuttingDown || this.agentsViewRequest) {
submissionOutcome = "lifecycle-cancelled";
}
if (
@@ -6004,6 +5989,20 @@ export class InteractiveMode {
return true;
}
+ private async openScopedAgentsView(): Promise<void> {
+ if (this.editor.getText().trim()) {
+ this.focusEditor();
+ this.showStatus("Send, stash, or clear your draft before opening agents");
+ return;
+ }
+ if (!this.options.returnToAgentsView) {
+ this.focusEditor();
+ this.showStatus("The agents view needs the daemon; start without --no-daemon to browse sessions");
+ return;
+ }
+ await this.returnToAgentsView("scoped_agents_view");
+ }
+
// Left from the focused subagent list: exit to manage sessions if available,
// otherwise just drop focus back to the editor.
private handleSubagentSummaryExit(): void {
@@ -6043,9 +6042,13 @@ export class InteractiveMode {
private getTrayLocationLabel(): string | undefined {
const modelLabel = this.getModelTrayLabel();
+ const hasChildren = this.options.sessionHasChildren === true || (this.childAgentSnapshots?.size ?? 0) > 0;
+ const depthLabel = formatAgentDepthLabel(this.options.sessionDepth, hasChildren);
const shortcutsHint = this.getShortcutsTrayHint();
const agentsHint = this.getAgentsViewTrayHint();
- return [agentsHint, modelLabel, shortcutsHint].filter((label): label is string => label !== undefined).join(" ");
+ return [agentsHint, depthLabel, modelLabel, shortcutsHint]
+ .filter((label): label is string => label !== undefined)
+ .join(" ");
}
private getShortcutsTrayHint(): string | undefined {
@@ -6162,32 +6165,6 @@ export class InteractiveMode {
this.ui.requestRender();
}
- private openChildAgentDetail(nodeId: string): boolean {
- // Live text deltas are stored without redrawing the summary on every token.
- // Rebuild once here so the detail opens with the latest preview and recap.
- this.childAgentNodes = this.buildChildAgentInspectorNodes();
- this.childAgentSummary.setNodes(this.childAgentNodes);
- const node = this.findChildAgentInspectorNode(nodeId);
- if (!node) {
- return false;
- }
- this.childAgentPanelMode = "detail";
- this.clearFeatureHintPresentation();
- this.childAgentDetailNodeId = nodeId;
- this.childAgentDetail.setNode(node);
- this.childAgentDetail.setBodyComponents([]);
- this.renderRecap();
- this.childAgentSummary.setHidden(true);
- this.editorContainer.clear();
- this.queuedMessagesContainer.clear();
- this.mainViewContainer.clear();
- this.mainViewContainer.addChild(this.childAgentDetail);
- this.ui.setFocus(this.childAgentDetail);
- this.ui.requestRender();
- void this.startChildAgentWatch(node);
- return true;
- }
-
private async startChildAgentWatch(node: ChildAgentInspectorNode): Promise<void> {
this.stopChildAgentWatch();
const key = node.activeSessionId ?? node.id;
@@ -6309,7 +6286,6 @@ export class InteractiveMode {
this.stopChildAgentWatch();
this.childAgentPanelMode = undefined;
this.childAgentDetailNodeId = undefined;
- this.enteredSessionViaSubagentDetail = false;
this.childAgentDetail.setBackHintLabel("back to chat");
this.childAgentDetail.setNode(undefined);
this.childAgentDetail.setBodyComponents([]);
@@ -6852,7 +6828,7 @@ export class InteractiveMode {
}
async getUserInput(): Promise<string | undefined> {
- if (this.returnToAgentsViewRequested) {
+ if (this.agentsViewRequest) {
return undefined;
}
return new Promise((resolve) => {
@@ -7071,9 +7047,9 @@ export class InteractiveMode {
await this.returnToAgentsView();
}
- private async returnToAgentsView(): Promise<void> {
- if (this.isShuttingDown || this.returnToAgentsViewRequested) return;
- this.returnToAgentsViewRequested = true;
+ private async returnToAgentsView(request: InteractiveModeRunResult["type"] = "agents_view"): Promise<void> {
+ if (this.isShuttingDown || this.agentsViewRequest) return;
+ this.agentsViewRequest = request;
this.isShuttingDown = true;
this.unregisterSignalHandlers();
diff --git a/packages/coding-agent/test/agents-view-mode.test.ts b/packages/coding-agent/test/agents-view-mode.test.ts
index ed1f9a0c0c..617a1b1c14 100644
--- a/packages/coding-agent/test/agents-view-mode.test.ts
+++ b/packages/coding-agent/test/agents-view-mode.test.ts
@@ -1,5 +1,59 @@
-import { describe, expect, it, vi } from "vitest";
-import { AgentsViewMode } from "../src/modes/agents-view/agents-view-mode.js";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { ModelRegistry } from "../src/core/model-registry.js";
+import { SettingsManager } from "../src/core/settings-manager.js";
+import { DaemonAgentConnection } from "../src/modes/agent-connection/daemon-agent-connection.js";
+import {
+ AgentsViewMode,
+ type AgentsViewPersistentState,
+ combineAgentsViewStartupNotices,
+ createInitialAgentsViewPersistentState,
+ runAgentsViewMode,
+} from "../src/modes/agents-view/agents-view-mode.js";
+import { DaemonClient } from "../src/modes/daemon/daemon-client.js";
+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
+import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
+import type { InteractiveModeUiServices } from "../src/modes/interactive/interactive-mode-services.js";
+import { stopThemeWatcher } from "../src/modes/interactive/theme/theme.js";
+
+function summary(overrides: Partial<SessionSummary> = {}): SessionSummary {
+ return {
+ id: "root-active",
+ activeSessionId: "root-active",
+ lifecycle: "live",
+ activity: "idle",
+ isSessionActive: true,
+ runtimeKind: "top-level",
+ sessionId: "root-session",
+ cwd: process.cwd(),
+ isStreaming: false,
+ isCompacting: false,
+ attachedClients: 0,
+ messageCount: 1,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
+ ...overrides,
+ };
+}
+
+function createUiServices(): InteractiveModeUiServices {
+ return {
+ settingsManager: SettingsManager.inMemory({ theme: "dark" }),
+ modelRegistry: {} as ModelRegistry,
+ getInitialCwd: () => process.cwd(),
+ getInitialSessionName: () => undefined,
+ getThemes: () => [],
+ };
+}
+
+function invoke(method: string, self: object, ...args: unknown[]): unknown {
+ const member = Reflect.get(AgentsViewMode.prototype, method) as ((...args: unknown[]) => unknown) | undefined;
+ if (typeof member !== "function") throw new Error(`AgentsViewMode.${method} no longer exists`);
+ return member.call(self, ...args);
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ stopThemeWatcher();
+});
describe("AgentsViewMode search selection", () => {
it("keeps the selection chosen by row rebuilding when the query changes", () => {
@@ -19,3 +73,205 @@ describe("AgentsViewMode search selection", () => {
expect(self.selectedIndex).toBe(4);
});
});
+
+describe("AgentsViewMode persistent catalog state", () => {
+ it("keeps an initial handoff scope when the first live poll fails after both catalogs settle", async () => {
+ const root = summary();
+ const scope = { sessionId: root.sessionId, activeSessionId: root.activeSessionId };
+ const persistentState = createInitialAgentsViewPersistentState({
+ initialScopeKey: scope,
+ initialSession: root,
+ });
+ 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");
+ }),
+ });
+
+ 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);
+ expect(persistentState.scopeFrames).toEqual([{ scope, returnChat: root }]);
+ expect(persistentState.lastSuccessfulLiveSummaries).toEqual([root]);
+ } finally {
+ stopThemeWatcher();
+ }
+ });
+
+ it("keeps a live-only scope after a fresh instance's first live poll fails", async () => {
+ const root = summary();
+ const persistentState: AgentsViewPersistentState = {
+ scopeFrames: [{ scope: { sessionId: root.sessionId, activeSessionId: root.activeSessionId } }],
+ lastSuccessfulLiveSummaries: [root],
+ 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");
+ }),
+ });
+
+ try {
+ await expect(invoke("refreshSessions", view, { preserveStatusOnError: true })).resolves.toBe(false);
+ expect(persistentState.scopeFrames).toEqual([
+ { scope: { sessionId: root.sessionId, activeSessionId: root.activeSessionId } },
+ ]);
+ } finally {
+ stopThemeWatcher();
+ }
+ });
+
+ it("keeps a live-only scope through reconnect timeout and settles it on the next successful list", async () => {
+ vi.useFakeTimers();
+ const root = summary();
+ const frame = { scope: { sessionId: root.sessionId, activeSessionId: root.activeSessionId } };
+ const persistentState: AgentsViewPersistentState = {
+ scopeFrames: [frame],
+ lastSuccessfulLiveSummaries: [root],
+ lastSuccessfulSavedSessions: [],
+ };
+ const view = new AgentsViewMode(
+ { config: {}, uiServices: createUiServices(), reconnectTimeoutMs: 0 },
+ persistentState,
+ );
+ const client = { isConnected: false, reconnect: vi.fn() };
+ Reflect.set(view, "client", client);
+ Reflect.set(view, "liveCatalogReady", true);
+ Reflect.set(view, "savedCatalogReady", true);
+
+ try {
+ await expect(invoke("reconnectClient", view, client, new Error("disconnected"))).resolves.toBeUndefined();
+ 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);
+ expect(persistentState.scopeFrames).toEqual([]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ 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" });
+ const returnedRoot = { ...root, sessionName: "Updated root" };
+ const scope = { sessionId: root.sessionId, activeSessionId: root.activeSessionId };
+ let runs = 0;
+ vi.spyOn(AgentsViewMode.prototype, "run").mockImplementation(async function (this: AgentsViewMode) {
+ runs += 1;
+ const persistentState = Reflect.get(this, "persistentState") as AgentsViewPersistentState;
+ if (runs === 1) {
+ persistentState.lastSuccessfulLiveSummaries = [other];
+ persistentState.lastSuccessfulSavedSessions = [];
+ return { type: "open", summary: root, hasChildren: false };
+ }
+
+ expect(persistentState.lastSuccessfulLiveSummaries).toEqual([other, returnedRoot]);
+ Reflect.set(this, "client", {
+ isConnected: true,
+ request: vi.fn(async () => {
+ throw new Error("transient list failure");
+ }),
+ });
+ await expect(invoke("refreshSessions", this, { preserveStatusOnError: true })).resolves.toBe(false);
+ expect(persistentState.scopeFrames).toEqual([{ scope, returnChat: returnedRoot }]);
+ return { type: "exit" };
+ });
+ vi.spyOn(DaemonClient.prototype, "connect").mockResolvedValue();
+ vi.spyOn(DaemonAgentConnection, "attach").mockResolvedValue({
+ dispose: vi.fn(async () => {}),
+ onBeforeSessionInvalidate: vi.fn(),
+ } as unknown as DaemonAgentConnection);
+ vi.spyOn(InteractiveMode.prototype, "run").mockResolvedValue({
+ type: "scoped_agents_view",
+ source: {
+ activeSessionId: root.activeSessionId!,
+ sessionId: root.sessionId,
+ sessionName: returnedRoot.sessionName,
+ cwd: root.cwd,
+ },
+ });
+
+ await runAgentsViewMode({
+ config: { cwd: process.cwd() },
+ socketPath: "/tmp/agents-view-test.sock",
+ uiServices: createUiServices(),
+ });
+
+ expect(runs).toBe(2);
+ });
+});
+
+describe("agents view startup notices", () => {
+ it("combines the open fallback and cwd fallback without dropping either notice", () => {
+ expect(combineAgentsViewStartupNotices("Child unavailable", "Original directory is missing")).toBe(
+ "Child unavailable · Original directory is missing",
+ );
+ expect(combineAgentsViewStartupNotices("Child unavailable", undefined)).toBe("Child unavailable");
+ expect(combineAgentsViewStartupNotices(undefined, "Original directory is missing")).toBe(
+ "Original directory is missing",
+ );
+ });
+
+ it("persists the combined open and cwd fallback notices after returning to agents view", async () => {
+ const root = summary({
+ activeSessionId: undefined,
+ cwd: "/definitely/not/a/real/dir/for/this/test",
+ lifecycle: "archived",
+ sessionFile: "/tmp/root.jsonl",
+ });
+ let runs = 0;
+ vi.spyOn(AgentsViewMode.prototype, "run").mockImplementation(async function (this: AgentsViewMode) {
+ runs += 1;
+ if (runs === 1) {
+ return {
+ type: "open",
+ summary: root,
+ hasChildren: false,
+ statusMessage: "Child unavailable",
+ };
+ }
+ expect(Reflect.get(this, "persistentState")).toMatchObject({
+ statusMessage: `Child unavailable · Original directory is missing (${root.cwd}); opened in ${process.cwd()} instead.`,
+ });
+ return { type: "exit" };
+ });
+ vi.spyOn(DaemonClient.prototype, "connect").mockResolvedValue();
+ vi.spyOn(DaemonClient.prototype, "request").mockResolvedValue({
+ type: "response",
+ command: "create",
+ success: true,
+ data: { ...root, cwd: process.cwd(), activeSessionId: "resumed-active", lifecycle: "live" },
+ });
+ vi.spyOn(DaemonAgentConnection, "attach").mockResolvedValue({
+ dispose: vi.fn(async () => {}),
+ onBeforeSessionInvalidate: vi.fn(),
+ } as unknown as DaemonAgentConnection);
+ vi.spyOn(InteractiveMode.prototype, "run").mockResolvedValue({
+ type: "agents_view",
+ source: {
+ activeSessionId: "resumed-active",
+ sessionId: root.sessionId,
+ cwd: process.cwd(),
+ },
+ });
+
+ await runAgentsViewMode({
+ config: { cwd: process.cwd() },
+ socketPath: "/tmp/agents-view-test.sock",
+ uiServices: createUiServices(),
+ });
+
+ expect(runs).toBe(2);
+ });
+});
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index cf033a88c6..26003edce5 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -10,27 +10,42 @@ import {
createAgentsViewListCommand,
createAgentsViewReplyHeadline,
createAgentsViewResumeConfig,
+ createInitialAgentsViewPersistentState,
+ createInitialAgentsViewScopeFrames,
+ createScopeBackReturnChatOpenResult,
formatAgentsViewRelativeTime,
formatAgentsViewStatusLine,
+ getAgentsViewDepth,
resolveAgentsViewActiveSummaryForPath,
resolveAgentsViewOpenCwd,
resolveAgentsViewSessionUiServices,
shouldReconnectAgentsViewDaemon,
} from "../src/modes/agents-view/agents-view-mode.js";
import {
+ type AgentsViewScopeFrame,
aggregateSessionHeartbeats,
buildAgentsViewRows,
+ buildUnifiedSessionIndex,
classifyAgentsViewSession,
+ createUnattachableChildOpenResult,
filterUnifiedSessions,
formatHeartbeatBadge,
getAgentsViewSelectionKey,
+ getUnifiedSessionAncestorSessionIds,
+ hasUnifiedSessionChildren,
reconcileUnifiedSessions,
+ resolveAgentsViewLeftResult,
+ resolveAgentsViewScopeFrames,
resolveAgentsViewSelectionIndex,
resolveAgentsViewSelectionState,
type SessionSummary,
+ scopeToSessionSubtree,
sectionTitle,
+ shouldApplyScopeResolution,
shouldShowAgentsViewSession,
+ transitionAgentsViewScope,
} from "../src/modes/index.js";
+import { formatAgentDepthLabel } from "../src/modes/interactive/interactive-mode.js";
import type { InteractiveModeUiServices } from "../src/modes/interactive/interactive-mode-services.js";
import type { Theme } from "../src/modes/interactive/theme/theme.js";
@@ -514,7 +529,7 @@ describe("agents view state", () => {
expect(rows[1]?.selectable).toBe(true);
});
- test("treats parent-linked summaries without runtimeKind as subagents", () => {
+ test("treats parent-linked summaries without runtimeKind as subagents and re-roots unresolved ones", () => {
const rows = buildAgentsViewRows([
makeSummary({
id: "legacy-child",
@@ -547,6 +562,7 @@ describe("agents view state", () => {
expect(rows.map((row) => [row.title, row.kind])).toEqual([
["Parent", "agent"],
["1 subagent running", "subagent-summary"],
+ ["Legacy rlm child", "agent"],
]);
expect(rows[0]?.runningSubagentCount).toBe(1);
});
@@ -660,7 +676,7 @@ describe("agents view state", () => {
expect(bodyLines[10]).toBe("… +15 more lines");
});
- test("omits subagents when their parent is not visible", () => {
+ test("re-roots live subagents when their parent is not visible", () => {
const rows = buildAgentsViewRows([
makeSummary({
id: "child-active",
@@ -683,7 +699,10 @@ describe("agents view state", () => {
}),
]);
- expect(rows.map((row) => row.title)).toEqual(["Other"]);
+ expect(rows.map((row) => [row.title, row.kind, row.depth])).toEqual([
+ ["Child", "agent", 0],
+ ["Other", "agent", 0],
+ ]);
});
test("shows daemon-resident sessions only", () => {
@@ -1132,6 +1151,315 @@ describe("agents view state", () => {
expect(resolveAgentsViewSelectionIndex(rows, undefined, undefined)).toBe(-1);
});
});
+
+ describe("scoped navigation", () => {
+ const rootScope = { sessionId: "root-session", activeSessionId: "root-active" };
+ const childScope = { sessionId: "child-session", activeSessionId: "child-active" };
+
+ test("seeds handoff scope frames with the matching return chat", () => {
+ const chat = makeSummary({ sessionId: "root-session", activeSessionId: "root-active" });
+ const persistentState = createInitialAgentsViewPersistentState({
+ initialScopeKey: rootScope,
+ initialSession: chat,
+ });
+ const handoffFrame = persistentState.scopeFrames?.at(-1);
+
+ expect(handoffFrame).toEqual({ scope: rootScope, returnChat: chat });
+ expect(createInitialAgentsViewScopeFrames(rootScope, persistentState.backSession)).toEqual([handoffFrame]);
+ expect(createInitialAgentsViewScopeFrames(rootScope, makeSummary({ sessionId: "stale-session" }))).toEqual([
+ { scope: rootScope },
+ ]);
+
+ const leftResult = resolveAgentsViewLeftResult(chat, [], handoffFrame?.returnChat);
+ expect(leftResult?.type).toBe("scope_back");
+ if (leftResult?.type !== "scope_back") throw new Error("Expected scoped Left navigation");
+ expect(createScopeBackReturnChatOpenResult({ ...leftResult, hasChildren: true })).toMatchObject({
+ type: "open",
+ summary: { sessionId: "root-session", activeSessionId: "root-active" },
+ });
+ });
+
+ test("pushes and pops immutable scope frames with their return chats one level at a time", () => {
+ const initial: AgentsViewScopeFrame[] = [];
+ const rootChat = makeSummary({ sessionId: "root-session" });
+ const childChat = makeSummary({ sessionId: "child-session" });
+ const rootFrames = transitionAgentsViewScope(initial, {
+ type: "push",
+ scope: rootScope,
+ returnChat: rootChat,
+ });
+ const childFrames = transitionAgentsViewScope(rootFrames, {
+ type: "push",
+ scope: childScope,
+ returnChat: childChat,
+ });
+
+ expect(initial).toEqual([]);
+ expect(childFrames.map((frame) => [frame.scope.sessionId, frame.returnChat?.sessionId])).toEqual([
+ ["root-session", "root-session"],
+ ["child-session", "child-session"],
+ ]);
+ expect(JSON.parse(JSON.stringify(childFrames))).toEqual(childFrames);
+ expect(transitionAgentsViewScope(childFrames, { type: "back" })).toEqual(rootFrames);
+ expect(transitionAgentsViewScope(rootFrames, { type: "back" })).toEqual([]);
+ });
+
+ test("refreshes the current frame instead of duplicating the same session", () => {
+ const frames = transitionAgentsViewScope([{ scope: rootScope }], {
+ type: "push",
+ scope: { ...rootScope, activeSessionId: "root-active-2" },
+ });
+ expect(frames).toEqual([{ scope: { ...rootScope, activeSessionId: "root-active-2" } }]);
+ });
+
+ test("Left is a no-op globally and returns through a surviving scoped chat", () => {
+ const root = makeSummary({ sessionId: "root-session", activeSessionId: "root-active" });
+ const recordedChat = makeSummary({ sessionId: "root-session", activeSessionId: "stale-active" });
+
+ expect(resolveAgentsViewLeftResult(undefined)).toBeUndefined();
+ expect(resolveAgentsViewLeftResult(root, [], recordedChat)).toMatchObject({
+ type: "scope_back",
+ selection: { sessionId: "root-session" },
+ returnChat: { sessionId: "root-session", activeSessionId: "root-active" },
+ });
+ });
+
+ test("Left falls back to the parent agents view when the recorded chat is gone", () => {
+ const root = makeSummary({ sessionId: "replacement-session" });
+ const deletedChat = makeSummary({ sessionId: "deleted-session" });
+
+ expect(resolveAgentsViewLeftResult(root, ["parent-session"], deletedChat)).toEqual({
+ type: "scope_back",
+ selection: root,
+ expandedAncestorSessionIds: ["parent-session"],
+ });
+ });
+
+ test("carries expansion and child metadata when scope-back reopens its return chat", () => {
+ const root = makeSummary({ sessionId: "root-session", activeSessionId: "root-active" });
+
+ expect(
+ createScopeBackReturnChatOpenResult({
+ type: "scope_back",
+ selection: root,
+ returnChat: root,
+ expandedAncestorSessionIds: ["ancestor-session", "parent-session"],
+ hasChildren: true,
+ }),
+ ).toEqual({
+ type: "open",
+ summary: root,
+ expandedAncestorSessionIds: ["ancestor-session", "parent-session"],
+ hasChildren: true,
+ });
+ });
+
+ test("falls back to the nearest surviving scope frame, then global", () => {
+ const root = makeSummary({
+ id: "root-active",
+ activeSessionId: "root-active",
+ sessionId: "root-session",
+ });
+ const frames = [{ scope: rootScope }, { scope: childScope }];
+ const records = reconcileUnifiedSessions([root], []);
+
+ expect(resolveAgentsViewScopeFrames(records, frames)).toMatchObject({
+ frames: [{ scope: rootScope }],
+ root: { daemon: { sessionId: "root-session" } },
+ droppedFrames: 1,
+ });
+ 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);
+ });
+ });
+
+ describe("scoped unified records", () => {
+ test("buildAgentsViewRows excludes the scope root", () => {
+ const root = makeSummary({
+ id: "root-active",
+ activeSessionId: "root-active",
+ sessionId: "root-session",
+ sessionName: "Root",
+ });
+ const scope = { sessionId: "root-session", activeSessionId: "root-active" };
+
+ expect(buildAgentsViewRows([root], new Set(), new Set(), scope)).toEqual([]);
+ });
+
+ test("buildAgentsViewRows promotes direct scope children to root agent rows", () => {
+ const root = makeSummary({
+ id: "root-active",
+ activeSessionId: "root-active",
+ sessionId: "root-session",
+ sessionName: "Root",
+ });
+ const child = makeSummary({
+ id: "child-active",
+ activeSessionId: "child-active",
+ sessionId: "child-session",
+ sessionName: "Child",
+ runtimeKind: "subagent",
+ parentActiveSessionId: "root-active",
+ parentSessionId: "root-session",
+ });
+ const scope = { sessionId: "root-session", activeSessionId: "root-active" };
+
+ expect(buildAgentsViewRows([root, child], new Set(), new Set(), scope)).toMatchObject([
+ { kind: "agent", depth: 0, summary: { sessionId: "child-session" } },
+ ]);
+ });
+
+ test("buildAgentsViewRows re-roots a saved child whose parent file is missing", () => {
+ const [child] = reconcileUnifiedSessions(
+ [],
+ [
+ makeSessionInfo({
+ id: "saved-child",
+ path: "/tmp/project/saved-child.jsonl",
+ parentSessionPath: "/tmp/project/missing-parent.jsonl",
+ }),
+ ],
+ );
+
+ expect(buildAgentsViewRows([child!])).toMatchObject([
+ { kind: "agent", depth: 0, summary: { sessionId: "saved-child" } },
+ ]);
+ });
+
+ test("gets ancestor session ids from root to immediate parent", () => {
+ const records = reconcileUnifiedSessions(
+ [
+ makeSummary({ id: "root", activeSessionId: "root", sessionId: "root-session" }),
+ makeSummary({
+ id: "child",
+ activeSessionId: "child",
+ sessionId: "child-session",
+ runtimeKind: "subagent",
+ parentActiveSessionId: "root",
+ }),
+ makeSummary({
+ id: "grandchild",
+ activeSessionId: "grandchild",
+ sessionId: "grandchild-session",
+ runtimeKind: "subagent",
+ parentActiveSessionId: "child",
+ }),
+ ],
+ [],
+ );
+ const index = buildUnifiedSessionIndex(records);
+
+ expect(
+ getUnifiedSessionAncestorSessionIds(
+ records,
+ { sessionId: "grandchild-session", activeSessionId: "grandchild" },
+ index,
+ ),
+ ).toEqual(["root-session", "child-session"]);
+ });
+
+ test("reports no children for leaf and unresolvable scopes", () => {
+ const records = reconcileUnifiedSessions(
+ [makeSummary({ id: "leaf", activeSessionId: "leaf", sessionId: "leaf-session" })],
+ [],
+ );
+ const index = buildUnifiedSessionIndex(records);
+
+ expect(hasUnifiedSessionChildren(records, { sessionId: "leaf-session", activeSessionId: "leaf" }, index)).toBe(
+ false,
+ );
+ expect(hasUnifiedSessionChildren(records, { sessionId: "missing" }, index)).toBe(false);
+ expect(scopeToSessionSubtree(records, { sessionId: "missing" }, index)).toEqual([]);
+ });
+ test("includes registry-backed and saved-only passive descendants", () => {
+ const rootPath = "/tmp/project/root.jsonl";
+ const root = makeSummary({
+ id: "root-active",
+ activeSessionId: "root-active",
+ sessionId: "root-session",
+ sessionFile: rootPath,
+ rlmDepth: 0,
+ });
+ const registryChild = makeSummary({
+ id: "registry-child",
+ activeSessionId: undefined,
+ sessionId: "registry-child",
+ sessionFile: "/tmp/project/registry-child.jsonl",
+ runtimeKind: "subagent",
+ parentSessionId: "root-session",
+ rlmDepth: 1,
+ });
+ const records = reconcileUnifiedSessions(
+ [root, registryChild],
+ [
+ makeSessionInfo({ path: rootPath, id: "root-session", rlmDepth: 0 }),
+ makeSessionInfo({
+ path: "/tmp/project/saved-child.jsonl",
+ id: "saved-child",
+ parentSessionPath: rootPath,
+ rlmDepth: 1,
+ }),
+ ],
+ );
+ const scope = { sessionId: "root-session", activeSessionId: "root-active" };
+ const scoped = scopeToSessionSubtree(records, scope);
+ const rows = buildAgentsViewRows(scoped, new Set(), new Set(), scope);
+
+ expect(hasUnifiedSessionChildren(records, scope)).toBe(true);
+ expect(scoped.map((record) => record.daemon?.sessionId ?? record.saved?.id)).toEqual([
+ "root-session",
+ "registry-child",
+ "saved-child",
+ ]);
+ expect(rows).toHaveLength(2);
+ expect(rows.every((row) => row.kind === "agent" && row.depth === 0)).toBe(true);
+ expect(rows.find((row) => row.summary.sessionId === "registry-child")?.summary).toMatchObject({
+ parentSessionId: "root-session",
+ rlmDepth: 1,
+ });
+ expect(rows.find((row) => row.summary.sessionId === "saved-child")?.summary).toMatchObject({
+ parentSessionPath: rootPath,
+ rlmDepth: 1,
+ });
+ });
+ });
+
+ test("unattachable-child fallback preserves child selection and explains the parent open", () => {
+ const child = makeSummary({ id: "child", sessionId: "child-session" });
+ const parent = makeSummary({ id: "parent", sessionId: "parent-session" });
+ const result = createUnattachableChildOpenResult(child, parent, ["root-session"], true);
+
+ expect(result).toMatchObject({
+ type: "open",
+ summary: { sessionId: "parent-session" },
+ selection: { sessionId: "child-session" },
+ expandedAncestorSessionIds: ["root-session"],
+ hasChildren: true,
+ statusMessage: "Child session is unavailable; opened its parent instead",
+ });
+ expect(result.selection).not.toBe(result.summary);
+ });
+
+ describe("stored depth display", () => {
+ test("labels the global agents view as depth zero and scoped views at their child level", () => {
+ expect(getAgentsViewDepth(undefined)).toBe(0);
+ expect(getAgentsViewDepth(makeSummary({ rlmDepth: 0 }))).toBe(1);
+ expect(getAgentsViewDepth(makeSummary({ rlmDepth: 3 }))).toBe(4);
+ });
+
+ test("never infers a chat depth when the persisted field is absent", () => {
+ expect(formatAgentDepthLabel(undefined, true)).toBeUndefined();
+ expect(formatAgentDepthLabel(0, false)).toBeUndefined();
+ expect(formatAgentDepthLabel(0, true)).toBe("depth 0");
+ expect(formatAgentDepthLabel(3, false)).toBe("depth 3");
+ });
+ });
});
function makeSummary(overrides: Partial<SessionSummary>): SessionSummary {
diff --git a/packages/coding-agent/test/interactive-mode-feature-hints.test.ts b/packages/coding-agent/test/interactive-mode-feature-hints.test.ts
index c9edfd4e80..ec65ce4fd9 100644
--- a/packages/coding-agent/test/interactive-mode-feature-hints.test.ts
+++ b/packages/coding-agent/test/interactive-mode-feature-hints.test.ts
@@ -195,7 +195,6 @@ describe("InteractiveMode feature hints", () => {
const mode = {
childAgentPanelMode: "detail",
childAgentDetailNodeId: "subagent-1",
- enteredSessionViaSubagentDetail: true,
childAgentDetail: { setBackHintLabel: vi.fn(), setNode: vi.fn() },
childAgentSummary: { setHidden: vi.fn() },
editor: { getText: () => "draft" },
diff --git a/packages/coding-agent/test/interactive-mode-streaming.test.ts b/packages/coding-agent/test/interactive-mode-streaming.test.ts
index b104de2207..a80be2eafb 100644
--- a/packages/coding-agent/test/interactive-mode-streaming.test.ts
+++ b/packages/coding-agent/test/interactive-mode-streaming.test.ts
@@ -59,7 +59,7 @@ type HandleEventThis = {
type HandleEvent = (this: HandleEventThis, event: AgentConnectionSessionEvent) => Promise<void>;
type GetUserInput = (this: {
- returnToAgentsViewRequested: boolean;
+ agentsViewRequest?: "agents_view" | "scoped_agents_view";
onInputCallback?: (text: string | undefined) => void;
}) => Promise<string | undefined>;
type HandleSubagentSummaryChatAction = (
@@ -286,7 +286,7 @@ describe("InteractiveMode streaming events", () => {
test("resolves input immediately after return to agents view was requested", async () => {
const getUserInput = (InteractiveMode.prototype as unknown as { getUserInput: GetUserInput }).getUserInput;
- await expect(getUserInput.call({ returnToAgentsViewRequested: true })).resolves.toBeUndefined();
+ await expect(getUserInput.call({ agentsViewRequest: "agents_view" })).resolves.toBeUndefined();
});
test("forwards typed keys from focused subagent summary back to the editor", () => {
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 2e83c4ad0b..e1b0d8d806 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
@@ -104,7 +104,7 @@ describe("#502 unified session view regressions", () => {
});
await oldPoll;
- if (kind === "live") expect(harness.applySessionList).toHaveBeenCalledWith([newer]);
+ if (kind === "live") expect(harness.applySessionList).toHaveBeenCalledWith([newer], true);
else expect(harness.heartbeats).toEqual([newer]);
expect(kind === "live" ? harness.applySessionList : harness.reconcileCatalogs).toHaveBeenCalledOnce();
},
@@ -280,7 +280,7 @@ describe("#502 unified session view regressions", () => {
await harness.reconnectPromise;
expect(client.reconnect).toHaveBeenCalledTimes(2);
- expect(harness.applySessionList).toHaveBeenCalledWith([summary("live")]);
+ expect(harness.applySessionList).toHaveBeenCalledWith([summary("live")], true);
expect(harness.heartbeats).toEqual([{ job: { id: "healthy" } }]);
expect(harness.reconnectPromise).toBeUndefined();
} finally {
@@ -422,7 +422,7 @@ describe("#502 unified session view regressions", () => {
renameTarget: mode === "rename" ? { identity: "target" } : undefined,
actionModeSearchQuery: "needle",
editor: { getText: () => "action editor text" },
- unifiedRecords: [
+ scopedRecords: [
{ identity: "match", identityAliases: [], section: "idle", searchableText: "needle session" },
{ identity: "other", identityAliases: [], section: "idle", searchableText: "other session" },
],