conversation-session-task-groups.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. import { writeFile } from "node:fs/promises";
  2. import { startProjectPointerDrag } from "#e2e/helpers/project-sidebar";
  3. import { join } from "node:path";
  4. import { isIsolatedE2EHomeDir } from "#e2e/helpers/e2e-runtime-paths";
  5. import { DatabaseSync } from "node:sqlite";
  6. import {
  7. loginWithApiKey,
  8. prepareV4ConversationE2E,
  9. sendV4Prompt,
  10. waitForV4AssistantMessageContaining,
  11. getV4PaneSnapshot,
  12. setV4ComposerText,
  13. waitForV4ComposerText,
  14. } from "#e2e/helpers/v4-conversation";
  15. import { installHandoffRpcProbe, callHandoffHost } from "#e2e/helpers/remote-project-handoff-probe";
  16. import { ServiceChannels, ZCODE_AGENT_PROVIDER } from "@zcode/shared";
  17. import { TID_TASK_ITEM, testId } from "@zcode/shared/test-ids";
  18. declare global {
  19. interface Window {
  20. __groupPlacementBarrier?: { held: number; release(): void; restore(): void };
  21. }
  22. }
  23. async function reloadGroupWorkspace() {
  24. await browser.refresh();
  25. const login = $('[data-testid="login-use-api-key-button"]');
  26. await browser.waitUntil(
  27. async () =>
  28. (await login.isDisplayed()) || (await $('[data-testid="sidebar-view-menu"]').isDisplayed()),
  29. { timeout: 45_000 },
  30. );
  31. if (await login.isDisplayed()) await loginWithApiKey();
  32. await $('[data-testid="sidebar-view-menu"]').waitForDisplayed({ timeout: 30_000 });
  33. }
  34. async function waitForGroupedLayout() {
  35. // 颜色菜单在 Portal 中退场;只等列表动画会让指针按在尚未卸载的菜单上。
  36. await $('[data-testid="task-group-color-gray"]').waitForExist({ reverse: true });
  37. await browser.waitUntil(() =>
  38. browser.execute(
  39. () =>
  40. !document
  41. .querySelector('[data-testid="task-grouped-view"]')
  42. ?.getAnimations({ subtree: true })
  43. .some(
  44. (animation) =>
  45. animation.playState === "running" &&
  46. animation.effect?.getComputedTiming().endTime !== Infinity,
  47. ),
  48. ),
  49. );
  50. }
  51. async function fillGroupTitle(value: string) {
  52. const input = $('[data-testid="task-group-title-input"]');
  53. await input.waitForDisplayed();
  54. await input.click();
  55. // WebDriver clear 会先 blur 并提交内联编辑;模拟真实用户全选输入。
  56. await browser.keys([process.platform === "darwin" ? "Meta" : "Control", "a"]);
  57. await input.addValue(value);
  58. }
  59. describe("任务分组独立视图", () => {
  60. afterEach(async function () {
  61. if (this.currentTest?.state === "failed") {
  62. const failureName = `task-groups-failure-${this.currentTest?.title.split(":")[0]?.replaceAll("/", "_")}`;
  63. await browser.saveScreenshot(join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `${failureName}.png`));
  64. const layout = await browser.execute(() => {
  65. const root = document.querySelector('[data-testid="task-grouped-view"]');
  66. const viewport = root?.closest("[data-scroll-mask]");
  67. const groups = [...document.querySelectorAll("[data-grouped-group-item-id]")].map(
  68. (group) => ({
  69. id: group.getAttribute("data-grouped-group-item-id"),
  70. collapsed: group.getAttribute("data-group-collapsed"),
  71. rect: group.getBoundingClientRect().toJSON(),
  72. header: group
  73. .querySelector("[data-grouped-group-header-id]")
  74. ?.getBoundingClientRect()
  75. .toJSON(),
  76. }),
  77. );
  78. return {
  79. root: root?.getBoundingClientRect().toJSON(),
  80. viewport: viewport?.getBoundingClientRect().toJSON(),
  81. scrollTop: viewport?.scrollTop,
  82. scrollHeight: viewport?.scrollHeight,
  83. groups,
  84. bodyCursor: document.body.style.cursor,
  85. sticky: document.querySelector("[data-grouped-sticky-header]")?.outerHTML,
  86. };
  87. });
  88. await writeFile(
  89. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `${failureName}.json`),
  90. JSON.stringify(layout, null, 2),
  91. );
  92. process.stderr.write(
  93. `GRP failure UI: ${await browser.execute(() => document.body.innerText.slice(0, 3500))}\n`,
  94. );
  95. }
  96. });
  97. before(async () => {
  98. await prepareV4ConversationE2E();
  99. await installHandoffRpcProbe();
  100. });
  101. it("GRP02:旧分组偏好迁移,新选择在重载后优先", async function () {
  102. this.timeout(60_000);
  103. await browser.execute(() => {
  104. localStorage.removeItem("zcode-project-sidebar-preferences");
  105. localStorage.setItem(
  106. "zcode-sidebar-task-preferences",
  107. JSON.stringify({ organizeBy: "grouped", sortBy: "updated" }),
  108. );
  109. });
  110. await reloadGroupWorkspace();
  111. await $('[data-testid="task-group-add"]').waitForDisplayed({ timeout: 30_000 });
  112. await $('[data-testid="sidebar-view-menu"]').click();
  113. expect(await $('[data-testid="sidebar-view-grouped"]').getAttribute("data-state")).toBe(
  114. "checked",
  115. );
  116. // 恢复必须沿用旧 Hash 入口;不是重新画一套分组控件。
  117. expect(await $('[data-testid="sidebar-view-grouped"] svg.lucide-hash').isExisting()).toBe(true);
  118. await $('[data-testid="sidebar-view-timeline"]').click();
  119. await reloadGroupWorkspace();
  120. await $('[data-testid="sidebar-view-menu"]').waitForClickable();
  121. await $('[data-testid="sidebar-view-menu"]').click();
  122. expect(await $('[data-testid="sidebar-view-timeline"]').getAttribute("data-state")).toBe(
  123. "checked",
  124. );
  125. await browser.keys("Escape");
  126. await $('[data-testid="sidebar-view-timeline"]').waitForExist({ reverse: true });
  127. await installHandoffRpcProbe();
  128. });
  129. it("GRP02/03/11:三视图、创建改色改名、重载与取消空组", async function () {
  130. this.timeout(90_000);
  131. await $('[data-testid="sidebar-view-menu"]').click();
  132. for (const view of ["projects", "grouped", "timeline"])
  133. await $(`[data-testid="sidebar-view-${view}"]`).waitForDisplayed();
  134. await $('[data-testid="sidebar-view-grouped"]').click();
  135. await $('[data-testid="task-group-add"]').waitForClickable();
  136. await $('[data-testid="task-group-add"]').click();
  137. const input = $('[data-testid="task-group-title-input"]');
  138. await input.waitForDisplayed();
  139. await fillGroupTitle("E2E_GROUP");
  140. await browser.keys("Enter");
  141. const row = $('[data-task-group-title="E2E_GROUP"]');
  142. await row.waitForDisplayed();
  143. await $('[data-testid="task-group-color-blue"]').click();
  144. const before = await callHandoffHost<{
  145. groups: Array<{ id: string; title: string; color: string }>;
  146. }>(ServiceChannels.TaskGroups, "read");
  147. const group = before.groups.find((group) => group.title === "E2E_GROUP");
  148. expect(group?.color).toBe("blue");
  149. await reloadGroupWorkspace();
  150. await row.waitForDisplayed();
  151. await installHandoffRpcProbe();
  152. await row.$('[data-testid="task-group-menu"]').click({ button: "right" });
  153. await $('[data-testid="task-group-rename"]').click();
  154. await fillGroupTitle("E2E_RENAMED");
  155. await browser.keys("Enter");
  156. const renamed = $('[data-task-group-title="E2E_RENAMED"]');
  157. await renamed.waitForDisplayed();
  158. // GRP11:旧版颜色圆标、标题折叠、可点击空态、草稿关闭,不能退回新画的拖拽把手。
  159. expect(await renamed.$("svg.lucide-hash").isExisting()).toBe(true);
  160. expect(await $$('[data-testid="task-group-drag-handle"]')).toHaveLength(0);
  161. await renamed.$("[data-grouped-group-header-id]").click();
  162. expect(await renamed.getAttribute("data-group-collapsed")).toBe("true");
  163. await renamed.$("[data-grouped-group-header-id]").click();
  164. await renamed.$("[data-grouped-empty-drop-zone-id]").click();
  165. const draft = renamed.$('[data-testid="grouped-draft-task"]');
  166. await draft.waitForDisplayed();
  167. await setV4ComposerText("PD12_GROUP_DRAFT_KEEP");
  168. await draft.moveTo();
  169. await draft.$("button").click();
  170. await draft.waitForExist({ reverse: true });
  171. await renamed.$("[data-grouped-empty-drop-zone-id]").waitForDisplayed();
  172. // 关闭分组行只撤销组织意图;刷新仍保留正文,不能从旧目录 key 复活分组行。
  173. await reloadGroupWorkspace();
  174. await installHandoffRpcProbe();
  175. await waitForV4ComposerText("PD12_GROUP_DRAFT_KEEP", "关闭分组草稿丢失正文");
  176. expect(await renamed.$('[data-testid="grouped-draft-task"]').isExisting()).toBe(false);
  177. await setV4ComposerText("");
  178. for (const [theme, locale] of [
  179. ["zai-light", "zh-CN"],
  180. ["zai-dark", "en-US"],
  181. ]) {
  182. await browser.execute(
  183. ([theme, locale]) => {
  184. const actions = (
  185. window as Window & {
  186. __testActions?: { setTheme(value: string): void; setLocale(value: string): void };
  187. }
  188. ).__testActions!;
  189. actions.setTheme(theme!);
  190. actions.setLocale(locale!);
  191. },
  192. [theme, locale],
  193. );
  194. await browser.waitUntil(() =>
  195. browser.execute(
  196. (value) => document.documentElement.classList.contains(`theme-${value}`),
  197. theme,
  198. ),
  199. );
  200. await browser.waitUntil(
  201. async () =>
  202. (await $('[data-testid="task-group-add"]').getAttribute("aria-label")) ===
  203. (locale === "zh-CN" ? "新建分组" : "New group"),
  204. );
  205. await browser.saveScreenshot(
  206. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `task-groups-${theme}.png`),
  207. );
  208. }
  209. await renamed.$('[data-testid="task-group-menu"]').click({ button: "right" });
  210. await $('[data-testid="task-group-ungroup"]').click();
  211. await renamed.waitForExist({ reverse: true });
  212. const after = await callHandoffHost<{ groups: Array<{ id: string }> }>(
  213. ServiceChannels.TaskGroups,
  214. "read",
  215. );
  216. expect(after.groups.some((item) => item.id === group!.id)).toBe(false);
  217. });
  218. it("GRP04/05/06:组内首发、三视图菜单、置顶/归档和恢复保持成员", async function () {
  219. this.timeout(180_000);
  220. await $('[data-testid="task-group-add"]').click();
  221. await fillGroupTitle("E2E_GROUP_MEMBERS");
  222. await browser.keys("Enter");
  223. await browser.keys("Escape");
  224. const groupRow = $('[data-task-group-title="E2E_GROUP_MEMBERS"]');
  225. await groupRow.waitForDisplayed();
  226. const groupId = await groupRow.getAttribute("data-task-group-id");
  227. await groupRow.$('[data-testid="task-group-new-task"]').click();
  228. await sendV4Prompt("E2E_GROUP_TASK 请回复 E2E_GROUP_READY。");
  229. await waitForV4AssistantMessageContaining("E2E_GROUP_READY");
  230. await groupRow.$('[data-testid="grouped-draft-task"]').waitForExist({ reverse: true });
  231. const taskId = (await getV4PaneSnapshot()).sessionId!;
  232. const read = () =>
  233. callHandoffHost<{
  234. members: Array<{ groupId: string; taskId: string; workspaceKey: string }>;
  235. }>(ServiceChannels.TaskGroups, "read");
  236. await browser.waitUntil(async () =>
  237. (await read()).members.some((m) => m.taskId === taskId && m.groupId === groupId),
  238. );
  239. const tree = await callHandoffHost<{
  240. tasks: Array<{ taskId: string; workspacePath: string; projectId: string | null }>;
  241. }>(ServiceChannels.Project, "readTree");
  242. const task = tree.tasks.find((t) => t.taskId === taskId)!;
  243. expect(task.projectId).toBeNull();
  244. const target = { taskId, workspacePath: task.workspacePath };
  245. const selector = `[data-testid="${testId(TID_TASK_ITEM, taskId)}"]`;
  246. for (const view of ["projects", "timeline", "grouped"]) {
  247. await $('[data-testid="sidebar-view-menu"]').click();
  248. await $(`[data-testid="sidebar-view-${view}"]`).click();
  249. await $(selector).waitForDisplayed();
  250. await $(selector).click({ button: "right" });
  251. await $('[data-testid="task-group-move-menu"]').waitForDisplayed();
  252. await browser.keys("Escape");
  253. await $('[data-testid="task-group-move-menu"]').waitForExist({ reverse: true });
  254. }
  255. await callHandoffHost(ServiceChannels.ZCodeTask, "setTaskPinned", [
  256. { ...target, pinned: true },
  257. ]);
  258. await browser.execute(() => window.dispatchEvent(new Event("focus")));
  259. await $('[data-testid="project-pinned-tasks"]').$(selector).waitForDisplayed();
  260. expect(await $$(`[data-testid="task-grouped-view"] ${selector}`)).toHaveLength(0);
  261. await callHandoffHost(ServiceChannels.ZCodeTask, "setTaskPinned", [
  262. { ...target, pinned: false },
  263. ]);
  264. await callHandoffHost(ServiceChannels.ZCodeTask, "archiveTask", [target]);
  265. await browser.execute(() => window.dispatchEvent(new Event("focus")));
  266. await $(selector).waitForExist({ reverse: true });
  267. expect((await read()).members.some((m) => m.taskId === taskId && m.groupId === groupId)).toBe(
  268. true,
  269. );
  270. await callHandoffHost(ServiceChannels.ZCodeTask, "unarchiveTask", [target]);
  271. await browser.execute(() => window.dispatchEvent(new Event("focus")));
  272. await $(selector).waitForDisplayed();
  273. await $('[data-testid="task-group-add"]').click();
  274. await fillGroupTitle("E2E_DROP_TARGET");
  275. await browser.keys("Enter");
  276. await browser.keys("Escape");
  277. const dropTarget = $('[data-task-group-title="E2E_DROP_TARGET"]');
  278. await dropTarget.waitForDisplayed();
  279. const targetGroupId = await dropTarget.getAttribute("data-task-group-id");
  280. await waitForGroupedLayout();
  281. await startProjectPointerDrag(selector);
  282. const dropPoint = await browser.execute(() => {
  283. const rect = document
  284. .querySelector(
  285. '[data-task-group-title="E2E_DROP_TARGET"] [data-grouped-empty-drop-zone-id]',
  286. )!
  287. .getBoundingClientRect();
  288. return {
  289. x: Math.round(rect.left + rect.width / 2),
  290. y: Math.round(rect.top + rect.height / 2),
  291. };
  292. });
  293. await browser.performActions([
  294. {
  295. type: "pointer",
  296. id: "project-drag",
  297. parameters: { pointerType: "mouse" },
  298. actions: [{ type: "pointerMove", ...dropPoint, duration: 200 }],
  299. },
  300. ]);
  301. await browser.waitUntil(async () => await dropTarget.$(selector).isExisting());
  302. await browser.performActions([
  303. {
  304. type: "pointer",
  305. id: "project-drag",
  306. parameters: { pointerType: "mouse" },
  307. actions: [{ type: "pointerUp", button: 0 }],
  308. },
  309. ]);
  310. await browser.releaseActions();
  311. await browser.waitUntil(async () =>
  312. (await read()).members.some((m) => m.taskId === taskId && m.groupId === targetGroupId),
  313. );
  314. await waitForGroupedLayout();
  315. await $(selector).click({ button: "right" });
  316. await $('[data-testid="task-group-move-menu"]').waitForDisplayed();
  317. await $('[data-testid="task-group-move-menu"]').moveTo();
  318. await $('[data-testid="task-group-remove"]').waitForDisplayed();
  319. await $('[data-testid="task-group-remove"]').click();
  320. await browser.waitUntil(async () => !(await read()).members.some((m) => m.taskId === taskId));
  321. expect(
  322. (
  323. await callHandoffHost<{
  324. tasks: Array<{ taskId: string; workspacePath: string; projectId: string | null }>;
  325. }>(ServiceChannels.Project, "readTree")
  326. ).tasks.find((t) => t.taskId === taskId),
  327. ).toMatchObject({ taskId, workspacePath: task.workspacePath, projectId: task.projectId });
  328. });
  329. it("GRP06/CR-01:组织登记挂起时取消首发仍可刷新目录,释放后只入组一次", async function () {
  330. this.timeout(90_000);
  331. await $('[data-testid="sidebar-view-menu"]').click();
  332. await $('[data-testid="sidebar-view-grouped"]').click();
  333. await $('[data-testid="task-group-add"]').click();
  334. await fillGroupTitle("E2E_GROUP_PENDING");
  335. await browser.keys("Enter");
  336. await browser.keys("Escape");
  337. const row = $('[data-task-group-title="E2E_GROUP_PENDING"]');
  338. await row.waitForDisplayed();
  339. const groupId = await row.getAttribute("data-task-group-id");
  340. if (!groupId) throw new Error("CR-01: group identity unavailable");
  341. const readTree = () =>
  342. callHandoffHost<{ tasks: Array<{ taskId: string }> }>(ServiceChannels.Project, "readTree");
  343. const before = new Set((await readTree()).tasks.map((task) => task.taskId));
  344. // 挂住真实 UI 的 placement RPC,普通目录、分组读取和无 placement 登记继续通行。
  345. // 只控制故障边界,不替换创建 ACK、权威目录或分组服务。
  346. await browser.execute((groupId) => {
  347. const original = MessagePort.prototype.postMessage;
  348. const held: Array<{ port: MessagePort; args: unknown[] }> = [];
  349. const probe = {
  350. held: 0,
  351. release() {
  352. for (const { port, args } of held.splice(0)) Reflect.apply(original, port, args);
  353. },
  354. restore() {
  355. this.release();
  356. MessagePort.prototype.postMessage = original;
  357. delete window.__groupPlacementBarrier;
  358. },
  359. };
  360. MessagePort.prototype.postMessage = function (message: unknown, options?: unknown) {
  361. const text = message instanceof Uint8Array ? new TextDecoder().decode(message) : "";
  362. const args = options === undefined ? [message] : [message, options];
  363. if (
  364. text.includes("task-groups") &&
  365. text.includes("admit") &&
  366. text.includes("placement") &&
  367. text.includes(groupId)
  368. ) {
  369. held.push({ port: this, args });
  370. probe.held++;
  371. return;
  372. }
  373. Reflect.apply(original, this, args);
  374. };
  375. window.__groupPlacementBarrier = probe;
  376. }, groupId);
  377. try {
  378. await row.$('[data-testid="task-group-new-task"]').click();
  379. await sendV4Prompt("E2E_GROUP_PENDING 请回复 E2E_GROUP_PENDING_READY。");
  380. await browser.waitUntil(() =>
  381. browser.execute(() => window.__groupPlacementBarrier?.held === 1),
  382. );
  383. const created = (await readTree()).tasks.filter((task) => !before.has(task.taskId));
  384. expect(created).toHaveLength(1);
  385. const taskId = created[0]!.taskId;
  386. // 在组织请求未返回时离开首发 pane;新的目录事实必须仍可进入共享列表。
  387. await row.$('[data-testid="task-group-new-task"]').click();
  388. await callHandoffHost(ServiceChannels.Project, "saveProject", [
  389. { name: "E2E_CR01_REFRESH", roots: [] },
  390. ]);
  391. await $('[data-testid="sidebar-view-menu"]').click();
  392. await $('[data-testid="sidebar-view-projects"]').click();
  393. await $('[data-project-name="E2E_CR01_REFRESH"]').waitForDisplayed({ timeout: 10_000 });
  394. expect((await getV4PaneSnapshot()).sessionId).toBe("draft");
  395. expect(await browser.execute(() => window.__groupPlacementBarrier?.held)).toBe(1);
  396. await browser.execute(() => window.__groupPlacementBarrier?.release());
  397. await browser.waitUntil(async () => {
  398. const groups = await callHandoffHost<{
  399. members: Array<{ taskId: string; groupId: string }>;
  400. }>(ServiceChannels.TaskGroups, "read");
  401. return (
  402. groups.members.filter((member) => member.taskId === taskId && member.groupId === groupId)
  403. .length === 1
  404. );
  405. });
  406. expect((await getV4PaneSnapshot()).sessionId).toBe("draft");
  407. expect((await readTree()).tasks.filter((task) => !before.has(task.taskId))).toHaveLength(1);
  408. process.stderr.write(
  409. "CR-01: held placement, navigation cancellation, directory refresh and late group admission passed\n",
  410. );
  411. } finally {
  412. await browser.execute(() => window.__groupPlacementBarrier?.restore());
  413. }
  414. });
  415. it("GRP11:整组拖拽取消恢复展开,释放只调整顶层顺序", async function () {
  416. this.timeout(45_000);
  417. await $('[data-testid="sidebar-view-menu"]').click();
  418. await $('[data-testid="sidebar-view-grouped"]').click();
  419. // 失败原因:视图菜单是 modal DropdownMenu,选中后在 Portal 里还有约 100ms 的退场动画,
  420. // 期间 Radix 给 body 设 pointer-events:none。日志里选中菜单项到 pointerDown 只隔 68ms
  421. // (wdio.log 27.959 → 28.027),按下事件落在不可交互的页面上,dnd-kit 没有激活,
  422. // aria-pressed 一直是 null。等菜单项卸载(可观察结果)后再开始拖拽。
  423. await $('[data-testid="sidebar-view-grouped"]').waitForExist({ reverse: true });
  424. await installHandoffRpcProbe();
  425. const first = await callHandoffHost<{ id: string }>(ServiceChannels.TaskGroups, "save", [
  426. { title: "E2E_ORDER_A" },
  427. ]);
  428. const second = await callHandoffHost<{ id: string }>(ServiceChannels.TaskGroups, "save", [
  429. { title: "E2E_ORDER_B" },
  430. ]);
  431. const readOrder = async () =>
  432. (await callHandoffHost<{ order: unknown[] }>(ServiceChannels.TaskGroups, "read")).order;
  433. const original = await readOrder();
  434. const source = `[data-grouped-group-header-id="${first.id}"]`;
  435. const target = `[data-grouped-group-header-id="${second.id}"]`;
  436. await $(source).waitForDisplayed();
  437. const start = async () => {
  438. await waitForGroupedLayout();
  439. const point = await browser.execute((selector) => {
  440. const rect = document.querySelector(selector)!.getBoundingClientRect();
  441. return { x: Math.round(rect.left + 80), y: Math.round(rect.top + rect.height / 2) };
  442. }, source);
  443. await browser.performActions([
  444. {
  445. type: "pointer",
  446. id: "group-drag",
  447. parameters: { pointerType: "mouse" },
  448. actions: [
  449. { type: "pointerMove", ...point, duration: 0 },
  450. { type: "pointerDown", button: 0 },
  451. { type: "pointerMove", x: point.x, y: point.y + 8, duration: 0 },
  452. ],
  453. },
  454. ]);
  455. await browser.waitUntil(
  456. async () => (await $(source).getAttribute("aria-pressed")) === "true",
  457. );
  458. const over = await browser.execute((selector) => {
  459. const rect = document.querySelector(selector)!.getBoundingClientRect();
  460. return { x: Math.round(rect.left + 80), y: Math.round(rect.top + rect.height / 2) };
  461. }, target);
  462. await browser.performActions([
  463. {
  464. type: "pointer",
  465. id: "group-drag",
  466. parameters: { pointerType: "mouse" },
  467. actions: [{ type: "pointerMove", ...over, duration: 250 }],
  468. },
  469. ]);
  470. expect(await $(source).getAttribute("aria-expanded")).toBe("false");
  471. };
  472. await start();
  473. await browser.keys("Escape");
  474. await browser.releaseActions();
  475. await browser.waitUntil(async () => (await $(source).getAttribute("aria-expanded")) === "true");
  476. expect(await readOrder()).toEqual(original);
  477. await start();
  478. await browser.performActions([
  479. {
  480. type: "pointer",
  481. id: "group-drag",
  482. parameters: { pointerType: "mouse" },
  483. actions: [{ type: "pointerUp", button: 0 }],
  484. },
  485. ]);
  486. await browser.releaseActions();
  487. await browser.waitUntil(
  488. async () => JSON.stringify(await readOrder()) !== JSON.stringify(original),
  489. );
  490. expect(await $(source).getAttribute("aria-expanded")).toBe("true");
  491. });
  492. it("GRP10:千行分组虚拟滚动、吸顶和折叠重载", async function () {
  493. this.timeout(90_000);
  494. await installHandoffRpcProbe();
  495. const group = await callHandoffHost<{ id: string }>(ServiceChannels.TaskGroups, "save", [
  496. { title: "E2E_LARGE_GROUP" },
  497. ]);
  498. const tree = await callHandoffHost<{ tasks: Array<{ workspacePath: string }> }>(
  499. ServiceChannels.Project,
  500. "readTree",
  501. );
  502. const cwd = tree.tasks[0]?.workspacePath;
  503. const home = process.env.ZCODE_E2E_HOME_DIR;
  504. // 批量 runner 的 HOME 可能是 .e2e-home、带 runId 或显式根下的 shard 目录;仍只允许写入隔离 E2E HOME。
  505. if (!isIsolatedE2EHomeDir(home) || !cwd) throw new Error("隔离 HOME 和真实任务目录 required");
  506. const db = new DatabaseSync(join(home, ".zcode/v2/tasks-index.sqlite"));
  507. try {
  508. db.exec("BEGIN IMMEDIATE");
  509. const task = db.prepare(
  510. `INSERT INTO tasks(workspace_key,workspace_path,task_id,title,created_at,updated_at,host_id,root_path,cli_title,cli_title_source,cli_created_at,cli_updated_at,cli_last_outcome,cli_deleted,handoff_pending,provider) VALUES(?,?,?,?,?,?,'local',?,?,'custom',?,?,'completed',0,8,?)`,
  511. );
  512. const member = db.prepare(
  513. `INSERT INTO task_group_members(group_id,workspace_key,workspace_path,task_id,sort_order,added_at,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?)`,
  514. );
  515. const now = Date.now();
  516. for (let i = 0; i < 1000; i++) {
  517. const id = `E2E_LARGE_${i}`;
  518. // 项目树现在只展示当前执行后端;列表夹具必须声明与真实任务一致的 provider。
  519. task.run(
  520. cwd,
  521. cwd,
  522. id,
  523. id,
  524. now + i,
  525. now + i,
  526. cwd,
  527. id,
  528. now + i,
  529. now + i,
  530. ZCODE_AGENT_PROVIDER,
  531. );
  532. member.run(group.id, cwd, cwd, id, i, now, now, now);
  533. }
  534. db.exec("COMMIT");
  535. } finally {
  536. db.close();
  537. }
  538. await reloadGroupWorkspace();
  539. await $('[data-testid="sidebar-view-menu"]').click();
  540. await $('[data-testid="sidebar-view-grouped"]').click();
  541. await $('[data-task-group-title="E2E_LARGE_GROUP"]').waitForDisplayed();
  542. await browser.waitUntil(() =>
  543. browser.execute(
  544. () =>
  545. document.querySelectorAll('[data-testid="task-grouped-view"] [data-task-item-key]')
  546. .length > 5,
  547. ),
  548. );
  549. const scroll = async (bottom: boolean) =>
  550. browser.execute((bottom) => {
  551. const list = document.querySelector('[data-testid="task-grouped-view"]')!;
  552. const viewport = list.closest("[data-scroll-mask]")!;
  553. viewport.scrollTop = bottom ? viewport.scrollHeight : 0;
  554. viewport.dispatchEvent(new Event("scroll"));
  555. }, bottom);
  556. await scroll(true);
  557. await $(`[data-testid="${testId(TID_TASK_ITEM, "E2E_LARGE_999")}"]`).waitForDisplayed();
  558. expect(
  559. (await $('[data-testid="task-grouped-view"]').$$("[data-task-item-key]")).length,
  560. ).toBeLessThan(80);
  561. // 大组后还有其他组;滚动到底并不代表仍在大组内,必须核对该组中段的吸顶身份。
  562. await browser.execute(() => {
  563. const group = document.querySelector('[data-task-group-title="E2E_LARGE_GROUP"]')!;
  564. const viewport = group.closest("[data-scroll-mask]")!;
  565. viewport.scrollTop +=
  566. group.getBoundingClientRect().top - viewport.getBoundingClientRect().top + 1000;
  567. });
  568. await $(`[data-grouped-sticky-header="${group.id}"]`).waitForDisplayed();
  569. const geometry = await browser.execute(() => {
  570. const header = document.querySelector("[data-grouped-sticky-header]")!;
  571. const viewport = document
  572. .querySelector('[data-testid="task-grouped-view"]')!
  573. .closest("[data-scroll-mask]")!;
  574. return {
  575. header: header.getBoundingClientRect().top,
  576. top: viewport.getBoundingClientRect().top,
  577. };
  578. });
  579. expect(Math.abs(geometry.header - geometry.top)).toBeLessThan(40);
  580. await browser.saveScreenshot(
  581. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "task-groups-long-list.png"),
  582. );
  583. await scroll(false);
  584. const header = $('[data-task-group-title="E2E_LARGE_GROUP"]');
  585. await header.$("[data-grouped-group-header-id]").click();
  586. await $(`[data-testid="${testId(TID_TASK_ITEM, "E2E_LARGE_0")}"]`).waitForExist({
  587. reverse: true,
  588. });
  589. await reloadGroupWorkspace();
  590. expect(await header.$("[data-grouped-group-header-id]").getAttribute("aria-expanded")).toBe(
  591. "false",
  592. );
  593. await header.$("[data-grouped-group-header-id]").click();
  594. await $(`[data-testid="${testId(TID_TASK_ITEM, "E2E_LARGE_0")}"]`).waitForDisplayed();
  595. });
  596. });