workflow-mode-option.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. import assert from "node:assert/strict";
  2. import test from "node:test";
  3. import type { RunContext } from "@zcode/shared-types";
  4. import { run } from "../src/run.js";
  5. import type { RunDependencies } from "../src/run.js";
  6. import { createCommandCenter, listSlashCommandSuggestions } from "../src/command-center.js";
  7. import type { CommandCenterApp, CommandCenterDeps } from "../src/command-center.js";
  8. import { createTuiSubmitPrompt } from "../src/tui-prompt-handler.js";
  9. import { WORKFLOW_DISABLED_NOTICE, WORKFLOW_MODE_SCOPE_ERROR } from "../src/workflow-mode.js";
  10. /**
  11. * 独立 CLI 的 `--workflow-mode`(docs/dynamic-workflow/launch.md「The standalone CLI:
  12. * `--workflow-mode`」,DWG-14 ~ DWG-17)。缺省 disabled;两个 runtime 字段总是显式写出。
  13. */
  14. type CapturedWriteStream = NodeJS.WriteStream & { output: () => string };
  15. const createWriteStream = (): CapturedWriteStream => {
  16. let output = "";
  17. return {
  18. isTTY: false,
  19. output: () => output,
  20. write: (chunk: string | Uint8Array, encodingOrCallback?: unknown, callback?: unknown) => {
  21. output += typeof chunk === "string" ? chunk : chunk.toString();
  22. const done = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
  23. (done as (() => void) | undefined)?.();
  24. return true;
  25. },
  26. } as CapturedWriteStream;
  27. };
  28. const createContext = (argv: string[]) =>
  29. ({
  30. argv,
  31. stderr: createWriteStream(),
  32. stdin: { isTTY: false } as NodeJS.ReadStream,
  33. stdout: createWriteStream(),
  34. }) satisfies RunContext;
  35. const fakeProjection = {
  36. contextUsed: 0,
  37. contextWindow: 0,
  38. status: "idle",
  39. totalTokenCount: 0,
  40. turnCount: 1,
  41. };
  42. type RuntimeConfigSeen = {
  43. dynamicWorkflowEnabled?: boolean;
  44. dynamicWorkflowToolsOnDemand?: boolean;
  45. };
  46. /** 记录每次建 app 时的两个工作流字段;app 本身只够跑通一次 prompt / TUI 启动。 */
  47. function createRecordingDeps(): { deps: RunDependencies; seen: RuntimeConfigSeen[] } {
  48. const seen: RuntimeConfigSeen[] = [];
  49. const deps: RunDependencies = {
  50. createModelAdapter: () => ({}) as never,
  51. createZCodeApp: (options) => {
  52. const config = (options?.runtimeConfig ?? {}) as RuntimeConfigSeen;
  53. seen.push({
  54. dynamicWorkflowEnabled: config.dynamicWorkflowEnabled,
  55. dynamicWorkflowToolsOnDemand: config.dynamicWorkflowToolsOnDemand,
  56. });
  57. return {
  58. getLocale: () => "en-US",
  59. getModel: () => "openai/gpt-test",
  60. getThoughtLevel: () => "medium",
  61. sessionId: `session-${seen.length}`,
  62. traceId: "trace-test",
  63. runtime: {} as never,
  64. submitPrompt: async (prompt: string) => ({
  65. events: [],
  66. projection: fakeProjection as never,
  67. response: prompt,
  68. traceId: "trace-test" as never,
  69. turnId: "turn-test" as never,
  70. }),
  71. } as never;
  72. },
  73. loadDotenv: () => ({ keys: [], loaded: false }),
  74. startProcessProviderRegistryRuntime: async () =>
  75. ({ dispose: () => {}, runtime: { registryService: {} } }) as never,
  76. skipUserConfig: true,
  77. listCustomCommands: async () => ({ commands: [], diagnostics: [] }) as never,
  78. };
  79. return { deps, seen };
  80. }
  81. const DISABLED_PAIR = { dynamicWorkflowEnabled: false, dynamicWorkflowToolsOnDemand: false };
  82. const ON_DEMAND_PAIR = { dynamicWorkflowEnabled: true, dynamicWorkflowToolsOnDemand: true };
  83. const ALWAYS_ON_PAIR = { dynamicWorkflowEnabled: true, dynamicWorkflowToolsOnDemand: false };
  84. // ── DWG-14:取值与 runtime 字段 ────────────────────────────────────────────
  85. test("TUI without --workflow-mode writes the disabled pair and suggests no /workflow", async () => {
  86. const { deps, seen } = createRecordingDeps();
  87. let suggestions: string[] = [];
  88. const ctx = createContext(["tui"]);
  89. const exitCode = await run(ctx, {
  90. ...deps,
  91. runTui: async (options) => {
  92. // TUI 的斜杠命令与首个 App 由启动选项异步提供(TUI 启动画面先渲染,再加载会话元数据)。
  93. const startup = await options.loadStartupOptions?.();
  94. suggestions = (startup?.slashCommands ?? options.slashCommands ?? []).map(
  95. (entry) => entry.name,
  96. );
  97. return 0;
  98. },
  99. });
  100. assert.equal(exitCode, 0);
  101. assert.ok(seen.length > 0, "the TUI creates its first app at startup");
  102. for (const config of seen) assert.deepEqual(config, DISABLED_PAIR);
  103. assert.ok(!suggestions.includes("workflow"));
  104. assert.ok(suggestions.includes("dwf"), "/dwf stays for viewing existing runs");
  105. });
  106. test("TUI with --workflow-mode onDemand writes the onDemand pair and suggests /workflow", async () => {
  107. const { deps, seen } = createRecordingDeps();
  108. let suggestions: string[] = [];
  109. const ctx = createContext(["--workflow-mode", "onDemand"]);
  110. const exitCode = await run(ctx, {
  111. ...deps,
  112. runTui: async (options) => {
  113. // TUI 的斜杠命令与首个 App 由启动选项异步提供(TUI 启动画面先渲染,再加载会话元数据)。
  114. const startup = await options.loadStartupOptions?.();
  115. suggestions = (startup?.slashCommands ?? options.slashCommands ?? []).map(
  116. (entry) => entry.name,
  117. );
  118. return 0;
  119. },
  120. });
  121. assert.equal(exitCode, 0);
  122. assert.ok(seen.length > 0);
  123. for (const config of seen) assert.deepEqual(config, ON_DEMAND_PAIR);
  124. assert.ok(suggestions.includes("workflow"));
  125. });
  126. test("every app the TUI creates, including /new, carries the same pair", async () => {
  127. const { deps, seen } = createRecordingDeps();
  128. const handler = createTuiSubmitPrompt(
  129. deps,
  130. {},
  131. "test",
  132. undefined,
  133. undefined,
  134. undefined,
  135. undefined,
  136. undefined,
  137. false,
  138. "off",
  139. undefined,
  140. undefined,
  141. "alwaysOn",
  142. );
  143. try {
  144. await handler.getSessionMetadata!();
  145. await handler("/new", { abortSignal: new AbortController().signal });
  146. } finally {
  147. await handler.close?.();
  148. }
  149. assert.equal(seen.length, 2);
  150. for (const config of seen) assert.deepEqual(config, ALWAYS_ON_PAIR);
  151. });
  152. test("an unknown --workflow-mode value fails before any app is created", async () => {
  153. const { deps, seen } = createRecordingDeps();
  154. const ctx = createContext(["--prompt", "hello", "--workflow-mode", "sometimes"]);
  155. assert.equal(await run(ctx, deps), 1);
  156. assert.match(
  157. ctx.stderr.output(),
  158. /Unsupported --workflow-mode value: sometimes\. Supported modes: disabled, onDemand, alwaysOn\./,
  159. );
  160. assert.deepEqual(seen, []);
  161. });
  162. // ── DWG-15:作用域 ──────────────────────────────────────────────────────────
  163. for (const argv of [["app-server"], ["agent-server"], ["login"], ["skills"]] as const) {
  164. test(`--workflow-mode is rejected with ${argv[0]}`, async () => {
  165. const { deps, seen } = createRecordingDeps();
  166. const ctx = createContext([...argv, "--workflow-mode", "alwaysOn"]);
  167. assert.equal(await run(ctx, deps), 1);
  168. assert.equal(ctx.stderr.output(), `${WORKFLOW_MODE_SCOPE_ERROR}\n`);
  169. assert.deepEqual(seen, []);
  170. });
  171. }
  172. // ── DWG-17:headless ─────────────────────────────────────────────────────────
  173. test("headless /workflow under the default mode exits 1 before any app exists", async () => {
  174. const { deps, seen } = createRecordingDeps();
  175. const ctx = createContext(["--prompt", "/workflow build me a plan"]);
  176. assert.equal(await run(ctx, deps), 1);
  177. assert.equal(ctx.stderr.output(), `Error: ${WORKFLOW_DISABLED_NOTICE}\n`);
  178. assert.equal(ctx.stdout.output(), "");
  179. assert.deepEqual(seen, []);
  180. });
  181. test("headless /help lists /workflow only when workflows are on", async () => {
  182. const disabled = createContext(["--prompt", "/help"]);
  183. assert.equal(await run(disabled, createRecordingDeps().deps), 0);
  184. assert.doesNotMatch(disabled.stdout.output(), /\/workflow/);
  185. assert.match(disabled.stdout.output(), /\/dwf/);
  186. const onDemand = createContext(["--prompt", "/help", "--workflow-mode", "onDemand"]);
  187. assert.equal(await run(onDemand, createRecordingDeps().deps), 0);
  188. assert.match(onDemand.stdout.output(), /\/workflow \[what the workflow should accomplish\]/);
  189. });
  190. // ── DWG-16:命令面 ───────────────────────────────────────────────────────────
  191. function createHarness(
  192. workflowMode: CommandCenterDeps["workflowMode"],
  193. app: Partial<CommandCenterApp> = {},
  194. ) {
  195. const calls = { getApp: 0, submitted: [] as string[] };
  196. const submitPrompt = createCommandCenter({
  197. getApp: async () => {
  198. calls.getApp += 1;
  199. return {
  200. sessionId: "sess_active",
  201. traceId: "trace-active",
  202. submitPrompt: async (prompt: string) => {
  203. calls.submitted.push(prompt);
  204. return { response: "submitted", traceId: "trace-submit" };
  205. },
  206. ...app,
  207. } as never;
  208. },
  209. getMode: () => "build" as never,
  210. resumeApp: async () => {
  211. throw new Error("resumeApp should not run");
  212. },
  213. workflowMode,
  214. });
  215. return { calls, submitPrompt };
  216. }
  217. const ABORT = { abortSignal: new AbortController().signal };
  218. test("disabled: /workflow answers the notice locally without an app or a model turn", async () => {
  219. const { calls, submitPrompt } = createHarness("disabled");
  220. const result = await submitPrompt("/workflow review the auth module", ABORT);
  221. assert.equal(result.response, WORKFLOW_DISABLED_NOTICE);
  222. assert.equal(calls.getApp, 0);
  223. assert.deepEqual(calls.submitted, []);
  224. });
  225. test("disabled: /help and /help workflow leave /workflow out", async () => {
  226. const { submitPrompt } = createHarness("disabled");
  227. const all = await submitPrompt("/help", ABORT);
  228. assert.doesNotMatch(all.response, /\/workflow/);
  229. const single = await submitPrompt("/help workflow", ABORT);
  230. assert.match(single.response, /^Unknown slash command: \/workflow\./);
  231. assert.doesNotMatch(single.response, /Available commands:.*\/workflow\b/);
  232. });
  233. test("disabled: /dwf list and cancel still work, resume is refused before the server", async () => {
  234. let resumed = 0;
  235. let cancelled = 0;
  236. const { submitPrompt } = createHarness("disabled", {
  237. listDynamicWorkflowRuns: async () => [],
  238. cancelBackgroundTask: async () => {
  239. cancelled += 1;
  240. return { cancelled: true, status: "cancelled" } as never;
  241. },
  242. resumeWorkflowRun: async () => {
  243. resumed += 1;
  244. return { ok: true, runId: "dwfrun_1" } as never;
  245. },
  246. });
  247. assert.match((await submitPrompt("/dwf list", ABORT)).response, /No dynamic workflow runs/);
  248. assert.match(
  249. (await submitPrompt("/dwf cancel dwfrun_1", ABORT)).response,
  250. /Cancelled dynamic workflow run dwfrun_1/,
  251. );
  252. assert.equal(cancelled, 1);
  253. assert.equal(
  254. (await submitPrompt("/dwf resume dwfrun_1", ABORT)).response,
  255. WORKFLOW_DISABLED_NOTICE,
  256. );
  257. assert.equal(resumed, 0);
  258. });
  259. for (const mode of ["onDemand", "alwaysOn"] as const) {
  260. test(`${mode}: /workflow is suggested and submitted to the app as before`, async () => {
  261. const { calls, submitPrompt } = createHarness(mode);
  262. const result = await submitPrompt("/workflow review the auth module", ABORT);
  263. assert.equal(result.response, "submitted");
  264. assert.deepEqual(calls.submitted, ["/workflow review the auth module"]);
  265. const names = listSlashCommandSuggestions(undefined, { workflowMode: mode }).map(
  266. (entry) => entry.name,
  267. );
  268. assert.ok(names.includes("workflow"));
  269. });
  270. }
  271. test("disabled: the suggestion list drops only /workflow", () => {
  272. const all = listSlashCommandSuggestions().map((entry) => entry.name);
  273. const disabled = listSlashCommandSuggestions(undefined, { workflowMode: "disabled" }).map(
  274. (entry) => entry.name,
  275. );
  276. assert.deepEqual(
  277. disabled,
  278. all.filter((name) => name !== "workflow"),
  279. );
  280. });