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

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