v4-native-session-mgmt.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. // L2:v4 原生会话管理命令组(renameSession / deleteSession)——验证语义保真:
  2. // rename 直驱 core runtime.setCustomSessionTitle(titleSource=custom 粘性归 core),
  3. // delete = CLI 软删除后关闭运行实例,经 host.deleteSession 过渡钩子。
  4. // 08-phasing M4 完成定义的 L2 层(命令 → core 调用 → 状态推进,不经旧协议代码)。
  5. import { describe, expect, it, vi } from "vitest";
  6. import { SessionEventType } from "@zcode/contracts";
  7. import type { CommandEnvelope } from "@zcode/shared/zcode-protocol-v4";
  8. import { V4CommandExecutor } from "../src/zcode-protocol-v4/commands/executor.js";
  9. import { V4SessionNotFoundError } from "../src/zcode-protocol-v4/commands/record-access.js";
  10. import type {
  11. V4CommandCoreHost,
  12. V4SessionRecordView,
  13. } from "../src/zcode-protocol-v4/commands/types.js";
  14. const TRACE = { traceId: "trace-1", sessionId: "s1" };
  15. function makeApp(overrides: Record<string, unknown> = {}) {
  16. return {
  17. sessionId: "s1",
  18. getModel: () => "provider-a/model-a",
  19. getMode: () => "build",
  20. close: vi.fn().mockResolvedValue(undefined),
  21. runtime: {
  22. setCustomSessionTitle: vi.fn().mockResolvedValue(undefined),
  23. },
  24. ...overrides,
  25. };
  26. }
  27. function makeRecord(
  28. overrides: Partial<V4SessionRecordView> & { app?: ReturnType<typeof makeApp> } = {},
  29. ): V4SessionRecordView {
  30. return {
  31. app: (overrides.app ?? makeApp()) as unknown as V4SessionRecordView["app"],
  32. traceContext: TRACE,
  33. workspace: { workspacePath: "/w" },
  34. persistence: "immediate",
  35. ...overrides,
  36. } as V4SessionRecordView;
  37. }
  38. function makeHost(
  39. record: V4SessionRecordView,
  40. hostOverrides: Partial<V4CommandCoreHost> = {},
  41. ): V4CommandCoreHost {
  42. return {
  43. getRecord: (id) => (id === "s1" ? record : undefined),
  44. waitForProjectionEventCommit: async () => {},
  45. ...hostOverrides,
  46. };
  47. }
  48. function envelope(type: string, payload: unknown, sessionId = "s1"): CommandEnvelope {
  49. return {
  50. type,
  51. payload,
  52. sessionId,
  53. commandId: "cmd-1",
  54. baseRevision: 0,
  55. } as unknown as CommandEnvelope;
  56. }
  57. describe("v4 原生 renameSession", () => {
  58. it("正路径:直驱 runtime.setCustomSessionTitle,透传 title + 会话根 traceContext", async () => {
  59. const app = makeApp();
  60. const record = makeRecord({ app });
  61. await new V4CommandExecutor(makeHost(record)).execute(
  62. envelope("renameSession", { title: "新标题" }),
  63. );
  64. expect(app.runtime.setCustomSessionTitle).toHaveBeenCalledTimes(1);
  65. expect(app.runtime.setCustomSessionTitle).toHaveBeenCalledWith({
  66. title: "新标题",
  67. // 语义保真:traceContext = record 透传的会话根 trace,不得中途另起。
  68. traceContext: TRACE,
  69. });
  70. });
  71. it("session 不存在:拒绝(V4SessionNotFoundError)", async () => {
  72. const record = makeRecord();
  73. await expect(
  74. new V4CommandExecutor(makeHost(record)).execute(
  75. envelope("renameSession", { title: "x" }, "missing"),
  76. ),
  77. ).rejects.toThrow(V4SessionNotFoundError);
  78. expect(
  79. (record.app as unknown as ReturnType<typeof makeApp>).runtime.setCustomSessionTitle,
  80. ).not.toHaveBeenCalled();
  81. });
  82. });
  83. describe("v4 原生 deleteSession", () => {
  84. it("正路径:语义 = deleteSession,经 host.deleteSession 钩子执行关闭", async () => {
  85. const record = makeRecord();
  86. const deleteSession = vi.fn().mockResolvedValue(undefined);
  87. await new V4CommandExecutor(makeHost(record, { deleteSession })).execute(
  88. envelope("deleteSession", {}),
  89. );
  90. expect(deleteSession).toHaveBeenCalledTimes(1);
  91. expect(deleteSession).toHaveBeenCalledWith("s1");
  92. });
  93. it("session 不存在:拒绝,且不触碰 deleteSession 钩子", async () => {
  94. const record = makeRecord();
  95. const deleteSession = vi.fn().mockResolvedValue(undefined);
  96. await expect(
  97. new V4CommandExecutor(makeHost(record, { deleteSession })).execute(
  98. envelope("deleteSession", {}, "missing"),
  99. ),
  100. ).rejects.toThrow(V4SessionNotFoundError);
  101. expect(deleteSession).not.toHaveBeenCalled();
  102. });
  103. it("deleteSession 钩子缺失:显式失败(关闭不能静默降级)", async () => {
  104. const record = makeRecord();
  105. await expect(
  106. new V4CommandExecutor(makeHost(record)).execute(envelope("deleteSession", {})),
  107. ).rejects.toThrow(/deleteSession/);
  108. });
  109. });
  110. describe("v4 原生 createSession", () => {
  111. function makeCreateHost(record: V4SessionRecordView) {
  112. const createSessionRecord = vi.fn().mockImplementation(async () => {
  113. // 钩子契约:record 已建立并注册(deferred draft),返回 sessionId。
  114. return { sessionId: "s1" };
  115. });
  116. const host = makeHost(record, { createSessionRecord });
  117. return { host, createSessionRecord };
  118. }
  119. it("创建前透传 Host 预留的会话 ID 与附加目录", async () => {
  120. const record = makeRecord({ persistence: "deferred" });
  121. const { host, createSessionRecord } = makeCreateHost(record);
  122. await new V4CommandExecutor(host).execute(
  123. envelope(
  124. "createSession",
  125. { workspaceId: "/w", sessionId: "reserved", additionalDirectories: ["/b"] },
  126. "draft",
  127. ),
  128. );
  129. expect(createSessionRecord).toHaveBeenCalledWith(
  130. expect.objectContaining({ sessionId: "reserved", additionalDirectories: ["/b"] }),
  131. );
  132. });
  133. it("受管 worktree:透传 cwd,记录 worktreeCreation 等首轮落盘(docs/git/worktree.md §6.6.4)", async () => {
  134. const recordPendingWorktreeCreation = vi.fn();
  135. const app = makeApp({
  136. runtime: { setCustomSessionTitle: vi.fn(), recordPendingWorktreeCreation },
  137. });
  138. const record = makeRecord({ app, persistence: "deferred" });
  139. const { host, createSessionRecord } = makeCreateHost(record);
  140. const worktreeCreation = {
  141. path: "/wt/3f2a/project",
  142. sha: "9e6d2f72d4",
  143. ref: "origin/main",
  144. output: "HEAD is now at 9e6d2f7\n",
  145. };
  146. await new V4CommandExecutor(host).execute(
  147. envelope(
  148. "createSession",
  149. { workspaceId: "/w", cwd: "/wt/3f2a/project", worktreeCreation },
  150. "draft",
  151. ),
  152. );
  153. expect(createSessionRecord).toHaveBeenCalledWith(
  154. expect.objectContaining({ workspaceId: "/w", cwd: "/wt/3f2a/project" }),
  155. );
  156. expect(recordPendingWorktreeCreation).toHaveBeenCalledWith(worktreeCreation);
  157. });
  158. it("worktreeCreation 缺 cwd:创建 record 前拒绝", async () => {
  159. const record = makeRecord({ persistence: "deferred" });
  160. const { host, createSessionRecord } = makeCreateHost(record);
  161. await expect(
  162. new V4CommandExecutor(host).execute(
  163. envelope(
  164. "createSession",
  165. {
  166. workspaceId: "/w",
  167. worktreeCreation: { path: "/wt", sha: "abc", ref: null, output: "" },
  168. },
  169. "draft",
  170. ),
  171. ),
  172. ).rejects.toThrow(/worktreeCreation requires cwd/);
  173. expect(createSessionRecord).not.toHaveBeenCalled();
  174. });
  175. it("无 firstInput:只建 draft record(deferred),不起 turn", async () => {
  176. const app = makeApp({ sendInput: vi.fn() });
  177. const record = makeRecord({ app, persistence: "deferred" });
  178. const { host, createSessionRecord } = makeCreateHost(record);
  179. const result = await new V4CommandExecutor(host).execute(
  180. envelope("createSession", { workspaceId: "/w" }, "draft"),
  181. );
  182. expect(createSessionRecord).toHaveBeenCalledWith({ workspaceId: "/w" });
  183. expect(result).toEqual({ type: "createSession", sessionId: "s1" });
  184. // draft 语义:无首条输入不提升 persistence、不触发 core 输入。
  185. expect(record.persistence).toBe("deferred");
  186. expect(app.sendInput).not.toHaveBeenCalled();
  187. });
  188. it("requests isolated permission persistence before returning a group session", async () => {
  189. const record = makeRecord({ app: makeApp(), persistence: "deferred" });
  190. const { host, createSessionRecord } = makeCreateHost(record);
  191. await new V4CommandExecutor(host).execute(
  192. envelope("createSession", { workspaceId: "/w", permissionScope: "session" }, "group-draft"),
  193. );
  194. expect(createSessionRecord).toHaveBeenCalledWith({
  195. workspaceId: "/w",
  196. permissionScope: "session",
  197. });
  198. });
  199. it("创建 draft record 时透传 MCP runtime 配置", async () => {
  200. const record = makeRecord({ app: makeApp(), persistence: "deferred" });
  201. const { host, createSessionRecord } = makeCreateHost(record);
  202. const mcpServers = [{ name: "docs", command: "node", args: ["server.js"], env: [] }];
  203. await new V4CommandExecutor(host).execute(
  204. envelope("createSession", { workspaceId: "/w", mcpServers }, "draft-mcp"),
  205. );
  206. expect(createSessionRecord).toHaveBeenCalledWith({ workspaceId: "/w", mcpServers });
  207. });
  208. it("Guarded 配置失败会清理新草稿且不执行首条输入", async () => {
  209. const sendInput = vi.fn();
  210. const deleteSession = vi.fn(async () => {});
  211. const app = makeApp({
  212. sendInput,
  213. runtime: {
  214. getSessionModelSelection: () => {
  215. throw new Error("config unavailable");
  216. },
  217. },
  218. });
  219. const record = makeRecord({ app, persistence: "deferred" });
  220. const { host } = makeCreateHost(record);
  221. host.deleteSession = deleteSession;
  222. await expect(
  223. new V4CommandExecutor(host).execute(
  224. envelope(
  225. "createSession",
  226. {
  227. workspaceId: "/w",
  228. config: { mode: "guarded" },
  229. firstInput: { text: "do work", mode: "guarded" },
  230. },
  231. "draft",
  232. ),
  233. ),
  234. ).rejects.toThrow("config unavailable");
  235. expect(deleteSession).toHaveBeenCalledWith("s1");
  236. expect(sendInput).not.toHaveBeenCalled();
  237. });
  238. it("创建 draft record 时透传 Off-Peak 工具面 flag(D49:v4 是桌面新会话的实际创建路径)", async () => {
  239. const record = makeRecord({ app: makeApp(), persistence: "deferred" });
  240. const { host, createSessionRecord } = makeCreateHost(record);
  241. await new V4CommandExecutor(host).execute(
  242. envelope("createSession", { workspaceId: "/w", offPeakToolEnabled: true }, "draft-offpeak"),
  243. );
  244. expect(createSessionRecord).toHaveBeenCalledWith(
  245. expect.objectContaining({ workspaceId: "/w", offPeakToolEnabled: true }),
  246. );
  247. });
  248. it("带 firstInput:经原生 prompt turn 提交(draft 提升 + inputId=commandId 锚点)", async () => {
  249. const app = makeApp({
  250. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  251. options?.onTurnStartedObserved?.({
  252. id: "event-started",
  253. type: SessionEventType.TurnStarted,
  254. payload: { messageId: "msg-event-started" },
  255. });
  256. return {};
  257. }),
  258. });
  259. const record = makeRecord({ app, persistence: "deferred" });
  260. const admitInputCommand = vi.fn().mockResolvedValue({ sourceCommandId: "cmd-1" });
  261. const cancelInputCommand = vi.fn().mockResolvedValue(undefined);
  262. const { host } = makeCreateHost(record);
  263. host.admitInputCommand = admitInputCommand;
  264. host.cancelInputCommand = cancelInputCommand;
  265. const command = envelope(
  266. "createSession",
  267. {
  268. workspaceId: "/w",
  269. firstInput: {
  270. text: "首条",
  271. modelSelection: {
  272. providerId: "provider-a",
  273. modelId: "model-a",
  274. options: { reasoningLevel: "high" },
  275. },
  276. mode: "build",
  277. planEnabled: true,
  278. },
  279. },
  280. "draft",
  281. );
  282. const result = await new V4CommandExecutor(host).execute(command);
  283. expect(result).toEqual({
  284. type: "createSession",
  285. sessionId: "s1",
  286. input: {
  287. delivery: "startNow",
  288. inputId: "cmd-1",
  289. },
  290. });
  291. expect(admitInputCommand).toHaveBeenCalledWith(
  292. command,
  293. "s1",
  294. expect.objectContaining({ queueItemId: "queue_cmd-1" }),
  295. );
  296. // 与 sendText 同一条写路径:draft 提升语义免费获得。
  297. expect(record.persistence).toBe("immediate");
  298. expect(app.sendInput).toHaveBeenCalledWith(
  299. { text: "首条" },
  300. expect.objectContaining({
  301. inputId: "cmd-1",
  302. queryId: "cmd-1",
  303. intent: expect.objectContaining({
  304. modelSelection: {
  305. providerId: "provider-a",
  306. modelId: "model-a",
  307. options: { reasoningLevel: "high" },
  308. },
  309. mode: "build",
  310. planEnabled: true,
  311. }),
  312. }),
  313. );
  314. expect(admitInputCommand.mock.invocationCallOrder[0]).toBeLessThan(
  315. app.sendInput.mock.invocationCallOrder[0]!,
  316. );
  317. expect(cancelInputCommand).not.toHaveBeenCalled();
  318. });
  319. it("firstInput 正文和附件都为空时在创建 record 前拒绝", async () => {
  320. const app = makeApp({ sendInput: vi.fn() });
  321. const record = makeRecord({ app, persistence: "deferred" });
  322. const { host, createSessionRecord } = makeCreateHost(record);
  323. await expect(
  324. new V4CommandExecutor(host).execute(
  325. envelope(
  326. "createSession",
  327. { workspaceId: "/w", firstInput: { text: " ", attachments: [] } },
  328. "draft",
  329. ),
  330. ),
  331. ).rejects.toMatchObject({ reasonCode: "proto.invalidPayload" });
  332. expect(createSessionRecord).not.toHaveBeenCalled();
  333. expect(app.sendInput).not.toHaveBeenCalled();
  334. });
  335. it("firstInput 启动失败:保留原错误并把 durable admission 收口为 cancelled", async () => {
  336. // 首发模型不在 Worker Registry:与 sendText 共用模型准入,在 Core 建模前以 modelUnavailable 拒绝。
  337. const app = makeApp({ sendInput: vi.fn(), listModels: () => [] });
  338. const record = makeRecord({ app, persistence: "deferred" });
  339. const admitInputCommand = vi.fn().mockResolvedValue({ sourceCommandId: "cmd-1" });
  340. const cancelInputCommand = vi.fn().mockRejectedValue(new Error("ledger unavailable"));
  341. const warn = vi.fn();
  342. const { host } = makeCreateHost(record);
  343. host.admitInputCommand = admitInputCommand;
  344. host.cancelInputCommand = cancelInputCommand;
  345. host.logger = { warn };
  346. await expect(
  347. new V4CommandExecutor(host).execute(
  348. envelope("createSession", { workspaceId: "/w", firstInput: { text: "首条" } }, "draft"),
  349. ),
  350. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  351. expect(cancelInputCommand).toHaveBeenCalledWith(
  352. "s1",
  353. "queue_cmd-1",
  354. "fault.command.inputRejected",
  355. );
  356. expect(warn).toHaveBeenCalledWith(
  357. "v4 createSession first input cancellation failed",
  358. expect.objectContaining({
  359. inputError: expect.stringContaining("Provider Registry 中不存在 Model"),
  360. queueItemId: "queue_cmd-1",
  361. }),
  362. );
  363. expect(record.persistence).toBe("deferred");
  364. expect(app.sendInput).not.toHaveBeenCalled();
  365. });
  366. it("record 创建失败:错误原样上抛(钩子内已自清理半初始化 record)", async () => {
  367. const record = makeRecord();
  368. const host = makeHost(record, {
  369. createSessionRecord: vi.fn().mockRejectedValue(new Error("model seed failed")),
  370. });
  371. await expect(
  372. new V4CommandExecutor(host).execute(
  373. envelope("createSession", { workspaceId: "/w" }, "draft"),
  374. ),
  375. ).rejects.toThrow("model seed failed");
  376. });
  377. it("钩子缺失:binder 接线不完整直接失败(不静默降级)", async () => {
  378. await expect(
  379. new V4CommandExecutor(makeHost(makeRecord())).execute(
  380. envelope("createSession", { workspaceId: "/w" }, "draft"),
  381. ),
  382. ).rejects.toThrow(/createSessionRecord/);
  383. });
  384. });