v4SessionPaneComposerContinuity.test.ts 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  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, type SessionPaneProps } 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(
  495. root: Root,
  496. sessionId: string | null,
  497. props: Partial<SessionPaneProps> = {},
  498. ): void {
  499. act(() => {
  500. root.render(
  501. createElement(
  502. ZCodeIntlProvider,
  503. { initialLocale: "zh-CN" },
  504. createElement(SessionPane, {
  505. paneId: "workspace-main",
  506. sessionId,
  507. workspacePath: "/workspace",
  508. ...props,
  509. }),
  510. ),
  511. );
  512. });
  513. }
  514. beforeEach(() => {
  515. servicesMock.projectService.resolveSessionDirectories.mockClear();
  516. sessionCreateCapture.report.mockClear();
  517. recoveryCapture.entries = [];
  518. recoveryCapture.onResend = null;
  519. prewarmHookInputs.binding = null;
  520. composerLifecycle.disabledStates = [];
  521. composerLifecycle.mounts = 0;
  522. composerLifecycle.nextInstanceId = 1;
  523. composerLifecycle.renders = [];
  524. composerLifecycle.unmounts = 0;
  525. conversationMock.layer.acquire.mockClear();
  526. conversationMock.lease.release.mockClear();
  527. conversationMock.lease.store.expectAcceptedInputProjection.mockClear();
  528. conversationMock.currentLayer = null;
  529. conversationMock.currentSendCommand = null;
  530. conversationMock.sendCommand.mockReset();
  531. conversationMock.sendCommand.mockImplementation(async (envelope) => ({
  532. commandId: envelope.commandId,
  533. revisionAtDecision: 1,
  534. status: "accepted" as const,
  535. }));
  536. prewarmHookInputs.current = [];
  537. scrollFocus.composerProps = null;
  538. scrollFocus.queueProps = null;
  539. scrollFocus.statusPanelProps = null;
  540. scrollFocus.scrollToBottom.mockClear();
  541. projectionState.current = {
  542. status: "live",
  543. snapshot: makeDraftSnapshot(),
  544. subscriptionId: "sub-draft",
  545. lastError: null,
  546. optimisticCommands: [],
  547. loadingOlder: false,
  548. };
  549. });
  550. afterEach(() => {
  551. for (const root of mountedRoots.splice(0)) {
  552. act(() => root.unmount());
  553. }
  554. delete (globalThis as { document?: unknown }).document;
  555. delete (globalThis as { window?: unknown }).window;
  556. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  557. });
  558. describe("SessionPane composer continuity", () => {
  559. it.each([
  560. ["selection_side_chat", true, "parent"],
  561. ["interactive", false, "session-1"],
  562. ["fork", false, "session-1"],
  563. ] as const)("%s 发送按自身语义解析 Recent 归属", async (_kind, selectionSideChat, ownerId) => {
  564. const root = createRoot(installMinimalDom());
  565. mountedRoots.push(root);
  566. projectionState.current = {
  567. ...projectionState.current,
  568. snapshot: { ...makeDraftSnapshot(), sessionId: "session-1" },
  569. };
  570. servicesMock.projectService.resolveSessionDirectories.mockImplementationOnce(async (task) => {
  571. if (selectionSideChat && task.taskId === "session-1")
  572. throw new Error("project.remote-project-required");
  573. return { ...task, projectId: null, additionalDirectories: [] };
  574. });
  575. renderPane(root, "session-1", { selectionSideChat, rootSessionId: "parent" });
  576. await act(async () => {
  577. await scrollFocus.composerProps?.onSendText("follow up");
  578. });
  579. expect(servicesMock.projectService.resolveSessionDirectories).toHaveBeenCalledWith(
  580. expect.objectContaining({ taskId: ownerId }),
  581. expect.any(String),
  582. );
  583. expect(conversationMock.sendCommand).toHaveBeenCalledWith(
  584. expect.objectContaining({ type: "sendText", sessionId: "session-1" }),
  585. );
  586. });
  587. it.each(["group", "project", "session"] as const)(
  588. "%s 首发只在 accepted 后报告,打开和后续发送不报告",
  589. async (source) => {
  590. const store = useZCodeSessionStore.getState();
  591. store.startDraft("/workspace", undefined, undefined, { createSource: source });
  592. const root = createRoot(installMinimalDom());
  593. mountedRoots.push(root);
  594. renderPane(root, null);
  595. expect(sessionCreateCapture.report).not.toHaveBeenCalled();
  596. conversationMock.sendCommand.mockImplementationOnce(async (envelope) => ({
  597. commandId: envelope.commandId,
  598. revisionAtDecision: 1,
  599. status: "accepted" as const,
  600. result: { type: "createSession", sessionId: `created-${source}` },
  601. }));
  602. await act(async () => {
  603. await scrollFocus.composerProps?.onSendText("create session");
  604. });
  605. // Highspeed 统一了首发链路:无附件首发也走「空 createSession + sendText」两段式,
  606. // 好让抽卡 admission 拿到真实 sessionId,因此首发 message_id 是 sendText 的 commandId
  607. // (calls[1]),不是空创建的 commandId(calls[0])。埋点不变量仍成立:accepted 后只报一次。
  608. const firstSendCalls = conversationMock.sendCommand.mock.calls;
  609. expect(firstSendCalls).toHaveLength(2);
  610. expect(sessionCreateCapture.report).toHaveBeenCalledExactlyOnceWith(
  611. null,
  612. expect.objectContaining({
  613. sessionId: `created-${source}`,
  614. messageId: firstSendCalls[1]![0].commandId,
  615. source,
  616. }),
  617. );
  618. renderPane(root, `created-${source}`);
  619. await act(async () => {
  620. await scrollFocus.composerProps?.onSendText("follow up");
  621. });
  622. expect(sessionCreateCapture.report).toHaveBeenCalledTimes(1);
  623. },
  624. );
  625. it.each(["accepted", "rejected"] as const)("Goal 首发 %s 时只按 ACK 统计", async (status) => {
  626. const root = createRoot(installMinimalDom());
  627. mountedRoots.push(root);
  628. renderPane(root, null);
  629. conversationMock.sendCommand.mockImplementationOnce(async (envelope) => ({
  630. commandId: envelope.commandId,
  631. revisionAtDecision: 1,
  632. status: "accepted" as const,
  633. result: { type: "createSession", sessionId: "goal-created" },
  634. }));
  635. conversationMock.sendCommand.mockResolvedValueOnce({
  636. commandId: "goal-command",
  637. revisionAtDecision: 1,
  638. status,
  639. } as never);
  640. await act(async () => {
  641. await scrollFocus.composerProps?.onSendText("/goal explain the test");
  642. });
  643. expect(sessionCreateCapture.report).toHaveBeenCalledTimes(status === "accepted" ? 1 : 0);
  644. if (status === "accepted")
  645. expect(sessionCreateCapture.report).toHaveBeenCalledWith(
  646. null,
  647. expect.objectContaining({ messageId: "goal-command" }),
  648. );
  649. });
  650. it.each(["hello", "/goal explain"])("预热首发 %s 携带实际输入 commandId", async (text) => {
  651. prewarmHookInputs.binding = {
  652. sessionId: "prewarmed",
  653. beginPromotion: () => true,
  654. promote: vi.fn(),
  655. };
  656. const root = createRoot(installMinimalDom());
  657. mountedRoots.push(root);
  658. renderPane(root, null);
  659. await act(async () => {
  660. await scrollFocus.composerProps?.onSendText(text);
  661. });
  662. const commandId = conversationMock.sendCommand.mock.calls[0]![0].commandId;
  663. expect(sessionCreateCapture.report).toHaveBeenCalledExactlyOnceWith(
  664. null,
  665. expect.objectContaining({ sessionId: "prewarmed", messageId: commandId }),
  666. );
  667. });
  668. it("先空创建再首发使用 sendText ID,不用空创建 ID", async () => {
  669. const root = createRoot(installMinimalDom());
  670. mountedRoots.push(root);
  671. renderPane(root, null);
  672. conversationMock.sendCommand.mockImplementationOnce(async (envelope) => ({
  673. commandId: envelope.commandId,
  674. revisionAtDecision: 1,
  675. status: "accepted" as const,
  676. result: { type: "createSession", sessionId: "two-phase" },
  677. }));
  678. await act(async () => {
  679. await scrollFocus.composerProps?.onSendText("context", {
  680. sharedContextRefs: [{ kind: "shared_context_import", context_id: "context-1" }],
  681. });
  682. });
  683. const calls = conversationMock.sendCommand.mock.calls;
  684. expect(calls).toHaveLength(2);
  685. expect(calls[0]![0].commandId).not.toBe(calls[1]![0].commandId);
  686. expect(sessionCreateCapture.report).toHaveBeenCalledWith(
  687. null,
  688. expect.objectContaining({ messageId: calls[1]![0].commandId }),
  689. );
  690. });
  691. it("用户确认恢复重发使用新 accepted ID,不用旧命令 ID", async () => {
  692. recoveryCapture.entries = [
  693. {
  694. commandId: "old-command",
  695. sessionId: null,
  696. replay: { kind: "input" },
  697. } as PendingCommandEntry,
  698. ];
  699. const replay = vi.spyOn(pendingCommandRegistry, "consumeReplay").mockReturnValueOnce({
  700. type: "createSession",
  701. sessionId: null,
  702. payload: { workspaceId: "/workspace", firstInput: { text: "retry" } },
  703. clientContext: { workspace: { workspacePath: "/workspace" }, sessionCreateSource: "project" },
  704. });
  705. try {
  706. const root = createRoot(installMinimalDom());
  707. mountedRoots.push(root);
  708. renderPane(root, null);
  709. conversationMock.sendCommand.mockImplementationOnce(async (envelope) => ({
  710. commandId: envelope.commandId,
  711. revisionAtDecision: 1,
  712. status: "accepted" as const,
  713. result: { type: "createSession", sessionId: "recovered" },
  714. }));
  715. await act(async () => {
  716. recoveryCapture.onResend?.();
  717. });
  718. const newId = conversationMock.sendCommand.mock.calls[0]![0].commandId;
  719. expect(newId).not.toBe("old-command");
  720. expect(sessionCreateCapture.report).toHaveBeenCalledWith(
  721. null,
  722. expect.objectContaining({ sessionId: "recovered", messageId: newId }),
  723. );
  724. } finally {
  725. replay.mockRestore();
  726. }
  727. });
  728. it("首发传输失败不产生 session_create", async () => {
  729. const root = createRoot(installMinimalDom());
  730. mountedRoots.push(root);
  731. renderPane(root, null);
  732. conversationMock.sendCommand.mockRejectedValueOnce(new Error("transport offline"));
  733. await act(async () => {
  734. await expect(scrollFocus.composerProps?.onSendText("create session")).rejects.toThrow(
  735. "transport offline",
  736. );
  737. });
  738. expect(sessionCreateCapture.report).not.toHaveBeenCalled();
  739. });
  740. it("/goal 沿用点击发送时冻结的 Submission,不在异步准备后回读草稿", async () => {
  741. const root = createRoot(installMinimalDom());
  742. mountedRoots.push(root);
  743. renderPane(root, "session-1");
  744. const submission = {
  745. mode: "build" as const,
  746. modelSelection: {
  747. providerId: "provider-deepseek",
  748. modelId: "deepseek-v4-flash",
  749. options: { reasoningLevel: "low" },
  750. },
  751. };
  752. await act(async () => {
  753. await scrollFocus.composerProps?.onSendText("/goal 固定此次选择", { submission });
  754. });
  755. expect(conversationMock.sendCommand).toHaveBeenCalledWith(
  756. expect.objectContaining({
  757. type: "sendGoalCommand",
  758. payload: expect.objectContaining(submission),
  759. }),
  760. );
  761. });
  762. it("workspace 切换后旧预热 dispatcher 仍发送到原本地 transport", async () => {
  763. const sendCommandA = vi.fn(async (envelope: { commandId: string }) => ({
  764. commandId: envelope.commandId,
  765. revisionAtDecision: 1,
  766. status: "accepted" as const,
  767. }));
  768. const sendCommandB = vi.fn(async (envelope: { commandId: string }) => ({
  769. commandId: envelope.commandId,
  770. revisionAtDecision: 1,
  771. status: "accepted" as const,
  772. }));
  773. const layerA = { ...conversationMock.layer };
  774. const layerB = { ...conversationMock.layer };
  775. const root = createRoot(installMinimalDom());
  776. mountedRoots.push(root);
  777. conversationMock.currentLayer = layerA;
  778. conversationMock.currentSendCommand = sendCommandA;
  779. act(() => {
  780. root.render(
  781. createElement(
  782. ZCodeIntlProvider,
  783. { initialLocale: "zh-CN" },
  784. createElement(SessionPane, {
  785. paneId: "workspace-main",
  786. sessionId: null,
  787. workspacePath: "/local/a",
  788. }),
  789. ),
  790. );
  791. });
  792. const bindingA = prewarmHookInputs.current.findLast(
  793. (input) => input.workspaceKey === "/local/a",
  794. );
  795. // Bug 根因:single-flight 协调器已改用稳定的 SessionDataLayer 标识 transport,
  796. // 旧断言仍把 provider 每次可重建的 sendCommand wrapper 当作 identity。
  797. expect(bindingA?.transportIdentity).toBe(layerA);
  798. conversationMock.currentLayer = layerB;
  799. conversationMock.currentSendCommand = sendCommandB;
  800. act(() => {
  801. root.render(
  802. createElement(
  803. ZCodeIntlProvider,
  804. { initialLocale: "zh-CN" },
  805. createElement(SessionPane, {
  806. paneId: "workspace-main",
  807. sessionId: null,
  808. workspacePath: "/local/b",
  809. }),
  810. ),
  811. );
  812. });
  813. await act(async () => {
  814. await bindingA?.dispatchCommand("deleteSession", {}, "draft-a");
  815. });
  816. expect(sendCommandA).toHaveBeenCalledTimes(1);
  817. expect(sendCommandB).not.toHaveBeenCalled();
  818. });
  819. it("keeps one composer instance while draft promotion waits for the first snapshot", () => {
  820. const root = createRoot(installMinimalDom());
  821. mountedRoots.push(root);
  822. renderPane(root, null);
  823. projectionState.current = {
  824. status: "connecting",
  825. snapshot: null,
  826. subscriptionId: null,
  827. lastError: null,
  828. optimisticCommands: [],
  829. loadingOlder: false,
  830. };
  831. renderPane(root, "session-1");
  832. projectionState.current = {
  833. status: "live",
  834. snapshot: { ...makeDraftSnapshot(), sessionId: "session-1" },
  835. subscriptionId: "sub-session",
  836. lastError: null,
  837. optimisticCommands: [],
  838. loadingOlder: false,
  839. };
  840. renderPane(root, "session-1");
  841. expect(composerLifecycle.mounts).toBe(1);
  842. expect(composerLifecycle.unmounts).toBe(0);
  843. expect(new Set(composerLifecycle.renders)).toEqual(new Set([1]));
  844. expect(composerLifecycle.disabledStates).toContain(true);
  845. expect(composerLifecycle.disabledStates.at(-1)).toBe(false);
  846. });
  847. it("focuses after start-now, preserves position on enqueue, and focuses on queue send-now", async () => {
  848. const root = createRoot(installMinimalDom());
  849. mountedRoots.push(root);
  850. projectionState.current = {
  851. status: "live",
  852. snapshot: { ...makeDraftSnapshot(), sessionId: "session-1" },
  853. subscriptionId: "sub-session",
  854. lastError: null,
  855. optimisticCommands: [],
  856. loadingOlder: false,
  857. };
  858. renderPane(root, "session-1");
  859. await act(async () => {
  860. await scrollFocus.composerProps?.onSendText("direct prompt");
  861. });
  862. expect(scrollFocus.scrollToBottom).toHaveBeenCalledTimes(1);
  863. scrollFocus.scrollToBottom.mockClear();
  864. projectionState.current = {
  865. ...projectionState.current,
  866. snapshot: {
  867. ...projectionState.current.snapshot,
  868. inputRouting: { mode: "enqueue" },
  869. },
  870. };
  871. renderPane(root, "session-1");
  872. await act(async () => {
  873. await scrollFocus.composerProps?.onSendText("queued prompt");
  874. });
  875. expect(scrollFocus.scrollToBottom).not.toHaveBeenCalled();
  876. act(() => scrollFocus.queueProps?.onSendNow?.("queue-1"));
  877. expect(scrollFocus.scrollToBottom).toHaveBeenCalledTimes(1);
  878. });
  879. it("running startNow dispatches one atomic sendText and never creates or promotes a queue item", async () => {
  880. const root = createRoot(installMinimalDom());
  881. mountedRoots.push(root);
  882. projectionState.current = {
  883. status: "live",
  884. snapshot: {
  885. ...makeDraftSnapshot(),
  886. sessionId: "session-1",
  887. inputRouting: { mode: "enqueue" },
  888. },
  889. subscriptionId: "sub-session",
  890. lastError: null,
  891. optimisticCommands: [],
  892. loadingOlder: false,
  893. };
  894. renderPane(root, "session-1");
  895. conversationMock.sendCommand.mockReset();
  896. conversationMock.sendCommand.mockImplementation(async (envelope) => ({
  897. commandId: envelope.commandId,
  898. revisionAtDecision: 1,
  899. status: "accepted" as const,
  900. }));
  901. await act(async () => {
  902. await scrollFocus.composerProps?.onSendText("立即执行", {
  903. requestedDelivery: "startNow",
  904. });
  905. });
  906. expect(conversationMock.sendCommand).toHaveBeenCalledTimes(1);
  907. expect(conversationMock.sendCommand).toHaveBeenCalledWith(
  908. expect.objectContaining({
  909. type: "sendText",
  910. payload: expect.objectContaining({
  911. text: "立即执行",
  912. requestedDelivery: "startNow",
  913. }),
  914. }),
  915. );
  916. expect(conversationMock.lease.store.expectAcceptedInputProjection).toHaveBeenCalledWith(
  917. conversationMock.sendCommand.mock.calls[0]?.[0].commandId,
  918. );
  919. });
  920. it("routes paused queue input to modal, while /compact queues directly", async () => {
  921. const root = createRoot(installMinimalDom());
  922. mountedRoots.push(root);
  923. const queuedItem = {
  924. queueItemId: "q-1",
  925. kind: "sendText" as const,
  926. text: "旧消息",
  927. sourceCommandId: "old-command",
  928. clientId: "desktop",
  929. attachments: [],
  930. delivery: { requested: "queue" as const, admitted: "queue" as const },
  931. order: { admissionSeq: 1, queuePosition: 0 },
  932. steer: { state: "notRequested" as const },
  933. dispatch: { state: "queued" as const },
  934. admittedAt: 1,
  935. };
  936. projectionState.current = {
  937. status: "live",
  938. snapshot: {
  939. ...makeDraftSnapshot(),
  940. sessionId: "session-1",
  941. revision: 7,
  942. inputRouting: { mode: "choice" },
  943. queue: { autoDrain: false, pauseReason: "stopped", items: [queuedItem] },
  944. },
  945. subscriptionId: "sub-session",
  946. lastError: null,
  947. optimisticCommands: [],
  948. loadingOlder: false,
  949. };
  950. renderPane(root, "session-1");
  951. await act(async () => {
  952. await expect(scrollFocus.composerProps?.onSendText("新消息")).resolves.toBe(
  953. "confirmationRequired",
  954. );
  955. await expect(scrollFocus.composerProps?.onSendText("/goal 新目标")).resolves.toBe(
  956. "confirmationRequired",
  957. );
  958. });
  959. expect(conversationMock.sendCommand).not.toHaveBeenCalled();
  960. await act(async () => {
  961. await scrollFocus.composerProps?.onSendText("/compact");
  962. });
  963. expect(conversationMock.sendCommand).toHaveBeenCalledWith(
  964. expect.objectContaining({ type: "compact", sessionId: "session-1" }),
  965. );
  966. conversationMock.sendCommand.mockReset();
  967. conversationMock.sendCommand.mockImplementation(async (envelope) => ({
  968. commandId: envelope.commandId,
  969. revisionAtDecision: 1,
  970. status: "accepted" as const,
  971. }));
  972. await act(async () => {
  973. await scrollFocus.composerProps?.onSendText("新消息", {
  974. heldQueueDisposition: "clearQueueAndSend",
  975. expectedHeldQueueItemIds: ["q-1"],
  976. });
  977. });
  978. expect(conversationMock.sendCommand).toHaveBeenCalledWith(
  979. expect.objectContaining({
  980. type: "sendText",
  981. payload: expect.objectContaining({
  982. heldQueueDisposition: "clearQueueAndSend",
  983. expectedHeldQueueItemIds: ["q-1"],
  984. }),
  985. }),
  986. );
  987. });
  988. it("paused queue continue dispatches CAS setAutoDrain without preempting in UI", async () => {
  989. const root = createRoot(installMinimalDom());
  990. mountedRoots.push(root);
  991. const snapshot = makeDraftSnapshot();
  992. projectionState.current = {
  993. status: "live",
  994. snapshot: {
  995. ...snapshot,
  996. sessionId: "session-1",
  997. revision: 9,
  998. queue: {
  999. autoDrain: false,
  1000. items: [
  1001. {
  1002. queueItemId: "q-1",
  1003. kind: "sendText",
  1004. text: "旧消息",
  1005. sourceCommandId: "old-command",
  1006. clientId: "desktop",
  1007. attachments: [],
  1008. delivery: { requested: "queue", admitted: "queue" },
  1009. order: { admissionSeq: 1, queuePosition: 0 },
  1010. steer: { state: "notRequested" },
  1011. dispatch: { state: "queued" },
  1012. admittedAt: 1,
  1013. },
  1014. ],
  1015. },
  1016. },
  1017. subscriptionId: "sub-session",
  1018. lastError: null,
  1019. optimisticCommands: [],
  1020. loadingOlder: false,
  1021. };
  1022. renderPane(root, "session-1");
  1023. await scrollFocus.queueProps?.onResume?.();
  1024. expect(conversationMock.sendCommand).toHaveBeenCalledWith(
  1025. expect.objectContaining({
  1026. baseRevision: 9,
  1027. payload: { autoDrain: true },
  1028. sessionId: "session-1",
  1029. type: "setAutoDrain",
  1030. }),
  1031. );
  1032. });
  1033. // 展开后看到的不能比胶囊还少(docs/dynamic-workflow/presentation.md「Other places a run appears」):
  1034. // 活的 run 出现时(在跑数从 0 变成 ≥1,包括进入一个本就有活 run 的会话)「工作流」分区打开;
  1035. // 最后一条结束时折起。读者手动折起后保持折起,直到 run 全部结束或换会话。
  1036. it("opens the Workflows section while a run is live and respects a manual fold", () => {
  1037. const root = createRoot(installMinimalDom());
  1038. mountedRoots.push(root);
  1039. const liveRun = {
  1040. runId: "dwfrun-1",
  1041. toolCallId: "tool-wf-1",
  1042. status: "running" as const,
  1043. usage: { spentTokens: 0, nodesUsed: 0 },
  1044. actors: [],
  1045. nodes: [],
  1046. lastEventSequence: 1,
  1047. };
  1048. const withRuns = (sessionId: string, runs: (typeof liveRun)[]) => ({
  1049. status: "live" as const,
  1050. snapshot: {
  1051. ...makeDraftSnapshot(),
  1052. sessionId,
  1053. workflowRuns: { revision: runs.length, runs },
  1054. },
  1055. subscriptionId: `sub-${sessionId}`,
  1056. lastError: null,
  1057. optimisticCommands: [],
  1058. loadingOlder: false,
  1059. });
  1060. projectionState.current = withRuns("session-1", []);
  1061. renderPane(root, "session-1");
  1062. expect(scrollFocus.statusPanelProps?.workflowSectionOpen).toBe(false);
  1063. // 0 → 1:打开。
  1064. projectionState.current = withRuns("session-1", [liveRun]);
  1065. renderPane(root, "session-1");
  1066. expect(scrollFocus.statusPanelProps?.workflowSectionOpen).toBe(true);
  1067. // 手动折起后,run 还在跑(再来一条也一样)就保持折起。
  1068. act(() => scrollFocus.statusPanelProps?.onWorkflowSectionOpenChange?.(false));
  1069. projectionState.current = withRuns("session-1", [liveRun, { ...liveRun, runId: "dwfrun-2" }]);
  1070. renderPane(root, "session-1");
  1071. expect(scrollFocus.statusPanelProps?.workflowSectionOpen).toBe(false);
  1072. // 全部结束:折起;下一条 run 出现:重新打开。
  1073. projectionState.current = withRuns("session-1", [{ ...liveRun, status: "completed" as never }]);
  1074. renderPane(root, "session-1");
  1075. expect(scrollFocus.statusPanelProps?.workflowSectionOpen).toBe(false);
  1076. projectionState.current = withRuns("session-1", [{ ...liveRun, runId: "dwfrun-3" }]);
  1077. renderPane(root, "session-1");
  1078. expect(scrollFocus.statusPanelProps?.workflowSectionOpen).toBe(true);
  1079. // 在一个有活 run 的会话里折起,再进入另一个也有活 run 的会话:新会话里是打开的。
  1080. act(() => scrollFocus.statusPanelProps?.onWorkflowSectionOpenChange?.(false));
  1081. projectionState.current = withRuns("session-2", [liveRun]);
  1082. renderPane(root, "session-2");
  1083. expect(scrollFocus.statusPanelProps?.workflowSectionOpen).toBe(true);
  1084. });
  1085. it("opens typed background sections and resets them independently", () => {
  1086. const root = createRoot(installMinimalDom());
  1087. mountedRoots.push(root);
  1088. const runningWork = {
  1089. workId: "work-bash",
  1090. kind: "bash" as const,
  1091. title: "Run checks",
  1092. status: "running" as const,
  1093. startedAt: 1_700_000_000_000,
  1094. anchorRowId: null,
  1095. };
  1096. const runningAgent = {
  1097. ...runningWork,
  1098. workId: "work-agent",
  1099. kind: "subagent" as const,
  1100. title: "Review changes",
  1101. };
  1102. const runningSubagents = [
  1103. {
  1104. childSessionId: "child-agent",
  1105. subagentType: "Explore",
  1106. title: "Review changes",
  1107. status: "running",
  1108. startedAt: 1_700_000_000_000,
  1109. },
  1110. ];
  1111. projectionState.current = {
  1112. status: "live",
  1113. snapshot: {
  1114. ...makeDraftSnapshot(),
  1115. sessionId: "session-1",
  1116. backgroundWorks: [runningWork, runningAgent],
  1117. subagents: {
  1118. revision: 1,
  1119. childSessionIds: ["child-agent"],
  1120. running: runningSubagents,
  1121. endedTotal: 0,
  1122. },
  1123. },
  1124. subscriptionId: "sub-session-1",
  1125. lastError: null,
  1126. optimisticCommands: [],
  1127. loadingOlder: false,
  1128. };
  1129. renderPane(root, "session-1");
  1130. expect(scrollFocus.statusPanelProps?.terminalSectionOpen).toBe(false);
  1131. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(false);
  1132. act(() => scrollFocus.composerProps?.onOpenRunningBackgroundWorks?.());
  1133. expect(scrollFocus.statusPanelProps?.summaryPanelVariantOverride).toBe("panel");
  1134. expect(scrollFocus.statusPanelProps?.terminalSectionOpen).toBe(true);
  1135. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(true);
  1136. act(() => scrollFocus.statusPanelProps?.onTerminalSectionOpenChange?.(false));
  1137. expect(scrollFocus.statusPanelProps?.terminalSectionOpen).toBe(false);
  1138. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(true);
  1139. act(() => scrollFocus.composerProps?.onOpenRunningBackgroundWorks?.());
  1140. expect(scrollFocus.statusPanelProps?.terminalSectionOpen).toBe(true);
  1141. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(true);
  1142. projectionState.current = {
  1143. ...projectionState.current,
  1144. snapshot: {
  1145. ...projectionState.current.snapshot,
  1146. sessionId: "session-2",
  1147. backgroundWorks: [runningWork, runningAgent],
  1148. },
  1149. subscriptionId: "sub-session-2",
  1150. };
  1151. renderPane(root, "session-2");
  1152. expect(scrollFocus.statusPanelProps?.terminalSectionOpen).toBe(false);
  1153. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(false);
  1154. act(() => scrollFocus.composerProps?.onOpenRunningBackgroundWorks?.());
  1155. projectionState.current = {
  1156. ...projectionState.current,
  1157. snapshot: {
  1158. ...projectionState.current.snapshot,
  1159. backgroundWorks: [runningAgent],
  1160. },
  1161. };
  1162. renderPane(root, "session-2");
  1163. expect(scrollFocus.statusPanelProps?.terminalSectionOpen).toBe(false);
  1164. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(true);
  1165. projectionState.current = {
  1166. ...projectionState.current,
  1167. snapshot: {
  1168. ...projectionState.current.snapshot,
  1169. backgroundWorks: [],
  1170. subagents: {
  1171. revision: 2,
  1172. childSessionIds: [],
  1173. running: [],
  1174. endedTotal: 0,
  1175. },
  1176. },
  1177. };
  1178. renderPane(root, "session-2");
  1179. expect(scrollFocus.statusPanelProps?.agentSectionOpen).toBe(false);
  1180. expect(scrollFocus.composerProps?.onOpenRunningBackgroundWorks).toBeUndefined();
  1181. });
  1182. });