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

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