v4ConversationRowViewUserEdit.test.ts 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295
  1. import { act, createElement, type ReactElement } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { FileClockIcon } from "lucide-react";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. TID_V4_EDIT,
  7. TID_V4_EDIT_ATTACHMENT_REMOVE,
  8. TID_V4_EDIT_REWIND_WORKSPACE,
  9. TID_V4_FEEDBACK_DISLIKE,
  10. TID_V4_FEEDBACK_LIKE,
  11. testId,
  12. } from "@zcode/shared/test-ids";
  13. import type { AssistantTextRow, ReasoningRow, UserInputRow } from "@zcode/shared/zcode-protocol-v4";
  14. import type { CodeCommentComposerAttachment } from "@/lib/codeCommentContext.js";
  15. import { DEFAULT_CODE_PREVIEW_SETTINGS } from "@/lib/codePreviewSettings.js";
  16. import type { ConversationSelectionReference } from "@/lib/conversationSelectionReference.js";
  17. import type { PptxElementReference } from "@/lib/pptxElementReference.js";
  18. import {
  19. buildPromptWithWebElementContexts,
  20. type WebElementContextComposerAttachment,
  21. } from "@/lib/webElementContext.js";
  22. import { ConversationRowView } from "@/v4/ConversationRowView.js";
  23. import type { ConversationRowRenderContext } from "@/v4/conversationRowContext.js";
  24. import { serializeComposerPromptContexts } from "@/v4/composer/composerPromptContexts.js";
  25. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  26. const {
  27. attachmentPropsById,
  28. attachmentRemovePropsByTestId,
  29. chatPromptEditorProps,
  30. fileRewindDialogProps,
  31. hoverCardContentProps,
  32. imagePreviewDialogProps,
  33. messageActionPropsByTestId,
  34. messageResponseProps,
  35. reasoningTriggerProps,
  36. } = vi.hoisted(() => ({
  37. attachmentPropsById: new Map<string, Record<string, unknown>>(),
  38. attachmentRemovePropsByTestId: new Map<string, Record<string, unknown>>(),
  39. chatPromptEditorProps: [] as Array<Record<string, unknown>>,
  40. fileRewindDialogProps: [] as Array<Record<string, unknown>>,
  41. hoverCardContentProps: [] as Array<Record<string, unknown>>,
  42. imagePreviewDialogProps: [] as Array<Record<string, unknown>>,
  43. messageActionPropsByTestId: new Map<string, Record<string, unknown>>(),
  44. messageResponseProps: [] as Array<Record<string, unknown>>,
  45. reasoningTriggerProps: [] as Array<Record<string, unknown>>,
  46. }));
  47. vi.mock("@/components/ai-elements/image-preview-dialog.js", () => ({
  48. ImagePreviewDialog: (props: Record<string, unknown>) => {
  49. imagePreviewDialogProps.push(props);
  50. return null;
  51. },
  52. }));
  53. vi.mock("@/prompt-editor/ChatPromptEditor.js", async () => {
  54. const React = await import("react");
  55. return {
  56. ChatPromptEditor: (props: Record<string, unknown>) => {
  57. chatPromptEditorProps.push(props);
  58. return React.createElement(
  59. "form",
  60. { "data-testid": "mock-v4-user-edit-editor" },
  61. props.topContent as React.ReactNode,
  62. );
  63. },
  64. };
  65. });
  66. vi.mock("@/v4/ConversationFileRewindDialog.js", () => ({
  67. ConversationFileRewindDialog: (props: Record<string, unknown>) => {
  68. fileRewindDialogProps.push(props);
  69. return null;
  70. },
  71. }));
  72. vi.mock("@/components/ai-elements/attachments.js", async () => {
  73. const React = await import("react");
  74. const RemoveContext = React.createContext<(() => void) | undefined>(undefined);
  75. const Passthrough = ({ children, ...props }: { children?: React.ReactNode }) =>
  76. React.createElement("div", props, children);
  77. const Attachment = ({
  78. children,
  79. onRemove,
  80. data,
  81. variant: _variant,
  82. ...props
  83. }: {
  84. children?: React.ReactNode;
  85. onRemove?: () => void;
  86. data?: { id?: string };
  87. variant?: string;
  88. }) => {
  89. if (data?.id) {
  90. attachmentPropsById.set(data.id, {
  91. ...props,
  92. data,
  93. onRemove,
  94. variant: _variant,
  95. });
  96. }
  97. return React.createElement(
  98. RemoveContext.Provider,
  99. { value: onRemove },
  100. React.createElement("div", props, children),
  101. );
  102. };
  103. const AttachmentRemove = ({ alwaysVisible, label, ...props }: Record<string, unknown>) => {
  104. const onRemove = React.useContext(RemoveContext);
  105. const testIdValue = props["data-testid"];
  106. if (typeof testIdValue === "string") {
  107. attachmentRemovePropsByTestId.set(testIdValue, {
  108. ...props,
  109. alwaysVisible,
  110. label,
  111. onClick: onRemove,
  112. });
  113. }
  114. return React.createElement("button", { ...props, onClick: onRemove }, label);
  115. };
  116. const Trigger = ({ children }: { children?: React.ReactNode }) =>
  117. React.createElement(React.Fragment, null, children);
  118. const HoverCard = ({ children }: { children?: React.ReactNode }) =>
  119. React.createElement(React.Fragment, null, children);
  120. const HoverCardContent = ({ children, ...props }: { children?: React.ReactNode }) => {
  121. hoverCardContentProps.push(props);
  122. return React.createElement("div", props, children);
  123. };
  124. const Span = (props: Record<string, unknown>) => React.createElement("span", props);
  125. return {
  126. Attachment,
  127. AttachmentHoverCard: HoverCard,
  128. AttachmentHoverCardContent: HoverCardContent,
  129. AttachmentHoverCardTrigger: Trigger,
  130. AttachmentInfo: Span,
  131. AttachmentPreview: Span,
  132. AttachmentRemove,
  133. Attachments: Passthrough,
  134. };
  135. });
  136. vi.mock("@/components/ai-elements/message.js", async () => {
  137. const React = await import("react");
  138. return {
  139. MessageAction: ({
  140. children,
  141. label,
  142. tooltip,
  143. ...props
  144. }: {
  145. children?: React.ReactNode;
  146. label?: string;
  147. tooltip?: string;
  148. } & Record<string, unknown>) => {
  149. const testIdValue = props["data-testid"];
  150. if (typeof testIdValue === "string") {
  151. messageActionPropsByTestId.set(testIdValue, {
  152. ...props,
  153. label,
  154. tooltip,
  155. });
  156. }
  157. return React.createElement(
  158. "button",
  159. props,
  160. children,
  161. React.createElement("span", null, label ?? tooltip),
  162. );
  163. },
  164. MessageActions: ({ children, ...props }: { children?: React.ReactNode }) =>
  165. React.createElement("div", props, children),
  166. MessageResponse: ({
  167. children,
  168. ...props
  169. }: {
  170. children?: React.ReactNode;
  171. } & Record<string, unknown>) => {
  172. messageResponseProps.push(props);
  173. return React.createElement("div", null, children);
  174. },
  175. };
  176. });
  177. vi.mock("@/components/ai-elements/reasoning.js", async () => {
  178. const React = await import("react");
  179. const Passthrough = ({ children }: { children?: React.ReactNode }) =>
  180. React.createElement("div", null, children);
  181. return {
  182. Reasoning: Passthrough,
  183. ReasoningContent: Passthrough,
  184. ReasoningTrigger: (props: Record<string, unknown>) => {
  185. reasoningTriggerProps.push(props);
  186. return React.createElement("div", null, props.children as React.ReactNode);
  187. },
  188. };
  189. });
  190. vi.mock("@/ToolCallBlocks.js", async () => {
  191. const React = await import("react");
  192. return {
  193. ToolCallBlock: () => React.createElement("div", { "data-testid": "mock-tool-call" }),
  194. };
  195. });
  196. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  197. const element = {
  198. addEventListener: () => {},
  199. appendChild: (child: Node) => {
  200. Object.assign(child, { parentNode: element });
  201. element.childNodes.push(child);
  202. return child;
  203. },
  204. childNodes: [] as Node[],
  205. getAttribute: (name: string) => element.attributes.get(name) ?? null,
  206. insertBefore: (child: Node, beforeChild?: Node | null) => {
  207. Object.assign(child, { parentNode: element });
  208. const beforeIndex = beforeChild ? element.childNodes.indexOf(beforeChild) : -1;
  209. if (beforeIndex >= 0) {
  210. element.childNodes.splice(beforeIndex, 0, child);
  211. } else {
  212. element.childNodes.push(child);
  213. }
  214. return child;
  215. },
  216. attributes: new Map<string, string>(),
  217. nodeName: tagName.toUpperCase(),
  218. nodeType: 1,
  219. ownerDocument,
  220. parentNode: null as Node | null,
  221. removeAttribute: (name: string) => {
  222. element.attributes.delete(name);
  223. },
  224. removeChild: (child: Node) => {
  225. element.childNodes = element.childNodes.filter((item) => item !== child);
  226. Object.assign(child, { parentNode: null });
  227. return child;
  228. },
  229. removeEventListener: () => {},
  230. setAttribute: (name: string, value: string) => {
  231. element.attributes.set(name, String(value));
  232. },
  233. style: {},
  234. tagName: tagName.toUpperCase(),
  235. };
  236. return element as unknown as Element;
  237. }
  238. function installMinimalDom() {
  239. const documentMock = {
  240. addEventListener: () => {},
  241. createComment: (nodeValue: string) => ({
  242. nodeType: 8,
  243. nodeValue,
  244. parentNode: null,
  245. }),
  246. createElement: (tagName: string) =>
  247. createMinimalElement(documentMock as unknown as Document, tagName),
  248. createElementNS: (_namespace: string, tagName: string) =>
  249. createMinimalElement(documentMock as unknown as Document, tagName),
  250. createTextNode: (nodeValue: string) => ({
  251. nodeType: 3,
  252. nodeValue,
  253. parentNode: null,
  254. }),
  255. nodeType: 9,
  256. removeEventListener: () => {},
  257. } as unknown as Document & { defaultView?: unknown };
  258. const windowMock = {
  259. addEventListener: () => {},
  260. document: documentMock,
  261. HTMLIFrameElement: function HTMLIFrameElement() {},
  262. HTMLElement: function HTMLElement() {},
  263. Node: function Node() {},
  264. removeEventListener: () => {},
  265. requestAnimationFrame: (callback: FrameRequestCallback) => {
  266. callback(0);
  267. return 0;
  268. },
  269. };
  270. documentMock.defaultView = windowMock;
  271. Object.defineProperty(globalThis, "document", {
  272. configurable: true,
  273. value: documentMock,
  274. });
  275. Object.defineProperty(globalThis, "window", {
  276. configurable: true,
  277. value: windowMock,
  278. });
  279. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  280. configurable: true,
  281. value: true,
  282. });
  283. return createMinimalElement(documentMock, "div");
  284. }
  285. function collectText(node: unknown): string {
  286. if (!node || typeof node !== "object") return "";
  287. const candidate = node as {
  288. childNodes?: unknown[];
  289. nodeValue?: string;
  290. textContent?: string;
  291. };
  292. if (typeof candidate.nodeValue === "string") return candidate.nodeValue;
  293. if (candidate.childNodes && candidate.childNodes.length > 0) {
  294. return candidate.childNodes.map((child) => collectText(child)).join("");
  295. }
  296. return typeof candidate.textContent === "string" ? candidate.textContent : "";
  297. }
  298. function collectAttributeValues(node: unknown, attributeName: string): string[] {
  299. if (!node || typeof node !== "object") return [];
  300. const candidate = node as {
  301. attributes?: Map<string, string>;
  302. childNodes?: unknown[];
  303. getAttribute?: (name: string) => string | null;
  304. };
  305. const ownValue =
  306. typeof candidate.getAttribute === "function"
  307. ? candidate.getAttribute(attributeName)
  308. : (candidate.attributes?.get(attributeName) ?? null);
  309. const childValues =
  310. candidate.childNodes?.flatMap((child) => collectAttributeValues(child, attributeName)) ?? [];
  311. return ownValue ? [ownValue, ...childValues] : childValues;
  312. }
  313. function findElementByAttribute(
  314. node: unknown,
  315. attributeName: string,
  316. attributeValue: string,
  317. ): { childNodes?: unknown[]; parentNode?: unknown } | null {
  318. if (!node || typeof node !== "object") return null;
  319. const candidate = node as {
  320. childNodes?: unknown[];
  321. getAttribute?: (name: string) => string | null;
  322. parentNode?: unknown;
  323. };
  324. if (candidate.getAttribute?.(attributeName) === attributeValue) return candidate;
  325. for (const child of candidate.childNodes ?? []) {
  326. const match = findElementByAttribute(child, attributeName, attributeValue);
  327. if (match) return match;
  328. }
  329. return null;
  330. }
  331. const rowContext: ConversationRowRenderContext = {
  332. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  333. messageStreamShowReasoning: true,
  334. sessionId: "session-1",
  335. theme: "system",
  336. workspaceIdentity: "remote:workspace",
  337. workspacePath: "/workspace",
  338. };
  339. function userInputRow(overrides: Partial<UserInputRow> = {}): UserInputRow {
  340. return {
  341. rowId: 42,
  342. entityId: "message-user-42",
  343. turnId: "turn-1",
  344. createdAt: 1_700_000_000_000,
  345. createdAtSeq: 1,
  346. kind: "userInput",
  347. origin: "realUser",
  348. text: "我刚刚说了啥",
  349. attachments: [
  350. {
  351. bytes: 12,
  352. fileName: "note.txt",
  353. mime: "text/plain",
  354. ref: "/workspace/note.txt",
  355. },
  356. ],
  357. ...overrides,
  358. };
  359. }
  360. function assistantTextRow(overrides: Partial<AssistantTextRow> = {}): AssistantTextRow {
  361. return {
  362. rowId: 43,
  363. turnId: "turn-1",
  364. createdAt: 1_700_000_000_001,
  365. createdAtSeq: 2,
  366. kind: "assistantText",
  367. state: "streaming",
  368. text: "正在输出",
  369. ...overrides,
  370. };
  371. }
  372. function reasoningRow(overrides: Partial<ReasoningRow> = {}): ReasoningRow {
  373. return {
  374. rowId: 44,
  375. turnId: "turn-1",
  376. createdAt: 1_700_000_000_002,
  377. createdAtSeq: 3,
  378. kind: "reasoning",
  379. state: "streaming",
  380. text: "正在检查摘要接线",
  381. ...overrides,
  382. };
  383. }
  384. afterEach(() => {
  385. attachmentPropsById.clear();
  386. attachmentRemovePropsByTestId.clear();
  387. chatPromptEditorProps.length = 0;
  388. fileRewindDialogProps.length = 0;
  389. hoverCardContentProps.length = 0;
  390. imagePreviewDialogProps.length = 0;
  391. messageActionPropsByTestId.clear();
  392. messageResponseProps.length = 0;
  393. reasoningTriggerProps.length = 0;
  394. vi.restoreAllMocks();
  395. delete (globalThis as { document?: unknown }).document;
  396. delete (globalThis as { window?: unknown }).window;
  397. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  398. });
  399. describe("ConversationRowView reasoning summary", () => {
  400. it("opens topic history from the owning transport only after clicking the attachment", async () => {
  401. const readAttachment = vi.fn(async () => ({
  402. bytes: new TextEncoder().encode("Alice | ou_a\nOriginal history"),
  403. mediaType: "text/plain",
  404. }));
  405. const row = userInputRow({
  406. attachments: [
  407. {
  408. ref: "zcode-artifact://history",
  409. fileName: "topic-history.txt",
  410. mime: "text/plain",
  411. bytes: 30,
  412. sourceKind: "topic-history",
  413. messageCount: 2,
  414. },
  415. ],
  416. });
  417. const root = createRoot(installMinimalDom());
  418. await act(async () => {
  419. root.render(
  420. createElement(
  421. ZCodeIntlProvider,
  422. { initialLocale: "zh-CN" },
  423. createElement(ConversationRowView, { context: { ...rowContext, readAttachment }, row }),
  424. ),
  425. );
  426. });
  427. expect(readAttachment).not.toHaveBeenCalled();
  428. const props = attachmentPropsById.get(`${row.rowId}-0`)!;
  429. expect(props.onOpen).toBeTypeOf("function");
  430. await act(async () => {
  431. await (props.onOpen as () => Promise<void>)();
  432. });
  433. expect(readAttachment).toHaveBeenCalledWith(
  434. expect.objectContaining({ sessionId: "session-1", ref: "zcode-artifact://history" }),
  435. );
  436. await act(async () => root.unmount());
  437. });
  438. it("forwards streaming reasoning text to the collapsed summary trigger", async () => {
  439. const root: Root = createRoot(installMinimalDom());
  440. const row = reasoningRow();
  441. await act(async () => {
  442. root.render(
  443. createElement(
  444. ZCodeIntlProvider,
  445. { initialLocale: "zh-CN" },
  446. createElement(ConversationRowView, { context: rowContext, row }),
  447. ),
  448. );
  449. });
  450. expect(reasoningTriggerProps).toHaveLength(1);
  451. expect(reasoningTriggerProps[0]?.streamingText).toBe(row.text);
  452. await act(async () => root.unmount());
  453. });
  454. });
  455. describe("ConversationRowView user query editing", () => {
  456. it.each([false, true])(
  457. "renders topic originals separately (mobile=%s)",
  458. async (compactForRemoteControl) => {
  459. const container = installMinimalDom();
  460. const root = createRoot(container);
  461. const row = userInputRow({
  462. text: "combined execution payload",
  463. botGroupSource: {
  464. provider: "feishu",
  465. botId: "bot",
  466. chatId: "chat",
  467. threadId: "topic",
  468. senderId: "b",
  469. senderName: "乙",
  470. messageId: "b",
  471. messages: [
  472. {
  473. messageId: "a",
  474. senderId: "a",
  475. senderName: "甲",
  476. text: "第一条需求",
  477. attachmentIndexes: [],
  478. conversationQuotes: [{ text: "根原文" }],
  479. },
  480. {
  481. messageId: "b",
  482. senderId: "b",
  483. senderName: "乙",
  484. text: "第二条补充",
  485. attachmentIndexes: [],
  486. },
  487. ],
  488. },
  489. });
  490. await act(async () => {
  491. root.render(
  492. createElement(
  493. ZCodeIntlProvider,
  494. { initialLocale: "zh-CN" },
  495. createElement(ConversationRowView, {
  496. context: { ...rowContext, compactForRemoteControl },
  497. row,
  498. }),
  499. ),
  500. );
  501. });
  502. const first = findElementByAttribute(container, "data-topic-message-id", "a");
  503. const second = findElementByAttribute(container, "data-topic-message-id", "b");
  504. expect(first).not.toBeNull();
  505. expect(second).not.toBeNull();
  506. expect(collectText(first)).toContain("第一条需求");
  507. expect(collectText(first)).toContain("甲");
  508. expect(collectText(second)).toContain("第二条补充");
  509. expect(collectText(second)).toContain("乙");
  510. expect(findElementByAttribute(first, "data-v4-user-input-quotes", "true")).not.toBeNull();
  511. expect(findElementByAttribute(second, "data-v4-user-input-quotes", "true")).toBeNull();
  512. expect(collectText(container)).not.toContain("combined execution payload");
  513. await act(async () => root.unmount());
  514. },
  515. );
  516. it("orders group sender, quote and attachments without an invented message bubble", async () => {
  517. const container = installMinimalDom();
  518. const root = createRoot(container);
  519. const row = userInputRow({
  520. text: "",
  521. conversationQuotes: [
  522. {
  523. text: "actual quoted request",
  524. senderName: "Ryan Bot",
  525. senderId: "ou_bot",
  526. sentAt: "2026-09-09T10:32:44+08:00",
  527. },
  528. ],
  529. botGroupSource: {
  530. provider: "feishu",
  531. botId: "bot",
  532. chatId: "chat",
  533. senderId: "member",
  534. senderName: "测试成员",
  535. messageId: "message",
  536. },
  537. });
  538. await act(async () => {
  539. root.render(
  540. createElement(
  541. ZCodeIntlProvider,
  542. { initialLocale: "zh-CN" },
  543. createElement(ConversationRowView, { context: rowContext, row }),
  544. ),
  545. );
  546. });
  547. const source = findElementByAttribute(container, "data-v4-user-input-source", "true");
  548. const area = findElementByAttribute(container, "data-v4-user-input-attachments", "true");
  549. const quotes = findElementByAttribute(container, "data-v4-user-input-quotes", "true");
  550. expect(source).not.toBeNull();
  551. expect(quotes).not.toBeNull();
  552. const siblings = [...source!.parentNode.childNodes];
  553. expect(siblings.indexOf(source)).toBeLessThan(siblings.indexOf(area));
  554. expect([...area!.childNodes][0]).toBe(quotes);
  555. expect(findElementByAttribute(container, "data-v4-user-input-bubble", "true")).toBeNull();
  556. await act(async () => root.unmount());
  557. });
  558. it.each([
  559. {
  560. label: "scheduled automation prompt",
  561. sourceCommandId: "automation-1:1700000000000",
  562. visible: true,
  563. },
  564. {
  565. label: "manual automation prompt",
  566. sourceCommandId: "automation-1:manual:run-1",
  567. visible: true,
  568. },
  569. { label: "ordinary prompt", sourceCommandId: "command-1", visible: false },
  570. ])("shows the scheduled-task origin only for $label", async ({ sourceCommandId, visible }) => {
  571. const container = installMinimalDom();
  572. const root: Root = createRoot(container);
  573. await act(async () => {
  574. root.render(
  575. createElement(
  576. ZCodeIntlProvider,
  577. { initialLocale: "zh-CN" },
  578. createElement(ConversationRowView, {
  579. context: rowContext,
  580. row: userInputRow({ sourceCommandId }),
  581. }),
  582. ),
  583. );
  584. });
  585. const origin = findElementByAttribute(
  586. container,
  587. "data-v4-user-input-automation-origin",
  588. "schedule",
  589. );
  590. expect(Boolean(origin)).toBe(visible);
  591. if (origin) {
  592. expect(collectText(origin)).toBe("由定时任务发送");
  593. expect(findElementByAttribute(origin, "data-cron-task-icon", "true")).not.toBeNull();
  594. }
  595. await act(async () => root.unmount());
  596. });
  597. it.each([
  598. {
  599. label: "attachments and text",
  600. text: "解释附件",
  601. attachments: userInputRow().attachments,
  602. bubble: true,
  603. },
  604. {
  605. label: "attachments only",
  606. text: "",
  607. attachments: userInputRow().attachments,
  608. bubble: false,
  609. },
  610. { label: "text only", text: "只有文字", attachments: [], bubble: true },
  611. ])("renders the user message layout for $label", async ({ text, attachments, bubble }) => {
  612. const container = installMinimalDom();
  613. const root: Root = createRoot(container);
  614. await act(async () => {
  615. root.render(
  616. createElement(
  617. ZCodeIntlProvider,
  618. { initialLocale: "zh-CN" },
  619. createElement(ConversationRowView, {
  620. context: rowContext,
  621. row: userInputRow({ text, attachments }),
  622. }),
  623. ),
  624. );
  625. });
  626. const attachmentArea = findElementByAttribute(
  627. container,
  628. "data-v4-user-input-attachments",
  629. "true",
  630. );
  631. const messageBubble = findElementByAttribute(container, "data-v4-user-input-bubble", "true");
  632. expect(Boolean(attachmentArea)).toBe(attachments.length > 0);
  633. expect(Boolean(messageBubble)).toBe(bubble);
  634. if (attachmentArea && messageBubble) {
  635. expect(attachmentArea.parentNode).toBe(messageBubble.parentNode);
  636. const siblings = attachmentArea.parentNode as {
  637. childNodes?: unknown[];
  638. };
  639. expect(siblings.childNodes?.indexOf(attachmentArea)).toBeLessThan(
  640. siblings.childNodes?.indexOf(messageBubble) ?? -1,
  641. );
  642. }
  643. await act(async () => root.unmount());
  644. });
  645. it("renders sent file attachments with their icon and filename", async () => {
  646. const container = installMinimalDom();
  647. const root: Root = createRoot(container);
  648. await act(async () => {
  649. root.render(
  650. createElement(
  651. ZCodeIntlProvider,
  652. { initialLocale: "zh-CN" },
  653. createElement(ConversationRowView, {
  654. context: rowContext,
  655. row: userInputRow({ text: "" }),
  656. }),
  657. ),
  658. );
  659. });
  660. const pill = findElementByAttribute(container, "data-v4-user-input-attachment-pill", "true");
  661. expect(pill).not.toBeNull();
  662. expect(collectText(pill)).toBe("note.txt");
  663. expect(collectAttributeValues(pill, "src").some((src) => src.endsWith(".svg"))).toBe(true);
  664. await act(async () => root.unmount());
  665. });
  666. it("renders image thumbnails above ordered file and context pills", async () => {
  667. const context: WebElementContextComposerAttachment = {
  668. capturedAt: 1_700_000_000_000,
  669. id: "element-1",
  670. pageTitle: "Docs",
  671. pageUrl: "https://example.test/docs",
  672. tagName: "button",
  673. text: "Submit",
  674. workspacePath: "/workspace",
  675. };
  676. const readAttachment = vi.fn().mockResolvedValue({
  677. bytes: new Uint8Array([137, 80, 78, 71]),
  678. mediaType: "image/png",
  679. });
  680. vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:sent-thumbnail");
  681. vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
  682. const comment: CodeCommentComposerAttachment = {
  683. id: "comment-1",
  684. workspacePath: "/workspace",
  685. sourcePath: "/workspace/app.ts",
  686. sourceTitle: "app.ts",
  687. selectedText: "const value = 1",
  688. comment: "检查这里",
  689. startLine: 1,
  690. endLine: 1,
  691. };
  692. const pptxElement: PptxElementReference = {
  693. id: "pptx-1",
  694. workspacePath: "/workspace",
  695. sourcePath: "/workspace/deck.pptx",
  696. sourceTitle: "deck.pptx",
  697. sourceFingerprint: `sha256:${"a".repeat(64)}`,
  698. slideIndex: 0,
  699. slidePart: "ppt/slides/slide1.xml",
  700. nodeId: "7",
  701. nodeName: "Title",
  702. nodeType: "shape",
  703. bounds: { x: 0, y: 0, width: 100, height: 30 },
  704. zIndex: 1,
  705. capturedAt: 1,
  706. };
  707. const selection: ConversationSelectionReference = {
  708. id: "selection-1",
  709. sourceSessionId: "source-session",
  710. sourceRowId: 8,
  711. contentType: "assistant",
  712. text: "selected answer",
  713. };
  714. const row = userInputRow({
  715. text: serializeComposerPromptContexts("", {
  716. codeComments: [comment],
  717. conversationSelections: [selection],
  718. pptxElements: [pptxElement],
  719. webElements: [context],
  720. }),
  721. attachments: [
  722. {
  723. ref: "/workspace/shot.png",
  724. fileName: "shot.png",
  725. mime: "image/png",
  726. bytes: 4,
  727. },
  728. {
  729. ref: "/workspace/demo.mov",
  730. fileName: "demo.mov",
  731. mime: "video/quicktime",
  732. bytes: 8,
  733. },
  734. {
  735. ref: "/workspace/note.txt",
  736. fileName: "note.txt",
  737. mime: "text/plain",
  738. bytes: 4,
  739. },
  740. ],
  741. });
  742. const container = installMinimalDom();
  743. const root: Root = createRoot(container);
  744. await act(async () => {
  745. root.render(
  746. createElement(
  747. ZCodeIntlProvider,
  748. { initialLocale: "zh-CN" },
  749. createElement(ConversationRowView, {
  750. context: { ...rowContext, readAttachment },
  751. row,
  752. }),
  753. ),
  754. );
  755. await Promise.resolve();
  756. await Promise.resolve();
  757. });
  758. const attachmentArea = findElementByAttribute(
  759. container,
  760. "data-v4-user-input-attachments",
  761. "true",
  762. );
  763. const imageRow = findElementByAttribute(
  764. attachmentArea,
  765. "data-v4-user-input-media-attachments",
  766. "true",
  767. );
  768. const pillRow = findElementByAttribute(
  769. attachmentArea,
  770. "data-v4-user-input-attachment-pills",
  771. "true",
  772. );
  773. const image = findElementByAttribute(imageRow, "data-v4-user-input-media-attachment", "true");
  774. // findElementByAttribute 只返回首个匹配;media 行内还有视频卡,按子节点序取第二个。
  775. const mediaCards = [...(imageRow as { childNodes?: unknown[] }).childNodes!].filter(
  776. (child) =>
  777. typeof child === "object" &&
  778. child !== null &&
  779. "getAttribute" in child &&
  780. (child as { getAttribute(name: string): string | null }).getAttribute(
  781. "data-v4-user-input-media-attachment",
  782. ) === "true",
  783. );
  784. const video = mediaCards[1] ?? null;
  785. const file = findElementByAttribute(pillRow, "data-v4-user-input-attachment-pill", "true");
  786. const web = findElementByAttribute(pillRow, "aria-label", "1 个网页元素");
  787. const codeComment = findElementByAttribute(pillRow, "aria-label", "1 条评论");
  788. const pptx = findElementByAttribute(pillRow, "aria-label", "1 个幻灯片元素");
  789. const conversation = findElementByAttribute(pillRow, "aria-label", "1 条对话引用");
  790. expect(imageRow?.parentNode).toBe(attachmentArea);
  791. expect(pillRow?.parentNode).toBe(attachmentArea);
  792. expect(image?.parentNode).toBe(imageRow);
  793. expect(video?.parentNode).toBe(imageRow);
  794. expect(file?.parentNode).toBe(pillRow);
  795. // 媒体行内按添加顺序混排图片与视频;视频不进入文件 pill 行。
  796. const mediaChildren = (imageRow as { childNodes?: unknown[] }).childNodes ?? [];
  797. expect(mediaChildren.indexOf(image)).toBeLessThan(mediaChildren.indexOf(video));
  798. expect(web?.parentNode).toBe(pillRow);
  799. const areaChildren = (attachmentArea as { childNodes?: unknown[] }).childNodes ?? [];
  800. expect(areaChildren.indexOf(imageRow)).toBeLessThan(areaChildren.indexOf(pillRow));
  801. const pillChildren = (pillRow as { childNodes?: unknown[] }).childNodes ?? [];
  802. expect([
  803. pillChildren.indexOf(file),
  804. pillChildren.indexOf(codeComment),
  805. pillChildren.indexOf(web),
  806. pillChildren.indexOf(pptx),
  807. pillChildren.indexOf(conversation),
  808. ]).toEqual(
  809. [...pillChildren]
  810. .map((child, index) => ({ child, index }))
  811. .filter(({ child }) => [file, codeComment, web, pptx, conversation].includes(child))
  812. .map(({ index }) => index),
  813. );
  814. expect(attachmentPropsById.get("42-0")).toMatchObject({
  815. variant: "grid",
  816. data: { url: "blob:sent-thumbnail" },
  817. });
  818. // 可见消息行会读取已发送视频,卡片复用 Blob URL 由无控件 video 展示首帧。
  819. expect(attachmentPropsById.get("42-1")).toMatchObject({
  820. variant: "grid",
  821. data: { url: "blob:sent-thumbnail", filename: "demo.mov" },
  822. });
  823. expect(readAttachment).toHaveBeenCalledWith({
  824. sessionId: "session-1",
  825. ref: "/workspace/demo.mov",
  826. mediaType: "video/quicktime",
  827. target: { rowId: 42, entityId: "message-user-42" },
  828. attachmentIndex: 1,
  829. signal: expect.any(AbortSignal),
  830. });
  831. await act(async () => root.unmount());
  832. });
  833. it("opens sent images with the shared Markdown preview gallery and leaves non-images static", async () => {
  834. const readAttachment = vi.fn().mockResolvedValue({
  835. bytes: new Uint8Array([137, 80, 78, 71]),
  836. mediaType: "image/png",
  837. });
  838. const createObjectUrl = vi
  839. .spyOn(URL, "createObjectURL")
  840. .mockReturnValueOnce("blob:first-preview")
  841. .mockReturnValueOnce("blob:second-preview");
  842. const revokeObjectUrl = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
  843. const row = userInputRow({
  844. attachments: [
  845. {
  846. ref: "/workspace/first.png",
  847. fileName: "first.png",
  848. mime: "image/png",
  849. bytes: 4,
  850. },
  851. {
  852. ref: "/workspace/second.png",
  853. fileName: "second.png",
  854. mime: "image/png",
  855. bytes: 4,
  856. },
  857. {
  858. ref: "/workspace/note.txt",
  859. fileName: "note.txt",
  860. mime: "text/plain",
  861. bytes: 4,
  862. },
  863. ],
  864. });
  865. const root: Root = createRoot(installMinimalDom());
  866. await act(async () => {
  867. root.render(
  868. createElement(
  869. ZCodeIntlProvider,
  870. { initialLocale: "zh-CN" },
  871. createElement(ConversationRowView, {
  872. context: { ...rowContext, readAttachment },
  873. row,
  874. }),
  875. ),
  876. );
  877. });
  878. expect(attachmentPropsById.get("42-0")?.onOpen).toBeTypeOf("function");
  879. expect(attachmentPropsById.get("42-0")?.openLabel).toBe("打开图片预览");
  880. expect(attachmentPropsById.get("42-1")?.onOpen).toBeTypeOf("function");
  881. expect(attachmentPropsById.get("42-2")?.onOpen).toBeUndefined();
  882. const openPreview = attachmentPropsById.get("42-1")?.onOpen;
  883. expect(openPreview).toBeTypeOf("function");
  884. await act(async () => {
  885. (openPreview as () => void)();
  886. await Promise.resolve();
  887. await Promise.resolve();
  888. });
  889. expect(readAttachment).toHaveBeenCalledTimes(2);
  890. expect(createObjectUrl).toHaveBeenCalledTimes(2);
  891. expect(imagePreviewDialogProps.at(-1)).toMatchObject({
  892. open: true,
  893. initialIndex: 1,
  894. items: [
  895. { alt: "first.png", filename: "first.png", src: "blob:first-preview" },
  896. {
  897. alt: "second.png",
  898. filename: "second.png",
  899. src: "blob:second-preview",
  900. },
  901. ],
  902. });
  903. const onPreviewOpenChange = imagePreviewDialogProps.at(-1)?.onOpenChange;
  904. expect(onPreviewOpenChange).toBeTypeOf("function");
  905. await act(async () => {
  906. (onPreviewOpenChange as (open: boolean) => void)(false);
  907. });
  908. await act(async () => root.unmount());
  909. expect(revokeObjectUrl).toHaveBeenCalledWith("blob:first-preview");
  910. expect(revokeObjectUrl).toHaveBeenCalledWith("blob:second-preview");
  911. });
  912. it("opens sent videos in the shared mixed media gallery by exact row attachment", async () => {
  913. const readAttachment = vi.fn().mockResolvedValue({
  914. bytes: new Uint8Array([0, 0, 0, 24]),
  915. mediaType: "video/quicktime",
  916. });
  917. const createObjectUrl = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:sent-preview");
  918. const revokeObjectUrl = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
  919. const row = userInputRow({
  920. attachments: [
  921. {
  922. ref: "/workspace/shot.png",
  923. fileName: "shot.png",
  924. mime: "image/png",
  925. bytes: 4,
  926. },
  927. {
  928. ref: "/workspace/demo.mov",
  929. fileName: "demo.mov",
  930. mime: "video/quicktime",
  931. bytes: 4,
  932. },
  933. {
  934. ref: "/workspace/note.txt",
  935. fileName: "note.txt",
  936. mime: "text/plain",
  937. bytes: 4,
  938. },
  939. ],
  940. });
  941. const root: Root = createRoot(installMinimalDom());
  942. await act(async () => {
  943. root.render(
  944. createElement(
  945. ZCodeIntlProvider,
  946. { initialLocale: "zh-CN" },
  947. createElement(ConversationRowView, {
  948. context: { ...rowContext, readAttachment },
  949. row,
  950. }),
  951. ),
  952. );
  953. });
  954. expect(attachmentPropsById.get("42-0")?.onOpen).toBeTypeOf("function");
  955. expect(attachmentPropsById.get("42-0")?.openLabel).toBe("打开图片预览");
  956. expect(attachmentPropsById.get("42-1")?.onOpen).toBeTypeOf("function");
  957. expect(attachmentPropsById.get("42-1")?.openLabel).toBe("打开视频预览");
  958. expect(attachmentPropsById.get("42-2")?.onOpen).toBeUndefined();
  959. const openPreview = attachmentPropsById.get("42-1")?.onOpen;
  960. expect(openPreview).toBeTypeOf("function");
  961. await act(async () => {
  962. (openPreview as () => void)();
  963. await Promise.resolve();
  964. await Promise.resolve();
  965. });
  966. expect(readAttachment).toHaveBeenCalledWith({
  967. sessionId: "session-1",
  968. ref: "/workspace/demo.mov",
  969. mediaType: "video/quicktime",
  970. target: { rowId: 42, entityId: "message-user-42" },
  971. attachmentIndex: 1,
  972. signal: expect.any(AbortSignal),
  973. });
  974. // 挂载时 image/video 各读取一次;点击 video 复用首帧 Blob,不重复读取。
  975. expect(createObjectUrl).toHaveBeenCalledTimes(2);
  976. expect(imagePreviewDialogProps.at(-1)).toMatchObject({
  977. open: true,
  978. initialIndex: 1,
  979. items: [
  980. {
  981. alt: "shot.png",
  982. filename: "shot.png",
  983. mediaType: "image/png",
  984. src: expect.stringMatching(/^blob:/u),
  985. },
  986. {
  987. alt: "demo.mov",
  988. filename: "demo.mov",
  989. mediaType: "video/quicktime",
  990. src: "blob:sent-preview",
  991. },
  992. ],
  993. });
  994. const onPreviewOpenChange = imagePreviewDialogProps.at(-1)?.onOpenChange;
  995. expect(onPreviewOpenChange).toBeTypeOf("function");
  996. await act(async () => {
  997. (onPreviewOpenChange as (open: boolean) => void)(false);
  998. });
  999. // gallery 关闭后首帧仍在消息卡片使用,直到消息行卸载才统一释放。
  1000. expect(revokeObjectUrl).not.toHaveBeenCalledWith("blob:sent-preview");
  1001. await act(async () => root.unmount());
  1002. expect(revokeObjectUrl).toHaveBeenCalledWith("blob:sent-preview");
  1003. });
  1004. it("loads a video when mixed-media gallery navigation selects it", async () => {
  1005. let resolveVideoPreview!: (value: { bytes: Uint8Array; mediaType: string }) => void;
  1006. let videoReads = 0;
  1007. const readAttachment = vi.fn(({ ref }: { ref: string }) => {
  1008. if (ref.endsWith("shot.png")) {
  1009. return Promise.resolve({
  1010. bytes: new Uint8Array([1, 2, 3]),
  1011. mediaType: "image/png",
  1012. });
  1013. }
  1014. videoReads += 1;
  1015. if (videoReads === 1) {
  1016. return Promise.reject(new Error("thumbnail prefetch failed"));
  1017. }
  1018. return new Promise<{ bytes: Uint8Array; mediaType: string }>((resolve) => {
  1019. resolveVideoPreview = resolve;
  1020. });
  1021. });
  1022. vi.spyOn(URL, "createObjectURL")
  1023. .mockReturnValueOnce("blob:image-preview")
  1024. .mockReturnValueOnce("blob:video-preview");
  1025. vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
  1026. const row = userInputRow({
  1027. attachments: [
  1028. {
  1029. ref: "/workspace/shot.png",
  1030. fileName: "shot.png",
  1031. mime: "image/png",
  1032. bytes: 3,
  1033. },
  1034. {
  1035. ref: "/workspace/demo.mp4",
  1036. fileName: "demo.mp4",
  1037. mime: "video/mp4",
  1038. bytes: 4,
  1039. },
  1040. ],
  1041. });
  1042. const root: Root = createRoot(installMinimalDom());
  1043. await act(async () => {
  1044. root.render(
  1045. createElement(
  1046. ZCodeIntlProvider,
  1047. { initialLocale: "zh-CN" },
  1048. createElement(ConversationRowView, {
  1049. context: { ...rowContext, readAttachment },
  1050. row,
  1051. }),
  1052. ),
  1053. );
  1054. await Promise.resolve();
  1055. await Promise.resolve();
  1056. });
  1057. const openImagePreview = attachmentPropsById.get("42-0")?.onOpen;
  1058. expect(openImagePreview).toBeTypeOf("function");
  1059. await act(async () => {
  1060. (openImagePreview as () => void)();
  1061. });
  1062. const onActiveIndexChange = imagePreviewDialogProps.at(-1)?.onActiveIndexChange as
  1063. | ((index: number) => void)
  1064. | undefined;
  1065. expect(onActiveIndexChange).toBeTypeOf("function");
  1066. await act(async () => {
  1067. onActiveIndexChange?.(1);
  1068. await Promise.resolve();
  1069. });
  1070. expect(readAttachment).toHaveBeenLastCalledWith({
  1071. sessionId: "session-1",
  1072. ref: "/workspace/demo.mp4",
  1073. mediaType: "video/mp4",
  1074. target: { rowId: 42, entityId: "message-user-42" },
  1075. attachmentIndex: 1,
  1076. signal: expect.any(AbortSignal),
  1077. });
  1078. expect(imagePreviewDialogProps.at(-1)).toMatchObject({
  1079. initialIndex: 1,
  1080. items: [
  1081. expect.objectContaining({ src: "blob:image-preview" }),
  1082. expect.objectContaining({ loading: true, src: undefined }),
  1083. ],
  1084. });
  1085. await act(async () => {
  1086. resolveVideoPreview({
  1087. bytes: new Uint8Array([0, 0, 0, 24]),
  1088. mediaType: "video/mp4",
  1089. });
  1090. await Promise.resolve();
  1091. await Promise.resolve();
  1092. });
  1093. expect(imagePreviewDialogProps.at(-1)).toMatchObject({
  1094. items: [
  1095. expect.objectContaining({ src: "blob:image-preview" }),
  1096. expect.objectContaining({ loading: false, src: "blob:video-preview" }),
  1097. ],
  1098. });
  1099. await act(async () => root.unmount());
  1100. });
  1101. it("opens a Desktop local media URL without creating or revoking a Blob URL", async () => {
  1102. const readAttachment = vi.fn().mockResolvedValue({
  1103. url: "zcode-media://local/desktop-video",
  1104. mediaType: "video/mp4",
  1105. });
  1106. const createObjectUrl = vi.spyOn(URL, "createObjectURL");
  1107. const revokeObjectUrl = vi.spyOn(URL, "revokeObjectURL");
  1108. const row = userInputRow({
  1109. attachments: [{ ref: "/tmp/demo.mp4", fileName: "demo.mp4", mime: "video/mp4", bytes: 1024 }],
  1110. });
  1111. const root: Root = createRoot(installMinimalDom());
  1112. await act(async () => {
  1113. root.render(
  1114. createElement(
  1115. ZCodeIntlProvider,
  1116. { initialLocale: "zh-CN" },
  1117. createElement(ConversationRowView, {
  1118. context: { ...rowContext, readAttachment },
  1119. row,
  1120. }),
  1121. ),
  1122. );
  1123. await Promise.resolve();
  1124. await Promise.resolve();
  1125. });
  1126. expect(readAttachment).toHaveBeenCalledWith({
  1127. sessionId: "session-1",
  1128. ref: "/tmp/demo.mp4",
  1129. mediaType: "video/mp4",
  1130. target: { rowId: row.rowId, entityId: row.entityId },
  1131. attachmentIndex: 0,
  1132. signal: expect.any(AbortSignal),
  1133. });
  1134. expect(attachmentPropsById.get(`${row.rowId}-0`)).toMatchObject({
  1135. data: { url: "zcode-media://local/desktop-video" },
  1136. });
  1137. const openPreview = attachmentPropsById.get(`${row.rowId}-0`)?.onOpen;
  1138. expect(openPreview).toBeTypeOf("function");
  1139. await act(async () => {
  1140. (openPreview as () => void)();
  1141. await Promise.resolve();
  1142. await Promise.resolve();
  1143. });
  1144. expect(imagePreviewDialogProps.at(-1)).toMatchObject({
  1145. open: true,
  1146. initialIndex: 0,
  1147. items: [
  1148. {
  1149. alt: "demo.mp4",
  1150. filename: "demo.mp4",
  1151. mediaType: "video/mp4",
  1152. src: "zcode-media://local/desktop-video",
  1153. loading: false,
  1154. error: false,
  1155. },
  1156. ],
  1157. });
  1158. expect(createObjectUrl).not.toHaveBeenCalled();
  1159. const closePreview = imagePreviewDialogProps.at(-1)?.onOpenChange;
  1160. expect(closePreview).toBeTypeOf("function");
  1161. await act(async () => {
  1162. (closePreview as (open: boolean) => void)(false);
  1163. });
  1164. expect(revokeObjectUrl).not.toHaveBeenCalled();
  1165. await act(async () => root.unmount());
  1166. });
  1167. it("aborts an unfinished sent media read when the preview closes", async () => {
  1168. let readSignal: AbortSignal | undefined;
  1169. const readAttachment = vi.fn(
  1170. (params: { signal?: AbortSignal }) =>
  1171. new Promise<{ bytes: Uint8Array; mediaType: string }>(() => {
  1172. readSignal = params.signal;
  1173. }),
  1174. );
  1175. const row = userInputRow({
  1176. attachments: [
  1177. {
  1178. ref: "/workspace/large.mp4",
  1179. fileName: "large.mp4",
  1180. mime: "video/mp4",
  1181. bytes: 80,
  1182. },
  1183. ],
  1184. });
  1185. const root: Root = createRoot(installMinimalDom());
  1186. await act(async () => {
  1187. root.render(
  1188. createElement(
  1189. ZCodeIntlProvider,
  1190. { initialLocale: "zh-CN" },
  1191. createElement(ConversationRowView, {
  1192. context: { ...rowContext, readAttachment },
  1193. row,
  1194. }),
  1195. ),
  1196. );
  1197. });
  1198. const openPreview = attachmentPropsById.get("42-0")?.onOpen;
  1199. expect(openPreview).toBeTypeOf("function");
  1200. await act(async () => {
  1201. (openPreview as () => void)();
  1202. await Promise.resolve();
  1203. });
  1204. expect(readSignal).toBeDefined();
  1205. expect(readSignal?.aborted).toBe(false);
  1206. const replacedSignal = readSignal;
  1207. await act(async () => {
  1208. (openPreview as () => void)();
  1209. await Promise.resolve();
  1210. });
  1211. expect(replacedSignal?.aborted).toBe(true);
  1212. expect(readSignal).not.toBe(replacedSignal);
  1213. expect(readSignal?.aborted).toBe(false);
  1214. const closePreview = imagePreviewDialogProps.at(-1)?.onOpenChange;
  1215. expect(closePreview).toBeTypeOf("function");
  1216. await act(async () => {
  1217. (closePreview as (open: boolean) => void)(false);
  1218. });
  1219. expect(readSignal?.aborted).toBe(true);
  1220. const closedSignal = readSignal;
  1221. await act(async () => {
  1222. (openPreview as () => void)();
  1223. await Promise.resolve();
  1224. });
  1225. expect(readSignal).not.toBe(closedSignal);
  1226. expect(readSignal?.aborted).toBe(false);
  1227. await act(async () => root.unmount());
  1228. expect(readSignal?.aborted).toBe(true);
  1229. });
  1230. it("aborts unfinished visible-row media prefetch when the row unmounts", async () => {
  1231. let prefetchSignal: AbortSignal | undefined;
  1232. const readAttachment = vi.fn(
  1233. (params: { signal?: AbortSignal }) =>
  1234. new Promise<{ bytes: Uint8Array; mediaType: string }>(() => {
  1235. prefetchSignal = params.signal;
  1236. }),
  1237. );
  1238. const row = userInputRow({
  1239. attachments: [
  1240. {
  1241. ref: "/workspace/large.mp4",
  1242. fileName: "large.mp4",
  1243. mime: "video/mp4",
  1244. bytes: 80,
  1245. },
  1246. ],
  1247. });
  1248. const root: Root = createRoot(installMinimalDom());
  1249. await act(async () => {
  1250. root.render(
  1251. createElement(
  1252. ZCodeIntlProvider,
  1253. { initialLocale: "zh-CN" },
  1254. createElement(ConversationRowView, {
  1255. context: { ...rowContext, readAttachment },
  1256. row,
  1257. }),
  1258. ),
  1259. );
  1260. await Promise.resolve();
  1261. });
  1262. expect(prefetchSignal).toBeDefined();
  1263. expect(prefetchSignal?.aborted).toBe(false);
  1264. await act(async () => root.unmount());
  1265. expect(prefetchSignal?.aborted).toBe(true);
  1266. });
  1267. it("marks an unreadable sent image unavailable and removes its open action", async () => {
  1268. const readAttachment = vi.fn().mockRejectedValue(new Error("gone"));
  1269. vi.spyOn(console, "warn").mockImplementation(() => {});
  1270. const row = userInputRow({
  1271. attachments: [
  1272. {
  1273. ref: "/workspace/gone.png",
  1274. fileName: "gone.png",
  1275. mime: "image/png",
  1276. bytes: 4,
  1277. },
  1278. ],
  1279. });
  1280. const root: Root = createRoot(installMinimalDom());
  1281. await act(async () => {
  1282. root.render(
  1283. createElement(
  1284. ZCodeIntlProvider,
  1285. { initialLocale: "zh-CN" },
  1286. createElement(ConversationRowView, {
  1287. context: { ...rowContext, readAttachment },
  1288. row,
  1289. }),
  1290. ),
  1291. );
  1292. });
  1293. expect(readAttachment).toHaveBeenCalledWith({
  1294. sessionId: "session-1",
  1295. ref: "/workspace/gone.png",
  1296. signal: expect.any(AbortSignal),
  1297. });
  1298. expect(attachmentPropsById.get("42-0")?.onOpen).toBeUndefined();
  1299. expect(attachmentPropsById.get("42-0")?.title).toBe("这张图片已无法预览。");
  1300. await act(async () => root.unmount());
  1301. });
  1302. // 回归:v4 迁移后用户行复制/编辑按钮硬编码中文,未走 i18n;
  1303. // en-US 下会显示「复制」「编辑」。文案必须跟随当前 locale。
  1304. it.each([
  1305. ["zh-CN", "复制", "编辑"],
  1306. ["en-US", "Copy", "Edit"],
  1307. ] as const)(
  1308. "renders user row copy/edit action labels from locale %s",
  1309. async (locale, copyLabel, editLabel) => {
  1310. const row = userInputRow();
  1311. const container = installMinimalDom();
  1312. const root: Root = createRoot(container);
  1313. await act(async () => {
  1314. root.render(
  1315. createElement(
  1316. ZCodeIntlProvider,
  1317. { initialLocale: locale },
  1318. createElement(ConversationRowView, {
  1319. context: rowContext,
  1320. onEdit: vi.fn(),
  1321. row,
  1322. }),
  1323. ),
  1324. );
  1325. });
  1326. const copyAction = messageActionPropsByTestId.get(`v4-copy-${row.rowId}`);
  1327. expect(copyAction?.label).toBe(copyLabel);
  1328. expect(copyAction?.tooltip).toBe(copyLabel);
  1329. const editAction = messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)));
  1330. expect(editAction?.label).toBe(editLabel);
  1331. expect(editAction?.tooltip).toBe(editLabel);
  1332. await act(async () => {
  1333. root.unmount();
  1334. });
  1335. },
  1336. );
  1337. it("keeps user message actions visible in compact remote control mode", async () => {
  1338. const row = userInputRow();
  1339. const container = installMinimalDom();
  1340. const root: Root = createRoot(container);
  1341. await act(async () => {
  1342. root.render(
  1343. createElement(
  1344. ZCodeIntlProvider,
  1345. { initialLocale: "zh-CN" },
  1346. createElement(ConversationRowView, {
  1347. context: { ...rowContext, compactForRemoteControl: true },
  1348. row,
  1349. onEdit: vi.fn(),
  1350. }),
  1351. ),
  1352. );
  1353. });
  1354. const actionsClassName = collectAttributeValues(container, "class").find((value) =>
  1355. value.includes("mt-1 opacity"),
  1356. );
  1357. expect(actionsClassName).toContain("opacity-100");
  1358. expect(actionsClassName).not.toContain("opacity-0");
  1359. await act(async () => {
  1360. root.unmount();
  1361. });
  1362. });
  1363. it("keeps assistant feedback local to the mounted action toolbar", async () => {
  1364. const row = assistantTextRow({
  1365. entityId: "message-assistant-43",
  1366. state: "complete",
  1367. });
  1368. const root: Root = createRoot(installMinimalDom());
  1369. await act(async () => {
  1370. root.render(
  1371. createElement(
  1372. ZCodeIntlProvider,
  1373. { initialLocale: "zh-CN" },
  1374. createElement(ConversationRowView, {
  1375. context: { ...rowContext, compactForRemoteControl: true },
  1376. row,
  1377. onFeedbackChange: vi.fn(async () => true),
  1378. }),
  1379. ),
  1380. );
  1381. });
  1382. const likeTestId = testId(TID_V4_FEEDBACK_LIKE, String(row.rowId));
  1383. const dislikeTestId = testId(TID_V4_FEEDBACK_DISLIKE, String(row.rowId));
  1384. expect(messageActionPropsByTestId.get(likeTestId)?.["aria-pressed"]).toBe(false);
  1385. expect(messageActionPropsByTestId.get(dislikeTestId)?.["aria-pressed"]).toBe(false);
  1386. expect(messageActionPropsByTestId.get(likeTestId)?.tooltip).toBeUndefined();
  1387. const handleLike = messageActionPropsByTestId.get(likeTestId)?.onClick;
  1388. expect(handleLike).toBeTypeOf("function");
  1389. await act(async () => {
  1390. (handleLike as () => void)();
  1391. });
  1392. expect(messageActionPropsByTestId.get(likeTestId)?.["aria-pressed"]).toBe(true);
  1393. expect(messageActionPropsByTestId.get(dislikeTestId)?.["aria-pressed"]).toBe(false);
  1394. const handleLikeAgain = messageActionPropsByTestId.get(likeTestId)?.onClick;
  1395. expect(handleLikeAgain).toBeTypeOf("function");
  1396. await act(async () => {
  1397. (handleLikeAgain as () => void)();
  1398. });
  1399. expect(messageActionPropsByTestId.get(likeTestId)?.["aria-pressed"]).toBe(false);
  1400. expect(messageActionPropsByTestId.get(dislikeTestId)?.["aria-pressed"]).toBe(false);
  1401. const handleDislike = messageActionPropsByTestId.get(dislikeTestId)?.onClick;
  1402. expect(handleDislike).toBeTypeOf("function");
  1403. await act(async () => {
  1404. (handleDislike as () => void)();
  1405. });
  1406. expect(messageActionPropsByTestId.get(likeTestId)?.["aria-pressed"]).toBe(false);
  1407. expect(messageActionPropsByTestId.get(dislikeTestId)?.["aria-pressed"]).toBe(true);
  1408. await act(async () => {
  1409. root.unmount();
  1410. });
  1411. });
  1412. it.each(["complete", "streaming"] as const)(
  1413. "puts assistant %s text inside a real selectable DOM region",
  1414. async (state) => {
  1415. const row = assistantTextRow({ state });
  1416. const container = installMinimalDom();
  1417. const root: Root = createRoot(container);
  1418. await act(async () => {
  1419. root.render(
  1420. createElement(
  1421. ZCodeIntlProvider,
  1422. { initialLocale: "zh-CN" },
  1423. createElement(ConversationRowView, {
  1424. context: rowContext,
  1425. row,
  1426. }),
  1427. ),
  1428. );
  1429. });
  1430. expect(collectAttributeValues(container, "data-conversation-selectable")).toContain("true");
  1431. // 回归根因:标记不能继续依赖不透传 data-* 的 MessageResponse。
  1432. expect(messageResponseProps.at(-1)?.["data-conversation-selectable"]).toBeUndefined();
  1433. await act(async () => {
  1434. root.unmount();
  1435. });
  1436. },
  1437. );
  1438. it("保持显式 Markdown 文件处理器,仅为 Assistant 开启 citation 投影", async () => {
  1439. const row = assistantTextRow({
  1440. state: "complete",
  1441. text: "See [README](./README.md) and https://example.test.",
  1442. });
  1443. const onOpenBrowserUrl = vi.fn();
  1444. const onOpenCodeViewer = vi.fn();
  1445. const onOpenFileLink = vi.fn();
  1446. const readAttachment = vi.fn();
  1447. const container = installMinimalDom();
  1448. const root: Root = createRoot(container);
  1449. await act(async () => {
  1450. root.render(
  1451. createElement(
  1452. ZCodeIntlProvider,
  1453. { initialLocale: "zh-CN" },
  1454. createElement(ConversationRowView, {
  1455. context: {
  1456. ...rowContext,
  1457. onOpenBrowserUrl,
  1458. onOpenCodeViewer,
  1459. onOpenFileLink,
  1460. readAttachment,
  1461. },
  1462. row,
  1463. }),
  1464. ),
  1465. );
  1466. });
  1467. expect(messageResponseProps).toHaveLength(1);
  1468. expect(messageResponseProps[0]?.onOpenExternalUrl).toBe(onOpenBrowserUrl);
  1469. expect(messageResponseProps[0]?.onOpenCodeViewer).toBe(onOpenCodeViewer);
  1470. expect(messageResponseProps[0]?.onOpenFileLink).toBe(onOpenFileLink);
  1471. expect(messageResponseProps[0]?.renderZCodeFileCitations).toBe(true);
  1472. // 回归根因:artifact 图片读取能力必须由行级生产接线继续传入 Markdown。
  1473. expect(messageResponseProps[0]?.sessionId).toBe("session-1");
  1474. expect(messageResponseProps[0]?.readAttachment).toBe(readAttachment);
  1475. await act(async () => {
  1476. root.unmount();
  1477. });
  1478. });
  1479. it("renders web element contexts as read-only chips while keeping the raw row text for actions", async () => {
  1480. const context: WebElementContextComposerAttachment = {
  1481. capturedAt: 1_700_000_000_000,
  1482. id: "element-1",
  1483. pageTitle: "Docs",
  1484. pageUrl: "https://example.test/docs",
  1485. role: "button",
  1486. tagName: "button",
  1487. text: "Submit",
  1488. workspaceIdentity: "remote:workspace",
  1489. workspacePath: "/workspace",
  1490. };
  1491. const rawText = buildPromptWithWebElementContexts("帮我看这个按钮", [context]);
  1492. const row = userInputRow({
  1493. text: rawText,
  1494. });
  1495. const container = installMinimalDom();
  1496. const root: Root = createRoot(container);
  1497. await act(async () => {
  1498. root.render(
  1499. createElement(
  1500. ZCodeIntlProvider,
  1501. { initialLocale: "zh-CN" },
  1502. createElement(ConversationRowView, {
  1503. context: rowContext,
  1504. onEdit: vi.fn(),
  1505. row,
  1506. }),
  1507. ),
  1508. );
  1509. });
  1510. const text = collectText(container);
  1511. expect(text).toContain("帮我看这个按钮");
  1512. expect(text).toContain("1 个网页元素");
  1513. expect(text).not.toContain("# Web page elements:");
  1514. const attachmentArea = findElementByAttribute(
  1515. container,
  1516. "data-v4-user-input-attachments",
  1517. "true",
  1518. );
  1519. const messageBubble = findElementByAttribute(container, "data-v4-user-input-bubble", "true");
  1520. expect(collectText(attachmentArea)).toContain("note.txt");
  1521. expect(collectText(attachmentArea)).toContain("1 个网页元素");
  1522. expect(collectText(messageBubble)).toBe("帮我看这个按钮");
  1523. const fileAttachmentPill = findElementByAttribute(
  1524. attachmentArea,
  1525. "data-v4-user-input-attachment-pill",
  1526. "true",
  1527. );
  1528. const webElementChip = findElementByAttribute(attachmentArea, "aria-label", "1 个网页元素");
  1529. const pillRow = findElementByAttribute(
  1530. attachmentArea,
  1531. "data-v4-user-input-attachment-pills",
  1532. "true",
  1533. );
  1534. expect(fileAttachmentPill?.parentNode).toBe(pillRow);
  1535. expect(webElementChip?.parentNode).toBe(pillRow);
  1536. const copyAction = messageActionPropsByTestId.get(`v4-copy-${row.rowId}`);
  1537. expect(copyAction).toBeDefined();
  1538. expect(copyAction?.disabled).toBe(false);
  1539. await act(async () => {
  1540. root.unmount();
  1541. });
  1542. });
  1543. it("right-aligns PPT and conversation-reference hover cards in sent user rows", async () => {
  1544. const pptxElement: PptxElementReference = {
  1545. id: "pptx-1",
  1546. workspacePath: "/workspace",
  1547. sourcePath: "/workspace/deck.pptx",
  1548. sourceTitle: "deck.pptx",
  1549. sourceFingerprint: `sha256:${"a".repeat(64)}`,
  1550. slideIndex: 0,
  1551. slidePart: "ppt/slides/slide1.xml",
  1552. nodeId: "7",
  1553. nodeName: "Title",
  1554. nodeType: "shape",
  1555. bounds: { x: 0, y: 0, width: 100, height: 30 },
  1556. zIndex: 1,
  1557. capturedAt: 1,
  1558. };
  1559. const selection: ConversationSelectionReference = {
  1560. id: "selection-1",
  1561. sourceSessionId: "source-session",
  1562. sourceRowId: 8,
  1563. contentType: "assistant",
  1564. text: "selected answer",
  1565. };
  1566. const row = userInputRow({
  1567. text: serializeComposerPromptContexts("请处理", {
  1568. codeComments: [],
  1569. conversationSelections: [selection],
  1570. pptxElements: [pptxElement],
  1571. webElements: [],
  1572. }),
  1573. });
  1574. const container = installMinimalDom();
  1575. const root: Root = createRoot(container);
  1576. await act(async () => {
  1577. root.render(
  1578. createElement(
  1579. ZCodeIntlProvider,
  1580. { initialLocale: "zh-CN" },
  1581. createElement(ConversationRowView, {
  1582. context: rowContext,
  1583. onEdit: vi.fn(),
  1584. row,
  1585. }),
  1586. ),
  1587. );
  1588. });
  1589. expect(hoverCardContentProps).toHaveLength(4);
  1590. expect(hoverCardContentProps.every((props) => props.align === "end")).toBe(true);
  1591. await act(async () => {
  1592. root.unmount();
  1593. });
  1594. });
  1595. it("does not render a bubble when a user row only contains context references", async () => {
  1596. const context: WebElementContextComposerAttachment = {
  1597. capturedAt: 1_700_000_000_000,
  1598. id: "element-only",
  1599. pageTitle: "Docs",
  1600. pageUrl: "https://example.test/docs",
  1601. tagName: "main",
  1602. text: "Content",
  1603. workspaceIdentity: "remote:workspace",
  1604. workspacePath: "/workspace",
  1605. };
  1606. const container = installMinimalDom();
  1607. const root: Root = createRoot(container);
  1608. await act(async () => {
  1609. root.render(
  1610. createElement(
  1611. ZCodeIntlProvider,
  1612. { initialLocale: "zh-CN" },
  1613. createElement(ConversationRowView, {
  1614. context: rowContext,
  1615. row: userInputRow({
  1616. attachments: [],
  1617. text: buildPromptWithWebElementContexts("", [context]),
  1618. }),
  1619. }),
  1620. ),
  1621. );
  1622. });
  1623. expect(
  1624. findElementByAttribute(container, "data-v4-user-input-attachments", "true"),
  1625. ).not.toBeNull();
  1626. expect(findElementByAttribute(container, "data-v4-user-input-bubble", "true")).toBeNull();
  1627. await act(async () => root.unmount());
  1628. });
  1629. it("renders an authoritative goal query without the slash", async () => {
  1630. const row = userInputRow({
  1631. attachments: [],
  1632. text: "/goal 看一下这是个啥项目",
  1633. });
  1634. const container = installMinimalDom();
  1635. const root: Root = createRoot(container);
  1636. await act(async () => {
  1637. root.render(
  1638. createElement(
  1639. ZCodeIntlProvider,
  1640. { initialLocale: "zh-CN" },
  1641. createElement(ConversationRowView, {
  1642. context: rowContext,
  1643. row,
  1644. }),
  1645. ),
  1646. );
  1647. });
  1648. expect(collectText(container)).toContain("goal 看一下这是个啥项目");
  1649. expect(collectText(container)).not.toContain("/goal");
  1650. expect(collectAttributeValues(container, "class").join(" ")).toContain("lucide-goal");
  1651. expect(collectAttributeValues(container, "data-v4-user-input-command")).toContain("goal");
  1652. await act(async () => {
  1653. root.unmount();
  1654. });
  1655. });
  1656. it("opens an inline editor and submits edited text with original attachments", async () => {
  1657. const onEdit = vi.fn(async () => true);
  1658. const row = userInputRow();
  1659. const root: Root = createRoot(installMinimalDom());
  1660. await act(async () => {
  1661. root.render(
  1662. createElement(
  1663. ZCodeIntlProvider,
  1664. { initialLocale: "zh-CN" },
  1665. createElement(ConversationRowView, {
  1666. context: rowContext,
  1667. onEdit,
  1668. row,
  1669. }),
  1670. ),
  1671. );
  1672. });
  1673. const editAction = messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)));
  1674. expect(editAction).toBeDefined();
  1675. const editOnClick = editAction?.onClick;
  1676. expect(typeof editOnClick).toBe("function");
  1677. await act(async () => {
  1678. (editOnClick as () => void)();
  1679. });
  1680. expect(chatPromptEditorProps).toHaveLength(1);
  1681. expect(chatPromptEditorProps[0]?.initialValue).toBe(row.text);
  1682. const submitEdit = chatPromptEditorProps[0]?.onSubmit;
  1683. expect(typeof submitEdit).toBe("function");
  1684. await act(async () => {
  1685. await (submitEdit as (value: string) => Promise<void>)("改过的问题");
  1686. });
  1687. expect(onEdit).toHaveBeenCalledWith(
  1688. { rowId: row.rowId, entityId: row.entityId },
  1689. "改过的问题",
  1690. row.attachments,
  1691. "preserve",
  1692. );
  1693. await act(async () => {
  1694. root.unmount();
  1695. });
  1696. });
  1697. it("renders edit attachments like the composer and submits the remaining refs in source order", async () => {
  1698. const onEdit = vi.fn(async () => true);
  1699. const row = userInputRow({
  1700. text: "",
  1701. attachments: [
  1702. {
  1703. bytes: 12,
  1704. fileName: "first.txt",
  1705. mime: "text/plain",
  1706. ref: "/workspace/first.txt",
  1707. },
  1708. {
  1709. bytes: 24,
  1710. fileName: "second.png",
  1711. mime: "image/png",
  1712. ref: "/workspace/second.png",
  1713. },
  1714. {
  1715. bytes: 48,
  1716. fileName: "third.mov",
  1717. mime: "video/quicktime",
  1718. ref: "/workspace/third.mov",
  1719. },
  1720. ],
  1721. });
  1722. const root: Root = createRoot(installMinimalDom());
  1723. await act(async () => {
  1724. root.render(
  1725. createElement(
  1726. ZCodeIntlProvider,
  1727. { initialLocale: "zh-CN" },
  1728. createElement(ConversationRowView, {
  1729. context: rowContext,
  1730. onEdit,
  1731. row,
  1732. }),
  1733. ),
  1734. );
  1735. });
  1736. await act(async () => {
  1737. (
  1738. messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)))?.onClick as
  1739. | (() => void)
  1740. | undefined
  1741. )?.();
  1742. });
  1743. // 编辑态按「媒体优先、组内原序」排列:second.png、third.mov 为媒体卡,first.txt 为文件卡。
  1744. expect(attachmentPropsById.get(`${row.rowId}-1`)).toMatchObject({
  1745. variant: "grid",
  1746. "data-v4-user-edit-attachment-kind": "image",
  1747. });
  1748. expect(attachmentPropsById.get(`${row.rowId}-2`)).toMatchObject({
  1749. variant: "grid",
  1750. "data-v4-user-edit-attachment-kind": "video",
  1751. });
  1752. expect(attachmentPropsById.get(`${row.rowId}-0`)).toMatchObject({
  1753. variant: "inline",
  1754. "data-v4-user-edit-attachment-kind": "file",
  1755. });
  1756. const firstRemoveId = testId(TID_V4_EDIT_ATTACHMENT_REMOVE, `${row.rowId}-0`);
  1757. const secondRemoveId = testId(TID_V4_EDIT_ATTACHMENT_REMOVE, `${row.rowId}-1`);
  1758. expect(attachmentRemovePropsByTestId.get(firstRemoveId)).toMatchObject({
  1759. alwaysVisible: undefined,
  1760. label: "移除附件",
  1761. placement: "corner",
  1762. variant: "default",
  1763. });
  1764. expect(attachmentRemovePropsByTestId.get(secondRemoveId)).toBeDefined();
  1765. await act(async () => {
  1766. (attachmentRemovePropsByTestId.get(firstRemoveId)!.onClick as () => void)();
  1767. });
  1768. expect(chatPromptEditorProps.at(-1)?.allowSubmitWhenEmpty).toBe(true);
  1769. expect(chatPromptEditorProps.at(-1)?.submitDisabled).toBe(false);
  1770. await act(async () => {
  1771. await (chatPromptEditorProps.at(-1)!.onSubmit as (value: string) => Promise<void>)("");
  1772. });
  1773. expect(onEdit).toHaveBeenCalledWith(
  1774. { rowId: row.rowId, entityId: row.entityId },
  1775. "",
  1776. [row.attachments?.[1], row.attachments?.[2]],
  1777. "preserve",
  1778. );
  1779. await act(async () => root.unmount());
  1780. });
  1781. it("renders prompt contexts in the edit second row and keeps protocol text out of the editor", async () => {
  1782. const onEdit = vi.fn(async () => true);
  1783. const webContext: WebElementContextComposerAttachment = {
  1784. capturedAt: 1_700_000_000_000,
  1785. id: "edit-web-element",
  1786. pageTitle: "Docs",
  1787. pageUrl: "https://example.test/docs",
  1788. selector: "main",
  1789. tagName: "main",
  1790. workspacePath: "/workspace",
  1791. };
  1792. const row = userInputRow({
  1793. attachments: [],
  1794. text: buildPromptWithWebElementContexts("改一下", [webContext]),
  1795. });
  1796. const container = installMinimalDom();
  1797. const root: Root = createRoot(container);
  1798. await act(async () => {
  1799. root.render(
  1800. createElement(
  1801. ZCodeIntlProvider,
  1802. { initialLocale: "zh-CN" },
  1803. createElement(ConversationRowView, {
  1804. context: rowContext,
  1805. onEdit,
  1806. row,
  1807. }),
  1808. ),
  1809. );
  1810. });
  1811. await act(async () => {
  1812. (
  1813. messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)))?.onClick as
  1814. | (() => void)
  1815. | undefined
  1816. )?.();
  1817. });
  1818. expect(chatPromptEditorProps.at(-1)?.initialValue).toBe("改一下");
  1819. const contextRow = findElementByAttribute(
  1820. container,
  1821. "data-v4-user-edit-context-attachments-row",
  1822. "true",
  1823. );
  1824. expect(contextRow).not.toBeNull();
  1825. expect(collectText(contextRow)).toContain("1 个网页元素");
  1826. await act(async () => {
  1827. await (chatPromptEditorProps.at(-1)!.onSubmit as (value: string) => Promise<void>)("更新");
  1828. });
  1829. expect(onEdit).toHaveBeenCalledWith(
  1830. { rowId: row.rowId, entityId: row.entityId },
  1831. buildPromptWithWebElementContexts("更新", [webContext]),
  1832. [],
  1833. "preserve",
  1834. );
  1835. await act(async () => root.unmount());
  1836. });
  1837. it("rejects an edit only after both text and attachments become empty", async () => {
  1838. const onEdit = vi.fn(async () => true);
  1839. const row = userInputRow({ text: "" });
  1840. const root: Root = createRoot(installMinimalDom());
  1841. await act(async () => {
  1842. root.render(
  1843. createElement(
  1844. ZCodeIntlProvider,
  1845. { initialLocale: "zh-CN" },
  1846. createElement(ConversationRowView, {
  1847. context: rowContext,
  1848. onEdit,
  1849. row,
  1850. }),
  1851. ),
  1852. );
  1853. });
  1854. await act(async () => {
  1855. (
  1856. messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)))?.onClick as
  1857. | (() => void)
  1858. | undefined
  1859. )?.();
  1860. });
  1861. expect(chatPromptEditorProps.at(-1)?.submitDisabled).toBe(false);
  1862. await act(async () => {
  1863. (
  1864. attachmentRemovePropsByTestId.get(testId(TID_V4_EDIT_ATTACHMENT_REMOVE, `${row.rowId}-0`))!
  1865. .onClick as () => void
  1866. )();
  1867. });
  1868. expect(chatPromptEditorProps.at(-1)?.allowSubmitWhenEmpty).toBe(false);
  1869. expect(chatPromptEditorProps.at(-1)?.submitDisabled).toBe(true);
  1870. await act(async () => {
  1871. await (chatPromptEditorProps.at(-1)!.onSubmit as (value: string) => Promise<void>)(" ");
  1872. });
  1873. expect(onEdit).not.toHaveBeenCalled();
  1874. await act(async () => root.unmount());
  1875. });
  1876. it("restores the original attachment list after cancelling and reopening edit", async () => {
  1877. const onEdit = vi.fn(async () => true);
  1878. const row = userInputRow({
  1879. attachments: [
  1880. ...(userInputRow().attachments ?? []),
  1881. {
  1882. bytes: 24,
  1883. fileName: "second.txt",
  1884. mime: "text/plain",
  1885. ref: "/workspace/second.txt",
  1886. },
  1887. ],
  1888. });
  1889. const root: Root = createRoot(installMinimalDom());
  1890. await act(async () => {
  1891. root.render(
  1892. createElement(
  1893. ZCodeIntlProvider,
  1894. { initialLocale: "zh-CN" },
  1895. createElement(ConversationRowView, {
  1896. context: rowContext,
  1897. onEdit,
  1898. row,
  1899. }),
  1900. ),
  1901. );
  1902. });
  1903. await act(async () => {
  1904. (
  1905. messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)))?.onClick as
  1906. | (() => void)
  1907. | undefined
  1908. )?.();
  1909. });
  1910. await act(async () => {
  1911. (
  1912. attachmentRemovePropsByTestId.get(testId(TID_V4_EDIT_ATTACHMENT_REMOVE, `${row.rowId}-0`))!
  1913. .onClick as () => void
  1914. )();
  1915. (chatPromptEditorProps.at(-1)!.onCancel as () => void)();
  1916. });
  1917. await act(async () => {
  1918. (
  1919. messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)))?.onClick as
  1920. | (() => void)
  1921. | undefined
  1922. )?.();
  1923. });
  1924. await act(async () => {
  1925. await (chatPromptEditorProps.at(-1)!.onSubmit as (value: string) => Promise<void>)(row.text);
  1926. });
  1927. expect(onEdit).toHaveBeenCalledWith(
  1928. { rowId: row.rowId, entityId: row.entityId },
  1929. row.text,
  1930. row.attachments,
  1931. "preserve",
  1932. );
  1933. await act(async () => root.unmount());
  1934. });
  1935. it("keeps removed refs after a failed ACK and leaves 15360+ pasted text in the editor", async () => {
  1936. const onEdit = vi.fn(async () => false);
  1937. const row = userInputRow({
  1938. attachments: [
  1939. ...(userInputRow().attachments ?? []),
  1940. {
  1941. bytes: 24,
  1942. fileName: "second.txt",
  1943. mime: "text/plain",
  1944. ref: "/workspace/second.txt",
  1945. },
  1946. ],
  1947. });
  1948. const longText = "长".repeat(15_361);
  1949. const root: Root = createRoot(installMinimalDom());
  1950. await act(async () => {
  1951. root.render(
  1952. createElement(
  1953. ZCodeIntlProvider,
  1954. { initialLocale: "zh-CN" },
  1955. createElement(ConversationRowView, {
  1956. context: rowContext,
  1957. onEdit,
  1958. row,
  1959. }),
  1960. ),
  1961. );
  1962. });
  1963. await act(async () => {
  1964. (
  1965. messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)))?.onClick as
  1966. | (() => void)
  1967. | undefined
  1968. )?.();
  1969. });
  1970. expect(chatPromptEditorProps.at(-1)?.onPaste).toBeUndefined();
  1971. await act(async () => {
  1972. (
  1973. attachmentRemovePropsByTestId.get(testId(TID_V4_EDIT_ATTACHMENT_REMOVE, `${row.rowId}-0`))!
  1974. .onClick as () => void
  1975. )();
  1976. (chatPromptEditorProps.at(-1)!.onChange as (value: string) => void)(longText);
  1977. });
  1978. await act(async () => {
  1979. await (chatPromptEditorProps.at(-1)!.onSubmit as (value: string) => Promise<void>)(longText);
  1980. });
  1981. expect(onEdit).toHaveBeenCalledWith(
  1982. { rowId: row.rowId, entityId: row.entityId },
  1983. longText,
  1984. [row.attachments?.[1]],
  1985. "preserve",
  1986. );
  1987. expect(chatPromptEditorProps.at(-1)?.initialValue).toBe(row.text);
  1988. expect(
  1989. attachmentRemovePropsByTestId.has(testId(TID_V4_EDIT_ATTACHMENT_REMOVE, `${row.rowId}-0`)),
  1990. ).toBe(true);
  1991. await act(async () => root.unmount());
  1992. });
  1993. it("keeps the disabled file reset tooltip hoverable and explains why it is unavailable", async () => {
  1994. const row = userInputRow();
  1995. const root: Root = createRoot(installMinimalDom());
  1996. await act(async () => {
  1997. root.render(
  1998. createElement(
  1999. ZCodeIntlProvider,
  2000. { initialLocale: "zh-CN" },
  2001. createElement(ConversationRowView, {
  2002. context: rowContext,
  2003. editWorkspaceRewindAvailability: {
  2004. enabled: false,
  2005. reason: "noFiles",
  2006. },
  2007. onEdit: vi.fn(),
  2008. row,
  2009. }),
  2010. ),
  2011. );
  2012. });
  2013. const editAction = messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)));
  2014. const editOnClick = editAction?.onClick;
  2015. expect(editOnClick).toBeTypeOf("function");
  2016. await act(async () => {
  2017. (editOnClick as () => void)();
  2018. });
  2019. const slot = chatPromptEditorProps.at(-1)?.betweenCancelAndSubmitAction as ReactElement<{
  2020. description?: string;
  2021. title: string;
  2022. children: ReactElement<Record<string, unknown>>;
  2023. }>;
  2024. const disabledTooltipTrigger = slot.props.children;
  2025. const rewindButton = disabledTooltipTrigger.props.children as ReactElement<
  2026. Record<string, unknown>
  2027. >;
  2028. expect(slot.props.title).toBe("与文件一起重置");
  2029. expect(slot.props.description).toBe("本轮没有可安全恢复的文件改动");
  2030. expect(disabledTooltipTrigger.type).toBe("span");
  2031. expect(disabledTooltipTrigger.props["data-disabled-tooltip-trigger"]).toBe("true");
  2032. expect(rewindButton.props.disabled).toBe(true);
  2033. expect((rewindButton.props.children as ReactElement).type).toBe(FileClockIcon);
  2034. await act(async () => {
  2035. root.unmount();
  2036. });
  2037. });
  2038. it("keeps the file+conversation action between cancel and send and falls back after a blocked preview", async () => {
  2039. const preview = {
  2040. canApply: false,
  2041. safeFiles: [],
  2042. unsafeFiles: [
  2043. {
  2044. action: "restore" as const,
  2045. operationCount: 1,
  2046. path: "/workspace/note.txt",
  2047. reason: "external_modified" as const,
  2048. toolNames: ["Write"],
  2049. },
  2050. ],
  2051. ignoredFiles: [],
  2052. };
  2053. const onEdit = vi
  2054. .fn()
  2055. .mockResolvedValueOnce({
  2056. commandId: "edit-rewind-command",
  2057. accepted: true,
  2058. result: {
  2059. type: "editUserQuery",
  2060. disposition: "blocked",
  2061. preview,
  2062. reasonCode: "edit.workspaceRewindBlocked",
  2063. },
  2064. })
  2065. .mockResolvedValueOnce({
  2066. commandId: "edit-conversation-only-command",
  2067. accepted: true,
  2068. result: { type: "editUserQuery", disposition: "rewind" },
  2069. });
  2070. const row = userInputRow();
  2071. const root: Root = createRoot(installMinimalDom());
  2072. await act(async () => {
  2073. root.render(
  2074. createElement(
  2075. ZCodeIntlProvider,
  2076. { initialLocale: "zh-CN" },
  2077. createElement(ConversationRowView, {
  2078. context: rowContext,
  2079. editWorkspaceRewindAvailability: {
  2080. enabled: true,
  2081. reason: "available",
  2082. },
  2083. onEdit,
  2084. row,
  2085. }),
  2086. ),
  2087. );
  2088. });
  2089. const editAction = messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)));
  2090. const editOnClick = editAction?.onClick;
  2091. expect(editOnClick).toBeTypeOf("function");
  2092. await act(async () => {
  2093. (editOnClick as () => void)();
  2094. });
  2095. const slot = chatPromptEditorProps.at(-1)?.betweenCancelAndSubmitAction as ReactElement<{
  2096. description?: string;
  2097. title: string;
  2098. children: ReactElement<Record<string, unknown>>;
  2099. }>;
  2100. const rewindButton = slot.props.children;
  2101. expect(slot.props.title).toBe("与文件一起重置");
  2102. expect(slot.props.description).toBeUndefined();
  2103. expect(rewindButton.props["data-testid"]).toBe(
  2104. testId(TID_V4_EDIT_REWIND_WORKSPACE, String(row.rowId)),
  2105. );
  2106. expect(rewindButton.props.disabled).toBe(false);
  2107. expect((rewindButton.props.children as ReactElement).type).toBe(FileClockIcon);
  2108. await act(async () => {
  2109. (rewindButton.props.onClick as () => void)();
  2110. await Promise.resolve();
  2111. });
  2112. expect(onEdit).toHaveBeenNthCalledWith(
  2113. 1,
  2114. { rowId: row.rowId, entityId: row.entityId },
  2115. row.text,
  2116. row.attachments,
  2117. "rewind",
  2118. );
  2119. expect(fileRewindDialogProps.at(-1)).toMatchObject({
  2120. open: true,
  2121. preview,
  2122. variant: "editConflict",
  2123. });
  2124. const onConversationOnly = fileRewindDialogProps.at(-1)?.onConversationOnly;
  2125. expect(onConversationOnly).toBeTypeOf("function");
  2126. await act(async () => {
  2127. (onConversationOnly as () => void)();
  2128. await Promise.resolve();
  2129. });
  2130. expect(onEdit).toHaveBeenNthCalledWith(
  2131. 2,
  2132. { rowId: row.rowId, entityId: row.entityId },
  2133. row.text,
  2134. row.attachments,
  2135. "preserve",
  2136. );
  2137. await act(async () => {
  2138. root.unmount();
  2139. });
  2140. });
  2141. });