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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. import { assertIncomingMessage, wireText } from "../helpers/incoming-message-evidence.js";
  2. import {
  3. INCOMING_MESSAGE_MODES,
  4. prepareIncomingMessageCapability,
  5. switchIncomingMessageCapability,
  6. } from "../helpers/incoming-message-capability.js";
  7. import { TID_CHAT_ASSISTANT_HISTORY_TRIGGER, TID_V4_TIMELINE } from "@zcode/shared";
  8. import {
  9. clearAppData,
  10. readSettings,
  11. waitForDefaultWorkspaceReady,
  12. } from "../helpers/desktop-app.js";
  13. import {
  14. E2E_READONLY_TOOL_FILE_CONTENT,
  15. ensureReadonlyToolFixtureFile,
  16. } from "../helpers/conversation-session-readonly-tool.js";
  17. import {
  18. getUpstreamRequestRecordCount,
  19. getUpstreamRequestEvidence,
  20. waitForUpstreamRequest,
  21. waitForUpstreamRequestContaining,
  22. } from "../helpers/conversation-session-network.js";
  23. import { getQueueItems } from "../helpers/conversation-session-queue.js";
  24. import { waitForTaskStoreSnapshot } from "../helpers/conversation-session-store.js";
  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 "../helpers/v4-conversation.js";
  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. role: mcs ? "system" : "user",
  101. evidenceLabel: label,
  102. body: `${guideOneMarker}: apply the first guide after the Read result batch.`,
  103. });
  104. expect(JSON.stringify(firstWire.messages.slice(0, firstWire.index + 1))).toContain(
  105. '"type":"tool_result"',
  106. );
  107. await waitForV4UserMessageContaining(guideOneMarker);
  108. await waitForV4ConversationState(
  109. (snapshot) => snapshot.state === "streaming",
  110. "P06 guide-1 续跑没有保持 streaming",
  111. 15000,
  112. );
  113. await sendV4Prompt(`${guideTwoMarker}: apply the second guide after the text-only response.`);
  114. await waitForGuidedPromptProjection(guideTwoMarker);
  115. await waitForUpstreamRequest(
  116. {
  117. includes: [guideTwoMarker, middleAssistantMarker],
  118. lastUserMessageIncludes: [guideTwoMarker],
  119. },
  120. "P06 guide-2 没有在 text-only assistant 完成后进入同一 active turn",
  121. 30000,
  122. { afterIndex: lastRequestIndexBefore },
  123. );
  124. const secondEvidence = await getUpstreamRequestEvidence(
  125. { includes: [guideTwoMarker, middleAssistantMarker] },
  126. { afterIndex: lastRequestIndexBefore },
  127. );
  128. const secondWire = await assertIncomingMessage(secondEvidence[0]!.requestJson, {
  129. presentation: "user_steer",
  130. marker: guideTwoMarker,
  131. evidenceLabel: label,
  132. role: "user",
  133. body: `${guideTwoMarker}: apply the second guide after the text-only response.`,
  134. });
  135. expect(secondWire.messages[secondWire.index - 1]?.role).toBe("assistant");
  136. expect(JSON.stringify(secondWire.messages[secondWire.index - 1]?.content)).toContain(
  137. middleAssistantMarker,
  138. );
  139. await waitForV4UserMessageContaining(guideTwoMarker);
  140. await waitForV4AssistantMessageContaining(finalAssistantMarker);
  141. await waitForV4ConversationState(
  142. (snapshot) => snapshot.state !== "streaming" && snapshot.runtimeStatus !== "streaming",
  143. "P06 两次 guide drain 后会话没有完成",
  144. 30000,
  145. );
  146. expect(await getQueueItems()).toHaveLength(0);
  147. // 同选择 Guide 可重新解析配置,但不能误触发切模前缀变化;检查实际请求而非模型自述。
  148. const requests = await getUpstreamRequestEvidence(
  149. { includes: [baseMarker] },
  150. { afterIndex: lastRequestIndexBefore },
  151. );
  152. // 辅助的标题/摘要调用也可能引用用户正文;这里只比较主执行的流式请求。
  153. const prefixes = requests
  154. .filter(({ requestJson }) => (requestJson as { stream?: boolean }).stream === true)
  155. .map(({ requestJson }) => {
  156. const body = requestJson as {
  157. system?: unknown;
  158. messages?: Array<{ role: string; content: unknown }>;
  159. };
  160. const messages = body.messages ?? [];
  161. const firstUser = messages.findIndex((message) => message.role !== "system");
  162. return body.system ?? messages.slice(0, firstUser < 0 ? messages.length : firstUser);
  163. });
  164. expect(prefixes.length).toBeGreaterThanOrEqual(3);
  165. expect(prefixes[0]).toBeTruthy();
  166. expect(JSON.stringify(prefixes[0]).length).toBeGreaterThan(2);
  167. for (const prefix of prefixes.slice(1)) expect(prefix).toEqual(prefixes[0]);
  168. const expectedSequence = [
  169. "base-user",
  170. "work-segment",
  171. "guide-one",
  172. "work-segment",
  173. "middle-assistant",
  174. "guide-two",
  175. "work-segment",
  176. "final-assistant",
  177. ];
  178. const dom = await waitForGuideTimelineDomOrder(
  179. {
  180. baseMarker,
  181. finalAssistantMarker,
  182. guideOneMarker,
  183. guideTwoMarker,
  184. middleAssistantMarker,
  185. },
  186. expectedSequence,
  187. );
  188. expect(dom.sequence).toEqual(expectedSequence);
  189. expect(dom.historyTriggerCount).toBe(3);
  190. expect(dom.turnId).toBeTruthy();
  191. const sessionId = (await getV4ConversationState()).taskId!;
  192. await browser.reloadSession();
  193. await waitForDefaultWorkspaceReady(60_000);
  194. await selectV4TaskById(sessionId);
  195. await waitForV4ConversationState(
  196. (state) => state.taskId === sessionId,
  197. "P06 冷恢复未回到原会话",
  198. 30_000,
  199. );
  200. await switchIncomingMessageCapability(!mcs);
  201. const restoredMarker = `E2E_GUIDE_TIMELINE_RESTORED_${runId}`;
  202. const restoredBody = `${restoredMarker}: Continue after cold restore and a model capability switch.
  203. Message from coordinator:
  204. <subagent-message>ordinary user supplied text</subagent-message>`;
  205. await sendV4Prompt(restoredBody);
  206. await waitForUpstreamRequest(
  207. { lastUserMessageIncludes: [restoredMarker] },
  208. "P06 冷恢复请求缺失",
  209. );
  210. const restored = (
  211. await getUpstreamRequestEvidence({ lastUserMessageIncludes: [restoredMarker] })
  212. )[0]!;
  213. const lastInput = (
  214. restored.requestJson as { messages: Array<{ role: string; content: unknown }> }
  215. ).messages.at(-1)!;
  216. expect(lastInput.role).toBe("user");
  217. expect(wireText(lastInput.content)).toContain(restoredBody);
  218. expect(wireText(lastInput.content)).not.toContain(
  219. "The coordinator sent a message while you were working:",
  220. );
  221. expect(wireText(lastInput.content)).not.toContain("Another ZCode session sent a message:");
  222. for (const [marker, body, role] of [
  223. [
  224. guideOneMarker,
  225. `${guideOneMarker}: apply the first guide after the Read result batch.`,
  226. !mcs ? "system" : "user",
  227. ],
  228. [
  229. guideTwoMarker,
  230. `${guideTwoMarker}: apply the second guide after the text-only response.`,
  231. "user",
  232. ],
  233. ] as const) {
  234. await assertIncomingMessage(restored.requestJson, {
  235. presentation: "user_steer",
  236. marker,
  237. body,
  238. role,
  239. evidenceLabel: `${label}-cold-switched`,
  240. });
  241. }
  242. await waitForV4AssistantMessageContaining("guide-timeline-restored-ok");
  243. });
  244. }
  245. it("guide 模式下 running 中发送引导消息,不得从 steer 队列和历史中消失", async function () {
  246. this.timeout(150000);
  247. await prepareV4ConversationE2E({ resetDraftBeforeProvider: true });
  248. expect((await readSettings()).zcodeInteractionBehavior).toBe("guide");
  249. const runId = Date.now();
  250. const runningMarker = `E2E_RUNNING_GUIDE_STEER_BASE_${runId}`;
  251. const guidedMarker = `E2E_RUNNING_GUIDE_STEER_FOLLOWUP_${runId}`;
  252. const runningPrompt = `E2E_SLOW_STREAM ${runningMarker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  253. await sendV4Prompt(runningPrompt);
  254. await waitForV4ComposerText("", "running guide steer 基础消息发送后输入框没有清空");
  255. await waitForV4UserMessageContaining(runningMarker);
  256. await waitForV4ConversationState(
  257. (snapshot) => snapshot.state === "streaming",
  258. "running guide steer 基础消息没有进入 streaming",
  259. 30000,
  260. );
  261. await waitForUpstreamRequestContaining(runningMarker);
  262. const runningSnapshot = await getV4ConversationState();
  263. expect(runningSnapshot.taskId).toBeTruthy();
  264. const storeSnapshot = await waitForTaskStoreSnapshot(
  265. runningSnapshot.taskId!,
  266. (snapshot) => snapshot.workspaceKey !== null,
  267. "running guide steer 基础消息没有进入 task store",
  268. );
  269. expect(storeSnapshot.selectedProvider).toBe("glm");
  270. expect(storeSnapshot.queueCount).toBe(0);
  271. const guidedPrompt = `${guidedMarker}: Keep guiding the current turn and preserve this message.`;
  272. await sendV4Prompt(guidedPrompt);
  273. await waitForV4ComposerText("", "running guide steer 引导消息发送后输入框没有清空");
  274. await browser.waitUntil(
  275. () =>
  276. browser.execute((marker) => {
  277. const list = document.querySelector('[data-v4-pending-guide-list="true"]');
  278. const row = Array.from(list?.querySelectorAll<HTMLElement>("[data-row-id]") ?? []).find(
  279. (element) => element.innerText.includes(marker),
  280. );
  281. return Boolean(row?.querySelector('[data-v4-user-input-status="true"]'));
  282. }, guidedMarker),
  283. { timeout: 15000, timeoutMsg: "引导消息没有显示等待提示,无法检查对齐" },
  284. );
  285. const alignment = await browser.execute((marker) => {
  286. const list = document.querySelector('[data-v4-pending-guide-list="true"]');
  287. const row = Array.from(list?.querySelectorAll<HTMLElement>("[data-row-id]") ?? []).find(
  288. (element) => element.innerText.includes(marker),
  289. )!;
  290. const status = row.querySelector<HTMLElement>('[data-v4-user-input-status="true"]')!;
  291. const bubble = row.querySelector<HTMLElement>('[data-v4-user-input-bubble="true"]')!;
  292. const composer = document.querySelector<HTMLElement>(".chat-composer-input-surface")!;
  293. return {
  294. rowRight: row.getBoundingClientRect().right,
  295. statusRight: status.getBoundingClientRect().right,
  296. bubbleRight: bubble.getBoundingClientRect().right,
  297. composerRight: composer.getBoundingClientRect().right,
  298. };
  299. }, guidedMarker);
  300. // 回归原因:待引导列表绕过轮容器后漏掉水平留白,气泡和等待提示比输入框更靠右。
  301. for (const right of [alignment.rowRight, alignment.statusRight, alignment.bubbleRight]) {
  302. expect(Math.abs(right - alignment.composerRight)).toBeLessThanOrEqual(1);
  303. }
  304. const firstProjection = await waitForGuidedPromptProjection(guidedMarker);
  305. expect(firstProjection.location).not.toBe("missing");
  306. if (firstProjection.location === "queue") {
  307. // 修复原因:V4 将 guide admission 暂存在 host runtime sendText queue,
  308. // 旧 renderer-local DOM 才暴露 turn-steer;最终语义由 drain 后的 user row 校验。
  309. expect(["turn-steer", "text"]).toContain(firstProjection.kind);
  310. expect(["submitting", "queued"]).toContain(firstProjection.status);
  311. }
  312. // 修复原因:用户反馈的是 guide/steer 模式下消息短暂出现后丢失;
  313. // 因此不仅要验证入队瞬间,还要等一小段时间确认它仍在 steer 队列、
  314. // 已转为普通本地队列,或已经投影成 user message。
  315. await browser.pause(1500);
  316. const stableProjection = await getGuidedPromptProjection(guidedMarker);
  317. expect(stableProjection.location).not.toBe("missing");
  318. });
  319. it("guide 模式下 active goal 运行中发送引导消息,不得 stop active target", async function () {
  320. this.timeout(150000);
  321. await prepareV4ConversationE2E({ resetDraftBeforeProvider: true });
  322. expect((await readSettings()).zcodeInteractionBehavior).toBe("guide");
  323. const runId = Date.now();
  324. await establishGuideGoalSession(`E2E_RUNNING_GUIDE_GOAL_SEED_ACTIVE_${runId}`);
  325. const goalMarker = `E2E_RUNNING_GUIDE_GOAL_ACTIVE_${runId}`;
  326. const guidedMarker = `E2E_RUNNING_GUIDE_GOAL_STEER_${runId}`;
  327. const requestCountBefore = await getUpstreamRequestRecordCount();
  328. const lastRequestIndexBefore = requestCountBefore - 1;
  329. const goalPrompt = `/goal E2E_SLOW_STREAM ${goalMarker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  330. await sendV4Prompt(goalPrompt);
  331. await waitForV4ComposerText("", "running guide goal steer 目标消息发送后输入框没有清空");
  332. await waitForV4UserMessageContaining(goalMarker);
  333. await waitForUpstreamRequest(
  334. {
  335. includes: [goalMarker, "Continue working toward the active session goal"],
  336. },
  337. "running guide goal steer active goal continuation request 没有发出",
  338. 30000,
  339. { afterIndex: lastRequestIndexBefore },
  340. );
  341. await waitForV4GoalProjection(
  342. goalMarker,
  343. ["active"],
  344. "running guide goal steer 没有形成 active goal 投影",
  345. );
  346. const guidedPrompt = `${guidedMarker}: Guide the active goal without stopping it.`;
  347. await sendV4Prompt(guidedPrompt);
  348. await waitForV4ComposerText("", "running guide goal steer 引导消息发送后输入框没有清空");
  349. const firstProjection = await waitForGuidedPromptProjection(guidedMarker);
  350. expect(firstProjection.location).not.toBe("missing");
  351. if (firstProjection.location === "queue") {
  352. expect(["turn-steer", "text"]).toContain(firstProjection.kind);
  353. expect(["submitting", "queued"]).toContain(firstProjection.status);
  354. }
  355. await waitForUpstreamRequestContaining(guidedMarker, 30000);
  356. const afterGuide = await getV4ConversationState();
  357. expect(afterGuide.stopRequested).toBe(false);
  358. const goalAfterGuide = await waitForV4GoalProjection(
  359. goalMarker,
  360. ["active", "verifying"],
  361. "running guide goal steer drain 后 active goal 投影丢失",
  362. );
  363. expect(goalAfterGuide.objective).toContain(goalMarker);
  364. await browser.pause(1500);
  365. const stableProjection = await getGuidedPromptProjection(guidedMarker);
  366. expect(stableProjection.location).not.toBe("missing");
  367. const stableSnapshot = await getV4ConversationState();
  368. expect(stableSnapshot.stopRequested).toBe(false);
  369. const stableGoal = await getV4GoalProjection();
  370. expect(stableGoal?.status).toBe("active");
  371. expect(stableGoal?.objective).toContain(goalMarker);
  372. });
  373. it("guide 模式下 goal verifier 运行中发送消息,应保留为 future queue 且不 stop active target", async function () {
  374. this.timeout(150000);
  375. await prepareV4ConversationE2E({ resetDraftBeforeProvider: true });
  376. expect((await readSettings()).zcodeInteractionBehavior).toBe("guide");
  377. const runId = Date.now();
  378. await establishGuideGoalSession(`E2E_RUNNING_GUIDE_GOAL_SEED_VERIFY_${runId}`);
  379. const goalMarker = `E2E_RUNNING_GUIDE_GOAL_VERIFY_${runId}`;
  380. const guidedMarker = `E2E_RUNNING_GUIDE_GOAL_VERIFY_QUEUE_${runId}`;
  381. const requestCountBefore = await getUpstreamRequestRecordCount();
  382. const lastRequestIndexBefore = requestCountBefore - 1;
  383. const goalPrompt = `/goal ${goalMarker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  384. await sendV4Prompt(goalPrompt);
  385. await waitForV4ComposerText(
  386. "",
  387. "running guide goal verifier steer 目标消息发送后输入框没有清空",
  388. );
  389. await waitForV4UserMessageContaining(goalMarker);
  390. await waitForUpstreamRequest(
  391. {
  392. includes: [goalMarker, "Verify whether the active session goal"],
  393. },
  394. "running guide goal verifier steer 没有进入 verifier request",
  395. 90000,
  396. { afterIndex: lastRequestIndexBefore },
  397. );
  398. await waitForV4GoalProjection(
  399. goalMarker,
  400. ["active", "verifying"],
  401. "running guide goal verifier steer 没有形成 verifier goal 投影",
  402. );
  403. const guidedPrompt = `${guidedMarker}: Queue guidance while the active verifier keeps running.`;
  404. await sendV4Prompt(guidedPrompt);
  405. await waitForV4ComposerText(
  406. "",
  407. "running guide goal verifier steer 引导消息发送后输入框没有清空",
  408. );
  409. const firstProjection = await waitForGuidedPromptProjection(guidedMarker);
  410. expect(firstProjection.location).toBe("queue");
  411. if (firstProjection.location !== "queue") {
  412. throw new Error(
  413. `running guide goal verifier queue 投影位置不正确: ${JSON.stringify(firstProjection)}`,
  414. );
  415. }
  416. expect(firstProjection.kind).toBe("text");
  417. expect(firstProjection.status).toBe("queued");
  418. const afterGuide = await getV4ConversationState();
  419. expect(afterGuide.stopRequested).toBe(false);
  420. const goalAfterGuide = await getV4GoalProjection();
  421. expect(["active", "verifying"]).toContain(goalAfterGuide?.status);
  422. expect(goalAfterGuide?.objective).toContain(goalMarker);
  423. });
  424. });
  425. async function establishGuideGoalSession(seedMarker: string) {
  426. // 修复原因:draft prewarm 不是 active goal/goal verifier 的产品前置态;直接把 /goal
  427. // 作为首条输入会把 prewarm admission 混入断言。先建立稳定 session,再验证目标链路。
  428. await sendV4Prompt(
  429. `${seedMarker}: Reply with exactly "${GUIDE_GOAL_SEED_REPLY}" and no other text.`,
  430. );
  431. await waitForV4ComposerText("", "running guide goal seed 发送后输入框没有清空");
  432. await waitForV4UserMessageContaining(seedMarker);
  433. await waitForV4AssistantMessageContaining(GUIDE_GOAL_SEED_REPLY);
  434. await waitForV4ConversationState(
  435. (snapshot) =>
  436. snapshot.taskId !== null &&
  437. snapshot.state !== "streaming" &&
  438. snapshot.runtimeStatus !== "streaming",
  439. "running guide goal seed 没有建立稳定 session",
  440. 30000,
  441. );
  442. }
  443. async function waitForV4GoalProjection(
  444. marker: string,
  445. statuses: readonly string[],
  446. timeoutMsg: string,
  447. ) {
  448. let latest = await getV4GoalProjection();
  449. try {
  450. await browser.waitUntil(
  451. async () => {
  452. latest = await getV4GoalProjection();
  453. return (
  454. latest?.objective?.includes(marker) === true &&
  455. latest.status !== null &&
  456. statuses.includes(latest.status)
  457. );
  458. },
  459. { timeout: 30000, timeoutMsg },
  460. );
  461. } catch (error) {
  462. latest = await getV4GoalProjection();
  463. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, { cause: error });
  464. }
  465. if (!latest) {
  466. throw new Error(`${timeoutMsg}; latest=null`);
  467. }
  468. return latest;
  469. }
  470. type GuidedPromptProjection =
  471. | { location: "queue"; kind: string | null; status: string | null }
  472. | { location: "user-message"; id: string | null }
  473. | { location: "missing"; queue: unknown[]; userMessages: unknown[] };
  474. interface GuideTimelineMarkers {
  475. baseMarker: string;
  476. finalAssistantMarker: string;
  477. guideOneMarker: string;
  478. guideTwoMarker: string;
  479. middleAssistantMarker: string;
  480. }
  481. interface GuideTimelineDomSnapshot {
  482. historyTriggerCount: number;
  483. sequence: string[];
  484. turnId: string | null;
  485. }
  486. async function waitForGuideTimelineDomOrder(
  487. markers: GuideTimelineMarkers,
  488. expectedSequence: string[],
  489. ): Promise<GuideTimelineDomSnapshot> {
  490. let latest: GuideTimelineDomSnapshot = {
  491. historyTriggerCount: 0,
  492. sequence: [],
  493. turnId: null,
  494. };
  495. try {
  496. await browser.waitUntil(
  497. async () => {
  498. latest = await getGuideTimelineDomSnapshot(markers);
  499. return JSON.stringify(latest.sequence) === JSON.stringify(expectedSequence);
  500. },
  501. {
  502. timeout: 30000,
  503. timeoutMsg: "P06 steer 与工作段没有按 CLI row 全序渲染",
  504. },
  505. );
  506. } catch (error) {
  507. latest = await getGuideTimelineDomSnapshot(markers);
  508. throw new Error(
  509. `P06 steer DOM 顺序错误; expected=${JSON.stringify(expectedSequence)}; latest=${JSON.stringify(latest)}`,
  510. { cause: error },
  511. );
  512. }
  513. return latest;
  514. }
  515. function getGuideTimelineDomSnapshot(
  516. markers: GuideTimelineMarkers,
  517. ): Promise<GuideTimelineDomSnapshot> {
  518. return browser.execute(
  519. (timelineTestId, historyTriggerPrefix, expectedMarkers) => {
  520. const normalizeText = (value: string) => value.replace(/\u00a0/g, " ").trim();
  521. const timeline = document.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  522. const rowElements = Array.from(
  523. timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [],
  524. );
  525. const baseRow = rowElements.find(
  526. (element) =>
  527. element.classList.contains("group/user-row") &&
  528. normalizeText(element.innerText).includes(expectedMarkers.baseMarker),
  529. );
  530. const turn = baseRow?.closest<HTMLElement>("[data-turn-id]") ?? null;
  531. if (!turn) {
  532. return { historyTriggerCount: 0, sequence: [], turnId: null };
  533. }
  534. const sequence = Array.from(
  535. turn.querySelectorAll<HTMLElement>(
  536. `[data-row-id],[data-testid^="${historyTriggerPrefix}-"]`,
  537. ),
  538. )
  539. .map((element) => {
  540. const testIdValue = element.getAttribute("data-testid") ?? "";
  541. if (testIdValue.startsWith(`${historyTriggerPrefix}-`)) return "work-segment";
  542. const text = normalizeText(element.innerText);
  543. if (text.includes(expectedMarkers.baseMarker)) return "base-user";
  544. if (text.includes(expectedMarkers.guideOneMarker)) return "guide-one";
  545. if (text.includes(expectedMarkers.middleAssistantMarker)) return "middle-assistant";
  546. if (text.includes(expectedMarkers.guideTwoMarker)) return "guide-two";
  547. if (text.includes(expectedMarkers.finalAssistantMarker)) return "final-assistant";
  548. return null;
  549. })
  550. .filter((item) => item !== null);
  551. return {
  552. historyTriggerCount: sequence.filter((item) => item === "work-segment").length,
  553. sequence,
  554. turnId: turn.getAttribute("data-turn-id"),
  555. };
  556. },
  557. TID_V4_TIMELINE,
  558. TID_CHAT_ASSISTANT_HISTORY_TRIGGER,
  559. markers,
  560. );
  561. }
  562. async function waitForGuidedPromptProjection(marker: string): Promise<GuidedPromptProjection> {
  563. let latest: GuidedPromptProjection = {
  564. location: "missing",
  565. queue: [],
  566. userMessages: [],
  567. };
  568. await browser.waitUntil(
  569. async () => {
  570. latest = await getGuidedPromptProjection(marker);
  571. return latest.location !== "missing";
  572. },
  573. {
  574. timeout: 30000,
  575. timeoutMsg: `running guide steer 没有观察到引导消息投影: ${marker}`,
  576. },
  577. );
  578. return latest;
  579. }
  580. async function getGuidedPromptProjection(marker: string): Promise<GuidedPromptProjection> {
  581. const queue = await getQueueItems();
  582. const queued = queue.find((item) => item.content.includes(marker));
  583. if (queued) {
  584. return {
  585. kind: queued.kind,
  586. location: "queue",
  587. status: queued.status,
  588. };
  589. }
  590. const userMessages = await getV4Messages("user");
  591. const message = userMessages.find((candidate) => candidate.text.includes(marker));
  592. if (message) {
  593. return {
  594. id: message.id,
  595. location: "user-message",
  596. };
  597. }
  598. return {
  599. location: "missing",
  600. queue,
  601. userMessages,
  602. };
  603. }
  604. async function stopIfBusy() {
  605. const snapshot = await getV4ConversationState().catch(() => null);
  606. // 修复原因:goal verifier 运行时 ChatView 普通消息状态可能已是 idle,
  607. // 但 task runtime 仍在 streaming;清理阶段必须按 runtime 状态补停。
  608. if (snapshot?.state !== "streaming" && snapshot?.runtimeStatus !== "streaming") {
  609. return;
  610. }
  611. await clickV4Stop().catch(() => undefined);
  612. await waitForV4ConversationState(
  613. (candidate) => candidate.state !== "streaming" && candidate.runtimeStatus !== "streaming",
  614. "running guide steer 清理阶段没有退出 streaming",
  615. 30000,
  616. ).catch(() => undefined);
  617. await getQueueItems().catch(() => []);
  618. }