conversation-session-subagent-side-tabs.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. import {
  2. TID_CHAT_SUMMARY_PANEL,
  3. TID_V4_PANE_SHELL,
  4. TID_V4_SUBAGENT_OPEN_SIDE_PANE,
  5. } from "@zcode/shared/test-ids";
  6. import { releaseControlledReplay } from "#e2e/helpers/controlled-replay";
  7. import { ensureReadonlyToolFixtureFile } from "#e2e/helpers/conversation-session-readonly-tool";
  8. import { clearAppData } from "#e2e/helpers/desktop-app";
  9. import {
  10. prepareV4ConversationE2E,
  11. sendV4Prompt,
  12. waitForV4AssistantMessageContaining,
  13. waitForV4ComposerText,
  14. } from "#e2e/helpers/v4-conversation";
  15. import { ensureToolCrossProductFullAccessMode } from "#e2e/helpers/conversation-session-tool-cross-product";
  16. const PARENT_MARKER = "E2E_SUBAGENT_SIDE_TABS_PARENT";
  17. const PARENT_DONE = "E2E_SUBAGENT_SIDE_TABS_PARENT_DONE";
  18. const CHILD_COUNT = 6;
  19. const BACKGROUND_PARENT_MARKER = "E2E_RUNNING_SUBAGENT_SIDE_TAB_PARENT";
  20. const BACKGROUND_LAUNCHED = "E2E_RUNNING_SUBAGENT_SIDE_TAB_LAUNCHED";
  21. const BACKGROUND_PARENT_DONE = "E2E_RUNNING_SUBAGENT_SIDE_TAB_PARENT_DONE";
  22. describe("子智能体右侧 tabs manual review", () => {
  23. after(async () => {
  24. await browser.electron.restoreAllMocks();
  25. await clearAppData();
  26. });
  27. it("SAT12: Running subagent 摘要行复用 child 右侧 tab", async function () {
  28. this.timeout(240000);
  29. await prepareV4ConversationE2E();
  30. await ensureToolCrossProductFullAccessMode();
  31. await ensureReadonlyToolFixtureFile();
  32. const prompt = [
  33. `${BACKGROUND_PARENT_MARKER}: launch exactly one Agent with run_in_background true.`,
  34. `The child must read the readonly fixture and reply with exactly E2E_SIDE_TAB_BACKGROUND_CHILD_DONE.`,
  35. `After the background launch tool returns, reply with exactly ${BACKGROUND_LAUNCHED} without waiting.`,
  36. `After its task notification arrives, reply with exactly ${BACKGROUND_PARENT_DONE}.`,
  37. ].join(" ");
  38. await sendV4Prompt(prompt);
  39. await waitForV4ComposerText("", "Running subagent side-tab 首发后输入框没有清空");
  40. await waitForV4AssistantMessageContaining(`${BACKGROUND_LAUNCHED}`);
  41. await waitForRunningSubagentTrigger(90000);
  42. await clickRunningSubagentTrigger();
  43. await waitForVisibleSubagentTabCount(1, 30000);
  44. await clickRunningSubagentTrigger();
  45. expect(await countVisibleSubagentTabs()).toBe(1);
  46. // 先观察运行中 tab 的去重,再释放上游流,避免依赖固定 sleep 的抢时序。
  47. await releaseControlledReplay("side-tab-child-background");
  48. await waitForV4AssistantMessageContaining(BACKGROUND_PARENT_DONE);
  49. });
  50. it("SAT01-SAT03: 6 个 running child 使用右侧 tabs 且打开后持续更新", async function () {
  51. this.timeout(240000);
  52. await prepareV4ConversationE2E();
  53. await ensureToolCrossProductFullAccessMode();
  54. await ensureReadonlyToolFixtureFile();
  55. const prompt = [
  56. `${PARENT_MARKER}: In one assistant turn launch exactly ${CHILD_COUNT} foreground Agent tool calls in parallel.`,
  57. `Use subagent_type "general-purpose" for every child.`,
  58. `Give child N this exact instruction: E2E_SIDE_TAB_CHILD_N: read the readonly fixture, then reply with E2E_SIDE_TAB_CHILD_N_DONE.`,
  59. `Do not finish the parent response until every child completes; then reply with exactly ${PARENT_DONE}.`,
  60. ].join(" ");
  61. await sendV4Prompt(prompt);
  62. await waitForV4ComposerText("", "subagent side tabs 首发后输入框没有清空");
  63. await waitForSubagentSummaryActions(CHILD_COUNT, 90000);
  64. await expectSubagentSummariesToOpenSidePaneDirectly();
  65. await openAllSubagentTabs();
  66. // 流式增量更新同一 row;隐藏 tab 的虚拟列表也可能卸载正文,不能要求所有 DOM 同时可见。
  67. // 先验证保活 pane 的投影,再逐个激活读取正文,覆盖 SAT03 的“切回直接显示最新内容”。
  68. await browser.waitUntil(
  69. async () => {
  70. const children = await readChildTimelineStates();
  71. return children.length === CHILD_COUNT && children.every((child) => child.seq > 0);
  72. },
  73. { timeout: 30000, timeoutMsg: "六个 child tabs 没有保留初始投影" },
  74. );
  75. const initialChildren: Awaited<ReturnType<typeof readChildTimelineStates>> = [];
  76. for (const child of await readChildTimelineStates()) {
  77. initialChildren.push(
  78. await readVisibleChildTimelineState(child, /^E2E_SIDE_TAB_CHILD_\d+_$/u),
  79. );
  80. }
  81. expect(new Set(initialChildren.map((child) => child.sessionId)).size).toBe(CHILD_COUNT);
  82. expect(
  83. initialChildren
  84. .map((child) => child.assistantText.match(/E2E_SIDE_TAB_CHILD_\d+_/u)?.[0])
  85. .sort(),
  86. ).toEqual(
  87. Array.from({ length: CHILD_COUNT }, (_, index) => `E2E_SIDE_TAB_CHILD_${index + 1}_`).sort(),
  88. );
  89. await waitForVisibleSubagentTabCount(CHILD_COUNT, 30000);
  90. expect(await countWorkbenchPanes()).toBe(1);
  91. await clickFirstSubagentSummaryAction();
  92. expect(await countVisibleSubagentTabs()).toBe(CHILD_COUNT);
  93. for (let index = 1; index <= CHILD_COUNT; index++) {
  94. await releaseControlledReplay(`side-tab-child-${index}`);
  95. }
  96. await browser.waitUntil(
  97. async () => {
  98. const current = await readChildTimelineStates();
  99. return (
  100. current.length === CHILD_COUNT &&
  101. current.every((child) => {
  102. const initial = initialChildren.find((item) => item.sessionId === child.sessionId);
  103. return Boolean(initial && child.seq > initial.seq);
  104. })
  105. );
  106. },
  107. {
  108. timeout: 120000,
  109. timeoutMsg: "已打开的 child tabs 没有持续更新 projection sequence",
  110. },
  111. );
  112. for (const initial of initialChildren) {
  113. const current = await readVisibleChildTimelineState(
  114. initial,
  115. new RegExp(`^${initial.assistantText}DONE$`, "u"),
  116. );
  117. expect(current.seq).toBeGreaterThan(initial.seq);
  118. }
  119. expect((await readChildTimelineStates()).map((child) => child.sessionId).sort()).toEqual(
  120. initialChildren.map((child) => child.sessionId).sort(),
  121. );
  122. await waitForV4AssistantMessageContaining(`${PARENT_DONE}`);
  123. });
  124. });
  125. async function waitForSubagentSummaryActions(expected: number, timeout: number): Promise<void> {
  126. await browser.waitUntil(
  127. async () =>
  128. browser.execute(
  129. (prefix, count) => document.querySelectorAll(`[data-testid^="${prefix}-"]`).length >= count,
  130. TID_V4_SUBAGENT_OPEN_SIDE_PANE,
  131. expected,
  132. ),
  133. {
  134. timeout,
  135. timeoutMsg: `没有等到 ${expected} 个 subagent 摘要直开入口`,
  136. },
  137. );
  138. }
  139. async function waitForRunningSubagentTrigger(timeout: number): Promise<void> {
  140. // 修复原因:面板 test id 来自 shared 常量;旧代码误传了只存在于浏览器回调
  141. // 形参里的同名变量,导致 E2E TypeScript 编译阶段直接失败。
  142. await browser.waitUntil(
  143. async () =>
  144. browser.execute((panelTestId) => {
  145. const panel = document.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  146. if (panel?.dataset.state === "collapsed") {
  147. panel.querySelector<HTMLButtonElement>("button")?.click();
  148. }
  149. const runningSection = panel?.querySelector<HTMLButtonElement>(
  150. '[data-status-section-trigger="agent"]',
  151. );
  152. if (runningSection?.getAttribute("aria-expanded") === "false") {
  153. runningSection.click();
  154. }
  155. return Boolean(panel?.querySelector('[data-running-subagent-session-trigger="true"]'));
  156. }, TID_CHAT_SUMMARY_PANEL),
  157. {
  158. timeout,
  159. timeoutMsg: "右上角智能体区块没有出现可打开的 subagent session 行",
  160. },
  161. );
  162. }
  163. async function clickRunningSubagentTrigger(): Promise<void> {
  164. await browser.execute(() => {
  165. document
  166. .querySelector<HTMLButtonElement>('[data-running-subagent-session-trigger="true"]')
  167. ?.click();
  168. });
  169. }
  170. async function expectSubagentSummariesToOpenSidePaneDirectly(): Promise<void> {
  171. const summaries = await browser.execute(
  172. (prefix) =>
  173. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid^="${prefix}-"]`)).map(
  174. (summary) => ({
  175. ariaExpanded: summary.getAttribute("aria-expanded"),
  176. hasChevron: Boolean(summary.querySelector(".lucide-chevron-right")),
  177. hasInlineDetails: Boolean(
  178. summary.parentElement?.querySelector('[data-slot="collapsible-content"]'),
  179. ),
  180. }),
  181. ),
  182. TID_V4_SUBAGENT_OPEN_SIDE_PANE,
  183. );
  184. expect(summaries).toHaveLength(CHILD_COUNT);
  185. expect(summaries.every((summary) => summary.ariaExpanded === null)).toBe(true);
  186. expect(summaries.every((summary) => !summary.hasChevron)).toBe(true);
  187. expect(summaries.every((summary) => !summary.hasInlineDetails)).toBe(true);
  188. }
  189. async function openAllSubagentTabs(): Promise<void> {
  190. await browser.execute(
  191. (prefix, expected) => {
  192. const summaries = Array.from(
  193. document.querySelectorAll<HTMLElement>(`[data-testid^="${prefix}-"]`),
  194. ).slice(0, expected);
  195. for (const summary of summaries) summary.click();
  196. },
  197. TID_V4_SUBAGENT_OPEN_SIDE_PANE,
  198. CHILD_COUNT,
  199. );
  200. await waitForVisibleSubagentTabCount(CHILD_COUNT, 30000);
  201. }
  202. async function clickFirstSubagentSummaryAction(): Promise<void> {
  203. await browser.execute((prefix) => {
  204. document.querySelector<HTMLElement>(`[data-testid^="${prefix}-"]`)?.click();
  205. }, TID_V4_SUBAGENT_OPEN_SIDE_PANE);
  206. }
  207. async function waitForVisibleSubagentTabCount(expected: number, timeout: number): Promise<void> {
  208. await browser.waitUntil(async () => (await countVisibleSubagentTabs()) === expected, {
  209. timeout,
  210. timeoutMsg: `右侧没有出现 ${expected} 个 subagent tabs`,
  211. });
  212. }
  213. async function countVisibleSubagentTabs(): Promise<number> {
  214. return browser.execute(
  215. () => document.querySelectorAll('[data-side-pane-tab-id^="subagent-session:"]').length,
  216. );
  217. }
  218. async function countWorkbenchPanes(): Promise<number> {
  219. return browser.execute(
  220. (testId) => document.querySelectorAll(`[data-testid^="${testId}"]`).length,
  221. TID_V4_PANE_SHELL,
  222. );
  223. }
  224. async function readChildTimelineStates() {
  225. return browser.execute(() => {
  226. // 切换任务后旧 pane 仍可能保活;只统计当前 tabs 对应的 child,不能混入前一个 case。
  227. const tabs = Array.from(
  228. document.querySelectorAll<HTMLElement>('[data-side-pane-tab-id^="subagent-session:"]'),
  229. );
  230. return tabs.map((tab) => {
  231. const pane = document.querySelector<HTMLElement>(
  232. `[data-testid=${JSON.stringify(`v4-session-pane-${tab.dataset.sidePaneTabId}`)}]`,
  233. );
  234. const timeline = pane?.querySelector<HTMLElement>('[data-testid="v4-timeline"]');
  235. return {
  236. tabId: tab.dataset.sidePaneTabId ?? null,
  237. sessionId: pane?.dataset.sessionId ?? null,
  238. seq: Number(pane?.dataset.projectionSeq ?? 0),
  239. // 不读 user prompt,避免指令中已有 DONE marker 导致完成态假阳性。
  240. assistantText: Array.from(timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [])
  241. .filter((row) => row.classList.contains("group/assistant-row"))
  242. .map((row) => row.textContent ?? "")
  243. .join("\n"),
  244. };
  245. });
  246. });
  247. }
  248. async function readVisibleChildTimelineState(
  249. child: Awaited<ReturnType<typeof readChildTimelineStates>>[number],
  250. expectedText: RegExp,
  251. ) {
  252. const { sessionId, tabId } = child;
  253. if (!sessionId || !tabId) throw new Error("child tab 没有 session identity");
  254. await browser.execute((id) => {
  255. // tab ID 还包含 root/Host 作用域,必须读取真实 DOM 身份,不能只用 child ID 拼接。
  256. const tab = document.querySelector<HTMLElement>(
  257. `[data-side-pane-tab-id=${JSON.stringify(id)}]`,
  258. );
  259. if (!tab) throw new Error(`child tab 已丢失: ${id}`);
  260. tab.click();
  261. }, tabId);
  262. let state: Awaited<ReturnType<typeof readChildTimelineStates>>[number] | undefined;
  263. await browser.waitUntil(
  264. async () => {
  265. state = (await readChildTimelineStates()).find((child) => child.sessionId === sessionId);
  266. return Boolean(state && expectedText.test(state.assistantText));
  267. },
  268. { timeout: 30000, timeoutMsg: `切回 ${sessionId} 后没有显示预期的 assistant 正文` },
  269. );
  270. if (!state) throw new Error(`child pane 已丢失: ${sessionId}`);
  271. return state;
  272. }