|
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 2 | +import type { GatewayRecoveryRuntime } from "../gateway/server-instance-runtime.types.js"; |
| 3 | +import { |
| 4 | + resetOrphanRecoveryCoordinationForTest, |
| 5 | + scheduleOrphanRecovery, |
| 6 | +} from "./subagent-orphan-recovery.js"; |
| 7 | +import * as subagentRegistrySteerRuntime from "./subagent-registry-steer-runtime.js"; |
| 8 | +import type { SubagentRunRecord } from "./subagent-registry.types.js"; |
| 9 | +import { createSubagentRunRecord } from "./subagent-test-fixtures.test-helpers.js"; |
| 10 | + |
| 11 | +const sessionMocks = vi.hoisted(() => { |
| 12 | + type MockSessionEntry = Record<string, unknown>; |
| 13 | + type MockSessionStore = Record<string, MockSessionEntry>; |
| 14 | + const loadSessionStore = vi.fn((): MockSessionStore => ({})); |
| 15 | + const patchSessionEntry = vi.fn( |
| 16 | + async ( |
| 17 | + scope: { sessionKey: string }, |
| 18 | + update: ( |
| 19 | + entry: MockSessionEntry, |
| 20 | + ) => MockSessionEntry | Partial<MockSessionEntry> | null | Promise<MockSessionEntry | null>, |
| 21 | + ) => { |
| 22 | + const store = loadSessionStore(); |
| 23 | + const current = store[scope.sessionKey]; |
| 24 | + if (!current) { |
| 25 | + return null; |
| 26 | + } |
| 27 | + const next = await update({ ...current }); |
| 28 | + if (!next) { |
| 29 | + return current; |
| 30 | + } |
| 31 | + store[scope.sessionKey] = next; |
| 32 | + return next; |
| 33 | + }, |
| 34 | + ); |
| 35 | + return { loadSessionStore, patchSessionEntry }; |
| 36 | +}); |
| 37 | + |
| 38 | +vi.mock("../config/config.js", () => ({ |
| 39 | + getRuntimeConfig: vi.fn(() => ({ session: { store: undefined } })), |
| 40 | +})); |
| 41 | + |
| 42 | +vi.mock("../config/sessions.js", () => ({ |
| 43 | + resolveAgentIdFromSessionKey: vi.fn(() => "main"), |
| 44 | + resolveStorePath: vi.fn(() => "/tmp/test-sessions.json"), |
| 45 | +})); |
| 46 | + |
| 47 | +vi.mock("../config/sessions/session-accessor.js", () => ({ |
| 48 | + loadSessionEntry: vi.fn( |
| 49 | + (scope: { sessionKey: string }) => sessionMocks.loadSessionStore()[scope.sessionKey], |
| 50 | + ), |
| 51 | + patchSessionEntry: sessionMocks.patchSessionEntry, |
| 52 | +})); |
| 53 | + |
| 54 | +vi.mock("../logging/subsystem.js", () => ({ |
| 55 | + createSubsystemLogger: () => ({ info: vi.fn(), warn: vi.fn() }), |
| 56 | +})); |
| 57 | + |
| 58 | +vi.mock("./subagent-registry-steer-runtime.js", () => ({ |
| 59 | + finalizeInterruptedSubagentRun: vi.fn(async () => 1), |
| 60 | + replaceSubagentRunAfterSteer: vi.fn(() => true), |
| 61 | + reserveSwarmCollectorLaunch: vi.fn(() => true), |
| 62 | +})); |
| 63 | + |
| 64 | +const childSessionKey = "agent:main:subagent:recovery-coordination"; |
| 65 | +const dispatchAgent = vi.fn(async () => ({ runId: "recovery-run" })); |
| 66 | +const readSessionMessages = vi.fn(async () => [] as unknown[]); |
| 67 | +const gatewayRuntime: GatewayRecoveryRuntime = { |
| 68 | + dispatchAgent: dispatchAgent as GatewayRecoveryRuntime["dispatchAgent"], |
| 69 | + waitForAgent: vi.fn(), |
| 70 | + sendRecoveryNotice: vi.fn(), |
| 71 | +}; |
| 72 | + |
| 73 | +function createRun(): SubagentRunRecord { |
| 74 | + return createSubagentRunRecord({ |
| 75 | + runId: "interrupted-run", |
| 76 | + childSessionKey, |
| 77 | + requesterSessionKey: "agent:main:main", |
| 78 | + requesterDisplayKey: "main", |
| 79 | + task: "continue the interrupted task", |
| 80 | + cleanup: "keep", |
| 81 | + createdAt: Date.now() - 60_000, |
| 82 | + startedAt: Date.now() - 55_000, |
| 83 | + }); |
| 84 | +} |
| 85 | + |
| 86 | +function createActiveRuns(): Map<string, SubagentRunRecord> { |
| 87 | + const run = createRun(); |
| 88 | + return new Map([[run.runId, run]]); |
| 89 | +} |
| 90 | + |
| 91 | +function mockAbortedSession() { |
| 92 | + const store = { |
| 93 | + [childSessionKey]: { |
| 94 | + sessionId: "session-1", |
| 95 | + updatedAt: Date.now(), |
| 96 | + abortedLastRun: true, |
| 97 | + }, |
| 98 | + }; |
| 99 | + sessionMocks.loadSessionStore.mockReturnValue(store); |
| 100 | + return store; |
| 101 | +} |
| 102 | + |
| 103 | +function schedule( |
| 104 | + getActiveRuns: () => Map<string, SubagentRunRecord>, |
| 105 | + options: { |
| 106 | + delayMs?: number; |
| 107 | + getGatewayRuntime?: () => GatewayRecoveryRuntime | undefined; |
| 108 | + maxRetries?: number; |
| 109 | + } = {}, |
| 110 | +) { |
| 111 | + scheduleOrphanRecovery({ |
| 112 | + getGatewayRuntime: options.getGatewayRuntime ?? (() => gatewayRuntime), |
| 113 | + getActiveRuns, |
| 114 | + readSessionMessages, |
| 115 | + delayMs: options.delayMs ?? 1, |
| 116 | + maxRetries: options.maxRetries ?? 0, |
| 117 | + }); |
| 118 | +} |
| 119 | + |
| 120 | +describe("subagent orphan recovery coordination", () => { |
| 121 | + beforeEach(() => { |
| 122 | + vi.useFakeTimers(); |
| 123 | + vi.clearAllMocks(); |
| 124 | + resetOrphanRecoveryCoordinationForTest(); |
| 125 | + dispatchAgent.mockResolvedValue({ runId: "recovery-run" }); |
| 126 | + readSessionMessages.mockResolvedValue([]); |
| 127 | + vi.mocked(subagentRegistrySteerRuntime.finalizeInterruptedSubagentRun).mockResolvedValue(1); |
| 128 | + }); |
| 129 | + |
| 130 | + afterEach(() => { |
| 131 | + resetOrphanRecoveryCoordinationForTest(); |
| 132 | + vi.useRealTimers(); |
| 133 | + }); |
| 134 | + |
| 135 | + it("coalesces duplicate schedules before the recovery scan starts", async () => { |
| 136 | + mockAbortedSession(); |
| 137 | + const activeRuns = createActiveRuns(); |
| 138 | + const getActiveRuns = vi.fn(() => activeRuns); |
| 139 | + |
| 140 | + schedule(getActiveRuns); |
| 141 | + schedule(getActiveRuns); |
| 142 | + await vi.advanceTimersByTimeAsync(1); |
| 143 | + |
| 144 | + expect(getActiveRuns).toHaveBeenCalledOnce(); |
| 145 | + expect(dispatchAgent).toHaveBeenCalledOnce(); |
| 146 | + expect(sessionMocks.patchSessionEntry).toHaveBeenCalledOnce(); |
| 147 | + }); |
| 148 | + |
| 149 | + it("queues one follow-up scan when recovery is requested during an active scan", async () => { |
| 150 | + mockAbortedSession(); |
| 151 | + const activeRuns = createActiveRuns(); |
| 152 | + const getActiveRuns = vi.fn(() => activeRuns); |
| 153 | + let releaseDispatch: () => void = () => {}; |
| 154 | + let markDispatchStarted: () => void = () => {}; |
| 155 | + const dispatchStarted = new Promise<void>((resolve) => { |
| 156 | + markDispatchStarted = resolve; |
| 157 | + }); |
| 158 | + const dispatchRelease = new Promise<void>((resolve) => { |
| 159 | + releaseDispatch = resolve; |
| 160 | + }); |
| 161 | + dispatchAgent.mockImplementationOnce(async () => { |
| 162 | + markDispatchStarted(); |
| 163 | + await dispatchRelease; |
| 164 | + return { runId: "recovery-run" }; |
| 165 | + }); |
| 166 | + |
| 167 | + schedule(getActiveRuns); |
| 168 | + await vi.advanceTimersByTimeAsync(1); |
| 169 | + await dispatchStarted; |
| 170 | + |
| 171 | + schedule(getActiveRuns); |
| 172 | + releaseDispatch(); |
| 173 | + await vi.advanceTimersByTimeAsync(0); |
| 174 | + expect(getActiveRuns).toHaveBeenCalledOnce(); |
| 175 | + |
| 176 | + await vi.advanceTimersByTimeAsync(1); |
| 177 | + |
| 178 | + expect(getActiveRuns).toHaveBeenCalledTimes(2); |
| 179 | + expect(dispatchAgent).toHaveBeenCalledOnce(); |
| 180 | + }); |
| 181 | + |
| 182 | + it("queues one follow-up scan when recovery is requested during retry backoff", async () => { |
| 183 | + mockAbortedSession(); |
| 184 | + const activeRuns = createActiveRuns(); |
| 185 | + const getActiveRuns = vi.fn(() => activeRuns); |
| 186 | + dispatchAgent |
| 187 | + .mockRejectedValueOnce(new Error("gateway unavailable")) |
| 188 | + .mockResolvedValueOnce({ runId: "recovery-run" }); |
| 189 | + |
| 190 | + schedule(getActiveRuns, { maxRetries: 1 }); |
| 191 | + await vi.advanceTimersByTimeAsync(1); |
| 192 | + |
| 193 | + schedule(getActiveRuns); |
| 194 | + await vi.advanceTimersByTimeAsync(2); |
| 195 | + |
| 196 | + expect(getActiveRuns).toHaveBeenCalledTimes(2); |
| 197 | + expect(dispatchAgent).toHaveBeenCalledTimes(2); |
| 198 | + |
| 199 | + await vi.advanceTimersByTimeAsync(1); |
| 200 | + |
| 201 | + expect(getActiveRuns).toHaveBeenCalledTimes(3); |
| 202 | + expect(dispatchAgent).toHaveBeenCalledTimes(2); |
| 203 | + }); |
| 204 | + |
| 205 | + it.each([ |
| 206 | + ["missing runtime", () => undefined], |
| 207 | + [ |
| 208 | + "thrown runtime lookup", |
| 209 | + () => { |
| 210 | + throw new Error("runtime unavailable"); |
| 211 | + }, |
| 212 | + ], |
| 213 | + ])("releases coordination after terminal %s", async (_label, getGatewayRuntime) => { |
| 214 | + mockAbortedSession(); |
| 215 | + const activeRuns = createActiveRuns(); |
| 216 | + const getActiveRuns = vi.fn(() => activeRuns); |
| 217 | + |
| 218 | + schedule(getActiveRuns, { getGatewayRuntime }); |
| 219 | + await vi.advanceTimersByTimeAsync(1); |
| 220 | + |
| 221 | + schedule(getActiveRuns); |
| 222 | + await vi.advanceTimersByTimeAsync(1); |
| 223 | + |
| 224 | + expect(getActiveRuns).toHaveBeenCalledOnce(); |
| 225 | + expect(dispatchAgent).toHaveBeenCalledOnce(); |
| 226 | + }); |
| 227 | + |
| 228 | + it("releases coordination after terminal finalization is exhausted", async () => { |
| 229 | + mockAbortedSession(); |
| 230 | + const activeRuns = createActiveRuns(); |
| 231 | + const getActiveRuns = vi.fn(() => activeRuns); |
| 232 | + dispatchAgent.mockRejectedValueOnce(new Error("gateway unavailable")); |
| 233 | + vi.mocked(subagentRegistrySteerRuntime.finalizeInterruptedSubagentRun).mockResolvedValue(0); |
| 234 | + |
| 235 | + schedule(getActiveRuns); |
| 236 | + await vi.advanceTimersByTimeAsync(4); |
| 237 | + |
| 238 | + expect(subagentRegistrySteerRuntime.finalizeInterruptedSubagentRun).toHaveBeenCalledTimes(3); |
| 239 | + |
| 240 | + schedule(getActiveRuns); |
| 241 | + await vi.advanceTimersByTimeAsync(1); |
| 242 | + |
| 243 | + expect(getActiveRuns).toHaveBeenCalledTimes(2); |
| 244 | + expect(dispatchAgent).toHaveBeenCalledTimes(2); |
| 245 | + }); |
| 246 | +}); |
0 commit comments