v4-worktree-cwd.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. // 受管 worktree = 会话 cwd(docs/git/worktree.md §1.1 / §9.3)集成验收:
  2. // 真实 git 仓库 + 真实 linked worktree(<dataBaseDir>/.zcode/worktrees/<bucket>/<repo>)+
  3. // 真 sqlite sessionStore + ZCodeProtocolAgentServer + 真 app。
  4. // 覆盖:能力声明、createSession.cwd(key 属于项目、执行路径是 worktree、权限/记忆映射回源仓库)、
  5. // "已创建 worktree" 首轮落盘并在首个用户输入之前投影、冷恢复(Host key + 存储 cwd)、
  6. // forkAssistant.targetCwd(同一进程注册、追加标记、幂等)、worktreeSessionIds 冷列表。
  7. import { execFile } from "node:child_process";
  8. import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
  9. import { tmpdir } from "node:os";
  10. import { join } from "node:path";
  11. import { promisify } from "node:util";
  12. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  13. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  14. import {
  15. zcodeProtocolMethods,
  16. zcodeRuntimeCapabilitiesSchema,
  17. type ZCodeProtocolMessage,
  18. } from "@zcode/shared";
  19. import {
  20. V4_METHODS,
  21. V4_NOTIFICATIONS,
  22. commandAckSchema,
  23. conversationTopic,
  24. conversationTopicFrameSchema,
  25. routedTopicWireFrameSchema,
  26. sessionsIndexTopic,
  27. sessionsIndexTopicFrameSchema,
  28. type ConversationSnapshot,
  29. } from "@zcode/shared/zcode-protocol-v4";
  30. import type {
  31. MessageId,
  32. MessagePart,
  33. ModelId,
  34. ModelProviderId,
  35. SessionId,
  36. } from "@zcode/contracts";
  37. import { ZCodeProtocolAgentServer } from "../src/zcode-protocol/server.js";
  38. import { projectIdFromDirectory } from "../src/app/paths.js";
  39. import type { ZCodeApp, ZCodeAppOptions } from "../src/app/types.js";
  40. import {
  41. createRegistryBackedTestApp,
  42. createTestProviderRegistry,
  43. } from "./helpers/registry-backed-test-app.js";
  44. const execFileAsync = promisify(execFile);
  45. const BUCKET = "3f2a";
  46. const REPO = "repo";
  47. const MODEL = { providerId: "zai", modelId: "glm-4.6" };
  48. const WORKTREE_CREATION_OUTPUT = "Preparing worktree (detached HEAD)\nHEAD is now at abc\n";
  49. const PARENT_SESSION_ID = "sess_worktree_fork_parent";
  50. type Booted = Awaited<ReturnType<typeof bootServer>>;
  51. /** 父会话直接落 sqlite(项目主目录),冷订阅即可得到可 fork 的 assistant 行,不依赖模型。 */
  52. async function seedParentSession(dbPath: string, directory: string) {
  53. const store = await createSqliteSessionStore({ dbPath });
  54. const sessionID = PARENT_SESSION_ID as SessionId;
  55. try {
  56. await store.createSession({
  57. id: sessionID,
  58. projectID: projectIdFromDirectory(directory),
  59. slug: "worktree-fork-parent",
  60. directory,
  61. path: directory,
  62. title: "Worktree fork parent",
  63. version: "test-version",
  64. time: { created: 1, updated: 2 },
  65. });
  66. for (const [index, role, text] of [
  67. [1, "user", "父任务问题"],
  68. [2, "assistant", "父任务回答"],
  69. ] as const) {
  70. const id = `msg_wt_fork_${role}` as MessageId;
  71. await store.saveMessage(
  72. role === "user"
  73. ? {
  74. id,
  75. sessionID,
  76. role,
  77. time: { created: index },
  78. agent: "zcode-agent",
  79. model: { providerID: MODEL.providerId as ModelProviderId, modelID: MODEL.modelId as ModelId },
  80. tools: {},
  81. }
  82. : {
  83. id,
  84. sessionID,
  85. role,
  86. time: { created: index, completed: index },
  87. parentID: "msg_wt_fork_user" as MessageId,
  88. providerID: MODEL.providerId as ModelProviderId,
  89. modelID: MODEL.modelId as ModelId,
  90. mode: "build",
  91. agent: "zcode-agent",
  92. path: { cwd: directory, root: directory },
  93. cost: 0,
  94. tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
  95. },
  96. );
  97. await store.savePart({
  98. id: `${id}_text` as MessagePart["id"],
  99. sessionID,
  100. messageID: id,
  101. type: "text",
  102. text,
  103. time: { start: index, end: index },
  104. });
  105. }
  106. } finally {
  107. store.close();
  108. }
  109. }
  110. async function git(cwd: string, ...args: string[]): Promise<string> {
  111. const { stdout } = await execFileAsync(
  112. "git",
  113. ["-c", "user.name=ZCode Test", "-c", "user.email=test@example.com", ...args],
  114. { cwd },
  115. );
  116. return stdout.trim();
  117. }
  118. async function fixture(root: string) {
  119. const source = join(root, "projects", REPO);
  120. const dataBaseDir = join(root, "data");
  121. const worktree = join(dataBaseDir, ".zcode", "worktrees", BUCKET, REPO);
  122. const plain = join(root, "plain");
  123. await mkdir(source, { recursive: true });
  124. await mkdir(plain, { recursive: true });
  125. await writeFile(join(source, "README.md"), "hello\n");
  126. await git(source, "init", "-q");
  127. await git(source, "add", ".");
  128. await git(source, "commit", "-qm", "init");
  129. await mkdir(join(dataBaseDir, ".zcode", "worktrees", BUCKET), { recursive: true });
  130. await git(source, "worktree", "add", "--detach", worktree, "HEAD");
  131. const sha = await git(worktree, "rev-parse", "HEAD");
  132. return { source, dataBaseDir, worktree, plain, sha };
  133. }
  134. async function bootServer(dbPath: string, dataBaseDir: string) {
  135. const store = await createSqliteSessionStore({ dbPath });
  136. const apps: Array<{ app: ZCodeApp; options: Omit<ZCodeAppOptions, "providerRegistry"> }> = [];
  137. const env = { ZCODE_DATA_BASE_DIR: dataBaseDir };
  138. const providerRegistry = createTestProviderRegistry([MODEL]);
  139. const server = new ZCodeProtocolAgentServer({
  140. cwd: process.cwd(),
  141. env,
  142. sessionStore: store,
  143. createZCodeApp: async (options = {}) => {
  144. const app = await createRegistryBackedTestApp({
  145. ...options,
  146. // 内置 MCP 子进程与本用例无关,关闭避免进程握手噪声。
  147. runtimeConfig: { ...options.runtimeConfig, mcp: { enabled: false } },
  148. env,
  149. skipUserConfig: true,
  150. providerRegistry,
  151. modelExecutor: {
  152. async generateText() {
  153. return {
  154. finishReason: "stop" as const,
  155. text: "worktree answer",
  156. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  157. };
  158. },
  159. async *streamText() {
  160. yield { type: "text_delta" as const, text: "worktree answer" };
  161. yield { type: "finish" as const, finishReason: "stop" as const, usage: {} };
  162. },
  163. },
  164. });
  165. apps.push({ app, options });
  166. return app;
  167. },
  168. });
  169. server.setNotificationSink((message) => {
  170. if (!("id" in message)) return;
  171. if (message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences) {
  172. void server.handleMessage({
  173. id: message.id,
  174. result: { nativeSearchEnhancementsEnabled: false, memoryEnabled: false },
  175. });
  176. }
  177. });
  178. return {
  179. server,
  180. store,
  181. apps,
  182. close: async () => {
  183. await server.shutdown();
  184. server.disposeProjections();
  185. for (const { app } of apps) await app.close();
  186. store.close();
  187. },
  188. };
  189. }
  190. async function requestResult(server: ZCodeProtocolAgentServer, message: ZCodeProtocolMessage) {
  191. const response = await server.handleMessage(message);
  192. if (!response || !("result" in response)) {
  193. throw new Error(`Expected protocol success response: ${JSON.stringify(response)}`);
  194. }
  195. return response.result;
  196. }
  197. function takeInitialFrame(server: ZCodeProtocolAgentServer, requestId: string) {
  198. const messages = server.takePostResponseMessages(requestId);
  199. const frameMessage = messages.find(
  200. (message) => "method" in message && message.method === V4_NOTIFICATIONS.conversationFrame,
  201. );
  202. if (!frameMessage) throw new Error("Expected an initial conversation frame");
  203. const wire = routedTopicWireFrameSchema.parse((frameMessage as { params: unknown }).params);
  204. if (wire.kind !== "complete") throw new Error("Expected one complete physical wire");
  205. return wire.frame;
  206. }
  207. async function conversationSnapshot(
  208. booted: Booted,
  209. sessionId: string,
  210. workspace?: { workspaceKey: string; workspacePath: string },
  211. ): Promise<ConversationSnapshot> {
  212. const id = `subscribe-${sessionId}-${Math.random()}`;
  213. await requestResult(booted.server, {
  214. id,
  215. method: V4_METHODS.conversationSubscribe,
  216. params: {
  217. topic: conversationTopic(sessionId),
  218. connectionId: id,
  219. clientMode: "desktop-continuous",
  220. ...(workspace ? { workspace } : {}),
  221. },
  222. });
  223. const frame = conversationTopicFrameSchema.parse(takeInitialFrame(booted.server, id));
  224. if (frame.payload.kind !== "snapshot") throw new Error("Expected conversation snapshot");
  225. return frame.payload.snapshot;
  226. }
  227. async function sessionsIndexIds(
  228. booted: Booted,
  229. workspaceId: string,
  230. worktreeSessionIds?: string[],
  231. ): Promise<string[]> {
  232. const id = `index-${workspaceId}-${Math.random()}`;
  233. await requestResult(booted.server, {
  234. id,
  235. method: V4_METHODS.conversationSubscribe,
  236. params: {
  237. topic: sessionsIndexTopic(workspaceId),
  238. connectionId: id,
  239. clientMode: "desktop-continuous",
  240. ...(worktreeSessionIds ? { worktreeSessionIds } : {}),
  241. },
  242. });
  243. const frame = sessionsIndexTopicFrameSchema.parse(takeInitialFrame(booted.server, id));
  244. if (frame.payload.kind !== "snapshot") throw new Error("Expected sessions-index snapshot");
  245. return frame.payload.snapshot.sessions.map((session) => session.sessionId).sort();
  246. }
  247. function command(
  248. id: string,
  249. type: string,
  250. payload: Record<string, unknown>,
  251. extra: { sessionId?: string | null; baseRevision?: number; baseLogEpoch?: string } = {},
  252. ) {
  253. return {
  254. id,
  255. method: V4_METHODS.command,
  256. params: {
  257. commandId: id,
  258. clientId: "client-worktree-cwd",
  259. sessionId: extra.sessionId ?? null,
  260. ...(extra.baseRevision !== undefined ? { baseRevision: extra.baseRevision } : {}),
  261. ...(extra.baseLogEpoch ? { baseLogEpoch: extra.baseLogEpoch } : {}),
  262. type,
  263. payload,
  264. issuedAt: 1_700_000_000_000,
  265. },
  266. };
  267. }
  268. async function waitFor(predicate: () => Promise<boolean>, timeoutMs = 10_000): Promise<void> {
  269. const deadline = Date.now() + timeoutMs;
  270. while (!(await predicate())) {
  271. if (Date.now() > deadline) throw new Error("waitFor timed out");
  272. await new Promise((resolve) => setTimeout(resolve, 20));
  273. }
  274. }
  275. function rowKinds(snapshot: ConversationSnapshot): string[] {
  276. return snapshot.rows.window.map((row) =>
  277. row.kind === "timelineMarker" ? `marker:${row.marker.type}` : row.kind,
  278. );
  279. }
  280. describe("受管 worktree 作为会话 cwd(集成:真 git worktree + sqlite + server + app)", { timeout: 30_000 }, () => {
  281. let root: string;
  282. let paths: Awaited<ReturnType<typeof fixture>>;
  283. beforeEach(async () => {
  284. // resolver 按 realpath 判定;macOS 临时目录是软链,fixture 统一用 realpath。
  285. root = await realpath(await mkdtemp(join(tmpdir(), "zcode-v4-worktree-cwd-")));
  286. paths = await fixture(root);
  287. });
  288. afterEach(async () => {
  289. await rm(root, { force: true, recursive: true });
  290. });
  291. it("runtime/capabilities 声明 worktreeCwd,不再声明 forkTargetWorkspace", async () => {
  292. const booted = await bootServer(join(root, "capabilities.db"), paths.dataBaseDir);
  293. try {
  294. const capabilities = await requestResult(booted.server, {
  295. id: "capabilities",
  296. method: zcodeProtocolMethods.runtimeCapabilities,
  297. params: {},
  298. });
  299. expect(capabilities).toMatchObject({ worktreeCwd: true });
  300. expect(capabilities).not.toHaveProperty("forkTargetWorkspace");
  301. } finally {
  302. await booted.close();
  303. }
  304. });
  305. it("runtime/capabilities 声明 conversationQuoteComment,App 才提供选区批注入口", async () => {
  306. const booted = await bootServer(join(root, "quote-comment.db"), paths.dataBaseDir);
  307. try {
  308. const capabilities = await requestResult(booted.server, {
  309. id: "capabilities-quote-comment",
  310. method: zcodeProtocolMethods.runtimeCapabilities,
  311. params: {},
  312. });
  313. expect(zcodeRuntimeCapabilitiesSchema.parse(capabilities)).toMatchObject({
  314. conversationQuoteComment: true,
  315. });
  316. } finally {
  317. await booted.close();
  318. }
  319. });
  320. it("createSession.cwd:key 属于项目、在 worktree 执行;首轮前落盘标记;冷恢复保持 cwd", async () => {
  321. const dbPath = join(root, "create.db");
  322. const live = await bootServer(dbPath, paths.dataBaseDir);
  323. let sessionId = "";
  324. try {
  325. const ack = commandAckSchema.parse(
  326. await requestResult(
  327. live.server,
  328. command("create-wt", "createSession", {
  329. workspaceId: paths.source,
  330. cwd: paths.worktree,
  331. worktreeCreation: {
  332. path: paths.worktree,
  333. sha: paths.sha,
  334. ref: null,
  335. output: WORKTREE_CREATION_OUTPUT,
  336. },
  337. firstInput: { text: "在 worktree 里工作", modelSelection: MODEL },
  338. }),
  339. ),
  340. );
  341. expect(ack.status).toBe("accepted");
  342. if (ack.result?.type !== "createSession") throw new Error("Expected createSession result");
  343. sessionId = ack.result.sessionId;
  344. const created = live.apps.at(-1)!;
  345. expect(created.options.runtimeConfig?.workingDirectory).toBe(paths.worktree);
  346. // Hook Trust 等对外字段使用项目 workspace key(§7.3)。
  347. expect(created.options.workspaceKey).toBe(paths.source);
  348. // MCP 工具调用与官方 MCP 授权头以会话 key 为身份(§9.3)。config 是 runtime 私有字段,
  349. // 这里只读校验 create-app 的接线。
  350. expect(
  351. (created.app.runtime as unknown as { config: { workspaceKey?: string } }).config.workspaceKey,
  352. ).toBe(paths.source);
  353. // 权限与记忆的项目身份映射回源仓库(§6.6.3)。
  354. expect(created.app.runtime.getProjectId()).toBe(projectIdFromDirectory(paths.source));
  355. await waitFor(async () => {
  356. const messages = await live.store.messages({ sessionID: sessionId as SessionId });
  357. return messages.some((message) => message.info.role === "user");
  358. });
  359. const stored = await live.store.getSession(sessionId as SessionId);
  360. expect(stored).toMatchObject({ directory: paths.worktree, path: paths.worktree });
  361. expect(stored?.workspaceID).toBeUndefined();
  362. const firstMessage = (await live.store.messages({ sessionID: sessionId as SessionId }))[0]!;
  363. expect(firstMessage.parts).toEqual([
  364. expect.objectContaining({
  365. type: "timeline",
  366. timelineType: "worktree_creation",
  367. worktreeCreation: {
  368. path: paths.worktree,
  369. sha: paths.sha,
  370. ref: null,
  371. output: WORKTREE_CREATION_OUTPUT,
  372. },
  373. }),
  374. ]);
  375. const liveKinds = rowKinds(await conversationSnapshot(live, sessionId));
  376. expect(liveKinds.indexOf("marker:worktreeCreated")).toBeGreaterThanOrEqual(0);
  377. expect(liveKinds.indexOf("marker:worktreeCreated")).toBeLessThan(
  378. liveKinds.indexOf("userInput"),
  379. );
  380. // live 记录按项目 key 进入项目的 sessions-index。
  381. expect(await sessionsIndexIds(live, paths.source)).toContain(sessionId);
  382. } finally {
  383. await live.close();
  384. }
  385. const cold = await bootServer(dbPath, paths.dataBaseDir);
  386. try {
  387. // 合并后激活预检也要认识受管 worktree,但普通目录不能借用项目 key 绕过归属校验。
  388. const wrongWorkspace = { workspaceKey: paths.source, workspacePath: paths.plain };
  389. const rejectedCold = await cold.server.handleMessage({
  390. id: "reject-foreign-cold-workspace",
  391. method: zcodeProtocolMethods.sessionLifecycleEnsureReady,
  392. params: { sessionId, workspace: wrongWorkspace },
  393. });
  394. expect(rejectedCold).toHaveProperty("error");
  395. expect(cold.apps).toHaveLength(0);
  396. // 冷列表:目录扫描看不到 worktree 会话,Host 用 worktreeSessionIds 精确提供。
  397. expect(await sessionsIndexIds(cold, paths.source)).not.toContain(sessionId);
  398. expect(await sessionsIndexIds(cold, paths.source, [sessionId, "sess_foreign"])).toContain(
  399. sessionId,
  400. );
  401. const snapshot = await conversationSnapshot(cold, sessionId, {
  402. workspaceKey: paths.source,
  403. workspacePath: paths.source,
  404. });
  405. const kinds = rowKinds(snapshot);
  406. expect(kinds.filter((kind) => kind === "marker:worktreeCreated")).toHaveLength(1);
  407. expect(kinds.indexOf("marker:worktreeCreated")).toBeLessThan(kinds.indexOf("userInput"));
  408. const resumed = cold.apps.at(-1)!;
  409. // 冷恢复:身份取 Host 请求(项目),执行路径取存储 cwd(I2)。
  410. expect(resumed.options.runtimeConfig?.workingDirectory).toBe(paths.worktree);
  411. // Gen UI 目录按 [workspace 路径, sessionId] 计算;冷恢复后 workspace 路径仍是 worktree,
  412. // fork 时按目标 cwd 算出的目录才与子会话自己的一致(core session-fork 的 targetCwd 用例)。
  413. expect(resumed.options.runtimeConfig?.workspacePath).toBe(paths.worktree);
  414. expect(resumed.options.workspaceKey).toBe(paths.source);
  415. await requestResult(cold.server, {
  416. id: "ensure-active-from-project",
  417. method: zcodeProtocolMethods.sessionLifecycleEnsureReady,
  418. params: {
  419. sessionId,
  420. workspace: { workspaceKey: paths.source, workspacePath: paths.source },
  421. },
  422. });
  423. const rejectedActive = await cold.server.handleMessage({
  424. id: "reject-foreign-active-workspace",
  425. method: zcodeProtocolMethods.sessionLifecycleEnsureReady,
  426. params: { sessionId, workspace: wrongWorkspace },
  427. });
  428. expect(rejectedActive).toHaveProperty("error");
  429. expect(cold.apps).toHaveLength(1);
  430. } finally {
  431. await cold.close();
  432. }
  433. // worktree 删除后:归属以创建时持久化的 projectID 为准,Host 提供的 id 仍能列出(§3.12)。
  434. await rm(paths.worktree, { recursive: true, force: true });
  435. const afterRemoval = await bootServer(dbPath, paths.dataBaseDir);
  436. try {
  437. expect(await sessionsIndexIds(afterRemoval, paths.source, [sessionId])).toContain(sessionId);
  438. } finally {
  439. await afterRemoval.close();
  440. }
  441. });
  442. it("冷恢复归属:Host key 大小写与磁盘不同、worktree 已删除时仍属于项目", async () => {
  443. const dbPath = join(root, "ownership.db");
  444. const live = await bootServer(dbPath, paths.dataBaseDir);
  445. let sessionId = "";
  446. try {
  447. const ack = commandAckSchema.parse(
  448. await requestResult(
  449. live.server,
  450. command("create-wt-ownership", "createSession", {
  451. workspaceId: paths.source,
  452. cwd: paths.worktree,
  453. firstInput: { text: "归属校验", modelSelection: MODEL },
  454. }),
  455. ),
  456. );
  457. if (ack.result?.type !== "createSession") throw new Error("Expected createSession result");
  458. sessionId = ack.result.sessionId;
  459. await waitFor(async () => {
  460. const messages = await live.store.messages({ sessionID: sessionId as SessionId });
  461. return messages.some((message) => message.info.role === "user");
  462. });
  463. } finally {
  464. await live.close();
  465. }
  466. // 用户添加项目时输入的大小写会原样成为 Host key;resolver 返回磁盘真实大小写(WT-36)。
  467. // 只在大小写不敏感的文件系统(macOS / Windows 默认)上有意义。
  468. const caseVariant = join(root, "projects", REPO.toUpperCase());
  469. const caseInsensitive = await realpath(caseVariant).then(
  470. () => true,
  471. () => false,
  472. );
  473. if (caseInsensitive) {
  474. const cold = await bootServer(dbPath, paths.dataBaseDir);
  475. try {
  476. const snapshot = await conversationSnapshot(cold, sessionId, {
  477. workspaceKey: caseVariant,
  478. workspacePath: caseVariant,
  479. });
  480. expect(rowKinds(snapshot)).toContain("userInput");
  481. expect(cold.apps.at(-1)?.options.runtimeConfig?.workingDirectory).toBe(paths.worktree);
  482. } finally {
  483. await cold.close();
  484. }
  485. }
  486. // worktree 删除后 resolver 无法校验 .git 链接,归属以创建时的 projectID 为准(WT-38)。
  487. await rm(paths.worktree, { recursive: true, force: true });
  488. const afterRemoval = await bootServer(dbPath, paths.dataBaseDir);
  489. try {
  490. const snapshot = await conversationSnapshot(afterRemoval, sessionId, {
  491. workspaceKey: paths.source,
  492. workspacePath: paths.source,
  493. });
  494. expect(rowKinds(snapshot)).toContain("userInput");
  495. // 普通目录仍不能借用项目 key 绕过归属校验。
  496. const rejected = await afterRemoval.server.handleMessage({
  497. id: "reject-foreign-after-removal",
  498. method: zcodeProtocolMethods.sessionLifecycleEnsureReady,
  499. params: {
  500. sessionId,
  501. workspace: { workspaceKey: paths.source, workspacePath: paths.plain },
  502. },
  503. });
  504. expect(rejected).toHaveProperty("error");
  505. } finally {
  506. await afterRemoval.close();
  507. }
  508. });
  509. it("冷恢复归属:projectID 相同的另一个项目不能借用当前 key 恢复会话", async () => {
  510. // "my project" 与 "my-project" 的 projectID slug 相同,但不是同一个目录(MR !3520 review CR-01)。
  511. const spaced = join(root, "projects", "my project");
  512. const dashed = join(root, "projects", "my-project");
  513. await mkdir(spaced, { recursive: true });
  514. await mkdir(dashed, { recursive: true });
  515. expect(projectIdFromDirectory(spaced)).toBe(projectIdFromDirectory(dashed));
  516. const dbPath = join(root, "slug-collision.db");
  517. const live = await bootServer(dbPath, paths.dataBaseDir);
  518. let sessionId = "";
  519. try {
  520. const ack = commandAckSchema.parse(
  521. await requestResult(
  522. live.server,
  523. command("create-spaced", "createSession", {
  524. workspaceId: spaced,
  525. firstInput: { text: "另一个项目", modelSelection: MODEL },
  526. }),
  527. ),
  528. );
  529. if (ack.result?.type !== "createSession") throw new Error("Expected createSession result");
  530. sessionId = ack.result.sessionId;
  531. await waitFor(async () => {
  532. const messages = await live.store.messages({ sessionID: sessionId as SessionId });
  533. return messages.some((message) => message.info.role === "user");
  534. });
  535. } finally {
  536. await live.close();
  537. }
  538. const cold = await bootServer(dbPath, paths.dataBaseDir);
  539. try {
  540. const rejected = await cold.server.handleMessage({
  541. id: "reject-slug-collision",
  542. method: zcodeProtocolMethods.sessionLifecycleEnsureReady,
  543. params: { sessionId, workspace: { workspaceKey: dashed, workspacePath: dashed } },
  544. });
  545. expect(rejected).toHaveProperty("error");
  546. expect(cold.apps).toHaveLength(0);
  547. } finally {
  548. await cold.close();
  549. }
  550. });
  551. it("subscribe 之外的冷恢复入口(plans、改名)使用 Host 注入的项目 workspace", async () => {
  552. const dbPath = join(root, "query-resume.db");
  553. const live = await bootServer(dbPath, paths.dataBaseDir);
  554. let sessionId = "";
  555. try {
  556. const ack = commandAckSchema.parse(
  557. await requestResult(
  558. live.server,
  559. command("create-wt-query", "createSession", {
  560. workspaceId: paths.source,
  561. cwd: paths.worktree,
  562. firstInput: { text: "计划目录冷恢复", modelSelection: MODEL },
  563. }),
  564. ),
  565. );
  566. if (ack.result?.type !== "createSession") throw new Error("Expected createSession result");
  567. sessionId = ack.result.sessionId;
  568. await waitFor(async () => {
  569. const messages = await live.store.messages({ sessionID: sessionId as SessionId });
  570. return messages.some((message) => message.info.role === "user");
  571. });
  572. } finally {
  573. await live.close();
  574. }
  575. const project = { workspaceKey: paths.source, workspacePath: paths.source };
  576. // runtime 卸载后先到的是计划目录查询,而不是 subscribe(WT-37)。
  577. const queried = await bootServer(dbPath, paths.dataBaseDir);
  578. try {
  579. await requestResult(queried.server, {
  580. id: "plans-cold",
  581. method: V4_METHODS.conversationPlans,
  582. params: { sessionId, workspace: project },
  583. });
  584. const resumed = queried.apps.at(-1)!;
  585. expect(resumed.options.workspaceKey).toBe(paths.source);
  586. expect(resumed.options.runtimeConfig?.workingDirectory).toBe(paths.worktree);
  587. } finally {
  588. await queried.close();
  589. }
  590. // 历史行改名经命令信封冷恢复,同样使用 Host 注入的身份。
  591. const renamed = await bootServer(dbPath, paths.dataBaseDir);
  592. try {
  593. const envelope = command(
  594. "rename-cold",
  595. "renameSession",
  596. { title: "改名后" },
  597. { sessionId },
  598. );
  599. const ack = commandAckSchema.parse(
  600. await requestResult(renamed.server, {
  601. ...envelope,
  602. params: { ...envelope.params, workspace: project },
  603. }),
  604. );
  605. expect(ack.status).toBe("accepted");
  606. expect(renamed.apps.at(-1)?.options.workspaceKey).toBe(paths.source);
  607. } finally {
  608. await renamed.close();
  609. }
  610. });
  611. it("createSession.cwd 指向普通目录:项目身份回退为 cwd;远程 workspace 结构化拒绝", async () => {
  612. const booted = await bootServer(join(root, "fallback.db"), paths.dataBaseDir);
  613. try {
  614. const ack = commandAckSchema.parse(
  615. await requestResult(
  616. booted.server,
  617. command("create-plain", "createSession", { workspaceId: paths.source, cwd: paths.plain }),
  618. ),
  619. );
  620. expect(ack.status).toBe("accepted");
  621. expect(booted.apps.at(-1)!.app.runtime.getProjectId()).toBe(
  622. projectIdFromDirectory(paths.plain),
  623. );
  624. const remote = commandAckSchema.parse(
  625. await requestResult(
  626. booted.server,
  627. command("create-remote", "createSession", {
  628. workspaceId: "remote:ssh:example.test:22:coder:/workspace/project",
  629. cwd: "/workspace/project-wt",
  630. }),
  631. ),
  632. );
  633. expect(remote.status).not.toBe("accepted");
  634. } finally {
  635. await booted.close();
  636. }
  637. });
  638. it("forkAssistant.targetCwd:child 在同一进程与 workspace 注册,cwd 为 worktree,追加标记,重试幂等", async () => {
  639. const dbPath = join(root, "fork.db");
  640. await seedParentSession(dbPath, paths.source);
  641. const booted = await bootServer(dbPath, paths.dataBaseDir);
  642. const childSessionId = "sess_worktree_fork_child";
  643. try {
  644. const parentId = PARENT_SESSION_ID;
  645. const snapshot = await conversationSnapshot(booted, parentId);
  646. const assistantRow = snapshot.rows.window.find(
  647. (row) => row.kind === "assistantText" && row.actions?.canFork,
  648. )!;
  649. const appsBeforeFork = booted.apps.length;
  650. const forkPayload = {
  651. target: { rowId: assistantRow.rowId, entityId: assistantRow.entityId },
  652. targetCwd: {
  653. cwd: paths.worktree,
  654. childSessionId,
  655. worktreeCreation: { path: paths.worktree, sha: paths.sha, ref: null, output: "" },
  656. },
  657. };
  658. const fork = (id: string) =>
  659. command(id, "forkAssistant", forkPayload, {
  660. sessionId: parentId,
  661. baseRevision: snapshot.revision,
  662. baseLogEpoch: snapshot.logEpoch,
  663. });
  664. const ack = commandAckSchema.parse(await requestResult(booted.server, fork("fork-1")));
  665. expect(ack).toMatchObject({
  666. status: "accepted",
  667. result: { type: "forkAssistant", sessionId: childSessionId },
  668. });
  669. // 同一 workspace:child 在当前进程注册(不再交给另一个 CLI 进程冷恢复)。
  670. expect(booted.apps.length).toBe(appsBeforeFork + 1);
  671. const childApp = booted.apps.at(-1)!;
  672. expect(childApp.options.runtimeConfig?.workingDirectory).toBe(paths.worktree);
  673. expect(childApp.options.workspaceKey).toBe(paths.source);
  674. const child = await booted.store.getSession(childSessionId as SessionId);
  675. expect(child).toMatchObject({
  676. parentID: parentId,
  677. taskType: "fork",
  678. directory: paths.worktree,
  679. path: paths.worktree,
  680. projectID: projectIdFromDirectory(paths.source),
  681. });
  682. expect(child?.workspaceID).toBeUndefined();
  683. // core 的 fork 按 targetCwd.directory 计算子会话的 Gen UI 目录(键为 [workspace 路径, sessionId]),
  684. // 并写进子会话的环境更新;子会话 runtime 的 workspace 路径必须是同一个值,否则两边的目录不一致。
  685. expect(childApp.options.runtimeConfig?.workspacePath).toBe(paths.worktree);
  686. expect(childApp.options.runtimeConfig?.workspacePath).toBe(child?.path);
  687. const childKinds = rowKinds(await conversationSnapshot(booted, childSessionId));
  688. expect(childKinds).toContain("marker:forkNotice");
  689. expect(childKinds.indexOf("marker:worktreeCreated")).toBeGreaterThan(
  690. childKinds.indexOf("marker:forkNotice"),
  691. );
  692. const retry = commandAckSchema.parse(await requestResult(booted.server, fork("fork-2")));
  693. expect(["accepted", "duplicate"]).toContain(retry.status);
  694. expect(retry.result).toEqual({ type: "forkAssistant", sessionId: childSessionId });
  695. expect(await sessionsIndexIds(booted, paths.source)).toEqual(
  696. [parentId, childSessionId].sort(),
  697. );
  698. } finally {
  699. await booted.close();
  700. }
  701. });
  702. });