v4ConversationTurnGroup.test.ts 109 KB

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