Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Preserve app authorization return behavior on current main (#1283)

Regan Bell3acf9b6455d0
diff --git a/plugins/web-ui/README.md b/plugins/web-ui/README.md
index 001768d20..af26d4db0 100644
--- a/plugins/web-ui/README.md
+++ b/plugins/web-ui/README.md
@@ -279,7 +279,7 @@ Open `http://localhost:8138/?connectionDemo=1` on the local dev instance. This l
Session storage retains the account-scoped attempt for twenty minutes, picker query, expanded state, scroll position, and simulated connections. Returning skips the welcome animation, verifies the simulated result, clears callback parameters, and restores the picker. Reset clears the preview's simulated connections. No provider authorization, tokens, or actual connected accounts are changed by this mode.
-This is an interaction prototype, not the production callback implementation. Production must pass Composio's `callback_url`, bind the attempt to the authenticated user and account, and verify account ownership and ACTIVE status with Composio before showing connected. The existing real authorization route still does not provide that callback.
+Real authorization supplies a callback URL on the configured public origin and returns to the same conversation. A twenty-minute, user-bound session-storage attempt retains the account ID, originating widget, search, expanded state, and scroll position. The server lists only the authenticated actor’s active connected accounts; the browser verifies the expected account before showing success and removes callback parameters. Connected apps are refreshed on page load and window focus. Returning skips the welcome animation. Reply widgets become available after the reply is persisted. The loopback preview remains a separate simulation and does not connect real accounts.
The welcome uses the organization's configured branding `orgName`, falling back to “your company” when it is unavailable.
diff --git a/plugins/web-ui/server/composio-return.ts b/plugins/web-ui/server/composio-return.ts
new file mode 100644
index 000000000..f5c1f6b64
--- /dev/null
+++ b/plugins/web-ui/server/composio-return.ts
@@ -0,0 +1,20 @@
+export function composioCallbackUrl(publicUrl: string, returnTo: unknown, state: unknown): string | null {
+ if (typeof returnTo !== "string" || typeof state !== "string" || !/^[a-zA-Z0-9_-]{20,100}$/.test(state)) return null;
+ if (!returnTo.startsWith("/") || returnTo.startsWith("//") || /[\\\r\n]/.test(returnTo) || returnTo.length > 4096)
+ return null;
+ const base = new URL(publicUrl);
+ const target = new URL(returnTo, base);
+ const prefix = base.pathname.replace(/\/$/, "");
+ if (
+ target.origin !== base.origin ||
+ !(
+ target.pathname === `${prefix}/` ||
+ new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/s/[a-zA-Z0-9_-]+$`).test(target.pathname)
+ )
+ )
+ return null;
+ for (const key of ["status", "error", "connectedAccountId", "composioReturn"]) target.searchParams.delete(key);
+ target.hash = "";
+ target.searchParams.set("composioReturn", state);
+ return target.href;
+}
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index 8e47a8ee1..af7e7e72b 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -1,3 +1,4 @@
+import { composioCallbackUrl } from "./composio-return.ts";
import { sharedSessionHtml } from "./shared-session.ts";
import { createServer, type IncomingMessage, type ServerResponse, type Server } from "node:http";
import { AsyncLocalStorage } from "node:async_hooks";
@@ -1147,14 +1148,35 @@ const apiRoutes: readonly WebRoute[] = [
`/v1/composio/toolkits?${new URLSearchParams({ cursor: c.url.searchParams.get("cursor") ?? "" })}`,
),
},
+ {
+ method: "GET",
+ path: "/api/composio/connections",
+ handle: async (c) => {
+ c.res.setHeader("Cache-Control", "no-store");
+ return relayCore(
+ c.res,
+ "GET",
+ `/v1/composio/connections?${new URLSearchParams({ cursor: c.url.searchParams.get("cursor") ?? "" })}`,
+ );
+ },
+ },
{
method: "POST",
path: "/api/composio/authorize",
handle: async (c) => {
- const body = await readJson<{ toolkit?: unknown }>(c.req, c.res, false);
+ const body = await readJson<{ toolkit?: unknown; returnTo?: unknown; state?: unknown }>(c.req, c.res, false);
if (!body) return;
c.res.setHeader("Cache-Control", "no-store");
- return relayCore(c.res, "POST", "/v1/composio/authorize", JSON.stringify({ toolkit: body.toolkit }));
+ const callbackUrl = composioCallbackUrl(PUBLIC_URL, body.returnTo, body.state);
+ if (!callbackUrl && (body.returnTo !== undefined || body.state !== undefined)) {
+ return json(c.res, 400, { error: "invalid_return_url" });
+ }
+ return relayCore(
+ c.res,
+ "POST",
+ "/v1/composio/authorize",
+ JSON.stringify({ toolkit: body.toolkit, ...(callbackUrl ? { callbackUrl } : {}) }),
+ );
},
},
{
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index ce860958c..97a532546 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -1,3 +1,4 @@
+import { isConnectionReturn } from "./connection-return";
import "./onboarding-welcome";
import { setupContent } from "./setup-widget";
import { isWelcomeConversation } from "./welcome-session";
@@ -210,6 +211,8 @@ export function createChatSurface(
ctx.composer.state.error = message;
});
const transcriptViewport = createTranscriptViewport();
+ let preserveConnectionScroll = isConnectionReturn();
+ let connectionReturnMessageCount: number | null = null;
const transcriptFetcher = dependencies.fetchTranscript ?? fetchTranscript;
const sessionOpener = dependencies.openSession ?? openSession;
@@ -1296,6 +1299,10 @@ export function createChatSurface(
if (!agent || agent !== chatState.agent || !chatState.host || appState.currentView !== "chats") return;
transcriptViewport.beforeRender();
const currentMessages = visibleMessages(agent);
+ if (preserveConnectionScroll) {
+ connectionReturnMessageCount ??= currentMessages.length;
+ if (connectionReturnMessageCount !== currentMessages.length) preserveConnectionScroll = false;
+ }
const messages = chatState.inheritedExpanded
? [...chatState.inheritedMessages, ...currentMessages]
: currentMessages;
@@ -1313,7 +1320,7 @@ export function createChatSurface(
}
const tier = ctx.density();
const glanceTier = tier === "card" || tier === "strip" ? tier : null;
- const emptyChat = !messages.length && !chatState.forkSession;
+ const emptyChat = !messages.length && (showWelcome || !chatState.forkSession);
render(
html`
<div
@@ -1339,7 +1346,7 @@ export function createChatSurface(
<div class="message-stack ${emptyChat ? "empty-stack" : ""}">
${showWelcome ? welcomeGreeting(!messages.length) : nothing} ${inheritedHeader()}
${chatState.earlierCount > 0 ? earlierNotice(agent) : nothing} ${messageContent}
- ${emptyChat && !isNewUser ? html`<h1 class="chat-cta">${chatCta()}</h1>` : nothing}
+ ${emptyChat && !isNewUser && !showWelcome ? html`<h1 class="chat-cta">${chatCta()}</h1>` : nothing}
${showStateError(messages, agent.state.errorMessage) ? html`<div class="composer-error inline">${agent.state.errorMessage}</div>` : nothing}
</div>
</section>
@@ -1758,16 +1765,18 @@ export function createChatSurface(
function assistantContent(message: AssistantMessage, isStreaming = false, hasWork = false): TemplateResult[] {
const parts: TemplateResult[] = [];
- for (const chunk of message.content) {
+ for (const [chunkIndex, chunk] of message.content.entries()) {
if (chunk.type === "text") {
- for (const part of setupContent(assistantDisplayText(chunk.text))) {
+ for (const [partIndex, part] of setupContent(assistantDisplayText(chunk.text)).entries()) {
if (part.type !== "text") {
+ if (!(message as AssistantWork).persisted) continue;
parts.push(
html`<qm-onboarding-welcome
.me=${appState.me}
.base=${withBase("")}
.adminBase=${ADMIN_BASE}
.widget=${part.type === "slack" ? "slack" : "apps"}
+ .returnKey=${`reply:${message.timestamp}:${chunkIndex}:${partIndex}`}
.setupOnly=${true}
.animateWelcome=${false}
></qm-onboarding-welcome>`,
@@ -2711,7 +2720,7 @@ export function createChatSurface(
}
function scrollTranscript(force = false): void {
- if (ctx.container()?.querySelector(".empty-chat qm-onboarding-welcome")) {
+ if (preserveConnectionScroll || ctx.container()?.querySelector(".empty-chat qm-onboarding-welcome")) {
transcriptViewport.sync(null);
return;
}
diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.ts
index b9cee9d6f..b4c8bb240 100644
--- a/plugins/web-ui/src/composer.ts
+++ b/plugins/web-ui/src/composer.ts
@@ -1645,7 +1645,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
return;
}
pendingComposerFocus = false;
- ta.focus();
+ ta.focus({ preventScroll: true });
ta.setSelectionRange(ta.value.length, ta.value.length);
});
}
diff --git a/plugins/web-ui/src/connection-return.ts b/plugins/web-ui/src/connection-return.ts
new file mode 100644
index 000000000..7662fbe85
--- /dev/null
+++ b/plugins/web-ui/src/connection-return.ts
@@ -0,0 +1,97 @@
+import type { PickerState } from "./connection-preview";
+
+export interface ConnectionAttempt {
+ state: string;
+ user: string;
+ service: { id: string; name: string };
+ accountId: string;
+ widget: string;
+ expiresAt: number;
+ path: string;
+ picker: PickerState;
+ scrollTop: number;
+}
+const key = (user: string) => `qm-connection-return:${user}`;
+
+export function saveConnectionAttempt(attempt: ConnectionAttempt): void {
+ sessionStorage.setItem(key(attempt.user), JSON.stringify(attempt));
+}
+
+export function readConnectionAttempt(user: string, state: string, path: string): ConnectionAttempt | null {
+ try {
+ const attempt = JSON.parse(sessionStorage.getItem(key(user)) ?? "null") as ConnectionAttempt | null;
+ if (
+ !attempt ||
+ attempt.user !== user ||
+ attempt.state !== state ||
+ attempt.path !== path ||
+ !Number.isFinite(attempt.expiresAt) ||
+ attempt.expiresAt <= Date.now() ||
+ typeof attempt.accountId !== "string" ||
+ !/^ca_[a-zA-Z0-9_-]+$/.test(attempt.accountId) ||
+ typeof attempt.widget !== "string" ||
+ typeof attempt.service?.id !== "string" ||
+ typeof attempt.service.name !== "string" ||
+ typeof attempt.picker?.query !== "string" ||
+ typeof attempt.picker.expanded !== "boolean" ||
+ !Number.isFinite(attempt.scrollTop) ||
+ attempt.scrollTop < 0
+ )
+ return null;
+ return attempt;
+ } catch {
+ return null;
+ }
+}
+
+export function clearConnectionAttempt(user: string): void {
+ try {
+ sessionStorage.removeItem(key(user));
+ } catch {
+ return;
+ }
+}
+
+let initialReturnUrl: URL | null = null;
+let capturedReturn: {
+ user: string;
+ widget: string;
+ url: URL;
+ attempt: ConnectionAttempt | null;
+ verified: boolean;
+} | null = null;
+export function captureConnectionReturn(url: string): void {
+ initialReturnUrl = new URL(url);
+ capturedReturn = null;
+}
+export function isConnectionReturn(): boolean {
+ return initialReturnUrl?.searchParams.has("composioReturn") === true;
+}
+export function takeConnectionReturn(
+ user: string,
+ widget: string,
+): { url: URL; attempt: ConnectionAttempt | null; verified: boolean } | null {
+ if (!isConnectionReturn()) return null;
+ if (capturedReturn) return capturedReturn.user === user && capturedReturn.widget === widget ? capturedReturn : null;
+ let owner = "welcome";
+ try {
+ const attempt = JSON.parse(sessionStorage.getItem(key(user)) ?? "null") as ConnectionAttempt | null;
+ if (typeof attempt?.widget === "string") owner = attempt.widget;
+ } catch {
+ owner = "welcome";
+ }
+ if (owner !== widget) return null;
+ const url = new URL(initialReturnUrl!.href);
+ capturedReturn = {
+ user,
+ widget,
+ verified: false,
+ url,
+ attempt: readConnectionAttempt(user, url.searchParams.get("composioReturn")!, url.pathname),
+ };
+ return capturedReturn;
+}
+
+export function completeConnectionReturn(user: string, state: string): void {
+ if (capturedReturn?.user === user && capturedReturn.attempt?.state === state) capturedReturn.verified = true;
+}
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index deea0ba4a..3c8e8531d 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -414,6 +414,7 @@ export interface ApprovalDecision {
scope?: "once" | "session" | "always";
}
export type AssistantWork = AssistantMessage & {
+ persisted?: boolean;
work?: WorkBlock;
deliveredFiles?: DeliveredFile[];
retryableSend?: boolean;
@@ -1684,6 +1685,7 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):
}
}
const msg: AssistantWork = {
+ persisted: true,
role: "assistant",
content: [{ type: "text", text }],
api: model?.api ?? "unknown",
diff --git a/plugins/web-ui/src/onboarding-welcome.ts b/plugins/web-ui/src/onboarding-welcome.ts
index 71805022e..9c6ee6eff 100644
--- a/plugins/web-ui/src/onboarding-welcome.ts
+++ b/plugins/web-ui/src/onboarding-welcome.ts
@@ -1,3 +1,11 @@
+import {
+ isConnectionReturn,
+ takeConnectionReturn,
+ completeConnectionReturn,
+ saveConnectionAttempt,
+ clearConnectionAttempt,
+ type ConnectionAttempt,
+} from "./connection-return";
import { LitElement, html, nothing } from "lit";
import { ArrowUpRight, Check } from "lucide";
import { icon, slackMark } from "./ui";
@@ -25,6 +33,7 @@ export class OnboardingWelcome extends LitElement {
animateWelcome: { type: Boolean },
setupOnly: { type: Boolean },
widget: {},
+ returnKey: {},
base: {},
adminBase: {},
loading: { state: true },
@@ -32,17 +41,30 @@ export class OnboardingWelcome extends LitElement {
authorizing: { state: true },
authorizationError: { state: true },
connectionOutcome: { state: true },
+ connections: { state: true },
+ connectionError: { state: true },
};
declare me: Me | null;
declare animateWelcome: boolean;
declare setupOnly: boolean;
declare widget: "all" | "apps" | "slack";
+ declare returnKey: string;
declare base: string;
declare adminBase: string;
declare loading: boolean;
declare error: string;
declare authorizing: string;
declare authorizationError: string;
+ private connections: Array<{ id: string; toolkit: string }> = [];
+ private connectionError = "";
+ private realReturn: ConnectionAttempt | null = null;
+ private connectionsController?: AbortController;
+ private restoreScrollTop: number | null = null;
+ private returnError = "";
+ private returnAccount = "";
+ private refreshConnections = () => {
+ if (!this.preview && this.widget !== "slack" && !document.hidden) void this.loadConnections();
+ };
private preview = connectionPreviewEnabled();
private consent: PreviewAttempt | null = null;
private returned: PreviewAttempt | null = null;
@@ -58,6 +80,7 @@ export class OnboardingWelcome extends LitElement {
this.animateWelcome = true;
this.setupOnly = false;
this.widget = "all";
+ this.returnKey = "welcome";
this.base = "/";
this.adminBase = "/admin";
this.loading = true;
@@ -74,6 +97,30 @@ export class OnboardingWelcome extends LitElement {
}
protected firstUpdated(): void {
const params = previewParameters();
+ const returnUrl =
+ !this.preview && this.widget !== "slack" ? takeConnectionReturn(this.previewUser(), this.returnKey) : null;
+ const realParams = returnUrl?.url.searchParams;
+ const returning = !this.preview && isConnectionReturn();
+ if (realParams) {
+ const attempt = returnUrl!.attempt;
+ this.realReturn = returnUrl!.verified ? null : attempt;
+ this.returnError = realParams.get("error") ?? "";
+ this.returnAccount = realParams.get("connectedAccountId") ?? "";
+ if (attempt) {
+ this.pickerState = { ...attempt.picker };
+ this.restoreScrollTop = attempt.scrollTop;
+ this.retryService = attempt.service;
+ this.connectionOutcome = returnUrl!.verified ? "" : "checking";
+ } else this.connectionOutcome = "expired";
+ const clean = new URL(location.href);
+ for (const key of ["composioReturn", "status", "error", "connectedAccountId"]) clean.searchParams.delete(key);
+ history.replaceState(history.state, "", clean);
+ }
+ if (!this.preview && this.widget !== "slack") {
+ window.addEventListener("focus", this.refreshConnections);
+ document.addEventListener("visibilitychange", this.refreshConnections);
+ void this.loadConnections();
+ }
if (this.preview) {
const visible = new URL(location.href);
visible.searchParams.set("connectionDemo", "1");
@@ -110,6 +157,7 @@ export class OnboardingWelcome extends LitElement {
for (const key of ["connectionReturn", "status", "error", "connectedAccountId"]) clean.searchParams.delete(key);
history.replaceState(history.state, "", clean);
} else if (
+ !returning &&
!this.setupOnly &&
this.animateWelcome &&
globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches === false
@@ -120,7 +168,9 @@ export class OnboardingWelcome extends LitElement {
}
private drawPicker(): void {
const target = this.querySelector<HTMLElement>(".welcome-picker");
- const connected = this.preview ? previewConnections(this.previewUser()) : [];
+ const connected = this.preview
+ ? previewConnections(this.previewUser())
+ : this.connections.map((account) => account.toolkit);
if (target && !this.error && !this.loading)
mountConnectionPicker(
target,
@@ -132,6 +182,56 @@ export class OnboardingWelcome extends LitElement {
disconnectedCallback(): void {
super.disconnectedCallback();
this.controller?.abort();
+ this.connectionsController?.abort();
+ window.removeEventListener("focus", this.refreshConnections);
+ document.removeEventListener("visibilitychange", this.refreshConnections);
+ }
+ private async loadConnections(): Promise<void> {
+ this.connectionsController?.abort();
+ const controller = (this.connectionsController = new AbortController());
+ this.connectionError = "";
+ try {
+ const accounts: Array<{ id: string; toolkit: string }> = [];
+ const seen = new Set<string>();
+ let cursor = "";
+ do {
+ if (seen.has(cursor) || seen.size >= 100) throw new Error("Could not finish checking connected apps.");
+ seen.add(cursor);
+ const response = await fetch(`${this.base}api/composio/connections?${new URLSearchParams({ cursor })}`, {
+ signal: controller.signal,
+ });
+ const result = await response.json();
+ if (!response.ok || !Array.isArray(result.items))
+ throw new Error("Could not check connected apps. Please try again.");
+ accounts.push(...result.items);
+ cursor = typeof result.nextCursor === "string" ? result.nextCursor : "";
+ } while (cursor);
+ if (!this.isConnected || controller.signal.aborted) return;
+ this.connections = accounts;
+ if (this.realReturn) {
+ const attempt = this.realReturn;
+ const verified = accounts.some(
+ (account) => account.id === attempt.accountId && account.toolkit === attempt.service.id,
+ );
+ if (verified && (!this.returnAccount || this.returnAccount === attempt.accountId))
+ this.connectionOutcome = "success";
+ else this.connectionOutcome = this.returnError === "access_denied" ? "cancelled" : "failed";
+ clearConnectionAttempt(this.previewUser());
+ if (this.connectionOutcome === "success") {
+ completeConnectionReturn(this.previewUser(), attempt.state);
+ this.realReturn = null;
+ }
+ }
+ await this.updateComplete;
+ this.drawPicker();
+ } catch (error) {
+ if (controller.signal.aborted || !this.isConnected) return;
+ this.connections = [];
+ this.connectionOutcome = "";
+ this.connectionError = error instanceof Error ? error.message : "Could not check connected apps.";
+ await this.updateComplete;
+ this.drawPicker();
+ }
}
private async loadCatalog(): Promise<void> {
this.controller?.abort();
@@ -167,9 +267,14 @@ export class OnboardingWelcome extends LitElement {
this.loading = false;
await this.updateComplete;
this.drawPicker();
- if (this.returned) {
- const scroller = this.closest(".chat-scroll");
- if (scroller) scroller.scrollTop = this.returned.scrollTop;
+ const restoreTop = this.returned?.scrollTop ?? this.restoreScrollTop;
+ if (restoreTop !== null && restoreTop !== undefined) {
+ await this.updateComplete;
+ requestAnimationFrame(() => {
+ const scroller = this.closest(".chat-scroll");
+ if (scroller && this.isConnected) scroller.scrollTop = restoreTop;
+ this.restoreScrollTop = null;
+ });
}
}
private async authorize(service: ConnectionService): Promise<void> {
@@ -181,13 +286,29 @@ export class OnboardingWelcome extends LitElement {
this.authorizing = service.name;
this.authorizationError = "";
try {
+ const state = crypto.randomUUID();
+ const attempt: ConnectionAttempt = {
+ state,
+ user: this.previewUser(),
+ service: { id: service.id, name: service.name },
+ accountId: "",
+ widget: this.returnKey,
+ expiresAt: Date.now() + 20 * 60_000,
+ path: location.pathname,
+ picker: { ...this.pickerState },
+ scrollTop: this.closest(".chat-scroll")?.scrollTop ?? 0,
+ };
+ saveConnectionAttempt(attempt);
const response = await fetch(`${this.base}api/composio/authorize`, {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ toolkit: service.id }),
+ body: JSON.stringify({ toolkit: service.id, returnTo: location.pathname + location.search, state }),
});
const result = await response.json();
if (!response.ok) throw new Error(result.message ?? "Could not open authorization. Please try again.");
+ if (typeof result.accountId !== "string" || !/^ca_[a-zA-Z0-9_-]+$/.test(result.accountId))
+ throw new Error("Could not start authorization. Please try again.");
+ saveConnectionAttempt({ ...attempt, accountId: result.accountId });
window.location.assign(result.url);
} catch (error) {
this.authorizationError =
@@ -227,8 +348,12 @@ export class OnboardingWelcome extends LitElement {
const name = this.me?.displayName?.trim().split(/\s+/)[0];
const cohort = this.me?.welcomeCohort;
const serviceName = this.retryService?.name ?? "App";
- const connected = this.preview ? previewConnections(this.previewUser()) : [];
- const connectedServices = this.services.filter((service) => connected.includes(service.id));
+ const connected = this.preview
+ ? previewConnections(this.previewUser())
+ : this.connections.map((account) => account.toolkit);
+ const connectedServices = [...new Set(connected)].map(
+ (id) => this.services.find((service) => service.id === id) ?? { id, name: id },
+ );
const outcome = {
"": { title: "", detail: "" },
checking: {
@@ -246,7 +371,7 @@ export class OnboardingWelcome extends LitElement {
expired: { title: "This connection attempt has expired", detail: "Choose an app below to start again." },
failed: {
title: `Couldn’t connect ${serviceName}`,
- detail: "The provider couldn’t finish authorization. Your other connections are unchanged.",
+ detail: "We couldn’t confirm an active connection yet. Try checking again, or restart authorization.",
},
}[this.connectionOutcome];
return html`<section class="welcome-content">
@@ -324,6 +449,8 @@ export class OnboardingWelcome extends LitElement {
</div>`
: nothing
}
+ ${this.connectionError ? html`<div class="welcome-connection-status" role="status">${this.connectionError} <button class="btn" @click=${() => void this.loadConnections()}>Check again</button></div>` : nothing}
+ ${!this.preview && this.connectionOutcome === "failed" ? html`<button class="btn" @click=${() => void this.loadConnections()}>Check again</button>` : nothing}
<div class="welcome-picker" ?inert=${Boolean(this.authorizing)}></div>
${
connectedServices.length
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index 929ce0a04..9ba1c4853 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -11702,3 +11702,30 @@ h3.ambient-field-label {
object-fit: contain;
background: var(--background);
}
+
+.conversation-error {
+ margin: auto;
+ padding: 48px 24px;
+ max-width: 480px;
+ text-align: center;
+}
+.conversation-error-code {
+ color: var(--muted-foreground);
+ font-size: 13px;
+}
+.conversation-error h1 {
+ outline: none;
+ margin: 12px 0;
+ font-size: 24px;
+ font-weight: 600;
+}
+.conversation-error p {
+ color: var(--muted-foreground);
+ line-height: 1.6;
+}
+.conversation-error-actions {
+ display: flex;
+ justify-content: center;
+ gap: 12px;
+ margin-top: 24px;
+}
diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.ts
index 818716229..cc2af946d 100644
--- a/plugins/web-ui/src/shell.ts
+++ b/plugins/web-ui/src/shell.ts
@@ -1,3 +1,4 @@
+import { captureConnectionReturn } from "./connection-return";
import { openModelConnectManager, renderModelConnectGate } from "./model-connect";
import { html, nothing, render, type TemplateResult } from "lit";
import {
@@ -25,6 +26,7 @@ import {
} from "lucide";
import {
api,
+ ApiError,
setSigninRequiredHandler,
type SigninRequired,
fetchRuntimeConfig,
@@ -45,7 +47,6 @@ import { clearAllDrafts, saveDraft, storedDraft } from "./drafts";
import { deepLinkPath, isPlainLeftClick, parseDeepLink, UI_BASE } from "./deep-link";
import {
adoptRemoteSplit,
- canvasToast,
beginPaneKindDrag,
drawCanvas,
endPaneDrag,
@@ -799,6 +800,32 @@ export function showMainEmpty(text: string): void {
);
}
+function showConversationError(unavailable: boolean): void {
+ showMainEmpty("");
+ if (!appState.mainEl) return;
+ render(
+ html`
+ <section class="conversation-error" aria-labelledby="conversation-error-title">
+ <span class="conversation-error-code">${unavailable ? "Connection problem" : "404"}</span>
+ <h1 id="conversation-error-title" tabindex="-1">
+ ${unavailable ? "Couldn't load conversation" : "Conversation not found"}
+ </h1>
+ <p>
+ ${unavailable ? "Something went wrong loading this conversation. Please try again." : "This conversation may have been deleted, or you may be signed into an account that doesn’t have access."}
+ </p>
+ <div class="conversation-error-actions">
+ <a class="btn" href=${withBase("/")}>Back to chats</a>
+ ${unavailable ? html`<button class="btn" @click=${() => location.reload()}>Try again</button>` : nothing}
+ </div>
+ </section>
+ `,
+ appState.mainEl,
+ );
+ appState.mainEl.querySelector<HTMLElement>("h1")?.focus();
+ renderList();
+ document.title = `${unavailable ? "Couldn't load conversation" : "Conversation not found"} · ${brandName()}`;
+}
+
function toggleSidebar(): void {
setSidebarOpen(!sidebarOpen);
}
@@ -954,6 +981,7 @@ export async function bootSafely(): Promise<void> {
}
export async function boot(): Promise<void> {
+ captureConnectionReturn(location.href);
const params = new URLSearchParams(location.search);
const {
view: wanted,
@@ -962,7 +990,13 @@ export async function boot(): Promise<void> {
} = parseDeepLink(UI_BASE, location.pathname, location.search);
const chatsLink = wanted === null || wanted === "chats";
const linkedId = wantedSession && chatsLink ? wantedSession : null;
- const entriesPrefetch = linkedId ? fetchTranscript(linkedId, { tailTurns: TAIL_TURNS }).catch(() => null) : null;
+ let transcriptUnavailable = false;
+ const loadLinkedTranscript = (id: string) =>
+ fetchTranscript(id, { tailTurns: TAIL_TURNS }).catch((error: unknown) => {
+ transcriptUnavailable = !(error instanceof ApiError && (error.status === 404 || error.status === 403));
+ return null;
+ });
+ const entriesPrefetch = linkedId ? loadLinkedTranscript(linkedId) : null;
const approvalsPrefetch = linkedId ? fetchSessionApprovals(linkedId) : null;
const runtimeConfigFetch = fetchRuntimeConfig();
const remoteSplitFetch = fetchRemoteSplit();
@@ -1019,7 +1053,7 @@ export async function boot(): Promise<void> {
const sessions = refreshSessions({ showLoading: true });
if (wantedSession && !viewIntent && wanted !== "app-edit") {
- const transcript = entriesPrefetch ?? fetchTranscript(wantedSession, { tailTurns: TAIL_TURNS }).catch(() => null);
+ const transcript = entriesPrefetch ?? loadLinkedTranscript(wantedSession);
const linked = (await transcript)?.session;
if (linked) {
exitSplitIfActive();
@@ -1034,12 +1068,8 @@ export async function boot(): Promise<void> {
exitSplitIfActive();
revealSessionSurface(match);
await openSession(match);
- } else if (mountRestoredCanvas()) {
- canvasToast("That conversation wasn't found, or you don't have access to it.");
- syncUrlFromState();
} else {
- showMainEmpty("That conversation wasn't found, or you don't have access to it.");
- renderList();
+ showConversationError(transcriptUnavailable);
}
return;
}
diff --git a/plugins/web-ui/test/api-body-parsing.test.ts b/plugins/web-ui/test/api-body-parsing.test.ts
index 707b5b052..8c7d9485e 100644
--- a/plugins/web-ui/test/api-body-parsing.test.ts
+++ b/plugins/web-ui/test/api-body-parsing.test.ts
@@ -132,3 +132,35 @@ test("routes that historically tolerated an empty body still do", async () => {
const forked = calls.at(-1);
assert.deepEqual(forked?.body, { principalId: "alice" });
});
+
+test("app authorization accepts existing browser payloads and validates new return context", async () => {
+ const authorize = (body: Record<string, unknown>) =>
+ fetch(`${base}/api/composio/authorize`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(body),
+ });
+ const legacy = await authorize({ toolkit: "gmail" });
+ assert.equal(legacy.status, 200);
+ assert.ok(calls.at(-1)?.url.startsWith("/v1/composio/authorize"));
+ assert.deepEqual(calls.at(-1)?.body, { toolkit: "gmail" });
+ const state = "00000000-0000-4000-8000-000000000000";
+ const modern = await authorize({ toolkit: "gmail", returnTo: "/s/chat", state });
+ assert.equal(modern.status, 200);
+ const callback = new URL(String(calls.at(-1)?.body.callbackUrl));
+ assert.equal(callback.pathname, "/s/chat");
+ assert.equal(callback.searchParams.get("composioReturn"), state);
+ const before = calls.length;
+ for (const invalid of [
+ { returnTo: "/s/chat" },
+ { state },
+ { returnTo: null, state: null },
+ { returnTo: "https://evil.example", state },
+ { returnTo: "/", state: "bad" },
+ ]) {
+ const response = await authorize({ toolkit: "gmail", ...invalid });
+ assert.equal(response.status, 400);
+ assert.equal((await response.json()).error, "invalid_return_url");
+ }
+ assert.equal(calls.length, before);
+});
diff --git a/plugins/web-ui/test/composio-return.test.ts b/plugins/web-ui/test/composio-return.test.ts
new file mode 100644
index 000000000..ae345fc6f
--- /dev/null
+++ b/plugins/web-ui/test/composio-return.test.ts
@@ -0,0 +1,60 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { composioCallbackUrl } from "../server/composio-return.ts";
+import { saveConnectionAttempt, readConnectionAttempt, clearConnectionAttempt } from "../src/connection-return.ts";
+
+const state = "00000000-0000-4000-8000-000000000000";
+test("callbacks stay on the configured public origin and preserve the conversation", () => {
+ assert.equal(
+ composioCallbackUrl("https://qm.example", "/s/chat?layout=single", state),
+ `https://qm.example/s/chat?layout=single&composioReturn=${state}`,
+ );
+ assert.equal(
+ composioCallbackUrl("https://qm.example/web-ui", "/web-ui/s/chat", state),
+ `https://qm.example/web-ui/s/chat?composioReturn=${state}`,
+ );
+ for (const path of [
+ "https://evil.example/",
+ "//evil.example/",
+ "/\\evil.example/",
+ "/admin/",
+ "/s/chat/../../auth/logout",
+ "/s/chat\n",
+ ]) {
+ assert.equal(composioCallbackUrl("https://qm.example", path, state), null);
+ }
+ assert.equal(composioCallbackUrl("https://qm.example", "/", "bad"), null);
+});
+
+test("return context is bound to the user, nonce, path and expiry", () => {
+ const values = new Map<string, string>();
+ Object.defineProperty(globalThis, "sessionStorage", {
+ configurable: true,
+ value: {
+ getItem: (key: string) => values.get(key) ?? null,
+ setItem: (key: string, value: string) => values.set(key, value),
+ removeItem: (key: string) => values.delete(key),
+ },
+ });
+ const attempt = {
+ state,
+ user: "theo:alice",
+ path: "/s/chat",
+ service: { id: "gmail", name: "Gmail" },
+ accountId: "ca_test",
+ widget: "welcome",
+ expiresAt: Date.now() + 60000,
+ picker: { query: "gmail", expanded: true },
+ scrollTop: 180,
+ };
+ saveConnectionAttempt(attempt);
+ assert.deepEqual(readConnectionAttempt(attempt.user, state, attempt.path), attempt);
+ assert.equal(readConnectionAttempt("theo:bob", state, attempt.path), null);
+ assert.equal(readConnectionAttempt(attempt.user, "different", attempt.path), null);
+ assert.equal(readConnectionAttempt(attempt.user, state, "/s/other"), null);
+ saveConnectionAttempt({ ...attempt, expiresAt: Date.now() - 1 });
+ assert.equal(readConnectionAttempt(attempt.user, state, attempt.path), null);
+ saveConnectionAttempt(attempt);
+ clearConnectionAttempt(attempt.user);
+ assert.equal(readConnectionAttempt(attempt.user, state, attempt.path), null);
+});
diff --git a/plugins/web-ui/test/connection-return-boot.test.ts b/plugins/web-ui/test/connection-return-boot.test.ts
new file mode 100644
index 000000000..ac82e6e7c
--- /dev/null
+++ b/plugins/web-ui/test/connection-return-boot.test.ts
@@ -0,0 +1,41 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { harness, type Harness } from "./deep-link-boot-fixture.ts";
+
+async function waitForText(h: Harness, text: RegExp): Promise<void> {
+ for (let i = 0; i < 100 && !text.test(h.mainText()); i++) await new Promise((resolve) => setTimeout(resolve, 5));
+ assert.match(h.mainText(), text);
+}
+
+test("real connection return survives router normalization and retires after verification", async () => {
+ const h = await harness({
+ path: "/s/sess-deep?composioReturn=return-nonce&status=success&connectedAccountId=ca_test",
+ welcome: true,
+ connectionReturn: true,
+ });
+ try {
+ await h.boot();
+ await waitForText(h, /Gmail connected/);
+ assert.equal(new URLSearchParams(location.search).has("composioReturn"), false);
+ assert.equal(sessionStorage.getItem("qm-connection-return:test:tester"), null);
+ assert.equal(document.querySelector("qm-onboarding-welcome.welcome-rolling"), null);
+ assert.equal((document.querySelector('input[type="search"]') as HTMLInputElement)?.value, "mail");
+ const original = document.querySelector("qm-onboarding-welcome")!;
+ const replacement = document.createElement("qm-onboarding-welcome");
+ Object.assign(replacement, { me: { org: "test", user: "tester" }, base: "/", animateWelcome: true });
+ original.replaceWith(replacement);
+ await waitForText(h, /Gmail connected/);
+ assert.equal((document.querySelector('input[type="search"]') as HTMLInputElement)?.value, "mail");
+ h.setConnections([]);
+ const remounted = document.createElement("qm-onboarding-welcome");
+ Object.assign(remounted, { me: { org: "test", user: "tester" }, base: "/", animateWelcome: true });
+ replacement.replaceWith(remounted);
+ window.dispatchEvent(new Event("focus"));
+ for (let i = 0; i < 100 && /Gmail connected/.test(h.mainText()); i++)
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ assert.doesNotMatch(h.mainText(), /Gmail connected|Couldn’t connect/);
+ } finally {
+ await h.close();
+ }
+});
diff --git a/plugins/web-ui/test/connection-return-widgets.test.ts b/plugins/web-ui/test/connection-return-widgets.test.ts
new file mode 100644
index 000000000..7b066fbd9
--- /dev/null
+++ b/plugins/web-ui/test/connection-return-widgets.test.ts
@@ -0,0 +1,41 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { harness } from "./deep-link-boot-fixture.ts";
+
+test("a recalled app picker owns its return even when welcome and Slack widgets mount first", async () => {
+ const h = await harness({
+ path: "/s/sess-deep?composioReturn=return-nonce&status=success&connectedAccountId=ca_test",
+ welcome: true,
+ connectionReturn: true,
+ returnWidget: "reply:1:0:0",
+ });
+ try {
+ await h.boot();
+ const welcome = document.querySelector("qm-onboarding-welcome")!;
+ const slack = Object.assign(document.createElement("qm-onboarding-welcome"), {
+ me: { org: "test", user: "tester" },
+ widget: "slack",
+ setupOnly: true,
+ returnKey: "reply:0:0:0",
+ });
+ document.querySelector(".message-stack")!.append(slack);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ assert.notEqual(sessionStorage.getItem("qm-connection-return:test:tester"), null);
+ assert.equal((welcome.querySelector('input[type="search"]') as HTMLInputElement)?.value, "");
+ const apps = Object.assign(document.createElement("qm-onboarding-welcome"), {
+ me: { org: "test", user: "tester" },
+ widget: "apps",
+ setupOnly: true,
+ returnKey: "reply:1:0:0",
+ });
+ document.querySelector(".message-stack")!.append(apps);
+ for (let i = 0; i < 100 && sessionStorage.getItem("qm-connection-return:test:tester"); i++)
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ assert.equal(sessionStorage.getItem("qm-connection-return:test:tester"), null);
+ assert.equal((apps.querySelector('input[type="search"]') as HTMLInputElement)?.value, "mail");
+ assert.equal((welcome.querySelector('input[type="search"]') as HTMLInputElement)?.value, "");
+ assert.match(apps.textContent ?? "", /Gmail connected/);
+ } finally {
+ await h.close();
+ }
+});
diff --git a/plugins/web-ui/test/deep-link-boot-fixture.ts b/plugins/web-ui/test/deep-link-boot-fixture.ts
new file mode 100644
index 000000000..a796d8c52
--- /dev/null
+++ b/plugins/web-ui/test/deep-link-boot-fixture.ts
@@ -0,0 +1,226 @@
+import { JSDOM } from "jsdom";
+import { createServer } from "vite";
+
+export interface Harness {
+ requests: string[];
+ setConnections: (items: unknown[], status?: number) => void;
+ releaseSessions: () => void;
+ releaseTranscript: () => void;
+ releaseApprovals: () => void;
+ sessionsReady: () => Promise<void>;
+ boot: () => Promise<void>;
+ appState: { currentView: string };
+ sessionsState: { list: Array<{ id: string }>; loaded: boolean; openingKey: string | null };
+ visibleConversation: () => { state: { sessionId: string | null; threadRef: string | null } };
+ mainText: () => string;
+ close: () => Promise<void>;
+}
+
+interface HarnessOptions {
+ path: string;
+ transcriptStatus?: number;
+ transcriptFailures?: number;
+ holdTranscript?: boolean;
+ holdApprovals?: boolean;
+ listSessions?: unknown[];
+ savedCanvas?: boolean;
+ welcome?: boolean;
+ connectionReturn?: boolean;
+ returnWidget?: string;
+}
+
+export const SESSION = {
+ id: "sess-deep",
+ threadRef: "web:tester:deep",
+ scopeId: "personal:tester",
+ title: "Deep linked chat",
+};
+
+export async function harness(opts: HarnessOptions): Promise<Harness> {
+ const dom = new JSDOM('<!doctype html><div id="app"></div>', {
+ url: `http://localhost${opts.path}`,
+ pretendToBeVisual: true,
+ });
+ if (opts.savedCanvas)
+ dom.window.localStorage.setItem(
+ "web-ui:split-canvas:v1",
+ JSON.stringify({
+ v: 1,
+ active: true,
+ root: {
+ kind: "split",
+ a: { kind: "leaf", threadRef: "web:tester:old-a" },
+ b: { kind: "leaf", threadRef: "web:tester:old-b" },
+ },
+ }),
+ );
+ let connectedItems: unknown[] = opts.connectionReturn ? [{ id: "ca_test", toolkit: "gmail" }] : [];
+ let connectedStatus = 200;
+ if (opts.connectionReturn)
+ dom.window.sessionStorage.setItem(
+ "qm-connection-return:test:tester",
+ JSON.stringify({
+ state: "return-nonce",
+ user: "test:tester",
+ path: "/s/sess-deep",
+ service: { id: "gmail", name: "Gmail" },
+ accountId: "ca_test",
+ widget: opts.returnWidget ?? "welcome",
+ expiresAt: Date.now() + 60000,
+ picker: { query: "mail", expanded: true },
+ scrollTop: 0,
+ }),
+ );
+ const timers = new Set<ReturnType<typeof setTimeout>>();
+ const realSetTimeout = globalThis.setTimeout;
+ const realSetInterval = globalThis.setInterval;
+ const requests: string[] = [];
+ const inFlight = new Set<Promise<Response>>();
+ let releaseSessions = (): void => {};
+ let releaseTranscript = (): void => {};
+ let releaseApprovals = (): void => {};
+ const approvalsHeld = new Promise<void>((resolve) => (releaseApprovals = resolve));
+ const sessionsHeld = new Promise<void>((resolve) => (releaseSessions = resolve));
+ const transcriptHeld = new Promise<void>((resolve) => (releaseTranscript = resolve));
+ let failuresLeft = opts.transcriptFailures ?? (opts.transcriptStatus ? Number.POSITIVE_INFINITY : 0);
+ const respond = async (input: RequestInfo | URL): Promise<Response> => {
+ const path = String(input);
+ requests.push(path);
+ if (path === "/me")
+ return Response.json({
+ user: "tester",
+ org: "test",
+ permissions: [],
+ ...(opts.welcome ? { welcomeCohort: "F26" } : {}),
+ });
+ if (path.startsWith("/api/composio/connections"))
+ return Response.json({ items: connectedItems, nextCursor: null }, { status: connectedStatus });
+ if (path.startsWith("/api/composio/toolkits"))
+ return Response.json({ items: [{ id: "gmail", name: "Gmail", description: "Email" }], nextCursor: null });
+ if (path.startsWith("/api/runtime-config")) {
+ return Response.json({
+ scopeId: "personal:tester",
+ approvedHarnesses: [],
+ modelsByHarness: {},
+ modelCatalog: {},
+ orgDefault: { harnessId: "pi", modelId: "m", revision: 1 },
+ scopeOverride: null,
+ effective: { harnessId: "pi", modelId: "m" },
+ upgradeAvailable: false,
+ });
+ }
+ if (path.startsWith("/api/ui-state")) return Response.json({ value: null, updatedAt: 0 });
+ if (path.startsWith("/api/sessions/") && path.includes("/approvals")) {
+ if (opts.holdApprovals) await approvalsHeld;
+ return Response.json({ approvals: [] });
+ }
+ if (path.startsWith(`/api/sessions/${SESSION.id}`)) {
+ if (opts.holdTranscript) await transcriptHeld;
+ if (failuresLeft > 0) {
+ failuresLeft--;
+ return Response.json({ error: "not_found" }, { status: opts.transcriptStatus ?? 500 });
+ }
+ return Response.json({ session: SESSION, entries: [] });
+ }
+ if (path === "/api/sessions") {
+ await sessionsHeld;
+ return Response.json({ sessions: opts.listSessions ?? [] });
+ }
+ return Response.json({ contexts: [], items: [], crons: [] });
+ };
+
+ const globals = {
+ fetch: (input: RequestInfo | URL): Promise<Response> => {
+ const answer = respond(input);
+ inFlight.add(answer);
+ void answer.finally(() => inFlight.delete(answer)).catch(() => {});
+ return answer;
+ },
+ window: dom.window,
+ document: dom.window.document,
+ location: dom.window.location,
+ history: dom.window.history,
+ localStorage: dom.window.localStorage,
+ sessionStorage: dom.window.sessionStorage,
+ navigator: dom.window.navigator,
+ HTMLElement: dom.window.HTMLElement,
+ Element: dom.window.Element,
+ Node: dom.window.Node,
+ Event: dom.window.Event,
+ PointerEvent: dom.window.PointerEvent,
+ MouseEvent: dom.window.MouseEvent,
+ customElements: dom.window.customElements,
+ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
+ cancelAnimationFrame: clearTimeout,
+ EventSource: undefined,
+ ResizeObserver: class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ setTimeout: ((...args: Parameters<typeof setTimeout>) => {
+ const id = realSetTimeout(...args);
+ timers.add(id);
+ return id;
+ }) as typeof setTimeout,
+ setInterval: ((...args: Parameters<typeof setInterval>) => {
+ const id = realSetInterval(...args);
+ timers.add(id);
+ return id;
+ }) as typeof setInterval,
+ requestAnimationFrame: (callback: FrameRequestCallback) => {
+ const id = realSetTimeout(() => callback(Date.now()), 0);
+ timers.add(id);
+ return id as unknown as number;
+ },
+ };
+ const descriptors = new Map<string, PropertyDescriptor | undefined>();
+ for (const [key, value] of Object.entries(globals)) {
+ descriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
+ Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
+ }
+ Object.defineProperty(dom.window, "matchMedia", {
+ value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),
+ });
+
+ const vite = await createServer({ server: { middlewareMode: true, hmr: false, ws: false }, appType: "custom" });
+ const shell = await vite.ssrLoadModule("/src/shell.ts");
+ const sessions = await vite.ssrLoadModule("/src/sessions.ts");
+ const conversations = await vite.ssrLoadModule("/src/conversations.ts");
+ return {
+ requests,
+ setConnections: (items, status = 200) => {
+ connectedItems = items;
+ connectedStatus = status;
+ },
+ releaseSessions,
+ releaseTranscript,
+ releaseApprovals,
+ sessionsReady: sessions.sessionsReady as () => Promise<void>,
+ boot: shell.boot as () => Promise<void>,
+ appState: shell.appState as Harness["appState"],
+ sessionsState: sessions.sessionsState as Harness["sessionsState"],
+ visibleConversation: () =>
+ conversations
+ .allConversations()
+ .find((conv: { state: { host: HTMLElement | null } }) => conv.state.host?.isConnected) ??
+ conversations.mainConversation(),
+ mainText: () => dom.window.document.querySelector(".main")?.textContent ?? "",
+ close: async () => {
+ releaseSessions();
+ releaseTranscript();
+ releaseApprovals();
+ for (let drain = 0; drain < 5 && inFlight.size; drain++) {
+ await Promise.allSettled(inFlight);
+ await new Promise((resolve) => realSetTimeout(resolve, 0));
+ }
+ await vite.close();
+ dom.window.close();
+ for (const id of timers) clearTimeout(id);
+ for (const [key, descriptor] of descriptors) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else delete (globalThis as Record<string, unknown>)[key];
+ }
+ },
+ };
+}
diff --git a/plugins/web-ui/test/deep-link-boot.test.ts b/plugins/web-ui/test/deep-link-boot.test.ts
index 288cdd0c7..7824da456 100644
--- a/plugins/web-ui/test/deep-link-boot.test.ts
+++ b/plugins/web-ui/test/deep-link-boot.test.ts
@@ -1,178 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { JSDOM } from "jsdom";
-import { createServer } from "vite";
-
-interface Harness {
- requests: string[];
- releaseSessions: () => void;
- releaseTranscript: () => void;
- releaseApprovals: () => void;
- sessionsReady: () => Promise<void>;
- boot: () => Promise<void>;
- appState: { currentView: string };
- sessionsState: { list: Array<{ id: string }>; loaded: boolean; openingKey: string | null };
- visibleConversation: () => { state: { sessionId: string | null; threadRef: string | null } };
- mainText: () => string;
- close: () => Promise<void>;
-}
-
-interface HarnessOptions {
- path: string;
- transcriptStatus?: number;
- transcriptFailures?: number;
- holdTranscript?: boolean;
- holdApprovals?: boolean;
- listSessions?: unknown[];
-}
-
-const SESSION = {
- id: "sess-deep",
- threadRef: "web:tester:deep",
- scopeId: "personal:tester",
- title: "Deep linked chat",
-};
-
-async function harness(opts: HarnessOptions): Promise<Harness> {
- const dom = new JSDOM('<!doctype html><div id="app"></div>', { url: `http://localhost${opts.path}` });
- const timers = new Set<ReturnType<typeof setTimeout>>();
- const realSetTimeout = globalThis.setTimeout;
- const realSetInterval = globalThis.setInterval;
- const requests: string[] = [];
- const inFlight = new Set<Promise<Response>>();
- let releaseSessions = (): void => {};
- let releaseTranscript = (): void => {};
- let releaseApprovals = (): void => {};
- const approvalsHeld = new Promise<void>((resolve) => (releaseApprovals = resolve));
- const sessionsHeld = new Promise<void>((resolve) => (releaseSessions = resolve));
- const transcriptHeld = new Promise<void>((resolve) => (releaseTranscript = resolve));
- let failuresLeft = opts.transcriptFailures ?? (opts.transcriptStatus ? Number.POSITIVE_INFINITY : 0);
- const respond = async (input: RequestInfo | URL): Promise<Response> => {
- const path = String(input);
- requests.push(path);
- if (path === "/me") return Response.json({ user: "tester", org: "test", permissions: [] });
- if (path.startsWith("/api/runtime-config")) {
- return Response.json({
- scopeId: "personal:tester",
- approvedHarnesses: [],
- modelsByHarness: {},
- modelCatalog: {},
- orgDefault: { harnessId: "pi", modelId: "m", revision: 1 },
- scopeOverride: null,
- effective: { harnessId: "pi", modelId: "m" },
- upgradeAvailable: false,
- });
- }
- if (path.startsWith("/api/ui-state")) return Response.json({ value: null, updatedAt: 0 });
- if (path.startsWith("/api/sessions/") && path.includes("/approvals")) {
- if (opts.holdApprovals) await approvalsHeld;
- return Response.json({ approvals: [] });
- }
- if (path.startsWith(`/api/sessions/${SESSION.id}`)) {
- if (opts.holdTranscript) await transcriptHeld;
- if (failuresLeft > 0) {
- failuresLeft--;
- return Response.json({ error: "not_found" }, { status: opts.transcriptStatus ?? 500 });
- }
- return Response.json({ session: SESSION, entries: [] });
- }
- if (path === "/api/sessions") {
- await sessionsHeld;
- return Response.json({ sessions: opts.listSessions ?? [] });
- }
- return Response.json({ contexts: [], items: [], crons: [] });
- };
-
- const globals = {
- fetch: (input: RequestInfo | URL): Promise<Response> => {
- const answer = respond(input);
- inFlight.add(answer);
- void answer.finally(() => inFlight.delete(answer)).catch(() => {});
- return answer;
- },
- window: dom.window,
- document: dom.window.document,
- location: dom.window.location,
- history: dom.window.history,
- localStorage: dom.window.localStorage,
- navigator: dom.window.navigator,
- HTMLElement: dom.window.HTMLElement,
- Element: dom.window.Element,
- Node: dom.window.Node,
- Event: dom.window.Event,
- PointerEvent: dom.window.PointerEvent,
- MouseEvent: dom.window.MouseEvent,
- customElements: dom.window.customElements,
- getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
- cancelAnimationFrame: clearTimeout,
- EventSource: undefined,
- ResizeObserver: class {
- observe() {}
- unobserve() {}
- disconnect() {}
- },
- setTimeout: ((...args: Parameters<typeof setTimeout>) => {
- const id = realSetTimeout(...args);
- timers.add(id);
- return id;
- }) as typeof setTimeout,
- setInterval: ((...args: Parameters<typeof setInterval>) => {
- const id = realSetInterval(...args);
- timers.add(id);
- return id;
- }) as typeof setInterval,
- requestAnimationFrame: (callback: FrameRequestCallback) => {
- const id = realSetTimeout(() => callback(Date.now()), 0);
- timers.add(id);
- return id as unknown as number;
- },
- };
- const descriptors = new Map<string, PropertyDescriptor | undefined>();
- for (const [key, value] of Object.entries(globals)) {
- descriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
- Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
- }
- Object.defineProperty(dom.window, "matchMedia", {
- value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),
- });
-
- const vite = await createServer({ server: { middlewareMode: true, hmr: false, ws: false }, appType: "custom" });
- const shell = await vite.ssrLoadModule("/src/shell.ts");
- const sessions = await vite.ssrLoadModule("/src/sessions.ts");
- const conversations = await vite.ssrLoadModule("/src/conversations.ts");
- return {
- requests,
- releaseSessions,
- releaseTranscript,
- releaseApprovals,
- sessionsReady: sessions.sessionsReady as () => Promise<void>,
- boot: shell.boot as () => Promise<void>,
- appState: shell.appState as Harness["appState"],
- sessionsState: sessions.sessionsState as Harness["sessionsState"],
- visibleConversation: () =>
- conversations
- .allConversations()
- .find((conv: { state: { host: HTMLElement | null } }) => conv.state.host?.isConnected) ??
- conversations.mainConversation(),
- mainText: () => dom.window.document.querySelector(".main")?.textContent ?? "",
- close: async () => {
- releaseSessions();
- releaseTranscript();
- releaseApprovals();
- for (let drain = 0; drain < 5 && inFlight.size; drain++) {
- await Promise.allSettled(inFlight);
- await new Promise((resolve) => realSetTimeout(resolve, 0));
- }
- await vite.close();
- dom.window.close();
- for (const id of timers) clearTimeout(id);
- for (const [key, descriptor] of descriptors) {
- if (descriptor) Object.defineProperty(globalThis, key, descriptor);
- else delete (globalThis as Record<string, unknown>)[key];
- }
- },
- };
-}
+import { harness, SESSION, type Harness } from "./deep-link-boot-fixture.ts";
test("a share link paints its conversation from the transcript, without waiting for the session list", async () => {
const h = await harness({ path: "/s/sess-deep" });
@@ -219,7 +47,12 @@ test("a share link whose transcript 404s falls back to the session list", async
await booted;
assert.equal(h.sessionsState.loaded, true, "the fallback waits for the list");
assert.equal(h.visibleConversation().state.sessionId, null, "no conversation is mounted");
- assert.match(h.mainText(), /wasn't found, or you don't have access to it/);
+ assert.match(h.mainText(), /Conversation not found/);
+ assert.match(h.mainText(), /404/);
+ assert.match(h.mainText(), /Back to chats/);
+ assert.equal(location.pathname, "/s/sess-deep");
+ assert.equal(document.querySelector("textarea"), null);
+ assert.equal(document.activeElement?.id, "conversation-error-title");
} finally {
await h.close();
}
@@ -332,3 +165,66 @@ test("a view deep link still waits for the list and never fetches a transcript",
await h.close();
}
});
+
+test("a server failure shows a retry page rather than a missing conversation", async () => {
+ const h = await harness({ path: "/s/sess-deep", transcriptStatus: 503 });
+ try {
+ const booted = h.boot();
+ h.releaseSessions();
+ await booted;
+ assert.match(h.mainText(), /Couldn't load conversation/);
+ assert.match(h.mainText(), /Try again/);
+ assert.doesNotMatch(h.mainText(), /404/);
+ assert.equal(location.pathname, "/s/sess-deep");
+ } finally {
+ await h.close();
+ }
+});
+
+test("a missing share link keeps its error page instead of restoring the saved canvas", async () => {
+ const h = await harness({ path: "/s/sess-deep", transcriptStatus: 404, savedCanvas: true });
+ try {
+ const booted = h.boot();
+ h.releaseSessions();
+ await booted;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ assert.match(h.mainText(), /Conversation not found/);
+ assert.equal(location.pathname, "/s/sess-deep");
+ assert.equal(document.querySelector(".dockview-theme-light"), null);
+ assert.equal(document.querySelector("textarea"), null);
+ } finally {
+ await h.close();
+ }
+});
+
+async function waitForText(h: Harness, text: RegExp): Promise<void> {
+ for (let i = 0; i < 100 && !text.test(h.mainText()); i++) await new Promise((resolve) => setTimeout(resolve, 5));
+ assert.match(h.mainText(), text);
+}
+
+test("saved empty welcome stays an empty chat and doesn't show another starter heading", async () => {
+ const h = await harness({ path: "/s/sess-deep", welcome: true });
+ try {
+ await h.boot();
+ await waitForText(h, /Connect your apps/);
+ assert.ok(document.querySelector(".empty-chat qm-onboarding-welcome"));
+ assert.equal(document.querySelector(".chat-cta"), null);
+ } finally {
+ await h.close();
+ }
+});
+
+test("a failed connection refresh removes previously verified badges", async () => {
+ const h = await harness({ path: "/s/sess-deep", welcome: true });
+ try {
+ h.setConnections([{ id: "ca_test", toolkit: "gmail" }]);
+ await h.boot();
+ await waitForText(h, /Gmail connected/);
+ h.setConnections([], 503);
+ window.dispatchEvent(new Event("focus"));
+ await waitForText(h, /Could not check connected apps/);
+ assert.doesNotMatch(h.mainText(), /Gmail connected/);
+ } finally {
+ await h.close();
+ }
+});
diff --git a/src/api/routes/composio.ts b/src/api/routes/composio.ts
index 6c1a4764f..835769d9e 100644
--- a/src/api/routes/composio.ts
+++ b/src/api/routes/composio.ts
@@ -122,6 +122,25 @@ async function authorize(ctx: ApiCtx): Promise<void> {
const toolkit = (ctx.body as { toolkit?: unknown } | null)?.toolkit;
if (typeof toolkit !== "string" || !/^[a-z0-9_-]{1,100}$/.test(toolkit))
return sendJson(ctx.res, 400, { error: "invalid_toolkit" });
+ const callbackUrl = (ctx.body as { callbackUrl?: unknown }).callbackUrl;
+ if (callbackUrl !== undefined) {
+ try {
+ if (typeof callbackUrl !== "string" || callbackUrl.length > 4096) throw new Error("Invalid callback");
+ const callback = new URL(callbackUrl);
+ if (
+ callback.username ||
+ callback.password ||
+ callback.hash ||
+ !(
+ callback.protocol === "https:" ||
+ (callback.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(callback.hostname))
+ )
+ )
+ throw new Error("Invalid callback");
+ } catch {
+ return sendJson(ctx.res, 400, { error: "invalid_callback" });
+ }
+ }
try {
const session = await request(ctx, access.key, "/tool_router/session", {
user_id: composioUserId(orgId(), access.principal),
@@ -133,7 +152,10 @@ async function authorize(ctx: ApiCtx): Promise<void> {
throw new Error("Invalid session");
const link = await request(ctx, access.key, `/tool_router/session/${encodeURIComponent(session.session_id)}/link`, {
toolkit,
+ ...(callbackUrl ? { callback_url: callbackUrl } : {}),
});
+ if (typeof link.connected_account_id !== "string" || !/^ca_[a-zA-Z0-9_-]+$/.test(link.connected_account_id))
+ throw new Error("Invalid account");
const url = new URL(String(link.redirect_url));
if (
!(
@@ -150,7 +172,7 @@ async function authorize(ctx: ApiCtx): Promise<void> {
resource: toolkit,
scopeLabel: scopeId("personal", access.principal),
});
- return sendJson(ctx.res, 200, { url: url.href });
+ return sendJson(ctx.res, 200, { url: url.href, accountId: link.connected_account_id });
} catch {
return sendJson(ctx.res, 502, {
error: "composio_authorization_failed",
@@ -159,6 +181,44 @@ async function authorize(ctx: ApiCtx): Promise<void> {
}
}
+async function connections(ctx: ApiCtx): Promise<void> {
+ const access = await credential(ctx);
+ if (!access) return;
+ const cursor = ctx.url.searchParams.get("cursor") ?? "";
+ if (cursor.length > 2048) return sendJson(ctx.res, 400, { error: "bad_cursor" });
+ const userId = composioUserId(orgId(), access.principal);
+ const query = new URLSearchParams({ user_ids: userId, statuses: "ACTIVE", limit: "100" });
+ if (cursor) query.set("cursor", cursor);
+ try {
+ const data = await request(ctx, access.key, `/connected_accounts?${query}`);
+ if (!Array.isArray(data.items)) throw new Error("Invalid accounts");
+ const items = data.items.flatMap((item) => {
+ if (
+ !item ||
+ item.user_id !== userId ||
+ item.status !== "ACTIVE" ||
+ item.is_disabled === true ||
+ typeof item.id !== "string" ||
+ !/^ca_[a-zA-Z0-9_-]+$/.test(item.id) ||
+ typeof item.toolkit?.slug !== "string" ||
+ !/^[a-zA-Z0-9_-]{1,100}$/.test(item.toolkit.slug)
+ )
+ return [];
+ return [{ id: item.id, toolkit: item.toolkit.slug }];
+ });
+ ctx.res.setHeader("Cache-Control", "no-store");
+ return sendJson(ctx.res, 200, {
+ items,
+ nextCursor: typeof data.next_cursor === "string" ? data.next_cursor : null,
+ });
+ } catch {
+ return sendJson(ctx.res, 502, {
+ error: "composio_unavailable",
+ message: "Could not check connected apps. Please try again.",
+ });
+ }
+}
+
async function identity(ctx: ApiCtx): Promise<void> {
const principal = ctx.actor?.p ?? ctx.capability?.actorId;
if (!principal || !(await activePrincipal(ctx.deps, principal)))
@@ -167,6 +227,7 @@ async function identity(ctx: ApiCtx): Promise<void> {
}
export const composioRoutes: ReadonlyArray<Route<ApiCtx>> = [
+ { method: "GET", path: "/v1/composio/connections", auth: "source", handle: connections },
{ method: "GET", path: "/v1/composio/toolkits", auth: "source", handle: catalog },
{ method: "POST", path: "/v1/composio/authorize", auth: "source", handle: authorize },
{ method: "GET", path: "/v1/composio/identity", auth: "either", handle: identity },
diff --git a/test/composio-route.test.ts b/test/composio-route.test.ts
index bb817b458..34882ac11 100644
--- a/test/composio-route.test.ts
+++ b/test/composio-route.test.ts
@@ -37,6 +37,7 @@ function fixture() {
let text = "";
const url = new URL(path, "http://localhost");
const res = {
+ setHeader() {},
writeHead(code: number) {
status = code;
},
@@ -136,10 +137,13 @@ test("authorization binds the session to the authenticated actor, ignoring suppl
for (const link of ["https://connect.composio.dev/link/lk_test", "https://app.composio.dev/link/lt_test"]) {
const f = fixture();
await f.own();
- f.replies.push({ session_id: "trs_test" }, { redirect_url: link, secret: "hidden" });
+ f.replies.push(
+ { session_id: "trs_test" },
+ { redirect_url: link, connected_account_id: "ca_test", secret: "hidden" },
+ );
const r = await f.invoke("/v1/composio/authorize", { toolkit: "gmail", user_id: "bob", principalId: "bob" });
assert.equal(r.status, 200);
- assert.deepEqual(r.data, { url: link });
+ assert.deepEqual(r.data, { url: link, accountId: "ca_test" });
const payload = JSON.parse(String(f.calls[0]!.init?.body));
assert.equal(payload.user_id, composioUserId(orgId(), "alice"));
assert.deepEqual(payload.toolkits, { enable: ["gmail"] });
@@ -160,7 +164,7 @@ test("invalid toolkits and unsafe authorization destinations are rejected", asyn
"http://connect.composio.dev/link/lk_test",
"https://connect.composio.dev/other",
]) {
- f.replies.push({ session_id: "trs_test" }, { redirect_url });
+ f.replies.push({ session_id: "trs_test" }, { redirect_url, connected_account_id: "ca_test" });
assert.equal((await f.invoke("/v1/composio/authorize", { toolkit: "gmail" })).status, 502);
}
});
@@ -176,3 +180,60 @@ test("upstream errors are redacted and identity is stable per organization and p
assert.notEqual(composioUserId("a", "alice"), composioUserId("a", "bob"));
assert.deepEqual((await f.invoke("/v1/composio/identity")).data, { userId: composioUserId(orgId(), "alice") });
});
+
+test("authorization supplies the callback and account binding without accepting unsafe callback schemes", async () => {
+ const f = fixture();
+ await f.own();
+ for (const callbackUrl of ["javascript:alert(1)", "http://evil.example/", "https://user:[email protected]/"]) {
+ assert.equal((await f.invoke("/v1/composio/authorize", { toolkit: "gmail", callbackUrl })).status, 400);
+ }
+ assert.equal(f.calls.length, 0);
+ const callbackUrl = "https://qm.example/s/chat?composioReturn=nonce";
+ f.replies.push(
+ { session_id: "trs_test" },
+ { redirect_url: "https://connect.composio.dev/link/lk_test", connected_account_id: "ca_test" },
+ );
+ const r = await f.invoke("/v1/composio/authorize", { toolkit: "gmail", callbackUrl });
+ assert.equal(r.data.accountId, "ca_test");
+ assert.equal(JSON.parse(String(f.calls[1]!.init?.body)).callback_url, callbackUrl);
+});
+
+test("connections return only this actor's active accounts and strip credentials", async () => {
+ const f = fixture();
+ await f.own();
+ const owned = {
+ id: "ca_gmail",
+ user_id: composioUserId(orgId(), "alice"),
+ status: "ACTIVE",
+ toolkit: { slug: "gmail" },
+ data: { token: "secret-token" },
+ };
+ f.replies.push({
+ items: [
+ owned,
+ { ...owned, id: "ca_other", user_id: composioUserId(orgId(), "bob") },
+ { ...owned, status: "INITIATED" },
+ { ...owned, is_disabled: true },
+ ],
+ next_cursor: "next-page",
+ });
+ const r = await f.invoke("/v1/composio/connections?user_ids=bob&cursor=page-1");
+ assert.equal(r.status, 200);
+ assert.deepEqual(r.data, { items: [{ id: "ca_gmail", toolkit: "gmail" }], nextCursor: "next-page" });
+ const q = new URL(f.calls[0]!.url).searchParams;
+ assert.equal(q.get("user_ids"), composioUserId(orgId(), "alice"));
+ assert.equal(q.get("statuses"), "ACTIVE");
+ assert.equal(q.get("cursor"), "page-1");
+ assert.doesNotMatch(r.text, /secret-token|private-key|user_id/);
+});
+
+test("connections require credential access and fail visibly on upstream errors", async () => {
+ const f = fixture();
+ assert.equal((await f.invoke("/v1/composio/connections", undefined, null)).status, 401);
+ assert.equal((await f.invoke("/v1/composio/connections")).status, 403);
+ await f.own();
+ f.replies.push(new Error("private-key"));
+ const r = await f.invoke("/v1/composio/connections");
+ assert.equal(r.status, 502);
+ assert.doesNotMatch(r.text, /private-key/);
+});