subagent-browser-session.test.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. import { describe, expect, it, vi } from "vitest";
  2. import { createSessionId, type BrowserControlPort } from "@zcode/contracts";
  3. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  4. import { createTestModelFactory } from "./test-runtime-model.js";
  5. import { createTestSessionEventStore } from "./test-event-store.js";
  6. import { createRecordingSubagentSessionStore } from "./subagent-test-store.js";
  7. import { done, initial, spawn, usage } from "./subagent-profile-scenario.js";
  8. function createPorts() {
  9. const childPort: BrowserControlPort = {
  10. list: vi.fn(async () => []),
  11. execute: vi.fn(async () => ({ ok: true as const, elapsedMs: 0 })),
  12. turnEnded: vi.fn(async () => {}),
  13. closeSession: vi.fn(async () => {}),
  14. };
  15. const parentPort: BrowserControlPort = {
  16. list: vi.fn(async () => []),
  17. execute: vi.fn(async () => ({ ok: true as const, elapsedMs: 0 })),
  18. turnEnded: vi.fn(async () => {}),
  19. closeSession: vi.fn(async () => {}),
  20. forChildSession: vi.fn(() => childPort),
  21. };
  22. return { childPort, parentPort };
  23. }
  24. async function runParentWithChild(browserControlPort: BrowserControlPort) {
  25. const sessionId = createSessionId();
  26. const childSessionIds: string[] = [];
  27. let issued = false;
  28. const runtime = createTestAgentRuntime(
  29. sessionId,
  30. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: false } },
  31. {
  32. browserControlPort,
  33. sessionStore: createRecordingSubagentSessionStore(),
  34. eventStore: createTestSessionEventStore(),
  35. loadAgentDefinitions: vi.fn(async () => ({ activeAgents: [initial()] })),
  36. modelFactory: createTestModelFactory({
  37. async generateText(_request, observation) {
  38. if (observation.invocationContext?.metadata?.querySource === "subagent") {
  39. childSessionIds.push(observation.invocationContext.traceContext!.sessionId!);
  40. return done();
  41. }
  42. if (issued) return done();
  43. issued = true;
  44. return { finishReason: "tool-calls", text: "", usage, toolCalls: [spawn("BROWSE")] };
  45. },
  46. }),
  47. },
  48. );
  49. try {
  50. await runtime.executeTurn("START");
  51. } finally {
  52. runtime.beginShutdown();
  53. }
  54. return { sessionId, childSessionId: childSessionIds[0]! };
  55. }
  56. describe("subagent Browser Use session", () => {
  57. it("releases child resources when initial session persistence fails before its turn", async () => {
  58. const { childPort, parentPort } = createPorts();
  59. const sessionStore = createRecordingSubagentSessionStore();
  60. const sessionId = createSessionId("init-failure");
  61. const createSession = sessionStore.createSession.bind(sessionStore);
  62. sessionStore.createSession = vi.fn(async (input) => {
  63. if (input.id !== sessionId) throw new Error("persistence unavailable");
  64. return createSession(input);
  65. });
  66. const runtime = createTestAgentRuntime(
  67. sessionId,
  68. { mode: "yolo", titleGeneration: { enabled: false } },
  69. {
  70. browserControlPort: parentPort,
  71. eventStore: createTestSessionEventStore(),
  72. sessionStore,
  73. modelFactory: createTestModelFactory({ generateText: async () => done() }),
  74. },
  75. );
  76. const port = (runtime as unknown as import("../src/runtime/internal.js").AgentRuntimeInternal)
  77. .subagentPort!;
  78. await expect(
  79. port.run({
  80. agentType: "Explore",
  81. description: "test",
  82. prompt: "initialize",
  83. sessionId: runtime.sessionId,
  84. turnId: "turn" as never,
  85. trace: runtime.rootTraceContext,
  86. workingDirectory: "/tmp",
  87. workspaceRoot: "/tmp",
  88. }),
  89. ).rejects.toThrow("persistence unavailable");
  90. expect(childPort.closeSession).toHaveBeenCalledOnce();
  91. await port.close!();
  92. expect(childPort.closeSession).toHaveBeenCalledOnce();
  93. });
  94. it("以父会话为 tab 归属登记子会话,子代理结束时经子端口撤销登记", async () => {
  95. const { childPort, parentPort } = createPorts();
  96. const { sessionId, childSessionId } = await runParentWithChild(parentPort);
  97. expect(childSessionId).toBeDefined();
  98. expect(childSessionId).not.toBe(sessionId);
  99. expect(parentPort.forChildSession).toHaveBeenCalledWith({
  100. childSessionId,
  101. parentSessionId: sessionId,
  102. tabOwner: "parent",
  103. });
  104. expect(childPort.closeSession).toHaveBeenCalledWith(
  105. expect.objectContaining({ sessionId: childSessionId }),
  106. );
  107. expect(parentPort.closeSession).not.toHaveBeenCalledWith(
  108. expect.objectContaining({ sessionId: childSessionId }),
  109. );
  110. });
  111. it("端口没有 forChildSession 时直接用父端口关闭子会话自己的 session", async () => {
  112. const { parentPort } = createPorts();
  113. delete parentPort.forChildSession;
  114. const { childSessionId } = await runParentWithChild(parentPort);
  115. expect(parentPort.closeSession).toHaveBeenCalledWith(
  116. expect.objectContaining({ sessionId: childSessionId }),
  117. );
  118. });
  119. });
  120. it("preserves child success and retries only its unreleased browser at owner close", async () => {
  121. const { childPort, parentPort } = createPorts();
  122. vi.mocked(childPort.closeSession!)
  123. .mockRejectedValueOnce(new Error("transient close failure"))
  124. .mockRejectedValueOnce(new Error("owner first attempt failed"));
  125. const runtime = createTestAgentRuntime(
  126. createSessionId("cleanup-result"),
  127. { mode: "yolo", titleGeneration: { enabled: false } },
  128. {
  129. browserControlPort: parentPort,
  130. eventStore: createTestSessionEventStore(),
  131. sessionStore: createRecordingSubagentSessionStore(),
  132. modelFactory: createTestModelFactory({ generateText: async () => done() }),
  133. },
  134. );
  135. const port = (runtime as unknown as import("../src/runtime/internal.js").AgentRuntimeInternal)
  136. .subagentPort!;
  137. const result = await port.run({
  138. agentType: "Explore",
  139. description: "test",
  140. prompt: "return success",
  141. sessionId: runtime.sessionId,
  142. turnId: "turn" as never,
  143. trace: runtime.rootTraceContext,
  144. workingDirectory: "/tmp",
  145. workspaceRoot: "/tmp",
  146. });
  147. expect(result.status).toBe("completed");
  148. await expect(port.close!()).rejects.toThrow("Subagent cleanup failed");
  149. await expect(port.close!()).resolves.toBeUndefined();
  150. await expect(port.close!()).resolves.toBeUndefined();
  151. expect(childPort.closeSession).toHaveBeenCalledTimes(3);
  152. });