v4SessionPaneReadOnly.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. drafts: shareStoreState.draft ? { "child-session": shareStoreState.draft } : {},
  39. // ac4bc6e79c 起 SessionPane 从 dockStates[sessionId] 读取发布中 dock 状态,
  40. // mock 缺这个字段会让 SSR selector 读 undefined[sessionId] 直接抛错。
  41. dockStates: {},
  42. closeShare: vi.fn(),
  43. confirmSelectionEdit: vi.fn(),
  44. beginSelectionEdit: vi.fn(),
  45. cancelSelectionEdit: vi.fn(),
  46. togglePendingRow: vi.fn(),
  47. setAllPendingRowsSelected: vi.fn(),
  48. deselectProductTurn: vi.fn(),
  49. updateDockState: vi.fn(),
  50. setAccessMode: vi.fn(),
  51. syncAvailableTurns: vi.fn(),
  52. });
  53. // 只替换 hook 与 getState;派生 selector 保留真实实现,避免测试自证。
  54. const hook = (selector: (state: unknown) => unknown) => selector(fakeState());
  55. return {
  56. ...actual,
  57. useConversationShareSelectionStore: Object.assign(hook, { getState: fakeState }),
  58. };
  59. });
  60. vi.mock("@/v4/useConversationProjection.js", () => ({
  61. useConversationProjection: () => projectionState.current,
  62. }));
  63. vi.mock("@/v4/V4ConversationContext.js", () => ({
  64. useV4Conversation: () => ({
  65. attachmentPut: vi.fn(),
  66. layer: { acquire: vi.fn() },
  67. sendCommand: vi.fn(),
  68. }),
  69. }));
  70. vi.mock("@/store/StoreProvider.js", () => ({
  71. useZCodeStoreWithDefault: (_selector: unknown, fallback: unknown) => fallback,
  72. }));
  73. vi.mock("@/hooks/useSettingService.js", () => ({
  74. useSettings: () => ({
  75. error: null,
  76. loading: false,
  77. refresh: vi.fn(async () => {}),
  78. settings: { zcodeInteractionBehavior: "queue" },
  79. update: vi.fn(async () => {}),
  80. }),
  81. }));
  82. vi.mock("@/hooks/useServices.js", () => ({
  83. useComposerClientNamespace: () => "desktop",
  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. }: {
  231. allowWorkspaceFileRewind?: boolean;
  232. apiRetry?: ConversationSnapshot["control"]["apiRetry"];
  233. lastError?: ConversationSnapshot["control"]["lastError"];
  234. readOnly?: boolean;
  235. } = {}): string {
  236. const snapshot = makeSnapshot(lastError);
  237. snapshot.control.apiRetry = apiRetry;
  238. projectionState.current = {
  239. lastError: null,
  240. loadingOlder: false,
  241. optimisticCommands: [],
  242. snapshot,
  243. status: "live",
  244. subscriptionId: "sub-1",
  245. };
  246. return renderToStaticMarkup(
  247. createElement(
  248. ZCodeIntlProvider,
  249. { initialLocale: "zh-CN" },
  250. createElement(SessionPane, {
  251. allowWorkspaceFileRewind,
  252. paneId: "pane-1",
  253. readOnly,
  254. sessionId: "child-session",
  255. workspacePath: "/workspace",
  256. ...(readOnly ? {} : { onOpenWorkflowRun: () => {} }),
  257. }),
  258. ),
  259. );
  260. }
  261. describe("SessionPane read-only mode", () => {
  262. afterEach(() => {
  263. timelineState.apiRetry = null;
  264. timelineState.rowContext = null;
  265. });
  266. it("renders subagent child panes without composer or queue input affordances", () => {
  267. const html = renderReadOnlyPane();
  268. expect(html).toContain('data-testid="mock-timeline"');
  269. expect(html).not.toContain('data-testid="mock-composer"');
  270. expect(html).not.toContain('data-testid="mock-queue"');
  271. expect(timelineState.rowContext).toMatchObject({
  272. previewFileRewind: undefined,
  273. applyFileRewind: undefined,
  274. });
  275. });
  276. it("把 child snapshot 的 provider retry 传入只读时间线", () => {
  277. const apiRetry = {
  278. attempt: 2,
  279. maxAttempts: 6,
  280. nextRetryAt: 1_700_000_001_000,
  281. reasonCode: "fault.provider.requestFailed",
  282. };
  283. const html = renderReadOnlyPane({ apiRetry });
  284. expect(html).not.toContain('data-testid="mock-composer"');
  285. expect(timelineState.apiRetry).toEqual(apiRetry);
  286. });
  287. it("can expose workspace file rewind without making the child conversation editable", () => {
  288. const html = renderReadOnlyPane({ allowWorkspaceFileRewind: true });
  289. expect(html).not.toContain('data-testid="mock-composer"');
  290. expect(html).not.toContain('data-testid="mock-queue"');
  291. expect(timelineState.rowContext).toMatchObject({
  292. previewFileRewind: expect.any(Function),
  293. applyFileRewind: expect.any(Function),
  294. });
  295. });
  296. it("shows the current child projection error without adding an editable composer", () => {
  297. const html = renderReadOnlyPane({
  298. lastError: {
  299. at: 1_700_000_000_000,
  300. code: "fault.provider.requestFailed",
  301. message: "Provider connection failed",
  302. recoverable: true,
  303. source: "provider",
  304. },
  305. });
  306. expect(html).toContain('data-testid="v4-subagent-readonly-error"');
  307. expect(html).toContain("Provider connection failed");
  308. expect(html).not.toContain('data-testid="mock-composer"');
  309. });
  310. });
  311. /**
  312. * 这些用例守护 SessionPane 到 timeline 的分享模式接线。
  313. *
  314. * 分享浮窗必须保留 Composer 和正文滚动,勾选期仍禁用 message 工具条。
  315. * 断言必须落在 SessionPane 真正传给 ConversationTimeline 的 props 上。
  316. */
  317. describe("SessionPane 分享模式接线", () => {
  318. afterEach(() => {
  319. timelineState.apiRetry = null;
  320. timelineState.rowContext = null;
  321. timelineState.backgroundScrollLocked = false;
  322. timelineState.selectionActionsEnabled = null;
  323. timelineState.scrollToQueryActionRef = null;
  324. shareStoreState.draft = undefined;
  325. });
  326. const partialDraft = (
  327. overrides: Partial<ConversationShareSelectionDraft> = {},
  328. ): ConversationShareSelectionDraft => ({
  329. open: true,
  330. pendingExcludedRowIds: [],
  331. availableRowIds: [1],
  332. excludedRowIds: [],
  333. productTurnIdByRowId: { 1: "product-turn-1" },
  334. accessMode: "private",
  335. ...overrides,
  336. });
  337. const renderSharePane = (draft?: ConversationShareSelectionDraft): string => {
  338. shareStoreState.draft = draft;
  339. projectionState.current = {
  340. lastError: null,
  341. loadingOlder: false,
  342. optimisticCommands: [],
  343. snapshot: makeSnapshot(null),
  344. status: "live",
  345. subscriptionId: "sub-1",
  346. };
  347. return renderToStaticMarkup(
  348. createElement(
  349. ZCodeIntlProvider,
  350. { initialLocale: "zh-CN" },
  351. createElement(SessionPane, {
  352. paneId: "pane-1",
  353. readOnly: false,
  354. sessionId: "child-session",
  355. workspacePath: "/workspace",
  356. }),
  357. ),
  358. );
  359. };
  360. it("选择面板展开和收起时都保留正文滚动", () => {
  361. renderSharePane(partialDraft());
  362. expect(timelineState.backgroundScrollLocked).toBe(false);
  363. renderSharePane(partialDraft({ pendingExcludedRowIds: null }));
  364. expect(timelineState.backgroundScrollLocked).toBe(false);
  365. });
  366. it("选择面板展开时向 Timeline 传递正文定位 action ref", () => {
  367. renderSharePane(partialDraft());
  368. expect(timelineState.scrollToQueryActionRef).not.toBeNull();
  369. });
  370. it("分享选择确认 handler 接线到当前 session 的 confirmShareSelection", () => {
  371. const nextHandlerStart = sessionPaneSource.indexOf(
  372. "const handleConfirmShareSelection = useCallback",
  373. );
  374. const nextHandlerEnd = sessionPaneSource.indexOf(
  375. "const handleDismissShareError = useCallback",
  376. nextHandlerStart,
  377. );
  378. expect(nextHandlerStart).toBeGreaterThanOrEqual(0);
  379. expect(nextHandlerEnd).toBeGreaterThan(nextHandlerStart);
  380. const nextHandler = sessionPaneSource.slice(nextHandlerStart, nextHandlerEnd);
  381. expect(nextHandler).toContain("confirmShareSelection(sessionId)");
  382. });
  383. it("不在分享模式时不锁定背景滚动", () => {
  384. renderSharePane(undefined);
  385. expect(timelineState.backgroundScrollLocked).toBe(false);
  386. });
  387. it("局部勾选期间禁用全局 message 工具条,退出分享后恢复", () => {
  388. renderSharePane(partialDraft());
  389. expect(timelineState.selectionActionsEnabled).toBe(false);
  390. renderSharePane(undefined);
  391. expect(timelineState.selectionActionsEnabled).toBe(true);
  392. });
  393. it("分享浮窗保持 chat 输入区,不再替换 Composer", () => {
  394. expect(renderSharePane(undefined)).toContain('data-conversation-bottom-dock-mode="chat"');
  395. const html = renderSharePane(partialDraft());
  396. expect(html).toContain('data-conversation-bottom-dock-mode="chat"');
  397. expect(html).toContain('data-testid="mock-composer"');
  398. expect(html).not.toContain('data-conversation-bottom-dock-mode="confirmation"');
  399. });
  400. });