Skip to content

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

Rust

stop silent daemon replacement from looking like random crashes (#233)

kt2dd75cab11b8
diff --git a/packages/coding-agent/src/cli/daemon-launch.ts b/packages/coding-agent/src/cli/daemon-launch.ts
index 81cd4c589a..785e3d9a2b 100644
--- a/packages/coding-agent/src/cli/daemon-launch.ts
+++ b/packages/coding-agent/src/cli/daemon-launch.ts
@@ -10,7 +10,7 @@
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { resolve } from "node:path";
-import { expandTildePath, VERSION } from "../config.js";
+import { appendRotatingLog, expandTildePath, getClientErrorLogPath, VERSION } from "../config.js";
import { DaemonClient } from "../modes/daemon/daemon-client.js";
import { DAEMON_PROTOCOL_VERSION } from "../modes/daemon/daemon-protocol.js";
import type { SessionSummary } from "../modes/daemon/daemon-session-list.js";
@@ -28,6 +28,13 @@ function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+// Daemon replacement used to be silent (no crash, no log), so a daemon dying
+// out from under another window looked "random". Trace the decisions to the
+// client-errors log so replacements are attributable after the fact.
+function logDaemonLaunch(message: string): void {
+ appendRotatingLog(getClientErrorLogPath(), `[${new Date().toISOString()}] daemon-launch: ${message}`);
+}
+
async function canConnectToDaemon(socketPath: string, timeoutMs: number): Promise<boolean> {
const client = new DaemonClient(socketPath);
try {
@@ -54,9 +61,16 @@ async function probeDaemonVersion(socketPath: string): Promise<DaemonVersionProb
try {
const hello = await client.waitForHello(2000);
const current = hello.protocol.version === DAEMON_PROTOCOL_VERSION && hello.appVersion === VERSION;
+ if (!current) {
+ logDaemonLaunch(
+ `running daemon on ${socketPath} is stale: daemon v${hello.appVersion}/proto${hello.protocol.version} ` +
+ `vs client v${VERSION}/proto${DAEMON_PROTOCOL_VERSION}`,
+ );
+ }
return current ? "current" : "stale";
} catch {
// Connected but no recognizable greeting: assume a stale daemon.
+ logDaemonLaunch(`running daemon on ${socketPath} sent no recognizable hello; treating as stale`);
return "stale";
} finally {
client.close();
@@ -151,11 +165,13 @@ async function shutdownStaleDaemonIfNotBusy(socketPath: string): Promise<boolean
const client = new DaemonClient(socketPath);
let connected = false;
let hasBusySessions = false;
+ let loadedSessionCount = 0;
try {
await client.connect(1000);
connected = true;
try {
const summaries = await listActiveDaemonSessionSummaries(client);
+ loadedSessionCount = summaries.length;
hasBusySessions = summaries.some(isSessionBusy);
} catch {
// Couldn't confirm idleness: treat as busy rather than risk interrupting work.
@@ -171,8 +187,12 @@ async function shutdownStaleDaemonIfNotBusy(socketPath: string): Promise<boolean
return waitForDaemonGone(socketPath);
}
if (hasBusySessions) {
+ logDaemonLaunch(`refusing to replace stale daemon on ${socketPath}: busy session(s) present`);
return false;
}
+ logDaemonLaunch(
+ `replacing stale daemon on ${socketPath} (idle): ${loadedSessionCount} loaded session(s) will reload`,
+ );
return shutdownDaemonAndWait(socketPath);
}
diff --git a/packages/coding-agent/src/cli/daemon-list-format.ts b/packages/coding-agent/src/cli/daemon-list-format.ts
index aedf45e31c..fc0479c58d 100644
--- a/packages/coding-agent/src/cli/daemon-list-format.ts
+++ b/packages/coding-agent/src/cli/daemon-list-format.ts
@@ -10,7 +10,6 @@ const LIST_STATUS_ORDER: Record<SessionStatus, number> = {
active: 4,
sleep: 5,
crash: 6,
- hidden: 7,
};
type ListRow = {
@@ -61,7 +60,6 @@ function formatListCell(row: ListRow, column: keyof ListRow, value: string): str
case "active":
case "sleep":
case "crash":
- case "hidden":
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 0783f8f91a..59c37c4bb8 100644
--- a/packages/coding-agent/src/core/session-manager.ts
+++ b/packages/coding-agent/src/core/session-manager.ts
@@ -138,7 +138,7 @@ export interface SessionInfoEntry extends SessionEntryBase {
name?: string;
}
-export type SessionStateStatus = "active" | "sleep" | "crash" | "hidden";
+export type SessionStateStatus = "active" | "sleep" | "crash";
export interface SessionState {
status: SessionStateStatus;
@@ -699,8 +699,15 @@ function extractTextContent(message: Message): string {
.join(" ");
}
-function isSessionStateStatus(value: unknown): value is SessionStateStatus {
- return value === "active" || value === "sleep" || value === "crash" || value === "hidden";
+// Legacy "hidden" status is coerced to "sleep" for sessions written by older versions.
+function normalizeSessionStateStatus(value: unknown): SessionStateStatus | undefined {
+ if (value === "active" || value === "sleep" || value === "crash") {
+ return value;
+ }
+ if (value === "hidden") {
+ return "sleep";
+ }
+ return undefined;
}
function updateLastActivityTime(lastActivityTime: number | undefined, entry: FileEntry): number | undefined {
@@ -899,8 +906,9 @@ async function scanSessionInfo(filePath: string, stats: Awaited<ReturnType<typeo
}
if (entry.type === "session_state") {
const stateEntry = entry as SessionStateEntry;
- if (isSessionStateStatus(stateEntry.state?.status)) {
- state = { status: stateEntry.state.status };
+ const status = normalizeSessionStateStatus(stateEntry.state?.status);
+ if (status) {
+ state = { status };
}
}
@@ -1370,7 +1378,10 @@ export class SessionManager {
for (let i = entries.length - 1; i >= 0; i--) {
const entry = entries[i];
if (entry.type === "session_state") {
- return { status: entry.state.status };
+ const status = normalizeSessionStateStatus(entry.state.status);
+ if (status) {
+ return { status };
+ }
}
}
return undefined;
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index 7214a699c8..7b26141254 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" | "hidden";
+export type AgentConnectionSavedSessionStateStatus = "active" | "sleep" | "crash";
export type AgentConnectionSourceScope = "user" | "project" | "temporary";
export type AgentConnectionSourceOrigin = "package" | "top-level";
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 3fe82f608f..fd8b00ab31 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -389,11 +389,6 @@ export class AgentDaemon {
this.rebindCronJobsToState(existing);
return existing;
}
- if ((sessionPath || command.continueRecent) && sessionManager.getSessionState()?.status === "hidden") {
- // Resuming a hidden session is the intentional opt-in that makes it
- // visible in session lists again.
- sessionManager.appendSessionState({ status: "sleep" });
- }
let stateRef: ActiveSessionState | undefined;
const runtime = await createAgentSessionRuntime(this.options.createRuntime, {
cwd: sessionManager.getCwd(),
@@ -1411,6 +1406,7 @@ export class AgentDaemon {
}
case "shutdown":
+ this.log(`shutdown command received over socket; ${this.sessions.size} active session(s) will be closed`);
setImmediate(() => {
void this.shutdown(0);
});
@@ -1623,6 +1619,7 @@ export class AgentDaemon {
}
for (const signal of signals) {
const handler = () => {
+ this.log(`received ${signal}; shutting down`);
killTrackedDetachedChildren();
void this.shutdown(signal === "SIGINT" ? 130 : signal === "SIGHUP" ? 129 : 143);
};
@@ -1639,6 +1636,7 @@ export class AgentDaemon {
process.exit(exitCode);
}
this.shuttingDown = true;
+ this.log(`shutting down (exit ${exitCode}); closing ${this.sessions.size} active session(s)`);
this.summarizer.stop();
for (const cleanup of this.signalCleanupHandlers) {
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index 401d274ea2..f425d1f6ba 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -373,12 +373,9 @@ describe("agents view state", () => {
});
test("shows daemon-resident sessions only", () => {
- const inactiveHidden = makeSummary({ status: "hidden" });
const inactiveSleep = makeSummary({ status: "sleep" });
- delete inactiveHidden.activeSessionId;
delete inactiveSleep.activeSessionId;
- expect(shouldShowAgentsViewSession(inactiveHidden)).toBe(false);
expect(shouldShowAgentsViewSession(inactiveSleep)).toBe(false);
expect(shouldShowAgentsViewSession(makeSummary({ status: "idle" }))).toBe(true);
expect(shouldShowAgentsViewSession(makeSummary({ status: "idle" }), true)).toBe(false);
diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.ts
index 3bd0359c38..0d244117b3 100644
--- a/packages/coding-agent/test/daemon-session-list.test.ts
+++ b/packages/coding-agent/test/daemon-session-list.test.ts
@@ -39,12 +39,10 @@ describe("buildSessionList", () => {
const activePath = resolve("/tmp/project/active.jsonl");
const sleepingPath = resolve("/tmp/project/sleeping.jsonl");
const crashedPath = resolve("/tmp/project/crashed.jsonl");
- const hiddenPath = resolve("/tmp/project/hidden.jsonl");
const savedSessions = [
makeSessionInfo({ path: activePath, id: "saved-active", name: "active saved" }),
makeSessionInfo({ path: sleepingPath, id: "saved-sleeping", name: "sleeping saved" }),
makeSessionInfo({ path: crashedPath, id: "saved-crashed", state: { status: "crash" } }),
- makeSessionInfo({ path: hiddenPath, id: "saved-hidden", state: { status: "hidden" } }),
];
const entries = buildSessionList(
@@ -52,12 +50,11 @@ describe("buildSessionList", () => {
savedSessions,
);
- expect(entries).toHaveLength(4);
+ 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"],
- ["saved-hidden", "saved-hidden", "hidden"],
]);
expect(entries[0]!.sessionName).toBe("session active-1");
});
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 dc02157a32..8e66284067 100644
--- a/packages/coding-agent/test/session-manager/session-state.test.ts
+++ b/packages/coding-agent/test/session-manager/session-state.test.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { appendFileSync, existsSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -66,7 +66,7 @@ describe("SessionManager session state", () => {
}
});
- it("persists hidden lifecycle state for sessions hidden from agents view", async () => {
+ it("coerces legacy hidden lifecycle state to sleep on read", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "session-state-hidden-"));
try {
const cwd = join(tempDir, "project");
@@ -74,24 +74,46 @@ describe("SessionManager session state", () => {
const session = SessionManager.create(cwd, sessionDir);
session.appendMessage(userMsg("hide me"));
- session.appendSessionState({ status: "hidden" });
-
+ session.appendSessionState({ status: "sleep" });
const sessionFile = session.getSessionFile();
expect(sessionFile).toBeDefined();
- expect(existsSync(sessionFile!)).toBe(true);
- expect(session.getSessionState()).toEqual({ status: "hidden" });
+ appendFileSync(sessionFile!, `${JSON.stringify({ type: "session_state", state: { status: "hidden" } })}\n`);
+
+ expect(SessionManager.open(sessionFile!, sessionDir).getSessionState()).toEqual({ status: "sleep" });
const sessions = await SessionManager.list(cwd, sessionDir);
expect(sessions).toHaveLength(1);
expect(sessions[0]).toMatchObject({
id: session.getSessionId(),
- state: { status: "hidden" },
+ state: { status: "sleep" },
});
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});
+ it("falls back to the last valid status when the newest entry is unrecognized", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "session-state-bad-"));
+ try {
+ const cwd = join(tempDir, "project");
+ const sessionDir = join(tempDir, "sessions");
+ const session = SessionManager.create(cwd, sessionDir);
+
+ session.appendMessage(userMsg("hi"));
+ session.appendSessionState({ status: "active" });
+ const sessionFile = session.getSessionFile();
+ expect(sessionFile).toBeDefined();
+ appendFileSync(sessionFile!, `${JSON.stringify({ type: "session_state", state: { status: "bogus" } })}\n`);
+
+ expect(SessionManager.open(sessionFile!, sessionDir).getSessionState()).toEqual({ status: "active" });
+
+ const sessions = await SessionManager.list(cwd, sessionDir);
+ expect(sessions[0]).toMatchObject({ id: session.getSessionId(), state: { status: "active" } });
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
it("does not duplicate entries when lifecycle state is followed by a normal turn", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "session-state-turn-"));
try {