protocol-binding.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. import { describe, expect, it, vi } from "vitest";
  2. import { zcodeProtocolMethods, zcodeSessionMessagesResultSchema } from "@zcode/shared";
  3. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  4. import { createMessageId, createPartId, createProjectId, createSessionId } from "@zcode/contracts";
  5. import { ZCodeProtocolAgentServer } from "../../src/zcode-protocol/server.js";
  6. import type { ZCodeAppOptions } from "../../src/app/types.js";
  7. import { createFakeApp } from "../helpers/fake-zcode-app.js";
  8. const workspace = { workspacePath: "/workspace", workspaceKey: "/workspace" };
  9. function advertiseAppControl(server: ZCodeProtocolAgentServer, enabled = true) {
  10. server.setNotificationSink((message) => {
  11. if (
  12. "id" in message &&
  13. message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences
  14. ) {
  15. void server.handleMessage({
  16. id: message.id,
  17. result: {
  18. memoryEnabled: false,
  19. nativeSearchEnhancementsEnabled: true,
  20. appControlEnabled: enabled,
  21. },
  22. });
  23. }
  24. });
  25. }
  26. function fakeApp(options?: Omit<ZCodeAppOptions, "providerRegistry">) {
  27. const app = createFakeApp(options);
  28. app.runtime.beginShutdown = () => undefined;
  29. return app;
  30. }
  31. describe("production protocol session control materialization", () => {
  32. it("maps persisted SQLite messages and parts to the wire schema without losing media or tool metadata", async () => {
  33. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  34. const sessionId = createSessionId("read-messages-wire");
  35. const userId = createMessageId("wire-user");
  36. const assistantId = createMessageId("wire-assistant");
  37. const filePartId = createPartId("wire-image");
  38. const toolPartId = createPartId("wire-tool");
  39. const mediaMetadata = {
  40. artifactUri: "zcode-artifact://session/image",
  41. originalFilename: "sample.png",
  42. };
  43. const readArtifact = vi.fn(async () => ({
  44. uri: mediaMetadata.artifactUri,
  45. contentType: "image/png",
  46. content: "aGVsbG8=",
  47. sizeBytes: 8,
  48. truncated: false,
  49. }));
  50. const server = new ZCodeProtocolAgentServer({
  51. createZCodeApp: (options) => ({ ...fakeApp(options), readToolResultArtifact: readArtifact }),
  52. cwd: workspace.workspacePath,
  53. sessionStore: store,
  54. version: "test",
  55. });
  56. try {
  57. await store.createSession({
  58. id: sessionId,
  59. projectID: createProjectId("wire-project"),
  60. slug: "wire-history",
  61. directory: workspace.workspacePath,
  62. path: workspace.workspacePath,
  63. title: "wire history",
  64. version: "test",
  65. taskType: "interactive",
  66. });
  67. await store.saveMessage({
  68. id: userId,
  69. sessionID: sessionId,
  70. role: "user",
  71. time: { created: 1 },
  72. agent: "build",
  73. metadata: { source: "fixture" },
  74. });
  75. await store.savePart({
  76. id: createPartId("wire-text"),
  77. sessionID: sessionId,
  78. messageID: userId,
  79. type: "text",
  80. text: "Inspect this image",
  81. metadata: { language: "en" },
  82. });
  83. await store.savePart({
  84. id: filePartId,
  85. sessionID: sessionId,
  86. messageID: userId,
  87. type: "file",
  88. mime: "image/png",
  89. filename: "sample.png",
  90. url: mediaMetadata.artifactUri,
  91. metadata: mediaMetadata,
  92. });
  93. await store.saveMessage({
  94. id: assistantId,
  95. sessionID: sessionId,
  96. role: "assistant",
  97. parentID: userId,
  98. time: { created: 2, completed: 4 },
  99. mode: "build",
  100. agent: "build",
  101. path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
  102. cost: 0,
  103. tokens: { input: 2, output: 3, reasoning: 0, cache: { read: 0, write: 0 } },
  104. finish: "stop",
  105. });
  106. await store.savePart({
  107. id: createPartId("wire-reasoning"),
  108. sessionID: sessionId,
  109. messageID: assistantId,
  110. type: "reasoning",
  111. text: "Inspecting",
  112. time: { start: 2, end: 3 },
  113. metadata: { signature: "fixture-signature" },
  114. });
  115. await store.savePart({
  116. id: toolPartId,
  117. sessionID: sessionId,
  118. messageID: assistantId,
  119. type: "tool",
  120. callID: "wire-call",
  121. tool: "Read",
  122. metadata: { presentation: "file-preview", providerToolName: "private-read-name" },
  123. state: {
  124. status: "completed",
  125. input: { file_path: "sample.png" },
  126. output: "image inspected",
  127. title: "Read image",
  128. metadata: {
  129. contentType: "image/png",
  130. display: { variant: "fixture-display" },
  131. readFileState: { private: "snapshot" },
  132. },
  133. time: { start: 3, end: 4 },
  134. },
  135. });
  136. const restored = await server.handleMessage({
  137. id: "restore-wire",
  138. method: zcodeProtocolMethods.sessionResume,
  139. params: { sessionId, workspace },
  140. });
  141. expect(restored, JSON.stringify(restored)).toHaveProperty("result");
  142. readArtifact.mockClear();
  143. const response = await server.handleMessage({
  144. id: "read-wire",
  145. method: zcodeProtocolMethods.sessionMessages,
  146. params: { sessionId },
  147. });
  148. expect(response, JSON.stringify(response)).toHaveProperty("result");
  149. const parsed = zcodeSessionMessagesResultSchema.parse(
  150. response && "result" in response ? response.result : undefined,
  151. );
  152. expect(parsed.messages.map((message) => message.info.messageId)).toEqual([
  153. userId,
  154. assistantId,
  155. ]);
  156. expect(readArtifact).toHaveBeenCalledExactlyOnceWith(mediaMetadata.artifactUri);
  157. expect(parsed.messages[0]?.info).toMatchObject({
  158. sessionId,
  159. metadata: { source: "fixture" },
  160. });
  161. expect(parsed.messages[0]?.parts).toEqual(
  162. expect.arrayContaining([
  163. expect.objectContaining({
  164. type: "file",
  165. partId: filePartId,
  166. messageId: userId,
  167. sessionId,
  168. filename: "sample.png",
  169. mime: "image/png",
  170. url: "data:image/png;base64,aGVsbG8=",
  171. metadata: mediaMetadata,
  172. }),
  173. expect.objectContaining({
  174. type: "text",
  175. text: "Inspect this image",
  176. metadata: { language: "en" },
  177. }),
  178. ]),
  179. );
  180. expect(parsed.messages[1]?.info).toMatchObject({
  181. parentMessageId: userId,
  182. time: { created: 2, completed: 4 },
  183. });
  184. expect(parsed.messages[1]?.parts).toEqual(
  185. expect.arrayContaining([
  186. expect.objectContaining({
  187. type: "reasoning",
  188. text: "Inspecting",
  189. metadata: { signature: "fixture-signature" },
  190. }),
  191. expect.objectContaining({
  192. type: "tool",
  193. partId: toolPartId,
  194. messageId: assistantId,
  195. sessionId,
  196. callId: "wire-call",
  197. metadata: { presentation: "file-preview" },
  198. state: {
  199. status: "completed",
  200. input: { file_path: "sample.png" },
  201. output: "image inspected",
  202. title: "Read image",
  203. metadata: { contentType: "image/png", display: { variant: "fixture-display" } },
  204. startedAt: 3,
  205. completedAt: 4,
  206. },
  207. }),
  208. ]),
  209. );
  210. const page = await server.handleMessage({
  211. id: "read-page",
  212. method: zcodeProtocolMethods.sessionMessages,
  213. params: { sessionId, afterMessageId: userId, limit: 1 },
  214. });
  215. const parsedPage = zcodeSessionMessagesResultSchema.parse(
  216. page && "result" in page ? page.result : undefined,
  217. );
  218. expect(parsedPage.messages).toEqual([parsed.messages[1]]);
  219. } finally {
  220. await server.shutdown();
  221. store.close();
  222. }
  223. });
  224. it("pages forward from the oldest message while preserving the default tail window", async () => {
  225. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  226. const sessionId = createSessionId("read-messages-pages");
  227. const ids = ["first", "second", "third", "fourth"].map(createMessageId);
  228. const server = new ZCodeProtocolAgentServer({
  229. createZCodeApp: fakeApp,
  230. cwd: workspace.workspacePath,
  231. sessionStore: store,
  232. version: "test",
  233. });
  234. try {
  235. await store.createSession({
  236. id: sessionId,
  237. projectID: createProjectId("paging-project"),
  238. slug: "paging-history",
  239. directory: workspace.workspacePath,
  240. path: workspace.workspacePath,
  241. title: "paging history",
  242. version: "test",
  243. taskType: "interactive",
  244. });
  245. // 运行时提醒以隐藏 user 消息落库,夹在可见消息之间;forward 分页必须跳过它。
  246. // 消息按写入顺序排列,所以在第一条之后立即写入。
  247. const reminderId = createMessageId("hidden-reminder");
  248. for (const [index, id] of ids.entries()) {
  249. await store.saveMessage({
  250. id,
  251. sessionID: sessionId,
  252. role: "user",
  253. time: { created: (index + 1) * 10 },
  254. agent: "build",
  255. });
  256. if (index === 0)
  257. await store.saveMessage({
  258. id: reminderId,
  259. sessionID: sessionId,
  260. role: "user",
  261. time: { created: 15 },
  262. agent: "build",
  263. visibility: "model-only",
  264. synthetic: true,
  265. } as never);
  266. }
  267. const restored = await server.handleMessage({
  268. id: "restore-pages",
  269. method: zcodeProtocolMethods.sessionResume,
  270. params: { sessionId, workspace },
  271. });
  272. expect(restored, JSON.stringify(restored)).toHaveProperty("result");
  273. const read = async (params: Record<string, unknown>) => {
  274. const response = await server.handleMessage({
  275. id: "read-pages",
  276. method: zcodeProtocolMethods.sessionMessages,
  277. params: { sessionId, ...params },
  278. });
  279. expect(response, JSON.stringify(response)).toHaveProperty("result");
  280. return zcodeSessionMessagesResultSchema
  281. .parse(response && "result" in response ? response.result : undefined)
  282. .messages.map((message) => message.info.messageId);
  283. };
  284. // 默认与 backward 保持原尾部窗口与原始消息集合,不受 forward 过滤影响。
  285. expect(await read({})).toContain(reminderId);
  286. expect(await read({ limit: 3 })).toEqual(ids.slice(-3));
  287. expect(await read({ limit: 3, direction: "backward" })).toEqual(ids.slice(-3));
  288. expect(await read({ limit: 3, direction: "forward" })).toEqual(ids.slice(0, 3));
  289. expect(await read({ afterMessageId: ids[0], limit: 1, direction: "forward" })).toEqual([
  290. ids[1],
  291. ]);
  292. expect(await read({ afterMessageId: ids[1], limit: 3, direction: "forward" })).toEqual(
  293. ids.slice(2),
  294. );
  295. expect(await read({ afterMessageId: ids[3], limit: 3, direction: "forward" })).toEqual([]);
  296. expect(await read({ direction: "forward" })).not.toContain(reminderId);
  297. // cursor 落在不可见或已不存在的消息上时报错,不从头重读出重复页。
  298. for (const missing of [reminderId, "msg_missing"]) {
  299. const response = await server.handleMessage({
  300. id: "read-missing-cursor",
  301. method: zcodeProtocolMethods.sessionMessages,
  302. params: { sessionId, afterMessageId: missing, limit: 1, direction: "forward" },
  303. });
  304. expect(response).toHaveProperty("error");
  305. }
  306. } finally {
  307. await server.shutdown();
  308. store.close();
  309. }
  310. });
  311. // 规格 0.9:ReadSession 读一个从未恢复的冷会话。原先一律 requireSession,
  312. // forward 因此抛 sessionUnavailable 并被 Host 压成 "App control failed"。
  313. it("reads a cold session forward without restoring its runtime", async () => {
  314. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  315. const sessionId = createSessionId("read-messages-cold");
  316. const deletedId = createSessionId("read-messages-cold-deleted");
  317. const visible = ["cold-first", "cold-second"].map(createMessageId);
  318. const reminderId = createMessageId("cold-reminder");
  319. const server = new ZCodeProtocolAgentServer({
  320. createZCodeApp: fakeApp,
  321. cwd: workspace.workspacePath,
  322. sessionStore: store,
  323. version: "test",
  324. });
  325. try {
  326. for (const id of [sessionId, deletedId]) {
  327. await store.createSession({
  328. id,
  329. projectID: createProjectId("cold-project"),
  330. slug: "cold-history",
  331. directory: workspace.workspacePath,
  332. path: workspace.workspacePath,
  333. title: "cold history",
  334. version: "test",
  335. taskType: "interactive",
  336. });
  337. }
  338. await store.saveMessage({
  339. id: visible[0]!,
  340. sessionID: sessionId,
  341. role: "user",
  342. time: { created: 10 },
  343. agent: "build",
  344. });
  345. await store.saveMessage({
  346. id: reminderId,
  347. sessionID: sessionId,
  348. role: "user",
  349. time: { created: 15 },
  350. agent: "build",
  351. visibility: "model-only",
  352. synthetic: true,
  353. } as never);
  354. await store.saveMessage({
  355. id: visible[1]!,
  356. sessionID: sessionId,
  357. role: "user",
  358. time: { created: 20 },
  359. agent: "build",
  360. });
  361. await store.softDeleteSession(deletedId);
  362. const read = (params: Record<string, unknown>) =>
  363. server.handleMessage({
  364. id: "read-cold",
  365. method: zcodeProtocolMethods.sessionMessages,
  366. params,
  367. });
  368. const cold = await read({ sessionId, limit: 20, direction: "forward" });
  369. expect(cold, JSON.stringify(cold)).toHaveProperty("result");
  370. const messages = zcodeSessionMessagesResultSchema
  371. .parse(cold && "result" in cold ? cold.result : undefined)
  372. .messages.map((message) => message.info.messageId);
  373. // 只返回可见消息,并且没有为读取创建任何 runtime record。
  374. expect(messages).toEqual(visible);
  375. expect(messages).not.toContain(reminderId);
  376. // backward 仍要求活跃 record:不扩大桌面分页历史的读取面。
  377. expect(await read({ sessionId, limit: 20, direction: "backward" })).toHaveProperty("error");
  378. // 软删除与不存在的会话都明确不可用,不返回空页。
  379. expect(await read({ sessionId: deletedId, limit: 20, direction: "forward" })).toHaveProperty(
  380. "error",
  381. );
  382. expect(
  383. await read({ sessionId: "sess_missing-cold", limit: 20, direction: "forward" }),
  384. ).toHaveProperty("error");
  385. } finally {
  386. await server.shutdown();
  387. store.close();
  388. }
  389. });
  390. it.each([
  391. "interactive",
  392. "fork",
  393. "workflow_parent",
  394. "subagent_child",
  395. "workflow_child",
  396. "nested_workflow_child",
  397. "selection_side_chat",
  398. ] as const)("binds only an authorized root kind: %s", async (taskType) => {
  399. let createdOptions: ZCodeAppOptions | undefined;
  400. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  401. const sessionId = createSessionId(`control-${taskType}`);
  402. await store.createSession({
  403. id: sessionId,
  404. projectID: createProjectId("project"),
  405. slug: "session",
  406. directory: workspace.workspacePath,
  407. path: workspace.workspacePath,
  408. title: "session",
  409. version: "test",
  410. taskType,
  411. ...(taskType === "fork" ? { parentID: createSessionId("fork-source") } : {}),
  412. });
  413. const server = new ZCodeProtocolAgentServer({
  414. createZCodeApp: (options) => {
  415. createdOptions = options;
  416. return fakeApp(options);
  417. },
  418. cwd: workspace.workspacePath,
  419. version: "test",
  420. sessionStore: store,
  421. });
  422. advertiseAppControl(server);
  423. const response = await server.handleMessage({
  424. id: `resume-${taskType}`,
  425. method: zcodeProtocolMethods.sessionResume,
  426. params: { workspace, sessionId },
  427. });
  428. expect(response, JSON.stringify(response)).toHaveProperty("result");
  429. const isRoot = ["interactive", "fork", "workflow_parent"].includes(taskType);
  430. expect(createdOptions?.sessionControl?.kind).toBe(isRoot ? "app" : undefined);
  431. if (isRoot) {
  432. expect(createdOptions?.sessionControl?.context().rootSession).toMatchObject({
  433. kind: "app",
  434. workspacePath: "/workspace",
  435. sessionId: createdOptions?.sessionId,
  436. });
  437. }
  438. await server.shutdown();
  439. store.close();
  440. });
  441. it.each(["no-host", "disabled", "old-host"] as const)(
  442. "hides App tools when capabilities are unavailable: %s",
  443. async (kind) => {
  444. let createdOptions: ZCodeAppOptions | undefined;
  445. const server = new ZCodeProtocolAgentServer({
  446. createZCodeApp: (options) => {
  447. createdOptions = options;
  448. return fakeApp(options);
  449. },
  450. cwd: workspace.workspacePath,
  451. version: "test",
  452. });
  453. if (kind === "disabled") advertiseAppControl(server, false);
  454. if (kind === "old-host")
  455. server.setNotificationSink((message) => {
  456. if ("id" in message)
  457. void server.handleMessage({
  458. id: message.id,
  459. error: { code: -32601, message: "Method not found" },
  460. });
  461. });
  462. const response = await server.handleMessage({
  463. id: "root",
  464. method: zcodeProtocolMethods.sessionCreate,
  465. params: { workspace },
  466. });
  467. expect(response, JSON.stringify(response)).toHaveProperty("result");
  468. expect(createdOptions?.sessionControl).toBeUndefined();
  469. await server.shutdown();
  470. },
  471. );
  472. it("does not inherit App control into a parent-linked interactive session", async () => {
  473. let createdOptions: ZCodeAppOptions | undefined;
  474. const server = new ZCodeProtocolAgentServer({
  475. createZCodeApp: (options) => {
  476. createdOptions = options;
  477. return fakeApp(options);
  478. },
  479. cwd: workspace.workspacePath,
  480. version: "test",
  481. });
  482. advertiseAppControl(server);
  483. const response = await server.handleMessage({
  484. id: "child",
  485. method: zcodeProtocolMethods.sessionCreate,
  486. params: { workspace, parentSessionId: "parent" },
  487. });
  488. expect(response).toHaveProperty("result");
  489. expect(createdOptions?.sessionControl).toBeUndefined();
  490. await server.shutdown();
  491. });
  492. });