v4SessionPaneReadOnly.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. // @vitest-environment jsdom
  2. import { createElement, type ReactNode } from "react";
  3. import { readFileSync } from "node:fs";
  4. import { renderToStaticMarkup } from "react-dom/server";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import type { ConversationSnapshot } from "@zcode/shared/zcode-protocol-v4";
  7. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  8. import { SessionPane } from "@/v4/SessionPane.js";
  9. import type { ConversationShareSelectionDraft } from "@/store/conversationShareSelectionStore.js";
  10. import type { ConversationRowRenderContext } from "@/v4/conversationRowContext.js";
  11. const sessionPaneSource = readFileSync("packages/ui/src/v4/SessionPane.tsx", "utf8");
  12. const projectionState = vi.hoisted(() => ({
  13. current: null as {
  14. status: "live";
  15. snapshot: ConversationSnapshot;
  16. subscriptionId: string;
  17. lastError: string | null;
  18. optimisticCommands: readonly [];
  19. loadingOlder: boolean;
  20. } | null,
  21. }));
  22. const timelineState = vi.hoisted(() => ({
  23. apiRetry: null as ConversationSnapshot["control"]["apiRetry"],
  24. rowContext: null as unknown,
  25. backgroundScrollLocked: false,
  26. selectionActionsEnabled: null as boolean | null,
  27. scrollToQueryActionRef: null as { current: unknown } | null,
  28. }));
  29. // SSR 渲染不执行 effect,因此 zustand 的 getServerSnapshot(= 初始 state)看不到真实 store
  30. // 的写入。这里直接替换 store,让测试能声明式地摆出任意 share draft。
  31. const shareStoreState = vi.hoisted(() => ({
  32. draft: undefined as unknown,
  33. }));
  34. vi.mock("@/store/conversationShareSelectionStore.js", async (importOriginal) => {
  35. const actual =
  36. await importOriginal<typeof import("@/store/conversationShareSelectionStore.js")>();
  37. const fakeState = () => ({
  38. popoverOpen: false,
  39. drafts: shareStoreState.draft ? { "child-session": shareStoreState.draft } : {},
  40. // ac4bc6e79c 起 SessionPane 从 dockStates[sessionId] 读取发布中 dock 状态,
  41. // mock 缺这个字段会让 SSR selector 读 undefined[sessionId] 直接抛错。
  42. dockStates: {},
  43. finishSelection: vi.fn(),
  44. updateDockState: vi.fn(),
  45. goToConfiguration: vi.fn(),
  46. goToSelection: vi.fn(),
  47. setAccessMode: vi.fn(),
  48. setAllRowsSelected: vi.fn(),
  49. showTimeline: vi.fn(),
  50. showSelectionPanel: vi.fn(),
  51. syncAvailableTurns: vi.fn(),
  52. toggleRow: vi.fn(),
  53. });
  54. // 只替换 hook 与 getState;派生 selector 保留真实实现,避免测试自证。
  55. const hook = (selector: (state: unknown) => unknown) => selector(fakeState());
  56. return {
  57. ...actual,
  58. useConversationShareSelectionStore: Object.assign(hook, { getState: fakeState }),
  59. };
  60. });
  61. vi.mock("@/v4/useConversationProjection.js", () => ({
  62. useConversationProjection: () => projectionState.current,
  63. }));
  64. vi.mock("@/v4/V4ConversationContext.js", () => ({
  65. useV4Conversation: () => ({
  66. attachmentPut: vi.fn(),
  67. layer: { acquire: vi.fn() },
  68. sendCommand: vi.fn(),
  69. }),
  70. }));
  71. vi.mock("@/store/StoreProvider.js", () => ({
  72. useZCodeStoreWithDefault: (_selector: unknown, fallback: unknown) => fallback,
  73. }));
  74. vi.mock("@/hooks/useSettingService.js", () => ({
  75. useSettings: () => ({
  76. error: null,
  77. loading: false,
  78. refresh: vi.fn(async () => {}),
  79. settings: { zcodeInteractionBehavior: "queue" },
  80. update: vi.fn(async () => {}),
  81. }),
  82. }));
  83. vi.mock("@/hooks/useServices.js", () => ({
  84. useOptionalServices: () => null,
  85. useServices: () => ({
  86. zcodeSessionService: {
  87. updateProviderRegistry: vi.fn(),
  88. },
  89. zcodeTaskService: {
  90. restartWorkspaceProcess: vi.fn(),
  91. },
  92. }),
  93. }));
  94. vi.mock("@/v4/composer/useDraftConfigControl.js", () => ({
  95. buildDraftCreateConfigPayload: () => ({}),
  96. useDraftConfigControl: () => ({
  97. modelSelectionRead: { state: { status: "loading" }, reload: vi.fn() },
  98. captureAcceptedModelSelection: () => vi.fn(),
  99. draftConfigRef: { current: {} },
  100. handleDraftSelectModel: vi.fn(),
  101. handleDraftSelectThought: vi.fn(),
  102. handleDraftSwitchMode: vi.fn(),
  103. }),
  104. }));
  105. vi.mock("@/v4/composer/useDraftSessionPrewarm.js", () => ({
  106. useDraftSessionPrewarm: () => ({
  107. binding: null,
  108. }),
  109. }));
  110. vi.mock("@/v4/ConversationComposer.js", async () => {
  111. const React = await import("react");
  112. return {
  113. ConversationComposer: () =>
  114. React.createElement("div", { "data-testid": "mock-composer" }, "composer"),
  115. };
  116. });
  117. vi.mock("@/v4/ConversationTimeline.js", async () => {
  118. const React = await import("react");
  119. return {
  120. ConversationTimeline: ({
  121. apiRetry,
  122. backgroundScrollLocked,
  123. bottomDock,
  124. rowContext,
  125. selectionActions,
  126. scrollToQueryActionRef,
  127. }: {
  128. apiRetry?: ConversationSnapshot["control"]["apiRetry"];
  129. backgroundScrollLocked?: boolean;
  130. bottomDock?: ReactNode;
  131. rowContext?: ConversationRowRenderContext;
  132. selectionActions?: { enabled: boolean };
  133. scrollToQueryActionRef?: { current: unknown };
  134. }) => {
  135. timelineState.apiRetry = apiRetry ?? null;
  136. timelineState.rowContext = rowContext ?? null;
  137. timelineState.backgroundScrollLocked = backgroundScrollLocked ?? false;
  138. timelineState.selectionActionsEnabled = selectionActions?.enabled ?? null;
  139. timelineState.scrollToQueryActionRef = scrollToQueryActionRef ?? null;
  140. return React.createElement("div", { "data-testid": "mock-timeline" }, bottomDock);
  141. },
  142. };
  143. });
  144. vi.mock("@/v4/ConversationHeader.js", async () => {
  145. const React = await import("react");
  146. return {
  147. ConversationHeader: () => React.createElement("div", { "data-testid": "mock-header" }),
  148. };
  149. });
  150. vi.mock("@/v4/ConversationStatusPanel.js", async () => {
  151. const React = await import("react");
  152. return {
  153. ConversationStatusPanel: () => React.createElement("div", { "data-testid": "mock-status" }),
  154. };
  155. });
  156. vi.mock("@/v4/ConversationQueuePanel.js", async () => {
  157. const React = await import("react");
  158. return {
  159. ConversationQueuePanel: () => React.createElement("div", { "data-testid": "mock-queue" }),
  160. };
  161. });
  162. vi.mock("@/v4/V4InteractionDialogs.js", async () => {
  163. const React = await import("react");
  164. return {
  165. V4InteractionDialogs: () => React.createElement("div", { "data-testid": "mock-interactions" }),
  166. };
  167. });
  168. vi.mock("@/request-security-edition/V4ProviderRuntimeHeadersController.js", async () => {
  169. const React = await import("react");
  170. return {
  171. V4ProviderRuntimeHeadersController: () =>
  172. React.createElement("div", { "data-testid": "mock-runtime-headers" }),
  173. };
  174. });
  175. function makeSnapshot(
  176. lastError: ConversationSnapshot["control"]["lastError"] = null,
  177. ): ConversationSnapshot {
  178. return {
  179. availability: {
  180. fork: { allowed: true },
  181. compact: { allowed: true },
  182. queueEdit: { allowed: true },
  183. pauseGoal: { allowed: false, reasonCode: "noGoalToPause" },
  184. resumeGoal: { allowed: false, reasonCode: "noGoalToResume" },
  185. sendQueuedNow: { allowed: true },
  186. setFollowupMode: { allowed: true },
  187. switchModelConfig: { allowed: true },
  188. },
  189. backgroundWorks: [],
  190. config: { followupMode: "queue", model: "", provider: "", thought: "" },
  191. control: {
  192. activeWorks: [],
  193. apiRetry: null,
  194. canStop: false,
  195. lastError,
  196. phase: "completedSuccess",
  197. sessionEnded: true,
  198. stopState: "idle",
  199. stopTargetKind: "unknown",
  200. },
  201. goal: null,
  202. inputRouting: { mode: "startNow" },
  203. logEpoch: "epoch-1",
  204. meta: { title: "Subagent", titleSource: "generated" },
  205. pendingCommands: [],
  206. pendingInteractions: [],
  207. plan: null,
  208. protocolVersion: 1,
  209. queue: { autoDrain: true, items: [] },
  210. revision: 1,
  211. rows: { firstRowId: null, totalCount: 0, window: [] },
  212. seq: 1,
  213. sessionId: "child-session",
  214. usage: {
  215. contextWindow: null,
  216. cumulative: {
  217. cacheReadTokens: 0,
  218. cacheWriteTokens: 0,
  219. inputTokens: 0,
  220. outputTokens: 0,
  221. },
  222. },
  223. };
  224. }
  225. function renderReadOnlyPane({
  226. allowWorkspaceFileRewind = false,
  227. apiRetry = null,
  228. lastError = null,
  229. readOnly = true,
  230. workflowRuns,
  231. sharedContextImport,
  232. }: {
  233. allowWorkspaceFileRewind?: boolean;
  234. apiRetry?: ConversationSnapshot["control"]["apiRetry"];
  235. lastError?: ConversationSnapshot["control"]["lastError"];
  236. readOnly?: boolean;
  237. workflowRuns?: ConversationSnapshot["workflowRuns"];
  238. sharedContextImport?: ConversationSnapshot["sharedContextImport"];
  239. } = {}): string {
  240. const snapshot = makeSnapshot(lastError);
  241. snapshot.control.apiRetry = apiRetry;
  242. if (workflowRuns) snapshot.workflowRuns = workflowRuns;
  243. snapshot.sharedContextImport = sharedContextImport;
  244. projectionState.current = {
  245. lastError: null,
  246. loadingOlder: false,
  247. optimisticCommands: [],
  248. snapshot,
  249. status: "live",
  250. subscriptionId: "sub-1",
  251. };
  252. return renderToStaticMarkup(
  253. createElement(
  254. ZCodeIntlProvider,
  255. { initialLocale: "zh-CN" },
  256. createElement(SessionPane, {
  257. allowWorkspaceFileRewind,
  258. paneId: "pane-1",
  259. readOnly,
  260. sessionId: "child-session",
  261. workspacePath: "/workspace",
  262. ...(readOnly ? {} : { onOpenWorkflowRun: () => {} }),
  263. }),
  264. ),
  265. );
  266. }
  267. describe("SessionPane read-only mode", () => {
  268. afterEach(() => {
  269. timelineState.apiRetry = null;
  270. timelineState.rowContext = null;
  271. });
  272. it("renders subagent child panes without composer or queue input affordances", () => {
  273. const html = renderReadOnlyPane();
  274. expect(html).toContain('data-testid="mock-timeline"');
  275. expect(html).not.toContain('data-testid="mock-composer"');
  276. expect(html).not.toContain('data-testid="mock-queue"');
  277. expect(timelineState.rowContext).toMatchObject({
  278. previewFileRewind: undefined,
  279. applyFileRewind: undefined,
  280. });
  281. });
  282. it("把 child snapshot 的 provider retry 传入只读时间线", () => {
  283. const apiRetry = {
  284. attempt: 2,
  285. maxAttempts: 6,
  286. nextRetryAt: 1_700_000_001_000,
  287. reasonCode: "fault.provider.requestFailed",
  288. };
  289. const html = renderReadOnlyPane({ apiRetry });
  290. expect(html).not.toContain('data-testid="mock-composer"');
  291. expect(timelineState.apiRetry).toEqual(apiRetry);
  292. });
  293. it("can expose workspace file rewind without making the child conversation editable", () => {
  294. const html = renderReadOnlyPane({ allowWorkspaceFileRewind: true });
  295. expect(html).not.toContain('data-testid="mock-composer"');
  296. expect(html).not.toContain('data-testid="mock-queue"');
  297. expect(timelineState.rowContext).toMatchObject({
  298. previewFileRewind: expect.any(Function),
  299. applyFileRewind: expect.any(Function),
  300. });
  301. });
  302. it("shows the current child projection error without adding an editable composer", () => {
  303. const html = renderReadOnlyPane({
  304. lastError: {
  305. at: 1_700_000_000_000,
  306. code: "fault.provider.requestFailed",
  307. message: "Provider connection failed",
  308. recoverable: true,
  309. source: "provider",
  310. },
  311. });
  312. expect(html).toContain('data-testid="v4-subagent-readonly-error"');
  313. expect(html).toContain("Provider connection failed");
  314. expect(html).not.toContain('data-testid="mock-composer"');
  315. });
  316. // 浮岛已删除(docs/dynamic-workflow/presentation.md「Other places a run appears」item 1):运行态迁进状态胶囊的
  317. // Workflows 分区,composer 上方不再有任何 workflow 浮层。原来这里是「只读缺席 / 主对话在场」
  318. // 两个方向的用例,现在**两个方向都断言无岛**——留一条正向用例才能钉住"删除是全局的",
  319. // 只删掉在场那条会让主对话 pane 重新长出浮岛而没人发现。
  320. const runningWorkflowRuns = {
  321. revision: 1,
  322. runs: [
  323. {
  324. runId: "dwfrun-1",
  325. toolCallId: "tool-wf-1",
  326. status: "running" as const,
  327. usage: { spentTokens: 0, nodesUsed: 0 },
  328. actors: [],
  329. nodes: [],
  330. lastEventSequence: 1,
  331. },
  332. ],
  333. };
  334. it("read-only panes never float the workflow run island", () => {
  335. const html = renderReadOnlyPane({ workflowRuns: runningWorkflowRuns });
  336. expect(html).not.toContain('data-testid="workflow-run-island"');
  337. });
  338. it("primary conversation panes no longer float the workflow run island either", () => {
  339. const html = renderReadOnlyPane({ readOnly: false, workflowRuns: runningWorkflowRuns });
  340. expect(html).toContain('data-testid="mock-composer"');
  341. expect(html).not.toContain('data-testid="workflow-run-island"');
  342. expect(html).not.toContain("workflow-run-island-pill");
  343. });
  344. it("does not show the legacy imported-share notice in read-only panes", () => {
  345. const html = renderReadOnlyPane({
  346. sharedContextImport: { title: "筛选近一年收益前10%的偏股混合基金" },
  347. });
  348. expect(html).not.toContain('data-testid="conversation-share-import-notice"');
  349. expect(html).not.toContain("shared_context");
  350. });
  351. });
  352. /**
  353. * 这些用例守护 SessionPane 到 timeline 的分享模式接线。
  354. *
  355. * Bug 根因:滚动锁定、勾选期禁用 message 工具条和 dock 进出动画曾经只有 policy 模块的
  356. * 隔离单测,SessionPane 从未引用过它们,所以三条修复实际都没生效而测试仍是绿的。
  357. * 断言必须落在 SessionPane 真正传给 ConversationTimeline 的 props 上。
  358. */
  359. describe("SessionPane 分享模式接线", () => {
  360. afterEach(() => {
  361. timelineState.apiRetry = null;
  362. timelineState.rowContext = null;
  363. timelineState.backgroundScrollLocked = false;
  364. timelineState.selectionActionsEnabled = null;
  365. timelineState.scrollToQueryActionRef = null;
  366. shareStoreState.draft = undefined;
  367. });
  368. const partialDraft = (
  369. overrides: Partial<ConversationShareSelectionDraft> = {},
  370. ): ConversationShareSelectionDraft => ({
  371. scope: "partial",
  372. stage: "selection",
  373. view: "selection",
  374. availableRowIds: [1],
  375. excludedRowIds: [],
  376. productTurnIdByRowId: { 1: "product-turn-1" },
  377. accessMode: "private",
  378. ...overrides,
  379. });
  380. const renderSharePane = (draft?: ConversationShareSelectionDraft): string => {
  381. shareStoreState.draft = draft;
  382. projectionState.current = {
  383. lastError: null,
  384. loadingOlder: false,
  385. optimisticCommands: [],
  386. snapshot: makeSnapshot(null),
  387. status: "live",
  388. subscriptionId: "sub-1",
  389. };
  390. return renderToStaticMarkup(
  391. createElement(
  392. ZCodeIntlProvider,
  393. { initialLocale: "zh-CN" },
  394. createElement(SessionPane, {
  395. paneId: "pane-1",
  396. readOnly: false,
  397. sessionId: "child-session",
  398. workspacePath: "/workspace",
  399. }),
  400. ),
  401. );
  402. };
  403. it("选择面板展开时锁定背景滚动,收起到 timeline 后恢复", () => {
  404. renderSharePane(partialDraft({ view: "selection" }));
  405. expect(timelineState.backgroundScrollLocked).toBe(true);
  406. renderSharePane(partialDraft({ view: "timeline" }));
  407. expect(timelineState.backgroundScrollLocked).toBe(false);
  408. });
  409. it("选择面板展开时向 Timeline 传递正文定位 action ref", () => {
  410. renderSharePane(partialDraft({ view: "selection" }));
  411. expect(timelineState.scrollToQueryActionRef).not.toBeNull();
  412. });
  413. it("进入配置阶段后不再锁定背景滚动", () => {
  414. renderSharePane(partialDraft({ stage: "configuration", view: "selection" }));
  415. expect(timelineState.backgroundScrollLocked).toBe(false);
  416. });
  417. it("预检可跳过项不提前写入发布成功 warning,避免确认页重复展示", () => {
  418. const nextHandlerStart = sessionPaneSource.indexOf("const handleShareNext = useCallback");
  419. const nextHandlerEnd = sessionPaneSource.indexOf(
  420. "const handleShareSelectAll = useCallback",
  421. nextHandlerStart,
  422. );
  423. expect(nextHandlerStart).toBeGreaterThanOrEqual(0);
  424. expect(nextHandlerEnd).toBeGreaterThan(nextHandlerStart);
  425. const nextHandler = sessionPaneSource.slice(nextHandlerStart, nextHandlerEnd);
  426. expect(nextHandler).toContain("goToShareConfiguration(sessionId)");
  427. expect(nextHandler).not.toContain("setShareWarnings");
  428. });
  429. it("不在分享模式时不锁定背景滚动", () => {
  430. renderSharePane(undefined);
  431. expect(timelineState.backgroundScrollLocked).toBe(false);
  432. });
  433. it("局部勾选期间禁用全局 message 工具条,退出分享后恢复", () => {
  434. renderSharePane(partialDraft());
  435. expect(timelineState.selectionActionsEnabled).toBe(false);
  436. renderSharePane(undefined);
  437. expect(timelineState.selectionActionsEnabled).toBe(true);
  438. });
  439. it("chat 与分享 dock 通过同一个过渡层切换 mode", () => {
  440. expect(renderSharePane(undefined)).toContain('data-conversation-bottom-dock-mode="chat"');
  441. expect(renderSharePane(partialDraft())).toContain(
  442. 'data-conversation-bottom-dock-mode="confirmation"',
  443. );
  444. });
  445. });