workflow-mode-option.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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("headless prompt without --workflow-mode writes the disabled pair explicitly", async () => {
  86. const { deps, seen } = createRecordingDeps();
  87. const ctx = createContext(["--prompt", "hello"]);
  88. assert.equal(await run(ctx, deps), 0);
  89. assert.deepEqual(seen, [DISABLED_PAIR]);
  90. });
  91. for (const [mode, pair] of [
  92. ["disabled", DISABLED_PAIR],
  93. ["onDemand", ON_DEMAND_PAIR],
  94. ["alwaysOn", ALWAYS_ON_PAIR],
  95. ] as const) {
  96. test(`headless prompt with --workflow-mode ${mode} writes the matching pair`, async () => {
  97. const { deps, seen } = createRecordingDeps();
  98. const ctx = createContext(["--prompt", "hello", "--workflow-mode", mode]);
  99. assert.equal(await run(ctx, deps), 0);
  100. assert.deepEqual(seen, [pair]);
  101. });
  102. }
  103. test("TUI without --workflow-mode writes the disabled pair and suggests no /workflow", async () => {
  104. const { deps, seen } = createRecordingDeps();
  105. let suggestions: string[] = [];
  106. const ctx = createContext(["tui"]);
  107. const exitCode = await run(ctx, {
  108. ...deps,
  109. runTui: async (options) => {
  110. // TUI 的斜杠命令与首个 App 由启动选项异步提供(TUI 启动画面先渲染,再加载会话元数据)。
  111. const startup = await options.loadStartupOptions?.();
  112. suggestions = (startup?.slashCommands ?? options.slashCommands ?? []).map(
  113. (entry) => entry.name,
  114. );
  115. return 0;
  116. },
  117. });
  118. assert.equal(exitCode, 0);
  119. assert.ok(seen.length > 0, "the TUI creates its first app at startup");
  120. for (const config of seen) assert.deepEqual(config, DISABLED_PAIR);
  121. assert.ok(!suggestions.includes("workflow"));
  122. assert.ok(suggestions.includes("dwf"), "/dwf stays for viewing existing runs");
  123. });
  124. test("TUI with --workflow-mode onDemand writes the onDemand pair and suggests /workflow", async () => {
  125. const { deps, seen } = createRecordingDeps();
  126. let suggestions: string[] = [];
  127. const ctx = createContext(["--workflow-mode", "onDemand"]);
  128. const exitCode = await run(ctx, {
  129. ...deps,
  130. runTui: async (options) => {
  131. // TUI 的斜杠命令与首个 App 由启动选项异步提供(TUI 启动画面先渲染,再加载会话元数据)。
  132. const startup = await options.loadStartupOptions?.();
  133. suggestions = (startup?.slashCommands ?? options.slashCommands ?? []).map(
  134. (entry) => entry.name,
  135. );
  136. return 0;
  137. },
  138. });
  139. assert.equal(exitCode, 0);
  140. assert.ok(seen.length > 0);
  141. for (const config of seen) assert.deepEqual(config, ON_DEMAND_PAIR);
  142. assert.ok(suggestions.includes("workflow"));
  143. });
  144. test("every app the TUI creates, including /new, carries the same pair", async () => {
  145. const { deps, seen } = createRecordingDeps();
  146. const handler = createTuiSubmitPrompt(
  147. deps,
  148. {},
  149. "test",
  150. undefined,
  151. undefined,
  152. undefined,
  153. undefined,
  154. undefined,
  155. false,
  156. undefined,
  157. undefined,
  158. "alwaysOn",
  159. );
  160. try {
  161. await handler.getSessionMetadata!();
  162. await handler("/new", { abortSignal: new AbortController().signal });
  163. } finally {
  164. await handler.close?.();
  165. }
  166. assert.equal(seen.length, 2);
  167. for (const config of seen) assert.deepEqual(config, ALWAYS_ON_PAIR);
  168. });
  169. test("an unknown --workflow-mode value fails before any app is created", async () => {
  170. const { deps, seen } = createRecordingDeps();
  171. const ctx = createContext(["--prompt", "hello", "--workflow-mode", "sometimes"]);
  172. assert.equal(await run(ctx, deps), 1);
  173. assert.match(
  174. ctx.stderr.output(),
  175. /Unsupported --workflow-mode value: sometimes\. Supported modes: disabled, onDemand, alwaysOn\./,
  176. );
  177. assert.deepEqual(seen, []);
  178. });
  179. // ── DWG-15:作用域 ──────────────────────────────────────────────────────────
  180. for (const argv of [["app-server"], ["agent-server"], ["login"], ["skills"]] as const) {
  181. test(`--workflow-mode is rejected with ${argv[0]}`, async () => {
  182. const { deps, seen } = createRecordingDeps();
  183. const ctx = createContext([...argv, "--workflow-mode", "alwaysOn"]);
  184. assert.equal(await run(ctx, deps), 1);
  185. assert.equal(ctx.stderr.output(), `${WORKFLOW_MODE_SCOPE_ERROR}\n`);
  186. assert.deepEqual(seen, []);
  187. });
  188. }
  189. test("--workflow-mode is accepted with --target", async () => {
  190. const ctx = createContext(["--target", "ship it", "--workflow-mode", "alwaysOn"]);
  191. let seenPair: RuntimeConfigSeen | undefined;
  192. const exitCode = await run(ctx, {
  193. ...createRecordingDeps().deps,
  194. createZCodeApp: (options) => {
  195. const config = (options?.runtimeConfig ?? {}) as RuntimeConfigSeen;
  196. seenPair = {
  197. dynamicWorkflowEnabled: config.dynamicWorkflowEnabled,
  198. dynamicWorkflowToolsOnDemand: config.dynamicWorkflowToolsOnDemand,
  199. };
  200. throw new Error("stop after app options were checked");
  201. },
  202. });
  203. assert.equal(exitCode, 1);
  204. assert.doesNotMatch(ctx.stderr.output(), /can only be used/);
  205. assert.deepEqual(seenPair, ALWAYS_ON_PAIR);
  206. });
  207. // ── DWG-17:headless ─────────────────────────────────────────────────────────
  208. test("headless /workflow under the default mode exits 1 before any app exists", async () => {
  209. const { deps, seen } = createRecordingDeps();
  210. const ctx = createContext(["--prompt", "/workflow build me a plan"]);
  211. assert.equal(await run(ctx, deps), 1);
  212. assert.equal(ctx.stderr.output(), `Error: ${WORKFLOW_DISABLED_NOTICE}\n`);
  213. assert.equal(ctx.stdout.output(), "");
  214. assert.deepEqual(seen, []);
  215. });
  216. test("headless /help lists /workflow only when workflows are on", async () => {
  217. const disabled = createContext(["--prompt", "/help"]);
  218. assert.equal(await run(disabled, createRecordingDeps().deps), 0);
  219. assert.doesNotMatch(disabled.stdout.output(), /\/workflow/);
  220. assert.match(disabled.stdout.output(), /\/dwf/);
  221. const onDemand = createContext(["--prompt", "/help", "--workflow-mode", "onDemand"]);
  222. assert.equal(await run(onDemand, createRecordingDeps().deps), 0);
  223. assert.match(onDemand.stdout.output(), /\/workflow \[what the workflow should accomplish\]/);
  224. });
  225. // ── DWG-16:命令面 ───────────────────────────────────────────────────────────
  226. function createHarness(
  227. workflowMode: CommandCenterDeps["workflowMode"],
  228. app: Partial<CommandCenterApp> = {},
  229. ) {
  230. const calls = { getApp: 0, submitted: [] as string[] };
  231. const submitPrompt = createCommandCenter({
  232. getApp: async () => {
  233. calls.getApp += 1;
  234. return {
  235. sessionId: "sess_active",
  236. traceId: "trace-active",
  237. submitPrompt: async (prompt: string) => {
  238. calls.submitted.push(prompt);
  239. return { response: "submitted", traceId: "trace-submit" };
  240. },
  241. ...app,
  242. } as never;
  243. },
  244. getMode: () => "build" as never,
  245. resumeApp: async () => {
  246. throw new Error("resumeApp should not run");
  247. },
  248. workflowMode,
  249. });
  250. return { calls, submitPrompt };
  251. }
  252. const ABORT = { abortSignal: new AbortController().signal };
  253. test("disabled: /workflow answers the notice locally without an app or a model turn", async () => {
  254. const { calls, submitPrompt } = createHarness("disabled");
  255. const result = await submitPrompt("/workflow review the auth module", ABORT);
  256. assert.equal(result.response, WORKFLOW_DISABLED_NOTICE);
  257. assert.equal(calls.getApp, 0);
  258. assert.deepEqual(calls.submitted, []);
  259. });
  260. test("disabled: /help and /help workflow leave /workflow out", async () => {
  261. const { submitPrompt } = createHarness("disabled");
  262. const all = await submitPrompt("/help", ABORT);
  263. assert.doesNotMatch(all.response, /\/workflow/);
  264. const single = await submitPrompt("/help workflow", ABORT);
  265. assert.match(single.response, /^Unknown slash command: \/workflow\./);
  266. assert.doesNotMatch(single.response, /Available commands:.*\/workflow\b/);
  267. });
  268. test("disabled: /dwf list and cancel still work, resume is refused before the server", async () => {
  269. let resumed = 0;
  270. let cancelled = 0;
  271. const { submitPrompt } = createHarness("disabled", {
  272. listDynamicWorkflowRuns: async () => [],
  273. cancelBackgroundTask: async () => {
  274. cancelled += 1;
  275. return { cancelled: true, status: "cancelled" } as never;
  276. },
  277. resumeWorkflowRun: async () => {
  278. resumed += 1;
  279. return { ok: true, runId: "dwfrun_1" } as never;
  280. },
  281. });
  282. assert.match((await submitPrompt("/dwf list", ABORT)).response, /No dynamic workflow runs/);
  283. assert.match(
  284. (await submitPrompt("/dwf cancel dwfrun_1", ABORT)).response,
  285. /Cancelled dynamic workflow run dwfrun_1/,
  286. );
  287. assert.equal(cancelled, 1);
  288. assert.equal(
  289. (await submitPrompt("/dwf resume dwfrun_1", ABORT)).response,
  290. WORKFLOW_DISABLED_NOTICE,
  291. );
  292. assert.equal(resumed, 0);
  293. });
  294. for (const mode of ["onDemand", "alwaysOn"] as const) {
  295. test(`${mode}: /workflow is suggested and submitted to the app as before`, async () => {
  296. const { calls, submitPrompt } = createHarness(mode);
  297. const result = await submitPrompt("/workflow review the auth module", ABORT);
  298. assert.equal(result.response, "submitted");
  299. assert.deepEqual(calls.submitted, ["/workflow review the auth module"]);
  300. const names = listSlashCommandSuggestions(undefined, { workflowMode: mode }).map(
  301. (entry) => entry.name,
  302. );
  303. assert.ok(names.includes("workflow"));
  304. });
  305. }
  306. test("disabled: the suggestion list drops only /workflow", () => {
  307. const all = listSlashCommandSuggestions().map((entry) => entry.name);
  308. const disabled = listSlashCommandSuggestions(undefined, { workflowMode: "disabled" }).map(
  309. (entry) => entry.name,
  310. );
  311. assert.deepEqual(
  312. disabled,
  313. all.filter((name) => name !== "workflow"),
  314. );
  315. });