v4ConversationComposerErrorBanner.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. import { createElement, type ComponentType, type ReactNode } from "react";
  2. import { renderToStaticMarkup } from "react-dom/server";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. import type { ConversationSnapshot } from "@zcode/shared/zcode-protocol-v4";
  5. import { ConversationComposer } from "@/v4/ConversationComposer.js";
  6. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  7. import { RemoteConversationAvailability } from "@/v4/RemoteConversationAvailability.js";
  8. const captured = vi.hoisted(() => ({
  9. chatErrorBannerProps: null as Record<string, unknown> | null,
  10. chatPromptEditorProps: null as Record<string, unknown> | null,
  11. modelControlsProps: null as Record<string, unknown> | null,
  12. }));
  13. vi.mock("@/ChatErrorBanner.js", async () => {
  14. const React = await import("react");
  15. return {
  16. ChatErrorBanner: (props: {
  17. error: { message: string };
  18. onOpenModelSettings?: () => void;
  19. onOpenUpgrade?: () => void;
  20. }) => {
  21. captured.chatErrorBannerProps = props;
  22. return React.createElement(
  23. "section",
  24. { "data-testid": "mock-chat-error-banner" },
  25. props.error.message,
  26. );
  27. },
  28. shouldSuppressChatErrorBanner: () => false,
  29. };
  30. });
  31. vi.mock("@/ControlHintTooltip.js", async () => {
  32. const React = await import("react");
  33. return {
  34. ControlHintTooltip: ({ children }: { children: ReactNode }) =>
  35. React.createElement(React.Fragment, null, children),
  36. };
  37. });
  38. vi.mock("@/prompt-editor/ChatPromptEditor.js", async () => {
  39. const React = await import("react");
  40. return {
  41. ChatPromptEditor: (
  42. props: {
  43. inputLeadingContent?: ReactNode;
  44. leadingActions?: ReactNode;
  45. submitControl?: ReactNode;
  46. topContent?: ReactNode;
  47. } & Record<string, unknown>,
  48. ) => {
  49. captured.chatPromptEditorProps = props;
  50. return React.createElement(
  51. "form",
  52. { "data-testid": "mock-chat-prompt-editor" },
  53. props.topContent,
  54. props.inputLeadingContent,
  55. props.leadingActions,
  56. props.submitControl,
  57. );
  58. },
  59. };
  60. });
  61. vi.mock("@/v4/composer/useComposerAttachments.js", () => ({
  62. useComposerAttachments: () => ({
  63. attachments: [],
  64. attachmentError: null,
  65. adoptSentAttachments: vi.fn(async () => {}),
  66. hasAttachments: false,
  67. hasUnreadyAttachments: false,
  68. isDraggingOverComposer: false,
  69. attachmentInputRef: { current: null },
  70. openAttachmentPicker: vi.fn(),
  71. handleAttachmentInputChange: vi.fn(),
  72. handlePaste: vi.fn(),
  73. handleDragOverComposer: vi.fn(),
  74. handleDragLeaveComposer: vi.fn(),
  75. handleDropComposer: vi.fn(),
  76. handleWhiteboardMentionSelected: vi.fn(),
  77. removeAttachment: vi.fn(),
  78. retryAttachment: vi.fn(),
  79. clearAttachments: vi.fn(),
  80. prepareForSend: vi.fn(async () => []),
  81. setAttachmentError: vi.fn(),
  82. }),
  83. }));
  84. vi.mock("@/v4/composer/V4ComposerToolbar.js", async () => {
  85. const React = await import("react");
  86. const Stub = ({ label }: { label: string }) => React.createElement("span", null, label);
  87. return {
  88. V4ComposerModeSwitch: () => React.createElement(Stub, { label: "mode" }),
  89. V4ComposerModelControls: (props: Record<string, unknown>) => {
  90. captured.modelControlsProps = props;
  91. return React.createElement(Stub, { label: "model" });
  92. },
  93. };
  94. });
  95. const AnyConversationComposer = ConversationComposer as unknown as ComponentType<
  96. Record<string, unknown>
  97. >;
  98. function makeSnapshot(): ConversationSnapshot {
  99. return {
  100. protocolVersion: 1,
  101. sessionId: "session-1",
  102. logEpoch: "epoch-1",
  103. seq: 1,
  104. revision: 1,
  105. control: {
  106. phase: "completedSuccess",
  107. sessionEnded: true,
  108. canStop: false,
  109. stopState: "idle",
  110. stopTargetKind: "unknown",
  111. activeWorks: [],
  112. lastError: null,
  113. apiRetry: null,
  114. },
  115. availability: {
  116. fork: { allowed: true },
  117. compact: { allowed: true },
  118. switchModelConfig: { allowed: true },
  119. setFollowupMode: { allowed: true },
  120. queueEdit: { allowed: true },
  121. sendQueuedNow: { allowed: false, reasonCode: "sendQueuedNowRequiresRunning" },
  122. pauseGoal: { allowed: false, reasonCode: "noGoalToPause" },
  123. resumeGoal: { allowed: false, reasonCode: "noGoalToResume" },
  124. },
  125. inputRouting: { mode: "startNow" },
  126. meta: { title: "Session", titleSource: "generated" },
  127. config: { provider: "", model: "", thought: "", followupMode: "queue", mode: "build" },
  128. usage: {
  129. contextWindow: null,
  130. cumulative: {
  131. inputTokens: 0,
  132. outputTokens: 0,
  133. cacheReadTokens: 0,
  134. cacheWriteTokens: 0,
  135. },
  136. },
  137. queue: { items: [], autoDrain: true },
  138. pendingInteractions: [],
  139. pendingCommands: [],
  140. backgroundWorks: [],
  141. goal: null,
  142. plan: null,
  143. rows: { window: [], totalCount: 0, firstRowId: null },
  144. };
  145. }
  146. function renderComposerWithError(
  147. message: string,
  148. actions: {
  149. onOpenModelSettings?: () => void;
  150. onOpenModelUpgrade?: () => void;
  151. contextHeader?: ReactNode;
  152. } = {},
  153. ): string {
  154. return renderToStaticMarkup(
  155. createElement(
  156. ZCodeIntlProvider,
  157. { initialLocale: "zh-CN" },
  158. createElement(AnyConversationComposer, {
  159. snapshot: null,
  160. sessionId: "session-1",
  161. workspacePath: "/workspace",
  162. provider: undefined,
  163. onSendText: vi.fn(async () => {}),
  164. onStop: vi.fn(),
  165. onSelectModel: vi.fn(),
  166. onSelectThought: vi.fn(),
  167. onSwitchMode: vi.fn(),
  168. error: {
  169. code: "fault.provider.rateLimited",
  170. message,
  171. taskId: "session-1",
  172. },
  173. onDismissError: vi.fn(),
  174. contextHeader: actions.contextHeader,
  175. ...actions,
  176. }),
  177. ),
  178. );
  179. }
  180. function renderComposerWithSnapshot(
  181. snapshot: ConversationSnapshot | null = makeSnapshot(),
  182. overrides: Record<string, unknown> = {},
  183. remoteAvailable = true,
  184. ): string {
  185. return renderToStaticMarkup(
  186. createElement(
  187. ZCodeIntlProvider,
  188. { initialLocale: "zh-CN" },
  189. createElement(RemoteConversationAvailability, {
  190. available: remoteAvailable,
  191. children: createElement(AnyConversationComposer, {
  192. snapshot,
  193. sessionId: "session-1",
  194. workspacePath: "/workspace",
  195. provider: undefined,
  196. onSendText: vi.fn(async () => {}),
  197. onStop: vi.fn(),
  198. onSelectModel: vi.fn(),
  199. onSelectThought: vi.fn(),
  200. onSwitchMode: vi.fn(),
  201. ...overrides,
  202. }),
  203. }),
  204. ),
  205. );
  206. }
  207. function renderHighspeedComposer(overrides: Record<string, unknown> = {}): string {
  208. return renderToStaticMarkup(
  209. createElement(
  210. ZCodeIntlProvider,
  211. { initialLocale: "zh-CN" },
  212. createElement(AnyConversationComposer, {
  213. snapshot: makeSnapshot(),
  214. sessionId: "session-1",
  215. workspacePath: "/workspace",
  216. provider: undefined,
  217. highspeedCard: {
  218. cardId: "hsc-composer",
  219. taskId: "session-1",
  220. provider: "zai",
  221. model: "glm-5.2",
  222. issuedAt: 1_000,
  223. expiresAt: 60_000,
  224. },
  225. onSendText: vi.fn(async () => {}),
  226. onStop: vi.fn(),
  227. onSelectModel: vi.fn(),
  228. onSelectThought: vi.fn(),
  229. onSwitchMode: vi.fn(),
  230. ...overrides,
  231. }),
  232. ),
  233. );
  234. }
  235. function renderBlockedComposer(): string {
  236. return renderToStaticMarkup(
  237. createElement(
  238. ZCodeIntlProvider,
  239. { initialLocale: "zh-CN" },
  240. createElement(AnyConversationComposer, {
  241. snapshot: makeSnapshot(),
  242. sessionId: "session-1",
  243. workspacePath: "/workspace",
  244. provider: undefined,
  245. blockingRequestId: "perm-1",
  246. onSendText: vi.fn(async () => {}),
  247. onStop: vi.fn(),
  248. onSelectModel: vi.fn(),
  249. onSelectThought: vi.fn(),
  250. onSwitchMode: vi.fn(),
  251. }),
  252. ),
  253. );
  254. }
  255. afterEach(() => {
  256. captured.chatErrorBannerProps = null;
  257. captured.chatPromptEditorProps = null;
  258. captured.modelControlsProps = null;
  259. });
  260. describe("ConversationComposer error banner", () => {
  261. it("renders the session error banner above the prompt editor", () => {
  262. const html = renderComposerWithError("Provider rate limit exceeded.");
  263. expect(html).toContain("Provider rate limit exceeded.");
  264. expect(html.indexOf("mock-chat-error-banner")).toBeGreaterThanOrEqual(0);
  265. expect(html.indexOf("mock-chat-error-banner")).toBeLessThan(
  266. html.indexOf("mock-chat-prompt-editor"),
  267. );
  268. });
  269. it("renders the session error banner above the workspace context header", () => {
  270. const html = renderComposerWithError("No model", {
  271. contextHeader: createElement(
  272. "nav",
  273. { "data-testid": "mock-workspace-context-header" },
  274. "选择工作区",
  275. ),
  276. });
  277. expect(html.indexOf("mock-chat-error-banner")).toBeLessThan(
  278. html.indexOf("mock-workspace-context-header"),
  279. );
  280. expect(html.indexOf("mock-workspace-context-header")).toBeLessThan(
  281. html.indexOf("mock-chat-prompt-editor"),
  282. );
  283. });
  284. it("keeps the error banner outside the workspace and editor surface", () => {
  285. const html = renderComposerWithError("No model", {
  286. contextHeader: createElement(
  287. "nav",
  288. { "data-testid": "mock-workspace-context-header" },
  289. "选择工作区",
  290. ),
  291. });
  292. const bannerIndex = html.indexOf("mock-chat-error-banner");
  293. const inputSurfaceIndex = html.indexOf("chat-composer-input-surface");
  294. expect(bannerIndex).toBeGreaterThanOrEqual(0);
  295. expect(inputSurfaceIndex).toBeGreaterThan(bannerIndex);
  296. expect(html.indexOf("mock-workspace-context-header")).toBeGreaterThan(inputSurfaceIndex);
  297. expect(html.indexOf("mock-chat-prompt-editor")).toBeGreaterThan(inputSurfaceIndex);
  298. });
  299. it("forwards model recovery actions to the shared error banner", () => {
  300. const onOpenModelSettings = vi.fn();
  301. const onOpenModelUpgrade = vi.fn();
  302. renderComposerWithError("No model", {
  303. onOpenModelSettings,
  304. onOpenModelUpgrade,
  305. });
  306. expect(captured.chatErrorBannerProps?.onOpenModelSettings).toBe(onOpenModelSettings);
  307. expect(captured.chatErrorBannerProps?.onOpenUpgrade).toBe(onOpenModelUpgrade);
  308. });
  309. it("不再把 snapshot api retry 状态传入输入框工具条", () => {
  310. const snapshot = makeSnapshot();
  311. snapshot.control.apiRetry = {
  312. attempt: 1,
  313. maxAttempts: 11,
  314. nextRetryAt: 123,
  315. reasonCode: "fault.provider.rateLimited",
  316. };
  317. renderComposerWithSnapshot(snapshot);
  318. expect(captured.modelControlsProps).not.toHaveProperty("apiRetry");
  319. });
  320. it("keeps Enter and the submit control enabled by routing in guide mode", () => {
  321. const snapshot = makeSnapshot();
  322. snapshot.control = {
  323. ...snapshot.control,
  324. phase: "running",
  325. sessionEnded: false,
  326. canStop: true,
  327. };
  328. snapshot.inputRouting = { mode: "guide" };
  329. renderComposerWithSnapshot(snapshot);
  330. expect(captured.chatPromptEditorProps?.disabled).toBe(false);
  331. expect(captured.chatPromptEditorProps?.submitDisabled).toBe(false);
  332. });
  333. it("keeps modified submit available when idle and reverses delivery only while running", () => {
  334. renderComposerWithSnapshot();
  335. const onModifiedSubmit = captured.chatPromptEditorProps?.onModifiedSubmit;
  336. expect(onModifiedSubmit).toEqual(expect.any(Function));
  337. expect((onModifiedSubmit as (value: string) => boolean)("草稿")).toBe(false);
  338. const snapshot = makeSnapshot();
  339. snapshot.control = {
  340. ...snapshot.control,
  341. phase: "running",
  342. sessionEnded: false,
  343. canStop: true,
  344. };
  345. snapshot.config.followupMode = "queue";
  346. snapshot.inputRouting = { mode: "enqueue" };
  347. renderComposerWithSnapshot(snapshot);
  348. expect(captured.chatPromptEditorProps?.onModifiedSubmit).toEqual(expect.any(Function));
  349. });
  350. it("keeps modified submit wired for a desktop new-task draft", () => {
  351. renderComposerWithSnapshot(null, {
  352. draftMode: true,
  353. sessionId: null,
  354. });
  355. expect(captured.chatPromptEditorProps?.onModifiedSubmit).toEqual(expect.any(Function));
  356. });
  357. it("keeps the composer mounted but hidden while a blocking request is active", () => {
  358. const html = renderBlockedComposer();
  359. expect(html).toMatch(
  360. /<div data-testid="v4-composer"[^>]*aria-hidden="true"[^>]*style="display:none"/,
  361. );
  362. });
  363. });
  364. it("离线输入栏优先显示禁发送原因,不让不可用模型控件挤占窄窗空间", async () => {
  365. const { RemoteConversationAvailability } = await import("@/v4/RemoteConversationAvailability.js");
  366. captured.modelControlsProps = null;
  367. const html = renderToStaticMarkup(
  368. createElement(
  369. ZCodeIntlProvider,
  370. { initialLocale: "zh-CN" },
  371. createElement(
  372. RemoteConversationAvailability,
  373. { available: false },
  374. createElement(AnyConversationComposer, {
  375. workspacePath: "/workspace",
  376. sessionId: null,
  377. snapshot: null,
  378. provider: "glm",
  379. draftMode: "build",
  380. draftConfig: {},
  381. composerDraft: { text: "草稿", updatedAt: 1 },
  382. onSendText: vi.fn(),
  383. onStop: vi.fn(),
  384. onSelectModel: vi.fn(),
  385. onSelectThought: vi.fn(),
  386. onSwitchMode: vi.fn(),
  387. }),
  388. ),
  389. ),
  390. );
  391. expect(html).toContain("设备未连接,暂时无法发送");
  392. expect(captured.modelControlsProps).toBeNull();
  393. });
  394. describe("ConversationComposer Highspeed style", () => {
  395. it("激活卡传递到期时间并锁定模型", () => {
  396. vi.spyOn(Date, "now").mockReturnValue(1_000);
  397. const html = renderHighspeedComposer();
  398. expect(html).toContain('data-highspeed-composer="true"');
  399. expect(captured.modelControlsProps).toMatchObject({
  400. highspeedExpiresAt: 60_000,
  401. modelLocked: true,
  402. });
  403. });
  404. it("没有激活请求的卡(切回 Task、快照恢复)直接呈现稳定态,不重播激活动效", () => {
  405. vi.spyOn(Date, "now").mockReturnValue(1_000);
  406. const html = renderHighspeedComposer();
  407. expect(html).toContain('data-highspeed-entrance="restore"');
  408. expect(html).toContain('data-phase="stable"');
  409. expect(html).not.toContain("highspeed-diffusion-canvas");
  410. expect(html).toContain("highspeed-placeholder-presented");
  411. expect(captured.modelControlsProps).toMatchObject({
  412. highspeedPresented: true,
  413. highspeedEntranceAnimated: false,
  414. highspeedSweepActive: false,
  415. });
  416. });
  417. it("draw 新命中的激活请求从扩散起点播放,模型与倒计时等待交接后再展示", () => {
  418. vi.spyOn(Date, "now").mockReturnValue(1_000);
  419. const html = renderHighspeedComposer({ highspeedActivationCardId: "hsc-composer" });
  420. expect(html).toContain('data-highspeed-entrance="activation"');
  421. expect(html).toContain('data-phase="diffusing"');
  422. expect(html).not.toContain("highspeed-placeholder-presented");
  423. expect(captured.modelControlsProps).toMatchObject({
  424. highspeedPresented: false,
  425. highspeedEntranceAnimated: true,
  426. });
  427. });
  428. });
  429. describe("history-first initialization", () => {
  430. it.each([true, false])("respects the remote gate when available=%s", (remoteAvailable) => {
  431. // 合并时两道门禁不能互相覆盖:runtime 就绪也不能放行断开的远程项目。
  432. const html = renderComposerWithSnapshot(
  433. {
  434. ...makeSnapshot(),
  435. runtimeInitialization: { status: "ready", attemptId: "attempt-1" },
  436. },
  437. {},
  438. remoteAvailable,
  439. );
  440. expect(captured.chatPromptEditorProps?.disabled).toBe(!remoteAvailable);
  441. expect(html.includes('data-testid="remote-send-unavailable"')).toBe(!remoteAvailable);
  442. if (remoteAvailable) {
  443. expect(captured.modelControlsProps?.disabled).toBe(false);
  444. } else {
  445. expect(captured.modelControlsProps).toBeNull();
  446. }
  447. });
  448. it("keeps an initializing remote project blocked after the attachment becomes available", () => {
  449. const snapshot: ConversationSnapshot = {
  450. ...makeSnapshot(),
  451. runtimeInitialization: { status: "initializing", attemptId: "attempt-1" },
  452. };
  453. renderComposerWithSnapshot(snapshot, {}, false);
  454. expect(captured.chatPromptEditorProps?.disabled).toBe(true);
  455. expect(captured.modelControlsProps).toBeNull();
  456. renderComposerWithSnapshot(snapshot, {}, true);
  457. expect(captured.chatPromptEditorProps?.disabled).toBe(false);
  458. expect(captured.chatPromptEditorProps?.submitDisabled).toBe(true);
  459. expect(captured.modelControlsProps?.disabled).toBe(true);
  460. });
  461. it("keeps text editable without a preparation banner while disabling execution controls", () => {
  462. const snapshot = {
  463. ...makeSnapshot(),
  464. runtimeInitialization: { status: "initializing" as const, attemptId: "attempt-1" },
  465. };
  466. const html = renderComposerWithSnapshot(snapshot);
  467. expect(captured.chatPromptEditorProps?.disabled).toBe(false);
  468. expect(captured.chatPromptEditorProps?.submitDisabled).toBe(true);
  469. expect(captured.modelControlsProps?.disabled).toBe(true);
  470. expect(html).not.toContain("v4-session-initialization");
  471. });
  472. it("places retry above the editor without replacing history or editing state", () => {
  473. const snapshot = {
  474. ...makeSnapshot(),
  475. runtimeInitialization: {
  476. status: "failed" as const,
  477. attemptId: "attempt-1",
  478. reasonCode: "fault.subscribe.resumeFailed",
  479. message: "resume failed",
  480. },
  481. };
  482. const html = renderComposerWithSnapshot(snapshot, { onRetryInitialization: vi.fn() });
  483. expect(html).toContain("v4-session-initialization-retry");
  484. expect(html.indexOf("v4-session-initialization")).toBeLessThan(
  485. html.indexOf("mock-chat-prompt-editor"),
  486. );
  487. expect(captured.chatPromptEditorProps?.disabled).toBe(false);
  488. expect(captured.chatPromptEditorProps?.submitDisabled).toBe(true);
  489. });
  490. });