diff --git a/web/components/events-shim/EventsShimTry.tsx b/web/components/events-shim/EventsShimTry.tsx index af15112f..3f4adc48 100644 --- a/web/components/events-shim/EventsShimTry.tsx +++ b/web/components/events-shim/EventsShimTry.tsx @@ -3,6 +3,19 @@ import Link from 'next/link'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { + adoptStored, + fragmentFor, + LEGACY_STORAGE_KEY, + restore, + serializeStore, + STORAGE_KEY, + withInbox, + withoutInbox, + type AgentId, + type Session, + type Store, +} from '../../lib/events-shim-inboxes'; import { teamsCloudUrl } from '../../lib/teams-cloud'; import { CodeBlock, CopyButton } from './CodeBlock'; import { KeepInbox } from './KeepInbox'; @@ -10,18 +23,11 @@ import s from './events-shim.module.css'; /** Mounted by Agent Relay Cloud; see `@agent-relay/events-shim`. */ const API = teamsCloudUrl('/api/v1/events-shim'); -const STORAGE_KEY = 'agent-relay-events-shim'; const POLL_MS = 3000; type Mode = 'open' | 'github' | 'stripe' | 'linear' | 'bearer'; type SecretMode = Exclude; -interface Session { - /** Capability for the feed, rotate and secrets. Kept only in this browser and the page link. */ - manageToken: string; - mcpUrl: string; -} - interface FeedEvent { id: string; seq: number; @@ -37,7 +43,14 @@ interface FeedEvent { interface Feed { webhook_urls: Record; secrets_set: Record; - agent: { connected: boolean; last_seen_at: string | null; wake: 'linked' | 'broken' | 'none'; wake_error: string | null }; + agent: { + connected: boolean; + last_seen_at: string | null; + wake: 'linked' | 'broken' | 'none'; + wake_error: string | null; + /** The Agent Relay agent the wake link targets. Newer hosts only; absent or null otherwise. */ + wake_agent?: string | null; + }; expires_at: string; events: FeedEvent[]; } @@ -54,36 +67,65 @@ const relayfileListen = (webhookUrl: string) => const setupCommand = (flag: string) => (url: string) => `npx @agent-relay/events-shim@latest setup ${shellQuote(url)} --${flag}`; +const NEWEST_OPEN = (label: string) => `This inbox wakes one ${label} session: the newest open one.`; + const AGENTS = [ { id: 'claude-code', label: 'Claude Code', note: 'Adds the MCP server, installs the webhooks skill and remembers the inbox.', + oneSession: + 'This inbox wakes one Claude Code session: the one started most recently. An older session takes the posts back when you tell it “watch for webhooks”.', command: setupCommand('claude'), wakes: true, listener: true, }, - { id: 'codex', label: 'Codex', note: 'Adds the MCP server and the webhooks skill.', command: setupCommand('codex'), wakes: true, listener: false }, - { id: 'cursor', label: 'Cursor', note: 'Adds the server to ~/.cursor/mcp.json.', command: setupCommand('cursor'), wakes: false }, - { id: 'opencode', label: 'opencode', note: 'Adds the server to opencode.json.', command: setupCommand('opencode'), wakes: true, listener: false }, + { + id: 'codex', + label: 'Codex', + note: 'Adds the MCP server and the webhooks skill.', + oneSession: NEWEST_OPEN('Codex'), + command: setupCommand('codex'), + wakes: true, + listener: false, + }, + { + id: 'cursor', + label: 'Cursor', + note: 'Adds the server to ~/.cursor/mcp.json.', + oneSession: 'This inbox wakes one Cursor session.', + command: setupCommand('cursor'), + wakes: false, + }, + { + id: 'opencode', + label: 'opencode', + note: 'Adds the server to opencode.json.', + oneSession: NEWEST_OPEN('opencode'), + command: setupCommand('opencode'), + wakes: true, + listener: false, + }, { id: 'muse', label: 'Muse', note: 'Adds the MCP server. Muse sessions are not woken yet; the agent reads posts when you ask.', + oneSession: 'This inbox is for one Muse session.', command: setupCommand('muse'), wakes: false, }, - { id: 'gemini', label: 'Gemini CLI', command: setupCommand('gemini'), wakes: false }, - { id: 'grok', label: 'Grok', command: setupCommand('grok'), wakes: true, listener: false }, - { id: 'devin', label: 'Devin', command: setupCommand('devin'), wakes: true, listener: false }, + { id: 'gemini', label: 'Gemini CLI', oneSession: 'This inbox wakes one Gemini CLI session.', command: setupCommand('gemini'), wakes: false }, + { id: 'grok', label: 'Grok', oneSession: NEWEST_OPEN('Grok'), command: setupCommand('grok'), wakes: true, listener: false }, + { id: 'devin', label: 'Devin', oneSession: NEWEST_OPEN('Devin'), command: setupCommand('devin'), wakes: true, listener: false }, { id: 'other', label: 'Any MCP client', note: 'Streamable HTTP, no authentication', + oneSession: 'This inbox is for one MCP client and one session. Give each other client its own inbox.', command: (url: string) => url, wakes: false, }, -] as const; +] as const satisfies readonly { id: AgentId; label: string; oneSession: string; [key: string]: unknown }[]; const MODES: { id: Mode; label: string; help: string }[] = [ { id: 'open', label: 'Open', help: 'Anyone with the URL can post. Limits still apply.' }, @@ -93,63 +135,50 @@ const MODES: { id: Mode; label: string; help: string }[] = [ { id: 'bearer', label: 'Bearer token', help: 'Senders include Authorization: Bearer . Generate one below; it is shown once.' }, ]; -const TOKEN = /^[A-Za-z0-9_-]{43}$/; - -/** The MCP URL this page's API issues: `/t/esm_<43>/mcp` on the API's own origin. */ -function isOurMcpUrl(value: string): boolean { - try { - const url = new URL(value); - const api = new URL(API, window.location.origin); - const prefix = `${api.pathname.replace(/\/$/, '')}/t/esm_`; - if (url.origin !== api.origin || url.search || url.hash || url.username || url.password) return false; - if (!url.pathname.startsWith(prefix) || !url.pathname.endsWith('/mcp')) return false; - return TOKEN.test(url.pathname.slice(prefix.length, -'/mcp'.length)); - } catch { - return false; - } -} - -function isSession(value: unknown): value is Session { - if (!value || typeof value !== 'object') return false; - const { manageToken, mcpUrl } = value as Record; - return ( - typeof manageToken === 'string' && - manageToken.startsWith('esk_') && - TOKEN.test(manageToken.slice(4)) && - typeof mcpUrl === 'string' && - isOurMcpUrl(mcpUrl) - ); -} +/** The API as an absolute URL, so issued MCP URLs can be checked against its origin and path. */ +const apiBase = () => new URL(API, window.location.origin).toString(); /** One shell word, whatever it contains. */ function shellQuote(value: string): string { return `'${value.replace(/'/g, `'\\''`)}'`; } -function readSession(): Session | null { +function readStore(): Store { + let stored: string | null = null; + let legacy: string | null = null; try { - const hash = new URLSearchParams(window.location.hash.slice(1)); - // A page link can be crafted by anyone: accept only what this page's API issues, - // so a link cannot make the page show someone else's command to copy and run. - const fromHash = { manageToken: hash.get('k'), mcpUrl: hash.get('m') }; - if (isSession(fromHash)) return fromHash; - const saved: unknown = JSON.parse(localStorage.getItem(STORAGE_KEY) || 'null'); - if (isSession(saved)) return saved; + stored = localStorage.getItem(STORAGE_KEY); + legacy = localStorage.getItem(LEGACY_STORAGE_KEY); } catch { /* Storage can be unavailable; the page still works for this tab. */ } - return null; + const { store, legacyMigrated } = restore({ hash: window.location.hash, stored, legacy, apiBase: apiBase() }); + try { + localStorage.setItem(STORAGE_KEY, serializeStore(store)); + if (legacyMigrated) localStorage.removeItem(LEGACY_STORAGE_KEY); + } catch { + /* Best effort. */ + } + return store; +} + +function readStored(): string | null { + try { + return localStorage.getItem(STORAGE_KEY); + } catch { + return null; + } } -function saveSession(session: Session | null) { +function writeStore(store: Store) { try { - if (session) localStorage.setItem(STORAGE_KEY, JSON.stringify(session)); - else localStorage.removeItem(STORAGE_KEY); + localStorage.setItem(STORAGE_KEY, serializeStore(store)); } catch { /* Best effort. */ } + // Keep the page link (fragment) on the selected tab's inbox, so copying or bookmarking the address opens it there. const url = new URL(window.location.href); - url.hash = session ? new URLSearchParams({ k: session.manageToken, m: session.mcpUrl }).toString() : ''; + url.hash = fragmentFor(store.selected, store.inboxes[store.selected] ?? null); window.history.replaceState(null, '', url.toString()); } @@ -177,48 +206,74 @@ async function api(path: string, init: RequestInit & { token?: string } = {}): P } export function EventsShimTry() { - const [session, setSession] = useState(null); - const [feed, setFeed] = useState(null); - const [ready, setReady] = useState(false); + const [store, setStore] = useState(null); + /** The feed for one inbox, tagged with its manage token so another tab's feed is never shown. */ + const [loaded, setLoaded] = useState<{ token: string; feed: Feed } | null>(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); - const [agentId, setAgentId] = useState<(typeof AGENTS)[number]['id']>('claude-code'); const [mode, setMode] = useState('open'); const [secretDraft, setSecretDraft] = useState(''); - const [bearerToken, setBearerToken] = useState(null); + /** A generated bearer token, tagged with its inbox so it never shows under another tab's inbox. */ + const [generated, setGenerated] = useState<{ token: string; secret: string } | null>(null); const [expanded, setExpanded] = useState(null); const timer = useRef | null>(null); useEffect(() => { - const restored = readSession(); - // Keep the page link (fragment) in step with an inbox restored from this browser, - // so copying or bookmarking the address still opens it. - if (restored) saveSession(restored); - setSession(restored); - setReady(true); + setStore(readStore()); + }, []); + + // Persist and keep the page link in step after every change (not inside a state updater: + // Next.js routes `history.replaceState`, which must not run while React renders). + useEffect(() => { + if (store) writeStore(store); + }, [store]); + + // Every change starts from the latest stored inboxes, so another window's new inbox is never written over. + const update = useCallback((change: (current: Store) => Store) => { + setStore((current) => (current ? change(adoptStored(current, readStored(), apiBase())) : current)); + }, []); + + // Pick up inboxes another window created or cleared. + useEffect(() => { + const onStorage = (event: StorageEvent) => { + if (event.key !== STORAGE_KEY) return; + setStore((current) => (current ? adoptStored(current, event.newValue, apiBase()) : current)); + }; + window.addEventListener('storage', onStorage); + return () => window.removeEventListener('storage', onStorage); }, []); + const ready = store !== null; + const agentId: AgentId = store?.selected ?? 'claude-code'; + const session: Session | null = store?.inboxes[agentId] ?? null; + const feed = session && loaded?.token === session.manageToken ? loaded.feed : null; + const bearerToken = session && generated?.token === session.manageToken ? generated.secret : null; + /** The selected inbox right now, for completions that finish after a tab switch. */ + const selectedToken = useRef(null); + selectedToken.current = session?.manageToken ?? null; + const load = useCallback( - async (current: Session, signal: AbortSignal) => { + async (owner: AgentId, current: Session, signal: AbortSignal) => { const response = await api('/shims/current', { token: current.manageToken, signal }); // A late answer for an inbox this page has since left must not touch the current one. if (signal.aborted) return; if (response.status === 404) { - saveSession(null); - setSession(null); - setFeed(null); + // Only this tab's inbox expired; the other agents keep theirs. + update((currentStore) => withoutInbox(currentStore, owner, current.manageToken)); + setLoaded(null); setError('That webhook expired or the link was replaced. Create a new one.'); return; } if (!response.ok) throw new Error(`Feed unavailable (HTTP ${response.status}).`); const next = (await response.json()) as Feed; if (signal.aborted) return; - setFeed(next); + setLoaded({ token: current.manageToken, feed: next }); setError(null); }, - [], + [update], ); + // Polls only the selected tab's inbox. useEffect(() => { if (!session) return; let stopped = false; @@ -226,7 +281,7 @@ export function EventsShimTry() { const tick = async () => { if (document.visibilityState === 'visible') { try { - await load(session, controller.signal); + await load(agentId, session, controller.signal); } catch (failure) { if (!controller.signal.aborted) setError(failure instanceof Error ? failure.message : 'Feed unavailable.'); } @@ -239,9 +294,21 @@ export function EventsShimTry() { controller.abort(); if (timer.current) clearTimeout(timer.current); }; - }, [session, load]); + }, [agentId, session, load]); + + function selectAgent(next: AgentId) { + if (next === agentId) return; + update((current) => ({ ...current, selected: next })); + // Per-inbox UI state belongs to the inbox being left. + setError(null); + setSecretDraft(''); + setGenerated(null); + setExpanded(null); + } - async function create() { + // Inboxes are created one tab at a time, on click, never when a tab is opened: the API allows + // only 10 new inboxes per hour per IP, so clicking through every agent tab must not spend them. + async function create(owner: AgentId) { setBusy(true); setError(null); try { @@ -250,8 +317,7 @@ export function EventsShimTry() { if (!response.ok) throw new Error('Could not create a webhook. Please try again.'); const created = (await response.json()) as { manage_token: string; mcp_url: string }; const next = { manageToken: created.manage_token, mcpUrl: created.mcp_url }; - saveSession(next); - setSession(next); + update((current) => withInbox(current, owner, next)); } catch (failure) { setError(failure instanceof Error ? failure.message : 'Could not create a webhook.'); } finally { @@ -261,11 +327,12 @@ export function EventsShimTry() { async function rotate() { if (!session || !window.confirm('Replace the webhook URL? The old URL stops working immediately. Your agent keeps watching.')) return; + const current = session; setBusy(true); try { - const response = await api('/shims/current/rotate', { method: 'POST', token: session.manageToken }); + const response = await api('/shims/current/rotate', { method: 'POST', token: current.manageToken }); if (!response.ok) throw new Error('Could not replace the URL.'); - setFeed((await response.json()) as Feed); + setLoaded({ token: current.manageToken, feed: (await response.json()) as Feed }); } catch (failure) { setError(failure instanceof Error ? failure.message : 'Could not replace the URL.'); } finally { @@ -275,18 +342,21 @@ export function EventsShimTry() { async function saveSecret(target: SecretMode, value: string | null | undefined) { if (!session) return; + const owner = agentId; + const current = session; setBusy(true); try { const response = await api(`/shims/current/secrets/${target}`, { method: 'PUT', - token: session.manageToken, + token: current.manageToken, body: JSON.stringify(value === undefined ? {} : { secret: value }), }); const body = (await response.json()) as { secret?: string; message?: string }; if (!response.ok) throw new Error(body.message || 'Could not save the secret.'); - if (body.secret) setBearerToken(body.secret); - setSecretDraft(''); - await load(session, new AbortController().signal); + if (body.secret) setGenerated({ token: current.manageToken, secret: body.secret }); + // A late completion must not wipe a draft typed for another tab's inbox. + if (selectedToken.current === current.manageToken) setSecretDraft(''); + await load(owner, current, new AbortController().signal); } catch (failure) { setError(failure instanceof Error ? failure.message : 'Could not save the secret.'); } finally { @@ -311,7 +381,13 @@ export function EventsShimTry() { : !feed.agent.connected ? { tone: 'idle', text: 'No agent connected yet' } : feed.agent.wake === 'linked' - ? { tone: 'live', text: 'Agent connected · posts wake it, even when idle' } + ? { + tone: 'live', + // Name the session only when the host says which one; otherwise don't claim a specific one. + text: feed.agent.wake_agent + ? `Agent connected · posts wake ${feed.agent.wake_agent}, even when idle` + : 'Agent connected · posts wake its linked session, even when idle', + } : feed.agent.wake === 'broken' ? { tone: 'warn', text: `Agent connected · wake link stopped working${feed.agent.wake_error ? ` (${feed.agent.wake_error})` : ''}` } : { tone: 'wait', text: 'Agent connected · it reads posts with wait_for_webhook' }; @@ -324,95 +400,116 @@ export function EventsShimTry() { Connect your agent, then post.

- One MCP server, one webhook URL. Every post is delivered into your agent's session through Agent Relay, so an{' '} - idle agent wakes up and acts on it. No polling loop, no restarts. + Pick your agent, add its MCP server and post to its webhook URL. Every post is delivered into that agent's + session through Agent Relay, so an idle agent wakes up and acts on it. No polling loop, no restarts.

Building your own MCP? Use our API to wake agents with your own messages →

- {ready && !session && ( -
- -

No sign-up. The page link becomes yours: anyone holding it can connect an agent and read posts.

-
- )} - {error &&

{error}

} - {session && } - {session && ( - <> -
-

- i Connect your agent -

-
- {AGENTS.map((candidate) => ( - - ))} + {ready && ( +
+

+ i Connect your agent +

+
+ {AGENTS.map((candidate) => ( + + ))} +
+

+ {agent.oneSession} Each agent here has its own inbox and webhook URL. To wake two agents, set each + one up from its own tab. +

+ {!session ? ( +
+ +

+ No sign-up. The page link becomes yours: anyone holding it can connect an agent and read posts. +

+ {error && ( +

+ {error} +

+ )}
- {'note' in agent && agent.note &&

{agent.note}

} - -

- Then ask your agent: Watch for webhooks and tell me when one arrives. -

- {agent.id === 'codex' && ( -

- Codex: the session has to be started. Open Codex and send it that message first. A Codex session can be - woken only once it has started; a new window with no message yet cannot be reached. + ) : ( + <> + {'note' in agent && agent.note &&

{agent.note}

} + +

+ Then ask your agent: Watch for webhooks and tell me when one arrives.

- )} -
    - {agent.wakes ? ( - <> -
  • - With Agent Relay running, the agent links its own session (one command it runs itself) and - each post is injected into the session, waking it within seconds, even when idle. -
  • - {'listener' in agent && agent.listener ? ( + {agent.id === 'codex' && ( +

    + Codex: the session has to be started. Open Codex and send it that message first. A Codex session can be + woken only once it has started; a new window with no message yet cannot be reached. +

    + )} +
      + {agent.wakes ? ( + <>
    • - Without Agent Relay, the agent runs npx @agent-relay/events-shim listen in the background. It exits - with the next post, which wakes the idle agent, and the agent starts it again. Nothing else to install. + With Agent Relay running, the agent links its own session (one command it runs + itself) and each post is injected into that session, waking it within seconds, even when idle.
    • - ) : ( + {'listener' in agent && agent.listener ? ( +
    • + Without Agent Relay, the agent runs npx @agent-relay/events-shim listen in the background. It + exits with the next post, which wakes the idle agent, and the agent starts it again. Nothing else to install. +
    • + ) : ( +
    • + Without the Agent Relay app, setup runs Agent Relay's core for this client itself, so its newest open + session is still woken by each post. +
    • + )} + + ) : ( + <> +
    • The agent keeps a background wait_for_webhook call open; it returns as soon as a post arrives.
    • - Without the Agent Relay app, setup runs Agent Relay's core for this client itself, so its newest - open session is still woken by each post. + Clients that can't run tools in the background see new posts on their next get_webhook_events{' '} + call.
    • - )} - - ) : ( - <> -
    • The agent keeps a background wait_for_webhook call open; it returns as soon as a post arrives.
    • -
    • - Clients that can't run tools in the background see new posts on their next get_webhook_events call. -
    • - + + )} +
    • + Posts to the open URL reach the agent marked as untrusted data, never as instructions. A{' '} + text/plain post to a verified URL (bearer, GitHub, Stripe, Linear) is delivered verbatim, so only + senders holding that secret can choose the agent's words. A signed provider URL wraps a JSON body as data + whatever its header says. +
    • +
    + {status &&

    {status.text}

    } + {error && ( +

    + {error} +

    )} -
  • - Posts to the open URL reach the agent marked as untrusted data, never as instructions. A{' '} - text/plain post to a verified URL (bearer, GitHub, Stripe, Linear) is delivered verbatim, so only - senders holding that secret can choose the agent's words. A signed provider URL wraps a JSON body as - data whatever its header says. -
  • -
- {status &&

{status.text}

} -
+ + )} +
+ )} + {session && } + {session && ( + <>

- ii Post to your webhook URL + ii Post to {agent.label}'s webhook URL

{MODES.map((candidate) => ( @@ -536,8 +633,8 @@ export function EventsShimTry() {

GitHub, Slack, Linear and more, through relayfile

- Wake the agent on provider events without setting up each provider's webhook or secret. Connect the - provider once (a browser opens to sign in), then forward its events into this inbox: + Wake {agent.label} on provider events without setting up each provider's webhook or secret. Connect the + provider once (a browser opens to sign in), then forward its events into this agent's inbox:

')} /> diff --git a/web/components/events-shim/KeepInbox.tsx b/web/components/events-shim/KeepInbox.tsx index b56c23e4..008103cc 100644 --- a/web/components/events-shim/KeepInbox.tsx +++ b/web/components/events-shim/KeepInbox.tsx @@ -71,7 +71,13 @@ export function KeepInbox({ manageToken }: { manageToken: string }) { useEffect(() => { if (autoTried.current) return; autoTried.current = true; - if (new URLSearchParams(window.location.search).get('keep') === '1') void keep(); + const url = new URL(window.location.href); + if (url.searchParams.get('keep') !== '1') return; + // Keep once, for the inbox open on return from sign-up. Each agent tab has its own inbox + // (and its own KeepInbox), so drop the flag before another tab's inbox could be kept too. + url.searchParams.delete('keep'); + window.history.replaceState(null, '', url.toString()); + void keep(); }, [keep]); return ( diff --git a/web/components/events-shim/events-shim.module.css b/web/components/events-shim/events-shim.module.css index 2b640aba..f55d2f9b 100644 --- a/web/components/events-shim/events-shim.module.css +++ b/web/components/events-shim/events-shim.module.css @@ -476,3 +476,27 @@ background: var(--primary-bg, var(--primary)); color: var(--primary-fg, #fff); } + +.oneInbox { + margin: 0 0 1rem; + padding: 0.7rem 0.9rem; + border-left: 3px solid var(--primary); + border-radius: 0.4rem; + background: color-mix(in srgb, var(--primary) 7%, transparent); + color: var(--fg-muted); + font-size: 0.86rem; + line-height: 1.6; +} + +.oneInbox strong { + color: var(--fg); +} + +.startTab { + margin-top: 0.4rem; +} + +.startTab .helper, +.startTab .error { + margin: 0.8rem 0 0; +} diff --git a/web/lib/events-shim-inboxes.ts b/web/lib/events-shim-inboxes.ts new file mode 100644 index 00000000..5e4f4846 --- /dev/null +++ b/web/lib/events-shim-inboxes.ts @@ -0,0 +1,205 @@ +/** + * Per-agent webhook inboxes for the /mcp-events-shim page. + * + * One inbox wakes exactly one agent session, so the page keeps a separate inbox + * for each agent tab instead of showing one inbox's command under every tab. + * Everything here is pure (no `window`, no storage) so it can be unit-tested; + * the component reads and writes localStorage and the page fragment around it. + */ + +export const AGENT_IDS = ['claude-code', 'codex', 'cursor', 'opencode', 'muse', 'gemini', 'grok', 'devin', 'other'] as const; +export type AgentId = (typeof AGENT_IDS)[number]; +export const DEFAULT_AGENT: AgentId = 'claude-code'; + +/** The single inbox the page kept before inboxes were per agent. Read once, then migrated. */ +export const LEGACY_STORAGE_KEY = 'agent-relay-events-shim'; +/** `{ version: 1, selected, inboxes: { [agentId]: Session } }`. */ +export const STORAGE_KEY = 'agent-relay-events-shim-inboxes'; + +export interface Session { + /** Capability for the feed, rotate and secrets. Kept only in this browser and the page link. */ + manageToken: string; + mcpUrl: string; +} + +export type Inboxes = Partial>; + +export interface Store { + selected: AgentId; + inboxes: Inboxes; +} + +const TOKEN = /^[A-Za-z0-9_-]{43}$/; + +export function isAgentId(value: unknown): value is AgentId { + return typeof value === 'string' && (AGENT_IDS as readonly string[]).includes(value); +} + +/** + * The MCP URL this page's API issues: `/t/esm_<43>/mcp` on the API's own origin. + * + * @param apiBase - The events-shim API as an absolute URL (resolved against the page origin). + */ +export function isOurMcpUrl(value: string, apiBase: string): boolean { + try { + const url = new URL(value); + const api = new URL(apiBase); + const prefix = `${api.pathname.replace(/\/$/, '')}/t/esm_`; + if (url.origin !== api.origin || url.search || url.hash || url.username || url.password) return false; + if (!url.pathname.startsWith(prefix) || !url.pathname.endsWith('/mcp')) return false; + return TOKEN.test(url.pathname.slice(prefix.length, -'/mcp'.length)); + } catch { + return false; + } +} + +export function isSession(value: unknown, apiBase: string): value is Session { + if (!value || typeof value !== 'object') return false; + const { manageToken, mcpUrl } = value as Record; + return ( + typeof manageToken === 'string' && + manageToken.startsWith('esk_') && + TOKEN.test(manageToken.slice(4)) && + typeof mcpUrl === 'string' && + isOurMcpUrl(mcpUrl, apiBase) + ); +} + +/** Only the two fields, so nothing else from storage or a link rides along. */ +const pick = (session: Session): Session => ({ manageToken: session.manageToken, mcpUrl: session.mcpUrl }); + +/** + * Reads the page link fragment `#k=&m=&a=`. + * + * A page link can be crafted by anyone: only an inbox this page's API issues is + * accepted, so a link cannot make the page show someone else's command to copy + * and run. An unknown or missing `a` is ignored (old links open on the default tab). + */ +export function parseFragment(hash: string, apiBase: string): { session: Session | null; agentId: AgentId | null } { + const params = new URLSearchParams(hash.replace(/^#/, '')); + const candidate = { manageToken: params.get('k'), mcpUrl: params.get('m') }; + const agent = params.get('a'); + return { + session: isSession(candidate, apiBase) ? pick(candidate) : null, + agentId: isAgentId(agent) ? agent : null, + }; +} + +/** The fragment for the selected tab: its inbox (if any) and the tab itself. */ +export function fragmentFor(agentId: AgentId, session: Session | null): string { + const params = new URLSearchParams(); + if (session) { + params.set('k', session.manageToken); + params.set('m', session.mcpUrl); + } + params.set('a', agentId); + return params.toString(); +} + +/** Parses the stored map, dropping anything malformed instead of failing the page. */ +export function parseStore(raw: string | null, apiBase: string): Store { + const empty: Store = { selected: DEFAULT_AGENT, inboxes: {} }; + if (!raw) return empty; + let value: unknown; + try { + value = JSON.parse(raw); + } catch { + return empty; + } + if (!value || typeof value !== 'object') return empty; + const { selected, inboxes } = value as Record; + const store: Store = { selected: isAgentId(selected) ? selected : DEFAULT_AGENT, inboxes: {} }; + if (inboxes && typeof inboxes === 'object') { + for (const [agentId, session] of Object.entries(inboxes as Record)) { + if (isAgentId(agentId) && isSession(session, apiBase)) store.inboxes[agentId] = pick(session); + } + } + return store; +} + +export function serializeStore(store: Store): string { + return JSON.stringify({ version: 1, selected: store.selected, inboxes: store.inboxes }); +} + +/** + * Puts `session` under `agentId` (or clears that tab with `null`). An inbox + * belongs to one tab only: the same inbox under a second tab would read as two + * agents sharing it, which is exactly the setup that leaves one of them unwoken. + */ +export function withInbox(store: Store, agentId: AgentId, session: Session | null): Store { + const inboxes: Inboxes = {}; + for (const id of AGENT_IDS) { + const current = store.inboxes[id]; + if (!current || id === agentId) continue; + if (session && current.manageToken === session.manageToken) continue; + inboxes[id] = current; + } + if (session) inboxes[agentId] = pick(session); + return { ...store, inboxes }; +} + +/** + * Clears `agentId`'s inbox only if it is still `manageToken`, so a late 404 for + * an inbox the tab has since replaced cannot clear the new one. + */ +export function withoutInbox(store: Store, agentId: AgentId, manageToken: string): Store { + return store.inboxes[agentId]?.manageToken === manageToken ? withInbox(store, agentId, null) : store; +} + +export interface Restored { + store: Store; + /** True when the legacy single inbox was moved into the map and its key can be removed. */ + legacyMigrated: boolean; +} + +/** + * Works out the page's inboxes and selected tab on load. + * + * - The tab comes from the link's `a`, else the tab last selected in this browser, else the default. + * - A valid inbox in the link opens on that tab (a shared or bookmarked link wins over storage). + * - The legacy single inbox moves under the tab that is active now, so existing users keep it; + * if that tab already holds another inbox it goes to the default tab when that is free, else stays put. + */ +export function restore(input: { hash: string; stored: string | null; legacy: string | null; apiBase: string }): Restored { + const { apiBase } = input; + const fromLink = parseFragment(input.hash, apiBase); + let store = parseStore(input.stored, apiBase); + const selected = fromLink.agentId ?? (fromLink.session ? DEFAULT_AGENT : store.selected); + store = { ...store, selected }; + + // The link's inbox takes the selected tab first; the legacy inbox is placed around it afterwards, + // and counts as migrated only if the final map still holds it. + if (fromLink.session) store = withInbox(store, selected, fromLink.session); + + let legacy: unknown = null; + try { + legacy = JSON.parse(input.legacy || 'null'); + } catch { + legacy = null; + } + if (input.legacy === null) return { store, legacyMigrated: false }; + // Unreadable leftovers: nothing to keep. + if (!isSession(legacy, apiBase)) return { store, legacyMigrated: true }; + const kept: Session = legacy; + const held = (current: Store) => Object.values(current.inboxes).some((session) => session?.manageToken === kept.manageToken); + if (!held(store)) { + const target = [selected, DEFAULT_AGENT].find((id) => !store.inboxes[id]); + if (target) store = withInbox(store, target, kept); + } + return { store, legacyMigrated: held(store) }; +} + +/** + * Takes the inboxes from the stored map (shared by every window on this origin) and keeps this + * window's selected tab. Changes are applied on top of this, so a window opened earlier cannot + * write back a stale map and erase an inbox another window created or cleared since. + * + * @param raw - The stored map, or `null` when there is none or storage is unavailable (keeps `current`). + */ +export function adoptStored(current: Store, raw: string | null, apiBase: string): Store { + if (raw === null) return current; + const inboxes = parseStore(raw, apiBase).inboxes; + // Unchanged: return the same object, so windows with different selected tabs don't keep rewriting each other. + const same = AGENT_IDS.every((id) => current.inboxes[id]?.manageToken === inboxes[id]?.manageToken && current.inboxes[id]?.mcpUrl === inboxes[id]?.mcpUrl); + return same ? current : { selected: current.selected, inboxes }; +} diff --git a/web/lib/test/events-shim-inboxes.test.ts b/web/lib/test/events-shim-inboxes.test.ts new file mode 100644 index 00000000..259becaa --- /dev/null +++ b/web/lib/test/events-shim-inboxes.test.ts @@ -0,0 +1,184 @@ +import { describe, expect, it } from 'vitest'; + +import { + adoptStored, + fragmentFor, + isSession, + parseFragment, + parseStore, + restore, + serializeStore, + withInbox, + withoutInbox, + type Session, + type Store, +} from '../events-shim-inboxes'; + +// Obviously fake values: an API base like the page resolves, and tokens of the issued shape. +const API = 'https://example.test/cloud/api/v1/events-shim'; +const fake = (char: string): Session => ({ + manageToken: `esk_${char.repeat(43)}`, + mcpUrl: `${API}/t/esm_${char.repeat(43)}/mcp`, +}); +const A = fake('a'); +const B = fake('b'); +const C = fake('c'); + +const hashOf = (session: Session | null, agent?: string) => { + const params = new URLSearchParams(); + if (session) { + params.set('k', session.manageToken); + params.set('m', session.mcpUrl); + } + if (agent) params.set('a', agent); + return `#${params.toString()}`; +}; + +const stored = (store: Store) => serializeStore(store); + +describe('events-shim inbox validation', () => { + it('accepts only inboxes this page’s API issues', () => { + expect(isSession(A, API)).toBe(true); + expect(isSession({ ...A, mcpUrl: A.mcpUrl.replace('example.test', 'evil.test') }, API)).toBe(false); + expect(isSession({ ...A, mcpUrl: `${A.mcpUrl}?x=1` }, API)).toBe(false); + expect(isSession({ ...A, mcpUrl: A.mcpUrl.replace('/cloud/', '/other/') }, API)).toBe(false); + expect(isSession({ ...A, manageToken: 'esk_short' }, API)).toBe(false); + expect(isSession({ ...A, manageToken: A.manageToken.replace('esk_', 'xsk_') }, API)).toBe(false); + expect(isSession(null, API)).toBe(false); + }); +}); + +describe('page link fragment', () => { + it('round-trips the inbox and the tab', () => { + expect(parseFragment(`#${fragmentFor('codex', A)}`, API)).toEqual({ session: A, agentId: 'codex' }); + expect(parseFragment(`#${fragmentFor('cursor', null)}`, API)).toEqual({ session: null, agentId: 'cursor' }); + }); + + it('ignores a crafted inbox and an unknown tab', () => { + const crafted = { manageToken: A.manageToken, mcpUrl: 'https://evil.test/t/esm_x/mcp' }; + expect(parseFragment(hashOf(crafted, 'codex'), API)).toEqual({ session: null, agentId: 'codex' }); + expect(parseFragment(hashOf(A, 'not-an-agent'), API)).toEqual({ session: A, agentId: null }); + expect(parseFragment('', API)).toEqual({ session: null, agentId: null }); + }); +}); + +describe('stored inboxes', () => { + it('drops malformed entries and unknown tabs', () => { + const raw = JSON.stringify({ + version: 1, + selected: 'codex', + inboxes: { codex: A, nope: B, cursor: { manageToken: 'esk_x', mcpUrl: 'x' }, grok: { ...C, extra: 'ignored' } }, + }); + expect(parseStore(raw, API)).toEqual({ selected: 'codex', inboxes: { codex: A, grok: C } }); + expect(parseStore('not json', API)).toEqual({ selected: 'claude-code', inboxes: {} }); + expect(parseStore(JSON.stringify({ selected: 'nope' }), API)).toEqual({ selected: 'claude-code', inboxes: {} }); + }); + + it('keeps one inbox per tab, and an inbox under one tab only', () => { + let store: Store = { selected: 'claude-code', inboxes: {} }; + store = withInbox(store, 'claude-code', A); + store = withInbox(store, 'codex', B); + expect(store.inboxes).toEqual({ 'claude-code': A, codex: B }); + // Same inbox placed under another tab moves there rather than being shared. + store = withInbox(store, 'cursor', A); + expect(store.inboxes).toEqual({ codex: B, cursor: A }); + }); + + it('clears only the expired tab, and only if it still holds that inbox', () => { + const store: Store = { selected: 'codex', inboxes: { 'claude-code': A, codex: B } }; + expect(withoutInbox(store, 'codex', B.manageToken).inboxes).toEqual({ 'claude-code': A }); + expect(withoutInbox(store, 'codex', C.manageToken)).toBe(store); + }); +}); + +describe('restoring the page', () => { + it('starts on the default tab with nothing', () => { + expect(restore({ hash: '', stored: null, legacy: null, apiBase: API })).toEqual({ + store: { selected: 'claude-code', inboxes: {} }, + legacyMigrated: false, + }); + }); + + it('migrates the legacy single inbox under the default tab', () => { + const result = restore({ hash: '', stored: null, legacy: JSON.stringify(A), apiBase: API }); + expect(result).toEqual({ store: { selected: 'claude-code', inboxes: { 'claude-code': A } }, legacyMigrated: true }); + }); + + it('migrates the legacy inbox under the tab active on restore', () => { + const result = restore({ hash: hashOf(null, 'codex'), stored: null, legacy: JSON.stringify(A), apiBase: API }); + expect(result.store).toEqual({ selected: 'codex', inboxes: { codex: A } }); + expect(result.legacyMigrated).toBe(true); + }); + + it('opens an old link (no tab) and its legacy copy as one inbox on the default tab', () => { + const result = restore({ hash: hashOf(A), stored: null, legacy: JSON.stringify(A), apiBase: API }); + expect(result.store).toEqual({ selected: 'claude-code', inboxes: { 'claude-code': A } }); + expect(result.legacyMigrated).toBe(true); + }); + + it('does not let a link overwrite a different legacy inbox', () => { + const result = restore({ hash: hashOf(B, 'codex'), stored: null, legacy: JSON.stringify(A), apiBase: API }); + expect(result.store).toEqual({ selected: 'codex', inboxes: { codex: B, 'claude-code': A } }); + expect(result.legacyMigrated).toBe(true); + }); + + it('leaves the legacy inbox in place when there is nowhere free to put it', () => { + const existing = stored({ selected: 'claude-code', inboxes: { 'claude-code': B } }); + const result = restore({ hash: '', stored: existing, legacy: JSON.stringify(A), apiBase: API }); + expect(result.store.inboxes).toEqual({ 'claude-code': B }); + expect(result.legacyMigrated).toBe(false); + }); + + it('keeps the legacy key when a link displaces the stored copy of that inbox', () => { + const existing = stored({ selected: 'claude-code', inboxes: { 'claude-code': A } }); + const result = restore({ hash: hashOf(B), stored: existing, legacy: JSON.stringify(A), apiBase: API }); + expect(result.store.inboxes).toEqual({ 'claude-code': B }); + expect(result.legacyMigrated).toBe(false); + }); + + it('moves a displaced legacy inbox to the default tab when that is free', () => { + const existing = stored({ selected: 'codex', inboxes: { codex: A } }); + const result = restore({ hash: hashOf(B, 'codex'), stored: existing, legacy: JSON.stringify(A), apiBase: API }); + expect(result.store.inboxes).toEqual({ codex: B, 'claude-code': A }); + expect(result.legacyMigrated).toBe(true); + }); + + it('drops unreadable legacy data', () => { + expect(restore({ hash: '', stored: null, legacy: '{oops', apiBase: API }).legacyMigrated).toBe(true); + expect(restore({ hash: '', stored: null, legacy: JSON.stringify({ manageToken: 'x' }), apiBase: API }).legacyMigrated).toBe(true); + }); + + it('opens a shared link on its tab, keeping the other tabs’ inboxes', () => { + const existing = stored({ selected: 'claude-code', inboxes: { 'claude-code': A } }); + const result = restore({ hash: hashOf(B, 'codex'), stored: existing, legacy: null, apiBase: API }); + expect(result.store).toEqual({ selected: 'codex', inboxes: { 'claude-code': A, codex: B } }); + }); + + it('reopens the tab last selected in this browser when the link names none', () => { + const existing = stored({ selected: 'grok', inboxes: { grok: C } }); + expect(restore({ hash: '', stored: existing, legacy: null, apiBase: API }).store.selected).toBe('grok'); + }); + + it('never accepts a crafted inbox from the link', () => { + const crafted = { manageToken: A.manageToken, mcpUrl: 'https://evil.test/cloud/api/v1/events-shim/t/esm_x/mcp' }; + const result = restore({ hash: hashOf(crafted, 'codex'), stored: null, legacy: null, apiBase: API }); + expect(result.store).toEqual({ selected: 'codex', inboxes: {} }); + }); +}); + +describe('several windows', () => { + it('starts each change from the stored inboxes and keeps this window’s tab', () => { + const mine: Store = { selected: 'codex', inboxes: { 'claude-code': A } }; + // Another window added a Grok inbox since this one loaded. + const latest = stored({ selected: 'grok', inboxes: { 'claude-code': A, grok: C } }); + const merged = adoptStored(mine, latest, API); + expect(merged).toEqual({ selected: 'codex', inboxes: { 'claude-code': A, grok: C } }); + expect(withInbox(merged, 'codex', B).inboxes).toEqual({ 'claude-code': A, grok: C, codex: B }); + }); + + it('keeps the same object when nothing changed, and this window’s map when storage is unavailable', () => { + const mine: Store = { selected: 'codex', inboxes: { 'claude-code': A } }; + expect(adoptStored(mine, stored({ selected: 'grok', inboxes: { 'claude-code': A } }), API)).toBe(mine); + expect(adoptStored(mine, null, API)).toBe(mine); + }); +});