v4ConversationComposerPromptHistory.test.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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 { pendingCommandRegistry } from "@/v4/pendingCommandRegistry.js";
  22. import type {
  23. CommandAck,
  24. CommandEnvelope,
  25. ConversationSnapshot,
  26. } from "@zcode/shared/zcode-protocol-v4";
  27. import type { ComposerSubmissionConfig } from "@/v4/composer/composerSubmissionConfig.js";
  28. const { attachmentState, chatPromptEditorProps, dialogOpenStates, inputClear, inputSetText } =
  29. vi.hoisted(() => ({
  30. attachmentState: {
  31. adoptSentAttachments: vi.fn(async () => {}),
  32. hasUnreadyAttachments: false,
  33. prepareForSend: vi.fn(async () => []),
  34. },
  35. chatPromptEditorProps: [] as Array<Record<string, unknown>>,
  36. dialogOpenStates: [] as boolean[],
  37. inputClear: vi.fn(),
  38. inputSetText: vi.fn(),
  39. }));
  40. function expectedTelemetrySendOptions() {
  41. return expect.objectContaining({
  42. telemetrySeed: {
  43. sendTime: expect.any(Number),
  44. extraDetail: {
  45. ask_mode: "",
  46. model_name: "",
  47. model_provider: "glm",
  48. agent: "glm",
  49. plan_status: "unknown",
  50. plan_product_id: "",
  51. message_source: "chat",
  52. task_trigger: "",
  53. },
  54. },
  55. });
  56. }
  57. vi.mock("@/components/ui/dialog.js", async () => {
  58. const React = await import("react");
  59. const Passthrough = ({ children }: { children?: ReactNode }) =>
  60. React.createElement(React.Fragment, null, children);
  61. return {
  62. Dialog: ({ children, open }: { children?: ReactNode; open?: boolean }) => {
  63. dialogOpenStates.push(Boolean(open));
  64. return open ? React.createElement(React.Fragment, null, children) : null;
  65. },
  66. DialogClose: Passthrough,
  67. DialogContent: Passthrough,
  68. DialogDescription: Passthrough,
  69. DialogFooter: Passthrough,
  70. DialogHeader: Passthrough,
  71. DialogTitle: Passthrough,
  72. };
  73. });
  74. vi.mock("@/ControlHintTooltip.js", async () => {
  75. const React = await import("react");
  76. return {
  77. ControlHintTooltip: ({ children }: { children: ReactNode }) =>
  78. React.createElement(React.Fragment, null, children),
  79. };
  80. });
  81. vi.mock("@/prompt-editor/ChatPromptEditor.js", async () => {
  82. const React = await import("react");
  83. return {
  84. ChatPromptEditor: (props: Record<string, unknown>) => {
  85. chatPromptEditorProps.push(props);
  86. const inputApiRef = props.inputApiRef as
  87. | { current: Record<string, unknown> | null }
  88. | undefined;
  89. if (inputApiRef) {
  90. inputApiRef.current = {
  91. clear: inputClear,
  92. focus: vi.fn(),
  93. getEditorState: () => null,
  94. getMarkdown: () => "",
  95. setEditorStateJson: vi.fn(),
  96. setText: inputSetText,
  97. };
  98. }
  99. return React.createElement(
  100. "form",
  101. { "data-testid": "mock-chat-prompt-editor" },
  102. props.topContent as ReactNode,
  103. props.leadingActions as ReactNode,
  104. props.submitControl as ReactNode,
  105. );
  106. },
  107. };
  108. });
  109. vi.mock("@/components/ai-elements/attachments.js", async () => {
  110. const React = await import("react");
  111. const Passthrough = ({
  112. children,
  113. ...props
  114. }: {
  115. children?: React.ReactNode;
  116. } & Record<string, unknown>) => React.createElement("div", props, children);
  117. const Trigger = ({ children }: { children?: React.ReactNode }) =>
  118. React.createElement(React.Fragment, null, children);
  119. const Span = (props: Record<string, unknown>) => React.createElement("span", props);
  120. return {
  121. Attachment: Passthrough,
  122. AttachmentHoverCard: Passthrough,
  123. AttachmentHoverCardContent: Passthrough,
  124. AttachmentHoverCardTrigger: Trigger,
  125. AttachmentInfo: Span,
  126. AttachmentPreview: Span,
  127. AttachmentRemove: (props: Record<string, unknown>) => React.createElement("button", props),
  128. Attachments: Passthrough,
  129. };
  130. });
  131. vi.mock("@/v4/composer/useComposerAttachments.js", () => ({
  132. useComposerAttachments: () => ({
  133. attachmentError: null,
  134. adoptSentAttachments: attachmentState.adoptSentAttachments,
  135. attachmentInputRef: { current: null },
  136. attachments: [],
  137. clearAttachments: vi.fn(),
  138. handleAttachmentInputChange: vi.fn(),
  139. handleDragLeaveComposer: vi.fn(),
  140. handleDragOverComposer: vi.fn(),
  141. handleDropComposer: vi.fn(),
  142. handlePaste: vi.fn(),
  143. handleWhiteboardMentionSelected: vi.fn(),
  144. hasAttachments: false,
  145. hasUnreadyAttachments: attachmentState.hasUnreadyAttachments,
  146. isDraggingOverComposer: false,
  147. openAttachmentPicker: vi.fn(),
  148. prepareForSend: attachmentState.prepareForSend,
  149. removeAttachment: vi.fn(),
  150. retryAttachment: vi.fn(),
  151. setAttachmentError: vi.fn(),
  152. }),
  153. }));
  154. vi.mock("@/v4/composer/V4ComposerToolbar.js", async () => {
  155. const React = await import("react");
  156. return {
  157. V4ComposerModeSwitch: () => React.createElement("span", null, "mode"),
  158. V4ComposerModelControls: () => React.createElement("span", null, "model"),
  159. };
  160. });
  161. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  162. const element = {
  163. addEventListener: () => {},
  164. appendChild: (child: Node) => {
  165. Object.assign(child, { parentNode: element });
  166. element.childNodes.push(child);
  167. return child;
  168. },
  169. attributes: new Map<string, string>(),
  170. childNodes: [] as Node[],
  171. getAttribute: (name: string) => element.attributes.get(name) ?? null,
  172. insertBefore: (child: Node, beforeChild?: Node | null) => {
  173. Object.assign(child, { parentNode: element });
  174. const beforeIndex = beforeChild ? element.childNodes.indexOf(beforeChild) : -1;
  175. if (beforeIndex >= 0) {
  176. element.childNodes.splice(beforeIndex, 0, child);
  177. } else {
  178. element.childNodes.push(child);
  179. }
  180. return child;
  181. },
  182. nodeName: tagName.toUpperCase(),
  183. nodeType: 1,
  184. ownerDocument,
  185. parentNode: null as Node | null,
  186. removeAttribute: (name: string) => {
  187. element.attributes.delete(name);
  188. },
  189. removeChild: (child: Node) => {
  190. element.childNodes = element.childNodes.filter((item) => item !== child);
  191. Object.assign(child, { parentNode: null });
  192. return child;
  193. },
  194. removeEventListener: () => {},
  195. setAttribute: (name: string, value: string) => {
  196. element.attributes.set(name, String(value));
  197. },
  198. style: {},
  199. tagName: tagName.toUpperCase(),
  200. };
  201. return element as unknown as Element;
  202. }
  203. function createStorageMock(): Storage {
  204. const values = new Map<string, string>();
  205. return {
  206. clear: () => values.clear(),
  207. getItem: (key: string) => values.get(key) ?? null,
  208. key: (index: number) => Array.from(values.keys())[index] ?? null,
  209. get length() {
  210. return values.size;
  211. },
  212. removeItem: (key: string) => {
  213. values.delete(key);
  214. },
  215. setItem: vi.fn((key: string, value: string) => {
  216. values.set(key, String(value));
  217. }),
  218. } as Storage;
  219. }
  220. function installMinimalDom() {
  221. const target = new EventTarget();
  222. const documentMock = {
  223. addEventListener: () => {},
  224. createComment: (nodeValue: string) => ({
  225. nodeType: 8,
  226. nodeValue,
  227. parentNode: null,
  228. }),
  229. createElement: (tagName: string) =>
  230. createMinimalElement(documentMock as unknown as Document, tagName),
  231. createElementNS: (_namespace: string, tagName: string) =>
  232. createMinimalElement(documentMock as unknown as Document, tagName),
  233. createTextNode: (nodeValue: string) => ({
  234. nodeType: 3,
  235. nodeValue,
  236. parentNode: null,
  237. }),
  238. nodeType: 9,
  239. removeEventListener: () => {},
  240. } as unknown as Document & { defaultView?: unknown };
  241. const windowMock = {
  242. addEventListener: target.addEventListener.bind(target),
  243. cancelAnimationFrame: () => {},
  244. clearTimeout,
  245. document: documentMock,
  246. HTMLIFrameElement: function HTMLIFrameElement() {},
  247. HTMLElement: function HTMLElement() {},
  248. localStorage: createStorageMock(),
  249. matchMedia: () => ({
  250. addEventListener: () => {},
  251. addListener: () => {},
  252. matches: false,
  253. removeEventListener: () => {},
  254. removeListener: () => {},
  255. }),
  256. Node: function Node() {},
  257. removeEventListener: target.removeEventListener.bind(target),
  258. requestAnimationFrame: (callback: FrameRequestCallback) => {
  259. callback(0);
  260. return 0;
  261. },
  262. setTimeout,
  263. };
  264. documentMock.defaultView = windowMock;
  265. Object.defineProperty(globalThis, "document", {
  266. configurable: true,
  267. value: documentMock,
  268. });
  269. Object.defineProperty(globalThis, "window", {
  270. configurable: true,
  271. value: windowMock,
  272. });
  273. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  274. configurable: true,
  275. value: true,
  276. });
  277. return createMinimalElement(documentMock, "div");
  278. }
  279. function flushAsyncWork() {
  280. return new Promise((resolve) => setTimeout(resolve, 0));
  281. }
  282. function renderComposerElement(
  283. onSendText: (text: string, options?: unknown) => Promise<ConversationComposerSendResult | void>,
  284. sessionId: string | null,
  285. telemetryDraftConfig?: {
  286. mode?: string;
  287. model?: string;
  288. provider?: string;
  289. },
  290. skillCatalogSessionId?: string | null,
  291. createSubmissionFromComposer?: () => ComposerSubmissionConfig | null,
  292. composerDraft?: V4ComposerDraft,
  293. updateComposerContent?: (
  294. content: Pick<V4ComposerDraft, "text" | "editorStateJson" | "mention">,
  295. ) => void,
  296. submissionReady = true,
  297. ) {
  298. const scopeId = sessionId ?? V4_DRAFT_SCOPE_ROOT;
  299. let ownedDraft = composerDraft ??
  300. readV4ComposerDraft("/workspace", undefined, scopeId) ?? {
  301. text: "",
  302. updatedAt: 0,
  303. };
  304. const persistOwnedContent =
  305. updateComposerContent ??
  306. ((content: Pick<V4ComposerDraft, "text" | "editorStateJson" | "mention">) => {
  307. ownedDraft = { ...ownedDraft, ...content };
  308. persistV4ComposerDraft("/workspace", undefined, scopeId, ownedDraft);
  309. });
  310. return createElement(
  311. ZCodeIntlProvider,
  312. { initialLocale: "zh-CN" },
  313. createElement(ConversationComposer, {
  314. draftMode: sessionId === null,
  315. onSelectModel: vi.fn(),
  316. onSelectThought: vi.fn(),
  317. onSendText,
  318. createSubmissionFromComposer,
  319. submissionReady,
  320. composerDraft: ownedDraft,
  321. updateComposerContent: persistOwnedContent,
  322. replaceComposerDraft: (next) => {
  323. ownedDraft = { ...next, updatedAt: Date.now() };
  324. persistV4ComposerDraft("/workspace", undefined, scopeId, ownedDraft);
  325. },
  326. onStop: vi.fn(),
  327. onSwitchMode: vi.fn(),
  328. provider: undefined,
  329. sessionId,
  330. skillCatalogSessionId,
  331. snapshot: null,
  332. telemetryDraftConfig,
  333. workspacePath: "/workspace",
  334. }),
  335. );
  336. }
  337. function renderComposer(
  338. onSendText: (text: string, options?: unknown) => Promise<ConversationComposerSendResult | void>,
  339. telemetryDraftConfig?: {
  340. mode?: string;
  341. model?: string;
  342. provider?: string;
  343. },
  344. ) {
  345. const container = installMinimalDom();
  346. const root: Root = createRoot(container);
  347. act(() => {
  348. root.render(renderComposerElement(onSendText, null, telemetryDraftConfig));
  349. });
  350. return {
  351. rerenderSession: (sessionId: string) => {
  352. act(() => root.render(renderComposerElement(onSendText, sessionId)));
  353. },
  354. root,
  355. };
  356. }
  357. afterEach(() => {
  358. chatPromptEditorProps.length = 0;
  359. attachmentState.hasUnreadyAttachments = false;
  360. attachmentState.adoptSentAttachments.mockClear();
  361. attachmentState.prepareForSend.mockClear();
  362. attachmentState.prepareForSend.mockResolvedValue([]);
  363. inputClear.mockClear();
  364. inputSetText.mockClear();
  365. dialogOpenStates.length = 0;
  366. delete (globalThis as { document?: unknown }).document;
  367. delete (globalThis as { window?: unknown }).window;
  368. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  369. });
  370. describe("ConversationComposer prompt history", () => {
  371. it("真实编辑器文本变更会推进草稿 revision,保护迟到的推荐 Prompt", async () => {
  372. const { root } = renderComposer(vi.fn(async () => {}));
  373. const revisionBefore = getComposerDraftRevision("/workspace");
  374. const onChange = chatPromptEditorProps.at(-1)?.onChange;
  375. await act(async () => {
  376. (onChange as (value: string) => void)("用户正在输入");
  377. });
  378. expect(getComposerDraftRevision("/workspace")).toBe(revisionBefore + 1);
  379. await act(async () => root.unmount());
  380. });
  381. it("草稿预热 Session 只作为 Skill catalog authority 传给输入区", async () => {
  382. const container = installMinimalDom();
  383. const root: Root = createRoot(container);
  384. act(() => {
  385. root.render(
  386. renderComposerElement(
  387. vi.fn(async () => {}),
  388. null,
  389. undefined,
  390. "prewarm-a",
  391. ),
  392. );
  393. });
  394. expect(chatPromptEditorProps.at(-1)).toMatchObject({
  395. taskId: null,
  396. skillCatalogSessionId: "prewarm-a",
  397. });
  398. await act(async () => root.unmount());
  399. });
  400. it("prewarm snapshot 未到时仍用冻结草稿 config 建立 send telemetry seed", async () => {
  401. const onSendText = vi.fn(async () => {});
  402. const { root } = renderComposer(onSendText, {
  403. mode: "build",
  404. model: "deepseek-v4-flash",
  405. provider: "e2e-deepseek",
  406. });
  407. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  408. await act(async () => {
  409. (submit as (value: string) => boolean)("立即发送草稿");
  410. await flushAsyncWork();
  411. });
  412. expect(onSendText).toHaveBeenCalledWith(
  413. "立即发送草稿",
  414. expect.objectContaining({
  415. telemetrySeed: expect.objectContaining({
  416. extraDetail: expect.objectContaining({
  417. ask_mode: "build",
  418. model_name: "custom:e2e-deepseek:deepseek-v4-flash",
  419. model_provider: "e2e-deepseek",
  420. }),
  421. }),
  422. }),
  423. );
  424. await act(async () => root.unmount());
  425. });
  426. it("存在非 ready 附件时 submit 不发送,也不调用最终附件提交入口", async () => {
  427. attachmentState.hasUnreadyAttachments = true;
  428. const onSendText = vi.fn(async () => {});
  429. const { root } = renderComposer(onSendText);
  430. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  431. await act(async () => {
  432. (submit as (value: string) => boolean)("不能提前发送");
  433. await flushAsyncWork();
  434. });
  435. expect(attachmentState.prepareForSend).not.toHaveBeenCalled();
  436. expect(attachmentState.adoptSentAttachments).not.toHaveBeenCalled();
  437. expect(onSendText).not.toHaveBeenCalled();
  438. await act(async () => root.unmount());
  439. });
  440. it("等待附件就绪期间切换模型,本次请求仍使用点击发送时的选择", async () => {
  441. const container = installMinimalDom();
  442. const root = createRoot(container);
  443. const onSendText = vi.fn(async () => {});
  444. let composer: ComposerSubmissionConfig = {
  445. mode: "build",
  446. modelSelection: {
  447. providerId: "provider-a",
  448. modelId: "shared-model",
  449. options: { reasoningLevel: "high" },
  450. },
  451. };
  452. const readSubmission = vi.fn(() => structuredClone(composer));
  453. let finishAttachments!: (value: []) => void;
  454. attachmentState.prepareForSend.mockImplementationOnce(
  455. () =>
  456. new Promise<[]>((resolve) => {
  457. finishAttachments = resolve;
  458. }),
  459. );
  460. act(() =>
  461. root.render(renderComposerElement(onSendText, null, undefined, null, readSubmission)),
  462. );
  463. const submit = chatPromptEditorProps.at(-1)!.onSubmit as (text: string) => boolean;
  464. await act(async () => {
  465. submit("冻结本次选择");
  466. await flushAsyncWork();
  467. });
  468. expect(readSubmission).toHaveBeenCalledTimes(1);
  469. expect(onSendText).not.toHaveBeenCalled();
  470. composer = {
  471. mode: "yolo",
  472. modelSelection: {
  473. providerId: "provider-b",
  474. modelId: "shared-model",
  475. options: { reasoningLevel: "low" },
  476. },
  477. };
  478. await act(async () => {
  479. finishAttachments([]);
  480. await flushAsyncWork();
  481. });
  482. expect(readSubmission).toHaveBeenCalledTimes(1);
  483. expect(onSendText).toHaveBeenCalledWith(
  484. "冻结本次选择",
  485. expect.objectContaining({
  486. submission: {
  487. mode: "build",
  488. modelSelection: {
  489. providerId: "provider-a",
  490. modelId: "shared-model",
  491. options: { reasoningLevel: "high" },
  492. },
  493. },
  494. }),
  495. );
  496. await act(async () => root.unmount());
  497. });
  498. it("模型或 reasoning 选择不完整时禁止提交并保留正文", async () => {
  499. const onSendText = vi.fn(async () => {});
  500. const container = installMinimalDom();
  501. const root = createRoot(container);
  502. act(() =>
  503. root.render(
  504. renderComposerElement(
  505. onSendText,
  506. "session-a",
  507. undefined,
  508. null,
  509. () => null,
  510. undefined,
  511. undefined,
  512. false,
  513. ),
  514. ),
  515. );
  516. expect(chatPromptEditorProps.at(-1)?.submitDisabled).toBe(true);
  517. await act(async () => {
  518. (chatPromptEditorProps.at(-1)!.onSubmit as (text: string) => boolean)("等待补全选择");
  519. await flushAsyncWork();
  520. });
  521. expect(onSendText).not.toHaveBeenCalled();
  522. expect(inputClear).not.toHaveBeenCalled();
  523. await act(async () => root.unmount());
  524. });
  525. it("发送成功删除持久草稿,内存保留当前模式和模型选择", async () => {
  526. const container = installMinimalDom();
  527. const root = createRoot(container);
  528. const selection = {
  529. providerId: "provider-a",
  530. modelId: "model-a",
  531. options: { reasoningLevel: "high" },
  532. };
  533. let draft: V4ComposerDraft = {
  534. text: "会被发送",
  535. mode: "yolo",
  536. modelSelection: selection,
  537. updatedAt: 1,
  538. };
  539. persistV4ComposerDraft("/workspace", undefined, "session-a", draft);
  540. const updateContent = vi.fn(
  541. (content: Pick<V4ComposerDraft, "text" | "editorStateJson" | "mention">) => {
  542. draft = { ...draft, ...content };
  543. persistV4ComposerDraft("/workspace", undefined, "session-a", draft);
  544. },
  545. );
  546. act(() =>
  547. root.render(
  548. renderComposerElement(
  549. vi.fn(async () => {}),
  550. "session-a",
  551. undefined,
  552. null,
  553. () => ({ mode: "yolo", modelSelection: selection }),
  554. draft,
  555. updateContent,
  556. ),
  557. ),
  558. );
  559. await act(async () => {
  560. (chatPromptEditorProps.at(-1)!.onSubmit as (text: string) => boolean)("会被发送");
  561. await flushAsyncWork();
  562. });
  563. expect(readV4ComposerDraft("/workspace", undefined, "session-a")).toBeNull();
  564. expect(draft).toMatchObject({
  565. text: "",
  566. mode: "yolo",
  567. modelSelection: selection,
  568. });
  569. await act(async () => root.unmount());
  570. });
  571. it("迟到的发送成功不能清除等待期间产生的新正文", async () => {
  572. let resolveSend!: () => void;
  573. const onSendText = vi.fn(
  574. () =>
  575. new Promise<void>((resolve) => {
  576. resolveSend = resolve;
  577. }),
  578. );
  579. const { root } = renderComposer(onSendText);
  580. const submit = chatPromptEditorProps.at(-1)!.onSubmit as (text: string) => boolean;
  581. const onChange = chatPromptEditorProps.at(-1)!.onChange as (text: string) => void;
  582. inputClear.mockClear();
  583. await act(async () => {
  584. submit("第一条");
  585. await flushAsyncWork();
  586. });
  587. await act(async () => onChange("下一条"));
  588. await act(async () => {
  589. resolveSend();
  590. await flushAsyncWork();
  591. });
  592. expect(inputClear).not.toHaveBeenCalled();
  593. expect(readV4ComposerDraft("/workspace", undefined, V4_DRAFT_SCOPE_ROOT)?.text).toBe("下一条");
  594. await act(async () => root.unmount());
  595. });
  596. it("二次门禁返回 null 时保留编辑器且不发送", async () => {
  597. attachmentState.prepareForSend.mockResolvedValueOnce(null);
  598. const onSendText = vi.fn(async () => {});
  599. const { root } = renderComposer(onSendText);
  600. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  601. await act(async () => {
  602. (submit as (value: string) => boolean)("提交边界再次检查");
  603. await flushAsyncWork();
  604. });
  605. expect(attachmentState.prepareForSend).toHaveBeenCalledTimes(1);
  606. expect(attachmentState.adoptSentAttachments).not.toHaveBeenCalled();
  607. expect(onSendText).not.toHaveBeenCalled();
  608. expect(inputClear).not.toHaveBeenCalled();
  609. expect(readPromptHistoryEntries("/workspace")).toEqual([]);
  610. await act(async () => root.unmount());
  611. });
  612. it("writes submitted text to localStorage before an accepted send can promote away the draft composer", async () => {
  613. let resolveSend: (() => void) | undefined;
  614. const onSendText = vi.fn(
  615. () =>
  616. new Promise<void>((resolve) => {
  617. resolveSend = resolve;
  618. }),
  619. );
  620. const { root } = renderComposer(onSendText);
  621. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  622. expect(typeof submit).toBe("function");
  623. await act(async () => {
  624. (submit as (value: string) => boolean)("你回答 1");
  625. await flushAsyncWork();
  626. });
  627. expect(onSendText).toHaveBeenCalledWith("你回答 1", expectedTelemetrySendOptions());
  628. expect(readPromptHistoryEntries("/workspace")).toEqual(["你回答 1"]);
  629. await act(async () => {
  630. root.unmount();
  631. resolveSend?.();
  632. await flushAsyncWork();
  633. });
  634. });
  635. it("restores the previous localStorage prompt history when send fails", async () => {
  636. const onSendText = vi.fn(async () => {
  637. throw new Error("send failed");
  638. });
  639. const { root } = renderComposer(onSendText);
  640. persistPromptHistoryEntries("/workspace", ["上一条"]);
  641. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  642. expect(typeof submit).toBe("function");
  643. await act(async () => {
  644. (submit as (value: string) => boolean)("失败的消息");
  645. await flushAsyncWork();
  646. });
  647. expect(onSendText).toHaveBeenCalledWith("失败的消息", expectedTelemetrySendOptions());
  648. expect(readPromptHistoryEntries("/workspace")).toEqual(["上一条"]);
  649. await act(async () => {
  650. root.unmount();
  651. });
  652. });
  653. it("keeps the editor draft and prompt history untouched when a product guard blocks send", async () => {
  654. const onSendText = vi.fn(async () => "blocked" as const);
  655. const { root } = renderComposer(onSendText);
  656. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  657. await act(async () => {
  658. (submit as (value: string) => boolean)("/goal 保留这段输入");
  659. await flushAsyncWork();
  660. });
  661. expect(onSendText).toHaveBeenCalledWith("/goal 保留这段输入", expectedTelemetrySendOptions());
  662. expect(inputClear).not.toHaveBeenCalled();
  663. expect(attachmentState.adoptSentAttachments).not.toHaveBeenCalled();
  664. expect(readPromptHistoryEntries("/workspace")).toEqual([]);
  665. expect(readV4ComposerDraft("/workspace", undefined, V4_DRAFT_SCOPE_ROOT)?.text).toBe(
  666. "/goal 保留这段输入",
  667. );
  668. await act(async () => {
  669. root.unmount();
  670. });
  671. });
  672. it("opens paused-queue confirmation without adopting the draft or prompt history", async () => {
  673. const onSendText = vi.fn(async () => "confirmationRequired" as const);
  674. const { root } = renderComposer(onSendText);
  675. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  676. await act(async () => {
  677. (submit as (value: string) => boolean)("等待确认的消息");
  678. await flushAsyncWork();
  679. });
  680. expect(dialogOpenStates.at(-1)).toBe(true);
  681. expect(inputClear).not.toHaveBeenCalled();
  682. expect(attachmentState.adoptSentAttachments).not.toHaveBeenCalled();
  683. expect(readPromptHistoryEntries("/workspace")).toEqual([]);
  684. expect(readV4ComposerDraft("/workspace", undefined, V4_DRAFT_SCOPE_ROOT)?.text).toBe(
  685. "等待确认的消息",
  686. );
  687. await act(async () => root.unmount());
  688. });
  689. it("does not persist a consecutive duplicate after trimming outer whitespace", async () => {
  690. const onSendText = vi.fn(async () => {});
  691. const { root } = renderComposer(onSendText);
  692. const firstSubmit = chatPromptEditorProps.at(-1)?.onSubmit;
  693. await act(async () => {
  694. (firstSubmit as (value: string) => boolean)("重复消息");
  695. await flushAsyncWork();
  696. });
  697. const setItem = vi.mocked(window.localStorage.setItem);
  698. setItem.mockClear();
  699. const duplicateSubmit = chatPromptEditorProps.at(-1)?.onSubmit;
  700. await act(async () => {
  701. (duplicateSubmit as (value: string) => boolean)(" 重复消息 ");
  702. await flushAsyncWork();
  703. });
  704. expect(onSendText).toHaveBeenNthCalledWith(2, "重复消息", expectedTelemetrySendOptions());
  705. expect(readPromptHistoryEntries("/workspace")).toEqual(["重复消息"]);
  706. expect(setItem).not.toHaveBeenCalled();
  707. await act(async () => {
  708. root.unmount();
  709. });
  710. });
  711. it("does not write or roll back history when a consecutive duplicate send fails", async () => {
  712. const onSendText = vi
  713. .fn<() => Promise<void>>()
  714. .mockResolvedValueOnce()
  715. .mockRejectedValueOnce(new Error("send failed"));
  716. const { root } = renderComposer(onSendText);
  717. const firstSubmit = chatPromptEditorProps.at(-1)?.onSubmit;
  718. await act(async () => {
  719. (firstSubmit as (value: string) => boolean)("重复消息");
  720. await flushAsyncWork();
  721. });
  722. const setItem = vi.mocked(window.localStorage.setItem);
  723. setItem.mockClear();
  724. const duplicateSubmit = chatPromptEditorProps.at(-1)?.onSubmit;
  725. await act(async () => {
  726. (duplicateSubmit as (value: string) => boolean)("重复消息");
  727. await flushAsyncWork();
  728. });
  729. expect(readPromptHistoryEntries("/workspace")).toEqual(["重复消息"]);
  730. expect(setItem).not.toHaveBeenCalledWith(
  731. getPromptHistoryStorageKey("/workspace"),
  732. expect.any(String),
  733. );
  734. await act(async () => {
  735. root.unmount();
  736. });
  737. });
  738. it("does not restore the submitted draft while the composer is promoted to a session", async () => {
  739. let resolveSend: (() => void) | undefined;
  740. const onSendText = vi.fn(
  741. () =>
  742. new Promise<void>((resolve) => {
  743. resolveSend = resolve;
  744. }),
  745. );
  746. const { rerenderSession, root } = renderComposer(onSendText);
  747. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  748. await act(async () => {
  749. (submit as (value: string) => boolean)("首条消息");
  750. await flushAsyncWork();
  751. });
  752. rerenderSession("session-1");
  753. expect(readV4ComposerDraft("/workspace", undefined, V4_DRAFT_SCOPE_ROOT)).toBeNull();
  754. await act(async () => {
  755. resolveSend?.();
  756. await flushAsyncWork();
  757. });
  758. expect(readV4ComposerDraft("/workspace", undefined, V4_DRAFT_SCOPE_ROOT)).toBeNull();
  759. await act(async () => {
  760. root.unmount();
  761. });
  762. });
  763. });
  764. // ── R3A-B-07:ACK 丢失 + 断连期间 composer 卸载重挂后的结算 ──
  765. const REMOUNT_SESSION_ID = "sess_remount";
  766. const REMOUNT_COMMAND_ID = "cmd_remount_1";
  767. const REMOUNT_TEXT = "E2E_R3_ACK_LOSS_ACK 请回复";
  768. function authoritativeSnapshot(): ConversationSnapshot {
  769. return {
  770. sessionId: REMOUNT_SESSION_ID,
  771. queue: { items: [] },
  772. rows: {
  773. window: [
  774. {
  775. kind: "userInput",
  776. rowId: "row-1",
  777. sourceCommandId: REMOUNT_COMMAND_ID,
  778. text: REMOUNT_TEXT,
  779. },
  780. ],
  781. },
  782. } as unknown as ConversationSnapshot;
  783. }
  784. /** 测试自持的草稿对象,等价于 useDraftConfigControl 持有并跨组件实例存活的 composerDraft。 */
  785. function createDraftOwner() {
  786. const owner = {
  787. draft: { text: "", updatedAt: 0 } as V4ComposerDraft,
  788. writes: [] as string[],
  789. update(content: Pick<V4ComposerDraft, "text" | "editorStateJson" | "mention">) {
  790. owner.draft = { ...owner.draft, editorStateJson: undefined, mention: undefined, ...content };
  791. owner.writes.push(content.text);
  792. },
  793. };
  794. return owner;
  795. }
  796. function mountRemountSession(
  797. onSendText: (text: string, options?: unknown) => Promise<void>,
  798. owner: ReturnType<typeof createDraftOwner>,
  799. existingContainer?: Element,
  800. ) {
  801. const container = existingContainer ?? installMinimalDom();
  802. const root: Root = createRoot(container);
  803. act(() => {
  804. root.render(
  805. renderComposerElement(
  806. onSendText,
  807. REMOUNT_SESSION_ID,
  808. undefined,
  809. undefined,
  810. undefined,
  811. owner.draft,
  812. (content) => owner.update(content),
  813. ),
  814. );
  815. });
  816. return { root, container };
  817. }
  818. /** onSendText 先回报 commandId,再挂起等待测试决定传输结果。 */
  819. function makePendingSend() {
  820. let reject: (error: Error) => void = () => {};
  821. const pending = new Promise<void>((_resolve, rej) => {
  822. reject = rej;
  823. });
  824. const onSendText = vi.fn(async (_text: string, options?: unknown) => {
  825. (options as { onCommandCreated?: (id: string) => void }).onCommandCreated?.(REMOUNT_COMMAND_ID);
  826. await pending;
  827. });
  828. return { onSendText, reject };
  829. }
  830. async function typeAndSubmitRemountText(text = REMOUNT_TEXT) {
  831. const props = chatPromptEditorProps.at(-1)!;
  832. await act(async () => {
  833. (props.onChange as (value: string) => void)(text);
  834. });
  835. await act(async () => {
  836. (props.onSubmit as (value: string) => boolean)(text);
  837. await flushAsyncWork();
  838. });
  839. }
  840. /** 模拟远端 ChannelClient.dispose() 拒绝在途 RPC。 */
  841. async function closeTransport(reject: (error: Error) => void) {
  842. await act(async () => {
  843. const error = new Error("ChannelClient disposed");
  844. error.name = "ConnectionClosed";
  845. reject(error);
  846. await flushAsyncWork();
  847. });
  848. }
  849. async function applyAuthoritativeSnapshot() {
  850. await act(async () => {
  851. pendingCommandRegistry.reconcileSnapshot(authoritativeSnapshot());
  852. await flushAsyncWork();
  853. });
  854. }
  855. async function submitAndLoseTransport() {
  856. const owner = createDraftOwner();
  857. const { onSendText, reject } = makePendingSend();
  858. const { root, container } = mountRemountSession(onSendText, owner);
  859. await typeAndSubmitRemountText();
  860. expect(onSendText).toHaveBeenCalledTimes(1);
  861. // claimSubmittedDraft:草稿 store 先被占用清空。
  862. expect(owner.writes.at(-1)).toBe("");
  863. await closeTransport(reject);
  864. // catch → restoreSubmittedDraft:正文写回草稿 store,编辑器未清空。
  865. expect(owner.writes.at(-1)).toBe(REMOUNT_TEXT);
  866. expect(inputClear).not.toHaveBeenCalled();
  867. return { owner, root, container };
  868. }
  869. describe("ConversationComposer settles submissions across pane remount (R3A-B-07)", () => {
  870. it("对照:composer 保持挂载时,传输关闭后权威投影仍能清空正文", async () => {
  871. const { owner, root } = await submitAndLoseTransport();
  872. await applyAuthoritativeSnapshot();
  873. expect(inputClear).toHaveBeenCalledTimes(1);
  874. expect(owner.writes.at(-1)).toBe("");
  875. await act(async () => root.unmount());
  876. });
  877. it("断连期间卸载重挂后,权威投影到达时清空回填的正文与草稿", async () => {
  878. const { owner, root, container } = await submitAndLoseTransport();
  879. // 断连:V4PaneConversationProvider rpcReady=false 返回 null → SessionPane/composer 卸载。
  880. await act(async () => root.unmount());
  881. inputClear.mockClear();
  882. inputSetText.mockClear();
  883. // 重连:重挂载,正文从草稿 store 回填到编辑器。
  884. const { root: remounted } = mountRemountSession(
  885. vi.fn(async () => {}),
  886. owner,
  887. container,
  888. );
  889. await act(async () => {
  890. await flushAsyncWork();
  891. });
  892. expect(inputSetText).toHaveBeenCalledWith(REMOUNT_TEXT);
  893. await applyAuthoritativeSnapshot();
  894. expect(inputClear).toHaveBeenCalledTimes(1);
  895. expect(owner.draft.text).toBe("");
  896. await act(async () => remounted.unmount());
  897. });
  898. it("权威投影先于重挂到达时,重挂后的 composer 同步清空回填正文", async () => {
  899. const { owner, root, container } = await submitAndLoseTransport();
  900. await act(async () => root.unmount());
  901. await applyAuthoritativeSnapshot();
  902. inputClear.mockClear();
  903. const { root: remounted } = mountRemountSession(
  904. vi.fn(async () => {}),
  905. owner,
  906. container,
  907. );
  908. await act(async () => {
  909. await flushAsyncWork();
  910. });
  911. expect(inputClear).toHaveBeenCalledTimes(1);
  912. expect(owner.draft.text).toBe("");
  913. await act(async () => remounted.unmount());
  914. });
  915. it("重挂后用户已修改正文时,迟到的权威投影不得清空新输入", async () => {
  916. const { owner, root, container } = await submitAndLoseTransport();
  917. await act(async () => root.unmount());
  918. inputClear.mockClear();
  919. const { root: remounted } = mountRemountSession(
  920. vi.fn(async () => {}),
  921. owner,
  922. container,
  923. );
  924. await act(async () => {
  925. await flushAsyncWork();
  926. });
  927. const props = chatPromptEditorProps.at(-1)!;
  928. await act(async () => {
  929. (props.onChange as (value: string) => void)(`${REMOUNT_TEXT} 补充`);
  930. });
  931. await applyAuthoritativeSnapshot();
  932. expect(inputClear).not.toHaveBeenCalled();
  933. expect(owner.draft.text).toBe(`${REMOUNT_TEXT} 补充`);
  934. await act(async () => remounted.unmount());
  935. });
  936. it("命令以失败终态收口时,重挂后的 composer 保留正文供用户重试", async () => {
  937. const envelope = {
  938. commandId: REMOUNT_COMMAND_ID,
  939. clientId: "client-1",
  940. sessionId: REMOUNT_SESSION_ID,
  941. type: "sendText",
  942. payload: { text: REMOUNT_TEXT },
  943. issuedAt: Date.now(),
  944. } as unknown as CommandEnvelope;
  945. pendingCommandRegistry.record(envelope);
  946. const { owner, root, container } = await submitAndLoseTransport();
  947. await act(async () => root.unmount());
  948. inputClear.mockClear();
  949. const { root: remounted } = mountRemountSession(
  950. vi.fn(async () => {}),
  951. owner,
  952. container,
  953. );
  954. await act(async () => {
  955. await flushAsyncWork();
  956. });
  957. await act(async () => {
  958. pendingCommandRegistry.applyAck(envelope, {
  959. commandId: REMOUNT_COMMAND_ID,
  960. status: "failed",
  961. reasonCode: "guard.rejected",
  962. revisionAtDecision: 1,
  963. } as unknown as CommandAck);
  964. await flushAsyncWork();
  965. });
  966. expect(inputClear).not.toHaveBeenCalled();
  967. expect(owner.draft.text).toBe(REMOUNT_TEXT);
  968. await act(async () => remounted.unmount());
  969. });
  970. });
  971. // 冲突整合回归:projection 已接管提交后,附件 adoption 尚在等待时的传输失败
  972. // 不能再恢复旧正文,否则 accepted 输入会重新出现在待发草稿中。
  973. it("权威投影开始接管附件后,传输失败不能恢复已提交正文", async () => {
  974. let completeAdoption = () => {};
  975. attachmentState.adoptSentAttachments.mockImplementationOnce(
  976. () =>
  977. new Promise<void>((resolve) => {
  978. completeAdoption = resolve;
  979. }),
  980. );
  981. const owner = createDraftOwner();
  982. const { onSendText, reject } = makePendingSend();
  983. const { root } = mountRemountSession(onSendText, owner);
  984. await typeAndSubmitRemountText();
  985. await applyAuthoritativeSnapshot();
  986. expect(attachmentState.adoptSentAttachments).toHaveBeenCalledOnce();
  987. await closeTransport(reject);
  988. try {
  989. expect(owner.draft.text).toBe("");
  990. } finally {
  991. await act(async () => {
  992. completeAdoption();
  993. await flushAsyncWork();
  994. root.unmount();
  995. });
  996. }
  997. });