Skip to content

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

Rust

feat: unified agents and resume view (#541)

Sebastian Müller2f218e151309
diff --git a/README.md b/README.md
index b9057724a7..78ce8961f7 100644
--- a/README.md
+++ b/README.md
@@ -67,8 +67,8 @@ Public releases are currently installed from versioned release artifacts through
Other useful commands:
```bash
-prime-agent agents # Open the agents view
-prime-agent --resume [path|id] # Browse or resume a previous session
+prime-agent agents # Search running, idle, and inactive sessions
+prime-agent --resume <path|id> # Resume a specific session
prime-agent doctor [--fix] # Inspect or repair background services
prime-agent update [--force] # Update Prime Agent
prime-agent shutdown [--force] # Stop every agent, worker, and background service
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 63e92d3677..2eff5466d2 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -2,7 +2,13 @@
## [Unreleased]
+- Added starting a new session directly from the agents view with `ctrl+n`.
+- Added queueing a reply as a follow-up with `alt+enter` in the agents-view reply composer; plain Enter now steers a streaming agent.
+- Added session-owned slash commands (`/compact`, `/refine`, `/goal`, `/autonomous`) with autocomplete to the agents-view reply composer; other built-in commands are rejected with guidance instead of being sent as prompt text.
+- Added `/name` and `/kill` view commands to the agents view reply composer, acting on its armed target; the search bar stays pure search.
- Added `/new` support for an optional stable session name and initial prompt.
+- Removed the `/resume` command and bare `--resume`; browse sessions with left-arrow from a chat (daemon view), and use `--resume <session-id|path>` for direct resumes.
+- Fixed `prime-agent agents` opening a new chat when running with a process-local session.
- Changed collapsed edit and IPython tool calls to show compact per-file line-change summaries while keeping full diffs available when expanded.
- Changed bare `/effort` to open a selector for the current model's supported reasoning levels.
- Changed session search to rank exact name and first-message matches before prefix, substring, and stricter transcript fuzzy matches.
@@ -15,7 +21,9 @@
- Removed the bundled orchestration heartbeat skill from the model system prompt.
- Fixed feature hints crowding queued messages and side questions by placing them below the recap and hiding them while messages are queued ([ENG-4741](https://linear.app/primeintellect/issue/ENG-4741/recap-queuefollow-upmessage-hint-looks-cluttered)).
- Fixed `/btw` truncating long answers by rendering side questions in the scrollable transcript.
+- Changed recognized slash commands to retain accent coloring after submission in live, replayed, and queued TUI surfaces while preserving Markdown arguments.
- Unified prompt, steering, follow-up, and session-command scheduling under session-owned admission with durable queue state and coordinated update/restart checkpoints.
+- Unified Agents View and session resume into one searchable Running/Idle/Inactive session view with live heartbeat badges.
- Changed selection cursors from `→` to `›` across model selectors, scoped-models, and the theme default for consistency with tree and user-message selectors.
- Changed the queued follow-up hint connector from `↳` to `╰─` to match the tool-execution continuation connector.
- Changed `/context` tree connectors from `├ `/`└ ` to `├─ `/`└─ ` to match the tree selector and session picker.
diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.md
index 23d28bf3fe..8b5f95c16d 100644
--- a/packages/coding-agent/README.md
+++ b/packages/coding-agent/README.md
@@ -150,7 +150,7 @@ Type `/` in the editor to trigger commands. [Extensions](#extensions) can regist
| `/effort` | Set reasoning/thinking level |
| `/scoped-models` | Enable/disable models for Ctrl+P cycling |
| `/settings` | Thinking level, theme, message delivery, transport |
-| `/resume` | Pick from previous sessions |
+| `/resume` | Open the searchable session view |
| `/new`, `/clear` | Start a new session |
| `/name <name>` | Set session display name |
| `/session` | Show session info (file, ID, messages) |
@@ -206,7 +206,7 @@ Sessions are stored as JSONL files with a tree structure. Each entry has an `id`
### Management
-Sessions auto-save as flat JSONL files under `~/.prime/agent/sessions/`. Each session header records its working directory, which the session picker uses for project-scoped views.
+Sessions auto-save as flat JSONL files under `~/.prime/agent/sessions/`. Each session header records its working directory, which the searchable session view uses to identify and open saved sessions.
```bash
prime-agent -c # Continue most recent session
@@ -495,7 +495,7 @@ Run `prime-agent help` for the command list and `prime-agent help <command>` for
### Agent Commands
```bash
-prime-agent agents # Open the agents view
+prime-agent agents # Search running, idle, and inactive sessions
prime-agent list [--all] # List active or saved agents
prime-agent attach <agent> # Attach the interactive UI
prime-agent stop <agent> # Stop one agent
@@ -563,7 +563,7 @@ Use `prime-agent model list [search]` to list available models.
| Option | Description |
|--------|-------------|
| `-c`, `--continue` | Continue most recent session |
-| `-r`, `--resume [path\|id]` | Browse and select session, or resume a specific session file or partial UUID |
+| `-r`, `--resume [path\|id]` | Open the searchable session view, or resume a specific session file or partial UUID |
| `--fork <path\|id>` | Fork specific session file or partial UUID into a new session |
| `--session-dir <dir>` | Custom session storage directory |
| `--no-session` | Ephemeral mode (don't save) |
diff --git a/packages/coding-agent/docs/extensions.md b/packages/coding-agent/docs/extensions.md
index 0ea5626666..5cc38a5086 100644
--- a/packages/coding-agent/docs/extensions.md
+++ b/packages/coding-agent/docs/extensions.md
@@ -2066,7 +2066,6 @@ Available functions:
- `rawKeyHint(key, description)` - Format a raw key string
Use namespaced keybinding ids:
-- Coding-agent ids use the `app.*` namespace, for example `app.tools.expand`, `app.editor.external`, `app.session.rename`
- Shared TUI ids use the `tui.*` namespace, for example `tui.select.confirm`, `tui.select.cancel`, `tui.input.tab`
For the exhaustive list of keybinding ids and defaults, see [keybindings.md](keybindings.md). `keybindings.json` uses those same namespaced ids.
diff --git a/packages/coding-agent/docs/keybindings.md b/packages/coding-agent/docs/keybindings.md
index b94b1e1633..5433e2f7a3 100644
--- a/packages/coding-agent/docs/keybindings.md
+++ b/packages/coding-agent/docs/keybindings.md
@@ -107,12 +107,6 @@ Modifier combinations: `ctrl+shift+x`, `alt+ctrl+x`, `ctrl+shift+alt+x`, `ctrl+1
| `app.session.tree` | *(none)* | Open session tree navigator (`/tree`) |
| `app.session.fork` | *(none)* | Fork current session (`/fork`) |
| `app.session.resume` | *(none)* | Open session resume picker (`/resume`) |
-| `app.session.togglePath` | `ctrl+p` | Toggle path display |
-| `app.session.toggleSort` | `ctrl+s` | Toggle sort mode |
-| `app.session.toggleNamedFilter` | `ctrl+n` | Toggle named-only filter |
-| `app.session.rename` | `ctrl+r` | Rename session |
-| `app.session.delete` | `ctrl+d` | Delete session |
-| `app.session.deleteNoninvasive` | `ctrl+backspace` | Delete session when query is empty |
### Models and Thinking
diff --git a/packages/coding-agent/src/cli/command-registry.ts b/packages/coding-agent/src/cli/command-registry.ts
index 9fcf4e813a..76b794ffab 100644
--- a/packages/coding-agent/src/cli/command-registry.ts
+++ b/packages/coding-agent/src/cli/command-registry.ts
@@ -18,7 +18,7 @@ export const COMMAND_SPECS: readonly CommandSpec[] = [
{
path: ["agents"],
usage: "agents",
- summary: "Open the agents view",
+ summary: "Search and open sessions",
},
{
path: ["list"],
@@ -161,7 +161,7 @@ export const REMOVED_COMMAND_NAMES = new Set(["app", "daemon", "install", "manag
const TOP_LEVEL_OPTIONS = [
["-p, --print", "Print a response and exit"],
["-c, --continue", "Continue the previous session"],
- ["-r, --resume [path|id]", "Resume a session, or browse when omitted"],
+ ["-r, --resume <path|id>", "Resume a session"],
["--model <pattern>", "Choose a model"],
["--thinking <level>", "Set the reasoning level"],
["--offline", "Disable startup network operations"],
diff --git a/packages/coding-agent/src/cli/session-picker.ts b/packages/coding-agent/src/cli/session-picker.ts
deleted file mode 100644
index 201f9eb756..0000000000
--- a/packages/coding-agent/src/cli/session-picker.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * TUI session selector for --resume flag
- */
-
-import { ProcessTerminal, setKeybindings, TUI } from "@earendil-works/pi-tui";
-import { VERSION } from "../config.js";
-import { KeybindingsManager } from "../core/keybindings.js";
-import { type SessionInfo, type SessionListCallbacks, SessionManager } from "../core/session-manager.js";
-import { SessionPickerScreen } from "../modes/interactive/components/session-picker-screen.js";
-import { SessionSelectorComponent } from "../modes/interactive/components/session-selector.js";
-import { BrandSplashHeader } from "../modes/interactive/interactive-mode.js";
-
-type SessionsLoader = (callbacks?: SessionListCallbacks) => Promise<SessionInfo[]>;
-type AllSessionsLoader = (callbacks?: SessionListCallbacks, sessionDir?: string) => Promise<SessionInfo[]>;
-
-/** Show TUI session selector and return selected session path or null if cancelled */
-export async function selectSession(
- currentSessionsLoader: SessionsLoader,
- allSessionsLoader: AllSessionsLoader,
- options?: { cwd?: string; modelId?: string; sessionDir?: string },
-): Promise<string | null> {
- return new Promise((resolve) => {
- const ui = new TUI(new ProcessTerminal());
- const keybindings = KeybindingsManager.create();
- setKeybindings(keybindings);
- let resolved = false;
-
- const selector = new SessionSelectorComponent(
- (callbacks) =>
- currentSessionsLoader({
- onProgress: callbacks?.onProgress,
- onSession: callbacks?.onSession,
- }),
- (callbacks) =>
- allSessionsLoader(
- {
- onProgress: callbacks?.onProgress,
- onSession: callbacks?.onSession,
- },
- options?.sessionDir,
- ),
- (path: string) => {
- if (!resolved) {
- resolved = true;
- ui.stop();
- resolve(path);
- }
- },
- () => {
- if (!resolved) {
- resolved = true;
- ui.stop();
- resolve(null);
- }
- },
- () => {
- ui.stop();
- process.exit(0);
- },
- () => ui.requestRender(),
- {
- renameSession: async (sessionPath, nextName) => {
- const name = (nextName ?? "").trim();
- if (!name) return;
- SessionManager.open(sessionPath, options?.sessionDir).appendSessionInfo(name);
- },
- showRenameHint: true,
- keybindings,
- frameless: true,
- },
- );
-
- const splash = new BrandSplashHeader(
- VERSION,
- () => options?.modelId,
- () => options?.cwd ?? process.cwd(),
- );
- ui.addChild(new SessionPickerScreen(ui, splash, selector));
- ui.setFocus(selector);
- ui.start();
- });
-}
diff --git a/packages/coding-agent/src/core/agent-session-runtime.ts b/packages/coding-agent/src/core/agent-session-runtime.ts
index dbbb929335..c51108380e 100644
--- a/packages/coding-agent/src/core/agent-session-runtime.ts
+++ b/packages/coding-agent/src/core/agent-session-runtime.ts
@@ -749,7 +749,7 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
* Create the initial runtime from a runtime factory and initial session target.
*
* The same factory is stored on the returned AgentSessionRuntime and reused for
- * later /new, /resume, /fork, and import flows.
+ * later /new, resume, /fork, and import flows.
*/
export async function createAgentSessionRuntime(
createRuntime: CreateAgentSessionRuntimeFactory,
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index 0da3e2f11a..dc7bde0a9a 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -183,6 +183,7 @@ import {
isSessionSlashCommandMessage,
} from "./messages.js";
import type { ModelRegistry } from "./model-registry.js";
+import { throwIfPromptAdmissionCancelled, waitForPromptAdmission } from "./prompt-admission.js";
import { expandPromptTemplate, type PromptTemplate } from "./prompt-templates.js";
import {
type AutoRefineReason,
@@ -241,6 +242,7 @@ import { getPythonSkillRuntimeInfo, type Skill } from "./skills.js";
import {
parseRefineCommandOptions,
parseSessionSlashCommand,
+ parseSlashCommand,
type SessionSlashCommand,
type SlashCommandInfo,
} from "./slash-commands.js";
@@ -568,38 +570,6 @@ function oncePreflight(
};
}
-function throwIfPromptAdmissionCancelled(signal: AbortSignal | undefined): void {
- if (signal?.aborted) throw new Error("Prompt admission was cancelled.");
-}
-
-export function waitForPromptAdmission<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
- if (!signal) return promise;
- if (signal.aborted) {
- void promise.catch(() => {});
- throwIfPromptAdmissionCancelled(signal);
- }
- return new Promise<T>((resolve, reject) => {
- const onAbort = () => {
- cleanup();
- reject(new Error("Prompt admission was cancelled."));
- };
- const cleanup = () => signal.removeEventListener("abort", onAbort);
- signal.addEventListener("abort", onAbort, { once: true });
- // Close the listener-registration race before observing the awaited work.
- if (signal.aborted) return onAbort();
- promise.then(
- (value) => {
- cleanup();
- resolve(value);
- },
- (error: unknown) => {
- cleanup();
- reject(error);
- },
- );
- });
-}
-
interface PreparedCommandInput {
kind: "command";
text: string;
@@ -1020,7 +990,6 @@ export class AgentSession {
private _turnAdmissionTail: Promise<void> = Promise.resolve();
private _turnAdmissionOwner: symbol | undefined;
private readonly _turnAdmissionContext = new AsyncLocalStorage<symbol>();
- private _legacyQueuedWorkPause: { release(): void } | undefined;
private _pumpingSessionInput = false;
private _activeSessionInput:
| {
@@ -1037,7 +1006,6 @@ export class AgentSession {
private _directPromptSectionCount = 0;
/** One-shot waiters resolved when a dispatched message reaches message_start. */
private _directDispatchObservers = new Set<{ message: AgentMessage; resolve: () => void }>();
- private _steeringStopPending = false;
/** Messages queued to be included with the next user prompt as context ("asides"). */
private _pendingNextTurnMessages: CustomMessage[] = [];
@@ -1550,7 +1518,6 @@ export class AgentSession {
this._removeActivePreparingPrompts(isGoalContext);
this._steeringMessages = this._steeringMessages.filter((input) => !isGoalContext(input));
this._followUpMessages = this._followUpMessages.filter((input) => !isGoalContext(input));
- this._syncSteeringStopPending();
this._emitQueueUpdate();
}
@@ -1946,14 +1913,14 @@ export class AgentSession {
return true;
}
- private _syncSteeringStopPending(): void {
+ private get _steeringStopPending(): boolean {
const activeSteeringHandoff =
this._activeSessionInput?.kind === "prompt" &&
this._activeSessionInput.lane === "steer" &&
this._activeSessionInput.phase === "preparing" &&
!this._activeSessionInput.cancelled &&
this._activeSessionInput.items.length > 0;
- this._steeringStopPending = this._steeringMessages.length > 0 || activeSteeringHandoff;
+ return this._steeringMessages.length > 0 || activeSteeringHandoff;
}
private _shouldStopBeforeTurn(): boolean {
@@ -2561,7 +2528,6 @@ export class AgentSession {
input.kind === "prompt" && queuedMessageSet.has(input.message);
this._steeringMessages = this._steeringMessages.filter((input) => !isQueuedContinuation(input));
this._followUpMessages = this._followUpMessages.filter((input) => !isQueuedContinuation(input));
- this._syncSteeringStopPending();
this._emitQueueUpdate();
if (options.restoreAutonomousState) {
for (const queuedMessage of queuedMessages) {
@@ -3719,7 +3685,6 @@ export class AgentSession {
}
this._steeringMessages = [];
this._followUpMessages = [];
- this._syncSteeringStopPending();
this.agent.clearAllQueues();
this._extensionRunner.invalidate(
"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().",
@@ -4691,11 +4656,13 @@ export class AgentSession {
}
private _executeExtensionCommand(text: string): Promise<void> | undefined {
- const spaceIndex = text.indexOf(" ");
- const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
+ const parsed = parseSlashCommand(text);
+ if (!parsed) return undefined;
+ const commandName = parsed.name;
+ const args = parsed.args;
+
const command = this._extensionRunner.getCommand(commandName);
if (!command) return undefined;
- const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
const context = this._extensionRunner.createCommandContext();
return Promise.resolve()
.then(() => command.handler(args, context))
@@ -4719,9 +4686,10 @@ export class AgentSession {
private _expandSkillCommand(text: string): string {
if (!text.startsWith("/skill:")) return text;
- const spaceIndex = text.indexOf(" ");
- const skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);
- const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1).trim();
+ const parsed = parseSlashCommand(text);
+ if (!parsed?.name.startsWith("skill:")) return text;
+ const skillName = parsed.name.slice("skill:".length);
+ const args = parsed.args;
const skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);
if (!skill) return text; // Unknown skill, pass through
@@ -4989,7 +4957,6 @@ export class AgentSession {
}
queue.push(input);
this._sessionInputArrivalEpoch++;
- this._syncSteeringStopPending();
this._emitQueueUpdate();
if (
!options.restore &&
@@ -5063,7 +5030,6 @@ export class AgentSession {
if (first.kind === "command") {
queue.shift();
this._activeSessionInput = { kind: "command", lane, item: first, phase: "executing" };
- this._syncSteeringStopPending();
this._notifySessionInputCheckpointChange();
this._emitQueueUpdate();
try {
@@ -5073,7 +5039,6 @@ export class AgentSession {
this._rejectAgentMessage(first.agentMessageId, this._asError(error));
} finally {
this._activeSessionInput = undefined;
- this._syncSteeringStopPending();
this._notifySessionInputCheckpointChange();
this._emitQueueUpdate();
}
@@ -5086,7 +5051,6 @@ export class AgentSession {
}
if (epoch !== this._sessionInputPumpEpoch) {
queue.unshift(...prompts);
- this._syncSteeringStopPending();
return;
}
this._activeSessionInput = {
@@ -5095,7 +5059,6 @@ export class AgentSession {
items: prompts,
phase: "preparing",
};
- this._syncSteeringStopPending();
this._notifySessionInputCheckpointChange();
this._emitQueueUpdate();
try {
@@ -5116,7 +5079,6 @@ export class AgentSession {
// Clear ownership before emitting so the requeued items are not
// double-counted as both owned and queued.
this._activeSessionInput = undefined;
- this._syncSteeringStopPending();
this._emitQueueUpdate();
}
blocked = true;
@@ -5132,7 +5094,6 @@ export class AgentSession {
this._surfaceSessionInputError(error);
} finally {
this._activeSessionInput = undefined;
- this._syncSteeringStopPending();
this._notifySessionInputCheckpointChange();
}
} finally {
@@ -5141,7 +5102,6 @@ export class AgentSession {
}
} finally {
this._pumpingSessionInput = false;
- this._syncSteeringStopPending();
if (!blocked && epoch === this._sessionInputPumpEpoch && this.pendingMessageCount > 0) {
this._scheduleSessionInputPump();
}
@@ -5186,17 +5146,28 @@ export class AgentSession {
}
private _isDeferredSessionInputError(error: unknown, epoch: number): boolean {
- return error instanceof DeferredSessionInputError || this._isSessionInputHandoffDeferred(epoch);
+ if (error instanceof DeferredSessionInputError) return true;
+ if (epoch !== this._sessionInputPumpEpoch) return true;
+ if (this._isBusyForSessionInput("pump")) {
+ // Requeue, but surface the error: this was not a deliberate deferral.
+ this._surfaceSessionInputError(error);
+ return true;
+ }
+ return false;
}
private _surfaceSessionInputError(error: unknown): void {
const normalized = this._asError(error);
- this._extensionRunner.emitError({
- extensionPath: "<session-input>",
- event: "session_input",
- error: normalized.message,
- stack: normalized.stack,
- });
+ try {
+ this._extensionRunner.emitError({
+ extensionPath: "<session-input>",
+ event: "session_input",
+ error: normalized.message,
+ stack: normalized.stack,
+ });
+ } catch {
+ // Best-effort: a throwing error listener must not break the pump's requeue path.
+ }
}
private async _startPreparedPromptItems(
@@ -5272,7 +5243,6 @@ export class AgentSession {
}
if (this._activeSessionInput?.kind === "prompt") {
this._activeSessionInput.phase = "handedOff";
- this._syncSteeringStopPending();
this._notifySessionInputCheckpointChange();
this._emitQueueUpdate();
}
@@ -5377,8 +5347,7 @@ export class AgentSession {
* Throw an error if the text is an extension command.
*/
private _throwIfExtensionCommand(text: string): void {
- const spaceIndex = text.indexOf(" ");
- const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
+ const commandName = parseSlashCommand(text)?.name ?? "";
const command = this._extensionRunner.getCommand(commandName);
if (command) {
@@ -5539,7 +5508,6 @@ export class AgentSession {
this._rejectQueuedAgentMessageDeliveries(new Error("Queued agent message was cleared before delivery."));
this._steeringMessages = [];
this._followUpMessages = [];
- this._syncSteeringStopPending();
this.agent.clearAllQueues();
this._emitQueueUpdate();
return { steering, followUp };
@@ -5596,7 +5564,6 @@ export class AgentSession {
this._followUpMessages = this._followUpMessages.filter(
(message) => !followUpSet.has(message as PreparedPromptInput),
);
- this._syncSteeringStopPending();
for (const message of [...steering, ...followUp]) {
this._rejectAgentMessage(
message.agentMessageId,
@@ -5847,23 +5814,10 @@ export class AgentSession {
}
}
- /** Compatibility wrapper for callers migrating to owned pause leases. */
- pauseQueuedWork(): boolean {
- if (this._legacyQueuedWorkPause) return false;
- this._legacyQueuedWorkPause = this.acquireQueuedWorkPause();
- return true;
- }
-
- /** Compatibility wrapper that releases only the pause acquired by pauseQueuedWork(). */
+ /** Resume the scheduler after requestAbort/abortForUpdateRestart suspended it; owned pause leases are unaffected. */
resumeQueuedWork(): boolean {
this._sessionInputPumpSuspended = false;
- const pause = this._legacyQueuedWorkPause;
- if (pause) {
- this._legacyQueuedWorkPause = undefined;
- pause.release();
- } else {
- this._scheduleSessionInputPump();
- }
+ this._scheduleSessionInputPump();
return this.pendingMessageCount > 0;
}
@@ -5952,7 +5906,6 @@ export class AgentSession {
const removed = new Set<QueuedSessionInput>([...removedSteering, ...removedFollowUp]);
this._steeringMessages = this._steeringMessages.filter((message) => !removed.has(message));
this._followUpMessages = this._followUpMessages.filter((message) => !removed.has(message));
- this._syncSteeringStopPending();
for (const message of removed) {
this._rejectAgentMessage(
message.agentMessageId,
@@ -8388,7 +8341,10 @@ export class AgentSession {
// cancelled runs have nothing useful to show, so dispose them now. retainFinished…
// disposes the child itself when it declines, so only dispose here otherwise.
if (status === "done") {
- await flushAgentTraceUpload(runtime.session.sessionManager).catch(() => undefined);
+ // Trace sharing is best-effort telemetry for every completed run, retained
+ // or not. Rate-limit retries can take minutes, so it must not delay the
+ // model-facing rlm.run result.
+ void flushAgentTraceUpload(runtime.session.sessionManager).catch(() => undefined);
if (!options.parentSession.retainFinishedRlmChildSession(options.id, runtime.session)) {
runtime.session.dispose();
}
diff --git a/packages/coding-agent/src/core/keybindings.ts b/packages/coding-agent/src/core/keybindings.ts
index 588bd3a49c..85ad00ead3 100644
--- a/packages/coding-agent/src/core/keybindings.ts
+++ b/packages/coding-agent/src/core/keybindings.ts
@@ -24,7 +24,6 @@ export interface AppKeybindings {
"app.subagents.focus": true;
"app.heartbeats.open": true;
"app.heartbeats.openSelected": true;
- "app.session.toggleNamedFilter": true;
"app.editor.external": true;
"app.prompt.stash": true;
"app.message.followUp": true;
@@ -38,6 +37,7 @@ export interface AppKeybindings {
"app.agents.open": true;
"app.modal.back": true;
"app.agents.reply": true;
+ "app.agents.new": true;
"app.agents.delete": true;
"app.agents.program": true;
"app.agents.rename": true;
@@ -45,11 +45,6 @@ export interface AppKeybindings {
"app.tree.unfoldOrDown": true;
"app.tree.editLabel": true;
"app.tree.toggleLabelTimestamp": true;
- "app.session.togglePath": true;
- "app.session.toggleSort": true;
- "app.session.rename": true;
- "app.session.delete": true;
- "app.session.deleteNoninvasive": true;
"app.models.save": true;
"app.models.enableAll": true;
"app.models.clearAll": true;
@@ -101,10 +96,6 @@ export const KEYBINDINGS = {
defaultKeys: "right",
description: "Open selected heartbeat",
},
- "app.session.toggleNamedFilter": {
- defaultKeys: "ctrl+n",
- description: "Toggle named session filter",
- },
"app.editor.external": {
defaultKeys: "ctrl+g",
description: "Open external editor",
@@ -129,10 +120,11 @@ export const KEYBINDINGS = {
"app.session.tree": { defaultKeys: [], description: "Open session tree" },
"app.session.fork": { defaultKeys: [], description: "Fork current session" },
"app.session.resume": { defaultKeys: [], description: "Resume a session" },
- "app.agents.back": { defaultKeys: "left", description: "Return to agents view" },
+ "app.agents.back": { defaultKeys: "left", description: "Return to session view" },
"app.agents.open": { defaultKeys: "right", description: "Open chat view for selected agent" },
"app.modal.back": { defaultKeys: "left", description: "Go back / close the current dialog" },
"app.agents.reply": { defaultKeys: "space", description: "Reply to selected agent" },
+ "app.agents.new": { defaultKeys: "ctrl+n", description: "Start a new session from the agents view" },
"app.agents.delete": { defaultKeys: "ctrl+x", description: "Stop or delete selected agent" },
"app.agents.program": { defaultKeys: "ctrl+o", description: "Show the program that spawned subagents" },
"app.agents.rename": { defaultKeys: "ctrl+r", description: "Rename selected agent session" },
@@ -152,26 +144,6 @@ export const KEYBINDINGS = {
defaultKeys: "shift+t",
description: "Toggle tree label timestamps",
},
- "app.session.togglePath": {
- defaultKeys: "ctrl+p",
- description: "Toggle session path display",
- },
- "app.session.toggleSort": {
- defaultKeys: "ctrl+s",
- description: "Toggle session sort mode",
- },
- "app.session.rename": {
- defaultKeys: "ctrl+r",
- description: "Rename session",
- },
- "app.session.delete": {
- defaultKeys: "ctrl+d",
- description: "Delete session",
- },
- "app.session.deleteNoninvasive": {
- defaultKeys: "ctrl+backspace",
- description: "Delete session when query is empty",
- },
"app.models.save": {
defaultKeys: "ctrl+s",
description: "Save model selection",
@@ -267,7 +239,6 @@ const KEYBINDING_NAME_MIGRATIONS = {
expandTools: "app.tools.expand",
toggleThinking: "app.thinking.toggle",
focusSubagents: "app.subagents.focus",
- toggleSessionNamedFilter: "app.session.toggleNamedFilter",
externalEditor: "app.editor.external",
followUp: "app.message.followUp",
dequeue: "app.message.dequeue",
@@ -278,6 +249,7 @@ const KEYBINDING_NAME_MIGRATIONS = {
resume: "app.session.resume",
agentsBack: "app.agents.back",
agentsReply: "app.agents.reply",
+ agentsNew: "app.agents.new",
agentsDelete: "app.agents.delete",
agentsProgram: "app.agents.program",
agentsRename: "app.agents.rename",
@@ -285,11 +257,6 @@ const KEYBINDING_NAME_MIGRATIONS = {
treeUnfoldOrDown: "app.tree.unfoldOrDown",
treeEditLabel: "app.tree.editLabel",
treeToggleLabelTimestamp: "app.tree.toggleLabelTimestamp",
- toggleSessionPath: "app.session.togglePath",
- toggleSessionSort: "app.session.toggleSort",
- renameSession: "app.session.rename",
- deleteSession: "app.session.delete",
- deleteSessionNoninvasive: "app.session.deleteNoninvasive",
} as const satisfies Record<string, Keybinding>;
function isRecord(value: unknown): value is Record<string, unknown> {
diff --git a/packages/coding-agent/src/core/prompt-admission.ts b/packages/coding-agent/src/core/prompt-admission.ts
new file mode 100644
index 0000000000..7b7908ba78
--- /dev/null
+++ b/packages/coding-agent/src/core/prompt-admission.ts
@@ -0,0 +1,42 @@
+export class PromptAdmissionCancelledError extends Error {
+ constructor() {
+ super("Prompt admission was cancelled.");
+ this.name = "PromptAdmissionCancelledError";
+ }
+}
+
+export function throwIfPromptAdmissionCancelled(signal: AbortSignal | undefined): void {
+ if (signal?.aborted) throw new PromptAdmissionCancelledError();
+}
+
+/**
+ * Await `promise` unless `signal` aborts first. Always observes the supplied
+ * work's rejection so a cancelled admission never leaks an unhandled rejection.
+ */
+export function waitForPromptAdmission<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
+ if (!signal) return promise;
+ if (signal.aborted) {
+ void promise.catch(() => {});
+ return Promise.reject(new PromptAdmissionCancelledError());
+ }
+ return new Promise<T>((resolve, reject) => {
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
+ const onAbort = () => {
+ cleanup();
+ reject(new PromptAdmissionCancelledError());
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ // Close the listener-registration race before observing the awaited work.
+ if (signal.aborted) return onAbort();
+ promise.then(
+ (value) => {
+ cleanup();
+ resolve(value);
+ },
+ (error: unknown) => {
+ cleanup();
+ reject(error);
+ },
+ );
+ });
+}
diff --git a/packages/coding-agent/src/core/prompt-templates.ts b/packages/coding-agent/src/core/prompt-templates.ts
index 8a4400e9ed..1c69ea38aa 100644
--- a/packages/coding-agent/src/core/prompt-templates.ts
+++ b/packages/coding-agent/src/core/prompt-templates.ts
@@ -3,6 +3,7 @@ import { homedir } from "os";
import { basename, dirname, isAbsolute, join, resolve, sep } from "path";
import { CONFIG_DIR_NAME } from "../config.js";
import { parseFrontmatter } from "../utils/frontmatter.js";
+import { parseSlashCommand } from "./slash-commands.js";
import { createSyntheticSourceInfo, type SourceInfo } from "./source-info.js";
/**
@@ -37,7 +38,7 @@ export function parseCommandArgs(argsString: string): string[] {
}
} else if (char === '"' || char === "'") {
inQuote = char;
- } else if (char === " " || char === "\t") {
+ } else if (/[\t\p{Zs}]/u.test(char)) {
if (current) {
args.push(current);
current = "";
@@ -283,9 +284,10 @@ export function loadPromptTemplates(options: LoadPromptTemplatesOptions): Prompt
export function expandPromptTemplate(text: string, templates: PromptTemplate[]): string {
if (!text.startsWith("/")) return text;
- const spaceIndex = text.indexOf(" ");
- const templateName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
- const argsString = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
+ const parsed = parseSlashCommand(text);
+ if (!parsed) return text;
+ const templateName = parsed.name;
+ const argsString = parsed.args;
const template = templates.find((t) => t.name === templateName);
if (template) {
diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.ts
index 641a09c4b2..ba23f1fdcb 100644
--- a/packages/coding-agent/src/core/session-manager.ts
+++ b/packages/coding-agent/src/core/session-manager.ts
@@ -2067,8 +2067,8 @@ export class SessionManager {
}
/** Create an in-memory session (no file persistence) */
- static inMemory(cwd: string = process.cwd()): SessionManager {
- return new SessionManager(cwd, "", undefined, false);
+ static inMemory(cwd: string = process.cwd(), sessionDir = ""): SessionManager {
+ return new SessionManager(cwd, sessionDir, undefined, false);
}
/**
diff --git a/packages/coding-agent/src/core/slash-commands.ts b/packages/coding-agent/src/core/slash-commands.ts
index 21504d4b54..8722e59e06 100644
--- a/packages/coding-agent/src/core/slash-commands.ts
+++ b/packages/coding-agent/src/core/slash-commands.ts
@@ -164,7 +164,6 @@ const CANONICAL_BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [
takesArgument: true,
},
{ name: "heartbeats", description: "View and manage all user and agent heartbeats" },
- { name: "resume", description: "Resume a different session" },
{ name: "reload", description: "Reload keybindings, extensions, skills, prompts, and themes" },
{
name: "fullscreen",
diff --git a/packages/coding-agent/src/index.ts b/packages/coding-agent/src/index.ts
index 72b26f7abc..7a25e8e862 100644
--- a/packages/coding-agent/src/index.ts
+++ b/packages/coding-agent/src/index.ts
@@ -363,7 +363,6 @@ export {
type RenderDiffOptions,
rawKeyHint,
renderDiff,
- SessionSelectorComponent,
type SettingsCallbacks,
type SettingsConfig,
SettingsSelectorComponent,
diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.ts
index 803dd660f9..94097c6fa2 100644
--- a/packages/coding-agent/src/main.ts
+++ b/packages/coding-agent/src/main.ts
@@ -27,7 +27,6 @@ import { buildInitialMessage } from "./cli/initial-message.js";
import { listModels } from "./cli/list-models.js";
import { installOwnedSessionRecoveryTracking, isOwnedSessionWorkerProcess } from "./cli/owned-session-worker.js";
import { handlePublicCommand } from "./cli/public-command.js";
-import { selectSession } from "./cli/session-picker.js";
import {
looksLikeSessionPath,
resolveSessionPath,
@@ -162,6 +161,10 @@ export function shouldRejectNonInteractiveAttach(attachAgent: string | undefined
return attachAgent !== undefined && appMode !== "interactive";
}
+export function shouldRejectBareResume(resume: true | string | undefined): boolean {
+ return resume === true;
+}
+
function resolveAppMode(parsed: Args, stdinIsTTY: boolean): AppMode {
if (parsed.mode === "daemon") {
return "daemon";
@@ -244,14 +247,12 @@ export interface AgentsViewStartupDecision {
export function shouldOpenAgentsViewForDaemonInteractive(options: AgentsViewStartupDecision): boolean {
return (
options.useDaemonInteractive &&
- // `prime-agent` opens a new chat by default; the agents view is reached via
+ // `prime-agent` opens a new chat by default; the unified agents view is reached via
// left-arrow from a session or requested explicitly (`agents`).
!!options.explicitAgentsView &&
- // Onboarding lives in InteractiveMode, so a first run must take the
- // direct session path; the agents view would otherwise require creating
- // an agent before the onboarding splash ever renders.
!options.needsOnboarding &&
- !options.resume &&
+ // A resume selector resolves and opens its target directly.
+ typeof options.resume !== "string" &&
!options.continue &&
!options.fork
);
@@ -267,7 +268,7 @@ export interface DaemonInteractiveSessionManagerDecision {
export function shouldUseEphemeralSessionManagerForDaemonInteractive(
options: DaemonInteractiveSessionManagerDecision,
): boolean {
- return !options.hasActiveDaemonSession && !options.resume && !options.continue && !options.fork;
+ return !options.hasActiveDaemonSession && options.resume === undefined && !options.continue && !options.fork;
}
export interface DaemonActiveSessionLookupDecision {
@@ -439,7 +440,6 @@ export async function createSessionManager(
parsed: Args,
cwd: string,
sessionDir: string | undefined,
- settingsManager: SettingsManager,
): Promise<SessionManager> {
const explicitCwdOverride = parsed.cwd ? cwd : undefined;
@@ -479,24 +479,6 @@ export async function createSessionManager(
}
}
- if (parsed.resume) {
- initTheme(settingsManager.getTheme(), true);
- try {
- const selectedPath = await selectSession(
- (callbacks) => SessionManager.list(cwd, sessionDir, callbacks),
- SessionManager.listAll,
- { cwd, sessionDir },
- );
- if (!selectedPath) {
- console.log(chalk.dim("No session selected"));
- process.exit(0);
- }
- return SessionManager.open(selectedPath, sessionDir, explicitCwdOverride);
- } finally {
- stopThemeWatcher();
- }
- }
-
if (parsed.continue) {
return SessionManager.continueRecent(cwd, sessionDir);
}
@@ -1081,6 +1063,12 @@ export async function main(args: string[], options?: MainOptions) {
console.error(chalk.red("Error: attach requires an interactive terminal"));
process.exit(1);
}
+ if (shouldRejectBareResume(parsed.resume)) {
+ console.error(
+ chalk.red("Error: --resume requires a session id or path; browse sessions with left-arrow from a chat"),
+ );
+ process.exit(1);
+ }
setLogContext({ mode: appMode });
const shouldTakeOverStdout = appMode !== "interactive";
if (shouldTakeOverStdout) {
@@ -1211,7 +1199,7 @@ export async function main(args: string[], options?: MainOptions) {
sessionManager = SessionManager.inMemory(cwd);
} else {
try {
- sessionManager = await createSessionManager(parsed, cwd, sessionDir, startupSettingsManager);
+ sessionManager = await createSessionManager(parsed, cwd, sessionDir);
} catch (error) {
if (!(error instanceof SessionSelectorError)) {
throw error;
@@ -1221,7 +1209,7 @@ export async function main(args: string[], options?: MainOptions) {
? ` Did you mean '${error.suggestion}'?`
: "";
console.error(chalk.red(`Error: ${error.message}.${suggestion}`));
- console.error(chalk.dim(`Run "${APP_NAME} --resume" to browse sessions.`));
+ console.error(chalk.dim(`Open ${APP_NAME} and press left-arrow to browse sessions.`));
process.exit(1);
}
}
@@ -1367,7 +1355,7 @@ export async function main(args: string[], options?: MainOptions) {
services,
sessionManager,
});
- const launchAgentsView = async (includeInitialPrompts: boolean) => {
+ const launchAgentsView = async (initialSession?: SessionSummary) => {
await runAgentsViewMode({
socketPath: daemonSocketPath,
config: defaultSessionConfig,
@@ -1396,7 +1384,7 @@ export async function main(args: string[], options?: MainOptions) {
modelFallbackMessage: startupModel.modelFallbackMessage,
promptStashStore,
startupModelId: startupModel.model?.id,
- ...(includeInitialPrompts ? { initialMessage, initialImages, initialMessages: parsed.messages } : {}),
+ initialSession,
verbose: parsed.verbose,
});
};
@@ -1417,7 +1405,7 @@ export async function main(args: string[], options?: MainOptions) {
daemonReady = (await awaitDaemonReady(daemonReady)).ready;
await preloadCodeHighlighter();
printTimings();
- await launchAgentsView(true);
+ await launchAgentsView();
return;
}
@@ -1465,11 +1453,15 @@ export async function main(args: string[], options?: MainOptions) {
await preloadCodeHighlighter();
printTimings();
- await interactiveMode.run();
+ const interactiveResult = await interactiveMode.run();
if (parsed.noSession) {
return;
}
- await launchAgentsView(false);
+ await launchAgentsView({
+ ...summary,
+ ...interactiveResult.source,
+ id: interactiveResult.source.activeSessionId ?? summary.id,
+ });
return;
}
if (useDaemonClient) {
@@ -1604,6 +1596,9 @@ export async function main(args: string[], options?: MainOptions) {
printTimings();
await runRpcMode(runtime);
} else if (appMode === "interactive") {
+ if (explicitAgentsView) {
+ console.error(chalk.yellow("Warning: the agents view needs the daemon; opening a normal chat instead"));
+ }
if (scopedModels.length > 0 && (parsed.verbose || !settingsManager.getQuietStartup())) {
const modelList = scopedModels
.map((sm) => {
diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
index 5db722615f..041405aee9 100644
--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
@@ -41,6 +41,7 @@ import {
isUnknownDaemonCommandError,
} from "../daemon/daemon-protocol.js";
import type { SessionSummary } from "../daemon/daemon-session-list.js";
+import { listDaemonHeartbeats } from "../daemon/heartbeat-catalog.js";
import {
deleteDaemonSavedSession,
listDaemonSavedSessions,
@@ -529,25 +530,7 @@ export class DaemonAgentConnection implements AgentConnection {
}
async listHeartbeats(): Promise<AgentConnectionHeartbeat[]> {
- const hasCapability = this.client.supportsServerCapability("heartbeat_catalog");
- if (!hasCapability && this.client.hello?.protocol.version !== 3) {
- return [];
- }
- try {
- const command = {
- type: "heartbeats_list",
- ...(this.options.ownedSession ? { activeSessionId: this.activeSessionId } : {}),
- } as const;
- const data = hasCapability
- ? await this.requestData<{ heartbeats: AgentConnectionHeartbeat[] }>(command)
- : await this.requestLegacyData<{ heartbeats: AgentConnectionHeartbeat[] }>(command);
- return data.heartbeats;
- } catch (error) {
- if (isUnknownDaemonCommandError(error, "heartbeats_list")) {
- return [];
- }
- throw error;
- }
+ return listDaemonHeartbeats(this.client, this.options.ownedSession ? this.activeSessionId : undefined);
}
async manageHeartbeat(
@@ -1256,6 +1239,7 @@ export class DaemonAgentConnection implements AgentConnection {
}
return {
getMessages: () => connection.getMessages(),
+ getCommands: () => connection.getCommands(),
subscribe: (listener) => connection.subscribe(listener),
getToolDefinition: (name) => connection.getToolDefinition(name),
close: () => connection.dispose(),
diff --git a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
index 75726e8c2b..46ffc1d5bb 100644
--- a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
@@ -176,14 +176,13 @@ export class InProcessAgentConnection implements AgentConnection {
scope: AgentConnectionSavedSessionScope,
callbacks?: AgentConnectionSessionListCallbacks,
): Promise<AgentConnectionSavedSessionInfo[]> {
+ // In-memory managers hold "" for "no explicit session dir"; pass undefined so
+ // list()/listAll() fall back to the default directories instead of scanning "".
+ const sessionDir = this.session.sessionManager.getSessionDir() || undefined;
if (scope === "current") {
- return SessionManager.list(
- this.session.sessionManager.getCwd(),
- this.session.sessionManager.getSessionDir(),
- callbacks,
- );
+ return SessionManager.list(this.session.sessionManager.getCwd(), sessionDir, callbacks);
}
- return SessionManager.listAll(callbacks, this.session.sessionManager.getSessionDir());
+ return SessionManager.listAll(callbacks, sessionDir);
}
async getQueue(): Promise<AgentConnectionQueueState> {
@@ -555,6 +554,7 @@ export class InProcessAgentConnection implements AgentConnection {
const unsubscribes = new Set<() => void>();
return {
getMessages: async () => child.messages,
+ getCommands: async () => createAgentConnectionCommands(child),
subscribe: (listener) => {
const unsubscribe = child.subscribe((event) => void listener({ type: "session_event", event }));
unsubscribes.add(unsubscribe);
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index 9d27a1320a..dda657cffd 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -739,6 +739,7 @@ export interface AgentConnection {
export interface AgentConnectionSessionWatcher {
getMessages(): Promise<AgentMessage[]>;
+ getCommands(): Promise<AgentConnectionSlashCommand[]>;
subscribe(listener: AgentConnectionEventListener): () => void;
getToolDefinition(name: string): Promise<AgentConnectionToolDefinition | undefined>;
close(): Promise<void>;
diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-commands.ts b/packages/coding-agent/src/modes/agents-view/agents-view-commands.ts
deleted file mode 100644
index 75ecd5a4a0..0000000000
--- a/packages/coding-agent/src/modes/agents-view/agents-view-commands.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * Slash command support for the agents view.
- *
- * The agents view is session-less, so only a small whitelist of global
- * built-in commands runs here. Other built-in names are swallowed with a
- * pointer to open an agent instead of spawning a junk agent, while unknown
- * "/..." text passes through untouched — prompt templates, skills, and
- * extension commands are expanded by the daemon-side session.
- */
-
-import {
- BUILTIN_SLASH_COMMANDS,
- type BuiltinSlashCommand,
- isBuiltinSlashCommandName,
- type ParsedSlashCommand,
- resolveBuiltinSlashCommandName,
-} from "../../core/slash-commands.js";
-
-const AGENTS_VIEW_COMMAND_NAMES = ["login", "logout", "model", "mcp", "resume", "quit"] as const;
-
-export type AgentsViewCommandName = (typeof AGENTS_VIEW_COMMAND_NAMES)[number];
-
-/** Descriptions that differ from the in-session built-in. */
-const AGENTS_VIEW_COMMAND_DESCRIPTIONS: Partial<Record<AgentsViewCommandName, string>> = {
- model: "Select the model for new agents",
-};
-
-export const AGENTS_VIEW_SLASH_COMMANDS: readonly BuiltinSlashCommand[] = AGENTS_VIEW_COMMAND_NAMES.map((name) => {
- const builtin = BUILTIN_SLASH_COMMANDS.find((command) => command.name === name);
- if (!builtin) {
- throw new Error(`Agents view command '/${name}' is not a built-in slash command`);
- }
- return { ...builtin, description: AGENTS_VIEW_COMMAND_DESCRIPTIONS[name] ?? builtin.description };
-});
-
-export { type ParsedSlashCommand, parseSlashCommand } from "../../core/slash-commands.js";
-
-export type AgentsViewCommandKind =
- /** Whitelisted built-in that runs directly in the agents view. */
- | "agents-view"
- /** Built-in that only works inside an open agent session. */
- | "session-only"
- /** Not a built-in; passes through to the daemon session untouched. */
- | "unknown";
-
-export function classifyAgentsViewCommand(name: string): AgentsViewCommandKind {
- const canonicalName = resolveBuiltinSlashCommandName(name);
- if ((AGENTS_VIEW_COMMAND_NAMES as readonly string[]).includes(canonicalName)) {
- return "agents-view";
- }
- if (isBuiltinSlashCommandName(name)) {
- return "session-only";
- }
- return "unknown";
-}
-
-export function resolveAgentsViewCommand(command: ParsedSlashCommand): ParsedSlashCommand {
- return { ...command, name: resolveBuiltinSlashCommandName(command.name) };
-}
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 86bba27ff2..857ffac4b2 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
@@ -1,8 +1,7 @@
import { existsSync } from "node:fs";
import { resolve as resolvePath } from "node:path";
-import type { Api, ImageContent, Model } from "@earendil-works/pi-ai";
-import type { AutocompleteItem, OverlayHandle, SlashCommand } from "@earendil-works/pi-tui";
import {
+ type AutocompleteProvider,
CombinedAutocompleteProvider,
type Component,
clippedFullscreenDockHeight,
@@ -17,43 +16,36 @@ import {
import { APP_TITLE, appendRotatingLog, getAgentDir, getClientErrorLogPath, VERSION } from "../../config.js";
import type { AgentSessionRuntimeConfig } from "../../core/agent-session-config.js";
import { KeybindingsManager } from "../../core/keybindings.js";
-import type { ModelCatalogSnapshot, ModelRegistry } from "../../core/model-registry.js";
-import { findExactModelReferenceMatch } from "../../core/model-resolver.js";
-import { resolvePrimeInferencePostLoginModelAction } from "../../core/prime-inference-model-selection.js";
import { SessionManager } from "../../core/session-manager.js";
+import {
+ BUILTIN_SLASH_COMMANDS,
+ isBuiltinSlashCommandName,
+ isSessionSlashCommandName,
+ parseSlashCommand,
+ resolveBuiltinSlashCommandName,
+} from "../../core/slash-commands.js";
+import { canonicalizePath } from "../../utils/paths.js";
import { ensureTool } from "../../utils/tools-manager.js";
import { DaemonAgentConnection } from "../agent-connection/daemon-agent-connection.js";
-import type { AgentConnectionSavedSessionInfo } from "../agent-connection/types.js";
+import type { AgentConnectionHeartbeat, AgentConnectionSavedSessionInfo } from "../agent-connection/types.js";
import { DaemonClient, getDaemonSocketCloseReason } from "../daemon/daemon-client.js";
import {
+ collectDaemonClientEnv,
type DaemonClosingReason,
type DaemonCommand,
type DaemonResponse,
isUnknownDaemonCommandError,
} from "../daemon/daemon-protocol.js";
-import {
- resolveAttachModelFallbackMessage,
- type SessionSummary,
- summaryForInactiveSession,
-} from "../daemon/daemon-session-list.js";
+import { resolveAttachModelFallbackMessage, type SessionSummary } from "../daemon/daemon-session-list.js";
+import { listDaemonHeartbeats } from "../daemon/heartbeat-catalog.js";
import {
type DaemonSavedSessionCatalogContext,
deleteDaemonSavedSession,
listDaemonSavedSessions,
renameDaemonSavedSession,
} from "../daemon/saved-session-catalog.js";
-import {
- type AuthenticationResult,
- getAnthropicSubscriptionAuthWarning,
- ProviderAuthFlows,
-} from "../interactive/auth-flows.js";
-import { showFullPaneOverlay } from "../interactive/components/centered-overlay.js";
-import { ConfigurationMenuComponent, type ConfigurationMenuTab } from "../interactive/components/configuration-menu.js";
import { CustomEditor } from "../interactive/components/custom-editor.js";
import { keyText } from "../interactive/components/keybinding-hints.js";
-import type { AuthSelectorProvider } from "../interactive/components/oauth-selector.js";
-import { SessionPickerScreen } from "../interactive/components/session-picker-screen.js";
-import { type SessionListCallbacks, SessionSelectorComponent } from "../interactive/components/session-selector.js";
import { BrandSplashHeader, InteractiveMode } from "../interactive/interactive-mode.js";
import type { InteractiveModeUiServices } from "../interactive/interactive-mode-services.js";
import { ClientPromptStashStore } from "../interactive/prompt-stash-state.js";
@@ -66,7 +58,6 @@ import {
theme,
} from "../interactive/theme/theme.js";
import { WORKING_ICON_INTERVAL_MS, workingIconFrame } from "../interactive/theme/working-icon.js";
-import { getModelArgumentCompletions } from "../model-autocomplete.js";
import {
formatPackageUpdateNotice,
formatTmuxWarningNotice,
@@ -74,61 +65,57 @@ import {
gatherStartupNotices,
type StartupNotices,
} from "../shared/startup-notices.js";
-import {
- AGENTS_VIEW_SLASH_COMMANDS,
- type AgentsViewCommandName,
- classifyAgentsViewCommand,
- type ParsedSlashCommand,
- parseSlashCommand,
- resolveAgentsViewCommand,
-} from "./agents-view-commands.js";
import {
type AgentsViewRow,
type AgentsViewSection,
type AgentsViewSelectionKey,
buildAgentsViewRows,
+ filterUnifiedSessions,
+ formatHeartbeatBadge,
getAgentsViewSelectionKey,
getAgentsViewSummaryIdentity as getSummaryIdentity,
- resolveAgentsViewSelectionIndex,
+ reconcileUnifiedSessions,
+ resolveAgentsViewSelectionState,
sectionTitle,
shouldShowAgentsViewSession,
+ summaryForUnifiedRecord,
+ type UnifiedSessionRecord,
} from "./agents-view-state.js";
+import { matchesSearchText } from "./session-view-search.js";
const POLL_INTERVAL_MS = 1000;
+const HEARTBEAT_POLL_INTERVAL_MS = 15000;
const RECONNECT_TIMEOUT_MS = 120000;
const RECONNECT_RETRY_MS = 1000;
const EXIT_HINT_DURATION_MS = 2000;
const DELETE_CONFIRM_DURATION_MS = 2000;
const STATUS_MESSAGE_DURATION_MS = 4500;
-const SESSION_NAME_MAX_LENGTH = 80;
-const DEFAULT_PROMPT_PLACEHOLDER = "Describe a task for a new session";
+const SEARCH_PROMPT_PLACEHOLDER = "Search sessions";
const REPLY_PROMPT_FALLBACK_PLACEHOLDER = "Write a reply to this agent";
+const RESUME_PROMPT_PLACEHOLDER = "Write a prompt to resume this session";
const COMPLETED_ROW_ICON = "✓";
const NEEDS_INPUT_ROW_ICON = "●";
-const HEARTBEAT_ROW_ICON = "♥";
const SELECTED_ROW_MARKER = "\0agents-view-selected-row\0";
// Tags a spawn-code line so finalize can wrap the whole row in a panel
// background, visually segmenting the program from the agent rows.
const CODE_ROW_MARKER = "\0agents-view-code-row\0";
export interface AgentsViewModeOptions {
- socketPath: string;
+ socketPath?: string;
config: AgentSessionRuntimeConfig;
uiServices: InteractiveModeUiServices;
createUiServicesForSession?: (summary: SessionSummary) => Promise<InteractiveModeUiServices>;
migratedProviders?: string[];
modelFallbackMessage?: string;
startupModelId?: string;
- initialMessage?: string;
- initialImages?: ImageContent[];
- initialMessages?: string[];
verbose?: boolean;
recoverDaemon?: () => Promise<void>;
reconnectTimeoutMs?: number;
promptStashStore?: ClientPromptStashStore;
+ initialSession?: SessionSummary;
}
-type AgentsViewRunResult =
+export type AgentsViewRunResult =
| { type: "exit" }
| {
type: "open";
@@ -138,18 +125,23 @@ type AgentsViewRunResult =
// opened subagent, from the root agent down to its immediate parent.
subagentAncestorSessionIds?: string[];
};
-type AgentsViewPersistentState = {
+export type AgentsViewPersistentState = {
selectedRowIdentity?: string;
+ backSession?: SessionSummary;
selectedSessionKey?: AgentsViewSelectionKey;
// Ancestor chain to re-expand on return to a subagent. Kept by sessionId, not
// row identity, so it survives a parent's active→persisted identity flip.
pendingExpandedAncestorSessionIds?: string[];
statusMessage?: string;
- initialPromptsSent?: boolean;
// 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.
startupNotices?: StartupNotices;
startupNoticesPromise?: Promise<StartupNotices>;
+ query?: string;
+ savedSessions?: AgentConnectionSavedSessionInfo[];
+ lastSuccessfulSavedSessions?: AgentConnectionSavedSessionInfo[];
+ savedCatalogGeneration?: number;
+ heartbeats?: AgentConnectionHeartbeat[];
};
type PromptCommand = Extract<DaemonCommand, { type: "prompt" }>;
@@ -190,34 +182,20 @@ export function createAgentsViewResumeConfig(
export function createAgentsViewListCommand(): Extract<DaemonCommand, { type: "list" }> {
// Omitting `all` returns daemon-resident sessions only; on-disk ones come back
- // via /resume.
+ // through the view's saved-session catalog.
return { type: "list" };
}
-export function resolveAgentsViewResumeSummary(
- sessionPath: string,
- savedSessions: readonly AgentConnectionSavedSessionInfo[],
- visibleSummaries: readonly SessionSummary[],
-): SessionSummary | undefined {
- const activeSummary = resolveAgentsViewActiveSummaryForPath(sessionPath, visibleSummaries);
- if (activeSummary) {
- return activeSummary;
- }
- const selectedPath = resolvePath(sessionPath);
- const savedSession = savedSessions.find((session) => resolvePath(session.path) === selectedPath);
- return savedSession ? summaryForInactiveSession(savedSession) : undefined;
-}
-
export function resolveAgentsViewActiveSummaryForPath(
sessionPath: string,
summaries: readonly SessionSummary[],
): SessionSummary | undefined {
- const selectedPath = resolvePath(sessionPath);
+ const selectedPath = resolvePath(canonicalizePath(sessionPath));
return summaries.find(
(summary) =>
summary.activeSessionId !== undefined &&
summary.sessionFile !== undefined &&
- resolvePath(summary.sessionFile) === selectedPath,
+ resolvePath(canonicalizePath(summary.sessionFile)) === selectedPath,
);
}
@@ -228,23 +206,6 @@ export function formatAgentsViewStatusLine(text: string): string {
return text.replace(/\s+/g, " ").trim();
}
-export async function getAgentsViewModelArgumentCompletions(
- prefix: string,
- modelRegistry: Pick<ModelRegistry, "refreshModelCatalog">,
-): Promise<AutocompleteItem[] | null> {
- const catalog = await modelRegistry.refreshModelCatalog();
- return getModelArgumentCompletions(prefix, catalog.models);
-}
-
-export function syncAgentsViewModelMenuAfterAuth(
- menu: Pick<ConfigurationMenuComponent, "refreshAuthentication" | "updateModels">,
- currentModel: Model<Api> | undefined,
- catalog: ModelCatalogSnapshot,
-): void {
- menu.refreshAuthentication();
- menu.updateModels(currentModel, catalog.models, new Set(catalog.configuredProviders));
-}
-
export function shouldReconnectAgentsViewDaemon(reason: DaemonClosingReason | undefined): boolean {
return reason !== "shutdown";
}
@@ -279,7 +240,9 @@ async function openAgentsViewSession(
options: AgentsViewModeOptions,
summary: SessionSummary,
): Promise<OpenedAgentsViewSession> {
- let client = await connectAgentsViewDaemonClient(options.socketPath);
+ const socketPath = options.socketPath;
+ if (!socketPath) throw new Error("Agents view daemon socket is not configured");
+ let client = await connectAgentsViewDaemonClient(socketPath);
if (summary.activeSessionId) {
try {
const connection = await DaemonAgentConnection.attach(client, summary.activeSessionId, {
@@ -293,7 +256,7 @@ async function openAgentsViewSession(
if (!summary.sessionFile || !isUnknownActiveSessionError(error)) {
throw error;
}
- client = await connectAgentsViewDaemonClient(options.socketPath);
+ client = await connectAgentsViewDaemonClient(socketPath);
}
}
@@ -302,27 +265,47 @@ async function openAgentsViewSession(
throw new Error("Cannot open agent without an active runtime or saved session file");
}
- const { overrideCwd, notice } = resolveAgentsViewOpenCwd(summary, options.config.cwd);
try {
- const response = await client.request({
- type: "create",
- config: createAgentsViewResumeConfig(options.config, overrideCwd),
- sessionPath: summary.sessionFile,
- });
- const createdSummary = expectSessionSummary(requireDaemonData(response));
- const activeSessionId = getRequiredActiveSessionId(createdSummary);
- const connection = await DaemonAgentConnection.attach(client, activeSessionId, {
+ const resumed = await resumeSavedAgentsViewSession(client, options.config, summary);
+ const connection = await DaemonAgentConnection.attach(client, resumed.activeSessionId, {
closeClientOnDispose: true,
recoverDaemon: options.recoverDaemon,
reconnectTimeoutMs: options.reconnectTimeoutMs,
});
- return { connection, summary: createdSummary, cwdFallbackNotice: notice };
+ return { connection, summary: resumed.summary, cwdFallbackNotice: resumed.cwdFallbackNotice };
} catch (error) {
client.close();
throw error;
}
}
+/**
+ * Resume a saved session file into the daemon and return the live summary.
+ * The daemon's create-with-sessionPath is idempotent for this client: an
+ * already-resident session is reused instead of resumed twice.
+ */
+async function resumeSavedAgentsViewSession(
+ client: DaemonClient,
+ config: AgentSessionRuntimeConfig,
+ summary: SessionSummary,
+): Promise<{ summary: SessionSummary; activeSessionId: string; cwdFallbackNotice?: string }> {
+ if (!summary.sessionFile) {
+ throw new Error("Cannot resume a session without a saved session file");
+ }
+ const { overrideCwd, notice } = resolveAgentsViewOpenCwd(summary, config.cwd);
+ const response = await client.request({
+ type: "create",
+ config: createAgentsViewResumeConfig(config, overrideCwd),
+ sessionPath: summary.sessionFile,
+ });
+ const createdSummary = expectSessionSummary(requireDaemonData(response));
+ return {
+ summary: createdSummary,
+ activeSessionId: getRequiredActiveSessionId(createdSummary),
+ cwdFallbackNotice: notice,
+ };
+}
+
async function connectAgentsViewDaemonClient(socketPath: string): Promise<DaemonClient> {
const client = new DaemonClient(socketPath);
try {
@@ -346,7 +329,14 @@ function isUnknownActiveSessionError(error: unknown): boolean {
}
export async function runAgentsViewMode(options: AgentsViewModeOptions): Promise<void> {
- const persistentState: AgentsViewPersistentState = {};
+ const initialSession = options.initialSession;
+ const persistentState: AgentsViewPersistentState = initialSession
+ ? {
+ selectedRowIdentity: getSummaryIdentity(initialSession),
+ selectedSessionKey: getAgentsViewSelectionKey(initialSession),
+ backSession: initialSession,
+ }
+ : {};
const promptStashStore = options.promptStashStore ?? new ClientPromptStashStore();
while (true) {
@@ -370,6 +360,7 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): Promise
let opened: OpenedAgentsViewSession | undefined;
try {
opened = await openAgentsViewSession(options, result.summary);
+ persistentState.backSession = opened.summary;
if (opened.cwdFallbackNotice) {
persistentState.statusMessage = opened.cwdFallbackNotice;
}
@@ -396,7 +387,26 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): Promise
: undefined,
});
try {
- await interactiveMode.run();
+ const interactiveResult = await interactiveMode.run();
+ const source = interactiveResult.source;
+ // A subagent selection was recorded before the chat opened; keep it so
+ // the view reselects the subagent instead of its root session.
+ if (!result.subagent) {
+ persistentState.selectedRowIdentity = source.sessionFile
+ ? `file:${resolvePath(canonicalizePath(source.sessionFile))}`
+ : source.activeSessionId
+ ? `active:${source.activeSessionId}`
+ : `session:${source.sessionId}`;
+ persistentState.selectedSessionKey = {
+ sessionId: source.sessionId,
+ activeSessionId: source.activeSessionId,
+ };
+ }
+ persistentState.backSession = {
+ ...opened.summary,
+ ...source,
+ id: source.activeSessionId ?? opened.summary.id,
+ };
} catch (error) {
// The session opened fine and then threw while running; label it as a
// runtime crash so it isn't mixed in with true open failures.
@@ -416,7 +426,97 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): Promise
}
}
-class AgentsViewMode implements Component, Focusable {
+const AGENTS_VIEW_COMMAND_NAMES = ["name", "kill"] as const;
+export type AgentsViewCommandName = (typeof AGENTS_VIEW_COMMAND_NAMES)[number];
+const AGENTS_VIEW_COMMAND_NAME_SET: ReadonlySet<string> = new Set(AGENTS_VIEW_COMMAND_NAMES);
+
+export interface AgentsViewCommand {
+ name: AgentsViewCommandName;
+ args: string;
+}
+
+/** Row-targeted commands the armed composer maps onto existing RPCs. */
+export function parseAgentsViewCommand(text: string): AgentsViewCommand | undefined {
+ const parsed = parseSlashCommand(text);
+ if (!parsed) return undefined;
+ const name = resolveBuiltinSlashCommandName(parsed.name);
+ if (!AGENTS_VIEW_COMMAND_NAME_SET.has(name)) return undefined;
+ return { name: name as AgentsViewCommandName, args: parsed.args };
+}
+
+/**
+ * Reject recognized built-ins that are neither session-owned nor view
+ * commands, so they are never sent to the model as plain prompt text.
+ */
+export function getReplyComposerCommandRejection(text: string): string | undefined {
+ const parsed = parseSlashCommand(text);
+ if (!parsed) return undefined;
+ const name = resolveBuiltinSlashCommandName(parsed.name);
+ if (isSessionSlashCommandName(name)) return undefined;
+ if (AGENTS_VIEW_COMMAND_NAME_SET.has(name)) return undefined;
+ if (!isBuiltinSlashCommandName(parsed.name)) return undefined;
+ return `/${parsed.name} is not available here; open the session to run it`;
+}
+
+const AGENTS_VIEW_COMMAND_DESCRIPTIONS: Record<AgentsViewCommandName, { description: string; argumentHint?: string }> =
+ {
+ name: { description: "Set session display name", argumentHint: "<name>" },
+ kill: { description: "Stop this agent's runtime (session stays resumable)" },
+ };
+
+function agentsViewSlashCommands(): {
+ name: string;
+ aliases?: readonly string[];
+ description: string;
+ argumentHint?: string;
+ takesArgument?: boolean;
+}[] {
+ return AGENTS_VIEW_COMMAND_NAMES.map((name) => {
+ const builtin = BUILTIN_SLASH_COMMANDS.find((command) => command.name === name);
+ const display = AGENTS_VIEW_COMMAND_DESCRIPTIONS[name];
+ return {
+ name,
+ aliases: builtin?.aliases,
+ description: display.description,
+ argumentHint: display.argumentHint ?? builtin?.argumentHint,
+ takesArgument: name === "name" ? true : builtin?.takesArgument,
+ };
+ });
+}
+
+/** Autocomplete for the reply composer: session-owned plus view commands. */
+export function createReplyComposerAutocompleteProvider(cwd: string, fdPath?: string): AutocompleteProvider {
+ const sessionCommands = BUILTIN_SLASH_COMMANDS.filter((command) => isSessionSlashCommandName(command.name)).map(
+ (command) => ({
+ name: command.name,
+ aliases: command.aliases,
+ description: command.description,
+ argumentHint: command.argumentHint,
+ takesArgument: command.takesArgument,
+ }),
+ );
+ return new CombinedAutocompleteProvider([...sessionCommands, ...agentsViewSlashCommands()], cwd, fdPath ?? null);
+}
+
+export function resolveCurrentReplyTargetSummary(
+ records: readonly UnifiedSessionRecord[],
+ target: { key: string; summary: SessionSummary },
+ findLive: (activeSessionId: string) => SessionSummary | undefined,
+): SessionSummary {
+ const identity = getSummaryIdentity(target.summary);
+ const current = records.find((record) => record.identity === identity || record.identityAliases.includes(identity));
+ if (current) return summaryForUnifiedRecord(current);
+ const live = target.summary.activeSessionId ? findLive(target.summary.activeSessionId) : undefined;
+ if (live) return live;
+ // A persisted target missing from the current live catalog can still be
+ // resumed from its captured file, but its captured runtime id is stale.
+ if (target.summary.sessionFile && target.summary.activeSessionId) {
+ return { ...target.summary, activeSessionId: undefined, lifecycle: "archived", activity: "idle" };
+ }
+ return target.summary;
+}
+
+export class AgentsViewMode implements Component, Focusable {
focused = false;
private readonly ui: TUI;
@@ -426,11 +526,13 @@ class AgentsViewMode implements Component, Focusable {
private readonly keybindings: KeybindingsManager;
private client: DaemonClient | undefined;
private unsubscribeClientClose: (() => void) | undefined;
+ private unsubscribeClientMessage: (() => void) | undefined;
private reconnectPromise: Promise<void> | undefined;
private reconnectTimedOut = false;
private daemonShutdownReceived = false;
private resolveRun: ((result: AgentsViewRunResult) => void) | undefined;
private pollTimer: NodeJS.Timeout | undefined;
+ private heartbeatPollTimer: NodeJS.Timeout | undefined;
private animationTimer: NodeJS.Timeout | undefined;
private ctrlCExitHintExpiresAt = 0;
private ctrlCExitHintTimer: ReturnType<typeof setTimeout> | undefined;
@@ -440,6 +542,16 @@ class AgentsViewMode implements Component, Focusable {
private rows: AgentsViewRow[] = [];
private lastListedSummaries: SessionSummary[] = [];
private lastVisibleSummaries: SessionSummary[] = [];
+ private savedSessions: AgentConnectionSavedSessionInfo[] = [];
+ private lastSuccessfulSavedSessions: AgentConnectionSavedSessionInfo[] = [];
+ private heartbeats: AgentConnectionHeartbeat[] = [];
+ private unifiedRecords: UnifiedSessionRecord[] = [];
+ private savedCatalogGeneration = 0;
+ private liveCatalogGeneration = 0;
+ private heartbeatCatalogGeneration = 0;
+ private liveCatalogPollPromise: Promise<void> | undefined;
+ private liveCatalogRefreshPending = false;
+ private savedCatalogRefreshPending = false;
private expandedSubagentParents = new Set<string>();
// Agent row identities whose full spawn program is currently shown.
// The program key toggles each agent shown ↔ hidden.
@@ -448,21 +560,26 @@ class AgentsViewMode implements Component, Focusable {
private selectedRowIdentity: string | undefined;
private selectedActiveSessionId: string | undefined;
private selectedSessionKey: AgentsViewSelectionKey | undefined;
- private replyActiveSessionId: string | undefined;
+ private selectionAnchorPending = false;
+ /** Armed reply composer target: a live agent or a saved session to resume on send. */
+ private replyTarget: { key: string; summary: SessionSummary } | undefined;
+ /** Provider bound to the armed target's cwd for file-path completions. */
+ private replyAutocomplete: AutocompleteProvider | undefined;
+ private fdPath: string | undefined;
+ private creatingNewSession = false;
private replyLastAssistantText: string | undefined;
private replyLastAssistantTextLoading = false;
private replyHeaderTime = "";
private pendingDeleteAgent: PendingDeleteAgent | undefined;
private pendingKillSubagent: PendingKillSubagent | undefined;
- private renameTarget: { activeSessionId: string; identity: string } | undefined;
+ private renameTarget: { activeSessionId?: string; sessionFile?: string; summary: SessionSummary } | undefined;
+ private actionModeSearchQuery: string | undefined;
private readonly inactiveAgentIdentities = new Set<string>();
- private fdPath: string | undefined;
private statusMessage: string | undefined;
private statusMessageTone: "muted" | "error" | "warning" = "muted";
private statusMessageSticky = false;
private statusMessageTimer: ReturnType<typeof setTimeout> | undefined;
private stopped = false;
- private anthropicSubscriptionWarningShown = false;
constructor(
private readonly options: AgentsViewModeOptions,
@@ -471,6 +588,10 @@ class AgentsViewMode implements Component, Focusable {
this.selectedRowIdentity = persistentState.selectedRowIdentity;
this.selectedSessionKey = persistentState.selectedSessionKey;
this.selectedActiveSessionId = persistentState.selectedSessionKey?.activeSessionId;
+ this.savedSessions = persistentState.savedSessions ?? [];
+ this.lastSuccessfulSavedSessions = persistentState.lastSuccessfulSavedSessions ?? this.savedSessions;
+ this.heartbeats = persistentState.heartbeats ?? [];
+ this.savedCatalogGeneration = persistentState.savedCatalogGeneration ?? 0;
this.keybindings = KeybindingsManager.create();
setKeybindings(this.keybindings);
setRegisteredThemes(options.uiServices.getThemes());
@@ -482,28 +603,58 @@ class AgentsViewMode implements Component, Focusable {
this.editor = new CustomEditor(this.ui, getEditorTheme(), this.keybindings, {
paddingX: options.uiServices.settingsManager.getEditorPaddingX(),
autocompleteMaxVisible: options.uiServices.settingsManager.getAutocompleteMaxVisible(),
- placeholder: DEFAULT_PROMPT_PLACEHOLDER,
+ placeholder: SEARCH_PROMPT_PLACEHOLDER,
placeholderColor: (text) => theme.fg("dim", text),
});
+ void ensureTool("fd").then((fdPath) => {
+ this.fdPath = fdPath;
+ // Rebind an already-armed provider so @-completion picks up fd.
+ if (this.replyTarget) {
+ this.replyAutocomplete = createReplyComposerAutocompleteProvider(this.replyTarget.summary.cwd, fdPath);
+ }
+ });
+ // Search input never autocompletes; only the armed composer's provider answers.
+ this.editor.setAutocompleteProvider({
+ getSuggestions: async (lines, cursorLine, cursorCol, suggestOptions) => {
+ if (!this.replyTarget) return null;
+ return this.replyAutocomplete?.getSuggestions(lines, cursorLine, cursorCol, suggestOptions) ?? null;
+ },
+ applyCompletion: (lines, cursorLine, cursorCol, item, prefix) =>
+ this.replyAutocomplete?.applyCompletion(lines, cursorLine, cursorCol, item, prefix) ?? {
+ lines,
+ cursorLine,
+ cursorCol,
+ },
+ });
this.editor.focused = true;
- this.editor.setAutocompleteProvider(this.createAutocompleteProvider());
this.editor.getHeaderLine = () => this.renderReplyHeaderLine();
this.editor.onSubmit = (value) => {
void this.submit(value);
};
+ this.editor.setText(persistentState.query ?? "");
this.editor.onCtrlD = () => {
this.finish({ type: "exit" });
};
this.editor.onAgentsBack = () => {
- if (this.editor.getText().trim()) {
- return false;
- }
- if (!this.replyActiveSessionId) {
- return false;
+ if (this.replyTarget) {
+ this.setReplyTarget(undefined);
+ return true;
}
- this.setReplyTarget(undefined);
+ if (this.editor.getText().length > 0) return false;
+ const backSession = this.persistentState.backSession;
+ this.finish(backSession ? { type: "open", summary: backSession } : { type: "exit" });
return true;
};
+ this.editor.onEscape = () => {
+ if (this.replyTarget) {
+ this.setReplyTarget(undefined);
+ } else if (this.editor.getText().length > 0) {
+ this.setSearchQuery("");
+ } else {
+ const backSession = this.persistentState.backSession;
+ this.finish(backSession ? { type: "open", summary: backSession } : { type: "exit" });
+ }
+ };
this.fullscreenDock = {
render: (width) => this.renderDock(width),
invalidate: () => {
@@ -523,11 +674,12 @@ class AgentsViewMode implements Component, Focusable {
}
async run(): Promise<AgentsViewRunResult> {
- this.client = new DaemonClient(this.options.socketPath);
+ this.client = new DaemonClient(this.requireSocketPath());
await this.client.connect();
this.subscribeToClientClose(this.client);
- this.fdPath = await ensureTool("fd");
- this.editor.setAutocompleteProvider(this.createAutocompleteProvider());
+ this.unsubscribeClientMessage = this.client.onMessage((message) => {
+ if (message.type === "heartbeats_changed") void this.refreshHeartbeats();
+ });
this.ui.addChild(this);
this.ui.setFocus(this);
@@ -549,30 +701,29 @@ class AgentsViewMode implements Component, Focusable {
this.ui.requestRender();
});
- await this.refreshSessions();
+ const runPromise = new Promise<AgentsViewRunResult>((resolve) => {
+ this.resolveRun = resolve;
+ });
+ void this.refreshSessions();
+ void this.refreshSavedSessions();
+ void this.refreshHeartbeats();
this.loadStartupNotices();
- this.pollTimer = setInterval(() => {
- void this.refreshSessions();
- }, POLL_INTERVAL_MS);
+ this.pollTimer = setInterval(() => this.pollSessions(), POLL_INTERVAL_MS);
this.pollTimer.unref?.();
+ this.heartbeatPollTimer = setInterval(() => void this.refreshHeartbeats(), HEARTBEAT_POLL_INTERVAL_MS);
+ this.heartbeatPollTimer.unref?.();
this.animationTimer = setInterval(() => {
- if (!this.rows.some((row) => row.section === "working")) {
- return;
- }
+ if (!this.rows.some((row) => row.section === "running")) return;
this.workingIconFrame += 1;
this.ui.requestRender();
}, WORKING_ICON_INTERVAL_MS);
this.animationTimer.unref?.();
- return new Promise((resolve) => {
- this.resolveRun = resolve;
- });
+ return runPromise;
}
handleInput(data: string): void {
this.clearStickyStatusMessage();
- // While renaming, the editor holds the proposed name: Escape cancels, Enter
- // (via onSubmit) confirms, everything else edits the text.
if (this.renameTarget) {
if (this.keybindings.matches(data, "tui.select.cancel")) {
this.exitRenameMode();
@@ -582,14 +733,19 @@ class AgentsViewMode implements Component, Focusable {
return;
}
if (this.keybindings.matches(data, "app.clear")) {
+ // The composer hints advertise ctrl+c as cancel; it must not start the exit flow.
+ if (this.replyTarget) {
+ this.setReplyTarget(undefined);
+ return;
+ }
this.handleCtrlC();
return;
}
- if (this.keybindings.matches(data, "app.agents.rename") && this.editor.getText().length === 0) {
+ if (this.editor.getText().length === 0 && this.keybindings.matches(data, "app.agents.rename")) {
this.enterRenameMode();
return;
}
- if (this.keybindings.matches(data, "app.agents.delete") && this.editor.getText().length === 0) {
+ if (this.editor.getText().length === 0 && this.keybindings.matches(data, "app.agents.delete")) {
this.clearCtrlCExitHint({ render: false });
void this.handleDeleteSelected();
return;
@@ -600,25 +756,38 @@ class AgentsViewMode implements Component, Focusable {
void this.toggleReplyTarget();
return;
}
- if (this.keybindings.matches(data, "app.agents.program") && this.editor.getText().length === 0) {
- this.cycleProgramForSelected();
+ if (!this.replyTarget && this.keybindings.matches(data, "app.agents.new")) {
+ void this.createNewSession();
return;
}
- // Mirror the confirm shortcut: open the selected agent only when the prompt
- // is empty and we are not composing a reply (empty confirm is a no-op then).
- // Match the confirm path's trim() so a whitespace-only prompt still opens.
- if (
- this.keybindings.matches(data, "app.agents.open") &&
- this.editor.getText().trim().length === 0 &&
- !this.replyActiveSessionId
- ) {
- this.openSelected();
+ if (this.replyTarget && this.keybindings.matches(data, "app.message.followUp")) {
+ this.handleReplyFollowUp();
+ return;
+ }
+ if (this.editor.getText().length === 0 && this.keybindings.matches(data, "app.agents.program")) {
+ this.cycleProgramForSelected();
return;
}
- if (this.editor.getText().length === 0 && this.handleListNavigation(data)) {
+ if (!this.replyTarget && this.keybindings.matches(data, "app.agents.open")) {
+ if (this.editor.getText().length === 0 || this.isSearchCursorAtEnd()) {
+ this.openSelected();
+ return;
+ }
+ }
+ if (!this.replyTarget && this.handleListNavigation(data)) {
return;
}
+ const previous = this.editor.getText();
this.editor.handleInput(data);
+ if (!this.replyTarget && this.editor.getText() !== previous) {
+ this.queryChanged();
+ }
+ }
+
+ private isSearchCursorAtEnd(): boolean {
+ const lines = this.editor.getLines();
+ const cursor = this.editor.getCursor();
+ return cursor.line === lines.length - 1 && cursor.col === (lines[cursor.line]?.length ?? 0);
}
render(width: number): string[] {
@@ -640,13 +809,22 @@ class AgentsViewMode implements Component, Focusable {
if (height <= 0) {
return [];
}
- const lines: string[] = [];
- lines.push(...this.splash.render(width));
+ const headerLines = this.splash.render(width);
const noticeLines = this.renderStartupNotices(width);
if (noticeLines.length > 0) {
- lines.push("", ...noticeLines);
- }
- lines.push("");
+ headerLines.push("", ...noticeLines);
+ }
+ headerLines.push("");
+
+ // The prompt belongs to the scroll pane rather than the fullscreen dock, but
+ // it must remain usable when a short viewport or wrapped notices exhaust the
+ // header. Trim optional header chrome first and reserve one session-list row.
+ const promptLines = this.renderPrompt(width);
+ const listGap = height >= promptLines.length + 2 ? 1 : 0;
+ const headerRows = Math.max(0, height - promptLines.length - listGap - 1);
+ const lines = headerLines.slice(0, headerRows);
+ lines.push(...promptLines);
+ if (listGap > 0) lines.push("");
const listRows = Math.max(0, height - lines.length);
lines.push(...this.renderSessionRows(width, listRows));
return lines;
@@ -854,8 +1032,8 @@ class AgentsViewMode implements Component, Focusable {
// targets; nested rows share the parent's session id but are read-only.
const selectedRow = this.rows[this.selectedIndex];
if (
- this.replyActiveSessionId &&
- (selectedRow?.kind !== "agent" || this.replyActiveSessionId !== this.selectedActiveSessionId)
+ this.replyTarget &&
+ (selectedRow?.kind !== "agent" || this.replyTarget.key !== this.selectedActiveSessionId)
) {
this.setReplyTarget(undefined);
}
@@ -923,11 +1101,30 @@ class AgentsViewMode implements Component, Focusable {
this.rebuildRows();
}
+ private setSearchQuery(query: string): void {
+ this.editor.setText(query);
+ this.queryChanged();
+ }
+
+ private queryChanged(): void {
+ this.persistentState.query = this.editor.getText();
+ this.rebuildRows();
+ // Typing must not claim the visible fallback row while the restored
+ // anchor is still waiting for its catalog row.
+ if (!this.selectionAnchorPending) this.syncSelectedRowState();
+ this.ui.requestRender();
+ }
+
+ private getFilteredRecords(): UnifiedSessionRecord[] {
+ const query = this.replyTarget || this.renameTarget ? (this.actionModeSearchQuery ?? "") : this.editor.getText();
+ return filterUnifiedSessions(this.unifiedRecords, (text) => matchesSearchText(text, query));
+ }
+
/** Rebuild rows from the last fetched summaries, keeping selection on the same row. */
private rebuildRows(): void {
const selectedIdentity = this.rows[this.selectedIndex]?.identity;
this.rows = buildAgentsViewRows(
- this.lastVisibleSummaries,
+ this.getFilteredRecords(),
this.expandedSubagentParents,
this.programShownParents,
);
@@ -940,357 +1137,61 @@ class AgentsViewMode implements Component, Focusable {
}
}
- private async submit(value: string): Promise<void> {
+ private async submit(value: string, delivery: "steer" | "followUp" = "steer"): Promise<void> {
if (this.renameTarget) {
await this.confirmRename(value);
return;
}
- const text = value.trim();
- if (!text) {
- if (this.replyActiveSessionId) {
+ if (this.replyTarget) {
+ const target = this.replyTarget;
+ const text = value.trim();
+ const viewCommand = parseAgentsViewCommand(text);
+ if (viewCommand) {
+ // Stale summaries mis-route the RPCs after a runtime replacement.
+ const currentSummary = resolveCurrentReplyTargetSummary(
+ this.unifiedRecords ?? [],
+ target,
+ (activeSessionId) => this.findSummaryByActiveSessionId(activeSessionId),
+ );
+ const succeeded = await this.runAgentsViewCommand(viewCommand, currentSummary);
+ if (!succeeded && this.replyTarget === target && this.editor.getText().length === 0) {
+ this.editor.setText(value);
+ }
return;
}
- this.openSelected();
- return;
- }
-
- // Only built-in interactive commands are intercepted here; unknown "/..."
- // text still reaches the daemon session, which expands prompt templates,
- // skills, and extension commands.
- const command = parseSlashCommand(text);
- if (command) {
- const kind = classifyAgentsViewCommand(command.name);
- if (kind === "agents-view") {
- this.editor.setText("");
- await this.runSlashCommand(resolveAgentsViewCommand(command));
+ const rejection = getReplyComposerCommandRejection(text);
+ if (rejection) {
+ // submitValue cleared the buffer before onSubmit; keep the draft.
+ if (this.editor.getText().length === 0) this.editor.setText(value);
+ this.setStatusMessage(rejection, { tone: "warning" });
return;
}
- if (kind === "session-only") {
+ if (text) {
this.editor.setText("");
- const resolvedCommand = resolveAgentsViewCommand(command);
- const commandLabel =
- resolvedCommand.name === command.name
- ? `/${command.name}`
- : `/${command.name} maps to /${resolvedCommand.name}, which`;
- this.setStatusMessage(
- `${commandLabel} is only available inside an agent session — press ${keyText("tui.select.confirm")} on an agent to open it`,
- );
- return;
- }
- }
-
- this.editor.setText("");
- if (this.replyActiveSessionId) {
- await this.sendReply(this.replyActiveSessionId, text);
- return;
- }
- const created = await this.createAgentForPrompt(text);
- if (created) {
- this.finish({ type: "open", summary: created.summary });
- }
- }
-
- private async runSlashCommand(command: ParsedSlashCommand): Promise<void> {
- switch (command.name as AgentsViewCommandName) {
- case "login":
- await this.showConfigurationMenu("providers");
- return;
- case "logout":
- await this.createAuthFlows().runLogout();
- return;
- case "mcp":
- if (command.args) {
- this.setStatusMessage("MCP subcommands are only available inside an agent session.");
- return;
- }
- await this.showConfigurationMenu("mcp-connections");
- return;
- case "model": {
- const searchTerm = command.args || undefined;
- if (searchTerm) {
- const authFlows = this.createAuthFlows();
- const providerOptions = authFlows.getLoginProviderOptions();
- const catalog = await this.options.uiServices.modelRegistry.refreshModelCatalog();
- const match = findExactModelReferenceMatch(searchTerm, catalog.models);
- if (match) {
- const { ready } = await this.ensureDefaultModelProviderConfigured(match, authFlows, providerOptions);
- if (ready) {
- this.applyDefaultModel(match);
- }
- return;
+ const sent = await this.sendReply(target, text, delivery);
+ if (sent) {
+ if (this.replyTarget === target && this.editor.getText().length === 0) {
+ this.setReplyTarget(undefined);
}
+ // Keep the send outcome (or sticky cwd notice) that sendReply just surfaced.
+ await this.refreshSessions({ preserveStatusOnError: true });
+ } else if (this.replyTarget === target && this.editor.getText().length === 0) {
+ this.editor.setText(value);
}
- await this.showConfigurationMenu("models", searchTerm);
- return;
}
- case "resume":
- await this.showSessionSelector();
- return;
- case "quit":
- this.finish({ type: "exit" });
- return;
- default: {
- const _exhaustive: never = command.name as never;
- return _exhaustive;
- }
- }
- }
-
- private createAuthFlows(): ProviderAuthFlows {
- const modelRegistry = this.options.uiServices.modelRegistry;
- return new ProviderAuthFlows({
- ui: this.ui,
- modelRegistry,
- showStatus: (message) => this.setStatusMessage(message),
- showError: (message) => this.setStatusMessage(message, { tone: "error" }),
- getAvailableModels: () => modelRegistry.refreshAvailableModels(),
- onLoginCompleted: () => {
- void this.maybeWarnAboutAnthropicSubscriptionAuth(this.getDefaultModelForNewAgents());
- },
- });
- }
-
- private async applyPrimeInferenceFallbackAfterLogin(authResult: AuthenticationResult): Promise<void> {
- const currentModel = this.getDefaultModelForNewAgents();
- const action = resolvePrimeInferencePostLoginModelAction(
- authResult,
- currentModel,
- this.options.uiServices.modelRegistry,
- );
- if (!action.openModelPicker) {
return;
}
-
- if (action.fallbackModel) {
- this.applyDefaultModel(action.fallbackModel);
- await this.options.uiServices.settingsManager.flush();
- } else if (!currentModel) {
- this.setStatusMessage("Prime Inference login succeeded, but the default GLM 5.2 model is unavailable.", {
- tone: "error",
- });
- }
+ // Search text is never a prompt or a command; Enter opens the selection.
+ this.openSelected();
}
- private async maybeWarnAboutAnthropicSubscriptionAuth(model: Model<Api> | undefined): Promise<void> {
- if (this.options.uiServices.settingsManager.getWarnings().anthropicExtraUsage === false) {
- return;
- }
- if (this.anthropicSubscriptionWarningShown) {
- return;
- }
- const warning = await getAnthropicSubscriptionAuthWarning(this.options.uiServices.modelRegistry, model);
- if (!warning) {
- return;
- }
- this.anthropicSubscriptionWarningShown = true;
- this.setStatusMessage(warning, { tone: "warning", sticky: true });
- }
-
- private async ensureDefaultModelProviderConfigured(
- model: Model<Api>,
- authFlows: ProviderAuthFlows,
- providerOptions: ReadonlyArray<AuthSelectorProvider>,
- ): Promise<{ ready: boolean; refreshedCatalog?: ModelCatalogSnapshot }> {
- const modelRegistry = this.options.uiServices.modelRegistry;
- if (modelRegistry.hasConfiguredAuth(model)) return { ready: true };
-
- const provider = providerOptions.find(
- (option) => option.id === model.provider && (option.category ?? "provider") === "provider",
- );
- if (!provider) {
- this.setStatusMessage(`Authentication for ${model.provider} must be configured externally.`, {
- tone: "error",
- });
- return { ready: false };
- }
-
- const result = await authFlows.loginProvider(provider);
- if (result.status !== "success") return { ready: false };
-
- const refreshedCatalog = await modelRegistry.refreshModelCatalog();
- if (modelRegistry.hasConfiguredAuth(model)) return { ready: true, refreshedCatalog };
-
- this.setStatusMessage(`Authentication completed, but ${model.provider} is still unavailable.`, {
- tone: "error",
- });
- return { ready: false, refreshedCatalog };
- }
-
- private async showConfigurationMenu(initialTab: ConfigurationMenuTab, initialModelSearch?: string): Promise<void> {
- const modelRegistry = this.options.uiServices.modelRegistry;
- const authFlows = this.createAuthFlows();
- const providerOptions = authFlows.getLoginProviderOptions();
- const initialCatalog = await modelRegistry.refreshModelCatalog();
- return new Promise((resolve) => {
- let handle: OverlayHandle | undefined;
- let settled = false;
- let hidden = false;
- let menu: ConfigurationMenuComponent;
- const hide = () => {
- if (hidden) return;
- hidden = true;
- handle?.hide();
- this.ui.requestRender();
- };
- const finish = () => {
- if (settled) return;
- settled = true;
- hide();
- resolve();
- };
- const authenticate = (provider: AuthSelectorProvider, tab: "providers" | "mcp-connections") => {
- if (settled) return;
- void authFlows
- .loginProvider(provider)
- .then(async (authResult) => {
- if (settled) return;
- handle?.focus();
- if (authResult.status !== "success" || tab === "mcp-connections") {
- menu.refreshAuthentication();
- return;
- }
-
- await this.applyPrimeInferenceFallbackAfterLogin(authResult);
- const catalog = await modelRegistry.refreshModelCatalog();
- syncAgentsViewModelMenuAfterAuth(menu, this.getDefaultModelForNewAgents(), catalog);
- menu.setActiveTab("models");
- })
- .catch((error) => {
- handle?.focus();
- this.setStatusMessage(error instanceof Error ? error.message : String(error), { tone: "error" });
- });
- };
-
- menu = new ConfigurationMenuComponent({
- initialTab,
- tui: this.ui,
- authStorage: modelRegistry.authStorage,
- providerOptions,
- modelRegistry,
- currentModel: this.getDefaultModelForNewAgents(),
- scopedModels: [],
- availableModels: initialCatalog.models,
- configuredProviders: new Set(initialCatalog.configuredProviders),
- recentModels: this.options.uiServices.settingsManager.getRecentModels(),
- initialModelSearch,
- getRows: () => this.ui.terminal.rows,
- requestRender: () => this.ui.requestRender(),
- onSelectProvider: (provider) => authenticate(provider, "providers"),
- onSelectMcpConnection: (provider) => authenticate(provider, "mcp-connections"),
- onSelectModel: (model) => {
- void (async () => {
- try {
- const result = await this.ensureDefaultModelProviderConfigured(model, authFlows, providerOptions);
- handle?.focus();
- if (result.refreshedCatalog) {
- syncAgentsViewModelMenuAfterAuth(
- menu,
- this.getDefaultModelForNewAgents(),
- result.refreshedCatalog,
- );
- } else {
- menu.refreshAuthentication();
- }
- if (!result.ready || settled) return;
- this.applyDefaultModel(model);
- finish();
- } catch (error) {
- this.setStatusMessage(error instanceof Error ? error.message : String(error), { tone: "error" });
- }
- })();
- },
- onCancel: finish,
- });
- handle = showFullPaneOverlay(this.ui, menu, 96);
- });
- }
-
- private showSessionSelector(): Promise<void> {
- return new Promise((done) => {
- let handle: OverlayHandle | undefined;
- let settled = false;
- const savedSessionsByPath = new Map<string, AgentConnectionSavedSessionInfo>();
-
- const rememberSessions = <T extends AgentConnectionSavedSessionInfo[]>(sessions: T): T => {
- for (const session of sessions) {
- savedSessionsByPath.set(resolvePath(session.path), session);
- }
- return sessions;
- };
- const listSavedSessions = async (
- scope: "current" | "all",
- callbacks?: SessionListCallbacks,
- ): Promise<AgentConnectionSavedSessionInfo[]> => {
- const sessions = await listDaemonSavedSessions(
- this.requireClient(),
- this.getSavedSessionCatalogContext(),
- scope,
- {
- onProgress: callbacks?.onProgress,
- onSession: (session) => {
- rememberSessions([session]);
- callbacks?.onSession?.(session);
- },
- },
- );
- return rememberSessions(sessions);
- };
-
- const close = () => {
- if (settled) {
- return;
- }
- settled = true;
- handle?.hide();
- this.ui.requestRender();
- done();
- };
-
- const selector = new SessionSelectorComponent(
- (callbacks) => listSavedSessions("current", callbacks),
- (callbacks) => listSavedSessions("all", callbacks),
- (sessionPath) => {
- const summary = resolveAgentsViewResumeSummary(
- sessionPath,
- [...savedSessionsByPath.values()],
- this.lastListedSummaries,
- );
- close();
- if (!summary) {
- this.setStatusMessage("Failed to resume session: selected session was not found");
- return;
- }
- this.finish({ type: "open", summary });
- },
- close,
- () => {
- close();
- this.finish({ type: "exit" });
- },
- () => this.ui.requestRender(),
- {
- renameSession: async (sessionPath, nextName) => {
- const name = (nextName ?? "").trim();
- if (!name) {
- return;
- }
- await this.renameSavedSessionFromSelector(sessionPath, name);
- },
- deleteSession: (sessionPath) => this.deleteSavedSessionFromSelector(sessionPath),
- showRenameHint: true,
- keybindings: this.keybindings,
- frameless: true,
- },
- );
- const splash = new BrandSplashHeader(
- VERSION,
- () => this.getSplashModelId(),
- () => this.getSavedSessionCwd(),
- );
- handle = showFullPaneOverlay(this.ui, new SessionPickerScreen(this.ui, splash, selector), {
- fullWidth: true,
- });
- });
+ /** Alt+Enter in the reply composer queues the reply as a follow-up. */
+ private handleReplyFollowUp(): void {
+ if (!this.replyTarget) return;
+ // Unlike Enter, this path skips submitValue, so expand paste markers here.
+ const text = this.editor.getExpandedText();
+ if (!text.trim()) return;
+ void this.submit(text, "followUp");
}
private getSavedSessionCwd(): string {
@@ -1301,48 +1202,15 @@ class AgentsViewMode implements Component, Focusable {
return { cwd: this.getSavedSessionCwd(), sessionDir: this.options.config.sessionDir };
}
- private async renameSavedSessionFromSelector(sessionPath: string, name: string): Promise<void> {
- await renameDaemonSavedSession(this.requireClient(), this.getSavedSessionCatalogContext(), sessionPath, name);
- await this.refreshSessions();
- }
-
- private async deleteSavedSessionFromSelector(sessionPath: string) {
- return deleteDaemonSavedSession(this.requireClient(), this.getSavedSessionCatalogContext(), sessionPath);
- }
-
- private getDefaultModelForNewAgents(): Model<Api> | undefined {
- const settings = this.options.uiServices.settingsManager;
- const provider = settings.getDefaultProvider();
- const modelId = settings.getDefaultModel();
- return provider && modelId ? this.options.uiServices.modelRegistry.find(provider, modelId) : undefined;
- }
-
- private applyDefaultModel(model: Model<Api>): void {
- this.options.uiServices.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
- // New agents are created from this shared config; pin the model explicitly
- // so the daemon does not fall back to its own settings snapshot.
- this.options.config.provider = model.provider;
- this.options.config.model = model.id;
- this.options.startupModelId = model.id;
- this.setStatusMessage(`Model for new agents: ${model.id}`);
- void this.maybeWarnAboutAnthropicSubscriptionAuth(model);
- }
-
- private createAutocompleteProvider(): CombinedAutocompleteProvider {
- const cwd = resolveAgentsViewAutocompleteCwd(
- this.options.uiServices.getInitialCwd(),
- this.replyActiveSessionId ? this.findSummaryByActiveSessionId(this.replyActiveSessionId) : undefined,
- );
- return createAgentsViewAutocompleteProvider(cwd, this.fdPath, (prefix) =>
- getAgentsViewModelArgumentCompletions(prefix, this.options.uiServices.modelRegistry),
- );
- }
-
private openSelected(): void {
const row = this.rows[this.selectedIndex];
if (!row?.selectable || this.isPendingDeleteRow(row)) {
return;
}
+ if (this.selectionAnchorPending) {
+ this.setStatusMessage("Waiting for the selected session to load");
+ return;
+ }
if (row.kind === "subagent-summary") {
this.expandSubagentList(row);
return;
@@ -1486,42 +1354,70 @@ class AgentsViewMode implements Component, Focusable {
if (selectedRow?.kind !== "agent") {
return;
}
- const activeSessionId = selectedRow.summary.activeSessionId;
- if (!activeSessionId) {
+ const summary = selectedRow.summary;
+ // Live agents reply directly; saved sessions are resumed when the reply is
+ // sent. Rows with neither runtime nor file have nothing to receive a prompt.
+ if (!summary.activeSessionId && !summary.sessionFile) {
return;
}
if (this.pendingDeleteAgent?.identity === getSelectedRowIdentity(selectedRow)) {
return;
}
- if (this.replyActiveSessionId === activeSessionId) {
+ const key = summary.activeSessionId ?? summary.id;
+ if (this.replyTarget?.key === key) {
this.setReplyTarget(undefined);
return;
}
- this.setReplyTarget(activeSessionId);
+ this.setReplyTarget({ key, summary });
+ if (!summary.activeSessionId) {
+ // Inactive sessions have no live transcript endpoint; the persisted recap
+ // (or opener) is the best preview and needs no daemon round-trip.
+ this.replyLastAssistantText = summary.summary ?? summary.firstMessage;
+ this.ui.requestRender();
+ return;
+ }
+ const activeSessionId = summary.activeSessionId;
this.replyLastAssistantTextLoading = true;
try {
const latestAssistantText = await this.getLastAssistantText(activeSessionId);
- if (this.replyActiveSessionId === activeSessionId) {
+ if (this.replyTarget?.key === key) {
this.replyLastAssistantText = latestAssistantText;
this.replyLastAssistantTextLoading = false;
this.ui.requestRender();
}
} catch (error) {
- if (this.replyActiveSessionId === activeSessionId) {
+ if (this.replyTarget?.key === key) {
this.replyLastAssistantTextLoading = false;
this.setStatusMessage(formatError("Failed to load latest response", error));
}
}
}
- private setReplyTarget(activeSessionId: string | undefined): void {
- this.replyActiveSessionId = activeSessionId;
+ private setReplyTarget(target: { key: string; summary: SessionSummary } | undefined): void {
+ if (target && !this.replyTarget) {
+ this.actionModeSearchQuery = this.editor.getText();
+ this.editor.setText("");
+ } else if (!target && this.replyTarget) {
+ this.editor.setText(this.actionModeSearchQuery ?? this.persistentState.query ?? "");
+ this.actionModeSearchQuery = undefined;
+ }
+ this.replyTarget = target;
+ this.replyAutocomplete = target
+ ? createReplyComposerAutocompleteProvider(target.summary.cwd, this.fdPath)
+ : undefined;
this.replyLastAssistantText = undefined;
this.replyLastAssistantTextLoading = false;
- // Captured once on entry so the header does not count up while reply mode stays open.
- this.replyHeaderTime = activeSessionId ? this.getReplyHeaderTime(activeSessionId) : "";
- this.editor.setPlaceholder(activeSessionId ? REPLY_PROMPT_FALLBACK_PLACEHOLDER : DEFAULT_PROMPT_PLACEHOLDER);
- this.editor.setAutocompleteProvider(this.createAutocompleteProvider());
+ this.replyHeaderTime = target
+ ? formatAgentsViewRelativeTime(target.summary.modified ?? target.summary.created)
+ : "";
+ this.editor.setPlaceholder(
+ target
+ ? target.summary.activeSessionId
+ ? REPLY_PROMPT_FALLBACK_PLACEHOLDER
+ : RESUME_PROMPT_PLACEHOLDER
+ : SEARCH_PROMPT_PLACEHOLDER,
+ );
+ if (!target) this.rebuildRows();
this.ui.requestRender();
}
@@ -1532,14 +1428,16 @@ class AgentsViewMode implements Component, Focusable {
return;
}
const activeSessionId = row.summary.activeSessionId;
- if (!activeSessionId) {
- this.setStatusMessage("This agent has no active session to rename");
+ const sessionFile = row.summary.sessionFile;
+ if (!activeSessionId && !sessionFile) {
+ this.setStatusMessage("This session cannot be renamed");
return;
}
this.setReplyTarget(undefined);
+ this.actionModeSearchQuery = this.editor.getText();
this.pendingDeleteAgent = undefined;
this.pendingKillSubagent = undefined;
- this.renameTarget = { activeSessionId, identity: getSummaryIdentity(row.summary) };
+ this.renameTarget = { activeSessionId, sessionFile, summary: row.summary };
this.editor.setPlaceholder("Name this agent session");
this.editor.setText(row.summary.sessionName ?? "");
this.ui.requestRender();
@@ -1547,8 +1445,10 @@ class AgentsViewMode implements Component, Focusable {
private exitRenameMode(): void {
this.renameTarget = undefined;
- this.editor.setText("");
- this.editor.setPlaceholder(DEFAULT_PROMPT_PLACEHOLDER);
+ this.editor.setText(this.actionModeSearchQuery ?? this.persistentState.query ?? "");
+ this.actionModeSearchQuery = undefined;
+ this.editor.setPlaceholder(SEARCH_PROMPT_PLACEHOLDER);
+ this.rebuildRows();
this.ui.requestRender();
}
@@ -1563,29 +1463,41 @@ class AgentsViewMode implements Component, Focusable {
return;
}
this.exitRenameMode();
+ await this.renameSession(target.summary, name);
+ }
+
+ /** Shared by rename mode and /name: rename, refresh both catalogs, report. */
+ private async renameSession(summary: SessionSummary, name: string): Promise<boolean> {
this.setStatusMessage("Renaming agent...");
try {
- await this.requireClient().request({
- type: "rename",
- activeSessionId: target.activeSessionId,
- name,
- });
- this.setStatusMessage(`Renamed to ${name}`, { render: false });
- await this.refreshSessions();
+ if (summary.activeSessionId) {
+ requireDaemonData(
+ await this.requireClient().request({ type: "rename", activeSessionId: summary.activeSessionId, name }),
+ );
+ } else if (summary.sessionFile) {
+ await renameDaemonSavedSession(
+ this.requireClient(),
+ this.getSavedSessionCatalogContext(),
+ summary.sessionFile,
+ name,
+ );
+ } else {
+ this.setStatusMessage("This session cannot be renamed", { tone: "warning" });
+ return false;
+ }
+ const refreshed = await this.refreshBothCatalogs();
+ this.setStatusMessage(refreshed ? `Renamed to ${name}` : `Renamed to ${name}; refresh failed`);
+ return true;
} catch (error) {
this.setStatusMessage(
isUnknownDaemonCommandError(error, "rename")
? "Failed to rename: the daemon is running an older build; restart the daemon and try again"
: formatError("Failed to rename agent", error),
);
+ return false;
}
}
- private getReplyHeaderTime(activeSessionId: string): string {
- const summary = this.findSummaryByActiveSessionId(activeSessionId);
- return formatAgentsViewRelativeTime(summary?.modified ?? summary?.created);
- }
-
private findSummaryByActiveSessionId(activeSessionId: string): SessionSummary | undefined {
return this.rows.find((row) => (row.summary.activeSessionId ?? row.summary.id) === activeSessionId)?.summary;
}
@@ -1594,7 +1506,7 @@ class AgentsViewMode implements Component, Focusable {
if (this.renameTarget) {
return theme.fg("warning", "Rename agent session");
}
- if (!this.replyActiveSessionId) {
+ if (!this.replyTarget) {
return undefined;
}
const headline =
@@ -1621,19 +1533,153 @@ class AgentsViewMode implements Component, Focusable {
return data.text;
}
- private async sendReply(activeSessionId: string, text: string): Promise<void> {
- const behavior = this.findSummaryByActiveSessionId(activeSessionId)?.isStreaming ? "followUp" : undefined;
- this.setStatusMessage("Sending reply...");
+ private async sendReply(
+ target: { key: string; summary: SessionSummary },
+ text: string,
+ delivery: "steer" | "followUp" = "steer",
+ ): Promise<boolean> {
+ const currentSummary = resolveCurrentReplyTargetSummary(this.unifiedRecords ?? [], target, (activeSessionId) =>
+ this.findSummaryByActiveSessionId(activeSessionId),
+ );
+ let activeSessionId = currentSummary.activeSessionId;
+ let liveSummary = activeSessionId ? currentSummary : undefined;
+ let cwdFallbackNotice: string | undefined;
+ let didResume = false;
try {
- await this.sendPrompt(activeSessionId, text, undefined, behavior);
- this.setStatusMessage("Reply sent");
- this.setReplyTarget(undefined);
- await this.refreshSessions();
+ if (!activeSessionId) {
+ // Saved session: resume it into the daemon first, then deliver the
+ // prompt through the same path as a live reply.
+ this.setStatusMessage("Resuming session...");
+ const resumed = await resumeSavedAgentsViewSession(
+ this.requireClient(),
+ this.options.config,
+ currentSummary,
+ );
+ activeSessionId = resumed.activeSessionId;
+ didResume = true;
+ // The rows are still pre-resume; the fresh summary is the authoritative
+ // streaming state for scheduling the prompt.
+ liveSummary = resumed.summary;
+ cwdFallbackNotice = resumed.cwdFallbackNotice;
+ this.inactiveAgentIdentities.delete(getSummaryIdentity(target.summary));
+ // The resume and delivery still belong to this submission, but selection
+ // belongs to the current composer. Do not steal it after cancellation.
+ if (this.replyTarget === target) this.selectSummary(resumed.summary);
+ }
+ const behavior = delivery === "followUp" ? "followUp" : liveSummary?.isStreaming ? "steer" : undefined;
+ this.setStatusMessage("Sending reply...");
+ await this.sendPrompt(activeSessionId, text, behavior);
+ // The fallback-directory notice must outlive the transient send statuses.
+ if (cwdFallbackNotice) this.setStatusMessage(cwdFallbackNotice, { sticky: true });
+ else this.setStatusMessage("Reply sent");
+ return true;
} catch (error) {
this.setStatusMessage(formatError("Failed to send reply", error));
+ if (didResume) await this.refreshSessions({ preserveStatusOnError: true });
+ return false;
+ }
+ }
+
+ /** Create a fresh daemon session and open it in the chat view. */
+ private async createNewSession(): Promise<boolean> {
+ if (this.creatingNewSession || this.stopped) return false;
+ this.creatingNewSession = true;
+ try {
+ const client = await this.connectDedicatedClient();
+ try {
+ this.setStatusMessage("Creating session...");
+ const response = await client.request({
+ type: "create",
+ config: this.options.config,
+ env: collectDaemonClientEnv(),
+ });
+ const created = expectSessionSummary(requireDaemonData(response));
+ // The view can finish mid-create; kill the fresh session instead of orphaning it.
+ if (this.stopped) {
+ if (created.activeSessionId) {
+ await client
+ .request({ type: "kill", activeSessionId: created.activeSessionId })
+ .catch(() => undefined);
+ }
+ return false;
+ }
+ this.selectSummary(created);
+ this.finish({ type: "open", summary: created });
+ return true;
+ } finally {
+ client.close();
+ }
+ } catch (error) {
+ if (!this.stopped) this.setStatusMessage(formatError("Failed to create session", error));
+ return false;
+ } finally {
+ this.creatingNewSession = false;
}
}
+ /**
+ * Run a view command against the armed composer's target. Returns whether
+ * it completed so callers can restore the draft; disarms are guarded
+ * against a composer re-armed during the awaited RPCs.
+ */
+ private async runAgentsViewCommand(command: AgentsViewCommand, target: SessionSummary): Promise<boolean> {
+ const armedAtStart = this.replyTarget;
+ const disarmIfUnchanged = () => {
+ if (armedAtStart && this.replyTarget === armedAtStart) this.setReplyTarget(undefined);
+ };
+ try {
+ switch (command.name) {
+ case "name": {
+ const name = command.args.trim();
+ if (!name) {
+ this.setStatusMessage("Usage: /name <session name>", { tone: "warning" });
+ return false;
+ }
+ return await this.renameSession(target, name);
+ }
+ case "kill": {
+ if (!target.activeSessionId) {
+ this.setStatusMessage("/kill needs a running agent; this session is inactive", { tone: "warning" });
+ return false;
+ }
+ try {
+ requireDaemonData(
+ await this.requireClient().request({ type: "kill", activeSessionId: target.activeSessionId }),
+ );
+ } catch (error) {
+ // As in deactivatePendingAgent: an agent that already finished counts as stopped.
+ if (!isUnknownActiveSessionError(error)) throw error;
+ }
+ disarmIfUnchanged();
+ this.setStatusMessage("Agent stopped");
+ await this.refreshBothCatalogs();
+ return true;
+ }
+ }
+ } catch (error) {
+ this.setStatusMessage(formatError(`Failed to run /${command.name}`, error));
+ return false;
+ }
+ return false;
+ }
+
+ /**
+ * Outlives finish(), which closes the shared client and would reject an
+ * in-flight create while the daemon still materializes the session.
+ */
+ private async connectDedicatedClient(): Promise<DaemonClient> {
+ return connectAgentsViewDaemonClient(this.requireSocketPath());
+ }
+
+ /** Point selection (and its persisted key) at a freshly resumed session row. */
+ private selectSummary(summary: SessionSummary): void {
+ this.selectedRowIdentity = getSummaryIdentity(summary);
+ this.selectedActiveSessionId = summary.activeSessionId ?? summary.id;
+ this.selectedSessionKey = getAgentsViewSelectionKey(summary);
+ this.persistentState.selectedRowIdentity = this.selectedRowIdentity;
+ this.persistentState.selectedSessionKey = this.selectedSessionKey;
+ }
+
private async handleDeleteSelected(): Promise<void> {
const row = this.rows[this.selectedIndex];
if (!row?.selectable) {
@@ -1649,6 +1695,50 @@ class AgentsViewMode implements Component, Focusable {
}
this.pendingKillSubagent = undefined;
const identity = getSummaryIdentity(row.summary);
+ if (!row.summary.activeSessionId && row.summary.sessionFile) {
+ if (this.pendingDeleteAgent?.identity === identity && this.isDeleteConfirmationVisible()) {
+ this.clearDeleteConfirmation({ render: false });
+ try {
+ const latest = expectSessionList(
+ requireDaemonData(await this.requireClient().request(createAgentsViewListCommand())),
+ );
+ this.lastListedSummaries = latest;
+ const active = resolveAgentsViewActiveSummaryForPath(row.summary.sessionFile, latest);
+ if (active) {
+ this.pendingDeleteAgent = undefined;
+ this.setStatusMessage("Session became active; stop it before deleting", { tone: "warning" });
+ await this.refreshSessions();
+ return;
+ }
+ const result = await deleteDaemonSavedSession(
+ this.requireClient(),
+ this.getSavedSessionCatalogContext(),
+ row.summary.sessionFile,
+ );
+ if (!result.ok) {
+ this.setStatusMessage(`Failed to delete session: ${result.error ?? "Unknown error"}`, {
+ tone: "error",
+ });
+ return;
+ }
+ this.pendingDeleteAgent = undefined;
+ const refreshed = await this.refreshSavedSessions({ preserveStatusOnError: true });
+ const success = result.method === "trash" ? "Session moved to trash" : "Session deleted";
+ this.setStatusMessage(refreshed ? success : `${success}; refresh failed`);
+ } catch (error) {
+ this.setStatusMessage(formatError("Failed to delete session", error));
+ }
+ return;
+ }
+ this.pendingDeleteAgent = {
+ identity,
+ sessionFile: row.summary.sessionFile,
+ summary: row.summary,
+ stopped: false,
+ };
+ this.showDeleteConfirmation();
+ return;
+ }
if (this.pendingDeleteAgent?.identity === identity) {
if (this.isDeleteConfirmationVisible()) {
await this.deactivatePendingAgent();
@@ -1796,113 +1886,70 @@ class AgentsViewMode implements Component, Focusable {
}
}
- private async createAgentForPrompt(
- text: string,
- images?: ImageContent[],
- ): Promise<{ summary: SessionSummary; activeSessionId: string } | undefined> {
- const client = this.requireClient();
- this.setStatusMessage("Creating agent...");
- try {
- const response = await client.request({
- type: "create",
- config: this.options.config,
- name: createAgentsViewSessionName(text),
- });
- const summary = expectSessionSummary(requireDaemonData(response));
- const activeSessionId = summary.activeSessionId ?? summary.id;
- await this.sendPrompt(activeSessionId, text, images);
- this.setStatusMessage("Agent started");
- await this.refreshSessions();
- this.selectedRowIdentity = getSummaryIdentity(summary);
- this.selectedActiveSessionId = activeSessionId;
- this.selectedSessionKey = getAgentsViewSelectionKey(summary);
- this.persistentState.selectedRowIdentity = this.selectedRowIdentity;
- this.persistentState.selectedSessionKey = this.selectedSessionKey;
- this.restoreSelection();
- return { summary, activeSessionId };
- } catch (error) {
- this.setStatusMessage(formatError("Failed to create agent", error));
- return undefined;
- }
- }
-
private async sendPrompt(
activeSessionId: string,
message: string,
- images?: ImageContent[],
streamingBehavior?: "steer" | "followUp",
): Promise<void> {
- const command: PromptCommand = {
- type: "prompt",
- activeSessionId,
- message,
- };
- if (images && images.length > 0) {
- command.images = images;
- }
- if (streamingBehavior) {
- command.streamingBehavior = streamingBehavior;
- }
+ const command: PromptCommand = { type: "prompt", activeSessionId, message };
+ if (streamingBehavior) command.streamingBehavior = streamingBehavior;
const response = await this.requireClient().request(command);
requireDaemonData(response);
}
- private async sendInitialPrompts(): Promise<void> {
- if (this.persistentState.initialPromptsSent) {
- return;
- }
- this.persistentState.initialPromptsSent = true;
- const initialMessages = this.options.initialMessages ?? [];
- const firstMessage = this.options.initialMessage ?? initialMessages[0];
- if (!firstMessage) {
- return;
- }
- const remainingMessages = this.options.initialMessage ? initialMessages : initialMessages.slice(1);
- const created = await this.createAgentForPrompt(firstMessage, this.options.initialImages);
- if (!created) {
- return;
- }
- const { activeSessionId } = created;
- for (const message of remainingMessages) {
- try {
- await this.sendPrompt(activeSessionId, message, undefined, "followUp");
- } catch (error) {
- this.setStatusMessage(formatError("Failed to send startup prompt", error));
- break;
- }
- }
- await this.refreshSessions();
+ private pollSessions(): void {
+ if (this.liveCatalogPollPromise) return;
+ const poll = this.refreshSessions().then(() => undefined);
+ this.liveCatalogPollPromise = poll;
+ void poll.finally(() => {
+ if (this.liveCatalogPollPromise === poll) this.liveCatalogPollPromise = undefined;
+ });
}
- private async refreshSessions(): Promise<void> {
- if (this.reconnectPromise || this.daemonShutdownReceived) {
- return;
- }
- const client = this.requireClient();
+ private async refreshSessions(options: { preserveStatusOnError?: boolean } = {}): Promise<boolean> {
+ if (this.reconnectPromise || this.daemonShutdownReceived) return false;
+ const generation = ++this.liveCatalogGeneration;
+ this.liveCatalogRefreshPending = true;
try {
- const response = await client.request(createAgentsViewListCommand());
- const data = requireDaemonData(response);
- this.applySessionList(expectSessionList(data));
- await this.sendInitialPrompts();
- } catch (error) {
- if (!this.reconnectPromise) {
- if (client.isConnected) {
- this.setStatusMessage(formatError("Failed to refresh agents", error));
- } else {
- this.startClientReconnect(client, error);
+ const client = this.requireClient();
+ try {
+ const response = await client.request(createAgentsViewListCommand());
+ if (generation !== this.liveCatalogGeneration) return false;
+ this.applySessionList(expectSessionList(requireDaemonData(response)));
+ return true;
+ } catch (error) {
+ if (!options.preserveStatusOnError && !this.reconnectPromise) {
+ if (client.isConnected) this.setStatusMessage(formatError("Failed to refresh agents", error));
+ else this.startClientReconnect(client, error);
}
+ return false;
+ }
+ } catch (error) {
+ if (generation === this.liveCatalogGeneration && !options.preserveStatusOnError) {
+ this.setStatusMessage(formatError("Failed to refresh current session", error));
+ }
+ return false;
+ } finally {
+ if (generation === this.liveCatalogGeneration) {
+ this.liveCatalogRefreshPending = false;
+ this.resolveMissingSelectionAnchor();
}
}
}
private applySessionList(sessions: SessionSummary[]): void {
this.lastListedSummaries = sessions;
- const visibleSessions = sessions.filter((summary) =>
+ this.reconcileCatalogs();
+ }
+
+ private reconcileCatalogs(): void {
+ const visibleSessions = this.lastListedSummaries.filter((summary) =>
shouldShowAgentsViewSession(summary, this.inactiveAgentIdentities.has(getSummaryIdentity(summary))),
);
this.lastVisibleSummaries = this.withPendingDeleteSession(visibleSessions);
+ this.unifiedRecords = reconcileUnifiedSessions(this.lastVisibleSummaries, this.savedSessions, this.heartbeats);
this.rows = buildAgentsViewRows(
- this.lastVisibleSummaries,
+ this.getFilteredRecords(),
this.expandedSubagentParents,
this.programShownParents,
);
@@ -1911,9 +1958,91 @@ class AgentsViewMode implements Component, Focusable {
this.ui.requestRender();
}
+ /** A session appears in both catalogs; mutations must refresh both. */
+ private async refreshBothCatalogs(): Promise<boolean> {
+ const results = await Promise.all([
+ this.refreshSessions({ preserveStatusOnError: true }),
+ this.refreshSavedSessions({ preserveStatusOnError: true }),
+ ]);
+ return results.every(Boolean);
+ }
+
+ private async refreshSavedSessions(
+ options: { duringReconnect?: boolean; preserveStatusOnError?: boolean } = {},
+ ): Promise<boolean> {
+ if ((!options.duringReconnect && this.reconnectPromise) || this.daemonShutdownReceived) return false;
+ const generation = ++this.savedCatalogGeneration;
+ this.persistentState.savedCatalogGeneration = generation;
+ this.savedCatalogRefreshPending = true;
+ const successfulSessions = this.lastSuccessfulSavedSessions;
+ const progressiveSessions = new Map(
+ successfulSessions.map((session) => [resolvePath(canonicalizePath(session.path)), session]),
+ );
+ try {
+ 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();
+ };
+ const sessions = await listDaemonSavedSessions(
+ this.requireClient(),
+ this.getSavedSessionCatalogContext(),
+ "all",
+ {
+ onSession,
+ },
+ );
+ if (generation !== this.savedCatalogGeneration) return false;
+ this.savedSessions = sessions;
+ this.lastSuccessfulSavedSessions = sessions;
+ this.persistentState.lastSuccessfulSavedSessions = sessions;
+ this.persistentState.savedSessions = sessions;
+ this.reconcileCatalogs();
+ return true;
+ } catch (error) {
+ if (generation === this.savedCatalogGeneration) {
+ this.savedSessions = successfulSessions;
+ this.persistentState.savedSessions = successfulSessions;
+ this.reconcileCatalogs();
+ if (!options.preserveStatusOnError && !this.reconnectPromise && !this.daemonShutdownReceived) {
+ this.setStatusMessage(formatError("Failed to load saved sessions", error));
+ }
+ }
+ return false;
+ } finally {
+ if (generation === this.savedCatalogGeneration) {
+ this.savedCatalogRefreshPending = false;
+ this.resolveMissingSelectionAnchor();
+ }
+ }
+ }
+
+ private async refreshHeartbeats(options: { duringReconnect?: boolean } = {}): Promise<boolean> {
+ if ((!options.duringReconnect && this.reconnectPromise) || this.daemonShutdownReceived) return false;
+ const generation = ++this.heartbeatCatalogGeneration;
+ try {
+ const heartbeats = await listDaemonHeartbeats(this.requireClient());
+ if (generation !== this.heartbeatCatalogGeneration) return false;
+ this.heartbeats = heartbeats;
+ this.persistentState.heartbeats = heartbeats;
+ this.reconcileCatalogs();
+ return true;
+ } catch (error) {
+ if (generation === this.heartbeatCatalogGeneration && !this.reconnectPromise) {
+ this.setStatusMessage(formatError("Failed to refresh heartbeats", error));
+ }
+ return false;
+ }
+ }
+
private withPendingDeleteSession(sessions: readonly SessionSummary[]): SessionSummary[] {
const pending = this.pendingDeleteAgent;
- if (!pending) {
+ // Saved-only rows already come from the durable catalog. Injecting their
+ // synthetic archived summary as a daemon record would move confirmation
+ // from Inactive to Idle.
+ if (!pending || pending.summary.lifecycle !== "live") {
return [...sessions];
}
if (!this.isDeleteConfirmationVisible()) {
@@ -1930,27 +2059,46 @@ class AgentsViewMode implements Component, Focusable {
return replaced ? merged : [...merged, pending.summary];
}
+ private resolveMissingSelectionAnchor(): void {
+ if (!this.selectionAnchorPending || this.liveCatalogRefreshPending || this.savedCatalogRefreshPending) {
+ return;
+ }
+ // Unblock the fallback row, but keep the anchor identities: a later poll
+ // can still deliver the intended session and re-anchor selection to it.
+ this.selectionAnchorPending = false;
+ const row = this.rows[this.selectedIndex];
+ this.selectedActiveSessionId = row?.selectable ? (row.summary.activeSessionId ?? row.summary.id) : undefined;
+ }
+
private restoreSelection(): void {
if (this.rows.length === 0) {
this.selectedIndex = 0;
this.selectedActiveSessionId = undefined;
return;
}
- const index = this.findSelectedRowIndex();
- if (index >= 0) {
- this.selectedIndex = index;
- } else if (!this.rows[this.selectedIndex]?.selectable) {
- this.selectedIndex = this.getSelectableRowIndexes()[0] ?? 0;
- } else {
- this.selectedIndex = Math.min(this.selectedIndex, this.rows.length - 1);
+ const resolution = resolveAgentsViewSelectionState(
+ this.rows,
+ this.selectedIndex,
+ this.selectedRowIdentity ?? this.persistentState.selectedRowIdentity,
+ this.selectedSessionKey ?? this.persistentState.selectedSessionKey,
+ );
+ this.selectedIndex = resolution.index;
+ if (resolution.resolved) {
+ this.syncSelectedRowState();
+ return;
}
- this.syncSelectedRowState();
- }
-
- private findSelectedRowIndex(): number {
- const identity = this.selectedRowIdentity ?? this.persistentState.selectedRowIdentity;
- const key = this.selectedSessionKey ?? this.persistentState.selectedSessionKey;
- return resolveAgentsViewSelectionIndex(this.rows, identity, key);
+ this.selectionAnchorPending = Boolean(
+ this.selectedRowIdentity ??
+ this.persistentState.selectedRowIdentity ??
+ this.selectedSessionKey ??
+ this.persistentState.selectedSessionKey,
+ );
+ // Catalogs stream independently. Show a temporary fallback row without
+ // replacing the source-session anchor before its daemon row arrives.
+ const fallback = this.rows[this.selectedIndex];
+ this.selectedActiveSessionId = fallback?.selectable
+ ? (fallback.summary.activeSessionId ?? fallback.summary.id)
+ : undefined;
}
private getSelectableRowIndexes(): number[] {
@@ -1958,6 +2106,7 @@ class AgentsViewMode implements Component, Focusable {
}
private syncSelectedRowState(): void {
+ this.selectionAnchorPending = false;
const row = this.rows[this.selectedIndex];
this.selectedActiveSessionId = row?.selectable ? (row.summary.activeSessionId ?? row.summary.id) : undefined;
this.selectedRowIdentity = getSelectedRowIdentity(row);
@@ -1971,10 +2120,17 @@ class AgentsViewMode implements Component, Focusable {
return;
}
this.stopped = true;
+ this.savedCatalogGeneration += 1;
+ this.liveCatalogGeneration += 1;
+ this.heartbeatCatalogGeneration += 1;
if (this.pollTimer) {
clearInterval(this.pollTimer);
this.pollTimer = undefined;
}
+ if (this.heartbeatPollTimer) {
+ clearInterval(this.heartbeatPollTimer);
+ this.heartbeatPollTimer = undefined;
+ }
if (this.animationTimer) {
clearInterval(this.animationTimer);
this.animationTimer = undefined;
@@ -1989,6 +2145,8 @@ class AgentsViewMode implements Component, Focusable {
stopThemeWatcher();
this.unsubscribeClientClose?.();
this.unsubscribeClientClose = undefined;
+ this.unsubscribeClientMessage?.();
+ this.unsubscribeClientMessage = undefined;
this.client?.close();
this.client = undefined;
this.resolveRun?.(result);
@@ -2044,11 +2202,13 @@ class AgentsViewMode implements Component, Focusable {
const response = await client.request(createAgentsViewListCommand());
const data = requireDaemonData(response);
const sessions = expectSessionList(data);
+ const heartbeatsRefreshed = await this.refreshHeartbeats({ duringReconnect: true });
+ if (!heartbeatsRefreshed) throw new Error("Heartbeat catalog did not refresh during reconnect");
this.daemonShutdownReceived = false;
this.reconnectTimedOut = false;
this.setStatusMessage("Daemon reconnected", { render: false });
this.applySessionList(sessions);
- await this.sendInitialPrompts();
+ void this.refreshSavedSessions({ duringReconnect: true, preserveStatusOnError: true });
return;
} catch (error) {
lastError = error;
@@ -2069,6 +2229,11 @@ class AgentsViewMode implements Component, Focusable {
}
}
+ private requireSocketPath(): string {
+ if (!this.options.socketPath) throw new Error("Session view daemon socket is not configured");
+ return this.options.socketPath;
+ }
+
private requireClient(): DaemonClient {
if (!this.client) {
throw new Error("Agents view daemon client is not connected");
@@ -2078,16 +2243,7 @@ class AgentsViewMode implements Component, Focusable {
private getAgentCountsText(): string {
const counts = countRowsBySection(this.rows);
- const parts: string[] = [];
- if (counts["needs-input"] > 0) {
- parts.push(`${counts["needs-input"]} needs input`);
- }
- parts.push(`${counts.working} working`);
- if (counts.heartbeats > 0) {
- parts.push(`${counts.heartbeats} heartbeats`);
- }
- parts.push(`${counts.completed} completed`);
- return parts.join(", ");
+ return `${counts.running} running, ${counts.idle} idle, ${counts.inactive} inactive`;
}
private renderSessionRows(width: number, maxRows: number): string[] {
@@ -2095,10 +2251,10 @@ class AgentsViewMode implements Component, Focusable {
return [];
}
if (this.rows.length === 0) {
- return [
- theme.bold(sectionTitle("working")),
- theme.fg("dim", " No agents yet. Describe a task below to start one."),
- ].slice(0, maxRows);
+ return [theme.bold(sectionTitle("running")), theme.fg("dim", " No sessions match your search.")].slice(
+ 0,
+ maxRows,
+ );
}
const displayItems = buildDisplayItems(this.rows);
@@ -2159,8 +2315,21 @@ class AgentsViewMode implements Component, Focusable {
const rawIcon = this.getRowIcon(row.section);
const icon = this.formatRowIcon(row.section, rawIcon);
const indent = " ".repeat(row.depth);
- const timeWidth = 10;
- const titleWidth = Math.max(0, width - visibleWidth(indent) - visibleWidth(rawIcon) - timeWidth - 2);
+ const age = formatSessionDuration(row.summary);
+ const details = row.section === "inactive" ? `${row.summary.messageCount} · ${age}` : age;
+ const detailsWidth = row.section === "inactive" ? Math.max(10, visibleWidth(details)) : 10;
+ const heartbeatBadge = !pendingDelete && !pendingKill ? formatHeartbeatBadge(row.heartbeat) : "";
+ const heartbeatCell = heartbeatBadge ? theme.fg("error", heartbeatBadge) : "";
+ const heartbeatWidth = visibleWidth(heartbeatBadge);
+ const titleWidth = Math.max(
+ 0,
+ width -
+ visibleWidth(indent) -
+ visibleWidth(rawIcon) -
+ detailsWidth -
+ 2 -
+ (heartbeatWidth > 0 ? heartbeatWidth + 1 : 0),
+ );
const title = pendingDelete
? this.getPendingDeleteTitle()
: pendingKill
@@ -2175,9 +2344,9 @@ class AgentsViewMode implements Component, Focusable {
const cells = [
icon,
pendingDelete || pendingKill ? theme.fg("error", titleCell) : titleCell,
- formatRightTableCell(formatSessionDuration(row.summary), timeWidth),
+ formatRightTableCell(details, detailsWidth),
];
- const base = `${indent}${cells[0]} ${cells[1]} ${cells[2]}`;
+ 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;
}
@@ -2236,9 +2405,7 @@ class AgentsViewMode implements Component, Focusable {
private renderDock(width: number): string[] {
const safeWidth = Math.max(1, width);
- return [...this.renderPrompt(safeWidth), this.renderHints(safeWidth)].map((line) =>
- this.finalizeRenderedLine(line, safeWidth),
- );
+ return [this.renderHints(safeWidth)].map((line) => this.finalizeRenderedLine(line, safeWidth));
}
private renderHints(width: number): string {
@@ -2254,27 +2421,49 @@ class AgentsViewMode implements Component, Focusable {
const hint = `${keyText("tui.select.confirm")} save ${keyText("tui.select.cancel")} cancel`;
return truncateToWidth(theme.fg("muted", hint), width);
}
+ if (this.replyTarget) {
+ return truncateToWidth(theme.fg("muted", this.renderReplyComposerHints()), width);
+ }
// Replying is reserved for top-level agents; subagents can be stopped.
const selectedRow = this.rows[this.selectedIndex];
const selectedAgent = selectedRow?.kind === "agent";
const selectedSubagent = selectedRow?.kind === "subagent";
const hints = [
`${keyText("tui.select.up")}/${keyText("tui.select.down")} move`,
- `${keyText("tui.select.confirm")} open/send`,
+ `${keyText("tui.select.confirm")} open`,
`${keyText("app.agents.open")} open`,
- "/ commands",
- selectedAgent ? `${keyText("app.agents.reply")} reply` : undefined,
+ selectedAgent
+ ? `${keyText("app.agents.reply")} ${selectedRow?.section === "inactive" ? "resume" : "reply"}`
+ : undefined,
+ `${keyText("app.agents.new")} new`,
selectedAgent ? `${keyText("app.agents.rename")} rename` : undefined,
- selectedAgent ? `${keyText("app.agents.delete")} stop/deactivate` : undefined,
+ selectedAgent
+ ? `${keyText("app.agents.delete")} ${selectedRow?.section === "inactive" ? "delete" : "stop/deactivate"}`
+ : undefined,
selectedSubagent ? `${keyText("app.agents.delete")} stop` : undefined,
this.selectedRowCanShowProgram() ? `${keyText("app.agents.program")} program` : undefined,
- this.replyActiveSessionId ? `${keyText("app.agents.back")} back` : undefined,
]
.filter((hint): hint is string => hint !== undefined)
.join(" ");
return truncateToWidth(theme.fg("muted", hints), width);
}
+ private renderReplyComposerHints(): string {
+ const target = this.replyTarget!;
+ const current = resolveCurrentReplyTargetSummary(this.unifiedRecords ?? [], target, (activeSessionId) =>
+ this.findSummaryByActiveSessionId(activeSessionId),
+ );
+ const streaming = current.activeSessionId !== undefined && current.isStreaming;
+ const hasText = this.editor.getText().trim().length > 0;
+ return [
+ `${keyText("tui.select.confirm")} ${streaming ? "steer" : current.activeSessionId ? "send" : "resume & send"}`,
+ hasText ? `${keyText("app.message.followUp")} queue` : undefined,
+ `${keyText("tui.select.cancel")} cancel`,
+ ]
+ .filter((hint): hint is string => hint !== undefined)
+ .join(" ");
+ }
+
private visibleListRows(): number {
return Math.max(4, this.ui.terminal.rows - 9);
}
@@ -2295,13 +2484,11 @@ class AgentsViewMode implements Component, Focusable {
private getRowIcon(section: AgentsViewSection): string {
switch (section) {
- case "working":
+ case "running":
return workingIconFrame(this.workingIconFrame);
- case "needs-input":
+ case "idle":
return NEEDS_INPUT_ROW_ICON;
- case "heartbeats":
- return HEARTBEAT_ROW_ICON;
- case "completed":
+ case "inactive":
return COMPLETED_ROW_ICON;
default: {
const _exhaustive: never = section;
@@ -2312,14 +2499,12 @@ class AgentsViewMode implements Component, Focusable {
private formatRowIcon(section: AgentsViewSection, icon: string): string {
switch (section) {
- case "working":
+ case "running":
return theme.bold(icon);
- case "needs-input":
+ case "idle":
return theme.fg("warning", icon);
- case "heartbeats":
- return theme.fg("error", icon);
- case "completed":
- return theme.fg("success", icon);
+ case "inactive":
+ return theme.fg("dim", icon);
default: {
const _exhaustive: never = section;
return _exhaustive;
@@ -2336,7 +2521,7 @@ type DisplayItem =
function buildDisplayItems(rows: readonly AgentsViewRow[]): DisplayItem[] {
const items: DisplayItem[] = [];
- const sections: AgentsViewSection[] = ["needs-input", "working", "heartbeats", "completed"];
+ const sections: AgentsViewSection[] = ["running", "idle", "inactive"];
for (const [index, section] of sections.entries()) {
if (index > 0) {
items.push({ type: "spacer" });
@@ -2373,10 +2558,9 @@ function getDisplayRowsForSection(rows: readonly AgentsViewRow[], section: Agent
function countRowsBySection(rows: readonly AgentsViewRow[]): Record<AgentsViewSection, number> {
const agents = rows.filter((row) => row.kind === "agent");
return {
- working: agents.filter((row) => row.section === "working").length,
- "needs-input": agents.filter((row) => row.section === "needs-input").length,
- heartbeats: agents.filter((row) => row.section === "heartbeats").length,
- completed: agents.filter((row) => row.section === "completed").length,
+ running: agents.filter((row) => row.section === "running").length,
+ idle: agents.filter((row) => row.section === "idle").length,
+ inactive: agents.filter((row) => row.section === "inactive").length,
};
}
@@ -2393,35 +2577,6 @@ function isRunningSessionSummary(summary: SessionSummary): boolean {
return summary.activity === "working";
}
-export function resolveAgentsViewAutocompleteCwd(initialCwd: string, replyTarget?: SessionSummary): string {
- const replyCwd = replyTarget?.cwd;
- return replyCwd && existsSync(replyCwd) ? replyCwd : initialCwd;
-}
-
-export function createAgentsViewAutocompleteProvider(
- cwd: string,
- fdPath: string | undefined,
- getModelArgumentCompletions: NonNullable<SlashCommand["getArgumentCompletions"]>,
-): CombinedAutocompleteProvider {
- const commands: SlashCommand[] = AGENTS_VIEW_SLASH_COMMANDS.map((command) => ({
- name: command.name,
- description: command.description,
- ...(command.argumentHint ? { argumentHint: command.argumentHint } : {}),
- }));
- const modelCommand = commands.find((command) => command.name === "model");
- if (modelCommand) {
- modelCommand.getArgumentCompletions = getModelArgumentCompletions;
- }
- return new CombinedAutocompleteProvider(commands, cwd, fdPath ?? null);
-}
-
-export function createAgentsViewSessionName(text: string): string {
- const normalized = text.replace(/\s+/g, " ").trim();
- return normalized.length > SESSION_NAME_MAX_LENGTH
- ? `${normalized.slice(0, SESSION_NAME_MAX_LENGTH - 3)}...`
- : normalized;
-}
-
function formatTableCell(value: string, width: number): string {
const truncated = truncateToWidth(value, width, "");
return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));
@@ -2433,7 +2588,9 @@ function formatRightTableCell(value: string, width: number): string {
}
function formatSessionDuration(summary: SessionSummary): string {
- return formatAgentsViewRelativeTime(summary.created ?? summary.modified);
+ return formatAgentsViewRelativeTime(
+ summary.activeSessionId ? (summary.created ?? summary.modified) : (summary.modified ?? summary.created),
+ );
}
export function formatAgentsViewRelativeTime(value: string | undefined, now: number = Date.now()): string {
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 7730fc2431..bd99ba3e14 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,26 @@
-import { basename } from "node:path";
+import { basename, resolve } from "node:path";
+import { canonicalizePath } from "../../utils/paths.js";
+import type { AgentConnectionHeartbeat, AgentConnectionSavedSessionInfo } from "../agent-connection/index.js";
import type { SessionSummary } from "../daemon/daemon-session-list.js";
-export type AgentsViewSection = "working" | "needs-input" | "heartbeats" | "completed";
+export type AgentsViewSection = "running" | "idle" | "inactive";
+
+export interface UnifiedSessionHeartbeat {
+ activeCount: number;
+ nextRunAt?: string;
+}
+
+export interface UnifiedSessionRecord {
+ daemon?: SessionSummary;
+ saved?: AgentConnectionSavedSessionInfo;
+ /** Stable UI key, chosen using canonical path, session id, then active id. */
+ identity: string;
+ /** Alternate keys used to restore selection while a session is persisted or reattached. */
+ identityAliases: readonly string[];
+ section: AgentsViewSection;
+ searchableText: string;
+ heartbeat?: UnifiedSessionHeartbeat;
+}
export type AgentsViewRowKind = "agent" | "subagent-summary" | "subagent" | "subagent-code";
@@ -26,17 +45,37 @@ export interface AgentsViewRow {
hasSpawnCode?: boolean;
/** One source line of the spawn cell, for "subagent-code" rows. */
code?: string;
+ /** Merged durable/live source data for unified rows. */
+ record?: UnifiedSessionRecord;
+ heartbeat?: UnifiedSessionHeartbeat;
}
export function classifyAgentsViewSession(summary: SessionSummary): AgentsViewSection {
- if (summary.hasActiveHeartbeat) {
- return "heartbeats";
+ if (summary.hasActiveHeartbeat || summary.activity === "working" || isAgentsViewSessionBusy(summary)) {
+ return "running";
}
- if (summary.activity === "working") {
- return "working";
+ return "idle";
+}
+
+function isAgentsViewSessionBusy(summary: SessionSummary): boolean {
+ return (
+ summary.isStreaming ||
+ summary.isCompacting ||
+ summary.isBashRunning === true ||
+ summary.isRunningTools === true ||
+ summary.hasRunningRlmChildren === true ||
+ summary.pendingMessageCount > 0
+ );
+}
+
+export function classifyUnifiedSession(record: Pick<UnifiedSessionRecord, "daemon" | "heartbeat">): AgentsViewSection {
+ if (!record.daemon) {
+ return "inactive";
+ }
+ if ((record.heartbeat?.activeCount ?? 0) > 0) {
+ return "running";
}
- // Idle defaults to Needs Input; only an explicit completed verdict moves it on.
- return summary.taskState === "completed" ? "completed" : "needs-input";
+ return classifyAgentsViewSession(record.daemon);
}
// Live sessions only; drafts and archived stay out.
@@ -49,14 +88,12 @@ export function shouldShowAgentsViewSession(summary: SessionSummary, manuallyIna
export function sectionTitle(section: AgentsViewSection): string {
switch (section) {
- case "working":
- return "Working";
- case "needs-input":
- return "Needs Input";
- case "heartbeats":
- return "Heartbeats";
- case "completed":
- return "Completed";
+ case "running":
+ return "Running";
+ case "idle":
+ return "Idle";
+ case "inactive":
+ return "Inactive";
default: {
const _exhaustive: never = section;
return _exhaustive;
@@ -64,9 +101,261 @@ export function sectionTitle(section: AgentsViewSection): string {
}
}
+function canonicalSessionPath(path: string): string {
+ return resolve(canonicalizePath(path));
+}
+
+function fileIdentity(path: string): string {
+ return `file:${canonicalSessionPath(path)}`;
+}
+
+function summaryIdentityAliases(summary: SessionSummary): string[] {
+ return [
+ summary.sessionFile ? fileIdentity(summary.sessionFile) : undefined,
+ `session:${summary.sessionId}`,
+ summary.activeSessionId ? `active:${summary.activeSessionId}` : undefined,
+ `active:${summary.id}`,
+ ].filter((identity): identity is string => identity !== undefined);
+}
+
+function savedIdentityAliases(saved: AgentConnectionSavedSessionInfo): string[] {
+ return [fileIdentity(saved.path), `session:${saved.id}`];
+}
+
+function createUnifiedSearchableText(
+ daemon: SessionSummary | undefined,
+ saved: AgentConnectionSavedSessionInfo | undefined,
+): string {
+ return [
+ daemon?.sessionId,
+ daemon?.activeSessionId,
+ daemon?.sessionName,
+ daemon?.firstMessage,
+ daemon?.cwd,
+ daemon?.sessionFile,
+ daemon?.summary,
+ saved?.id,
+ saved?.name,
+ saved?.firstMessage,
+ saved?.allMessagesText,
+ saved?.agentStatus?.summary,
+ saved?.cwd,
+ saved?.path,
+ saved?.parentSessionPath,
+ ]
+ .filter((part): part is string => typeof part === "string" && part.length > 0)
+ .join(" ");
+}
+
+/**
+ * Reconcile daemon-resident and saved catalog rows without inventing runtime
+ * ancestry from persisted fork metadata. Daemon data remains authoritative;
+ * saved data only enriches durable/search fields.
+ */
+export function reconcileUnifiedSessions(
+ daemonSummaries: readonly SessionSummary[],
+ savedSessions: readonly AgentConnectionSavedSessionInfo[],
+ heartbeats: readonly AgentConnectionHeartbeat[] = [],
+): UnifiedSessionRecord[] {
+ const heartbeatByActiveId = aggregateSessionHeartbeats(daemonSummaries, heartbeats);
+ const records: UnifiedSessionRecord[] = [];
+ const recordByAlias = new Map<string, UnifiedSessionRecord>();
+
+ for (const daemon of daemonSummaries) {
+ const aliases = summaryIdentityAliases(daemon);
+ const heartbeat =
+ heartbeatByActiveId.get(daemon.activeSessionId ?? daemon.id) ??
+ (daemon.hasActiveHeartbeat ? { activeCount: 1 } : undefined);
+ const record: UnifiedSessionRecord = {
+ daemon: heartbeat && !daemon.hasActiveHeartbeat ? { ...daemon, hasActiveHeartbeat: true } : daemon,
+ identity: aliases[0]!,
+ identityAliases: aliases,
+ section: "idle",
+ searchableText: "",
+ ...(heartbeat ? { heartbeat } : {}),
+ };
+ record.section = classifyUnifiedSession(record);
+ record.searchableText = createUnifiedSearchableText(daemon, undefined);
+ records.push(record);
+ for (const alias of aliases) recordByAlias.set(alias, record);
+ }
+
+ for (const saved of savedSessions) {
+ const aliases = savedIdentityAliases(saved);
+ const record = aliases.map((alias) => recordByAlias.get(alias)).find(Boolean);
+ if (record) {
+ record.saved = saved;
+ record.identityAliases = [...new Set([...record.identityAliases, ...aliases])];
+ record.searchableText = createUnifiedSearchableText(record.daemon, saved);
+ for (const alias of aliases) recordByAlias.set(alias, record);
+ continue;
+ }
+ const inactive: UnifiedSessionRecord = {
+ saved,
+ identity: aliases[0]!,
+ identityAliases: aliases,
+ section: "inactive",
+ searchableText: createUnifiedSearchableText(undefined, saved),
+ };
+ records.push(inactive);
+ for (const alias of aliases) recordByAlias.set(alias, inactive);
+ }
+ return records;
+}
+
+/** Convert a merged row to the existing live-row rendering/action shape. */
+export function summaryForUnifiedRecord(record: UnifiedSessionRecord): SessionSummary {
+ if (record.daemon) {
+ const saved = record.saved;
+ if (!saved) return record.daemon;
+ return {
+ ...record.daemon,
+ sessionName: record.daemon.sessionName ?? saved.name,
+ firstMessage: record.daemon.firstMessage ?? saved.firstMessage,
+ sessionFile: record.daemon.sessionFile ?? canonicalSessionPath(saved.path),
+ created: record.daemon.created ?? saved.created.toISOString(),
+ modified: record.daemon.modified ?? saved.modified.toISOString(),
+ };
+ }
+ const saved = record.saved;
+ if (!saved) throw new Error("Unified session record has no daemon or saved source");
+ return {
+ id: saved.id,
+ lifecycle: "archived",
+ activity: "idle",
+ sessionId: saved.id,
+ sessionFile: canonicalSessionPath(saved.path),
+ sessionName: saved.name,
+ cwd: saved.cwd,
+ isStreaming: false,
+ isCompacting: false,
+ attachedClients: 0,
+ messageCount: saved.messageCount,
+ pendingMessageCount: 0,
+ created: saved.created.toISOString(),
+ modified: saved.modified.toISOString(),
+ firstMessage: saved.firstMessage,
+ summary: saved.agentStatus?.summary,
+ taskState: saved.agentStatus?.taskState,
+ };
+}
+
+export function filterUnifiedSessions(
+ records: readonly UnifiedSessionRecord[],
+ matches: (searchableText: string) => boolean,
+): UnifiedSessionRecord[] {
+ const recordsByKey = new Map<string, UnifiedSessionRecord>();
+ for (const record of records) {
+ for (const key of record.identityAliases) recordsByKey.set(key, record);
+ }
+
+ const retained = new Set<UnifiedSessionRecord>();
+ for (const record of records) {
+ if (!matches(record.searchableText)) continue;
+ let current: UnifiedSessionRecord | undefined = record;
+ while (current && !retained.has(current)) {
+ retained.add(current);
+ current = findParentRecord(current, recordsByKey);
+ }
+ }
+ // Keep catalog order and the original records so row ranking and sections
+ // remain authoritative while ancestors provide the hierarchy for matches.
+ return records.filter((record) => retained.has(record));
+}
+
+function findParentRecord(
+ record: UnifiedSessionRecord,
+ byKey: ReadonlyMap<string, UnifiedSessionRecord>,
+): UnifiedSessionRecord | undefined {
+ // Only live daemon summaries carry parent links; saved-only rows are roots.
+ if (!record.daemon) return undefined;
+ for (const key of getParentKeys(record.daemon)) {
+ const parent = byKey.get(key);
+ if (parent) return parent;
+ }
+ return undefined;
+}
+
+export function aggregateSessionHeartbeats(
+ summaries: readonly SessionSummary[],
+ heartbeats: readonly AgentConnectionHeartbeat[],
+): ReadonlyMap<string, UnifiedSessionHeartbeat> {
+ const summaryByKey = new Map<string, SessionSummary>();
+ for (const summary of summaries) {
+ for (const key of getSummaryKeys(summary)) summaryByKey.set(key, summary);
+ }
+ const jobIdsByOwner = new Map<string, Set<string>>();
+ const nextRunByJob = new Map<string, string>();
+ const add = (owner: string, jobId: string): void => {
+ const ids = jobIdsByOwner.get(owner) ?? new Set<string>();
+ ids.add(jobId);
+ jobIdsByOwner.set(owner, ids);
+ };
+ for (const heartbeat of heartbeats) {
+ const job = heartbeat.job;
+ if (job.status !== "active") continue;
+ if (job.nextRunAt && Number.isFinite(Date.parse(job.nextRunAt))) nextRunByJob.set(job.id, job.nextRunAt);
+ let summary = summaryByKey.get(`active:${job.activeSessionId}`);
+ const visited = new Set<string>();
+ if (!summary) add(job.activeSessionId, job.id);
+ while (summary) {
+ const owner = summary.activeSessionId ?? summary.id;
+ if (visited.has(owner)) break;
+ visited.add(owner);
+ add(owner, job.id);
+ summary = findParentSummary(summary, summaryByKey);
+ }
+ }
+ const result = new Map<string, UnifiedSessionHeartbeat>();
+ for (const [owner, jobIds] of jobIdsByOwner) {
+ const nextRunAt = [...jobIds]
+ .map((jobId) => nextRunByJob.get(jobId))
+ .filter((value): value is string => value !== undefined)
+ .sort((a, b) => Date.parse(a) - Date.parse(b))[0];
+ result.set(owner, { activeCount: jobIds.size, ...(nextRunAt ? { nextRunAt } : {}) });
+ }
+ return result;
+}
+
+export function formatHeartbeatBadge(heartbeat: UnifiedSessionHeartbeat | undefined, now = Date.now()): string {
+ if (!heartbeat || heartbeat.activeCount < 1) return "";
+ const next = heartbeat.nextRunAt ? Date.parse(heartbeat.nextRunAt) : Number.NaN;
+ const countdown = Number.isFinite(next) ? formatHeartbeatCountdown(next - now) : undefined;
+ return `♥ ${heartbeat.activeCount}${countdown ? `·${countdown}` : ""}`;
+}
+
+function formatHeartbeatCountdown(durationMs: number): string {
+ const seconds = Math.max(1, Math.round(Math.max(0, durationMs) / 1000));
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.round(seconds / 60);
+ if (minutes < 60) return `${minutes}m`;
+ const hours = Math.round(minutes / 60);
+ if (hours < 24) return `${hours}h`;
+ return `${Math.round(hours / 24)}d`;
+}
+
+function findParentSummary(
+ summary: SessionSummary,
+ byKey: ReadonlyMap<string, SessionSummary>,
+): SessionSummary | undefined {
+ for (const key of getParentKeys(summary)) {
+ const parent = byKey.get(key);
+ if (parent) return parent;
+ }
+ return undefined;
+}
+
+function getParentKeys(summary: SessionSummary): string[] {
+ return [
+ summary.parentActiveSessionId ? `active:${summary.parentActiveSessionId}` : undefined,
+ summary.parentSessionId ? `session:${summary.parentSessionId}` : undefined,
+ summary.parentSessionPath ? fileIdentity(summary.parentSessionPath) : undefined,
+ ].filter((key): key is string => key !== undefined);
+}
+
export function getAgentsViewSummaryIdentity(summary: SessionSummary): string {
if (summary.sessionFile) {
- return `file:${summary.sessionFile}`;
+ return fileIdentity(summary.sessionFile);
}
if (summary.activeSessionId) {
return `active:${summary.activeSessionId}`;
@@ -96,7 +385,9 @@ export function resolveAgentsViewSelectionIndex(
if (identity !== undefined) {
const index = findSelectable((row) => row.identity === identity);
- if (index >= 0) {
+ // Synthetic nested rows deliberately reuse their parent's session key, so
+ // their exact row identity must win over the active-runtime fallback.
+ if (index >= 0 && rows[index]?.kind !== "agent") {
return index;
}
}
@@ -107,6 +398,12 @@ export function resolveAgentsViewSelectionIndex(
return index;
}
}
+ if (identity !== undefined) {
+ const index = findSelectable((row) => row.identity === identity);
+ if (index >= 0) {
+ return index;
+ }
+ }
if (key?.sessionId !== undefined) {
const sessionId = key.sessionId;
return findSelectable((row) => row.summary.sessionId === sessionId);
@@ -114,15 +411,38 @@ export function resolveAgentsViewSelectionIndex(
return -1;
}
+export interface AgentsViewSelectionResolution {
+ index: number;
+ resolved: boolean;
+}
+
+export function resolveAgentsViewSelectionState(
+ rows: readonly AgentsViewRow[],
+ currentIndex: number,
+ identity: string | undefined,
+ key: AgentsViewSelectionKey | undefined,
+): AgentsViewSelectionResolution {
+ if (rows.length === 0) return { index: 0, resolved: false };
+ const resolvedIndex = resolveAgentsViewSelectionIndex(rows, identity, key);
+ if (resolvedIndex >= 0) return { index: resolvedIndex, resolved: true };
+ const boundedIndex = Math.max(0, Math.min(currentIndex, rows.length - 1));
+ if (rows[boundedIndex]?.selectable) return { index: boundedIndex, resolved: false };
+ const firstSelectable = rows.findIndex((row) => row.selectable);
+ return { index: firstSelectable >= 0 ? firstSelectable : 0, resolved: false };
+}
+
export function buildAgentsViewRows(
- summaries: readonly SessionSummary[],
+ summariesOrRecords: readonly (SessionSummary | UnifiedSessionRecord)[],
expandedSubagentParents: ReadonlySet<string> = new Set(),
programShownParents: ReadonlySet<string> = new Set(),
): AgentsViewRow[] {
- const baseRows = summaries.map(
- (summary): MutableAgentsViewRow => ({
+ const inputs = summariesOrRecords.map((input) =>
+ isUnifiedSessionRecord(input) ? { summary: summaryForUnifiedRecord(input), record: input } : { summary: input },
+ );
+ const baseRows = inputs.map(
+ ({ summary, record }): MutableAgentsViewRow => ({
kind: isSubagentSummary(summary) ? "subagent" : "agent",
- section: classifyAgentsViewSession(summary),
+ section: record?.section ?? classifyAgentsViewSession(summary),
summary,
title: getSessionTitle(summary),
subtitle: getSessionSubtitle(summary),
@@ -130,7 +450,8 @@ export function buildAgentsViewRows(
depth: 0,
selectable: true,
runningSubagentCount: 0,
- identity: getAgentsViewSummaryIdentity(summary),
+ identity: record?.identity ?? getAgentsViewSummaryIdentity(summary),
+ ...(record ? { record, heartbeat: record.heartbeat } : {}),
}),
);
const rowsByKey = buildRowKeyMap(baseRows);
@@ -148,7 +469,7 @@ export function buildAgentsViewRows(
continue;
}
parentByChild.set(row, parent);
- if (row.summary.activity === "working" || row.summary.hasActiveHeartbeat) {
+ if (row.section === "running") {
parent.runningSubagentCount += 1;
}
const siblings = childrenByParent.get(parent) ?? [];
@@ -191,6 +512,10 @@ export function buildAgentsViewRows(
return flattened;
}
+function isUnifiedSessionRecord(value: SessionSummary | UnifiedSessionRecord): value is UnifiedSessionRecord {
+ return "identityAliases" in value;
+}
+
function propagateHeartbeatStateToAncestors(
rows: readonly MutableAgentsViewRow[],
parentByChild: ReadonlyMap<MutableAgentsViewRow, MutableAgentsViewRow>,
@@ -203,7 +528,7 @@ function propagateHeartbeatStateToAncestors(
let ancestor = parentByChild.get(row);
while (ancestor && !visited.has(ancestor)) {
visited.add(ancestor);
- ancestor.section = "heartbeats";
+ ancestor.section = "running";
ancestor.statusLabel = getSessionStatusLabel(ancestor.summary, true);
ancestor = parentByChild.get(ancestor);
}
@@ -220,7 +545,9 @@ function createSubagentSummaryRow(
): AgentsViewRow {
const totalCount = children.length;
const running = parent.runningSubagentCount;
- const heartbeatCount = children.filter((child) => child.summary.hasActiveHeartbeat).length;
+ const heartbeatCount = children.filter(
+ (child) => child.summary.hasActiveHeartbeat || (child.heartbeat?.activeCount ?? 0) > 0,
+ ).length;
// Finished subagents stay reachable through the summary row even when
// nothing is running anymore.
const subagentTitle =
@@ -337,9 +664,9 @@ function buildRowKeyMap(rows: readonly MutableAgentsViewRow[]): Map<string, Muta
function getSummaryKeys(summary: SessionSummary): string[] {
return [
- summary.activeSessionId ? `active:${summary.activeSessionId}` : undefined,
+ `active:${summary.activeSessionId ?? summary.id}`,
`session:${summary.sessionId}`,
- summary.sessionFile ? `file:${summary.sessionFile}` : undefined,
+ summary.sessionFile ? fileIdentity(summary.sessionFile) : undefined,
].filter((key): key is string => key !== undefined);
}
@@ -347,16 +674,9 @@ function findParentRow(
summary: SessionSummary,
rowsByKey: ReadonlyMap<string, MutableAgentsViewRow>,
): MutableAgentsViewRow | undefined {
- const keys = [
- summary.parentActiveSessionId ? `active:${summary.parentActiveSessionId}` : undefined,
- summary.parentSessionId ? `session:${summary.parentSessionId}` : undefined,
- summary.parentSessionPath ? `file:${summary.parentSessionPath}` : undefined,
- ].filter((key): key is string => key !== undefined);
- for (const key of keys) {
+ for (const key of getParentKeys(summary)) {
const row = rowsByKey.get(key);
- if (row) {
- return row;
- }
+ if (row) return row;
}
return undefined;
}
@@ -374,14 +694,12 @@ function isSubagentSummary(summary: SessionSummary): boolean {
function sectionRank(section: AgentsViewSection): number {
switch (section) {
- case "needs-input":
+ case "running":
return 0;
- case "working":
+ case "idle":
return 1;
- case "heartbeats":
+ case "inactive":
return 2;
- case "completed":
- return 3;
default: {
const _exhaustive: never = section;
return _exhaustive;
@@ -424,6 +742,17 @@ function getSessionStatusLabel(summary: SessionSummary, hasActiveHeartbeat = sum
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.hasRunningRlmChildren === true) {
+ return "subagents running";
+ }
if (summary.pendingMessageCount > 0) {
return `${summary.pendingMessageCount} queued`;
}
diff --git a/packages/coding-agent/src/modes/agents-view/session-view-search.ts b/packages/coding-agent/src/modes/agents-view/session-view-search.ts
new file mode 100644
index 0000000000..ef36814b1f
--- /dev/null
+++ b/packages/coding-agent/src/modes/agents-view/session-view-search.ts
@@ -0,0 +1,142 @@
+import { fuzzyMatch } from "@earendil-works/pi-tui";
+export interface ParsedSearchQuery {
+ mode: "tokens" | "regex";
+ tokens: { kind: "fuzzy" | "phrase"; value: string }[];
+ regex: RegExp | null;
+ /** If set, parsing failed and we should treat query as non-matching. */
+ error?: string;
+}
+
+export interface MatchResult {
+ matches: boolean;
+ /** Lower is better; only meaningful when matches === true */
+ score: number;
+}
+
+function normalizeWhitespaceLower(text: string): string {
+ return text.toLowerCase().replace(/\s+/g, " ").trim();
+}
+
+/** Join arbitrary session fields into the common search corpus. */
+export function createSessionSearchText(parts: readonly (string | undefined | null)[]): string {
+ return parts.filter((part): part is string => typeof part === "string" && part.length > 0).join(" ");
+}
+
+export function parseSearchQuery(query: string): ParsedSearchQuery {
+ const trimmed = query.trim();
+ if (!trimmed) {
+ return { mode: "tokens", tokens: [], regex: null };
+ }
+
+ // Regex mode: re:<pattern>
+ if (trimmed.startsWith("re:")) {
+ const pattern = trimmed.slice(3).trim();
+ if (!pattern) {
+ return { mode: "regex", tokens: [], regex: null, error: "Empty regex" };
+ }
+ try {
+ return { mode: "regex", tokens: [], regex: new RegExp(pattern, "i") };
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ return { mode: "regex", tokens: [], regex: null, error: msg };
+ }
+ }
+
+ // Token mode with quote support.
+ // Example: foo "node cve" bar
+ const tokens: { kind: "fuzzy" | "phrase"; value: string }[] = [];
+ let buf = "";
+ let inQuote = false;
+ let hadUnclosedQuote = false;
+
+ const flush = (kind: "fuzzy" | "phrase"): void => {
+ const v = buf.trim();
+ buf = "";
+ if (!v) return;
+ tokens.push({ kind, value: v });
+ };
+
+ for (let i = 0; i < trimmed.length; i++) {
+ const ch = trimmed[i]!;
+ if (ch === '"') {
+ if (inQuote) {
+ flush("phrase");
+ inQuote = false;
+ } else {
+ flush("fuzzy");
+ inQuote = true;
+ }
+ continue;
+ }
+
+ if (!inQuote && /\s/.test(ch)) {
+ flush("fuzzy");
+ continue;
+ }
+
+ buf += ch;
+ }
+
+ if (inQuote) {
+ hadUnclosedQuote = true;
+ }
+
+ // If quotes were unbalanced, fall back to plain whitespace tokenization.
+ if (hadUnclosedQuote) {
+ return {
+ mode: "tokens",
+ tokens: trimmed
+ .split(/\s+/)
+ .map((t) => t.trim())
+ .filter((t) => t.length > 0)
+ .map((t) => ({ kind: "fuzzy" as const, value: t })),
+ regex: null,
+ };
+ }
+
+ flush(inQuote ? "phrase" : "fuzzy");
+
+ return { mode: "tokens", tokens, regex: null };
+}
+
+const STRICT_FUZZY_MAX_TOKEN_SCORE = 25;
+
+/** Match any precomputed search corpus using the resume picker's query language. */
+export function matchSearchText(text: string, parsed: ParsedSearchQuery): MatchResult {
+ if (parsed.mode === "regex") {
+ if (!parsed.regex) {
+ return { matches: false, score: 0 };
+ }
+ const idx = text.search(parsed.regex);
+ if (idx < 0) return { matches: false, score: 0 };
+ return { matches: true, score: idx * 0.1 };
+ }
+
+ if (parsed.tokens.length === 0) {
+ return { matches: true, score: 0 };
+ }
+
+ let totalScore = 0;
+ const normalizedText = normalizeWhitespaceLower(text);
+
+ for (const token of parsed.tokens) {
+ const needle = normalizeWhitespaceLower(token.value);
+ if (!needle) continue;
+ const idx = normalizedText.indexOf(needle);
+ if (idx >= 0) {
+ totalScore += idx * 0.1;
+ continue;
+ }
+ if (token.kind === "phrase") return { matches: false, score: 0 };
+ const m = fuzzyMatch(token.value, text);
+ if (!m.matches || m.score > STRICT_FUZZY_MAX_TOKEN_SCORE) return { matches: false, score: 0 };
+ totalScore += m.score;
+ }
+
+ return { matches: true, score: totalScore };
+}
+
+export function matchesSearchText(text: string, query: string): boolean {
+ const parsed = parseSearchQuery(query);
+ return !parsed.error && matchSearchText(text, parsed).matches;
+}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 874335e276..d465c267f5 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -90,6 +90,7 @@ import {
shouldDeferHeartbeatCronJob,
} from "../../core/cron-jobs.js";
import { ORPHAN_PROCESS_JOURNAL_ENV } from "../../core/orphan-process-journal.js";
+import { PromptAdmissionCancelledError, waitForPromptAdmission } from "../../core/prompt-admission.js";
import type {
CreateRlmSubagentRuntimeOptions,
RlmSubagentRuntime,
@@ -328,43 +329,6 @@ function delay(ms: number): Promise<void> {
return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
}
-class DaemonPromptAdmissionCancelledError extends Error {
- constructor() {
- super("Prompt admission was cancelled.");
- this.name = "DaemonPromptAdmissionCancelledError";
- }
-}
-
-export function waitForDaemonPromptAdmission<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
- if (!signal) return promise;
- if (signal.aborted) {
- // The caller supplied already-running work. Observe its eventual rejection
- // even though admission cancellation wins immediately.
- void promise.catch(() => {});
- return Promise.reject(new DaemonPromptAdmissionCancelledError());
- }
- return new Promise<T>((resolve, reject) => {
- const cleanup = () => signal.removeEventListener("abort", onAbort);
- const onAbort = () => {
- cleanup();
- reject(new DaemonPromptAdmissionCancelledError());
- };
- signal.addEventListener("abort", onAbort, { once: true });
- // Close the registration-to-check race before observing the awaited work.
- if (signal.aborted) return onAbort();
- promise.then(
- (value) => {
- cleanup();
- resolve(value);
- },
- (error: unknown) => {
- cleanup();
- reject(error);
- },
- );
- });
-}
-
type RuntimeOpenGuard = () => boolean | Promise<boolean>;
type SupervisorGenerationClaim = Omit<Extract<DaemonWorkerCommand, { type: "worker_auth" }>, "id" | "type" | "token">;
@@ -427,6 +391,8 @@ export class AgentDaemon {
private readonly clients = new Set<DaemonSocketClient>();
private readonly sessions = new Map<string, ActiveSessionState>();
private readonly openingSessions = new Map<string, Promise<ActiveSessionState>>();
+ /** Covers path resolution through publication in openingSessions, before the runtime promise exists. */
+ private readonly reservingSessionOpens = new Map<string, Promise<void>>();
private readonly rlmRehydrationClaims = new Map<
string,
{ parentState: ActiveSessionState; entry: PersistedRlmSubagentRegistryEntry }
@@ -581,7 +547,7 @@ export class AgentDaemon {
this.registerSignalHandlers();
this.summarizer.start();
this.log(`Prime Agent daemon listening on ${this.socketPath}`);
- // No startup restore: on-disk sessions return only via /resume or --resume.
+ // No startup restore: on-disk sessions return only via --resume or the agents view.
if (!this.shuttingDown) {
this.cronScheduler.start();
}
@@ -1099,6 +1065,71 @@ export class AgentDaemon {
const sessionPath = command.sessionPath
? await resolveDaemonSessionPath(command.sessionPath, cwd, config.sessionDir)
: undefined;
+ const sessionKey = sessionPath ? resolve(sessionPath) : undefined;
+ const pending = sessionKey ? this.openingSessions.get(sessionKey) : undefined;
+ if (pending && sessionKey) {
+ // Join the in-process open before attempting the filesystem lease. The
+ // creator owns that lease until its runtime is ready.
+ let state: ActiveSessionState;
+ try {
+ state = await pending;
+ } catch (error) {
+ if (!runtimeOpenGuard && error instanceof RuntimeOpenCancelledError) {
+ if (this.openingSessions.get(sessionKey) === pending) {
+ this.openingSessions.delete(sessionKey);
+ }
+ return this.createRuntime(command);
+ }
+ throw error;
+ }
+ if (runtimeOpenGuard && !(await runtimeOpenGuard())) {
+ throw new RuntimeOpenCancelledError();
+ }
+ if (command.name) {
+ state.runtime.session.setSessionName(command.name);
+ }
+ this.adoptClientEnv(state, clientEnv);
+ this.rebindCronJobsToState(state);
+ return state;
+ }
+
+ let releaseOpenReservation = () => {};
+ if (sessionKey) {
+ const reservation = this.reservingSessionOpens.get(sessionKey);
+ if (reservation) {
+ await reservation;
+ return this.createRuntime(command, runtimeOpenGuard);
+ }
+ let release!: () => void;
+ const reserved = new Promise<void>((resolveReservation) => {
+ release = resolveReservation;
+ });
+ this.reservingSessionOpens.set(sessionKey, reserved);
+ let released = false;
+ releaseOpenReservation = () => {
+ if (released) return;
+ released = true;
+ if (this.reservingSessionOpens.get(sessionKey) === reserved) {
+ this.reservingSessionOpens.delete(sessionKey);
+ }
+ release();
+ };
+ }
+
+ const existing = sessionPath ? this.findSessionBySessionFile(sessionPath) : undefined;
+ if (existing) {
+ releaseOpenReservation();
+ if (runtimeOpenGuard && !(await runtimeOpenGuard())) {
+ throw new RuntimeOpenCancelledError();
+ }
+ if (command.name) {
+ existing.runtime.session.setSessionName(command.name);
+ }
+ this.adoptClientEnv(existing, clientEnv);
+ this.rebindCronJobsToState(existing);
+ return existing;
+ }
+
let sessionLease: SessionLease | undefined;
let sessionManager: SessionManager;
try {
@@ -1112,6 +1143,7 @@ export class AgentDaemon {
: SessionManager.create(cwd, config.sessionDir);
} catch (error) {
sessionLease?.release();
+ releaseOpenReservation();
throw error;
}
const createState = async (): Promise<ActiveSessionState> => {
@@ -1210,43 +1242,24 @@ export class AgentDaemon {
const sessionFile = sessionManager.getSessionFile();
if (!sessionFile) {
+ releaseOpenReservation();
return createState();
}
- const sessionKey = resolve(sessionFile);
- const pending = this.openingSessions.get(sessionKey);
- if (pending) {
+ const openedSessionKey = resolve(sessionFile);
+ if (this.openingSessions.has(openedSessionKey)) {
sessionLease?.release();
- // Same as the reuse path above: adopt-if-absent, never overwrite the
- // identity the racing creator's extensions already captured.
- let state: ActiveSessionState;
- try {
- state = await pending;
- } catch (error) {
- if (!runtimeOpenGuard && error instanceof RuntimeOpenCancelledError) {
- if (this.openingSessions.get(sessionKey) === pending) {
- this.openingSessions.delete(sessionKey);
- }
- return this.createRuntime(command);
- }
- throw error;
- }
- if (runtimeOpenGuard && !(await runtimeOpenGuard())) {
- throw new RuntimeOpenCancelledError();
- }
- if (command.name) {
- state.runtime.session.setSessionName(command.name);
- }
- this.adoptClientEnv(state, clientEnv);
- this.rebindCronJobsToState(state);
- return state;
+ releaseOpenReservation();
+ return this.createRuntime({ ...command, sessionPath: sessionFile }, runtimeOpenGuard);
}
const opening = Promise.resolve().then(createState);
- this.openingSessions.set(sessionKey, opening);
+ this.openingSessions.set(openedSessionKey, opening);
+ releaseOpenReservation();
try {
return await opening;
} finally {
- if (this.openingSessions.get(sessionKey) === opening) {
- this.openingSessions.delete(sessionKey);
+ releaseOpenReservation();
+ if (this.openingSessions.get(openedSessionKey) === opening) {
+ this.openingSessions.delete(openedSessionKey);
}
}
}
@@ -1418,7 +1431,7 @@ export class AgentDaemon {
try {
const targetLock = this.agentMessageTargetLocks.get(activeSessionId);
if (targetLock)
- await waitForDaemonPromptAdmission(
+ await waitForPromptAdmission(
targetLock.catch(() => undefined),
signal,
);
@@ -1881,14 +1894,18 @@ export class AgentDaemon {
},
releaseRlmSubagentRuntime: async (runtime, options, status) => {
const state = this.findRuntimeState(runtime);
+ // Trace sharing is best-effort telemetry. In particular, 429 retries can
+ // take minutes and must not delay the model-facing rlm.run result or retention.
+ if (state && status === "done") {
+ void flushAgentTraceUpload(state.runtime.session.sessionManager).catch(() => undefined);
+ }
// A successful subagent stays resident so it's still viewable and messageable;
// closeChildSessions tears it down with the parent. Errored or cancelled children
// would re-seed as "done", so close them immediately.
if (state && status === "done") {
- await flushAgentTraceUpload(state.runtime.session.sessionManager).catch(() => undefined);
- // Retention can decline if deletion or parent teardown won while the trace
- // flush was in flight. Persist completion only after retention succeeds, so
- // a late completion cannot overwrite a durable deletion tombstone.
+ // Retention can decline if deletion or parent teardown won. Persist completion
+ // only after retention succeeds, so a late completion cannot overwrite a
+ // durable deletion tombstone.
if (options.parentSession.retainFinishedRlmChildSession(options.id, runtime.session)) {
if (runtime.session.sessionFile) {
const retainedModel = runtime.session.model ?? options.model;
@@ -2582,17 +2599,14 @@ export class AgentDaemon {
// wins the command wait below.
void claimCheck.catch(() => {});
try {
- const ownerFingerprint = await waitForDaemonPromptAdmission(
- claimCheck,
- parsedAdmission?.controller?.signal,
- );
+ const ownerFingerprint = await waitForPromptAdmission(claimCheck, parsedAdmission?.controller?.signal);
if (this.supervisorClaims.get(client) !== boundClaim || client.socket.destroyed) {
clearParsedAdmission();
return;
}
boundClaim.ownerFingerprint = ownerFingerprint;
} catch (error) {
- const admissionCancelled = error instanceof DaemonPromptAdmissionCancelledError;
+ const admissionCancelled = error instanceof PromptAdmissionCancelledError;
if (admissionCancelled) {
// The fence check remains authoritative after cancellation. Its rejection
// revokes only the exact binding that initiated it; replacements survive.
@@ -3090,7 +3104,7 @@ export class AgentDaemon {
};
let state: ActiveSessionState;
try {
- if (admission?.status === "cancelled") throw new Error("Prompt admission was cancelled.");
+ if (admission?.status === "cancelled") throw new PromptAdmissionCancelledError();
state = this.getBoundSessionState(command.activeSessionId);
} catch (error) {
clearAdmission();
diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
index cf4ae066fa..2dfe6de0e5 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
@@ -12,7 +12,7 @@ import type { ActiveSessionState } from "./active-session-state.js";
// Durable lifecycle; decides agents-view visibility. Only "live" is shown.
// "draft" = no message sent yet (discarded on close); "archived" = ctrl+x'd,
-// reachable only via /resume.
+// reachable only via --resume <selector>.
export type SessionLifecycle = "draft" | "live" | "archived";
// Heuristic activity of a live session. Classification-in-flight counts as
@@ -188,7 +188,7 @@ export function summaryForActiveSession(
messageCount: session.messages.length,
pendingMessageCount,
streamingMessage: session.state.streamingMessage,
- created: savedSession?.created.toISOString(),
+ created: savedSession?.created.toISOString() ?? session.sessionManager.getHeader?.()?.timestamp,
modified,
// Subagent sessions live in artifact dirs that the saved-session scan
// never sees; their spawn prompt is the most identifying title we have.
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index 54c906618c..f66e3fa585 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -27,6 +27,7 @@ import {
ORPHAN_PROCESS_JOURNAL_ENV,
readActiveOrphanProcesses,
} from "../../core/orphan-process-journal.js";
+import { PromptAdmissionCancelledError, waitForPromptAdmission } from "../../core/prompt-admission.js";
import { canonicalSessionPath, getProcessStartId, SessionAlreadyActiveError } from "../../core/session-lease.js";
import type { SessionInfo } from "../../core/session-manager.js";
import { signalProcessGroupOrProcess } from "../../utils/child-process.js";
@@ -286,6 +287,10 @@ interface SupervisorPromptAdmission {
workerActiveSessionId?: string;
}
+function throwIfAdmissionCancelled(admission: SupervisorPromptAdmission | undefined): void {
+ if (admission?.status === "cancelled") throw new PromptAdmissionCancelledError();
+}
+
class SupervisorRecoveryCancelledError extends Error {
readonly code = "supervisor_recovery_cancelled" as const;
}
@@ -317,33 +322,6 @@ function delay(ms: number): Promise<void> {
return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
}
-export function waitForSupervisorPromptAdmission<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
- if (!signal) return promise;
- if (signal.aborted) {
- void promise.catch(() => {});
- return Promise.reject(new Error("Prompt admission was cancelled."));
- }
- return new Promise<T>((resolve, reject) => {
- const cleanup = () => signal.removeEventListener("abort", onAbort);
- const onAbort = () => {
- cleanup();
- reject(new Error("Prompt admission was cancelled."));
- };
- signal.addEventListener("abort", onAbort, { once: true });
- if (signal.aborted) return onAbort();
- promise.then(
- (value) => {
- cleanup();
- resolve(value);
- },
- (error: unknown) => {
- cleanup();
- reject(error);
- },
- );
- });
-}
-
function unrefDelay(ms: number): Promise<void> {
return new Promise((resolveDelay) => setTimeout(resolveDelay, ms).unref());
}
@@ -1094,7 +1072,7 @@ export class DaemonSupervisor {
cancellationAdmission.controller.abort();
}
try {
- await waitForSupervisorPromptAdmission(this.ready, parsedAdmission?.controller.signal);
+ await waitForPromptAdmission(this.ready, parsedAdmission?.controller.signal);
} catch (error) {
if (parsedAdmission) this.deletePromptAdmission(parsedAdmission);
this.write(client, failure(command.id, command.type, error));
@@ -1112,7 +1090,7 @@ export class DaemonSupervisor {
}
try {
- await waitForSupervisorPromptAdmission(this.assertCurrentOwnership(), parsedAdmission?.controller.signal);
+ await waitForPromptAdmission(this.assertCurrentOwnership(), parsedAdmission?.controller.signal);
} catch (error) {
if (parsedAdmission) this.deletePromptAdmission(parsedAdmission);
this.write(client, failure(command.id, command.type, error));
@@ -1617,14 +1595,12 @@ export class DaemonSupervisor {
? this.getPromptAdmission(client, command.activeSessionId, command.admissionId)
: undefined;
try {
- if (admission?.status === "cancelled") throw new Error("Prompt admission was cancelled.");
- const match = await waitForSupervisorPromptAdmission(
+ throwIfAdmissionCancelled(admission);
+ const match = await waitForPromptAdmission(
this.findWorkerForClient(client, command.activeSessionId),
admission?.controller.signal,
);
- if ((admission as { status: string } | undefined)?.status === "cancelled") {
- throw new Error("Prompt admission was cancelled.");
- }
+ throwIfAdmissionCancelled(admission);
const resolvedCommand = {
...command,
activeSessionId: match.summary.activeSessionId ?? match.summary.id,
diff --git a/packages/coding-agent/src/modes/daemon/heartbeat-catalog.ts b/packages/coding-agent/src/modes/daemon/heartbeat-catalog.ts
new file mode 100644
index 0000000000..bc4dcb15e7
--- /dev/null
+++ b/packages/coding-agent/src/modes/daemon/heartbeat-catalog.ts
@@ -0,0 +1,28 @@
+import type { AgentConnectionHeartbeat } from "../agent-connection/types.js";
+import type { DaemonClient } from "./daemon-client.js";
+import { deserializeDaemonError } from "./daemon-errors.js";
+import { isUnknownDaemonCommandError } from "./daemon-protocol.js";
+
+export async function listDaemonHeartbeats(
+ client: DaemonClient,
+ activeSessionId?: string,
+): Promise<AgentConnectionHeartbeat[]> {
+ if (!client.hello) await client.waitForHello();
+ const hasCapability = client.supportsServerCapability("heartbeat_catalog");
+ if (!hasCapability && client.hello?.protocol.version !== 3) {
+ return [];
+ }
+ try {
+ const command = { type: "heartbeats_list", ...(activeSessionId ? { activeSessionId } : {}) } as const;
+ const response = hasCapability ? await client.request(command) : await client.requestLegacy(command);
+ if (!response.success) {
+ throw deserializeDaemonError(response);
+ }
+ return (response.data as { heartbeats: AgentConnectionHeartbeat[] }).heartbeats;
+ } catch (error) {
+ if (isUnknownDaemonCommandError(error, "heartbeats_list")) {
+ return [];
+ }
+ throw error;
+ }
+}
diff --git a/packages/coding-agent/src/modes/index.ts b/packages/coding-agent/src/modes/index.ts
index 933a2d24e8..43ebadf4a4 100644
--- a/packages/coding-agent/src/modes/index.ts
+++ b/packages/coding-agent/src/modes/index.ts
@@ -24,12 +24,19 @@ export {
type AgentsViewRow,
type AgentsViewSection,
type AgentsViewSelectionKey,
+ aggregateSessionHeartbeats,
buildAgentsViewRows,
classifyAgentsViewSession,
+ filterUnifiedSessions,
+ formatHeartbeatBadge,
getAgentsViewSelectionKey,
+ reconcileUnifiedSessions,
resolveAgentsViewSelectionIndex,
+ resolveAgentsViewSelectionState,
sectionTitle,
shouldShowAgentsViewSession,
+ type UnifiedSessionHeartbeat,
+ type UnifiedSessionRecord,
} from "./agents-view/agents-view-state.js";
export {
DaemonCapabilityUnavailableError,
diff --git a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
index 7505932329..ebd0d61a41 100644
--- a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
+++ b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
@@ -35,6 +35,7 @@ export interface ConversationComponentsOptions {
hideThinkingBlock?: boolean;
hiddenThinkingLabel?: string;
toolsExpanded?: boolean;
+ isRecognizedSlashCommand?: (name: string) => boolean;
}
function readUserText(content: string | Array<{ type: string; text?: string }>): string {
@@ -137,7 +138,7 @@ export function buildConversationComponents(
// An image-only prompt has no text; show a placeholder rather than dropping it.
const display = text || (hasContent ? "[image]" : "");
if (display) {
- components.push(new UserMessageComponent(display, options.markdownTheme));
+ components.push(new UserMessageComponent(display, options.markdownTheme, options.isRecognizedSlashCommand));
}
}
// Non-conversational messages (bash/branch-summary/compaction/other custom) aren't shown.
diff --git a/packages/coding-agent/src/modes/interactive/components/index.ts b/packages/coding-agent/src/modes/interactive/components/index.ts
index 6b5bc16d2c..3195b7edba 100644
--- a/packages/coding-agent/src/modes/interactive/components/index.ts
+++ b/packages/coding-agent/src/modes/interactive/components/index.ts
@@ -43,7 +43,6 @@ export { ModelSelectorComponent } from "./model-selector.js";
export { OAuthSelectorComponent } from "./oauth-selector.js";
export { PrimeOnboardingSplashComponent } from "./prime-onboarding-splash.js";
export { type ModelsCallbacks, type ModelsConfig, ScopedModelsSelectorComponent } from "./scoped-models-selector.js";
-export { SessionSelectorComponent } from "./session-selector.js";
export { type SettingsCallbacks, type SettingsConfig, SettingsSelectorComponent } from "./settings-selector.js";
export { ShowImagesSelectorComponent } from "./show-images-selector.js";
export { SkillInvocationMessageComponent } from "./skill-invocation-message.js";
diff --git a/packages/coding-agent/src/modes/interactive/components/session-picker-screen.ts b/packages/coding-agent/src/modes/interactive/components/session-picker-screen.ts
deleted file mode 100644
index 902bc90245..0000000000
--- a/packages/coding-agent/src/modes/interactive/components/session-picker-screen.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { type Component, type Focusable, type TUI, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
-import type { SessionSelectorComponent } from "./session-selector.js";
-
-export function sessionPickerListMaxVisible(rows: number, headerLines: number): number {
- return Math.max(3, rows - headerLines - 10);
-}
-
-export class SessionPickerScreen implements Component, Focusable {
- private _focused = false;
-
- constructor(
- private readonly ui: TUI,
- private readonly header: Component,
- private readonly selector: SessionSelectorComponent,
- ) {}
-
- get focused(): boolean {
- return this._focused;
- }
-
- set focused(value: boolean) {
- this._focused = value;
- this.selector.focused = value;
- }
-
- handleInput(data: string): void {
- this.selector.handleInput(data);
- }
-
- invalidate(): void {
- this.header.invalidate?.();
- this.selector.invalidate();
- }
-
- render(width: number): string[] {
- const safeWidth = Math.max(1, width);
- const height = Math.max(1, this.ui.terminal.rows);
- const headerLines = this.header.render(safeWidth);
- this.selector.setListMaxVisible(sessionPickerListMaxVisible(height, headerLines.length));
- const content = [...headerLines, ...this.selector.render(safeWidth)];
-
- const lines = content.slice(0, height).map((line) => {
- const truncated = truncateToWidth(line, safeWidth, "");
- return truncated + " ".repeat(Math.max(0, safeWidth - visibleWidth(truncated)));
- });
- while (lines.length < height) {
- lines.push(" ".repeat(safeWidth));
- }
- return lines;
- }
-}
diff --git a/packages/coding-agent/src/modes/interactive/components/session-selector-search.ts b/packages/coding-agent/src/modes/interactive/components/session-selector-search.ts
deleted file mode 100644
index 25d49e26c5..0000000000
--- a/packages/coding-agent/src/modes/interactive/components/session-selector-search.ts
+++ /dev/null
@@ -1,225 +0,0 @@
-import { fuzzyMatch } from "@earendil-works/pi-tui";
-import type { AgentConnectionSavedSessionInfo } from "../../agent-connection/index.js";
-
-export type SortMode = "threaded" | "recent" | "relevance";
-
-export type NameFilter = "all" | "named";
-
-export interface ParsedSearchQuery {
- mode: "tokens" | "regex";
- tokens: { kind: "fuzzy" | "phrase"; value: string }[];
- regex: RegExp | null;
- /** If set, parsing failed and we should treat query as non-matching. */
- error?: string;
-}
-
-export interface MatchResult {
- matches: boolean;
- /** Lower is better; only meaningful when matches === true */
- score: number;
-}
-
-function normalizeWhitespaceLower(text: string): string {
- return text.toLowerCase().replace(/\s+/g, " ").trim();
-}
-
-function normalizeSessionTitle(value: string | undefined): string {
- if (value === "(no messages)" || value === "(large message)") return "";
- return normalizeWhitespaceLower(value ?? "");
-}
-
-function getSessionSearchText(session: AgentConnectionSavedSessionInfo): string {
- return `${session.id} ${session.name ?? ""} ${session.allMessagesText} ${session.cwd}`;
-}
-
-export function hasSessionName(session: AgentConnectionSavedSessionInfo): boolean {
- return Boolean(session.name?.trim());
-}
-
-function matchesNameFilter(session: AgentConnectionSavedSessionInfo, filter: NameFilter): boolean {
- if (filter === "all") return true;
- return hasSessionName(session);
-}
-
-function compareSessionsByModifiedDesc(a: AgentConnectionSavedSessionInfo, b: AgentConnectionSavedSessionInfo): number {
- const modifiedDiff = b.modified.getTime() - a.modified.getTime();
- if (modifiedDiff !== 0) return modifiedDiff;
- const createdDiff = b.created.getTime() - a.created.getTime();
- if (createdDiff !== 0) return createdDiff;
- return a.path.localeCompare(b.path);
-}
-
-export function parseSearchQuery(query: string): ParsedSearchQuery {
- const trimmed = query.trim();
- if (!trimmed) {
- return { mode: "tokens", tokens: [], regex: null };
- }
-
- // Regex mode: re:<pattern>
- if (trimmed.startsWith("re:")) {
- const pattern = trimmed.slice(3).trim();
- if (!pattern) {
- return { mode: "regex", tokens: [], regex: null, error: "Empty regex" };
- }
- try {
- return { mode: "regex", tokens: [], regex: new RegExp(pattern, "i") };
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- return { mode: "regex", tokens: [], regex: null, error: msg };
- }
- }
-
- // Token mode with quote support.
- // Example: foo "node cve" bar
- const tokens: { kind: "fuzzy" | "phrase"; value: string }[] = [];
- let buf = "";
- let inQuote = false;
- let hadUnclosedQuote = false;
-
- const flush = (kind: "fuzzy" | "phrase"): void => {
- const v = buf.trim();
- buf = "";
- if (!v) return;
- tokens.push({ kind, value: v });
- };
-
- for (let i = 0; i < trimmed.length; i++) {
- const ch = trimmed[i]!;
- if (ch === '"') {
- if (inQuote) {
- flush("phrase");
- inQuote = false;
- } else {
- flush("fuzzy");
- inQuote = true;
- }
- continue;
- }
-
- if (!inQuote && /\s/.test(ch)) {
- flush("fuzzy");
- continue;
- }
-
- buf += ch;
- }
-
- if (inQuote) {
- hadUnclosedQuote = true;
- }
-
- // If quotes were unbalanced, fall back to plain whitespace tokenization.
- if (hadUnclosedQuote) {
- return {
- mode: "tokens",
- tokens: trimmed
- .split(/\s+/)
- .map((t) => t.trim())
- .filter((t) => t.length > 0)
- .map((t) => ({ kind: "fuzzy" as const, value: t })),
- regex: null,
- };
- }
-
- flush(inQuote ? "phrase" : "fuzzy");
-
- return { mode: "tokens", tokens, regex: null };
-}
-
-const STRICT_FUZZY_MAX_TOKEN_SCORE = 25;
-const SCORE_TIER_SIZE = 1000;
-
-export function matchSession(session: AgentConnectionSavedSessionInfo, parsed: ParsedSearchQuery): MatchResult {
- const text = getSessionSearchText(session);
-
- if (parsed.mode === "regex") {
- if (!parsed.regex) return { matches: false, score: 0 };
- const idx = text.search(parsed.regex);
- return idx < 0 ? { matches: false, score: 0 } : { matches: true, score: idx * 0.1 };
- }
- if (parsed.tokens.length === 0) return { matches: true, score: 0 };
-
- const titles = [session.name, session.firstMessage].map(normalizeSessionTitle);
- if (parsed.tokens.length > 1 && parsed.tokens.every((token) => token.kind === "fuzzy")) {
- const query = parsed.tokens.map((token) => normalizeWhitespaceLower(token.value)).join(" ");
- const exact = titles.indexOf(query);
- const prefix = titles.findIndex((title) => title.startsWith(query));
- const substring = titles.findIndex((title) => title.includes(query));
- if (exact >= 0) return { matches: true, score: exact };
- if (prefix >= 0) return { matches: true, score: SCORE_TIER_SIZE + prefix };
- if (substring >= 0) return { matches: true, score: SCORE_TIER_SIZE * 2 + substring };
- }
-
- const normalizedText = normalizeWhitespaceLower(text);
- let worstTier = 0;
- let tieScore = 0;
- let matchedTokens = 0;
- for (const token of parsed.tokens) {
- const needle = normalizeWhitespaceLower(token.value);
- if (!needle) continue;
- const exact = titles.indexOf(needle);
- const prefix = titles.findIndex((title) => title.startsWith(needle));
- const substring = titles.findIndex((title) => title.includes(needle));
- let tier: number;
- let tie: number;
- if (exact >= 0) [tier, tie] = [3, exact];
- else if (prefix >= 0) [tier, tie] = [4, prefix];
- else if (substring >= 0) [tier, tie] = [5, substring];
- else {
- const position = normalizedText.indexOf(needle);
- if (position >= 0) [tier, tie] = [6, position];
- else {
- if (token.kind === "phrase") return { matches: false, score: 0 };
- const match = fuzzyMatch(token.value, text);
- if (!match.matches || match.score > STRICT_FUZZY_MAX_TOKEN_SCORE) return { matches: false, score: 0 };
- [tier, tie] = [7, match.score];
- }
- }
- worstTier = Math.max(worstTier, tier);
- tieScore += 0.5 + Math.atan(tie) / Math.PI;
- matchedTokens++;
- }
- return { matches: true, score: worstTier * SCORE_TIER_SIZE + tieScore / Math.max(1, matchedTokens) };
-}
-
-export function filterAndSortSessions(
- sessions: AgentConnectionSavedSessionInfo[],
- query: string,
- sortMode: SortMode,
- nameFilter: NameFilter = "all",
-): AgentConnectionSavedSessionInfo[] {
- const nameFiltered =
- nameFilter === "all" ? sessions : sessions.filter((session) => matchesNameFilter(session, nameFilter));
- const trimmed = query.trim();
- if (!trimmed) {
- return sortMode === "recent" ? [...nameFiltered].sort(compareSessionsByModifiedDesc) : nameFiltered;
- }
-
- const parsed = parseSearchQuery(query);
- if (parsed.error) return [];
-
- // Recent mode: filter, then order by the latest user or assistant message.
- if (sortMode === "recent") {
- const filtered: AgentConnectionSavedSessionInfo[] = [];
- for (const s of nameFiltered) {
- const res = matchSession(s, parsed);
- if (res.matches) filtered.push(s);
- }
- return filtered.sort(compareSessionsByModifiedDesc);
- }
-
- // Relevance mode: sort by score, tie-break by modified desc.
- const scored: { session: AgentConnectionSavedSessionInfo; score: number }[] = [];
- for (const s of nameFiltered) {
- const res = matchSession(s, parsed);
- if (!res.matches) continue;
- scored.push({ session: s, score: res.score });
- }
-
- scored.sort((a, b) => {
- if (a.score !== b.score) return a.score - b.score;
- return compareSessionsByModifiedDesc(a.session, b.session);
- });
-
- return scored.map((r) => r.session);
-}
diff --git a/packages/coding-agent/src/modes/interactive/components/session-selector.ts b/packages/coding-agent/src/modes/interactive/components/session-selector.ts
deleted file mode 100644
index 37b2eda747..0000000000
--- a/packages/coding-agent/src/modes/interactive/components/session-selector.ts
+++ /dev/null
@@ -1,1106 +0,0 @@
-import * as os from "node:os";
-import {
- type Component,
- Container,
- type Focusable,
- getKeybindings,
- Input,
- Spacer,
- Text,
- truncateToWidth,
- visibleWidth,
-} from "@earendil-works/pi-tui";
-import { KeybindingsManager } from "../../../core/keybindings.js";
-import { type DeleteSessionFileResult, deleteSessionFile } from "../../../core/session-file-actions.js";
-import { canonicalizePath as _canonicalizePath } from "../../../utils/paths.js";
-import type {
- AgentConnectionSavedSessionInfo,
- AgentConnectionSessionListProgress,
-} from "../../agent-connection/index.js";
-import { theme } from "../theme/theme.js";
-import { DynamicBorder } from "./dynamic-border.js";
-import { keyHint, keyText } from "./keybinding-hints.js";
-import { shouldTreatAsBack } from "./modal-back.js";
-import { filterAndSortSessions, hasSessionName, type NameFilter, type SortMode } from "./session-selector-search.js";
-
-type SessionScope = "current" | "all";
-
-export interface SessionListCallbacks {
- onProgress?: AgentConnectionSessionListProgress;
- onSession?: (session: AgentConnectionSavedSessionInfo) => void;
-}
-
-// Mirrors the agents view delete flow: press the delete key once to arm, again
-// within this window to confirm; anything else (or the timeout) cancels.
-const DELETE_CONFIRM_DURATION_MS = 2000;
-
-function shortenPath(path: string): string {
- const home = os.homedir();
- if (!path) return path;
- if (path.startsWith(home)) {
- return `~${path.slice(home.length)}`;
- }
- return path;
-}
-
-function formatSessionDate(date: Date): string {
- const now = new Date();
- const diffMs = now.getTime() - date.getTime();
- const diffMins = Math.floor(diffMs / 60000);
- const diffHours = Math.floor(diffMs / 3600000);
- const diffDays = Math.floor(diffMs / 86400000);
-
- if (diffMins < 1) return "now";
- if (diffMins < 60) return `${diffMins}m`;
- if (diffHours < 24) return `${diffHours}h`;
- if (diffDays < 7) return `${diffDays}d`;
- if (diffDays < 30) return `${Math.floor(diffDays / 7)}w`;
- if (diffDays < 365) return `${Math.floor(diffDays / 30)}mo`;
- return `${Math.floor(diffDays / 365)}y`;
-}
-
-function canonicalizePath(path: string | undefined): string | undefined {
- if (!path) return path;
- return _canonicalizePath(path);
-}
-
-function formatMutationError(error: unknown): string {
- return error instanceof Error ? error.message : String(error);
-}
-
-// truncateToWidth brackets its marker with a full SGR reset, which would clear a selected row's background.
-function truncateRowContent(text: string, width: number, ellipsis = "..."): string {
- return truncateToWidth(text, width, ellipsis).replaceAll("\x1b[0m", "");
-}
-
-class SessionSelectorHeader implements Component {
- private scope: SessionScope;
- private sortMode: SortMode;
- private nameFilter: NameFilter;
- private requestRender: () => void;
- private loading = false;
- private loadProgress: { loaded: number; total: number } | null = null;
- private showPath = false;
- private confirmingDeletePath: string | null = null;
- private statusMessage: { type: "info" | "error"; message: string } | null = null;
- private statusTimeout: ReturnType<typeof setTimeout> | null = null;
- private showRenameHint = false;
-
- constructor(scope: SessionScope, sortMode: SortMode, nameFilter: NameFilter, requestRender: () => void) {
- this.scope = scope;
- this.sortMode = sortMode;
- this.nameFilter = nameFilter;
- this.requestRender = requestRender;
- }
-
- setScope(scope: SessionScope): void {
- this.scope = scope;
- }
-
- setSortMode(sortMode: SortMode): void {
- this.sortMode = sortMode;
- }
-
- setNameFilter(nameFilter: NameFilter): void {
- this.nameFilter = nameFilter;
- }
-
- setLoading(loading: boolean): void {
- this.loading = loading;
- // Progress is scoped to the current load; clear whenever the loading state is set
- this.loadProgress = null;
- }
-
- setProgress(loaded: number, total: number): void {
- this.loadProgress = { loaded, total };
- }
-
- setShowPath(showPath: boolean): void {
- this.showPath = showPath;
- }
-
- setShowRenameHint(show: boolean): void {
- this.showRenameHint = show;
- }
-
- setConfirmingDeletePath(path: string | null): void {
- this.confirmingDeletePath = path;
- }
-
- private clearStatusTimeout(): void {
- if (!this.statusTimeout) return;
- clearTimeout(this.statusTimeout);
- this.statusTimeout = null;
- }
-
- setStatusMessage(msg: { type: "info" | "error"; message: string } | null, autoHideMs?: number): void {
- this.clearStatusTimeout();
- this.statusMessage = msg;
- if (!msg || !autoHideMs) return;
-
- this.statusTimeout = setTimeout(() => {
- this.statusMessage = null;
- this.statusTimeout = null;
- this.requestRender();
- }, autoHideMs);
- this.statusTimeout.unref?.();
- }
-
- invalidate(): void {}
-
- render(width: number): string[] {
- const leftText = theme.bold("Resume Session");
-
- const sortLabel = this.sortMode === "threaded" ? "threaded" : this.sortMode === "recent" ? "recent" : "fuzzy";
- const segments: string[] = [];
- if (this.loading) {
- const progressText = this.loadProgress ? `${this.loadProgress.loaded}/${this.loadProgress.total}` : "...";
- segments.push(`loading ${progressText}`);
- } else {
- segments.push(this.scope === "current" ? "current folder" : "all projects");
- }
- segments.push(`sort: ${sortLabel}`);
- if (this.nameFilter === "named") {
- segments.push("named only");
- }
- const rightText = truncateToWidth(theme.fg("muted", segments.join(" ")), width, "");
- const availableLeft = Math.max(0, width - visibleWidth(rightText) - 1);
- const left = truncateToWidth(leftText, availableLeft, "");
- const spacing = Math.max(0, width - visibleWidth(left) - visibleWidth(rightText));
-
- // Build hint lines - changes based on state (all branches truncate to width)
- let hintLine1: string;
- let hintLine2: string;
- if (this.confirmingDeletePath !== null) {
- const confirmHint = `Press ${keyText("app.agents.delete")} again to delete`;
- hintLine1 = theme.fg("error", truncateToWidth(confirmHint, width, "…"));
- hintLine2 = "";
- } else if (this.statusMessage) {
- const color = this.statusMessage.type === "error" ? "error" : "accent";
- hintLine1 = theme.fg(color, truncateToWidth(this.statusMessage.message, width, "…"));
- hintLine2 = "";
- } else {
- const pathState = this.showPath ? "(on)" : "(off)";
- const sep = theme.fg("muted", " · ");
- const hint1 =
- keyHint("tui.input.tab", "scope") + sep + theme.fg("muted", 're:<pattern> regex · "phrase" exact');
- const hint2Parts = [
- keyHint("app.session.toggleSort", "sort"),
- keyHint("app.session.toggleNamedFilter", "named"),
- keyHint("app.agents.delete", "delete"),
- keyHint("app.session.togglePath", `path ${pathState}`),
- ];
- if (this.showRenameHint) {
- hint2Parts.push(keyHint("app.session.rename", "rename"));
- }
- const hint2 = hint2Parts.join(sep);
- hintLine1 = truncateToWidth(hint1, width, "…");
- hintLine2 = truncateToWidth(hint2, width, "…");
- }
-
- return [`${left}${" ".repeat(spacing)}${rightText}`, hintLine1, hintLine2];
- }
-}
-
-/** A session tree node for hierarchical display */
-interface SessionTreeNode {
- session: AgentConnectionSavedSessionInfo;
- children: SessionTreeNode[];
-}
-
-/** Flattened node for display with tree structure info */
-interface FlatSessionNode {
- session: AgentConnectionSavedSessionInfo;
- depth: number;
- isLast: boolean;
- /** For each ancestor level, whether there are more siblings after it */
- ancestorContinues: boolean[];
-}
-
-/**
- * Build a tree structure from sessions based on parentSessionPath.
- * Returns root nodes sorted by modified date (descending).
- */
-function buildSessionTree(sessions: AgentConnectionSavedSessionInfo[]): SessionTreeNode[] {
- const byPath = new Map<string, SessionTreeNode>();
-
- for (const session of sessions) {
- const sessionPath = canonicalizePath(session.path) ?? session.path;
- byPath.set(sessionPath, { session, children: [] });
- }
-
- const roots: SessionTreeNode[] = [];
-
- for (const session of sessions) {
- const sessionPath = canonicalizePath(session.path) ?? session.path;
- const node = byPath.get(sessionPath)!;
- const parentPath = canonicalizePath(session.parentSessionPath);
-
- if (parentPath && byPath.has(parentPath)) {
- byPath.get(parentPath)!.children.push(node);
- } else {
- roots.push(node);
- }
- }
-
- // Sort children and roots by modified date (descending)
- const sortNodes = (nodes: SessionTreeNode[]): void => {
- nodes.sort((a, b) => b.session.modified.getTime() - a.session.modified.getTime());
- for (const node of nodes) {
- sortNodes(node.children);
- }
- };
- sortNodes(roots);
-
- return roots;
-}
-
-/**
- * Flatten tree into display list with tree structure metadata.
- */
-function flattenSessionTree(roots: SessionTreeNode[]): FlatSessionNode[] {
- const result: FlatSessionNode[] = [];
-
- const walk = (node: SessionTreeNode, depth: number, ancestorContinues: boolean[], isLast: boolean): void => {
- result.push({ session: node.session, depth, isLast, ancestorContinues });
-
- for (let i = 0; i < node.children.length; i++) {
- const childIsLast = i === node.children.length - 1;
- // Only show continuation line for non-root ancestors
- const continues = depth > 0 ? !isLast : false;
- walk(node.children[i]!, depth + 1, [...ancestorContinues, continues], childIsLast);
- }
- };
-
- for (let i = 0; i < roots.length; i++) {
- walk(roots[i]!, 0, [], i === roots.length - 1);
- }
-
- return result;
-}
-
-/**
- * Custom session list component with multi-line items and search
- */
-class SessionList implements Component, Focusable {
- private getSelectedSessionPath(): string | undefined {
- return this.filteredSessions[this.selectedIndex]?.session.path;
- }
-
- private allSessions: AgentConnectionSavedSessionInfo[] = [];
- private filteredSessions: FlatSessionNode[] = [];
- private selectedIndex: number = 0;
- private searchQuery = "";
- private searchInput: Input;
- private showCwd = false;
- private sortMode: SortMode = "recent";
- private nameFilter: NameFilter = "all";
- private keybindings: KeybindingsManager;
- private showPath = false;
- private loading = false;
- private confirmingDeletePath: string | null = null;
- private deleteConfirmTimer: ReturnType<typeof setTimeout> | null = null;
- private currentSessionCanonicalPath?: string;
- public onSelect?: (sessionPath: string) => void;
- public onCancel?: () => void;
- public onExit: () => void = () => {};
- public onToggleScope?: () => void;
- public onToggleSort?: () => void;
- public onToggleNameFilter?: () => void;
- public onTogglePath?: (showPath: boolean) => void;
- public onDeleteConfirmationChange?: (path: string | null) => void;
- public onDeleteSession?: (sessionPath: string) => Promise<void>;
- public onRenameSession?: (sessionPath: string) => void;
- public onError?: (message: string) => void;
- private maxVisible: number = 10; // Max sessions visible (one line each)
-
- // Focusable implementation - propagate to searchInput for IME cursor positioning
- private _focused = false;
- get focused(): boolean {
- return this._focused;
- }
- set focused(value: boolean) {
- this._focused = value;
- this.searchInput.focused = value;
- }
-
- constructor(
- sessions: AgentConnectionSavedSessionInfo[],
- showCwd: boolean,
- sortMode: SortMode,
- nameFilter: NameFilter,
- keybindings: KeybindingsManager,
- currentSessionFilePath?: string,
- ) {
- this.allSessions = sessions;
- this.filteredSessions = [];
- this.searchInput = new Input();
- this.showCwd = showCwd;
- this.sortMode = sortMode;
- this.nameFilter = nameFilter;
- this.keybindings = keybindings;
- this.currentSessionCanonicalPath = canonicalizePath(currentSessionFilePath);
- this.filterSessions("");
-
- // Handle Enter in search input - select current item
- this.searchInput.onSubmit = () => {
- if (this.filteredSessions[this.selectedIndex]) {
- const selected = this.filteredSessions[this.selectedIndex];
- if (this.onSelect) {
- this.onSelect(selected.session.path);
- }
- }
- };
- }
-
- setMaxVisible(maxVisible: number): void {
- this.maxVisible = Math.max(3, maxVisible);
- }
-
- setLoading(loading: boolean): void {
- this.loading = loading;
- }
-
- setSortMode(sortMode: SortMode): void {
- this.sortMode = sortMode;
- this.filterSessions(this.searchInput.getValue());
- }
-
- setNameFilter(nameFilter: NameFilter): void {
- this.nameFilter = nameFilter;
- this.filterSessions(this.searchInput.getValue());
- }
-
- setSessions(sessions: AgentConnectionSavedSessionInfo[], showCwd: boolean): void {
- const selectedPath = this.getSelectedSessionPath();
- this.allSessions = sessions;
- this.showCwd = showCwd;
- this.filterSessions(this.searchInput.getValue());
- if (selectedPath) {
- const selectedIndex = this.filteredSessions.findIndex((session) => session.session.path === selectedPath);
- if (selectedIndex >= 0) {
- this.selectedIndex = selectedIndex;
- }
- }
- }
-
- private filterSessions(query: string): void {
- const queryChanged = query !== this.searchQuery;
- this.searchQuery = query;
- const trimmed = query.trim();
- const nameFiltered =
- this.nameFilter === "all" ? this.allSessions : this.allSessions.filter((session) => hasSessionName(session));
-
- if (this.sortMode === "threaded" && !trimmed) {
- // Threaded mode without search: show tree structure
- const roots = buildSessionTree(nameFiltered);
- this.filteredSessions = flattenSessionTree(roots);
- } else {
- // Other modes or with search: flat list
- const filtered = filterAndSortSessions(nameFiltered, query, this.sortMode, "all");
- this.filteredSessions = filtered.map((session) => ({
- session,
- depth: 0,
- isLast: true,
- ancestorContinues: [],
- }));
- }
- this.selectedIndex = queryChanged
- ? 0
- : Math.min(this.selectedIndex, Math.max(0, this.filteredSessions.length - 1));
- }
-
- private setConfirmingDeletePath(path: string | null): void {
- this.confirmingDeletePath = path;
- this.onDeleteConfirmationChange?.(path);
- }
-
- private clearDeleteConfirmation(): void {
- if (this.deleteConfirmTimer) {
- clearTimeout(this.deleteConfirmTimer);
- this.deleteConfirmTimer = null;
- }
- if (this.confirmingDeletePath !== null) {
- this.setConfirmingDeletePath(null);
- }
- }
-
- private startDeleteConfirmationForSelectedSession(): void {
- const selected = this.filteredSessions[this.selectedIndex];
- if (!selected) return;
-
- // Prevent deleting current session
- if (this.isCurrentSessionPath(selected.session.path)) {
- this.onError?.("Cannot delete the currently active session");
- return;
- }
-
- // Second press within the window confirms.
- if (this.confirmingDeletePath === selected.session.path) {
- const pathToDelete = this.confirmingDeletePath;
- this.clearDeleteConfirmation();
- void this.onDeleteSession?.(pathToDelete);
- return;
- }
-
- this.clearDeleteConfirmation();
- this.setConfirmingDeletePath(selected.session.path);
- this.deleteConfirmTimer = setTimeout(() => {
- this.deleteConfirmTimer = null;
- this.setConfirmingDeletePath(null);
- }, DELETE_CONFIRM_DURATION_MS);
- this.deleteConfirmTimer.unref?.();
- }
-
- private isCurrentSessionPath(path: string): boolean {
- if (!this.currentSessionCanonicalPath) return false;
- return (canonicalizePath(path) ?? path) === this.currentSessionCanonicalPath;
- }
-
- invalidate(): void {}
-
- render(width: number): string[] {
- const lines: string[] = [];
-
- // Render search input
- lines.push(...this.searchInput.render(width));
- lines.push(""); // Blank line after search
- if (this.loading && this.filteredSessions.length === 0) return lines;
-
- if (this.filteredSessions.length === 0) {
- let emptyMessage: string;
- if (this.nameFilter === "named") {
- const toggleKey = keyText("app.session.toggleNamedFilter");
- if (this.showCwd) {
- emptyMessage = ` No named sessions found. Press ${toggleKey} to show all.`;
- } else {
- emptyMessage = ` No named sessions in current folder. Press ${toggleKey} to show all, or Tab to view all.`;
- }
- } else if (this.showCwd) {
- // "All" scope - no sessions anywhere that match filter
- emptyMessage = " No sessions found";
- } else {
- // "Current folder" scope - hint to try "all"
- emptyMessage = " No sessions in current folder. Press Tab to view all.";
- }
- lines.push(theme.fg("muted", truncateToWidth(emptyMessage, width, "…")));
- return lines;
- }
-
- // Calculate visible range with scrolling
- const startIndex = Math.max(
- 0,
- Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredSessions.length - this.maxVisible),
- );
- const endIndex = Math.min(startIndex + this.maxVisible, this.filteredSessions.length);
-
- // Render visible sessions like agents view rows: icon, title, right-aligned details.
- for (let i = startIndex; i < endIndex; i++) {
- const node = this.filteredSessions[i]!;
- const session = node.session;
- const isSelected = i === this.selectedIndex;
- const isConfirmingDelete = session.path === this.confirmingDeletePath;
- const isCurrent = this.isCurrentSessionPath(session.path);
-
- // Build tree prefix
- const prefix = this.buildTreePrefix(node);
-
- // Session display text (name or first message); an armed delete shows
- // the confirm prompt in place of the title like the agents view.
- const displayText = isConfirmingDelete
- ? `${keyText("app.agents.delete")} again to remove`
- : (session.name ?? session.firstMessage);
- const normalizedMessage = displayText.replace(/[\x00-\x1f\x7f]/g, " ").trim();
-
- // Right side: message count and age
- const age = formatSessionDate(session.modified);
- let rightPart = `${session.messageCount} · ${age}`;
- if (this.showCwd && session.cwd) {
- rightPart = `${shortenPath(session.cwd)} ${rightPart}`;
- }
- if (this.showPath) {
- rightPart = `${shortenPath(session.path)} ${rightPart}`;
- }
-
- const rawIcon = isConfirmingDelete ? "✗" : "✓";
- const icon = isConfirmingDelete
- ? theme.fg("error", rawIcon)
- : isCurrent
- ? theme.fg("accent", rawIcon)
- : theme.fg("success", rawIcon);
-
- // Calculate available width for message
- const prefixWidth = visibleWidth(prefix);
- const rightWidth = visibleWidth(rightPart) + 2; // +2 for spacing
- const availableForMsg = width - 2 - prefixWidth - rightWidth - 2; // icon + gap
-
- const truncatedMsg = truncateRowContent(normalizedMessage, Math.max(10, availableForMsg), "…");
-
- const styledMsg = isConfirmingDelete ? theme.fg("error", truncatedMsg) : truncatedMsg;
-
- // Build line
- const leftPart = `${theme.fg("dim", prefix)}${icon} ${styledMsg}`;
- const leftWidth = visibleWidth(leftPart);
- const spacing = Math.max(1, width - leftWidth - visibleWidth(rightPart));
- const styledRight = theme.fg(isConfirmingDelete ? "error" : "dim", rightPart);
-
- let line = leftPart + " ".repeat(spacing) + styledRight;
- if (isSelected) {
- const padded = truncateRowContent(line, width);
- line = theme.bg("selectedBg", padded + " ".repeat(Math.max(0, width - visibleWidth(padded))));
- }
- lines.push(truncateToWidth(line, width));
- }
-
- // Add scroll indicator if needed
- if (startIndex > 0 || endIndex < this.filteredSessions.length) {
- const scrollText = ` (${this.selectedIndex + 1}/${this.filteredSessions.length})`;
- const scrollInfo = theme.fg("muted", truncateToWidth(scrollText, width, ""));
- lines.push(scrollInfo);
- }
-
- return lines;
- }
-
- private buildTreePrefix(node: FlatSessionNode): string {
- if (node.depth === 0) {
- return "";
- }
-
- const parts = node.ancestorContinues.map((continues) => (continues ? "│ " : " "));
- const branch = node.isLast ? "└─ " : "├─ ";
- return parts.join("") + branch;
- }
-
- handleInput(keyData: string): void {
- const kb = getKeybindings();
-
- // Any key other than another delete press cancels an armed confirmation
- // and is then handled normally, like the agents view.
- const hadDeleteConfirmation = this.confirmingDeletePath !== null;
- if (
- hadDeleteConfirmation &&
- !kb.matches(keyData, "app.agents.delete") &&
- !kb.matches(keyData, "app.session.deleteNoninvasive")
- ) {
- this.clearDeleteConfirmation();
- }
-
- if (kb.matches(keyData, "tui.input.tab")) {
- if (this.onToggleScope) {
- this.onToggleScope();
- }
- return;
- }
-
- if (kb.matches(keyData, "app.session.toggleSort")) {
- this.onToggleSort?.();
- return;
- }
-
- if (this.keybindings.matches(keyData, "app.session.toggleNamedFilter")) {
- this.onToggleNameFilter?.();
- return;
- }
-
- // Ctrl+P: toggle path display
- if (kb.matches(keyData, "app.session.togglePath")) {
- this.showPath = !this.showPath;
- this.onTogglePath?.(this.showPath);
- return;
- }
-
- // Same binding as the agents view: arm on first press, confirm on second.
- if (kb.matches(keyData, "app.agents.delete")) {
- this.startDeleteConfirmationForSelectedSession();
- return;
- }
-
- // Rename selected session
- if (kb.matches(keyData, "app.session.rename")) {
- const selected = this.filteredSessions[this.selectedIndex];
- if (selected) {
- this.onRenameSession?.(selected.session.path);
- }
- return;
- }
-
- // Ctrl+Backspace: non-invasive convenience alias for delete
- // Only triggers deletion when the query is empty; otherwise it is forwarded to the input
- if (kb.matches(keyData, "app.session.deleteNoninvasive")) {
- if (this.searchInput.getValue().length > 0) {
- this.searchInput.handleInput(keyData);
- this.filterSessions(this.searchInput.getValue());
- return;
- }
-
- this.startDeleteConfirmationForSelectedSession();
- return;
- }
-
- // Up arrow
- if (kb.matches(keyData, "tui.select.up")) {
- this.selectedIndex = Math.max(0, this.selectedIndex - 1);
- }
- // Down arrow
- else if (kb.matches(keyData, "tui.select.down")) {
- this.selectedIndex = Math.min(this.filteredSessions.length - 1, this.selectedIndex + 1);
- }
- // Page up - jump up by maxVisible items
- else if (kb.matches(keyData, "tui.select.pageUp")) {
- this.selectedIndex = Math.max(0, this.selectedIndex - this.maxVisible);
- }
- // Page down - jump down by maxVisible items
- else if (kb.matches(keyData, "tui.select.pageDown")) {
- this.selectedIndex = Math.min(this.filteredSessions.length - 1, this.selectedIndex + this.maxVisible);
- }
- // Enter
- else if (kb.matches(keyData, "tui.select.confirm")) {
- const selected = this.filteredSessions[this.selectedIndex];
- if (selected && this.onSelect) {
- this.onSelect(selected.session.path);
- }
- }
- // Escape, or left arrow when the search field is at its start - cancel.
- // If this same keypress just disarmed a delete confirmation, left only
- // disarms (like other nav keys); Esc still cancels, matching its role.
- else if (
- kb.matches(keyData, "tui.select.cancel") ||
- (!hadDeleteConfirmation && shouldTreatAsBack(keyData, this.searchInput))
- ) {
- if (this.onCancel) {
- this.onCancel();
- }
- }
- // Pass everything else to search input
- else {
- this.searchInput.handleInput(keyData);
- this.filterSessions(this.searchInput.getValue());
- }
- }
-}
-
-type SessionsLoader = (callbacks?: SessionListCallbacks) => Promise<AgentConnectionSavedSessionInfo[]>;
-type SessionDeleter = (sessionPath: string) => Promise<DeleteSessionFileResult>;
-
-/**
- * Component that renders a session selector
- */
-export class SessionSelectorComponent extends Container implements Focusable {
- handleInput(data: string): void {
- if (this.mode === "rename") {
- const kb = getKeybindings();
- if (kb.matches(data, "tui.select.cancel")) {
- this.exitRenameMode();
- return;
- }
- this.renameInput.handleInput(data);
- return;
- }
-
- this.sessionList.handleInput(data);
- }
-
- private canRename = true;
- private readonly frameless: boolean;
- private sessionList: SessionList;
- private header: SessionSelectorHeader;
- private keybindings: KeybindingsManager;
- private scope: SessionScope = "current";
- private sortMode: SortMode = "recent";
- private nameFilter: NameFilter = "all";
- private currentSessions: AgentConnectionSavedSessionInfo[] | null = null;
- private allSessions: AgentConnectionSavedSessionInfo[] | null = null;
- private currentSessionsLoader: SessionsLoader;
- private allSessionsLoader: SessionsLoader;
- private onCancel: () => void;
- private requestRender: () => void;
- private renameSession?: (sessionPath: string, currentName: string | undefined) => Promise<void>;
- private deleteSession: SessionDeleter;
- private currentLoading = false;
- private allLoading = false;
- private currentLoadSeq = 0;
- private allLoadSeq = 0;
-
- private mode: "list" | "rename" = "list";
- private renameInput = new Input();
- private renameTargetPath: string | null = null;
-
- // Focusable implementation - propagate to sessionList for IME cursor positioning
- private _focused = false;
- get focused(): boolean {
- return this._focused;
- }
- set focused(value: boolean) {
- this._focused = value;
- this.sessionList.focused = value;
- this.renameInput.focused = value;
- if (value && this.mode === "rename") {
- this.renameInput.focused = true;
- }
- }
-
- private buildBaseLayout(content: Component, options?: { showHeader?: boolean }): void {
- this.clear();
- this.addChild(new Spacer(1));
- if (!this.frameless) {
- this.addChild(new DynamicBorder((s) => theme.fg("borderMuted", s)));
- this.addChild(new Spacer(1));
- }
- if (options?.showHeader ?? true) {
- this.addChild(this.header);
- this.addChild(new Spacer(1));
- }
- this.addChild(content);
- if (!this.frameless) {
- this.addChild(new Spacer(1));
- this.addChild(new DynamicBorder((s) => theme.fg("borderMuted", s)));
- }
- }
-
- constructor(
- currentSessionsLoader: SessionsLoader,
- allSessionsLoader: SessionsLoader,
- onSelect: (sessionPath: string) => void,
- onCancel: () => void,
- onExit: () => void,
- requestRender: () => void,
- options?: {
- renameSession?: (sessionPath: string, currentName: string | undefined) => Promise<void>;
- deleteSession?: SessionDeleter;
- showRenameHint?: boolean;
- keybindings?: KeybindingsManager;
- /** Skip the framing borders; used when the selector fills the whole screen. */
- frameless?: boolean;
- },
- currentSessionFilePath?: string,
- ) {
- super();
- this.frameless = options?.frameless ?? false;
- this.keybindings = options?.keybindings ?? KeybindingsManager.create();
- this.currentSessionsLoader = currentSessionsLoader;
- this.allSessionsLoader = allSessionsLoader;
- this.onCancel = onCancel;
- this.requestRender = requestRender;
- this.header = new SessionSelectorHeader(this.scope, this.sortMode, this.nameFilter, this.requestRender);
- const renameSession = options?.renameSession;
- this.renameSession = renameSession;
- this.deleteSession = options?.deleteSession ?? deleteSessionFile;
- this.canRename = !!renameSession;
- this.header.setShowRenameHint(options?.showRenameHint ?? this.canRename);
-
- // Create session list (starts empty, will be populated after load)
- this.sessionList = new SessionList(
- [],
- false,
- this.sortMode,
- this.nameFilter,
- this.keybindings,
- currentSessionFilePath,
- );
-
- this.buildBaseLayout(this.sessionList);
-
- this.renameInput.onSubmit = (value) => {
- void this.confirmRename(value);
- };
-
- // Ensure header status timeouts are cleared when leaving the selector
- const clearStatusMessage = () => this.header.setStatusMessage(null);
- this.sessionList.onSelect = (sessionPath) => {
- clearStatusMessage();
- onSelect(sessionPath);
- };
- this.sessionList.onCancel = () => {
- clearStatusMessage();
- onCancel();
- };
- this.sessionList.onExit = () => {
- clearStatusMessage();
- onExit();
- };
- this.sessionList.onToggleScope = () => this.toggleScope();
- this.sessionList.onToggleSort = () => this.toggleSortMode();
- this.sessionList.onToggleNameFilter = () => this.toggleNameFilter();
- this.sessionList.onRenameSession = (sessionPath) => {
- if (!renameSession) return;
- if (this.scope === "current" && this.currentLoading) return;
- if (this.scope === "all" && this.allLoading) return;
-
- const sessions = this.scope === "all" ? (this.allSessions ?? []) : (this.currentSessions ?? []);
- const session = sessions.find((s) => s.path === sessionPath);
- this.enterRenameMode(sessionPath, session?.name);
- };
-
- // Sync list events to header
- this.sessionList.onTogglePath = (showPath) => {
- this.header.setShowPath(showPath);
- this.requestRender();
- };
- this.sessionList.onDeleteConfirmationChange = (path) => {
- this.header.setConfirmingDeletePath(path);
- this.requestRender();
- };
- this.sessionList.onError = (msg) => {
- this.header.setStatusMessage({ type: "error", message: msg }, 3000);
- this.requestRender();
- };
-
- // Handle session deletion
- this.sessionList.onDeleteSession = async (sessionPath: string) => {
- let result: DeleteSessionFileResult;
- try {
- result = await this.deleteSession(sessionPath);
- } catch (error) {
- this.header.setStatusMessage(
- { type: "error", message: `Failed to delete: ${formatMutationError(error)}` },
- 3000,
- );
- this.requestRender();
- return;
- }
-
- if (result.ok) {
- if (this.currentSessions) {
- this.currentSessions = this.currentSessions.filter((s) => s.path !== sessionPath);
- }
- if (this.allSessions) {
- this.allSessions = this.allSessions.filter((s) => s.path !== sessionPath);
- }
-
- const sessions = this.scope === "all" ? (this.allSessions ?? []) : (this.currentSessions ?? []);
- const showCwd = this.scope === "all";
- this.sessionList.setSessions(sessions, showCwd);
-
- const msg = result.method === "trash" ? "Session moved to trash" : "Session deleted";
- try {
- await this.refreshSessionsAfterMutation();
- this.header.setStatusMessage({ type: "info", message: msg }, 2000);
- } catch (error) {
- this.header.setStatusMessage(
- { type: "error", message: `${msg}; refresh failed: ${formatMutationError(error)}` },
- 3000,
- );
- }
- } else {
- const errorMessage = result.error ?? "Unknown error";
- this.header.setStatusMessage({ type: "error", message: `Failed to delete: ${errorMessage}` }, 3000);
- }
-
- this.requestRender();
- };
-
- // Start loading current sessions immediately
- this.loadCurrentSessions();
- }
-
- private loadCurrentSessions(): void {
- void this.loadScope("current", "initial");
- }
-
- private enterRenameMode(sessionPath: string, currentName: string | undefined): void {
- this.mode = "rename";
- this.renameTargetPath = sessionPath;
- this.renameInput.setValue(currentName ?? "");
- this.renameInput.focused = true;
-
- const panel = new Container();
- panel.addChild(new Text(theme.bold("Rename Session"), 1, 0));
- panel.addChild(new Spacer(1));
- panel.addChild(this.renameInput);
- panel.addChild(new Spacer(1));
- panel.addChild(
- new Text(
- theme.fg("muted", `${keyText("tui.select.confirm")} to save · ${keyText("tui.select.cancel")} to cancel`),
- 1,
- 0,
- ),
- );
-
- this.buildBaseLayout(panel, { showHeader: false });
- this.requestRender();
- }
-
- private exitRenameMode(): void {
- this.mode = "list";
- this.renameTargetPath = null;
-
- this.buildBaseLayout(this.sessionList);
-
- this.requestRender();
- }
-
- private async confirmRename(value: string): Promise<void> {
- const next = value.trim();
- if (!next) return;
- const target = this.renameTargetPath;
- if (!target) {
- this.exitRenameMode();
- return;
- }
-
- // Find current name for callback
- const renameSession = this.renameSession;
- if (!renameSession) {
- this.exitRenameMode();
- return;
- }
-
- try {
- await renameSession(target, next);
- } catch (error) {
- this.exitRenameMode();
- this.header.setStatusMessage(
- { type: "error", message: `Failed to rename: ${formatMutationError(error)}` },
- 4000,
- );
- this.requestRender();
- return;
- }
-
- try {
- await this.refreshSessionsAfterMutation();
- } catch (error) {
- this.exitRenameMode();
- this.header.setStatusMessage(
- { type: "error", message: `Session renamed; refresh failed: ${formatMutationError(error)}` },
- 4000,
- );
- this.requestRender();
- return;
- }
-
- this.exitRenameMode();
- }
-
- private async loadScope(scope: SessionScope, reason: "initial" | "refresh" | "toggle"): Promise<void> {
- const showCwd = scope === "all";
-
- // Mark loading
- if (scope === "current") {
- this.currentLoading = true;
- } else {
- this.allLoading = true;
- }
-
- const seq = scope === "current" ? ++this.currentLoadSeq : ++this.allLoadSeq;
- this.header.setScope(scope);
- this.header.setLoading(true);
- this.sessionList.setLoading(true);
- if (reason !== "refresh") {
- this.sessionList.setSessions([], showCwd);
- }
- this.requestRender();
- const isLatestLoad = () => seq === (scope === "current" ? this.currentLoadSeq : this.allLoadSeq);
- const isCurrentView = () => scope === this.scope;
- const onProgress = (loaded: number, total: number) => {
- if (!isLatestLoad() || !isCurrentView()) return;
- this.header.setProgress(loaded, total);
- this.requestRender();
- };
-
- try {
- const sessions = await (scope === "current"
- ? this.currentSessionsLoader({ onProgress })
- : this.allSessionsLoader({ onProgress }));
-
- if (!isLatestLoad()) return;
-
- if (scope === "current") {
- this.currentSessions = sessions;
- this.currentLoading = false;
- } else {
- this.allSessions = sessions;
- this.allLoading = false;
- }
-
- if (!isCurrentView()) return;
-
- this.header.setLoading(false);
- this.sessionList.setLoading(false);
- this.sessionList.setSessions(sessions, showCwd);
- this.requestRender();
-
- if (scope === "all" && sessions.length === 0 && (this.currentSessions?.length ?? 0) === 0) {
- this.onCancel();
- }
- } catch (err) {
- if (!isLatestLoad()) return;
-
- if (scope === "current") {
- this.currentLoading = false;
- } else {
- this.allLoading = false;
- }
-
- if (!isCurrentView()) return;
-
- const message = err instanceof Error ? err.message : String(err);
- this.header.setLoading(false);
- this.sessionList.setLoading(false);
- this.header.setStatusMessage({ type: "error", message: `Failed to load sessions: ${message}` }, 4000);
-
- if (reason === "initial") {
- this.sessionList.setSessions([], showCwd);
- }
- this.requestRender();
- }
- }
-
- private toggleSortMode(): void {
- // Cycle: recent -> relevance -> threaded -> recent
- this.sortMode = this.sortMode === "threaded" ? "recent" : this.sortMode === "recent" ? "relevance" : "threaded";
- this.header.setSortMode(this.sortMode);
- this.sessionList.setSortMode(this.sortMode);
- this.requestRender();
- }
-
- private toggleNameFilter(): void {
- this.nameFilter = this.nameFilter === "all" ? "named" : "all";
- this.header.setNameFilter(this.nameFilter);
- this.sessionList.setNameFilter(this.nameFilter);
- this.requestRender();
- }
-
- private async refreshSessionsAfterMutation(): Promise<void> {
- await this.loadScope(this.scope, "refresh");
- }
-
- private toggleScope(): void {
- if (this.scope === "current") {
- this.scope = "all";
- this.header.setScope(this.scope);
- this.header.setLoading(this.allLoading);
- this.sessionList.setLoading(this.allLoading);
-
- if (this.allSessions !== null) {
- this.sessionList.setSessions(this.allSessions, true);
- this.requestRender();
- return;
- }
-
- if (!this.allLoading) {
- void this.loadScope("all", "toggle");
- } else {
- this.sessionList.setSessions([], true);
- this.requestRender();
- }
- return;
- }
-
- this.scope = "current";
- this.header.setScope(this.scope);
- this.header.setLoading(this.currentLoading);
- this.sessionList.setLoading(this.currentLoading);
- this.sessionList.setSessions(this.currentSessions ?? [], false);
- this.requestRender();
- }
-
- setListMaxVisible(maxVisible: number): void {
- this.sessionList.setMaxVisible(maxVisible);
- }
-
- getSessionList(): SessionList {
- return this.sessionList;
- }
-}
diff --git a/packages/coding-agent/src/modes/interactive/components/slash-command-message.ts b/packages/coding-agent/src/modes/interactive/components/slash-command-message.ts
index 41af912a70..d977028edd 100644
--- a/packages/coding-agent/src/modes/interactive/components/slash-command-message.ts
+++ b/packages/coding-agent/src/modes/interactive/components/slash-command-message.ts
@@ -1,15 +1,20 @@
import { Box, Container, Text } from "@earendil-works/pi-tui";
+import { parseSlashCommand } from "../../../core/slash-commands.js";
import { theme } from "../theme/theme.js";
const OSC133_ZONE_START = "\x1b]133;A\x07";
const OSC133_ZONE_END = "\x1b]133;B\x07";
const OSC133_ZONE_FINAL = "\x1b]133;C\x07";
-export function styleSlashCommandText(text: string): string {
- const space = text.search(/\s/);
- const command = space === -1 ? text : text.slice(0, space);
- const rest = space === -1 ? "" : text.slice(space);
- return `${theme.fg("accent", command)}${rest}`;
+export function isLeadingSlashCommand(text: string, isRecognized: (name: string) => boolean): boolean {
+ const command = parseSlashCommand(text);
+ return command !== undefined && isRecognized(command.name);
+}
+
+export function styleSlashCommandText(text: string, styleRest: (rest: string) => string = (rest) => rest): string {
+ const parsed = parseSlashCommand(text);
+ const commandEnd = parsed ? parsed.name.length + 1 : text.length;
+ return `${theme.fg("accent", text.slice(0, commandEnd))}${styleRest(text.slice(commandEnd))}`;
}
/** Renders a durable session command with the same layout as a user message. */
diff --git a/packages/coding-agent/src/modes/interactive/components/user-message.ts b/packages/coding-agent/src/modes/interactive/components/user-message.ts
index e5b54cc6cb..2674f52b31 100644
--- a/packages/coding-agent/src/modes/interactive/components/user-message.ts
+++ b/packages/coding-agent/src/modes/interactive/components/user-message.ts
@@ -1,9 +1,57 @@
-import { Box, Container, Markdown, type MarkdownTheme } from "@earendil-works/pi-tui";
+import { Box, type Component, Container, Markdown, type MarkdownTheme, visibleWidth } from "@earendil-works/pi-tui";
+import { parseSlashCommand } from "../../../core/slash-commands.js";
import { getMarkdownTheme, theme } from "../theme/theme.js";
+import { isLeadingSlashCommand } from "./slash-command-message.js";
const OSC133_ZONE_START = "\x1b]133;A\x07";
const OSC133_ZONE_END = "\x1b]133;B\x07";
const OSC133_ZONE_FINAL = "\x1b]133;C\x07";
+const COMMAND_MASK_BASE = "\uE000";
+const COMMAND_MASK_EXTRA_WIDTH = "\uFF9E";
+const COMMAND_MASK_ZERO_WIDTH = "\u2060";
+const COMMAND_MASK_PATTERN = /\u2060|\uE000\uFF9E*/gu;
+const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
+
+class SlashCommandMarkdown implements Component {
+ private readonly markdown: Markdown;
+ private readonly commandGraphemes: string[];
+
+ constructor(text: string, markdownTheme: MarkdownTheme) {
+ const parsed = parseSlashCommand(text);
+ const commandEnd = parsed ? parsed.name.length + 1 : text.length;
+ this.commandGraphemes = [...graphemeSegmenter.segment(text.slice(0, commandEnd))].map(({ segment }) => segment);
+ const placeholder = this.commandGraphemes
+ .map((grapheme) => {
+ const width = visibleWidth(grapheme);
+ return width === 0
+ ? COMMAND_MASK_ZERO_WIDTH
+ : COMMAND_MASK_BASE + COMMAND_MASK_EXTRA_WIDTH.repeat(width - 1);
+ })
+ .join("");
+ this.markdown = new Markdown(`${placeholder}${text.slice(commandEnd)}`, 0, 0, markdownTheme, {
+ color: (content: string) => theme.fg("userMessageText", content),
+ });
+ }
+
+ render(width: number): string[] {
+ let commandOffset = 0;
+ return this.markdown.render(width).map((line) => {
+ const chunks: string[] = [];
+ const replaced = line.replace(COMMAND_MASK_PATTERN, (placeholder) => {
+ const grapheme = this.commandGraphemes[commandOffset];
+ if (grapheme === undefined) return placeholder;
+ commandOffset++;
+ chunks.push(grapheme);
+ return "";
+ });
+ return chunks.length === 0 ? replaced : `${theme.fg("accent", chunks.join(""))}${replaced}`;
+ });
+ }
+
+ invalidate(): void {
+ this.markdown.invalidate();
+ }
+}
/**
* Component that renders a user message
@@ -11,13 +59,19 @@ const OSC133_ZONE_FINAL = "\x1b]133;C\x07";
export class UserMessageComponent extends Container {
private contentBox: Box;
- constructor(text: string, markdownTheme: MarkdownTheme = getMarkdownTheme()) {
+ constructor(
+ text: string,
+ markdownTheme: MarkdownTheme = getMarkdownTheme(),
+ isRecognizedSlashCommand: (name: string) => boolean = () => false,
+ ) {
super();
this.contentBox = new Box(2, 1, (content: string) => theme.getUserMessageBackgroundColor()(content));
this.contentBox.addChild(
- new Markdown(text, 0, 0, markdownTheme, {
- color: (content: string) => theme.fg("userMessageText", content),
- }),
+ isLeadingSlashCommand(text, isRecognizedSlashCommand)
+ ? new SlashCommandMarkdown(text, markdownTheme)
+ : new Markdown(text, 0, 0, markdownTheme, {
+ color: (content: string) => theme.fg("userMessageText", content),
+ }),
);
this.addChild(this.contentBox);
}
diff --git a/packages/coding-agent/src/modes/interactive/feature-hints.ts b/packages/coding-agent/src/modes/interactive/feature-hints.ts
index 6f15fa227e..56877a0737 100644
--- a/packages/coding-agent/src/modes/interactive/feature-hints.ts
+++ b/packages/coding-agent/src/modes/interactive/feature-hints.ts
@@ -47,7 +47,7 @@ export const FEATURE_HINTS: readonly FeatureHintDefinition[] = [
getText: ({ getKeybinding, isResidentSession }) => {
if (!isResidentSession) return undefined;
const key = getKeybinding("app.agents.back");
- return key ? `Hit ${key} for Agents View, where you can manage all your running agents.` : undefined;
+ return key ? `Hit ${key} for Session View: search running, idle, and inactive sessions.` : undefined;
},
},
{
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 7b5c8672b0..2b6188d30d 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -106,6 +106,8 @@ import {
isCompactionOutcomeMessage,
isSessionSlashCommandMessage,
isSessionSlashCommandResultMessage,
+ SESSION_SLASH_COMMAND_CUSTOM_TYPE,
+ SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE,
} from "../../core/messages.js";
import { findExactModelReferenceMatch, resolveModelScopeFromModels } from "../../core/model-resolver.js";
import { parseNewSessionCommand } from "../../core/new-session-command.js";
@@ -203,12 +205,14 @@ import { formatKeyText, keyHint, keyText, rawKeyHint } from "./components/keybin
import type { AuthSelectorProvider } from "./components/oauth-selector.js";
import { PrimeOnboardingSplashComponent } from "./components/prime-onboarding-splash.js";
import { ScopedModelsSelectorComponent } from "./components/scoped-models-selector.js";
-import { SessionPickerScreen } from "./components/session-picker-screen.js";
-import { SessionSelectorComponent } from "./components/session-selector.js";
import { SettingsSelectorComponent } from "./components/settings-selector.js";
import { SideQuestionComponent } from "./components/side-question.js";
import { SkillInvocationMessageComponent } from "./components/skill-invocation-message.js";
-import { SlashCommandMessageComponent } from "./components/slash-command-message.js";
+import {
+ isLeadingSlashCommand,
+ SlashCommandMessageComponent,
+ styleSlashCommandText,
+} from "./components/slash-command-message.js";
import { SlashCommandResultMessageComponent } from "./components/slash-command-result-message.js";
import { ThinkingSelectorComponent } from "./components/thinking-selector.js";
import {
@@ -294,6 +298,17 @@ export function formatQueuedMessagePreview(message: string, label: "Steering" |
return isLabeledQueuedPreview(message) ? message : `${label}: ${message}`;
}
+export function styleQueuedMessagePreview(
+ message: string,
+ label: "Steering" | "Follow-up",
+ isRecognizedSlashCommand: (name: string) => boolean,
+): string {
+ const preview = formatQueuedMessagePreview(message, label);
+ if (!isLeadingSlashCommand(message, isRecognizedSlashCommand)) return theme.fg("dim", preview);
+ const prefix = preview.slice(0, preview.length - message.length);
+ return `${theme.fg("dim", prefix)}${styleSlashCommandText(message, (rest) => theme.fg("dim", rest))}`;
+}
+
function isExpandable(obj: unknown): obj is Expandable {
return typeof obj === "object" && obj !== null && "setExpanded" in obj && typeof obj.setExpanded === "function";
}
@@ -808,7 +823,10 @@ export interface InteractiveModeOptions {
promptStashSessionId?: string;
}
-export type InteractiveModeRunResult = "agents_view";
+export interface InteractiveModeRunResult {
+ type: "agents_view";
+ source: Pick<AgentConnectionState, "activeSessionId" | "sessionFile" | "sessionId" | "sessionName" | "cwd">;
+}
export class InteractiveMode {
private static readonly EXIT_HINT_DURATION_MS = 2000;
@@ -925,6 +943,7 @@ export class InteractiveMode {
// Serializes session event handling; see subscribeToAgent
private sessionEventQueue: Promise<void> = Promise.resolve();
+ private sessionEventGeneration = 0;
private fastModeToggleQueue: Promise<void> = Promise.resolve();
// Tool execution tracking: toolCallId -> component
@@ -948,8 +967,8 @@ export class InteractiveMode {
private childAgentWatcher: AgentConnectionSessionWatcher | undefined;
private childAgentWatcherToken = 0;
private childAgentWatcherMessages: AgentMessage[] = [];
- // Monotonic per-watch counter so a late-resolving getMessages can't clobber a newer one.
private childAgentRefreshSeq = 0;
+ private childAgentBodyBuildSeq = 0;
// The session key the current watcher attached with, so a later snapshot that
// gains the real activeSessionId can retry the attach.
private childAgentWatchedKey: string | undefined;
@@ -1261,6 +1280,10 @@ export class InteractiveMode {
}));
}
+ private isRecognizedSlashCommand(name: string): boolean {
+ return isBuiltinSlashCommandName(name) || this.connectionCommands.some((command) => command.name === name);
+ }
+
private createBaseAutocompleteProvider(): AutocompleteProvider {
// Define commands for autocomplete
const slashCommands: SlashCommand[] = BUILTIN_SLASH_COMMANDS.filter(
@@ -1686,8 +1709,9 @@ export class InteractiveMode {
() => settleStartupPrompts("admitted"),
);
- // Enter/Alt+Enter submit directly through AgentConnection. Keep run alive
- // until shutdown or a return to the agents view resolves the lifecycle wait.
+ // Enter/Alt+Enter submit directly through AgentConnection. Wait for the
+ // lifecycle signal exactly once; a returned editor value has already been
+ // admitted and must never be submitted again here.
try {
await this.getUserInput();
} finally {
@@ -1695,7 +1719,18 @@ export class InteractiveMode {
settleStartupPrompts("lifecycle-cancelled");
this.admitPendingStartupPrompts = undefined;
}
- return "agents_view";
+
+ const state = this.connectionState;
+ return {
+ type: "agents_view",
+ source: {
+ activeSessionId: state?.activeSessionId,
+ sessionFile: state?.sessionFile,
+ sessionId: state?.sessionId ?? this.promptStashSessionId ?? "",
+ sessionName: state?.sessionName,
+ cwd: state?.cwd ?? this.getCurrentCwd(),
+ },
+ };
}
private getModelFallbackWarningAction(modelFallbackMessage: string | undefined): ModelFallbackWarningAction {
@@ -2519,7 +2554,7 @@ export class InteractiveMode {
this.invalidateConnectionModelRefresh();
const [state, commands, modelCatalog, resources] = await Promise.all([
this.agentConnection.getState(),
- this.agentConnection.getCommands(),
+ this.agentConnection.getCommands().catch(() => []),
this.agentConnection.getModelCatalog(),
this.agentConnection.getResourceSnapshot(),
]);
@@ -2860,11 +2895,27 @@ export class InteractiveMode {
}
private async renderCurrentSessionState(): Promise<void> {
+ // Replacement events own the session-scoped command catalog. The daemon
+ // sends that event before its command response, but its handler may still
+ // be refreshing commands when the response resolves.
+ await this.sessionEventQueue;
this.resetCurrentSessionRenderState();
await this.renderInitialMessages();
+ // The session transition and transcript are already authoritative here;
+ // a transient queue read must not turn a successful switch into a fatal error.
+ await this.refreshConnectionQueue().catch(() => undefined);
this.syncWorkingLoader();
}
+ private async refreshCommandCatalogForCurrentSession(): Promise<void> {
+ try {
+ this.connectionCommands = await this.agentConnection.getCommands();
+ } catch {
+ this.connectionCommands = [];
+ }
+ this.setupAutocompleteProvider();
+ }
+
private async renderResyncedSession(snapshot: AgentConnectionSnapshot): Promise<void> {
const bashFinished = this.isBashRunning() && !snapshot.state.isBashRunning;
this.applyConnectionStateSnapshot(snapshot.state);
@@ -4151,15 +4202,9 @@ export class InteractiveMode {
void this.showUserMessageSelector();
});
this.defaultEditor.onAction("app.session.resume", () => {
- void this.showSessionSelector();
+ void this.requestAgentsView();
});
- this.defaultEditor.onAgentsBack = () => {
- if (!this.options.returnToAgentsView || this.editor.getText().trim()) {
- return false;
- }
- void this.returnToAgentsView();
- return true;
- };
+ this.defaultEditor.onAgentsBack = () => this.handleAgentsBack();
this.defaultEditor.onMoveBelowPrompt = () => this.focusChildAgentSummary();
this.defaultEditor.onChange = (text: string) => {
@@ -4830,11 +4875,6 @@ export class InteractiveMode {
this.editor.setText("");
return;
}
- if (text === "/resume") {
- this.editor.setText("");
- await this.showSessionSelector();
- return;
- }
if (text === "/quit") {
this.editor.setText("");
await this.shutdown();
@@ -5029,25 +5069,40 @@ export class InteractiveMode {
this.unsubscribe = this.agentConnection.subscribe(async (event) => {
try {
if (event.type === "session_event") {
- // Connection adapters dispatch without awaiting, so a handler that
- // suspends would let later events overtake it; queue session events
- // to keep paired events like bash_start/bash_end in emission order.
- const run = this.sessionEventQueue.then(() => this.handleEvent(event.event));
+ // Connection adapters dispatch without awaiting, so serialize events.
+ // Replacement advances the generation before entering this queue, which
+ // prevents already-queued source events from mutating the target UI.
+ const generation = this.sessionEventGeneration;
+ const run = this.sessionEventQueue.then(() =>
+ generation === this.sessionEventGeneration ? this.handleEvent(event.event) : undefined,
+ );
this.sessionEventQueue = run.catch(() => {});
await run;
} else if (event.type === "session_replaced") {
- this.resetSideQuestion();
- this.resetExtensionUI();
- this.applyConnectionStateSnapshot(event.state);
- this.resetCurrentSessionRenderState();
- await this.rebindCurrentSession();
- await this.renderInitialMessages();
- this.ui.requestRender();
- } else if (event.type === "session_resynced") {
- const run = this.sessionEventQueue.then(() => this.renderResyncedSession(event.snapshot));
+ const generation = ++this.sessionEventGeneration;
+ const run = this.sessionEventQueue.then(async () => {
+ if (generation !== this.sessionEventGeneration) return;
+ this.resetSideQuestion();
+ this.resetExtensionUI();
+ this.applyConnectionStateSnapshot(event.state);
+ this.resetCurrentSessionRenderState();
+ await this.rebindCurrentSession();
+ await this.renderInitialMessages();
+ this.ui.requestRender();
+ });
this.sessionEventQueue = run.catch(() => {});
await run;
- this.ui.requestRender();
+ } else if (event.type === "session_resynced") {
+ const generation = this.sessionEventGeneration;
+ const run = this.sessionEventQueue.then(async () => {
+ if (generation !== this.sessionEventGeneration) return false;
+ await this.refreshCommandCatalogForCurrentSession?.();
+ if (generation !== this.sessionEventGeneration) return false;
+ await this.renderResyncedSession(event.snapshot);
+ return true;
+ });
+ this.sessionEventQueue = run.then(() => undefined).catch(() => {});
+ if (await run) this.ui.requestRender();
} else if (event.type === "session_status") {
this.sessionRecap = event.recap;
this.patchConnectionState({ recap: event.recap });
@@ -6019,7 +6074,7 @@ export class InteractiveMode {
if (!this.options.returnToAgentsView) {
return undefined;
}
- return keyHint("app.agents.back", "agents");
+ return keyHint("app.agents.back", "agents/resume");
}
private getTrayContextLabel(): string | undefined {
@@ -6184,6 +6239,7 @@ export class InteractiveMode {
if (!watcher || token !== this.childAgentWatcherToken) {
return;
}
+ const buildSeq = ++this.childAgentBodyBuildSeq;
const messages = this.childAgentWatcherMessages;
const toolNames = new Set<string>();
for (const message of messages) {
@@ -6196,13 +6252,15 @@ export class InteractiveMode {
}
}
const definitions = new Map<string, ToolExecutionDefinition | undefined>();
+ const childCommandsPromise = watcher.getCommands().catch(() => []);
await Promise.all(
[...toolNames].map(async (name) => {
definitions.set(name, (await watcher.getToolDefinition(name).catch(() => undefined)) ?? undefined);
}),
);
- // A newer refresh (or a close) may have superseded this build while awaiting defs.
- if (token !== this.childAgentWatcherToken) {
+ const childCommands = await childCommandsPromise;
+ const childCommandNames = new Set(childCommands.map((command) => command.name));
+ if (token !== this.childAgentWatcherToken || buildSeq !== this.childAgentBodyBuildSeq) {
return;
}
this.childAgentDetail.setBodyComponents(
@@ -6217,6 +6275,7 @@ export class InteractiveMode {
hideThinkingBlock: this.hideThinkingBlock,
hiddenThinkingLabel: this.hiddenThinkingLabel,
toolsExpanded: this.toolOutputExpanded,
+ isRecognizedSlashCommand: (name) => isBuiltinSlashCommandName(name) || childCommandNames.has(name),
}),
);
}
@@ -6413,7 +6472,11 @@ export class InteractiveMode {
if (this.chatContainer.children.length > 0) {
this.chatContainer.addChild(new Spacer(1));
}
- this.chatContainer.addChild(new UserMessageComponent(text, this.getMarkdownThemeWithSettings()));
+ this.chatContainer.addChild(
+ new UserMessageComponent(text, this.getMarkdownThemeWithSettings(), (name) =>
+ this.isRecognizedSlashCommand(name),
+ ),
+ );
}
private addMessageToEditorHistory(message: AgentMessage): void {
@@ -6444,28 +6507,38 @@ export class InteractiveMode {
}
case "custom": {
if (message.display) {
+ const reservedSessionCommand =
+ message.customType === SESSION_SLASH_COMMAND_CUSTOM_TYPE ||
+ message.customType === SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE;
const component = isSessionSlashCommandMessage(message)
? new SlashCommandMessageComponent(message.content)
: isSessionSlashCommandResultMessage(message)
? new SlashCommandResultMessageComponent(message)
- : isCompactionOutcomeMessage(message)
- ? new CompactionOutcomeMessageComponent(message)
- : message.customType === COMPACTION_OUTCOME_CUSTOM_TYPE
- ? new MalformedCompactionOutcomeMessageComponent()
- : isAgentSessionMessage(message)
- ? new AgentMessageComponent(message, this.getMarkdownThemeWithSettings())
- : isInjectedPromptMessage(message)
- ? new InjectedPromptMessageComponent(message, this.getMarkdownThemeWithSettings())
- : new CustomMessageComponent(
- message,
- this.bindLocalSessionExtensions
- ? this.getLocalSessionHost()
- .getExtensionRunner()
- .getMessageRenderer(message.customType)
- : undefined,
- this.getMarkdownThemeWithSettings(),
- );
- component.setExpanded(this.toolOutputExpanded);
+ : reservedSessionCommand
+ ? new UserMessageComponent(
+ "[Malformed session command message]",
+ this.getMarkdownThemeWithSettings(),
+ )
+ : isCompactionOutcomeMessage(message)
+ ? new CompactionOutcomeMessageComponent(message)
+ : message.customType === COMPACTION_OUTCOME_CUSTOM_TYPE
+ ? new MalformedCompactionOutcomeMessageComponent()
+ : isAgentSessionMessage(message)
+ ? new AgentMessageComponent(message, this.getMarkdownThemeWithSettings())
+ : isInjectedPromptMessage(message)
+ ? new InjectedPromptMessageComponent(message, this.getMarkdownThemeWithSettings())
+ : new CustomMessageComponent(
+ message,
+ this.bindLocalSessionExtensions
+ ? this.getLocalSessionHost()
+ .getExtensionRunner()
+ .getMessageRenderer(message.customType)
+ : undefined,
+ this.getMarkdownThemeWithSettings(),
+ );
+ if (!(component instanceof UserMessageComponent)) {
+ component.setExpanded(this.toolOutputExpanded);
+ }
if (isSessionSlashCommandMessage(message) && this.chatContainer.children.length > 0) {
this.chatContainer.addChild(new Spacer(1));
}
@@ -6521,11 +6594,16 @@ export class InteractiveMode {
const userComponent = new UserMessageComponent(
skillBlock.userMessage,
this.getMarkdownThemeWithSettings(),
+ (name) => this.isRecognizedSlashCommand(name),
);
this.chatContainer.addChild(userComponent);
}
} else {
- const userComponent = new UserMessageComponent(textContent, this.getMarkdownThemeWithSettings());
+ const userComponent = new UserMessageComponent(
+ textContent,
+ this.getMarkdownThemeWithSettings(),
+ (name) => this.isRecognizedSlashCommand(name),
+ );
this.chatContainer.addChild(userComponent);
}
if (options?.populateHistory) {
@@ -6953,6 +7031,30 @@ export class InteractiveMode {
stopThemeWatcher();
}
+ private handleAgentsBack(): boolean {
+ if (this.editor.getText().trim()) {
+ return false;
+ }
+ if (!this.options.returnToAgentsView) {
+ void this.requestAgentsView();
+ return true;
+ }
+ void this.returnToAgentsView();
+ return true;
+ }
+
+ private async requestAgentsView(): Promise<void> {
+ if (this.editor.getText().length > 0) {
+ this.showStatus("Send, stash, or clear your draft before opening agents");
+ return;
+ }
+ if (!this.options.returnToAgentsView) {
+ this.showStatus("The agents view needs the daemon; start without --no-daemon to browse sessions");
+ return;
+ }
+ await this.returnToAgentsView();
+ }
+
private async returnToAgentsView(): Promise<void> {
if (this.isShuttingDown || this.returnToAgentsViewRequested) return;
this.returnToAgentsViewRequested = true;
@@ -7338,11 +7440,11 @@ export class InteractiveMode {
if (hasQueuedMessages) {
this.queuedMessagesContainer.addChild(new Spacer(1));
for (const message of steeringMessages) {
- const text = theme.fg("dim", formatQueuedMessagePreview(message, "Steering"));
+ const text = styleQueuedMessagePreview(message, "Steering", (name) => this.isRecognizedSlashCommand(name));
this.queuedMessagesContainer.addChild(new TruncatedText(text, 1, 0));
}
for (const message of followUpMessages) {
- const text = theme.fg("dim", formatQueuedMessagePreview(message, "Follow-up"));
+ const text = styleQueuedMessagePreview(message, "Follow-up", (name) => this.isRecognizedSlashCommand(name));
this.queuedMessagesContainer.addChild(new TruncatedText(text, 1, 0));
}
const dequeueHint = this.getAppKeyDisplay("app.message.dequeue");
@@ -8373,65 +8475,6 @@ export class InteractiveMode {
});
}
- private async showSessionSelector(): Promise<void> {
- let state: AgentConnectionState;
- try {
- state = await this.agentConnection.getState();
- this.applyConnectionStateSnapshot(state);
- } catch (error) {
- this.showError(error instanceof Error ? error.message : String(error));
- return;
- }
- await new Promise<void>((done) => {
- let handle: OverlayHandle | undefined;
- let settled = false;
- const close = () => {
- if (settled) {
- return;
- }
- settled = true;
- handle?.hide();
- this.ui.requestRender();
- done();
- };
- const selector = new SessionSelectorComponent(
- (callbacks) => this.agentConnection.listSavedSessions("current", callbacks),
- (callbacks) => this.agentConnection.listSavedSessions("all", callbacks),
- async (sessionPath) => {
- close();
- await this.handleResumeSession(sessionPath);
- },
- () => {
- close();
- },
- () => {
- close();
- void this.shutdown();
- },
- () => this.ui.requestRender(),
- {
- renameSession: async (sessionFilePath: string, nextName: string | undefined) => {
- const next = (nextName ?? "").trim();
- if (!next) return;
- await this.agentConnection.renameSavedSession(sessionFilePath, next);
- },
- deleteSession: (sessionFilePath: string) => this.agentConnection.deleteSavedSession(sessionFilePath),
- showRenameHint: true,
- keybindings: this.keybindings,
- frameless: true,
- },
-
- state.sessionFile,
- );
- const splash = new BrandSplashHeader(
- this.version,
- () => this.getCurrentModelId(),
- () => this.getCurrentCwd(),
- );
- handle = this.showFullPaneOverlay(new SessionPickerScreen(this.ui, splash, selector), { fullWidth: true });
- });
- }
-
private async handleResumeSession(
sessionPath: string,
options?: Parameters<ExtensionCommandContext["switchSession"]>[1],
diff --git a/packages/coding-agent/test/agents-view-commands.test.ts b/packages/coding-agent/test/agents-view-commands.test.ts
deleted file mode 100644
index 2301832d6c..0000000000
--- a/packages/coding-agent/test/agents-view-commands.test.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { describe, expect, test } from "vitest";
-import { BUILTIN_SLASH_COMMANDS } from "../src/core/slash-commands.js";
-import {
- AGENTS_VIEW_SLASH_COMMANDS,
- classifyAgentsViewCommand,
- parseSlashCommand,
- resolveAgentsViewCommand,
-} from "../src/modes/agents-view/agents-view-commands.js";
-
-describe("parseSlashCommand", () => {
- test("parses a bare command", () => {
- expect(parseSlashCommand("/login")).toEqual({ name: "login", args: "" });
- });
-
- test("parses a command with arguments", () => {
- expect(parseSlashCommand("/model opus anthropic")).toEqual({ name: "model", args: "opus anthropic" });
- });
-
- test("trims argument whitespace", () => {
- expect(parseSlashCommand("/compact focus on the bug ")).toEqual({ name: "compact", args: "focus on the bug" });
- });
-
- test("returns undefined for non-command text", () => {
- expect(parseSlashCommand("fix the bug")).toBeUndefined();
- expect(parseSlashCommand("")).toBeUndefined();
- });
-
- test("returns undefined for a lone slash", () => {
- expect(parseSlashCommand("/")).toBeUndefined();
- expect(parseSlashCommand("/ leading space")).toBeUndefined();
- });
-});
-
-describe("classifyAgentsViewCommand", () => {
- test("whitelisted global commands run in the agents view", () => {
- for (const name of ["login", "logout", "model", "mcp", "resume", "quit"]) {
- expect(classifyAgentsViewCommand(name)).toBe("agents-view");
- }
- });
-
- test("other built-ins are session-only", () => {
- for (const name of ["compact", "fork", "settings", "new", "clear", "export"]) {
- expect(classifyAgentsViewCommand(name)).toBe("session-only");
- }
- });
-
- test("aliases classify by their canonical built-in target", () => {
- expect(classifyAgentsViewCommand("clear")).toBe("session-only");
- expect(resolveAgentsViewCommand({ name: "clear", args: "" })).toEqual({ name: "new", args: "" });
- });
-
- test("non-built-ins pass through for daemon-side expansion", () => {
- expect(classifyAgentsViewCommand("skill:create-pr")).toBe("unknown");
- expect(classifyAgentsViewCommand("my-template")).toBe("unknown");
- });
-});
-
-describe("AGENTS_VIEW_SLASH_COMMANDS", () => {
- test("every whitelisted command is a built-in with a description", () => {
- const builtinNames = new Set(BUILTIN_SLASH_COMMANDS.map((command) => command.name));
- for (const command of AGENTS_VIEW_SLASH_COMMANDS) {
- expect(builtinNames.has(command.name)).toBe(true);
- expect(command.description.length).toBeGreaterThan(0);
- }
- });
-
- test("classification agrees with the command list", () => {
- for (const command of AGENTS_VIEW_SLASH_COMMANDS) {
- expect(classifyAgentsViewCommand(command.name)).toBe("agents-view");
- }
- });
-});
diff --git a/packages/coding-agent/test/agents-view-inactive-reply.test.ts b/packages/coding-agent/test/agents-view-inactive-reply.test.ts
new file mode 100644
index 0000000000..ae3556f256
--- /dev/null
+++ b/packages/coding-agent/test/agents-view-inactive-reply.test.ts
@@ -0,0 +1,754 @@
+import { setKeybindings } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import { KeybindingsManager } from "../src/core/keybindings.js";
+import {
+ AgentsViewMode,
+ createReplyComposerAutocompleteProvider,
+ getReplyComposerCommandRejection,
+ parseAgentsViewCommand,
+} from "../src/modes/agents-view/agents-view-mode.js";
+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
+
+function summary(overrides: Partial<SessionSummary>): SessionSummary {
+ return {
+ id: "saved-1",
+ lifecycle: "archived",
+ activity: "idle",
+ sessionId: "saved-1",
+ cwd: process.cwd(),
+ isStreaming: false,
+ isCompacting: false,
+ attachedClients: 0,
+ messageCount: 3,
+ pendingMessageCount: 0,
+ ...overrides,
+ };
+}
+
+function invoke(method: string, self: object, ...args: unknown[]): unknown {
+ const member = Reflect.get(AgentsViewMode.prototype, method) as ((...a: unknown[]) => unknown) | undefined;
+ if (typeof member !== "function") {
+ throw new Error(`AgentsViewMode.${method} no longer exists; update this test harness`);
+ }
+ return member.call(self, ...args);
+}
+
+function editorWithText(initial: string) {
+ let text = initial;
+ return {
+ getText: () => text,
+ setText: vi.fn((next: string) => {
+ text = next;
+ }),
+ };
+}
+
+describe("agents view reply on inactive sessions", () => {
+ beforeAll(() => {
+ setKeybindings(new KeybindingsManager());
+ });
+
+ const savedSummary = summary({
+ sessionFile: "/tmp/sessions/saved-1.jsonl",
+ cwd: process.cwd(),
+ summary: "Persisted recap text",
+ firstMessage: "opener",
+ });
+
+ it("arms the composer on a saved-only row using the persisted recap", async () => {
+ const setReplyTarget = vi.fn();
+ const requestRender = vi.fn();
+ const self: Record<string, unknown> = {
+ rows: [
+ { kind: "agent", selectable: true, identity: "file:/tmp/sessions/saved-1.jsonl", summary: savedSummary },
+ ],
+ selectedIndex: 0,
+ pendingDeleteAgent: undefined,
+ replyTarget: undefined,
+ setReplyTarget,
+ ui: { requestRender },
+ requireClient: () => {
+ throw new Error("saved rows must not hit the daemon for a preview");
+ },
+ };
+
+ await invoke("toggleReplyTarget", self);
+
+ expect(setReplyTarget).toHaveBeenCalledWith({ key: "saved-1", summary: savedSummary });
+ expect(self.replyLastAssistantText).toBe("Persisted recap text");
+ });
+
+ it("ignores rows with neither a runtime nor a session file", async () => {
+ const setReplyTarget = vi.fn();
+ const self = {
+ rows: [{ kind: "agent", selectable: true, identity: "session:saved-1", summary: summary({}) }],
+ selectedIndex: 0,
+ setReplyTarget,
+ };
+
+ await invoke("toggleReplyTarget", self);
+
+ expect(setReplyTarget).not.toHaveBeenCalled();
+ });
+
+ it("resumes a saved session before delivering the reply", async () => {
+ const request = vi.fn(async (command: { type: string }) => {
+ if (command.type === "create") {
+ return {
+ success: true,
+ data: { ...savedSummary, lifecycle: "live", activeSessionId: "active-9", isStreaming: true },
+ };
+ }
+ return { success: true, data: {} };
+ });
+ const target = { key: "saved-1", summary: savedSummary };
+ const self: Record<string, unknown> = {
+ options: { config: { cwd: process.cwd() } },
+ requireClient: () => ({ request }),
+ replyTarget: target,
+ // Stale pre-resume rows do not know the resumed session; scheduling must
+ // come from the resume response instead.
+ findSummaryByActiveSessionId: () => undefined,
+ inactiveAgentIdentities: new Set(["file:/tmp/sessions/saved-1.jsonl"]),
+ setStatusMessage: vi.fn(),
+ setReplyTarget: vi.fn(),
+ refreshSessions: vi.fn(async () => true),
+ selectSummary: vi.fn(),
+ sendPrompt: vi.fn(async () => {}),
+ };
+
+ await invoke("sendReply", self, target, "wake up");
+
+ expect(request).toHaveBeenCalledWith(
+ expect.objectContaining({ type: "create", sessionPath: savedSummary.sessionFile }),
+ );
+ expect(self.sendPrompt).toHaveBeenCalledWith("active-9", "wake up", "steer");
+ expect(self.selectSummary).toHaveBeenCalledWith(expect.objectContaining({ activeSessionId: "active-9" }));
+ expect(self.inactiveAgentIdentities).not.toContain("file:/tmp/sessions/saved-1.jsonl");
+ expect(self.setReplyTarget).not.toHaveBeenCalled();
+ });
+
+ it("does not select a resumed session after its reply target is cancelled", async () => {
+ let finishResume: ((result: { success: true; data: SessionSummary }) => void) | undefined;
+ const request = vi.fn(
+ () =>
+ new Promise<{ success: true; data: SessionSummary }>((resolve) => {
+ finishResume = resolve;
+ }),
+ );
+ const target = { key: "saved-1", summary: savedSummary };
+ const selection = { activeSessionId: "active-2" };
+ const selectSummary = vi.fn((next: SessionSummary) => {
+ selection.activeSessionId = next.activeSessionId ?? next.id;
+ });
+ const sendPrompt = vi.fn(async () => {});
+ const self: Record<string, unknown> = {
+ options: { config: { cwd: process.cwd() } },
+ requireClient: () => ({ request }),
+ findSummaryByActiveSessionId: () => undefined,
+ inactiveAgentIdentities: new Set(["file:/tmp/sessions/saved-1.jsonl"]),
+ replyTarget: target,
+ setStatusMessage: vi.fn(),
+ selectSummary,
+ sendPrompt,
+ };
+
+ const reply = invoke("sendReply", self, target, "wake up") as Promise<boolean>;
+ await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
+ self.replyTarget = undefined;
+ finishResume?.({
+ success: true,
+ data: { ...savedSummary, lifecycle: "live", activeSessionId: "active-9" },
+ });
+
+ await expect(reply).resolves.toBe(true);
+ expect(selectSummary).not.toHaveBeenCalled();
+ expect(selection.activeSessionId).toBe("active-2");
+ expect(sendPrompt).toHaveBeenCalledWith("active-9", "wake up", undefined);
+ expect(self.inactiveAgentIdentities).not.toContain("file:/tmp/sessions/saved-1.jsonl");
+ });
+
+ it("preserves a replacement composer when an older reply succeeds", async () => {
+ const editor = editorWithText("old reply");
+ const oldTarget = { key: "saved-1", summary: savedSummary };
+ const newTarget = {
+ key: "active-2",
+ summary: summary({ id: "active-2", activeSessionId: "active-2", lifecycle: "live" }),
+ };
+ const self: Record<string, unknown> = {
+ replyTarget: oldTarget,
+ options: {},
+ editor,
+ setReplyTarget: vi.fn(),
+ refreshSessions: vi.fn(async () => true),
+ sendReply: vi.fn(async () => {
+ self.replyTarget = newTarget;
+ editor.setText("new reply");
+ return true;
+ }),
+ };
+
+ await invoke("submit", self, "old reply");
+
+ expect(self.replyTarget).toBe(newTarget);
+ expect(editor.getText()).toBe("new reply");
+ expect(self.setReplyTarget).not.toHaveBeenCalled();
+ expect(self.refreshSessions).toHaveBeenCalledWith({ preserveStatusOnError: true });
+ });
+
+ it("preserves new text entered while the same reply succeeds", async () => {
+ const editor = editorWithText("first reply");
+ const target = { key: "saved-1", summary: savedSummary };
+ const self: Record<string, unknown> = {
+ replyTarget: target,
+ options: {},
+ editor,
+ setReplyTarget: vi.fn(),
+ refreshSessions: vi.fn(async () => true),
+ sendReply: vi.fn(async () => {
+ editor.setText("next reply");
+ return true;
+ }),
+ };
+
+ await invoke("submit", self, "first reply");
+
+ expect(self.replyTarget).toBe(target);
+ expect(editor.getText()).toBe("next reply");
+ expect(self.setReplyTarget).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { name: "resume failure", failure: "resume", remainsInactive: true },
+ { name: "send failure", failure: "send", remainsInactive: false },
+ {
+ name: "replacement text entered during send failure",
+ failure: "send",
+ replacement: "replacement",
+ remainsInactive: false,
+ },
+ ] as const)("handles $name", async ({ failure, replacement, remainsInactive }) => {
+ const editor = editorWithText("wake up");
+ const target = { key: "saved-1", summary: savedSummary };
+ const inactiveAgentIdentities = new Set(["file:/tmp/sessions/saved-1.jsonl"]);
+ const request = vi.fn(async () => {
+ if (failure === "resume") throw new Error("resume failed");
+ return {
+ success: true,
+ data: { ...savedSummary, lifecycle: "live", activeSessionId: "active-9" },
+ };
+ });
+ const sendPrompt = vi.fn(async () => {
+ if (replacement) editor.setText(replacement);
+ throw new Error("send failed");
+ });
+ const self: Record<string, unknown> = {
+ options: { config: { cwd: process.cwd() } },
+ requireClient: () => ({ request }),
+ findSummaryByActiveSessionId: () => undefined,
+ inactiveAgentIdentities,
+ replyTarget: target,
+ editor,
+ setStatusMessage: vi.fn(),
+ setReplyTarget: vi.fn(),
+ refreshSessions: vi.fn(async () => true),
+ selectSummary: vi.fn(),
+ sendPrompt,
+ sendReply: (replyTarget: unknown, text: string) => invoke("sendReply", self, replyTarget, text),
+ };
+
+ await invoke("submit", self, "wake up");
+
+ expect(editor.setText).toHaveBeenNthCalledWith(1, "");
+ expect(editor.getText()).toBe(replacement ?? "wake up");
+ expect(inactiveAgentIdentities.has("file:/tmp/sessions/saved-1.jsonl")).toBe(remainsInactive);
+ expect(self.refreshSessions).toHaveBeenCalledTimes(remainsInactive ? 0 : 1);
+ if (!remainsInactive) {
+ expect(self.refreshSessions).toHaveBeenCalledWith({ preserveStatusOnError: true });
+ }
+ });
+
+ it("keeps the cwd-fallback notice visible after the reply is sent", async () => {
+ const missingCwd = "/definitely/not/a/real/dir/for/this/test";
+ const savedWithMissingCwd = { ...savedSummary, cwd: missingCwd };
+ const request = vi.fn(async () => ({
+ success: true,
+ data: { ...savedWithMissingCwd, lifecycle: "live", activeSessionId: "active-9" },
+ }));
+ const statuses: Array<[string, { sticky?: boolean } | undefined]> = [];
+ const self: Record<string, unknown> = {
+ options: { config: { cwd: process.cwd() } },
+ requireClient: () => ({ request }),
+ findSummaryByActiveSessionId: () => undefined,
+ inactiveAgentIdentities: new Set(["file:/tmp/sessions/saved-1.jsonl"]),
+ setStatusMessage: vi.fn((message: string, options?: { sticky?: boolean }) => {
+ statuses.push([message, options]);
+ }),
+ setReplyTarget: vi.fn(),
+ refreshSessions: vi.fn(async () => true),
+ selectSummary: vi.fn(),
+ sendPrompt: vi.fn(async () => {}),
+ };
+
+ await invoke("sendReply", self, { key: "saved-1", summary: savedWithMissingCwd }, "wake up");
+
+ const last = statuses.at(-1);
+ expect(last?.[0]).toContain("Original directory is missing");
+ expect(last?.[1]).toEqual({ sticky: true });
+ });
+
+ it("resumes the current saved row when an armed live target becomes inactive", async () => {
+ const capturedLive = summary({
+ activeSessionId: "active-dead",
+ lifecycle: "live",
+ sessionFile: savedSummary.sessionFile,
+ });
+ const currentSaved = { ...savedSummary, activeSessionId: undefined };
+ const request = vi.fn(async () => ({
+ success: true,
+ data: { ...currentSaved, lifecycle: "live", activeSessionId: "active-new" },
+ }));
+ const self: Record<string, unknown> = {
+ options: { config: { cwd: process.cwd() } },
+ requireClient: () => ({ request }),
+ unifiedRecords: [
+ {
+ daemon: currentSaved,
+ identity: "file:/tmp/sessions/saved-1.jsonl",
+ identityAliases: ["file:/tmp/sessions/saved-1.jsonl"],
+ section: "inactive",
+ searchableText: "",
+ },
+ ],
+ findSummaryByActiveSessionId: () => undefined,
+ inactiveAgentIdentities: new Set<string>(),
+ replyTarget: undefined,
+ setStatusMessage: vi.fn(),
+ selectSummary: vi.fn(),
+ sendPrompt: vi.fn(async () => {}),
+ };
+
+ await invoke("sendReply", self, { key: "active-dead", summary: capturedLive }, "wake up");
+
+ expect(request).toHaveBeenCalledWith(
+ expect.objectContaining({ type: "create", sessionPath: savedSummary.sessionFile }),
+ );
+ expect(self.sendPrompt).toHaveBeenCalledWith("active-new", "wake up", undefined);
+ expect(self.sendPrompt).not.toHaveBeenCalledWith("active-dead", expect.anything(), expect.anything());
+ });
+
+ it("replies to live sessions without resuming, steering or queueing per delivery", async () => {
+ let liveSummary = summary({ activeSessionId: "active-1", lifecycle: "live" });
+ const request = vi.fn();
+ const self: Record<string, unknown> = {
+ options: { config: {} },
+ requireClient: () => ({ request }),
+ findSummaryByActiveSessionId: () => liveSummary,
+ setStatusMessage: vi.fn(),
+ selectSummary: vi.fn(),
+ sendPrompt: vi.fn(async () => {}),
+ };
+ const target = () => ({ key: "active-1", summary: liveSummary });
+
+ await invoke("sendReply", self, target(), "hello");
+ expect(self.sendPrompt).toHaveBeenCalledWith("active-1", "hello", undefined);
+
+ liveSummary = summary({ activeSessionId: "active-1", lifecycle: "live", isStreaming: true });
+ await invoke("sendReply", self, target(), "change course");
+ expect(self.sendPrompt).toHaveBeenCalledWith("active-1", "change course", "steer");
+
+ await invoke("sendReply", self, target(), "later please", "followUp");
+ expect(self.sendPrompt).toHaveBeenCalledWith("active-1", "later please", "followUp");
+
+ expect(request).not.toHaveBeenCalled();
+ expect(self.selectSummary).not.toHaveBeenCalled();
+ });
+
+ it("alt+enter submits expanded text as followUp, only with an armed target and text", () => {
+ const submit = vi.fn(async () => {});
+ invoke("handleReplyFollowUp", { replyTarget: undefined, editor: { getExpandedText: () => "text" }, submit });
+ invoke("handleReplyFollowUp", {
+ replyTarget: { key: "a", summary: summary({}) },
+ editor: { getExpandedText: () => " " },
+ submit,
+ });
+ expect(submit).not.toHaveBeenCalled();
+
+ invoke("handleReplyFollowUp", {
+ replyTarget: { key: "active-1", summary: summary({ activeSessionId: "active-1" }) },
+ editor: { getExpandedText: () => "expanded paste body" },
+ submit,
+ });
+ expect(submit).toHaveBeenCalledWith("expanded paste body", "followUp");
+ });
+
+ it("ctrl+c disarms the composer instead of starting the exit flow", () => {
+ const setReplyTarget = vi.fn();
+ const handleCtrlC = vi.fn();
+ const self: Record<string, unknown> = {
+ clearStickyStatusMessage: vi.fn(),
+ renameTarget: undefined,
+ keybindings: { matches: (_d: string, action: string) => action === "app.clear" },
+ replyTarget: { key: "active-1", summary: summary({ activeSessionId: "active-1" }) },
+ setReplyTarget,
+ handleCtrlC,
+ };
+
+ invoke("handleInput", self, "\x03");
+
+ expect(setReplyTarget).toHaveBeenCalledWith(undefined);
+ expect(handleCtrlC).not.toHaveBeenCalled();
+ });
+
+ it("creates a new daemon session over a dedicated connection and opens it", async () => {
+ const created = summary({ id: "active-new", activeSessionId: "active-new", lifecycle: "live" });
+ const request = vi.fn(async () => ({ success: true, data: created }));
+ const close = vi.fn();
+ const finish = vi.fn();
+ const self: Record<string, unknown> = {
+ creatingNewSession: false,
+ options: { config: { cwd: process.cwd() } },
+ connectDedicatedClient: vi.fn(async () => ({ request, close })),
+ setStatusMessage: vi.fn(),
+ selectSummary: vi.fn(),
+ finish,
+ };
+
+ await invoke("createNewSession", self);
+
+ expect(request).toHaveBeenCalledWith(expect.objectContaining({ type: "create" }));
+ expect(self.selectSummary).toHaveBeenCalledWith(created);
+ expect(finish).toHaveBeenCalledWith({ type: "open", summary: created });
+ expect(close).toHaveBeenCalled();
+ });
+
+ it("kills a session created after the view already finished", async () => {
+ const created = summary({ id: "active-new", activeSessionId: "active-new", lifecycle: "live" });
+ const requests: { type: string }[] = [];
+ const self: Record<string, unknown> = {
+ creatingNewSession: false,
+ stopped: false,
+ options: { config: {} },
+ connectDedicatedClient: vi.fn(async () => ({
+ close: vi.fn(),
+ request: vi.fn(async (command: { type: string }) => {
+ requests.push(command);
+ // The view finishes while create is in flight.
+ self.stopped = true;
+ return { success: true, data: created };
+ }),
+ })),
+ setStatusMessage: vi.fn(),
+ selectSummary: vi.fn(),
+ finish: vi.fn(),
+ };
+
+ await invoke("createNewSession", self);
+
+ expect(requests.map((r) => r.type)).toEqual(["create", "kill"]);
+ expect(self.finish).not.toHaveBeenCalled();
+ expect(self.selectSummary).not.toHaveBeenCalled();
+ });
+
+ it("reports create failures and resets the guard", async () => {
+ // Failure after connecting.
+ const finish = vi.fn();
+ const setStatusMessage = vi.fn();
+ const self: Record<string, unknown> = {
+ creatingNewSession: false,
+ options: { config: {} },
+ connectDedicatedClient: vi.fn(async () => ({
+ request: vi.fn(async () => {
+ throw new Error("daemon busy");
+ }),
+ close: vi.fn(),
+ })),
+ setStatusMessage,
+ selectSummary: vi.fn(),
+ finish,
+ };
+ await expect(invoke("createNewSession", self)).resolves.toBe(false);
+ expect(finish).not.toHaveBeenCalled();
+ expect(setStatusMessage).toHaveBeenCalledWith(expect.stringContaining("Failed to create session"));
+ expect(self.creatingNewSession).toBe(false);
+
+ // Failure to connect at all must also reset the guard.
+ self.creatingNewSession = false;
+ self.connectDedicatedClient = vi.fn(async () => {
+ throw new Error("Agents view daemon socket is not configured");
+ });
+ await expect(invoke("createNewSession", self)).resolves.toBe(false);
+ expect(self.creatingNewSession).toBe(false);
+ });
+
+ it("shows composer-mode hints that track target state and typed text", () => {
+ const live = summary({ activeSessionId: "active-1", lifecycle: "live", isStreaming: true });
+ const self: Record<string, unknown> = {
+ replyTarget: { key: "active-1", summary: live },
+ unifiedRecords: [],
+ findSummaryByActiveSessionId: () => live,
+ editor: editorWithText(""),
+ };
+
+ const idleHints = stripAnsi(invoke("renderReplyComposerHints", self) as string);
+ expect(idleHints).toContain("steer");
+ expect(idleHints).toContain("cancel");
+ expect(idleHints).not.toContain("queue");
+
+ self.editor = editorWithText("some reply");
+ const typedHints = stripAnsi(invoke("renderReplyComposerHints", self) as string);
+ expect(typedHints).toContain("queue");
+
+ const saved = summary({ sessionFile: "/tmp/sessions/saved-1.jsonl" });
+ self.replyTarget = { key: "saved-1", summary: saved };
+ self.findSummaryByActiveSessionId = () => undefined;
+ const savedHints = stripAnsi(invoke("renderReplyComposerHints", self) as string);
+ expect(savedHints).toContain("resume & send");
+ });
+});
+
+describe("reply composer slash commands", () => {
+ it("classifies composer input: session commands pass, other built-ins reject, plain text flows", () => {
+ expect(getReplyComposerCommandRejection("/compact focus on the API work")).toBeUndefined();
+ expect(getReplyComposerCommandRejection("/goal ship it")).toBeUndefined();
+ expect(getReplyComposerCommandRejection("/model gpt-5")).toContain("/model is not available here");
+ expect(getReplyComposerCommandRejection("/settings")).toContain("not available here");
+ expect(getReplyComposerCommandRejection("/usr/local/bin looks wrong")).toBeUndefined();
+ expect(getReplyComposerCommandRejection("plain reply")).toBeUndefined();
+ });
+
+ it("restores rejected-command drafts without overwriting newer typing", async () => {
+ // submitValue empties the editor before onSubmit runs.
+ const editor = editorWithText("");
+ const setStatusMessage = vi.fn();
+ const sendReply = vi.fn();
+ const self: Record<string, unknown> = {
+ replyTarget: { key: "active-1", summary: summary({ activeSessionId: "active-1" }) },
+ options: {},
+ editor,
+ setStatusMessage,
+ sendReply,
+ };
+
+ await invoke("submit", self, "/model gpt-5");
+ expect(sendReply).not.toHaveBeenCalled();
+ expect(setStatusMessage).toHaveBeenCalledWith(expect.stringContaining("not available here"), {
+ tone: "warning",
+ });
+ expect(editor.getText()).toBe("/model gpt-5");
+
+ editor.setText("newer draft");
+ await invoke("submit", self, "/settings");
+ expect(editor.getText()).toBe("newer draft");
+ });
+
+ it("binds reply autocomplete to the armed target's cwd", () => {
+ const self: Record<string, unknown> = {
+ replyTarget: undefined,
+ replyAutocomplete: undefined,
+ actionModeSearchQuery: undefined,
+ persistentState: {},
+ editor: Object.assign(editorWithText(""), { setPlaceholder: vi.fn() }),
+ replyLastAssistantText: undefined,
+ replyLastAssistantTextLoading: false,
+ replyHeaderTime: "",
+ rebuildRows: vi.fn(),
+ ui: { requestRender: vi.fn() },
+ };
+ const target = { key: "active-1", summary: summary({ activeSessionId: "active-1", cwd: "/tmp/elsewhere" }) };
+ invoke("setReplyTarget", self, target);
+ expect(self.replyAutocomplete).toBeDefined();
+ invoke("setReplyTarget", self, undefined);
+ expect(self.replyAutocomplete).toBeUndefined();
+ });
+});
+
+describe("agents view slash commands", () => {
+ it("parses whitelisted view commands, which the composer never rejects", () => {
+ expect(parseAgentsViewCommand("/name My Agent")).toEqual({ name: "name", args: "My Agent" });
+ expect(parseAgentsViewCommand("/rename My Agent")).toEqual({ name: "name", args: "My Agent" });
+ expect(parseAgentsViewCommand("/kill")).toEqual({ name: "kill", args: "" });
+ expect(parseAgentsViewCommand("/compact")).toBeUndefined();
+ expect(parseAgentsViewCommand("plain search text")).toBeUndefined();
+ expect(getReplyComposerCommandRejection("/kill")).toBeUndefined();
+ // /new and /fork are builtins but not composer commands; rejected with guidance.
+ expect(getReplyComposerCommandRejection("/new")).toContain("not available here");
+ expect(getReplyComposerCommandRejection("/fork")).toContain("not available here");
+ });
+
+ it("suggests session and view commands in the armed composer", async () => {
+ const composer = createReplyComposerAutocompleteProvider(process.cwd());
+ const signal = new AbortController().signal;
+ const composerNames =
+ (await composer.getSuggestions(["/"], 0, 1, { signal }))?.items.map((item) => item.value) ?? [];
+ expect(composerNames).toEqual(
+ expect.arrayContaining(["compact", "refine", "goal", "autonomous", "name", "kill"]),
+ );
+ expect(composerNames).not.toContain("new");
+ expect(composerNames).not.toContain("model");
+ expect(composerNames).not.toContain("settings");
+ });
+
+ it("search submit always opens the selection, even for slash-prefixed text", async () => {
+ const openSelected = vi.fn();
+ const self: Record<string, unknown> = {
+ replyTarget: undefined,
+ renameTarget: undefined,
+ openSelected,
+ };
+
+ await invoke("submit", self, "release planner");
+ await invoke("submit", self, "/kill");
+
+ expect(openSelected).toHaveBeenCalledTimes(2);
+ });
+
+ it("renames a live target via the rename RPC and refreshes both catalogs", async () => {
+ const live = summary({ activeSessionId: "active-1", lifecycle: "live" });
+ const request = vi.fn(async () => ({ success: true, data: {} }));
+ const editor = editorWithText("/name Fresh Name");
+ const self: Record<string, unknown> = {
+ options: {},
+ requireClient: () => ({ request }),
+ editor,
+ setStatusMessage: vi.fn(),
+ refreshSessions: vi.fn(async () => true),
+ refreshSavedSessions: vi.fn(async () => true),
+ renameSession(s: unknown, n: string) {
+ return invoke("renameSession", self, s, n);
+ },
+ refreshBothCatalogs() {
+ return invoke("refreshBothCatalogs", self);
+ },
+ };
+
+ await expect(invoke("runAgentsViewCommand", self, { name: "name", args: "Fresh Name" }, live)).resolves.toBe(
+ true,
+ );
+
+ expect(request).toHaveBeenCalledWith({ type: "rename", activeSessionId: "active-1", name: "Fresh Name" });
+ expect(self.refreshSessions).toHaveBeenCalledWith({ preserveStatusOnError: true });
+ expect(self.refreshSavedSessions).toHaveBeenCalledWith({ preserveStatusOnError: true });
+ });
+
+ it("kills a live target and disarms the composer", async () => {
+ const live = summary({ activeSessionId: "active-1", lifecycle: "live" });
+ const request = vi.fn(async () => ({ success: true, data: {} }));
+ const setReplyTarget = vi.fn();
+ const self: Record<string, unknown> = {
+ requireClient: () => ({ request }),
+ editor: editorWithText("/kill"),
+ setStatusMessage: vi.fn(),
+ setReplyTarget,
+ replyTarget: { key: "active-1", summary: live },
+ refreshBothCatalogs: vi.fn(async () => true),
+ };
+
+ await invoke("runAgentsViewCommand", self, { name: "kill", args: "" }, live);
+
+ expect(request).toHaveBeenCalledWith({ type: "kill", activeSessionId: "active-1" });
+ expect(setReplyTarget).toHaveBeenCalledWith(undefined);
+ expect(self.refreshBothCatalogs).toHaveBeenCalled();
+
+ // An agent that finished before the RPC still counts as stopped.
+ self.request = undefined;
+ self.requireClient = () => ({
+ request: vi.fn(async () => ({ success: false, error: "Unknown active session: active-1" })),
+ });
+ await expect(invoke("runAgentsViewCommand", self, { name: "kill", args: "" }, live)).resolves.toBe(true);
+ });
+
+ it("does not disarm a composer that was re-armed during the command", async () => {
+ const live = summary({ activeSessionId: "active-1", lifecycle: "live" });
+ const originalTarget = { key: "active-1", summary: live };
+ const newTarget = { key: "active-2", summary: summary({ activeSessionId: "active-2" }) };
+ const setReplyTarget = vi.fn();
+ const self: Record<string, unknown> = {
+ requireClient: () => ({
+ request: vi.fn(async () => {
+ // The user re-arms against a different agent mid-RPC.
+ self.replyTarget = newTarget;
+ return { success: true, data: {} };
+ }),
+ }),
+ editor: editorWithText(""),
+ setStatusMessage: vi.fn(),
+ setReplyTarget,
+ replyTarget: originalTarget,
+ refreshBothCatalogs: vi.fn(async () => true),
+ };
+
+ await invoke("runAgentsViewCommand", self, { name: "kill", args: "" }, live);
+
+ expect(setReplyTarget).not.toHaveBeenCalled();
+ });
+
+ it("restores the command draft when the armed command fails", async () => {
+ const live = summary({ activeSessionId: "active-1", lifecycle: "live" });
+ const target = { key: "active-1", summary: live };
+ const editor = editorWithText("");
+ const self: Record<string, unknown> = {
+ replyTarget: target,
+ options: {},
+ unifiedRecords: [],
+ findSummaryByActiveSessionId: () => live,
+ editor,
+ setStatusMessage: vi.fn(),
+ runAgentsViewCommand: vi.fn(async () => false),
+ };
+
+ await invoke("submit", self, "/name");
+
+ expect(editor.getText()).toBe("/name");
+ });
+
+ it("re-resolves the armed target before dispatching a view command", async () => {
+ const stale = summary({ sessionFile: "/tmp/sessions/saved-1.jsonl" });
+ const liveNow = summary({
+ sessionFile: "/tmp/sessions/saved-1.jsonl",
+ activeSessionId: "active-9",
+ lifecycle: "live",
+ });
+ const runAgentsViewCommand = vi.fn(async () => true);
+ const self: Record<string, unknown> = {
+ replyTarget: { key: "saved-1", summary: stale },
+ options: {},
+ unifiedRecords: [
+ {
+ daemon: liveNow,
+ identity: "file:/tmp/sessions/saved-1.jsonl",
+ identityAliases: ["file:/tmp/sessions/saved-1.jsonl"],
+ section: "idle",
+ searchableText: "",
+ },
+ ],
+ findSummaryByActiveSessionId: () => undefined,
+ editor: editorWithText(""),
+ runAgentsViewCommand,
+ };
+
+ await invoke("submit", self, "/kill");
+
+ expect(runAgentsViewCommand).toHaveBeenCalledWith(
+ { name: "kill", args: "" },
+ expect.objectContaining({ activeSessionId: "active-9" }),
+ );
+ });
+
+ it("refuses /kill on an inactive row", async () => {
+ const saved = summary({ sessionFile: "/tmp/sessions/saved-1.jsonl" });
+ const request = vi.fn();
+ const setStatusMessage = vi.fn();
+ const self: Record<string, unknown> = {
+ requireClient: () => ({ request }),
+ editor: editorWithText("/kill"),
+ setStatusMessage,
+ };
+
+ await invoke("runAgentsViewCommand", self, { name: "kill", args: "" }, saved);
+
+ expect(request).not.toHaveBeenCalled();
+ expect(setStatusMessage).toHaveBeenCalledWith(expect.stringContaining("inactive"), { tone: "warning" });
+ });
+});
diff --git a/packages/coding-agent/test/agents-view-mode.test.ts b/packages/coding-agent/test/agents-view-mode.test.ts
new file mode 100644
index 0000000000..ed1f9a0c0c
--- /dev/null
+++ b/packages/coding-agent/test/agents-view-mode.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it, vi } from "vitest";
+import { AgentsViewMode } from "../src/modes/agents-view/agents-view-mode.js";
+
+describe("AgentsViewMode search selection", () => {
+ it("keeps the selection chosen by row rebuilding when the query changes", () => {
+ const self = {
+ editor: { getText: () => "matching query" },
+ persistentState: { query: "" },
+ selectedIndex: 4,
+ rebuildRows: vi.fn(),
+ syncSelectedRowState: vi.fn(),
+ ui: { requestRender: vi.fn() },
+ };
+
+ (AgentsViewMode.prototype as unknown as { queryChanged(this: typeof self): void }).queryChanged.call(self);
+
+ expect(self.persistentState.query).toBe("matching query");
+ expect(self.rebuildRows).toHaveBeenCalledOnce();
+ expect(self.selectedIndex).toBe(4);
+ });
+});
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index c17a429604..73f26d21e7 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -1,32 +1,32 @@
-import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import type { AutocompleteItem } from "@earendil-works/pi-tui";
import { 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";
import type { SettingsManager } from "../src/core/settings-manager.js";
import {
- createAgentsViewAutocompleteProvider,
createAgentsViewListCommand,
createAgentsViewReplyHeadline,
createAgentsViewResumeConfig,
- createAgentsViewSessionName,
formatAgentsViewRelativeTime,
formatAgentsViewStatusLine,
resolveAgentsViewActiveSummaryForPath,
- resolveAgentsViewAutocompleteCwd,
resolveAgentsViewOpenCwd,
- resolveAgentsViewResumeSummary,
resolveAgentsViewSessionUiServices,
shouldReconnectAgentsViewDaemon,
} from "../src/modes/agents-view/agents-view-mode.js";
import {
+ aggregateSessionHeartbeats,
buildAgentsViewRows,
classifyAgentsViewSession,
+ filterUnifiedSessions,
+ formatHeartbeatBadge,
getAgentsViewSelectionKey,
+ reconcileUnifiedSessions,
resolveAgentsViewSelectionIndex,
+ resolveAgentsViewSelectionState,
type SessionSummary,
sectionTitle,
shouldShowAgentsViewSession,
@@ -34,50 +34,65 @@ import {
import type { InteractiveModeUiServices } from "../src/modes/interactive/interactive-mode-services.js";
import type { Theme } from "../src/modes/interactive/theme/theme.js";
+function heartbeat(id: string, nextRunAt?: string, activeSessionId = "child") {
+ return {
+ job: {
+ id,
+ status: "active" as const,
+ activeSessionId,
+ sessionId: `${activeSessionId}-session`,
+ sessionFile: `/tmp/${activeSessionId}.jsonl`,
+ cwd: "/tmp",
+ prompt: "tick",
+ schedule: { kind: "interval" as const, expression: "5m" },
+ createdAt: "2026-01-01T00:00:00Z",
+ updatedAt: "2026-01-01T00:00:00Z",
+ ...(nextRunAt ? { nextRunAt } : {}),
+ runCount: 0,
+ },
+ };
+}
+
describe("agents view state", () => {
test("classifies active daemon sessions into coarse fleet sections", () => {
- expect(classifyAgentsViewSession(makeSummary({ isStreaming: true, activity: "working" }))).toBe("working");
- expect(classifyAgentsViewSession(makeSummary({ pendingMessageCount: 1, activity: "working" }))).toBe("working");
- expect(classifyAgentsViewSession(makeSummary({ activity: "working" }))).toBe("working");
- expect(classifyAgentsViewSession(makeSummary({ activity: "idle", messageCount: 2 }))).toBe("needs-input");
- expect(classifyAgentsViewSession(makeSummary({ activity: "idle", messageCount: 0 }))).toBe("needs-input");
- expect(classifyAgentsViewSession(makeSummary({ activity: "idle", messageCount: 4 }))).toBe("needs-input");
+ expect(classifyAgentsViewSession(makeSummary({ isStreaming: true, activity: "working" }))).toBe("running");
+ expect(classifyAgentsViewSession(makeSummary({ pendingMessageCount: 1, activity: "working" }))).toBe("running");
+ expect(classifyAgentsViewSession(makeSummary({ activity: "working" }))).toBe("running");
+ expect(classifyAgentsViewSession(makeSummary({ activity: "idle", messageCount: 2 }))).toBe("idle");
+ expect(classifyAgentsViewSession(makeSummary({ activity: "idle", messageCount: 0 }))).toBe("idle");
+ expect(classifyAgentsViewSession(makeSummary({ activity: "idle", messageCount: 4 }))).toBe("idle");
});
- test("idle sessions split by the summarizer's completion verdict", () => {
+ test("places all non-busy resident sessions in Idle", () => {
// Working is heuristic and ignores taskState.
expect(
classifyAgentsViewSession(makeSummary({ isStreaming: true, activity: "working", taskState: "completed" })),
- ).toBe("working");
- // Idle sessions follow the verdict; absent one they default to needs-input.
- expect(classifyAgentsViewSession(makeSummary({ activity: "idle", taskState: "needs_input" }))).toBe(
- "needs-input",
- );
- expect(classifyAgentsViewSession(makeSummary({ activity: "idle", taskState: "completed" }))).toBe("completed");
- expect(classifyAgentsViewSession(makeSummary({ activity: "idle", taskState: undefined }))).toBe("needs-input");
+ ).toBe("running");
+ // Secondary completion verdicts do not create extra sections.
+ expect(classifyAgentsViewSession(makeSummary({ activity: "idle", taskState: "needs_input" }))).toBe("idle");
+ expect(classifyAgentsViewSession(makeSummary({ activity: "idle", taskState: "completed" }))).toBe("idle");
+ expect(classifyAgentsViewSession(makeSummary({ activity: "idle", taskState: undefined }))).toBe("idle");
});
- test("active heartbeats use their own section regardless of current activity", () => {
- expect(classifyAgentsViewSession(makeSummary({ activity: "working", hasActiveHeartbeat: true }))).toBe(
- "heartbeats",
- );
+ test("active heartbeats make sessions Running regardless of current activity", () => {
+ expect(classifyAgentsViewSession(makeSummary({ activity: "working", hasActiveHeartbeat: true }))).toBe("running");
expect(
classifyAgentsViewSession(makeSummary({ activity: "idle", taskState: "completed", hasActiveHeartbeat: true })),
- ).toBe("heartbeats");
+ ).toBe("running");
const [row] = buildAgentsViewRows([makeSummary({ activity: "idle", hasActiveHeartbeat: true })]);
- expect(row).toMatchObject({ section: "heartbeats", statusLabel: "heartbeat active" });
+ expect(row).toMatchObject({ section: "running", statusLabel: "heartbeat active" });
const [busyRow] = buildAgentsViewRows([
makeSummary({ activity: "working", hasActiveHeartbeat: true, isStreaming: true, isRunningTools: true }),
]);
- expect(busyRow).toMatchObject({ section: "heartbeats", statusLabel: "running tools" });
- expect(sectionTitle("heartbeats")).toBe("Heartbeats");
+ expect(busyRow).toMatchObject({ section: "running", statusLabel: "running tools" });
+ expect(sectionTitle("running")).toBe("Running");
});
test("defaults an idle session with no verdict to needs-input", () => {
// A slow, failed, or absent classification never lingers in Working; only
// an explicit completed verdict moves an idle session out of needs-input.
- expect(classifyAgentsViewSession(makeSummary({ activity: "idle", taskState: undefined }))).toBe("needs-input");
+ expect(classifyAgentsViewSession(makeSummary({ activity: "idle", taskState: undefined }))).toBe("idle");
});
test("sorts rows by section and creation time", () => {
@@ -116,7 +131,7 @@ describe("agents view state", () => {
]);
expect(rows.map((row) => row.title)).toEqual(["newer working", "older working", "heartbeat", "completed"]);
- expect(rows.map((row) => row.section)).toEqual(["working", "working", "heartbeats", "completed"]);
+ expect(rows.map((row) => row.section)).toEqual(["running", "running", "running", "idle"]);
});
test("keeps row order stable when modification times and daemon input order change", () => {
@@ -251,19 +266,19 @@ describe("agents view state", () => {
const collapsed = buildAgentsViewRows(summaries);
expect(collapsed[0]).toMatchObject({
kind: "agent",
- section: "heartbeats",
+ section: "running",
statusLabel: "heartbeat active",
});
expect(collapsed[1]).toMatchObject({
kind: "subagent-summary",
- section: "heartbeats",
+ section: "running",
title: "1 subagent running · 1 heartbeat active",
runningSubagentCount: 1,
});
const expanded = buildAgentsViewRows(summaries, new Set([collapsed[0]?.identity ?? ""]));
expect(expanded[1]).toMatchObject({
kind: "subagent",
- section: "heartbeats",
+ section: "running",
statusLabel: "heartbeat active",
});
});
@@ -284,6 +299,13 @@ describe("agents view state", () => {
);
const rows = buildAgentsViewRows([
...heartbeatChildren,
+ makeSummary({
+ id: "busy-child",
+ runtimeKind: "subagent",
+ parentActiveSessionId: "parent-active",
+ activity: "idle",
+ isRunningTools: true,
+ }),
makeSummary({
id: "parent-active",
activeSessionId: "parent-active",
@@ -294,11 +316,11 @@ describe("agents view state", () => {
}),
]);
- expect(rows[0]).toMatchObject({ section: "heartbeats", runningSubagentCount: 10 });
+ expect(rows[0]).toMatchObject({ section: "running", runningSubagentCount: 11 });
expect(rows[1]).toMatchObject({
kind: "subagent-summary",
- title: "10 subagents running · 10 heartbeats active",
- runningSubagentCount: 10,
+ title: "11 subagents running · 10 heartbeats active",
+ runningSubagentCount: 11,
});
});
@@ -338,8 +360,8 @@ describe("agents view state", () => {
const rootIdentity = buildAgentsViewRows(summaries)[0]?.identity ?? "";
const oneLevel = buildAgentsViewRows(summaries, new Set([rootIdentity]));
const child = oneLevel.find((row) => row.title === "Child");
- expect(oneLevel[0]).toMatchObject({ section: "heartbeats", statusLabel: "heartbeat active" });
- expect(child).toMatchObject({ section: "heartbeats", statusLabel: "heartbeat active" });
+ expect(oneLevel[0]).toMatchObject({ section: "running", statusLabel: "heartbeat active" });
+ expect(child).toMatchObject({ section: "running", statusLabel: "heartbeat active" });
const childIdentity = child?.identity ?? "";
const expanded = buildAgentsViewRows(summaries, new Set([rootIdentity, childIdentity]));
@@ -348,9 +370,9 @@ describe("agents view state", () => {
.filter((row) => row.kind === "agent" || row.kind === "subagent")
.map((row) => [row.title, row.section, row.statusLabel]),
).toEqual([
- ["Root", "heartbeats", "heartbeat active"],
- ["Child", "heartbeats", "heartbeat active"],
- ["Heartbeat grandchild", "heartbeats", "heartbeat active"],
+ ["Root", "running", "heartbeat active"],
+ ["Child", "running", "heartbeat active"],
+ ["Heartbeat grandchild", "running", "heartbeat active"],
]);
});
@@ -717,105 +739,6 @@ describe("agents view state", () => {
expect(createAgentsViewListCommand()).toEqual({ type: "list" });
});
- test("uses the active-chat file autocomplete for new-agent prompts", async () => {
- const dir = mkdtempSync(join(tmpdir(), "agents-view-autocomplete-"));
- const fdPath = join(dir, "fd");
- writeFileSync(
- fdPath,
- `#!/bin/sh
-printf 'src/referenced.ts\n'
-`,
- );
- chmodSync(fdPath, 0o755);
-
- try {
- const provider = createAgentsViewAutocompleteProvider(dir, fdPath, () => []);
- const suggestions = await provider.getSuggestions(["review @refer"], 0, 13, {
- signal: new AbortController().signal,
- });
-
- expect(suggestions).toEqual({
- prefix: "@refer",
- items: [{ value: "@src/referenced.ts", label: "referenced.ts", description: "src/referenced.ts" }],
- kind: "file",
- });
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
- });
-
- test("uses the reply target cwd for file autocomplete", () => {
- const missing = mkdtempSync(join(tmpdir(), "agents-view-autocomplete-missing-"));
- rmSync(missing, { recursive: true, force: true });
-
- expect(resolveAgentsViewAutocompleteCwd("/launch", makeSummary({ cwd: tmpdir() }))).toBe(tmpdir());
- expect(resolveAgentsViewAutocompleteCwd("/launch")).toBe("/launch");
- expect(resolveAgentsViewAutocompleteCwd("/launch", makeSummary({ cwd: missing }))).toBe("/launch");
- expect(resolveAgentsViewAutocompleteCwd("/launch", makeSummary({ cwd: "" }))).toBe("/launch");
- });
-
- test("reads current models for each autocomplete request", async () => {
- let completions: AutocompleteItem[] | null = null;
- const provider = createAgentsViewAutocompleteProvider("/tmp", undefined, () => completions);
-
- expect(
- await provider.getSuggestions(["/model fresh"], 0, 12, { signal: new AbortController().signal }),
- ).toBeNull();
-
- completions = [{ value: "test-provider/fresh-model", label: "fresh-model", description: "test-provider" }];
- expect(await provider.getSuggestions(["/model fresh"], 0, 12, { signal: new AbortController().signal })).toEqual({
- prefix: "fresh",
- items: [{ value: "test-provider/fresh-model", label: "fresh-model", description: "test-provider" }],
- });
- });
-
- test("creates an inactive summary for a saved session selected from resume", () => {
- const savedSession = makeSessionInfo({
- path: "/tmp/sessions/saved.jsonl",
- id: "saved",
- name: "Saved session",
- cwd: "/tmp/project",
- messageCount: 2,
- agentStatus: {
- summary: "Finished the task",
- taskState: "completed",
- basedOnMessageCount: 2,
- },
- });
-
- const summary = resolveAgentsViewResumeSummary(savedSession.path, [savedSession], []);
-
- expect(summary).toMatchObject({
- id: "saved",
- activity: "idle",
- sessionId: "saved",
- sessionFile: savedSession.path,
- sessionName: "Saved session",
- cwd: "/tmp/project",
- summary: "Finished the task",
- taskState: "completed",
- });
- expect(summary?.activeSessionId).toBeUndefined();
- expect(summary?.lifecycle).toBe("live");
- });
-
- test("reuses the live daemon summary when resuming an already-active saved session", () => {
- const savedSession = makeSessionInfo({
- path: "/tmp/sessions/active.jsonl",
- id: "saved-active",
- cwd: "/tmp/project",
- });
- const activeSummary = makeSummary({
- id: "active-runtime",
- activeSessionId: "active-runtime",
- sessionId: "saved-active",
- sessionFile: savedSession.path,
- sessionName: "Running",
- });
-
- expect(resolveAgentsViewResumeSummary(savedSession.path, [savedSession], [activeSummary])).toBe(activeSummary);
- });
-
test("resolves active summaries by session file path", () => {
const activeSummary = makeSummary({
id: "active-runtime",
@@ -871,11 +794,6 @@ printf 'src/referenced.ts\n'
expect(shouldReconnectAgentsViewDaemon("shutdown")).toBe(false);
});
- test("caps generated session names at the configured limit", () => {
- expect(createAgentsViewSessionName("x".repeat(120))).toHaveLength(80);
- expect(createAgentsViewSessionName("short")).toBe("short");
- });
-
test("uses session-specific UI services when opening an agent", async () => {
const dashboardServices = makeUiServices("/tmp/dashboard");
const sessionServices = makeUiServices("/tmp/project");
@@ -894,6 +812,213 @@ printf 'src/referenced.ts\n'
expect(createUiServicesForSession).toHaveBeenCalledWith(summary);
});
+ test("reconciles canonical paths and session ids while retaining saved search text", () => {
+ const saved = makeSessionInfo({
+ path: "/tmp/sessions/../sessions/merged.jsonl",
+ id: "merged-session",
+ name: "Durable name",
+ allMessagesText: "a uniquely searchable transcript",
+ agentStatus: { summary: "Investigated the lunar regression", basedOnMessageCount: 1 },
+ });
+ const daemon = makeSummary({
+ id: "runtime",
+ activeSessionId: "runtime",
+ sessionId: "merged-session",
+ sessionFile: "/tmp/sessions/merged.jsonl",
+ sessionName: "Live name",
+ });
+
+ const [record] = reconcileUnifiedSessions([daemon], [saved]);
+ expect(record).toMatchObject({ daemon, saved, identity: "file:/tmp/sessions/merged.jsonl", section: "idle" });
+ expect(record?.searchableText).toContain("uniquely searchable transcript");
+ expect(record?.searchableText).toContain("lunar regression");
+ expect(buildAgentsViewRows([record!])[0]).toMatchObject({
+ title: "Live name",
+ record,
+ });
+ });
+
+ test("retains the ancestor chain when search matches only a nested subagent", () => {
+ const summaries = [
+ makeSummary({ id: "root", activeSessionId: "root", sessionId: "root-session", sessionName: "Root" }),
+ makeSummary({
+ id: "child",
+ activeSessionId: "child",
+ sessionId: "child-session",
+ sessionName: "Child",
+ runtimeKind: "subagent",
+ parentActiveSessionId: "root",
+ }),
+ makeSummary({
+ id: "match",
+ activeSessionId: "match",
+ sessionId: "match-session",
+ sessionName: "Needle",
+ runtimeKind: "subagent",
+ parentActiveSessionId: "child",
+ }),
+ makeSummary({
+ id: "newer",
+ activeSessionId: "newer",
+ sessionId: "newer-session",
+ sessionName: "Needle peer",
+ created: "2026-02-01T00:00:00Z",
+ }),
+ ];
+ const records = reconcileUnifiedSessions(summaries, []);
+ const filtered = filterUnifiedSessions(records, (text) => text.includes("Needle"));
+
+ expect(filtered.map((record) => record.daemon?.sessionId)).toEqual([
+ "root-session",
+ "child-session",
+ "match-session",
+ "newer-session",
+ ]);
+ const rootIdentity = records[0]?.identity ?? "";
+ const childIdentity = records[1]?.identity ?? "";
+ expect(
+ buildAgentsViewRows(filtered, new Set([rootIdentity, childIdentity])).map((row) => [
+ row.summary.sessionId,
+ row.depth,
+ ]),
+ ).toEqual([
+ ["newer-session", 0],
+ ["root-session", 0],
+ ["child-session", 1],
+ ["match-session", 2],
+ ]);
+ });
+
+ test("deduplicates and protects sessions across symlink aliases", () => {
+ const root = mkdtempSync(join(tmpdir(), "session-view-alias-"));
+ try {
+ const real = join(root, "session.jsonl");
+ const alias = join(root, "alias.jsonl");
+ writeFileSync(real, "");
+ symlinkSync(real, alias);
+ const daemon = makeSummary({ activeSessionId: "active", sessionFile: alias, sessionId: "same" });
+ const saved = makeSessionInfo({ id: "same", path: real });
+ expect(reconcileUnifiedSessions([daemon], [saved])).toHaveLength(1);
+ expect(resolveAgentsViewActiveSummaryForPath(real, [daemon])).toBe(daemon);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ test("uses canonical path and fallback active-id keys for heartbeat ancestry", () => {
+ const root = mkdtempSync(join(tmpdir(), "session-view-parent-alias-"));
+ try {
+ const path = join(root, "parent.jsonl");
+ const alias = join(root, "alias.jsonl");
+ writeFileSync(path, "");
+ symlinkSync(path, alias);
+ const summaries = [
+ makeSummary({ id: "root", activeSessionId: undefined, sessionFile: path }),
+ makeSummary({
+ id: "parent",
+ activeSessionId: undefined,
+ parentSessionPath: alias,
+ runtimeKind: "subagent",
+ }),
+ makeSummary({
+ id: "child",
+ activeSessionId: undefined,
+ parentActiveSessionId: "parent",
+ runtimeKind: "subagent",
+ }),
+ ];
+ const aggregates = aggregateSessionHeartbeats(summaries, [heartbeat("job", undefined, "child")]);
+ expect(["root", "parent", "child"].map((id) => aggregates.get(id))).toEqual(
+ Array.from({ length: 3 }, () => ({ activeCount: 1 })),
+ );
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ test("shows a fallback heartbeat count while catalog details are unavailable", () => {
+ const [record] = reconcileUnifiedSessions([makeSummary({ hasActiveHeartbeat: true })], []);
+ expect(record).toMatchObject({ section: "running", heartbeat: { activeCount: 1 } });
+ expect(formatHeartbeatBadge(record?.heartbeat)).toBe("♥ 1");
+ });
+
+ test("preserves live identity and row state when saved metadata adds a file alias", () => {
+ const saved = makeSessionInfo({ path: "/tmp/saved.jsonl", id: "saved", allMessagesText: "transcript" });
+ const parent = makeSummary({
+ id: "parent",
+ activeSessionId: "parent",
+ sessionId: "saved",
+ sessionFile: undefined,
+ });
+ const child = makeSummary({
+ id: "child",
+ activeSessionId: "child",
+ sessionId: "child-session",
+ runtimeKind: "subagent",
+ parentActiveSessionId: "parent",
+ spawnCode: "run_subagent()",
+ });
+ const [inactive] = reconcileUnifiedSessions([], [saved]);
+ const [live] = reconcileUnifiedSessions([parent, child], []);
+ const enrichedRecords = reconcileUnifiedSessions([parent, child], [saved]);
+ const enriched = enrichedRecords.find((record) => record.daemon?.sessionId === parent.sessionId);
+ const expanded = buildAgentsViewRows(enrichedRecords, new Set([live!.identity]), new Set([live!.identity]));
+
+ expect(inactive).toMatchObject({ identity: "file:/tmp/saved.jsonl", section: "inactive" });
+ expect(enriched).toMatchObject({ identity: live?.identity, section: "idle", saved });
+ expect(enriched?.identityAliases).toContain("file:/tmp/saved.jsonl");
+ expect(expanded.map((row) => row.kind)).toContain("subagent-code");
+ expect(expanded.some((row) => row.kind === "subagent" && row.summary.sessionId === "child-session")).toBe(true);
+ });
+
+ test("aggregates active descendant heartbeats once and formats the soonest run", () => {
+ const parent = makeSummary({ id: "parent", activeSessionId: "parent", sessionId: "parent-session" });
+ const child = makeSummary({
+ id: "child",
+ activeSessionId: "child",
+ sessionId: "child-session",
+ runtimeKind: "subagent",
+ parentActiveSessionId: "parent",
+ });
+
+ const aggregates = aggregateSessionHeartbeats(
+ [parent, child],
+ [heartbeat("one", "2026-01-01T00:10:00Z"), heartbeat("two", "2026-01-01T00:05:00Z")],
+ );
+ expect(aggregates.get("child")).toEqual({ activeCount: 2, nextRunAt: "2026-01-01T00:05:00Z" });
+ expect(aggregates.get("parent")).toEqual({ activeCount: 2, nextRunAt: "2026-01-01T00:05:00Z" });
+ const rows = buildAgentsViewRows(reconcileUnifiedSessions([parent, child], [], [heartbeat("one")]));
+ expect(rows[0]).toMatchObject({ section: "running", heartbeat: { activeCount: 1 } });
+ expect(rows[1]).toMatchObject({ title: "1 subagent running · 1 heartbeat active" });
+ expect(formatHeartbeatBadge(aggregates.get("parent"), Date.parse("2026-01-01T00:00:00Z"))).toBe("♥ 2·5m");
+ expect(
+ formatHeartbeatBadge(
+ { activeCount: 1, nextRunAt: "2026-01-01T00:10:00Z" },
+ Date.parse("2026-01-01T00:00:00Z"),
+ ),
+ ).toBe("♥ 1·10m");
+ expect(formatHeartbeatBadge({ activeCount: 1 })).toBe("♥ 1");
+ // Sub-minute countdowns show seconds instead of rounding up to 1m.
+ expect(
+ formatHeartbeatBadge(
+ { activeCount: 1, nextRunAt: "2026-01-01T00:00:42Z" },
+ Date.parse("2026-01-01T00:00:00Z"),
+ ),
+ ).toBe("♥ 1·42s");
+ expect(
+ formatHeartbeatBadge(
+ { activeCount: 1, nextRunAt: "2026-01-01T00:00:59.700Z" },
+ Date.parse("2026-01-01T00:00:00Z"),
+ ),
+ ).toBe("♥ 1·1m");
+ expect(
+ formatHeartbeatBadge(
+ { activeCount: 1, nextRunAt: "2026-01-01T00:00:00Z" },
+ Date.parse("2026-01-01T00:00:00Z"),
+ ),
+ ).toBe("♥ 1·1s");
+ });
+
describe("restores selection to the previously open session", () => {
const opened = makeSummary({
id: "active-open",
@@ -914,8 +1039,9 @@ printf 'src/referenced.ts\n'
test("re-finds the session after a section change reorders the list", () => {
const rows = buildAgentsViewRows([{ ...opened, activity: "working" }, other]);
- expect(rows[1]?.summary.sessionId).toBe("session-open");
- expect(resolveAgentsViewSelectionIndex(rows, identity, key)).toBe(1);
+ const openIndex = rows.findIndex((row) => row.summary.sessionId === "session-open");
+ expect(openIndex).toBe(0);
+ expect(resolveAgentsViewSelectionIndex(rows, identity, key)).toBe(openIndex);
});
test("falls back to activeSessionId when the row identity changed", () => {
@@ -927,6 +1053,25 @@ printf 'src/referenced.ts\n'
);
});
+ test("prefers the current runtime over a stale saved-file identity", () => {
+ const switched = {
+ ...opened,
+ sessionId: "session-switched",
+ sessionFile: "/tmp/project/switched.jsonl",
+ };
+ const staleSaved = makeSummary({
+ id: "session-open",
+ activeSessionId: undefined,
+ sessionId: "session-open",
+ sessionFile: opened.sessionFile,
+ lifecycle: "archived",
+ });
+ const rows = buildAgentsViewRows([staleSaved, switched]);
+ expect(resolveAgentsViewSelectionIndex(rows, identity, key)).toBe(
+ rows.findIndex((row) => row.summary.sessionId === "session-switched"),
+ );
+ });
+
test("falls back to sessionId after a daemon re-attach regenerates the active id", () => {
// Re-attach gives a fresh activeSessionId, so only the sessionId still matches.
const reattached = { ...opened, id: "active-open-2", activeSessionId: "active-open-2" };
@@ -936,6 +1081,42 @@ printf 'src/referenced.ts\n'
);
});
+ test("keeps an unresolved source anchor while streamed rows provide a visual fallback", () => {
+ const partialRows = buildAgentsViewRows([other]);
+ expect(resolveAgentsViewSelectionState(partialRows, 0, identity, key)).toEqual({
+ index: 0,
+ resolved: false,
+ });
+ const completeRows = buildAgentsViewRows([other, opened]);
+ expect(resolveAgentsViewSelectionState(completeRows, 0, identity, key)).toEqual({
+ index: completeRows.findIndex((row) => row.summary.sessionId === "session-open"),
+ resolved: true,
+ });
+ });
+
+ test("keeps a collapsed subagent summary selected across refreshes", () => {
+ const child = makeSummary({
+ id: "child-active",
+ activeSessionId: "child-active",
+ sessionId: "child-session",
+ sessionFile: "/tmp/project/child.jsonl",
+ runtimeKind: "subagent",
+ parentActiveSessionId: opened.activeSessionId,
+ parentSessionId: opened.sessionId,
+ });
+ const initialRows = buildAgentsViewRows([opened, child]);
+ const selected = initialRows.find((row) => row.kind === "subagent-summary")!;
+ const refreshedRows = buildAgentsViewRows([{ ...opened }, { ...child }]);
+ const refreshedSummaryIndex = refreshedRows.findIndex((row) => row.kind === "subagent-summary");
+ expect(
+ resolveAgentsViewSelectionIndex(
+ refreshedRows,
+ selected.identity,
+ getAgentsViewSelectionKey(selected.summary),
+ ),
+ ).toBe(refreshedSummaryIndex);
+ });
+
test("returns -1 when the session is gone so callers pick a default", () => {
const rows = buildAgentsViewRows([other]);
expect(resolveAgentsViewSelectionIndex(rows, identity, key)).toBe(-1);
diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.ts
index 667a54f674..91d6003cf6 100644
--- a/packages/coding-agent/test/daemon-mode.test.ts
+++ b/packages/coding-agent/test/daemon-mode.test.ts
@@ -7,9 +7,16 @@ import type { Api, Model } from "@earendil-works/pi-ai";
import { describe, expect, it, vi } from "vitest";
import type { AgentSessionMessageController } from "../src/core/agent-messages.js";
import type { CreateAgentSessionRuntimeFactory } from "../src/core/agent-session-runtime.js";
+import { installAgentTraceUpload } from "../src/core/agent-traces.js";
+import { AuthStorage } from "../src/core/auth-storage.js";
import type { AgentCronJob, AgentCronJobStore } from "../src/core/cron-jobs.js";
-import { type CreateRlmSubagentRuntimeOptions, createDefaultRlmSubagentSessionName } from "../src/core/rlm-runtime.js";
+import {
+ type CreateRlmSubagentRuntimeOptions,
+ createDefaultRlmSubagentSessionName,
+ type SubagentRuntimeHost,
+} from "../src/core/rlm-runtime.js";
import { SessionManager } from "../src/core/session-manager.js";
+import { SettingsManager } from "../src/core/settings-manager.js";
import type { ActiveSessionState, DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";
import {
AgentDaemon,
@@ -20,7 +27,6 @@ import {
markClientSnapshotStreaming,
setDaemonClientSessionCapabilities,
shouldSendDaemonOutboundToClient,
- waitForDaemonPromptAdmission,
} from "../src/modes/daemon/daemon-mode.js";
import {
createDaemonCommandEnvelope,
@@ -41,18 +47,6 @@ describe("daemon mode helpers", () => {
expect(client.id).toBe("public-client");
});
- it("observes supplied work when prompt admission is already aborted", async () => {
- const controller = new AbortController();
- controller.abort();
- const work = Promise.reject(new Error("late claim failure"));
-
- await expect(waitForDaemonPromptAdmission(work, controller.signal)).rejects.toThrow(
- "Prompt admission was cancelled.",
- );
- // Let the observed work settle; an unhandled rejection would fail Vitest.
- await Promise.resolve();
- });
-
it("finds only direct child active sessions", () => {
const parent = makeState("parent");
const child = makeState("child", "parent");
@@ -272,6 +266,66 @@ describe("daemon mode helpers", () => {
expect(acceptAgentMessagePrompt.mock.calls[0]?.[0]).toContain("report current progress");
});
+ it("starts trace flush and skips the registry when teardown wins the retention race", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-trace-race-"));
+ try {
+ const manager = SessionManager.create(tempDir, tempDir);
+ manager.newSession();
+ let markTraceStarted: () => void = () => {};
+ const traceStarted = new Promise<void>((resolve) => {
+ markTraceStarted = resolve;
+ });
+ const fetchFn = vi.fn(async () => {
+ markTraceStarted();
+ return await new Promise<Response>(() => {});
+ });
+ installAgentTraceUpload(manager, {
+ authStorage: AuthStorage.inMemory({
+ "prime-agent-traces": { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: true } }),
+ fetchFn,
+ });
+ manager.appendSessionInfo("trace-race");
+
+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ });
+ const parentState = makeState("parent");
+ const parentSession = makeRuntimeSession(manager);
+ parentSession.retainFinishedRlmChildSession = vi.fn(() => false);
+ const childState = makeState("child", parentState.activeSessionId);
+ const childSession = makeRuntimeSession(manager);
+ childState.runtime = { ...childState.runtime, session: childSession } as ActiveSessionState["runtime"];
+ // Competing teardown already closed the state, so this release-time close is a no-op.
+ const closeSession = vi.fn(async () => {});
+ const recordRlmSubagentRegistryEntry = vi.fn();
+ Object.assign(daemon, {
+ findRuntimeState: vi.fn(() => childState),
+ closeSession,
+ recordRlmSubagentRegistryEntry,
+ });
+ const host = Reflect.get(daemon, "createSubagentRuntimeHost").call(daemon, parentState) as SubagentRuntimeHost;
+
+ await host.releaseRlmSubagentRuntime?.(
+ childState.runtime,
+ { parentSession, id: "child-1" } as CreateRlmSubagentRuntimeOptions,
+ "done",
+ );
+ await traceStarted;
+
+ expect(fetchFn).toHaveBeenCalledOnce();
+ expect(parentSession.retainFinishedRlmChildSession).toHaveBeenCalledWith("child-1", childSession);
+ expect(closeSession).toHaveBeenCalledWith(childState, "completed");
+ expect(recordRlmSubagentRegistryEntry).not.toHaveBeenCalled();
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
it("keeps RLM heartbeats active when a successful subagent is retained", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-retained-heartbeat-"));
try {
@@ -290,6 +344,20 @@ describe("daemon mode helpers", () => {
if (!childSessionFile) {
throw new Error("Missing child session file");
}
+ let traceUploadStarted: () => void = () => {};
+ const traceStarted = new Promise<void>((resolve) => {
+ traceUploadStarted = resolve;
+ });
+ installAgentTraceUpload(childManager, {
+ authStorage: AuthStorage.inMemory({
+ "prime-agent-traces": { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: true } }),
+ fetchFn: vi.fn(async () => {
+ traceUploadStarted();
+ return await new Promise<Response>(() => {});
+ }),
+ });
const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {
defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir },
@@ -376,9 +444,12 @@ describe("daemon mode helpers", () => {
} as unknown as CreateRlmSubagentRuntimeOptions;
internals.sessions.set(childState.activeSessionId, childState);
- await internals
+ const release = internals
.createSubagentRuntimeHost(parentState)
.releaseRlmSubagentRuntime(childState.runtime, releaseOptions, "done");
+ await expect(Promise.race([release.then(() => "released"), traceStarted.then(() => "trace")])).resolves.toBe(
+ "released",
+ );
expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({
status: "active",
@@ -3117,10 +3188,15 @@ describe("daemon mode helpers", () => {
}
});
- it("deduplicates concurrent creates for the same session file", async () => {
- const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-race-"));
+ it.each([
+ ["explicit session file", (sessionPath: string) => ({ type: "create" as const, sessionPath })],
+ ["continue recent", (_sessionPath: string) => ({ type: "create" as const, continueRecent: true })],
+ ])("deduplicates concurrent creates after resolving the %s", async (_label, commandFor) => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-open-race-"));
try {
- const sessionPath = join(tempDir, "session.jsonl");
+ const recent = SessionManager.create(tempDir, tempDir);
+ const sessionPath = recent.materializeSessionFile();
+ recent.appendSessionInfo("Recent");
let releaseCreate: () => void = () => {};
const createBarrier = new Promise<void>((resolve) => {
releaseCreate = resolve;
@@ -3139,11 +3215,7 @@ describe("daemon mode helpers", () => {
};
});
const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {
- defaultSessionConfig: {
- agentDir: tempDir,
- cwd: tempDir,
- sessionDir: tempDir,
- },
+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir: tempDir },
createRuntime,
});
const create = (
@@ -3152,17 +3224,17 @@ describe("daemon mode helpers", () => {
}
).createRuntime.bind(daemon);
- const first = create({ type: "create", sessionPath });
- const second = create({ type: "create", sessionPath });
- for (let attempt = 0; attempt < 20 && createRuntime.mock.calls.length === 0; attempt++) {
- await Promise.resolve();
- }
-
- expect(createRuntime).toHaveBeenCalledTimes(1);
+ const first = create(commandFor(sessionPath));
+ const second = create(commandFor(sessionPath));
+ // The pre-create session resolution is async (continueRecent scans the
+ // session dir); wait on a deadline, not a fixed number of ticks.
+ await vi.waitFor(() => {
+ expect(createRuntime).toHaveBeenCalledTimes(1);
+ });
releaseCreate();
const [firstState, secondState] = await Promise.all([first, second]);
-
expect(secondState).toBe(firstState);
+ expect(firstState.runtime.session.sessionFile).toBe(sessionPath);
expect(createRuntime).toHaveBeenCalledTimes(1);
} finally {
rmSync(tempDir, { recursive: true, force: true });
diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.ts
index 065de503f5..83fc4a144e 100644
--- a/packages/coding-agent/test/daemon-session-list.test.ts
+++ b/packages/coding-agent/test/daemon-session-list.test.ts
@@ -56,6 +56,14 @@ describe("buildSessionList", () => {
]);
});
+ it("uses the stable session header time for active rows without a saved catalog entry", () => {
+ const state = makeState({ activeSessionId: "active", sessionFile: "/tmp/active.jsonl" });
+ const first = summaryForActiveSession(state);
+ const second = summaryForActiveSession(state);
+ expect(first.created).toBe("2026-05-01T00:00:00.000Z");
+ expect(second.created).toBe(first.created);
+ });
+
it("keeps a session working while background subagents run", () => {
const oneMessage = [{ role: "user", content: "hi" }] as unknown as AgentMessage[];
const entries = buildSessionList(
@@ -582,6 +590,7 @@ function makeState(options: StateOptions): ActiveSessionState {
sessionName: `session ${options.activeSessionId}`,
sessionManager: {
getCwd: () => "/tmp/project",
+ getHeader: () => ({ timestamp: "2026-05-01T00:00:00.000Z" }),
getSessionDir: () => "/tmp/sessions",
hasUserContent: () => options.hasUserContent ?? false,
},
diff --git a/packages/coding-agent/test/daemon-supervisor-admission.test.ts b/packages/coding-agent/test/daemon-supervisor-admission.test.ts
index 784403e7a2..fd711c5a3e 100644
--- a/packages/coding-agent/test/daemon-supervisor-admission.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-admission.test.ts
@@ -8,8 +8,9 @@ import {
type DaemonResponse,
success,
} from "../src/modes/daemon/daemon-protocol.js";
-import { DaemonSupervisor, waitForSupervisorPromptAdmission } from "../src/modes/daemon/daemon-supervisor.js";
+import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";
import { MutationDrainLatch } from "../src/modes/daemon/mutation-drain-latch.js";
+import { type Deferred, createDeferred as deferred } from "./suite/scheduling.js";
interface AdmissionRecord {
client: DaemonSocketClient;
@@ -29,22 +30,6 @@ interface SupervisorHarness {
promptAdmissions: Map<DaemonSocketClient, Map<string, AdmissionRecord>>;
}
-interface Deferred<T> {
- promise: Promise<T>;
- resolve(value: T): void;
- reject(error: unknown): void;
-}
-
-function deferred<T>(): Deferred<T> {
- let resolve!: (value: T) => void;
- let reject!: (error: unknown) => void;
- const promise = new Promise<T>((resolvePromise, rejectPromise) => {
- resolve = resolvePromise;
- reject = rejectPromise;
- });
- return { promise, resolve, reject };
-}
-
function client(id: string): DaemonSocketClient {
return { id, attachedActiveSessionIds: new Set(), capabilities: new Set() } as DaemonSocketClient;
}
@@ -61,6 +46,8 @@ async function waitFor(predicate: () => boolean): Promise<void> {
throw new Error("Condition was not reached");
}
+// Constructor-bypass harness: the real constructor spawns watchers and needs a
+// socket dir. The field list is hand-coupled to what handleLine touches.
function createHarness(
options: {
ready?: Promise<void>;
@@ -102,17 +89,6 @@ function createHarness(
}
describe("daemon supervisor prompt admission ownership", () => {
- it("observes an already-running promise when admission is pre-aborted", async () => {
- const abort = new AbortController();
- abort.abort();
- const work = Promise.reject(new Error("late failure"));
-
- await expect(waitForSupervisorPromptAdmission(work, abort.signal)).rejects.toThrow(
- "Prompt admission was cancelled",
- );
- await Promise.resolve();
- });
-
it("registers a prompt synchronously before readiness and ownership awaits", async () => {
const ready = deferred<void>();
const ownership = deferred<void>();
diff --git a/packages/coding-agent/test/heartbeat-catalog.test.ts b/packages/coding-agent/test/heartbeat-catalog.test.ts
new file mode 100644
index 0000000000..8c4e4caab8
--- /dev/null
+++ b/packages/coding-agent/test/heartbeat-catalog.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it, vi } from "vitest";
+import type { DaemonClient, DaemonHello } from "../src/modes/daemon/daemon-client.js";
+import { listDaemonHeartbeats } from "../src/modes/daemon/heartbeat-catalog.js";
+
+function hello(): DaemonHello {
+ return {
+ type: "daemon_hello",
+ socketPath: "/tmp/daemon.sock",
+ protocol: { name: "prime-agent.daemon", version: 4 },
+ schemaId: "test",
+ appVersion: "test",
+ runtime: { buildId: "test", executablePath: "node" },
+ clientId: "client",
+ serverCapabilities: ["heartbeat_catalog"],
+ };
+}
+
+describe("daemon heartbeat catalog", () => {
+ it("waits for the daemon hello before checking heartbeat capabilities", async () => {
+ let greeted = false;
+ const heartbeat = { job: { id: "heartbeat" } };
+ const client = {
+ hello: undefined,
+ waitForHello: vi.fn(async () => {
+ greeted = true;
+ return hello();
+ }),
+ supportsServerCapability: vi.fn(() => greeted),
+ request: vi.fn(async () => ({
+ id: "request",
+ type: "response",
+ command: "heartbeats_list",
+ success: true,
+ data: { heartbeats: [heartbeat] },
+ })),
+ requestLegacy: vi.fn(),
+ } as unknown as DaemonClient;
+
+ await expect(listDaemonHeartbeats(client)).resolves.toEqual([heartbeat]);
+ expect(client.waitForHello).toHaveBeenCalledOnce();
+ expect(client.request).toHaveBeenCalledWith({ type: "heartbeats_list" });
+ });
+});
diff --git a/packages/coding-agent/test/interactive-mode-compaction.test.ts b/packages/coding-agent/test/interactive-mode-compaction.test.ts
index f00bf9d1b3..213cd78106 100644
--- a/packages/coding-agent/test/interactive-mode-compaction.test.ts
+++ b/packages/coding-agent/test/interactive-mode-compaction.test.ts
@@ -101,6 +101,23 @@ describe("InteractiveMode compaction events", () => {
}
});
+ test("shows manual warning-severity outcomes as warnings, not errors", async () => {
+ const fakeThis = createFakeThis();
+
+ await handleEvent.call(fakeThis, {
+ type: "compaction_end",
+ reason: "manual",
+ result: undefined,
+ aborted: false,
+ willRetry: false,
+ errorMessage: "Session is too short to compact",
+ errorSeverity: "warning",
+ });
+
+ expect(fakeThis.showWarning).toHaveBeenCalledWith("Session is too short to compact");
+ expect(fakeThis.showError).not.toHaveBeenCalled();
+ });
+
test("restores the compaction loader from state when no start event was seen", () => {
const statusContainer = new Container();
const fakeThis = createFakeThis({
diff --git a/packages/coding-agent/test/interactive-mode-feature-hints.test.ts b/packages/coding-agent/test/interactive-mode-feature-hints.test.ts
index 3f6bddcbf2..c9edfd4e80 100644
--- a/packages/coding-agent/test/interactive-mode-feature-hints.test.ts
+++ b/packages/coding-agent/test/interactive-mode-feature-hints.test.ts
@@ -87,7 +87,7 @@ describe("feature hint deck", () => {
const textById = new Map(hints.map((hint) => [hint?.id, hint?.text]));
expect(textById.get("subagents")).toBe("Prime Agent can delegate tasks to subagents and run them in parallel.");
- expect(textById.get("agents-view")).toContain("Agents View");
+ expect(textById.get("agents-view")).toContain("Session View");
expect(textById.get("session-rewind")).toContain("/tree");
expect(textById.get("steering")).toContain("steer");
expect(textById.get("agent-messaging")).toContain("message each other");
diff --git a/packages/coding-agent/test/interactive-mode-session-command-rendering.test.ts b/packages/coding-agent/test/interactive-mode-session-command-rendering.test.ts
deleted file mode 100644
index 85ce698975..0000000000
--- a/packages/coding-agent/test/interactive-mode-session-command-rendering.test.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { beforeAll, describe, expect, test, vi } from "vitest";
-import { createSessionSlashCommandMessage, createSessionSlashCommandResultMessage } from "../src/core/messages.js";
-import { SlashCommandMessageComponent } from "../src/modes/interactive/components/slash-command-message.js";
-import { SlashCommandResultMessageComponent } from "../src/modes/interactive/components/slash-command-result-message.js";
-import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
-import { initTheme } from "../src/modes/interactive/theme/theme.js";
-
-const command = { name: "compact" as const, args: "focus", text: "/compact focus" };
-
-describe("InteractiveMode session command rendering", () => {
- beforeAll(() => initTheme("dark"));
- test("uses specialized components for live command messages", () => {
- const children: unknown[] = [];
- const fakeThis = {
- chatContainer: { children: [], addChild: vi.fn((child: unknown) => children.push(child)) },
- toolOutputExpanded: false,
- };
- const add = Reflect.get(InteractiveMode.prototype, "addMessageToChat") as (
- this: typeof fakeThis,
- message:
- | ReturnType<typeof createSessionSlashCommandMessage>
- | ReturnType<typeof createSessionSlashCommandResultMessage>,
- ) => void;
-
- add.call(fakeThis, createSessionSlashCommandMessage(command));
- add.call(
- fakeThis,
- createSessionSlashCommandResultMessage("Command failed", {
- command,
- success: false,
- severity: "error",
- error: "failed",
- }),
- );
-
- expect(children[0]).toBeInstanceOf(SlashCommandMessageComponent);
- expect(children[1]).toBeInstanceOf(SlashCommandResultMessageComponent);
- });
-});
diff --git a/packages/coding-agent/test/interactive-mode-startup.test.ts b/packages/coding-agent/test/interactive-mode-startup.test.ts
index 983ff8b60b..9ddfdcf891 100644
--- a/packages/coding-agent/test/interactive-mode-startup.test.ts
+++ b/packages/coding-agent/test/interactive-mode-startup.test.ts
@@ -83,15 +83,90 @@ describe("InteractiveMode startup hints", () => {
expect(stripAnsi(label)).toBe("test-model • high ? for shortcuts");
});
+ it("routes session-view requests through the existing agents-view return path", async () => {
+ const returnToAgentsView = vi.fn(async () => {});
+ const mode = Object.assign(createMode(false, true), { returnToAgentsView });
+
+ await Reflect.get(InteractiveMode.prototype, "requestAgentsView").call(mode);
+
+ expect(returnToAgentsView).toHaveBeenCalledOnce();
+ });
+
+ it("explains why a draft blocks the destructive agents-view handoff", async () => {
+ const returnToAgentsView = vi.fn(async () => {});
+ const showStatus = vi.fn();
+ const mode = Object.assign(
+ createMode(false, true, () => "draft prompt"),
+ { returnToAgentsView, showStatus },
+ );
+
+ await Reflect.get(InteractiveMode.prototype, "requestAgentsView").call(mode);
+
+ expect(returnToAgentsView).not.toHaveBeenCalled();
+ expect(showStatus).toHaveBeenCalledWith("Send, stash, or clear your draft before opening agents");
+ });
+
+ it("opens the shared session view on back navigation for process-local chats", async () => {
+ const requestAgentsView = vi.fn(async () => {});
+ const returnToAgentsView = vi.fn(async () => {});
+ const mode = Object.assign(createMode(false, false), { requestAgentsView, returnToAgentsView });
+
+ const handled = Reflect.get(InteractiveMode.prototype, "handleAgentsBack").call(mode) as boolean;
+
+ expect(handled).toBe(true);
+ expect(requestAgentsView).toHaveBeenCalledOnce();
+ expect(returnToAgentsView).not.toHaveBeenCalled();
+ });
+
+ it("returns to the daemon agents view on back navigation for daemon chats", async () => {
+ const requestAgentsView = vi.fn(async () => {});
+ const returnToAgentsView = vi.fn(async () => {});
+ const mode = Object.assign(createMode(false, true), { requestAgentsView, returnToAgentsView });
+
+ const handled = Reflect.get(InteractiveMode.prototype, "handleAgentsBack").call(mode) as boolean;
+
+ expect(handled).toBe(true);
+ expect(returnToAgentsView).toHaveBeenCalledOnce();
+ expect(requestAgentsView).not.toHaveBeenCalled();
+ });
+
+ it("leaves back navigation to the editor while a draft exists", async () => {
+ const requestAgentsView = vi.fn(async () => {});
+ const mode = Object.assign(
+ createMode(false, false, () => "draft prompt"),
+ { requestAgentsView },
+ );
+
+ const handled = Reflect.get(InteractiveMode.prototype, "handleAgentsBack").call(mode) as boolean;
+
+ expect(handled).toBe(false);
+ expect(requestAgentsView).not.toHaveBeenCalled();
+ });
+
+ it("explains that the agents view needs the daemon for non-daemon chats", async () => {
+ const showStatus = vi.fn();
+ const shutdown = vi.fn(async () => {});
+ const mode = Object.assign(createMode(false, false), {
+ returnToAgentsView: vi.fn(async () => {}),
+ showStatus,
+ shutdown,
+ });
+
+ await Reflect.get(InteractiveMode.prototype, "requestAgentsView").call(mode);
+
+ expect(showStatus).toHaveBeenCalledWith(expect.stringContaining("needs the daemon"));
+ expect(shutdown).not.toHaveBeenCalled();
+ });
+
it("keeps the lowercase agents hint while typing", () => {
let editorText = "";
const mode = createMode(false, true, () => editorText);
const getLabel = () => Reflect.get(InteractiveMode.prototype, "getTrayLocationLabel").call(mode);
- expect(stripAnsi(getLabel())).toBe("← agents test-model • high ? for shortcuts");
+ expect(stripAnsi(getLabel())).toBe("← agents/resume test-model • high ? for shortcuts");
editorText = "draft prompt";
- expect(stripAnsi(getLabel())).toBe("← agents test-model • high");
+ expect(stripAnsi(getLabel())).toBe("← agents/resume test-model • high");
});
it("hides the fresh-chat shortcut hint while the prompt has text", () => {
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index 1df42211ed..e758e9c0b9 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -14,6 +14,7 @@ import {
visibleWidth,
} from "@earendil-works/pi-tui";
import { beforeAll, describe, expect, test, vi } from "vitest";
+import type { AgentSessionRuntime } from "../src/core/agent-session-runtime.js";
import { formatNoModelsAvailableMessage } from "../src/core/auth-guidance.js";
import { type AuthStatus, AuthStorage } from "../src/core/auth-storage.js";
import type { AgentCronJob } from "../src/core/cron-jobs.js";
@@ -23,6 +24,7 @@ import { KeybindingsManager } from "../src/core/keybindings.js";
import type { ModelRegistry } from "../src/core/model-registry.js";
import { PRIME_INFERENCE_PROVIDER_ID } from "../src/core/prime-inference-auth.js";
import { emptyUsage } from "../src/core/usage.js";
+import { InProcessAgentConnection } from "../src/modes/agent-connection/in-process-agent-connection.js";
import type {
AgentConnectionExtensionUiRequest,
AgentConnectionExtensionUiResponse,
@@ -52,7 +54,7 @@ import {
truncatePathMiddle,
} from "../src/modes/interactive/interactive-mode.js";
import { ClientPromptStashStore, type PromptStashState } from "../src/modes/interactive/prompt-stash-state.js";
-import { initTheme } from "../src/modes/interactive/theme/theme.js";
+import { initTheme, theme } from "../src/modes/interactive/theme/theme.js";
function renderLastLine(container: Container, width = 120): string {
const last = container.children[container.children.length - 1];
@@ -674,6 +676,7 @@ type SubmitHandlerHarness = {
showError: (message: string) => void;
isBashRunning: () => boolean;
patchConnectionState: (patch: Record<string, unknown>) => void;
+ requestAgentsView: () => Promise<void>;
agentConnection: {
prompt: (message: string) => Promise<void>;
executeBash: (command: string, options?: { excludeFromContext?: boolean }) => Promise<void>;
@@ -692,6 +695,7 @@ function createSubmitHandlerHarness(overrides: Partial<SubmitHandlerHarness> = {
isBashRunning: () => false,
patchConnectionState: vi.fn(),
promptStashState: {},
+ requestAgentsView: vi.fn(async () => {}),
promptStash: undefined,
pastedImages: new Map(),
getPromptStashImages: vi.fn(() => []),
@@ -1080,8 +1084,15 @@ describe("InteractiveMode pending bash components", () => {
pendingBashComponents: [],
getAllQueuedMessages: () => ({
steering: ["Heartbeat prompt: check steering", "Goal context: steer goal", "plain steering"],
- followUp: ["Heartbeat prompt: check status", "Goal context: continue goal", "plain follow-up"],
+ followUp: [
+ "Heartbeat prompt: check status",
+ "Goal context: continue goal",
+ "plain follow-up",
+ "/compact focus",
+ "/unknown",
+ ],
}),
+ isRecognizedSlashCommand: (name: string) => name === "compact",
getAppKeyDisplay: () => "Ctrl+Q",
featureHintSuppressedByQueue: false,
clearFeatureHintPresentation: vi.fn(),
@@ -1091,7 +1102,10 @@ describe("InteractiveMode pending bash components", () => {
InteractiveMode.prototype as unknown as { updatePendingMessagesDisplay(this: unknown): void }
).updatePendingMessagesDisplay.call(fakeThis);
+ const raw = queuedMessagesContainer.render(100).join("\n");
const rendered = normalizeRenderedOutput(queuedMessagesContainer);
+ expect(raw).toContain(theme.fg("accent", "/compact"));
+ expect(raw).not.toContain(theme.fg("accent", "/unknown"));
expect(rendered).toContain("Heartbeat prompt: check steering");
expect(rendered).not.toContain("Steering: Heartbeat prompt");
expect(rendered).toContain("Goal context: steer goal");
@@ -1206,6 +1220,26 @@ describe("InteractiveMode pending bash components", () => {
});
describe("InteractiveMode connection events", () => {
+ test("rendering a switched session tolerates a transient queue refresh failure", async () => {
+ const harness = {
+ resetCurrentSessionRenderState: vi.fn(),
+ renderInitialMessages: vi.fn(async () => {}),
+ refreshConnectionQueue: vi.fn(async () => {
+ throw new Error("queue unavailable");
+ }),
+ syncWorkingLoader: vi.fn(),
+ };
+
+ await expect(
+ (
+ InteractiveMode.prototype as unknown as {
+ renderCurrentSessionState(this: typeof harness): Promise<void>;
+ }
+ ).renderCurrentSessionState.call(harness),
+ ).resolves.toBeUndefined();
+ expect(harness.syncWorkingLoader).toHaveBeenCalledOnce();
+ });
+
test("degrades heartbeat refresh failures without hiding queue refresh failures during rebind", async () => {
const rebindCurrentSession = (
InteractiveMode.prototype as unknown as { rebindCurrentSession(this: InteractiveMode): Promise<void> }
@@ -1317,6 +1351,8 @@ describe("InteractiveMode connection events", () => {
return vi.fn();
}),
},
+ sessionEventQueue: Promise.resolve(),
+ sessionEventGeneration: 0,
resetSideQuestion: vi.fn(),
resetExtensionUI: vi.fn(),
applyConnectionStateSnapshot: vi.fn(),
@@ -1347,7 +1383,6 @@ describe("InteractiveMode connection events", () => {
expect(rebindOrder).toBeLessThan(renderMessagesOrder);
expect(fakeThis.applyConnectionStateSnapshot).toHaveBeenCalledWith(state);
expect(fakeThis.resetCurrentSessionRenderState).toHaveBeenCalledWith();
- expect(fakeThis.rebindCurrentSession).toHaveBeenCalledWith();
expect(fakeThis.renderInitialMessages).toHaveBeenCalledWith();
expect(fakeThis.ui.requestRender).toHaveBeenCalledWith();
});
@@ -1366,7 +1401,9 @@ describe("InteractiveMode connection events", () => {
}),
},
sessionEventQueue: Promise.resolve(),
+ sessionEventGeneration: 0,
renderResyncedSession: vi.fn(async () => {}),
+ refreshCommandCatalogForCurrentSession: vi.fn(async () => {}),
resetSideQuestion: vi.fn(),
resetExtensionUI: vi.fn(),
resetCurrentSessionRenderState: vi.fn(),
@@ -1384,13 +1421,65 @@ describe("InteractiveMode connection events", () => {
const snapshot = { state: createConnectionState(), messages: [] as [] };
await listener?.({ type: "session_resynced", snapshot });
+ expect(fakeThis.refreshCommandCatalogForCurrentSession).toHaveBeenCalledOnce();
expect(fakeThis.renderResyncedSession).toHaveBeenCalledWith(snapshot);
+ expect(fakeThis.refreshCommandCatalogForCurrentSession.mock.invocationCallOrder[0]).toBeLessThan(
+ fakeThis.renderResyncedSession.mock.invocationCallOrder[0]!,
+ );
expect(fakeThis.resetSideQuestion).not.toHaveBeenCalled();
expect(fakeThis.resetExtensionUI).not.toHaveBeenCalled();
expect(fakeThis.resetCurrentSessionRenderState).not.toHaveBeenCalled();
expect(fakeThis.rebindCurrentSession).not.toHaveBeenCalled();
});
+ test("drops a resync superseded while its command catalog refreshes", async () => {
+ type ConnectionEvent =
+ | { type: "session_resynced"; snapshot: { state: AgentConnectionState; messages: [] } }
+ | { type: "session_replaced"; state: AgentConnectionState; messages: [] };
+ let listener: ((event: ConnectionEvent) => Promise<void> | void) | undefined;
+ let releaseCatalog = () => {};
+ const catalog = new Promise<void>((resolve) => {
+ releaseCatalog = resolve;
+ });
+ const fakeThis = {
+ agentConnection: {
+ subscribe: vi.fn((callback) => {
+ listener = callback;
+ return vi.fn();
+ }),
+ },
+ sessionEventQueue: Promise.resolve(),
+ sessionEventGeneration: 0,
+ refreshCommandCatalogForCurrentSession: vi.fn(() => catalog),
+ renderResyncedSession: vi.fn(async () => {}),
+ resetSideQuestion: vi.fn(),
+ resetExtensionUI: vi.fn(),
+ applyConnectionStateSnapshot: vi.fn(),
+ resetCurrentSessionRenderState: vi.fn(),
+ rebindCurrentSession: vi.fn(async () => {}),
+ renderInitialMessages: vi.fn(async () => {}),
+ ui: { requestRender: vi.fn() },
+ handleEvent: vi.fn(),
+ handleConnectionExtensionUiRequest: vi.fn(),
+ showError: vi.fn(),
+ };
+ (InteractiveMode.prototype as unknown as { subscribeToAgent(this: typeof fakeThis): void }).subscribeToAgent.call(
+ fakeThis,
+ );
+
+ const resync = listener?.({
+ type: "session_resynced",
+ snapshot: { state: createConnectionState(), messages: [] },
+ });
+ await vi.waitFor(() => expect(fakeThis.refreshCommandCatalogForCurrentSession).toHaveBeenCalledOnce());
+ const replacement = listener?.({ type: "session_replaced", state: createConnectionState(), messages: [] });
+ releaseCatalog();
+ await Promise.all([resync, replacement]);
+
+ expect(fakeThis.renderResyncedSession).not.toHaveBeenCalled();
+ expect(fakeThis.renderInitialMessages).toHaveBeenCalledOnce();
+ });
+
test("preserves client-local work while rendering a resynchronized snapshot", async () => {
const sideQuestion = { id: "side-1", status: "running" };
const extensionRequests = new Map([["request-1", { cancelLocal: vi.fn() }]]);
@@ -1410,10 +1499,12 @@ describe("InteractiveMode connection events", () => {
startAssistantStreamingMessage(message);
}
});
+ const refreshCommandCatalogForCurrentSession = vi.fn(async () => {});
const fakeThis = {
sideQuestionEvent: sideQuestion,
activeConnectionExtensionUiRequests: extensionRequests,
activeBashComponent,
+ refreshCommandCatalogForCurrentSession,
isAgentCompacting: () => true,
isBashRunning: () => true,
streamingComponent: {},
@@ -1451,6 +1542,7 @@ describe("InteractiveMode connection events", () => {
(fakeThis as unknown as { renderSessionContext: ReturnType<typeof vi.fn> }).renderSessionContext,
).toHaveBeenCalledWith(expect.anything(), { clearChat: true, updateFooter: true });
expect(startAssistantStreamingMessage).toHaveBeenCalledWith(streamingMessage);
+ expect(refreshCommandCatalogForCurrentSession).not.toHaveBeenCalled();
});
test("finishes local bash UI when a resync proves the operation ended", async () => {
@@ -1494,6 +1586,119 @@ describe("InteractiveMode connection events", () => {
expect((fakeThis as unknown as { activeBashComponent: unknown }).activeBashComponent).toBeUndefined();
expect(flushPendingBashComponents).toHaveBeenCalledOnce();
});
+
+ test("sends /resume as plain prompt text now that the command is retired", async () => {
+ const fakeThis = createSubmitHandlerHarness();
+
+ await fakeThis.defaultEditor.onSubmit?.("/resume unexpected");
+
+ expect(fakeThis.showError).not.toHaveBeenCalled();
+ expect(fakeThis.requestAgentsView).not.toHaveBeenCalled();
+ });
+
+ test("renderCurrentSessionState waits for replacement handling before rendering", async () => {
+ const calls: string[] = [];
+ const fakeThis = {
+ sessionEventQueue: Promise.resolve().then(() => {
+ calls.push("replacement");
+ }),
+ resetCurrentSessionRenderState: () => calls.push("reset"),
+ renderInitialMessages: async () => calls.push("messages"),
+ refreshConnectionQueue: async () => calls.push("queue"),
+ syncWorkingLoader: () => calls.push("loader"),
+ };
+
+ await (
+ InteractiveMode.prototype as unknown as {
+ renderCurrentSessionState(this: typeof fakeThis): Promise<void>;
+ }
+ ).renderCurrentSessionState.call(fakeThis);
+
+ expect(calls).toEqual(["replacement", "reset", "messages", "queue", "loader"]);
+ });
+
+ test("drops a queued source event after the session is replaced", async () => {
+ type Event =
+ | { type: "session_event"; event: { type: string } }
+ | { type: "session_replaced"; state: AgentConnectionState };
+ let listener: ((event: Event) => Promise<void>) | undefined;
+ let releaseQueue: (() => void) | undefined;
+ const blocked = new Promise<void>((resolve) => {
+ releaseQueue = resolve;
+ });
+ const fakeThis = {
+ agentConnection: {
+ subscribe: (callback: (event: Event) => Promise<void>) => {
+ listener = callback;
+ return vi.fn();
+ },
+ },
+ sessionEventQueue: blocked,
+ sessionEventGeneration: 0,
+ handleEvent: vi.fn(async () => {}),
+ resetSideQuestion: vi.fn(),
+ resetExtensionUI: vi.fn(),
+ applyConnectionStateSnapshot: vi.fn(),
+ resetCurrentSessionRenderState: vi.fn(),
+ rebindCurrentSession: vi.fn(async () => {}),
+ renderInitialMessages: vi.fn(async () => {}),
+ ui: { requestRender: vi.fn() },
+ showError: vi.fn(),
+ };
+ (InteractiveMode.prototype as unknown as { subscribeToAgent(this: typeof fakeThis): void }).subscribeToAgent.call(
+ fakeThis,
+ );
+
+ const staleEvent = listener?.({ type: "session_event", event: { type: "message_update" } });
+ const replacement = listener?.({ type: "session_replaced", state: createConnectionState() });
+ releaseQueue?.();
+ await Promise.all([staleEvent, replacement]);
+
+ expect(fakeThis.handleEvent).not.toHaveBeenCalled();
+ expect(fakeThis.renderInitialMessages).toHaveBeenCalledOnce();
+ });
+
+ test("drops child body builds superseded by any newer caller", async () => {
+ const oldCommands = createDeferred<[]>();
+ const watcher = {
+ getCommands: vi.fn().mockReturnValueOnce(oldCommands.promise).mockResolvedValueOnce([]),
+ getToolDefinition: vi.fn(async () => undefined),
+ };
+ const setBodyComponents = vi.fn();
+ const fakeThis = {
+ childAgentWatcher: watcher,
+ childAgentWatcherToken: 1,
+ childAgentWatcherMessages: [userMessage("old", 1)],
+ childAgentBodyBuildSeq: 0,
+ childAgentDetail: { setBodyComponents },
+ ui: {},
+ getCurrentCwd: () => process.cwd(),
+ settingsManager: { getShowImages: () => true },
+ getMarkdownThemeWithSettings: () => ({}),
+ hideThinkingBlock: false,
+ hiddenThinkingLabel: "",
+ toolOutputExpanded: false,
+ };
+ Object.setPrototypeOf(fakeThis, InteractiveMode.prototype);
+ const rebuildChildAgentBody = (
+ InteractiveMode.prototype as unknown as {
+ rebuildChildAgentBody(this: typeof fakeThis, token: number): Promise<void>;
+ }
+ ).rebuildChildAgentBody;
+
+ const staleBuild = rebuildChildAgentBody.call(fakeThis, 1);
+ fakeThis.childAgentWatcherMessages = [userMessage("new", 2)];
+ await rebuildChildAgentBody.call(fakeThis, 1);
+ oldCommands.resolve([]);
+ await staleBuild;
+
+ expect(setBodyComponents).toHaveBeenCalledOnce();
+ const rendered = setBodyComponents.mock.calls[0]![0].flatMap((component: Component) => component.render(40)).join(
+ "\n",
+ );
+ expect(rendered).toContain("new");
+ expect(rendered).not.toContain("old");
+ });
});
describe("InteractiveMode connection extension UI", () => {
@@ -2621,9 +2826,10 @@ describe("InteractiveMode model selection persistence", () => {
).invalidateConnectionModelRefresh;
fakeThis.applyConnectionStateSnapshot = vi.fn();
- await expect(fakeThis.refreshConnectionCatalog()).rejects.toThrow("commands unavailable");
+ await expect(fakeThis.refreshConnectionCatalog()).resolves.toBeUndefined();
- expect(fakeThis.connectionModels).toEqual([cachedModel]);
+ expect(fakeThis.connectionCommands).toEqual([]);
+ expect(fakeThis.connectionModels).toEqual([expect.objectContaining({ id: "fresh" })]);
expect(fakeThis.connectionModelsFetchedAt).toBeGreaterThan(0);
});
@@ -2647,6 +2853,173 @@ describe("InteractiveMode model selection persistence", () => {
});
});
+function createFakeConnectionSession(commandName: string): AgentSessionRuntime["session"] {
+ return {
+ extensionRunner: { getRegisteredCommands: () => [] },
+ promptTemplates: [
+ {
+ name: commandName,
+ sourceInfo: {
+ path: `/${commandName}.md`,
+ source: `/${commandName}.md`,
+ scope: "project",
+ origin: "top-level",
+ },
+ },
+ ],
+ resourceLoader: {
+ getSkills: () => ({ skills: [] }),
+ getPrompts: () => ({ prompts: [] }),
+ getThemes: () => ({ themes: [] }),
+ getExtensions: () => ({ extensions: [], errors: [] }),
+ getAgentsFiles: () => ({ agentsFiles: [] }),
+ },
+ modelRegistry: { refreshModelCatalog: async () => ({ models: [], configuredProviders: [] }) },
+ sessionManager: {
+ getCwd: () => "/tmp/project",
+ getSessionDir: () => "/tmp/sessions",
+ getLeafId: () => null,
+ getEntries: () => [],
+ },
+ getAvailableThinkingLevels: () => ["medium"],
+ getActiveToolNames: () => [],
+ getContextUsage: () => undefined,
+ thinkingLevel: "medium",
+ serviceTier: "default",
+ isStreaming: false,
+ isCompacting: false,
+ isBashRunning: false,
+ retryAttempt: 0,
+ steeringMode: "all",
+ followUpMode: "all",
+ sessionId: commandName,
+ autoCompactionEnabled: true,
+ pendingMessageCount: 0,
+ goalState: emptyGoalState(),
+ scopedModels: [],
+ subscribe: () => () => {},
+ messages: [],
+ } as unknown as AgentSessionRuntime["session"];
+}
+
+class EventEmittingReplacementRuntime {
+ private rebindSession: Parameters<AgentSessionRuntime["setRebindSession"]>[0];
+
+ constructor(
+ public session: AgentSessionRuntime["session"],
+ private readonly replacement: AgentSessionRuntime["session"],
+ ) {}
+
+ setRebindSession(callback?: Parameters<AgentSessionRuntime["setRebindSession"]>[0]): void {
+ this.rebindSession = callback;
+ }
+
+ setBeforeSessionInvalidate(): void {}
+
+ newSession(): Promise<{ cancelled: boolean }> {
+ return this.replaceSession();
+ }
+
+ switchSession(): Promise<{ cancelled: boolean }> {
+ return this.replaceSession();
+ }
+
+ async fork(): Promise<{ cancelled: boolean; selectedText?: string }> {
+ return this.replaceSession();
+ }
+
+ private async replaceSession(): Promise<{ cancelled: boolean }> {
+ this.session = this.replacement;
+ await this.rebindSession?.(this.replacement);
+ return { cancelled: false };
+ }
+}
+
+describe("InteractiveMode session switch command catalog", () => {
+ test.each(["switchSession", "newSession", "fork"] as const)(
+ "refreshes an event-emitting in-process %s replacement exactly once before replay",
+ async (operation) => {
+ const sourceSession = createFakeConnectionSession("source-command");
+ const targetSession = createFakeConnectionSession("target-command");
+ const runtime = new EventEmittingReplacementRuntime(sourceSession, targetSession);
+ const connection = new InProcessAgentConnection(runtime as unknown as AgentSessionRuntime);
+ const getCommands = vi.spyOn(connection, "getCommands");
+ const calls: string[] = [];
+ const fakeThis = {
+ agentConnection: connection,
+ sessionEventQueue: Promise.resolve(),
+ sessionEventGeneration: 0,
+ connectionCommands: await connection.getCommands(),
+ connectionModelsRefreshVersion: 0,
+ bindLocalSessionExtensions: false,
+ uiServices: { getThemes: () => [] },
+ toolDefinitionCache: { clear: vi.fn() },
+ applyRuntimeSettings: vi.fn(),
+ applyConnectionModelCatalog: vi.fn(),
+ showLoadedResources: vi.fn(),
+ refreshHeartbeatCatalog: vi.fn(async () => {}),
+ updateAvailableProviderCount: vi.fn(async () => {}),
+ updateEditorBorderColor: vi.fn(),
+ updateTerminalTitle: vi.fn(),
+ setGoalAnnouncementBaseline: vi.fn(),
+ syncGoalTray: vi.fn(),
+ getGoalState: () => emptyGoalState(),
+ resetSideQuestion: vi.fn(),
+ resetExtensionUI: vi.fn(),
+ applyConnectionStateSnapshot: vi.fn(),
+ resetCurrentSessionRenderState: vi.fn(() => calls.push("reset")),
+ setupAutocompleteProvider: vi.fn(() => calls.push("catalog")),
+ renderInitialMessages: vi.fn(async () => {
+ calls.push("render");
+ expect(fakeThis.connectionCommands.map((command) => command.name)).toEqual(["target-command"]);
+ }),
+ refreshConnectionQueue: vi.fn(async () => {}),
+ syncWorkingLoader: vi.fn(),
+ ui: { requestRender: vi.fn() },
+ handleEvent: vi.fn(),
+ handleConnectionExtensionUiRequest: vi.fn(),
+ showError: vi.fn(),
+ };
+ Object.setPrototypeOf(fakeThis, InteractiveMode.prototype);
+ const interactiveHarness = fakeThis as typeof fakeThis & {
+ subscribeToAgent(): void;
+ renderCurrentSessionState(): Promise<void>;
+ };
+ interactiveHarness.subscribeToAgent();
+
+ if (operation === "switchSession") await connection.switchSession("/target/session.jsonl");
+ else if (operation === "newSession") await connection.newSession();
+ else await connection.fork("entry-1");
+ await interactiveHarness.renderCurrentSessionState();
+
+ expect(calls).toEqual(["reset", "catalog", "render", "reset", "render"]);
+ expect(getCommands).toHaveBeenCalledTimes(2); // initial catalog + one replacement refresh
+ },
+ );
+
+ test("keeps catalog refresh failures nonfatal and drops stale dynamic commands", async () => {
+ const setupAutocompleteProvider = vi.fn();
+ const fakeThis = Object.create(InteractiveMode.prototype) as {
+ agentConnection: { getCommands(): Promise<never> };
+ connectionCommands: unknown[];
+ setupAutocompleteProvider(): void;
+ refreshCommandCatalogForCurrentSession(): Promise<void>;
+ };
+ fakeThis.agentConnection = {
+ getCommands: vi.fn(async () => {
+ throw new Error("catalog unavailable");
+ }),
+ };
+ fakeThis.connectionCommands = [{ name: "stale-command" }];
+ fakeThis.setupAutocompleteProvider = setupAutocompleteProvider;
+
+ await expect(fakeThis.refreshCommandCatalogForCurrentSession()).resolves.toBeUndefined();
+
+ expect(fakeThis.connectionCommands).toEqual([]);
+ expect(setupAutocompleteProvider).toHaveBeenCalledOnce();
+ });
+});
+
describe("InteractiveMode Prime CLI onboarding", () => {
type OnboardingSplashHandle = {
showProgress(message: string): void;
@@ -2698,6 +3071,16 @@ describe("InteractiveMode Prime CLI onboarding", () => {
const markOnboardingShown = (InteractiveMode.prototype as unknown as OnboardingHarness).markOnboardingShown;
const runStartupOnboarding = (InteractiveMode.prototype as unknown as OnboardingHarness).runStartupOnboarding;
const runOnboardingFlow = (InteractiveMode.prototype as unknown as OnboardingHarness).runOnboardingFlow;
+ const startupRunResult = {
+ type: "agents_view",
+ source: {
+ activeSessionId: undefined,
+ sessionFile: undefined,
+ sessionId: "",
+ sessionName: undefined,
+ cwd: "/tmp/project",
+ },
+ };
function createStartupRunHarness(
options: Record<string, unknown>,
overrides: Record<string, unknown> = {},
@@ -2712,6 +3095,7 @@ describe("InteractiveMode Prime CLI onboarding", () => {
getUserInput: vi.fn(() => new Promise<void>(() => {})),
showWarning: vi.fn(),
showError: vi.fn(),
+ getCurrentCwd: () => startupRunResult.source.cwd,
sessionHasMessages: false,
...overrides,
};
@@ -2815,7 +3199,7 @@ describe("InteractiveMode Prime CLI onboarding", () => {
await vi.advanceTimersByTimeAsync(1_000);
expect(prompt).toHaveBeenCalledTimes(8);
inputDone.resolve(undefined);
- await expect(run).resolves.toBe("agents_view");
+ await expect(run).resolves.toEqual(startupRunResult);
} finally {
vi.useRealTimers();
}
@@ -2864,7 +3248,8 @@ describe("InteractiveMode Prime CLI onboarding", () => {
const blockedSubmission = fakeThis.defaultEditor.onSubmit?.("blocked user");
rejectStartup(new AgentConnectionPromptAdmissionError("daemon admission uncertain", status));
await blockedSubmission;
- await new Promise((resolve) => setTimeout(resolve, 300));
+ // An erroneous retry would already be scheduled; drain continuations.
+ for (let i = 0; i < 25; i++) await new Promise((resolve) => setImmediate(resolve));
expect(prompt).toHaveBeenCalledOnce();
expect(fakeThis.showError).toHaveBeenCalledWith("daemon admission uncertain");
expect(fakeThis.promptStashState.stash).toEqual({
@@ -2882,7 +3267,7 @@ describe("InteractiveMode Prime CLI onboarding", () => {
expect(fakeThis.pastedImages.get(6)).toBe(firstImage);
expect(fakeThis.pastedImages.get(7)).toBe(secondImage);
inputDone.resolve(undefined);
- await expect(run).resolves.toBe("agents_view");
+ await expect(run).resolves.toMatchObject({ type: "agents_view" });
},
);
@@ -2916,7 +3301,7 @@ describe("InteractiveMode Prime CLI onboarding", () => {
expect(prompt.mock.calls.map(([message]) => message)).toEqual(["owned startup", "next startup"]);
expect(fakeThis.promptStashState.stash).toBeUndefined();
inputDone.resolve(undefined);
- await expect(run).resolves.toBe("agents_view");
+ await expect(run).resolves.toMatchObject({ type: "agents_view" });
});
test.each(["typing", "Alt+Enter"] as const)(
@@ -3000,7 +3385,7 @@ describe("InteractiveMode Prime CLI onboarding", () => {
},
]);
inputDone.resolve(undefined);
- await expect(run).resolves.toBe("agents_view");
+ await expect(run).resolves.toEqual(startupRunResult);
} finally {
vi.useRealTimers();
}
@@ -3038,7 +3423,7 @@ describe("InteractiveMode Prime CLI onboarding", () => {
expect(blockedSignal?.aborted).toBe(false);
inputDone.resolve(undefined);
- await expect(run).resolves.toBe("agents_view");
+ await expect(run).resolves.toMatchObject({ type: "agents_view" });
expect(blockedSignal?.aborted).toBe(true);
expect(fakeThis.showError).not.toHaveBeenCalled();
});
@@ -3097,7 +3482,7 @@ describe("InteractiveMode Prime CLI onboarding", () => {
fakeThis.isShuttingDown = true;
inputDone.resolve(undefined);
- await expect(run).resolves.toBe("agents_view");
+ await expect(run).resolves.toMatchObject({ type: "agents_view" });
await submission;
expect(fakeThis.agentConnection.prompt).not.toHaveBeenCalled();
@@ -3297,7 +3682,7 @@ describe("InteractiveMode Prime CLI onboarding", () => {
fakeThis.returnToAgentsViewRequested = true;
fakeThis.isShuttingDown = true;
inputDone.resolve(undefined);
- await expect(run).resolves.toBe("agents_view");
+ await expect(run).resolves.toMatchObject({ type: "agents_view" });
await Promise.all([first, second]);
expect(promptStashState.stash).toEqual({ text: "first rich draft", expandedText: "first expanded" });
@@ -3305,25 +3690,20 @@ describe("InteractiveMode Prime CLI onboarding", () => {
});
test("keeps the TUI alive while direct editor submissions own prompt delivery", async () => {
- const fakeThis = {
- init: vi.fn(async () => {}),
- options: { agentsViewOwnsStartupNotices: true },
- modelRegistry: { getError: vi.fn(() => undefined) },
- runStartupOnboarding: vi.fn(async () => true),
- getModelFallbackWarningAction: vi.fn(() => "suppress"),
- getCurrentModel: vi.fn(() => primeModel),
- maybeWarnAboutAnthropicSubscriptionAuth: vi.fn(),
- getUserInput: vi.fn(async () => undefined),
- agentConnection: { prompt: vi.fn() },
- showWarning: vi.fn(),
- showError: vi.fn(),
- returnToAgentsViewRequested: false,
- sessionHasMessages: false,
- };
+ const prompt = vi.fn();
+ const fakeThis = createStartupRunHarness(
+ {},
+ {
+ getCurrentModel: vi.fn(() => primeModel),
+ getUserInput: vi.fn(async () => undefined),
+ agentConnection: { prompt },
+ returnToAgentsViewRequested: false,
+ },
+ );
- await expect(InteractiveMode.prototype.run.call(fakeThis as never)).resolves.toBe("agents_view");
+ await expect(InteractiveMode.prototype.run.call(fakeThis as never)).resolves.toEqual(startupRunResult);
expect(fakeThis.getUserInput).toHaveBeenCalledOnce();
- expect(fakeThis.agentConnection.prompt).not.toHaveBeenCalled();
+ expect(prompt).not.toHaveBeenCalled();
});
function createPrimeCliHarness(shown: boolean): OnboardingFake {
diff --git a/packages/coding-agent/test/main-interactive-routing.test.ts b/packages/coding-agent/test/main-interactive-routing.test.ts
index 79cb483488..dc3b7b97de 100644
--- a/packages/coding-agent/test/main-interactive-routing.test.ts
+++ b/packages/coding-agent/test/main-interactive-routing.test.ts
@@ -16,6 +16,7 @@ import {
shouldEnsureDaemonBeforeActiveSessionLookup,
shouldEnsureInteractiveDaemonForStartup,
shouldOpenAgentsViewForDaemonInteractive,
+ shouldRejectBareResume,
shouldRejectNonInteractiveAttach,
shouldUseDaemonClient,
shouldUseDaemonClientRuntime,
@@ -122,10 +123,13 @@ describe("interactive startup routing", () => {
).toBe(false);
});
- test("rejects attach before non-interactive startup", () => {
+ test("rejects interactive-only selectors before non-interactive startup", () => {
expect(shouldRejectNonInteractiveAttach("worker", "print")).toBe(true);
expect(shouldRejectNonInteractiveAttach("worker", "interactive")).toBe(false);
expect(shouldRejectNonInteractiveAttach(undefined, "print")).toBe(false);
+ expect(shouldRejectBareResume(true)).toBe(true);
+ expect(shouldRejectBareResume("session-id")).toBe(false);
+ expect(shouldRejectBareResume(undefined)).toBe(false);
});
test("does not start the daemon for attach", () => {
@@ -165,7 +169,6 @@ describe("daemon-backed interactive session manager routing", () => {
"resume selector",
{ useDaemonInteractive: true, needsOnboarding: false, explicitAgentsView: true, resume: "active-1" },
],
- ["resume picker", { useDaemonInteractive: true, needsOnboarding: false, explicitAgentsView: true, resume: true }],
[
"continue recent",
{ useDaemonInteractive: true, needsOnboarding: false, explicitAgentsView: true, continue: true },
@@ -180,6 +183,16 @@ describe("daemon-backed interactive session manager routing", () => {
expect(shouldOpenAgentsViewForDaemonInteractive(decision)).toBe(false);
});
+ test("bare --resume no longer routes to the agents view (it is rejected at startup)", () => {
+ expect(
+ shouldOpenAgentsViewForDaemonInteractive({
+ useDaemonInteractive: true,
+ needsOnboarding: false,
+ resume: true,
+ }),
+ ).toBe(false);
+ });
+
test("ensures daemon is available before probing non-path session selectors", () => {
expect(
shouldEnsureDaemonBeforeActiveSessionLookup({
@@ -256,7 +269,6 @@ describe("daemon-backed interactive session manager routing", () => {
const persistentSelectionCases: Array<[string, DaemonInteractiveSessionManagerDecision]> = [
["active daemon attach", { hasActiveDaemonSession: true }],
["explicit saved session", { resume: "saved-session-id" }],
- ["resume picker", { resume: true }],
["continue recent", { continue: true }],
["fork", { fork: "source-session-id" }],
];
@@ -265,6 +277,10 @@ describe("daemon-backed interactive session manager routing", () => {
expect(shouldUseEphemeralSessionManagerForDaemonInteractive(decision)).toBe(false);
});
+ test("keeps bare --resume off the ephemeral local session manager", () => {
+ expect(shouldUseEphemeralSessionManagerForDaemonInteractive({ resume: true })).toBe(false);
+ });
+
test("finds an active daemon session by resolved session file", () => {
const inactiveSummary = makeSessionSummary({
id: "saved-1",
diff --git a/packages/coding-agent/test/prompt-admission.test.ts b/packages/coding-agent/test/prompt-admission.test.ts
new file mode 100644
index 0000000000..656b73beb2
--- /dev/null
+++ b/packages/coding-agent/test/prompt-admission.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import { PromptAdmissionCancelledError, waitForPromptAdmission } from "../src/core/prompt-admission.js";
+
+describe("waitForPromptAdmission", () => {
+ it("observes already-running work when admission is pre-aborted", async () => {
+ const abort = new AbortController();
+ abort.abort();
+ const work = Promise.reject(new Error("late failure"));
+
+ await expect(waitForPromptAdmission(work, abort.signal)).rejects.toThrow("Prompt admission was cancelled.");
+ // Let the observed work settle; an unhandled rejection would fail Vitest.
+ await Promise.resolve();
+ });
+
+ it("rejects with the typed cancellation error when the signal aborts mid-wait", async () => {
+ const abort = new AbortController();
+ const wait = waitForPromptAdmission(new Promise(() => {}), abort.signal);
+ abort.abort();
+ await expect(wait).rejects.toBeInstanceOf(PromptAdmissionCancelledError);
+ });
+
+ it("passes work through untouched without a signal and settles with the work otherwise", async () => {
+ const resolved = Promise.resolve("value");
+ expect(waitForPromptAdmission(resolved, undefined)).toBe(resolved);
+ await expect(waitForPromptAdmission(resolved, new AbortController().signal)).resolves.toBe("value");
+ await expect(
+ waitForPromptAdmission(Promise.reject(new Error("work failed")), new AbortController().signal),
+ ).rejects.toThrow("work failed");
+ });
+});
diff --git a/packages/coding-agent/test/prompt-templates.test.ts b/packages/coding-agent/test/prompt-templates.test.ts
index 7a70f9949b..882bd9b6b6 100644
--- a/packages/coding-agent/test/prompt-templates.test.ts
+++ b/packages/coding-agent/test/prompt-templates.test.ts
@@ -318,8 +318,21 @@ describe("parseCommandArgs", () => {
expect(parseCommandArgs("a b c")).toEqual(["a", "b", "c"]);
});
- test("should handle tabs as separators", () => {
- expect(parseCommandArgs("a\tb\tc")).toEqual(["a", "b", "c"]);
+ test.each([
+ { name: "tabs", input: "a\tb\tc", expected: ["a", "b", "c"] },
+ {
+ name: "Unicode spaces",
+ input: "first\u2002second",
+ expected: ["first", "second"],
+ positionalResult: "first|second",
+ },
+ ])("should handle $name as separators", ({ input, expected, positionalResult }) => {
+ const args = parseCommandArgs(input);
+
+ expect(args).toEqual(expected);
+ if (positionalResult) {
+ expect(substituteArgs("$1|$2", args)).toBe(positionalResult);
+ }
});
test("should handle quoted empty string", () => {
diff --git a/packages/coding-agent/test/selector-search-reset.test.ts b/packages/coding-agent/test/selector-search-reset.test.ts
index be2d93d1dd..55534d5da7 100644
--- a/packages/coding-agent/test/selector-search-reset.test.ts
+++ b/packages/coding-agent/test/selector-search-reset.test.ts
@@ -2,12 +2,10 @@ import { setKeybindings, type TUI } from "@earendil-works/pi-tui";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { AuthStorage } from "../src/core/auth-storage.js";
import { KeybindingsManager } from "../src/core/keybindings.js";
-import type { AgentConnectionSavedSessionInfo } from "../src/modes/agent-connection/index.js";
import { ModelSelectorComponent } from "../src/modes/interactive/components/model-selector.js";
import { OAuthSelectorComponent } from "../src/modes/interactive/components/oauth-selector.js";
import { PrimeTeamSelectorComponent } from "../src/modes/interactive/components/prime-team-selector.js";
import { ScopedModelsSelectorComponent } from "../src/modes/interactive/components/scoped-models-selector.js";
-import { SessionSelectorComponent } from "../src/modes/interactive/components/session-selector.js";
import { initTheme } from "../src/modes/interactive/theme/theme.js";
import { createHarness, type Harness } from "./suite/harness.js";
@@ -23,24 +21,6 @@ function moveDown(component: { handleInput(data: string): void }, count: number)
}
}
-function makeSession(index: number): AgentConnectionSavedSessionInfo {
- return {
- path: `/tmp/session-${index}.jsonl`,
- id: `session-${index}`,
- cwd: "/tmp",
- name: `Session ${index}`,
- created: new Date(index),
- modified: new Date(index),
- messageCount: 1,
- firstMessage: "common topic",
- allMessagesText: "common topic",
- };
-}
-
-async function flushPromises(): Promise<void> {
- await new Promise<void>((resolve) => setImmediate(resolve));
-}
-
describe("searchable selector navigation", () => {
const harnesses: Harness[] = [];
@@ -159,27 +139,4 @@ describe("searchable selector navigation", () => {
expect(enabledModelIds).toEqual([`${harness.models[0]?.provider}/faux-1`]);
});
-
- it("selects the first session after the search query changes", async () => {
- const sessions = Array.from({ length: 12 }, (_, index) => makeSession(index + 1));
- let selectedPath: string | undefined;
- const selector = new SessionSelectorComponent(
- async () => sessions,
- async () => sessions,
- (path) => {
- selectedPath = path;
- },
- () => {},
- () => {},
- () => {},
- );
- await flushPromises();
-
- const list = selector.getSessionList();
- moveDown(list, 8);
- list.handleInput("c");
- list.handleInput("\r");
-
- expect(selectedPath).toBe(sessions.at(-1)?.path);
- });
});
diff --git a/packages/coding-agent/test/session-cwd.test.ts b/packages/coding-agent/test/session-cwd.test.ts
index cf3583ccab..1615d31605 100644
--- a/packages/coding-agent/test/session-cwd.test.ts
+++ b/packages/coding-agent/test/session-cwd.test.ts
@@ -7,7 +7,6 @@ import { SessionSelectorNotFoundError } from "../src/cli/session-resolver.js";
import { type CreateAgentSessionRuntimeFactory, createAgentSessionRuntime } from "../src/core/agent-session-runtime.js";
import { getMissingSessionCwdIssue, MissingSessionCwdError } from "../src/core/session-cwd.js";
import { SessionManager } from "../src/core/session-manager.js";
-import { SettingsManager } from "../src/core/settings-manager.js";
import { createSessionManager } from "../src/main.js";
function createTempDir(name: string): string {
@@ -99,12 +98,7 @@ describe("session cwd handling", () => {
writeSessionFile(sessionFile, storedCwd);
const parsed = parseArgs(["--cwd", explicitCwd, "--resume", sessionFile]);
- const sessionManager = await createSessionManager(
- parsed,
- explicitCwd,
- sessionDir,
- SettingsManager.create(explicitCwd, agentDir),
- );
+ const sessionManager = await createSessionManager(parsed, explicitCwd, sessionDir);
expect(sessionManager.getCwd()).toBe(explicitCwd);
});
@@ -116,9 +110,7 @@ describe("session cwd handling", () => {
cleanupPaths.push(cwd, agentDir, sessionDir);
const parsed = parseArgs(["--resume", "fix", "the", "bug"]);
- await expect(
- createSessionManager(parsed, cwd, sessionDir, SettingsManager.create(cwd, agentDir)),
- ).rejects.toMatchObject({
+ await expect(createSessionManager(parsed, cwd, sessionDir)).rejects.toMatchObject({
name: SessionSelectorNotFoundError.name,
selector: "fix",
suggestion: undefined,
@@ -152,4 +144,9 @@ describe("session cwd handling", () => {
).rejects.toBeInstanceOf(MissingSessionCwdError);
expect(createRuntimeCalled).toBe(false);
});
+
+ it("preserves an explicit catalog directory for in-memory bootstrap sessions", () => {
+ const manager = SessionManager.inMemory("/tmp/project", "/tmp/sessions");
+ expect(manager.getSessionDir()).toBe("/tmp/sessions");
+ });
});
diff --git a/packages/coding-agent/test/session-picker-screen.test.ts b/packages/coding-agent/test/session-picker-screen.test.ts
deleted file mode 100644
index 4e6f1f0b55..0000000000
--- a/packages/coding-agent/test/session-picker-screen.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { type Component, type TUI, visibleWidth } from "@earendil-works/pi-tui";
-import { describe, expect, it, vi } from "vitest";
-import {
- SessionPickerScreen,
- sessionPickerListMaxVisible,
-} from "../src/modes/interactive/components/session-picker-screen.js";
-import type { SessionSelectorComponent } from "../src/modes/interactive/components/session-selector.js";
-
-describe("SessionPickerScreen", () => {
- it("uses a centered full-terminal surface and sizes the session list to the viewport", () => {
- const ui = { terminal: { rows: 24 } } as unknown as TUI;
- const header = {
- invalidate: vi.fn(),
- render: vi.fn(() => ["Resume Session"]),
- } as Component;
- const selector = {
- focused: false,
- handleInput: vi.fn(),
- invalidate: vi.fn(),
- render: vi.fn(() => ["Saved session"]),
- setListMaxVisible: vi.fn(),
- } as unknown as SessionSelectorComponent;
-
- const screen = new SessionPickerScreen(ui, header, selector);
- screen.focused = true;
- screen.handleInput("x");
- const lines = screen.render(120);
-
- expect(selector.focused).toBe(true);
- expect(selector.handleInput).toHaveBeenCalledWith("x");
- expect(sessionPickerListMaxVisible(24, 1)).toBe(13);
- expect(header.render).toHaveBeenCalledWith(120);
- expect(selector.setListMaxVisible).toHaveBeenCalledWith(13);
- expect(selector.render).toHaveBeenCalledWith(120);
- expect(lines).toHaveLength(24);
- expect(lines[0]!.trim()).toBe("Resume Session");
- expect(lines[1]!.trim()).toBe("Saved session");
- expect(lines.every((line) => visibleWidth(line) === 120)).toBe(true);
- });
-});
diff --git a/packages/coding-agent/test/session-selector-path-delete.test.ts b/packages/coding-agent/test/session-selector-path-delete.test.ts
deleted file mode 100644
index 69a29cbbe1..0000000000
--- a/packages/coding-agent/test/session-selector-path-delete.test.ts
+++ /dev/null
@@ -1,571 +0,0 @@
-import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { setKeybindings, visibleWidth } from "@earendil-works/pi-tui";
-import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
-import { KeybindingsManager } from "../src/core/keybindings.js";
-import type { AgentConnectionSavedSessionInfo } from "../src/modes/agent-connection/index.js";
-import { SessionSelectorComponent } from "../src/modes/interactive/components/session-selector.js";
-import { initTheme, preloadCodeHighlighter, theme } from "../src/modes/interactive/theme/theme.js";
-
-type Deferred<T> = {
- promise: Promise<T>;
- resolve: (value: T) => void;
- reject: (err: unknown) => void;
-};
-
-function createDeferred<T>(): Deferred<T> {
- let resolve: (value: T) => void = () => {};
- let reject: (err: unknown) => void = () => {};
- const promise = new Promise<T>((res, rej) => {
- resolve = res;
- reject = rej;
- });
- return { promise, resolve, reject };
-}
-
-async function flushPromises(): Promise<void> {
- await new Promise<void>((resolve) => {
- setImmediate(resolve);
- });
-}
-
-function stripAnsi(text: string): string {
- return text.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "");
-}
-
-function makeSession(
- overrides: Partial<AgentConnectionSavedSessionInfo> & { id: string },
-): AgentConnectionSavedSessionInfo {
- return {
- path: overrides.path ?? `/tmp/${overrides.id}.jsonl`,
- id: overrides.id,
- cwd: overrides.cwd ?? "",
- name: overrides.name,
- parentSessionPath: overrides.parentSessionPath,
- created: overrides.created ?? new Date(0),
- modified: overrides.modified ?? new Date(0),
- messageCount: overrides.messageCount ?? 1,
- firstMessage: overrides.firstMessage ?? "hello",
- allMessagesText: overrides.allMessagesText ?? "hello",
- };
-}
-
-function createSymlinkedSessionPaths(): {
- baseDir: string;
- parentAliasA: string;
- parentAliasB: string;
- childAliasB: string;
-} {
- const baseDir = mkdtempSync(join(tmpdir(), "pi-session-selector-"));
- const realDir = join(baseDir, "real");
- const aliasADir = join(baseDir, "alias-a");
- const aliasBDir = join(baseDir, "alias-b");
- mkdirSync(realDir, { recursive: true });
- mkdirSync(aliasADir, { recursive: true });
- mkdirSync(aliasBDir, { recursive: true });
-
- const sharedDir = join(realDir, "sessions");
- mkdirSync(sharedDir, { recursive: true });
- const aliasASessions = join(aliasADir, "sessions");
- const aliasBSessions = join(aliasBDir, "sessions");
- symlinkSync(sharedDir, aliasASessions);
- symlinkSync(sharedDir, aliasBSessions);
-
- const parentRealPath = join(sharedDir, "parent.jsonl");
- const childRealPath = join(sharedDir, "child.jsonl");
- writeFileSync(parentRealPath, "parent\n");
- writeFileSync(childRealPath, "child\n");
-
- return {
- baseDir,
- parentAliasA: join(aliasASessions, "parent.jsonl"),
- parentAliasB: join(aliasBSessions, "parent.jsonl"),
- childAliasB: join(aliasBSessions, "child.jsonl"),
- };
-}
-
-const CTRL_X = "\x18";
-const CTRL_S = "\x13";
-const CTRL_BACKSPACE = "\x1b[127;5u";
-
-describe("session selector path/delete interactions", () => {
- const keybindings = new KeybindingsManager();
- const tempDirs: string[] = [];
-
- afterEach(() => {
- for (const dir of tempDirs.splice(0)) {
- rmSync(dir, { recursive: true, force: true });
- }
- });
-
- beforeEach(() => {
- // Ensure test isolation: keybindings are a global singleton
- setKeybindings(new KeybindingsManager());
- });
-
- beforeAll(async () => {
- // session selector uses the global theme instance
- initTheme("dark");
- await preloadCodeHighlighter();
- });
- it("does not treat Ctrl+Backspace as delete when search query is non-empty", async () => {
- const sessions = [makeSession({ id: "a" }), makeSession({ id: "b" })];
-
- const selector = new SessionSelectorComponent(
- async () => sessions,
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { keybindings },
- );
- await flushPromises();
-
- const list = selector.getSessionList();
- const confirmationChanges: Array<string | null> = [];
- list.onDeleteConfirmationChange = (path) => confirmationChanges.push(path);
-
- list.handleInput("a");
- list.handleInput(CTRL_BACKSPACE);
-
- expect(confirmationChanges).toEqual([]);
- });
-
- it("enters confirmation mode on Ctrl+X even with a non-empty search query", async () => {
- const sessions = [makeSession({ id: "a" }), makeSession({ id: "b" })];
-
- const selector = new SessionSelectorComponent(
- async () => sessions,
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { keybindings },
- );
- await flushPromises();
-
- const list = selector.getSessionList();
- const confirmationChanges: Array<string | null> = [];
- list.onDeleteConfirmationChange = (path) => confirmationChanges.push(path);
-
- list.handleInput("a");
- list.handleInput(CTRL_X);
-
- expect(confirmationChanges).toEqual([sessions[0]!.path]);
- });
-
- it("enters confirmation mode on Ctrl+Backspace when search query is empty", async () => {
- const sessions = [makeSession({ id: "a" }), makeSession({ id: "b" })];
-
- const selector = new SessionSelectorComponent(
- async () => sessions,
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { keybindings },
- );
- await flushPromises();
-
- const list = selector.getSessionList();
- const confirmationChanges: Array<string | null> = [];
- list.onDeleteConfirmationChange = (path) => confirmationChanges.push(path);
-
- let deletedPath: string | null = null;
- list.onDeleteSession = async (sessionPath) => {
- deletedPath = sessionPath;
- };
-
- list.handleInput(CTRL_BACKSPACE);
- expect(confirmationChanges).toEqual([sessions[0]!.path]);
-
- list.handleInput(CTRL_BACKSPACE);
- expect(confirmationChanges).toEqual([sessions[0]!.path, null]);
- expect(deletedPath).toBe(sessions[0]!.path);
- });
-
- it("delegates confirmed deletion to the injected delete handler", async () => {
- const sessions = [makeSession({ id: "a" })];
- const deleteSession = vi.fn(async () => ({ ok: true as const, method: "unlink" as const }));
-
- const selector = new SessionSelectorComponent(
- async () => sessions,
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { keybindings, deleteSession },
- );
- await flushPromises();
-
- const list = selector.getSessionList();
- list.handleInput(CTRL_X);
- list.handleInput(CTRL_X);
- await flushPromises();
-
- expect(deleteSession).toHaveBeenCalledTimes(1);
- expect(deleteSession).toHaveBeenCalledWith(sessions[0]!.path);
- });
-
- it("shows an error when the injected delete handler rejects", async () => {
- const sessions = [makeSession({ id: "a" })];
- const deleteSession = vi.fn(async () => {
- throw new Error("Cannot delete the currently active session");
- });
-
- const selector = new SessionSelectorComponent(
- async () => sessions,
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { keybindings, deleteSession },
- );
- await flushPromises();
-
- const list = selector.getSessionList();
- list.handleInput(CTRL_X);
- list.handleInput(CTRL_X);
- await flushPromises();
-
- const output = stripAnsi(selector.render(120).join("\n"));
- expect(deleteSession).toHaveBeenCalledTimes(1);
- expect(output).toContain("Failed to delete: Cannot delete the currently active session");
- });
-
- it("keeps delete success visible when refresh after deletion fails", async () => {
- const sessions = [makeSession({ id: "a" })];
- const deleteSession = vi.fn(async () => ({ ok: true as const, method: "unlink" as const }));
- let loadCalls = 0;
-
- const selector = new SessionSelectorComponent(
- async () => {
- loadCalls++;
- if (loadCalls > 1) {
- throw new Error("refresh unavailable");
- }
- return sessions;
- },
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { keybindings, deleteSession },
- );
- await flushPromises();
-
- const list = selector.getSessionList();
- list.handleInput(CTRL_X);
- list.handleInput(CTRL_X);
- await flushPromises();
-
- const output = stripAnsi(selector.render(120).join("\n"));
- expect(deleteSession).toHaveBeenCalledTimes(1);
- expect(output).toContain("Session deleted");
- expect(output).not.toContain("Failed to delete");
- });
-
- it("waits for the complete session list while reporting load progress", async () => {
- const session = makeSession({ id: "complete", name: "Complete session" });
- const sessionsDeferred = createDeferred<AgentConnectionSavedSessionInfo[]>();
- let receivedItemCallback = false;
-
- const selector = new SessionSelectorComponent(
- async (callbacks) => {
- callbacks?.onProgress?.(1, 2);
- receivedItemCallback = callbacks?.onSession !== undefined;
- return sessionsDeferred.promise;
- },
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { keybindings },
- );
- await flushPromises();
-
- const loadingOutput = stripAnsi(selector.render(120).join("\n"));
- expect(loadingOutput).toContain("loading 1/2");
- expect(loadingOutput).not.toContain("Complete session");
- expect(receivedItemCallback).toBe(false);
-
- sessionsDeferred.resolve([session]);
- await flushPromises();
-
- const output = stripAnsi(selector.render(120).join("\n"));
- expect(output).toContain("current folder");
- expect(output).toContain("Complete session");
- });
-
- it("selects the newest session from an unsorted completed list", async () => {
- const older = makeSession({
- id: "older",
- name: "Older session",
- modified: new Date("2026-01-01T00:00:00.000Z"),
- });
- const newer = makeSession({
- id: "newer",
- name: "Newer session",
- modified: new Date("2026-01-03T00:00:00.000Z"),
- });
- const sessionsDeferred = createDeferred<AgentConnectionSavedSessionInfo[]>();
- const onSelect = vi.fn();
-
- const selector = new SessionSelectorComponent(
- async () => sessionsDeferred.promise,
- async () => [],
- onSelect,
- () => {},
- () => {},
- () => {},
- { keybindings },
- );
- await flushPromises();
-
- sessionsDeferred.resolve([older, newer]);
- await flushPromises();
-
- const output = stripAnsi(selector.render(120).join("\n"));
- expect(output).toContain("sort: recent");
- expect(output.indexOf("Newer session")).toBeLessThan(output.indexOf("Older session"));
-
- const list = selector.getSessionList();
- list.handleInput("\r");
- expect(onSelect).toHaveBeenCalledWith(newer.path);
- });
-
- it("keeps the selected session when a completed reload reorders the list", async () => {
- const selected = makeSession({
- id: "selected",
- name: "Selected session",
- modified: new Date("2026-01-02T00:00:00.000Z"),
- });
- const previousNewest = makeSession({
- id: "previous-newest",
- name: "Previous newest session",
- modified: new Date("2026-01-03T00:00:00.000Z"),
- });
- const newNewest = makeSession({
- id: "new-newest",
- name: "New newest session",
- modified: new Date("2026-01-04T00:00:00.000Z"),
- });
- const onSelect = vi.fn();
- const selector = new SessionSelectorComponent(
- async () => [selected, previousNewest],
- async () => [],
- onSelect,
- () => {},
- () => {},
- () => {},
- { keybindings },
- );
- await flushPromises();
-
- const list = selector.getSessionList();
- list.handleInput("\x1b[B");
- list.setSessions([selected, previousNewest, newNewest], false);
- list.handleInput("\r");
-
- expect(onSelect).toHaveBeenCalledWith(selected.path);
- });
-
- it("keeps the selected background across a truncated session row", async () => {
- const session = makeSession({
- id: "long",
- name: "A session prompt that is much too long to fit within the available row width",
- });
- const selector = new SessionSelectorComponent(
- async () => [session],
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { keybindings },
- );
- await flushPromises();
-
- const line = selector.render(60).find((candidate) => stripAnsi(candidate).includes("A session prompt"));
- const backgroundStart = theme.bg("selectedBg", "").replace("\x1b[49m", "");
- expect(stripAnsi(line ?? "")).toContain("…");
- expect(line?.startsWith(backgroundStart)).toBe(true);
- expect(line?.endsWith("\x1b[49m")).toBe(true);
- expect(line).not.toContain("\x1b[0m");
- expect(visibleWidth(line ?? "")).toBe(60);
- });
-
- it("does not switch scope back to All when All load resolves after toggling back to Current", async () => {
- const currentSessions = [makeSession({ id: "current" })];
- const allDeferred = createDeferred<AgentConnectionSavedSessionInfo[]>();
- let allLoadCalls = 0;
-
- const selector = new SessionSelectorComponent(
- async () => currentSessions,
- async () => {
- allLoadCalls++;
- return allDeferred.promise;
- },
- () => {},
- () => {},
- () => {},
- () => {},
- { keybindings },
- );
- await flushPromises();
-
- const list = selector.getSessionList();
- list.handleInput("\t"); // current -> all (starts async load)
- list.handleInput("\t"); // all -> current
-
- allDeferred.resolve([makeSession({ id: "all" })]);
- await flushPromises();
-
- expect(allLoadCalls).toBe(1);
- const output = selector.render(120).join("\n");
- expect(output).toContain("current folder");
- expect(output).not.toContain("all projects");
- });
-
- it("hides current-folder rows while all projects are loading", async () => {
- const currentSession = makeSession({ id: "current", name: "Current folder session" });
- const allDeferred = createDeferred<AgentConnectionSavedSessionInfo[]>();
- const onSelect = vi.fn();
- const selector = new SessionSelectorComponent(
- async () => [currentSession],
- async () => allDeferred.promise,
- onSelect,
- () => {},
- () => {},
- () => {},
- { keybindings },
- );
- await flushPromises();
-
- const list = selector.getSessionList();
- list.handleInput("\t");
-
- const output = stripAnsi(selector.render(120).join("\n"));
- expect(output).toContain("loading");
- expect(output).not.toContain("Current folder session");
- expect(output).not.toContain("No sessions found");
-
- list.handleInput("\r");
- expect(onSelect).not.toHaveBeenCalled();
-
- allDeferred.resolve([makeSession({ id: "all", name: "All projects session" })]);
- await flushPromises();
- });
-
- it("does not start redundant All loads when toggling scopes while All is already loading", async () => {
- const currentSessions = [makeSession({ id: "current", name: "Current folder session" })];
- const allDeferred = createDeferred<AgentConnectionSavedSessionInfo[]>();
- let allLoadCalls = 0;
-
- const selector = new SessionSelectorComponent(
- async () => currentSessions,
- async () => {
- allLoadCalls++;
- return allDeferred.promise;
- },
- () => {},
- () => {},
- () => {},
- () => {},
- { keybindings },
- );
- await flushPromises();
-
- const list = selector.getSessionList();
- list.handleInput("\t"); // current -> all (starts async load)
- list.handleInput("\t"); // all -> current
- list.handleInput("\t"); // current -> all again while load pending
-
- expect(allLoadCalls).toBe(1);
- const output = stripAnsi(selector.render(120).join("\n"));
- expect(output).toContain("loading");
- expect(output).not.toContain("Current folder session");
-
- allDeferred.resolve([makeSession({ id: "all" })]);
- await flushPromises();
- });
-
- it("threads sessions when parent and child paths use different symlink aliases", async () => {
- const paths = createSymlinkedSessionPaths();
- tempDirs.push(paths.baseDir);
-
- const sessions = [
- makeSession({
- id: "parent",
- path: paths.parentAliasB,
- name: "Parent",
- modified: new Date("2026-01-01T00:00:00.000Z"),
- }),
- makeSession({
- id: "child",
- path: paths.childAliasB,
- parentSessionPath: paths.parentAliasA,
- name: "Child",
- modified: new Date("2025-12-31T00:00:00.000Z"),
- }),
- ];
-
- const selector = new SessionSelectorComponent(
- async () => sessions,
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { keybindings },
- );
- await flushPromises();
-
- const list = selector.getSessionList();
- list.handleInput(CTRL_S);
- list.handleInput(CTRL_S);
-
- const output = stripAnsi(selector.render(120).join("\n"));
- expect(output).toContain("Parent");
- expect(output).toContain("└─ ✓ Child");
- });
-
- it("treats the current session as active across symlink aliases", async () => {
- const paths = createSymlinkedSessionPaths();
- tempDirs.push(paths.baseDir);
-
- const sessions = [makeSession({ id: "parent", path: paths.parentAliasB, name: "Parent" })];
- const selector = new SessionSelectorComponent(
- async () => sessions,
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { keybindings },
- paths.parentAliasA,
- );
- await flushPromises();
-
- const list = selector.getSessionList();
- const confirmationChanges: Array<string | null> = [];
- let errorMessage: string | undefined;
- list.onDeleteConfirmationChange = (path) => confirmationChanges.push(path);
- list.onError = (message) => {
- errorMessage = message;
- };
-
- list.handleInput(CTRL_X);
-
- expect(confirmationChanges).toEqual([]);
- expect(errorMessage).toBe("Cannot delete the currently active session");
- });
-});
diff --git a/packages/coding-agent/test/session-selector-rename.test.ts b/packages/coding-agent/test/session-selector-rename.test.ts
deleted file mode 100644
index 1d7df10059..0000000000
--- a/packages/coding-agent/test/session-selector-rename.test.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-import { setKeybindings } from "@earendil-works/pi-tui";
-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
-import { KeybindingsManager } from "../src/core/keybindings.js";
-import type { AgentConnectionSavedSessionInfo } from "../src/modes/agent-connection/index.js";
-import { SessionSelectorComponent } from "../src/modes/interactive/components/session-selector.js";
-import { initTheme, preloadCodeHighlighter } from "../src/modes/interactive/theme/theme.js";
-
-async function flushPromises(): Promise<void> {
- await new Promise<void>((resolve) => {
- setImmediate(resolve);
- });
-}
-
-function makeSession(
- overrides: Partial<AgentConnectionSavedSessionInfo> & { id: string },
-): AgentConnectionSavedSessionInfo {
- return {
- path: overrides.path ?? `/tmp/${overrides.id}.jsonl`,
- id: overrides.id,
- cwd: overrides.cwd ?? "",
- name: overrides.name,
- created: overrides.created ?? new Date(0),
- modified: overrides.modified ?? new Date(0),
- messageCount: overrides.messageCount ?? 1,
- firstMessage: overrides.firstMessage ?? "hello",
- allMessagesText: overrides.allMessagesText ?? "hello",
- };
-}
-
-// Kitty keyboard protocol encoding for Ctrl+R
-const CTRL_R = "\x1b[114;5u";
-
-describe("session selector rename", () => {
- beforeAll(async () => {
- initTheme("dark");
- await preloadCodeHighlighter();
- });
-
- beforeEach(() => {
- // Ensure test isolation: keybindings are a global singleton
- setKeybindings(new KeybindingsManager());
- });
-
- it("shows rename hint in interactive /resume picker configuration", async () => {
- const sessions = [makeSession({ id: "a" })];
- const keybindings = new KeybindingsManager();
- const selector = new SessionSelectorComponent(
- async () => sessions,
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { showRenameHint: true, keybindings },
- );
- await flushPromises();
-
- const output = selector.render(120).join("\n");
- expect(output).toContain("Ctrl+R");
- expect(output).toContain("rename");
- });
-
- it("shows rename hint in --resume picker configuration", async () => {
- const sessions = [makeSession({ id: "a" })];
- const keybindings = new KeybindingsManager();
- const selector = new SessionSelectorComponent(
- async () => sessions,
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { renameSession: async () => {}, showRenameHint: true, keybindings },
- );
- await flushPromises();
-
- const output = selector.render(120).join("\n");
- expect(output).toContain("Ctrl+R");
- expect(output).toContain("rename");
- });
-
- it("enters rename mode on Ctrl+R and submits with Enter", async () => {
- const sessions = [makeSession({ id: "a", name: "Old" })];
- const renameSession = vi.fn(async () => {});
-
- const keybindings = new KeybindingsManager();
- const selector = new SessionSelectorComponent(
- async () => sessions,
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { renameSession, showRenameHint: true, keybindings },
- );
- await flushPromises();
-
- selector.handleInput(CTRL_R);
- await flushPromises();
-
- // Rename mode layout
- const output = selector.render(120).join("\n");
- expect(output).toContain("Rename Session");
- expect(output).not.toContain("Resume Session");
-
- // Type and submit
- selector.handleInput("X");
- selector.handleInput("\r");
- await flushPromises();
-
- expect(renameSession).toHaveBeenCalledTimes(1);
- expect(renameSession).toHaveBeenCalledWith(sessions[0]!.path, "XOld");
- });
-
- it("shows an error when rename fails", async () => {
- const sessions = [makeSession({ id: "a", name: "Old" })];
- const renameSession = vi.fn(async () => {
- throw new Error("daemon unavailable");
- });
-
- const keybindings = new KeybindingsManager();
- const selector = new SessionSelectorComponent(
- async () => sessions,
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { renameSession, showRenameHint: true, keybindings },
- );
- await flushPromises();
-
- selector.getSessionList().handleInput(CTRL_R);
- await flushPromises();
-
- selector.handleInput("\r");
- await flushPromises();
-
- const output = selector.render(120).join("\n");
- expect(renameSession).toHaveBeenCalledTimes(1);
- expect(output).toContain("Resume Session");
- expect(output).toContain("Failed to rename: daemon unavailable");
- });
-
- it("does not report rename failure when refresh after rename fails", async () => {
- const sessions = [makeSession({ id: "a", name: "Old" })];
- const renameSession = vi.fn(async () => {});
- let loadCalls = 0;
-
- const keybindings = new KeybindingsManager();
- const selector = new SessionSelectorComponent(
- async () => {
- loadCalls++;
- if (loadCalls > 1) {
- throw new Error("refresh unavailable");
- }
- return sessions;
- },
- async () => [],
- () => {},
- () => {},
- () => {},
- () => {},
- { renameSession, showRenameHint: true, keybindings },
- );
- await flushPromises();
-
- selector.getSessionList().handleInput(CTRL_R);
- await flushPromises();
-
- selector.handleInput("\r");
- await flushPromises();
-
- const output = selector.render(120).join("\n");
- expect(renameSession).toHaveBeenCalledTimes(1);
- expect(output).toContain("Resume Session");
- expect(output).not.toContain("Failed to rename");
- });
-});
diff --git a/packages/coding-agent/test/session-selector-search.test.ts b/packages/coding-agent/test/session-selector-search.test.ts
deleted file mode 100644
index 5042486aa7..0000000000
--- a/packages/coding-agent/test/session-selector-search.test.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-import { describe, expect, it } from "vitest";
-import type { AgentConnectionSavedSessionInfo } from "../src/modes/agent-connection/index.js";
-import { filterAndSortSessions } from "../src/modes/interactive/components/session-selector-search.js";
-
-function makeSession(
- overrides: Partial<AgentConnectionSavedSessionInfo> & { id: string; modified: Date; allMessagesText: string },
-): AgentConnectionSavedSessionInfo {
- return {
- path: `/tmp/${overrides.id}.jsonl`,
- id: overrides.id,
- cwd: overrides.cwd ?? "",
- name: overrides.name,
- created: overrides.created ?? new Date(0),
- modified: overrides.modified,
- messageCount: overrides.messageCount ?? 1,
- firstMessage: overrides.firstMessage ?? "(no messages)",
- allMessagesText: overrides.allMessagesText,
- };
-}
-
-describe("session selector search", () => {
- it("filters by quoted phrase with whitespace normalization", () => {
- const sessions: AgentConnectionSavedSessionInfo[] = [
- makeSession({
- id: "a",
- modified: new Date("2026-01-01T00:00:00.000Z"),
- allMessagesText: "node\n\n cve was discussed",
- }),
- makeSession({
- id: "b",
- modified: new Date("2026-01-02T00:00:00.000Z"),
- allMessagesText: "node something else",
- }),
- ];
-
- const result = filterAndSortSessions(sessions, '"node cve"', "recent");
- expect(result.map((s) => s.id)).toEqual(["a"]);
- });
-
- it("filters by regex (re:) and is case-insensitive", () => {
- const sessions: AgentConnectionSavedSessionInfo[] = [
- makeSession({
- id: "a",
- modified: new Date("2026-01-02T00:00:00.000Z"),
- allMessagesText: "Brave is great",
- }),
- makeSession({
- id: "b",
- modified: new Date("2026-01-03T00:00:00.000Z"),
- allMessagesText: "bravery is not the same",
- }),
- ];
-
- const result = filterAndSortSessions(sessions, "re:\\bbrave\\b", "recent");
- expect(result.map((s) => s.id)).toEqual(["a"]);
- });
-
- it("recent sort orders matches by modified date descending", () => {
- const sessions: AgentConnectionSavedSessionInfo[] = [
- makeSession({
- id: "older",
- modified: new Date("2026-01-01T00:00:00.000Z"),
- allMessagesText: "brave",
- }),
- makeSession({
- id: "newer",
- modified: new Date("2026-01-03T00:00:00.000Z"),
- allMessagesText: "brave",
- }),
- makeSession({
- id: "nomatch",
- modified: new Date("2026-01-04T00:00:00.000Z"),
- allMessagesText: "something else",
- }),
- ];
-
- const result = filterAndSortSessions(sessions, '"brave"', "recent");
- expect(result.map((s) => s.id)).toEqual(["newer", "older"]);
- });
-
- it("searches session names", () => {
- const sessions: AgentConnectionSavedSessionInfo[] = [
- makeSession({
- id: "named",
- name: "Release Planning",
- modified: new Date("2026-01-01T00:00:00.000Z"),
- allMessagesText: "unrelated messages",
- }),
- makeSession({
- id: "other",
- modified: new Date("2026-01-02T00:00:00.000Z"),
- allMessagesText: "another topic",
- }),
- ];
-
- const result = filterAndSortSessions(sessions, '"release planning"', "recent");
- expect(result.map((session) => session.id)).toEqual(["named"]);
- });
-
- it("relevance sort orders by score and tie-breaks by modified desc", () => {
- const sessions: AgentConnectionSavedSessionInfo[] = [
- makeSession({
- id: "late",
- modified: new Date("2026-01-03T00:00:00.000Z"),
- allMessagesText: "xxxx brave",
- }),
- makeSession({
- id: "early",
- modified: new Date("2026-01-01T00:00:00.000Z"),
- allMessagesText: "brave xxxx",
- }),
- ];
-
- const result1 = filterAndSortSessions(sessions, '"brave"', "relevance");
- expect(result1.map((s) => s.id)).toEqual(["early", "late"]);
-
- const tieSessions: AgentConnectionSavedSessionInfo[] = [
- makeSession({
- id: "newer",
- modified: new Date("2026-01-03T00:00:00.000Z"),
- allMessagesText: "brave",
- }),
- makeSession({
- id: "older",
- modified: new Date("2026-01-01T00:00:00.000Z"),
- allMessagesText: "brave",
- }),
- ];
-
- const result2 = filterAndSortSessions(tieSessions, '"brave"', "relevance");
- expect(result2.map((s) => s.id)).toEqual(["newer", "older"]);
- });
-
- it("returns empty list for invalid regex", () => {
- const sessions: AgentConnectionSavedSessionInfo[] = [
- makeSession({
- id: "a",
- modified: new Date("2026-01-01T00:00:00.000Z"),
- allMessagesText: "brave",
- }),
- ];
-
- const result = filterAndSortSessions(sessions, "re:(", "recent");
- expect(result).toEqual([]);
- });
-
- describe("name filter", () => {
- const sessions: AgentConnectionSavedSessionInfo[] = [
- makeSession({
- id: "named1",
- name: "My Project",
- modified: new Date("2026-01-03T00:00:00.000Z"),
- allMessagesText: "blueberry",
- }),
- makeSession({
- id: "named2",
- name: "Another Named",
- modified: new Date("2026-01-02T00:00:00.000Z"),
- allMessagesText: "blueberry",
- }),
- makeSession({
- id: "other1",
- modified: new Date("2026-01-04T00:00:00.000Z"),
- allMessagesText: "blueberry",
- }),
- makeSession({
- id: "other2",
- modified: new Date("2026-01-01T00:00:00.000Z"),
- allMessagesText: "blueberry",
- }),
- ];
-
- it("returns all sessions when nameFilter is 'all'", () => {
- const result = filterAndSortSessions(sessions, "", "recent", "all");
- expect(result.map((session) => session.id)).toEqual(["other1", "named1", "named2", "other2"]);
- });
-
- it("returns only named sessions when nameFilter is 'named'", () => {
- const result = filterAndSortSessions(sessions, "", "recent", "named");
- expect(result.map((session) => session.id)).toEqual(["named1", "named2"]);
- });
-
- it("applies name filter before search query", () => {
- const result = filterAndSortSessions(sessions, "blueberry", "recent", "named");
- expect(result.map((session) => session.id)).toEqual(["named1", "named2"]);
- });
-
- it("excludes whitespace-only names from named filter", () => {
- const sessionsWithWhitespace: AgentConnectionSavedSessionInfo[] = [
- makeSession({
- id: "whitespace",
- name: " ",
- modified: new Date("2026-01-01T00:00:00.000Z"),
- allMessagesText: "test",
- }),
- makeSession({
- id: "empty",
- name: "",
- modified: new Date("2026-01-02T00:00:00.000Z"),
- allMessagesText: "test",
- }),
- makeSession({
- id: "named",
- name: "Real Name",
- modified: new Date("2026-01-03T00:00:00.000Z"),
- allMessagesText: "test",
- }),
- ];
-
- const result = filterAndSortSessions(sessionsWithWhitespace, "", "recent", "named");
- expect(result.map((session) => session.id)).toEqual(["named"]);
- });
- });
-});
diff --git a/packages/coding-agent/test/session-view-search.test.ts b/packages/coding-agent/test/session-view-search.test.ts
new file mode 100644
index 0000000000..9c6182fc37
--- /dev/null
+++ b/packages/coding-agent/test/session-view-search.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+import { createSessionSearchText, matchesSearchText } from "../src/modes/agents-view/session-view-search.js";
+
+describe("session view search", () => {
+ it("matches fuzzy tokens, normalized phrases, and case-insensitive regexes", () => {
+ const text = createSessionSearchText(["Release Planner", "/work/widget", "fixed the node\n CVE"]);
+ expect(matchesSearchText(text, "rls plnr")).toBe(true);
+ expect(matchesSearchText(text, '"node cve"')).toBe(true);
+ expect(matchesSearchText(text, "re:/WORK/\\w+")).toBe(true);
+ expect(matchesSearchText(text, "re:(")).toBe(false);
+ });
+
+ it("rejects noisy fuzzy matches that only scatter across the corpus", () => {
+ const text = createSessionSearchText(["Release Planner", "/work/widget", "fixed the node\n CVE"]);
+ expect(matchesSearchText(text, "planner")).toBe(true);
+ expect(matchesSearchText(text, "rwfxce")).toBe(false);
+ });
+});
diff --git a/packages/coding-agent/test/suite/agent-session-prompt.test.ts b/packages/coding-agent/test/suite/agent-session-prompt.test.ts
index 02d1c7592c..f4a58ba464 100644
--- a/packages/coding-agent/test/suite/agent-session-prompt.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-prompt.test.ts
@@ -5,7 +5,6 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
import { fauxAssistantMessage, fauxToolCall, type Model } from "@earendil-works/pi-ai";
import { Type } from "typebox";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { waitForPromptAdmission } from "../../src/core/agent-session.js";
import type { BashResult } from "../../src/core/bash-executor.js";
import type { PromptTemplate } from "../../src/core/prompt-templates.js";
import { createSyntheticSourceInfo } from "../../src/core/source-info.js";
@@ -13,8 +12,6 @@ import { createTestResourceLoader } from "../utilities.js";
import { createHarness, getAssistantTexts, getMessageText, getUserTexts, type Harness } from "./harness.js";
import { createDeferred, createWaitingHarness, gatedHook } from "./scheduling.js";
-// acceptAgentMessagePrompt admission is asynchronous. Pause after agent.prompt has
-// synchronously claimed the run, but before its prompt messages become delivered.
function gateNextAgentStart(harness: Harness): { reached: Promise<void>; release(): void } {
let markReached = () => {};
const reached = new Promise<void>((resolve) => {
@@ -35,15 +32,6 @@ function gateNextAgentStart(harness: Harness): { reached: Promise<void>; release
}
describe("AgentSession prompt characterization", () => {
- it("observes already-running work when prompt admission is pre-aborted", async () => {
- const abort = new AbortController();
- abort.abort();
- const work = Promise.reject(new Error("late idle failure"));
-
- expect(() => waitForPromptAdmission(work, abort.signal)).toThrow("Prompt admission was cancelled");
- await Promise.resolve();
- });
-
const harnesses: Harness[] = [];
const tempDirs: string[] = [];
@@ -1083,93 +1071,94 @@ stale post-hook extension instructions`,
expect(harness.session.hasPendingBashMessages).toBe(false);
});
- it("cleared accepted agent message cleanup does not remove messages from a newer prompt", async () => {
- let gateAgentStart = false;
- let releaseGate = () => {};
- const gate = new Promise<void>((resolve) => {
- releaseGate = resolve;
+ it("clears an accepted agent message before delivery without disturbing later work", async () => {
+ let holdAgentStart = true;
+ let releaseEventQueue = () => {};
+ const eventQueueGate = new Promise<void>((resolve) => {
+ releaseEventQueue = resolve;
});
const harness = await createHarness({
extensionFactories: [
(pi) => {
pi.on("agent_start", async () => {
- if (gateAgentStart) {
- await gate;
- }
+ if (holdAgentStart) await eventQueueGate;
});
},
],
});
harnesses.push(harness);
- const agentPrompt =
- "Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_stale_cleanup\n\nagent text";
- harness.setResponses([fauxAssistantMessage("seed response")]);
- await harness.session.prompt("seed");
-
- harness.setResponses([fauxAssistantMessage("never delivered"), fauxAssistantMessage("after clear response")]);
- gateAgentStart = true;
- const admission = gateNextAgentStart(harness);
- const accepted = harness.session.acceptAgentMessagePrompt(agentPrompt, { expandPromptTemplates: false });
- await admission.reached;
- expect(harness.session.clearQueuedUserMessagesMatching((text) => text.includes("agentmsg_"))).toEqual({
- steering: [],
- followUp: [agentPrompt],
- });
- admission.release();
- await expect(accepted).rejects.toThrow("cleared before delivery");
- await harness.session.agent.waitForIdle();
-
- // The cleared run's events are still stalled in the session event queue;
- // run a newer prompt so its messages land in state before the stale cleanup.
- harness.setResponses([fauxAssistantMessage("after clear response")]);
- gateAgentStart = false;
- await harness.session.prompt("after clear");
- releaseGate();
- await (harness.session as unknown as { _agentEventQueue: Promise<void> })._agentEventQueue;
-
- expect(getUserTexts(harness)).toEqual(["seed", "after clear"]);
- expect(getAssistantTexts(harness)).toEqual(["seed response", "after clear response"]);
- });
-
- it("restores drained nextTurn messages when an accepted agent message is cleared", async () => {
- const harness = await createHarness();
- harnesses.push(harness);
- const agentPrompt =
- "Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_next_turn\n\nagent text";
+ const agentMessageId = "agentmsg_clear_lifecycle";
+ const agentPrompt = `Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: ${agentMessageId}\n\nagent text`;
await harness.session.sendCustomMessage(
{ customType: "next-turn", content: "carry this", display: true, details: {} },
{ deliverAs: "nextTurn" },
);
+ harness.events.splice(0);
harness.setResponses([fauxAssistantMessage("never delivered")]);
- const admission = gateNextAgentStart(harness);
+ let markAdmitted = () => {};
+ const admitted = new Promise<void>((resolve) => {
+ markAdmitted = resolve;
+ });
+ let releaseAdmission = () => {};
+ const admissionGate = new Promise<void>((resolve) => {
+ releaseAdmission = resolve;
+ });
+ let unsubscribe = () => {};
+ unsubscribe = harness.session.agent.subscribe(async (event) => {
+ if (event.type !== "agent_start") return;
+ unsubscribe();
+ markAdmitted();
+ await admissionGate;
+ });
+
+ const delivery = harness.session.waitForAgentMessagePromptDelivery(agentMessageId);
const accepted = harness.session.acceptAgentMessagePrompt(agentPrompt, { expandPromptTemplates: false });
- await admission.reached;
- expect(harness.session.clearQueuedUserMessagesMatching((text) => text.includes("agentmsg_"))).toEqual({
+ const acceptedRejection = expect(accepted).rejects.toThrow("cleared before delivery");
+ const deliveryRejection = expect(delivery).rejects.toThrow("cleared before delivery");
+ await admitted;
+
+ expect(harness.session.clearQueuedUserMessagesMatching((text) => text.includes(agentMessageId))).toEqual({
steering: [],
followUp: [agentPrompt],
});
- admission.release();
- await expect(accepted).rejects.toThrow("cleared before delivery");
+ releaseAdmission();
+ await Promise.all([acceptedRejection, deliveryRejection]);
await harness.session.agent.waitForIdle();
- await (harness.session as unknown as { _agentEventQueue: Promise<void> })._agentEventQueue;
- let sawCustomMessage = false;
+ let sawRestoredNextTurn = false;
harness.setResponses([
(context) => {
- sawCustomMessage = context.messages.some(
- (message) =>
- message.role === "user" &&
- typeof message.content !== "string" &&
- message.content.some((part) => part.type === "text" && part.text === "carry this"),
+ sawRestoredNextTurn = context.messages.some(
+ (message) => message.role === "user" && getMessageText(message) === "carry this",
);
- return fauxAssistantMessage("done");
+ return fauxAssistantMessage("newer response");
},
]);
- await harness.session.prompt("normal prompt");
+ holdAgentStart = false;
+ await harness.session.prompt("newer prompt");
+ releaseEventQueue();
+ await harness.session.waitForIdle();
- expect(sawCustomMessage).toBe(true);
- expect(harness.session.messages.map((message) => message.role)).toEqual(["custom", "user", "assistant"]);
+ expect(sawRestoredNextTurn).toBe(true);
+ expect(getUserTexts(harness)).toEqual(["newer prompt"]);
+ expect(getAssistantTexts(harness)).toEqual(["newer response"]);
+ const deliveredEventTexts = harness.events
+ .filter((event) => event.type === "message_start" || event.type === "message_end")
+ .map((event) => getMessageText(event.message));
+ expect(deliveredEventTexts).not.toContain(agentPrompt);
+ expect(deliveredEventTexts).not.toContain("never delivered");
+ await vi.waitFor(() =>
+ expect(
+ harness.sessionManager
+ .getEntries()
+ .filter((entry) => entry.type === "message")
+ .map((entry) => getMessageText(entry.message)),
+ ).toEqual(["newer prompt", "newer response"]),
+ );
+ expect(harness.session.agent.state.errorMessage).toBeUndefined();
+ expect(harness.session.getAcceptedPromptSnapshot()).toBeUndefined();
+ expect(harness.session.hasAcceptedPromptInFlight).toBe(false);
});
it("restores drained nextTurn messages when direct agent message acceptance fails before delivery", async () => {
diff --git a/packages/coding-agent/test/suite/agent-session-queue.test.ts b/packages/coding-agent/test/suite/agent-session-queue.test.ts
index 9c9e825a83..1cab98badd 100644
--- a/packages/coding-agent/test/suite/agent-session-queue.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-queue.test.ts
@@ -2553,6 +2553,7 @@ describe("AgentSession scheduler scenarios", () => {
firstGate.resolve();
await first.catch(() => undefined);
await harness.session.agent.waitForIdle();
+ await harness.session.waitForSessionInputIdle();
expect(providerCalls).toBe(0);
expect(harness.session.getFollowUpMessages()).toEqual(["queued for restart", "/goal inspect image", agentPrompt]);
expect(harness.session.getFollowUpQueueSnapshots()).toEqual([
diff --git a/packages/coding-agent/test/suite/agent-session-serialized-refine.test.ts b/packages/coding-agent/test/suite/agent-session-serialized-refine.test.ts
index e8c636a553..89009aa61f 100644
--- a/packages/coding-agent/test/suite/agent-session-serialized-refine.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-serialized-refine.test.ts
@@ -25,7 +25,7 @@ type SerializedInternals = {
abort: AbortController,
): Promise<unknown>;
_serializedRefine: boolean;
- _steeringStopPending: boolean;
+ _steeringMessages: unknown[];
_pendingRequestedRefine: { instructions?: string; global?: boolean } | undefined;
_assistantTurnsSinceAutoRefine: number;
_lastAutoRefineReviewAt: number;
@@ -310,7 +310,12 @@ describe("Serialized agent-callable refine", () => {
const internals = harness.session as unknown as SerializedInternals;
const { applyRefine } = mockSerializedRefine(harness);
internals._pendingRequestedRefine = { instructions: "capture a lesson" };
- internals._steeringStopPending = true;
+ internals._steeringMessages.push({
+ kind: "prompt",
+ text: "steer",
+ prefixMessages: [],
+ message: { role: "user", content: "steer" },
+ });
const compactionSpy = vi
.spyOn(
internals as unknown as { _shouldStopForThresholdCompaction: (ctx: unknown) => Promise<boolean> },
@@ -1705,7 +1710,12 @@ describe("P0 concurrency regressions", () => {
});
harnesses.push(harness);
const internals = harness.session as unknown as SerializedInternals;
- internals._steeringStopPending = true;
+ internals._steeringMessages.push({
+ kind: "prompt",
+ text: "steer",
+ prefixMessages: [],
+ message: { role: "user", content: "steer" },
+ });
let planResolved = false;
let applyFinished = false;
diff --git a/packages/coding-agent/test/suite/regressions/4575-model-auth-selection.test.ts b/packages/coding-agent/test/suite/regressions/4575-model-auth-selection.test.ts
index efdf3558e8..cd87112ba6 100644
--- a/packages/coding-agent/test/suite/regressions/4575-model-auth-selection.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4575-model-auth-selection.test.ts
@@ -3,10 +3,6 @@ import stripAnsi from "strip-ansi";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { KeybindingsManager } from "../../../src/core/keybindings.js";
import type { AgentConnectionModel, AgentConnectionModelCatalog } from "../../../src/modes/agent-connection/types.js";
-import {
- getAgentsViewModelArgumentCompletions,
- syncAgentsViewModelMenuAfterAuth,
-} from "../../../src/modes/agents-view/agents-view-mode.js";
import { ModelSelectorComponent } from "../../../src/modes/interactive/components/model-selector.js";
import { InteractiveMode } from "../../../src/modes/interactive/interactive-mode.js";
import { initTheme } from "../../../src/modes/interactive/theme/theme.js";
@@ -202,40 +198,6 @@ describe("ENG-4575 model authentication", () => {
});
});
- test("uses the full public catalog for agents view model autocomplete", async () => {
- const harness = await createHarness({ models: [{ id: "base", name: "Base", reasoning: true }] });
- harnesses.push(harness);
- const publicModel = { ...harness.getModel("base")!, provider: "openai", id: "gpt-5.4" };
- const refreshModelCatalog = vi.fn(async () => ({ models: [publicModel], configuredProviders: [] }));
-
- const completions = await getAgentsViewModelArgumentCompletions("gpt-5.4", { refreshModelCatalog });
-
- expect(refreshModelCatalog).toHaveBeenCalledOnce();
- expect(completions).toContainEqual({
- value: "openai/gpt-5.4",
- label: "gpt-5.4",
- description: "openai",
- });
- });
-
- test("syncs agents view model rows after provider authentication", async () => {
- const harness = await createHarness({ models: [{ id: "base", name: "Base", reasoning: true }] });
- harnesses.push(harness);
- const model = { ...harness.getModel("base")!, provider: "openai" };
- const menu = {
- refreshAuthentication: vi.fn(),
- updateModels: vi.fn(),
- };
-
- syncAgentsViewModelMenuAfterAuth(menu, undefined, {
- models: [model],
- configuredProviders: [model.provider],
- });
-
- expect(menu.refreshAuthentication).toHaveBeenCalledOnce();
- expect(menu.updateModels).toHaveBeenCalledWith(undefined, [model], new Set([model.provider]));
- });
-
test("filters shared model argument completions by provider and model id", () => {
expect(
getModelArgumentCompletions("openai gpt-5.4", [
diff --git a/packages/coding-agent/test/suite/regressions/4645-internal-glm.test.ts b/packages/coding-agent/test/suite/regressions/4645-internal-glm.test.ts
index 3da2dc3042..5a87100a7f 100644
--- a/packages/coding-agent/test/suite/regressions/4645-internal-glm.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4645-internal-glm.test.ts
@@ -4,7 +4,6 @@ import { afterEach, describe, expect, test, vi } from "vitest";
import { AuthStorage } from "../../../src/core/auth-storage.js";
import { ModelRegistry } from "../../../src/core/model-registry.js";
import { findInitialModel, restoreModelFromSession } from "../../../src/core/model-resolver.js";
-import { getAgentsViewModelArgumentCompletions } from "../../../src/modes/agents-view/agents-view-mode.js";
import { createHarness, type Harness } from "../harness.js";
describe("ENG-4645 internal GLM configuration", () => {
@@ -181,32 +180,6 @@ describe("ENG-4645 internal GLM configuration", () => {
expect(fetchMock).toHaveBeenCalledOnce();
});
- test("refreshes private routes for agents view model autocomplete", async () => {
- const harness = await createHarness({ withConfiguredAuth: false });
- harnesses.push(harness);
- const fetchMock = vi.fn(
- async () => new Response(JSON.stringify({ data: [{ id: "internal/glm-5.2-fast" }] }), { status: 200 }),
- );
- vi.stubGlobal("fetch", fetchMock);
- const authStorage = AuthStorage.inMemory({
- "prime-inference": {
- type: "api_key",
- key: "prime-key",
- primeTeam: { teamId: "engineering-team", name: "Prime Engineering" },
- },
- });
- const registry = ModelRegistry.inMemory(authStorage);
-
- const completions = await getAgentsViewModelArgumentCompletions("internal/glm", registry);
-
- expect(completions).toContainEqual({
- value: "prime-inference/internal/glm-5.2-fast",
- label: "internal/glm-5.2-fast",
- description: "prime-inference",
- });
- expect(fetchMock).toHaveBeenCalledOnce();
- });
-
test("refreshes private routes before cycling models", async () => {
const harness = await createHarness();
harnesses.push(harness);
diff --git a/packages/coding-agent/test/suite/regressions/4722-invalid-resume-selector.test.ts b/packages/coding-agent/test/suite/regressions/4722-invalid-resume-selector.test.ts
index a002600ab7..54821b162e 100644
--- a/packages/coding-agent/test/suite/regressions/4722-invalid-resume-selector.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4722-invalid-resume-selector.test.ts
@@ -8,7 +8,6 @@ import {
SessionSelectorNotFoundError,
} from "../../../src/cli/session-resolver.js";
import { SessionManager } from "../../../src/core/session-manager.js";
-import { SettingsManager } from "../../../src/core/settings-manager.js";
import { createSessionManager } from "../../../src/main.js";
import { createHarness, type Harness } from "../harness.js";
@@ -31,9 +30,7 @@ describe("ENG-4722 invalid resume selectors", () => {
const parsed = parseArgs(["--resume", mistypedId, "do not submit this"]);
const sessionDir = join(harness.tempDir, "sessions");
- await expect(
- createSessionManager(parsed, harness.tempDir, sessionDir, SettingsManager.inMemory()),
- ).rejects.toMatchObject({
+ await expect(createSessionManager(parsed, harness.tempDir, sessionDir)).rejects.toMatchObject({
name: SessionSelectorNotFoundError.name,
selector: mistypedId,
suggestion: sessionId,
@@ -55,9 +52,7 @@ describe("ENG-4722 invalid resume selectors", () => {
createSavedSession(harness.tempDir, sessionDir, "11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb");
const parsed = parseArgs(["--resume", "11111111", "do not submit this"]);
- await expect(
- createSessionManager(parsed, harness.tempDir, sessionDir, SettingsManager.inMemory()),
- ).rejects.toMatchObject({
+ await expect(createSessionManager(parsed, harness.tempDir, sessionDir)).rejects.toMatchObject({
name: SessionSelectorAmbiguousError.name,
selector: "11111111",
});
@@ -71,12 +66,7 @@ describe("ENG-4722 invalid resume selectors", () => {
createSavedSession(harness.tempDir, sessionDir, sessionId);
const parsed = parseArgs(["--resume", "aaaaaaaaaaaa"]);
- const sessionManager = await createSessionManager(
- parsed,
- harness.tempDir,
- sessionDir,
- SettingsManager.inMemory(),
- );
+ const sessionManager = await createSessionManager(parsed, harness.tempDir, sessionDir);
expect(sessionManager.getSessionId()).toBe(sessionId);
});
@@ -89,12 +79,7 @@ describe("ENG-4722 invalid resume selectors", () => {
createSavedSession(harness.tempDir, sessionDir, "1abcd");
const parsed = parseArgs(["--resume", "AB-CD"]);
- const sessionManager = await createSessionManager(
- parsed,
- harness.tempDir,
- sessionDir,
- SettingsManager.inMemory(),
- );
+ const sessionManager = await createSessionManager(parsed, harness.tempDir, sessionDir);
expect(sessionManager.getSessionId()).toBe("abcd");
});
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
new file mode 100644
index 0000000000..efff0658ef
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/502-unified-session-view.test.ts
@@ -0,0 +1,472 @@
+import stripAnsi from "strip-ansi";
+import { describe, expect, test, vi } from "vitest";
+import { AgentsViewMode } from "../../../src/modes/agents-view/agents-view-mode.js";
+import type { SessionSummary } from "../../../src/modes/daemon/daemon-session-list.js";
+import { createDeferred as deferred } from "../scheduling.js";
+
+function summary(id: string): SessionSummary {
+ return {
+ id,
+ activeSessionId: id,
+ sessionId: `session-${id}`,
+ lifecycle: "live",
+ activity: "idle",
+ cwd: "/tmp/project",
+ isStreaming: false,
+ isCompacting: false,
+ attachedClients: 0,
+ messageCount: 1,
+ pendingMessageCount: 0,
+ };
+}
+
+function rawSavedSession(id: string) {
+ return {
+ path: `/tmp/${id}.jsonl`,
+ id,
+ cwd: "/tmp/project",
+ state: "idle",
+ created: new Date(0).toISOString(),
+ modified: new Date(0).toISOString(),
+ messageCount: 1,
+ };
+}
+
+function savedSession(id: string) {
+ return { path: `/tmp/${id}.jsonl`, id };
+}
+
+function refreshHarness() {
+ const applySessionList = vi.fn();
+ const reconcileCatalogs = vi.fn();
+ const persistentState: {
+ savedSessions?: unknown[];
+ lastSuccessfulSavedSessions?: unknown[];
+ heartbeats?: unknown[];
+ savedCatalogGeneration?: number;
+ } = {};
+ return {
+ reconnectPromise: undefined,
+ daemonShutdownReceived: false,
+ options: {},
+ liveCatalogGeneration: 0,
+ savedCatalogGeneration: 0,
+ heartbeatCatalogGeneration: 0,
+ liveCatalogRefreshPending: false,
+ savedCatalogRefreshPending: false,
+ heartbeats: [] as unknown[],
+ persistentState,
+ applySessionList,
+ reconcileCatalogs,
+ resolveMissingSelectionAnchor: vi.fn(),
+ setStatusMessage: vi.fn(),
+ startClientReconnect: vi.fn(),
+ };
+}
+
+function privateMethod<T>(name: string): T {
+ const member = Reflect.get(AgentsViewMode.prototype, name) as T;
+ if (typeof member !== "function") {
+ throw new Error(`AgentsViewMode.${name} no longer exists; update this regression harness`);
+ }
+ return member;
+}
+
+describe("#502 unified session view regressions", () => {
+ test.each(["live", "heartbeat"] as const)(
+ "an older overlapping %s poll cannot overwrite the newer response",
+ async (kind) => {
+ const old = deferred<unknown>();
+ const newer = kind === "live" ? summary("new") : { job: { id: "new" } };
+ const client = {
+ isConnected: true,
+ hello: { protocol: { version: 3 } },
+ supportsServerCapability: () => true,
+ request: vi
+ .fn()
+ .mockReturnValueOnce(old.promise)
+ .mockResolvedValueOnce({
+ success: true,
+ data: kind === "live" ? { sessions: [newer] } : { heartbeats: [newer] },
+ }),
+ };
+ const harness = { ...refreshHarness(), requireClient: () => client };
+ const refresh = privateMethod<(this: typeof harness) => Promise<unknown>>(
+ kind === "live" ? "refreshSessions" : "refreshHeartbeats",
+ );
+
+ const oldPoll = refresh.call(harness);
+ await refresh.call(harness);
+ old.resolve({
+ success: true,
+ data: kind === "live" ? { sessions: [summary("old")] } : { heartbeats: [{ job: { id: "old" } }] },
+ });
+ await oldPoll;
+
+ if (kind === "live") expect(harness.applySessionList).toHaveBeenCalledWith([newer]);
+ else expect(harness.heartbeats).toEqual([newer]);
+ expect(kind === "live" ? harness.applySessionList : harness.reconcileCatalogs).toHaveBeenCalledOnce();
+ },
+ );
+
+ test("overlapping saved scans retain the last complete catalog after the newest scan fails", async () => {
+ const previous = [savedSession("previous")];
+ const older = deferred<{ success: true; data: { sessions: unknown[] } }>();
+ const client = {
+ request: vi
+ .fn()
+ .mockReturnValueOnce(older.promise)
+ .mockImplementationOnce(
+ async (
+ _command: unknown,
+ _timeout: unknown,
+ options: { onProgress: (update: { type: string; session: unknown }) => void },
+ ) => {
+ options.onProgress({ type: "session_list_session", session: rawSavedSession("streamed") });
+ throw new Error("scan failed");
+ },
+ ),
+ };
+ const harness = {
+ ...refreshHarness(),
+ savedSessions: previous,
+ lastSuccessfulSavedSessions: previous,
+ requireClient: () => client,
+ getSavedSessionCatalogContext: () => ({ cwd: "/tmp/project" }),
+ };
+ harness.persistentState.savedSessions = previous;
+ const refresh = privateMethod<(this: typeof harness) => Promise<boolean>>("refreshSavedSessions");
+
+ const oldScan = refresh.call(harness);
+ await Promise.resolve();
+ expect(await refresh.call(harness)).toBe(false);
+ older.resolve({ success: true, data: { sessions: [rawSavedSession("stale")] } });
+ expect(await oldScan).toBe(false);
+
+ expect([harness.savedSessions, harness.persistentState.savedSessions]).toEqual([previous, previous]);
+ expect(harness.savedCatalogRefreshPending).toBe(false);
+ });
+
+ test("reconnect retries the saved catalog and fences a stale startup scan", async () => {
+ const previous = [savedSession("previous")];
+ const startup = deferred<{ success: true; data: { sessions: unknown[] } }>();
+ const retried = deferred<{ success: true; data: { sessions: unknown[] } }>();
+ const replacement = savedSession("retried");
+ const client = {
+ request: vi.fn().mockReturnValueOnce(startup.promise).mockReturnValueOnce(retried.promise),
+ };
+ const harness = {
+ ...refreshHarness(),
+ reconnectPromise: undefined as Promise<void> | undefined,
+ savedSessions: previous,
+ lastSuccessfulSavedSessions: previous,
+ requireClient: () => client,
+ getSavedSessionCatalogContext: () => ({ cwd: "/tmp/project" }),
+ };
+ harness.persistentState.savedSessions = previous;
+ const refresh =
+ privateMethod<
+ (
+ this: typeof harness,
+ options?: { duringReconnect?: boolean; preserveStatusOnError?: boolean },
+ ) => Promise<boolean>
+ >("refreshSavedSessions");
+
+ harness.reconnectPromise = undefined;
+ const startupScan = refresh.call(harness);
+ harness.reconnectPromise = Promise.resolve();
+ const retry = refresh.call(harness, { duringReconnect: true, preserveStatusOnError: true });
+ expect(harness.savedCatalogGeneration).toBe(2);
+ expect(harness.persistentState.savedCatalogGeneration).toBe(2);
+
+ retried.resolve({ success: true, data: { sessions: [rawSavedSession("retried")] } });
+ expect(await retry).toBe(true);
+ startup.resolve({ success: true, data: { sessions: [rawSavedSession("stale")] } });
+ expect(await startupScan).toBe(false);
+ expect(harness.savedSessions).toEqual([expect.objectContaining({ path: replacement.path })]);
+ });
+
+ test("failed saved retry during reconnect preserves status and complete catalog", async () => {
+ const previous = [savedSession("previous")];
+ const client = {
+ request: async (
+ _command: unknown,
+ _timeout: unknown,
+ options: { onProgress: (update: { type: string; session: unknown }) => void },
+ ) => {
+ options.onProgress({ type: "session_list_session", session: rawSavedSession("partial") });
+ throw new Error("retry failed");
+ },
+ };
+ const harness = {
+ ...refreshHarness(),
+ reconnectPromise: Promise.resolve(),
+ savedSessions: previous,
+ lastSuccessfulSavedSessions: previous,
+ requireClient: () => client,
+ getSavedSessionCatalogContext: () => ({ cwd: "/tmp/project" }),
+ };
+ harness.persistentState.savedSessions = previous;
+
+ const refreshed = await privateMethod<
+ (
+ this: typeof harness,
+ options: { duringReconnect: boolean; preserveStatusOnError: boolean },
+ ) => Promise<boolean>
+ >("refreshSavedSessions").call(harness, { duringReconnect: true, preserveStatusOnError: false });
+
+ expect(refreshed).toBe(false);
+ expect(harness.savedSessions).toEqual(previous);
+ expect(harness.persistentState.savedSessions).toEqual(previous);
+ expect(harness.setStatusMessage).not.toHaveBeenCalled();
+ });
+
+ test("reconnect stays active until the heartbeat catalog refresh succeeds", async () => {
+ vi.useFakeTimers();
+ try {
+ const firstHeartbeatAttempt = deferred<void>();
+ let heartbeatAttempts = 0;
+ const client = {
+ hello: { protocol: { version: 3 } },
+ supportsServerCapability: () => true,
+ reconnect: vi.fn(async () => {}),
+ request: vi.fn(async (command: { type: string }) => {
+ if (command.type === "list") return { success: true, data: { sessions: [summary("live")] } };
+ heartbeatAttempts += 1;
+ if (heartbeatAttempts === 1) {
+ firstHeartbeatAttempt.resolve();
+ throw new Error("heartbeat connection lost");
+ }
+ return { success: true, data: { heartbeats: [{ job: { id: "healthy" } }] } };
+ }),
+ };
+ const harness = {
+ ...refreshHarness(),
+ stopped: false,
+ reconnectTimedOut: false,
+ client,
+ options: { reconnectTimeoutMs: 10_000 },
+ requireClient: () => client,
+ refreshSavedSessions: vi.fn(async () => true),
+ refreshHeartbeats: vi.fn(async (_options?: { duringReconnect?: boolean }) => false),
+ reconnectClient: vi.fn(async (_reconnectingClient: typeof client, _error: unknown) => {}),
+ };
+ const refreshHeartbeats =
+ privateMethod<(this: typeof harness, options?: { duringReconnect?: boolean }) => Promise<boolean>>(
+ "refreshHeartbeats",
+ );
+ const reconnectClient =
+ privateMethod<(this: typeof harness, reconnectingClient: typeof client, error: unknown) => Promise<void>>(
+ "reconnectClient",
+ );
+ harness.refreshHeartbeats.mockImplementation((options) => refreshHeartbeats.call(harness, options));
+ harness.reconnectClient.mockImplementation((reconnectingClient, error) =>
+ reconnectClient.call(harness, reconnectingClient, error),
+ );
+
+ privateMethod<(this: typeof harness, reconnectingClient: typeof client, error: unknown) => void>(
+ "startClientReconnect",
+ ).call(harness, client, new Error("disconnected"));
+ await firstHeartbeatAttempt.promise;
+ await Promise.resolve();
+
+ expect(harness.reconnectPromise).toBeDefined();
+ expect(harness.applySessionList).not.toHaveBeenCalled();
+ expect(harness.setStatusMessage).not.toHaveBeenCalledWith("Daemon reconnected", { render: false });
+ expect(client.reconnect).toHaveBeenCalledOnce();
+
+ await vi.advanceTimersByTimeAsync(1_000);
+ await harness.reconnectPromise;
+
+ expect(client.reconnect).toHaveBeenCalledTimes(2);
+ expect(harness.applySessionList).toHaveBeenCalledWith([summary("live")]);
+ expect(harness.heartbeats).toEqual([{ job: { id: "healthy" } }]);
+ expect(harness.reconnectPromise).toBeUndefined();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test("a pending saved scan cannot overwrite daemon shutdown status", async () => {
+ const scan = deferred<void>();
+ const client = {
+ request: async () => {
+ await scan.promise;
+ throw new Error("scan failed");
+ },
+ };
+ const harness = {
+ ...refreshHarness(),
+ savedSessions: [],
+ lastSuccessfulSavedSessions: [],
+ requireClient: () => client,
+ getSavedSessionCatalogContext: () => ({ cwd: "/tmp/project" }),
+ };
+
+ const pending = privateMethod<(this: typeof harness) => Promise<boolean>>("refreshSavedSessions").call(harness);
+ harness.daemonShutdownReceived = true;
+ scan.resolve();
+ expect(await pending).toBe(false);
+ expect(harness.setStatusMessage).not.toHaveBeenCalled();
+ });
+
+ test("a missing selection anchor blocks open only until both catalogs settle", () => {
+ const finish = vi.fn();
+ const fallback = summary("fallback");
+ const harness = {
+ selectionAnchorPending: true,
+ liveCatalogRefreshPending: false,
+ savedCatalogRefreshPending: true,
+ selectedIndex: 0,
+ selectedActiveSessionId: undefined as string | undefined,
+ selectedRowIdentity: "identity-intended",
+ rows: [{ selectable: true, kind: "agent", summary: fallback }],
+ isPendingDeleteRow: () => false,
+ setStatusMessage: vi.fn(),
+ finish,
+ };
+
+ privateMethod<(this: typeof harness) => void>("openSelected").call(harness);
+ expect(finish).not.toHaveBeenCalled();
+ privateMethod<(this: typeof harness) => void>("resolveMissingSelectionAnchor").call(harness);
+ expect(harness.selectionAnchorPending).toBe(true);
+ harness.savedCatalogRefreshPending = false;
+ privateMethod<(this: typeof harness) => void>("resolveMissingSelectionAnchor").call(harness);
+ // Open unblocks on the visible fallback row...
+ expect(harness.selectionAnchorPending).toBe(false);
+ expect(harness.selectedActiveSessionId).toBe(fallback.activeSessionId ?? fallback.id);
+ // ...but the restored anchor identity survives so a late poll can still re-anchor.
+ expect(harness.selectedRowIdentity).toBe("identity-intended");
+ });
+ test("rename uses the captured row after refresh removes it", async () => {
+ const captured = summary("captured");
+ const request = vi.fn(async () => ({ success: true, data: {} }));
+ const harness = {
+ renameTarget: { activeSessionId: captured.activeSessionId, summary: captured },
+ rows: [],
+ exitRenameMode: vi.fn(),
+ setStatusMessage: vi.fn(),
+ refreshBothCatalogs: vi.fn(async () => true),
+ requireClient: () => ({ request }),
+ renameSession: Reflect.get(AgentsViewMode.prototype, "renameSession"),
+ };
+
+ await privateMethod<(this: typeof harness, value: string) => Promise<void>>("confirmRename").call(
+ harness,
+ "Renamed",
+ );
+
+ expect(request).toHaveBeenCalledWith({
+ type: "rename",
+ activeSessionId: captured.activeSessionId,
+ name: "Renamed",
+ });
+ });
+
+ test("saved-only delete confirmation remains in the inactive catalog", () => {
+ const savedOnly = { ...summary("saved"), lifecycle: "archived" as const, activeSessionId: undefined };
+ const harness = {
+ pendingDeleteAgent: { identity: "saved", summary: savedOnly, stopped: false },
+ isDeleteConfirmationVisible: () => true,
+ };
+
+ expect(
+ privateMethod<(this: typeof harness, sessions: SessionSummary[]) => SessionSummary[]>(
+ "withPendingDeleteSession",
+ ).call(harness, []),
+ ).toEqual([]);
+ });
+
+ test("slow live polls are coalesced instead of repeatedly superseded", async () => {
+ const slow = deferred<boolean>();
+ const refreshSessions = vi.fn(() => slow.promise);
+ const harness = { liveCatalogPollPromise: undefined, refreshSessions };
+ const poll = privateMethod<(this: typeof harness) => void>("pollSessions");
+
+ poll.call(harness);
+ poll.call(harness);
+ expect(refreshSessions).toHaveBeenCalledOnce();
+ slow.resolve(true);
+ await slow.promise;
+ await Promise.resolve();
+ poll.call(harness);
+ expect(refreshSessions).toHaveBeenCalledTimes(2);
+ });
+
+ test.each([
+ { mode: "search", prompt: ["prompt top", "prompt input", "prompt bottom"] },
+ { mode: "reply", prompt: ["prompt top", "reply header", "reply gap", "prompt input", "prompt bottom"] },
+ ])("short content reserves the $mode editor and a session row ahead of startup chrome", ({ prompt }) => {
+ const renderSessionRows = vi.fn(() => ["session row"]);
+ const harness = {
+ splash: { render: () => Array.from({ length: 8 }, () => "splash") },
+ renderStartupNotices: () => Array.from({ length: 8 }, () => "notice"),
+ renderPrompt: () => prompt,
+ renderSessionRows,
+ };
+ const height = prompt.length + 2;
+
+ const lines = privateMethod<(this: typeof harness, width: number, height: number) => string[]>(
+ "renderContent",
+ ).call(harness, 80, height);
+
+ expect(lines).toHaveLength(height);
+ expect(lines).toEqual(expect.arrayContaining([...prompt, "session row"]));
+ expect(renderSessionRows).toHaveBeenCalledWith(80, 1);
+ });
+
+ test.each(["reply", "rename"] as const)("%s refresh keeps the captured search filter", (mode) => {
+ const harness = {
+ replyTarget: mode === "reply" ? { key: "active", summary: {} } : undefined,
+ renameTarget: mode === "rename" ? { identity: "target" } : undefined,
+ actionModeSearchQuery: "needle",
+ editor: { getText: () => "action editor text" },
+ unifiedRecords: [
+ { identity: "match", identityAliases: [], section: "idle", searchableText: "needle session" },
+ { identity: "other", identityAliases: [], section: "idle", searchableText: "other session" },
+ ],
+ };
+
+ const filtered =
+ privateMethod<(this: typeof harness) => Array<{ identity: string }>>("getFilteredRecords").call(harness);
+ expect(filtered.map((record) => record.identity)).toEqual(["match"]);
+ });
+
+ test("inactive rows give message count and age their full responsive cell", () => {
+ const inactive = {
+ kind: "agent" as const,
+ section: "inactive" as const,
+ summary: {
+ ...summary("archived"),
+ activeSessionId: undefined,
+ lifecycle: "archived" as const,
+ messageCount: 123456,
+ modified: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
+ },
+ title: "archived",
+ subtitle: "",
+ statusLabel: "inactive",
+ depth: 0,
+ selectable: true,
+ runningSubagentCount: 0,
+ identity: "archived",
+ };
+ const harness = {
+ rows: [inactive],
+ selectedIndex: 0,
+ isPendingDeleteRow: () => false,
+ isPendingKillSubagentRow: () => false,
+ getRowIcon: () => "x",
+ formatRowIcon: (_section: string, icon: string) => icon,
+ };
+
+ const rendered = stripAnsi(
+ privateMethod<(this: typeof harness, row: typeof inactive, width: number) => string>("renderRow").call(
+ harness,
+ inactive,
+ 50,
+ ),
+ );
+ expect(rendered).toMatch(/123456 · 2h\s*$/);
+ });
+});
diff --git a/packages/coding-agent/test/user-message.test.ts b/packages/coding-agent/test/user-message.test.ts
index 60a7181348..602dcaa62e 100644
--- a/packages/coding-agent/test/user-message.test.ts
+++ b/packages/coding-agent/test/user-message.test.ts
@@ -1,7 +1,7 @@
-import { clearDefaultTerminalColors, setDefaultTerminalColors } from "@earendil-works/pi-tui";
+import { clearDefaultTerminalColors, setDefaultTerminalColors, visibleWidth } from "@earendil-works/pi-tui";
import { afterEach, describe, expect, test } from "vitest";
import { UserMessageComponent } from "../src/modes/interactive/components/user-message.js";
-import { initTheme } from "../src/modes/interactive/theme/theme.js";
+import { initTheme, theme } from "../src/modes/interactive/theme/theme.js";
const OSC133_ZONE_START = "\x1b]133;A\x07";
const OSC133_ZONE_END = "\x1b]133;B\x07";
@@ -42,4 +42,58 @@ describe("UserMessageComponent", () => {
expect(lines[0].endsWith(BG_RESET)).toBe(true);
expect(lines[2].endsWith(BG_RESET)).toBe(true);
});
+
+ test("colors only recognized leading slash commands", () => {
+ clearDefaultTerminalColors();
+ initTheme("dark");
+ const recognized = (name: string) => name === "compact";
+
+ const command = new UserMessageComponent("/compact focus on **errors**", undefined, recognized)
+ .render(40)
+ .join("\n");
+ const unknown = new UserMessageComponent("/unknown focus here", undefined, recognized).render(40).join("\n");
+ const embedded = new UserMessageComponent("Explain /compact", undefined, recognized).render(40).join("\n");
+
+ expect(command).toContain(theme.fg("accent", "/compact"));
+ expect(command).not.toContain("**errors**");
+ expect(command).not.toBe(unknown);
+ expect(unknown).not.toContain(theme.fg("accent", "/unknown"));
+ expect(embedded).not.toContain(theme.fg("accent", "/compact"));
+ });
+
+ test.each([
+ {
+ name: "wide and multi-code-point command graphemes",
+ message: "/命é令 arg **bold**",
+ commandName: "命é令",
+ expectedLines: ["", "/命é", "令", "arg", "bold", ""],
+ },
+ {
+ name: "width-three command graphemes atomically",
+ message: "/界゙x arg",
+ commandName: "界゙x",
+ expectedLines: ["", "/界゙", "x", "arg", ""],
+ },
+ ])("wraps $name at terminal width", ({ message, commandName, expectedLines }) => {
+ initTheme("dark");
+ const lines = new UserMessageComponent(message, undefined, (name) => name === commandName).render(8);
+ const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m|\x1b\]133;[ABC]\x07/g, "").trim());
+
+ expect(lines.every((line) => visibleWidth(line) === 8)).toBe(true);
+ expect(plainLines).toEqual(expectedLines);
+ });
+
+ test("preserves mask-like argument text across narrow wraps", () => {
+ initTheme("dark");
+ const command = "/averyveryverylongcommand";
+ const lines = new UserMessageComponent(
+ `${command} 界\uE000`,
+ undefined,
+ (name) => name === command.slice(1),
+ ).render(8);
+ const plain = lines.join("\n").replace(/\x1b\[[0-9;]*m|\x1b\]133;[ABC]\x07/g, "");
+
+ expect(plain.replace(/\s+/g, "")).toContain(`${command}界\uE000`);
+ expect(lines.every((line) => visibleWidth(line) === 8)).toBe(true);
+ });
});