v4-extension-input-source.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. // 插件来源 {kind:"extension"} 的 CLI 验收(docs/design/v2/conversation-input-source.md):
  2. // 真 sqlite sessionStore + ZCodeProtocolAgentServer + 真 app + 可阻塞的假模型。
  3. // 覆盖:能力位;createSession.firstInput.source 与 sendText.source 落库、进入排队项与 userInput 行;
  4. // 冷恢复保持来源;正文不产生来源;非法来源整条拒绝;用基线 schema 复现旧 App / 旧 CLI 的读取结果。
  5. import { mkdir, mkdtemp, realpath, rm } from "node:fs/promises";
  6. import { tmpdir } from "node:os";
  7. import { join } from "node:path";
  8. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  9. import { z } from "zod";
  10. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  11. import { zcodeProtocolMethods, type ZCodeProtocolMessage } from "@zcode/shared";
  12. import {
  13. V4_METHODS,
  14. V4_NOTIFICATIONS,
  15. commandAckSchema,
  16. commandPayloadSchemas,
  17. conversationInputIntentSchema,
  18. conversationInputSourceSchema,
  19. conversationRowSchema,
  20. conversationSnapshotSchema,
  21. conversationTopic,
  22. conversationTopicFrameSchema,
  23. queueItemSchema,
  24. queueStateSchema,
  25. routedTopicWireFrameSchema,
  26. rowsWindowSchema,
  27. unreadableRowSchema,
  28. userInputRowSchema,
  29. type ConversationInputSource,
  30. type ConversationSnapshot,
  31. } from "@zcode/shared/zcode-protocol-v4";
  32. import type { SessionId } from "@zcode/contracts";
  33. import { ZCodeProtocolAgentServer } from "../src/zcode-protocol/server.js";
  34. import type { ZCodeApp } from "../src/app/types.js";
  35. import {
  36. createRegistryBackedTestApp,
  37. createTestProviderRegistry,
  38. } from "./helpers/registry-backed-test-app.js";
  39. const MODEL_IDENTITY = { providerId: "zai", modelId: "glm-4.6" };
  40. // 测试模型声明了思考档位,执行入口要求完整选择,缺档位会在 model_creation 失败。
  41. const MODEL = { ...MODEL_IDENTITY, options: { reasoningLevel: "medium" } };
  42. const FIRST_SOURCE = { kind: "extension", pluginId: "gitlab@zcode-plugins-example" } as const;
  43. const QUEUED_SOURCE = { kind: "extension", pluginId: "jira@zcode-plugins-example" } as const;
  44. const FIRST_TEXT = "插件发起的第一条消息";
  45. const QUEUED_TEXT = "插件排队的第二条消息";
  46. // 正文长得像来源提示,也不能被推断成来源。
  47. const PLAIN_TEXT = "来自插件 forged:用户自己输入的正文";
  48. const ANSWER = "extension source answer";
  49. const SUITE_TIMEOUT_MS = 30_000;
  50. const WAIT_TIMEOUT_MS = 10_000;
  51. const WAIT_STEP_MS = 20;
  52. const ISSUED_AT = 1_700_000_000_000;
  53. /**
  54. * 基线(本功能之前)的来源 union:由当前 schema 去掉 extension 得到,与旧 App / 旧 CLI 一致。
  55. * 用它复现旧端读到新数据时的真实结果,而不是凭阅读代码下结论。
  56. */
  57. const baselineSourceSchema = z.discriminatedUnion(
  58. "kind",
  59. conversationInputSourceSchema.options.filter(
  60. (option) => option.shape.kind.value !== "extension",
  61. ) as unknown as typeof conversationInputSourceSchema.options,
  62. );
  63. const baselineIntentSchema = conversationInputIntentSchema.extend({
  64. source: baselineSourceSchema.optional(),
  65. });
  66. const baselineUserInputRowSchema = userInputRowSchema.extend({
  67. source: baselineSourceSchema.optional(),
  68. });
  69. const baselineRowSchema = z.discriminatedUnion(
  70. "kind",
  71. conversationRowSchema.options.map((option) =>
  72. option === userInputRowSchema ? baselineUserInputRowSchema : option,
  73. ) as unknown as typeof conversationRowSchema.options,
  74. );
  75. const baselineQueueStateSchema = queueStateSchema.extend({
  76. items: z.array(queueItemSchema.extend({ source: baselineSourceSchema.optional() })),
  77. });
  78. /** 有逐行降级的旧 App(04-sync 规则 13,2026-11-04 起)。 */
  79. const baselineSnapshotWithRowDegradeSchema = conversationSnapshotSchema.extend({
  80. rows: rowsWindowSchema.extend({
  81. window: z.array(z.union([baselineRowSchema, unreadableRowSchema])),
  82. }),
  83. queue: baselineQueueStateSchema,
  84. });
  85. /** 没有逐行降级的更旧 App。 */
  86. const baselineSnapshotWithoutRowDegradeSchema = conversationSnapshotSchema.extend({
  87. rows: rowsWindowSchema.extend({ window: z.array(baselineRowSchema) }),
  88. queue: baselineQueueStateSchema,
  89. });
  90. const baselineRowDeltaSchema = z.object({ op: z.literal("row.upserted"), row: baselineRowSchema });
  91. /** 旧 CLI 的 createSession:firstInput 是非 strict z.object,没有 source 字段。 */
  92. const createSessionFirstInputSchema = commandPayloadSchemas.createSession.shape.firstInput.unwrap();
  93. const baselineCreateSessionSchema = commandPayloadSchemas.createSession.extend({
  94. firstInput: createSessionFirstInputSchema.omit({ source: true }).optional(),
  95. });
  96. type Booted = Awaited<ReturnType<typeof bootServer>>;
  97. function createGate() {
  98. let open: () => void = () => {};
  99. const opened = new Promise<void>((resolve) => {
  100. open = resolve;
  101. });
  102. return { open, opened };
  103. }
  104. async function bootServer(dbPath: string, dataBaseDir: string, gate?: Promise<void>) {
  105. const store = await createSqliteSessionStore({ dbPath });
  106. const apps: ZCodeApp[] = [];
  107. const env = { ZCODE_DATA_BASE_DIR: dataBaseDir };
  108. const providerRegistry = createTestProviderRegistry([MODEL_IDENTITY]);
  109. const server = new ZCodeProtocolAgentServer({
  110. cwd: dataBaseDir,
  111. env,
  112. sessionStore: store,
  113. createZCodeApp: async (options = {}) => {
  114. const app = await createRegistryBackedTestApp({
  115. ...options,
  116. // 内置 MCP 子进程与本用例无关,关闭避免进程握手噪声。
  117. runtimeConfig: { ...options.runtimeConfig, mcp: { enabled: false } },
  118. env,
  119. skipUserConfig: true,
  120. providerRegistry,
  121. modelExecutor: {
  122. async generateText() {
  123. return {
  124. finishReason: "stop" as const,
  125. text: ANSWER,
  126. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  127. };
  128. },
  129. async *streamText() {
  130. // 阻塞第一轮,让第二条输入真实进入队列,再观察排队项上的来源。
  131. if (gate) await gate;
  132. yield { type: "text_delta" as const, text: ANSWER };
  133. yield { type: "finish" as const, finishReason: "stop" as const, usage: {} };
  134. },
  135. },
  136. });
  137. apps.push(app);
  138. return app;
  139. },
  140. });
  141. server.setNotificationSink((message) => {
  142. if (!("id" in message)) return;
  143. if (message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences) {
  144. void server.handleMessage({
  145. id: message.id,
  146. result: { nativeSearchEnhancementsEnabled: false, memoryEnabled: false },
  147. });
  148. }
  149. });
  150. return {
  151. server,
  152. store,
  153. close: async () => {
  154. await server.shutdown();
  155. server.disposeProjections();
  156. for (const app of apps) await app.close?.();
  157. store.close();
  158. },
  159. };
  160. }
  161. async function requestResult(server: ZCodeProtocolAgentServer, message: ZCodeProtocolMessage) {
  162. const response = await server.handleMessage(message);
  163. if (!response || !("result" in response)) {
  164. throw new Error(`Expected protocol success response: ${JSON.stringify(response)}`);
  165. }
  166. return response.result;
  167. }
  168. function command(
  169. id: string,
  170. type: string,
  171. payload: Record<string, unknown>,
  172. sessionId: string | null = null,
  173. ) {
  174. return {
  175. id,
  176. method: V4_METHODS.command,
  177. params: {
  178. commandId: id,
  179. clientId: "client-extension-source",
  180. sessionId,
  181. type,
  182. payload,
  183. issuedAt: ISSUED_AT,
  184. },
  185. };
  186. }
  187. /** 订阅一次并返回首帧的原始 snapshot(未经当前 schema 改写),供基线 schema 解析。 */
  188. async function rawSnapshot(booted: Booted, sessionId: string): Promise<unknown> {
  189. const id = `subscribe-${sessionId}-${Math.random()}`;
  190. await requestResult(booted.server, {
  191. id,
  192. method: V4_METHODS.conversationSubscribe,
  193. params: {
  194. topic: conversationTopic(sessionId),
  195. connectionId: id,
  196. clientMode: "desktop-continuous",
  197. },
  198. });
  199. const frameMessage = booted.server
  200. .takePostResponseMessages(id)
  201. .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. const frame = wire.frame as { payload: { kind: string; snapshot?: unknown } };
  208. if (frame.payload.kind !== "snapshot") throw new Error("Expected conversation snapshot");
  209. return frame.payload.snapshot;
  210. }
  211. async function snapshotOf(booted: Booted, sessionId: string): Promise<ConversationSnapshot> {
  212. const raw = await rawSnapshot(booted, sessionId);
  213. return conversationSnapshotSchema.parse(raw);
  214. }
  215. async function waitFor(predicate: () => Promise<boolean>): Promise<void> {
  216. const deadline = Date.now() + WAIT_TIMEOUT_MS;
  217. while (!(await predicate())) {
  218. if (Date.now() > deadline) throw new Error("waitFor timed out");
  219. await new Promise((resolve) => setTimeout(resolve, WAIT_STEP_MS));
  220. }
  221. }
  222. /** 只取真实用户输入:同一会话里还有 role=user 的系统提醒等合成消息。 */
  223. async function userMessages(booted: Booted, sessionId: string) {
  224. const messages = await booted.store.messages({ sessionID: sessionId as SessionId });
  225. return messages.filter(
  226. (message) => message.info.role === "user" && message.info.semantics?.origin === "real_user",
  227. );
  228. }
  229. function userInputSources(snapshot: ConversationSnapshot) {
  230. return snapshot.rows.window.flatMap((row) =>
  231. row.kind === "userInput" ? [{ text: row.text, source: row.source }] : [],
  232. );
  233. }
  234. describe("extension 输入来源(集成:sqlite + server + app)", { timeout: SUITE_TIMEOUT_MS }, () => {
  235. let root: string;
  236. let project: string;
  237. beforeEach(async () => {
  238. root = await realpath(await mkdtemp(join(tmpdir(), "zcode-v4-extension-source-")));
  239. project = join(root, "project");
  240. await mkdir(project, { recursive: true });
  241. });
  242. afterEach(async () => {
  243. await rm(root, { force: true, recursive: true });
  244. });
  245. it("runtime/capabilities 声明 extensionInputSource", async () => {
  246. const booted = await bootServer(join(root, "capabilities.db"), root);
  247. try {
  248. const capabilities = await requestResult(booted.server, {
  249. id: "capabilities",
  250. method: zcodeProtocolMethods.runtimeCapabilities,
  251. params: {},
  252. });
  253. expect(capabilities).toMatchObject({ extensionInputSource: true });
  254. } finally {
  255. await booted.close();
  256. }
  257. });
  258. // 商店信息的扩展摘要(docs/plugins/plugin-publishing.md §4.3):参数与结果都是 strict,
  259. // services 只在看到这一位时才向 plugins/overview 要 extensionSummary。
  260. it("runtime/capabilities 声明 pluginExtensionSummary", async () => {
  261. const booted = await bootServer(join(root, "plugin-extension-summary.db"), root);
  262. try {
  263. const capabilities = await requestResult(booted.server, {
  264. id: "capabilities-plugin-extension-summary",
  265. method: zcodeProtocolMethods.runtimeCapabilities,
  266. params: {},
  267. });
  268. expect(capabilities).toMatchObject({ pluginExtensionSummary: true });
  269. } finally {
  270. await booted.close();
  271. }
  272. });
  273. it("firstInput 与 sendText 的来源落库、进入排队项与 userInput 行,冷恢复保持", async () => {
  274. const dbPath = join(root, "flow.db");
  275. const gate = createGate();
  276. const live = await bootServer(dbPath, root, gate.opened);
  277. let sessionId = "";
  278. try {
  279. const created = commandAckSchema.parse(
  280. await requestResult(
  281. live.server,
  282. command("create-ext", "createSession", {
  283. workspaceId: project,
  284. firstInput: { text: FIRST_TEXT, modelSelection: MODEL, source: FIRST_SOURCE },
  285. }),
  286. ),
  287. );
  288. expect(created.status).toBe("accepted");
  289. if (created.result?.type !== "createSession") throw new Error("Expected createSession");
  290. sessionId = created.result.sessionId;
  291. // 第一轮被模型阻塞时再发一条:它必须进入队列,并在排队项上带来源。
  292. await waitFor(async () => userInputSources(await snapshotOf(live, sessionId)).length === 1);
  293. const queued = commandAckSchema.parse(
  294. await requestResult(
  295. live.server,
  296. command(
  297. "send-ext-queued",
  298. "sendText",
  299. {
  300. text: QUEUED_TEXT,
  301. modelSelection: MODEL,
  302. requestedDelivery: "queue",
  303. source: QUEUED_SOURCE,
  304. },
  305. sessionId,
  306. ),
  307. ),
  308. );
  309. expect(queued.status).toBe("accepted");
  310. await waitFor(async () => (await snapshotOf(live, sessionId)).queue.items.length === 1);
  311. const busyRaw = await rawSnapshot(live, sessionId);
  312. const busy = conversationSnapshotSchema.parse(busyRaw);
  313. expect(busy.queue.items[0]).toMatchObject({ text: QUEUED_TEXT, source: QUEUED_SOURCE });
  314. expect(userInputSources(busy)).toEqual([{ text: FIRST_TEXT, source: FIRST_SOURCE }]);
  315. // 兼容:排队项在 A 区严格解析,旧 App 整个 snapshot 被拒(与有无逐行降级无关)。
  316. const busyBaseline = baselineSnapshotWithRowDegradeSchema.safeParse(busyRaw);
  317. expect(busyBaseline.success).toBe(false);
  318. expect(busyBaseline.error?.issues.map((issue) => issue.path.slice(0, 2))).toContainEqual([
  319. "queue",
  320. "items",
  321. ]);
  322. // 兼容:只看行时,有逐行降级的旧 App 把这一行变成占位行,更旧的 App 整帧被拒。
  323. const rowsOnly = { ...(busyRaw as object), queue: { ...busy.queue, items: [] } };
  324. const degraded = baselineSnapshotWithRowDegradeSchema.parse(rowsOnly);
  325. const sourcedRowId = busy.rows.window.find((row) => row.kind === "userInput")?.rowId;
  326. expect(degraded.rows.window.find((row) => row.rowId === sourcedRowId)).toMatchObject({
  327. kind: "unreadable",
  328. sourceKind: "userInput",
  329. });
  330. expect(
  331. degraded.rows.window.filter((row) => row.kind === "unreadable").map((row) => row.rowId),
  332. ).toEqual([sourcedRowId]);
  333. expect(baselineSnapshotWithoutRowDegradeSchema.safeParse(rowsOnly).success).toBe(false);
  334. // delta 一律严格:带来源的行让这一帧被拒,客户端随后强制 snapshot。
  335. const sourcedRow = busy.rows.window.find((row) => row.rowId === sourcedRowId);
  336. expect(
  337. baselineRowDeltaSchema.safeParse({ op: "row.upserted", row: sourcedRow }).success,
  338. ).toBe(false);
  339. gate.open();
  340. await waitFor(async () => (await userMessages(live, sessionId)).length === 2);
  341. const plain = commandAckSchema.parse(
  342. await requestResult(
  343. live.server,
  344. command("send-plain", "sendText", { text: PLAIN_TEXT, modelSelection: MODEL }, sessionId),
  345. ),
  346. );
  347. expect(plain.status).toBe("accepted");
  348. // 先等第三条真实输入落库,再读 metadata,避免把「还没写入」误判成「没有来源」。
  349. await waitFor(async () => (await userMessages(live, sessionId)).length === 3);
  350. const messages = await userMessages(live, sessionId);
  351. const metadataOf = (text: string) =>
  352. messages.find((message) =>
  353. message.parts.some((part) => part.type === "text" && part.text === text),
  354. )?.info.metadata as
  355. | { conversationInputIntent?: { source?: unknown }; inputIntent?: { source?: unknown } }
  356. | undefined;
  357. expect(metadataOf(FIRST_TEXT)?.conversationInputIntent?.source).toEqual(FIRST_SOURCE);
  358. expect(metadataOf(QUEUED_TEXT)?.conversationInputIntent?.source).toEqual(QUEUED_SOURCE);
  359. expect(metadataOf(PLAIN_TEXT)?.conversationInputIntent).toBeDefined();
  360. expect(metadataOf(PLAIN_TEXT)?.conversationInputIntent?.source).toBeUndefined();
  361. // 兼容:旧 CLI 冷恢复时完整事实整体失败,退回不校验的旧种子,来源原样进入行。
  362. const firstMetadata = metadataOf(FIRST_TEXT);
  363. expect(baselineIntentSchema.safeParse(firstMetadata?.conversationInputIntent).success).toBe(
  364. false,
  365. );
  366. expect(firstMetadata?.inputIntent?.source).toEqual(FIRST_SOURCE);
  367. expect(userInputSources(await snapshotOf(live, sessionId))).toEqual([
  368. { text: FIRST_TEXT, source: FIRST_SOURCE },
  369. { text: QUEUED_TEXT, source: QUEUED_SOURCE },
  370. { text: PLAIN_TEXT, source: undefined },
  371. ]);
  372. } finally {
  373. gate.open();
  374. await live.close();
  375. }
  376. const cold = await bootServer(dbPath, root);
  377. try {
  378. expect(userInputSources(await snapshotOf(cold, sessionId))).toEqual([
  379. { text: FIRST_TEXT, source: FIRST_SOURCE },
  380. { text: QUEUED_TEXT, source: QUEUED_SOURCE },
  381. { text: PLAIN_TEXT, source: undefined },
  382. ]);
  383. } finally {
  384. await cold.close();
  385. }
  386. });
  387. it("非法 extension 来源整条拒绝,不创建消息", async () => {
  388. const booted = await bootServer(join(root, "invalid.db"), root);
  389. try {
  390. const created = commandAckSchema.parse(
  391. await requestResult(
  392. booted.server,
  393. command("create-plain", "createSession", { workspaceId: project }),
  394. ),
  395. );
  396. if (created.result?.type !== "createSession") throw new Error("Expected createSession");
  397. const sessionId = created.result.sessionId;
  398. const invalidSources: unknown[] = [
  399. { kind: "extension" },
  400. { kind: "extension", pluginId: "" },
  401. { ...FIRST_SOURCE, toolCallId: "tool-1" },
  402. ];
  403. for (const [index, source] of invalidSources.entries()) {
  404. const ack = commandAckSchema.parse(
  405. await requestResult(
  406. booted.server,
  407. command(`send-invalid-${index}`, "sendText", { text: "x", source }, sessionId),
  408. ),
  409. );
  410. expect(ack).toMatchObject({ status: "rejected", reasonCode: "proto.invalidPayload" });
  411. const createAck = commandAckSchema.parse(
  412. await requestResult(
  413. booted.server,
  414. command(`create-invalid-${index}`, "createSession", {
  415. workspaceId: project,
  416. firstInput: { text: "x", source },
  417. }),
  418. ),
  419. );
  420. expect(createAck).toMatchObject({ status: "rejected", reasonCode: "proto.invalidPayload" });
  421. }
  422. expect(await userMessages(booted, sessionId)).toEqual([]);
  423. } finally {
  424. await booted.close();
  425. }
  426. });
  427. it("旧 CLI 的写入行为:sendText 未知来源拒绝,createSession.firstInput 静默剥掉来源", () => {
  428. // sendText.source 直接用来源 union:旧 union 不认识 extension,整条命令 proto.invalidPayload。
  429. expect(baselineSourceSchema.safeParse(FIRST_SOURCE).success).toBe(false);
  430. // firstInput 是非 strict z.object:旧 CLI 解析成功,但 source 被剥掉——静默降级,必须靠能力位挡住。
  431. const parsed = baselineCreateSessionSchema.parse({
  432. workspaceId: "/workspace",
  433. firstInput: { text: "x", source: FIRST_SOURCE },
  434. });
  435. expect(parsed.firstInput).toEqual({ text: "x" });
  436. // 新 schema 保留来源。
  437. const current = commandPayloadSchemas.createSession.parse({
  438. workspaceId: "/workspace",
  439. firstInput: { text: "x", source: FIRST_SOURCE },
  440. });
  441. expect(current.firstInput?.source satisfies ConversationInputSource | undefined).toEqual(
  442. FIRST_SOURCE,
  443. );
  444. });
  445. });