v4ConversationComposerPromptHistory.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. import { act, createElement, type ReactNode } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. import {
  5. getPromptHistoryStorageKey,
  6. persistPromptHistoryEntries,
  7. readPromptHistoryEntries,
  8. } from "@/lib/promptHistoryStorage.js";
  9. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  10. import {
  11. ConversationComposer,
  12. type ConversationComposerSendResult,
  13. } from "@/v4/ConversationComposer.js";
  14. import {
  15. persistV4ComposerDraft,
  16. readV4ComposerDraft,
  17. V4_DRAFT_SCOPE_ROOT,
  18. type V4ComposerDraft,
  19. } from "@/v4/composer/composerDraftStore.js";
  20. import { getComposerDraftRevision } from "@/v4/composer/composerDraftRevision.js";
  21. import type { ComposerSubmissionConfig } from "@/v4/composer/composerSubmissionConfig.js";
  22. const { attachmentState, chatPromptEditorProps, dialogOpenStates, inputClear } = vi.hoisted(() => ({
  23. attachmentState: {
  24. adoptSentAttachments: vi.fn(async () => {}),
  25. hasUnreadyAttachments: false,
  26. prepareForSend: vi.fn(async () => []),
  27. },
  28. chatPromptEditorProps: [] as Array<Record<string, unknown>>,
  29. dialogOpenStates: [] as boolean[],
  30. inputClear: vi.fn(),
  31. }));
  32. function expectedTelemetrySendOptions() {
  33. return expect.objectContaining({
  34. telemetrySeed: {
  35. sendTime: expect.any(Number),
  36. extraDetail: {
  37. ask_mode: "",
  38. model_name: "",
  39. model_provider: "glm",
  40. agent: "glm",
  41. plan_status: "unknown",
  42. plan_product_id: "",
  43. message_source: "chat",
  44. task_trigger: "",
  45. },
  46. },
  47. });
  48. }
  49. vi.mock("@/components/ui/dialog.js", async () => {
  50. const React = await import("react");
  51. const Passthrough = ({ children }: { children?: ReactNode }) =>
  52. React.createElement(React.Fragment, null, children);
  53. return {
  54. Dialog: ({ children, open }: { children?: ReactNode; open?: boolean }) => {
  55. dialogOpenStates.push(Boolean(open));
  56. return open ? React.createElement(React.Fragment, null, children) : null;
  57. },
  58. DialogClose: Passthrough,
  59. DialogContent: Passthrough,
  60. DialogDescription: Passthrough,
  61. DialogFooter: Passthrough,
  62. DialogHeader: Passthrough,
  63. DialogTitle: Passthrough,
  64. };
  65. });
  66. vi.mock("@/ControlHintTooltip.js", async () => {
  67. const React = await import("react");
  68. return {
  69. ControlHintTooltip: ({ children }: { children: ReactNode }) =>
  70. React.createElement(React.Fragment, null, children),
  71. };
  72. });
  73. vi.mock("@/prompt-editor/ChatPromptEditor.js", async () => {
  74. const React = await import("react");
  75. return {
  76. ChatPromptEditor: (props: Record<string, unknown>) => {
  77. chatPromptEditorProps.push(props);
  78. const inputApiRef = props.inputApiRef as
  79. | { current: Record<string, unknown> | null }
  80. | undefined;
  81. if (inputApiRef) {
  82. inputApiRef.current = {
  83. clear: inputClear,
  84. focus: vi.fn(),
  85. getEditorState: () => null,
  86. getMarkdown: () => "",
  87. setEditorStateJson: vi.fn(),
  88. setText: vi.fn(),
  89. };
  90. }
  91. return React.createElement(
  92. "form",
  93. { "data-testid": "mock-chat-prompt-editor" },
  94. props.topContent as ReactNode,
  95. props.leadingActions as ReactNode,
  96. props.submitControl as ReactNode,
  97. );
  98. },
  99. };
  100. });
  101. vi.mock("@/components/ai-elements/attachments.js", async () => {
  102. const React = await import("react");
  103. const Passthrough = ({
  104. children,
  105. ...props
  106. }: {
  107. children?: React.ReactNode;
  108. } & Record<string, unknown>) => React.createElement("div", props, children);
  109. const Trigger = ({ children }: { children?: React.ReactNode }) =>
  110. React.createElement(React.Fragment, null, children);
  111. const Span = (props: Record<string, unknown>) => React.createElement("span", props);
  112. return {
  113. Attachment: Passthrough,
  114. AttachmentHoverCard: Passthrough,
  115. AttachmentHoverCardContent: Passthrough,
  116. AttachmentHoverCardTrigger: Trigger,
  117. AttachmentInfo: Span,
  118. AttachmentPreview: Span,
  119. AttachmentRemove: (props: Record<string, unknown>) => React.createElement("button", props),
  120. Attachments: Passthrough,
  121. };
  122. });
  123. vi.mock("@/v4/composer/useComposerAttachments.js", () => ({
  124. useComposerAttachments: () => ({
  125. attachmentError: null,
  126. adoptSentAttachments: attachmentState.adoptSentAttachments,
  127. attachmentInputRef: { current: null },
  128. attachments: [],
  129. clearAttachments: vi.fn(),
  130. handleAttachmentInputChange: vi.fn(),
  131. handleDragLeaveComposer: vi.fn(),
  132. handleDragOverComposer: vi.fn(),
  133. handleDropComposer: vi.fn(),
  134. handlePaste: vi.fn(),
  135. handleWhiteboardMentionSelected: vi.fn(),
  136. hasAttachments: false,
  137. hasUnreadyAttachments: attachmentState.hasUnreadyAttachments,
  138. isDraggingOverComposer: false,
  139. openAttachmentPicker: vi.fn(),
  140. prepareForSend: attachmentState.prepareForSend,
  141. removeAttachment: vi.fn(),
  142. retryAttachment: vi.fn(),
  143. setAttachmentError: vi.fn(),
  144. }),
  145. }));
  146. vi.mock("@/v4/composer/V4ComposerToolbar.js", async () => {
  147. const React = await import("react");
  148. return {
  149. V4ComposerModeSwitch: () => React.createElement("span", null, "mode"),
  150. V4ComposerModelControls: () => React.createElement("span", null, "model"),
  151. };
  152. });
  153. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  154. const element = {
  155. addEventListener: () => {},
  156. appendChild: (child: Node) => {
  157. Object.assign(child, { parentNode: element });
  158. element.childNodes.push(child);
  159. return child;
  160. },
  161. attributes: new Map<string, string>(),
  162. childNodes: [] as Node[],
  163. getAttribute: (name: string) => element.attributes.get(name) ?? null,
  164. insertBefore: (child: Node, beforeChild?: Node | null) => {
  165. Object.assign(child, { parentNode: element });
  166. const beforeIndex = beforeChild ? element.childNodes.indexOf(beforeChild) : -1;
  167. if (beforeIndex >= 0) {
  168. element.childNodes.splice(beforeIndex, 0, child);
  169. } else {
  170. element.childNodes.push(child);
  171. }
  172. return child;
  173. },
  174. nodeName: tagName.toUpperCase(),
  175. nodeType: 1,
  176. ownerDocument,
  177. parentNode: null as Node | null,
  178. removeAttribute: (name: string) => {
  179. element.attributes.delete(name);
  180. },
  181. removeChild: (child: Node) => {
  182. element.childNodes = element.childNodes.filter((item) => item !== child);
  183. Object.assign(child, { parentNode: null });
  184. return child;
  185. },
  186. removeEventListener: () => {},
  187. setAttribute: (name: string, value: string) => {
  188. element.attributes.set(name, String(value));
  189. },
  190. style: {},
  191. tagName: tagName.toUpperCase(),
  192. };
  193. return element as unknown as Element;
  194. }
  195. function createStorageMock(): Storage {
  196. const values = new Map<string, string>();
  197. return {
  198. clear: () => values.clear(),
  199. getItem: (key: string) => values.get(key) ?? null,
  200. key: (index: number) => Array.from(values.keys())[index] ?? null,
  201. get length() {
  202. return values.size;
  203. },
  204. removeItem: (key: string) => {
  205. values.delete(key);
  206. },
  207. setItem: vi.fn((key: string, value: string) => {
  208. values.set(key, String(value));
  209. }),
  210. } as Storage;
  211. }
  212. function installMinimalDom() {
  213. const target = new EventTarget();
  214. const documentMock = {
  215. addEventListener: () => {},
  216. createComment: (nodeValue: string) => ({
  217. nodeType: 8,
  218. nodeValue,
  219. parentNode: null,
  220. }),
  221. createElement: (tagName: string) =>
  222. createMinimalElement(documentMock as unknown as Document, tagName),
  223. createElementNS: (_namespace: string, tagName: string) =>
  224. createMinimalElement(documentMock as unknown as Document, tagName),
  225. createTextNode: (nodeValue: string) => ({
  226. nodeType: 3,
  227. nodeValue,
  228. parentNode: null,
  229. }),
  230. nodeType: 9,
  231. removeEventListener: () => {},
  232. } as unknown as Document & { defaultView?: unknown };
  233. const windowMock = {
  234. addEventListener: target.addEventListener.bind(target),
  235. cancelAnimationFrame: () => {},
  236. clearTimeout,
  237. document: documentMock,
  238. HTMLIFrameElement: function HTMLIFrameElement() {},
  239. HTMLElement: function HTMLElement() {},
  240. localStorage: createStorageMock(),
  241. matchMedia: () => ({
  242. addEventListener: () => {},
  243. addListener: () => {},
  244. matches: false,
  245. removeEventListener: () => {},
  246. removeListener: () => {},
  247. }),
  248. Node: function Node() {},
  249. removeEventListener: target.removeEventListener.bind(target),
  250. requestAnimationFrame: (callback: FrameRequestCallback) => {
  251. callback(0);
  252. return 0;
  253. },
  254. setTimeout,
  255. };
  256. documentMock.defaultView = windowMock;
  257. Object.defineProperty(globalThis, "document", {
  258. configurable: true,
  259. value: documentMock,
  260. });
  261. Object.defineProperty(globalThis, "window", {
  262. configurable: true,
  263. value: windowMock,
  264. });
  265. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  266. configurable: true,
  267. value: true,
  268. });
  269. return createMinimalElement(documentMock, "div");
  270. }
  271. function flushAsyncWork() {
  272. return new Promise((resolve) => setTimeout(resolve, 0));
  273. }
  274. function renderComposerElement(
  275. onSendText: (text: string, options?: unknown) => Promise<ConversationComposerSendResult | void>,
  276. sessionId: string | null,
  277. telemetryDraftConfig?: {
  278. mode?: string;
  279. model?: string;
  280. provider?: string;
  281. },
  282. skillCatalogSessionId?: string | null,
  283. createSubmissionFromComposer?: () => ComposerSubmissionConfig | null,
  284. composerDraft?: V4ComposerDraft,
  285. updateComposerContent?: (
  286. content: Pick<V4ComposerDraft, "text" | "editorStateJson" | "mention">,
  287. ) => void,
  288. submissionReady = true,
  289. ) {
  290. const scopeId = sessionId ?? V4_DRAFT_SCOPE_ROOT;
  291. let ownedDraft =
  292. composerDraft ??
  293. readV4ComposerDraft("/workspace", undefined, scopeId) ?? {
  294. text: "",
  295. updatedAt: 0,
  296. };
  297. const persistOwnedContent =
  298. updateComposerContent ??
  299. ((content: Pick<V4ComposerDraft, "text" | "editorStateJson" | "mention">) => {
  300. ownedDraft = { ...ownedDraft, ...content };
  301. persistV4ComposerDraft("/workspace", undefined, scopeId, ownedDraft);
  302. });
  303. return createElement(
  304. ZCodeIntlProvider,
  305. { initialLocale: "zh-CN" },
  306. createElement(ConversationComposer, {
  307. draftMode: sessionId === null,
  308. onSelectModel: vi.fn(),
  309. onSelectThought: vi.fn(),
  310. onSendText,
  311. createSubmissionFromComposer,
  312. submissionReady,
  313. composerDraft: ownedDraft,
  314. updateComposerContent: persistOwnedContent,
  315. replaceComposerDraft: (next) => {
  316. ownedDraft = { ...next, updatedAt: Date.now() };
  317. persistV4ComposerDraft("/workspace", undefined, scopeId, ownedDraft);
  318. },
  319. onStop: vi.fn(),
  320. onSwitchMode: vi.fn(),
  321. provider: undefined,
  322. sessionId,
  323. skillCatalogSessionId,
  324. snapshot: null,
  325. telemetryDraftConfig,
  326. workspacePath: "/workspace",
  327. }),
  328. );
  329. }
  330. function renderComposer(
  331. onSendText: (text: string, options?: unknown) => Promise<ConversationComposerSendResult | void>,
  332. telemetryDraftConfig?: {
  333. mode?: string;
  334. model?: string;
  335. provider?: string;
  336. },
  337. ) {
  338. const container = installMinimalDom();
  339. const root: Root = createRoot(container);
  340. act(() => {
  341. root.render(renderComposerElement(onSendText, null, telemetryDraftConfig));
  342. });
  343. return {
  344. rerenderSession: (sessionId: string) => {
  345. act(() => root.render(renderComposerElement(onSendText, sessionId)));
  346. },
  347. root,
  348. };
  349. }
  350. afterEach(() => {
  351. chatPromptEditorProps.length = 0;
  352. attachmentState.hasUnreadyAttachments = false;
  353. attachmentState.adoptSentAttachments.mockClear();
  354. attachmentState.prepareForSend.mockClear();
  355. attachmentState.prepareForSend.mockResolvedValue([]);
  356. inputClear.mockClear();
  357. dialogOpenStates.length = 0;
  358. delete (globalThis as { document?: unknown }).document;
  359. delete (globalThis as { window?: unknown }).window;
  360. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  361. });
  362. describe("ConversationComposer prompt history", () => {
  363. it("真实编辑器文本变更会推进草稿 revision,保护迟到的推荐 Prompt", async () => {
  364. const { root } = renderComposer(vi.fn(async () => {}));
  365. const revisionBefore = getComposerDraftRevision("/workspace");
  366. const onChange = chatPromptEditorProps.at(-1)?.onChange;
  367. await act(async () => {
  368. (onChange as (value: string) => void)("用户正在输入");
  369. });
  370. expect(getComposerDraftRevision("/workspace")).toBe(revisionBefore + 1);
  371. await act(async () => root.unmount());
  372. });
  373. it("草稿预热 Session 只作为 Skill catalog authority 传给输入区", async () => {
  374. const container = installMinimalDom();
  375. const root: Root = createRoot(container);
  376. act(() => {
  377. root.render(
  378. renderComposerElement(
  379. vi.fn(async () => {}),
  380. null,
  381. undefined,
  382. "prewarm-a",
  383. ),
  384. );
  385. });
  386. expect(chatPromptEditorProps.at(-1)).toMatchObject({
  387. taskId: null,
  388. skillCatalogSessionId: "prewarm-a",
  389. });
  390. await act(async () => root.unmount());
  391. });
  392. it("prewarm snapshot 未到时仍用冻结草稿 config 建立 send telemetry seed", async () => {
  393. const onSendText = vi.fn(async () => {});
  394. const { root } = renderComposer(onSendText, {
  395. mode: "build",
  396. model: "deepseek-v4-flash",
  397. provider: "e2e-deepseek",
  398. });
  399. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  400. await act(async () => {
  401. (submit as (value: string) => boolean)("立即发送草稿");
  402. await flushAsyncWork();
  403. });
  404. expect(onSendText).toHaveBeenCalledWith(
  405. "立即发送草稿",
  406. expect.objectContaining({
  407. telemetrySeed: expect.objectContaining({
  408. extraDetail: expect.objectContaining({
  409. ask_mode: "build",
  410. model_name: "custom:e2e-deepseek:deepseek-v4-flash",
  411. model_provider: "e2e-deepseek",
  412. }),
  413. }),
  414. }),
  415. );
  416. await act(async () => root.unmount());
  417. });
  418. it("存在非 ready 附件时 submit 不发送,也不调用最终附件提交入口", async () => {
  419. attachmentState.hasUnreadyAttachments = true;
  420. const onSendText = vi.fn(async () => {});
  421. const { root } = renderComposer(onSendText);
  422. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  423. await act(async () => {
  424. (submit as (value: string) => boolean)("不能提前发送");
  425. await flushAsyncWork();
  426. });
  427. expect(attachmentState.prepareForSend).not.toHaveBeenCalled();
  428. expect(attachmentState.adoptSentAttachments).not.toHaveBeenCalled();
  429. expect(onSendText).not.toHaveBeenCalled();
  430. await act(async () => root.unmount());
  431. });
  432. it("等待附件就绪期间切换模型,本次请求仍使用点击发送时的选择", async () => {
  433. const container = installMinimalDom();
  434. const root = createRoot(container);
  435. const onSendText = vi.fn(async () => {});
  436. let composer: ComposerSubmissionConfig = {
  437. mode: "build",
  438. modelSelection: {
  439. providerId: "provider-a",
  440. modelId: "shared-model",
  441. options: { reasoningLevel: "high" },
  442. },
  443. };
  444. const readSubmission = vi.fn(() => structuredClone(composer));
  445. let finishAttachments!: (value: []) => void;
  446. attachmentState.prepareForSend.mockImplementationOnce(
  447. () =>
  448. new Promise<[]>((resolve) => {
  449. finishAttachments = resolve;
  450. }),
  451. );
  452. act(() =>
  453. root.render(renderComposerElement(onSendText, null, undefined, null, readSubmission)),
  454. );
  455. const submit = chatPromptEditorProps.at(-1)!.onSubmit as (text: string) => boolean;
  456. await act(async () => {
  457. submit("冻结本次选择");
  458. await flushAsyncWork();
  459. });
  460. expect(readSubmission).toHaveBeenCalledTimes(1);
  461. expect(onSendText).not.toHaveBeenCalled();
  462. composer = {
  463. mode: "yolo",
  464. modelSelection: {
  465. providerId: "provider-b",
  466. modelId: "shared-model",
  467. options: { reasoningLevel: "low" },
  468. },
  469. };
  470. await act(async () => {
  471. finishAttachments([]);
  472. await flushAsyncWork();
  473. });
  474. expect(readSubmission).toHaveBeenCalledTimes(1);
  475. expect(onSendText).toHaveBeenCalledWith(
  476. "冻结本次选择",
  477. expect.objectContaining({
  478. submission: {
  479. mode: "build",
  480. modelSelection: {
  481. providerId: "provider-a",
  482. modelId: "shared-model",
  483. options: { reasoningLevel: "high" },
  484. },
  485. },
  486. }),
  487. );
  488. await act(async () => root.unmount());
  489. });
  490. it("模型或 reasoning 选择不完整时禁止提交并保留正文", async () => {
  491. const onSendText = vi.fn(async () => {});
  492. const container = installMinimalDom();
  493. const root = createRoot(container);
  494. act(() =>
  495. root.render(
  496. renderComposerElement(
  497. onSendText,
  498. "session-a",
  499. undefined,
  500. null,
  501. () => null,
  502. undefined,
  503. undefined,
  504. false,
  505. ),
  506. ),
  507. );
  508. expect(chatPromptEditorProps.at(-1)?.submitDisabled).toBe(true);
  509. await act(async () => {
  510. (chatPromptEditorProps.at(-1)!.onSubmit as (text: string) => boolean)("等待补全选择");
  511. await flushAsyncWork();
  512. });
  513. expect(onSendText).not.toHaveBeenCalled();
  514. expect(inputClear).not.toHaveBeenCalled();
  515. await act(async () => root.unmount());
  516. });
  517. it("发送成功只清正文,保留当前 scope 的模式和模型选择", async () => {
  518. const container = installMinimalDom();
  519. const root = createRoot(container);
  520. const selection = {
  521. providerId: "provider-a",
  522. modelId: "model-a",
  523. options: { reasoningLevel: "high" },
  524. };
  525. let draft: V4ComposerDraft = {
  526. text: "会被发送",
  527. mode: "yolo",
  528. modelSelection: selection,
  529. updatedAt: 1,
  530. };
  531. persistV4ComposerDraft("/workspace", undefined, "session-a", draft);
  532. const updateContent = vi.fn(
  533. (content: Pick<V4ComposerDraft, "text" | "editorStateJson" | "mention">) => {
  534. draft = { ...draft, ...content };
  535. persistV4ComposerDraft("/workspace", undefined, "session-a", draft);
  536. },
  537. );
  538. act(() =>
  539. root.render(
  540. renderComposerElement(
  541. vi.fn(async () => {}),
  542. "session-a",
  543. undefined,
  544. null,
  545. () => ({ mode: "yolo", modelSelection: selection }),
  546. draft,
  547. updateContent,
  548. ),
  549. ),
  550. );
  551. await act(async () => {
  552. (chatPromptEditorProps.at(-1)!.onSubmit as (text: string) => boolean)("会被发送");
  553. await flushAsyncWork();
  554. });
  555. expect(readV4ComposerDraft("/workspace", undefined, "session-a")).toMatchObject({
  556. text: "",
  557. mode: "yolo",
  558. modelSelection: selection,
  559. });
  560. await act(async () => root.unmount());
  561. });
  562. it("迟到的发送成功不能清除等待期间产生的新正文", async () => {
  563. let resolveSend!: () => void;
  564. const onSendText = vi.fn(
  565. () => new Promise<void>((resolve) => { resolveSend = resolve; }),
  566. );
  567. const { root } = renderComposer(onSendText);
  568. const submit = chatPromptEditorProps.at(-1)!.onSubmit as (text: string) => boolean;
  569. const onChange = chatPromptEditorProps.at(-1)!.onChange as (text: string) => void;
  570. inputClear.mockClear();
  571. await act(async () => {
  572. submit("第一条");
  573. await flushAsyncWork();
  574. });
  575. await act(async () => onChange("下一条"));
  576. await act(async () => {
  577. resolveSend();
  578. await flushAsyncWork();
  579. });
  580. expect(inputClear).not.toHaveBeenCalled();
  581. expect(readV4ComposerDraft("/workspace", undefined, V4_DRAFT_SCOPE_ROOT)?.text).toBe("下一条");
  582. await act(async () => root.unmount());
  583. });
  584. it("二次门禁返回 null 时保留编辑器且不发送", async () => {
  585. attachmentState.prepareForSend.mockResolvedValueOnce(null);
  586. const onSendText = vi.fn(async () => {});
  587. const { root } = renderComposer(onSendText);
  588. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  589. await act(async () => {
  590. (submit as (value: string) => boolean)("提交边界再次检查");
  591. await flushAsyncWork();
  592. });
  593. expect(attachmentState.prepareForSend).toHaveBeenCalledTimes(1);
  594. expect(attachmentState.adoptSentAttachments).not.toHaveBeenCalled();
  595. expect(onSendText).not.toHaveBeenCalled();
  596. expect(inputClear).not.toHaveBeenCalled();
  597. expect(readPromptHistoryEntries("/workspace")).toEqual([]);
  598. await act(async () => root.unmount());
  599. });
  600. it("writes submitted text to localStorage before an accepted send can promote away the draft composer", async () => {
  601. let resolveSend: (() => void) | undefined;
  602. const onSendText = vi.fn(
  603. () =>
  604. new Promise<void>((resolve) => {
  605. resolveSend = resolve;
  606. }),
  607. );
  608. const { root } = renderComposer(onSendText);
  609. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  610. expect(typeof submit).toBe("function");
  611. await act(async () => {
  612. (submit as (value: string) => boolean)("你回答 1");
  613. await flushAsyncWork();
  614. });
  615. expect(onSendText).toHaveBeenCalledWith("你回答 1", expectedTelemetrySendOptions());
  616. expect(readPromptHistoryEntries("/workspace")).toEqual(["你回答 1"]);
  617. await act(async () => {
  618. root.unmount();
  619. resolveSend?.();
  620. await flushAsyncWork();
  621. });
  622. });
  623. it("restores the previous localStorage prompt history when send fails", async () => {
  624. const onSendText = vi.fn(async () => {
  625. throw new Error("send failed");
  626. });
  627. const { root } = renderComposer(onSendText);
  628. persistPromptHistoryEntries("/workspace", ["上一条"]);
  629. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  630. expect(typeof submit).toBe("function");
  631. await act(async () => {
  632. (submit as (value: string) => boolean)("失败的消息");
  633. await flushAsyncWork();
  634. });
  635. expect(onSendText).toHaveBeenCalledWith("失败的消息", expectedTelemetrySendOptions());
  636. expect(readPromptHistoryEntries("/workspace")).toEqual(["上一条"]);
  637. await act(async () => {
  638. root.unmount();
  639. });
  640. });
  641. it("keeps the editor draft and prompt history untouched when a product guard blocks send", async () => {
  642. const onSendText = vi.fn(async () => "blocked" as const);
  643. const { root } = renderComposer(onSendText);
  644. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  645. await act(async () => {
  646. (submit as (value: string) => boolean)("/goal 保留这段输入");
  647. await flushAsyncWork();
  648. });
  649. expect(onSendText).toHaveBeenCalledWith("/goal 保留这段输入", expectedTelemetrySendOptions());
  650. expect(inputClear).not.toHaveBeenCalled();
  651. expect(attachmentState.adoptSentAttachments).not.toHaveBeenCalled();
  652. expect(readPromptHistoryEntries("/workspace")).toEqual([]);
  653. expect(readV4ComposerDraft("/workspace", undefined, V4_DRAFT_SCOPE_ROOT)?.text).toBe(
  654. "/goal 保留这段输入",
  655. );
  656. await act(async () => {
  657. root.unmount();
  658. });
  659. });
  660. it("opens paused-queue confirmation without adopting the draft or prompt history", async () => {
  661. const onSendText = vi.fn(async () => "confirmationRequired" as const);
  662. const { root } = renderComposer(onSendText);
  663. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  664. await act(async () => {
  665. (submit as (value: string) => boolean)("等待确认的消息");
  666. await flushAsyncWork();
  667. });
  668. expect(dialogOpenStates.at(-1)).toBe(true);
  669. expect(inputClear).not.toHaveBeenCalled();
  670. expect(attachmentState.adoptSentAttachments).not.toHaveBeenCalled();
  671. expect(readPromptHistoryEntries("/workspace")).toEqual([]);
  672. expect(readV4ComposerDraft("/workspace", undefined, V4_DRAFT_SCOPE_ROOT)?.text).toBe(
  673. "等待确认的消息",
  674. );
  675. await act(async () => root.unmount());
  676. });
  677. it("does not persist a consecutive duplicate after trimming outer whitespace", async () => {
  678. const onSendText = vi.fn(async () => {});
  679. const { root } = renderComposer(onSendText);
  680. const firstSubmit = chatPromptEditorProps.at(-1)?.onSubmit;
  681. await act(async () => {
  682. (firstSubmit as (value: string) => boolean)("重复消息");
  683. await flushAsyncWork();
  684. });
  685. const setItem = vi.mocked(window.localStorage.setItem);
  686. setItem.mockClear();
  687. const duplicateSubmit = chatPromptEditorProps.at(-1)?.onSubmit;
  688. await act(async () => {
  689. (duplicateSubmit as (value: string) => boolean)(" 重复消息 ");
  690. await flushAsyncWork();
  691. });
  692. expect(onSendText).toHaveBeenNthCalledWith(2, "重复消息", expectedTelemetrySendOptions());
  693. expect(readPromptHistoryEntries("/workspace")).toEqual(["重复消息"]);
  694. expect(setItem).not.toHaveBeenCalled();
  695. await act(async () => {
  696. root.unmount();
  697. });
  698. });
  699. it("does not write or roll back history when a consecutive duplicate send fails", async () => {
  700. const onSendText = vi
  701. .fn<() => Promise<void>>()
  702. .mockResolvedValueOnce()
  703. .mockRejectedValueOnce(new Error("send failed"));
  704. const { root } = renderComposer(onSendText);
  705. const firstSubmit = chatPromptEditorProps.at(-1)?.onSubmit;
  706. await act(async () => {
  707. (firstSubmit as (value: string) => boolean)("重复消息");
  708. await flushAsyncWork();
  709. });
  710. const setItem = vi.mocked(window.localStorage.setItem);
  711. setItem.mockClear();
  712. const duplicateSubmit = chatPromptEditorProps.at(-1)?.onSubmit;
  713. await act(async () => {
  714. (duplicateSubmit as (value: string) => boolean)("重复消息");
  715. await flushAsyncWork();
  716. });
  717. expect(readPromptHistoryEntries("/workspace")).toEqual(["重复消息"]);
  718. expect(setItem).not.toHaveBeenCalledWith(
  719. getPromptHistoryStorageKey("/workspace"),
  720. expect.any(String),
  721. );
  722. await act(async () => {
  723. root.unmount();
  724. });
  725. });
  726. it("does not restore the submitted draft while the composer is promoted to a session", async () => {
  727. let resolveSend: (() => void) | undefined;
  728. const onSendText = vi.fn(
  729. () =>
  730. new Promise<void>((resolve) => {
  731. resolveSend = resolve;
  732. }),
  733. );
  734. const { rerenderSession, root } = renderComposer(onSendText);
  735. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  736. await act(async () => {
  737. (submit as (value: string) => boolean)("首条消息");
  738. await flushAsyncWork();
  739. });
  740. rerenderSession("session-1");
  741. expect(readV4ComposerDraft("/workspace", undefined, V4_DRAFT_SCOPE_ROOT)).toBeNull();
  742. await act(async () => {
  743. resolveSend?.();
  744. await flushAsyncWork();
  745. });
  746. expect(readV4ComposerDraft("/workspace", undefined, V4_DRAFT_SCOPE_ROOT)).toBeNull();
  747. await act(async () => {
  748. root.unmount();
  749. });
  750. });
  751. });