conversation-session-command-unknown-recovery.test.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import { clearAppData, readModelProviders, readSettings } from "#e2e/helpers/desktop-app";
  2. import {
  3. getV4PaneSnapshot,
  4. prepareV4ConversationE2E,
  5. sendV4Prompt,
  6. waitForV4Pane,
  7. waitForV4AssistantMessageContaining,
  8. } from "#e2e/helpers/v4-conversation";
  9. const CASE_TIMEOUT_MS = 120_000;
  10. const PENDING_COMMAND_STORAGE_KEY = "zcode-v4-pending-commands:v1";
  11. const PROMPT_MARKER = "E2E_COMMAND_UNKNOWN_RECOVERY";
  12. const REPLY_MARKER = "COMMAND_UNKNOWN_RECOVERY_OK";
  13. const UNKNOWN_TEXT = "E2E_UNKNOWN_COMMAND_MUST_NOT_REPLAY";
  14. const COMPOSER_UNKNOWN_TEXT = "E2E_COMPOSER_UNKNOWN_MUST_NOT_REPLAY";
  15. let queryProbeScriptId: string | undefined;
  16. describe("PV4-25U:unknown command recovery 保留待确认", () => {
  17. after(async () => {
  18. if (queryProbeScriptId) {
  19. await browser.electron.execute(async (electron, identifier) => {
  20. const target = electron.BrowserWindow.getAllWindows().find((win) =>
  21. win.webContents.getURL().includes("/renderer/index.html"),
  22. );
  23. await target?.webContents.debugger.sendCommand("Page.removeScriptToEvaluateOnNewDocument", {
  24. identifier,
  25. });
  26. }, queryProbeScriptId);
  27. }
  28. await browser.electron.restoreAllMocks();
  29. await clearAppData();
  30. });
  31. it("同一 workspace 的普通与 Composer unknown 均保留线索且不重放", async function () {
  32. this.timeout(CASE_TIMEOUT_MS);
  33. await prepareV4ConversationE2E();
  34. await sendV4Prompt(`${PROMPT_MARKER}: Reply with exactly "${REPLY_MARKER}" and no other text.`);
  35. // 提示也包含回答 marker,必须以 assistant 正文确认前置会话已完成,避免过早刷新。
  36. await waitForV4AssistantMessageContaining(REPLY_MARKER, 60_000);
  37. const terminal = await waitForV4Pane(
  38. (snapshot) =>
  39. !snapshot.canStop && Boolean(snapshot.sessionId && snapshot.sessionId !== "draft"),
  40. "PV4-25U 前置 session 没有完成",
  41. 60_000,
  42. );
  43. const sessionId = requireSessionId(terminal.sessionId);
  44. const commandId = `e2e-unknown-composer-${Date.now()}`;
  45. const plainCommandId = `${commandId}-plain`;
  46. const workspace = await readActiveWorkspace();
  47. // unknown 可能先于 Host 发送,不能再用普通记录被清除证明查询发生。
  48. // 在刷新前安装只观察回执的探针,确认真实查询完成后再检查两类记录。
  49. await seedPendingSendText(sessionId, commandId, COMPOSER_UNKNOWN_TEXT, true, workspace);
  50. await seedPendingSendText(sessionId, plainCommandId, UNKNOWN_TEXT, false, workspace);
  51. expect(await readPendingCommandIds()).toContain(commandId);
  52. expect(await readPendingCommandIds()).toContain(plainCommandId);
  53. queryProbeScriptId = await installUnknownQueryProbe([commandId, plainCommandId]);
  54. await browser.refresh();
  55. try {
  56. await waitForV4Pane(
  57. (snapshot) => snapshot.sessionId === sessionId && !snapshot.canStop,
  58. "PV4-25U unknown 刷新后没有恢复原 session",
  59. 60_000,
  60. );
  61. } catch (cause) {
  62. // 正式默认轮在刷新后进入欢迎页;仅采集脱敏配置,不通过重载或重试绕过启动异常。
  63. const [providers, settings] = await Promise.all([readModelProviders(), readSettings()]);
  64. throw new Error(
  65. `PV4-25U 刷新恢复失败: ${JSON.stringify({
  66. providerFamilyDomain: settings.providerFamilyDomain,
  67. providers: providers.map((provider) => ({
  68. id: provider.id,
  69. enabled: provider.enabled,
  70. apiKeyPresent: Boolean(provider.apiKey),
  71. systemDisabledReason: provider.systemDisabledReason,
  72. models: provider.models.map((model) => ({
  73. id: model.id,
  74. disabledReason: model.disabledReason,
  75. })),
  76. })),
  77. })}`,
  78. { cause },
  79. );
  80. }
  81. await browser.waitUntil(
  82. () =>
  83. browser.execute(
  84. (commandIds) => {
  85. const seen = (window as Window & { __unknownQueryResults?: string[] })
  86. .__unknownQueryResults;
  87. return commandIds.every((id) => seen?.includes(id));
  88. },
  89. [commandId, plainCommandId],
  90. ),
  91. { timeout: 30_000, timeoutMsg: "未观察到普通与 Composer 命令的真实 unknown 查询回执" },
  92. );
  93. expect(await readPendingCommandIds()).toEqual(
  94. expect.arrayContaining([commandId, plainCommandId]),
  95. );
  96. expect(await hasPendingRecoveryBanner()).toBe(false);
  97. expect((await getV4PaneSnapshot()).timelineText).not.toContain(COMPOSER_UNKNOWN_TEXT);
  98. expect((await getV4PaneSnapshot()).timelineText).not.toContain(UNKNOWN_TEXT);
  99. await browser.execute(
  100. (storageKey) => window.localStorage.removeItem(storageKey),
  101. PENDING_COMMAND_STORAGE_KEY,
  102. );
  103. });
  104. });
  105. function requireSessionId(value: string | null): string {
  106. if (!value || value === "draft") {
  107. throw new Error(`PV4-25U 缺少 sessionId: ${String(value)}`);
  108. }
  109. return value;
  110. }
  111. async function seedPendingSendText(
  112. sessionId: string,
  113. commandId: string,
  114. text: string,
  115. withComposer = false,
  116. workspace?: { workspacePath: string; workspaceIdentity: string | null },
  117. ) {
  118. await browser.execute(
  119. (
  120. storageKey,
  121. currentSessionId,
  122. currentCommandId,
  123. currentText,
  124. now,
  125. includeComposer,
  126. currentWorkspace,
  127. ) => {
  128. const raw = window.localStorage.getItem(storageKey);
  129. const entries = raw ? (JSON.parse(raw) as Array<Record<string, unknown>>) : [];
  130. entries.push({
  131. commandId: currentCommandId,
  132. clientId: "e2e-command-recovery",
  133. sessionId: currentSessionId,
  134. issuedAt: now,
  135. expiresAt: now + 300_000,
  136. replay: {
  137. kind: "input",
  138. type: "sendText",
  139. payload: { text: currentText, attachments: [] },
  140. },
  141. ...(currentWorkspace ? { clientContext: { workspace: currentWorkspace } } : {}),
  142. ...(includeComposer
  143. ? {
  144. clientContext: {
  145. workspace: currentWorkspace,
  146. composer: {
  147. scope: {
  148. clientNamespace: "e2e-unknown",
  149. hostId: "e2e-host",
  150. projectId: null,
  151. },
  152. selection: {
  153. modelSelection: {
  154. providerId: "e2e-upstream",
  155. modelId: "deepseek-v4-flash",
  156. },
  157. mode: "build",
  158. },
  159. order: now,
  160. draftId: "00000000-0000-4000-8000-000000000001",
  161. submittedText: currentText,
  162. },
  163. },
  164. }
  165. : {}),
  166. });
  167. window.localStorage.setItem(storageKey, JSON.stringify(entries));
  168. },
  169. PENDING_COMMAND_STORAGE_KEY,
  170. sessionId,
  171. commandId,
  172. text,
  173. Date.now(),
  174. withComposer,
  175. workspace ?? null,
  176. );
  177. }
  178. function readActiveWorkspace(): Promise<{
  179. workspacePath: string;
  180. workspaceIdentity: string | null;
  181. }> {
  182. return browser.execute(() => {
  183. const tabs = (
  184. window as Window & {
  185. __zcodeTabStoreE2E?: {
  186. getState(): {
  187. activeWorkspacePath: string | null;
  188. activeWorkspaceIdentity: string | null;
  189. };
  190. };
  191. }
  192. ).__zcodeTabStoreE2E?.getState();
  193. if (!tabs?.activeWorkspacePath) throw new Error("PV4-25U 缺少活动 workspace 身份");
  194. return {
  195. workspacePath: tabs.activeWorkspacePath,
  196. workspaceIdentity: tabs.activeWorkspaceIdentity,
  197. };
  198. });
  199. }
  200. function readPendingCommandIds(): Promise<string[]> {
  201. return browser.execute((storageKey) => {
  202. const raw = window.localStorage.getItem(storageKey);
  203. if (!raw) return [];
  204. try {
  205. const entries = JSON.parse(raw) as Array<{ commandId?: unknown }>;
  206. return entries.flatMap((entry) =>
  207. typeof entry.commandId === "string" ? [entry.commandId] : [],
  208. );
  209. } catch {
  210. return ["<invalid-json>"];
  211. }
  212. }, PENDING_COMMAND_STORAGE_KEY);
  213. }
  214. async function installUnknownQueryProbe(commandIds: string[]): Promise<string> {
  215. // 只读 MessagePort 回执,不伪造 query 结果、不改变发送与恢复时序。
  216. const source = `(() => {
  217. const ids = ${JSON.stringify(commandIds)};
  218. const seen = window.__unknownQueryResults = [];
  219. const ports = new WeakSet();
  220. const original = MessagePort.prototype.postMessage;
  221. MessagePort.prototype.postMessage = function (...args) {
  222. if (!ports.has(this)) {
  223. ports.add(this);
  224. this.addEventListener("message", event => {
  225. const data = event.data;
  226. const bytes = data instanceof ArrayBuffer ? new Uint8Array(data)
  227. : ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : null;
  228. if (!bytes) return;
  229. const wire = new TextDecoder().decode(bytes);
  230. if (!wire.includes('"result":"unknown"')) return;
  231. for (const id of ids) {
  232. if (wire.includes('"commandId":"' + id + '"') && !seen.includes(id)) seen.push(id);
  233. }
  234. });
  235. }
  236. return Reflect.apply(original, this, args);
  237. };
  238. })();`;
  239. return browser.electron.execute(async (electron, source) => {
  240. const target = electron.BrowserWindow.getAllWindows().find((win) =>
  241. win.webContents.getURL().includes("/renderer/index.html"),
  242. );
  243. if (!target) throw new Error("PV4-25U 缺少 renderer");
  244. const debug = target.webContents.debugger;
  245. if (!debug.isAttached()) debug.attach("1.3");
  246. await debug.sendCommand("Page.enable");
  247. const result = await debug.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source });
  248. return result.identifier as string;
  249. }, source);
  250. }
  251. function hasPendingRecoveryBanner(): Promise<boolean> {
  252. return browser.execute(() => {
  253. const text = document.body.innerText;
  254. return (
  255. text.includes("CLI 重启前已提交的输入没有进入对话") ||
  256. text.includes("An input submitted before the CLI restarted did not reach the conversation")
  257. );
  258. });
  259. }