v4ConversationRowViewUserEdit.test.ts 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355
  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";
  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 (messageBubble) {
  635. const bubbleClasses = collectAttributeValues(messageBubble, "class").join(" ");
  636. const bubbleClassTokens = bubbleClasses.split(/\s+/);
  637. expect(bubbleClasses).toContain("max-w-full");
  638. expect(bubbleClasses).toContain("@min-[624px]/conversation:max-w-xl");
  639. expect(bubbleClassTokens).not.toContain("w-fit");
  640. expect(bubbleClassTokens).not.toContain("w-full");
  641. expect(bubbleClassTokens).not.toContain("@md/conversation:max-w-xl");
  642. expect(bubbleClassTokens).not.toContain("@xl/conversation:max-w-xl");
  643. expect(bubbleClassTokens).not.toContain("@md/conversation:w-full");
  644. }
  645. if (attachmentArea && messageBubble) {
  646. expect(attachmentArea.parentNode).toBe(messageBubble.parentNode);
  647. const siblings = attachmentArea.parentNode as {
  648. childNodes?: unknown[];
  649. };
  650. expect(siblings.childNodes?.indexOf(attachmentArea)).toBeLessThan(
  651. siblings.childNodes?.indexOf(messageBubble) ?? -1,
  652. );
  653. }
  654. await act(async () => root.unmount());
  655. });
  656. it("renders sent attachments as surface pills with a file icon and filename", async () => {
  657. const container = installMinimalDom();
  658. const root: Root = createRoot(container);
  659. await act(async () => {
  660. root.render(
  661. createElement(
  662. ZCodeIntlProvider,
  663. { initialLocale: "zh-CN" },
  664. createElement(ConversationRowView, {
  665. context: rowContext,
  666. row: userInputRow({ text: "" }),
  667. }),
  668. ),
  669. );
  670. });
  671. const pill = findElementByAttribute(container, "data-v4-user-input-attachment-pill", "true");
  672. expect(pill).not.toBeNull();
  673. const classes = collectAttributeValues(pill, "class").join(" ");
  674. expect(classes).toContain("rounded-full");
  675. expect(classes).toContain("bg-surface");
  676. expect(collectText(pill)).toBe("note.txt");
  677. expect(collectAttributeValues(pill, "src").some((src) => src.endsWith(".svg"))).toBe(true);
  678. await act(async () => root.unmount());
  679. });
  680. it("renders image thumbnails above ordered file and context pills", async () => {
  681. const context: WebElementContextComposerAttachment = {
  682. capturedAt: 1_700_000_000_000,
  683. id: "element-1",
  684. pageTitle: "Docs",
  685. pageUrl: "https://example.test/docs",
  686. tagName: "button",
  687. text: "Submit",
  688. workspacePath: "/workspace",
  689. };
  690. const readAttachment = vi.fn().mockResolvedValue({
  691. bytes: new Uint8Array([137, 80, 78, 71]),
  692. mediaType: "image/png",
  693. });
  694. vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:sent-thumbnail");
  695. vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
  696. const comment: CodeCommentComposerAttachment = {
  697. id: "comment-1",
  698. workspacePath: "/workspace",
  699. sourcePath: "/workspace/app.ts",
  700. sourceTitle: "app.ts",
  701. selectedText: "const value = 1",
  702. comment: "检查这里",
  703. startLine: 1,
  704. endLine: 1,
  705. };
  706. const pptxElement: PptxElementReference = {
  707. id: "pptx-1",
  708. workspacePath: "/workspace",
  709. sourcePath: "/workspace/deck.pptx",
  710. sourceTitle: "deck.pptx",
  711. sourceFingerprint: `sha256:${"a".repeat(64)}`,
  712. slideIndex: 0,
  713. slidePart: "ppt/slides/slide1.xml",
  714. nodeId: "7",
  715. nodeName: "Title",
  716. nodeType: "shape",
  717. bounds: { x: 0, y: 0, width: 100, height: 30 },
  718. zIndex: 1,
  719. capturedAt: 1,
  720. };
  721. const selection: ConversationSelectionReference = {
  722. id: "selection-1",
  723. sourceSessionId: "source-session",
  724. sourceRowId: 8,
  725. contentType: "assistant",
  726. text: "selected answer",
  727. };
  728. const row = userInputRow({
  729. text: serializeComposerPromptContexts("", {
  730. codeComments: [comment],
  731. conversationSelections: [selection],
  732. pptxElements: [pptxElement],
  733. webElements: [context],
  734. }),
  735. attachments: [
  736. {
  737. ref: "/workspace/shot.png",
  738. fileName: "shot.png",
  739. mime: "image/png",
  740. bytes: 4,
  741. },
  742. {
  743. ref: "/workspace/demo.mov",
  744. fileName: "demo.mov",
  745. mime: "video/quicktime",
  746. bytes: 8,
  747. },
  748. {
  749. ref: "/workspace/note.txt",
  750. fileName: "note.txt",
  751. mime: "text/plain",
  752. bytes: 4,
  753. },
  754. ],
  755. });
  756. const container = installMinimalDom();
  757. const root: Root = createRoot(container);
  758. await act(async () => {
  759. root.render(
  760. createElement(
  761. ZCodeIntlProvider,
  762. { initialLocale: "zh-CN" },
  763. createElement(ConversationRowView, {
  764. context: { ...rowContext, readAttachment },
  765. row,
  766. }),
  767. ),
  768. );
  769. await Promise.resolve();
  770. await Promise.resolve();
  771. });
  772. const attachmentArea = findElementByAttribute(
  773. container,
  774. "data-v4-user-input-attachments",
  775. "true",
  776. );
  777. const imageRow = findElementByAttribute(
  778. attachmentArea,
  779. "data-v4-user-input-media-attachments",
  780. "true",
  781. );
  782. const pillRow = findElementByAttribute(
  783. attachmentArea,
  784. "data-v4-user-input-attachment-pills",
  785. "true",
  786. );
  787. const image = findElementByAttribute(imageRow, "data-v4-user-input-media-attachment", "true");
  788. // findElementByAttribute 只返回首个匹配;media 行内还有视频卡,按子节点序取第二个。
  789. const mediaCards = [...(imageRow as { childNodes?: unknown[] }).childNodes!].filter(
  790. (child) =>
  791. typeof child === "object" &&
  792. child !== null &&
  793. "getAttribute" in child &&
  794. (child as { getAttribute(name: string): string | null }).getAttribute(
  795. "data-v4-user-input-media-attachment",
  796. ) === "true",
  797. );
  798. const video = mediaCards[1] ?? null;
  799. const file = findElementByAttribute(pillRow, "data-v4-user-input-attachment-pill", "true");
  800. const web = findElementByAttribute(pillRow, "aria-label", "1 个网页元素");
  801. const codeComment = findElementByAttribute(pillRow, "aria-label", "1 条评论");
  802. const pptx = findElementByAttribute(pillRow, "aria-label", "1 个幻灯片元素");
  803. const conversation = findElementByAttribute(pillRow, "aria-label", "1 条对话引用");
  804. expect(imageRow?.parentNode).toBe(attachmentArea);
  805. expect(pillRow?.parentNode).toBe(attachmentArea);
  806. expect(image?.parentNode).toBe(imageRow);
  807. expect(video?.parentNode).toBe(imageRow);
  808. expect(file?.parentNode).toBe(pillRow);
  809. // 媒体行内按添加顺序混排图片与视频;视频不进入文件 pill 行。
  810. const mediaChildren = (imageRow as { childNodes?: unknown[] }).childNodes ?? [];
  811. expect(mediaChildren.indexOf(image)).toBeLessThan(mediaChildren.indexOf(video));
  812. expect(web?.parentNode).toBe(pillRow);
  813. const areaChildren = (attachmentArea as { childNodes?: unknown[] }).childNodes ?? [];
  814. expect(areaChildren.indexOf(imageRow)).toBeLessThan(areaChildren.indexOf(pillRow));
  815. const pillChildren = (pillRow as { childNodes?: unknown[] }).childNodes ?? [];
  816. expect([
  817. pillChildren.indexOf(file),
  818. pillChildren.indexOf(codeComment),
  819. pillChildren.indexOf(web),
  820. pillChildren.indexOf(pptx),
  821. pillChildren.indexOf(conversation),
  822. ]).toEqual(
  823. [...pillChildren]
  824. .map((child, index) => ({ child, index }))
  825. .filter(({ child }) => [file, codeComment, web, pptx, conversation].includes(child))
  826. .map(({ index }) => index),
  827. );
  828. expect(attachmentPropsById.get("42-0")).toMatchObject({
  829. variant: "grid",
  830. data: { url: "blob:sent-thumbnail" },
  831. });
  832. // 可见消息行会读取已发送视频,卡片复用 Blob URL 由无控件 video 展示首帧。
  833. expect(attachmentPropsById.get("42-1")).toMatchObject({
  834. variant: "grid",
  835. data: { url: "blob:sent-thumbnail", filename: "demo.mov" },
  836. });
  837. expect(readAttachment).toHaveBeenCalledWith({
  838. sessionId: "session-1",
  839. ref: "/workspace/demo.mov",
  840. mediaType: "video/quicktime",
  841. target: { rowId: 42, entityId: "message-user-42" },
  842. attachmentIndex: 1,
  843. signal: expect.any(AbortSignal),
  844. });
  845. const imageClasses = collectAttributeValues(image, "class").join(" ");
  846. expect(imageClasses).toContain("size-20");
  847. expect(imageClasses).toContain("rounded-xl");
  848. expect(imageClasses).not.toMatch(/(?:^|\s)border(?:\s|$)/u);
  849. expect(imageClasses).toContain("after:border");
  850. expect(imageClasses).toContain("after:pointer-events-none");
  851. const videoClasses = collectAttributeValues(video, "class").join(" ");
  852. expect(videoClasses).toContain("size-20");
  853. expect(videoClasses).toContain("rounded-xl");
  854. await act(async () => root.unmount());
  855. });
  856. it("opens sent images with the shared Markdown preview gallery and leaves non-images static", async () => {
  857. const readAttachment = vi.fn().mockResolvedValue({
  858. bytes: new Uint8Array([137, 80, 78, 71]),
  859. mediaType: "image/png",
  860. });
  861. const createObjectUrl = vi
  862. .spyOn(URL, "createObjectURL")
  863. .mockReturnValueOnce("blob:first-preview")
  864. .mockReturnValueOnce("blob:second-preview");
  865. const revokeObjectUrl = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
  866. const row = userInputRow({
  867. attachments: [
  868. {
  869. ref: "/workspace/first.png",
  870. fileName: "first.png",
  871. mime: "image/png",
  872. bytes: 4,
  873. },
  874. {
  875. ref: "/workspace/second.png",
  876. fileName: "second.png",
  877. mime: "image/png",
  878. bytes: 4,
  879. },
  880. {
  881. ref: "/workspace/note.txt",
  882. fileName: "note.txt",
  883. mime: "text/plain",
  884. bytes: 4,
  885. },
  886. ],
  887. });
  888. const root: Root = createRoot(installMinimalDom());
  889. await act(async () => {
  890. root.render(
  891. createElement(
  892. ZCodeIntlProvider,
  893. { initialLocale: "zh-CN" },
  894. createElement(ConversationRowView, {
  895. context: { ...rowContext, readAttachment },
  896. row,
  897. }),
  898. ),
  899. );
  900. });
  901. expect(attachmentPropsById.get("42-0")?.onOpen).toBeTypeOf("function");
  902. expect(attachmentPropsById.get("42-0")?.openLabel).toBe("打开图片预览");
  903. expect(attachmentPropsById.get("42-1")?.onOpen).toBeTypeOf("function");
  904. expect(attachmentPropsById.get("42-2")?.onOpen).toBeUndefined();
  905. const openPreview = attachmentPropsById.get("42-1")?.onOpen;
  906. expect(openPreview).toBeTypeOf("function");
  907. await act(async () => {
  908. (openPreview as () => void)();
  909. await Promise.resolve();
  910. await Promise.resolve();
  911. });
  912. expect(readAttachment).toHaveBeenCalledTimes(2);
  913. expect(createObjectUrl).toHaveBeenCalledTimes(2);
  914. expect(imagePreviewDialogProps.at(-1)).toMatchObject({
  915. open: true,
  916. initialIndex: 1,
  917. items: [
  918. { alt: "first.png", filename: "first.png", src: "blob:first-preview" },
  919. {
  920. alt: "second.png",
  921. filename: "second.png",
  922. src: "blob:second-preview",
  923. },
  924. ],
  925. });
  926. const onPreviewOpenChange = imagePreviewDialogProps.at(-1)?.onOpenChange;
  927. expect(onPreviewOpenChange).toBeTypeOf("function");
  928. await act(async () => {
  929. (onPreviewOpenChange as (open: boolean) => void)(false);
  930. });
  931. await act(async () => root.unmount());
  932. expect(revokeObjectUrl).toHaveBeenCalledWith("blob:first-preview");
  933. expect(revokeObjectUrl).toHaveBeenCalledWith("blob:second-preview");
  934. });
  935. it("opens sent videos in the shared mixed media gallery by exact row attachment", async () => {
  936. const readAttachment = vi.fn().mockResolvedValue({
  937. bytes: new Uint8Array([0, 0, 0, 24]),
  938. mediaType: "video/quicktime",
  939. });
  940. const createObjectUrl = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:sent-preview");
  941. const revokeObjectUrl = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
  942. const row = userInputRow({
  943. attachments: [
  944. {
  945. ref: "/workspace/shot.png",
  946. fileName: "shot.png",
  947. mime: "image/png",
  948. bytes: 4,
  949. },
  950. {
  951. ref: "/workspace/demo.mov",
  952. fileName: "demo.mov",
  953. mime: "video/quicktime",
  954. bytes: 4,
  955. },
  956. {
  957. ref: "/workspace/note.txt",
  958. fileName: "note.txt",
  959. mime: "text/plain",
  960. bytes: 4,
  961. },
  962. ],
  963. });
  964. const root: Root = createRoot(installMinimalDom());
  965. await act(async () => {
  966. root.render(
  967. createElement(
  968. ZCodeIntlProvider,
  969. { initialLocale: "zh-CN" },
  970. createElement(ConversationRowView, {
  971. context: { ...rowContext, readAttachment },
  972. row,
  973. }),
  974. ),
  975. );
  976. });
  977. expect(attachmentPropsById.get("42-0")?.onOpen).toBeTypeOf("function");
  978. expect(attachmentPropsById.get("42-0")?.openLabel).toBe("打开图片预览");
  979. expect(attachmentPropsById.get("42-1")?.onOpen).toBeTypeOf("function");
  980. expect(attachmentPropsById.get("42-1")?.openLabel).toBe("打开视频预览");
  981. expect(attachmentPropsById.get("42-2")?.onOpen).toBeUndefined();
  982. const openPreview = attachmentPropsById.get("42-1")?.onOpen;
  983. expect(openPreview).toBeTypeOf("function");
  984. await act(async () => {
  985. (openPreview as () => void)();
  986. await Promise.resolve();
  987. await Promise.resolve();
  988. });
  989. expect(readAttachment).toHaveBeenCalledWith({
  990. sessionId: "session-1",
  991. ref: "/workspace/demo.mov",
  992. mediaType: "video/quicktime",
  993. target: { rowId: 42, entityId: "message-user-42" },
  994. attachmentIndex: 1,
  995. signal: expect.any(AbortSignal),
  996. });
  997. // 挂载时 image/video 各读取一次;点击 video 复用首帧 Blob,不重复读取。
  998. expect(createObjectUrl).toHaveBeenCalledTimes(2);
  999. expect(imagePreviewDialogProps.at(-1)).toMatchObject({
  1000. open: true,
  1001. initialIndex: 1,
  1002. items: [
  1003. {
  1004. alt: "shot.png",
  1005. filename: "shot.png",
  1006. mediaType: "image/png",
  1007. src: expect.stringMatching(/^blob:/u),
  1008. },
  1009. {
  1010. alt: "demo.mov",
  1011. filename: "demo.mov",
  1012. mediaType: "video/quicktime",
  1013. src: "blob:sent-preview",
  1014. },
  1015. ],
  1016. });
  1017. const onPreviewOpenChange = imagePreviewDialogProps.at(-1)?.onOpenChange;
  1018. expect(onPreviewOpenChange).toBeTypeOf("function");
  1019. await act(async () => {
  1020. (onPreviewOpenChange as (open: boolean) => void)(false);
  1021. });
  1022. // gallery 关闭后首帧仍在消息卡片使用,直到消息行卸载才统一释放。
  1023. expect(revokeObjectUrl).not.toHaveBeenCalledWith("blob:sent-preview");
  1024. await act(async () => root.unmount());
  1025. expect(revokeObjectUrl).toHaveBeenCalledWith("blob:sent-preview");
  1026. });
  1027. it("loads a video when mixed-media gallery navigation selects it", async () => {
  1028. let resolveVideoPreview!: (value: { bytes: Uint8Array; mediaType: string }) => void;
  1029. let videoReads = 0;
  1030. const readAttachment = vi.fn(({ ref }: { ref: string }) => {
  1031. if (ref.endsWith("shot.png")) {
  1032. return Promise.resolve({
  1033. bytes: new Uint8Array([1, 2, 3]),
  1034. mediaType: "image/png",
  1035. });
  1036. }
  1037. videoReads += 1;
  1038. if (videoReads === 1) {
  1039. return Promise.reject(new Error("thumbnail prefetch failed"));
  1040. }
  1041. return new Promise<{ bytes: Uint8Array; mediaType: string }>((resolve) => {
  1042. resolveVideoPreview = resolve;
  1043. });
  1044. });
  1045. vi.spyOn(URL, "createObjectURL")
  1046. .mockReturnValueOnce("blob:image-preview")
  1047. .mockReturnValueOnce("blob:video-preview");
  1048. vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
  1049. const row = userInputRow({
  1050. attachments: [
  1051. {
  1052. ref: "/workspace/shot.png",
  1053. fileName: "shot.png",
  1054. mime: "image/png",
  1055. bytes: 3,
  1056. },
  1057. {
  1058. ref: "/workspace/demo.mp4",
  1059. fileName: "demo.mp4",
  1060. mime: "video/mp4",
  1061. bytes: 4,
  1062. },
  1063. ],
  1064. });
  1065. const root: Root = createRoot(installMinimalDom());
  1066. await act(async () => {
  1067. root.render(
  1068. createElement(
  1069. ZCodeIntlProvider,
  1070. { initialLocale: "zh-CN" },
  1071. createElement(ConversationRowView, {
  1072. context: { ...rowContext, readAttachment },
  1073. row,
  1074. }),
  1075. ),
  1076. );
  1077. await Promise.resolve();
  1078. await Promise.resolve();
  1079. });
  1080. const openImagePreview = attachmentPropsById.get("42-0")?.onOpen;
  1081. expect(openImagePreview).toBeTypeOf("function");
  1082. await act(async () => {
  1083. (openImagePreview as () => void)();
  1084. });
  1085. const onActiveIndexChange = imagePreviewDialogProps.at(-1)?.onActiveIndexChange as
  1086. | ((index: number) => void)
  1087. | undefined;
  1088. expect(onActiveIndexChange).toBeTypeOf("function");
  1089. await act(async () => {
  1090. onActiveIndexChange?.(1);
  1091. await Promise.resolve();
  1092. });
  1093. expect(readAttachment).toHaveBeenLastCalledWith({
  1094. sessionId: "session-1",
  1095. ref: "/workspace/demo.mp4",
  1096. mediaType: "video/mp4",
  1097. target: { rowId: 42, entityId: "message-user-42" },
  1098. attachmentIndex: 1,
  1099. signal: expect.any(AbortSignal),
  1100. });
  1101. expect(imagePreviewDialogProps.at(-1)).toMatchObject({
  1102. initialIndex: 1,
  1103. items: [
  1104. expect.objectContaining({ src: "blob:image-preview" }),
  1105. expect.objectContaining({ loading: true, src: undefined }),
  1106. ],
  1107. });
  1108. await act(async () => {
  1109. resolveVideoPreview({
  1110. bytes: new Uint8Array([0, 0, 0, 24]),
  1111. mediaType: "video/mp4",
  1112. });
  1113. await Promise.resolve();
  1114. await Promise.resolve();
  1115. });
  1116. expect(imagePreviewDialogProps.at(-1)).toMatchObject({
  1117. items: [
  1118. expect.objectContaining({ src: "blob:image-preview" }),
  1119. expect.objectContaining({ loading: false, src: "blob:video-preview" }),
  1120. ],
  1121. });
  1122. await act(async () => root.unmount());
  1123. });
  1124. it("opens a Desktop local media URL without creating or revoking a Blob URL", async () => {
  1125. const readAttachment = vi.fn().mockResolvedValue({
  1126. url: "zcode-media://local/desktop-video",
  1127. mediaType: "video/mp4",
  1128. });
  1129. const createObjectUrl = vi.spyOn(URL, "createObjectURL");
  1130. const revokeObjectUrl = vi.spyOn(URL, "revokeObjectURL");
  1131. const row = userInputRow({
  1132. attachments: [{ ref: "/tmp/demo.mp4", fileName: "demo.mp4", mime: "video/mp4", bytes: 1024 }],
  1133. });
  1134. const root: Root = createRoot(installMinimalDom());
  1135. await act(async () => {
  1136. root.render(
  1137. createElement(
  1138. ZCodeIntlProvider,
  1139. { initialLocale: "zh-CN" },
  1140. createElement(ConversationRowView, {
  1141. context: { ...rowContext, readAttachment },
  1142. row,
  1143. }),
  1144. ),
  1145. );
  1146. await Promise.resolve();
  1147. await Promise.resolve();
  1148. });
  1149. expect(readAttachment).toHaveBeenCalledWith({
  1150. sessionId: "session-1",
  1151. ref: "/tmp/demo.mp4",
  1152. mediaType: "video/mp4",
  1153. target: { rowId: row.rowId, entityId: row.entityId },
  1154. attachmentIndex: 0,
  1155. signal: expect.any(AbortSignal),
  1156. });
  1157. expect(attachmentPropsById.get(`${row.rowId}-0`)).toMatchObject({
  1158. data: { url: "zcode-media://local/desktop-video" },
  1159. });
  1160. const openPreview = attachmentPropsById.get(`${row.rowId}-0`)?.onOpen;
  1161. expect(openPreview).toBeTypeOf("function");
  1162. await act(async () => {
  1163. (openPreview as () => void)();
  1164. await Promise.resolve();
  1165. await Promise.resolve();
  1166. });
  1167. expect(imagePreviewDialogProps.at(-1)).toMatchObject({
  1168. open: true,
  1169. initialIndex: 0,
  1170. items: [
  1171. {
  1172. alt: "demo.mp4",
  1173. filename: "demo.mp4",
  1174. mediaType: "video/mp4",
  1175. src: "zcode-media://local/desktop-video",
  1176. loading: false,
  1177. error: false,
  1178. },
  1179. ],
  1180. });
  1181. expect(createObjectUrl).not.toHaveBeenCalled();
  1182. const closePreview = imagePreviewDialogProps.at(-1)?.onOpenChange;
  1183. expect(closePreview).toBeTypeOf("function");
  1184. await act(async () => {
  1185. (closePreview as (open: boolean) => void)(false);
  1186. });
  1187. expect(revokeObjectUrl).not.toHaveBeenCalled();
  1188. await act(async () => root.unmount());
  1189. });
  1190. it("aborts an unfinished sent media read when the preview closes", async () => {
  1191. let readSignal: AbortSignal | undefined;
  1192. const readAttachment = vi.fn(
  1193. (params: { signal?: AbortSignal }) =>
  1194. new Promise<{ bytes: Uint8Array; mediaType: string }>(() => {
  1195. readSignal = params.signal;
  1196. }),
  1197. );
  1198. const row = userInputRow({
  1199. attachments: [
  1200. {
  1201. ref: "/workspace/large.mp4",
  1202. fileName: "large.mp4",
  1203. mime: "video/mp4",
  1204. bytes: 80,
  1205. },
  1206. ],
  1207. });
  1208. const root: Root = createRoot(installMinimalDom());
  1209. await act(async () => {
  1210. root.render(
  1211. createElement(
  1212. ZCodeIntlProvider,
  1213. { initialLocale: "zh-CN" },
  1214. createElement(ConversationRowView, {
  1215. context: { ...rowContext, readAttachment },
  1216. row,
  1217. }),
  1218. ),
  1219. );
  1220. });
  1221. const openPreview = attachmentPropsById.get("42-0")?.onOpen;
  1222. expect(openPreview).toBeTypeOf("function");
  1223. await act(async () => {
  1224. (openPreview as () => void)();
  1225. await Promise.resolve();
  1226. });
  1227. expect(readSignal).toBeDefined();
  1228. expect(readSignal?.aborted).toBe(false);
  1229. const replacedSignal = readSignal;
  1230. await act(async () => {
  1231. (openPreview as () => void)();
  1232. await Promise.resolve();
  1233. });
  1234. expect(replacedSignal?.aborted).toBe(true);
  1235. expect(readSignal).not.toBe(replacedSignal);
  1236. expect(readSignal?.aborted).toBe(false);
  1237. const closePreview = imagePreviewDialogProps.at(-1)?.onOpenChange;
  1238. expect(closePreview).toBeTypeOf("function");
  1239. await act(async () => {
  1240. (closePreview as (open: boolean) => void)(false);
  1241. });
  1242. expect(readSignal?.aborted).toBe(true);
  1243. const closedSignal = readSignal;
  1244. await act(async () => {
  1245. (openPreview as () => void)();
  1246. await Promise.resolve();
  1247. });
  1248. expect(readSignal).not.toBe(closedSignal);
  1249. expect(readSignal?.aborted).toBe(false);
  1250. await act(async () => root.unmount());
  1251. expect(readSignal?.aborted).toBe(true);
  1252. });
  1253. it("aborts unfinished visible-row media prefetch when the row unmounts", async () => {
  1254. let prefetchSignal: AbortSignal | undefined;
  1255. const readAttachment = vi.fn(
  1256. (params: { signal?: AbortSignal }) =>
  1257. new Promise<{ bytes: Uint8Array; mediaType: string }>(() => {
  1258. prefetchSignal = params.signal;
  1259. }),
  1260. );
  1261. const row = userInputRow({
  1262. attachments: [
  1263. {
  1264. ref: "/workspace/large.mp4",
  1265. fileName: "large.mp4",
  1266. mime: "video/mp4",
  1267. bytes: 80,
  1268. },
  1269. ],
  1270. });
  1271. const root: Root = createRoot(installMinimalDom());
  1272. await act(async () => {
  1273. root.render(
  1274. createElement(
  1275. ZCodeIntlProvider,
  1276. { initialLocale: "zh-CN" },
  1277. createElement(ConversationRowView, {
  1278. context: { ...rowContext, readAttachment },
  1279. row,
  1280. }),
  1281. ),
  1282. );
  1283. await Promise.resolve();
  1284. });
  1285. expect(prefetchSignal).toBeDefined();
  1286. expect(prefetchSignal?.aborted).toBe(false);
  1287. await act(async () => root.unmount());
  1288. expect(prefetchSignal?.aborted).toBe(true);
  1289. });
  1290. it("marks an unreadable sent image unavailable and removes its open action", async () => {
  1291. const readAttachment = vi.fn().mockRejectedValue(new Error("gone"));
  1292. vi.spyOn(console, "warn").mockImplementation(() => {});
  1293. const row = userInputRow({
  1294. attachments: [
  1295. {
  1296. ref: "/workspace/gone.png",
  1297. fileName: "gone.png",
  1298. mime: "image/png",
  1299. bytes: 4,
  1300. },
  1301. ],
  1302. });
  1303. const root: Root = createRoot(installMinimalDom());
  1304. await act(async () => {
  1305. root.render(
  1306. createElement(
  1307. ZCodeIntlProvider,
  1308. { initialLocale: "zh-CN" },
  1309. createElement(ConversationRowView, {
  1310. context: { ...rowContext, readAttachment },
  1311. row,
  1312. }),
  1313. ),
  1314. );
  1315. });
  1316. expect(readAttachment).toHaveBeenCalledWith({
  1317. sessionId: "session-1",
  1318. ref: "/workspace/gone.png",
  1319. signal: expect.any(AbortSignal),
  1320. });
  1321. expect(attachmentPropsById.get("42-0")?.onOpen).toBeUndefined();
  1322. expect(attachmentPropsById.get("42-0")?.title).toBe("这张图片已无法预览。");
  1323. await act(async () => root.unmount());
  1324. });
  1325. // 回归:v4 迁移后用户行复制/编辑按钮硬编码中文,未走 i18n;
  1326. // en-US 下会显示「复制」「编辑」。文案必须跟随当前 locale。
  1327. it.each([
  1328. ["zh-CN", "复制", "编辑"],
  1329. ["en-US", "Copy", "Edit"],
  1330. ] as const)(
  1331. "renders user row copy/edit action labels from locale %s",
  1332. async (locale, copyLabel, editLabel) => {
  1333. const row = userInputRow();
  1334. const container = installMinimalDom();
  1335. const root: Root = createRoot(container);
  1336. await act(async () => {
  1337. root.render(
  1338. createElement(
  1339. ZCodeIntlProvider,
  1340. { initialLocale: locale },
  1341. createElement(ConversationRowView, {
  1342. context: rowContext,
  1343. onEdit: vi.fn(),
  1344. row,
  1345. }),
  1346. ),
  1347. );
  1348. });
  1349. const copyAction = messageActionPropsByTestId.get(`v4-copy-${row.rowId}`);
  1350. expect(copyAction?.label).toBe(copyLabel);
  1351. expect(copyAction?.tooltip).toBe(copyLabel);
  1352. const editAction = messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)));
  1353. expect(editAction?.label).toBe(editLabel);
  1354. expect(editAction?.tooltip).toBe(editLabel);
  1355. await act(async () => {
  1356. root.unmount();
  1357. });
  1358. },
  1359. );
  1360. it("keeps user message actions visible in compact remote control mode", async () => {
  1361. const row = userInputRow();
  1362. const container = installMinimalDom();
  1363. const root: Root = createRoot(container);
  1364. await act(async () => {
  1365. root.render(
  1366. createElement(
  1367. ZCodeIntlProvider,
  1368. { initialLocale: "zh-CN" },
  1369. createElement(ConversationRowView, {
  1370. context: { ...rowContext, compactForRemoteControl: true },
  1371. row,
  1372. onEdit: vi.fn(),
  1373. }),
  1374. ),
  1375. );
  1376. });
  1377. const actionsClassName = collectAttributeValues(container, "class").find((value) =>
  1378. value.includes("mt-1 opacity"),
  1379. );
  1380. expect(actionsClassName).toContain("opacity-100");
  1381. expect(actionsClassName).not.toContain("opacity-0");
  1382. await act(async () => {
  1383. root.unmount();
  1384. });
  1385. });
  1386. it("keeps assistant feedback local to the mounted action toolbar", async () => {
  1387. const row = assistantTextRow({
  1388. entityId: "message-assistant-43",
  1389. state: "complete",
  1390. });
  1391. const root: Root = createRoot(installMinimalDom());
  1392. await act(async () => {
  1393. root.render(
  1394. createElement(
  1395. ZCodeIntlProvider,
  1396. { initialLocale: "zh-CN" },
  1397. createElement(ConversationRowView, {
  1398. context: { ...rowContext, compactForRemoteControl: true },
  1399. row,
  1400. onFeedbackChange: vi.fn(async () => true),
  1401. }),
  1402. ),
  1403. );
  1404. });
  1405. const likeTestId = testId(TID_V4_FEEDBACK_LIKE, String(row.rowId));
  1406. const dislikeTestId = testId(TID_V4_FEEDBACK_DISLIKE, String(row.rowId));
  1407. expect(messageActionPropsByTestId.get(likeTestId)?.["aria-pressed"]).toBe(false);
  1408. expect(messageActionPropsByTestId.get(dislikeTestId)?.["aria-pressed"]).toBe(false);
  1409. expect(messageActionPropsByTestId.get(likeTestId)?.tooltip).toBeUndefined();
  1410. const handleLike = messageActionPropsByTestId.get(likeTestId)?.onClick;
  1411. expect(handleLike).toBeTypeOf("function");
  1412. await act(async () => {
  1413. (handleLike as () => void)();
  1414. });
  1415. expect(messageActionPropsByTestId.get(likeTestId)?.["aria-pressed"]).toBe(true);
  1416. expect(messageActionPropsByTestId.get(dislikeTestId)?.["aria-pressed"]).toBe(false);
  1417. const handleLikeAgain = messageActionPropsByTestId.get(likeTestId)?.onClick;
  1418. expect(handleLikeAgain).toBeTypeOf("function");
  1419. await act(async () => {
  1420. (handleLikeAgain as () => void)();
  1421. });
  1422. expect(messageActionPropsByTestId.get(likeTestId)?.["aria-pressed"]).toBe(false);
  1423. expect(messageActionPropsByTestId.get(dislikeTestId)?.["aria-pressed"]).toBe(false);
  1424. const handleDislike = messageActionPropsByTestId.get(dislikeTestId)?.onClick;
  1425. expect(handleDislike).toBeTypeOf("function");
  1426. await act(async () => {
  1427. (handleDislike as () => void)();
  1428. });
  1429. expect(messageActionPropsByTestId.get(likeTestId)?.["aria-pressed"]).toBe(false);
  1430. expect(messageActionPropsByTestId.get(dislikeTestId)?.["aria-pressed"]).toBe(true);
  1431. await act(async () => {
  1432. root.unmount();
  1433. });
  1434. });
  1435. it("does not append a visual cursor to streaming assistant text", async () => {
  1436. const row = assistantTextRow();
  1437. const container = installMinimalDom();
  1438. const root: Root = createRoot(container);
  1439. await act(async () => {
  1440. root.render(
  1441. createElement(
  1442. ZCodeIntlProvider,
  1443. { initialLocale: "zh-CN" },
  1444. createElement(ConversationRowView, {
  1445. context: rowContext,
  1446. row,
  1447. }),
  1448. ),
  1449. );
  1450. });
  1451. expect(collectText(container)).toContain(row.text);
  1452. const classValues = collectAttributeValues(container, "class");
  1453. expect(classValues.join(" ")).not.toContain("animate-pulse");
  1454. await act(async () => {
  1455. root.unmount();
  1456. });
  1457. });
  1458. it.each(["complete", "streaming"] as const)(
  1459. "puts assistant %s text inside a real selectable DOM region",
  1460. async (state) => {
  1461. const row = assistantTextRow({ state });
  1462. const container = installMinimalDom();
  1463. const root: Root = createRoot(container);
  1464. await act(async () => {
  1465. root.render(
  1466. createElement(
  1467. ZCodeIntlProvider,
  1468. { initialLocale: "zh-CN" },
  1469. createElement(ConversationRowView, {
  1470. context: rowContext,
  1471. row,
  1472. }),
  1473. ),
  1474. );
  1475. });
  1476. expect(collectAttributeValues(container, "data-conversation-selectable")).toContain("true");
  1477. // 回归根因:标记不能继续依赖不透传 data-* 的 MessageResponse。
  1478. expect(messageResponseProps.at(-1)?.["data-conversation-selectable"]).toBeUndefined();
  1479. await act(async () => {
  1480. root.unmount();
  1481. });
  1482. },
  1483. );
  1484. it("保持显式 Markdown 文件处理器,仅为 Assistant 开启 citation 投影", async () => {
  1485. const row = assistantTextRow({
  1486. state: "complete",
  1487. text: "See [README](./README.md) and https://example.test.",
  1488. });
  1489. const onOpenBrowserUrl = vi.fn();
  1490. const onOpenCodeViewer = vi.fn();
  1491. const onOpenFileLink = vi.fn();
  1492. const readAttachment = vi.fn();
  1493. const container = installMinimalDom();
  1494. const root: Root = createRoot(container);
  1495. await act(async () => {
  1496. root.render(
  1497. createElement(
  1498. ZCodeIntlProvider,
  1499. { initialLocale: "zh-CN" },
  1500. createElement(ConversationRowView, {
  1501. context: {
  1502. ...rowContext,
  1503. onOpenBrowserUrl,
  1504. onOpenCodeViewer,
  1505. onOpenFileLink,
  1506. readAttachment,
  1507. },
  1508. row,
  1509. }),
  1510. ),
  1511. );
  1512. });
  1513. expect(messageResponseProps).toHaveLength(1);
  1514. expect(messageResponseProps[0]?.onOpenExternalUrl).toBe(onOpenBrowserUrl);
  1515. expect(messageResponseProps[0]?.onOpenCodeViewer).toBe(onOpenCodeViewer);
  1516. expect(messageResponseProps[0]?.onOpenFileLink).toBe(onOpenFileLink);
  1517. expect(messageResponseProps[0]?.renderZCodeFileCitations).toBe(true);
  1518. // 回归根因:artifact 图片读取能力必须由行级生产接线继续传入 Markdown。
  1519. expect(messageResponseProps[0]?.sessionId).toBe("session-1");
  1520. expect(messageResponseProps[0]?.readAttachment).toBe(readAttachment);
  1521. await act(async () => {
  1522. root.unmount();
  1523. });
  1524. });
  1525. it("renders web element contexts as read-only chips while keeping the raw row text for actions", async () => {
  1526. const context: WebElementContextComposerAttachment = {
  1527. capturedAt: 1_700_000_000_000,
  1528. id: "element-1",
  1529. pageTitle: "Docs",
  1530. pageUrl: "https://example.test/docs",
  1531. role: "button",
  1532. tagName: "button",
  1533. text: "Submit",
  1534. workspaceIdentity: "remote:workspace",
  1535. workspacePath: "/workspace",
  1536. };
  1537. const rawText = buildPromptWithWebElementContexts("帮我看这个按钮", [context]);
  1538. const row = userInputRow({
  1539. text: rawText,
  1540. });
  1541. const container = installMinimalDom();
  1542. const root: Root = createRoot(container);
  1543. await act(async () => {
  1544. root.render(
  1545. createElement(
  1546. ZCodeIntlProvider,
  1547. { initialLocale: "zh-CN" },
  1548. createElement(ConversationRowView, {
  1549. context: rowContext,
  1550. onEdit: vi.fn(),
  1551. row,
  1552. }),
  1553. ),
  1554. );
  1555. });
  1556. const text = collectText(container);
  1557. expect(text).toContain("帮我看这个按钮");
  1558. expect(text).toContain("1 个网页元素");
  1559. expect(text).not.toContain("# Web page elements:");
  1560. const attachmentArea = findElementByAttribute(
  1561. container,
  1562. "data-v4-user-input-attachments",
  1563. "true",
  1564. );
  1565. const messageBubble = findElementByAttribute(container, "data-v4-user-input-bubble", "true");
  1566. expect(collectText(attachmentArea)).toContain("note.txt");
  1567. expect(collectText(attachmentArea)).toContain("1 个网页元素");
  1568. expect(collectText(messageBubble)).toBe("帮我看这个按钮");
  1569. const fileAttachmentPill = findElementByAttribute(
  1570. attachmentArea,
  1571. "data-v4-user-input-attachment-pill",
  1572. "true",
  1573. );
  1574. const webElementChip = findElementByAttribute(attachmentArea, "aria-label", "1 个网页元素");
  1575. const pillRow = findElementByAttribute(
  1576. attachmentArea,
  1577. "data-v4-user-input-attachment-pills",
  1578. "true",
  1579. );
  1580. expect(fileAttachmentPill?.parentNode).toBe(pillRow);
  1581. expect(webElementChip?.parentNode).toBe(pillRow);
  1582. expect(collectAttributeValues(webElementChip, "class").join(" ")).toContain("rounded-full");
  1583. const copyAction = messageActionPropsByTestId.get(`v4-copy-${row.rowId}`);
  1584. expect(copyAction).toBeDefined();
  1585. expect(copyAction?.disabled).toBe(false);
  1586. await act(async () => {
  1587. root.unmount();
  1588. });
  1589. });
  1590. it("right-aligns PPT and conversation-reference hover cards in sent user rows", async () => {
  1591. const pptxElement: PptxElementReference = {
  1592. id: "pptx-1",
  1593. workspacePath: "/workspace",
  1594. sourcePath: "/workspace/deck.pptx",
  1595. sourceTitle: "deck.pptx",
  1596. sourceFingerprint: `sha256:${"a".repeat(64)}`,
  1597. slideIndex: 0,
  1598. slidePart: "ppt/slides/slide1.xml",
  1599. nodeId: "7",
  1600. nodeName: "Title",
  1601. nodeType: "shape",
  1602. bounds: { x: 0, y: 0, width: 100, height: 30 },
  1603. zIndex: 1,
  1604. capturedAt: 1,
  1605. };
  1606. const selection: ConversationSelectionReference = {
  1607. id: "selection-1",
  1608. sourceSessionId: "source-session",
  1609. sourceRowId: 8,
  1610. contentType: "assistant",
  1611. text: "selected answer",
  1612. };
  1613. const row = userInputRow({
  1614. text: serializeComposerPromptContexts("请处理", {
  1615. codeComments: [],
  1616. conversationSelections: [selection],
  1617. pptxElements: [pptxElement],
  1618. webElements: [],
  1619. }),
  1620. });
  1621. const container = installMinimalDom();
  1622. const root: Root = createRoot(container);
  1623. await act(async () => {
  1624. root.render(
  1625. createElement(
  1626. ZCodeIntlProvider,
  1627. { initialLocale: "zh-CN" },
  1628. createElement(ConversationRowView, {
  1629. context: rowContext,
  1630. onEdit: vi.fn(),
  1631. row,
  1632. }),
  1633. ),
  1634. );
  1635. });
  1636. expect(hoverCardContentProps).toHaveLength(4);
  1637. expect(hoverCardContentProps.every((props) => props.align === "end")).toBe(true);
  1638. await act(async () => {
  1639. root.unmount();
  1640. });
  1641. });
  1642. it("does not render a bubble when a user row only contains context references", async () => {
  1643. const context: WebElementContextComposerAttachment = {
  1644. capturedAt: 1_700_000_000_000,
  1645. id: "element-only",
  1646. pageTitle: "Docs",
  1647. pageUrl: "https://example.test/docs",
  1648. tagName: "main",
  1649. text: "Content",
  1650. workspaceIdentity: "remote:workspace",
  1651. workspacePath: "/workspace",
  1652. };
  1653. const container = installMinimalDom();
  1654. const root: Root = createRoot(container);
  1655. await act(async () => {
  1656. root.render(
  1657. createElement(
  1658. ZCodeIntlProvider,
  1659. { initialLocale: "zh-CN" },
  1660. createElement(ConversationRowView, {
  1661. context: rowContext,
  1662. row: userInputRow({
  1663. attachments: [],
  1664. text: buildPromptWithWebElementContexts("", [context]),
  1665. }),
  1666. }),
  1667. ),
  1668. );
  1669. });
  1670. expect(
  1671. findElementByAttribute(container, "data-v4-user-input-attachments", "true"),
  1672. ).not.toBeNull();
  1673. expect(findElementByAttribute(container, "data-v4-user-input-bubble", "true")).toBeNull();
  1674. await act(async () => root.unmount());
  1675. });
  1676. it("renders an authoritative goal query without the slash", async () => {
  1677. const row = userInputRow({
  1678. attachments: [],
  1679. text: "/goal 看一下这是个啥项目",
  1680. });
  1681. const container = installMinimalDom();
  1682. const root: Root = createRoot(container);
  1683. await act(async () => {
  1684. root.render(
  1685. createElement(
  1686. ZCodeIntlProvider,
  1687. { initialLocale: "zh-CN" },
  1688. createElement(ConversationRowView, {
  1689. context: rowContext,
  1690. row,
  1691. }),
  1692. ),
  1693. );
  1694. });
  1695. expect(collectText(container)).toContain("goal 看一下这是个啥项目");
  1696. expect(collectText(container)).not.toContain("/goal");
  1697. expect(collectAttributeValues(container, "class").join(" ")).toContain("lucide-goal");
  1698. expect(collectAttributeValues(container, "data-v4-user-input-command")).toContain("goal");
  1699. await act(async () => {
  1700. root.unmount();
  1701. });
  1702. });
  1703. it("opens an inline editor and submits edited text with original attachments", async () => {
  1704. const onEdit = vi.fn(async () => true);
  1705. const row = userInputRow();
  1706. const root: Root = createRoot(installMinimalDom());
  1707. await act(async () => {
  1708. root.render(
  1709. createElement(
  1710. ZCodeIntlProvider,
  1711. { initialLocale: "zh-CN" },
  1712. createElement(ConversationRowView, {
  1713. context: rowContext,
  1714. onEdit,
  1715. row,
  1716. }),
  1717. ),
  1718. );
  1719. });
  1720. const editAction = messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)));
  1721. expect(editAction).toBeDefined();
  1722. const editOnClick = editAction?.onClick;
  1723. expect(typeof editOnClick).toBe("function");
  1724. await act(async () => {
  1725. (editOnClick as () => void)();
  1726. });
  1727. expect(chatPromptEditorProps).toHaveLength(1);
  1728. expect(chatPromptEditorProps[0]?.initialValue).toBe(row.text);
  1729. const submitEdit = chatPromptEditorProps[0]?.onSubmit;
  1730. expect(typeof submitEdit).toBe("function");
  1731. await act(async () => {
  1732. await (submitEdit as (value: string) => Promise<void>)("改过的问题");
  1733. });
  1734. expect(onEdit).toHaveBeenCalledWith(
  1735. { rowId: row.rowId, entityId: row.entityId },
  1736. "改过的问题",
  1737. row.attachments,
  1738. "preserve",
  1739. );
  1740. await act(async () => {
  1741. root.unmount();
  1742. });
  1743. });
  1744. it("renders edit attachments like the composer and submits the remaining refs in source order", async () => {
  1745. const onEdit = vi.fn(async () => true);
  1746. const row = userInputRow({
  1747. text: "",
  1748. attachments: [
  1749. {
  1750. bytes: 12,
  1751. fileName: "first.txt",
  1752. mime: "text/plain",
  1753. ref: "/workspace/first.txt",
  1754. },
  1755. {
  1756. bytes: 24,
  1757. fileName: "second.png",
  1758. mime: "image/png",
  1759. ref: "/workspace/second.png",
  1760. },
  1761. {
  1762. bytes: 48,
  1763. fileName: "third.mov",
  1764. mime: "video/quicktime",
  1765. ref: "/workspace/third.mov",
  1766. },
  1767. ],
  1768. });
  1769. const root: Root = createRoot(installMinimalDom());
  1770. await act(async () => {
  1771. root.render(
  1772. createElement(
  1773. ZCodeIntlProvider,
  1774. { initialLocale: "zh-CN" },
  1775. createElement(ConversationRowView, {
  1776. context: rowContext,
  1777. onEdit,
  1778. row,
  1779. }),
  1780. ),
  1781. );
  1782. });
  1783. await act(async () => {
  1784. (
  1785. messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)))?.onClick as
  1786. | (() => void)
  1787. | undefined
  1788. )?.();
  1789. });
  1790. // 编辑态按「媒体优先、组内原序」排列:second.png、third.mov 为媒体卡,first.txt 为文件卡。
  1791. expect(attachmentPropsById.get(`${row.rowId}-1`)).toMatchObject({
  1792. className: expect.stringContaining("size-12"),
  1793. variant: "grid",
  1794. "data-v4-user-edit-attachment-kind": "image",
  1795. });
  1796. expect(attachmentPropsById.get(`${row.rowId}-2`)).toMatchObject({
  1797. className: expect.stringContaining("size-12"),
  1798. variant: "grid",
  1799. "data-v4-user-edit-attachment-kind": "video",
  1800. });
  1801. expect(attachmentPropsById.get(`${row.rowId}-0`)).toMatchObject({
  1802. className: expect.stringContaining("h-12"),
  1803. variant: "inline",
  1804. "data-v4-user-edit-attachment-kind": "file",
  1805. });
  1806. const firstRemoveId = testId(TID_V4_EDIT_ATTACHMENT_REMOVE, `${row.rowId}-0`);
  1807. const secondRemoveId = testId(TID_V4_EDIT_ATTACHMENT_REMOVE, `${row.rowId}-1`);
  1808. expect(attachmentRemovePropsByTestId.get(firstRemoveId)).toMatchObject({
  1809. alwaysVisible: undefined,
  1810. className: expect.stringContaining("size-3.5"),
  1811. label: "移除附件",
  1812. placement: "corner",
  1813. variant: "default",
  1814. });
  1815. expect(attachmentRemovePropsByTestId.get(secondRemoveId)).toBeDefined();
  1816. await act(async () => {
  1817. (attachmentRemovePropsByTestId.get(firstRemoveId)!.onClick as () => void)();
  1818. });
  1819. expect(chatPromptEditorProps.at(-1)?.allowSubmitWhenEmpty).toBe(true);
  1820. expect(chatPromptEditorProps.at(-1)?.submitDisabled).toBe(false);
  1821. await act(async () => {
  1822. await (chatPromptEditorProps.at(-1)!.onSubmit as (value: string) => Promise<void>)("");
  1823. });
  1824. expect(onEdit).toHaveBeenCalledWith(
  1825. { rowId: row.rowId, entityId: row.entityId },
  1826. "",
  1827. [row.attachments?.[1], row.attachments?.[2]],
  1828. "preserve",
  1829. );
  1830. await act(async () => root.unmount());
  1831. });
  1832. it("renders prompt contexts in the edit second row and keeps protocol text out of the editor", async () => {
  1833. const onEdit = vi.fn(async () => true);
  1834. const webContext: WebElementContextComposerAttachment = {
  1835. capturedAt: 1_700_000_000_000,
  1836. id: "edit-web-element",
  1837. pageTitle: "Docs",
  1838. pageUrl: "https://example.test/docs",
  1839. selector: "main",
  1840. tagName: "main",
  1841. workspacePath: "/workspace",
  1842. };
  1843. const row = userInputRow({
  1844. attachments: [],
  1845. text: buildPromptWithWebElementContexts("改一下", [webContext]),
  1846. });
  1847. const container = installMinimalDom();
  1848. const root: Root = createRoot(container);
  1849. await act(async () => {
  1850. root.render(
  1851. createElement(
  1852. ZCodeIntlProvider,
  1853. { initialLocale: "zh-CN" },
  1854. createElement(ConversationRowView, {
  1855. context: rowContext,
  1856. onEdit,
  1857. row,
  1858. }),
  1859. ),
  1860. );
  1861. });
  1862. await act(async () => {
  1863. (
  1864. messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)))?.onClick as
  1865. | (() => void)
  1866. | undefined
  1867. )?.();
  1868. });
  1869. expect(chatPromptEditorProps.at(-1)?.initialValue).toBe("改一下");
  1870. const contextRow = findElementByAttribute(
  1871. container,
  1872. "data-v4-user-edit-context-attachments-row",
  1873. "true",
  1874. );
  1875. expect(contextRow).not.toBeNull();
  1876. expect(collectText(contextRow)).toContain("1 个网页元素");
  1877. await act(async () => {
  1878. await (chatPromptEditorProps.at(-1)!.onSubmit as (value: string) => Promise<void>)("更新");
  1879. });
  1880. expect(onEdit).toHaveBeenCalledWith(
  1881. { rowId: row.rowId, entityId: row.entityId },
  1882. buildPromptWithWebElementContexts("更新", [webContext]),
  1883. [],
  1884. "preserve",
  1885. );
  1886. await act(async () => root.unmount());
  1887. });
  1888. it("rejects an edit only after both text and attachments become empty", async () => {
  1889. const onEdit = vi.fn(async () => true);
  1890. const row = userInputRow({ text: "" });
  1891. const root: Root = createRoot(installMinimalDom());
  1892. await act(async () => {
  1893. root.render(
  1894. createElement(
  1895. ZCodeIntlProvider,
  1896. { initialLocale: "zh-CN" },
  1897. createElement(ConversationRowView, {
  1898. context: rowContext,
  1899. onEdit,
  1900. row,
  1901. }),
  1902. ),
  1903. );
  1904. });
  1905. await act(async () => {
  1906. (
  1907. messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)))?.onClick as
  1908. | (() => void)
  1909. | undefined
  1910. )?.();
  1911. });
  1912. expect(chatPromptEditorProps.at(-1)?.submitDisabled).toBe(false);
  1913. await act(async () => {
  1914. (
  1915. attachmentRemovePropsByTestId.get(testId(TID_V4_EDIT_ATTACHMENT_REMOVE, `${row.rowId}-0`))!
  1916. .onClick as () => void
  1917. )();
  1918. });
  1919. expect(chatPromptEditorProps.at(-1)?.allowSubmitWhenEmpty).toBe(false);
  1920. expect(chatPromptEditorProps.at(-1)?.submitDisabled).toBe(true);
  1921. await act(async () => {
  1922. await (chatPromptEditorProps.at(-1)!.onSubmit as (value: string) => Promise<void>)(" ");
  1923. });
  1924. expect(onEdit).not.toHaveBeenCalled();
  1925. await act(async () => root.unmount());
  1926. });
  1927. it("restores the original attachment list after cancelling and reopening edit", async () => {
  1928. const onEdit = vi.fn(async () => true);
  1929. const row = userInputRow({
  1930. attachments: [
  1931. ...(userInputRow().attachments ?? []),
  1932. {
  1933. bytes: 24,
  1934. fileName: "second.txt",
  1935. mime: "text/plain",
  1936. ref: "/workspace/second.txt",
  1937. },
  1938. ],
  1939. });
  1940. const root: Root = createRoot(installMinimalDom());
  1941. await act(async () => {
  1942. root.render(
  1943. createElement(
  1944. ZCodeIntlProvider,
  1945. { initialLocale: "zh-CN" },
  1946. createElement(ConversationRowView, {
  1947. context: rowContext,
  1948. onEdit,
  1949. row,
  1950. }),
  1951. ),
  1952. );
  1953. });
  1954. await act(async () => {
  1955. (
  1956. messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)))?.onClick as
  1957. | (() => void)
  1958. | undefined
  1959. )?.();
  1960. });
  1961. await act(async () => {
  1962. (
  1963. attachmentRemovePropsByTestId.get(testId(TID_V4_EDIT_ATTACHMENT_REMOVE, `${row.rowId}-0`))!
  1964. .onClick as () => void
  1965. )();
  1966. (chatPromptEditorProps.at(-1)!.onCancel as () => void)();
  1967. });
  1968. await act(async () => {
  1969. (
  1970. messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)))?.onClick as
  1971. | (() => void)
  1972. | undefined
  1973. )?.();
  1974. });
  1975. await act(async () => {
  1976. await (chatPromptEditorProps.at(-1)!.onSubmit as (value: string) => Promise<void>)(row.text);
  1977. });
  1978. expect(onEdit).toHaveBeenCalledWith(
  1979. { rowId: row.rowId, entityId: row.entityId },
  1980. row.text,
  1981. row.attachments,
  1982. "preserve",
  1983. );
  1984. await act(async () => root.unmount());
  1985. });
  1986. it("keeps removed refs after a failed ACK and leaves 15360+ pasted text in the editor", async () => {
  1987. const onEdit = vi.fn(async () => false);
  1988. const row = userInputRow({
  1989. attachments: [
  1990. ...(userInputRow().attachments ?? []),
  1991. {
  1992. bytes: 24,
  1993. fileName: "second.txt",
  1994. mime: "text/plain",
  1995. ref: "/workspace/second.txt",
  1996. },
  1997. ],
  1998. });
  1999. const longText = "长".repeat(15_361);
  2000. const root: Root = createRoot(installMinimalDom());
  2001. await act(async () => {
  2002. root.render(
  2003. createElement(
  2004. ZCodeIntlProvider,
  2005. { initialLocale: "zh-CN" },
  2006. createElement(ConversationRowView, {
  2007. context: rowContext,
  2008. onEdit,
  2009. row,
  2010. }),
  2011. ),
  2012. );
  2013. });
  2014. await act(async () => {
  2015. (
  2016. messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)))?.onClick as
  2017. | (() => void)
  2018. | undefined
  2019. )?.();
  2020. });
  2021. expect(chatPromptEditorProps.at(-1)?.onPaste).toBeUndefined();
  2022. await act(async () => {
  2023. (
  2024. attachmentRemovePropsByTestId.get(testId(TID_V4_EDIT_ATTACHMENT_REMOVE, `${row.rowId}-0`))!
  2025. .onClick as () => void
  2026. )();
  2027. (chatPromptEditorProps.at(-1)!.onChange as (value: string) => void)(longText);
  2028. });
  2029. await act(async () => {
  2030. await (chatPromptEditorProps.at(-1)!.onSubmit as (value: string) => Promise<void>)(longText);
  2031. });
  2032. expect(onEdit).toHaveBeenCalledWith(
  2033. { rowId: row.rowId, entityId: row.entityId },
  2034. longText,
  2035. [row.attachments?.[1]],
  2036. "preserve",
  2037. );
  2038. expect(chatPromptEditorProps.at(-1)?.initialValue).toBe(row.text);
  2039. expect(
  2040. attachmentRemovePropsByTestId.has(testId(TID_V4_EDIT_ATTACHMENT_REMOVE, `${row.rowId}-0`)),
  2041. ).toBe(true);
  2042. await act(async () => root.unmount());
  2043. });
  2044. it("keeps the disabled file reset tooltip hoverable and explains why it is unavailable", async () => {
  2045. const row = userInputRow();
  2046. const root: Root = createRoot(installMinimalDom());
  2047. await act(async () => {
  2048. root.render(
  2049. createElement(
  2050. ZCodeIntlProvider,
  2051. { initialLocale: "zh-CN" },
  2052. createElement(ConversationRowView, {
  2053. context: rowContext,
  2054. editWorkspaceRewindAvailability: {
  2055. enabled: false,
  2056. reason: "noFiles",
  2057. },
  2058. onEdit: vi.fn(),
  2059. row,
  2060. }),
  2061. ),
  2062. );
  2063. });
  2064. const editAction = messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)));
  2065. const editOnClick = editAction?.onClick;
  2066. expect(editOnClick).toBeTypeOf("function");
  2067. await act(async () => {
  2068. (editOnClick as () => void)();
  2069. });
  2070. const slot = chatPromptEditorProps.at(-1)?.betweenCancelAndSubmitAction as ReactElement<{
  2071. description?: string;
  2072. title: string;
  2073. children: ReactElement<Record<string, unknown>>;
  2074. }>;
  2075. const disabledTooltipTrigger = slot.props.children;
  2076. const rewindButton = disabledTooltipTrigger.props.children as ReactElement<
  2077. Record<string, unknown>
  2078. >;
  2079. expect(slot.props.title).toBe("与文件一起重置");
  2080. expect(slot.props.description).toBe("本轮没有可安全恢复的文件改动");
  2081. expect(disabledTooltipTrigger.type).toBe("span");
  2082. expect(disabledTooltipTrigger.props["data-disabled-tooltip-trigger"]).toBe("true");
  2083. expect(rewindButton.props.disabled).toBe(true);
  2084. expect(rewindButton.props.size).toBe("icon-md");
  2085. expect((rewindButton.props.children as ReactElement).type).toBe(FileClockIcon);
  2086. await act(async () => {
  2087. root.unmount();
  2088. });
  2089. });
  2090. it("keeps the file+conversation action between cancel and send and falls back after a blocked preview", async () => {
  2091. const preview = {
  2092. canApply: false,
  2093. safeFiles: [],
  2094. unsafeFiles: [
  2095. {
  2096. action: "restore" as const,
  2097. operationCount: 1,
  2098. path: "/workspace/note.txt",
  2099. reason: "external_modified" as const,
  2100. toolNames: ["Write"],
  2101. },
  2102. ],
  2103. ignoredFiles: [],
  2104. };
  2105. const onEdit = vi
  2106. .fn()
  2107. .mockResolvedValueOnce({
  2108. commandId: "edit-rewind-command",
  2109. accepted: true,
  2110. result: {
  2111. type: "editUserQuery",
  2112. disposition: "blocked",
  2113. preview,
  2114. reasonCode: "edit.workspaceRewindBlocked",
  2115. },
  2116. })
  2117. .mockResolvedValueOnce({
  2118. commandId: "edit-conversation-only-command",
  2119. accepted: true,
  2120. result: { type: "editUserQuery", disposition: "rewind" },
  2121. });
  2122. const row = userInputRow();
  2123. const root: Root = createRoot(installMinimalDom());
  2124. await act(async () => {
  2125. root.render(
  2126. createElement(
  2127. ZCodeIntlProvider,
  2128. { initialLocale: "zh-CN" },
  2129. createElement(ConversationRowView, {
  2130. context: rowContext,
  2131. editWorkspaceRewindAvailability: {
  2132. enabled: true,
  2133. reason: "available",
  2134. },
  2135. onEdit,
  2136. row,
  2137. }),
  2138. ),
  2139. );
  2140. });
  2141. const editAction = messageActionPropsByTestId.get(testId(TID_V4_EDIT, String(row.rowId)));
  2142. const editOnClick = editAction?.onClick;
  2143. expect(editOnClick).toBeTypeOf("function");
  2144. await act(async () => {
  2145. (editOnClick as () => void)();
  2146. });
  2147. const slot = chatPromptEditorProps.at(-1)?.betweenCancelAndSubmitAction as ReactElement<{
  2148. description?: string;
  2149. title: string;
  2150. children: ReactElement<Record<string, unknown>>;
  2151. }>;
  2152. const rewindButton = slot.props.children;
  2153. expect(slot.props.title).toBe("与文件一起重置");
  2154. expect(slot.props.description).toBeUndefined();
  2155. expect(rewindButton.props["data-testid"]).toBe(
  2156. testId(TID_V4_EDIT_REWIND_WORKSPACE, String(row.rowId)),
  2157. );
  2158. expect(rewindButton.props.disabled).toBe(false);
  2159. expect(rewindButton.props.size).toBe("icon-md");
  2160. expect(rewindButton.props.children).toMatchObject({
  2161. type: FileClockIcon,
  2162. props: { className: "size-4" },
  2163. });
  2164. await act(async () => {
  2165. (rewindButton.props.onClick as () => void)();
  2166. await Promise.resolve();
  2167. });
  2168. expect(onEdit).toHaveBeenNthCalledWith(
  2169. 1,
  2170. { rowId: row.rowId, entityId: row.entityId },
  2171. row.text,
  2172. row.attachments,
  2173. "rewind",
  2174. );
  2175. expect(fileRewindDialogProps.at(-1)).toMatchObject({
  2176. open: true,
  2177. preview,
  2178. variant: "editConflict",
  2179. });
  2180. const onConversationOnly = fileRewindDialogProps.at(-1)?.onConversationOnly;
  2181. expect(onConversationOnly).toBeTypeOf("function");
  2182. await act(async () => {
  2183. (onConversationOnly as () => void)();
  2184. await Promise.resolve();
  2185. });
  2186. expect(onEdit).toHaveBeenNthCalledWith(
  2187. 2,
  2188. { rowId: row.rowId, entityId: row.entityId },
  2189. row.text,
  2190. row.attachments,
  2191. "preserve",
  2192. );
  2193. await act(async () => {
  2194. root.unmount();
  2195. });
  2196. });
  2197. });