headless-workflow-option.test.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. import assert from "node:assert/strict";
  2. import test from "node:test";
  3. import type { ZCodeAppOptions } from "@zcode/bootstrap";
  4. import type { RunContext } from "@zcode/shared-types";
  5. import { run, type RunDependencies } from "../src/run.js";
  6. import { WORKFLOW_MODE_SCOPE_ERROR } from "../src/workflow-mode.js";
  7. /**
  8. * `--workflow-mode` 在 headless / resume / stdio 各入口上的取值与隔离
  9. * (docs/dynamic-workflow/launch.md「The standalone CLI: `--workflow-mode`」)。
  10. * staging 的布尔 `--enable-workflow` 已由 `--workflow-mode` 取代,这里同时钉住它的退役。
  11. */
  12. function harness(argv: string[]) {
  13. let stdout = "";
  14. let stderr = "";
  15. const appOptions: ZCodeAppOptions[] = [];
  16. let protocolCalls = 0;
  17. const ctx: RunContext = {
  18. argv,
  19. stdin: { isTTY: true } as NodeJS.ReadStream,
  20. stdout: {
  21. isTTY: true,
  22. write: (chunk: string) => {
  23. stdout += chunk;
  24. return true;
  25. },
  26. } as NodeJS.WriteStream,
  27. stderr: {
  28. write: (chunk: string) => {
  29. stderr += chunk;
  30. return true;
  31. },
  32. } as NodeJS.WriteStream,
  33. };
  34. const result = {
  35. response: "done",
  36. events: [],
  37. projection: { status: "idle", turnCount: 1, totalTokenCount: 0 },
  38. traceId: "trace-workflow-option",
  39. turnId: "turn-workflow-option",
  40. };
  41. const deps: RunDependencies = {
  42. skipUserConfig: true,
  43. env: {},
  44. loadDotenv: () => ({ keys: [], loaded: false }),
  45. resolveLatestSession: async () => ({ id: "sess_latest" }) as never,
  46. resolveWorkspaceGitBranch: async () => undefined,
  47. listCustomCommands: async () => ({ commands: [], diagnostics: [] }),
  48. startProcessProviderRegistryRuntime: async () =>
  49. ({ runtime: { registryService: {} }, dispose: () => {} }) as never,
  50. createZCodeApp: (options) => {
  51. appOptions.push(options!);
  52. return {
  53. sessionId: "sess_workflow_option",
  54. traceId: "trace-workflow-option",
  55. runtime: {},
  56. close: async () => {},
  57. getLocale: () => "en-US",
  58. getModel: () => "openai/test",
  59. getThoughtLevel: () => "medium",
  60. getTheme: () => "light",
  61. clearTarget: async () => false,
  62. readTarget: async () => null,
  63. updateTargetStatus: async () => null,
  64. setTarget: async ({ objective }: { objective: string }) => ({
  65. objective,
  66. status: "active",
  67. targetID: "target-workflow-option",
  68. sessionID: "sess_workflow_option",
  69. time: { created: 1, updated: 1 },
  70. }),
  71. continueActiveTarget: async () => result,
  72. submitPrompt: async () => result,
  73. } as never;
  74. },
  75. runTui: async (options) => {
  76. await options.submitPrompt("hello", {
  77. requestPermission: async () => ({ decision: "deny" }),
  78. });
  79. return 0;
  80. },
  81. runZCodeProtocolAgent: async (options) => {
  82. protocolCalls += 1;
  83. // stdio 只接收原有协议入口参数,工作流策略继续由 Host 决定。
  84. assert.equal("dynamicWorkflowEnabled" in options, false);
  85. assert.equal("workflowMode" in options, false);
  86. },
  87. };
  88. return {
  89. ctx,
  90. deps,
  91. appOptions,
  92. stdout: () => stdout,
  93. stderr: () => stderr,
  94. protocolCalls: () => protocolCalls,
  95. };
  96. }
  97. const PAIRS = {
  98. disabled: { enabled: false, onDemand: false },
  99. onDemand: { enabled: true, onDemand: true },
  100. alwaysOn: { enabled: true, onDemand: false },
  101. } as const;
  102. function assertPair(options: ZCodeAppOptions, mode: keyof typeof PAIRS) {
  103. assert.equal(options.runtimeConfig?.dynamicWorkflowEnabled, PAIRS[mode].enabled);
  104. assert.equal(options.runtimeConfig?.dynamicWorkflowToolsOnDemand, PAIRS[mode].onDemand);
  105. }
  106. for (const promptFlag of ["-p", "--prompt", "--target"]) {
  107. for (const mode of [undefined, "disabled", "onDemand", "alwaysOn"] as const) {
  108. test(`${promptFlag}: workflow mode ${mode ?? "defaults to disabled"}`, async () => {
  109. const h = harness([...(mode ? ["--workflow-mode", mode] : []), promptFlag, "hello"]);
  110. assert.equal(await run(h.ctx, h.deps), 0, h.stderr());
  111. assert.equal(h.appOptions.length, 1);
  112. assertPair(h.appOptions[0], mode ?? "disabled");
  113. assert.equal(h.stdout(), "done\n");
  114. });
  115. }
  116. }
  117. for (const resumeArgs of [["--resume", "sess_existing"], ["--continue"]]) {
  118. for (const mode of [undefined, "alwaysOn"] as const) {
  119. test(`${resumeArgs[0]} uses this invocation's workflow mode: ${mode ?? "default"}`, async () => {
  120. const h = harness(["-p", "hello", ...resumeArgs, ...(mode ? ["--workflow-mode", mode] : [])]);
  121. assert.equal(await run(h.ctx, h.deps), 0, h.stderr());
  122. assert.equal(h.appOptions[0].resume, true);
  123. assert.equal(h.appOptions[0].sessionId, resumeArgs[1] ?? "sess_latest");
  124. assertPair(h.appOptions[0], mode ?? "disabled");
  125. });
  126. }
  127. }
  128. test("an enabling workflow mode preserves the explicit tool disallowlist", async () => {
  129. const h = harness([
  130. "--workflow-mode",
  131. "alwaysOn",
  132. "--disallowed-tools",
  133. "CreateWorkflow",
  134. "-p",
  135. "hello",
  136. ]);
  137. assert.equal(await run(h.ctx, h.deps), 0, h.stderr());
  138. assertPair(h.appOptions[0], "alwaysOn");
  139. assert.deepEqual(h.appOptions[0].runtimeConfig?.toolDisallowlist, ["CreateWorkflow"]);
  140. });
  141. for (const argv of [
  142. ["app-server", "--stdio"],
  143. ["agent-server", "--stdio"],
  144. ]) {
  145. test(`${argv[0]} leaves the workflow policy to the Host`, async () => {
  146. const h = harness(argv);
  147. assert.equal(await run(h.ctx, h.deps), 0, h.stderr());
  148. assert.equal(h.protocolCalls(), 1);
  149. assert.equal(h.appOptions.length, 0);
  150. });
  151. }
  152. for (const argv of [[], ["tui"]]) {
  153. test(`${argv[0] ?? "implicit TUI"} startup defaults to disabled like headless`, async () => {
  154. const h = harness(argv);
  155. assert.equal(await run(h.ctx, h.deps), 0, h.stderr());
  156. assert.equal(h.appOptions.length, 1);
  157. assertPair(h.appOptions[0], "disabled");
  158. });
  159. }
  160. for (const argv of [["app-server", "--stdio"], ["agent-server", "--stdio"], ["doctor"]]) {
  161. test(`rejects --workflow-mode outside TUI and headless: ${argv[0]}`, async () => {
  162. const h = harness([...argv, "--workflow-mode", "alwaysOn"]);
  163. assert.equal(await run(h.ctx, h.deps), 1);
  164. assert.equal(h.stderr(), `${WORKFLOW_MODE_SCOPE_ERROR}\n`);
  165. assert.equal(h.appOptions.length, 0);
  166. assert.equal(h.protocolCalls(), 0);
  167. assert.equal(h.stdout(), "");
  168. });
  169. }
  170. test("the retired --enable-workflow flag is an unknown option", async () => {
  171. const h = harness(["--enable-workflow", "-p", "hello"]);
  172. assert.notEqual(await run(h.ctx, h.deps), 0);
  173. assert.match(h.stderr(), /enable-workflow/);
  174. assert.equal(h.appOptions.length, 0);
  175. });
  176. for (const locale of ["en-US", "zh-CN"]) {
  177. test(`help documents --workflow-mode and not the retired flag: ${locale}`, async () => {
  178. const h = harness(["--help", "--locale", locale]);
  179. assert.equal(await run(h.ctx, h.deps), 0, h.stderr());
  180. assert.match(h.stdout(), /--workflow-mode <mode>.*disabled.*onDemand.*alwaysOn/);
  181. assert.doesNotMatch(h.stdout(), /--enable-workflow/);
  182. assert.equal(h.appOptions.length, 0);
  183. });
  184. }