Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(ui): dashboard client works from any host with a Bearer token
Salman Qureshi88b62fb68c2d
diff --git a/ui/src/components/bots/useBotEvents.ts b/ui/src/components/bots/useBotEvents.tsindex 5054c846..fbd392e1 100644--- a/ui/src/components/bots/useBotEvents.ts+++ b/ui/src/components/bots/useBotEvents.ts@@ -1,10 +1,11 @@import { useEffect, useState, useRef } from "react";+import { createEventStream, type EventStream } from "@/lib/sse";/**- * Live fleet feed — one EventSource per mounted cockpit. Rides the same+ * Live fleet feed — one event stream per mounted cockpit. Rides the same* in-process activity bus as the CLI's bot-thread live region, so what the- * dashboard shows is what the bot is doing right now. EventSource reconnects- * natively; components keep their periodic roster poll as the fallback.+ * dashboard shows is what the bot is doing right now. The stream reconnects+ * by itself; components keep their periodic roster poll as the fallback.*/export interface BotEventState {/** botId → current activity label ("read_file …","fetch_url …"). */@@ -20,10 +21,10 @@ export function useBotEvents(): BotEventState {lastDelivery: null,connected: false,});- const esRef = useRef<EventSource | null>(null);+ const esRef = useRef<EventStream | null>(null);useEffect(() => {- const es = new EventSource(`${window.location.origin}/api/bots/events`);+ const es = createEventStream("/api/bots/events");esRef.current = es;es.addEventListener("bot_activity", (e) => {diff --git a/ui/src/components/layout/Sidebar.tsx b/ui/src/components/layout/Sidebar.tsxindex 70360bd4..5ff03a31 100644--- a/ui/src/components/layout/Sidebar.tsx+++ b/ui/src/components/layout/Sidebar.tsx@@ -1,5 +1,6 @@import { NavLink, useLocation } from "react-router-dom";import { cn } from "@/lib/utils";+import api from "@/lib/api";import { useThemeStore } from "@/stores/theme";import { ThemeToggle } from "./ThemeToggle";import {@@ -246,7 +247,7 @@ export function Sidebar({ open, onToggle }: SidebarProps) {{(() => {const btn = (<button- onClick={() => { window.location.href = "/api/auth/logout"; }}+ onClick={() => { void api.auth.signOut(); }}className="p-2 rounded-lg text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors"><LogOut size={18} />diff --git a/ui/src/hooks/useSSE.ts b/ui/src/hooks/useSSE.tsindex fc8f7b34..c2178a7c 100644--- a/ui/src/hooks/useSSE.ts+++ b/ui/src/hooks/useSSE.ts@@ -1,5 +1,6 @@import { useEffect, useRef, useCallback, useState } from "react";import { useChatStore } from "@/stores/chat";+import { createEventStream, type EventStream } from "@/lib/sse";interface SSEResult {connected: boolean;@@ -9,7 +10,7 @@ interface SSEResult {export function useSSE(): SSEResult {const [connected, setConnected] = useState(false);const [reconnecting, setReconnecting] = useState(false);- const esRef = useRef<EventSource | null>(null);+ const esRef = useRef<EventStream | null>(null);const reconnectTimer = useRef<ReturnType<typeof setTimeout> | null>(null);const store = useChatStore;@@ -21,7 +22,7 @@ export function useSSE(): SSEResult {}const query = activeSessionId ? `?sessionId=${encodeURIComponent(activeSessionId)}` : "";- const es = new EventSource(`/api/chat/events${query}`);+ const es = createEventStream(`/api/chat/events${query}`);esRef.current = es;es.onopen = () => {diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.tsindex d78e0d3d..c4375d5c 100644--- a/ui/src/lib/api.ts+++ b/ui/src/lib/api.ts@@ -2,22 +2,23 @@Mercury API Client — Typed fetch layer for all endpoints═══════════════════════════════════════════════════════════════ */-const BASE = "";+import { apiUrl, authHeaders, handleUnauthorized, handleSignedOut, isRemoteMode } from "./connection";async function request<T>(path: string,options?: RequestInit): Promise<T> {- const res = await fetch(`${BASE}${path}`, {+ const res = await fetch(apiUrl(path), {+ ...options,headers: {"Content-Type": "application/json",+ ...authHeaders(),...options?.headers,},- ...options,});if (res.status === 401) {- window.location.href = "/login";+ handleUnauthorized();throw new Error("Unauthorized");}@@ -65,15 +66,102 @@ export const status = {get: () => get<AgentStatus>("/api/status"),};+// ── Health / contract (see src/web/api-contract.ts in the runtime) ──+export const health = {+ get: () => get<HealthInfo>("/api/health"),+ /** Probe an arbitrary runtime URL with an explicit token; used before a connection is configured. */+ probe: async (baseUrl: string, token: string | null, timeoutMs = 5000): Promise<HealthInfo> => {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ try {+ const res = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/health`, {+ headers: token ? { Authorization: `Bearer ${token}` } : {},+ signal: controller.signal,+ });+ if (!res.ok) throw new Error(res.status === 404 || res.status === 401 ? "Unauthorized" : `Health check failed (${res.status})`);+ return (await res.json()) as HealthInfo;+ } finally {+ clearTimeout(timer);+ }+ },+};++export interface HealthInfo {+ ok: boolean;+ pid: number;+ version: string;+ apiVersion: number;+ features: string[];+ state: string;+ booting: boolean;+}++export interface DeviceSummary {+ id: string;+ name: string;+ platform: string;+ createdAt: string;+ lastSeenAt: string | null;+}++export interface PairResponse {+ token: string;+ device: DeviceSummary;+ apiVersion: number;+ features: string[];+}++export class PairError extends Error {+ constructor(message: string, public readonly status: number, public readonly retryAfterSeconds: number | null) {+ super(message);+ this.name = "PairError";+ }+}+// ── Auth ──export const auth = {+ /** Cookie session for the runtime-served dashboard. */login: (username: string, password: string) =>- fetch("/api/auth/login", {+ fetch(apiUrl("/api/auth/login"), {method: "POST",headers: { "Content-Type": "application/x-www-form-urlencoded" },body: new URLSearchParams({ username, password }),redirect: "manual",}),+ /**+ * Device token for a hosted client (Mercury Desktop, phones). Unlike+ * login() this never touches cookies and the token is the only secret+ * the client keeps. Pass the runtime URL explicitly: nothing is+ * configured yet when a connection is being added.+ */+ pair: async (baseUrl: string, username: string, password: string, deviceName: string, platform: string) => {+ const res = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/auth/token`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ username, password, deviceName, platform }),+ });+ const body = (await res.json().catch(() => ({}))) as Partial<PairResponse> & { error?: string };+ if (!res.ok) {+ const retry = res.headers.get("Retry-After");+ throw new PairError(body.error || `Pairing failed (${res.status})`, res.status, retry ? Number(retry) : null);+ }+ return body as PairResponse;+ },+ /** Sign out of whatever we are signed in as, then hand control to the shell (or /login). */+ signOut: async () => {+ try {+ if (isRemoteMode()) {+ await post<{ success: boolean }>("/api/auth/token/revoke").catch(() => post("/api/auth/logout"));+ } else {+ window.location.href = "/api/auth/logout";+ return;+ }+ } finally {+ if (isRemoteMode()) handleSignedOut();+ }+ },+ devices: () => get<{ devices: DeviceSummary[]; current: string | null }>("/api/auth/devices"),+ revokeDevice: (id: string) => del<{ success: boolean }>(`/api/auth/devices/${encodeURIComponent(id)}`),logout: () => get<void>("/api/auth/logout"),changePassword: (currentPassword: string, newPassword: string) =>post<{ success: boolean }>("/api/auth/password", {@@ -1053,6 +1141,7 @@ export interface BoardResources {// Default export for convenienceconst api = {status,+ health,auth,config,providers,diff --git a/ui/src/lib/connection.ts b/ui/src/lib/connection.tsnew file mode 100644index 00000000..b0edeb54--- /dev/null+++ b/ui/src/lib/connection.ts@@ -0,0 +1,77 @@+/* ═══════════════════════════════════════════════════════════════+ Connection — where the API lives and how we prove who we are.++ Served by the runtime itself (the normal web dashboard) nothing is+ configured: requests are same-origin and the session cookie does the+ work. Hosted elsewhere (Mercury Desktop, a phone, a dev server) the+ shell calls configureApi() once with the runtime's URL and a device+ token, and every request and event stream picks it up from here.+ ═══════════════════════════════════════════════════════════════ */++export interface ApiConnection {+ /** Origin of the runtime, no trailing slash. "" = same origin. */+ baseUrl: string;+ /** Bearer credential (device token or session token). null = cookie session. */+ token: string | null;+}++export interface ConfigureApiOptions extends Partial<ApiConnection> {+ /** Called on a 401 instead of the default redirect to /login. */+ onUnauthorized?: (() => void) | null;+ /** Called after a sign-out completes instead of the default redirect. */+ onSignedOut?: (() => void) | null;+}++let connection: ApiConnection = { baseUrl: "", token: null };+let unauthorizedHandler: (() => void) | null = null;+let signedOutHandler: (() => void) | null = null;++export function configureApi(options: ConfigureApiOptions): void {+ connection = {+ baseUrl: normalizeBaseUrl(options.baseUrl ?? connection.baseUrl),+ token: options.token === undefined ? connection.token : options.token,+ };+ if (options.onUnauthorized !== undefined) unauthorizedHandler = options.onUnauthorized;+ if (options.onSignedOut !== undefined) signedOutHandler = options.onSignedOut;+}++export function getConnection(): ApiConnection {+ return connection;+}++/** True when a shell (not the runtime) hosts this UI: Bearer auth, absolute URLs. */+export function isRemoteMode(): boolean {+ return connection.token !== null || connection.baseUrl !== "";+}++export function apiUrl(path: string): string {+ if (/^https?:\/\//i.test(path)) return path;+ return `${connection.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;+}++export function authHeaders(): Record<string, string> {+ return connection.token ? { Authorization: `Bearer ${connection.token}` } : {};+}++/** The 401 path: a shell decides (re-pair, pick another connection); the web redirects. */+export function handleUnauthorized(): void {+ if (unauthorizedHandler) {+ unauthorizedHandler();+ return;+ }+ if (typeof window !== "undefined") window.location.href = "/login";+}++export function handleSignedOut(): void {+ if (signedOutHandler) {+ signedOutHandler();+ return;+ }+ if (typeof window !== "undefined") window.location.href = "/login";+}++export function normalizeBaseUrl(raw: string): string {+ const trimmed = (raw ?? "").trim();+ if (!trimmed) return "";+ return trimmed.replace(/\/+$/, "");+}diff --git a/ui/src/lib/sse.test.ts b/ui/src/lib/sse.test.tsnew file mode 100644index 00000000..cb173344--- /dev/null+++ b/ui/src/lib/sse.test.ts@@ -0,0 +1,84 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createSseParser, createEventStream } from "./sse";+import { configureApi } from "./connection";++/**+ * The hosted-client event stream: a fetch() with a Bearer header that+ * behaves like EventSource for the hooks that consume it.+ */++describe("sse parser", () => {+ it("splits frames on blank lines, joins multi-line data, keeps ids, skips comments", () => {+ const p = createSseParser();+ expect(p.push("event: text_delta\ndata: {\"a\":1}\n\n")).toEqual([+ { event: "text_delta", data: "{\"a\":1}", id: "" },+ ]);+ expect(p.push(": keepalive\n")).toEqual([]);+ // Chunk boundaries fall anywhere.+ expect(p.push("id: 7\ndata: one\nda")).toEqual([]);+ expect(p.push("ta: two\n\ndata: x\r\n\r\n")).toEqual([+ { event: "message", data: "one\ntwo", id: "7" },+ { event: "message", data: "x", id: "7" },+ ]);+ });+});++describe("bearer event stream", () => {+ const realFetch = globalThis.fetch;++ beforeEach(() => {+ configureApi({ baseUrl: "https://mercury.example", token: "mdt_test", onUnauthorized: () => {} });+ });++ afterEach(() => {+ globalThis.fetch = realFetch;+ configureApi({ baseUrl: "", token: null, onUnauthorized: null, onSignedOut: null });+ });++ it("sends the token, dispatches named events, and stops on close", async () => {+ let seenUrl = "";+ let seenAuth = "";+ let pulled = 0;+ globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ seenUrl = String(input);+ seenAuth = String((init?.headers as Record<string, string>)?.Authorization ?? "");+ const encoder = new TextEncoder();+ const body = new ReadableStream<Uint8Array>({+ pull(controller) {+ pulled += 1;+ if (pulled === 1) controller.enqueue(encoder.encode("event: thinking\ndata: {}\n\nevent: text_delta\ndata: {\"text\":\"hi\"}\n\n"));+ // Then hang open like a real stream until aborted.+ if (pulled > 1) return new Promise<void>(() => {});+ },+ });+ return new Response(body, { status: 200, headers: { "Content-Type": "text/event-stream" } });+ }) as typeof fetch;++ const stream = createEventStream("/api/chat/events?sessionId=abc");+ const got: Array<{ type: string; data: string }> = [];+ const opened = new Promise<void>((resolve) => { stream.onopen = () => resolve(); });+ stream.addEventListener("thinking", (e) => got.push({ type: "thinking", data: e.data }));+ stream.addEventListener("text_delta", (e) => got.push({ type: "text_delta", data: e.data }));++ await opened;+ await vi.waitFor(() => expect(got).toHaveLength(2));+ expect(seenUrl).toBe("https://mercury.example/api/chat/events?sessionId=abc");+ expect(seenAuth).toBe("Bearer mdt_test");+ expect(got[1]).toEqual({ type: "text_delta", data: "{\"text\":\"hi\"}" });+ expect(stream.readyState).toBe(1);++ stream.close();+ expect(stream.readyState).toBe(2);+ });++ it("hands a 401 to the shell instead of retrying forever", async () => {+ const unauthorized = vi.fn();+ configureApi({ onUnauthorized: unauthorized });+ globalThis.fetch = vi.fn(async () => new Response("{}", { status: 401 })) as typeof fetch;+ const stream = createEventStream("/api/bots/events");+ const errored = new Promise<void>((resolve) => { stream.onerror = () => resolve(); });+ await errored;+ await vi.waitFor(() => expect(unauthorized).toHaveBeenCalledTimes(1));+ expect(stream.readyState).toBe(2);+ });+});diff --git a/ui/src/lib/sse.ts b/ui/src/lib/sse.tsnew file mode 100644index 00000000..feb4a108--- /dev/null+++ b/ui/src/lib/sse.ts@@ -0,0 +1,199 @@+/* ═══════════════════════════════════════════════════════════════+ Event streams that work in both homes of this UI.++ Same-origin (served by the runtime): the browser's EventSource, which+ sends the session cookie and reconnects by itself.++ Hosted by a shell (Mercury Desktop, phones): EventSource cannot send an+ Authorization header, so the stream is a fetch() with the Bearer token,+ parsed frame by frame, with the same reconnect behaviour. Call sites+ see one interface either way.+ ═══════════════════════════════════════════════════════════════ */++import { apiUrl, authHeaders, handleUnauthorized, isRemoteMode } from "./connection";++type Listener = (event: MessageEvent) => void;++export interface EventStream {+ addEventListener(type: string, listener: Listener): void;+ removeEventListener(type: string, listener: Listener): void;+ close(): void;+ onopen: (() => void) | null;+ onerror: (() => void) | null;+ readonly readyState: number;+}++export function createEventStream(path: string): EventStream {+ if (!isRemoteMode()) {+ return new EventSource(apiUrl(path)) as unknown as EventStream;+ }+ return new BearerEventStream(apiUrl(path));+}++const CONNECTING = 0;+const OPEN = 1;+const CLOSED = 2;++const RECONNECT_MIN_MS = 1_000;+const RECONNECT_MAX_MS = 15_000;++class BearerEventStream implements EventStream {+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ readyState = CONNECTING;++ private readonly listeners = new Map<string, Set<Listener>>();+ private controller: AbortController | null = null;+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;+ private attempt = 0;+ private lastEventId = "";++ constructor(private readonly url: string) {+ void this.connect();+ }++ addEventListener(type: string, listener: Listener): void {+ let set = this.listeners.get(type);+ if (!set) {+ set = new Set();+ this.listeners.set(type, set);+ }+ set.add(listener);+ }++ removeEventListener(type: string, listener: Listener): void {+ this.listeners.get(type)?.delete(listener);+ }++ close(): void {+ this.readyState = CLOSED;+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);+ this.reconnectTimer = null;+ this.controller?.abort();+ this.controller = null;+ }++ private emit(type: string, data: string, id: string): void {+ const set = this.listeners.get(type);+ if (!set || set.size === 0) return;+ const event = new MessageEvent(type, { data, lastEventId: id });+ for (const listener of set) {+ try {+ listener(event);+ } catch {+ /* a listener's bug must not kill the stream */+ }+ }+ }++ private scheduleReconnect(): void {+ if (this.readyState === CLOSED) return;+ this.readyState = CONNECTING;+ const delay = Math.min(RECONNECT_MAX_MS, RECONNECT_MIN_MS * 2 ** this.attempt) + Math.random() * 250;+ this.attempt = Math.min(this.attempt + 1, 6);+ this.reconnectTimer = setTimeout(() => void this.connect(), delay);+ }++ private async connect(): Promise<void> {+ if (this.readyState === CLOSED) return;+ const controller = new AbortController();+ this.controller = controller;+ let response: Response;+ try {+ response = await fetch(this.url, {+ headers: {+ Accept: "text/event-stream",+ "Cache-Control": "no-cache",+ ...authHeaders(),+ ...(this.lastEventId ? { "Last-Event-ID": this.lastEventId } : {}),+ },+ signal: controller.signal,+ });+ } catch {+ if (controller.signal.aborted) return;+ this.onerror?.();+ this.scheduleReconnect();+ return;+ }+ if (response.status === 401) {+ this.onerror?.();+ this.close();+ handleUnauthorized();+ return;+ }+ if (!response.ok || !response.body) {+ this.onerror?.();+ this.scheduleReconnect();+ return;+ }++ this.readyState = OPEN;+ this.attempt = 0;+ this.onopen?.();++ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ const parser = createSseParser();+ try {+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ for (const frame of parser.push(decoder.decode(value, { stream: true }))) {+ if (frame.id) this.lastEventId = frame.id;+ this.emit(frame.event, frame.data, frame.id);+ }+ }+ } catch {+ /* network drop: fall through to reconnect */+ }+ if (controller.signal.aborted || this.readyState === CLOSED) return;+ this.onerror?.();+ this.scheduleReconnect();+ }+}++export interface SseFrame {+ event: string;+ data: string;+ id: string;+}++/** Incremental text/event-stream parser (same rules as the CLI's attach client). */+export function createSseParser(): { push(chunk: string): SseFrame[] } {+ let buffer = "";+ let eventName = "";+ let dataLines: string[] = [];+ let id = "";++ const flush = (frames: SseFrame[]): void => {+ if (eventName || dataLines.length > 0) {+ frames.push({ event: eventName || "message", data: dataLines.join("\n"), id });+ }+ eventName = "";+ dataLines = [];+ };++ return {+ push(chunk: string): SseFrame[] {+ const frames: SseFrame[] = [];+ buffer += chunk.replace(/\r\n/g, "\n").replace(/\r/g, "\n");+ let idx: number;+ while ((idx = buffer.indexOf("\n")) !== -1) {+ const line = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 1);+ if (line.length === 0) {+ flush(frames);+ continue;+ }+ if (line.startsWith(":")) continue; // comment / keepalive+ const colon = line.indexOf(":");+ const field = colon === -1 ? line : line.slice(0, colon);+ const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");+ if (field === "event") eventName = value;+ else if (field === "data") dataLines.push(value);+ else if (field === "id" && !value.includes("\0")) id = value;+ }+ return frames;+ },+ };+}diff --git a/ui/src/pages/Chat.tsx b/ui/src/pages/Chat.tsxindex 32113031..cd2c2848 100644--- a/ui/src/pages/Chat.tsx+++ b/ui/src/pages/Chat.tsx@@ -698,7 +698,7 @@ export function ChatPage() {variant="ghost"size="icon"className="h-8 w-8 hidden md:inline-flex"- onClick={() => (window.location.href = "/settings")}+ onClick={() => navigate("/settings")}><Settings className="h-4 w-4" /></Button>diff --git a/ui/src/pages/Kanban.tsx b/ui/src/pages/Kanban.tsxindex 85710300..d330f4f1 100644--- a/ui/src/pages/Kanban.tsx+++ b/ui/src/pages/Kanban.tsx@@ -5,6 +5,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useParams, useNavigate } from "react-router-dom";+import { createEventStream, type EventStream } from "@/lib/sse";import { AnimatePresence, motion } from "framer-motion";import {DndContext,@@ -414,7 +415,7 @@ function BoardDetailView({ boardId, onBack }: { boardId: string; onBack: () => vconst [plan, setPlan] = useState<ExecutionPlan | null>(null);const [planLoading, setPlanLoading] = useState(false);const pollRef = useRef<ReturnType<typeof setInterval>>();- const sseRef = useRef<EventSource | null>(null);+ const sseRef = useRef<EventStream | null>(null);const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),@@ -443,8 +444,7 @@ function BoardDetailView({ boardId, onBack }: { boardId: string; onBack: () => vload();// Use SSE for real-time updates, fallback to polling- const baseUrl = window.location.origin;- const es = new EventSource(`${baseUrl}/api/boards/${boardId}/events`);+ const es = createEventStream(`/api/boards/${boardId}/events`);sseRef.current = es;es.addEventListener('board-update', (e) => {diff --git a/ui/src/pages/Login.tsx b/ui/src/pages/Login.tsxindex 18c6cc0c..78f93d26 100644--- a/ui/src/pages/Login.tsx+++ b/ui/src/pages/Login.tsx@@ -1,4 +1,5 @@import { useState, type FormEvent } from "react";+import { useNavigate } from "react-router-dom";import { Input } from "@/components/ui/input";import { Button } from "@/components/ui/button";import { cn } from "@/lib/utils";@@ -11,6 +12,7 @@ export function LoginPage() {const [error, setError] = useState("");const [loading, setLoading] = useState(false);const resolved = useThemeStore((s) => s.resolved);+ const navigate = useNavigate();async function handleSubmit(e: FormEvent) {e.preventDefault();@@ -21,7 +23,7 @@ export function LoginPage() {const res = await api.auth.login(username, password);if (res.type === "opaqueredirect" || res.status === 0 || res.ok || res.status === 302) {- window.location.href = "/";+ navigate("/", { replace: true });return;}