claudeNativeSessionImportFlow.test.ts 13 KB

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