headless-workflow.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. import assert from "node:assert/strict";
  2. import test from "node:test";
  3. import {
  4. SessionEventType,
  5. type DynamicWorkflowRunProgressPayload,
  6. type SessionEvent,
  7. } from "@zcode/contracts";
  8. import type { RunContext } from "@zcode/shared-types";
  9. import { zcodeSessionEventTypeSchema } from "@zcode/shared";
  10. import { run } from "../src/run.js";
  11. import type { RunDependencies } from "../src/run.js";
  12. import {
  13. WORKFLOW_RUN_PROGRESS_STREAM_TYPE,
  14. createHeadlessPermissionBroker,
  15. createWorkflowProgressReporter,
  16. isDynamicWorkflowRunProgressEvent,
  17. mapWorkflowRunProgressStreamLine,
  18. waitForHeadlessWorkflowSettle,
  19. } from "../src/headless-workflow.js";
  20. const progressEvent = (
  21. payload: Partial<DynamicWorkflowRunProgressPayload> & { eventType: string },
  22. envelope: Partial<SessionEvent> = {},
  23. ): SessionEvent =>
  24. ({
  25. id: "evt-dwf-1",
  26. sessionId: "session-test",
  27. traceId: "trace-test",
  28. type: SessionEventType.DynamicWorkflowRunProgress,
  29. timestamp: new Date(1_700_000_000_000),
  30. sequenceNumber: 7,
  31. payload: {
  32. runId: "dwfrun-abc",
  33. sequence: 3,
  34. payload: {},
  35. ...payload,
  36. },
  37. ...envelope,
  38. }) as SessionEvent;
  39. const permissionRequest = (toolName: string) =>
  40. ({
  41. requestId: "perm_1",
  42. sessionId: "session-test",
  43. traceId: "trace-test",
  44. toolCallId: "call-1",
  45. toolName,
  46. input: {},
  47. mode: "build",
  48. ruleId: "tool.alwaysAsk",
  49. reason: `Tool ${toolName} always requires explicit approval`,
  50. riskLevel: "low",
  51. requestedAt: new Date(),
  52. }) as never;
  53. // —————————————————————————————————————————————————————————————
  54. // 审批旁路(headless broker)
  55. // —————————————————————————————————————————————————————————————
  56. test("headless broker allows CreateWorkflow", async () => {
  57. const broker = createHeadlessPermissionBroker();
  58. const result = await broker.requestPermission(permissionRequest("CreateWorkflow"));
  59. assert.equal(result.decision, "allow");
  60. });
  61. test("headless broker leaves every other tool at today's deny semantics", async () => {
  62. // 回归钉:旁路必须是按工具名的一个洞,不是一把开关。文案也钉住——它来自 core 的
  63. // deny broker,旁路只委托、不复写,所以这里的断言同时证明"没有第二份文案"。
  64. const broker = createHeadlessPermissionBroker();
  65. for (const toolName of ["Bash", "Write", "Edit", "Agent", "Workflow"]) {
  66. const result = await broker.requestPermission(permissionRequest(toolName));
  67. assert.equal(result.decision, "deny", `${toolName} must stay denied`);
  68. assert.match(result.reason ?? "", /No permission client configured for/);
  69. assert.match(result.reason ?? "", new RegExp(toolName));
  70. }
  71. });
  72. // —————————————————————————————————————————————————————————————
  73. // stream-json 定型行
  74. // —————————————————————————————————————————————————————————————
  75. test("dwf progress events are recognised, other session events are not", () => {
  76. assert.equal(
  77. isDynamicWorkflowRunProgressEvent(progressEvent({ eventType: "run-started" })),
  78. true,
  79. );
  80. assert.equal(
  81. isDynamicWorkflowRunProgressEvent(
  82. progressEvent({ eventType: "run-started" }, { type: SessionEventType.AssistantMessage }),
  83. ),
  84. false,
  85. );
  86. });
  87. test("the CLI-private stream type stays out of the v3 protocol enum", () => {
  88. // 绊线:定型行的 type 刻意不是 zcodeSessionEventTypeSchema 的成员。那个 enum 是闭集
  89. // 且喂给 zcodeSessionEventSchema 的 discriminated union,加值等于让 v3 app-server 在
  90. // 类型面上宣告一个它永不发出的事件(协议路径在 mapSessionEventForProtocol 里就已经
  91. // 把这个事件剥掉了)。谁把映射搬进协议枚举,这条先红。
  92. assert.equal(
  93. zcodeSessionEventTypeSchema.options.includes(WORKFLOW_RUN_PROGRESS_STREAM_TYPE as never),
  94. false,
  95. );
  96. });
  97. test("the typed stream-json line carries its own type and the bounded payload verbatim", () => {
  98. const event = progressEvent({
  99. eventType: "node-settled",
  100. runId: "dwfrun-abc",
  101. sequence: 12,
  102. toolCallId: "call-42",
  103. payload: { instance: { siteId: "ask#1", ordinal: 2 }, outcome: "ok" },
  104. truncated: true,
  105. });
  106. const line = mapWorkflowRunProgressStreamLine(event);
  107. // 定型:独立 type,不是 catch-all session.updated。
  108. assert.equal(line.type, WORKFLOW_RUN_PROGRESS_STREAM_TYPE);
  109. assert.notEqual(line.type as string, "session.updated");
  110. // 信封与 mapSessionEvent 对齐(同样的 String()/getTime() 规范化)。
  111. assert.equal(line.eventId, "evt-dwf-1");
  112. assert.equal(line.sessionId, "session-test");
  113. assert.equal(line.traceId, "trace-test");
  114. assert.equal(line.seq, 7);
  115. assert.equal(line.timestamp, 1_700_000_000_000);
  116. // dwf 事件是出回合的,信封里没有 turnId 键(不是 undefined 值)。
  117. assert.equal("turnId" in line, false);
  118. // payload 原样:不重塑字段名,读端按 eventType 解释。
  119. assert.deepEqual(line.payload, {
  120. runId: "dwfrun-abc",
  121. sequence: 12,
  122. toolCallId: "call-42",
  123. eventType: "node-settled",
  124. payload: { instance: { siteId: "ask#1", ordinal: 2 }, outcome: "ok" },
  125. truncated: true,
  126. });
  127. // 一行 NDJSON 必须能独立 parse。
  128. assert.doesNotThrow(() => JSON.parse(JSON.stringify(line)));
  129. });
  130. // —————————————————————————————————————————————————————————————
  131. // text 模式的 stderr 进度
  132. // —————————————————————————————————————————————————————————————
  133. const collectProgress = (
  134. events: readonly SessionEvent[],
  135. options: { throttleMs?: number; clock?: number[] } = {},
  136. ): string[] => {
  137. const lines: string[] = [];
  138. const clock = options.clock ? [...options.clock] : undefined;
  139. let fallbackNow = 0;
  140. const reporter = createWorkflowProgressReporter({
  141. now: () => (clock ? (clock.shift() ?? 0) : fallbackNow++),
  142. ...(options.throttleMs === undefined ? {} : { throttleMs: options.throttleMs }),
  143. write: (line) => lines.push(line),
  144. });
  145. for (const event of events) reporter(event);
  146. return lines;
  147. };
  148. test("run lifecycle and log lines are never throttled away", () => {
  149. const lines = collectProgress(
  150. [
  151. progressEvent({ eventType: "run-started" }),
  152. progressEvent({ eventType: "log", payload: { message: "compiled" } }),
  153. progressEvent({ eventType: "log", payload: { message: "asking reviewer" } }),
  154. progressEvent({ eventType: "run-settled", payload: { status: "completed" } }),
  155. ],
  156. // 时钟不动:任何按时间的节流都会在这里吃掉后三条——这正是这条用例要挡住的退步。
  157. { clock: [0, 0, 0, 0] },
  158. );
  159. assert.deepEqual(lines, [
  160. "workflow dwfrun-abc: started\n",
  161. "workflow dwfrun-abc: log: compiled\n",
  162. "workflow dwfrun-abc: log: asking reviewer\n",
  163. "workflow dwfrun-abc: completed\n",
  164. ]);
  165. });
  166. test("a failed settle carries the error message", () => {
  167. const lines = collectProgress([
  168. progressEvent({
  169. eventType: "run-settled",
  170. payload: { status: "errored", error: { code: "DriverError", message: "boom" } },
  171. }),
  172. ]);
  173. assert.deepEqual(lines, ["workflow dwfrun-abc: errored: boom\n"]);
  174. });
  175. test("a stopped settle prints the stop reason next to the status", () => {
  176. const lines = collectProgress([
  177. progressEvent({
  178. eventType: "run-settled",
  179. payload: {
  180. status: "stopped",
  181. stopReason: "provider",
  182. error: { code: "ProviderStop", message: "sign-in expired" },
  183. },
  184. }),
  185. ]);
  186. assert.deepEqual(lines, ["workflow dwfrun-abc: stopped/provider: sign-in expired\n"]);
  187. });
  188. test("node phase transitions are throttled but the first one gets through", () => {
  189. const nodeEvent = (eventType: string, ordinal: number) =>
  190. progressEvent({
  191. eventType,
  192. payload: {
  193. instance: { siteId: "ask#1", ordinal },
  194. ...(eventType === "node-settled" ? { outcome: "ok" } : {}),
  195. },
  196. });
  197. // 节流对**所有**节点相位一视同仁,`node-settled` 也会被吃掉——刻意如此:run 的
  198. // 端点由 run-settled 保证(上面那条用例),节点级的完成不是必达面,否则一个
  199. // 100 节点的 run 在 text 模式下会刷屏。
  200. const lines = collectProgress(
  201. [
  202. nodeEvent("node-queued", 1),
  203. nodeEvent("node-dispatched", 1),
  204. nodeEvent("node-settled", 1),
  205. nodeEvent("node-queued", 2),
  206. ],
  207. { clock: [0, 100, 200, 1_000], throttleMs: 400 },
  208. );
  209. assert.deepEqual(lines, [
  210. "workflow dwfrun-abc: queued ask#1@1\n",
  211. "workflow dwfrun-abc: queued ask#1@2\n",
  212. ]);
  213. });
  214. test("counting-only and non-transition events produce no progress line", () => {
  215. const lines = collectProgress([
  216. progressEvent({ eventType: "usage-updated", payload: { spentTokens: 12 } }),
  217. progressEvent({
  218. eventType: "actor-created",
  219. payload: { actor: { siteId: "actor#1", ordinal: 1 } },
  220. }),
  221. progressEvent({ eventType: "compaction", payload: {} }),
  222. progressEvent({ eventType: "log", payload: {} }),
  223. progressEvent({ eventType: "run-started" }, { type: SessionEventType.AssistantMessage }),
  224. ]);
  225. assert.deepEqual(lines, []);
  226. });
  227. // —————————————————————————————————————————————————————————————
  228. // 经 run() 的端到端接线(headless prompt 路径)
  229. // —————————————————————————————————————————————————————————————
  230. type CapturedWriteStream = NodeJS.WriteStream & { output: () => string };
  231. const createWriteStream = (): CapturedWriteStream => {
  232. let output = "";
  233. return {
  234. output: () => output,
  235. write: (
  236. chunk: string | Uint8Array,
  237. encodingOrCallback?: BufferEncoding | ((err?: Error | null) => void),
  238. callback?: (err?: Error | null) => void,
  239. ): boolean => {
  240. output += typeof chunk === "string" ? chunk : chunk.toString();
  241. (typeof encodingOrCallback === "function" ? encodingOrCallback : callback)?.();
  242. return true;
  243. },
  244. } as CapturedWriteStream;
  245. };
  246. const createContext = (
  247. argv: string[],
  248. ): RunContext & { stderr: CapturedWriteStream; stdout: CapturedWriteStream } => ({
  249. argv,
  250. stderr: createWriteStream(),
  251. stdin: { isTTY: false } as NodeJS.ReadStream,
  252. stdout: createWriteStream(),
  253. });
  254. const turnEvents: readonly SessionEvent[] = [
  255. progressEvent({ eventType: "run-started" }, { id: "evt-1" }),
  256. progressEvent(
  257. {
  258. eventType: "node-settled",
  259. payload: { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" },
  260. },
  261. { id: "evt-2", sequenceNumber: 8 },
  262. ),
  263. {
  264. ...progressEvent({ eventType: "run-started" }),
  265. id: "evt-3",
  266. type: SessionEventType.TurnComplete,
  267. payload: {},
  268. } as SessionEvent,
  269. ];
  270. const createRunDeps = (): RunDependencies & { appOptions: () => unknown } => {
  271. let appOptions: unknown;
  272. return {
  273. appOptions: () => appOptions,
  274. createZCodeApp: (options?: unknown) => {
  275. appOptions = options;
  276. return {
  277. getModel: () => "openai/gpt-test",
  278. getThoughtLevel: () => "medium",
  279. sessionId: "session-test",
  280. traceId: "trace-test",
  281. runtime: {} as never,
  282. submitPrompt: async (
  283. _prompt: unknown,
  284. submitOptions?: { onEvent?: (event: unknown) => void | Promise<void> },
  285. ) => {
  286. for (const event of turnEvents) submitOptions?.onEvent?.(event);
  287. return {
  288. events: turnEvents,
  289. projection: {
  290. contextUsed: 12,
  291. contextWindow: 1000,
  292. status: "idle",
  293. totalTokenCount: 12,
  294. turnCount: 1,
  295. } as never,
  296. response: "the answer",
  297. traceId: "trace-test" as never,
  298. turnId: "turn-test" as never,
  299. };
  300. },
  301. } as never;
  302. },
  303. loadDotenv: () => ({ keys: [], loaded: false }),
  304. // The prompt command now starts the process Provider Registry runtime before it
  305. // creates the app; without this stand-in `run` exits 1 before the broker is built.
  306. startProcessProviderRegistryRuntime: async () =>
  307. ({
  308. dispose: () => {},
  309. runtime: { registryService: {} },
  310. }) as never,
  311. mapSessionEvent: ((event: { id: string; type: string }) => ({
  312. eventId: event.id,
  313. type: event.type,
  314. })) as never,
  315. } as RunDependencies & { appOptions: () => unknown };
  316. };
  317. test("headless app creation installs the CreateWorkflow-only broker", async () => {
  318. const ctx = createContext(["--workflow-mode", "alwaysOn", "--prompt", "hi"]);
  319. const deps = createRunDeps();
  320. assert.equal(await run(ctx, deps), 0);
  321. const broker = (deps.appOptions() as { permissionBroker?: { requestPermission: unknown } })
  322. .permissionBroker;
  323. const allowed = await (
  324. broker as { requestPermission: (r: unknown) => Promise<{ decision: string }> }
  325. ).requestPermission(permissionRequest("CreateWorkflow"));
  326. assert.equal(allowed.decision, "allow");
  327. const denied = await (
  328. broker as { requestPermission: (r: unknown) => Promise<{ decision: string }> }
  329. ).requestPermission(permissionRequest("Bash"));
  330. assert.equal(denied.decision, "deny");
  331. });
  332. test("stream-json emits the typed workflow line and still terminates with the result line", async () => {
  333. const ctx = createContext([
  334. "--workflow-mode",
  335. "alwaysOn",
  336. "--output-format",
  337. "stream-json",
  338. "--prompt",
  339. "hi",
  340. ]);
  341. assert.equal(await run(ctx, createRunDeps()), 0);
  342. const lines = ctx.stdout
  343. .output()
  344. .trim()
  345. .split("\n")
  346. .map((line) => JSON.parse(line) as { type: string; payload?: { eventType?: string } });
  347. const workflowLines = lines.filter((line) => line.type === WORKFLOW_RUN_PROGRESS_STREAM_TYPE);
  348. assert.equal(workflowLines.length, 2);
  349. assert.deepEqual(
  350. workflowLines.map((line) => line.payload?.eventType),
  351. ["run-started", "node-settled"],
  352. );
  353. // 回归钉:这两条今天漏成 catch-all session.updated。
  354. assert.equal(
  355. lines.some((line) => line.type === "session.updated"),
  356. false,
  357. );
  358. // 非 dwf 事件仍走 mapSessionEvent,result 行仍是流的终止符。
  359. assert.equal(lines.at(-2)?.type, "turn_complete");
  360. assert.equal(lines.at(-1)?.type, "result");
  361. });
  362. test("text mode prints workflow progress to stderr and keeps stdout to the answer", async () => {
  363. const ctx = createContext(["--workflow-mode", "alwaysOn", "--prompt", "hi"]);
  364. assert.equal(await run(ctx, createRunDeps()), 0);
  365. assert.equal(ctx.stdout.output(), "the answer\n");
  366. const stderr = ctx.stderr.output();
  367. assert.match(stderr, /^workflow dwfrun-abc: started$/m);
  368. assert.match(stderr, /^workflow dwfrun-abc: settled ask#1@1 \(ok\)$/m);
  369. });
  370. test("json mode stays exactly one object: no progress, no stderr noise", async () => {
  371. const ctx = createContext([
  372. "--workflow-mode",
  373. "alwaysOn",
  374. "--output-format",
  375. "json",
  376. "--prompt",
  377. "hi",
  378. ]);
  379. assert.equal(await run(ctx, createRunDeps()), 0);
  380. assert.doesNotThrow(() => JSON.parse(ctx.stdout.output()));
  381. assert.equal(ctx.stderr.output().includes("workflow dwfrun-abc"), false);
  382. });
  383. test("stream-json does not duplicate progress onto stderr", async () => {
  384. const ctx = createContext([
  385. "--workflow-mode",
  386. "alwaysOn",
  387. "--output-format",
  388. "stream-json",
  389. "--prompt",
  390. "hi",
  391. ]);
  392. assert.equal(await run(ctx, createRunDeps()), 0);
  393. assert.equal(ctx.stderr.output().includes("workflow dwfrun-abc"), false);
  394. });
  395. // —————————————————————————————————————————————————————————————
  396. // 等待结算(在飞 run + 通知驱动回合)
  397. // —————————————————————————————————————————————————————————————
  398. const abortedSignal = (): AbortSignal => {
  399. const controller = new AbortController();
  400. controller.abort();
  401. return controller.signal;
  402. };
  403. test("the wait returns immediately when the runtime reports no work", async () => {
  404. let polls = 0;
  405. await waitForHeadlessWorkflowSettle({
  406. runtime: {
  407. hasActiveOrQueuedTurnWork: () => {
  408. polls += 1;
  409. return false;
  410. },
  411. hasRunningBackgroundTasks: () => false,
  412. },
  413. signal: new AbortController().signal,
  414. sleep: async () => assert.fail("must not sleep when there is nothing to wait for"),
  415. });
  416. assert.equal(polls, 1);
  417. });
  418. test("the wait polls until both busy facts clear", async () => {
  419. // 谓词是"或":后台任务先清空,但通知回合还在队列里,等待必须继续。
  420. // 两个计数器各自独立,因为谓词短路——后台任务为真时根本不问回合工作。
  421. let backgroundCalls = 0;
  422. let turnWorkCalls = 0;
  423. let sleeps = 0;
  424. await waitForHeadlessWorkflowSettle({
  425. runtime: {
  426. hasActiveOrQueuedTurnWork: () => {
  427. turnWorkCalls += 1;
  428. return turnWorkCalls <= 1;
  429. },
  430. hasRunningBackgroundTasks: () => {
  431. backgroundCalls += 1;
  432. return backgroundCalls <= 2;
  433. },
  434. },
  435. signal: new AbortController().signal,
  436. sleep: async () => {
  437. sleeps += 1;
  438. },
  439. });
  440. // 2 轮等后台 + 1 轮等通知回合,第 4 轮两者都清空才退出。
  441. assert.equal(sleeps, 3);
  442. assert.equal(backgroundCalls, 4);
  443. });
  444. test("an already-aborted signal never enters the wait: Ctrl-C is not swallowed", async () => {
  445. await waitForHeadlessWorkflowSettle({
  446. runtime: {
  447. hasActiveOrQueuedTurnWork: () => true,
  448. hasRunningBackgroundTasks: () => true,
  449. },
  450. signal: abortedSignal(),
  451. sleep: async () => assert.fail("an aborted wait must not sleep"),
  452. });
  453. });
  454. test("aborting mid-wait breaks the loop even while the runtime stays busy", async () => {
  455. const controller = new AbortController();
  456. let sleeps = 0;
  457. await waitForHeadlessWorkflowSettle({
  458. runtime: {
  459. hasActiveOrQueuedTurnWork: () => true,
  460. hasRunningBackgroundTasks: () => true,
  461. },
  462. signal: controller.signal,
  463. sleep: async () => {
  464. sleeps += 1;
  465. if (sleeps === 2) controller.abort();
  466. },
  467. });
  468. assert.equal(sleeps, 2);
  469. });
  470. /**
  471. * 一个会「起 dwf run、结算、再由通知驱动一个回合」的 app 替身。
  472. *
  473. * 关键点:`submitPrompt` 把事件**同时**扇给常驻订阅的 sink 与 `options.onEvent`——真实
  474. * runtime 在两者都装上时就是这个行为。于是"恰好一次"这件事在这个装配下是可证的:
  475. * 若 prompt-command 两个都装,每条事件就会出现两行。
  476. */
  477. const createWaitingRunDeps = (
  478. script: {
  479. busyPolls: number;
  480. notificationTurns?: readonly { turnId: string; response: string }[];
  481. } = {
  482. busyPolls: 2,
  483. },
  484. ): RunDependencies & { pollCount: () => number } => {
  485. let remainingBusyPolls = script.busyPolls;
  486. let polls = 0;
  487. const sinks: ((event: SessionEvent) => void)[] = [];
  488. return {
  489. pollCount: () => polls,
  490. createZCodeApp: () =>
  491. ({
  492. getModel: () => "openai/gpt-test",
  493. getThoughtLevel: () => "medium",
  494. sessionId: "session-test",
  495. traceId: "trace-test",
  496. runtime: {
  497. subscribeEvents: (sink: { onSessionEvent: (event: SessionEvent) => void }) => {
  498. sinks.push(sink.onSessionEvent);
  499. return () => {
  500. const at = sinks.indexOf(sink.onSessionEvent);
  501. if (at >= 0) sinks.splice(at, 1);
  502. };
  503. },
  504. hasRunningBackgroundTasks: () => {
  505. polls += 1;
  506. return remainingBusyPolls-- > 0;
  507. },
  508. hasActiveOrQueuedTurnWork: () => false,
  509. } as never,
  510. submitPrompt: async (
  511. _prompt: unknown,
  512. submitOptions?: { onEvent?: (event: SessionEvent) => void | Promise<void> },
  513. ) => {
  514. const emit = (event: SessionEvent) => {
  515. for (const sink of [...sinks]) sink(event);
  516. void submitOptions?.onEvent?.(event);
  517. };
  518. for (const event of turnEvents) emit(event);
  519. // 通知驱动的回合在等待期到达:sleep(100) 之前这个 0ms timer 必然先触发。
  520. setTimeout(() => {
  521. for (const turn of script.notificationTurns ?? []) {
  522. emit({
  523. ...progressEvent({ eventType: "run-settled" }),
  524. id: `evt-${turn.turnId}`,
  525. turnId: turn.turnId as never,
  526. type: SessionEventType.TurnComplete,
  527. payload: { response: turn.response },
  528. } as SessionEvent);
  529. }
  530. }, 0);
  531. return {
  532. events: turnEvents,
  533. projection: {
  534. contextUsed: 12,
  535. contextWindow: 1000,
  536. status: "idle",
  537. totalTokenCount: 12,
  538. turnCount: 1,
  539. } as never,
  540. response: "starting the workflow",
  541. traceId: "trace-test" as never,
  542. turnId: "turn-test" as never,
  543. };
  544. },
  545. }) as never,
  546. loadDotenv: () => ({ keys: [], loaded: false }),
  547. startProcessProviderRegistryRuntime: async () =>
  548. ({
  549. dispose: () => {},
  550. runtime: { registryService: {} },
  551. }) as never,
  552. mapSessionEvent: ((event: { id: string; type: string }) => ({
  553. eventId: event.id,
  554. type: event.type,
  555. })) as never,
  556. } as RunDependencies & { pollCount: () => number };
  557. };
  558. test("text mode waits for settle and prints every turn, ending with the post-settle answer", async () => {
  559. const ctx = createContext(["--workflow-mode", "alwaysOn", "--prompt", "run my workflow"]);
  560. const deps = createWaitingRunDeps({
  561. busyPolls: 2,
  562. notificationTurns: [{ turnId: "turn-notify", response: "the workflow produced 42" }],
  563. });
  564. assert.equal(await run(ctx, deps), 0);
  565. // 等待真的发生了(谓词被轮询过不止一次)。
  566. assert.ok(deps.pollCount() >= 3, `expected repeated polling, got ${deps.pollCount()}`);
  567. // 两个回合按到达序,最后一段是结算后的总结。
  568. assert.equal(ctx.stdout.output(), "starting the workflow\n\nthe workflow produced 42\n");
  569. });
  570. test("json mode reports the last turn as response and every turn in turnResponses", async () => {
  571. const ctx = createContext([
  572. "--workflow-mode",
  573. "alwaysOn",
  574. "--output-format",
  575. "json",
  576. "--prompt",
  577. "run my workflow",
  578. ]);
  579. const deps = createWaitingRunDeps({
  580. busyPolls: 1,
  581. notificationTurns: [{ turnId: "turn-notify", response: "the workflow produced 42" }],
  582. });
  583. assert.equal(await run(ctx, deps), 0);
  584. const parsed = JSON.parse(ctx.stdout.output()) as {
  585. response: string;
  586. turnResponses?: string[];
  587. };
  588. assert.equal(parsed.response, "the workflow produced 42");
  589. assert.deepEqual(parsed.turnResponses, ["starting the workflow", "the workflow produced 42"]);
  590. });
  591. test("a late turn_complete for the first turn is not counted twice", async () => {
  592. // 首个回合的文本来自 submitPrompt 的返回值。它的 turn_complete 若在等待期才到达,
  593. // 必须被 turnId 挡住——否则 response 会退回第一个回合的文本。
  594. const ctx = createContext([
  595. "--workflow-mode",
  596. "alwaysOn",
  597. "--output-format",
  598. "json",
  599. "--prompt",
  600. "run my workflow",
  601. ]);
  602. const deps = createWaitingRunDeps({
  603. busyPolls: 1,
  604. notificationTurns: [
  605. { turnId: "turn-notify", response: "the workflow produced 42" },
  606. { turnId: "turn-test", response: "starting the workflow" },
  607. ],
  608. });
  609. assert.equal(await run(ctx, deps), 0);
  610. const parsed = JSON.parse(ctx.stdout.output()) as { response: string; turnResponses?: string[] };
  611. assert.equal(parsed.response, "the workflow produced 42");
  612. assert.deepEqual(parsed.turnResponses, ["starting the workflow", "the workflow produced 42"]);
  613. });
  614. test("every event reaches stdout exactly once even though both sinks are offered", async () => {
  615. // 这条钉的是重复行:替身把每条事件同时扇给常驻 sink 与 options.onEvent。
  616. // prompt-command 必须二选一——两个都装的话每条事件就是两行。
  617. const ctx = createContext([
  618. "--workflow-mode",
  619. "alwaysOn",
  620. "--output-format",
  621. "stream-json",
  622. "--prompt",
  623. "run my workflow",
  624. ]);
  625. const deps = createWaitingRunDeps({
  626. busyPolls: 1,
  627. notificationTurns: [{ turnId: "turn-notify", response: "the workflow produced 42" }],
  628. });
  629. assert.equal(await run(ctx, deps), 0);
  630. const lines = ctx.stdout
  631. .output()
  632. .trim()
  633. .split("\n")
  634. .map((line) => JSON.parse(line) as { type: string; eventId?: string });
  635. const eventIds = lines.filter((line) => line.eventId !== undefined).map((line) => line.eventId);
  636. assert.deepEqual(
  637. eventIds.length,
  638. new Set(eventIds).size,
  639. `duplicate NDJSON lines for the same event: ${eventIds.join(", ")}`,
  640. );
  641. // 通知回合的事件也在流里(常驻订阅跨回合),且 result 行仍是唯一的终止符。
  642. assert.equal(
  643. lines.some((line) => line.eventId === "evt-turn-notify"),
  644. true,
  645. );
  646. assert.equal(lines.filter((line) => line.type === "result").length, 1);
  647. assert.equal(lines.at(-1)?.type, "result");
  648. });
  649. test("a resolvable custom command waits for settle instead of early-returning", async () => {
  650. // Bug 回归钉:自定义命令解析出来是 type === "unknown",过去因此早退进 command-center,
  651. // 第一个回合结束就退出进程,把在飞的 run 孤儿化成 stopped(interrupted)。现在能解析成真实
  652. // 自定义命令的走普通 prompt 路径,于是等待与"最后一个回合"语义都生效;提交给 app 的是
  653. // 原文(展开由 facade 负责)。示例命令是一个项目自定义命令(`/workflow` 已是内置保留名,见下一条)。
  654. const ctx = createContext([
  655. "--workflow-mode",
  656. "alwaysOn",
  657. "--prompt",
  658. "/launch-plan build me a plan",
  659. ]);
  660. const deps = createWaitingRunDeps({
  661. busyPolls: 2,
  662. notificationTurns: [{ turnId: "turn-notify", response: "the workflow produced 42" }],
  663. });
  664. const loadedNames: string[] = [];
  665. const exitCode = await run(ctx, {
  666. ...deps,
  667. isReservedSlashCommandName: () => false,
  668. loadCustomCommand: async (options) => {
  669. loadedNames.push(options.name);
  670. return {
  671. content: "Run the dynamic workflow: $ARGUMENTS.",
  672. metadata: {
  673. description: "Start a dynamic workflow",
  674. name: "launch-plan",
  675. path: "/workspace/.zcode/commands/launch-plan.md",
  676. scope: "project",
  677. source: "zcode",
  678. },
  679. } as never;
  680. },
  681. });
  682. assert.equal(exitCode, 0);
  683. assert.deepEqual(loadedNames, ["launch-plan"]);
  684. assert.ok(deps.pollCount() >= 3, `expected repeated polling, got ${deps.pollCount()}`);
  685. assert.equal(ctx.stdout.output(), "starting the workflow\n\nthe workflow produced 42\n");
  686. });
  687. test("the builtin /workflow command rides the plain prompt path without a custom command lookup", async () => {
  688. // `/workflow` 现在是 CLI 内置 prompt 命令(bootstrap/src/builtin-workflow-command.ts):
  689. // 解析成 known 且不是 expert/goal,直接进普通 prompt 路径,不再探测自定义命令;原文交给
  690. // facade 展开。dwf 结算等待与"最后一个回合"语义与自定义命令一致。独立 CLI 缺省 disabled
  691. // (launch.md「The standalone CLI: `--workflow-mode`」),所以这里显式开启。
  692. const ctx = createContext([
  693. "--prompt",
  694. "/workflow build me a plan",
  695. "--workflow-mode",
  696. "alwaysOn",
  697. ]);
  698. const deps = createWaitingRunDeps({
  699. busyPolls: 2,
  700. notificationTurns: [{ turnId: "turn-notify", response: "the workflow produced 42" }],
  701. });
  702. const loadedNames: string[] = [];
  703. const exitCode = await run(ctx, {
  704. ...deps,
  705. loadCustomCommand: async (options) => {
  706. loadedNames.push(options.name);
  707. throw new Error(`Custom command not found: ${options.name}`);
  708. },
  709. });
  710. assert.equal(exitCode, 0);
  711. assert.deepEqual(loadedNames, []);
  712. assert.ok(deps.pollCount() >= 3, `expected repeated polling, got ${deps.pollCount()}`);
  713. assert.equal(ctx.stdout.output(), "starting the workflow\n\nthe workflow produced 42\n");
  714. });
  715. test("a run with no workflow activity never polls and stays byte-identical", async () => {
  716. const ctx = createContext(["--prompt", "hi"]);
  717. const deps = createWaitingRunDeps({ busyPolls: 99 });
  718. // 把 dwf 活动从回合事件里摘掉:没有触发证据就绝不进等待。
  719. const quietDeps = {
  720. ...deps,
  721. createZCodeApp: ((options?: unknown) => {
  722. const app = (deps.createZCodeApp as (o?: unknown) => Record<string, unknown>)(options);
  723. return {
  724. ...app,
  725. submitPrompt: async (
  726. _prompt: unknown,
  727. submitOptions?: { onEvent?: (event: SessionEvent) => void },
  728. ) => {
  729. submitOptions?.onEvent?.({
  730. ...progressEvent({ eventType: "run-started" }),
  731. type: SessionEventType.TurnComplete,
  732. payload: { response: "" },
  733. } as SessionEvent);
  734. return {
  735. events: [],
  736. projection: { status: "idle", turnCount: 1, totalTokenCount: 1 } as never,
  737. response: "the answer",
  738. traceId: "trace-test" as never,
  739. turnId: "turn-test" as never,
  740. };
  741. },
  742. };
  743. }) as never,
  744. } as RunDependencies & { pollCount: () => number };
  745. assert.equal(await run(ctx, quietDeps), 0);
  746. assert.equal(ctx.stdout.output(), "the answer\n");
  747. assert.equal(deps.pollCount(), 0);
  748. });