v4ConversationStatusPanel.test.ts 72 KB

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