Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat: backup provider accounts, better default models, and a bot-owned model picker (#352)

Leo55028ceeba4e
diff --git a/.changeset/bots-pick-better-models.md b/.changeset/bots-pick-better-models.md
new file mode 100644
index 000000000..bc2110e41
--- /dev/null
+++ b/.changeset/bots-pick-better-models.md
@@ -0,0 +1,5 @@
+---
+"akeru-bot": minor
+---
+
+Add backup accounts to a provider, named by plan, and bots move to the next one when an account hits a usage limit. New bots start on Claude Opus 5.5 for Claude, Grok 4.7 for Grok, and GPT-6 Luna for OpenCode Go. The model picker moved from the chat composer into the bot's settings, chats show a sign-in card when a bot's provider needs connecting, and the macOS desktop sidebar no longer crowds the window controls.
diff --git a/apps/mobile/src/features/settings/ProviderConnections.tsx b/apps/mobile/src/features/settings/ProviderConnections.tsx
index 9cc74ef3a..73f1dce27 100644
--- a/apps/mobile/src/features/settings/ProviderConnections.tsx
+++ b/apps/mobile/src/features/settings/ProviderConnections.tsx
@@ -4,11 +4,13 @@ import { useMobileI18n } from "../../lib/i18n";
import { useCallback, useEffect, useState } from "react";
import { Linking, Pressable, TextInput, View } from "react-native";
import type {
- EnvironmentId,
ProviderInstanceId,
+ EnvironmentId,
+ SubscriptionAccountId,
SubscriptionAuthLoginProgress,
SubscriptionAuthStartResult,
SubscriptionProviderId,
+ SubscriptionProviderStatus,
} from "@akeru/contracts";
import {
anyProviderHealthChecking,
@@ -36,6 +38,35 @@ import { copySignInCode } from "./copySignInCode";
const RETRY_POLL_MS = 5000;
+/**
+ * Which account a sign-in, check, or removal applies to: one failover account,
+ * a new one, or a separately named instance. Empty means the account in use.
+ */
+type AccountTarget = {
+ readonly accountId?: SubscriptionAccountId;
+ readonly addAccount?: true;
+ readonly instanceId?: ProviderInstanceId;
+};
+
+/** One account row: a failover account, or a separately named instance when `instanceId` is set. */
+type AccountRow = {
+ readonly status: SubscriptionProviderStatus | undefined;
+ readonly account: AccountTarget;
+ readonly instanceId?: ProviderInstanceId;
+};
+
+function accountName(
+ status: SubscriptionProviderStatus | undefined,
+ providerLabel: string,
+ t: ReturnType<typeof useMobileI18n>["t"],
+): string {
+ if (providerUsesApiKey(status)) return t("API key");
+
+ return status?.plan
+ ? `${providerLabel} ${status.plan}`
+ : t("{provider} account", { provider: providerLabel });
+}
+
function commandError(
result: AtomCommandResult<unknown, unknown>,
t: (message: string) => string,
@@ -86,9 +117,14 @@ export function ProviderConnections({ environmentId }: { readonly environmentId:
const cancel = useAtomCommand(serverEnvironment.cancelSubscriptionAuth, { reportFailure: false });
const logout = useAtomCommand(serverEnvironment.logoutSubscriptionAuth, { reportFailure: false });
const test = useAtomCommand(serverEnvironment.testSubscriptionAuth, { reportFailure: false });
+
+ const order = useAtomCommand(serverEnvironment.setSubscriptionAccountOrder, {
+ reportFailure: false,
+ });
+
const [flow, setFlow] = useState<SubscriptionAuthStartResult | null>(null);
const [keyProvider, setKeyProvider] = useState<SubscriptionProviderId | null>(null);
- const [activeInstanceId, setActiveInstanceId] = useState<ProviderInstanceId | undefined>();
+ const [target, setTarget] = useState<AccountTarget>({});
const [code, setCode] = useState("");
const [baseUrl, setBaseUrl] = useState("");
const [busy, setBusy] = useState(false);
@@ -100,7 +136,7 @@ export function ProviderConnections({ environmentId }: { readonly environmentId:
if (progress.status === "connected") {
setFlow(null);
setCode("");
- setActiveInstanceId(undefined);
+ setTarget({});
query.refresh();
return true;
@@ -172,40 +208,40 @@ export function ProviderConnections({ environmentId }: { readonly environmentId:
}
};
- const openKey = (provider: SubscriptionProviderId, instanceId?: ProviderInstanceId) => {
+ const openKey = (provider: SubscriptionProviderId, account: AccountTarget = {}) => {
setError(null);
setCode("");
- setActiveInstanceId(instanceId);
+ setTarget(account);
setBaseUrl(
- providerSupportsBaseUrl(provider)
- ? ((instanceId
- ? query.data?.accounts.find(
- (status) => status.provider === provider && status.instanceId === instanceId,
+ providerSupportsBaseUrl(provider) && !account.addAccount
+ ? ((account.accountId
+ ? query.data?.linkedAccounts.find(
+ (status) => status.provider === provider && status.accountId === account.accountId,
)
- : query.data?.providers.find((status) => status.provider === provider)
+ : account.instanceId
+ ? query.data?.accounts.find(
+ (status) =>
+ status.provider === provider && status.instanceId === account.instanceId,
+ )
+ : query.data?.providers.find((status) => status.provider === provider)
)?.baseUrl ?? "")
: "",
);
setKeyProvider(provider);
};
- const connect = async (provider: SubscriptionProviderId, instanceId?: ProviderInstanceId) => {
+ const connect = async (provider: SubscriptionProviderId, account: AccountTarget = {}) => {
if (provider === "opencode-go") {
- openKey(provider, instanceId);
+ openKey(provider, account);
return;
}
setError(null);
setCode("");
- setActiveInstanceId(instanceId);
+ setTarget(account);
setBusy(true);
-
- const result = await start({
- environmentId,
- input: { provider, ...(instanceId ? { instanceId } : {}) },
- });
-
+ const result = await start({ environmentId, input: { provider, ...account } });
setBusy(false);
if (Predicate.isTagged(result, "Failure")) {
@@ -233,7 +269,7 @@ export function ProviderConnections({ environmentId }: { readonly environmentId:
environmentId,
input: {
...apiKeyStartInput(keyProvider, baseUrl),
- ...(activeInstanceId ? { instanceId: activeInstanceId } : {}),
+ ...target,
},
});
@@ -256,7 +292,7 @@ export function ProviderConnections({ environmentId }: { readonly environmentId:
setKeyProvider(null);
setCode("");
setBaseUrl("");
- setActiveInstanceId(undefined);
+ setTarget({});
query.refresh();
} else {
if (Predicate.isTagged(result, "Failure")) setError(commandError(result, t));
@@ -287,7 +323,7 @@ export function ProviderConnections({ environmentId }: { readonly environmentId:
setKeyProvider(null);
setCode("");
setBaseUrl("");
- setActiveInstanceId(undefined);
+ setTarget({});
setError(null);
if (login) {
@@ -300,14 +336,14 @@ export function ProviderConnections({ environmentId }: { readonly environmentId:
const runAction = async (
provider: SubscriptionProviderId,
action: "disconnect" | "test",
- instanceId?: ProviderInstanceId,
+ account: AccountTarget,
) => {
setError(null);
setBusy(true);
const result = await (action === "disconnect" ? logout : test)({
environmentId,
- input: { provider, ...(instanceId ? { instanceId } : {}) },
+ input: { provider, ...account },
});
setBusy(false);
@@ -316,6 +352,26 @@ export function ProviderConnections({ environmentId }: { readonly environmentId:
else if (Predicate.isTagged(result, "Failure")) setError(commandError(result, t));
};
+ const move = async (
+ provider: SubscriptionProviderId,
+ accountIds: ReadonlyArray<SubscriptionAccountId>,
+ index: number,
+ offset: -1 | 1,
+ ) => {
+ const next = [...accountIds];
+ const [moved] = next.splice(index, 1);
+
+ if (!moved) return;
+ next.splice(index + offset, 0, moved);
+ setError(null);
+ setBusy(true);
+ const result = await order({ environmentId, input: { provider, accountIds: next } });
+ setBusy(false);
+
+ if (Predicate.isTagged(result, "Success")) query.refresh();
+ else if (Predicate.isTagged(result, "Failure")) setError(commandError(result, t));
+ };
+
const activeProvider = keyProvider ?? flow?.provider;
const label = PROVIDER_CONNECTIONS.find((provider) => provider.id === activeProvider)?.label;
@@ -441,74 +497,161 @@ export function ProviderConnections({ environmentId }: { readonly environmentId:
{query.isPending ? (
<Text className="text-sm text-foreground-muted">{t("Loading connections…")}</Text>
) : null}
- {PROVIDER_CONNECTIONS.flatMap((provider) => [
- {
- provider,
- status: query.data?.providers.find((entry) => entry.provider === provider.id),
- instanceId: undefined,
- },
- ...(query.data?.accounts
- .filter((entry) => entry.provider === provider.id)
- .map((status) => ({ provider, status, instanceId: status.instanceId })) ?? []),
- ]).map(({ provider, status, instanceId }) => {
- const apiKey = providerUsesApiKey(status);
+ {PROVIDER_CONNECTIONS.map((provider) => {
+ const linked =
+ query.data?.linkedAccounts.filter((entry) => entry.provider === provider.id) ?? [];
+
+ const accountIds = linked.flatMap((entry) =>
+ entry.accountId ? [entry.accountId] : [],
+ );
+
+ // Failover accounts first, then any separately named accounts of this provider.
+ const rows = [
+ ...(linked.length > 0
+ ? linked
+ : [query.data?.providers.find((entry) => entry.provider === provider.id)]
+ ).map(
+ (status): AccountRow => ({
+ status,
+ account: status?.accountId ? { accountId: status.accountId } : {},
+ }),
+ ),
+ ...(query.data?.accounts
+ .filter((entry) => entry.provider === provider.id)
+ .map(
+ (status): AccountRow => ({
+ status,
+ account: status.instanceId ? { instanceId: status.instanceId } : {},
+ ...(status.instanceId ? { instanceId: status.instanceId } : {}),
+ }),
+ ) ?? []),
+ ];
return (
- <View
- key={`${provider.id}:${instanceId ?? "default"}`}
- className="gap-2 border-b border-border-subtle py-3"
- >
- <Text className="text-base font-t3-medium text-foreground">
- {provider.label}
- {instanceId ? ` · ${instanceId}` : ""}
- </Text>
- <Text className="text-sm text-foreground-muted">
- {status ? t(providerConnectionLabel(status)) : t("Status unavailable")}
- </Text>
- {status?.baseUrl ? (
- <Text selectable className="text-sm text-foreground-muted">
- {status.baseUrl}
- </Text>
+ <View key={provider.id} className="gap-3 border-b border-border-subtle py-3">
+ <Text className="text-base font-t3-medium text-foreground">{provider.label}</Text>
+ {rows.map(({ status, account, instanceId }, index) => {
+ const apiKey = providerUsesApiKey(status);
+ const failover = instanceId === undefined && linked.length > 0;
+ const name = accountName(status, provider.label, t);
+
+ const resting =
+ status?.nextRetryAt !== undefined &&
+ Date.parse(status.nextRetryAt) > Date.now();
+
+ const resetTime = status?.nextRetryAt
+ ? new Date(status.nextRetryAt).toLocaleTimeString([], {
+ hour: "numeric",
+ minute: "2-digit",
+ })
+ : "";
+
+ return (
+ <View key={instanceId ?? account.accountId ?? "default"} className="gap-2">
+ {instanceId ? (
+ <Text className="text-sm font-t3-medium text-foreground">
+ {`${name} · ${instanceId}`}
+ </Text>
+ ) : failover ? (
+ <Text className="text-sm font-t3-medium text-foreground">
+ {`${index + 1}. ${name}`}
+ </Text>
+ ) : null}
+ {failover && linked.length > 1 ? (
+ <Text className="text-sm text-foreground-muted">
+ {index === 0
+ ? t("Main account")
+ : t("Backup {number}", { number: String(index) })}
+ {status?.active ? ` · ${t("In use")}` : ""}
+ </Text>
+ ) : null}
+ <Text className="text-sm text-foreground-muted">
+ {status ? t(providerConnectionLabel(status)) : t("Status unavailable")}
+ </Text>
+ {resting ? (
+ <Text className="text-sm text-foreground-muted">
+ {t("Usage limit reached, back at {time}", { time: resetTime })}
+ </Text>
+ ) : null}
+ {status?.baseUrl ? (
+ <Text selectable className="text-sm text-foreground-muted">
+ {status.baseUrl}
+ </Text>
+ ) : null}
+ <View className="flex-row flex-wrap gap-2">
+ <Action
+ label={
+ status?.connected
+ ? apiKey && provider.id !== "opencode-go"
+ ? t("Use OAuth")
+ : t("Reconnect")
+ : t("Connect")
+ }
+ disabled={busy || query.isPending}
+ onPress={() => void connect(provider.id, account)}
+ />
+ {provider.id !== "opencode-go" ? (
+ <Action
+ label={apiKey ? t("Reconnect key") : t("API key")}
+ disabled={busy || query.isPending}
+ onPress={() => openKey(provider.id, account)}
+ />
+ ) : null}
+ {status?.connected ? (
+ <>
+ <Action
+ label={apiKey ? t("Check key") : t("Check OAuth")}
+ disabled={busy}
+ onPress={() => void runAction(provider.id, "test", account)}
+ />
+ <Action
+ label={t("Disconnect")}
+ disabled={busy}
+ onPress={() => void runAction(provider.id, "disconnect", account)}
+ />
+ </>
+ ) : null}
+ {failover && linked.length > 1 && index > 0 ? (
+ <Action
+ label={t("Move up")}
+ disabled={busy}
+ onPress={() => void move(provider.id, accountIds, index, -1)}
+ />
+ ) : null}
+ {failover && linked.length > 1 && index < linked.length - 1 ? (
+ <Action
+ label={t("Move down")}
+ disabled={busy}
+ onPress={() => void move(provider.id, accountIds, index, 1)}
+ />
+ ) : null}
+ </View>
+ </View>
+ );
+ })}
+ {linked.length > 0 ? (
+ <View className="gap-2">
+ <View className="flex-row flex-wrap gap-2">
+ {provider.id !== "opencode-go" ? (
+ <Action
+ label={t("Add account")}
+ disabled={busy || query.isPending}
+ onPress={() => void connect(provider.id, { addAccount: true })}
+ />
+ ) : null}
+ <Action
+ label={t("Add key")}
+ disabled={busy || query.isPending}
+ onPress={() => openKey(provider.id, { addAccount: true })}
+ />
+ </View>
+ </View>
) : null}
<ProviderAccessSummary
provider={provider.id}
- status={status}
+ status={rows.find((row) => row.status?.active)?.status ?? rows[0]?.status}
models={providerAccessModelNames(serverProviders, provider.id)}
/>
- <View className="flex-row flex-wrap gap-2">
- <Action
- label={
- status?.connected
- ? apiKey && provider.id !== "opencode-go"
- ? t("Use OAuth")
- : t("Reconnect")
- : t("Connect")
- }
- disabled={busy || query.isPending}
- onPress={() => void connect(provider.id, instanceId)}
- />
- {provider.id !== "opencode-go" ? (
- <Action
- label={apiKey ? t("Reconnect key") : t("API key")}
- disabled={busy || query.isPending}
- onPress={() => openKey(provider.id, instanceId)}
- />
- ) : null}
- {status?.connected ? (
- <>
- <Action
- label={apiKey ? t("Check key") : t("Check OAuth")}
- disabled={busy}
- onPress={() => void runAction(provider.id, "test", instanceId)}
- />
- <Action
- label={t("Disconnect")}
- disabled={busy}
- onPress={() => void runAction(provider.id, "disconnect", instanceId)}
- />
- </>
- ) : null}
- </View>
</View>
);
})}
diff --git a/apps/mobile/src/lib/modelOptions.ts b/apps/mobile/src/lib/modelOptions.ts
index d39f55ab7..2fcaca680 100644
--- a/apps/mobile/src/lib/modelOptions.ts
+++ b/apps/mobile/src/lib/modelOptions.ts
@@ -5,6 +5,7 @@ import type {
SubscriptionProviderStatus,
} from "@akeru/contracts";
import { PROVIDER_DISPLAY_NAMES, ProviderDriverKind } from "@akeru/contracts";
+import { formatModelSlug } from "@akeru/shared/model";
import {
filterProvidersBySubscriptionConnection,
withRefreshableSubscriptionLogin,
@@ -90,7 +91,7 @@ export function resolveModelSendBlock(
const modelName =
provider?.models.find((candidate) => candidate.slug === selection.model)?.name ??
- selection.model;
+ formatModelSlug(selection.model);
return presentProviderUnavailability(
{
diff --git a/apps/server/integration/test-support/OrchestrationScenario.ts b/apps/server/integration/test-support/OrchestrationScenario.ts
index df0f25613..9688a2844 100644
--- a/apps/server/integration/test-support/OrchestrationScenario.ts
+++ b/apps/server/integration/test-support/OrchestrationScenario.ts
@@ -70,7 +70,7 @@ export function mastraWireModelFor(provider: IntegrationProvider): string {
// its concrete model before reaching Mastra.
if (provider === CLAUDE_AGENT_PROVIDER) return "anthropic/claude-opus-4-6[1m]";
- if (provider === GROK_PROVIDER) return "xai/grok-4.6";
+ if (provider === GROK_PROVIDER) return "xai/grok-4.7";
return `opencode-go/${modelFor(provider, "b")}`;
}
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index 9c3e19373..318bc4514 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -49,6 +49,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.subscriptionAuthCancel]: AuthOrchestrationOperateScope,
[WS_METHODS.subscriptionAuthLogout]: AuthOrchestrationOperateScope,
[WS_METHODS.subscriptionAuthHealthTest]: AuthOrchestrationOperateScope,
+ [WS_METHODS.subscriptionAuthSetAccountOrder]: AuthOrchestrationOperateScope,
[WS_METHODS.imageProviderList]: AuthOrchestrationReadScope,
[WS_METHODS.imageProviderHealthTest]: AuthOrchestrationOperateScope,
[WS_METHODS.mcpServerAuthenticate]: AuthOrchestrationOperateScope,
diff --git a/apps/server/src/provider/AkeruMastraHarness.accounts.test.ts b/apps/server/src/provider/AkeruMastraHarness.accounts.test.ts
new file mode 100644
index 000000000..42f3ef46d
--- /dev/null
+++ b/apps/server/src/provider/AkeruMastraHarness.accounts.test.ts
@@ -0,0 +1,236 @@
+import type { createOpenAICompatible } from "@ai-sdk/openai-compatible";
+import { AuthStorage } from "@mastra/code-sdk/auth/storage";
+import * as NodeFS from "node:fs";
+import { expect, it, vi } from "vite-plus/test";
+
+import { resolveAkeruMastraModel } from "./AkeruMastraHarness.ts";
+import { makeTestSubscriptionAuthService } from "../subscription-auth/testUtils/subscriptionAuthService.ts";
+import { fixture } from "../subscription-auth/testUtils/subscriptionAuthStorage.ts";
+
+it("pins OpenCode Go's key, endpoint, and outcome when another thread benches its account", async () => {
+ const { authPath, directory } = fixture();
+ NodeFS.writeFileSync(
+ authPath,
+ JSON.stringify({
+ "opencode-go": { type: "api-key", access: "first-key", baseUrl: "https://first.example/v1" },
+ "account:opencode-go:backup": {
+ type: "api-key",
+ access: "second-key",
+ baseUrl: "https://second.example/v1",
+ },
+ }),
+ );
+ const service = await makeTestSubscriptionAuthService(authPath);
+
+ const request = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) =>
+ Response.json({
+ id: "reply",
+ model: "deepseek-v4-pro",
+ choices: [
+ { index: 0, message: { role: "assistant", content: "Done" }, finish_reason: "stop" },
+ ],
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
+ }),
+ );
+
+ vi.stubGlobal("fetch", request);
+
+ try {
+ const model = resolveAkeruMastraModel(
+ "opencode-go/deepseek-v4-pro",
+ new AuthStorage(authPath),
+ undefined,
+ async (instanceId, threadId) => {
+ const credential = service.getApiKeyCredential("opencode-go", instanceId, threadId);
+ service.recordRequestFailure(
+ "opencode-go",
+ "Spending limit reached.",
+ undefined,
+ "request",
+ "thread-other",
+ );
+ expect(service.getApiKeyCredential("opencode-go", undefined, "thread-backup")?.access).toBe(
+ "second-key",
+ );
+
+ return credential;
+ },
+ undefined,
+ (provider, instanceId, threadId) =>
+ service.getApiKeyCredential(provider, instanceId, threadId),
+ undefined,
+ undefined,
+ undefined,
+ "thread-request",
+ ) as ReturnType<ReturnType<typeof createOpenAICompatible>>;
+
+ await model.doGenerate({
+ prompt: [{ role: "user", content: [{ type: "text", text: "Hello" }] }],
+ });
+ expect(request.mock.calls[0]?.[0]).toBe("https://first.example/v1/chat/completions");
+ expect(new Headers(request.mock.calls[0]?.[1]?.headers).get("authorization")).toBe(
+ "Bearer first-key",
+ );
+ service.recordRequestSuccess("opencode-go", undefined, "thread-request");
+ expect(
+ service
+ .linkedAccountStatuses()
+ .find((status) => status.provider === "opencode-go" && status.accountId === "default")
+ ?.health,
+ ).toBe("recovered");
+ } finally {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ NodeFS.rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+it.each(["openai-codex", "anthropic", "xai"] as const)(
+ "pins %s OAuth auth when a backup uses an API key",
+ async (provider) => {
+ const { authPath, directory } = fixture();
+ NodeFS.writeFileSync(
+ authPath,
+ JSON.stringify({
+ [provider]: {
+ type: "oauth",
+ access: "expired",
+ refresh: "main-refresh",
+ expires: 0,
+ accountId: "main-account",
+ },
+ [`account:${provider}:backup`]: { type: "api-key", access: "backup-key" },
+ }),
+ );
+ const service = await makeTestSubscriptionAuthService(authPath);
+ vi.stubEnv("NODE_ENV", "production");
+ vi.stubEnv("VITEST", undefined);
+
+ const request = vi.fn(async (input: string | URL | Request, _init?: RequestInit) => {
+ if (String(input).includes("token"))
+ return Response.json({
+ access_token: "refreshed-main",
+ refresh_token: "main-refresh",
+ expires_in: 3600,
+ });
+
+ return new Response("dispatch reached", { status: 503 });
+ });
+
+ vi.stubGlobal("fetch", request);
+
+ try {
+ const prefix = { "openai-codex": "openai", anthropic: "anthropic", xai: "xai" }[provider];
+
+ const model = resolveAkeruMastraModel(
+ `${prefix}/test-model`,
+ new AuthStorage(authPath),
+ undefined,
+ undefined,
+ undefined,
+ (id, scope, thread) => service.getApiKeyCredential(id, scope, thread),
+ undefined,
+ (id, scope, thread) => service.getOAuthCredential(id, scope, thread),
+ (id, scope, thread) => service.getAccessToken(id, scope, thread),
+ "thread-request",
+ ) as ReturnType<ReturnType<typeof createOpenAICompatible>>;
+
+ service.recordRequestFailure(
+ provider,
+ "Spending limit reached.",
+ undefined,
+ "request",
+ "thread-other",
+ );
+ expect(service.getApiKeyCredential(provider, undefined, "thread-backup")?.access).toBe(
+ "backup-key",
+ );
+ await expect(
+ model.doGenerate({
+ prompt: [{ role: "user", content: [{ type: "text", text: "Hello" }] }],
+ }),
+ ).rejects.toThrow();
+ const dispatch = request.mock.calls.find(([input]) => !String(input).includes("token"));
+ expect(dispatch).toBeDefined();
+ const headers = new Headers(dispatch?.[1]?.headers);
+ expect(headers.get("authorization")).toBe("Bearer refreshed-main");
+
+ if (provider === "openai-codex")
+ expect(headers.get("chatgpt-account-id")).toBe("main-account");
+ service.recordRequestSuccess(provider, undefined, "thread-request");
+ expect(
+ service
+ .linkedAccountStatuses()
+ .find((status) => status.provider === provider && status.accountId === "default")?.health,
+ ).toBe("recovered");
+ } finally {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ NodeFS.rmSync(directory, { recursive: true, force: true });
+ }
+ },
+);
+
+it("pins Codex Responses auth when another thread selects an OAuth backup", async () => {
+ const { authPath, directory } = fixture();
+ NodeFS.writeFileSync(
+ authPath,
+ JSON.stringify({
+ "openai-codex": { type: "api-key", access: "main-key", baseUrl: "https://main.example/v1" },
+ "account:openai-codex:backup": {
+ type: "oauth",
+ access: "backup-token",
+ refresh: "backup-refresh",
+ expires: Date.now() + 60000,
+ accountId: "backup-account",
+ },
+ }),
+ );
+ const service = await makeTestSubscriptionAuthService(authPath);
+ vi.stubEnv("NODE_ENV", "production");
+ vi.stubEnv("VITEST", undefined);
+
+ const request = vi.fn(
+ async (_input: string | URL | Request, _init?: RequestInit) =>
+ new Response("dispatch reached", { status: 503 }),
+ );
+
+ vi.stubGlobal("fetch", request);
+
+ try {
+ const model = resolveAkeruMastraModel(
+ "openai/test-model",
+ new AuthStorage(authPath),
+ undefined,
+ undefined,
+ undefined,
+ (id, scope, thread) => service.getApiKeyCredential(id, scope, thread),
+ undefined,
+ undefined,
+ undefined,
+ "thread-request",
+ ) as ReturnType<ReturnType<typeof createOpenAICompatible>>;
+
+ service.recordRequestFailure(
+ "openai-codex",
+ "Spending limit reached.",
+ undefined,
+ "request",
+ "thread-other",
+ );
+ expect(service.getOAuthCredential("openai-codex", undefined, "thread-backup")?.access).toBe(
+ "backup-token",
+ );
+ await expect(
+ model.doGenerate({ prompt: [{ role: "user", content: [{ type: "text", text: "Hello" }] }] }),
+ ).rejects.toThrow();
+ expect(request.mock.calls[0]?.[0]).toBe("https://main.example/v1/responses");
+ expect(new Headers(request.mock.calls[0]?.[1]?.headers).get("authorization")).toBe(
+ "Bearer main-key",
+ );
+ } finally {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ NodeFS.rmSync(directory, { recursive: true, force: true });
+ }
+});
diff --git a/apps/server/src/provider/AkeruMastraHarness.models.test.ts b/apps/server/src/provider/AkeruMastraHarness.models.test.ts
index 4decb457f..df4ceae6f 100644
--- a/apps/server/src/provider/AkeruMastraHarness.models.test.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.models.test.ts
@@ -37,7 +37,7 @@ describe("AkeruMastraHarness", () => {
getCredential,
),
).toMatchObject({ modelId: "gpt-5.6", provider: "openai.responses" });
- expect(getCredential).toHaveBeenCalledWith("openai-codex");
+ expect(getCredential).toHaveBeenCalledWith("openai-codex", undefined, undefined);
});
it("uses the selected instance key without reading the provider-wide credential", () => {
@@ -95,7 +95,7 @@ describe("AkeruMastraHarness", () => {
},
),
).toMatchObject({ modelId: "grok-code-fast-1", provider: "xai.chat" });
- expect(getCredential).toHaveBeenCalledWith("xai", "grok_work");
+ expect(getCredential).toHaveBeenCalledWith("xai", "grok_work", undefined);
});
it("does not leak provider-wide credentials into an isolated instance", () => {
@@ -233,12 +233,9 @@ describe("AkeruMastraHarness", () => {
"opencode-go/gpt-5.6-luna",
);
assert.deepInclude(
- resolveAkeruMastraModel(
- "opencode-go/gpt-5.6-luna",
- authStorage,
- undefined,
- async () => "go-key",
- ),
+ resolveAkeruMastraModel("opencode-go/gpt-5.6-luna", authStorage, undefined, async () => ({
+ access: "go-key",
+ })),
{ provider: "opencode-go.responses", modelId: "gpt-5.6-luna" },
);
assert.throws(
@@ -338,7 +335,7 @@ describe("AkeruMastraHarness", () => {
{ provider: "anthropic.messages", modelId: "claude-sonnet-4-5" },
);
assert.equal(mastraModelId(ProviderDriverKind.make("grok"), "grok-4"), "xai/grok-4");
- assert.equal(mastraModelId(ProviderDriverKind.make("grok"), "grok-build"), "xai/grok-4.6");
+ assert.equal(mastraModelId(ProviderDriverKind.make("grok"), "grok-build"), "xai/grok-4.7");
assert.deepInclude(
resolveAkeruMastraModel(
"xai/grok-4",
diff --git a/apps/server/src/provider/AkeruMastraHarness.ts b/apps/server/src/provider/AkeruMastraHarness.ts
index 4a2597ec8..f196f607b 100644
--- a/apps/server/src/provider/AkeruMastraHarness.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.ts
@@ -35,6 +35,7 @@ import {
controllerModelId,
controllerModelOptions,
controllerModelConnection,
+ controllerResourceId,
} from "./mastra/AkeruMemory.ts";
import {
AkeruMastraHarnessError,
@@ -232,6 +233,7 @@ export const makeAkeruMastraHarness = Effect.fnUntraced(function* (
controllerModelConnection(requestContext, options.getModelConnection),
options.getSubscriptionOAuth,
options.getSubscriptionAccessToken,
+ controllerResourceId(requestContext),
),
tools: ({ requestContext }) => resolveAkeruTools(requestContext, options),
memory: observationalMemory.memory,
diff --git a/apps/server/src/provider/AkeruOpenCodeGoProvider.test.ts b/apps/server/src/provider/AkeruOpenCodeGoProvider.test.ts
index 999d22bf1..716142fe8 100644
--- a/apps/server/src/provider/AkeruOpenCodeGoProvider.test.ts
+++ b/apps/server/src/provider/AkeruOpenCodeGoProvider.test.ts
@@ -16,9 +16,8 @@ describe("AkeruOpenCodeGoProvider", () => {
await buildAkeruOpenCodeGoFetch(
protocol,
- async () => "custom-key",
+ async () => ({ access: "custom-key", baseUrl: "http://localhost:8080/v1" }),
request,
- () => "http://localhost:8080/v1",
)("https://opencode.ai/zen/go/v1/messages", { method: "POST", body: "{}" });
expect(request).toHaveBeenCalledWith(
"http://localhost:8080/v1/messages",
@@ -40,7 +39,9 @@ describe("AkeruOpenCodeGoProvider", () => {
});
it("builds a model while keeping the OpenCode Go model id", () => {
- expect(akeruOpenCodeGoProvider("gpt-5.6-luna", async () => "go-key")).toMatchObject({
+ expect(
+ akeruOpenCodeGoProvider("gpt-5.6-luna", async () => ({ access: "go-key" })),
+ ).toMatchObject({
modelId: "gpt-5.6-luna",
});
});
@@ -58,7 +59,7 @@ describe("AkeruOpenCodeGoProvider", () => {
await buildAkeruOpenCodeGoFetch(
"chat-completions",
- async () => "go-key",
+ async () => ({ access: "go-key" }),
request,
)("https://opencode.ai/zen/go/v1/chat/completions", {
method: "POST",
diff --git a/apps/server/src/provider/AkeruOpenCodeGoProvider.ts b/apps/server/src/provider/AkeruOpenCodeGoProvider.ts
index 8874fd228..5e2a20cf1 100644
--- a/apps/server/src/provider/AkeruOpenCodeGoProvider.ts
+++ b/apps/server/src/provider/AkeruOpenCodeGoProvider.ts
@@ -4,6 +4,8 @@ import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import type { MastraModelConfig } from "@mastra/core/llm";
import { subscriptionRequestUrl } from "../subscription-auth/runtime.ts";
+export type AkeruOpenCodeGoAccess = { readonly access: string; readonly baseUrl?: string };
+
const OPEN_CODE_GO_BASE_URL = "https://opencode.ai/zen/go/v1";
const OPEN_CODE_GO_USER_AGENT = "akeru-bot/0.0.37";
@@ -29,12 +31,12 @@ export function openCodeGoProtocol(modelId: string): OpenCodeGoProtocol {
export function buildAkeruOpenCodeGoFetch(
protocol: OpenCodeGoProtocol,
- getApiKey: () => Promise<string | undefined>,
+ getAccess: () => Promise<AkeruOpenCodeGoAccess | undefined>,
request: AkeruOpenCodeGoFetch = globalThis.fetch,
- getBaseUrl: () => string | undefined = () => undefined,
): AkeruOpenCodeGoFetch {
return async (input, init) => {
- const apiKey = await getApiKey();
+ const credential = await getAccess();
+ const apiKey = credential?.access;
if (!apiKey) throw new Error("OpenCode Go is not connected. Add an API key in Settings.");
@@ -55,7 +57,7 @@ export function buildAkeruOpenCodeGoFetch(
headers.set("Authorization", `Bearer ${apiKey}`);
}
- return request(subscriptionRequestUrl(input, OPEN_CODE_GO_BASE_URL, getBaseUrl()), {
+ return request(subscriptionRequestUrl(input, OPEN_CODE_GO_BASE_URL, credential?.baseUrl), {
...init,
headers,
redirect: "error",
@@ -65,18 +67,14 @@ export function buildAkeruOpenCodeGoFetch(
export function akeruOpenCodeGoProvider(
modelId: string,
- getApiKey: () => Promise<string | undefined>,
- getBaseUrl?: () => string | undefined,
+ getAccess: () => Promise<AkeruOpenCodeGoAccess | undefined>,
): MastraModelConfig {
const protocol = openCodeGoProtocol(modelId);
// SAFETY: The request adapter implements Fetch; this SDK declaration also includes an unused Bun preconnect method.
- const fetch = buildAkeruOpenCodeGoFetch(
- protocol,
- getApiKey,
- globalThis.fetch,
- getBaseUrl,
- ) as NonNullable<NonNullable<Parameters<typeof createOpenAI>[0]>["fetch"]>;
+ const fetch = buildAkeruOpenCodeGoFetch(protocol, getAccess, globalThis.fetch) as NonNullable<
+ NonNullable<Parameters<typeof createOpenAI>[0]>["fetch"]
+ >;
if (protocol === "responses") {
return createOpenAI({
diff --git a/apps/server/src/provider/Drivers/HarnessProviderDrivers.test.ts b/apps/server/src/provider/Drivers/HarnessProviderDrivers.test.ts
index 5107b8a28..56ecbeb1b 100644
--- a/apps/server/src/provider/Drivers/HarnessProviderDrivers.test.ts
+++ b/apps/server/src/provider/Drivers/HarnessProviderDrivers.test.ts
@@ -432,7 +432,7 @@ it.layer(testLayer)("Harness provider drivers without CLIs", (it) => {
if (driver.driverKind === "grok") {
expect(after.models).toContainEqual(
- expect.objectContaining({ slug: "grok-build", name: "Grok 4.6", isDefault: true }),
+ expect.objectContaining({ slug: "grok-build", name: "Grok 4.7", isDefault: true }),
);
for (const slug of ["grok-4.6", "grok-4.5", "grok-code-fast-1"]) {
diff --git a/apps/server/src/provider/Drivers/OpenCodeGoDriver.test.ts b/apps/server/src/provider/Drivers/OpenCodeGoDriver.test.ts
index 6d61ed865..9489a8832 100644
--- a/apps/server/src/provider/Drivers/OpenCodeGoDriver.test.ts
+++ b/apps/server/src/provider/Drivers/OpenCodeGoDriver.test.ts
@@ -48,7 +48,7 @@ describe("OpenCodeGoDriver", () => {
displayName: "OpenCode Go",
auth: { status: "unauthenticated", type: "apiKey" },
models: expect.arrayContaining([
- expect.objectContaining({ slug: "gpt-5.6-luna", isDefault: true }),
+ expect.objectContaining({ slug: "gpt-6-luna", isDefault: true }),
expect.objectContaining({ slug: "grok-4.5" }),
expect.objectContaining({ slug: "muse-spark-1.3-contributor" }),
expect.objectContaining({ slug: "qwen3.8-max" }),
diff --git a/apps/server/src/provider/Drivers/OpenCodeGoDriver.ts b/apps/server/src/provider/Drivers/OpenCodeGoDriver.ts
index e35c0909f..06b623b9c 100644
--- a/apps/server/src/provider/Drivers/OpenCodeGoDriver.ts
+++ b/apps/server/src/provider/Drivers/OpenCodeGoDriver.ts
@@ -24,6 +24,7 @@ const DRIVER_KIND = ProviderDriverKind.make("opencodeGo");
const decodeSettings = Schema.decodeSync(OpenCodeGoSettings);
export const OPEN_CODE_GO_MODELS = [
+ "gpt-6-luna",
"gpt-5.6-luna",
"grok-4.5",
"grok-4.6",
diff --git a/apps/server/src/provider/HarnessProviderStatus.test.ts b/apps/server/src/provider/HarnessProviderStatus.test.ts
index 85615f783..ac6193397 100644
--- a/apps/server/src/provider/HarnessProviderStatus.test.ts
+++ b/apps/server/src/provider/HarnessProviderStatus.test.ts
@@ -1,37 +1,11 @@
import { describe, expect, it } from "vite-plus/test";
-import { codexModelCapabilities, harnessModelName } from "./HarnessProviderStatus.ts";
+import { codexModelCapabilities } from "./HarnessProviderStatus.ts";
import {
getClaudeModelCapabilities,
normalizeClaudeCliEffort,
} from "./Layers/claude/ClaudeModels.ts";
-describe("harnessModelName", () => {
- it("formats model slugs as picker names", () => {
- expect(
- [
- "gpt-6.1-sol",
- "gpt-6-luna",
- "gpt-5.3-codex-spark",
- "gpt-5",
- "gpt-daybreak-blue-latest",
- "claude-opus-5-5",
- "claude-sonnet-5",
- "grok-4.20-beta",
- ].map(harnessModelName),
- ).toEqual([
- "GPT-6.1 Sol",
- "GPT-6 Luna",
- "GPT-5.3 Codex Spark",
- "GPT-5",
- "GPT Daybreak Blue Latest",
- "Claude Opus 5.5",
- "Claude Sonnet 5",
- "Grok 4.20 Beta",
- ]);
- });
-});
-
describe("codexModelCapabilities", () => {
const options = (slug: string, entry: Parameters<typeof codexModelCapabilities>[1]) =>
codexModelCapabilities(slug, entry).optionDescriptors?.map((descriptor) => [
diff --git a/apps/server/src/provider/HarnessProviderStatus.ts b/apps/server/src/provider/HarnessProviderStatus.ts
index a5d5072b9..5720caad3 100644
--- a/apps/server/src/provider/HarnessProviderStatus.ts
+++ b/apps/server/src/provider/HarnessProviderStatus.ts
@@ -5,7 +5,7 @@ import {
type ProviderInstanceId,
} from "@akeru/contracts";
import { getAvailableThinkingLevelsForModel } from "@mastra/code-sdk/thinking";
-import { createModelCapabilities } from "@akeru/shared/model";
+import { createModelCapabilities, formatModelSlug } from "@akeru/shared/model";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -44,31 +44,6 @@ export const CODEX_HARNESS_HISTORICAL_MODELS = [
"codex-mini-latest",
] as const;
-/**
- * Readable picker name for a harness model slug that has no catalog entry:
- * `gpt-6.1-sol` becomes "GPT-6.1 Sol" and `claude-opus-5-5` becomes
- * "Claude Opus 5.5".
- */
-export function harnessModelName(slug: string): string {
- const words: string[] = [];
-
- for (const part of slug.split("-")) {
- const previous = words.at(-1);
-
- if (/^\d{1,2}$/.test(part) && previous && /^\d+(\.\d+)*$/.test(previous)) {
- words[words.length - 1] = `${previous}.${part}`;
- } else if (/^\d/.test(part) && previous === "GPT") {
- words[words.length - 1] = `GPT-${part}`;
- } else if (part === "gpt") {
- words.push("GPT");
- } else {
- words.push(/^\d/.test(part) ? part : part.charAt(0).toUpperCase() + part.slice(1));
- }
- }
-
- return words.join(" ");
-}
-
/** Codex model ids: the catalog's, newest first, then historical slugs that
* saved threads may still reference. */
export function codexHarnessModelIds(catalogIds: ReadonlyArray<string>): string[] {
@@ -241,7 +216,7 @@ export const makeHarnessProviderStatus = Effect.fn("makeHarnessProviderStatus")(
.filter((slug) => !draft.models.some((model) => !model.isCustom && model.slug === slug))
.map((slug, index) => ({
slug,
- name: entries.get(slug)?.name ?? harnessModelName(slug),
+ name: entries.get(slug)?.name ?? formatModelSlug(slug),
isCustom: false,
...(index === 0 && !draft.models.some((model) => !model.isCustom)
? { isDefault: true }
@@ -281,7 +256,7 @@ export const makeHarnessProviderStatus = Effect.fn("makeHarnessProviderStatus")(
if (model.slug !== "grok-build" || model.isCustom) return model;
const { isLegacy: _isLegacy, ...rest } = model;
- return { ...rest, name: "Grok 4.6", isDefault: true };
+ return { ...rest, name: "Grok 4.7", isDefault: true };
}),
}
: classified;
diff --git a/apps/server/src/provider/Layers/agentController/Harness.ts b/apps/server/src/provider/Layers/agentController/Harness.ts
index 9a4ac22af..c13ad9740 100644
--- a/apps/server/src/provider/Layers/agentController/Harness.ts
+++ b/apps/server/src/provider/Layers/agentController/Harness.ts
@@ -125,15 +125,16 @@ export function createHarness(deps: {
const bundle = yield* makeMastraHarness({
authStorage: deps.authStorage,
- getKimiAccess: (instanceId) => deps.subscriptionAuth.getKimiForCodingAccess(instanceId),
- getOpenCodeGoApiKey: async (instanceId) =>
- deps.subscriptionAuth.getApiKeyCredential("opencode-go", instanceId)?.access,
- getSubscriptionApiKey: (provider, instanceId) =>
- deps.subscriptionAuth.getApiKeyCredential(provider, instanceId),
- getSubscriptionOAuth: (provider, instanceId) =>
- deps.subscriptionAuth.getOAuthCredential(provider, instanceId),
- getSubscriptionAccessToken: (provider, instanceId) =>
- deps.subscriptionAuth.getAccessToken(provider, instanceId),
+ getKimiAccess: (instanceId, threadId) =>
+ deps.subscriptionAuth.getKimiForCodingAccess(instanceId, threadId),
+ getOpenCodeGoApiKey: async (instanceId, threadId) =>
+ deps.subscriptionAuth.getApiKeyCredential("opencode-go", instanceId, threadId),
+ getSubscriptionApiKey: (provider, instanceId, threadId) =>
+ deps.subscriptionAuth.getApiKeyCredential(provider, instanceId, threadId),
+ getSubscriptionOAuth: (provider, instanceId, threadId) =>
+ deps.subscriptionAuth.getOAuthCredential(provider, instanceId, threadId),
+ getSubscriptionAccessToken: (provider, instanceId, threadId) =>
+ deps.subscriptionAuth.getAccessToken(provider, instanceId, threadId),
getModelConnection: (providerInstanceId) => {
const connection = deps.modelConnections.get(providerInstanceId);
diff --git a/apps/server/src/provider/Layers/agentController/ProviderAccess.ts b/apps/server/src/provider/Layers/agentController/ProviderAccess.ts
index 359cccf8d..4b4651df1 100644
--- a/apps/server/src/provider/Layers/agentController/ProviderAccess.ts
+++ b/apps/server/src/provider/Layers/agentController/ProviderAccess.ts
@@ -137,6 +137,7 @@ export function recordProviderAccessHealth(
): void {
const provider = subscriptionProviderForDriver(event.provider);
const providerInstanceId = event.providerInstanceId;
+ const threadId = String(event.threadId);
if (event.type === "turn.completed") {
if (event.payload.state === "failed") {
@@ -149,8 +150,16 @@ export function recordProviderAccessHealth(
providerInstanceId,
message,
event.createdAt,
+ threadId,
+ );
+ else
+ subscriptionAuth.recordRequestFailure(
+ provider,
+ message,
+ event.createdAt,
+ "request",
+ threadId,
);
- else subscriptionAuth.recordRequestFailure(provider, message, event.createdAt);
}
if (providerInstanceId) {
@@ -168,8 +177,9 @@ export function recordProviderAccessHealth(
provider,
providerInstanceId,
event.createdAt,
+ threadId,
);
- else subscriptionAuth.recordRequestSuccess(provider, event.createdAt);
+ else subscriptionAuth.recordRequestSuccess(provider, event.createdAt, threadId);
}
if (providerInstanceId) {
@@ -189,8 +199,16 @@ export function recordProviderAccessHealth(
providerInstanceId,
event.payload.message,
event.createdAt,
+ threadId,
+ );
+ else
+ subscriptionAuth.recordRequestFailure(
+ provider,
+ event.payload.message,
+ event.createdAt,
+ "request",
+ threadId,
);
- else subscriptionAuth.recordRequestFailure(provider, event.payload.message, event.createdAt);
}
if (providerInstanceId) {
diff --git a/apps/server/src/provider/ReasoningOptions.test.ts b/apps/server/src/provider/ReasoningOptions.test.ts
index d6c7f8dae..dcecc8504 100644
--- a/apps/server/src/provider/ReasoningOptions.test.ts
+++ b/apps/server/src/provider/ReasoningOptions.test.ts
@@ -57,7 +57,7 @@ async function capturedRequest(
mastraModelId(provider, modelId),
auth,
async () => ({ accessToken: "kimi-token" }),
- async () => "go-key",
+ async () => ({ access: "go-key" }),
modelOptions,
oauth ? undefined : () => ({ type: "api-key", access: "test-key" }),
);
diff --git a/apps/server/src/provider/mastra/AkeruHarnessTypes.ts b/apps/server/src/provider/mastra/AkeruHarnessTypes.ts
index a8dcebfba..b1c918ed2 100644
--- a/apps/server/src/provider/mastra/AkeruHarnessTypes.ts
+++ b/apps/server/src/provider/mastra/AkeruHarnessTypes.ts
@@ -12,6 +12,7 @@ import {
} from "@akeru/contracts";
import * as Duration from "effect/Duration";
import type { SubscriptionAuthService } from "../../subscription-auth/service.ts";
+import type { AkeruOpenCodeGoAccess } from "../AkeruOpenCodeGoProvider.ts";
import { type AkeruKimiAccess } from "../AkeruKimiProvider.ts";
import type { AkeruToolRuntime, AkeruToolResult } from "../tools/AkeruToolTypes.ts";
import {
@@ -56,8 +57,14 @@ export type AkeruControllerSession = Pick<
export interface AkeruMastraHarnessOptions {
readonly authStorage: AuthStorage;
- readonly getKimiAccess?: (instanceId?: string) => Promise<AkeruKimiAccess | undefined>;
- readonly getOpenCodeGoApiKey?: (instanceId?: string) => Promise<string | undefined>;
+ readonly getKimiAccess?: (
+ instanceId?: string,
+ threadId?: string,
+ ) => Promise<AkeruKimiAccess | undefined>;
+ readonly getOpenCodeGoApiKey?: (
+ instanceId?: string,
+ threadId?: string,
+ ) => Promise<AkeruOpenCodeGoAccess | undefined>;
readonly getSubscriptionApiKey?: SubscriptionAuthService["getApiKeyCredential"];
readonly getSubscriptionOAuth?: SubscriptionAuthService["getOAuthCredential"];
readonly getSubscriptionAccessToken?: SubscriptionAuthService["getAccessToken"];
diff --git a/apps/server/src/provider/mastra/AkeruModels.ts b/apps/server/src/provider/mastra/AkeruModels.ts
index 4eafbd2c2..d48986ed0 100644
--- a/apps/server/src/provider/mastra/AkeruModels.ts
+++ b/apps/server/src/provider/mastra/AkeruModels.ts
@@ -5,19 +5,17 @@ import { opencodeClaudeMaxProvider } from "@mastra/code-sdk/providers/claude-max
import { xaiProvider } from "@mastra/code-sdk/providers/xai";
import { createAnthropic } from "@ai-sdk/anthropic";
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
-import { SubscriptionProviderId, type ProviderDriverKind } from "@akeru/contracts";
+import { type SubscriptionProviderId, type ProviderDriverKind } from "@akeru/contracts";
import type { SubscriptionAuthService } from "../../subscription-auth/service.ts";
import { akeruCodexOAuthProvider, akeruOpenAIProvider } from "../AkeruOpenAIProvider.ts";
import { akeruKimiProvider, type AkeruKimiAccess } from "../AkeruKimiProvider.ts";
-import { akeruOpenCodeGoProvider } from "../AkeruOpenCodeGoProvider.ts";
+import { akeruOpenCodeGoProvider, type AkeruOpenCodeGoAccess } from "../AkeruOpenCodeGoProvider.ts";
import { type AkeruMastraState } from "./AkeruHarnessTypes.ts";
const decodeInlineConfig = Schema.decodeUnknownSync(
Schema.Struct({ provider: Schema.optionalKey(Schema.Unknown) }),
);
-const isSubscriptionProviderId = Schema.is(SubscriptionProviderId);
-
export const DEFAULT_MODEL_ID = "openai/gpt-5.6-sol";
export type AkeruRunOptions = {
@@ -81,7 +79,7 @@ export const MASTRA_MODEL_PREFIX = {
} as const;
export function mastraModelId(provider: ProviderDriverKind, model: string): string {
- const trimmed = provider === "grok" && model.trim() === "grok-build" ? "grok-4.6" : model.trim();
+ const trimmed = provider === "grok" && model.trim() === "grok-build" ? "grok-4.7" : model.trim();
const prefix = Object.entries(MASTRA_MODEL_PREFIX).find(([driver]) => driver === provider)?.[1];
if (!prefix) return trimmed.includes("/") ? trimmed : `${provider}/${trimmed}`;
@@ -125,8 +123,11 @@ export function openCodeGoInlineConnection(environment: NodeJS.ProcessEnv | unde
export function resolveAkeruMastraModel(
modelId: string,
authStorage: AuthStorage,
- getKimiAccess?: (instanceId?: string) => Promise<AkeruKimiAccess | undefined>,
- getOpenCodeGoApiKey?: (instanceId?: string) => Promise<string | undefined>,
+ getKimiAccess?: (instanceId?: string, threadId?: string) => Promise<AkeruKimiAccess | undefined>,
+ getOpenCodeGoApiKey?: (
+ instanceId?: string,
+ threadId?: string,
+ ) => Promise<AkeruOpenCodeGoAccess | undefined>,
_modelOptions?: AkeruMastraState["modelOptions"],
getSubscriptionApiKey?: SubscriptionAuthService["getApiKeyCredential"],
connection?: {
@@ -137,6 +138,8 @@ export function resolveAkeruMastraModel(
},
getSubscriptionOAuth?: SubscriptionAuthService["getOAuthCredential"],
getSubscriptionAccessToken?: SubscriptionAuthService["getAccessToken"],
+ /** The thread this request serves, so its outcome is recorded on the account it used. */
+ threadId?: string,
) {
const trimmed = modelId.trim();
@@ -148,23 +151,23 @@ export function resolveAkeruMastraModel(
const instanceId = connection?.instanceId;
const savedApiKey = (provider: Parameters<NonNullable<typeof getSubscriptionApiKey>>[0]) =>
- instanceId ? getSubscriptionApiKey?.(provider, instanceId) : getSubscriptionApiKey?.(provider);
-
- // SAFETY: The scoped view inherits AuthStorage methods and state, and overrides only credential lookup.
- const scopedAuthStorage =
- instanceId && getSubscriptionOAuth && getSubscriptionAccessToken
- ? Object.assign(Object.create(authStorage) as AuthStorage, {
- reload: () => {},
- get: (provider: string) =>
- isSubscriptionProviderId(provider)
- ? getSubscriptionOAuth(provider, instanceId)
- : undefined,
- getApiKey: (provider: string) =>
- isSubscriptionProviderId(provider)
- ? getSubscriptionAccessToken(provider, instanceId)
- : undefined,
- })
- : authStorage;
+ getSubscriptionApiKey?.(provider, instanceId, threadId);
+
+ // OAuth token refresh stays on the account selected for this model's transport.
+ const scopedAuthStorage = (providerId: SubscriptionProviderId) => {
+ if (!getSubscriptionOAuth || !getSubscriptionAccessToken) return authStorage;
+ const credential = getSubscriptionOAuth(providerId, instanceId, threadId);
+
+ // SAFETY: The scoped view inherits AuthStorage methods and state, and overrides only credential lookup.
+ return Object.assign(Object.create(authStorage) as AuthStorage, {
+ reload: () => {},
+ get: (provider: string) => (provider === providerId ? credential : undefined),
+ getApiKey: (provider: string) =>
+ provider === providerId && credential
+ ? getSubscriptionAccessToken(providerId, credential.scope ?? instanceId)
+ : undefined,
+ });
+ };
if (trimmed.startsWith("openai/")) {
const instanceApiKey = environment?.OPENAI_API_KEY?.trim();
@@ -181,15 +184,20 @@ export function resolveAkeruMastraModel(
? () => savedApiKey("openai-codex")
: undefined;
- if (getCredential?.()) {
- return akeruOpenAIProvider(trimmed.slice("openai/".length), () => getCredential());
+ const credential = getCredential?.();
+
+ if (credential) {
+ return akeruOpenAIProvider(trimmed.slice("openai/".length), () => credential);
}
if (!useSavedCredential) {
throw new Error("This Codex instance has no OPENAI_API_KEY transport for Akeru Mastra.");
}
- return akeruCodexOAuthProvider(trimmed.slice("openai/".length), scopedAuthStorage);
+ return akeruCodexOAuthProvider(
+ trimmed.slice("openai/".length),
+ scopedAuthStorage("openai-codex"),
+ );
}
if (trimmed.startsWith("anthropic/")) {
@@ -232,7 +240,10 @@ export function resolveAkeruMastraModel(
);
}
- return opencodeClaudeMaxProvider(model, { ...contextHeaders, authStorage: scopedAuthStorage });
+ return opencodeClaudeMaxProvider(model, {
+ ...contextHeaders,
+ authStorage: scopedAuthStorage("anthropic"),
+ });
}
if (trimmed.startsWith("xai/")) {
@@ -260,7 +271,7 @@ export function resolveAkeruMastraModel(
throw new Error("This Grok instance has no XAI_API_KEY transport for Akeru Mastra.");
}
- return xaiProvider(model, { authStorage: scopedAuthStorage });
+ return xaiProvider(model, { authStorage: scopedAuthStorage("xai") });
}
if (trimmed.startsWith("kimi-for-coding/")) {
@@ -273,7 +284,7 @@ export function resolveAkeruMastraModel(
if (!getKimiAccess) throw new Error("Kimi For Coding subscription access is unavailable.");
return akeruKimiProvider(trimmed.slice("kimi-for-coding/".length), () =>
- getKimiAccess(instanceId),
+ getKimiAccess(instanceId, threadId),
);
}
@@ -281,22 +292,29 @@ export function resolveAkeruMastraModel(
const inlineConnection = openCodeGoInlineConnection(environment);
const instanceApiKey = environment?.OPENCODE_API_KEY?.trim() || inlineConnection.apiKey;
- const resolveApiKey = instanceApiKey
- ? async () => instanceApiKey
+ const baseUrl = environment?.OPENCODE_BASE_URL?.trim() || inlineConnection.baseUrl;
+
+ const resolveAccess = instanceApiKey
+ ? async () => {
+ const resolvedBaseUrl =
+ baseUrl || (useSavedCredential ? savedApiKey("opencode-go")?.baseUrl : undefined);
+
+ return {
+ access: instanceApiKey,
+ ...(resolvedBaseUrl ? { baseUrl: resolvedBaseUrl } : {}),
+ };
+ }
: useSavedCredential && getOpenCodeGoApiKey
- ? () => getOpenCodeGoApiKey(instanceId)
+ ? async () => {
+ const credential = await getOpenCodeGoApiKey(instanceId, threadId);
+
+ return credential ? { ...credential, ...(baseUrl ? { baseUrl } : {}) } : undefined;
+ }
: undefined;
- if (!resolveApiKey) throw new Error("OpenCode Go subscription access is unavailable.");
+ if (!resolveAccess) throw new Error("OpenCode Go subscription access is unavailable.");
- return akeruOpenCodeGoProvider(
- trimmed.slice("opencode-go/".length),
- resolveApiKey,
- () =>
- environment?.OPENCODE_BASE_URL?.trim() ||
- inlineConnection.baseUrl ||
- (useSavedCredential ? savedApiKey("opencode-go")?.baseUrl : undefined),
- );
+ return akeruOpenCodeGoProvider(trimmed.slice("opencode-go/".length), resolveAccess);
}
if (trimmed.startsWith("custom-openai/")) {
diff --git a/apps/server/src/subscription-auth/accountLimits.ts b/apps/server/src/subscription-auth/accountLimits.ts
new file mode 100644
index 000000000..12b0bc325
--- /dev/null
+++ b/apps/server/src/subscription-auth/accountLimits.ts
@@ -0,0 +1,39 @@
+import * as Effect from "effect/Effect";
+import * as Clock from "effect/Clock";
+import * as DateTime from "effect/DateTime";
+
+// How long an account that hit a limit sits out when the provider did not say
+// when it resets. Requests use the next linked account meanwhile.
+const LIMIT_COOLDOWN_MS = 60 * 60_000;
+
+const LIMIT_PATTERN =
+ /usage limit|rate limit|too many requests|quota|usage cap|limit reached|hit your .*limit|spending limit|budget exceeded|max usage|\b429\b/i;
+
+export function isAccountLimitMessage(message: string): boolean {
+ return LIMIT_PATTERN.test(message);
+}
+
+/** When an account that hit a limit may be tried again, from the provider's wording when it gives one. */
+export function limitRetryAt(message: string, at: string): string {
+ const start = Date.parse(at);
+ const base = Number.isFinite(start) ? start : Effect.runSync(Clock.currentTimeMillis);
+ const window = /(?:try again|resets?|retry)\s+(?:in|after)\s+([^.;]*)/i.exec(message)?.[1];
+ let ms = 0;
+
+ if (window) {
+ const units = new Map([
+ ["s", 1_000],
+ ["m", 60_000],
+ ["h", 3_600_000],
+ ["d", 86_400_000],
+ ]);
+
+ for (const match of window.matchAll(
+ /(\d+(?:\.\d+)?)\s*(s|sec|second|m|min|minute|h|hr|hour|d|day)s?\b/gi,
+ )) {
+ ms += Number(match[1]) * (units.get(match[2]!.toLowerCase()[0]!) ?? 0);
+ }
+ }
+
+ return DateTime.formatIso(DateTime.makeUnsafe(base + (ms > 0 ? ms : LIMIT_COOLDOWN_MS)));
+}
diff --git a/apps/server/src/subscription-auth/accountState.test.ts b/apps/server/src/subscription-auth/accountState.test.ts
new file mode 100644
index 000000000..54e1a7375
--- /dev/null
+++ b/apps/server/src/subscription-auth/accountState.test.ts
@@ -0,0 +1,75 @@
+import * as Clock from "effect/Clock";
+import * as Effect from "effect/Effect";
+import * as Path from "effect/Path";
+import * as NodeFS from "node:fs";
+import { expect, it, vi } from "vite-plus/test";
+
+import { SubscriptionAccountState } from "./accountState.ts";
+import { subscriptionCredentialStore } from "./credentialStore.ts";
+import { SubscriptionHealthService } from "./healthService.ts";
+import { fixture } from "./testUtils/subscriptionAuthStorage.ts";
+import { runWithNodeServices } from "./testUtils/subscriptionAuthService.ts";
+
+it.each(["reorder", "remember"] as const)(
+ "merges a concurrent provider order during %s",
+ async (operation) => {
+ const { authPath, directory } = fixture();
+ NodeFS.writeFileSync(
+ authPath,
+ JSON.stringify({
+ "openai-codex": { type: "api-key", access: "codex-key" },
+ "account:openai-codex:backup": { type: "api-key", access: "codex-backup" },
+ xai: { type: "api-key", access: "grok-key" },
+ "account:xai:backup": { type: "api-key", access: "grok-backup" },
+ }),
+ );
+ NodeFS.writeFileSync(
+ `${authPath}.accounts`,
+ JSON.stringify({ "openai-codex": ["default", "backup"], xai: ["default", "backup"] }),
+ );
+
+ const accounts = await runWithNodeServices(
+ Effect.gen(function* () {
+ const store = yield* subscriptionCredentialStore(authPath);
+ yield* store.reload;
+ const clock = yield* Clock.Clock;
+ const path = yield* Path.Path;
+ const reload = () => store.reload;
+
+ return new SubscriptionAccountState(
+ store,
+ new SubscriptionHealthService(store, clock, path, false, reload),
+ clock,
+ reload,
+ );
+ }),
+ );
+
+ const linkedAccountIds = accounts.linkedAccountIds.bind(accounts);
+
+ const lookup = vi.spyOn(accounts, "linkedAccountIds").mockImplementationOnce((provider) => {
+ const ids = linkedAccountIds(provider);
+ // Another process writes after this operation has read its linked accounts.
+ NodeFS.writeFileSync(
+ `${authPath}.accounts`,
+ JSON.stringify({ "openai-codex": ["default", "backup"], xai: ["backup", "default"] }),
+ );
+
+ return ids;
+ });
+
+ try {
+ if (operation === "reorder")
+ await accounts.setAccountOrder("openai-codex", ["backup", "default"]);
+ else accounts.rememberAccountOrder("openai-codex");
+ expect(JSON.parse(NodeFS.readFileSync(`${authPath}.accounts`, "utf-8"))).toEqual({
+ "openai-codex": operation === "reorder" ? ["backup", "default"] : ["default", "backup"],
+ xai: ["backup", "default"],
+ });
+ expect(NodeFS.statSync(`${authPath}.accounts`).mode & 0o777).toBe(0o600);
+ } finally {
+ lookup.mockRestore();
+ NodeFS.rmSync(directory, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/apps/server/src/subscription-auth/accountState.ts b/apps/server/src/subscription-auth/accountState.ts
new file mode 100644
index 000000000..98cfdf479
--- /dev/null
+++ b/apps/server/src/subscription-auth/accountState.ts
@@ -0,0 +1,224 @@
+import { isAccountLimitMessage } from "./accountLimits.ts";
+import * as Effect from "effect/Effect";
+import * as Predicate from "effect/Predicate";
+import type * as Clock from "effect/Clock";
+import { type SubscriptionCredentialStore } from "./credentialStore.ts";
+import { SubscriptionHealthService, fileVersion } from "./healthService.ts";
+import {
+ accountIdForKey,
+ defaultInstanceByProvider,
+ SUBSCRIPTION_PROVIDER_IDS,
+ type RequestHealthStatus,
+ accountScope,
+ credentialAt,
+ credentialKey,
+ DEFAULT_ACCOUNT_ID,
+ isDefaultScope,
+ isSubscriptionProviderId,
+ type SubscriptionProviderId,
+} from "./serviceTypes.ts";
+
+const SERVED_BY_THREAD_CAP = 512;
+
+export class SubscriptionAccountState {
+ private readonly orderPath: string;
+ private accountOrder: Partial<Record<SubscriptionProviderId, string[]>> = {};
+ readonly lastServedKey = new Map<SubscriptionProviderId, string>();
+ private readonly servedByThread = new Map<string, string>();
+ private orderVersion: string | undefined;
+ private readonly store: SubscriptionCredentialStore;
+ private readonly healthService: SubscriptionHealthService;
+ private readonly clock: Clock.Clock;
+ private readonly reload: () => Effect.Effect<void>;
+ constructor(
+ store: SubscriptionCredentialStore,
+ healthService: SubscriptionHealthService,
+ clock: Clock.Clock,
+ reload: () => Effect.Effect<void>,
+ ) {
+ this.store = store;
+ this.healthService = healthService;
+ this.clock = clock;
+ this.reload = reload;
+ this.orderPath = `${store.path}.accounts`;
+ this.reloadAccountOrder();
+ }
+ private get data() {
+ return this.store.current().data;
+ }
+ private get health() {
+ return this.healthService.health;
+ }
+ private reloadAsync() {
+ return Effect.runPromise(this.reload());
+ }
+ reloadAccountOrder(): void {
+ this.orderVersion = fileVersion(this.orderPath);
+
+ try {
+ const parsed = this.healthService.readAccountOrder(this.orderPath);
+ this.accountOrder = {};
+
+ if (!Predicate.isObjectKeyword(parsed)) return;
+
+ for (const [provider, ids] of Object.entries(parsed)) {
+ if (isSubscriptionProviderId(provider) && Array.isArray(ids))
+ this.accountOrder[provider] = ids.filter((id): id is string => Predicate.isString(id));
+ }
+ } catch {
+ this.accountOrder = {};
+ }
+ }
+
+ private saveAccountOrder(provider: SubscriptionProviderId, accountIds: string[]): void {
+ this.reloadAccountOrder();
+ this.accountOrder[provider] = accountIds;
+ this.healthService.writeSecureJson(this.orderPath, this.accountOrder);
+ this.orderVersion = fileVersion(this.orderPath);
+ }
+
+ /** Picks up an order or health change another service instance wrote, such as a reorder from Settings. */
+ refreshAccountState(): void {
+ if (fileVersion(this.orderPath) !== this.orderVersion) this.reloadAccountOrder();
+
+ if (fileVersion(this.healthService.healthPath) !== this.healthService.healthVersion)
+ this.healthService.reloadHealth();
+ }
+
+ /** Signed-in account ids for a provider, in priority order. */
+ linkedAccountIds(provider: SubscriptionProviderId): string[] {
+ const present: string[] = [];
+
+ if (credentialAt(this.data, provider)) present.push(DEFAULT_ACCOUNT_ID);
+
+ for (const key of Object.keys(this.data).toSorted()) {
+ const accountId = accountIdForKey(provider, key);
+
+ if (accountId && accountId !== DEFAULT_ACCOUNT_ID && credentialAt(this.data, key))
+ present.push(accountId);
+ }
+
+ const stored = (this.accountOrder[provider] ?? []).filter((id) => present.includes(id));
+
+ return [...new Set(stored), ...present.filter((id) => !stored.includes(id))];
+ }
+
+ /** False while an account sits out a limit or its sign-in was rejected. */
+ accountReady(key: string, now: number): boolean {
+ const health = this.health[key];
+
+ if (!health) return true;
+
+ if (health.nextRetryAt && Date.parse(health.nextRetryAt) > now) return false;
+
+ const failedLast =
+ health.lastFailedRequest !== undefined &&
+ (health.lastSuccessfulRequestAt === undefined ||
+ health.lastFailedRequest.at >= health.lastSuccessfulRequestAt);
+
+ return !(failedLast && health.failureKind === "revoked");
+ }
+
+ /**
+ * The credential key default-scope requests use: the first linked account
+ * that is ready, else the first linked account so its error still surfaces.
+ */
+ activeAccountKey(
+ provider: SubscriptionProviderId,
+ now = this.clock.currentTimeMillisUnsafe(),
+ ): string {
+ this.refreshAccountState();
+
+ const keys = this.linkedAccountIds(provider).map((id) =>
+ credentialKey(provider, accountScope(id)),
+ );
+
+ return keys.find((key) => this.accountReady(key, now)) ?? keys[0] ?? provider;
+ }
+
+ /** The key a read resolves to. Default-scope reads follow the account order. */
+ liveKey(provider: SubscriptionProviderId, scope?: string): string {
+ return isDefaultScope(provider, scope)
+ ? this.activeAccountKey(provider)
+ : credentialKey(provider, scope);
+ }
+
+ /**
+ * `liveKey` for a request about to be sent, remembered so its outcome is recorded there.
+ * A `threadId` keeps concurrent turns on different accounts from claiming each other's outcomes.
+ */
+ servingKey(provider: SubscriptionProviderId, scope?: string, threadId?: string): string {
+ const key = this.liveKey(provider, scope);
+
+ if (!isDefaultScope(provider, scope)) return key;
+ this.lastServedKey.set(provider, key);
+
+ if (threadId !== undefined) {
+ const slot = `${provider}:${threadId}`;
+ this.servedByThread.delete(slot);
+ this.servedByThread.set(slot, key);
+
+ if (this.servedByThread.size > SERVED_BY_THREAD_CAP) {
+ const oldest = this.servedByThread.keys().next().value;
+
+ if (oldest !== undefined) this.servedByThread.delete(oldest);
+ }
+ }
+
+ return key;
+ }
+
+ /** The key a request outcome belongs to: the account that thread's request used. */
+ outcomeKey(provider: SubscriptionProviderId, scope?: string, threadId?: string): string {
+ if (!isDefaultScope(provider, scope)) return credentialKey(provider, scope);
+
+ const served =
+ threadId === undefined ? undefined : this.servedByThread.get(`${provider}:${threadId}`);
+
+ return served ?? this.lastServedKey.get(provider) ?? this.activeAccountKey(provider);
+ }
+
+ /** Keeps a newly signed-in account at the end of the order. */
+ rememberAccountOrder(provider: SubscriptionProviderId): void {
+ this.reloadAccountOrder();
+ this.saveAccountOrder(provider, this.linkedAccountIds(provider));
+ }
+
+ /** Reorder linked accounts. Ids that are not linked are ignored; missing ones keep their place at the end. */
+ async setAccountOrder(
+ provider: SubscriptionProviderId,
+ accountIds: ReadonlyArray<string>,
+ ): Promise<void> {
+ await this.reloadAsync();
+ this.reloadAccountOrder();
+ const linked = this.linkedAccountIds(provider);
+ const ordered = [...new Set(accountIds.filter((id) => linked.includes(id)))];
+ this.saveAccountOrder(provider, [...ordered, ...linked.filter((id) => !ordered.includes(id))]);
+ }
+ providerInstanceRequestHealth(instanceId: string): RequestHealthStatus | undefined {
+ const health = this.healthService.requestHealth(`provider:${instanceId}`);
+
+ const provider = SUBSCRIPTION_PROVIDER_IDS.find(
+ (candidate) => defaultInstanceByProvider[candidate] === instanceId,
+ );
+
+ // An account limit does not block the provider once a linked account is ready.
+ if (
+ provider &&
+ health?.lastFailedRequest &&
+ (health.health === "failed" || health.health === "failed-first-request") &&
+ isAccountLimitMessage(health.lastFailedRequest.message) &&
+ // Only a limit an account actually recorded can be routed around.
+ this.linkedAccountIds(provider).some((id) => {
+ const failure = this.health[credentialKey(provider, accountScope(id))]?.lastFailedRequest;
+
+ return failure !== undefined && isAccountLimitMessage(failure.message);
+ }) &&
+ this.accountReady(this.activeAccountKey(provider), this.clock.currentTimeMillisUnsafe())
+ ) {
+ return undefined;
+ }
+
+ return health;
+ }
+}
diff --git a/apps/server/src/subscription-auth/credentialAccess.ts b/apps/server/src/subscription-auth/credentialAccess.ts
index 04a8d6112..07c16fc22 100644
--- a/apps/server/src/subscription-auth/credentialAccess.ts
+++ b/apps/server/src/subscription-auth/credentialAccess.ts
@@ -1,3 +1,4 @@
+import { SubscriptionAccountState } from "./accountState.ts";
import * as Predicate from "effect/Predicate";
import * as NodeCrypto from "node:crypto";
import * as Effect from "effect/Effect";
@@ -9,6 +10,10 @@ import {
type SubscriptionProviderId,
oauthFailureKind,
credentialKey,
+ accountScope,
+ accountIdForKey,
+ DEFAULT_ACCOUNT_ID,
+ isDefaultScope,
credentialAt,
refreshedCredential,
runRefresh,
@@ -16,6 +21,7 @@ import {
import { SubscriptionHealthService } from "./healthService.ts";
export class SubscriptionCredentialAccess {
+ private readonly accounts: SubscriptionAccountState;
private readonly clock: Clock.Clock;
private readonly reload: () => Effect.Effect<void>;
private readonly store: SubscriptionCredentialStore;
@@ -23,9 +29,11 @@ export class SubscriptionCredentialAccess {
constructor(
store: SubscriptionCredentialStore,
healthService: SubscriptionHealthService,
+ accounts: SubscriptionAccountState,
clock: Clock.Clock,
reload: () => Effect.Effect<void>,
) {
+ this.accounts = accounts;
this.clock = clock;
this.reload = reload;
this.store = store;
@@ -51,8 +59,9 @@ export class SubscriptionCredentialAccess {
async getAccessToken(
provider: SubscriptionProviderId,
instanceId?: string,
+ threadId?: string,
): Promise<string | undefined> {
- const key = credentialKey(provider, instanceId);
+ const key = this.accounts.servingKey(provider, instanceId, threadId);
const credential = credentialAt(this.data, key);
if (!credential) return undefined;
@@ -67,7 +76,7 @@ export class SubscriptionCredentialAccess {
if (inFlight) return inFlight;
- const refresh = this.refreshCredential(provider, credential, instanceId).finally(() => {
+ const refresh = this.refreshCredential(provider, credential, key).finally(() => {
this.refreshInFlight.delete(key);
});
@@ -94,8 +103,11 @@ export class SubscriptionCredentialAccess {
async getPlanAccess(
provider: SubscriptionProviderId,
): Promise<{ readonly accessToken: string | null; readonly accountId: string } | undefined> {
- const key = credentialKey(provider);
await this.reloadAsync();
+
+ const key = this.accounts.liveKey(provider);
+
+ const scope = accountScope(accountIdForKey(provider, key) ?? DEFAULT_ACCOUNT_ID);
const credential = credentialAt(this.data, key);
if (
@@ -115,7 +127,7 @@ export class SubscriptionCredentialAccess {
});
}
- const accessToken = await this.getPlanAccessToken(provider).catch(() => undefined);
+ const accessToken = await this.getPlanAccessToken(provider, scope).catch(() => undefined);
await this.reloadAsync();
const current = credentialAt(this.data, key);
@@ -135,27 +147,38 @@ export class SubscriptionCredentialAccess {
getApiKeyCredential(
provider: SubscriptionProviderId,
instanceId?: string,
+ threadId?: string,
): ApiKeyCredential | undefined {
- const credential = credentialAt(this.data, credentialKey(provider, instanceId));
+ const credential = credentialAt(
+ this.data,
+ this.accounts.servingKey(provider, instanceId, threadId),
+ );
return credential?.type === "api-key" ? credential : undefined;
}
+ /** The OAuth credential and fixed scope to use when refreshing it. */
getOAuthCredential(
provider: SubscriptionProviderId,
instanceId?: string,
- ): OAuthCredential | undefined {
- const credential = credentialAt(this.data, credentialKey(provider, instanceId));
+ threadId?: string,
+ ): (OAuthCredential & { readonly scope?: string }) | undefined {
+ const scope = this.pinnedScope(provider, instanceId, threadId);
+ const credential = credentialAt(this.data, credentialKey(provider, scope));
- return credential?.type === "oauth" ? credential : undefined;
+ return credential?.type === "oauth"
+ ? { ...credential, ...(scope !== undefined ? { scope } : {}) }
+ : undefined;
}
async getOpenAICodexAccess(
instanceId?: string,
+ threadId?: string,
): Promise<{ readonly accessToken: string; readonly accountId: string } | undefined> {
await this.reloadAsync();
- const accessToken = await this.getAccessToken("openai-codex", instanceId);
- const credential = credentialAt(this.data, credentialKey("openai-codex", instanceId));
+ const scope = this.pinnedScope("openai-codex", instanceId, threadId);
+ const accessToken = await this.getAccessToken("openai-codex", scope);
+ const credential = credentialAt(this.data, credentialKey("openai-codex", scope));
const accountId = credential?.type === "oauth" ? credential.accountId : undefined;
return accessToken && Predicate.isString(accountId) && accountId.length > 0
@@ -165,13 +188,15 @@ export class SubscriptionCredentialAccess {
async getKimiForCodingAccess(
instanceId?: string,
+ threadId?: string,
): Promise<
| { readonly accessToken: string; readonly deviceId?: string; readonly baseUrl?: string }
| undefined
> {
await this.reloadAsync();
- const accessToken = await this.getAccessToken("kimi-for-coding", instanceId);
- const credential = credentialAt(this.data, credentialKey("kimi-for-coding", instanceId));
+ const scope = this.pinnedScope("kimi-for-coding", instanceId, threadId);
+ const accessToken = await this.getAccessToken("kimi-for-coding", scope);
+ const credential = credentialAt(this.data, credentialKey("kimi-for-coding", scope));
if (credential?.type === "api-key" && accessToken) {
return { accessToken, ...(credential.baseUrl ? { baseUrl: credential.baseUrl } : {}) };
@@ -182,13 +207,23 @@ export class SubscriptionCredentialAccess {
return accessToken && isKimiCodingDeviceId(deviceId) ? { accessToken, deviceId } : undefined;
}
+ /** One account for a read that touches the credential twice, so both reads agree. */
+ private pinnedScope(
+ provider: SubscriptionProviderId,
+ instanceId?: string,
+ threadId?: string,
+ ): string | undefined {
+ if (!isDefaultScope(provider, instanceId)) return instanceId;
+ const key = this.accounts.servingKey(provider, instanceId, threadId);
+
+ return accountScope(accountIdForKey(provider, key) ?? DEFAULT_ACCOUNT_ID);
+ }
+
private async refreshCredential(
provider: SubscriptionProviderId,
credential: OAuthCredential,
- instanceId?: string,
+ key: string,
): Promise<string | undefined> {
- const key = credentialKey(provider, instanceId);
-
try {
const refreshed = await this.runRefresh(provider, credential);
await this.reloadAsync();
@@ -219,11 +254,10 @@ export class SubscriptionCredentialAccess {
} catch (cause) {
// Refresh failed — the user must re-connect. Keep the stored credential
// so status still shows which account was linked.
- this.healthService.recordOAuthFailure(
- provider,
+ this.healthService.recordOAuthFailureForKey(
+ key,
cause instanceof Error ? cause.message : "The provider rejected the token refresh.",
oauthFailureKind(cause),
- instanceId,
);
return undefined;
diff --git a/apps/server/src/subscription-auth/healthService.ts b/apps/server/src/subscription-auth/healthService.ts
index ee240988a..df73228bb 100644
--- a/apps/server/src/subscription-auth/healthService.ts
+++ b/apps/server/src/subscription-auth/healthService.ts
@@ -1,3 +1,5 @@
+import * as Schema from "effect/Schema";
+import { isAccountLimitMessage, limitRetryAt } from "./accountLimits.ts";
import { decodeProviderHealth } from "./persistedSchemas.ts";
import * as NodeFS from "node:fs";
import type * as Path from "effect/Path";
@@ -23,10 +25,24 @@ import {
oauthFailureKind,
credentialKey,
credentialAt,
+ defaultInstanceByProvider,
refreshedCredential,
runRefresh,
} from "./serviceTypes.ts";
+/** Changes on every atomic rewrite: each write renames a fresh file into place. */
+export function fileVersion(path: string): string | undefined {
+ try {
+ const stat = NodeFS.statSync(path);
+
+ return `${stat.ino}:${stat.mtimeMs}:${stat.size}`;
+ } catch {
+ return undefined;
+ }
+}
+
+const decodeAccountOrder = Schema.decodeUnknownSync(Schema.Json);
+
export class SubscriptionHealthService {
private readonly clock: Clock.Clock;
private readonly reload: () => Effect.Effect<void>;
@@ -59,6 +75,7 @@ export class SubscriptionHealthService {
public readonly healthPath: string;
public health: ProviderHealthData = {};
+ public healthVersion: string | undefined;
public readonly healthChecks = new Map<string, Promise<void>>();
@@ -66,7 +83,15 @@ export class SubscriptionHealthService {
public readonly checkHealthOnConnect: boolean;
+ public readAccountOrder(filePath: string) {
+ return NodeFS.existsSync(filePath)
+ ? decodeAccountOrder(JSON.parse(NodeFS.readFileSync(filePath, "utf-8")))
+ : {};
+ }
+
public reloadHealth(): void {
+ this.healthVersion = fileVersion(this.healthPath);
+
if (!NodeFS.existsSync(this.healthPath)) {
this.health = {};
@@ -98,6 +123,7 @@ export class SubscriptionHealthService {
public saveHealth(): void {
this.writeSecureJson(this.healthPath, this.health);
+ this.healthVersion = fileVersion(this.healthPath);
}
recordRequestSuccess(
@@ -122,18 +148,42 @@ export class SubscriptionHealthService {
this.recordHealthSuccess(`provider:${instanceId}`, at);
}
+ public recordAccountFailure(
+ key: string,
+ message: string,
+ at: string,
+ failureKind: "request" | "revoked",
+ ): void {
+ this.reloadHealth();
+ const previous = this.health[key];
+
+ const revoked =
+ previous?.failureKind === "revoked" &&
+ previous.lastFailedRequest !== undefined &&
+ (previous.lastSuccessfulRequestAt === undefined ||
+ previous.lastFailedRequest.at >= previous.lastSuccessfulRequestAt);
+
+ this.recordHealthFailure(key, message, at, revoked ? "revoked" : failureKind);
+
+ if (failureKind !== "request" || !isAccountLimitMessage(message)) return;
+ this.health[key] = { ...this.health[key], nextRetryAt: limitRetryAt(message, at) };
+ this.saveHealth();
+ }
+
public recordHealthSuccess(key: string, at: string): void {
this.reloadHealth();
const previous = this.health[key];
- const {
- nextRetryAt: _nextRetryAt,
- lastCredentialProbeFailure: _probeFailure,
- ...rest
- } = previous ?? {};
+ const { nextRetryAt, lastCredentialProbeFailure: _probeFailure, ...rest } = previous ?? {};
+
+ // A limit cooldown runs out on its own clock. A success from a request that
+ // was already in flight, or a passing check, does not end it early.
+ const coolingDown =
+ nextRetryAt !== undefined && Date.parse(nextRetryAt) > this.clock.currentTimeMillisUnsafe();
this.health[key] = {
...rest,
+ ...(coolingDown ? { nextRetryAt } : {}),
lastSuccessfulRequestAt: at,
healthTest: { status: "passed", checkedAt: at },
};
@@ -572,7 +622,14 @@ export class SubscriptionHealthService {
failureKind: "request" | "revoked" = "request",
instanceId?: string,
): void {
- const key = credentialKey(provider, instanceId);
+ this.recordOAuthFailureForKey(credentialKey(provider, instanceId), message, failureKind);
+ }
+
+ public recordOAuthFailureForKey(
+ key: string,
+ message: string,
+ failureKind: "request" | "revoked",
+ ): void {
const checkedAt = DateTime.formatIso(DateTime.makeUnsafe(this.clock.currentTimeMillisUnsafe()));
this.reloadHealth();
const { nextRetryAt: _nextRetryAt, ...previous } = this.health[key] ?? {};
@@ -585,8 +642,22 @@ export class SubscriptionHealthService {
this.saveHealth();
}
+ /**
+ * Drops a usage limit recorded only on the provider's default instance once
+ * one of its backup accounts is removed or signs in again, so the provider
+ * is not left blocked by a limit no remaining account carries.
+ */
+ public clearProviderLimit(provider: SubscriptionProviderId, key: string): void {
+ if (key.startsWith("instance:")) return;
+ const providerKey = `provider:${defaultInstanceByProvider[provider]}`;
+ const failure = this.health[providerKey]?.lastFailedRequest;
+
+ if (failure !== undefined && isAccountLimitMessage(failure.message))
+ delete this.health[providerKey];
+ }
+
public clearImageHealth(provider: SubscriptionProviderId, instanceId?: string): void {
- if (instanceId !== undefined) return;
+ if (credentialKey(provider, instanceId) !== provider) return;
if (provider === "openai-codex") delete this.health["image:chatgpt"];
diff --git a/apps/server/src/subscription-auth/loginStart.ts b/apps/server/src/subscription-auth/loginStart.ts
new file mode 100644
index 000000000..a81923ecf
--- /dev/null
+++ b/apps/server/src/subscription-auth/loginStart.ts
@@ -0,0 +1,141 @@
+import * as NodeCrypto from "node:crypto";
+import type { SubscriptionAuthStartInput } from "@akeru/contracts";
+import { startAnthropicLogin } from "./providers/anthropic.ts";
+import { startCodexDeviceLogin } from "./providers/openaiCodex.ts";
+import { startKimiDeviceLogin } from "./providers/kimi.ts";
+import { startXAIDeviceLogin } from "./providers/xai.ts";
+import {
+ decodeBaseUrl,
+ OPENCODE_GO_AUTH_URL,
+ PENDING_LOGIN_CAP,
+ type BoundLogin,
+ type StartedLogin,
+ type SubscriptionProviderId,
+} from "./serviceTypes.ts";
+
+interface LoginStartContext {
+ readonly reloadAsync: () => Promise<void>;
+ readonly loginScope: (
+ provider: SubscriptionProviderId,
+ options: Omit<SubscriptionAuthStartInput, "provider">,
+ ) => string;
+ readonly pendingLogins: Map<string, BoundLogin>;
+ readonly savePending: () => void;
+}
+
+export async function startSubscriptionLogin(
+ context: LoginStartContext,
+ provider: SubscriptionProviderId,
+ options: Omit<SubscriptionAuthStartInput, "provider"> = {},
+): Promise<StartedLogin> {
+ await context.reloadAsync();
+ const authMode = options.authMode ?? (provider === "opencode-go" ? "api-key" : "oauth");
+
+ if (options.baseUrl !== undefined && authMode !== "api-key") {
+ throw new Error("Custom base URLs require API-key authentication. Select API key first.");
+ }
+
+ if (options.baseUrl !== undefined && provider === "xai") {
+ throw new Error("The Grok bridge does not support custom base URLs. Use the default endpoint.");
+ }
+
+ if (authMode === "oauth" && provider === "opencode-go") {
+ throw new Error("OpenCode Go requires an API key. Select API key first.");
+ }
+
+ const baseUrl =
+ options.baseUrl === undefined ? undefined : decodeBaseUrl(options.baseUrl).replace(/\/+$/, "");
+
+ const loginId = NodeCrypto.randomUUID();
+ const binding = { instanceId: context.loginScope(provider, options) };
+ let started: StartedLogin;
+
+ if (authMode === "api-key") {
+ context.pendingLogins.set(loginId, {
+ provider,
+ authMode,
+ ...binding,
+ ...(baseUrl ? { baseUrl } : {}),
+ });
+ started = {
+ loginId,
+ provider,
+ url: provider === "opencode-go" ? OPENCODE_GO_AUTH_URL : "",
+ instructions: "Paste the provider API key.",
+ completion: "paste",
+ };
+ } else
+ switch (provider) {
+ case "anthropic": {
+ const { url, verifier } = await startAnthropicLogin();
+ context.pendingLogins.set(loginId, { provider, verifier, ...binding });
+ started = { loginId, provider, url, completion: "paste" };
+ break;
+ }
+
+ case "openai-codex": {
+ const pending = await startCodexDeviceLogin();
+ context.pendingLogins.set(loginId, { provider, pending, ...binding });
+ started = {
+ loginId,
+ provider,
+ url: pending.url,
+ userCode: pending.userCode,
+ instructions: pending.instructions,
+ completion: "poll",
+ };
+ break;
+ }
+
+ case "xai": {
+ const pending = await startXAIDeviceLogin();
+ context.pendingLogins.set(loginId, { provider, pending, ...binding });
+ started = {
+ loginId,
+ provider,
+ url: pending.url,
+ userCode: pending.userCode,
+ instructions: pending.instructions,
+ completion: "poll",
+ };
+ break;
+ }
+
+ case "kimi-for-coding": {
+ const pending = await startKimiDeviceLogin();
+ context.pendingLogins.set(loginId, { provider, pending, ...binding });
+ started = {
+ loginId,
+ provider,
+ url: pending.url,
+ userCode: pending.userCode,
+ instructions: pending.instructions,
+ completion: "poll",
+ };
+ break;
+ }
+
+ case "opencode-go": {
+ context.pendingLogins.set(loginId, { provider, ...binding });
+ started = {
+ loginId,
+ provider,
+ url: OPENCODE_GO_AUTH_URL,
+ instructions: "Subscribe to OpenCode Go, copy the API key, then paste it here.",
+ completion: "paste",
+ };
+ break;
+ }
+ }
+
+ // Drop the oldest abandoned login rather than growing without bound.
+ if (context.pendingLogins.size > PENDING_LOGIN_CAP) {
+ const oldest = context.pendingLogins.keys().next().value;
+
+ if (oldest !== undefined) context.pendingLogins.delete(oldest);
+ }
+
+ context.savePending();
+
+ return started;
+}
diff --git a/apps/server/src/subscription-auth/plan.ts b/apps/server/src/subscription-auth/plan.ts
new file mode 100644
index 000000000..a72ffbcef
--- /dev/null
+++ b/apps/server/src/subscription-auth/plan.ts
@@ -0,0 +1,67 @@
+import * as Predicate from "effect/Predicate";
+import * as Schema from "effect/Schema";
+/**
+ * Subscription tiers as people know them ("Pro", "Max 20x"), read from what
+ * each provider reports at sign-in. Unknown values stay unknown rather than guessed.
+ */
+
+const CODEX_PLANS = new Map([
+ ["free", "Free"],
+ ["plus", "Plus"],
+ ["pro", "Pro"],
+ ["prolite", "Pro Lite"],
+ ["team", "Team"],
+ ["business", "Business"],
+ ["enterprise", "Enterprise"],
+ ["edu", "Edu"],
+]);
+
+/** The ChatGPT tier from a Codex token's `chatgpt_plan_type` claim. */
+export function codexPlanLabel(value: string | undefined): string | undefined {
+ return Predicate.isString(value) ? CODEX_PLANS.get(value.toLowerCase()) : undefined;
+}
+
+export const ClaudeProfile = Schema.Struct({
+ account: Schema.optional(
+ Schema.Struct({
+ has_claude_max: Schema.optional(Schema.Unknown),
+ has_claude_pro: Schema.optional(Schema.Unknown),
+ }),
+ ),
+ organization: Schema.optional(
+ Schema.Struct({
+ organization_type: Schema.optional(Schema.Unknown),
+ rate_limit_tier: Schema.optional(Schema.Unknown),
+ }),
+ ),
+});
+
+type ClaudeProfile = typeof ClaudeProfile.Type;
+
+/** The Claude tier from the OAuth profile: Max 20x, Max 5x, Max, Pro, Team, or Enterprise. */
+export function claudePlanLabel(profile: ClaudeProfile): string | undefined {
+ const tier = profile.organization?.rate_limit_tier;
+
+ if (Predicate.isString(tier)) {
+ if (tier.includes("max_20x")) return "Max 20x";
+
+ if (tier.includes("max_5x")) return "Max 5x";
+ }
+
+ switch (profile.organization?.organization_type) {
+ case "claude_max":
+ return "Max";
+ case "claude_pro":
+ return "Pro";
+ case "claude_team":
+ return "Team";
+ case "claude_enterprise":
+ return "Enterprise";
+ }
+
+ if (profile.account?.has_claude_max === true) return "Max";
+
+ if (profile.account?.has_claude_pro === true) return "Pro";
+
+ return undefined;
+}
diff --git a/apps/server/src/subscription-auth/providerStatuses.ts b/apps/server/src/subscription-auth/providerStatuses.ts
index ed68891bd..f9ab330c1 100644
--- a/apps/server/src/subscription-auth/providerStatuses.ts
+++ b/apps/server/src/subscription-auth/providerStatuses.ts
@@ -1,3 +1,5 @@
+import type { SubscriptionAccountState } from "./accountState.ts";
+import { codexPlanFromToken } from "./providers/openaiCodex.ts";
import type { BotId, ProviderInstanceId } from "@akeru/contracts";
import * as DateTime from "effect/DateTime";
import * as Predicate from "effect/Predicate";
@@ -8,15 +10,18 @@ import {
lastGoodWarning,
storeErrorStatus,
credentialKey,
+ accountScope,
credentialAt,
type SubscriptionProviderId,
type ProviderHealthData,
type ProviderStatus,
} from "./serviceTypes.ts";
-export function providerStatuses(
- state: CredentialStoreState,
+export function statusForKey(
+ credentialState: CredentialStoreState,
healthData: ProviderHealthData,
+ provider: SubscriptionProviderId,
+ key: string,
dependentBots: ReadonlyArray<{
readonly id: BotId;
readonly name: string;
@@ -24,8 +29,8 @@ export function providerStatuses(
}>,
now: number,
instanceId?: ProviderInstanceId,
-): ProviderStatus[] {
- const { data, loadError, loadErrorAt, servingLastGood } = state;
+): ProviderStatus {
+ const { data, loadError, loadErrorAt, servingLastGood } = credentialState;
const damagedAt = loadErrorAt ?? DateTime.formatIso(DateTime.makeUnsafe(now));
const credentialWarning =
@@ -33,89 +38,138 @@ export function providerStatuses(
? { at: damagedAt, message: lastGoodWarning(loadError) }
: undefined;
- return SUBSCRIPTION_PROVIDER_IDS.map((provider) => {
- if (loadError && !servingLastGood) {
- return storeErrorStatus(
- provider,
- { at: damagedAt, message: loadError.message },
- dependentBots,
- );
- }
-
- const key = credentialKey(provider, instanceId);
- const credential = credentialAt(data, key);
- const health = healthData[key];
- const expired = credential?.type === "oauth" && credential.expires <= now;
-
- const failedAfterSuccess =
- health?.lastFailedRequest !== undefined &&
- (health.lastSuccessfulRequestAt === undefined ||
- health.lastFailedRequest.at >= health.lastSuccessfulRequestAt);
-
- const recovered =
- health?.lastSuccessfulRequestAt !== undefined &&
- health.lastFailedRequest !== undefined &&
- health.lastSuccessfulRequestAt > health.lastFailedRequest.at;
-
- const checking =
- health?.healthCheckStartedAt !== undefined &&
- now - Date.parse(health.healthCheckStartedAt) < HEALTH_CHECK_STALE_MS;
-
- const state = !credential
- ? "missing"
- : failedAfterSuccess
- ? health?.failureKind === "revoked"
- ? "revoked"
+ if (loadError && !servingLastGood) {
+ return storeErrorStatus(provider, { at: damagedAt, message: loadError.message }, dependentBots);
+ }
+
+ const credential = credentialAt(data, key);
+ const health = healthData[key];
+ const expired = credential?.type === "oauth" && credential.expires <= now;
+
+ const failedAfterSuccess =
+ health?.lastFailedRequest !== undefined &&
+ (health.lastSuccessfulRequestAt === undefined ||
+ health.lastFailedRequest.at >= health.lastSuccessfulRequestAt);
+
+ const recovered =
+ health?.lastSuccessfulRequestAt !== undefined &&
+ health.lastFailedRequest !== undefined &&
+ health.lastSuccessfulRequestAt > health.lastFailedRequest.at;
+
+ const checking =
+ health?.healthCheckStartedAt !== undefined &&
+ now - Date.parse(health.healthCheckStartedAt) < HEALTH_CHECK_STALE_MS;
+
+ const state = !credential
+ ? "missing"
+ : failedAfterSuccess
+ ? health?.failureKind === "revoked"
+ ? "revoked"
+ : health?.lastSuccessfulRequestAt
+ ? "failed"
+ : "failed-first-request"
+ : expired
+ ? "expired"
+ : recovered
+ ? "recovered"
: health?.lastSuccessfulRequestAt
- ? "failed"
- : "failed-first-request"
- : expired
- ? "expired"
- : recovered
- ? "recovered"
- : health?.lastSuccessfulRequestAt
- ? "healthy"
- : "detected";
-
- const accountLabel =
- credential?.type === "oauth"
- ? [credential.email, credential.accountId].find(
- (value): value is string => Predicate.isString(value) && value.trim().length > 0,
- )
- : undefined;
-
- return {
+ ? "healthy"
+ : "detected";
+
+ const accountLabel =
+ credential?.type === "oauth"
+ ? [credential.email, credential.accountId].find(
+ (value): value is string => Predicate.isString(value) && value.trim().length > 0,
+ )
+ : undefined;
+
+ const plan =
+ credential?.type === "oauth"
+ ? ((Predicate.isString(credential.plan) ? credential.plan : undefined) ??
+ (provider === "openai-codex" ? codexPlanFromToken(credential.access) : undefined))
+ : undefined;
+
+ return {
+ provider,
+ ...(plan ? { plan } : {}),
+ ...(instanceId ? { instanceId } : {}),
+ connected: credential !== undefined,
+ ...(accountLabel ? { accountLabel } : {}),
+ ...(credential ? { authMode: credential.type } : {}),
+ ...(credential?.type === "api-key" && credential.baseUrl
+ ? { baseUrl: credential.baseUrl }
+ : {}),
+ ...(credential?.type === "oauth" ? { expiresAt: credential.expires } : {}),
+ health: state,
+ ...(credential && checking ? { healthChecking: true } : {}),
+ ...(health?.lastSuccessfulRequestAt
+ ? { lastSuccessfulRequestAt: health.lastSuccessfulRequestAt }
+ : {}),
+ ...(health?.lastFailedRequest ? { lastFailedRequest: health.lastFailedRequest } : {}),
+ ...(health?.nextRetryAt ? { nextRetryAt: health.nextRetryAt } : {}),
+ ...(credentialWarning ? { credentialWarning } : {}),
+ reconnectAction:
+ credential?.type === "api-key" || provider === "opencode-go"
+ ? credential
+ ? "Replace API key"
+ : "Connect API key"
+ : credential
+ ? "Reconnect account"
+ : "Connect account",
+ healthTest: health?.healthTest ?? { status: "not-run" },
+ ...(health?.oauthCheck ? { oauthCheck: health.oauthCheck } : {}),
+ dependentBots: dependentBots.flatMap((bot) =>
+ bot.provider === provider ? [{ id: bot.id, name: bot.name }] : [],
+ ),
+ dependentRoutines: [],
+ };
+}
+
+export function providerStatuses(
+ state: CredentialStoreState,
+ healthData: ProviderHealthData,
+ dependentBots: ReadonlyArray<{
+ readonly id: BotId;
+ readonly name: string;
+ readonly provider: SubscriptionProviderId;
+ }>,
+ now: number,
+ instanceId?: ProviderInstanceId,
+ keyForProvider: (provider: SubscriptionProviderId) => string = (provider) =>
+ credentialKey(provider, instanceId),
+): ProviderStatus[] {
+ return SUBSCRIPTION_PROVIDER_IDS.map((provider) =>
+ statusForKey(
+ state,
+ healthData,
provider,
- ...(instanceId ? { instanceId } : {}),
- connected: credential !== undefined,
- ...(accountLabel ? { accountLabel } : {}),
- ...(credential ? { authMode: credential.type } : {}),
- ...(credential?.type === "api-key" && credential.baseUrl
- ? { baseUrl: credential.baseUrl }
- : {}),
- ...(credential?.type === "oauth" ? { expiresAt: credential.expires } : {}),
- health: state,
- ...(credential && checking ? { healthChecking: true } : {}),
- ...(health?.lastSuccessfulRequestAt
- ? { lastSuccessfulRequestAt: health.lastSuccessfulRequestAt }
- : {}),
- ...(health?.lastFailedRequest ? { lastFailedRequest: health.lastFailedRequest } : {}),
- ...(health?.nextRetryAt ? { nextRetryAt: health.nextRetryAt } : {}),
- ...(credentialWarning ? { credentialWarning } : {}),
- reconnectAction:
- credential?.type === "api-key" || provider === "opencode-go"
- ? credential
- ? "Replace API key"
- : "Connect API key"
- : credential
- ? "Reconnect account"
- : "Connect account",
- healthTest: health?.healthTest ?? { status: "not-run" },
- ...(health?.oauthCheck ? { oauthCheck: health.oauthCheck } : {}),
- dependentBots: dependentBots.flatMap((bot) =>
- bot.provider === provider ? [{ id: bot.id, name: bot.name }] : [],
- ),
- dependentRoutines: [],
- };
+ keyForProvider(provider),
+ dependentBots,
+ now,
+ instanceId,
+ ),
+ );
+}
+
+export function linkedAccountStatuses(
+ state: CredentialStoreState,
+ healthData: ProviderHealthData,
+ accounts: SubscriptionAccountState,
+ now: number,
+): ProviderStatus[] {
+ if (state.loadError && !state.servingLastGood) return [];
+
+ return SUBSCRIPTION_PROVIDER_IDS.flatMap((provider) => {
+ const active = accounts.activeAccountKey(provider, now);
+
+ return accounts.linkedAccountIds(provider).map((accountId) => {
+ const key = credentialKey(provider, accountScope(accountId));
+
+ return {
+ ...statusForKey(state, healthData, provider, key, [], now),
+ accountId,
+ active: key === active,
+ };
+ });
});
}
diff --git a/apps/server/src/subscription-auth/providers/anthropic.test.ts b/apps/server/src/subscription-auth/providers/anthropic.test.ts
index b6acc9ed1..ccafede38 100644
--- a/apps/server/src/subscription-auth/providers/anthropic.test.ts
+++ b/apps/server/src/subscription-auth/providers/anthropic.test.ts
@@ -28,6 +28,39 @@ describe("Anthropic OAuth", () => {
}),
);
+ it.effect("records the Claude tier from the account profile", () =>
+ Effect.gen(function* () {
+ const { client, requests } = scriptedHttpClient((request) =>
+ request.url.endsWith("/api/oauth/profile")
+ ? Response.json({ organization: { rate_limit_tier: "default_claude_max_20x" } })
+ : Response.json(tokens),
+ );
+
+ const result = yield* AnthropicOAuth.refreshToken("refresh").pipe(
+ Effect.provideService(HttpClient.HttpClient, client),
+ );
+
+ expect(result.plan).toBe("Max 20x");
+ expect(requests[1]?.headers["authorization"]).toBe("Bearer access");
+ }),
+ );
+
+ it.effect("still signs in when the profile is unavailable", () =>
+ Effect.gen(function* () {
+ const { client } = scriptedHttpClient((request) =>
+ request.url.endsWith("/api/oauth/profile")
+ ? new Response("nope", { status: 500 })
+ : Response.json(tokens),
+ );
+
+ const result = yield* AnthropicOAuth.refreshToken("refresh").pipe(
+ Effect.provideService(HttpClient.HttpClient, client),
+ );
+
+ expect(result).toEqual({ access: "access", refresh: "refresh", expires: 3_300_000 });
+ }),
+ );
+
it.effect("rejects a mismatched state before any request", () =>
Effect.gen(function* () {
const { client, requests } = scriptedHttpClient(() => Response.json(tokens));
diff --git a/apps/server/src/subscription-auth/providers/anthropic.ts b/apps/server/src/subscription-auth/providers/anthropic.ts
index d6b3315fd..6187d0c48 100644
--- a/apps/server/src/subscription-auth/providers/anthropic.ts
+++ b/apps/server/src/subscription-auth/providers/anthropic.ts
@@ -27,6 +27,7 @@ import {
withOAuthTimeout,
} from "../oauthHttp.ts";
import { generatePKCE } from "../pkce.ts";
+import { ClaudeProfile, claudePlanLabel } from "../plan.ts";
import type { OAuthCredentials } from "../types.ts";
const decode = (s: string) => atob(s);
@@ -45,6 +46,10 @@ const REFRESH_SKEW_MS = 5 * 60 * 1000;
const REQUEST_TIMEOUT = "15 seconds";
+const PROFILE_URL = "https://api.anthropic.com/api/oauth/profile";
+
+const PROFILE_TIMEOUT = "5 seconds";
+
const TokenResponse = Schema.Struct({
access_token: Schema.NonEmptyString,
refresh_token: Schema.NonEmptyString,
@@ -90,14 +95,34 @@ const requestTokens = Effect.fn("anthropic.requestTokens")(function* (
);
const now = yield* Clock.currentTimeMillis;
+ const plan = yield* readPlan(tokens.access_token);
return {
+ ...(plan ? { plan } : {}),
refresh: tokens.refresh_token,
access: tokens.access_token,
expires: now + tokens.expires_in * 1000 - REFRESH_SKEW_MS,
} satisfies OAuthCredentials;
});
+const readPlan = (accessToken: string) =>
+ sendOAuthRequest(
+ "Anthropic profile",
+ HttpClientRequest.get(PROFILE_URL).pipe(
+ HttpClientRequest.setHeaders({
+ Authorization: `Bearer ${accessToken}`,
+ "anthropic-beta": "oauth-2025-04-20",
+ }),
+ ),
+ ).pipe(
+ Effect.flatMap(ensureOk("Anthropic profile")),
+ Effect.flatMap(responseJson),
+ Effect.flatMap(decodeOAuthBody(ClaudeProfile, "Anthropic profile: invalid response")),
+ Effect.map(claudePlanLabel),
+ withOAuthTimeout("Anthropic profile", PROFILE_TIMEOUT),
+ Effect.orElseSucceed(() => undefined),
+ );
+
/**
* Complete an Anthropic login: parse the pasted authorization input
* (full URL, `code#state`, or query string), validate its state, and exchange
diff --git a/apps/server/src/subscription-auth/providers/openaiCodex.test.ts b/apps/server/src/subscription-auth/providers/openaiCodex.test.ts
index 327711a30..dbc221b16 100644
--- a/apps/server/src/subscription-auth/providers/openaiCodex.test.ts
+++ b/apps/server/src/subscription-auth/providers/openaiCodex.test.ts
@@ -110,6 +110,29 @@ describe("OpenAI Codex device login", () => {
}),
);
+ it.effect("records the ChatGPT tier from the token claims", () =>
+ Effect.gen(function* () {
+ const { client } = scriptedHttpClient((request) =>
+ request.url.endsWith("/deviceauth/token")
+ ? Response.json({ authorization_code: "code", code_verifier: "verifier" })
+ : Response.json(
+ tokens({
+ "https://api.openai.com/auth": {
+ chatgpt_account_id: "acct",
+ chatgpt_plan_type: "pro",
+ },
+ }),
+ ),
+ );
+
+ const result = yield* CodexOAuth.pollDeviceLogin(pending).pipe(
+ Effect.provideService(HttpClient.HttpClient, client),
+ );
+
+ expect(result).toMatchObject({ status: "complete", credentials: { plan: "Pro" } });
+ }),
+ );
+
it.effect("fails when no token carries an account id", () =>
Effect.gen(function* () {
const { client } = scriptedHttpClient((request) =>
diff --git a/apps/server/src/subscription-auth/providers/openaiCodex.ts b/apps/server/src/subscription-auth/providers/openaiCodex.ts
index f367df693..ffdf3fe1a 100644
--- a/apps/server/src/subscription-auth/providers/openaiCodex.ts
+++ b/apps/server/src/subscription-auth/providers/openaiCodex.ts
@@ -27,6 +27,7 @@ import {
type SubscriptionAuthRequestError,
withOAuthTimeout,
} from "../oauthHttp.ts";
+import { codexPlanLabel } from "../plan.ts";
import type { OAuthCredentials } from "../types.ts";
const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
@@ -88,6 +89,28 @@ function accountIdFromJwt(token: string | undefined): string | undefined {
);
}
+/** The ChatGPT tier from a token's `chatgpt_plan_type` claim; works on id and access tokens. */
+export function codexPlanFromToken(token: string | undefined): string | undefined {
+ const payload = token?.split(".");
+
+ if (payload?.length !== 3) return undefined;
+
+ return decodeJwtClaims(Buffer.from(payload[1] ?? "", "base64url").toString("utf8")).pipe(
+ Option.map((claims) => {
+ const auth = claims[JWT_CLAIM_PATH];
+
+ return codexPlanLabel(
+ Predicate.isObjectKeyword(auth) &&
+ "chatgpt_plan_type" in auth &&
+ Predicate.isString(auth.chatgpt_plan_type)
+ ? auth.chatgpt_plan_type
+ : undefined,
+ );
+ }),
+ Option.getOrUndefined,
+ );
+}
+
const TokenResponse = Schema.Struct({
id_token: Schema.optional(Schema.String),
access_token: Schema.NonEmptyString,
@@ -125,8 +148,10 @@ const credentialsFromTokenResponse = Effect.fn("codex.credentialsFromTokenRespon
}
const now = yield* Clock.currentTimeMillis;
+ const plan = codexPlanFromToken(tokens.id_token) ?? codexPlanFromToken(tokens.access_token);
return {
+ ...(plan ? { plan } : {}),
access: tokens.access_token,
refresh: tokens.refresh_token,
expires: now + (tokens.expires_in ?? DEFAULT_TOKEN_EXPIRES_IN_SECONDS) * 1000,
diff --git a/apps/server/src/subscription-auth/service.accounts.test.ts b/apps/server/src/subscription-auth/service.accounts.test.ts
new file mode 100644
index 000000000..2453029c6
--- /dev/null
+++ b/apps/server/src/subscription-auth/service.accounts.test.ts
@@ -0,0 +1,440 @@
+import { fixture } from "./testUtils/subscriptionAuthStorage.ts";
+import * as NodeFS from "node:fs";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { makeTestSubscriptionAuthService } from "./testUtils/subscriptionAuthService.ts";
+
+import { accountScope, isAccountLimitMessage, limitRetryAt } from "./service.ts";
+
+describe("linked subscription accounts", () => {
+ it("uses linked accounts in priority order and skips one that hit a limit", async () => {
+ const { authPath } = fixture();
+ const service = await makeTestSubscriptionAuthService(authPath);
+ const first = await service.startLogin("openai-codex", { authMode: "api-key" });
+ expect(await service.completeLogin(first.loginId, "first-key")).toEqual({
+ status: "connected",
+ });
+
+ const second = await service.startLogin("openai-codex", {
+ authMode: "api-key",
+ addAccount: true,
+ });
+
+ expect(await service.completeLogin(second.loginId, "second-key")).toEqual({
+ status: "connected",
+ });
+ const [defaultId, addedId] = service.linkedAccountIds("openai-codex");
+ expect(defaultId).toBe("default");
+ expect(addedId).toMatch(/^acct-[a-z0-9]+$/);
+ expect(await service.getAccessToken("openai-codex")).toBe("first-key");
+
+ service.recordRequestFailure(
+ "openai-codex",
+ "You've hit your usage limit. Try again in 2 hours.",
+ new Date().toISOString(),
+ );
+ expect(await service.getAccessToken("openai-codex")).toBe("second-key");
+ expect(
+ service
+ .linkedAccountStatuses()
+ .filter((status) => status.provider === "openai-codex")
+ .map((status) => [status.accountId, status.active]),
+ ).toEqual([
+ ["default", false],
+ [addedId, true],
+ ]);
+ // An ordinary failure does not bench the account.
+ service.recordRequestFailure("openai-codex", "socket hang up", new Date().toISOString());
+ expect(await service.getAccessToken("openai-codex")).toBe("second-key");
+
+ await service.setAccountOrder("openai-codex", [addedId!, "default"]);
+ const restarted = await makeTestSubscriptionAuthService(authPath);
+ expect(restarted.linkedAccountIds("openai-codex")).toEqual([addedId, "default"]);
+ await restarted.logout("openai-codex", accountScope(addedId!));
+ expect(restarted.linkedAccountIds("openai-codex")).toEqual(["default"]);
+ expect(NodeFS.readFileSync(authPath, "utf-8")).not.toContain("second-key");
+ });
+
+ it("records each turn's outcome on the account that turn used", async () => {
+ const { authPath } = fixture();
+ const service = await makeTestSubscriptionAuthService(authPath);
+ const first = await service.startLogin("openai-codex", { authMode: "api-key" });
+ await service.completeLogin(first.loginId, "first-key");
+
+ const second = await service.startLogin("openai-codex", {
+ authMode: "api-key",
+ addAccount: true,
+ });
+
+ await service.completeLogin(second.loginId, "second-key");
+ const [, addedId] = service.linkedAccountIds("openai-codex");
+
+ expect(await service.getAccessToken("openai-codex", undefined, "thread-a")).toBe("first-key");
+ service.recordRequestFailure(
+ "openai-codex",
+ "You've hit your usage limit. Try again in 2 hours.",
+ new Date().toISOString(),
+ "request",
+ "thread-a",
+ );
+ // Thread B starts on the second account; a settings probe then reads the default scope.
+ expect(await service.getAccessToken("openai-codex", undefined, "thread-b")).toBe("second-key");
+ await service.getAccessToken("openai-codex");
+ // A late limit from thread A must not bench the account thread B is using.
+ service.recordRequestFailure(
+ "openai-codex",
+ "You've hit your usage limit. Try again in 2 hours.",
+ new Date().toISOString(),
+ "request",
+ "thread-a",
+ );
+ service.recordRequestSuccess("openai-codex", new Date().toISOString(), "thread-b");
+ expect(
+ service
+ .linkedAccountStatuses()
+ .filter((status) => status.provider === "openai-codex")
+ .map((status) => [status.accountId, status.active]),
+ ).toEqual([
+ ["default", false],
+ [addedId, true],
+ ]);
+ });
+
+ it("follows an account order saved by another service instance", async () => {
+ const { authPath } = fixture();
+ const controller = await makeTestSubscriptionAuthService(authPath);
+ const first = await controller.startLogin("openai-codex", { authMode: "api-key" });
+ await controller.completeLogin(first.loginId, "first-key");
+
+ const second = await controller.startLogin("openai-codex", {
+ authMode: "api-key",
+ addAccount: true,
+ });
+
+ await controller.completeLogin(second.loginId, "second-key");
+ const [, addedId] = controller.linkedAccountIds("openai-codex");
+ expect(await controller.getAccessToken("openai-codex")).toBe("first-key");
+
+ const settings = await makeTestSubscriptionAuthService(authPath);
+ await settings.setAccountOrder("openai-codex", [addedId!, "default"]);
+ expect(await controller.getAccessToken("openai-codex")).toBe("second-key");
+ });
+
+ it("reads a limit reset time from the provider message", () => {
+ const at = "2026-10-01T00:00:00.000Z";
+ expect(limitRetryAt("Rate limit reached. Try again in 1h 30m.", at)).toBe(
+ "2026-10-01T01:30:00.000Z",
+ );
+ expect(limitRetryAt("Usage limit reached.", at)).toBe("2026-10-01T01:00:00.000Z");
+ expect(isAccountLimitMessage("429 Too Many Requests")).toBe(true);
+ expect(isAccountLimitMessage("socket hang up")).toBe(false);
+ });
+
+ it("reads the ChatGPT tier from a login saved before tiers were recorded", async () => {
+ const { authPath } = fixture();
+ const claims = { "https://api.openai.com/auth": { chatgpt_plan_type: "plus" } };
+ NodeFS.writeFileSync(
+ authPath,
+ JSON.stringify({
+ "openai-codex": {
+ type: "oauth",
+ access: `e30.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.sig`,
+ refresh: "refresh",
+ expires: Date.now() + 60_000,
+ accountId: "account-123",
+ },
+ }),
+ );
+
+ const status = (await makeTestSubscriptionAuthService(authPath))
+ .statuses()
+ .find((entry) => entry.provider === "openai-codex");
+
+ expect(status?.plan).toBe("Plus");
+ });
+});
+
+it("reads plan usage through the active account and picks up a shared limit", async () => {
+ const { authPath } = fixture();
+ const service = await makeTestSubscriptionAuthService(authPath);
+ const first = await service.startLogin("opencode-go", { authMode: "api-key" });
+ await service.completeLogin(first.loginId, "first-key");
+ const second = await service.startLogin("opencode-go", { authMode: "api-key", addAccount: true });
+ await service.completeLogin(second.loginId, "second-key");
+ const firstAccess = await service.getPlanAccess("opencode-go");
+ expect(firstAccess?.accessToken).toBe("first-key");
+ const other = await makeTestSubscriptionAuthService(authPath);
+ other.recordRequestFailure("opencode-go", "Rate limit reached. Try again in 2h.");
+ const secondAccess = await service.getPlanAccess("opencode-go");
+ expect(secondAccess?.accessToken).toBe("second-key");
+ expect(secondAccess?.accountId).not.toBe(firstAccess?.accountId);
+ expect(NodeFS.statSync(`${authPath}.accounts`).mode & 0o777).toBe(0o600);
+});
+
+it("keeps the provider available while another linked account can serve requests", async () => {
+ const { authPath } = fixture();
+ const service = await makeTestSubscriptionAuthService(authPath);
+ const first = await service.startLogin("openai-codex", { authMode: "api-key" });
+ await service.completeLogin(first.loginId, "first-key");
+
+ const second = await service.startLogin("openai-codex", {
+ authMode: "api-key",
+ addAccount: true,
+ });
+
+ await service.completeLogin(second.loginId, "second-key");
+ service.recordRequestFailure("openai-codex", "Rate limit reached.");
+ service.recordProviderInstanceFailure("codex", "Rate limit reached.");
+ expect(service.providerInstanceRequestHealth("codex")).toBeUndefined();
+ expect(await service.getAccessToken("openai-codex")).toBe("second-key");
+ service.recordRequestFailure("openai-codex", "Rate limit reached.");
+ expect(service.providerInstanceRequestHealth("codex")?.health).toBe("failed-first-request");
+ expect(await service.getAccessToken("openai-codex")).toBe("first-key");
+});
+
+it("disconnects the displayed active account after a reorder and then the remaining account", async () => {
+ const { authPath } = fixture();
+ const service = await makeTestSubscriptionAuthService(authPath);
+ const first = await service.startLogin("openai-codex", { authMode: "api-key" });
+ await service.completeLogin(first.loginId, "first-key");
+
+ const second = await service.startLogin("openai-codex", {
+ authMode: "api-key",
+ addAccount: true,
+ });
+
+ await service.completeLogin(second.loginId, "second-key");
+ const addedId = service.linkedAccountIds("openai-codex")[1]!;
+ await service.setAccountOrder("openai-codex", [addedId, "default"]);
+ expect(service.getApiKeyCredential("openai-codex")?.access).toBe("second-key");
+ await service.logout("openai-codex");
+ expect(service.linkedAccountIds("openai-codex")).toEqual(["default"]);
+ expect(await service.getAccessToken("openai-codex")).toBe("first-key");
+ await service.logout("openai-codex", "codex");
+ expect(service.linkedAccountIds("openai-codex")).toEqual([]);
+});
+
+it("recovers from an account spending limit after its cooldown with the backup removed", async () => {
+ const { authPath } = fixture();
+ const service = await makeTestSubscriptionAuthService(authPath);
+ const first = await service.startLogin("openai-codex", { authMode: "api-key" });
+ await service.completeLogin(first.loginId, "first-key");
+
+ const second = await service.startLogin("openai-codex", {
+ authMode: "api-key",
+ addAccount: true,
+ });
+
+ await service.completeLogin(second.loginId, "second-key");
+ const addedId = service.linkedAccountIds("openai-codex")[1]!;
+ const at = new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString();
+ await service.getAccessToken("openai-codex");
+ service.recordRequestFailure("openai-codex", "Spending limit reached. Try again in 1h.", at);
+ service.recordProviderInstanceFailure("codex", "Spending limit reached.", at);
+ await service.logout("openai-codex", accountScope(addedId));
+ expect(service.linkedAccountIds("openai-codex")).toEqual(["default"]);
+ expect(service.providerInstanceRequestHealth("codex")).toBeUndefined();
+ expect(await service.getAccessToken("openai-codex")).toBe("first-key");
+});
+
+it("keeps a provider-only usage failure when no account limit was recorded", async () => {
+ const { authPath } = fixture();
+ const service = await makeTestSubscriptionAuthService(authPath);
+ const first = await service.startLogin("openai-codex", { authMode: "api-key" });
+ await service.completeLogin(first.loginId, "first-key");
+ service.recordProviderInstanceFailure("codex", "Budget exceeded.");
+ expect(service.providerInstanceRequestHealth("codex")?.health).toBe("failed-first-request");
+});
+
+it("keeps a limit cooldown when an older request reports success later", async () => {
+ const { authPath } = fixture();
+ const service = await makeTestSubscriptionAuthService(authPath);
+ const first = await service.startLogin("openai-codex", { authMode: "api-key" });
+ await service.completeLogin(first.loginId, "first-key");
+
+ const second = await service.startLogin("openai-codex", {
+ authMode: "api-key",
+ addAccount: true,
+ });
+
+ await service.completeLogin(second.loginId, "second-key");
+ const startedAt = new Date(Date.now() - 60_000).toISOString();
+ await service.getAccessToken("openai-codex", undefined, "thread-a");
+ await service.getAccessToken("openai-codex", undefined, "thread-b");
+ service.recordRequestFailure(
+ "openai-codex",
+ "Rate limit reached. Try again in 1h.",
+ new Date().toISOString(),
+ "request",
+ "thread-b",
+ );
+ service.recordRequestSuccess("openai-codex", startedAt, "thread-a");
+ expect(await service.getAccessToken("openai-codex")).toBe("second-key");
+});
+
+it("keeps a provider limit when backups exist but no account recorded the limit", async () => {
+ const { authPath } = fixture();
+ const service = await makeTestSubscriptionAuthService(authPath);
+ const first = await service.startLogin("openai-codex", { authMode: "api-key" });
+ await service.completeLogin(first.loginId, "first-key");
+
+ const second = await service.startLogin("openai-codex", {
+ authMode: "api-key",
+ addAccount: true,
+ });
+
+ await service.completeLogin(second.loginId, "second-key");
+ service.recordProviderInstanceFailure("codex", "Rate limit reached.");
+ expect(service.providerInstanceRequestHealth("codex")?.health).toBe("failed-first-request");
+});
+
+it("keeps a rejected refresh revoked after the failed turn reports its outcome", async () => {
+ const { authPath, directory } = fixture();
+ NodeFS.writeFileSync(
+ authPath,
+ JSON.stringify({
+ "openai-codex": {
+ type: "oauth",
+ access: "expired",
+ refresh: "rejected",
+ expires: 0,
+ accountId: "main",
+ },
+ "account:openai-codex:backup": { type: "api-key", access: "backup-key" },
+ }),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => Response.json({ error: "invalid_grant" }, { status: 400 })),
+ );
+
+ try {
+ const service = await makeTestSubscriptionAuthService(authPath);
+ expect(await service.getAccessToken("openai-codex", undefined, "failed-turn")).toBeUndefined();
+ expect(await service.getAccessToken("openai-codex", undefined, "backup-turn")).toBe(
+ "backup-key",
+ );
+ service.recordAccountRequestFailure(
+ "openai-codex",
+ "codex",
+ "Token unavailable",
+ new Date().toISOString(),
+ "failed-turn",
+ );
+ expect(
+ service
+ .linkedAccountStatuses()
+ .find((status) => status.provider === "openai-codex" && status.accountId === "default")
+ ?.health,
+ ).toBe("revoked");
+ expect(await service.getAccessToken("openai-codex")).toBe("backup-key");
+ service.recordRequestSuccess(
+ "openai-codex",
+ new Date(Date.now() + 1000).toISOString(),
+ "failed-turn",
+ );
+ service.recordRequestFailure(
+ "openai-codex",
+ "socket hang up",
+ new Date(Date.now() + 2000).toISOString(),
+ "request",
+ "failed-turn",
+ );
+ expect(service.getOAuthCredential("openai-codex")?.accountId).toBe("main");
+ } finally {
+ vi.unstubAllGlobals();
+ NodeFS.rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+it("keeps a limit cooldown when the limited account reports a later success", async () => {
+ const { authPath } = fixture();
+ const service = await makeTestSubscriptionAuthService(authPath);
+ const first = await service.startLogin("openai-codex", { authMode: "api-key" });
+ await service.completeLogin(first.loginId, "first-key");
+
+ const second = await service.startLogin("openai-codex", {
+ authMode: "api-key",
+ addAccount: true,
+ });
+
+ await service.completeLogin(second.loginId, "second-key");
+ await service.getAccessToken("openai-codex", undefined, "thread-a");
+ await service.getAccessToken("openai-codex", undefined, "thread-b");
+ const failedAt = new Date(Date.now() - 60_000).toISOString();
+ service.recordRequestFailure(
+ "openai-codex",
+ "Rate limit reached. Try again in 1h.",
+ failedAt,
+ "request",
+ "thread-b",
+ );
+ service.recordRequestSuccess("openai-codex", new Date().toISOString(), "thread-a");
+ expect(await service.getAccessToken("openai-codex")).toBe("second-key");
+});
+
+it("unblocks the provider when the limited account is removed or signs in again", async () => {
+ const { authPath } = fixture();
+ const service = await makeTestSubscriptionAuthService(authPath);
+ const first = await service.startLogin("openai-codex", { authMode: "api-key" });
+ await service.completeLogin(first.loginId, "first-key");
+
+ const second = await service.startLogin("openai-codex", {
+ authMode: "api-key",
+ addAccount: true,
+ });
+
+ await service.completeLogin(second.loginId, "second-key");
+ const addedId = service.linkedAccountIds("openai-codex")[1]!;
+ await service.getAccessToken("openai-codex");
+ service.recordRequestFailure("openai-codex", "Usage cap reached.");
+ service.recordProviderInstanceFailure("codex", "Usage cap reached.");
+ await service.logout("openai-codex", accountScope("default"));
+ expect(service.linkedAccountIds("openai-codex")).toEqual([addedId]);
+ expect(service.providerInstanceRequestHealth("codex")).toBeUndefined();
+
+ service.recordRequestFailure("openai-codex", "Usage cap reached.");
+ service.recordProviderInstanceFailure("codex", "Usage cap reached.");
+
+ const again = await service.startLogin("openai-codex", {
+ authMode: "api-key",
+ accountId: addedId,
+ });
+
+ await service.completeLogin(again.loginId, "replacement-key");
+ expect(service.providerInstanceRequestHealth("codex")).toBeUndefined();
+ expect(await service.getAccessToken("openai-codex")).toBe("replacement-key");
+});
+
+it("keeps the provider blocked when the remaining account is still limited", async () => {
+ const { authPath } = fixture();
+ const service = await makeTestSubscriptionAuthService(authPath);
+ const first = await service.startLogin("openai-codex", { authMode: "api-key" });
+ await service.completeLogin(first.loginId, "first-key");
+
+ const second = await service.startLogin("openai-codex", {
+ authMode: "api-key",
+ addAccount: true,
+ });
+
+ await service.completeLogin(second.loginId, "second-key");
+ await service.getAccessToken("openai-codex", undefined, "thread-a");
+ service.recordRequestFailure(
+ "openai-codex",
+ "Usage cap reached.",
+ undefined,
+ "request",
+ "thread-a",
+ );
+ await service.getAccessToken("openai-codex", undefined, "thread-b");
+ service.recordRequestFailure(
+ "openai-codex",
+ "Usage cap reached.",
+ undefined,
+ "request",
+ "thread-b",
+ );
+ service.recordProviderInstanceFailure("codex", "Usage cap reached.");
+ await service.logout("openai-codex", accountScope("default"));
+ expect(service.providerInstanceRequestHealth("codex")?.health).toBe("failed-first-request");
+});
diff --git a/apps/server/src/subscription-auth/service.credentialReload.test.ts b/apps/server/src/subscription-auth/service.credentialReload.test.ts
index c676c32e6..52dcba1fd 100644
--- a/apps/server/src/subscription-auth/service.credentialReload.test.ts
+++ b/apps/server/src/subscription-auth/service.credentialReload.test.ts
@@ -42,7 +42,7 @@ it.effect.each(["codex", "plan", "kimi"])(
"revoked",
);
expect(reader.statuses().find((status) => status.provider === "openai-codex")?.health).toBe(
- "detected",
+ "revoked",
);
yield* Effect.promise(async () => {
await Match.value(access).pipe(
diff --git a/apps/server/src/subscription-auth/service.lifecycle.test.ts b/apps/server/src/subscription-auth/service.lifecycle.test.ts
index 87d3d65a0..9b1c70f78 100644
--- a/apps/server/src/subscription-auth/service.lifecycle.test.ts
+++ b/apps/server/src/subscription-auth/service.lifecycle.test.ts
@@ -18,6 +18,7 @@ describe("subscription auth storage", () => {
anthropic: {
type: "oauth",
access: "first-token",
+ plan: "Max 20x",
refresh: "refresh",
expires: Date.now() + 60_000,
},
@@ -49,6 +50,9 @@ describe("subscription auth storage", () => {
accessToken: "refreshed-token",
accountId: first?.accountId,
});
+ expect(service.statuses().find((entry) => entry.provider === "anthropic")?.plan).toBe(
+ "Max 20x",
+ );
expect(
await (await makeTestSubscriptionAuthService(authPath)).getPlanAccess("anthropic"),
).toEqual({
diff --git a/apps/server/src/subscription-auth/service.login-races.test.ts b/apps/server/src/subscription-auth/service.login-races.test.ts
index ae4f603ff..89c6f9ca9 100644
--- a/apps/server/src/subscription-auth/service.login-races.test.ts
+++ b/apps/server/src/subscription-auth/service.login-races.test.ts
@@ -30,7 +30,7 @@ describe("OAuth completion ownership", () => {
checkHealthOnConnect: false,
});
- const request = vi.fn(async () =>
+ const request = vi.fn(async (_input: string | URL | Request) =>
Response.json({ access_token: "access", refresh_token: "refresh", expires_in: 3600 }),
);
@@ -60,7 +60,11 @@ describe("OAuth completion ownership", () => {
const retry = await service.completeLogin(login.loginId, `code#${state}`);
expect(retry.status).toBe(cancelDuringWrite ? "failed" : "connected");
expect(service.isConnected("anthropic")).toBe(!cancelDuringWrite);
- expect(request).toHaveBeenCalledOnce();
+ expect(
+ request.mock.calls.filter(([input]) =>
+ String(input instanceof Request ? input.url : input).includes("/oauth/token"),
+ ),
+ ).toHaveLength(1);
} finally {
updateSpy.mockRestore();
}
diff --git a/apps/server/src/subscription-auth/service.ts b/apps/server/src/subscription-auth/service.ts
index 0ba04b9fc..381dc00ee 100644
--- a/apps/server/src/subscription-auth/service.ts
+++ b/apps/server/src/subscription-auth/service.ts
@@ -1,3 +1,6 @@
+import { startSubscriptionLogin } from "./loginStart.ts";
+import { SubscriptionAccountState } from "./accountState.ts";
+import * as DateTime from "effect/DateTime";
import { decodePendingLogins } from "./persistedSchemas.ts";
import * as Predicate from "effect/Predicate";
import * as NodeFS from "node:fs";
@@ -16,14 +19,12 @@ import {
type SubscriptionAuthData,
type SubscriptionCredentialStore,
} from "./credentialStore.ts";
-import { completeAnthropicLogin, startAnthropicLogin } from "./providers/anthropic.ts";
-import { pollCodexDeviceLogin, startCodexDeviceLogin } from "./providers/openaiCodex.ts";
-import { pollKimiDeviceLogin, startKimiDeviceLogin } from "./providers/kimi.ts";
-import { pollXAIDeviceLogin, startXAIDeviceLogin } from "./providers/xai.ts";
+import { completeAnthropicLogin } from "./providers/anthropic.ts";
+import { pollCodexDeviceLogin } from "./providers/openaiCodex.ts";
+import { pollKimiDeviceLogin } from "./providers/kimi.ts";
+import { pollXAIDeviceLogin } from "./providers/xai.ts";
import type { ApiKeyCredential, OAuthCredential, OAuthCredentials } from "./types.ts";
import {
- decodeBaseUrl,
- OPENCODE_GO_AUTH_URL,
SUBSCRIPTION_PROVIDER_IDS,
type SubscriptionProviderId,
type StartedLogin,
@@ -34,14 +35,19 @@ import {
type BoundLogin,
defaultInstanceByProvider,
credentialKey,
+ accountScope,
+ accountIdForKey,
+ DEFAULT_ACCOUNT_ID,
+ isDefaultScope,
credentialAt,
PENDING_LOGIN_CAP,
} from "./serviceTypes.ts";
import { SubscriptionHealthService } from "./healthService.ts";
import { SubscriptionCredentialAccess } from "./credentialAccess.ts";
-import { providerStatuses } from "./providerStatuses.ts";
+import { providerStatuses, linkedAccountStatuses } from "./providerStatuses.ts";
export class SubscriptionAuthService {
+ private readonly accounts: SubscriptionAccountState;
private readonly clock: Clock.Clock;
private readonly credentialAccess: SubscriptionCredentialAccess;
private readonly healthService: SubscriptionHealthService;
@@ -79,10 +85,17 @@ export class SubscriptionAuthService {
options.checkHealthOnConnect ?? false,
() => this.reload(),
);
+ this.accounts = new SubscriptionAccountState(store, this.healthService, clock, () =>
+ this.reload(),
+ );
this.pendingPath = `${this.authPath}.pending`;
- this.credentialAccess = new SubscriptionCredentialAccess(store, this.healthService, clock, () =>
- this.reload(),
+ this.credentialAccess = new SubscriptionCredentialAccess(
+ store,
+ this.healthService,
+ this.accounts,
+ clock,
+ () => this.reload(),
);
this.reloadLocal();
}
@@ -138,6 +151,7 @@ export class SubscriptionAuthService {
private reloadLocal(): void {
this.reloadHealth();
+ this.accounts.reloadAccountOrder();
this.pendingLogins.clear();
@@ -177,7 +191,34 @@ export class SubscriptionAuthService {
now = this.clock.currentTimeMillisUnsafe(),
instanceId?: ProviderInstanceId,
): ProviderStatus[] {
- return providerStatuses(this.store.current(), this.health, dependentBots, now, instanceId);
+ this.accounts.refreshAccountState();
+
+ return providerStatuses(
+ this.store.current(),
+ this.health,
+ dependentBots,
+ now,
+ instanceId,
+ (provider) =>
+ isDefaultScope(provider, instanceId)
+ ? this.accounts.activeAccountKey(provider, now)
+ : credentialKey(provider, instanceId),
+ );
+ }
+
+ linkedAccountIds(provider: SubscriptionProviderId): string[] {
+ return this.accounts.linkedAccountIds(provider);
+ }
+ setAccountOrder(
+ provider: SubscriptionProviderId,
+ accountIds: ReadonlyArray<string>,
+ ): Promise<void> {
+ return this.accounts.setAccountOrder(provider, accountIds);
+ }
+ linkedAccountStatuses(now = this.clock.currentTimeMillisUnsafe()): ProviderStatus[] {
+ this.accounts.refreshAccountState();
+
+ return linkedAccountStatuses(this.store.current(), this.health, this.accounts, now);
}
accountStatus(
@@ -194,16 +235,27 @@ export class SubscriptionAuthService {
)!;
}
- recordRequestSuccess(provider: SubscriptionProviderId, at?: string): void {
- return this.healthService.recordRequestSuccess(provider, at);
+ recordRequestSuccess(
+ provider: SubscriptionProviderId,
+ at = DateTime.formatIso(DateTime.makeUnsafe(this.clock.currentTimeMillisUnsafe())),
+ threadId?: string,
+ ): void {
+ this.healthService.recordHealthSuccess(
+ this.accounts.outcomeKey(provider, undefined, threadId),
+ at,
+ );
}
recordAccountRequestSuccess(
provider: SubscriptionProviderId,
instanceId: string,
at: string,
+ threadId?: string,
): void {
- return this.healthService.recordAccountRequestSuccess(provider, instanceId, at);
+ this.healthService.recordHealthSuccess(
+ this.accounts.outcomeKey(provider, instanceId, threadId),
+ at,
+ );
}
recordProviderInstanceSuccess(instanceId: string, at?: string): void {
@@ -213,10 +265,16 @@ export class SubscriptionAuthService {
recordRequestFailure(
provider: SubscriptionProviderId,
message: string,
- at?: string,
+ at = DateTime.formatIso(DateTime.makeUnsafe(this.clock.currentTimeMillisUnsafe())),
failureKind: "request" | "revoked" = "request",
+ threadId?: string,
): void {
- return this.healthService.recordRequestFailure(provider, message, at, failureKind);
+ this.healthService.recordAccountFailure(
+ this.accounts.outcomeKey(provider, undefined, threadId),
+ message,
+ at,
+ failureKind,
+ );
}
recordAccountRequestFailure(
@@ -224,8 +282,14 @@ export class SubscriptionAuthService {
instanceId: string,
message: string,
at: string,
+ threadId?: string,
): void {
- return this.healthService.recordAccountRequestFailure(provider, instanceId, message, at);
+ this.healthService.recordAccountFailure(
+ this.accounts.outcomeKey(provider, instanceId, threadId),
+ message,
+ at,
+ "request",
+ );
}
recordProviderInstanceFailure(
@@ -292,7 +356,7 @@ export class SubscriptionAuthService {
}
providerInstanceRequestHealth(instanceId: string): RequestHealthStatus | undefined {
- return this.healthService.providerInstanceRequestHealth(instanceId);
+ return this.accounts.providerInstanceRequestHealth(instanceId);
}
mcpRequestHealth(serverId: string): RequestHealthStatus | undefined {
@@ -300,7 +364,14 @@ export class SubscriptionAuthService {
}
async testHealth(provider: SubscriptionProviderId, instanceId?: string): Promise<void> {
- return this.healthService.testHealth(provider, instanceId);
+ const scope = isDefaultScope(provider, instanceId)
+ ? accountScope(
+ accountIdForKey(provider, this.accounts.liveKey(provider, instanceId)) ??
+ DEFAULT_ACCOUNT_ID,
+ )
+ : instanceId;
+
+ return this.healthService.testHealth(provider, scope);
}
/**
@@ -308,6 +379,8 @@ export class SubscriptionAuthService {
* client that finished the login disconnects; `awaitHealthCheck` observes it.
*/
private startHealthCheck(provider: SubscriptionProviderId, instanceId?: string): LoginPollStatus {
+ this.accounts.rememberAccountOrder(provider);
+
return this.healthService.startHealthCheck(provider, instanceId);
}
@@ -317,11 +390,11 @@ export class SubscriptionAuthService {
}
isConnected(provider: SubscriptionProviderId, instanceId?: string): boolean {
- return credentialAt(this.data, credentialKey(provider, instanceId)) !== undefined;
+ return credentialAt(this.data, this.accounts.liveKey(provider, instanceId)) !== undefined;
}
hasOpenAICodexAccount(): boolean {
- const credential = this.data["openai-codex"];
+ const credential = credentialAt(this.data, this.accounts.liveKey("openai-codex"));
return (
credential?.type === "oauth" &&
@@ -330,124 +403,38 @@ export class SubscriptionAuthService {
);
}
- async startLogin(
+ startLogin(
provider: SubscriptionProviderId,
options: Omit<SubscriptionAuthStartInput, "provider"> = {},
): Promise<StartedLogin> {
- await this.reloadAsync();
- const authMode = options.authMode ?? (provider === "opencode-go" ? "api-key" : "oauth");
-
- if (options.baseUrl !== undefined && authMode !== "api-key") {
- throw new Error("Custom base URLs require API-key authentication. Select API key first.");
- }
-
- if (options.baseUrl !== undefined && provider === "xai") {
- throw new Error(
- "The Grok bridge does not support custom base URLs. Use the default endpoint.",
- );
- }
-
- if (authMode === "oauth" && provider === "opencode-go") {
- throw new Error("OpenCode Go requires an API key. Select API key first.");
- }
-
- const baseUrl =
- options.baseUrl === undefined
- ? undefined
- : decodeBaseUrl(options.baseUrl).replace(/\/+$/, "");
-
- const loginId = NodeCrypto.randomUUID();
- const binding = options.instanceId ? { instanceId: options.instanceId } : {};
- let started: StartedLogin;
-
- if (authMode === "api-key") {
- this.pendingLogins.set(loginId, {
- provider,
- authMode,
- ...binding,
- ...(baseUrl ? { baseUrl } : {}),
- });
- started = {
- loginId,
- provider,
- url: provider === "opencode-go" ? OPENCODE_GO_AUTH_URL : "",
- instructions: "Paste the provider API key.",
- completion: "paste",
- };
- } else
- switch (provider) {
- case "anthropic": {
- const { url, verifier } = await startAnthropicLogin();
- this.pendingLogins.set(loginId, { provider, verifier, ...binding });
- started = { loginId, provider, url, completion: "paste" };
- break;
- }
-
- case "openai-codex": {
- const pending = await startCodexDeviceLogin();
- this.pendingLogins.set(loginId, { provider, pending, ...binding });
- started = {
- loginId,
- provider,
- url: pending.url,
- userCode: pending.userCode,
- instructions: pending.instructions,
- completion: "poll",
- };
- break;
- }
-
- case "xai": {
- const pending = await startXAIDeviceLogin();
- this.pendingLogins.set(loginId, { provider, pending, ...binding });
- started = {
- loginId,
- provider,
- url: pending.url,
- userCode: pending.userCode,
- instructions: pending.instructions,
- completion: "poll",
- };
- break;
- }
-
- case "kimi-for-coding": {
- const pending = await startKimiDeviceLogin();
- this.pendingLogins.set(loginId, { provider, pending, ...binding });
- started = {
- loginId,
- provider,
- url: pending.url,
- userCode: pending.userCode,
- instructions: pending.instructions,
- completion: "poll",
- };
- break;
- }
+ return startSubscriptionLogin(
+ {
+ reloadAsync: () => this.reloadAsync(),
+ loginScope: (provider, options) => this.loginScope(provider, options),
+ pendingLogins: this.pendingLogins,
+ savePending: () => this.savePending(),
+ },
+ provider,
+ options,
+ );
+ }
- case "opencode-go": {
- this.pendingLogins.set(loginId, { provider, ...binding });
- started = {
- loginId,
- provider,
- url: OPENCODE_GO_AUTH_URL,
- instructions: "Subscribe to OpenCode Go, copy the API key, then paste it here.",
- completion: "paste",
- };
- break;
- }
- }
+ private loginScope(
+ provider: SubscriptionProviderId,
+ options: Omit<SubscriptionAuthStartInput, "provider">,
+ ): string {
+ if (options.accountId) return accountScope(options.accountId);
- // Drop the oldest abandoned login rather than growing without bound.
- if (this.pendingLogins.size > PENDING_LOGIN_CAP) {
- const oldest = this.pendingLogins.keys().next().value;
+ if (!isDefaultScope(provider, options.instanceId)) return options.instanceId!;
+ const linked = this.linkedAccountIds(provider);
- if (oldest !== undefined) this.pendingLogins.delete(oldest);
+ if (options.addAccount && linked.length > 0) {
+ return accountScope(`acct-${NodeCrypto.randomBytes(6).toString("hex")}`);
}
- this.savePending();
+ const active = accountIdForKey(provider, this.accounts.activeAccountKey(provider));
- return started;
+ return accountScope(active ?? DEFAULT_ACCOUNT_ID);
}
/** One upstream poll for a started login. Persists credentials on success. */
@@ -590,6 +577,7 @@ export class SubscriptionAuthService {
this.reloadHealth();
delete this.health[key];
this.clearImageHealth(login.provider, login.instanceId);
+ this.clearProviderLimitIfReady(login.provider, key);
this.saveHealth();
return this.startHealthCheck(login.provider, login.instanceId);
@@ -625,8 +613,8 @@ export class SubscriptionAuthService {
}
async logout(provider: SubscriptionProviderId, instanceId?: string): Promise<void> {
- this.reloadLocal();
- const key = credentialKey(provider, instanceId);
+ await this.reloadAsync();
+ const key = this.accounts.liveKey(provider, instanceId);
for (const [loginId, pending] of this.pendingLogins) {
if (credentialKey(pending.provider, pending.instanceId) === key) {
@@ -640,7 +628,20 @@ export class SubscriptionAuthService {
this.reloadHealth();
delete this.health[key];
this.clearImageHealth(provider, instanceId);
+ this.clearProviderLimitIfReady(provider, key);
this.saveHealth();
+
+ if (this.accounts.lastServedKey.get(provider) === key)
+ this.accounts.lastServedKey.delete(provider);
+ this.accounts.rememberAccountOrder(provider);
+ }
+
+ /** Lifts a provider-level limit only once a linked account can take the next request. */
+ private clearProviderLimitIfReady(provider: SubscriptionProviderId, key: string): void {
+ const now = this.clock.currentTimeMillisUnsafe();
+
+ if (this.accounts.accountReady(this.accounts.activeAccountKey(provider, now), now))
+ this.healthService.clearProviderLimit(provider, key);
}
private clearImageHealth(provider: SubscriptionProviderId, instanceId?: string): void {
@@ -716,6 +717,7 @@ export class SubscriptionAuthService {
this.reloadHealth();
delete this.health[key];
this.clearImageHealth(login.provider, login.instanceId);
+ this.clearProviderLimitIfReady(login.provider, key);
this.saveHealth();
return true;
@@ -729,8 +731,9 @@ export class SubscriptionAuthService {
async getAccessToken(
provider: SubscriptionProviderId,
instanceId?: string,
+ threadId?: string,
): Promise<string | undefined> {
- return this.credentialAccess.getAccessToken(provider, instanceId);
+ return this.credentialAccess.getAccessToken(provider, instanceId, threadId);
}
async getPlanAccessToken(
@@ -753,35 +756,40 @@ export class SubscriptionAuthService {
getApiKeyCredential(
provider: SubscriptionProviderId,
instanceId?: string,
+ threadId?: string,
): ApiKeyCredential | undefined {
- return this.credentialAccess.getApiKeyCredential(provider, instanceId);
+ return this.credentialAccess.getApiKeyCredential(provider, instanceId, threadId);
}
getOAuthCredential(
provider: SubscriptionProviderId,
instanceId?: string,
- ): OAuthCredential | undefined {
- return this.credentialAccess.getOAuthCredential(provider, instanceId);
+ threadId?: string,
+ ): (OAuthCredential & { readonly scope?: string }) | undefined {
+ return this.credentialAccess.getOAuthCredential(provider, instanceId, threadId);
}
async getOpenAICodexAccess(
instanceId?: string,
+ threadId?: string,
): Promise<{ readonly accessToken: string; readonly accountId: string } | undefined> {
- return this.credentialAccess.getOpenAICodexAccess(instanceId);
+ return this.credentialAccess.getOpenAICodexAccess(instanceId, threadId);
}
async getKimiForCodingAccess(
instanceId?: string,
+ threadId?: string,
): Promise<
| { readonly accessToken: string; readonly deviceId?: string; readonly baseUrl?: string }
| undefined
> {
- return this.credentialAccess.getKimiForCodingAccess(instanceId);
+ return this.credentialAccess.getKimiForCodingAccess(instanceId, threadId);
}
}
export {
anthropicApiBaseUrl,
+ accountScope,
SUBSCRIPTION_PROVIDER_IDS,
isSubscriptionProviderId,
type SubscriptionProviderId,
@@ -791,3 +799,5 @@ export {
type ProviderStatus,
type RequestHealthStatus,
} from "./serviceTypes.ts";
+
+export { isAccountLimitMessage, limitRetryAt } from "./accountLimits.ts";
diff --git a/apps/server/src/subscription-auth/serviceTypes.ts b/apps/server/src/subscription-auth/serviceTypes.ts
index 55913b623..9177f9735 100644
--- a/apps/server/src/subscription-auth/serviceTypes.ts
+++ b/apps/server/src/subscription-auth/serviceTypes.ts
@@ -68,6 +68,9 @@ export interface ProviderStatus {
instanceId?: ProviderInstanceId;
connected: boolean;
accountLabel?: string;
+ accountId?: string;
+ active?: boolean;
+ plan?: string;
authMode?: "oauth" | "api-key";
baseUrl?: string;
/** ms epoch when the current access token expires; refreshed on demand. */
@@ -239,10 +242,34 @@ export const defaultInstanceByProvider: Record<SubscriptionProviderId, string> =
};
/** The default instance keeps the bare provider key; other instances get their own account. */
-export function credentialKey(provider: SubscriptionProviderId, instanceId?: string): string {
- return !instanceId || instanceId === defaultInstanceByProvider[provider]
- ? provider
- : `instance:${provider}:${instanceId}`;
+export function credentialKey(provider: SubscriptionProviderId, scope?: string): string {
+ if (scope?.startsWith(ACCOUNT_SCOPE_PREFIX)) {
+ const accountId = scope.slice(ACCOUNT_SCOPE_PREFIX.length);
+
+ return accountId === DEFAULT_ACCOUNT_ID ? provider : `account:${provider}:${accountId}`;
+ }
+
+ return isDefaultScope(provider, scope) ? provider : `instance:${provider}:${scope}`;
+}
+
+/** The scope bots on the built-in provider use; it follows the linked-account order. */
+export function isDefaultScope(provider: SubscriptionProviderId, scope?: string): boolean {
+ return !scope || scope === defaultInstanceByProvider[provider];
+}
+
+const ACCOUNT_SCOPE_PREFIX = "account:";
+
+export const DEFAULT_ACCOUNT_ID = "default";
+
+export function accountScope(accountId: string): string {
+ return `${ACCOUNT_SCOPE_PREFIX}${accountId}`;
+}
+
+export function accountIdForKey(provider: SubscriptionProviderId, key: string): string | undefined {
+ if (key === provider) return DEFAULT_ACCOUNT_ID;
+ const prefix = `account:${provider}:`;
+
+ return key.startsWith(prefix) ? key.slice(prefix.length) : undefined;
}
export function credentialAt(
@@ -261,6 +288,7 @@ export function refreshedCredential(
): OAuthCredential {
return {
...refreshed,
+ ...(refreshed.plan === undefined && previous.plan !== undefined ? { plan: previous.plan } : {}),
type: "oauth",
...(refreshed.connectionId === undefined && previous.connectionId !== undefined
? { connectionId: previous.connectionId }
diff --git a/apps/server/src/textGeneration/HarnessTextGeneration.test.ts b/apps/server/src/textGeneration/HarnessTextGeneration.test.ts
index f1bbfcd77..9e8af8d2a 100644
--- a/apps/server/src/textGeneration/HarnessTextGeneration.test.ts
+++ b/apps/server/src/textGeneration/HarnessTextGeneration.test.ts
@@ -198,7 +198,7 @@ describe("HarnessTextGeneration", () => {
for (const [driver, provider, model, transport] of [
["codex", "openai-codex", "gpt-6-sol", "gpt-6-sol"],
["claudeAgent", "anthropic", "claude-sonnet-5", "claude-sonnet-5"],
- ["grok", "xai", "grok-build", "grok-4.6"],
+ ["grok", "xai", "grok-build", "grok-4.7"],
] as const) {
it.effect(
`generates ${driver} titles and branches with a saved credential, without a CLI`,
diff --git a/apps/server/src/wsAuthHandlers.ts b/apps/server/src/wsAuthHandlers.ts
index 6396ff199..fef0b88b6 100644
--- a/apps/server/src/wsAuthHandlers.ts
+++ b/apps/server/src/wsAuthHandlers.ts
@@ -1,3 +1,4 @@
+import { accountScope } from "./subscription-auth/service.ts";
import type * as RpcGroup from "effect/unstable/rpc/RpcGroup";
import * as Effect from "effect/Effect";
import * as Queue from "effect/Queue";
@@ -206,11 +207,12 @@ export const createWsAuthHandlers = ({
{ "rpc.aggregate": "server" },
),
- [WS_METHODS.subscriptionAuthLogout]: ({ provider, instanceId }) =>
+ [WS_METHODS.subscriptionAuthLogout]: ({ provider, instanceId, accountId }) =>
observeRpcEffect(
WS_METHODS.subscriptionAuthLogout,
Effect.tryPromise({
- try: () => subscriptionAuth.logout(provider, instanceId),
+ try: () =>
+ subscriptionAuth.logout(provider, accountId ? accountScope(accountId) : instanceId),
catch: (cause) =>
new SubscriptionAuthError({
reason: cause instanceof Error ? cause.message : String(cause),
@@ -223,11 +225,25 @@ export const createWsAuthHandlers = ({
{ "rpc.aggregate": "server" },
),
- [WS_METHODS.subscriptionAuthHealthTest]: ({ provider, instanceId }) =>
+ [WS_METHODS.subscriptionAuthHealthTest]: ({ provider, instanceId, accountId }) =>
observeRpcEffect(
WS_METHODS.subscriptionAuthHealthTest,
Effect.tryPromise({
- try: () => subscriptionAuth.testHealth(provider, instanceId),
+ try: () =>
+ subscriptionAuth.testHealth(provider, accountId ? accountScope(accountId) : instanceId),
+ catch: (cause) =>
+ new SubscriptionAuthError({
+ reason: cause instanceof Error ? cause.message : String(cause),
+ }),
+ }).pipe(Effect.andThen(getAccessHealthSnapshot())),
+ { "rpc.aggregate": "server" },
+ ),
+
+ [WS_METHODS.subscriptionAuthSetAccountOrder]: ({ provider, accountIds }) =>
+ observeRpcEffect(
+ WS_METHODS.subscriptionAuthSetAccountOrder,
+ Effect.tryPromise({
+ try: () => subscriptionAuth.setAccountOrder(provider, accountIds),
catch: (cause) =>
new SubscriptionAuthError({
reason: cause instanceof Error ? cause.message : String(cause),
@@ -302,6 +318,7 @@ export const createWsAuthHandlers = ({
| typeof WS_METHODS.subscriptionAuthComplete
| typeof WS_METHODS.subscriptionAuthCancel
| typeof WS_METHODS.subscriptionAuthLogout
+ | typeof WS_METHODS.subscriptionAuthSetAccountOrder
| typeof WS_METHODS.subscriptionAuthHealthTest
| typeof WS_METHODS.imageProviderList
| typeof WS_METHODS.imageProviderHealthTest
diff --git a/apps/server/src/wsServices.ts b/apps/server/src/wsServices.ts
index baad98988..b57358026 100644
--- a/apps/server/src/wsServices.ts
+++ b/apps/server/src/wsServices.ts
@@ -466,6 +466,7 @@ export const createWsServices = (
},
),
access,
+ linkedAccounts: subscriptionAuth.linkedAccountStatuses(),
inbox: botInbox.list(),
};
});
diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx
index 21333bfd3..94ef258a1 100644
--- a/apps/web/src/components/AppSidebarLayout.tsx
+++ b/apps/web/src/components/AppSidebarLayout.tsx
@@ -245,6 +245,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
<SidebarProvider
className="h-dvh! min-h-0!"
data-sidebar-experiment={sidebarExperiment ? "" : undefined}
+ data-macos-traffic-lights={isMacosDesktop && !isWindowFullscreen ? "" : undefined}
defaultOpen
style={sidebarProviderStyle}
>
diff --git a/apps/web/src/components/chat/ProviderConnectCard.tsx b/apps/web/src/components/chat/ProviderConnectCard.tsx
new file mode 100644
index 000000000..fc6749e10
--- /dev/null
+++ b/apps/web/src/components/chat/ProviderConnectCard.tsx
@@ -0,0 +1,147 @@
+import type {
+ EnvironmentId,
+ SubscriptionProviderId,
+ SubscriptionProviderStatus,
+} from "@akeru/contracts";
+import { providerSupportsBaseUrl } from "@akeru/client-runtime/provider-auth";
+import { LoaderIcon } from "lucide-react";
+
+import { useI18n } from "../../i18n";
+import { cn } from "../../lib/utils";
+import { SettingsEntityIcon } from "../settings/settingsDetailLayout";
+import { ActiveLoginPanel, ProviderApiKeyForm } from "../settings/ProviderAccountControls";
+import { SUBSCRIPTION_PROVIDERS } from "../settings/subscriptionProviders";
+import { useSubscriptionAccounts } from "../settings/useSubscriptionAccounts";
+import { Button } from "../ui/button";
+
+/**
+ * What the user still has to do for an account before its bots can reply:
+ * sign in, sign in again, or wait for the check that follows a sign-in. Null
+ * when the account is ready or its status has not loaded yet.
+ */
+export function providerConnectStep(
+ status: SubscriptionProviderStatus | undefined,
+): "connect" | "reconnect" | "checking" | null {
+ if (!status) return null;
+
+ if (!status.connected) return "connect";
+
+ if (status.health === "revoked" || status.health === "expired") return "reconnect";
+
+ return status.healthChecking ? "checking" : null;
+}
+
+/**
+ * Asks the user to connect the account a bot runs on and runs the sign-in in
+ * place, so fixing it never leaves the chat. Renders nothing once the account
+ * is connected, which clears the card as soon as the post-login check lands.
+ */
+export function ProviderConnectCard({
+ environmentId,
+ provider,
+ botName,
+ id,
+ className,
+}: {
+ readonly environmentId: EnvironmentId | null;
+ readonly provider: SubscriptionProviderId;
+ readonly botName: string;
+ readonly id?: string | undefined;
+ readonly className?: string;
+}) {
+ const { t } = useI18n();
+ const accounts = useSubscriptionAccounts(environmentId);
+ const definition = SUBSCRIPTION_PROVIDERS.find((candidate) => candidate.id === provider);
+ const status = accounts.statusByProvider.get(provider);
+
+ if (!definition || environmentId === null) return null;
+
+ const signingIn = accounts.activeLogin !== null || accounts.keyProvider !== null;
+ const step = providerConnectStep(status);
+
+ if (!signingIn && step === null) return null;
+
+ if (!signingIn && step === "checking") {
+ return (
+ <div
+ id={id}
+ role="status"
+ className="flex items-center justify-center gap-2 px-4 pb-3 text-xs text-muted-foreground"
+ >
+ <LoaderIcon className="size-3.5 animate-spin" />
+ {t("Checking your {provider} account…", { provider: definition.label })}
+ </div>
+ );
+ }
+
+ const lapsed = step === "reconnect";
+
+ return (
+ <div
+ id={id}
+ role="status"
+ data-provider-connect=""
+ className={cn(
+ "mx-4 max-w-3xl rounded-xl sm:mx-auto sm:w-full border bg-card text-card-foreground shadow-sm",
+ className,
+ )}
+ >
+ <div className="flex items-center gap-3 px-3 py-2.5">
+ <SettingsEntityIcon icon={definition.icon} />
+ <p className="min-w-0 flex-1 text-sm leading-5">
+ {lapsed
+ ? t("Reconnect {provider} to keep chatting with {bot}", {
+ provider: definition.label,
+ bot: botName,
+ })
+ : t("Connect {provider} to chat with {bot}", {
+ provider: definition.label,
+ bot: botName,
+ })}
+ </p>
+ {signingIn ? null : (
+ <Button
+ size="xs"
+ disabled={accounts.busyProvider !== null}
+ onClick={() => void accounts.connect(definition)}
+ >
+ {accounts.busyProvider === provider ? (
+ <LoaderIcon className="size-3.5 animate-spin" />
+ ) : null}
+ {lapsed ? t("Reconnect") : t("Connect")}
+ </Button>
+ )}
+ </div>
+ {accounts.activeLogin ? (
+ <div className="border-t">
+ <ActiveLoginPanel
+ login={accounts.activeLogin}
+ pastedCode={accounts.pastedCode}
+ onPastedCodeChange={accounts.setPastedCode}
+ onComplete={() => void accounts.complete()}
+ onCancel={() => void accounts.cancelLogin()}
+ completing={accounts.completing}
+ />
+ </div>
+ ) : accounts.keyProvider ? (
+ <div className="border-t pt-3">
+ <ProviderApiKeyForm
+ supportsBaseUrl={providerSupportsBaseUrl(accounts.keyProvider.id)}
+ apiKey={accounts.pastedCode}
+ baseUrl={accounts.baseUrl}
+ busy={accounts.completing}
+ error={accounts.error}
+ onKeyChange={accounts.setPastedCode}
+ onBaseUrlChange={accounts.setBaseUrl}
+ onSave={() => void accounts.saveApiKey()}
+ onCancel={accounts.closeApiKey}
+ />
+ </div>
+ ) : accounts.error ? (
+ <p role="alert" className="border-t px-3 py-2 text-xs text-destructive">
+ {accounts.error}
+ </p>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/roster/BotComposerModelControl.test.tsx b/apps/web/src/components/roster/BotComposerModelControl.test.tsx
deleted file mode 100644
index 13ccd781b..000000000
--- a/apps/web/src/components/roster/BotComposerModelControl.test.tsx
+++ /dev/null
@@ -1,239 +0,0 @@
-import type { TestValue } from "../test-support/reactTree";
-import { decodeServerProvider } from "../test-support/fixtures";
-import { Predicate } from "effect";
-import {
- DEFAULT_UNIFIED_SETTINGS,
- EnvironmentId,
- ProviderDriverKind,
- ProviderInstanceId,
- type ModelCapabilities,
- type ServerProvider,
-} from "@akeru/contracts";
-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
-
-import { visitElements } from "../test-support/reactTree";
-import { reactHookHarness as hooks } from "../../test/reactHookHarness";
-import type { Bot } from "./types";
-
-const atoms = vi.hoisted(() => ({
- providers: Symbol("providers"),
- keybindings: Symbol("keybindings"),
- update: Symbol("botUpdate"),
-}));
-
-const state = vi.hoisted(() => ({
- bots: [] as Bot[],
- providers: [] as ServerProvider[],
- updateBot: vi.fn(),
-}));
-
-vi.mock("react", async (importOriginal) => {
- const actual = await importOriginal<typeof import("react")>();
- const { reactHookHarness } = await import("../../test/reactHookHarness");
-
- return {
- ...actual,
- useCallback: reactHookHarness.useCallback,
- useEffect: () => {},
- useMemo: reactHookHarness.useMemo,
- useRef: reactHookHarness.useRef,
- useState: reactHookHarness.useState,
- };
-});
-
-vi.mock("react/compiler-runtime", async () => {
- const { reactHookHarness } = await import("../../test/reactHookHarness");
-
- return { c: reactHookHarness.useMemoCache };
-});
-
-vi.mock("@effect/atom-react", () => ({
- useAtomValue: (atom: symbol) => (atom === atoms.providers ? state.providers : []),
-}));
-
-vi.mock("../../state/server", () => ({
- primaryServerProvidersAtom: atoms.providers,
- primaryServerKeybindingsAtom: atoms.keybindings,
-}));
-
-vi.mock("../../state/bots", () => ({ botEnvironment: { update: atoms.update } }));
-
-vi.mock("../../state/environments", () => ({
- usePrimaryEnvironmentId: () => EnvironmentId.make("environment-1"),
-}));
-
-vi.mock("../../state/use-atom-command", () => ({
- useAtomCommand: (atom: symbol) => (atom === atoms.update ? state.updateBot : vi.fn()),
-}));
-
-vi.mock("../../hooks/useSettings", () => ({
- usePrimarySettings: () => DEFAULT_UNIFIED_SETTINGS,
-}));
-
-vi.mock("./rosterStore", () => ({
- useRosterStore: <T,>(selector: (store: { bots: Bot[] }) => T) => selector({ bots: state.bots }),
-}));
-
-vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
-
-vi.mock("../../i18n", async () => {
- const { createTranslator } = await import("@akeru/client-runtime/i18n");
- const translator = createTranslator("en");
-
- return { useI18n: () => ({ ...translator, t: translator.translate }) };
-});
-
-import { BotComposerModelControl } from "./BotComposerModelControl";
-
-const reasoning = (levels: ReadonlyArray<string>): ModelCapabilities => ({
- optionDescriptors: [
- {
- id: "reasoningEffort",
- label: "Reasoning",
- type: "select",
- currentValue: "default",
- options: [
- { id: "default", label: "Provider default", isDefault: true },
- ...levels.map((id) => ({ id, label: id })),
- ],
- },
- ],
-});
-
-function provider(instance: string): ServerProvider {
- return decodeServerProvider({
- instanceId: ProviderInstanceId.make(instance),
- driver: ProviderDriverKind.make("codex"),
- enabled: true,
- installed: true,
- version: "1.0.0",
- status: "ready",
- auth: { status: "authenticated" },
- checkedAt: "2026-09-01T00:00:00.000Z",
- models: [
- {
- slug: "gpt-a",
- name: "A",
- isCustom: false,
- isDefault: true,
- capabilities: reasoning(["minimal", "high"]),
- },
- { slug: "gpt-b", name: "B", isCustom: false, capabilities: reasoning(["high"]) },
- ],
- slashCommands: [],
- skills: [],
- });
-}
-
-function makeBot(overrides: Partial<Bot> = {}): Bot {
- return {
- id: "bot-1",
- name: "Scout",
- title: "Scout",
- label: null,
- description: null,
- disabledMcpServerIds: [],
- avatar: { kind: "blob", shape: "circle", color: "#2E8EFF" },
- engine: {
- provider: "codex",
- model: "gpt-a",
- options: [{ id: "reasoningEffort", value: "minimal" }],
- },
- sandbox: "local",
- runtimeMode: "full-access",
- personalityTone: 50,
- voiceEnabled: false,
- imageProvider: null,
- groupId: null,
- pinned: false,
- archivedAt: null,
- createdAt: "2026-09-01T00:00:00.000Z",
- updatedAt: "2026-09-01T00:00:00.000Z",
- ...overrides,
- };
-}
-
-function render(botId = "bot-1", disabled = false): TestValue {
- hooks.beginRender();
-
- return BotComposerModelControl({ botId, disabled }) as TestValue;
-}
-
-function traitsPicker(tree: TestValue) {
- return visitElements(tree, (element) => Predicate.isFunction(element.props.onModelOptionsChange));
-}
-
-function modelPicker(tree: TestValue) {
- const picker = visitElements(tree, (element) =>
- Predicate.isFunction(element.props.onInstanceModelChange),
- );
-
- expect(picker).not.toBeNull();
-
- return picker!.props as {
- readonly disabled: boolean;
- readonly onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
- };
-}
-
-function savedEngine() {
- return state.updateBot.mock.calls.at(-1)?.[0];
-}
-
-describe("bot composer model control", () => {
- beforeEach(() => {
- hooks.reset();
- state.bots = [makeBot()];
- state.providers = [provider("codex"), provider("codex_work")];
- state.updateBot = vi.fn(async () => ({ _tag: "Success" }));
- });
-
- it("offers model selection without a composer reasoning control", () => {
- const tree = render();
-
- expect(traitsPicker(tree)).toBeNull();
- expect(modelPicker(tree).disabled).toBe(false);
- expect(state.updateBot).not.toHaveBeenCalled();
- });
-
- it("keeps supported choices across models on one instance and clears them across instances", () => {
- const picker = modelPicker(render());
-
- picker.onInstanceModelChange(ProviderInstanceId.make("codex"), "gpt-b");
- expect(savedEngine()?.input.engine).toEqual({ provider: "codex", model: "gpt-b" });
-
- state.bots = [
- makeBot({
- engine: {
- provider: "codex",
- model: "gpt-a",
- options: [{ id: "reasoningEffort", value: "high" }],
- },
- }),
- ];
- modelPicker(render()).onInstanceModelChange(ProviderInstanceId.make("codex"), "gpt-b");
- expect(savedEngine()?.input.engine).toEqual({
- provider: "codex",
- model: "gpt-b",
- options: [{ id: "reasoningEffort", value: "high" }],
- });
-
- modelPicker(render()).onInstanceModelChange(ProviderInstanceId.make("codex_work"), "gpt-a");
- expect(savedEngine()?.input.engine).toEqual({ provider: "codex_work", model: "gpt-a" });
- });
-
- it("hides the reasoning control in a read-only composer", () => {
- const tree = render("bot-1", true);
-
- expect(traitsPicker(tree)).toBeNull();
- expect(modelPicker(tree).disabled).toBe(true);
- });
-
- it("renders nothing for a group or archived bot, so no engine is written", () => {
- expect(render("group-1")).toBeNull();
-
- state.bots = [makeBot({ archivedAt: "2026-09-02T00:00:00.000Z" })];
- expect(render()).toBeNull();
- expect(state.updateBot).not.toHaveBeenCalled();
- });
-});
diff --git a/apps/web/src/components/roster/BotComposerModelControl.tsx b/apps/web/src/components/roster/BotComposerModelControl.tsx
index 18add9c12..9ce639879 100644
--- a/apps/web/src/components/roster/BotComposerModelControl.tsx
+++ b/apps/web/src/components/roster/BotComposerModelControl.tsx
@@ -1,34 +1,15 @@
-import { Predicate } from "effect";
import { useAtomValue } from "@effect/atom-react";
-import { BotId, ProviderInstanceId, type BotEngine } from "@akeru/contracts";
-import { useEffect, useMemo, useState } from "react";
+import { useNavigate } from "@tanstack/react-router";
+import { useEffect } from "react";
-import { usePrimarySettings } from "../../hooks/useSettings";
-import { useI18n } from "../../i18n";
-import { resolveShortcutCommand } from "../../keybindings";
-import {
- getCustomModelOptionsByInstance,
- resolveAppModelSelectionState,
-} from "../../modelSelection";
-import {
- applyProviderInstanceSettings,
- deriveProviderInstanceEntries,
- sortProviderInstanceEntries,
-} from "../../providerInstances";
import { registerComposerModelPicker } from "../../composerModelPickerRegistry";
-import { botEnvironment } from "../../state/bots";
-import { usePrimaryEnvironmentId } from "../../state/environments";
-import { primaryServerKeybindingsAtom, primaryServerProvidersAtom } from "../../state/server";
-import { useAtomCommand } from "../../state/use-atom-command";
-import { ProviderModelPicker } from "../chat/ProviderModelPicker";
-import { toastManager } from "../ui/toast";
-import { botEngineForModelPick, resolveStickyBotEngine } from "./botEngineSelection";
-import { useRosterStore } from "./rosterStore";
+import { resolveShortcutCommand } from "../../keybindings";
+import { primaryServerKeybindingsAtom } from "../../state/server";
/**
- * The bot's engine at the composer: shows which model answers the next message
- * and opens the shared model picker. Model changes retain the bot's saved
- * reasoning when the selected model supports it.
+ * Renders nothing. The model belongs to the bot, so the chat shows no picker.
+ * The model shortcut and the command palette's "Change model" open the bot's
+ * settings at the Model section instead.
*/
export function BotComposerModelControl({
botId,
@@ -37,116 +18,37 @@ export function BotComposerModelControl({
readonly botId: string;
readonly disabled?: boolean;
}) {
- const { t } = useI18n();
- const bot = useRosterStore((state) => state.bots.find((candidate) => candidate.id === botId));
- const environmentId = usePrimaryEnvironmentId();
- const providers = useAtomValue(primaryServerProvidersAtom);
+ const navigate = useNavigate();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
- const settings = usePrimarySettings();
- const updateBot = useAtomCommand(botEnvironment.update, { reportFailure: false });
- const [pickerOpen, setPickerOpen] = useState(false);
-
- const instanceEntries = useMemo(
- () =>
- sortProviderInstanceEntries(
- applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings),
- ),
- [providers, settings],
- );
-
- const defaultSelection = useMemo(
- () => resolveAppModelSelectionState(settings, providers),
- [providers, settings],
- );
-
- const selection = useMemo(
- () =>
- resolveStickyBotEngine({
- engine: bot?.engine ?? null,
- instanceEntries,
- settings,
- providers,
- defaultSelection,
- }),
- [bot?.engine, defaultSelection, instanceEntries, providers, settings],
- );
-
- const modelOptionsByInstance = useMemo(
- () =>
- getCustomModelOptionsByInstance(
- settings,
- providers,
- selection?.instanceId ?? null,
- selection?.model ?? null,
- ),
- [providers, selection?.instanceId, selection?.model, settings],
- );
- const selectable = selection !== null && !disabled;
useEffect(() => {
- if (!selectable) return;
+ if (disabled) return;
- return registerComposerModelPicker({ openModelPicker: () => setPickerOpen(true) });
- }, [selectable]);
+ const openModelSettings = () =>
+ void navigate({ to: "/bots/$botId/settings", params: { botId }, hash: "model" });
- useEffect(() => {
- if (!selectable) return;
+ const unregister = registerComposerModelPicker({ openModelPicker: openModelSettings });
const onKeyDown = (event: KeyboardEvent) => {
if (event.defaultPrevented || event.repeat) return;
const command = resolveShortcutCommand(event, keybindings, {
- context: { modelPickerOpen: pickerOpen },
+ context: { modelPickerOpen: false },
});
if (command !== "modelPicker.toggle") return;
event.preventDefault();
event.stopPropagation();
- setPickerOpen((open) => !open);
+ openModelSettings();
};
window.addEventListener("keydown", onKeyDown);
- return () => window.removeEventListener("keydown", onKeyDown);
- }, [keybindings, pickerOpen, selectable]);
-
- // Only a live bot's own composer edits an engine; a group or archived bot never does.
- if (selection === null || !bot || bot.archivedAt !== null) return null;
-
- const saveEngine = async (engine: BotEngine, failureTitle: string) => {
- if (environmentId === null) return;
-
- const result = await updateBot({
- environmentId,
- input: { botId: BotId.make(bot.id), engine },
- });
-
- if (Predicate.isTagged(result, "Failure")) {
- toastManager.add({ type: "error", title: failureTitle });
- }
- };
+ return () => {
+ unregister();
+ window.removeEventListener("keydown", onKeyDown);
+ };
+ }, [botId, disabled, keybindings, navigate]);
- return (
- <ProviderModelPicker
- activeInstanceId={ProviderInstanceId.make(selection.instanceId)}
- model={selection.model}
- lockedProvider={null}
- lockedContinuationGroupKey={null}
- instanceEntries={instanceEntries}
- keybindings={keybindings}
- modelOptionsByInstance={modelOptionsByInstance}
- compact
- disabled={disabled}
- open={pickerOpen}
- triggerAriaLabel={t("Change model")}
- triggerFit="capped"
- onOpenChange={setPickerOpen}
- onInstanceModelChange={(instanceId, model) => {
- void saveEngine(
- botEngineForModelPick({ previous: selection, instanceId, model, instanceEntries }),
- t("Could not change the model"),
- );
- }}
- />
- );
+ return null;
}
diff --git a/apps/web/src/components/roster/BotPromptComposer.tsx b/apps/web/src/components/roster/BotPromptComposer.tsx
index d9f9acd0f..6c8f594f6 100644
--- a/apps/web/src/components/roster/BotPromptComposer.tsx
+++ b/apps/web/src/components/roster/BotPromptComposer.tsx
@@ -362,9 +362,7 @@ export function BotPromptComposer({
/>
</ComposerBanner.Dock>
{composerBotId !== null ? (
- <div className="mb-1 flex min-w-0 items-center px-1" data-testid="bot-composer-model">
- <BotComposerModelControl botId={composerBotId} disabled={readOnly} />
- </div>
+ <BotComposerModelControl botId={composerBotId} disabled={readOnly} />
) : null}
<AnimatePresence initial={false}>
{activitySlot ? (
diff --git a/apps/web/src/components/roster/BotThreadLanding.tsx b/apps/web/src/components/roster/BotThreadLanding.tsx
index cbbabf844..5f73796b2 100644
--- a/apps/web/src/components/roster/BotThreadLanding.tsx
+++ b/apps/web/src/components/roster/BotThreadLanding.tsx
@@ -42,7 +42,9 @@ import {
isBotConversationWorking,
visibleBotChatMessages,
} from "./botConversationPresentation";
-import { botEngineFailureContext } from "./botEngineSelection";
+import { botEngineFailureContext, botEngineSubscriptionToConnect } from "./botEngineSelection";
+import { ProviderConnectCard, providerConnectStep } from "../chat/ProviderConnectCard";
+import { useSubscriptionStatuses } from "../settings/ProvidersPanel";
import { BotTurnFailureRow } from "./BotTurnFailureRow";
import { useBotEngineAvailability } from "./useBotEngineAvailability";
import { BotPromptComposer } from "./BotPromptComposer";
@@ -134,6 +136,19 @@ export function BotThreadLanding({
runtime.failure?.providerInstanceId,
);
+ const { statusByProvider: subscriptionStatuses } = useSubscriptionStatuses(environmentId);
+
+ const subscriptionToConnect = botEngineSubscriptionToConnect(
+ stickyEngine,
+ instanceEntries,
+ sendBlocked ? engineUnavailability?.reason : runtime.failure?.unavailability,
+ );
+
+ // Signing in fixes this chat, so the connect card replaces the failure copy.
+ const connectNeeded =
+ subscriptionToConnect !== null &&
+ providerConnectStep(subscriptionStatuses.get(subscriptionToConnect)) !== null;
+
const openBotSettings = () => void navigate({ to: "/bots/$botId/settings", params: { botId } });
const approvalState = useRosterPendingApproval(runtime.linkedThreadRef);
const enableAutoReview = useEnableBotAutoReview();
@@ -530,9 +545,19 @@ export function BotThreadLanding({
onOpenDetails={() => openSettings("advanced", "errors", environmentId)}
/>
<ThreadRuntimeWarningBanner warning={runtimeWarning} />
+ {connectNeeded && subscriptionToConnect ? (
+ <ProviderConnectCard
+ id={engineNoticeId}
+ environmentId={environmentId}
+ provider={subscriptionToConnect}
+ botName={bot.name}
+ className="mt-2"
+ />
+ ) : null}
<ThreadErrorBanner
threadKey={`${runtime.linkedThreadRef?.environmentId ?? environmentId ?? "unknown"}:${runtime.linkedThreadRef?.threadId ?? bot.id}`}
error={
+ connectNeeded ||
inboxItems.some((item) => item.lastFailure === runtime.error) ||
(sendBlocked && runtime.failure?.unavailability === engineUnavailability?.reason)
? null
@@ -610,7 +635,7 @@ export function BotThreadLanding({
return sent;
}}
/>
- {sendBlocked && engineUnavailability ? (
+ {connectNeeded ? null : sendBlocked && engineUnavailability ? (
<ProviderUnavailableLine
provider={engineUnavailability.provider}
id={engineNoticeId}
diff --git a/apps/web/src/components/roster/GroupThreadLanding.tsx b/apps/web/src/components/roster/GroupThreadLanding.tsx
index 367d96b0e..bee5a0910 100644
--- a/apps/web/src/components/roster/GroupThreadLanding.tsx
+++ b/apps/web/src/components/roster/GroupThreadLanding.tsx
@@ -55,7 +55,13 @@ import {
} from "./BotChatMessageRows";
import { useBotPromptMentionScope } from "./BotPromptMentions";
import { BotTurnFailureRow } from "./BotTurnFailureRow";
-import { botEngineFailureContext, botEngineTakesDelegatedWork } from "./botEngineSelection";
+import {
+ botEngineFailureContext,
+ botEngineSubscriptionToConnect,
+ botEngineTakesDelegatedWork,
+} from "./botEngineSelection";
+import { ProviderConnectCard, providerConnectStep } from "../chat/ProviderConnectCard";
+import { useSubscriptionStatuses } from "../settings/ProvidersPanel";
import { buildBotStepMeters } from "@akeru/client-runtime/bot-step-usage";
import { useGroupPresence } from "./botPresence";
import { groupBotMembers, isCurrentGroupPerson } from "./roster.logic";
@@ -133,12 +139,45 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
const boss = group ? resolveAvailableGroupBoss(members, group.bossBotId) : null;
// The boss answers a group message first, so its provider's skills label sent messages.
- const bossCatalog = useBotEngineAvailability(boss?.engine ?? null).catalog;
+ const bossEngine = useBotEngineAvailability(boss?.engine ?? null);
+ const bossCatalog = bossEngine.catalog;
// A mention sends the draft to that member, so the `$` and `/` pickers offer its provider's catalog.
const [addressedBotId, setAddressedBotId] = useState<string | null>(null);
const addressedBot = resolveGroupAddressedBot(members, boss, addressedBotId);
const composerCatalog = useBotEngineAvailability(addressedBot?.engine ?? null).catalog;
const noProviderNoticeId = useId();
+ // Signing in fixes a reply that failed on a missing account, or a boss that
+ // cannot answer yet, so the connect card replaces the failure copy.
+ const { statusByProvider: subscriptionStatuses } = useSubscriptionStatuses(environmentId);
+
+ const failedConnect = respondingBot
+ ? botEngineSubscriptionToConnect(
+ respondingEngine.selection,
+ respondingEngine.instanceEntries,
+ runtime.failure?.unavailability,
+ )
+ : null;
+
+ // A turn error that signing in cannot fix stays visible instead of the boss's card.
+ const bossConnect =
+ boss && !runtime.providerAvailable && !runtime.error
+ ? botEngineSubscriptionToConnect(
+ bossEngine.selection,
+ bossEngine.instanceEntries,
+ bossEngine.unavailability?.reason,
+ )
+ : null;
+
+ const connect =
+ failedConnect && respondingBot
+ ? { provider: failedConnect, botName: respondingBot.name }
+ : bossConnect && boss
+ ? { provider: bossConnect, botName: boss.name }
+ : null;
+
+ const connectNeeded =
+ connect !== null && providerConnectStep(subscriptionStatuses.get(connect.provider)) !== null;
+
const replyPlayback = useOptionalReplyPlayback();
const voiceCall = useOptionalVoiceCall();
const [replyTarget, setReplyTarget] = useState<MessageReplyTarget | null>(null);
@@ -399,10 +438,21 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
onOpenDetails={() => openSettings("advanced", "errors", environmentId)}
/>
<ThreadRuntimeWarningBanner warning={runtimeWarning} />
+ {connectNeeded && connect ? (
+ <ProviderConnectCard
+ id={noProviderNoticeId}
+ environmentId={environmentId}
+ provider={connect.provider}
+ botName={connect.botName}
+ className="mt-2"
+ />
+ ) : null}
<ThreadErrorBanner
threadKey={`${runtime.linkedThreadRef?.environmentId ?? environmentId ?? "unknown"}:${runtime.linkedThreadRef?.threadId ?? group.id}`}
error={
- inboxItems.some((item) => item.lastFailure === runtime.error) ? null : runtime.error
+ connectNeeded || inboxItems.some((item) => item.lastFailure === runtime.error)
+ ? null
+ : runtime.error
}
context={failureContext}
environmentId={environmentId}
@@ -501,7 +551,7 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
return sent;
}}
/>
- {!runtime.providerAvailable ? (
+ {!runtime.providerAvailable && !connectNeeded ? (
<ProviderUnavailableLine
id={noProviderNoticeId}
presentation={{
diff --git a/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx b/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
index d649e6d1f..6482f1af8 100644
--- a/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
+++ b/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
@@ -116,6 +116,10 @@ vi.mock("../../state/entities", () => ({
vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: { inbox: [] } }) }));
+vi.mock("../settings/ProvidersPanel", () => ({
+ useSubscriptionStatuses: () => ({ statusByProvider: new Map() }),
+}));
+
vi.mock("../../state/server", () => ({
primaryServerProvidersAtom: mocks.providersAtom,
serverEnvironment: { subscriptionAuth: () => null, routineThreadRuns: () => null },
diff --git a/apps/web/src/components/roster/ThreadLanding.hookOrder.test.tsx b/apps/web/src/components/roster/ThreadLanding.hookOrder.test.tsx
index 8218459c5..00a34d1ac 100644
--- a/apps/web/src/components/roster/ThreadLanding.hookOrder.test.tsx
+++ b/apps/web/src/components/roster/ThreadLanding.hookOrder.test.tsx
@@ -98,6 +98,10 @@ vi.mock("../../state/query", () => ({
useEnvironmentQuery: () => ({ data: mocks.queryData, refresh: mocks.refreshHistory }),
}));
+vi.mock("../settings/ProvidersPanel", () => ({
+ useSubscriptionStatuses: () => ({ statusByProvider: new Map() }),
+}));
+
vi.mock("../../state/server", () => ({
primaryServerProvidersAtom: null,
serverEnvironment: { subscriptionAuth: () => null, routineThreadRuns: () => null },
diff --git a/apps/web/src/components/roster/botEngineSelection.test.ts b/apps/web/src/components/roster/botEngineSelection.test.ts
index cae1699a6..081427644 100644
--- a/apps/web/src/components/roster/botEngineSelection.test.ts
+++ b/apps/web/src/components/roster/botEngineSelection.test.ts
@@ -16,6 +16,7 @@ import {
botEngineFailureContext,
botEngineForModelPick,
botEngineForOptions,
+ botEngineSubscriptionToConnect,
botEngineTakesDelegatedWork,
botEngineUnavailability,
resolveStickyBotEngine,
@@ -113,7 +114,7 @@ describe("resolveStickyBotEngine", () => {
expect(
botEngineUnavailability({ instanceId, model: "gpt-4-retired" }, signedIn, zh),
).toMatchObject({
- title: expect.stringMatching(/^gpt-4-retired 在 .+ 上不可用$/),
+ title: expect.stringMatching(/^GPT-4 Retired 在 .+ 上不可用$/),
description: "请为此机器人选择其他模型。",
});
expect(botEngineUnavailability(null, signedIn, zh)).toMatchObject({
@@ -362,6 +363,31 @@ describe("botEngineFailureContext", () => {
});
});
+describe("botEngineSubscriptionToConnect", () => {
+ const instanceEntries = deriveProviderInstanceEntries([makeComposerTestProvider()]);
+ const codex = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" };
+
+ it("names the subscription when signing in is the fix", () => {
+ expect(botEngineSubscriptionToConnect(codex, instanceEntries, "missing-login")).toBe(
+ "openai-codex",
+ );
+ // An unconnected default instance is hidden from the client entirely.
+ expect(botEngineSubscriptionToConnect(codex, [], "missing-provider")).toBe("openai-codex");
+ });
+
+ it("leaves other failures and custom instances to the usual notice", () => {
+ expect(botEngineSubscriptionToConnect(codex, instanceEntries, "limit-reached")).toBeNull();
+ expect(botEngineSubscriptionToConnect(codex, instanceEntries, null)).toBeNull();
+ expect(
+ botEngineSubscriptionToConnect(
+ { instanceId: ProviderInstanceId.make("codex_work"), model: "gpt-5.6-sol" },
+ instanceEntries,
+ "missing-login",
+ ),
+ ).toBeNull();
+ });
+});
+
describe("botEngineTakesDelegatedWork", () => {
const instanceEntries = deriveProviderInstanceEntries([
makeComposerTestProvider(),
diff --git a/apps/web/src/components/roster/botEngineSelection.ts b/apps/web/src/components/roster/botEngineSelection.ts
index 0428b9158..667857749 100644
--- a/apps/web/src/components/roster/botEngineSelection.ts
+++ b/apps/web/src/components/roster/botEngineSelection.ts
@@ -1,5 +1,6 @@
import {
stockProviderAccountName,
+ defaultInstanceIdForDriver,
ProviderDriverKind,
ProviderInstanceId,
type BotEngine,
@@ -8,14 +9,17 @@ import {
type ProviderOptionSelection,
type ServerProvider,
type ServerProviderUnavailability,
+ type SubscriptionProviderId,
type UnifiedSettings,
} from "@akeru/contracts";
import { createTranslator } from "@akeru/client-runtime/i18n";
+import { SUBSCRIPTION_PROVIDER_BY_DRIVER } from "@akeru/client-runtime/provider-auth";
import { driverSupportsDelegation } from "@akeru/shared/delegationProviders";
import {
botEngineFromModelSelection,
botEngineModelSelection,
+ formatModelSlug,
providerOptionsForModelChange,
} from "@akeru/shared/model";
import type { ProviderAvailabilityTranslate } from "@akeru/client-runtime/provider-availability";
@@ -233,7 +237,8 @@ export function botEngineUnavailability(
const entry = instanceEntries.find((candidate) => candidate.instanceId === selection.instanceId);
const modelName =
- entry?.models.find((candidate) => candidate.slug === selection.model)?.name ?? selection.model;
+ entry?.models.find((candidate) => candidate.slug === selection.model)?.name ??
+ formatModelSlug(selection.model);
const unavailability = providerInstanceUnavailability(entry, {
model: selection.model,
@@ -247,6 +252,32 @@ export function botEngineUnavailability(
: null;
}
+const CONNECTABLE_REASONS: ReadonlySet<string> = new Set([
+ "missing-provider",
+ "disabled",
+ "missing-login",
+ "expired-login",
+]);
+
+/**
+ * The subscription to connect when signing in is what stands between a bot and
+ * its next reply. Only default instances qualify: they run on the account the
+ * user connects in Settings, while custom instances bring their own credentials.
+ */
+export function botEngineSubscriptionToConnect(
+ selection: ModelSelection | null,
+ instanceEntries: ReadonlyArray<ProviderInstanceEntry>,
+ reason: string | null | undefined,
+): SubscriptionProviderId | null {
+ if (!selection || !reason || !CONNECTABLE_REASONS.has(reason)) return null;
+ const entry = instanceEntries.find((candidate) => candidate.instanceId === selection.instanceId);
+ const driver = entry?.driverKind ?? ProviderDriverKind.make(selection.instanceId);
+
+ if (selection.instanceId !== defaultInstanceIdForDriver(driver)) return null;
+
+ return SUBSCRIPTION_PROVIDER_BY_DRIVER.get(driver) ?? null;
+}
+
/**
* What a chat's failure copy needs to name the provider and model that failed,
* plus the Providers page that fixes it. A failure that recorded its instance
@@ -271,7 +302,9 @@ export function botEngineFailureContext(
unavailability: unavailability ?? null,
providerName: instanceId ? botProviderName(instanceId, entry) : null,
provider: instanceId ? botProviderCatalogEntry(instanceId, entry) : null,
- modelName: entry?.models.find((candidate) => candidate.slug === model)?.name ?? model ?? null,
+ modelName:
+ entry?.models.find((candidate) => candidate.slug === model)?.name ??
+ (model ? formatModelSlug(model) : null),
};
}
diff --git a/apps/web/src/components/settings/ProviderAccountControls.tsx b/apps/web/src/components/settings/ProviderAccountControls.tsx
index efb99f023..7ad573b62 100644
--- a/apps/web/src/components/settings/ProviderAccountControls.tsx
+++ b/apps/web/src/components/settings/ProviderAccountControls.tsx
@@ -9,7 +9,7 @@ import { ProviderAccessDetails } from "./ProviderAccessDetails";
import { accountConnectionState } from "./providerStatus";
import { SignInCodeCopy } from "./SignInCodeCopy";
import { SettingsRow } from "./settingsLayout";
-import type { SubscriptionProviderDefinition } from "./subscriptionProviders";
+import { linkedAccountTitle, type SubscriptionProviderDefinition } from "./subscriptionProviders";
import type { ActiveLogin } from "./useSubscriptionAccounts";
export type Translate = ReturnType<typeof useI18n>["t"];
@@ -33,7 +33,7 @@ function disconnectDescription(
: t("{names} use this account.", { names });
}
-function BusyIcon({ busy, idle }: { readonly busy: boolean; readonly idle?: ReactNode }) {
+export function BusyIcon({ busy, idle }: { readonly busy: boolean; readonly idle?: ReactNode }) {
if (busy) return <LoaderIcon className="size-3.5 animate-spin" />;
return idle ?? null;
@@ -79,8 +79,9 @@ export function ProviderAccountRows({
<SettingsRow
title={t("Connected account")}
description={
- status.accountLabel ??
- (usesKey ? t("API key saved on this environment") : t("Account identity unavailable"))
+ usesKey
+ ? t("API key saved on this environment")
+ : linkedAccountTitle(definition, status, t)
}
/>
) : null}
diff --git a/apps/web/src/components/settings/ProviderDetailPage.tsx b/apps/web/src/components/settings/ProviderDetailPage.tsx
index c45b01e61..8125a9210 100644
--- a/apps/web/src/components/settings/ProviderDetailPage.tsx
+++ b/apps/web/src/components/settings/ProviderDetailPage.tsx
@@ -5,6 +5,7 @@ import { useSettingsEnvironmentId } from "../../settingsDialogStore";
import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
import { PROVIDER_CATALOG, type ProviderCatalogEntry } from "./providerCatalog";
import { ProviderInstancesSection } from "./ProviderInstancesSection";
+import { ProviderAccountsSection } from "./ProviderLinkedAccounts";
import { ProviderAccountSection, useSubscriptionStatuses } from "./ProvidersPanel";
import {
accountConnectionState,
@@ -152,7 +153,10 @@ function ConnectedProviderDetail({
plan={plans.get(entry.slug) ?? translate(entry.planHint)}
/>
{entry.account ? (
- <ProviderAccountSection environmentId={environmentId} definition={entry.account} />
+ <>
+ <ProviderAccountSection environmentId={environmentId} definition={entry.account} />
+ <ProviderAccountsSection environmentId={environmentId} definition={entry.account} />
+ </>
) : null}
<ProviderInstancesSection
environmentId={environmentId}
diff --git a/apps/web/src/components/settings/ProviderInstancesSection.tsx b/apps/web/src/components/settings/ProviderInstancesSection.tsx
index c64b19594..f29fcec00 100644
--- a/apps/web/src/components/settings/ProviderInstancesSection.tsx
+++ b/apps/web/src/components/settings/ProviderInstancesSection.tsx
@@ -347,7 +347,7 @@ export function ProviderInstancesSection({
{addDriverOption ? (
<Button size="xs" variant="ghost-muted" onClick={() => setIsAddDialogOpen(true)}>
<PlusIcon className="size-3.5" />
- {t("Add account")}
+ {account ? t("Add separate account") : t("Add account")}
</Button>
) : null}
</div>
diff --git a/apps/web/src/components/settings/ProviderLinkedAccounts.tsx b/apps/web/src/components/settings/ProviderLinkedAccounts.tsx
new file mode 100644
index 000000000..951859fb1
--- /dev/null
+++ b/apps/web/src/components/settings/ProviderLinkedAccounts.tsx
@@ -0,0 +1,381 @@
+import {
+ ArrowDownIcon,
+ ArrowUpIcon,
+ EllipsisIcon,
+ ExternalLinkIcon,
+ KeyRoundIcon,
+ LoaderIcon,
+ LogOutIcon,
+ PlusIcon,
+ RefreshCwIcon,
+} from "lucide-react";
+import { type ReactNode } from "react";
+import type { EnvironmentId, SubscriptionProviderStatus } from "@akeru/contracts";
+import type { MessageKey } from "@akeru/client-runtime/i18n";
+import { providerSupportsBaseUrl, providerUsesApiKey } from "@akeru/client-runtime/provider-auth";
+
+import { useI18n } from "../../i18n";
+import { cn } from "../../lib/utils";
+import { Button } from "../ui/button";
+import { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from "../ui/menu";
+import { ActiveLoginPanel, BusyIcon, ProviderApiKeyForm } from "./ProviderAccountControls";
+import { SettingsMessageRow } from "./settingsDetailLayout";
+import { SettingsSection } from "./settingsLayout";
+import { linkedAccountTitle, type SubscriptionProviderDefinition } from "./subscriptionProviders";
+import { useSubscriptionAccounts } from "./useSubscriptionAccounts";
+
+/** True while a linked account sits out a usage limit. */
+function accountResting(status: SubscriptionProviderStatus, now: number): boolean {
+ return status.nextRetryAt !== undefined && Date.parse(status.nextRetryAt) > now;
+}
+
+/** A reset time: the clock time when it is within the day, else the date. */
+function formatResetTime(iso: string, locale: string, now: number): string {
+ const at = new Date(iso);
+ const sameDay = at.getTime() - now < 20 * 60 * 60 * 1000;
+
+ return new Intl.DateTimeFormat(
+ locale,
+ sameDay ? { hour: "numeric", minute: "2-digit" } : { month: "short", day: "numeric" },
+ ).format(at);
+}
+
+type AccountState =
+ | { readonly kind: "checking" }
+ | { readonly kind: "resting"; readonly time: string }
+ | { readonly kind: "signed-out"; readonly label: MessageKey }
+ | { readonly kind: "unreachable" }
+ | { readonly kind: "in-use" }
+ | { readonly kind: "ready" };
+
+function linkedAccountState(
+ status: SubscriptionProviderStatus,
+ busy: boolean,
+ locale: string,
+ now: number,
+): AccountState {
+ if (busy || status.healthChecking === true) return { kind: "checking" };
+
+ if (status.nextRetryAt && accountResting(status, now)) {
+ return { kind: "resting", time: formatResetTime(status.nextRetryAt, locale, now) };
+ }
+
+ if (status.health === "expired") return { kind: "signed-out", label: "Login expired" };
+
+ if (status.health === "revoked") {
+ return {
+ kind: "signed-out",
+ label: providerUsesApiKey(status) ? "Key rejected" : "Signed out",
+ };
+ }
+
+ if (status.health === "failed" || status.health === "failed-first-request") {
+ return { kind: "unreachable" };
+ }
+
+ return status.active ? { kind: "in-use" } : { kind: "ready" };
+}
+
+/**
+ * One linked account in priority order: its place in line, its tier, what it
+ * is doing now, and the one action that fixes it when it is not working.
+ */
+function LinkedAccountCard({
+ definition,
+ status,
+ position,
+ count,
+ busy,
+ disabled,
+ onMove,
+ onReconnect,
+ onRetry,
+ onRemove,
+}: {
+ readonly definition: SubscriptionProviderDefinition;
+ readonly status: SubscriptionProviderStatus;
+ readonly position: number;
+ readonly count: number;
+ readonly busy: boolean;
+ readonly disabled: boolean;
+ readonly onMove: (offset: -1 | 1) => void;
+ readonly onReconnect: () => void;
+ readonly onRetry: () => void;
+ readonly onRemove: () => void;
+}) {
+ const { t, locale } = useI18n();
+ const usesKey = providerUsesApiKey(status);
+ const title = linkedAccountTitle(definition, status, t);
+ const state = linkedAccountState(status, busy, locale, Date.now());
+ const reconnectLabel = usesKey ? t("Replace key") : t("Sign in again");
+
+ const role =
+ count > 1
+ ? position === 0
+ ? t("Main account")
+ : t("Backup {number}", { number: String(position) })
+ : null;
+
+ let stateText: ReactNode;
+
+ switch (state.kind) {
+ case "checking":
+ stateText = (
+ <span className="inline-flex items-center gap-1 text-muted-foreground">
+ <LoaderIcon className="size-3 animate-spin" />
+ {t("Checking sign-in")}
+ </span>
+ );
+ break;
+ case "resting":
+ stateText = (
+ <span className="text-warning-foreground">
+ {t("Usage limit reached, back at {time}", { time: state.time })}
+ </span>
+ );
+ break;
+ case "signed-out":
+ stateText = <span className="text-destructive-foreground">{t(state.label)}</span>;
+ break;
+ case "unreachable":
+ stateText = (
+ <span className="text-destructive-foreground">
+ {t("Can't reach {provider}", { provider: definition.label })}
+ </span>
+ );
+ break;
+ case "in-use":
+ stateText = <span className="text-success-foreground">{t("In use")}</span>;
+ break;
+ case "ready":
+ stateText = <span className="text-muted-foreground">{t("Ready")}</span>;
+ break;
+ }
+
+ let fix: ReactNode = null;
+
+ if (state.kind === "signed-out") {
+ fix = (
+ <Button size="xs" variant="outline" disabled={disabled} onClick={onReconnect}>
+ {reconnectLabel}
+ </Button>
+ );
+ } else if (state.kind === "unreachable") {
+ fix = (
+ <Button size="xs" variant="outline" disabled={disabled} onClick={onRetry}>
+ <RefreshCwIcon className="size-3.5" />
+ {t("Try again")}
+ </Button>
+ );
+ }
+
+ return (
+ <div
+ data-settings-row=""
+ data-account-id={status.accountId}
+ className="flex items-center gap-3 rounded-xl px-3 py-3 sm:px-4"
+ >
+ <span
+ aria-hidden
+ className={cn(
+ "flex size-6 shrink-0 items-center justify-center rounded-full text-xs font-medium tabular-nums",
+ state.kind === "in-use"
+ ? "bg-foreground text-background"
+ : "bg-muted text-muted-foreground",
+ )}
+ >
+ {position + 1}
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium text-foreground">{title}</p>
+ <p className="truncate text-xs">
+ {role ? <span className="text-muted-foreground">{role} · </span> : null}
+ {stateText}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-0.5">
+ {fix ? <span className="mr-1.5">{fix}</span> : null}
+ {count > 1 ? (
+ <>
+ <Button
+ size="icon-xs"
+ variant="ghost-muted"
+ aria-label={t("Move {account} up", { account: title })}
+ disabled={disabled || position === 0}
+ onClick={() => onMove(-1)}
+ >
+ <ArrowUpIcon className="size-3.5" />
+ </Button>
+ <Button
+ size="icon-xs"
+ variant="ghost-muted"
+ aria-label={t("Move {account} down", { account: title })}
+ disabled={disabled || position === count - 1}
+ onClick={() => onMove(1)}
+ >
+ <ArrowDownIcon className="size-3.5" />
+ </Button>
+ </>
+ ) : null}
+ <Menu>
+ <MenuTrigger
+ render={
+ <Button
+ size="icon-xs"
+ variant="ghost-muted"
+ aria-label={t("Actions for {name}", { name: title })}
+ disabled={disabled}
+ />
+ }
+ >
+ <EllipsisIcon className="size-3.5" />
+ </MenuTrigger>
+ <MenuPopup align="end" className="min-w-40">
+ <MenuItem onClick={onReconnect}>
+ <KeyRoundIcon />
+ {reconnectLabel}
+ </MenuItem>
+ <MenuSeparator />
+ <MenuItem variant="destructive" onClick={onRemove}>
+ <LogOutIcon />
+ {t("Remove")}
+ </MenuItem>
+ </MenuPopup>
+ </Menu>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Accounts section of a provider subpage. Lists every linked account in the
+ * order bots use them: the first ready one serves requests, and one that hits
+ * a usage limit sits out while the next takes over. Hidden until an account
+ * is linked, since the Account section above handles the first sign-in.
+ */
+export function ProviderAccountsSection({
+ environmentId,
+ definition,
+}: {
+ readonly environmentId: EnvironmentId | null;
+ readonly definition: SubscriptionProviderDefinition;
+}) {
+ const { t } = useI18n();
+ const accounts = useSubscriptionAccounts(environmentId);
+
+ const linked = (accounts.statusQuery.data?.linkedAccounts ?? []).filter(
+ (status) => status.provider === definition.id && status.accountId !== undefined,
+ );
+
+ const keyOnly = definition.id === "opencode-go";
+ const locked = accounts.busyProvider !== null;
+ const adding = accounts.keyProvider !== null || accounts.activeLogin !== null;
+
+ if (environmentId === null || (linked.length === 0 && !adding)) return null;
+
+ const move = (index: number, offset: -1 | 1) => {
+ const ids = linked.map((entry) => entry.accountId!);
+ const [moved] = ids.splice(index, 1);
+ ids.splice(index + offset, 0, moved!);
+ void accounts.setAccountOrder(definition.id, ids);
+ };
+
+ const addButton = keyOnly ? (
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={locked || adding}
+ onClick={() => accounts.openApiKey(definition, { addAccount: true })}
+ >
+ <PlusIcon className="size-3.5" />
+ {t("Add account")}
+ </Button>
+ ) : (
+ <Menu>
+ <MenuTrigger render={<Button size="xs" variant="outline" disabled={locked || adding} />}>
+ <BusyIcon
+ busy={accounts.busyProvider === definition.id && accounts.busyAccount === null}
+ idle={<PlusIcon className="size-3.5" />}
+ />
+ {t("Add account")}
+ </MenuTrigger>
+ <MenuPopup align="end" className="min-w-44">
+ <MenuItem onClick={() => void accounts.connect(definition, { addAccount: true })}>
+ <ExternalLinkIcon />
+ {t("Sign in with {provider}", { provider: definition.label })}
+ </MenuItem>
+ <MenuItem onClick={() => accounts.openApiKey(definition, { addAccount: true })}>
+ <KeyRoundIcon />
+ {t("Use an API key")}
+ </MenuItem>
+ </MenuPopup>
+ </Menu>
+ );
+
+ let body: ReactNode;
+
+ if (accounts.keyProvider) {
+ body = (
+ <div data-settings-row="" className="rounded-xl pt-3">
+ <h3 className="px-3 pb-3 text-sm font-medium text-foreground sm:px-4">
+ {accounts.keyTarget.accountId ? t("Replace API key") : t("Add API key")}
+ </h3>
+ <ProviderApiKeyForm
+ supportsBaseUrl={providerSupportsBaseUrl(accounts.keyProvider.id)}
+ apiKey={accounts.pastedCode}
+ baseUrl={accounts.baseUrl}
+ busy={accounts.completing}
+ error={accounts.error}
+ onKeyChange={accounts.setPastedCode}
+ onBaseUrlChange={accounts.setBaseUrl}
+ onSave={() => void accounts.saveApiKey()}
+ onCancel={accounts.closeApiKey}
+ />
+ </div>
+ );
+ } else if (accounts.activeLogin) {
+ body = (
+ <ActiveLoginPanel
+ login={accounts.activeLogin}
+ pastedCode={accounts.pastedCode}
+ onPastedCodeChange={accounts.setPastedCode}
+ onComplete={() => void accounts.complete()}
+ onCancel={() => void accounts.cancelLogin()}
+ completing={accounts.completing}
+ />
+ );
+ } else {
+ body = (
+ <>
+ {accounts.error ? (
+ <SettingsMessageRow tone="error">{accounts.error}</SettingsMessageRow>
+ ) : null}
+ {linked.map((entry, index) => (
+ <LinkedAccountCard
+ key={entry.accountId}
+ definition={definition}
+ status={entry}
+ position={index}
+ count={linked.length}
+ busy={accounts.busyAccount === entry.accountId}
+ disabled={locked}
+ onMove={(offset) => move(index, offset)}
+ onReconnect={() =>
+ providerUsesApiKey(entry)
+ ? accounts.openApiKey(definition, { accountId: entry.accountId! })
+ : void accounts.connect(definition, { accountId: entry.accountId! })
+ }
+ onRetry={() => void accounts.testHealth(definition.id, entry.accountId)}
+ onRemove={() => void accounts.disconnect(definition.id, entry.accountId)}
+ />
+ ))}
+ </>
+ );
+ }
+
+ return (
+ <SettingsSection id="provider-accounts" title={t("Accounts")} headerAction={addButton}>
+ {body}
+ </SettingsSection>
+ );
+}
diff --git a/apps/web/src/components/settings/ProvidersPanel.test.tsx b/apps/web/src/components/settings/ProvidersPanel.test.tsx
index d247df82f..443765f92 100644
--- a/apps/web/src/components/settings/ProvidersPanel.test.tsx
+++ b/apps/web/src/components/settings/ProvidersPanel.test.tsx
@@ -70,7 +70,7 @@ describe("subscription providers", () => {
expect(markup).toContain("Check key");
expect(markup).toContain("Connected account");
- expect(markup).toContain("[email protected]");
+ expect(markup).not.toContain("[email protected]");
expect(markup).not.toContain("Check OAuth");
expect(markup).toContain("Saved · https://proxy.example/v1");
expect(markup).toContain("Replace key");
diff --git a/apps/web/src/components/settings/ProvidersPanel.zh-CN.test.tsx b/apps/web/src/components/settings/ProvidersPanel.zh-CN.test.tsx
index be29bb08c..c04a917a9 100644
--- a/apps/web/src/components/settings/ProvidersPanel.zh-CN.test.tsx
+++ b/apps/web/src/components/settings/ProvidersPanel.zh-CN.test.tsx
@@ -41,6 +41,7 @@ describe("provider account rows in Simplified Chinese", () => {
expect(html).not.toContain(label);
}
- expect(html).toContain("[email protected]");
+ expect(html).not.toContain("[email protected]");
+ expect(html).toContain("ChatGPT 账户");
});
});
diff --git a/apps/web/src/components/settings/SettingsPanels.zh-CN.test.tsx b/apps/web/src/components/settings/SettingsPanels.zh-CN.test.tsx
index 3ce7d364e..4ac136dc8 100644
--- a/apps/web/src/components/settings/SettingsPanels.zh-CN.test.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.zh-CN.test.tsx
@@ -153,12 +153,12 @@ describe("settings panels in Simplified Chinese", () => {
);
});
- it("translates the provider detail page and its instances", () => {
+ it("translates the provider detail page without instance configuration", () => {
environment.id = ENVIRONMENT_ID;
expectTranslated(
renderInChinese(<ProviderDetailPage entry={PROVIDER_CATALOG[0]!} />),
- [">配置<", "添加账户", "刷新 ChatGPT 状态", ">刷新<"],
- [">Configuration<", "Add account", ">Refresh<", "Refresh ChatGPT status"],
+ [">配置<", "添加单独账户", "刷新 ChatGPT 状态", ">刷新<"],
+ [">Configuration<", "Add separate account", ">Refresh<", "Refresh ChatGPT status"],
);
});
diff --git a/apps/web/src/components/settings/subscriptionProviders.ts b/apps/web/src/components/settings/subscriptionProviders.ts
index 15559fc72..ef37d852e 100644
--- a/apps/web/src/components/settings/subscriptionProviders.ts
+++ b/apps/web/src/components/settings/subscriptionProviders.ts
@@ -1,6 +1,8 @@
import type { MessageKey } from "@akeru/client-runtime/i18n";
-import type { SubscriptionProviderId } from "@akeru/contracts";
+import { providerUsesApiKey } from "@akeru/client-runtime/provider-auth";
+import type { SubscriptionProviderId, SubscriptionProviderStatus } from "@akeru/contracts";
+import type { useI18n } from "../../i18n";
import { ClaudeAI, GrokIcon, KimiIcon, OpenAI, OpenCodeIcon, type Icon } from "../Icons";
export interface SubscriptionProviderDefinition {
@@ -12,6 +14,21 @@ export interface SubscriptionProviderDefinition {
readonly icon: Icon | string;
}
+/** An account's name in the list: its tier, such as "ChatGPT Pro", never its email. */
+export function linkedAccountTitle(
+ definition: SubscriptionProviderDefinition,
+ status: SubscriptionProviderStatus,
+ t: ReturnType<typeof useI18n>["t"],
+): string {
+ if (definition.id === "opencode-go") return definition.label;
+
+ if (providerUsesApiKey(status)) return t("API key");
+
+ return status.plan
+ ? `${definition.label} ${status.plan}`
+ : t("{provider} account", { provider: definition.label });
+}
+
/** Row anchor in Providers settings, so other pages can open Settings on one provider. */
export function subscriptionProviderTargetId(id: SubscriptionProviderId): string {
return `subscription-provider-${id}`;
diff --git a/apps/web/src/components/settings/useSubscriptionAccounts.ts b/apps/web/src/components/settings/useSubscriptionAccounts.ts
index 0e1d11947..0c9ae3ae5 100644
--- a/apps/web/src/components/settings/useSubscriptionAccounts.ts
+++ b/apps/web/src/components/settings/useSubscriptionAccounts.ts
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";
import type {
EnvironmentId,
ProviderInstanceId,
+ SubscriptionAccountId,
SubscriptionAuthLoginProgress,
SubscriptionAuthStartResult,
SubscriptionProviderId,
@@ -14,8 +15,10 @@ import {
type AtomCommandResult,
} from "@akeru/client-runtime/state/runtime";
import {
+ anyProviderHealthChecking,
apiKeyStartInput,
apiKeyValidationError,
+ HEALTH_CHECK_REFRESH_MS,
providerSupportsBaseUrl,
} from "@akeru/client-runtime/provider-auth";
import { useI18n } from "../../i18n";
@@ -55,9 +58,32 @@ export function useSubscriptionStatuses(environmentId: EnvironmentId | null) {
[statusQuery.data],
);
+ // The server checks health right after a login stores credentials and does
+ // not push the result, so refresh until it lands instead of sticking on
+ // "Checking access".
+ const { refresh } = statusQuery;
+
+ useEffect(() => {
+ const data = statusQuery.data;
+
+ if (!data || !anyProviderHealthChecking([...data.providers, ...data.linkedAccounts])) return;
+ const timer = setTimeout(refresh, HEALTH_CHECK_REFRESH_MS);
+
+ return () => clearTimeout(timer);
+ }, [refresh, statusQuery.data]);
+
return { statusQuery, statusByProvider };
}
+/**
+ * Which of a provider's linked accounts an action targets. Without one, the
+ * action uses the account bots are on now. `addAccount` signs in a new one.
+ */
+export interface SubscriptionAccountTarget {
+ readonly accountId?: SubscriptionAccountId;
+ readonly addAccount?: true;
+}
+
/** Sign-in, API key, check, and disconnect flows for subscription accounts. */
export function useSubscriptionAccounts(
environmentId: EnvironmentId | null,
@@ -90,6 +116,10 @@ export function useSubscriptionAccounts(
reportFailure: false,
});
+ const orderAuth = useAtomCommand(serverEnvironment.setSubscriptionAccountOrder, {
+ reportFailure: false,
+ });
+
const [activeLogin, setActiveLogin] = useState<ActiveLogin | null>(null);
const [busyProvider, setBusyProvider] = useState<SubscriptionProviderId | null>(null);
const [pastedCode, setPastedCode] = useState("");
@@ -97,6 +127,8 @@ export function useSubscriptionAccounts(
const [error, setError] = useState<string | null>(null);
const [keyProvider, setKeyProvider] = useState<SubscriptionProviderDefinition | null>(null);
const [baseUrl, setBaseUrl] = useState("");
+ const [target, setTarget] = useState<SubscriptionAccountTarget>({});
+ const [busyAccount, setBusyAccount] = useState<SubscriptionAccountId | null>(null);
const settleLogin = useCallback(
(progress: SubscriptionAuthLoginProgress) => {
@@ -158,16 +190,27 @@ export function useSubscriptionAccounts(
};
}, [activeLogin, environmentId, pollAuth, settleLogin]);
- const openApiKey = (definition: SubscriptionProviderDefinition) => {
+ const openApiKey = (
+ definition: SubscriptionProviderDefinition,
+ account: SubscriptionAccountTarget = {},
+ ) => {
setError(null);
+ setTarget(account);
setPastedCode("");
setBaseUrl(
providerSupportsBaseUrl(definition.id)
- ? ((instanceId
- ? statusQuery.data?.accounts.find(
- (entry) => entry.provider === definition.id && entry.instanceId === instanceId,
- )
- : statusByProvider.get(definition.id)
+ ? ((account.addAccount
+ ? undefined
+ : account.accountId
+ ? statusQuery.data?.linkedAccounts.find(
+ (entry) =>
+ entry.provider === definition.id && entry.accountId === account.accountId,
+ )
+ : instanceId
+ ? statusQuery.data?.accounts.find(
+ (entry) => entry.provider === definition.id && entry.instanceId === instanceId,
+ )
+ : statusByProvider.get(definition.id)
)?.baseUrl ?? "")
: "",
);
@@ -194,6 +237,7 @@ export function useSubscriptionAccounts(
input: {
...apiKeyStartInput(keyProvider.id, baseUrl),
...(instanceId ? { instanceId } : {}),
+ ...target,
},
});
@@ -229,11 +273,14 @@ export function useSubscriptionAccounts(
}
};
- const connect = async (definition: SubscriptionProviderDefinition) => {
+ const connect = async (
+ definition: SubscriptionProviderDefinition,
+ account: SubscriptionAccountTarget = {},
+ ) => {
if (environmentId === null) return;
if (definition.id === "opencode-go") {
- openApiKey(definition);
+ openApiKey(definition, account);
return;
}
@@ -241,12 +288,15 @@ export function useSubscriptionAccounts(
setError(null);
setPastedCode("");
setBusyProvider(definition.id);
+ setBusyAccount(account.accountId ?? null);
const result = await startAuth({
environmentId,
- input: { provider: definition.id, ...(instanceId ? { instanceId } : {}) },
+ input: { provider: definition.id, ...(instanceId ? { instanceId } : {}), ...account },
});
+ setBusyAccount(null);
+
if (isAtomCommandInterrupted(result)) return;
if (Predicate.isTagged(result, "Failure")) {
@@ -296,40 +346,55 @@ export function useSubscriptionAccounts(
if (Predicate.isTagged(result, "Failure")) setError(commandError(result, t));
};
- const disconnect = async (provider: SubscriptionProviderId) => {
+ const disconnect = async (
+ provider: SubscriptionProviderId,
+ accountId?: SubscriptionAccountId,
+ ) => {
if (environmentId === null) return;
setError(null);
setBusyProvider(provider);
+ setBusyAccount(accountId ?? null);
const result = await logoutAuth({
environmentId,
- input: { provider, ...(instanceId ? { instanceId } : {}) },
+ input: { provider, ...(accountId ? { accountId } : instanceId ? { instanceId } : {}) },
});
setBusyProvider(null);
+ setBusyAccount(null);
if (Predicate.isTagged(result, "Success")) statusQuery.refresh();
else if (Predicate.isTagged(result, "Failure")) setError(commandError(result, t));
};
- const testHealth = async (provider: SubscriptionProviderId) => {
+ const testHealth = async (
+ provider: SubscriptionProviderId,
+ accountId?: SubscriptionAccountId,
+ ) => {
if (environmentId === null) return;
setError(null);
setBusyProvider(provider);
+ setBusyAccount(accountId ?? null);
const result = await testAuth({
environmentId,
- input: { provider, ...(instanceId ? { instanceId } : {}) },
+ input: { provider, ...(accountId ? { accountId } : instanceId ? { instanceId } : {}) },
});
setBusyProvider(null);
+ setBusyAccount(null);
if (Predicate.isTagged(result, "Success")) {
statusQuery.refresh();
- const status = (instanceId ? result.value.accounts : result.value.providers).find(
- (entry) => entry.provider === provider && (!instanceId || entry.instanceId === instanceId),
- );
+ const status = accountId
+ ? result.value.linkedAccounts.find(
+ (entry) => entry.provider === provider && entry.accountId === accountId,
+ )
+ : (instanceId ? result.value.accounts : result.value.providers).find(
+ (entry) =>
+ entry.provider === provider && (!instanceId || entry.instanceId === instanceId),
+ );
if (status?.oauthCheck?.status === "failed" || status?.healthTest?.status === "failed") {
setError(
@@ -340,11 +405,33 @@ export function useSubscriptionAccounts(
} else if (Predicate.isTagged(result, "Failure")) setError(commandError(result, t));
};
+ const setAccountOrder = async (
+ provider: SubscriptionProviderId,
+ accountIds: ReadonlyArray<SubscriptionAccountId>,
+ ) => {
+ if (environmentId === null) return;
+ setError(null);
+ setBusyProvider(provider);
+
+ const result = await orderAuth({
+ environmentId,
+ input: { provider, accountIds: [...accountIds] },
+ });
+
+ setBusyProvider(null);
+
+ if (Predicate.isTagged(result, "Success")) statusQuery.refresh();
+ else if (Predicate.isTagged(result, "Failure")) setError(commandError(result, t));
+ };
+
return {
statusQuery,
statusByProvider,
activeLogin,
busyProvider,
+ busyAccount,
+ keyTarget: target,
+ setAccountOrder,
pastedCode,
setPastedCode,
completing,
diff --git a/apps/web/src/components/sidebar/ExperimentalSidebar.tsx b/apps/web/src/components/sidebar/ExperimentalSidebar.tsx
index e7a186b55..bf5971afe 100644
--- a/apps/web/src/components/sidebar/ExperimentalSidebar.tsx
+++ b/apps/web/src/components/sidebar/ExperimentalSidebar.tsx
@@ -20,7 +20,7 @@ import { useI18n } from "../../i18n";
import { useChangedSinceMount } from "../../hooks/useChangedSinceMount";
import { useClientSettings } from "../../hooks/useSettings";
import { useTheme } from "../../hooks/useTheme";
-import { cn, isMacPlatform } from "../../lib/utils";
+import { cn } from "../../lib/utils";
import { openPlugins } from "../../pluginsDialogStore";
import { openProductFeedback } from "../../productFeedbackStore";
import { openUsage } from "../../usageDialogStore";
@@ -104,7 +104,6 @@ export function ExperimentalSidebar() {
if (onSettings || railOnly) void navigate({ to: "/" });
};
- const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
const { resolvedTheme, setAppearanceMode } = useTheme();
const nextAppearance = resolvedTheme === "dark" ? "light" : "dark";
const panel = onSettings ? "settings" : place;
@@ -113,98 +112,109 @@ export function ExperimentalSidebar() {
const { t } = useI18n();
return (
- <div className="flex h-full min-h-0 w-full overflow-hidden">
- <nav
- aria-label={t("Main")}
- className="flex h-full w-(--rail-width) shrink-0 flex-col items-center pb-3"
- style={{ "--rail-width": `${RAIL_WIDTH}px` }}
- >
- {/* macOS desktop keeps the full titlebar height clear for the traffic
- lights. Elsewhere the first icon centers on the panel title row. */}
- <div
- className={cn(
- "w-full shrink-0",
- isMacosDesktop ? "h-(--workspace-topbar-height)" : "h-topbar-spacer",
- isElectron && "drag-region",
- )}
- />
- <div className="flex flex-col items-center gap-1.5">
- <RailButton
- label={t("Chats")}
- icon={BubbleChatIcon}
- active={!onSettings && !railOnly && place === "chats"}
- onClick={() => choosePlace("chats")}
- />
- <RailButton
- label={t("Routines")}
- icon={Calendar03Icon}
- active={!onSettings && !railOnly && place === "routines"}
- onClick={() => choosePlace("routines")}
- />
- <RailButton
- label={t("Plugins")}
- icon={PuzzleIcon}
- active={onPlugins}
- onClick={() => {
- if (!onPlugins) openPlugins();
- }}
- />
- <RailButton
- label={t("Usage")}
- icon={Analytics01Icon}
- active={onUsage}
- onClick={() => {
- if (!onUsage) openUsage();
- }}
- />
- </div>
- <div className="mt-auto flex flex-col items-center gap-1.5">
- <RailButton
- label={nextAppearance === "dark" ? t("Switch to dark mode") : t("Switch to light mode")}
- icon={nextAppearance === "dark" ? Moon02Icon : Sun03Icon}
- onClick={() => setAppearanceMode(nextAppearance)}
- />
- <RailButton
- label={t("Feedback")}
- icon={HelpCircleIcon}
- onClick={() => openProductFeedback()}
- />
- <RailButton
- label={t("Settings")}
- icon={Settings02Icon}
- active={onSettings}
- onClick={() => {
- revealPanel();
-
- if (!onSettings) openSettings();
- }}
- />
- </div>
- </nav>
- {/* The panel is a raised card; its row tokens are re-based on the card surface. */}
- {/* Fixed width so collapsing clips the panel instead of squeezing its rows. */}
+ <div className="flex h-full min-h-0 w-full flex-col overflow-hidden">
+ {/* The macOS traffic lights are wider than the rail, so while they show
+ they get a titlebar strip across rail and panel. Fullscreen hides
+ them and drops the strip. */}
<div
className={cn(
- "flex w-(--panel-width) shrink-0 py-2 pr-2",
- railOnly && !isMobile && "hidden",
+ "hidden h-(--workspace-topbar-height) w-full shrink-0 in-data-[macos-traffic-lights]:block",
+ isElectron && "drag-region",
)}
- style={{ "--panel-width": `${PANEL_WIDTH}px` }}
- >
- <div className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-2xl border border-sidebar-border/70 bg-sidebar shadow-(--shell-card-shadow) sidebar-shell-card">
+ />
+ <div className="flex min-h-0 w-full flex-1 overflow-hidden">
+ <nav
+ aria-label={t("Main")}
+ className="flex h-full w-(--rail-width) shrink-0 flex-col items-center pb-3"
+ style={{ "--rail-width": `${RAIL_WIDTH}px` }}
+ >
+ {/* The first icon centers on the panel title row. */}
<div
- key={panel}
- className={cn("flex min-h-0 flex-1 flex-col", panelSwitched && "motion-place-enter")}
- >
- {Match.value(panel).pipe(
- Match.when("settings", () => (
- <>
- <PanelHeader title={t("Settings")} />
- <SettingsPanelNav />
- </>
- )),
- Match.when("chats", () => <BotRosterSidebar chrome="panel" />),
- Match.orElse(() => <RoutinesPanel />),
+ className={cn(
+ "h-topbar-spacer w-full shrink-0 in-data-[macos-traffic-lights]:h-0",
+ isElectron && "drag-region",
)}
+ />
+ <div className="flex flex-col items-center gap-1.5">
+ <RailButton
+ label={t("Chats")}
+ icon={BubbleChatIcon}
+ active={!onSettings && !railOnly && place === "chats"}
+ onClick={() => choosePlace("chats")}
+ />
+ <RailButton
+ label={t("Routines")}
+ icon={Calendar03Icon}
+ active={!onSettings && !railOnly && place === "routines"}
+ onClick={() => choosePlace("routines")}
+ />
+ <RailButton
+ label={t("Plugins")}
+ icon={PuzzleIcon}
+ active={onPlugins}
+ onClick={() => {
+ if (!onPlugins) openPlugins();
+ }}
+ />
+ <RailButton
+ label={t("Usage")}
+ icon={Analytics01Icon}
+ active={onUsage}
+ onClick={() => {
+ if (!onUsage) openUsage();
+ }}
+ />
+ </div>
+ <div className="mt-auto flex flex-col items-center gap-1.5">
+ <RailButton
+ label={
+ nextAppearance === "dark" ? t("Switch to dark mode") : t("Switch to light mode")
+ }
+ icon={nextAppearance === "dark" ? Moon02Icon : Sun03Icon}
+ onClick={() => setAppearanceMode(nextAppearance)}
+ />
+ <RailButton
+ label={t("Feedback")}
+ icon={HelpCircleIcon}
+ onClick={() => openProductFeedback()}
+ />
+ <RailButton
+ label={t("Settings")}
+ icon={Settings02Icon}
+ active={onSettings}
+ onClick={() => {
+ revealPanel();
+
+ if (!onSettings) openSettings();
+ }}
+ />
+ </div>
+ </nav>
+ {/* The panel is a raised card; its row tokens are re-based on the card surface. */}
+ {/* Fixed width so collapsing clips the panel instead of squeezing its rows. */}
+ <div
+ className={cn(
+ "flex w-(--panel-width) shrink-0 py-2 pr-2 in-data-[macos-traffic-lights]:pt-0",
+ railOnly && !isMobile && "hidden",
+ )}
+ style={{ "--panel-width": `${PANEL_WIDTH}px` }}
+ >
+ <div className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-2xl border border-sidebar-border/70 bg-sidebar shadow-(--shell-card-shadow) sidebar-shell-card">
+ <div
+ key={panel}
+ className={cn("flex min-h-0 flex-1 flex-col", panelSwitched && "motion-place-enter")}
+ >
+ {Match.value(panel).pipe(
+ Match.when("settings", () => (
+ <>
+ <PanelHeader title={t("Settings")} />
+ <SettingsPanelNav />
+ </>
+ )),
+ Match.when("chats", () => <BotRosterSidebar chrome="panel" />),
+ Match.orElse(() => <RoutinesPanel />),
+ )}
+ </div>
</div>
</div>
</div>
diff --git a/docs/internals/providers.md b/docs/internals/providers.md
index e146dac85..149192c1b 100644
--- a/docs/internals/providers.md
+++ b/docs/internals/providers.md
@@ -211,7 +211,7 @@ When a refresh omits a historical model, its bundled catalog entry or known nati
remain available.
CLI workflow choices such as Ultracode and Ultrathink are excluded from its native effort picker.
Grok includes its API model IDs
-alongside catalog additions. It labels the compatibility `grok-build` selection as Grok 4.6 and maps it to `grok-4.6` in
+alongside catalog additions. It labels the compatibility `grok-build` selection as Grok 4.7 and maps it to `grok-4.7` in
`mastraModelId`, because the product slug is not an API model ID. Keeping the selection slug lets
existing bots and the default model pass catalog validation. Custom models are retained.
@@ -270,6 +270,26 @@ silent; other skill discovery failures are logged as warnings. Claude still read
files directly, without a CLI. Codex's CLI-only skills and Claude's CLI slash-command discovery are
not part of readiness snapshots. Version checks are skipped when there is no CLI version.
+### Backup subscription accounts
+
+A subscription provider can have several linked accounts. The first sign-in is account `default`,
+stored under the bare provider key in `subscription-auth.json`; each added account gets an
+`acct-<hex>` id stored under `account:<provider>:<id>`. Separately named provider instances keep
+their own `instance:<provider>:<instanceId>` key and never join the backup order.
+
+`SubscriptionAccountState` (`apps/server/src/subscription-auth/accountState.ts`) owns the order,
+persisted next to the credentials as `subscription-auth.json.accounts`. Credential reads for the
+default instance resolve to the first ready account: one is skipped while its `nextRetryAt` is in
+the future or its last failure was a revoked sign-in. When a request fails with a usage-limit
+message, `accountLimits.ts` benches that account until the reset time the provider gave, or for an
+hour. Every credential read takes the thread id, and outcomes are recorded on the account that
+served that thread, so concurrent chats on different accounts do not claim each other's failures.
+Order and health files are re-read when another server process rewrites them.
+
+`SubscriptionAuthStatuses.linkedAccounts` lists every linked account in order with `accountId`,
+`active`, and `plan`. `subscriptionAuth.setAccountOrder` reorders them, and start, logout, and
+health-test inputs accept an `accountId` or `addAccount`.
+
### Legacy Grok CLI probe
`checkGrokProviderStatus` is retained for legacy probe tests and is not used by `GrokDriver`.
diff --git a/docs/user/bots.md b/docs/user/bots.md
index 8acaa5e42..e261da67c 100644
--- a/docs/user/bots.md
+++ b/docs/user/bots.md
@@ -31,10 +31,10 @@ empty, the main view shows **Create bot**.
## Profile
You can change the bot's avatar, name, label, description, model, voice access, and enabled tools.
-Select **Save** to apply the changes. The model button in the composer shows which model answers the
-next message. Select it to change the bot's model without leaving the chat. The model list also
-shows providers that cannot run right now, such as one that is signed out or turned off. Their
-models are dimmed and say why.
+Select **Save** to apply the changes. The model lives in the bot's settings under **Model & usage**,
+not in the chat. From a chat, use **Change model** in the command palette or its shortcut to jump
+straight there. The model list also shows providers that cannot run right now, such as one that is
+signed out or turned off. Their models are dimmed and say why.
Reasoning controls how much thinking the bot spends before answering. Change it under **Reasoning**
in the bot's settings on web or desktop. On mobile, open **Model and reasoning settings** in the
diff --git a/docs/user/providers.md b/docs/user/providers.md
index f37f2d929..f1f7fd81c 100644
--- a/docs/user/providers.md
+++ b/docs/user/providers.md
@@ -12,10 +12,12 @@ Model lists update on their own. The environment server checks models.dev for ne
about once an hour, and open clients pick them up within a few minutes, with no reload or app
update. Older models move to the picker's legacy section when a newer one in the same line ships.
-Use **Add account** on a provider's page to connect a second account of the same provider, such as a
-work and a personal subscription. Give it a name, then sign in from its card. An account configured with its own credentials uses those
-credentials rather than the shared connection. A custom configuration directory alone does not
-connect an account to Akeru's runtime.
+A provider can have more than one account. Backup accounts take over when one hits a usage limit;
+see [Backup accounts](#backup-accounts). To keep a second subscription apart instead, such as a work
+and a personal one that different bots use, choose **Add separate account** on the provider's page.
+Give it a name, then sign in from its card. A separate account configured with its own credentials
+uses those credentials rather than the shared connection. A custom configuration directory alone
+does not connect an account to Akeru's runtime.
## Custom API endpoints
@@ -47,6 +49,32 @@ gateway.
The environment sends requests to the URL you configure. Point it only at an endpoint you trust, and
prefer HTTPS for anything outside your machine.
+## Backup accounts
+
+Once you are signed in to a provider, its page lists your accounts under **Accounts**. Choose **Add
+account** there, then sign in or use an API key. Each new account goes to the bottom of the list.
+
+Each account is named by its plan, such as **ChatGPT Pro** or **Claude Max 20x**, so the list never
+shows your email address. API keys show as **API key**. Grok and Kimi For Coding don't report a plan,
+so their accounts show as **Grok account** and **Kimi For Coding account**.
+
+The list is in the order bots use it. The first account is the **Main account** and the rest are
+**Backup 1**, **Backup 2**, and so on. Bots use the main account, marked **In use**. When it reaches
+a usage limit, the account shows **Usage limit reached, back at** the time it resets, and bots move
+to the next account. The request that hit the limit still fails, and the bot's next request uses
+the backup. Once the limit resets, bots go back to the main account. A backup waiting its turn
+shows **Ready**.
+
+If an account stops working, it says why and offers the fix next to it. **Signed out** and **Login
+expired** come with **Sign in again**, and **Key rejected** comes with **Replace key**. **Can't reach**
+the provider comes with **Try again**.
+
+Use the arrows to change the order. The actions menu on each account has **Sign in again** (or
+**Replace key**) and **Remove**. On mobile, use **Move up**, **Move down**, and **Disconnect**.
+
+Backup accounts serve bots on the provider's main connection. A separate account added with **Add
+separate account** keeps its own sign-in and does not take part in the backup order.
+
## Subscription login health
After a login or API key save completes, the environment server sends one request that costs nothing, to confirm the account can reach its models or usage endpoint. The check runs on the server, so closing the app or losing the connection right after login does not stop it. While it runs, the provider row shows **Checking health…**. It then changes to **Connected** when the request succeeds or **Failed** when it does not. A failed check does not undo a successful login. Repair the provider account, then use **Reconnect** or **Check OAuth**.
diff --git a/packages/client-runtime/src/i18n/__snapshots__/coverage.test.ts.snap b/packages/client-runtime/src/i18n/__snapshots__/coverage.test.ts.snap
index 1368319a1..64a46f8dc 100644
--- a/packages/client-runtime/src/i18n/__snapshots__/coverage.test.ts.snap
+++ b/packages/client-runtime/src/i18n/__snapshots__/coverage.test.ts.snap
@@ -2,7 +2,7 @@
exports[`discovered interface message coverage > covers static calls and finite label sources without translating identifiers 1`] = `
{
- "directMessageCount": 1766,
+ "directMessageCount": 1781,
"expressions": {
"apps/mobile/src/components/DictationControls.tsx": [
"announcements[status]);",
@@ -165,6 +165,9 @@ exports[`discovered interface message coverage > covers static calls and finite
"entry.planHint)}",
"entry.planHint)}",
],
+ "apps/web/src/components/settings/ProviderLinkedAccounts.tsx": [
+ "state.label)}</span>;",
+ ],
"apps/web/src/components/settings/SandboxSettingsPanel.tsx": [
"definition.description)}",
"field.label)}",
@@ -409,6 +412,7 @@ exports[`discovered interface message coverage > covers static calls and finite
"apps/web/src/components/chat/ModelPickerContent.tsx",
"apps/web/src/components/chat/ModelPickerSidebar.tsx",
"apps/web/src/components/chat/PluginSearchResultCard.tsx",
+ "apps/web/src/components/chat/ProviderConnectCard.tsx",
"apps/web/src/components/chat/ProviderModelPicker.tsx",
"apps/web/src/components/chat/ProviderUnavailableNotice.tsx",
"apps/web/src/components/chat/ReplyPlaybackControls.tsx",
@@ -454,7 +458,6 @@ exports[`discovered interface message coverage > covers static calls and finite
"apps/web/src/components/roster/BotChannelsSheet.tsx",
"apps/web/src/components/roster/BotChatMessageRows.tsx",
"apps/web/src/components/roster/BotChatsSection.tsx",
- "apps/web/src/components/roster/BotComposerModelControl.tsx",
"apps/web/src/components/roster/BotConversationScrollArea.tsx",
"apps/web/src/components/roster/BotDetailsPanel.tsx",
"apps/web/src/components/roster/BotDurableMemory.tsx",
@@ -536,6 +539,7 @@ exports[`discovered interface message coverage > covers static calls and finite
"apps/web/src/components/settings/ProviderAccountControls.tsx",
"apps/web/src/components/settings/ProviderDetailPage.tsx",
"apps/web/src/components/settings/ProviderInstancesSection.tsx",
+ "apps/web/src/components/settings/ProviderLinkedAccounts.tsx",
"apps/web/src/components/settings/ProvidersPanel.tsx",
"apps/web/src/components/settings/SandboxSettingsPanel.tsx",
"apps/web/src/components/settings/SettingsDialog.tsx",
@@ -551,6 +555,7 @@ exports[`discovered interface message coverage > covers static calls and finite
"apps/web/src/components/settings/VoiceSettings.tsx",
"apps/web/src/components/settings/portabilityPresentation.ts",
"apps/web/src/components/settings/settingsLayout.tsx",
+ "apps/web/src/components/settings/subscriptionProviders.ts",
"apps/web/src/components/settings/useDesktopBackendSettings.ts",
"apps/web/src/components/settings/useSettingsRestore.ts",
"apps/web/src/components/settings/useSubscriptionAccounts.ts",
diff --git a/packages/client-runtime/src/i18n/catalogs/en/connections.ts b/packages/client-runtime/src/i18n/catalogs/en/connections.ts
index 8907b3bb6..c80228ddc 100644
--- a/packages/client-runtime/src/i18n/catalogs/en/connections.ts
+++ b/packages/client-runtime/src/i18n/catalogs/en/connections.ts
@@ -491,4 +491,21 @@ export const connectionsCatalog = {
"Connect to an environment to see its archived chats.",
"Check the connection to this environment, then reopen this page.":
"Check the connection to this environment, then reopen this page.",
+ "Connect {provider} to chat with {bot}": "Connect {provider} to chat with {bot}",
+ "Reconnect {provider} to keep chatting with {bot}":
+ "Reconnect {provider} to keep chatting with {bot}",
+ "Checking your {provider} account…": "Checking your {provider} account…",
+ "{provider} account": "{provider} account",
+ "In use": "In use",
+ "Main account": "Main account",
+ "Backup {number}": "Backup {number}",
+ "Checking sign-in": "Checking sign-in",
+ "Usage limit reached, back at {time}": "Usage limit reached, back at {time}",
+ "Signed out": "Signed out",
+ "Can't reach {provider}": "Can't reach {provider}",
+ "Sign in again": "Sign in again",
+ "Sign in with {provider}": "Sign in with {provider}",
+ "Move {account} up": "Move {account} up",
+ "Move {account} down": "Move {account} down",
+ "Add separate account": "Add separate account",
} as const;
diff --git a/packages/client-runtime/src/i18n/catalogs/zh-CN/connections.ts b/packages/client-runtime/src/i18n/catalogs/zh-CN/connections.ts
index 8105eef52..79e51eb03 100644
--- a/packages/client-runtime/src/i18n/catalogs/zh-CN/connections.ts
+++ b/packages/client-runtime/src/i18n/catalogs/zh-CN/connections.ts
@@ -456,4 +456,20 @@ export const connectionsCatalog = {
"Connect to an environment to see its archived chats.": "连接到一个环境以查看其已归档聊天。",
"Check the connection to this environment, then reopen this page.":
"请检查与此环境的连接,然后重新打开此页面。",
+ "Connect {provider} to chat with {bot}": "连接 {provider} 即可与 {bot} 聊天",
+ "Reconnect {provider} to keep chatting with {bot}": "重新连接 {provider} 以继续与 {bot} 聊天",
+ "Checking your {provider} account…": "正在检查你的 {provider} 账户…",
+ "{provider} account": "{provider} 账户",
+ "In use": "使用中",
+ "Main account": "主账户",
+ "Backup {number}": "备用 {number}",
+ "Checking sign-in": "正在检查登录",
+ "Usage limit reached, back at {time}": "已达用量上限,{time} 恢复",
+ "Signed out": "已退出登录",
+ "Can't reach {provider}": "无法连接 {provider}",
+ "Sign in again": "重新登录",
+ "Sign in with {provider}": "使用 {provider} 登录",
+ "Move {account} up": "上移 {account}",
+ "Move {account} down": "下移 {account}",
+ "Add separate account": "添加单独账户",
} as const;
diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts
index 37c1fdc7b..f46a5d4ba 100644
--- a/packages/client-runtime/src/state/server.ts
+++ b/packages/client-runtime/src/state/server.ts
@@ -527,6 +527,10 @@ export function createServerEnvironmentAtoms<R, E>(
label: "environment-data:server:subscription-auth:health-test",
tag: WS_METHODS.subscriptionAuthHealthTest,
}),
+ setSubscriptionAccountOrder: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:subscription-auth:set-account-order",
+ tag: WS_METHODS.subscriptionAuthSetAccountOrder,
+ }),
testImageProvider: createEnvironmentRpcCommand(runtime, {
label: "environment-data:server:image-provider:health-test",
tag: WS_METHODS.imageProviderHealthTest,
diff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.ts
index d90acb1ec..7c5d3490b 100644
--- a/packages/contracts/src/model.ts
+++ b/packages/contracts/src/model.ts
@@ -170,18 +170,18 @@ export const PREFERRED_DEFAULT_CODEX_MODELS: ReadonlyArray<string> = [
"gpt-5.6-terra",
];
-export const DEFAULT_TEXT_GENERATION_MODEL = "gpt-5.6-luna";
+export const DEFAULT_TEXT_GENERATION_MODEL = "gpt-6-luna";
export const DEFAULT_TEXT_GENERATION_REASONING_EFFORT = "low";
export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
- [CLAUDE_DRIVER_KIND]: "claude-sonnet-5",
+ [CLAUDE_DRIVER_KIND]: "claude-opus-5-5",
// Product slug, not an ACP model id. The Grok adapter treats it as "the session's current model".
[GROK_DRIVER_KIND]: "grok-build",
[KIMI_DRIVER_KIND]: "k3",
- [OPENCODE_DRIVER_KIND]: "openai/gpt-5",
- [OPENCODE_GO_DRIVER_KIND]: "gpt-5.6-luna",
+ [OPENCODE_DRIVER_KIND]: "openai/gpt-6.1-sol",
+ [OPENCODE_GO_DRIVER_KIND]: "gpt-6-luna",
};
/** Per-provider text generation model defaults. */
@@ -190,7 +190,7 @@ export const DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER: Partial<
> = {
[CODEX_DRIVER_KIND]: DEFAULT_TEXT_GENERATION_MODEL,
[CLAUDE_DRIVER_KIND]: "claude-haiku-4-5",
- [OPENCODE_DRIVER_KIND]: "openai/gpt-5",
+ [OPENCODE_DRIVER_KIND]: "openai/gpt-6-luna",
};
export const MODEL_SLUG_ALIASES_BY_PROVIDER: Partial<
@@ -221,7 +221,9 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Partial<
"opus-4.6": "claude-opus-4-6",
"claude-opus-4.6": "claude-opus-4-6",
"claude-opus-4-6-20251117": "claude-opus-4-6",
- sonnet: "claude-sonnet-5",
+ sonnet: "claude-sonnet-5-5",
+ "sonnet-5.5": "claude-sonnet-5-5",
+ "claude-sonnet-5.5": "claude-sonnet-5-5",
"sonnet-5": "claude-sonnet-5",
"claude-sonnet-5.0": "claude-sonnet-5",
"claude-sonnet-5-0": "claude-sonnet-5",
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index f00bb5e4a..a95ab9d91 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -23,6 +23,7 @@ import {
WsSubscriptionAuthCancelRpc,
WsSubscriptionAuthLogoutRpc,
WsSubscriptionAuthHealthTestRpc,
+ WsSubscriptionAuthSetAccountOrderRpc,
WsImageProviderListRpc,
WsImageProviderHealthTestRpc,
WsMcpServerAuthenticateRpc,
@@ -145,6 +146,7 @@ export const WsRpcGroup = RpcGroup.make(
WsSubscriptionAuthCancelRpc,
WsSubscriptionAuthLogoutRpc,
WsSubscriptionAuthHealthTestRpc,
+ WsSubscriptionAuthSetAccountOrderRpc,
WsImageProviderListRpc,
WsImageProviderHealthTestRpc,
WsMcpServerAuthenticateRpc,
@@ -261,6 +263,7 @@ export {
WsSubscriptionAuthCancelRpc,
WsSubscriptionAuthLogoutRpc,
WsSubscriptionAuthHealthTestRpc,
+ WsSubscriptionAuthSetAccountOrderRpc,
WsImageProviderListRpc,
WsImageProviderHealthTestRpc,
WsMcpServerAuthenticateRpc,
diff --git a/packages/contracts/src/rpc/methods.ts b/packages/contracts/src/rpc/methods.ts
index 9f688060b..17160d9f6 100644
--- a/packages/contracts/src/rpc/methods.ts
+++ b/packages/contracts/src/rpc/methods.ts
@@ -63,6 +63,7 @@ export const WS_METHODS = {
subscriptionAuthCancel: "subscriptionAuth.cancel",
subscriptionAuthLogout: "subscriptionAuth.logout",
subscriptionAuthHealthTest: "subscriptionAuth.healthTest",
+ subscriptionAuthSetAccountOrder: "subscriptionAuth.setAccountOrder",
// Image generation providers
imageProviderList: "imageProvider.list",
diff --git a/packages/contracts/src/rpc/server.ts b/packages/contracts/src/rpc/server.ts
index af3473de9..261b86348 100644
--- a/packages/contracts/src/rpc/server.ts
+++ b/packages/contracts/src/rpc/server.ts
@@ -109,6 +109,7 @@ import {
McpServerAuthenticateInput,
McpServerAuthenticationError,
McpServerAuthenticationProgress,
+ SubscriptionAuthAccountOrderInput,
SubscriptionAuthCompleteInput,
SubscriptionAuthError,
SubscriptionAuthHealthTestInput,
@@ -321,6 +322,15 @@ export const WsSubscriptionAuthHealthTestRpc = Rpc.make(WS_METHODS.subscriptionA
error: Schema.Union([SubscriptionAuthError, EnvironmentAuthorizationError]),
});
+export const WsSubscriptionAuthSetAccountOrderRpc = Rpc.make(
+ WS_METHODS.subscriptionAuthSetAccountOrder,
+ {
+ payload: SubscriptionAuthAccountOrderInput,
+ success: SubscriptionAuthStatuses,
+ error: Schema.Union([SubscriptionAuthError, EnvironmentAuthorizationError]),
+ },
+);
+
export const WsImageProviderListRpc = Rpc.make(WS_METHODS.imageProviderList, {
payload: Schema.Struct({}),
success: ImageProviderListResult,
diff --git a/packages/contracts/src/settings.providers.test.ts b/packages/contracts/src/settings.providers.test.ts
index dc6aa6a40..361a53114 100644
--- a/packages/contracts/src/settings.providers.test.ts
+++ b/packages/contracts/src/settings.providers.test.ts
@@ -124,7 +124,7 @@ describe("ServerSettings.providerInstances (slice-2 invariant)", () => {
it("defaults text generation to Luna at low reasoning effort", () => {
expect(DEFAULT_SERVER_SETTINGS.textGenerationModelSelection).toEqual({
instanceId: ProviderInstanceId.make("codex"),
- model: "gpt-5.6-luna",
+ model: "gpt-6-luna",
options: [{ id: "reasoningEffort", value: "low" }],
});
});
diff --git a/packages/contracts/src/subscriptionAuth.ts b/packages/contracts/src/subscriptionAuth.ts
index d4d86a544..179c6eb5f 100644
--- a/packages/contracts/src/subscriptionAuth.ts
+++ b/packages/contracts/src/subscriptionAuth.ts
@@ -48,12 +48,28 @@ export const SubscriptionBaseUrl = TrimmedNonEmptyString.check(
),
);
+/**
+ * One signed-in account for a provider. `default` is the account the first
+ * sign-in created; added accounts get their own ids.
+ */
+export const SubscriptionAccountId = TrimmedNonEmptyString.check(
+ Schema.isPattern(/^(default|acct-[a-z0-9]{6,32})$/),
+);
+
+export type SubscriptionAccountId = typeof SubscriptionAccountId.Type;
+
export const SubscriptionProviderStatus = Schema.Struct({
provider: SubscriptionProviderId,
instanceId: Schema.optional(ProviderInstanceId),
+ /** Set on entries of `linkedAccounts`. */
+ accountId: Schema.optional(SubscriptionAccountId),
+ /** True on the linked account that new requests use right now. */
+ active: Schema.optional(Schema.Boolean),
connected: Schema.Boolean,
/** Account identifier supplied by the provider, when available. Never a token. */
accountLabel: Schema.optional(TrimmedNonEmptyString),
+ /** Subscription tier, such as "Pro" or "Max 20x", when the provider reports one. */
+ plan: Schema.optional(TrimmedNonEmptyString),
authMode: Schema.optional(SubscriptionAuthMode),
baseUrl: Schema.optional(SubscriptionBaseUrl),
/** ms epoch when the current access token expires. Absent when disconnected. */
@@ -196,6 +212,13 @@ export const SubscriptionAuthStatuses = Schema.Struct({
accounts: Schema.Array(SubscriptionProviderStatus).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
),
+ /**
+ * Every signed-in account per provider, in the order requests try them.
+ * When one hits a usage limit or is signed out, requests move to the next.
+ */
+ linkedAccounts: Schema.Array(SubscriptionProviderStatus).pipe(
+ Schema.withDecodingDefault(Effect.succeed([])),
+ ),
access: Schema.Array(ProviderAccessStatus).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
inbox: Schema.Array(BotInboxItem).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
});
@@ -205,6 +228,7 @@ export type SubscriptionAuthStatuses = typeof SubscriptionAuthStatuses.Type;
export const SubscriptionAuthHealthTestInput = Schema.Struct({
provider: SubscriptionProviderId,
instanceId: Schema.optional(ProviderInstanceId),
+ accountId: Schema.optional(SubscriptionAccountId),
});
export type SubscriptionAuthHealthTestInput = typeof SubscriptionAuthHealthTestInput.Type;
@@ -212,6 +236,10 @@ export type SubscriptionAuthHealthTestInput = typeof SubscriptionAuthHealthTestI
export const SubscriptionAuthStartInput = Schema.Struct({
provider: SubscriptionProviderId,
instanceId: Schema.optional(ProviderInstanceId),
+ /** Sign in to this linked account again. */
+ accountId: Schema.optional(SubscriptionAccountId),
+ /** Sign in to another account and add it to the end of the order. */
+ addAccount: Schema.optional(Schema.Boolean),
authMode: Schema.optional(SubscriptionAuthMode),
/** Custom endpoints apply to API-key authentication only. */
baseUrl: Schema.optional(SubscriptionBaseUrl),
@@ -264,10 +292,18 @@ export type SubscriptionAuthLoginProgress = typeof SubscriptionAuthLoginProgress
export const SubscriptionAuthLogoutInput = Schema.Struct({
provider: SubscriptionProviderId,
instanceId: Schema.optional(ProviderInstanceId),
+ accountId: Schema.optional(SubscriptionAccountId),
});
export type SubscriptionAuthLogoutInput = typeof SubscriptionAuthLogoutInput.Type;
+export const SubscriptionAuthAccountOrderInput = Schema.Struct({
+ provider: SubscriptionProviderId,
+ accountIds: Schema.Array(SubscriptionAccountId),
+});
+
+export type SubscriptionAuthAccountOrderInput = typeof SubscriptionAuthAccountOrderInput.Type;
+
export class SubscriptionAuthError extends Schema.TaggedErrorClass<SubscriptionAuthError>()(
"SubscriptionAuthError",
{
diff --git a/packages/shared/src/model.test.ts b/packages/shared/src/model.test.ts
index c82790abc..92fe9953a 100644
--- a/packages/shared/src/model.test.ts
+++ b/packages/shared/src/model.test.ts
@@ -8,6 +8,7 @@ import {
buildProviderOptionSelectionsFromDescriptors,
createModelCapabilities,
createModelSelection,
+ formatModelSlug,
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
getProviderOptionDescriptors,
@@ -191,6 +192,22 @@ describe("applyClaudePromptEffortPrefix", () => {
});
});
+describe("formatModelSlug", () => {
+ it("names unlisted slugs the way providers write them", () => {
+ expect(formatModelSlug("gpt-5.5")).toBe("GPT-5.5");
+ expect(formatModelSlug("gpt-5.1-codex-max")).toBe("GPT-5.1 Codex Max");
+ expect(formatModelSlug("claude-opus-4-8")).toBe("Claude Opus 4.8");
+ expect(formatModelSlug("grok-4.20-beta")).toBe("Grok 4.20 Beta");
+ expect(formatModelSlug("glm-5.3")).toBe("GLM-5.3");
+ expect(formatModelSlug("qwen3.8-max")).toBe("Qwen3.8 Max");
+ expect(formatModelSlug("deepseek-v4-pro")).toBe("DeepSeek V4 Pro");
+ expect(formatModelSlug("openai/gpt-6.1-sol")).toBe("GPT-6.1 Sol");
+ expect(formatModelSlug("gpt-5.3-codex-spark")).toBe("GPT-5.3 Codex Spark");
+ expect(formatModelSlug("gpt-daybreak-blue-latest")).toBe("GPT Daybreak Blue Latest");
+ expect(formatModelSlug("claude-opus-5-5")).toBe("Claude Opus 5.5");
+ });
+});
+
const nativeReasoningCaps = (levels: ReadonlyArray<string>): ModelCapabilities =>
createModelCapabilities({
optionDescriptors: [
diff --git a/packages/shared/src/model.ts b/packages/shared/src/model.ts
index 6c21373b5..8b169fdb2 100644
--- a/packages/shared/src/model.ts
+++ b/packages/shared/src/model.ts
@@ -526,3 +526,49 @@ export function applyClaudePromptEffortPrefix(
return `Ultrathink:\n${trimmed}`;
}
+
+const MODEL_NAME_BRANDS = new Map([
+ ["gpt", "GPT"],
+ ["glm", "GLM"],
+ ["deepseek", "DeepSeek"],
+ ["minimax", "MiniMax"],
+ ["mimo", "MiMo"],
+ ["longcat", "LongCat"],
+]);
+
+/** Brands written with a hyphen before their version, as in "GPT-6.1". */
+const HYPHENATED_MODEL_BRANDS = new Set(["GPT", "GLM"]);
+
+/**
+ * Readable fallback name for a model slug the provider did not name, such as
+ * "gpt-5.5" → "GPT-5.5" or "claude-opus-4-8" → "Claude Opus 4.8". Use the
+ * provider's own model name when one exists.
+ */
+export function formatModelSlug(slug: string): string {
+ const parts = (slug.split("/").at(-1) ?? slug).split("-").filter((part) => part.length > 0);
+ const words: string[] = [];
+
+ for (const part of parts) {
+ const previous = words.at(-1);
+
+ // Claude slugs spell versions with hyphens: "opus-4-8" is Opus 4.8.
+ if (/^\d+$/.test(part) && previous !== undefined && /^\d+(\.\d+)*$/.test(previous)) {
+ words[words.length - 1] = `${previous}.${part}`;
+ continue;
+ }
+
+ const brand = MODEL_NAME_BRANDS.get(part.toLowerCase());
+ words.push(
+ brand ?? (/^\d/.test(part) ? part.toUpperCase() : part[0]!.toUpperCase() + part.slice(1)),
+ );
+ }
+
+ return words.reduce((name, word, index) => {
+ if (index === 0) return word;
+
+ const separator =
+ index === 1 && HYPHENATED_MODEL_BRANDS.has(words[0]!) && /^\d/.test(word) ? "-" : " ";
+
+ return `${name}${separator}${word}`;
+ }, "");
+}