v4SessionPaneComposerContinuity.test.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. import { act, createElement, useEffect, useLayoutEffect, useRef, type ReactNode } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  4. import type { ConversationSnapshot } from "@zcode/shared/zcode-protocol-v4";
  5. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  6. import { useZCodeSessionStore } from "@/store/zcodeSessionStore.js";
  7. import { pendingCommandRegistry, type PendingCommandEntry } from "@/v4/pendingCommandRegistry.js";
  8. import { SessionPane } from "@/v4/SessionPane.js";
  9. import { useModelSelectionServiceView } from "@/hooks/useModelSelectionView.js";
  10. type ProjectionState = {
  11. status: "connecting" | "live";
  12. snapshot: ConversationSnapshot | null;
  13. subscriptionId: string | null;
  14. lastError: string | null;
  15. optimisticCommands: readonly [];
  16. loadingOlder: boolean;
  17. };
  18. const recoveryCapture = vi.hoisted(() => ({
  19. entries: [] as PendingCommandEntry[],
  20. onResend: null as null | (() => void),
  21. }));
  22. vi.mock("@/v4/usePendingCommandRecovery.js", () => ({
  23. usePendingCommandRecovery: () => recoveryCapture.entries,
  24. }));
  25. vi.mock("@/v4/PendingCommandRecoveryBanner.js", () => ({
  26. PendingCommandRecoveryBanner: (props: { onResend?: () => void }) => {
  27. recoveryCapture.onResend = props.onResend ?? null;
  28. return null;
  29. },
  30. }));
  31. const sessionCreateCapture = vi.hoisted(() => ({ report: vi.fn(async () => {}) }));
  32. vi.mock("@/lib/sessionCreateTelemetry.js", () => ({
  33. reportSessionCreate: sessionCreateCapture.report,
  34. }));
  35. const projectionState = vi.hoisted(() => ({
  36. current: null as ProjectionState | null,
  37. }));
  38. const composerLifecycle = vi.hoisted(() => ({
  39. disabledStates: [] as boolean[],
  40. mounts: 0,
  41. nextInstanceId: 1,
  42. renders: [] as number[],
  43. unmounts: 0,
  44. }));
  45. const scrollFocus = vi.hoisted(() => ({
  46. composerProps: null as null | {
  47. onOpenRunningBackgroundWorks?: () => void;
  48. onSendText: (
  49. text: string,
  50. options?: {
  51. heldQueueDisposition?: "clearQueueAndSend" | "keepQueueAndSend";
  52. expectedHeldQueueItemIds?: readonly string[];
  53. requestedDelivery?: "startNow" | "queue" | "guide";
  54. sharedContextRefs?: Array<{ kind: "shared_context_import"; context_id: string }>;
  55. submission?: {
  56. mode: "build";
  57. modelSelection: {
  58. providerId: string;
  59. modelId: string;
  60. options: { reasoningLevel: string };
  61. };
  62. };
  63. },
  64. ) => Promise<"sent" | "blocked" | "confirmationRequired">;
  65. },
  66. queueProps: null as null | {
  67. onResume?: () => Promise<void>;
  68. onSendNow?: (queueItemId: string) => void;
  69. },
  70. statusPanelProps: null as null | {
  71. onTerminalSectionOpenChange?: (open: boolean) => void;
  72. terminalSectionOpen?: boolean;
  73. onAgentSectionOpenChange?: (open: boolean) => void;
  74. agentSectionOpen?: boolean;
  75. summaryPanelVariantOverride?: "panel" | "mini" | null;
  76. },
  77. scrollToBottom: vi.fn(),
  78. }));
  79. // 永不 resolve:这些文件不测发现查询;resolve 会在环境拆除后触发 setState(未处理异常)。
  80. const workflowRunsQueryMock = vi.hoisted(() =>
  81. vi.fn(() => new Promise<{ runs: unknown[] }>(() => {})),
  82. );
  83. const conversationMock = vi.hoisted(() => {
  84. const lease = {
  85. release: vi.fn(),
  86. store: {
  87. expectAcceptedInputProjection: vi.fn(),
  88. markCommandPending: vi.fn(),
  89. recoverFromStaleAuthority: vi.fn(),
  90. onOnlineModelTransition: vi.fn(() => () => {}),
  91. refreshPlans: vi.fn(async () => {}),
  92. settleCommand: vi.fn(),
  93. },
  94. };
  95. const sendCommand = vi.fn(async (envelope: { commandId: string }) => ({
  96. commandId: envelope.commandId,
  97. revisionAtDecision: 1,
  98. status: "accepted" as const,
  99. }));
  100. const layer = {
  101. acquire: vi.fn(() => lease),
  102. queryCommands: vi.fn(async () => ({ results: [] })),
  103. };
  104. return {
  105. layer,
  106. lease,
  107. currentLayer: null as typeof layer | null,
  108. currentSendCommand: null as typeof sendCommand | null,
  109. sendCommand,
  110. };
  111. });
  112. const prewarmHookInputs = vi.hoisted(() => ({
  113. binding: null as null | { sessionId: string; beginPromotion: () => boolean; promote: () => void },
  114. current: [] as Array<{
  115. workspaceKey: string;
  116. transportIdentity: unknown;
  117. dispatchCommand: (
  118. type: string,
  119. payload: Record<string, unknown>,
  120. sessionId: string | null,
  121. ) => Promise<unknown>;
  122. }>,
  123. }));
  124. const servicesMock = vi.hoisted(() => ({
  125. projectService: {
  126. resolveSessionDirectories: vi.fn(async (task) => ({
  127. ...task,
  128. projectId: null,
  129. additionalDirectories: [],
  130. })),
  131. },
  132. highspeedCardService: {
  133. // 本文件使用会在用例结束后销毁的极简 DOM;保持无关 Highspeed 查询 pending,
  134. // 避免其 Promise 回调在 window 清理后再次唤醒 React scheduler。
  135. getSnapshot: vi.fn(() => new Promise(() => {})),
  136. prepareTurn: vi.fn(async () => ({
  137. kind: "fallback" as const,
  138. reason: "draw-miss" as const,
  139. nextDrawAt: null,
  140. })),
  141. healthy: vi.fn(),
  142. share: vi.fn(),
  143. },
  144. // 修复原因:readiness hook 将 service 作为 effect 依赖;每次 render 重建会导致无限重渲染直至 OOM。
  145. modelSelectionService: {
  146. getView: vi.fn(async () => ({
  147. revision: 1,
  148. providers: [
  149. {
  150. providerId: "provider-deepseek",
  151. config: { kind: "api" as const },
  152. models: [{ modelId: "deepseek-v4-flash", config: {} }],
  153. },
  154. ],
  155. })),
  156. onDidChange: vi.fn(() => ({ dispose: vi.fn() })),
  157. validate: vi.fn(),
  158. },
  159. zcodeSessionService: {
  160. updateProviderRegistry: vi.fn(),
  161. },
  162. zcodeTaskService: {
  163. restartWorkspaceProcess: vi.fn(),
  164. },
  165. }));
  166. vi.mock("@/components/ui/toast.js", () => ({ toast: vi.fn() }));
  167. // 本组只验证输入框连续性;群同步服务由独立组件测试和真实 Host/CLI E2E 覆盖。
  168. vi.mock("@/v4/BotGroupDeliveryAction.js", () => ({
  169. BotGroupDeliveryProvider: ({ children }: { children: unknown }) => children,
  170. ConnectedBotGroupDeliveryAction: () => null,
  171. }));
  172. // Bugfix:本文件只验证 SessionPane 的 composer 连续性,隔离闲时入口对真实 TabStore 的依赖。
  173. vi.mock("@/v4/OffPeakNewTaskEntry.js", () => ({
  174. OffPeakNewTaskEntry: () => null,
  175. }));
  176. // 同理隔离推荐提示词占位:本文件用的是只实现 createElement 的极简 DOM,
  177. // 渲染 lucide 图标会走 createElementNS 而直接崩掉,与 composer 连续性无关。
  178. vi.mock("@/v4/ConversationDraftSuggestedPromptsContainer.js", () => ({
  179. ConversationDraftSuggestedPromptsContainer: () => null,
  180. }));
  181. vi.mock("@/v4/useConversationProjection.js", () => ({
  182. useConversationProjection: () => projectionState.current,
  183. }));
  184. vi.mock("@/v4/V4ConversationContext.js", () => ({
  185. useV4Conversation: () => ({
  186. layer: conversationMock.currentLayer ?? conversationMock.layer,
  187. sendCommand: conversationMock.currentSendCommand ?? conversationMock.sendCommand,
  188. attachmentPut: vi.fn(),
  189. // SessionPane 挂载即拉 journal 兜底的 run 发现查询:缺桩会在 effect 里 TypeError;
  190. // 桩必须是稳定引用——effect 以 workflowRuns 为依赖,每次渲染换新函数会死循环。
  191. workflowRuns: workflowRunsQueryMock,
  192. fileChanges: vi.fn(),
  193. fileRewindPreview: vi.fn(),
  194. }),
  195. }));
  196. vi.mock("@/store/StoreProvider.js", () => ({
  197. useZCodeStoreWithDefault: (_selector: unknown, fallback: unknown) => fallback,
  198. }));
  199. vi.mock("@/hooks/useSettingService.js", () => ({
  200. useSettings: () => ({
  201. settings: { zcodeInteractionBehavior: "queue" },
  202. loading: false,
  203. error: null,
  204. update: vi.fn(async () => {}),
  205. refresh: vi.fn(async () => {}),
  206. }),
  207. }));
  208. vi.mock("@/hooks/useServices.js", () => ({
  209. useComposerClientNamespace: () => "desktop",
  210. useOptionalServices: () => null,
  211. useServices: () => servicesMock,
  212. }));
  213. // 本文件只验证 composer 生命周期;目标 Host View 的异步订阅已有独立 hook 测试。
  214. // 若让真实 hook 在极简 DOM 中运行,Promise 回流会把 React 调度留到 window 清理之后。
  215. vi.mock("@/hooks/useModelSelectionView.js", () => ({
  216. useModelSelectionServiceView: () => ({
  217. state: {
  218. status: "ready",
  219. view: {
  220. revision: 1,
  221. preferredSelection: {
  222. providerId: "provider-deepseek",
  223. modelId: "deepseek-v4-flash",
  224. },
  225. providers: [
  226. {
  227. providerId: "provider-deepseek",
  228. config: { kind: "api" as const },
  229. models: [
  230. {
  231. modelId: "deepseek-v4-flash",
  232. config: {
  233. optionSpecs: { reasoningLevel: { values: ["low", "high"], map: "{}" } },
  234. },
  235. },
  236. ],
  237. },
  238. ],
  239. },
  240. },
  241. reload: vi.fn(),
  242. }),
  243. }));
  244. vi.mock("@/v4/composer/useDraftConfigControl.js", () => ({
  245. buildDraftCreateConfigPayload: () => ({}),
  246. useDraftConfigControl: () => ({
  247. modelSelectionRead: useModelSelectionServiceView(null),
  248. captureAcceptedModelSelection: () => vi.fn(),
  249. composerDraft: { text: "", updatedAt: 0 },
  250. draftConfig: {},
  251. draftConfigRef: {
  252. current: {
  253. mode: "build",
  254. modelSelection: {
  255. providerId: "provider-deepseek",
  256. modelId: "deepseek-v4-flash",
  257. options: { reasoningLevel: "high" },
  258. },
  259. },
  260. },
  261. resolveInitialDraftConfig: vi.fn(async () => ({})),
  262. handleDraftSelectModel: vi.fn(),
  263. handleDraftSelectThought: vi.fn(),
  264. handleDraftSwitchMode: vi.fn(),
  265. promoteComposerDraft: vi.fn(),
  266. replaceComposerDraft: vi.fn(),
  267. updateComposerContent: vi.fn(),
  268. }),
  269. }));
  270. vi.mock("@/v4/composer/useDraftSessionPrewarm.js", () => ({
  271. useDraftSessionPrewarm: (params: (typeof prewarmHookInputs.current)[number]) => {
  272. prewarmHookInputs.current.push(params);
  273. return {
  274. binding: prewarmHookInputs.binding,
  275. waitForSession: async () => {
  276. if (prewarmHookInputs.binding) return prewarmHookInputs.binding;
  277. const ack = (await params.dispatchCommand("createSession", {}, null)) as {
  278. result: { sessionId: string };
  279. };
  280. return { sessionId: ack.result.sessionId, beginPromotion: () => true, promote: vi.fn() };
  281. },
  282. };
  283. },
  284. }));
  285. vi.mock("@/v4/ConversationComposer.js", () => ({
  286. ConversationComposer: (props: {
  287. disabled?: boolean;
  288. onOpenRunningBackgroundWorks?: () => void;
  289. onSendText: (
  290. text: string,
  291. options?: {
  292. heldQueueDisposition?: "clearQueueAndSend" | "keepQueueAndSend";
  293. expectedHeldQueueItemIds?: readonly string[];
  294. requestedDelivery?: "startNow" | "queue" | "guide";
  295. sharedContextRefs?: Array<{ kind: "shared_context_import"; context_id: string }>;
  296. },
  297. ) => Promise<"sent" | "blocked" | "confirmationRequired">;
  298. }) => {
  299. const { disabled = false } = props;
  300. scrollFocus.composerProps = props;
  301. const instanceIdRef = useRef<number | null>(null);
  302. if (instanceIdRef.current === null) {
  303. instanceIdRef.current = composerLifecycle.nextInstanceId;
  304. composerLifecycle.nextInstanceId += 1;
  305. }
  306. composerLifecycle.renders.push(instanceIdRef.current);
  307. composerLifecycle.disabledStates.push(disabled);
  308. useEffect(() => {
  309. composerLifecycle.mounts += 1;
  310. return () => {
  311. composerLifecycle.unmounts += 1;
  312. };
  313. }, []);
  314. return createElement("div", { "data-testid": "mock-composer" });
  315. },
  316. }));
  317. vi.mock("@/v4/ConversationHeader.js", () => ({
  318. ConversationHeader: () => createElement("div", null),
  319. }));
  320. vi.mock("@/v4/ConversationStatusPanel.js", () => ({
  321. ConversationStatusPanel: (props: {
  322. onTerminalSectionOpenChange?: (open: boolean) => void;
  323. terminalSectionOpen?: boolean;
  324. onAgentSectionOpenChange?: (open: boolean) => void;
  325. agentSectionOpen?: boolean;
  326. summaryPanelVariantOverride?: "panel" | "mini" | null;
  327. }) => {
  328. scrollFocus.statusPanelProps = props;
  329. return createElement("div", null);
  330. },
  331. }));
  332. vi.mock("@/v4/ConversationTimeline.js", () => ({
  333. ConversationTimeline: ({
  334. bottomDock,
  335. emptyState,
  336. scrollToBottomActionRef,
  337. }: {
  338. bottomDock?: ReactNode;
  339. emptyState?: ReactNode;
  340. scrollToBottomActionRef?: { current: (() => void) | null };
  341. }) => {
  342. useLayoutEffect(() => {
  343. if (scrollToBottomActionRef) {
  344. scrollToBottomActionRef.current = scrollFocus.scrollToBottom;
  345. }
  346. }, [scrollToBottomActionRef]);
  347. return createElement("div", null, emptyState, bottomDock);
  348. },
  349. }));
  350. vi.mock("@/v4/ConversationQueuePanel.js", () => ({
  351. ConversationQueuePanel: (props: {
  352. onResume?: () => Promise<void>;
  353. onSendNow?: (queueItemId: string) => void;
  354. }) => {
  355. scrollFocus.queueProps = props;
  356. return createElement("div", null);
  357. },
  358. }));
  359. vi.mock("@/v4/V4InteractionDialogs.js", () => ({
  360. V4InteractionDialogs: () => createElement("div", null),
  361. }));
  362. vi.mock("@/request-security-edition/V4ProviderRuntimeHeadersController.js", () => ({
  363. V4ProviderRuntimeHeadersController: () => createElement("div", null),
  364. }));
  365. vi.mock("@/v4/ConversationDraftEmptyState.js", () => ({
  366. ConversationDraftEmptyState: () => createElement("div", null),
  367. }));
  368. function makeDraftSnapshot(): ConversationSnapshot {
  369. return {
  370. protocolVersion: 1,
  371. sessionId: "prewarm-1",
  372. logEpoch: "epoch-1",
  373. seq: 0,
  374. revision: 0,
  375. control: {
  376. phase: "draft",
  377. sessionEnded: false,
  378. canStop: false,
  379. stopState: "idle",
  380. stopTargetKind: "unknown",
  381. activeWorks: [],
  382. lastError: null,
  383. apiRetry: null,
  384. },
  385. availability: {
  386. fork: { allowed: true },
  387. compact: { allowed: false, reasonCode: "noHistory" },
  388. switchModelConfig: { allowed: true },
  389. setFollowupMode: { allowed: true },
  390. queueEdit: { allowed: true },
  391. sendQueuedNow: { allowed: false, reasonCode: "emptyQueue" },
  392. pauseGoal: { allowed: false, reasonCode: "noGoalToPause" },
  393. resumeGoal: { allowed: false, reasonCode: "noGoalToResume" },
  394. },
  395. inputRouting: { mode: "startNow" },
  396. meta: { title: "", titleSource: "firstInput" },
  397. config: {
  398. provider: "provider-deepseek",
  399. model: "deepseek-v4-flash",
  400. thought: "medium",
  401. followupMode: "queue",
  402. mode: "build",
  403. },
  404. usage: {
  405. contextWindow: null,
  406. cumulative: {
  407. inputTokens: 0,
  408. outputTokens: 0,
  409. cacheReadTokens: 0,
  410. cacheWriteTokens: 0,
  411. },
  412. },
  413. queue: { items: [], autoDrain: true },
  414. pendingInteractions: [],
  415. pendingCommands: [],
  416. backgroundWorks: [],
  417. subagents: { revision: 0, childSessionIds: [], running: [], endedTotal: 0 },
  418. goal: null,
  419. plan: null,
  420. rows: { window: [], totalCount: 0, firstRowId: null },
  421. };
  422. }
  423. const mountedRoots: Root[] = [];
  424. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  425. const element = {
  426. addEventListener: () => {},
  427. appendChild: (child: { parentNode?: unknown }) => {
  428. child.parentNode = element;
  429. return child;
  430. },
  431. childNodes: [] as unknown[],
  432. clientWidth: 1024,
  433. getAttribute: () => null,
  434. insertBefore: (child: { parentNode?: unknown }) => {
  435. child.parentNode = element;
  436. return child;
  437. },
  438. nodeName: tagName.toUpperCase(),
  439. nodeType: 1,
  440. ownerDocument,
  441. parentNode: null as unknown,
  442. removeAttribute: () => {},
  443. removeChild: (child: { parentNode?: unknown }) => {
  444. child.parentNode = null;
  445. return child;
  446. },
  447. removeEventListener: () => {},
  448. setAttribute: () => {},
  449. style: {
  450. removeProperty: () => {},
  451. setProperty: () => {},
  452. },
  453. tagName: tagName.toUpperCase(),
  454. };
  455. return element as unknown as Element;
  456. }
  457. function installMinimalDom() {
  458. const documentMock = {
  459. addEventListener: () => {},
  460. createElement: (tagName: string) =>
  461. createMinimalElement(documentMock as unknown as Document, tagName),
  462. createTextNode: (nodeValue: string) => ({
  463. nodeType: 3,
  464. nodeValue,
  465. ownerDocument: documentMock,
  466. parentNode: null,
  467. }),
  468. nodeType: 9,
  469. removeEventListener: () => {},
  470. } as unknown as Document;
  471. const windowMock = {
  472. addEventListener: () => {},
  473. document: documentMock,
  474. HTMLIFrameElement: function HTMLIFrameElement() {},
  475. HTMLElement: function HTMLElement() {},
  476. innerWidth: 1024,
  477. Node: function Node() {},
  478. removeEventListener: () => {},
  479. };
  480. Object.defineProperty(globalThis, "document", {
  481. configurable: true,
  482. value: documentMock,
  483. });
  484. Object.defineProperty(globalThis, "window", {
  485. configurable: true,
  486. value: windowMock,
  487. });
  488. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  489. configurable: true,
  490. value: true,
  491. });
  492. return createMinimalElement(documentMock, "div");
  493. }
  494. function renderPane(root: Root, sessionId: string | null): void {
  495. act(() => {
  496. root.render(
  497. createElement(
  498. ZCodeIntlProvider,
  499. { initialLocale: "zh-CN" },
  500. createElement(SessionPane, {
  501. paneId: "workspace-main",
  502. sessionId,
  503. workspacePath: "/workspace",
  504. }),
  505. ),
  506. );
  507. });
  508. }
  509. beforeEach(() => {
  510. sessionCreateCapture.report.mockClear();
  511. recoveryCapture.entries = [];
  512. recoveryCapture.onResend = null;
  513. prewarmHookInputs.binding = null;
  514. composerLifecycle.disabledStates = [];
  515. composerLifecycle.mounts = 0;
  516. composerLifecycle.nextInstanceId = 1;
  517. composerLifecycle.renders = [];
  518. composerLifecycle.unmounts = 0;
  519. conversationMock.layer.acquire.mockClear();
  520. conversationMock.lease.release.mockClear();
  521. conversationMock.lease.store.expectAcceptedInputProjection.mockClear();
  522. conversationMock.currentLayer = null;
  523. conversationMock.currentSendCommand = null;
  524. conversationMock.sendCommand.mockReset();
  525. conversationMock.sendCommand.mockImplementation(async (envelope) => ({
  526. commandId: envelope.commandId,
  527. revisionAtDecision: 1,
  528. status: "accepted" as const,
  529. }));
  530. prewarmHookInputs.current = [];
  531. scrollFocus.composerProps = null;
  532. scrollFocus.queueProps = null;
  533. scrollFocus.statusPanelProps = null;
  534. scrollFocus.scrollToBottom.mockClear();
  535. projectionState.current = {
  536. status: "live",
  537. snapshot: makeDraftSnapshot(),
  538. subscriptionId: "sub-draft",
  539. lastError: null,
  540. optimisticCommands: [],
  541. loadingOlder: false,
  542. };
  543. });
  544. afterEach(() => {
  545. for (const root of mountedRoots.splice(0)) {
  546. act(() => root.unmount());
  547. }
  548. delete (globalThis as { document?: unknown }).document;
  549. delete (globalThis as { window?: unknown }).window;
  550. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  551. });
  552. describe("SessionPane composer continuity", () => {
  553. it.each(["group", "project", "session"] as const)(
  554. "%s 首发只在 accepted 后报告,打开和后续发送不报告",
  555. async (source) => {
  556. const store = useZCodeSessionStore.getState();
  557. store.startDraft("/workspace", undefined, undefined, { createSource: source });
  558. const root = createRoot(installMinimalDom());
  559. mountedRoots.push(root);
  560. renderPane(root, null);
  561. expect(sessionCreateCapture.report).not.toHaveBeenCalled();
  562. conversationMock.sendCommand.mockImplementationOnce(async (envelope) => ({
  563. commandId: envelope.commandId,
  564. revisionAtDecision: 1,
  565. status: "accepted" as const,
  566. result: { type: "createSession", sessionId: `created-${source}` },
  567. }));
  568. await act(async () => {
  569. await scrollFocus.composerProps?.onSendText("create session");
  570. });
  571. // Highspeed 统一了首发链路:无附件首发也走「空 createSession + sendText」两段式,
  572. // 好让抽卡 admission 拿到真实 sessionId,因此首发 message_id 是 sendText 的 commandId
  573. // (calls[1]),不是空创建的 commandId(calls[0])。埋点不变量仍成立:accepted 后只报一次。
  574. const firstSendCalls = conversationMock.sendCommand.mock.calls;
  575. expect(firstSendCalls).toHaveLength(2);
  576. expect(sessionCreateCapture.report).toHaveBeenCalledExactlyOnceWith(
  577. null,
  578. expect.objectContaining({
  579. sessionId: `created-${source}`,
  580. messageId: firstSendCalls[1]![0].commandId,
  581. source,
  582. }),
  583. );
  584. renderPane(root, `created-${source}`);
  585. await act(async () => {
  586. await scrollFocus.composerProps?.onSendText("follow up");
  587. });
  588. expect(sessionCreateCapture.report).toHaveBeenCalledTimes(1);
  589. },
  590. );
  591. it.each(["accepted", "rejected"] as const)("Goal 首发 %s 时只按 ACK 统计", async (status) => {
  592. const root = createRoot(installMinimalDom());
  593. mountedRoots.push(root);
  594. renderPane(root, null);
  595. conversationMock.sendCommand.mockImplementationOnce(async (envelope) => ({
  596. commandId: envelope.commandId,
  597. revisionAtDecision: 1,
  598. status: "accepted" as const,
  599. result: { type: "createSession", sessionId: "goal-created" },
  600. }));
  601. conversationMock.sendCommand.mockResolvedValueOnce({
  602. commandId: "goal-command",
  603. revisionAtDecision: 1,
  604. status,
  605. } as never);
  606. await act(async () => {
  607. await scrollFocus.composerProps?.onSendText("/goal explain the test");
  608. });
  609. expect(sessionCreateCapture.report).toHaveBeenCalledTimes(status === "accepted" ? 1 : 0);
  610. if (status === "accepted")
  611. expect(sessionCreateCapture.report).toHaveBeenCalledWith(
  612. null,
  613. expect.objectContaining({ messageId: "goal-command" }),
  614. );
  615. });
  616. it.each(["hello", "/goal explain"])("预热首发 %s 携带实际输入 commandId", async (text) => {
  617. prewarmHookInputs.binding = {
  618. sessionId: "prewarmed",
  619. beginPromotion: () => true,
  620. promote: vi.fn(),
  621. };
  622. const root = createRoot(installMinimalDom());
  623. mountedRoots.push(root);
  624. renderPane(root, null);
  625. await act(async () => {
  626. await scrollFocus.composerProps?.onSendText(text);
  627. });
  628. const commandId = conversationMock.sendCommand.mock.calls[0]![0].commandId;
  629. expect(sessionCreateCapture.report).toHaveBeenCalledExactlyOnceWith(
  630. null,
  631. expect.objectContaining({ sessionId: "prewarmed", messageId: commandId }),
  632. );
  633. });
  634. it("先空创建再首发使用 sendText ID,不用空创建 ID", async () => {
  635. const root = createRoot(installMinimalDom());
  636. mountedRoots.push(root);
  637. renderPane(root, null);
  638. conversationMock.sendCommand.mockImplementationOnce(async (envelope) => ({
  639. commandId: envelope.commandId,
  640. revisionAtDecision: 1,
  641. status: "accepted" as const,
  642. result: { type: "createSession", sessionId: "two-phase" },
  643. }));
  644. await act(async () => {
  645. await scrollFocus.composerProps?.onSendText("context", {
  646. sharedContextRefs: [{ kind: "shared_context_import", context_id: "context-1" }],
  647. });
  648. });
  649. const calls = conversationMock.sendCommand.mock.calls;
  650. expect(calls).toHaveLength(2);
  651. expect(calls[0]![0].commandId).not.toBe(calls[1]![0].commandId);
  652. expect(sessionCreateCapture.report).toHaveBeenCalledWith(
  653. null,
  654. expect.objectContaining({ messageId: calls[1]![0].commandId }),
  655. );
  656. });
  657. it("用户确认恢复重发使用新 accepted ID,不用旧命令 ID", async () => {
  658. recoveryCapture.entries = [
  659. {
  660. commandId: "old-command",
  661. sessionId: null,
  662. replay: { kind: "input" },
  663. } as PendingCommandEntry,
  664. ];
  665. const replay = vi.spyOn(pendingCommandRegistry, "consumeReplay").mockReturnValueOnce({
  666. type: "createSession",
  667. sessionId: null,
  668. payload: { workspaceId: "/workspace", firstInput: { text: "retry" } },
  669. clientContext: { workspace: { workspacePath: "/workspace" }, sessionCreateSource: "project" },
  670. });
  671. try {
  672. const root = createRoot(installMinimalDom());
  673. mountedRoots.push(root);
  674. renderPane(root, null);
  675. conversationMock.sendCommand.mockImplementationOnce(async (envelope) => ({
  676. commandId: envelope.commandId,
  677. revisionAtDecision: 1,
  678. status: "accepted" as const,
  679. result: { type: "createSession", sessionId: "recovered" },
  680. }));
  681. await act(async () => {
  682. recoveryCapture.onResend?.();
  683. });
  684. const newId = conversationMock.sendCommand.mock.calls[0]![0].commandId;
  685. expect(newId).not.toBe("old-command");
  686. expect(sessionCreateCapture.report).toHaveBeenCalledWith(
  687. null,
  688. expect.objectContaining({ sessionId: "recovered", messageId: newId }),
  689. );
  690. } finally {
  691. replay.mockRestore();
  692. }
  693. });
  694. it("首发传输失败不产生 session_create", async () => {
  695. const root = createRoot(installMinimalDom());
  696. mountedRoots.push(root);
  697. renderPane(root, null);
  698. conversationMock.sendCommand.mockRejectedValueOnce(new Error("transport offline"));
  699. await act(async () => {
  700. await expect(scrollFocus.composerProps?.onSendText("create session")).rejects.toThrow(
  701. "transport offline",
  702. );
  703. });
  704. expect(sessionCreateCapture.report).not.toHaveBeenCalled();
  705. });
  706. it("/goal 沿用点击发送时冻结的 Submission,不在异步准备后回读草稿", async () => {
  707. const root = createRoot(installMinimalDom());
  708. mountedRoots.push(root);
  709. renderPane(root, "session-1");
  710. const submission = {
  711. mode: "build" as const,
  712. modelSelection: {
  713. providerId: "provider-deepseek",
  714. modelId: "deepseek-v4-flash",
  715. options: { reasoningLevel: "low" },
  716. },
  717. };
  718. await act(async () => {
  719. await scrollFocus.composerProps?.onSendText("/goal 固定此次选择", { submission });
  720. });
  721. expect(conversationMock.sendCommand).toHaveBeenCalledWith(
  722. expect.objectContaining({
  723. type: "sendGoalCommand",
  724. payload: expect.objectContaining(submission),
  725. }),
  726. );
  727. });
  728. it("workspace 切换后旧预热 dispatcher 仍发送到原本地 transport", async () => {
  729. const sendCommandA = vi.fn(async (envelope: { commandId: string }) => ({
  730. commandId: envelope.commandId,
  731. revisionAtDecision: 1,
  732. status: "accepted" as const,
  733. }));
  734. const sendCommandB = vi.fn(async (envelope: { commandId: string }) => ({
  735. commandId: envelope.commandId,
  736. revisionAtDecision: 1,
  737. status: "accepted" as const,
  738. }));
  739. const layerA = { ...conversationMock.layer };
  740. const layerB = { ...conversationMock.layer };
  741. const root = createRoot(installMinimalDom());
  742. mountedRoots.push(root);
  743. conversationMock.currentLayer = layerA;
  744. conversationMock.currentSendCommand = sendCommandA;
  745. act(() => {
  746. root.render(
  747. createElement(
  748. ZCodeIntlProvider,
  749. { initialLocale: "zh-CN" },
  750. createElement(SessionPane, {
  751. paneId: "workspace-main",
  752. sessionId: null,
  753. workspacePath: "/local/a",
  754. }),
  755. ),
  756. );
  757. });
  758. const bindingA = prewarmHookInputs.current.findLast(
  759. (input) => input.workspaceKey === "/local/a",
  760. );
  761. // Bug 根因:single-flight 协调器已改用稳定的 SessionDataLayer 标识 transport,
  762. // 旧断言仍把 provider 每次可重建的 sendCommand wrapper 当作 identity。
  763. expect(bindingA?.transportIdentity).toBe(layerA);
  764. conversationMock.currentLayer = layerB;
  765. conversationMock.currentSendCommand = sendCommandB;
  766. act(() => {
  767. root.render(
  768. createElement(
  769. ZCodeIntlProvider,
  770. { initialLocale: "zh-CN" },
  771. createElement(SessionPane, {
  772. paneId: "workspace-main",
  773. sessionId: null,
  774. workspacePath: "/local/b",
  775. }),
  776. ),
  777. );
  778. });
  779. await act(async () => {
  780. await bindingA?.dispatchCommand("deleteSession", {}, "draft-a");
  781. });
  782. expect(sendCommandA).toHaveBeenCalledTimes(1);
  783. expect(sendCommandB).not.toHaveBeenCalled();
  784. });
  785. it("keeps one composer instance while draft promotion waits for the first snapshot", () => {
  786. const root = createRoot(installMinimalDom());
  787. mountedRoots.push(root);
  788. renderPane(root, null);
  789. projectionState.current = {
  790. status: "connecting",
  791. snapshot: null,
  792. subscriptionId: null,
  793. lastError: null,
  794. optimisticCommands: [],
  795. loadingOlder: false,
  796. };
  797. renderPane(root, "session-1");
  798. projectionState.current = {
  799. status: "live",
  800. snapshot: { ...makeDraftSnapshot(), sessionId: "session-1" },
  801. subscriptionId: "sub-session",
  802. lastError: null,
  803. optimisticCommands: [],
  804. loadingOlder: false,
  805. };
  806. renderPane(root, "session-1");
  807. expect(composerLifecycle.mounts).toBe(1);
  808. expect(composerLifecycle.unmounts).toBe(0);
  809. expect(new Set(composerLifecycle.renders)).toEqual(new Set([1]));
  810. expect(composerLifecycle.disabledStates).toContain(true);
  811. expect(composerLifecycle.disabledStates.at(-1)).toBe(false);
  812. });
  813. it("focuses after start-now, preserves position on enqueue, and focuses on queue send-now", async () => {
  814. const root = createRoot(installMinimalDom());
  815. mountedRoots.push(root);
  816. projectionState.current = {
  817. status: "live",
  818. snapshot: { ...makeDraftSnapshot(), sessionId: "session-1" },
  819. subscriptionId: "sub-session",
  820. lastError: null,
  821. optimisticCommands: [],
  822. loadingOlder: false,
  823. };
  824. renderPane(root, "session-1");
  825. await act(async () => {
  826. await scrollFocus.composerProps?.onSendText("direct prompt");
  827. });
  828. expect(scrollFocus.scrollToBottom).toHaveBeenCalledTimes(1);
  829. scrollFocus.scrollToBottom.mockClear();
  830. projectionState.current = {
  831. ...projectionState.current,
  832. snapshot: {
  833. ...projectionState.current.snapshot,
  834. inputRouting: { mode: "enqueue" },
  835. },
  836. };
  837. renderPane(root, "session-1");
  838. await act(async () => {
  839. await scrollFocus.composerProps?.onSendText("queued prompt");
  840. });
  841. expect(scrollFocus.scrollToBottom).not.toHaveBeenCalled();
  842. act(() => scrollFocus.queueProps?.onSendNow?.("queue-1"));
  843. expect(scrollFocus.scrollToBottom).toHaveBeenCalledTimes(1);
  844. });
  845. it("running startNow dispatches one atomic sendText and never creates or promotes a queue item", async () => {
  846. const root = createRoot(installMinimalDom());
  847. mountedRoots.push(root);
  848. projectionState.current = {
  849. status: "live",
  850. snapshot: {
  851. ...makeDraftSnapshot(),
  852. sessionId: "session-1",
  853. inputRouting: { mode: "enqueue" },
  854. },
  855. subscriptionId: "sub-session",
  856. lastError: null,
  857. optimisticCommands: [],
  858. loadingOlder: false,
  859. };
  860. renderPane(root, "session-1");
  861. conversationMock.sendCommand.mockReset();
  862. conversationMock.sendCommand.mockImplementation(async (envelope) => ({
  863. commandId: envelope.commandId,
  864. revisionAtDecision: 1,
  865. status: "accepted" as const,
  866. }));
  867. await act(async () => {
  868. await scrollFocus.composerProps?.onSendText("立即执行", {
  869. requestedDelivery: "startNow",
  870. });
  871. });
  872. expect(conversationMock.sendCommand).toHaveBeenCalledTimes(1);
  873. expect(conversationMock.sendCommand).toHaveBeenCalledWith(
  874. expect.objectContaining({
  875. type: "sendText",
  876. payload: expect.objectContaining({
  877. text: "立即执行",
  878. requestedDelivery: "startNow",
  879. }),
  880. }),
  881. );
  882. expect(conversationMock.lease.store.expectAcceptedInputProjection).toHaveBeenCalledWith(
  883. conversationMock.sendCommand.mock.calls[0]?.[0].commandId,
  884. );
  885. });
  886. it("routes paused queue input to modal, while /compact queues directly", async () => {
  887. const root = createRoot(installMinimalDom());
  888. mountedRoots.push(root);
  889. const queuedItem = {
  890. queueItemId: "q-1",
  891. kind: "sendText" as const,
  892. text: "旧消息",
  893. sourceCommandId: "old-command",
  894. clientId: "desktop",
  895. attachments: [],
  896. delivery: { requested: "queue" as const, admitted: "queue" as const },
  897. order: { admissionSeq: 1, queuePosition: 0 },
  898. steer: { state: "notRequested" as const },
  899. dispatch: { state: "queued" as const },
  900. admittedAt: 1,
  901. };
  902. projectionState.current = {
  903. status: "live",
  904. snapshot: {
  905. ...makeDraftSnapshot(),
  906. sessionId: "session-1",
  907. revision: 7,
  908. inputRouting: { mode: "choice" },
  909. queue: { autoDrain: false, pauseReason: "stopped", items: [queuedItem] },
  910. },
  911. subscriptionId: "sub-session",
  912. lastError: null,
  913. optimisticCommands: [],
  914. loadingOlder: false,
  915. };
  916. renderPane(root, "session-1");
  917. await act(async () => {
  918. await expect(scrollFocus.composerProps?.onSendText("新消息")).resolves.toBe(
  919. "confirmationRequired",
  920. );
  921. await expect(scrollFocus.composerProps?.onSendText("/goal 新目标")).resolves.toBe(
  922. "confirmationRequired",
  923. );
  924. });
  925. expect(conversationMock.sendCommand).not.toHaveBeenCalled();
  926. await act(async () => {
  927. await scrollFocus.composerProps?.onSendText("/compact");
  928. });
  929. expect(conversationMock.sendCommand).toHaveBeenCalledWith(
  930. expect.objectContaining({ type: "compact", sessionId: "session-1" }),
  931. );
  932. conversationMock.sendCommand.mockReset();
  933. conversationMock.sendCommand.mockImplementation(async (envelope) => ({
  934. commandId: envelope.commandId,
  935. revisionAtDecision: 1,
  936. status: "accepted" as const,
  937. }));
  938. await act(async () => {
  939. await scrollFocus.composerProps?.onSendText("新消息", {
  940. heldQueueDisposition: "clearQueueAndSend",
  941. expectedHeldQueueItemIds: ["q-1"],
  942. });
  943. });
  944. expect(conversationMock.sendCommand).toHaveBeenCalledWith(
  945. expect.objectContaining({
  946. type: "sendText",
  947. payload: expect.objectContaining({
  948. heldQueueDisposition: "clearQueueAndSend",
  949. expectedHeldQueueItemIds: ["q-1"],
  950. }),
  951. }),
  952. );
  953. });
  954. it("paused queue continue dispatches CAS setAutoDrain without preempting in UI", async () => {
  955. const root = createRoot(installMinimalDom());
  956. mountedRoots.push(root);
  957. const snapshot = makeDraftSnapshot();
  958. projectionState.current = {
  959. status: "live",
  960. snapshot: {
  961. ...snapshot,
  962. sessionId: "session-1",
  963. revision: 9,
  964. queue: {
  965. autoDrain: false,
  966. items: [
  967. {
  968. queueItemId: "q-1",
  969. kind: "sendText",
  970. text: "旧消息",
  971. sourceCommandId: "old-command",
  972. clientId: "desktop",
  973. attachments: [],
  974. delivery: { requested: "queue", admitted: "queue" },
  975. order: { admissionSeq: 1, queuePosition: 0 },
  976. steer: { state: "notRequested" },
  977. dispatch: { state: "queued" },
  978. admittedAt: 1,
  979. },
  980. ],
  981. },
  982. },
  983. subscriptionId: "sub-session",
  984. lastError: null,
  985. optimisticCommands: [],
  986. loadingOlder: false,
  987. };
  988. renderPane(root, "session-1");
  989. await scrollFocus.queueProps?.onResume?.();
  990. expect(conversationMock.sendCommand).toHaveBeenCalledWith(
  991. expect.objectContaining({
  992. baseRevision: 9,
  993. payload: { autoDrain: true },
  994. sessionId: "session-1",
  995. type: "setAutoDrain",
  996. }),
  997. );
  998. });
  999. // 展开后看到的不能比胶囊还少(docs/dynamic-workflow/presentation.md「Other places a run appears」):
  1000. // 活的 run 出现时(在跑数从 0 变成 ≥1,包括进入一个本就有活 run 的会话)「工作流」分区打开;
  1001. // 最后一条结束时折起。读者手动折起后保持折起,直到 run 全部结束或换会话。
  1002. it("opens the Workflows section while a run is live and respects a manual fold", () => {
  1003. const root = createRoot(installMinimalDom());
  1004. mountedRoots.push(root);
  1005. const liveRun = {
  1006. runId: "dwfrun-1",
  1007. toolCallId: "tool-wf-1",
  1008. status: "running" as const,
  1009. usage: { spentTokens: 0, nodesUsed: 0 },
  1010. actors: [],
  1011. nodes: [],
  1012. lastEventSequence: 1,
  1013. };
  1014. const withRuns = (sessionId: string, runs: (typeof liveRun)[]) => ({
  1015. status: "live" as const,
  1016. snapshot: {
  1017. ...makeDraftSnapshot(),
  1018. sessionId,
  1019. workflowRuns: { revision: runs.length, runs },
  1020. },
  1021. subscriptionId: `sub-${sessionId}`,
  1022. lastError: null,
  1023. optimisticCommands: [],
  1024. loadingOlder: false,
  1025. });
  1026. projectionState.current = withRuns("session-1", []);
  1027. renderPane(root, "session-1");
  1028. expect(scrollFocus.statusPanelProps?.workflowSectionOpen).toBe(false);
  1029. // 0 → 1:打开。
  1030. projectionState.current = withRuns("session-1", [liveRun]);
  1031. renderPane(root, "session-1");
  1032. expect(scrollFocus.statusPanelProps?.workflowSectionOpen).toBe(true);
  1033. // 手动折起后,run 还在跑(再来一条也一样)就保持折起。
  1034. act(() => scrollFocus.statusPanelProps?.onWorkflowSectionOpenChange?.(false));
  1035. projectionState.current = withRuns("session-1", [liveRun, { ...liveRun, runId: "dwfrun-2" }]);
  1036. renderPane(root, "session-1");
  1037. expect(scrollFocus.statusPanelProps?.workflowSectionOpen).toBe(false);
  1038. // 全部结束:折起;下一条 run 出现:重新打开。
  1039. projectionState.current = withRuns("session-1", [{ ...liveRun, status: "completed" as never }]);
  1040. renderPane(root, "session-1");
  1041. expect(scrollFocus.statusPanelProps?.workflowSectionOpen).toBe(false);
  1042. projectionState.current = withRuns("session-1", [{ ...liveRun, runId: "dwfrun-3" }]);
  1043. renderPane(root, "session-1");
  1044. expect(scrollFocus.statusPanelProps?.workflowSectionOpen).toBe(true);
  1045. // 在一个有活 run 的会话里折起,再进入另一个也有活 run 的会话:新会话里是打开的。
  1046. act(() => scrollFocus.statusPanelProps?.onWorkflowSectionOpenChange?.(false));
  1047. projectionState.current = withRuns("session-2", [liveRun]);
  1048. renderPane(root, "session-2");
  1049. expect(scrollFocus.statusPanelProps?.workflowSectionOpen).toBe(true);
  1050. });
  1051. it("opens typed background sections and resets them independently", () => {
  1052. const root = createRoot(installMinimalDom());
  1053. mountedRoots.push(root);
  1054. const runningWork = {
  1055. workId: "work-bash",
  1056. kind: "bash" as const,
  1057. title: "Run checks",
  1058. status: "running" as const,
  1059. startedAt: 1_700_000_000_000,
  1060. anchorRowId: null,
  1061. };
  1062. const runningAgent = {
  1063. ...runningWork,
  1064. workId: "work-agent",
  1065. kind: "subagent" as const,
  1066. title: "Review changes",
  1067. };
  1068. const runningSubagents = [
  1069. {
  1070. childSessionId: "child-agent",
  1071. subagentType: "Explore",
  1072. title: "Review changes",
  1073. status: "running",
  1074. startedAt: 1_700_000_000_000,
  1075. },
  1076. ];
  1077. projectionState.current = {
  1078. status: "live",
  1079. snapshot: {
  1080. ...makeDraftSnapshot(),
  1081. sessionId: "session-1",
  1082. backgroundWorks: [runningWork, runningAgent],
  1083. subagents: {
  1084. revision: 1,
  1085. childSessionIds: ["child-agent"],
  1086. running: runningSubagents,
  1087. endedTotal: 0,
  1088. },
  1089. },
  1090. subscriptionId: "sub-session-1",
  1091. lastError: null,
  1092. optimisticCommands: [],
  1093. loadingOlder: false,
  1094. };
  1095. renderPane(root, "session-1");
  1096. expect(scrollFocus.statusPanelProps?.terminalSectionOpen).toBe(false);
  1097. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(false);
  1098. act(() => scrollFocus.composerProps?.onOpenRunningBackgroundWorks?.());
  1099. expect(scrollFocus.statusPanelProps?.summaryPanelVariantOverride).toBe("panel");
  1100. expect(scrollFocus.statusPanelProps?.terminalSectionOpen).toBe(true);
  1101. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(true);
  1102. act(() => scrollFocus.statusPanelProps?.onTerminalSectionOpenChange?.(false));
  1103. expect(scrollFocus.statusPanelProps?.terminalSectionOpen).toBe(false);
  1104. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(true);
  1105. act(() => scrollFocus.composerProps?.onOpenRunningBackgroundWorks?.());
  1106. expect(scrollFocus.statusPanelProps?.terminalSectionOpen).toBe(true);
  1107. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(true);
  1108. projectionState.current = {
  1109. ...projectionState.current,
  1110. snapshot: {
  1111. ...projectionState.current.snapshot,
  1112. sessionId: "session-2",
  1113. backgroundWorks: [runningWork, runningAgent],
  1114. },
  1115. subscriptionId: "sub-session-2",
  1116. };
  1117. renderPane(root, "session-2");
  1118. expect(scrollFocus.statusPanelProps?.terminalSectionOpen).toBe(false);
  1119. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(false);
  1120. act(() => scrollFocus.composerProps?.onOpenRunningBackgroundWorks?.());
  1121. projectionState.current = {
  1122. ...projectionState.current,
  1123. snapshot: {
  1124. ...projectionState.current.snapshot,
  1125. backgroundWorks: [runningAgent],
  1126. },
  1127. };
  1128. renderPane(root, "session-2");
  1129. expect(scrollFocus.statusPanelProps?.terminalSectionOpen).toBe(false);
  1130. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(true);
  1131. projectionState.current = {
  1132. ...projectionState.current,
  1133. snapshot: {
  1134. ...projectionState.current.snapshot,
  1135. backgroundWorks: [],
  1136. subagents: {
  1137. revision: 2,
  1138. childSessionIds: [],
  1139. running: [],
  1140. endedTotal: 0,
  1141. },
  1142. },
  1143. };
  1144. renderPane(root, "session-2");
  1145. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(false);
  1146. expect(scrollFocus.composerProps?.onOpenRunningBackgroundWorks).toBeUndefined();
  1147. });
  1148. });