conversation-session-worker-effective-selection.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { BUILTIN_MODEL_PROVIDER_IDS, encodeCustomModelValue, generateTraceId } from "@zcode/shared";
  4. import { createWorkerSelectionIntegration } from "../../../helpers/worker-selection-integration.js";
  5. import {
  6. createBotsServiceHarness,
  7. createFeishuConfig,
  8. } from "../../../bots/helpers/bots-service-harness.js";
  9. import { clearAppData, getE2EAppDataPaths } from "../../../helpers/desktop-app.js";
  10. import {
  11. restartIntoWorkspace,
  12. seedBigModelConnectionSelection,
  13. seedBigModelOAuthCredential,
  14. E2E_PLAN_NON_DEFAULT_MODEL,
  15. } from "../../../helpers/model-provider-restart.js";
  16. import {
  17. UPSTREAM_MODEL,
  18. UPSTREAM_PROVIDER_ID,
  19. UPSTREAM_THOUGHT_LEVEL,
  20. } from "../../../helpers/upstream-provider.js";
  21. import {
  22. prepareV4ConversationE2E,
  23. sendV4PromptAndWaitAccepted,
  24. switchV4Model,
  25. waitForV4AssistantMessageContaining,
  26. } from "../../../helpers/v4-conversation.js";
  27. const profileName = "e2e-worker-account-reviewer";
  28. const parentMarker = "E2E_W99_EXPLICIT_PARENT";
  29. const childMarker = "E2E_W99_EXPLICIT_CHILD";
  30. const finalMarker = "E2E_W99_PARENT_DONE";
  31. describe("Todo99 Worker 有效选择真实执行", () => {
  32. after(async () => {
  33. await browser.electron.restoreAllMocks();
  34. await clearAppData();
  35. });
  36. it("W99-E01: 显式子代理按 Worker 当前 Team 执行,原 profile 和父模型不变", async function () {
  37. this.timeout(180000);
  38. const paths = getE2EAppDataPaths();
  39. const profilePath = join(paths.storageRoot, "agents", `${profileName}.md`);
  40. const originalProfile = [
  41. "---",
  42. `name: ${profileName}`,
  43. "description: Review the requested marker with the configured account model.",
  44. `model: ${encodeCustomModelValue(BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan, E2E_PLAN_NON_DEFAULT_MODEL)}`,
  45. "thoughtLevel: high",
  46. "tools: Read",
  47. "maxTurns: 1",
  48. "---",
  49. "Reply only with the requested marker.",
  50. "",
  51. ].join("\n");
  52. await prepareV4ConversationE2E();
  53. await restartIntoWorkspace({
  54. afterElectronProcessExit: async () => {
  55. await seedBigModelConnectionSelection({
  56. kind: "team-coding-plan",
  57. productId: "product-team-a",
  58. organizationId: "org-team-a",
  59. projectId: "proj-team-a",
  60. });
  61. await seedBigModelOAuthCredential();
  62. await mkdir(join(paths.storageRoot, "agents"), { recursive: true });
  63. await writeFile(profilePath, originalProfile, "utf8");
  64. },
  65. });
  66. await switchV4Model(UPSTREAM_PROVIDER_ID, UPSTREAM_MODEL, UPSTREAM_THOUGHT_LEVEL);
  67. await sendV4PromptAndWaitAccepted(
  68. `${parentMarker}: Use Agent with subagent_type ${profileName}, then report the result.`,
  69. parentMarker,
  70. "父会话没有接纳输入",
  71. );
  72. await waitForV4AssistantMessageContaining(finalMarker);
  73. // 读取真正 adapter 写出的 model-io,不用 helper 返回值冒充 child 请求。
  74. const records = await readModelIoRecords();
  75. const child = records.find(
  76. (record) =>
  77. record.querySource === "subagent" && JSON.stringify(record.request).includes(childMarker),
  78. );
  79. expect(child?.model).toEqual({
  80. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  81. modelId: E2E_PLAN_NON_DEFAULT_MODEL,
  82. });
  83. expect(child?.request.body).toMatchObject({
  84. model: E2E_PLAN_NON_DEFAULT_MODEL,
  85. output_config: { effort: "high" },
  86. });
  87. expect(child?.error).toBeUndefined();
  88. const parent = records.filter(
  89. (record) =>
  90. record.querySource === "main_turn" && JSON.stringify(record.request).includes(parentMarker),
  91. );
  92. expect(parent.length).toBeGreaterThanOrEqual(2);
  93. expect(parent.every((record) => record.model.providerId === UPSTREAM_PROVIDER_ID)).toBe(true);
  94. expect(await readFile(profilePath, "utf8")).toBe(originalProfile);
  95. });
  96. it("W99-E02/03/06: 绑定 Bot 的下一轮、附件和立即设置贯穿真实 Host/Worker", async function () {
  97. this.timeout(180000);
  98. const host = await createWorkerSelectionIntegration();
  99. try {
  100. const original = {
  101. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  102. modelId: E2E_PLAN_NON_DEFAULT_MODEL,
  103. options: { reasoningLevel: "high" },
  104. };
  105. const effective = {
  106. ...original,
  107. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  108. };
  109. const created = await host.task.createTask({
  110. workspacePath: host.workspacePath,
  111. modelSelection: original,
  112. deferPersistenceUntilFirstPrompt: true,
  113. });
  114. const target = { workspacePath: host.workspacePath, sessionId: created.taskId };
  115. const harness = createBotsServiceHarness({
  116. config: createFeishuConfig(),
  117. state: {
  118. version: 3,
  119. bots: {
  120. "feishu-e2e": {
  121. botId: "feishu-e2e",
  122. workspacePath: host.workspacePath,
  123. mode: "task",
  124. activeTaskId: created.taskId,
  125. updatedAt: 1,
  126. },
  127. },
  128. },
  129. modelSelectionService: host.modelSelectionService,
  130. });
  131. // 只替换测试 harness 的 task port;以下读取、命令、发送、订阅均为生产 adapter。
  132. Object.assign(harness.zcodeTaskService, host.task);
  133. const sendBot = (text: string) =>
  134. harness.service.handleInboundMessage({
  135. botId: "feishu-e2e",
  136. actor: {
  137. provider: "feishu",
  138. botId: "feishu-e2e",
  139. providerUserId: "ou_e2e_user",
  140. chatType: "private",
  141. },
  142. text,
  143. });
  144. const debugDir = join(host.home, ".zcode/cli/debug");
  145. async function waitRequest(marker: string) {
  146. let result: ModelIoRecord | undefined;
  147. await browser.waitUntil(
  148. async () => {
  149. result = (await readModelIoRecords(debugDir)).find(
  150. (record) =>
  151. record.querySource === "main_turn" &&
  152. JSON.stringify(record.request).includes(marker),
  153. );
  154. return Boolean(result);
  155. },
  156. { timeout: 30000, timeoutMsg: `缺少真实请求 ${marker}` },
  157. );
  158. await browser.waitUntil(
  159. async () => (await host.agent.readSession(target)).session.status === "idle",
  160. { timeout: 15000, timeoutMsg: "上一轮没有结束" },
  161. );
  162. return result!;
  163. }
  164. try {
  165. await host.task.sendPrompt({
  166. taskId: created.taskId,
  167. content: "E2E_W99_BOT_INITIAL",
  168. traceId: generateTraceId("w99"),
  169. modelSelection: original,
  170. });
  171. expect((await waitRequest("E2E_W99_BOT_INITIAL")).model.providerId).toBe(
  172. original.providerId,
  173. );
  174. await host.selectAccount(effective.providerId);
  175. expect(await host.task.getTaskModelSelection({ taskId: created.taskId })).toEqual(original);
  176. await sendBot("E2E_W99_BOT_NEXT");
  177. const next = await waitRequest("E2E_W99_BOT_NEXT");
  178. expect(next.model.providerId).toBe(effective.providerId);
  179. expect(next.request.body).toMatchObject({ output_config: { effort: "high" } });
  180. expect(harness.readState().bots["feishu-e2e"]?.draftOptions).toBeUndefined();
  181. await sendBot(`/model ${encodeCustomModelValue(effective.providerId, effective.modelId)}`);
  182. expect(
  183. (await host.task.getTaskModelSelection({ taskId: created.taskId }))?.options
  184. ?.reasoningLevel,
  185. ).toBe("max");
  186. // 单独设置档位是已提交的 Session 命令,必须立刻保存,不等下一条消息。
  187. await sendBot("/think low");
  188. expect(await host.task.getTaskModelSelection({ taskId: created.taskId })).toEqual({
  189. ...effective,
  190. options: { reasoningLevel: "low" },
  191. });
  192. // 真正退出 Worker 再恢复,不能只靠同进程内存读证明立即持久化。
  193. await host.agent.disposeWorkspace({ workspacePath: host.workspacePath });
  194. await host.task.resumeTask({ taskId: created.taskId, workspacePath: host.workspacePath });
  195. expect(await host.task.getTaskModelSelection({ taskId: created.taskId })).toEqual({
  196. ...effective,
  197. options: { reasoningLevel: "low" },
  198. });
  199. await expect(
  200. host.task.setModel({
  201. taskId: created.taskId,
  202. traceId: generateTraceId("w99"),
  203. modelSelection: { ...effective, options: { reasoningLevel: "invalid" } },
  204. }),
  205. ).rejects.toThrow();
  206. expect(
  207. (await host.task.getTaskModelSelection({ taskId: created.taskId }))?.options
  208. ?.reasoningLevel,
  209. ).toBe("low");
  210. // Session 当前 low;本次已固定 high,附件分支不能退回旧 Session 选择。
  211. await host.task.sendPrompt({
  212. taskId: created.taskId,
  213. content: "E2E_W99_ATTACHMENT",
  214. traceId: generateTraceId("w99"),
  215. modelSelection: effective,
  216. modelExecution: { selectionScope: "execution", memoryExtraction: "skip" },
  217. attachments: [
  218. {
  219. kind: "file",
  220. filename: "first.txt",
  221. mimeType: "text/plain",
  222. sizeBytes: 5,
  223. textContent: "FIRST",
  224. },
  225. {
  226. kind: "file",
  227. filename: "second.txt",
  228. mimeType: "text/plain",
  229. sizeBytes: 6,
  230. textContent: "SECOND",
  231. },
  232. ],
  233. });
  234. const attached = await waitRequest("E2E_W99_ATTACHMENT");
  235. expect(attached.model.providerId).toBe(effective.providerId);
  236. expect(attached.request.body).toMatchObject({ output_config: { effort: "high" } });
  237. const body = JSON.stringify(attached.request.body);
  238. expect(body.indexOf("FIRST")).toBeGreaterThanOrEqual(0);
  239. expect(body.indexOf("SECOND")).toBeGreaterThan(body.indexOf("FIRST"));
  240. expect(attached.error).toBeUndefined();
  241. expect(
  242. (await host.task.getTaskModelSelection({ taskId: created.taskId }))?.options
  243. ?.reasoningLevel,
  244. ).toBe("low");
  245. } finally {
  246. harness.service.disposeAll();
  247. }
  248. } finally {
  249. await host.dispose();
  250. }
  251. });
  252. it("W99-E04: Worker 保留完整旧状态时明确拒绝新选择,交付后新提交可执行", async function () {
  253. this.timeout(90000);
  254. const host = await createWorkerSelectionIntegration();
  255. let frameListener: { dispose(): void } | undefined;
  256. try {
  257. const original = {
  258. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  259. modelId: E2E_PLAN_NON_DEFAULT_MODEL,
  260. options: { reasoningLevel: "high" },
  261. };
  262. const effective = {
  263. ...original,
  264. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  265. };
  266. const created = await host.task.createTask({
  267. workspacePath: host.workspacePath,
  268. modelSelection: original,
  269. deferPersistenceUntilFirstPrompt: true,
  270. });
  271. const target = { workspacePath: host.workspacePath, sessionId: created.taskId };
  272. await host.task.sendPrompt({
  273. taskId: created.taskId,
  274. content: "E2E_W99_LAG_INITIAL",
  275. traceId: generateTraceId("w99"),
  276. modelSelection: original,
  277. });
  278. await browser.waitUntil(
  279. async () => {
  280. const snapshot = await host.agent.readSession(target);
  281. return snapshot.session.status === "idle" && snapshot.messages.length > 0;
  282. },
  283. { timeout: 30000, timeoutMsg: "旧状态初始执行未完成" },
  284. );
  285. await host.setDeliveryPaused(true);
  286. await host.selectAccount(effective.providerId);
  287. expect(
  288. (await host.modelSelectionService.getView({ selection: original })).effectiveSelection,
  289. ).toEqual(effective);
  290. const frames: unknown[] = [];
  291. frameListener = host.agent.onDynamicConversationFrame(target)((frame) => frames.push(frame));
  292. await host.agent.subscribeConversationV4(target);
  293. // 命令接纳与执行失败分开:ACK 可成功,但不能等待尚未释放的交付或偷偷换模型。
  294. await host.task.sendPrompt({
  295. taskId: created.taskId,
  296. content: "E2E_W99_LAG_REJECT",
  297. traceId: generateTraceId("w99"),
  298. modelSelection: effective,
  299. });
  300. await browser.waitUntil(
  301. async () =>
  302. (await host.agent.readSessionEvents(target)).some(
  303. (event) => event.type === "turn.failed",
  304. ),
  305. { timeout: 15000, timeoutMsg: "旧 Worker 未明确报告模型执行失败" },
  306. );
  307. await browser.waitUntil(() => JSON.stringify(frames).includes('"phase":"error"'), {
  308. timeout: 10000,
  309. timeoutMsg: "桌面 V4 没有收到执行错误",
  310. });
  311. expect(
  312. (await readModelIoRecords(join(host.home, ".zcode/cli/debug"))).some((record) =>
  313. JSON.stringify(record.request).includes("E2E_W99_LAG_REJECT"),
  314. ),
  315. ).toBe(false);
  316. expect(await host.task.getTaskModelSelection({ taskId: created.taskId })).toEqual(original);
  317. await host.setDeliveryPaused(false);
  318. // 复用既有读取同步检查确认交付后再作新提交;没有给普通发送加等待机制。
  319. await host.agent.readSession(target);
  320. await host.task.sendPrompt({
  321. taskId: created.taskId,
  322. content: "E2E_W99_LAG_RECOVERED",
  323. traceId: generateTraceId("w99"),
  324. modelSelection: effective,
  325. });
  326. let records: ModelIoRecord[] = [];
  327. await browser.waitUntil(
  328. async () => {
  329. records = await readModelIoRecords(join(host.home, ".zcode/cli/debug"));
  330. return records.some(
  331. (record) =>
  332. record.querySource === "main_turn" &&
  333. JSON.stringify(record.request).includes("E2E_W99_LAG_RECOVERED") &&
  334. record.model.providerId === effective.providerId &&
  335. !record.error,
  336. );
  337. },
  338. { timeout: 30000, timeoutMsg: "重新提交没有发出 Team 请求" },
  339. );
  340. } finally {
  341. frameListener?.dispose();
  342. await host.dispose();
  343. }
  344. });
  345. });
  346. type ModelIoRecord = {
  347. querySource?: string;
  348. model: { providerId: string; modelId: string };
  349. request: { body?: unknown };
  350. error?: unknown;
  351. };
  352. async function readModelIoRecords(
  353. debugDir = join(getE2EAppDataPaths().storageRoot, "cli", "debug"),
  354. ): Promise<ModelIoRecord[]> {
  355. const records: ModelIoRecord[] = [];
  356. for (const file of await readdir(debugDir).catch(() => [])) {
  357. if (!file.startsWith("model-io-") || !file.endsWith(".jsonl")) continue;
  358. for (const line of (await readFile(join(debugDir, file), "utf8")).split("\n")) {
  359. if (line.trim()) records.push(JSON.parse(line) as ModelIoRecord);
  360. }
  361. }
  362. return records;
  363. }