Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix: bind Composio sessions to selected connections

Abdurrahman Fakhrulf346196a4c79
diff --git a/app/api/v1/integrations/composio/session/handler.ts b/app/api/v1/integrations/composio/session/handler.ts
index 4d7f0973..b6f87e95 100644
--- a/app/api/v1/integrations/composio/session/handler.ts
+++ b/app/api/v1/integrations/composio/session/handler.ts
@@ -4,20 +4,30 @@ import { rateLimited } from "@/lib/host/limits-api";
import { audit } from "@/lib/host/audit-api";
import { readRequestJson, RequestBodyError } from "@/lib/security/request-body";
import { IntegrationError } from "@/lib/infra/identity";
-import { currentIntegrationSelection } from "@/lib/infra/connection-service";
-import { readInfraProvider } from "@/lib/infra/store";
+import { readIntegrationState } from "@/lib/infra/connection-storage";
+import { identity, selectConnection, resolveSharedConnection } from "@/lib/infra/identity";
import { composioKeyKind } from "@/lib/infra/composio";
-import { composioSessionForUser } from "@/lib/infra/composio-session";
+import { composioConnectionScope, composioSessionForUser } from "@/lib/infra/composio-session";
const headers = { "Cache-Control": "no-store, private", "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff" };
-export async function handleGetComposioSession(): Promise<Response> {
+async function selection(user: unknown, connection: unknown) {
+ const state = await readIntegrationState();
+ const selected = selectConnection(state, "composio", { user: identity(user, "user"), connection: identity(connection, "connection") });
+ if (selected.connection.source !== "direct") throw new IntegrationError("external_source_requires_own_executor", 409);
+ const backing = resolveSharedConnection(state, selected.user, selected.connection).connection;
+ return { user: selected.user, values: backing.values, scope: composioConnectionScope(selected.connection.uid, backing.revision, backing.values) };
+}
+
+export async function handleGetComposioSession(req: NextRequest): Promise<Response> {
const context = await getSessionContext();
if (context?.role !== "owner") return NextResponse.json({ error: "owner_required" }, { status: 403, headers });
try {
- return NextResponse.json({ keyKind: composioKeyKind(await readInfraProvider("composio")) }, { headers });
- } catch {
- return NextResponse.json({ keyKind: null }, { headers });
+ const selected = await selection(req.nextUrl.searchParams.get("user"), req.nextUrl.searchParams.get("connection"));
+ return NextResponse.json({ keyKind: composioKeyKind(selected.values) }, { headers });
+ } catch (error) {
+ const safe = error instanceof IntegrationError ? error : new IntegrationError("composio_session_failed", 502);
+ return NextResponse.json({ error: safe.message }, { status: safe.status, headers });
}
}
@@ -29,11 +39,12 @@ export async function handlePostComposioSession(req: NextRequest): Promise<Respo
}
try {
const input = req.body && req.headers.get("content-length") !== "0" ? await readRequestJson(req, 4096) : {};
- if (Object.keys(input).some((key) => key !== "refresh")) throw new IntegrationError("invalid_session_fields", 400);
- const values = await readInfraProvider("composio");
+ if (Object.keys(input).some((key) => !["refresh", "user", "connection"].includes(key))) throw new IntegrationError("invalid_session_fields", 400);
+ const selected = await selection(input.user, input.connection);
const session = await composioSessionForUser({
- values,
- user: currentIntegrationSelection().user,
+ values: selected.values,
+ user: selected.user,
+ cacheScope: selected.scope,
refresh: input.refresh === true,
});
void audit({
diff --git a/app/api/v1/integrations/composio/session/route.test.ts b/app/api/v1/integrations/composio/session/route.test.ts
index b49f4d65..795a6f51 100644
--- a/app/api/v1/integrations/composio/session/route.test.ts
+++ b/app/api/v1/integrations/composio/session/route.test.ts
@@ -14,7 +14,8 @@ vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
let root = "", route: typeof import("./route");
const owner = { role: "owner", session: { device_id: "device-1" } };
-const request = (body?: unknown) => new NextRequest("http://localhost/api/v1/integrations/composio/session", {
+const get = (connection = "project") => new NextRequest("http://localhost/api/v1/integrations/composio/session?user=lara&connection=" + connection);
+const request = (body: unknown = { user: "lara", connection: "project" }) => new NextRequest("http://localhost/api/v1/integrations/composio/session", {
method: "POST",
headers: { "content-type": "application/json" },
...(body === undefined ? {} : { body: JSON.stringify(body) }),
@@ -43,7 +44,7 @@ afterEach(async () => {
describe("POST /api/v1/integrations/composio/session", () => {
it("returns the MCP URL and never the session headers", async () => {
- const response = await route.POST(request({}));
+ const response = await route.POST(request());
expect(response.status).toBe(200);
const body = await response.json();
expect(body).toEqual({ mcpUrl: MCP_URL });
@@ -54,33 +55,57 @@ describe("POST /api/v1/integrations/composio/session", () => {
it("refuses a non-owner session", async () => {
mocks.session.mockResolvedValue({ ...owner, role: "operator" });
- expect((await route.POST(request({}))).status).toBe(403);
+ expect((await route.POST(request())).status).toBe(403);
mocks.session.mockResolvedValue(null);
- expect((await route.POST(request({}))).status).toBe(403);
+ expect((await route.POST(request())).status).toBe(403);
});
- it("refuses to take a userId from the body", async () => {
- const response = await route.POST(request({ user: "sams" }));
+ it("refuses unsupported fields", async () => {
+ const response = await route.POST(request({ user: "lara", connection: "project", userId: "sams" }));
expect(response.status).toBe(400);
expect((await response.json()).error).toBe("invalid_session_fields");
});
+ it("isolates sessions by owner, connection and credential revision", async () => {
+ const file = path.join(root, "infra.json");
+ const state = JSON.parse(await fs.readFile(file, "utf8"));
+ const original = state.users.lara.connections.composio.project;
+ state.users.lara.connections.composio.second = { ...original, id: "second", uid: "conn-2", values: { apiKey: "ak_second_synthetic" } };
+ state.users.sams = { ...state.users.lara, id: "sams", uid: "uid-2", connections: { composio: { project: { ...original, uid: "conn-3", values: { apiKey: "ak_sams_synthetic" } } } } };
+ await fs.writeFile(file, JSON.stringify(state), { mode: 0o600 });
+ const calls: string[] = [];
+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, init: RequestInit) => {
+ calls.push(String((init.headers as Record<string, string>)["x-api-key"]));
+ return new Response(JSON.stringify({ session_id: "trs_" + calls.length, mcp: { url: "https://backend.composio.dev/tool_router/v3/trs_" + calls.length + "/mcp" } }), { status: 201 });
+ }));
+ for (const selection of [{ user: "lara", connection: "project" }, { user: "lara", connection: "second" }, { user: "sams", connection: "project" }, { user: "lara", connection: "project" }]) {
+ expect((await route.POST(request(selection))).status).toBe(200);
+ }
+ expect(calls).toEqual(["ak_project_synthetic", "ak_second_synthetic", "ak_sams_synthetic"]);
+ state.users.lara.connections.composio.project.revision++;
+ state.users.lara.connections.composio.project.values.apiKey = "ak_rotated_synthetic";
+ await fs.writeFile(file, JSON.stringify(state), { mode: 0o600 });
+ expect((await route.POST(request())).status).toBe(200);
+ expect(calls.at(-1)).toBe("ak_rotated_synthetic");
+ expect((await route.POST(request({ user: "sams", connection: "second" }))).status).toBe(404);
+ });
+
it("is rate limited", async () => {
mocks.limited.mockReturnValue(true);
- const response = await route.POST(request({}));
+ const response = await route.POST(request());
expect(response.status).toBe(429);
expect(mocks.limited).toHaveBeenCalledWith("composio.session:device-1", 10, 60_000);
});
it("reuses the stored session on a second call", async () => {
- await route.POST(request({}));
- await route.POST(request({}));
+ await route.POST(request());
+ await route.POST(request());
expect(vi.mocked(fetch)).toHaveBeenCalledTimes(1);
});
it("never leaks the composed credential when upstream returns no headers", async () => {
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ session_id: SESSION_ID, mcp: { type: "http", url: MCP_URL } }), { status: 201 })));
- const response = await route.POST(request({}));
+ const response = await route.POST(request());
expect(response.status).toBe(200);
const text = JSON.stringify(await response.json());
expect(text).toBe(JSON.stringify({ mcpUrl: MCP_URL }));
@@ -90,7 +115,7 @@ describe("POST /api/v1/integrations/composio/session", () => {
it("does not expose the credential when upstream fails", async () => {
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ error: { message: "key ak_project_synthetic rejected", slug: "APIKey_InvalidAPIKey" } }), { status: 401 })));
- const response = await route.POST(request({}));
+ const response = await route.POST(request());
expect(response.status).toBe(401);
const text = JSON.stringify(await response.json());
expect(text).not.toContain("ak_project_synthetic");
@@ -99,7 +124,7 @@ describe("POST /api/v1/integrations/composio/session", () => {
describe("GET /api/v1/integrations/composio/session", () => {
it("reports only the key kind for the form", async () => {
- const response = await route.GET();
+ const response = await route.GET(get());
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ keyKind: "project" });
});
@@ -110,6 +135,6 @@ describe("GET /api/v1/integrations/composio/session", () => {
users: { lara: { id: "lara", uid: "uid-1", label: "Lara", defaults: { composio: "c" }, connections: { composio: { c: { id: "c", uid: "conn-2", label: "Connect", provider: "composio", source: "direct", authMethod: "project", scope: "account", revision: 1, values: { apiKey: "ck_consumer_key" }, createdAt: 0, updatedAt: 0 } } } } },
bindings: [],
}), { mode: 0o600 });
- expect(await (await route.GET()).json()).toEqual({ keyKind: "connect" });
+ expect(await (await route.GET(get("c"))).json()).toEqual({ keyKind: "connect" });
});
});
diff --git a/app/api/v1/integrations/composio/session/route.ts b/app/api/v1/integrations/composio/session/route.ts
index 6dada459..a24cbfc7 100644
--- a/app/api/v1/integrations/composio/session/route.ts
+++ b/app/api/v1/integrations/composio/session/route.ts
@@ -4,8 +4,8 @@ import { handleGetComposioSession, handlePostComposioSession } from "./handler";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
-export async function GET() {
- return handleGetComposioSession();
+export async function GET(req: NextRequest) {
+ return handleGetComposioSession(req);
}
export async function POST(req: NextRequest) {
diff --git a/components/external-app-frame.tsx b/components/external-app-frame.tsx
index 60afa47a..51ffc9aa 100644
--- a/components/external-app-frame.tsx
+++ b/components/external-app-frame.tsx
@@ -24,7 +24,7 @@ function ExternalAppFrameContent({ app, frameTitle }: { app: WorkflowEmbed; fram
const reload = () => { setLoading(true); setSlow(false); setRevision((value) => value + 1); };
return <div className="flex h-full min-h-0 min-w-0 flex-col" data-slot="external-app-frame">
<div className="flex min-h-11 shrink-0 flex-wrap items-center gap-2 border-b px-3 py-1.5">
- <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground" title={app.origin}>{app.origin}</span>
+ <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground" title={app.origin}>If blank, use Open</span>
{app.loginUrl ? <Button asChild variant="ghost" size="sm"><a href={app.loginUrl} target="_blank" rel="noopener noreferrer"><LogIn className="size-4"/><span>Sign in</span></a></Button> : null}
<Button asChild variant="outline" size="sm"><a href={app.url} target="_blank" rel="noopener noreferrer"><ExternalLink className="size-4"/><span>Open {app.title}</span></a></Button>
{app.origin && app.url !== app.origin && app.url !== app.origin + "/" ? <Button asChild variant="ghost" size="sm"><a href={app.origin} target="_blank" rel="noopener noreferrer">Open home</a></Button> : null}
@@ -34,6 +34,6 @@ function ExternalAppFrameContent({ app, frameTitle }: { app: WorkflowEmbed; fram
{loading ? <div className="absolute inset-x-0 top-0 z-10 border-b bg-background px-3 py-2 text-xs text-muted-foreground" role="status">{slow ? `Taking longer than expected. Open ${app.title} in a new tab if its login or frame policy blocks embedding.` : `Loading ${app.title}…`}</div> : null}
<iframe key={`${revision}:${app.sandbox}`} src={app.url} title={frameTitle ?? `${app.title} application`} sandbox={app.sandbox} referrerPolicy="no-referrer" className="h-full w-full border-0 bg-background" onLoad={() => setLoading(false)} onError={() => { setLoading(true); setSlow(true); }}/>
</div> : <div className="flex min-h-0 flex-1 items-center justify-center p-6 text-center text-sm text-muted-foreground">{app.reason || `${app.title} opens in a separate tab. Embedded access is not enabled for this provider.`}</div>}
- <p className="shrink-0 border-t px-3 py-1.5 text-xs text-muted-foreground [@media(max-height:520px)]:sr-only">{app.msoSession ? `${app.title} uses your MSO session.` : `${app.title} keeps its own login. Sign in in a new tab, then reload here. If embedding is blocked, use Open ${app.title}.`}</p>
+ <p className="shrink-0 border-t px-3 py-1.5 text-xs text-muted-foreground [@media(max-height:520px)]:sr-only">{app.msoSession ? `Embedding cannot be verified. If the app is blank, use Open ${app.title}.` : `Embedding cannot be verified. If the app is blank, sign in or use Open ${app.title}.`}</p>
</div>;
}
diff --git a/docs/evidence/2026-11-04-final-surfaces.md b/docs/evidence/2026-11-04-final-surfaces.md
new file mode 100644
index 00000000..be6715c8
--- /dev/null
+++ b/docs/evidence/2026-11-04-final-surfaces.md
@@ -0,0 +1,26 @@
+# Frontend surfaces final handoff, 2026-11-04
+
+Base a2268f2b. This document distinguishes implementation from behavioral proof. The earlier
+[handoff](2026-11-04-frontend-surfaces.md) records the prior candidate and remaining journeys.
+No production provider, credential, installation, or external frame was used.
+
+| ID | Implemented | Evidence and limits |
+|---|---|---|
+| PX-01 | Infrastructure superseded reads are aborted. | Prior candidate source; reversed delayed project and zone responses have not been rerun after the fix. |
+| PX-02 | Loading, empty, failure, stale and refresh affordances are distinct. | Prior candidate source; 403, retry and provider-switch journeys remain unverified. |
+| PX-03 | Same-origin, source-checked manager owner message; explicit named connection in panel; owner-only server validation; session cache scoped to connection UID, backing revision and credential digest. Selection changes clear results and abort requests. | Synthetic route tests exercise two owners, two keys, reuse, rotation and wrong-owner connection rejection; 38 focused tests pass. Browser owner-switch, out-of-order UI requests and manager-to-panel handshake remain unverified. No upstream call is made in tests. |
+| PX-04 | Create App fields have associated labels. | Prior candidate source; label click and multiple-window browser checks remain unverified. |
+| PX-05 | Accent swatches wrap and expose selection. | Prior candidate source; coarse 320/390 and 200% text checks remain unverified. |
+| PX-06 | Nonsecret drafts are scoped to window with discard guards. | Prior candidate source; remount, two windows and cancelled discard remain unverified. |
+| PX-07 | Failed n8n refresh identifies retained embed as stale. | Prior candidate source; 3 existing n8n embed tests pass, but success-to-rejection/retry is not covered by them. |
+| PX-08 | Monitor identifies stale telemetry and process failures, and ignores superseded polls. | Prior candidate source; slow, hidden, disconnected and recovery journeys remain unverified. |
+| PX-09 | Composio disclosure has a 40% height cap and internal scrolling. | Source inspection; 100/500 tools, keyboard and short viewport measurements remain unverified after the panel change. |
+| ST-01 | Browser registry writes precede published state; failure is shown. | Prior candidate source; quota failure and retry for all operations remain unverified. |
+| ST-02 | Skills refresh publishes one generation and serializes writes. | Prior candidate source; reversed responses and concurrent mutation journey remain unverified. |
+| ST-03 | Frame guidance states embedding cannot be verified and gives an Open fallback; compact toolbar retains fallback guidance at short heights. Sandbox, origin and links are unchanged. | Source inspection and 3 existing n8n embed tests; denied-frame load, timeout and 844x390 geometry remain unverified. Cross-origin content readiness cannot be observed from iframe load. |
+
+Scoped checks: TypeScript, changed-file ESLint, architecture ratchet, 38 Composio/manager tests,
+and 11 existing integration/n8n/domain/extension tests passed. Existing tests outside PX-03 do
+not establish the pending journeys above. Full build, security preflight, browser journeys and
+remote checks belong to the integration owner and are not asserted here. Revert this commit to
+roll back this incremental patch; prior candidate fixes are on the base.
diff --git a/frontend/slices/integrations/app.tsx b/frontend/slices/integrations/app.tsx
index f40f15de..5c88ba47 100644
--- a/frontend/slices/integrations/app.tsx
+++ b/frontend/slices/integrations/app.tsx
@@ -15,11 +15,17 @@ export default function IntegrationsApp() {
const frame = useRef<HTMLIFrameElement>(null);
const [status, setStatus] = useState<"loading" | "ready" | "error">("loading");
const [retry, setRetry] = useState(0);
+ const [owner, setOwner] = useState<string | null>(null);
useEffect(() => {
const target = frame.current;
if (!target) return;
const onReady = (event: MessageEvent) => {
- if (event.source !== target.contentWindow || event.origin !== window.location.origin || event.data?.type !== "mso:integrations-ready") return;
+ if (event.source !== target.contentWindow || event.origin !== window.location.origin) return;
+ if (event.data?.type === "mso:integrations-selection") {
+ setOwner(typeof event.data.user === "string" ? event.data.user : null);
+ return;
+ }
+ if (event.data?.type !== "mso:integrations-ready") return;
syncIntegrationFrameTokens(target);
setStatus("ready");
};
@@ -54,7 +60,7 @@ export default function IntegrationsApp() {
</p>
{status === "error" && <Button variant="secondary" onClick={() => { setStatus("loading"); setRetry(n => n + 1); }}>Retry</Button>}
</div>}
- <ComposioSessionPanel />
+ <ComposioSessionPanel key={owner ?? "none"} owner={owner} />
<iframe ref={frame} title="MSO native Integrations manager" className="min-h-0 w-full flex-1 border-0"
referrerPolicy="no-referrer" onLoad={() => { if (frame.current?.contentDocument?.querySelector(".integration.manager")) { syncIntegrationFrameTokens(frame.current); setStatus("ready"); } }}
onError={() => setStatus("error")} />
diff --git a/frontend/slices/integrations/composio-session-panel.tsx b/frontend/slices/integrations/composio-session-panel.tsx
index e5f6ed2f..b8e46bcb 100644
--- a/frontend/slices/integrations/composio-session-panel.tsx
+++ b/frontend/slices/integrations/composio-session-panel.tsx
@@ -1,124 +1,96 @@
"use client";
-import { useCallback, useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
const SESSION_PATH = "/api/v1/integrations/composio/session";
-const EXECUTE_PATH = "/api/v1/integrations";
type KeyKind = "organization" | "user" | "project" | "connect" | null;
-type ConnectTool = { name: string; description: string };
+type Connection = { id: string; label: string; provider: string; source: string };
+type ConnectTool = { name: string };
-/**
- * Connect keys run under the Connect account, so only bounded tool discovery is
- * offered. The credential owner and connection come from the same snapshot the
- * manager uses; the key itself never leaves the server.
- */
-async function listConnectTools(): Promise<ConnectTool[]> {
- const query = await fetch("/api/v1/integrations?view=snapshot", { headers: { accept: "application/json" }, cache: "no-store" });
- const snapshot = await query.json().catch(() => ({}));
- if (!query.ok) throw new Error(String(snapshot.error ?? "composio_connect_tools_failed"));
- const connection = (Array.isArray(snapshot.connections) ? snapshot.connections : [])
- .find((row: { provider?: string; id?: string }) => row?.provider === "composio" && typeof row.id === "string");
- if (!snapshot.user || !connection) throw new Error("Configure a Composio connection under this credential owner first.");
- const response = await fetch(EXECUTE_PATH, {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ mode: "execute", user: snapshot.user, provider: "composio", connection: connection.id, operation: "composio.tools.list", confirm: true }),
- });
- const body = await response.json().catch(() => ({}));
- if (!response.ok) throw new Error(String(body.error ?? "composio_connect_tools_failed"));
- return (Array.isArray(body?.tools) ? body.tools as ConnectTool[] : []).filter(tool => typeof tool?.name === "string");
+export function ComposioSessionPanel({ owner }: { owner: string | null }) {
+ const [connections, setConnections] = useState<Connection[]>([]);
+ const [connection, setConnection] = useState("");
+ const [kind, setKind] = useState<KeyKind | undefined>();
+ const [status, setStatus] = useState("");
+
+ useEffect(() => {
+ if (!owner) return;
+ const controller = new AbortController();
+ fetch(`/api/v1/integrations?view=snapshot&user=${encodeURIComponent(owner)}`, { cache: "no-store", signal: controller.signal })
+ .then(async response => {
+ const body = await response.json();
+ if (!response.ok) throw new Error(body.error);
+ if (controller.signal.aborted) return;
+ setConnections((body.connections as Connection[]).filter(row => row.provider === "composio" && row.source === "direct"));
+ }).catch(() => { if (!controller.signal.aborted) setStatus("Could not load Composio connections."); });
+ return () => controller.abort();
+ }, [owner]);
+
+ useEffect(() => {
+ if (!owner || !connection) return;
+ const controller = new AbortController();
+ const query = new URLSearchParams({ user: owner, connection });
+ fetch(`${SESSION_PATH}?${query}`, { cache: "no-store", signal: controller.signal })
+ .then(async response => {
+ const body = await response.json();
+ if (!response.ok) throw new Error(body.error);
+ if (!controller.signal.aborted) setKind(body.keyKind ?? null);
+ }).catch(() => { if (!controller.signal.aborted) setStatus("Could not inspect this connection."); });
+ return () => controller.abort();
+ }, [owner, connection]);
+
+ // Changing either selection unmounts the operation component and aborts its request.
+ if (!owner || (!connections.length && !status)) return null;
+ return <details className="max-h-[40%] shrink-0 overflow-auto border-b p-[var(--feature-padding,.75rem)]" aria-label="Composio">
+ <summary className="cursor-pointer text-sm">Composio tools and session</summary>
+ <label className="mt-2 block text-sm">Connection for {owner}
+ <select className="mt-1 block min-h-11 w-full rounded border bg-background p-2" value={connection} onChange={event => { setKind(undefined); setStatus(""); setConnection(event.target.value); }}>
+ <option value="">Choose a connection</option>
+ {connections.map(row => <option key={row.id} value={row.id}>{row.label} ({row.id})</option>)}
+ </select>
+ </label>
+ {connection && kind === null && <p className="mt-2 text-sm text-muted-foreground">No Composio key is configured for this connection.</p>}
+ {owner && connection && kind && <SessionActions key={owner + ":" + connection} owner={owner} connection={connection} kind={kind} />}
+ {status && <p role="status" className="mt-2 text-sm text-muted-foreground">{status}</p>}
+ </details>;
}
-/**
- * Composio agent session, shown for a Platform key only. The session credential
- * (`mcp.headers`) never leaves the server: only the MCP URL is displayed, and it is
- * the URL of the session belonging to this signed-in credential owner.
- */
-export function ComposioSessionPanel() {
- const [kind, setKind] = useState<KeyKind | undefined>(undefined);
- const [mcpUrl, setMcpUrl] = useState("");
+function SessionActions({ owner, connection, kind }: { owner: string; connection: string; kind: Exclude<KeyKind, null> }) {
const [status, setStatus] = useState("");
const [busy, setBusy] = useState(false);
+ const [mcpUrl, setMcpUrl] = useState("");
const [tools, setTools] = useState<ConnectTool[] | null>(null);
-
- useEffect(() => {
- let live = true;
- fetch(SESSION_PATH, { headers: { accept: "application/json" }, cache: "no-store" })
- .then(response => response.ok ? response.json() : { keyKind: null })
- .then((body: { keyKind?: KeyKind }) => { if (live) setKind(body.keyKind ?? null); })
- .catch(() => { if (live) setKind(null); });
- return () => { live = false; };
- }, []);
-
- const create = useCallback(async (refresh: boolean) => {
- setBusy(true);
- setStatus("Creating the agent session…");
+ const controller = useRef<AbortController | null>(null);
+ useEffect(() => () => controller.current?.abort(), []);
+ async function run(refresh = false) {
+ const request = new AbortController();
+ controller.current = request;
+ setBusy(true); setStatus(kind === "connect" ? "Listing tools..." : "Creating the agent session...");
try {
- const response = await fetch(SESSION_PATH, {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(refresh ? { refresh: true } : {}),
+ const response = await fetch(kind === "connect" ? "/api/v1/integrations" : SESSION_PATH, {
+ method: "POST", headers: { "content-type": "application/json" }, signal: request.signal,
+ body: JSON.stringify(kind === "connect"
+ ? { mode: "execute", user: owner, provider: "composio", connection, operation: "composio.tools.list", confirm: true }
+ : { user: owner, connection, refresh }),
});
- const body = await response.json().catch(() => ({}));
- if (!response.ok || typeof body.mcpUrl !== "string") {
- setStatus(String(body.error ?? "The session could not be created."));
- return;
- }
- setMcpUrl(body.mcpUrl);
- setStatus(refresh ? "Fresh agent session created." : "Agent session ready.");
- } catch {
- setStatus("The session could not be created.");
- } finally { setBusy(false); }
- }, []);
-
- const loadTools = useCallback(async () => {
- setBusy(true);
- setStatus("Listing Composio Connect tools…");
- try {
- setTools(await listConnectTools());
- setStatus("");
+ const body = await response.json();
+ if (request.signal.aborted) return;
+ if (!response.ok) throw new Error(String(body.error ?? "Request failed."));
+ if (kind === "connect") setTools(Array.isArray(body.tools) ? body.tools.filter((tool: ConnectTool) => typeof tool?.name === "string") : []);
+ else if (typeof body.mcpUrl === "string") setMcpUrl(body.mcpUrl);
+ else throw new Error("The session could not be created.");
+ setStatus(kind === "connect" ? "" : "Agent session ready.");
} catch (error) {
- setStatus(error instanceof Error ? error.message : "The Connect tool list could not be loaded.");
- } finally { setBusy(false); }
- }, []);
-
- if (kind === undefined) return null;
- if (kind === "connect") {
- return (
- <details className="max-h-[40%] shrink-0 overflow-auto border-b p-[var(--feature-padding,.75rem)]" aria-label="Composio Connect"><summary className="cursor-pointer text-sm">Composio Connect tools</summary>
- <div className="flex flex-wrap items-center gap-3">
- <p className="text-sm">Composio Connect</p>
- <Button variant="secondary" disabled={busy} onClick={() => void loadTools()}>List tools</Button>
- </div>
- <p className="mt-2 text-sm text-muted-foreground">
- Connect tools run under the Composio Connect account and cannot create a per-user agent session.
- </p>
- {tools && (
- tools.length ? <ul className="mt-2 break-words text-sm">{tools.map(tool => <li key={tool.name}>{tool.name}</li>)}</ul> : <p role="status" className="mt-2 text-sm text-muted-foreground">No tools returned.</p>
- )}
- {status && <p role="status" className="mt-2 text-sm text-muted-foreground">{status}</p>}
- </details>
- );
+ if (!request.signal.aborted) setStatus(error instanceof Error ? error.message : "Request failed.");
+ } finally { if (!request.signal.aborted) setBusy(false); }
}
- if (kind === null) return null;
-
- return (
- <details className="max-h-[40%] shrink-0 overflow-auto border-b p-[var(--feature-padding,.75rem)]" aria-label="Composio agent session"><summary className="cursor-pointer text-sm">Composio agent session</summary>
- <div className="flex flex-wrap items-center gap-3">
- <Button variant="secondary" disabled={busy} onClick={() => void create(false)}>Create agent session</Button>
- {mcpUrl && <Button variant="ghost" disabled={busy} onClick={() => void create(true)}>Refresh session</Button>}
- </div>
- <p className="mt-2 text-sm text-muted-foreground">
- Tools run as this credential owner. The session credential stays on the MSO server.
- </p>
- {mcpUrl && (
- <label className="mt-2 block text-sm">
- Hosted MCP endpoint
- <input readOnly value={mcpUrl} className="mt-1 w-full rounded border bg-background p-2 font-mono text-xs" onFocus={event => event.currentTarget.select()} />
- </label>
- )}
- {status && <p role="status" className="mt-2 text-sm text-muted-foreground">{status}</p>}
- </details>
- );
+ return <div className="mt-2">
+ <Button variant="secondary" disabled={busy} onClick={() => void run()}>{kind === "connect" ? "List tools" : "Create agent session"}</Button>
+ {mcpUrl && <Button variant="ghost" disabled={busy} onClick={() => void run(true)}>Refresh session</Button>}
+ <p className="mt-2 text-sm text-muted-foreground">{kind === "connect" ? "Connect tools run under this connection's account." : "Tools run as this credential owner. The session credential stays on the MSO server."}</p>
+ {mcpUrl && <label className="mt-2 block text-sm">Hosted MCP endpoint<input readOnly value={mcpUrl} className="mt-1 w-full rounded border bg-background p-2 font-mono text-xs" onFocus={event => event.currentTarget.select()} /></label>}
+ {tools && (tools.length ? <ul className="mt-2 break-words text-sm">{tools.map(tool => <li key={tool.name}>{tool.name}</li>)}</ul> : <p className="mt-2 text-sm">No tools returned.</p>)}
+ {status && <p role="status" className="mt-2 text-sm text-muted-foreground">{status}</p>}
+ </div>;
}
diff --git a/lib/infra/composio-session-store.ts b/lib/infra/composio-session-store.ts
index 7d3eb4de..794e1cc2 100644
--- a/lib/infra/composio-session-store.ts
+++ b/lib/infra/composio-session-store.ts
@@ -25,7 +25,7 @@ function parseStore(value: unknown): Store {
for (const [key, entry] of Object.entries(raw.sessions as Record<string, unknown>)) {
const row = obj(entry);
const keyParts = key.split(":");
- if (keyParts.length !== 2 || keyParts.some((part) => !KEY_PART.test(part))) bad();
+ if ((keyParts.length !== 2 && keyParts.length !== 3) || keyParts.some((part) => !KEY_PART.test(part))) bad();
const { sessionId, instanceId, userUid, createdAt, expiresAt, mcpUrl: rawUrl } = row;
const id = typeof sessionId === "string" && /^[A-Za-z0-9_-]{1,200}$/.test(sessionId) ? sessionId : bad();
const instance = typeof instanceId === "string" ? instanceId : bad();
@@ -81,8 +81,8 @@ export const storeKey = (instanceId: string, userUid: string) => {
};
/** Never returns another MSO user's session: the key is (instance, credential-owner uid). */
-export async function readComposioSession(instanceId: string, userUid: string): Promise<StoredSession | null> {
- const key = storeKey(instanceId, userUid);
+export async function readComposioSession(instanceId: string, userUid: string, scope?: string): Promise<StoredSession | null> {
+ const key = storeKey(instanceId, userUid) + (scope ? `:${scope}` : "");
const row = (await readComposioSessions()).sessions[key];
if (!row || row.instanceId !== instanceId || row.userUid !== userUid) return null;
if (row.expiresAt !== undefined && row.expiresAt <= Date.now()) return null;
diff --git a/lib/infra/composio-session.ts b/lib/infra/composio-session.ts
index f491b58e..50047cea 100644
--- a/lib/infra/composio-session.ts
+++ b/lib/infra/composio-session.ts
@@ -1,3 +1,4 @@
+import { createHash } from "node:crypto";
import { withSecurityStoreLock } from "@/lib/security-store-lock";
import { request, obj } from "./http";
import { composioAuthHeader } from "./composio";
@@ -89,6 +90,7 @@ export async function composioSessionForUser(input: {
values: InfraProviderValues;
user?: string;
refresh?: boolean;
+ cacheScope?: string;
toolkits?: string[];
authConfigs?: Record<string, string>;
fetchImpl?: (value: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
@@ -99,7 +101,7 @@ export async function composioSessionForUser(input: {
if (!profile) throw new IntegrationError("user_not_found", 404);
const instanceId = state.instanceId, userUid = profile.uid;
if (!input.refresh) {
- const stored = await readComposioSession(instanceId, userUid);
+ const stored = await readComposioSession(instanceId, userUid, input.cacheScope);
if (stored) return { sessionId: stored.sessionId, mcpUrl: stored.mcpUrl, mcpHeaders: stored.mcpHeaders, ...(stored.expiresAt !== undefined ? { expiresAt: stored.expiresAt } : {}), reused: true, user };
}
const created = await createComposioSession({
@@ -109,7 +111,7 @@ export async function composioSessionForUser(input: {
authConfigs: input.authConfigs,
fetchImpl: input.fetchImpl,
});
- const key = storeKey(instanceId, userUid);
+ const key = storeKey(instanceId, userUid) + (input.cacheScope ? `:${input.cacheScope}` : "");
await withSecurityStoreLock(composioSessionStorePath(), async () => {
const store = await readComposioSessions();
store.sessions[key] = { ...created, instanceId, userUid, createdAt: Date.now() };
@@ -117,3 +119,8 @@ export async function composioSessionForUser(input: {
});
return { ...created, reused: false, user };
}
+
+/** Bind a cached session to the exact connection and credential revision. */
+export function composioConnectionScope(uid: string, revision: number, values: InfraProviderValues): string {
+ return createHash("sha256").update(JSON.stringify([uid, revision, values.apiKey ?? "", values.orgApiKey ?? ""])).digest("hex");
+}
diff --git a/lib/infra/setup-browser.ts b/lib/infra/setup-browser.ts
index 333967df..62bec2bf 100644
--- a/lib/infra/setup-browser.ts
+++ b/lib/infra/setup-browser.ts
@@ -15,7 +15,7 @@ export const INTEGRATION_BROWSER_SCRIPT=String.raw`
async function loadManager(){
cleanup();authController?.abort();authController=new AbortController();
let owner=false,authenticated=false,role=null;try{const auth=await json("/api/auth/me",{signal:authController.signal});owner=auth.role==="owner";authenticated=auth.authenticated===true;role=auth.role}catch{}
- const bridge={headingLevel:1,remember:s=>state=s,openLink:url=>window.open(url,"_blank","noopener,noreferrer")};
+ const bridge={headingLevel:1,remember:s=>{state=s;if(window.parent!==window)window.parent.postMessage({type:"mso:integrations-selection",user:s.user||null},location.origin)},openLink:url=>window.open(url,"_blank","noopener,noreferrer")};
if(owner){
bridge.openTransfer=openTransfer;bridge.mountTransfer=mountTransfer;
bridge.projectMcp=args=>json("/api/v1/project-mcp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(args)});