Skip to content

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

Rust

unify session state and remove the deferred-agent path (#269)

kt8d4a1e116557
diff --git a/packages/coding-agent/src/cli/daemon-command.ts b/packages/coding-agent/src/cli/daemon-command.ts
index e0ca153b61..ae8ed4a006 100644
--- a/packages/coding-agent/src/cli/daemon-command.ts
+++ b/packages/coding-agent/src/cli/daemon-command.ts
@@ -1416,7 +1416,8 @@ function isSessionSummary(value: unknown): value is SessionSummary {
typeof candidate.id === "string" &&
typeof candidate.sessionId === "string" &&
typeof candidate.cwd === "string" &&
- typeof candidate.status === "string" &&
+ typeof candidate.lifecycle === "string" &&
+ typeof candidate.activity === "string" &&
typeof candidate.isStreaming === "boolean" &&
typeof candidate.isCompacting === "boolean" &&
typeof candidate.attachedClients === "number" &&
diff --git a/packages/coding-agent/src/cli/daemon-list-format.ts b/packages/coding-agent/src/cli/daemon-list-format.ts
index fc0479c58d..59e91e0107 100644
--- a/packages/coding-agent/src/cli/daemon-list-format.ts
+++ b/packages/coding-agent/src/cli/daemon-list-format.ts
@@ -1,21 +1,27 @@
import chalk from "chalk";
import { formatSessionDisplayId } from "../modes/daemon/daemon-session-id.js";
-import type { SessionStatus, SessionSummary } from "../modes/daemon/daemon-session-list.js";
+import type { SessionSummary } from "../modes/daemon/daemon-session-list.js";
-const LIST_STATUS_ORDER: Record<SessionStatus, number> = {
- user: 0,
+// Display status derived from the lifecycle + activity axes.
+type ListStatus = "working" | "idle" | "archived";
+
+const LIST_STATUS_ORDER: Record<ListStatus, number> = {
+ working: 0,
idle: 1,
- tool: 2,
- model: 3,
- active: 4,
- sleep: 5,
- crash: 6,
+ archived: 2,
};
+function listStatusForSummary(summary: SessionSummary): ListStatus {
+ if (summary.lifecycle === "archived") {
+ return "archived";
+ }
+ return summary.activity === "working" ? "working" : "idle";
+}
+
type ListRow = {
name: string;
id: string;
- status: SessionStatus;
+ status: ListStatus;
age: string;
model: string;
messages: string;
@@ -26,7 +32,7 @@ export function formatSessionListTable(sessions: readonly SessionSummary[], nowM
const rows = sortSessionsForList(sessions).map((session) => ({
name: session.sessionName ?? "",
id: formatSessionDisplayId(session.id),
- status: session.status,
+ status: listStatusForSummary(session),
age: formatSessionAge(session.modified, nowMs),
model: formatSessionModel(session.model),
messages: String(session.messageCount),
@@ -39,7 +45,9 @@ function sortSessionsForList(sessions: readonly SessionSummary[]): SessionSummar
return sessions
.map((session, index) => ({ session, index }))
.sort((left, right) => {
- const statusDelta = LIST_STATUS_ORDER[left.session.status] - LIST_STATUS_ORDER[right.session.status];
+ const statusDelta =
+ LIST_STATUS_ORDER[listStatusForSummary(left.session)] -
+ LIST_STATUS_ORDER[listStatusForSummary(right.session)];
return statusDelta || left.index - right.index;
})
.map(({ session }) => session);
@@ -51,15 +59,11 @@ function formatListCell(row: ListRow, column: keyof ListRow, value: string): str
}
switch (row.status) {
- case "tool":
- case "model":
+ case "working":
return chalk.red(value);
- case "user":
case "idle":
return chalk.blue(value);
- case "active":
- case "sleep":
- case "crash":
+ case "archived":
return chalk.dim(value);
}
}
diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.ts
index 59c37c4bb8..5da24d1b33 100644
--- a/packages/coding-agent/src/core/session-manager.ts
+++ b/packages/coding-agent/src/core/session-manager.ts
@@ -32,6 +32,21 @@ const SESSION_LIST_SEARCH_TEXT_MAX_CHARS = 64 * 1024;
const SESSION_LIST_PARSE_MAX_LINE_CHARS = 1024 * 1024;
const SESSION_LIST_LARGE_MESSAGE_PREVIEW_MAX_CHARS = 256;
+// Entry types that can represent user intent (vs. daemon bookkeeping like
+// session_state/agent_status/git_state/child_usage_attributed). Used by
+// hasUserContent to decide whether a message-less draft is safe to discard.
+const CONTENT_ENTRY_TYPES = new Set([
+ "message",
+ "custom_message",
+ "custom",
+ "model_change",
+ "thinking_level_change",
+ "session_info",
+ "label",
+ "compaction",
+ "branch_summary",
+]);
+
export interface SessionHeader {
type: "session";
version?: number; // v1 sessions don't have this
@@ -138,7 +153,9 @@ export interface SessionInfoEntry extends SessionEntryBase {
name?: string;
}
-export type SessionStateStatus = "active" | "sleep" | "crash";
+// On-disk lifecycle. "archived" replaces legacy "sleep" (normalized on read).
+// "crash" is read-only back-compat; no longer written.
+export type SessionStateStatus = "active" | "archived" | "crash";
export interface SessionState {
status: SessionStateStatus;
@@ -244,6 +261,8 @@ export interface SessionInfo {
messageCount: number;
firstMessage: string;
allMessagesText: string;
+ /** Latest persisted recap/verdict, so off-daemon sessions keep their status. */
+ agentStatus?: AgentStatus;
}
export type ReadonlySessionManager = Pick<
@@ -699,13 +718,14 @@ function extractTextContent(message: Message): string {
.join(" ");
}
-// Legacy "hidden" status is coerced to "sleep" for sessions written by older versions.
+// Legacy "hidden" and "sleep" statuses (written by older versions) both map to
+// the current "archived".
function normalizeSessionStateStatus(value: unknown): SessionStateStatus | undefined {
- if (value === "active" || value === "sleep" || value === "crash") {
+ if (value === "active" || value === "archived" || value === "crash") {
return value;
}
- if (value === "hidden") {
- return "sleep";
+ if (value === "hidden" || value === "sleep") {
+ return "archived";
}
return undefined;
}
@@ -868,6 +888,7 @@ async function scanSessionInfo(filePath: string, stats: Awaited<ReturnType<typeo
let allMessagesText = "";
let name: string | undefined;
let state: SessionState | undefined;
+ let agentStatus: AgentStatus | undefined;
let lastActivityTime: number | undefined;
for await (const line of lines) {
@@ -911,6 +932,11 @@ async function scanSessionInfo(filePath: string, stats: Awaited<ReturnType<typeo
state = { status };
}
}
+ // Keep the latest recap/verdict so off-daemon sessions don't all show as
+ // unjudged in the agents view. Append-only, so last seen wins.
+ if (entry.type === "agent_status") {
+ agentStatus = (entry as AgentStatusEntry).status;
+ }
if (!header) {
if (entry.type !== "session") {
@@ -954,6 +980,7 @@ async function scanSessionInfo(filePath: string, stats: Awaited<ReturnType<typeo
messageCount,
firstMessage: firstMessage || "(no messages)",
allMessagesText,
+ agentStatus,
};
} catch {
return null;
@@ -1387,6 +1414,29 @@ export class SessionManager {
return undefined;
}
+ /**
+ * True when the session holds user-meaningful persisted content, as opposed to
+ * only daemon-written bookkeeping (session_state, agent_status, git_state) or
+ * the default model/thinking entries every new session is created with. Used by
+ * the daemon discard guard to decide whether a message-less draft is safe to
+ * delete (that guard always also requires zero messages).
+ *
+ * createAgentSession opens a new session with an optional leading `model_change`
+ * (only when a model is available) followed by `thinking_level_change`. That
+ * creation prefix is skipped; anything beyond it is user content.
+ */
+ hasUserContent(): boolean {
+ const contentEntries = this.getEntries().filter((entry) => CONTENT_ENTRY_TYPES.has(entry.type));
+ let start = 0;
+ if (contentEntries[start]?.type === "model_change") {
+ start++;
+ }
+ if (contentEntries[start]?.type === "thinking_level_change") {
+ start++;
+ }
+ return contentEntries.length > start;
+ }
+
/** Append the latest agent status (summary + completion judgment). Returns entry id. */
appendAgentStatus(status: AgentStatus): string {
const entry: AgentStatusEntry = {
diff --git a/packages/coding-agent/src/index.ts b/packages/coding-agent/src/index.ts
index 771bb74b74..749baa0a88 100644
--- a/packages/coding-agent/src/index.ts
+++ b/packages/coding-agent/src/index.ts
@@ -328,7 +328,8 @@ export {
type RpcSessionState,
runPrintMode,
runRpcMode,
- type SessionStatus,
+ type SessionActivity,
+ type SessionLifecycle,
type SessionSummary,
} from "./modes/index.js";
// UI components for extensions
diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.ts
index 98f1b3d62a..5525628f93 100644
--- a/packages/coding-agent/src/main.ts
+++ b/packages/coding-agent/src/main.ts
@@ -59,7 +59,6 @@ import {
createInteractiveModeUiServicesFromServices,
DaemonAgentConnection,
DaemonClient,
- DeferredAgentConnection,
defaultDaemonSocketPath,
InProcessAgentConnection,
InteractiveMode,
@@ -887,40 +886,6 @@ async function findActiveDaemonSessionSummary(
}
}
-// Best-effort: kill a promoted session that never received a message so abandoned
-// new-chats don't linger in the agents view. Any failure leaves it in place.
-async function discardEmptyDaemonSession(socketPath: string, activeSessionId: string): Promise<void> {
- const client = new DaemonClient(socketPath);
- try {
- await client.connect(250);
- } catch {
- return;
- }
- try {
- const state = await client.request({ type: "get_state", activeSessionId }, 3000);
- if (!state.success || !isDaemonSessionSummary(state.data)) {
- return;
- }
- const summary = state.data;
- // Keep the session if it holds any work: messages, a queued/streaming turn,
- // an in-progress compaction, or a running user bash command.
- if (
- summary.messageCount > 0 ||
- summary.pendingMessageCount > 0 ||
- summary.isStreaming ||
- summary.isCompacting ||
- summary.isBashRunning
- ) {
- return;
- }
- await client.request({ type: "kill", activeSessionId }, 3000);
- } catch {
- // Best-effort cleanup; leave the session in place on any error.
- } finally {
- client.close();
- }
-}
-
async function normalizeDaemonRichTuiAttachArgs(args: string[]): Promise<string[] | undefined> {
const shortcut = parseDaemonRichTuiAttachShortcut(args);
if (!shortcut) {
@@ -1364,55 +1329,23 @@ export async function main(args: string[], options?: MainOptions) {
}
daemonReady = (await awaitDaemonReady(daemonReady)).ready;
- // No attach and no session selector means a fresh default chat. Defer the
- // daemon session until the first action so startup is instant and leaving
- // straight to the agents view (or quitting) creates nothing to clean up.
+ // A fresh default chat opens a real but message-less session; the lifecycle
+ // axis treats it as a draft (hidden, discarded on detach if never used), so
+ // no DeferredAgentConnection is needed to avoid creating it up front.
const isFreshDefaultSession =
!activeDaemonSessionSummary && !getInteractiveDaemonSessionPath(parsed, sessionManager);
- let agentConnection: AgentConnection;
- let attachModelFallbackMessage: string | undefined;
- if (isFreshDefaultSession) {
- agentConnection = new DeferredAgentConnection(
- async () => {
- const created = await createDaemonInteractiveConnection({
- socketPath: daemonSocketPath,
- config: defaultSessionConfig,
- });
- return {
- connection: created.connection,
- activeSessionId: getDaemonSummaryActiveSessionId(created.summary),
- };
- },
- {
- cwd: sessionManager.getCwd(),
- sessionDir,
- model: startupModel.model,
- thinkingLevel: prepared.sessionOptions.thinkingLevel ?? defaultSessionConfig.thinking ?? "off",
- scopedModels: prepared.sessionOptions.scopedModels ?? [],
- availableModels: () => services.modelRegistry.getAvailable(),
- steeringMode: settingsManager.getSteeringMode(),
- followUpMode: settingsManager.getFollowUpMode(),
- autoCompactionEnabled: settingsManager.getCompactionEnabled(),
- },
- (activeSessionId) => discardEmptyDaemonSession(daemonSocketPath, activeSessionId),
- );
- // The deferred path only ever fresh-creates with this same config, so the
- // startup resolution is authoritative — there is no attached session whose
- // summary could carry a different fallback (resolveAttachModelFallbackMessage
- // only matters when attaching to an existing session).
- attachModelFallbackMessage = startupModel.modelFallbackMessage;
- } else {
- const { connection, summary } = await createDaemonInteractiveConnection({
- socketPath: daemonSocketPath,
- config: defaultSessionConfig,
- activeSessionId: activeDaemonSessionSummary
- ? getDaemonSummaryActiveSessionId(activeDaemonSessionSummary)
- : undefined,
- sessionPath: getInteractiveDaemonSessionPath(parsed, sessionManager),
- });
- agentConnection = connection;
- attachModelFallbackMessage = resolveAttachModelFallbackMessage(summary, startupModel.modelFallbackMessage);
- }
+ const { connection, summary } = await createDaemonInteractiveConnection({
+ socketPath: daemonSocketPath,
+ config: defaultSessionConfig,
+ activeSessionId: activeDaemonSessionSummary
+ ? getDaemonSummaryActiveSessionId(activeDaemonSessionSummary)
+ : undefined,
+ sessionPath: getInteractiveDaemonSessionPath(parsed, sessionManager),
+ });
+ const agentConnection: AgentConnection = connection;
+ const attachModelFallbackMessage = isFreshDefaultSession
+ ? startupModel.modelFallbackMessage
+ : resolveAttachModelFallbackMessage(summary, startupModel.modelFallbackMessage);
const interactiveMode = new InteractiveMode({
agentConnection,
diff --git a/packages/coding-agent/src/modes/agent-connection/deferred-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/deferred-agent-connection.ts
deleted file mode 100644
index f237e2abb8..0000000000
--- a/packages/coding-agent/src/modes/agent-connection/deferred-agent-connection.ts
+++ /dev/null
@@ -1,534 +0,0 @@
-import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";
-import { getSupportedThinkingLevels, type ImageContent, type Transport } from "@earendil-works/pi-ai";
-import type { CompactionResult } from "../../core/compaction/index.js";
-import type { ContextTreeNode } from "../../core/context-tree.js";
-import type { AgentCronJob, AgentHeartbeatUpdateAction } from "../../core/cron-jobs.js";
-import { emptyGoalState } from "../../core/goals.js";
-import type { RefinementResult } from "../../core/refinement/index.js";
-import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";
-import { SessionManager } from "../../core/session-manager.js";
-import type { SessionStats } from "../../core/session-stats.js";
-import { emptyUsage } from "../../core/usage.js";
-import type {
- AgentConnection,
- AgentConnectionBeforeSessionInvalidateListener,
- AgentConnectionEvent,
- AgentConnectionEventListener,
- AgentConnectionExecuteBashOptions,
- AgentConnectionExtensionUiResponse,
- AgentConnectionForkOptions,
- AgentConnectionModel,
- AgentConnectionModelCycleResult,
- AgentConnectionNavigateTreeOptions,
- AgentConnectionNavigateTreeResult,
- AgentConnectionNewSessionOptions,
- AgentConnectionPromptOptions,
- AgentConnectionQueueMode,
- AgentConnectionQueueState,
- AgentConnectionResourceSnapshot,
- AgentConnectionSavedSessionInfo,
- AgentConnectionSavedSessionScope,
- AgentConnectionScopedModel,
- AgentConnectionSessionContext,
- AgentConnectionSessionListProgress,
- AgentConnectionSessionTreeNode,
- AgentConnectionSlashCommand,
- AgentConnectionSnapshot,
- AgentConnectionState,
- AgentConnectionSwitchSessionOptions,
- AgentConnectionToolDefinition,
- AgentConnectionUserMessage,
-} from "./types.js";
-
-/** Local data used to render the chat before a session exists. */
-export interface DeferredAgentConnectionSeed {
- cwd: string;
- sessionDir?: string;
- model?: AgentConnectionModel;
- thinkingLevel: ThinkingLevel;
- scopedModels: AgentConnectionScopedModel[];
- availableModels: () => AgentConnectionModel[];
- steeringMode: AgentConnectionQueueMode;
- followUpMode: AgentConnectionQueueMode;
- autoCompactionEnabled: boolean;
-}
-
-function emptyResourceSnapshot(): AgentConnectionResourceSnapshot {
- return {
- contextFiles: [],
- skills: [],
- prompts: [],
- extensions: [],
- themes: [],
- diagnostics: { skills: [], prompts: [], extensions: [], themes: [] },
- };
-}
-
-/**
- * Opens the chat instantly by serving local catalog data, and only creates the
- * real daemon session on the first action (a prompt, model change, etc.). Until
- * then nothing is created, so pressing left to the agents view — or quitting —
- * costs nothing. On creation it pipes the real connection's events through and
- * emits one session_replaced so the UI rebinds to the live catalog.
- */
-export class DeferredAgentConnection implements AgentConnection {
- private readonly listeners = new Set<AgentConnectionEventListener>();
- private readonly beforeInvalidateListeners = new Set<AgentConnectionBeforeSessionInvalidateListener>();
- private readonly beforeInvalidateRealUnsubs = new Map<AgentConnectionBeforeSessionInvalidateListener, () => void>();
- private real: AgentConnection | undefined;
- private realUnsub: (() => void) | undefined;
- private promotion: Promise<AgentConnection> | undefined;
- private promotedActiveSessionId: string | undefined;
- private disposed = false;
-
- constructor(
- // Creates the real session and returns its connection plus the daemon
- // activeSessionId, so the id is known even if a later setup step fails.
- private readonly factory: () => Promise<{ connection: AgentConnection; activeSessionId: string }>,
- private readonly seed: DeferredAgentConnectionSeed,
- // Called with a promoted session id so the caller can drop it if it was
- // created but never used (e.g. cycled the model then left, or setup failed).
- private readonly discardEmptySession?: (activeSessionId: string) => Promise<void>,
- ) {}
-
- /** True once the real session has been created. */
- get created(): boolean {
- return this.real !== undefined;
- }
-
- subscribe(listener: AgentConnectionEventListener): () => void {
- this.listeners.add(listener);
- return () => {
- this.listeners.delete(listener);
- };
- }
-
- onBeforeSessionInvalidate(listener: AgentConnectionBeforeSessionInvalidateListener): () => void {
- if (this.real) {
- return this.real.onBeforeSessionInvalidate(listener);
- }
- this.beforeInvalidateListeners.add(listener);
- // Unsubscribe must work whether called before or after promotion forwards
- // the listener to the real connection.
- return () => {
- this.beforeInvalidateListeners.delete(listener);
- this.beforeInvalidateRealUnsubs.get(listener)?.();
- this.beforeInvalidateRealUnsubs.delete(listener);
- };
- }
-
- private emit(event: AgentConnectionEvent): void {
- for (const listener of [...this.listeners]) {
- void listener(event);
- }
- }
-
- private async emitAndWait(event: AgentConnectionEvent): Promise<void> {
- await Promise.allSettled([...this.listeners].map((listener) => Promise.resolve().then(() => listener(event))));
- }
-
- private ensure(): Promise<AgentConnection> {
- if (this.real) {
- return Promise.resolve(this.real);
- }
- if (!this.promotion) {
- // Drop a failed attempt so a later action can retry instead of replaying
- // the same rejection forever.
- this.promotion = this.promote().catch((error) => {
- this.promotion = undefined;
- throw error;
- });
- }
- return this.promotion;
- }
-
- private async promote(): Promise<AgentConnection> {
- const { connection: real, activeSessionId } = await this.factory();
- // dispose() may have run, or a setup step may throw. In any of those cases
- // tear down the client AND drop the daemon session the factory just created,
- // so a failed/cancelled promotion never commits half-state or orphans an
- // empty agent (and retries can't pile more up).
- try {
- if (this.disposed) {
- throw new Error("Deferred connection disposed before promotion completed");
- }
- const [state, messages] = await Promise.all([real.getState(), real.getMessages()]);
- if (this.disposed) {
- throw new Error("Deferred connection disposed before promotion completed");
- }
- this.real = real;
- this.promotedActiveSessionId = activeSessionId;
- this.realUnsub = real.subscribe((event) => this.emit(event));
- // Clear the buffer only after wiring succeeds, so a throw here keeps the
- // listeners for a retry.
- for (const listener of this.beforeInvalidateListeners) {
- this.beforeInvalidateRealUnsubs.set(listener, real.onBeforeSessionInvalidate(listener));
- }
- this.beforeInvalidateListeners.clear();
- // Wait for the UI to rebind to the (empty) real session before the caller's
- // action runs, so the action's own events aren't double-rendered against a
- // concurrent full re-render.
- await this.emitAndWait({ type: "session_replaced", state, messages });
- return real;
- } catch (error) {
- await real.dispose().catch(() => undefined);
- await this.discardEmptySession?.(activeSessionId).catch(() => undefined);
- // Roll back a partial commit so ensure() retries instead of short-circuiting
- // to this disposed connection.
- if (this.real === real) {
- this.realUnsub = undefined;
- this.real = undefined;
- this.promotedActiveSessionId = undefined;
- }
- throw error;
- }
- }
-
- private defaultState(): AgentConnectionState {
- return {
- cwd: this.seed.cwd,
- model: this.seed.model,
- thinkingLevel: this.seed.thinkingLevel,
- availableThinkingLevels: this.seed.model
- ? (getSupportedThinkingLevels(this.seed.model) as ThinkingLevel[])
- : [],
- isStreaming: false,
- isCompacting: false,
- isBashRunning: false,
- retryAttempt: 0,
- steeringMode: this.seed.steeringMode,
- followUpMode: this.seed.followUpMode,
- sessionId: "",
- sessionDir: this.seed.sessionDir,
- leafId: null,
- autoCompactionEnabled: this.seed.autoCompactionEnabled,
- messageCount: 0,
- pendingMessageCount: 0,
- compactionCount: 0,
- goal: emptyGoalState(),
- scopedModels: this.seed.scopedModels,
- activeToolNames: [],
- contextUsage: undefined,
- };
- }
-
- async getState(): Promise<AgentConnectionState> {
- return this.real ? this.real.getState() : this.defaultState();
- }
-
- async getInitialSnapshot(): Promise<AgentConnectionSnapshot> {
- if (this.real) {
- return this.real.getInitialSnapshot();
- }
- return { state: this.defaultState(), messages: [], sessionTree: { tree: [], leafId: null } };
- }
-
- async getMessages(): Promise<AgentMessage[]> {
- return this.real ? this.real.getMessages() : [];
- }
-
- // Extension/skill commands and resources are session-scoped, so they stay
- // empty until promotion; builtin slash commands work meanwhile, and the
- // session_replaced on first action repopulates the catalog.
- async getCommands(): Promise<AgentConnectionSlashCommand[]> {
- return this.real ? this.real.getCommands() : [];
- }
-
- async getResourceSnapshot(): Promise<AgentConnectionResourceSnapshot> {
- return this.real ? this.real.getResourceSnapshot() : emptyResourceSnapshot();
- }
-
- async getAvailableModels(): Promise<AgentConnectionModel[]> {
- return this.real ? this.real.getAvailableModels() : this.seed.availableModels();
- }
-
- async getSessionStats(): Promise<SessionStats> {
- if (this.real) {
- return this.real.getSessionStats();
- }
- return {
- sessionFile: undefined,
- sessionId: "",
- userMessages: 0,
- assistantMessages: 0,
- toolCalls: 0,
- toolResults: 0,
- totalMessages: 0,
- tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
- cost: 0,
- };
- }
-
- async getContextTree(): Promise<ContextTreeNode> {
- if (this.real) {
- return this.real.getContextTree();
- }
- return {
- id: "root",
- label: "",
- status: "active",
- ownUsage: emptyUsage(),
- totalUsage: emptyUsage(),
- children: [],
- };
- }
-
- async getSessionContext(): Promise<AgentConnectionSessionContext> {
- if (this.real) {
- return this.real.getSessionContext();
- }
- return {
- messages: [],
- thinkingLevel: this.seed.thinkingLevel,
- model: this.seed.model ? { provider: this.seed.model.provider, modelId: this.seed.model.id } : null,
- };
- }
-
- async getSessionTree(): Promise<{ tree: AgentConnectionSessionTreeNode[]; leafId: string | null }> {
- return this.real ? this.real.getSessionTree() : { tree: [], leafId: null };
- }
-
- async listSavedSessions(
- scope: AgentConnectionSavedSessionScope,
- onProgress?: AgentConnectionSessionListProgress,
- ): Promise<AgentConnectionSavedSessionInfo[]> {
- if (this.real) {
- return this.real.listSavedSessions(scope, onProgress);
- }
- // Saved sessions live on disk, so the resume picker works without a session.
- return scope === "current"
- ? SessionManager.list(this.seed.cwd, this.seed.sessionDir, onProgress)
- : SessionManager.listAll(onProgress, this.seed.sessionDir);
- }
-
- async getQueue(): Promise<AgentConnectionQueueState> {
- return this.real ? this.real.getQueue() : { steering: [], followUp: [] };
- }
-
- async clearQueue(): Promise<AgentConnectionQueueState> {
- return this.real ? this.real.clearQueue() : { steering: [], followUp: [] };
- }
-
- async listCronJobs(options?: { includeInactive?: boolean }): Promise<AgentCronJob[]> {
- return this.real ? this.real.listCronJobs(options) : [];
- }
-
- async getHeartbeat(): Promise<AgentCronJob | undefined> {
- return this.real ? this.real.getHeartbeat() : undefined;
- }
-
- async getUserMessagesForForking(): Promise<AgentConnectionUserMessage[]> {
- return this.real ? this.real.getUserMessagesForForking() : [];
- }
-
- async getLastAssistantText(): Promise<string | undefined> {
- return this.real ? this.real.getLastAssistantText() : undefined;
- }
-
- async getSystemPrompt(): Promise<string> {
- return this.real ? this.real.getSystemPrompt() : "";
- }
-
- async getToolDefinition(name: string): Promise<AgentConnectionToolDefinition | undefined> {
- return this.real ? this.real.getToolDefinition(name) : undefined;
- }
-
- async setSessionEntryLabel(entryId: string, label: string | undefined): Promise<void> {
- return (await this.ensure()).setSessionEntryLabel(entryId, label);
- }
-
- async respondToExtensionUiRequest(requestId: string, response: AgentConnectionExtensionUiResponse): Promise<void> {
- if (this.real) {
- await this.real.respondToExtensionUiRequest(requestId, response);
- }
- }
-
- async prompt(message: string, options?: AgentConnectionPromptOptions): Promise<void> {
- return (await this.ensure()).prompt(message, options);
- }
-
- async steer(message: string, images?: ImageContent[]): Promise<void> {
- return (await this.ensure()).steer(message, images);
- }
-
- async followUp(message: string, images?: ImageContent[]): Promise<void> {
- return (await this.ensure()).followUp(message, images);
- }
-
- async abort(): Promise<void> {
- if (this.real) {
- await this.real.abort();
- }
- }
-
- async cancelRlmChild(childId: string): Promise<boolean> {
- return this.real ? this.real.cancelRlmChild(childId) : false;
- }
-
- async waitForIdle(): Promise<void> {
- if (this.real) {
- await this.real.waitForIdle();
- }
- }
-
- async executeBash(command: string, options?: AgentConnectionExecuteBashOptions): Promise<void> {
- return (await this.ensure()).executeBash(command, options);
- }
-
- async abortBash(): Promise<void> {
- if (this.real) {
- await this.real.abortBash();
- }
- }
-
- async setModel(provider: string, modelId: string): Promise<AgentConnectionModel> {
- return (await this.ensure()).setModel(provider, modelId);
- }
-
- async cycleModel(direction?: "forward" | "backward"): Promise<AgentConnectionModelCycleResult | undefined> {
- return (await this.ensure()).cycleModel(direction);
- }
-
- async setScopedModels(scopedModels: AgentConnectionScopedModel[]): Promise<void> {
- return (await this.ensure()).setScopedModels(scopedModels);
- }
-
- async setThinkingLevel(level: ThinkingLevel): Promise<void> {
- return (await this.ensure()).setThinkingLevel(level);
- }
-
- async cycleThinkingLevel(): Promise<ThinkingLevel | undefined> {
- return (await this.ensure()).cycleThinkingLevel();
- }
-
- async setTransport(transport: Transport): Promise<void> {
- return (await this.ensure()).setTransport(transport);
- }
-
- async setSteeringMode(mode: AgentConnectionQueueMode): Promise<void> {
- return (await this.ensure()).setSteeringMode(mode);
- }
-
- async setFollowUpMode(mode: AgentConnectionQueueMode): Promise<void> {
- return (await this.ensure()).setFollowUpMode(mode);
- }
-
- async setAutoCompactionEnabled(enabled: boolean): Promise<void> {
- return (await this.ensure()).setAutoCompactionEnabled(enabled);
- }
-
- async compact(customInstructions?: string): Promise<CompactionResult> {
- return (await this.ensure()).compact(customInstructions);
- }
-
- async refine(options?: { instructions?: string; rollbackId?: string }): Promise<RefinementResult> {
- return (await this.ensure()).refine(options);
- }
-
- async abortCompaction(): Promise<void> {
- if (this.real) {
- await this.real.abortCompaction();
- }
- }
-
- async abortBranchSummary(): Promise<void> {
- if (this.real) {
- await this.real.abortBranchSummary();
- }
- }
-
- async abortRetry(): Promise<void> {
- if (this.real) {
- await this.real.abortRetry();
- }
- }
-
- async reload(): Promise<void> {
- return (await this.ensure()).reload();
- }
-
- async newSession(options?: AgentConnectionNewSessionOptions): Promise<{ cancelled: boolean }> {
- return (await this.ensure()).newSession(options);
- }
-
- async switchSession(
- sessionPath: string,
- options?: AgentConnectionSwitchSessionOptions,
- ): Promise<{ cancelled: boolean }> {
- return (await this.ensure()).switchSession(sessionPath, options);
- }
-
- async fork(
- entryId: string,
- options?: AgentConnectionForkOptions,
- ): Promise<{ cancelled: boolean; selectedText?: string }> {
- return (await this.ensure()).fork(entryId, options);
- }
-
- async navigateTree(
- targetId: string,
- options?: AgentConnectionNavigateTreeOptions,
- ): Promise<AgentConnectionNavigateTreeResult> {
- return (await this.ensure()).navigateTree(targetId, options);
- }
-
- async importFromJsonl(inputPath: string, cwdOverride?: string): Promise<{ cancelled: boolean }> {
- return (await this.ensure()).importFromJsonl(inputPath, cwdOverride);
- }
-
- async exportToHtml(outputPath?: string): Promise<string> {
- return (await this.ensure()).exportToHtml(outputPath);
- }
-
- async exportToJsonl(outputPath?: string): Promise<string> {
- return (await this.ensure()).exportToJsonl(outputPath);
- }
-
- async setSessionName(name: string): Promise<void> {
- return (await this.ensure()).setSessionName(name);
- }
-
- async renameSavedSession(sessionPath: string, name: string): Promise<void> {
- return (await this.ensure()).renameSavedSession(sessionPath, name);
- }
-
- async deleteSavedSession(sessionPath: string): Promise<DeleteSessionFileResult> {
- return (await this.ensure()).deleteSavedSession(sessionPath);
- }
-
- async addCronJob(schedule: string, prompt: string): Promise<AgentCronJob> {
- return (await this.ensure()).addCronJob(schedule, prompt);
- }
-
- async cancelCronJob(jobId: string): Promise<AgentCronJob> {
- return (await this.ensure()).cancelCronJob(jobId);
- }
-
- async setHeartbeat(schedule: string, instruction: string): Promise<AgentCronJob> {
- return (await this.ensure()).setHeartbeat(schedule, instruction);
- }
-
- async updateHeartbeat(action: AgentHeartbeatUpdateAction): Promise<AgentCronJob | undefined> {
- return (await this.ensure()).updateHeartbeat(action);
- }
-
- async dispose(): Promise<void> {
- this.disposed = true;
- // Wait out an in-flight promotion so a session created during teardown is
- // not left attached with no client.
- if (this.promotion) {
- await this.promotion.catch(() => undefined);
- }
- this.realUnsub?.();
- this.realUnsub = undefined;
- if (this.real) {
- await this.real.dispose();
- this.real = undefined;
- // A promoted-but-never-messaged session (e.g. only a model cycle) would
- // otherwise linger in the daemon; let the caller drop it if abandoned.
- if (this.promotedActiveSessionId && this.discardEmptySession) {
- await this.discardEmptySession(this.promotedActiveSessionId).catch(() => undefined);
- }
- }
- }
-}
diff --git a/packages/coding-agent/src/modes/agent-connection/index.ts b/packages/coding-agent/src/modes/agent-connection/index.ts
index 6355e35052..6eac24da31 100644
--- a/packages/coding-agent/src/modes/agent-connection/index.ts
+++ b/packages/coding-agent/src/modes/agent-connection/index.ts
@@ -1,5 +1,4 @@
export { DaemonAgentConnection } from "./daemon-agent-connection.js";
-export { DeferredAgentConnection, type DeferredAgentConnectionSeed } from "./deferred-agent-connection.js";
export { InProcessAgentConnection } from "./in-process-agent-connection.js";
export { createAgentConnectionCommands, createAgentConnectionState } from "./snapshot.js";
export type {
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index f9f2aece8b..38f7892cbb 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -41,7 +41,7 @@ export type AgentConnectionQueueMode = "all" | "one-at-a-time";
export type AgentConnectionModel = Model<Api>;
export type AgentConnectionSavedSessionScope = "current" | "all";
-export type AgentConnectionSavedSessionStateStatus = "active" | "sleep" | "crash";
+export type AgentConnectionSavedSessionStateStatus = "active" | "archived" | "crash";
export type AgentConnectionSourceScope = "user" | "project" | "temporary";
export type AgentConnectionSourceOrigin = "package" | "top-level";
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 d6eed13f94..0c56f1c007 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
@@ -134,7 +134,10 @@ export function createAgentsViewResumeConfig(config: AgentSessionRuntimeConfig):
export function createAgentsViewListCommand(
config: AgentSessionRuntimeConfig,
): Extract<DaemonCommand, { type: "list" }> {
- const command: Extract<DaemonCommand, { type: "list" }> = { type: "list" };
+ // `all` makes the daemon merge on-disk sessions with in-memory ones; without it
+ // only daemon-resident sessions return and live sessions saved to disk are lost
+ // from the view. No cwd is set so the fleet view spans every directory.
+ const command: Extract<DaemonCommand, { type: "list" }> = { type: "list", all: true };
if (config.sessionDir) {
command.sessionDir = config.sessionDir;
}
@@ -1369,13 +1372,13 @@ class AgentsViewMode implements Component, Focusable {
}
}
if (pending.sessionFile) {
- // The kill above normally persists sleep, but it can be skipped or
- // hit an unknown session (e.g. the daemon died after listing). Make
- // sure the file is not left marked active, or a restarted daemon
- // would resurrect a deliberately deactivated agent.
+ // The kill above normally persists the archived state, but it can be
+ // skipped or hit an unknown session (e.g. the daemon died after
+ // listing). Make sure the file is not left marked active, or a
+ // restarted daemon would resurrect a deliberately deactivated agent.
const sessionManager = SessionManager.open(pending.sessionFile, this.options.config.sessionDir);
if (sessionManager.getSessionState()?.status === "active") {
- sessionManager.appendSessionState({ status: "sleep" });
+ sessionManager.appendSessionState({ status: "archived" });
}
}
this.inactiveAgentIdentities.add(pending.identity);
@@ -1870,13 +1873,7 @@ function rowHasSpawnCode(row: AgentsViewRow): boolean {
}
function isRunningSessionSummary(summary: SessionSummary): boolean {
- return (
- summary.isStreaming ||
- summary.isCompacting ||
- summary.pendingMessageCount > 0 ||
- summary.status === "model" ||
- summary.status === "tool"
- );
+ return summary.activity === "working";
}
export function createAgentsViewSessionName(text: string): 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 e1889aac64..b5a009521a 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
@@ -29,26 +29,19 @@ export interface AgentsViewRow {
}
export function classifyAgentsViewSession(summary: SessionSummary): AgentsViewSection {
- if (summary.isStreaming || summary.isCompacting || summary.pendingMessageCount > 0) {
+ if (summary.activity === "working") {
return "working";
}
- if (summary.status === "model" || summary.status === "tool") {
- return "working";
- }
- // Idle defaults to Completed; only an explicit verdict moves it to Needs Input.
- if (summary.taskState === "needs_input") {
- return "needs-input";
- }
- return "completed";
+ // Idle defaults to Needs Input; only an explicit completed verdict moves it on.
+ return summary.taskState === "completed" ? "completed" : "needs-input";
}
-// The agents view shows daemon-resident sessions only; saved (slept) sessions
-// stay out of the list until they are resumed back into the daemon.
+// Live sessions only; drafts and archived stay out.
export function shouldShowAgentsViewSession(summary: SessionSummary, manuallyInactive = false): boolean {
if (manuallyInactive) {
return false;
}
- return summary.activeSessionId !== undefined;
+ return summary.lifecycle === "live";
}
export function sectionTitle(section: AgentsViewSection): string {
@@ -390,19 +383,16 @@ function getSessionStatusLabel(summary: SessionSummary): string {
return "compacting";
}
if (summary.isStreaming) {
- return summary.status === "tool" ? "running tools" : "thinking";
+ return summary.isRunningTools ? "running tools" : "thinking";
}
if (summary.pendingMessageCount > 0) {
return `${summary.pendingMessageCount} queued`;
}
- if (summary.status === "crash") {
- return "crashed";
- }
- if (summary.status === "sleep") {
- return "saved";
+ if (summary.lifecycle === "archived") {
+ return "archived";
}
- if (summary.messageCount === 0) {
- return "new";
+ if (summary.activity === "working") {
+ return "classifying";
}
- return summary.status;
+ return summary.taskState === "completed" ? "completed" : "needs input";
}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 0461285d2a..7eb76b7ff5 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -65,7 +65,12 @@ import {
isDaemonDialogExtensionUiRequest,
success,
} from "./daemon-protocol.js";
-import { buildRlmChildSnapshots, buildSessionList, summaryForActiveSession } from "./daemon-session-list.js";
+import {
+ buildRlmChildSnapshots,
+ buildSessionList,
+ isActiveSessionBusy,
+ summaryForActiveSession,
+} from "./daemon-session-list.js";
import { DaemonSessionSummarizer } from "./daemon-session-summarizer.js";
import {
cleanupDaemonSocketPath,
@@ -81,7 +86,7 @@ export interface DaemonModeOptions {
}
export type { DaemonCommand, DaemonOutbound, DaemonResponse } from "./daemon-protocol.js";
-export type { SessionStatus, SessionSummary } from "./daemon-session-list.js";
+export type { SessionActivity, SessionLifecycle, SessionSummary } from "./daemon-session-list.js";
export { defaultDaemonSocketPath } from "./daemon-socket.js";
const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
@@ -1489,6 +1494,54 @@ export class AgentDaemon {
private detachClientFromSession(client: DaemonSocketClient, state: ActiveSessionState): void {
detachClientFromActiveSession(client, state);
this.write(client, { type: "session_detached", activeSessionId: state.activeSessionId });
+ // Abandoned new-chat: discard it so it doesn't linger in memory or leave an
+ // empty file. Replaces the old DeferredAgentConnection.
+ if (this.isDiscardableDraft(state)) {
+ // Re-check after yielding: a client may reattach before the async close
+ // runs, in which case the draft is no longer abandoned and must be kept.
+ queueMicrotask(() => {
+ if (this.sessions.has(state.activeSessionId) && this.isDiscardableDraft(state)) {
+ void this.closeSession(state, "killed");
+ }
+ });
+ }
+ }
+
+ private isDiscardableDraft(state: ActiveSessionState): boolean {
+ if (state.clients.size > 0) {
+ return false;
+ }
+ if (state.runtime.metadata.kind === "subagent") {
+ return false;
+ }
+ // A running bash or in-flight turn means there is live work to preserve.
+ if (state.runtime.session.isBashRunning || isActiveSessionBusy(state)) {
+ return false;
+ }
+ return this.isEmptyDraftContent(state);
+ }
+
+ /**
+ * True when a session holds nothing worth persisting: no messages, no user
+ * config (model/name/etc.), and no scheduled jobs. Shared by the detach-time
+ * discard and the close-time file deletion so both agree on what an abandoned
+ * draft is.
+ */
+ private isEmptyDraftContent(state: ActiveSessionState): boolean {
+ const session = state.runtime.session;
+ if (session.messages.length > 0 || session.sessionManager.hasUserContent()) {
+ return false;
+ }
+ return !this.hasScheduledJobsForSession(state.activeSessionId);
+ }
+
+ private hasScheduledJobsForSession(activeSessionId: string): boolean {
+ return this.cronStore
+ .list()
+ .some(
+ (job) =>
+ job.activeSessionId === activeSessionId && job.status !== "cancelled" && job.status !== "completed",
+ );
}
private detachClient(client: DaemonSocketClient): void {
@@ -1535,13 +1588,14 @@ export class AgentDaemon {
// agent_status to a session being torn down.
this.summarizer.forget(state.activeSessionId);
const cascadeError = await this.closeChildSessions(state, reason);
- // A killed session with no messages (abandoned new-chat) is discarded
- // outright instead of persisting a sleep state that clutters the list.
- const isEmptyKilledSession = reason === "killed" && state.runtime.session.messages.length === 0;
+ // Empty draft (no messages, config, or jobs): discard rather than persist an
+ // empty session file. Mirrors the detach-time discard so a config-bearing
+ // draft closed via kill/completed is never wiped.
+ const isEmptyDraftSession = reason !== "shutdown" && this.isEmptyDraftContent(state);
let persistError: unknown;
- if (reason !== "shutdown" && !isEmptyKilledSession) {
+ if (reason !== "shutdown" && !isEmptyDraftSession) {
try {
- state.runtime.session.sessionManager.appendSessionState({ status: "sleep" });
+ state.runtime.session.sessionManager.appendSessionState({ status: "archived" });
} catch (error) {
persistError = error;
}
@@ -1558,7 +1612,7 @@ export class AgentDaemon {
}
state.clients.clear();
this.sessions.delete(state.activeSessionId);
- if (isEmptyKilledSession) {
+ if (isEmptyDraftSession) {
const sessionFile = state.runtime.session.sessionFile;
if (sessionFile) {
await deleteSessionFile(sessionFile).catch(() => undefined);
@@ -1588,12 +1642,21 @@ export class AgentDaemon {
}
private broadcastToSession(state: ActiveSessionState, message: DaemonOutbound): void {
- // A finished turn/compaction is the cue to refresh status.
- if (
- message.type === "session_event" &&
- (message.event.type === "turn_end" || message.event.type === "compaction_end")
- ) {
- this.summarizer.notifyActivity(state);
+ if (message.type === "session_event") {
+ const eventType = message.event.type;
+ // A finished turn/compaction is the cue to refresh status.
+ if (eventType === "turn_end" || eventType === "compaction_end") {
+ this.summarizer.notifyActivity(state);
+ }
+ // A draft whose last client detached while it was busy isn't discardable
+ // at detach time; re-check once any work (turn, compaction, or bash)
+ // settles so it doesn't linger in the daemon.
+ if (
+ (eventType === "turn_end" || eventType === "compaction_end" || eventType === "bash_end") &&
+ this.isDiscardableDraft(state)
+ ) {
+ void this.closeSession(state, "killed");
+ }
}
const sequencedMessage = this.addSessionEventMeta(state, message);
for (const client of state.clients) {
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 00c116785d..0998bf8700 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
@@ -9,11 +9,17 @@ import type { AgentTaskState, SessionInfo } from "../../core/session-manager.js"
import type {
AgentConnectionRlmChildAgentSnapshot,
AgentConnectionRlmChildAgentTranscriptLine,
- AgentConnectionSavedSessionStateStatus,
} from "../agent-connection/types.js";
import type { ActiveSessionState } from "./active-session-state.js";
-export type SessionStatus = "user" | "idle" | "tool" | "model" | AgentConnectionSavedSessionStateStatus;
+// 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.
+export type SessionLifecycle = "draft" | "live" | "archived";
+
+// Heuristic activity of a live session. Classification-in-flight counts as
+// "working" so the view never sees an unlabeled idle session.
+export type SessionActivity = "working" | "idle";
// Upper bound on the spawn-code source carried in a session summary. Generous
// enough for real spawn cells while keeping the daemon wire payload bounded.
@@ -22,7 +28,8 @@ const SPAWN_CODE_MAX_CHARS = 4000;
// Lightweight daemon session shape used by list, create, rename, attach, and state responses.
export interface SessionSummary {
id: string;
- status: SessionStatus;
+ lifecycle: SessionLifecycle;
+ activity: SessionActivity;
runtimeKind?: "top-level" | "subagent";
activeSessionId?: string;
sessionId: string;
@@ -34,6 +41,8 @@ export interface SessionSummary {
isStreaming: boolean;
isCompacting: boolean;
isBashRunning?: boolean;
+ /** True while the agent is streaming with tool calls pending; drives the "running tools" label. */
+ isRunningTools?: boolean;
attachedClients: number;
messageCount: number;
pendingMessageCount: number;
@@ -122,7 +131,8 @@ export function summaryForActiveSession(activeSession: ActiveSessionState, saved
return {
id: activeSession.activeSessionId,
- status: activeStatusForSession(activeSession),
+ lifecycle: activeLifecycleForSession(activeSession),
+ activity: activeActivityForSession(activeSession),
runtimeKind: metadata.kind,
activeSessionId: activeSession.activeSessionId,
sessionId: session.sessionId,
@@ -134,6 +144,7 @@ export function summaryForActiveSession(activeSession: ActiveSessionState, saved
isStreaming: session.isStreaming,
isCompacting: session.isCompacting,
isBashRunning: session.isBashRunning,
+ isRunningTools: session.isStreaming && session.state.pendingToolCalls.size > 0,
attachedClients: activeSession.clients.size,
messageCount: session.messages.length,
pendingMessageCount: session.pendingMessageCount,
@@ -175,7 +186,8 @@ export function isSummaryCurrent(activeSession: ActiveSessionState): boolean {
export function summaryForInactiveSession(session: SessionInfo): SessionSummary {
return {
id: session.id,
- status: session.state?.status ?? "sleep",
+ lifecycle: inactiveLifecycleForSession(session),
+ activity: "idle",
sessionId: session.id,
sessionFile: session.path,
sessionName: session.name,
@@ -189,6 +201,13 @@ export function summaryForInactiveSession(session: SessionInfo): SessionSummary
modified: session.modified.toISOString(),
firstMessage: session.firstMessage,
parentSessionPath: session.parentSessionPath,
+ // Carry the persisted recap/verdict so an off-daemon session keeps its
+ // agents-view bucket (e.g. Completed) instead of defaulting to Needs Input.
+ // Gate on message-count currency like isSummaryCurrent does for resident
+ // sessions, so a verdict from before later messages isn't shown stale.
+ ...(session.agentStatus?.basedOnMessageCount === session.messageCount
+ ? { summary: session.agentStatus.summary, taskState: session.agentStatus.taskState }
+ : {}),
};
}
@@ -299,10 +318,44 @@ function readMessageText(content: unknown): string {
.join("\n");
}
-function activeStatusForSession(activeSession: ActiveSessionState): SessionStatus {
+// Agent doing work, ignoring the classification verdict.
+export function isActiveSessionBusy(activeSession: ActiveSessionState): boolean {
const session = activeSession.runtime.session;
- if (session.isStreaming) {
- return session.state.pendingToolCalls.size > 0 ? "tool" : "model";
+ return session.isStreaming || session.isCompacting || session.pendingMessageCount > 0;
+}
+
+export function activeActivityForSession(activeSession: ActiveSessionState): SessionActivity {
+ if (isActiveSessionBusy(activeSession)) {
+ return "working";
+ }
+ // Hold at "working" until the idle verdict is current, so the view never
+ // buckets an unlabeled idle session.
+ return isSummaryCurrent(activeSession) ? "idle" : "working";
+}
+
+/**
+ * Lifecycle for an on-disk session not resident in the daemon. Explicitly
+ * archived/crashed records stay out of the view; everything else is classified
+ * by message count (live once a message exists, draft otherwise). A missing
+ * session_state is treated as not-archived, so older sessions that never wrote a
+ * lifecycle entry still surface. Message-based to match activeLifecycleForSession.
+ */
+export function inactiveLifecycleForSession(session: SessionInfo): SessionLifecycle {
+ const status = session.state?.status;
+ if (status === "archived" || status === "crash") {
+ return "archived";
}
- return activeSession.clients.size > 0 ? "user" : "idle";
+ return session.messageCount > 0 ? "live" : "draft";
+}
+
+export function activeLifecycleForSession(activeSession: ActiveSessionState): SessionLifecycle {
+ // Lifecycle drives agents-view visibility and is message-based: a session
+ // becomes live once a message is sent. A message-less session is a draft (hidden
+ // from the view) even if the user changed its model/name first — that config is
+ // still preserved on disk by the discard guard (see isEmptyDraftContent), it
+ // just doesn't surface a conversation-less row. Keeping this purely message-based
+ // matches inactiveLifecycleForSession, so a session doesn't change lifecycle when
+ // it leaves daemon memory. Stale on-disk archived/crash markers never apply to a
+ // resident session.
+ return activeSession.runtime.session.messages.length === 0 ? "draft" : "live";
}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-summarizer.ts b/packages/coding-agent/src/modes/daemon/daemon-session-summarizer.ts
index 6c106011d6..d3030f5f3c 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-session-summarizer.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-session-summarizer.ts
@@ -308,7 +308,11 @@ export class DaemonSessionSummarizer {
// always refresh so the recap keeps up with the in-progress turn.
const contentUnchanged = previous?.basedOnMessageCount === messageCount;
const owesIdleVerdict = !isWorking && previous?.taskState === undefined;
- if (contentUnchanged && !isWorking && !owesIdleVerdict) {
+ // A blank recap means the model call hasn't succeeded yet (e.g. the
+ // needs_input fallback fired on a transient failure); keep retrying until a
+ // real summary lands so the recap isn't left permanently empty.
+ const owesSummary = !isWorking && !previous?.summary;
+ if (contentUnchanged && !isWorking && !owesIdleVerdict && !owesSummary) {
return;
}
// Include the in-progress message so a long streaming turn gets a live recap.
@@ -318,12 +322,20 @@ export class DaemonSessionSummarizer {
const controller = new AbortController();
this.inFlight.set(id, controller);
try {
- const result = await this.generate({
+ const generated = await this.generate({
registry: session.modelRegistry,
messages: contextMessages,
isWorking,
signal: controller.signal,
});
+ // A failed classification on an idle session would spin at "working"
+ // forever (the activity axis holds unjudged idle sessions there), so
+ // settle it to needs_input.
+ const result =
+ generated ??
+ (!isWorking && (owesIdleVerdict || owesSummary)
+ ? { summary: previous?.summary ?? "", taskState: "needs_input" as const }
+ : undefined);
if (!result) {
return;
}
diff --git a/packages/coding-agent/src/modes/index.ts b/packages/coding-agent/src/modes/index.ts
index 2a1b1cd607..1ca9ff4810 100644
--- a/packages/coding-agent/src/modes/index.ts
+++ b/packages/coding-agent/src/modes/index.ts
@@ -18,12 +18,7 @@ export type {
AgentConnectionSlashCommand,
AgentConnectionState,
} from "./agent-connection/index.js";
-export {
- DaemonAgentConnection,
- DeferredAgentConnection,
- type DeferredAgentConnectionSeed,
- InProcessAgentConnection,
-} from "./agent-connection/index.js";
+export { DaemonAgentConnection, InProcessAgentConnection } from "./agent-connection/index.js";
export { type AgentsViewModeOptions, runAgentsViewMode } from "./agents-view/agents-view-mode.js";
export {
type AgentsViewRow,
@@ -65,7 +60,7 @@ export {
DAEMON_PROTOCOL_NAME,
DAEMON_PROTOCOL_VERSION,
} from "./daemon/daemon-protocol.js";
-export type { SessionStatus, SessionSummary } from "./daemon/daemon-session-list.js";
+export type { SessionActivity, SessionLifecycle, SessionSummary } from "./daemon/daemon-session-list.js";
export { resolveAttachModelFallbackMessage } from "./daemon/daemon-session-list.js";
export { defaultDaemonSocketPath } from "./daemon/daemon-socket.js";
export {
diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.ts
index ceb862dd6b..17e98c15f2 100644
--- a/packages/coding-agent/test/agent-connection-daemon.test.ts
+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts
@@ -391,7 +391,8 @@ function createAttachResult(
const summary = {
id: activeSessionId,
activeSessionId,
- status: "idle" as const,
+ lifecycle: "live" as const,
+ activity: "idle" as const,
sessionId: state.sessionId,
cwd: "/tmp/project",
isStreaming: false,
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index 039c1a4ede..7ecfc3e293 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -24,34 +24,54 @@ import type { Theme } from "../src/modes/interactive/theme/theme.js";
describe("agents view state", () => {
test("classifies active daemon sessions into coarse fleet sections", () => {
- expect(classifyAgentsViewSession(makeSummary({ isStreaming: true, status: "model" }))).toBe("working");
- expect(classifyAgentsViewSession(makeSummary({ pendingMessageCount: 1 }))).toBe("working");
- expect(classifyAgentsViewSession(makeSummary({ status: "tool" }))).toBe("working");
- expect(classifyAgentsViewSession(makeSummary({ status: "user", messageCount: 2 }))).toBe("completed");
- expect(classifyAgentsViewSession(makeSummary({ status: "idle", messageCount: 0 }))).toBe("completed");
- expect(classifyAgentsViewSession(makeSummary({ status: "idle", messageCount: 4 }))).toBe("completed");
+ 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");
});
test("idle sessions split by the summarizer's completion verdict", () => {
// Working is heuristic and ignores taskState.
- expect(classifyAgentsViewSession(makeSummary({ isStreaming: true, taskState: "completed" }))).toBe("working");
- // Idle sessions follow the verdict; absent one they stay completed.
- expect(classifyAgentsViewSession(makeSummary({ status: "idle", taskState: "needs_input" }))).toBe("needs-input");
- expect(classifyAgentsViewSession(makeSummary({ status: "idle", taskState: "completed" }))).toBe("completed");
- expect(classifyAgentsViewSession(makeSummary({ status: "idle", taskState: undefined }))).toBe("completed");
+ 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");
});
- test("defaults an idle session with no verdict to completed", () => {
+ test("defaults an idle session with no verdict to needs-input", () => {
// A slow, failed, or absent classification never lingers in Working; only
- // an explicit needs_input verdict moves an idle session out of completed.
- expect(classifyAgentsViewSession(makeSummary({ status: "idle", taskState: undefined }))).toBe("completed");
+ // an explicit completed verdict moves an idle session out of needs-input.
+ expect(classifyAgentsViewSession(makeSummary({ activity: "idle", taskState: undefined }))).toBe("needs-input");
});
test("sorts rows by section and most recent modified time", () => {
const rows = buildAgentsViewRows([
- makeSummary({ sessionName: "completed", status: "idle", messageCount: 2, modified: "2026-01-01T00:00:00Z" }),
- makeSummary({ sessionName: "older working", isStreaming: true, modified: "2026-01-01T00:00:00Z" }),
- makeSummary({ sessionName: "newer working", isStreaming: true, modified: "2026-01-02T00:00:00Z" }),
+ makeSummary({
+ sessionName: "completed",
+ activity: "idle",
+ taskState: "completed",
+ messageCount: 2,
+ modified: "2026-01-01T00:00:00Z",
+ }),
+ makeSummary({
+ sessionName: "older working",
+ activity: "working",
+ isStreaming: true,
+ modified: "2026-01-01T00:00:00Z",
+ }),
+ makeSummary({
+ sessionName: "newer working",
+ activity: "working",
+ isStreaming: true,
+ modified: "2026-01-02T00:00:00Z",
+ }),
]);
expect(rows.map((row) => row.title)).toEqual(["newer working", "older working", "completed"]);
@@ -69,7 +89,7 @@ describe("agents view state", () => {
parentActiveSessionId: "parent-active",
parentSessionId: "parent-session",
isStreaming: true,
- status: "model",
+ activity: "working",
}),
makeSummary({
id: "second-child-active",
@@ -79,7 +99,7 @@ describe("agents view state", () => {
runtimeKind: "subagent",
parentActiveSessionId: "parent-active",
parentSessionId: "parent-session",
- status: "tool",
+ activity: "working",
}),
makeSummary({
id: "completed-child-active",
@@ -89,7 +109,7 @@ describe("agents view state", () => {
runtimeKind: "subagent",
parentActiveSessionId: "parent-active",
parentSessionId: "parent-session",
- status: "idle",
+ activity: "idle",
messageCount: 2,
}),
makeSummary({
@@ -98,14 +118,15 @@ describe("agents view state", () => {
sessionId: "parent-session",
sessionName: "Parent",
isStreaming: true,
- status: "tool",
+ activity: "working",
}),
makeSummary({
id: "other-active",
activeSessionId: "other-active",
sessionId: "other-session",
sessionName: "Other",
- status: "idle",
+ activity: "idle",
+ taskState: "completed",
messageCount: 2,
}),
]);
@@ -133,7 +154,7 @@ describe("agents view state", () => {
runtimeKind: "subagent",
parentActiveSessionId: "parent-active",
isStreaming: true,
- status: "model",
+ activity: "working",
}),
makeSummary({
id: "completed-child-active",
@@ -143,7 +164,8 @@ describe("agents view state", () => {
sessionName: "Completed child",
runtimeKind: "subagent",
parentActiveSessionId: "parent-active",
- status: "idle",
+ activity: "idle",
+ taskState: "completed",
messageCount: 2,
}),
makeSummary({
@@ -153,7 +175,7 @@ describe("agents view state", () => {
sessionFile: "/tmp/parent.jsonl",
sessionName: "Parent",
isStreaming: true,
- status: "tool",
+ activity: "working",
}),
];
@@ -181,7 +203,7 @@ describe("agents view state", () => {
sessionName: "Done child",
runtimeKind: "subagent",
parentActiveSessionId: "parent-active",
- status: "idle",
+ activity: "idle",
messageCount: 2,
}),
makeSummary({
@@ -190,7 +212,7 @@ describe("agents view state", () => {
sessionId: "parent-session",
sessionFile: "/tmp/parent.jsonl",
sessionName: "Parent",
- status: "idle",
+ activity: "idle",
messageCount: 4,
}),
]);
@@ -211,7 +233,7 @@ describe("agents view state", () => {
sessionName: "Legacy child",
parentActiveSessionId: "parent-active",
isStreaming: true,
- status: "model",
+ activity: "working",
}),
makeSummary({
id: "legacy-rlm-child",
@@ -219,7 +241,7 @@ describe("agents view state", () => {
sessionId: "legacy-rlm-session",
sessionName: "Legacy rlm child",
rlmChildId: "node-1",
- status: "idle",
+ activity: "idle",
messageCount: 2,
}),
makeSummary({
@@ -228,7 +250,7 @@ describe("agents view state", () => {
sessionId: "parent-session",
sessionName: "Parent",
isStreaming: true,
- status: "tool",
+ activity: "working",
}),
]);
@@ -279,7 +301,7 @@ describe("agents view state", () => {
sessionId: "parent-session",
sessionName: "Parent",
isStreaming: true,
- status: "tool",
+ activity: "working",
}),
];
@@ -335,7 +357,7 @@ describe("agents view state", () => {
sessionId: "parent-session",
sessionName: "Parent",
isStreaming: true,
- status: "tool",
+ activity: "working",
}),
];
const parentIdentity = buildAgentsViewRows(summaries)[0]?.identity ?? "";
@@ -359,14 +381,14 @@ describe("agents view state", () => {
parentActiveSessionId: "removed-parent-active",
parentSessionId: "removed-parent-session",
isStreaming: true,
- status: "model",
+ activity: "working",
}),
makeSummary({
id: "other-active",
activeSessionId: "other-active",
sessionId: "other-session",
sessionName: "Other",
- status: "idle",
+ activity: "idle",
messageCount: 2,
}),
]);
@@ -375,12 +397,12 @@ describe("agents view state", () => {
});
test("shows daemon-resident sessions only", () => {
- const inactiveSleep = makeSummary({ status: "sleep" });
+ const inactiveSleep = makeSummary({ lifecycle: "archived", activity: "idle" });
delete inactiveSleep.activeSessionId;
expect(shouldShowAgentsViewSession(inactiveSleep)).toBe(false);
- expect(shouldShowAgentsViewSession(makeSummary({ status: "idle" }))).toBe(true);
- expect(shouldShowAgentsViewSession(makeSummary({ status: "idle" }), true)).toBe(false);
+ expect(shouldShowAgentsViewSession(makeSummary({ lifecycle: "live", activity: "idle" }))).toBe(true);
+ expect(shouldShowAgentsViewSession(makeSummary({ lifecycle: "live", activity: "idle" }), true)).toBe(false);
});
test("does not override saved session cwd when reopening inactive agents", () => {
@@ -400,10 +422,11 @@ describe("agents view state", () => {
expect(config.cwd).toBe("/tmp/dashboard");
});
- test("requests only daemon-resident sessions for the agents view refresh", () => {
- expect(createAgentsViewListCommand({ cwd: "/tmp/project" })).toEqual({ type: "list" });
+ test("requests all sessions (in-memory + on-disk) for the agents view refresh", () => {
+ expect(createAgentsViewListCommand({ cwd: "/tmp/project" })).toEqual({ type: "list", all: true });
expect(createAgentsViewListCommand({ cwd: "/tmp/project", sessionDir: "/tmp/sessions" })).toEqual({
type: "list",
+ all: true,
sessionDir: "/tmp/sessions",
});
});
@@ -521,7 +544,8 @@ function makeSummary(overrides: Partial<SessionSummary>): SessionSummary {
return {
id: "active-1",
activeSessionId: "active-1",
- status: "idle",
+ lifecycle: "live",
+ activity: "idle",
sessionId: "session-1",
cwd: "/tmp/project",
isStreaming: false,
diff --git a/packages/coding-agent/test/daemon-list-format.test.ts b/packages/coding-agent/test/daemon-list-format.test.ts
index 9e410943d9..c18b5a617e 100644
--- a/packages/coding-agent/test/daemon-list-format.test.ts
+++ b/packages/coding-agent/test/daemon-list-format.test.ts
@@ -2,7 +2,7 @@ import type { Api, Model } from "@earendil-works/pi-ai";
import stripAnsi from "strip-ansi";
import { describe, expect, it } from "vitest";
import { formatSessionListTable } from "../src/cli/daemon-list-format.js";
-import type { SessionStatus, SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
+import type { SessionActivity, SessionLifecycle, SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
describe("formatSessionListTable", () => {
it("sorts sessions by status and renders compact suffix ids", () => {
@@ -10,15 +10,17 @@ describe("formatSessionListTable", () => {
const table = stripAnsi(
formatSessionListTable(
[
- makeSummary({ name: "sleep", id: "019e71ec-e08a-75a9-b573-fc10e9f8380f", status: "sleep" }),
- makeSummary({ name: "tool", id: "ccccddddeeee", status: "tool" }),
- makeSummary({ name: "crash", id: "019e71ec-e08a-75a9-b573-abcdef123456", status: "crash" }),
- makeSummary({ name: "idle", id: "bbbbccccdddd", status: "idle" }),
- makeSummary({ name: "model", id: "ddddeeeeffff", status: "model" }),
+ makeSummary({ name: "sleep", id: "019e71ec-e08a-75a9-b573-fc10e9f8380f", lifecycle: "archived", activity: "idle" }),
+ makeSummary({ name: "tool", id: "ccccddddeeee", lifecycle: "live", activity: "working" }),
+ makeSummary({ name: "crash", id: "019e71ec-e08a-75a9-b573-abcdef123456", lifecycle: "archived", activity: "idle" }),
+ makeSummary({ name: "idle", id: "bbbbccccdddd", lifecycle: "live", activity: "idle" }),
+ makeSummary({ name: "model", id: "ddddeeeeffff", lifecycle: "live", activity: "working" }),
makeSummary({
name: "user",
id: "aaaabbbbcccc",
- status: "user",
+ lifecycle: "live",
+ activity: "idle",
+ clients: 1,
model: { provider: "openai-codex", id: "gpt-5.5" } as Model<Api>,
}),
],
@@ -29,12 +31,12 @@ describe("formatSessionListTable", () => {
const lines = table.split("\n");
expect(lines[0]!.trim().split(/\s+/)).toEqual(["name", "id", "status", "age", "model", "messages", "clients"]);
expect(lines.slice(1).map((line) => line.trim().split(/\s+/).slice(0, 3))).toEqual([
- ["user", "aaaabbbbcccc", "user"],
+ ["tool", "ccccddddeeee", "working"],
+ ["model", "ddddeeeeffff", "working"],
["idle", "bbbbccccdddd", "idle"],
- ["tool", "ccccddddeeee", "tool"],
- ["model", "ddddeeeeffff", "model"],
- ["sleep", "fc10e9f8380f", "sleep"],
- ["crash", "abcdef123456", "crash"],
+ ["user", "aaaabbbbcccc", "idle"],
+ ["sleep", "fc10e9f8380f", "archived"],
+ ["crash", "abcdef123456", "archived"],
]);
expect(table).toContain("openai-codex/gpt-5.5");
expect(table).not.toContain("/tmp/project");
@@ -42,17 +44,25 @@ describe("formatSessionListTable", () => {
});
});
-function makeSummary(options: { name: string; id: string; status: SessionStatus; model?: Model<Api> }): SessionSummary {
+function makeSummary(options: {
+ name: string;
+ id: string;
+ lifecycle: SessionLifecycle;
+ activity: SessionActivity;
+ clients?: number;
+ model?: Model<Api>;
+}): SessionSummary {
return {
id: options.id,
- status: options.status,
+ lifecycle: options.lifecycle,
+ activity: options.activity,
sessionId: options.id,
sessionName: options.name,
cwd: "/tmp/project",
model: options.model,
- isStreaming: options.status === "tool" || options.status === "model",
+ isStreaming: options.lifecycle === "live" && options.activity === "working",
isCompacting: false,
- attachedClients: options.status === "user" ? 1 : 0,
+ attachedClients: options.clients ?? 0,
messageCount: 2,
pendingMessageCount: 0,
modified: "2026-05-29T10:00:00.000Z",
diff --git a/packages/coding-agent/test/daemon-session-id.test.ts b/packages/coding-agent/test/daemon-session-id.test.ts
index 5b087aac41..b09cb069de 100644
--- a/packages/coding-agent/test/daemon-session-id.test.ts
+++ b/packages/coding-agent/test/daemon-session-id.test.ts
@@ -100,5 +100,5 @@ function makeState(activeSessionId: string, sessionId: string): ActiveSessionSta
function createSavedSession(cwd: string, sessionDir: string, sessionId: string): void {
const session = SessionManager.create(cwd, sessionDir);
session.newSession({ id: sessionId });
- session.appendSessionState({ status: "sleep" });
+ session.appendSessionState({ status: "archived" });
}
diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.ts
index aad7156527..5bb6a12340 100644
--- a/packages/coding-agent/test/daemon-session-list.test.ts
+++ b/packages/coding-agent/test/daemon-session-list.test.ts
@@ -12,27 +12,46 @@ import {
} from "../src/modes/daemon/daemon-session-list.js";
describe("buildSessionList", () => {
- it("derives active session statuses", () => {
+ it("derives active session lifecycle and activity", () => {
+ const oneMessage = [{ role: "user", content: "hi" }] as unknown as AgentMessage[];
+ const currentSummary = { basedOnMessageCount: 1 } as ActiveSessionState["summaryState"];
const entries = buildSessionList(
[
- makeState({ activeSessionId: "model", sessionFile: "/tmp/model.jsonl", isStreaming: true }),
+ makeState({
+ activeSessionId: "model",
+ sessionFile: "/tmp/model.jsonl",
+ isStreaming: true,
+ messages: oneMessage,
+ }),
makeState({
activeSessionId: "tool",
sessionFile: "/tmp/tool.jsonl",
isStreaming: true,
pendingToolCalls: ["tool-1"],
+ messages: oneMessage,
+ }),
+ makeState({
+ activeSessionId: "needs-user",
+ sessionFile: "/tmp/needs-user.jsonl",
+ clients: 1,
+ messages: oneMessage,
+ summaryState: currentSummary,
+ }),
+ makeState({
+ activeSessionId: "done",
+ sessionFile: "/tmp/done.jsonl",
+ messages: oneMessage,
+ summaryState: currentSummary,
}),
- makeState({ activeSessionId: "needs-user", sessionFile: "/tmp/needs-user.jsonl", clients: 1 }),
- makeState({ activeSessionId: "done", sessionFile: "/tmp/done.jsonl" }),
],
[],
);
- expect(entries.map((entry) => [entry.id, entry.status])).toEqual([
- ["model", "model"],
- ["tool", "tool"],
- ["needs-user", "user"],
- ["done", "idle"],
+ expect(entries.map((entry) => [entry.id, entry.lifecycle, entry.activity])).toEqual([
+ ["model", "live", "working"],
+ ["tool", "live", "working"],
+ ["needs-user", "live", "idle"],
+ ["done", "live", "idle"],
]);
});
@@ -42,24 +61,120 @@ describe("buildSessionList", () => {
const crashedPath = resolve("/tmp/project/crashed.jsonl");
const savedSessions = [
makeSessionInfo({ path: activePath, id: "saved-active", name: "active saved" }),
- makeSessionInfo({ path: sleepingPath, id: "saved-sleeping", name: "sleeping saved" }),
+ makeSessionInfo({
+ path: sleepingPath,
+ id: "saved-sleeping",
+ name: "sleeping saved",
+ state: { status: "archived" },
+ }),
makeSessionInfo({ path: crashedPath, id: "saved-crashed", state: { status: "crash" } }),
];
const entries = buildSessionList(
- [makeState({ activeSessionId: "active-1", sessionFile: activePath, sessionId: "saved-active" })],
+ [
+ makeState({
+ activeSessionId: "active-1",
+ sessionFile: activePath,
+ sessionId: "saved-active",
+ messages: [{ role: "user", content: "hi" }] as unknown as AgentMessage[],
+ summaryState: { basedOnMessageCount: 1 } as ActiveSessionState["summaryState"],
+ }),
+ ],
savedSessions,
);
expect(entries).toHaveLength(3);
- expect(entries.map((entry) => [entry.id, entry.sessionId, entry.status])).toEqual([
- ["active-1", "saved-active", "idle"],
- ["saved-sleeping", "saved-sleeping", "sleep"],
- ["saved-crashed", "saved-crashed", "crash"],
+ expect(entries.map((entry) => [entry.id, entry.sessionId, entry.lifecycle, entry.activity])).toEqual([
+ ["active-1", "saved-active", "live", "idle"],
+ ["saved-sleeping", "saved-sleeping", "archived", "idle"],
+ ["saved-crashed", "saved-crashed", "archived", "idle"],
]);
expect(entries[0]!.sessionName).toBe("session active-1");
});
+ it("treats a message-less on-disk active session as a hidden draft", () => {
+ const emptyPath = resolve("/tmp/project/empty.jsonl");
+ const usedPath = resolve("/tmp/project/used.jsonl");
+ const entries = buildSessionList(
+ [],
+ [
+ // Active record, no messages: a draft, hidden from the view (lifecycle is
+ // message-based; any config it holds is still preserved on disk).
+ makeSessionInfo({
+ path: emptyPath,
+ id: "empty",
+ messageCount: 0,
+ name: "named draft",
+ state: { status: "active" },
+ }),
+ // Active record with a message: a real conversation, stays live.
+ makeSessionInfo({
+ path: usedPath,
+ id: "used",
+ messageCount: 1,
+ state: { status: "active" },
+ }),
+ ],
+ );
+ expect(entries.map((entry) => [entry.id, entry.lifecycle])).toEqual([
+ ["empty", "draft"],
+ ["used", "live"],
+ ]);
+ });
+
+ it("shows an off-daemon session with messages but no lifecycle entry as live", () => {
+ // Older sessions never wrote a session_state entry; a missing state must not
+ // be treated as archived, or those conversations vanish from the view.
+ const [entry] = buildSessionList(
+ [],
+ [
+ makeSessionInfo({
+ path: resolve("/tmp/project/legacy.jsonl"),
+ id: "legacy",
+ messageCount: 4,
+ state: undefined,
+ }),
+ ],
+ );
+ expect(entry?.lifecycle).toBe("live");
+ });
+
+ it("carries the persisted recap and verdict for off-daemon sessions", () => {
+ const path = resolve("/tmp/project/done.jsonl");
+ const [entry] = buildSessionList(
+ [],
+ [
+ makeSessionInfo({
+ path,
+ id: "done",
+ messageCount: 3,
+ state: { status: "active" },
+ agentStatus: { summary: "Shipped the fix", taskState: "completed", basedOnMessageCount: 3 },
+ }),
+ ],
+ );
+ expect(entry).toMatchObject({ summary: "Shipped the fix", taskState: "completed" });
+ });
+
+ it("drops a stale persisted verdict when later messages outpaced it", () => {
+ const path = resolve("/tmp/project/stale.jsonl");
+ const [entry] = buildSessionList(
+ [],
+ [
+ makeSessionInfo({
+ path,
+ id: "stale",
+ messageCount: 5,
+ state: { status: "active" },
+ // Verdict was based on an earlier turn (3 < 5), so it must not show.
+ agentStatus: { summary: "Old recap", taskState: "completed", basedOnMessageCount: 3 },
+ }),
+ ],
+ );
+ expect(entry?.summary).toBeUndefined();
+ expect(entry?.taskState).toBeUndefined();
+ });
+
it("includes active subagent parent metadata", () => {
const entries = buildSessionList(
[
@@ -234,7 +349,8 @@ describe("resolveAttachModelFallbackMessage", () => {
function makeSummary(overrides: Partial<SessionSummary>): SessionSummary {
return {
id: "active-1",
- status: "idle",
+ lifecycle: "draft",
+ activity: "idle",
sessionId: "session-1",
cwd: "/tmp/project",
isStreaming: false,
@@ -271,6 +387,7 @@ interface StateOptions {
pendingToolCalls?: string[];
clients?: number;
messages?: AgentMessage[];
+ hasUserContent?: boolean;
summaryState?: ActiveSessionState["summaryState"];
childRunStatuses?: Record<string, "queued" | "running" | "done" | "error" | "cancelled">;
metadata?: {
@@ -311,6 +428,7 @@ function makeState(options: StateOptions): ActiveSessionState {
sessionManager: {
getCwd: () => "/tmp/project",
getSessionDir: () => "/tmp/sessions",
+ hasUserContent: () => options.hasUserContent ?? false,
},
messages: options.messages ?? ([] as AgentMessage[]),
getRlmChildRunStatus: (childId: string) => options.childRunStatuses?.[childId],
@@ -333,8 +451,9 @@ function makeSessionInfo(overrides: Pick<SessionInfo, "path" | "id"> & Partial<S
state: overrides.state,
created: new Date("2026-05-01T00:00:00.000Z"),
modified: new Date("2026-05-02T00:00:00.000Z"),
- messageCount: 2,
+ messageCount: overrides.messageCount ?? 2,
firstMessage: "hello",
allMessagesText: "hello world",
+ agentStatus: overrides.agentStatus,
};
}
diff --git a/packages/coding-agent/test/daemon-session-summarizer-lifecycle.test.ts b/packages/coding-agent/test/daemon-session-summarizer-lifecycle.test.ts
index 9704d00a42..441df8920e 100644
--- a/packages/coding-agent/test/daemon-session-summarizer-lifecycle.test.ts
+++ b/packages/coding-agent/test/daemon-session-summarizer-lifecycle.test.ts
@@ -56,7 +56,7 @@ describe("DaemonSessionSummarizer lifecycle", () => {
expect(onStatusChanged).toHaveBeenCalled();
});
- test("a failing model leaves no verdict — the view then defaults to completed", async () => {
+ test("a failing model on an idle session settles to a needs_input fallback verdict", async () => {
vi.useFakeTimers();
const generate = vi.fn().mockResolvedValue(undefined); // 404 / 401 / timeout / unparseable
const summarizer = new DaemonSessionSummarizer(() => [], undefined, generate);
@@ -65,8 +65,29 @@ describe("DaemonSessionSummarizer lifecycle", () => {
summarizer.notifyActivity(state);
await vi.advanceTimersByTimeAsync(SETTLE_MS + 500);
expect(generate).toHaveBeenCalledOnce();
- // No status recorded; taskState stays undefined so classification → completed.
- expect(state.summaryState).toBeUndefined();
+ // The activity axis holds an unjudged idle session at "working"; the fallback
+ // settles it to needs_input so it doesn't spin forever.
+ expect(state.summaryState).toMatchObject({ taskState: "needs_input", basedOnMessageCount: 2 });
+ });
+
+ test("retries after a needs_input fallback until a real summary lands", async () => {
+ vi.useFakeTimers();
+ const generate = vi
+ .fn()
+ .mockResolvedValueOnce(undefined) // transient failure → blank needs_input fallback
+ .mockResolvedValue({ summary: "Reviewed the diff", taskState: "completed" });
+ const summarizer = new DaemonSessionSummarizer(() => [], undefined, generate);
+ const state = makeState({ working: false });
+
+ summarizer.notifyActivity(state);
+ await vi.advanceTimersByTimeAsync(SETTLE_MS + 500);
+ expect(state.summaryState).toMatchObject({ summary: "", taskState: "needs_input" });
+
+ // A blank recap still owes a summary, so a later sweep retries and records it.
+ summarizer.notifyActivity(state);
+ await vi.advanceTimersByTimeAsync(SETTLE_MS + 500);
+ expect(generate).toHaveBeenCalledTimes(2);
+ expect(state.summaryState).toMatchObject({ summary: "Reviewed the diff", taskState: "completed" });
});
test("refreshes a working session even when the message count is unchanged", async () => {
diff --git a/packages/coding-agent/test/deferred-agent-connection.test.ts b/packages/coding-agent/test/deferred-agent-connection.test.ts
deleted file mode 100644
index 8dbb94d941..0000000000
--- a/packages/coding-agent/test/deferred-agent-connection.test.ts
+++ /dev/null
@@ -1,406 +0,0 @@
-import { describe, expect, test, vi } from "vitest";
-import {
- DeferredAgentConnection,
- type DeferredAgentConnectionSeed,
-} from "../src/modes/agent-connection/deferred-agent-connection.js";
-import type {
- AgentConnection,
- AgentConnectionEvent,
- AgentConnectionModel,
-} from "../src/modes/agent-connection/types.js";
-
-const MODEL = { provider: "anthropic", id: "claude-x" } as unknown as AgentConnectionModel;
-
-const SEED: DeferredAgentConnectionSeed = {
- cwd: "/tmp/project",
- sessionDir: "/tmp/sessions",
- model: MODEL,
- thinkingLevel: "off",
- scopedModels: [],
- availableModels: () => [MODEL],
- steeringMode: "all",
- followUpMode: "all",
- autoCompactionEnabled: true,
-};
-
-class FakeRealConnection {
- readonly listeners = new Set<(event: AgentConnectionEvent) => void>();
- readonly beforeInvalidate = new Set<() => void>();
- readonly promptCalls: string[] = [];
- disposed = false;
-
- subscribe(listener: (event: AgentConnectionEvent) => void): () => void {
- this.listeners.add(listener);
- return () => this.listeners.delete(listener);
- }
- onBeforeSessionInvalidate(listener: () => void): () => void {
- this.beforeInvalidate.add(listener);
- return () => this.beforeInvalidate.delete(listener);
- }
- emit(event: AgentConnectionEvent): void {
- for (const listener of [...this.listeners]) {
- listener(event);
- }
- }
- async getState() {
- return { sessionId: "real-session", activeSessionId: "real-session", cwd: "/tmp/project" };
- }
- async getMessages() {
- return [{ role: "user", content: "hi" }];
- }
- async prompt(message: string) {
- this.promptCalls.push(message);
- }
- async dispose() {
- this.disposed = true;
- }
-}
-
-function makeFactory(fake = new FakeRealConnection()) {
- const factory = vi.fn(async () => ({
- connection: fake as unknown as AgentConnection,
- activeSessionId: "real-session",
- }));
- return { factory, fake };
-}
-
-describe("DeferredAgentConnection", () => {
- test("serves local catalog and creates nothing for reads or dispose", async () => {
- const { factory } = makeFactory();
- const conn = new DeferredAgentConnection(factory, SEED);
-
- const state = await conn.getState();
- expect(state.model).toBe(MODEL);
- expect(state.cwd).toBe("/tmp/project");
- expect(state.messageCount).toBe(0);
- expect(await conn.getCommands()).toEqual([]);
- expect(await conn.getMessages()).toEqual([]);
- expect(await conn.getAvailableModels()).toEqual([MODEL]);
- expect(await conn.getQueue()).toEqual({ steering: [], followUp: [] });
- expect((await conn.getSessionStats()).totalMessages).toBe(0);
-
- await conn.dispose();
- expect(factory).not.toHaveBeenCalled();
- expect(conn.created).toBe(false);
- });
-
- test("derives available thinking levels from the seed model before a session exists", async () => {
- const reasoningModel = {
- provider: "anthropic",
- id: "claude-opus",
- reasoning: true,
- } as unknown as AgentConnectionModel;
- const { factory } = makeFactory();
- const conn = new DeferredAgentConnection(factory, { ...SEED, model: reasoningModel });
-
- const state = await conn.getState();
-
- expect(state.availableThinkingLevels).toContain("high");
- expect(state.availableThinkingLevels.length).toBeGreaterThan(1);
- expect(factory).not.toHaveBeenCalled();
- });
-
- test("reports no thinking levels for a non-reasoning seed model", async () => {
- const { factory } = makeFactory();
- const conn = new DeferredAgentConnection(factory, SEED);
-
- const state = await conn.getState();
-
- expect(state.availableThinkingLevels).toEqual(["off"]);
- });
-
- test("re-evaluates availableModels on each read so login during onboarding shows models", async () => {
- const { factory } = makeFactory();
- let models: AgentConnectionModel[] = [];
- const conn = new DeferredAgentConnection(factory, { ...SEED, availableModels: () => models });
-
- expect(await conn.getAvailableModels()).toEqual([]);
-
- models = [MODEL];
- expect(await conn.getAvailableModels()).toEqual([MODEL]);
- expect(factory).not.toHaveBeenCalled();
- });
-
- test("creates the session on first prompt and delegates", async () => {
- const { factory, fake } = makeFactory();
- const conn = new DeferredAgentConnection(factory, SEED);
- const events: AgentConnectionEvent[] = [];
- conn.subscribe((event) => {
- events.push(event);
- });
-
- await conn.prompt("do the thing");
-
- expect(factory).toHaveBeenCalledTimes(1);
- expect(fake.promptCalls).toEqual(["do the thing"]);
- expect(conn.created).toBe(true);
- expect(events.some((event) => event.type === "session_replaced")).toBe(true);
- });
-
- test("is single-flight when actions race the first creation", async () => {
- const { factory, fake } = makeFactory();
- const conn = new DeferredAgentConnection(factory, SEED);
-
- await Promise.all([conn.prompt("a"), conn.prompt("b")]);
-
- expect(factory).toHaveBeenCalledTimes(1);
- expect(fake.promptCalls.sort()).toEqual(["a", "b"]);
- });
-
- test("pipes real connection events through after promotion", async () => {
- const { fake, factory } = makeFactory();
- const conn = new DeferredAgentConnection(factory, SEED);
- const events: AgentConnectionEvent[] = [];
- conn.subscribe((event) => {
- events.push(event);
- });
-
- await conn.prompt("go");
- const replacedCount = events.filter((event) => event.type === "session_replaced").length;
- fake.emit({ type: "session_status", recap: "working" });
-
- expect(events.at(-1)).toEqual({ type: "session_status", recap: "working" });
- // Promotion emits exactly one session_replaced; later events are not re-replays.
- expect(replacedCount).toBe(1);
- });
-
- test("buffers onBeforeSessionInvalidate listeners until promotion", async () => {
- const { fake, factory } = makeFactory();
- const conn = new DeferredAgentConnection(factory, SEED);
- const listener = vi.fn();
- conn.onBeforeSessionInvalidate(listener);
-
- expect(fake.beforeInvalidate.size).toBe(0);
- await conn.prompt("go");
- expect(fake.beforeInvalidate.has(listener)).toBe(true);
- });
-
- test("dispose after creation tears down the real connection", async () => {
- const { fake, factory } = makeFactory();
- const conn = new DeferredAgentConnection(factory, SEED);
- const events: AgentConnectionEvent[] = [];
- conn.subscribe((event) => {
- events.push(event);
- });
- await conn.prompt("go");
-
- await conn.dispose();
- expect(fake.disposed).toBe(true);
-
- const countAfterDispose = events.length;
- fake.emit({ type: "session_status", recap: "late" });
- expect(events.length).toBe(countAfterDispose);
- });
-
- test("read-only stop actions never create a session", async () => {
- const { factory } = makeFactory();
- const conn = new DeferredAgentConnection(factory, SEED);
-
- await conn.abort();
- await conn.waitForIdle();
- await conn.abortBash();
- expect(await conn.cancelRlmChild("child")).toBe(false);
-
- expect(factory).not.toHaveBeenCalled();
- expect(conn.created).toBe(false);
- });
-
- test("disposes a session created while teardown was in flight", async () => {
- const fake = new FakeRealConnection();
- const discarded: string[] = [];
- type FactoryResult = { connection: AgentConnection; activeSessionId: string };
- let resolveFactory: (result: FactoryResult) => void = () => {};
- const factory = vi.fn(
- () =>
- new Promise<FactoryResult>((resolve) => {
- resolveFactory = resolve;
- }),
- );
- const conn = new DeferredAgentConnection(factory, SEED, async (id) => {
- discarded.push(id);
- });
-
- // Start promotion, then dispose before the factory resolves.
- const prompting = conn.prompt("go").catch(() => undefined);
- const disposing = conn.dispose();
- resolveFactory({ connection: fake as unknown as AgentConnection, activeSessionId: "real-session" });
- await Promise.all([prompting, disposing]);
-
- expect(fake.disposed).toBe(true);
- // The session the factory created during teardown is dropped, not orphaned.
- expect(discarded).toEqual(["real-session"]);
- // The aborted promotion never wires events through.
- const events: AgentConnectionEvent[] = [];
- conn.subscribe((event) => {
- events.push(event);
- });
- fake.emit({ type: "session_status", recap: "late" });
- expect(events).toEqual([]);
- });
-
- test("finishes the session_replaced handler before sending the triggering action", async () => {
- const order: string[] = [];
- const fake = new FakeRealConnection();
- const originalPrompt = fake.prompt.bind(fake);
- fake.prompt = async (message: string) => {
- order.push("prompt");
- return originalPrompt(message);
- };
- const conn = new DeferredAgentConnection(
- async () => ({ connection: fake as unknown as AgentConnection, activeSessionId: "real-session" }),
- SEED,
- );
- conn.subscribe(async (event) => {
- if (event.type === "session_replaced") {
- // Simulate the UI's async rebind work.
- await Promise.resolve();
- order.push("replaced");
- }
- });
-
- await conn.prompt("hi");
-
- // The action must not be sent until the UI has rebound, or its events
- // would double-render against the rebind.
- expect(order).toEqual(["replaced", "prompt"]);
- });
-
- test("discards an abandoned promoted session on dispose", async () => {
- const discarded: string[] = [];
- const conn = new DeferredAgentConnection(
- async () => ({
- connection: new FakeRealConnection() as unknown as AgentConnection,
- activeSessionId: "real-session",
- }),
- SEED,
- async (id) => {
- discarded.push(id);
- },
- );
-
- await conn.prompt("go"); // promotes the session
- await conn.dispose();
-
- expect(discarded).toEqual(["real-session"]);
- });
-
- test("does not attempt discard when never promoted", async () => {
- const discarded: string[] = [];
- const { factory } = makeFactory();
- const conn = new DeferredAgentConnection(factory, SEED, async (id) => {
- discarded.push(id);
- });
-
- await conn.dispose();
-
- expect(factory).not.toHaveBeenCalled();
- expect(discarded).toEqual([]);
- });
-
- test("does not half-promote when the initial state fetch fails", async () => {
- const fake = new FakeRealConnection();
- fake.getState = async () => {
- throw new Error("state fetch failed");
- };
- const discarded: string[] = [];
- const conn = new DeferredAgentConnection(
- async () => ({ connection: fake as unknown as AgentConnection, activeSessionId: "real-session" }),
- SEED,
- async (id) => {
- discarded.push(id);
- },
- );
-
- await expect(conn.prompt("go")).rejects.toThrow("state fetch failed");
- // The uncommitted connection was torn down and its orphaned daemon session
- // discarded, leaving nothing half-wired.
- expect(fake.disposed).toBe(true);
- expect(conn.created).toBe(false);
- expect(discarded).toEqual(["real-session"]);
- });
-
- test("getContextTree does not create a session", async () => {
- const { factory } = makeFactory();
- const conn = new DeferredAgentConnection(factory, SEED);
-
- const tree = await conn.getContextTree();
- expect(tree.children).toEqual([]);
- expect(factory).not.toHaveBeenCalled();
- expect(conn.created).toBe(false);
- });
-
- test("retries promotion after a failed first attempt", async () => {
- const fake = new FakeRealConnection();
- let attempt = 0;
- const factory = vi.fn(async () => {
- attempt += 1;
- if (attempt === 1) {
- throw new Error("daemon unavailable");
- }
- return { connection: fake as unknown as AgentConnection, activeSessionId: "real-session" };
- });
- const conn = new DeferredAgentConnection(factory, SEED);
-
- await expect(conn.prompt("first")).rejects.toThrow("daemon unavailable");
- await conn.prompt("second");
-
- expect(factory).toHaveBeenCalledTimes(2);
- expect(fake.promptCalls).toEqual(["second"]);
- });
-
- test("rolls back a partial commit so a later action retries", async () => {
- const fakes: FakeRealConnection[] = [];
- let attempt = 0;
- const factory = vi.fn(async () => {
- const fake = new FakeRealConnection();
- attempt += 1;
- if (attempt === 1) {
- // Throw after this.real is already assigned in promote().
- fake.subscribe = () => {
- throw new Error("subscribe failed");
- };
- }
- fakes.push(fake);
- return { connection: fake as unknown as AgentConnection, activeSessionId: "real-session" };
- });
- const conn = new DeferredAgentConnection(factory, SEED);
-
- await expect(conn.prompt("first")).rejects.toThrow("subscribe failed");
- expect(conn.created).toBe(false);
- expect(fakes[0].disposed).toBe(true);
-
- await conn.prompt("second");
- expect(factory).toHaveBeenCalledTimes(2);
- expect(conn.created).toBe(true);
- expect(fakes[1].promptCalls).toEqual(["second"]);
- });
-
- test("unsubscribing a before-invalidate listener after promotion detaches it from the real connection", async () => {
- const { fake, factory } = makeFactory();
- const conn = new DeferredAgentConnection(factory, SEED);
- const listener = vi.fn();
- const unsubscribe = conn.onBeforeSessionInvalidate(listener);
-
- await conn.prompt("go");
- expect(fake.beforeInvalidate.has(listener)).toBe(true);
-
- unsubscribe();
- expect(fake.beforeInvalidate.has(listener)).toBe(false);
- });
-});
-
-describe("DeferredAgentConnection with a real-style saved-session lister", () => {
- test("delegates saved-session listing once promoted", async () => {
- const saved = [{ id: "s1" }] as unknown as Awaited<ReturnType<AgentConnection["listSavedSessions"]>>;
- const fake = Object.assign(new FakeRealConnection(), {
- listSavedSessions: async () => saved,
- });
- const conn = new DeferredAgentConnection(
- async () => ({ connection: fake as unknown as AgentConnection, activeSessionId: "real-session" }),
- SEED,
- );
-
- await conn.prompt("go");
- expect(await conn.listSavedSessions("current")).toBe(saved);
- });
-});
diff --git a/packages/coding-agent/test/main-interactive-routing.test.ts b/packages/coding-agent/test/main-interactive-routing.test.ts
index 33fdcef03d..751aeda5db 100644
--- a/packages/coding-agent/test/main-interactive-routing.test.ts
+++ b/packages/coding-agent/test/main-interactive-routing.test.ts
@@ -144,7 +144,8 @@ describe("daemon-backed interactive session manager routing", () => {
findActiveDaemonSessionSummaryForInteractiveStartup("/tmp/prime.sock", "active-1", async () => ({
id: "active-1",
activeSessionId: "active-1",
- status: "idle",
+ lifecycle: "draft",
+ activity: "idle",
sessionId: "session-1",
cwd: "/tmp/project",
isStreaming: false,
@@ -282,7 +283,8 @@ describe("runtime session option resolution", () => {
function makeSessionSummary(overrides: Partial<SessionSummary>): SessionSummary {
return {
id: "session-1",
- status: "idle",
+ lifecycle: "draft",
+ activity: "idle",
sessionId: "session-1",
cwd: "/tmp/project",
isStreaming: false,
diff --git a/packages/coding-agent/test/session-manager/has-user-content.test.ts b/packages/coding-agent/test/session-manager/has-user-content.test.ts
new file mode 100644
index 0000000000..1dbb908791
--- /dev/null
+++ b/packages/coding-agent/test/session-manager/has-user-content.test.ts
@@ -0,0 +1,77 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import { SessionManager } from "../../src/core/session-manager.js";
+import { userMsg } from "../utilities.js";
+
+describe("SessionManager.hasUserContent", () => {
+ function withSession(run: (session: SessionManager) => void): void {
+ const tempDir = mkdtempSync(join(tmpdir(), "has-user-content-"));
+ try {
+ run(SessionManager.create(join(tempDir, "project"), join(tempDir, "sessions")));
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ }
+
+ it("is false for a fresh session with only the default model and thinking entries", () => {
+ withSession((session) => {
+ // What createAgentSession writes for every new session.
+ session.appendModelChange("anthropic", "claude-opus-4-8");
+ session.appendThinkingLevelChange("off");
+ expect(session.hasUserContent()).toBe(false);
+ });
+ });
+
+ it("is true once the user changes the model after creation", () => {
+ withSession((session) => {
+ session.appendModelChange("anthropic", "claude-opus-4-8");
+ session.appendThinkingLevelChange("off");
+ session.appendModelChange("openai", "gpt-5");
+ expect(session.hasUserContent()).toBe(true);
+ });
+ });
+
+ it("is true once the user changes the thinking level after creation", () => {
+ withSession((session) => {
+ session.appendModelChange("anthropic", "claude-opus-4-8");
+ session.appendThinkingLevelChange("off");
+ session.appendThinkingLevelChange("high");
+ expect(session.hasUserContent()).toBe(true);
+ });
+ });
+
+ it("is false for a fresh session created with no model available (thinking entry only)", () => {
+ withSession((session) => {
+ // createAgentSession skips the model_change when no model is configured,
+ // leaving a lone leading thinking_level_change as the creation default.
+ session.appendThinkingLevelChange("off");
+ expect(session.hasUserContent()).toBe(false);
+ });
+ });
+
+ it("is true once the user changes the thinking level on a no-model session", () => {
+ withSession((session) => {
+ session.appendThinkingLevelChange("off");
+ session.appendThinkingLevelChange("high");
+ expect(session.hasUserContent()).toBe(true);
+ });
+ });
+
+ it("is true for a session with a message", () => {
+ withSession((session) => {
+ session.appendMessage(userMsg("hello"));
+ expect(session.hasUserContent()).toBe(true);
+ });
+ });
+
+ it("is true once the session is named", () => {
+ withSession((session) => {
+ session.appendModelChange("anthropic", "claude-opus-4-8");
+ session.appendThinkingLevelChange("off");
+ session.appendSessionInfo("my draft");
+ expect(session.hasUserContent()).toBe(true);
+ });
+ });
+});
diff --git a/packages/coding-agent/test/session-manager/session-state.test.ts b/packages/coding-agent/test/session-manager/session-state.test.ts
index 8e66284067..2babcada64 100644
--- a/packages/coding-agent/test/session-manager/session-state.test.ts
+++ b/packages/coding-agent/test/session-manager/session-state.test.ts
@@ -47,7 +47,7 @@ describe("SessionManager session state", () => {
const session = SessionManager.create(cwd, sessionDir);
session.appendSessionInfo("empty");
- session.appendSessionState({ status: "sleep" });
+ session.appendSessionState({ status: "archived" });
const sessionFile = session.getSessionFile();
expect(sessionFile).toBeDefined();
@@ -59,14 +59,14 @@ describe("SessionManager session state", () => {
id: session.getSessionId(),
name: "empty",
messageCount: 0,
- state: { status: "sleep" },
+ state: { status: "archived" },
});
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});
- it("coerces legacy hidden lifecycle state to sleep on read", async () => {
+ it("coerces legacy sleep and hidden lifecycle state to archived on read", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "session-state-hidden-"));
try {
const cwd = join(tempDir, "project");
@@ -74,18 +74,21 @@ describe("SessionManager session state", () => {
const session = SessionManager.create(cwd, sessionDir);
session.appendMessage(userMsg("hide me"));
- session.appendSessionState({ status: "sleep" });
+ // Flush a header + state entry, then append the legacy raw "sleep"/"hidden"
+ // entries older daemons wrote; both must normalize to "archived" on read.
+ session.appendSessionState({ status: "active" });
const sessionFile = session.getSessionFile();
expect(sessionFile).toBeDefined();
+ appendFileSync(sessionFile!, `${JSON.stringify({ type: "session_state", state: { status: "sleep" } })}\n`);
appendFileSync(sessionFile!, `${JSON.stringify({ type: "session_state", state: { status: "hidden" } })}\n`);
- expect(SessionManager.open(sessionFile!, sessionDir).getSessionState()).toEqual({ status: "sleep" });
+ expect(SessionManager.open(sessionFile!, sessionDir).getSessionState()).toEqual({ status: "archived" });
const sessions = await SessionManager.list(cwd, sessionDir);
expect(sessions).toHaveLength(1);
expect(sessions[0]).toMatchObject({
id: session.getSessionId(),
- state: { status: "sleep" },
+ state: { status: "archived" },
});
} finally {
rmSync(tempDir, { recursive: true, force: true });
@@ -121,7 +124,7 @@ describe("SessionManager session state", () => {
const sessionDir = join(tempDir, "sessions");
const session = SessionManager.create(cwd, sessionDir);
- session.appendSessionState({ status: "sleep" });
+ session.appendSessionState({ status: "archived" });
session.appendMessage(userMsg("hello"));
session.appendMessage(assistantMsg("hi"));
@@ -146,7 +149,7 @@ describe("SessionManager session state", () => {
expect(sessionFile).toBeDefined();
rmSync(sessionDir, { recursive: true, force: true });
- session.appendSessionState({ status: "sleep" });
+ session.appendSessionState({ status: "archived" });
expect(existsSync(sessionFile!)).toBe(true);
const entries = loadEntriesFromFile(sessionFile!);
@@ -171,7 +174,7 @@ describe("SessionManager session state", () => {
expect(existsSync(sessionFile!)).toBe(true);
rmSync(sessionFile!, { force: true });
- session.appendSessionState({ status: "sleep" });
+ session.appendSessionState({ status: "archived" });
const entries = loadEntriesFromFile(sessionFile!);
expect(entries[0]).toMatchObject({ type: "session", id: session.getSessionId() });