conversation-session-running-guide-steer.test.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. import { assertIncomingMessage, wireText } from "#e2e/helpers/incoming-message-evidence";
  2. import {
  3. INCOMING_MESSAGE_MODES,
  4. prepareIncomingMessageCapability,
  5. switchIncomingMessageCapability,
  6. } from "#e2e/helpers/incoming-message-capability";
  7. import { TID_CHAT_ASSISTANT_HISTORY_TRIGGER, TID_V4_TIMELINE } from "@zcode/shared/test-ids";
  8. import { clearAppData, readSettings, waitForDefaultWorkspaceReady } from "#e2e/helpers/desktop-app";
  9. import {
  10. E2E_READONLY_TOOL_FILE_CONTENT,
  11. ensureReadonlyToolFixtureFile,
  12. } from "#e2e/helpers/conversation-session-readonly-tool";
  13. import {
  14. getUpstreamRequestRecordCount,
  15. getUpstreamRequestEvidence,
  16. waitForUpstreamRequest,
  17. waitForUpstreamRequestContaining,
  18. } from "#e2e/helpers/conversation-session-network";
  19. import { getQueueItems } from "#e2e/helpers/conversation-session-queue";
  20. import { waitForTaskStoreSnapshot } from "#e2e/helpers/conversation-session-store";
  21. import {
  22. TOTAL_TOKENS_BUDGET,
  23. totalTokensAfterLastAssistant,
  24. } from "#e2e/helpers/total-tokens-evidence";
  25. import {
  26. E2E_REPLY_TOKEN,
  27. clickV4Stop,
  28. getV4ConversationState,
  29. getV4GoalProjection,
  30. getV4Messages,
  31. prepareV4ConversationE2E,
  32. sendV4Prompt,
  33. selectV4TaskById,
  34. waitForV4AssistantMessageContaining,
  35. waitForV4ComposerText,
  36. waitForV4ConversationState,
  37. waitForV4UserMessageContaining,
  38. } from "#e2e/helpers/v4-conversation";
  39. const GUIDE_GOAL_SEED_REPLY = "running-guide-goal-seed-ok";
  40. describe("会话区 Running Guide / Steer E2E", () => {
  41. before(async () => {
  42. await ensureReadonlyToolFixtureFile();
  43. });
  44. afterEach(async () => {
  45. await stopIfBusy();
  46. });
  47. after(async () => {
  48. await browser.electron.restoreAllMocks();
  49. await clearAppData();
  50. });
  51. for (const { label, mcs } of INCOMING_MESSAGE_MODES) {
  52. it(`P06 ${label}:tool-batch 与 text-only drain 后 steer 按同轮时间线顺序显示`, async function () {
  53. this.timeout(150000);
  54. // 修复原因:同一 worker 的前一条 steer/stop 会留下 completed 或 interrupted session;
  55. // guide、active goal 与 verifier 必须各自在新草稿中建立 owner,不能串用上一 case 的状态。
  56. await prepareIncomingMessageCapability(mcs);
  57. expect((await readSettings()).zcodeInteractionBehavior).toBe("guide");
  58. const runId = Date.now();
  59. const baseMarker = `E2E_GUIDE_TIMELINE_BASE_${runId}`;
  60. const guideOneMarker = `E2E_GUIDE_TIMELINE_GUIDE_ONE_${runId}`;
  61. const guideTwoMarker = `E2E_GUIDE_TIMELINE_GUIDE_TWO_${runId}`;
  62. const middleAssistantMarker = "E2E_GUIDE_TIMELINE_MIDDLE_ASSISTANT";
  63. const finalAssistantMarker = "guide-timeline-final-assistant-ok";
  64. const requestCountBefore = await getUpstreamRequestRecordCount();
  65. // Bug 根因:capture 的 afterIndex 是“最后一个已消费的数组下标”,而不是记录数;
  66. // 记录数为 0 时直接传 0 会把本次首条 request(index 0)排除,误报 provider 未发请求。
  67. const lastRequestIndexBefore = requestCountBefore - 1;
  68. await sendV4Prompt(
  69. `${baseMarker}: Read the readonly fixture, then keep following both guide messages in this active turn.`,
  70. );
  71. await waitForUpstreamRequest(
  72. { lastUserMessageIncludes: [baseMarker] },
  73. "P06 首轮 provider request 没有发出",
  74. 30000,
  75. { afterIndex: lastRequestIndexBefore },
  76. );
  77. await waitForV4ConversationState(
  78. (snapshot) => snapshot.state === "streaming",
  79. "P06 首轮请求没有保持 guide-1 可 admission 的 running 窗口",
  80. 15000,
  81. );
  82. await sendV4Prompt(`${guideOneMarker}: apply the first guide after the Read result batch.`);
  83. await waitForGuidedPromptProjection(guideOneMarker);
  84. await waitForUpstreamRequest(
  85. {
  86. includes: [guideOneMarker, E2E_READONLY_TOOL_FILE_CONTENT],
  87. lastUserMessageIncludes: [E2E_READONLY_TOOL_FILE_CONTENT],
  88. },
  89. "P06 guide-1 没有在完整 Read result batch 后进入同一 active turn",
  90. 30000,
  91. { afterIndex: lastRequestIndexBefore },
  92. );
  93. const firstEvidence = await getUpstreamRequestEvidence(
  94. { includes: [guideOneMarker, E2E_READONLY_TOOL_FILE_CONTENT] },
  95. { afterIndex: lastRequestIndexBefore },
  96. );
  97. const firstWire = await assertIncomingMessage(firstEvidence[0]!.requestJson, {
  98. presentation: "user_steer",
  99. marker: guideOneMarker,
  100. // guide 是中途消息:MCS 下并入 run 的 system,MCS 关时为 user reminder。
  101. role: mcs ? "system" : "user",
  102. evidenceLabel: label,
  103. body: `${guideOneMarker}: apply the first guide after the Read result batch.`,
  104. });
  105. expect(JSON.stringify(firstWire.messages.slice(0, firstWire.index + 1))).toContain(
  106. '"type":"tool_result"',
  107. );
  108. // 工具批次之后的 guide 不重新起算:提醒按 Read 响应的上下文(默认 usage 128/16)倒数,排在 guide 之后。
  109. expect(totalTokensAfterLastAssistant(firstEvidence[0]!.requestJson)).toEqual([
  110. TOTAL_TOKENS_BUDGET - 144,
  111. ]);
  112. const firstTail = JSON.stringify(
  113. firstWire.messages.slice(
  114. firstWire.messages.findLastIndex((message) => message.role === "assistant") + 1,
  115. ),
  116. );
  117. // 先确认 guide 在尾部:indexOf 找不到时是 -1,顺序比较会空过。
  118. expect(firstTail.indexOf(guideOneMarker)).toBeGreaterThanOrEqual(0);
  119. expect(firstTail.indexOf(guideOneMarker)).toBeLessThan(firstTail.indexOf("<total_tokens>"));
  120. await waitForV4UserMessageContaining(guideOneMarker);
  121. await waitForV4ConversationState(
  122. (snapshot) => snapshot.state === "streaming",
  123. "P06 guide-1 续跑没有保持 streaming",
  124. 15000,
  125. );
  126. await sendV4Prompt(`${guideTwoMarker}: apply the second guide after the text-only response.`);
  127. await waitForGuidedPromptProjection(guideTwoMarker);
  128. await waitForUpstreamRequest(
  129. {
  130. includes: [guideTwoMarker, middleAssistantMarker],
  131. lastUserMessageIncludes: [guideTwoMarker],
  132. },
  133. "P06 guide-2 没有在 text-only assistant 完成后进入同一 active turn",
  134. 30000,
  135. { afterIndex: lastRequestIndexBefore },
  136. );
  137. const secondEvidence = await getUpstreamRequestEvidence(
  138. { includes: [guideTwoMarker, middleAssistantMarker] },
  139. { afterIndex: lastRequestIndexBefore },
  140. );
  141. const secondWire = await assertIncomingMessage(secondEvidence[0]!.requestJson, {
  142. presentation: "user_steer",
  143. marker: guideTwoMarker,
  144. evidenceLabel: label,
  145. // text-only 回复之后没有 user/tool 锚点,MCS 下降级为 user reminder。
  146. role: "user",
  147. mcsFallback: mcs,
  148. body: `${guideTwoMarker}: apply the second guide after the text-only response.`,
  149. });
  150. expect(secondWire.messages[secondWire.index - 1]?.role).toBe("assistant");
  151. expect(JSON.stringify(secondWire.messages[secondWire.index - 1]?.content)).toContain(
  152. middleAssistantMarker,
  153. );
  154. // 纯文本回复之后取出的 guide 按用户发言处理,预算提醒重新起算。
  155. expect(totalTokensAfterLastAssistant(secondEvidence[0]!.requestJson)).toEqual([
  156. TOTAL_TOKENS_BUDGET,
  157. ]);
  158. await waitForV4UserMessageContaining(guideTwoMarker);
  159. await waitForV4AssistantMessageContaining(finalAssistantMarker);
  160. await waitForV4ConversationState(
  161. (snapshot) => snapshot.state !== "streaming" && snapshot.runtimeStatus !== "streaming",
  162. "P06 两次 guide drain 后会话没有完成",
  163. 30000,
  164. );
  165. expect(await getQueueItems()).toHaveLength(0);
  166. // 同选择 Guide 可重新解析配置,但不能误触发切模前缀变化;检查实际请求而非模型自述。
  167. const requests = await getUpstreamRequestEvidence(
  168. { includes: [baseMarker] },
  169. { afterIndex: lastRequestIndexBefore },
  170. );
  171. // 辅助的标题/摘要调用也可能引用用户正文;这里只比较主执行的流式请求。
  172. const prefixes = requests
  173. .filter(({ requestJson }) => (requestJson as { stream?: boolean }).stream === true)
  174. .map(({ requestJson }) => {
  175. const body = requestJson as {
  176. system?: unknown;
  177. messages?: Array<{ role: string; content: unknown }>;
  178. };
  179. const messages = body.messages ?? [];
  180. const firstUser = messages.findIndex((message) => message.role !== "system");
  181. return body.system ?? messages.slice(0, firstUser < 0 ? messages.length : firstUser);
  182. });
  183. expect(prefixes.length).toBeGreaterThanOrEqual(3);
  184. expect(prefixes[0]).toBeTruthy();
  185. expect(JSON.stringify(prefixes[0]).length).toBeGreaterThan(2);
  186. for (const prefix of prefixes.slice(1)) expect(prefix).toEqual(prefixes[0]);
  187. const expectedSequence = [
  188. "base-user",
  189. "work-segment",
  190. "guide-one",
  191. "work-segment",
  192. "middle-assistant",
  193. "guide-two",
  194. "work-segment",
  195. "final-assistant",
  196. ];
  197. const dom = await waitForGuideTimelineDomOrder(
  198. {
  199. baseMarker,
  200. finalAssistantMarker,
  201. guideOneMarker,
  202. guideTwoMarker,
  203. middleAssistantMarker,
  204. },
  205. expectedSequence,
  206. );
  207. expect(dom.sequence).toEqual(expectedSequence);
  208. expect(dom.historyTriggerCount).toBe(3);
  209. expect(dom.turnId).toBeTruthy();
  210. const sessionId = (await getV4ConversationState()).taskId!;
  211. await browser.reloadSession();
  212. await waitForDefaultWorkspaceReady(60_000);
  213. await selectV4TaskById(sessionId);
  214. await waitForV4ConversationState(
  215. (state) => state.taskId === sessionId,
  216. "P06 冷恢复未回到原会话",
  217. 30_000,
  218. );
  219. await switchIncomingMessageCapability(!mcs);
  220. const restoredMarker = `E2E_GUIDE_TIMELINE_RESTORED_${runId}`;
  221. const restoredBody = `${restoredMarker}: Continue after cold restore and a model capability switch.
  222. Message from coordinator:
  223. <subagent-message>ordinary user supplied text</subagent-message>`;
  224. await sendV4Prompt(restoredBody);
  225. await waitForUpstreamRequest(
  226. { lastUserMessageIncludes: [restoredMarker] },
  227. "P06 冷恢复请求缺失",
  228. );
  229. const restored = (
  230. await getUpstreamRequestEvidence({ lastUserMessageIncludes: [restoredMarker] })
  231. )[0]!;
  232. // Bug 原因:切换模型后,模型说明作为本轮输入附件排在用户输入之后;切到 MCS 时它是独立的
  233. // system 消息,at(-1) 取到的是它而不是本轮输入。这里跳过末尾的 system 消息。
  234. const lastInput = (
  235. restored.requestJson as { messages: Array<{ role: string; content: unknown }> }
  236. ).messages.findLast((message) => message.role !== "system")!;
  237. expect(lastInput.role).toBe("user");
  238. expect(wireText(lastInput.content)).toContain(restoredBody);
  239. expect(wireText(lastInput.content)).not.toContain(
  240. "The coordinator sent a message while you were working:",
  241. );
  242. expect(wireText(lastInput.content)).not.toContain("Another ZCode session sent a message:");
  243. for (const [marker, body] of [
  244. [guideOneMarker, `${guideOneMarker}: apply the first guide after the Read result batch.`],
  245. [guideTwoMarker, `${guideTwoMarker}: apply the second guide after the text-only response.`],
  246. ] as const) {
  247. // 冷恢复后按切换后的能力投影:工具后的 guide 在 MCS 下为 system,text-only 之后的降级为 user。
  248. const afterTool = marker === guideOneMarker;
  249. await assertIncomingMessage(restored.requestJson, {
  250. presentation: "user_steer",
  251. marker,
  252. body,
  253. role: !mcs && afterTool ? "system" : "user",
  254. mcsFallback: !mcs && !afterTool,
  255. evidenceLabel: `${label}-cold-switched`,
  256. });
  257. }
  258. await waitForV4AssistantMessageContaining("guide-timeline-restored-ok");
  259. });
  260. }
  261. it("M06f MCS:同一 tool batch 期间发送的两条 guide 一起 drain,并共用一个工作段", async function () {
  262. this.timeout(150000);
  263. await prepareIncomingMessageCapability(true);
  264. expect((await readSettings()).zcodeInteractionBehavior).toBe("guide");
  265. const runId = Date.now();
  266. const baseMarker = `E2E_GUIDE_BATCH_BASE_${runId}`;
  267. const guideOneMarker = `E2E_GUIDE_BATCH_GUIDE_ONE_${runId}`;
  268. const guideTwoMarker = `E2E_GUIDE_BATCH_GUIDE_TWO_${runId}`;
  269. const finalAssistantMarker = "guide-batch-final-assistant-ok";
  270. const lastRequestIndexBefore = (await getUpstreamRequestRecordCount()) - 1;
  271. await sendV4Prompt(
  272. `${baseMarker}: Read the readonly fixture, then follow both guide messages.`,
  273. );
  274. await waitForUpstreamRequest(
  275. { lastUserMessageIncludes: [baseMarker] },
  276. "M06f 首轮 provider request 没有发出",
  277. 30000,
  278. { afterIndex: lastRequestIndexBefore },
  279. );
  280. await waitForV4ConversationState(
  281. (snapshot) => snapshot.state === "streaming",
  282. "M06f 首轮请求没有保持 guide 可 admission 的 running 窗口",
  283. 15000,
  284. );
  285. // 两条 guide 都在 Read 的 tool batch 完成前进入等待。
  286. await sendV4Prompt(`${guideOneMarker}: first guide during the Read batch.`);
  287. await waitForGuidedPromptProjection(guideOneMarker);
  288. await sendV4Prompt(`${guideTwoMarker}: second guide during the Read batch.`);
  289. await waitForGuidedPromptProjection(guideTwoMarker);
  290. await waitForUpstreamRequest(
  291. { includes: [guideOneMarker, guideTwoMarker, E2E_READONLY_TOOL_FILE_CONTENT] },
  292. "M06f 两条 guide 没有在同一 Read result batch 后一起进入请求",
  293. 30000,
  294. { afterIndex: lastRequestIndexBefore },
  295. );
  296. // 同一边界一次取出:带 guide-1 的主请求都同时带 guide-2,且按 admission 顺序排列。
  297. const guideRequests = (
  298. await getUpstreamRequestEvidence(
  299. { includes: [guideOneMarker] },
  300. { afterIndex: lastRequestIndexBefore },
  301. )
  302. ).filter(({ requestJson }) => (requestJson as { stream?: boolean }).stream === true);
  303. expect(guideRequests.length).toBeGreaterThan(0);
  304. for (const { requestJson } of guideRequests) {
  305. const body = JSON.stringify(requestJson);
  306. expect(body).toContain(guideTwoMarker);
  307. expect(body.indexOf(guideOneMarker)).toBeLessThan(body.indexOf(guideTwoMarker));
  308. }
  309. await waitForV4AssistantMessageContaining(finalAssistantMarker);
  310. await waitForV4ConversationState(
  311. (snapshot) => snapshot.state !== "streaming" && snapshot.runtimeStatus !== "streaming",
  312. "M06f 两条 guide drain 后会话没有完成",
  313. 30000,
  314. );
  315. expect(await getQueueItems()).toHaveLength(0);
  316. const markers = {
  317. baseMarker,
  318. finalAssistantMarker,
  319. guideOneMarker,
  320. guideTwoMarker,
  321. middleAssistantMarker: `guide-batch-no-middle-${runId}`,
  322. };
  323. // 相邻 guide 共用第一条开启的工作段,中间不出现空的“已工作”。
  324. const expectedSequence = [
  325. "base-user",
  326. "work-segment",
  327. "guide-one",
  328. "guide-two",
  329. "work-segment",
  330. "final-assistant",
  331. ];
  332. expect((await waitForGuideTimelineDomOrder(markers, expectedSequence)).sequence).toEqual(
  333. expectedSequence,
  334. );
  335. // 冷恢复为每条 guide 各合成一个 drained 事件,工作段必须与 live 相同。
  336. const sessionId = (await getV4ConversationState()).taskId!;
  337. await browser.reloadSession();
  338. await waitForDefaultWorkspaceReady(60_000);
  339. await selectV4TaskById(sessionId);
  340. await waitForV4ConversationState(
  341. (state) => state.taskId === sessionId,
  342. "M06f 冷恢复未回到原会话",
  343. 30_000,
  344. );
  345. expect((await waitForGuideTimelineDomOrder(markers, expectedSequence)).sequence).toEqual(
  346. expectedSequence,
  347. );
  348. });
  349. it("guide 模式下 running 中发送引导消息,不得从 steer 队列和历史中消失", async function () {
  350. this.timeout(150000);
  351. await prepareV4ConversationE2E({ resetDraftBeforeProvider: true });
  352. expect((await readSettings()).zcodeInteractionBehavior).toBe("guide");
  353. const runId = Date.now();
  354. const runningMarker = `E2E_RUNNING_GUIDE_STEER_BASE_${runId}`;
  355. const guidedMarker = `E2E_RUNNING_GUIDE_STEER_FOLLOWUP_${runId}`;
  356. const runningPrompt = `E2E_SLOW_STREAM ${runningMarker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  357. await sendV4Prompt(runningPrompt);
  358. await waitForV4ComposerText("", "running guide steer 基础消息发送后输入框没有清空");
  359. await waitForV4UserMessageContaining(runningMarker);
  360. await waitForV4ConversationState(
  361. (snapshot) => snapshot.state === "streaming",
  362. "running guide steer 基础消息没有进入 streaming",
  363. 30000,
  364. );
  365. await waitForUpstreamRequestContaining(runningMarker);
  366. const runningSnapshot = await getV4ConversationState();
  367. expect(runningSnapshot.taskId).toBeTruthy();
  368. const storeSnapshot = await waitForTaskStoreSnapshot(
  369. runningSnapshot.taskId!,
  370. (snapshot) => snapshot.workspaceKey !== null,
  371. "running guide steer 基础消息没有进入 task store",
  372. );
  373. expect(storeSnapshot.selectedProvider).toBe("glm");
  374. expect(storeSnapshot.queueCount).toBe(0);
  375. const guidedPrompt = `${guidedMarker}: Keep guiding the current turn and preserve this message.`;
  376. await sendV4Prompt(guidedPrompt);
  377. await waitForV4ComposerText("", "running guide steer 引导消息发送后输入框没有清空");
  378. await browser.waitUntil(
  379. () =>
  380. browser.execute((marker) => {
  381. const list = document.querySelector('[data-v4-pending-guide-list="true"]');
  382. const row = Array.from(list?.querySelectorAll<HTMLElement>("[data-row-id]") ?? []).find(
  383. (element) => element.innerText.includes(marker),
  384. );
  385. return Boolean(row?.querySelector('[data-v4-user-input-status="true"]'));
  386. }, guidedMarker),
  387. { timeout: 15000, timeoutMsg: "引导消息没有显示等待提示,无法检查对齐" },
  388. );
  389. const alignment = await browser.execute((marker) => {
  390. const list = document.querySelector('[data-v4-pending-guide-list="true"]');
  391. const row = Array.from(list?.querySelectorAll<HTMLElement>("[data-row-id]") ?? []).find(
  392. (element) => element.innerText.includes(marker),
  393. )!;
  394. const status = row.querySelector<HTMLElement>('[data-v4-user-input-status="true"]')!;
  395. const bubble = row.querySelector<HTMLElement>('[data-v4-user-input-bubble="true"]')!;
  396. const composer = document.querySelector<HTMLElement>(".chat-composer-input-surface")!;
  397. return {
  398. rowRight: row.getBoundingClientRect().right,
  399. statusRight: status.getBoundingClientRect().right,
  400. bubbleRight: bubble.getBoundingClientRect().right,
  401. composerRight: composer.getBoundingClientRect().right,
  402. };
  403. }, guidedMarker);
  404. // 回归原因:待引导列表绕过轮容器后漏掉水平留白,气泡和等待提示比输入框更靠右。
  405. for (const right of [alignment.rowRight, alignment.statusRight, alignment.bubbleRight]) {
  406. expect(Math.abs(right - alignment.composerRight)).toBeLessThanOrEqual(1);
  407. }
  408. const firstProjection = await waitForGuidedPromptProjection(guidedMarker);
  409. expect(firstProjection.location).not.toBe("missing");
  410. if (firstProjection.location === "queue") {
  411. // 修复原因:V4 将 guide admission 暂存在 host runtime sendText queue,
  412. // 旧 renderer-local DOM 才暴露 turn-steer;最终语义由 drain 后的 user row 校验。
  413. expect(["turn-steer", "text"]).toContain(firstProjection.kind);
  414. expect(["submitting", "queued"]).toContain(firstProjection.status);
  415. }
  416. // 修复原因:用户反馈的是 guide/steer 模式下消息短暂出现后丢失;
  417. // 因此不仅要验证入队瞬间,还要等一小段时间确认它仍在 steer 队列、
  418. // 已转为普通本地队列,或已经投影成 user message。
  419. await browser.pause(1500);
  420. const stableProjection = await getGuidedPromptProjection(guidedMarker);
  421. expect(stableProjection.location).not.toBe("missing");
  422. });
  423. it("guide 模式下 active goal 运行中发送引导消息,不得 stop active target", async function () {
  424. this.timeout(150000);
  425. await prepareV4ConversationE2E({ resetDraftBeforeProvider: true });
  426. expect((await readSettings()).zcodeInteractionBehavior).toBe("guide");
  427. const runId = Date.now();
  428. await establishGuideGoalSession(`E2E_RUNNING_GUIDE_GOAL_SEED_ACTIVE_${runId}`);
  429. const goalMarker = `E2E_RUNNING_GUIDE_GOAL_ACTIVE_${runId}`;
  430. const guidedMarker = `E2E_RUNNING_GUIDE_GOAL_STEER_${runId}`;
  431. const requestCountBefore = await getUpstreamRequestRecordCount();
  432. const lastRequestIndexBefore = requestCountBefore - 1;
  433. const goalPrompt = `/goal E2E_SLOW_STREAM ${goalMarker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  434. await sendV4Prompt(goalPrompt);
  435. await waitForV4ComposerText("", "running guide goal steer 目标消息发送后输入框没有清空");
  436. await waitForV4UserMessageContaining(goalMarker);
  437. await waitForUpstreamRequest(
  438. {
  439. includes: [goalMarker, "Continue working toward the active session goal"],
  440. },
  441. "running guide goal steer active goal continuation request 没有发出",
  442. 30000,
  443. { afterIndex: lastRequestIndexBefore },
  444. );
  445. await waitForV4GoalProjection(
  446. goalMarker,
  447. ["active"],
  448. "running guide goal steer 没有形成 active goal 投影",
  449. );
  450. const guidedPrompt = `${guidedMarker}: Guide the active goal without stopping it.`;
  451. await sendV4Prompt(guidedPrompt);
  452. await waitForV4ComposerText("", "running guide goal steer 引导消息发送后输入框没有清空");
  453. const firstProjection = await waitForGuidedPromptProjection(guidedMarker);
  454. expect(firstProjection.location).not.toBe("missing");
  455. if (firstProjection.location === "queue") {
  456. expect(["turn-steer", "text"]).toContain(firstProjection.kind);
  457. expect(["submitting", "queued"]).toContain(firstProjection.status);
  458. }
  459. await waitForUpstreamRequestContaining(guidedMarker, 30000);
  460. const afterGuide = await getV4ConversationState();
  461. expect(afterGuide.stopRequested).toBe(false);
  462. const goalAfterGuide = await waitForV4GoalProjection(
  463. goalMarker,
  464. ["active", "verifying"],
  465. "running guide goal steer drain 后 active goal 投影丢失",
  466. );
  467. expect(goalAfterGuide.objective).toContain(goalMarker);
  468. await browser.pause(1500);
  469. const stableProjection = await getGuidedPromptProjection(guidedMarker);
  470. expect(stableProjection.location).not.toBe("missing");
  471. const stableSnapshot = await getV4ConversationState();
  472. expect(stableSnapshot.stopRequested).toBe(false);
  473. const stableGoal = await getV4GoalProjection();
  474. expect(stableGoal?.status).toBe("active");
  475. expect(stableGoal?.objective).toContain(goalMarker);
  476. });
  477. it("guide 模式下 goal verifier 运行中发送消息,应保留为 future queue 且不 stop active target", async function () {
  478. this.timeout(150000);
  479. await prepareV4ConversationE2E({ resetDraftBeforeProvider: true });
  480. expect((await readSettings()).zcodeInteractionBehavior).toBe("guide");
  481. const runId = Date.now();
  482. await establishGuideGoalSession(`E2E_RUNNING_GUIDE_GOAL_SEED_VERIFY_${runId}`);
  483. const goalMarker = `E2E_RUNNING_GUIDE_GOAL_VERIFY_${runId}`;
  484. const guidedMarker = `E2E_RUNNING_GUIDE_GOAL_VERIFY_QUEUE_${runId}`;
  485. const requestCountBefore = await getUpstreamRequestRecordCount();
  486. const lastRequestIndexBefore = requestCountBefore - 1;
  487. const goalPrompt = `/goal ${goalMarker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  488. await sendV4Prompt(goalPrompt);
  489. await waitForV4ComposerText(
  490. "",
  491. "running guide goal verifier steer 目标消息发送后输入框没有清空",
  492. );
  493. await waitForV4UserMessageContaining(goalMarker);
  494. await waitForUpstreamRequest(
  495. {
  496. includes: [goalMarker, "Verify whether the active session goal"],
  497. },
  498. "running guide goal verifier steer 没有进入 verifier request",
  499. 90000,
  500. { afterIndex: lastRequestIndexBefore },
  501. );
  502. await waitForV4GoalProjection(
  503. goalMarker,
  504. ["active", "verifying"],
  505. "running guide goal verifier steer 没有形成 verifier goal 投影",
  506. );
  507. const guidedPrompt = `${guidedMarker}: Queue guidance while the active verifier keeps running.`;
  508. await sendV4Prompt(guidedPrompt);
  509. await waitForV4ComposerText(
  510. "",
  511. "running guide goal verifier steer 引导消息发送后输入框没有清空",
  512. );
  513. const firstProjection = await waitForGuidedPromptProjection(guidedMarker);
  514. expect(firstProjection.location).toBe("queue");
  515. if (firstProjection.location !== "queue") {
  516. throw new Error(
  517. `running guide goal verifier queue 投影位置不正确: ${JSON.stringify(firstProjection)}`,
  518. );
  519. }
  520. expect(firstProjection.kind).toBe("text");
  521. expect(firstProjection.status).toBe("queued");
  522. const afterGuide = await getV4ConversationState();
  523. expect(afterGuide.stopRequested).toBe(false);
  524. const goalAfterGuide = await getV4GoalProjection();
  525. expect(["active", "verifying"]).toContain(goalAfterGuide?.status);
  526. expect(goalAfterGuide?.objective).toContain(goalMarker);
  527. });
  528. });
  529. async function establishGuideGoalSession(seedMarker: string) {
  530. // 修复原因:draft prewarm 不是 active goal/goal verifier 的产品前置态;直接把 /goal
  531. // 作为首条输入会把 prewarm admission 混入断言。先建立稳定 session,再验证目标链路。
  532. await sendV4Prompt(
  533. `${seedMarker}: Reply with exactly "${GUIDE_GOAL_SEED_REPLY}" and no other text.`,
  534. );
  535. await waitForV4ComposerText("", "running guide goal seed 发送后输入框没有清空");
  536. await waitForV4UserMessageContaining(seedMarker);
  537. await waitForV4AssistantMessageContaining(GUIDE_GOAL_SEED_REPLY);
  538. await waitForV4ConversationState(
  539. (snapshot) =>
  540. snapshot.taskId !== null &&
  541. snapshot.state !== "streaming" &&
  542. snapshot.runtimeStatus !== "streaming",
  543. "running guide goal seed 没有建立稳定 session",
  544. 30000,
  545. );
  546. }
  547. async function waitForV4GoalProjection(
  548. marker: string,
  549. statuses: readonly string[],
  550. timeoutMsg: string,
  551. ) {
  552. let latest = await getV4GoalProjection();
  553. try {
  554. await browser.waitUntil(
  555. async () => {
  556. latest = await getV4GoalProjection();
  557. return (
  558. latest?.objective?.includes(marker) === true &&
  559. latest.status !== null &&
  560. statuses.includes(latest.status)
  561. );
  562. },
  563. { timeout: 30000, timeoutMsg },
  564. );
  565. } catch (error) {
  566. latest = await getV4GoalProjection();
  567. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, { cause: error });
  568. }
  569. if (!latest) {
  570. throw new Error(`${timeoutMsg}; latest=null`);
  571. }
  572. return latest;
  573. }
  574. type GuidedPromptProjection =
  575. | { location: "queue"; kind: string | null; status: string | null }
  576. | { location: "user-message"; id: string | null }
  577. | { location: "missing"; queue: unknown[]; userMessages: unknown[] };
  578. interface GuideTimelineMarkers {
  579. baseMarker: string;
  580. finalAssistantMarker: string;
  581. guideOneMarker: string;
  582. guideTwoMarker: string;
  583. middleAssistantMarker: string;
  584. }
  585. interface GuideTimelineDomSnapshot {
  586. historyTriggerCount: number;
  587. sequence: string[];
  588. turnId: string | null;
  589. }
  590. async function waitForGuideTimelineDomOrder(
  591. markers: GuideTimelineMarkers,
  592. expectedSequence: string[],
  593. ): Promise<GuideTimelineDomSnapshot> {
  594. let latest: GuideTimelineDomSnapshot = {
  595. historyTriggerCount: 0,
  596. sequence: [],
  597. turnId: null,
  598. };
  599. try {
  600. await browser.waitUntil(
  601. async () => {
  602. latest = await getGuideTimelineDomSnapshot(markers);
  603. return JSON.stringify(latest.sequence) === JSON.stringify(expectedSequence);
  604. },
  605. {
  606. timeout: 30000,
  607. timeoutMsg: "P06 steer 与工作段没有按 CLI row 全序渲染",
  608. },
  609. );
  610. } catch (error) {
  611. latest = await getGuideTimelineDomSnapshot(markers);
  612. throw new Error(
  613. `P06 steer DOM 顺序错误; expected=${JSON.stringify(expectedSequence)}; latest=${JSON.stringify(latest)}`,
  614. { cause: error },
  615. );
  616. }
  617. return latest;
  618. }
  619. function getGuideTimelineDomSnapshot(
  620. markers: GuideTimelineMarkers,
  621. ): Promise<GuideTimelineDomSnapshot> {
  622. return browser.execute(
  623. (timelineTestId, historyTriggerPrefix, expectedMarkers) => {
  624. const normalizeText = (value: string) => value.replace(/\u00a0/g, " ").trim();
  625. const timeline = document.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  626. const rowElements = Array.from(
  627. timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [],
  628. );
  629. const baseRow = rowElements.find(
  630. (element) =>
  631. element.classList.contains("group/user-row") &&
  632. normalizeText(element.innerText).includes(expectedMarkers.baseMarker),
  633. );
  634. const turn = baseRow?.closest<HTMLElement>("[data-turn-id]") ?? null;
  635. if (!turn) {
  636. return { historyTriggerCount: 0, sequence: [], turnId: null };
  637. }
  638. const sequence = Array.from(
  639. turn.querySelectorAll<HTMLElement>(
  640. `[data-row-id],[data-testid^="${historyTriggerPrefix}-"]`,
  641. ),
  642. )
  643. .map((element) => {
  644. const testIdValue = element.getAttribute("data-testid") ?? "";
  645. if (testIdValue.startsWith(`${historyTriggerPrefix}-`)) return "work-segment";
  646. const text = normalizeText(element.innerText);
  647. if (text.includes(expectedMarkers.baseMarker)) return "base-user";
  648. if (text.includes(expectedMarkers.guideOneMarker)) return "guide-one";
  649. if (text.includes(expectedMarkers.middleAssistantMarker)) return "middle-assistant";
  650. if (text.includes(expectedMarkers.guideTwoMarker)) return "guide-two";
  651. if (text.includes(expectedMarkers.finalAssistantMarker)) return "final-assistant";
  652. return null;
  653. })
  654. .filter((item) => item !== null);
  655. return {
  656. historyTriggerCount: sequence.filter((item) => item === "work-segment").length,
  657. sequence,
  658. turnId: turn.getAttribute("data-turn-id"),
  659. };
  660. },
  661. TID_V4_TIMELINE,
  662. TID_CHAT_ASSISTANT_HISTORY_TRIGGER,
  663. markers,
  664. );
  665. }
  666. async function waitForGuidedPromptProjection(marker: string): Promise<GuidedPromptProjection> {
  667. let latest: GuidedPromptProjection = {
  668. location: "missing",
  669. queue: [],
  670. userMessages: [],
  671. };
  672. await browser.waitUntil(
  673. async () => {
  674. latest = await getGuidedPromptProjection(marker);
  675. return latest.location !== "missing";
  676. },
  677. {
  678. timeout: 30000,
  679. timeoutMsg: `running guide steer 没有观察到引导消息投影: ${marker}`,
  680. },
  681. );
  682. return latest;
  683. }
  684. async function getGuidedPromptProjection(marker: string): Promise<GuidedPromptProjection> {
  685. const queue = await getQueueItems();
  686. const queued = queue.find((item) => item.content.includes(marker));
  687. if (queued) {
  688. return {
  689. kind: queued.kind,
  690. location: "queue",
  691. status: queued.status,
  692. };
  693. }
  694. const userMessages = await getV4Messages("user");
  695. const message = userMessages.find((candidate) => candidate.text.includes(marker));
  696. if (message) {
  697. return {
  698. id: message.id,
  699. location: "user-message",
  700. };
  701. }
  702. return {
  703. location: "missing",
  704. queue,
  705. userMessages,
  706. };
  707. }
  708. async function stopIfBusy() {
  709. const snapshot = await getV4ConversationState().catch(() => null);
  710. // 修复原因:goal verifier 运行时 ChatView 普通消息状态可能已是 idle,
  711. // 但 task runtime 仍在 streaming;清理阶段必须按 runtime 状态补停。
  712. if (snapshot?.state !== "streaming" && snapshot?.runtimeStatus !== "streaming") {
  713. return;
  714. }
  715. await clickV4Stop().catch(() => undefined);
  716. await waitForV4ConversationState(
  717. (candidate) => candidate.state !== "streaming" && candidate.runtimeStatus !== "streaming",
  718. "running guide steer 清理阶段没有退出 streaming",
  719. 30000,
  720. ).catch(() => undefined);
  721. await getQueueItems().catch(() => []);
  722. }