Merge remote-tracking branch 'origin/v2/main' into v2/feat/1950-file-secret-store
Signed-off-by: cliffhall <cliff@futurescale.com> # Conflicts: # README.md # clients/web/src/App.tsx
This commit is contained in:
commit
a859093bd3
2 changed files with 4824 additions and 139 deletions
197
clients/web/src/lib/appElicitationController.test.ts
Normal file
197
clients/web/src/lib/appElicitationController.test.ts
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
import { describe, it, expect, vi } from "vitest";
|
||||
import type { ElicitRequest } from "@modelcontextprotocol/client";
|
||||
import {
|
||||
AppElicitationController,
|
||||
type AppElicitationSession,
|
||||
} from "./appElicitationController";
|
||||
|
||||
const params: ElicitRequest["params"] = {
|
||||
message: "Choose an option",
|
||||
requestedSchema: { type: "object", properties: {} },
|
||||
};
|
||||
|
||||
/**
|
||||
* Queue a request through a session. Defaults to one session per controller,
|
||||
* which is what a single connection looks like; the session tests open their
|
||||
* own to model a client swap.
|
||||
*/
|
||||
function request(
|
||||
controller: AppElicitationController,
|
||||
requestId: string,
|
||||
resourceUri = "ui://demo/pick.html",
|
||||
signal: AbortSignal = new AbortController().signal,
|
||||
session: AppElicitationSession = defaultSession(controller),
|
||||
) {
|
||||
return session.render({ requestId, resourceUri, params, signal });
|
||||
}
|
||||
|
||||
const sessions = new WeakMap<AppElicitationController, AppElicitationSession>();
|
||||
function defaultSession(
|
||||
controller: AppElicitationController,
|
||||
): AppElicitationSession {
|
||||
let session = sessions.get(controller);
|
||||
if (!session) {
|
||||
session = controller.openSession();
|
||||
sessions.set(controller, session);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
describe("AppElicitationController (#1854)", () => {
|
||||
it("queues a request and notifies subscribers", () => {
|
||||
const controller = new AppElicitationController();
|
||||
const listener = vi.fn();
|
||||
controller.subscribe(listener);
|
||||
|
||||
void request(controller, "a").catch(() => {});
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(controller.getEntries()).toHaveLength(1);
|
||||
expect(controller.getEntries()[0]).toMatchObject({
|
||||
requestId: "a",
|
||||
resourceUri: "ui://demo/pick.html",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the entries array identity stable between changes", () => {
|
||||
// `useSyncExternalStore` re-renders on every getSnapshot identity change,
|
||||
// so a fresh array per read would loop forever.
|
||||
const controller = new AppElicitationController();
|
||||
expect(controller.getEntries()).toBe(controller.getEntries());
|
||||
});
|
||||
|
||||
it("settle resolves the render promise and drops the entry", async () => {
|
||||
const controller = new AppElicitationController();
|
||||
const pending = request(controller, "a");
|
||||
controller.settle("a", { action: "accept", content: { choice: "x" } });
|
||||
await expect(pending).resolves.toEqual({
|
||||
action: "accept",
|
||||
content: { choice: "x" },
|
||||
});
|
||||
expect(controller.getEntries()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("fail rejects the render promise so the client falls back", async () => {
|
||||
const controller = new AppElicitationController();
|
||||
const pending = request(controller, "a");
|
||||
controller.fail("a", new Error("sandbox unavailable"));
|
||||
await expect(pending).rejects.toThrow(/sandbox unavailable/);
|
||||
expect(controller.getEntries()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("settling an unknown or already-settled id is a no-op", async () => {
|
||||
const controller = new AppElicitationController();
|
||||
const pending = request(controller, "a");
|
||||
controller.settle("a", { action: "cancel" });
|
||||
await expect(pending).resolves.toEqual({ action: "cancel" });
|
||||
// A second settle must not throw — the modal's unmount and the client's
|
||||
// abort can race, and both call in.
|
||||
expect(() => controller.settle("a", { action: "decline" })).not.toThrow();
|
||||
expect(() => controller.fail("nope", new Error("x"))).not.toThrow();
|
||||
});
|
||||
|
||||
it("keeps concurrent requests independent", async () => {
|
||||
const controller = new AppElicitationController();
|
||||
const first = request(controller, "a", "ui://demo/first.html");
|
||||
const second = request(controller, "b", "ui://demo/second.html");
|
||||
expect(controller.getEntries().map((e) => e.requestId)).toEqual(["a", "b"]);
|
||||
|
||||
controller.settle("b", { action: "accept", content: { choice: "b" } });
|
||||
expect(controller.getEntries().map((e) => e.requestId)).toEqual(["a"]);
|
||||
await expect(second).resolves.toMatchObject({ content: { choice: "b" } });
|
||||
|
||||
controller.settle("a", { action: "accept", content: { choice: "a" } });
|
||||
await expect(first).resolves.toMatchObject({ content: { choice: "a" } });
|
||||
});
|
||||
|
||||
it("drops and rejects an entry when the originating request aborts", async () => {
|
||||
const controller = new AppElicitationController();
|
||||
const aborter = new AbortController();
|
||||
const pending = request(
|
||||
controller,
|
||||
"a",
|
||||
"ui://demo/pick.html",
|
||||
aborter.signal,
|
||||
);
|
||||
expect(controller.getEntries()).toHaveLength(1);
|
||||
aborter.abort();
|
||||
await expect(pending).rejects.toThrow(/aborted/);
|
||||
expect(controller.getEntries()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("never queues a request whose signal already aborted", async () => {
|
||||
const controller = new AppElicitationController();
|
||||
const aborter = new AbortController();
|
||||
aborter.abort();
|
||||
await expect(
|
||||
request(controller, "a", "ui://demo/pick.html", aborter.signal),
|
||||
).rejects.toThrow(/aborted/);
|
||||
expect(controller.getEntries()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("closing a session drops the entries that session queued", async () => {
|
||||
// The host closes the old session when the InspectorClient is replaced: the
|
||||
// bridge factory resolves its client at call time, so an entry left queued
|
||||
// could otherwise rebuild against the NEXT connection and answer through a
|
||||
// different server.
|
||||
const controller = new AppElicitationController();
|
||||
const session = controller.openSession();
|
||||
const listener = vi.fn();
|
||||
const first = request(controller, "a", "ui://a", undefined, session);
|
||||
const second = request(controller, "b", "ui://b", undefined, session);
|
||||
controller.subscribe(listener);
|
||||
|
||||
session.close(new Error("connection replaced"));
|
||||
|
||||
await expect(first).rejects.toThrow(/connection replaced/);
|
||||
await expect(second).rejects.toThrow(/connection replaced/);
|
||||
expect(controller.getEntries()).toHaveLength(0);
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("refuses a request a closed session makes during its own teardown", async () => {
|
||||
// The half a one-shot sweep cannot provide: the replaced client
|
||||
// disconnects asynchronously and can still enqueue, and that entry would be
|
||||
// rendered by a factory bound to the REPLACEMENT client.
|
||||
const controller = new AppElicitationController();
|
||||
const session = controller.openSession();
|
||||
session.close(new Error("connection replaced"));
|
||||
await expect(
|
||||
request(controller, "late", "ui://a", undefined, session),
|
||||
).rejects.toThrow(/session is closed/);
|
||||
expect(controller.getEntries()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("leaves another session's entries alone", async () => {
|
||||
const controller = new AppElicitationController();
|
||||
const oldSession = controller.openSession();
|
||||
const newSession = controller.openSession();
|
||||
const stale = request(controller, "a", "ui://a", undefined, oldSession);
|
||||
const live = request(controller, "b", "ui://b", undefined, newSession);
|
||||
|
||||
oldSession.close(new Error("connection replaced"));
|
||||
|
||||
await expect(stale).rejects.toThrow(/connection replaced/);
|
||||
expect(controller.getEntries().map((e) => e.requestId)).toEqual(["b"]);
|
||||
controller.settle("b", { action: "cancel" });
|
||||
await expect(live).resolves.toEqual({ action: "cancel" });
|
||||
});
|
||||
|
||||
it("closing a session with nothing queued notifies nobody", () => {
|
||||
const controller = new AppElicitationController();
|
||||
const session = controller.openSession();
|
||||
const listener = vi.fn();
|
||||
controller.subscribe(listener);
|
||||
session.close(new Error("nothing to drop"));
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stops notifying an unsubscribed listener", () => {
|
||||
const controller = new AppElicitationController();
|
||||
const listener = vi.fn();
|
||||
const unsubscribe = controller.subscribe(listener);
|
||||
unsubscribe();
|
||||
void request(controller, "a").catch(() => {});
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
157
clients/web/src/lib/appElicitationController.ts
Normal file
157
clients/web/src/lib/appElicitationController.ts
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
import type { ElicitResult } from "@modelcontextprotocol/client";
|
||||
import type {
|
||||
AppElicitationRenderer,
|
||||
AppElicitationRequest,
|
||||
} from "@inspector/core/mcp/appElicitation.js";
|
||||
|
||||
/**
|
||||
* One app-rendered elicitation awaiting an answer, plus the settle functions
|
||||
* for the `InspectorClient` promise it belongs to (#1854).
|
||||
*
|
||||
* The entry — not a "currently active app" — is what owns the renderer, so two
|
||||
* concurrent elicitations each drive their own iframe and bridge and cannot
|
||||
* resolve through each other's.
|
||||
*/
|
||||
export interface AppElicitationEntry extends AppElicitationRequest {
|
||||
/** The session (one InspectorClient) this request belongs to. */
|
||||
sessionId: number;
|
||||
/** Hands the app's standard `ElicitResult` back to the server. */
|
||||
resolve: (result: ElicitResult) => void;
|
||||
/** Asks `InspectorClient` to fall back to the native elicitation UI. */
|
||||
reject: (error: Error) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* One client's window onto the controller.
|
||||
*
|
||||
* Requests are bound to the connection that made them. A closed session
|
||||
* rejects immediately, which is what a one-shot sweep cannot do: an
|
||||
* `InspectorClient` being replaced disconnects asynchronously and can still
|
||||
* enqueue during its own teardown, and that late entry would otherwise be
|
||||
* rendered by a factory bound to the *replacement* client — reading its
|
||||
* resource, and answering, through a different server.
|
||||
*/
|
||||
export interface AppElicitationSession {
|
||||
/** The renderer handed to this client's `InspectorClient`. */
|
||||
render: AppElicitationRenderer;
|
||||
/** Reject everything from this session and refuse anything later. */
|
||||
close: (error: Error) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bridges `InspectorClient`'s renderer callback — supplied at construction,
|
||||
* long before any React tree exists — to the React component that actually
|
||||
* mounts the app.
|
||||
*
|
||||
* The client is given {@link render} once and for all; the UI subscribes and
|
||||
* re-renders as entries come and go. Without this indirection the renderer
|
||||
* would have to be rebuilt (and the client reconstructed) whenever the host
|
||||
* component remounted.
|
||||
*/
|
||||
export class AppElicitationController {
|
||||
private entries: AppElicitationEntry[] = [];
|
||||
private listeners = new Set<() => void>();
|
||||
private nextSessionId = 0;
|
||||
/** Sessions still accepting requests. A closed one is removed. */
|
||||
private openSessions = new Set<number>();
|
||||
|
||||
/** Current queue. Stable identity between changes, for `useSyncExternalStore`. */
|
||||
getEntries = (): AppElicitationEntry[] => this.entries;
|
||||
|
||||
subscribe = (listener: () => void): (() => void) => {
|
||||
this.listeners.add(listener);
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
};
|
||||
|
||||
private emit(): void {
|
||||
for (const listener of this.listeners) listener();
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a window for one `InspectorClient`. Its `render` is what that client
|
||||
* is constructed with; `close` ends it when the client is replaced.
|
||||
*/
|
||||
openSession(): AppElicitationSession {
|
||||
const sessionId = this.nextSessionId++;
|
||||
this.openSessions.add(sessionId);
|
||||
return {
|
||||
render: (request) => this.render(sessionId, request),
|
||||
close: (error) => this.closeSession(sessionId, error),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue a request for the UI and resolve when {@link settle} or {@link fail}
|
||||
* is called for it.
|
||||
*
|
||||
* An abort of the originating request (cancelled tool call, disconnect) drops
|
||||
* the entry and rejects, so a modal can never outlive the request behind it.
|
||||
* A request from a closed session is rejected without ever being queued.
|
||||
*/
|
||||
private render = (sessionId: number, request: AppElicitationRequest) =>
|
||||
new Promise<ElicitResult>((resolve, reject) => {
|
||||
if (!this.openSessions.has(sessionId)) {
|
||||
reject(new Error("App elicitation session is closed"));
|
||||
return;
|
||||
}
|
||||
const entry: AppElicitationEntry = {
|
||||
...request,
|
||||
sessionId,
|
||||
resolve,
|
||||
reject,
|
||||
};
|
||||
const onAbort = () => {
|
||||
this.remove(entry.requestId);
|
||||
reject(new Error("App-rendered elicitation aborted"));
|
||||
};
|
||||
if (request.signal.aborted) {
|
||||
onAbort();
|
||||
return;
|
||||
}
|
||||
request.signal.addEventListener("abort", onAbort, { once: true });
|
||||
this.entries = [...this.entries, entry];
|
||||
this.emit();
|
||||
});
|
||||
|
||||
private take(requestId: string): AppElicitationEntry | undefined {
|
||||
const entry = this.entries.find((e) => e.requestId === requestId);
|
||||
if (entry) this.remove(requestId);
|
||||
return entry;
|
||||
}
|
||||
|
||||
private remove(requestId: string): void {
|
||||
const next = this.entries.filter((e) => e.requestId !== requestId);
|
||||
if (next.length === this.entries.length) return;
|
||||
this.entries = next;
|
||||
this.emit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete an elicitation with the app's result. `decline` and `cancel` are
|
||||
* completions too — they are returned to the server, not fallen back on.
|
||||
*/
|
||||
settle(requestId: string, result: ElicitResult): void {
|
||||
this.take(requestId)?.resolve(result);
|
||||
}
|
||||
|
||||
/** Give up on the app and let the native elicitation UI take the request. */
|
||||
fail(requestId: string, error: Error): void {
|
||||
this.take(requestId)?.reject(error);
|
||||
}
|
||||
|
||||
/**
|
||||
* End a session: reject everything it queued, and refuse anything it queues
|
||||
* later. The refusal is the half a one-shot sweep cannot provide — see
|
||||
* {@link AppElicitationSession}.
|
||||
*/
|
||||
private closeSession(sessionId: number, error: Error): void {
|
||||
this.openSessions.delete(sessionId);
|
||||
const dropped = this.entries.filter((e) => e.sessionId === sessionId);
|
||||
if (dropped.length === 0) return;
|
||||
this.entries = this.entries.filter((e) => e.sessionId !== sessionId);
|
||||
this.emit();
|
||||
for (const entry of dropped) entry.reject(error);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue