Skip to content

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

Rust

fix broken sessions in agents view from missing directories (#287)

kt71a398762c73
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 bf89a69f16..216c3e62f0 100644
--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
@@ -1,3 +1,4 @@
+import { existsSync } from "node:fs";
import type { Api, ImageContent, Model } from "@earendil-works/pi-ai";
import type { AutocompleteItem, OverlayHandle, SlashCommand } from "@earendil-works/pi-tui";
import {
@@ -137,9 +138,18 @@ export async function resolveAgentsViewSessionUiServices(
return options.createUiServicesForSession ? await options.createUiServicesForSession(summary) : options.uiServices;
}
-export function createAgentsViewResumeConfig(config: AgentSessionRuntimeConfig): AgentSessionRuntimeConfig {
+// Stripping cwd opens the session in its own stored directory; overrideCwd is
+// sent when that directory no longer exists so the daemon doesn't reject it.
+export function createAgentsViewResumeConfig(
+ config: AgentSessionRuntimeConfig,
+ overrideCwd?: string,
+): AgentSessionRuntimeConfig {
const resumeConfig: AgentSessionRuntimeConfig = { ...config };
- delete resumeConfig.cwd;
+ if (overrideCwd) {
+ resumeConfig.cwd = overrideCwd;
+ } else {
+ delete resumeConfig.cwd;
+ }
return resumeConfig;
}
@@ -170,10 +180,29 @@ export function createAgentsViewReplyHeadline(text: string | undefined): string
.find((line) => line.length > 0);
}
+interface OpenedAgentsViewSession {
+ connection: DaemonAgentConnection;
+ summary: SessionSummary;
+ cwdFallbackNotice?: string;
+}
+
+export function resolveAgentsViewOpenCwd(
+ summary: SessionSummary,
+ fallbackCwd: string | undefined,
+): { overrideCwd?: string; notice?: string } {
+ if (!summary.cwd || existsSync(summary.cwd) || !fallbackCwd) {
+ return {};
+ }
+ return {
+ overrideCwd: fallbackCwd,
+ notice: `Original directory is missing (${summary.cwd}); opened in ${fallbackCwd} instead.`,
+ };
+}
+
async function openAgentsViewSession(
options: AgentsViewModeOptions,
summary: SessionSummary,
-): Promise<{ connection: DaemonAgentConnection; summary: SessionSummary }> {
+): Promise<OpenedAgentsViewSession> {
let client = await connectAgentsViewDaemonClient(options.socketPath);
if (summary.activeSessionId) {
try {
@@ -195,10 +224,11 @@ async function openAgentsViewSession(
throw new Error("Cannot open agent without an active runtime or saved session file");
}
+ const { overrideCwd, notice } = resolveAgentsViewOpenCwd(summary, options.config.cwd);
try {
const response = await client.request({
type: "create",
- config: createAgentsViewResumeConfig(options.config),
+ config: createAgentsViewResumeConfig(options.config, overrideCwd),
sessionPath: summary.sessionFile,
});
const createdSummary = expectSessionSummary(requireDaemonData(response));
@@ -206,7 +236,7 @@ async function openAgentsViewSession(
const connection = await DaemonAgentConnection.attach(client, activeSessionId, {
closeClientOnDispose: true,
});
- return { connection, summary: createdSummary };
+ return { connection, summary: createdSummary, cwdFallbackNotice: notice };
} catch (error) {
client.close();
throw error;
@@ -256,9 +286,12 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): Promise
persistentState.pendingExpandedAncestorSessionIds = undefined;
}
- let opened: { connection: DaemonAgentConnection; summary: SessionSummary } | undefined;
+ let opened: OpenedAgentsViewSession | undefined;
try {
opened = await openAgentsViewSession(options, result.summary);
+ if (opened.cwdFallbackNotice) {
+ persistentState.statusMessage = opened.cwdFallbackNotice;
+ }
const uiServices = await resolveAgentsViewSessionUiServices(options, opened.summary);
const interactiveMode = new InteractiveMode({
agentConnection: opened.connection,
@@ -266,6 +299,7 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): Promise
bindLocalSessionExtensions: false,
migratedProviders: options.migratedProviders,
modelFallbackMessage: resolveAttachModelFallbackMessage(opened.summary, options.modelFallbackMessage),
+ startupNotice: opened.cwdFallbackNotice,
verbose: options.verbose,
returnToAgentsView: true,
// The agents view renders the global notices itself, so suppress them in-session.
@@ -1439,13 +1473,13 @@ class AgentsViewMode implements Component, Focusable {
}
}
}
- if (pending.sessionFile) {
- // 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.
+ // Skip a file deleted between listing and now: SessionManager.open would
+ // recreate a stub at the old path instead of loading it.
+ if (pending.sessionFile && existsSync(pending.sessionFile)) {
+ // Persist archived unless it already is: sessions with no prior
+ // session_state entry would otherwise resurface on the next scan.
const sessionManager = SessionManager.open(pending.sessionFile, this.options.config.sessionDir);
- if (sessionManager.getSessionState()?.status === "active") {
+ if (sessionManager.getSessionState()?.status !== "archived") {
sessionManager.appendSessionState({ status: "archived" });
}
}
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index a9cea56394..088fdb65ef 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -450,6 +450,8 @@ export interface InteractiveModeOptions {
migratedProviders?: string[];
/** Warning message if session model couldn't be restored */
modelFallbackMessage?: string;
+ /** One-off warning shown on startup. */
+ startupNotice?: string;
/** Initial message to send on startup (can include @file content) */
initialMessage?: string;
/** Images to attach to the initial message */
@@ -1059,6 +1061,10 @@ export class InteractiveMode {
this.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(", ")}`);
}
+ if (this.options.startupNotice) {
+ this.showWarning(this.options.startupNotice);
+ }
+
const modelsJsonError = this.modelRegistry.getError();
if (modelsJsonError) {
this.showError(`models.json error: ${modelsJsonError}`);
diff --git a/packages/coding-agent/test/agents-view-missing-cwd.test.ts b/packages/coding-agent/test/agents-view-missing-cwd.test.ts
new file mode 100644
index 0000000000..a84ce57d02
--- /dev/null
+++ b/packages/coding-agent/test/agents-view-missing-cwd.test.ts
@@ -0,0 +1,81 @@
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import { createAgentSessionRuntime } from "../src/core/agent-session-runtime.js";
+import { MissingSessionCwdError } from "../src/core/session-cwd.js";
+import { SessionManager } from "../src/core/session-manager.js";
+import { createAgentsViewResumeConfig, resolveAgentsViewOpenCwd } from "../src/modes/agents-view/agents-view-mode.js";
+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
+import { assistantMsg, userMsg } from "./utilities.js";
+
+describe("agents view open with a missing session cwd", () => {
+ it("repros the failure and proves the override opens the session", async () => {
+ const root = mkdtempSync(join(tmpdir(), "agents-view-missing-cwd-"));
+ const launchCwd = join(root, "launch");
+ const worktree = join(root, "worktree");
+ const sessionDir = join(root, "sessions");
+ const agentDir = join(root, "agent");
+ try {
+ mkdirSync(launchCwd, { recursive: true });
+ const session = SessionManager.create(worktree, sessionDir);
+ session.appendMessage(userMsg("do the thing"));
+ session.appendMessage(assistantMsg("done"));
+ const sessionFile = session.getSessionFile()!;
+
+ rmSync(worktree, { recursive: true, force: true });
+
+ const factory = async () => {
+ throw new Error("runtime factory should not be reached when the cwd is missing");
+ };
+
+ // With cwd stripped, the session resolves against its deleted cwd and throws.
+ const stripped = await SessionManager.openAsync(sessionFile, sessionDir);
+ await expect(
+ createAgentSessionRuntime(factory, {
+ cwd: stripped.getCwd(),
+ agentDir,
+ sessionManager: stripped,
+ }),
+ ).rejects.toThrowError(MissingSessionCwdError);
+
+ const summary: SessionSummary = {
+ id: session.getSessionId(),
+ lifecycle: "live",
+ activity: "idle",
+ sessionId: session.getSessionId(),
+ sessionFile,
+ cwd: worktree,
+ isStreaming: false,
+ isCompacting: false,
+ attachedClients: 0,
+ messageCount: 2,
+ pendingMessageCount: 0,
+ };
+ const { overrideCwd, notice } = resolveAgentsViewOpenCwd(summary, launchCwd);
+ expect(overrideCwd).toBe(launchCwd);
+ expect(notice).toContain(worktree);
+
+ const resumeConfig = createAgentsViewResumeConfig({ cwd: launchCwd, agentDir }, overrideCwd);
+ const overridden = await SessionManager.openAsync(sessionFile, sessionDir, resumeConfig.cwd);
+ expect(overridden.getCwd()).toBe(launchCwd);
+
+ // The override gets the build past the cwd guard and into the factory.
+ let factoryCwd: string | undefined;
+ const okFactory = async (opts: { cwd: string }) => {
+ factoryCwd = opts.cwd;
+ throw new Error("stop after the cwd guard");
+ };
+ await expect(
+ createAgentSessionRuntime(okFactory as never, {
+ cwd: overridden.getCwd(),
+ agentDir,
+ sessionManager: overridden,
+ }),
+ ).rejects.toThrow("stop after the cwd guard");
+ expect(factoryCwd).toBe(launchCwd);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index 4a754f7fe8..54d287d7ab 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -1,3 +1,6 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { describe, expect, test, vi } from "vitest";
import type { AgentSessionRuntimeConfig } from "../src/core/agent-session-config.js";
import type { ModelRegistry } from "../src/core/model-registry.js";
@@ -9,6 +12,7 @@ import {
createAgentsViewSessionName,
formatAgentsViewRelativeTime,
formatAgentsViewStatusLine,
+ resolveAgentsViewOpenCwd,
resolveAgentsViewSessionUiServices,
} from "../src/modes/agents-view/agents-view-mode.js";
import {
@@ -474,6 +478,34 @@ describe("agents view state", () => {
expect(config.cwd).toBe("/tmp/dashboard");
});
+ test("opens an existing-cwd session in its own directory with no override or notice", () => {
+ const dir = mkdtempSync(join(tmpdir(), "agents-view-cwd-"));
+ try {
+ expect(resolveAgentsViewOpenCwd(makeSummary({ cwd: dir }), "/tmp/launch")).toEqual({});
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("falls back to the launch cwd and explains it when the stored cwd is gone", () => {
+ const missing = join(tmpdir(), "agents-view-missing-worktree-does-not-exist");
+ const { overrideCwd, notice } = resolveAgentsViewOpenCwd(makeSummary({ cwd: missing }), "/tmp/launch");
+ expect(overrideCwd).toBe("/tmp/launch");
+ expect(notice).toContain(missing);
+ expect(notice).toContain("/tmp/launch");
+ });
+
+ test("does not override when there is no fallback cwd to use", () => {
+ const missing = join(tmpdir(), "agents-view-missing-worktree-does-not-exist");
+ expect(resolveAgentsViewOpenCwd(makeSummary({ cwd: missing }), undefined)).toEqual({});
+ });
+
+ test("passes the override cwd through the resume config when the stored cwd is missing", () => {
+ const config: AgentSessionRuntimeConfig = { cwd: "/tmp/launch", agentDir: "/tmp/agents" };
+ const resumeConfig = createAgentsViewResumeConfig(config, "/tmp/launch");
+ expect(resumeConfig.cwd).toBe("/tmp/launch");
+ });
+
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({
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 2babcada64..fe8b633be6 100644
--- a/packages/coding-agent/test/session-manager/session-state.test.ts
+++ b/packages/coding-agent/test/session-manager/session-state.test.ts
@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { loadEntriesFromFile, SessionManager, type SessionStateEntry } from "../../src/core/session-manager.js";
+import { inactiveLifecycleForSession } from "../../src/modes/daemon/daemon-session-list.js";
import { assistantMsg, userMsg } from "../utilities.js";
describe("SessionManager session state", () => {
@@ -66,6 +67,60 @@ describe("SessionManager session state", () => {
}
});
+ it("archives a deactivated session that has no prior state entry", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "session-state-deactivate-"));
+ try {
+ const cwd = join(tempDir, "project");
+ const sessionDir = join(tempDir, "sessions");
+ const session = SessionManager.create(cwd, sessionDir);
+ session.appendMessage(userMsg("hello"));
+ session.appendMessage(assistantMsg("hi"));
+ const sessionFile = session.getSessionFile()!;
+
+ const reopened = SessionManager.open(sessionFile, sessionDir);
+ expect(reopened.getSessionState()).toBeUndefined();
+ if (reopened.getSessionState()?.status !== "archived") {
+ reopened.appendSessionState({ status: "archived" });
+ }
+
+ const sessions = await SessionManager.list(cwd, sessionDir);
+ expect(sessions).toHaveLength(1);
+ expect(sessions[0]!.state).toEqual({ status: "archived" });
+ expect(inactiveLifecycleForSession(sessions[0]!)).toBe("archived");
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ // Guards the agents-view deactivate path: opening a deleted file and appending
+ // would recreate a stub session at the old path, so the caller must skip it.
+ it("recreates a stub when archiving a deleted file, which the existsSync guard prevents", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "session-state-deleted-"));
+ try {
+ const cwd = join(tempDir, "project");
+ const sessionDir = join(tempDir, "sessions");
+ const session = SessionManager.create(cwd, sessionDir);
+ session.appendMessage(userMsg("hello"));
+ session.appendMessage(assistantMsg("hi")); // forces a flush to disk
+ const sessionFile = session.getSessionFile()!;
+ rmSync(sessionFile);
+ expect(existsSync(sessionFile)).toBe(false);
+
+ // Without the guard, the open+append recreates a fresh stub on disk.
+ SessionManager.open(sessionFile, sessionDir).appendSessionState({ status: "archived" });
+ expect(existsSync(sessionFile)).toBe(true);
+
+ // The guard the caller uses skips a missing file, leaving nothing behind.
+ rmSync(sessionFile);
+ if (existsSync(sessionFile)) {
+ SessionManager.open(sessionFile, sessionDir).appendSessionState({ status: "archived" });
+ }
+ expect(existsSync(sessionFile)).toBe(false);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
it("coerces legacy sleep and hidden lifecycle state to archived on read", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "session-state-hidden-"));
try {