conversation-session-composer-compression.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import assert from "node:assert/strict";
  2. import { mkdir, readFile, writeFile } from "node:fs/promises";
  3. import { dirname, join } from "node:path";
  4. import { NodePersonalProviderConfigRepository } from "@zcode/provider-node";
  5. import { ZCODE_CUA_OFFICIAL_PLUGIN_ID } from "@zcode/shared";
  6. import {
  7. TID_LOGIN_USE_API_KEY_BUTTON,
  8. TID_TASK_SETTINGS_BUTTON,
  9. TID_CHAT_MODEL_SELECT_TRIGGER,
  10. } from "@zcode/shared/test-ids";
  11. import {
  12. clearAppData,
  13. DEFAULT_WORKSPACE,
  14. getE2EAppDataPaths,
  15. setCurrentElectronRendererContentSize,
  16. restoreElectronRendererContentSize,
  17. } from "#e2e/helpers/desktop-app";
  18. import { UPSTREAM_PROVIDER_ID, UPSTREAM_SECONDARY_MODEL } from "#e2e/helpers/upstream-provider";
  19. import {
  20. prepareV4ConversationE2E,
  21. loginWithApiKey,
  22. switchV4Model,
  23. switchV4Mode,
  24. } from "#e2e/helpers/v4-conversation";
  25. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  26. import { skipOccupationOnboardingIfPresent } from "#e2e/helpers/occupation-onboarding";
  27. const CASE_NAME = "conversation-session-composer-compression";
  28. const evidence = join(
  29. process.env.ZCODE_E2E_ARTIFACT_DIR ?? join(process.cwd(), ".e2e-artifacts"),
  30. CASE_NAME,
  31. );
  32. async function snapshot() {
  33. return browser.execute((testId) => {
  34. const model = document.querySelector<HTMLElement>(`[data-testid="${testId}"]`)!;
  35. const root =
  36. model.closest<HTMLElement>("[data-composer-toolbar]") ??
  37. model.closest<HTMLElement>(".group\\/toolbar")!;
  38. if (!root) throw new Error("找不到真实 composer toolbar");
  39. const visible = (el: Element | null) =>
  40. Boolean(
  41. el &&
  42. el.getBoundingClientRect().width > 0 &&
  43. el.getBoundingClientRect().height > 0 &&
  44. getComputedStyle(el).visibility !== "hidden",
  45. );
  46. const controls = ["0", "1", "2", "3"].map((priority) =>
  47. root.querySelector<HTMLElement>(`[data-composer-collapse-priority="${priority}"]`),
  48. );
  49. // Think 已合并到模型按钮;绿条在该按钮内,不再有独立 Think 控件。
  50. const thought = model;
  51. const prefix = model.querySelector(".composer-provider-prefix");
  52. const bar = thought?.querySelector(".bg-success") ?? null;
  53. const rect = (el: Element) => {
  54. const r = el.getBoundingClientRect();
  55. return { x: r.x, y: r.y, right: r.right, bottom: r.bottom, width: r.width, height: r.height };
  56. };
  57. const modelIcon = root.dataset.composerModelIcon === "true";
  58. const providerHidden = root.dataset.composerProviderCompact === "true";
  59. const compact = controls.map((el) => el?.dataset.composerCompact ?? "full");
  60. const stage = modelIcon
  61. ? 5
  62. : compact[3] === "true"
  63. ? 4
  64. : compact[2] === "true"
  65. ? 3
  66. : compact[1] === "true"
  67. ? 2
  68. : compact[0] === "true"
  69. ? 1
  70. : 0;
  71. return {
  72. stage,
  73. compact,
  74. providerHidden,
  75. modelIcon,
  76. prefix: prefix?.textContent ?? null,
  77. prefixVisible: visible(prefix),
  78. barVisible: visible(bar),
  79. bar: bar ? rect(bar) : null,
  80. track: bar?.parentElement ? rect(bar.parentElement) : null,
  81. label: model.querySelector("span[title]") ? rect(model.querySelector("span[title]")!) : null,
  82. modelText: model.querySelector("span[title] > span > span:last-child")
  83. ? rect(model.querySelector("span[title] > span > span:last-child")!)
  84. : null,
  85. providerText: prefix ? rect(prefix) : null,
  86. title: model.querySelector("[title]")?.getAttribute("title") ?? null,
  87. controls: controls.map((el) => (el ? rect(el) : null)),
  88. model: rect(model),
  89. root: rect(root),
  90. leading: rect(root.querySelector("[data-composer-leading-content]")!),
  91. trailing: rect(root.querySelector("[data-composer-trailing-actions]")!),
  92. text: model.innerText,
  93. };
  94. }, TID_CHAT_MODEL_SELECT_TRIGGER);
  95. }
  96. type Snapshot = Awaited<ReturnType<typeof snapshot>>;
  97. function assertLayout(s: Snapshot) {
  98. const expected: string[] = [s.stage >= 1, s.stage >= 2, s.stage >= 3].map((compact) =>
  99. compact ? "true" : "full",
  100. );
  101. expected.push(s.stage >= 4 ? "true" : "full");
  102. assert.deepEqual(s.compact, expected, JSON.stringify(s));
  103. assert.equal(s.prefixVisible, false, JSON.stringify(s));
  104. assert.equal(s.barVisible, s.stage >= 4, JSON.stringify(s));
  105. for (const [i, control] of s.controls.entries()) {
  106. assert.ok(control, "桌面各入口必须真实存在");
  107. if (i < 3 && s.compact[i] === "true") {
  108. assert.ok(
  109. Math.abs(control.width - 28) < 1 && Math.abs(control.height - 28) < 1,
  110. JSON.stringify(s),
  111. );
  112. }
  113. }
  114. if (s.modelIcon)
  115. assert.equal(s.text.includes(UPSTREAM_SECONDARY_MODEL), false, "最后一档显示模型图标");
  116. else assert.ok(s.text.includes(UPSTREAM_SECONDARY_MODEL), "模型文字必须保留到最后一档");
  117. if (!s.modelIcon) {
  118. assert.ok(s.label && s.modelText, "展开态必须保留完整模型文字");
  119. assert.ok(
  120. s.modelText.x >= s.label.x - 1 && s.modelText.right <= s.label.right + 1,
  121. "模型文字不能横向截断",
  122. );
  123. assert.ok(
  124. s.modelText.y >= s.label.y - 2 && s.modelText.bottom <= s.label.bottom + 2,
  125. "模型文字不能落到第二行被裁掉",
  126. );
  127. if (s.prefixVisible)
  128. assert.ok(
  129. s.providerText && Math.abs(s.providerText.y - s.modelText.y) < 1,
  130. "provider 与 model 必须同一行",
  131. );
  132. }
  133. if (s.barVisible) {
  134. assert.ok(s.bar && s.track && s.bar.width > 0 && s.bar.height > 0);
  135. assert.ok(Math.abs(s.bar.height - s.track.height) < 1, "max 档绿条应占满轨道");
  136. }
  137. assert.ok(s.leading.right <= s.trailing.x + 1, "两组按钮不能相互覆盖");
  138. assert.ok(s.trailing.right <= s.root.right + 1, "发送区不能溢出");
  139. assert.ok(Math.abs(s.model.y - s.controls[3]!.y) < 2, "模型与 think 必须保持单行");
  140. }
  141. async function settledSnapshot() {
  142. // 等待 ResizeObserver 布局回写后的两次绘制,不直接设置压缩状态。
  143. await browser.executeAsync((done) =>
  144. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  145. );
  146. return snapshot();
  147. }
  148. describe("Composer 五档压缩", () => {
  149. before(async () => {
  150. await browser.waitUntil(
  151. async () =>
  152. browser.execute(
  153. (login, settings) =>
  154. Boolean(
  155. document.querySelector(
  156. `[data-testid="${login}"], [data-testid="${settings}"], [data-testid="onboarding-page"]`,
  157. ),
  158. ),
  159. TID_LOGIN_USE_API_KEY_BUTTON,
  160. TID_TASK_SETTINGS_BUTTON,
  161. ),
  162. { timeout: 30000 },
  163. );
  164. if (await $(`[data-testid="${TID_LOGIN_USE_API_KEY_BUTTON}"]`).isExisting())
  165. await loginWithApiKey();
  166. await skipOccupationOnboardingIfPresent();
  167. });
  168. after(async () => {
  169. await clearAppData();
  170. });
  171. it("CMP01: 真实窗口逐档缩窄与放宽,合并模型入口按五档顺序压缩且绿条保留", async function () {
  172. this.timeout(240000);
  173. await prepareV4ConversationE2E();
  174. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  175. afterElectronProcessExit: async () => {
  176. const paths = getE2EAppDataPaths();
  177. const settingsFile = join(paths.appDataDir, "setting.json");
  178. const settings = JSON.parse(await readFile(settingsFile, "utf8"));
  179. await writeFile(
  180. settingsFile,
  181. JSON.stringify({
  182. ...settings,
  183. computerUseComposerEntryHidden: false,
  184. locale: "zh-CN",
  185. localePreference: "zh-CN",
  186. }),
  187. );
  188. const configFile = join(paths.homeDir, ".zcode", "cli", "config.json");
  189. const config = JSON.parse(
  190. await readFile(configFile, "utf8").catch((error: NodeJS.ErrnoException) => {
  191. if (error.code === "ENOENT") return "{}";
  192. throw error;
  193. }),
  194. );
  195. await mkdir(dirname(configFile), { recursive: true });
  196. await writeFile(
  197. configFile,
  198. JSON.stringify({
  199. ...config,
  200. plugins: {
  201. ...config.plugins,
  202. enabled: true,
  203. enabledPlugins: {
  204. ...config.plugins?.enabledPlugins,
  205. [ZCODE_CUA_OFFICIAL_PLUGIN_ID]: true,
  206. },
  207. },
  208. }),
  209. );
  210. const repo = new NodePersonalProviderConfigRepository({
  211. filePath: paths.configFile,
  212. pollingIntervalMs: false,
  213. });
  214. try {
  215. await repo.update((current) => ({
  216. ...current,
  217. providers: current.providers.setRule({
  218. ...current.providers.getRule(UPSTREAM_PROVIDER_ID)!,
  219. providerName: "E2E",
  220. }),
  221. }));
  222. } finally {
  223. repo.dispose();
  224. }
  225. },
  226. });
  227. await switchV4Model(UPSTREAM_PROVIDER_ID, UPSTREAM_SECONDARY_MODEL, "max");
  228. // 修复原因:CUA 入口要等 renderer 插件 store 初始化(plugin-management.listPlugins,
  229. // 冷启动实测 7s+,与官方插件 seed 同一条 agent 串行链)后才知道插件已启用。
  230. // 默认 5s 隐式等待在冷启动下不够,这里按真实耗时显式等待优先级 0 的控件。
  231. await $('[data-composer-collapse-priority="0"]').waitForDisplayed({
  232. timeout: 60000,
  233. timeoutMsg: "CUA 入口没有出现(插件 store 未就绪或插件未启用?)",
  234. });
  235. await switchV4Mode("plan");
  236. await $('[data-composer-collapse-priority="2"]').waitForDisplayed({ timeout: 30000 });
  237. await mkdir(evidence, { recursive: true });
  238. const original = await setCurrentElectronRendererContentSize(1600, 760);
  239. const minimum = await browser.electron.execute((electron, id) => {
  240. const win = electron.BrowserWindow.fromId(id)!;
  241. const min = win.getMinimumSize();
  242. win.setMinimumSize(320, 400);
  243. return min;
  244. }, original.windowId);
  245. const samples: { width: number; state: Snapshot }[] = [];
  246. const stages = new Map<number, number>();
  247. try {
  248. let previous = 0;
  249. for (let width = 1600; width >= 320; width -= 8) {
  250. await setCurrentElectronRendererContentSize(width, 760);
  251. const state = await settledSnapshot();
  252. samples.push({ width, state });
  253. assertLayout(state);
  254. assert.ok(state.stage >= previous, "缩窄时不能反向展开");
  255. previous = state.stage;
  256. if (!stages.has(state.stage)) {
  257. stages.set(state.stage, width);
  258. await browser.saveScreenshot(join(evidence, `stage-${state.stage}.png`));
  259. }
  260. if (state.stage === 5) break;
  261. }
  262. assert.deepEqual(
  263. [...stages.keys()],
  264. [0, 1, 2, 3, 4, 5],
  265. "必须观察到所有独立档位,不能只经过首尾状态",
  266. );
  267. for (const [stage, width] of [...stages.entries()].reverse()) {
  268. await setCurrentElectronRendererContentSize(width, 760);
  269. const state = await settledSnapshot();
  270. assertLayout(state);
  271. assert.equal(state.stage, stage, "相同宽度放宽必须恢复相同档位");
  272. }
  273. } finally {
  274. await writeFile(join(evidence, "compression.json"), JSON.stringify(samples, null, 2));
  275. await browser.electron.execute(
  276. (electron, id, min) => electron.BrowserWindow.fromId(id)?.setMinimumSize(min[0]!, min[1]!),
  277. original.windowId,
  278. minimum,
  279. );
  280. await restoreElectronRendererContentSize(original);
  281. }
  282. });
  283. });