sampling-main.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import { app, protocol } from "electron";
  2. import assert from "node:assert/strict";
  3. import { writeFile } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import { PLUGIN_SANDBOX_PRIVILEGED_SCHEME } from "../../src/main/pluginSandbox/index.js";
  6. import { checkSamplingExtras } from "./sampling-extra-checks.js";
  7. import { managedEnvironment } from "./managed-environment.js";
  8. const [root, profile, node, cli] = process.argv.slice(2) as [string, string, string, string];
  9. app.setPath("userData", profile);
  10. protocol.registerSchemesAsPrivileged([PLUGIN_SANDBOX_PRIVILEGED_SCHEME]);
  11. app.on("window-all-closed", () => {});
  12. app
  13. .whenReady()
  14. .then(async () => {
  15. const env = await managedEnvironment(root, node, cli);
  16. const checks: { name: string; ms: number }[] = [];
  17. const check = async (name: string, run: () => Promise<void>) => {
  18. const start = performance.now();
  19. let timer: ReturnType<typeof setTimeout>;
  20. try {
  21. await Promise.race([
  22. run(),
  23. new Promise<never>((_, reject) => {
  24. timer = setTimeout(
  25. () => reject(new Error(`Timed out: ${name}`)),
  26. name.includes("keep-warm") ? 45_000 : 20_000,
  27. );
  28. }),
  29. ]);
  30. checks.push({ name, ms: performance.now() - start });
  31. process.stdout.write(`PASS ${name}\n`);
  32. } catch (error) {
  33. await writeFile(
  34. join(root, "sampling-failure.json"),
  35. JSON.stringify(
  36. {
  37. name,
  38. requests: env.model.requests.history,
  39. approvals: env.agent.approvals.history,
  40. events: env.events.history.slice(-20),
  41. notifications: env.agent.notifications.history.slice(-10),
  42. },
  43. null,
  44. 2,
  45. ),
  46. );
  47. throw error;
  48. } finally {
  49. clearTimeout(timer!);
  50. }
  51. };
  52. try {
  53. const scope = await env.agent.session(join(root, "sampling-workspace"), "sampling");
  54. await env.agent.call("session/setModel", {
  55. sessionId: scope.sessionId,
  56. model: env.model.selection,
  57. });
  58. const started = performance.now();
  59. const win = await env.createWindow(scope, "sampling");
  60. const coldPageMs = performance.now() - started;
  61. const page = (code: string) => env.evalPage(win, code);
  62. const ui = (code: string) => win.webContents.executeJavaScript(code);
  63. const request = {
  64. messages: [{ role: "user", content: { type: "text", text: "What is 1 + 1?" } }],
  65. maxTokens: 128,
  66. };
  67. const sample = (key: string, params: any = request) =>
  68. page(`window.sample(${JSON.stringify(key)},${JSON.stringify(params)})`);
  69. const binding = (operationId: string) => ({
  70. ...scope,
  71. instance: env.handles.get(win.webContents.id).instance,
  72. operationId,
  73. });
  74. const mainBefore = await env.agent.call("session/read", { sessionId: scope.sessionId });
  75. await check(
  76. "official SDK sampling capability and app-owned three-round conversation",
  77. async () => {
  78. assert.deepEqual((await page("window.samplingCapabilities()")).sampling, {});
  79. const messages: any[] = [];
  80. for (let i = 0; i < 3; i++) {
  81. const key = `round-${i}`;
  82. messages.push({ role: "user", content: { type: "text", text: `question ${i}` } });
  83. env.model.plans.push({ key, delayed: false });
  84. const reply = await sample(key, { ...request, messages });
  85. assert.equal(reply.result.content.text, `answer:${key}`);
  86. assert.equal(reply.result.model, "gpt-4o");
  87. assert.equal(reply.result.stopReason, "endTurn");
  88. messages.push({ role: "assistant", content: reply.result.content });
  89. const sent = env.model.requests.history.at(-1).body;
  90. assert.equal(sent.messages.length, i * 2 + 1);
  91. assert.equal(sent.tools, undefined);
  92. }
  93. assert.equal(env.agent.approvals.history.length, 0);
  94. const after = await env.agent.call("session/read", { sessionId: scope.sessionId });
  95. assert.deepEqual(after.messages, mainBefore.messages);
  96. await ui("window.waitSamplingIdle()");
  97. assert.equal((await ui("window.managedState()")).busy, false);
  98. },
  99. );
  100. await check(
  101. "text plus image, explicit system prompt, token limit, advisory model hints",
  102. async () => {
  103. const image = {
  104. type: "image",
  105. mimeType: "image/png",
  106. data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/lS8AAAAASUVORK5CYII=",
  107. };
  108. const reply = await sample("image", {
  109. ...request,
  110. messages: [{ role: "user", content: [request.messages[0].content, image] }],
  111. systemPrompt: "Teach basic maths.",
  112. maxTokens: 17,
  113. modelPreferences: { hints: [{ name: "unavailable-model" }] },
  114. includeContext: "none",
  115. });
  116. assert.equal(reply.result.model, "gpt-4o");
  117. const sent = env.model.requests.history.at(-1).body;
  118. assert.equal(sent.model, "gpt-4o");
  119. assert.equal(sent.messages[0].content, "Teach basic maths.");
  120. assert.ok(JSON.stringify(sent.messages).includes(`data:image/png;base64,${image.data}`));
  121. assert.equal(sent.max_tokens ?? sent.max_completion_tokens, 17);
  122. },
  123. );
  124. await check(
  125. "unsupported content/options and non-actionable task fail before provider",
  126. async () => {
  127. const count = env.model.requests.history.length;
  128. for (const invalid of [
  129. { temperature: 0.5 },
  130. { stopSequences: ["END"] },
  131. { includeContext: "allServers" },
  132. { tools: [] },
  133. {
  134. messages: [
  135. { role: "user", content: { type: "audio", mimeType: "audio/wav", data: "AAAA" } },
  136. ],
  137. },
  138. ]) {
  139. assert.ok(
  140. (await sample("invalid", { ...request, ...invalid })).error,
  141. JSON.stringify(invalid),
  142. );
  143. }
  144. await ui("window.setSamplingEnabled(false)");
  145. assert.ok((await sample("read-only")).error);
  146. await ui("window.setSamplingEnabled(true)");
  147. assert.equal(env.model.requests.history.length, count);
  148. // 官方 SDK 在宿主 handler 前过滤非协议字段;它们不能覆盖绑定模型。
  149. assert.equal(
  150. (await sample("ignored-provider", { ...request, providerId: "other" })).result.model,
  151. "gpt-4o",
  152. );
  153. await assert.rejects(() =>
  154. env.agent.call("mcp/uiSampling", {
  155. ...binding("injected-provider"),
  156. request: { ...request, providerId: "other" },
  157. }),
  158. );
  159. },
  160. );
  161. await check("SDK cancellation aborts HTTP, frees busy state, and never replays", async () => {
  162. env.model.plans.push({ key: "cancel", delayed: true });
  163. const result = sample("cancel");
  164. await env.model.requests.wait((e) => e.plan?.key === "cancel");
  165. await page("window.cancelSample('cancel')");
  166. assert.ok((await result).error);
  167. await env.model.aborted.wait((key) => key === "cancel");
  168. await env.events.wait((e) => e.type === "bridge" && e.method === "cancelSampling");
  169. env.model.release("cancel");
  170. assert.equal(env.model.requests.history.filter((e) => e.plan?.key === "cancel").length, 1);
  171. });
  172. await check(
  173. "pending sampling survives twenty inline-sidebar moves and prevents recycle",
  174. async () => {
  175. env.model.plans.push({ key: "move", delayed: true });
  176. const result = sample("move");
  177. await env.model.requests.wait((e) => e.plan?.key === "move");
  178. const guestId = env.guests.get(win.webContents.id)!.id;
  179. const before = await ui("window.managedState()");
  180. const reads = env.agent.events.history.filter((e) => e.type === "read").length;
  181. assert.equal(before.busy, true);
  182. assert.equal(await ui("window.suspendManaged()"), false);
  183. assert.ok((await sample("concurrent")).error);
  184. for (let i = 0; i < 20; i++) await ui(`window.setAnchors(${i % 2 === 0},${i % 2 !== 0})`);
  185. const after = await ui("window.managedState()");
  186. assert.equal(env.guests.get(win.webContents.id)!.id, guestId);
  187. assert.deepEqual(after.handle, before.handle);
  188. assert.deepEqual(after.listeners, before.listeners);
  189. assert.equal(after.views, 1);
  190. assert.equal(env.agent.events.history.filter((e) => e.type === "read").length, reads);
  191. env.model.release("move");
  192. assert.equal((await result).result.content.text, "answer:move");
  193. await ui("window.waitSamplingIdle()");
  194. assert.equal((await ui("window.managedState()")).busy, false);
  195. },
  196. );
  197. await check(
  198. "Agent pre-admission cancellation, duplicate operation and forged credential",
  199. async () => {
  200. const before = env.model.requests.history.length;
  201. const cancelled = binding("cancel-before");
  202. assert.equal((await env.agent.call("mcp/uiCancelSampling", cancelled)).cancelled, false);
  203. await assert.rejects(() => env.agent.call("mcp/uiSampling", { ...cancelled, request }));
  204. const complete = binding("complete-once");
  205. await env.agent.call("mcp/uiSampling", { ...complete, request });
  206. await assert.rejects(() => env.agent.call("mcp/uiSampling", { ...complete, request }));
  207. assert.equal((await env.agent.call("mcp/uiCancelSampling", complete)).cancelled, false);
  208. await assert.rejects(() =>
  209. env.agent.call("mcp/uiSampling", {
  210. ...binding("forged"),
  211. instance: { ...complete.instance, token: "forged" },
  212. request,
  213. }),
  214. );
  215. await assert.rejects(() =>
  216. env.agent.call("mcp/uiSampling", {
  217. ...binding("wrong-server"),
  218. serverName: "different",
  219. request,
  220. }),
  221. );
  222. assert.equal(env.model.requests.history.length, before + 1);
  223. },
  224. );
  225. await check(
  226. "current model is frozen for admitted request and changes on the next call",
  227. async () => {
  228. env.model.plans.push({ key: "model-change", delayed: true });
  229. const result = sample("model-change");
  230. await env.model.requests.wait((e) => e.plan?.key === "model-change");
  231. await env.agent.call("session/setModel", {
  232. sessionId: scope.sessionId,
  233. model: { ...env.model.selection, modelId: "gpt-4o-mini" },
  234. });
  235. env.model.release("model-change");
  236. assert.equal((await result).result.model, "gpt-4o");
  237. assert.equal((await sample("new-model")).result.model, "gpt-4o-mini");
  238. assert.equal(env.model.requests.history.at(-1).body.model, "gpt-4o-mini");
  239. },
  240. );
  241. await check(
  242. "same source in another window isolates credentials and cancellation",
  243. async () => {
  244. const second = await env.createWindow(scope, "sampling");
  245. env.model.plans.push({ key: "isolated", delayed: true });
  246. const result = sample("isolated");
  247. await env.model.requests.wait((e) => e.plan?.key === "isolated");
  248. assert.notEqual(
  249. env.handles.get(second.webContents.id).instance.token,
  250. binding("unused").instance.token,
  251. );
  252. const reply = await env.evalPage(
  253. second,
  254. `window.sample('second',${JSON.stringify(request)})`,
  255. );
  256. assert.ok(reply.result);
  257. const guest = env.guests.get(second.webContents.id)!;
  258. const destroyed = new Promise<void>((resolve) => guest.once("destroyed", resolve));
  259. await second.webContents.executeJavaScript(
  260. "window.setAnchors(false,false).then(() => window.clearManaged())",
  261. );
  262. await destroyed;
  263. second.destroy();
  264. assert.equal((await ui("window.managedState()")).busy, true);
  265. env.model.release("isolated");
  266. assert.equal((await result).result.content.text, "answer:isolated");
  267. },
  268. );
  269. await check(
  270. "finish reason is preserved and sampling never appends main conversation",
  271. async () => {
  272. env.model.plans.push({ key: "length", delayed: false, finishReason: "length" });
  273. assert.equal((await sample("length")).result.stopReason, "maxTokens");
  274. const after = await env.agent.call("session/read", { sessionId: scope.sessionId });
  275. assert.deepEqual(after.messages, mainBefore.messages);
  276. assert.equal(env.agent.approvals.history.length, 0);
  277. const forbidden = env.agent.notifications.history.filter((e) =>
  278. /ModelRequest|ModelComplete|model_request/.test(JSON.stringify(e)),
  279. );
  280. assert.equal(forbidden.length, 0);
  281. },
  282. );
  283. await check(
  284. "connection revocation aborts provider and rejects the old credential",
  285. async () => {
  286. env.model.plans.push({ key: "revoke", delayed: true });
  287. const result = sample("revoke");
  288. await env.model.requests.wait((e) => e.plan?.key === "revoke");
  289. const old = binding("old");
  290. env.agent.disconnect("sampling");
  291. assert.ok((await result).error);
  292. await env.model.aborted.wait((key) => key === "revoke");
  293. await assert.rejects(() => env.agent.call("mcp/uiSampling", { ...old, request }));
  294. },
  295. );
  296. await check(
  297. "window teardown releases guests, feeds, and listeners after existing keep-warm deadline",
  298. async () => {
  299. await ui(
  300. "window.setAnchors(false,false).then(() => { window.clearManaged(); return window.waitConnectionsReleased(); })",
  301. );
  302. win.destroy();
  303. assert.equal(env.countGuests(), 0);
  304. },
  305. );
  306. await checkSamplingExtras(env, root, check);
  307. await writeFile(
  308. join(root, "sampling-results.json"),
  309. JSON.stringify(
  310. {
  311. coldPageMs,
  312. checks,
  313. modelRequests: env.model.requests.history.length,
  314. approvals: env.agent.approvals.history.length,
  315. remainingGuests: env.countGuests(),
  316. },
  317. null,
  318. 2,
  319. ),
  320. );
  321. } finally {
  322. await env.close();
  323. }
  324. app.exit(0);
  325. })
  326. .catch((error) => {
  327. process.stderr.write(String(error.stack ?? error) + "\n");
  328. app.exit(1);
  329. });