conversation-session-unbound-resume.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import { DatabaseSync } from "node:sqlite";
  2. import { join } from "node:path";
  3. import { writeFile } from "node:fs/promises";
  4. import {
  5. TID_V4_MODEL_CONFIG,
  6. TID_CHAT_MODEL_SELECT_TRIGGER,
  7. TID_CHAT_MODEL_SELECT_ITEM,
  8. testId,
  9. } from "@zcode/shared/test-ids";
  10. import { DEFAULT_WORKSPACE, clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  11. import { startConversationModelProviderReplayServer } from "#e2e/helpers/model-provider-replay";
  12. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  13. import { seedReplayProvider } from "#e2e/helpers/model-provider-restart";
  14. import {
  15. UPSTREAM_MODEL,
  16. UPSTREAM_PROVIDER_ID,
  17. UPSTREAM_PROVIDER_NAME,
  18. selectRegistryProviderModelById,
  19. selectUpstreamThoughtLevelValue,
  20. } from "#e2e/helpers/upstream-provider";
  21. import {
  22. prepareV4ConversationE2E,
  23. sendV4Prompt,
  24. waitForV4Pane,
  25. waitForV4TimelineContaining,
  26. selectV4TaskById,
  27. } from "#e2e/helpers/v4-conversation";
  28. import { waitForUpstreamNetworkCapture } from "#e2e/helpers/upstream-capture";
  29. const CASE_NAME = "conversation-session-unbound-resume";
  30. let replay: Awaited<ReturnType<typeof startConversationModelProviderReplayServer>>;
  31. describe("Todo 70:模型选择残缺不阻止历史打开", () => {
  32. before(async () => {
  33. replay = await startConversationModelProviderReplayServer(CASE_NAME);
  34. });
  35. after(async () => {
  36. await browser.electron.restoreAllMocks();
  37. await clearAppData();
  38. await replay?.stop();
  39. });
  40. it("DB109:启动迁移/回滚缺字段及残缺选择不阻止历史,重选后继续原会话", async function () {
  41. this.timeout(480000);
  42. await prepareV4ConversationE2E({ skipProvider: true });
  43. await seedReplayProvider({
  44. id: UPSTREAM_PROVIDER_ID,
  45. // 残缺历史恢复需要合法 high/max 目标;通用 seed 默认仅 disabled,不能用它验证重选。
  46. models: [
  47. {
  48. id: UPSTREAM_MODEL,
  49. reasoningLevel: {
  50. values: ["high", "max"],
  51. map: '{"chat_template_kwargs":{"reasoning_effort":reasoningLevel}}',
  52. },
  53. },
  54. ],
  55. name: UPSTREAM_PROVIDER_NAME,
  56. });
  57. // Replay 地址是在 worker 启动后生成的;完整重启让 Host/Agent 从正式
  58. // Personal Provider 配置读取同一个地址,避免测试进程与 Agent 各连一台服务。
  59. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE);
  60. await prepareV4ConversationE2E({ skipProvider: true });
  61. const selectModel = () =>
  62. selectRegistryProviderModelById(UPSTREAM_MODEL, {
  63. providerId: UPSTREAM_PROVIDER_ID,
  64. providerName: UPSTREAM_PROVIDER_NAME,
  65. includePlainModelFallback: false,
  66. });
  67. await selectModel();
  68. await sendV4Prompt("E2E_UNBOUND_RESUME_HISTORY: Reply unbound-history-ok.");
  69. const firstRequest = await waitForUpstreamNetworkCapture("E2E_UNBOUND_RESUME_HISTORY").catch(
  70. async (error: unknown) => {
  71. // 失败时展开真实业务错误,避免只记录“没有网络请求”而丢掉发送前失败的根因。
  72. await browser.execute(() => {
  73. const details = [...document.querySelectorAll("button")].find((button) =>
  74. /展开详情|Show details/i.test(button.textContent ?? ""),
  75. );
  76. details?.click();
  77. });
  78. await browser.saveScreenshot(".e2e-artifacts/todo70-first-send-failure.png");
  79. const diagnostic = await browser.execute(() => ({
  80. text: document.body.innerText.slice(-7000),
  81. config: document.querySelector('[data-testid="v4-model-config"]')?.outerHTML,
  82. }));
  83. throw new Error(`${String(error)}; ${JSON.stringify(diagnostic)}`, { cause: error });
  84. },
  85. );
  86. expect(firstRequest.statusCode).toBe(200);
  87. await waitForV4TimelineContaining("unbound-history-ok");
  88. const created = await waitForV4Pane(
  89. (state) => Boolean(state.sessionId) && state.sessionId !== "draft" && !state.canStop,
  90. "历史首轮未完成",
  91. 60000,
  92. );
  93. const sessionId = created.sessionId!;
  94. const choices = [
  95. { providerId: UPSTREAM_PROVIDER_ID, modelId: UPSTREAM_MODEL },
  96. {
  97. providerId: UPSTREAM_PROVIDER_ID,
  98. modelId: UPSTREAM_MODEL,
  99. options: { reasoningLevel: "removed" },
  100. },
  101. {
  102. providerId: "removed-provider",
  103. modelId: UPSTREAM_MODEL,
  104. options: { reasoningLevel: "high" },
  105. },
  106. undefined,
  107. ];
  108. let migrationLedger: unknown;
  109. for (const [index, selection] of choices.entries()) {
  110. // 真正旧会话没有 Todo 71 的 Composer 意图。只改 Session DB 会继续显示
  111. // 首轮发送已保存的合法 max,测到的是“已有草稿优先”而不是历史残缺恢复。
  112. await browser.execute(
  113. (workspacePath, targetSessionId) => {
  114. const key = `zcode-v4-composer-drafts:v1:${encodeURIComponent(workspacePath)}`;
  115. const raw = localStorage.getItem(key);
  116. if (!raw) return;
  117. const file = JSON.parse(raw);
  118. delete file.scopes[targetSessionId];
  119. localStorage.setItem(key, JSON.stringify(file));
  120. },
  121. DEFAULT_WORKSPACE,
  122. sessionId,
  123. );
  124. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  125. afterElectronProcessExit: () => {
  126. // 仅篡改本 case 的隔离会话,且等旧 Agent 退出,避免迟到写盘覆盖 fixture。
  127. const db = new DatabaseSync(
  128. join(getE2EAppDataPaths().storageRoot, "cli", "db", "db.sqlite"),
  129. );
  130. try {
  131. if (index === 0) {
  132. // DB109:只在测试隔离库撤销本迁移标记,模拟首次升级;旧消息正文不动。
  133. db.prepare(
  134. "DELETE FROM schema_migration WHERE id='0020_provider_model_selection'",
  135. ).run();
  136. // 复审回归:旧 User 的空 model 经 0020 转成 null,不能穿透为协议异常。
  137. db.prepare(
  138. "UPDATE message SET data=json_set(json_remove(data,'$.modelSelection'),'$.model',json('{}')) WHERE session_id=? AND json_extract(data,'$.role')='user'",
  139. ).run(sessionId);
  140. }
  141. if (index === 3) {
  142. migrationLedger = db.prepare("SELECT * FROM schema_migration ORDER BY id").all();
  143. db.prepare(
  144. "UPDATE message SET data=json_remove(data,'$.modelSelection') WHERE session_id=? AND json_extract(data,'$.role')='user'",
  145. ).run(sessionId);
  146. }
  147. const persisted =
  148. index === 0 || index === 3
  149. ? { providerId: UPSTREAM_PROVIDER_ID, modelId: UPSTREAM_MODEL }
  150. : { modelSelection: selection };
  151. const result = db
  152. .prepare(
  153. "update session_entry set data = ? where session_id = ? and type = 'runtime/model_selection'",
  154. )
  155. .run(JSON.stringify(persisted), sessionId);
  156. if (!Number(result.changes))
  157. throw new Error(
  158. JSON.stringify({
  159. sessionId,
  160. entries: db.prepare("select session_id,type from session_entry limit 15").all(),
  161. sessions: db.prepare("select id,title from session limit 10").all(),
  162. }),
  163. );
  164. } finally {
  165. db.close();
  166. }
  167. },
  168. });
  169. await selectV4TaskById(sessionId, 30000);
  170. await waitForV4TimelineContaining("unbound-history-ok");
  171. await waitForV4TimelineContaining("E2E_UNBOUND_RESUME_HISTORY");
  172. const visibleText = await browser.execute(() => document.body.innerText);
  173. expect(visibleText).not.toMatch(
  174. /ZodError|invalid_type|Expected object|Invalid input|读取失败|加载失败/,
  175. );
  176. const db = new DatabaseSync(
  177. join(getE2EAppDataPaths().storageRoot, "cli", "db", "db.sqlite"),
  178. { readOnly: true },
  179. );
  180. try {
  181. const row = db
  182. .prepare(
  183. "SELECT data FROM session_entry WHERE session_id=? AND type='runtime/model_selection'",
  184. )
  185. .get(sessionId)!;
  186. const data = JSON.parse(String(row.data));
  187. if (index === 0) {
  188. expect(data).toEqual({
  189. providerId: UPSTREAM_PROVIDER_ID,
  190. modelId: UPSTREAM_MODEL,
  191. modelSelection: choices[0],
  192. });
  193. expect(
  194. db
  195. .prepare("SELECT id FROM schema_migration WHERE id='0020_provider_model_selection'")
  196. .get(),
  197. ).toBeDefined();
  198. }
  199. if (index === 3) {
  200. expect(data).not.toHaveProperty("modelSelection");
  201. expect(db.prepare("SELECT * FROM schema_migration ORDER BY id").all()).toEqual(
  202. migrationLedger,
  203. );
  204. }
  205. } finally {
  206. db.close();
  207. }
  208. // 历史正文和模型目录分别水合;记录真实配置,不用“正文出现”冒充选择已恢复。
  209. if (index < 2) {
  210. await browser
  211. .waitUntil(
  212. () =>
  213. browser.execute(
  214. (tid, expected) =>
  215. document.querySelector<HTMLElement>(`[data-testid="${tid}"]`)?.dataset.model ===
  216. expected,
  217. TID_V4_MODEL_CONFIG,
  218. UPSTREAM_MODEL,
  219. ),
  220. { timeout: 15000, timeoutMsg: `DB109 第 ${index} 组模型身份没有恢复` },
  221. )
  222. .catch(async (error: unknown) => {
  223. const diagnostic = await browser.execute(() => ({
  224. text: document.body.innerText,
  225. config: document.querySelector('[data-testid="v4-model-config"]')?.outerHTML,
  226. drafts: Object.fromEntries(
  227. Object.entries(localStorage).filter(([key]) => key.startsWith("zcode-v4-composer")),
  228. ),
  229. }));
  230. await writeFile(
  231. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `unbound-resume-${index}.json`),
  232. JSON.stringify({ index, selection, diagnostic }, null, 2),
  233. );
  234. throw error;
  235. });
  236. }
  237. const config = await browser.execute((tid) => {
  238. const el = document.querySelector<HTMLElement>(`[data-testid="${tid}"]`);
  239. return { model: el?.dataset.model ?? "", thought: el?.dataset.thought ?? "" };
  240. }, TID_V4_MODEL_CONFIG);
  241. expect(config.thought).toBe("");
  242. if (index >= 2) expect(config.model).toBe("");
  243. else {
  244. expect(config.model).toBe(UPSTREAM_MODEL);
  245. // 模型与思考已合并为同一入口;缺档位显示横线,不能伪装成第一档“关闭”。
  246. const modelTrigger = await $(`[data-testid="${TID_CHAT_MODEL_SELECT_TRIGGER}"]`);
  247. expect(await modelTrigger.getAttribute("aria-label")).not.toMatch(/关闭|Disabled|Off/u);
  248. expect(await modelTrigger.$("[data-composer-thought-label]").getText()).toBe("—");
  249. }
  250. await browser.saveScreenshot(`.e2e-artifacts/todo70-unbound-${index}.png`);
  251. await selectModel();
  252. // 通用选择 helper 对同模型直接返回;此处测试残缺配置恢复,必须真实重选该模型。
  253. const modelTrigger = $(`[data-testid="${TID_CHAT_MODEL_SELECT_TRIGGER}"]`);
  254. if ((await modelTrigger.getAttribute("aria-expanded")) !== "true") await modelTrigger.click();
  255. const sameModel = $(
  256. `[data-testid="${testId(TID_CHAT_MODEL_SELECT_ITEM, `custom:${UPSTREAM_PROVIDER_ID}:${UPSTREAM_MODEL}`)}"]`,
  257. );
  258. await sameModel.waitForClickable({ timeout: 15000 });
  259. await sameModel.click();
  260. await browser.keys("Escape");
  261. await selectUpstreamThoughtLevelValue("high");
  262. const marker = `E2E_UNBOUND_RESUME_CONTINUE_${index}`;
  263. await sendV4Prompt(`${marker}: Reply unbound-continue-${index}-ok.`);
  264. await waitForV4TimelineContaining(`unbound-continue-${index}-ok`);
  265. const resumed = await waitForV4Pane(
  266. (state) => state.sessionId === sessionId && !state.canStop,
  267. "重选后未完成",
  268. 60000,
  269. );
  270. expect(resumed.sessionId).toBe(sessionId);
  271. const request = await waitForUpstreamNetworkCapture(marker);
  272. expect(request.statusCode).toBe(200);
  273. expect(request.requestJson).toMatchObject({ model: UPSTREAM_MODEL });
  274. }
  275. });
  276. });