taskIndexRepoWorkspaceIdentity.test.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import { seedTaskIndex } from "./helpers/taskIndexFixture.js";
  2. import { mkdtempSync, rmSync } from "node:fs";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  6. import type { ZCodeTaskMeta } from "@zcode/shared";
  7. import { setDataBaseDir } from "#src/paths.js";
  8. import { TaskIndexRepo } from "#src/session/taskIndexRepo.js";
  9. let repo: TaskIndexRepo;
  10. let tempDir: string;
  11. beforeEach(() => {
  12. tempDir = mkdtempSync(join(tmpdir(), "zcode-task-index-workspace-identity-"));
  13. setDataBaseDir(tempDir);
  14. repo = new TaskIndexRepo();
  15. });
  16. afterEach(async () => {
  17. repo.close();
  18. setDataBaseDir(null);
  19. // Windows 需要等待 SQLite 释放文件句柄,避免临时目录清理出现 EPERM。
  20. await new Promise((resolve) => setTimeout(resolve, 50));
  21. rmSync(tempDir, { recursive: true, force: true });
  22. });
  23. function task(params: {
  24. taskId: string;
  25. workspaceIdentity: string;
  26. title?: string;
  27. }): ZCodeTaskMeta {
  28. return {
  29. taskId: params.taskId,
  30. traceId: `trace-${params.taskId}`,
  31. title: params.title ?? params.taskId,
  32. workspacePath: "/workspace/project",
  33. workspaceIdentity: params.workspaceIdentity,
  34. createdAt: 10,
  35. updatedAt: 20,
  36. mode: "default",
  37. provider: "glm",
  38. status: "running",
  39. };
  40. }
  41. function getRepoDatabase(target: TaskIndexRepo): {
  42. prepare(sql: string): {
  43. run(...params: unknown[]): unknown;
  44. };
  45. } {
  46. return (
  47. target as unknown as {
  48. getDatabase(): {
  49. prepare(sql: string): {
  50. run(...params: unknown[]): unknown;
  51. };
  52. };
  53. }
  54. ).getDatabase();
  55. }
  56. function metaJsonWithoutWorkspaceIdentity(meta: ZCodeTaskMeta): string {
  57. const legacyMeta: Partial<ZCodeTaskMeta> = { ...meta };
  58. delete legacyMeta.workspaceIdentity;
  59. return JSON.stringify(legacyMeta);
  60. }
  61. describe("TaskIndexRepo workspace identity normalization", () => {
  62. it("归档条件删除只影响相同路径下指定 identity,冷启动仍保留 tombstone", async () => {
  63. const first = task({
  64. taskId: "same-id",
  65. workspaceIdentity: "remote:ssh:first:22:coder:/workspace/project",
  66. });
  67. const second = task({
  68. taskId: "same-id",
  69. workspaceIdentity: "remote:ssh:second:22:coder:/workspace/project",
  70. });
  71. for (const meta of [first, second]) {
  72. await seedTaskIndex(repo, { meta });
  73. await repo.updateTaskState({ ...meta, patch: { archived: true } });
  74. }
  75. expect(await repo.deleteArchivedTask(first)).toEqual(
  76. expect.objectContaining({ taskId: first.taskId }),
  77. );
  78. repo.close();
  79. repo = new TaskIndexRepo();
  80. expect(await repo.getTaskMeta(first)).toBeNull();
  81. expect(await repo.getTaskMeta(second)).toEqual(
  82. expect.objectContaining({ workspaceIdentity: second.workspaceIdentity }),
  83. );
  84. expect(await repo.deleteArchivedTask(first)).toBeNull();
  85. });
  86. it("以 SQLite remote workspace_key 覆盖 SSH 旧列和 meta_json 中过期的 identity", async () => {
  87. const workspaceIdentity = "remote:ssh:dev.example.test:22:coder:/workspace/project";
  88. const staleWorkspaceIdentity = "remote:ssh:stale.example.test:22:coder:/workspace/project";
  89. const meta = task({ taskId: "ssh-running", workspaceIdentity });
  90. await seedTaskIndex(repo, { meta });
  91. getRepoDatabase(repo)
  92. .prepare(
  93. `UPDATE tasks
  94. SET workspace_identity = ?, meta_json = ?
  95. WHERE workspace_key = ? AND task_id = ?`,
  96. )
  97. .run(
  98. staleWorkspaceIdentity,
  99. JSON.stringify({
  100. ...meta,
  101. workspaceIdentity: staleWorkspaceIdentity,
  102. }),
  103. workspaceIdentity,
  104. meta.taskId,
  105. );
  106. await expect(
  107. repo.listTaskMetas({
  108. workspacePath: meta.workspacePath,
  109. workspaceIdentity,
  110. }),
  111. ).resolves.toEqual([
  112. expect.objectContaining({
  113. taskId: meta.taskId,
  114. workspacePath: meta.workspacePath,
  115. workspaceIdentity,
  116. }),
  117. ]);
  118. });
  119. it("WSL 旧行 identity 列为空时从合法 remote workspace_key 恢复", async () => {
  120. const workspaceIdentity = "remote:wsl:ubuntu:/workspace/project";
  121. const meta = task({ taskId: "wsl-running", workspaceIdentity });
  122. await seedTaskIndex(repo, { meta });
  123. getRepoDatabase(repo)
  124. .prepare(
  125. `UPDATE tasks
  126. SET workspace_identity = NULL, meta_json = ?
  127. WHERE workspace_key = ? AND task_id = ?`,
  128. )
  129. .run(metaJsonWithoutWorkspaceIdentity(meta), workspaceIdentity, meta.taskId);
  130. await expect(
  131. repo.listTaskMetas({
  132. workspacePath: meta.workspacePath,
  133. workspaceIdentity,
  134. }),
  135. ).resolves.toEqual([
  136. expect.objectContaining({
  137. taskId: meta.taskId,
  138. workspaceIdentity,
  139. }),
  140. ]);
  141. });
  142. it("相同 path 和 taskId 的不同 SSH identity 仍保持隔离", async () => {
  143. const identityA = "remote:ssh:a.example.test:22:coder:/workspace/project";
  144. const identityB = "remote:ssh:b.example.test:22:coder:/workspace/project";
  145. const taskA = task({
  146. taskId: "shared-task",
  147. workspaceIdentity: identityA,
  148. title: "host-a",
  149. });
  150. const taskB = task({
  151. taskId: "shared-task",
  152. workspaceIdentity: identityB,
  153. title: "host-b",
  154. });
  155. await seedTaskIndex(repo, { meta: taskA });
  156. await seedTaskIndex(repo, { meta: taskB });
  157. const database = getRepoDatabase(repo);
  158. database
  159. .prepare(
  160. `UPDATE tasks
  161. SET meta_json = ?
  162. WHERE workspace_key = ? AND task_id = ?`,
  163. )
  164. .run(metaJsonWithoutWorkspaceIdentity(taskA), identityA, taskA.taskId);
  165. database
  166. .prepare(
  167. `UPDATE tasks
  168. SET meta_json = ?
  169. WHERE workspace_key = ? AND task_id = ?`,
  170. )
  171. .run(metaJsonWithoutWorkspaceIdentity(taskB), identityB, taskB.taskId);
  172. const [listedA, listedB] = await Promise.all([
  173. repo.listTaskMetas({
  174. workspacePath: taskA.workspacePath,
  175. workspaceIdentity: identityA,
  176. }),
  177. repo.listTaskMetas({
  178. workspacePath: taskB.workspacePath,
  179. workspaceIdentity: identityB,
  180. }),
  181. ]);
  182. expect(listedA).toEqual([
  183. expect.objectContaining({
  184. title: "host-a",
  185. workspaceIdentity: identityA,
  186. }),
  187. ]);
  188. expect(listedB).toEqual([
  189. expect.objectContaining({
  190. title: "host-b",
  191. workspaceIdentity: identityB,
  192. }),
  193. ]);
  194. });
  195. });
  196. describe("TaskIndexRepo migration startup barrier", () => {
  197. it("records project migrations before serving queries and does not import settings again on reopen", async () => {
  198. repo.close();
  199. repo = new TaskIndexRepo({
  200. lastWorkspaceSession: [
  201. { kind: "local", workspacePath: "/repo/upgrade", workspacePurpose: "project" },
  202. ],
  203. });
  204. await repo.ensureReady();
  205. const db = getRepoDatabase(repo) as unknown as { prepare(sql: string): { all(): unknown[] } };
  206. // 修复原因:新增 0006 后旧断言仍只允许 0005,导致正确完成迁移也阻塞 pre-push。
  207. // 明确验证当前两项迁移及重开幂等性,不依赖 SQLite 的隐式返回顺序。
  208. const expectedMigrations = [{ id: "0005_projects" }, { id: "0006_default_workspace_tasks" }];
  209. expect(db.prepare("select id from schema_migration order by id").all()).toEqual(
  210. expectedMigrations,
  211. );
  212. expect(db.prepare("select root_path from project_roots").all()).toContainEqual({
  213. root_path: "/repo/upgrade",
  214. });
  215. repo.close();
  216. repo = new TaskIndexRepo({
  217. lastWorkspaceSession: [
  218. { kind: "local", workspacePath: "/repo/should-not-reappear", workspacePurpose: "project" },
  219. ],
  220. });
  221. await repo.ensureReady();
  222. const reopened = getRepoDatabase(repo) as unknown as {
  223. prepare(sql: string): { all(): unknown[] };
  224. };
  225. expect(reopened.prepare("select id from schema_migration order by id").all()).toEqual(
  226. expectedMigrations,
  227. );
  228. expect(reopened.prepare("select root_path from project_roots").all()).not.toContainEqual({
  229. root_path: "/repo/should-not-reappear",
  230. });
  231. });
  232. });
  233. describe("CLI facts mirror", () => {
  234. it("keeps CLI activity times through title, pin and archive mutations and assigns new tasks once", async () => {
  235. const meta = {
  236. ...task({ taskId: "facts", workspaceIdentity: "" }),
  237. workspacePath: "/outside/default",
  238. updatedAt: 20,
  239. };
  240. await repo.applyCliFacts({ meta, titleSource: "custom", lastOutcome: "error" });
  241. await repo.updateTaskState({ ...meta, patch: { pinned: true, archived: true } });
  242. const projects = await repo.getProjectRepository();
  243. const first = projects.readTree().tasks.find((entry) => entry.taskId === "facts");
  244. expect(first).toMatchObject({
  245. projectId: null,
  246. title: "facts",
  247. updatedAt: 20,
  248. status: "error",
  249. pinned: true,
  250. archived: true,
  251. });
  252. projects.saveProject({ roots: [meta.workspacePath] });
  253. await repo.applyCliFacts({
  254. meta: { ...meta, title: "CLI renamed" },
  255. titleSource: "custom",
  256. lastOutcome: "error",
  257. });
  258. expect(projects.readTree().tasks.find((entry) => entry.taskId === "facts")).toMatchObject({
  259. projectId: null,
  260. title: "CLI renamed",
  261. updatedAt: 20,
  262. });
  263. });
  264. });