Multiplayer agent harness for work.
Let people use their own AI accounts from Settings (#1365)
Regan Bellba6707eb2cec
diff --git a/docs/screenshots/personal-ai-access.png b/docs/screenshots/personal-ai-access.pngnew file mode 100644index 000000000..c61a2dc06Binary files /dev/null and b/docs/screenshots/personal-ai-access.png differdiff --git a/docs/screenshots/personal-ai-connect.png b/docs/screenshots/personal-ai-connect.pngnew file mode 100644index 000000000..19940f179Binary files /dev/null and b/docs/screenshots/personal-ai-connect.png differdiff --git a/plugins/web-ui/README.md b/plugins/web-ui/README.mdindex 1a56c6a4a..7c83c8bee 100644--- a/plugins/web-ui/README.md+++ b/plugins/web-ui/README.md@@ -304,3 +304,17 @@ content, URLs, query strings, titles and referrers. Delivery is best effort.Set the same variables on core to capture `app_published` after a successful newapplication or version deployment. Core events use the application's creator andcompany, matching browser identity. No key means no analytics requests.++## Personal AI accounts++Open **Settings → AI access**, or use the account label beside the model picker.+Choose Company, Claude, or ChatGPT / Codex. Sign in with your subscription+or use the secondary API-key option; connecting automatically selects that account. **Company access** switches back without disconnecting+personal credentials. The choice is durable per person and applies to their human+chat turns on the web and in Slack; background tasks retain company access.++A submitted turn keeps its account choice, so switching affects new turns. Personal+access failures do not retry on company credentials. Messages using a different+account queue separately instead of steering an existing run; an explicit steer+across accounts is refused. Organizations that already require individual accounts+continue to require them.diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex e64c50721..b56441411 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -1116,6 +1116,19 @@ const apiRoutes: readonly WebRoute[] = [handle: async (c) =>relayCore(c.res, "GET", `/v1/user-model-auth/status?principalId=${encodeURIComponent(c.user)}`),},+ {+ method: "POST",+ path: "/api/user-model-auth/account",+ handle: async (c) => {+ const p = JSON.parse((await readBody(c.req)) || "{}") as { account?: unknown; provider?: unknown };+ return relayCore(+ c.res,+ "POST",+ "/v1/user-model-auth/account",+ JSON.stringify({ principalId: c.user, account: p.account, provider: p.provider }),+ );+ },+ },{method: "POST",path: "/api/user-model-auth/api-key",@@ -1234,6 +1247,7 @@ const apiRoutes: readonly WebRoute[] = [}const parsed = JSON.parse(authStatus.text) as {individualModelAuth?: boolean;+ account?: string;connections?: { provider: string }[];};const permissions = allPermissions.filter((permission) => permission !== "loops" && permission !== "inbox");@@ -1247,7 +1261,10 @@ const apiRoutes: readonly WebRoute[] = [mode: AUTH_MODE,slackWorkspaceUrl: workspaceUrl,individualModelAuth: parsed.individualModelAuth === true,- modelAuthConnected: (parsed.connections?.length ?? 0) > 0,+ modelAuthConnected:+ parsed.connections?.some(+ (c) => !parsed.account || parsed.account === "personal" || parsed.account === c.provider,+ ) ?? false,impersonatedBy: resolveIdentity(req)?.impersonator ?? null,displayName: resolveIdentity(req)?.name ?? null,...(welcomeCohort ? { welcomeCohort } : {}),diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.tsindex 52257e936..d97224fe2 100644--- a/plugins/web-ui/src/composer.ts+++ b/plugins/web-ui/src/composer.ts@@ -61,7 +61,7 @@ import {import { modelSupportsFastMode } from "./pi-models";import type { ComposerSurface, ConvCtx } from "./conv-types";import { bumpSessionActivity, dropPendingSession, renderList } from "./sessions";-import { appState } from "./shell";+import { appState, switchView } from "./shell";import { base64ToText, bytesToBase64, insertIntoDraft, pasteChipLabel } from "./paste-text";import { clearDraft, newChatDraftKey, saveDraft } from "./drafts";import { tip } from "./tooltip";@@ -215,6 +215,8 @@ export function resyncModelSelection(): void {}export function createComposerSurface(ctx: ConvCtx): ComposerSurface {+ const refreshAccount = () => ctx.chat.drawActiveChat();+ window.addEventListener("model-account-changed", refreshAccount);const loadoutMenuId = `composer-loadout-${crypto.randomUUID()}`;let runtimeRequest = 0;let runtimeIdentity = "";@@ -634,6 +636,9 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {${icon(Paperclip, 18)}</button>${showRuntimeControls ? runtimeControls : nothing}+ <button type="button" class="btn" @click=${() => switchView("settings")}>+ ${appState.me?.individualModelAuth ? "My account" : "Company access"}+ </button></div><div class="composer-right">${sendControls(agent)}</div></div>@@ -2427,6 +2432,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {}function dispose(): void {+ window.removeEventListener("model-account-changed", refreshAccount);cancelLoadoutClose();unsubscribeRuntime?.();++runtimeRequest;diff --git a/plugins/web-ui/src/model-connect.ts b/plugins/web-ui/src/model-connect.tsindex 6821cc948..61785faf3 100644--- a/plugins/web-ui/src/model-connect.ts+++ b/plugins/web-ui/src/model-connect.ts@@ -2,6 +2,8 @@ import { html, render, nothing, type TemplateResult } from "lit";import { api } from "./core-bridge";import { errMessage } from "../../chassis/src/errors";import { brandMark, brandName } from "./ui";+import { appState } from "./shell-state";+import { trapDialogFocus, restoreDialogFocus } from "./dialog-focus";type ProviderKey = "claude" | "chatgpt";type ConnKind = "apikey" | "oauth";@@ -44,7 +46,7 @@ const PROVIDERS: ProviderMeta[] = [},{key: "chatgpt",- name: "ChatGPT",+ name: "ChatGPT / Codex",apiName: "openai",mark: OPENAI_MARK,markClass: "mc-mark-chatgpt",@@ -63,8 +65,10 @@ interface DevicePrompt {expiresAt: number;}-interface StatusResponse {+export interface StatusResponse {+ account: "company" | "personal" | "anthropic" | "openai";individualModelAuth: boolean;+ required: boolean;connections: { provider: "anthropic" | "openai"; kind: ConnKind }[];}@@ -78,10 +82,19 @@ type Flow =interface State {mode: Mode;+ intent: ProviderMeta | null;+ active: boolean;+ revision: number;+ loaded: boolean;+ notice: string;+ controller: AbortController;required: boolean;+ personal: boolean;+ account: StatusResponse["account"];loading: boolean;error: string;busy: boolean;+ saving: boolean;connections: Partial<Record<ProviderKey, ConnKind>>;open: ProviderKey | null;method: Method | null;@@ -92,15 +105,24 @@ interface State {let s: State;let overlay: HTMLElement | null = null;-let deviceCache: DevicePrompt | null = null;+let opener: HTMLElement | null = null;function fresh(mode: Mode): State {return {mode,+ intent: null,+ active: true,+ revision: 0,+ loaded: false,+ notice: "",+ controller: new AbortController(),required: false,+ personal: false,+ account: "company",loading: true,error: "",busy: false,+ saving: false,connections: {},open: null,method: null,@@ -121,24 +143,49 @@ function stopPolling(): void {function resetFlow(): void {stopPolling();+ s.revision++;s.flow = { kind: "pick" };s.method = null;s.busy = false;s.error = "";+ s.notice = "";+}++function current(state: State, revision = state.revision): boolean {+ return s === state && state.active && state.revision === revision;+}++function applyStatus(status: StatusResponse): void {+ s.required = status.required === true;+ s.personal = status.individualModelAuth === true;+ s.account = status.account;+ s.connections = {};+ for (const c of status.connections ?? []) {+ s.connections[c.provider === "anthropic" ? "claude" : "chatgpt"] = c.kind;+ }+ s.loaded = true;+ if (appState.me) {+ appState.me.individualModelAuth = s.personal;+ appState.me.modelAuthConnected = status.connections.some(+ (c) => s.account === "personal" || s.account === c.provider,+ );+ window.dispatchEvent(new CustomEvent("model-account-changed", { detail: status }));+ }}async function load(): Promise<void> {+ const state = s;+ const revision = s.revision;s.loading = true;+ s.error = "";paint();try {- const status = await api<StatusResponse>("/api/user-model-auth/status");- s.required = status.individualModelAuth === true;- s.connections = {};- for (const c of status.connections ?? []) {- s.connections[c.provider === "anthropic" ? "claude" : "chatgpt"] = c.kind;- }- s.error = "";+ const status = await api<StatusResponse>("/api/user-model-auth/status", { signal: state.controller.signal });+ if (!current(state, revision)) return;+ applyStatus(status);} catch (e) {+ if (!current(state, revision)) return;+ s.loaded = false;s.error = friendly(e);}s.loading = false;@@ -155,41 +202,56 @@ function friendly(e: unknown): string {return raw;}-function afterConnect(): void {- stopPolling();- deviceCache = null;- if (s.mode === "gate") {- location.reload();+async function afterConnect(provider: "anthropic" | "openai"): Promise<void> {+ const state = s;+ resetFlow();+ s.open = null;+ await load();+ if (!current(state)) return;+ s.saving = false;+ if (!s.loaded) {+ paint();return;}- const mode = s.mode;- s = fresh(mode);- void load();+ if (s.intent || s.mode === "gate") {+ await switchAccount("personal", provider);+ if (current(state) && !s.error && s.mode === "manager") closeManager();+ return;+ }+ s.notice = "Account connected. Choose Use account to use it for your chats.";+ paint();}async function pickSubscription(p: ProviderMeta): Promise<void> {+ if (s.busy || s.method === "subscription") return;+ resetFlow();+ const state = s;+ const revision = s.revision;s.method = "subscription";- s.error = "";s.busy = true;paint();try {if (p.key === "claude") {const start = await api<{ authorizeUrl: string; verifier: string }>("/api/user-model-auth/claude/start", {method: "POST",+ signal: state.controller.signal,});+ if (!current(state, revision)) return;s.flow = { kind: "claude", ...start, code: "" };} else {- if (!deviceCache || deviceCache.expiresAt - 30_000 <= Date.now()) {- deviceCache = await api<DevicePrompt>("/api/user-model-auth/chatgpt/start", { method: "POST" });- }- stopPolling();- s.flow = { kind: "chatgpt", device: deviceCache };+ const device = await api<DevicePrompt>("/api/user-model-auth/chatgpt/start", {+ method: "POST",+ signal: state.controller.signal,+ });+ if (!current(state, revision)) return;+ s.flow = { kind: "chatgpt", device };s.busy = false;paint();- pollChatGPT();+ void pollChatGPT();return;}} catch (e) {+ if (!current(state, revision)) return;s.error = friendly(e);s.method = null;}@@ -198,84 +260,112 @@ async function pickSubscription(p: ProviderMeta): Promise<void> {}function pickApiKey(): void {- stopPolling();+ if (s.busy || s.method === "apikey") return;+ resetFlow();s.method = "apikey";s.flow = { kind: "apikey", value: "" };- s.error = "";paint();}async function copyCode(code: string): Promise<void> {+ const state = s;+ const revision = s.revision;try {await navigator.clipboard.writeText(code);+ if (!current(state, revision)) return;s.copied = true;paint();setTimeout(() => {+ if (!current(state, revision)) return;s.copied = false;paint();}, 1600);} catch {- s.copied = false;+ if (!current(state, revision)) return;+ s.error = "Could not copy the code. Select it and copy it manually.";+ paint();}}async function finishClaude(): Promise<void> {if (s.flow.kind !== "claude" || !s.flow.code.trim() || s.busy) return;+ const state = s;+ const revision = s.revision;s.error = "";s.busy = true;+ s.saving = true;paint();try {await api("/api/user-model-auth/claude/complete", {method: "POST",body: JSON.stringify({ code: s.flow.code.trim(), verifier: s.flow.verifier }),+ signal: state.controller.signal,});- return afterConnect();+ if (!current(state, revision)) return;+ return afterConnect("anthropic");} catch (e) {+ if (!current(state, revision)) return;s.busy = false;+ s.saving = false;s.error = friendly(e);paint();}}async function pollChatGPT(): Promise<void> {- if (s.flow.kind !== "chatgpt") return;+ if (s.flow.kind !== "chatgpt" || !s.active) return;+ const state = s;+ const revision = s.revision;const device = s.flow.device;if (Date.now() > device.expiresAt) {- deviceCache = null;resetFlow();- s.error = "That code expired — start the sign-in again.";+ s.error = "That code expired. Select Sign in to get a new code.";paint();return;}+ s.saving = true;+ paint();try {const r = await api<{ status: string }>("/api/user-model-auth/chatgpt/poll", {method: "POST",+ signal: state.controller.signal,body: JSON.stringify({ deviceAuthId: device.deviceAuthId, userCode: device.userCode }),});- if (r.status === "connected") return afterConnect();+ if (!current(state, revision)) return;+ if (r.status === "connected") return afterConnect("openai");+ s.saving = false;+ paint();} catch (e) {- s.error = friendly(e);- deviceCache = null;+ if (!current(state, revision)) return;resetFlow();+ s.saving = false;+ s.error = friendly(e);paint();return;}- if (s.flow.kind === "chatgpt") s.pollTimer = setTimeout(pollChatGPT, device.intervalMs || 5000);+ if (current(state, revision)) s.pollTimer = setTimeout(pollChatGPT, Math.max(1000, device.intervalMs || 5000));}async function saveKey(p: ProviderMeta): Promise<void> {if (s.flow.kind !== "apikey" || !s.flow.value.trim() || s.busy) return;+ const state = s;+ const revision = s.revision;s.error = "";s.busy = true;+ s.saving = true;paint();try {await api("/api/user-model-auth/api-key", {method: "POST",body: JSON.stringify({ provider: p.key, apiKey: s.flow.value.trim() }),+ signal: state.controller.signal,});- return afterConnect();+ if (!current(state, revision)) return;+ return afterConnect(p.apiName);} catch (e) {+ if (!current(state, revision)) return;s.busy = false;+ s.saving = false;s.error = friendly(e);paint();}@@ -283,15 +373,34 @@ async function saveKey(p: ProviderMeta): Promise<void> {async function disconnect(p: ProviderMeta): Promise<void> {if (s.busy) return;+ resetFlow();+ s.open = null;+ const state = s;+ const revision = s.revision;s.error = "";s.busy = true;+ s.saving = true;paint();try {- await api("/api/user-model-auth/disconnect", { method: "POST", body: JSON.stringify({ provider: p.key }) });+ await api("/api/user-model-auth/disconnect", {+ method: "POST",+ body: JSON.stringify({ provider: p.key }),+ signal: state.controller.signal,+ });+ if (!current(state, revision)) return;resetFlow();await load();+ if (!current(state)) return;+ s.saving = false;+ s.notice =+ s.account === p.apiName+ ? "Account disconnected. Reconnect it or choose company access to continue chatting."+ : "Account disconnected.";+ paint();} catch (e) {+ if (!current(state, revision)) return;s.busy = false;+ s.saving = false;s.error = friendly(e);paint();}@@ -299,7 +408,13 @@ async function disconnect(p: ProviderMeta): Promise<void> {function methodRow(title: string, detail: string, selected: boolean, onPick: () => void): TemplateResult {return html`- <button type="button" class="mc-method ${selected ? "selected" : ""}" ?disabled=${s.busy} @click=${onPick}>+ <button+ type="button"+ class="mc-method ${selected ? "selected" : ""}"+ ?disabled=${s.busy || s.saving || (title === "Company access" && s.required)}+ aria-pressed=${selected}+ @click=${onPick}+ ><span class="mc-method-radio" aria-hidden="true"></span><span class="mc-method-text"><span class="mc-method-title">${title}</span>@@ -315,14 +430,15 @@ function claudeSteps(): TemplateResult {return html`<ol class="mc-steps"><li>- <a class="btn" href=${flow.authorizeUrl} target="_blank" rel="noopener">Open claude.ai and approve ↗</a>+ <a class="btn" href=${flow.authorizeUrl} target="_blank" rel="noopener">Continue to Claude ↗</a></li><li><label class="mc-field">- <span>Paste the code Claude shows you</span>+ <span>Authorization code</span><input+ ?disabled=${s.busy || s.saving}.value=${flow.code}- placeholder="Code from claude.ai"+ placeholder="Paste the code from Claude"autocomplete="off"spellcheck="false"@input=${(e: Event) => {@@ -335,7 +451,7 @@ function claudeSteps(): TemplateResult {</li><li><button class="btn primary" ?disabled=${!flow.code.trim() || s.busy} @click=${finishClaude}>- ${s.busy ? "Connecting…" : "Finish"}+ ${s.busy ? "Connecting…" : "Connect account"}</button></li></ol>@@ -377,6 +493,7 @@ function apikeySteps(p: ProviderMeta): TemplateResult {<span>API key · from <a href=${p.keyConsoleUrl} target="_blank" rel="noopener">${p.keyConsole}</a></span><inputtype="password"+ ?disabled=${s.busy || s.saving}.value=${flow.value}placeholder=${p.keyPlaceholder}autocomplete="off"@@ -397,11 +514,25 @@ function apikeySteps(p: ProviderMeta): TemplateResult {function connectBody(p: ProviderMeta): TemplateResult {let subscriptionSteps: TemplateResult | typeof nothing = nothing;if (s.method === "subscription") subscriptionSteps = p.key === "claude" ? claudeSteps() : chatgptSteps();+ if (s.intent) {+ return html`<div class="mc-simple-flow">+ ${s.method === "apikey" ? apikeySteps(p) : subscriptionSteps}+ ${s.busy ? html`<p class="mc-waiting">Connecting…</p>` : nothing}+ ${!s.method ? html`<button class="btn primary" ?disabled=${s.saving} @click=${() => void pickSubscription(p)}>Sign in with ${p.name}</button>` : nothing}+ <button+ class="settings-theme-link"+ ?disabled=${s.busy || s.saving}+ @click=${() => (s.method === "apikey" ? void pickSubscription(p) : pickApiKey())}+ >+ ${s.method === "apikey" ? "Use my subscription instead" : "Use an API key instead"}+ </button>+ </div>`;+ }return html`<div class="mc-connect">${methodRow(`Sign in with ${p.name}`,- `Uses your ${p.subscription} subscription — nothing extra to pay.`,+ `Uses your ${p.subscription} subscription and its usage limits.`,s.method === "subscription",() => void pickSubscription(p),)}@@ -425,13 +556,32 @@ function providerRow(p: ProviderMeta): TemplateResult {else if (kind === "apikey") statusLine = "Connected with your API key";let action: TemplateResult | typeof nothing = nothing;if (kind) {- action = html`<button class="btn mc-quiet-danger" ?disabled=${s.busy} @click=${() => disconnect(p)}>- ${s.busy ? "…" : "Disconnect"}+ action = html`<button+ class="btn"+ ?disabled=${s.busy || s.saving || s.account === p.apiName}+ @click=${() => switchAccount("personal", p.apiName)}+ >+ ${s.account === p.apiName ? "In use" : "Use account"}</button+ ><button class="btn mc-quiet-danger" ?disabled=${s.busy || s.saving} @click=${() => disconnect(p)}>+ ${s.busy ? "…" : "Disconnect"}+ </button>`;+ } else if (open) {+ action = html`<button+ type="button"+ class="btn"+ ?disabled=${s.saving}+ @click=${() => {+ resetFlow();+ s.open = null;+ paint();+ }}+ >+ Cancel</button>`;} else if (!open) {action = html`<buttonclass="btn"- ?disabled=${s.busy}+ ?disabled=${s.busy || s.saving}@click=${() => {resetFlow();s.open = p.key;@@ -449,49 +599,117 @@ function providerRow(p: ProviderMeta): TemplateResult {<strong>${p.name}</strong><small>${statusLine}</small></div>- ${action}+ <div class="mc-provider-actions">${action}</div></div>${open && !kind ? connectBody(p) : nothing}</section>`;}+async function switchAccount(account: "personal" | "company", provider?: "anthropic" | "openai"): Promise<void> {+ if (s.busy || (account === "company" && !s.personal) || (account === "personal" && provider === s.account)) return;+ resetFlow();+ s.open = null;+ const state = s;+ const revision = s.revision;+ s.busy = true;+ s.saving = true;+ paint();+ try {+ const status = await api<StatusResponse>("/api/user-model-auth/account", {+ method: "POST",+ body: JSON.stringify({ account, provider }),+ signal: state.controller.signal,+ });+ if (!current(state, revision)) return;+ applyStatus(status);+ s.notice =+ account === "company"+ ? "New chats will use company access."+ : `New chats will use your ${provider === "anthropic" ? "Claude" : "ChatGPT / Codex"} account.`;+ } catch (e) {+ if (!current(state, revision)) return;+ s.error = friendly(e);+ }+ s.busy = false;+ s.saving = false;+ paint();+}+function view(): TemplateResult {- const anyConnected = Object.keys(s.connections).length > 0;+ const anyConnected = PROVIDERS.some(+ (p) => s.connections[p.key] && (s.account === "personal" || s.account === p.apiName),+ );let cta: TemplateResult | typeof nothing = nothing;- if (anyConnected) {+ if (s.loaded && (s.mode === "manager" || anyConnected || !s.personal)) {cta =s.mode === "gate"- ? html`<button class="btn primary mc-cta" @click=${() => location.reload()}>Start chatting</button>`- : html`<button class="btn primary mc-cta" @click=${closeManager}>Done</button>`;+ ? html`<button class="btn primary mc-cta" ?disabled=${s.saving} @click=${() => location.reload()}>+ Start chatting+ </button>`+ : html`<button class="btn primary mc-cta" ?disabled=${s.saving} @click=${closeManager}>Done</button>`;}+ let choices: TemplateResult;+ if (!s.loaded) choices = html`<button type="button" class="btn" @click=${() => void load()}>Retry</button>`;+ else if (s.intent)+ choices = html`<div class="mc-simple-connect">+ ${s.connections[s.intent.key] ? providerRow(s.intent) : connectBody(s.intent)}+ </div>`;+ else+ choices = html`<div class="mc-providers">+ ${methodRow(+ "Company access",+ s.required ? "Your organization requires a personal account." : "Use the access provided by your organization.",+ !s.personal,+ () => {+ if (!s.required) void switchAccount("company");+ },+ )}+ <p class="mc-account-hint">+ ${s.personal ? "Using a personal account. Choose a connected provider below." : "Or use your own account. Connect a provider, then choose Use account."}+ </p>+ ${PROVIDERS.map((p) => providerRow(p))}+ </div>`;+ let title = s.mode === "gate" ? "Connect your AI account" : "AI accounts";+ if (s.intent) title = `Connect ${s.intent.name}`;const body = s.loading? html`<div class="mc-waiting"><span class="mc-spinner" aria-hidden="true"></span>Loading…</div>`: html`${s.error ? html`<div class="mc-error" role="alert">${s.error}</div>` : nothing}- <div class="mc-providers">${PROVIDERS.map((p) => providerRow(p))}</div>- ${cta}+ ${s.saving || s.notice ? html`<p class="mc-notice" role="status">${s.saving ? "Saving changes…" : s.notice}</p>` : nothing}+ ${choices} ${s.intent ? nothing : cta}`;- let subCopy = "Chats run on the account you connect here, billed to you — not the organization.";- if (s.mode === "gate") {- subCopy =- "Your organization has each person chat on their own AI account. Connect one to get started — you can switch any time.";- } else if (s.required && !s.loading && !anyConnected) {- subCopy =- "Chats run on the account you connect here, billed to you — not the organization. Connect at least one to keep using the assistant.";- }+ const personalCopy =+ s.method === "apikey"+ ? "New chats will be billed to this API key."+ : `Use your ${s.intent?.subscription} subscription for new chats.`;+ const subCopy = s.intent+ ? personalCopy+ : "Choose who provides access for your chats on the web and in Slack. Background tasks continue using company access.";return html`<div class="signin">- <div class="signin-panel mc-panel">+ <div+ class="signin-panel mc-panel"+ role=${s.mode === "manager" ? "dialog" : "region"}+ aria-modal=${s.mode === "manager" ? "true" : nothing}+ aria-labelledby="mc-title"+ >${- s.mode === "manager" && !anyConnected && !s.loading- ? html`<button type="button" class="mc-close" aria-label="Close" title="Close" @click=${closeManager}>+ s.mode === "manager"+ ? html`<button+ type="button"+ class="mc-close"+ aria-label="Close"+ title="Close"+ ?disabled=${s.saving}+ @click=${closeManager}+ >×</button>`: nothing}${s.mode === "gate" ? html`<div class="signin-brand">${brandMark()}<span>${brandName()}</span></div>` : nothing}- <h1>${s.mode === "gate" ? "Connect your AI account" : "Your AI account"}</h1>+ <h1 id="mc-title">${title}</h1><p class="signin-body">${subCopy}</p>${body}</div>@@ -501,31 +719,57 @@ function view(): TemplateResult {function paint(): void {const el = target();- if (el) render(view(), el);+ if (!s.active || !el) return;+ const focused = document.activeElement;+ render(view(), el);+ if (s.mode === "manager" && focused && !focused.isConnected) {+ el.querySelector<HTMLElement>(".mc-provider.open .mc-provider-actions button, .mc-close")?.focus();+ }}function closeManager(): void {+ if (s.saving) return;stopPolling();+ s.active = false;+ s.controller.abort();overlay?.remove();overlay = null;- if (s.required && Object.keys(s.connections).length === 0) location.reload();+ restoreDialogFocus(opener, () => document.querySelector<HTMLElement>("[aria-label='Settings']"));+ opener = null;}export function renderModelConnectGate(): void {+ if (s) {+ stopPolling();+ s.active = false;+ s.controller.abort();+ }s = fresh("gate");paint();void load();}-export function openModelConnectManager(): void {+export function openModelConnectManager(provider?: "anthropic" | "openai"): void {if (overlay) return;+ opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;overlay = document.createElement("div");overlay.className = "mc-overlay";overlay.addEventListener("click", (e) => {- if (e.target === overlay) closeManager();+ if (!e.composedPath().some((node) => node instanceof Element && node.classList.contains("mc-panel")))+ closeManager();});+ overlay.addEventListener("keydown", (e) => trapDialogFocus(e, closeManager));document.body.appendChild(overlay);s = fresh("manager");+ s.intent = PROVIDERS.find((p) => p.apiName === provider) ?? null;paint();- void load();+ overlay.querySelector<HTMLElement>(".mc-close")?.focus();+ const state = s;+ void load().then(() => {+ if (current(state) && s.loaded && s.intent) {+ s.open = s.intent.key;+ if (!s.connections[s.intent.key]) void pickSubscription(s.intent);+ else paint();+ }+ });}diff --git a/plugins/web-ui/src/settings.ts b/plugins/web-ui/src/settings.tsindex d0cc4e7d3..892836cf4 100644--- a/plugins/web-ui/src/settings.ts+++ b/plugins/web-ui/src/settings.ts@@ -1,3 +1,5 @@+import { openModelConnectManager, type StatusResponse } from "./model-connect";+import { api } from "./core-bridge";import { html, nothing, render, type TemplateResult } from "lit";import { BookOpen, ExternalLink, LogOut, Monitor, Moon, ShieldUser, Sun, type IconNode } from "lucide";import { icon } from "./ui";@@ -234,6 +236,116 @@ function sidebarSurfaceRow(): TemplateResult {`;}+let aiStatus: StatusResponse | null = null;+let aiError = "";+let aiBusy = false;+let aiSaving = false;+let aiRevision = 0;++function acceptAiStatus(status: StatusResponse): void {+ aiRevision++;+ aiStatus = status;+ if (appState.me) {+ appState.me.individualModelAuth = status.individualModelAuth;+ appState.me.modelAuthConnected = status.connections.some(+ (c) => status.account === "personal" || status.account === c.provider,+ );+ }+ drawSettings();+}++window.addEventListener("model-account-changed", (event) => {+ const status = (event as CustomEvent<StatusResponse>).detail;+ if (status) {+ aiBusy = false;+ acceptAiStatus(status);+ }+});++async function loadAiStatus(): Promise<void> {+ if (aiSaving) return;+ const revision = ++aiRevision;+ aiBusy = true;+ aiError = "";+ drawSettings();+ try {+ const status = await api<StatusResponse>("/api/user-model-auth/status");+ if (revision !== aiRevision) return;+ acceptAiStatus(status);+ } catch (error) {+ aiError = errMessage(error);+ }+ aiBusy = false;+ drawSettings();+}++async function chooseAiAccount(account: "company" | "anthropic" | "openai"): Promise<void> {+ if (aiBusy || aiSaving) return;+ if (+ account === aiStatus?.account &&+ (account === "company" || aiStatus.connections.some((c) => c.provider === account))+ )+ return;+ if (account !== "company" && !aiStatus?.connections.some((c) => c.provider === account)) {+ openModelConnectManager(account);+ return;+ }+ aiSaving = true;+ aiError = "";+ drawSettings();+ try {+ const status = await api<StatusResponse>("/api/user-model-auth/account", {+ method: "POST",+ body: JSON.stringify({+ account: account === "company" ? "company" : "personal",+ provider: account === "company" ? undefined : account,+ }),+ });+ acceptAiStatus(status);+ window.dispatchEvent(new CustomEvent("model-account-changed", { detail: status }));+ } catch (error) {+ aiError = errMessage(error);+ }+ aiSaving = false;+ drawSettings();+}++function aiAccountsRow(): TemplateResult {+ return html`+ <div class="settings-row">+ <div class="settings-row-copy">+ <div class="settings-row-title">AI access</div>+ <div class="settings-row-note">Use company access or your own subscription.</div>+ ${aiError ? html`<div class="settings-row-error" role="alert">${aiError} <button class="settings-theme-link" ?disabled=${aiSaving} @click=${loadAiStatus}>Retry</button></div>` : nothing}+ </div>+ <div class="settings-ai-controls">+ <div class="settings-choice" role="group" aria-label="AI access">+ ${(+ [+ ["company", "Company"],+ ["anthropic", "Claude"],+ ["openai", "ChatGPT / Codex"],+ ] as const+ ).map(+ ([value, label]) => html`+ <button+ type="button"+ class="settings-choice-option ${aiStatus?.account === value ? "selected" : ""}"+ aria-pressed=${aiStatus?.account === value}+ ?disabled=${aiBusy || aiSaving || !aiStatus || (value === "company" && aiStatus.required)}+ @click=${() => void chooseAiAccount(value)}+ >+ ${label}+ </button>+ `,+ )}+ </div>+ ${aiStatus?.account === "anthropic" || aiStatus?.account === "openai" ? html`<button class="settings-theme-link" ?disabled=${aiBusy || aiSaving} @click=${() => openModelConnectManager(aiStatus!.account as "anthropic" | "openai")}>Connection settings</button>` : nothing}+ </div>+ </div>+ `;+}+function adminRow(): TemplateResult {return html`<div class="settings-row">@@ -287,7 +399,8 @@ function settingsPane(): TemplateResult {<h1 class="pane-title">Settings</h1></div><div class="settings-group">- ${themeRow()} ${sidebarSurfaceRow()} ${can("admin") ? adminRow() : nothing} ${aboutRow()} ${accountRow()}+ ${aiAccountsRow()} ${themeRow()} ${sidebarSurfaceRow()} ${can("admin") ? adminRow() : nothing} ${aboutRow()}+ ${accountRow()}</div>`;}@@ -304,4 +417,5 @@ function drawSettings(): void {export function renderSettings(): void {drawSettings();+ void loadAiStatus();}diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex f0beca213..6d34f2487 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -11023,6 +11023,7 @@ h3.ambient-field-label {.mc-panel {width: 520px;+ max-width: 100%;gap: 6px;}.mc-panel .signin-body {@@ -11037,11 +11038,15 @@ h3.ambient-field-label {align-items: center;justify-content: center;overflow: auto;+ padding: 24px;}.mc-overlay .signin {height: auto;min-height: 0;- padding: 32px 24px;+ padding: 0;+ width: min(420px, 100%);+ max-height: 100%;+ overflow: auto;}.mc-overlay .signin-panel {background: var(--background);@@ -11070,8 +11075,21 @@ h3.ambient-field-label {background: var(--background);border-color: var(--muted-foreground);}+.mc-account-hint,+.mc-notice {+ margin: 0;+ font-size: 13px;+ color: var(--muted-foreground);+}+.mc-provider-actions {+ margin-left: auto;+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+}.mc-provider-row {display: flex;+ flex-wrap: wrap;align-items: center;gap: 12px;padding: 14px 16px;@@ -11096,7 +11114,7 @@ h3.ambient-field-label {}.mc-provider-text {flex: 1;- min-width: 0;+ min-width: 100px;display: flex;flex-direction: column;line-height: 1.35;@@ -11179,34 +11197,17 @@ h3.ambient-field-label {position: relative;}.mc-steps {- margin: 2px 0 14px;- padding: 2px 0 2px 4px;+ margin: 0;+ padding: 0;display: flex;flex-direction: column;gap: 12px;- counter-reset: mcstep;list-style: none;}.mc-steps > li {display: flex;align-items: flex-start;gap: 10px;- counter-increment: mcstep;-}-.mc-steps > li::before {- content: counter(mcstep);- flex: none;- width: 20px;- height: 20px;- margin-top: 3px;- border-radius: 50%;- border: 1px solid var(--border);- color: var(--muted-foreground);- font-size: 11px;- font-weight: 600;- display: flex;- align-items: center;- justify-content: center;}.mc-steps > li > * {min-width: 0;@@ -11277,10 +11278,10 @@ h3.ambient-field-label {}.mc-close {position: absolute;- top: 12px;- right: 12px;- width: 28px;- height: 28px;+ top: 8px;+ right: 8px;+ width: 44px;+ height: 44px;display: flex;align-items: center;justify-content: center;@@ -11965,3 +11966,57 @@ body.app-edit-embed .custom-chat-shell.app-edit-chat > .chat-bottom-dock {.stopped-work[open] > .stopped-head > .activity-chevron {transform: rotate(90deg);}++.settings-ai-controls {+ display: flex;+ flex-direction: column;+ align-items: flex-end;+ gap: 8px;+}+.mc-simple-flow {+ display: flex;+ flex-direction: column;+ align-items: stretch;+ gap: 16px;+}+.mc-simple-flow > .settings-theme-link {+ align-self: flex-start;+}++.mc-overlay .mc-panel h1 {+ font-family: var(--app-font);+ font-size: 20px;+ line-height: 1.3;+ font-weight: 600;+ letter-spacing: -0.3px;+ margin: 0 28px 8px 0;+}+.mc-overlay .mc-panel .signin-body {+ font-size: 13px;+ line-height: 1.5;+ margin: 0 0 24px;+}+.mc-simple-flow .mc-steps {+ gap: 16px;+}+.mc-simple-flow .mc-steps .btn {+ width: 100%;+ min-height: 36px;+ justify-content: center;+}+.mc-simple-flow .mc-field > span {+ font-weight: 400;+ margin-bottom: 2px;+}+.mc-simple-flow > .settings-theme-link {+ font-size: 12px;+ text-decoration: none;+ color: var(--muted-foreground);+}+.mc-simple-flow > .settings-theme-link:hover {+ color: var(--foreground);+ text-decoration: underline;+}+.settings-ai-controls .settings-choice {+ flex-wrap: wrap;+}diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.tsindex ab5c4de9b..606576dd9 100644--- a/plugins/web-ui/src/shell.ts+++ b/plugins/web-ui/src/shell.ts@@ -1,6 +1,6 @@import { initializeAnalytics, capturePageview, stopAnalytics } from "./product-analytics";import { captureConnectionReturn } from "./connection-return";-import { openModelConnectManager, renderModelConnectGate } from "./model-connect";+import { renderModelConnectGate } from "./model-connect";import { html, nothing, render, type TemplateResult } from "lit";import {Box,@@ -564,7 +564,6 @@ export function renderSidebarFooter(): void {${userMenuOpen? html`<div class="session-menu-popover user-menu-popover" role="menu">- ${appState.me?.individualModelAuth ? html`<button class="session-menu-option" type="button" role="menuitem" @click=${openModelConnectManager}>Manage AI account</button>` : nothing}<button class="session-menu-option" type="button" role="menuitem" @click=${signOutFromMenu}>${icon(LogOut, 15)}<span>Sign out</span></button>diff --git a/plugins/web-ui/test/model-connect-interactions.test.ts b/plugins/web-ui/test/model-connect-interactions.test.tsnew file mode 100644index 000000000..a6374ae95--- /dev/null+++ b/plugins/web-ui/test/model-connect-interactions.test.ts@@ -0,0 +1,514 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import { fileURLToPath } from "node:url";+import { JSDOM } from "jsdom";+import { createServer } from "vite";++test("AI account modal interactions", async (t) => {+ const dom = new JSDOM('<!doctype html><div id="app"></div><button id="opener">Manage AI accounts</button>', {+ url: "http://localhost/settings",+ });+ Object.defineProperty(dom.window, "matchMedia", {+ value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),+ });+ for (const [key, value] of Object.entries({+ window: dom.window,+ document: dom.window.document,+ location: dom.window.location,+ history: dom.window.history,+ navigator: dom.window.navigator,+ localStorage: dom.window.localStorage,+ HTMLElement: dom.window.HTMLElement,+ Element: dom.window.Element,+ Node: dom.window.Node,+ customElements: dom.window.customElements,+ Event: dom.window.Event,+ CustomEvent: dom.window.CustomEvent,+ requestAnimationFrame: (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0),+ cancelAnimationFrame: clearTimeout,+ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),+ }))+ Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });+ const vite = await createServer({+ root: fileURLToPath(new URL("..", import.meta.url)),+ server: { middlewareMode: true, hmr: false },+ appType: "custom",+ plugins: [+ {+ name: "settings-shell-boundary",+ enforce: "pre",+ resolveId(source, importer) {+ if (!importer?.endsWith("/src/settings.ts")) return;+ if (source === "./shell" || source === "./sessions") return `\0settings-test:${source}`;+ },+ load(id) {+ if (id === "\0settings-test:./shell")+ return 'export { appState, can } from "/src/shell-state.ts"; export const ADMIN_HOME_URL = "/admin"; export function signOut() {}';+ if (id === "\0settings-test:./sessions")+ return "export const sessionsState = { webOnly: false }; export function setWebOnly(value) { sessionsState.webOnly = value; }";+ },+ },+ ],+ });+ const { openModelConnectManager, renderModelConnectGate } = await vite.ssrLoadModule("/src/model-connect.ts");+ const { appState } = await vite.ssrLoadModule("/src/shell-state.ts");+ appState.me = { user: "alice", org: "acme" };+ const doc = dom.window.document;+ const status = (account = "company", connections: { provider: string; kind: string }[] = []) => ({+ account,+ individualModelAuth: account !== "company",+ required: false,+ connections,+ });+ const pendingDevice = {+ deviceAuthId: "test-login",+ userCode: "TEST-CODE",+ verificationUrl: "https://example.test/device",+ expiresAt: Date.now() + 600_000,+ intervalMs: 60_000,+ };+ let fetcher: (path: string, init?: RequestInit) => Promise<Response>;+ globalThis.fetch = async (input, init) => fetcher(String(input), init);+ const tick = () => new Promise((resolve) => setTimeout(resolve, 20));+ const button = (label: string) => {+ const found = [...doc.querySelectorAll<HTMLButtonElement>(".mc-overlay button")].find(+ (b) => b.textContent?.trim() === label || b.getAttribute("aria-label") === label,+ );+ assert.ok(found, `button ${label} exists`);+ return found;+ };+ const provider = (name: string) => {+ const found = [...doc.querySelectorAll<HTMLElement>(".mc-provider")].find(+ (el) => el.querySelector("strong")?.textContent === name,+ );+ assert.ok(found, `provider ${name} exists`);+ return found;+ };+ const providerButton = (name: string, label: string) => {+ const found = [...provider(name).querySelectorAll<HTMLButtonElement>("button")].find(+ (b) => b.textContent?.trim() === label || b.querySelector(".mc-method-title")?.textContent === label,+ );+ assert.ok(found, `${name}: ${label} exists`);+ found.click();+ };+ const open = async () => {+ doc.querySelector<HTMLButtonElement>("#opener")!.focus();+ openModelConnectManager();+ await tick();+ };+ const close = () => doc.querySelector<HTMLButtonElement>(".mc-close")?.click();+ const base = async (path: string) => {+ if (path.endsWith("/status")) return Response.json(status());+ if (path.endsWith("/chatgpt/start")) return Response.json(pendingDevice);+ if (path.endsWith("/chatgpt/poll")) return Response.json({ status: "pending" });+ if (path.endsWith("/claude/start"))+ return Response.json({ authorizeUrl: "https://example.test/claude", verifier: "test-verifier" });+ throw new Error(`Unexpected request ${path}`);+ };+ t.after(async () => {+ close();+ await vite.close();+ dom.window.close();+ });++ await t.test("Escape, focus trap, backdrop close, and focus restoration work", async () => {+ fetcher = base;+ await open();+ assert.equal(doc.activeElement, button("Close"));+ const last = button("Done");+ last.focus();+ last.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true }));+ assert.equal(doc.activeElement, button("Close"));+ button("Close").dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "Escape", bubbles: true }));+ assert.equal(doc.querySelector(".mc-overlay"), null);+ assert.equal(doc.activeElement?.id, "opener");+ await open();+ doc.querySelector<HTMLElement>(".mc-overlay .signin")!.click();+ assert.equal(doc.querySelector(".mc-overlay"), null);+ });++ await t.test("an initial status failure is retryable and never shows a guessed account", async () => {+ let fail = true;+ fetcher = async (path) => (fail ? Response.json({ error: "offline" }, { status: 503 }) : base(path));+ await open();+ assert.match(doc.querySelector("[role=alert]")!.textContent!, /offline/);+ assert.equal(doc.querySelector(".mc-providers"), null);+ fail = false;+ button("Retry").click();+ await tick();+ assert.ok(doc.querySelector(".mc-providers"));+ close();+ });++ await t.test("switching providers clears key drafts; selecting the same method preserves them", async () => {+ fetcher = base;+ await open();+ providerButton("ChatGPT / Codex", "Connect");+ providerButton("ChatGPT / Codex", "Use an API key");+ const input = doc.querySelector<HTMLInputElement>("input")!;+ input.value = "test-only-openai-key";+ input.dispatchEvent(new dom.window.Event("input", { bubbles: true }));+ providerButton("ChatGPT / Codex", "Use an API key");+ assert.equal(doc.querySelector<HTMLInputElement>("input")!.value, "test-only-openai-key");+ providerButton("Claude", "Connect");+ assert.equal(doc.querySelector("input"), null);+ providerButton("Claude", "Use an API key");+ assert.equal(doc.querySelector<HTMLInputElement>("input")!.value, "");+ providerButton("Claude", "Cancel");+ assert.equal(doc.querySelector("input"), null);+ close();+ });++ await t.test("a delayed sign-in response cannot overwrite a reopened modal", async () => {+ let resolveStart!: (r: Response) => void;+ fetcher = (path) =>+ path.endsWith("/chatgpt/start")+ ? new Promise((resolve) => {+ resolveStart = resolve;+ })+ : base(path);+ await open();+ providerButton("ChatGPT / Codex", "Connect");+ providerButton("ChatGPT / Codex", "Sign in with ChatGPT / Codex");+ close();+ await open();+ providerButton("Claude", "Connect");+ providerButton("Claude", "Use an API key");+ resolveStart(Response.json(pendingDevice));+ await tick();+ assert.ok(provider("Claude").querySelector("input"));+ assert.equal(doc.querySelector(".mc-code"), null);+ close();+ });++ await t.test("poll errors stay visible and allow a fresh sign-in", async () => {+ let starts = 0;+ fetcher = (path) => {+ if (path.endsWith("/chatgpt/start")) starts++;+ return path.endsWith("/chatgpt/poll")+ ? Promise.resolve(Response.json({ message: "login expired or unknown" }, { status: 502 }))+ : base(path);+ };+ await open();+ providerButton("ChatGPT / Codex", "Connect");+ providerButton("ChatGPT / Codex", "Sign in with ChatGPT / Codex");+ await tick();+ assert.match(doc.querySelector("[role=alert]")!.textContent!, /expired/);+ providerButton("ChatGPT / Codex", "Sign in with ChatGPT / Codex");+ await tick();+ assert.equal(starts, 2);+ close();+ });++ await t.test("an in-flight successful poll cannot overlap a key save or reopened modal", async () => {+ let resolvePoll!: (response: Response) => void;+ let connected = false;+ fetcher = (path) => {+ if (path.endsWith("/chatgpt/poll"))+ return new Promise((resolve) => {+ resolvePoll = resolve;+ });+ if (path.endsWith("/status"))+ return Promise.resolve(+ Response.json(status("company", connected ? [{ provider: "openai", kind: "oauth" }] : [])),+ );+ return base(path);+ };+ await open();+ providerButton("ChatGPT / Codex", "Connect");+ providerButton("ChatGPT / Codex", "Sign in with ChatGPT / Codex");+ await tick();+ providerButton("ChatGPT / Codex", "Use an API key");+ assert.equal(doc.querySelector("input"), null);+ assert.equal(button("Cancel").disabled, true);+ close();+ assert.ok(doc.querySelector(".mc-overlay"));+ connected = true;+ resolvePoll(Response.json({ status: "connected" }));+ await tick();+ assert.ok(provider("ChatGPT / Codex").classList.contains("connected"));+ assert.equal(button("Done").disabled, false);+ close();+ });++ await t.test(+ "key errors preserve the draft, success refreshes connections, and disconnect keeps the chosen billing source",+ async () => {+ let connected = false;+ let fail = true;+ let account = "company";+ fetcher = async (path, init) => {+ if (path.endsWith("/api-key")) {+ if (fail) return Response.json({ error: "invalid_api_key" }, { status: 400 });+ connected = true;+ return Response.json({ ok: true });+ }+ if (path.endsWith("/account")) account = JSON.parse(String(init?.body)).provider;+ if (path.endsWith("/disconnect")) {+ connected = false;+ return Response.json({ ok: true });+ }+ return Response.json(status(account, connected ? [{ provider: "anthropic", kind: "apikey" }] : []));+ };+ await open();+ providerButton("Claude", "Connect");+ providerButton("Claude", "Use an API key");+ const input = doc.querySelector<HTMLInputElement>("input")!;+ input.value = "test-only-key";+ input.dispatchEvent(new dom.window.Event("input", { bubbles: true }));+ providerButton("Claude", "Connect");+ await tick();+ assert.match(doc.querySelector("[role=alert]")!.textContent!, /rejected/);+ assert.equal(doc.querySelector<HTMLInputElement>("input")!.value, "test-only-key");+ fail = false;+ providerButton("Claude", "Connect");+ await tick();+ assert.ok(provider("Claude").classList.contains("connected"));+ assert.equal(appState.me.individualModelAuth, false);+ providerButton("Claude", "Use account");+ await tick();+ providerButton("Claude", "Disconnect");+ await tick();+ assert.equal(appState.me.individualModelAuth, true);+ assert.equal(appState.me.modelAuthConnected, false);+ assert.match(doc.querySelector("[role=status]")!.textContent!, /Reconnect/);+ close();+ },+ );++ await t.test("account saves finish before the modal can close", async () => {+ let resolveSave!: (response: Response) => void;+ const connections = [{ provider: "openai", kind: "oauth" }];+ fetcher = (path) =>+ path.endsWith("/account")+ ? new Promise((resolve) => {+ resolveSave = resolve;+ })+ : Promise.resolve(Response.json(status("company", connections)));+ await open();+ providerButton("ChatGPT / Codex", "Use account");+ assert.equal(button("Done").disabled, true);+ close();+ doc+ .querySelector(".mc-overlay")!+ .dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "Escape", bubbles: true }));+ doc.querySelector<HTMLElement>(".mc-overlay .signin")!.click();+ assert.ok(doc.querySelector(".mc-overlay"));+ resolveSave(Response.json(status("openai", connections)));+ await tick();+ assert.equal(appState.me.individualModelAuth, true);+ assert.equal(button("Done").disabled, false);+ close();+ assert.equal(doc.querySelector(".mc-overlay"), null);+ });++ await t.test("a pending key save prevents cancellation and overlapping writes", async () => {+ let resolveSave!: (response: Response) => void;+ let writes = 0;+ fetcher = (path) => {+ if (path.endsWith("/api-key")) {+ writes++;+ return new Promise((resolve) => {+ resolveSave = resolve;+ });+ }+ return base(path);+ };+ await open();+ providerButton("Claude", "Connect");+ providerButton("Claude", "Use an API key");+ const input = doc.querySelector<HTMLInputElement>("input")!;+ input.value = "test-only-key";+ input.dispatchEvent(new dom.window.Event("input", { bubbles: true }));+ providerButton("Claude", "Connect");+ assert.equal(button("Cancel").disabled, true);+ providerButton("Claude", "Cancel");+ const submit = provider("Claude").querySelector<HTMLButtonElement>(".btn.primary")!;+ assert.equal(submit.disabled, true);+ submit.click();+ providerButton("ChatGPT / Codex", "Connect");+ assert.equal(writes, 1);+ assert.ok(provider("Claude").querySelector("input"));+ resolveSave(Response.json({ error: "invalid_api_key" }, { status: 400 }));+ await tick();+ assert.equal(button("Cancel").disabled, false);+ assert.equal(button("Done").disabled, false);+ assert.equal(doc.querySelector<HTMLInputElement>("input")!.value, "test-only-key");+ close();+ });++ await t.test("choosing a provider opens only its sign-in and activates it after connecting", async () => {+ let connected = false;+ let account = "company";+ fetcher = async (path, init) => {+ if (path.endsWith("/status"))+ return Response.json(status(account, connected ? [{ provider: "anthropic", kind: "apikey" }] : []));+ if (path.endsWith("/api-key")) {+ connected = true;+ return Response.json({ ok: true });+ }+ if (path.endsWith("/account")) {+ account = JSON.parse(String(init?.body)).provider;+ return Response.json(status(account, [{ provider: "anthropic", kind: "apikey" }]));+ }+ return base(path);+ };+ openModelConnectManager("anthropic");+ await tick();+ assert.equal(doc.querySelector("#mc-title")!.textContent?.trim(), "Connect Claude");+ assert.equal(doc.querySelector(".mc-providers"), null);+ assert.equal(doc.querySelector(".mc-method"), null);+ button("Use an API key instead").click();+ const input = doc.querySelector<HTMLInputElement>("input")!;+ input.value = "test-only-key";+ input.dispatchEvent(new dom.window.Event("input", { bubbles: true }));+ button("Connect").click();+ await tick();+ assert.equal(account, "anthropic");+ assert.equal(appState.me.individualModelAuth, true);+ assert.equal(doc.querySelector(".mc-overlay"), null);+ });++ await t.test("expired device codes offer a new sign-in rather than polling forever", async () => {+ let polls = 0;+ fetcher = (path) => {+ if (path.endsWith("/chatgpt/start")) return Promise.resolve(Response.json({ ...pendingDevice, expiresAt: 1 }));+ if (path.endsWith("/chatgpt/poll")) polls++;+ return base(path);+ };+ await open();+ providerButton("ChatGPT / Codex", "Connect");+ providerButton("ChatGPT / Codex", "Sign in with ChatGPT / Codex");+ await tick();+ assert.match(doc.querySelector("[role=alert]")!.textContent!, /expired/);+ assert.equal(polls, 0);+ assert.equal(doc.querySelector(".mc-code"), null);+ close();+ });++ await t.test("switching accounts updates the modal and app without reloading or disconnecting", async () => {+ const connections = [+ { provider: "openai", kind: "oauth" },+ { provider: "anthropic", kind: "apikey" },+ ];+ let account = "company";+ const writes: unknown[] = [];+ fetcher = async (path, init) => {+ if (path.endsWith("/account")) {+ const body = JSON.parse(String(init?.body));+ writes.push(body);+ account = body.account === "company" ? "company" : body.provider;+ }+ return Response.json(status(account, connections));+ };+ await open();+ providerButton("ChatGPT / Codex", "Use account");+ await tick();+ assert.equal(appState.me.individualModelAuth, true);+ assert.ok(provider("ChatGPT / Codex").textContent?.includes("In use"));+ assert.equal(doc.querySelector("[role=status]")?.textContent, "New chats will use your ChatGPT / Codex account.");+ const company = [...doc.querySelectorAll<HTMLButtonElement>(".mc-method")].find((b) =>+ b.textContent?.includes("Company access"),+ )!;+ company.click();+ await tick();+ assert.equal(appState.me.individualModelAuth, false);+ assert.equal(writes.length, 2);+ assert.equal(doc.querySelectorAll(".mc-provider.connected").length, 2);+ company.click();+ await tick();+ assert.equal(writes.length, 2);+ close();+ });++ await t.test("the startup gate activates the newly connected provider before allowing chats", async () => {+ let account = "anthropic";+ let connected = false;+ let resolveSave!: (response: Response) => void;+ const connections = () => (connected ? [{ provider: "openai", kind: "apikey" }] : []);+ fetcher = async (path, init) => {+ if (path.endsWith("/status")) return Response.json(status(account, connections()));+ if (path.endsWith("/api-key")) {+ connected = true;+ return Response.json({ ok: true });+ }+ if (path.endsWith("/account")) {+ assert.deepEqual(JSON.parse(String(init?.body)), { account: "personal", provider: "openai" });+ return new Promise((resolve) => {+ resolveSave = resolve;+ });+ }+ return base(path);+ };+ renderModelConnectGate();+ await tick();+ providerButton("ChatGPT / Codex", "Connect");+ providerButton("ChatGPT / Codex", "Use an API key");+ const input = doc.querySelector<HTMLInputElement>("#app input")!;+ input.value = "test-only-key";+ input.dispatchEvent(new dom.window.Event("input", { bubbles: true }));+ providerButton("ChatGPT / Codex", "Connect");+ await tick();+ const startButton = () =>+ [...doc.querySelectorAll<HTMLButtonElement>("#app button")].find(+ (el) => el.textContent?.trim() === "Start chatting",+ );+ assert.ok(!startButton() || startButton()!.disabled);+ assert.equal(typeof resolveSave, "function");+ account = "openai";+ resolveSave(Response.json(status(account, connections())));+ await tick();+ assert.equal(appState.me.modelAuthConnected, true);+ assert.equal(startButton()?.disabled, false);+ assert.match(provider("ChatGPT / Codex").textContent!, /In use/);+ doc.querySelector("#app")!.replaceChildren();+ });++ await t.test("settings keeps switches and connection settings locked until its account write finishes", async () => {+ const { renderSettings } = await vite.ssrLoadModule("/src/settings.ts");+ const connections = [+ { provider: "anthropic", kind: "oauth" },+ { provider: "openai", kind: "oauth" },+ ];+ let resolveSave!: (response: Response) => void;+ let writes = 0;+ fetcher = async (path) => {+ if (path.endsWith("/account")) {+ writes++;+ return new Promise((resolve) => {+ resolveSave = resolve;+ });+ }+ return Response.json(status("anthropic", connections));+ };+ appState.currentView = "settings";+ appState.mainEl = doc.querySelector("#app");+ renderSettings();+ await tick();+ const choice = (label: string) =>+ [...doc.querySelectorAll<HTMLButtonElement>('[aria-label="AI access"] button')].find(+ (el) => el.textContent?.trim() === label,+ )!;+ const manage = () =>+ [...doc.querySelectorAll<HTMLButtonElement>(".settings-ai-controls button")].find(+ (el) => el.textContent?.trim() === "Connection settings",+ )!;+ choice("ChatGPT / Codex").click();+ assert.equal(writes, 1);+ assert.equal(manage().disabled, true);+ manage().click();+ assert.equal(doc.querySelector(".mc-overlay"), null);+ window.dispatchEvent(new CustomEvent("model-account-changed", { detail: status("anthropic", connections) }));+ assert.equal(choice("Company").disabled, true);+ assert.equal(manage().disabled, true);+ choice("Company").click();+ assert.equal(writes, 1);+ resolveSave(Response.json(status("openai", connections)));+ await tick();+ assert.equal(choice("Company").disabled, false);+ assert.equal(choice("ChatGPT / Codex").getAttribute("aria-pressed"), "true");+ assert.equal(manage().disabled, false);+ appState.currentView = "chats";+ appState.mainEl = null;+ });+});diff --git a/src/api/app-turn.ts b/src/api/app-turn.tsindex dd361139e..bccd1839f 100644--- a/src/api/app-turn.ts+++ b/src/api/app-turn.ts@@ -164,7 +164,20 @@ export function createTurnMethods(return (await deps.projects.withVersion(conversationRef, projectVersion, fn)) ?? null;}- const individualAuth = !!deps.userModelCredentials && (await deps.config.getIndividualModelAuthDurable());+ const approvedRequest = req.approval ? (await deps.approvals?.get(req.approval.requestId))?.request : undefined;+ const sameApprovedMessage =+ approvedRequest?.text === req.text &&+ approvedRequest.actor.externalId === req.actor.externalId &&+ approvedRequest.conversation.threadRef === req.conversation.threadRef;+ let privateRequest = req.privateSessionMessage ? req : undefined;+ if (approvedRequest?.privateSessionMessage) privateRequest = approvedRequest;+ const origin = resolveTurnOrigin(privateRequest ?? req);++ const modelAccount =+ deps.userModelCredentials && origin.kind === "human"+ ? await deps.config.getModelAccountDurable(actor.id)+ : "company";+ const individualAuth = modelAccount !== "company";if (req.surface === "web") {const threadRef = req.conversation.threadRef;const existing = await deps.sessions.getByThread(threadRef);@@ -269,15 +282,6 @@ export function createTurnMethods(...(publishMembers ? { publishMembers } : {}),};- const approvedRequest = req.approval ? (await deps.approvals?.get(req.approval.requestId))?.request : undefined;- const sameApprovedMessage =- approvedRequest?.text === req.text &&- approvedRequest.actor.externalId === req.actor.externalId &&- approvedRequest.conversation.threadRef === req.conversation.threadRef;- let privateRequest = req.privateSessionMessage ? req : undefined;- if (approvedRequest?.privateSessionMessage) privateRequest = approvedRequest;- const origin = resolveTurnOrigin(privateRequest ?? req);-const input = {surface: req.surface,...(sameApprovedMessage && approvedRequest?.sessionSenderId@@ -288,6 +292,7 @@ export function createTurnMethods(actor,conversation,origin,+ modelAccount: origin.kind === "human" ? modelAccount : ("company" as const),text: req.text,...(req.gatewayContext ? { gatewayContext: req.gatewayContext } : {}),...(req.proactiveOpener ? { proactiveOpener: true } : {}),@@ -490,78 +495,101 @@ export function createTurnMethods(}}const targetRun = live;- const steerText = attributedSteerText(- actor,- origin.kind === "ambient" ? null : targetRun.request.actor.id,- req.text,- );- let injectedText = steerText;- if (origin.kind === "ambient") {- const session = await deps.sessions.getByThread(conversation.threadRef);- const decision = await deps.orchestrator.screenSecuritySteer({- payload: steerText,- actor,- conversation,- ...(session ? { sessionId: session.id } : {}),+ const sameAccount =+ targetRun.request.modelAccount !== undefined &&+ targetRun.request.modelAccount === input.modelAccount &&+ (input.modelAccount === "company" || targetRun.request.actor.id === actor.id);+ const cancel = origin.kind === "human" && (targetedCancel || isHalt(req.text));+ if (conversationRouting && !cancel && !sameAccount) {+ const { run, deduped } = await deps.runs.enqueue({+ sessionId: targetRun.sessionId,+ request: {+ ...input,+ deliveryTarget: req.gatewayContext?.details?.thread_ts+ ? input.deliveryTarget+ : (targetRun.request.deliveryTarget ?? input.deliveryTarget),+ conversation: { ...input.conversation, threadRef: targetRun.request.conversation.threadRef },+ },+ dedupKey: redeliveryKey,+ maxAttempts: deps.maxAttempts,});- if (decision === "block")- return req.async ? { status: "queued", runId: targetRun.id, steered: true } : drive(targetRun.id);- if (decision === "unscreened") injectedText = `${unscreenedNotice("mid-turn message")}\n${steerText}`;+ if (deduped) return { status: "silent" };+ return req.async ? { status: "queued", runId: run.id, conversationAside: true } : drive(run.id);}- const fileNames = (req.attachments ?? []).map((a) =>- a.sourceId- ? `${a.name} (fetch via surface-file, ts ${origin.kind === "human" ? (origin.messageTs ?? origin.entryTs) : origin.entryTs})`- : a.name,- );- const wake: Wake = {- situation: origin.kind === "ambient" ? "ambientUpdate" : "addressed",- ts: String(req.clientSentAt ?? Date.now()),- text: injectedText,- halt: origin.kind === "human" && (targetedCancel || isHalt(req.text)),- ...(fileNames.length ? { fileNames } : {}),- };- const route = routeWake(wake, true, resolveTurnOrigin(targetRun.request).kind === "ambient");- if (route.kind === "steer" || route.kind === "drop") {- const steerTs = origin.kind === "human" ? (origin.messageTs ?? origin.entryTs) : origin.entryTs;- let redelivered = false;- const routedRunId = await withCurrentProjectRoster(async () => {- if (route.kind === "steer")- redelivered = !(await deps.signals!.send(targetRun.id, {- kind: route.signal,- ...(route.text ? { text: route.text } : {}),- ...(steerTs ? { ts: steerTs } : {}),- ...(route.signal === "steer"- ? {- request: {- ...req,- ...(conversationRouting- ? {- deliveryTarget: targetRun.request.deliveryTarget ?? req.deliveryTarget,- }- : {}),- conversation: { ...req.conversation, threadRef: targetRun.request.conversation.threadRef },- },- }- : {}),- ...(redeliveryKey ? { dedupeKey: redeliveryKey } : {}),- }));- return targetRun.id;- });- if (!routedRunId)- return { status: "refused", reason: "project membership changed; retry from the current project" };- if (redelivered)- return req.async ? { status: "queued", runId: routedRunId, steered: true } : drive(routedRunId);- if (route.kind === "steer") {- const after = await deps.runs.get(targetRun.id);- if (!after || isTerminal(after.status)) {- const own = (await replayOrphanedRunSignals(targetRun.id)).find(- (d) => d.signal.text === route.text && d.signal.ts === steerTs,- );- if (own?.replayRunId)- return req.async ? { status: "queued", runId: own.replayRunId } : drive(own.replayRunId);+ if (!isTerminal(targetRun.status) && (cancel || sameAccount)) {+ const steerText = attributedSteerText(+ actor,+ origin.kind === "ambient" ? null : targetRun.request.actor.id,+ req.text,+ );+ let injectedText = steerText;+ if (origin.kind === "ambient") {+ const session = await deps.sessions.getByThread(conversation.threadRef);+ const decision = await deps.orchestrator.screenSecuritySteer({+ payload: steerText,+ actor,+ conversation,+ ...(session ? { sessionId: session.id } : {}),+ });+ if (decision === "block")+ return req.async ? { status: "queued", runId: targetRun.id, steered: true } : drive(targetRun.id);+ if (decision === "unscreened") injectedText = `${unscreenedNotice("mid-turn message")}\n${steerText}`;+ }+ const fileNames = (req.attachments ?? []).map((a) =>+ a.sourceId+ ? `${a.name} (fetch via surface-file, ts ${origin.kind === "human" ? (origin.messageTs ?? origin.entryTs) : origin.entryTs})`+ : a.name,+ );+ const wake: Wake = {+ situation: origin.kind === "ambient" ? "ambientUpdate" : "addressed",+ ts: String(req.clientSentAt ?? Date.now()),+ text: injectedText,+ halt: origin.kind === "human" && (targetedCancel || isHalt(req.text)),+ ...(fileNames.length ? { fileNames } : {}),+ };+ const route = routeWake(wake, true, resolveTurnOrigin(targetRun.request).kind === "ambient");+ if (route.kind === "steer" || route.kind === "drop") {+ const steerTs = origin.kind === "human" ? (origin.messageTs ?? origin.entryTs) : origin.entryTs;+ let redelivered = false;+ const routedRunId = await withCurrentProjectRoster(async () => {+ if (route.kind === "steer")+ redelivered = !(await deps.signals!.send(targetRun.id, {+ kind: route.signal,+ ...(route.text ? { text: route.text } : {}),+ ...(steerTs ? { ts: steerTs } : {}),+ ...(route.signal === "steer"+ ? {+ request: {+ ...req,+ ...(conversationRouting+ ? {+ deliveryTarget: targetRun.request.deliveryTarget ?? req.deliveryTarget,+ }+ : {}),+ conversation: { ...req.conversation, threadRef: targetRun.request.conversation.threadRef },+ },+ }+ : {}),+ ...(redeliveryKey ? { dedupeKey: redeliveryKey } : {}),+ }));+ return targetRun.id;+ });+ if (!routedRunId)+ return { status: "refused", reason: "project membership changed; retry from the current project" };+ if (redelivered)+ return req.async ? { status: "queued", runId: routedRunId, steered: true } : drive(routedRunId);+ if (route.kind === "steer") {+ const after = await deps.runs.get(targetRun.id);+ if (!after || isTerminal(after.status)) {+ const own = (await replayOrphanedRunSignals(targetRun.id)).find(+ (d) => d.signal.text === route.text && d.signal.ts === steerTs,+ );+ if (own?.replayRunId)+ return req.async ? { status: "queued", runId: own.replayRunId } : drive(own.replayRunId);+ }}+ return req.async ? { status: "queued", runId: routedRunId, steered: true } : drive(routedRunId);}- return req.async ? { status: "queued", runId: routedRunId, steered: true } : drive(routedRunId);}}}@@ -584,7 +612,12 @@ export function createTurnMethods(const ambientSession = await deps.sessions.getByThread(ambientRef);if (ambientSession) {const liveAmbient = await deps.runs.activeForThread(ambientRef);- if (liveAmbient && !isTerminal(liveAmbient.status)) {+ if (+ liveAmbient &&+ !isTerminal(liveAmbient.status) &&+ input.modelAccount === "company" &&+ liveAmbient.request.modelAccount === "company"+ ) {const routedRunId = await withCurrentProjectRoster(async () => {if (deps.signals)await deps.signals.send(liveAmbient.id, {@@ -837,6 +870,17 @@ export function createTurnMethods(if (signal.request && signal.request.conversation.threadRef !== run.request.conversation.threadRef) {return { accepted: false, reason: "conversation_mismatch" };}+ if (signal.kind === "steer") {+ const principal = viewer ?? signal.request?.actor.externalId ?? run.request.actor.id;+ const account = principal ? await deps.config.getModelAccountDurable(principal) : undefined;+ if (+ !account ||+ run.request.modelAccount !== account ||+ (account !== "company" && run.request.actor.id !== principal)+ ) {+ return { accepted: false, reason: "account_changed: send a new message to use your selected AI account" };+ }+ }let outbound = signal;if (signal.kind === "steer") {const requestActor = signal.request?.actor;diff --git a/src/api/routes/user-model-auth.ts b/src/api/routes/user-model-auth.tsindex 0e3a6e8ce..754efb076 100644--- a/src/api/routes/user-model-auth.ts+++ b/src/api/routes/user-model-auth.ts@@ -26,7 +26,41 @@ async function getStatus(ctx: ApiCtx): Promise<void> {if (!principal) return sendJson(ctx.res, 401, { error: "unauthorized" });const required = (await ctx.deps.config?.getIndividualModelAuthDurable()) ?? false;const connections = (await ctx.deps.userModelCredentials?.connections(principal)) ?? [];- return sendJson(ctx.res, 200, { individualModelAuth: required, connections });+ const individualModelAuth = (await ctx.deps.config?.getIndividualModelAuthDurable(principal)) ?? false;+ const account = (await ctx.deps.config?.getModelAccountDurable(principal)) ?? "company";+ return sendJson(ctx.res, 200, { individualModelAuth, required, account, connections });+}++async function setAccount(ctx: ApiCtx): Promise<void> {+ const principal = caller(ctx);+ if (!principal) return sendJson(ctx.res, 401, { error: "unauthorized" });+ if (!ctx.deps.config || !ctx.deps.userModelCredentials) return sendJson(ctx.res, 404, { error: "not_found" });+ const account = bodyObj(ctx).account;+ if (account !== "personal" && account !== "company") return sendJson(ctx.res, 400, { error: "bad_request" });+ if (account === "company" && (await ctx.deps.config.getIndividualModelAuthDurable())) {+ return sendJson(ctx.res, 403, { error: "Your organization requires a personal AI account." });+ }+ if (account === "personal" && !(await ctx.deps.userModelCredentials.connections(principal)).length) {+ return sendJson(ctx.res, 409, { error: "Connect an AI account first." });+ }+ const provider = bodyObj(ctx).provider;+ if (provider !== undefined && provider !== "anthropic" && provider !== "openai")+ return sendJson(ctx.res, 400, { error: "bad_request" });+ if (+ account === "personal" &&+ provider &&+ !(await ctx.deps.userModelCredentials.connections(principal)).some((c) => c.provider === provider)+ ) {+ return sendJson(ctx.res, 409, { error: "Connect this AI account first." });+ }+ await ctx.deps.config.setPersonalModelAuth(principal, account === "personal", provider);+ audit(ctx.deps, {+ principalId: principal,+ action: "user-model-auth.account",+ resource: account,+ scopeLabel: principal,+ });+ return getStatus(ctx);}async function disconnect(ctx: ApiCtx): Promise<void> {@@ -134,6 +168,7 @@ async function claudeComplete(ctx: ApiCtx): Promise<void> {}export const userModelAuthRoutes: ReadonlyArray<Route<ApiCtx>> = [+ { method: "POST", path: "/v1/user-model-auth/account", auth: "source", handle: setAccount },{ method: "GET", path: "/v1/user-model-auth/status", auth: "source", handle: getStatus },{ method: "POST", path: "/v1/user-model-auth/api-key", auth: "source", handle: putApiKey },{ method: "POST", path: "/v1/user-model-auth/disconnect", auth: "source", handle: disconnect },diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.tsindex 8ed33ad8b..6212d2266 100644--- a/src/api/user-scoped-routes.ts+++ b/src/api/user-scoped-routes.ts@@ -85,6 +85,7 @@ const USER_SCOPED: Rule[] = [pat("GET", "/v1/deployments", { in: "query", name: "principalId" }),pat("POST", "/v1/deployments", { in: "body", name: "createdBy" }),pat("GET", "/v1/user-model-auth/status", { in: "query", name: "principalId" }),+ pat("POST", "/v1/user-model-auth/account", { in: "body", name: "principalId" }),pat("POST", "/v1/user-model-auth/api-key", { in: "body", name: "principalId" }),pat("POST", "/v1/user-model-auth/disconnect", { in: "body", name: "principalId" }),pat("POST", "/v1/user-model-auth/chatgpt/start", { in: "body", name: "principalId" }),diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex 5f65d2f2b..7edc59077 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -2946,18 +2946,19 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {let claudeOauthToken: string | undefined;let codexTurnAuth: CodexTurnAuth | undefined;const userCredStore = deps.userModelCredentials;- if (userCredStore && humanTurn && (await deps.config?.getIndividualModelAuthDurable())) {+ const account = input.modelAccount ?? (await deps.config?.getModelAccountDurable(actor.id)) ?? "company";+ if (userCredStore && humanTurn && account !== "company") {const [anthCred, oaiCred] = await Promise.all([- userCredStore.get(actor.id, "anthropic"),- userCredStore.get(actor.id, "openai"),+ account === "openai" ? null : userCredStore.get(actor.id, "anthropic"),+ account === "anthropic" ? null : userCredStore.get(actor.id, "openai"),]);const orgRuntime = await deps.config?.getRuntimeSelectionDurable(resolution.orgScopeId);const preferredHarness = runtime.harnessId ?? input.harness ?? orgRuntime?.harnessId ?? deps.defaultHarness;const routing = resolveIndividualAuthRouting(anthCred ?? null,oaiCred ?? null,- runtime.modelId ?? input.model,- preferredHarness,+ account === "personal" ? (runtime.modelId ?? input.model) : runtime.modelId,+ account === "personal" ? preferredHarness : runtime.harnessId,);if (routing?.kind === "apikey") {userHarnessOverride = "pi";@@ -2997,7 +2998,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {}if (!userHarnessOverride) {throw new NonRetryableTurnError(- "This organization has each person chat on their own AI account, and yours isn't connected yet. Open the web app and connect Claude or ChatGPT from the AI account panel, then try again.",+ "Your personal AI account is unavailable. Open Settings → AI access to reconnect Claude or ChatGPT / Codex, or choose company access. The chat cannot continue on company access.",);}}diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.tsindex b04221428..293d2127b 100644--- a/src/core/orchestrator/types.ts+++ b/src/core/orchestrator/types.ts@@ -14,7 +14,7 @@ import type {import type { TurnOrigin } from "../turn-origin.ts";import type { IdentityService } from "../../identity/identity-service.ts";import type { ResolutionService } from "../../resolution/resolution-service.ts";-import type { OrgBranding, ScopedConfigStore } from "../../resolution/config-store.ts";+import type { ModelAccount, OrgBranding, ScopedConfigStore } from "../../resolution/config-store.ts";import type { UserModelCredentialStore } from "../../model/user-model-credential-store.ts";import type { IsCurrentSharedScopeMember, ManagedGroupDirectory } from "../../resolution/scope-membership.ts";import type { DirectoryStore } from "../../directory/directory-store.ts";@@ -85,6 +85,7 @@ export interface OrchestratorInput extends Omit<| "unprompted"| "liveActor"> {+ modelAccount?: ModelAccount;surface?: string;privateSessionMessage?: true;sessionMessageDepth?: number;diff --git a/src/model/codex-device-login.ts b/src/model/codex-device-login.tsindex 421dccb5c..8cf534483 100644--- a/src/model/codex-device-login.ts+++ b/src/model/codex-device-login.ts@@ -1,6 +1,6 @@import { mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";-import { join, resolve } from "node:path";+import { dirname, join, resolve } from "node:path";import { CodexAppServer } from "../harness/codex-app-server.ts";import { codexOAuthAuthFromValue } from "../harness/codex-auth-store.ts";import { asObject, codexOAuthJwtAccountId, type JsonObject } from "../harness/codex-auth-file.ts";@@ -72,7 +72,12 @@ export function createCodexDeviceLogin(opts: { binaryPath?: string; env?: NodeJSconst server = new CodexAppServer({binaryPath,cwd: home,- env: { ...opts.env, CODEX_HOME: home },+ env: {+ PATH: dirname(process.execPath),+ ...opts.env,+ HOME: home,+ CODEX_HOME: home,+ },onNotification: async (method, params) => {if (method !== "account/login/completed") return;const p = (params ?? {}) as Record<string, unknown>;diff --git a/src/resolution/config-store.ts b/src/resolution/config-store.tsindex d0850b703..446601713 100644--- a/src/resolution/config-store.ts+++ b/src/resolution/config-store.ts@@ -59,6 +59,12 @@ export interface PersistedEgressPolicy {scopeId: ScopeId;policy: EgressPolicy;}+export type ModelAccount = "company" | "personal" | "anthropic" | "openai";++export interface PersistedModelAccount extends PersistedScopedFlag {+ provider?: "anthropic" | "openai";+}+export interface PersistedScopedFlag {scopeId: ScopeId;on: boolean;@@ -224,7 +230,9 @@ export interface ScopedConfigStore {getInteractiveFastModeDurable(): Promise<boolean>;getIndividualModelAuth(): boolean;setIndividualModelAuth(on: boolean): void;- getIndividualModelAuthDurable(): Promise<boolean>;+ getIndividualModelAuthDurable(principalId?: string): Promise<boolean>;+ setPersonalModelAuth(principalId: string, on: boolean, provider?: "anthropic" | "openai"): Promise<void>;+ getModelAccountDurable(principalId: string): Promise<ModelAccount>;getBaseModelOwnDurable(id: ScopeId): Promise<string | null>;getWebuiModels(id: ScopeId): string[] | null;setWebuiModels(id: ScopeId, ids: string[] | null): void;@@ -277,7 +285,7 @@ export function createMemoryConfigStore(internalMemberOverrides?: DurableMap<PersistedInternalMemberOverrides>;orgAmbient?: DurableMap<PersistedScopedFlag>;interactiveFastMode?: DurableMap<PersistedScopedFlag>;- individualModelAuth?: DurableMap<PersistedScopedFlag>;+ individualModelAuth?: DurableMap<PersistedModelAccount>;webuiModels?: DurableMap<PersistedWebuiModels>;peopleDirectoryUrls?: DurableMap<PersistedPeopleDirectoryUrl>;ackEmoji?: DurableMap<PersistedAckEmoji>;@@ -334,7 +342,7 @@ export function createMemoryConfigStore(opts.internalMemberOverrides ?? createMemoryMap<PersistedInternalMemberOverrides>();const orgAmbientStore = opts.orgAmbient ?? createMemoryMap<PersistedScopedFlag>();const interactiveFastModeStore = opts.interactiveFastMode ?? createMemoryMap<PersistedScopedFlag>();- const individualModelAuthStore = opts.individualModelAuth ?? createMemoryMap<PersistedScopedFlag>();+ const individualModelAuthStore = opts.individualModelAuth ?? createMemoryMap<PersistedModelAccount>();const webuiModelStore = opts.webuiModels ?? createMemoryMap<PersistedWebuiModels>();const peopleDirectoryUrlStore = opts.peopleDirectoryUrls ?? createMemoryMap<PersistedPeopleDirectoryUrl>();const ackEmojiStore = opts.ackEmoji ?? createMemoryMap<PersistedAckEmoji>();@@ -927,7 +935,21 @@ export function createMemoryConfigStore(individualModelAuthStore.put(org, { scopeId: org, on }),);},- getIndividualModelAuthDurable: async () => (await individualModelAuthStore.get(org))?.on ?? false,+ async getIndividualModelAuthDurable(principalId) {+ if ((await individualModelAuthStore.get(org))?.on) return true;+ return principalId+ ? ((await individualModelAuthStore.get(scopeId("personal", principalId)))?.on ?? false)+ : false;+ },+ async getModelAccountDurable(principalId) {+ const row = await individualModelAuthStore.get(scopeId("personal", principalId));+ if (row?.on) return row.provider ?? "personal";+ return (await individualModelAuthStore.get(org))?.on ? "personal" : "company";+ },+ async setPersonalModelAuth(principalId, on, provider) {+ const id = scopeId("personal", principalId);+ await individualModelAuthStore.put(id, { scopeId: id, on, ...(on && provider ? { provider } : {}) });+ },getBaseModelOwnDurable: async (id) => (await baseModelStore.get(id))?.modelId ?? null,getBaseModelDurable: async (id) =>(await baseModelStore.get(id))?.modelId ??diff --git a/test/codex-device-login.test.ts b/test/codex-device-login.test.tsindex 28e75d05c..5e8283175 100644--- a/test/codex-device-login.test.ts+++ b/test/codex-device-login.test.ts@@ -15,7 +15,7 @@ function loginBinary(dir: string, opts: { succeed: boolean; delayMs?: number }):const path = join(dir, `codex-login-${opts.succeed ? "ok" : "fail"}`);writeFileSync(path,- `#!${process.execPath}+ `#!/usr/bin/env nodeconst fs = require("node:fs");const path = require("node:path");const readline = require("node:readline");diff --git a/test/conversation-status-intake.test.ts b/test/conversation-status-intake.test.tsindex a12cce3ad..28f9fab55 100644--- a/test/conversation-status-intake.test.ts+++ b/test/conversation-status-intake.test.ts@@ -125,6 +125,56 @@ test("independent tasks remain addressable after the root ends, including termin}});+test("a DM routed to a task on another account queues with the sender's account and preserves the task destination", async () => {+ const built = buildApp(testConfig());+ try {+ const turn: TurnRequest = {+ surface: "slack",+ actor: { externalId: "U1" },+ conversation: { kind: "dm", threadRef: "dm:D-account" },+ text: "Website",+ async: true,+ liveActor: true,+ redeliveryKey: "account-root",+ };+ const first = await built.app.turn(turn);+ const root = (await built.runs.get(first.runId!))!;+ const childRef = "dm:D-account:task:email";+ const child = (+ await built.runs.enqueue({+ sessionId: childRef,+ request: {+ ...root.request,+ modelAccount: "openai",+ deliveryTarget: "D-account:10.1",+ conversation: { ...root.request.conversation, threadRef: childRef },+ },+ })+ ).run;+ selectTask = child.id;+ const result = await built.app.turn({+ ...turn,+ text: "Shorten the email",+ deliveryTarget: "D-account:20.1",+ redeliveryKey: "account-update",+ });+ assert.equal(result.status, "queued");+ assert.equal(result.conversationAside, true);+ assert.notEqual(result.runId, child.id);+ assert.notEqual(result.steered, true);+ const queued = (await built.runs.get(result.runId!))!;+ assert.equal(queued.sessionId, childRef);+ assert.equal(queued.request.conversation.threadRef, childRef);+ assert.equal(queued.request.modelAccount, "company");+ assert.equal(queued.request.deliveryTarget, "D-account:10.1");+ assert.deepEqual(await built.signals.takePending(child.id), []);+ assert.deepEqual(await built.signals.takePending(root.id), []);+ } finally {+ selectTask = undefined;+ await built.runtime.stop();+ }+});+for (const excluded of [{ name: "channel", conversation: { kind: "channel", channelRef: "C1" } },{ name: "group DM", conversation: { kind: "group", channelRef: "G1", isMpim: true } },diff --git a/test/personal-model-account-execution.test.ts b/test/personal-model-account-execution.test.tsnew file mode 100644index 000000000..5ed91ac32--- /dev/null+++ b/test/personal-model-account-execution.test.ts@@ -0,0 +1,84 @@+import "./support/auto-fake-sprites.ts";+import assert from "node:assert/strict";+import { mock, test } from "node:test";+import * as piHarness from "../src/harness/pi-harness.ts";+import * as mockHarness from "../src/harness/mock-harness.ts";+import type { HarnessTurnInput } from "../src/harness/harness.ts";+import { resolveModel } from "../src/model/pi-models.ts";+import { testConfig } from "./support/test-config.ts";++const turns: HarnessTurnInput[] = [];+function observedHarness() {+ const harness = mockHarness.createMockHarness();+ const runTurn = harness.turns.runTurn;+ harness.turns.runTurn = async (turn) => {+ turns.push(turn);+ return runTurn(turn);+ };+ return harness;+}++mock.module("../src/harness/pi-harness.ts", {+ namedExports: { ...piHarness, createPiHarness: observedHarness },+});+mock.module("../src/harness/mock-harness.ts", {+ namedExports: { ...mockHarness, createMockHarness: observedHarness },+});+const { buildApp } = await import("../src/wiring.ts");++for (const provider of ["anthropic", "openai"] as const) {+ test(`queued personal ${provider} turns use only that provider's credentials after switching to company`, async () => {+ turns.length = 0;+ const built = buildApp(testConfig({ anthropicApiKey: "company-anthropic", openaiApiKey: "company-openai" }));+ await built.userModelCredentials.setApiKey("U1", "anthropic", "personal-anthropic");+ await built.userModelCredentials.setApiKey("U1", "openai", "personal-openai");+ await built.config.setPersonalModelAuth("U1", true, provider);+ const submitted = await built.app.turn({+ surface: "slack",+ actor: { externalId: "U1" },+ conversation: { kind: "dm", threadRef: `execute-personal-${provider}` },+ text: "hello",+ liveActor: true,+ async: true,+ });+ await built.config.setPersonalModelAuth("U1", false);+ built.runtime.start();+ try {+ const finished = await built.runs.waitFor(submitted.runId!, 5_000);+ assert.equal(finished.status, "done", JSON.stringify(finished.result));+ assert.equal(turns.length, 1);+ assert.deepEqual(turns[0]!.providerKeys, { [provider]: `personal-${provider}` });+ assert.equal(resolveModel(turns[0]!.runtime!.modelId!)?.provider, provider);+ assert.equal(turns[0]!.runtime!.harnessId, "pi");+ } finally {+ await built.runtime.stop();+ }+ });+}++test("disconnecting a queued personal account fails without invoking any main harness or another connected provider", async () => {+ turns.length = 0;+ const built = buildApp(testConfig({ anthropicApiKey: "company-anthropic", openaiApiKey: "company-openai" }));+ await built.userModelCredentials.setApiKey("U1", "anthropic", "personal-anthropic");+ await built.userModelCredentials.setApiKey("U1", "openai", "personal-openai");+ await built.config.setPersonalModelAuth("U1", true, "openai");+ const submitted = await built.app.turn({+ surface: "slack",+ actor: { externalId: "U1" },+ conversation: { kind: "dm", threadRef: "execute-disconnected-personal" },+ text: "hello",+ liveActor: true,+ async: true,+ });+ await built.userModelCredentials.delete("U1", "openai");+ await built.config.setPersonalModelAuth("U1", false);+ built.runtime.start();+ try {+ const finished = await built.runs.waitFor(submitted.runId!, 5_000);+ assert.equal(finished.status, "failed");+ assert.match(JSON.stringify(finished), /personal AI account is unavailable/);+ assert.equal(turns.length, 0);+ } finally {+ await built.runtime.stop();+ }+});diff --git a/test/personal-model-account.test.ts b/test/personal-model-account.test.tsnew file mode 100644index 000000000..6b2db402f--- /dev/null+++ b/test/personal-model-account.test.ts@@ -0,0 +1,136 @@+import "./support/auto-fake-sprites.ts";+import assert from "node:assert/strict";+import { test } from "node:test";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import type { AddressInfo } from "node:net";+import { createMemoryMap } from "../src/persistence/durable-map.ts";+import { createMemoryConfigStore, type PersistedScopedFlag } from "../src/resolution/config-store.ts";+import { createServer } from "../src/api/server.ts";+import { mintPortalIdentity } from "../src/auth/portal-identity.ts";+import { signRequest } from "../src/auth/source-auth.ts";+import { buildApp } from "../src/wiring.ts";+import { testConfig } from "./support/test-config.ts";++const SECRET = "personal-account-test-signing-secret";++test("personal account choice persists across instances without changing anyone else's choice", async () => {+ const individualModelAuth = createMemoryMap<PersistedScopedFlag>();+ const first = createMemoryConfigStore("default-org", { individualModelAuth });+ const second = createMemoryConfigStore("default-org", { individualModelAuth });+ assert.equal(await first.getIndividualModelAuthDurable("alice"), false);+ await first.setPersonalModelAuth("alice", true);+ assert.equal(await second.getIndividualModelAuthDurable("alice"), true);+ assert.equal(await second.getIndividualModelAuthDurable("bob"), false);+ assert.equal(await second.getIndividualModelAuthDurable(), false);+ await second.setPersonalModelAuth("alice", false);+ assert.equal(await first.getIndividualModelAuthDurable("alice"), false);+ first.setIndividualModelAuth(true);+ await first.flushScope("org:default-org");+ assert.equal(await second.getIndividualModelAuthDurable("alice"), true);+});++test("account API binds choice to the signed-in person, preserves connections, and fails closed after disconnect", async () => {+ const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "personal-account-")) }));+ built.config.setInternalMemberOverrides(["alice@default-org", "bob@default-org"]);+ await built.config.flushScope("org:default-org");+ const server = createServer(built.app, {+ signingSecret: SECRET,+ requireSignedPortalIdentity: true,+ capabilitySecret: SECRET + "capability",+ portalIdentitySecret: SECRET + "portal",+ config: built.config,+ userModelCredentials: built.userModelCredentials,+ auditLog: built.auditLog,+ });+ server.listen(0);+ const base = `http://localhost:${(server.address() as AddressInfo).port}`;+ async function request(account: unknown, principalId = "alice@default-org", signedIn = "alice@default-org") {+ const path = "/v1/user-model-auth/account";+ const body = JSON.stringify({ account, principalId, nonce: crypto.randomUUID() });+ const ts = Math.floor(Date.now() / 1000);+ return fetch(base + path, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "x-timestamp": String(ts),+ "x-signature": signRequest(SECRET, ts, `POST\n${path}\n${body}`),+ "x-portal-identity": await mintPortalIdentity({ p: signedIn, exp: Date.now() + 60_000 }, SECRET + "portal"),+ },+ body,+ });+ }+ try {+ assert.equal((await request("personal")).status, 409);+ assert.equal((await request("invalid")).status, 400);+ await built.userModelCredentials.setApiKey("alice@default-org", "anthropic", "test-personal-key");+ assert.equal((await request("personal", "bob@default-org", "alice@default-org")).status, 403);+ const enabled = await request("personal");+ assert.equal(enabled.status, 200);+ assert.deepEqual(await enabled.json(), {+ individualModelAuth: true,+ required: false,+ account: "personal",+ connections: [{ provider: "anthropic", kind: "apikey" }],+ });+ assert.equal(await built.config.getIndividualModelAuthDurable("bob@default-org"), false);+ assert.equal((await request("company")).status, 200);+ assert.equal((await built.userModelCredentials.connections("alice@default-org")).length, 1);+ assert.equal((await request("personal")).status, 200);+ await built.userModelCredentials.delete("alice@default-org", "anthropic");+ assert.equal(await built.config.getIndividualModelAuthDurable("alice@default-org"), true);+ assert.equal((await request("company")).status, 200);+ built.config.setIndividualModelAuth(true);+ await built.config.flushScope("org:default-org");+ assert.equal((await request("company")).status, 403);+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+});++test("personal provider choice is durable and controls the submitted run independently of the company model", async () => {+ const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "personal-routing-")) }));+ await built.userModelCredentials.setApiKey("U1", "anthropic", "test-anthropic-key");+ await built.userModelCredentials.setApiKey("U1", "openai", "test-openai-key");+ await built.config.setPersonalModelAuth("U1", true, "openai");+ const submitted = await built.app.turn({+ surface: "slack",+ actor: { externalId: "U1" },+ conversation: { kind: "dm", threadRef: "personal-provider-choice" },+ text: "hello",+ liveActor: true,+ async: true,+ model: "company-only-custom-model",+ harness: "pi",+ });+ const run = await built.runs.get(submitted.runId!);+ assert.equal(run?.request.modelAccount, "openai");+ assert.equal(run?.request.model, undefined);+ assert.equal(run?.request.harness, undefined);+ await built.config.setPersonalModelAuth("U1", false);+ assert.equal((await built.runs.get(submitted.runId!))?.request.modelAccount, "openai");+ const steered = await built.app.signalRun(submitted.runId!, { kind: "steer", text: "more work" }, "U1");+ assert.equal(steered.accepted, false);+ assert.match(steered.reason ?? "", /account_changed/);+ assert.equal((await built.app.signalRun(submitted.runId!, { kind: "abort" }, "U1")).accepted, true);+});++test("shared chat messages queue instead of borrowing another person's account", async () => {+ const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "personal-steering-")) }));+ const message = (user: string) => ({+ surface: "slack",+ actor: { externalId: user },+ conversation: { kind: "channel" as const, threadRef: "account-steering", channelRef: "C1" },+ text: "hello",+ liveActor: true,+ async: true,+ });+ await built.config.setPersonalModelAuth("U1", true, "anthropic");+ const first = await built.app.turn(message("U1"));+ const other = await built.app.turn(message("U2"));+ assert.notEqual(first.runId, other.runId);+ assert.notEqual(other.steered, true);+ assert.equal((await built.runs.get(other.runId!))?.request.modelAccount, "company");+ assert.equal((await built.signals.takePending(first.runId!)).length, 0);+});diff --git a/test/run-signal-route.test.ts b/test/run-signal-route.test.tsindex 4651b13cc..bb91f36bf 100644--- a/test/run-signal-route.test.ts+++ b/test/run-signal-route.test.ts@@ -40,7 +40,13 @@ after(async () => {const actor: Principal = { id: "internal:U1", type: "internal" };function request(text: string, threadRef = "t-signal"): OrchestratorInput {- return { actor, conversation: { kind: "dm", threadRef, audience: [actor] }, origin: { kind: "direct" }, text };+ return {+ modelAccount: "company",+ actor,+ conversation: { kind: "dm", threadRef, audience: [actor] },+ origin: { kind: "direct" },+ text,+ };}async function coreSignal(runId: string, body: unknown): Promise<{ status: number; json: Record<string, unknown> }> {@@ -158,6 +164,7 @@ test("signalRun attributes a bare steer from a shared-scope viewer who is not thconst { run } = await built.runs.enqueue({sessionId: threadRef,request: {+ modelAccount: "company",actor: owner,conversation: { kind: "channel", channelRef: "C-STEER", threadRef, audience: [owner] },origin: { kind: "direct" },@@ -544,6 +551,7 @@ test("run control follows current shared membership while public history requireconst { run } = await built.runs.enqueue({sessionId: threadRef,request: {+ modelAccount: "company",actor: owner,conversation: { kind: shared.kind, channelRef: shared.ref, threadRef, audience: [owner] },origin: { kind: "direct" },diff --git a/test/wake-steering.test.ts b/test/wake-steering.test.tsindex f336aade5..0ec1726c6 100644--- a/test/wake-steering.test.ts+++ b/test/wake-steering.test.ts@@ -526,6 +526,27 @@ test("reverse race: an addressed mention steers into the live ambient run, not aassert.equal(signals[0]!.text, "@bot are you on it?");});+for (const personalSide of ["ambient", "mention"] as const) {+ test(`reverse race: ${personalSide} personal access cannot share the other run's company account`, async () => {+ const built = freshApp();+ const channel = `C-account-${personalSide}`;+ const askTs = "1600.2";+ const ambientRef = `slack:${channel}:ambient:${askTs}`;+ await built.config.setPersonalModelAuth(personalSide === "ambient" ? "[email protected]" : "U1", true, "openai");+ await built.sessions.getOrCreateByThread(ambientRef, "channel", `channel:${channel}`);+ const ambient = await built.app.turn(spawnedWorker(channel, askTs));+ const second = await built.app.turn({ ...mention("@bot continue", channel, askTs), triggerTs: askTs });+ assert.equal(second.status, "queued");+ assert.notEqual(second.runId, ambient.runId);+ assert.notEqual(second.steered, true);+ assert.deepEqual(await built.signals.takePending(ambient.runId!), []);+ assert.equal(+ (await built.runs.get(second.runId!))?.request.modelAccount,+ personalSide === "mention" ? "openai" : "company",+ );+ });+}+test("spine ON: the FIRST message (no live run) engages normally — no steer", async () => {const built = freshApp();const channel = "C4";