conversation-session-project-behavior.test.ts 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  1. // 统一 runner 与旧手工入口均使用隔离 HOME;不能因 runId 前缀不同拒绝安全夹具。
  2. import { DatabaseSync } from "node:sqlite";
  3. import { join, basename } from "node:path";
  4. import { mkdir, writeFile } from "node:fs/promises";
  5. import { waitForWorkspaceApp, DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  6. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  7. import { loginWithApiKey } from "#e2e/helpers/v4-conversation";
  8. import { TID_AUTOMATIONS_OPEN } from "@zcode/shared/test-ids";
  9. import { ServiceChannels } from "@zcode/shared";
  10. import {
  11. installHandoffRpcProbe,
  12. callHandoffHost,
  13. restoreHandoffProbes,
  14. } from "#e2e/helpers/remote-project-handoff-probe";
  15. const projectId = "e2e-project-behavior";
  16. const name = "E2E_PROJECT_BEHAVIOR";
  17. const rowSelector = `[data-project-id="${projectId}"]`;
  18. const taskSelector = '[data-testid^="task-item-"]';
  19. const indicatorSelector = '[data-testid="project-drop-indicator"]';
  20. declare global {
  21. interface Window {
  22. __projectDeletionTrace?: { orders: string[][]; stop(): void };
  23. }
  24. }
  25. describe("虚拟项目旧产品体验", () => {
  26. afterEach(async function () {
  27. if (this.currentTest?.state !== "failed") return;
  28. const state = await browser.execute(() => ({
  29. body: document.body.innerText.slice(-3500),
  30. dialogs: [...document.querySelectorAll('[role="dialog"]')].map((el) => el.textContent),
  31. projects: [...document.querySelectorAll("[data-project-id]")].map((el) => ({
  32. id: el.getAttribute("data-project-id"),
  33. text: el.textContent?.slice(0, 160),
  34. })),
  35. focused: document.activeElement?.outerHTML.slice(0, 300),
  36. }));
  37. await writeFile(
  38. join(
  39. process.env.ZCODE_E2E_ARTIFACT_DIR!,
  40. `project-behavior-${this.currentTest?.title.replace(/[^a-z0-9]+/gi, "-")}.json`,
  41. ),
  42. JSON.stringify(
  43. { state, navigation: await readNavigation().catch((error) => String(error)) },
  44. null,
  45. 2,
  46. ),
  47. );
  48. });
  49. before(async function () {
  50. this.timeout(60_000);
  51. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 45_000);
  52. const home = process.env.ZCODE_E2E_HOME_DIR;
  53. // 修复原因:转正后默认 formal 单跑使用 `.e2e-home`(无 runId 后缀),旧守卫只认
  54. // `.e2e-home-`,会让正式用例在隔离 HOME 下误报。两种目录名都只存在于 E2E runner。
  55. if (!home || !/^(?:zcode-project-behavior-e2e-|\.e2e-home(?:-|$))/u.test(basename(home)))
  56. throw new Error("isolated project behavior E2E HOME required");
  57. const root = join(DEFAULT_WORKSPACE, ".zcode-e2e", "project-behavior");
  58. await mkdir(root, { recursive: true });
  59. await writeFile(join(root, "E2E_TASK_FILES.txt"), "project root file");
  60. const taskRoot = join(root, "task-cwd");
  61. await mkdir(taskRoot, { recursive: true });
  62. await writeFile(join(taskRoot, "E2E_PINNED_TASK_FILES.txt"), "task cwd file");
  63. // 运行中写库不发布 Host 快照;非法 meta 还会让归档/置顶命令读不到任务。
  64. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  65. afterElectronProcessExit: async () => {
  66. const db = new DatabaseSync(join(home, ".zcode/v2/tasks-index.sqlite"));
  67. try {
  68. // 纯列表 fixture:只在隔离库准备已持久化的历史镜像,不声称覆盖模型/CLI 执行。
  69. db.prepare(
  70. "INSERT INTO projects(project_id,host_id,name,position,created_at,updated_at) VALUES(?,'local',?,0,1,1)",
  71. ).run(projectId, name);
  72. db.prepare(
  73. "INSERT INTO project_roots(project_id,root_path,position,is_primary) VALUES(?,?,0,1)",
  74. ).run(projectId, root);
  75. for (const [id, label, position] of [
  76. ["e2e-empty-a", "E2E_EMPTY_A", 1],
  77. ["e2e-empty-b", "E2E_EMPTY_B", 2],
  78. ] as const) {
  79. db.prepare(
  80. "INSERT INTO projects(project_id,host_id,name,position,created_at,updated_at) VALUES(?,'local',?,?,1,1)",
  81. ).run(id, label, position);
  82. }
  83. const insert = db.prepare(
  84. "INSERT INTO tasks(workspace_key,workspace_path,task_id,title,provider,created_at,updated_at,host_id,root_path,project_id,pinned,unread_at,cli_title,cli_title_source,cli_created_at,cli_updated_at,cli_last_outcome,cli_deleted,meta_json) VALUES(?,?,?,?, 'glm',1,1,'local',?,?,?,?,?,'custom',?,?,'completed',0,?)",
  85. );
  86. const baselineTime = Date.now() - 100_000;
  87. const yesterday = new Date();
  88. yesterday.setDate(yesterday.getDate() - 1);
  89. yesterday.setHours(12, 0, 0, 0);
  90. for (let i = 0; i < 30; i++) {
  91. const title = `E2E_BEHAVIOR_${String(i).padStart(2, "0")}`;
  92. const taskPath = i === 7 ? taskRoot : root;
  93. insert.run(
  94. taskPath,
  95. taskPath,
  96. `e2e-behavior-${i}`,
  97. title,
  98. taskPath,
  99. projectId,
  100. i >= 7 ? 1 : 0,
  101. i === 29 ? 10 : null,
  102. title,
  103. baselineTime + i + 1,
  104. i < 18 ? baselineTime + 100 - i : yesterday.getTime() - i,
  105. JSON.stringify({
  106. taskId: `e2e-behavior-${i}`,
  107. traceId: `e2e-behavior-${i}`,
  108. title,
  109. workspacePath: taskPath,
  110. createdAt: baselineTime + i + 1,
  111. updatedAt: i < 18 ? baselineTime + 100 - i : yesterday.getTime() - i,
  112. mode: "build",
  113. provider: "glm",
  114. status: "completed",
  115. }),
  116. );
  117. }
  118. } finally {
  119. db.close();
  120. }
  121. },
  122. });
  123. await $(rowSelector).waitForDisplayed({ timeout: 45_000 });
  124. });
  125. it("D3:快捷键菜单命令和左上角继承项目,任务分区显式未归类", async () => {
  126. const project = $(rowSelector);
  127. await project.$('[data-testid="virtual-project-create-task"]').click();
  128. await browser.waitUntil(async () => (await readNavigation()).project === projectId);
  129. const target = await readNavigation();
  130. await invokeNewTaskMenuShortcut();
  131. await browser.waitUntil(async () => {
  132. const state = await readNavigation();
  133. return state.project === projectId && state.task === null && state.focus > target.focus;
  134. });
  135. expect((await readNavigation()).path).toBe(target.path);
  136. const afterShortcut = await readNavigation();
  137. await $('[data-testid="task-new-button"]').click();
  138. await browser.waitUntil(async () => (await readNavigation()).focus > afterShortcut.focus);
  139. expect((await readNavigation()).project).toBe(projectId);
  140. expect((await readNavigation()).path).toBe(target.path);
  141. await $('[data-testid="virtual-project-new-task"]').click();
  142. await browser.waitUntil(async () => {
  143. const state = await readNavigation();
  144. return state.project === null && state.path !== target.path;
  145. });
  146. const unclassified = await readNavigation();
  147. await invokeNewTaskMenuShortcut();
  148. // 新草稿生命周期在首发接纳前复用未归类目录;重复新建只重新聚焦该草稿。
  149. await browser.waitUntil(async () => (await readNavigation()).focus > unclassified.focus);
  150. expect((await readNavigation()).path).toBe(unclassified.path);
  151. expect((await readNavigation()).project).toBeNull();
  152. expect((await readNavigation()).task).toBeNull();
  153. });
  154. it("VP24/31:全部项目收起展开不导航,刷新保持且新建按钮右侧对齐", async () => {
  155. const before = await readNavigation();
  156. const toggle = $('[data-testid="virtual-project-toggle-all"]');
  157. await toggle.click();
  158. const states = () =>
  159. browser.execute(() =>
  160. [...document.querySelectorAll('[data-testid="virtual-project-toggle"]')].map((node) =>
  161. node.getAttribute("aria-expanded"),
  162. ),
  163. );
  164. await browser.waitUntil(async () => (await states()).every((value) => value === "false"));
  165. expect(await readNavigation()).toEqual(before);
  166. await refreshProjectSidebar();
  167. await $(rowSelector).waitForDisplayed({ timeout: 45_000 });
  168. expect((await states()).every((value) => value === "false")).toBe(true);
  169. await $('[data-testid="virtual-project-toggle-all"]').click();
  170. await browser.waitUntil(async () => (await states()).every((value) => value === "true"));
  171. await captureLayouts(
  172. async () => {
  173. await browser.execute(() => {
  174. document.querySelector('[data-testid="project-section"]')!.scrollIntoView({
  175. block: "start",
  176. behavior: "instant",
  177. });
  178. });
  179. await $('[data-testid="project-section"] [data-testid="virtual-project-row"]').moveTo();
  180. await browser.execute(async () => {
  181. await Promise.all(
  182. document.getAnimations().map((animation) => animation.finished.catch(() => {})),
  183. );
  184. });
  185. const edges = await browser.execute(() => {
  186. const right = (id: string) =>
  187. document.querySelector(`[data-testid="${id}"]`)!.getBoundingClientRect().right;
  188. return {
  189. project: right("virtual-project-add"),
  190. task: right("virtual-project-new-task"),
  191. session: right("virtual-project-create-task"),
  192. };
  193. });
  194. expect(Math.abs(edges.project - edges.session)).toBeLessThanOrEqual(1);
  195. expect(Math.abs(edges.task - edges.session)).toBeLessThanOrEqual(1);
  196. },
  197. "sidebar-actions",
  198. false,
  199. );
  200. });
  201. for (const entry of ["menu", "editor"] as const) {
  202. it(`VP31:删除项目保持原位直到消失(${entry})`, async () => {
  203. const targetId = "e2e-empty-a";
  204. const target = $(`[data-project-id="${targetId}"]`);
  205. const preferences = await browser.execute(() =>
  206. localStorage.getItem("zcode-project-sidebar-preferences"),
  207. );
  208. const activeWorkspace = (await readNavigation()).path;
  209. if (!activeWorkspace) throw new Error("缺少活动 workspace");
  210. try {
  211. await browser.electron.execute((electron) => {
  212. electron.BrowserWindow.getAllWindows()
  213. .find((window) => window.isVisible())
  214. ?.focus();
  215. });
  216. await browser.execute((id) => {
  217. document
  218. .querySelector(`[data-project-id="${id}"]`)!
  219. .scrollIntoView({ block: "center", behavior: "instant" });
  220. const orders: string[][] = [];
  221. const sample = () => {
  222. const order = [
  223. ...document.querySelectorAll(
  224. 'aside [data-testid="project-section"] [data-project-id]',
  225. ),
  226. ].map((node) => node.getAttribute("data-project-id")!);
  227. if (JSON.stringify(order) !== JSON.stringify(orders.at(-1))) orders.push(order);
  228. };
  229. sample();
  230. const observer = new MutationObserver(sample);
  231. observer.observe(document.querySelector("aside")!, { childList: true, subtree: true });
  232. window.__projectDeletionTrace = { orders, stop: () => observer.disconnect() };
  233. }, targetId);
  234. await target.$('[data-testid="virtual-project-row"]').click({ button: "right" });
  235. if (entry === "editor") {
  236. await $('[data-testid="virtual-project-edit"]').click();
  237. await $('[data-testid="virtual-project-editor-delete"]').click();
  238. } else {
  239. await $('[data-testid="virtual-project-delete"]').click();
  240. }
  241. await target.waitForExist({ reverse: true });
  242. const orders = await browser.execute(() => {
  243. window.__projectDeletionTrace!.stop();
  244. return window.__projectDeletionTrace!.orders;
  245. });
  246. await writeFile(
  247. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `project-deletion-${entry}.json`),
  248. JSON.stringify(orders, null, 2),
  249. );
  250. const before = orders[0]!;
  251. expect(before.indexOf(targetId)).toBeGreaterThan(0);
  252. expect(before.indexOf(targetId)).toBeLessThan(before.length - 1);
  253. expect(orders).toEqual([before, before.filter((id) => id !== targetId)]);
  254. await refreshProjectSidebar();
  255. await $(rowSelector).waitForDisplayed({ timeout: 45_000 });
  256. expect(await target.isExisting()).toBe(false);
  257. } finally {
  258. await browser.execute(() => window.__projectDeletionTrace?.stop());
  259. await browser.execute((saved) => {
  260. if (saved) localStorage.setItem("zcode-project-sidebar-preferences", saved);
  261. else localStorage.removeItem("zcode-project-sidebar-preferences");
  262. }, preferences);
  263. // 运行中的 Host 不发布直写库事件;等旧进程退出后恢复隔离项目,避免后项仍读删除态。
  264. await restartIntoWorkspacePreservingProfile(activeWorkspace, {
  265. afterElectronProcessExit: () => {
  266. const db = new DatabaseSync(
  267. join(process.env.ZCODE_E2E_HOME_DIR!, ".zcode/v2/tasks-index.sqlite"),
  268. );
  269. try {
  270. db.prepare("UPDATE projects SET deleted=0 WHERE project_id=?").run(targetId);
  271. } finally {
  272. db.close();
  273. }
  274. },
  275. });
  276. await $(rowSelector).waitForDisplayed({ timeout: 45_000 });
  277. await target.waitForDisplayed();
  278. }
  279. });
  280. }
  281. it("VP31:任务分区会话与项目内会话左侧留白一致", async () => {
  282. const setFixtureProject = async (id: string | null) => {
  283. // 前面的导航用例已切换到新目录;重启只恢复活动目录,不能等待无关的默认 workspace。
  284. const activeWorkspace = (await readNavigation()).path;
  285. if (!activeWorkspace) throw new Error("缺少活动 workspace");
  286. await restartIntoWorkspacePreservingProfile(activeWorkspace, {
  287. afterElectronProcessExit: () => {
  288. const db = new DatabaseSync(
  289. join(process.env.ZCODE_E2E_HOME_DIR!, ".zcode/v2/tasks-index.sqlite"),
  290. );
  291. try {
  292. db.prepare("UPDATE tasks SET project_id=? WHERE task_id='e2e-behavior-6'").run(id);
  293. } finally {
  294. db.close();
  295. }
  296. },
  297. });
  298. };
  299. const task = $('[data-testid="conversation-section"] [data-testid="task-item-e2e-behavior-6"]');
  300. const layouts: {
  301. width: number;
  302. theme: string;
  303. rowX: number;
  304. projectX: number;
  305. textX: number;
  306. projectTextX: number;
  307. }[] = [];
  308. try {
  309. // 热写 SQLite 不会发布 Host 快照;离线准备同一条历史后冷恢复,保留其他项目内任务用于比较。
  310. await setFixtureProject(null);
  311. await task.waitForExist({ timeout: 45_000 });
  312. await browser.electron.execute((electron) => {
  313. const window = electron.BrowserWindow.getAllWindows().find((item) => item.isVisible());
  314. window?.focus();
  315. });
  316. await captureLayouts(
  317. async () => {
  318. await browser.waitUntil(() =>
  319. browser.execute(() => {
  320. const panel = document.querySelector("[data-workspace-sidebar-panel]")!;
  321. const style = getComputedStyle(panel);
  322. const target = Math.min(
  323. parseFloat(style.getPropertyValue("--workspace-sidebar-panel-width")),
  324. innerWidth / 2,
  325. );
  326. return (
  327. style.opacity === "1" && Math.abs(panel.getBoundingClientRect().width - target) < 1
  328. );
  329. }),
  330. );
  331. // 只滚动到可见位置,避免 WebDriver 的横向居中滚动改变内缩测量。
  332. await browser.execute(async () => {
  333. await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
  334. await Promise.all(
  335. document
  336. .getAnimations()
  337. .filter(
  338. (animation) => animation.effect?.getComputedTiming().iterations !== Infinity,
  339. )
  340. .map((animation) => animation.finished.catch(() => {})),
  341. );
  342. document
  343. .querySelector('[data-testid="task-item-e2e-behavior-6"]')!
  344. .scrollIntoView({ block: "end", inline: "nearest", behavior: "instant" });
  345. });
  346. await task.moveTo();
  347. layouts.push(
  348. await browser.execute((projectSelector) => {
  349. const row = document.querySelector(
  350. '[data-testid="conversation-section"] [data-task-item-key]',
  351. )!;
  352. const projectRow = document.querySelector(`${projectSelector} [data-task-item-key]`)!;
  353. const sidebarX = document.querySelector("aside")!.getBoundingClientRect().x;
  354. const textX = (node: Element) =>
  355. node.querySelector('[data-task-title-copy="original"]')!.getBoundingClientRect().x -
  356. sidebarX;
  357. return {
  358. width: innerWidth,
  359. theme: document.documentElement.className,
  360. rowX: row.getBoundingClientRect().x - sidebarX,
  361. projectX: projectRow.getBoundingClientRect().x - sidebarX,
  362. textX: textX(row),
  363. projectTextX: textX(projectRow),
  364. };
  365. }, rowSelector),
  366. );
  367. },
  368. "task-section-inset",
  369. false,
  370. );
  371. await writeFile(
  372. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "task-section-inset.json"),
  373. JSON.stringify(layouts, null, 2),
  374. );
  375. for (const layout of layouts) {
  376. expect(layout.rowX).toBeCloseTo(8, 0);
  377. expect(layout.rowX).toBeCloseTo(layout.projectX, 0);
  378. expect(layout.textX).toBeCloseTo(layout.projectTextX, 0);
  379. }
  380. } finally {
  381. await setFixtureProject(projectId);
  382. await $(rowSelector).waitForDisplayed({ timeout: 45_000 });
  383. }
  384. });
  385. it("VP31:标题和置顶缩进、空态、排序动画及取消/刷新", async () => {
  386. const geometry = await browser.execute(() => {
  387. const pinned = document.querySelector('[data-testid="project-pinned-tasks"]')!;
  388. const title = pinned.firstElementChild!;
  389. const section = document.querySelector(
  390. '[data-testid="project-section"] button[data-slot="collapsible-trigger"] span',
  391. )!;
  392. const tasksTitle = document.querySelector(
  393. '[data-testid="conversation-section"] button[data-slot="collapsible-trigger"] span',
  394. )!;
  395. const text = pinned.querySelector('[data-task-title-copy="original"]')!;
  396. const sidebar = document.querySelector("aside")!.getBoundingClientRect();
  397. const range = document.createRange();
  398. range.selectNodeContents(title);
  399. return {
  400. font: getComputedStyle(title).fontSize,
  401. sectionFont: getComputedStyle(section).fontSize,
  402. weight: getComputedStyle(title).fontWeight,
  403. titleX: range.getBoundingClientRect().x - sidebar.x,
  404. sectionX: section.getBoundingClientRect().x - sidebar.x,
  405. tasksX: tasksTitle.getBoundingClientRect().x - sidebar.x,
  406. taskX: text.getBoundingClientRect().x - sidebar.x,
  407. };
  408. });
  409. expect(geometry.font).toBe(geometry.sectionFont);
  410. expect(geometry.weight).toBe("500");
  411. expect(geometry.titleX).toBeCloseTo(18, 0);
  412. expect(geometry.sectionX).toBeCloseTo(geometry.titleX, 0);
  413. expect(geometry.tasksX).toBeCloseTo(geometry.titleX, 0);
  414. expect(geometry.taskX).toBeGreaterThanOrEqual(42);
  415. const a = $('[data-project-id="e2e-empty-a"]');
  416. const b = $('[data-project-id="e2e-empty-b"]');
  417. expect(await a.getText()).toMatch(/暂无任务|No tasks yet/);
  418. expect(await $('[data-testid="conversation-section"]').getText()).toMatch(
  419. /暂无任务|No tasks yet/,
  420. );
  421. // 先收起以在同屏采样真实指针拖动,避免展开高度改变命中位置。
  422. for (const node of [$(rowSelector), a, b])
  423. await node.$('[data-testid="virtual-project-toggle"]').click();
  424. await a.scrollIntoView({ block: "center" });
  425. const order = () =>
  426. browser.execute(() =>
  427. [...document.querySelectorAll('[data-testid="project-section"] [data-project-id]')].map(
  428. (e) => e.getAttribute("data-project-id"),
  429. ),
  430. );
  431. const before = await order();
  432. expect(await $(indicatorSelector).isExisting()).toBe(false);
  433. await a.$('[data-testid="virtual-project-toggle"]').click();
  434. await browser.keys("Space");
  435. await browser.keys("ArrowDown");
  436. await browser.keys("Escape");
  437. expect(await $(indicatorSelector).isExisting()).toBe(false);
  438. expect(await order()).toEqual(before);
  439. await a.$('[data-testid="virtual-project-toggle"]').click();
  440. // 折叠动画结束后才量拖拽坐标,不把前一段高度变化算进排序位移。
  441. await browser.execute(async () => {
  442. await Promise.all(
  443. [...document.querySelectorAll('[data-testid="virtual-project-tasks"]')]
  444. .flatMap((e) => e.getAnimations({ subtree: true }))
  445. .map((a) => a.finished.catch(() => {})),
  446. );
  447. });
  448. const coords = await browser.execute(() => {
  449. const rect = (id: string) =>
  450. document
  451. .querySelector(`[data-project-id="${id}"] [data-testid="virtual-project-toggle"]`)!
  452. .getBoundingClientRect();
  453. const a = rect("e2e-empty-a"),
  454. b = rect("e2e-empty-b");
  455. return {
  456. x: Math.round(a.x + 40),
  457. ay: Math.round(a.y + a.height / 2),
  458. by: Math.round(b.y + b.height / 2),
  459. };
  460. });
  461. await browser.performActions([
  462. {
  463. type: "pointer",
  464. id: "project-mouse",
  465. parameters: { pointerType: "mouse" },
  466. actions: [
  467. { type: "pointerMove", duration: 0, x: coords.x, y: coords.ay },
  468. { type: "pointerDown", button: 0 },
  469. { type: "pointerMove", duration: 100, x: coords.x, y: coords.ay + 8 },
  470. { type: "pointerMove", duration: 200, x: coords.x, y: coords.by },
  471. ],
  472. },
  473. ]);
  474. await browser.waitUntil(() =>
  475. browser.execute(() => {
  476. const node = document.querySelector('[data-project-id="e2e-empty-b"]')!;
  477. const transform = getComputedStyle(node).transform;
  478. return transform !== "none" && Math.abs(new DOMMatrix(transform).m42) > 1;
  479. }),
  480. );
  481. const motion = await browser.execute(() =>
  482. [...document.querySelectorAll("[data-project-id]")].map((e) => ({
  483. id: e.getAttribute("data-project-id"),
  484. transform: getComputedStyle(e).transform,
  485. transition: getComputedStyle(e).transitionDuration,
  486. y:
  487. getComputedStyle(e).transform === "none"
  488. ? 0
  489. : new DOMMatrix(getComputedStyle(e).transform).m42,
  490. })),
  491. );
  492. expect(motion.some((e) => e.id === "e2e-empty-a" && e.transform !== "none")).toBe(true);
  493. expect(
  494. motion.some((e) => e.id === "e2e-empty-b" && Math.abs(e.y) > 1 && e.transition !== "0s"),
  495. ).toBe(true);
  496. await assertDropIndicator("e2e-empty-b", "after");
  497. await browser.saveScreenshot(
  498. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "project-insertion-pointer.png"),
  499. );
  500. await browser.performActions([
  501. {
  502. type: "pointer",
  503. id: "project-mouse",
  504. parameters: { pointerType: "mouse" },
  505. actions: [{ type: "pointerUp", button: 0 }],
  506. },
  507. ]);
  508. await browser.releaseActions();
  509. expect(await $(indicatorSelector).isExisting()).toBe(false);
  510. await browser.waitUntil(
  511. async () => (await order()).indexOf("e2e-empty-a") > (await order()).indexOf("e2e-empty-b"),
  512. );
  513. const pointerOrder = await order();
  514. // 键盘复用同一排序通路,将 A 移回 B 上方,并验证持久化。
  515. await browser.execute(() =>
  516. document
  517. .querySelector<HTMLElement>(
  518. '[data-project-id="e2e-empty-a"] [data-testid="virtual-project-toggle"]',
  519. )!
  520. .focus(),
  521. );
  522. await browser.keys("Space");
  523. await browser.keys("ArrowUp");
  524. await assertDropIndicator("e2e-empty-b", "before");
  525. await browser.keys("Space");
  526. expect(await $(indicatorSelector).isExisting()).toBe(false);
  527. await browser.waitUntil(
  528. async () => (await order()).indexOf("e2e-empty-a") < (await order()).indexOf("e2e-empty-b"),
  529. );
  530. const after = await order();
  531. expect(after).toEqual(before);
  532. await refreshProjectSidebar();
  533. await a.waitForExist({ timeout: 45_000 });
  534. expect(await order()).toEqual(after);
  535. await $(rowSelector).$('[data-testid="virtual-project-toggle"]').click();
  536. await writeFile(
  537. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "sidebar-regression.json"),
  538. JSON.stringify({ geometry, motion, before, pointerOrder, after }, null, 2),
  539. );
  540. });
  541. it("VP31:插入线在明暗主题和窄屏可见,取消后清除", async () => {
  542. const projectToggle = $(rowSelector).$('[data-testid="virtual-project-toggle"]');
  543. // 主题截图只验证落点样式;收起历史项目,让相邻目标不受长列表滚动影响。
  544. await projectToggle.click();
  545. try {
  546. await captureLayouts(async () => {
  547. // 指针拖拽已由上一用例覆盖;主题/视口截图用键盘固定目标,避免缩放后的坐标漂移。
  548. await browser.execute(async () => {
  549. await Promise.all(
  550. [...document.querySelectorAll("[data-workspace-sidebar-panel], [data-project-id]")]
  551. .flatMap((node) => node.getAnimations({ subtree: true }))
  552. .map((animation) => animation.finished.catch(() => {})),
  553. );
  554. const toggle = document.querySelector<HTMLElement>(
  555. '[data-project-id="e2e-empty-b"] [data-testid="virtual-project-toggle"]',
  556. )!;
  557. toggle.scrollIntoView({ block: "center", inline: "nearest", behavior: "instant" });
  558. toggle.focus();
  559. });
  560. expect(await $(indicatorSelector).isExisting()).toBe(false);
  561. await browser.keys("Space");
  562. await browser.keys("ArrowUp");
  563. await assertDropIndicator("e2e-empty-a", "before");
  564. });
  565. } finally {
  566. await projectToggle.click();
  567. }
  568. expect(await $(indicatorSelector).isExisting()).toBe(false);
  569. });
  570. it("VP23/SBV04:项目 5/+5,置顶 20/全部/更少,旧排序偏好不生效", async () => {
  571. const project = $(rowSelector);
  572. expect(await project.$$(taskSelector).length).toBe(5);
  573. await project.$('[data-task-list-show-more="true"]').click();
  574. expect(await project.$$(taskSelector).length).toBe(7);
  575. const pinned = $('[data-testid="project-pinned-tasks"]');
  576. expect(await pinned.getText()).toMatch(/已置顶|Pinned/);
  577. expect(await pinned.$$(taskSelector).length).toBe(20);
  578. await pinned.$('[data-task-list-show-more="true"]').click();
  579. expect(await pinned.$$(taskSelector).length).toBe(23);
  580. await pinned.$('[data-task-list-show-more="true"]').click();
  581. expect(await pinned.$$(taskSelector).length).toBe(20);
  582. await $('[data-testid="project-section"] button[data-slot="collapsible-trigger"]').click({
  583. button: "right",
  584. });
  585. expect(await $('[data-testid="project-task-sort-created"]').isExisting()).toBe(false);
  586. await browser.keys("Escape");
  587. await browser.execute(() => {
  588. localStorage.setItem("zcode-sidebar-task-preferences", JSON.stringify({ sortBy: "created" }));
  589. const key = "zcode-project-sidebar-preferences";
  590. localStorage.setItem(
  591. key,
  592. JSON.stringify({ ...JSON.parse(localStorage.getItem(key) ?? "{}"), sort: "updated" }),
  593. );
  594. });
  595. await refreshProjectSidebar();
  596. await project.waitForDisplayed({ timeout: 45_000 });
  597. expect(await project.$(taskSelector).getText()).toContain("E2E_BEHAVIOR_00");
  598. });
  599. it("SBV01/02/03/05:搜索、最近更新混排及分页,切换保留导航与折叠", async () => {
  600. const before = await readNavigation();
  601. const toggle = $(rowSelector).$('[data-testid="virtual-project-toggle"]');
  602. await toggle.click();
  603. const search = $('[data-testid="sidebar-search-open"]');
  604. await search.click();
  605. await $('[role="dialog"] [cmdk-input]').waitForDisplayed();
  606. await browser.keys("Escape");
  607. const apple = await browser.execute(() => /Mac|iPhone|iPad/.test(navigator.platform));
  608. // 搜索入口已改为图标按钮,平台键帽由共享 tooltip 展示。
  609. await $('[role="dialog"]').waitForExist({ reverse: true });
  610. await $("main").moveTo();
  611. await search.moveTo();
  612. const tooltip = $('[data-slot="tooltip-content"]');
  613. await tooltip.waitForDisplayed();
  614. expect(await tooltip.getText()).toContain(apple ? "⌘ K" : "Ctrl+K");
  615. await browser.keys([apple ? "Meta" : "Control", "k"]);
  616. await $('[role="dialog"] [cmdk-input]').waitForDisplayed();
  617. await browser.keys("Escape");
  618. await $('[data-testid="sidebar-view-menu"]').click();
  619. // 视图单选包含未读,图标和勾选沿用同一菜单。
  620. expect(
  621. await $$('[role="menuitemradio"]').map((item) => item.getAttribute("data-testid")),
  622. ).toEqual([
  623. "sidebar-view-projects",
  624. "sidebar-view-grouped",
  625. "sidebar-view-timeline",
  626. "sidebar-view-unread",
  627. ]);
  628. expect(await $('[data-testid="sidebar-view-projects"] svg.lucide-folder').isDisplayed()).toBe(
  629. true,
  630. );
  631. expect(await $('[data-testid="sidebar-view-timeline"] svg.lucide-clock').isDisplayed()).toBe(
  632. true,
  633. );
  634. await browser.saveScreenshot(
  635. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "sidebar-view-icons.png"),
  636. );
  637. await $('[data-testid="sidebar-view-timeline"]').click();
  638. const timeline = $('[data-testid="project-timeline-tasks"]');
  639. await timeline.waitForDisplayed();
  640. expect(await $('[data-testid="project-pinned-tasks"]').isExisting()).toBe(false);
  641. expect(await $('[data-testid="project-section"]').isExisting()).toBe(false);
  642. expect(await timeline.$$(taskSelector).length).toBe(20);
  643. expect(await timeline.$(taskSelector).getText()).toContain("E2E_BEHAVIOR_00");
  644. const dateHeadings = await timeline
  645. .$$("[data-timeline-date-heading]")
  646. .map((row) => row.getText());
  647. expect(dateHeadings).toHaveLength(2);
  648. expect(dateHeadings[0]).toMatch(/^(Today|今天)$/);
  649. expect(dateHeadings[1]).toMatch(/^(Yesterday|昨天)$/);
  650. expect(await timeline.$("[data-task-workspace-label]").getText()).toBe("project-behavior");
  651. expect(await timeline.$('[data-idle-indicator="true"]').isExisting()).toBe(false);
  652. const rowLayout = await browser.execute(() => {
  653. const row = document.querySelector(
  654. '[data-testid="project-timeline-tasks"] [data-task-item-key]',
  655. )!;
  656. const title = row.querySelector('[data-task-title-copy="original"]')!.getBoundingClientRect();
  657. const label = row.querySelector("[data-task-workspace-label]")!.getBoundingClientRect();
  658. const time = row.querySelector("[data-task-row-metadata]")!.getBoundingClientRect();
  659. return { below: label.top >= title.bottom, aligned: Math.abs(label.top - time.top) < 3 };
  660. });
  661. expect(rowLayout).toEqual({ below: true, aligned: true });
  662. await timeline.$('[data-task-list-show-more="true"]').click();
  663. expect(await timeline.$$(taskSelector).length).toBe(30);
  664. expect(
  665. await timeline
  666. .$('[data-testid="task-item-e2e-behavior-29"] [data-unread-indicator="true"]')
  667. .isExisting(),
  668. ).toBe(true);
  669. expect(await timeline.$$("[data-timeline-date-heading]").length).toBe(2);
  670. const db = new DatabaseSync(
  671. join(process.env.ZCODE_E2E_HOME_DIR!, ".zcode/v2/tasks-index.sqlite"),
  672. );
  673. let expected: string[];
  674. try {
  675. expected = db
  676. .prepare(
  677. // Host 会先留下未物化草稿行;列表只展示有 CLI 历史且未删除的任务。
  678. "SELECT task_id FROM tasks WHERE project_id=? AND archived=0 AND deleted=0 AND coalesce(cli_deleted,0)=0 AND cli_created_at IS NOT NULL ORDER BY cli_updated_at DESC,cli_created_at DESC,task_id DESC",
  679. )
  680. .all(projectId)
  681. .map((row) => String(row.task_id));
  682. } finally {
  683. db.close();
  684. }
  685. const actual = await timeline.$$(taskSelector).map((row) => row.getAttribute("data-testid"));
  686. expect(actual).toEqual(expected.map((id) => `task-item-${id}`));
  687. expect(new Set(actual).size).toBe(30);
  688. // 最近更新中的置顶只改变组织态;不从时间序列搬走。
  689. const pinned = $('[data-testid="task-item-e2e-behavior-7"]');
  690. await pinned.moveTo();
  691. await pinned.$('button[aria-label="取消置顶任务"], button[aria-label="Unpin task"]').click();
  692. await pinned.$('button[aria-label="置顶任务"], button[aria-label="Pin task"]').waitForExist();
  693. expect(await timeline.$$(taskSelector).map((row) => row.getAttribute("data-testid"))).toEqual(
  694. actual,
  695. );
  696. await pinned.$('button[aria-label="置顶任务"], button[aria-label="Pin task"]').click();
  697. await pinned
  698. .$('button[aria-label="取消置顶任务"], button[aria-label="Unpin task"]')
  699. .waitForExist();
  700. const archived = $('[data-testid="task-item-e2e-behavior-6"]');
  701. await archived.moveTo();
  702. await archived.$('button[data-testid^="task-archive-"]').click();
  703. await $('[data-archive-confirming-task-id="e2e-behavior-6"]').waitForExist();
  704. await archived.$('button[data-testid^="task-archive-"]').click();
  705. await archived.waitForExist({ reverse: true });
  706. expect(await timeline.$$(taskSelector).length).toBe(29);
  707. expect(await readNavigation()).toEqual(before);
  708. await refreshProjectSidebar('[data-testid="project-timeline-tasks"]');
  709. await timeline.waitForDisplayed({ timeout: 45_000 });
  710. expect(await timeline.$$(taskSelector).length).toBe(20);
  711. expect(await $('[data-testid="task-item-e2e-behavior-6"]').isExisting()).toBe(false);
  712. expect(await readNavigation()).toEqual(before);
  713. await writeFile(
  714. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "sidebar-view.json"),
  715. JSON.stringify({ before, expected, actual }, null, 2),
  716. );
  717. await browser.saveScreenshot(join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "sidebar-recent.png"));
  718. await captureLayouts(undefined, "sidebar-recent");
  719. await $('[data-testid="sidebar-view-menu"]').click();
  720. await $('[data-testid="sidebar-view-projects"]').click();
  721. await $(rowSelector).waitForDisplayed();
  722. expect(await toggle.getAttribute("aria-expanded")).toBe("false");
  723. await toggle.click();
  724. expect(await $(rowSelector).$("[data-task-workspace-label]").isExisting()).toBe(false);
  725. });
  726. it("SBV07:按未读分页、重载、已读移除与空态,切换不改变导航", async () => {
  727. const before = await readNavigation();
  728. const root = join(DEFAULT_WORKSPACE, ".zcode-e2e", "project-behavior");
  729. const setUnread = (index: number, unread: boolean) =>
  730. callHandoffHost(ServiceChannels.WindowController, "mutateTask", [
  731. {
  732. address: {
  733. workspacePath: index === 7 ? join(root, "task-cwd") : root,
  734. taskId: `e2e-behavior-${index}`,
  735. },
  736. mutation: { kind: unread ? "mark-unread" : "mark-read" },
  737. },
  738. ]);
  739. await installHandoffRpcProbe();
  740. try {
  741. // 使用真实 Host 命令产生未读及失效事件,不修改 UI 投影。
  742. for (let index = 7; index < 30; index++) await setUnread(index, true);
  743. await $('[data-testid="sidebar-view-menu"]').click();
  744. const option = $('[data-testid="sidebar-view-unread"]');
  745. expect(await option.$("svg.lucide-bell").isDisplayed()).toBe(true);
  746. await option.click();
  747. const unread = $('[data-testid="project-unread-tasks"]');
  748. await unread.waitForDisplayed();
  749. expect(await unread.$$(taskSelector).length).toBe(20);
  750. expect(await unread.$(taskSelector).getText()).toContain("E2E_BEHAVIOR_07");
  751. expect(await $('[data-testid="project-pinned-tasks"]').isExisting()).toBe(false);
  752. await unread.$('[data-task-list-show-more="true"]').click();
  753. expect(await unread.$$(taskSelector).map((row) => row.getAttribute("data-testid"))).toEqual(
  754. Array.from({ length: 23 }, (_, index) => `task-item-e2e-behavior-${index + 7}`),
  755. );
  756. expect(await readNavigation()).toEqual(before);
  757. await captureLayouts(async () => {
  758. await unread.waitForDisplayed();
  759. }, "sidebar-unread");
  760. await refreshProjectSidebar('[data-testid="project-unread-tasks"]');
  761. expect(await unread.$$(taskSelector).length).toBe(20);
  762. await $('[data-testid="sidebar-view-menu"]').click();
  763. expect(await option.getAttribute("aria-checked")).toBe("true");
  764. await browser.keys("Escape");
  765. await installHandoffRpcProbe();
  766. for (let index = 7; index < 30; index++) await setUnread(index, false);
  767. await $('[data-testid="project-no-tasks"]').waitForDisplayed();
  768. expect(await $('[data-testid="project-no-tasks"]').getText()).toMatch(
  769. /暂无未读任务|No unread tasks/,
  770. );
  771. expect(await unread.isExisting()).toBe(false);
  772. expect(await readNavigation()).toEqual(before);
  773. } finally {
  774. await setUnread(29, true);
  775. await restoreHandoffProbes();
  776. await $('[data-testid="sidebar-view-menu"]').click();
  777. await $('[data-testid="sidebar-view-projects"]').click();
  778. }
  779. });
  780. it("VP24:收起项目显示置顶成员未读,刷新记住折叠,展开不切草稿", async () => {
  781. const project = $(rowSelector);
  782. const toggle = project.$('[data-testid="virtual-project-toggle"]');
  783. await toggle.click();
  784. await project.$('[data-testid="virtual-project-unread"]').waitForDisplayed();
  785. await refreshProjectSidebar();
  786. await project.waitForDisplayed({ timeout: 45_000 });
  787. expect(await toggle.getAttribute("aria-expanded")).toBe("false");
  788. await project.$('[data-testid="virtual-project-unread"]').waitForDisplayed();
  789. const paneBefore = await readNavigation();
  790. await toggle.click();
  791. expect(await project.$('[data-testid="virtual-project-unread"]').isExisting()).toBe(false);
  792. expect(await readNavigation()).toEqual(paneBefore);
  793. });
  794. it("VP29:展开收起有高度和淡入淡出,快速反向点击不丢内容", async () => {
  795. const before = await readNavigation();
  796. const close = await sampleProjectMotion(false);
  797. await writeFile(
  798. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "project-collapse-close.json"),
  799. JSON.stringify(close, null, 2),
  800. );
  801. expect(close.some((frame) => frame.height > 1 && frame.height < close[0]!.height - 1)).toBe(
  802. true,
  803. );
  804. expect(close.some((frame) => frame.opacity > 0 && frame.opacity < 1)).toBe(true);
  805. expect(close.at(-1)!.height).toBe(0);
  806. const open = await sampleProjectMotion(false);
  807. const fullHeight = open.at(-1)!.height;
  808. expect(fullHeight).toBeGreaterThan(0);
  809. expect(open.some((frame) => frame.height > 1 && frame.height < fullHeight - 1)).toBe(true);
  810. expect(open.some((frame) => frame.opacity > 0 && frame.opacity < 1)).toBe(true);
  811. const reverse = await sampleProjectMotion(true);
  812. expect(reverse.at(-1)!.expanded).toBe("true");
  813. expect(reverse.at(-1)!.height).toBeGreaterThan(0);
  814. expect(await $(rowSelector).$$(taskSelector).length).toBe(5);
  815. expect(await readNavigation()).toEqual(before);
  816. await writeFile(
  817. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "project-collapse-motion.json"),
  818. JSON.stringify({ close, open, reverse }, null, 2),
  819. );
  820. });
  821. it("VP25/26/29:置顶任务恢复文件树,普通任务不显示;目录、置顶、窄屏与主题", async () => {
  822. const pinned = $('[data-testid="project-pinned-tasks"]');
  823. const first = pinned.$(taskSelector);
  824. await first.moveTo();
  825. const files = first.$('[data-testid="task-files-e2e-behavior-7"]');
  826. await files.waitForDisplayed();
  827. await files.click();
  828. // 文件入口已迁至右侧独立标签页;跨目录会导航 workspace,不能再查左栏“返回任务”。
  829. const fileTree = $(
  830. '[role="tabpanel"][data-state="active"] [data-file-manager-pane] [data-testid="workspace-file-tree-panel"]',
  831. );
  832. await fileTree.waitForDisplayed();
  833. await browser.waitUntil(async () =>
  834. (await fileTree.getText()).includes("E2E_PINNED_TASK_FILES.txt"),
  835. );
  836. expect(await fileTree.getText()).not.toContain("E2E_TASK_FILES.txt");
  837. expect((await readNavigation()).task).toBeNull();
  838. await $(rowSelector).waitForDisplayed();
  839. await closeActiveFileTab();
  840. const ordinary = $(rowSelector).$(taskSelector);
  841. await ordinary.moveTo();
  842. expect(await ordinary.$('[data-testid^="task-files-"]').isExisting()).toBe(false);
  843. expect(await ordinary.$('button[data-testid^="task-archive-"]').isExisting()).toBe(true);
  844. await $(rowSelector).moveTo();
  845. for (const action of ["menu", "files", "create-task"])
  846. expect(await $(rowSelector).$(`[data-testid="virtual-project-${action}"]`).isExisting()).toBe(
  847. true,
  848. );
  849. await $(rowSelector).$('[data-testid="virtual-project-files"]').click();
  850. await fileTree.waitForDisplayed();
  851. await browser.waitUntil(async () => (await fileTree.getText()).includes("E2E_TASK_FILES.txt"));
  852. expect((await readNavigation()).task).toBeNull();
  853. await closeActiveFileTab();
  854. // 更新时间倒序下首个置顶任务是 7;取消后仍在所属项目,可能位于第二页。
  855. expect(await first.getText()).toContain("E2E_BEHAVIOR_07");
  856. await first.moveTo();
  857. await first.$('button[aria-label="取消置顶任务"], button[aria-label="Unpin task"]').click();
  858. await $(rowSelector).$('[data-task-list-show-more="true"]').click();
  859. await $(rowSelector).$('[data-testid="task-item-e2e-behavior-7"]').waitForDisplayed();
  860. expect(await pinned.getText()).not.toContain("E2E_BEHAVIOR_07");
  861. await $(`[data-testid="${TID_AUTOMATIONS_OPEN}"]`).click();
  862. await browser.waitUntil(
  863. async () =>
  864. (await $(`[data-testid="${TID_AUTOMATIONS_OPEN}"]`).getAttribute("aria-pressed")) ===
  865. "true",
  866. );
  867. await $('[data-testid="plugin-store-sidebar-open"]').click();
  868. await browser.waitUntil(
  869. async () =>
  870. (await $('[data-testid="plugin-store-sidebar-open"]').getAttribute("aria-pressed")) ===
  871. "true",
  872. );
  873. expect(await $(`[data-testid="${TID_AUTOMATIONS_OPEN}"]`).getAttribute("aria-pressed")).toBe(
  874. "false",
  875. );
  876. await $(rowSelector).$('[data-testid="virtual-project-toggle"]').click();
  877. await $(rowSelector).$('[data-testid="virtual-project-unread"]').waitForDisplayed();
  878. await $(rowSelector).scrollIntoView({ block: "end" });
  879. await captureLayouts(
  880. async () => {
  881. const row = $('[data-testid="project-pinned-tasks"]').$(taskSelector);
  882. await row.scrollIntoView({ block: "center" });
  883. await row.moveTo();
  884. await row.$('[data-testid^="task-files-"]').waitForDisplayed();
  885. },
  886. "pinned-task-files",
  887. false,
  888. );
  889. });
  890. it("VP31:41 个项目拖拽启动保持响应,取消不改顺序", async () => {
  891. const home = process.env.ZCODE_E2E_HOME_DIR!;
  892. const db = new DatabaseSync(join(home, ".zcode/v2/tasks-index.sqlite"));
  893. try {
  894. const insert = db.prepare(
  895. "INSERT INTO projects(project_id,host_id,name,position,created_at,updated_at) VALUES(?,'local',?,?,1,1)",
  896. );
  897. for (let i = 0; i < 38; i++) insert.run(`e2e-drag-scale-${i}`, `E2E_DRAG_SCALE_${i}`, i + 10);
  898. } finally {
  899. db.close();
  900. }
  901. await refreshProjectSidebar();
  902. await $('[data-project-id="e2e-drag-scale-37"]').waitForExist({ timeout: 45_000 });
  903. await browser.execute(async () => {
  904. for (const toggle of document.querySelectorAll<HTMLButtonElement>(
  905. '[data-project-id] [data-testid="virtual-project-toggle"][aria-expanded="true"]',
  906. ))
  907. toggle.click();
  908. await new Promise<void>((resolve) =>
  909. requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
  910. );
  911. await Promise.all(
  912. [...document.querySelectorAll("[data-project-id]")]
  913. .flatMap((node) => node.getAnimations({ subtree: true }))
  914. .map((animation) => animation.finished.catch(() => {})),
  915. );
  916. });
  917. const coords = await browser.execute(() => {
  918. const source = document.querySelector<HTMLElement>(
  919. '[data-project-id="e2e-empty-a"] [data-testid="virtual-project-toggle"]',
  920. )!;
  921. source.scrollIntoView({ block: "center", behavior: "instant" });
  922. const a = source.getBoundingClientRect();
  923. const b = document.querySelector('[data-project-id="e2e-empty-b"]')!.getBoundingClientRect();
  924. return {
  925. x: Math.round(a.x + 40),
  926. from: Math.round(a.y + a.height / 2),
  927. to: Math.round(b.y + b.height / 2),
  928. order: [
  929. ...document.querySelectorAll('[data-testid="project-section"] [data-project-id]'),
  930. ].map((node) => node.getAttribute("data-project-id")),
  931. };
  932. });
  933. expect(coords.order.length).toBeGreaterThanOrEqual(41);
  934. await browser.execute(() => {
  935. let previous = performance.now();
  936. let frame = 0;
  937. const gaps: number[] = [];
  938. const longTasks: number[] = [];
  939. const observer = new PerformanceObserver((list) => {
  940. longTasks.push(...list.getEntries().map((entry) => entry.duration));
  941. });
  942. observer.observe({ type: "longtask" });
  943. const tick = (now: number) => {
  944. gaps.push(now - previous);
  945. previous = now;
  946. frame = requestAnimationFrame(tick);
  947. };
  948. frame = requestAnimationFrame(tick);
  949. (window as Window & { __finishProjectDragSample?: () => unknown }).__finishProjectDragSample =
  950. () => {
  951. cancelAnimationFrame(frame);
  952. longTasks.push(...observer.takeRecords().map((entry) => entry.duration));
  953. observer.disconnect();
  954. return {
  955. gaps,
  956. longTasks,
  957. maxFrameGap: Math.max(0, ...gaps),
  958. maxLongTask: Math.max(0, ...longTasks),
  959. };
  960. };
  961. });
  962. try {
  963. await browser.performActions([
  964. {
  965. type: "pointer",
  966. id: "project-scale-mouse",
  967. parameters: { pointerType: "mouse" },
  968. actions: [
  969. { type: "pointerMove", duration: 0, x: coords.x, y: coords.from },
  970. { type: "pointerDown", button: 0 },
  971. { type: "pointerMove", duration: 100, x: coords.x, y: coords.from + 8 },
  972. { type: "pointerMove", duration: 200, x: coords.x, y: coords.to },
  973. ],
  974. },
  975. ]);
  976. await assertDropIndicator("e2e-empty-b", "after");
  977. await browser.keys("Escape");
  978. } finally {
  979. await browser.releaseActions();
  980. }
  981. const sample = await browser.execute(() => {
  982. const bridge = window as Window & {
  983. __finishProjectDragSample?: () => {
  984. gaps: number[];
  985. longTasks: number[];
  986. maxFrameGap: number;
  987. maxLongTask: number;
  988. };
  989. };
  990. const sample = bridge.__finishProjectDragSample!();
  991. delete bridge.__finishProjectDragSample;
  992. return sample;
  993. });
  994. await writeFile(
  995. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "project-drag-performance.json"),
  996. JSON.stringify({ projects: coords.order.length, ...sample }, null, 2),
  997. );
  998. expect(sample.gaps.length).toBeGreaterThan(5);
  999. expect(sample.maxFrameGap).toBeLessThan(100);
  1000. expect(await $(indicatorSelector).isExisting()).toBe(false);
  1001. expect(
  1002. await browser.execute(() =>
  1003. [...document.querySelectorAll('[data-testid="project-section"] [data-project-id]')].map(
  1004. (node) => node.getAttribute("data-project-id"),
  1005. ),
  1006. ),
  1007. ).toEqual(coords.order);
  1008. });
  1009. });
  1010. async function sampleProjectMotion(reverse: boolean) {
  1011. return browser.execute(
  1012. async (selector, reverse) => {
  1013. const project = document.querySelector(selector)!;
  1014. const toggle = project.querySelector<HTMLButtonElement>(
  1015. '[data-testid="virtual-project-toggle"]',
  1016. )!;
  1017. const frames: {
  1018. height: number;
  1019. opacity: number;
  1020. expanded: string | null;
  1021. animation: string;
  1022. }[] = [];
  1023. // 上一个用例刚展开列表;必须等真实动画结束,不能把上一段淡入当作收起证据。
  1024. const previousContent = project.querySelector<HTMLElement>(
  1025. '[data-testid="virtual-project-tasks"]',
  1026. )!;
  1027. await Promise.all(
  1028. [
  1029. ...previousContent.getAnimations(),
  1030. ...(previousContent.firstElementChild?.getAnimations() ?? []),
  1031. ].map((animation) => animation.finished.catch(() => {})),
  1032. );
  1033. const sample = () => {
  1034. const content = project.querySelector<HTMLElement>('[data-testid="virtual-project-tasks"]');
  1035. frames.push({
  1036. height: content?.getBoundingClientRect().height ?? 0,
  1037. opacity: content?.firstElementChild
  1038. ? Number(getComputedStyle(content.firstElementChild).opacity)
  1039. : 0,
  1040. expanded: toggle.getAttribute("aria-expanded"),
  1041. animation: content?.firstElementChild
  1042. ? getComputedStyle(content.firstElementChild).animationName
  1043. : "none",
  1044. });
  1045. };
  1046. sample();
  1047. toggle.click();
  1048. const start = performance.now();
  1049. let reversed = false;
  1050. await new Promise<void>((resolve) => {
  1051. const tick = (now: number) => {
  1052. sample();
  1053. if (reverse && !reversed && now - start >= 90) {
  1054. toggle.click();
  1055. reversed = true;
  1056. }
  1057. if (now - start < 600) requestAnimationFrame(tick);
  1058. else resolve();
  1059. };
  1060. requestAnimationFrame(tick);
  1061. });
  1062. return frames;
  1063. },
  1064. rowSelector,
  1065. reverse,
  1066. );
  1067. }
  1068. async function readNavigation() {
  1069. return browser.execute(() => {
  1070. const bridge = window as Window & {
  1071. __zcodeTabStoreE2E?: {
  1072. getState(): { activeWorkspacePath: string | null; activeWorkspaceIdentity?: string | null };
  1073. };
  1074. __zcodeSessionStoreE2E?: {
  1075. getState(): {
  1076. getWorkspaceState(
  1077. path: string,
  1078. identity?: string,
  1079. ): {
  1080. activeTaskId: string | null;
  1081. draftProjectId?: string | null;
  1082. draftFocusVersion: number;
  1083. };
  1084. };
  1085. };
  1086. };
  1087. const tabs = bridge.__zcodeTabStoreE2E?.getState();
  1088. const sessions = bridge.__zcodeSessionStoreE2E?.getState();
  1089. if (!tabs || !sessions || !tabs.activeWorkspacePath)
  1090. throw new Error("missing E2E navigation bridge");
  1091. const state = sessions.getWorkspaceState(
  1092. tabs.activeWorkspacePath,
  1093. tabs.activeWorkspaceIdentity ?? undefined,
  1094. );
  1095. return {
  1096. path: tabs.activeWorkspacePath,
  1097. identity: tabs.activeWorkspaceIdentity,
  1098. task: state.activeTaskId,
  1099. project: state.draftProjectId,
  1100. focus: state.draftFocusVersion,
  1101. };
  1102. });
  1103. }
  1104. async function closeActiveFileTab() {
  1105. const tab = $('[data-side-pane-tab-id][data-state="active"]');
  1106. const id = await tab.getAttribute("data-side-pane-tab-id");
  1107. await tab.$("button").click();
  1108. await $(`[data-side-pane-tab-id="${id}"]`).waitForExist({ reverse: true });
  1109. }
  1110. async function assertDropIndicator(project: string, edge: "before" | "after") {
  1111. await browser.execute(async () => {
  1112. await Promise.all(
  1113. [...document.querySelectorAll("[data-project-id]")]
  1114. .flatMap((node) => node.getAnimations({ subtree: true }))
  1115. .map((animation) => animation.finished.catch(() => {})),
  1116. );
  1117. });
  1118. await writeFile(
  1119. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "insertion-diagnostics.json"),
  1120. JSON.stringify(
  1121. await browser.execute(() => ({
  1122. width: innerWidth,
  1123. theme: document.documentElement.className,
  1124. focus: document.activeElement?.outerHTML,
  1125. nodes: [...document.querySelectorAll("[data-project-id]")].map((node) => ({
  1126. id: node.getAttribute("data-project-id"),
  1127. rect: node.getBoundingClientRect().toJSON(),
  1128. visible: node.checkVisibility(),
  1129. style: node.getAttribute("style"),
  1130. })),
  1131. indicator: document.querySelector('[data-testid="project-drop-indicator"]')?.outerHTML,
  1132. })),
  1133. null,
  1134. 2,
  1135. ),
  1136. );
  1137. await $(indicatorSelector).waitForDisplayed();
  1138. expect(await $$(indicatorSelector).length).toBe(1);
  1139. const appearance = await browser.execute((selector) => {
  1140. const line = document.querySelector(selector)!;
  1141. const node = line.closest("[data-project-id]")!;
  1142. const rect = line.getBoundingClientRect();
  1143. const target = node.getBoundingClientRect();
  1144. const circle = line.firstElementChild!;
  1145. return {
  1146. project: node.getAttribute("data-project-id"),
  1147. edge: line.getAttribute("data-drop-position"),
  1148. height: rect.height,
  1149. width: rect.width,
  1150. within: rect.left >= target.left && rect.right <= target.right,
  1151. edgeOffset: Math.min(
  1152. Math.abs(rect.top + rect.height / 2 - target.top),
  1153. Math.abs(rect.top + rect.height / 2 - target.bottom),
  1154. ),
  1155. color: getComputedStyle(line).backgroundColor,
  1156. circleColor: getComputedStyle(circle).borderTopColor,
  1157. circleSize: circle.getBoundingClientRect().width,
  1158. pointerEvents: getComputedStyle(line).pointerEvents,
  1159. hidden: line.getAttribute("aria-hidden"),
  1160. };
  1161. }, indicatorSelector);
  1162. expect(appearance.project).toBe(project);
  1163. expect(appearance.edge).toBe(edge);
  1164. expect(appearance.height).toBe(2);
  1165. expect(appearance.width).toBeGreaterThan(100);
  1166. expect(appearance.within).toBe(true);
  1167. expect(appearance.edgeOffset).toBeLessThanOrEqual(1);
  1168. expect(appearance.color).not.toBe("rgba(0, 0, 0, 0)");
  1169. expect(appearance.color).toBe(appearance.circleColor);
  1170. expect(appearance.circleSize).toBe(8);
  1171. expect(appearance.pointerEvents).toBe("none");
  1172. expect(appearance.hidden).toBe("true");
  1173. }
  1174. async function captureLayouts(
  1175. beforeCapture?: () => Promise<void>,
  1176. prefix?: string,
  1177. clearDrag = true,
  1178. ) {
  1179. const sidebarWasOpen = (await $("aside").getAttribute("aria-hidden")) === "false";
  1180. const original = await browser.execute(() => {
  1181. const actions = (window as Window & { __testActions?: { getTheme(): string } }).__testActions;
  1182. if (!actions) throw new Error("missing E2E theme bridge");
  1183. return actions.getTheme();
  1184. });
  1185. const setTheme = async (theme: string) => {
  1186. await browser.execute((value) => {
  1187. const actions = (window as Window & { __testActions?: { setTheme(value: string): void } })
  1188. .__testActions;
  1189. if (!actions) throw new Error("missing E2E theme bridge");
  1190. actions.setTheme(value);
  1191. }, theme);
  1192. await browser.waitUntil(() =>
  1193. browser.execute(
  1194. (value) => document.documentElement.classList.contains(`theme-${value}`),
  1195. theme,
  1196. ),
  1197. );
  1198. };
  1199. const emulate = (width?: number) =>
  1200. browser.electron.execute(async (electron, width) => {
  1201. const window = electron.BrowserWindow.getAllWindows().find(
  1202. (item) => !item.isDestroyed() && item.isVisible(),
  1203. );
  1204. if (!window) throw new Error("missing renderer");
  1205. if (!window.webContents.debugger.isAttached()) window.webContents.debugger.attach("1.3");
  1206. await window.webContents.debugger.sendCommand(
  1207. width ? "Emulation.setDeviceMetricsOverride" : "Emulation.clearDeviceMetricsOverride",
  1208. width ? { width, height: 844, deviceScaleFactor: 1, mobile: false } : {},
  1209. );
  1210. }, width);
  1211. try {
  1212. for (const width of [1200, 390]) {
  1213. await emulate(width);
  1214. await browser.waitUntil(() => browser.execute((value) => innerWidth === value, width));
  1215. if ((beforeCapture || prefix === "sidebar-recent") && width === 390) {
  1216. // 只有聊天视图会在 resize 后自动收起侧栏;商店/定时任务页没有这条策略。
  1217. // 聊天先等待真实收起结束,避免迟到的收起打断键盘拖拽。
  1218. const isChat = await $('[data-testid="v4-composer-input"]').isDisplayed();
  1219. if (isChat) {
  1220. await browser.waitUntil(
  1221. async () => (await $("aside").getAttribute("aria-hidden")) === "true",
  1222. );
  1223. }
  1224. // 用真实按钮展开已收起的侧栏,再验证窄屏布局。
  1225. if ((await $("aside").getAttribute("aria-hidden")) === "true") {
  1226. await $('button[aria-label="Toggle sidebar"], button[aria-label="切换侧边栏"]').click();
  1227. }
  1228. await browser.waitUntil(
  1229. async () => (await $("aside").getAttribute("aria-hidden")) === "false",
  1230. );
  1231. }
  1232. for (const theme of ["zai-light", "zai-dark"]) {
  1233. await setTheme(theme);
  1234. await beforeCapture?.();
  1235. const bounds = await browser.execute(() => {
  1236. const node = document.querySelector('[data-testid="sidebar"]');
  1237. if (!node) throw new Error("missing sidebar");
  1238. const rect = node.getBoundingClientRect();
  1239. return {
  1240. left: rect.left,
  1241. right: rect.right,
  1242. width: innerWidth,
  1243. overflow: node.scrollWidth - node.clientWidth,
  1244. };
  1245. });
  1246. expect(bounds.left).toBeGreaterThanOrEqual(0);
  1247. expect(bounds.right).toBeLessThanOrEqual(bounds.width);
  1248. expect(bounds.overflow).toBeLessThanOrEqual(1);
  1249. const toolbar = await browser.execute(() => {
  1250. const search = document.querySelector('[data-testid="sidebar-search-open"]')!;
  1251. const filter = document.querySelector('[data-testid="sidebar-view-menu"]')!;
  1252. const store = document.querySelector('[data-testid="plugin-store-sidebar-open"]')!;
  1253. const a = search.getBoundingClientRect(),
  1254. b = filter.getBoundingClientRect();
  1255. return {
  1256. height: a.height,
  1257. filterHeight: b.height,
  1258. radius: getComputedStyle(search).borderTopLeftRadius,
  1259. background: getComputedStyle(search).backgroundColor,
  1260. border: getComputedStyle(search).borderTopColor,
  1261. belowStore: a.top >= store.getBoundingClientRect().bottom,
  1262. inside: a.left >= 0 && b.right <= innerWidth,
  1263. };
  1264. });
  1265. expect(toolbar.height).toBe(24);
  1266. expect(toolbar.filterHeight).toBe(24);
  1267. expect(toolbar.background).toBe("rgba(0, 0, 0, 0)");
  1268. expect(toolbar.border).toBe("rgba(0, 0, 0, 0)");
  1269. expect(toolbar.belowStore).toBe(true);
  1270. expect(toolbar.inside).toBe(true);
  1271. await browser.saveScreenshot(
  1272. join(
  1273. process.env.ZCODE_E2E_ARTIFACT_DIR!,
  1274. `${prefix ?? (beforeCapture ? "project-insertion" : "project-behavior")}-${width}-${theme}.png`,
  1275. ),
  1276. );
  1277. // 留白验证没有拖拽;额外 Escape 会收起侧栏并污染下一组布局。
  1278. if (beforeCapture && clearDrag) {
  1279. await browser.keys("Escape");
  1280. await browser.releaseActions();
  1281. expect(await $(indicatorSelector).isExisting()).toBe(false);
  1282. }
  1283. }
  1284. }
  1285. } finally {
  1286. // 循环已取消拖拽;多余 Escape 会关闭手机侧栏,导致后续合法元素不可交互。
  1287. if (beforeCapture && clearDrag && (await $(indicatorSelector).isExisting())) {
  1288. await browser.keys("Escape");
  1289. await browser.releaseActions();
  1290. }
  1291. await emulate();
  1292. await setTheme(original);
  1293. if (sidebarWasOpen && (await $("aside").getAttribute("aria-hidden")) === "true") {
  1294. await $('button[aria-label="Toggle sidebar"], button[aria-label="切换侧边栏"]').click();
  1295. await browser.waitUntil(
  1296. async () => (await $("aside").getAttribute("aria-hidden")) === "false",
  1297. );
  1298. }
  1299. }
  1300. }
  1301. async function invokeNewTaskMenuShortcut() {
  1302. const url = await browser.getUrl();
  1303. await browser.electron.execute((electron, targetUrl) => {
  1304. const window = electron.BrowserWindow.getAllWindows().find(
  1305. (item) => item.webContents.getURL() === targetUrl,
  1306. );
  1307. if (!window) throw new Error("missing E2E shortcut target");
  1308. window.focus();
  1309. const item = electron.Menu.getApplicationMenu()
  1310. ?.items.flatMap((menu) => menu.submenu?.items ?? [])
  1311. .find((menu) => menu.accelerator === "CmdOrCtrl+N");
  1312. if (!item) throw new Error("missing native new task accelerator");
  1313. // WebDriver 的 DOM 按键不经过原生菜单;验证真实菜单绑定并执行其现有命令入口。
  1314. item.click(undefined as never, window, undefined as never);
  1315. }, url);
  1316. }
  1317. async function refreshProjectSidebar(expectedSelector = '[data-testid="project-section"]') {
  1318. await browser.refresh();
  1319. // API key 夹具的 renderer 登录态可能随刷新清空;先恢复登录,再验证原项目与排序。
  1320. const login = $('[data-testid="login-use-api-key-button"]');
  1321. // 时间线视图不渲染项目分区;等待调用方原视图,不能把正确恢复误判成加载失败。
  1322. const projects = $(expectedSelector);
  1323. await browser.waitUntil(
  1324. async () => (await login.isDisplayed()) || (await projects.isDisplayed()),
  1325. {
  1326. timeout: 45_000,
  1327. },
  1328. );
  1329. if (await login.isDisplayed()) await loginWithApiKey();
  1330. await projects.waitForDisplayed({ timeout: 30_000 });
  1331. }