Multiplayer agent harness for work.
Route the first admin to onboarding instead of a 403 web UI (#29)
Regan Bell8ca1b120233d
diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.tsindex e5d228c12..ab5832b5d 100644--- a/plugins/portal/src/index.ts+++ b/plugins/portal/src/index.ts@@ -71,10 +71,19 @@ const LOCAL_AUTH_PRINCIPAL = process.env.PORTAL_DEV_PRINCIPAL || process.env.USEconst DEPLOYMENTS_ENABLED = process.env.PORTAL_DEPLOYMENTS_ENABLED === "1";const NEUTRAL_ACCENT = "#4f46e5";let brandAccent = NEUTRAL_ACCENT;-let brandAccentNextAt = 0;-async function refreshBrandAccent(): Promise<void> {- if (Date.now() < brandAccentNextAt) return;- brandAccentNextAt = Date.now() + 5_000;+let modelProviderConfigured: boolean | undefined;+let surfaceConfigNextAt = 0;+let surfaceConfigInflight: Promise<void> | null = null;+function refreshSurfaceConfig(): Promise<void> {+ if (Date.now() >= surfaceConfigNextAt) {+ surfaceConfigNextAt = Date.now() + 5_000;+ surfaceConfigInflight = fetchSurfaceConfig().finally(() => {+ surfaceConfigInflight = null;+ });+ }+ return surfaceConfigInflight ?? Promise.resolve();+}+async function fetchSurfaceConfig(): Promise<void> {try {const path = withSourceAuthNonce("/v1/surface-config", CORE_SIGNING_SECRET);const r = await fetch(`${CORE}${path}`, {@@ -82,9 +91,11 @@ async function refreshBrandAccent(): Promise<void> {signal: AbortSignal.timeout(2_000),});if (r.ok) {- const b = ((await r.json()) as { branding?: { accent?: unknown } }).branding;- brandAccent = typeof b?.accent === "string" ? b.accent : NEUTRAL_ACCENT;- brandAccentNextAt = Date.now() + 30_000;+ const body = (await r.json()) as { branding?: { accent?: unknown }; modelProviderConfigured?: unknown };+ brandAccent = typeof body.branding?.accent === "string" ? body.branding.accent : NEUTRAL_ACCENT;+ modelProviderConfigured =+ typeof body.modelProviderConfigured === "boolean" ? body.modelProviderConfigured : undefined;+ surfaceConfigNextAt = Date.now() + (modelProviderConfigured === false ? 5_000 : 30_000);}} catch {void 0;@@ -447,6 +458,18 @@ export function nonAdminDeniedHtml(o: { sub: string; org: string }): string {});}+export function notConfiguredHtml(): string {+ return cardPage({+ title: "Not set up yet",+ heading: "This deployment isn't set up yet",+ msg: "An admin still needs to finish setup by adding a model API key. Until then the assistant can't answer.",+ icon: ALERT_ICON,+ warn: true,+ actions: `<a class="btn primary" href="/">Try again</a>`,+ help: "Ask your admin to complete onboarding in the Admin area.",+ });+}+export function adminUnavailableHtml(): string {return cardPage({title: "Admin temporarily unavailable",@@ -730,7 +753,7 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>res.setHeader("x-content-type-options", "nosniff");res.setHeader("x-frame-options", "DENY");- void refreshBrandAccent();+ void refreshSurfaceConfig();if (method === "GET" && pathname === "/healthz") return json(res, 200, { ok: true });@@ -937,6 +960,17 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>}}+ if (key === "web-ui" && method === "GET" && wantsHtml(req)) {+ await refreshSurfaceConfig();+ if (modelProviderConfigured === false) {+ if (await isAdmin(session.sub)) {+ res.writeHead(302, { location: "/admin/onboarding", "cache-control": "no-store" });+ return void res.end();+ }+ return sendHtml(res, 503, notConfiguredHtml());+ }+ }+let principal = session.sub;let impersonator: string | undefined;if (key === "web-ui") {diff --git a/plugins/portal/test/onboarding-redirect.test.ts b/plugins/portal/test/onboarding-redirect.test.tsnew file mode 100644index 000000000..aa2f49bfd--- /dev/null+++ b/plugins/portal/test/onboarding-redirect.test.ts@@ -0,0 +1,92 @@+import test from "node:test";+import assert from "node:assert/strict";+import { createServer, type IncomingMessage } from "node:http";+import type { AddressInfo } from "node:net";++let providerConfigured = false;++const upstream = createServer((req: IncomingMessage, res) => {+ if (req.url?.startsWith("/v1/surface-config")) {+ res.writeHead(200, { "content-type": "application/json" });+ return void res.end(+ JSON.stringify({ webuiModels: [], baseModel: "m", harnessId: "pi", modelProviderConfigured: providerConfigured }),+ );+ }+ if (req.url === "/api/whoami") {+ const m = (req.headers.cookie ?? "").match(/admin=([^;]+)/);+ const sub = m ? decodeURIComponent(m[1] ?? "") : "";+ res.writeHead(200, { "content-type": "application/json" });+ return void res.end(JSON.stringify({ isAdmin: sub === "U-admin" }));+ }+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ url: req.url }));+});+await new Promise<void>((r) => upstream.listen(0, r));+const upstreamUrl = `http://localhost:${(upstream.address() as AddressInfo).port}`;++process.env.PORTAL_PUBLIC_URL = "http://portal.test";+process.env.PORTAL_SESSION_SECRET = "onboarding-test-portal-secret";+process.env.CORE_SIGNING_SECRET = "onboarding-test-core-secret";+process.env.WEB_UI_UPSTREAM = upstreamUrl;+process.env.ADMIN_UPSTREAM = upstreamUrl;+process.env.CORE_API_URL = upstreamUrl;++const { server } = await import("../src/index.ts");+const { deriveKey, seal } = await import("../src/session.ts");+await new Promise<void>((r) => server.listen(0, r));+const base = `http://localhost:${(server.address() as AddressInfo).port}`;++const sessionKey = deriveKey("onboarding-test-portal-secret", "portal.session.v1");+function sessionCookie(sub: string): string {+ const now = Math.floor(Date.now() / 1000);+ return `portal_session=${encodeURIComponent(seal({ k: "session", sub, org: "acme", iat: now, exp: now + 28800 }, sessionKey))}`;+}++test.after(() => {+ server.close();+ upstream.close();+});++test("unconfigured deployment: admin HTML navigation to web-ui redirects to admin onboarding", async () => {+ const r = await fetch(`${base}/`, {+ headers: { accept: "text/html", cookie: sessionCookie("U-admin") },+ redirect: "manual",+ });+ assert.equal(r.status, 302);+ assert.equal(r.headers.get("location"), "/admin/onboarding");+});++test("unconfigured deployment: non-admin HTML navigation gets a not-set-up page, not a bare 403", async () => {+ const r = await fetch(`${base}/`, {+ headers: { accept: "text/html", cookie: sessionCookie("U-member") },+ redirect: "manual",+ });+ assert.equal(r.status, 503);+ assert.match(await r.text(), /isn't set up yet/);+});++test("unconfigured deployment: web-ui JSON requests still proxy through untouched", async () => {+ const r = await fetch(`${base}/api/sessions`, { headers: { cookie: sessionCookie("U-admin") } });+ assert.equal(r.status, 200);+ assert.equal(((await r.json()) as { url: string }).url, "/api/sessions");+});++test("unconfigured deployment: the admin surface itself is reachable, so onboarding never loops", async () => {+ const r = await fetch(`${base}/admin/onboarding`, {+ headers: { accept: "text/html", cookie: sessionCookie("U-admin") },+ redirect: "manual",+ });+ assert.equal(r.status, 200);+ assert.equal(((await r.json()) as { url: string }).url, "/onboarding");+});++test("once a provider is configured, admin HTML navigation proxies to web-ui again", async () => {+ providerConfigured = true;+ await new Promise((r) => setTimeout(r, 5_200));+ const r = await fetch(`${base}/`, {+ headers: { accept: "text/html", cookie: sessionCookie("U-admin") },+ redirect: "manual",+ });+ assert.equal(r.status, 200);+ assert.equal(((await r.json()) as { url: string }).url, "/");+});diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex c94b1961a..ae2120bf6 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -889,6 +889,7 @@ async function getSurfaceConfig(ctx: ApiCtx): Promise<void> {webuiModels: configuredPicker.length ? configuredPicker : allowed,baseModel: resolvedBase,harnessId,+ ...(managedKeys ? { modelProviderConfigured: Object.values(managedKeys).some(Boolean) } : {}),externalSlackParticipants,...(Object.keys(resolvedBranding).length ? { branding: resolvedBranding } : {}),});diff --git a/test/model-credential-route.test.ts b/test/model-credential-route.test.tsindex afe79984b..3aaec1eb6 100644--- a/test/model-credential-route.test.ts+++ b/test/model-credential-route.test.ts@@ -386,6 +386,21 @@ test("a rejected rotation preserves the prior key and disabling suppresses envir}});+test("surface-config reports whether any model provider is configured", async () => {+ const srv = start();+ try {+ const before = await fetch(`${srv.base}/v1/surface-config`);+ assert.equal(before.status, 200);+ assert.equal(((await before.json()) as { modelProviderConfigured?: boolean }).modelProviderConfigured, false);++ await srv.built.modelCredentials.set("anthropic", "working-admin-key", "admin-alice@default-org");+ const after = await fetch(`${srv.base}/v1/surface-config`);+ assert.equal(((await after.json()) as { modelProviderConfigured?: boolean }).modelProviderConfigured, true);+ } finally {+ await srv.close();+ }+});+test("admin model credentials survive a second app instance on the same durable store", async () => {const backing = createMemoryMap<StoredModelCredential>();const first = createModelCredentialStore({ backing, keyMaterial: "shared-model-key" });