v4SessionPaneComposerContinuity.test.ts 40 KB

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