cwd-option.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import assert from "node:assert/strict";
  2. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import test from "node:test";
  6. import type { RunContext } from "@zcode/shared-types";
  7. import { run } from "../src/run.js";
  8. import { isTuiInvocation } from "../src/tui-stderr.js";
  9. import type { RunDependencies } from "../src/run.js";
  10. type CapturedWriteStream = NodeJS.WriteStream & {
  11. output: () => string;
  12. };
  13. const createWriteStream = (): CapturedWriteStream => {
  14. let output = "";
  15. return {
  16. output: () => output,
  17. write: (
  18. chunk: string | Uint8Array,
  19. encodingOrCallback?: BufferEncoding | ((err?: Error | null) => void),
  20. callback?: (err?: Error | null) => void,
  21. ): boolean => {
  22. output += typeof chunk === "string" ? chunk : chunk.toString();
  23. const writeCallback =
  24. typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
  25. writeCallback?.();
  26. return true;
  27. },
  28. } as CapturedWriteStream;
  29. };
  30. const createContext = (
  31. argv: string[],
  32. ): RunContext & { stderr: CapturedWriteStream; stdout: CapturedWriteStream } => ({
  33. argv,
  34. stderr: createWriteStream(),
  35. stdin: {
  36. isTTY: false,
  37. } as NodeJS.ReadStream,
  38. stdout: createWriteStream(),
  39. });
  40. const fakeProjection = {
  41. contextUsed: 0,
  42. contextWindow: 0,
  43. status: "idle",
  44. totalTokenCount: 0,
  45. turnCount: 1,
  46. };
  47. const createPromptDeps = (): RunDependencies => ({
  48. createZCodeApp: () => createPromptApp(),
  49. loadDotenv: () => ({
  50. keys: [],
  51. loaded: false,
  52. }),
  53. startProcessProviderRegistryRuntime: async () =>
  54. ({
  55. dispose: () => {},
  56. runtime: { registryService: {} },
  57. }) as never,
  58. });
  59. function createPromptApp(overrides: Record<string, unknown> = {}) {
  60. return {
  61. getModel: () => "openai/gpt-test",
  62. getThoughtLevel: () => "medium",
  63. sessionId: "session-test",
  64. traceId: "trace-test",
  65. runtime: {} as never,
  66. submitPrompt: async (prompt: string) => ({
  67. events: [],
  68. projection: fakeProjection as never,
  69. response: prompt,
  70. traceId: "trace-test" as never,
  71. turnId: "turn-test" as never,
  72. }),
  73. ...overrides,
  74. } as never;
  75. }
  76. test("recognizes --cwd as a default TUI invocation", () => {
  77. assert.equal(isTuiInvocation(["--cwd", "/workspace/project"]), true);
  78. });
  79. test("prints --cwd in help", async () => {
  80. const ctx = createContext(["--help"]);
  81. const exitCode = await run(ctx);
  82. assert.equal(exitCode, 0);
  83. assert.match(ctx.stdout.output(), /--cwd <path>/);
  84. });
  85. test("passes --cwd into prompt runtime config and dotenv loading", async () => {
  86. const cwd = await mkdtemp(join(tmpdir(), "zcode-cli-option-cwd-"));
  87. const ctx = createContext(["--cwd", cwd, "--prompt", "hello cwd option"]);
  88. try {
  89. const exitCode = await run(ctx, {
  90. ...createPromptDeps(),
  91. cwd: () => "/workspace/ignored",
  92. createZCodeApp: (options) => {
  93. assert.equal(options?.runtimeConfig?.workingDirectory, cwd);
  94. return createPromptApp();
  95. },
  96. loadDotenv: (options) => {
  97. assert.equal(options.cwd, cwd);
  98. return { keys: [], loaded: false };
  99. },
  100. });
  101. assert.equal(exitCode, 0);
  102. assert.equal(ctx.stdout.output(), "hello cwd option\n");
  103. assert.equal(ctx.stderr.output(), "");
  104. } finally {
  105. await rm(cwd, { force: true, recursive: true });
  106. }
  107. });
  108. test("resolves relative --cwd from the process cwd provider", async () => {
  109. const root = await mkdtemp(join(tmpdir(), "zcode-cli-relative-cwd-"));
  110. const project = join(root, "project");
  111. const ctx = createContext(["--cwd", "project", "--prompt", "hello relative cwd"]);
  112. try {
  113. await mkdir(project);
  114. const exitCode = await run(ctx, {
  115. ...createPromptDeps(),
  116. cwd: () => root,
  117. createZCodeApp: (options) => {
  118. assert.equal(options?.runtimeConfig?.workingDirectory, project);
  119. return createPromptApp();
  120. },
  121. });
  122. assert.equal(exitCode, 0);
  123. assert.equal(ctx.stdout.output(), "hello relative cwd\n");
  124. } finally {
  125. await rm(root, { force: true, recursive: true });
  126. }
  127. });
  128. test("uses --cwd when resolving latest sessions for --continue", async () => {
  129. const cwd = await mkdtemp(join(tmpdir(), "zcode-cli-continue-cwd-"));
  130. const ctx = createContext(["--cwd", cwd, "--continue", "--prompt", "hello continue cwd"]);
  131. let resolved = false;
  132. try {
  133. const exitCode = await run(ctx, {
  134. ...createPromptDeps(),
  135. cwd: () => "/workspace/ignored",
  136. resolveLatestSession: async (options) => {
  137. resolved = true;
  138. assert.equal(options.directory, cwd);
  139. return { id: "sess_latest" } as never;
  140. },
  141. createZCodeApp: (options) => {
  142. assert.equal(options?.runtimeConfig?.workingDirectory, cwd);
  143. assert.equal(options?.resume, true);
  144. assert.equal(options?.sessionId, "sess_latest");
  145. return createPromptApp({ sessionId: "sess_latest" });
  146. },
  147. });
  148. assert.equal(exitCode, 0);
  149. assert.equal(resolved, true);
  150. assert.equal(ctx.stdout.output(), "hello continue cwd\n");
  151. } finally {
  152. await rm(cwd, { force: true, recursive: true });
  153. }
  154. });
  155. test("passes --cwd into TUI app, skills, and session listing", async () => {
  156. const cwd = await mkdtemp(join(tmpdir(), "zcode-cli-tui-cwd-"));
  157. const ctx = createContext(["--cwd", cwd, "tui"]);
  158. try {
  159. const exitCode = await run(ctx, {
  160. ...createPromptDeps(),
  161. cwd: () => "/workspace/ignored",
  162. createZCodeApp: (options) => {
  163. assert.equal(options?.runtimeConfig?.workingDirectory, cwd);
  164. return createPromptApp();
  165. },
  166. listSessions: async (options) => {
  167. assert.equal(options.directory, cwd);
  168. return [] as never;
  169. },
  170. listSkills: async (options) => {
  171. assert.equal(options.workingDirectory, cwd);
  172. return { diagnostics: [], skills: [], totalDiscovered: 0 } as never;
  173. },
  174. loadDotenv: (options) => {
  175. assert.equal(options.cwd, cwd);
  176. return { keys: [], loaded: false };
  177. },
  178. runTui: async (options) => {
  179. // 初始模型随 loadStartupOptions 在启动屏首帧后返回,App 也在此时按 --cwd 创建。
  180. const startup = { ...options, ...(await options.loadStartupOptions?.()) };
  181. assert.equal(startup.initialModel, "openai/gpt-test");
  182. assert.equal(options.workspaceDirectory, cwd);
  183. await options.submitPrompt("/skill", { abortSignal: new AbortController().signal });
  184. await options.submitPrompt("/resume", { abortSignal: new AbortController().signal });
  185. return 0;
  186. },
  187. });
  188. assert.equal(exitCode, 0);
  189. assert.equal(ctx.stderr.output(), "");
  190. } finally {
  191. await rm(cwd, { force: true, recursive: true });
  192. }
  193. });
  194. test("passes --cwd into skills JSON output", async () => {
  195. const cwd = await mkdtemp(join(tmpdir(), "zcode-cli-skills-cwd-"));
  196. const ctx = createContext(["--cwd", cwd, "skills", "--json"]);
  197. try {
  198. const exitCode = await run(ctx, {
  199. cwd: () => "/workspace/ignored",
  200. listSkills: async (options) => {
  201. assert.equal(options.workingDirectory, cwd);
  202. return { diagnostics: [], skills: [], totalDiscovered: 0 } as never;
  203. },
  204. });
  205. const payload = JSON.parse(ctx.stdout.output()) as { cwd: string; totalDiscovered: number };
  206. assert.equal(exitCode, 0);
  207. assert.equal(payload.cwd, cwd);
  208. assert.equal(payload.totalDiscovered, 0);
  209. assert.equal(ctx.stderr.output(), "");
  210. } finally {
  211. await rm(cwd, { force: true, recursive: true });
  212. }
  213. });
  214. test("prints --cwd in doctor JSON", async () => {
  215. const cwd = await mkdtemp(join(tmpdir(), "zcode-cli-doctor-cwd-"));
  216. const ctx = createContext(["--cwd", cwd, "doctor", "--json"]);
  217. try {
  218. const exitCode = await run(ctx, { cwd: () => "/workspace/ignored" });
  219. const payload = JSON.parse(ctx.stdout.output()) as { runtime: { cwd: string } };
  220. assert.equal(exitCode, 0);
  221. assert.equal(payload.runtime.cwd, cwd);
  222. assert.equal(ctx.stderr.output(), "");
  223. } finally {
  224. await rm(cwd, { force: true, recursive: true });
  225. }
  226. });
  227. test("passes --cwd into the app-server runner", async () => {
  228. const cwd = await mkdtemp(join(tmpdir(), "zcode-cli-app-server-cwd-"));
  229. const ctx = createContext(["--cwd", cwd, "app-server", "--stdio"]);
  230. let called = false;
  231. let dotenvCalls = 0;
  232. try {
  233. const exitCode = await run(ctx, {
  234. cwd: () => "/workspace/ignored",
  235. loadDotenv: () => {
  236. dotenvCalls += 1;
  237. return { keys: [], loaded: false };
  238. },
  239. runZCodeProtocolAgent: async (options) => {
  240. called = true;
  241. assert.equal(options?.cwd, cwd);
  242. },
  243. });
  244. assert.equal(exitCode, 0);
  245. assert.equal(called, true);
  246. assert.equal(dotenvCalls, 0);
  247. assert.equal(ctx.stderr.output(), "");
  248. } finally {
  249. await rm(cwd, { force: true, recursive: true });
  250. }
  251. });
  252. test("rejects inaccessible --cwd before creating an app", async () => {
  253. const root = await mkdtemp(join(tmpdir(), "zcode-cli-missing-cwd-"));
  254. const missing = join(root, "missing");
  255. const ctx = createContext(["--cwd", missing, "--prompt", "hello"]);
  256. let appCreated = false;
  257. try {
  258. const exitCode = await run(ctx, {
  259. ...createPromptDeps(),
  260. createZCodeApp: () => {
  261. appCreated = true;
  262. throw new Error("app should not be created");
  263. },
  264. });
  265. assert.equal(exitCode, 1);
  266. assert.equal(appCreated, false);
  267. assert.match(ctx.stderr.output(), /--cwd path is not accessible/);
  268. assert.equal(ctx.stdout.output(), "");
  269. } finally {
  270. await rm(root, { force: true, recursive: true });
  271. }
  272. });
  273. test("rejects file --cwd before creating an app", async () => {
  274. const root = await mkdtemp(join(tmpdir(), "zcode-cli-file-cwd-"));
  275. const filePath = join(root, "file.txt");
  276. const ctx = createContext(["--cwd", filePath, "--prompt", "hello"]);
  277. let appCreated = false;
  278. try {
  279. await writeFile(filePath, "not a directory");
  280. const exitCode = await run(ctx, {
  281. ...createPromptDeps(),
  282. createZCodeApp: () => {
  283. appCreated = true;
  284. throw new Error("app should not be created");
  285. },
  286. });
  287. assert.equal(exitCode, 1);
  288. assert.equal(appCreated, false);
  289. assert.match(ctx.stderr.output(), /--cwd must point to a directory/);
  290. assert.equal(ctx.stdout.output(), "");
  291. } finally {
  292. await rm(root, { force: true, recursive: true });
  293. }
  294. });