Multiplayer agent harness for work.
Replace the web UI's sign-in form with auth-gate states (#23)
Joshua Francef23b36544cbb
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex 9a1340413..343194a72 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -33,6 +33,8 @@ const PUBLIC_URL = (process.env.WEB_UI_PUBLIC_URL ?? `http://localhost:${PORT}`)const WEB_UI_DEV = process.env.WEB_UI_DEV === "1";const ALLOW_UNSIGNED_TEST_IDENTITY =process.env.NODE_ENV === "test" && process.env.ALLOW_UNSIGNED_TEST_IDENTITY === "1";+const COOKIE_AUTH = !CORE_SIGNING_SECRET || ALLOW_UNSIGNED_TEST_IDENTITY;+const AUTH_MODE = COOKIE_AUTH ? "dev" : "portal";const ALLOW = (process.env.WEB_UI_PRINCIPALS ?? "").split(",").map((s) => s.trim())@@ -252,7 +254,7 @@ function resolveIdentity(name = claims.n ?? null;impersonator = claims.imp ?? null;} else {- if (CORE_SIGNING_SECRET && !ALLOW_UNSIGNED_TEST_IDENTITY) return null;+ if (!COOKIE_AUTH) return null;user = cookie(req, "webuiuser");name = cookie(req, "webuiuser_name");impersonator = cookie(req, "webui_impersonator");@@ -701,6 +703,7 @@ const routeRequest = async (req: IncomingMessage, res: ServerResponse) => {}if (method === "POST" && path === "/signin") {+ if (!COOKIE_AUTH) return json(res, 404, { error: "not_found" });const body = await readBody(req);const id = (() => {try {@@ -709,7 +712,12 @@ const routeRequest = async (req: IncomingMessage, res: ServerResponse) => {return "";}})();- if (!id || (ALLOW.length > 0 && !ALLOW.includes(id))) return json(res, 403, { error: "not allowed" });+ if (!id) return json(res, 400, { error: "bad_request", message: "Enter a principal to sign in as." });+ if (ALLOW.length > 0 && !ALLOW.includes(id))+ return json(res, 403, {+ error: "not_allowed",+ message: `${id.slice(0, 120)} isn't in this instance's allowed principals. Add it to WEB_UI_PRINCIPALS, or leave that unset to allow any principal.`,+ });res.writeHead(200, {"set-cookie": sessionCookie(id),"content-type": "application/json",@@ -741,7 +749,7 @@ const routeRequest = async (req: IncomingMessage, res: ServerResponse) => {if (path === "/me" || path.startsWith("/api/")) {const user = cookieUser(req);- if (!user) return json(res, 401, { error: "sign in" });+ if (!user) return json(res, 401, { error: "sign in", mode: AUTH_MODE });if (path === "/me") {res.setHeader("set-cookie", sessionCookie(user));@@ -749,6 +757,7 @@ const routeRequest = async (req: IncomingMessage, res: ServerResponse) => {return json(res, 200, {user,org: ORG,+ mode: AUTH_MODE,slackWorkspaceUrl: await slackWorkspaceUrl(),impersonatedBy: resolveIdentity(req)?.impersonator ?? null,permissions,@@ -1824,7 +1833,7 @@ const routeRequest = async (req: IncomingMessage, res: ServerResponse) => {if (method === "GET" && path.startsWith("/deployments/")) {const user = cookieUser(req);- if (!user) return json(res, 401, { error: "sign in" });+ if (!user) return json(res, 401, { error: "sign in", mode: AUTH_MODE });const rest = path.slice("/deployments/".length);const slash = rest.indexOf("/");const id = decodeURIComponent(slash === -1 ? rest : rest.slice(0, slash));@@ -1896,7 +1905,7 @@ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {);if (!WEB_UI_DEV && !existsSync(join(DIST, "index.html")))console.warn("[web-ui] dist-web/ not built — run `npm run build`");- if (ALLOW.length === 0)+ if (COOKIE_AUTH && ALLOW.length === 0)console.warn("[web-ui] WEB_UI_PRINCIPALS unset — any principal id may sign in (dev only)");const t = setInterval(() => void drainWebDeliveries(), WEB_DELIVERY_POLL_MS);t.unref?.();diff --git a/plugins/web-ui/src/main.ts b/plugins/web-ui/src/main.tsindex fc265b087..7e87a7ec3 100644--- a/plugins/web-ui/src/main.ts+++ b/plugins/web-ui/src/main.ts@@ -1,6 +1,7 @@import "dockview-core/dist/styles/dockview.css";import "./shell.css";-import { boot } from "./shell";+import { swallow } from "../../chassis/src/errors";+import { appState, boot, renderAuthGate } from "./shell";import { closeFormMenus } from "./ui";import { drawActiveChat } from "./chat";import { composerState, slashQuery } from "./composer";@@ -44,4 +45,7 @@ document.addEventListener("keydown", (e) => {if (changed) drawActiveChat();});-void boot();+void boot().catch((e: unknown) => {+ if (appState.me) swallow("web-ui: boot", e);+ else renderAuthGate({ kind: "unreachable" });+});diff --git a/plugins/web-ui/src/shell-state.ts b/plugins/web-ui/src/shell-state.tsindex 45b24dafe..032ce3a89 100644--- a/plugins/web-ui/src/shell-state.ts+++ b/plugins/web-ui/src/shell-state.ts@@ -1,6 +1,9 @@+export type AuthMode = "portal" | "dev";+export interface Me {user: string;org: string;+ mode?: AuthMode;slackWorkspaceUrl?: string | null;impersonatedBy?: string | null;permissions?: string[];diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 2f8b4cbe2..1b30ad5a8 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -2,7 +2,6 @@:root {--app-font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;- --app-serif: ui-serif, Georgia, "Times New Roman", Times, serif;--sidebar-w: 280px;--content-w: 820px;--radius-sm: 8px;@@ -10,6 +9,7 @@--radius-lg: 16px;--chat-pad: 22px;--brand-accent: #4f46e5;+ --dev-accent: #8a5a00;--brand-mark: "A";}@@ -2468,7 +2468,7 @@ body.resizing-sidebar {grid-template-rows: auto auto minmax(0, 1fr);}-.impersonation-banner {+.top-banner {position: fixed;top: 0;left: 0;@@ -2486,10 +2486,13 @@ body.resizing-sidebar {font-size: 13px;font-weight: 500;}-.impersonation-banner b {+.top-banner.dev {+ background: var(--dev-accent);+}+.top-banner b {font-weight: 700;}-.impersonation-banner-exit {+.top-banner-action {font: inherit;font-weight: 600;cursor: pointer;@@ -2499,10 +2502,10 @@ body.resizing-sidebar {border-radius: 6px;padding: 4px 12px;}-.impersonation-banner-exit:hover {+.top-banner-action:hover {background: rgba(0, 0, 0, 0.3);}-.layout.impersonating {+.layout.bannered {--surface-safe-top: 0px;height: calc(100vh - 38px - env(safe-area-inset-top));height: calc(100dvh - 38px - env(safe-area-inset-top));@@ -3887,6 +3890,7 @@ body.resizing-sidebar {padding: 24px;box-sizing: border-box;}+.signin-panel,.signin form {display: flex;flex-direction: column;@@ -3894,6 +3898,9 @@ body.resizing-sidebar {width: 340px;max-width: 100%;}+.signin form {+ width: auto;+}.signin-brand {display: flex;align-items: center;@@ -3903,6 +3910,35 @@ body.resizing-sidebar {letter-spacing: 0;margin-bottom: 4px;}+.signin-brand .dev-chip {+ margin-left: auto;+ padding: 2px 6px;+ border-radius: 4px;+ background: var(--dev-accent);+ color: #fff;+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.1em;+}+.signin-body {+ font-size: 13.5px;+ color: var(--muted-foreground);+ line-height: 1.5;+ margin: -4px 0 2px;+}+.signin-body b {+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);+ font-size: 0.9em;+ font-weight: 600;+ color: var(--foreground);+}+.signin label {+ font-size: 12px;+ font-weight: 600;+ color: var(--muted-foreground);+ margin-bottom: -6px;+}.signin-brand .brand-mark {width: 22px;height: 22px;@@ -3910,10 +3946,10 @@ body.resizing-sidebar {font-size: 16px;}.signin h1 {- font-family: var(--app-serif);- font-size: 26px;- font-weight: 500;+ font-size: 22px;+ font-weight: 600;letter-spacing: 0;+ line-height: 1.2;margin: 0 0 2px;}.signin input {@@ -3935,6 +3971,9 @@ body.resizing-sidebar {color: var(--muted-foreground);line-height: 1.45;}+.signin .hint.error {+ color: var(--destructive, #c00);+}@media (max-width: 860px) {:root {diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.tsindex fba3adf41..40a8d7d73 100644--- a/plugins/web-ui/src/shell.ts+++ b/plugins/web-ui/src/shell.ts@@ -62,10 +62,12 @@ import { renderDeploys } from "./deploys";import { renderMemory, resetMemoryState } from "./memory";import { renderSkills } from "./skills";import { contextsState, ensureContexts, renderContexts, resetContextsState } from "./contexts";-import { appState, isView, type Me, type View } from "./shell-state";+import { appState, isView, type AuthMode, type Me, type View } from "./shell-state";import { trapDialogFocus } from "./dialog-focus";export { appState, can, type Me, type View } from "./shell-state";+let authMode: AuthMode = "portal";+export const ADMIN_BASE = (() => {const base = ((import.meta as unknown as { env?: { BASE_URL?: string } }).env?.BASE_URL ?? "/").replace(/\/$/, "");return base ? base.replace(/\/[^/]+$/, "/admin") : "/admin";@@ -193,7 +195,16 @@ export async function signOut(): Promise<void> {resetContextsState();resetKeychainState();resetComposer();- renderSignin();+ if (authMode === "portal") {+ try {+ await fetch("/auth/logout", { method: "POST", headers: { accept: "application/json" } });+ } catch {+ void 0;+ }+ location.href = "/";+ return;+ }+ renderAuthGate({ kind: "dev" });}export async function exitImpersonation(): Promise<void> {@@ -207,43 +218,104 @@ export async function exitImpersonation(): Promise<void> {function impersonationBanner(by: string) {return html`- <div class="impersonation-banner" role="status">- <span class="impersonation-banner-text"- >Viewing the assistant as <b>${appState.me?.user ?? ""}</b> — you are <b>${by}</b></span- >- <button class="impersonation-banner-exit" type="button" @click=${exitImpersonation}>Exit impersonation</button>+ <div class="top-banner" role="status">+ <span>Viewing the assistant as <b>${appState.me?.user ?? ""}</b> — you are <b>${by}</b></span>+ <button class="top-banner-action" type="button" @click=${exitImpersonation}>Exit impersonation</button></div>`;}-export function renderSignin(errorText = ""): void {- render(- html`- <div class="signin">- <form- @submit=${async (e: Event) => {- e.preventDefault();- const input = (e.target as HTMLFormElement).querySelector("input");- const user = (input as HTMLInputElement)?.value.trim();- if (!user) return;- try {- await api("/signin", { method: "POST", body: JSON.stringify({ user }) });- await boot();- } catch (err) {- renderSignin(errMessage(err, "sign in failed"));- }- }}- >- <div class="signin-brand">${brandMark()}<span>${brandName()}</span></div>- <h1>Sign in</h1>- <input type="text" placeholder="your principal id (e.g. [email protected])" autofocus />- <button class="btn primary" type="submit">Continue</button>- ${errorText ? html`<div class="hint" style="color:var(--destructive,#c00)">${errorText}</div>` : html`<div class="hint">Use your principal ID.</div>`}- </form>+function devBanner(user: string) {+ return html`+ <div class="top-banner dev" role="status">+ <span><b>Dev mode</b> — no identity provider, signed in as ${user}</span>+ <button class="top-banner-action" type="button" @click=${signOut}>Sign out</button>+ </div>+ `;+}++function gateShell(body: unknown) {+ return html`+ <div class="signin">+ <div class="signin-panel">+ <div class="signin-brand">+ ${brandMark()}<span>${brandName()}</span>+ ${authMode === "dev" ? html`<span class="dev-chip">DEV</span>` : nothing}+ </div>+ ${body}</div>- `,- appEl as HTMLElement,- );+ </div>+ `;+}++function signInWithPortal(): void {+ const returnTo = `${location.pathname}${location.search}`;+ location.href = `/auth/login?returnTo=${encodeURIComponent(returnTo)}`;+}++function portalGate() {+ return gateShell(html`+ <h1>Your session ended</h1>+ <p class="signin-body">You've been signed out. Sign in again and you'll come back to this page.</p>+ <button class="btn primary" type="button" @click=${signInWithPortal}>Sign in</button>+ `);+}++function unreachableGate() {+ return gateShell(html`+ <h1>We couldn't reach the assistant</h1>+ <p class="signin-body">The service didn't respond. This is usually temporary.</p>+ <button class="btn primary" type="button" @click=${() => void boot()}>Try again</button>+ <div class="hint">If this keeps happening, the core service may be down.</div>+ `);+}++function devGate(errorText: string) {+ return gateShell(html`+ <form+ @submit=${async (e: Event) => {+ e.preventDefault();+ const form = e.target as HTMLFormElement;+ const input = form.querySelector("input") as HTMLInputElement | null;+ const user = input?.value.trim();+ if (!user || form.dataset.pending === "1") return;+ form.dataset.pending = "1";+ try {+ await api("/signin", { method: "POST", body: JSON.stringify({ user }) });+ await boot();+ } catch (err) {+ renderAuthGate({ kind: "dev", error: errMessage(err, "Sign-in failed.") });+ }+ }}+ >+ <h1>Dev sign-in</h1>+ <p class="signin-body">+ No identity provider is configured, so this instance trusts a local cookie. Set+ <b>CORE_SIGNING_SECRET</b> and run the portal to use real sign-in.+ </p>+ <label for="dev-principal">Work email</label>+ <input id="dev-principal" name="principal" type="email" autocomplete="username" autofocus spellcheck="false" />+ <button class="btn primary" type="submit">Continue</button>+ ${errorText ? html`<div class="hint error" role="alert">${errorText}</div>` : nothing}+ </form>+ `);+}++export type AuthGate = { kind: "portal" } | { kind: "unreachable" } | { kind: "dev"; error?: string };++export function renderAuthGate(gate: AuthGate): void {+ if (gate.kind === "dev") authMode = "dev";+ const body = (() => {+ switch (gate.kind) {+ case "portal":+ return portalGate();+ case "unreachable":+ return unreachableGate();+ default:+ return devGate(gate.error ?? "");+ }+ })();+ render(body, appEl as HTMLElement);}export function mountShell(): void {@@ -261,10 +333,13 @@ export function mountShell(): void {}applySavedSidebarWidth();const impersonatedBy = appState.me?.impersonatedBy ?? null;+ let banner: TemplateResult | null = null;+ if (impersonatedBy) banner = impersonationBanner(impersonatedBy);+ else if (authMode === "dev") banner = devBanner(appState.me?.user ?? "");render(html`- ${impersonatedBy ? impersonationBanner(impersonatedBy) : nothing}- <div class="layout ${sidebarOpen ? "" : "sidebar-closed"} ${impersonatedBy ? "impersonating" : ""}">+ ${banner ?? nothing}+ <div class="layout ${sidebarOpen ? "" : "sidebar-closed"} ${banner ? "bannered" : ""}"><aside class="sidebar" aria-label="Navigation" @keydown=${onSidebarKeydown}><div class="brand"><div class="brand-lockup">${brandMark()}<span class="brand-name">${brandName()}</span></div>@@ -614,13 +689,29 @@ function openAppEditChat(slug: string): void {}export async function boot(): Promise<void> {- const r = await fetch(withBase("/me"));+ let r: Response;+ try {+ r = await fetch(withBase("/me"));+ } catch {+ renderAuthGate({ kind: "unreachable" });+ return;+ }if (r.status === 401) {- renderSignin();+ const mode = await r+ .json()+ .then((b: { mode?: AuthMode }) => b.mode)+ .catch(() => undefined);+ authMode = mode ?? "portal";+ renderAuthGate(authMode === "dev" ? { kind: "dev" } : { kind: "portal" });+ return;+ }+ if (!r.ok) {+ renderAuthGate({ kind: "unreachable" });return;}resetKeychainState();appState.me = (await r.json()) as Me;+ authMode = appState.me.mode ?? "portal";const runtimeConfig = await fetchRuntimeConfig(`personal:${appState.me.user}`);if (runtimeConfig)applyRuntimeOptions(diff --git a/plugins/web-ui/test/responsive-source.test.ts b/plugins/web-ui/test/responsive-source.test.tsindex b71ad4741..f1a850c05 100644--- a/plugins/web-ui/test/responsive-source.test.ts+++ b/plugins/web-ui/test/responsive-source.test.ts@@ -67,11 +67,11 @@ test("the sidebar's new-session action keeps the shared outline treatment", () =assert.doesNotMatch(css, /split-new-session/);});-test("impersonation mode keeps its critical exit control below the top safe area", () => {+test("a top banner keeps its critical action below the top safe area", () => {assert.match(compactCss, /height: calc\(38px \+ env\(safe-area-inset-top\)\)/);assert.match(compactCss, /padding: env\(safe-area-inset-top\)/);assert.match(compactCss, /margin-top: calc\(38px \+ env\(safe-area-inset-top\)\)/);- assert.match(compactCss, /\.layout\.impersonating \{\s*--surface-safe-top: 0px;/);+ assert.match(compactCss, /\.layout\.bannered \{\s*--surface-safe-top: 0px;/);assert.match(compactCss, /padding-top: calc\(10px \+ var\(--surface-safe-top\)\)/);});diff --git a/plugins/web-ui/vite.config.ts b/plugins/web-ui/vite.config.tsindex fb3b2ebe9..46e5afc7d 100644--- a/plugins/web-ui/vite.config.ts+++ b/plugins/web-ui/vite.config.ts@@ -34,6 +34,7 @@ export default defineConfig({fs: { allow: [fileURLToPath(new URL("..", import.meta.url))] },proxy: {"/signin": SERVER,+ "/signout": SERVER,"/me": SERVER,"/api": SERVER,},