|
| 1 | +/** Real QuickJS bridge coverage for subscribed embedded tool lifecycles. */ |
| 2 | +import { expectDefined } from "@openclaw/normalization-core"; |
| 3 | +import { afterEach, describe, expect, it, vi } from "vitest"; |
| 4 | +import { createDeferred } from "../../test/helpers/promise.js"; |
| 5 | +import { createDiagnosticEmbeddedRunOwner } from "../logging/diagnostic-run-activity.js"; |
| 6 | +import { disposeAllCodeModeRuns } from "./code-mode-state.js"; |
| 7 | +import { applyCodeModeCatalog, createCodeModeTools } from "./code-mode.js"; |
| 8 | +import { |
| 9 | + pluginToolWithExecute, |
| 10 | + resetCodeModeTestState, |
| 11 | + resultDetails, |
| 12 | + testing, |
| 13 | +} from "./code-mode.test-support.js"; |
| 14 | +import { prepareEmbeddedAttemptStream } from "./embedded-agent-runner/run/attempt-stream-prepare.js"; |
| 15 | +import { clearActiveEmbeddedRun } from "./embedded-agent-runner/runs.js"; |
| 16 | +import { createStubSessionHarness } from "./embedded-agent-subscribe.e2e-harness.js"; |
| 17 | +import { countActiveToolExecutions } from "./embedded-agent-subscribe.handlers.tools.js"; |
| 18 | +import { createToolSearchCatalogRef } from "./tool-search.js"; |
| 19 | +import { jsonResult } from "./tools/common.js"; |
| 20 | + |
| 21 | +function createSubscribedCodeModeHarness(params: { |
| 22 | + name: string; |
| 23 | + onBlockReplyFlush?: () => Promise<void>; |
| 24 | + timeoutMs?: number; |
| 25 | +}) { |
| 26 | + const runId = `run-code-mode-${params.name}`; |
| 27 | + const sessionId = `session-code-mode-${params.name}`; |
| 28 | + const sessionKey = `agent:main:${params.name}`; |
| 29 | + const config = { |
| 30 | + tools: { codeMode: { enabled: true, timeoutMs: params.timeoutMs ?? 1_500 } }, |
| 31 | + } as never; |
| 32 | + const catalogRef = createToolSearchCatalogRef(); |
| 33 | + const runAbortController = new AbortController(); |
| 34 | + const { session } = createStubSessionHarness(); |
| 35 | + const activeSession = Object.assign(session, { |
| 36 | + agent: { hasQueuedMessages: () => false }, |
| 37 | + isStreaming: false, |
| 38 | + messages: [], |
| 39 | + pendingMessageCount: 0, |
| 40 | + }); |
| 41 | + const stream = prepareEmbeddedAttemptStream({ |
| 42 | + attempt: { config, runId, sessionId, sessionKey } as never, |
| 43 | + activeSession: activeSession as never, |
| 44 | + hookRunner: undefined as never, |
| 45 | + hookAgentId: "main", |
| 46 | + diagnosticTrace: {} as never, |
| 47 | + diagnosticOwner: createDiagnosticEmbeddedRunOwner({ sessionId, sessionKey, runId }), |
| 48 | + clientToolCallSlots: [], |
| 49 | + toolSearchTargetTranscriptProjections: [], |
| 50 | + isReplaySafeTool: () => false, |
| 51 | + runAbortController, |
| 52 | + abortRun: () => runAbortController.abort(), |
| 53 | + markExternalAbort: () => undefined, |
| 54 | + getRunState: () => ({ |
| 55 | + aborted: runAbortController.signal.aborted, |
| 56 | + promptError: undefined, |
| 57 | + timedOut: false, |
| 58 | + yieldDetected: false, |
| 59 | + }), |
| 60 | + hasDeliveredSourceReply: () => false, |
| 61 | + markSourceReplyDelivered: () => undefined, |
| 62 | + onBlockReply: undefined, |
| 63 | + onBlockReplyFlush: params.onBlockReplyFlush, |
| 64 | + sandboxSessionKey: sessionKey, |
| 65 | + builtinToolNames: new Set(), |
| 66 | + replaySafeToolNames: new Set(), |
| 67 | + }); |
| 68 | + const context = { |
| 69 | + config, |
| 70 | + runtimeConfig: config, |
| 71 | + sessionId, |
| 72 | + sessionKey, |
| 73 | + runId, |
| 74 | + catalogRef, |
| 75 | + abortSignal: runAbortController.signal, |
| 76 | + executeTool: stream.toolSearchCatalogExecutor, |
| 77 | + }; |
| 78 | + return { |
| 79 | + ...context, |
| 80 | + tools: createCodeModeTools(context), |
| 81 | + runAbortController, |
| 82 | + subscription: stream.subscription, |
| 83 | + dispose: () => { |
| 84 | + stream.subscription.unsubscribe(); |
| 85 | + clearActiveEmbeddedRun(sessionId, stream.queueHandle, sessionKey); |
| 86 | + }, |
| 87 | + }; |
| 88 | +} |
| 89 | + |
| 90 | +describe("Code Mode subscribed bridge lifecycle", () => { |
| 91 | + afterEach(() => resetCodeModeTestState()); |
| 92 | + |
| 93 | + it("starts a subscribed nested tool without re-entering its outer presentation flush", async () => { |
| 94 | + const blockReplyFlush = createDeferred(); |
| 95 | + const onBlockReplyFlush = vi.fn(() => blockReplyFlush.promise); |
| 96 | + const harness = createSubscribedCodeModeHarness({ name: "circular-flush", onBlockReplyFlush }); |
| 97 | + const target = pluginToolWithExecute("release_flush", "Release the pending reply", async () => { |
| 98 | + blockReplyFlush.resolve(); |
| 99 | + return jsonResult({ released: true }); |
| 100 | + }); |
| 101 | + applyCodeModeCatalog({ ...harness, tools: [...harness.tools, target] }); |
| 102 | + |
| 103 | + try { |
| 104 | + const result = resultDetails( |
| 105 | + await expectDefined(harness.tools[0], "Code Mode exec test invariant").execute( |
| 106 | + "code-call-circular-flush", |
| 107 | + { code: "return await release_flush({});" }, |
| 108 | + ), |
| 109 | + ); |
| 110 | + |
| 111 | + expect(result.status, JSON.stringify(result)).toBe("completed"); |
| 112 | + expect(result.value).toEqual({ released: true }); |
| 113 | + expect(target.execute).toHaveBeenCalledOnce(); |
| 114 | + expect(onBlockReplyFlush).not.toHaveBeenCalled(); |
| 115 | + expect(harness.subscription.getItemLifecycle()).toMatchObject({ |
| 116 | + startedCount: 1, |
| 117 | + completedCount: 1, |
| 118 | + activeCount: 0, |
| 119 | + }); |
| 120 | + expect(countActiveToolExecutions(harness.runId)).toBe(0); |
| 121 | + expect(testing.activeRuns.size).toBe(0); |
| 122 | + } finally { |
| 123 | + blockReplyFlush.resolve(); |
| 124 | + harness.dispose(); |
| 125 | + } |
| 126 | + }); |
| 127 | + |
| 128 | + it("settles subscribed nested dispatch exactly once across repeated exec and wait turns", async () => { |
| 129 | + const blockReplyFlush = createDeferred(); |
| 130 | + const onBlockReplyFlush = vi.fn(() => blockReplyFlush.promise); |
| 131 | + const harness = createSubscribedCodeModeHarness({ |
| 132 | + name: "repeated-lifecycle", |
| 133 | + onBlockReplyFlush, |
| 134 | + }); |
| 135 | + const target = pluginToolWithExecute("finish_stage", "Finish one suspended stage", async () => { |
| 136 | + blockReplyFlush.resolve(); |
| 137 | + return jsonResult({ finished: true }); |
| 138 | + }); |
| 139 | + applyCodeModeCatalog({ ...harness, tools: [...harness.tools, target] }); |
| 140 | + |
| 141 | + try { |
| 142 | + for (let stage = 0; stage < 2; stage += 1) { |
| 143 | + const suspended = resultDetails( |
| 144 | + await expectDefined(harness.tools[0], "Code Mode exec test invariant").execute( |
| 145 | + `code-call-stage-${stage}`, |
| 146 | + { code: 'await yield_control("pause"); return await finish_stage({});' }, |
| 147 | + ), |
| 148 | + ); |
| 149 | + expect(suspended).toMatchObject({ status: "waiting", reason: "yield" }); |
| 150 | + |
| 151 | + const completed = resultDetails( |
| 152 | + await expectDefined(harness.tools[1], "Code Mode wait test invariant").execute( |
| 153 | + `code-wait-stage-${stage}`, |
| 154 | + { runId: suspended.runId }, |
| 155 | + ), |
| 156 | + ); |
| 157 | + expect(completed).toMatchObject({ status: "completed", value: { finished: true } }); |
| 158 | + expect(countActiveToolExecutions(harness.runId)).toBe(0); |
| 159 | + } |
| 160 | + |
| 161 | + expect(target.execute).toHaveBeenCalledTimes(2); |
| 162 | + expect(onBlockReplyFlush).not.toHaveBeenCalled(); |
| 163 | + expect(harness.subscription.getItemLifecycle()).toMatchObject({ |
| 164 | + startedCount: 2, |
| 165 | + completedCount: 2, |
| 166 | + activeCount: 0, |
| 167 | + }); |
| 168 | + expect(testing.activeRuns.size).toBe(0); |
| 169 | + } finally { |
| 170 | + blockReplyFlush.resolve(); |
| 171 | + harness.dispose(); |
| 172 | + } |
| 173 | + }); |
| 174 | + |
| 175 | + it("preserves the initiating sessions_yield result across its run-owner handoff", async () => { |
| 176 | + const harness = createSubscribedCodeModeHarness({ name: "yield-handoff" }); |
| 177 | + const handoffReason = { code: "sessions_yield", turnHandoff: true } as const; |
| 178 | + const target = pluginToolWithExecute( |
| 179 | + "sessions_yield", |
| 180 | + "Hand off the current turn", |
| 181 | + async () => { |
| 182 | + harness.runAbortController.abort(handoffReason); |
| 183 | + return jsonResult({ status: "yielded" }); |
| 184 | + }, |
| 185 | + ); |
| 186 | + applyCodeModeCatalog({ ...harness, tools: [...harness.tools, target] }); |
| 187 | + |
| 188 | + try { |
| 189 | + const result = resultDetails( |
| 190 | + await expectDefined(harness.tools[0], "Code Mode exec test invariant").execute( |
| 191 | + "code-call-yield-handoff", |
| 192 | + { code: "return await sessions_yield({});" }, |
| 193 | + ), |
| 194 | + ); |
| 195 | + |
| 196 | + expect(result).toMatchObject({ status: "completed", value: { status: "yielded" } }); |
| 197 | + expect(target.execute).toHaveBeenCalledOnce(); |
| 198 | + expect(countActiveToolExecutions(harness.runId)).toBe(0); |
| 199 | + expect(testing.activeRuns.size).toBe(0); |
| 200 | + } finally { |
| 201 | + harness.dispose(); |
| 202 | + } |
| 203 | + }); |
| 204 | + |
| 205 | + it.each([ |
| 206 | + { kind: "explicit cancellation", close: "cancel" }, |
| 207 | + { kind: "run-owner loss", close: "abort" }, |
| 208 | + { kind: "snapshot expiry", close: "expire" }, |
| 209 | + { kind: "gateway shutdown", close: "shutdown" }, |
| 210 | + ] as const)( |
| 211 | + "settles an abort-ignoring subscribed tool exactly once after $kind", |
| 212 | + async ({ close }) => { |
| 213 | + const downstream = createDeferred(); |
| 214 | + const harness = createSubscribedCodeModeHarness({ |
| 215 | + name: `closure-${close}`, |
| 216 | + timeoutMs: 2_000, |
| 217 | + }); |
| 218 | + const target = pluginToolWithExecute("stalled_target", "Ignore cancellation", async () => { |
| 219 | + await downstream.promise; |
| 220 | + return jsonResult({ late: true }); |
| 221 | + }); |
| 222 | + applyCodeModeCatalog({ ...harness, tools: [...harness.tools, target] }); |
| 223 | + |
| 224 | + try { |
| 225 | + const suspended = resultDetails( |
| 226 | + await expectDefined(harness.tools[0], "Code Mode exec test invariant").execute( |
| 227 | + `code-call-${close}`, |
| 228 | + { |
| 229 | + code: `const target = stalled_target({}); |
| 230 | + await yield_control("pause"); |
| 231 | + try { return await target; } catch (error) { return error.message; }`, |
| 232 | + }, |
| 233 | + ), |
| 234 | + ); |
| 235 | + expect(suspended.status).toBe("waiting"); |
| 236 | + expect(target.execute).toHaveBeenCalledOnce(); |
| 237 | + expect(countActiveToolExecutions(harness.runId)).toBe(1); |
| 238 | + |
| 239 | + const parked = testing.activeRuns.get(suspended.runId as string); |
| 240 | + const pending = parked?.pending.find((entry) => entry.method === "callValue"); |
| 241 | + expect(pending).toBeDefined(); |
| 242 | + if (!parked || !pending) { |
| 243 | + throw new Error("expected one parked subscribed tool call"); |
| 244 | + } |
| 245 | + const settlements = vi.fn(); |
| 246 | + void pending.promise.then(settlements); |
| 247 | + const waiting = expectDefined(harness.tools[1], "Code Mode wait test invariant").execute( |
| 248 | + `code-wait-${close}`, |
| 249 | + { runId: suspended.runId }, |
| 250 | + ); |
| 251 | + |
| 252 | + if (close === "cancel") { |
| 253 | + pending.cancel?.(); |
| 254 | + } else if (close === "abort") { |
| 255 | + harness.runAbortController.abort(new Error("run owner closed")); |
| 256 | + } else if (close === "expire") { |
| 257 | + parked.expiresAt = Date.now() - 1; |
| 258 | + testing.removeExpiredRuns(); |
| 259 | + } else { |
| 260 | + disposeAllCodeModeRuns(); |
| 261 | + } |
| 262 | + |
| 263 | + const settlement = await pending.promise; |
| 264 | + expect(settlement).toMatchObject({ id: pending.id, ok: false }); |
| 265 | + expect(settlement.ok ? "" : settlement.error).toMatch(/cancel|abort|expir|owner|shut/i); |
| 266 | + expect(resultDetails(await waiting).status).not.toBe("waiting"); |
| 267 | + await vi.waitFor(() => expect(countActiveToolExecutions(harness.runId)).toBe(0)); |
| 268 | + expect(settlements).toHaveBeenCalledOnce(); |
| 269 | + expect(harness.subscription.getItemLifecycle().activeCount).toBe(0); |
| 270 | + expect(testing.activeRuns.size).toBe(0); |
| 271 | + |
| 272 | + downstream.resolve(); |
| 273 | + await Promise.resolve(); |
| 274 | + expect(target.execute).toHaveBeenCalledOnce(); |
| 275 | + expect(settlements).toHaveBeenCalledOnce(); |
| 276 | + } finally { |
| 277 | + downstream.resolve(); |
| 278 | + harness.dispose(); |
| 279 | + } |
| 280 | + }, |
| 281 | + ); |
| 282 | +}); |
0 commit comments