| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956 |
- import { readFileSync } from "node:fs";
- import { createElement, type ContextType } from "react";
- import { DeliveryContext } from "@/v4/botGroupDeliveryContext.js";
- import { withTopicPreparationMessages } from "@/v4/topicPreparationRenderUnits.js";
- import { renderToStaticMarkup } from "react-dom/server";
- import { describe, expect, it, vi } from "vitest";
- import type { IPlatformService } from "@zcode/shared";
- import type {
- ApiRetryState,
- AssistantTextRow,
- ConversationRowTarget,
- HookInvocationRow,
- ReasoningRow,
- SubagentRow,
- TimelineMarkerRow,
- ToolCallRow,
- TurnHeaderRow,
- UserInputRow,
- WorkflowLaunchMeta,
- WorkflowRunState,
- } from "@zcode/shared/zcode-protocol-v4";
- import { TID_CHAT_WORKFLOW_ARTIFACT_CHIP, TID_CHAT_WORKFLOW_RUN_DIGEST } from "@zcode/shared";
- import { TID_CRON_CREATE_CARD, TID_CRON_CREATE_OPEN, testId } from "@zcode/shared/test-ids";
- import { TooltipProvider } from "@/components/ui/tooltip.js";
- import { PlatformProvider } from "@/hooks/usePlatform.js";
- import { DEFAULT_CODE_PREVIEW_SETTINGS } from "@/lib/codePreviewSettings.js";
- import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
- import { ConversationTurnGroup } from "@/v4/ConversationTurnGroup.js";
- import {
- completeHighspeedTurn,
- markHighspeedTurnMetricsPersisted,
- recordHighspeedTurn,
- setHighspeedCardTps,
- } from "@/highspeed/highspeedTurnStore.js";
- import type { ConversationRowRenderContext } from "@/v4/conversationRowContext.js";
- import {
- buildConversationTurnRenderUnits,
- type ConversationTurnRenderUnit,
- } from "@/v4/conversationTurnRenderUnits.js";
- vi.mock("@/hooks/useWorkspaceServices.js", () => ({
- useWorkspaceServices: () => ({}),
- }));
- vi.mock("@/hooks/useServices.js", () => ({
- useOptionalServices: () => ({
- highspeedCardService: { share: vi.fn() },
- }),
- }));
- const topicInterrupted = vi.hoisted(() => vi.fn(() => false));
- vi.mock("@/v4/botGroupDeliveryContext.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("@/v4/botGroupDeliveryContext.js")>()),
- useBotTopicInterruption: topicInterrupted,
- }));
- const rowContext: ConversationRowRenderContext = {
- workspacePath: "/workspace",
- theme: "system",
- codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
- };
- const noopPlatform = {} as IPlatformService;
- function reasoningRow(): ReasoningRow {
- return {
- rowId: 3,
- turnId: "turn-complete",
- createdAt: 1_700_000_000_003,
- createdAtSeq: 3,
- kind: "reasoning",
- state: "complete",
- text: "完成了",
- };
- }
- function toolCallRow(
- rowId: number,
- toolName: string,
- input: unknown,
- overrides: Partial<ToolCallRow> = {},
- ): ToolCallRow {
- return {
- rowId,
- turnId: "turn-complete",
- createdAt: 1_700_000_000_000 + rowId,
- createdAtSeq: rowId,
- kind: "toolCall",
- toolCallId: `tool-${rowId}`,
- toolName,
- status: "success",
- input,
- inputText: JSON.stringify(input),
- ...overrides,
- };
- }
- function subagentRow(rowId: number, overrides: Partial<SubagentRow> = {}): SubagentRow {
- return {
- rowId,
- turnId: "turn-complete",
- createdAt: 1_700_000_000_000 + rowId,
- createdAtSeq: rowId,
- kind: "subagent",
- subagentType: "Explore",
- status: "complete",
- summaryText: "完成分析",
- childSessionId: `child-session-${rowId}`,
- ...overrides,
- };
- }
- function assistantTextRow(
- rowId: number,
- overrides: Partial<AssistantTextRow> = {},
- ): AssistantTextRow {
- return {
- rowId,
- entityId: `message-assistant-${rowId}`,
- turnId: "turn-complete",
- createdAt: 1_700_000_000_000 + rowId,
- createdAtSeq: rowId,
- kind: "assistantText",
- state: "complete",
- text: "完成回复",
- ...overrides,
- };
- }
- function hookInvocationRow(
- rowId: number,
- overrides: Partial<HookInvocationRow> = {},
- ): HookInvocationRow {
- return {
- rowId,
- turnId: "turn-complete",
- entityId: `hook-invocation-${rowId}`,
- productTurnId: "turn-complete",
- visibility: "visible",
- createdAt: 1_700_000_000_000 + rowId,
- createdAtSeq: rowId,
- kind: "hookInvocation",
- hookInvocationId: `hook-invocation-${rowId}`,
- hookEventName: "PreToolUse",
- hookCount: 1,
- state: "completed",
- startedAt: 1_700_000_000_000 + rowId,
- endedAt: 1_700_000_000_010 + rowId,
- durationMs: 10,
- lane: "toolBefore",
- anchorToolCallId: "tool-3",
- executions: [
- {
- hookRunId: `hook-run-${rowId}`,
- hookIndex: 0,
- didExecute: true,
- state: "completed",
- outcome: "success",
- startedAt: 1_700_000_000_000 + rowId,
- endedAt: 1_700_000_000_010 + rowId,
- durationMs: 10,
- displayName: "validate-write",
- sourceKind: "project",
- toolName: "Write",
- },
- ],
- ...overrides,
- };
- }
- function runningTimelineRow(rowId: number): TimelineMarkerRow {
- return {
- rowId,
- turnId: "turn-complete",
- createdAt: 1_700_000_000_000 + rowId,
- createdAtSeq: rowId,
- kind: "timelineMarker",
- lane: "assistantWork",
- marker: {
- type: "compact",
- origin: "manual",
- status: "running",
- },
- };
- }
- function runningGoalVerifyTimelineRow(rowId: number): TimelineMarkerRow {
- return {
- rowId,
- turnId: "turn-complete",
- createdAt: 1_700_000_000_000 + rowId,
- createdAtSeq: rowId,
- kind: "timelineMarker",
- lane: "turnTailBoundary",
- marker: {
- type: "goalVerify",
- iteration: 1,
- outcome: "running",
- },
- };
- }
- function forkNoticeTimelineRow(rowId: number): TimelineMarkerRow {
- return {
- rowId,
- turnId: "turn-complete",
- createdAt: 1_700_000_000_000 + rowId,
- createdAtSeq: rowId,
- kind: "timelineMarker",
- lane: "turnTailBoundary",
- marker: {
- type: "forkNotice",
- parentSessionId: "session-parent",
- parentRowId: 1,
- },
- };
- }
- function turnHeader(overrides: Partial<TurnHeaderRow> = {}): TurnHeaderRow {
- return {
- rowId: 1,
- turnId: "turn-complete",
- createdAt: 1_700_000_000_000,
- createdAtSeq: 1,
- kind: "turnHeader",
- origin: "userInput",
- state: "completedSuccess",
- startedAt: 1_700_000_000_000,
- ...overrides,
- };
- }
- function userInputRow(rowId: number, overrides: Partial<UserInputRow> = {}): UserInputRow {
- return {
- rowId,
- turnId: "turn-complete",
- createdAt: 1_700_000_000_000 + rowId,
- createdAtSeq: rowId,
- kind: "userInput",
- text: "看看项目",
- origin: "realUser",
- ...overrides,
- };
- }
- function baseUnit(overrides: Partial<ConversationTurnRenderUnit>): ConversationTurnRenderUnit {
- const synthesizedFlowItems: ConversationTurnRenderUnit["flowItems"] = [
- ...(overrides.visibleUserInputs ?? []).map((row) => ({
- kind: "userInput" as const,
- row,
- })),
- ...((overrides.assistantHistoryRows?.length ?? 0) > 0
- ? [
- {
- kind: "assistantHistory" as const,
- rows: overrides.assistantHistoryRows!,
- },
- ]
- : []),
- ...(overrides.latestAssistantTextRow
- ? [
- {
- kind: "assistantText" as const,
- row: overrides.latestAssistantTextRow,
- latest: true,
- },
- ]
- : []),
- ...((overrides.assistantFollowingRows?.length ?? 0) > 0
- ? [
- {
- kind: "assistantWork" as const,
- rows: overrides.assistantFollowingRows!,
- },
- ]
- : []),
- ];
- return {
- key: "turn-1:1",
- turnId: "turn-1",
- visibleUserInputs: [],
- assistantWorkRows: [],
- assistantHistoryRows: [],
- assistantFollowingRows: [],
- assistantTailRows: [],
- browserTurnEndRows: [],
- hookInvocations: [],
- assistantTextRows: [],
- leadingBoundaryRows: [],
- flowItems: synthesizedFlowItems,
- renderRows: [],
- isLastTurn: true,
- isRunning: false,
- assistantHistoryDefaultOpen: false,
- timelineOnly: false,
- ...overrides,
- };
- }
- function renderUnit(
- unit: ConversationTurnRenderUnit,
- options: {
- locale?: "zh-CN" | "en-US";
- botContext?: ContextType<typeof DeliveryContext>;
- chatLoadingBlockedByActiveWork?: boolean;
- chatLoadingBlockedByInteraction?: boolean;
- compactForRemoteControl?: boolean;
- messageStreamShowReasoning?: boolean;
- messageStreamShowTodos?: boolean;
- apiRetry?: ApiRetryState | null;
- nowMs?: number;
- onFork?: (rowId: number) => void;
- onRetry?: (target: ConversationRowTarget) => void;
- onFeedbackChange?: (target: ConversationRowTarget, feedback: "like" | "dislike" | null) => void;
- /** 覆盖行渲染上下文的若干键(产物 chips 的门就是 `sessionId` + `onOpenWorkflowArtifact`)。 */
- context?: Partial<ConversationRowRenderContext>;
- } = {},
- ): string {
- return renderToStaticMarkup(
- createElement(
- DeliveryContext.Provider,
- { value: options.botContext ?? null },
- createElement(
- ZCodeIntlProvider,
- { initialLocale: options.locale ?? "zh-CN" },
- createElement(
- PlatformProvider,
- { platform: noopPlatform },
- createElement(
- TooltipProvider,
- null,
- createElement(ConversationTurnGroup, {
- unit,
- nowMs: options.nowMs,
- apiRetry: options.apiRetry,
- context: {
- ...rowContext,
- chatLoadingBlockedByActiveWork: options.chatLoadingBlockedByActiveWork,
- chatLoadingBlockedByInteraction: options.chatLoadingBlockedByInteraction,
- compactForRemoteControl: options.compactForRemoteControl,
- messageStreamShowReasoning: options.messageStreamShowReasoning,
- messageStreamShowTodos: options.messageStreamShowTodos,
- ...options.context,
- },
- onFork: options.onFork,
- onRetry: options.onRetry,
- onFeedbackChange: options.onFeedbackChange,
- }),
- ),
- ),
- ),
- ),
- );
- }
- describe("ConversationTurnGroup layout", () => {
- it("removes the complete external assistant container after its response becomes CUA", () => {
- const responseId = "assistant-response-cua";
- const message = assistantTextRow(3, {
- assistantResponseId: responseId,
- text: "我先检查电脑操作权限与应用列表。",
- });
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- message,
- toolCallRow(
- 4,
- "mcp__computer-use__list_apps",
- {},
- {
- assistantResponseId: responseId,
- },
- ),
- ]);
- const html = renderUnit(unit!);
- expect(unit?.flowItems.map((item) => item.kind)).toContain("cuaGroup");
- expect(unit?.flowItems.some((item) => item.kind === "assistantText")).toBe(false);
- const group = unit?.flowItems.find((item) => item.kind === "cuaGroup");
- expect(
- group?.kind === "cuaGroup"
- ? group.events.some((event) => event.kind === "assistantMessage" && event.row === message)
- : false,
- ).toBe(true);
- expect(html).not.toContain(`data-row-id="${message.rowId}"`);
- });
- it("groups response reasoning and counts only reasoning visible under the existing setting", () => {
- const responseId = "assistant-response-cua-reasoning";
- const firstReasoning: ReasoningRow = {
- ...reasoningRow(),
- rowId: 3,
- assistantResponseId: responseId,
- text: "先确认飞书权限",
- };
- const secondReasoning: ReasoningRow = {
- ...reasoningRow(),
- rowId: 4,
- createdAtSeq: 4,
- assistantResponseId: responseId,
- text: "再观察飞书界面",
- };
- const message = assistantTextRow(5, {
- assistantResponseId: responseId,
- text: "现在观察飞书窗口状态。",
- });
- const rows = [
- turnHeader(),
- userInputRow(2),
- firstReasoning,
- secondReasoning,
- message,
- toolCallRow(
- 6,
- "mcp__computer-use__get_app_state",
- {},
- {
- assistantResponseId: responseId,
- },
- ),
- ];
- const [hiddenUnit] = buildConversationTurnRenderUnits(rows);
- const hiddenHtml = renderUnit(hiddenUnit!, { messageStreamShowReasoning: false });
- const visibleHtml = renderUnit(hiddenUnit!, { messageStreamShowReasoning: true });
- expect(hiddenUnit?.flowItems.map((item) => item.kind)).toContain("cuaGroup");
- expect(hiddenHtml).toContain("3 个事件, 1 条消息");
- expect(hiddenHtml).not.toContain("4 个事件");
- expect(visibleHtml).toContain("4 个事件, 1 条消息");
- });
- it("does not mount an empty history collapsible after inner work projection", () => {
- const deferredShell = toolCallRow(3, "Bash", {}, { status: "running" });
- const html = renderUnit(
- baseUnit({
- assistantWorkRows: [deferredShell],
- assistantHistoryRows: [deferredShell],
- assistantHistoryDefaultOpen: true,
- renderRows: [deferredShell],
- }),
- );
- expect(html).not.toContain("chat-assistant-history-content");
- expect(html).not.toContain('<div class="pt-5"><div class="flex flex-col gap-4"></div></div>');
- });
- });
- describe("ConversationTurnGroup Hook footer", () => {
- it("HK08 renders the Hook action after turn-local content and before the tail boundary", () => {
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- toolCallRow(3, "Write", { file_path: "README.md" }),
- assistantTextRow(4),
- hookInvocationRow(5),
- forkNoticeTimelineRow(6),
- ]);
- const html = renderUnit(unit!, { compactForRemoteControl: true });
- const assistantIndex = html.indexOf("完成回复");
- const hookIndex = html.indexOf('data-testid="v4-hook-details-trigger-turn-complete"');
- const boundaryIndex = html.indexOf("从对话中派生");
- expect(assistantIndex).toBeGreaterThanOrEqual(0);
- expect(hookIndex).toBeGreaterThan(assistantIndex);
- expect(boundaryIndex).toBeGreaterThan(hookIndex);
- expect(html.match(/data-testid="v4-hook-details-trigger-turn-complete"/g)).toHaveLength(1);
- });
- it.each(
- [false, true].flatMap((compactForRemoteControl) =>
- [false, true].flatMap((highspeed) =>
- [false, true].map((hasAssistantText) => ({
- compactForRemoteControl,
- highspeed,
- hasAssistantText,
- })),
- ),
- ),
- )(
- "HK08/HK11 每轮仅一个 Hook 入口:mobile=$compactForRemoteControl highspeed=$highspeed text=$hasAssistantText",
- ({ compactForRemoteControl, highspeed, hasAssistantText }) => {
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader({ state: hasAssistantText ? "completedSuccess" : "completedInterrupted" }),
- userInputRow(2, {
- ...(highspeed
- ? {
- highspeed: {
- schemaVersion: 1,
- cardId: "hsc-hook-footer",
- taskId: "session-hook-footer",
- provider: "zai",
- model: "glm-5",
- issuedAt: 1_000,
- expiresAt: 10_000,
- },
- }
- : {}),
- }),
- hookInvocationRow(3),
- ...(hasAssistantText ? [assistantTextRow(4)] : []),
- forkNoticeTimelineRow(5),
- ]);
- const html = renderUnit(
- { ...unit!, showHighspeedOutputFooter: highspeed },
- { compactForRemoteControl },
- );
- // 冲突合并曾把 Hook-only 分支接成 Highspeed footer 的 else:
- // 普通有正文时重复显示,Highspeed 无正文时则完全丢失。
- expect(html.match(/data-testid="v4-hook-details-trigger-turn-complete"/g) ?? []).toHaveLength(
- 1,
- );
- expect(html.includes('data-highspeed-output-footer="true"')).toBe(highspeed);
- expect(html.indexOf("v4-hook-details-trigger-turn-complete")).toBeLessThan(
- html.indexOf("从对话中派生"),
- );
- expect(html.includes('data-testid="v4-copy-4"')).toBe(hasAssistantText);
- },
- );
- it("HK11 renders a Hook-only action row for a terminal turn without assistant text", () => {
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader({ state: "failed" }),
- userInputRow(2),
- hookInvocationRow(3),
- ]);
- const html = renderUnit(unit!, { compactForRemoteControl: true });
- expect(html).toContain('data-testid="v4-hook-details-trigger-turn-complete"');
- expect(html.match(/data-testid="v4-copy-/g)).toHaveLength(1);
- expect(html).not.toContain("v4-feedback-like");
- expect(html).not.toContain("chat-assistant-history-trigger");
- });
- it("HK09 does not render an action when every Hook execution was blocked before start", () => {
- const blocked = hookInvocationRow(3, {
- executions: [
- {
- hookRunId: "blocked-before-start",
- hookIndex: 0,
- didExecute: false,
- state: "completed",
- outcome: "blocked",
- startedAt: 1_700_000_000_003,
- endedAt: 1_700_000_000_003,
- durationMs: 0,
- displayName: "blocked-project-hook",
- sourceKind: "project",
- },
- ],
- });
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- blocked,
- assistantTextRow(4),
- ]);
- expect(renderUnit(unit!, { compactForRemoteControl: true })).not.toContain(
- "v4-hook-details-trigger",
- );
- });
- it("HK17 does not render a Hook action on a timeline-only maintenance turn carrying legacy executed Hook rows", () => {
- // Bug 根因:首条输入即 /compact 时 SessionStart Hook 曾被错误挂到 compact 维护 turn;
- // 旧历史/旧投影数据可能仍含 timelineOnly + didExecute=true 组合。维护 turn 与普通
- // assistant action 共用 turn eligibility:timelineOnly 不渲染 Hook 图标或空操作栏。
- const compactMarker = runningTimelineRow(2);
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader({ state: "completedSuccess" }),
- compactMarker,
- hookInvocationRow(3),
- ]);
- expect(unit?.timelineOnly).toBe(true);
- expect(unit?.hookInvocations.length).toBe(1);
- const html = renderUnit(unit!, { compactForRemoteControl: true });
- expect(html).not.toContain("v4-hook-details-trigger");
- // 也不得留下只有 Hook 的空操作栏外壳。
- expect(html).not.toContain("v4-copy-");
- });
- });
- describe("ConversationTurnGroup message stream display settings", () => {
- const reasoning = reasoningRow();
- const todo = toolCallRow(4, "TodoWrite", {
- todos: [
- {
- content: "补齐设置接线",
- status: "in_progress",
- activeForm: "补齐设置接线",
- },
- ],
- });
- const shell = toolCallRow(5, "Bash", { command: "pnpm test" });
- const laterReasoning: ReasoningRow = {
- ...reasoningRow(),
- rowId: 6,
- createdAt: 1_700_000_000_006,
- createdAtSeq: 6,
- text: "后续思考",
- };
- const finalText = assistantTextRow(7);
- const [builtUnit] = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- reasoning,
- todo,
- shell,
- laterReasoning,
- finalText,
- ]);
- const unit = {
- ...builtUnit!,
- assistantHistoryDefaultOpen: true,
- };
- it.each([
- {
- label: "两个开关都关闭",
- showReasoning: false,
- showTodos: false,
- todoVisible: false,
- },
- {
- label: "只开启显示思考过程",
- showReasoning: true,
- showTodos: false,
- todoVisible: false,
- },
- {
- label: "只开启显示待办",
- showReasoning: false,
- showTodos: true,
- todoVisible: true,
- },
- {
- label: "两个开关都开启",
- showReasoning: true,
- showTodos: true,
- todoVisible: true,
- },
- ])("$label 时独立控制 reasoning 与 Todo", (scenario) => {
- const html = renderUnit(unit, {
- messageStreamShowReasoning: scenario.showReasoning,
- messageStreamShowTodos: scenario.showTodos,
- });
- // 每轮第一条 reasoning 不受开关影响;后续 reasoning 只在开关开启时展示。
- expect(html).toContain('data-row-id="3"');
- expect(html.includes('data-row-id="6"')).toBe(scenario.showReasoning);
- expect(html.includes('data-tool-call-id="tool-4"')).toBe(scenario.todoVisible);
- // 单个 Execute 不创建父分组,仍直接展示原始工具。
- expect(html).toContain("tool-summary-trigger-tool-5");
- });
- it("关闭思考时跨隐藏 reasoning 合并 Explore,开启时保持原始边界", () => {
- const firstReasoning = reasoningRow();
- const firstExplore = toolCallRow(4, "Read", { file_path: "package.json" });
- const hiddenReasoning: ReasoningRow = {
- ...reasoningRow(),
- rowId: 5,
- createdAt: 1_700_000_000_005,
- createdAtSeq: 5,
- text: "检查下一处",
- };
- const secondExplore = toolCallRow(6, "Bash", {
- command: "rg test packages/ui",
- });
- const finalText = assistantTextRow(7);
- const [builtUnit] = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- firstReasoning,
- firstExplore,
- hiddenReasoning,
- secondExplore,
- finalText,
- ]);
- const exploreUnit = {
- ...builtUnit!,
- assistantHistoryDefaultOpen: true,
- };
- const hiddenReasoningHtml = renderUnit(exploreUnit, {
- messageStreamShowReasoning: false,
- });
- expect(hiddenReasoningHtml).toContain('data-tool-call-id="explore:tool-4"');
- expect(hiddenReasoningHtml).not.toContain('data-row-id="5"');
- const visibleReasoningHtml = renderUnit(exploreUnit, {
- messageStreamShowReasoning: true,
- });
- expect(visibleReasoningHtml).toContain('data-tool-call-id="tool-4"');
- expect(visibleReasoningHtml).toContain('data-tool-call-id="tool-6"');
- expect(visibleReasoningHtml).toContain('data-row-id="5"');
- });
- });
- describe("ConversationTurnGroup assistant history status", () => {
- it("源码将会话内分享按钮接到本地卡片,且不调用后端分享接口", () => {
- const source = readFileSync("packages/ui/src/v4/ConversationTurnGroup.tsx", "utf8");
- expect(source).toContain("setHighspeedShareDialogOpen(true)");
- expect(source).toContain("<HighspeedShareDialog");
- expect(source).not.toContain("highspeedCardService.share");
- });
- it("冷恢复后从 userInput metadata 保留 accelerated output 的紫色工时", () => {
- const input = userInputRow(2, {
- sourceCommandId: "command-highspeed-cold-history",
- highspeed: {
- schemaVersion: 1,
- cardId: "hsc-cold-history",
- taskId: "session-highspeed-cold-history",
- provider: "zai",
- model: "glm-5",
- issuedAt: 1_000,
- expiresAt: 10_000,
- regularTps: 73,
- highspeedTps: 136,
- outputTokens: 120_000,
- durationMs: 881_000,
- savedDurationMs: 763_000,
- },
- });
- const work = reasoningRow();
- const html = renderUnit(
- baseUnit({
- visibleUserInputs: [input],
- workStatus: { state: "completed", durationMs: 881_000 },
- assistantWorkRows: [work],
- assistantHistoryRows: [work],
- renderRows: [input, work],
- showHighspeedOutputFooter: true,
- }),
- );
- expect(html).toContain("已工作 14 分 41 秒");
- expect(html).toContain('data-highspeed-duration="true"');
- expect(html).toContain("text-icon-purple");
- expect(html).toContain("节省约 12 分 43 秒");
- expect(html).toContain('data-highspeed-saved-duration="true"');
- expect(html).toContain('data-highspeed-status-tag="true"');
- expect(html).not.toContain('data-highspeed-gradient="true"');
- expect(html).toContain("HighSpeed");
- expect(html).toContain('data-highspeed-output-footer="true"');
- expect(html).toContain("以上由 Highspeed 生成");
- expect(html).toContain('data-highspeed-output-share="true"');
- expect(html).toContain("查看");
- const shareButton = html.match(/<button[^>]*data-highspeed-output-share="true"[^>]*>/)?.[0];
- expect(shareButton).toBeDefined();
- expect(shareButton).not.toMatch(/\sdisabled(?:=""|(?=[\s>]))/);
- expect(html).toContain('data-highspeed-output-share-icon="true"');
- expect(html).not.toContain('data-highspeed="true"');
- });
- it("卡失效降级后仍允许分享当前 Turn 的完整统计", () => {
- const input = userInputRow(2, {
- sourceCommandId: "command-highspeed-fallback-share",
- highspeed: {
- schemaVersion: 1,
- cardId: "hsc-fallback-share",
- taskId: "session-fallback-share",
- provider: "zai",
- model: "glm-5",
- issuedAt: 1_000,
- expiresAt: 10_000,
- regularTps: 73,
- highspeedTps: 136,
- outputTokens: 120_000,
- durationMs: 881_000,
- savedDurationMs: 763_000,
- fallbackAt: 10_001,
- },
- });
- const work = reasoningRow();
- const html = renderUnit(
- baseUnit({
- visibleUserInputs: [input],
- workStatus: { state: "completed", durationMs: 881_000 },
- assistantWorkRows: [work],
- assistantHistoryRows: [work],
- renderRows: [input, work],
- showHighspeedOutputFooter: true,
- }),
- );
- const shareButton = html.match(/<button[^>]*data-highspeed-output-share="true"[^>]*>/)?.[0];
- expect(shareButton).toBeDefined();
- expect(shareButton).not.toMatch(/\sdisabled(?:=""|(?=[\s>]))/);
- });
- it("缺少 durationMs 时不展示分享入口", () => {
- const input = userInputRow(2, {
- sourceCommandId: "command-highspeed-share-without-duration",
- highspeed: {
- schemaVersion: 1,
- cardId: "hsc-share-without-duration",
- taskId: "session-share-without-duration",
- provider: "zai",
- model: "glm-5",
- issuedAt: 1_000,
- expiresAt: 10_000,
- outputTokens: 120_000,
- regularTps: 73,
- highspeedTps: 136,
- },
- });
- const html = renderUnit(
- baseUnit({
- visibleUserInputs: [input],
- workStatus: { state: "completed", durationMs: 881_000 },
- assistantWorkRows: [reasoningRow()],
- assistantHistoryRows: [reasoningRow()],
- renderRows: [input, reasoningRow()],
- showHighspeedOutputFooter: true,
- }),
- );
- const shareButton = html.match(/<button[^>]*data-highspeed-output-share="true"[^>]*>/)?.[0];
- expect(shareButton).toBeUndefined();
- });
- it("总体加速倍率不大于 1.2x 时保留 footer 但隐藏分享入口", () => {
- const input = userInputRow(2, {
- sourceCommandId: "command-highspeed-low-speedup",
- highspeed: {
- schemaVersion: 1,
- cardId: "hsc-low-speedup",
- taskId: "session-low-speedup",
- provider: "zai",
- model: "glm-5",
- issuedAt: 1_000,
- expiresAt: 10_000,
- regularTps: 73,
- highspeedTps: 100,
- outputTokens: 120_000,
- durationMs: 881_000,
- savedDurationMs: 100_000,
- },
- });
- const html = renderUnit(
- baseUnit({
- visibleUserInputs: [input],
- workStatus: { state: "completed", durationMs: 881_000 },
- assistantWorkRows: [reasoningRow()],
- assistantHistoryRows: [reasoningRow()],
- renderRows: [input, reasoningRow()],
- showHighspeedOutputFooter: true,
- }),
- );
- expect(html).toContain('data-highspeed-output-footer="true"');
- expect(html).not.toContain('data-highspeed-output-share="true"');
- });
- it("Highspeed 生成期间只显示标签,不提前显示持久化的节省时间", () => {
- const input = userInputRow(2, {
- sourceCommandId: "command-highspeed-running",
- highspeed: {
- schemaVersion: 1,
- cardId: "hsc-running",
- taskId: "session-highspeed-running",
- provider: "zai",
- model: "glm-5",
- issuedAt: 1_000,
- expiresAt: 10_000,
- regularTps: 73,
- outputTokens: 120_000,
- durationMs: 881_000,
- savedDurationMs: 763_000,
- },
- });
- const work = reasoningRow();
- const html = renderUnit(
- baseUnit({
- visibleUserInputs: [input],
- // 多段输出中,前段可已完成但整轮仍在生成;节省时间必须服从整轮终态。
- workStatus: { state: "completed", durationMs: 5_000 },
- assistantWorkRows: [work],
- assistantHistoryRows: [work],
- renderRows: [input, work],
- isRunning: true,
- }),
- { nowMs: 9_999 },
- );
- expect(html).toContain('data-highspeed-status-tag="true"');
- expect(html).toContain('data-highspeed-gradient="true"');
- expect(html).toContain("highspeed-animated-gradient-text");
- expect(html).toContain("HighSpeed");
- expect(html).not.toContain('data-highspeed-saved-duration="true"');
- expect(html).not.toContain("节省约");
- });
- it("Highspeed 卡过期后执行中的 Tool 恢复普通流光样式", () => {
- const input = userInputRow(2, {
- sourceCommandId: "command-highspeed-expired-running-tool",
- highspeed: {
- schemaVersion: 1,
- cardId: "hsc-expired-running-tool",
- taskId: "session-expired-running-tool",
- provider: "zai",
- model: "glm-5",
- issuedAt: 1_000,
- expiresAt: 10_000,
- },
- });
- const runningTool = toolCallRow(3, "Bash", { command: "pnpm test" }, { status: "running" });
- const html = renderUnit(
- baseUnit({
- visibleUserInputs: [input],
- assistantWorkRows: [runningTool],
- assistantHistoryRows: [runningTool],
- renderRows: [input, runningTool],
- isRunning: true,
- }),
- { nowMs: 10_001 },
- );
- expect(html).not.toContain('data-highspeed-gradient="true"');
- expect(html).not.toContain("highspeed-animated-gradient-text");
- });
- it("普通 output 和仍在运行的 accelerated output 不显示 Highspeed 来源 footer", () => {
- const work = reasoningRow();
- const ordinaryHtml = renderUnit(
- baseUnit({
- visibleUserInputs: [userInputRow(2, { sourceCommandId: "command-ordinary-footer" })],
- workStatus: { state: "completed", durationMs: 5_000 },
- assistantWorkRows: [work],
- assistantHistoryRows: [work],
- renderRows: [work],
- }),
- );
- const runningHtml = renderUnit(
- baseUnit({
- visibleUserInputs: [
- userInputRow(2, {
- sourceCommandId: "command-highspeed-running-footer",
- highspeed: {
- schemaVersion: 1,
- cardId: "hsc-running-footer",
- taskId: "session-running-footer",
- provider: "zai",
- model: "glm-5",
- issuedAt: 1_000,
- expiresAt: 10_000,
- },
- }),
- ],
- workStatus: { state: "running", durationMs: 5_000 },
- assistantWorkRows: [work],
- assistantHistoryRows: [work],
- renderRows: [work],
- isRunning: true,
- showHighspeedOutputFooter: true,
- }),
- { nowMs: 9_999 },
- );
- expect(ordinaryHtml).not.toContain('data-highspeed-output-footer="true"');
- expect(ordinaryHtml).not.toContain('data-highspeed-gradient="true"');
- expect(runningHtml).not.toContain('data-highspeed-output-footer="true"');
- expect(runningHtml).toContain('data-highspeed-gradient="true"');
- });
- it.each([
- { label: "中断", workStatus: { state: "interrupted" as const, durationMs: 100 } },
- { label: "异常", workStatus: undefined },
- ])("Highspeed 组尾$label且自身无输出时仍展示可用分享入口", ({ workStatus }) => {
- const input = userInputRow(2, {
- sourceCommandId: "command-highspeed-terminal-footer",
- highspeed: {
- schemaVersion: 1,
- cardId: "hsc-terminal-footer",
- taskId: "session-terminal-footer",
- provider: "zai",
- model: "glm-5",
- issuedAt: 1_000,
- expiresAt: 10_000,
- regularTps: 20,
- highspeedTps: 50,
- outputTokens: 0,
- durationMs: 100,
- },
- });
- const html = renderUnit(
- baseUnit({
- visibleUserInputs: [input],
- ...(workStatus ? { workStatus } : {}),
- showHighspeedOutputFooter: true,
- highspeedOutputFooterTarget: {
- cardId: "hsc-terminal-footer",
- metrics: {
- outputTokens: 10,
- durationMs: 300,
- regularTps: 20,
- highspeedTps: 50,
- },
- },
- }),
- );
- expect(html).toContain('data-highspeed-output-footer="true"');
- const shareButton = html.match(/<button[^>]*data-highspeed-output-share="true"[^>]*>/)?.[0];
- expect(shareButton).toBeDefined();
- expect(shareButton).not.toMatch(/\sdisabled(?:=""|(?=[\s>]))/);
- });
- it("只用紫色工时标识 accelerated output,input 保持普通样式", () => {
- const sourceCommandId = "command-highspeed-output-duration";
- const input = userInputRow(2, { sourceCommandId });
- const work = reasoningRow();
- recordHighspeedTurn({
- sessionId: "session-highspeed-output-duration",
- sourceCommandId,
- card: {
- cardId: "hsc-output-duration",
- taskId: "session-highspeed-output-duration",
- provider: "zai",
- model: "glm-5",
- issuedAt: 1_000,
- expiresAt: 10_000,
- regularTps: 73,
- },
- createdAt: 1_000,
- });
- completeHighspeedTurn({
- sourceCommandId,
- outputTokens: 120_000,
- durationMs: 881_000,
- completedAt: 882_000,
- });
- setHighspeedCardTps("hsc-output-duration", 136);
- markHighspeedTurnMetricsPersisted(sourceCommandId, 763_000, 882_001);
- const html = renderUnit(
- baseUnit({
- visibleUserInputs: [input],
- workStatus: { state: "completed", durationMs: 881_000 },
- assistantWorkRows: [work],
- assistantHistoryRows: [work],
- renderRows: [input, work],
- showHighspeedOutputFooter: true,
- }),
- );
- expect(html).toContain("已工作 14 分 41 秒");
- expect(html).toContain('data-highspeed-duration="true"');
- expect(html).toContain("text-icon-purple");
- expect(html).toContain('data-highspeed-status-tag="true"');
- expect(html).toContain("HighSpeed");
- const shareButton = html.match(/<button[^>]*data-highspeed-output-share="true"[^>]*>/)?.[0];
- expect(shareButton).toBeDefined();
- expect(shareButton).not.toMatch(/\sdisabled(?:=""|(?=[\s>]))/);
- expect(html).not.toContain('data-highspeed="true"');
- });
- it("H17:切模型后的 /goal query 与 continuation 合计只显示一个工作状态", () => {
- const startedAt = 1_700_000_000_000;
- const units = buildConversationTurnRenderUnits(
- [
- {
- rowId: 1,
- turnId: "turn-goal",
- createdAt: startedAt,
- createdAtSeq: 1,
- kind: "timelineMarker",
- lane: "lightBoundary",
- marker: {
- type: "modelChange",
- fromProvider: "zhipu",
- fromModel: "glm-5.2-highspeed",
- toProvider: "deepseek",
- toModel: "deepseek-v4-flash",
- toThought: "max",
- },
- },
- turnHeader({
- rowId: 2,
- turnId: "turn-goal",
- executionKind: "controlOnly",
- activeMs: 0,
- }),
- userInputRow(3, {
- turnId: "turn-goal",
- text: "/Goal 开发一个招投标管理系统",
- }),
- turnHeader({
- rowId: 4,
- turnId: "turn-continuation",
- origin: "goalContinuation",
- executionKind: "agent",
- state: "running",
- startedAt,
- }),
- ],
- { nowMs: startedAt + 3_000 },
- );
- const html = units.map((unit) => renderUnit(unit)).join("");
- expect(html).not.toContain("/Goal");
- expect(html).toContain("Goal");
- expect(html).toContain("开发一个招投标管理系统");
- expect(html).not.toContain("已工作 1 秒");
- expect(html.match(/工作中 3 秒/g)).toHaveLength(1);
- expect(html.match(/chat-assistant-history-trigger/g)).toHaveLength(1);
- });
- it("labels a running turn as working with the elapsed duration", () => {
- const html = renderUnit(
- baseUnit({
- isRunning: true,
- assistantHistoryDefaultOpen: true,
- workStatus: { state: "running", durationMs: 5_000 },
- }),
- );
- expect(html).toContain("工作中 5 秒");
- });
- it("ETS01/ETS03:运行工作段尾部的单个 Explore 工具不创建父分组", () => {
- const explore = toolCallRow(10, "Read", { file_path: "AGENTS.md" });
- const text = assistantTextRow(11);
- const tailHtml = renderUnit(
- baseUnit({
- isRunning: true,
- workStatus: { state: "running", durationMs: 5_000 },
- assistantHistoryDefaultOpen: true,
- assistantWorkRows: [explore],
- assistantHistoryRows: [explore],
- renderRows: [explore],
- }),
- );
- const boundedHtml = renderUnit(
- baseUnit({
- isRunning: true,
- workStatus: { state: "running", durationMs: 5_000 },
- assistantHistoryDefaultOpen: true,
- assistantWorkRows: [explore, text],
- assistantHistoryRows: [explore],
- latestAssistantTextRow: text,
- assistantTextRows: [text],
- renderRows: [explore, text],
- }),
- );
- expect(tailHtml).toContain('data-tool-call-id="tool-10"');
- expect(tailHtml).not.toContain('data-tool-call-id="explore:tool-10"');
- expect(tailHtml).not.toContain("animated-gradient-text");
- expect(boundedHtml).not.toContain("animated-gradient-text");
- });
- it("labels a completed turn as worked with the final duration", () => {
- const row = reasoningRow();
- const html = renderUnit(
- baseUnit({
- key: "turn-complete:1",
- turnId: "turn-complete",
- isLastTurn: false,
- workStatus: { state: "completed", durationMs: 5_000 },
- assistantWorkRows: [row],
- assistantHistoryRows: [row],
- renderRows: [row],
- }),
- );
- expect(html).toContain("已工作 5 秒");
- expect(html).not.toContain("工作中 5 秒");
- });
- it("labels an authoritative topic interruption separately from a manual stop", () => {
- topicInterrupted.mockReturnValue(true);
- try {
- const row = reasoningRow();
- const unit = baseUnit({
- workStatus: { state: "interrupted", durationMs: 1000 },
- assistantHistoryDefaultOpen: true,
- assistantWorkRows: [row],
- assistantHistoryRows: [row],
- renderRows: [row],
- });
- expect(renderUnit(unit, { locale: "zh-CN" })).toContain("已被新消息中断");
- expect(renderUnit(unit, { locale: "en-US" })).toContain("Interrupted by a new message");
- } finally {
- topicInterrupted.mockReturnValue(false);
- }
- });
- it("labels an interrupted turn as stopped without duration", () => {
- const row = reasoningRow();
- const interruptedUnit = baseUnit({
- key: "turn-interrupted:1",
- turnId: "turn-interrupted",
- assistantHistoryDefaultOpen: true,
- workStatus: { state: "interrupted", durationMs: 5_000 },
- assistantWorkRows: [row],
- assistantHistoryRows: [row],
- renderRows: [row],
- });
- expect(renderUnit(interruptedUnit, { locale: "en-US" })).toContain("Stopped");
- expect(renderUnit(interruptedUnit, { locale: "en-US" })).not.toContain("Worked for 5s");
- expect(renderUnit(interruptedUnit, { locale: "zh-CN" })).toContain("已停止");
- expect(renderUnit(interruptedUnit, { locale: "zh-CN" })).not.toContain("已工作 5 秒");
- });
- it("按语言格式化工作时长的单位间距", () => {
- const row = reasoningRow();
- const completedUnit = baseUnit({
- key: "turn-complete:localized-duration",
- turnId: "turn-complete",
- isLastTurn: false,
- workStatus: { state: "completed", durationMs: 450_000 },
- assistantWorkRows: [row],
- assistantHistoryRows: [row],
- renderRows: [row],
- });
- expect(renderUnit(completedUnit, { locale: "en-US" })).toContain("Worked for 7m 30s");
- expect(renderUnit(completedUnit, { locale: "zh-CN" })).toContain("已工作 7 分 30 秒");
- });
- it.each([
- ["subagent", "Review the projection chain"],
- ["bash", "pnpm typecheck"],
- // 回归:dwf run 的终态回合也走后台结果头。标题由 CLI 的 workflowTaskSubject 铸造并经
- // originMeta.title 送上来(rows.ts 的 backgroundResultOriginMetaSchema 要求 min(1)),
- // UI 侧不本地化——与 bash / subagent 完全同构。漏掉这一支的表现是整条 run 完成之后
- // 那一轮既没有标题、也退化成普通 assistant 的工时折叠。
- ["workflow", "Fan out the review across three actors"],
- ] as const)(
- "BG27/BG28:%s background result 用任务标题永久展开历史",
- (backgroundSource, title) => {
- const earlyText = assistantTextRow(4, { text: "后台总结第一段" });
- const tool = toolCallRow(5, "Read", { file_path: "AGENTS.md" });
- const finalText = assistantTextRow(6, { text: "后台总结最终段" });
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader({
- origin: "backgroundResult",
- originMeta: {
- backgroundSource,
- title,
- workId: `${backgroundSource}-work`,
- },
- activeMs: 12_000,
- }),
- earlyText,
- tool,
- finalText,
- ]);
- const html = renderUnit(unit!);
- expect(html).toContain(`data-testid="chat-background-result-title-${unit!.key}"`);
- expect(html).toContain(title);
- expect(html).toContain("后台总结第一段");
- expect(html).toContain("tool-5");
- expect(html).toContain("后台总结最终段");
- expect(html.indexOf("后台总结第一段")).toBeLessThan(html.indexOf("tool-5"));
- expect(html.indexOf("tool-5")).toBeLessThan(html.indexOf("后台总结最终段"));
- expect(html).not.toContain("已工作 12 秒");
- expect(html).not.toContain("chat-assistant-history-trigger");
- expect(html).not.toContain("chat-assistant-history-content");
- expect(html).not.toContain("data-history-open");
- },
- );
- it("workflow 通知带载荷时渲染工具卡语法的通知行,替换裸标题行", () => {
- // docs/dynamic-workflow/transcript-and-notifications.md「The notification row」:backgroundSource==="workflow"
- // 且 workflowNotification 在场 → ToolLayout 通知行(自带 testid),不再走裸标题行。
- const finalText = assistantTextRow(6, { text: "后台总结最终段" });
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader({
- origin: "backgroundResult",
- originMeta: {
- backgroundSource: "workflow",
- title: "flaky-test-triage",
- workId: "run-abc",
- workflowNotification: {
- kind: "terminal",
- status: "completed",
- summary: "Workflow run completed: 3 flaky tests triaged.",
- durationMs: 252_000,
- },
- },
- }),
- finalText,
- ]);
- const html = renderUnit(unit!, { locale: "en-US" });
- expect(html).toContain(`data-testid="chat-workflow-notification-row-${unit!.key}"`);
- // 裸标题行的 testid 缺席——通知行取而代之。
- expect(html).not.toContain(`data-testid="chat-background-result-title-${unit!.key}"`);
- expect(html).toContain("flaky-test-triage");
- // kindLabel 承载状态(不再是 run 详情页的 Completed)。
- expect(html).toContain("Workflow completed");
- // 通知行之下的 assistant 反应行不受影响。
- expect(html).toContain("后台总结最终段");
- });
- it("提醒载荷在 originMeta.workflowBlocked 上:同样渲染成通知行", () => {
- // docs/dynamic-workflow/transcript-and-notifications.md「The payload」:提醒不是 workflowNotification
- // 的成员(闭集多一个 kind,老客户端会拒掉整帧),它在自己的键上;行照旧是「等待主代理」那一条。
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader({
- origin: "backgroundResult",
- originMeta: {
- backgroundSource: "workflow",
- title: "flaky-test-triage",
- workId: "run-abc",
- workflowBlocked: { questions: 2, holes: 1, sinceMs: 17 * 60_000 },
- },
- }),
- assistantTextRow(6, { text: "后台总结最终段" }),
- ]);
- const html = renderUnit(unit!, { locale: "en-US" });
- expect(html).toContain(`data-testid="chat-workflow-notification-row-${unit!.key}"`);
- expect(html).not.toContain(`data-testid="chat-background-result-title-${unit!.key}"`);
- expect(html).toContain("Workflow waiting on the agent");
- expect(html).toContain("flaky-test-triage");
- });
- // ── 终态通知行的产物 chips(docs/dynamic-workflow/authoring.md「How the user sees them」)──
- // ⚠ 术语:chip 上的 artifact 是脚本经 `artifact.*` 交付给用户的产出,与同一条通知里的
- // `result`(脚本顶层返回值)不是一回事。
- function workflowNotificationUnit(
- artifacts: readonly { id: string; kind: string; title?: string; version: number }[] | undefined,
- extra: Record<string, unknown> = {},
- ) {
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader({
- origin: "backgroundResult",
- originMeta: {
- backgroundSource: "workflow",
- title: "flaky-test-triage",
- workId: "run-abc",
- workflowNotification: {
- kind: "terminal",
- status: "completed",
- summary: "Workflow run completed.",
- durationMs: 1000,
- ...(artifacts === undefined ? {} : { artifacts }),
- ...extra,
- },
- },
- }),
- assistantTextRow(6, { text: "后台总结最终段" }),
- ]);
- return unit!;
- }
- const artifactContext = {
- sessionId: "parent-a",
- onOpenWorkflowArtifact: () => {},
- } as const;
- it("终态通知行的折叠头部尾部挂产物 chips(≤ 3 枚),每枚带 kind 词与标题", () => {
- const html = renderUnit(
- workflowNotificationUnit([
- { id: "book", kind: "file", title: "审计报告", version: 2 },
- { id: "perf", kind: "chart", title: "每轮耗时", version: 1 },
- ]),
- { context: artifactContext, locale: "zh-CN" },
- );
- expect(html).toContain('data-testid="workflow-notification-artifacts"');
- expect(
- (html.match(new RegExp(`data-testid="${TID_CHAT_WORKFLOW_ARTIFACT_CHIP}"`, "gu")) ?? [])
- .length,
- ).toBe(2);
- expect(html).toContain("审计报告");
- expect(html).toContain("每轮耗时");
- // 药丸的尾槽从 v2 起带紧凑版号(追记「产物药丸」推翻了「chip 不放版本」的旧规则):
- // 「这次跑的是第 2 版」是一件值得在收据上看到的事;长写在 tooltip 里。
- expect(html).toContain('data-testid="workflow-run-artifact-version"');
- expect(html).toContain(">v2<");
- expect(html).toContain('title="第 2 版"');
- });
- it("超过 3 件时只摆 3 枚,其余折进「+N」", () => {
- const html = renderUnit(
- workflowNotificationUnit(
- Array.from({ length: 5 }, (_unused, index) => ({
- id: `a${index}`,
- kind: "file",
- title: `产物 ${index}`,
- version: 1,
- })),
- ),
- { context: artifactContext, locale: "zh-CN" },
- );
- expect(
- (html.match(new RegExp(`data-testid="${TID_CHAT_WORKFLOW_ARTIFACT_CHIP}"`, "gu")) ?? [])
- .length,
- ).toBe(3);
- expect(html).toContain('data-testid="workflow-notification-artifacts-more"');
- expect(html).toContain("+2");
- });
- it("发射侧砍过(artifactsTruncated)时「+N」用省略号,不报一个会骗人的数字", () => {
- const html = renderUnit(
- workflowNotificationUnit([{ id: "a", kind: "file", title: "只剩一件", version: 1 }], {
- artifactsTruncated: true,
- }),
- { context: artifactContext, locale: "zh-CN" },
- );
- expect(html).toContain('data-testid="workflow-notification-artifacts-more"');
- expect(html).toContain("+…");
- });
- it("载荷缺席(批量轮 / 旧 CLI / 旧 transcript)⇒ 无 chips,通知行其余部分逐字不变", () => {
- const withoutArtifacts = renderUnit(workflowNotificationUnit(undefined), {
- context: artifactContext,
- locale: "zh-CN",
- });
- expect(withoutArtifacts).not.toContain('data-testid="workflow-notification-artifacts"');
- expect(withoutArtifacts).toContain("flaky-test-triage");
- expect(withoutArtifacts).toContain("后台总结最终段");
- // 与「一件产物都没有」的空数组同构:两者都不该长出 chips。
- const emptyArtifacts = renderUnit(workflowNotificationUnit([]), {
- context: artifactContext,
- locale: "zh-CN",
- });
- expect(emptyArtifacts).not.toContain('data-testid="workflow-notification-artifacts"');
- });
- it("宿主没注入打开能力时 chips 仍在场,只是不可点——交付了什么是事实,能不能打开是能力", () => {
- const html = renderUnit(
- workflowNotificationUnit([{ id: "book", kind: "file", title: "审计报告", version: 1 }]),
- { locale: "zh-CN" },
- );
- expect(html).toContain(`data-testid="${TID_CHAT_WORKFLOW_ARTIFACT_CHIP}"`);
- expect(html).toMatch(
- new RegExp(
- `<button(?=[^>]*data-testid="${TID_CHAT_WORKFLOW_ARTIFACT_CHIP}")(?=[^>]*disabled)`,
- "u",
- ),
- );
- });
- it("升级(escalation)通知不长 chips——产物只在终态载荷上", () => {
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader({
- origin: "backgroundResult",
- originMeta: {
- backgroundSource: "workflow",
- title: "flaky-test-triage",
- workId: "run-abc",
- workflowNotification: {
- kind: "escalation",
- qid: "q1",
- question: "要不要继续?",
- actorName: "planner",
- },
- },
- }),
- assistantTextRow(6, { text: "后台总结最终段" }),
- ]);
- const html = renderUnit(unit!, { context: artifactContext, locale: "zh-CN" });
- expect(html).not.toContain('data-testid="workflow-notification-artifacts"');
- });
- it("workflow 通知无载荷时(批量轮 / 旧 transcript)原样退回裸标题行", () => {
- const finalText = assistantTextRow(6, { text: "后台总结最终段" });
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader({
- origin: "backgroundResult",
- originMeta: {
- backgroundSource: "workflow",
- title: "flaky-test-triage",
- workId: "run-abc",
- },
- }),
- finalText,
- ]);
- const html = renderUnit(unit!, { locale: "en-US" });
- expect(html).toContain(`data-testid="chat-background-result-title-${unit!.key}"`);
- expect(html).not.toContain(`data-testid="chat-workflow-notification-row-${unit!.key}"`);
- expect(html).toContain("flaky-test-triage");
- });
- it("在 background result 的 history 兼容路径保留 CUA Group 内 Assistant message 事件", () => {
- const responseId = "background-cua-response";
- const reasoning = {
- ...reasoningRow(),
- assistantResponseId: responseId,
- text: "我需要先检查后台电脑状态。",
- };
- const message = assistantTextRow(4, {
- assistantResponseId: responseId,
- text: "我先检查电脑操作权限与应用列表。",
- });
- const cua = toolCallRow(
- 5,
- "mcp__computer-use__list_apps",
- {},
- {
- assistantResponseId: responseId,
- },
- );
- const html = renderUnit(
- baseUnit({
- key: "turn-background:cua-events",
- header: turnHeader({
- origin: "backgroundResult",
- originMeta: { backgroundSource: "bash", title: "后台 Computer Use", workId: "cua" },
- }),
- assistantWorkRows: [reasoning, message, cua],
- assistantHistoryRows: [reasoning, message, cua],
- renderRows: [reasoning, message, cua],
- }),
- );
- // 折叠态不挂载详情正文;计数同时包含 reasoning 与 message,证明兼容路径没有退化为仅 child tools。
- // CuaGroupToolCallBlock 的 forceOpen 测试另行覆盖详情正文渲染。
- expect(html).toContain("3 个事件, 1 条消息");
- expect(html).not.toContain("1 个事件");
- });
- it("旧 background result 缺少结构化标题时保持耗时折叠兼容分支", () => {
- const row = reasoningRow();
- const html = renderUnit(
- baseUnit({
- header: turnHeader({ origin: "backgroundResult" }),
- workStatus: { state: "completed", durationMs: 5_000 },
- assistantWorkRows: [row],
- assistantHistoryRows: [row],
- renderRows: [row],
- }),
- );
- expect(html).toContain("已工作 5 秒");
- expect(html).toContain("chat-assistant-history-trigger");
- expect(html).not.toContain("chat-background-result-title");
- });
- it("uses the paired subagent row type while the Agent input preview is incomplete", () => {
- const agentRow = toolCallRow(20, "Agent", undefined, {
- status: "inputStreaming",
- inputText: '{"description":"检查投影","prompt":"继续等待',
- });
- const childRow = subagentRow(21, {
- parentToolCallId: agentRow.toolCallId,
- subagentType: "Review",
- status: "running",
- });
- const html = renderUnit(
- baseUnit({
- key: "turn-complete:streaming-agent-type",
- turnId: "turn-complete",
- isRunning: true,
- assistantHistoryDefaultOpen: true,
- assistantWorkRows: [agentRow, childRow],
- assistantHistoryRows: [],
- assistantFollowingRows: [agentRow, childRow],
- renderRows: [agentRow, childRow],
- }),
- );
- expect(html).toContain("Review");
- expect(html).not.toContain("general-purpose");
- });
- it("renders ExitPlanMode at its original row before later tool and assistant output", () => {
- const middleText = assistantTextRow(3, { text: "计划前正文" });
- const plan = toolCallRow(4, "ExitPlanMode", {
- plan: "# PLAN_ROW_ORDER_TITLE",
- });
- const write = toolCallRow(5, "Write", {
- file_path: "/workspace/plan.md",
- content: "done",
- });
- const finalText = assistantTextRow(6, { text: "写入后的最终正文" });
- const [builtUnit] = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- middleText,
- plan,
- write,
- finalText,
- ]);
- const html = renderUnit({
- ...builtUnit!,
- assistantHistoryDefaultOpen: true,
- });
- const indexes = [
- html.indexOf("计划前正文"),
- html.indexOf("PLAN_ROW_ORDER_TITLE"),
- html.indexOf('data-tool-name="Write"'),
- html.indexOf("写入后的最终正文"),
- ];
- expect(indexes.every((index) => index >= 0)).toBe(true);
- expect(indexes).toEqual([...indexes].sort((left, right) => left - right));
- });
- it("renders per-turn file change summary when the header has fileChanges", () => {
- const html = renderUnit(
- baseUnit({
- key: "turn-complete:file-summary",
- turnId: "turn-complete",
- isLastTurn: false,
- header: turnHeader({
- fileChanges: {
- files: 1,
- additions: 2,
- deletions: 1,
- state: "active",
- },
- }),
- }),
- );
- expect(html).toContain("1 个文件已更改");
- expect(html).toContain("+2");
- expect(html).toContain("-1");
- });
- it("passes visualize references from the whole turn to the summary before details load", () => {
- const reference = assistantTextRow(3, {
- text: '::visualize{"path":"/workspace/calendar.html"}',
- });
- const finalText = assistantTextRow(4, { text: "可视化已完成" });
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader({
- entityId: "header-1",
- fileChanges: { files: 1, additions: 70, deletions: 0, state: "active" },
- }),
- userInputRow(2),
- reference,
- finalText,
- ]);
- const html = renderUnit(unit!, { context: { fetchFileChanges: async () => ({ items: [] }) } });
- expect(html).not.toContain("1 个文件已更改");
- expect(html).not.toContain("+70");
- expect(html).toContain("可视化已完成");
- });
- it("renders the completed assistant action toolbar after the file change summary", () => {
- const createdAt = new Date();
- createdAt.setHours(7, 15, 0, 0);
- const timeLabel = new Intl.DateTimeFormat("zh-CN", {
- hour: "2-digit",
- minute: "2-digit",
- }).format(createdAt);
- const row = assistantTextRow(20, { createdAt: createdAt.getTime() });
- const html = renderUnit(
- baseUnit({
- key: "turn-complete:action-order",
- turnId: "turn-complete",
- isLastTurn: true,
- header: turnHeader({
- fileChanges: {
- files: 1,
- additions: 2,
- deletions: 1,
- state: "active",
- },
- }),
- assistantWorkRows: [row],
- assistantTextRows: [row],
- latestAssistantTextRow: row,
- renderRows: [row],
- }),
- );
- const summaryIndex = html.indexOf("1 个文件已更改");
- const actionIndex = html.indexOf('data-testid="v4-copy-20"');
- const timeIndex = html.indexOf(`>${timeLabel}</span>`);
- expect(summaryIndex).toBeGreaterThanOrEqual(0);
- expect(actionIndex).toBeGreaterThanOrEqual(0);
- expect(timeIndex).toBeGreaterThanOrEqual(0);
- expect(summaryIndex).toBeLessThan(actionIndex);
- expect(actionIndex).toBeLessThan(timeIndex);
- });
- it("P07:在定时任务卡片、文件 summary 和操作栏之后渲染 fork 轮尾分割线", () => {
- const cronTool = toolCallRow(
- 5,
- "CronCreate",
- { title: "5分钟后提醒去干活" },
- {
- output: {
- text: JSON.stringify({
- automation: {
- automationId: "automation-p07",
- title: "5分钟后提醒去干活",
- cronExpr: "*/5 * * * *",
- },
- }),
- },
- },
- );
- const finalText = assistantTextRow(6, {
- text: "已设置好提醒。",
- actions: { canFork: true },
- });
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader({
- fileChanges: {
- files: 1,
- additions: 2,
- deletions: 1,
- state: "active",
- },
- }),
- userInputRow(2),
- cronTool,
- finalText,
- forkNoticeTimelineRow(7),
- ]);
- const html = renderUnit(unit!, {
- compactForRemoteControl: true,
- onFork: vi.fn(),
- onFeedbackChange: vi.fn(),
- });
- const cardIndex = html.indexOf(`data-testid="${TID_CRON_CREATE_CARD}"`);
- const summaryIndex = html.indexOf("1 个文件已更改");
- const dislikeIndex = html.indexOf('data-testid="v4-feedback-dislike-6"');
- const forkActionIndex = html.indexOf('data-testid="v4-fork-6"');
- const boundaryIndex = html.indexOf("从对话中派生");
- expect(cardIndex).toBeGreaterThanOrEqual(0);
- expect(summaryIndex).toBeGreaterThan(cardIndex);
- expect(dislikeIndex).toBeGreaterThan(summaryIndex);
- expect(forkActionIndex).toBeGreaterThan(dislikeIndex);
- expect(boundaryIndex).toBeGreaterThan(forkActionIndex);
- });
- it("P07:goalVerify 共用 turnTailBoundary 并在操作栏之后收尾", () => {
- const finalText = assistantTextRow(6, { text: "目标执行结果。" });
- const goalVerify = runningGoalVerifyTimelineRow(7);
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- finalText,
- goalVerify,
- ]);
- const html = renderUnit(unit!);
- expect(html.indexOf('data-testid="v4-copy-6"')).toBeLessThan(html.indexOf("目标校验中"));
- });
- it("renders CronCreate success card after the assistant reply while keeping the tool row ordinary", () => {
- const cronTool = toolCallRow(
- 5,
- "CronCreate",
- { title: "每2小时站起来走走提醒" },
- {
- output: {
- text: JSON.stringify({
- automation: {
- title: "每2小时站起来走走提醒",
- cronExpr: "0 9/2 * * *",
- },
- }),
- },
- },
- );
- const finalText = assistantTextRow(6, {
- text: "已设置:每2小时提醒你站起来走走。",
- });
- const [builtUnit] = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- cronTool,
- finalText,
- ]);
- const html = renderUnit({
- ...builtUnit!,
- assistantHistoryDefaultOpen: true,
- });
- const toolIndex = html.indexOf('data-tool-call-id="tool-5"');
- const replyIndex = html.indexOf("已设置:每2小时提醒你站起来走走。");
- const cardIndex = html.indexOf(`data-testid="${TID_CRON_CREATE_CARD}"`);
- const actionIndex = html.indexOf('data-testid="v4-copy-6"');
- const cardMatches = html.match(new RegExp(`data-testid="${TID_CRON_CREATE_CARD}"`, "g")) ?? [];
- expect(toolIndex).toBeGreaterThanOrEqual(0);
- expect(replyIndex).toBeGreaterThanOrEqual(0);
- expect(cardIndex).toBeGreaterThanOrEqual(0);
- expect(actionIndex).toBeGreaterThanOrEqual(0);
- expect(cardMatches).toHaveLength(1);
- expect(toolIndex).toBeLessThan(replyIndex);
- expect(replyIndex).toBeLessThan(cardIndex);
- expect(cardIndex).toBeLessThan(actionIndex);
- });
- it("renders the updated automation card after a successful CronUpdate", () => {
- const cronTool = toolCallRow(
- 5,
- "CronUpdate",
- { id: "automation-a", title: "工作日晨会提醒" },
- {
- output: {
- text: JSON.stringify({
- automation: {
- automationId: "automation-a",
- title: "工作日晨会提醒",
- cronExpr: "0 9 * * 1-5",
- },
- }),
- },
- },
- );
- const finalText = assistantTextRow(6, { text: "已修改定时任务。" });
- const [builtUnit] = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- cronTool,
- finalText,
- ]);
- const html = renderUnit({
- ...builtUnit!,
- assistantHistoryDefaultOpen: true,
- });
- const replyIndex = html.indexOf("已修改定时任务。");
- const cardIndex = html.indexOf(`data-testid="${TID_CRON_CREATE_CARD}"`);
- const actionIndex = html.indexOf('data-testid="v4-copy-6"');
- const cardSummary = html.slice(cardIndex, actionIndex);
- expect(html).toContain('data-tool-call-id="tool-5"');
- expect(replyIndex).toBeGreaterThanOrEqual(0);
- expect(cardIndex).toBeGreaterThan(replyIndex);
- expect(cardIndex).toBeLessThan(actionIndex);
- expect(cardSummary).toContain("工作日晨会提醒");
- expect(cardSummary).toContain("工作日");
- expect(cardSummary).toContain(`data-testid="${TID_CRON_CREATE_OPEN}"`);
- });
- it("只在轮尾展示同轮 Create/Delete 归并后仍存在的 CronCreate 卡片", () => {
- const firstCreate = toolCallRow(
- 5,
- "CronCreate",
- { title: "错误的一分钟提醒" },
- {
- output: {
- text: JSON.stringify({
- automation: {
- automationId: "automation-a",
- title: "错误的一分钟提醒",
- cronExpr: "54 14 17 7 *",
- },
- }),
- },
- },
- );
- const deleteFirst = toolCallRow(
- 6,
- "CronDelete",
- { id: "automation-a" },
- {
- output: {
- text: JSON.stringify({ deleted: true, id: "automation-a" }),
- },
- },
- );
- const secondCreate = toolCallRow(
- 7,
- "CronCreate",
- { title: "一分钟后开嗓提醒" },
- {
- output: {
- text: JSON.stringify({
- automation: {
- automationId: "automation-b",
- title: "一分钟后开嗓提醒",
- cronExpr: "55 14 17 7 *",
- },
- }),
- },
- },
- );
- const finalText = assistantTextRow(8, { text: "已经修正并重新设置。" });
- const [builtUnit] = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- firstCreate,
- deleteFirst,
- secondCreate,
- finalText,
- ]);
- const html = renderUnit({
- ...builtUnit!,
- assistantHistoryDefaultOpen: true,
- });
- const cardMatches = html.match(new RegExp(`data-testid="${TID_CRON_CREATE_CARD}"`, "g")) ?? [];
- const cardSummary = html.slice(
- html.indexOf(`data-testid="${TID_CRON_CREATE_CARD}"`),
- html.indexOf('data-testid="v4-copy-8"'),
- );
- expect(cardMatches).toHaveLength(1);
- expect(cardSummary).toContain("一分钟后开嗓提醒");
- expect(cardSummary).not.toContain("错误的一分钟提醒");
- expect(html).toContain('data-tool-call-id="tool-5"');
- expect(html).toContain('data-tool-call-id="tool-6"');
- expect(html).toContain('data-tool-call-id="tool-7"');
- });
- it("CronDelete 失败时保留对应的 CronCreate 轮尾卡片", () => {
- const create = toolCallRow(
- 5,
- "CronCreate",
- { title: "仍然有效的提醒" },
- {
- output: {
- text: JSON.stringify({
- automation: {
- automationId: "automation-a",
- title: "仍然有效的提醒",
- cronExpr: "0 9 * * *",
- },
- }),
- },
- },
- );
- const failedDelete = toolCallRow(
- 6,
- "CronDelete",
- { id: "automation-a" },
- {
- status: "error",
- error: { code: "DELETE_FAILED", message: "删除失败" },
- },
- );
- const finalText = assistantTextRow(7, { text: "删除没有成功。" });
- const [builtUnit] = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- create,
- failedDelete,
- finalText,
- ]);
- const html = renderUnit({
- ...builtUnit!,
- assistantHistoryDefaultOpen: true,
- });
- const cardMatches = html.match(new RegExp(`data-testid="${TID_CRON_CREATE_CARD}"`, "g")) ?? [];
- expect(cardMatches).toHaveLength(1);
- expect(html.slice(html.indexOf(`data-testid="${TID_CRON_CREATE_CARD}"`))).toContain(
- "仍然有效的提醒",
- );
- });
- it("does not render CronCreate success card until the assistant turn finishes", () => {
- const cronTool = toolCallRow(
- 5,
- "CronCreate",
- { title: "每2小时站起来走走提醒" },
- {
- output: {
- text: JSON.stringify({
- automation: {
- title: "每2小时站起来走走提醒",
- cronExpr: "0 9/2 * * *",
- },
- }),
- },
- },
- );
- const streamingText = assistantTextRow(6, {
- state: "streaming",
- text: "已设置:",
- });
- const html = renderUnit(
- baseUnit({
- key: "turn-complete:cron-running-card",
- turnId: "turn-complete",
- header: turnHeader({ state: "running" }),
- isRunning: true,
- workStatus: { state: "running", durationMs: 5_000 },
- assistantHistoryDefaultOpen: true,
- assistantWorkRows: [cronTool, streamingText],
- assistantHistoryRows: [cronTool, streamingText],
- assistantTextRows: [streamingText],
- renderRows: [cronTool, streamingText],
- }),
- );
- expect(html).toContain('data-tool-call-id="tool-5"');
- expect(html).toContain("已设置:");
- expect(html).not.toContain(`data-testid="${TID_CRON_CREATE_CARD}"`);
- });
- it("BTA09:renders the browser turn-end screenshot after preview cards and file summary", () => {
- const finalRow = assistantTextRow(20, {
- text: "网站已启动:http://localhost:3000",
- });
- const screenshotRow = toolCallRow(
- 21,
- "mcp__node_repl__js",
- { source: "browser_turn_end" },
- {
- display: {
- kind: "node_repl_images",
- source: "browser_turn_end",
- images: [{ base64: "AAAA", mimeType: "image/png" }],
- },
- },
- );
- const units = buildConversationTurnRenderUnits([
- turnHeader({
- fileChanges: {
- files: 1,
- additions: 38,
- deletions: 5,
- state: "active",
- },
- }),
- userInputRow(2),
- finalRow,
- screenshotRow,
- ]);
- const html = renderUnit(units[0]!);
- // lastIndexOf 取 Website 卡片标题,避开正文中更早出现的同一 URL。
- const previewIndex = html.lastIndexOf("localhost:3000");
- const summaryIndex = html.indexOf("1 个文件已更改");
- const screenshotIndex = html.indexOf("data:image/png;base64,AAAA");
- const actionIndex = html.indexOf('data-testid="v4-copy-20"');
- expect(previewIndex).toBeGreaterThanOrEqual(0);
- expect(summaryIndex).toBeGreaterThan(previewIndex);
- expect(screenshotIndex).toBeGreaterThan(summaryIndex);
- expect(actionIndex).toBeGreaterThan(screenshotIndex);
- });
- it("PV4-08:fork action 只读取 row.actions.canFork,不按 completed/数组位置猜测", () => {
- const onFork = vi.fn();
- const withoutAuthority = assistantTextRow(20);
- const withAuthority = assistantTextRow(21, { actions: { canFork: true } });
- const unit = (row: AssistantTextRow) =>
- baseUnit({
- key: `turn-complete:fork-${row.rowId}`,
- turnId: "turn-complete",
- isLastTurn: true,
- header: turnHeader(),
- assistantWorkRows: [row],
- assistantTextRows: [row],
- latestAssistantTextRow: row,
- renderRows: [row],
- });
- expect(renderUnit(unit(withoutAuthority), { onFork })).not.toContain("v4-fork-");
- expect(renderUnit(unit(withAuthority), { onFork })).toContain("v4-fork-21");
- });
- it("BG33:普通 assistant retry capability 保留但 UI 入口统一隐藏", () => {
- const onFork = vi.fn();
- const onRetry = vi.fn();
- const backgroundRow = assistantTextRow(30, { actions: { canFork: true } });
- const backgroundHtml = renderUnit(
- baseUnit({
- key: "turn-background:retry-boundary",
- turnId: "turn-complete",
- isLastTurn: true,
- header: turnHeader({
- origin: "backgroundResult",
- originMeta: {
- backgroundSource: "subagent",
- title: "Review retry projection",
- workId: "agent-retry-review",
- },
- }),
- assistantWorkRows: [backgroundRow],
- assistantTextRows: [backgroundRow],
- latestAssistantTextRow: backgroundRow,
- renderRows: [backgroundRow],
- }),
- { onFork, onRetry },
- );
- expect(backgroundHtml).toContain("v4-fork-30");
- expect(backgroundHtml).not.toContain("v4-retry-30");
- const realUserRow = assistantTextRow(31, {
- actions: { canFork: true, canRetry: true },
- });
- const realUserHtml = renderUnit(
- baseUnit({
- key: "turn-real-user:retry-boundary",
- turnId: "turn-complete",
- isLastTurn: true,
- header: turnHeader(),
- assistantWorkRows: [realUserRow],
- assistantTextRows: [realUserRow],
- latestAssistantTextRow: realUserRow,
- renderRows: [realUserRow],
- }),
- { onFork, onRetry },
- );
- expect(realUserHtml).not.toContain("v4-retry-31");
- });
- it("按复制、赞、踩、分叉顺序渲染反馈工具栏,手机远控常显", () => {
- const createdAt = new Date();
- createdAt.setHours(7, 15, 0, 0);
- const timeLabel = new Intl.DateTimeFormat("zh-CN", {
- hour: "2-digit",
- minute: "2-digit",
- }).format(createdAt);
- const row = assistantTextRow(22, {
- actions: { canFork: true },
- createdAt: createdAt.getTime(),
- });
- const html = renderUnit(
- baseUnit({
- key: "turn-complete:feedback",
- turnId: "turn-complete",
- isLastTurn: true,
- header: turnHeader(),
- assistantWorkRows: [row],
- assistantTextRows: [row],
- latestAssistantTextRow: row,
- renderRows: [row],
- }),
- {
- compactForRemoteControl: true,
- onFork: vi.fn(),
- onFeedbackChange: vi.fn(),
- },
- );
- const copyIndex = html.indexOf('data-testid="v4-copy-22"');
- const likeIndex = html.indexOf('data-testid="v4-feedback-like-22"');
- const dislikeIndex = html.indexOf('data-testid="v4-feedback-dislike-22"');
- const forkIndex = html.indexOf('data-testid="v4-fork-22"');
- const timeIndex = html.indexOf(`>${timeLabel}</span>`);
- expect(copyIndex).toBeGreaterThanOrEqual(0);
- expect(copyIndex).toBeLessThan(likeIndex);
- expect(likeIndex).toBeLessThan(dislikeIndex);
- expect(dislikeIndex).toBeLessThan(forkIndex);
- expect(forkIndex).toBeLessThan(timeIndex);
- expect(html).toContain('aria-pressed="false"');
- expect(html).toContain("opacity-100");
- expect(html).not.toContain("group-hover/assistant-turn:opacity-100");
- });
- it("带 CLI action 的 assistant 后面仍有 work row 时也渲染 action", () => {
- const onFork = vi.fn();
- const actionRow = assistantTextRow(4, { actions: { canFork: true } });
- const units = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- actionRow,
- reasoningRow(),
- ]);
- expect(renderUnit(units[0]!, { onFork })).toContain("v4-fork-4");
- });
- it("preserves text tool text order inside the single assistant history group", () => {
- const units = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- reasoningRow(),
- assistantTextRow(4, { text: "Let me看看这个项目里有什么。" }),
- toolCallRow(5, "Bash", {
- command: "ls -la /workspace",
- description: "List project files",
- }),
- assistantTextRow(6, { text: "最终回答" }),
- ]);
- const html = renderUnit({
- ...units[0]!,
- assistantHistoryDefaultOpen: true,
- });
- const historyTriggerMatches = html.match(/data-testid="chat-assistant-history-trigger/g) ?? [];
- const earlyTextIndex = html.indexOf("Let me看看这个项目里有什么。");
- const toolIndex = html.indexOf("tool-5");
- const finalTextIndex = html.indexOf("最终回答");
- expect(historyTriggerMatches).toHaveLength(1);
- expect(earlyTextIndex).toBeGreaterThanOrEqual(0);
- expect(toolIndex).toBeGreaterThanOrEqual(0);
- expect(finalTextIndex).toBeGreaterThanOrEqual(0);
- expect(earlyTextIndex).toBeLessThan(toolIndex);
- expect(toolIndex).toBeLessThan(finalTextIndex);
- expect(html).not.toContain('data-testid="v4-copy-4"');
- expect(html).toContain('data-testid="v4-copy-6"');
- });
- it("P06:每条 guided user 开独立工作段,且只展开目标段不影响其它段", () => {
- const units = buildConversationTurnRenderUnits([
- turnHeader({
- workSegments: [
- {
- segmentId: "initial",
- startedAt: 1_700_000_000_000,
- endedAt: 1_700_000_000_005,
- activeMs: 5_000,
- },
- {
- segmentId: "guide-1",
- triggerEntityId: "guide-1",
- startedAt: 1_700_000_000_005,
- endedAt: 1_700_000_000_007,
- activeMs: 2_000,
- },
- {
- segmentId: "guide-2",
- triggerEntityId: "guide-2",
- startedAt: 1_700_000_000_007,
- endedAt: 1_700_000_000_008,
- activeMs: 1_000,
- },
- ],
- }),
- userInputRow(2, { text: "这是个啥项目" }),
- reasoningRow(),
- toolCallRow(4, "Read", { file_path: "AGENTS.md" }),
- userInputRow(5, { text: "111", guided: true, entityId: "guide-1" }),
- assistantTextRow(6, { text: "这是项目介绍" }),
- userInputRow(7, { text: "11", guided: true, entityId: "guide-2" }),
- assistantTextRow(8, { text: "还需要我做什么?" }),
- ]);
- expect(units[0]?.workStatus).toBeDefined();
- const collapsedHtml = renderUnit(units[0]!);
- const collapsedIndexes = [
- collapsedHtml.indexOf('data-row-id="2"'),
- collapsedHtml.indexOf("chat-assistant-history-trigger"),
- collapsedHtml.indexOf('data-row-id="5"'),
- collapsedHtml.indexOf('data-row-id="6"'),
- collapsedHtml.indexOf('data-row-id="7"'),
- collapsedHtml.indexOf('data-row-id="8"'),
- ];
- expect(
- collapsedIndexes.every((index) => index >= 0),
- JSON.stringify(collapsedIndexes),
- ).toBe(true);
- expect(collapsedIndexes).toEqual([...collapsedIndexes].sort((left, right) => left - right));
- expect(collapsedHtml).not.toContain('data-row-id="4"');
- expect(collapsedHtml.match(/chat-assistant-history-trigger/g)).toHaveLength(3);
- expect(collapsedHtml).toContain("已工作 5 秒");
- expect(collapsedHtml).toContain("已工作 2 秒");
- expect(collapsedHtml).toContain("已工作 1 秒");
- const expandedHtml = renderUnit({
- ...units[0]!,
- workSegments: units[0]!.workSegments!.map((segment, index) => ({
- ...segment,
- assistantHistoryDefaultOpen: index === 0,
- })),
- });
- const expandedIndexes = [
- expandedHtml.indexOf('data-row-id="2"'),
- expandedHtml.indexOf('data-row-id="4"'),
- expandedHtml.indexOf('data-row-id="5"'),
- expandedHtml.indexOf('data-row-id="6"'),
- expandedHtml.indexOf('data-row-id="7"'),
- expandedHtml.indexOf('data-row-id="8"'),
- ];
- expect(expandedIndexes.every((index) => index >= 0)).toBe(true);
- expect(expandedIndexes).toEqual([...expandedIndexes].sort((left, right) => left - right));
- expect(expandedHtml.match(/chat-assistant-history-trigger/g)).toHaveLength(3);
- expect(expandedHtml).toContain(
- 'data-testid="chat-assistant-history-trigger-turn-complete" data-history-open="true"',
- );
- expect(expandedHtml).toContain(
- 'data-testid="chat-assistant-history-trigger-turn-complete:guide:guide-1" data-history-open="false"',
- );
- expect(expandedHtml).not.toContain('data-testid="v4-copy-6"');
- expect(expandedHtml).toContain('data-testid="v4-copy-8"');
- });
- });
- describe("ConversationTurnGroup ChatLoading lifecycle", () => {
- it("第三次 retry 才替换当前 turn 底部的通用 loading,并保留 3/10 计数口径", () => {
- const html = renderUnit(
- baseUnit({
- isRunning: true,
- assistantHistoryDefaultOpen: true,
- }),
- {
- apiRetry: {
- attempt: 3,
- maxAttempts: 11,
- nextRetryAt: 1_700_000_001_000,
- reasonCode: "fault.provider.rateLimited",
- },
- },
- );
- expect(html).toContain("重新连接中... 3/10");
- expect(html).not.toContain('data-testid="chat-loading"');
- });
- it.each([1, 2])("attempt=%d 时隐藏 retry 文案并继续显示通用 loading", (attempt) => {
- const html = renderUnit(
- baseUnit({
- isRunning: true,
- assistantHistoryDefaultOpen: true,
- }),
- {
- apiRetry: {
- attempt,
- maxAttempts: 11,
- nextRetryAt: 1_700_000_001_000,
- reasonCode: "fault.provider.rateLimited",
- },
- },
- );
- expect(html).not.toContain("重新连接中...");
- expect(html).toContain('data-testid="chat-loading"');
- expect(html).toContain('data-zcode-chat-loading-slot="true"');
- });
- it("attempt<=2 时仍遵守阻塞交互的 loading gate", () => {
- const html = renderUnit(
- baseUnit({
- isRunning: true,
- assistantHistoryDefaultOpen: true,
- }),
- {
- chatLoadingBlockedByInteraction: true,
- apiRetry: {
- attempt: 2,
- maxAttempts: 11,
- nextRetryAt: 1_700_000_001_000,
- reasonCode: "fault.provider.rateLimited",
- },
- },
- );
- expect(html).not.toContain("重新连接中...");
- expect(html).not.toContain('data-testid="chat-loading"');
- });
- it("retry 清除后恢复当前 running turn 的通用 loading", () => {
- const html = renderUnit(
- baseUnit({
- isRunning: true,
- assistantHistoryDefaultOpen: true,
- }),
- { apiRetry: null },
- );
- expect(html).not.toContain("重新连接中...");
- expect(html).toContain('data-testid="chat-loading"');
- });
- it.each([
- ["assistant text", assistantTextRow(10, { state: "streaming" })],
- ["reasoning", { ...reasoningRow(), state: "streaming" }],
- ["tool", toolCallRow(11, "Bash", { command: "pnpm test" }, { status: "running" })],
- ["subagent", subagentRow(12, { status: "running" })],
- ] as const)("shows loading immediately while a running turn contains %s", (_label, row) => {
- const html = renderUnit(
- baseUnit({
- isRunning: true,
- assistantHistoryDefaultOpen: true,
- assistantWorkRows: [row],
- assistantHistoryRows: [row],
- renderRows: [row],
- }),
- );
- expect(html).toContain('data-testid="chat-loading"');
- });
- it.each([
- ["compact", runningTimelineRow(20)],
- ["goal verifier", runningGoalVerifyTimelineRow(21)],
- ] as const)("hides loading for a running %s timeline-only turn", (_label, row) => {
- const html = renderUnit(
- baseUnit({
- isRunning: true,
- timelineOnly: true,
- assistantWorkRows: [row],
- assistantHistoryRows: [row],
- renderRows: [row],
- }),
- );
- expect(html).not.toContain('data-testid="chat-loading"');
- });
- it("keeps loading visible for a running structured background-result turn", () => {
- const row = assistantTextRow(30, { state: "streaming" });
- const html = renderUnit(
- baseUnit({
- header: turnHeader({
- origin: "backgroundResult",
- originMeta: {
- backgroundSource: "subagent",
- title: "Review projection",
- workId: "agent-work",
- },
- state: "running",
- }),
- isRunning: true,
- assistantWorkRows: [row],
- assistantHistoryRows: [row],
- assistantTextRows: [row],
- renderRows: [row],
- }),
- );
- expect(html).toContain('data-testid="chat-loading"');
- });
- it("hides loading after the latest turn reaches a terminal state", () => {
- const row = assistantTextRow(40);
- const html = renderUnit(
- baseUnit({
- assistantWorkRows: [row],
- assistantTextRows: [row],
- latestAssistantTextRow: row,
- renderRows: [row],
- }),
- );
- expect(html).not.toContain('data-testid="chat-loading"');
- });
- it("hides loading while the session projection is waiting for user interaction", () => {
- const html = renderUnit(
- baseUnit({
- isRunning: true,
- assistantHistoryDefaultOpen: true,
- }),
- { chatLoadingBlockedByInteraction: true },
- );
- expect(html).not.toContain('data-testid="chat-loading"');
- });
- it("hides loading while compact or goal verifier is active", () => {
- const html = renderUnit(
- baseUnit({
- isRunning: true,
- assistantHistoryDefaultOpen: true,
- }),
- { chatLoadingBlockedByActiveWork: true },
- );
- expect(html).not.toContain('data-testid="chat-loading"');
- });
- it("hides loading when a pendingApproval row arrives before interaction state", () => {
- const row = toolCallRow(
- 41,
- "Bash",
- { command: "touch output.txt" },
- { status: "pendingApproval" },
- );
- const html = renderUnit(
- baseUnit({
- isRunning: true,
- assistantHistoryDefaultOpen: true,
- assistantWorkRows: [row],
- assistantHistoryRows: [row],
- renderRows: [row],
- }),
- );
- expect(html).not.toContain('data-testid="chat-loading"');
- });
- it("does not show loading for a stale running historical turn", () => {
- const html = renderUnit(
- baseUnit({
- isLastTurn: false,
- isRunning: true,
- assistantHistoryDefaultOpen: true,
- }),
- );
- expect(html).not.toContain('data-testid="chat-loading"');
- });
- });
- const LAUNCH_META: WorkflowLaunchMeta = {
- runId: "run-42",
- toolCallId: "launch-abc",
- name: "deep-research",
- scope: "global",
- path: "/home/u/.zcode/workflows/deep-research.dwf.ts",
- description: "跨网深挖一个话题并写简报。",
- args: { topic: "adaptive concurrency" },
- };
- // agent 铸造的规范英文句(进 userInput.text,旧客户端 / TUI 的降级呈现);启动卡不显示它。
- const LAUNCH_CANONICAL =
- 'Started the saved workflow "deep-research" (global) from the workflows hub as run run-42.';
- describe("ConversationTurnGroup — 直接启动轮(workflowLaunch)", () => {
- const LAUNCH_GRAPH = {
- steps: [{ id: "ask#1", kind: "ask", label: "a", line: 1, column: 21, lane: "actor#1" }],
- lanes: [{ id: "actor#1", name: "researcher", line: 1, column: 11 }],
- participants: [
- { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
- ],
- handoffs: [],
- };
- const LAUNCH_RUN: WorkflowRunState = {
- runId: "run-42",
- toolCallId: "launch-abc",
- status: "running",
- usage: { spentTokens: 12, nodesUsed: 1 },
- actors: [{ siteId: "actor#1", ordinal: 1, name: "Ada", sessionId: "s-1", status: "running" }],
- nodes: [
- { siteId: "ask#1", ordinal: 1, phase: "executing", actorSiteId: "actor#1", actorOrdinal: 1 },
- ] as WorkflowRunState["nodes"],
- lastEventSequence: 3,
- };
- const LAUNCH_JOIN: Partial<ConversationRowRenderContext> = {
- sessionId: "session-main",
- workflowRunByRunId: new Map([
- [
- "run-42",
- {
- runId: "run-42",
- toolCallId: "launch-abc",
- status: "running",
- nodesSettled: 0,
- nodesTotal: 1,
- run: LAUNCH_RUN,
- },
- ],
- ]),
- workflowGraphByToolCallId: new Map([["launch-abc", LAUNCH_GRAPH]]),
- };
- function launchRows(meta: WorkflowLaunchMeta | undefined, turnId = "turn-complete") {
- return [
- turnHeader({
- turnId,
- origin: "workflowLaunch",
- executionKind: "controlOnly",
- ...(meta === undefined ? {} : { workflowLaunch: meta }),
- }),
- userInputRow(2, {
- turnId,
- origin: "workflowLaunch",
- text: LAUNCH_CANONICAL,
- ...(meta === undefined ? {} : { workflowLaunch: meta }),
- }),
- ];
- }
- it("启动轮就是一张 run 卡:与工具路径同一张 WorkflowRunDigest(时间线、子代理药丸),没有用户气泡", () => {
- const [unit] = buildConversationTurnRenderUnits(launchRows(LAUNCH_META));
- expect(unit!.workflowLaunch).toEqual(LAUNCH_META);
- expect(unit!.visibleUserInputs).toEqual([]);
- const html = renderUnit(unit!, { context: LAUNCH_JOIN });
- expect(html).toContain(
- `data-testid="${testId(TID_CHAT_WORKFLOW_RUN_DIGEST, `${unit!.key}-launch-abc`)}"`,
- );
- expect(html).toContain('data-workflow-run-id="run-42"');
- expect(html).toContain('data-workflow-run-status="running"');
- expect(html).toContain("deep-research");
- expect(html).toContain('data-testid="workflow-timeline-station"');
- expect(html).toContain('data-testid="workflow-agent-pill"');
- // 卡就是这一轮的全部呈现:不落那句规范英文气泡,也没有实参表(来龙去脉在详情侧板)。
- expect(html).not.toContain(LAUNCH_CANONICAL);
- expect(html).not.toContain("adaptive concurrency");
- expect(html.match(/data-workflow-run-digest="true"/g)).toHaveLength(1);
- });
- it("run 不在活投影里(淘汰 / 冷恢复):中性单行卡「Workflow ended」,无灯无轨道,仍不落气泡", () => {
- const [unit] = buildConversationTurnRenderUnits(launchRows(LAUNCH_META));
- const html = renderUnit(unit!, { context: { sessionId: "session-main" }, locale: "en-US" });
- expect(html).toContain('data-workflow-run-digest="true"');
- expect(html).toContain('data-workflow-run-status="absent"');
- expect(html).toContain("Workflow ended");
- expect(html).toContain("deep-research");
- expect(html).not.toContain('data-testid="workflow-timeline-station"');
- expect(html).not.toContain('data-testid="workflow-digest-cancel"');
- expect(html).not.toContain(LAUNCH_CANONICAL);
- });
- it("元数据缺席时落穿到普通渲染(降级为规范句气泡)", () => {
- const [unit] = buildConversationTurnRenderUnits(launchRows(undefined));
- expect(unit!.workflowLaunch).toBeUndefined();
- const html = renderUnit(unit!);
- expect(html).not.toContain('data-workflow-run-digest="true"');
- // 规范句进气泡(引号在 HTML 里转义,断言无引号片段)。
- expect(html).toContain("from the workflows hub as run run-42.");
- });
- it("后续普通轮不受影响", () => {
- const units = buildConversationTurnRenderUnits([
- ...launchRows(LAUNCH_META, "turn-launch"),
- turnHeader({ rowId: 3, createdAtSeq: 3, turnId: "turn-next" }),
- userInputRow(4, { turnId: "turn-next", text: "看看下一步" }),
- ]);
- const launchUnit = units.find((unit) => unit.turnId === "turn-launch");
- const nextUnit = units.find((unit) => unit.turnId === "turn-next");
- expect(launchUnit).toBeDefined();
- expect(nextUnit).toBeDefined();
- expect(renderUnit(launchUnit!, { context: LAUNCH_JOIN })).toContain(
- 'data-workflow-run-digest="true"',
- );
- const nextHtml = renderUnit(nextUnit!, { context: LAUNCH_JOIN });
- expect(nextHtml).not.toContain('data-workflow-run-digest="true"');
- expect(nextHtml).toContain("看看下一步");
- });
- });
- // ── 轮尾摘要(docs/dynamic-workflow/presentation.md「The run card」)──
- const DIGEST_GRAPH = {
- steps: [{ id: "ask#1", kind: "ask", label: "a", line: 1, column: 21, lane: "actor#1" }],
- lanes: [{ id: "actor#1", name: "planner", line: 1, column: 11 }],
- participants: [{ id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] }],
- handoffs: [],
- };
- function workflowToolRow(rowId: number, overrides: Partial<ToolCallRow> = {}): ToolCallRow {
- return toolCallRow(
- rowId,
- "CreateWorkflow",
- { name: "implement-verify", script: "const p = agent('planner');" },
- {
- output: {
- text: "ok",
- display: {
- kind: "create_workflow",
- ok: true,
- errorCount: 0,
- diagnostics: [],
- causalityGraph: DIGEST_GRAPH,
- },
- } as ToolCallRow["output"],
- ...overrides,
- },
- );
- }
- const DIGEST_RUN: WorkflowRunState = {
- runId: "run-7",
- toolCallId: "tool-5",
- status: "running",
- usage: { spentTokens: 12, nodesUsed: 1 },
- actors: [{ siteId: "actor#1", ordinal: 1, name: "Ada", sessionId: "s-1", status: "running" }],
- nodes: [
- { siteId: "ask#1", ordinal: 1, phase: "executing", actorSiteId: "actor#1", actorOrdinal: 1 },
- ] as WorkflowRunState["nodes"],
- lastEventSequence: 3,
- };
- const DIGEST_JOIN: Partial<ConversationRowRenderContext> = {
- sessionId: "session-main",
- // 图按发起 toolCallId 到图表取(docs/dynamic-workflow/presentation.md「The run card」)。
- workflowGraphByToolCallId: new Map([["tool-5", DIGEST_GRAPH]]),
- workflowRunByToolCallId: new Map([
- [
- "tool-5",
- {
- runId: "run-7",
- toolCallId: "tool-5",
- status: "running",
- nodesSettled: 0,
- nodesTotal: 1,
- run: DIGEST_RUN,
- },
- ],
- ]),
- };
- describe("ConversationTurnGroup — 轮尾摘要(workflow run digest)", () => {
- it("轮结束后,联接到 run 的 CreateWorkflow 行在最后一段正文之后、操作栏之前多出一张摘要;工具卡本身仍在折叠里", () => {
- const tool = workflowToolRow(5);
- const finalText = assistantTextRow(6, { text: "已启动,跑完我会汇报。" });
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- tool,
- finalText,
- ]);
- const html = renderUnit(
- { ...unit!, assistantHistoryDefaultOpen: true },
- { context: DIGEST_JOIN },
- );
- const toolIndex = html.indexOf('data-tool-call-id="tool-5"');
- const replyIndex = html.indexOf("已启动,跑完我会汇报。");
- const digestIndex = html.indexOf('data-workflow-run-digest="true"');
- const actionIndex = html.indexOf('data-testid="v4-copy-6"');
- expect(toolIndex).toBeGreaterThanOrEqual(0);
- expect(digestIndex).toBeGreaterThanOrEqual(0);
- expect(toolIndex).toBeLessThan(replyIndex);
- expect(replyIndex).toBeLessThan(digestIndex);
- expect(digestIndex).toBeLessThan(actionIndex);
- expect(html.match(/data-workflow-run-digest="true"/g)).toHaveLength(1);
- // 收起态:阶段线在、药丸不在(折叠里的卡照旧画药丸,只看摘要那一段);名字与运行状态在表头。
- const digestHtml = html.slice(digestIndex, actionIndex);
- expect(digestHtml).toContain('data-testid="workflow-timeline-station"');
- expect(digestHtml).toContain("implement-verify");
- expect(digestHtml).toContain('data-workflow-run-status="running"');
- expect(digestHtml).toContain('data-testid="workflow-agent-pill"');
- // sessionId + onOpenWorkflowRun 都在场才有 ⤢;这里没注入回调,就没有。
- expect(digestHtml).not.toContain('data-testid="workflow-card-open-details"');
- });
- it("主轮仍在运行时,有 run 立即显示摘要;没联接到 run 的行没有", () => {
- const tool = workflowToolRow(5);
- const streaming = assistantTextRow(6, { state: "streaming", text: "正在…" });
- const running = baseUnit({
- key: "turn-complete:digest-running",
- turnId: "turn-complete",
- header: turnHeader({ state: "running" }),
- isRunning: true,
- workStatus: { state: "running", durationMs: 5_000 },
- assistantHistoryDefaultOpen: true,
- assistantWorkRows: [tool, streaming],
- assistantHistoryRows: [tool, streaming],
- assistantTextRows: [streaming],
- renderRows: [tool, streaming],
- });
- const runningHtml = renderUnit(running, { context: DIGEST_JOIN });
- expect(runningHtml).toContain('data-tool-call-id="tool-5"');
- expect(runningHtml.match(/data-workflow-run-digest="true"/g)).toHaveLength(1);
- expect(runningHtml).toContain('data-testid="workflow-tool-summary"');
- expect(runningHtml).not.toContain('data-testid="workflow-card"');
- expect(runningHtml).toContain('data-testid="workflow-timeline-station"');
- const [finished] = buildConversationTurnRenderUnits([
- turnHeader(),
- userInputRow(2),
- tool,
- assistantTextRow(6),
- ]);
- expect(renderUnit(finished!)).not.toContain('data-workflow-run-digest="true"');
- });
- });
- // 完成卡(docs/dynamic-workflow/transcript-and-notifications.md):主代理消化 completed 通知的那一轮,轮尾落卡。
- // 这里没有会话上下文(静态渲染),卡画的是冷态那一层:通知载荷的产物(纸页字形)+ 联接到的数字。
- const COMPLETION_RUN: WorkflowRunState = {
- ...DIGEST_RUN,
- runId: "run-done",
- status: "completed",
- usage: { spentTokens: 386_412, nodesUsed: 16 },
- phases: [{ name: "plan", rounds: 1 }],
- artifacts: [
- { id: "brief", kind: "markdown", title: "research-brief.md", version: 1, bytes: 12_288 },
- ],
- };
- function completionUnit(status: "completed" | "failed" | "cancelled", withArtifacts = true) {
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader({
- origin: "backgroundResult",
- originMeta: {
- backgroundSource: "workflow",
- title: "deep-research",
- workId: "run-done",
- workflowNotification: {
- kind: "terminal",
- status,
- summary: "Workflow run completed.",
- durationMs: 708_000,
- ...(withArtifacts
- ? {
- artifacts: [
- { id: "brief", kind: "markdown", title: "research-brief.md", version: 1 },
- { id: "sources", kind: "file", title: "sources.csv", version: 2 },
- ],
- }
- : {}),
- },
- },
- }),
- assistantTextRow(6, { text: "研究跑完了,摘要如下。" }),
- ]);
- return unit!;
- }
- const COMPLETION_JOIN: Partial<ConversationRowRenderContext> = {
- sessionId: "session-main",
- onOpenWorkflowRun: () => {},
- onOpenWorkflowArtifact: () => {},
- workflowRunByRunId: new Map([
- [
- "run-done",
- {
- runId: "run-done",
- toolCallId: "tool-launch",
- status: "completed",
- nodesSettled: 16,
- nodesTotal: 16,
- run: COMPLETION_RUN,
- },
- ],
- ]),
- };
- describe("ConversationTurnGroup — 完成卡(workflow completion card)", () => {
- it("completed 通知轮:卡在最后一段正文之后、操作栏之前,且只一张;通知行仍在最前", () => {
- const unit = completionUnit("completed");
- const html = renderUnit(unit, { context: COMPLETION_JOIN, locale: "en-US" });
- const rowIndex = html.indexOf(`data-testid="chat-workflow-notification-row-${unit.key}"`);
- const replyIndex = html.indexOf("研究跑完了,摘要如下。");
- const cardIndex = html.indexOf('data-workflow-completion-card="true"');
- const actionIndex = html.indexOf('data-testid="v4-copy-6"');
- expect(rowIndex).toBeGreaterThanOrEqual(0);
- expect(cardIndex).toBeGreaterThanOrEqual(0);
- expect(rowIndex).toBeLessThan(replyIndex);
- expect(replyIndex).toBeLessThan(cardIndex);
- expect(cardIndex).toBeLessThan(actionIndex);
- expect(html.match(/data-workflow-completion-card="true"/g)).toHaveLength(1);
- const card = html.slice(cardIndex, actionIndex);
- // 表头:种类词 + 名字 + 状态词 + ⤢(sessionId + 回调 + 联接到的 toolCallId 都在)。
- expect(card).toContain("Workflow completed");
- expect(card).toContain("deep-research");
- expect(card).toContain('data-testid="workflow-completion-status"');
- expect(card).toContain('data-testid="workflow-card-open-details"');
- // 产物索引:没有交付物 ⇒ 两行、没有框(索引不画预览,也就没有纸页字形);v2 尾槽在;可点。
- expect(card.match(/data-testid="workflow-completion-line"/g)).toHaveLength(2);
- expect(card).toContain('data-testid="workflow-completion-index"');
- expect(card).not.toContain('data-testid="workflow-artifact-sheet"');
- expect(card).toContain(">v2<");
- expect(card).toContain('data-artifact-open="true"');
- // 四格:时间来自通知,其余三格来自联接到的投影。
- expect(card).toContain('data-value="11m 48s"');
- expect(card).toContain('data-value="386.4k"');
- // 夹具里一个子代理、一个进过的阶段;卡上不说「步」(2026-09-09)。
- expect(card).toMatch(/workflow-completion-figure-subagents" data-value="1"/u);
- expect(card).toMatch(/workflow-completion-figure-phases" data-value="1"/u);
- expect(card).not.toContain("figure-steps");
- });
- it("联接不到 run(冷恢复):时间与产物照画,其余三格 `—`,无 ⤢;零产物没有索引", () => {
- const html = renderUnit(completionUnit("completed"), { locale: "en-US" });
- const cardIndex = html.indexOf('data-workflow-completion-card="true"');
- expect(cardIndex).toBeGreaterThanOrEqual(0);
- const card = html.slice(cardIndex);
- expect(card).toContain('data-value="11m 48s"');
- expect(card).not.toContain('data-value="386.4k"');
- expect(card).toContain("—");
- expect(card).not.toContain('data-testid="workflow-card-open-details"');
- expect(card.match(/data-testid="workflow-completion-line"/g)).toHaveLength(2);
- const bare = renderUnit(completionUnit("completed", false), { locale: "en-US" });
- expect(bare).toContain('data-workflow-completion-card="true"');
- expect(bare).not.toContain('data-testid="workflow-completion-index"');
- });
- // 交付物(docs/dynamic-workflow/transcript-and-notifications.md「Artifact tiles」):载荷上的 primary + description
- // 让冷态卡(没有会话上下文)也画得出交付物行——冷 transcript 上只有这份载荷可读。
- it("载荷带 primary:冷态卡画交付物行(说明来自载荷)+ 索引行;没有「primary」字样", () => {
- const [unit] = buildConversationTurnRenderUnits([
- turnHeader({
- origin: "backgroundResult",
- originMeta: {
- backgroundSource: "workflow",
- title: "deep-research",
- workId: "run-done",
- workflowNotification: {
- kind: "terminal",
- status: "completed",
- summary: "Workflow run completed.",
- durationMs: 708_000,
- artifacts: [
- {
- id: "report",
- kind: "markdown",
- title: "Research report",
- version: 2,
- primary: true,
- description: "Twelve sources compared; three claims confirmed.",
- },
- { id: "sources", kind: "file", title: "sources.csv", version: 1 },
- ],
- },
- },
- }),
- assistantTextRow(6, { text: "研究跑完了,摘要如下。" }),
- ]);
- const html = renderUnit(unit!, { locale: "en-US" });
- const card = html.slice(html.indexOf('data-workflow-completion-card="true"'));
- expect(card).toContain('data-testid="workflow-completion-row"');
- expect(card).toContain("Twelve sources compared; three claims confirmed.");
- expect(card.match(/data-testid="workflow-completion-line"/g)).toHaveLength(1);
- expect(card).toContain('data-variant="line"');
- expect(card).toContain('data-testid="workflow-completion-index"');
- expect(card).not.toMatch(/>\s*primary\s*</iu);
- });
- it.each(["failed", "cancelled"] as const)("%s 的通知轮不画卡", (status) => {
- const html = renderUnit(completionUnit(status), { context: COMPLETION_JOIN });
- expect(html).not.toContain('data-workflow-completion-card="true"');
- expect(html).toContain("deep-research");
- });
- it("主轮还在跑时没有卡", () => {
- const finished = completionUnit("completed");
- const running = baseUnit({
- ...finished,
- key: "turn-complete:completion-running",
- isRunning: true,
- workStatus: { state: "running", durationMs: 5_000 },
- });
- expect(renderUnit(running, { context: COMPLETION_JOIN })).not.toContain(
- 'data-workflow-completion-card="true"',
- );
- });
- });
- describe("topic preparation flow membership", () => {
- it("renders preparing messages inside the conversation turn with a source loading indicator", () => {
- const items = [
- {
- messageId: "pending-a",
- senderName: "Alice",
- text: "weather",
- status: "preparing" as const,
- },
- ];
- const unit = withTopicPreparationMessages([], [], items)[0]!;
- const botContext = {
- taskId: "task",
- context: { activeTaskId: "task", group: { threadId: "topic" } },
- busyId: null,
- retryPreparation: async () => {},
- } as NonNullable<ContextType<typeof DeliveryContext>>;
- for (const compactForRemoteControl of [false, true]) {
- const html = renderUnit(unit, { botContext, compactForRemoteControl });
- expect(html).toContain('data-topic-preparation="pending-a"');
- const preparation = html.indexOf('data-topic-preparation="pending-a"');
- expect(html.indexOf("<section")).toBeLessThan(preparation);
- expect(html.indexOf("</section>")).toBeGreaterThan(preparation);
- expect(html).toContain('data-v4-user-input-collapsible-content="true"');
- expect(html).toContain('aria-label="正在准备材料"');
- }
- });
- });
|