headless-workflow.test.ts 30 KB

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