tui-workflow-card.test.ts 25 KB

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