plugin-install-interaction.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. createSessionEvent,
  4. SessionEventType,
  5. type SessionId,
  6. type TurnId,
  7. type SessionEvent,
  8. } from "@zcode/contracts";
  9. import {
  10. conversationSnapshotSchema,
  11. pluginInstallRequestPayloadSchema,
  12. boundPluginLocalizedText,
  13. filterConversationDeltasForProfile,
  14. DELIVERY_PROFILES,
  15. } from "@zcode/shared/zcode-protocol-v4";
  16. import { confirmPluginInstall } from "../src/zcode-protocol/plugin-install-interaction.js";
  17. import { V4InteractionRegistry } from "../src/zcode-protocol-v4/interaction-registry.js";
  18. import { ConversationTopicPublisher } from "../src/zcode-protocol-v4/conversation-topic-publisher.js";
  19. import { ProductProjection } from "../src/zcode-protocol-v4/product-projection.js";
  20. import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
  21. const plugin = {
  22. pluginId: "mail@zcode-plugins-official",
  23. name: "mail",
  24. installed: false,
  25. enabled: false,
  26. action: "install" as const,
  27. scope: "user" as const,
  28. };
  29. function setup() {
  30. const registry = new V4InteractionRegistry();
  31. const projection = new ProductProjection("session", "epoch");
  32. let seq = 0;
  33. const events: SessionEvent[] = [];
  34. const emitEvent = async (event: SessionEvent) => {
  35. event.sequenceNumber = ++seq;
  36. events.push(event);
  37. projection.applyEvent(event);
  38. };
  39. void emitEvent(
  40. createSessionEvent(SessionEventType.SessionCreated, "session" as SessionId, {
  41. mode: "build",
  42. contextWindow: 200_000,
  43. }),
  44. );
  45. void emitEvent(
  46. createSessionEvent(SessionEventType.TurnStarted, "session" as SessionId, {
  47. turnNumber: 1,
  48. input: "email",
  49. }),
  50. );
  51. return {
  52. registry,
  53. projection,
  54. events,
  55. emitEvent,
  56. server: { v4Interactions: registry } as ZCodeProtocolAgentServerContext,
  57. };
  58. }
  59. describe("plugin installation interaction", () => {
  60. const locales = () =>
  61. Object.fromEntries([
  62. ...Array.from({ length: 5_000 }, (_, index) => [`x-${index}`, '\"\n🚀'.repeat(2_000)]),
  63. ...["zh-CN", "en-US", "ja-JP", "ru-RU", "ko-KR"].map((locale) => [locale, `UI ${locale}`]),
  64. ]);
  65. it.each([
  66. ["count", Object.fromEntries(Array.from({ length: 17 }, (_, n) => [`x-${n}`, "ok"]))],
  67. ["key", { ["x".repeat(65)]: "ok" }],
  68. ["characters", { en: "a".repeat(4_001) }],
  69. ["encoded value", { en: "\n".repeat(3_000) }],
  70. [
  71. "encoded record",
  72. Object.fromEntries(Array.from({ length: 7 }, (_, n) => [`x-${n}`, "a".repeat(4_000)])),
  73. ],
  74. ])("rejects localized maps exceeding the %s budget before persistence", (_kind, map) => {
  75. const result = pluginInstallRequestPayloadSchema.safeParse({
  76. kind: "pluginInstall",
  77. pluginId: plugin.pluginId,
  78. name: plugin.name,
  79. descriptionI18n: map,
  80. reason: "Read emails",
  81. action: "install",
  82. scope: "user",
  83. toolCallId: "tool",
  84. });
  85. expect(result.success).toBe(false);
  86. });
  87. it("keeps supported language fallbacks, ignores invalid or inherited keys and stays idempotent", () => {
  88. const raw: Record<string, string> = Object.assign(Object.create({ "zh-CN": "Inherited" }), {
  89. ["x".repeat(65)]: "Invalid key",
  90. "": "Empty key",
  91. ...Object.fromEntries(Array.from({ length: 40 }, (_, n) => [`x-${n}`, "extra"])),
  92. "en-GB": "Mail",
  93. "zh-TW": "郵件",
  94. ja: "メール",
  95. ru: "Почта",
  96. ko: "메일",
  97. });
  98. const bounded = boundPluginLocalizedText(raw)!;
  99. expect(Object.keys(bounded)).toHaveLength(16);
  100. expect(bounded).toMatchObject({
  101. "en-GB": "Mail",
  102. "zh-TW": "郵件",
  103. ja: "メール",
  104. ru: "Почта",
  105. ko: "메일",
  106. });
  107. expect(bounded["zh-CN"]).toBeUndefined();
  108. expect(bounded[""]).toBeUndefined();
  109. expect(bounded["x".repeat(65)]).toBeUndefined();
  110. expect(boundPluginLocalizedText(bounded)).toEqual(bounded);
  111. });
  112. it("bounds a huge localized install request and preserves UI languages through serialized event replay", async () => {
  113. const { server, emitEvent, events, projection } = setup();
  114. const controller = new AbortController();
  115. const pending = confirmPluginInstall(
  116. server,
  117. {
  118. ...plugin,
  119. displayName: "Default name",
  120. description: "Default description",
  121. displayNameI18n: locales(),
  122. descriptionI18n: locales(),
  123. },
  124. "Read emails",
  125. {
  126. sessionId: "session",
  127. toolCallId: "tool",
  128. traceId: "trace",
  129. signal: controller.signal,
  130. emitEvent,
  131. },
  132. );
  133. try {
  134. await Promise.resolve();
  135. const request = projection.getSnapshot().pendingInteractions[0]?.payload;
  136. expect(request?.kind).toBe("pluginInstall");
  137. if (request?.kind !== "pluginInstall") throw new Error("Missing install request");
  138. expect(request.displayName).toBe("Default name");
  139. expect(request.description).toBe("Default description");
  140. for (const map of [request.displayNameI18n, request.descriptionI18n]) {
  141. expect(map).toBeDefined();
  142. expect(Object.keys(map!).length).toBeLessThanOrEqual(16);
  143. expect(Buffer.byteLength(JSON.stringify(map))).toBeLessThanOrEqual(24 * 1_024);
  144. for (const locale of ["zh-CN", "en-US", "ja-JP", "ru-RU", "ko-KR"]) {
  145. expect(map![locale]).toBe(`UI ${locale}`);
  146. }
  147. for (const text of Object.values(map!)) {
  148. expect(text.length).toBeLessThanOrEqual(4_000);
  149. expect(Buffer.byteLength(JSON.stringify(text))).toBeLessThanOrEqual(4_096);
  150. expect(text).not.toMatch(/[\uD800-\uDBFF]$/u);
  151. }
  152. }
  153. const replay = new ProductProjection("session", "epoch");
  154. for (const event of JSON.parse(JSON.stringify(events)) as SessionEvent[]) {
  155. replay.applyEvent({ ...event, timestamp: new Date(event.timestamp) });
  156. }
  157. const restored = replay.getSnapshot();
  158. expect(conversationSnapshotSchema.safeParse(restored).success).toBe(true);
  159. expect(restored.pendingInteractions[0]?.payload).toEqual(request);
  160. } finally {
  161. controller.abort();
  162. await pending.catch(() => undefined);
  163. }
  164. });
  165. it("filters pending installs for legacy snapshot, live patches and gap replay while a capable phone can reconnect", async () => {
  166. const { server, emitEvent, events } = setup();
  167. const publisher = new ConversationTopicPublisher("session", "epoch");
  168. for (const event of events) publisher.ingest(event);
  169. const legacy = publisher.subscribe({ connectionId: "legacy" });
  170. const base = { logEpoch: "epoch", seq: publisher.getSnapshot().seq };
  171. const controller = new AbortController();
  172. const pending = confirmPluginInstall(
  173. server,
  174. { ...plugin, descriptionI18n: locales() },
  175. "Read emails",
  176. {
  177. sessionId: "session",
  178. toolCallId: "tool",
  179. traceId: "trace",
  180. signal: controller.signal,
  181. emitEvent: async (event) => {
  182. await emitEvent(event);
  183. publisher.ingest(event);
  184. },
  185. },
  186. );
  187. try {
  188. await Promise.resolve();
  189. const frame = (id: string, capability = false) =>
  190. publisher.subscribe({
  191. connectionId: id,
  192. pluginDiscoveryUi: capability,
  193. }).frame;
  194. expect(JSON.stringify(frame("phone", true))).toContain('"kind":"pluginInstall"');
  195. expect(JSON.stringify(frame("old"))).not.toContain('"kind":"pluginInstall"');
  196. expect(JSON.stringify(publisher.flush(legacy.ack.subscriptionId))).not.toContain(
  197. '"kind":"pluginInstall"',
  198. );
  199. const replay = publisher.subscribe({ connectionId: "legacy", base });
  200. expect(replay.ack.mode).toBe("resume");
  201. expect(JSON.stringify(replay.frame)).not.toContain('"kind":"pluginInstall"');
  202. const upgrade = publisher.subscribe({
  203. connectionId: "legacy",
  204. base: { logEpoch: "epoch", seq: publisher.getSnapshot().seq },
  205. pluginDiscoveryUi: true,
  206. });
  207. expect(upgrade.ack.mode).toBe("snapshot");
  208. expect(JSON.stringify(upgrade.frame)).toContain('"kind":"pluginInstall"');
  209. expect(server.v4Interactions.has("plugin-install:session:tool")).toBe(true);
  210. } finally {
  211. controller.abort();
  212. await expect(pending).rejects.toThrow();
  213. }
  214. });
  215. it("does not resurrect an old turn's card after a new turn starts", async () => {
  216. const { emitEvent, projection } = setup();
  217. await emitEvent(
  218. createSessionEvent(
  219. SessionEventType.TurnStarted,
  220. "session" as SessionId,
  221. { turnNumber: 2, input: "new request" },
  222. { turnId: "new-turn" as TurnId },
  223. ),
  224. );
  225. await emitEvent(
  226. createSessionEvent(
  227. SessionEventType.PluginInstallRequested,
  228. "session" as SessionId,
  229. {
  230. interactionId: "old-confirm",
  231. request: {
  232. kind: "pluginInstall",
  233. pluginId: plugin.pluginId,
  234. name: plugin.name,
  235. reason: "Old request",
  236. action: "install",
  237. scope: "user",
  238. toolCallId: "old-tool",
  239. },
  240. },
  241. { turnId: "old-turn" as TurnId },
  242. ),
  243. );
  244. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  245. });
  246. it("survives waiting and projects the same immutable card to both profiles, with first-answer wins", async () => {
  247. vi.useFakeTimers();
  248. try {
  249. const { server, registry, projection, emitEvent } = setup();
  250. const pending = confirmPluginInstall(server, plugin, "Read emails", {
  251. sessionId: "session",
  252. toolCallId: "tool",
  253. traceId: "trace",
  254. signal: new AbortController().signal,
  255. emitEvent,
  256. });
  257. await Promise.resolve();
  258. const snapshot = conversationSnapshotSchema.parse(projection.getSnapshot());
  259. const card = snapshot.pendingInteractions[0]!;
  260. expect(card.kind).toBe("pluginInstall");
  261. expect(card.autoResolution).toBeUndefined();
  262. const delta = [{ op: "state.updated" as const, patch: { pendingInteractions: [card] } }];
  263. for (const profile of Object.values(DELIVERY_PROFILES)) {
  264. expect(filterConversationDeltasForProfile(delta, profile)).toEqual(delta);
  265. }
  266. await vi.advanceTimersByTimeAsync(10 * 60_000);
  267. expect(registry.has(card.interactionId)).toBe(true);
  268. expect(registry.resolve(card.interactionId, { optionId: "install" }, null)).toBe(false);
  269. expect(registry.resolve(card.interactionId, { optionId: "install" }, "wrong-session")).toBe(
  270. false,
  271. );
  272. expect(registry.resolve(card.interactionId, { optionId: "install" }, "session")).toBe(false);
  273. expect(registry.resolve(card.interactionId, { optionId: "install" }, "session", true)).toBe(
  274. true,
  275. );
  276. expect(registry.resolve(card.interactionId, { optionId: "install" }, "session")).toBe(false);
  277. expect(await pending).toBe(true);
  278. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  279. } finally {
  280. vi.useRealTimers();
  281. }
  282. });
  283. it.each(["skip", "allowAlways", "unknown"])("never installs for %s", async (optionId) => {
  284. const { server, registry, emitEvent, events } = setup();
  285. const pending = confirmPluginInstall(server, plugin, "Read emails", {
  286. sessionId: "session",
  287. toolCallId: "tool",
  288. traceId: "trace",
  289. signal: new AbortController().signal,
  290. emitEvent,
  291. });
  292. registry.resolve("plugin-install:session:tool", { optionId }, "session", true);
  293. expect(await pending).toBe(false);
  294. expect(events.at(-1)?.payload).toMatchObject({ decision: "skip" });
  295. });
  296. it("cancellation clears the registry and pending card without approval", async () => {
  297. const { server, registry, emitEvent, projection } = setup();
  298. const controller = new AbortController();
  299. const pending = confirmPluginInstall(server, plugin, "Read emails", {
  300. sessionId: "session",
  301. toolCallId: "tool",
  302. traceId: "trace",
  303. signal: controller.signal,
  304. emitEvent,
  305. });
  306. controller.abort();
  307. await expect(pending).rejects.toThrow();
  308. expect(registry.has("plugin-install:session:tool")).toBe(false);
  309. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  310. });
  311. });