claudeNativeSessionImportFlow.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import { seedTaskIndex } from "./helpers/taskIndexFixture.js";
  2. import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. const originalHome = process.env.HOME;
  7. const tempDirs: string[] = [];
  8. function makeTempDir(prefix: string): string {
  9. const dir = mkdtempSync(join(tmpdir(), prefix));
  10. tempDirs.push(dir);
  11. return dir;
  12. }
  13. afterEach(async () => {
  14. process.env.HOME = originalHome;
  15. delete process.env.ZCODE_DATA_BASE_DIR;
  16. vi.doUnmock("node:os");
  17. // Windows:等待一下让文件句柄释放
  18. await new Promise((resolve) => setTimeout(resolve, 50));
  19. while (tempDirs.length > 0) {
  20. const dir = tempDirs.pop();
  21. if (dir) {
  22. try {
  23. rmSync(dir, { recursive: true, force: true });
  24. } catch {
  25. // Windows 有时仍会有权限问题,忽略即可
  26. }
  27. }
  28. }
  29. });
  30. describe("Claude native import flow", () => {
  31. it("将 Claude jsonl 归一为 ZCodeSessionFile 并写入 legacy snapshot", async () => {
  32. const home = makeTempDir("zcode-claude-import-flow-");
  33. process.env.HOME = home;
  34. process.env.ZCODE_DATA_BASE_DIR = home;
  35. vi.resetModules();
  36. vi.doMock("node:os", async () => {
  37. const actual = await vi.importActual<typeof import("node:os")>("node:os");
  38. return { ...actual, homedir: () => home };
  39. });
  40. const workspacePath = "/repo/import-flow";
  41. const sessionId = "session-flow";
  42. const nativePath = join(home, ".claude", "projects", "-repo-import-flow", `${sessionId}.jsonl`);
  43. mkdirSync(join(home, ".claude", "projects", "-repo-import-flow"), { recursive: true });
  44. writeFileSync(
  45. nativePath,
  46. [
  47. JSON.stringify({
  48. type: "user",
  49. cwd: workspacePath,
  50. timestamp: "2026-04-16T11:00:00.000Z",
  51. message: { content: "迁移测试问题" },
  52. }),
  53. JSON.stringify({
  54. type: "assistant",
  55. cwd: workspacePath,
  56. model: "claude-sonnet-4-5-20250929",
  57. timestamp: "2026-04-16T11:01:00.000Z",
  58. message: { content: [{ type: "text", text: "迁移测试回答" }] },
  59. }),
  60. ].join("\n") + "\n",
  61. "utf-8",
  62. );
  63. const { parseClaudeNativeSessionFile } =
  64. await import("#src/session/claude-native/claudeNativeSessionImportParser.js");
  65. const { buildImportedClaudeTaskFile, buildImportedClaudeTaskId } =
  66. await import("#src/session/claude-native/buildImportedClaudeTaskFile.js");
  67. const { writeImportedClaudeTaskSnapshot } =
  68. await import("#src/session/claude-native/persistImportedClaudeTask.js");
  69. const { TaskIndexRepo } = await import("#src/session/taskIndexRepo.js");
  70. const { getLegacyTaskSessionSnapshotPath } = await import("#src/paths.js");
  71. const importedSource = await parseClaudeNativeSessionFile({
  72. filePath: nativePath,
  73. workspacePath,
  74. sessionId,
  75. });
  76. const sessionFile = buildImportedClaudeTaskFile(importedSource);
  77. const taskId = buildImportedClaudeTaskId(workspacePath, sessionId);
  78. expect(sessionFile.meta).toMatchObject({
  79. taskId,
  80. migrationSource: "claudeCode",
  81. workspacePath,
  82. status: "completed",
  83. });
  84. expect(sessionFile.meta).not.toHaveProperty("mode");
  85. expect(sessionFile.meta).not.toHaveProperty("model");
  86. expect(sessionFile.meta).not.toHaveProperty("provider");
  87. expect(sessionFile.messages).toHaveLength(2);
  88. expect(sessionFile.messages[0]?.role).toBe("user");
  89. expect(sessionFile.messages[1]?.role).toBe("assistant");
  90. expect(sessionFile.messages[1]).not.toHaveProperty("model");
  91. const repo = new TaskIndexRepo();
  92. await writeImportedClaudeTaskSnapshot({ sessionFile });
  93. const snapshotPath = getLegacyTaskSessionSnapshotPath(workspacePath, taskId);
  94. expect(existsSync(snapshotPath)).toBe(true);
  95. const persisted = JSON.parse(readFileSync(snapshotPath, "utf-8")) as {
  96. meta: {
  97. migrationSource?: string;
  98. taskId: string;
  99. mode?: string;
  100. model?: string;
  101. provider?: string;
  102. };
  103. messages: Array<{ role: string; model?: string }>;
  104. };
  105. expect(persisted.meta.migrationSource).toBe("claudeCode");
  106. expect(persisted.meta.taskId).toBe(taskId);
  107. expect(persisted.meta.mode).toBeUndefined();
  108. expect(persisted.meta.model).toBeUndefined();
  109. expect(persisted.meta.provider).toBeUndefined();
  110. expect(persisted.messages).toHaveLength(2);
  111. expect(persisted.messages[1]?.model).toBeUndefined();
  112. // 备份写入不能凭空创建索引;只有真实 CLI 导入完成后才出现任务。
  113. expect(await repo.listTaskMetas({ workspacePath })).toEqual([]);
  114. repo.close();
  115. });
  116. // Windows 上跳过此测试:路径编码逻辑与 Unix 不兼容,需要重构路径处理逻辑
  117. if (process.platform !== "win32") {
  118. it("导入为真实 ZCode session,保留续聊和切模型能力", async () => {
  119. const home = makeTempDir("zcode-claude-import-live-");
  120. process.env.HOME = home;
  121. process.env.ZCODE_DATA_BASE_DIR = home;
  122. vi.resetModules();
  123. vi.doMock("node:os", async () => {
  124. const actual = await vi.importActual<typeof import("node:os")>("node:os");
  125. return { ...actual, homedir: () => home };
  126. });
  127. const workspacePath = makeTempDir("zcode-claude-import-workspace-");
  128. // Windows 上 workspacePath 是 C:\...格式,用posix 路径格式避免 Windows 路径解析问题
  129. const encodedWorkspace = "ws_" + workspacePath.replace(/[/\\]/g, "_");
  130. const sessionId = "session-live";
  131. // 先把 home转换为正斜杠格式
  132. const homeSlash = home.replace(/\\/g, "/");
  133. // 使用正斜杠路径(Unix风格),Node.js 可以识别
  134. const projectsDir = homeSlash + "/.claude/projects/" + encodedWorkspace;
  135. const nativePath = projectsDir + "/" + sessionId + ".jsonl";
  136. mkdirSync(projectsDir, { recursive: true });
  137. writeFileSync(
  138. nativePath,
  139. [
  140. JSON.stringify({
  141. type: "user",
  142. cwd: workspacePath,
  143. timestamp: "2026-04-16T11:00:00.000Z",
  144. message: { content: "导入后继续聊" },
  145. }),
  146. JSON.stringify({
  147. type: "assistant",
  148. cwd: workspacePath,
  149. model: "claude-sonnet-4-5-20250929",
  150. timestamp: "2026-04-16T11:01:00.000Z",
  151. message: { content: [{ type: "text", text: "可以继续" }] },
  152. }),
  153. ].join("\n") + "\n",
  154. "utf-8",
  155. );
  156. const { importClaudeNativeSessions } =
  157. await import("#src/session/claude-native/claudeNativeSessionImportService.js");
  158. const { TaskIndexRepo } = await import("#src/session/taskIndexRepo.js");
  159. const { getLegacyTaskSessionSnapshotPath } = await import("#src/paths.js");
  160. const repo = new TaskIndexRepo();
  161. await seedTaskIndex(repo, {
  162. meta: {
  163. taskId: "sess_imported_deleted",
  164. traceId: "trace_old_hidden_import",
  165. title: "Hidden imported task",
  166. workspacePath,
  167. createdAt: 1,
  168. updatedAt: 2,
  169. mode: "default",
  170. model: "glm:glm-4.6",
  171. provider: "glm",
  172. migrationSource: "claudeCode",
  173. status: "completed",
  174. },
  175. archived: true,
  176. deleted: true,
  177. });
  178. const createdSessions: unknown[] = [];
  179. const result = await importClaudeNativeSessions({
  180. taskIndexRepo: repo,
  181. workspacePath,
  182. sessionIds: [sessionId],
  183. createImportedSession: async (source) => {
  184. createdSessions.push(source);
  185. return seedTaskIndex(repo, {
  186. meta: {
  187. taskId: "sess_imported_live",
  188. traceId: "trace_sess_imported_live",
  189. title: source.title ?? "Imported",
  190. workspacePath: source.workspacePath,
  191. createdAt: source.createdAt,
  192. updatedAt: source.updatedAt,
  193. mode: "default",
  194. model: "glm:glm-4.6",
  195. provider: "glm",
  196. migrationSource: "claudeCode",
  197. status: "completed",
  198. },
  199. });
  200. },
  201. onTaskImported: () => {},
  202. });
  203. expect(result.imported).toMatchObject([
  204. {
  205. provider: "claude",
  206. sessionId,
  207. taskId: "sess_imported_live",
  208. workspacePath,
  209. },
  210. ]);
  211. expect(createdSessions).toHaveLength(1);
  212. const snapshotPath = getLegacyTaskSessionSnapshotPath(workspacePath, "sess_imported_live");
  213. const persisted = JSON.parse(readFileSync(snapshotPath, "utf-8")) as {
  214. meta: { taskId: string; mode?: string; model?: string; provider?: string };
  215. messages: Array<{ role: string; model?: string }>;
  216. };
  217. expect(persisted.meta.taskId).toBe("sess_imported_live");
  218. expect(persisted.meta.mode).toBeUndefined();
  219. expect(persisted.meta.model).toBeUndefined();
  220. expect(persisted.meta.provider).toBeUndefined();
  221. expect(persisted.messages[1]?.model).toBeUndefined();
  222. const listed = await repo.listTaskMetas({ workspacePath });
  223. expect(listed.find((item) => item.taskId === "sess_imported_live")).toMatchObject({
  224. taskId: "sess_imported_live",
  225. model: "glm:glm-4.6",
  226. provider: "glm",
  227. migrationSource: "claudeCode",
  228. });
  229. await expect(
  230. repo.queryTaskList({
  231. workspaceScopes: [{ workspacePath }],
  232. kind: "active",
  233. provider: "glm",
  234. search: "可以继续",
  235. }),
  236. ).resolves.toMatchObject({
  237. items: [expect.objectContaining({ taskId: "sess_imported_live" })],
  238. total: 1,
  239. });
  240. await expect(repo.listTaskMetas({ workspacePath, archived: false })).resolves.toEqual([
  241. expect.objectContaining({
  242. taskId: "sess_imported_live",
  243. migrationSource: "claudeCode",
  244. }),
  245. ]);
  246. });
  247. }
  248. it("保留 Claude 原生日志里的 API Error assistant 消息", async () => {
  249. const home = makeTempDir("zcode-claude-import-api-error-");
  250. process.env.HOME = home;
  251. process.env.ZCODE_DATA_BASE_DIR = home;
  252. vi.resetModules();
  253. vi.doMock("node:os", async () => {
  254. const actual = await vi.importActual<typeof import("node:os")>("node:os");
  255. return { ...actual, homedir: () => home };
  256. });
  257. const workspacePath = "/repo/import-api-error";
  258. const sessionId = "session-api-error";
  259. const nativePath = join(
  260. home,
  261. ".claude",
  262. "projects",
  263. "-repo-import-api-error",
  264. `${sessionId}.jsonl`,
  265. );
  266. mkdirSync(join(home, ".claude", "projects", "-repo-import-api-error"), { recursive: true });
  267. writeFileSync(
  268. nativePath,
  269. [
  270. JSON.stringify({
  271. type: "user",
  272. cwd: workspacePath,
  273. timestamp: "2026-04-16T11:00:00.000Z",
  274. message: { content: "hi" },
  275. }),
  276. JSON.stringify({
  277. type: "assistant",
  278. cwd: workspacePath,
  279. timestamp: "2026-04-16T11:01:00.000Z",
  280. model: "<synthetic>",
  281. isApiErrorMessage: true,
  282. message: {
  283. role: "assistant",
  284. model: "<synthetic>",
  285. content: [{ type: "text", text: "API Error: 402 Insufficient Balance" }],
  286. },
  287. }),
  288. ].join("\n") + "\n",
  289. "utf-8",
  290. );
  291. const { parseClaudeNativeSessionFile } =
  292. await import("#src/session/claude-native/claudeNativeSessionImportParser.js");
  293. const { buildImportedClaudeTaskFile } =
  294. await import("#src/session/claude-native/buildImportedClaudeTaskFile.js");
  295. const importedSource = await parseClaudeNativeSessionFile({
  296. filePath: nativePath,
  297. workspacePath,
  298. sessionId,
  299. });
  300. expect(importedSource.messages).toMatchObject([
  301. { role: "user", content: "hi" },
  302. { role: "assistant", content: "API Error: 402 Insufficient Balance" },
  303. ]);
  304. const sessionFile = buildImportedClaudeTaskFile(importedSource);
  305. expect(sessionFile.messages).toMatchObject([
  306. { role: "user", content: "hi" },
  307. { role: "assistant", content: "API Error: 402 Insufficient Balance" },
  308. ]);
  309. expect(sessionFile.messages[1]).not.toHaveProperty("model");
  310. });
  311. });