conversation-session-draft-model-migration-mobile.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. // DMM-10:手机远控的新建草稿独立迁移,规格见 docs/chat/draft-model-migration.md。
  2. // 手机经 attachment 读取 ClientConfig(本次放行的频道,同时覆盖 CCF-12),迁移标记与气泡
  3. // 记录存在手机浏览器自己的 localStorage,作用域为 mobile:<device>,与桌面互不影响。
  4. import { once } from "node:events";
  5. import { createServer } from "node:http";
  6. import { join } from "node:path";
  7. import { chromium, type Browser, type Page } from "playwright-core";
  8. import {
  9. TID_CHAT_MODEL_GUIDE,
  10. TID_CHAT_MODEL_SELECT_TRIGGER,
  11. TID_V4_COMPOSER,
  12. } from "@zcode/shared/test-ids";
  13. import { encodeCustomModelValue } from "@zcode/shared";
  14. import {
  15. clearAppData,
  16. DEFAULT_WORKSPACE,
  17. pinE2ELocale,
  18. seedSettings,
  19. waitForWorkspaceApp,
  20. } from "#e2e/helpers/desktop-app";
  21. import { e2eMobileBrowserLaunchOptions } from "#e2e/helpers/e2e-mobile-browser-executable";
  22. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  23. import { seedReplayProvider } from "#e2e/helpers/model-provider-restart";
  24. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  25. const CASE_MARKER = "DMM-10";
  26. // 与用户从官方模板创建时的默认 ID 相同;归属由 templateId 决定。
  27. const OFFICIAL_PROVIDER_ID = "bigmodel-standard-api";
  28. // 型号用中性名:测试会随开源导出,不能出现任何真实的待发布或迁移计划。
  29. const SOURCE_MODEL = "e2e-dmm-model-a";
  30. const TARGET_MODEL = "e2e-dmm-model-b";
  31. // 较长的中文文案:390 宽的手机上必须换行,用来验证气泡不超出输入框、离屏幕边留出间距。
  32. const NOTICE_ZH_CN =
  33. "E2E 手机文案:新建任务的默认模型已按服务端规则切换为 e2e-dmm-model-b,可在模型菜单中改回原来的模型。";
  34. const NOTICE_KEY = "zcode-draft-model-migration-notice:v1";
  35. const PROJECT_SELECTOR = '[data-testid="project-section"]';
  36. type MobileWindow = Window & {
  37. __zcodeTabStoreE2E?: { getState(): { activeWorkspacePath: string | null } };
  38. __zcodeSessionStoreE2E?: {
  39. getState(): {
  40. getWorkspaceState(path: string): { draftProjectId?: string | null };
  41. };
  42. };
  43. __dmm10RestoreClipboard?: () => void;
  44. };
  45. /** 手机夹具的 relay 同时是控制面;规则经它的 client/configs 下发,不能另改 endpoint 打断配对认证。 */
  46. async function setRelayClientConfigs(configs: Record<string, unknown>) {
  47. const relayUrl = process.env.ZCODE_E2E_REMOTE_AUTH_GATE_URL?.trim();
  48. if (!relayUrl) throw new Error("手机 relay 夹具未启动,无法下发 client/configs");
  49. const response = await fetch(new URL("/__e2e/client-configs", relayUrl), {
  50. body: JSON.stringify({ configs }),
  51. headers: { "content-type": "application/json" },
  52. method: "POST",
  53. signal: AbortSignal.timeout(2_000),
  54. });
  55. if (!response.ok) throw new Error(`下发 client/configs 失败:status=${response.status}`);
  56. }
  57. describe("草稿模型迁移:手机远控", () => {
  58. after(async () => {
  59. await setRelayClientConfigs({}).catch(() => {});
  60. await clearAppData();
  61. });
  62. it("DMM-10:手机作用域独立迁移并弹一次气泡,经 attachment 读取规则", async () => {
  63. // Host 按刷新间隔缓存 client/configs;规则须在应用首次读取前就位。
  64. await setRelayClientConfigs({
  65. draftModelMigration: {
  66. revision: 1,
  67. targetModelId: TARGET_MODEL,
  68. sourceModelIds: [SOURCE_MODEL],
  69. notice: { "zh-CN": NOTICE_ZH_CN },
  70. },
  71. });
  72. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 45_000);
  73. // 保留 profile 的重启也会保留 renderer 的语言偏好,须先同步为中文,避免它写回系统语言。
  74. await pinE2ELocale("zh-CN");
  75. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  76. afterElectronProcessExit: async () => {
  77. // 手机应用优先读桌面语言;浏览器 locale=zh-CN 不能覆盖英文桌面设置。
  78. // 冷启动前落盘,避免运行中切换语言的异步持久化与手机读取设置竞争。
  79. await seedSettings({ locale: "zh-CN", localePreference: "zh-CN" });
  80. await seedReplayProvider({
  81. id: OFFICIAL_PROVIDER_ID,
  82. templateId: OFFICIAL_PROVIDER_ID,
  83. name: "BigModel API",
  84. baseURL: "http://127.0.0.1:9/v1",
  85. models: [TARGET_MODEL, SOURCE_MODEL],
  86. });
  87. },
  88. });
  89. // 配对材料只经内存与 loopback 传递,不写 WebDriver 日志。
  90. let receivePair!: (url: string) => void;
  91. const pairing = new Promise<string>((resolve) => {
  92. receivePair = resolve;
  93. });
  94. const receiver = createServer(async (request, response) => {
  95. response.setHeader("Access-Control-Allow-Origin", "*");
  96. if (request.method !== "OPTIONS") {
  97. let value = "";
  98. for await (const chunk of request) value += String(chunk);
  99. receivePair(value);
  100. }
  101. response.end();
  102. });
  103. receiver.listen(0, "127.0.0.1");
  104. await once(receiver, "listening");
  105. const address = receiver.address();
  106. if (!address || typeof address === "string") throw new Error("Missing pairing receiver");
  107. let mobile: Browser | undefined;
  108. let page: Page | undefined;
  109. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR!;
  110. try {
  111. await browser.execute((port) => {
  112. const original = navigator.clipboard.writeText.bind(navigator.clipboard);
  113. (window as MobileWindow).__dmm10RestoreClipboard = () => {
  114. navigator.clipboard.writeText = original;
  115. };
  116. navigator.clipboard.writeText = async (text) => {
  117. await fetch(`http://127.0.0.1:${port}`, { method: "POST", body: text });
  118. };
  119. }, address.port);
  120. await $(
  121. 'button[aria-label="移动端远程控制"], button[aria-label="Mobile remote control"]',
  122. ).click();
  123. await browser.waitUntil(
  124. () =>
  125. browser.execute(() => {
  126. const button = Array.from(
  127. document.querySelectorAll<HTMLButtonElement>(
  128. '[data-testid="web-remote-control-dialog-scroll"] button',
  129. ),
  130. ).find(
  131. (node) => /^(复制链接|Copy link)$/.test(node.innerText.trim()) && !node.disabled,
  132. );
  133. button?.click();
  134. return Boolean(button);
  135. }),
  136. { timeout: 60_000, timeoutMsg: "DMM-10 配对链接不可用" },
  137. );
  138. const pairUrl = await pairing;
  139. if (new URL(pairUrl).hostname !== "127.0.0.1") throw new Error("Local Web fixture required");
  140. mobile = await chromium.launch({
  141. ...e2eMobileBrowserLaunchOptions(),
  142. headless: true,
  143. args: process.env.ZCODE_E2E_BROWSER_NO_PROXY === "1" ? ["--no-proxy-server"] : [],
  144. });
  145. const context = await mobile.newContext({
  146. viewport: { width: 390, height: 844 },
  147. isMobile: true,
  148. hasTouch: true,
  149. locale: "zh-CN",
  150. });
  151. await seedMobileFixtureLogin(context);
  152. page = await context.newPage();
  153. await openMobilePairingPage(page, pairUrl, {
  154. artifactDir,
  155. caseMarker: CASE_MARKER,
  156. phase: "pair",
  157. readySelector: PROJECT_SELECTOR,
  158. });
  159. // 进入项目新建草稿,从手机 store 读取作用域,构造“官方模板 + 源模型”的手机端 Recent。
  160. const openProjectDraft = async () => {
  161. await page!
  162. .locator(PROJECT_SELECTOR)
  163. .getByTestId("virtual-project-create-task")
  164. .first()
  165. .tap();
  166. await page!.locator('[data-mobile-page="chat"]').waitFor();
  167. };
  168. await openProjectDraft();
  169. // 等应用完成语言水合再种源模型,不能让“无匹配文案”掩盖气泡断言。
  170. await page.waitForFunction(() => document.documentElement.lang === "zh-CN");
  171. const recentKey = await page.evaluate(() => {
  172. const target = window as MobileWindow;
  173. const path = target.__zcodeTabStoreE2E!.getState().activeWorkspacePath!;
  174. const projectId = target
  175. .__zcodeSessionStoreE2E!.getState()
  176. .getWorkspaceState(path).draftProjectId;
  177. // 手机命名空间来自配对参数;从已有键里取,避免测试侧复算设备身份。
  178. const existing = Object.keys(localStorage).find((key) =>
  179. key.startsWith("zcode-composer-workspace-scope:v1:"),
  180. );
  181. const scope = existing
  182. ? (JSON.parse(localStorage.getItem(existing)!) as {
  183. clientNamespace: string;
  184. hostId: string;
  185. })
  186. : null;
  187. if (!scope?.clientNamespace.startsWith("mobile:")) {
  188. throw new Error(`手机草稿作用域未就绪: ${existing ?? "none"}`);
  189. }
  190. return `zcode-composer-recent:v2:${JSON.stringify([scope.clientNamespace, scope.hostId, projectId ?? null])}`;
  191. });
  192. await page.evaluate(
  193. ({ key, providerId, modelId }) =>
  194. localStorage.setItem(
  195. key,
  196. JSON.stringify({
  197. modelSelection: { providerId, modelId, options: { reasoningLevel: "disabled" } },
  198. mode: "build",
  199. order: 1,
  200. }),
  201. ),
  202. { key: recentKey, providerId: OFFICIAL_PROVIDER_ID, modelId: SOURCE_MODEL },
  203. );
  204. // 返回首页再新建,让本次打开从上面写入的 Recent 初始化。
  205. await page.getByRole("button", { name: /返回任务首页|Back to task home/ }).tap();
  206. await openProjectDraft();
  207. const expectedValue = encodeCustomModelValue(OFFICIAL_PROVIDER_ID, TARGET_MODEL);
  208. const trigger = page.getByTestId(TID_CHAT_MODEL_SELECT_TRIGGER).first();
  209. await page.waitForFunction(
  210. ({ selector, value }) =>
  211. document.querySelector<HTMLElement>(selector)?.dataset.modelCurrentValue === value,
  212. { selector: `[data-testid="${TID_CHAT_MODEL_SELECT_TRIGGER}"]`, value: expectedValue },
  213. { timeout: 30_000 },
  214. );
  215. expect(await trigger.getAttribute("data-model-current-value")).toBe(expectedValue);
  216. // Radix Tooltip 另渲染一份 VisuallyHidden 副本(role=tooltip,1px 裁剪)供 aria-describedby 使用,
  217. // Playwright 仍视其为可见;按浮层结构只取真正显示的那份气泡。
  218. const guide = page.locator(
  219. `[data-slot="tooltip-content"] [data-testid="${TID_CHAT_MODEL_GUIDE}"]:not([role="tooltip"] *)`,
  220. );
  221. await guide.waitFor({ timeout: 15_000 });
  222. expect((await guide.innerText()).trim()).toBe(NOTICE_ZH_CN);
  223. await page.screenshot({ path: join(artifactDir, "dmm-10-mobile-guide.png") });
  224. // 布局:不超出输入框、离屏幕边至少 8px,长文案换行。
  225. const layout = await page.evaluate(
  226. ({ guideTestId, triggerTestId, composerTestId }) => {
  227. const guideElement = Array.from(
  228. document.querySelectorAll<HTMLElement>(`[data-testid="${guideTestId}"]`),
  229. ).find((element) => !element.closest('[role="tooltip"]'));
  230. const bubble = guideElement?.closest<HTMLElement>('[data-slot="tooltip-content"]');
  231. const trigger = Array.from(
  232. document.querySelectorAll<HTMLElement>(`[data-testid="${triggerTestId}"]`),
  233. ).find((element) => element.getClientRects().length > 0);
  234. const composer = trigger?.closest<HTMLElement>(`[data-testid="${composerTestId}"]`);
  235. const text = guideElement?.firstElementChild as HTMLElement | null | undefined;
  236. if (!bubble || !trigger || !composer || !text) return null;
  237. return {
  238. bubble: bubble.getBoundingClientRect().toJSON() as DOMRect,
  239. trigger: trigger.getBoundingClientRect().toJSON() as DOMRect,
  240. composer: composer.getBoundingClientRect().toJSON() as DOMRect,
  241. textHeight: text.getBoundingClientRect().height,
  242. // line-height 为 normal 时按字号 1.2 倍估算单行高度。
  243. lineHeight:
  244. Number.parseFloat(getComputedStyle(text).lineHeight) ||
  245. Number.parseFloat(getComputedStyle(text).fontSize) * 1.2,
  246. viewport: window.innerWidth,
  247. };
  248. },
  249. {
  250. guideTestId: TID_CHAT_MODEL_GUIDE,
  251. triggerTestId: TID_CHAT_MODEL_SELECT_TRIGGER,
  252. composerTestId: TID_V4_COMPOSER,
  253. },
  254. );
  255. if (!layout) throw new Error("没有找到气泡、模型按钮或输入框");
  256. console.log(`[DMM-10] 气泡布局 ${JSON.stringify(layout)}`);
  257. // 手机上按钮左侧放不下整行气泡,碰撞处理会向右平移;要求是不超出输入框、不贴屏幕边。
  258. expect(layout.bubble.right).toBeLessThanOrEqual(layout.composer.right + 0.5);
  259. expect(layout.bubble.left).toBeGreaterThanOrEqual(layout.composer.left - 0.5);
  260. expect(layout.bubble.left).toBeGreaterThanOrEqual(8 - 0.5);
  261. expect(layout.bubble.right).toBeLessThanOrEqual(layout.viewport - 8 + 0.5);
  262. if (layout.textHeight < layout.lineHeight * 2 - 1)
  263. throw new Error(`手机长文案没有换行: ${JSON.stringify(layout)}`);
  264. expect(
  265. JSON.parse((await page.evaluate((key) => localStorage.getItem(key), NOTICE_KEY))!),
  266. ).toEqual({ revision: 1 });
  267. const migratedRecent = JSON.parse(
  268. (await page.evaluate((key) => localStorage.getItem(key), recentKey))!,
  269. ) as { modelSelection: { modelId: string }; mode: string };
  270. expect(migratedRecent.modelSelection.modelId).toBe(TARGET_MODEL);
  271. expect(migratedRecent.mode).toBe("build");
  272. // 手机迁移不写桌面:桌面浏览器存储里没有手机作用域的迁移标记与气泡记录。
  273. const desktopNotice = await browser.execute(
  274. (key) => window.localStorage.getItem(key),
  275. NOTICE_KEY,
  276. );
  277. expect(desktopNotice).toBeNull();
  278. } finally {
  279. await browser
  280. .execute(() => (window as MobileWindow).__dmm10RestoreClipboard?.())
  281. .catch(() => {});
  282. await page?.close().catch(() => {});
  283. await mobile?.close().catch(() => {});
  284. receiver.closeAllConnections();
  285. await new Promise<void>((resolve) => receiver.close(() => resolve()));
  286. }
  287. });
  288. });