browser-state-option.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. import assert from "node:assert/strict";
  2. import { chmod, 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 {
  8. BROWSER_STATE_CONFLICT_ERROR,
  9. BROWSER_STATE_REQUIRES_HEADLESS_ERROR,
  10. } from "../src/browser-state-option.js";
  11. import { run } from "../src/run.js";
  12. import type { RunDependencies } from "../src/run.js";
  13. /**
  14. * `--browser-state` / `--no-browser-state` 与默认登录态文件
  15. * (docs/browser-use/2026-11-17-cli-browser-state-spec.md §4、§9)。
  16. */
  17. type CapturedWriteStream = NodeJS.WriteStream & { output: () => string };
  18. const BROWSER_USE_SCOPE_ERROR =
  19. "--browser-use=headless can only be used with --prompt, --target, or tui.";
  20. const SECRET_COOKIE_VALUE = "secret-cookie-value";
  21. const VALID_STATE = {
  22. cookies: [
  23. {
  24. name: "sid",
  25. value: "cookie-value",
  26. domain: ".example.com",
  27. path: "/",
  28. expires: -1,
  29. httpOnly: true,
  30. secure: true,
  31. sameSite: "Lax",
  32. },
  33. ],
  34. origins: [],
  35. };
  36. const createWriteStream = (): CapturedWriteStream => {
  37. let output = "";
  38. return {
  39. isTTY: false,
  40. output: () => output,
  41. write: (chunk: string | Uint8Array, encodingOrCallback?: unknown, callback?: unknown) => {
  42. output += typeof chunk === "string" ? chunk : chunk.toString();
  43. const done = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
  44. (done as (() => void) | undefined)?.();
  45. return true;
  46. },
  47. } as CapturedWriteStream;
  48. };
  49. const createContext = (argv: string[]) =>
  50. ({
  51. argv,
  52. stderr: createWriteStream(),
  53. stdin: { isTTY: false } as NodeJS.ReadStream,
  54. stdout: createWriteStream(),
  55. }) satisfies RunContext;
  56. const fakeProjection = {
  57. contextUsed: 0,
  58. contextWindow: 0,
  59. status: "idle",
  60. totalTokenCount: 0,
  61. turnCount: 1,
  62. };
  63. interface Fixture {
  64. home: string;
  65. launchCwd: string;
  66. defaultStatePath: string;
  67. runtimeStatePaths: Array<string | undefined>;
  68. appCount: () => number;
  69. deps: RunDependencies;
  70. cleanup: () => Promise<void>;
  71. }
  72. async function createFixture(): Promise<Fixture> {
  73. const root = await mkdtemp(join(tmpdir(), "zcode-browser-state-option-"));
  74. const home = join(root, "home");
  75. const launchCwd = join(root, "launch");
  76. await mkdir(home, { recursive: true });
  77. await mkdir(launchCwd, { recursive: true });
  78. const runtimeStatePaths: Array<string | undefined> = [];
  79. let apps = 0;
  80. const deps: RunDependencies = {
  81. cwd: () => launchCwd,
  82. env: { HOME: home },
  83. createManagedCdpBrowserRuntime: (options) => {
  84. runtimeStatePaths.push(options?.storageStatePath);
  85. return { browserControlPort: {} as never, close: async () => undefined };
  86. },
  87. createModelAdapter: () => ({}) as never,
  88. createZCodeApp: () => {
  89. apps += 1;
  90. return {
  91. getLocale: () => "en-US",
  92. getModel: () => "example/test-model",
  93. getThoughtLevel: () => "medium",
  94. sessionId: `session-${apps}`,
  95. traceId: "trace-test",
  96. runtime: {} as never,
  97. submitPrompt: async (prompt: string) => ({
  98. events: [],
  99. projection: fakeProjection as never,
  100. response: prompt,
  101. traceId: "trace-test" as never,
  102. turnId: "turn-test" as never,
  103. }),
  104. } as never;
  105. },
  106. loadDotenv: () => ({ keys: [], loaded: false }),
  107. startProcessProviderRegistryRuntime: async () =>
  108. ({ dispose: () => {}, runtime: { registryService: {} } }) as never,
  109. skipUserConfig: true,
  110. listCustomCommands: async () => ({ commands: [], diagnostics: [] }) as never,
  111. };
  112. return {
  113. home,
  114. launchCwd,
  115. defaultStatePath: join(home, ".zcode", "cli", "browser-state.json"),
  116. runtimeStatePaths,
  117. appCount: () => apps,
  118. deps,
  119. cleanup: () => rm(root, { recursive: true, force: true }),
  120. };
  121. }
  122. async function writeDefaultState(fixture: Fixture, content: unknown): Promise<void> {
  123. await mkdir(join(fixture.home, ".zcode", "cli"), { recursive: true });
  124. await writeFile(
  125. fixture.defaultStatePath,
  126. typeof content === "string" ? content : JSON.stringify(content),
  127. );
  128. }
  129. async function withFixture(body: (fixture: Fixture) => Promise<void>): Promise<void> {
  130. const fixture = await createFixture();
  131. try {
  132. await body(fixture);
  133. } finally {
  134. await fixture.cleanup();
  135. }
  136. }
  137. test("does not touch any state file without --browser-use=headless", () =>
  138. withFixture(async (fixture) => {
  139. await writeDefaultState(fixture, "{");
  140. const ctx = createContext(["--prompt", "hello"]);
  141. assert.equal(await run(ctx, fixture.deps), 0);
  142. assert.doesNotMatch(ctx.stderr.output(), /browser state/iu);
  143. }));
  144. test("rejects state flags without headless", () =>
  145. withFixture(async (fixture) => {
  146. for (const argv of [
  147. ["--browser-state", "state.json", "--prompt", "p"],
  148. ["--no-browser-state", "--prompt", "p"],
  149. ]) {
  150. const ctx = createContext(argv);
  151. assert.equal(await run(ctx, fixture.deps), 1);
  152. assert.equal(ctx.stderr.output(), `${BROWSER_STATE_REQUIRES_HEADLESS_ERROR}\n`);
  153. }
  154. assert.equal(fixture.appCount(), 0);
  155. }));
  156. test("rejects both state flags together", () =>
  157. withFixture(async (fixture) => {
  158. const ctx = createContext([
  159. "--browser-use=headless",
  160. "--browser-state",
  161. "state.json",
  162. "--no-browser-state",
  163. "--prompt",
  164. "p",
  165. ]);
  166. assert.equal(await run(ctx, fixture.deps), 1);
  167. assert.match(ctx.stderr.output(), new RegExp(escapeRegExp(BROWSER_STATE_CONFLICT_ERROR), "u"));
  168. assert.equal(fixture.appCount(), 0);
  169. }));
  170. test("keeps app-server rejecting headless browser flags", () =>
  171. withFixture(async (fixture) => {
  172. const invalidPath = join(fixture.launchCwd, "invalid.json");
  173. await writeFile(invalidPath, "{");
  174. const ctx = createContext([
  175. "app-server",
  176. "--browser-use=headless",
  177. "--browser-state",
  178. invalidPath,
  179. ]);
  180. assert.equal(await run(ctx, fixture.deps), 1);
  181. assert.match(ctx.stderr.output(), new RegExp(escapeRegExp(BROWSER_USE_SCOPE_ERROR), "u"));
  182. assert.doesNotMatch(ctx.stderr.output(), /Browser state/u);
  183. }));
  184. test("passes no state path when the default file is absent", () =>
  185. withFixture(async (fixture) => {
  186. const ctx = createContext(["--browser-use=headless", "--prompt", "hello"]);
  187. assert.equal(await run(ctx, fixture.deps), 0);
  188. assert.deepEqual(fixture.runtimeStatePaths, [undefined]);
  189. assert.doesNotMatch(ctx.stderr.output(), /browser state/iu);
  190. }));
  191. test("loads the default file and prints a notice", () =>
  192. withFixture(async (fixture) => {
  193. await writeDefaultState(fixture, VALID_STATE);
  194. await chmod(fixture.defaultStatePath, 0o600);
  195. const ctx = createContext(["--browser-use=headless", "--prompt", "hello"]);
  196. assert.equal(await run(ctx, fixture.deps), 0);
  197. assert.deepEqual(fixture.runtimeStatePaths, [fixture.defaultStatePath]);
  198. assert.match(ctx.stderr.output(), /Loaded default browser state/u);
  199. assert.match(ctx.stderr.output(), /--no-browser-state/u);
  200. }));
  201. test("skips the default file with --no-browser-state", () =>
  202. withFixture(async (fixture) => {
  203. await writeDefaultState(fixture, "{");
  204. const ctx = createContext(["--browser-use=headless", "--no-browser-state", "--prompt", "hi"]);
  205. assert.equal(await run(ctx, fixture.deps), 0);
  206. assert.deepEqual(fixture.runtimeStatePaths, [undefined]);
  207. }));
  208. test("resolves an explicit relative path against the launch directory", () =>
  209. withFixture(async (fixture) => {
  210. const workspace = join(fixture.home, "workspace");
  211. await mkdir(workspace);
  212. const statePath = join(fixture.launchCwd, "state.json");
  213. await writeFile(statePath, JSON.stringify(VALID_STATE));
  214. await chmod(statePath, 0o600);
  215. const ctx = createContext([
  216. "--cwd",
  217. workspace,
  218. "--browser-use=headless",
  219. "--browser-state",
  220. "./state.json",
  221. "--prompt",
  222. "hello",
  223. ]);
  224. assert.equal(await run(ctx, fixture.deps), 0);
  225. assert.deepEqual(fixture.runtimeStatePaths, [statePath]);
  226. }));
  227. test("reports the resolved path when an explicit file is missing", () =>
  228. withFixture(async (fixture) => {
  229. const ctx = createContext([
  230. "--browser-use=headless",
  231. "--browser-state=~/missing.json",
  232. "--prompt",
  233. "hello",
  234. ]);
  235. assert.equal(await run(ctx, fixture.deps), 1);
  236. assert.match(
  237. ctx.stderr.output(),
  238. new RegExp(escapeRegExp(join(fixture.launchCwd, "~", "missing.json")), "u"),
  239. );
  240. assert.deepEqual(fixture.runtimeStatePaths, []);
  241. assert.equal(fixture.appCount(), 0);
  242. }));
  243. test("fails closed when the default file is invalid", () =>
  244. withFixture(async (fixture) => {
  245. await writeDefaultState(fixture, "{");
  246. const ctx = createContext(["--browser-use=headless", "--prompt", "hello"]);
  247. assert.equal(await run(ctx, fixture.deps), 1);
  248. assert.match(ctx.stderr.output(), new RegExp(escapeRegExp(fixture.defaultStatePath), "u"));
  249. assert.match(ctx.stderr.output(), /--no-browser-state/u);
  250. assert.equal(fixture.appCount(), 0);
  251. }));
  252. test("fails closed when the default path is a directory", () =>
  253. withFixture(async (fixture) => {
  254. await mkdir(fixture.defaultStatePath, { recursive: true });
  255. const ctx = createContext(["--browser-use=headless", "--prompt", "hello"]);
  256. assert.equal(await run(ctx, fixture.deps), 1);
  257. assert.match(ctx.stderr.output(), new RegExp(escapeRegExp(fixture.defaultStatePath), "u"));
  258. assert.match(ctx.stderr.output(), /--no-browser-state/u);
  259. assert.equal(fixture.appCount(), 0);
  260. }));
  261. test("prints schema issues without values", () =>
  262. withFixture(async (fixture) => {
  263. const statePath = join(fixture.launchCwd, "state.json");
  264. await writeFile(
  265. statePath,
  266. JSON.stringify({
  267. cookies: [{ ...VALID_STATE.cookies[0], value: SECRET_COOKIE_VALUE, sameSite: "lax" }],
  268. }),
  269. );
  270. const ctx = createContext([
  271. "--browser-use=headless",
  272. "--browser-state",
  273. statePath,
  274. "--prompt",
  275. "hello",
  276. ]);
  277. assert.equal(await run(ctx, fixture.deps), 1);
  278. assert.match(ctx.stderr.output(), /cookies\[0\]\.sameSite/u);
  279. assert.doesNotMatch(ctx.stderr.output(), new RegExp(SECRET_COOKIE_VALUE, "u"));
  280. }));
  281. test("warns about unknown fields and loose permissions", () =>
  282. withFixture(async (fixture) => {
  283. const statePath = join(fixture.launchCwd, "state.json");
  284. await writeFile(
  285. statePath,
  286. JSON.stringify({ ...VALID_STATE, cookies: [{ ...VALID_STATE.cookies[0], sourcePort: 443 }] }),
  287. );
  288. await chmod(statePath, 0o644);
  289. const ctx = createContext([
  290. "--browser-use=headless",
  291. "--browser-state",
  292. statePath,
  293. "--prompt",
  294. "hello",
  295. ]);
  296. assert.equal(await run(ctx, fixture.deps), 0);
  297. assert.match(ctx.stderr.output(), /cookies\[\]\.sourcePort/u);
  298. if (process.platform !== "win32") assert.match(ctx.stderr.output(), /chmod 600/u);
  299. assert.deepEqual(fixture.runtimeStatePaths, [statePath]);
  300. }));
  301. test("passes the selection into the TUI browser runtime", () =>
  302. withFixture(async (fixture) => {
  303. const statePath = join(fixture.launchCwd, "state.json");
  304. await writeFile(statePath, JSON.stringify(VALID_STATE));
  305. await chmod(statePath, 0o600);
  306. const ctx = createContext(["tui", "--browser-use=headless", "--browser-state", statePath]);
  307. const exitCode = await run(ctx, {
  308. ...fixture.deps,
  309. runTui: async (options) => {
  310. await options.loadStartupOptions?.();
  311. return 0;
  312. },
  313. });
  314. assert.equal(exitCode, 0);
  315. assert.ok(fixture.appCount() > 0, "the TUI creates its first app at startup");
  316. assert.ok(fixture.runtimeStatePaths.length > 0);
  317. for (const path of fixture.runtimeStatePaths) assert.equal(path, statePath);
  318. }));
  319. function escapeRegExp(value: string): string {
  320. return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
  321. }