Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): resolve stream race condition and add lifecycle tests
yushen918b5d294d59
diff --git a/src/agent/async-agent.ts b/src/agent/async-agent.tsindex 97b473785f..c5bcdc073f 100644--- a/src/agent/async-agent.ts+++ b/src/agent/async-agent.ts@@ -14,6 +14,7 @@ export class AsyncAgent {private readonly channel = new Channel<ChannelItem>();private _closed = false;private queue: Promise<void> = Promise.resolve();+ private closeCallbacks: Array<() => void> = [];readonly sessionId: string;constructor(options?: AgentOptions) {@@ -57,10 +58,33 @@ export class AsyncAgent {return this.channel;}- /** Close agent, stop all reads */+ /** Returns a promise that resolves when the current message queue is drained */+ waitForIdle(): Promise<void> {+ return this.queue;+ }++ /** Register a callback to be invoked when the agent is closed */+ onClose(callback: () => void): void {+ if (this._closed) {+ // Already closed, fire immediately+ callback();+ return;+ }+ this.closeCallbacks.push(callback);+ }++ /** Close agent, stop all reads, fire close callbacks */close(): void {if (this._closed) return;this._closed = true;this.channel.close();+ for (const cb of this.closeCallbacks) {+ try {+ cb();+ } catch {+ // Don't let callback errors prevent other callbacks+ }+ }+ this.closeCallbacks = [];}}diff --git a/src/agent/subagent/index.ts b/src/agent/subagent/index.tsindex d0a24d994f..2785d86e0b 100644--- a/src/agent/subagent/index.ts+++ b/src/agent/subagent/index.ts@@ -20,6 +20,7 @@ export {releaseSubagentRun,getSubagentRun,resetSubagentRegistryForTests,+ shutdownSubagentRegistry,} from "./registry.js";export {diff --git a/src/agent/subagent/registry.test.ts b/src/agent/subagent/registry.test.tsnew file mode 100644index 0000000000..dda7891751--- /dev/null+++ b/src/agent/subagent/registry.test.ts@@ -0,0 +1,161 @@+import { describe, it, expect, beforeEach } from "vitest";+import {+ registerSubagentRun,+ listSubagentRuns,+ getSubagentRun,+ releaseSubagentRun,+ resetSubagentRegistryForTests,+ shutdownSubagentRegistry,+} from "./registry.js";++// Note: These tests exercise the registry's in-memory state management.+// They do NOT test the full lifecycle (which requires a live Hub + AsyncAgent).++beforeEach(() => {+ resetSubagentRegistryForTests();+});++describe("subagent registry", () => {+ it("registers a run and retrieves it by ID", () => {+ const record = registerSubagentRun({+ runId: "run-1",+ childSessionId: "child-1",+ requesterSessionId: "parent-1",+ task: "Analyze code",+ label: "Code Analysis",+ });++ expect(record.runId).toBe("run-1");+ expect(record.childSessionId).toBe("child-1");+ expect(record.requesterSessionId).toBe("parent-1");+ expect(record.task).toBe("Analyze code");+ expect(record.label).toBe("Code Analysis");+ expect(record.cleanup).toBe("delete"); // default+ expect(record.createdAt).toBeGreaterThan(0);+ expect(record.startedAt).toBeGreaterThan(0); // set by watchChildAgent++ const retrieved = getSubagentRun("run-1");+ expect(retrieved).toBe(record);+ });++ it("lists runs filtered by requester session", () => {+ registerSubagentRun({+ runId: "run-1",+ childSessionId: "child-1",+ requesterSessionId: "parent-A",+ task: "Task 1",+ });+ registerSubagentRun({+ runId: "run-2",+ childSessionId: "child-2",+ requesterSessionId: "parent-B",+ task: "Task 2",+ });+ registerSubagentRun({+ runId: "run-3",+ childSessionId: "child-3",+ requesterSessionId: "parent-A",+ task: "Task 3",+ });++ const parentARuns = listSubagentRuns("parent-A");+ expect(parentARuns).toHaveLength(2);+ expect(parentARuns.map((r) => r.runId).sort()).toEqual(["run-1", "run-3"]);++ const parentBRuns = listSubagentRuns("parent-B");+ expect(parentBRuns).toHaveLength(1);+ expect(parentBRuns[0]!.runId).toBe("run-2");++ const emptyRuns = listSubagentRuns("parent-C");+ expect(emptyRuns).toHaveLength(0);+ });++ it("releases a run from the registry", () => {+ registerSubagentRun({+ runId: "run-1",+ childSessionId: "child-1",+ requesterSessionId: "parent-1",+ task: "Task",+ });++ expect(getSubagentRun("run-1")).toBeDefined();++ const released = releaseSubagentRun("run-1");+ expect(released).toBe(true);+ expect(getSubagentRun("run-1")).toBeUndefined();++ // Double release returns false+ const releasedAgain = releaseSubagentRun("run-1");+ expect(releasedAgain).toBe(false);+ });++ it("applies custom cleanup value", () => {+ const record = registerSubagentRun({+ runId: "run-keep",+ childSessionId: "child-1",+ requesterSessionId: "parent-1",+ task: "Keep session",+ cleanup: "keep",+ });++ expect(record.cleanup).toBe("keep");+ });++ it("registers a run and ends it with error when Hub is not available", () => {+ // Without Hub initialized, watchChildAgent detects missing Hub+ // and immediately ends the run with an error+ registerSubagentRun({+ runId: "run-no-hub",+ childSessionId: "child-1",+ requesterSessionId: "parent-1",+ task: "Running task",+ });++ const record = getSubagentRun("run-no-hub");+ expect(record?.startedAt).toBeGreaterThan(0);+ expect(record?.endedAt).toBeGreaterThan(0);+ expect(record?.outcome?.status).toBe("error");+ expect(record?.outcome?.error).toContain("Hub not initialized");+ });++ it("shutdownSubagentRegistry marks unfinished runs as ended", () => {+ // Directly set up a record without going through watchChildAgent+ // to simulate a run that is still active+ registerSubagentRun({+ runId: "run-active",+ childSessionId: "child-1",+ requesterSessionId: "parent-1",+ task: "Running task",+ });++ // The above run already ended due to no Hub; reset its endedAt+ // to simulate a truly active run+ const record = getSubagentRun("run-active");+ if (record) {+ record.endedAt = undefined;+ record.outcome = undefined;+ }++ shutdownSubagentRegistry();++ const after = getSubagentRun("run-active");+ expect(after?.endedAt).toBeGreaterThan(0);+ expect(after?.outcome?.status).toBe("unknown");+ });++ it("resetSubagentRegistryForTests clears all state", () => {+ registerSubagentRun({+ runId: "run-1",+ childSessionId: "child-1",+ requesterSessionId: "parent-1",+ task: "Task",+ });++ expect(listSubagentRuns("parent-1")).toHaveLength(1);++ resetSubagentRegistryForTests();++ expect(listSubagentRuns("parent-1")).toHaveLength(0);+ expect(getSubagentRun("run-1")).toBeUndefined();+ });+});diff --git a/src/agent/subagent/registry.ts b/src/agent/subagent/registry.tsindex 9915e4a040..b2cc84462d 100644--- a/src/agent/subagent/registry.ts+++ b/src/agent/subagent/registry.ts@@ -5,7 +5,7 @@* watches for child completion, and triggers announce flow.*/-import { getHub } from "../../hub/hub-singleton.js";+import { getHub, isHubInitialized } from "../../hub/hub-singleton.js";import { loadSubagentRuns, saveSubagentRuns } from "./registry-store.js";import { runSubagentAnnounceFlow } from "./announce.js";import type {@@ -128,6 +128,27 @@ export function getSubagentRun(runId: string): SubagentRunRecord | undefined {return subagentRuns.get(runId);}+/** Mark all active (non-ended) runs as ended with "unknown" status. Called during Hub shutdown. */+export function shutdownSubagentRegistry(): void {+ const now = Date.now();+ let updated = 0;++ for (const record of subagentRuns.values()) {+ if (!record.endedAt) {+ record.endedAt = now;+ record.outcome = { status: "unknown" };+ updated++;+ }+ }++ if (updated > 0) {+ persist();+ console.log(`[SubagentRegistry] Marked ${updated} active run(s) as ended during shutdown`);+ }++ stopSweeper();+}+/** Reset all state (for testing). */export function resetSubagentRegistryForTests(): void {subagentRuns.clear();@@ -140,78 +161,65 @@ export function resetSubagentRegistryForTests(): void {// ============================================================================function watchChildAgent(record: SubagentRunRecord, timeoutSeconds?: number): void {- const { runId, childSessionId } = record;+ const { childSessionId } = record;// Mark as startedrecord.startedAt = Date.now();persist();+ const cleanup = (outcome: { status: "ok" | "error" | "timeout" | "unknown"; error?: string | undefined }) => {+ if (record.endedAt) return; // Already finalized+ if (timeoutTimer) clearTimeout(timeoutTimer);+ record.endedAt = Date.now();+ record.outcome = outcome;+ persist();+ handleRunCompletion(record);+ };+// Set up timeout if specifiedlet timeoutTimer: ReturnType<typeof setTimeout> | undefined;if (timeoutSeconds && timeoutSeconds > 0) {timeoutTimer = setTimeout(() => {- if (!record.endedAt) {- record.endedAt = Date.now();- record.outcome = { status: "timeout" };- persist();-- // Try to close the child agent- try {- const hub = getHub();- hub.closeAgent(childSessionId);- } catch {- // Hub may not be available- }-- handleRunCompletion(record);+ cleanup({ status: "timeout" });++ // Try to close the child agent+ try {+ const hub = getHub();+ hub.closeAgent(childSessionId);+ } catch {+ // Hub may not be available}}, timeoutSeconds * 1000);}- // Watch the child agent's channel for closure- void (async () => {- try {- const hub = getHub();- const childAgent = hub.getAgent(childSessionId);- if (!childAgent) {- record.endedAt = Date.now();- record.outcome = { status: "error", error: "Child agent not found" };- persist();- handleRunCompletion(record);- return;- }+ // Get child agent reference (Hub may not be available in tests)+ if (!isHubInitialized()) {+ cleanup({ status: "error", error: "Hub not initialized" });+ return;+ }- // Consume the child's output stream — when it ends, the agent is done- for await (const item of childAgent.read()) {- // Check for error messages- if ("content" in item && typeof item.content === "string" && item.content.startsWith("[error]")) {- record.outcome = { status: "error", error: item.content };- }- }+ const hub = getHub();+ const childAgent = hub.getAgent(childSessionId);+ if (!childAgent) {+ cleanup({ status: "error", error: "Child agent not found" });+ return;+ }- // Stream ended — child agent completed- if (!record.endedAt) {- if (timeoutTimer) clearTimeout(timeoutTimer);- record.endedAt = Date.now();- if (!record.outcome) {- record.outcome = { status: "ok" };- }- persist();- handleRunCompletion(record);- }- } catch (err) {- if (!record.endedAt) {- if (timeoutTimer) clearTimeout(timeoutTimer);- record.endedAt = Date.now();- record.outcome = {- status: "error",- error: err instanceof Error ? err.message : String(err),- };- persist();- handleRunCompletion(record);- }- }- })();+ // Wait for the child agent's task queue to drain (task completion),+ // then trigger announce flow. Uses waitForIdle() instead of consuming+ // the stream (which would conflict with Hub.consumeAgent).+ childAgent.waitForIdle().then(+ () => cleanup({ status: "ok" }),+ (err) => cleanup({+ status: "error",+ error: err instanceof Error ? err.message : String(err),+ }),+ );++ // Also handle explicit close (e.g., timeout kill, Hub shutdown)+ childAgent.onClose(() => {+ cleanup({ status: record.outcome?.status ?? "unknown" });+ });}// ============================================================================@@ -292,8 +300,9 @@ function sweep(): void {let removed = 0;for (const [runId, record] of subagentRuns) {- if (record.archiveAtMs && record.archiveAtMs <= now) {+ if (record.archiveAtMs !== undefined && record.archiveAtMs <= now) {subagentRuns.delete(runId);+ resumedRuns.delete(runId);removed++;}}