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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. // L2:v4 原生会话管理命令组(renameSession / deleteSession)——验证语义保真:
  2. // rename 直驱 core runtime.setCustomSessionTitle(titleSource=custom 粘性归 core),
  3. // delete = closeSession 语义(关闭+清理,非真删 record),经 host.closeSession 过渡钩子。
  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("正路径:语义 = closeSession,经 host.closeSession 钩子执行关闭", async () => {
  85. const record = makeRecord();
  86. const closeSession = vi.fn().mockResolvedValue(undefined);
  87. await new V4CommandExecutor(makeHost(record, { closeSession })).execute(
  88. envelope("deleteSession", {}),
  89. );
  90. expect(closeSession).toHaveBeenCalledTimes(1);
  91. expect(closeSession).toHaveBeenCalledWith("s1");
  92. });
  93. it("session 不存在:拒绝,且不触碰 closeSession 钩子", async () => {
  94. const record = makeRecord();
  95. const closeSession = vi.fn().mockResolvedValue(undefined);
  96. await expect(
  97. new V4CommandExecutor(makeHost(record, { closeSession })).execute(
  98. envelope("deleteSession", {}, "missing"),
  99. ),
  100. ).rejects.toThrow(V4SessionNotFoundError);
  101. expect(closeSession).not.toHaveBeenCalled();
  102. });
  103. it("closeSession 钩子缺失:显式失败(关闭不能静默降级)", async () => {
  104. const record = makeRecord();
  105. await expect(
  106. new V4CommandExecutor(makeHost(record)).execute(envelope("deleteSession", {})),
  107. ).rejects.toThrow(/closeSession/);
  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("无 firstInput:只建 draft record(deferred),不起 turn", async () => {
  120. const app = makeApp({ sendInput: vi.fn() });
  121. const record = makeRecord({ app, persistence: "deferred" });
  122. const { host, createSessionRecord } = makeCreateHost(record);
  123. const result = await new V4CommandExecutor(host).execute(
  124. envelope("createSession", { workspaceId: "/w" }, "draft"),
  125. );
  126. expect(createSessionRecord).toHaveBeenCalledWith({ workspaceId: "/w" });
  127. expect(result).toEqual({ type: "createSession", sessionId: "s1" });
  128. // draft 语义:无首条输入不提升 persistence、不触发 core 输入。
  129. expect(record.persistence).toBe("deferred");
  130. expect(app.sendInput).not.toHaveBeenCalled();
  131. });
  132. it("requests isolated permission persistence before returning a group session", async () => {
  133. const record = makeRecord({ app: makeApp(), persistence: "deferred" });
  134. const { host, createSessionRecord } = makeCreateHost(record);
  135. await new V4CommandExecutor(host).execute(
  136. envelope("createSession", { workspaceId: "/w", permissionScope: "session" }, "group-draft"),
  137. );
  138. expect(createSessionRecord).toHaveBeenCalledWith({
  139. workspaceId: "/w",
  140. permissionScope: "session",
  141. });
  142. });
  143. it("创建 draft record 时透传 MCP runtime 配置", async () => {
  144. const record = makeRecord({ app: makeApp(), persistence: "deferred" });
  145. const { host, createSessionRecord } = makeCreateHost(record);
  146. const mcpServers = [{ name: "docs", command: "node", args: ["server.js"], env: [] }];
  147. await new V4CommandExecutor(host).execute(
  148. envelope("createSession", { workspaceId: "/w", mcpServers }, "draft-mcp"),
  149. );
  150. expect(createSessionRecord).toHaveBeenCalledWith({ workspaceId: "/w", mcpServers });
  151. });
  152. it.each([false, true])(
  153. "Guarded 配置失败会清理新草稿且不执行(首发=%s)",
  154. async (withFirstInput) => {
  155. const sendInput = vi.fn();
  156. const closeSession = vi.fn(async () => {});
  157. const app = makeApp({
  158. sendInput,
  159. runtime: {
  160. getSessionModelSelection: () => {
  161. throw new Error("config unavailable");
  162. },
  163. },
  164. });
  165. const record = makeRecord({ app, persistence: "deferred" });
  166. const { host } = makeCreateHost(record);
  167. host.closeSession = closeSession;
  168. await expect(
  169. new V4CommandExecutor(host).execute(
  170. envelope(
  171. "createSession",
  172. {
  173. workspaceId: "/w",
  174. config: { mode: "guarded" },
  175. ...(withFirstInput ? { firstInput: { text: "do work", mode: "guarded" } } : {}),
  176. },
  177. "draft",
  178. ),
  179. ),
  180. ).rejects.toThrow("config unavailable");
  181. expect(closeSession).toHaveBeenCalledWith("s1");
  182. expect(sendInput).not.toHaveBeenCalled();
  183. },
  184. );
  185. it("创建 draft record 时透传 Off-Peak 工具面 flag(D49:v4 是桌面新会话的实际创建路径)", async () => {
  186. const record = makeRecord({ app: makeApp(), persistence: "deferred" });
  187. const { host, createSessionRecord } = makeCreateHost(record);
  188. await new V4CommandExecutor(host).execute(
  189. envelope("createSession", { workspaceId: "/w", offPeakToolEnabled: true }, "draft-offpeak"),
  190. );
  191. expect(createSessionRecord).toHaveBeenCalledWith(
  192. expect.objectContaining({ workspaceId: "/w", offPeakToolEnabled: true }),
  193. );
  194. });
  195. it("带 firstInput:经原生 prompt turn 提交(draft 提升 + inputId=commandId 锚点)", async () => {
  196. const app = makeApp({
  197. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  198. options?.onTurnStartedObserved?.({
  199. id: "event-started",
  200. type: SessionEventType.TurnStarted,
  201. payload: { messageId: "msg-event-started" },
  202. });
  203. return {};
  204. }),
  205. });
  206. const record = makeRecord({ app, persistence: "deferred" });
  207. const admitInputCommand = vi.fn().mockResolvedValue({ sourceCommandId: "cmd-1" });
  208. const cancelInputCommand = vi.fn().mockResolvedValue(undefined);
  209. const { host } = makeCreateHost(record);
  210. host.admitInputCommand = admitInputCommand;
  211. host.cancelInputCommand = cancelInputCommand;
  212. const command = envelope(
  213. "createSession",
  214. {
  215. workspaceId: "/w",
  216. firstInput: {
  217. text: "首条",
  218. modelSelection: {
  219. providerId: "provider-a",
  220. modelId: "model-a",
  221. options: { reasoningLevel: "high" },
  222. },
  223. mode: "build",
  224. planEnabled: true,
  225. },
  226. },
  227. "draft",
  228. );
  229. const result = await new V4CommandExecutor(host).execute(command);
  230. expect(result).toEqual({
  231. type: "createSession",
  232. sessionId: "s1",
  233. input: {
  234. delivery: "startNow",
  235. inputId: "cmd-1",
  236. },
  237. });
  238. expect(admitInputCommand).toHaveBeenCalledWith(
  239. command,
  240. "s1",
  241. expect.objectContaining({ queueItemId: "queue_cmd-1" }),
  242. );
  243. // 与 sendText 同一条写路径:draft 提升语义免费获得。
  244. expect(record.persistence).toBe("immediate");
  245. expect(app.sendInput).toHaveBeenCalledWith(
  246. { text: "首条" },
  247. expect.objectContaining({
  248. inputId: "cmd-1",
  249. queryId: "cmd-1",
  250. intent: expect.objectContaining({
  251. modelSelection: {
  252. providerId: "provider-a",
  253. modelId: "model-a",
  254. options: { reasoningLevel: "high" },
  255. },
  256. mode: "build",
  257. planEnabled: true,
  258. }),
  259. }),
  260. );
  261. expect(admitInputCommand.mock.invocationCallOrder[0]).toBeLessThan(
  262. app.sendInput.mock.invocationCallOrder[0]!,
  263. );
  264. expect(cancelInputCommand).not.toHaveBeenCalled();
  265. });
  266. it("firstInput 正文和附件都为空时在创建 record 前拒绝", async () => {
  267. const app = makeApp({ sendInput: vi.fn() });
  268. const record = makeRecord({ app, persistence: "deferred" });
  269. const { host, createSessionRecord } = makeCreateHost(record);
  270. await expect(
  271. new V4CommandExecutor(host).execute(
  272. envelope(
  273. "createSession",
  274. { workspaceId: "/w", firstInput: { text: " ", attachments: [] } },
  275. "draft",
  276. ),
  277. ),
  278. ).rejects.toMatchObject({ reasonCode: "proto.invalidPayload" });
  279. expect(createSessionRecord).not.toHaveBeenCalled();
  280. expect(app.sendInput).not.toHaveBeenCalled();
  281. });
  282. it("firstInput 启动失败:保留原错误并把 durable admission 收口为 cancelled", async () => {
  283. const app = makeApp({ sendInput: vi.fn() });
  284. const record = makeRecord({ app, persistence: "deferred" });
  285. const inputError = new Error("model unavailable");
  286. const admitInputCommand = vi.fn().mockResolvedValue({ sourceCommandId: "cmd-1" });
  287. const cancelInputCommand = vi.fn().mockRejectedValue(new Error("ledger unavailable"));
  288. const warn = vi.fn();
  289. const { host } = makeCreateHost(record);
  290. host.admitInputCommand = admitInputCommand;
  291. host.cancelInputCommand = cancelInputCommand;
  292. host.ensureModelReady = vi.fn().mockRejectedValue(inputError);
  293. host.logger = { warn };
  294. await expect(
  295. new V4CommandExecutor(host).execute(
  296. envelope("createSession", { workspaceId: "/w", firstInput: { text: "首条" } }, "draft"),
  297. ),
  298. ).rejects.toBe(inputError);
  299. expect(cancelInputCommand).toHaveBeenCalledWith(
  300. "s1",
  301. "queue_cmd-1",
  302. "fault.command.inputRejected",
  303. );
  304. expect(warn).toHaveBeenCalledWith(
  305. "v4 createSession first input cancellation failed",
  306. expect.objectContaining({
  307. inputError: "model unavailable",
  308. queueItemId: "queue_cmd-1",
  309. }),
  310. );
  311. expect(record.persistence).toBe("deferred");
  312. expect(app.sendInput).not.toHaveBeenCalled();
  313. });
  314. it("record 创建失败:错误原样上抛(钩子内已自清理半初始化 record)", async () => {
  315. const record = makeRecord();
  316. const host = makeHost(record, {
  317. createSessionRecord: vi.fn().mockRejectedValue(new Error("model seed failed")),
  318. });
  319. await expect(
  320. new V4CommandExecutor(host).execute(
  321. envelope("createSession", { workspaceId: "/w" }, "draft"),
  322. ),
  323. ).rejects.toThrow("model seed failed");
  324. });
  325. it("钩子缺失:binder 接线不完整直接失败(不静默降级)", async () => {
  326. await expect(
  327. new V4CommandExecutor(makeHost(makeRecord())).execute(
  328. envelope("createSession", { workspaceId: "/w" }, "draft"),
  329. ),
  330. ).rejects.toThrow(/createSessionRecord/);
  331. });
  332. });
  333. describe("supports 分流", () => {
  334. it("createSession/renameSession/deleteSession 已原生", () => {
  335. const executor = new V4CommandExecutor(makeHost(makeRecord()));
  336. expect(executor.supports("createSession")).toBe(true);
  337. expect(executor.supports("renameSession")).toBe(true);
  338. expect(executor.supports("deleteSession")).toBe(true);
  339. });
  340. });