Skip to content

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

Rust

[RSI, feature] Headless sessions operator table for the daemon CLI (#2422)

Seth Karten05398e41b9a6
diff --git a/packages/coding-agent/.changes/sessions-ops-table.md b/packages/coding-agent/.changes/sessions-ops-table.md
new file mode 100644
index 0000000000..4599fab12c
--- /dev/null
+++ b/packages/coding-agent/.changes/sessions-ops-table.md
@@ -0,0 +1 @@
+- Added `prime-agent sessions`, a one-line-per-agent operator table (status, activity, staleness, last error, usage) rendered client-side from the existing daemon session summaries.
diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.md
index dfe1a5b4dc..be55d6036e 100644
--- a/packages/coding-agent/README.md
+++ b/packages/coding-agent/README.md
@@ -508,6 +508,7 @@ Run `prime-agent help` for the command list and `prime-agent help <command>` for
```bash
prime-agent agents # Search running, idle, and inactive sessions
prime-agent list [--all] # List active or saved agents
+prime-agent sessions [--all] [--json] # Show agent status, activity, and usage
prime-agent attach <agent> # Attach the interactive UI
prime-agent stop <agent> # Stop one agent
prime-agent rename <agent> <name> # Rename an agent
diff --git a/packages/coding-agent/docs/usage.md b/packages/coding-agent/docs/usage.md
index e55009437b..d036037b7b 100644
--- a/packages/coding-agent/docs/usage.md
+++ b/packages/coding-agent/docs/usage.md
@@ -174,6 +174,7 @@ prime-agent [options] [@files...] [messages...]
```bash
prime-agent agents
prime-agent list [--all]
+prime-agent sessions [--all] [--json]
prime-agent attach <agent>
prime-agent stop <agent>
prime-agent rename <agent> <name>
diff --git a/packages/coding-agent/src/cli/command-registry.ts b/packages/coding-agent/src/cli/command-registry.ts
index b3cdbebcb8..92ae80fb19 100644
--- a/packages/coding-agent/src/cli/command-registry.ts
+++ b/packages/coding-agent/src/cli/command-registry.ts
@@ -27,6 +27,12 @@ export const COMMAND_SPECS: readonly CommandSpec[] = [
summary: "List agents",
options: ["-a, --all Include saved agents", "--json Print JSON"],
},
+ {
+ path: ["sessions"],
+ usage: "sessions [--all] [--json]",
+ summary: "Show agent status, activity, and usage",
+ options: ["-a, --all Include saved agents", "--json Print JSON"],
+ },
{
path: ["attach"],
usage: "attach <agent>",
diff --git a/packages/coding-agent/src/cli/daemon-command.ts b/packages/coding-agent/src/cli/daemon-command.ts
index e0073ab519..b3fcee37b0 100644
--- a/packages/coding-agent/src/cli/daemon-command.ts
+++ b/packages/coding-agent/src/cli/daemon-command.ts
@@ -18,6 +18,7 @@ import { isLocalPath } from "../utils/paths.js";
import { isValidThinkingLevel } from "./args.js";
import { formatSessionListTable } from "./daemon-list-format.js";
import { runPs, runReap } from "./daemon-ps.js";
+import { formatSessionsTable } from "./sessions-table-format.js";
interface ParsedDaemonClientCommand {
command: string;
@@ -30,6 +31,7 @@ const DAEMON_CLIENT_COMMANDS = new Set([
"start",
"ps",
"list",
+ "sessions",
"create",
"attach",
"detach",
@@ -154,6 +156,9 @@ async function runDaemonClientCommand(parsed: ParsedDaemonClientCommand): Promis
case "list":
await runList(client, parsed.positionals, parsed.json);
return;
+ case "sessions":
+ await runSessions(client, parsed.positionals, parsed.json);
+ return;
case "create":
await runCreate(client, parsed.positionals, parsed.json);
return;
@@ -779,6 +784,42 @@ function parseListArgs(args: string[]): { all: boolean } {
return { all };
}
+// The same list RPC as `prime-agent list`, rendered as a one-line-per-agent table.
+async function runSessions(client: DaemonClient, args: string[], json: boolean): Promise<void> {
+ const { all } = parseSessionsArgs(args);
+ const response = await client.request({ type: "list", all });
+ const data = requireSuccess(response);
+ if (json) {
+ printJson(data);
+ return;
+ }
+
+ const sessions = getSessionSummaries(data);
+ if (!sessions) {
+ printJson(data);
+ return;
+ }
+
+ if (sessions.length === 0) {
+ console.log(all ? "No agents." : "No active agents.");
+ return;
+ }
+
+ console.log(formatSessionsTable(sessions));
+}
+
+function parseSessionsArgs(args: string[]): { all: boolean } {
+ let all = false;
+ for (const arg of args) {
+ if (arg === "-a" || arg === "--all") {
+ all = true;
+ continue;
+ }
+ throw new Error(`Unknown sessions option: ${arg}`);
+ }
+ return { all };
+}
+
async function runCreate(client: DaemonClient, args: string[], json: boolean): Promise<void> {
const sessionArgs = parseSessionArgs(args);
const response = await client.request({
diff --git a/packages/coding-agent/src/cli/daemon-list-format.ts b/packages/coding-agent/src/cli/daemon-list-format.ts
index 4d963b8ef4..aecf9409b7 100644
--- a/packages/coding-agent/src/cli/daemon-list-format.ts
+++ b/packages/coding-agent/src/cli/daemon-list-format.ts
@@ -1,3 +1,4 @@
+import { visibleWidth } from "@earendil-works/pi-tui";
import chalk from "chalk";
import { formatSessionDisplayId } from "../modes/daemon/daemon-session-id.js";
import type { SessionSummary } from "../modes/daemon/daemon-session-list.js";
@@ -68,7 +69,7 @@ function formatListCell(row: ListRow, column: keyof ListRow, value: string): str
}
}
-function formatSessionAge(modified: string | undefined, nowMs: number): string {
+export function formatSessionAge(modified: string | undefined, nowMs: number): string {
if (!modified) {
return "";
}
@@ -103,19 +104,24 @@ function formatModelSelector(model: SessionSummary["model"]): string {
return model ? `${model.provider}/${model.id}` : "";
}
-function formatTable<T extends Record<string, string>>(
+// Column widths are terminal display widths: UTF-16 `.length` under-counts CJK
+// and emoji cells, which drifts the following columns (the agents view measures
+// with `visibleWidth` for the same reason).
+export function formatTable<T extends Record<string, string>>(
columns: Array<keyof T>,
rows: T[],
formatCell?: (row: T, column: keyof T, value: string) => string,
): string {
const widths = columns.map((column) =>
- Math.max(String(column).length, ...rows.map((row) => String(row[column]).length)),
+ Math.max(visibleWidth(String(column)), ...rows.map((row) => visibleWidth(String(row[column])))),
);
- const lines = [columns.map((column, index) => String(column).padEnd(widths[index])).join(" ")];
+ const padCell = (value: string, width: number): string =>
+ value + " ".repeat(Math.max(0, width - visibleWidth(value)));
+ const lines = [columns.map((column, index) => padCell(String(column), widths[index])).join(" ")];
for (const row of rows) {
const line = columns
.map((column, index) => {
- const value = String(row[column]).padEnd(widths[index]);
+ const value = padCell(String(row[column]), widths[index]);
return formatCell ? formatCell(row, column, value) : value;
})
.join(" ");
diff --git a/packages/coding-agent/src/cli/public-command.ts b/packages/coding-agent/src/cli/public-command.ts
index 2d946c9223..68f4bf0ab5 100644
--- a/packages/coding-agent/src/cli/public-command.ts
+++ b/packages/coding-agent/src/cli/public-command.ts
@@ -89,6 +89,8 @@ async function runPublicCommand(args: string[]): Promise<PublicCommandResult> {
return { handled: false, args: args.slice(1), explicitAgentsView: true };
case "list":
return runInternalAgentCommand("list", args.slice(1));
+ case "sessions":
+ return runInternalAgentCommand("sessions", args.slice(1));
case "attach": {
const rest = args.slice(1);
const agent = rest[0];
diff --git a/packages/coding-agent/src/cli/sessions-table-format.ts b/packages/coding-agent/src/cli/sessions-table-format.ts
new file mode 100644
index 0000000000..efa99708cd
--- /dev/null
+++ b/packages/coding-agent/src/cli/sessions-table-format.ts
@@ -0,0 +1,155 @@
+import { truncateToWidth } from "@earendil-works/pi-tui";
+import chalk from "chalk";
+import stripAnsi from "strip-ansi";
+import type { SessionUsageSummary } from "../core/usage.js";
+import { classifySessionRosterStatus, sessionActivityDetail } from "../modes/daemon/agent-roster.js";
+import { formatSessionDisplayId } from "../modes/daemon/daemon-session-id.js";
+import type { SessionSummary } from "../modes/daemon/daemon-session-list.js";
+import { formatSessionAge, formatTable } from "./daemon-list-format.js";
+
+// Display-width cap for free-text cells (names, recaps, error text) so one
+// long line never stretches the row; wide glyphs count as their terminal columns.
+const MAX_CELL_CHARS = 60;
+
+// C0/C1 controls that stripAnsi misses and whitespace compaction cannot remove.
+const CONTROL_CHARACTERS = /[\u0000-\u0008\u000E-\u001F\u007F-\u009F]/g;
+
+type SessionsRow = {
+ name: string;
+ status: string;
+ activity: string;
+ "last heard": string;
+ error: string;
+ usage: string;
+};
+
+/**
+ * One-line-per-agent operator table for `prime-agent sessions`.
+ */
+export function formatSessionsTable(sessions: readonly SessionSummary[], nowMs = Date.now()): string {
+ const rows = sortSessionsForTable(sessions).map((summary) => ({
+ name: truncateCell(sessionNameCell(summary)),
+ status: sessionsStatusLabel(summary),
+ activity: truncateCell(sessionActivityCell(summary)),
+ // lastHeardFromAt is the supervisor's staleness mark, served only when a
+ // worker's roster frames go stale (sweepRosterStaleness); healthy workers
+ // carry no heard-from timestamp, so the cell stays empty rather than
+ // mislabeling the session-file mtime as a heard-from time (the agents view
+ // keys the same label on the mark's presence).
+ "last heard": formatSessionAge(summary.lastHeardFromAt, nowMs),
+ error: truncateCell(sessionErrorCell(summary)),
+ usage: formatUsageCell(summary.usage),
+ }));
+ return formatTable(["name", "status", "activity", "last heard", "error", "usage"], rows, formatSessionsCell);
+}
+
+// Names are user-provided; sanitize them and fall back to the display id when
+// sanitizing leaves nothing (a name of only control characters had no
+// identifier to show).
+function sessionNameCell(summary: SessionSummary): string {
+ return compactCellText(summary.sessionName) || formatSessionDisplayId(summary.id);
+}
+
+// Failures first, then recovering/running, then idle, then everything else.
+function sortSessionsForTable(sessions: readonly SessionSummary[]): SessionSummary[] {
+ return sessions
+ .map((session, index) => ({ session, index }))
+ .sort((left, right) => sessionsSortKey(left.session) - sessionsSortKey(right.session) || left.index - right.index)
+ .map(({ session }) => session);
+}
+
+function sessionsSortKey(summary: SessionSummary): number {
+ if (summary.statusLabel === "failed" || summary.workerState === "failed") return 0;
+ if (summary.statusLabel === "recovering" || summary.workerState === "recovering") return 1;
+ if (summary.statusLabel === "queued" || sessionRosterStatus(summary) === "running") return 2;
+ if (sessionRosterStatus(summary) === "idle") return 3;
+ return 4;
+}
+
+function sessionRosterStatus(summary: SessionSummary): "running" | "idle" | "inactive" {
+ return summary.rosterStatus ?? classifySessionRosterStatus(summary);
+}
+
+// Exceptional labels (queued/recovering/failed) override the plain roster status,
+// mirroring the agents view's status-label precedence.
+function sessionsStatusLabel(summary: SessionSummary): string {
+ return summary.statusLabel ?? sessionRosterStatus(summary);
+}
+
+// The detail wording comes from the shared roster branch table (agent-roster.ts):
+// one table serves this column and the agents view status label, so a state
+// added there shows up on both surfaces. The table's knobs: the heartbeat mark
+// is just "heartbeat" (no countdown; the TUI has a live next-run timer, this
+// table does not) and the idle fallback is empty instead of "needs input"
+// (the status column already says idle). statusLabel and lastHeardFromAt get
+// their own columns here, and roster rows carry an empty sessionActions
+// snapshot (see RosterSessionSummary), so there is no action branch.
+function sessionActivityCell(summary: SessionSummary): string {
+ const detail = sessionActivityDetail(summary, { heartbeatLabel: "heartbeat", idleLabel: "" });
+ const recap = compactCellText(summary.summary);
+ return [detail, recap].filter((part) => part.length > 0).join(" · ");
+}
+
+// The supervisor `list` RPC serves roster rows, which omit summary.diagnostics
+// (see RosterSessionSummary in agent-roster.ts), so this cell can only show the
+// worker failure mark and the model fallback notice the roster actually carries.
+function sessionErrorCell(summary: SessionSummary): string {
+ if (summary.statusLabel === "failed" || summary.workerState === "failed") {
+ return "worker failed";
+ }
+ return compactCellText(summary.modelFallbackMessage);
+}
+
+function formatUsageCell(usage: SessionUsageSummary | undefined): string {
+ if (!usage) {
+ return "";
+ }
+ return `${formatTokenCount(usage.inputTokens)}/${formatTokenCount(usage.outputTokens)} $${usage.cost.toFixed(2)}`;
+}
+
+function formatTokenCount(tokens: number): string {
+ if (tokens < 1000) {
+ return String(tokens);
+ }
+ if (tokens < 1_000_000) {
+ return `${(tokens / 1000).toFixed(1)}k`;
+ }
+ if (tokens < 1_000_000_000) {
+ return `${(tokens / 1_000_000).toFixed(1)}m`;
+ }
+ return `${(tokens / 1_000_000_000).toFixed(1)}b`;
+}
+
+// All free-text cells (names, recaps, error notices) share one sanitizer: strip
+// ANSI escapes and control characters, then compact whitespace, so no cell can
+// clear the screen, move the cursor, restyle later columns, or add table lines.
+function compactCellText(value: string | undefined): string {
+ return (value === undefined ? "" : stripAnsi(value).replace(CONTROL_CHARACTERS, "")).replaceAll(/\s+/g, " ").trim();
+}
+
+function truncateCell(value: string, maxChars = MAX_CELL_CHARS): string {
+ return truncateToWidth(value, maxChars, "…");
+}
+
+function formatSessionsCell(row: SessionsRow, column: keyof SessionsRow, value: string): string {
+ if (column === "status") {
+ switch (row.status) {
+ case "running":
+ case "failed":
+ return chalk.red(value);
+ case "idle":
+ return chalk.blue(value);
+ case "inactive":
+ return chalk.dim(value);
+ case "recovering":
+ case "queued":
+ return chalk.yellow(value);
+ default:
+ return value;
+ }
+ }
+ if (column === "error" && row.error.length > 0) {
+ return chalk.red(value);
+ }
+ return value;
+}
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 10e821a06f..d0602f80ea 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,7 +1,7 @@
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";
+import { rosterAgentIdForSummary, sessionActivityDetail } from "../daemon/agent-roster.js";
import { classifySessionRosterStatus, type SessionSummary } from "../daemon/daemon-session-list.js";
export type AgentsViewSection = "running" | "idle" | "inactive";
@@ -1223,47 +1223,21 @@ export function getSessionStatusLabel(summary: SessionSummary, heartbeat?: Unifi
if (summary.lastHeardFromAt !== undefined) {
return `last heard ${formatAgeLabel(summary.lastHeardFromAt)}`;
}
- // A non-ready worker cannot report fresh runtime flags; its state is the row's story.
- if (summary.workerState !== undefined && summary.workerState !== "ready") {
- return summary.workerState;
- }
- if (summary.isCompacting) {
- return "compacting";
- }
- if (summary.isStreaming) {
- return summary.isRunningTools ? "running tools" : "thinking";
- }
- // These classify the session as Running (isAgentsViewSessionBusy); the label
- // must agree with the section instead of claiming the session needs input.
- if (summary.isRunningTools === true) {
- return "running tools";
- }
- if (summary.isBashRunning === true) {
- return "running bash";
- }
- if (summary.sessionActions.active) {
- return summary.sessionActions.active.label ?? summary.sessionActions.active.kind.replace("_", " ");
- }
- if (summary.sessionActions.queuedCount > 0) {
- return `${summary.sessionActions.queuedCount} queued`;
- }
- if (summary.lifecycle === "archived") {
- return "archived";
- }
- if (summary.hasActiveHeartbeat) {
- const next = heartbeat?.nextRunAt ? Date.parse(heartbeat.nextRunAt) : Number.NaN;
- return Number.isFinite(next)
+ const next = heartbeat?.nextRunAt ? Date.parse(heartbeat.nextRunAt) : Number.NaN;
+ return sessionActivityDetail(summary, {
+ heartbeatLabel: Number.isFinite(next)
? `heartbeat · next ${formatHeartbeatCountdown(next - Date.now())}`
- : "heartbeat active";
- }
- if (summary.runtimeKind === "subagent" && summary.repliedSinceTask) {
- return "replied";
- }
- if (summary.activity === "working") {
- return "classifying";
- }
- if (summary.taskState === "error") {
- return "error";
- }
- return summary.taskState === "completed" ? "completed" : "needs input";
+ : "heartbeat active",
+ idleLabel: "needs input",
+ // The TUI is the only surface whose summaries can carry action labels.
+ sessionAction: (session) => {
+ if (session.sessionActions.active) {
+ return session.sessionActions.active.label ?? session.sessionActions.active.kind.replace("_", " ");
+ }
+ if (session.sessionActions.queuedCount > 0) {
+ return `${session.sessionActions.queuedCount} queued`;
+ }
+ return undefined;
+ },
+ });
}
diff --git a/packages/coding-agent/src/modes/daemon/agent-roster.ts b/packages/coding-agent/src/modes/daemon/agent-roster.ts
index 7365a5c9dd..d50b907227 100644
--- a/packages/coding-agent/src/modes/daemon/agent-roster.ts
+++ b/packages/coding-agent/src/modes/daemon/agent-roster.ts
@@ -124,6 +124,67 @@ export function sessionSummaryFromRosterEntry(entry: WorkerRosterEntry | AgentRo
};
}
+// View-specific labels for the shared activity branch table below.
+export interface SessionActivityOptions {
+ /** Label for a row with an armed heartbeat (the agents view adds a live countdown). */
+ heartbeatLabel: string;
+ /** Fallback when no branch fires (the agents view says "needs input"; the table leaves the cell empty). */
+ idleLabel: string;
+ /**
+ * View-specific branch between the runtime flags and the tail. Only the agents
+ * view serves action labels; roster rows carry an empty sessionActions snapshot,
+ * so the sessions table passes none.
+ */
+ sessionAction?: (summary: SessionSummary) => string | undefined;
+}
+
+// One activity branch table shared by the agents view status label and the
+// sessions table activity column, so a state added here serves both surfaces.
+// Callers keep only what they own: statusLabel and lastHeardFromAt are the
+// agents view's first branches but separate columns in the table.
+export function sessionActivityDetail(summary: SessionSummary, options: SessionActivityOptions): string {
+ // A non-ready worker cannot report fresh runtime flags; its state is the row's story.
+ // The statusLabel guard is inert for the agents view (it returns statusLabel first);
+ // the table keeps the ledger mark in its own status column instead.
+ if (summary.statusLabel === undefined && summary.workerState !== undefined && summary.workerState !== "ready") {
+ return summary.workerState;
+ }
+ if (summary.isCompacting) {
+ return "compacting";
+ }
+ if (summary.isStreaming) {
+ return summary.isRunningTools ? "running tools" : "thinking";
+ }
+ // Tool/bash activity classifies the session as running; the label must agree
+ // with that section instead of claiming the session needs input.
+ if (summary.isRunningTools === true) {
+ return "running tools";
+ }
+ if (summary.isBashRunning === true) {
+ return "running bash";
+ }
+ const sessionAction = options.sessionAction?.(summary);
+ if (sessionAction !== undefined) {
+ return sessionAction;
+ }
+ if (summary.lifecycle === "archived") {
+ return "archived";
+ }
+ if (summary.hasActiveHeartbeat) {
+ return options.heartbeatLabel;
+ }
+ if (summary.runtimeKind === "subagent" && summary.repliedSinceTask) {
+ return "replied";
+ }
+ if (summary.activity === "working") {
+ return "classifying";
+ }
+ if (summary.taskState === "error") {
+ return "error";
+ }
+ return summary.taskState === "completed" ? "completed" : options.idleLabel;
+}
+
export type AgentRosterMutation = { type: "write"; agentId: string } | { type: "delete"; agentId: string };
// Supervisor-owned roster store; write() classifies once and its file index converges seed and worker keys.
diff --git a/packages/coding-agent/test/daemon-command.test.ts b/packages/coding-agent/test/daemon-command.test.ts
index 4d5557299d..6f217660fd 100644
--- a/packages/coding-agent/test/daemon-command.test.ts
+++ b/packages/coding-agent/test/daemon-command.test.ts
@@ -316,6 +316,32 @@ describe("daemon command", () => {
]);
});
+ const ALPHA_ROSTER = [makeSessionSummary("active-1", "session-1", "alpha")];
+ it.each<[string, string[], boolean, boolean, Array<Record<string, unknown>>]>([
+ ["prints the sessions operator table", ["sessions"], false, false, ALPHA_ROSTER],
+ ["passes --all and dumps raw summaries with --json", ["--json", "sessions", "--all"], true, true, ALPHA_ROSTER],
+ ["reports an empty roster without a table", ["sessions"], false, false, []],
+ ])("%s", async (_name, argv, all, json, sessions) => {
+ daemonClientMock.behavior.sessions = sessions;
+ await expect(handleDaemonCommand(["daemon", "--socket", "/tmp/prime-agent.sock", ...argv])).resolves.toBe(true);
+
+ expect(daemonClientMock.instances[0]?.requests).toEqual([{ type: "list", all }]);
+ const logged = String(vi.mocked(console.log).mock.calls[0]?.[0]);
+ if (json) {
+ expect(JSON.parse(logged)).toEqual({ sessions });
+ } else if (sessions.length === 0) {
+ expect(logged).toBe("No active agents.");
+ } else {
+ expect(logged).toContain("alpha");
+ }
+ });
+
+ it("rejects unknown sessions options", async () => {
+ await handleDaemonCommand(["daemon", "--socket", "/tmp/prime-agent.sock", "sessions", "--bogus"]);
+ expect(process.exitCode).toBe(1);
+ expect(consoleErrorMessages.join(" ")).toContain("Unknown sessions option: --bogus");
+ });
+
it("does not leak --goal/--goal-token-budget into daemon startup args", async () => {
// Force canConnectToDaemon to fail so runStart is exercised.
daemonClientMock.behavior.connectFails = true;
diff --git a/packages/coding-agent/test/public-command.test.ts b/packages/coding-agent/test/public-command.test.ts
index e08fe428a4..a87ec4533b 100644
--- a/packages/coding-agent/test/public-command.test.ts
+++ b/packages/coding-agent/test/public-command.test.ts
@@ -134,6 +134,10 @@ describe("public command routing", () => {
["list", "--all", "--json"],
["daemon", "list", "--all", "--json"],
],
+ [
+ ["sessions", "--all", "--json"],
+ ["daemon", "sessions", "--all", "--json"],
+ ],
[
["stop", "worker", "--daemon-socket", "/tmp/custom-daemon.sock"],
["daemon", "kill", "worker", "--daemon-socket", "/tmp/custom-daemon.sock"],
@@ -347,6 +351,11 @@ describe("public command routing", () => {
expect(console.error).toHaveBeenCalledWith(expect.stringContaining("Unknown command: install"));
});
+ it("shows sessions usage in command help", async () => {
+ await expect(handlePublicCommand(["help", "sessions"])).resolves.toMatchObject({ handled: true });
+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining("prime-agent sessions [--all] [--json]"));
+ });
+
it("separates Prime Agent updates from package updates", async () => {
await handlePublicCommand(["update", "--force"]);
await handlePublicCommand(["package", "update"]);
diff --git a/packages/coding-agent/test/sessions-table-format.test.ts b/packages/coding-agent/test/sessions-table-format.test.ts
new file mode 100644
index 0000000000..550d8ff2b5
--- /dev/null
+++ b/packages/coding-agent/test/sessions-table-format.test.ts
@@ -0,0 +1,132 @@
+import stripAnsi from "strip-ansi";
+import { describe, expect, it } from "vitest";
+import { formatSessionsTable } from "../src/cli/sessions-table-format.js";
+import { getSessionStatusLabel } from "../src/modes/agents-view/agents-view-state.js";
+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
+
+const NOW_MS = Date.parse("2026-05-29T12:00:00.000Z");
+const HEADER = ["name", "status", "activity", "last heard", "error", "usage"];
+const STALE_AT = "2026-05-29T11:50:00.000Z";
+const LONG_ID = "019e71ec-e08a-75a9-b573-fc10e9f8380f";
+const SPEND: SessionSummary["usage"] = { inputTokens: 1234, outputTokens: 567, cost: 0.4234 };
+const FLEET_SPEND: SessionSummary["usage"] = { inputTokens: 1_626_400_000, outputTokens: 2_100_000, cost: 382.85 };
+
+// Base summary: a resident idle session last modified two hours before NOW_MS.
+const BASE: SessionSummary = {
+ id: "s",
+ lifecycle: "live",
+ activity: "idle",
+ isSessionActive: false,
+ activeSessionId: "a1",
+ sessionId: "session-s",
+ cwd: "/tmp/project",
+ isStreaming: false,
+ isCompacting: false,
+ attachedClients: 0,
+ messageCount: 2,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
+ modified: "2026-05-29T10:00:00.000Z",
+};
+
+function makeSummary(overrides: Partial<SessionSummary> = {}): SessionSummary {
+ return { ...BASE, ...overrides, isSessionActive: (overrides.activity ?? BASE.activity) === "working" };
+}
+
+function row(name: string, status: string, activity: string, lastHeard = "", error = "", usage = ""): string[] {
+ return [name, status, activity, lastHeard, error, usage];
+}
+
+function expectTable(sessions: SessionSummary[], expectedRows: string[][]): void {
+ const widths = HEADER.map((header, index) => Math.max(header.length, ...expectedRows.map((r) => r[index]!.length)));
+ const pad = (cells: string[]) => cells.map((cell, i) => cell.padEnd(widths[i]!)).join(" ");
+ const lines = [pad(HEADER), ...expectedRows.map(pad)];
+ expect(stripAnsi(formatSessionsTable(sessions, NOW_MS)).split("\n")).toEqual(lines);
+}
+
+const UNSORTED = [
+ makeSummary({ sessionName: "plain-saved", activeSessionId: undefined, rosterStatus: "inactive" }),
+ makeSummary({ sessionName: "worker", activity: "working", isStreaming: true }),
+ // The diagnostics entry is never served by the supervisor list RPC; the row must keep showing the worker mark.
+ makeSummary({ sessionName: "crashed", workerState: "failed", diagnostics: [{ type: "error", message: "x" }] }),
+ makeSummary({ sessionName: "sleeper", taskState: "completed" }),
+ makeSummary({ sessionName: "restarting", workerState: "recovering" }),
+];
+const EXPECTED_SORT = [
+ row("crashed", "idle", "failed", "", "worker failed"),
+ row("restarting", "idle", "recovering"),
+ row("worker", "running", "thinking"),
+ row("sleeper", "idle", "completed"),
+ row("plain-saved", "inactive", ""),
+];
+
+describe("formatSessionsTable", () => {
+ it.each<[string, Partial<SessionSummary> | null, string[]]>([
+ ["empty roster renders the header only", null, []],
+ ["thinking detail", { activity: "working", isStreaming: true }, row("s", "running", "thinking")],
+ ["running bash", { activity: "working", isBashRunning: true }, row("s", "running", "running bash")],
+ ["compacting", { activity: "working", isCompacting: true }, row("s", "running", "compacting")],
+ ["completed verdict", { taskState: "completed" }, row("s", "idle", "completed")],
+ ["saved status", { activeSessionId: undefined, rosterStatus: "inactive" }, row("s", "inactive", "")],
+ ["queued label", { activity: "working", statusLabel: "queued" }, row("s", "queued", "classifying")],
+ ["recovering label", { statusLabel: "recovering" }, row("s", "recovering", "")],
+ ["failed label", { statusLabel: "failed" }, row("s", "failed", "", "", "worker failed")],
+ [
+ "sanitized model notice",
+ { modelFallbackMessage: "boom\u0007\u001B[31m!\u001B[39m" },
+ row("s", "idle", "", "", "boom!"),
+ ],
+ ["staleness", { activity: "working", lastHeardFromAt: STALE_AT }, row("s", "running", "classifying", "10m")],
+ ["usage compact", { usage: SPEND }, row("s", "idle", "", "", "", "1.2k/567 $0.42")],
+ [
+ "sanitizes and truncates the recap appended to the activity detail",
+ { activity: "working", isStreaming: true, isRunningTools: true, summary: `\u0007${"a".repeat(100)}` },
+ ["s", "running", `running tools · ${"a".repeat(43)}…`, "", "", ""],
+ ],
+ ["usage fleet scale", { usage: FLEET_SPEND }, row("s", "idle", "", "", "", "1.6b/2.1m $382.85")],
+ ["archived rows", { lifecycle: "archived", rosterStatus: "inactive" }, row("s", "inactive", "archived")],
+ ["display id fallback", { id: LONG_ID, sessionName: undefined }, row("fc10e9f8380f", "idle", "")],
+ ["newline in name", { sessionName: "sneaky\nagent" }, row("sneaky agent", "idle", "")],
+ ["ansi in name", { sessionName: "\u001B[31mansi\u001B[39m agent" }, row("ansi agent", "idle", "")],
+ ["control chars in name", { sessionName: "beep\u0007 agent" }, row("beep agent", "idle", "")],
+ ["blank name", { sessionName: "\u0007", id: LONG_ID }, row("fc10e9f8380f", "idle", "")],
+ ["long name cap", { sessionName: "n".repeat(200) }, row(`${"n".repeat(59)}…`, "idle", "")],
+ ["heartbeat", { hasActiveHeartbeat: true }, row("s", "idle", "heartbeat")],
+ ["ignores queued actions", { sessionActions: { ...BASE.sessionActions, queuedCount: 2 } }, row("s", "idle", "")],
+ ["starting worker", { activity: "working", workerState: "starting" }, row("s", "running", "starting")],
+ ["stopping worker", { workerState: "stopping" }, row("s", "idle", "stopping")],
+ ["replied subagent", { runtimeKind: "subagent", repliedSinceTask: true }, row("s", "idle", "replied")],
+ ])("%s", (_name, overrides, expected) => {
+ expectTable(overrides ? [makeSummary(overrides)] : [], overrides ? [expected] : []);
+ });
+
+ it("sorts failures first, then recovering workers, then running, then idle, then the rest", () => {
+ expectTable(UNSORTED, EXPECTED_SORT);
+ });
+
+ // One branch table (agent-roster.ts sessionActivityDetail) serves both surfaces; a re-added local branch splits the wording and fails here.
+ it.each<[string, Partial<SessionSummary>]>([
+ ["thinking", { activity: "working", isStreaming: true }],
+ ["running tools", { activity: "working", isStreaming: true, isRunningTools: true }],
+ ["running bash", { activity: "working", isBashRunning: true }],
+ ["compacting", { activity: "working", isCompacting: true }],
+ ["starting", { activity: "working", workerState: "starting" }],
+ ["archived", { lifecycle: "archived", rosterStatus: "inactive" }],
+ ["replied", { runtimeKind: "subagent", repliedSinceTask: true }],
+ ["classifying", { activity: "working" }],
+ ["error", { taskState: "error" }],
+ ["completed", { taskState: "completed" }],
+ ])("%s agrees with the table's activity wording", (expected, overrides) => {
+ expect(getSessionStatusLabel(makeSummary(overrides))).toBe(expected);
+ });
+
+ it("measures wide-glyph cells by display width", () => {
+ const sessions = [
+ makeSummary({ sessionName: "中文" }),
+ makeSummary({ sessionName: "hello", summary: "🚀".repeat(40) }),
+ ];
+ const lines = stripAnsi(formatSessionsTable(sessions)).split("\n");
+ // UTF-16 padding would misalign the CJK name; the recap cap counts display columns, pair-safe.
+ expect(lines[1]!.startsWith("中文 idle")).toBe(true);
+ expect(lines[2]!.includes(`${"🚀".repeat(29)}…`)).toBe(true);
+ });
+});