v4AssistantPreviewCards.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. import { createElement, type ReactNode } from "react";
  2. import { renderToStaticMarkup } from "react-dom/server";
  3. import { describe, expect, it, vi } from "vitest";
  4. import type {
  5. AssistantTextRow,
  6. ConversationSnapshot,
  7. SubagentRow,
  8. ToolCallRow,
  9. } from "@zcode/shared/zcode-protocol-v4";
  10. import { DEFAULT_CODE_PREVIEW_SETTINGS } from "@/lib/codePreviewSettings.js";
  11. import type { AssistantPreviewCard } from "@/lib/assistantPreviewCards.js";
  12. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  13. import { buildAssistantPreviewCardsForAssistantTextRow } from "@/v4/assistantPreviewCards.js";
  14. import { ConversationTurnGroup } from "@/v4/ConversationTurnGroup.js";
  15. import type { ConversationRowRenderContext } from "@/v4/conversationRowContext.js";
  16. import {
  17. buildConversationTurnRenderUnits,
  18. type ConversationTurnRenderUnit,
  19. } from "@/v4/conversationTurnRenderUnits.js";
  20. import { SessionPane } from "@/v4/SessionPane.js";
  21. import { AssistantCodeCommentFeatureProvider } from "@/AssistantCodeCommentFeatureProvider.js";
  22. import type { AssistantCodeCommentCard } from "@/lib/assistantCodeComment.js";
  23. const projectionState = vi.hoisted(() => ({
  24. current: null as {
  25. status: "live";
  26. snapshot: ConversationSnapshot;
  27. subscriptionId: string;
  28. lastError: string | null;
  29. optimisticCommands: readonly [];
  30. loadingOlder: boolean;
  31. } | null,
  32. }));
  33. const timelineCapture = vi.hoisted(() => ({
  34. props: [] as Array<Record<string, unknown>>,
  35. }));
  36. const toolCallBlockCapture = vi.hoisted(() => ({
  37. props: [] as Array<Record<string, unknown>>,
  38. }));
  39. vi.mock("@/AssistantPreviewCards.js", async () => {
  40. const React = await import("react");
  41. return {
  42. AssistantPreviewCards: ({
  43. cards,
  44. onOpenBrowserUrl,
  45. onOpenCodeViewer,
  46. onOpenFileLink,
  47. }: {
  48. cards: AssistantPreviewCard[];
  49. onOpenBrowserUrl?: (url: string) => void;
  50. onOpenCodeViewer?: (source: unknown) => void;
  51. onOpenFileLink?: (target: unknown) => void;
  52. }) =>
  53. React.createElement("div", {
  54. "data-testid": "mock-assistant-preview-cards",
  55. "data-card-ids": cards.map((card) => card.id).join("|"),
  56. "data-open-browser": String(Boolean(onOpenBrowserUrl)),
  57. "data-open-code": String(Boolean(onOpenCodeViewer)),
  58. "data-open-file": String(Boolean(onOpenFileLink)),
  59. }),
  60. };
  61. });
  62. vi.mock("@/AssistantCodeCommentCards.js", async () => {
  63. const React = await import("react");
  64. return {
  65. AssistantCodeCommentCards: ({
  66. cards,
  67. onOpenCodeViewer,
  68. }: {
  69. cards: AssistantCodeCommentCard[];
  70. onOpenCodeViewer?: (target: unknown) => void;
  71. }) =>
  72. React.createElement("div", {
  73. "data-testid": "mock-assistant-code-comment-cards",
  74. "data-card-titles": cards.map((card) => card.title).join("|"),
  75. "data-open-review": String(Boolean(onOpenCodeViewer)),
  76. }),
  77. };
  78. });
  79. vi.mock("@/components/ai-elements/message.js", async () => {
  80. const React = await import("react");
  81. return {
  82. MessageAction: ({ children, ...props }: { children?: ReactNode }) =>
  83. React.createElement("button", props, children),
  84. MessageActions: ({ children, ...props }: { children?: ReactNode }) =>
  85. React.createElement("div", props, children),
  86. MessageResponse: ({ children }: { children?: ReactNode }) =>
  87. React.createElement("div", null, children),
  88. };
  89. });
  90. vi.mock("@/components/ai-elements/reasoning.js", async () => {
  91. const React = await import("react");
  92. const Passthrough = ({ children }: { children?: ReactNode }) =>
  93. React.createElement("div", null, children);
  94. return {
  95. Reasoning: Passthrough,
  96. ReasoningContent: Passthrough,
  97. ReasoningTrigger: Passthrough,
  98. };
  99. });
  100. vi.mock("@/components/ai-elements/attachments.js", async () => {
  101. const React = await import("react");
  102. const Passthrough = ({ children, ...props }: { children?: ReactNode }) =>
  103. React.createElement("div", props, children);
  104. const Span = (props: Record<string, unknown>) => React.createElement("span", props);
  105. return {
  106. Attachment: Passthrough,
  107. AttachmentInfo: Span,
  108. AttachmentPreview: Span,
  109. Attachments: Passthrough,
  110. };
  111. });
  112. vi.mock("@/ToolCallBlocks.js", async () => {
  113. const React = await import("react");
  114. return {
  115. ToolCallBlock: (props: Record<string, unknown>) => {
  116. toolCallBlockCapture.props.push(props);
  117. return React.createElement("div", { "data-testid": "mock-tool-call" });
  118. },
  119. };
  120. });
  121. vi.mock("@/v4/useConversationProjection.js", () => ({
  122. useConversationProjection: () => projectionState.current,
  123. }));
  124. vi.mock("@/v4/V4ConversationContext.js", () => ({
  125. useV4Conversation: () => ({
  126. attachmentPut: vi.fn(),
  127. layer: { acquire: vi.fn() },
  128. sendCommand: vi.fn(),
  129. }),
  130. }));
  131. vi.mock("@/store/StoreProvider.js", () => ({
  132. useZCodeStoreWithDefault: (_selector: unknown, fallback: unknown) => fallback,
  133. }));
  134. vi.mock("@/hooks/useSettingService.js", () => ({
  135. useSettings: () => ({
  136. error: null,
  137. loading: false,
  138. refresh: vi.fn(async () => {}),
  139. settings: { zcodeInteractionBehavior: "queue" },
  140. update: vi.fn(async () => {}),
  141. }),
  142. }));
  143. vi.mock("@/hooks/useServices.js", () => ({
  144. // Bug 根因:Highspeed 历史消息改用可选服务以支持无 Provider 的只读渲染;
  145. // Vitest 的整模块 mock 未同步新导出,导致组件进入业务断言前就直接失败。
  146. useOptionalServices: () => null,
  147. useServices: () => ({
  148. zcodeSessionService: {
  149. updateProviderRegistry: vi.fn(),
  150. },
  151. zcodeTaskService: {
  152. restartWorkspaceProcess: vi.fn(),
  153. },
  154. }),
  155. }));
  156. vi.mock("@/v4/composer/useDraftConfigControl.js", () => ({
  157. buildDraftCreateConfigPayload: () => ({}),
  158. useDraftConfigControl: () => ({
  159. modelSelectionRead: { state: { status: "loading" }, reload: vi.fn() },
  160. captureAcceptedModelSelection: () => vi.fn(),
  161. draftConfigRef: { current: {} },
  162. handleDraftSelectModel: vi.fn(),
  163. handleDraftSelectThought: vi.fn(),
  164. handleDraftSwitchMode: vi.fn(),
  165. resolveInitialDraftConfig: vi.fn(() => ({})),
  166. }),
  167. }));
  168. vi.mock("@/v4/composer/useDraftSessionPrewarm.js", () => ({
  169. useDraftSessionPrewarm: () => ({
  170. binding: null,
  171. }),
  172. }));
  173. vi.mock("@/v4/ConversationTimeline.js", async () => {
  174. const React = await import("react");
  175. return {
  176. ConversationTimeline: (props: Record<string, unknown>) => {
  177. timelineCapture.props.push(props);
  178. return React.createElement("div", { "data-testid": "mock-timeline" });
  179. },
  180. };
  181. });
  182. vi.mock("@/v4/ConversationComposer.js", async () => {
  183. const React = await import("react");
  184. return {
  185. ConversationComposer: () => React.createElement("div", { "data-testid": "mock-composer" }),
  186. };
  187. });
  188. vi.mock("@/v4/ConversationHeader.js", async () => {
  189. const React = await import("react");
  190. return {
  191. ConversationHeader: () => React.createElement("div", { "data-testid": "mock-header" }),
  192. };
  193. });
  194. vi.mock("@/v4/ConversationStatusPanel.js", async () => {
  195. const React = await import("react");
  196. return {
  197. ConversationStatusPanel: () => React.createElement("div", { "data-testid": "mock-status" }),
  198. };
  199. });
  200. vi.mock("@/v4/ConversationQueuePanel.js", async () => {
  201. const React = await import("react");
  202. return {
  203. ConversationQueuePanel: () => React.createElement("div", { "data-testid": "mock-queue" }),
  204. };
  205. });
  206. vi.mock("@/v4/V4InteractionDialogs.js", async () => {
  207. const React = await import("react");
  208. return {
  209. V4InteractionDialogs: () => React.createElement("div", { "data-testid": "mock-interactions" }),
  210. };
  211. });
  212. vi.mock("@/request-security-edition/V4ProviderRuntimeHeadersController.js", async () => {
  213. const React = await import("react");
  214. return {
  215. V4ProviderRuntimeHeadersController: () =>
  216. React.createElement("div", { "data-testid": "mock-runtime-headers" }),
  217. };
  218. });
  219. vi.mock("@/v4/ConversationDraftEmptyState.js", async () => {
  220. const React = await import("react");
  221. return {
  222. ConversationDraftEmptyState: () =>
  223. React.createElement("div", { "data-testid": "mock-draft-empty" }),
  224. };
  225. });
  226. const rowContext: ConversationRowRenderContext = {
  227. workspacePath: "/workspace",
  228. theme: "system",
  229. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  230. };
  231. function assistantText(
  232. rowId: number,
  233. text: string,
  234. state: AssistantTextRow["state"] = "complete",
  235. ): AssistantTextRow {
  236. return {
  237. rowId,
  238. turnId: "turn-1",
  239. createdAt: 1_700_000_000_000 + rowId,
  240. createdAtSeq: rowId,
  241. kind: "assistantText",
  242. state,
  243. text,
  244. };
  245. }
  246. function buildForRow(
  247. row: AssistantTextRow,
  248. rows: readonly AssistantTextRow[],
  249. ): AssistantPreviewCard[] {
  250. return buildAssistantPreviewCardsForAssistantTextRow({
  251. row,
  252. assistantTextRows: rows,
  253. latestAssistantTextRow: rows.at(-1),
  254. workspacePath: "/workspace",
  255. changedFilePaths: ["/workspace/README.md"],
  256. });
  257. }
  258. function baseUnit(assistantTextRows: readonly AssistantTextRow[]): ConversationTurnRenderUnit {
  259. const latestAssistantTextRow = assistantTextRows.at(-1);
  260. return {
  261. key: "turn-1:1",
  262. turnId: "turn-1",
  263. visibleUserInputs: [],
  264. assistantWorkRows: [...assistantTextRows],
  265. assistantHistoryRows: [],
  266. assistantFollowingRows: [],
  267. assistantTailRows: [],
  268. browserTurnEndRows: [],
  269. hookInvocations: [],
  270. assistantTextRows,
  271. leadingBoundaryRows: [],
  272. ...(latestAssistantTextRow ? { latestAssistantTextRow } : {}),
  273. flowItems: latestAssistantTextRow
  274. ? [{ kind: "assistantText", row: latestAssistantTextRow, latest: true }]
  275. : [],
  276. renderRows: [...assistantTextRows],
  277. isLastTurn: true,
  278. isRunning: false,
  279. assistantHistoryDefaultOpen: false,
  280. timelineOnly: false,
  281. };
  282. }
  283. function makeSnapshot(): ConversationSnapshot {
  284. return {
  285. availability: {
  286. fork: { allowed: true },
  287. compact: { allowed: true },
  288. queueEdit: { allowed: true },
  289. pauseGoal: { allowed: false, reasonCode: "noGoalToPause" },
  290. resumeGoal: { allowed: false, reasonCode: "noGoalToResume" },
  291. sendQueuedNow: { allowed: true },
  292. setFollowupMode: { allowed: true },
  293. switchModelConfig: { allowed: true },
  294. },
  295. backgroundWorks: [],
  296. config: { followupMode: "queue", model: "", provider: "", thought: "" },
  297. control: {
  298. activeWorks: [],
  299. apiRetry: null,
  300. canStop: false,
  301. lastError: null,
  302. phase: "completedSuccess",
  303. sessionEnded: true,
  304. stopState: "idle",
  305. stopTargetKind: "unknown",
  306. },
  307. goal: null,
  308. inputRouting: { mode: "startNow" },
  309. logEpoch: "epoch-1",
  310. meta: { title: "Session", titleSource: "generated" },
  311. pendingCommands: [],
  312. pendingInteractions: [],
  313. plan: null,
  314. protocolVersion: 1,
  315. queue: { autoDrain: true, items: [] },
  316. revision: 1,
  317. rows: { firstRowId: null, totalCount: 0, window: [] },
  318. seq: 1,
  319. sessionId: "session-1",
  320. usage: {
  321. contextWindow: null,
  322. cumulative: {
  323. cacheReadTokens: 0,
  324. cacheWriteTokens: 0,
  325. inputTokens: 0,
  326. outputTokens: 0,
  327. },
  328. },
  329. };
  330. }
  331. function renderTurn(unit: ConversationTurnRenderUnit): string {
  332. return renderTurnWithContext(unit, rowContext);
  333. }
  334. function renderTurnWithContext(
  335. unit: ConversationTurnRenderUnit,
  336. context: ConversationRowRenderContext,
  337. ): string {
  338. return renderToStaticMarkup(
  339. createElement(
  340. ZCodeIntlProvider,
  341. { initialLocale: "zh-CN" },
  342. createElement(ConversationTurnGroup, {
  343. unit,
  344. context,
  345. }),
  346. ),
  347. );
  348. }
  349. function renderTurnWithCodeComments(
  350. unit: ConversationTurnRenderUnit,
  351. context: ConversationRowRenderContext = rowContext,
  352. ): string {
  353. return renderToStaticMarkup(
  354. createElement(
  355. ZCodeIntlProvider,
  356. { initialLocale: "zh-CN" },
  357. createElement(
  358. AssistantCodeCommentFeatureProvider,
  359. { enabled: true },
  360. createElement(ConversationTurnGroup, { unit, context }),
  361. ),
  362. ),
  363. );
  364. }
  365. function toolCallRow(rowId: number, overrides: Partial<ToolCallRow> = {}): ToolCallRow {
  366. return {
  367. rowId,
  368. turnId: "turn-1",
  369. createdAt: 1_700_000_000_000 + rowId,
  370. createdAtSeq: rowId,
  371. kind: "toolCall",
  372. toolCallId: `call-${rowId}`,
  373. toolName: "Bash",
  374. status: "success",
  375. inputText: '{"command":"node build.js"}',
  376. input: { command: "node build.js" },
  377. output: { text: "ok" },
  378. ...overrides,
  379. };
  380. }
  381. function subagentRow(rowId: number, overrides: Partial<SubagentRow> = {}): SubagentRow {
  382. return {
  383. rowId,
  384. turnId: "turn-1",
  385. createdAt: 1_700_000_000_000 + rowId,
  386. createdAtSeq: rowId,
  387. kind: "subagent",
  388. subagentType: "Explore",
  389. status: "success",
  390. summaryText: "done",
  391. childSessionId: `child-${rowId}`,
  392. ...overrides,
  393. };
  394. }
  395. function unitWithWorkRows(
  396. rows: ConversationTurnRenderUnit["assistantWorkRows"],
  397. ): ConversationTurnRenderUnit {
  398. return {
  399. key: "turn-1:tools",
  400. turnId: "turn-1",
  401. visibleUserInputs: [],
  402. assistantWorkRows: rows,
  403. assistantHistoryRows: [],
  404. assistantFollowingRows: [],
  405. assistantTailRows: [],
  406. browserTurnEndRows: [],
  407. // Bugfix:Hook footer 将该字段升级为必填后,手写 turn fixture 也必须显式提供空集合,
  408. // 否则 SSR 会在计算 action row 时访问 undefined.some。
  409. hookInvocations: [],
  410. assistantTextRows: [],
  411. leadingBoundaryRows: [],
  412. flowItems: rows.length > 0 ? [{ kind: "assistantWork", rows }] : [],
  413. renderRows: rows,
  414. isLastTurn: true,
  415. isRunning: false,
  416. assistantHistoryDefaultOpen: false,
  417. timelineOnly: false,
  418. };
  419. }
  420. describe("v4 assistant preview cards helper", () => {
  421. it("builds a website card for a completed latest assistant row", () => {
  422. const row = assistantText(1, "Preview http://localhost:5173.");
  423. expect(buildForRow(row, [row])).toMatchObject([
  424. {
  425. type: "website",
  426. url: "http://localhost:5173",
  427. },
  428. ]);
  429. });
  430. it("builds interrupted turn cards from early assistant text but only for the latest row", () => {
  431. const early = assistantText(1, "Preview http://localhost:5173.");
  432. const latest = assistantText(2, "已停止。", "interrupted");
  433. expect(buildForRow(early, [early, latest])).toEqual([]);
  434. expect(buildForRow(latest, [early, latest])).toMatchObject([
  435. {
  436. type: "website",
  437. url: "http://localhost:5173",
  438. },
  439. ]);
  440. });
  441. it("does not build cards for streaming, failed, or non-latest rows", () => {
  442. const streaming = assistantText(1, "Preview http://localhost:5173.", "streaming");
  443. const failed = assistantText(2, "Preview http://localhost:5173.", "failed");
  444. const latest = assistantText(3, "done");
  445. expect(buildForRow(streaming, [streaming])).toEqual([]);
  446. expect(buildForRow(failed, [failed])).toEqual([]);
  447. expect(buildForRow(streaming, [streaming, latest])).toEqual([]);
  448. });
  449. it("merges multiple assistant text segments before deduping candidates", () => {
  450. const first = assistantText(1, "Preview http://localhost:5173 and README.md.");
  451. const latest = assistantText(2, "Again: http://localhost:5173 and ./README.md.");
  452. expect(buildForRow(latest, [first, latest]).map((card) => card.id)).toEqual([
  453. "markdown:/workspace/README.md",
  454. "website:http://localhost:5173",
  455. ]);
  456. });
  457. });
  458. describe("ConversationTurnGroup assistant preview cards", () => {
  459. it("renders preview cards once below the latest assistant text row", () => {
  460. const early = assistantText(1, "Preview http://localhost:5173.");
  461. const latest = assistantText(2, "Final answer.");
  462. const html = renderTurn(baseUnit([early, latest]));
  463. expect(html.match(/mock-assistant-preview-cards/g)).toHaveLength(1);
  464. expect(html).toContain('data-card-ids="website:http://localhost:5173"');
  465. expect(html.indexOf("Final answer.")).toBeLessThan(
  466. html.indexOf('data-testid="mock-assistant-preview-cards"'),
  467. );
  468. });
  469. it("passes file, code, and browser open handlers to preview cards", () => {
  470. const onOpenBrowserUrl = vi.fn();
  471. const onOpenCodeViewer = vi.fn();
  472. const onOpenFileLink = vi.fn();
  473. const row = assistantText(1, "Preview http://localhost:5173 and README.md.");
  474. const html = renderTurnWithContext(baseUnit([row]), {
  475. ...rowContext,
  476. onOpenBrowserUrl,
  477. onOpenCodeViewer,
  478. onOpenFileLink,
  479. });
  480. expect(html).toContain('data-open-browser="true"');
  481. expect(html).toContain('data-open-code="true"');
  482. expect(html).toContain('data-open-file="true"');
  483. });
  484. });
  485. describe("ConversationTurnGroup assistant code-comment cards", () => {
  486. it("running turn 的 assistant text 即使落在 history renderer 也隐藏 code-comment 协议", () => {
  487. const directive = '::code-comment{title="Review" body="Action" file="src/main.ts"}';
  488. const [unit] = buildConversationTurnRenderUnits([
  489. {
  490. rowId: 1,
  491. turnId: "turn-1",
  492. createdAt: 1_700_000_000_001,
  493. createdAtSeq: 1,
  494. kind: "turnHeader",
  495. origin: "userInput",
  496. state: "running",
  497. startedAt: 1_700_000_000_001,
  498. },
  499. {
  500. rowId: 2,
  501. turnId: "turn-1",
  502. createdAt: 1_700_000_000_002,
  503. createdAtSeq: 2,
  504. kind: "userInput",
  505. text: "review",
  506. origin: "realUser",
  507. },
  508. assistantText(3, directive, "streaming"),
  509. ]);
  510. expect(unit?.isRunning).toBe(true);
  511. expect(unit?.latestAssistantTextRow).toBeUndefined();
  512. expect(unit?.assistantHistoryRows.map((row) => row.rowId)).toEqual([3]);
  513. const html = renderTurnWithCodeComments(unit!);
  514. expect(html).not.toContain("::code-comment");
  515. expect(html).not.toContain("mock-assistant-code-comment-cards");
  516. });
  517. it("灰度关闭时保持既有正文原样且不展示卡片", () => {
  518. const directive = '::code-comment{title="Review" body="Action" file="src/main.ts"}';
  519. const html = renderTurn(baseUnit([assistantText(1, directive)]));
  520. expect(html).toContain("::code-comment");
  521. expect(html).not.toContain("mock-assistant-code-comment-cards");
  522. });
  523. it("灰度开启后隐藏有效指令,只在最新完成态正文下展示一次卡片", () => {
  524. const directive =
  525. '::code-comment{title="[P1] Null risk" body="Guard user" file="src/main.ts" start=8 priority=1}';
  526. const early = assistantText(1, "Checking.");
  527. const latest = assistantText(2, `Done.\n${directive}`);
  528. const html = renderTurnWithCodeComments(baseUnit([early, latest]));
  529. expect(html).toContain("Done.");
  530. expect(html).not.toContain("::code-comment");
  531. expect(html.match(/mock-assistant-code-comment-cards/g)).toHaveLength(1);
  532. expect(html).toContain('data-card-titles="[P1] Null risk"');
  533. });
  534. it("streaming 时隐藏协议尾部但不生成卡片,终态才生成卡片", () => {
  535. const onOpenCodeViewer = vi.fn();
  536. const completedDirective = '::code-comment{title="Ready" body="Open now" file="src/ready.ts"}';
  537. const streaming = assistantText(
  538. 1,
  539. `正文\n${completedDirective}\n::code-comment{title="Partial" body="Still streaming`,
  540. "streaming",
  541. );
  542. const unit = { ...baseUnit([streaming]), isRunning: true };
  543. const html = renderTurnWithCodeComments(unit, {
  544. ...rowContext,
  545. onOpenCodeViewer,
  546. });
  547. expect(html).toContain("正文");
  548. expect(html).not.toContain("::code-comment");
  549. expect(html).not.toContain("mock-assistant-code-comment-cards");
  550. expect(html).not.toContain("Still streaming");
  551. const complete = assistantText(
  552. 2,
  553. '::code-comment{title="Review" body="Action" file="src/main.ts"}',
  554. );
  555. const completeHtml = renderTurnWithCodeComments(baseUnit([complete]), {
  556. ...rowContext,
  557. onOpenCodeViewer,
  558. });
  559. expect(completeHtml).toContain('data-open-review="true"');
  560. });
  561. it("failed turn 不展示卡片并恢复整轮有效 directive 原文,避免早段评论静默丢失", () => {
  562. const earlyDirective =
  563. '::code-comment{title="Early review" body="Early action" file="src/early.ts"}';
  564. const failedDirective =
  565. '::code-comment{title="Failed review" body="Failed action" file="src/failed.ts"}';
  566. const early = assistantText(1, earlyDirective);
  567. const failed = assistantText(2, failedDirective, "failed");
  568. const html = renderTurnWithCodeComments({
  569. ...baseUnit([early, failed]),
  570. flowItems: [
  571. { kind: "assistantText", row: early, latest: false },
  572. { kind: "assistantText", row: failed, latest: true },
  573. ],
  574. });
  575. expect(html.match(/::code-comment/g)).toHaveLength(2);
  576. expect(html).toContain("Early review");
  577. expect(html).toContain("Failed review");
  578. expect(html).not.toContain("mock-assistant-code-comment-cards");
  579. });
  580. it("interrupted 轮尾仍投影已完整到达的卡片", () => {
  581. const interrupted = assistantText(
  582. 1,
  583. 'Stopped.\n::code-comment{title="Review" body="Action" file="src/main.ts"}',
  584. "interrupted",
  585. );
  586. const html = renderTurnWithCodeComments(baseUnit([interrupted]));
  587. expect(html).toContain("Stopped.");
  588. expect(html).not.toContain("::code-comment");
  589. expect(html).toContain("mock-assistant-code-comment-cards");
  590. });
  591. });
  592. describe("ConversationTurnGroup tool handler wiring", () => {
  593. it("passes file, code viewer, and browser handlers to normal, agent, and explore tool rows", () => {
  594. const onOpenBrowserUrl = vi.fn();
  595. const onOpenCodeViewer = vi.fn();
  596. const onOpenFileLink = vi.fn();
  597. toolCallBlockCapture.props = [];
  598. renderTurnWithContext(
  599. unitWithWorkRows([
  600. toolCallRow(1),
  601. toolCallRow(2, {
  602. toolName: "Agent",
  603. inputText: '{"prompt":"inspect"}',
  604. input: { prompt: "inspect" },
  605. }),
  606. subagentRow(3),
  607. toolCallRow(4, {
  608. inputText: '{"command":"ls -la"}',
  609. input: { command: "ls -la" },
  610. }),
  611. ]),
  612. {
  613. ...rowContext,
  614. onOpenBrowserUrl,
  615. onOpenCodeViewer,
  616. onOpenFileLink,
  617. },
  618. );
  619. expect(toolCallBlockCapture.props).toHaveLength(3);
  620. for (const props of toolCallBlockCapture.props) {
  621. expect(props.onOpenBrowserUrl).toBe(onOpenBrowserUrl);
  622. expect(props.onOpenCodeViewer).toBe(onOpenCodeViewer);
  623. expect(props.onOpenFileLink).toBe(onOpenFileLink);
  624. }
  625. });
  626. });
  627. describe("SessionPane assistant preview card handler wiring", () => {
  628. it("passes file, browser, and code viewer open handlers through rowContext", () => {
  629. const onOpenBrowserUrl = vi.fn();
  630. const onOpenCodeViewer = vi.fn();
  631. const onOpenFileLink = vi.fn();
  632. timelineCapture.props = [];
  633. projectionState.current = {
  634. lastError: null,
  635. loadingOlder: false,
  636. optimisticCommands: [],
  637. snapshot: makeSnapshot(),
  638. status: "live",
  639. subscriptionId: "sub-1",
  640. };
  641. renderToStaticMarkup(
  642. createElement(
  643. ZCodeIntlProvider,
  644. { initialLocale: "zh-CN" },
  645. createElement(SessionPane, {
  646. paneId: "workspace-main",
  647. sessionId: "session-1",
  648. workspacePath: "/workspace",
  649. onOpenBrowserUrl,
  650. onOpenCodeViewer,
  651. onOpenFileLink,
  652. }),
  653. ),
  654. );
  655. expect(timelineCapture.props).toHaveLength(1);
  656. expect(timelineCapture.props[0]?.rowContext).toMatchObject({
  657. onOpenBrowserUrl,
  658. onOpenCodeViewer,
  659. onOpenFileLink,
  660. });
  661. });
  662. });