v4-worktree-cwd.test.ts 29 KB

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