v4ConversationStatusPanel.test.ts 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795
  1. // @vitest-environment jsdom
  2. import { createElement, type ReactNode } from "react";
  3. import { renderToStaticMarkup } from "react-dom/server";
  4. import { describe, expect, it, vi } from "vitest";
  5. import { act, render } from "@testing-library/react";
  6. import type { GitRepositorySummary, ZCodeSessionRunningSubagent } from "@zcode/shared";
  7. import type {
  8. BackgroundWorkSummary,
  9. GoalState,
  10. PlanState,
  11. ToolCallRow,
  12. WorkflowRunState,
  13. } from "@zcode/shared/zcode-protocol-v4";
  14. import { getStatusPanelTodoFocusWindow } from "@/v4/ConversationStatusPanel.js";
  15. const statusPanelCapture = vi.hoisted(() => ({
  16. collapsibles: [] as Array<{
  17. onOpenChange?: (open: boolean) => void;
  18. open?: boolean;
  19. section?: string;
  20. }>,
  21. radioGroups: [] as Array<{
  22. onValueChange?: (value: string) => void;
  23. value?: string;
  24. }>,
  25. hoverCards: [] as Array<{
  26. closeDelay?: number;
  27. onOpenChange?: (open: boolean) => void;
  28. open?: boolean;
  29. openDelay?: number;
  30. }>,
  31. gitBranchSwitchers: [] as Array<Record<string, unknown>>,
  32. }));
  33. vi.mock("@/ControlHintTooltip.js", async (importOriginal) => ({
  34. ...(await importOriginal<typeof import("@/ControlHintTooltip.js")>()),
  35. ControlHintTooltip: ({ children }: { children: ReactNode }) => children,
  36. }));
  37. vi.mock("@/GitActionMenu.js", () => ({
  38. GitActionMenu: () => createElement("div", { "data-testid": "mock-git-action-menu" }),
  39. }));
  40. vi.mock("@/GitBranchSwitcher.js", () => ({
  41. GitBranchSwitcher: (props: Record<string, unknown>) => {
  42. statusPanelCapture.gitBranchSwitchers.push(props);
  43. return createElement("div", { "data-testid": "mock-git-branch-switcher" });
  44. },
  45. }));
  46. vi.mock("@/components/ui/dropdown-menu.js", () => ({
  47. DropdownMenu: ({ children }: { children: ReactNode }) =>
  48. createElement("div", { "data-testid": "mock-dropdown" }, children),
  49. DropdownMenuContent: ({ children }: { children: ReactNode }) =>
  50. createElement("div", { "data-testid": "mock-dropdown-content" }, children),
  51. DropdownMenuRadioGroup: ({
  52. children,
  53. onValueChange,
  54. value,
  55. }: {
  56. children: ReactNode;
  57. onValueChange?: (value: string) => void;
  58. value?: string;
  59. }) => {
  60. statusPanelCapture.radioGroups.push({ onValueChange, value });
  61. return createElement(
  62. "div",
  63. { "data-testid": "mock-radio-group", "data-value": value },
  64. children,
  65. );
  66. },
  67. DropdownMenuRadioItem: ({ children, value }: { children: ReactNode; value: string }) =>
  68. createElement("div", { "data-testid": "mock-radio-item", "data-value": value }, children),
  69. DropdownMenuTrigger: ({ children }: { children: ReactNode }) => children,
  70. }));
  71. vi.mock("@/components/ui/hover-card.js", () => ({
  72. HoverCard: ({
  73. children,
  74. closeDelay,
  75. onOpenChange,
  76. open,
  77. openDelay,
  78. }: {
  79. children: ReactNode;
  80. closeDelay?: number;
  81. onOpenChange?: (open: boolean) => void;
  82. open?: boolean;
  83. openDelay?: number;
  84. }) => {
  85. statusPanelCapture.hoverCards.push({ closeDelay, onOpenChange, open, openDelay });
  86. return createElement("div", { "data-slot": "hover-card" }, children);
  87. },
  88. HoverCardTrigger: ({ children }: { children: ReactNode }) => children,
  89. HoverCardContent: ({
  90. align,
  91. children,
  92. side,
  93. sideOffset,
  94. ...props
  95. }: {
  96. align?: string;
  97. children: ReactNode;
  98. side?: string;
  99. sideOffset?: number;
  100. [key: string]: unknown;
  101. }) =>
  102. createElement(
  103. "div",
  104. {
  105. "data-align": align,
  106. "data-side": side,
  107. "data-side-offset": sideOffset,
  108. "data-slot": "hover-card-content",
  109. ...props,
  110. },
  111. children,
  112. ),
  113. }));
  114. vi.mock("@/components/ui/collapsible.js", () => ({
  115. Collapsible: ({
  116. children,
  117. defaultOpen: _defaultOpen,
  118. onOpenChange,
  119. open,
  120. ...props
  121. }: {
  122. children: ReactNode;
  123. defaultOpen?: boolean;
  124. onOpenChange?: (open: boolean) => void;
  125. open?: boolean;
  126. [key: string]: unknown;
  127. }) => {
  128. statusPanelCapture.collapsibles.push({
  129. onOpenChange,
  130. open,
  131. section: props["data-status-section"] as string | undefined,
  132. });
  133. return createElement("div", { "data-slot": "collapsible", ...props }, children);
  134. },
  135. CollapsibleTrigger: ({ children }: { children: ReactNode }) => children,
  136. CollapsibleContent: ({ children }: { children: ReactNode }) =>
  137. createElement("div", { "data-slot": "collapsible-content" }, children),
  138. }));
  139. vi.mock("@/i18n/IntlProvider.js", () => ({
  140. useZCodeIntl: () => ({
  141. intl: {
  142. formatMessage: (descriptor: { id: string }, values?: Record<string, string>) => {
  143. const durationUnits: Record<string, string> = {
  144. "chat.summaryPanel.duration.hours": "小时",
  145. "chat.summaryPanel.duration.minutes": "分",
  146. "chat.summaryPanel.duration.seconds": "秒",
  147. };
  148. return (
  149. durationUnits[descriptor.id] ??
  150. (values ? `${descriptor.id} ${Object.values(values).join("/")}` : descriptor.id)
  151. );
  152. },
  153. },
  154. locale: "zh-CN",
  155. }),
  156. }));
  157. function gitSummary(overrides: Partial<GitRepositorySummary> = {}): GitRepositorySummary {
  158. return {
  159. workspacePath: "/repo",
  160. repoRoot: "/repo",
  161. workspaceInRepoPath: "",
  162. autoRefreshWatchPaths: [],
  163. branchName: "main",
  164. trackingBranchName: "origin/main",
  165. headRefType: "branch",
  166. ahead: 0,
  167. behind: 0,
  168. isDirty: true,
  169. isGitAvailable: true,
  170. isRepository: true,
  171. ...overrides,
  172. };
  173. }
  174. function goalState(overrides: Partial<GoalState> = {}): GoalState {
  175. return {
  176. targetId: "goal-1",
  177. objective: "修好状态面板",
  178. summaryTitle: null,
  179. timeUsedSeconds: 0,
  180. activeRunStartedAtMs: null,
  181. status: "active",
  182. iteration: 1,
  183. verifications: [],
  184. iterations: [],
  185. ...overrides,
  186. };
  187. }
  188. function planState(overrides: Partial<PlanState> = {}): PlanState {
  189. return {
  190. updatedAt: 1_700_000_000_000,
  191. items: [
  192. { id: "1", content: "看 z-code-2", status: "completed" },
  193. { id: "2", content: "复刻浮层", status: "inProgress" },
  194. ],
  195. ...overrides,
  196. };
  197. }
  198. describe("getStatusPanelTodoFocusWindow", () => {
  199. const items = (count: number, currentIndex: number | null) =>
  200. planState({
  201. items: Array.from({ length: count }, (_, index) => ({
  202. id: String(index + 1),
  203. content: `Todo ${index + 1}`,
  204. status:
  205. index === currentIndex
  206. ? ("inProgress" as const)
  207. : index < 2
  208. ? ("completed" as const)
  209. : ("pending" as const),
  210. })),
  211. }).items;
  212. it("keeps up to six snapshot items fully visible in original order", () => {
  213. const snapshot = items(6, 2);
  214. const window = getStatusPanelTodoFocusWindow(snapshot);
  215. expect(window.compact).toBe(false);
  216. expect(window.precedingItems).toEqual([]);
  217. expect(window.focusItems).toEqual(snapshot);
  218. expect(window.followingItems).toEqual([]);
  219. });
  220. it("focuses the running item and its following context without reordering", () => {
  221. const window = getStatusPanelTodoFocusWindow(items(8, 3));
  222. expect(window.compact).toBe(true);
  223. expect(window.precedingItems.map((item) => item.id)).toEqual(["1", "2", "3"]);
  224. expect(window.focusItems.map((item) => item.id)).toEqual(["4", "5", "6"]);
  225. expect(window.followingItems.map((item) => item.id)).toEqual(["7", "8"]);
  226. });
  227. it("backfills the focus window when the running item is near the end", () => {
  228. const window = getStatusPanelTodoFocusWindow(items(8, 7));
  229. expect(window.focusItems.map((item) => item.id)).toEqual(["6", "7", "8"]);
  230. expect(window.followingItems).toEqual([]);
  231. });
  232. it("uses the first unfinished item or final three completed items as fallback", () => {
  233. const pendingWindow = getStatusPanelTodoFocusWindow(items(8, null));
  234. const completedWindow = getStatusPanelTodoFocusWindow(
  235. items(8, null).map((item) => ({ ...item, status: "completed" as const })),
  236. );
  237. expect(pendingWindow.focusItems.map((item) => item.id)).toEqual(["3", "4", "5"]);
  238. expect(completedWindow.focusItems.map((item) => item.id)).toEqual(["6", "7", "8"]);
  239. });
  240. });
  241. function backgroundWork(overrides: Partial<BackgroundWorkSummary> = {}): BackgroundWorkSummary {
  242. return {
  243. workId: "work-1",
  244. kind: "subagent",
  245. title: "探索渲染逻辑",
  246. status: "running",
  247. startedAt: Date.now() - 8_000,
  248. anchorRowId: null,
  249. ...overrides,
  250. };
  251. }
  252. function runningSubagent(
  253. overrides: Partial<ZCodeSessionRunningSubagent> = {},
  254. ): ZCodeSessionRunningSubagent {
  255. return {
  256. childSessionId: "child-session",
  257. subagentType: "Explore",
  258. title: "探索渲染逻辑",
  259. status: "running",
  260. startedAt: Date.now() - 8_000,
  261. ...overrides,
  262. };
  263. }
  264. // 面板自己从 workflowRuns 投影 + backgroundWorks 联接出行(模型层的活儿),所以这里造的是
  265. // 两侧输入,而不是行——行的形状由 v4ConversationStatusPanelModel.test.ts 穷举。
  266. /** 声明了三站(盘点 → 计划 → 构建)、正在「计划」的 run。 */
  267. function phasedRunProjection(overrides: Partial<WorkflowRunState> = {}): WorkflowRunState {
  268. return workflowRunProjection({
  269. phaseNames: ["盘点", "计划", "构建"],
  270. phases: [{ name: "盘点", rounds: 1 }],
  271. currentPhase: "计划",
  272. ...overrides,
  273. });
  274. }
  275. function workflowRunProjection(overrides: Partial<WorkflowRunState> = {}): WorkflowRunState {
  276. return {
  277. runId: "dwfrun-1",
  278. toolCallId: "tool-wf-1",
  279. status: "running",
  280. usage: { spentTokens: 0, nodesUsed: 0 },
  281. actors: [],
  282. nodes: [
  283. { siteId: "ask#1", ordinal: 1, phase: "settled" },
  284. { siteId: "ask#2", ordinal: 2, phase: "dispatched" },
  285. { siteId: "ask#3", ordinal: 3, phase: "queued" },
  286. ],
  287. lastEventSequence: 1,
  288. ...overrides,
  289. };
  290. }
  291. function sessionPlan(rowId: number, markdown: string): ToolCallRow {
  292. return {
  293. rowId,
  294. turnId: `turn-${rowId}`,
  295. createdAt: 1_700_000_000_000 + rowId,
  296. createdAtSeq: rowId,
  297. kind: "toolCall",
  298. toolCallId: `plan-${rowId}`,
  299. toolName: "ExitPlanMode",
  300. status: "success",
  301. input: { plan: markdown },
  302. inputText: JSON.stringify({ plan: markdown }),
  303. };
  304. }
  305. async function renderStatusPanel(props: Record<string, unknown>) {
  306. const { ConversationStatusPanel } = await import("@/v4/ConversationStatusPanel.js");
  307. return renderToStaticMarkup(
  308. createElement(ConversationStatusPanel, {
  309. workspacePath: "/repo",
  310. gitSummary: gitSummary(),
  311. gitDirtyFileCount: 2,
  312. gitWorktreeChangeSummary: { added: 12, removed: 3 },
  313. onRefreshGit: vi.fn(),
  314. ...props,
  315. }),
  316. );
  317. }
  318. describe("ConversationStatusPanel", () => {
  319. it("uses vertical viewport-bound overlays only on mobile Web remote control", async () => {
  320. const longPlan = planState({
  321. items: Array.from({ length: 9 }, (_, index) => ({
  322. id: String(index + 1),
  323. content: `Todo ${index + 1}`,
  324. status: index === 4 ? ("inProgress" as const) : ("pending" as const),
  325. })),
  326. });
  327. statusPanelCapture.gitBranchSwitchers = [];
  328. const mobileHtml = await renderStatusPanel({
  329. isMobileViewport: true,
  330. isWebRemoteControl: true,
  331. plan: longPlan,
  332. summaryPanelVariantOverride: "panel",
  333. });
  334. expect(statusPanelCapture.gitBranchSwitchers.at(-1)?.popoverSide).toBe("bottom");
  335. expect(statusPanelCapture.gitBranchSwitchers.at(-1)?.popoverClassName).toContain(
  336. "max-w-[calc(100vw-2rem)]",
  337. );
  338. expect(mobileHtml).toContain('data-side="bottom"');
  339. statusPanelCapture.gitBranchSwitchers = [];
  340. const desktopHtml = await renderStatusPanel({
  341. isMobileViewport: false,
  342. isWebRemoteControl: false,
  343. plan: longPlan,
  344. summaryPanelVariantOverride: "panel",
  345. });
  346. expect(statusPanelCapture.gitBranchSwitchers.at(-1)?.popoverSide).toBe("left");
  347. expect(desktopHtml).toContain('data-side="left"');
  348. });
  349. it("goal 计时器只在活动态起一次:投影换一个等值的 goal 对象不重建 interval,暂停即拆掉", async () => {
  350. // 修订 2026-09-12:此前 effect 以整个 goal 对象为依赖,每个 goal 事件都同步 setNow 并重建
  351. // interval——落在投影帧的同步提交里,给 React 的嵌套更新计数记一笔(与工作流卡崩溃同形)。
  352. vi.useFakeTimers();
  353. vi.setSystemTime(10_000);
  354. const setIntervalSpy = vi.spyOn(globalThis, "setInterval");
  355. const clearIntervalSpy = vi.spyOn(globalThis, "clearInterval");
  356. try {
  357. const { ConversationStatusPanel } = await import("@/v4/ConversationStatusPanel.js");
  358. const renderGoal = (goal: GoalState) =>
  359. createElement(ConversationStatusPanel, {
  360. workspacePath: "/repo",
  361. gitSummary: null,
  362. summaryPanelVariantOverride: "panel",
  363. goal,
  364. onPauseGoal: vi.fn(),
  365. onResumeGoal: vi.fn(),
  366. });
  367. const view = render(renderGoal(goalState({ activeRunStartedAtMs: 10_000 })));
  368. const intervalsAfterMount = setIntervalSpy.mock.calls.length;
  369. expect(intervalsAfterMount).toBeGreaterThan(0);
  370. // 同值、不同对象的 goal 帧 ×3:不再有新的 interval。
  371. for (let i = 0; i < 3; i += 1) {
  372. view.rerender(renderGoal(goalState({ activeRunStartedAtMs: 10_000, iteration: 1 + i })));
  373. }
  374. expect(setIntervalSpy.mock.calls.length).toBe(intervalsAfterMount);
  375. // 秒针仍在走:过 2 秒后用时文案跟着变。
  376. const before = view.container.textContent;
  377. act(() => vi.advanceTimersByTime(2_000));
  378. expect(view.container.textContent).not.toBe(before);
  379. // 暂停:interval 拆掉,不再起新的。
  380. const clearsBefore = clearIntervalSpy.mock.calls.length;
  381. view.rerender(renderGoal(goalState({ status: "paused", activeRunStartedAtMs: null })));
  382. expect(clearIntervalSpy.mock.calls.length).toBeGreaterThan(clearsBefore);
  383. expect(setIntervalSpy.mock.calls.length).toBe(intervalsAfterMount);
  384. } finally {
  385. setIntervalSpy.mockRestore();
  386. clearIntervalSpy.mockRestore();
  387. vi.useRealTimers();
  388. }
  389. });
  390. it("uses neutral labels for mixed position buckets and keeps previews mutually exclusive", async () => {
  391. statusPanelCapture.hoverCards = [];
  392. const { ConversationStatusPanel } = await import("@/v4/ConversationStatusPanel.js");
  393. const view = render(
  394. createElement(ConversationStatusPanel, {
  395. workspacePath: "/repo",
  396. gitSummary: null,
  397. summaryPanelVariantOverride: "panel",
  398. plan: planState({
  399. items: [
  400. { id: "1", content: "Todo 1", status: "completed" },
  401. { id: "2", content: "Todo 2", status: "completed" },
  402. { id: "3", content: "Todo 3", status: "pending" },
  403. { id: "4", content: "Todo 4", status: "pending" },
  404. { id: "5", content: "Todo 5", status: "inProgress" },
  405. { id: "6", content: "Todo 6", status: "pending" },
  406. { id: "7", content: "Todo 7", status: "pending" },
  407. { id: "8", content: "Todo 8", status: "pending" },
  408. { id: "9", content: "Todo 9", status: "completed" },
  409. ],
  410. }),
  411. }),
  412. );
  413. expect(view.container.textContent).toContain("chat.statusPanel.todoEarlierFold 4");
  414. expect(view.container.textContent).toContain("chat.statusPanel.todoLaterFold 2");
  415. let previews = statusPanelCapture.hoverCards.slice(-2);
  416. expect(previews.map((preview) => preview.open)).toEqual([false, false]);
  417. await act(async () => previews[0]?.onOpenChange?.(true));
  418. previews = statusPanelCapture.hoverCards.slice(-2);
  419. expect(previews.map((preview) => preview.open)).toEqual([true, false]);
  420. await act(async () => previews[1]?.onOpenChange?.(true));
  421. previews = statusPanelCapture.hoverCards.slice(-2);
  422. expect(previews.map((preview) => preview.open)).toEqual([false, true]);
  423. view.unmount();
  424. });
  425. it("renders all six Todos without fold controls at the compact threshold", async () => {
  426. const html = await renderStatusPanel({
  427. gitSummary: null,
  428. gitWorktreeChangeSummary: null,
  429. summaryPanelVariantOverride: "panel",
  430. plan: planState({
  431. items: Array.from({ length: 6 }, (_, index) => ({
  432. id: String(index + 1),
  433. content: `Todo ${index + 1}`,
  434. status: index === 0 ? "completed" : "pending",
  435. })),
  436. }),
  437. });
  438. expect(html).toContain("Todo 1");
  439. expect(html).toContain("Todo 6");
  440. expect(html).not.toContain("data-status-todo-preview-trigger");
  441. });
  442. it("keeps the full long Todo content and title", async () => {
  443. const content =
  444. "检查包含多个测试项目的目录,逐项核对配置文件、依赖安装状态、测试入口和输出目录是否完整";
  445. const html = await renderStatusPanel({
  446. summaryPanelVariantOverride: "panel",
  447. plan: planState({
  448. items: [{ id: "long-todo", content, status: "inProgress" }],
  449. }),
  450. });
  451. expect(html).toContain(`title="${content}"`);
  452. expect(html).toContain(content);
  453. });
  454. it("renders terminal plans newest-first and maps a row to the plan detail tab", async () => {
  455. const html = await renderStatusPanel({
  456. gitSummary: null,
  457. gitWorktreeChangeSummary: null,
  458. summaryPanelVariantOverride: "panel",
  459. parentSessionId: "parent-session",
  460. sessionPlans: [sessionPlan(3, "# 较早计划"), sessionPlan(9, "# 最新计划")],
  461. onOpenPlanDetail: vi.fn(),
  462. });
  463. const { buildSessionPlanOpenRequest } = await import("@/v4/ConversationStatusPanel.js");
  464. expect(html).toContain('data-status-section="sessionPlans"');
  465. expect(html).toContain('data-status-section-scroll="sessionPlans"');
  466. expect(html.indexOf("最新计划")).toBeLessThan(html.indexOf("较早计划"));
  467. expect(
  468. buildSessionPlanOpenRequest("parent-session", {
  469. rowId: 9,
  470. toolCallId: "plan-9",
  471. markdown: "# 最新计划",
  472. title: "最新计划",
  473. planFilePath: "/repo/.zcode/plans/latest.md",
  474. }),
  475. ).toEqual({
  476. parentSessionId: "parent-session",
  477. toolCallId: "plan-9",
  478. markdown: "# 最新计划",
  479. planFilePath: "/repo/.zcode/plans/latest.md",
  480. });
  481. });
  482. it("keeps the shell mounted for plan-only mini state", async () => {
  483. const html = await renderStatusPanel({
  484. gitSummary: null,
  485. gitWorktreeChangeSummary: null,
  486. summaryPanelVariantOverride: "mini",
  487. sessionPlans: [sessionPlan(4, "# 唯一计划")],
  488. });
  489. expect(html).toContain('data-state="collapsed"');
  490. expect(html).toContain("唯一计划");
  491. expect(html).toContain("chat.summaryPanel.showPanel");
  492. });
  493. it("orders expanded sections as Git, Goal, plans, Todo, terminals, workflows, and Agents", async () => {
  494. const html = await renderStatusPanel({
  495. summaryPanelVariantOverride: "panel",
  496. goal: goalState(),
  497. sessionPlans: [sessionPlan(4, "# 会话计划")],
  498. plan: planState(),
  499. backgroundWorks: [
  500. backgroundWork({ kind: "bash" }),
  501. backgroundWork({ workId: "dwfrun-1", kind: "workflow" }),
  502. ],
  503. workflowRuns: [workflowRunProjection()],
  504. runningSubagents: [runningSubagent()],
  505. });
  506. const indexes = [
  507. "environment",
  508. "goal",
  509. "sessionPlans",
  510. "plan",
  511. "terminal",
  512. "workflow",
  513. "agent",
  514. ].map((section) => html.indexOf(`data-status-section="${section}"`));
  515. expect(indexes.every((index) => index >= 0)).toBe(true);
  516. expect(indexes).toEqual([...indexes].sort((left, right) => left - right));
  517. });
  518. it("renders the mini shell with one-line git summary", async () => {
  519. const html = await renderStatusPanel({
  520. summaryPanelVariantOverride: "mini",
  521. });
  522. expect(html).toContain('data-state="collapsed"');
  523. expect(html).toContain("chat.summaryPanel.showPanel");
  524. expect(html).toContain("chat.statusPanel.changes");
  525. expect(html).toContain("+12");
  526. expect(html).toContain("-3");
  527. expect(html).not.toContain("mock-git-action-menu");
  528. });
  529. it("keeps goal and running background authority on the mini shell", async () => {
  530. const html = await renderStatusPanel({
  531. summaryPanelVariantOverride: "mini",
  532. goal: goalState(),
  533. runningSubagents: [runningSubagent()],
  534. });
  535. expect(html).toContain('data-state="collapsed"');
  536. expect(html).toContain('data-goal-status="active"');
  537. expect(html).toContain('data-goal-objective="修好状态面板"');
  538. expect(html).toContain('data-running-background-count="1"');
  539. expect(html).toContain("修好状态面板");
  540. expect(html).not.toContain("chat.summaryPanel.runningBackgroundTasksMiniValue 1");
  541. expect(html).not.toContain("lucide-bot");
  542. });
  543. it("uses Bot for Subagent-only mini summaries and reserves Activity for mixed work", async () => {
  544. const subagentOnly = await renderStatusPanel({
  545. gitSummary: null,
  546. gitWorktreeChangeSummary: null,
  547. summaryPanelVariantOverride: "mini",
  548. runningSubagents: [runningSubagent()],
  549. });
  550. expect(subagentOnly).toContain("chat.statusPanel.runningAgentsValue 1");
  551. expect(subagentOnly).not.toContain("chat.summaryPanel.runningBackgroundTasksMiniValue 1");
  552. expect(subagentOnly).not.toMatch(/\d+秒/u);
  553. expect(subagentOnly).toContain("lucide-bot");
  554. expect(subagentOnly).not.toContain("lucide-activity");
  555. expect(subagentOnly).not.toContain("lucide-square-terminal");
  556. const bashOnly = await renderStatusPanel({
  557. gitSummary: null,
  558. gitWorktreeChangeSummary: null,
  559. summaryPanelVariantOverride: "mini",
  560. backgroundWorks: [backgroundWork({ kind: "bash" })],
  561. });
  562. expect(bashOnly).toContain("chat.summaryPanel.runningBackgroundTasksMiniValue 1");
  563. expect(bashOnly).not.toContain("chat.statusPanel.runningAgentsValue 1");
  564. expect(bashOnly).toContain("lucide-square-terminal");
  565. expect(bashOnly).not.toContain("lucide-bot");
  566. expect(bashOnly).not.toContain("lucide-activity");
  567. const mixed = await renderStatusPanel({
  568. gitSummary: null,
  569. gitWorktreeChangeSummary: null,
  570. summaryPanelVariantOverride: "mini",
  571. backgroundWorks: [backgroundWork({ workId: "bash-1", kind: "bash" })],
  572. runningSubagents: [runningSubagent()],
  573. });
  574. expect(mixed).toContain("chat.statusPanel.runningAgentsValuePlural 2");
  575. expect(mixed).not.toContain("chat.summaryPanel.runningBackgroundTasksMiniValuePlural 2");
  576. expect(mixed).toContain("lucide-activity");
  577. expect(mixed).not.toContain("lucide-bot");
  578. expect(mixed).not.toContain("lucide-square-terminal");
  579. });
  580. // ── Workflows 分区(docs/dynamic-workflow/presentation.md「Other places a run appears」)──
  581. // 一行两行高:第一行 名称 + 时长,第二行 侧栏同款轨道 + phase 词。状态词不再可见(灯和 phase
  582. // 已经说了),但仍进打开按钮的无障碍名。步数只在没有 phase 表时出现。
  583. it("renders a run as name and time over the sidebar rail and its phase words", async () => {
  584. const { ConversationStatusPanel } = await import("@/v4/ConversationStatusPanel.js");
  585. const view = render(
  586. createElement(ConversationStatusPanel, {
  587. workspacePath: "/repo",
  588. gitSummary: null,
  589. summaryPanelVariantOverride: "panel",
  590. workflowRuns: [phasedRunProjection()],
  591. backgroundWorks: [
  592. backgroundWork({
  593. workId: "dwfrun-1",
  594. kind: "workflow",
  595. title: "重构状态胶囊",
  596. startedAt: Date.now() - 194_000,
  597. }),
  598. ],
  599. workflowSectionOpen: true,
  600. onCancelBackgroundWork: vi.fn(),
  601. onOpenWorkflowRun: vi.fn(),
  602. }),
  603. );
  604. const row = view.container.querySelector<HTMLElement>('[data-workflow-run-id="dwfrun-1"]');
  605. const lineOne = row?.querySelector<HTMLElement>("[data-workflow-island-line='name']");
  606. const lineTwo = row?.querySelector<HTMLElement>("[data-workflow-island-line='phase']");
  607. expect(lineOne?.textContent).toContain("重构状态胶囊");
  608. expect(lineOne?.querySelector("[data-workflow-run-elapsed]")?.textContent).toBe("3分 14秒");
  609. // 轨道就是侧栏那一条:done / running / pending 三种灯按声明序排开。
  610. expect(
  611. [...(lineTwo?.querySelectorAll("[data-rail-station]") ?? [])].map((lamp) =>
  612. lamp.getAttribute("data-rail-station"),
  613. ),
  614. ).toEqual(["done", "running", "pending"]);
  615. expect(lineTwo?.textContent).toContain("计划");
  616. // 可见文字里没有状态词、没有步数、没有「已运行」前缀。
  617. expect(row?.textContent).not.toContain("chat.toolCall.workflow.run.status.running");
  618. expect(row?.textContent).not.toContain("chat.toolCall.workflow.card.steps");
  619. expect(row?.textContent).not.toContain("chat.longRunning");
  620. // 状态词挪进打开按钮的无障碍名:名称 · 状态 · phase。
  621. expect(
  622. row?.querySelector('[data-workflow-run-details-trigger="true"]')?.getAttribute("aria-label"),
  623. ).toBe(
  624. "chat.toolCall.workflow.openRunDetails · 重构状态胶囊 · chat.toolCall.workflow.run.status.running · 计划",
  625. );
  626. // Stop 叠在时长上(悬停 / 键盘焦点时出现),无障碍名与卡片的「停止运行」同一个 key。
  627. const stop = row?.querySelector<HTMLElement>(
  628. '[data-testid="v4-background-work-cancel-dwfrun-1"]',
  629. );
  630. expect(stop?.getAttribute("aria-label")).toBe("chat.toolCall.workflow.run.cancel");
  631. expect(stop?.textContent).toContain("chat.statusPanel.runningStop");
  632. view.unmount();
  633. });
  634. it("joins parallel burning phases with ∥ and draws the twin segment", async () => {
  635. const html = await renderStatusPanel({
  636. gitSummary: null,
  637. gitWorktreeChangeSummary: null,
  638. summaryPanelVariantOverride: "panel",
  639. workflowRuns: [
  640. phasedRunProjection({
  641. phaseNames: ["准备", "安全", "性能"],
  642. phaseAlongside: [[], [], [1]],
  643. phases: [
  644. { name: "准备", rounds: 1 },
  645. { name: "安全", rounds: 1 },
  646. ],
  647. currentPhase: "性能",
  648. nodes: [
  649. { siteId: "ask#1", ordinal: 1, phase: "settled", phaseName: "准备" },
  650. { siteId: "ask#2", ordinal: 2, phase: "executing", phaseName: "安全" },
  651. { siteId: "ask#3", ordinal: 3, phase: "executing", phaseName: "性能" },
  652. ],
  653. }),
  654. ],
  655. workflowSectionOpen: true,
  656. });
  657. expect(html).toContain("安全 ∥ 性能");
  658. expect(html).toContain('data-rail-twin="true"');
  659. });
  660. it("falls back to one lamp and steps when the script declared no phases", async () => {
  661. const html = await renderStatusPanel({
  662. gitSummary: null,
  663. gitWorktreeChangeSummary: null,
  664. summaryPanelVariantOverride: "panel",
  665. workflowRuns: [workflowRunProjection()],
  666. workflowSectionOpen: true,
  667. });
  668. expect(html).toContain('data-workflow-island-line="phase"');
  669. expect(html).toContain('data-workflow-run-lamp="running"');
  670. expect(html).toContain("chat.toolCall.workflow.card.steps 1/3");
  671. expect(html).not.toContain("data-rail-station");
  672. });
  673. it("shows a pending run as a hollow lamp and the status word, with no time", async () => {
  674. const html = await renderStatusPanel({
  675. gitSummary: null,
  676. gitWorktreeChangeSummary: null,
  677. summaryPanelVariantOverride: "panel",
  678. workflowRuns: [workflowRunProjection({ status: "pending" })],
  679. backgroundWorks: [backgroundWork({ workId: "dwfrun-1", kind: "workflow", title: "迁移" })],
  680. workflowSectionOpen: true,
  681. });
  682. expect(html).toContain('data-workflow-run-lamp="pending"');
  683. expect(html).toContain("chat.toolCall.workflow.run.status.pending");
  684. expect(html).not.toContain("data-workflow-run-elapsed");
  685. expect(html).not.toContain("chat.toolCall.workflow.card.steps");
  686. });
  687. it("drops seconds from the elapsed time past an hour", async () => {
  688. const html = await renderStatusPanel({
  689. gitSummary: null,
  690. gitWorktreeChangeSummary: null,
  691. summaryPanelVariantOverride: "panel",
  692. workflowRuns: [workflowRunProjection()],
  693. backgroundWorks: [
  694. backgroundWork({
  695. workId: "dwfrun-1",
  696. kind: "workflow",
  697. title: "长跑",
  698. startedAt: Date.now() - 3_727_000,
  699. }),
  700. ],
  701. workflowSectionOpen: true,
  702. });
  703. expect(html).toMatch(/data-workflow-run-elapsed="true"[^>]*>1小时 2分</u);
  704. expect(html).not.toContain("1小时 2分 7秒");
  705. });
  706. // 头部右侧开合一个样:灯 + 「{n} 个运行中」。折叠时不再换成「所有 run 里最长的时长」——那不是
  707. // 任何一条 run 的时间。
  708. it("reads the same live count in the section header open or folded", async () => {
  709. const works = [
  710. backgroundWork({ workId: "dwfrun-1", kind: "workflow", startedAt: Date.now() - 3_727_000 }),
  711. backgroundWork({ workId: "dwfrun-2", kind: "workflow", startedAt: Date.now() - 5_000 }),
  712. ];
  713. const runs = [workflowRunProjection(), workflowRunProjection({ runId: "dwfrun-2" })];
  714. for (const open of [true, false]) {
  715. const html = await renderStatusPanel({
  716. gitSummary: null,
  717. gitWorktreeChangeSummary: null,
  718. summaryPanelVariantOverride: "panel",
  719. workflowRuns: runs,
  720. backgroundWorks: works,
  721. workflowSectionOpen: open,
  722. });
  723. const header = html.slice(
  724. html.indexOf('data-status-section-trigger="workflow"'),
  725. html.indexOf(
  726. 'data-slot="collapsible-content"',
  727. html.indexOf('data-status-section="workflow"'),
  728. ),
  729. );
  730. expect(header).toContain("chat.statusPanel.workflowsLive 2");
  731. expect(header).not.toMatch(/\d+秒/u);
  732. }
  733. });
  734. // 已结束入口在滚动区之外:runs 多到要滚时它也不会被滚出视野。
  735. it("keeps the ended-runs entry below the scrolling run list", async () => {
  736. const { ConversationStatusPanel } = await import("@/v4/ConversationStatusPanel.js");
  737. const view = render(
  738. createElement(ConversationStatusPanel, {
  739. workspacePath: "/repo",
  740. gitSummary: null,
  741. summaryPanelVariantOverride: "panel",
  742. workflowRuns: [workflowRunProjection()],
  743. endedWorkflowRunCount: 3,
  744. parentSessionId: "parent-a",
  745. workflowSectionOpen: true,
  746. onOpenWorkflowRunDirectory: vi.fn(),
  747. }),
  748. );
  749. const scroll = view.container.querySelector('[data-status-section-scroll="workflow"]');
  750. const trigger = view.container.querySelector('[data-testid="workflow-run-directory-trigger"]');
  751. const row = view.container.querySelector('[data-workflow-run-id="dwfrun-1"]');
  752. expect(scroll?.contains(row)).toBe(true);
  753. expect(trigger).not.toBeNull();
  754. expect(scroll?.contains(trigger)).toBe(false);
  755. view.unmount();
  756. });
  757. // 未命名规则:core 的 workflowTaskSubject 兜底链落到 taskId(≡ runId ≡ workId),投影再把
  758. // 非空 description 原样抄进 title——所以「题名恰好等于 id」是唯一可靠的未命名信号。
  759. it("substitutes the shared fallback name when the title is just the run id", async () => {
  760. const html = await renderStatusPanel({
  761. gitSummary: null,
  762. gitWorktreeChangeSummary: null,
  763. summaryPanelVariantOverride: "panel",
  764. workflowRuns: [workflowRunProjection()],
  765. backgroundWorks: [
  766. backgroundWork({ workId: "dwfrun-1", kind: "workflow", title: "dwfrun-1" }),
  767. ],
  768. workflowSectionOpen: true,
  769. });
  770. expect(html).toContain("chat.toolCall.workflow.fallbackName");
  771. expect(html).not.toContain(">dwfrun-1<");
  772. });
  773. it("keeps a degraded skew row without status or steps but with its Stop control", async () => {
  774. const html = await renderStatusPanel({
  775. gitSummary: null,
  776. gitWorktreeChangeSummary: null,
  777. summaryPanelVariantOverride: "panel",
  778. // 旧 CLI:只有 workflow work,没有 workflowRuns 投影键。
  779. backgroundWorks: [
  780. backgroundWork({ workId: "dwfrun-skew", kind: "workflow", title: "旧 CLI 的 run" }),
  781. ],
  782. workflowSectionOpen: true,
  783. onCancelBackgroundWork: vi.fn(),
  784. });
  785. expect(html).toContain('data-status-section="workflow"');
  786. expect(html).toContain("旧 CLI 的 run");
  787. expect(html).toContain('data-testid="v4-background-work-cancel-dwfrun-skew"');
  788. expect(html).not.toContain("chat.toolCall.workflow.run.status.");
  789. expect(html).not.toContain("chat.toolCall.workflow.card.steps");
  790. expect(html).not.toContain('data-workflow-island-line="phase"');
  791. expect(html).toContain("data-workflow-run-elapsed");
  792. });
  793. it("drops elapsed and Stop for a run whose background work is gone", async () => {
  794. const html = await renderStatusPanel({
  795. gitSummary: null,
  796. gitWorktreeChangeSummary: null,
  797. summaryPanelVariantOverride: "panel",
  798. workflowRuns: [workflowRunProjection()],
  799. workflowSectionOpen: true,
  800. onCancelBackgroundWork: vi.fn(),
  801. });
  802. expect(html).toContain("chat.toolCall.workflow.card.steps 1/3");
  803. expect(html).not.toContain("data-workflow-run-elapsed");
  804. // 无 work → 无 workId → 停不了;Stop 的两个前提字段在模型层就一起缺席。
  805. expect(html).not.toContain("v4-background-work-cancel");
  806. expect(html).not.toContain("chat.statusPanel.runningStop");
  807. });
  808. it("opens the run details tab through a transparent sibling button", async () => {
  809. const onOpenWorkflowRun = vi.fn();
  810. const { ConversationStatusPanel } = await import("@/v4/ConversationStatusPanel.js");
  811. const view = render(
  812. createElement(ConversationStatusPanel, {
  813. workspacePath: "/repo",
  814. gitSummary: null,
  815. summaryPanelVariantOverride: "panel",
  816. workflowRuns: [workflowRunProjection()],
  817. workflowSectionOpen: true,
  818. onOpenWorkflowRun,
  819. }),
  820. );
  821. const trigger = view.container.querySelector<HTMLButtonElement>(
  822. '[data-workflow-run-details-trigger="true"]',
  823. );
  824. expect(trigger).not.toBeNull();
  825. // Stop 是行内嵌套交互,所以详情入口不能是整行 button——透明同级按钮,与 Agent 行同款。
  826. expect(trigger?.getAttribute("aria-label")).toBe(
  827. "chat.toolCall.workflow.openRunDetails · chat.toolCall.workflow.fallbackName · chat.toolCall.workflow.run.status.running · chat.toolCall.workflow.card.steps 1/3",
  828. );
  829. await act(async () => trigger?.click());
  830. expect(onOpenWorkflowRun).toHaveBeenCalledWith({
  831. runId: "dwfrun-1",
  832. toolCallId: "tool-wf-1",
  833. });
  834. view.unmount();
  835. });
  836. it("carries the workflow name into the target for a named run", async () => {
  837. // 任务岛入口曾只交出 runId + toolCallId,详情页标签因此兜底成通用名,而工具卡入口显示真名。
  838. // 行的题名由 workflowRuns 投影按 workId ≡ runId 联接 workflow 后台任务的 title 得到。
  839. const onOpenWorkflowRun = vi.fn();
  840. const { ConversationStatusPanel } = await import("@/v4/ConversationStatusPanel.js");
  841. const view = render(
  842. createElement(ConversationStatusPanel, {
  843. workspacePath: "/repo",
  844. gitSummary: null,
  845. summaryPanelVariantOverride: "panel",
  846. workflowRuns: [workflowRunProjection()],
  847. backgroundWorks: [
  848. backgroundWork({ workId: "dwfrun-1", kind: "workflow", title: "Ship the release" }),
  849. ],
  850. workflowSectionOpen: true,
  851. onOpenWorkflowRun,
  852. }),
  853. );
  854. const trigger = view.container.querySelector<HTMLButtonElement>(
  855. '[data-workflow-run-details-trigger="true"]',
  856. );
  857. await act(async () => trigger?.click());
  858. expect(onOpenWorkflowRun).toHaveBeenCalledWith({
  859. runId: "dwfrun-1",
  860. toolCallId: "tool-wf-1",
  861. workflowName: "Ship the release",
  862. });
  863. view.unmount();
  864. });
  865. it("omits the workflow name for an unnamed run (title ≡ runId)", async () => {
  866. // `title ≡ runId` 是未命名 run 的兜底样子;把 runId 冻进标签比通用兜底名更糟,所以不带出去。
  867. const onOpenWorkflowRun = vi.fn();
  868. const { ConversationStatusPanel } = await import("@/v4/ConversationStatusPanel.js");
  869. const view = render(
  870. createElement(ConversationStatusPanel, {
  871. workspacePath: "/repo",
  872. gitSummary: null,
  873. summaryPanelVariantOverride: "panel",
  874. workflowRuns: [workflowRunProjection()],
  875. backgroundWorks: [
  876. backgroundWork({ workId: "dwfrun-1", kind: "workflow", title: "dwfrun-1" }),
  877. ],
  878. workflowSectionOpen: true,
  879. onOpenWorkflowRun,
  880. }),
  881. );
  882. const trigger = view.container.querySelector<HTMLButtonElement>(
  883. '[data-workflow-run-details-trigger="true"]',
  884. );
  885. await act(async () => trigger?.click());
  886. expect(onOpenWorkflowRun).toHaveBeenCalledWith({
  887. runId: "dwfrun-1",
  888. toolCallId: "tool-wf-1",
  889. });
  890. view.unmount();
  891. });
  892. it("leaves a row without toolCallId or host callback unclickable", async () => {
  893. const withoutToolCallId = await renderStatusPanel({
  894. gitSummary: null,
  895. gitWorktreeChangeSummary: null,
  896. summaryPanelVariantOverride: "panel",
  897. workflowRuns: [workflowRunProjection({ toolCallId: undefined })],
  898. workflowSectionOpen: true,
  899. onOpenWorkflowRun: vi.fn(),
  900. });
  901. expect(withoutToolCallId).toContain('data-workflow-run-id="dwfrun-1"');
  902. expect(withoutToolCallId).not.toContain("data-workflow-run-details-trigger");
  903. const withoutHostCallback = await renderStatusPanel({
  904. gitSummary: null,
  905. gitWorktreeChangeSummary: null,
  906. summaryPanelVariantOverride: "panel",
  907. workflowRuns: [workflowRunProjection()],
  908. workflowSectionOpen: true,
  909. });
  910. expect(withoutHostCallback).toContain('data-workflow-run-id="dwfrun-1"');
  911. expect(withoutHostCallback).not.toContain("data-workflow-run-details-trigger");
  912. });
  913. it("keeps the projection order of active runs instead of sorting by start time", async () => {
  914. const html = await renderStatusPanel({
  915. gitSummary: null,
  916. gitWorktreeChangeSummary: null,
  917. summaryPanelVariantOverride: "panel",
  918. // 投影序即启动序;后启动的 run 反而 startedAt 更早也不许把它排到前面。
  919. workflowRuns: [
  920. workflowRunProjection({ runId: "dwfrun-late", toolCallId: "tool-late" }),
  921. workflowRunProjection({ runId: "dwfrun-early", toolCallId: "tool-early" }),
  922. ],
  923. backgroundWorks: [
  924. backgroundWork({
  925. workId: "dwfrun-late",
  926. kind: "workflow",
  927. title: "后启动",
  928. startedAt: Date.now() - 1_000,
  929. }),
  930. backgroundWork({
  931. workId: "dwfrun-early",
  932. kind: "workflow",
  933. title: "先启动",
  934. startedAt: Date.now() - 60_000,
  935. }),
  936. ],
  937. workflowSectionOpen: true,
  938. });
  939. expect(html.indexOf('data-workflow-run-id="dwfrun-late"')).toBeLessThan(
  940. html.indexOf('data-workflow-run-id="dwfrun-early"'),
  941. );
  942. });
  943. // ── 已结束的 run 折进页脚行(docs/dynamic-workflow/presentation.md「Other places a run appears」)──
  944. it("folds ended runs into a footer row that opens the run directory", async () => {
  945. const onOpenWorkflowRunDirectory = vi.fn();
  946. const { ConversationStatusPanel } = await import("@/v4/ConversationStatusPanel.js");
  947. const view = render(
  948. createElement(ConversationStatusPanel, {
  949. workspacePath: "/repo",
  950. gitSummary: null,
  951. summaryPanelVariantOverride: "panel",
  952. workflowRuns: [workflowRunProjection()],
  953. endedWorkflowRunCount: 3,
  954. parentSessionId: "parent-a",
  955. workflowSectionOpen: true,
  956. onOpenWorkflowRunDirectory,
  957. }),
  958. );
  959. const trigger = view.container.querySelector<HTMLButtonElement>(
  960. '[data-testid="workflow-run-directory-trigger"]',
  961. );
  962. expect(trigger).not.toBeNull();
  963. // 桶名刻意不是「已完成」:这个桶里也有失败与取消的 run。
  964. expect(trigger?.textContent).toContain("chat.statusPanel.endedWorkflows");
  965. expect(trigger?.textContent).toContain("3");
  966. await act(async () => trigger?.click());
  967. expect(onOpenWorkflowRunDirectory).toHaveBeenCalledWith({ parentSessionId: "parent-a" });
  968. view.unmount();
  969. });
  970. it("keeps the Workflows section when nothing is active but history exists (the restart entry)", async () => {
  971. // 重启后 workflowRuns 投影为空(memory-only)。只按活动数开门的那一版在这里整块消失,
  972. // 于是通往 run 目录的唯一入口也没了——这条用例就是钉住那个失效。
  973. const html = await renderStatusPanel({
  974. gitSummary: null,
  975. gitWorktreeChangeSummary: null,
  976. summaryPanelVariantOverride: "panel",
  977. endedWorkflowRunCount: 2,
  978. parentSessionId: "parent-a",
  979. workflowSectionOpen: true,
  980. onOpenWorkflowRunDirectory: vi.fn(),
  981. });
  982. expect(html).toContain('data-status-section="workflow"');
  983. expect(html).toContain('data-testid="workflow-run-directory-trigger"');
  984. expect(html).toContain('data-ended-workflow-count="2"');
  985. // 一行活动 run 都没有,所以不该出现任何 run 行。
  986. expect(html).not.toContain("data-workflow-run-id");
  987. });
  988. it("hides the footer row when there is no history, no session, or no host callback", async () => {
  989. const noHistory = await renderStatusPanel({
  990. gitSummary: null,
  991. gitWorktreeChangeSummary: null,
  992. summaryPanelVariantOverride: "panel",
  993. workflowRuns: [workflowRunProjection()],
  994. endedWorkflowRunCount: 0,
  995. parentSessionId: "parent-a",
  996. workflowSectionOpen: true,
  997. onOpenWorkflowRunDirectory: vi.fn(),
  998. });
  999. expect(noHistory).toContain('data-workflow-run-id="dwfrun-1"');
  1000. expect(noHistory).not.toContain("workflow-run-directory-trigger");
  1001. // 点了没反应的入口比没有入口更糟:缺会话或缺回调时整行缺席。
  1002. const noCallback = await renderStatusPanel({
  1003. gitSummary: null,
  1004. gitWorktreeChangeSummary: null,
  1005. summaryPanelVariantOverride: "panel",
  1006. workflowRuns: [workflowRunProjection()],
  1007. endedWorkflowRunCount: 5,
  1008. parentSessionId: "parent-a",
  1009. workflowSectionOpen: true,
  1010. });
  1011. expect(noCallback).not.toContain("workflow-run-directory-trigger");
  1012. const noSession = await renderStatusPanel({
  1013. gitSummary: null,
  1014. gitWorktreeChangeSummary: null,
  1015. summaryPanelVariantOverride: "panel",
  1016. workflowRuns: [workflowRunProjection()],
  1017. endedWorkflowRunCount: 5,
  1018. workflowSectionOpen: true,
  1019. onOpenWorkflowRunDirectory: vi.fn(),
  1020. });
  1021. expect(noSession).not.toContain("workflow-run-directory-trigger");
  1022. });
  1023. it("names the live run in the mini capsule instead of counting it (an ended run is not activity)", async () => {
  1024. const html = await renderStatusPanel({
  1025. gitSummary: null,
  1026. gitWorktreeChangeSummary: null,
  1027. summaryPanelVariantOverride: "mini",
  1028. workflowRuns: [workflowRunProjection()],
  1029. endedWorkflowRunCount: 7,
  1030. parentSessionId: "parent-a",
  1031. onOpenWorkflowRunDirectory: vi.fn(),
  1032. });
  1033. expect(html).toContain('data-running-workflow-count="1"');
  1034. expect(html).toContain('data-running-background-count="1"');
  1035. expect(html).toContain('data-workflow-pill="dwfrun-1"');
  1036. expect(html).toContain("chat.toolCall.workflow.fallbackName");
  1037. expect(html).not.toContain("chat.summaryPanel.runningBackgroundTasksMiniValue");
  1038. expect(html).not.toContain("chat.statusPanel.endedWorkflows");
  1039. });
  1040. // 活的工作流排在胶囊最前:它在跑时就是会话在做的事;todo / goal / git 都让位。
  1041. it("puts a live workflow ahead of the to-do, goal and git summaries in the pill", async () => {
  1042. const html = await renderStatusPanel({
  1043. summaryPanelVariantOverride: "mini",
  1044. plan: planState(),
  1045. goal: goalState(),
  1046. workflowRuns: [
  1047. phasedRunProjection(),
  1048. workflowRunProjection({ runId: "dwfrun-2", status: "pending" }),
  1049. ],
  1050. backgroundWorks: [
  1051. backgroundWork({ workId: "dwfrun-1", kind: "workflow", title: "重构状态胶囊" }),
  1052. backgroundWork({ workId: "dwfrun-2", kind: "workflow", title: "第二条" }),
  1053. ],
  1054. });
  1055. const pill = html.slice(html.indexOf("data-workflow-pill"));
  1056. expect(pill).toContain("重构状态胶囊");
  1057. expect(pill).toContain('data-workflow-run-lamp="running"');
  1058. expect(pill).toContain("计划");
  1059. expect(pill).toContain("+1");
  1060. expect(pill).not.toContain("第二条");
  1061. expect(html).not.toContain("复刻浮层");
  1062. expect(html).not.toContain("chat.statusPanel.changes");
  1063. });
  1064. // 展开后看到的不能比胶囊还少:胶囊显示着工作流时,点它展开面板并同时打开「工作流」分区——
  1065. // 哪怕读者先前手动折过它。胶囊显示别的(todo / git …)时不碰这个分区。
  1066. it("opens the Workflows section when the clicked pill was showing a workflow", async () => {
  1067. const { ConversationStatusPanel } = await import("@/v4/ConversationStatusPanel.js");
  1068. const onVariantChange = vi.fn();
  1069. const onWorkflowSectionOpenChange = vi.fn();
  1070. const view = render(
  1071. createElement(ConversationStatusPanel, {
  1072. workspacePath: "/repo",
  1073. gitSummary: null,
  1074. summaryPanelVariantOverride: "mini",
  1075. workflowRuns: [workflowRunProjection()],
  1076. workflowSectionOpen: false,
  1077. onVariantChange,
  1078. onWorkflowSectionOpenChange,
  1079. }),
  1080. );
  1081. const pill = view.container.querySelector("[data-workflow-pill]")?.closest("button");
  1082. await act(async () => pill?.click());
  1083. expect(onVariantChange).toHaveBeenCalledWith("panel");
  1084. expect(onWorkflowSectionOpenChange).toHaveBeenCalledWith(true);
  1085. view.unmount();
  1086. const onOtherSectionOpenChange = vi.fn();
  1087. const todoView = render(
  1088. createElement(ConversationStatusPanel, {
  1089. workspacePath: "/repo",
  1090. gitSummary: null,
  1091. summaryPanelVariantOverride: "mini",
  1092. plan: planState(),
  1093. onVariantChange: vi.fn(),
  1094. onWorkflowSectionOpenChange: onOtherSectionOpenChange,
  1095. }),
  1096. );
  1097. const todoPill = todoView.container.querySelector<HTMLButtonElement>(
  1098. 'button[aria-label="chat.summaryPanel.showPanel"]',
  1099. );
  1100. await act(async () => todoPill?.click());
  1101. expect(onOtherSectionOpenChange).not.toHaveBeenCalled();
  1102. todoView.unmount();
  1103. });
  1104. it("shows a degraded run in the pill by name alone, without a lamp", async () => {
  1105. const html = await renderStatusPanel({
  1106. gitSummary: null,
  1107. gitWorktreeChangeSummary: null,
  1108. summaryPanelVariantOverride: "mini",
  1109. backgroundWorks: [
  1110. backgroundWork({ workId: "dwfrun-skew", kind: "workflow", title: "旧 CLI 的 run" }),
  1111. ],
  1112. });
  1113. expect(html).toContain('data-workflow-pill="dwfrun-skew"');
  1114. expect(html).toContain("旧 CLI 的 run");
  1115. expect(html).not.toContain("data-workflow-run-lamp");
  1116. });
  1117. it("shows the ended-runs metric in the mini capsule when nothing else is alive", async () => {
  1118. // Bug 复现:工作区无 Git 变更、workflow 跑完的瞬间——卸载闸门为了 run 目录入口保留
  1119. // 壳(canRenderEndedWorkflows),但胶囊兜底链没有终态分支,渲染成一条 2px 空壳线。
  1120. const html = await renderStatusPanel({
  1121. gitSummary: null,
  1122. gitWorktreeChangeSummary: null,
  1123. summaryPanelVariantOverride: "mini",
  1124. workflowRuns: [],
  1125. endedWorkflowRunCount: 3,
  1126. parentSessionId: "parent-a",
  1127. onOpenWorkflowRunDirectory: vi.fn(),
  1128. });
  1129. expect(html).toContain('data-state="collapsed"');
  1130. expect(html).toContain("chat.statusPanel.endedWorkflows");
  1131. expect(html).toContain("3");
  1132. });
  1133. it("keeps the ended-runs metric behind the directory gate (no session or callback → no capsule text)", async () => {
  1134. // 与页脚同一条规则:目录打不开时,报数就是一个点了没反应的入口。此时 hasContent 也是
  1135. // false,整个壳按既有闸门卸载。
  1136. const html = await renderStatusPanel({
  1137. gitSummary: null,
  1138. gitWorktreeChangeSummary: null,
  1139. summaryPanelVariantOverride: "mini",
  1140. workflowRuns: [],
  1141. endedWorkflowRunCount: 3,
  1142. parentSessionId: "parent-a",
  1143. });
  1144. expect(html).not.toContain("chat.statusPanel.endedWorkflows");
  1145. expect(html).not.toContain('data-state="collapsed"');
  1146. });
  1147. it("shows the workflow pill even when terminals run beside it", async () => {
  1148. const mixedWithWorkflow = await renderStatusPanel({
  1149. gitSummary: null,
  1150. gitWorktreeChangeSummary: null,
  1151. summaryPanelVariantOverride: "mini",
  1152. workflowRuns: [workflowRunProjection()],
  1153. backgroundWorks: [backgroundWork({ workId: "bash-1", kind: "bash" })],
  1154. });
  1155. expect(mixedWithWorkflow).toContain('data-running-background-count="2"');
  1156. expect(mixedWithWorkflow).toContain('data-workflow-pill="dwfrun-1"');
  1157. expect(mixedWithWorkflow).toContain("lucide-workflow");
  1158. expect(mixedWithWorkflow).not.toContain("lucide-activity");
  1159. expect(mixedWithWorkflow).not.toContain("chat.summaryPanel.runningBackgroundTasksMiniValue");
  1160. });
  1161. it("keeps the capsule alive for a workflow run as the only content", async () => {
  1162. const html = await renderStatusPanel({
  1163. gitSummary: null,
  1164. gitWorktreeChangeSummary: null,
  1165. summaryPanelVariantOverride: "mini",
  1166. workflowRuns: [workflowRunProjection()],
  1167. });
  1168. expect(html).toContain('data-testid="chat-summary-panel"');
  1169. expect(html).toContain('data-state="collapsed"');
  1170. });
  1171. it("controls the workflow section open state and forwards manual collapse", async () => {
  1172. const onWorkflowSectionOpenChange = vi.fn();
  1173. statusPanelCapture.collapsibles = [];
  1174. const html = await renderStatusPanel({
  1175. gitSummary: null,
  1176. gitWorktreeChangeSummary: null,
  1177. summaryPanelVariantOverride: "panel",
  1178. workflowRuns: [workflowRunProjection()],
  1179. workflowSectionOpen: true,
  1180. onWorkflowSectionOpenChange,
  1181. });
  1182. expect(html).toContain('data-status-section-trigger="workflow"');
  1183. const workflow = statusPanelCapture.collapsibles.find((entry) => entry.section === "workflow");
  1184. expect(workflow?.open).toBe(true);
  1185. workflow?.onOpenChange?.(false);
  1186. expect(onWorkflowSectionOpenChange).toHaveBeenCalledWith(false);
  1187. });
  1188. it("shows realtime activity only when the capsule has no primary status", async () => {
  1189. const gitPrimary = await renderStatusPanel({
  1190. summaryPanelVariantOverride: "mini",
  1191. runningSubagents: [runningSubagent()],
  1192. });
  1193. expect(gitPrimary).toContain("chat.statusPanel.changes");
  1194. expect(gitPrimary).not.toContain("chat.summaryPanel.runningBackgroundTasksMiniValue 1");
  1195. expect(gitPrimary).not.toContain("lucide-bot");
  1196. const completedGoalPrimary = await renderStatusPanel({
  1197. gitSummary: null,
  1198. gitWorktreeChangeSummary: null,
  1199. summaryPanelVariantOverride: "mini",
  1200. goal: goalState({ status: "verified", summaryTitle: "已完成主目标" }),
  1201. backgroundWorks: [backgroundWork({ kind: "bash" })],
  1202. });
  1203. expect(completedGoalPrimary).toContain("已完成主目标");
  1204. expect(completedGoalPrimary).not.toContain(
  1205. "chat.summaryPanel.runningBackgroundTasksMiniValue 1",
  1206. );
  1207. expect(completedGoalPrimary).not.toContain("lucide-square-terminal");
  1208. });
  1209. it("keeps a notSatisfied goal visible in mini with its summary title", async () => {
  1210. const html = await renderStatusPanel({
  1211. gitSummary: null,
  1212. gitWorktreeChangeSummary: null,
  1213. summaryPanelVariantOverride: "mini",
  1214. goal: goalState({
  1215. objective: "复现用目标:总共完成 4 个 checkpoint",
  1216. summaryTitle: "四步Checkpoint复现",
  1217. status: "notSatisfied",
  1218. }),
  1219. });
  1220. expect(html).toContain('data-state="collapsed"');
  1221. expect(html).toContain('data-goal-status="notSatisfied"');
  1222. expect(html).toContain("chat.summaryPanel.showPanel");
  1223. expect(html).toContain("四步Checkpoint复现");
  1224. expect(html).not.toContain(">复现用目标:总共完成 4 个 checkpoint<");
  1225. });
  1226. it("does not keep a mini capsule alive for ended Agents alone", async () => {
  1227. const html = await renderStatusPanel({
  1228. gitSummary: null,
  1229. gitWorktreeChangeSummary: null,
  1230. summaryPanelVariantOverride: "mini",
  1231. endedSubagentCount: 3,
  1232. parentSessionId: "parent-session",
  1233. onOpenSubagentDirectory: vi.fn(),
  1234. });
  1235. expect(html).toBe("");
  1236. });
  1237. it("nests the ended directory row inside the Agent section", async () => {
  1238. const html = await renderStatusPanel({
  1239. gitSummary: null,
  1240. gitWorktreeChangeSummary: null,
  1241. summaryPanelVariantOverride: "panel",
  1242. plan: planState(),
  1243. runningSubagents: [runningSubagent()],
  1244. endedSubagentCount: 3,
  1245. rootSessionId: "root-session",
  1246. parentSessionId: "parent-session",
  1247. onOpenSubagentDirectory: vi.fn(),
  1248. });
  1249. const agentSectionStart = html.indexOf('data-status-section="agent"');
  1250. const agentSectionEnd = html.indexOf("</section>", agentSectionStart);
  1251. const endedDirectoryRow = html.indexOf("chat.statusPanel.endedAgents");
  1252. expect(agentSectionStart).toBeGreaterThanOrEqual(0);
  1253. expect(endedDirectoryRow).toBeGreaterThan(agentSectionStart);
  1254. expect(endedDirectoryRow).toBeLessThan(agentSectionEnd);
  1255. expect(html).toContain("chat.statusPanel.endedAgents");
  1256. expect(html).toContain(">3<");
  1257. });
  1258. it("keeps ended-only content inside an Agent section when another summary keeps the panel", async () => {
  1259. const html = await renderStatusPanel({
  1260. gitSummary: null,
  1261. gitWorktreeChangeSummary: null,
  1262. summaryPanelVariantOverride: "panel",
  1263. plan: planState(),
  1264. endedSubagentCount: 3,
  1265. rootSessionId: "root-session",
  1266. parentSessionId: "parent-session",
  1267. onOpenSubagentDirectory: vi.fn(),
  1268. });
  1269. const agentSectionStart = html.indexOf('data-status-section="agent"');
  1270. const agentSectionEnd = html.indexOf("</section>", agentSectionStart);
  1271. const endedDirectoryRow = html.indexOf("chat.statusPanel.endedAgents");
  1272. expect(agentSectionStart).toBeGreaterThanOrEqual(0);
  1273. expect(endedDirectoryRow).toBeGreaterThan(agentSectionStart);
  1274. expect(endedDirectoryRow).toBeLessThan(agentSectionEnd);
  1275. });
  1276. it("renders expanded panel controls and sections", async () => {
  1277. const html = await renderStatusPanel({
  1278. summaryPanelVariantOverride: "panel",
  1279. goal: goalState(),
  1280. plan: planState(),
  1281. runningSubagents: [runningSubagent()],
  1282. });
  1283. expect(html).toContain('data-state="expanded"');
  1284. expect(html).toContain("chat.summaryPanel.displayMode");
  1285. expect(html).toContain("chat.summaryPanel.displayModeAuto");
  1286. expect(html).not.toContain("chat.summaryPanel.displayModeExpanded");
  1287. expect(html).not.toContain("chat.summaryPanel.displayModeCollapsed");
  1288. expect(html).toContain("mock-git-branch-switcher");
  1289. expect(html).toContain("mock-git-action-menu");
  1290. expect(html).toContain("修好状态面板");
  1291. expect(html).toContain("复刻浮层");
  1292. expect(html).toContain("chat.statusPanel.agents");
  1293. expect(html).toContain('data-goal-status="active"');
  1294. expect(html).toContain('data-goal-objective="修好状态面板"');
  1295. expect(html).toContain('data-running-background-count="1"');
  1296. expect(html).toContain('data-status-section="agent"');
  1297. expect(html).toContain('data-status-section-trigger="agent"');
  1298. });
  1299. it("projects automatic display mode to the shell", async () => {
  1300. const html = await renderStatusPanel({
  1301. layoutMode: "auto",
  1302. summaryPanelVariantOverride: null,
  1303. });
  1304. expect(html).toContain('data-display-mode="auto"');
  1305. });
  1306. it("controls the Agent section open state and forwards manual collapse", async () => {
  1307. const onAgentSectionOpenChange = vi.fn();
  1308. statusPanelCapture.collapsibles = [];
  1309. const html = await renderStatusPanel({
  1310. gitSummary: null,
  1311. gitWorktreeChangeSummary: null,
  1312. summaryPanelVariantOverride: "panel",
  1313. runningSubagents: [runningSubagent()],
  1314. agentSectionOpen: true,
  1315. onAgentSectionOpenChange,
  1316. });
  1317. expect(html).toContain('data-status-section-trigger="agent"');
  1318. expect(html).toContain('aria-expanded="true"');
  1319. const agent = statusPanelCapture.collapsibles.find((entry) => entry.section === "agent");
  1320. expect(agent?.open).toBe(true);
  1321. agent?.onOpenChange?.(false);
  1322. expect(onAgentSectionOpenChange).toHaveBeenCalledWith(false);
  1323. });
  1324. it("labels the Agent section count as running instead of background", async () => {
  1325. const html = await renderStatusPanel({
  1326. gitSummary: null,
  1327. gitWorktreeChangeSummary: null,
  1328. summaryPanelVariantOverride: "panel",
  1329. runningSubagents: [
  1330. runningSubagent({ childSessionId: "agent-1" }),
  1331. runningSubagent({ childSessionId: "agent-2" }),
  1332. ],
  1333. agentSectionOpen: true,
  1334. });
  1335. const agentSectionStart = html.indexOf('data-status-section="agent"');
  1336. const agentSection = html.slice(
  1337. agentSectionStart,
  1338. html.indexOf("</section>", agentSectionStart),
  1339. );
  1340. expect(agentSection).toContain("chat.statusPanel.runningAgentsValuePlural 2");
  1341. expect(agentSection).not.toContain("chat.summaryPanel.runningBackgroundTasksMiniValuePlural 2");
  1342. });
  1343. it("renders active elapsed, pause control, and every iteration action/status", async () => {
  1344. const html = await renderStatusPanel({
  1345. gitSummary: null,
  1346. gitWorktreeChangeSummary: null,
  1347. summaryPanelVariantOverride: "panel",
  1348. onPauseGoal: vi.fn(),
  1349. goal: goalState({
  1350. summaryTitle: "第一轮:恢复摘要",
  1351. timeUsedSeconds: 9,
  1352. iteration: 1,
  1353. verifications: [
  1354. {
  1355. iteration: 1,
  1356. outcome: "notSatisfied",
  1357. at: 1_700_000_000_000,
  1358. anchorRowId: null,
  1359. reason: "还缺状态",
  1360. nextAction: "第二轮:补暂停和完成态",
  1361. },
  1362. ],
  1363. iterations: [
  1364. {
  1365. iteration: 1,
  1366. updatedAt: 1_700_000_000_000,
  1367. items: [{ id: "one", content: "恢复计时", status: "completed" }],
  1368. },
  1369. {
  1370. iteration: 2,
  1371. updatedAt: 1_700_000_001_000,
  1372. items: [
  1373. { id: "two", content: "恢复按钮", status: "inProgress" },
  1374. { id: "three", content: "验证状态", status: "pending" },
  1375. ],
  1376. },
  1377. ],
  1378. }),
  1379. });
  1380. expect(html).toContain("9秒");
  1381. expect(html).toContain('data-goal-action="pause"');
  1382. expect(html).toContain("第一轮:恢复摘要");
  1383. expect(html).toContain("第二轮:补暂停和完成态");
  1384. expect(html).toContain('data-goal-iteration="1"');
  1385. expect(html).toContain('data-goal-iteration-completed="true"');
  1386. expect(html).toContain("0/2");
  1387. });
  1388. it("renders paused play and verified green check as mutually exclusive controls", async () => {
  1389. const paused = await renderStatusPanel({
  1390. gitSummary: null,
  1391. gitWorktreeChangeSummary: null,
  1392. summaryPanelVariantOverride: "panel",
  1393. onResumeGoal: vi.fn(),
  1394. goal: goalState({ status: "paused", timeUsedSeconds: 12 }),
  1395. });
  1396. expect(paused).toContain('data-goal-action="resume"');
  1397. expect(paused).not.toContain('data-goal-action="pause"');
  1398. const verified = await renderStatusPanel({
  1399. gitSummary: null,
  1400. gitWorktreeChangeSummary: null,
  1401. summaryPanelVariantOverride: "panel",
  1402. goal: goalState({ status: "verified", timeUsedSeconds: 18 }),
  1403. });
  1404. expect(verified).toContain("chat.goalVerification.complete");
  1405. expect(verified).not.toContain("data-goal-action=");
  1406. });
  1407. it("does not append verifier reason cards after visible iteration actions", async () => {
  1408. const html = await renderStatusPanel({
  1409. gitSummary: null,
  1410. gitWorktreeChangeSummary: null,
  1411. summaryPanelVariantOverride: "panel",
  1412. goal: goalState({
  1413. iteration: 1,
  1414. verifications: [
  1415. {
  1416. iteration: 1,
  1417. outcome: "notSatisfied",
  1418. at: 1_700_000_000_000,
  1419. anchorRowId: null,
  1420. reason: "这段 verifier reason 不应出现在右上角灰卡",
  1421. nextAction: "继续第二轮 action",
  1422. },
  1423. ],
  1424. }),
  1425. });
  1426. expect(html).toContain("继续第二轮 action");
  1427. expect(html).not.toContain("这段 verifier reason 不应出现在右上角灰卡");
  1428. });
  1429. it("restores Stop only for projected Agents with an exact background control match", async () => {
  1430. const html = await renderStatusPanel({
  1431. gitSummary: null,
  1432. gitWorktreeChangeSummary: null,
  1433. summaryPanelVariantOverride: "panel",
  1434. onCancelBackgroundWork: vi.fn(),
  1435. backgroundWorks: [
  1436. backgroundWork({
  1437. workId: "bash-newer",
  1438. kind: "bash",
  1439. title: "启动开发服务器",
  1440. startedAt: Date.now() - 3_000,
  1441. cancellable: false,
  1442. }),
  1443. backgroundWork({
  1444. workId: "agent-control-work",
  1445. kind: "subagent",
  1446. childSessionId: "agent-older",
  1447. title: "packages结构分析",
  1448. cancellable: true,
  1449. }),
  1450. backgroundWork({
  1451. workId: "agent-disabled-work",
  1452. kind: "subagent",
  1453. childSessionId: "agent-disabled",
  1454. title: "不可停止的 Agent",
  1455. cancellable: false,
  1456. }),
  1457. ],
  1458. runningSubagents: [
  1459. runningSubagent({
  1460. childSessionId: "agent-older",
  1461. title: "packages结构分析",
  1462. startedAt: Date.now() - 9_000,
  1463. }),
  1464. runningSubagent({
  1465. childSessionId: "agent-disabled",
  1466. title: "不可停止的 Agent",
  1467. }),
  1468. runningSubagent({
  1469. childSessionId: "foreground-agent",
  1470. title: "同名但无 background control",
  1471. }),
  1472. ],
  1473. });
  1474. expect(html).toContain('data-background-task-kind="bash"');
  1475. expect(html).toContain('data-background-task-kind="agent"');
  1476. expect(html).toContain('data-child-session-id="agent-older"');
  1477. expect(html).toContain('data-work-id="agent-control-work"');
  1478. expect(html).toContain('data-work-status="running"');
  1479. expect(html).toContain('data-testid="v4-background-work-item-agent-control-work"');
  1480. expect(html).toContain('data-status-section="terminal"');
  1481. expect(html).toContain('data-status-section="agent"');
  1482. expect(html).toContain("chat.statusPanel.terminals");
  1483. expect(html).toContain("chat.statusPanel.agents");
  1484. expect(html).toContain("lucide-bot");
  1485. expect(html).toContain("lucide-square-terminal");
  1486. expect(html).not.toContain("subagent · packages结构分析");
  1487. expect(html).not.toContain("bash · 启动开发服务器");
  1488. expect(html).toContain("chat.longRunning.elapsedSeconds 9");
  1489. expect(html).toContain("flex-wrap");
  1490. expect(html).toContain('data-testid="v4-background-work-cancel-agent-control-work"');
  1491. expect(html).not.toContain('data-testid="v4-background-work-cancel-agent-older"');
  1492. expect(html).not.toContain('data-testid="v4-background-work-cancel-agent-disabled-work"');
  1493. expect(html).not.toContain('data-testid="v4-background-work-cancel-foreground-agent"');
  1494. expect(html).not.toContain('data-testid="v4-background-work-cancel-bash-newer"');
  1495. const terminalSection = html.slice(
  1496. html.indexOf('data-status-section="terminal"'),
  1497. html.indexOf('data-status-section="agent"'),
  1498. );
  1499. expect(terminalSection).toContain("启动开发服务器");
  1500. expect(terminalSection).not.toContain("packages结构分析");
  1501. const agentSection = html.slice(html.indexOf('data-status-section="agent"'));
  1502. expect(agentSection).toContain("packages结构分析");
  1503. expect(agentSection).not.toContain("启动开发服务器");
  1504. });
  1505. it("turns projected running Agents into child-session triggers", async () => {
  1506. const addressableSubagent = runningSubagent({
  1507. childSessionId: "child-addressable",
  1508. });
  1509. const html = await renderStatusPanel({
  1510. gitSummary: null,
  1511. gitWorktreeChangeSummary: null,
  1512. summaryPanelVariantOverride: "panel",
  1513. parentSessionId: "parent-session",
  1514. rootSessionId: "root-session",
  1515. onOpenSubagentSession: vi.fn(),
  1516. runningSubagents: [
  1517. addressableSubagent,
  1518. runningSubagent({ childSessionId: "child-second", title: "第二个 Agent" }),
  1519. ],
  1520. });
  1521. const { buildRunningSubagentOpenRequest } = await import("@/v4/ConversationStatusPanel.js");
  1522. expect(html.match(/data-running-subagent-session-trigger="true"/g)).toHaveLength(2);
  1523. expect(html).toContain('data-child-session-id="child-addressable"');
  1524. expect(
  1525. buildRunningSubagentOpenRequest({
  1526. parentSessionId: "parent-session",
  1527. rootSessionId: "root-session",
  1528. subagent: addressableSubagent,
  1529. }),
  1530. ).toEqual({
  1531. rootSessionId: "root-session",
  1532. parentSessionId: "parent-session",
  1533. childSessionId: "child-addressable",
  1534. subagentType: "Explore",
  1535. title: "探索渲染逻辑",
  1536. });
  1537. });
  1538. it("bounds all six long status section types and keeps long Todos behind expansion", async () => {
  1539. const todoItems = Array.from({ length: 8 }, (_, index) => ({
  1540. id: `todo-${index + 1}`,
  1541. content: `Todo 第 ${index + 1} 项`,
  1542. status: index === 0 ? ("inProgress" as const) : ("pending" as const),
  1543. }));
  1544. const html = await renderStatusPanel({
  1545. summaryPanelVariantOverride: "panel",
  1546. goal: goalState({
  1547. iterations: Array.from({ length: 8 }, (_, index) => ({
  1548. iteration: index + 1,
  1549. updatedAt: 1_700_000_000_000 + index,
  1550. items: [],
  1551. })),
  1552. }),
  1553. sessionPlans: Array.from({ length: 8 }, (_, index) =>
  1554. sessionPlan(index + 1, `# 计划第 ${index + 1} 项`),
  1555. ),
  1556. plan: planState({ items: todoItems }),
  1557. backgroundWorks: [
  1558. backgroundWork({ workId: "bash-1", kind: "bash", title: "终端任务一" }),
  1559. backgroundWork({ workId: "bash-2", kind: "bash", title: "终端任务二" }),
  1560. backgroundWork({ workId: "dwfrun-1", kind: "workflow", title: "工作流一" }),
  1561. ],
  1562. workflowRuns: [workflowRunProjection()],
  1563. runningSubagents: [
  1564. runningSubagent({ childSessionId: "agent-1", title: "智能体一" }),
  1565. runningSubagent({ childSessionId: "agent-2", title: "智能体二" }),
  1566. ],
  1567. terminalSectionOpen: true,
  1568. workflowSectionOpen: true,
  1569. agentSectionOpen: true,
  1570. });
  1571. for (const section of ["goal", "sessionPlans", "plan", "terminal", "workflow", "agent"]) {
  1572. expect(html).toContain(`data-status-section-scroll="${section}"`);
  1573. }
  1574. expect(html).not.toContain('data-status-section-scroll="environment"');
  1575. expect(html).toContain("max-h-80 min-h-0 overflow-x-hidden overflow-y-auto pr-1");
  1576. expect(html).toContain("max-h-48 min-h-0 overflow-x-hidden overflow-y-auto pr-1");
  1577. expect(html).toContain("max-h-[min(64dvh,32rem)]");
  1578. expect(html).toContain(
  1579. "min-h-0 flex-1 flex-col gap-2 overflow-x-hidden overflow-y-auto p-2 flex",
  1580. );
  1581. for (const item of todoItems) {
  1582. expect(html).toContain(item.content);
  1583. }
  1584. expect(html).toContain('data-status-todo-preview-trigger="following"');
  1585. expect(html).toContain('data-status-todo-preview-content="following"');
  1586. expect(html).toContain('data-side="left"');
  1587. expect(html).toContain('data-align="start"');
  1588. expect(html).toContain('data-side-offset="4"');
  1589. expect(html).toContain("flex max-h-[min(24rem,calc(100dvh-2rem))] min-w-0 flex-col");
  1590. expect(html).toContain("min-h-0 space-y-0 overflow-y-auto pr-1");
  1591. expect(html).toContain("chat.statusPanel.todoWaitingFold 5");
  1592. expect(html).toContain(
  1593. "rounded-lg px-2 text-left text-ui-base text-[var(--color-foreground-subtle)]",
  1594. );
  1595. expect(statusPanelCapture.hoverCards).toContainEqual(
  1596. expect.objectContaining({
  1597. closeDelay: 80,
  1598. open: false,
  1599. openDelay: 120,
  1600. }),
  1601. );
  1602. });
  1603. it("keeps a long Agent viewport bounded beside short Progress and Plans sections", async () => {
  1604. const agents = Array.from({ length: 5 }, (_, index) =>
  1605. runningSubagent({
  1606. childSessionId: `mixed-agent-${index + 1}`,
  1607. title: `Background sleep agent ${index + 1}`,
  1608. }),
  1609. );
  1610. const html = await renderStatusPanel({
  1611. gitSummary: null,
  1612. gitWorktreeChangeSummary: null,
  1613. summaryPanelVariantOverride: "panel",
  1614. sessionPlans: [sessionPlan(1, "# 组合场景计划")],
  1615. plan: planState({
  1616. items: [{ id: "short-progress", content: "你好", status: "inProgress" }],
  1617. }),
  1618. runningSubagents: agents,
  1619. agentSectionOpen: true,
  1620. });
  1621. for (const section of ["sessionPlans", "plan", "agent"]) {
  1622. expect(html).toContain(`data-status-section-scroll="${section}"`);
  1623. }
  1624. for (const agent of agents) {
  1625. expect(html).toContain(agent.title);
  1626. }
  1627. expect(html).toContain("max-h-80 min-h-0 overflow-x-hidden overflow-y-auto pr-1");
  1628. expect(html).toContain("max-h-48 min-h-0 overflow-x-hidden overflow-y-auto pr-1");
  1629. });
  1630. it("maps the display mode menu back to nullable shell override", async () => {
  1631. statusPanelCapture.radioGroups = [];
  1632. const onVariantChange = vi.fn();
  1633. vi.stubGlobal("window", {
  1634. innerWidth: 1200,
  1635. addEventListener: vi.fn(),
  1636. removeEventListener: vi.fn(),
  1637. });
  1638. try {
  1639. await renderStatusPanel({
  1640. summaryPanelVariantOverride: null,
  1641. onVariantChange,
  1642. });
  1643. } finally {
  1644. vi.unstubAllGlobals();
  1645. }
  1646. expect(statusPanelCapture.radioGroups).toHaveLength(1);
  1647. expect(statusPanelCapture.radioGroups[0]?.value).toBe("auto");
  1648. statusPanelCapture.radioGroups[0]?.onValueChange?.("mini");
  1649. expect(onVariantChange).toHaveBeenLastCalledWith("mini");
  1650. statusPanelCapture.radioGroups[0]?.onValueChange?.("auto");
  1651. expect(onVariantChange).toHaveBeenLastCalledWith(null);
  1652. });
  1653. });