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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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";
  9. import { clearAppData, getE2EAppDataPaths } from "../helpers/desktop-app.js";
  10. import {
  11. getUpstreamRequestEvidence,
  12. waitForUpstreamRequest,
  13. } from "../helpers/conversation-session-network.js";
  14. import {
  15. buildReadonlyToolPrompt,
  16. ensureReadonlyToolFixtureFile,
  17. E2E_READONLY_TOOL_FILE_CONTENT,
  18. } from "../helpers/conversation-session-readonly-tool.js";
  19. import {
  20. getV4PaneSnapshot,
  21. prepareV4ConversationE2E,
  22. sendV4Prompt,
  23. switchV4Model,
  24. waitForV4AssistantMessageContaining,
  25. waitForV4Pane,
  26. } from "../helpers/v4-conversation.js";
  27. import {
  28. UPSTREAM_MODEL,
  29. UPSTREAM_PROVIDER_ID,
  30. ensureUpstreamModelForE2E,
  31. } from "../helpers/upstream-provider.js";
  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. expect(boundaryMessage.content).toMatchObject([
  172. { type: "text", text: expect.stringContaining(`<system-reminder>\n${BOUNDARY_TEXT}`) },
  173. { type: "text", text: childPrompt },
  174. ]);
  175. expect(JSON.stringify(boundaryMessage.content)).toContain("</system-reminder>");
  176. await waitForV4AssistantMessageContaining(CHILD_REPLY, 120000, childPaneId);
  177. await waitForV4Pane(
  178. (pane) => !pane.canStop && pane.rowCount === 2,
  179. "Side chat 首轮没有完成",
  180. 120000,
  181. childPaneId,
  182. );
  183. expect(readMessages(parent.sessionId)).toEqual(parentMessages);
  184. expect((await getV4PaneSnapshot()).timelineText).not.toContain(childPrompt);
  185. });
  186. }
  187. });
  188. async function openEmptySideChat(): Promise<void> {
  189. const inputSelector = `[data-testid="${testId(TID_V4_SESSION_PANE, "workspace-main")}"] [data-testid="${TID_V4_COMPOSER_INPUT}"]`;
  190. await $(inputSelector).click();
  191. await browser.keys(["/", "b", "t", "w"]);
  192. // App slash 选项在 mousedown 触发;不直接调用创建 session 的内部方法。
  193. await browser.waitUntil(
  194. async () =>
  195. browser.execute(() => {
  196. const option = document.querySelector<HTMLElement>('[data-option-id="app-slash:btw"]');
  197. if (!option) return false;
  198. option.dispatchEvent(
  199. new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }),
  200. );
  201. return true;
  202. }),
  203. { timeout: 15000, timeoutMsg: "裸 /btw 没有出现辅助对话选项" },
  204. );
  205. }
  206. function readMessages(sessionId: string): unknown[] {
  207. // Node SQLite 只提供同步 API;只读隔离 E2E DB,不改写运行中的 session。
  208. const db = new DatabaseSync(
  209. join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "db", "db.sqlite"),
  210. { readOnly: true },
  211. );
  212. try {
  213. return db
  214. .prepare("select id, data from message where session_id = ? order by time_created, id")
  215. .all(sessionId)
  216. .map((message) => ({
  217. info: { id: message.id, ...JSON.parse(String(message.data)) },
  218. parts: db
  219. .prepare("select id, data from part where message_id = ? order by time_created, id")
  220. .all(String(message.id))
  221. .map((part) => ({ id: part.id, ...JSON.parse(String(part.data)) })),
  222. }));
  223. } finally {
  224. db.close();
  225. }
  226. }