conversation-session-side-chat-reminder.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. import { join } from "node:path";
  2. import { DatabaseSync } from "node:sqlite";
  3. import {
  4. TID_V4_COMPOSER_INPUT,
  5. TID_V4_COMPOSER_SEND,
  6. TID_V4_SESSION_PANE,
  7. testId,
  8. } from "@zcode/shared/test-ids";
  9. import { clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  10. import {
  11. getUpstreamRequestEvidence,
  12. waitForUpstreamRequest,
  13. } from "#e2e/helpers/conversation-session-network";
  14. import {
  15. buildReadonlyToolPrompt,
  16. ensureReadonlyToolFixtureFile,
  17. E2E_READONLY_TOOL_FILE_CONTENT,
  18. } from "#e2e/helpers/conversation-session-readonly-tool";
  19. import {
  20. getV4PaneSnapshot,
  21. prepareV4ConversationE2E,
  22. sendV4Prompt,
  23. switchV4Model,
  24. waitForV4AssistantMessageContaining,
  25. waitForV4Pane,
  26. } from "#e2e/helpers/v4-conversation";
  27. import {
  28. UPSTREAM_MODEL,
  29. UPSTREAM_PROVIDER_ID,
  30. ensureUpstreamModelForE2E,
  31. } from "#e2e/helpers/upstream-provider";
  32. const SCENARIOS = [
  33. { name: "non-mcs", model: UPSTREAM_MODEL, useMidConversationSystem: false },
  34. // 本地 endpoint 也通过真实模型能力判定启用 MCS,避免正式回归依赖在线 capture。
  35. { name: "mcs", model: "claude-opus-4-8", useMidConversationSystem: true },
  36. ] as const;
  37. const PARENT_MARKER = "E2E_SSC_REMINDER_SEED";
  38. const CHILD_MARKER = "E2E_SSC_REMINDER_QUERY";
  39. const CHILD_REPLY = "side-chat-ok";
  40. const BOUNDARY_TEXT =
  41. "The preceding conversation was inherited from the parent task for reference only.";
  42. describe("Side chat reminder E2E", () => {
  43. after(async () => {
  44. await browser.electron.restoreAllMocks();
  45. await clearAppData();
  46. });
  47. for (const scenario of SCENARIOS) {
  48. it(`SSC33: ${scenario.name} 下 side chat reminder 位于首条问题之前且仅出现一次`, async function () {
  49. this.timeout(240000);
  50. expect(process.env.E2E_PROVIDER_CAPTURE_MODE).toBe("replay");
  51. const parentMarker = `${PARENT_MARKER}_${scenario.name}`;
  52. const childPrompt = `${CHILD_MARKER}_${scenario.name}: 请只回复 ${CHILD_REPLY},不使用工具。`;
  53. await prepareV4ConversationE2E({ resetDraftBeforeProvider: true });
  54. await ensureUpstreamModelForE2E(scenario.model);
  55. await switchV4Model(UPSTREAM_PROVIDER_ID, scenario.model, "");
  56. await ensureReadonlyToolFixtureFile();
  57. await sendV4Prompt(buildReadonlyToolPrompt(parentMarker));
  58. const parent = await waitForV4Pane(
  59. (pane) =>
  60. Boolean(pane.sessionId && pane.sessionId !== "draft") &&
  61. !pane.canStop &&
  62. pane.timelineText.includes("upstream-e2e-ok"),
  63. "父会话未完成只读工具请求",
  64. 120000,
  65. );
  66. if (!parent.sessionId) throw new Error("Parent session ID missing");
  67. await waitForUpstreamRequest(
  68. { includes: [parentMarker, E2E_READONLY_TOOL_FILE_CONTENT] },
  69. "父会话没有真实只读工具结果回传",
  70. );
  71. const parentMessages = readMessages(parent.sessionId);
  72. const previousTabIds = await browser.execute(() =>
  73. Array.from(
  74. document.querySelectorAll<HTMLElement>('[data-side-pane-tab-id^="selection-side-chat:"]'),
  75. ).map((tab) => tab.dataset.sidePaneTabId),
  76. );
  77. await openEmptySideChat();
  78. let childPaneId = "";
  79. await browser.waitUntil(
  80. async () => {
  81. childPaneId = await browser.execute(
  82. (previous) =>
  83. Array.from(
  84. document.querySelectorAll<HTMLElement>(
  85. '[data-side-pane-tab-id^="selection-side-chat:"]',
  86. ),
  87. ).find((tab) => !previous.includes(tab.dataset.sidePaneTabId))?.dataset
  88. .sidePaneTabId ?? "",
  89. previousTabIds,
  90. );
  91. return Boolean(childPaneId);
  92. },
  93. { timeout: 30000, timeoutMsg: "Side chat tab 没有创建" },
  94. );
  95. const emptyChild = await waitForV4Pane(
  96. (pane) => Boolean(pane.sessionId && pane.sessionId !== "draft"),
  97. "Side chat session 没有挂载",
  98. 30000,
  99. childPaneId,
  100. );
  101. if (!emptyChild.sessionId) throw new Error("Child session ID missing");
  102. expect(readMessages(emptyChild.sessionId).at(-1)).toMatchObject({
  103. parts: [
  104. {
  105. synthetic: true,
  106. metadata: {
  107. source: "selection_side_chat",
  108. runtimeMessage: { source: "selection_side_chat" },
  109. },
  110. },
  111. ],
  112. });
  113. expect(emptyChild.sessionId).not.toBe(parent.sessionId);
  114. expect(emptyChild.rowCount).toBe(0);
  115. expect(emptyChild.timelineText).not.toContain(parentMarker);
  116. // Side chat 没有普通 pane shell;直接在其 SessionPane 内键入,避免错用分屏 helper。
  117. const childPane = $(`[data-testid="${testId(TID_V4_SESSION_PANE, childPaneId)}"]`);
  118. const childInput = childPane.$(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`);
  119. // sessionId 先于订阅完成出现;等待真实可编辑状态,避免输入被挂载阶段丢弃。
  120. await browser.waitUntil(
  121. async () => (await childInput.getAttribute("contenteditable")) === "true",
  122. {
  123. timeout: 15000,
  124. timeoutMsg: "Child composer 尚不可编辑",
  125. },
  126. );
  127. await childInput.click();
  128. await browser.keys(childPrompt);
  129. await browser.waitUntil(async () => (await childInput.getText()) === childPrompt, {
  130. timeout: 15000,
  131. timeoutMsg: "首条用户消息没有进入 child composer",
  132. });
  133. const childSend = childPane.$(`[data-testid="${TID_V4_COMPOSER_SEND}"]`);
  134. await childSend.waitForClickable();
  135. await childSend.click();
  136. await waitForUpstreamRequest(
  137. { lastUserMessageIncludes: [childPrompt] },
  138. "Side chat 首条用户消息没有到达 provider",
  139. 60000,
  140. );
  141. const childRequests = await getUpstreamRequestEvidence({
  142. lastUserMessageIncludes: [childPrompt],
  143. });
  144. const firstRequest = childRequests[0];
  145. if (!firstRequest) throw new Error("Child first request missing");
  146. const body = JSON.stringify(firstRequest.requestJson);
  147. expect(body).toContain(parentMarker);
  148. expect(body).toContain(E2E_READONLY_TOOL_FILE_CONTENT);
  149. expect(body).toContain(childPrompt);
  150. expect(body.split(BOUNDARY_TEXT)).toHaveLength(2);
  151. const request = firstRequest.requestJson as {
  152. model: string;
  153. messages: Array<{
  154. role: string;
  155. content: string | Array<{ type: string; text?: string }>;
  156. }>;
  157. };
  158. expect(request.model).toBe(scenario.model);
  159. const boundaryIndex = request.messages.findIndex((message) =>
  160. JSON.stringify(message.content).includes(BOUNDARY_TEXT),
  161. );
  162. const questionIndex = request.messages.findIndex((message) =>
  163. JSON.stringify(message.content).includes(childPrompt),
  164. );
  165. const boundaryMessage = request.messages[boundaryIndex]!;
  166. const { useMidConversationSystem } = scenario;
  167. const hasOtherSystemMessages = request.messages.some((message) => message.role === "system");
  168. expect(hasOtherSystemMessages).toBe(useMidConversationSystem);
  169. expect(boundaryMessage.role).toBe("user");
  170. expect(boundaryIndex).toBe(questionIndex);
  171. // 修复原因:non-MCS 下 Windows 会在同一条 user message 前部追加 Git Bash 平台提醒,
  172. // 整体按位置比对会误判。本用例只约束 side chat 边界紧贴首条问题,因此比对末尾两段。
  173. expect((boundaryMessage.content as unknown[]).slice(-2)).toMatchObject([
  174. { type: "text", text: expect.stringContaining(`<system-reminder>\n${BOUNDARY_TEXT}`) },
  175. { type: "text", text: childPrompt },
  176. ]);
  177. expect(JSON.stringify(boundaryMessage.content)).toContain("</system-reminder>");
  178. await waitForV4AssistantMessageContaining(CHILD_REPLY, 120000, childPaneId);
  179. await waitForV4Pane(
  180. (pane) => !pane.canStop && pane.rowCount === 2,
  181. "Side chat 首轮没有完成",
  182. 120000,
  183. childPaneId,
  184. );
  185. expect(readMessages(parent.sessionId)).toEqual(parentMessages);
  186. expect((await getV4PaneSnapshot()).timelineText).not.toContain(childPrompt);
  187. });
  188. }
  189. });
  190. async function openEmptySideChat(): Promise<void> {
  191. const inputSelector = `[data-testid="${testId(TID_V4_SESSION_PANE, "workspace-main")}"] [data-testid="${TID_V4_COMPOSER_INPUT}"]`;
  192. await $(inputSelector).click();
  193. await browser.keys(["/", "b", "t", "w"]);
  194. // App slash 选项在 mousedown 触发;不直接调用创建 session 的内部方法。
  195. try {
  196. await browser.waitUntil(
  197. async () =>
  198. browser.execute(() => {
  199. const option = document.querySelector<HTMLElement>('[data-option-id="app-slash:btw"]');
  200. if (!option) return false;
  201. option.dispatchEvent(
  202. new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }),
  203. );
  204. return true;
  205. }),
  206. { timeout: 15000, timeoutMsg: "裸 /btw 没有出现辅助对话选项" },
  207. );
  208. } catch (error) {
  209. // 失败时带回 composer 文本、焦点与当前可见选项,区分按键丢失与选项未注册。
  210. const diagnostics = await browser.execute((selector) => {
  211. const input = document.querySelector<HTMLElement>(selector);
  212. const active = document.activeElement as HTMLElement | null;
  213. return {
  214. activeTestId: active?.getAttribute("data-testid") ?? active?.tagName ?? null,
  215. inputText: input?.innerText ?? null,
  216. optionIds: Array.from(document.querySelectorAll<HTMLElement>("[data-option-id]")).map(
  217. (option) => option.dataset.optionId,
  218. ),
  219. };
  220. }, inputSelector);
  221. throw new Error(`裸 /btw 没有出现辅助对话选项; diagnostics=${JSON.stringify(diagnostics)}`, {
  222. cause: error,
  223. });
  224. }
  225. }
  226. function readMessages(sessionId: string): unknown[] {
  227. // Node SQLite 只提供同步 API;只读隔离 E2E DB,不改写运行中的 session。
  228. const db = new DatabaseSync(
  229. join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "db", "db.sqlite"),
  230. { readOnly: true },
  231. );
  232. try {
  233. return db
  234. .prepare("select id, data from message where session_id = ? order by time_created, id")
  235. .all(sessionId)
  236. .map((message) => ({
  237. info: { id: message.id, ...JSON.parse(String(message.data)) },
  238. parts: db
  239. .prepare("select id, data from part where message_id = ? order by time_created, id")
  240. .all(String(message.id))
  241. .map((part) => ({ id: part.id, ...JSON.parse(String(part.data)) })),
  242. }));
  243. } finally {
  244. db.close();
  245. }
  246. }