Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

fix(daemon): defer restarts asked while the engine starts

Alan Buscaglia6a5a0e4e2bef
diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.ts
index 7f44b96..08ecbfe 100644
--- a/packages/daemon/src/bridge.ts
+++ b/packages/daemon/src/bridge.ts
@@ -1362,7 +1362,8 @@ export class DotBridge {
case "restarting":
return "restarting";
case "stopped":
- return "error";
+ // Before the engine was asked to start (the daemon waits for the connectors key), it is starting.
+ return this.supervisor.launched ? "error" : "starting";
}
if (this.asks.size > 0) return "needs_you";
if (!this.supervisor.busy) return "idle";
diff --git a/packages/daemon/src/supervisor.ts b/packages/daemon/src/supervisor.ts
index 7a955a5..320cc67 100644
--- a/packages/daemon/src/supervisor.ts
+++ b/packages/daemon/src/supervisor.ts
@@ -86,6 +86,13 @@ export class AgentSupervisor {
private restarting = false;
private interrupted = false;
private restartTimer: NodeJS.Timeout | undefined;
+ /** The spawn whose engine has not answered yet, while there is one. */
+ private initializing: Promise<void> | undefined;
+ /** A restart asked while an engine starts, run once that start settles. */
+ private queuedRestart: Promise<void> | undefined;
+ /** A restart closing the old process; the engine it starts next comes after any request made meanwhile. */
+ private replacing: Promise<void> | undefined;
+ private wasLaunched = false;
private closeWaiters: (() => void)[] = [];
/** For a session started by rotation, the session files it continues, oldest first. */
private chains: Record<string, string[]> = {};
@@ -100,6 +107,11 @@ export class AgentSupervisor {
this.sessionFile = this.readPersistedSession();
}
+ /** Whether `start()` or `stop()` was called: before that, `stopped` only means not started yet. */
+ get launched(): boolean {
+ return this.wasLaunched;
+ }
+
get pid(): number | undefined {
return this.child?.pid;
}
@@ -123,9 +135,10 @@ export class AgentSupervisor {
/** Spawns the agent and resolves once it answered `get_state`. */
async start(): Promise<void> {
this.stopping = false;
+ this.wasLaunched = true;
mkdirSync(this.sessionDir, { recursive: true });
this.setState("starting");
- await this.spawnAndInitialize();
+ await this.initialize();
}
/** Sends a command and resolves with its successful response. */
@@ -157,8 +170,29 @@ export class AgentSupervisor {
/**
* Replaces the agent process on purpose (for example after new credentials),
* reopening the same conversation. Not reported as an interruption.
+ * An engine still starting is not cut off: it is replaced once that start settles,
+ * once for any number of requests made meanwhile.
*/
- async restart(): Promise<void> {
+ restart(): Promise<void> {
+ if (this.stopping) return Promise.resolve();
+ if (this.initializing) {
+ this.queuedRestart ??= this.initializing
+ .catch(() => {})
+ .then(() => {
+ this.queuedRestart = undefined;
+ return this.restart();
+ });
+ return this.queuedRestart;
+ }
+ if (this.replacing) return this.replacing;
+ const replacing = this.replace().finally(() => {
+ if (this.replacing === replacing) this.replacing = undefined;
+ });
+ this.replacing = replacing;
+ return replacing;
+ }
+
+ private async replace(): Promise<void> {
const child = this.child;
if (!child || this.stopping) return;
this.restarting = true;
@@ -173,11 +207,13 @@ export class AgentSupervisor {
return;
}
this.setState("restarting");
- await this.spawnAndInitialize();
+ this.replacing = undefined;
+ await this.initialize();
}
async stop(): Promise<void> {
this.stopping = true;
+ this.wasLaunched = true;
clearTimeout(this.restartTimer);
const child = this.child;
if (!child) {
@@ -193,6 +229,14 @@ export class AgentSupervisor {
clearTimeout(kill);
}
+ private initialize(): Promise<void> {
+ const run = this.spawnAndInitialize().finally(() => {
+ if (this.initializing === run) this.initializing = undefined;
+ });
+ this.initializing = run;
+ return run;
+ }
+
private async spawnAndInitialize(): Promise<void> {
const wanted = this.sessionFile;
const child = this.spawnChild();
@@ -305,7 +349,7 @@ export class AgentSupervisor {
this.setState("restarting");
this.restartTimer = setTimeout(() => {
if (this.stopping) return;
- this.spawnAndInitialize().catch((error: Error) => {
+ this.initialize().catch((error: Error) => {
this.log(`agent restart failed: ${error.message}`);
// A child that is still alive will close and schedule the next attempt.
if (!this.child && !this.stopping) this.scheduleRestart();
diff --git a/packages/daemon/test/startup-state.test.ts b/packages/daemon/test/startup-state.test.ts
new file mode 100644
index 0000000..85539db
--- /dev/null
+++ b/packages/daemon/test/startup-state.test.ts
@@ -0,0 +1,36 @@
+import type { ServerPayload } from "@gentle-dot/protocol";
+import { afterEach, describe, expect, it } from "vitest";
+import { DotBridge } from "../src/bridge.ts";
+import type { AgentSupervisor } from "../src/supervisor.ts";
+import { fakeSupervisor } from "./helpers.ts";
+
+const supervisors: AgentSupervisor[] = [];
+afterEach(async () => {
+ await Promise.all(supervisors.splice(0).map((s) => s.stop()));
+});
+
+function setup() {
+ const { supervisor, dataDir } = fakeSupervisor();
+ supervisors.push(supervisor);
+ const bridge = new DotBridge(supervisor, { dataDir, log: () => {}, features: { conversations: true } });
+ const received: ServerPayload[] = [];
+ bridge.attach({ send: (payload: ServerPayload) => received.push(payload) });
+ return { supervisor, bridge, received };
+}
+
+describe("agent state at startup (S2)", () => {
+ it("reports starting before the engine was asked to start, not an error", () => {
+ const { bridge, received } = setup();
+ expect(bridge.agentState).toBe("starting");
+ expect(received.find((p) => p.type === "ready")).toMatchObject({ agentState: "starting" });
+ });
+
+ it("still reports an error once the engine stopped", async () => {
+ const { supervisor, bridge, received } = setup();
+ await supervisor.start();
+ expect(bridge.agentState).toBe("idle");
+ await supervisor.stop();
+ expect(bridge.agentState).toBe("error");
+ expect(received.filter((p) => p.type === "agent_state").at(-1)).toMatchObject({ state: "error" });
+ });
+});
diff --git a/packages/daemon/test/supervisor.test.ts b/packages/daemon/test/supervisor.test.ts
index a8b612c..86b07da 100644
--- a/packages/daemon/test/supervisor.test.ts
+++ b/packages/daemon/test/supervisor.test.ts
@@ -159,6 +159,72 @@ describe("AgentSupervisor", () => {
expect(events.some((e) => e.type === "interrupted")).toBe(false);
});
+ it("a restart asked while the engine starts waits for it, then replaces it once (S1)", async () => {
+ let spawns = 0;
+ const logs: string[] = [];
+ const { supervisor, events } = track(
+ fakeSupervisor({
+ env: { ...process.env, FAKE_AGENT_START_DELAY_MS: "300" },
+ prepareSpawn: () => {
+ spawns += 1;
+ return {};
+ },
+ log: (line) => logs.push(line),
+ }),
+ );
+ const starting = supervisor.start();
+ const firstPid = supervisor.pid;
+ // Two requests while starting (computer control, then connector files put back) make one restart.
+ const restarts = [supervisor.restart(), supervisor.restart()];
+ await expect(starting).resolves.toBeUndefined();
+ await Promise.all(restarts);
+ expect(supervisor.state).toBe("ready");
+ expect(spawns).toBe(2);
+ expect(supervisor.pid).not.toBe(firstPid);
+ const states = events.flatMap((e) => (e.type === "supervisor_state" && "state" in e ? [e.state] : []));
+ expect(states).toEqual(["starting", "ready", "restarting", "ready"]);
+ expect(events.some((e) => e.type === "interrupted")).toBe(false);
+ expect(logs.filter((line) => /exited unexpectedly|restart failed/.test(line))).toEqual([]);
+ });
+
+ it("a stop while a restart waits for the start starts nothing again", async () => {
+ let spawns = 0;
+ const { supervisor } = track(
+ fakeSupervisor({
+ env: { ...process.env, FAKE_AGENT_START_DELAY_MS: "300" },
+ prepareSpawn: () => {
+ spawns += 1;
+ return {};
+ },
+ }),
+ );
+ const starting = supervisor.start().catch(() => {});
+ const restarting = supervisor.restart();
+ await supervisor.stop();
+ await Promise.all([starting, restarting]);
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ expect(spawns).toBe(1);
+ expect(supervisor.state).toBe("stopped");
+ expect(supervisor.pid).toBeUndefined();
+ });
+
+ it("a restart while ready replaces the engine right away, once", async () => {
+ let spawns = 0;
+ const { supervisor, events } = track(
+ fakeSupervisor({
+ prepareSpawn: () => {
+ spawns += 1;
+ return {};
+ },
+ }),
+ );
+ await supervisor.start();
+ await supervisor.restart();
+ expect(spawns).toBe(2);
+ const states = events.flatMap((e) => (e.type === "supervisor_state" && "state" in e ? [e.state] : []));
+ expect(states).toEqual(["starting", "ready", "restarting", "ready"]);
+ });
+
it("a stop during a restart starts nothing again (S35.2: the app quitting does both)", async () => {
const { supervisor } = track(fakeSupervisor());
await supervisor.start();