Skip to content

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

Rust

fix(coding-agent): reduce agents view rebuild overhead (#2272)

Florian Brand878410b3981f
diff --git a/packages/coding-agent/.changes/agents-view-rebuild-perf.md b/packages/coding-agent/.changes/agents-view-rebuild-perf.md
new file mode 100644
index 0000000000..46f9ef722e
--- /dev/null
+++ b/packages/coding-agent/.changes/agents-view-rebuild-perf.md
@@ -0,0 +1 @@
+- Fixed slow agents-view updates and searches in large session catalogs, while keeping streamed sessions and status ages current.
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 a2a96dce06..8673849cb7 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,6 +67,7 @@ import {
type StartupNotices,
} from "../shared/startup-notices.js";
import {
+ type AgentsViewRecursiveRollup,
type AgentsViewRow,
type AgentsViewScopeFrame,
type AgentsViewScopeKey,
@@ -81,6 +82,7 @@ import {
formatHeartbeatBadge,
getAgentsViewSelectionKey,
getAgentsViewSessionTitle,
+ getSessionStatusLabel,
getAgentsViewSummaryIdentity as getSummaryIdentity,
getUnifiedSessionAncestorSessionIds,
hasUnifiedSessionChildren,
@@ -102,6 +104,7 @@ import { AgentsViewRosterStore, STALE_ROSTER_DAEMON_MESSAGE } from "./roster-sto
import { matchesSearchText } from "./session-view-search.js";
const HEARTBEAT_POLL_INTERVAL_MS = 15000;
+const SAVED_CATALOG_RECONCILE_INTERVAL_MS = 75;
const RECONNECT_TIMEOUT_MS = 120000;
const RECONNECT_RETRY_MS = 1000;
const EXIT_HINT_DURATION_MS = 2000;
@@ -671,6 +674,7 @@ export class AgentsViewMode implements Component, Focusable {
private heartbeats: AgentConnectionHeartbeat[] = [];
private unifiedRecords: UnifiedSessionRecord[] = [];
private unifiedIndex: UnifiedSessionIndex = buildUnifiedSessionIndex([]);
+ private recursiveRollups: ReadonlyMap<UnifiedSessionRecord, AgentsViewRecursiveRollup> = new Map();
private scopedRecords: UnifiedSessionRecord[] = [];
private scopeKey: AgentsViewScopeKey | undefined;
private scopeRootSummary: SessionSummary | undefined;
@@ -678,6 +682,7 @@ export class AgentsViewMode implements Component, Focusable {
private savedCatalogGeneration = 0;
private heartbeatCatalogGeneration = 0;
private savedCatalogRefreshPending = false;
+ private savedCatalogReconcileTimer: ReturnType<typeof setTimeout> | undefined;
private expandedSubagentParents = new Set<string>();
// Agent row identities whose full spawn program is currently shown.
// The program key toggles each agent shown ↔ hidden.
@@ -900,8 +905,6 @@ export class AgentsViewMode implements Component, Focusable {
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);
@@ -1297,8 +1300,10 @@ export class AgentsViewMode implements Component, Focusable {
...(this.scopeKey ? [this.scopeKey.sessionId] : []),
...this.heartbeats.map((heartbeat) => heartbeat.job.sessionId),
]);
- const records = filterEmptyAgentsViewSessions(this.scopedRecords, preservedSessionIds);
- return query.trim() ? filterUnifiedSessions(records, (text) => matchesSearchText(text, query)) : records;
+ const records = filterEmptyAgentsViewSessions(this.scopedRecords, preservedSessionIds, this.unifiedIndex);
+ return query.trim()
+ ? filterUnifiedSessions(records, (text) => matchesSearchText(text, query), this.unifiedIndex)
+ : records;
}
/** Rebuild rows from the last fetched summaries, keeping selection on the same row. */
@@ -1309,7 +1314,7 @@ export class AgentsViewMode implements Component, Focusable {
this.expandedSubagentParents,
this.programShownParents,
this.scopeKey,
- computeRecursiveRollups(this.unifiedRecords, this.unifiedIndex),
+ this.recursiveRollups,
this.anchorSessionId,
);
const index =
@@ -2158,6 +2163,7 @@ 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);
+ this.recursiveRollups = computeRecursiveRollups(this.unifiedRecords, this.unifiedIndex);
migrateAgentsViewIdentitySet(this.expandedSubagentParents, this.unifiedIndex.byKey);
migrateAgentsViewIdentitySet(this.programShownParents, this.unifiedIndex.byKey);
@@ -2179,7 +2185,7 @@ export class AgentsViewMode implements Component, Focusable {
this.expandedSubagentParents,
this.programShownParents,
this.scopeKey,
- computeRecursiveRollups(this.unifiedRecords, this.unifiedIndex),
+ this.recursiveRollups,
this.anchorSessionId,
);
this.applyPendingAncestorExpansion();
@@ -2200,6 +2206,10 @@ export class AgentsViewMode implements Component, Focusable {
}
const generation = ++this.savedCatalogGeneration;
this.persistentState.savedCatalogGeneration = generation;
+ if (this.savedCatalogReconcileTimer) {
+ clearTimeout(this.savedCatalogReconcileTimer);
+ this.savedCatalogReconcileTimer = undefined;
+ }
this.savedCatalogRefreshPending = true;
this.savedCatalogReady = false;
const successfulSessions = this.lastSuccessfulSavedSessions;
@@ -2210,9 +2220,16 @@ export class AgentsViewMode implements Component, Focusable {
const onSession = (session: AgentConnectionSavedSessionInfo) => {
if (generation !== this.savedCatalogGeneration) return;
progressiveSessions.set(resolvePath(canonicalizePath(session.path)), session);
- this.savedSessions = [...progressiveSessions.values()];
- this.persistentState.savedSessions = this.savedSessions;
- this.reconcileCatalogs();
+ // Keep a bounded batch window so a continuous stream still appears progressively.
+ if (this.savedCatalogReconcileTimer) return;
+ this.savedCatalogReconcileTimer = setTimeout(() => {
+ if (generation !== this.savedCatalogGeneration) return;
+ this.savedCatalogReconcileTimer = undefined;
+ this.savedSessions = [...progressiveSessions.values()];
+ this.persistentState.savedSessions = this.savedSessions;
+ this.reconcileCatalogs();
+ }, SAVED_CATALOG_RECONCILE_INTERVAL_MS);
+ this.savedCatalogReconcileTimer.unref?.();
};
const sessions = await listDaemonSavedSessions(
this.requireClient(),
@@ -2246,6 +2263,10 @@ export class AgentsViewMode implements Component, Focusable {
return false;
} finally {
if (generation === this.savedCatalogGeneration) {
+ if (this.savedCatalogReconcileTimer) {
+ clearTimeout(this.savedCatalogReconcileTimer);
+ this.savedCatalogReconcileTimer = undefined;
+ }
this.savedCatalogRefreshPending = false;
this.resolveMissingSelectionAnchor();
}
@@ -2359,6 +2380,10 @@ export class AgentsViewMode implements Component, Focusable {
this.stopped = true;
this.savedCatalogGeneration += 1;
this.heartbeatCatalogGeneration += 1;
+ if (this.savedCatalogReconcileTimer) {
+ clearTimeout(this.savedCatalogReconcileTimer);
+ this.savedCatalogReconcileTimer = undefined;
+ }
if (this.heartbeatPollTimer) {
clearInterval(this.heartbeatPollTimer);
this.heartbeatPollTimer = undefined;
@@ -2555,9 +2580,11 @@ export class AgentsViewMode implements Component, Focusable {
const heartbeat = badge ? `${theme.fg((row.heartbeat?.activeCount ?? 0) > 0 ? "error" : "dim", badge)} ` : "";
const title = `${" ".repeat(row.depth)}${icon} ${heartbeat}${styleRowTitle(row)}`;
const status =
- row.summary.statusLabel !== undefined || row.summary.lastHeardFromAt !== undefined
- ? row.statusLabel
- : undefined;
+ row.summary.lastHeardFromAt !== undefined
+ ? getSessionStatusLabel(row.summary, row.heartbeat)
+ : row.summary.statusLabel !== undefined
+ ? row.statusLabel
+ : undefined;
const activity = [status, row.summary.summary].filter(Boolean).join(" · ");
const cells = [
formatTableCell(title, layout.nameWidth),
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 3db4ff780f..e3e56e187e 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,4 +1,4 @@
-import { basename, resolve } from "node:path";
+import { basename, isAbsolute, 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";
@@ -140,8 +140,49 @@ function formatAgeLabel(timestamp: string): string {
return minutes < 120 ? `${minutes}m ago` : `${Math.round(minutes / 60)}h ago`;
}
+const SESSION_IDENTITY_CACHE_LIMIT = 4096;
+const SESSION_IDENTITY_CACHE_TTL_MS = 60_000;
+interface CachedSessionIdentity {
+ value: string;
+ expiresAt: number;
+}
+// Cache misses too to avoid repeated filesystem calls during rebuilds. File creation
+// and symlink changes can take up to a minute to appear in these UI-only caches.
+const canonicalSessionPathCache = new Map<string, CachedSessionIdentity>();
+const rosterAgentIdCache = new Map<string, CachedSessionIdentity>();
+
+function cachedSessionIdentity(cache: Map<string, CachedSessionIdentity>, key: string, compute: () => string): string {
+ const now = Date.now();
+ const cached = cache.get(key);
+ if (cached) {
+ cache.delete(key);
+ if (cached.expiresAt > now) {
+ cache.set(key, cached);
+ return cached.value;
+ }
+ }
+ const value = compute();
+ if (cache.size >= SESSION_IDENTITY_CACHE_LIMIT) {
+ const oldestKey = cache.keys().next().value;
+ if (oldestKey !== undefined) cache.delete(oldestKey);
+ }
+ cache.set(key, { value, expiresAt: now + SESSION_IDENTITY_CACHE_TTL_MS });
+ return value;
+}
+
function canonicalSessionPath(path: string): string {
- return resolve(canonicalizePath(path));
+ const key = isAbsolute(path) ? path : `${process.cwd()}\0${path}`;
+ return cachedSessionIdentity(canonicalSessionPathCache, key, () => resolve(canonicalizePath(path)));
+}
+
+function cachedRosterAgentIdForSummary(summary: SessionSummary): string {
+ const key = JSON.stringify([
+ summary.parentSessionPath,
+ summary.parentActiveSessionId,
+ summary.rlmChildId,
+ summary.parentSessionPath && !isAbsolute(summary.parentSessionPath) ? process.cwd() : undefined,
+ ]);
+ return cachedSessionIdentity(rosterAgentIdCache, key, () => rosterAgentIdForSummary(summary));
}
function fileIdentity(path: string): string {
@@ -151,7 +192,7 @@ function fileIdentity(path: string): string {
function summaryIdentityAliases(summary: SessionSummary): string[] {
return [
summary.runtimeKind === "subagent" && summary.rlmChildId
- ? `agent:${rosterAgentIdForSummary(summary)}`
+ ? `agent:${cachedRosterAgentIdForSummary(summary)}`
: undefined,
summary.sessionFile ? fileIdentity(summary.sessionFile) : undefined,
`session:${summary.sessionId}`,
@@ -408,8 +449,8 @@ export function getUnifiedSessionAncestorSessionIds(
export function filterUnifiedSessions(
records: readonly UnifiedSessionRecord[],
matches: (searchableText: string) => boolean,
+ index: UnifiedSessionIndex = buildUnifiedSessionIndex(records),
): UnifiedSessionRecord[] {
- const index = buildUnifiedSessionIndex(records);
const retained = new Set<UnifiedSessionRecord>();
for (const record of records) {
if (!matches(record.searchableText)) continue;
@@ -428,8 +469,8 @@ export function filterUnifiedSessions(
export function filterEmptyAgentsViewSessions(
records: readonly UnifiedSessionRecord[],
preservedSessionIds: ReadonlySet<string> = new Set(),
+ index: UnifiedSessionIndex = buildUnifiedSessionIndex(records),
): UnifiedSessionRecord[] {
- const index = buildUnifiedSessionIndex(records);
const retained = new Set<UnifiedSessionRecord>();
for (const record of records) {
const summary = summaryForUnifiedRecord(record);
@@ -718,7 +759,7 @@ export function collectSubagentDescendantSummaries(
export function getAgentsViewSummaryIdentity(summary: SessionSummary): string {
if (summary.runtimeKind === "subagent" && summary.rlmChildId) {
- return `agent:${rosterAgentIdForSummary(summary)}`;
+ return `agent:${cachedRosterAgentIdForSummary(summary)}`;
}
if (summary.sessionFile) {
return fileIdentity(summary.sessionFile);
@@ -1175,7 +1216,7 @@ function getSessionSubtitle(summary: SessionSummary): string {
return parts.join(" ");
}
-function getSessionStatusLabel(summary: SessionSummary, heartbeat?: UnifiedSessionHeartbeat): string {
+export function getSessionStatusLabel(summary: SessionSummary, heartbeat?: UnifiedSessionHeartbeat): string {
if (summary.statusLabel !== undefined) {
return summary.statusLabel;
}
diff --git a/packages/coding-agent/test/agents-view-mode.test.ts b/packages/coding-agent/test/agents-view-mode.test.ts
index 25bd430004..9c43b9eed6 100644
--- a/packages/coding-agent/test/agents-view-mode.test.ts
+++ b/packages/coding-agent/test/agents-view-mode.test.ts
@@ -15,15 +15,19 @@ import {
createInitialAgentsViewPersistentState,
runAgentsViewMode,
} from "../src/modes/agents-view/agents-view-mode.js";
+import * as agentsViewState from "../src/modes/agents-view/agents-view-state.js";
import {
type AgentsViewRow,
buildAgentsViewRows,
reconcileUnifiedSessions,
resolveAgentsViewLeftResult,
+ type UnifiedSessionRecord,
} from "../src/modes/agents-view/agents-view-state.js";
import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
+import * as savedSessionCatalog from "../src/modes/daemon/saved-session-catalog.js";
import type { InteractiveModeUiServices } from "../src/modes/interactive/interactive-mode-services.js";
-import { stopThemeWatcher, theme } from "../src/modes/interactive/theme/theme.js";
+import { initTheme, stopThemeWatcher, theme } from "../src/modes/interactive/theme/theme.js";
+import { WORKING_ICON_INTERVAL_MS } from "../src/modes/interactive/theme/working-icon.js";
const modeMocks = vi.hoisted(() => ({
interactiveRun: vi.fn<() => Promise<never>>(),
@@ -89,6 +93,95 @@ function invoke(method: string, self: object, ...args: unknown[]): unknown {
return member.call(self, ...args);
}
+function savedSession(id: string): AgentConnectionSavedSessionInfo {
+ return {
+ id,
+ path: `/tmp/${id}.jsonl`,
+ cwd: "/tmp",
+ created: new Date(0),
+ modified: new Date(0),
+ messageCount: 1,
+ firstMessage: id,
+ allMessagesText: id,
+ };
+}
+
+function deferredSavedCatalog() {
+ let resolve!: (sessions: AgentConnectionSavedSessionInfo[]) => void;
+ let reject!: (error: Error) => void;
+ let onSession: ((session: AgentConnectionSavedSessionInfo) => void) | undefined;
+ const promise = new Promise<AgentConnectionSavedSessionInfo[]>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ vi.spyOn(savedSessionCatalog, "listDaemonSavedSessions").mockImplementationOnce(
+ async (_client, _context, _scope, callbacks) => {
+ onSession = callbacks?.onSession;
+ return promise;
+ },
+ );
+ return {
+ resolve,
+ reject,
+ emit(session: AgentConnectionSavedSessionInfo): void {
+ if (!onSession) throw new Error("Saved catalog refresh has not started");
+ onSession(session);
+ },
+ };
+}
+
+function catalogHarness(saved: AgentConnectionSavedSessionInfo[] = [], live: SessionSummary[] = []) {
+ const persistentState: AgentsViewPersistentState = {
+ savedSessions: saved,
+ lastSuccessfulSavedSessions: saved,
+ savedCatalogLoaded: true,
+ };
+ const self = {
+ persistentState,
+ lastListedSummaries: live,
+ savedSessions: saved,
+ lastSuccessfulSavedSessions: saved,
+ heartbeats: [],
+ rows: [] as AgentsViewRow[],
+ selectedIndex: 0,
+ savedCatalogGeneration: 0,
+ heartbeatCatalogGeneration: 0,
+ savedCatalogReady: true,
+ savedCatalogRefreshPending: false,
+ savedCatalogReconcileTimer: undefined as ReturnType<typeof setTimeout> | undefined,
+ stopped: false,
+ inactiveAgentIdentities: new Set<string>(),
+ expandedSubagentParents: new Set<string>(),
+ programShownParents: new Set<string>(),
+ editor: { getText: vi.fn(() => "") },
+ ui: { requestRender: vi.fn(), stop: vi.fn() },
+ requireClient: () => ({}),
+ getSavedSessionCatalogContext: () => ({ cwd: "/tmp" }),
+ withPendingDeleteSession: (sessions: SessionSummary[]) => sessions,
+ getFilteredRecords(): UnifiedSessionRecord[] {
+ return invoke("getFilteredRecords", self) as UnifiedSessionRecord[];
+ },
+ reconcileCatalogs: vi.fn((): void => {
+ invoke("reconcileCatalogs", self);
+ }),
+ rebuildRows: vi.fn((): void => {
+ invoke("rebuildRows", self);
+ }),
+ rearmSavedSearchFetch(): void {
+ invoke("rearmSavedSearchFetch", self);
+ },
+ armSavedSearchFetch: vi.fn(),
+ applyPendingAncestorExpansion: vi.fn(),
+ restoreSelection: vi.fn(),
+ syncSelectedRowState: vi.fn(),
+ resolveMissingSelectionAnchor: vi.fn(),
+ clearCtrlCExitHint: vi.fn(),
+ clearDeleteConfirmation: vi.fn(),
+ setStatusMessage: vi.fn(),
+ };
+ return self;
+}
+
const settingsManager = {
getTheme: () => "dark",
getShowHardwareCursor: () => false,
@@ -1676,6 +1769,353 @@ describe("AgentsViewMode persistent catalog state", () => {
});
});
+describe("AgentsViewMode catalog performance", () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it("coalesces bursts without copying snapshots per item and flushes during a continuous stream", async () => {
+ const previous = [savedSession("previous")];
+ const self = catalogHarness(previous);
+ const catalog = deferredSavedCatalog();
+ const refresh = invoke("refreshSavedSessions", self) as Promise<boolean>;
+ const first = savedSession("first");
+ const updatedFirst = { ...first, path: "/tmp/./first.jsonl", name: "updated first" };
+ const second = savedSession("second");
+ const third = savedSession("third");
+ catalog.emit(first);
+ const firstTimer = self.savedCatalogReconcileTimer;
+ await vi.advanceTimersByTimeAsync(25);
+ catalog.emit(updatedFirst);
+ catalog.emit(second);
+ await vi.advanceTimersByTimeAsync(25);
+ catalog.emit(third);
+ await vi.advanceTimersByTimeAsync(24);
+
+ expect(self.savedSessions).toBe(previous);
+ expect(self.persistentState.savedSessions).toBe(previous);
+ expect(self.savedCatalogReconcileTimer).toBe(firstTimer);
+ expect(self.reconcileCatalogs).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(1);
+
+ await vi.advanceTimersByTimeAsync(1);
+ expect(self.reconcileCatalogs).toHaveBeenCalledOnce();
+ expect(self.savedSessions).toEqual([previous[0], updatedFirst, second, third]);
+ expect(self.persistentState.savedSessions).toBe(self.savedSessions);
+ expect(self.rows.map((row) => row.summary.sessionId).sort()).toEqual(["first", "previous", "second", "third"]);
+ expect(self.rows.find((row) => row.summary.sessionId === "first")?.title).toBe("updated first");
+ expect(self.savedCatalogReady).toBe(false);
+ expect(self.savedCatalogRefreshPending).toBe(true);
+ expect(self.lastSuccessfulSavedSessions).toBe(previous);
+ expect(self.persistentState.lastSuccessfulSavedSessions).toBe(previous);
+ expect(self.savedCatalogReconcileTimer).toBeUndefined();
+
+ const firstSnapshot = self.savedSessions;
+ const fourth = savedSession("fourth");
+ const fifth = savedSession("fifth");
+ catalog.emit(fourth);
+ await vi.advanceTimersByTimeAsync(50);
+ catalog.emit(fifth);
+ await vi.advanceTimersByTimeAsync(24);
+ expect(self.savedSessions).toBe(firstSnapshot);
+ expect(self.persistentState.savedSessions).toBe(firstSnapshot);
+ expect(self.reconcileCatalogs).toHaveBeenCalledOnce();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(self.reconcileCatalogs).toHaveBeenCalledTimes(2);
+ expect(self.savedSessions).toEqual([...firstSnapshot, fourth, fifth]);
+ expect(self.rows).toHaveLength(6);
+ expect(self.savedCatalogRefreshPending).toBe(true);
+
+ catalog.resolve([updatedFirst, second, third, fourth, fifth]);
+ await expect(refresh).resolves.toBe(true);
+ });
+
+ it("publishes the final canonical catalog immediately and cancels its pending batch", async () => {
+ const self = catalogHarness([savedSession("previous")]);
+ const catalog = deferredSavedCatalog();
+ const refresh = invoke("refreshSavedSessions", self) as Promise<boolean>;
+ catalog.emit(savedSession("partial"));
+ const final = [savedSession("canonical")];
+ catalog.resolve(final);
+ await expect(refresh).resolves.toBe(true);
+
+ expect(self.savedSessions).toBe(final);
+ expect(self.lastSuccessfulSavedSessions).toBe(final);
+ expect(self.persistentState.savedSessions).toBe(final);
+ expect(self.persistentState.lastSuccessfulSavedSessions).toBe(final);
+ expect(self.persistentState.savedCatalogLoaded).toBe(true);
+ expect(self.savedCatalogReady).toBe(true);
+ expect(self.savedCatalogRefreshPending).toBe(false);
+ expect(self.rows.map((row) => row.summary.sessionId)).toEqual(["canonical"]);
+ expect(self.resolveMissingSelectionAnchor).toHaveBeenCalledOnce();
+ expect(self.savedCatalogReconcileTimer).toBeUndefined();
+ expect(vi.getTimerCount()).toBe(0);
+ await vi.advanceTimersByTimeAsync(150);
+ expect(self.savedSessions).toBe(final);
+ expect(self.reconcileCatalogs).toHaveBeenCalledOnce();
+ });
+
+ it.each([false, true])("restores the last successful catalog after failure (batch flushed: %s)", async (flushed) => {
+ const previous = [savedSession("previous")];
+ const self = catalogHarness(previous);
+ const catalog = deferredSavedCatalog();
+ const refresh = invoke("refreshSavedSessions", self) as Promise<boolean>;
+ catalog.emit(savedSession("partial"));
+ if (flushed) {
+ await vi.advanceTimersByTimeAsync(75);
+ expect(self.rows.map((row) => row.summary.sessionId).sort()).toEqual(["partial", "previous"]);
+ catalog.emit(savedSession("pending"));
+ }
+ catalog.reject(new Error("scan failed"));
+ await expect(refresh).resolves.toBe(false);
+
+ expect(self.savedSessions).toBe(previous);
+ expect(self.persistentState.savedSessions).toBe(previous);
+ expect(self.lastSuccessfulSavedSessions).toBe(previous);
+ expect(self.persistentState.lastSuccessfulSavedSessions).toBe(previous);
+ expect(self.rows.map((row) => row.summary.sessionId)).toEqual(["previous"]);
+ expect(self.savedCatalogReady).toBe(true);
+ expect(self.savedCatalogRefreshPending).toBe(false);
+ expect(self.setStatusMessage).toHaveBeenCalledWith("Failed to load saved sessions: scan failed");
+ expect(self.savedCatalogReconcileTimer).toBeUndefined();
+ expect(vi.getTimerCount()).toBe(0);
+ await vi.advanceTimersByTimeAsync(150);
+ expect(self.savedSessions).toBe(previous);
+ expect(self.reconcileCatalogs).toHaveBeenCalledTimes(flushed ? 2 : 1);
+ });
+
+ it.each(["success", "failure"])("fences a superseded scan's timer, callback, and terminal %s", async (outcome) => {
+ const previous = [savedSession("previous")];
+ const self = catalogHarness(previous);
+ const older = deferredSavedCatalog();
+ const newer = deferredSavedCatalog();
+ const oldRefresh = invoke("refreshSavedSessions", self) as Promise<boolean>;
+ older.emit(savedSession("old-partial"));
+ await vi.advanceTimersByTimeAsync(25);
+ const newRefresh = invoke("refreshSavedSessions", self) as Promise<boolean>;
+ expect(self.savedCatalogGeneration).toBe(2);
+ expect(self.persistentState.savedCatalogGeneration).toBe(2);
+ expect(self.savedCatalogReconcileTimer).toBeUndefined();
+ expect(vi.getTimerCount()).toBe(0);
+ older.emit(savedSession("old-late"));
+ expect(vi.getTimerCount()).toBe(0);
+ const replacement = savedSession("new-partial");
+ newer.emit(replacement);
+ const newTimer = self.savedCatalogReconcileTimer;
+ if (outcome === "success") older.resolve([savedSession("old-final")]);
+ else older.reject(new Error("old scan failed"));
+ await expect(oldRefresh).resolves.toBe(false);
+ expect(self.savedCatalogReconcileTimer).toBe(newTimer);
+ expect(self.savedCatalogRefreshPending).toBe(true);
+ expect(self.savedCatalogReady).toBe(false);
+ expect(self.resolveMissingSelectionAnchor).not.toHaveBeenCalled();
+ expect(self.setStatusMessage).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(50);
+ expect(self.savedSessions).toBe(previous);
+ expect(self.reconcileCatalogs).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(25);
+ expect(self.savedSessions).toEqual([...previous, replacement]);
+ expect(self.rows.map((row) => row.summary.sessionId).sort()).toEqual(["new-partial", "previous"]);
+ expect(self.reconcileCatalogs).toHaveBeenCalledOnce();
+ const final = [savedSession("new-final")];
+ newer.resolve(final);
+ await expect(newRefresh).resolves.toBe(true);
+ await vi.advanceTimersByTimeAsync(150);
+ expect(self.savedSessions).toBe(final);
+ expect(self.persistentState.savedSessions).toBe(final);
+ expect(self.reconcileCatalogs).toHaveBeenCalledTimes(2);
+ });
+
+ it.each(["success", "failure"])("finish cancels pending batches and ignores late catalog %s", async (outcome) => {
+ const previous = [savedSession("previous")];
+ const self = catalogHarness(previous);
+ const catalog = deferredSavedCatalog();
+ const refresh = invoke("refreshSavedSessions", self) as Promise<boolean>;
+ catalog.emit(savedSession("partial"));
+ expect(vi.getTimerCount()).toBe(1);
+ invoke("finish", self, { type: "exit" });
+ expect(self.stopped).toBe(true);
+ expect(self.savedCatalogReconcileTimer).toBeUndefined();
+ expect(vi.getTimerCount()).toBe(0);
+ catalog.emit(savedSession("late"));
+ if (outcome === "success") catalog.resolve([savedSession("final")]);
+ else catalog.reject(new Error("late failure"));
+ await expect(refresh).resolves.toBe(false);
+ await vi.advanceTimersByTimeAsync(150);
+
+ expect(self.savedSessions).toBe(previous);
+ expect(self.persistentState.savedSessions).toBe(previous);
+ expect(self.lastSuccessfulSavedSessions).toBe(previous);
+ expect(self.reconcileCatalogs).not.toHaveBeenCalled();
+ expect(self.ui.requestRender).not.toHaveBeenCalled();
+ expect(self.resolveMissingSelectionAnchor).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("ticks stale ages and working icons without rebuilding rows or rendering an unchanged idle list", async () => {
+ initTheme("dark");
+ vi.setSystemTime(new Date("2026-01-01T00:00:10Z"));
+ const rows = buildAgentsViewRows([summary({ lastHeardFromAt: "2026-01-01T00:00:00Z" })]);
+ const self = {
+ rows,
+ selectedIndex: -1,
+ workingIconFrame: 0,
+ savedCatalogGeneration: 0,
+ heartbeatCatalogGeneration: 0,
+ persistentState: {
+ rosterClient: { isConnected: true, onMessage: vi.fn(() => vi.fn()) },
+ rosterStore: {
+ attach: vi.fn(async () => true),
+ onUpdate: vi.fn(() => vi.fn()),
+ summaries: () => [],
+ },
+ },
+ ui: {
+ addChild: vi.fn(),
+ setFocus: vi.fn(),
+ start: vi.fn(),
+ enterFullscreen: vi.fn(),
+ requestRender: vi.fn(),
+ invalidate: vi.fn(),
+ stop: vi.fn(),
+ },
+ subscribeToClientClose: vi.fn(),
+ applySessionList: vi.fn(),
+ armSavedSearchFetch: vi.fn(),
+ resolveMissingSelectionAnchor: vi.fn(),
+ refreshHeartbeats: vi.fn(async () => true),
+ loadStartupNotices: vi.fn(),
+ rebuildRows: vi.fn(),
+ clearCtrlCExitHint: vi.fn(),
+ clearDeleteConfirmation: vi.fn(),
+ setStatusMessage: vi.fn(),
+ isPendingDeleteRow: () => false,
+ isPendingKillSubagentRow: () => false,
+ getRowIcon(section: AgentsViewRow["section"]): string {
+ return invoke("getRowIcon", self, section) as string;
+ },
+ formatRowIcon(section: AgentsViewRow["section"], icon: string): string {
+ return invoke("formatRowIcon", self, section, icon) as string;
+ },
+ };
+ const render = (row = self.rows[0]!) => stripAnsi(invoke("renderRow", self, row, 160) as string);
+ const run = invoke("run", self) as Promise<unknown>;
+ try {
+ await vi.advanceTimersByTimeAsync(0);
+ expect(self.ui.start).toHaveBeenCalledOnce();
+ expect(render()).toContain("last heard 10s ago");
+ self.ui.requestRender.mockClear();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(self.ui.requestRender).toHaveBeenCalledTimes(1000 / WORKING_ICON_INTERVAL_MS);
+ expect(self.rebuildRows).not.toHaveBeenCalled();
+ expect(self.rows).toBe(rows);
+ expect(rows[0]?.statusLabel).toBe("last heard 10s ago");
+ expect(render()).toContain("last heard 11s ago");
+ expect(self.workingIconFrame).toBe(0);
+
+ self.rows = buildAgentsViewRows([summary({ activity: "working", isStreaming: true })]);
+ self.ui.requestRender.mockClear();
+ await vi.advanceTimersByTimeAsync(WORKING_ICON_INTERVAL_MS);
+ expect(self.workingIconFrame).toBe(1);
+ expect(self.ui.requestRender).toHaveBeenCalledOnce();
+ expect(render()).toContain("◈");
+ expect(render()).not.toContain("thinking");
+
+ self.rows = buildAgentsViewRows([summary()]);
+ self.ui.requestRender.mockClear();
+ await vi.advanceTimersByTimeAsync(WORKING_ICON_INTERVAL_MS);
+ expect(self.workingIconFrame).toBe(1);
+ expect(self.ui.requestRender).not.toHaveBeenCalled();
+ expect(self.rebuildRows).not.toHaveBeenCalled();
+
+ const recovering = buildAgentsViewRows([
+ summary({ statusLabel: "recovering", lastHeardFromAt: "2026-01-01T00:00:00Z" }),
+ ])[0]!;
+ recovering.heartbeat = { activeCount: 1 };
+ const failed = buildAgentsViewRows([summary({ statusLabel: "failed" })])[0]!;
+ const statusLabel = vi.spyOn(agentsViewState, "getSessionStatusLabel");
+ expect(render(recovering)).toContain("recovering");
+ expect(render(recovering)).not.toContain("last heard");
+ expect(render(failed)).toContain("failed");
+ expect(render()).not.toContain("needs input");
+ expect(statusLabel).toHaveBeenCalledTimes(2);
+ expect(statusLabel).toHaveBeenCalledWith(recovering.summary, recovering.heartbeat);
+ } finally {
+ invoke("finish", self, { type: "exit" });
+ await run;
+ }
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("reuses the catalog index and recursive totals across searches until reconciliation", () => {
+ const parent = summary({ sessionName: "parent", usage: { inputTokens: 0, outputTokens: 0, cost: 1 } });
+ const child = summary({
+ id: "child",
+ activeSessionId: "child",
+ sessionId: "child",
+ sessionFile: "/tmp/child.jsonl",
+ sessionName: "child",
+ runtimeKind: "subagent",
+ parentActiveSessionId: parent.activeSessionId,
+ usage: { inputTokens: 0, outputTokens: 0, cost: 2 },
+ });
+ const grandchild = summary({
+ id: "grandchild",
+ activeSessionId: "grandchild",
+ sessionId: "grandchild",
+ sessionFile: "/tmp/grandchild.jsonl",
+ sessionName: "grandchild",
+ runtimeKind: "subagent",
+ parentActiveSessionId: child.activeSessionId,
+ usage: { inputTokens: 0, outputTokens: 0, cost: 4 },
+ });
+ const self = catalogHarness([], [parent, child, grandchild]);
+ const computeRollups = vi.spyOn(agentsViewState, "computeRecursiveRollups");
+ const buildIndex = vi.spyOn(agentsViewState, "buildUnifiedSessionIndex");
+ const filterEmpty = vi.spyOn(agentsViewState, "filterEmptyAgentsViewSessions");
+ const filterSearch = vi.spyOn(agentsViewState, "filterUnifiedSessions");
+ const buildRows = vi.spyOn(agentsViewState, "buildAgentsViewRows");
+ self.reconcileCatalogs();
+ const index = Reflect.get(self, "unifiedIndex");
+ const rollups = Reflect.get(self, "recursiveRollups");
+ expect(rollups).toBeInstanceOf(Map);
+ const parentRow = () => self.rows.find((row) => row.summary.sessionId === parent.sessionId);
+ expect(parentRow()).toMatchObject({ recursiveCost: 7, descendantCount: 2 });
+
+ for (const query of ["parent", "grandchild", "no match", ""]) {
+ self.editor.getText.mockReturnValue(query);
+ invoke("queryChanged", self);
+ expect(Reflect.get(self, "unifiedIndex")).toBe(index);
+ expect(Reflect.get(self, "recursiveRollups")).toBe(rollups);
+ if (query === "no match") expect(self.rows).toEqual([]);
+ else expect(parentRow()).toMatchObject({ recursiveCost: 7, descendantCount: 2 });
+ }
+ expect(computeRollups).toHaveBeenCalledOnce();
+ expect(buildIndex).toHaveBeenCalledOnce();
+ expect(filterEmpty).toHaveBeenCalledTimes(5);
+ expect(filterSearch).toHaveBeenCalledTimes(3);
+ for (const call of [...filterEmpty.mock.calls, ...filterSearch.mock.calls]) expect(call[2]).toBe(index);
+ for (const call of buildRows.mock.calls) expect(call[4]).toBe(rollups);
+
+ self.lastListedSummaries = [
+ parent,
+ child,
+ { ...grandchild, usage: { inputTokens: 0, outputTokens: 0, cost: 10 } },
+ { ...child, id: "new", activeSessionId: "new", sessionId: "new", sessionFile: "/tmp/new.jsonl" },
+ ];
+ self.reconcileCatalogs();
+ expect(Reflect.get(self, "unifiedIndex")).not.toBe(index);
+ expect(Reflect.get(self, "recursiveRollups")).not.toBe(rollups);
+ expect(computeRollups).toHaveBeenCalledTimes(2);
+ expect(buildIndex).toHaveBeenCalledTimes(2);
+ expect(parentRow()).toMatchObject({ recursiveCost: 15, descendantCount: 3 });
+ self.editor.getText.mockReturnValue("parent");
+ invoke("queryChanged", self);
+ expect(parentRow()).toMatchObject({ recursiveCost: 15, descendantCount: 3 });
+ expect(computeRollups).toHaveBeenCalledTimes(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(
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index de75aa6892..fa0d2d8119 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -1,7 +1,7 @@
-import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { describe, expect, test, vi } from "vitest";
+import { join, resolve } from "node:path";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import type { AgentSessionRuntimeConfig } from "../src/core/agent-session-config.js";
import type { ModelRegistry } from "../src/core/model-registry.js";
import type { SessionInfo } from "../src/core/session-manager.js";
@@ -21,7 +21,12 @@ import {
resolveAgentsViewSessionUiServices,
shouldReconnectAgentsViewDaemon,
} from "../src/modes/agents-view/agents-view-mode.js";
-import { summaryForUnifiedRecord } from "../src/modes/agents-view/agents-view-state.js";
+import {
+ filterEmptyAgentsViewSessions,
+ getAgentsViewSummaryIdentity,
+ summaryForUnifiedRecord,
+} from "../src/modes/agents-view/agents-view-state.js";
+import * as agentRoster from "../src/modes/daemon/agent-roster.js";
import {
type AgentsViewScopeFrame,
aggregateSessionHeartbeats,
@@ -50,6 +55,7 @@ import {
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";
+import * as paths from "../src/utils/paths.js";
function heartbeat(id: string, nextRunAt?: string, activeSessionId = "child", status: "active" | "paused" = "active") {
return {
@@ -71,6 +77,196 @@ function heartbeat(id: string, nextRunAt?: string, activeSessionId = "child", st
}
describe("agents view state", () => {
+ describe("session identity caches", () => {
+ let root: string;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "agents-view-path-cache-"));
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ test("reuses successful canonical paths across reconciliation and row construction", () => {
+ const real = join(root, "session.jsonl");
+ const alias = join(root, "alias.jsonl");
+ writeFileSync(real, "");
+ symlinkSync(real, alias);
+ const canonicalize = vi.spyOn(paths, "canonicalizePath");
+ const saved = makeSessionInfo({ id: "cached", path: alias });
+ const identity = `file:${realpathSync(real)}`;
+
+ for (let rebuild = 0; rebuild < 3; rebuild++) {
+ const records = reconcileUnifiedSessions([], [saved]);
+ expect(records[0]?.identity).toBe(identity);
+ expect(buildAgentsViewRows(records)[0]?.identity).toBe(identity);
+ }
+ expect(canonicalize.mock.calls).toEqual([[alias], [realpathSync(real)]]);
+ });
+
+ test("caches raw-path fallbacks for missing files", () => {
+ const missing = join(root, "missing.jsonl");
+ const canonicalize = vi.spyOn(paths, "canonicalizePath");
+ const summary = makeSummary({ sessionFile: missing });
+
+ for (let lookup = 0; lookup < 3; lookup++) {
+ expect(getAgentsViewSummaryIdentity(summary)).toBe(`file:${resolve(missing)}`);
+ }
+ expect(canonicalize).toHaveBeenCalledExactlyOnceWith(missing);
+ expect(canonicalize).toHaveReturnedWith(missing);
+ });
+
+ test.each(["missing", "symlink"] as const)("refreshes a cached %s after a fixed one-minute TTL", (kind) => {
+ const first = join(root, "first.jsonl");
+ const second = join(root, "second.jsonl");
+ const alias = join(root, "alias.jsonl");
+ writeFileSync(first, "");
+ writeFileSync(second, "");
+ if (kind === "symlink") symlinkSync(first, alias);
+ const initialIdentity = `file:${kind === "symlink" ? realpathSync(first) : resolve(alias)}`;
+ const summary = makeSummary({ sessionFile: alias });
+ const start = Date.now();
+ const now = vi.spyOn(Date, "now").mockReturnValue(start);
+ const canonicalize = vi.spyOn(paths, "canonicalizePath");
+
+ expect(getAgentsViewSummaryIdentity(summary)).toBe(initialIdentity);
+ if (kind === "symlink") rmSync(alias);
+ symlinkSync(second, alias);
+ now.mockReturnValue(start + 59_999);
+ expect(getAgentsViewSummaryIdentity(summary)).toBe(initialIdentity);
+ expect(canonicalize).toHaveBeenCalledTimes(1);
+
+ now.mockReturnValue(start + 60_000);
+ expect(getAgentsViewSummaryIdentity(summary)).toBe(`file:${realpathSync(second)}`);
+ expect(canonicalize).toHaveBeenCalledTimes(2);
+ });
+
+ test.each(["path", "roster"] as const)("evicts the least recently used %s identity at 4096 entries", (kind) => {
+ vi.spyOn(Date, "now").mockReturnValue(Date.now());
+ const compute =
+ kind === "path"
+ ? vi.spyOn(paths, "canonicalizePath").mockImplementation((path) => path)
+ : vi.spyOn(agentRoster, "rosterAgentIdForSummary").mockImplementation((summary) => summary.rlmChildId!);
+ const createSummary = (id: string): SessionSummary =>
+ makeSummary({
+ sessionFile: join(root, `${id}.jsonl`),
+ parentSessionPath: join(root, "parent.jsonl"),
+ runtimeKind: kind === "roster" ? "subagent" : undefined,
+ rlmChildId: id,
+ });
+ const summaries = Array.from({ length: 4096 }, (_, index) => createSummary(String(index)));
+ for (const summary of summaries) getAgentsViewSummaryIdentity(summary);
+ expect(compute).toHaveBeenCalledTimes(4096);
+
+ getAgentsViewSummaryIdentity(summaries[0]!);
+ expect(compute).toHaveBeenCalledTimes(4096);
+ getAgentsViewSummaryIdentity(createSummary("overflow"));
+ expect(compute).toHaveBeenCalledTimes(4097);
+ getAgentsViewSummaryIdentity(summaries[0]!);
+ expect(compute).toHaveBeenCalledTimes(4097);
+ getAgentsViewSummaryIdentity(summaries[1]!);
+ expect(compute).toHaveBeenCalledTimes(4098);
+ expect(compute).toHaveBeenLastCalledWith(kind === "path" ? summaries[1]!.sessionFile : summaries[1]);
+ });
+
+ test.each(["symlink", "missing-file", "missing-directory", "active-parent", "no-parent"] as const)(
+ "caches roster IDs with %s ancestry without changing their identity",
+ (kind) => {
+ const realDirectory = join(root, "real");
+ const aliasDirectory = join(root, "alias");
+ mkdirSync(realDirectory);
+ symlinkSync(realDirectory, aliasDirectory, "dir");
+ const parentPath = join(aliasDirectory, "parent.jsonl");
+ if (kind === "symlink") writeFileSync(parentPath, "");
+ const summary = makeSummary({
+ runtimeKind: "subagent",
+ rlmChildId: "cached-child",
+ parentSessionPath:
+ kind === "active-parent" || kind === "no-parent"
+ ? undefined
+ : kind === "missing-directory"
+ ? join(root, "missing", "parent.jsonl")
+ : parentPath,
+ parentActiveSessionId: kind === "no-parent" ? undefined : "active-parent",
+ });
+ const originalRosterId = agentRoster.rosterAgentIdForSummary;
+ const identity = `agent:${originalRosterId(summary)}`;
+ const rosterId = vi.spyOn(agentRoster, "rosterAgentIdForSummary");
+
+ for (let rebuild = 0; rebuild < 3; rebuild++) {
+ expect(getAgentsViewSummaryIdentity({ ...summary })).toBe(identity);
+ const records = reconcileUnifiedSessions([{ ...summary }], []);
+ expect(records[0]?.identity).toBe(identity);
+ expect(buildAgentsViewRows(records)[0]?.identity).toBe(identity);
+ }
+ expect(rosterId).toHaveBeenCalledExactlyOnceWith(summary);
+ const otherChild = { ...summary, rlmChildId: "other-child" };
+ expect(getAgentsViewSummaryIdentity(otherChild)).toBe(`agent:${originalRosterId(otherChild)}`);
+ expect(rosterId).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ test("refreshes cached roster IDs after their parent symlink changes and the TTL expires", () => {
+ const first = join(root, "first.jsonl");
+ const second = join(root, "second.jsonl");
+ const alias = join(root, "alias.jsonl");
+ writeFileSync(first, "");
+ writeFileSync(second, "");
+ symlinkSync(first, alias);
+ const summary = makeSummary({ runtimeKind: "subagent", rlmChildId: "child", parentSessionPath: alias });
+ const start = Date.now();
+ const now = vi.spyOn(Date, "now").mockReturnValue(start);
+ const originalRosterId = agentRoster.rosterAgentIdForSummary;
+ const identity = `agent:${originalRosterId(summary)}`;
+ const rosterId = vi.spyOn(agentRoster, "rosterAgentIdForSummary");
+
+ expect(getAgentsViewSummaryIdentity(summary)).toBe(identity);
+ rmSync(alias);
+ symlinkSync(second, alias);
+ now.mockReturnValue(start + 59_999);
+ expect(getAgentsViewSummaryIdentity(summary)).toBe(identity);
+ expect(rosterId).toHaveBeenCalledTimes(1);
+
+ now.mockReturnValue(start + 60_000);
+ expect(getAgentsViewSummaryIdentity(summary)).toBe(`agent:${originalRosterId(summary)}`);
+ expect(rosterId).toHaveBeenCalledTimes(2);
+ });
+
+ test("keeps relative parent roster IDs separate when the working directory changes", () => {
+ const cwd = vi.spyOn(process, "cwd").mockReturnValue(root);
+ const summary = makeSummary({
+ runtimeKind: "subagent",
+ rlmChildId: "relative-child",
+ parentSessionPath: "parent.jsonl",
+ });
+ const originalRosterId = agentRoster.rosterAgentIdForSummary;
+ const identity = `agent:${originalRosterId(summary)}`;
+ const rosterId = vi.spyOn(agentRoster, "rosterAgentIdForSummary");
+
+ expect(getAgentsViewSummaryIdentity(summary)).toBe(identity);
+ cwd.mockReturnValue(join(root, "other"));
+ expect(getAgentsViewSummaryIdentity(summary)).toBe(`agent:${originalRosterId(summary)}`);
+ cwd.mockReturnValue(root);
+ expect(getAgentsViewSummaryIdentity(summary)).toBe(identity);
+ expect(rosterId).toHaveBeenCalledTimes(2);
+ });
+
+ test("keeps relative path entries separate when the working directory changes", () => {
+ const cwd = vi.spyOn(process, "cwd").mockReturnValue(root);
+ const canonicalize = vi.spyOn(paths, "canonicalizePath").mockImplementation((path) => resolve(path));
+ const summary = makeSummary({ sessionFile: "relative-session.jsonl" });
+
+ expect(getAgentsViewSummaryIdentity(summary)).toBe(`file:${join(root, "relative-session.jsonl")}`);
+ cwd.mockReturnValue(join(root, "other"));
+ expect(getAgentsViewSummaryIdentity(summary)).toBe(`file:${join(root, "other", "relative-session.jsonl")}`);
+ cwd.mockReturnValue(root);
+ expect(getAgentsViewSummaryIdentity(summary)).toBe(`file:${join(root, "relative-session.jsonl")}`);
+ expect(canonicalize).toHaveBeenCalledTimes(2);
+ });
+ });
+
test("classifies a saved orphan with rlmDepth > 0 as a subagent", () => {
const saved = {
path: "/tmp/sessions/child.jsonl",
@@ -1399,6 +1595,88 @@ describe("agents view state", () => {
]);
});
+ test.each(["search", "empty"] as const)("reuses a prebuilt index for the %s filter", (kind) => {
+ const rootPath = "/tmp/agents-view-filter-index/root.jsonl";
+ const childPath = "/tmp/agents-view-filter-index/child.jsonl";
+ const records = reconcileUnifiedSessions(
+ [
+ makeSummary({
+ id: "child",
+ activeSessionId: "child",
+ sessionId: "child-session",
+ sessionFile: childPath,
+ parentSessionPath: rootPath,
+ runtimeKind: "subagent",
+ }),
+ ],
+ [
+ makeSessionInfo({
+ id: "root-session",
+ path: rootPath,
+ messageCount: 0,
+ firstMessage: "",
+ allMessagesText: "",
+ }),
+ makeSessionInfo({
+ id: "grandchild-session",
+ path: "/tmp/agents-view-filter-index/grandchild.jsonl",
+ parentSessionPath: childPath,
+ rlmDepth: 2,
+ allMessagesText: "Needle",
+ }),
+ makeSessionInfo({
+ id: "empty-session",
+ path: "/tmp/agents-view-filter-index/empty.jsonl",
+ messageCount: 0,
+ firstMessage: "",
+ allMessagesText: "",
+ }),
+ makeSessionInfo({
+ id: "preserved-session",
+ path: "/tmp/agents-view-filter-index/preserved.jsonl",
+ messageCount: 0,
+ firstMessage: "",
+ allMessagesText: "",
+ }),
+ ],
+ );
+ const matches = (text: string): boolean => text.includes("Needle");
+ const preserved = new Set(["preserved-session"]);
+ const expected =
+ kind === "search"
+ ? filterUnifiedSessions(records, matches)
+ : filterEmptyAgentsViewSessions(records, preserved);
+ expect(expected.map((record) => summaryForUnifiedRecord(record).sessionId)).toEqual([
+ "child-session",
+ "root-session",
+ "grandchild-session",
+ ...(kind === "empty" ? ["preserved-session"] : []),
+ ]);
+ const index = buildUnifiedSessionIndex(records);
+ const aliasIterators = records.map((record) => vi.spyOn(record.identityAliases, Symbol.iterator));
+ const lookups = vi.spyOn(index.byKey, "get");
+ try {
+ const filtered =
+ kind === "search"
+ ? filterUnifiedSessions(records, matches, index)
+ : filterEmptyAgentsViewSessions(records, preserved, index);
+ for (const iterator of aliasIterators) expect(iterator).not.toHaveBeenCalled();
+ expect(lookups).toHaveBeenCalled();
+ expect(filtered).toHaveLength(expected.length);
+ for (const [position, record] of filtered.entries()) expect(record).toBe(expected[position]);
+
+ const subset = records.filter((record) => record.saved?.id !== "root-session");
+ const filteredSubset =
+ kind === "search"
+ ? filterUnifiedSessions(subset, matches, index)
+ : filterEmptyAgentsViewSessions(subset, preserved, index);
+ expect(filteredSubset).toEqual(filtered.filter((record) => record.saved?.id !== "root-session"));
+ } finally {
+ for (const iterator of aliasIterators) iterator.mockRestore();
+ lookups.mockRestore();
+ }
+ });
+
test("deduplicates and protects sessions across symlink aliases", () => {
const root = mkdtempSync(join(tmpdir(), "session-view-alias-"));
try {