tui-workflow-card.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. import assert from "node:assert/strict";
  2. import test from "node:test";
  3. import { SessionEventType, createSessionEvent, type SessionEvent } from "@zcode/contracts";
  4. import { getZCodeCopy } from "@zcode/i18n";
  5. import { WORKFLOW_RUNS_LIMITS } from "@zcode/shared/zcode-protocol-v4";
  6. import {
  7. EMPTY_TUI_WORKFLOW_MIRROR,
  8. applyWorkflowProgressToMirror,
  9. buildTuiWorkflowCardIndex,
  10. seedWorkflowMirror,
  11. workflowRunStepCounts,
  12. type TuiWorkflowMirror,
  13. } from "../src/app-workflow-mirror.js";
  14. import { MAX_ACTOR_ROWS, WorkflowRunCardView, actorRowsForCard } from "../src/app-workflow-card.js";
  15. import { applySessionEventToState } from "../src/app-events.js";
  16. import { rememberSessionEvent } from "../src/app-session-event-handler.js";
  17. import {
  18. appendWorkflowInterruptedNotices,
  19. interruptedWorkflowNotices,
  20. workflowInterruptedNoticeText,
  21. workflowRunSeedFromSummary,
  22. } from "../src/app-workflow-seed.js";
  23. const COPY = getZCodeCopy("en-US").tui;
  24. const RUN_ID = "dwfrun-1";
  25. const TOOL_CALL_ID = "tc-1";
  26. let sequence = 0;
  27. function progress(
  28. eventType: string,
  29. payload: Record<string, unknown> = {},
  30. extra: Record<string, unknown> = {},
  31. ) {
  32. sequence += 1;
  33. return {
  34. runId: RUN_ID,
  35. toolCallId: TOOL_CALL_ID,
  36. sequence,
  37. eventType,
  38. payload,
  39. ...extra,
  40. };
  41. }
  42. function mirrorAfter(
  43. events: readonly Record<string, unknown>[],
  44. initial: TuiWorkflowMirror = EMPTY_TUI_WORKFLOW_MIRROR,
  45. ): TuiWorkflowMirror {
  46. let mirror = initial;
  47. for (const event of events) mirror = applyWorkflowProgressToMirror(mirror, event);
  48. return mirror;
  49. }
  50. function startedMirror(): TuiWorkflowMirror {
  51. sequence = -1;
  52. return mirrorAfter([progress("run-started", { runId: RUN_ID, caps: { maxConcurrency: 4 } })]);
  53. }
  54. // ── 镜像:共享 reducer 驱动 + React 引用回传 ──
  55. test("progress events drive the mirror through the shared reducer", () => {
  56. const dispatched = mirrorAfter(
  57. [
  58. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 }, name: "planner" }),
  59. progress("node-queued", {
  60. instance: { siteId: "ask#1", ordinal: 1 },
  61. kind: "ask",
  62. actor: { siteId: "actor#1", ordinal: 1 },
  63. }),
  64. progress("node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } }),
  65. ],
  66. startedMirror(),
  67. );
  68. const run = dispatched.state.runs[0];
  69. assert.equal(run?.runId, RUN_ID);
  70. assert.equal(run?.status, "running");
  71. // actor 状态是派生的,由共享 reducer 按决策 39 算出,TUI 不重推导
  72. // (docs/dynamic-workflow/concurrency.md):dispatched 只是「会话就绪、首个请求尚未
  73. // 准入」,算 waiting;要到 node-executing(模型请求已发出)才是 running。
  74. assert.equal(run?.actors[0]?.status, "waiting");
  75. assert.deepEqual(workflowRunStepCounts(run!), { nodesSettled: 0, nodesTotal: 1 });
  76. const executing = mirrorAfter(
  77. [progress("node-executing", { instance: { siteId: "ask#1", ordinal: 1 } })],
  78. dispatched,
  79. );
  80. assert.equal(executing.state.runs[0]?.actors[0]?.status, "running");
  81. });
  82. // 步数读法只有一处(@zcode/shared 的 workflowRunStepCounts)。镜像此前自己数 nodes,于是一条
  83. // 撞过节点界的 run 在 TUI 卡、run 卡与时间线摘要上显示三个数字,而且三个都比真实步数小。
  84. test("step counts include the instances the node cap kept out of the list", () => {
  85. const rejected = 3;
  86. const events = [progress("run-started", { runId: RUN_ID, caps: { maxConcurrency: 4 } })];
  87. for (let ordinal = 1; ordinal <= WORKFLOW_RUNS_LIMITS.maxNodes + rejected; ordinal += 1) {
  88. events.push(progress("node-queued", { instance: { siteId: "ask#1", ordinal }, kind: "ask" }));
  89. }
  90. events.push(
  91. progress("node-settled", {
  92. instance: { siteId: "ask#1", ordinal: WORKFLOW_RUNS_LIMITS.maxNodes + 1 },
  93. outcome: "ok",
  94. }),
  95. );
  96. sequence = -1;
  97. const run = mirrorAfter(events).state.runs[0]!;
  98. assert.equal(run.nodes.length, WORKFLOW_RUNS_LIMITS.maxNodes);
  99. assert.equal(run.truncated, true);
  100. assert.deepEqual(workflowRunStepCounts(run), {
  101. nodesSettled: 1,
  102. nodesTotal: WORKFLOW_RUNS_LIMITS.maxNodes + rejected,
  103. });
  104. // 卡片读的是同一个函数,所以两处不可能再各说各话。
  105. const card = buildTuiWorkflowCardIndex({
  106. ...EMPTY_TUI_WORKFLOW_MIRROR,
  107. state: { revision: 1, runs: [run] },
  108. }).get(TOOL_CALL_ID);
  109. assert.equal(card?.nodesTotal, WORKFLOW_RUNS_LIMITS.maxNodes + rejected);
  110. assert.equal(card?.nodesSettled, 1);
  111. });
  112. test("an unchanged event returns the identical mirror reference so React skips the repaint", () => {
  113. const mirror = startedMirror();
  114. const settle = progress("node-settled", {
  115. instance: { siteId: "ask#1", ordinal: 1 },
  116. outcome: "ok",
  117. });
  118. const advanced = applyWorkflowProgressToMirror(mirror, settle);
  119. assert.notEqual(advanced, mirror);
  120. // 同一条事件立刻重放:共享 reducer 回 null,镜像回传同一个引用。
  121. assert.equal(applyWorkflowProgressToMirror(advanced, settle), advanced);
  122. });
  123. test("an invalid envelope never allocates a new mirror", () => {
  124. const mirror = startedMirror();
  125. assert.equal(applyWorkflowProgressToMirror(mirror, { eventType: "run-started" }), mirror);
  126. assert.equal(applyWorkflowProgressToMirror(mirror, { runId: RUN_ID }), mirror);
  127. });
  128. test("log events stay out of the protocol state but land in the bounded TUI log tail", () => {
  129. const mirror = mirrorAfter(
  130. [progress("log", { message: " step one\n" }), progress("log", { message: "step two" })],
  131. startedMirror(),
  132. );
  133. // log 不进图:没有 site id,节点/actor 表不动。
  134. assert.deepEqual(mirror.state.runs[0]?.nodes, []);
  135. assert.deepEqual(mirror.logTailByRunId[RUN_ID], ["step one", "step two"]);
  136. });
  137. test("the log tail is bounded and keeps the newest entries", () => {
  138. let mirror = startedMirror();
  139. for (let index = 0; index < 20; index += 1) {
  140. mirror = applyWorkflowProgressToMirror(mirror, progress("log", { message: `line ${index}` }));
  141. }
  142. const tail = mirror.logTailByRunId[RUN_ID] ?? [];
  143. assert.equal(tail.length, 10);
  144. assert.equal(tail.at(-1), "line 19");
  145. assert.equal(tail[0], "line 10");
  146. });
  147. test("a log event with no usable message stays out of the tail but still raises the水位", () => {
  148. // 一条有效事件哪怕内容不可用也会抬 lastEventSequence(共享 reducer 的既有裁定:
  149. // 事件日志需要知道有新内容可取)。所以这里能断言的是**日志尾不动**,不是整个镜像不动。
  150. const mirror = startedMirror();
  151. const before = mirror.state.runs[0]?.lastEventSequence ?? 0;
  152. for (const payload of [{ message: " " }, {}]) {
  153. const next = applyWorkflowProgressToMirror(mirror, progress("log", payload));
  154. assert.equal(next.logTailByRunId[RUN_ID], undefined, "empty log entered the tail");
  155. assert.ok(
  156. (next.state.runs[0]?.lastEventSequence ?? 0) > before,
  157. "lastEventSequence should still rise",
  158. );
  159. }
  160. });
  161. // ── join:按 toolCallId(运行态只来自镜像状态;补种只给展示名)──
  162. test("the card index joins by toolCallId and carries settled/observed step counts", () => {
  163. const mirror = mirrorAfter(
  164. [
  165. progress("node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" }),
  166. progress("node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" }),
  167. progress("node-queued", { instance: { siteId: "ask#2", ordinal: 1 }, kind: "ask" }),
  168. ],
  169. startedMirror(),
  170. );
  171. const card = buildTuiWorkflowCardIndex(mirror).get(TOOL_CALL_ID);
  172. assert.equal(card?.runId, RUN_ID);
  173. assert.equal(card?.nodesSettled, 1);
  174. // 分母是**已排程**节点数,不是冒充的全程总数。
  175. assert.equal(card?.nodesTotal, 2);
  176. });
  177. test("a run with no toolCallId has no card to join", () => {
  178. const mirror = applyWorkflowProgressToMirror(EMPTY_TUI_WORKFLOW_MIRROR, {
  179. runId: "dwfrun-orphan",
  180. sequence: 0,
  181. eventType: "run-started",
  182. payload: { caps: { maxConcurrency: 1 } },
  183. });
  184. assert.equal(buildTuiWorkflowCardIndex(mirror).size, 0);
  185. });
  186. test("cold replay drives the mirror through the shared reducer; seeding only adds the label", () => {
  187. // docs/dynamic-workflow/presentation.md:运行态只从回放来(journal 的真实有序事件),
  188. // 摘要只补展示名。回放出的 run 与 live 归约同形:步数、用量、actor、resumable 一个不少。
  189. sequence = -1;
  190. const replayed = mirrorAfter(
  191. [
  192. progress("run-started", { runId: RUN_ID, caps: { maxConcurrency: 4 } }),
  193. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 }, name: "planner" }),
  194. progress("node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" }),
  195. progress("node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" }),
  196. progress("usage-updated", { spentTokens: 4200 }),
  197. progress("run-settled", { status: "stopped", stopReason: "user", resumable: true }),
  198. ],
  199. EMPTY_TUI_WORKFLOW_MIRROR,
  200. );
  201. const seeded = seedWorkflowMirror(replayed, [
  202. { runId: RUN_ID, label: "cold run" },
  203. // 镜像里没有的 run:摘要不会为它造一张卡。
  204. { runId: "dwfrun-unknown", label: "ghost" },
  205. ]);
  206. const index = buildTuiWorkflowCardIndex(seeded);
  207. assert.equal(index.size, 1);
  208. const card = index.get(TOOL_CALL_ID);
  209. assert.equal(card?.status, "stopped");
  210. assert.equal(card?.stopReason, "user");
  211. assert.equal(card?.label, "cold run");
  212. assert.equal(card?.resumable, true);
  213. assert.deepEqual(
  214. { settled: card?.nodesSettled, total: card?.nodesTotal },
  215. { settled: 1, total: 1 },
  216. );
  217. assert.equal(card?.usage?.spentTokens, 4200);
  218. assert.equal(card?.actors.length, 1);
  219. });
  220. test("seeding the same summaries twice returns the identical reference", () => {
  221. const seeds = [{ runId: "dwfrun-cold", label: "cold" }];
  222. const once = seedWorkflowMirror(EMPTY_TUI_WORKFLOW_MIRROR, seeds);
  223. assert.notEqual(once, EMPTY_TUI_WORKFLOW_MIRROR);
  224. assert.equal(seedWorkflowMirror(once, seeds), once);
  225. assert.equal(seedWorkflowMirror(once, []), once);
  226. });
  227. test("resumable is rendered from the state bit and never re-derived from status", () => {
  228. sequence = -1;
  229. const withoutBit = mirrorAfter([
  230. progress("run-started", { runId: RUN_ID, caps: { maxConcurrency: 4 } }),
  231. progress("run-settled", { status: "stopped" }),
  232. ]);
  233. // stopped 却没带状态位(旧 CLI):不当成可恢复。
  234. assert.equal(buildTuiWorkflowCardIndex(withoutBit).get(TOOL_CALL_ID)?.resumable, undefined);
  235. });
  236. test("interrupted notices come from the server boolean and preserve the server's order", () => {
  237. // 端口注释明确:updatedAt 只供展示,读侧拿它重排会与服务端的 tie-break 漂移。服务端按
  238. // 「最近更新在前」给序,这里必须原样保留——先来的 newer 就该排在 older 之前。
  239. const notices = interruptedWorkflowNotices([
  240. { runId: "newer", status: "stopped", resumable: true, updatedAt: 900, label: "N" },
  241. { runId: "older", status: "stopped", resumable: true, updatedAt: 100 },
  242. { runId: "plain", status: "errored", resumable: false, updatedAt: 500 },
  243. { runId: "done", status: "completed", updatedAt: 700 },
  244. ]);
  245. assert.deepEqual(
  246. notices.map((seed) => seed.runId),
  247. ["newer", "older"],
  248. );
  249. assert.equal(notices[0]?.label, "N");
  250. });
  251. // ── 事件开关:progress 事件不再落进 default ──
  252. function sessionEvent(payload: unknown): SessionEvent {
  253. return {
  254. id: `evt-${(sequence += 1)}`,
  255. sessionId: "session-1",
  256. type: SessionEventType.DynamicWorkflowRunProgress,
  257. timestamp: new Date(0),
  258. traceId: "trace-1",
  259. sequenceNumber: sequence,
  260. payload,
  261. } as SessionEvent;
  262. }
  263. test("applySessionEventToState routes dwf progress into the mirror", () => {
  264. let mirror = EMPTY_TUI_WORKFLOW_MIRROR;
  265. const handlers = {
  266. setActiveTurnId: () => {},
  267. setCacheStats: () => {},
  268. setContextUsage: () => {},
  269. setLastError: () => {},
  270. setLiveModelText: () => {},
  271. setMessages: () => {},
  272. setModel: () => {},
  273. setNetworkRequests: () => {},
  274. setStatus: () => {},
  275. setTodos: () => {},
  276. setUsage: () => {},
  277. setWorkflowMirror: (update: unknown) => {
  278. mirror =
  279. typeof update === "function"
  280. ? (update as (m: TuiWorkflowMirror) => TuiWorkflowMirror)(mirror)
  281. : (update as TuiWorkflowMirror);
  282. },
  283. assistantMessageIdsByToolCallId: new Map<string, string>(),
  284. toolNamesById: new Map<string, string>(),
  285. } as unknown as Parameters<typeof applySessionEventToState>[1];
  286. applySessionEventToState(
  287. sessionEvent({
  288. runId: RUN_ID,
  289. toolCallId: TOOL_CALL_ID,
  290. sequence: 0,
  291. eventType: "run-started",
  292. payload: { caps: { maxConcurrency: 2 } },
  293. }),
  294. handlers,
  295. COPY,
  296. );
  297. assert.equal(mirror.state.runs[0]?.runId, RUN_ID);
  298. assert.equal(mirror.state.runs[0]?.status, "running");
  299. });
  300. // ── 去重:常驻订阅与 per-turn sink 绝不双投 ──
  301. test("events built by the real contracts factory always carry a dedup key", () => {
  302. // 去重的全部依据是 SessionEvent.id。这条用例故意走**真实**的 createSessionEvent,
  303. // 而不是本文件的手写 fixture:如果哪天有人加了一条不铸 id 的事件构造路径,
  304. // 「缺 id 就放行」会静默退化成「双份渲染」(流式增量双投会当场把可见文本写坏)。
  305. // 结构性保证有两层:createSessionEvent 无条件铸 id,且 SessionEvent.id 是必填字段。
  306. const applied = new Set<string>();
  307. for (const type of [
  308. SessionEventType.ModelStreaming,
  309. SessionEventType.AssistantMessage,
  310. SessionEventType.ToolCallScheduled,
  311. SessionEventType.ToolCallResult,
  312. SessionEventType.TurnComplete,
  313. SessionEventType.DynamicWorkflowRunProgress,
  314. ]) {
  315. const event = createSessionEvent(type, "session-1" as never, {});
  316. assert.ok(event.id, `${type} must carry an id`);
  317. // 第一次投递应用,第二个 sink 的同一条被丢弃。
  318. assert.equal(rememberSessionEvent(applied, event), true);
  319. assert.equal(rememberSessionEvent(applied, event), false);
  320. }
  321. });
  322. test("events with no id are always applied rather than silently swallowed", () => {
  323. const applied = new Set<string>();
  324. const anonymous = { ...sessionEvent({}), id: "" } as SessionEvent;
  325. assert.equal(rememberSessionEvent(applied, anonymous), true);
  326. assert.equal(rememberSessionEvent(applied, anonymous), true);
  327. });
  328. test("the dedup window is bounded", () => {
  329. const applied = new Set<string>();
  330. for (let index = 0; index < 3_000; index += 1) {
  331. rememberSessionEvent(applied, { ...sessionEvent({}), id: `bulk-${index}` } as SessionEvent);
  332. }
  333. assert.ok(applied.size <= 2_048, `window grew to ${applied.size}`);
  334. });
  335. // ── 卡片渲染 ──
  336. function renderCardText(element: React.ReactElement): string[] {
  337. const lines: string[] = [];
  338. const visit = (node: unknown): void => {
  339. if (node === null || node === undefined || typeof node === "boolean") return;
  340. if (typeof node === "string" || typeof node === "number") {
  341. lines.push(String(node));
  342. return;
  343. }
  344. if (Array.isArray(node)) {
  345. for (const child of node) visit(child);
  346. return;
  347. }
  348. const element = node as { props?: { children?: unknown } };
  349. if (element.props?.children !== undefined) visit(element.props.children);
  350. };
  351. visit(element);
  352. return lines;
  353. }
  354. test("the collapsed card line shows label, run status and settled/observed steps", () => {
  355. const mirror = mirrorAfter(
  356. [
  357. progress("node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" }),
  358. progress("node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" }),
  359. ],
  360. startedMirror(),
  361. );
  362. const card = buildTuiWorkflowCardIndex(
  363. seedWorkflowMirror(mirror, [{ runId: RUN_ID, label: "lean-loop" }]),
  364. ).get(TOOL_CALL_ID)!;
  365. const collapsed = renderCardText(WorkflowRunCardView({ card, copy: COPY })).join("\n");
  366. assert.match(collapsed, /lean-loop/u);
  367. assert.match(collapsed, /running/u);
  368. assert.match(collapsed, /1\/1 steps/u);
  369. assert.match(collapsed, /\+ to expand/u);
  370. // 折叠态不泄漏展开详情。
  371. assert.doesNotMatch(collapsed, /budget/u);
  372. });
  373. test("the card falls back to the runId when the server has not supplied a label", () => {
  374. const card = buildTuiWorkflowCardIndex(startedMirror()).get(TOOL_CALL_ID)!;
  375. const collapsed = renderCardText(WorkflowRunCardView({ card, copy: COPY })).join("\n");
  376. assert.match(collapsed, new RegExp(RUN_ID, "u"));
  377. });
  378. test("the expanded card shows usage, actors, log tail and result", () => {
  379. const mirror = mirrorAfter(
  380. [
  381. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 }, name: "planner" }),
  382. // usage-updated 直接携带已花总量(docs/dynamic-workflow/authoring.md),没有派生字段。
  383. progress("usage-updated", { spentTokens: 1_234 }),
  384. progress("log", { message: "compiling proof" }),
  385. ],
  386. startedMirror(),
  387. );
  388. const card = buildTuiWorkflowCardIndex(mirror).get(TOOL_CALL_ID)!;
  389. const expanded = renderCardText(WorkflowRunCardView({ card, copy: COPY, expanded: true })).join(
  390. "\n",
  391. );
  392. assert.match(expanded, /usage: 1234 tokens/u);
  393. assert.doesNotMatch(expanded, /budget/u);
  394. assert.match(expanded, /planner/u);
  395. assert.match(expanded, /compiling proof/u);
  396. assert.match(expanded, /- to collapse/u);
  397. });
  398. // ── 六行位置的挑选:跑着的优先(docs/dynamic-workflow/launch.md「The inline card」)──
  399. function actorFixture(
  400. name: string,
  401. status: "running" | "waiting" | "completed",
  402. ): { siteId: string; ordinal: number; name: string; status: "running" | "waiting" | "completed" } {
  403. return { siteId: `site-${name}`, ordinal: 1, name, status };
  404. }
  405. test("the six actor rows go running, then waiting, then completed, stable within a bucket", () => {
  406. const rows = actorRowsForCard([
  407. actorFixture("done-1", "completed"),
  408. actorFixture("wait-1", "waiting"),
  409. actorFixture("done-2", "completed"),
  410. actorFixture("run-1", "running"),
  411. actorFixture("wait-2", "waiting"),
  412. actorFixture("done-3", "completed"),
  413. actorFixture("run-2", "running"),
  414. actorFixture("wait-3", "waiting"),
  415. ]);
  416. assert.equal(rows.length, MAX_ACTOR_ROWS);
  417. // 桶内保持协议顺序:run-1 在 run-2 之前,wait-1..3 原序。
  418. assert.deepEqual(
  419. rows.map((actor) => actor.name),
  420. ["run-1", "run-2", "wait-1", "wait-2", "wait-3", "done-1"],
  421. );
  422. });
  423. test("a card that fits every subagent still leads with the running ones", () => {
  424. const rows = actorRowsForCard(
  425. [
  426. actorFixture("done-1", "completed"),
  427. actorFixture("run-1", "running"),
  428. actorFixture("wait-1", "waiting"),
  429. ],
  430. MAX_ACTOR_ROWS,
  431. );
  432. assert.deepEqual(
  433. rows.map((actor) => actor.name),
  434. ["run-1", "wait-1", "done-1"],
  435. );
  436. });
  437. test("a wide run's expanded card shows the agent that is running, not the six that finished", () => {
  438. sequence = -1;
  439. const events: Record<string, unknown>[] = [
  440. progress("run-started", { runId: RUN_ID, caps: { maxConcurrency: 8 } }),
  441. ];
  442. const total = MAX_ACTOR_ROWS + 1;
  443. for (let index = 1; index <= total; index += 1) {
  444. const actor = { siteId: `actor#${index}`, ordinal: 1 };
  445. const instance = { siteId: `ask#${index}`, ordinal: 1 };
  446. events.push(progress("actor-created", { actor, name: `planner-${index}` }));
  447. events.push(progress("node-queued", { instance, kind: "ask", actor }));
  448. // 最后一个还在跑,前六个都已结算——协议顺序下它恰好被挤出六行之外。
  449. events.push(
  450. index === total
  451. ? progress("node-executing", { instance })
  452. : progress("node-settled", { instance, outcome: "ok" }),
  453. );
  454. }
  455. const card = buildTuiWorkflowCardIndex(mirrorAfter(events)).get(TOOL_CALL_ID)!;
  456. assert.equal(card.actors.length, total);
  457. const expanded = renderCardText(WorkflowRunCardView({ card, copy: COPY, expanded: true }));
  458. const rows = expanded.filter((line) => /planner-/u.test(line));
  459. assert.equal(rows.length, MAX_ACTOR_ROWS);
  460. assert.match(rows[0]!, /planner-7/u);
  461. assert.match(rows[0]!, /running/u);
  462. // 被挤出去的是最后一个已完成的,不是那个还在跑的。
  463. assert.ok(
  464. rows.every((line) => !/planner-6/u.test(line)),
  465. "a completed agent should be the one dropped",
  466. );
  467. });
  468. test("the expanded card surfaces the settlement error", () => {
  469. const mirror = mirrorAfter(
  470. [progress("run-settled", { status: "errored", error: { message: "node cap exhausted" } })],
  471. startedMirror(),
  472. );
  473. const card = buildTuiWorkflowCardIndex(mirror).get(TOOL_CALL_ID)!;
  474. const expanded = renderCardText(WorkflowRunCardView({ card, copy: COPY, expanded: true })).join(
  475. "\n",
  476. );
  477. assert.match(expanded, /node cap exhausted/u);
  478. assert.match(renderCardText(WorkflowRunCardView({ card, copy: COPY })).join("\n"), /errored/u);
  479. });
  480. test("a stopped run renders the stop reason next to the status word", () => {
  481. const mirror = mirrorAfter(
  482. [progress("run-settled", { status: "stopped", stopReason: "provider", resumable: true })],
  483. startedMirror(),
  484. );
  485. const card = buildTuiWorkflowCardIndex(mirror).get(TOOL_CALL_ID)!;
  486. assert.equal(card.stopReason, "provider");
  487. assert.match(
  488. renderCardText(WorkflowRunCardView({ card, copy: COPY })).join("\n"),
  489. /stopped \(model error\)/u,
  490. );
  491. });
  492. test("a replayed stopped run renders its real facts after a cold start", () => {
  493. sequence = -1;
  494. const mirror = seedWorkflowMirror(
  495. mirrorAfter([
  496. progress("run-started", { runId: RUN_ID, caps: { maxConcurrency: 4 } }),
  497. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 }, name: "planner" }),
  498. progress("run-settled", { status: "stopped", resumable: true }),
  499. ]),
  500. [{ runId: RUN_ID, label: "cold" }],
  501. );
  502. const card = buildTuiWorkflowCardIndex(mirror).get(TOOL_CALL_ID)!;
  503. const expanded = renderCardText(WorkflowRunCardView({ card, copy: COPY, expanded: true })).join(
  504. "\n",
  505. );
  506. assert.match(expanded, /cold/u);
  507. assert.match(expanded, /stopped/u);
  508. // 回放带回了真实的 actor,不再是空壳。
  509. assert.match(expanded, /planner/u);
  510. });
  511. test("both locales render the card without leaking raw copy keys", () => {
  512. const card = buildTuiWorkflowCardIndex(startedMirror()).get(TOOL_CALL_ID)!;
  513. for (const locale of ["en-US", "zh-CN"] as const) {
  514. const copy = getZCodeCopy(locale).tui;
  515. const text = renderCardText(WorkflowRunCardView({ card, copy, expanded: true })).join("\n");
  516. assert.ok(text.length > 0, `${locale} rendered nothing`);
  517. assert.doesNotMatch(text, /undefined/u, `${locale} leaked undefined`);
  518. assert.doesNotMatch(text, /\[object Object\]/u, `${locale} leaked an object`);
  519. }
  520. });
  521. // ── 冷补种 → notice 行(启动 / /resume 后)──
  522. test("summaries map to seeds carrying only display facts, never runtime state", () => {
  523. const seed = workflowRunSeedFromSummary({ runId: "dwfrun-1", status: "running" });
  524. assert.deepEqual(seed, { runId: "dwfrun-1" });
  525. // label / updatedAt 缺席就该缺席,不造默认值;status / resumable 是运行态,走回放,不进补种。
  526. const full = workflowRunSeedFromSummary({
  527. runId: "dwfrun-2",
  528. toolCallId: "tc-2",
  529. status: "stopped",
  530. label: "lean-loop",
  531. resumable: true,
  532. updatedAt: 1_700_000_000_000,
  533. });
  534. assert.deepEqual(full, { runId: "dwfrun-2", label: "lean-loop", updatedAt: 1_700_000_000_000 });
  535. });
  536. test("notice lines carry the label and the /dwf resume hint", () => {
  537. const text = workflowInterruptedNoticeText({ runId: "dwfrun-1", label: "lean-loop" }, COPY);
  538. assert.match(text, /lean-loop/u);
  539. assert.match(text, /\/dwf resume dwfrun-1/u);
  540. });
  541. test("a notice falls back to the runId when the server sent no label", () => {
  542. const text = workflowInterruptedNoticeText({ runId: "dwfrun-9" }, COPY);
  543. assert.match(text, /dwfrun-9/u);
  544. assert.doesNotMatch(text, /undefined/u);
  545. });
  546. test("notices append as system rows, never as fabricated user rows", () => {
  547. const messages = appendWorkflowInterruptedNotices([], [{ runId: "dwfrun-1", label: "A" }], COPY);
  548. assert.equal(messages.length, 1);
  549. // 这不是用户说的话:system 行,不伪造 user 行(与不渲染 model-only 合成 user 行同一裁定)。
  550. assert.equal(messages[0]?.role, "system");
  551. });
  552. test("no resumable runs means zero notice output", () => {
  553. const before: never[] = [];
  554. assert.equal(appendWorkflowInterruptedNotices(before, [], COPY), before);
  555. });
  556. test("both locales render a notice without leaking raw keys", () => {
  557. for (const locale of ["en-US", "zh-CN"] as const) {
  558. const text = workflowInterruptedNoticeText(
  559. { runId: "dwfrun-1", label: "L" },
  560. getZCodeCopy(locale).tui,
  561. );
  562. assert.ok(text.length > 0);
  563. assert.doesNotMatch(text, /undefined|\[object Object\]/u);
  564. assert.match(text, /\/dwf resume/u);
  565. }
  566. });