Skip to content

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

Rust

feat(coding-agent): agents-view usage columns, section legend, empty-session sort, zebra striping (#2056)

Sebastian Müller367511225ebf
diff --git a/packages/coding-agent/.changes/agents-view-usage-legend-zebra.md b/packages/coding-agent/.changes/agents-view-usage-legend-zebra.md
new file mode 100644
index 0000000000..2db7e34548
--- /dev/null
+++ b/packages/coding-agent/.changes/agents-view-usage-legend-zebra.md
@@ -0,0 +1,3 @@
+- Changed agents-view row usage to aligned `↑in ↓out · $agent · #sub · $total · age` columns with an explicit total-subagent count; empty sessions show only their age.
+- Added a bold usage legend and session count to every agents-view section header, sharing one column layout with the rows.
+- Changed empty sessions to sort last within their agents-view section, except the session the view was entered from.
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 e36c972f43..ee09e04302 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
@@ -74,7 +74,7 @@ import {
type AgentsViewSelectionKey,
buildAgentsViewRows,
buildUnifiedSessionIndex,
- computeRecursiveCosts,
+ computeRecursiveRollups,
createUnattachableChildOpenResult,
filterUnifiedSessions,
formatHeartbeatBadge,
@@ -83,6 +83,7 @@ import {
getAgentsViewSummaryIdentity as getSummaryIdentity,
getUnifiedSessionAncestorSessionIds,
hasUnifiedSessionChildren,
+ isEmptyAgentsViewSession,
isSubagentSummary,
migrateAgentsViewIdentitySet,
reconcileUnifiedSessions,
@@ -694,6 +695,8 @@ export class AgentsViewMode implements Component, Focusable {
private pendingKillSubagent: PendingKillSubagent | undefined;
private renameTarget: { activeSessionId?: string; sessionFile?: string; summary: SessionSummary } | undefined;
private actionModeSearchQuery: string | undefined;
+ /** Session the view was entered from; exempt from the empty-session sort demotion. */
+ private readonly anchorSessionId: string | undefined;
private readonly inactiveAgentIdentities = new Set<string>();
private rosterStore: AgentsViewRosterStore | undefined;
private unsubscribeRosterUpdate: (() => void) | undefined;
@@ -715,6 +718,7 @@ export class AgentsViewMode implements Component, Focusable {
persistentState.backSession ?? options.initialSession,
);
persistentState.scopeFrames = initialFrames;
+ this.anchorSessionId = (persistentState.backSession ?? options.initialSession)?.sessionId;
this.scopeKey = initialFrames.at(-1)?.scope;
this.scopeRootSummary = persistentState.scopeRootSummary;
this.selectedRowIdentity = persistentState.selectedRowIdentity;
@@ -1287,7 +1291,8 @@ export class AgentsViewMode implements Component, Focusable {
this.expandedSubagentParents,
this.programShownParents,
this.scopeKey,
- computeRecursiveCosts(this.unifiedRecords, this.unifiedIndex),
+ computeRecursiveRollups(this.unifiedRecords, this.unifiedIndex),
+ this.anchorSessionId,
);
const index =
selectedIdentity === undefined ? -1 : this.rows.findIndex((row) => row.identity === selectedIdentity);
@@ -2174,7 +2179,8 @@ export class AgentsViewMode implements Component, Focusable {
this.expandedSubagentParents,
this.programShownParents,
this.scopeKey,
- computeRecursiveCosts(this.unifiedRecords, this.unifiedIndex),
+ computeRecursiveRollups(this.unifiedRecords, this.unifiedIndex),
+ this.anchorSessionId,
);
this.applyPendingAncestorExpansion();
this.restoreSelection();
@@ -2477,13 +2483,15 @@ export class AgentsViewMode implements Component, Focusable {
return [];
}
if (this.rows.length === 0) {
- return [theme.bold(sectionTitle("running")), theme.fg("dim", " No sessions match your search.")].slice(
- 0,
- maxRows,
- );
+ const emptyLegend = buildAgentsViewUsageLayout([]).legends.get("running") ?? "";
+ return [
+ this.renderSectionHeading("running", width, emptyLegend),
+ theme.fg("dim", " No sessions match your search."),
+ ].slice(0, maxRows);
}
const displayItems = buildDisplayItems(this.rows);
+ const usageLayout = buildAgentsViewUsageLayout(this.rows);
const selectedIdentity = this.rows[this.selectedIndex]?.identity;
const selectedDisplayIndex = displayItems.findIndex(
(item) => item.type === "row" && item.row.identity === selectedIdentity,
@@ -2502,18 +2510,22 @@ export class AgentsViewMode implements Component, Focusable {
0,
visibleRows - (showLeadingEllipsis ? 1 : 0) - (showTrailingEllipsis ? 1 : 0),
);
- const visibleItems = displayItems.slice(start, start + contentVisibleRows);
+ // The prepended ellipsis consumes a viewport line; shift the window down
+ // so a selection at the very end is not pushed out of the slice.
+ const sliceStart =
+ selectedDisplayIndex >= start + contentVisibleRows ? selectedDisplayIndex - contentVisibleRows + 1 : start;
+ const visibleItems = displayItems.slice(sliceStart, sliceStart + contentVisibleRows);
const lines = visibleItems.map((item) => {
if (item.type === "spacer") {
return "";
}
if (item.type === "heading") {
- return theme.bold(sectionTitle(item.section));
+ return this.renderSectionHeading(item.section, width, usageLayout.legends.get(item.section) ?? "");
}
if (item.type === "empty") {
return theme.fg("dim", " No agents");
}
- return this.renderRow(item.row, width);
+ return this.renderRow(item.row, width, usageLayout.details);
});
if (showLeadingEllipsis) {
lines.unshift(theme.fg("dim", " ..."));
@@ -2524,8 +2536,13 @@ export class AgentsViewMode implements Component, Focusable {
return lines;
}
- private renderRow(row: AgentsViewRow, width: number): string {
+ private renderRow(
+ row: AgentsViewRow,
+ width: number,
+ rowDetails: ReadonlyMap<string, string> = buildAgentsViewUsageLayout([row]).details,
+ ): string {
const selected = row.selectable && row.identity === this.rows[this.selectedIndex]?.identity;
+ const markRow = (line: string): string => (selected ? `${SELECTED_ROW_MARKER}${line}` : line);
if (row.kind === "subagent-code") {
return this.renderCodeRow(row);
}
@@ -2535,16 +2552,14 @@ export class AgentsViewMode implements Component, Focusable {
const titleColor = row.runningSubagentCount > 0 ? ("success" as const) : ("dim" as const);
const label = `${theme.fg(titleColor, `${row.expanded ? "▾" : "▸"} ${row.title}`)}${hint}`;
const line = padLine(truncateToWidth(`${indent}${label}`, width, ""), width);
- return selected ? `${SELECTED_ROW_MARKER}${line}` : line;
+ return markRow(line);
}
const pendingDelete = row.kind === "agent" && this.isPendingDeleteRow(row);
const pendingKill = row.kind === "subagent" && this.isPendingKillSubagentRow(row);
const rawIcon = this.getRowIcon(row.section);
const icon = this.formatRowIcon(row.section, rawIcon);
const indent = " ".repeat(row.depth);
- const age = formatSessionDuration(row.summary);
- const usageText = formatRowUsage(row);
- const details = usageText ? `${usageText} · ${age}` : age;
+ const details = rowDetails.get(row.identity) ?? "";
const detailsWidth = Math.max(10, visibleWidth(details));
const heartbeatBadge = !pendingDelete && !pendingKill ? formatHeartbeatBadge(row.heartbeat) : "";
const heartbeatPausedOnly = (row.heartbeat?.activeCount ?? 0) < 1;
@@ -2590,7 +2605,20 @@ export class AgentsViewMode implements Component, Focusable {
];
const base = `${indent}${cells[0]} ${heartbeatCell ? `${heartbeatCell} ` : ""}${cells[1]} ${cells[2]}`;
const line = padLine(truncateToWidth(base, width, ""), width);
- return selected ? `${SELECTED_ROW_MARKER}${line}` : line;
+ return markRow(line);
+ }
+
+ // Bold like the section title so the legend reads as part of the header line.
+ // The legend is right-aligned to the same edge as the row details cells, so
+ // its columns sit exactly above the row columns.
+ private renderSectionHeading(section: AgentsViewSection, width: number, legend: string): string {
+ const counts = countRowsBySection(this.rows);
+ const title = `${sectionTitle(section)} (${counts[section]})`;
+ const gap = width - visibleWidth(title) - visibleWidth(legend);
+ if (legend.length === 0 || gap < 2) {
+ return theme.bold(truncateToWidth(title, width, ""));
+ }
+ return `${theme.bold(title)}${" ".repeat(gap)}${theme.bold(legend)}`;
}
// Spawn-code rows are read-only context. They render deemphasized — muted
@@ -2831,11 +2859,97 @@ function hasLiveWork(row: AgentsViewRow): boolean {
return row.section === "running" || row.runningSubagentCount > 0 || row.summary.hasRunningRlmChildren === true;
}
-function formatRowUsage(row: AgentsViewRow): string {
- const usage = row.summary.usage;
- return `↑${formatTokenCount(usage?.inputTokens ?? 0)} ↓${formatTokenCount(usage?.outputTokens ?? 0)} · $${(
- usage?.cost ?? 0
- ).toFixed(2)} ($${row.recursiveCost.toFixed(2)} w/ subagents)`;
+interface AgentsViewUsageParts {
+ inTokens: string;
+ outTokens: string;
+ agentCost: string;
+ count: string;
+ totalCost: string;
+ age: string;
+}
+
+const AGENTS_VIEW_USAGE_LABELS: AgentsViewUsageParts = {
+ inTokens: "↑in",
+ outTokens: "↓out",
+ agentCost: "$agent",
+ count: "#sub",
+ totalCost: "$total",
+ age: "age",
+};
+
+const AGENTS_VIEW_USAGE_COLUMNS = Object.keys(AGENTS_VIEW_USAGE_LABELS) as (keyof AgentsViewUsageParts)[];
+
+export interface AgentsViewUsageLayout {
+ /** Legend line per section, padded to that section's column widths. */
+ legends: ReadonlyMap<AgentsViewSection, string>;
+ /** Details string per row identity, padded to its section's column widths. */
+ details: ReadonlyMap<string, string>;
+}
+
+/**
+ * One shared column layout per section for the header legend and every row:
+ * each column is as wide as the section's widest value or its legend label,
+ * everything right-aligned, so the ` · ` separators land in the same terminal
+ * column for the legend and every row. Empty sessions render only the age,
+ * aligned to the age column.
+ */
+export function buildAgentsViewUsageLayout(rows: readonly AgentsViewRow[]): AgentsViewUsageLayout {
+ const rowsBySection = new Map<AgentsViewSection, AgentsViewRow[]>();
+ // Nested rows render inside their top-level agent's section block, so group
+ // by the block's section rather than each row's own.
+ let blockSection: AgentsViewSection = "running";
+ for (const row of rows) {
+ if (row.depth === 0) blockSection = row.section;
+ if (row.kind !== "agent" && row.kind !== "subagent") continue;
+ const sectionRows = rowsBySection.get(blockSection) ?? [];
+ sectionRows.push(row);
+ rowsBySection.set(blockSection, sectionRows);
+ }
+ const legends = new Map<AgentsViewSection, string>();
+ const details = new Map<string, string>();
+ for (const section of ["running", "idle", "inactive"] as const) {
+ const entries = (rowsBySection.get(section) ?? []).map((row) => {
+ const usage = row.summary.usage;
+ const parts: AgentsViewUsageParts = {
+ inTokens: `↑${formatTokenCount(usage?.inputTokens ?? 0)}`,
+ outTokens: `↓${formatTokenCount(usage?.outputTokens ?? 0)}`,
+ agentCost: `$${(usage?.cost ?? 0).toFixed(2)}`,
+ count: String(row.descendantCount),
+ totalCost: `$${row.recursiveCost.toFixed(2)}`,
+ age: formatSessionDuration(row.summary),
+ };
+ return { identity: row.identity, empty: isEmptyAgentsViewSession(row.summary), parts };
+ });
+ const widths = {} as Record<keyof AgentsViewUsageParts, number>;
+ for (const column of AGENTS_VIEW_USAGE_COLUMNS) {
+ let width = visibleWidth(AGENTS_VIEW_USAGE_LABELS[column]);
+ for (const entry of entries) {
+ // Empty sessions render no usage segment; only their age takes space.
+ if (entry.empty && column !== "age") continue;
+ width = Math.max(width, visibleWidth(entry.parts[column]));
+ }
+ widths[column] = width;
+ }
+ const pad = (parts: AgentsViewUsageParts, column: keyof AgentsViewUsageParts): string =>
+ padCellStart(parts[column], widths[column]);
+ const formatLine = (parts: AgentsViewUsageParts): string =>
+ [
+ `${pad(parts, "inTokens")} ${pad(parts, "outTokens")}`,
+ pad(parts, "agentCost"),
+ pad(parts, "count"),
+ pad(parts, "totalCost"),
+ pad(parts, "age"),
+ ].join(" · ");
+ legends.set(section, formatLine(AGENTS_VIEW_USAGE_LABELS));
+ for (const entry of entries) {
+ details.set(entry.identity, entry.empty ? pad(entry.parts, "age") : formatLine(entry.parts));
+ }
+ }
+ return { legends, details };
+}
+
+function padCellStart(value: string, width: number): string {
+ return " ".repeat(Math.max(0, width - visibleWidth(value))) + value;
}
// Explicit session names read bold so they stand out from fallback titles
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 5ad1db9577..131787a7ea 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
@@ -77,6 +77,8 @@ export interface AgentsViewRow {
selectable: boolean;
runningSubagentCount: number;
recursiveCost: number;
+ /** Total descendant sessions (resident + passive) under this row. */
+ descendantCount: number;
/** Unique selection identity for this row. */
identity: string;
/** Identity of the agent row this row is nested under. */
@@ -110,6 +112,12 @@ export function shouldShowAgentsViewSession(summary: SessionSummary, manuallyIna
return summary.lifecycle === "live";
}
+// TODO(unify: #2055): replace with the shared user-content rule once it lands;
+// session summaries only carry message counts today.
+export function isEmptyAgentsViewSession(summary: SessionSummary): boolean {
+ return summary.messageCount === 0;
+}
+
export function sectionTitle(section: AgentsViewSection): string {
switch (section) {
case "running":
@@ -421,11 +429,19 @@ export interface UnifiedSessionIndex {
childrenByParent: Map<UnifiedSessionRecord, UnifiedSessionRecord[]>;
}
-// Rolls costs over the UNFILTERED hierarchy: filters must never change a row's total.
-export function computeRecursiveCosts(
+export interface AgentsViewRecursiveRollup {
+ /** Own cost plus every descendant's cost. */
+ cost: number;
+ /** Total descendant sessions (resident + passive) under this record. */
+ descendantCount: number;
+}
+
+// Rolls costs and descendant counts over the UNFILTERED hierarchy: filters must
+// never change a row's totals.
+export function computeRecursiveRollups(
records: readonly UnifiedSessionRecord[],
index: UnifiedSessionIndex = buildUnifiedSessionIndex(records),
-): ReadonlyMap<UnifiedSessionRecord, number> {
+): ReadonlyMap<UnifiedSessionRecord, AgentsViewRecursiveRollup> {
const order = records.filter((record) => {
const parent = findParentRecord(record, index.byKey);
return !parent || parent === record;
@@ -435,16 +451,35 @@ export function computeRecursiveCosts(
order.push(child);
}
}
- const costs = new Map<UnifiedSessionRecord, number>();
+ const rollups = new Map<UnifiedSessionRecord, AgentsViewRecursiveRollup>();
for (let position = order.length - 1; position >= 0; position--) {
const record = order[position]!;
- let total = record.daemon?.usage?.cost ?? record.saved?.usage?.cost ?? 0;
+ let cost = record.daemon?.usage?.cost ?? record.saved?.usage?.cost ?? 0;
+ let descendantCount = 0;
for (const child of index.childrenByParent.get(record) ?? []) {
- total += costs.get(child) ?? 0;
+ if (!isSubagentDescendantRecord(child, record)) continue;
+ const childRollup = rollups.get(child);
+ cost += childRollup?.cost ?? 0;
+ descendantCount += 1 + (childRollup?.descendantCount ?? 0);
}
- costs.set(record, total);
+ rollups.set(record, { cost, descendantCount });
+ }
+ return rollups;
+}
+
+/**
+ * Rollups follow agent lineage only. A branched/forked session links to its
+ * source through parentSession but keeps the source's rlmDepth: it is a
+ * sibling chat, not a descendant, and its copied transcript would double-book
+ * the source's totals. Spawned subagents carry runtimeKind (resident) or a
+ * deeper rlmDepth (saved) and do roll up.
+ */
+function isSubagentDescendantRecord(child: UnifiedSessionRecord, parent: UnifiedSessionRecord): boolean {
+ if (child.daemon) {
+ return isSubagentSummary(child.daemon);
}
- return costs;
+ const childDepth = child.saved?.rlmDepth ?? 0;
+ return childDepth > (parent.daemon?.rlmDepth ?? parent.saved?.rlmDepth ?? 0);
}
export function buildUnifiedSessionIndex(records: readonly UnifiedSessionRecord[]): UnifiedSessionIndex {
@@ -697,7 +732,8 @@ export function buildAgentsViewRows(
expandedSubagentParents: ReadonlySet<string> = new Set(),
programShownParents: ReadonlySet<string> = new Set(),
scope?: AgentsViewScopeKey,
- recursiveCosts?: ReadonlyMap<UnifiedSessionRecord, number>,
+ recursiveRollups?: ReadonlyMap<UnifiedSessionRecord, AgentsViewRecursiveRollup>,
+ anchorSessionId?: string,
): AgentsViewRow[] {
const inputs = summariesOrRecords.map((input) =>
isUnifiedSessionRecord(input) ? { summary: summaryForUnifiedRecord(input), record: input } : { summary: input },
@@ -726,6 +762,7 @@ export function buildAgentsViewRows(
selectable: true,
runningSubagentCount: 0,
recursiveCost: summary.usage?.cost ?? 0,
+ descendantCount: 0,
identity: record?.identity ?? getAgentsViewSummaryIdentity(summary),
...(record ? { record, heartbeat: record.heartbeat } : {}),
}),
@@ -745,6 +782,13 @@ export function buildAgentsViewRows(
row.kind = "agent";
continue;
}
+ // One definition of "child" with the rollup walk: a branched/forked
+ // session links to its source but is a top-level chat in its own right,
+ // so it must not nest (nor count in the expander) while #sub excludes it.
+ if (row.record && parent.record && !isSubagentDescendantRecord(row.record, parent.record)) {
+ row.kind = "agent";
+ continue;
+ }
nestedRows.add(row);
const siblings = childrenByParent.get(parent) ?? [];
siblings.push(row);
@@ -761,16 +805,20 @@ export function buildAgentsViewRows(
const row = tallyOrder[index]!;
let count = 0;
let descendantsCost = 0;
+ let descendants = 0;
for (const child of childrenByParent.get(row) ?? []) {
count += (child.section === "running" ? 1 : 0) + child.runningSubagentCount;
descendantsCost += child.recursiveCost;
+ descendants += 1 + child.descendantCount;
}
row.runningSubagentCount = count;
- row.recursiveCost =
- (row.record ? recursiveCosts?.get(row.record) : undefined) ?? (row.summary.usage?.cost ?? 0) + descendantsCost;
+ const rollup = row.record ? recursiveRollups?.get(row.record) : undefined;
+ row.recursiveCost = rollup?.cost ?? (row.summary.usage?.cost ?? 0) + descendantsCost;
+ row.descendantCount = rollup?.descendantCount ?? descendants;
}
const roots = baseRows.filter((row) => !nestedRows.has(row));
+ const compareRows = (a: AgentsViewRow, b: AgentsViewRow): number => compareAgentsViewRows(a, b, anchorSessionId);
const flattened: AgentsViewRow[] = [];
const emit = (row: MutableAgentsViewRow, depth: number): void => {
row.depth = depth;
@@ -786,7 +834,7 @@ export function buildAgentsViewRows(
return;
}
const showProgram = programShownParents.has(row.identity);
- const groups = groupChildrenBySpawnCode(children.sort(compareAgentsViewRows));
+ const groups = groupChildrenBySpawnCode(children.sort(compareRows));
for (const [groupIndex, group] of groups.entries()) {
if (showProgram && group.spawnCode) {
for (const codeRow of buildSpawnCodeRows(row, group.spawnCode, depth + 1, groupIndex)) {
@@ -801,7 +849,7 @@ export function buildAgentsViewRows(
};
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)) {
+ for (const root of visibleRoots.sort(compareRows)) {
emit(root, 0);
}
return flattened;
@@ -846,6 +894,7 @@ function createSubagentSummaryRow(
selectable: true,
runningSubagentCount: running,
recursiveCost: 0,
+ descendantCount: 0,
identity: `subagents:${parent.identity}`,
parentIdentity: parent.identity,
hasSpawnCode,
@@ -901,6 +950,7 @@ function buildSpawnCodeRows(
selectable: false,
runningSubagentCount: 0,
recursiveCost: 0,
+ descendantCount: 0,
identity: `code:${parent.identity}:${groupIndex}:${lineIndex}`,
parentIdentity: parent.identity,
code,
@@ -916,11 +966,15 @@ function buildSpawnCodeRows(
return [makeRow("", "pad-top"), ...lines, makeRow("", "pad-bottom")];
}
-function compareAgentsViewRows(a: AgentsViewRow, b: AgentsViewRow): number {
+function compareAgentsViewRows(a: AgentsViewRow, b: AgentsViewRow, anchorSessionId?: string): number {
const sectionDiff = sectionRank(a.section) - sectionRank(b.section);
if (sectionDiff !== 0) {
return sectionDiff;
}
+ const emptyDiff = emptySessionRank(a, anchorSessionId) - emptySessionRank(b, anchorSessionId);
+ if (emptyDiff !== 0) {
+ return emptyDiff;
+ }
if (a.section === "inactive") {
const heartbeatDiff =
Number(b.summary.hasActiveHeartbeat ?? false) - Number(a.summary.hasActiveHeartbeat ?? false);
@@ -949,6 +1003,16 @@ function compareAgentsViewRows(a: AgentsViewRow, b: AgentsViewRow): number {
return a.summary.sessionId.localeCompare(b.summary.sessionId);
}
+// Message-less sessions sink to the bottom of their section, except the session
+// the view was entered from: it keeps its recency slot so opening the agents
+// view from a fresh chat doesn't catapult that chat to the bottom.
+function emptySessionRank(row: AgentsViewRow, anchorSessionId: string | undefined): number {
+ if (!isEmptyAgentsViewSession(row.summary) || row.summary.sessionId === anchorSessionId) {
+ return 0;
+ }
+ return 1;
+}
+
function buildRowKeyMap(rows: readonly MutableAgentsViewRow[]): Map<string, MutableAgentsViewRow> {
const rowsByKey = new Map<string, MutableAgentsViewRow>();
for (const row of rows) {
diff --git a/packages/coding-agent/src/modes/index.ts b/packages/coding-agent/src/modes/index.ts
index 67327ca102..be3fedb232 100644
--- a/packages/coding-agent/src/modes/index.ts
+++ b/packages/coding-agent/src/modes/index.ts
@@ -32,6 +32,7 @@ export type {
export { DaemonAgentConnection, InProcessAgentConnection } from "./agent-connection/index.js";
export { type AgentsViewModeOptions, runAgentsViewMode } from "./agents-view/agents-view-mode.js";
export {
+ type AgentsViewRecursiveRollup,
type AgentsViewRow,
type AgentsViewScopeFrame,
type AgentsViewScopeKey,
@@ -41,7 +42,7 @@ export {
buildAgentsViewRows,
buildUnifiedSessionIndex,
classifyAgentsViewSession,
- computeRecursiveCosts,
+ computeRecursiveRollups,
createUnattachableChildOpenResult,
filterUnifiedSessions,
formatHeartbeatBadge,
@@ -49,6 +50,7 @@ export {
getAgentsViewSessionTitle,
getUnifiedSessionAncestorSessionIds,
hasUnifiedSessionChildren,
+ isEmptyAgentsViewSession,
reconcileUnifiedSessions,
resolveAgentsViewLeftResult,
resolveAgentsViewScopeFrames,
diff --git a/packages/coding-agent/test/agents-view-mode.test.ts b/packages/coding-agent/test/agents-view-mode.test.ts
index 5c947b67c7..bd731ee688 100644
--- a/packages/coding-agent/test/agents-view-mode.test.ts
+++ b/packages/coding-agent/test/agents-view-mode.test.ts
@@ -9,6 +9,7 @@ import type { AgentConnectionSavedSessionInfo } from "../src/modes/agent-connect
import {
AgentsViewMode,
type AgentsViewPersistentState,
+ buildAgentsViewUsageLayout,
combineAgentsViewStartupNotices,
createInitialAgentsViewPersistentState,
runAgentsViewMode,
@@ -717,7 +718,7 @@ describe("AgentsViewMode", () => {
}
});
- it("renders the unconditional usage cell and drops the message count", () => {
+ it("renders aligned usage columns with an explicit subagent count and drops the message count", () => {
const parent = summary({
id: "spender",
activeSessionId: "spender",
@@ -741,23 +742,148 @@ describe("AgentsViewMode", () => {
rosterStatus: "inactive",
messageCount: 7,
});
+ const empty = summary({
+ id: "empty-draft",
+ activeSessionId: undefined,
+ sessionId: "empty-draft-session",
+ sessionFile: "/tmp/empty-draft.jsonl",
+ rosterStatus: "inactive",
+ messageCount: 0,
+ modified: new Date(Date.now() - 120_000).toISOString(),
+ });
const view = new AgentsViewMode({ config: {}, uiServices: createUiServices() }, {});
try {
- const collapsed = buildAgentsViewRows([parent, child, inactive]);
- const rows = buildAgentsViewRows([parent, child, inactive], new Set(collapsed.map((row) => row.identity)));
+ const collapsed = buildAgentsViewRows([parent, child, inactive, empty]);
+ const rows = buildAgentsViewRows(
+ [parent, child, inactive, empty],
+ new Set(collapsed.map((row) => row.identity)),
+ );
Reflect.set(view, "rows", rows);
- const line = (row: AgentsViewRow | undefined) => stripAnsi(invoke("renderRow", view, row, 200) as string);
+ const layout = buildAgentsViewUsageLayout(rows);
+ const line = (row: AgentsViewRow | undefined) =>
+ stripAnsi(invoke("renderRow", view, row, 200, layout.details) as string);
const byId = (sessionId: string, kind?: string) =>
rows.find((row) => row.summary.sessionId === sessionId && (!kind || row.kind === kind));
- expect(line(byId("spender-session"))).toContain("↑12k ↓1.2k · $0.42 ($1.10 w/ subagents)");
- expect(line(byId("spender-child-session", "subagent"))).toContain("↑500 ↓50 · $0.68 ($0.68 w/ subagents)");
+ // Shared per-section layout: every column right-aligned to
+ // max(widest section value, legend label width).
+ expect(line(byId("spender-session"))).toContain("↑12k ↓1.2k · $0.42 · 1 · $1.10 ·");
+ expect(line(byId("spender-child-session", "subagent"))).toContain("↑500 ↓50 · $0.68 · 0 · $0.68 ·");
const inactiveLine = line(byId("saved-only-session"));
- expect(inactiveLine).toContain("↑0 ↓0 · $0.00 ($0.00 w/ subagents)");
+ expect(inactiveLine).toContain("↑0 ↓0 · $0.00 · 0 · $0.00 ·");
expect(inactiveLine).not.toContain("7 ·");
+ // The ` · ` separators land in the same column for the legend and every
+ // row of its section.
+ const dotColumns = (text: string) => [...text].flatMap((ch, index) => (ch === "·" ? [index] : []));
+ for (const [section, sessionId] of [
+ ["idle", "spender-session"],
+ ["idle", "spender-child-session"],
+ ["inactive", "saved-only-session"],
+ ] as const) {
+ const detail = layout.details.get(byId(sessionId)!.identity)!;
+ expect(dotColumns(detail)).toEqual(dotColumns(layout.legends.get(section)!));
+ }
+ // Empty sessions keep the age but drop the whole usage segment.
+ const emptyLine = line(byId("empty-draft-session"));
+ expect(emptyLine).not.toContain("↑");
+ expect(emptyLine).not.toContain("$");
+ expect(emptyLine).toMatch(/\d+[smhd]\s*$/);
+ // Without a shared layout the row pads only against its own section of one.
const bare = { ...byId("spender-session")!, summary: { ...parent, usage: undefined } };
- expect(line(bare)).toContain("↑0 ↓0 · $0.00 ($1.10 w/ subagents)");
+ expect(stripAnsi(invoke("renderRow", view, bare, 200) as string)).toContain(
+ " ↑0 ↓0 · $0.00 · 1 · $1.10 ·",
+ );
+ } finally {
+ stopThemeWatcher();
+ }
+ });
+
+ it("shows the bold usage legend on every section header", () => {
+ const running = (id: string, created: string) =>
+ summary({
+ id,
+ activeSessionId: id,
+ sessionId: `${id}-session`,
+ sessionName: id,
+ activity: "working",
+ isStreaming: true,
+ created,
+ });
+ const parent = running("busy-parent", "2026-01-01T00:00:00Z");
+ const child = summary({
+ id: "busy-child",
+ activeSessionId: "busy-child",
+ sessionId: "busy-child-session",
+ sessionName: "busy-child",
+ sessionFile: "/tmp/busy-child.jsonl",
+ runtimeKind: "subagent",
+ parentActiveSessionId: "busy-parent",
+ });
+ const summaries = [
+ running("busy-solo", "2026-01-02T00:00:00Z"),
+ parent,
+ child,
+ summary({ id: "idle-a", activeSessionId: "idle-a", sessionId: "idle-a-session", sessionName: "idle-a" }),
+ summary({ id: "idle-b", activeSessionId: "idle-b", sessionId: "idle-b-session", sessionName: "idle-b" }),
+ ];
+ const parentIdentity = buildAgentsViewRows(summaries).find(
+ (row) => row.summary.sessionId === "busy-parent-session",
+ )!.identity;
+ const rows = buildAgentsViewRows(summaries, new Set([parentIdentity]));
+ const view = new AgentsViewMode({ config: {}, uiServices: createUiServices() }, {});
+
+ try {
+ Reflect.set(view, "rows", rows);
+ Reflect.set(view, "selectedIndex", -1);
+ Reflect.set(view, "ui", { terminal: { rows: 60 }, requestRender: () => {} });
+ const rendered = invoke("renderSessionRows", view, 120, 40) as string[];
+ const lines = rendered.map(stripAnsi);
+ const headings = lines.filter((line) => /^(Running|Idle|Inactive) \(\d+\)/.test(line));
+ expect(headings).toHaveLength(3);
+ for (const heading of headings) {
+ expect(heading).toMatch(/↑in\s+↓out ·\s+\$agent ·\s+#sub ·\s+\$total ·\s+age$/);
+ }
+ // Same bold weight for title and legend.
+ const runningLegend = buildAgentsViewUsageLayout(rows).legends.get("running")!;
+ expect(invoke("renderSectionHeading", view, "running", 120, runningLegend)).toContain(
+ theme.bold(runningLegend),
+ );
+
+ // Session rows carry no background of their own; only the selection
+ // highlight may paint one.
+ const finalized = rendered.map((line) => invoke("finalizeRenderedLine", view, line, 120) as string);
+ for (const line of finalized) {
+ expect(line).not.toContain("\x1b[48");
+ }
+ } finally {
+ stopThemeWatcher();
+ }
+ });
+
+ it("keeps a selection at the end of the list visible when the leading ellipsis is shown", () => {
+ const summaries = Array.from({ length: 12 }, (_, index) =>
+ summary({
+ id: `saved-${index}`,
+ activeSessionId: undefined,
+ sessionId: `saved-${index}-session`,
+ sessionName: `saved-${index}`,
+ sessionFile: `/tmp/saved-${index}.jsonl`,
+ rosterStatus: "inactive" as const,
+ created: `2026-01-${String(index + 1).padStart(2, "0")}T00:00:00Z`,
+ }),
+ );
+ const rows = buildAgentsViewRows(summaries);
+ const view = new AgentsViewMode({ config: {}, uiServices: createUiServices() }, {});
+
+ try {
+ Reflect.set(view, "rows", rows);
+ Reflect.set(view, "selectedIndex", rows.length - 1);
+ Reflect.set(view, "ui", { terminal: { rows: 13 }, requestRender: () => {} });
+ const lines = (invoke("renderSessionRows", view, 120, 4) as string[]).map(stripAnsi);
+ expect(lines[0]).toContain("...");
+ const lastTitle = rows.at(-1)!.title;
+ expect(lines.some((line) => line.includes(lastTitle))).toBe(true);
} finally {
stopThemeWatcher();
}
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index 6807081fde..fc87951e40 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -27,7 +27,7 @@ import {
buildAgentsViewRows,
buildUnifiedSessionIndex,
classifyAgentsViewSession,
- computeRecursiveCosts,
+ computeRecursiveRollups,
createUnattachableChildOpenResult,
filterUnifiedSessions,
formatHeartbeatBadge,
@@ -303,6 +303,48 @@ describe("agents view state", () => {
expect(rows.map((row) => row.summary.sessionId)).toEqual(["beating", "recent"]);
});
+ test("demotes empty sessions to the bottom of their section except the entered-from anchor", () => {
+ const empty = makeSummary({
+ id: "empty",
+ activeSessionId: undefined,
+ sessionId: "empty",
+ sessionName: "empty",
+ messageCount: 0,
+ lastActivityAt: "2026-01-04T00:00:00Z",
+ });
+ const anchor = makeSummary({
+ id: "anchor",
+ activeSessionId: undefined,
+ sessionId: "anchor",
+ sessionName: "anchor",
+ messageCount: 0,
+ lastActivityAt: "2026-01-03T00:00:00Z",
+ });
+ const older = makeSummary({
+ id: "older",
+ activeSessionId: undefined,
+ sessionId: "older",
+ sessionName: "older",
+ messageCount: 3,
+ lastActivityAt: "2026-01-02T00:00:00Z",
+ });
+
+ // The entered-from session keeps its recency slot even while empty.
+ const anchored = buildAgentsViewRows(
+ [empty, anchor, older],
+ new Set(),
+ new Set(),
+ undefined,
+ undefined,
+ "anchor",
+ );
+ expect(anchored.map((row) => row.summary.sessionId)).toEqual(["anchor", "older", "empty"]);
+
+ // Entered from elsewhere, every empty session sinks below non-empty ones.
+ const unanchored = buildAgentsViewRows([empty, anchor, older]);
+ expect(unanchored.map((row) => row.summary.sessionId)).toEqual(["older", "empty", "anchor"]);
+ });
+
test("summarizes subagents on their parent and omits subagent rows", () => {
const rows = buildAgentsViewRows([
makeSummary({
@@ -527,13 +569,14 @@ describe("agents view state", () => {
usage: { inputTokens: 20, outputTokens: 2, cost: 0.18 },
});
const records = reconcileUnifiedSessions([parent, child, grandchild], []);
- const costs = computeRecursiveCosts(records);
+ const rollups = computeRecursiveRollups(records);
const filtered = filterUnifiedSessions(records, (text) => text.includes("Searchable"));
expect(filtered).toHaveLength(1);
- const rows = buildAgentsViewRows(filtered, new Set(), new Set(), undefined, costs);
+ const rows = buildAgentsViewRows(filtered, new Set(), new Set(), undefined, rollups);
expect(rows[0]?.summary.usage?.cost).toBe(0.42);
expect(rows[0]?.recursiveCost).toBeCloseTo(1.28);
+ expect(rows[0]?.descendantCount).toBe(2);
});
test("keeps a parent's recursive total when a passivated child survives only as a catalog row", () => {
@@ -554,7 +597,7 @@ describe("agents view state", () => {
usage: { inputTokens: 50, outputTokens: 5, cost: 0.68 },
});
const before = reconcileUnifiedSessions([parent, liveChild], []);
- const beforeTotal = computeRecursiveCosts(before).get(before[0]!);
+ const beforeRollup = computeRecursiveRollups(before).get(before[0]!);
// After a restart the child exists only as a saved-catalog row.
const after = reconcileUnifiedSessions(
@@ -569,10 +612,50 @@ describe("agents view state", () => {
}),
],
);
- const afterTotal = computeRecursiveCosts(after).get(after[0]!);
+ const afterRollup = computeRecursiveRollups(after).get(after[0]!);
+
+ expect(beforeRollup?.cost).toBeCloseTo(1.1);
+ expect(afterRollup).toEqual(beforeRollup);
+ expect(afterRollup?.descendantCount).toBe(1);
+ });
+
+ test("rolls up spawned subagents but never a branched session's copied lineage", () => {
+ const source = makeSummary({
+ id: "src",
+ activeSessionId: "src",
+ sessionId: "src-session",
+ sessionFile: "/tmp/project/src.jsonl",
+ usage: { inputTokens: 100, outputTokens: 10, cost: 0.4 },
+ });
+ const branch = makeSessionInfo({
+ path: "/tmp/project/branch.jsonl",
+ id: "branch-session",
+ parentSessionPath: "/tmp/project/src.jsonl",
+ // Branch/fork headers keep the source's depth; only spawns go deeper.
+ rlmDepth: 0,
+ usage: { inputTokens: 100, outputTokens: 10, cost: 0.4 },
+ });
+ const child = makeSessionInfo({
+ path: "/tmp/project/child.jsonl",
+ id: "child-session",
+ parentSessionPath: "/tmp/project/src.jsonl",
+ rlmDepth: 1,
+ usage: { inputTokens: 20, outputTokens: 2, cost: 0.1 },
+ });
+
+ const branchOnly = reconcileUnifiedSessions([source], [branch]);
+ expect(computeRecursiveRollups(branchOnly).get(branchOnly[0]!)).toEqual({ cost: 0.4, descendantCount: 0 });
+
+ const withChild = reconcileUnifiedSessions([source], [branch, child]);
+ const rollup = computeRecursiveRollups(withChild).get(withChild[0]!);
+ expect(rollup?.descendantCount).toBe(1);
+ expect(rollup?.cost).toBeCloseTo(0.5);
- expect(beforeTotal).toBeCloseTo(1.1);
- expect(afterTotal).toBe(beforeTotal);
+ // The tree shares that definition of "child": the branch renders as its
+ // own top-level session while only the spawned child nests and counts.
+ const rows = buildAgentsViewRows(withChild, new Set(), new Set(), undefined, computeRecursiveRollups(withChild));
+ expect(rows.find((row) => row.summary.sessionId === "branch-session")).toMatchObject({ kind: "agent", depth: 0 });
+ expect(rows.find((row) => row.kind === "subagent-summary")).toMatchObject({ title: "1 subagent" });
});
test("tallies a very deep child chain without overflowing the stack", () => {
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 0de5ced79d..9e891ebbc0 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
@@ -427,6 +427,7 @@ describe("#502 unified session view regressions", () => {
selectable: true,
runningSubagentCount: 0,
recursiveCost: 0,
+ descendantCount: 0,
identity: "archived",
};
const harness = {
@@ -445,7 +446,7 @@ describe("#502 unified session view regressions", () => {
50,
),
);
- expect(rendered).toMatch(/↑0 ↓0 · \$0\.00 \(\$0\.00 w\/ subagents\) · 2h\s*$/);
+ expect(rendered).toMatch(/↑0\s+↓0 ·\s+\$0\.00 ·\s+0 ·\s+\$0\.00 ·\s+2h\s*$/);
});
test("scoped subagent rows keep model and effort ahead of summaries", () => {
@@ -469,6 +470,7 @@ describe("#502 unified session view regressions", () => {
selectable: true,
runningSubagentCount: 0,
recursiveCost: 0,
+ descendantCount: 0,
identity: "effort-child",
parentIdentity: "parent",
};