v4ConversationTurnGroup.test.ts 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956
  1. import { readFileSync } from "node:fs";
  2. import { createElement, type ContextType } from "react";
  3. import { DeliveryContext } from "@/v4/botGroupDeliveryContext.js";
  4. import { withTopicPreparationMessages } from "@/v4/topicPreparationRenderUnits.js";
  5. import { renderToStaticMarkup } from "react-dom/server";
  6. import { describe, expect, it, vi } from "vitest";
  7. import type { IPlatformService } from "@zcode/shared";
  8. import type {
  9. ApiRetryState,
  10. AssistantTextRow,
  11. ConversationRowTarget,
  12. HookInvocationRow,
  13. ReasoningRow,
  14. SubagentRow,
  15. TimelineMarkerRow,
  16. ToolCallRow,
  17. TurnHeaderRow,
  18. UserInputRow,
  19. WorkflowLaunchMeta,
  20. WorkflowRunState,
  21. } from "@zcode/shared/zcode-protocol-v4";
  22. import { TID_CHAT_WORKFLOW_ARTIFACT_CHIP, TID_CHAT_WORKFLOW_RUN_DIGEST } from "@zcode/shared";
  23. import { TID_CRON_CREATE_CARD, TID_CRON_CREATE_OPEN, testId } from "@zcode/shared/test-ids";
  24. import { TooltipProvider } from "@/components/ui/tooltip.js";
  25. import { PlatformProvider } from "@/hooks/usePlatform.js";
  26. import { DEFAULT_CODE_PREVIEW_SETTINGS } from "@/lib/codePreviewSettings.js";
  27. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  28. import { ConversationTurnGroup } from "@/v4/ConversationTurnGroup.js";
  29. import {
  30. completeHighspeedTurn,
  31. markHighspeedTurnMetricsPersisted,
  32. recordHighspeedTurn,
  33. setHighspeedCardTps,
  34. } from "@/highspeed/highspeedTurnStore.js";
  35. import type { ConversationRowRenderContext } from "@/v4/conversationRowContext.js";
  36. import {
  37. buildConversationTurnRenderUnits,
  38. type ConversationTurnRenderUnit,
  39. } from "@/v4/conversationTurnRenderUnits.js";
  40. vi.mock("@/hooks/useWorkspaceServices.js", () => ({
  41. useWorkspaceServices: () => ({}),
  42. }));
  43. vi.mock("@/hooks/useServices.js", () => ({
  44. useOptionalServices: () => ({
  45. highspeedCardService: { share: vi.fn() },
  46. }),
  47. }));
  48. const topicInterrupted = vi.hoisted(() => vi.fn(() => false));
  49. vi.mock("@/v4/botGroupDeliveryContext.js", async (importOriginal) => ({
  50. ...(await importOriginal<typeof import("@/v4/botGroupDeliveryContext.js")>()),
  51. useBotTopicInterruption: topicInterrupted,
  52. }));
  53. const rowContext: ConversationRowRenderContext = {
  54. workspacePath: "/workspace",
  55. theme: "system",
  56. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  57. };
  58. const noopPlatform = {} as IPlatformService;
  59. function reasoningRow(): ReasoningRow {
  60. return {
  61. rowId: 3,
  62. turnId: "turn-complete",
  63. createdAt: 1_700_000_000_003,
  64. createdAtSeq: 3,
  65. kind: "reasoning",
  66. state: "complete",
  67. text: "完成了",
  68. };
  69. }
  70. function toolCallRow(
  71. rowId: number,
  72. toolName: string,
  73. input: unknown,
  74. overrides: Partial<ToolCallRow> = {},
  75. ): ToolCallRow {
  76. return {
  77. rowId,
  78. turnId: "turn-complete",
  79. createdAt: 1_700_000_000_000 + rowId,
  80. createdAtSeq: rowId,
  81. kind: "toolCall",
  82. toolCallId: `tool-${rowId}`,
  83. toolName,
  84. status: "success",
  85. input,
  86. inputText: JSON.stringify(input),
  87. ...overrides,
  88. };
  89. }
  90. function subagentRow(rowId: number, overrides: Partial<SubagentRow> = {}): SubagentRow {
  91. return {
  92. rowId,
  93. turnId: "turn-complete",
  94. createdAt: 1_700_000_000_000 + rowId,
  95. createdAtSeq: rowId,
  96. kind: "subagent",
  97. subagentType: "Explore",
  98. status: "complete",
  99. summaryText: "完成分析",
  100. childSessionId: `child-session-${rowId}`,
  101. ...overrides,
  102. };
  103. }
  104. function assistantTextRow(
  105. rowId: number,
  106. overrides: Partial<AssistantTextRow> = {},
  107. ): AssistantTextRow {
  108. return {
  109. rowId,
  110. entityId: `message-assistant-${rowId}`,
  111. turnId: "turn-complete",
  112. createdAt: 1_700_000_000_000 + rowId,
  113. createdAtSeq: rowId,
  114. kind: "assistantText",
  115. state: "complete",
  116. text: "完成回复",
  117. ...overrides,
  118. };
  119. }
  120. function hookInvocationRow(
  121. rowId: number,
  122. overrides: Partial<HookInvocationRow> = {},
  123. ): HookInvocationRow {
  124. return {
  125. rowId,
  126. turnId: "turn-complete",
  127. entityId: `hook-invocation-${rowId}`,
  128. productTurnId: "turn-complete",
  129. visibility: "visible",
  130. createdAt: 1_700_000_000_000 + rowId,
  131. createdAtSeq: rowId,
  132. kind: "hookInvocation",
  133. hookInvocationId: `hook-invocation-${rowId}`,
  134. hookEventName: "PreToolUse",
  135. hookCount: 1,
  136. state: "completed",
  137. startedAt: 1_700_000_000_000 + rowId,
  138. endedAt: 1_700_000_000_010 + rowId,
  139. durationMs: 10,
  140. lane: "toolBefore",
  141. anchorToolCallId: "tool-3",
  142. executions: [
  143. {
  144. hookRunId: `hook-run-${rowId}`,
  145. hookIndex: 0,
  146. didExecute: true,
  147. state: "completed",
  148. outcome: "success",
  149. startedAt: 1_700_000_000_000 + rowId,
  150. endedAt: 1_700_000_000_010 + rowId,
  151. durationMs: 10,
  152. displayName: "validate-write",
  153. sourceKind: "project",
  154. toolName: "Write",
  155. },
  156. ],
  157. ...overrides,
  158. };
  159. }
  160. function runningTimelineRow(rowId: number): TimelineMarkerRow {
  161. return {
  162. rowId,
  163. turnId: "turn-complete",
  164. createdAt: 1_700_000_000_000 + rowId,
  165. createdAtSeq: rowId,
  166. kind: "timelineMarker",
  167. lane: "assistantWork",
  168. marker: {
  169. type: "compact",
  170. origin: "manual",
  171. status: "running",
  172. },
  173. };
  174. }
  175. function runningGoalVerifyTimelineRow(rowId: number): TimelineMarkerRow {
  176. return {
  177. rowId,
  178. turnId: "turn-complete",
  179. createdAt: 1_700_000_000_000 + rowId,
  180. createdAtSeq: rowId,
  181. kind: "timelineMarker",
  182. lane: "turnTailBoundary",
  183. marker: {
  184. type: "goalVerify",
  185. iteration: 1,
  186. outcome: "running",
  187. },
  188. };
  189. }
  190. function forkNoticeTimelineRow(rowId: number): TimelineMarkerRow {
  191. return {
  192. rowId,
  193. turnId: "turn-complete",
  194. createdAt: 1_700_000_000_000 + rowId,
  195. createdAtSeq: rowId,
  196. kind: "timelineMarker",
  197. lane: "turnTailBoundary",
  198. marker: {
  199. type: "forkNotice",
  200. parentSessionId: "session-parent",
  201. parentRowId: 1,
  202. },
  203. };
  204. }
  205. function turnHeader(overrides: Partial<TurnHeaderRow> = {}): TurnHeaderRow {
  206. return {
  207. rowId: 1,
  208. turnId: "turn-complete",
  209. createdAt: 1_700_000_000_000,
  210. createdAtSeq: 1,
  211. kind: "turnHeader",
  212. origin: "userInput",
  213. state: "completedSuccess",
  214. startedAt: 1_700_000_000_000,
  215. ...overrides,
  216. };
  217. }
  218. function userInputRow(rowId: number, overrides: Partial<UserInputRow> = {}): UserInputRow {
  219. return {
  220. rowId,
  221. turnId: "turn-complete",
  222. createdAt: 1_700_000_000_000 + rowId,
  223. createdAtSeq: rowId,
  224. kind: "userInput",
  225. text: "看看项目",
  226. origin: "realUser",
  227. ...overrides,
  228. };
  229. }
  230. function baseUnit(overrides: Partial<ConversationTurnRenderUnit>): ConversationTurnRenderUnit {
  231. const synthesizedFlowItems: ConversationTurnRenderUnit["flowItems"] = [
  232. ...(overrides.visibleUserInputs ?? []).map((row) => ({
  233. kind: "userInput" as const,
  234. row,
  235. })),
  236. ...((overrides.assistantHistoryRows?.length ?? 0) > 0
  237. ? [
  238. {
  239. kind: "assistantHistory" as const,
  240. rows: overrides.assistantHistoryRows!,
  241. },
  242. ]
  243. : []),
  244. ...(overrides.latestAssistantTextRow
  245. ? [
  246. {
  247. kind: "assistantText" as const,
  248. row: overrides.latestAssistantTextRow,
  249. latest: true,
  250. },
  251. ]
  252. : []),
  253. ...((overrides.assistantFollowingRows?.length ?? 0) > 0
  254. ? [
  255. {
  256. kind: "assistantWork" as const,
  257. rows: overrides.assistantFollowingRows!,
  258. },
  259. ]
  260. : []),
  261. ];
  262. return {
  263. key: "turn-1:1",
  264. turnId: "turn-1",
  265. visibleUserInputs: [],
  266. assistantWorkRows: [],
  267. assistantHistoryRows: [],
  268. assistantFollowingRows: [],
  269. assistantTailRows: [],
  270. browserTurnEndRows: [],
  271. hookInvocations: [],
  272. assistantTextRows: [],
  273. leadingBoundaryRows: [],
  274. flowItems: synthesizedFlowItems,
  275. renderRows: [],
  276. isLastTurn: true,
  277. isRunning: false,
  278. assistantHistoryDefaultOpen: false,
  279. timelineOnly: false,
  280. ...overrides,
  281. };
  282. }
  283. function renderUnit(
  284. unit: ConversationTurnRenderUnit,
  285. options: {
  286. locale?: "zh-CN" | "en-US";
  287. botContext?: ContextType<typeof DeliveryContext>;
  288. chatLoadingBlockedByActiveWork?: boolean;
  289. chatLoadingBlockedByInteraction?: boolean;
  290. compactForRemoteControl?: boolean;
  291. messageStreamShowReasoning?: boolean;
  292. messageStreamShowTodos?: boolean;
  293. apiRetry?: ApiRetryState | null;
  294. nowMs?: number;
  295. onFork?: (rowId: number) => void;
  296. onRetry?: (target: ConversationRowTarget) => void;
  297. onFeedbackChange?: (target: ConversationRowTarget, feedback: "like" | "dislike" | null) => void;
  298. /** 覆盖行渲染上下文的若干键(产物 chips 的门就是 `sessionId` + `onOpenWorkflowArtifact`)。 */
  299. context?: Partial<ConversationRowRenderContext>;
  300. } = {},
  301. ): string {
  302. return renderToStaticMarkup(
  303. createElement(
  304. DeliveryContext.Provider,
  305. { value: options.botContext ?? null },
  306. createElement(
  307. ZCodeIntlProvider,
  308. { initialLocale: options.locale ?? "zh-CN" },
  309. createElement(
  310. PlatformProvider,
  311. { platform: noopPlatform },
  312. createElement(
  313. TooltipProvider,
  314. null,
  315. createElement(ConversationTurnGroup, {
  316. unit,
  317. nowMs: options.nowMs,
  318. apiRetry: options.apiRetry,
  319. context: {
  320. ...rowContext,
  321. chatLoadingBlockedByActiveWork: options.chatLoadingBlockedByActiveWork,
  322. chatLoadingBlockedByInteraction: options.chatLoadingBlockedByInteraction,
  323. compactForRemoteControl: options.compactForRemoteControl,
  324. messageStreamShowReasoning: options.messageStreamShowReasoning,
  325. messageStreamShowTodos: options.messageStreamShowTodos,
  326. ...options.context,
  327. },
  328. onFork: options.onFork,
  329. onRetry: options.onRetry,
  330. onFeedbackChange: options.onFeedbackChange,
  331. }),
  332. ),
  333. ),
  334. ),
  335. ),
  336. );
  337. }
  338. describe("ConversationTurnGroup layout", () => {
  339. it("removes the complete external assistant container after its response becomes CUA", () => {
  340. const responseId = "assistant-response-cua";
  341. const message = assistantTextRow(3, {
  342. assistantResponseId: responseId,
  343. text: "我先检查电脑操作权限与应用列表。",
  344. });
  345. const [unit] = buildConversationTurnRenderUnits([
  346. turnHeader(),
  347. userInputRow(2),
  348. message,
  349. toolCallRow(
  350. 4,
  351. "mcp__computer-use__list_apps",
  352. {},
  353. {
  354. assistantResponseId: responseId,
  355. },
  356. ),
  357. ]);
  358. const html = renderUnit(unit!);
  359. expect(unit?.flowItems.map((item) => item.kind)).toContain("cuaGroup");
  360. expect(unit?.flowItems.some((item) => item.kind === "assistantText")).toBe(false);
  361. const group = unit?.flowItems.find((item) => item.kind === "cuaGroup");
  362. expect(
  363. group?.kind === "cuaGroup"
  364. ? group.events.some((event) => event.kind === "assistantMessage" && event.row === message)
  365. : false,
  366. ).toBe(true);
  367. expect(html).not.toContain(`data-row-id="${message.rowId}"`);
  368. });
  369. it("groups response reasoning and counts only reasoning visible under the existing setting", () => {
  370. const responseId = "assistant-response-cua-reasoning";
  371. const firstReasoning: ReasoningRow = {
  372. ...reasoningRow(),
  373. rowId: 3,
  374. assistantResponseId: responseId,
  375. text: "先确认飞书权限",
  376. };
  377. const secondReasoning: ReasoningRow = {
  378. ...reasoningRow(),
  379. rowId: 4,
  380. createdAtSeq: 4,
  381. assistantResponseId: responseId,
  382. text: "再观察飞书界面",
  383. };
  384. const message = assistantTextRow(5, {
  385. assistantResponseId: responseId,
  386. text: "现在观察飞书窗口状态。",
  387. });
  388. const rows = [
  389. turnHeader(),
  390. userInputRow(2),
  391. firstReasoning,
  392. secondReasoning,
  393. message,
  394. toolCallRow(
  395. 6,
  396. "mcp__computer-use__get_app_state",
  397. {},
  398. {
  399. assistantResponseId: responseId,
  400. },
  401. ),
  402. ];
  403. const [hiddenUnit] = buildConversationTurnRenderUnits(rows);
  404. const hiddenHtml = renderUnit(hiddenUnit!, { messageStreamShowReasoning: false });
  405. const visibleHtml = renderUnit(hiddenUnit!, { messageStreamShowReasoning: true });
  406. expect(hiddenUnit?.flowItems.map((item) => item.kind)).toContain("cuaGroup");
  407. expect(hiddenHtml).toContain("3 个事件, 1 条消息");
  408. expect(hiddenHtml).not.toContain("4 个事件");
  409. expect(visibleHtml).toContain("4 个事件, 1 条消息");
  410. });
  411. it("does not mount an empty history collapsible after inner work projection", () => {
  412. const deferredShell = toolCallRow(3, "Bash", {}, { status: "running" });
  413. const html = renderUnit(
  414. baseUnit({
  415. assistantWorkRows: [deferredShell],
  416. assistantHistoryRows: [deferredShell],
  417. assistantHistoryDefaultOpen: true,
  418. renderRows: [deferredShell],
  419. }),
  420. );
  421. expect(html).not.toContain("chat-assistant-history-content");
  422. expect(html).not.toContain('<div class="pt-5"><div class="flex flex-col gap-4"></div></div>');
  423. });
  424. });
  425. describe("ConversationTurnGroup Hook footer", () => {
  426. it("HK08 renders the Hook action after turn-local content and before the tail boundary", () => {
  427. const [unit] = buildConversationTurnRenderUnits([
  428. turnHeader(),
  429. userInputRow(2),
  430. toolCallRow(3, "Write", { file_path: "README.md" }),
  431. assistantTextRow(4),
  432. hookInvocationRow(5),
  433. forkNoticeTimelineRow(6),
  434. ]);
  435. const html = renderUnit(unit!, { compactForRemoteControl: true });
  436. const assistantIndex = html.indexOf("完成回复");
  437. const hookIndex = html.indexOf('data-testid="v4-hook-details-trigger-turn-complete"');
  438. const boundaryIndex = html.indexOf("从对话中派生");
  439. expect(assistantIndex).toBeGreaterThanOrEqual(0);
  440. expect(hookIndex).toBeGreaterThan(assistantIndex);
  441. expect(boundaryIndex).toBeGreaterThan(hookIndex);
  442. expect(html.match(/data-testid="v4-hook-details-trigger-turn-complete"/g)).toHaveLength(1);
  443. });
  444. it.each(
  445. [false, true].flatMap((compactForRemoteControl) =>
  446. [false, true].flatMap((highspeed) =>
  447. [false, true].map((hasAssistantText) => ({
  448. compactForRemoteControl,
  449. highspeed,
  450. hasAssistantText,
  451. })),
  452. ),
  453. ),
  454. )(
  455. "HK08/HK11 每轮仅一个 Hook 入口:mobile=$compactForRemoteControl highspeed=$highspeed text=$hasAssistantText",
  456. ({ compactForRemoteControl, highspeed, hasAssistantText }) => {
  457. const [unit] = buildConversationTurnRenderUnits([
  458. turnHeader({ state: hasAssistantText ? "completedSuccess" : "completedInterrupted" }),
  459. userInputRow(2, {
  460. ...(highspeed
  461. ? {
  462. highspeed: {
  463. schemaVersion: 1,
  464. cardId: "hsc-hook-footer",
  465. taskId: "session-hook-footer",
  466. provider: "zai",
  467. model: "glm-5",
  468. issuedAt: 1_000,
  469. expiresAt: 10_000,
  470. },
  471. }
  472. : {}),
  473. }),
  474. hookInvocationRow(3),
  475. ...(hasAssistantText ? [assistantTextRow(4)] : []),
  476. forkNoticeTimelineRow(5),
  477. ]);
  478. const html = renderUnit(
  479. { ...unit!, showHighspeedOutputFooter: highspeed },
  480. { compactForRemoteControl },
  481. );
  482. // 冲突合并曾把 Hook-only 分支接成 Highspeed footer 的 else:
  483. // 普通有正文时重复显示,Highspeed 无正文时则完全丢失。
  484. expect(html.match(/data-testid="v4-hook-details-trigger-turn-complete"/g) ?? []).toHaveLength(
  485. 1,
  486. );
  487. expect(html.includes('data-highspeed-output-footer="true"')).toBe(highspeed);
  488. expect(html.indexOf("v4-hook-details-trigger-turn-complete")).toBeLessThan(
  489. html.indexOf("从对话中派生"),
  490. );
  491. expect(html.includes('data-testid="v4-copy-4"')).toBe(hasAssistantText);
  492. },
  493. );
  494. it("HK11 renders a Hook-only action row for a terminal turn without assistant text", () => {
  495. const [unit] = buildConversationTurnRenderUnits([
  496. turnHeader({ state: "failed" }),
  497. userInputRow(2),
  498. hookInvocationRow(3),
  499. ]);
  500. const html = renderUnit(unit!, { compactForRemoteControl: true });
  501. expect(html).toContain('data-testid="v4-hook-details-trigger-turn-complete"');
  502. expect(html.match(/data-testid="v4-copy-/g)).toHaveLength(1);
  503. expect(html).not.toContain("v4-feedback-like");
  504. expect(html).not.toContain("chat-assistant-history-trigger");
  505. });
  506. it("HK09 does not render an action when every Hook execution was blocked before start", () => {
  507. const blocked = hookInvocationRow(3, {
  508. executions: [
  509. {
  510. hookRunId: "blocked-before-start",
  511. hookIndex: 0,
  512. didExecute: false,
  513. state: "completed",
  514. outcome: "blocked",
  515. startedAt: 1_700_000_000_003,
  516. endedAt: 1_700_000_000_003,
  517. durationMs: 0,
  518. displayName: "blocked-project-hook",
  519. sourceKind: "project",
  520. },
  521. ],
  522. });
  523. const [unit] = buildConversationTurnRenderUnits([
  524. turnHeader(),
  525. userInputRow(2),
  526. blocked,
  527. assistantTextRow(4),
  528. ]);
  529. expect(renderUnit(unit!, { compactForRemoteControl: true })).not.toContain(
  530. "v4-hook-details-trigger",
  531. );
  532. });
  533. it("HK17 does not render a Hook action on a timeline-only maintenance turn carrying legacy executed Hook rows", () => {
  534. // Bug 根因:首条输入即 /compact 时 SessionStart Hook 曾被错误挂到 compact 维护 turn;
  535. // 旧历史/旧投影数据可能仍含 timelineOnly + didExecute=true 组合。维护 turn 与普通
  536. // assistant action 共用 turn eligibility:timelineOnly 不渲染 Hook 图标或空操作栏。
  537. const compactMarker = runningTimelineRow(2);
  538. const [unit] = buildConversationTurnRenderUnits([
  539. turnHeader({ state: "completedSuccess" }),
  540. compactMarker,
  541. hookInvocationRow(3),
  542. ]);
  543. expect(unit?.timelineOnly).toBe(true);
  544. expect(unit?.hookInvocations.length).toBe(1);
  545. const html = renderUnit(unit!, { compactForRemoteControl: true });
  546. expect(html).not.toContain("v4-hook-details-trigger");
  547. // 也不得留下只有 Hook 的空操作栏外壳。
  548. expect(html).not.toContain("v4-copy-");
  549. });
  550. });
  551. describe("ConversationTurnGroup message stream display settings", () => {
  552. const reasoning = reasoningRow();
  553. const todo = toolCallRow(4, "TodoWrite", {
  554. todos: [
  555. {
  556. content: "补齐设置接线",
  557. status: "in_progress",
  558. activeForm: "补齐设置接线",
  559. },
  560. ],
  561. });
  562. const shell = toolCallRow(5, "Bash", { command: "pnpm test" });
  563. const laterReasoning: ReasoningRow = {
  564. ...reasoningRow(),
  565. rowId: 6,
  566. createdAt: 1_700_000_000_006,
  567. createdAtSeq: 6,
  568. text: "后续思考",
  569. };
  570. const finalText = assistantTextRow(7);
  571. const [builtUnit] = buildConversationTurnRenderUnits([
  572. turnHeader(),
  573. userInputRow(2),
  574. reasoning,
  575. todo,
  576. shell,
  577. laterReasoning,
  578. finalText,
  579. ]);
  580. const unit = {
  581. ...builtUnit!,
  582. assistantHistoryDefaultOpen: true,
  583. };
  584. it.each([
  585. {
  586. label: "两个开关都关闭",
  587. showReasoning: false,
  588. showTodos: false,
  589. todoVisible: false,
  590. },
  591. {
  592. label: "只开启显示思考过程",
  593. showReasoning: true,
  594. showTodos: false,
  595. todoVisible: false,
  596. },
  597. {
  598. label: "只开启显示待办",
  599. showReasoning: false,
  600. showTodos: true,
  601. todoVisible: true,
  602. },
  603. {
  604. label: "两个开关都开启",
  605. showReasoning: true,
  606. showTodos: true,
  607. todoVisible: true,
  608. },
  609. ])("$label 时独立控制 reasoning 与 Todo", (scenario) => {
  610. const html = renderUnit(unit, {
  611. messageStreamShowReasoning: scenario.showReasoning,
  612. messageStreamShowTodos: scenario.showTodos,
  613. });
  614. // 每轮第一条 reasoning 不受开关影响;后续 reasoning 只在开关开启时展示。
  615. expect(html).toContain('data-row-id="3"');
  616. expect(html.includes('data-row-id="6"')).toBe(scenario.showReasoning);
  617. expect(html.includes('data-tool-call-id="tool-4"')).toBe(scenario.todoVisible);
  618. // 单个 Execute 不创建父分组,仍直接展示原始工具。
  619. expect(html).toContain("tool-summary-trigger-tool-5");
  620. });
  621. it("关闭思考时跨隐藏 reasoning 合并 Explore,开启时保持原始边界", () => {
  622. const firstReasoning = reasoningRow();
  623. const firstExplore = toolCallRow(4, "Read", { file_path: "package.json" });
  624. const hiddenReasoning: ReasoningRow = {
  625. ...reasoningRow(),
  626. rowId: 5,
  627. createdAt: 1_700_000_000_005,
  628. createdAtSeq: 5,
  629. text: "检查下一处",
  630. };
  631. const secondExplore = toolCallRow(6, "Bash", {
  632. command: "rg test packages/ui",
  633. });
  634. const finalText = assistantTextRow(7);
  635. const [builtUnit] = buildConversationTurnRenderUnits([
  636. turnHeader(),
  637. userInputRow(2),
  638. firstReasoning,
  639. firstExplore,
  640. hiddenReasoning,
  641. secondExplore,
  642. finalText,
  643. ]);
  644. const exploreUnit = {
  645. ...builtUnit!,
  646. assistantHistoryDefaultOpen: true,
  647. };
  648. const hiddenReasoningHtml = renderUnit(exploreUnit, {
  649. messageStreamShowReasoning: false,
  650. });
  651. expect(hiddenReasoningHtml).toContain('data-tool-call-id="explore:tool-4"');
  652. expect(hiddenReasoningHtml).not.toContain('data-row-id="5"');
  653. const visibleReasoningHtml = renderUnit(exploreUnit, {
  654. messageStreamShowReasoning: true,
  655. });
  656. expect(visibleReasoningHtml).toContain('data-tool-call-id="tool-4"');
  657. expect(visibleReasoningHtml).toContain('data-tool-call-id="tool-6"');
  658. expect(visibleReasoningHtml).toContain('data-row-id="5"');
  659. });
  660. });
  661. describe("ConversationTurnGroup assistant history status", () => {
  662. it("源码将会话内分享按钮接到本地卡片,且不调用后端分享接口", () => {
  663. const source = readFileSync("packages/ui/src/v4/ConversationTurnGroup.tsx", "utf8");
  664. expect(source).toContain("setHighspeedShareDialogOpen(true)");
  665. expect(source).toContain("<HighspeedShareDialog");
  666. expect(source).not.toContain("highspeedCardService.share");
  667. });
  668. it("冷恢复后从 userInput metadata 保留 accelerated output 的紫色工时", () => {
  669. const input = userInputRow(2, {
  670. sourceCommandId: "command-highspeed-cold-history",
  671. highspeed: {
  672. schemaVersion: 1,
  673. cardId: "hsc-cold-history",
  674. taskId: "session-highspeed-cold-history",
  675. provider: "zai",
  676. model: "glm-5",
  677. issuedAt: 1_000,
  678. expiresAt: 10_000,
  679. regularTps: 73,
  680. highspeedTps: 136,
  681. outputTokens: 120_000,
  682. durationMs: 881_000,
  683. savedDurationMs: 763_000,
  684. },
  685. });
  686. const work = reasoningRow();
  687. const html = renderUnit(
  688. baseUnit({
  689. visibleUserInputs: [input],
  690. workStatus: { state: "completed", durationMs: 881_000 },
  691. assistantWorkRows: [work],
  692. assistantHistoryRows: [work],
  693. renderRows: [input, work],
  694. showHighspeedOutputFooter: true,
  695. }),
  696. );
  697. expect(html).toContain("已工作 14 分 41 秒");
  698. expect(html).toContain('data-highspeed-duration="true"');
  699. expect(html).toContain("text-icon-purple");
  700. expect(html).toContain("节省约 12 分 43 秒");
  701. expect(html).toContain('data-highspeed-saved-duration="true"');
  702. expect(html).toContain('data-highspeed-status-tag="true"');
  703. expect(html).not.toContain('data-highspeed-gradient="true"');
  704. expect(html).toContain("HighSpeed");
  705. expect(html).toContain('data-highspeed-output-footer="true"');
  706. expect(html).toContain("以上由 Highspeed 生成");
  707. expect(html).toContain('data-highspeed-output-share="true"');
  708. expect(html).toContain("查看");
  709. const shareButton = html.match(/<button[^>]*data-highspeed-output-share="true"[^>]*>/)?.[0];
  710. expect(shareButton).toBeDefined();
  711. expect(shareButton).not.toMatch(/\sdisabled(?:=""|(?=[\s>]))/);
  712. expect(html).toContain('data-highspeed-output-share-icon="true"');
  713. expect(html).not.toContain('data-highspeed="true"');
  714. });
  715. it("卡失效降级后仍允许分享当前 Turn 的完整统计", () => {
  716. const input = userInputRow(2, {
  717. sourceCommandId: "command-highspeed-fallback-share",
  718. highspeed: {
  719. schemaVersion: 1,
  720. cardId: "hsc-fallback-share",
  721. taskId: "session-fallback-share",
  722. provider: "zai",
  723. model: "glm-5",
  724. issuedAt: 1_000,
  725. expiresAt: 10_000,
  726. regularTps: 73,
  727. highspeedTps: 136,
  728. outputTokens: 120_000,
  729. durationMs: 881_000,
  730. savedDurationMs: 763_000,
  731. fallbackAt: 10_001,
  732. },
  733. });
  734. const work = reasoningRow();
  735. const html = renderUnit(
  736. baseUnit({
  737. visibleUserInputs: [input],
  738. workStatus: { state: "completed", durationMs: 881_000 },
  739. assistantWorkRows: [work],
  740. assistantHistoryRows: [work],
  741. renderRows: [input, work],
  742. showHighspeedOutputFooter: true,
  743. }),
  744. );
  745. const shareButton = html.match(/<button[^>]*data-highspeed-output-share="true"[^>]*>/)?.[0];
  746. expect(shareButton).toBeDefined();
  747. expect(shareButton).not.toMatch(/\sdisabled(?:=""|(?=[\s>]))/);
  748. });
  749. it("缺少 durationMs 时不展示分享入口", () => {
  750. const input = userInputRow(2, {
  751. sourceCommandId: "command-highspeed-share-without-duration",
  752. highspeed: {
  753. schemaVersion: 1,
  754. cardId: "hsc-share-without-duration",
  755. taskId: "session-share-without-duration",
  756. provider: "zai",
  757. model: "glm-5",
  758. issuedAt: 1_000,
  759. expiresAt: 10_000,
  760. outputTokens: 120_000,
  761. regularTps: 73,
  762. highspeedTps: 136,
  763. },
  764. });
  765. const html = renderUnit(
  766. baseUnit({
  767. visibleUserInputs: [input],
  768. workStatus: { state: "completed", durationMs: 881_000 },
  769. assistantWorkRows: [reasoningRow()],
  770. assistantHistoryRows: [reasoningRow()],
  771. renderRows: [input, reasoningRow()],
  772. showHighspeedOutputFooter: true,
  773. }),
  774. );
  775. const shareButton = html.match(/<button[^>]*data-highspeed-output-share="true"[^>]*>/)?.[0];
  776. expect(shareButton).toBeUndefined();
  777. });
  778. it("总体加速倍率不大于 1.2x 时保留 footer 但隐藏分享入口", () => {
  779. const input = userInputRow(2, {
  780. sourceCommandId: "command-highspeed-low-speedup",
  781. highspeed: {
  782. schemaVersion: 1,
  783. cardId: "hsc-low-speedup",
  784. taskId: "session-low-speedup",
  785. provider: "zai",
  786. model: "glm-5",
  787. issuedAt: 1_000,
  788. expiresAt: 10_000,
  789. regularTps: 73,
  790. highspeedTps: 100,
  791. outputTokens: 120_000,
  792. durationMs: 881_000,
  793. savedDurationMs: 100_000,
  794. },
  795. });
  796. const html = renderUnit(
  797. baseUnit({
  798. visibleUserInputs: [input],
  799. workStatus: { state: "completed", durationMs: 881_000 },
  800. assistantWorkRows: [reasoningRow()],
  801. assistantHistoryRows: [reasoningRow()],
  802. renderRows: [input, reasoningRow()],
  803. showHighspeedOutputFooter: true,
  804. }),
  805. );
  806. expect(html).toContain('data-highspeed-output-footer="true"');
  807. expect(html).not.toContain('data-highspeed-output-share="true"');
  808. });
  809. it("Highspeed 生成期间只显示标签,不提前显示持久化的节省时间", () => {
  810. const input = userInputRow(2, {
  811. sourceCommandId: "command-highspeed-running",
  812. highspeed: {
  813. schemaVersion: 1,
  814. cardId: "hsc-running",
  815. taskId: "session-highspeed-running",
  816. provider: "zai",
  817. model: "glm-5",
  818. issuedAt: 1_000,
  819. expiresAt: 10_000,
  820. regularTps: 73,
  821. outputTokens: 120_000,
  822. durationMs: 881_000,
  823. savedDurationMs: 763_000,
  824. },
  825. });
  826. const work = reasoningRow();
  827. const html = renderUnit(
  828. baseUnit({
  829. visibleUserInputs: [input],
  830. // 多段输出中,前段可已完成但整轮仍在生成;节省时间必须服从整轮终态。
  831. workStatus: { state: "completed", durationMs: 5_000 },
  832. assistantWorkRows: [work],
  833. assistantHistoryRows: [work],
  834. renderRows: [input, work],
  835. isRunning: true,
  836. }),
  837. { nowMs: 9_999 },
  838. );
  839. expect(html).toContain('data-highspeed-status-tag="true"');
  840. expect(html).toContain('data-highspeed-gradient="true"');
  841. expect(html).toContain("highspeed-animated-gradient-text");
  842. expect(html).toContain("HighSpeed");
  843. expect(html).not.toContain('data-highspeed-saved-duration="true"');
  844. expect(html).not.toContain("节省约");
  845. });
  846. it("Highspeed 卡过期后执行中的 Tool 恢复普通流光样式", () => {
  847. const input = userInputRow(2, {
  848. sourceCommandId: "command-highspeed-expired-running-tool",
  849. highspeed: {
  850. schemaVersion: 1,
  851. cardId: "hsc-expired-running-tool",
  852. taskId: "session-expired-running-tool",
  853. provider: "zai",
  854. model: "glm-5",
  855. issuedAt: 1_000,
  856. expiresAt: 10_000,
  857. },
  858. });
  859. const runningTool = toolCallRow(3, "Bash", { command: "pnpm test" }, { status: "running" });
  860. const html = renderUnit(
  861. baseUnit({
  862. visibleUserInputs: [input],
  863. assistantWorkRows: [runningTool],
  864. assistantHistoryRows: [runningTool],
  865. renderRows: [input, runningTool],
  866. isRunning: true,
  867. }),
  868. { nowMs: 10_001 },
  869. );
  870. expect(html).not.toContain('data-highspeed-gradient="true"');
  871. expect(html).not.toContain("highspeed-animated-gradient-text");
  872. });
  873. it("普通 output 和仍在运行的 accelerated output 不显示 Highspeed 来源 footer", () => {
  874. const work = reasoningRow();
  875. const ordinaryHtml = renderUnit(
  876. baseUnit({
  877. visibleUserInputs: [userInputRow(2, { sourceCommandId: "command-ordinary-footer" })],
  878. workStatus: { state: "completed", durationMs: 5_000 },
  879. assistantWorkRows: [work],
  880. assistantHistoryRows: [work],
  881. renderRows: [work],
  882. }),
  883. );
  884. const runningHtml = renderUnit(
  885. baseUnit({
  886. visibleUserInputs: [
  887. userInputRow(2, {
  888. sourceCommandId: "command-highspeed-running-footer",
  889. highspeed: {
  890. schemaVersion: 1,
  891. cardId: "hsc-running-footer",
  892. taskId: "session-running-footer",
  893. provider: "zai",
  894. model: "glm-5",
  895. issuedAt: 1_000,
  896. expiresAt: 10_000,
  897. },
  898. }),
  899. ],
  900. workStatus: { state: "running", durationMs: 5_000 },
  901. assistantWorkRows: [work],
  902. assistantHistoryRows: [work],
  903. renderRows: [work],
  904. isRunning: true,
  905. showHighspeedOutputFooter: true,
  906. }),
  907. { nowMs: 9_999 },
  908. );
  909. expect(ordinaryHtml).not.toContain('data-highspeed-output-footer="true"');
  910. expect(ordinaryHtml).not.toContain('data-highspeed-gradient="true"');
  911. expect(runningHtml).not.toContain('data-highspeed-output-footer="true"');
  912. expect(runningHtml).toContain('data-highspeed-gradient="true"');
  913. });
  914. it.each([
  915. { label: "中断", workStatus: { state: "interrupted" as const, durationMs: 100 } },
  916. { label: "异常", workStatus: undefined },
  917. ])("Highspeed 组尾$label且自身无输出时仍展示可用分享入口", ({ workStatus }) => {
  918. const input = userInputRow(2, {
  919. sourceCommandId: "command-highspeed-terminal-footer",
  920. highspeed: {
  921. schemaVersion: 1,
  922. cardId: "hsc-terminal-footer",
  923. taskId: "session-terminal-footer",
  924. provider: "zai",
  925. model: "glm-5",
  926. issuedAt: 1_000,
  927. expiresAt: 10_000,
  928. regularTps: 20,
  929. highspeedTps: 50,
  930. outputTokens: 0,
  931. durationMs: 100,
  932. },
  933. });
  934. const html = renderUnit(
  935. baseUnit({
  936. visibleUserInputs: [input],
  937. ...(workStatus ? { workStatus } : {}),
  938. showHighspeedOutputFooter: true,
  939. highspeedOutputFooterTarget: {
  940. cardId: "hsc-terminal-footer",
  941. metrics: {
  942. outputTokens: 10,
  943. durationMs: 300,
  944. regularTps: 20,
  945. highspeedTps: 50,
  946. },
  947. },
  948. }),
  949. );
  950. expect(html).toContain('data-highspeed-output-footer="true"');
  951. const shareButton = html.match(/<button[^>]*data-highspeed-output-share="true"[^>]*>/)?.[0];
  952. expect(shareButton).toBeDefined();
  953. expect(shareButton).not.toMatch(/\sdisabled(?:=""|(?=[\s>]))/);
  954. });
  955. it("只用紫色工时标识 accelerated output,input 保持普通样式", () => {
  956. const sourceCommandId = "command-highspeed-output-duration";
  957. const input = userInputRow(2, { sourceCommandId });
  958. const work = reasoningRow();
  959. recordHighspeedTurn({
  960. sessionId: "session-highspeed-output-duration",
  961. sourceCommandId,
  962. card: {
  963. cardId: "hsc-output-duration",
  964. taskId: "session-highspeed-output-duration",
  965. provider: "zai",
  966. model: "glm-5",
  967. issuedAt: 1_000,
  968. expiresAt: 10_000,
  969. regularTps: 73,
  970. },
  971. createdAt: 1_000,
  972. });
  973. completeHighspeedTurn({
  974. sourceCommandId,
  975. outputTokens: 120_000,
  976. durationMs: 881_000,
  977. completedAt: 882_000,
  978. });
  979. setHighspeedCardTps("hsc-output-duration", 136);
  980. markHighspeedTurnMetricsPersisted(sourceCommandId, 763_000, 882_001);
  981. const html = renderUnit(
  982. baseUnit({
  983. visibleUserInputs: [input],
  984. workStatus: { state: "completed", durationMs: 881_000 },
  985. assistantWorkRows: [work],
  986. assistantHistoryRows: [work],
  987. renderRows: [input, work],
  988. showHighspeedOutputFooter: true,
  989. }),
  990. );
  991. expect(html).toContain("已工作 14 分 41 秒");
  992. expect(html).toContain('data-highspeed-duration="true"');
  993. expect(html).toContain("text-icon-purple");
  994. expect(html).toContain('data-highspeed-status-tag="true"');
  995. expect(html).toContain("HighSpeed");
  996. const shareButton = html.match(/<button[^>]*data-highspeed-output-share="true"[^>]*>/)?.[0];
  997. expect(shareButton).toBeDefined();
  998. expect(shareButton).not.toMatch(/\sdisabled(?:=""|(?=[\s>]))/);
  999. expect(html).not.toContain('data-highspeed="true"');
  1000. });
  1001. it("H17:切模型后的 /goal query 与 continuation 合计只显示一个工作状态", () => {
  1002. const startedAt = 1_700_000_000_000;
  1003. const units = buildConversationTurnRenderUnits(
  1004. [
  1005. {
  1006. rowId: 1,
  1007. turnId: "turn-goal",
  1008. createdAt: startedAt,
  1009. createdAtSeq: 1,
  1010. kind: "timelineMarker",
  1011. lane: "lightBoundary",
  1012. marker: {
  1013. type: "modelChange",
  1014. fromProvider: "zhipu",
  1015. fromModel: "glm-5.2-highspeed",
  1016. toProvider: "deepseek",
  1017. toModel: "deepseek-v4-flash",
  1018. toThought: "max",
  1019. },
  1020. },
  1021. turnHeader({
  1022. rowId: 2,
  1023. turnId: "turn-goal",
  1024. executionKind: "controlOnly",
  1025. activeMs: 0,
  1026. }),
  1027. userInputRow(3, {
  1028. turnId: "turn-goal",
  1029. text: "/Goal 开发一个招投标管理系统",
  1030. }),
  1031. turnHeader({
  1032. rowId: 4,
  1033. turnId: "turn-continuation",
  1034. origin: "goalContinuation",
  1035. executionKind: "agent",
  1036. state: "running",
  1037. startedAt,
  1038. }),
  1039. ],
  1040. { nowMs: startedAt + 3_000 },
  1041. );
  1042. const html = units.map((unit) => renderUnit(unit)).join("");
  1043. expect(html).not.toContain("/Goal");
  1044. expect(html).toContain("Goal");
  1045. expect(html).toContain("开发一个招投标管理系统");
  1046. expect(html).not.toContain("已工作 1 秒");
  1047. expect(html.match(/工作中 3 秒/g)).toHaveLength(1);
  1048. expect(html.match(/chat-assistant-history-trigger/g)).toHaveLength(1);
  1049. });
  1050. it("labels a running turn as working with the elapsed duration", () => {
  1051. const html = renderUnit(
  1052. baseUnit({
  1053. isRunning: true,
  1054. assistantHistoryDefaultOpen: true,
  1055. workStatus: { state: "running", durationMs: 5_000 },
  1056. }),
  1057. );
  1058. expect(html).toContain("工作中 5 秒");
  1059. });
  1060. it("ETS01/ETS03:运行工作段尾部的单个 Explore 工具不创建父分组", () => {
  1061. const explore = toolCallRow(10, "Read", { file_path: "AGENTS.md" });
  1062. const text = assistantTextRow(11);
  1063. const tailHtml = renderUnit(
  1064. baseUnit({
  1065. isRunning: true,
  1066. workStatus: { state: "running", durationMs: 5_000 },
  1067. assistantHistoryDefaultOpen: true,
  1068. assistantWorkRows: [explore],
  1069. assistantHistoryRows: [explore],
  1070. renderRows: [explore],
  1071. }),
  1072. );
  1073. const boundedHtml = renderUnit(
  1074. baseUnit({
  1075. isRunning: true,
  1076. workStatus: { state: "running", durationMs: 5_000 },
  1077. assistantHistoryDefaultOpen: true,
  1078. assistantWorkRows: [explore, text],
  1079. assistantHistoryRows: [explore],
  1080. latestAssistantTextRow: text,
  1081. assistantTextRows: [text],
  1082. renderRows: [explore, text],
  1083. }),
  1084. );
  1085. expect(tailHtml).toContain('data-tool-call-id="tool-10"');
  1086. expect(tailHtml).not.toContain('data-tool-call-id="explore:tool-10"');
  1087. expect(tailHtml).not.toContain("animated-gradient-text");
  1088. expect(boundedHtml).not.toContain("animated-gradient-text");
  1089. });
  1090. it("labels a completed turn as worked with the final duration", () => {
  1091. const row = reasoningRow();
  1092. const html = renderUnit(
  1093. baseUnit({
  1094. key: "turn-complete:1",
  1095. turnId: "turn-complete",
  1096. isLastTurn: false,
  1097. workStatus: { state: "completed", durationMs: 5_000 },
  1098. assistantWorkRows: [row],
  1099. assistantHistoryRows: [row],
  1100. renderRows: [row],
  1101. }),
  1102. );
  1103. expect(html).toContain("已工作 5 秒");
  1104. expect(html).not.toContain("工作中 5 秒");
  1105. });
  1106. it("labels an authoritative topic interruption separately from a manual stop", () => {
  1107. topicInterrupted.mockReturnValue(true);
  1108. try {
  1109. const row = reasoningRow();
  1110. const unit = baseUnit({
  1111. workStatus: { state: "interrupted", durationMs: 1000 },
  1112. assistantHistoryDefaultOpen: true,
  1113. assistantWorkRows: [row],
  1114. assistantHistoryRows: [row],
  1115. renderRows: [row],
  1116. });
  1117. expect(renderUnit(unit, { locale: "zh-CN" })).toContain("已被新消息中断");
  1118. expect(renderUnit(unit, { locale: "en-US" })).toContain("Interrupted by a new message");
  1119. } finally {
  1120. topicInterrupted.mockReturnValue(false);
  1121. }
  1122. });
  1123. it("labels an interrupted turn as stopped without duration", () => {
  1124. const row = reasoningRow();
  1125. const interruptedUnit = baseUnit({
  1126. key: "turn-interrupted:1",
  1127. turnId: "turn-interrupted",
  1128. assistantHistoryDefaultOpen: true,
  1129. workStatus: { state: "interrupted", durationMs: 5_000 },
  1130. assistantWorkRows: [row],
  1131. assistantHistoryRows: [row],
  1132. renderRows: [row],
  1133. });
  1134. expect(renderUnit(interruptedUnit, { locale: "en-US" })).toContain("Stopped");
  1135. expect(renderUnit(interruptedUnit, { locale: "en-US" })).not.toContain("Worked for 5s");
  1136. expect(renderUnit(interruptedUnit, { locale: "zh-CN" })).toContain("已停止");
  1137. expect(renderUnit(interruptedUnit, { locale: "zh-CN" })).not.toContain("已工作 5 秒");
  1138. });
  1139. it("按语言格式化工作时长的单位间距", () => {
  1140. const row = reasoningRow();
  1141. const completedUnit = baseUnit({
  1142. key: "turn-complete:localized-duration",
  1143. turnId: "turn-complete",
  1144. isLastTurn: false,
  1145. workStatus: { state: "completed", durationMs: 450_000 },
  1146. assistantWorkRows: [row],
  1147. assistantHistoryRows: [row],
  1148. renderRows: [row],
  1149. });
  1150. expect(renderUnit(completedUnit, { locale: "en-US" })).toContain("Worked for 7m 30s");
  1151. expect(renderUnit(completedUnit, { locale: "zh-CN" })).toContain("已工作 7 分 30 秒");
  1152. });
  1153. it.each([
  1154. ["subagent", "Review the projection chain"],
  1155. ["bash", "pnpm typecheck"],
  1156. // 回归:dwf run 的终态回合也走后台结果头。标题由 CLI 的 workflowTaskSubject 铸造并经
  1157. // originMeta.title 送上来(rows.ts 的 backgroundResultOriginMetaSchema 要求 min(1)),
  1158. // UI 侧不本地化——与 bash / subagent 完全同构。漏掉这一支的表现是整条 run 完成之后
  1159. // 那一轮既没有标题、也退化成普通 assistant 的工时折叠。
  1160. ["workflow", "Fan out the review across three actors"],
  1161. ] as const)(
  1162. "BG27/BG28:%s background result 用任务标题永久展开历史",
  1163. (backgroundSource, title) => {
  1164. const earlyText = assistantTextRow(4, { text: "后台总结第一段" });
  1165. const tool = toolCallRow(5, "Read", { file_path: "AGENTS.md" });
  1166. const finalText = assistantTextRow(6, { text: "后台总结最终段" });
  1167. const [unit] = buildConversationTurnRenderUnits([
  1168. turnHeader({
  1169. origin: "backgroundResult",
  1170. originMeta: {
  1171. backgroundSource,
  1172. title,
  1173. workId: `${backgroundSource}-work`,
  1174. },
  1175. activeMs: 12_000,
  1176. }),
  1177. earlyText,
  1178. tool,
  1179. finalText,
  1180. ]);
  1181. const html = renderUnit(unit!);
  1182. expect(html).toContain(`data-testid="chat-background-result-title-${unit!.key}"`);
  1183. expect(html).toContain(title);
  1184. expect(html).toContain("后台总结第一段");
  1185. expect(html).toContain("tool-5");
  1186. expect(html).toContain("后台总结最终段");
  1187. expect(html.indexOf("后台总结第一段")).toBeLessThan(html.indexOf("tool-5"));
  1188. expect(html.indexOf("tool-5")).toBeLessThan(html.indexOf("后台总结最终段"));
  1189. expect(html).not.toContain("已工作 12 秒");
  1190. expect(html).not.toContain("chat-assistant-history-trigger");
  1191. expect(html).not.toContain("chat-assistant-history-content");
  1192. expect(html).not.toContain("data-history-open");
  1193. },
  1194. );
  1195. it("workflow 通知带载荷时渲染工具卡语法的通知行,替换裸标题行", () => {
  1196. // docs/dynamic-workflow/transcript-and-notifications.md「The notification row」:backgroundSource==="workflow"
  1197. // 且 workflowNotification 在场 → ToolLayout 通知行(自带 testid),不再走裸标题行。
  1198. const finalText = assistantTextRow(6, { text: "后台总结最终段" });
  1199. const [unit] = buildConversationTurnRenderUnits([
  1200. turnHeader({
  1201. origin: "backgroundResult",
  1202. originMeta: {
  1203. backgroundSource: "workflow",
  1204. title: "flaky-test-triage",
  1205. workId: "run-abc",
  1206. workflowNotification: {
  1207. kind: "terminal",
  1208. status: "completed",
  1209. summary: "Workflow run completed: 3 flaky tests triaged.",
  1210. durationMs: 252_000,
  1211. },
  1212. },
  1213. }),
  1214. finalText,
  1215. ]);
  1216. const html = renderUnit(unit!, { locale: "en-US" });
  1217. expect(html).toContain(`data-testid="chat-workflow-notification-row-${unit!.key}"`);
  1218. // 裸标题行的 testid 缺席——通知行取而代之。
  1219. expect(html).not.toContain(`data-testid="chat-background-result-title-${unit!.key}"`);
  1220. expect(html).toContain("flaky-test-triage");
  1221. // kindLabel 承载状态(不再是 run 详情页的 Completed)。
  1222. expect(html).toContain("Workflow completed");
  1223. // 通知行之下的 assistant 反应行不受影响。
  1224. expect(html).toContain("后台总结最终段");
  1225. });
  1226. it("提醒载荷在 originMeta.workflowBlocked 上:同样渲染成通知行", () => {
  1227. // docs/dynamic-workflow/transcript-and-notifications.md「The payload」:提醒不是 workflowNotification
  1228. // 的成员(闭集多一个 kind,老客户端会拒掉整帧),它在自己的键上;行照旧是「等待主代理」那一条。
  1229. const [unit] = buildConversationTurnRenderUnits([
  1230. turnHeader({
  1231. origin: "backgroundResult",
  1232. originMeta: {
  1233. backgroundSource: "workflow",
  1234. title: "flaky-test-triage",
  1235. workId: "run-abc",
  1236. workflowBlocked: { questions: 2, holes: 1, sinceMs: 17 * 60_000 },
  1237. },
  1238. }),
  1239. assistantTextRow(6, { text: "后台总结最终段" }),
  1240. ]);
  1241. const html = renderUnit(unit!, { locale: "en-US" });
  1242. expect(html).toContain(`data-testid="chat-workflow-notification-row-${unit!.key}"`);
  1243. expect(html).not.toContain(`data-testid="chat-background-result-title-${unit!.key}"`);
  1244. expect(html).toContain("Workflow waiting on the agent");
  1245. expect(html).toContain("flaky-test-triage");
  1246. });
  1247. // ── 终态通知行的产物 chips(docs/dynamic-workflow/authoring.md「How the user sees them」)──
  1248. // ⚠ 术语:chip 上的 artifact 是脚本经 `artifact.*` 交付给用户的产出,与同一条通知里的
  1249. // `result`(脚本顶层返回值)不是一回事。
  1250. function workflowNotificationUnit(
  1251. artifacts: readonly { id: string; kind: string; title?: string; version: number }[] | undefined,
  1252. extra: Record<string, unknown> = {},
  1253. ) {
  1254. const [unit] = buildConversationTurnRenderUnits([
  1255. turnHeader({
  1256. origin: "backgroundResult",
  1257. originMeta: {
  1258. backgroundSource: "workflow",
  1259. title: "flaky-test-triage",
  1260. workId: "run-abc",
  1261. workflowNotification: {
  1262. kind: "terminal",
  1263. status: "completed",
  1264. summary: "Workflow run completed.",
  1265. durationMs: 1000,
  1266. ...(artifacts === undefined ? {} : { artifacts }),
  1267. ...extra,
  1268. },
  1269. },
  1270. }),
  1271. assistantTextRow(6, { text: "后台总结最终段" }),
  1272. ]);
  1273. return unit!;
  1274. }
  1275. const artifactContext = {
  1276. sessionId: "parent-a",
  1277. onOpenWorkflowArtifact: () => {},
  1278. } as const;
  1279. it("终态通知行的折叠头部尾部挂产物 chips(≤ 3 枚),每枚带 kind 词与标题", () => {
  1280. const html = renderUnit(
  1281. workflowNotificationUnit([
  1282. { id: "book", kind: "file", title: "审计报告", version: 2 },
  1283. { id: "perf", kind: "chart", title: "每轮耗时", version: 1 },
  1284. ]),
  1285. { context: artifactContext, locale: "zh-CN" },
  1286. );
  1287. expect(html).toContain('data-testid="workflow-notification-artifacts"');
  1288. expect(
  1289. (html.match(new RegExp(`data-testid="${TID_CHAT_WORKFLOW_ARTIFACT_CHIP}"`, "gu")) ?? [])
  1290. .length,
  1291. ).toBe(2);
  1292. expect(html).toContain("审计报告");
  1293. expect(html).toContain("每轮耗时");
  1294. // 药丸的尾槽从 v2 起带紧凑版号(追记「产物药丸」推翻了「chip 不放版本」的旧规则):
  1295. // 「这次跑的是第 2 版」是一件值得在收据上看到的事;长写在 tooltip 里。
  1296. expect(html).toContain('data-testid="workflow-run-artifact-version"');
  1297. expect(html).toContain(">v2<");
  1298. expect(html).toContain('title="第 2 版"');
  1299. });
  1300. it("超过 3 件时只摆 3 枚,其余折进「+N」", () => {
  1301. const html = renderUnit(
  1302. workflowNotificationUnit(
  1303. Array.from({ length: 5 }, (_unused, index) => ({
  1304. id: `a${index}`,
  1305. kind: "file",
  1306. title: `产物 ${index}`,
  1307. version: 1,
  1308. })),
  1309. ),
  1310. { context: artifactContext, locale: "zh-CN" },
  1311. );
  1312. expect(
  1313. (html.match(new RegExp(`data-testid="${TID_CHAT_WORKFLOW_ARTIFACT_CHIP}"`, "gu")) ?? [])
  1314. .length,
  1315. ).toBe(3);
  1316. expect(html).toContain('data-testid="workflow-notification-artifacts-more"');
  1317. expect(html).toContain("+2");
  1318. });
  1319. it("发射侧砍过(artifactsTruncated)时「+N」用省略号,不报一个会骗人的数字", () => {
  1320. const html = renderUnit(
  1321. workflowNotificationUnit([{ id: "a", kind: "file", title: "只剩一件", version: 1 }], {
  1322. artifactsTruncated: true,
  1323. }),
  1324. { context: artifactContext, locale: "zh-CN" },
  1325. );
  1326. expect(html).toContain('data-testid="workflow-notification-artifacts-more"');
  1327. expect(html).toContain("+…");
  1328. });
  1329. it("载荷缺席(批量轮 / 旧 CLI / 旧 transcript)⇒ 无 chips,通知行其余部分逐字不变", () => {
  1330. const withoutArtifacts = renderUnit(workflowNotificationUnit(undefined), {
  1331. context: artifactContext,
  1332. locale: "zh-CN",
  1333. });
  1334. expect(withoutArtifacts).not.toContain('data-testid="workflow-notification-artifacts"');
  1335. expect(withoutArtifacts).toContain("flaky-test-triage");
  1336. expect(withoutArtifacts).toContain("后台总结最终段");
  1337. // 与「一件产物都没有」的空数组同构:两者都不该长出 chips。
  1338. const emptyArtifacts = renderUnit(workflowNotificationUnit([]), {
  1339. context: artifactContext,
  1340. locale: "zh-CN",
  1341. });
  1342. expect(emptyArtifacts).not.toContain('data-testid="workflow-notification-artifacts"');
  1343. });
  1344. it("宿主没注入打开能力时 chips 仍在场,只是不可点——交付了什么是事实,能不能打开是能力", () => {
  1345. const html = renderUnit(
  1346. workflowNotificationUnit([{ id: "book", kind: "file", title: "审计报告", version: 1 }]),
  1347. { locale: "zh-CN" },
  1348. );
  1349. expect(html).toContain(`data-testid="${TID_CHAT_WORKFLOW_ARTIFACT_CHIP}"`);
  1350. expect(html).toMatch(
  1351. new RegExp(
  1352. `<button(?=[^>]*data-testid="${TID_CHAT_WORKFLOW_ARTIFACT_CHIP}")(?=[^>]*disabled)`,
  1353. "u",
  1354. ),
  1355. );
  1356. });
  1357. it("升级(escalation)通知不长 chips——产物只在终态载荷上", () => {
  1358. const [unit] = buildConversationTurnRenderUnits([
  1359. turnHeader({
  1360. origin: "backgroundResult",
  1361. originMeta: {
  1362. backgroundSource: "workflow",
  1363. title: "flaky-test-triage",
  1364. workId: "run-abc",
  1365. workflowNotification: {
  1366. kind: "escalation",
  1367. qid: "q1",
  1368. question: "要不要继续?",
  1369. actorName: "planner",
  1370. },
  1371. },
  1372. }),
  1373. assistantTextRow(6, { text: "后台总结最终段" }),
  1374. ]);
  1375. const html = renderUnit(unit!, { context: artifactContext, locale: "zh-CN" });
  1376. expect(html).not.toContain('data-testid="workflow-notification-artifacts"');
  1377. });
  1378. it("workflow 通知无载荷时(批量轮 / 旧 transcript)原样退回裸标题行", () => {
  1379. const finalText = assistantTextRow(6, { text: "后台总结最终段" });
  1380. const [unit] = buildConversationTurnRenderUnits([
  1381. turnHeader({
  1382. origin: "backgroundResult",
  1383. originMeta: {
  1384. backgroundSource: "workflow",
  1385. title: "flaky-test-triage",
  1386. workId: "run-abc",
  1387. },
  1388. }),
  1389. finalText,
  1390. ]);
  1391. const html = renderUnit(unit!, { locale: "en-US" });
  1392. expect(html).toContain(`data-testid="chat-background-result-title-${unit!.key}"`);
  1393. expect(html).not.toContain(`data-testid="chat-workflow-notification-row-${unit!.key}"`);
  1394. expect(html).toContain("flaky-test-triage");
  1395. });
  1396. it("在 background result 的 history 兼容路径保留 CUA Group 内 Assistant message 事件", () => {
  1397. const responseId = "background-cua-response";
  1398. const reasoning = {
  1399. ...reasoningRow(),
  1400. assistantResponseId: responseId,
  1401. text: "我需要先检查后台电脑状态。",
  1402. };
  1403. const message = assistantTextRow(4, {
  1404. assistantResponseId: responseId,
  1405. text: "我先检查电脑操作权限与应用列表。",
  1406. });
  1407. const cua = toolCallRow(
  1408. 5,
  1409. "mcp__computer-use__list_apps",
  1410. {},
  1411. {
  1412. assistantResponseId: responseId,
  1413. },
  1414. );
  1415. const html = renderUnit(
  1416. baseUnit({
  1417. key: "turn-background:cua-events",
  1418. header: turnHeader({
  1419. origin: "backgroundResult",
  1420. originMeta: { backgroundSource: "bash", title: "后台 Computer Use", workId: "cua" },
  1421. }),
  1422. assistantWorkRows: [reasoning, message, cua],
  1423. assistantHistoryRows: [reasoning, message, cua],
  1424. renderRows: [reasoning, message, cua],
  1425. }),
  1426. );
  1427. // 折叠态不挂载详情正文;计数同时包含 reasoning 与 message,证明兼容路径没有退化为仅 child tools。
  1428. // CuaGroupToolCallBlock 的 forceOpen 测试另行覆盖详情正文渲染。
  1429. expect(html).toContain("3 个事件, 1 条消息");
  1430. expect(html).not.toContain("1 个事件");
  1431. });
  1432. it("旧 background result 缺少结构化标题时保持耗时折叠兼容分支", () => {
  1433. const row = reasoningRow();
  1434. const html = renderUnit(
  1435. baseUnit({
  1436. header: turnHeader({ origin: "backgroundResult" }),
  1437. workStatus: { state: "completed", durationMs: 5_000 },
  1438. assistantWorkRows: [row],
  1439. assistantHistoryRows: [row],
  1440. renderRows: [row],
  1441. }),
  1442. );
  1443. expect(html).toContain("已工作 5 秒");
  1444. expect(html).toContain("chat-assistant-history-trigger");
  1445. expect(html).not.toContain("chat-background-result-title");
  1446. });
  1447. it("uses the paired subagent row type while the Agent input preview is incomplete", () => {
  1448. const agentRow = toolCallRow(20, "Agent", undefined, {
  1449. status: "inputStreaming",
  1450. inputText: '{"description":"检查投影","prompt":"继续等待',
  1451. });
  1452. const childRow = subagentRow(21, {
  1453. parentToolCallId: agentRow.toolCallId,
  1454. subagentType: "Review",
  1455. status: "running",
  1456. });
  1457. const html = renderUnit(
  1458. baseUnit({
  1459. key: "turn-complete:streaming-agent-type",
  1460. turnId: "turn-complete",
  1461. isRunning: true,
  1462. assistantHistoryDefaultOpen: true,
  1463. assistantWorkRows: [agentRow, childRow],
  1464. assistantHistoryRows: [],
  1465. assistantFollowingRows: [agentRow, childRow],
  1466. renderRows: [agentRow, childRow],
  1467. }),
  1468. );
  1469. expect(html).toContain("Review");
  1470. expect(html).not.toContain("general-purpose");
  1471. });
  1472. it("renders ExitPlanMode at its original row before later tool and assistant output", () => {
  1473. const middleText = assistantTextRow(3, { text: "计划前正文" });
  1474. const plan = toolCallRow(4, "ExitPlanMode", {
  1475. plan: "# PLAN_ROW_ORDER_TITLE",
  1476. });
  1477. const write = toolCallRow(5, "Write", {
  1478. file_path: "/workspace/plan.md",
  1479. content: "done",
  1480. });
  1481. const finalText = assistantTextRow(6, { text: "写入后的最终正文" });
  1482. const [builtUnit] = buildConversationTurnRenderUnits([
  1483. turnHeader(),
  1484. userInputRow(2),
  1485. middleText,
  1486. plan,
  1487. write,
  1488. finalText,
  1489. ]);
  1490. const html = renderUnit({
  1491. ...builtUnit!,
  1492. assistantHistoryDefaultOpen: true,
  1493. });
  1494. const indexes = [
  1495. html.indexOf("计划前正文"),
  1496. html.indexOf("PLAN_ROW_ORDER_TITLE"),
  1497. html.indexOf('data-tool-name="Write"'),
  1498. html.indexOf("写入后的最终正文"),
  1499. ];
  1500. expect(indexes.every((index) => index >= 0)).toBe(true);
  1501. expect(indexes).toEqual([...indexes].sort((left, right) => left - right));
  1502. });
  1503. it("renders per-turn file change summary when the header has fileChanges", () => {
  1504. const html = renderUnit(
  1505. baseUnit({
  1506. key: "turn-complete:file-summary",
  1507. turnId: "turn-complete",
  1508. isLastTurn: false,
  1509. header: turnHeader({
  1510. fileChanges: {
  1511. files: 1,
  1512. additions: 2,
  1513. deletions: 1,
  1514. state: "active",
  1515. },
  1516. }),
  1517. }),
  1518. );
  1519. expect(html).toContain("1 个文件已更改");
  1520. expect(html).toContain("+2");
  1521. expect(html).toContain("-1");
  1522. });
  1523. it("passes visualize references from the whole turn to the summary before details load", () => {
  1524. const reference = assistantTextRow(3, {
  1525. text: '::visualize{"path":"/workspace/calendar.html"}',
  1526. });
  1527. const finalText = assistantTextRow(4, { text: "可视化已完成" });
  1528. const [unit] = buildConversationTurnRenderUnits([
  1529. turnHeader({
  1530. entityId: "header-1",
  1531. fileChanges: { files: 1, additions: 70, deletions: 0, state: "active" },
  1532. }),
  1533. userInputRow(2),
  1534. reference,
  1535. finalText,
  1536. ]);
  1537. const html = renderUnit(unit!, { context: { fetchFileChanges: async () => ({ items: [] }) } });
  1538. expect(html).not.toContain("1 个文件已更改");
  1539. expect(html).not.toContain("+70");
  1540. expect(html).toContain("可视化已完成");
  1541. });
  1542. it("renders the completed assistant action toolbar after the file change summary", () => {
  1543. const createdAt = new Date();
  1544. createdAt.setHours(7, 15, 0, 0);
  1545. const timeLabel = new Intl.DateTimeFormat("zh-CN", {
  1546. hour: "2-digit",
  1547. minute: "2-digit",
  1548. }).format(createdAt);
  1549. const row = assistantTextRow(20, { createdAt: createdAt.getTime() });
  1550. const html = renderUnit(
  1551. baseUnit({
  1552. key: "turn-complete:action-order",
  1553. turnId: "turn-complete",
  1554. isLastTurn: true,
  1555. header: turnHeader({
  1556. fileChanges: {
  1557. files: 1,
  1558. additions: 2,
  1559. deletions: 1,
  1560. state: "active",
  1561. },
  1562. }),
  1563. assistantWorkRows: [row],
  1564. assistantTextRows: [row],
  1565. latestAssistantTextRow: row,
  1566. renderRows: [row],
  1567. }),
  1568. );
  1569. const summaryIndex = html.indexOf("1 个文件已更改");
  1570. const actionIndex = html.indexOf('data-testid="v4-copy-20"');
  1571. const timeIndex = html.indexOf(`>${timeLabel}</span>`);
  1572. expect(summaryIndex).toBeGreaterThanOrEqual(0);
  1573. expect(actionIndex).toBeGreaterThanOrEqual(0);
  1574. expect(timeIndex).toBeGreaterThanOrEqual(0);
  1575. expect(summaryIndex).toBeLessThan(actionIndex);
  1576. expect(actionIndex).toBeLessThan(timeIndex);
  1577. });
  1578. it("P07:在定时任务卡片、文件 summary 和操作栏之后渲染 fork 轮尾分割线", () => {
  1579. const cronTool = toolCallRow(
  1580. 5,
  1581. "CronCreate",
  1582. { title: "5分钟后提醒去干活" },
  1583. {
  1584. output: {
  1585. text: JSON.stringify({
  1586. automation: {
  1587. automationId: "automation-p07",
  1588. title: "5分钟后提醒去干活",
  1589. cronExpr: "*/5 * * * *",
  1590. },
  1591. }),
  1592. },
  1593. },
  1594. );
  1595. const finalText = assistantTextRow(6, {
  1596. text: "已设置好提醒。",
  1597. actions: { canFork: true },
  1598. });
  1599. const [unit] = buildConversationTurnRenderUnits([
  1600. turnHeader({
  1601. fileChanges: {
  1602. files: 1,
  1603. additions: 2,
  1604. deletions: 1,
  1605. state: "active",
  1606. },
  1607. }),
  1608. userInputRow(2),
  1609. cronTool,
  1610. finalText,
  1611. forkNoticeTimelineRow(7),
  1612. ]);
  1613. const html = renderUnit(unit!, {
  1614. compactForRemoteControl: true,
  1615. onFork: vi.fn(),
  1616. onFeedbackChange: vi.fn(),
  1617. });
  1618. const cardIndex = html.indexOf(`data-testid="${TID_CRON_CREATE_CARD}"`);
  1619. const summaryIndex = html.indexOf("1 个文件已更改");
  1620. const dislikeIndex = html.indexOf('data-testid="v4-feedback-dislike-6"');
  1621. const forkActionIndex = html.indexOf('data-testid="v4-fork-6"');
  1622. const boundaryIndex = html.indexOf("从对话中派生");
  1623. expect(cardIndex).toBeGreaterThanOrEqual(0);
  1624. expect(summaryIndex).toBeGreaterThan(cardIndex);
  1625. expect(dislikeIndex).toBeGreaterThan(summaryIndex);
  1626. expect(forkActionIndex).toBeGreaterThan(dislikeIndex);
  1627. expect(boundaryIndex).toBeGreaterThan(forkActionIndex);
  1628. });
  1629. it("P07:goalVerify 共用 turnTailBoundary 并在操作栏之后收尾", () => {
  1630. const finalText = assistantTextRow(6, { text: "目标执行结果。" });
  1631. const goalVerify = runningGoalVerifyTimelineRow(7);
  1632. const [unit] = buildConversationTurnRenderUnits([
  1633. turnHeader(),
  1634. userInputRow(2),
  1635. finalText,
  1636. goalVerify,
  1637. ]);
  1638. const html = renderUnit(unit!);
  1639. expect(html.indexOf('data-testid="v4-copy-6"')).toBeLessThan(html.indexOf("目标校验中"));
  1640. });
  1641. it("renders CronCreate success card after the assistant reply while keeping the tool row ordinary", () => {
  1642. const cronTool = toolCallRow(
  1643. 5,
  1644. "CronCreate",
  1645. { title: "每2小时站起来走走提醒" },
  1646. {
  1647. output: {
  1648. text: JSON.stringify({
  1649. automation: {
  1650. title: "每2小时站起来走走提醒",
  1651. cronExpr: "0 9/2 * * *",
  1652. },
  1653. }),
  1654. },
  1655. },
  1656. );
  1657. const finalText = assistantTextRow(6, {
  1658. text: "已设置:每2小时提醒你站起来走走。",
  1659. });
  1660. const [builtUnit] = buildConversationTurnRenderUnits([
  1661. turnHeader(),
  1662. userInputRow(2),
  1663. cronTool,
  1664. finalText,
  1665. ]);
  1666. const html = renderUnit({
  1667. ...builtUnit!,
  1668. assistantHistoryDefaultOpen: true,
  1669. });
  1670. const toolIndex = html.indexOf('data-tool-call-id="tool-5"');
  1671. const replyIndex = html.indexOf("已设置:每2小时提醒你站起来走走。");
  1672. const cardIndex = html.indexOf(`data-testid="${TID_CRON_CREATE_CARD}"`);
  1673. const actionIndex = html.indexOf('data-testid="v4-copy-6"');
  1674. const cardMatches = html.match(new RegExp(`data-testid="${TID_CRON_CREATE_CARD}"`, "g")) ?? [];
  1675. expect(toolIndex).toBeGreaterThanOrEqual(0);
  1676. expect(replyIndex).toBeGreaterThanOrEqual(0);
  1677. expect(cardIndex).toBeGreaterThanOrEqual(0);
  1678. expect(actionIndex).toBeGreaterThanOrEqual(0);
  1679. expect(cardMatches).toHaveLength(1);
  1680. expect(toolIndex).toBeLessThan(replyIndex);
  1681. expect(replyIndex).toBeLessThan(cardIndex);
  1682. expect(cardIndex).toBeLessThan(actionIndex);
  1683. });
  1684. it("renders the updated automation card after a successful CronUpdate", () => {
  1685. const cronTool = toolCallRow(
  1686. 5,
  1687. "CronUpdate",
  1688. { id: "automation-a", title: "工作日晨会提醒" },
  1689. {
  1690. output: {
  1691. text: JSON.stringify({
  1692. automation: {
  1693. automationId: "automation-a",
  1694. title: "工作日晨会提醒",
  1695. cronExpr: "0 9 * * 1-5",
  1696. },
  1697. }),
  1698. },
  1699. },
  1700. );
  1701. const finalText = assistantTextRow(6, { text: "已修改定时任务。" });
  1702. const [builtUnit] = buildConversationTurnRenderUnits([
  1703. turnHeader(),
  1704. userInputRow(2),
  1705. cronTool,
  1706. finalText,
  1707. ]);
  1708. const html = renderUnit({
  1709. ...builtUnit!,
  1710. assistantHistoryDefaultOpen: true,
  1711. });
  1712. const replyIndex = html.indexOf("已修改定时任务。");
  1713. const cardIndex = html.indexOf(`data-testid="${TID_CRON_CREATE_CARD}"`);
  1714. const actionIndex = html.indexOf('data-testid="v4-copy-6"');
  1715. const cardSummary = html.slice(cardIndex, actionIndex);
  1716. expect(html).toContain('data-tool-call-id="tool-5"');
  1717. expect(replyIndex).toBeGreaterThanOrEqual(0);
  1718. expect(cardIndex).toBeGreaterThan(replyIndex);
  1719. expect(cardIndex).toBeLessThan(actionIndex);
  1720. expect(cardSummary).toContain("工作日晨会提醒");
  1721. expect(cardSummary).toContain("工作日");
  1722. expect(cardSummary).toContain(`data-testid="${TID_CRON_CREATE_OPEN}"`);
  1723. });
  1724. it("只在轮尾展示同轮 Create/Delete 归并后仍存在的 CronCreate 卡片", () => {
  1725. const firstCreate = toolCallRow(
  1726. 5,
  1727. "CronCreate",
  1728. { title: "错误的一分钟提醒" },
  1729. {
  1730. output: {
  1731. text: JSON.stringify({
  1732. automation: {
  1733. automationId: "automation-a",
  1734. title: "错误的一分钟提醒",
  1735. cronExpr: "54 14 17 7 *",
  1736. },
  1737. }),
  1738. },
  1739. },
  1740. );
  1741. const deleteFirst = toolCallRow(
  1742. 6,
  1743. "CronDelete",
  1744. { id: "automation-a" },
  1745. {
  1746. output: {
  1747. text: JSON.stringify({ deleted: true, id: "automation-a" }),
  1748. },
  1749. },
  1750. );
  1751. const secondCreate = toolCallRow(
  1752. 7,
  1753. "CronCreate",
  1754. { title: "一分钟后开嗓提醒" },
  1755. {
  1756. output: {
  1757. text: JSON.stringify({
  1758. automation: {
  1759. automationId: "automation-b",
  1760. title: "一分钟后开嗓提醒",
  1761. cronExpr: "55 14 17 7 *",
  1762. },
  1763. }),
  1764. },
  1765. },
  1766. );
  1767. const finalText = assistantTextRow(8, { text: "已经修正并重新设置。" });
  1768. const [builtUnit] = buildConversationTurnRenderUnits([
  1769. turnHeader(),
  1770. userInputRow(2),
  1771. firstCreate,
  1772. deleteFirst,
  1773. secondCreate,
  1774. finalText,
  1775. ]);
  1776. const html = renderUnit({
  1777. ...builtUnit!,
  1778. assistantHistoryDefaultOpen: true,
  1779. });
  1780. const cardMatches = html.match(new RegExp(`data-testid="${TID_CRON_CREATE_CARD}"`, "g")) ?? [];
  1781. const cardSummary = html.slice(
  1782. html.indexOf(`data-testid="${TID_CRON_CREATE_CARD}"`),
  1783. html.indexOf('data-testid="v4-copy-8"'),
  1784. );
  1785. expect(cardMatches).toHaveLength(1);
  1786. expect(cardSummary).toContain("一分钟后开嗓提醒");
  1787. expect(cardSummary).not.toContain("错误的一分钟提醒");
  1788. expect(html).toContain('data-tool-call-id="tool-5"');
  1789. expect(html).toContain('data-tool-call-id="tool-6"');
  1790. expect(html).toContain('data-tool-call-id="tool-7"');
  1791. });
  1792. it("CronDelete 失败时保留对应的 CronCreate 轮尾卡片", () => {
  1793. const create = toolCallRow(
  1794. 5,
  1795. "CronCreate",
  1796. { title: "仍然有效的提醒" },
  1797. {
  1798. output: {
  1799. text: JSON.stringify({
  1800. automation: {
  1801. automationId: "automation-a",
  1802. title: "仍然有效的提醒",
  1803. cronExpr: "0 9 * * *",
  1804. },
  1805. }),
  1806. },
  1807. },
  1808. );
  1809. const failedDelete = toolCallRow(
  1810. 6,
  1811. "CronDelete",
  1812. { id: "automation-a" },
  1813. {
  1814. status: "error",
  1815. error: { code: "DELETE_FAILED", message: "删除失败" },
  1816. },
  1817. );
  1818. const finalText = assistantTextRow(7, { text: "删除没有成功。" });
  1819. const [builtUnit] = buildConversationTurnRenderUnits([
  1820. turnHeader(),
  1821. userInputRow(2),
  1822. create,
  1823. failedDelete,
  1824. finalText,
  1825. ]);
  1826. const html = renderUnit({
  1827. ...builtUnit!,
  1828. assistantHistoryDefaultOpen: true,
  1829. });
  1830. const cardMatches = html.match(new RegExp(`data-testid="${TID_CRON_CREATE_CARD}"`, "g")) ?? [];
  1831. expect(cardMatches).toHaveLength(1);
  1832. expect(html.slice(html.indexOf(`data-testid="${TID_CRON_CREATE_CARD}"`))).toContain(
  1833. "仍然有效的提醒",
  1834. );
  1835. });
  1836. it("does not render CronCreate success card until the assistant turn finishes", () => {
  1837. const cronTool = toolCallRow(
  1838. 5,
  1839. "CronCreate",
  1840. { title: "每2小时站起来走走提醒" },
  1841. {
  1842. output: {
  1843. text: JSON.stringify({
  1844. automation: {
  1845. title: "每2小时站起来走走提醒",
  1846. cronExpr: "0 9/2 * * *",
  1847. },
  1848. }),
  1849. },
  1850. },
  1851. );
  1852. const streamingText = assistantTextRow(6, {
  1853. state: "streaming",
  1854. text: "已设置:",
  1855. });
  1856. const html = renderUnit(
  1857. baseUnit({
  1858. key: "turn-complete:cron-running-card",
  1859. turnId: "turn-complete",
  1860. header: turnHeader({ state: "running" }),
  1861. isRunning: true,
  1862. workStatus: { state: "running", durationMs: 5_000 },
  1863. assistantHistoryDefaultOpen: true,
  1864. assistantWorkRows: [cronTool, streamingText],
  1865. assistantHistoryRows: [cronTool, streamingText],
  1866. assistantTextRows: [streamingText],
  1867. renderRows: [cronTool, streamingText],
  1868. }),
  1869. );
  1870. expect(html).toContain('data-tool-call-id="tool-5"');
  1871. expect(html).toContain("已设置:");
  1872. expect(html).not.toContain(`data-testid="${TID_CRON_CREATE_CARD}"`);
  1873. });
  1874. it("BTA09:renders the browser turn-end screenshot after preview cards and file summary", () => {
  1875. const finalRow = assistantTextRow(20, {
  1876. text: "网站已启动:http://localhost:3000",
  1877. });
  1878. const screenshotRow = toolCallRow(
  1879. 21,
  1880. "mcp__node_repl__js",
  1881. { source: "browser_turn_end" },
  1882. {
  1883. display: {
  1884. kind: "node_repl_images",
  1885. source: "browser_turn_end",
  1886. images: [{ base64: "AAAA", mimeType: "image/png" }],
  1887. },
  1888. },
  1889. );
  1890. const units = buildConversationTurnRenderUnits([
  1891. turnHeader({
  1892. fileChanges: {
  1893. files: 1,
  1894. additions: 38,
  1895. deletions: 5,
  1896. state: "active",
  1897. },
  1898. }),
  1899. userInputRow(2),
  1900. finalRow,
  1901. screenshotRow,
  1902. ]);
  1903. const html = renderUnit(units[0]!);
  1904. // lastIndexOf 取 Website 卡片标题,避开正文中更早出现的同一 URL。
  1905. const previewIndex = html.lastIndexOf("localhost:3000");
  1906. const summaryIndex = html.indexOf("1 个文件已更改");
  1907. const screenshotIndex = html.indexOf("data:image/png;base64,AAAA");
  1908. const actionIndex = html.indexOf('data-testid="v4-copy-20"');
  1909. expect(previewIndex).toBeGreaterThanOrEqual(0);
  1910. expect(summaryIndex).toBeGreaterThan(previewIndex);
  1911. expect(screenshotIndex).toBeGreaterThan(summaryIndex);
  1912. expect(actionIndex).toBeGreaterThan(screenshotIndex);
  1913. });
  1914. it("PV4-08:fork action 只读取 row.actions.canFork,不按 completed/数组位置猜测", () => {
  1915. const onFork = vi.fn();
  1916. const withoutAuthority = assistantTextRow(20);
  1917. const withAuthority = assistantTextRow(21, { actions: { canFork: true } });
  1918. const unit = (row: AssistantTextRow) =>
  1919. baseUnit({
  1920. key: `turn-complete:fork-${row.rowId}`,
  1921. turnId: "turn-complete",
  1922. isLastTurn: true,
  1923. header: turnHeader(),
  1924. assistantWorkRows: [row],
  1925. assistantTextRows: [row],
  1926. latestAssistantTextRow: row,
  1927. renderRows: [row],
  1928. });
  1929. expect(renderUnit(unit(withoutAuthority), { onFork })).not.toContain("v4-fork-");
  1930. expect(renderUnit(unit(withAuthority), { onFork })).toContain("v4-fork-21");
  1931. });
  1932. it("BG33:普通 assistant retry capability 保留但 UI 入口统一隐藏", () => {
  1933. const onFork = vi.fn();
  1934. const onRetry = vi.fn();
  1935. const backgroundRow = assistantTextRow(30, { actions: { canFork: true } });
  1936. const backgroundHtml = renderUnit(
  1937. baseUnit({
  1938. key: "turn-background:retry-boundary",
  1939. turnId: "turn-complete",
  1940. isLastTurn: true,
  1941. header: turnHeader({
  1942. origin: "backgroundResult",
  1943. originMeta: {
  1944. backgroundSource: "subagent",
  1945. title: "Review retry projection",
  1946. workId: "agent-retry-review",
  1947. },
  1948. }),
  1949. assistantWorkRows: [backgroundRow],
  1950. assistantTextRows: [backgroundRow],
  1951. latestAssistantTextRow: backgroundRow,
  1952. renderRows: [backgroundRow],
  1953. }),
  1954. { onFork, onRetry },
  1955. );
  1956. expect(backgroundHtml).toContain("v4-fork-30");
  1957. expect(backgroundHtml).not.toContain("v4-retry-30");
  1958. const realUserRow = assistantTextRow(31, {
  1959. actions: { canFork: true, canRetry: true },
  1960. });
  1961. const realUserHtml = renderUnit(
  1962. baseUnit({
  1963. key: "turn-real-user:retry-boundary",
  1964. turnId: "turn-complete",
  1965. isLastTurn: true,
  1966. header: turnHeader(),
  1967. assistantWorkRows: [realUserRow],
  1968. assistantTextRows: [realUserRow],
  1969. latestAssistantTextRow: realUserRow,
  1970. renderRows: [realUserRow],
  1971. }),
  1972. { onFork, onRetry },
  1973. );
  1974. expect(realUserHtml).not.toContain("v4-retry-31");
  1975. });
  1976. it("按复制、赞、踩、分叉顺序渲染反馈工具栏,手机远控常显", () => {
  1977. const createdAt = new Date();
  1978. createdAt.setHours(7, 15, 0, 0);
  1979. const timeLabel = new Intl.DateTimeFormat("zh-CN", {
  1980. hour: "2-digit",
  1981. minute: "2-digit",
  1982. }).format(createdAt);
  1983. const row = assistantTextRow(22, {
  1984. actions: { canFork: true },
  1985. createdAt: createdAt.getTime(),
  1986. });
  1987. const html = renderUnit(
  1988. baseUnit({
  1989. key: "turn-complete:feedback",
  1990. turnId: "turn-complete",
  1991. isLastTurn: true,
  1992. header: turnHeader(),
  1993. assistantWorkRows: [row],
  1994. assistantTextRows: [row],
  1995. latestAssistantTextRow: row,
  1996. renderRows: [row],
  1997. }),
  1998. {
  1999. compactForRemoteControl: true,
  2000. onFork: vi.fn(),
  2001. onFeedbackChange: vi.fn(),
  2002. },
  2003. );
  2004. const copyIndex = html.indexOf('data-testid="v4-copy-22"');
  2005. const likeIndex = html.indexOf('data-testid="v4-feedback-like-22"');
  2006. const dislikeIndex = html.indexOf('data-testid="v4-feedback-dislike-22"');
  2007. const forkIndex = html.indexOf('data-testid="v4-fork-22"');
  2008. const timeIndex = html.indexOf(`>${timeLabel}</span>`);
  2009. expect(copyIndex).toBeGreaterThanOrEqual(0);
  2010. expect(copyIndex).toBeLessThan(likeIndex);
  2011. expect(likeIndex).toBeLessThan(dislikeIndex);
  2012. expect(dislikeIndex).toBeLessThan(forkIndex);
  2013. expect(forkIndex).toBeLessThan(timeIndex);
  2014. expect(html).toContain('aria-pressed="false"');
  2015. expect(html).toContain("opacity-100");
  2016. expect(html).not.toContain("group-hover/assistant-turn:opacity-100");
  2017. });
  2018. it("带 CLI action 的 assistant 后面仍有 work row 时也渲染 action", () => {
  2019. const onFork = vi.fn();
  2020. const actionRow = assistantTextRow(4, { actions: { canFork: true } });
  2021. const units = buildConversationTurnRenderUnits([
  2022. turnHeader(),
  2023. userInputRow(2),
  2024. actionRow,
  2025. reasoningRow(),
  2026. ]);
  2027. expect(renderUnit(units[0]!, { onFork })).toContain("v4-fork-4");
  2028. });
  2029. it("preserves text tool text order inside the single assistant history group", () => {
  2030. const units = buildConversationTurnRenderUnits([
  2031. turnHeader(),
  2032. userInputRow(2),
  2033. reasoningRow(),
  2034. assistantTextRow(4, { text: "Let me看看这个项目里有什么。" }),
  2035. toolCallRow(5, "Bash", {
  2036. command: "ls -la /workspace",
  2037. description: "List project files",
  2038. }),
  2039. assistantTextRow(6, { text: "最终回答" }),
  2040. ]);
  2041. const html = renderUnit({
  2042. ...units[0]!,
  2043. assistantHistoryDefaultOpen: true,
  2044. });
  2045. const historyTriggerMatches = html.match(/data-testid="chat-assistant-history-trigger/g) ?? [];
  2046. const earlyTextIndex = html.indexOf("Let me看看这个项目里有什么。");
  2047. const toolIndex = html.indexOf("tool-5");
  2048. const finalTextIndex = html.indexOf("最终回答");
  2049. expect(historyTriggerMatches).toHaveLength(1);
  2050. expect(earlyTextIndex).toBeGreaterThanOrEqual(0);
  2051. expect(toolIndex).toBeGreaterThanOrEqual(0);
  2052. expect(finalTextIndex).toBeGreaterThanOrEqual(0);
  2053. expect(earlyTextIndex).toBeLessThan(toolIndex);
  2054. expect(toolIndex).toBeLessThan(finalTextIndex);
  2055. expect(html).not.toContain('data-testid="v4-copy-4"');
  2056. expect(html).toContain('data-testid="v4-copy-6"');
  2057. });
  2058. it("P06:每条 guided user 开独立工作段,且只展开目标段不影响其它段", () => {
  2059. const units = buildConversationTurnRenderUnits([
  2060. turnHeader({
  2061. workSegments: [
  2062. {
  2063. segmentId: "initial",
  2064. startedAt: 1_700_000_000_000,
  2065. endedAt: 1_700_000_000_005,
  2066. activeMs: 5_000,
  2067. },
  2068. {
  2069. segmentId: "guide-1",
  2070. triggerEntityId: "guide-1",
  2071. startedAt: 1_700_000_000_005,
  2072. endedAt: 1_700_000_000_007,
  2073. activeMs: 2_000,
  2074. },
  2075. {
  2076. segmentId: "guide-2",
  2077. triggerEntityId: "guide-2",
  2078. startedAt: 1_700_000_000_007,
  2079. endedAt: 1_700_000_000_008,
  2080. activeMs: 1_000,
  2081. },
  2082. ],
  2083. }),
  2084. userInputRow(2, { text: "这是个啥项目" }),
  2085. reasoningRow(),
  2086. toolCallRow(4, "Read", { file_path: "AGENTS.md" }),
  2087. userInputRow(5, { text: "111", guided: true, entityId: "guide-1" }),
  2088. assistantTextRow(6, { text: "这是项目介绍" }),
  2089. userInputRow(7, { text: "11", guided: true, entityId: "guide-2" }),
  2090. assistantTextRow(8, { text: "还需要我做什么?" }),
  2091. ]);
  2092. expect(units[0]?.workStatus).toBeDefined();
  2093. const collapsedHtml = renderUnit(units[0]!);
  2094. const collapsedIndexes = [
  2095. collapsedHtml.indexOf('data-row-id="2"'),
  2096. collapsedHtml.indexOf("chat-assistant-history-trigger"),
  2097. collapsedHtml.indexOf('data-row-id="5"'),
  2098. collapsedHtml.indexOf('data-row-id="6"'),
  2099. collapsedHtml.indexOf('data-row-id="7"'),
  2100. collapsedHtml.indexOf('data-row-id="8"'),
  2101. ];
  2102. expect(
  2103. collapsedIndexes.every((index) => index >= 0),
  2104. JSON.stringify(collapsedIndexes),
  2105. ).toBe(true);
  2106. expect(collapsedIndexes).toEqual([...collapsedIndexes].sort((left, right) => left - right));
  2107. expect(collapsedHtml).not.toContain('data-row-id="4"');
  2108. expect(collapsedHtml.match(/chat-assistant-history-trigger/g)).toHaveLength(3);
  2109. expect(collapsedHtml).toContain("已工作 5 秒");
  2110. expect(collapsedHtml).toContain("已工作 2 秒");
  2111. expect(collapsedHtml).toContain("已工作 1 秒");
  2112. const expandedHtml = renderUnit({
  2113. ...units[0]!,
  2114. workSegments: units[0]!.workSegments!.map((segment, index) => ({
  2115. ...segment,
  2116. assistantHistoryDefaultOpen: index === 0,
  2117. })),
  2118. });
  2119. const expandedIndexes = [
  2120. expandedHtml.indexOf('data-row-id="2"'),
  2121. expandedHtml.indexOf('data-row-id="4"'),
  2122. expandedHtml.indexOf('data-row-id="5"'),
  2123. expandedHtml.indexOf('data-row-id="6"'),
  2124. expandedHtml.indexOf('data-row-id="7"'),
  2125. expandedHtml.indexOf('data-row-id="8"'),
  2126. ];
  2127. expect(expandedIndexes.every((index) => index >= 0)).toBe(true);
  2128. expect(expandedIndexes).toEqual([...expandedIndexes].sort((left, right) => left - right));
  2129. expect(expandedHtml.match(/chat-assistant-history-trigger/g)).toHaveLength(3);
  2130. expect(expandedHtml).toContain(
  2131. 'data-testid="chat-assistant-history-trigger-turn-complete" data-history-open="true"',
  2132. );
  2133. expect(expandedHtml).toContain(
  2134. 'data-testid="chat-assistant-history-trigger-turn-complete:guide:guide-1" data-history-open="false"',
  2135. );
  2136. expect(expandedHtml).not.toContain('data-testid="v4-copy-6"');
  2137. expect(expandedHtml).toContain('data-testid="v4-copy-8"');
  2138. });
  2139. });
  2140. describe("ConversationTurnGroup ChatLoading lifecycle", () => {
  2141. it("第三次 retry 才替换当前 turn 底部的通用 loading,并保留 3/10 计数口径", () => {
  2142. const html = renderUnit(
  2143. baseUnit({
  2144. isRunning: true,
  2145. assistantHistoryDefaultOpen: true,
  2146. }),
  2147. {
  2148. apiRetry: {
  2149. attempt: 3,
  2150. maxAttempts: 11,
  2151. nextRetryAt: 1_700_000_001_000,
  2152. reasonCode: "fault.provider.rateLimited",
  2153. },
  2154. },
  2155. );
  2156. expect(html).toContain("重新连接中... 3/10");
  2157. expect(html).not.toContain('data-testid="chat-loading"');
  2158. });
  2159. it.each([1, 2])("attempt=%d 时隐藏 retry 文案并继续显示通用 loading", (attempt) => {
  2160. const html = renderUnit(
  2161. baseUnit({
  2162. isRunning: true,
  2163. assistantHistoryDefaultOpen: true,
  2164. }),
  2165. {
  2166. apiRetry: {
  2167. attempt,
  2168. maxAttempts: 11,
  2169. nextRetryAt: 1_700_000_001_000,
  2170. reasonCode: "fault.provider.rateLimited",
  2171. },
  2172. },
  2173. );
  2174. expect(html).not.toContain("重新连接中...");
  2175. expect(html).toContain('data-testid="chat-loading"');
  2176. expect(html).toContain('data-zcode-chat-loading-slot="true"');
  2177. });
  2178. it("attempt<=2 时仍遵守阻塞交互的 loading gate", () => {
  2179. const html = renderUnit(
  2180. baseUnit({
  2181. isRunning: true,
  2182. assistantHistoryDefaultOpen: true,
  2183. }),
  2184. {
  2185. chatLoadingBlockedByInteraction: true,
  2186. apiRetry: {
  2187. attempt: 2,
  2188. maxAttempts: 11,
  2189. nextRetryAt: 1_700_000_001_000,
  2190. reasonCode: "fault.provider.rateLimited",
  2191. },
  2192. },
  2193. );
  2194. expect(html).not.toContain("重新连接中...");
  2195. expect(html).not.toContain('data-testid="chat-loading"');
  2196. });
  2197. it("retry 清除后恢复当前 running turn 的通用 loading", () => {
  2198. const html = renderUnit(
  2199. baseUnit({
  2200. isRunning: true,
  2201. assistantHistoryDefaultOpen: true,
  2202. }),
  2203. { apiRetry: null },
  2204. );
  2205. expect(html).not.toContain("重新连接中...");
  2206. expect(html).toContain('data-testid="chat-loading"');
  2207. });
  2208. it.each([
  2209. ["assistant text", assistantTextRow(10, { state: "streaming" })],
  2210. ["reasoning", { ...reasoningRow(), state: "streaming" }],
  2211. ["tool", toolCallRow(11, "Bash", { command: "pnpm test" }, { status: "running" })],
  2212. ["subagent", subagentRow(12, { status: "running" })],
  2213. ] as const)("shows loading immediately while a running turn contains %s", (_label, row) => {
  2214. const html = renderUnit(
  2215. baseUnit({
  2216. isRunning: true,
  2217. assistantHistoryDefaultOpen: true,
  2218. assistantWorkRows: [row],
  2219. assistantHistoryRows: [row],
  2220. renderRows: [row],
  2221. }),
  2222. );
  2223. expect(html).toContain('data-testid="chat-loading"');
  2224. });
  2225. it.each([
  2226. ["compact", runningTimelineRow(20)],
  2227. ["goal verifier", runningGoalVerifyTimelineRow(21)],
  2228. ] as const)("hides loading for a running %s timeline-only turn", (_label, row) => {
  2229. const html = renderUnit(
  2230. baseUnit({
  2231. isRunning: true,
  2232. timelineOnly: true,
  2233. assistantWorkRows: [row],
  2234. assistantHistoryRows: [row],
  2235. renderRows: [row],
  2236. }),
  2237. );
  2238. expect(html).not.toContain('data-testid="chat-loading"');
  2239. });
  2240. it("keeps loading visible for a running structured background-result turn", () => {
  2241. const row = assistantTextRow(30, { state: "streaming" });
  2242. const html = renderUnit(
  2243. baseUnit({
  2244. header: turnHeader({
  2245. origin: "backgroundResult",
  2246. originMeta: {
  2247. backgroundSource: "subagent",
  2248. title: "Review projection",
  2249. workId: "agent-work",
  2250. },
  2251. state: "running",
  2252. }),
  2253. isRunning: true,
  2254. assistantWorkRows: [row],
  2255. assistantHistoryRows: [row],
  2256. assistantTextRows: [row],
  2257. renderRows: [row],
  2258. }),
  2259. );
  2260. expect(html).toContain('data-testid="chat-loading"');
  2261. });
  2262. it("hides loading after the latest turn reaches a terminal state", () => {
  2263. const row = assistantTextRow(40);
  2264. const html = renderUnit(
  2265. baseUnit({
  2266. assistantWorkRows: [row],
  2267. assistantTextRows: [row],
  2268. latestAssistantTextRow: row,
  2269. renderRows: [row],
  2270. }),
  2271. );
  2272. expect(html).not.toContain('data-testid="chat-loading"');
  2273. });
  2274. it("hides loading while the session projection is waiting for user interaction", () => {
  2275. const html = renderUnit(
  2276. baseUnit({
  2277. isRunning: true,
  2278. assistantHistoryDefaultOpen: true,
  2279. }),
  2280. { chatLoadingBlockedByInteraction: true },
  2281. );
  2282. expect(html).not.toContain('data-testid="chat-loading"');
  2283. });
  2284. it("hides loading while compact or goal verifier is active", () => {
  2285. const html = renderUnit(
  2286. baseUnit({
  2287. isRunning: true,
  2288. assistantHistoryDefaultOpen: true,
  2289. }),
  2290. { chatLoadingBlockedByActiveWork: true },
  2291. );
  2292. expect(html).not.toContain('data-testid="chat-loading"');
  2293. });
  2294. it("hides loading when a pendingApproval row arrives before interaction state", () => {
  2295. const row = toolCallRow(
  2296. 41,
  2297. "Bash",
  2298. { command: "touch output.txt" },
  2299. { status: "pendingApproval" },
  2300. );
  2301. const html = renderUnit(
  2302. baseUnit({
  2303. isRunning: true,
  2304. assistantHistoryDefaultOpen: true,
  2305. assistantWorkRows: [row],
  2306. assistantHistoryRows: [row],
  2307. renderRows: [row],
  2308. }),
  2309. );
  2310. expect(html).not.toContain('data-testid="chat-loading"');
  2311. });
  2312. it("does not show loading for a stale running historical turn", () => {
  2313. const html = renderUnit(
  2314. baseUnit({
  2315. isLastTurn: false,
  2316. isRunning: true,
  2317. assistantHistoryDefaultOpen: true,
  2318. }),
  2319. );
  2320. expect(html).not.toContain('data-testid="chat-loading"');
  2321. });
  2322. });
  2323. const LAUNCH_META: WorkflowLaunchMeta = {
  2324. runId: "run-42",
  2325. toolCallId: "launch-abc",
  2326. name: "deep-research",
  2327. scope: "global",
  2328. path: "/home/u/.zcode/workflows/deep-research.dwf.ts",
  2329. description: "跨网深挖一个话题并写简报。",
  2330. args: { topic: "adaptive concurrency" },
  2331. };
  2332. // agent 铸造的规范英文句(进 userInput.text,旧客户端 / TUI 的降级呈现);启动卡不显示它。
  2333. const LAUNCH_CANONICAL =
  2334. 'Started the saved workflow "deep-research" (global) from the workflows hub as run run-42.';
  2335. describe("ConversationTurnGroup — 直接启动轮(workflowLaunch)", () => {
  2336. const LAUNCH_GRAPH = {
  2337. steps: [{ id: "ask#1", kind: "ask", label: "a", line: 1, column: 21, lane: "actor#1" }],
  2338. lanes: [{ id: "actor#1", name: "researcher", line: 1, column: 11 }],
  2339. participants: [
  2340. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  2341. ],
  2342. handoffs: [],
  2343. };
  2344. const LAUNCH_RUN: WorkflowRunState = {
  2345. runId: "run-42",
  2346. toolCallId: "launch-abc",
  2347. status: "running",
  2348. usage: { spentTokens: 12, nodesUsed: 1 },
  2349. actors: [{ siteId: "actor#1", ordinal: 1, name: "Ada", sessionId: "s-1", status: "running" }],
  2350. nodes: [
  2351. { siteId: "ask#1", ordinal: 1, phase: "executing", actorSiteId: "actor#1", actorOrdinal: 1 },
  2352. ] as WorkflowRunState["nodes"],
  2353. lastEventSequence: 3,
  2354. };
  2355. const LAUNCH_JOIN: Partial<ConversationRowRenderContext> = {
  2356. sessionId: "session-main",
  2357. workflowRunByRunId: new Map([
  2358. [
  2359. "run-42",
  2360. {
  2361. runId: "run-42",
  2362. toolCallId: "launch-abc",
  2363. status: "running",
  2364. nodesSettled: 0,
  2365. nodesTotal: 1,
  2366. run: LAUNCH_RUN,
  2367. },
  2368. ],
  2369. ]),
  2370. workflowGraphByToolCallId: new Map([["launch-abc", LAUNCH_GRAPH]]),
  2371. };
  2372. function launchRows(meta: WorkflowLaunchMeta | undefined, turnId = "turn-complete") {
  2373. return [
  2374. turnHeader({
  2375. turnId,
  2376. origin: "workflowLaunch",
  2377. executionKind: "controlOnly",
  2378. ...(meta === undefined ? {} : { workflowLaunch: meta }),
  2379. }),
  2380. userInputRow(2, {
  2381. turnId,
  2382. origin: "workflowLaunch",
  2383. text: LAUNCH_CANONICAL,
  2384. ...(meta === undefined ? {} : { workflowLaunch: meta }),
  2385. }),
  2386. ];
  2387. }
  2388. it("启动轮就是一张 run 卡:与工具路径同一张 WorkflowRunDigest(时间线、子代理药丸),没有用户气泡", () => {
  2389. const [unit] = buildConversationTurnRenderUnits(launchRows(LAUNCH_META));
  2390. expect(unit!.workflowLaunch).toEqual(LAUNCH_META);
  2391. expect(unit!.visibleUserInputs).toEqual([]);
  2392. const html = renderUnit(unit!, { context: LAUNCH_JOIN });
  2393. expect(html).toContain(
  2394. `data-testid="${testId(TID_CHAT_WORKFLOW_RUN_DIGEST, `${unit!.key}-launch-abc`)}"`,
  2395. );
  2396. expect(html).toContain('data-workflow-run-id="run-42"');
  2397. expect(html).toContain('data-workflow-run-status="running"');
  2398. expect(html).toContain("deep-research");
  2399. expect(html).toContain('data-testid="workflow-timeline-station"');
  2400. expect(html).toContain('data-testid="workflow-agent-pill"');
  2401. // 卡就是这一轮的全部呈现:不落那句规范英文气泡,也没有实参表(来龙去脉在详情侧板)。
  2402. expect(html).not.toContain(LAUNCH_CANONICAL);
  2403. expect(html).not.toContain("adaptive concurrency");
  2404. expect(html.match(/data-workflow-run-digest="true"/g)).toHaveLength(1);
  2405. });
  2406. it("run 不在活投影里(淘汰 / 冷恢复):中性单行卡「Workflow ended」,无灯无轨道,仍不落气泡", () => {
  2407. const [unit] = buildConversationTurnRenderUnits(launchRows(LAUNCH_META));
  2408. const html = renderUnit(unit!, { context: { sessionId: "session-main" }, locale: "en-US" });
  2409. expect(html).toContain('data-workflow-run-digest="true"');
  2410. expect(html).toContain('data-workflow-run-status="absent"');
  2411. expect(html).toContain("Workflow ended");
  2412. expect(html).toContain("deep-research");
  2413. expect(html).not.toContain('data-testid="workflow-timeline-station"');
  2414. expect(html).not.toContain('data-testid="workflow-digest-cancel"');
  2415. expect(html).not.toContain(LAUNCH_CANONICAL);
  2416. });
  2417. it("元数据缺席时落穿到普通渲染(降级为规范句气泡)", () => {
  2418. const [unit] = buildConversationTurnRenderUnits(launchRows(undefined));
  2419. expect(unit!.workflowLaunch).toBeUndefined();
  2420. const html = renderUnit(unit!);
  2421. expect(html).not.toContain('data-workflow-run-digest="true"');
  2422. // 规范句进气泡(引号在 HTML 里转义,断言无引号片段)。
  2423. expect(html).toContain("from the workflows hub as run run-42.");
  2424. });
  2425. it("后续普通轮不受影响", () => {
  2426. const units = buildConversationTurnRenderUnits([
  2427. ...launchRows(LAUNCH_META, "turn-launch"),
  2428. turnHeader({ rowId: 3, createdAtSeq: 3, turnId: "turn-next" }),
  2429. userInputRow(4, { turnId: "turn-next", text: "看看下一步" }),
  2430. ]);
  2431. const launchUnit = units.find((unit) => unit.turnId === "turn-launch");
  2432. const nextUnit = units.find((unit) => unit.turnId === "turn-next");
  2433. expect(launchUnit).toBeDefined();
  2434. expect(nextUnit).toBeDefined();
  2435. expect(renderUnit(launchUnit!, { context: LAUNCH_JOIN })).toContain(
  2436. 'data-workflow-run-digest="true"',
  2437. );
  2438. const nextHtml = renderUnit(nextUnit!, { context: LAUNCH_JOIN });
  2439. expect(nextHtml).not.toContain('data-workflow-run-digest="true"');
  2440. expect(nextHtml).toContain("看看下一步");
  2441. });
  2442. });
  2443. // ── 轮尾摘要(docs/dynamic-workflow/presentation.md「The run card」)──
  2444. const DIGEST_GRAPH = {
  2445. steps: [{ id: "ask#1", kind: "ask", label: "a", line: 1, column: 21, lane: "actor#1" }],
  2446. lanes: [{ id: "actor#1", name: "planner", line: 1, column: 11 }],
  2447. participants: [{ id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] }],
  2448. handoffs: [],
  2449. };
  2450. function workflowToolRow(rowId: number, overrides: Partial<ToolCallRow> = {}): ToolCallRow {
  2451. return toolCallRow(
  2452. rowId,
  2453. "CreateWorkflow",
  2454. { name: "implement-verify", script: "const p = agent('planner');" },
  2455. {
  2456. output: {
  2457. text: "ok",
  2458. display: {
  2459. kind: "create_workflow",
  2460. ok: true,
  2461. errorCount: 0,
  2462. diagnostics: [],
  2463. causalityGraph: DIGEST_GRAPH,
  2464. },
  2465. } as ToolCallRow["output"],
  2466. ...overrides,
  2467. },
  2468. );
  2469. }
  2470. const DIGEST_RUN: WorkflowRunState = {
  2471. runId: "run-7",
  2472. toolCallId: "tool-5",
  2473. status: "running",
  2474. usage: { spentTokens: 12, nodesUsed: 1 },
  2475. actors: [{ siteId: "actor#1", ordinal: 1, name: "Ada", sessionId: "s-1", status: "running" }],
  2476. nodes: [
  2477. { siteId: "ask#1", ordinal: 1, phase: "executing", actorSiteId: "actor#1", actorOrdinal: 1 },
  2478. ] as WorkflowRunState["nodes"],
  2479. lastEventSequence: 3,
  2480. };
  2481. const DIGEST_JOIN: Partial<ConversationRowRenderContext> = {
  2482. sessionId: "session-main",
  2483. // 图按发起 toolCallId 到图表取(docs/dynamic-workflow/presentation.md「The run card」)。
  2484. workflowGraphByToolCallId: new Map([["tool-5", DIGEST_GRAPH]]),
  2485. workflowRunByToolCallId: new Map([
  2486. [
  2487. "tool-5",
  2488. {
  2489. runId: "run-7",
  2490. toolCallId: "tool-5",
  2491. status: "running",
  2492. nodesSettled: 0,
  2493. nodesTotal: 1,
  2494. run: DIGEST_RUN,
  2495. },
  2496. ],
  2497. ]),
  2498. };
  2499. describe("ConversationTurnGroup — 轮尾摘要(workflow run digest)", () => {
  2500. it("轮结束后,联接到 run 的 CreateWorkflow 行在最后一段正文之后、操作栏之前多出一张摘要;工具卡本身仍在折叠里", () => {
  2501. const tool = workflowToolRow(5);
  2502. const finalText = assistantTextRow(6, { text: "已启动,跑完我会汇报。" });
  2503. const [unit] = buildConversationTurnRenderUnits([
  2504. turnHeader(),
  2505. userInputRow(2),
  2506. tool,
  2507. finalText,
  2508. ]);
  2509. const html = renderUnit(
  2510. { ...unit!, assistantHistoryDefaultOpen: true },
  2511. { context: DIGEST_JOIN },
  2512. );
  2513. const toolIndex = html.indexOf('data-tool-call-id="tool-5"');
  2514. const replyIndex = html.indexOf("已启动,跑完我会汇报。");
  2515. const digestIndex = html.indexOf('data-workflow-run-digest="true"');
  2516. const actionIndex = html.indexOf('data-testid="v4-copy-6"');
  2517. expect(toolIndex).toBeGreaterThanOrEqual(0);
  2518. expect(digestIndex).toBeGreaterThanOrEqual(0);
  2519. expect(toolIndex).toBeLessThan(replyIndex);
  2520. expect(replyIndex).toBeLessThan(digestIndex);
  2521. expect(digestIndex).toBeLessThan(actionIndex);
  2522. expect(html.match(/data-workflow-run-digest="true"/g)).toHaveLength(1);
  2523. // 收起态:阶段线在、药丸不在(折叠里的卡照旧画药丸,只看摘要那一段);名字与运行状态在表头。
  2524. const digestHtml = html.slice(digestIndex, actionIndex);
  2525. expect(digestHtml).toContain('data-testid="workflow-timeline-station"');
  2526. expect(digestHtml).toContain("implement-verify");
  2527. expect(digestHtml).toContain('data-workflow-run-status="running"');
  2528. expect(digestHtml).toContain('data-testid="workflow-agent-pill"');
  2529. // sessionId + onOpenWorkflowRun 都在场才有 ⤢;这里没注入回调,就没有。
  2530. expect(digestHtml).not.toContain('data-testid="workflow-card-open-details"');
  2531. });
  2532. it("主轮仍在运行时,有 run 立即显示摘要;没联接到 run 的行没有", () => {
  2533. const tool = workflowToolRow(5);
  2534. const streaming = assistantTextRow(6, { state: "streaming", text: "正在…" });
  2535. const running = baseUnit({
  2536. key: "turn-complete:digest-running",
  2537. turnId: "turn-complete",
  2538. header: turnHeader({ state: "running" }),
  2539. isRunning: true,
  2540. workStatus: { state: "running", durationMs: 5_000 },
  2541. assistantHistoryDefaultOpen: true,
  2542. assistantWorkRows: [tool, streaming],
  2543. assistantHistoryRows: [tool, streaming],
  2544. assistantTextRows: [streaming],
  2545. renderRows: [tool, streaming],
  2546. });
  2547. const runningHtml = renderUnit(running, { context: DIGEST_JOIN });
  2548. expect(runningHtml).toContain('data-tool-call-id="tool-5"');
  2549. expect(runningHtml.match(/data-workflow-run-digest="true"/g)).toHaveLength(1);
  2550. expect(runningHtml).toContain('data-testid="workflow-tool-summary"');
  2551. expect(runningHtml).not.toContain('data-testid="workflow-card"');
  2552. expect(runningHtml).toContain('data-testid="workflow-timeline-station"');
  2553. const [finished] = buildConversationTurnRenderUnits([
  2554. turnHeader(),
  2555. userInputRow(2),
  2556. tool,
  2557. assistantTextRow(6),
  2558. ]);
  2559. expect(renderUnit(finished!)).not.toContain('data-workflow-run-digest="true"');
  2560. });
  2561. });
  2562. // 完成卡(docs/dynamic-workflow/transcript-and-notifications.md):主代理消化 completed 通知的那一轮,轮尾落卡。
  2563. // 这里没有会话上下文(静态渲染),卡画的是冷态那一层:通知载荷的产物(纸页字形)+ 联接到的数字。
  2564. const COMPLETION_RUN: WorkflowRunState = {
  2565. ...DIGEST_RUN,
  2566. runId: "run-done",
  2567. status: "completed",
  2568. usage: { spentTokens: 386_412, nodesUsed: 16 },
  2569. phases: [{ name: "plan", rounds: 1 }],
  2570. artifacts: [
  2571. { id: "brief", kind: "markdown", title: "research-brief.md", version: 1, bytes: 12_288 },
  2572. ],
  2573. };
  2574. function completionUnit(status: "completed" | "failed" | "cancelled", withArtifacts = true) {
  2575. const [unit] = buildConversationTurnRenderUnits([
  2576. turnHeader({
  2577. origin: "backgroundResult",
  2578. originMeta: {
  2579. backgroundSource: "workflow",
  2580. title: "deep-research",
  2581. workId: "run-done",
  2582. workflowNotification: {
  2583. kind: "terminal",
  2584. status,
  2585. summary: "Workflow run completed.",
  2586. durationMs: 708_000,
  2587. ...(withArtifacts
  2588. ? {
  2589. artifacts: [
  2590. { id: "brief", kind: "markdown", title: "research-brief.md", version: 1 },
  2591. { id: "sources", kind: "file", title: "sources.csv", version: 2 },
  2592. ],
  2593. }
  2594. : {}),
  2595. },
  2596. },
  2597. }),
  2598. assistantTextRow(6, { text: "研究跑完了,摘要如下。" }),
  2599. ]);
  2600. return unit!;
  2601. }
  2602. const COMPLETION_JOIN: Partial<ConversationRowRenderContext> = {
  2603. sessionId: "session-main",
  2604. onOpenWorkflowRun: () => {},
  2605. onOpenWorkflowArtifact: () => {},
  2606. workflowRunByRunId: new Map([
  2607. [
  2608. "run-done",
  2609. {
  2610. runId: "run-done",
  2611. toolCallId: "tool-launch",
  2612. status: "completed",
  2613. nodesSettled: 16,
  2614. nodesTotal: 16,
  2615. run: COMPLETION_RUN,
  2616. },
  2617. ],
  2618. ]),
  2619. };
  2620. describe("ConversationTurnGroup — 完成卡(workflow completion card)", () => {
  2621. it("completed 通知轮:卡在最后一段正文之后、操作栏之前,且只一张;通知行仍在最前", () => {
  2622. const unit = completionUnit("completed");
  2623. const html = renderUnit(unit, { context: COMPLETION_JOIN, locale: "en-US" });
  2624. const rowIndex = html.indexOf(`data-testid="chat-workflow-notification-row-${unit.key}"`);
  2625. const replyIndex = html.indexOf("研究跑完了,摘要如下。");
  2626. const cardIndex = html.indexOf('data-workflow-completion-card="true"');
  2627. const actionIndex = html.indexOf('data-testid="v4-copy-6"');
  2628. expect(rowIndex).toBeGreaterThanOrEqual(0);
  2629. expect(cardIndex).toBeGreaterThanOrEqual(0);
  2630. expect(rowIndex).toBeLessThan(replyIndex);
  2631. expect(replyIndex).toBeLessThan(cardIndex);
  2632. expect(cardIndex).toBeLessThan(actionIndex);
  2633. expect(html.match(/data-workflow-completion-card="true"/g)).toHaveLength(1);
  2634. const card = html.slice(cardIndex, actionIndex);
  2635. // 表头:种类词 + 名字 + 状态词 + ⤢(sessionId + 回调 + 联接到的 toolCallId 都在)。
  2636. expect(card).toContain("Workflow completed");
  2637. expect(card).toContain("deep-research");
  2638. expect(card).toContain('data-testid="workflow-completion-status"');
  2639. expect(card).toContain('data-testid="workflow-card-open-details"');
  2640. // 产物索引:没有交付物 ⇒ 两行、没有框(索引不画预览,也就没有纸页字形);v2 尾槽在;可点。
  2641. expect(card.match(/data-testid="workflow-completion-line"/g)).toHaveLength(2);
  2642. expect(card).toContain('data-testid="workflow-completion-index"');
  2643. expect(card).not.toContain('data-testid="workflow-artifact-sheet"');
  2644. expect(card).toContain(">v2<");
  2645. expect(card).toContain('data-artifact-open="true"');
  2646. // 四格:时间来自通知,其余三格来自联接到的投影。
  2647. expect(card).toContain('data-value="11m 48s"');
  2648. expect(card).toContain('data-value="386.4k"');
  2649. // 夹具里一个子代理、一个进过的阶段;卡上不说「步」(2026-09-09)。
  2650. expect(card).toMatch(/workflow-completion-figure-subagents" data-value="1"/u);
  2651. expect(card).toMatch(/workflow-completion-figure-phases" data-value="1"/u);
  2652. expect(card).not.toContain("figure-steps");
  2653. });
  2654. it("联接不到 run(冷恢复):时间与产物照画,其余三格 `—`,无 ⤢;零产物没有索引", () => {
  2655. const html = renderUnit(completionUnit("completed"), { locale: "en-US" });
  2656. const cardIndex = html.indexOf('data-workflow-completion-card="true"');
  2657. expect(cardIndex).toBeGreaterThanOrEqual(0);
  2658. const card = html.slice(cardIndex);
  2659. expect(card).toContain('data-value="11m 48s"');
  2660. expect(card).not.toContain('data-value="386.4k"');
  2661. expect(card).toContain("—");
  2662. expect(card).not.toContain('data-testid="workflow-card-open-details"');
  2663. expect(card.match(/data-testid="workflow-completion-line"/g)).toHaveLength(2);
  2664. const bare = renderUnit(completionUnit("completed", false), { locale: "en-US" });
  2665. expect(bare).toContain('data-workflow-completion-card="true"');
  2666. expect(bare).not.toContain('data-testid="workflow-completion-index"');
  2667. });
  2668. // 交付物(docs/dynamic-workflow/transcript-and-notifications.md「Artifact tiles」):载荷上的 primary + description
  2669. // 让冷态卡(没有会话上下文)也画得出交付物行——冷 transcript 上只有这份载荷可读。
  2670. it("载荷带 primary:冷态卡画交付物行(说明来自载荷)+ 索引行;没有「primary」字样", () => {
  2671. const [unit] = buildConversationTurnRenderUnits([
  2672. turnHeader({
  2673. origin: "backgroundResult",
  2674. originMeta: {
  2675. backgroundSource: "workflow",
  2676. title: "deep-research",
  2677. workId: "run-done",
  2678. workflowNotification: {
  2679. kind: "terminal",
  2680. status: "completed",
  2681. summary: "Workflow run completed.",
  2682. durationMs: 708_000,
  2683. artifacts: [
  2684. {
  2685. id: "report",
  2686. kind: "markdown",
  2687. title: "Research report",
  2688. version: 2,
  2689. primary: true,
  2690. description: "Twelve sources compared; three claims confirmed.",
  2691. },
  2692. { id: "sources", kind: "file", title: "sources.csv", version: 1 },
  2693. ],
  2694. },
  2695. },
  2696. }),
  2697. assistantTextRow(6, { text: "研究跑完了,摘要如下。" }),
  2698. ]);
  2699. const html = renderUnit(unit!, { locale: "en-US" });
  2700. const card = html.slice(html.indexOf('data-workflow-completion-card="true"'));
  2701. expect(card).toContain('data-testid="workflow-completion-row"');
  2702. expect(card).toContain("Twelve sources compared; three claims confirmed.");
  2703. expect(card.match(/data-testid="workflow-completion-line"/g)).toHaveLength(1);
  2704. expect(card).toContain('data-variant="line"');
  2705. expect(card).toContain('data-testid="workflow-completion-index"');
  2706. expect(card).not.toMatch(/>\s*primary\s*</iu);
  2707. });
  2708. it.each(["failed", "cancelled"] as const)("%s 的通知轮不画卡", (status) => {
  2709. const html = renderUnit(completionUnit(status), { context: COMPLETION_JOIN });
  2710. expect(html).not.toContain('data-workflow-completion-card="true"');
  2711. expect(html).toContain("deep-research");
  2712. });
  2713. it("主轮还在跑时没有卡", () => {
  2714. const finished = completionUnit("completed");
  2715. const running = baseUnit({
  2716. ...finished,
  2717. key: "turn-complete:completion-running",
  2718. isRunning: true,
  2719. workStatus: { state: "running", durationMs: 5_000 },
  2720. });
  2721. expect(renderUnit(running, { context: COMPLETION_JOIN })).not.toContain(
  2722. 'data-workflow-completion-card="true"',
  2723. );
  2724. });
  2725. });
  2726. describe("topic preparation flow membership", () => {
  2727. it("renders preparing messages inside the conversation turn with a source loading indicator", () => {
  2728. const items = [
  2729. {
  2730. messageId: "pending-a",
  2731. senderName: "Alice",
  2732. text: "weather",
  2733. status: "preparing" as const,
  2734. },
  2735. ];
  2736. const unit = withTopicPreparationMessages([], [], items)[0]!;
  2737. const botContext = {
  2738. taskId: "task",
  2739. context: { activeTaskId: "task", group: { threadId: "topic" } },
  2740. busyId: null,
  2741. retryPreparation: async () => {},
  2742. } as NonNullable<ContextType<typeof DeliveryContext>>;
  2743. for (const compactForRemoteControl of [false, true]) {
  2744. const html = renderUnit(unit, { botContext, compactForRemoteControl });
  2745. expect(html).toContain('data-topic-preparation="pending-a"');
  2746. const preparation = html.indexOf('data-topic-preparation="pending-a"');
  2747. expect(html.indexOf("<section")).toBeLessThan(preparation);
  2748. expect(html.indexOf("</section>")).toBeGreaterThan(preparation);
  2749. expect(html).toContain('data-v4-user-input-collapsible-content="true"');
  2750. expect(html).toContain('aria-label="正在准备材料"');
  2751. }
  2752. });
  2753. });