Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud home: an engine sign-in ends cleanly for sleep, and support can see every attempt (#7723)
Milind Soni46f01612581a
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex 5dbccc60ca..aa812015c2 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1799,10 +1799,35 @@ wait for the next read, `truncated: true`):"boot": { "waits": 5, "stopped": 1, "killed": 1, "stallMinutes": 4 } },"speed": { "windowS": 300, "steal": 1.2, "psi": { "cpu": 3.4, "memory": 0, "io": 0.8 }, "bootMs": 5400, "wakeMs": null,"turnStarts": [12, 3, 1, 0, 0, 0], "loop": { "n": 2, "worstMs": 1800 } },- "clock": { "v": 1, "errorMs": 21660000, "measuredAt": 1790021660000 }+ "clock": { "v": 1, "errorMs": 21660000, "measuredAt": 1790021660000 },+ "signIns": { "attempts": 3, "open": 0,+ "engines": [{ "kind": "claudeAgent", "attempts": 3, "completed": 0, "last": { "outcome": "interrupted", "at": 1790000780000 } }],+ "recent": [{ "kind": "claudeAgent", "method": "paste-code", "outcome": "wrong_code", "at": 1790000420000 },+ { "kind": "claudeAgent", "method": "paste-code", "outcome": "interrupted", "at": 1790000780000 }] }}```+**`signIns`** is the home's engine sign-ins (`server/sign-in-trace.ts`, kept+in `sign-in-trace.json` so a stop can't wipe it): `attempts` since the first+one (each press of an engine's sign-in), how many are `open` now, per engine+kind its attempts, completed ones and the last event, and the last 10 events+(`started`, or an outcome). An outcome is a fixed code+(`shared/sign-in-outcome.ts`): `completed`, `wrong_code` (a pasted code that+is not a code; the sign-in stays open), `refused` (the provider refused it),+`expired`, `cancelled`, `exited` (the engine's login command ended),+`interrupted` (the server stopped or restarted under it, which the next boot+records, or the engine's settings changed), `not_installed`, `timed_out` or+`failed`. `method` is the provider card's (`paste-code`, `device-code`,+`browser-pkce`, `browser`, `callback-url`). Never a code, link, account,+session or flow. Each event is also one log line, such as `sign-in:+claudeAgent paste-code wrong_code after 1m 12s`. Left out when it can't be+read; older homes don't send it, and an Admin that doesn't know it drops it.+The sign-in status the screen polls (`GET /api/instances/<id>/auth/status`)+carries the same code as `reason` on a finished sign-in, and an error from+`auth/start`, `auth/complete` or `auth/cancel` carries it as `reason` where+known: a flow the server's stop cut short reads `{"phase":"failed",+"reason":"interrupted"}`.+**`clock`** is the home's clock as it last measured it ("The home's clock"below): `errorMs` how far it is behind the true time (negative: ahead), and`measuredAt` when, in true time; both `null` when nothing measured it in the@@ -2083,7 +2108,9 @@ judge a pending timer by a wall-clock time stored when it was set.send; one parked on a person's answer doesn't count), no Live call, no cloudcomputer on or starting (its idle timerlives in this process), no maintenance (backup or restore, Move to Cloud, an- engine or browser install, a provider sign-in) and no request in progress;+ engine or browser install, a provider sign-in until it finishes, fails, is+ cancelled or reaches its own expiry, at most 15 minutes for every engine) and no+ request in progress;- nobody used the home for 10 minutes (the Admin may ask for another window).A use is an authenticated request, except the event stream, `/api/health`,`/api/sync/…`, `/api/shared-computers/…` and requests the page marksdiff --git a/server/cloud-health.test.ts b/server/cloud-health.test.tsindex 469099a8f9..bcdc3be9fd 100644--- a/server/cloud-health.test.ts+++ b/server/cloud-health.test.ts@@ -1,5 +1,6 @@import { randomBytes } from "node:crypto";-import { mkdirSync, rmSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";import type { IncomingMessage, ServerResponse } from "node:http";import { join } from "node:path";import { PassThrough } from "node:stream";@@ -17,9 +18,12 @@ import type { RuntimeEvent } from "./contracts.ts";import { doctorAtStart } from "./doctor/start.ts";import { toolFailureMessage } from "./drivers/tool-failure.ts";import { STORAGE_HEALTH_MAX_BYTES, type StorageReport } from "./perf/disk-usage.ts";+import { ProviderAuthSessions } from "./provider-auth-sessions.ts";import { createCloudSignedRoutes } from "./routes/cloud-signed.ts";import { SessionRegistry } from "./sessions.ts";+import { createSignInTrace } from "./sign-in-trace.ts";import { Store } from "./store.ts";+import { removeTempDir } from "./testing/cleanup.ts";const START = 1_800_000_000_000;const secret = "S".repeat(43);@@ -75,6 +79,33 @@ describe("a Cloud home's storage in its health report", () => {});});+describe("a Cloud home's engine sign-ins in its health report", () => {+ it("counts attempts and says how the last one ended, with no code, link, flow or account in it; left out where there is no trace or its read throws", async () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-health-sign-ins-"));+ try {+ const trace = createSignInTrace({ dataDir: dir, now: () => START, log: () => {} });+ const sessions = new ProviderAuthSessions({ trace, now: () => START });+ const auth = { phase: "waiting" as const, flowId: "flow-secret-1", authorizationUrl: "https://claude.com/cai/oauth/authorize?state=secret-state", expiresAt: null };+ const instance = { instanceId: "claude-ada-work", driverKind: "claudeAgent", startAuthentication: async () => auth, getAuthentication: async () => auth,+ completeAuthentication: async () => { throw Object.assign(new Error("Paste the whole code"), { reason: "wrong_code" }); }, cancelAuthentication: async () => {} };+ for (let attempt = 0; attempt < 3; attempt++) {+ await sessions.start(instance, "session-secret");+ await expect(sessions.complete(instance.instanceId, "session-secret", "flow-secret-1", "SHORT")).rejects.toThrow();+ if (attempt < 2) await sessions.cancel(instance.instanceId, "session-secret", "flow-secret-1");+ }+ const report = world({ signIns: () => trace.summary() }).health.report(undefined);+ expect(report.signIns).toMatchObject({ attempts: 3, open: 1, engines: [{ kind: "claudeAgent", attempts: 3, completed: 0, last: { outcome: "wrong_code", at: START } }] });+ expect(report.signIns!.recent.at(-1)).toEqual({ kind: "claudeAgent", method: "paste-code", outcome: "wrong_code", at: START });+ for (const secret of ["SHORT", "flow-secret", "secret-state", "claude.com", "session-secret", "ada-work"]) expect(JSON.stringify(report)).not.toContain(secret);+ } finally { await removeTempDir(dir); }+ expect(world().health.report(undefined)).not.toHaveProperty("signIns");+ const warned: string[] = [];+ const broken = world({ signIns: () => { throw new TypeError("flow-secret-1"); }, log: (line) => warned.push(line) });+ expect(broken.health.report(undefined)).not.toHaveProperty("signIns");+ expect(warned).toEqual(["cloud health: signIns left out: TypeError"]);+ });+});+describe("a Cloud home's memory pressure in its health report", () => {it("carries the last day's counts where the home watches memory, and null where it does not", () => {expect(world().health.report(undefined)).toMatchObject({ room: null });diff --git a/server/cloud-health.ts b/server/cloud-health.tsindex 3dcdaf04dc..563e2bd803 100644--- a/server/cloud-health.ts+++ b/server/cloud-health.ts@@ -20,6 +20,7 @@ import { storageHealth, type StorageReport } from "./perf/disk-usage.ts";import type { PerfHealth } from "./perf/perf-report.ts";import type { RoutineHealth } from "./routine-health.ts";import type { ScheduleSection } from "./routine-schedule-report.ts";+import type { SignInSummary } from "./sign-in-trace.ts";import type { Message, StoreChange } from "./store.ts";/** The report's largest JSON body; incidents past it wait for the next poll. */@@ -282,6 +283,8 @@ export interface CloudHealthDeps {perf?: () => PerfHealth | null;/** What fills the volume (perf/disk-usage.ts), at most STORAGE_HEALTH_MAX_BYTES; the field is left out on a throw or null. */storage?: () => StorageReport | null;+ /** Engine sign-in attempts and how they ended (server/sign-in-trace.ts): kinds, method names, codes and times; left out on a throw. */+ signIns?: () => SignInSummary | null;log?: (line: string) => void;now?: () => number;}@@ -325,6 +328,9 @@ export function createCloudHealth(deps: CloudHealthDeps) {const perf = () => {try { return deps.perf?.() ?? null; } catch (error) { leftOut("perf", error); return null; }};+ const signIns = (): { signIns?: SignInSummary } => {+ try { const summary = deps.signIns?.(); return summary ? { signIns: summary } : {}; } catch (error) { leftOut("signIns", error); return {}; }+ };const storage = (): { storage?: StorageReport } => {try { const report = deps.storage?.(); return report ? { storage: storageHealth(report) } : {}; } catch (error) { leftOut("storage", error); return {}; }};@@ -356,7 +362,7 @@ export function createCloudHealth(deps: CloudHealthDeps) {engines: engines(), connectors: connectorState(),browser: { available: browser.available, installing: browser.installing, interrupted: browser.interrupted, ...(browser.cloudComputer ? { cloudComputer: browser.cloudComputer } : {}) },box: boxSummary(deps.box?.()),- firstHour: first?.firstHour ?? null, value: first?.value ?? null, room: deps.room?.() ?? null, speed: speed.report(), perf: perf(), ...storage(),+ firstHour: first?.firstHour ?? null, value: first?.value ?? null, room: deps.room?.() ?? null, speed: speed.report(), perf: perf(), ...storage(), ...signIns(),// The data checks of this version's first start: check ids and counts (server/doctor/start.ts).doctor: doctorHealth(),system: { ...memory, rssBytes: process.memoryUsage.rss(), load1: loadavg()[0] ?? 0, cpus: availableParallelism(), disk: diskBytes(deps.dataDir), eventLogWritable: writable(deps.eventsDir) },diff --git a/server/cloud-sign-in.e2e.test.ts b/server/cloud-sign-in.e2e.test.tsnew file mode 100644index 0000000000..98a868bdb9--- /dev/null+++ b/server/cloud-sign-in.e2e.test.ts@@ -0,0 +1,169 @@+// A real Cloud home (the server as the Admin runs it, with a quarter-second power clock) whose owner is signing in to+// Claude: while the paste-code sign-in is open the home refuses the Admin's sleep request as `maintenance`, a code that is+// not a code keeps it open, the health report counts the attempt with no secret in it, and a stop in the middle (the+// process killed, as a stop for sleep does) is recorded as interrupted on the next boot, which the sign-in screen's next+// read hears. Cancelling lets it sleep. The engine is a stand-in CLI; nothing leaves loopback.+import { randomBytes } from "node:crypto";+import { spawn, type ChildProcess } from "node:child_process";+import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { afterAll, beforeAll, expect, it } from "vitest";+import { CLOUD_HEALTH_PATH, cloudPairingSignature, cloudRequestSignature } from "./cloud-home.ts";+import { removeTempDir, waitForExit } from "./testing/cleanup.ts";+import { hostTimeout } from "./testing/host-timeout.ts";+import { freePortBlock } from "./testing/ports.ts";++const SERVER_DIR = fileURLToPath(new URL("./", import.meta.url));+const HOST = "omb-t-5a4b3c2d1e0f.fly.dev";+const MACHINE = "1c2d3e4f-5a6b-4c7d-8e9f-0a1b2c3d4e5f";+const TEAM = { id: "team-sign-in-1", name: "Quayside" };+const OWNER = { email: "[email protected]", role: "owner" as const };+const EDGE = { host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", origin: `https://${HOST}` };+const PASTED = "SHORT#1", LINK_SECRET = "state-7c1d2e";+const secret = randomBytes(32).toString("base64url");+let home = "", base = "", log = "", owner = "", port = 0;+let child: ChildProcess | undefined;++const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms));++async function as(method: string, path: string, body?: unknown) {+ const response = await fetch(`${base}${path}`, { method, body: body === undefined ? undefined : JSON.stringify(body),+ headers: { ...EDGE, authorization: `Bearer ${owner}`, ...(body === undefined ? {} : { "content-type": "application/json" }) } });+ return { status: response.status, body: await response.json().catch(() => null) as any };+}++/** The Admin's signed calls: its health and power reads and its sleep request. */+async function admin(method: "GET" | "POST", path: string, body = "") {+ const timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(16).toString("base64url");+ const response = await fetch(`${base}${path}`, { method, ...(method === "POST" ? { body } : {}), headers: {+ ...EDGE, ...(method === "POST" ? { "content-type": "application/json" } : {}),+ "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${cloudRequestSignature(secret, timestamp, nonce, method, path, body)}`,+ } });+ return { status: response.status, body: await response.json().catch(() => null) as any };+}+const askToSleep = () => admin("POST", "/api/cloud/power/sleep", JSON.stringify({ v: 1 }));++async function pair() {+ const body = JSON.stringify({ label: "OpenMausBot app (Team Cloud)", ttlSeconds: 300, team: TEAM, member: OWNER });+ const timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(16).toString("base64url");+ const minted = await fetch(`${base}/api/cloud/pairing`, { method: "POST", body, headers: { ...EDGE, "content-type": "application/json",+ "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${cloudPairingSignature(secret, timestamp, nonce, body)}` } });+ expect(minted.status, log.slice(-2000)).toBe(200);+ const { code } = await minted.json() as { code: string };+ const paired = await fetch(`${base}/api/auth/pair`, { method: "POST", headers: { ...EDGE, "content-type": "application/json" }, body: JSON.stringify({ code }) });+ return ((await paired.json()) as { token: string }).token;+}++async function boot() {+ const offline = `data:text/javascript,${encodeURIComponent('const real = globalThis.fetch; globalThis.fetch = async (url, init) => String(url).startsWith("http://127.0.0.1:") ? real(url, init) : new Response("offline fixture", { status: 503 });')}`;+ child = spawn(process.execPath, ["--import", offline, "--import", new URL("./testing/power-clock-hooks.mjs", import.meta.url).href, join(SERVER_DIR, "index.ts")], {+ cwd: join(SERVER_DIR, ".."),+ env: {+ PATH: process.env.PATH, ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}), HOME: home, USERPROFILE: home, OMB_DATA_DIR: home,+ OMB_PORT: String(port), OMB_WEBHOOK_PORT: String(port + 1), OMB_CLOUD_ROLE: "team", OMB_CLOUD_TEAM_ID: TEAM.id, OMB_CLOUD_TEAM_NAME: TEAM.name,+ OMB_CLOUD_MACHINE_ID: MACHINE, OMB_CLOUD_ADMIN_URL: "https://cloud.example.test", OMB_CLOUD_BOOTSTRAP_SECRET: secret, OMB_PUBLIC_URL: `https://${HOST}`,+ OMB_TEST_POWER_CLOCK: "1",+ },+ stdio: ["ignore", "pipe", "pipe"],+ });+ child.stdout?.on("data", (chunk) => { log += chunk; });+ child.stderr?.on("data", (chunk) => { log += chunk; });+ const deadline = Date.now() + 30_000;+ for (;;) {+ if (child.exitCode !== null) throw new Error(`the server exited:\n${log}`);+ try { if ((await fetch(`${base}/api/health`)).ok) break; } catch {}+ if (Date.now() > deadline) throw new Error(`the server did not start:\n${log}`);+ await sleep(100);+ }+}++/** Asks until the home agrees (the power clock's windows are a quarter second), or gives up after `ms`. */+async function sleepsWithin(ms: number) {+ let answer = await askToSleep();+ for (const deadline = Date.now() + ms; answer.status !== 200 && Date.now() < deadline;) {+ await sleep(250);+ answer = await askToSleep();+ }+ return answer;+}++beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), "omb-cloud-sign-in-"));+ const cli = join(home, "fixture-claude.mjs");+ // Claude signed out: `auth login` shows its link and waits for the pasted code; anything else is the synthetic engine.+ writeFileSync(cli, `#!/usr/bin/env node+const args = process.argv.slice(2).join(" ");+if (args === "auth status --json") { console.log(JSON.stringify({ loggedIn: false })); process.exit(1); }+if (args === "auth login") {+ process.stdout.write("If the browser did not open, visit: https://claude.com/cai/oauth/authorize?code=true&state=${LINK_SECRET}\\n");+ process.stdout.write("Paste code here if prompted > ");+ process.stdin.resume();+ setInterval(() => {}, 1000);+} else {+ process.env.FAKE_CLAUDE_VERSION = "2.1.284";+ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-claude-cli.ts")).href)});+}+`, { mode: 0o755 });+ writeFileSync(join(home, "config.json"), JSON.stringify({ instances: { claude: { driver: "claudeAgent", displayName: "Fixture", config: { cli } } } }));+ port = await freePortBlock([0, 1]);+ base = `http://127.0.0.1:${port}`;+ await boot();+ owner = await pair();+}, hostTimeout(90_000));++afterAll(async () => {+ if (child) await waitForExit(child, { signal: "SIGTERM" });+ if (home) await removeTempDir(home);+});++it("keeps the home awake while a Claude sign-in is open, counts it with no secret, and calls a stop in the middle interrupted", async () => {+ const started = await as("POST", "/api/instances/claude/auth/start", {});+ expect(started, log.slice(-2000)).toMatchObject({ status: 200, body: { auth: { phase: "waiting" } } });+ const flowId = started.body.auth.flowId as string;+ await expect.poll(async () => (await admin("GET", "/api/cloud/power")).body.busy, { timeout: 10_000, interval: 250 }).toEqual(["maintenance"]);+ const refused = await askToSleep();+ expect(refused).toMatchObject({ status: 409, body: { ok: false, busy: ["maintenance"] } });++ // Too short to be a code: refused with its reason, and the sign-in stays open.+ const pasted = await as("POST", "/api/instances/claude/auth/complete", { flowId, code: PASTED });+ expect(pasted.status).toBeGreaterThanOrEqual(400);+ expect(pasted.body).toMatchObject({ reason: "wrong_code" });+ await sleep(500);+ expect((await askToSleep()).body.busy).toEqual(["maintenance"]);++ const health = await admin("GET", `${CLOUD_HEALTH_PATH}?after=0`);+ expect(health.status).toBe(200);+ expect(health.body.signIns).toMatchObject({ attempts: 1, open: 1, engines: [{ kind: "claudeAgent", attempts: 1, completed: 0, last: { outcome: "wrong_code" } }] });+ for (const text of [JSON.stringify(health.body), log]) {+ for (const hidden of [PASTED, LINK_SECRET, flowId, owner]) expect(text).not.toContain(hidden);+ }+ expect(log).toMatch(/sign-in: claudeAgent paste-code started/);+ expect(log).toMatch(/sign-in: claudeAgent paste-code wrong_code after (?:\d+m )?\d+s/);++ // The machine is stopped under the open sign-in (Fly's stop is a SIGTERM: the server shuts down), then boots again.+ await waitForExit(child!, { signal: "SIGTERM" });+ expect(JSON.parse(readFileSync(join(home, "sign-in-trace.json"), "utf8")).open, log.slice(-2000)).toHaveLength(1);+ log = "";+ await boot();+ expect(log).toMatch(/sign-in: claudeAgent paste-code interrupted after (?:\d+m )?\d+s \(the server restarted\)/);+ owner = await pair();+ const after = await admin("GET", `${CLOUD_HEALTH_PATH}?after=0`);+ expect(after.body.signIns).toMatchObject({ attempts: 1, open: 0, engines: [{ last: { outcome: "interrupted" } }] });+ // The screen's next poll of that flow hears why it is gone.+ const status = await as("GET", `/api/instances/claude/auth/status?flowId=${encodeURIComponent(flowId)}`);+ expect(status).toMatchObject({ status: 200, body: { auth: { phase: "failed", reason: "interrupted" } } });+ const resent = await as("POST", "/api/instances/claude/auth/complete", { flowId, code: PASTED });+ expect(resent).toMatchObject({ status: 404, body: { reason: "interrupted" } });++ // A new sign-in holds the home again; cancelling it lets the home sleep.+ const again = await as("POST", "/api/instances/claude/auth/start", {});+ expect(again.status, log.slice(-2000)).toBe(200);+ await expect.poll(async () => (await admin("GET", "/api/cloud/power")).body.busy, { timeout: 10_000, interval: 250 }).toContain("maintenance");+ expect((await as("POST", "/api/instances/claude/auth/cancel", { flowId: again.body.auth.flowId })).status).toBe(200);+ const slept = await sleepsWithin(30_000);+ expect(slept, log.slice(-2000)).toMatchObject({ status: 200, body: { ok: true } });+ const last = await admin("GET", `${CLOUD_HEALTH_PATH}?after=0`);+ expect(last.body.signIns).toMatchObject({ attempts: 2, open: 0, engines: [{ last: { outcome: "cancelled" } }] });+}, hostTimeout(150_000));diff --git a/server/contracts.ts b/server/contracts.tsindex 5d527e00d3..f9bf9d260c 100644--- a/server/contracts.ts+++ b/server/contracts.ts@@ -9,6 +9,7 @@ import type {import type { LocalModelFacts, OllamaProblem } from "../shared/local-model.ts";import type { ProviderIcon } from "../shared/provider-icon.ts";import type { ContextBreakdown } from "../shared/context-breakdown.ts";+import type { SignInOutcome } from "../shared/sign-in-outcome.ts";export type { CloudBackend, EffortLevel, ModelSelection } from "../shared/wire.ts";export type {@@ -534,6 +535,9 @@ export interface ProviderAuthenticationStatus extends Omit<ProviderAuthenticatiophase: "waiting" | "verifying" | "succeeded" | "failed" | "expired" | "cancelled";/** Safe, actionable copy; never unfiltered CLI output or credentials. */message?: string;+ /** Why it ended, as a fixed code (shared/sign-in-outcome.ts), where the engine's sign-in knows; `interrupted` for a+ * sign-in the server's stop or restart cut short. Absent on `waiting`, `verifying` and `succeeded`. */+ reason?: SignInOutcome;}export interface ModelCatalog {diff --git a/server/drivers/claude-login-auth.ts b/server/drivers/claude-login-auth.tsindex 30dc93e252..53cf40bac4 100644--- a/server/drivers/claude-login-auth.ts+++ b/server/drivers/claude-login-auth.ts@@ -9,6 +9,7 @@ import { homedir } from "node:os";import { isAbsolute, join, resolve } from "node:path";import { stripVTControlCharacters } from "node:util";import type { ProviderAuthenticationStart, ProviderAuthenticationStatus } from "../contracts.ts";+import { withSignInReason, type SignInOutcome } from "../../shared/sign-in-outcome.ts";import { killCliTree, spawnCli } from "../procs.ts";import { canonicalPath } from "./device-auth.ts";@@ -121,10 +122,10 @@ export class ClaudeLoginController {homeKey,env,startupTimer: setTimeout(- () => this.finish(flow, "failed", "Claude Code did not show a sign-in link in time. Check that it is installed and up to date on the server, then try again."),+ () => this.finish(flow, "failed", "Claude Code did not show a sign-in link in time. Check that it is installed and up to date on the server, then try again.", "timed_out"),this.options.startupTimeoutMs ?? 30_000,),- expiryTimer: setTimeout(() => this.finish(flow, "expired", "The Claude sign-in link expired. Start sign-in again."), this.options.lifetimeMs ?? 15 * 60_000),+ expiryTimer: setTimeout(() => this.finish(flow, "expired", "The Claude sign-in link expired. Start sign-in again.", "expired"), this.options.lifetimeMs ?? 15 * 60_000),};flow.startupTimer.unref();flow.expiryTimer.unref();@@ -147,7 +148,7 @@ export class ClaudeLoginController {if (flow.status.phase !== "waiting" || !flow.ready) throw new Error(NOT_AVAILABLE);if (flow.codeSent) throw new Error("A code was already sent for this sign-in. Wait for the result, or cancel and start again.");const code = claudeLoginCode(pasted);- if (!code) throw new Error("Paste the whole code shown on Anthropic's page after signing in.");+ if (!code) throw withSignInReason(new Error("Paste the whole code shown on Anthropic's page after signing in."), "wrong_code");const child = flow.child;const stdin = child?.stdin;if (!child || !stdin || child.exitCode !== null || child.signalCode !== null) throw new Error(NOT_AVAILABLE);@@ -155,12 +156,12 @@ export class ClaudeLoginController {await new Promise<void>((resolveDone, rejectDone) => {flow.completion = { resolve: resolveDone, reject: rejectDone };const timer = setTimeout(- () => this.finish(flow, "failed", "Claude Code did not finish the sign-in after the code was entered. Start sign-in again."),+ () => this.finish(flow, "failed", "Claude Code did not finish the sign-in after the code was entered. Start sign-in again.", "timed_out"),this.options.completeTimeoutMs ?? 60_000,);timer.unref();stdin.write(`${code}\n`, (error) => {- if (error) this.finish(flow, "failed", "The code could not be handed to Claude Code on the server. Start sign-in again.");+ if (error) this.finish(flow, "failed", "The code could not be handed to Claude Code on the server. Start sign-in again.", "failed");});});}@@ -171,7 +172,7 @@ export class ClaudeLoginController {}async cancel(): Promise<void> {- if (this.flow?.status.phase === "waiting") this.finish(this.flow, "cancelled", "Claude sign-in cancelled.");+ if (this.flow?.status.phase === "waiting") this.finish(this.flow, "cancelled", "Claude sign-in cancelled.", "cancelled");await this.flow?.stopping;if (this.flow?.terminationFailed) throw new Error(this.flow.status.message);if (this.logoutChild && !await this.stopChild(this.logoutChild)) {@@ -318,14 +319,14 @@ export class ClaudeLoginController {stdio: ["pipe", "pipe", "pipe"],});} catch {- this.finish(flow, "failed", "Claude Code could not start on this server. Install or update the configured Claude CLI, then try again.");+ this.finish(flow, "failed", "Claude Code could not start on this server. Install or update the configured Claude CLI, then try again.", "failed");return;}flow.child = child;const receive = (chunk: Buffer) => {if (flow.status.phase !== "waiting") return;if (flow.output.length + chunk.length > MAX_OUTPUT) {- this.finish(flow, "failed", "Claude Code returned an unexpected sign-in response. Update the server's Claude CLI and try again.");+ this.finish(flow, "failed", "Claude Code returned an unexpected sign-in response. Update the server's Claude CLI and try again.", "failed");return;}flow.output += chunk.toString("utf8");@@ -343,7 +344,7 @@ export class ClaudeLoginController {const message = error.code === "ENOENT"? "Claude Code is not installed on this server. Install it on the server, then try again.": "Claude Code could not start on this server. Check the configured CLI path and its executable permissions.";- this.finish(flow, "failed", message);+ this.finish(flow, "failed", message, error.code === "ENOENT" ? "not_installed" : "failed");});child.once("close", (code) => {if (flow.child === child) flow.child = null;@@ -356,18 +357,20 @@ export class ClaudeLoginController {this.finish(flow, "succeeded");return;}+ const refused = flow.codeSent && /invalid|expired|denied|rejected/i.test(output);this.finish(flow, "failed", flow.codeSent- ? /invalid|expired|denied|rejected/i.test(output)+ ? refused? "Anthropic did not accept that code. Start sign-in again and paste the whole code it shows.": "Claude Code finished but is not signed in. Start sign-in again.": code === 0? "Claude Code finished but is not signed in. Start sign-in again."- : "Claude Code stopped before the sign-in finished. Check the server's connection and try again.");+ : "Claude Code stopped before the sign-in finished. Check the server's connection and try again.", refused ? "refused" : "exited");});});}- private finish(flow: Flow, phase: Exclude<ProviderAuthenticationStatus["phase"], "waiting">, message?: string): void {+ /** `reason`: why it ended, as a fixed code, on the status and on the error a waiting start or code gets. */+ private finish(flow: Flow, phase: Exclude<ProviderAuthenticationStatus["phase"], "waiting">, message?: string, reason?: SignInOutcome): void {if (flow.status.phase !== "waiting") return;clearTimeout(flow.startupTimer);clearTimeout(flow.expiryTimer);@@ -377,15 +380,20 @@ export class ClaudeLoginController {authorizationUrl: null,expiresAt: null,...(phase !== "succeeded" && message ? { message } : {}),+ ...(phase !== "succeeded" && reason ? { reason } : {}),};flow.output = "";+ const failure = () => {+ const error = new Error(message ?? "Claude sign-in did not finish.");+ return reason ? withSignInReason(error, reason) : error;+ };if (!flow.ready) {if (phase === "succeeded") flow.resolve({ ...flow.status, phase });- else flow.reject(new Error(message ?? "Claude sign-in did not finish."));+ else flow.reject(failure());}if (flow.completion) {if (phase === "succeeded") flow.completion.resolve();- else flow.completion.reject(new Error(message ?? "Claude sign-in did not finish."));+ else flow.completion.reject(failure());flow.completion = undefined;}flow.stopping = this.stopChild(flow.child)@@ -397,7 +405,7 @@ export class ClaudeLoginController {return;}flow.terminationFailed = true;- flow.status = { ...flow.status, phase: "failed", message: "Claude Code could not be stopped on this server. Ask the server administrator to stop the login process before trying again." };+ flow.status = { ...flow.status, phase: "failed", message: "Claude Code could not be stopped on this server. Ask the server administrator to stop the login process before trying again.", reason: "failed" };const child = flow.child;if (!child || child.exitCode !== null || child.signalCode !== null) release();else child.once("close", release);diff --git a/server/drivers/codex-device-auth.ts b/server/drivers/codex-device-auth.tsindex 2448cbb4f3..c699b9bf15 100644--- a/server/drivers/codex-device-auth.ts+++ b/server/drivers/codex-device-auth.ts@@ -1,5 +1,6 @@// Codex's device-code sign-in: `codex login --device-auth`, `codex login status` to keep and confirm a login, `codex logout`.import { stripVTControlCharacters } from "node:util";+import type { SignInOutcome } from "../../shared/sign-in-outcome.ts";import { deviceSignInPrompt } from "../../shared/device-sign-in.ts";import { DeviceAuthController, type DeviceAuthOptions, type DeviceSignIn } from "./device-auth.ts";import { codexReportsLogin } from "./codex-login.ts";@@ -22,6 +23,13 @@ function loginFailure(output: string): string {return "ChatGPT sign-in did not finish. Check the server's connection and that device-code login is enabled in ChatGPT, then try again.";}+/** `loginFailure` as a fixed code: an expired code, device sign-in refused by the account's settings, else the command ended. */+function loginFailureReason(output: string): SignInOutcome {+ if (/device.{0,40}(disabled|not enabled|not allowed)|enable.{0,40}device/i.test(output)) return "refused";+ if (/expired|expiration|timed out/i.test(output)) return "expired";+ return "exited";+}+export const CODEX_DEVICE_SIGN_IN: DeviceSignIn = {provider: "codex",product: "Codex",@@ -31,6 +39,7 @@ export const CODEX_DEVICE_SIGN_IN: DeviceSignIn = {loginArgs: ["login", "--device-auth"],install: "Run npm install -g @openai/codex@latest on the server, then try again.",failure: loginFailure,+ failureReason: loginFailureReason,status: {args: ["login", "status"],read: (code, output) =>diff --git a/server/drivers/device-auth.ts b/server/drivers/device-auth.tsindex 8479b5ac57..2eea368bd9 100644--- a/server/drivers/device-auth.ts+++ b/server/drivers/device-auth.ts@@ -8,6 +8,7 @@ import { homedir } from "node:os";import { basename, dirname, isAbsolute, join, resolve } from "node:path";import { stripVTControlCharacters } from "node:util";import { deviceSignInPrompt, type DeviceSignInProvider } from "../../shared/device-sign-in.ts";+import { withSignInReason, type SignInOutcome } from "../../shared/sign-in-outcome.ts";import type { ProviderAuthenticationStart, ProviderAuthenticationStatus } from "../contracts.ts";import { killCliTree, spawnCli } from "../procs.ts";@@ -40,6 +41,8 @@ export interface DeviceSignIn {install: string;/** One safe sentence for a failed login command; never the CLI's own words, which may carry tokens. */failure(output: string): string;+ /** The same as a fixed code (shared/sign-in-outcome.ts); unset: `exited`. */+ failureReason?(output: string): SignInOutcome;/** Checked before a sign-in, so a working one is never replaced, and after it to confirm. */status?: { args: readonly string[]; read(code: number | null, output: string): DeviceSignInState };/** Without a status command: whether the sign-in a turn uses is now there. */@@ -134,21 +137,21 @@ export class DeviceAuthController {expiresAt: new Date(Date.now() + (this.options.lifetimeMs ?? 15 * 60_000)).toISOString(),},child: null, ready: false, resolve: resolveStart, reject, homeKey,- startupTimer: setTimeout(() => this.finish(flow, "failed", `${product} did not provide a sign-in code in time. Check the server connection and update ${product}, then try again.`), this.options.startupTimeoutMs ?? 30_000),- expiryTimer: setTimeout(() => this.finish(flow, "expired", `The ${account} sign-in code expired. Start sign-in again.`), this.options.lifetimeMs ?? 15 * 60_000),+ startupTimer: setTimeout(() => this.finish(flow, "failed", `${product} did not provide a sign-in code in time. Check the server connection and update ${product}, then try again.`, "timed_out"), this.options.startupTimeoutMs ?? 30_000),+ expiryTimer: setTimeout(() => this.finish(flow, "expired", `The ${account} sign-in code expired. Start sign-in again.`, "expired"), this.options.lifetimeMs ?? 15 * 60_000),};flow.startupTimer.unref();flow.expiryTimer.unref();this.flow = flow;const login = () => this.run(flow, [...this.spec.loginArgs], env, home, (loginCode, loginOutput) => {if (loginCode !== 0 || !flow.ready) {- this.finish(flow, "failed", this.spec.failure(loginOutput));+ this.finish(flow, "failed", this.spec.failure(loginOutput), this.spec.failureReason?.(loginOutput) ?? "exited");return;}- flow.startupTimer = setTimeout(() => this.finish(flow, "failed", `${product} finished sign-in but could not confirm the account. Refresh Settings and try again.`), this.options.startupTimeoutMs ?? 30_000);+ flow.startupTimer = setTimeout(() => this.finish(flow, "failed", `${product} finished sign-in but could not confirm the account. Refresh Settings and try again.`, "timed_out"), this.options.startupTimeoutMs ?? 30_000);flow.startupTimer.unref();this.confirm(flow, env, home, (signedIn) => this.finish(flow, signedIn ? "succeeded" : "failed",- `${product} finished sign-in but did not confirm a ${account} account. Refresh Settings and try again.`));+ `${product} finished sign-in but did not confirm a ${account} account. Refresh Settings and try again.`, signedIn ? undefined : "failed"));}, true);// Never overwrite a working login; one the provider refused is not working, whatever status says.if (!status) { login(); return; }@@ -156,8 +159,8 @@ export class DeviceAuthController {const state = status.read(code, output);if (state === "signed-in" && !this.options.signInRejected?.()) this.finish(flow, "succeeded");else if (state === "signed-in" || state === "signed-out") login();- else if (state === "other") this.finish(flow, "failed", `${product} already has a different sign-in method on this server. Ask the server administrator to review it before changing accounts.`);- else this.finish(flow, "failed", `${product} could not confirm the existing sign-in on this server. Update ${product} and check its login status before trying again.`);+ else if (state === "other") this.finish(flow, "failed", `${product} already has a different sign-in method on this server. Ask the server administrator to review it before changing accounts.`, "failed");+ else this.finish(flow, "failed", `${product} could not confirm the existing sign-in on this server. Update ${product} and check its login status before trying again.`, "failed");});});}@@ -168,7 +171,7 @@ export class DeviceAuthController {}async cancel(): Promise<void> {- if (this.flow?.status.phase === "waiting") this.finish(this.flow, "cancelled", `${this.spec.account} sign-in cancelled.`);+ if (this.flow?.status.phase === "waiting") this.finish(this.flow, "cancelled", `${this.spec.account} sign-in cancelled.`, "cancelled");await this.flow?.stopping;if (this.flow?.terminationFailed) throw new Error(this.flow.status.message);if (this.command && !await this.stopChild(this.command)) {@@ -312,7 +315,7 @@ export class DeviceAuthController {try {child = spawnCli(this.options.cli, args, { env: { ...env, NO_COLOR: "1", ...this.spec.env }, cwd, stdio: ["pipe", "pipe", "pipe"] });} catch {- this.finish(flow, "failed", `${product} could not start on this server. Install or update the configured ${product} CLI, then try again.`);+ this.finish(flow, "failed", `${product} could not start on this server. Install or update the configured ${product} CLI, then try again.`, "failed");return;}flow.child = child;@@ -321,7 +324,7 @@ export class DeviceAuthController {const receive = (chunk: Buffer) => {if (flow.status.phase !== "waiting") return;if (output.length + chunk.length > MAX_OUTPUT) {- this.finish(flow, "failed", `${product} returned an unexpected sign-in response. Update the server's ${product} CLI and try again.`);+ this.finish(flow, "failed", `${product} returned an unexpected sign-in response. Update the server's ${product} CLI and try again.`, "failed");return;}output += chunk.toString("utf8");@@ -336,7 +339,7 @@ export class DeviceAuthController {};child.stdout.on("data", receive);child.stderr.on("data", receive);- child.once("error", (error: NodeJS.ErrnoException) => this.finish(flow, "failed", this.startFailure(error)));+ child.once("error", (error: NodeJS.ErrnoException) => this.finish(flow, "failed", this.startFailure(error), error.code === "ENOENT" ? "not_installed" : "failed"));child.once("close", (code) => {if (flow.child === child) flow.child = null;if (flow.status.phase === "waiting") done(code, stripVTControlCharacters(output));@@ -344,7 +347,8 @@ export class DeviceAuthController {});}- private finish(flow: Flow, phase: Exclude<ProviderAuthenticationStatus["phase"], "waiting">, message?: string): void {+ /** `reason`: why it ended, as a fixed code, on the status and on the error a waiting start gets. */+ private finish(flow: Flow, phase: Exclude<ProviderAuthenticationStatus["phase"], "waiting">, message?: string, reason?: SignInOutcome): void {const { product, account } = this.spec;if (flow.status.phase !== "waiting") return;clearTimeout(flow.startupTimer);@@ -352,16 +356,20 @@ export class DeviceAuthController {flow.status = {phase, flowId: flow.status.flowId, authorizationUrl: null, expiresAt: null,...(phase !== "succeeded" && message ? { message } : {}),+ ...(phase !== "succeeded" && reason ? { reason } : {}),};if (!flow.ready) {if (phase === "succeeded") flow.resolve({ ...flow.status, phase });- else flow.reject(new Error(message ?? `${account} sign-in did not finish.`));+ else {+ const error = new Error(message ?? `${account} sign-in did not finish.`);+ flow.reject(reason ? withSignInReason(error, reason) : error);+ }}flow.stopping = this.stopChild(flow.child).catch(() => false).then((stopped) => {const release = () => authenticatingHomes.delete(flow.homeKey);if (stopped) { release(); return; }flow.terminationFailed = true;- flow.status = { ...flow.status, phase: "failed", message: `${product} could not be stopped on this server. Ask the server administrator to stop the login process before trying again.` };+ flow.status = { ...flow.status, phase: "failed", message: `${product} could not be stopped on this server. Ask the server administrator to stop the login process before trying again.`, reason: "failed" };// Retain the credential-home lock until the OS actually reports exit.const child = flow.child;if (!child || child.exitCode !== null || child.signalCode !== null) release();diff --git a/server/harness/registry.ts b/server/harness/registry.tsindex ff1f4ffc57..4de9a88cf1 100644--- a/server/harness/registry.ts+++ b/server/harness/registry.ts@@ -18,6 +18,7 @@ import { withTurnScope } from "../crash-guard.ts";import { withWslNotice } from "./wsl-launch.ts";import { modelManifest, startModelManifestRefresh } from "../model-manifest/manifest.ts";import { machinePressure } from "../machine-pressure.ts";+import { signInMethodOf } from "../sign-in-trace.ts";export { engineMemory } from "../engine-memory.ts";import { clientInstall } from "../contracts.ts";import type {@@ -63,11 +64,9 @@ function withServerInstall(install: AnyProviderDriver["install"], npmPresent: boexport function signInOf(inst: ProviderInstance) {return inst.startAuthentication? {- method: inst.authenticationMethod ?? (inst.getAuthentication && inst.completeAuthentication- ? "paste-code" as const // a link to open, then a code pasted back (Claude)- : inst.getAuthentication- ? "device-code" as const // a code to enter at the provider's page (Codex)- : "callback-url" as const), // a link and a callback URL (managed engines)+ // Named, else a link then a code pasted back (Claude), a code to enter at the provider's page (Codex), or a link+ // and a callback URL (managed engines).+ method: signInMethodOf(inst),signOut: inst.signOut !== undefined,}: undefined;diff --git a/server/index.ts b/server/index.tsindex dda759277f..62b4a44592 100644--- a/server/index.ts+++ b/server/index.ts@@ -523,7 +523,7 @@ import { repairMovedWorkspacePaths } from "./moved-paths-repair.ts";import { createCustomDomainVerifier, customDomainIpv4, normalizeCustomDomain } from "./custom-domain.ts";import { allowedScopes, createEmailSignIn, parseAllowList } from "./account-signin.ts";import { pairingLinkBase, signInMailTarget } from "./pairing-base.ts"; import { lanUrl, listenHost } from "./lan-address.ts"; import { createTailnetShare } from "./tailnet-listener.ts";-import { ProviderAuthSessions } from "./provider-auth-sessions.ts";+import { ProviderAuthSessions } from "./provider-auth-sessions.ts"; import { createSignInTrace } from "./sign-in-trace.ts";import {clearSessionCookie,isLoopbackHost,@@ -1352,7 +1352,7 @@ const attributeUsage = createUsageAttribution({ section: (botId) => store.bot(bo} usageCapGate.booked(row.botId);}-const providerAuthSessions = new ProviderAuthSessions({ signedIn: (instanceId) => signInResume.appSignedIn(instanceId) }); const mcpServersHost = createMcpServersHost({ dataDir: DATA_DIR, cfg: () => cfg, personMcp: () => teamConnections.personMcp(), botsPath: () => brokerPath(botBox), moveGrants: (bot, move) => moveSavedGrants(store, bot, move), persist: persistMcpServers, bots: () => store.bots, policy: (servers) => managedPolicy.filterMcp(servers), tell: (text, about) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), startsServers: (botId) => { const bot = store.bot(botId); return Boolean(bot && registry.get(bot.modelSelection.instanceId)?.adapter.capabilities.customMcp === true); }, boxed: () => botBox.enabled(), keys: mcpKeys, forgetSignIn: (name) => mcpOAuth.forget(name) });+const signInTrace = CLOUD_HOME ? createSignInTrace({ dataDir: DATA_DIR, wokeFromSleep: () => startedFromSleep }) : null; const providerAuthSessions = new ProviderAuthSessions({ signedIn: (instanceId) => signInResume.appSignedIn(instanceId), trace: signInTrace }); const mcpServersHost = createMcpServersHost({ dataDir: DATA_DIR, cfg: () => cfg, personMcp: () => teamConnections.personMcp(), botsPath: () => brokerPath(botBox), moveGrants: (bot, move) => moveSavedGrants(store, bot, move), persist: persistMcpServers, bots: () => store.bots, policy: (servers) => managedPolicy.filterMcp(servers), tell: (text, about) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), startsServers: (botId) => { const bot = store.bot(botId); return Boolean(bot && registry.get(bot.modelSelection.instanceId)?.adapter.capabilities.customMcp === true); }, boxed: () => botBox.enabled(), keys: mcpKeys, forgetSignIn: (name) => mcpOAuth.forget(name) });const mcpOAuth = new McpOAuthManager({file: join(DATA_DIR, "mcp-oauth.json"),isOwnerLive: (owner) => owner === "loopback" || sessions.isLive(owner) || isCardOwnerLive(store, owner),@@ -2780,7 +2780,7 @@ const phones = createPhones({active: (turn) => internalCapabilityIsActive(turn as InternalCapability),});const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => { broadcast({ kind: "config", ...configStatus() }); pausesChanged(); } }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, laneOwned: (threadId) => burst.laneOwned(threadId), botName: (botId) => store.bot(botId)?.name, routineThread: (botId, threadId) => { const run = activeRoutineRunForThread(threadId); return run?.botId === botId && run.target === "bot"; }, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); let starterRoutineWake: StarterRoutineWake | undefined; /* made beside tieAutomationsToBots, once the routines and triggers are */ const botHolds = createBotHolds({ dataDir: DATA_DIR, bots: () => store.bots, line: (language, key, params) => serverLine(language, key, params), changed: () => { broadcast({ kind: "config", ...configStatus() }); pausesChanged(); } }); /** A bot was paused or woken: the other places of the link hear it (server/bot-link/link.ts; nothing while the link is off). */ function pausesChanged() { try { botLink.link.botsChanged(); } catch { /* the link is made further down; nothing to tell before it is */ } } let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.-const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, perf: perf.health, storage: () => withCacheCounters(perf.storage(), cacheSweeper), dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE, routines: (cap) => routines?.health(cap) ?? [], schedule: () => routines?.scheduleReport() ?? null,+const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, perf: perf.health, signIns: () => signInTrace?.summary() ?? null, storage: () => withCacheCounters(perf.storage(), cacheSweeper), dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE, routines: (cap) => routines?.health(cap) ?? [], schedule: () => routines?.scheduleReport() ?? null,engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),connectors: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount(), cloudComputer: cloudBrowserReport() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.roomReport() } : {}) } });@@ -15116,7 +15116,7 @@ if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATAbotLink.start(); let pausedSent = starterAwake.paused().join(); store.onChange((change) => { if (change.type === "bot.deleted") botHolds.forget("bot", change.botId); if (change.type !== "bot" && change.type !== "bot.deleted") return; const paused = starterAwake.paused().join(); if (paused !== pausedSent) { pausedSent = paused; broadcast({ kind: "config", ...configStatus() }); } });server.listen(PORT, listenHost(server), async () => {- companyRuntimeReady(); cloudHealth?.speed.ready(); void tailnetShare.start(process.env);+ companyRuntimeReady(); cloudHealth?.speed.ready(); signInTrace?.recover(); void tailnetShare.start(process.env);console.log(`openmausbot server on http://127.0.0.1:${PORT}`); launchListening();personWaits.boot(); handoffRequests.boot(); browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); startCloudTeamRoster({ cloudHome: CLOUD_HOME, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, ownKey: () => composio.connectionMode(cfg) === "self-hosted", apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });void afterFirstEngineRead().then(() => { if (builtInBrowserEnabled(cfg)) chromeLauncher.start(); checkpointSeeds.start(); });@@ -15181,7 +15181,7 @@ const gracefulShutdown = createGracefulShutdown({companyShutdown = true;// Before any provider is torn down, so what the teardown fails stays cut for the next start.coordinator.close(); botLink.close(); checkpointSeeds.stop(); checkpoints.stopCollections();- noteTurnsCutByShutdown();+ noteTurnsCutByShutdown(); signInTrace?.stopping();if (workspaceAccessTimer) clearInterval(workspaceAccessTimer);// Invalidate turn bearers before any cleanup reaches an await: child MCP processes and the listener may outlive it.revokeAllInternalCapabilities();diff --git a/server/provider-auth-sessions.ts b/server/provider-auth-sessions.tsindex 4cfe248d71..5895b5521f 100644--- a/server/provider-auth-sessions.ts+++ b/server/provider-auth-sessions.ts@@ -1,7 +1,13 @@// An in-progress login belongs to the admin session that started it: never put its device code on global SSE.-import type { ProviderAuthenticationStart, ProviderInstance } from "./contracts.ts";+// While one is under way (`active`) a Cloud home reports itself busy (`maintenance`, server/cloud-power.ts), so it never+// sleeps under a login process; a flow that is abandoned stops counting at its own expiry (at most 15 minutes for every engine).+// On a Cloud home each attempt and its outcome also go to the sign-in trace (server/sign-in-trace.ts): codes, never secrets.+import { signInOutcome, signInReasonOf, withSignInReason, type SignInOutcome } from "../shared/sign-in-outcome.ts";+import type { ProviderAuthenticationStart, ProviderAuthenticationStatus, ProviderInstance } from "./contracts.ts";+import { signInMethodOf, type SignInAttempt, type SignInInterruption, type SignInTrace } from "./sign-in-trace.ts";-type LoginInstance = Pick<ProviderInstance, "instanceId" | "startAuthentication" | "getAuthentication" | "completeAuthentication" | "cancelAuthentication" | "signOut">;+type LoginInstance = Pick<ProviderInstance, "instanceId" | "startAuthentication" | "getAuthentication" | "completeAuthentication" | "cancelAuthentication" | "signOut">+ & Partial<Pick<ProviderInstance, "driverKind" | "authenticationMethod">>;type Flow = {instance: LoginInstance;owner: string;@@ -13,51 +19,99 @@ type Flow = {revision: number;/** Its success was told: a client reading the finished flow again is not another sign-in. */told?: true;+ /** Its entry in the sign-in trace; null where there is no trace (a desktop). */+ attempt: SignInAttempt | null;+ /** Its expiry was noticed and the engine is being asked how it ended. */+ settling?: true;};const failure = (message: string, status: number) => Object.assign(new Error(message), { status });+const INTERRUPTED = "This sign-in was interrupted because the server stopped. Start sign-in again.";+const finished = (phase: ProviderAuthenticationStatus["phase"]) => phase !== "waiting" && phase !== "verifying";+/** How a finished status ended, as a code: the engine's own reason when it gives one. */+function outcomeOf(status: Pick<ProviderAuthenticationStatus, "phase" | "reason">): SignInOutcome {+ if (status.phase === "succeeded") return "completed";+ return signInOutcome(status.reason) ?? (status.phase === "expired" ? "expired" : status.phase === "cancelled" ? "cancelled" : "failed");+}export class ProviderAuthSessions {private readonly flows = new Map<string, Flow>();/** A sign-in to this AI finished: whatever waited on it being signed out may use it again. */private readonly signedIn: (instanceId: string) => void;+ private readonly trace: SignInTrace | null;+ private readonly now: () => number;- constructor(options: { signedIn?: (instanceId: string) => void } = {}) {+ constructor(options: { signedIn?: (instanceId: string) => void; trace?: SignInTrace | null; now?: () => number } = {}) {this.signedIn = options.signedIn ?? (() => {});+ this.trace = options.trace ?? null;+ this.now = options.now ?? Date.now;}/** A sign-in under way, until it expires: one whose provider call never returns stops counting then too. */get active(): boolean {- return [...this.flows.values()].some((flow) => flow.expiresAt > Date.now() && (flow.busy || !flow.revoked));+ const at = this.now();+ if (this.trace) for (const flow of this.flows.values()) if (flow.expiresAt <= at && !flow.busy) this.settleLate(flow);+ return [...this.flows.values()].some((flow) => flow.expiresAt > at && (flow.busy || !flow.revoked));+ }++ /** A flow that ran out without anyone reading it (a pasted-code screen does not poll): its outcome is the engine's, else expired. */+ private settleLate(flow: Flow): void {+ const attempt = flow.attempt;+ if (!attempt || attempt.ended || flow.settling) return;+ flow.settling = true;+ const { flowId, instance } = flow;+ // Read on a later tick and caught either way: this runs inside `active`, the power probe, which must never throw.+ void Promise.resolve()+ .then(() => flowId && instance.getAuthentication ? instance.getAuthentication(flowId) : null)+ .catch(() => null)+ .then((status) => attempt.end(status && finished(status.phase) ? outcomeOf(status) : "expired"))+ .catch(() => {});+ }++ private end(flow: Flow | undefined, outcome: SignInOutcome, by?: SignInInterruption): void {+ flow?.attempt?.end(outcome, by);}async start(instance: LoginInstance, owner: string): Promise<ProviderAuthenticationStart> {if (!instance.startAuthentication) throw failure("Account setup is unavailable for this provider.", 404);const existing = this.flows.get(instance.instanceId);- if (existing && (existing.busy || (existing.owner !== owner && existing.expiresAt > Date.now()))) {+ if (existing && (existing.busy || (existing.owner !== owner && existing.expiresAt > this.now()))) {throw failure("A sign-in is already in progress. Finish or cancel it in the browser that started it, or wait for it to expire.", 409);}- const resuming = existing && existing.owner === owner && existing.expiresAt > Date.now() && !existing.revoked;- const flow: Flow = resuming ? existing : { instance, owner, flowId: null, expiresAt: Date.now() + 15 * 60_000, busy: false, starting: false, revoked: false, revision: 0 };+ const resuming = existing && existing.owner === owner && existing.expiresAt > this.now() && !existing.revoked;+ if (existing && !resuming) this.settleLate(existing);+ const flow: Flow = resuming ? existing : { instance, owner, flowId: null, expiresAt: this.now() + 15 * 60_000, busy: false, starting: false, revoked: false, revision: 0, attempt: null };flow.busy = true;flow.starting = true;this.flows.set(instance.instanceId, flow);+ let begun = false;try {+ // The engine's flow behind a resumed one may have ended unread (its login command exited): that attempt is over.+ if (this.trace && resuming && flow.attempt && !flow.attempt.ended && flow.flowId && instance.getAuthentication) {+ const prior = await instance.getAuthentication(flow.flowId).catch(() => null);+ if (!prior || finished(prior.phase)) flow.attempt.end(prior ? outcomeOf(prior) : "failed");+ }+ if (this.trace && (!flow.attempt || flow.attempt.ended)) { flow.attempt = this.trace.begin(instance.driverKind, signInMethodOf(instance)); begun = true; }const result = await instance.startAuthentication();if (flow.revoked || this.flows.get(instance.instanceId) !== flow) {await instance.cancelAuthentication?.();throw failure("Sign-in cancelled because the session or provider changed.", 409);}flow.flowId = result.flowId;+ if (result.flowId) flow.attempt?.opened(instance.instanceId, result.flowId);const expiry = Date.parse(result.expiresAt ?? "");if (Number.isFinite(expiry)) flow.expiresAt = expiry;if (result.phase === "succeeded") {this.flows.delete(instance.instanceId);+ this.end(flow, "completed");this.signedIn(instance.instanceId);}return result;} catch (error) {if ((!resuming || flow.revoked) && this.flows.get(instance.instanceId) === flow) this.flows.delete(instance.instanceId);+ if (begun || !resuming || flow.revoked || this.flows.get(instance.instanceId) !== flow) this.end(flow, flow.revoked ? "interrupted" : signInReasonOf(error) ?? "failed", flow.revoked ? "session" : undefined);+ // A resumed flow whose engine flow had ended, and whose new one did not start: nothing is open any more.+ if (begun && resuming) flow.expiresAt = 0;throw error;} finally {flow.busy = false;@@ -68,19 +122,31 @@ export class ProviderAuthSessions {private owned(instanceId: string, owner: string, flowId: string): Flow {const flow = this.flows.get(instanceId);if (!flowId || !flow || flow.revoked || flow.owner !== owner || flow.flowId !== flowId) {+ if (this.cutShort(instanceId, flowId)) throw withSignInReason(failure(INTERRUPTED, 404), "interrupted");throw failure("This sign-in is no longer available in this browser. Start a new sign-in.", 404);}if (flow.busy) throw failure("The sign-in is still being updated. Try again shortly.", 409);return flow;}- async status(instanceId: string, owner: string, flowId: string) {+ /** This flow was open when the server last stopped (a restart, a stop for sleep) and is not the one under way now. */+ private cutShort(instanceId: string, flowId: string): boolean {+ return Boolean(this.trace?.interrupted(instanceId, flowId)) && this.flows.get(instanceId)?.flowId !== flowId;+ }++ async status(instanceId: string, owner: string, flowId: string): Promise<ProviderAuthenticationStatus> {+ // The screen polling a flow the server's stop cut short hears why, as a finished status. No `message`: the screen words+ // `reason` in the person's own language.+ if (this.cutShort(instanceId, flowId)) return { phase: "failed", flowId, authorizationUrl: null, expiresAt: null, reason: "interrupted" };const flow = this.owned(instanceId, owner, flowId);if (!flow.instance.getAuthentication) throw failure("Sign-in status is unavailable for this provider.", 404);const revision = flow.revision;const status = await flow.instance.getAuthentication(flowId);if (flow.revoked || this.flows.get(instanceId) !== flow || flow.flowId !== flowId || flow.revision !== revision) throw failure("This sign-in session ended.", 404);- if (status.phase !== "waiting" && status.phase !== "verifying") flow.expiresAt = 0;+ if (finished(status.phase)) {+ flow.expiresAt = 0;+ this.end(flow, outcomeOf(status));+ }if (status.phase === "succeeded" && !flow.told) {flow.told = true;this.signedIn(instanceId);@@ -93,33 +159,56 @@ export class ProviderAuthSessions {if (!flow.instance.completeAuthentication) throw failure("This provider does not use a callback URL.", 400);flow.busy = true;try {- await flow.instance.completeAuthentication(flowId, callbackUrl);+ try {+ await flow.instance.completeAuthentication(flowId, callbackUrl);+ } catch (error) {+ if (this.trace && !flow.revoked && this.flows.get(instanceId) === flow) await this.afterRefusedCode(flow, flowId, error);+ throw error;+ }if (flow.revoked || this.flows.get(instanceId) !== flow) throw failure("This sign-in session ended.", 404);this.flows.delete(instanceId);+ this.end(flow, "completed");this.signedIn(instanceId);} finally { flow.busy = false; }}+ /** A code the engine did not take, on a Cloud home (with a trace): a sign-in it ended (the provider refused it, the command+ * exited) is over and no longer keeps the home awake; one still waiting (a pasted code that is not a code) stays open for+ * another try. A desktop keeps its flow until it is read or expires, as before. */+ private async afterRefusedCode(flow: Flow, flowId: string, error: unknown): Promise<void> {+ const reason = signInReasonOf(error);+ const after = flow.instance.getAuthentication ? await flow.instance.getAuthentication(flowId).catch(() => null) : null;+ if (after && finished(after.phase)) {+ flow.expiresAt = 0;+ this.end(flow, signInOutcome(after.reason) ?? reason ?? outcomeOf(after));+ } else if (reason) flow.attempt?.note(reason);+ }+async cancel(instanceId: string, owner: string, flowId: string) {+ // Nothing is left to cancel of a flow the server's stop cut short.+ if (this.cutShort(instanceId, flowId)) return;const flow = this.owned(instanceId, owner, flowId);flow.busy = true;// Invalidate polls already in flight, but let a later poll read the provider's cancelled status.flow.revision++;try { await flow.instance.cancelAuthentication?.(); }- finally { flow.busy = false; flow.expiresAt = 0; }+ finally { flow.busy = false; flow.expiresAt = 0; this.end(flow, "cancelled"); }}/** Never pulls a login another admin is completing, and no one may start one while the credential is being removed. */async signOut(instance: LoginInstance, owner: string): Promise<void> {if (!instance.signOut) throw failure("Sign-out is unavailable for this provider.", 404);const existing = this.flows.get(instance.instanceId);- if (existing && (existing.busy || (existing.owner !== owner && existing.expiresAt > Date.now() && !existing.revoked))) {+ if (existing && (existing.busy || (existing.owner !== owner && existing.expiresAt > this.now() && !existing.revoked))) {throw failure("A sign-in is in progress. Finish or cancel it in the browser that started it, or wait for it to expire.", 409);}- const flow: Flow = { instance, owner, flowId: null, expiresAt: Date.now() + 60_000, busy: true, starting: false, revoked: false, revision: 0 };+ const flow: Flow = { instance, owner, flowId: null, expiresAt: this.now() + 60_000, busy: true, starting: false, revoked: false, revision: 0, attempt: null };this.flows.set(instance.instanceId, flow);try {- if (existing) await existing.instance.cancelAuthentication?.();+ if (existing) {+ this.end(existing, "cancelled");+ await existing.instance.cancelAuthentication?.();+ }await instance.signOut();} finally {if (this.flows.get(instance.instanceId) === flow) this.flows.delete(instance.instanceId);@@ -132,6 +221,7 @@ export class ProviderAuthSessions {flow.revoked = true;// A pending start owns its eventual cancellation: keep the reservation so another browser cannot race into this auth home.if (flow.starting) continue;+ this.end(flow, "interrupted", "session");flow.busy = true;void Promise.resolve().then(() => flow.instance.cancelAuthentication?.()).catch(() => {}).finally(() => {if (this.flows.get(id) === flow) this.flows.delete(id);@@ -140,13 +230,13 @@ export class ProviderAuthSessions {}clear(): void {- for (const flow of this.flows.values()) flow.revoked = true;+ for (const flow of this.flows.values()) { flow.revoked = true; this.end(flow, "interrupted", "settings"); }this.flows.clear();}clearInstance(instanceId: string): void {const flow = this.flows.get(instanceId);- if (flow) flow.revoked = true;+ if (flow) { flow.revoked = true; this.end(flow, "interrupted", "settings"); }this.flows.delete(instanceId);}}diff --git a/server/routes/instances.ts b/server/routes/instances.tsindex 6472068032..d787d066bd 100644--- a/server/routes/instances.ts+++ b/server/routes/instances.ts@@ -1,6 +1,7 @@import { agentEndpointAddress, discoverAgentEndpointModels, hasExplicitModel, isGatewayEndpoint } from "../agent-endpoint-models.ts";import { codexEndpointSchema, codexEndpointUpdateSchema, newCodexEndpoint, updateCodexEndpoint, withCodexEndpointInfo, isCodexEndpoint } from "../codex-endpoints.ts";import { userError, userErrorFields } from "../user-errors.ts";+import { signInReasonOf } from "../../shared/sign-in-outcome.ts";import { modelManifest } from "../model-manifest/manifest.ts";import { randomUUID } from "node:crypto";import { providerIconError } from "../../shared/provider-icon.ts";@@ -409,7 +410,9 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {} catch (error) {const requestedStatus = error && typeof error === "object" ? (error as { status?: unknown }).status : undefined;const status = typeof requestedStatus === "number" && [400, 401, 404, 409, 413, 415].includes(requestedStatus) ? requestedStatus : 500;- return json(res, status, { error: error instanceof Error ? error.message : String(error), ...userErrorFields(error) });+ // `reason`: why a sign-in did not go on, as a fixed code (shared/sign-in-outcome.ts), such as `wrong_code` or `interrupted`.+ const reason = action.startsWith("auth/") ? signInReasonOf(error) : null;+ return json(res, status, { error: error instanceof Error ? error.message : String(error), ...userErrorFields(error), ...(reason ? { reason } : {}) });}}diff --git a/server/sign-in-awake.test.ts b/server/sign-in-awake.test.tsnew file mode 100644index 0000000000..7cf490c6f5--- /dev/null+++ b/server/sign-in-awake.test.ts@@ -0,0 +1,226 @@+// A Cloud home with an engine sign-in open never looks idle to the sleep handshake (server/cloud-power.ts): the real Claude+// paste-code and Codex device-code controllers, each running a stand-in CLI, behind the real ProviderAuthSessions, read by+// the real power report. Finishing, cancelling, failing and expiring each let the home sleep again, and the sign-in trace+// those flows write never holds the code, the link or the device code. No real CLI, network or credential.+import { chmodSync, existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { CLOUD_IDLE_AWAKE_MS, CLOUD_IDLE_WORK_MS, createCloudPower, type CloudPower } from "./cloud-power.ts";+import { ClaudeLoginController } from "./drivers/claude-login-auth.ts";+import { CODEX_DEVICE_SIGN_IN, CodexDeviceAuthController } from "./drivers/codex-device-auth.ts";+import { deviceAuthInstanceSurface } from "./drivers/device-auth.ts";+import { ProviderAuthSessions } from "./provider-auth-sessions.ts";+import { createSignInTrace, SIGN_IN_TRACE_FILE, type SignInTrace } from "./sign-in-trace.ts";+import { removeTempDir } from "./testing/cleanup.ts";++const CLAUDE_CODE = "GOODCODE#abc", REFUSED_CODE = "WRONGCODE#abc", DEVICE_CODE = "0CSG-0IXIM";+// Claude's `auth login` / `auth status --json`: prints its link and reads the pasted code.+const FAKE_CLAUDE = `#!/usr/bin/env node+import { existsSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+const home = process.env.HOME;+const args = process.argv.slice(2).join(' ');+if (args === 'auth status --json') {+ const signedIn = existsSync(join(home, 'claude-authenticated'));+ process.stdout.write(JSON.stringify({ loggedIn: signedIn }) + '\\n');+ process.exit(signedIn ? 0 : 1);+} else if (args === 'auth login') {+ process.stdout.write('If the browser did not open, visit: https://claude.com/cai/oauth/authorize?code=true&state=secret-state\\n');+ process.stdout.write('Paste code here if prompted > ');+ let buffered = '';+ process.stdin.setEncoding('utf8');+ process.stdin.on('data', (chunk) => {+ buffered += chunk;+ if (!buffered.includes('\\n')) return;+ if (buffered.split('\\n')[0].trim() === ${JSON.stringify(CLAUDE_CODE)}) {+ writeFileSync(join(home, 'claude-authenticated'), 'fixture only');+ process.stdout.write('Login successful\\n');+ process.exit(0);+ }+ process.stderr.write('Invalid authorization code\\n');+ process.exit(1);+ });+} else process.exit(2);+`;+// Codex's `login --device-auth` / `login status`: shows the page and the code, then waits for the approval marker+// (FAKE_AUTH_MODE=crash: exits with a token-looking line instead).+const FAKE_CODEX = `#!/usr/bin/env node+import { existsSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+const home = process.env.HOME;+const args = process.argv.slice(2).join(' ');+if (args === 'login status') {+ if (existsSync(join(home, 'codex-authenticated'))) { process.stderr.write('Logged in using ChatGPT\\n'); process.exit(0); }+ process.stderr.write('Not logged in\\n'); process.exit(1);+} else if (args === 'login --device-auth') {+ console.error('Open this link:');+ console.error('https://auth.openai.com/codex/device');+ console.error('Enter this one-time code (expires in 15 minutes)');+ console.error(${JSON.stringify(DEVICE_CODE)});+ if (process.env.FAKE_AUTH_MODE === 'crash') setTimeout(() => { console.error('access_token=secret-token'); process.exit(1); }, 50);+ else setInterval(() => {+ if (!existsSync(join(home, 'approve'))) return;+ writeFileSync(join(home, 'codex-authenticated'), 'fixture only');+ console.error('Successfully logged in'); process.exit(0);+ }, 50);+} else process.exit(4);+`;++describe("an engine sign-in on a Cloud home", () => {+ let home: string, clock: number, lines: string[];+ let trace: SignInTrace, sessions: ProviderAuthSessions, power: CloudPower;+ const disposers: Array<() => Promise<void>> = [];++ const claude = (options: { lifetimeMs?: number } = {}) => {+ const cli = join(home, "fake-claude.mjs");+ writeFileSync(cli, FAKE_CLAUDE, { mode: 0o700 });+ chmodSync(cli, 0o700);+ const login = new ClaudeLoginController({ cli, environment: () => ({ ...process.env, HOME: home, CLAUDE_CONFIG_DIR: join(home, ".claude") }),+ startupTimeoutMs: 10_000, completeTimeoutMs: 10_000, terminateTimeoutMs: 50, lifetimeMs: options.lifetimeMs ?? 60_000 });+ disposers.push(() => login.dispose());+ // The instance id is the person's own account name: it must never reach the trace.+ return { instanceId: "claude-private-account", driverKind: "claudeAgent", startAuthentication: () => login.start(), getAuthentication: (flowId: string) => login.get(flowId),+ completeAuthentication: (flowId: string, code: string) => login.complete(flowId, code), cancelAuthentication: () => login.cancel(), signOut: () => login.signOut() };+ };+ const codex = (options: { mode?: string; lifetimeMs?: number } = {}) => {+ const cli = join(home, "fake-codex.mjs");+ writeFileSync(cli, FAKE_CODEX, { mode: 0o700 });+ chmodSync(cli, 0o700);+ const device = new CodexDeviceAuthController({ cli, environment: () => ({ ...process.env, HOME: home, CODEX_HOME: join(home, ".codex"), FAKE_AUTH_MODE: options.mode ?? "wait" }),+ startupTimeoutMs: 10_000, terminateTimeoutMs: 50, lifetimeMs: options.lifetimeMs ?? 60_000 });+ disposers.push(() => device.dispose());+ return { instanceId: "codex-private-account", driverKind: "codex", ...deviceAuthInstanceSurface(device, CODEX_DEVICE_SIGN_IN) };+ };+ /** The power report's busy codes, at the power clock's time. */+ const busy = () => power.report().busy;+ /** Past the home's own windows (just woke, work just ended), so only what is open now decides. */+ const settle = () => {+ // In the power clock's own 5 s ticks: a jump much larger than a tick reads as a resume from a suspend.+ for (const until = clock + Math.max(CLOUD_IDLE_AWAKE_MS, CLOUD_IDLE_WORK_MS) + 5_000; clock < until;) { clock += 5_000; power.tick(); }+ };+ const secrets = () => [CLAUDE_CODE, REFUSED_CODE, "BADCODE", DEVICE_CODE, "secret-state", "secret-token", "claude.com", "auth.openai.com", "private-account", "https://"];+ /** Everything the trace wrote: its file, its log lines and the health report's summary. */+ const written = () => [existsSync(join(home, SIGN_IN_TRACE_FILE)) ? readFileSync(join(home, SIGN_IN_TRACE_FILE), "utf8") : "", ...lines, JSON.stringify(trace.summary())].join("\n");++ beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), "omb-sign-in-awake-"));+ clock = 1_800_000_000_000;+ lines = [];+ trace = createSignInTrace({ dataDir: home, log: (line) => lines.push(line) });+ sessions = new ProviderAuthSessions({ trace });+ power = createCloudPower({ dataDir: home, now: () => clock, broadcast: () => {}, probes: {+ turn: () => false, run: () => false, handoff: () => false, liveCall: () => false, computer: () => false,+ // The home's wiring (server/index.ts): a provider sign-in under way is maintenance.+ maintenance: () => sessions.active, nextDueAt: () => null,+ } });+ settle();+ expect(power.report()).toMatchObject({ idle: true, busy: [] });+ });+ afterEach(async () => {+ power.close();+ await Promise.all(disposers.splice(0).map((dispose) => dispose().catch(() => {})));+ await removeTempDir(home);+ });++ it("Claude: an open paste-code sign-in keeps it awake, a code that is not a code keeps it open, and the right code lets it sleep", async () => {+ const instance = claude();+ const started = await sessions.start(instance, "owner-session");+ expect(started).toMatchObject({ phase: "waiting" });+ settle();+ expect(busy()).toEqual(["maintenance"]);+ // While it is open, nothing the trace wrote holds the link, the flow or the account.+ for (const secret of [...secrets(), started.flowId!]) expect(written()).not.toContain(secret);+ expect(power.prepareSleep()).toEqual({ ok: false, busy: ["maintenance"] });++ // Too short to be a code: refused before it reaches Claude, and the sign-in is still open.+ await expect(sessions.complete(instance.instanceId, "owner-session", started.flowId!, "BADCODE")).rejects.toMatchObject({ reason: "wrong_code" });+ settle();+ expect(busy()).toEqual(["maintenance"]);++ await sessions.complete(instance.instanceId, "owner-session", started.flowId!, CLAUDE_CODE);+ expect(busy()).not.toContain("maintenance");+ settle();+ expect(power.report()).toMatchObject({ idle: true, busy: [] });+ expect(trace.summary()).toMatchObject({ attempts: 1, open: 0, engines: [{ kind: "claudeAgent", attempts: 1, completed: 1, last: { outcome: "completed" } }] });+ expect(trace.summary().recent.map((event) => event.outcome)).toEqual(["started", "wrong_code", "completed"]);+ expect(lines).toEqual(["sign-in: claudeAgent paste-code started", expect.stringMatching(/^sign-in: claudeAgent paste-code wrong_code after \d+s$/),+ expect.stringMatching(/^sign-in: claudeAgent paste-code completed after \d+s$/)]);+ for (const secret of secrets()) expect(written()).not.toContain(secret);+ }, 30_000);++ it("Claude: a code the provider refuses ends the sign-in and lets it sleep at once, not at the expiry", async () => {+ const instance = claude();+ const started = await sessions.start(instance, "owner-session");+ await expect(sessions.complete(instance.instanceId, "owner-session", started.flowId!, REFUSED_CODE)).rejects.toMatchObject({ reason: "refused" });+ settle();+ expect(power.report()).toMatchObject({ idle: true, busy: [] });+ expect(trace.summary().engines[0]).toMatchObject({ attempts: 1, completed: 0, last: { outcome: "refused" } });+ for (const secret of secrets()) expect(written()).not.toContain(secret);+ }, 30_000);++ it("Claude: cancelling lets it sleep", async () => {+ const instance = claude();+ const started = await sessions.start(instance, "owner-session");+ settle();+ expect(busy()).toEqual(["maintenance"]);+ await sessions.cancel(instance.instanceId, "owner-session", started.flowId!);+ settle();+ expect(power.report()).toMatchObject({ idle: true, busy: [] });+ expect(trace.summary().engines[0].last).toMatchObject({ outcome: "cancelled" });+ }, 30_000);++ it("Codex: an open device-code sign-in keeps it awake until the person approves it", async () => {+ const instance = codex();+ const started = await sessions.start(instance, "owner-session");+ expect(started).toMatchObject({ phase: "waiting", userCode: DEVICE_CODE });+ settle();+ expect(busy()).toEqual(["maintenance"]);+ for (const secret of [...secrets(), started.flowId!]) expect(written()).not.toContain(secret);+ expect(power.prepareSleep()).toMatchObject({ ok: false });++ writeFileSync(join(home, "approve"), "fixture only");+ // The sign-in screen polls the status, as SignInPill does.+ await expect.poll(async () => (await sessions.status(instance.instanceId, "owner-session", started.flowId!)).phase, { timeout: 10_000, interval: 100 }).toBe("succeeded");+ settle();+ expect(power.report()).toMatchObject({ idle: true, busy: [] });+ expect(trace.summary().engines).toEqual([expect.objectContaining({ kind: "codex", attempts: 1, completed: 1 })]);+ expect(lines[0]).toBe("sign-in: codex device-code started");+ for (const secret of secrets()) expect(written()).not.toContain(secret);+ }, 30_000);++ it("Codex: a login command that exits fails the sign-in and lets it sleep", async () => {+ const instance = codex({ mode: "crash" });+ const started = await sessions.start(instance, "owner-session");+ settle();+ expect(busy()).toEqual(["maintenance"]);+ await expect.poll(async () => (await sessions.status(instance.instanceId, "owner-session", started.flowId!)).phase, { timeout: 10_000, interval: 100 }).toBe("failed");+ expect(await sessions.status(instance.instanceId, "owner-session", started.flowId!)).toMatchObject({ reason: "exited" });+ settle();+ expect(power.report()).toMatchObject({ idle: true, busy: [] });+ expect(trace.summary().engines[0].last).toMatchObject({ outcome: "exited" });+ for (const secret of secrets()) expect(written()).not.toContain(secret);+ }, 30_000);++ it("Codex: a code nobody enters expires by itself and lets it sleep, recorded as expired with no one polling", async () => {+ const instance = codex({ lifetimeMs: 1_500 });+ await sessions.start(instance, "owner-session");+ settle();+ expect(busy()).toEqual(["maintenance"]);+ // Nobody reads the status: the power report alone notices the expiry.+ await expect.poll(() => busy(), { timeout: 15_000, interval: 100 }).not.toContain("maintenance");+ await expect.poll(() => trace.summary().engines[0]?.last?.outcome, { timeout: 5_000, interval: 50 }).toBe("expired");+ settle();+ expect(power.report()).toMatchObject({ idle: true, busy: [] });+ }, 30_000);++ it("Claude: a paste-code screen left open expires by itself, though its screen never polls", async () => {+ const instance = claude({ lifetimeMs: 1_500 });+ await sessions.start(instance, "owner-session");+ settle();+ expect(busy()).toEqual(["maintenance"]);+ await expect.poll(() => busy(), { timeout: 15_000, interval: 100 }).not.toContain("maintenance");+ await expect.poll(() => trace.summary().engines[0]?.last?.outcome, { timeout: 5_000, interval: 50 }).toBe("expired");+ expect(trace.summary().open).toBe(0);+ }, 30_000);+});diff --git a/server/sign-in-trace.test.ts b/server/sign-in-trace.test.tsnew file mode 100644index 0000000000..774be88c72--- /dev/null+++ b/server/sign-in-trace.test.ts@@ -0,0 +1,218 @@+// The sign-in trace and the sign-in sessions around it: an abandoned flow stops keeping the home awake at its cap, a flow+// the server's stop cut short is recorded as interrupted and the sign-in screen hears so, what is kept stays small and holds+// no secret, and a desktop (no trace) writes nothing and behaves as before.+import { mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ProviderAuthenticationStart, ProviderAuthenticationStatus } from "./contracts.ts";+import { ProviderAuthSessions } from "./provider-auth-sessions.ts";+import { createSignInTrace, signInMethodOf, SIGN_IN_TRACE_FILE } from "./sign-in-trace.ts";+import { removeTempDir } from "./testing/cleanup.ts";++const FLOW = "flow-7f3a9c1e-secret", CODE = "PASTED-CODE-1234567", LINK = "https://claude.com/cai/oauth/authorize?code=true&state=secret-state";+const START = 1_800_000_000_000, MINUTE = 60_000;++/** An engine's sign-in surface whose answers the test sets: it never ends a flow by itself. */+function engine(instanceId = "claude-ada-work", driverKind = "claudeAgent", start: Partial<ProviderAuthenticationStart> = {}) {+ let status: ProviderAuthenticationStatus = { phase: "waiting", flowId: FLOW, authorizationUrl: LINK, expiresAt: null };+ return {+ instanceId, driverKind,+ startAuthentication: vi.fn(async (): Promise<ProviderAuthenticationStart> => ({ phase: "waiting", flowId: FLOW, authorizationUrl: LINK, expiresAt: null, ...start })),+ getAuthentication: vi.fn(async () => status),+ completeAuthentication: vi.fn(async () => {}),+ cancelAuthentication: vi.fn(async () => {}),+ set: (next: Partial<ProviderAuthenticationStatus>) => { status = { ...status, ...next }; },+ };+}++describe("the sign-in trace", () => {+ let dir: string, clock: number, lines: string[];+ const trace = (wokeFromSleep = false) => createSignInTrace({ dataDir: dir, now: () => clock, log: (line) => lines.push(line), wokeFromSleep: () => wokeFromSleep });+ const file = () => readFileSync(join(dir, SIGN_IN_TRACE_FILE), "utf8");++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "omb-sign-in-trace-"));+ clock = START;+ lines = [];+ });+ afterEach(async () => { await removeTempDir(dir); });++ it("lets an abandoned flow stop keeping the home awake at the 15-minute cap, though the engine names no expiry and never ends it", async () => {+ const signIns = trace();+ const sessions = new ProviderAuthSessions({ trace: signIns, now: () => clock });+ await sessions.start(engine(), "session-1");+ expect(sessions.active).toBe(true);+ clock += 15 * MINUTE - 1;+ expect(sessions.active).toBe(true);+ clock += 1;+ expect(sessions.active).toBe(false);+ await vi.waitFor(() => expect(signIns.summary().engines[0]?.last?.outcome).toBe("expired"));+ expect(signIns.summary()).toMatchObject({ attempts: 1, open: 0 });+ expect(lines.at(-1)).toBe("sign-in: claudeAgent paste-code expired after 15m 00s");+ });++ it("never lets an engine's read throw out of the power probe: a flow it can't read counts as expired", async () => {+ const signIns = trace();+ const sessions = new ProviderAuthSessions({ trace: signIns, now: () => clock });+ const instance = engine();+ await sessions.start(instance, "session-1");+ instance.getAuthentication.mockImplementation((() => { throw new Error("broken engine"); }) as never);+ clock += 15 * MINUTE;+ expect(() => sessions.active).not.toThrow();+ expect(sessions.active).toBe(false);+ await vi.waitFor(() => expect(signIns.summary().engines[0]?.last?.outcome).toBe("expired"));+ });++ it("keeps a newer attempt as the engine's last when an older one's expiry is recorded after it began", async () => {+ const signIns = trace();+ const sessions = new ProviderAuthSessions({ trace: signIns, now: () => clock });+ const first = engine();+ await sessions.start(first, "session-1");+ let answer: (status: ProviderAuthenticationStatus) => void = () => {};+ first.getAuthentication.mockImplementationOnce(() => new Promise((resolve) => { answer = resolve; }));+ clock += 15 * MINUTE;+ expect(sessions.active).toBe(false);+ await vi.waitFor(() => expect(first.getAuthentication).toHaveBeenCalled());+ // The person signs in again before the engine answers how the first one ended.+ await sessions.start(engine(first.instanceId, "claudeAgent", { flowId: "flow-second" }), "session-1");+ answer({ phase: "expired", flowId: FLOW, authorizationUrl: null, expiresAt: null, reason: "expired" });+ await vi.waitFor(() => expect(signIns.summary().recent.map((event) => event.outcome)).toEqual(["started", "started", "expired"]));+ expect(signIns.summary()).toMatchObject({ attempts: 2, open: 1, engines: [{ kind: "claudeAgent", attempts: 2, last: { outcome: "started" } }] });+ });++ it("records a flow that was open when the server stopped as interrupted on the next start, and the sign-in screen hears it", async () => {+ const before = new ProviderAuthSessions({ trace: trace(), now: () => clock });+ const instance = engine();+ await before.start(instance, "session-1");+ expect(JSON.parse(file()).open).toHaveLength(1);+ // While it is open, the file recognises the flow by a hash only: never the flow, the instance or the session.+ for (const hidden of [FLOW, instance.instanceId, "session-1", LINK]) expect(file()).not.toContain(hidden);++ // The machine is stopped to sleep and boots again: a new process, the same data folder.+ clock += 4 * MINUTE + 5_000;+ lines = [];+ const signIns = trace(true);+ signIns.recover();+ expect(lines).toEqual(["sign-in: claudeAgent paste-code interrupted after 4m 05s (the server was stopped to sleep)"]);+ expect(signIns.summary()).toMatchObject({ attempts: 1, open: 0, engines: [{ kind: "claudeAgent", attempts: 1, completed: 0, last: { outcome: "interrupted", at: clock } }] });+ signIns.recover();+ expect(lines).toHaveLength(1);++ const after = new ProviderAuthSessions({ trace: signIns, now: () => clock });+ // The screen's poll: a finished status that says why. The browser's session id is not kept, so any session asking+ // about that flow hears it, and nothing more.+ // No message: the screen words the reason in the person's own language.+ expect(await after.status(instance.instanceId, "session-1", FLOW)).toEqual({ phase: "failed", flowId: FLOW, authorizationUrl: null, expiresAt: null, reason: "interrupted" });+ // The paste-code screen finds out when it sends the code.+ await expect(after.complete(instance.instanceId, "session-1", FLOW, CODE)).rejects.toMatchObject({ status: 404, reason: "interrupted" });+ await expect(after.cancel(instance.instanceId, "session-1", FLOW)).resolves.toBeUndefined();+ // Any other flow is just gone, as before.+ await expect(after.status(instance.instanceId, "session-1", "another-flow")).rejects.toMatchObject({ status: 404 });+ await expect(after.status(instance.instanceId, "session-1", "another-flow")).rejects.not.toHaveProperty("reason");+ expect(instance.completeAuthentication).not.toHaveBeenCalled();++ // A new sign-in on the same engine is its own attempt, and its flow is never mistaken for the old one.+ await after.start(engine(instance.instanceId, "claudeAgent", { flowId: "flow-new" }), "session-1");+ expect(await after.status(instance.instanceId, "session-1", "flow-new")).toMatchObject({ phase: "waiting" });+ expect(signIns.summary()).toMatchObject({ attempts: 2, open: 1 });+ });++ it("leaves an attempt the shutdown tears down open, so the next boot calls it interrupted, not cancelled", async () => {+ const signIns = trace();+ const sessions = new ProviderAuthSessions({ trace: signIns, now: () => clock });+ const instance = engine();+ await sessions.start(instance, "session-1");+ signIns.stopping();+ sessions.clearInstance(instance.instanceId);+ expect(JSON.parse(file()).open).toHaveLength(1);+ expect(lines).toEqual(["sign-in: claudeAgent paste-code started"]);+ const next = trace();+ next.recover();+ expect(next.summary().engines[0].last?.outcome).toBe("interrupted");+ expect(next.interrupted(instance.instanceId, FLOW)).toBe(true);+ });++ it("a restart, not a sleep, says so; a boot with nothing open writes nothing", () => {+ writeFileSync(join(dir, SIGN_IN_TRACE_FILE), JSON.stringify({ v: 1, open: [{ id: "a", kind: "codex", method: "device-code", at: START - 30_000 }], recent: [], engines: {} }));+ trace(false).recover();+ expect(lines).toEqual(["sign-in: codex device-code interrupted after 30s (the server restarted)"]);+ const empty = mkdtempSync(join(tmpdir(), "omb-sign-in-trace-empty-"));+ try {+ createSignInTrace({ dataDir: empty, log: (line) => lines.push(line) }).recover();+ expect(readdirSync(empty)).toEqual([]);+ } finally { void removeTempDir(empty); }+ });++ it("keeps a small, bounded summary and never a code, a link, a flow, a session or an instance's name", async () => {+ const signIns = trace();+ const sessions = new ProviderAuthSessions({ trace: signIns, now: () => clock });+ for (let index = 0; index < 30; index++) {+ const instance = engine(`personal-name-${index}`, `engine${index % 25}`);+ await sessions.start(instance, `session-secret-${index}`);+ instance.completeAuthentication.mockRejectedValueOnce(Object.assign(new Error(`bad code ${CODE}`), { reason: "wrong_code" }));+ await expect(sessions.complete(instance.instanceId, `session-secret-${index}`, FLOW, CODE)).rejects.toThrow();+ await sessions.cancel(instance.instanceId, `session-secret-${index}`, FLOW);+ clock += MINUTE;+ }+ const summary = signIns.summary();+ // engine0 to engine19 are counted (the first twenty kinds), engine0 to engine4 twice.+ expect(summary.attempts).toBe(20 + 5);+ expect(summary.engines).toHaveLength(20);+ expect(summary.recent).toHaveLength(10);+ expect(summary.recent.at(-1)).toMatchObject({ kind: "engine4", method: "paste-code", outcome: "cancelled" });+ expect(JSON.stringify(summary).length).toBeLessThan(4_096);+ for (const text of [file(), lines.join("\n"), JSON.stringify(summary)]) {+ for (const secret of [FLOW, CODE, "secret-state", "claude.com", "session-secret", "personal-name"]) expect(text).not.toContain(secret);+ }+ });++ it("reads a file that is not its own as empty, and drops anything in it that is not a code", () => {+ writeFileSync(join(dir, SIGN_IN_TRACE_FILE), "not json");+ expect(trace().summary()).toEqual({ attempts: 0, open: 0, engines: [], recent: [] });+ writeFileSync(join(dir, SIGN_IN_TRACE_FILE), JSON.stringify({ v: 1, open: [], recent: [+ { kind: "has spaces [email protected]", method: "pasted the token", outcome: "completed", at: 5 },+ { kind: "codex", method: "device-code", outcome: "token=secret", at: 6 },+ ], engines: { "codex": { attempts: -3, completed: "lots", last: { outcome: "secret", at: 1 } }, "bad kind!": { attempts: 1 } } }));+ expect(trace().summary()).toEqual({ attempts: 0, open: 0, engines: [{ kind: "codex", attempts: 0, completed: 0, last: null }],+ recent: [{ kind: "unknown", method: "other", outcome: "completed", at: 5 }] });+ });++ it("names each method as the provider card does", () => {+ expect(signInMethodOf({ getAuthentication: () => {}, completeAuthentication: () => {} })).toBe("paste-code");+ expect(signInMethodOf({ getAuthentication: () => {} })).toBe("device-code");+ expect(signInMethodOf({})).toBe("callback-url");+ expect(signInMethodOf({ authenticationMethod: "browser-pkce", getAuthentication: () => {} })).toBe("browser-pkce");+ expect(signInMethodOf({ authenticationMethod: "callback-url", getAuthentication: () => {}, completeAuthentication: () => {} })).toBe("callback-url");+ });+});++describe("a desktop's sign-in sessions (no trace)", () => {+ let dir: string;+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "omb-sign-in-desktop-")); });+ afterEach(async () => { await removeTempDir(dir); });++ it("write nothing, log nothing, and count a sign-in as under way exactly as before", async () => {+ const log = vi.spyOn(console, "log");+ let clock = START;+ const sessions = new ProviderAuthSessions({ now: () => clock });+ const instance = engine();+ await sessions.start(instance, "session-1");+ expect(sessions.active).toBe(true);+ instance.completeAuthentication.mockRejectedValueOnce(Object.assign(new Error("not a code"), { reason: "wrong_code" }));+ await expect(sessions.complete(instance.instanceId, "session-1", FLOW, "short")).rejects.toThrow();+ expect(sessions.active).toBe(true);+ clock += 15 * MINUTE;+ expect(sessions.active).toBe(false);+ await sessions.start(instance, "session-1");+ await sessions.cancel(instance.instanceId, "session-1", FLOW);+ expect(sessions.active).toBe(false);+ // Without a trace, a resumed flow is never re-read before its start, as before.+ await sessions.start(instance, "session-1");+ await sessions.start(instance, "session-1");+ expect(instance.getAuthentication).not.toHaveBeenCalled();+ expect(readdirSync(dir)).toEqual([]);+ expect(log.mock.calls.flat().some((line) => String(line).startsWith("sign-in:"))).toBe(false);+ log.mockRestore();+ });+});diff --git a/server/sign-in-trace.ts b/server/sign-in-trace.tsnew file mode 100644index 0000000000..41c9e9baca--- /dev/null+++ b/server/sign-in-trace.ts@@ -0,0 +1,199 @@+// A Cloud home's record of engine sign-ins, for support: each attempt's engine, method, start and outcome, as one plain log+// line per event and a small summary on the health report (`signIns`). Kept in sign-in-trace.json in the data folder, so a+// stop (a restart, a stop for sleep) can't wipe the record of what it cut short: an attempt still open in the file when the+// server starts again is recorded as `interrupted`, and the sign-in screen's next read of it says so.+//+// Privacy: engine kinds, method names, fixed outcome codes (shared/sign-in-outcome.ts) and times only. Never a code, a+// token, a link, an account, an instance's name, a session or a flow id: the file keeps a hash of the flow to recognise it.+import { createHash, randomUUID } from "node:crypto";+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { signInOutcome, type SignInOutcome } from "../shared/sign-in-outcome.ts";+import { writeFileAtomic } from "./atomic.ts";++export const SIGN_IN_TRACE_FILE = "sign-in-trace.json";+/** The methods a sign-in can take (the provider card's `authentication.method`), and `other`. */+export const SIGN_IN_METHODS = ["paste-code", "device-code", "callback-url", "browser-pkce", "browser", "other"] as const;+export type SignInMethod = (typeof SIGN_IN_METHODS)[number];+/** Events kept for the report, newest last; engines counted; attempts the file holds open at once. */+const RECENT = 10, ENGINES = 20, OPEN = 20, INTERRUPTED = 20, COUNT_MAX = 1_000_000;+const KIND = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;+const METHODS: ReadonlySet<string> = new Set(SIGN_IN_METHODS);+/** Why an attempt was cut short, for the log line only. */+export type SignInInterruption = "sleep" | "restart" | "settings" | "session";+const INTERRUPTED_BY: Record<SignInInterruption, string> = {+ sleep: "the server was stopped to sleep", restart: "the server restarted", settings: "the engine's settings changed", session: "the session that started it ended",+};++/** How an instance signs in (what its provider card shows): named, or told apart by the calls it offers. */+export function signInMethodOf(inst: { authenticationMethod?: string; getAuthentication?: unknown; completeAuthentication?: unknown }): Exclude<SignInMethod, "other"> {+ if (inst.authenticationMethod === "browser-pkce" || inst.authenticationMethod === "browser" || inst.authenticationMethod === "callback-url") return inst.authenticationMethod;+ return inst.getAuthentication && inst.completeAuthentication ? "paste-code" : inst.getAuthentication ? "device-code" : "callback-url";+}++type EventOutcome = SignInOutcome | "started";+export interface SignInEvent { kind: string; method: SignInMethod; outcome: EventOutcome; at: number }+interface OpenAttempt { id: string; kind: string; method: SignInMethod; at: number; flow?: string }+interface EngineTotals { attempts: number; completed: number; last: { outcome: EventOutcome; at: number } | null }+interface TraceFile { v: 1; open: OpenAttempt[]; recent: SignInEvent[]; engines: Record<string, EngineTotals> }++/** The health report's `signIns`: counts since the first sign-in, per engine and in all, and the last few events. */+export interface SignInSummary {+ attempts: number; open: number;+ engines: Array<{ kind: string; attempts: number; completed: number; last: { outcome: EventOutcome; at: number } | null }>;+ recent: SignInEvent[];+}++/** One attempt, from the press of the sign-in button to its outcome. Every call after `end` is ignored. */+export interface SignInAttempt {+ /** The engine began the flow: it can be recognised after a restart. */+ opened(instanceId: string, flowId: string): void;+ /** A try inside it that did not end it (a pasted code that is not a code). */+ note(outcome: SignInOutcome): void;+ end(outcome: SignInOutcome, by?: SignInInterruption): void;+ readonly ended: boolean;+}++const flowKey = (instanceId: string, flowId: string) => createHash("sha256").update(`${instanceId}\n${flowId}`).digest("hex").slice(0, 32);+const time = (value: unknown): number | null => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;+const count = (value: unknown) => typeof value === "number" && Number.isInteger(value) && value >= 0 ? Math.min(value, COUNT_MAX) : 0;+const kindOf = (value: unknown) => typeof value === "string" && KIND.test(value) ? value : "unknown";+const methodOf = (value: unknown): SignInMethod => typeof value === "string" && METHODS.has(value) ? value as SignInMethod : "other";+const eventOutcome = (value: unknown): EventOutcome | null => value === "started" ? "started" : signInOutcome(value);+const seconds = (ms: number) => {+ const total = Math.max(0, Math.round(ms / 1000));+ return total < 60 ? `${total}s` : `${Math.floor(total / 60)}m ${String(total % 60).padStart(2, "0")}s`;+};++/** What a file on disk says, with anything that is not ours dropped. */+function parseTrace(text: string): TraceFile {+ const empty: TraceFile = { v: 1, open: [], recent: [], engines: {} };+ let raw: unknown;+ try { raw = JSON.parse(text); } catch { return empty; }+ if (!raw || typeof raw !== "object") return empty;+ const value = raw as Record<string, unknown>;+ const open = (Array.isArray(value.open) ? value.open : []).flatMap((item): OpenAttempt[] => {+ const entry = item as Record<string, unknown> | null, at = time(entry?.at);+ if (!entry || at === null || typeof entry.id !== "string") return [];+ return [{ id: entry.id.slice(0, 64), kind: kindOf(entry.kind), method: methodOf(entry.method), at, ...(typeof entry.flow === "string" && /^[0-9a-f]{32}$/.test(entry.flow) ? { flow: entry.flow } : {}) }];+ }).slice(-OPEN);+ const recent = (Array.isArray(value.recent) ? value.recent : []).flatMap((item): SignInEvent[] => {+ const entry = item as Record<string, unknown> | null, at = time(entry?.at), outcome = eventOutcome(entry?.outcome);+ return entry && at !== null && outcome ? [{ kind: kindOf(entry.kind), method: methodOf(entry.method), outcome, at }] : [];+ }).slice(-RECENT);+ const engines: Record<string, EngineTotals> = {};+ const stored = value.engines && typeof value.engines === "object" ? value.engines as Record<string, unknown> : {};+ for (const [kind, item] of Object.entries(stored).slice(0, ENGINES)) {+ if (!KIND.test(kind) || !item || typeof item !== "object") continue;+ const totals = item as Record<string, unknown>, last = totals.last as Record<string, unknown> | null, at = time(last?.at), outcome = eventOutcome(last?.outcome);+ engines[kind] = { attempts: count(totals.attempts), completed: count(totals.completed), last: at !== null && outcome ? { outcome, at } : null };+ }+ return { v: 1, open, recent, engines };+}++export function createSignInTrace(options: {+ dataDir: string; now?: () => number; log?: (line: string) => void;+ /** This boot follows a stop for sleep: an attempt it cut short says so in its log line. */+ wokeFromSleep?: () => boolean;+}) {+ const now = options.now ?? Date.now, log = options.log ?? ((line: string) => console.log(line));+ const path = join(options.dataDir, SIGN_IN_TRACE_FILE);+ let state: TraceFile | null = null;+ /** The server is shutting down: whatever ends attempts now (engines torn down, settings cleared) is the stop itself, so+ * they stay open in the file and the next boot records them as interrupted. */+ let stopping = false;+ /** Flows open when the server last stopped, by hash: the sign-in screen's next read of one hears `interrupted`. */+ const interruptedFlows = new Set<string>();+ /** Each engine kind's newest attempt in this process: an older one that ends later (a late expiry) never becomes its `last`. */+ const newest = new Map<string, string>();++ const save = () => {+ try { writeFileAtomic(path, `${JSON.stringify(state)}\n`, { durable: false }); }+ catch (error) { log(`sign-in: the record could not be saved: ${error instanceof Error ? error.name : "error"}`); }+ };+ const record = (file: TraceFile, event: SignInEvent, isLast = true) => {+ file.recent = [...file.recent, event].slice(-RECENT);+ const totals = file.engines[event.kind] ?? (Object.keys(file.engines).length < ENGINES ? (file.engines[event.kind] = { attempts: 0, completed: 0, last: null }) : null);+ if (!totals) return;+ if (event.outcome === "started") totals.attempts = Math.min(totals.attempts + 1, COUNT_MAX);+ if (event.outcome === "completed") totals.completed = Math.min(totals.completed + 1, COUNT_MAX);+ if (isLast) totals.last = { outcome: event.outcome, at: event.at };+ };+ const line = (event: SignInEvent, startedAt: number | null, by?: SignInInterruption) =>+ log(`sign-in: ${event.kind} ${event.method} ${event.outcome}${startedAt !== null && event.outcome !== "started" ? ` after ${seconds(event.at - startedAt)}` : ""}${by ? ` (${INTERRUPTED_BY[by]})` : ""}`);++ /** Loads the file once; attempts it holds open were cut short by the server's stop. */+ const recover = (): TraceFile => {+ if (state) return state;+ let text: string | null = null;+ try { text = readFileSync(path, "utf8"); } catch {}+ const file = state = text === null ? { v: 1, open: [], recent: [], engines: {} } : parseTrace(text);+ if (!file.open.length) return file;+ const by: SignInInterruption = options.wokeFromSleep?.() ? "sleep" : "restart", at = now();+ for (const attempt of file.open) {+ const event: SignInEvent = { kind: attempt.kind, method: attempt.method, outcome: "interrupted", at };+ record(file, event);+ line(event, attempt.at, by);+ if (attempt.flow && interruptedFlows.size < INTERRUPTED) interruptedFlows.add(attempt.flow);+ }+ file.open = [];+ save();+ return file;+ };++ return {+ recover: () => { recover(); },+ /** The server began shutting down (a restart, a stop for sleep or an update). */+ stopping: () => { stopping = true; },+ /** The person pressed sign-in for an engine of this kind. */+ begin(kind: string | undefined, method: SignInMethod): SignInAttempt {+ const file = recover();+ const attempt: OpenAttempt = { id: randomUUID(), kind: kindOf(kind), method: methodOf(method), at: now() };+ const started: SignInEvent = { kind: attempt.kind, method: attempt.method, outcome: "started", at: attempt.at };+ file.open = [...file.open, attempt].slice(-OPEN);+ newest.set(attempt.kind, attempt.id);+ record(file, started);+ save();+ line(started, null);+ let ended = false;+ const event = (outcome: SignInOutcome): SignInEvent => ({ kind: attempt.kind, method: attempt.method, outcome, at: now() });+ return {+ get ended() { return ended; },+ opened(instanceId, flowId) {+ if (ended || !flowId) return;+ attempt.flow = flowKey(instanceId, flowId);+ if (file.open.includes(attempt)) save();+ },+ note(outcome) {+ if (ended) return;+ const noted = event(outcome);+ record(file, noted, newest.get(attempt.kind) === attempt.id);+ save();+ line(noted, attempt.at);+ },+ end(outcome, by) {+ if (ended) return;+ ended = true;+ if (stopping && outcome !== "completed") return;+ const done = event(outcome);+ file.open = file.open.filter((open) => open !== attempt);+ record(file, done, newest.get(attempt.kind) === attempt.id);+ save();+ line(done, attempt.at, by);+ },+ };+ },+ /** This flow was open when the server last stopped. */+ interrupted(instanceId: string, flowId: string): boolean {+ recover();+ return Boolean(flowId) && interruptedFlows.has(flowKey(instanceId, flowId));+ },+ summary(): SignInSummary {+ const file = recover();+ const engines = Object.entries(file.engines).map(([kind, totals]) => ({ kind, ...totals }));+ return { attempts: engines.reduce((sum, engine) => Math.min(sum + engine.attempts, COUNT_MAX), 0), open: file.open.length, engines, recent: file.recent.map((event) => ({ ...event })) };+ },+ };+}++export type SignInTrace = ReturnType<typeof createSignInTrace>;diff --git a/shared/sign-in-outcome.ts b/shared/sign-in-outcome.tsnew file mode 100644index 0000000000..d34090dc4e--- /dev/null+++ b/shared/sign-in-outcome.ts@@ -0,0 +1,38 @@+// Why an engine sign-in ended (or why a try inside it did not count), as fixed codes: the server's sign-in status and error+// bodies carry one as `reason`, and a Cloud home's sign-in trace (server/sign-in-trace.ts) counts them. Never words.++export const SIGN_IN_OUTCOMES = [+ /** Signed in. */+ "completed",+ /** A pasted code that is not a code at all (too short, spaces): refused before it reached the engine; the sign-in stays open. */+ "wrong_code",+ /** The provider refused the code or the sign-in. */+ "refused",+ /** The sign-in's own time ran out. */+ "expired",+ /** The person cancelled it. */+ "cancelled",+ /** The engine's login command ended before the sign-in finished. */+ "exited",+ /** The server stopped (a restart, a stop for sleep), the engine's settings changed, or the session that started it ended. */+ "interrupted",+ /** The engine's command is not on this server. */+ "not_installed",+ /** The engine showed no link or code in time, or did not finish after the code was entered. */+ "timed_out",+ /** Anything else. */+ "failed",+] as const;+export type SignInOutcome = (typeof SIGN_IN_OUTCOMES)[number];++const OUTCOMES: ReadonlySet<string> = new Set(SIGN_IN_OUTCOMES);+export const signInOutcome = (value: unknown): SignInOutcome | null => typeof value === "string" && OUTCOMES.has(value) ? value as SignInOutcome : null;++/** An error that says why with a code (`reason`), for the status and error bodies. */+export function withSignInReason<T extends Error>(error: T, reason: SignInOutcome): T & { reason: SignInOutcome } {+ return Object.assign(error, { reason });+}++/** The code an error carries, if it is one of ours. */+export const signInReasonOf = (error: unknown): SignInOutcome | null =>+ error && typeof error === "object" ? signInOutcome((error as { reason?: unknown }).reason) : null;