v4SessionPaneLayoutParity.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. import { createElement } from "react";
  2. import { renderToStaticMarkup } from "react-dom/server";
  3. import { describe, expect, it, vi } from "vitest";
  4. import type {
  5. ConversationSnapshot,
  6. PendingInteraction,
  7. SubagentRow,
  8. UserInputRow,
  9. } from "@zcode/shared/zcode-protocol-v4";
  10. import { SessionPane } from "@/v4/SessionPane.js";
  11. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  12. import type {
  13. OpenScopedSubagentSideTabRequest,
  14. OpenScopedWorkflowRunSideTabRequest,
  15. } from "@/lib/workspaceSidePane.js";
  16. const projectionState = vi.hoisted(() => ({
  17. current: null as {
  18. status: "live";
  19. snapshot: ConversationSnapshot;
  20. subscriptionId: string;
  21. lastError: string | null;
  22. optimisticCommands: readonly [];
  23. loadingOlder: boolean;
  24. } | null,
  25. }));
  26. const statusPanelCapture = vi.hoisted(() => ({
  27. composerProps: [] as Array<Record<string, unknown>>,
  28. props: [] as Array<Record<string, unknown>>,
  29. }));
  30. const conversationTelemetryState = vi.hoisted(() => ({
  31. current: null as null | {
  32. acceptPromptSeed: ReturnType<typeof vi.fn>;
  33. attachForeground: ReturnType<typeof vi.fn>;
  34. },
  35. }));
  36. // Bugfix:本文件只验证 SessionPane 布局骨架,隔离闲时入口对真实 TabStore 的依赖。
  37. vi.mock("@/v4/OffPeakNewTaskEntry.js", () => ({
  38. OffPeakNewTaskEntry: () => null,
  39. }));
  40. // 同理隔离推荐提示词容器:它通过 useWorkspaceServicesResolution 依赖 TabStoreProvider,
  41. // 而本文件只挂 SessionPane 验证布局,不提供 Tab store。
  42. vi.mock("@/v4/ConversationDraftSuggestedPromptsContainer.js", () => ({
  43. ConversationDraftSuggestedPromptsContainer: () => null,
  44. }));
  45. vi.mock("@/v4/telemetry/ConversationTelemetryAttachment.js", () => ({
  46. useScopedConversationTelemetrySupervisor: () => conversationTelemetryState.current,
  47. useScopedConversationTelemetryForegroundEnabled: () =>
  48. conversationTelemetryState.current !== null,
  49. }));
  50. vi.mock("@/v4/useConversationProjection.js", () => ({
  51. useConversationProjection: () => projectionState.current,
  52. }));
  53. vi.mock("@/v4/V4ConversationContext.js", () => ({
  54. useV4Conversation: () => ({
  55. layer: {
  56. acquire: vi.fn(),
  57. },
  58. sendCommand: vi.fn(),
  59. attachmentPut: vi.fn(),
  60. }),
  61. }));
  62. vi.mock("@/store/StoreProvider.js", () => ({
  63. useZCodeStoreWithDefault: (_selector: unknown, fallback: unknown) => fallback,
  64. }));
  65. vi.mock("@/hooks/useSettingService.js", () => ({
  66. useSettings: () => ({
  67. settings: { zcodeInteractionBehavior: "queue" },
  68. loading: false,
  69. error: null,
  70. update: vi.fn(async () => {}),
  71. refresh: vi.fn(async () => {}),
  72. }),
  73. }));
  74. vi.mock("@/hooks/useServices.js", () => ({
  75. useComposerClientNamespace: () => "desktop",
  76. useOptionalServices: () => null,
  77. useServices: () => ({
  78. zcodeSessionService: {},
  79. zcodeTaskService: {
  80. restartWorkspaceProcess: vi.fn(),
  81. },
  82. }),
  83. }));
  84. vi.mock("@/v4/composer/useDraftConfigControl.js", () => ({
  85. buildDraftCreateConfigPayload: () => ({}),
  86. useDraftConfigControl: () => ({
  87. modelSelectionRead: { state: { status: "loading" }, reload: vi.fn() },
  88. captureAcceptedModelSelection: () => vi.fn(),
  89. draftConfig: {},
  90. draftConfigRef: { current: {} },
  91. resolveInitialDraftConfig: vi.fn(() => ({})),
  92. acceptAuthoritativeDraftModelConfig: vi.fn(),
  93. handleDraftSelectModel: vi.fn(),
  94. handleDraftSelectThought: vi.fn(),
  95. handleDraftSwitchMode: vi.fn(),
  96. }),
  97. }));
  98. vi.mock("@/v4/composer/useDraftSessionPrewarm.js", () => ({
  99. useDraftSessionPrewarm: () => ({
  100. binding: null,
  101. }),
  102. }));
  103. vi.mock("@/v4/ConversationComposer.js", async () => {
  104. const React = await import("react");
  105. return {
  106. ConversationComposer: (props: Record<string, unknown>) => {
  107. statusPanelCapture.composerProps.push(props);
  108. return React.createElement(
  109. "div",
  110. {
  111. "data-testid": "mock-composer",
  112. "data-blocking-request-id": (props.blockingRequestId as string | null) ?? "",
  113. "data-centered": props.centered ? "true" : "false",
  114. "data-draft-mode": props.draftMode ? "true" : "false",
  115. },
  116. "composer",
  117. );
  118. },
  119. };
  120. });
  121. vi.mock("@/v4/ConversationHeader.js", async () => {
  122. const React = await import("react");
  123. return {
  124. ConversationHeader: () => React.createElement("div", { "data-testid": "mock-header" }),
  125. };
  126. });
  127. vi.mock("@/v4/ConversationStatusPanel.js", async () => {
  128. const React = await import("react");
  129. return {
  130. ConversationStatusPanel: (props: Record<string, unknown>) => {
  131. statusPanelCapture.props.push(props);
  132. return React.createElement("div", { "data-testid": "mock-status" });
  133. },
  134. };
  135. });
  136. vi.mock("@/v4/ConversationQueuePanel.js", async () => {
  137. const React = await import("react");
  138. return {
  139. ConversationQueuePanel: () => React.createElement("div", { "data-testid": "mock-queue" }),
  140. };
  141. });
  142. vi.mock("@/v4/V4InteractionDialogs.js", async () => {
  143. const React = await import("react");
  144. return {
  145. V4InteractionDialogs: () => React.createElement("div", { "data-testid": "mock-interactions" }),
  146. };
  147. });
  148. vi.mock("@/request-security-edition/V4ProviderRuntimeHeadersController.js", async () => {
  149. const React = await import("react");
  150. return {
  151. V4ProviderRuntimeHeadersController: () =>
  152. React.createElement("div", { "data-testid": "mock-runtime-headers" }),
  153. };
  154. });
  155. vi.mock("@/v4/ConversationDraftEmptyState.js", async () => {
  156. const React = await import("react");
  157. return {
  158. ConversationDraftEmptyState: (props: { compactForRemoteControl?: boolean }) =>
  159. React.createElement("div", {
  160. "data-testid": "mock-draft-empty",
  161. "data-compact-remote": props.compactForRemoteControl ? "true" : "false",
  162. }),
  163. };
  164. });
  165. vi.mock("@/v4/ConversationTurnGroup.js", async () => {
  166. const React = await import("react");
  167. return {
  168. ConversationTurnGroup: () => React.createElement("div", { "data-testid": "mock-turn-group" }),
  169. };
  170. });
  171. function userInputRow(): UserInputRow {
  172. return {
  173. rowId: 1,
  174. turnId: "turn-1",
  175. createdAt: 1_777_777_777,
  176. createdAtSeq: 1,
  177. kind: "userInput",
  178. text: "hello",
  179. origin: "realUser",
  180. };
  181. }
  182. function subagentRow(overrides: Partial<SubagentRow> = {}): SubagentRow {
  183. return {
  184. rowId: 2,
  185. turnId: "turn-1",
  186. createdAt: 1_777_777_778,
  187. createdAtSeq: 2,
  188. kind: "subagent",
  189. subagentType: "Explore",
  190. status: "running",
  191. summaryText: "正在后台探索",
  192. backgrounded: true,
  193. workId: "work-agent",
  194. childSessionId: "child-session",
  195. ...overrides,
  196. };
  197. }
  198. function pendingPermissionInteraction(): PendingInteraction {
  199. return {
  200. interactionId: "perm-1",
  201. kind: "permission",
  202. anchorRowId: null,
  203. createdAt: 1_777_777_778,
  204. payload: {
  205. kind: "permission",
  206. toolCallId: "tool-call-1",
  207. toolName: "Bash",
  208. summary: "Tool has side effects and requires approval",
  209. detail: { command: "touch quickSort.js" },
  210. options: [
  211. { optionId: "allow_once", label: "允许", kind: "allowOnce" },
  212. { optionId: "allow_always", label: "始终允许", kind: "allowAlways" },
  213. { optionId: "deny", label: "拒绝", kind: "deny" },
  214. ],
  215. },
  216. };
  217. }
  218. function pendingStructuredUserInputInteraction(): PendingInteraction {
  219. return {
  220. interactionId: "ask-1",
  221. kind: "userInput",
  222. anchorRowId: null,
  223. createdAt: 1_777_777_779,
  224. payload: {
  225. kind: "userInput",
  226. prompt: "选择实现形式",
  227. freeText: false,
  228. toolName: "AskUserQuestion",
  229. toolCallId: "tool-call-ask-1",
  230. questions: [
  231. {
  232. question: "你想把这个番茄时钟作为什么形式存在?",
  233. header: "形式",
  234. options: [
  235. { value: "page", label: "独立新页面", description: "通过导航访问" },
  236. { value: "widget", label: "独立小工具视图", description: "可复用组件" },
  237. ],
  238. },
  239. ],
  240. },
  241. };
  242. }
  243. function makeSnapshot(overrides: Partial<ConversationSnapshot> = {}): ConversationSnapshot {
  244. const snapshot: ConversationSnapshot = {
  245. protocolVersion: 1,
  246. sessionId: "session-1",
  247. logEpoch: "epoch-1",
  248. seq: 1,
  249. revision: 1,
  250. control: {
  251. phase: "completedSuccess",
  252. sessionEnded: true,
  253. canStop: false,
  254. stopState: "idle",
  255. stopTargetKind: "unknown",
  256. activeWorks: [],
  257. lastError: null,
  258. apiRetry: null,
  259. },
  260. availability: {
  261. fork: { allowed: true },
  262. compact: { allowed: true },
  263. switchModelConfig: { allowed: true },
  264. setFollowupMode: { allowed: true },
  265. queueEdit: { allowed: true },
  266. sendQueuedNow: { allowed: true },
  267. pauseGoal: { allowed: false, reasonCode: "noGoalToPause" },
  268. resumeGoal: { allowed: false, reasonCode: "noGoalToResume" },
  269. },
  270. inputRouting: { mode: "startNow" },
  271. meta: { title: "Session", titleSource: "generated" },
  272. config: { provider: "", model: "", thought: "", followupMode: "queue" },
  273. usage: {
  274. contextWindow: null,
  275. cumulative: {
  276. inputTokens: 0,
  277. outputTokens: 0,
  278. cacheReadTokens: 0,
  279. cacheWriteTokens: 0,
  280. },
  281. },
  282. queue: { items: [], autoDrain: true },
  283. pendingInteractions: [],
  284. pendingCommands: [],
  285. backgroundWorks: [],
  286. goal: null,
  287. plan: null,
  288. rows: { window: [userInputRow()], totalCount: 1, firstRowId: 1 },
  289. };
  290. return { ...snapshot, ...overrides };
  291. }
  292. function renderPane({
  293. compactForRemoteControl = false,
  294. onOpenSubagentSession,
  295. onOpenWorkflowRun,
  296. onSummaryPanelVariantOverrideChange,
  297. snapshot = makeSnapshot(),
  298. sessionId = "session-1",
  299. }: {
  300. compactForRemoteControl?: boolean;
  301. onOpenSubagentSession?: (request: OpenScopedSubagentSideTabRequest) => void;
  302. onOpenWorkflowRun?: (request: OpenScopedWorkflowRunSideTabRequest) => void;
  303. onSummaryPanelVariantOverrideChange?: (variant: "panel" | "mini" | null) => void;
  304. snapshot?: ConversationSnapshot;
  305. sessionId?: string | null;
  306. } = {}): string {
  307. statusPanelCapture.props = [];
  308. statusPanelCapture.composerProps = [];
  309. projectionState.current = {
  310. status: "live",
  311. snapshot,
  312. subscriptionId: "sub-1",
  313. lastError: null,
  314. optimisticCommands: [],
  315. loadingOlder: false,
  316. };
  317. return renderToStaticMarkup(
  318. createElement(
  319. ZCodeIntlProvider,
  320. { initialLocale: "zh-CN" },
  321. createElement(SessionPane, {
  322. paneId: "workspace-main",
  323. sessionId,
  324. workspacePath: "/workspace",
  325. compactForRemoteControl,
  326. ...(onOpenSubagentSession ? { onOpenSubagentSession } : {}),
  327. ...(onOpenWorkflowRun ? { onOpenWorkflowRun } : {}),
  328. ...(onSummaryPanelVariantOverrideChange ? { onSummaryPanelVariantOverrideChange } : {}),
  329. }),
  330. ),
  331. );
  332. }
  333. describe("SessionPane v4 chat layout parity", () => {
  334. it("renders the draft greeting and the composer in the shared timeline viewport", () => {
  335. const html = renderPane({ sessionId: null });
  336. expect(html).toContain('data-v4-conversation-drop-target="true"');
  337. expect(html).toContain('data-v4-timeline-scroll="true"');
  338. expect(html).toContain('data-testid="mock-draft-empty"');
  339. expect(html).toContain('data-v4-composer-dock="true"');
  340. expect(html).toContain('data-compact-remote="false"');
  341. expect(html).toContain('data-draft-mode="true"');
  342. expect(html).toContain('data-centered="true"');
  343. });
  344. it("passes compact remote draft mode to the empty state", () => {
  345. const html = renderPane({ sessionId: null, compactForRemoteControl: true });
  346. expect(html).toContain('data-compact-remote="true"');
  347. });
  348. it("keeps a bound empty session blank while preserving the bottom composer dock", () => {
  349. const html = renderPane({
  350. snapshot: makeSnapshot({
  351. rows: { window: [], totalCount: 0, firstRowId: null },
  352. }),
  353. });
  354. expect(html).toContain('data-v4-timeline-scroll="true"');
  355. expect(html).toContain('data-v4-composer-dock="true"');
  356. expect(html).toContain('data-testid="mock-composer"');
  357. expect(html).not.toContain("v4-timeline-empty");
  358. expect(html).not.toContain("发送第一条消息开始对话");
  359. });
  360. it("renders the composer after the timeline viewport and inside its dock", () => {
  361. const html = renderPane();
  362. expect(html).toContain('data-v4-timeline-scroll="true"');
  363. expect(html).toContain('data-v4-timeline-content-column="true"');
  364. expect(html).toContain('data-v4-composer-dock="true"');
  365. expect(html.indexOf('data-v4-timeline-scroll="true"')).toBeLessThan(
  366. html.indexOf('data-v4-composer-dock="true"'),
  367. );
  368. expect(html.indexOf('data-v4-composer-dock="true"')).toBeLessThan(
  369. html.indexOf('data-testid="mock-composer"'),
  370. );
  371. });
  372. it("anchors the back-to-bottom control to the composer dock above input", () => {
  373. const html = renderPane();
  374. expect(html).toContain('data-v4-back-to-bottom-anchor="composer-dock"');
  375. expect(html.indexOf('data-v4-composer-dock="true"')).toBeLessThan(
  376. html.indexOf('data-v4-back-to-bottom-anchor="composer-dock"'),
  377. );
  378. expect(html.indexOf('data-v4-back-to-bottom-anchor="composer-dock"')).toBeLessThan(
  379. html.indexOf('data-testid="mock-composer"'),
  380. );
  381. });
  382. it("renders pending permission before the composer inside the composer dock", () => {
  383. conversationTelemetryState.current = {
  384. acceptPromptSeed: vi.fn(),
  385. attachForeground: vi.fn(() => () => {}),
  386. };
  387. const html = renderPane({
  388. snapshot: makeSnapshot({
  389. pendingInteractions: [pendingPermissionInteraction()],
  390. }),
  391. });
  392. conversationTelemetryState.current = null;
  393. const dockIndex = html.indexOf('data-v4-composer-dock="true"');
  394. const interactionIndex = html.indexOf('data-testid="mock-interactions"');
  395. const composerIndex = html.indexOf('data-testid="mock-composer"');
  396. expect(dockIndex).toBeGreaterThanOrEqual(0);
  397. expect(interactionIndex).toBeGreaterThanOrEqual(0);
  398. expect(composerIndex).toBeGreaterThanOrEqual(0);
  399. expect(dockIndex).toBeLessThan(interactionIndex);
  400. expect(interactionIndex).toBeLessThan(composerIndex);
  401. // 2026-08-17:Start Plan runtime headers 应答方已迁出 SessionPane,改由 Root 的
  402. // V4WorkspaceProviderRuntimeHeadersBridge 按 workspace 常驻挂载(web 远控新建会话
  403. // 在桌面没有 pane 时也必须有应答方),pane 内不再渲染该控制器。
  404. expect(html).not.toContain('data-testid="mock-runtime-headers"');
  405. expect(html).toContain('data-blocking-request-id="perm-1"');
  406. });
  407. for (const compactForRemoteControl of [false, true]) {
  408. it.each([
  409. ["permission", [pendingPermissionInteraction()]],
  410. ["user input", [pendingStructuredUserInputInteraction()]],
  411. ["mixed requests", [pendingPermissionInteraction(), pendingStructuredUserInputInteraction()]],
  412. ])(
  413. `keeps %s in the bottom dock without a top notice (remote=${compactForRemoteControl})`,
  414. (_label, pendingInteractions) => {
  415. const html = renderPane({
  416. compactForRemoteControl,
  417. snapshot: makeSnapshot({ pendingInteractions }),
  418. });
  419. // 待处理请求已有底部卡片,顶部不再重复展示 warning 和跳转入口。
  420. expect(html).not.toContain('data-testid="v4-pending-interaction-top-notice"');
  421. const dockIndex = html.indexOf('data-v4-composer-dock="true"');
  422. const interactionIndex = html.indexOf('data-testid="mock-interactions"');
  423. const composerIndex = html.indexOf('data-testid="mock-composer"');
  424. expect(dockIndex).toBeGreaterThanOrEqual(0);
  425. expect(interactionIndex).toBeGreaterThan(dockIndex);
  426. expect(composerIndex).toBeGreaterThan(interactionIndex);
  427. },
  428. );
  429. }
  430. it("普通 Web 没有 desktop-continuous attachment 时不挂一次性 runtime header controller", () => {
  431. conversationTelemetryState.current = null;
  432. const html = renderPane();
  433. expect(html).not.toContain('data-testid="mock-runtime-headers"');
  434. });
  435. it("renders structured user input before the composer inside the composer dock", () => {
  436. const html = renderPane({
  437. snapshot: makeSnapshot({
  438. pendingInteractions: [pendingStructuredUserInputInteraction()],
  439. }),
  440. });
  441. const dockIndex = html.indexOf('data-v4-composer-dock="true"');
  442. const interactionIndex = html.indexOf('data-testid="mock-interactions"');
  443. const composerIndex = html.indexOf('data-testid="mock-composer"');
  444. expect(dockIndex).toBeGreaterThanOrEqual(0);
  445. expect(interactionIndex).toBeGreaterThanOrEqual(0);
  446. expect(composerIndex).toBeGreaterThanOrEqual(0);
  447. expect(dockIndex).toBeLessThan(interactionIndex);
  448. expect(interactionIndex).toBeLessThan(composerIndex);
  449. expect(html).toContain('data-blocking-request-id="ask-1"');
  450. });
  451. it("selects automatic status panel layout for an active goal", () => {
  452. vi.stubGlobal("window", {
  453. innerWidth: 1280,
  454. addEventListener: vi.fn(),
  455. removeEventListener: vi.fn(),
  456. });
  457. try {
  458. const html = renderPane({
  459. snapshot: makeSnapshot({
  460. goal: {
  461. targetId: "goal-inline",
  462. objective: "Keep status panel inline with the conversation column",
  463. summaryTitle: null,
  464. timeUsedSeconds: 0,
  465. activeRunStartedAtMs: null,
  466. status: "active",
  467. iteration: 1,
  468. verifications: [],
  469. iterations: [],
  470. },
  471. }),
  472. });
  473. expect(html).toContain('data-v4-timeline-content-column="true"');
  474. expect(html).toContain('data-v4-composer-dock="true"');
  475. expect(statusPanelCapture.props.at(-1)?.layoutMode).toBe("auto");
  476. } finally {
  477. vi.unstubAllGlobals();
  478. }
  479. });
  480. it("wires pause/resume callbacks only from authoritative goal availability", () => {
  481. const active = makeSnapshot();
  482. active.goal = {
  483. targetId: "goal-controls",
  484. objective: "Restore goal controls",
  485. summaryTitle: null,
  486. timeUsedSeconds: 3,
  487. activeRunStartedAtMs: null,
  488. status: "active",
  489. iteration: 0,
  490. verifications: [],
  491. iterations: [],
  492. };
  493. active.availability = {
  494. ...active.availability,
  495. pauseGoal: { allowed: true },
  496. resumeGoal: { allowed: false, reasonCode: "goalNotPaused" },
  497. };
  498. renderPane({ snapshot: active });
  499. expect(statusPanelCapture.props.at(-1)?.onPauseGoal).toEqual(expect.any(Function));
  500. expect(statusPanelCapture.props.at(-1)?.onResumeGoal).toBeUndefined();
  501. const paused = makeSnapshot({
  502. goal: { ...active.goal, status: "paused" },
  503. availability: {
  504. ...active.availability,
  505. pauseGoal: { allowed: false, reasonCode: "goalNotActive" },
  506. resumeGoal: { allowed: true },
  507. },
  508. });
  509. renderPane({ snapshot: paused });
  510. expect(statusPanelCapture.props.at(-1)?.onPauseGoal).toBeUndefined();
  511. expect(statusPanelCapture.props.at(-1)?.onResumeGoal).toEqual(expect.any(Function));
  512. });
  513. it("keeps scoped Agent detail opening on remote compact while hiding the directory", () => {
  514. const onOpenSubagentSession = vi.fn();
  515. const row = subagentRow();
  516. const snapshot = makeSnapshot({
  517. backgroundWorks: [
  518. {
  519. workId: "work-agent",
  520. kind: "subagent",
  521. title: "分析状态面板",
  522. status: "running",
  523. startedAt: 1_777_777_778,
  524. anchorRowId: row.rowId,
  525. childSessionId: "child-session",
  526. },
  527. ],
  528. rows: { window: [userInputRow(), row], totalCount: 2, firstRowId: 1 },
  529. });
  530. renderPane({ snapshot, onOpenSubagentSession });
  531. const panelProps = statusPanelCapture.props.at(-1);
  532. if (!panelProps) throw new Error("Status panel props were not captured");
  533. expect(panelProps.parentSessionId).toBe("session-1");
  534. expect(panelProps.runningSubagents).toEqual([]);
  535. (
  536. panelProps.onOpenSubagentSession as (request: {
  537. rootSessionId: string;
  538. parentSessionId: string;
  539. childSessionId: string;
  540. subagentType: string;
  541. title: string;
  542. }) => void
  543. )({
  544. rootSessionId: "session-1",
  545. parentSessionId: "session-1",
  546. childSessionId: "child-session",
  547. subagentType: "Explore",
  548. title: "分析状态面板",
  549. });
  550. expect(onOpenSubagentSession).toHaveBeenCalledWith({
  551. workspacePath: "/workspace",
  552. rootSessionId: "session-1",
  553. parentSessionId: "session-1",
  554. childSessionId: "child-session",
  555. subagentType: "Explore",
  556. title: "分析状态面板",
  557. });
  558. renderPane({
  559. compactForRemoteControl: true,
  560. snapshot,
  561. onOpenSubagentSession,
  562. });
  563. expect(statusPanelCapture.props.at(-1)?.isWebRemoteControl).toBe(true);
  564. expect(statusPanelCapture.props.at(-1)?.isMobileViewport).toBe(false);
  565. expect(statusPanelCapture.props.at(-1)?.onOpenSubagentSession).toEqual(expect.any(Function));
  566. expect(statusPanelCapture.props.at(-1)?.onOpenSubagentDirectory).toBeUndefined();
  567. });
  568. it("wires the Composer background entry to panel expansion and controlled Running state", () => {
  569. const onSummaryPanelVariantOverrideChange = vi.fn();
  570. const snapshot = makeSnapshot({
  571. backgroundWorks: [
  572. {
  573. workId: "work-bash",
  574. kind: "bash",
  575. title: "Run checks",
  576. status: "running",
  577. startedAt: 1_777_777_778,
  578. anchorRowId: null,
  579. },
  580. ],
  581. });
  582. renderPane({ snapshot, onSummaryPanelVariantOverrideChange });
  583. const composerProps = statusPanelCapture.composerProps.at(-1);
  584. const panelProps = statusPanelCapture.props.at(-1);
  585. expect(panelProps?.terminalSectionOpen).toBe(false);
  586. expect(panelProps?.onTerminalSectionOpenChange).toEqual(expect.any(Function));
  587. expect(panelProps?.agentSectionOpen).toBe(false);
  588. expect(panelProps?.onAgentSectionOpenChange).toEqual(expect.any(Function));
  589. (composerProps?.onOpenRunningBackgroundWorks as (() => void) | undefined)?.();
  590. expect(onSummaryPanelVariantOverrideChange).toHaveBeenCalledWith("panel");
  591. });
  592. it("keeps the Composer Agent count while the directory projection catches up", () => {
  593. const snapshot = makeSnapshot({
  594. backgroundWorks: [
  595. {
  596. workId: "work-agent",
  597. kind: "subagent",
  598. title: "后台分析",
  599. status: "running",
  600. startedAt: 1_777_777_778,
  601. anchorRowId: null,
  602. childSessionId: "child-session",
  603. },
  604. ],
  605. subagents: {
  606. revision: 2,
  607. childSessionIds: ["child-session"],
  608. running: [],
  609. endedTotal: 0,
  610. },
  611. });
  612. renderPane({ snapshot });
  613. const composerProps = statusPanelCapture.composerProps.at(-1);
  614. expect(composerProps?.runningSubagentCount).toBe(1);
  615. expect(composerProps?.onOpenRunningBackgroundWorks).toEqual(expect.any(Function));
  616. });
  617. // composer 徽标直达(docs/dynamic-workflow/presentation.md):唯一在跑的工作流
  618. // 点徽标直接开详情 side tab,胶囊不动;其他形态照旧展开胶囊。
  619. describe("Composer background entry with dwf workflow runs", () => {
  620. const workflowWork = {
  621. workId: "dwfrun-1",
  622. kind: "workflow" as const,
  623. title: "发布前检查",
  624. status: "running" as const,
  625. startedAt: 1_777_777_778,
  626. anchorRowId: null,
  627. };
  628. const workflowRun = {
  629. runId: "dwfrun-1",
  630. toolCallId: "tool-wf-1",
  631. status: "running" as const,
  632. usage: { spentTokens: 0, nodesUsed: 0 },
  633. actors: [],
  634. nodes: [],
  635. lastEventSequence: 0,
  636. };
  637. it("opens the run details directly when one workflow is the only running activity", () => {
  638. const onSummaryPanelVariantOverrideChange = vi.fn();
  639. const onOpenWorkflowRun = vi.fn();
  640. const snapshot = makeSnapshot({
  641. backgroundWorks: [workflowWork],
  642. workflowRuns: { revision: 1, runs: [workflowRun] },
  643. });
  644. renderPane({ snapshot, onOpenWorkflowRun, onSummaryPanelVariantOverrideChange });
  645. const composerProps = statusPanelCapture.composerProps.at(-1);
  646. expect(composerProps?.backgroundWorkOpenTarget).toBe("workflow-run");
  647. (composerProps?.onOpenRunningBackgroundWorks as (() => void) | undefined)?.();
  648. expect(onOpenWorkflowRun).toHaveBeenCalledWith({
  649. parentSessionId: "session-1",
  650. runId: "dwfrun-1",
  651. toolCallId: "tool-wf-1",
  652. workflowName: "发布前检查",
  653. workspacePath: "/workspace",
  654. });
  655. expect(onSummaryPanelVariantOverrideChange).not.toHaveBeenCalled();
  656. });
  657. it("falls back to panel expansion when another kind runs alongside the workflow", () => {
  658. const onSummaryPanelVariantOverrideChange = vi.fn();
  659. const onOpenWorkflowRun = vi.fn();
  660. const snapshot = makeSnapshot({
  661. backgroundWorks: [
  662. workflowWork,
  663. {
  664. workId: "work-bash",
  665. kind: "bash",
  666. title: "Run checks",
  667. status: "running",
  668. startedAt: 1_777_777_778,
  669. anchorRowId: null,
  670. },
  671. ],
  672. workflowRuns: { revision: 1, runs: [workflowRun] },
  673. });
  674. renderPane({ snapshot, onOpenWorkflowRun, onSummaryPanelVariantOverrideChange });
  675. const composerProps = statusPanelCapture.composerProps.at(-1);
  676. expect(composerProps?.backgroundWorkOpenTarget).toBe("panel");
  677. (composerProps?.onOpenRunningBackgroundWorks as (() => void) | undefined)?.();
  678. expect(onOpenWorkflowRun).not.toHaveBeenCalled();
  679. expect(onSummaryPanelVariantOverrideChange).toHaveBeenCalledWith("panel");
  680. });
  681. it("falls back to panel expansion when the host cannot open run details", () => {
  682. const onSummaryPanelVariantOverrideChange = vi.fn();
  683. const snapshot = makeSnapshot({
  684. backgroundWorks: [workflowWork],
  685. workflowRuns: { revision: 1, runs: [workflowRun] },
  686. });
  687. renderPane({ snapshot, onSummaryPanelVariantOverrideChange });
  688. const composerProps = statusPanelCapture.composerProps.at(-1);
  689. expect(composerProps?.backgroundWorkOpenTarget).toBe("panel");
  690. (composerProps?.onOpenRunningBackgroundWorks as (() => void) | undefined)?.();
  691. expect(onSummaryPanelVariantOverrideChange).toHaveBeenCalledWith("panel");
  692. });
  693. });
  694. });