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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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 "#e2e/helpers/worker-selection-integration";
  5. import {
  6. createBotsServiceHarness,
  7. createFeishuConfig,
  8. } from "#e2e/bots/helpers/bots-service-harness";
  9. import { clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  10. import {
  11. restartIntoWorkspace,
  12. seedBigModelConnectionSelection,
  13. seedBigModelOAuthCredential,
  14. E2E_PLAN_NON_DEFAULT_MODEL,
  15. } from "#e2e/helpers/model-provider-restart";
  16. import {
  17. UPSTREAM_MODEL,
  18. UPSTREAM_PROVIDER_ID,
  19. UPSTREAM_THOUGHT_LEVEL,
  20. } from "#e2e/helpers/upstream-provider";
  21. import {
  22. prepareV4ConversationE2E,
  23. sendV4PromptAndWaitAccepted,
  24. switchV4Model,
  25. waitForV4AssistantMessageContaining,
  26. } from "#e2e/helpers/v4-conversation";
  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
  159. .waitUntil(async () => (await host.agent.readSession(target)).session.status === "idle", {
  160. timeout: 15000,
  161. timeoutMsg: "上一轮没有结束",
  162. })
  163. .catch(async (error) => {
  164. await logWorkerFailure(host, target, marker);
  165. throw error;
  166. });
  167. return result!;
  168. }
  169. try {
  170. await host.task.sendPrompt({
  171. taskId: created.taskId,
  172. content: "E2E_W99_BOT_INITIAL",
  173. traceId: generateTraceId("w99"),
  174. modelSelection: original,
  175. });
  176. expect((await waitRequest("E2E_W99_BOT_INITIAL")).model.providerId).toBe(
  177. original.providerId,
  178. );
  179. await host.selectAccount(effective.providerId);
  180. expect(await host.task.getTaskModelSelection({ taskId: created.taskId })).toEqual(original);
  181. await sendBot("E2E_W99_BOT_NEXT");
  182. const next = await waitRequest("E2E_W99_BOT_NEXT");
  183. expect(next.model.providerId).toBe(effective.providerId);
  184. expect(next.request.body).toMatchObject({ output_config: { effort: "high" } });
  185. expect(harness.readState().bots["feishu-e2e"]?.draftOptions).toBeUndefined();
  186. await sendBot(`/model ${encodeCustomModelValue(effective.providerId, effective.modelId)}`);
  187. expect(
  188. (await host.task.getTaskModelSelection({ taskId: created.taskId }))?.options
  189. ?.reasoningLevel,
  190. ).toBe("max");
  191. // 单独设置档位是已提交的 Session 命令,必须立刻保存,不等下一条消息。
  192. await sendBot("/think low");
  193. expect(await host.task.getTaskModelSelection({ taskId: created.taskId })).toEqual({
  194. ...effective,
  195. options: { reasoningLevel: "low" },
  196. });
  197. // 真正退出 Worker 再恢复,不能只靠同进程内存读证明立即持久化。
  198. await host.agent.disposeWorkspace({ workspacePath: host.workspacePath });
  199. await host.task.resumeTask({ taskId: created.taskId, workspacePath: host.workspacePath });
  200. expect(await host.task.getTaskModelSelection({ taskId: created.taskId })).toEqual({
  201. ...effective,
  202. options: { reasoningLevel: "low" },
  203. });
  204. await expect(
  205. host.task.setModel({
  206. taskId: created.taskId,
  207. traceId: generateTraceId("w99"),
  208. modelSelection: { ...effective, options: { reasoningLevel: "invalid" } },
  209. }),
  210. ).rejects.toThrow();
  211. expect(
  212. (await host.task.getTaskModelSelection({ taskId: created.taskId }))?.options
  213. ?.reasoningLevel,
  214. ).toBe("low");
  215. // Session 当前 low;本次已固定 high,附件分支不能退回旧 Session 选择。
  216. await host.task.sendPrompt({
  217. taskId: created.taskId,
  218. content: "E2E_W99_ATTACHMENT",
  219. traceId: generateTraceId("w99"),
  220. modelSelection: effective,
  221. modelExecution: { selectionScope: "execution", memoryExtraction: "skip" },
  222. attachments: [
  223. {
  224. kind: "file",
  225. filename: "first.txt",
  226. mimeType: "text/plain",
  227. sizeBytes: 5,
  228. textContent: "FIRST",
  229. },
  230. {
  231. kind: "file",
  232. filename: "second.txt",
  233. mimeType: "text/plain",
  234. sizeBytes: 6,
  235. textContent: "SECOND",
  236. },
  237. ],
  238. });
  239. const attached = await waitRequest("E2E_W99_ATTACHMENT");
  240. expect(attached.model.providerId).toBe(effective.providerId);
  241. expect(attached.request.body).toMatchObject({ output_config: { effort: "high" } });
  242. const body = JSON.stringify(attached.request.body);
  243. expect(body.indexOf("FIRST")).toBeGreaterThanOrEqual(0);
  244. expect(body.indexOf("SECOND")).toBeGreaterThan(body.indexOf("FIRST"));
  245. expect(attached.error).toBeUndefined();
  246. expect(
  247. (await host.task.getTaskModelSelection({ taskId: created.taskId }))?.options
  248. ?.reasoningLevel,
  249. ).toBe("low");
  250. } finally {
  251. harness.service.disposeAll();
  252. }
  253. } finally {
  254. await host.dispose();
  255. }
  256. });
  257. it("W99-E04: Worker 保留完整旧状态时明确拒绝新选择,交付后新提交可执行", async function () {
  258. this.timeout(90000);
  259. const host = await createWorkerSelectionIntegration();
  260. try {
  261. const original = {
  262. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  263. modelId: E2E_PLAN_NON_DEFAULT_MODEL,
  264. options: { reasoningLevel: "high" },
  265. };
  266. const effective = {
  267. ...original,
  268. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  269. };
  270. const created = await host.task.createTask({
  271. workspacePath: host.workspacePath,
  272. modelSelection: original,
  273. deferPersistenceUntilFirstPrompt: true,
  274. });
  275. const target = { workspacePath: host.workspacePath, sessionId: created.taskId };
  276. await host.task.sendPrompt({
  277. taskId: created.taskId,
  278. content: "E2E_W99_LAG_INITIAL",
  279. traceId: generateTraceId("w99"),
  280. modelSelection: original,
  281. });
  282. await browser
  283. .waitUntil(
  284. async () => {
  285. const snapshot = await host.agent.readSession(target);
  286. return snapshot.session.status === "idle" && snapshot.messages.length > 0;
  287. },
  288. { timeout: 30000, timeoutMsg: "旧状态初始执行未完成" },
  289. )
  290. .catch(async (error) => {
  291. await logWorkerFailure(host, target, "E2E_W99_LAG_INITIAL");
  292. throw error;
  293. });
  294. await host.setDeliveryPaused(true);
  295. await host.selectAccount(effective.providerId);
  296. expect(
  297. (await host.modelSelectionService.getView({ selection: original })).effectiveSelection,
  298. ).toEqual(effective);
  299. const beforeRejected = await host.agent.readSession(target);
  300. // 当前模型准入先于 turn 创建。旧用例等待 turn.failed,会把正确的拒绝 ACK
  301. // 当作缺失终态;这里验证准入根因、无新回合,并保留后续完整交付和显式新提交。
  302. await expect(
  303. host.task.sendPrompt({
  304. taskId: created.taskId,
  305. content: "E2E_W99_LAG_REJECT",
  306. traceId: generateTraceId("w99"),
  307. modelSelection: effective,
  308. }),
  309. ).rejects.toMatchObject({
  310. name: "ZCodeV4CommandRejectedError",
  311. ack: { status: "failed", reasonCode: "modelUnavailable" },
  312. });
  313. const afterRejected = await host.agent.readSession(target);
  314. expect(afterRejected.session.status).toBe("idle");
  315. expect(afterRejected.messages).toEqual(beforeRejected.messages);
  316. expect(
  317. (await readModelIoRecords(join(host.home, ".zcode/cli/debug"))).some((record) =>
  318. JSON.stringify(record.request).includes("E2E_W99_LAG_REJECT"),
  319. ),
  320. ).toBe(false);
  321. expect(await host.task.getTaskModelSelection({ taskId: created.taskId })).toEqual(original);
  322. await host.setDeliveryPaused(false);
  323. // 复用既有读取同步检查确认交付后再作新提交;没有给普通发送加等待机制。
  324. await host.agent.readSession(target);
  325. await host.task.sendPrompt({
  326. taskId: created.taskId,
  327. content: "E2E_W99_LAG_RECOVERED",
  328. traceId: generateTraceId("w99"),
  329. modelSelection: effective,
  330. });
  331. let records: ModelIoRecord[] = [];
  332. await browser.waitUntil(
  333. async () => {
  334. records = await readModelIoRecords(join(host.home, ".zcode/cli/debug"));
  335. return records.some(
  336. (record) =>
  337. record.querySource === "main_turn" &&
  338. JSON.stringify(record.request).includes("E2E_W99_LAG_RECOVERED") &&
  339. record.model.providerId === effective.providerId &&
  340. !record.error,
  341. );
  342. },
  343. { timeout: 30000, timeoutMsg: "重新提交没有发出 Team 请求" },
  344. );
  345. } finally {
  346. await host.dispose();
  347. }
  348. });
  349. });
  350. type ModelIoRecord = {
  351. querySource?: string;
  352. model: { providerId: string; modelId: string };
  353. request: { body?: unknown };
  354. error?: unknown;
  355. };
  356. async function logWorkerFailure(
  357. host: Awaited<ReturnType<typeof createWorkerSelectionIntegration>>,
  358. target: { workspacePath: string; sessionId: string },
  359. marker: string,
  360. ) {
  361. const snapshot = await host.agent.readSession(target);
  362. const events = await host.agent.readSessionEvents(target);
  363. const records = await readModelIoRecords(join(host.home, ".zcode/cli/debug"));
  364. console.log(
  365. "E2E_WORKER_FAILURE",
  366. JSON.stringify({
  367. marker,
  368. status: snapshot.session.status,
  369. messageCount: snapshot.messages.length,
  370. failures: events.filter((event) => event.type === "turn.failed"),
  371. requests: records
  372. .filter((record) => JSON.stringify(record.request).includes(marker))
  373. .map((record) => ({ model: record.model, error: record.error })),
  374. }),
  375. );
  376. }
  377. async function readModelIoRecords(
  378. debugDir = join(getE2EAppDataPaths().storageRoot, "cli", "debug"),
  379. ): Promise<ModelIoRecord[]> {
  380. const records: ModelIoRecord[] = [];
  381. for (const file of await readdir(debugDir).catch(() => [])) {
  382. if (!file.startsWith("model-io-") || !file.endsWith(".jsonl")) continue;
  383. for (const line of (await readFile(join(debugDir, file), "utf8")).split("\n")) {
  384. if (line.trim()) records.push(JSON.parse(line) as ModelIoRecord);
  385. }
  386. }
  387. return records;
  388. }