record-isolation.test.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import { deepStrictEqual, equal, ok, rejects } from "node:assert/strict";
  2. import { access, mkdtemp, readFile, readdir, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { after, before, describe, it } from "node:test";
  6. import type { PromptTrajectoryFixture } from "../src/fixture.js";
  7. import { recordPromptTrajectoryFromFixture } from "../src/record.js";
  8. import type { RequestEntry, TrajectoryJsonlEntry } from "../src/types.js";
  9. // 本文件跑真实录制,与 `record` 命令一样依赖已构建的 bootstrap dist。
  10. // 临时目录指向测试自己的沙箱:录制用的隔离家目录和工作区都落在沙箱里,结束后整体删除。
  11. const ENV_KEYS = ["HOME", "USERPROFILE", "ZCODE_STORAGE_DIR", "TMPDIR", "TMP", "TEMP"] as const;
  12. const ISOLATED_HOME_PREFIX = "zcode-prompt-trajectory-home-";
  13. function fixture(overrides: Partial<PromptTrajectoryFixture> = {}): PromptTrajectoryFixture {
  14. return {
  15. name: "record-isolation",
  16. model: {
  17. apiKey: "test-key",
  18. apiKeyRequired: false,
  19. id: "mock/mock-model",
  20. kind: "openai-compatible",
  21. upstreamBaseURL: "http://127.0.0.1:9/v1",
  22. },
  23. runtimeConfig: { mode: "yolo", modelStreaming: "off" },
  24. mockResponses: [
  25. {
  26. id: "mock-response",
  27. object: "chat.completion",
  28. created: 0,
  29. model: "mock-model",
  30. choices: [
  31. { index: 0, finish_reason: "stop", message: { role: "assistant", content: "done" } },
  32. ],
  33. usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
  34. },
  35. ],
  36. steps: [{ type: "submitPrompt", text: "hello recorder" }],
  37. ...overrides,
  38. };
  39. }
  40. async function exists(path: string): Promise<boolean> {
  41. return access(path).then(
  42. () => true,
  43. () => false,
  44. );
  45. }
  46. describe("prompt trajectory recording environment", () => {
  47. const previousEnv = new Map(ENV_KEYS.map((key) => [key, process.env[key]]));
  48. let sandbox: string;
  49. let runIndex = 0;
  50. before(async () => {
  51. sandbox = await mkdtemp(join(tmpdir(), "zcode-prompt-trajectory-record-test-"));
  52. for (const key of ["TMPDIR", "TMP", "TEMP"] as const) process.env[key] = sandbox;
  53. });
  54. after(async () => {
  55. for (const [key, value] of previousEnv) {
  56. if (value === undefined) delete process.env[key];
  57. else process.env[key] = value;
  58. }
  59. await rm(sandbox, { recursive: true, force: true });
  60. });
  61. const isolatedHomes = async () =>
  62. (await readdir(sandbox)).filter((name) => name.startsWith(ISOLATED_HOME_PREFIX));
  63. const record = async (input: PromptTrajectoryFixture) => {
  64. runIndex += 1;
  65. const outDir = join(sandbox, `out-${runIndex}`);
  66. await recordPromptTrajectoryFromFixture({ fixture: input, outDir });
  67. return outDir;
  68. };
  69. const firstRequestToolNames = async (outDir: string) => {
  70. const entries = (await readFile(join(outDir, "trajectory.jsonl"), "utf8"))
  71. .trim()
  72. .split("\n")
  73. .map((line) => JSON.parse(line) as TrajectoryJsonlEntry);
  74. const request = entries.find((entry): entry is RequestEntry => entry.kind === "request");
  75. ok(request, "录制没有写出请求");
  76. const tools = request.bodyWithoutMessages.tools as Array<{ function?: { name?: string } }>;
  77. return tools.map((tool) => tool.function?.name);
  78. };
  79. it("writes the session store under an isolated home and restores the environment afterwards", async () => {
  80. const home = join(sandbox, "user-home");
  81. const storage = join(sandbox, "user-storage");
  82. process.env.HOME = home;
  83. delete process.env.USERPROFILE;
  84. process.env.ZCODE_STORAGE_DIR = storage;
  85. const homesBefore = await isolatedHomes();
  86. await record(fixture());
  87. // 录制期间的会话库落在新建的隔离家目录,录制前的家目录和存储目录都没有被创建。
  88. const created = (await isolatedHomes()).filter((name) => !homesBefore.includes(name));
  89. equal(created.length, 1);
  90. ok(await exists(join(sandbox, created[0]!, ".zcode", "cli", "db", "db.sqlite")));
  91. equal(await exists(home), false);
  92. equal(await exists(storage), false);
  93. // 恢复原值;原来没有的变量要删掉,不能留下字符串 "undefined"。
  94. equal(process.env.HOME, home);
  95. equal(Object.hasOwn(process.env, "USERPROFILE"), false);
  96. equal(process.env.ZCODE_STORAGE_DIR, storage);
  97. });
  98. it("restores the environment when recording fails", async () => {
  99. const home = join(sandbox, "failing-home");
  100. const profile = join(sandbox, "failing-profile");
  101. process.env.HOME = home;
  102. process.env.USERPROFILE = profile;
  103. delete process.env.ZCODE_STORAGE_DIR;
  104. await rejects(record({ name: "missing-model", steps: [] }), /missing upstreamBaseURL/u);
  105. deepStrictEqual(
  106. [process.env.HOME, process.env.USERPROFILE, Object.hasOwn(process.env, "ZCODE_STORAGE_DIR")],
  107. [home, profile, false],
  108. );
  109. });
  110. it("exposes WebSearch only when the fixture declares native web search", async () => {
  111. process.env.HOME = join(sandbox, "web-search-home");
  112. // 能力只来自 fixture 的 modelProperties 写进 Registry 的模型声明。
  113. const withSearch = await firstRequestToolNames(
  114. await record(fixture({ modelProperties: { supportsNativeWebSearch: true } })),
  115. );
  116. const withoutSearch = await firstRequestToolNames(await record(fixture()));
  117. ok(withSearch.includes("WebSearch"));
  118. equal(withoutSearch.includes("WebSearch"), false);
  119. deepStrictEqual(
  120. withSearch.filter((name) => name !== "WebSearch"),
  121. withoutSearch,
  122. );
  123. });
  124. });