session-history-first-fixture.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. import { mkdir, readFile, writeFile } from "node:fs/promises";
  2. import { join, sep } from "node:path";
  3. import { DatabaseSync } from "node:sqlite";
  4. import { seedProviderReadinessHistoryFixture } from "./provider-readiness-history-fixture.js";
  5. export const HISTORY_FIRST_SESSION = "sess_e2e_history_first";
  6. export const HISTORY_FIRST_FAILED_SESSION = "sess_e2e_history_first_failed";
  7. export const HISTORY_FIRST_TEXT = "E2E_HISTORY_FIRST 已持久化的历史正文";
  8. export async function seedSessionHistoryFirstFixture(options: {
  9. cliEntryPoint: string;
  10. e2eHomeDir: string;
  11. workspacePath: string;
  12. providerId: string;
  13. modelId: string;
  14. thoughtLevel?: string;
  15. legacyTitleHandoff?: boolean;
  16. }) {
  17. for (const sessionId of options.legacyTitleHandoff
  18. ? [HISTORY_FIRST_SESSION]
  19. : [HISTORY_FIRST_SESSION, HISTORY_FIRST_FAILED_SESSION]) {
  20. await seedProviderReadinessHistoryFixture({
  21. ...options,
  22. history: {
  23. sessionId,
  24. title:
  25. sessionId === HISTORY_FIRST_SESSION ? "E2E_HISTORY_FIRST" : "E2E_HISTORY_FIRST_FAILURE",
  26. userText: "E2E_HISTORY_FIRST 历史问题",
  27. assistantText:
  28. sessionId === HISTORY_FIRST_SESSION
  29. ? HISTORY_FIRST_TEXT
  30. : `${HISTORY_FIRST_TEXT}\n\n${Array.from({ length: 80 }, (_, i) => `历史段落 ${i + 1}:初始化失败后仍可阅读。`).join("\n\n")}`,
  31. assistantInputTokens: 10,
  32. assistantOutputTokens: 10,
  33. modelId: options.modelId,
  34. runtimeProviderId: options.providerId,
  35. taskProviderId: "glm",
  36. },
  37. });
  38. // 通用 fixture 用于测试缺失 provider;此处补齐正式会话的 durable 模型选择,验证 ready 后续发。
  39. const database = new DatabaseSync(join(options.e2eHomeDir, ".zcode", "cli", "db", "db.sqlite"));
  40. try {
  41. // 旧版本可能保存不同的词法路径表示;真实 Host 仍从原 attachment 打开,不能靠迁库修正。
  42. if (sessionId === HISTORY_FIRST_SESSION) {
  43. database
  44. .prepare("UPDATE session SET directory = ?, path = ? WHERE id = ?")
  45. .run(options.workspacePath + sep, options.workspacePath + sep, sessionId);
  46. }
  47. database
  48. .prepare(`INSERT INTO session_entry (id, session_id, type, time_created, time_updated, data)
  49. VALUES (?, ?, 'runtime/model_selection', ?, ?, ?)`)
  50. .run(
  51. `entry_model_${sessionId}`,
  52. sessionId,
  53. Date.now(),
  54. Date.now(),
  55. JSON.stringify({
  56. modelSelection: {
  57. providerId: options.providerId,
  58. modelId: options.modelId,
  59. ...(options.thoughtLevel
  60. ? { options: { reasoningLevel: options.thoughtLevel } }
  61. : {}),
  62. },
  63. }),
  64. );
  65. } finally {
  66. database.close();
  67. }
  68. }
  69. if (!options.legacyTitleHandoff) {
  70. // 普通历史不带旧 Host 标题交接;迁移场景在独立 HOME 中保留旧意图并单独验收。
  71. const database = new DatabaseSync(
  72. join(options.e2eHomeDir, ".zcode", "v2", "tasks-index.sqlite"),
  73. );
  74. try {
  75. database
  76. .prepare(`UPDATE tasks SET title_overridden = 0,
  77. meta_json = json_set(meta_json, '$.titleOverridden', json('false'))
  78. WHERE task_id IN (?, ?)`)
  79. .run(HISTORY_FIRST_SESSION, HISTORY_FIRST_FAILED_SESSION);
  80. } finally {
  81. database.close();
  82. }
  83. } else {
  84. const database = new DatabaseSync(join(options.e2eHomeDir, ".zcode", "cli", "db", "db.sqlite"));
  85. try {
  86. // 两端标题不同,必须观察交接实际落盘,不能用本来相同的标题制造通过。
  87. database
  88. .prepare("UPDATE session SET title = 'E2E_BEFORE_TITLE_HANDOFF' WHERE id = ?")
  89. .run(HISTORY_FIRST_SESSION);
  90. } finally {
  91. database.close();
  92. }
  93. }
  94. const root = join(options.workspacePath, ".zcode", "history-first-e2e");
  95. await mkdir(root, { recursive: true });
  96. const script = join(root, "resume-gate.mjs");
  97. // 文件事件屏障证明首帧不等待 hook;不用固定 sleep 猜测初始化进度。
  98. await writeFile(
  99. script,
  100. `import { watch } from 'node:fs';
  101. import { writeFile, appendFile, access } from 'node:fs/promises';
  102. const [entered, release] = process.argv.slice(2);
  103. await appendFile(${JSON.stringify(join(root, "attempts"))}, 'resume\\n');
  104. await new Promise((resolve, reject) => {
  105. const checkReleased = async () => {
  106. try { await access(release); watcher.close(); resolve(); } catch {}
  107. };
  108. const watcher = watch(${JSON.stringify(root)}, checkReleased);
  109. watcher.on('error', reject);
  110. // 重启时 release 可能早已存在;先订阅再读条件,不能只依赖下一次目录事件。
  111. writeFile(entered, 'entered').then(checkReleased, reject);
  112. });
  113. process.stdout.write('{}');
  114. `,
  115. );
  116. const config = join(options.e2eHomeDir, ".zcode", "cli", "config.json");
  117. const settings = JSON.parse(await readFile(config, "utf8").catch(() => "{}"));
  118. await writeFile(
  119. config,
  120. JSON.stringify({
  121. ...settings,
  122. hooks: {
  123. enabled: true,
  124. events: {
  125. SessionStart: [
  126. {
  127. matcher: "resume",
  128. hooks: [
  129. {
  130. type: "process",
  131. command: process.execPath,
  132. args: [script, join(root, "entered"), join(root, "release")],
  133. timeoutMs: 120_000,
  134. },
  135. ],
  136. },
  137. ],
  138. },
  139. },
  140. }),
  141. );
  142. }