A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
ENG-5105 Keep agents view expansion state when leaving and returning (#1135)
Sebastian Müllerd698b4b7029d
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex e766736e7a..f0ec06063b 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -6,6 +6,8 @@- Added privacy-safe pseudonymous product analytics for onboarding, command use, execution modes, run outcomes, TTFT, latency, usage, tools, retries, and compactions, with disclosure and opt-out controls ([ENG-4682](https://linear.app/primeintellect/issue/ENG-4682/add-privacy-safe-posthog-analytics-to-prime-agent)).- Changed sent agent messages in the IPython cell UI to show only the message text with a `╰─` gutter when expanded, matching received messages, and hid the raw `agent_message.send` receipt dictionary.- Fixed Homebrew installs attempting to self-update their versioned Cellar keg instead of directing users to `brew upgrade prime-agent` ([#844](https://github.com/PrimeIntellect-ai/prime-agent/issues/844))+- Fixed the agents view collapsing expanded subagent lists when returning from an opened agent ([ENG-5105](https://linear.app/primeintellect/issue/ENG-5105/keep-the-agents-view-state-persistent)).+- Kept the subagent summary row visible and selectable while its list is expanded in the agents view, so pressing enter on it collapses the list again ([ENG-5105](https://linear.app/primeintellect/issue/ENG-5105/keep-the-agents-view-state-persistent)).## [0.7.1] - 2026-08-07diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.tsindex a7e700400a..611f4be603 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@@ -81,6 +81,7 @@ import {getAgentsViewSummaryIdentity as getSummaryIdentity,getUnifiedSessionAncestorSessionIds,hasUnifiedSessionChildren,+ migrateAgentsViewIdentitySet,reconcileUnifiedSessions,resolveAgentsViewLeftResult,resolveAgentsViewScopeFrames,@@ -157,6 +158,9 @@ export type AgentsViewPersistentState = {// 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[];+ // Shared with each view instance so in-place expansion mutations survive remounts.+ expandedSubagentParents?: Set<string>;+ programShownParents?: Set<string>;statusMessage?: string;// Gathered once and reused across agents-view instances so the notices survive// re-entry and render the moment they resolve, even if the first view was left early.@@ -705,6 +709,10 @@ export class AgentsViewMode implements Component, Focusable {this.savedCatalogReady = persistentState.lastSuccessfulSavedSessions !== undefined;this.heartbeats = persistentState.heartbeats ?? [];this.savedCatalogGeneration = persistentState.savedCatalogGeneration ?? 0;+ this.expandedSubagentParents = persistentState.expandedSubagentParents ?? new Set();+ persistentState.expandedSubagentParents = this.expandedSubagentParents;+ this.programShownParents = persistentState.programShownParents ?? new Set();+ persistentState.programShownParents = this.programShownParents;this.keybindings = KeybindingsManager.create();setKeybindings(this.keybindings);setRegisteredThemes(options.uiServices.getThemes());@@ -1175,7 +1183,6 @@ export class AgentsViewMode implements Component, Focusable {: 0;const nextPosition = Math.max(0, Math.min(selectableIndexes.length - 1, currentPosition + delta));this.selectedIndex = selectableIndexes[nextPosition] ?? 0;- this.collapseSubagentListsOutsideSelection();this.syncSelectedRowState();this.clearDeleteConfirmation({ render: false });// Reply stays armed only while the selection sits on the agent row it@@ -1217,40 +1224,6 @@ export class AgentsViewMode implements Component, Focusable {}}- /** Expanded subagent lists collapse back to their summary row once selection leaves them. */- private collapseSubagentListsOutsideSelection(): void {- if (this.expandedSubagentParents.size === 0) {- return;- }- const keep = new Set<string>();- const selectedRow = this.rows[this.selectedIndex];- // Selecting the expanded agent itself still counts as inside its list;- // only moving past the block (above the parent or below the last child)- // collapses it.- if (selectedRow && this.expandedSubagentParents.has(selectedRow.identity)) {- keep.add(selectedRow.identity);- }- let parentIdentity = selectedRow?.parentIdentity;- while (parentIdentity !== undefined && !keep.has(parentIdentity)) {- keep.add(parentIdentity);- const target: string = parentIdentity;- parentIdentity = this.rows.find((row) => row.identity === target)?.parentIdentity;- }- const next = new Set([...this.expandedSubagentParents].filter((identity) => keep.has(identity)));- if (next.size === this.expandedSubagentParents.size) {- return;- }- this.expandedSubagentParents = next;- // A collapsed agent's revealed program collapses with it, so reopening- // starts from the hidden state rather than a stale reveal.- for (const identity of [...this.programShownParents]) {- if (!next.has(identity)) {- this.programShownParents.delete(identity);- }- }- this.rebuildRows();- }-private setSearchQuery(query: string): void {this.editor.setText(query);this.queryChanged();@@ -1363,7 +1336,7 @@ export class AgentsViewMode implements Component, Focusable {return;}if (row.kind === "subagent-summary") {- this.expandSubagentList(row);+ this.toggleSubagentList(row);return;}if (row.kind === "subagent") {@@ -1385,18 +1358,19 @@ export class AgentsViewMode implements Component, Focusable {});}- private expandSubagentList(row: AgentsViewRow): void {+ private toggleSubagentList(row: AgentsViewRow): void {if (!row.parentIdentity) {return;}- this.expandedSubagentParents.add(row.parentIdentity);- this.rebuildRows();- const firstChild = this.rows.findIndex(- (candidate) => candidate.kind === "subagent" && candidate.parentIdentity === row.parentIdentity,- );- if (firstChild >= 0) {- this.selectedIndex = firstChild;+ if (this.expandedSubagentParents.has(row.parentIdentity)) {+ this.expandedSubagentParents.delete(row.parentIdentity);+ // A collapsed agent's revealed program collapses with it, so reopening+ // starts from the hidden state rather than a stale reveal.+ this.programShownParents.delete(row.parentIdentity);+ } else {+ this.expandedSubagentParents.add(row.parentIdentity);}+ this.rebuildRows();this.syncSelectedRowState();this.ui.requestRender();}@@ -1426,15 +1400,7 @@ export class AgentsViewMode implements Component, Focusable {} else {this.programShownParents.add(target);}- const prevIdentity = row.identity;this.rebuildRows();- // The collapsed summary row vanishes once expanded; keep a sane selection.- if (this.rows[this.selectedIndex]?.identity !== prevIdentity) {- const agentIndex = this.rows.findIndex((candidate) => candidate.identity === target);- if (agentIndex >= 0) {- this.selectedIndex = agentIndex;- }- }this.syncSelectedRowState();this.ui.requestRender();}@@ -2179,6 +2145,8 @@ 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);+ migrateAgentsViewIdentitySet(this.expandedSubagentParents, this.unifiedIndex.byKey);+ migrateAgentsViewIdentitySet(this.programShownParents, this.unifiedIndex.byKey);const frames = this.persistentState.scopeFrames ?? [];const resolution = resolveAgentsViewScopeFrames(this.unifiedRecords, frames, this.unifiedIndex);@@ -2555,7 +2523,7 @@ export class AgentsViewMode implements Component, Focusable {if (row.kind === "subagent-summary") {const indent = " ".repeat(row.depth);const hint = row.hasSpawnCode ? theme.fg("dim", ` · ${keyText("app.agents.program")} show program`) : "";- const label = `${theme.fg("dim", `▸ ${row.title}`)}${hint}`;+ const label = `${theme.fg("dim", `${row.expanded ? "▾" : "▸"} ${row.title}`)}${hint}`;const line = padLine(truncateToWidth(`${indent}${label}`, width, ""), width);return selected ? `${SELECTED_ROW_MARKER}${line}` : line;}@@ -2683,10 +2651,13 @@ export class AgentsViewMode implements Component, Focusable {const selectedRow = this.rows[this.selectedIndex];const selectedAgent = selectedRow?.kind === "agent";const selectedSubagent = selectedRow?.kind === "subagent";+ const selectedSummary = selectedRow?.kind === "subagent-summary";const hints = [`${keyText("tui.select.up")}/${keyText("tui.select.down")} move`,- `${keyText("tui.select.confirm")} open`,- `${keyText("app.agents.open")} open`,+ selectedSummary+ ? `${keyText("tui.select.confirm")} ${selectedRow?.expanded ? "collapse" : "expand"}`+ : `${keyText("tui.select.confirm")} open`,+ selectedSummary ? undefined : `${keyText("app.agents.open")} open`,selectedAgent? `${keyText("app.agents.reply")} ${selectedRow?.section === "inactive" ? "resume" : "reply"}`: undefined,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.tsindex 2cc944a892..b7a70a2195 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@@ -80,6 +80,8 @@ export interface AgentsViewRow {parentIdentity?: string;/** True when this row's subagents carry spawn code that can be revealed. */hasSpawnCode?: boolean;+ /** True when this subagent-summary row's list is expanded. */+ expanded?: boolean;/** One source line of the spawn cell, for "subagent-code" rows. */code?: string;/** Merged durable/live source data for unified rows. */@@ -423,6 +425,24 @@ export function buildUnifiedSessionIndex(records: readonly UnifiedSessionRecord[return { byKey, childrenByParent };}+/**+ * Row identities flip when a session gains a sessionFile (active→persisted) or+ * is re-attached; the old identity survives as an alias. Rewrite stale entries+ * in a persisted identity set to the current record identity. Entries with no+ * alias match are kept: their record may not have streamed in yet.+ */+export function migrateAgentsViewIdentitySet(+ identities: Set<string>,+ byKey: ReadonlyMap<string, UnifiedSessionRecord>,+): void {+ for (const identity of [...identities]) {+ const record = byKey.get(identity);+ if (!record || record.identity === identity) continue;+ identities.delete(identity);+ identities.add(record.identity);+ }+}+function findScopeRecord(scope: AgentsViewScopeKey,byKey: ReadonlyMap<string, UnifiedSessionRecord>,@@ -675,22 +695,23 @@ export function buildAgentsViewRows(return;}const childHasSpawnCode = children.some((child) => hasSpawnCode(child.summary));- if (expandedSubagentParents.has(row.identity)) {- const showProgram = programShownParents.has(row.identity);- const groups = groupChildrenBySpawnCode(children.sort(compareAgentsViewRows));- for (const [groupIndex, group] of groups.entries()) {- if (showProgram && group.spawnCode) {- for (const codeRow of buildSpawnCodeRows(row, group.spawnCode, depth + 1, groupIndex)) {- flattened.push(codeRow);- }- }- for (const child of group.children) {- child.parentIdentity = row.identity;- emit(child, depth + 1);+ const expanded = expandedSubagentParents.has(row.identity);+ flattened.push(createSubagentSummaryRow(row, children, depth + 1, childHasSpawnCode, expanded));+ if (!expanded) {+ return;+ }+ const showProgram = programShownParents.has(row.identity);+ const groups = groupChildrenBySpawnCode(children.sort(compareAgentsViewRows));+ for (const [groupIndex, group] of groups.entries()) {+ if (showProgram && group.spawnCode) {+ for (const codeRow of buildSpawnCodeRows(row, group.spawnCode, depth + 1, groupIndex)) {+ flattened.push(codeRow);}}- } else {- flattened.push(createSubagentSummaryRow(row, children, depth + 1, childHasSpawnCode));+ for (const child of group.children) {+ child.parentIdentity = row.identity;+ emit(child, depth + 1);+ }}};const scopedRootRow = scopeRoot ? baseRows.find((row) => row.summary === scopeRoot.summary) : undefined;@@ -731,6 +752,7 @@ function createSubagentSummaryRow(children: readonly AgentsViewRow[],depth: number,hasSpawnCode: boolean,+ expanded: boolean,): AgentsViewRow {const totalCount = children.length;const running = parent.runningSubagentCount;@@ -760,6 +782,7 @@ function createSubagentSummaryRow(identity: `subagents:${parent.identity}`,parentIdentity: parent.identity,hasSpawnCode,+ expanded,};}diff --git a/packages/coding-agent/test/agents-view-mode.test.ts b/packages/coding-agent/test/agents-view-mode.test.tsindex b565937521..d04a2b7a73 100644--- a/packages/coding-agent/test/agents-view-mode.test.ts+++ b/packages/coding-agent/test/agents-view-mode.test.ts@@ -12,7 +12,7 @@ import {createInitialAgentsViewPersistentState,runAgentsViewMode,} from "../src/modes/agents-view/agents-view-mode.js";-import { resolveAgentsViewLeftResult } from "../src/modes/agents-view/agents-view-state.js";+import { type AgentsViewRow, resolveAgentsViewLeftResult } from "../src/modes/agents-view/agents-view-state.js";import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";import type { InteractiveModeUiServices } from "../src/modes/interactive/interactive-mode-services.js";import { stopThemeWatcher } from "../src/modes/interactive/theme/theme.js";@@ -522,6 +522,132 @@ describe("AgentsViewMode", () => {selection: { sessionId: root.sessionId },});});++ it("restores expanded subagent lists across view remounts", () => {+ const persistentState: AgentsViewPersistentState = {};+ const view = new AgentsViewMode({ config: {}, uiServices: createUiServices() }, persistentState);+ try {+ (Reflect.get(view, "expandedSubagentParents") as Set<string>).add("file:/tmp/root.jsonl");+ (Reflect.get(view, "programShownParents") as Set<string>).add("file:/tmp/root.jsonl");++ const remount = new AgentsViewMode({ config: {}, uiServices: createUiServices() }, persistentState);+ expect((Reflect.get(remount, "expandedSubagentParents") as Set<string>).has("file:/tmp/root.jsonl")).toBe(+ true,+ );+ expect((Reflect.get(remount, "programShownParents") as Set<string>).has("file:/tmp/root.jsonl")).toBe(true);++ // A collapsed-back list persists that way too.+ (Reflect.get(remount, "expandedSubagentParents") as Set<string>).delete("file:/tmp/root.jsonl");+ const collapsedRemount = new AgentsViewMode({ config: {}, uiServices: createUiServices() }, persistentState);+ expect(+ (Reflect.get(collapsedRemount, "expandedSubagentParents") as Set<string>).has("file:/tmp/root.jsonl"),+ ).toBe(false);+ } finally {+ stopThemeWatcher();+ }+ });++ it("keeps subagent expansion across the active-to-persisted identity flip", () => {+ const rowsOf = (self: Record<string, unknown>) => Reflect.get(self, "rows") as AgentsViewRow[];+ const buildView = (expand: boolean) => {+ const parent = summary({+ id: "root-active",+ activeSessionId: "root-active",+ sessionId: "root-session",+ sessionFile: undefined,+ runtimeKind: "top-level",+ });+ const child = summary({+ id: "child-active",+ activeSessionId: "child-active",+ sessionId: "child-session",+ sessionFile: undefined,+ runtimeKind: "subagent",+ parentSessionId: "root-session",+ parentActiveSessionId: "root-active",+ });+ const expandedSubagentParents = new Set<string>();+ const self: Record<string, unknown> = {+ persistentState: {},+ lastListedSummaries: [parent, child],+ savedSessions: [],+ heartbeats: [],+ inactiveAgentIdentities: new Set(),+ pendingDeleteAgent: undefined,+ liveCatalogReady: true,+ savedCatalogReady: true,+ expandedSubagentParents,+ programShownParents: new Set(),+ editor: { getText: () => "" },+ getFilteredRecords: () => Reflect.get(self, "scopedRecords"),+ applyPendingAncestorExpansion: vi.fn(),+ restoreSelection: vi.fn(),+ ui: { requestRender: vi.fn() },+ setStatusMessage: vi.fn(),+ withPendingDeleteSession: (sessions: SessionSummary[]) => sessions,+ };+ invoke("reconcileCatalogs", self);+ if (expand) {+ const parentRow = rowsOf(self).find(+ (row) => row.kind === "agent" && row.summary.sessionId === "root-session",+ );+ expect(parentRow?.identity).toBe("session:root-session");+ expandedSubagentParents.add(parentRow!.identity);+ invoke("reconcileCatalogs", self);+ expect(rowsOf(self).some((row) => row.kind === "subagent-summary" && row.expanded)).toBe(true);+ }+ // The runtime flushes the session file; the record identity flips to file:.+ self.lastListedSummaries = [{ ...parent, sessionFile: "/tmp/root.jsonl" }, child];+ invoke("reconcileCatalogs", self);+ return { self, expandedSubagentParents };+ };++ const expandedView = buildView(true);+ const expandedRows = rowsOf(expandedView.self);+ expect(+ expandedRows.find((row) => row.kind === "agent" && row.summary.sessionId === "root-session")?.identity,+ ).toBe("file:/tmp/root.jsonl");+ expect(expandedRows.some((row) => row.kind === "subagent-summary" && row.expanded)).toBe(true);+ expect(expandedRows.some((row) => row.kind === "subagent" && row.summary.sessionId === "child-session")).toBe(+ true,+ );+ expect([...expandedView.expandedSubagentParents]).toEqual(["file:/tmp/root.jsonl"]);++ const collapsedView = buildView(false);+ const collapsedRows = rowsOf(collapsedView.self);+ expect(collapsedRows.some((row) => row.kind === "subagent-summary" && row.expanded)).toBe(false);+ expect(collapsedRows.some((row) => row.kind === "subagent")).toBe(false);+ expect(collapsedView.expandedSubagentParents.size).toBe(0);+ });++ it("toggles subagent list expansion from the summary row", () => {+ const expandedSubagentParents = new Set(["root-row"]);+ const programShownParents = new Set(["root-row"]);+ const persistentState: AgentsViewPersistentState = {+ expandedSubagentParents,+ programShownParents,+ };+ const self: Record<string, unknown> = {+ persistentState,+ expandedSubagentParents,+ programShownParents,+ rebuildRows: vi.fn(),+ syncSelectedRowState: vi.fn(),+ ui: { requestRender: vi.fn() },+ };+ const summaryRow = { kind: "subagent-summary", parentIdentity: "root-row", expanded: true };++ invoke("toggleSubagentList", self, summaryRow);+ expect(expandedSubagentParents.size).toBe(0);+ // Collapsing the list hides its revealed program too.+ expect(programShownParents.size).toBe(0);+ expect(self.rebuildRows).toHaveBeenCalledTimes(1);++ invoke("toggleSubagentList", self, { ...summaryRow, expanded: false });+ expect(expandedSubagentParents).toEqual(new Set(["root-row"]));+ expect(programShownParents.size).toBe(0);+ expect(self.rebuildRows).toHaveBeenCalledTimes(2);+ });});function createUiServices(): InteractiveModeUiServices {diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.tsindex b673983f13..004e43e9db 100644--- a/packages/coding-agent/test/agents-view-state.test.ts+++ b/packages/coding-agent/test/agents-view-state.test.ts@@ -335,7 +335,8 @@ describe("agents view state", () => {runningSubagentCount: 1,});const expanded = buildAgentsViewRows(summaries, new Set([collapsed[0]?.identity ?? ""]));- expect(expanded[1]).toMatchObject({+ expect(expanded[1]).toMatchObject({ kind: "subagent-summary", expanded: true });+ expect(expanded[2]).toMatchObject({kind: "subagent",section: "running",statusLabel: "heartbeat active",@@ -475,14 +476,17 @@ describe("agents view state", () => {const collapsed = buildAgentsViewRows(summaries);expect(collapsed.map((row) => row.kind)).toEqual(["agent", "subagent-summary"]);expect(collapsed[1]?.title).toBe("1 subagent running");+ expect(collapsed[1]?.expanded).toBe(false);const parentIdentity = collapsed[0]?.identity;const expanded = buildAgentsViewRows(summaries, new Set([parentIdentity ?? ""]));expect(expanded.map((row) => [row.title, row.kind, row.depth])).toEqual([["Parent", "agent", 0],+ ["1 subagent running", "subagent-summary", 1],["Child", "subagent", 1],["Completed child", "subagent", 1],]);+ expect(expanded[1]?.expanded).toBe(true);expect(expanded.slice(1).every((row) => row.selectable && row.parentIdentity === parentIdentity)).toBe(true);});@@ -525,6 +529,7 @@ describe("agents view state", () => {const oneLevel = buildAgentsViewRows(summaries, new Set([rootIdentity]));expect(oneLevel.map((row) => [row.title, row.kind])).toEqual([["Root", "agent"],+ ["1 subagent running", "subagent-summary"],["Child", "subagent"],["1 subagent running", "subagent-summary"],]);@@ -533,7 +538,9 @@ describe("agents view state", () => {const twoLevel = buildAgentsViewRows(summaries, new Set([rootIdentity, childIdentity]));expect(twoLevel.map((row) => [row.title, row.kind, row.depth])).toEqual([["Root", "agent", 0],+ ["1 subagent running", "subagent-summary", 1],["Child", "subagent", 1],+ ["1 subagent running", "subagent-summary", 2],["Grandchild", "subagent", 2],]);});@@ -657,14 +664,21 @@ describe("agents view state", () => {const parentIdentity = collapsed[0]?.identity ?? "";const expandedNoProgram = buildAgentsViewRows(summaries, new Set([parentIdentity]));- // Without the program toggle, only the grouped subagent rows render.- expect(expandedNoProgram.map((row) => row.kind)).toEqual(["agent", "subagent", "subagent", "subagent"]);+ // Without the program toggle, only the summary and grouped subagent rows render.+ expect(expandedNoProgram.map((row) => row.kind)).toEqual([+ "agent",+ "subagent-summary",+ "subagent",+ "subagent",+ "subagent",+ ]);const expanded = buildAgentsViewRows(summaries, new Set([parentIdentity]), new Set([parentIdentity]));// Each spawn cell renders in full, once, directly above the subagents it// launched — padded with a blank panel line above and below, no truncation.expect(expanded.map((row) => [row.kind, row.code ?? row.title])).toEqual([["agent", "Parent"],+ ["subagent-summary", "3 subagents"],["subagent-code", ""],["subagent-code", "task = sleep(60)"],["subagent-code", "for i in range(2):"],@@ -948,7 +962,9 @@ describe("agents view state", () => {).toEqual([["newer-session", 0],["root-session", 0],+ ["root-session", 1],["child-session", 1],+ ["child-session", 2],["match-session", 2],]);});