fix(runtime): clean up sessions on disconnect (#17)

* fix(runtime): clean up sessions on disconnect

* chore(ci): match Biome 2.4 formatting

* ci: retry stalled Rust job

* test: bind daemon ports without probe races
This commit is contained in:
NianJiu authored and GitHub committed 2026-08-12 18:44:22 +08:00
1 parent c75f97119d
commit 1371c92721
8 files changed
+261 -24

No files matched your search

@@ -0,0 +1,58 @@
import { describe, expect, it, vi } from "vitest";
import { createDisconnectCleanup } from "../disconnect-cleanup";
import { SessionManager } from "../manager";
describe("disconnect session cleanup", () => {
it("stops every local session through the safe session-stop path", async () => {
const remove = vi.fn(async () => {});
let nextWindowId = 100;
const manager = new SessionManager({
agentWindow: {
create: vi.fn(async () => nextWindowId++),
ensureActiveTab: vi.fn(async () => {}),
remove,
},
});
await manager.start("aa11");
await manager.start("bb22");
const detachSession = vi.fn(async () => {});
const onSessionsChanged = vi.fn();
const cleanup = createDisconnectCleanup({
manager,
sessionStopDeps: { cdp: { detachSession } },
onSessionsChanged,
});
const report = await cleanup();
expect(report).toEqual({ stoppedSessionIds: ["aa11", "bb22"], failures: [] });
expect(manager.list()).toEqual([]);
expect(remove).toHaveBeenCalledTimes(2);
expect(detachSession).toHaveBeenCalledWith("aa11");
expect(detachSession).toHaveBeenCalledWith("bb22");
expect(onSessionsChanged).toHaveBeenCalledTimes(1);
});
it("coalesces overlapping disconnect notifications", async () => {
let releaseRemove: () => void = () => {};
const removeGate = new Promise<void>((resolve) => {
releaseRemove = resolve;
});
const manager = new SessionManager({
agentWindow: {
create: vi.fn(async () => 100),
ensureActiveTab: vi.fn(async () => {}),
remove: vi.fn(() => removeGate),
},
});
await manager.start("aa11");
const cleanup = createDisconnectCleanup({ manager });
const first = cleanup();
const second = cleanup();
expect(second).toBe(first);
releaseRemove();
await expect(first).resolves.toEqual({ stoppedSessionIds: ["aa11"], failures: [] });
});
});
@@ -0,0 +1,75 @@
import { handleSessionStop, type SessionStopDeps } from "@/tools/session";
import type { SessionManager } from "./manager";
export interface DisconnectCleanupFailure {
sessionId: string;
message: string;
}
export interface DisconnectCleanupReport {
stoppedSessionIds: string[];
failures: DisconnectCleanupFailure[];
}
export interface DisconnectCleanupOptions {
manager: SessionManager;
sessionStopDeps?: SessionStopDeps;
onSessionsChanged?: () => void;
}
/**
* Build a coalesced cleanup operation for transport loss.
*
* The daemon purges its registry when the extension socket disappears. To
* keep the extension-side mirror consistent, every local session must follow
* the normal safe stop path as well: return borrowed tabs, clear refs, detach
* CDP, and only then close the Agent Window.
*/
export function createDisconnectCleanup(options: DisconnectCleanupOptions) {
let inFlight: Promise<DisconnectCleanupReport> | null = null;
return (): Promise<DisconnectCleanupReport> => {
if (inFlight) return inFlight;
inFlight = cleanupSessions(options).finally(() => {
inFlight = null;
});
return inFlight;
};
}
async function cleanupSessions(
options: DisconnectCleanupOptions,
): Promise<DisconnectCleanupReport> {
const stoppedSessionIds: string[] = [];
const failures: DisconnectCleanupFailure[] = [];
for (const ctx of options.manager.list()) {
try {
const result = await handleSessionStop(
options.manager,
{ session_id: ctx.sessionId },
options.sessionStopDeps,
);
if ("code" in result) {
failures.push({ sessionId: ctx.sessionId, message: result.message });
continue;
}
if (result.return_failures?.length) {
failures.push({
sessionId: ctx.sessionId,
message: result.return_failures.map((failure) => failure.message).join("; "),
});
continue;
}
stoppedSessionIds.push(ctx.sessionId);
} catch (err) {
failures.push({
sessionId: ctx.sessionId,
message: err instanceof Error ? err.message : String(err),
});
}
}
options.onSessionsChanged?.();
return { stoppedSessionIds, failures };
}