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(bots): add connector health and error inbox (#17)
Leo1d42aed33517
diff --git a/apps/mobile/modules/t3-markdown-text/src/markdownLinks.test.ts b/apps/mobile/modules/t3-markdown-text/src/markdownLinks.test.tsnew file mode 100644index 000000000..283a99231--- /dev/null+++ b/apps/mobile/modules/t3-markdown-text/src/markdownLinks.test.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from "vite-plus/test";++import { resolveMarkdownLinkPresentation } from "./markdownLinks";++describe("mobile Markdown Settings links", () => {+ it("preserves an Akeru Settings URL for the native press handler", () => {+ expect(resolveMarkdownLinkPresentation("grokbot://app/v1/settings?id=bot-inbox")).toEqual({+ kind: "link",+ href: "grokbot://app/v1/settings?id=bot-inbox",+ });+ });+});diff --git a/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts b/apps/mobile/modules/t3-markdown-text/src/markdownLinks.tsindex 20637c6ba..da7bdc74c 100644--- a/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts+++ b/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts@@ -396,6 +396,6 @@ export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPresereturn {kind: "link",- href: /^(?:mailto|tel):/i.test(normalized) ? normalized : null,+ href: /^(?:grokbot|mailto|tel):/i.test(normalized) ? normalized : null,};}diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsxindex 7cffbf62b..efbdfb487 100644--- a/apps/mobile/src/Stack.tsx+++ b/apps/mobile/src/Stack.tsx@@ -58,6 +58,7 @@ import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteimport { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";import { UsageRouteScreen } from "./features/usage/UsageRouteScreen";import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";+import { SettingsProviderHealthRouteScreen } from "./features/settings/SettingsProviderHealthRouteScreen";import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";import {SettingsLegalDocumentCloseHeaderButton,@@ -198,6 +199,13 @@ const SettingsContentStack = createNativeStackNavigator({title: "Usage",},}),+ SettingsProviderHealth: createNativeStackScreen({+ screen: SettingsProviderHealthRouteScreen,+ linking: "provider-health",+ options: {+ title: "Settings",+ },+ }),},});diff --git a/apps/mobile/src/features/settings/SettingsProviderHealthRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProviderHealthRouteScreen.tsxnew file mode 100644index 000000000..638b111c2--- /dev/null+++ b/apps/mobile/src/features/settings/SettingsProviderHealthRouteScreen.tsx@@ -0,0 +1,147 @@+import { useNavigation, type StaticScreenProps } from "@react-navigation/native";+import { useAtomValue } from "@effect/atom-react";+import type { EnvironmentId, SubscriptionAuthStatuses } from "@t3tools/contracts";+import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";++import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";+import { AppText as Text } from "../../components/AppText";+import { NativeStackScreenOptions } from "../../native/StackHeader";+import { useEnvironmentQuery } from "../../state/query";+import { serverEnvironment } from "../../state/server";+import { useAtomCommand } from "../../state/use-atom-command";+import { SettingsSection } from "./components/SettingsSection";++export type SettingsProviderHealthParams = {+ readonly environmentId: EnvironmentId;+ readonly target: "local-execution" | "bot-inbox";+} & Record<string, unknown>;++function Field(props: { readonly label: string; readonly value: string }) {+ return (+ <View className="gap-1">+ <Text className="text-xs font-t3-medium text-foreground-muted">{props.label}</Text>+ <Text className="text-sm text-foreground">{props.value}</Text>+ </View>+ );+}++function BotInbox({ data }: { readonly data: SubscriptionAuthStatuses }) {+ const openItems = data.inbox.filter((item) => item.status === "open");+ return (+ <SettingsSection title="Error inbox" card>+ {openItems.length === 0 ? (+ <Text className="p-4 text-sm text-foreground-muted">No open items.</Text>+ ) : (+ openItems.map((item, index) => (+ <View+ key={item.id}+ className={index === 0 ? "gap-2 p-4" : "gap-2 border-t border-border-subtle p-4"}+ >+ <Text className="text-base font-t3-medium text-foreground">{item.botName}</Text>+ <Field label="Task or routine" value={item.taskOrRoutine} />+ <Field label="Last failure" value={item.lastFailure} />+ <Field label="Next action" value={item.nextAction} />+ </View>+ ))+ )}+ </SettingsSection>+ );+}++function LocalExecution({ environmentId }: { readonly environmentId: EnvironmentId }) {+ const settings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });+ const mode = settings?.defaultThreadEnvMode ?? "local";+ return (+ <SettingsSection title="Local execution" card>+ <View className="gap-3 p-4">+ <Text className="text-sm text-foreground-muted">+ Pick the default workspace mode for new threads on this environment.+ </Text>+ <View className="flex-row gap-2">+ {(["local", "worktree"] as const).map((value) => (+ <Pressable+ key={value}+ accessibilityRole="button"+ accessibilityState={{ selected: mode === value }}+ className={+ mode === value+ ? "flex-1 rounded-[14px] bg-foreground px-4 py-3"+ : "flex-1 rounded-[14px] bg-subtle px-4 py-3"+ }+ onPress={() => {+ void updateSettings({+ environmentId,+ input: { patch: { defaultThreadEnvMode: value } },+ });+ }}+ >+ <Text+ className={+ mode === value+ ? "text-center text-sm font-t3-medium text-background"+ : "text-center text-sm font-t3-medium text-foreground"+ }+ >+ {value === "local" ? "Local" : "New worktree"}+ </Text>+ </Pressable>+ ))}+ </View>+ </View>+ </SettingsSection>+ );+}++export function SettingsProviderHealthRouteScreen({+ route,+}: StaticScreenProps<SettingsProviderHealthParams>) {+ const navigation = useNavigation();+ const insets = useSafeAreaInsets();+ const query = useEnvironmentQuery(+ route.params.target === "local-execution"+ ? null+ : serverEnvironment.subscriptionAuth({+ environmentId: route.params.environmentId,+ input: {},+ }),+ );+ const section =+ route.params.target === "local-execution" ? (+ <LocalExecution environmentId={route.params.environmentId} />+ ) : query.data ? (+ <BotInbox data={query.data} />+ ) : null;++ return (+ <View collapsable={false} className="flex-1 bg-sheet">+ {Platform.OS === "android" ? (+ <NativeStackScreenOptions options={{ headerShown: false }} />+ ) : null}+ {Platform.OS === "android" ? (+ <AndroidScreenHeader title="Settings" onBack={() => navigation.goBack()} />+ ) : null}+ <ScrollView+ contentInsetAdjustmentBehavior="automatic"+ showsVerticalScrollIndicator={false}+ className="flex-1"+ contentContainerClassName="gap-6 px-5 pt-4"+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}+ refreshControl={<RefreshControl refreshing={query.isPending} onRefresh={query.refresh} />}+ >+ {route.params.target === "local-execution" ? (+ section+ ) : query.error ? (+ <Text className="py-16 text-center text-sm text-danger">{query.error}</Text>+ ) : query.data === null ? (+ <Text className="py-16 text-center text-sm text-foreground-muted">+ Loading provider health…+ </Text>+ ) : (+ section+ )}+ </ScrollView>+ </View>+ );+}diff --git a/apps/mobile/src/features/settings/settingsDeepLink.test.ts b/apps/mobile/src/features/settings/settingsDeepLink.test.tsnew file mode 100644index 000000000..176b968f3--- /dev/null+++ b/apps/mobile/src/features/settings/settingsDeepLink.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from "vite-plus/test";++import { resolveMobileSettingsHealthTarget } from "./settingsDeepLink";++describe("mobile Settings chat links", () => {+ it.each(["local-execution", "bot-inbox"] as const)("opens the %s target", (target) => {+ expect(resolveMobileSettingsHealthTarget(`grokbot://app/v1/settings?id=${target}`)).toBe(+ target,+ );+ });++ it.each([+ "grokbot://app/v1/settings?id=providers",+ "grokbot://app/v1/settings?id=provider-access",+ "grokbot://app/v1/settings?id=provider-access&id=bot-inbox",+ "grokbot://app/v1/settings?id=provider-access&from=chat",+ "grokbot://app/v1/settings?id=provider-access#health",+ "grokbot://other/v1/settings?id=provider-access",+ ])("rejects unsupported or malformed destination %s", (href) => {+ expect(resolveMobileSettingsHealthTarget(href)).toBeNull();+ });+});diff --git a/apps/mobile/src/features/settings/settingsDeepLink.ts b/apps/mobile/src/features/settings/settingsDeepLink.tsnew file mode 100644index 000000000..5f33601e7--- /dev/null+++ b/apps/mobile/src/features/settings/settingsDeepLink.ts@@ -0,0 +1,8 @@+import { parseSettingsDeepLinkId } from "@t3tools/client-runtime/settings-deep-link";++export type MobileSettingsHealthTarget = "local-execution" | "bot-inbox";++export function resolveMobileSettingsHealthTarget(href: string): MobileSettingsHealthTarget | null {+ const id = parseSettingsDeepLinkId(href);+ return id === "local-execution" || id === "bot-inbox" ? id : null;+}diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex 60b397802..6c7f66b88 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -111,6 +111,7 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";import { useAssetUrl, useAssetUrlState } from "../../state/assets";import { resolveWorkspaceRelativeFilePath } from "../files/filePath";import { MARKDOWN_IMAGE_MAX_WIDTH, resolveMarkdownImageDisplaySize } from "./markdownImageSize";+import { resolveMobileSettingsHealthTarget } from "../settings/settingsDeepLink";const WIDE_MARKDOWN_BLOCK_OPTIONS = {includeOrderedLists: Platform.OS === "android",@@ -708,6 +709,17 @@ function useMarkdownStyles(highlightCode: boolean,): CustomRenderers => ({link: ({ children, href = "" }) => {+ if (resolveMobileSettingsHealthTarget(href) !== null) {+ return (+ <NativeText+ className="font-t3-bold underline"+ onPress={() => onLinkPress(href)}+ style={{ color: markdownLinkColor }}+ >+ {children}+ </NativeText>+ );+ }const presentation = resolveMarkdownLinkPresentation(href);if (presentation.kind === "file") {return (@@ -1580,6 +1592,22 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {const userBubbleColor = useThemeColor("--color-user-bubble");const onMarkdownLinkPress = useCallback((href: string) => {+ const settingsTarget = resolveMobileSettingsHealthTarget(href);+ if (settingsTarget !== null) {+ void Haptics.selectionAsync();+ navigation.navigate("SettingsSheet", {+ screen: "SettingsContent",+ params: {+ screen: "SettingsProviderHealth",+ params: {+ environmentId: props.environmentId,+ target: settingsTarget,+ },+ },+ });+ return;+ }+ if (/^grokbot:/i.test(href.trim())) return;const presentation = resolveMarkdownLinkPresentation(href);if (presentation.kind === "file") {const relativePath = resolveWorkspaceRelativeFilePath(diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex 464ac3bf5..3a5a4bcdd 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -45,6 +45,7 @@ export const RPC_REQUIRED_SCOPES = {[WS_METHODS.subscriptionAuthComplete]: AuthOrchestrationOperateScope,[WS_METHODS.subscriptionAuthCancel]: AuthOrchestrationOperateScope,[WS_METHODS.subscriptionAuthLogout]: AuthOrchestrationOperateScope,+ [WS_METHODS.subscriptionAuthHealthTest]: AuthOrchestrationOperateScope,[WS_METHODS.voiceCallGet]: AuthOrchestrationReadScope,[WS_METHODS.voiceCallStart]: AuthOrchestrationOperateScope,[WS_METHODS.voiceCallHangup]: AuthOrchestrationOperateScope,diff --git a/apps/server/src/bot-inbox/connectorIncidents.test.ts b/apps/server/src/bot-inbox/connectorIncidents.test.tsnew file mode 100644index 000000000..bfb34cf47--- /dev/null+++ b/apps/server/src/bot-inbox/connectorIncidents.test.ts@@ -0,0 +1,116 @@+// @effect-diagnostics nodeBuiltinImport:off+import * as NodeFS from "node:fs";+import * as NodeOS from "node:os";+import * as NodePath from "node:path";++import { BotId } from "@t3tools/contracts";+import { afterEach, describe, expect, it } from "vite-plus/test";++import type { ProviderStatus } from "../subscription-auth/service.ts";+import { syncConnectorIncidents } from "./connectorIncidents.ts";+import { BotInboxService } from "./service.ts";++const directories: string[] = [];++afterEach(() => {+ for (const directory of directories.splice(0)) {+ NodeFS.rmSync(directory, { recursive: true, force: true });+ }+});++function fixture() {+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-incidents-"));+ directories.push(directory);+ return new BotInboxService(NodePath.join(directory, "bot-inbox.json"));+}++function status(+ health: ProviderStatus["health"],+ message = health === "failed-first-request" ? "The first request failed." : undefined,+): ProviderStatus {+ return {+ provider: "xai",+ connected: true,+ health,+ reconnectAction: "Reconnect account",+ healthTest: { status: "not-run" },+ dependentBots: [{ id: BotId.make("bot-akeru"), name: "Akeru" }],+ dependentRoutines: [],+ ...(message+ ? {+ lastFailedRequest: {+ at: "2026-08-30T20:00:00.000Z",+ message,+ },+ }+ : {}),+ };+}++describe("connector inbox incidents", () => {+ it("opens once for a failed first request and does not count Settings reads", () => {+ const inbox = fixture();+ syncConnectorIncidents(inbox, [status("failed-first-request")]);+ syncConnectorIncidents(inbox, [status("failed-first-request")]);++ expect(inbox.list()).toEqual([+ expect.objectContaining({+ kind: "connector-failure",+ status: "open",+ occurrenceCount: 1,+ lastFailure: "The first request failed.",+ }),+ ]);+ });++ it("resolves the incident after reconnect or a recovered request", () => {+ const inbox = fixture();+ syncConnectorIncidents(inbox, [status("expired")]);+ syncConnectorIncidents(inbox, [status("detected")]);+ expect(inbox.list()[0]?.status).toBe("resolved");++ syncConnectorIncidents(inbox, [status("failed-first-request")]);+ syncConnectorIncidents(inbox, [status("recovered")]);+ expect(inbox.list().filter((item) => item.status === "open")).toHaveLength(0);+ });++ it("resolves the incident when the dependent bot is removed", () => {+ const inbox = fixture();+ syncConnectorIncidents(inbox, [status("failed")]);+ syncConnectorIncidents(inbox, [{ ...status("failed"), dependentBots: [] }]);++ expect(inbox.list()[0]?.status).toBe("resolved");+ });++ it("resolves the incident when the provider status is removed", () => {+ const inbox = fixture();+ syncConnectorIncidents(inbox, [status("failed")]);+ syncConnectorIncidents(inbox, []);++ expect(inbox.list()[0]?.status).toBe("resolved");+ });++ it.each([+ ["expired", "oauth-expired"],+ ["revoked", "connector-failure"],+ ["failed", "connector-failure"],+ ["failed-first-request", "connector-failure"],+ ] as const)("maps %s access to a %s incident", (health, kind) => {+ const inbox = fixture();+ syncConnectorIncidents(inbox, [status(health)]);+ expect(inbox.list()[0]?.kind).toBe(kind);+ });++ it("refreshes failure details without duplicating a connector incident", () => {+ const inbox = fixture();+ syncConnectorIncidents(inbox, [status("failed", "The request timed out.")]);+ syncConnectorIncidents(inbox, [status("failed", "The account lost access.")]);++ expect(inbox.list()).toEqual([+ expect.objectContaining({+ occurrenceCount: 1,+ lastFailure: "The account lost access.",+ }),+ ]);+ });+});diff --git a/apps/server/src/bot-inbox/connectorIncidents.ts b/apps/server/src/bot-inbox/connectorIncidents.tsnew file mode 100644index 000000000..76df979ae--- /dev/null+++ b/apps/server/src/bot-inbox/connectorIncidents.ts@@ -0,0 +1,53 @@+import type { ProviderStatus } from "../subscription-auth/service.ts";+import { BotInboxService } from "./service.ts";++export function syncConnectorIncidents(+ botInbox: BotInboxService,+ statuses: ReadonlyArray<ProviderStatus>,+): void {+ const currentIncidentKeys = new Set<string>();+ for (const status of statuses) {+ for (const bot of status.dependentBots) {+ const incidentKey = `connector:${status.provider}:${bot.id}`;+ currentIncidentKeys.add(incidentKey);+ if (+ status.health === "expired" ||+ status.health === "revoked" ||+ status.health === "failed" ||+ status.health === "failed-first-request"+ ) {+ botInbox.ensureOpen({+ incidentKey,+ kind: status.health === "expired" ? "oauth-expired" : "connector-failure",+ botId: bot.id,+ botName: bot.name,+ taskOrRoutine: `${status.provider} access`,+ lastFailure:+ status.lastFailedRequest?.message ??+ (status.health === "expired"+ ? "The OAuth access token expired."+ : "The provider rejected the request."),+ nextAction: `${status.reconnectAction} in Settings, then send a provider request.`,+ });+ continue;+ }+ if (+ status.health === "detected" ||+ status.health === "healthy" ||+ status.health === "recovered"+ ) {+ botInbox.resolve(incidentKey);+ }+ }+ }++ for (const incident of botInbox.list()) {+ if (+ incident.status === "open" &&+ incident.incidentKey.startsWith("connector:") &&+ !currentIncidentKeys.has(incident.incidentKey)+ ) {+ botInbox.resolve(incident.incidentKey);+ }+ }+}diff --git a/apps/server/src/bot-inbox/service.test.ts b/apps/server/src/bot-inbox/service.test.tsnew file mode 100644index 000000000..37553a284--- /dev/null+++ b/apps/server/src/bot-inbox/service.test.ts@@ -0,0 +1,111 @@+// @effect-diagnostics nodeBuiltinImport:off+import * as NodeCrypto from "node:crypto";+import * as NodeFS from "node:fs";+import * as NodeOS from "node:os";+import * as NodePath from "node:path";+import { afterEach, describe, expect, it } from "vite-plus/test";++import { BotId } from "@t3tools/contracts";+import { BOT_INBOX_KINDS, BotInboxService } from "./service.ts";++const directories: string[] = [];++afterEach(() => {+ for (const directory of directories.splice(0)) {+ NodeFS.rmSync(directory, { recursive: true, force: true });+ }+});++function makeService(times: readonly string[]) {+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-bot-inbox-"));+ directories.push(directory);+ const remaining = [...times];+ const filePath = NodePath.join(directory, `${NodeCrypto.randomUUID()}.json`);+ return {+ filePath,+ service: new BotInboxService(filePath, () => remaining.shift() ?? times.at(-1)!),+ };+}++const incident = {+ incidentKey: "connector:xai:bot-akeru",+ kind: "connector-failure" as const,+ botId: BotId.make("bot-akeru"),+ botName: "Akeru",+ taskOrRoutine: "Morning research",+ lastFailure: "Grok rejected the first ACP request.",+ nextAction: "Reconnect Grok in Settings.",+};++describe("bot inbox incidents", () => {+ it("accepts every action-required event kind", () => {+ expect(BOT_INBOX_KINDS).toEqual([+ "oauth-expired",+ "connector-failure",+ "routine-failure",+ "browser-dead",+ "silence-watchdog-failure",+ "approval-request",+ ]);+ for (const kind of BOT_INBOX_KINDS) {+ const { service } = makeService(["2026-08-30T20:00:00.000Z"]);+ expect(service.upsert({ ...incident, incidentKey: `kind:${kind}`, kind }).kind).toBe(kind);+ }+ });++ it("deduplicates an open incident and keeps the latest failure", () => {+ const { service } = makeService(["2026-08-30T20:00:00.000Z", "2026-08-30T20:01:00.000Z"]);+ const first = service.upsert(incident);+ const second = service.upsert({ ...incident, lastFailure: "OAuth was revoked." });++ expect(second.id).toBe(first.id);+ expect(second.occurrenceCount).toBe(2);+ expect(second.lastFailure).toBe("OAuth was revoked.");+ expect(service.list()).toHaveLength(1);+ });++ it("does not count a Settings snapshot as another occurrence", () => {+ const { service } = makeService(["2026-08-30T20:00:00.000Z", "2026-08-30T20:01:00.000Z"]);+ const first = service.ensureOpen(incident);+ const second = service.ensureOpen(incident);++ expect(second.id).toBe(first.id);+ expect(second.occurrenceCount).toBe(1);+ expect(second.lastSeenAt).toBe("2026-08-30T20:00:00.000Z");+ });++ it("resolves on recovery and opens a new incident after a later failure", () => {+ const { filePath, service } = makeService([+ "2026-08-30T20:00:00.000Z",+ "2026-08-30T20:02:00.000Z",+ "2026-08-30T20:03:00.000Z",+ ]);+ const first = service.upsert(incident);+ expect(service.resolve(incident.incidentKey)).toBe(true);+ const next = service.upsert(incident);++ expect(next.id).not.toBe(first.id);+ expect(service.list().map((item) => item.status)).toEqual(["open", "resolved"]);+ expect(new BotInboxService(filePath).list()).toHaveLength(2);+ });++ it("preserves incidents written by another service instance", () => {+ const { filePath, service: approvalWriter } = makeService([+ "2026-08-30T20:00:00.000Z",+ "2026-08-30T20:01:00.000Z",+ ]);+ const connectorWriter = new BotInboxService(filePath, () => "2026-08-30T20:02:00.000Z");++ approvalWriter.upsert({+ ...incident,+ incidentKey: "approval:request-1",+ kind: "approval-request",+ });+ connectorWriter.ensureOpen(incident);++ expect(new BotInboxService(filePath).list().map((item) => item.incidentKey)).toEqual([+ incident.incidentKey,+ "approval:request-1",+ ]);+ });+});diff --git a/apps/server/src/bot-inbox/service.ts b/apps/server/src/bot-inbox/service.tsnew file mode 100644index 000000000..61ad7a58a--- /dev/null+++ b/apps/server/src/bot-inbox/service.ts@@ -0,0 +1,156 @@+// @effect-diagnostics nodeBuiltinImport:off globalDate:off+import * as NodeCrypto from "node:crypto";+import * as NodeFS from "node:fs";+import * as NodePath from "node:path";+import type { BotId } from "@t3tools/contracts";++export const BOT_INBOX_KINDS = [+ "oauth-expired",+ "connector-failure",+ "routine-failure",+ "browser-dead",+ "silence-watchdog-failure",+ "approval-request",+] as const;++export type BotInboxKind = (typeof BOT_INBOX_KINDS)[number];++export interface BotInboxItem {+ readonly id: string;+ readonly incidentKey: string;+ readonly kind: BotInboxKind;+ readonly status: "open" | "resolved";+ readonly botId: BotId;+ readonly botName: string;+ readonly taskOrRoutine: string;+ readonly lastFailure: string;+ readonly nextAction: string;+ readonly firstSeenAt: string;+ readonly lastSeenAt: string;+ readonly resolvedAt?: string;+ readonly occurrenceCount: number;+}++export type BotInboxIncident = Pick<+ BotInboxItem,+ "incidentKey" | "kind" | "botId" | "botName" | "taskOrRoutine" | "lastFailure" | "nextAction"+>;++export class BotInboxService {+ private items: BotInboxItem[] = [];+ private readonly filePath: string;+ private readonly now: () => string;++ constructor(filePath: string, now: () => string = () => new Date().toISOString()) {+ this.filePath = filePath;+ this.now = now;+ this.reload();+ }++ static forSecretsDir(secretsDir: string): BotInboxService {+ return new BotInboxService(NodePath.join(secretsDir, "bot-inbox.json"));+ }++ reload(): void {+ if (!NodeFS.existsSync(this.filePath)) {+ this.items = [];+ return;+ }+ try {+ const decoded = JSON.parse(NodeFS.readFileSync(this.filePath, "utf-8")) as BotInboxItem[];+ this.items = Array.isArray(decoded) ? decoded : [];+ } catch {+ this.items = [];+ }+ }++ list(): ReadonlyArray<BotInboxItem> {+ return [...this.items].sort((left, right) => right.lastSeenAt.localeCompare(left.lastSeenAt));+ }++ upsert(incident: BotInboxIncident): BotInboxItem {+ this.reload();+ const seenAt = this.now();+ const existingIndex = this.items.findIndex(+ (item) => item.incidentKey === incident.incidentKey && item.status === "open",+ );+ if (existingIndex >= 0) {+ const existing = this.items[existingIndex]!;+ const updated: BotInboxItem = {+ ...existing,+ ...incident,+ lastSeenAt: seenAt,+ occurrenceCount: existing.occurrenceCount + 1,+ };+ this.items[existingIndex] = updated;+ this.save();+ return updated;+ }++ const created: BotInboxItem = {+ id: NodeCrypto.randomUUID(),+ ...incident,+ status: "open",+ firstSeenAt: seenAt,+ lastSeenAt: seenAt,+ occurrenceCount: 1,+ };+ this.items.push(created);+ this.save();+ return created;+ }++ ensureOpen(incident: BotInboxIncident): BotInboxItem {+ this.reload();+ const existingIndex = this.items.findIndex(+ (item) => item.incidentKey === incident.incidentKey && item.status === "open",+ );+ if (existingIndex < 0) return this.upsert(incident);++ const existing = this.items[existingIndex]!;+ if (+ existing.kind === incident.kind &&+ existing.botId === incident.botId &&+ existing.botName === incident.botName &&+ existing.taskOrRoutine === incident.taskOrRoutine &&+ existing.lastFailure === incident.lastFailure &&+ existing.nextAction === incident.nextAction+ ) {+ return existing;+ }++ const updated = {+ ...existing,+ ...incident,+ lastSeenAt: this.now(),+ };+ this.items[existingIndex] = updated;+ this.save();+ return updated;+ }++ resolve(incidentKey: string): boolean {+ this.reload();+ const resolvedAt = this.now();+ let changed = false;+ this.items = this.items.map((item) => {+ if (item.incidentKey !== incidentKey || item.status === "resolved") return item;+ changed = true;+ return { ...item, status: "resolved", resolvedAt, lastSeenAt: resolvedAt };+ });+ if (changed) this.save();+ return changed;+ }++ private save(): void {+ const directory = NodePath.dirname(this.filePath);+ NodeFS.mkdirSync(directory, { recursive: true, mode: 0o700 });+ const temporaryPath = `${this.filePath}.${NodeCrypto.randomUUID()}.tmp`;+ NodeFS.writeFileSync(temporaryPath, JSON.stringify(this.items, null, 2), {+ encoding: "utf-8",+ mode: 0o600,+ });+ NodeFS.renameSync(temporaryPath, this.filePath);+ NodeFS.chmodSync(this.filePath, 0o600);+ }+}diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.tsindex 49f6a2389..5b84aa107 100644--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts@@ -12,6 +12,7 @@ import {} from "@t3tools/contracts";import {ApprovalRequestId,+ BotId,CommandId,DEFAULT_PROVIDER_INTERACTION_MODE,EventId,@@ -19,6 +20,7 @@ import {type OrchestrationCommand,ProjectId,ProviderItemId,+ RuntimeRequestId,type ServerSettings,ThreadId,TurnId,@@ -55,6 +57,7 @@ import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"import { ServerConfig } from "../../config.ts";import { ServerSettingsService } from "../../serverSettings.ts";import * as NodeServices from "@effect/platform-node/NodeServices";+import { BotInboxService } from "../../bot-inbox/service.ts";function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {return ServerSettingsService.layerTest(overrides);@@ -214,6 +217,7 @@ describe("ProviderRuntimeIngestion", () => {async function createHarness(options?: {serverSettings?: Partial<ServerSettings>;threadTitle?: string;+ botOwned?: boolean;}) {const workspaceRoot = makeTempDir("t3-provider-project-");NodeFS.mkdirSync(NodePath.join(workspaceRoot, ".git"));@@ -240,7 +244,7 @@ describe("ProviderRuntimeIngestion", () => {Layer.provideMerge(SqlitePersistenceMemory),Layer.provideMerge(Layer.succeed(AgentController, provider.service)),Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),- Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), workspaceRoot)),Layer.provideMerge(NodeServices.layer),);runtime = ManagedRuntime.make(layer);@@ -265,11 +269,31 @@ describe("ProviderRuntimeIngestion", () => {},createdAt,});+ if (options?.botOwned) {+ await dispatch({+ type: "bot.create",+ commandId: CommandId.make("cmd-bot-create"),+ botId: BotId.make("bot-akeru"),+ name: "Akeru",+ title: "Research bot",+ avatar: { kind: "dither", seed: "akeru" },+ engine: {+ provider: ProviderInstanceId.make("codex"),+ model: "gpt-5-codex",+ },+ sandbox: null,+ runtimeMode: "approval-required",+ usageCap: null,+ groupId: null,+ createdAt,+ });+ }await dispatch({type: "thread.create",commandId: CommandId.make("cmd-thread-create"),threadId: ThreadId.make("thread-1"),projectId: asProjectId("project-1"),+ ...(options?.botOwned ? { botId: BotId.make("bot-akeru") } : {}),title: options?.threadTitle ?? "Thread",modelSelection: {instanceId: ProviderInstanceId.make("codex"),@@ -312,9 +336,56 @@ describe("ProviderRuntimeIngestion", () => {emit: provider.emit,setProviderSession: provider.setSession,drain,+ botInbox: new BotInboxService(+ NodePath.join(workspaceRoot, "userdata", "secrets", "bot-inbox.json"),+ ),};}+ it("opens and resolves bot inbox approval incidents from runtime requests", async () => {+ const harness = await createHarness({ botOwned: true, threadTitle: "Morning research" });+ const base = {+ provider: ProviderDriverKind.make("codex"),+ threadId: asThreadId("thread-1"),+ createdAt: "2026-01-01T00:00:01.000Z",+ requestId: RuntimeRequestId.make("approval-1"),+ };++ harness.emit({+ ...base,+ type: "request.opened",+ eventId: asEventId("evt-approval-opened"),+ payload: {+ requestType: "command_execution_approval",+ detail: "Allow the booking command?",+ },+ });+ await harness.drain();+ harness.botInbox.reload();+ expect(harness.botInbox.list()).toEqual([+ expect.objectContaining({+ kind: "approval-request",+ status: "open",+ botName: "Akeru",+ taskOrRoutine: "Morning research",+ lastFailure: "Allow the booking command?",+ }),+ ]);++ harness.emit({+ ...base,+ type: "request.resolved",+ eventId: asEventId("evt-approval-resolved"),+ payload: {+ requestType: "command_execution_approval",+ decision: "accept",+ },+ });+ await harness.drain();+ harness.botInbox.reload();+ expect(harness.botInbox.list()[0]?.status).toBe("resolved");+ });+it("maps turn started/completed events into thread session updates", async () => {const harness = await createHarness();const now = "2026-01-01T00:00:00.000Z";diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.tsindex b2807c822..fd5a3ab74 100644--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts@@ -18,6 +18,7 @@ import {type OrchestrationProposedPlan,type OrchestrationThread,type OrchestrationThreadActivity,+ type OrchestrationThreadShell,type ProviderRuntimeEvent,ProductFeedbackToolDraft,} from "@t3tools/contracts";@@ -49,6 +50,8 @@ import { projectActivityPayload } from "../ActivityPayloadProjection.ts";import { forkParked } from "../../serverActivation.ts";import { ServerSettingsService } from "../../serverSettings.ts";import { canReplaceThreadTitle } from "../threadTitles.ts";+import { ServerConfig } from "../../config.ts";+import { BotInboxService } from "../../bot-inbox/service.ts";const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`;@@ -912,6 +915,8 @@ const make = Effect.gen(function* () {const agentController = yield* AgentController;const projectionTurnRepository = yield* ProjectionTurnRepository;const serverSettingsService = yield* ServerSettingsService;+ const serverConfig = yield* ServerConfig;+ const botInbox = BotInboxService.forSecretsDir(serverConfig.secretsDir);const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>crypto.randomUUIDv4.pipe(Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),@@ -977,6 +982,34 @@ const make = Effect.gen(function* () {.pipe(Effect.map(Option.getOrUndefined));});+ const syncApprovalInbox = Effect.fn("syncApprovalInbox")(function* (+ event: Extract<ProviderRuntimeEvent, { type: "request.opened" | "request.resolved" }>,+ thread: OrchestrationThreadShell,+ ) {+ const botId = thread.respondingBotId ?? thread.botId;+ if (!botId) return;+ const snapshot = yield* projectionSnapshotQuery.getShellSnapshot();+ const bot = snapshot.bots.find((candidate) => candidate.id === botId);+ if (!bot) return;+ const incidentKey = `approval:${event.requestId}`;+ yield* Effect.sync(() => {+ botInbox.reload();+ if (event.type === "request.resolved") {+ botInbox.resolve(incidentKey);+ return;+ }+ botInbox.ensureOpen({+ incidentKey,+ kind: "approval-request",+ botId,+ botName: bot.name,+ taskOrRoutine: thread.title,+ lastFailure: event.payload.detail ?? "This request needs approval.",+ nextAction: "Open the thread and approve or decline the request.",+ });+ });+ });+const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(Effect.flatMap((existingIds) =>@@ -1513,6 +1546,9 @@ const make = Effect.gen(function* () {Effect.gen(function* () {const thread = yield* resolveThreadShell(event.threadId);if (!thread) return;+ if (event.type === "request.opened" || event.type === "request.resolved") {+ yield* syncApprovalInbox(event, thread);+ }let loadedThreadDetail: OrchestrationThread | null | undefined;const getLoadedThreadDetail = () =>diff --git a/apps/server/src/provider/Layers/AgentController.test.ts b/apps/server/src/provider/Layers/AgentController.test.tsindex c9c9bfa55..a45df932e 100644--- a/apps/server/src/provider/Layers/AgentController.test.ts+++ b/apps/server/src/provider/Layers/AgentController.test.ts@@ -9,6 +9,7 @@ import { LocalFilesystem, LocalSandbox, Workspace } from "@mastra/core/workspaceimport {AKERU_PRODUCT_FEEDBACK_TOOL_NAME,ApprovalRequestId,+ EventId,McpServerId,ProviderDriverKind,ProviderInstanceId,@@ -31,9 +32,11 @@ import type { ProviderServiceShape } from "../Services/ProviderService.ts";import {createAkeruMastraAuthStorage,makeAgentControllerLive,+ recordProviderAccessHealth,toMcpServerConfigs,type AgentControllerLiveOptions,} from "./AgentController.ts";+import { SubscriptionAuthService } from "../../subscription-auth/service.ts";const codexThreadId = ThreadId.make("thread-mastra-codex");const claudeThreadId = ThreadId.make("thread-legacy-claude");@@ -275,6 +278,130 @@ describe("toMcpServerConfigs", () => {});});+describe("provider access health", () => {+ it.each([+ ["codex", "openai-codex"],+ ["claudeAgent", "anthropic"],+ ["cursor", "cursor"],+ ["grok", "xai"],+ ["opencode", "kimi-for-coding"],+ ] as const)("maps %s runtime requests to %s access health", (driver, provider) => {+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-access-map-"));+ const authPath = NodePath.join(directory, "subscription-auth.json");+ try {+ NodeFS.writeFileSync(+ authPath,+ JSON.stringify({+ [provider]: { type: "oauth", access: "a", refresh: "r", expires: 1_900_000_000_000 },+ }),+ );+ const service = new SubscriptionAuthService(authPath);+ const providerInstanceId = ProviderInstanceId.make(`instance-${driver}`);+ const base = {+ provider: ProviderDriverKind.make(driver),+ providerInstanceId,+ threadId: ThreadId.make(`thread-${driver}`),+ };+ recordProviderAccessHealth(service, {+ ...base,+ type: "runtime.error",+ eventId: EventId.make(`evt-${driver}-failed`),+ createdAt: "2026-08-30T20:00:00.000Z",+ payload: { message: "The first request failed.", class: "provider_error" },+ });+ expect(+ service.statuses([], 1_800_000_000_000).find((item) => item.provider === provider),+ ).toMatchObject({ health: "failed-first-request" });+ expect(service.providerInstanceHealth(providerInstanceId)).toBe("failed-first-request");++ recordProviderAccessHealth(service, {+ ...base,+ type: "turn.completed",+ eventId: EventId.make(`evt-${driver}-recovered`),+ createdAt: "2026-08-30T20:01:00.000Z",+ turnId: TurnId.make(`turn-${driver}`),+ payload: { state: "completed", stopReason: null },+ });+ expect(+ service.statuses([], 1_800_000_000_000).find((item) => item.provider === provider),+ ).toMatchObject({ health: "recovered" });+ expect(service.providerInstanceHealth(providerInstanceId)).toBe("recovered");+ } finally {+ NodeFS.rmSync(directory, { recursive: true, force: true });+ }+ });++ it("records a failed first request and recovery at the runtime event boundary", () => {+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-access-health-"));+ const authPath = NodePath.join(directory, "subscription-auth.json");+ try {+ NodeFS.writeFileSync(+ authPath,+ JSON.stringify({+ xai: { type: "oauth", access: "a", refresh: "r", expires: 1_900_000_000_000 },+ }),+ );+ const service = new SubscriptionAuthService(authPath);+ const base = {+ provider: ProviderDriverKind.make("grok"),+ providerInstanceId: ProviderInstanceId.make("grok"),+ threadId: ThreadId.make("thread-health"),+ };+ recordProviderAccessHealth(service, {+ ...base,+ type: "runtime.error",+ eventId: EventId.make("evt-health-failed"),+ createdAt: "2026-08-30T20:00:00.000Z",+ payload: { message: "The first request failed.", class: "provider_error" },+ });+ expect(+ service.statuses([], 1_800_000_000_000).find((item) => item.provider === "xai")?.health,+ ).toBe("failed-first-request");+ expect(service.providerInstanceHealth("grok")).toBe("failed-first-request");++ recordProviderAccessHealth(service, {+ ...base,+ type: "turn.completed",+ eventId: EventId.make("evt-health-recovered"),+ createdAt: "2026-08-30T20:01:00.000Z",+ turnId: TurnId.make("turn-health"),+ payload: { state: "completed", stopReason: null },+ });+ expect(+ service.statuses([], 1_800_000_000_000).find((item) => item.provider === "xai")?.health,+ ).toBe("recovered");+ expect(service.providerInstanceHealth("grok")).toBe("recovered");+ } finally {+ NodeFS.rmSync(directory, { recursive: true, force: true });+ }+ });++ it.each(["interrupted", "cancelled"] as const)(+ "does not call a %s turn a successful provider request",+ (state) => {+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-access-stop-"));+ const authPath = NodePath.join(directory, "subscription-auth.json");+ try {+ const service = new SubscriptionAuthService(authPath);+ recordProviderAccessHealth(service, {+ provider: ProviderDriverKind.make("grok"),+ providerInstanceId: ProviderInstanceId.make("grok"),+ threadId: ThreadId.make("thread-stopped"),+ turnId: TurnId.make("turn-stopped"),+ type: "turn.completed",+ eventId: EventId.make(`evt-health-${state}`),+ createdAt: "2026-08-30T20:00:00.000Z",+ payload: { state, stopReason: null },+ });++ expect(service.providerInstanceHealth("grok")).toBeUndefined();+ } finally {+ NodeFS.rmSync(directory, { recursive: true, force: true });+ }+ },+ );+});+describe("AgentControllerLive", () => {it.effect("reads Akeru subscription credentials through Mastra AuthStorage", () =>Effect.gen(function* () {diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.tsindex 6d7ea8c18..13e47588c 100644--- a/apps/server/src/provider/Layers/AgentController.ts+++ b/apps/server/src/provider/Layers/AgentController.ts@@ -39,6 +39,10 @@ import * as Stream from "effect/Stream";import { resolveAttachmentPath } from "../../attachmentStore.ts";import { ServerConfig } from "../../config.ts";+import {+ SubscriptionAuthService,+ type SubscriptionProviderId,+} from "../../subscription-auth/service.ts";import {createAkeruMastraHarness,type AkeruMastraHarness,@@ -161,6 +165,63 @@ function usesMastraCode(provider: ProviderDriverKind): boolean {return String(provider) === "codex";}+function subscriptionProviderForDriver(+ provider: ProviderDriverKind,+): SubscriptionProviderId | undefined {+ switch (String(provider)) {+ case "codex":+ return "openai-codex";+ case "claudeAgent":+ return "anthropic";+ case "cursor":+ return "cursor";+ case "grok":+ return "xai";+ case "opencode":+ return "kimi-for-coding";+ default:+ return undefined;+ }+}++export function recordProviderAccessHealth(+ subscriptionAuth: SubscriptionAuthService,+ event: ProviderRuntimeEvent,+): void {+ const provider = subscriptionProviderForDriver(event.provider);+ const providerInstanceId = event.providerInstanceId;+ if (event.type === "turn.completed") {+ if (event.payload.state === "failed") {+ const message = event.payload.errorMessage ?? "The provider request failed.";+ if (provider) subscriptionAuth.recordRequestFailure(provider, message, event.createdAt);+ if (providerInstanceId) {+ subscriptionAuth.recordProviderInstanceFailure(+ providerInstanceId,+ message,+ event.createdAt,+ );+ }+ } else if (event.payload.state === "completed") {+ if (provider) subscriptionAuth.recordRequestSuccess(provider, event.createdAt);+ if (providerInstanceId) {+ subscriptionAuth.recordProviderInstanceSuccess(providerInstanceId, event.createdAt);+ }+ }+ return;+ }+ if (event.type !== "runtime.error" || event.payload.class !== "provider_error") return;+ if (provider) {+ subscriptionAuth.recordRequestFailure(provider, event.payload.message, event.createdAt);+ }+ if (providerInstanceId) {+ subscriptionAuth.recordProviderInstanceFailure(+ providerInstanceId,+ event.payload.message,+ event.createdAt,+ );+ }+}+function itemType(toolName: string,): "command_execution" | "file_change" | "mcp_tool_call" | "dynamic_tool_call" {@@ -195,6 +256,7 @@ const make = (options?: AgentControllerLiveOptions) =>});const authStorage = createAkeruMastraAuthStorage(config.secretsDir);+ const subscriptionAuth = SubscriptionAuthService.forSecretsDir(config.secretsDir);const mcpManagers = new Map<string, McpManager>();const workspaces = new Map<string, Workspace>();const makeMastraHarness = options?.makeMastraHarness ?? createAkeruMastraHarness;@@ -910,7 +972,16 @@ const make = (options?: AgentControllerLiveOptions) =>rollbackConversation,uploadFeedback: legacyProviderBridge.uploadFeedback,get streamEvents() {- return Stream.merge(legacyProviderBridge.streamEvents, Stream.fromPubSub(runtimeEvents));+ return Stream.merge(+ legacyProviderBridge.streamEvents,+ Stream.fromPubSub(runtimeEvents),+ ).pipe(+ Stream.tap((event) =>+ Effect.sync(() => {+ recordProviderAccessHealth(subscriptionAuth, event);+ }),+ ),+ );},});});diff --git a/apps/server/src/subscription-auth/service.test.ts b/apps/server/src/subscription-auth/service.test.tsindex 2885b7686..a6c797af1 100644--- a/apps/server/src/subscription-auth/service.test.ts+++ b/apps/server/src/subscription-auth/service.test.ts@@ -3,7 +3,7 @@ import * as NodeFS from "node:fs";import * as NodePath from "node:path";import * as NodeOS from "node:os";import * as NodeCrypto from "node:crypto";-import { describe, expect, it } from "vite-plus/test";+import { describe, expect, it, vi } from "vite-plus/test";import { SubscriptionAuthService } from "./service.ts";@@ -38,6 +38,11 @@ describe("subscription auth storage", () => {provider: "anthropic",connected: true,expiresAt: 1_800_000_000_000,+ health: "detected",+ reconnectAction: "Reconnect account",+ healthTest: { status: "not-run" },+ dependentBots: [],+ dependentRoutines: [],});expect(JSON.stringify(service.statuses())).not.toContain("secret-access");expect(JSON.stringify(service.statuses())).not.toContain("secret-refresh");@@ -86,4 +91,112 @@ describe("subscription auth storage", () => {expect(JSON.parse(NodeFS.readFileSync(authPath, "utf-8"))).toEqual({});expect(NodeFS.statSync(authPath).mode & 0o777).toBe(0o600);});++ it("reports expiry, failure, and recovery without calling detection healthy", () => {+ const { authPath } = fixture();+ NodeFS.writeFileSync(+ authPath,+ JSON.stringify({ anthropic: { type: "oauth", access: "a", refresh: "r", expires: 100 } }),+ );+ const service = new SubscriptionAuthService(authPath);++ expect(service.statuses([], 101)[0]?.health).toBe("expired");+ service.recordRequestFailure("anthropic", "OAuth was revoked.", "2026-08-30T20:00:00.000Z");+ expect(service.statuses([], 50)[0]?.health).toBe("failed-first-request");+ service.recordRequestSuccess("anthropic", "2026-08-30T20:01:00.000Z");+ expect(service.statuses([], 50)[0]?.health).toBe("recovered");+ service.recordRequestFailure("anthropic", "OAuth was revoked.", "2026-08-30T20:02:00.000Z");+ expect(service.statuses([], 50)[0]?.health).toBe("failed");+ service.recordRequestFailure(+ "anthropic",+ "OAuth was revoked.",+ "2026-08-30T20:03:00.000Z",+ "revoked",+ );+ expect(service.statuses([], 50)[0]?.health).toBe("revoked");+ });++ it("does not call an automatic OAuth refresh a successful provider request", async () => {+ const { authPath } = fixture();+ NodeFS.writeFileSync(+ authPath,+ JSON.stringify({ xai: { type: "oauth", access: "a", refresh: "r", expires: 0 } }),+ );+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ access_token: "refreshed", expires_in: 3600 }), {+ status: 200,+ headers: { "content-type": "application/json" },+ }),+ ),+ );+ const service = new SubscriptionAuthService(authPath);+ await service.getAccessToken("xai");++ expect(service.statuses().find((status) => status.provider === "xai")?.health).toBe("detected");+ vi.unstubAllGlobals();+ });++ it("keeps an OAuth check separate from a real provider health test", async () => {+ const { authPath } = fixture();+ NodeFS.writeFileSync(+ authPath,+ JSON.stringify({ xai: { type: "oauth", access: "a", refresh: "r", expires: 0 } }),+ );+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ access_token: "refreshed", expires_in: 3600 }), {+ status: 200,+ headers: { "content-type": "application/json" },+ }),+ ),+ );+ const service = new SubscriptionAuthService(authPath);+ await service.testHealth("xai");++ expect(service.statuses().find((status) => status.provider === "xai")).toMatchObject({+ health: "detected",+ healthTest: { status: "not-run" },+ oauthCheck: { status: "passed" },+ });+ vi.unstubAllGlobals();+ });++ it("tracks provider-instance failure and recovery from real requests", () => {+ const { authPath } = fixture();+ const service = new SubscriptionAuthService(authPath);++ service.recordProviderInstanceFailure(+ "grok",+ "The first request failed.",+ "2026-08-30T20:00:00.000Z",+ );+ expect(service.providerInstanceHealth("grok")).toBe("failed-first-request");+ service.recordProviderInstanceSuccess("grok", "2026-08-30T20:01:00.000Z");+ expect(service.providerInstanceHealth("grok")).toBe("recovered");+ expect(new SubscriptionAuthService(authPath).providerInstanceHealth("grok")).toBe("recovered");+ });++ it("preserves health updates written by another service instance", () => {+ const { authPath } = fixture();+ const providerRuntime = new SubscriptionAuthService(authPath);+ const rpcRuntime = new SubscriptionAuthService(authPath);++ providerRuntime.recordProviderInstanceSuccess("grok", "2026-08-30T20:00:00.000Z");+ rpcRuntime.recordRequestFailure(+ "xai",+ "The OAuth grant was revoked.",+ "2026-08-30T20:01:00.000Z",+ "revoked",+ );++ const restarted = new SubscriptionAuthService(authPath);+ expect(restarted.providerInstanceHealth("grok")).toBe("healthy");+ expect(restarted.statuses().find((status) => status.provider === "xai")).toMatchObject({+ health: "missing",+ lastFailedRequest: { message: "The OAuth grant was revoked." },+ });+ });});diff --git a/apps/server/src/subscription-auth/service.ts b/apps/server/src/subscription-auth/service.tsindex 630686712..6420af1c1 100644--- a/apps/server/src/subscription-auth/service.ts+++ b/apps/server/src/subscription-auth/service.ts@@ -17,6 +17,7 @@import * as NodeFS from "node:fs";import * as NodePath from "node:path";import * as NodeCrypto from "node:crypto";+import type { BotId } from "@t3tools/contracts";import {completeAnthropicLogin,@@ -87,6 +88,41 @@ export interface ProviderStatus {connected: boolean;/** ms epoch when the current access token expires; refreshed on demand. */expiresAt?: number;+ health:+ | "missing"+ | "detected"+ | "healthy"+ | "expired"+ | "revoked"+ | "failed"+ | "failed-first-request"+ | "recovered";+ lastSuccessfulRequestAt?: string;+ lastFailedRequest?: { at: string; message: string };+ nextRetryAt?: string;+ reconnectAction: string;+ healthTest: { status: "not-run" | "passed" | "failed"; checkedAt?: string };+ oauthCheck?: { status: "passed" | "failed"; checkedAt: string };+ dependentBots: ReadonlyArray<{ id: BotId; name: string }>;+ dependentRoutines: ReadonlyArray<string>;+}++interface ProviderHealthRecord {+ lastSuccessfulRequestAt?: string;+ lastFailedRequest?: { at: string; message: string };+ nextRetryAt?: string;+ healthTest?: { status: "passed" | "failed"; checkedAt: string };+ oauthCheck?: { status: "passed" | "failed"; checkedAt: string };+ failureKind?: "request" | "revoked";+}++type ProviderHealthData = Record<string, ProviderHealthRecord | undefined>;++function oauthFailureKind(cause: unknown): "request" | "revoked" {+ const message = cause instanceof Error ? cause.message : String(cause);+ return /\b(?:invalid_grant|revoked|unauthori[sz]ed|401|403)\b/i.test(message)+ ? "revoked"+ : "request";}type PendingLogin =@@ -103,12 +139,15 @@ export class SubscriptionAuthService {private data: SubscriptionAuthData = {};private readonly authPath: string;private readonly pendingPath: string;+ private readonly healthPath: string;+ private health: ProviderHealthData = {};private readonly pendingLogins = new Map<string, PendingLogin>();private readonly refreshInFlight = new Map<string, Promise<string | undefined>>();constructor(authPath: string) {this.authPath = authPath;this.pendingPath = `${authPath}.pending`;+ this.healthPath = `${authPath}.health`;this.reload();}@@ -127,6 +166,8 @@ export class SubscriptionAuthService {}}+ this.reloadHealth();+this.pendingLogins.clear();if (!NodeFS.existsSync(this.pendingPath)) return;try {@@ -141,6 +182,18 @@ export class SubscriptionAuthService {}}+ private reloadHealth(): void {+ if (!NodeFS.existsSync(this.healthPath)) {+ this.health = {};+ return;+ }+ try {+ this.health = JSON.parse(NodeFS.readFileSync(this.healthPath, "utf-8")) as ProviderHealthData;+ } catch {+ this.health = {};+ }+ }+private writeSecureJson(filePath: string, value: unknown): void {const dir = NodePath.dirname(filePath);if (!NodeFS.existsSync(dir)) {@@ -163,15 +216,187 @@ export class SubscriptionAuthService {this.writeSecureJson(this.pendingPath, [...this.pendingLogins.entries()]);}- statuses(): ProviderStatus[] {+ private saveHealth(): void {+ this.writeSecureJson(this.healthPath, this.health);+ }++ statuses(+ dependentBots: ReadonlyArray<{+ readonly id: BotId;+ readonly name: string;+ readonly provider: SubscriptionProviderId;+ }> = [],+ now = Date.now(),+ ): ProviderStatus[] {return SUBSCRIPTION_PROVIDER_IDS.map((provider) => {const credential = this.data[provider];- return credential- ? { provider, connected: true, expiresAt: credential.expires }- : { provider, connected: false };+ const health = this.health[provider];+ const expired = credential !== undefined && 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 state = !credential+ ? "missing"+ : failedAfterSuccess+ ? health?.failureKind === "revoked"+ ? "revoked"+ : health?.lastSuccessfulRequestAt+ ? "failed"+ : "failed-first-request"+ : expired+ ? "expired"+ : recovered+ ? "recovered"+ : health?.lastSuccessfulRequestAt+ ? "healthy"+ : "detected";+ return {+ provider,+ connected: credential !== undefined,+ ...(credential ? { expiresAt: credential.expires } : {}),+ health: state,+ ...(health?.lastSuccessfulRequestAt+ ? { lastSuccessfulRequestAt: health.lastSuccessfulRequestAt }+ : {}),+ ...(health?.lastFailedRequest ? { lastFailedRequest: health.lastFailedRequest } : {}),+ ...(health?.nextRetryAt ? { nextRetryAt: health.nextRetryAt } : {}),+ reconnectAction: credential ? "Reconnect account" : "Connect account",+ healthTest: health?.healthTest ?? { status: "not-run" },+ ...(health?.oauthCheck ? { oauthCheck: health.oauthCheck } : {}),+ dependentBots: dependentBots+ .filter((bot) => bot.provider === provider)+ .map(({ id, name }) => ({ id, name })),+ dependentRoutines: [],+ };});}+ recordRequestSuccess(provider: SubscriptionProviderId, at = new Date().toISOString()): void {+ this.recordHealthSuccess(provider, at);+ }++ recordProviderInstanceSuccess(instanceId: string, at = new Date().toISOString()): void {+ this.recordHealthSuccess(`provider:${instanceId}`, at);+ }++ private recordHealthSuccess(key: string, at: string): void {+ this.reloadHealth();+ const previous = this.health[key];+ const { nextRetryAt: _nextRetryAt, ...rest } = previous ?? {};+ this.health[key] = {+ ...rest,+ lastSuccessfulRequestAt: at,+ healthTest: { status: "passed", checkedAt: at },+ };+ this.saveHealth();+ }++ recordRequestFailure(+ provider: SubscriptionProviderId,+ message: string,+ at = new Date().toISOString(),+ failureKind: "request" | "revoked" = "request",+ ): void {+ this.recordHealthFailure(provider, message, at, failureKind);+ }++ recordProviderInstanceFailure(+ instanceId: string,+ message: string,+ at = new Date().toISOString(),+ ): void {+ this.recordHealthFailure(`provider:${instanceId}`, message, at, "request");+ }++ private recordHealthFailure(+ key: string,+ message: string,+ at: string,+ failureKind: "request" | "revoked",+ ): void {+ this.reloadHealth();+ const { nextRetryAt: _nextRetryAt, ...previous } = this.health[key] ?? {};+ this.health[key] = {+ ...previous,+ lastFailedRequest: { at, message },+ failureKind,+ healthTest: { status: "failed", checkedAt: at },+ };+ this.saveHealth();+ }++ providerInstanceHealth(+ instanceId: string,+ ): "healthy" | "failed" | "failed-first-request" | "recovered" | undefined {+ const health = this.health[`provider:${instanceId}`];+ if (!health) return undefined;+ if (+ health.lastFailedRequest &&+ (!health.lastSuccessfulRequestAt ||+ health.lastFailedRequest.at >= health.lastSuccessfulRequestAt)+ ) {+ return health.lastSuccessfulRequestAt ? "failed" : "failed-first-request";+ }+ if (+ health.lastSuccessfulRequestAt &&+ health.lastFailedRequest &&+ health.lastSuccessfulRequestAt > health.lastFailedRequest.at+ ) {+ return "recovered";+ }+ return health.lastSuccessfulRequestAt ? "healthy" : undefined;+ }++ async testHealth(provider: SubscriptionProviderId): Promise<void> {+ const credential = this.data[provider];+ if (!credential) {+ this.recordOAuthFailure(provider, "No account is connected.");+ return;+ }+ try {+ const refreshed = await this.runRefresh(provider, credential);+ this.setCredential(provider, refreshed);+ // Refresh proves the OAuth grant is usable. It does not prove that the+ // subscription can make a model request, so keep access detected until+ // the runtime records the first successful provider request.+ const checkedAt = new Date().toISOString();+ this.reloadHealth();+ this.health[provider] = {+ ...this.health[provider],+ oauthCheck: { status: "passed", checkedAt },+ };+ this.saveHealth();+ } catch (cause) {+ this.recordOAuthFailure(+ provider,+ cause instanceof Error ? cause.message : "The provider rejected the health request.",+ oauthFailureKind(cause),+ );+ }+ }++ private recordOAuthFailure(+ provider: SubscriptionProviderId,+ message: string,+ failureKind: "request" | "revoked" = "request",+ ): void {+ const checkedAt = new Date().toISOString();+ this.reloadHealth();+ const { nextRetryAt: _nextRetryAt, ...previous } = this.health[provider] ?? {};+ this.health[provider] = {+ ...previous,+ lastFailedRequest: { at: checkedAt, message },+ failureKind,+ oauthCheck: { status: "failed", checkedAt },+ };+ this.saveHealth();+ }+isConnected(provider: SubscriptionProviderId): boolean {return this.data[provider] !== undefined;}@@ -347,7 +572,10 @@ export class SubscriptionAuthService {logout(provider: SubscriptionProviderId): void {delete this.data[provider];+ this.reloadHealth();+ delete this.health[provider];this.save();+ this.saveHealth();}private setCredential(provider: SubscriptionProviderId, credentials: OAuthCredentials): void {@@ -398,9 +626,14 @@ export class SubscriptionAuthService {const refreshed = await this.runRefresh(provider, credential);this.setCredential(provider, refreshed);return refreshed.access;- } catch {+ } catch (cause) {// Refresh failed — the user must re-connect. Keep the stored credential// so status still shows which account was linked.+ this.recordOAuthFailure(+ provider,+ cause instanceof Error ? cause.message : "The provider rejected the token refresh.",+ oauthFailureKind(cause),+ );return undefined;}}diff --git a/apps/server/src/subscription-auth/snapshot.test.ts b/apps/server/src/subscription-auth/snapshot.test.tsnew file mode 100644index 000000000..e41f5b5be--- /dev/null+++ b/apps/server/src/subscription-auth/snapshot.test.ts@@ -0,0 +1,148 @@+import { BotId, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import { buildProviderAccessCapabilities } from "./snapshot.ts";+import type { ProviderStatus } from "./service.ts";++const baseSubscription: ProviderStatus = {+ provider: "xai",+ connected: true,+ health: "detected",+ reconnectAction: "Reconnect account",+ healthTest: { status: "not-run" },+ dependentBots: [],+ dependentRoutines: [],+};++function grokProvider(status: "ready" | "error", authenticated: boolean) {+ return {+ instanceId: ProviderInstanceId.make("grok"),+ driver: ProviderDriverKind.make("grok"),+ enabled: true,+ installed: true,+ version: "1.0.0",+ status,+ auth: { status: authenticated ? ("authenticated" as const) : ("unknown" as const) },+ checkedAt: "2026-08-30T20:00:00.000Z",+ models: [],+ slashCommands: [],+ skills: [],+ };+}++function providerFixture(+ instanceId: string,+ driver: string,+ authType: "apiKey" | "oauth" | undefined,+) {+ return {+ instanceId: ProviderInstanceId.make(instanceId),+ driver: ProviderDriverKind.make(driver),+ displayName: driver,+ enabled: true,+ installed: true,+ version: "1.0.0",+ status: "ready" as const,+ auth: { status: "authenticated" as const, ...(authType ? { type: authType } : {}) },+ checkedAt: "2026-08-30T20:00:00.000Z",+ models: [],+ slashCommands: [],+ skills: [],+ };+}++describe("provider access capabilities", () => {+ it.each([+ ["openai-codex", "chatgpt", "expired"],+ ["anthropic", "claude-max", "revoked"],+ ["cursor", "cursor-pro", "recovered"],+ ] as const)("reports %s subscription access on the %s row", (provider, rowId, health) => {+ const capabilities = buildProviderAccessCapabilities(+ [{ ...baseSubscription, provider, health }],+ [],+ );++ expect(capabilities.find((item) => item.id === rowId)).toMatchObject({+ health,+ apiAccess: "separate",+ });+ });++ it("does not call detected OAuth or a detected CLI healthy", () => {+ const capabilities = buildProviderAccessCapabilities(+ [baseSubscription],+ [grokProvider("error", false)],+ );++ expect(capabilities.find((item) => item.id === "xai-subscription")?.health).toBe("detected");+ expect(capabilities.find((item) => item.id === "supergrok")?.health).toBe("unsupported");+ expect(capabilities.find((item) => item.id === "grok-acp")?.health).toBe(+ "failed-first-request",+ );+ });++ it("reports recovery without claiming X Premium+ or CLI health", () => {+ const capabilities = buildProviderAccessCapabilities(+ [+ {+ ...baseSubscription,+ health: "recovered",+ dependentBots: [{ id: BotId.make("bot-1"), name: "Akeru" }],+ },+ ],+ [grokProvider("ready", true)],+ );++ expect(capabilities.find((item) => item.id === "x-premium-plus")).toMatchObject({+ health: "unsupported",+ apiAccess: "separate",+ });+ expect(capabilities.find((item) => item.id === "xai-subscription")?.health).toBe("recovered");+ expect(capabilities.find((item) => item.id === "grok-acp")?.health).toBe("detected");+ });++ it("uses a real provider request to move an ACP CLI from detected to healthy", () => {+ const capabilities = buildProviderAccessCapabilities(+ [baseSubscription],+ [grokProvider("ready", true)],+ (instanceId) => (instanceId === "grok" ? "healthy" : undefined),+ );++ expect(capabilities.find((item) => item.id === "grok-acp")?.health).toBe("healthy");+ });++ it("keeps API keys and Cursor ACP detected until a real request passes", () => {+ const providers = [+ providerFixture("custom-openai", "codex", "apiKey"),+ providerFixture("cursor", "cursor", undefined),+ ];+ const detected = buildProviderAccessCapabilities([], providers);++ expect(detected.find((item) => item.id === "api-key-custom-openai")?.health).toBe("detected");+ expect(detected.find((item) => item.id === "cursor-acp")?.health).toBe("detected");++ const requested = buildProviderAccessCapabilities([], providers, (instanceId) =>+ instanceId === "custom-openai" ? "failed-first-request" : "recovered",+ );+ expect(requested.find((item) => item.id === "api-key-custom-openai")?.health).toBe(+ "failed-first-request",+ );+ expect(requested.find((item) => item.id === "cursor-acp")?.health).toBe("recovered");+ });++ it("labels unsupported browser gaps as temporary and gives a repair action", () => {+ const capabilities = buildProviderAccessCapabilities([], []);++ for (const id of ["email-browser", "shopping-browser", "booking-browser"]) {+ expect(capabilities.find((item) => item.id === id)).toMatchObject({+ accessMethod: "browser",+ health: "unsupported",+ temporary: true,+ });+ const capability = capabilities.find((item) => item.id === id);+ expect(+ capability && "repairAction" in capability ? capability.repairAction : undefined,+ ).toBeTruthy();+ }+ });+});diff --git a/apps/server/src/subscription-auth/snapshot.ts b/apps/server/src/subscription-auth/snapshot.tsnew file mode 100644index 000000000..9d3881c43--- /dev/null+++ b/apps/server/src/subscription-auth/snapshot.ts@@ -0,0 +1,190 @@+import type { BotEngine, BotId, ServerProvider } from "@t3tools/contracts";++import type { ProviderStatus, SubscriptionProviderId } from "./service.ts";++const SUBSCRIPTION_ACCESS = [+ { id: "chatgpt", label: "ChatGPT", provider: "openai-codex" },+ { id: "claude-max", label: "Claude Max", provider: "anthropic" },+ { id: "cursor-pro", label: "Cursor Pro", provider: "cursor" },+] as const;++const SUBSCRIPTION_DRIVER: Readonly<Record<SubscriptionProviderId, string>> = {+ anthropic: "claudeAgent",+ "openai-codex": "codex",+ cursor: "cursor",+ xai: "grok",+ "kimi-for-coding": "opencode",+};++export function subscriptionDependentBots(+ bots: ReadonlyArray<{+ readonly id: BotId;+ readonly name: string;+ readonly engine: BotEngine | null;+ }>,+ providers: ReadonlyArray<ServerProvider>,+) {+ return bots.flatMap((bot) => {+ if (!bot.engine) return [];+ const driver =+ providers.find((provider) => provider.instanceId === bot.engine?.provider)?.driver ??+ bot.engine.provider;+ const subscriptionProvider = Object.entries(SUBSCRIPTION_DRIVER).find(+ ([, candidate]) => candidate === driver,+ )?.[0] as SubscriptionProviderId | undefined;+ return subscriptionProvider+ ? [{ id: bot.id, name: bot.name, provider: subscriptionProvider }]+ : [];+ });+}++type ActualRequestHealth = "healthy" | "failed" | "failed-first-request" | "recovered" | undefined;++function providerAccessHealth(+ provider: ServerProvider | undefined,+ actualRequestHealth: ActualRequestHealth,+) {+ if (!provider || !provider.installed) return "missing" as const;+ if (provider.availability === "unavailable") return "unsupported" as const;+ if (provider.status === "error") return "failed-first-request" as const;+ if (actualRequestHealth) return actualRequestHealth;+ return "detected" as const;+}++export function buildProviderAccessCapabilities(+ subscriptions: ReadonlyArray<ProviderStatus>,+ providers: ReadonlyArray<ServerProvider>,+ providerRequestHealth: (instanceId: string) => ActualRequestHealth = () => undefined,+) {+ const subscriptionById = new Map(subscriptions.map((status) => [status.provider, status]));+ const subscriptionRows = SUBSCRIPTION_ACCESS.map((entry) => {+ const status = subscriptionById.get(entry.provider);+ return {+ id: entry.id,+ label: entry.label,+ accessMethod: "subscription-oauth" as const,+ health: status?.health ?? ("missing" as const),+ apiAccess: "separate" as const,+ nextAction:+ status?.health === "healthy" || status?.health === "recovered"+ ? "Send a provider request after the provider changes access."+ : status?.connected+ ? "Check OAuth, then send a provider request to verify access."+ : `Connect ${entry.label} in Settings.`,+ };+ });++ const apiKeyProviders = providers.filter((provider) => provider.auth.type === "apiKey");+ const apiKeyRows = apiKeyProviders.map((provider) => {+ const health = providerAccessHealth(+ provider,+ provider ? providerRequestHealth(provider.instanceId) : undefined,+ );+ return {+ id: `api-key-${provider.instanceId}`,+ label: `${provider.displayName ?? provider.driver} API key`,+ accessMethod: "api-key" as const,+ health,+ apiAccess: "included" as const,+ nextAction:+ health === "failed" || health === "failed-first-request"+ ? "Check the API key and billing, then retry a provider request."+ : "Send a provider request to verify the key and billing.",+ };+ });++ const acpRows = [+ { id: "cursor-acp", label: "Cursor ACP CLI", driver: "cursor" },+ { id: "grok-acp", label: "Grok ACP CLI", driver: "grok" },+ ].map((entry) => {+ const provider = providers.find((candidate) => candidate.driver === entry.driver);+ const health = providerAccessHealth(+ provider,+ provider ? providerRequestHealth(provider.instanceId) : undefined,+ );+ return {+ id: entry.id,+ label: entry.label,+ accessMethod: "acp-cli" as const,+ health,+ apiAccess: "not-applicable" as const,+ nextAction:+ health === "failed" || health === "failed-first-request"+ ? (provider?.message ?? "The first provider request failed.")+ : provider+ ? `Send a request through ${entry.label} to verify access.`+ : `Install and sign in to the ${entry.label}.`,+ };+ });++ return [+ ...subscriptionRows,+ {+ id: "xai-subscription",+ label: "xAI subscription login",+ accessMethod: "subscription-oauth" as const,+ health: subscriptionById.get("xai")?.health ?? ("missing" as const),+ apiAccess: "separate" as const,+ nextAction: "Send a Grok request to verify the shared xAI login.",+ },+ {+ id: "supergrok",+ label: "SuperGrok",+ accessMethod: "subscription-oauth" as const,+ health: "unsupported" as const,+ apiAccess: "separate" as const,+ nextAction: "Akeru cannot distinguish this plan from the shared xAI login.",+ },+ {+ id: "x-premium-plus",+ label: "X Premium+",+ accessMethod: "subscription-oauth" as const,+ health: "unsupported" as const,+ apiAccess: "separate" as const,+ nextAction: "Akeru cannot verify this plan from the shared xAI login.",+ },+ ...(apiKeyRows.length > 0+ ? apiKeyRows+ : [+ {+ id: "api-keys",+ label: "API keys",+ accessMethod: "api-key" as const,+ health: "missing" as const,+ apiAccess: "included" as const,+ nextAction: "Add a provider API key, then send a provider request.",+ },+ ]),+ ...acpRows,+ {+ id: "email-browser",+ label: "Email browser session",+ accessMethod: "browser" as const,+ health: "unsupported" as const,+ apiAccess: "not-applicable" as const,+ nextAction: "Use a supported email connector when one is available.",+ temporary: true,+ repairAction: "Add an email connector or configure it through Executor, then reconnect it.",+ },+ {+ id: "shopping-browser",+ label: "Shopping browser session",+ accessMethod: "browser" as const,+ health: "unsupported" as const,+ apiAccess: "not-applicable" as const,+ nextAction: "Use the browser session only for this task.",+ temporary: true,+ repairAction: "Add a shopping connector when Akeru supports one.",+ },+ {+ id: "booking-browser",+ label: "Booking browser session",+ accessMethod: "browser" as const,+ health: "unsupported" as const,+ apiAccess: "not-applicable" as const,+ nextAction: "Use the browser session only for this approved booking.",+ temporary: true,+ repairAction: "Add a calendar or booking connector when Akeru supports one.",+ },+ ];+}diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 853fa9f3c..2bd622275 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -68,6 +68,12 @@ import {} from "@t3tools/contracts";import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";import { SubscriptionAuthService } from "./subscription-auth/service.ts";+import {+ buildProviderAccessCapabilities,+ subscriptionDependentBots,+} from "./subscription-auth/snapshot.ts";+import { BotInboxService } from "./bot-inbox/service.ts";+import { syncConnectorIncidents } from "./bot-inbox/connectorIncidents.ts";import { HttpRouter, HttpServerRequest, HttpServerRespondable } from "effect/unstable/http";import { RpcSerialization, RpcServer } from "effect/unstable/rpc";@@ -487,6 +493,7 @@ const makeWsRpcLayer = (const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;const config = yield* ServerConfig.ServerConfig;const subscriptionAuth = SubscriptionAuthService.forSecretsDir(config.secretsDir);+ const botInbox = BotInboxService.forSecretsDir(config.secretsDir);const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;const serverSettings = yield* ServerSettings.ServerSettingsService;const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;@@ -540,6 +547,31 @@ const makeWsRpcLayer = (message: `The authenticated token is missing required scope: ${requiredScope}.`,requiredScope,});+ const getAccessHealthSnapshot = Effect.fn("getAccessHealthSnapshot")(function* () {+ subscriptionAuth.reload();+ botInbox.reload();+ const [providers, bots] = yield* Effect.all([+ providerRegistry.getProviders,+ projectionBots+ .listAll()+ .pipe(Effect.mapError((cause) => new SubscriptionAuthError({ reason: cause.message }))),+ ]);+ const dependentBots = subscriptionDependentBots(+ bots.map((bot) => ({ id: bot.botId, name: bot.name, engine: bot.engine })),+ providers,+ );+ const subscriptionStatuses = subscriptionAuth.statuses(dependentBots);++ syncConnectorIncidents(botInbox, subscriptionStatuses);++ return {+ providers: subscriptionStatuses,+ access: buildProviderAccessCapabilities(subscriptionStatuses, providers, (instanceId) =>+ subscriptionAuth.providerInstanceHealth(instanceId),+ ),+ inbox: botInbox.list(),+ };+ });const authorizeEffect = <A, E, R>(requiredScope: AuthEnvironmentScope,effect: Effect.Effect<A, E, R>,@@ -1803,11 +1835,9 @@ const makeWsRpcLayer = (},),[WS_METHODS.subscriptionAuthList]: (_input) =>- observeRpcEffect(- WS_METHODS.subscriptionAuthList,- Effect.sync(() => ({ providers: subscriptionAuth.statuses() })),- { "rpc.aggregate": "server" },- ),+ observeRpcEffect(WS_METHODS.subscriptionAuthList, getAccessHealthSnapshot(), {+ "rpc.aggregate": "server",+ }),[WS_METHODS.subscriptionAuthStart]: ({ provider }) =>observeRpcEffect(WS_METHODS.subscriptionAuthStart,@@ -1858,8 +1888,19 @@ const makeWsRpcLayer = (WS_METHODS.subscriptionAuthLogout,Effect.sync(() => {subscriptionAuth.logout(provider);- return { providers: subscriptionAuth.statuses() };- }),+ }).pipe(Effect.andThen(getAccessHealthSnapshot())),+ { "rpc.aggregate": "server" },+ ),+ [WS_METHODS.subscriptionAuthHealthTest]: ({ provider }) =>+ observeRpcEffect(+ WS_METHODS.subscriptionAuthHealthTest,+ Effect.tryPromise({+ try: () => subscriptionAuth.testHealth(provider),+ catch: (cause) =>+ new SubscriptionAuthError({+ reason: cause instanceof Error ? cause.message : String(cause),+ }),+ }).pipe(Effect.andThen(getAccessHealthSnapshot())),{ "rpc.aggregate": "server" },),[WS_METHODS.voiceCallGet]: (_input) =>diff --git a/apps/web/src/botInbox.ts b/apps/web/src/botInbox.tsnew file mode 100644index 000000000..389089484--- /dev/null+++ b/apps/web/src/botInbox.ts@@ -0,0 +1,12 @@+import type { SubscriptionAuthStatuses } from "@t3tools/contracts";++export type BotInboxItem = SubscriptionAuthStatuses["inbox"][number];++export function selectOpenBotInboxItems(+ inbox: ReadonlyArray<BotInboxItem>,+ botIds?: ReadonlySet<string>,+): ReadonlyArray<BotInboxItem> {+ return inbox+ .filter((item) => item.status === "open" && (botIds === undefined || botIds.has(item.botId)))+ .toSorted((left, right) => right.lastSeenAt.localeCompare(left.lastSeenAt));+}diff --git a/apps/web/src/components/ChatMarkdown.test.tsx b/apps/web/src/components/ChatMarkdown.test.tsxindex 92418b70d..4594444bc 100644--- a/apps/web/src/components/ChatMarkdown.test.tsx+++ b/apps/web/src/components/ChatMarkdown.test.tsx@@ -104,6 +104,18 @@ describe("ChatMarkdown file option chips", () => {});});+describe("ChatMarkdown settings chips", () => {+ it("opens the exact Settings pane without an external-browser target", () => {+ const html = renderToStaticMarkup(+ <ChatMarkdown cwd={undefined} text="[Error inbox](grokbot://app/v1/settings?id=bot-inbox)" />,+ );++ expect(html).toContain("chat-markdown-settings-link");+ expect(html).toContain("Open Settings > Errors");+ expect(html).not.toContain('target="_blank"');+ });+});+describe("shouldUseMarkdownFileBrowserPrimaryAction", () => {it("uses the browser when it is the only available primary action", () => {expect(diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex 365bf178c..dd9f3b8a9 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -57,6 +57,7 @@ import { remarkGithubAlerts } from "../markdown-github-alerts";import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";import { PierreEntryIcon } from "./chat/PierreEntryIcon";+import { SettingsLinkChip } from "./chat/SettingsLinkChip";import {revealInFileExplorerLabelForKind,revealInFileExplorerLabelForOs,@@ -131,6 +132,7 @@ import {} from "~/lib/openPullRequestLink";import { writeTextToClipboard } from "../hooks/useCopyToClipboard";import { isPreviewSupportedInRuntime } from "../previewStateStore";+import { parseSettingsDeepLink } from "../settingsDeepLink";import { resolvePathLinkTarget } from "../terminal-links";import {isBrowserPreviewFile,@@ -281,7 +283,7 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {},protocols: {...defaultSchema.protocols,- href: [...(defaultSchema.protocols?.href ?? []), "file"],+ href: [...(defaultSchema.protocols?.href ?? []), "file", "grokbot"],src: [...(defaultSchema.protocols?.src ?? []), "file"],},} satisfies Parameters<typeof rehypeSanitize>[0];@@ -1839,6 +1841,7 @@ function ChatMarkdown({return buildFileLinkParentSuffixByPath(filePaths);}, [inlineCodeFileLinkMetaByText, markdownFileLinkMetaByHref]);const markdownUrlTransform = useCallback((href: string) => {+ if (parseSettingsDeepLink(href)) return href;return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);}, []);// Re-emit highlighted content as markdown so copying out of the rendered@@ -2105,6 +2108,19 @@ function ChatMarkdown({},a({ node, href, children, title: _title, ...props }) {const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";+ const settingsDestination = parseSettingsDeepLink(normalizedHref);+ if (settingsDestination) {+ return (+ <SettingsLinkChip+ href={normalizedHref}+ destination={settingsDestination}+ environmentId={environmentId}+ {...(props.className ? { className: props.className } : {})}+ >+ {children}+ </SettingsLinkChip>+ );+ }const fileLinkMeta = normalizedHref? (markdownFileLinkMetaByHref.get(normalizedHref) ??resolveMarkdownFileLinkMeta(normalizedHref, cwd))diff --git a/apps/web/src/components/ProviderUpdatePrimaryNotification.test.tsx b/apps/web/src/components/ProviderUpdatePrimaryNotification.test.tsxnew file mode 100644index 000000000..531223f24--- /dev/null+++ b/apps/web/src/components/ProviderUpdatePrimaryNotification.test.tsx@@ -0,0 +1,171 @@+import type { ReactElement } from "react";+import {+ EnvironmentId,+ ProviderDriverKind,+ ProviderInstanceId,+ type ServerProvider,+} from "@t3tools/contracts";+import * as Cause from "effect/Cause";+import { AsyncResult } from "effect/unstable/reactivity";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";++import { reactHookHarness as hooks } from "../test/reactHookHarness";++const state = vi.hoisted(() => ({+ environmentId: "environment-a" as EnvironmentId,+ providers: [] as ServerProvider[],+ updateProvider: vi.fn(),+ openSettings: vi.fn(),+ dismissNotificationKey: vi.fn(),+ toasts: [] as Array<Record<string, unknown>>,+ closedToastIds: [] as string[],+ notificationVersion: 0,+}));++vi.mock("react", async (importOriginal) => {+ const actual = await importOriginal<typeof import("react")>();+ const { reactHookHarness } = await import("../test/reactHookHarness");+ return {+ ...actual,+ useCallback: reactHookHarness.useCallback,+ useEffect: (effect: () => void | (() => void)) => {+ effect();+ },+ useMemo: reactHookHarness.useMemo,+ useRef: reactHookHarness.useRef,+ };+});++vi.mock("react/compiler-runtime", async () => {+ const { reactHookHarness } = await import("../test/reactHookHarness");+ return { c: reactHookHarness.useMemoCache };+});++vi.mock("@effect/atom-react", () => ({+ useAtomValue: () => state.providers,+}));++vi.mock("../state/server", () => ({+ primaryServerProvidersAtom: Symbol("primaryServerProvidersAtom"),+ serverEnvironment: { updateProvider: Symbol("updateProvider") },+}));++vi.mock("../state/environments", () => ({+ usePrimaryEnvironment: () => ({ environmentId: state.environmentId }),+}));++vi.mock("../state/use-atom-command", () => ({+ useAtomCommand: () => state.updateProvider,+}));++vi.mock("../providerUpdateDismissal", () => ({+ useDismissedProviderUpdateNotificationKeys: () => ({+ dismissedNotificationKeys: new Set<string>(),+ dismissNotificationKey: state.dismissNotificationKey,+ }),+}));++vi.mock("~/settingsDialogStore", () => ({+ openSettings: state.openSettings,+}));++vi.mock("./ui/toast", () => ({+ hiddenToastActionProps: { children: null },+ stackedThreadToast: (input: Record<string, unknown>) => input,+ toastManager: {+ add: (input: Record<string, unknown>) => {+ state.toasts.push(input);+ return `toast-${state.toasts.length}`;+ },+ close: (toastId: string) => state.closedToastIds.push(toastId),+ },+}));++import { ProviderUpdatePrimaryNotification } from "./ProviderUpdatePrimaryNotification";++const providerInstanceId = ProviderInstanceId.make("codex");++function provider(updateState?: ServerProvider["updateState"]): ServerProvider {+ return {+ instanceId: providerInstanceId,+ driver: ProviderDriverKind.make("codex"),+ enabled: true,+ installed: true,+ version: "1.0.0",+ status: "ready",+ auth: { status: "authenticated" },+ checkedAt: "2026-08-30T12:00:00.000Z",+ models: [],+ slashCommands: [],+ skills: [],+ versionAdvisory: {+ status: "behind_latest",+ currentVersion: "1.0.0",+ latestVersion: `1.1.${state.notificationVersion}`,+ updateCommand: "npm install -g @openai/codex@latest",+ canUpdate: true,+ checkedAt: "2026-08-30T12:00:00.000Z",+ message: "Update available.",+ },+ ...(updateState ? { updateState } : {}),+ };+}++function renderNotification() {+ hooks.beginRender();+ return ProviderUpdatePrimaryNotification() as ReactElement | null;+}++describe("ProviderUpdatePrimaryNotification", () => {+ beforeEach(() => {+ hooks.reset();+ state.environmentId = EnvironmentId.make("environment-a");+ state.providers = [provider()];+ state.updateProvider.mockReset().mockReturnValue(new Promise(() => {}));+ state.openSettings.mockReset();+ state.dismissNotificationKey.mockReset();+ state.toasts = [];+ state.closedToastIds = [];+ state.notificationVersion += 1;+ });++ it("opens repair settings for the environment where the update started", async () => {+ let finishUpdate!: () => void;+ state.updateProvider.mockImplementation(+ () =>+ new Promise((resolve) => {+ finishUpdate = () => resolve(AsyncResult.failure(Cause.die(new Error("Update failed"))));+ }),+ );+ renderNotification();++ const prompt = state.toasts[0] as {+ actionProps?: { onClick?: () => void };+ };+ prompt.actionProps?.onClick?.();++ state.environmentId = EnvironmentId.make("environment-b");+ renderNotification();+ expect(state.toasts).toHaveLength(1);++ finishUpdate();+ await Promise.resolve();+ await Promise.resolve();++ const repairToast = state.toasts[1] as {+ actionProps?: { onClick?: () => void };+ };+ repairToast.actionProps?.onClick?.();++ expect(state.openSettings).toHaveBeenCalledWith(+ "providers",+ null,+ EnvironmentId.make("environment-a"),+ );+ expect(state.openSettings).not.toHaveBeenCalledWith(+ "providers",+ null,+ EnvironmentId.make("environment-b"),+ );+ });+});diff --git a/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx b/apps/web/src/components/ProviderUpdatePrimaryNotification.tsxindex cfa086202..8766ed8a7 100644--- a/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx+++ b/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx@@ -1,7 +1,11 @@import { useAtomValue } from "@effect/atom-react";import { DownloadIcon } from "lucide-react";import { useCallback, useEffect, useMemo, useRef } from "react";-import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts";+import {+ type EnvironmentId,+ type ProviderDriverKind,+ type ProviderInstanceId,+} from "@t3tools/contracts";import { primaryServerProvidersAtom, serverEnvironment } from "../state/server";import { usePrimaryEnvironment } from "../state/environments";@@ -27,10 +31,16 @@ const seenProviderUpdateNotificationKeys = new Set<string>();type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;type ActiveProviderUpdateToast =- | { readonly kind: "prompt"; readonly key: string; readonly toastId: ProviderUpdateToastId }+ | {+ readonly kind: "prompt";+ readonly key: string;+ readonly environmentId: EnvironmentId | null;+ readonly toastId: ProviderUpdateToastId;+ }| {readonly kind: "update";readonly key: string;+ readonly environmentId: EnvironmentId;readonly providerInstanceIds: ReadonlySet<ProviderInstanceId>;readonly providerCount: number;};@@ -134,27 +144,34 @@ export function ProviderUpdatePrimaryNotification() {[providers, updateProviders],);- const openProviderSettings = useCallback((toastId?: ProviderUpdateToastId) => {- const activeToast = activeToastRef.current;- if (toastId !== undefined) {- toastManager.close(toastId);- } else if (activeToast?.kind === "prompt") {- toastManager.close(activeToast.toastId);- }- if (- activeToast &&- (toastId === undefined || (activeToast.kind === "prompt" && activeToast.toastId === toastId))- ) {- activeToastRef.current = null;- }- openSettings("providers");- }, []);+ const openProviderSettings = useCallback(+ (toastId: ProviderUpdateToastId | undefined, environmentId: EnvironmentId | null) => {+ const activeToast = activeToastRef.current;+ if (toastId !== undefined) {+ toastManager.close(toastId);+ } else if (activeToast?.kind === "prompt") {+ toastManager.close(activeToast.toastId);+ }+ if (+ activeToast &&+ (toastId === undefined ||+ (activeToast.kind === "prompt" && activeToast.toastId === toastId))+ ) {+ activeToastRef.current = null;+ }+ openSettings("providers", null, environmentId);+ },+ [],+ );useEffect(() => {const activeToast = activeToastRef.current;if (activeToast?.kind !== "update") {return;}+ if (primaryEnvironment?.environmentId !== activeToast.environmentId) {+ return;+ }const activeProviders = providers.filter((provider) =>activeToast.providerInstanceIds.has(provider.instanceId),@@ -167,9 +184,12 @@ export function ProviderUpdatePrimaryNotification() {return;}- addProviderUpdateToast({ view, openSettings: openProviderSettings });+ addProviderUpdateToast({+ view,+ openSettings: (toastId) => openProviderSettings(toastId, activeToast.environmentId),+ });activeToastRef.current = null;- }, [providers, openProviderSettings]);+ }, [primaryEnvironment?.environmentId, providers, openProviderSettings]);useEffect(() => {const activeToast = activeToastRef.current;@@ -190,16 +210,17 @@ export function ProviderUpdatePrimaryNotification() {seenProviderUpdateNotificationKeys.add(notificationKey);const initialView = getProviderUpdateInitialToastView({ updateProviders, oneClickProviders });+ const promptEnvironmentId = primaryEnvironment?.environmentId ?? null;let toastId!: ProviderUpdateToastId;let updateStarted = false;- const openSettings = () => openProviderSettings(toastId);+ const openSettings = () => openProviderSettings(toastId, promptEnvironmentId);const dismissPrompt = () => {dismissNotificationKey(notificationKey);};const runUpdates = () => {- if (updateStarted || oneClickProviders.length === 0 || !primaryEnvironment) {+ if (updateStarted || oneClickProviders.length === 0 || promptEnvironmentId === null) {return;}updateStarted = true;@@ -209,6 +230,7 @@ export function ProviderUpdatePrimaryNotification() {const activeUpdate: ActiveProviderUpdateToast = {kind: "update",key: notificationKey,+ environmentId: promptEnvironmentId,providerInstanceIds,providerCount,};@@ -221,7 +243,7 @@ export function ProviderUpdatePrimaryNotification() {for (const provider of oneClickProviders) {results.push(await updateProvider({- environmentId: primaryEnvironment.environmentId,+ environmentId: activeUpdate.environmentId,input: {provider: provider.driver,instanceId: provider.instanceId,@@ -239,7 +261,7 @@ export function ProviderUpdatePrimaryNotification() {if (failedMessage) {addProviderUpdateToast({view: getProviderUpdateRejectedToastView(providerCount, failedMessage),- openSettings: openProviderSettings,+ openSettings: (toastId) => openProviderSettings(toastId, activeUpdate.environmentId),});activeToastRef.current = null;return;@@ -254,7 +276,10 @@ export function ProviderUpdatePrimaryNotification() {providerCount,});if (shouldShowPrimaryProviderUpdateToast(view)) {- addProviderUpdateToast({ view, openSettings: openProviderSettings });+ addProviderUpdateToast({+ view,+ openSettings: (toastId) => openProviderSettings(toastId, activeUpdate.environmentId),+ });activeToastRef.current = null;}})();@@ -296,7 +321,12 @@ export function ProviderUpdatePrimaryNotification() {},}),);- activeToastRef.current = { kind: "prompt", key: notificationKey, toastId };+ activeToastRef.current = {+ kind: "prompt",+ key: notificationKey,+ environmentId: promptEnvironmentId,+ toastId,+ };}, [updateProvider,dismissNotificationKey,diff --git a/apps/web/src/components/chat/SettingsLinkChip.tsx b/apps/web/src/components/chat/SettingsLinkChip.tsxnew file mode 100644index 000000000..1885f204a--- /dev/null+++ b/apps/web/src/components/chat/SettingsLinkChip.tsx@@ -0,0 +1,55 @@+import { Settings02Icon } from "@hugeicons/core-free-icons";+import type { EnvironmentId } from "@t3tools/contracts";+import type { MouseEvent, ReactNode } from "react";++import { openSettings } from "../../settingsDialogStore";+import type { SettingsDeepLinkDestination } from "../../settingsDeepLink";+import { cn } from "../../lib/utils";+import {+ CHAT_INLINE_CHIP_CLASS_NAME,+ CHAT_INLINE_CHIP_LABEL_CLASS_NAME,+ COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,+} from "../composerInlineChip";+import { AppIcon } from "../ui/app-icon";+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";++export function SettingsLinkChip({+ href,+ destination,+ environmentId,+ children,+ className,+}: {+ readonly href: string;+ readonly destination: SettingsDeepLinkDestination;+ readonly environmentId: EnvironmentId | null;+ readonly children: ReactNode;+ readonly className?: string;+}) {+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <a+ href={href}+ aria-label={destination.tooltip}+ className={cn(+ CHAT_INLINE_CHIP_CLASS_NAME,+ "chat-markdown-settings-link cursor-pointer",+ className,+ )}+ onClick={(event: MouseEvent<HTMLAnchorElement>) => {+ event.preventDefault();+ event.stopPropagation();+ openSettings(destination.section, destination.targetId, environmentId);+ }}+ >+ <AppIcon icon={Settings02Icon} className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME} />+ <span className={CHAT_INLINE_CHIP_LABEL_CLASS_NAME}>{children}</span>+ </a>+ }+ />+ <TooltipPopup side="top">{destination.tooltip}</TooltipPopup>+ </Tooltip>+ );+}diff --git a/apps/web/src/components/plugins/PluginsDialog.test.tsx b/apps/web/src/components/plugins/PluginsDialog.test.tsxindex 7b9cab4fc..fdbe036ac 100644--- a/apps/web/src/components/plugins/PluginsDialog.test.tsx+++ b/apps/web/src/components/plugins/PluginsDialog.test.tsx@@ -8,6 +8,7 @@ import {PLUGIN_DIALOG_CLASS_NAME,PLUGIN_DIRECTORY_HEADER_CLASS_NAME,PLUGIN_DIRECTORY_PANEL_CLASS_NAME,+ PLUGIN_DIRECTORY_SCROLL_CLASS_NAME,validateMcpServerDraft,} from "./PluginsDialog";import { CustomMcpServers, PluginsCatalog } from "./PluginsCatalog";@@ -40,6 +41,13 @@ describe("Plugins dialog content", () => {expect(PLUGIN_DIRECTORY_PANEL_CLASS_NAME).toContain("pt-5!");});+ it("keeps the complete filter row visible above the scrolling catalog", () => {+ expect(PLUGIN_DIRECTORY_HEADER_CLASS_NAME).toContain("shrink-0");+ expect(PLUGIN_DIRECTORY_SCROLL_CLASS_NAME).toContain("min-h-0");+ expect(PLUGIN_DIRECTORY_SCROLL_CLASS_NAME).toContain("flex-1");+ expect(PLUGIN_DIRECTORY_SCROLL_CLASS_NAME).toContain("overflow-hidden");+ });+it("renders a categorized directory with compact add and configure controls", () => {const markup = renderToStaticMarkup(<PluginsCatalogdiff --git a/apps/web/src/components/plugins/PluginsDialog.tsx b/apps/web/src/components/plugins/PluginsDialog.tsxindex a3990431a..c7362ee2c 100644--- a/apps/web/src/components/plugins/PluginsDialog.tsx+++ b/apps/web/src/components/plugins/PluginsDialog.tsx@@ -47,7 +47,8 @@ const CATALOG = loadCatalog();export const PLUGIN_DIALOG_CLASS_NAME = "h-[min(48rem,90dvh)] max-w-5xl flex-col overflow-hidden";export const PLUGIN_DIRECTORY_HEADER_CLASS_NAME =- "max-h-[45%] min-h-0 gap-3 overflow-y-auto overscroll-contain px-6 py-5";+ "max-h-[45%] min-h-0 shrink-0 gap-3 overflow-y-auto overscroll-contain px-6 py-5";+export const PLUGIN_DIRECTORY_SCROLL_CLASS_NAME = "min-h-0 flex-1 overflow-hidden";export const PLUGIN_DIRECTORY_PANEL_CLASS_NAME = "space-y-8 px-5 pt-5! pb-5 sm:px-6";export interface McpServerDraft {@@ -365,25 +366,27 @@ function PluginsDialogForEnvironment({ environmentId }: { readonly environmentId</div>) : null}</DialogHeader>- <DialogPanel className={PLUGIN_DIRECTORY_PANEL_CLASS_NAME}>- <PluginsCatalog- sections={view.kind === "installed" ? installedSections : sections}- servers={servers}- pendingServerId={pendingServerId}- onToggle={(plugin, enabled) => void togglePlugin(plugin, enabled)}- onOpen={openPlugin}- onViewAll={setFilter}- />- {view.kind === "installed" ? (- <CustomMcpServers- servers={customServers}+ <div className={PLUGIN_DIRECTORY_SCROLL_CLASS_NAME}>+ <DialogPanel className={PLUGIN_DIRECTORY_PANEL_CLASS_NAME}>+ <PluginsCatalog+ sections={view.kind === "installed" ? installedSections : sections}+ servers={servers}pendingServerId={pendingServerId}- onToggle={(server, enabled) => void toggleCustom(server, enabled)}- onEdit={openCustomEditor}- onDelete={(server) => void removeCustom(server)}+ onToggle={(plugin, enabled) => void togglePlugin(plugin, enabled)}+ onOpen={openPlugin}+ onViewAll={setFilter}/>- ) : null}- </DialogPanel>+ {view.kind === "installed" ? (+ <CustomMcpServers+ servers={customServers}+ pendingServerId={pendingServerId}+ onToggle={(server, enabled) => void toggleCustom(server, enabled)}+ onEdit={openCustomEditor}+ onDelete={(server) => void removeCustom(server)}+ />+ ) : null}+ </DialogPanel>+ </div></>)}<Dialog open={editorTarget !== null} onOpenChange={(open) => !open && closeEditor()}>diff --git a/apps/web/src/components/roster/BotInboxAlertStack.test.tsx b/apps/web/src/components/roster/BotInboxAlertStack.test.tsxnew file mode 100644index 000000000..3b145adfe--- /dev/null+++ b/apps/web/src/components/roster/BotInboxAlertStack.test.tsx@@ -0,0 +1,55 @@+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vite-plus/test";+import { BotId, type SubscriptionAuthStatuses } from "@t3tools/contracts";++import { selectOpenBotInboxItems } from "../../botInbox";+import { BotInboxAlertStack } from "./BotInboxAlertStack";++type BotInboxItem = SubscriptionAuthStatuses["inbox"][number];++function incident(overrides: Partial<BotInboxItem> = {}): BotInboxItem {+ return {+ id: "incident-1",+ incidentKey: "connector:claude:bot-1",+ kind: "connector-failure",+ status: "open",+ botId: BotId.make("bot-1"),+ botName: "Akeru",+ taskOrRoutine: "Research brief",+ lastFailure: "Claude rejected the request.",+ nextAction: "Reconnect Claude in Settings.",+ firstSeenAt: "2026-08-30T10:00:00.000Z",+ lastSeenAt: "2026-08-30T10:00:00.000Z",+ occurrenceCount: 1,+ ...overrides,+ };+}++describe("bot inbox alerts", () => {+ it("shows only open incidents for the visible bots, newest first", () => {+ const selected = selectOpenBotInboxItems(+ [+ incident({ id: "older" }),+ incident({ id: "resolved", status: "resolved" }),+ incident({ id: "other", botId: BotId.make("bot-2") }),+ incident({ id: "newer", lastSeenAt: "2026-08-30T11:00:00.000Z" }),+ ],+ new Set(["bot-1"]),+ );++ expect(selected.map((item) => item.id)).toEqual(["newer", "older"]);+ });++ it("renders the incident through the existing composer alert", () => {+ const markup = renderToStaticMarkup(+ <BotInboxAlertStack items={[incident()]} onOpenDetails={() => {}} />,+ );++ expect(markup).toContain('role="alert"');+ expect(markup).toContain('data-variant="error"');+ expect(markup).toContain("Akeru · Research brief");+ expect(markup).toContain("Claude rejected the request.");+ expect(markup).toContain("Next: Reconnect Claude in Settings.");+ expect(markup).toContain("View details");+ });+});diff --git a/apps/web/src/components/roster/BotInboxAlertStack.tsx b/apps/web/src/components/roster/BotInboxAlertStack.tsxnew file mode 100644index 000000000..50daba0f1--- /dev/null+++ b/apps/web/src/components/roster/BotInboxAlertStack.tsx@@ -0,0 +1,38 @@+import { CircleAlertIcon } from "lucide-react";++import type { BotInboxItem } from "../../botInbox";+import { Button } from "../ui/button";+import { ComposerBannerStack } from "../chat/ComposerBannerStack";++export function BotInboxAlertStack({+ items,+ onOpenDetails,+}: {+ readonly items: ReadonlyArray<BotInboxItem>;+ readonly onOpenDetails: () => void;+}) {+ if (items.length === 0) return null;++ return (+ <ComposerBannerStack+ className="relative z-0 mx-4 sm:mx-6"+ items={items.map((item) => ({+ id: item.id,+ variant: "error",+ icon: <CircleAlertIcon />,+ title: `${item.botName} · ${item.taskOrRoutine}`,+ description: (+ <>+ <span>{item.lastFailure}</span>+ <span>Next: {item.nextAction}</span>+ </>+ ),+ actions: (+ <Button size="xs" variant="ghost" onClick={onOpenDetails}>+ View details+ </Button>+ ),+ }))}+ />+ );+}diff --git a/apps/web/src/components/roster/BotThreadLanding.tsx b/apps/web/src/components/roster/BotThreadLanding.tsxindex 236c6aed0..d42d8b374 100644--- a/apps/web/src/components/roster/BotThreadLanding.tsx+++ b/apps/web/src/components/roster/BotThreadLanding.tsx@@ -4,6 +4,7 @@ import { useNavigate } from "@tanstack/react-router";import { useEffect, useMemo, useState } from "react";import { usePrimarySettings } from "../../hooks/useSettings";+import { selectOpenBotInboxItems } from "../../botInbox";import {getCustomModelOptionsByInstance,resolveAppModelSelectionState,@@ -15,18 +16,22 @@ import {} from "../../providerInstances";import { botEnvironment } from "../../state/bots";import { usePrimaryEnvironmentId } from "../../state/environments";-import { primaryServerProvidersAtom } from "../../state/server";+import { primaryServerProvidersAtom, serverEnvironment } from "../../state/server";+import { useEnvironmentQuery } from "../../state/query";import { useAtomCommand } from "../../state/use-atom-command";+import { openSettings } from "../../settingsDialogStore";import { SidebarInset } from "../ui/sidebar";import { toastManager } from "../ui/toast";import ChatMarkdown from "../ChatMarkdown";import { WorkspacePageHeader } from "../WorkspacePageHeader";import { BotActivityStatus } from "./BotActivityStatus";+import { BotInboxAlertStack } from "./BotInboxAlertStack";import { BotAvatarView } from "./BotAvatarView";import { BotConversationScrollArea } from "./BotConversationScrollArea";import { visibleBotChatMessages } from "./botConversationPresentation";import { resolveStickyBotEngine } from "./botEngineSelection";import { BotPromptComposer } from "./BotPromptComposer";+import { ThreadErrorBanner } from "../chat/ThreadErrorBanner";import { BotVoiceCallButton, useVoiceCall } from "../voice/VoiceCall";import { useBotPresence } from "./botPresence";import { useRosterStore } from "./rosterStore";@@ -77,6 +82,11 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {const runtime = useBotThreadRuntime(botId, effectiveModelSelection);const voiceCall = useVoiceCall();const presence = useBotPresence(botId);+ const inboxQuery = useEnvironmentQuery(+ environmentId === null+ ? null+ : serverEnvironment.subscriptionAuth({ environmentId, input: {} }),+ );useEffect(() => {if (@@ -99,6 +109,7 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {if (!bot || bot.archivedAt !== null) return null;const working = runtime.sending || presence === "working";const messages = visibleBotChatMessages(runtime.messages, working);+ const inboxItems = selectOpenBotInboxItems(inboxQuery.data?.inbox ?? [], new Set([bot.id]));return (<SidebarInset@@ -171,16 +182,16 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {))}{working ? <BotActivityStatus avatar={bot.avatar} name={bot.name} /> : null}- {runtime.error ? (- <div- role="alert"- data-testid="bot-chat-error"- className="rounded-lg border border-destructive/30 bg-destructive/8 px-3 py-2 text-sm text-destructive"- >- {runtime.error}- </div>- ) : null}</BotConversationScrollArea>+ <BotInboxAlertStack+ items={inboxItems}+ onOpenDetails={() => openSettings("inbox", null, environmentId)}+ />+ <ThreadErrorBanner+ error={+ inboxItems.some((item) => item.lastFailure === runtime.error) ? null : runtime.error+ }+ /><BotPromptComposerbotName={bot.name}draftKey={bot.id}diff --git a/apps/web/src/components/roster/GroupThreadLanding.tsx b/apps/web/src/components/roster/GroupThreadLanding.tsxindex 022530087..3f521f316 100644--- a/apps/web/src/components/roster/GroupThreadLanding.tsx+++ b/apps/web/src/components/roster/GroupThreadLanding.tsx@@ -1,9 +1,16 @@import { useNavigate } from "@tanstack/react-router";import { useEffect } from "react";+import { selectOpenBotInboxItems } from "../../botInbox";+import { openSettings } from "../../settingsDialogStore";+import { usePrimaryEnvironmentId } from "../../state/environments";+import { useEnvironmentQuery } from "../../state/query";+import { serverEnvironment } from "../../state/server";import { SidebarInset } from "../ui/sidebar";import { WorkspacePageHeader } from "../WorkspacePageHeader";+import { ThreadErrorBanner } from "../chat/ThreadErrorBanner";import { BotActivityStatus } from "./BotActivityStatus";+import { BotInboxAlertStack } from "./BotInboxAlertStack";import { BotAvatarView } from "./BotAvatarView";import { BotConversationScrollArea } from "./BotConversationScrollArea";import { visibleBotChatMessages } from "./botConversationPresentation";@@ -14,12 +21,18 @@ import { useGroupThreadRuntime } from "./useGroupThreadRuntime";export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {const navigate = useNavigate();+ const environmentId = usePrimaryEnvironmentId();const group = useRosterStore((state) =>state.groups.find((candidate) => candidate.id === groupId),);const bots = useRosterStore((state) => state.bots);const runtime = useGroupThreadRuntime(groupId);const presence = useGroupPresence(groupId);+ const inboxQuery = useEnvironmentQuery(+ environmentId === null+ ? null+ : serverEnvironment.subscriptionAuth({ environmentId, input: {} }),+ );useEffect(() => {if (!group) void navigate({ to: "/", replace: true });@@ -32,6 +45,10 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {const working = runtime.sending || presence === "working";const messages = visibleBotChatMessages(runtime.messages, working);const activeBot = members.find((bot) => bot.id === runtime.respondingBotId) ?? boss;+ const inboxItems = selectOpenBotInboxItems(+ inboxQuery.data?.inbox ?? [],+ new Set(members.map((bot) => bot.id)),+ );return (<SidebarInset@@ -105,15 +122,16 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {}))}{working ? <BotActivityStatus avatar={activeBot.avatar} name={activeBot.name} /> : null}- {runtime.error ? (- <div- role="alert"- className="rounded-lg border border-destructive/30 bg-destructive/8 px-3 py-2 text-sm text-destructive"- >- {runtime.error}- </div>- ) : null}</BotConversationScrollArea>+ <BotInboxAlertStack+ items={inboxItems}+ onOpenDetails={() => openSettings("inbox", null, environmentId)}+ />+ <ThreadErrorBanner+ error={+ inboxItems.some((item) => item.lastFailure === runtime.error) ? null : runtime.error+ }+ /><BotPromptComposerbotName={group.name}draftKey={`group:${group.id}`}diff --git a/apps/web/src/components/settings/InboxPanel.tsx b/apps/web/src/components/settings/InboxPanel.tsxnew file mode 100644index 000000000..4d553bb84--- /dev/null+++ b/apps/web/src/components/settings/InboxPanel.tsx@@ -0,0 +1,59 @@+import { CircleAlertIcon } from "lucide-react";++import { selectOpenBotInboxItems } from "../../botInbox";+import { useSettingsEnvironmentId } from "../../settingsDialogStore";+import { useEnvironmentQuery } from "../../state/query";+import { serverEnvironment } from "../../state/server";+import { Badge } from "../ui/badge";+import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";++export function InboxPanel() {+ const environmentId = useSettingsEnvironmentId();+ const inboxQuery = useEnvironmentQuery(+ environmentId === null+ ? null+ : serverEnvironment.subscriptionAuth({ environmentId, input: {} }),+ );+ const openItems = selectOpenBotInboxItems(inboxQuery.data?.inbox ?? []);++ return (+ <SettingsPageContainer>+ <SettingsSection+ title="Error inbox"+ headerAction={+ openItems.length > 0 ? <Badge variant="error">{openItems.length} open</Badge> : null+ }+ >+ {inboxQuery.isPending ? (+ <SettingsRow title="Loading errors" />+ ) : inboxQuery.error ? (+ <SettingsRow title="Could not load errors" description={inboxQuery.error} />+ ) : openItems.length === 0 ? (+ <SettingsRow+ title="No errors"+ description="Bot failures and approval requests appear here."+ />+ ) : (+ openItems.map((item) => (+ <SettingsRow+ key={item.id}+ title={+ <span className="flex items-center gap-2">+ <CircleAlertIcon className="size-4 text-destructive" />+ {item.botName} · {item.taskOrRoutine}+ </span>+ }+ description={item.lastFailure}+ status={`Next: ${item.nextAction}`}+ control={+ <Badge variant="error">+ {item.occurrenceCount > 1 ? `${item.occurrenceCount} events` : "Action needed"}+ </Badge>+ }+ />+ ))+ )}+ </SettingsSection>+ </SettingsPageContainer>+ );+}diff --git a/apps/web/src/components/settings/ProvidersPanel.tsx b/apps/web/src/components/settings/ProvidersPanel.tsxindex 5bf761824..e5322c520 100644--- a/apps/web/src/components/settings/ProvidersPanel.tsx+++ b/apps/web/src/components/settings/ProvidersPanel.tsx@@ -1,4 +1,11 @@-import { CheckIcon, CopyIcon, ExternalLinkIcon, LoaderIcon, LogOutIcon } from "lucide-react";+import {+ CheckIcon,+ CopyIcon,+ ExternalLinkIcon,+ LoaderIcon,+ LogOutIcon,+ RefreshCwIcon,+} from "lucide-react";import { useCallback, useEffect, useMemo, useState } from "react";import type {SubscriptionAuthLoginProgress,@@ -12,7 +19,7 @@ import {type AtomCommandResult,} from "@t3tools/client-runtime/state/runtime";-import { usePrimaryEnvironmentId } from "../../state/environments";+import { useSettingsEnvironmentId } from "../../settingsDialogStore";import { serverEnvironment } from "../../state/server";import { useEnvironmentQuery } from "../../state/query";import { useAtomCommand } from "../../state/use-atom-command";@@ -74,6 +81,38 @@ interface ActiveLogin {readonly error: string | null;}+const healthLabels: Readonly<Record<NonNullable<SubscriptionProviderStatus["health"]>, string>> = {+ missing: "Missing",+ detected: "Detected",+ healthy: "Healthy",+ expired: "Expired",+ revoked: "Revoked",+ failed: "Failed",+ unsupported: "Unsupported",+ "failed-first-request": "First request failed",+ recovered: "Recovered",+};++function healthBadgeVariant(health: SubscriptionProviderStatus["health"] | undefined) {+ if (health === "healthy" || health === "recovered") return "success" as const;+ if (+ health === "expired" ||+ health === "revoked" ||+ health === "failed" ||+ health === "failed-first-request"+ ) {+ return "error" as const;+ }+ if (health === "detected") return "warning" as const;+ return "secondary" as const;+}++function formatTimestamp(value: string | number | undefined): string {+ if (value === undefined) return "Never";+ const date = new Date(value);+ return Number.isNaN(date.getTime()) ? "Never" : date.toLocaleString();+}+function commandError(result: AtomCommandResult<unknown, unknown>): string {if (result._tag !== "Failure") return "The request failed.";const error = squashAtomCommandFailure(result);@@ -86,12 +125,14 @@ function ProviderLoginCard({busy,onConnect,onDisconnect,+ onTest,}: {readonly definition: SubscriptionProviderDefinition;readonly status: SubscriptionProviderStatus | undefined;readonly busy: boolean;readonly onConnect: () => void;readonly onDisconnect: () => void;+ readonly onTest: () => void;}) {const connected = status?.connected === true;const ProviderIcon = typeof definition.icon === "string" ? null : definition.icon;@@ -110,25 +151,37 @@ function ProviderLoginCard({/>)}{definition.label}- {connected ? (- <Badge variant="success" className="h-4 px-1.5 text-[10px]">- Connected- </Badge>- ) : null}+ <Badge variant={healthBadgeVariant(status?.health)} className="h-4 px-1.5 text-[10px]">+ {status?.health ? healthLabels[status.health] : connected ? "Detected" : "Missing"}+ </Badge></span>}description={definition.description}status={definition.subscription}control={connected ? (- <Button size="xs" variant="ghost-muted" disabled={busy} onClick={onDisconnect}>- {busy ? (- <LoaderIcon className="size-3.5 animate-spin" />- ) : (+ <div className="flex items-center gap-1.5">+ <Button size="xs" variant="outline" disabled={busy} onClick={onTest}>+ {busy ? (+ <LoaderIcon className="size-3.5 animate-spin" />+ ) : (+ <RefreshCwIcon className="size-3.5" />+ )}+ Check OAuth+ </Button>+ <Button size="xs" variant="ghost-muted" disabled={busy} onClick={onConnect}>+ Reconnect+ </Button>+ <Button+ size="icon-xs"+ variant="ghost-muted"+ aria-label={`Disconnect ${definition.label}`}+ disabled={busy}+ onClick={onDisconnect}+ ><LogOutIcon className="size-3.5" />- )}- Disconnect- </Button>+ </Button>+ </div>) : (<Button size="xs" variant="outline" disabled={busy} onClick={onConnect}>{busy ? <LoaderIcon className="size-3.5 animate-spin" /> : null}@@ -136,7 +189,50 @@ function ProviderLoginCard({</Button>)}- />+ >+ {connected ? (+ <dl className="grid gap-x-6 gap-y-2 border-t border-border/50 py-3 text-xs sm:grid-cols-2">+ <div>+ <dt className="text-muted-foreground">Last successful request</dt>+ <dd>{formatTimestamp(status?.lastSuccessfulRequestAt)}</dd>+ </div>+ <div>+ <dt className="text-muted-foreground">Last failed request</dt>+ <dd>+ {status?.lastFailedRequest+ ? `${formatTimestamp(status.lastFailedRequest.at)} · ${status.lastFailedRequest.message}`+ : "Never"}+ </dd>+ </div>+ <div>+ <dt className="text-muted-foreground">OAuth expiry</dt>+ <dd>{formatTimestamp(status?.expiresAt)}</dd>+ </div>+ <div>+ <dt className="text-muted-foreground">Next retry</dt>+ <dd>+ {status?.nextRetryAt ? formatTimestamp(status.nextRetryAt) : "No automatic retry"}+ </dd>+ </div>+ <div>+ <dt className="text-muted-foreground">OAuth check</dt>+ <dd>+ {!status?.oauthCheck+ ? "Not run"+ : `${status.oauthCheck.status === "passed" ? "Passed" : "Failed"} · ${formatTimestamp(status.oauthCheck.checkedAt)}`}+ </dd>+ </div>+ <div>+ <dt className="text-muted-foreground">Dependent bots</dt>+ <dd>{status?.dependentBots.map((bot) => bot.name).join(", ") || "None"}</dd>+ </div>+ <div>+ <dt className="text-muted-foreground">Dependent routines</dt>+ <dd>{status?.dependentRoutines.join(", ") || "Unavailable until routines ship"}</dd>+ </div>+ </dl>+ ) : null}+ </SettingsRow>);}@@ -221,7 +317,7 @@ function ActiveLoginPanel({}export function ProvidersPanel() {- const environmentId = usePrimaryEnvironmentId();+ const environmentId = useSettingsEnvironmentId();const statusQuery = useEnvironmentQuery(environmentId === null? null@@ -242,6 +338,9 @@ export function ProvidersPanel() {const logoutAuth = useAtomCommand(serverEnvironment.logoutSubscriptionAuth, {reportFailure: false,});+ const testAuth = useAtomCommand(serverEnvironment.testSubscriptionAuth, {+ reportFailure: false,+ });const [activeLogin, setActiveLogin] = useState<ActiveLogin | null>(null);const [busyProvider, setBusyProvider] = useState<SubscriptionProviderId | null>(null);@@ -353,9 +452,17 @@ export function ProvidersPanel() {if (result._tag === "Success") statusQuery.refresh();};- if (activeLogin) {- return (- <SettingsPageContainer>+ const testHealth = async (provider: SubscriptionProviderId) => {+ if (environmentId === null) return;+ setBusyProvider(provider);+ const result = await testAuth({ environmentId, input: { provider } });+ setBusyProvider(null);+ if (result._tag === "Success") statusQuery.refresh();+ };++ return (+ <SettingsPageContainer>+ {activeLogin ? (<SettingsSection title={`Connect ${activeLogin.providerLabel}`}><ActiveLoginPanellogin={activeLogin}@@ -366,12 +473,7 @@ export function ProvidersPanel() {completing={completing}/></SettingsSection>- </SettingsPageContainer>- );- }-- return (- <SettingsPageContainer>+ ) : null}<SettingsSection title="Subscriptions"><div className="px-3 pb-2 text-[13px] leading-[1.45] text-muted-foreground sm:px-4">Connect accounts you already pay for. Akeru uses the coding access included with each@@ -392,6 +494,7 @@ export function ProvidersPanel() {busy={busyProvider === definition.id || statusQuery.isPending}onConnect={() => void connect(definition)}onDisconnect={() => void disconnect(definition.id)}+ onTest={() => void testHealth(definition.id)}/>))}</SettingsSection>diff --git a/apps/web/src/components/settings/SettingsDialog.tsx b/apps/web/src/components/settings/SettingsDialog.tsxindex 56d50a93a..81c8c20ad 100644--- a/apps/web/src/components/settings/SettingsDialog.tsx+++ b/apps/web/src/components/settings/SettingsDialog.tsx@@ -1,4 +1,5 @@import {+ AlertCircleIcon,BotIcon,CallIcon,KeyboardIcon,@@ -21,6 +22,9 @@ const GeneralSettingsPanel = lazy(async () => ({const AppearanceSettingsPanel = lazy(async () => ({default: (await import("./SettingsPanels")).AppearanceSettingsPanel,}));+const InboxPanel = lazy(async () => ({+ default: (await import("./InboxPanel")).InboxPanel,+}));const ProvidersPanel = lazy(async () => ({default: (await import("./ProvidersPanel")).ProvidersPanel,}));@@ -42,6 +46,7 @@ const DiagnosticsSettingsPanel = lazy(async () => ({const SECTION_PANELS: Readonly<Record<SettingsSection, ComponentType>> = {general: GeneralSettingsPanel,+ inbox: InboxPanel,appearance: AppearanceSettingsPanel,providers: ProvidersPanel,voice: VoiceSettingsPanel,@@ -61,6 +66,7 @@ const NAV_ITEMS: ReadonlyArray<{{ section: "appearance", label: "Appearance", icon: PaintBrush01Icon },{ section: "providers", label: "Providers", icon: BotIcon },{ section: "voice", label: "Voice", icon: CallIcon },+ { section: "inbox", label: "Errors", icon: AlertCircleIcon },{ section: "connections", label: "Connections", icon: Link02Icon },{ section: "keybindings", label: "Keybindings", icon: KeyboardIcon },];diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex 33e83060f..753363708 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -2262,6 +2262,7 @@ export function GeneralSettingsPanel() {<SettingsRow{...searchableSetting("new-threads")}+ id="local-execution"description="Pick the default workspace mode for newly created draft threads."resetAction={settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ||diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsxindex 15540ff59..c1cbc3c30 100644--- a/apps/web/src/components/settings/settingsLayout.tsx+++ b/apps/web/src/components/settings/settingsLayout.tsx@@ -12,6 +12,7 @@ import {} from "react";import { cn } from "../../lib/utils";+import { clearSettingsTarget, useSettingsDialogStore } from "../../settingsDialogStore";import { WorkspacePageContainer, type WorkspacePageWidth } from "../WorkspacePageContainer";import { Button } from "../ui/button";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";@@ -242,10 +243,14 @@ export function SettingsPageContainer({}) {const navigate = useNavigate();const hash = useLocation({ select: (location) => location.hash });- const targetId = hash.replace(/^#/, "") || null;+ const dialogTargetId = useSettingsDialogStore((state) => state.targetId);+ const hashTargetId = hash.replace(/^#/, "") || null;+ const targetId = dialogTargetId ?? hashTargetId;const clearTargetHash = useCallback(() => {- void navigate({ hash: "", replace: true, resetScroll: false, hashScrollIntoView: false });- }, [navigate]);+ clearSettingsTarget();+ if (hashTargetId)+ void navigate({ hash: "", replace: true, resetScroll: false, hashScrollIntoView: false });+ }, [hashTargetId, navigate]);return (<SettingsSearchTargetProvider targetId={targetId} onTargetHandled={clearTargetHash}>diff --git a/apps/web/src/components/sidebar/SidebarChrome.test.ts b/apps/web/src/components/sidebar/SidebarChrome.test.tsindex 6d6720b86..143afa341 100644--- a/apps/web/src/components/sidebar/SidebarChrome.test.ts+++ b/apps/web/src/components/sidebar/SidebarChrome.test.ts@@ -12,6 +12,13 @@ describe("sidebar footer", () => {expect(formatEnabledPluginStatus(3)).toBe("3 plugins enabled");});+ it("keeps the error inbox in Settings instead of the sidebar", () => {+ const source = NodeFS.readFileSync(new URL("./SidebarChrome.tsx", import.meta.url), "utf8");++ expect(source).not.toContain("SidebarInboxSummary");+ expect(source).not.toContain('openSettings("inbox")');+ });+it("shows the verified remote-access account identity when Clerk is configured", () => {const source = NodeFS.readFileSync(new URL("../clerk/T3ConnectSidebarSignIn.tsx", import.meta.url),diff --git a/apps/web/src/settingsDeepLink.test.ts b/apps/web/src/settingsDeepLink.test.tsnew file mode 100644index 000000000..ab1b6ea9a--- /dev/null+++ b/apps/web/src/settingsDeepLink.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from "vite-plus/test";++import { parseSettingsDeepLink } from "./settingsDeepLink";++describe("settings deep links", () => {+ it.each([+ ["general", "general", null],+ ["local-execution", "general", "local-execution"],+ ["bot-inbox", "inbox", null],+ ["appearance", "appearance", null],+ ["providers", "providers", null],+ ["voice", "voice", null],+ ["connections", "connections", null],+ ["keybindings", "keybindings", null],+ ["source-control", "source-control", null],+ ["diagnostics", "diagnostics", null],+ ] as const)("maps %s to %s and target %s", (id, section, targetId) => {+ expect(parseSettingsDeepLink(`grokbot://app/v1/settings?id=${id}`)).toMatchObject({+ section,+ targetId,+ });+ });++ it("uses General for a bare Settings link", () => {+ expect(parseSettingsDeepLink("grokbot://app/v1/settings")).toMatchObject({+ section: "general",+ targetId: null,+ });+ });++ it("opens the error inbox and rejects the removed access matrix", () => {+ expect(parseSettingsDeepLink("grokbot://app/v1/settings?id=provider-access")).toBeNull();+ expect(parseSettingsDeepLink("grokbot://app/v1/settings?id=bot-inbox")).toMatchObject({+ section: "inbox",+ targetId: null,+ tooltip: "Open Settings > Errors",+ });+ });++ it("maps local execution and rejects external lookalikes", () => {+ expect(parseSettingsDeepLink("grokbot://app/v1/settings?id=local-execution")).toMatchObject({+ section: "general",+ targetId: "local-execution",+ tooltip: "Open Settings > General > Local execution",+ });+ expect(parseSettingsDeepLink("https://app/v1/settings?id=providers")).toBeNull();+ expect(parseSettingsDeepLink("grokbot://app/v1/not-settings?id=providers")).toBeNull();+ expect(parseSettingsDeepLink("grokbot://app/v1/settings?id=unknown")).toBeNull();+ expect(parseSettingsDeepLink("grokbot://app/v1/settings?id=providers&from=chat")).toBeNull();+ expect(parseSettingsDeepLink("grokbot://app/v1/settings?id=providers&id=general")).toBeNull();+ expect(parseSettingsDeepLink("grokbot://app/v1/settings?id=providers#access")).toBeNull();+ });+});diff --git a/apps/web/src/settingsDeepLink.ts b/apps/web/src/settingsDeepLink.tsnew file mode 100644index 000000000..f2c214605--- /dev/null+++ b/apps/web/src/settingsDeepLink.ts@@ -0,0 +1,44 @@+import type { SettingsSection } from "./settingsDialogStore";+import { parseSettingsDeepLinkId } from "@t3tools/client-runtime/settings-deep-link";++const destinations: Readonly<+ Record<+ string,+ { readonly section: SettingsSection; readonly label: string; readonly targetId?: string }+ >+> = {+ general: { section: "general", label: "General" },+ "local-execution": {+ section: "general",+ label: "General > Local execution",+ targetId: "local-execution",+ },+ appearance: { section: "appearance", label: "Appearance" },+ providers: { section: "providers", label: "Providers" },+ "bot-inbox": { section: "inbox", label: "Errors" },+ voice: { section: "voice", label: "Voice" },+ connections: { section: "connections", label: "Connections" },+ keybindings: { section: "keybindings", label: "Keybindings" },+ "source-control": { section: "source-control", label: "Source control" },+ diagnostics: { section: "diagnostics", label: "Diagnostics" },+};++export interface SettingsDeepLinkDestination {+ readonly section: SettingsSection;+ readonly targetId: string | null;+ readonly tooltip: string;+}++export function parseSettingsDeepLink(+ href: string | undefined,+): SettingsDeepLinkDestination | null {+ const id = parseSettingsDeepLinkId(href);+ if (id === null) return null;+ const destination = destinations[id];+ if (!destination) return null;+ return {+ section: destination.section,+ targetId: destination.targetId ?? null,+ tooltip: `Open Settings > ${destination.label}`,+ };+}diff --git a/apps/web/src/settingsDialogStore.test.ts b/apps/web/src/settingsDialogStore.test.tsindex d74d58069..60848e980 100644--- a/apps/web/src/settingsDialogStore.test.ts+++ b/apps/web/src/settingsDialogStore.test.ts@@ -1,6 +1,8 @@import { beforeEach, describe, expect, it } from "vite-plus/test";+import { EnvironmentId } from "@t3tools/contracts";import {+ clearSettingsTarget,closeSettings,openSettings,settingsSectionFromPathname,@@ -18,16 +20,56 @@ describe("settings dialog store", () => {});it("closes back to no section", () => {- openSettings("providers");- expect(useSettingsDialogStore.getState().section).toBe("providers");+ openSettings("inbox");+ expect(useSettingsDialogStore.getState().section).toBe("inbox");+ expect(useSettingsDialogStore.getState().targetId).toBeNull();closeSettings();expect(useSettingsDialogStore.getState().section).toBeNull();+ expect(useSettingsDialogStore.getState().targetId).toBeNull();+ });++ it("clears a handled target without closing its Settings section", () => {+ openSettings("general", "local-execution");+ clearSettingsTarget();++ expect(useSettingsDialogStore.getState()).toMatchObject({+ section: "general",+ targetId: null,+ });+ });++ it("keeps the originating environment while navigating Settings", () => {+ const environmentId = EnvironmentId.make("env-secondary");+ openSettings("inbox", null, environmentId);+ useSettingsDialogStore.getState().openSettings("voice");++ expect(useSettingsDialogStore.getState()).toMatchObject({+ section: "voice",+ environmentId,+ });++ closeSettings();+ expect(useSettingsDialogStore.getState().environmentId).toBeNull();+ });++ it("replaces a stale environment when an entry point names its environment", () => {+ const secondaryEnvironmentId = EnvironmentId.make("env-secondary");+ const primaryEnvironmentId = EnvironmentId.make("env-primary");+ openSettings("inbox", null, secondaryEnvironmentId);++ openSettings("providers", null, primaryEnvironmentId);++ expect(useSettingsDialogStore.getState()).toMatchObject({+ section: "providers",+ environmentId: primaryEnvironmentId,+ });});});describe("legacy settings deep links", () => {it("maps a known settings path onto its section", () => {expect(settingsSectionFromPathname("/settings/connections")).toBe("connections");+ expect(settingsSectionFromPathname("/settings/inbox")).toBe("inbox");expect(settingsSectionFromPathname("/settings/voice")).toBe("voice");expect(settingsSectionFromPathname("/settings/source-control")).toBe("source-control");});diff --git a/apps/web/src/settingsDialogStore.ts b/apps/web/src/settingsDialogStore.tsindex 59b2cfb76..3efa8cdef 100644--- a/apps/web/src/settingsDialogStore.ts+++ b/apps/web/src/settingsDialogStore.ts@@ -4,6 +4,9 @@* `/settings` deep links) lands on the same surface.*/import { create } from "zustand";+import type { EnvironmentId } from "@t3tools/contracts";++import { usePrimaryEnvironmentId } from "./state/environments";/*** Every panel the dialog can render. Some sections are reachable only from a@@ -11,6 +14,7 @@ import { create } from "zustand";*/export const SETTINGS_SECTIONS = ["general",+ "inbox","appearance","providers","voice",@@ -25,19 +29,48 @@ export type SettingsSection = (typeof SETTINGS_SECTIONS)[number];interface SettingsDialogState {/** The open section, or null while the dialog is closed. */readonly section: SettingsSection | null;- readonly openSettings: (section?: SettingsSection) => void;+ readonly targetId: string | null;+ readonly environmentId: EnvironmentId | null;+ readonly openSettings: (+ section?: SettingsSection,+ targetId?: string | null,+ environmentId?: EnvironmentId | null,+ ) => void;+ readonly clearTarget: () => void;readonly closeSettings: () => void;}export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({section: null,- openSettings: (section = "general") => set({ section }),- closeSettings: () => set({ section: null }),+ targetId: null,+ environmentId: null,+ openSettings: (section = "general", targetId = null, environmentId) =>+ set((state) => ({+ section,+ targetId,+ environmentId: environmentId === undefined ? state.environmentId : environmentId,+ })),+ clearTarget: () => set({ targetId: null }),+ closeSettings: () => set({ section: null, targetId: null, environmentId: null }),}));/** Open the settings modal from outside React. */-export function openSettings(section?: SettingsSection): void {- useSettingsDialogStore.getState().openSettings(section);+export function openSettings(+ section?: SettingsSection,+ targetId?: string | null,+ environmentId?: EnvironmentId | null,+): void {+ useSettingsDialogStore.getState().openSettings(section, targetId, environmentId);+}++export function useSettingsEnvironmentId(): EnvironmentId | null {+ const primaryEnvironmentId = usePrimaryEnvironmentId();+ const environmentId = useSettingsDialogStore((state) => state.environmentId);+ return environmentId ?? primaryEnvironmentId;+}++export function clearSettingsTarget(): void {+ useSettingsDialogStore.getState().clearTarget();}export function closeSettings(): void {diff --git a/docs/internals/connector-gap-matrix.md b/docs/internals/connector-gap-matrix.mdnew file mode 100644index 000000000..6144e030e--- /dev/null+++ b/docs/internals/connector-gap-matrix.md@@ -0,0 +1,14 @@+# Connector gap matrix++Akeru Bot prefers a supported connector over a browser login. A browser session is temporary when no connector exists. Settings must show the repair action for each temporary session.++| Launch example | Preferred access | Current support | Browser fallback | Repair action |+| --------------------------- | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |+| Inbox triage | Authenticated email connector | No first-party email connector. Executor can expose an email integration only after the user configures it. | Temporary email browser session | Add an email connector or configure it through Executor, then reconnect it. |+| Sourced research brief | Exa, Context, Firecrawl, or Parallel Search | Supported built-in connectors | Use a browser only when the source cannot be reached through a connector. | Reconnect the failed research connector in Settings. |+| Cheaper-shopping comparison | Shopping or price connector | No shopping connector | Temporary shopping browser session | Add a shopping connector when Akeru Bot supports one. |+| Approved booking | Calendar or booking connector | No calendar, travel, or booking connector | Temporary booking browser session | Add a calendar or booking connector when Akeru Bot supports one. Approval stays a separate action. |++Detection means that Akeru Bot found a credential, subscription login, key, or CLI. Healthy means that a real provider request passed. OAuth refresh, an installed CLI, and an authenticated CLI probe do not prove provider access.++Consumer subscription access and API billing are separate. ChatGPT, Claude Max, Cursor Pro, SuperGrok, and X Premium+ do not prove billed API access. Akeru Bot cannot distinguish SuperGrok from X Premium+ through the shared xAI login, so it does not report plan-specific X Premium+ health.diff --git a/docs/user/bots.md b/docs/user/bots.mdindex 9e3e85299..d4025b0f0 100644--- a/docs/user/bots.md+++ b/docs/user/bots.md@@ -16,6 +16,8 @@ Use the panel button to collapse or reopen the editor. The default shortcut is *Bot replies support headings, links, tables, task lists, code blocks, math, and Mermaid diagrams.+On web and desktop, a bot can link to an app setting with a chip such as `[Error inbox](grokbot://app/v1/settings?id=bot-inbox)`. The chip opens the matching Settings section and shows the destination on hover.+## Call a botOpen **Settings → Voice** to enable voice, choose the ChatGPT subscription provider, and select a voice. Turning voice off there removes calling for every bot.diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex e5326c4f2..dae772c99 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -43,6 +43,10 @@"types": "./src/providerSkills.ts","default": "./src/providerSkills.ts"},+ "./settings-deep-link": {+ "types": "./src/settingsDeepLink.ts",+ "default": "./src/settingsDeepLink.ts"+ },"./relay": {"types": "./src/relay/index.ts","default": "./src/relay/index.ts"diff --git a/packages/client-runtime/src/settingsDeepLink.ts b/packages/client-runtime/src/settingsDeepLink.tsnew file mode 100644index 000000000..d0a21b5e0--- /dev/null+++ b/packages/client-runtime/src/settingsDeepLink.ts@@ -0,0 +1,38 @@+export const SETTINGS_DEEP_LINK_IDS = [+ "general",+ "local-execution",+ "appearance",+ "providers",+ "bot-inbox",+ "voice",+ "connections",+ "keybindings",+ "source-control",+ "diagnostics",+] as const;++export type SettingsDeepLinkId = (typeof SETTINGS_DEEP_LINK_IDS)[number];++const settingsDeepLinkIds = new Set<string>(SETTINGS_DEEP_LINK_IDS);++export function parseSettingsDeepLinkId(href: string | undefined): SettingsDeepLinkId | null {+ if (!href) return null;+ let url: URL;+ try {+ url = new URL(href);+ } catch {+ return null;+ }+ if (+ url.protocol !== "grokbot:" ||+ url.hostname !== "app" ||+ url.pathname !== "/v1/settings" ||+ url.hash !== "" ||+ [...url.searchParams.keys()].some((key) => key !== "id") ||+ url.searchParams.getAll("id").length > 1+ ) {+ return null;+ }+ const id = url.searchParams.get("id")?.trim() || "general";+ return settingsDeepLinkIds.has(id) ? (id as SettingsDeepLinkId) : null;+}diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.tsindex c0270c5f9..98fd2a0a3 100644--- a/packages/client-runtime/src/state/server.ts+++ b/packages/client-runtime/src/state/server.ts@@ -807,6 +807,10 @@ export function createServerEnvironmentAtoms<R, E>(label: "environment-data:server:subscription-auth:logout",tag: WS_METHODS.subscriptionAuthLogout,}),+ testSubscriptionAuth: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:server:subscription-auth:health-test",+ tag: WS_METHODS.subscriptionAuthHealthTest,+ }),startVoiceCall: createEnvironmentRpcCommand(runtime, {label: "environment-data:server:voice-call:start",tag: WS_METHODS.voiceCallStart,diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 46508f5b2..bfc3da0f5 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -171,6 +171,7 @@ import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settimport {SubscriptionAuthCompleteInput,SubscriptionAuthError,+ SubscriptionAuthHealthTestInput,SubscriptionAuthLoginProgress,SubscriptionAuthLogoutInput,SubscriptionAuthPollInput,@@ -277,6 +278,7 @@ export const WS_METHODS = {subscriptionAuthComplete: "subscriptionAuth.complete",subscriptionAuthCancel: "subscriptionAuth.cancel",subscriptionAuthLogout: "subscriptionAuth.logout",+ subscriptionAuthHealthTest: "subscriptionAuth.healthTest",voiceCallGet: "voiceCall.get",voiceCallStart: "voiceCall.start",voiceCallHangup: "voiceCall.hangup",@@ -422,6 +424,12 @@ export const WsSubscriptionAuthLogoutRpc = Rpc.make(WS_METHODS.subscriptionAuthLerror: Schema.Union([SubscriptionAuthError, EnvironmentAuthorizationError]),});+export const WsSubscriptionAuthHealthTestRpc = Rpc.make(WS_METHODS.subscriptionAuthHealthTest, {+ payload: SubscriptionAuthHealthTestInput,+ success: SubscriptionAuthStatuses,+ error: Schema.Union([SubscriptionAuthError, EnvironmentAuthorizationError]),+});+export const WsVoiceCallGetRpc = Rpc.make(WS_METHODS.voiceCallGet, {payload: Schema.Struct({}),success: VoiceCallSnapshot,@@ -945,6 +953,7 @@ export const WsRpcGroup = RpcGroup.make(WsSubscriptionAuthCompleteRpc,WsSubscriptionAuthCancelRpc,WsSubscriptionAuthLogoutRpc,+ WsSubscriptionAuthHealthTestRpc,WsVoiceCallGetRpc,WsVoiceCallStartRpc,WsVoiceCallHangupRpc,diff --git a/packages/contracts/src/subscriptionAuth.test.ts b/packages/contracts/src/subscriptionAuth.test.tsindex a47937dba..7c1c8f6b6 100644--- a/packages/contracts/src/subscriptionAuth.test.ts+++ b/packages/contracts/src/subscriptionAuth.test.ts@@ -20,9 +20,60 @@ describe("subscription auth contracts", () => {provider: "openai-codex",connected: true,expiresAt: 123,+ dependentBots: [],+ dependentRoutines: [],});});+ it("decodes every access-health state and action-required inbox data", () => {+ const healthStates = [+ "missing",+ "detected",+ "healthy",+ "expired",+ "revoked",+ "failed",+ "unsupported",+ "failed-first-request",+ "recovered",+ ] as const;+ for (const health of healthStates) {+ expect(+ decodeStatuses({+ providers: [{ provider: "xai", connected: true, health }],+ access: [+ {+ id: `access-${health}`,+ label: "Temporary email browser",+ accessMethod: "browser",+ health,+ apiAccess: "not-applicable",+ nextAction: "Use an email connector.",+ temporary: true,+ repairAction: "Add an email connector, then reconnect it.",+ },+ ],+ inbox: [+ {+ id: `incident-${health}`,+ incidentKey: `connector:xai:${health}`,+ kind: "connector-failure",+ status: "open",+ botId: "bot-akeru",+ botName: "Akeru",+ taskOrRoutine: "Morning research",+ lastFailure: "The provider request failed.",+ nextAction: "Reconnect the provider.",+ firstSeenAt: "2026-08-30T20:00:00.000Z",+ lastSeenAt: "2026-08-30T20:00:00.000Z",+ occurrenceCount: 1,+ },+ ],+ }).access[0],+ ).toMatchObject({ health, temporary: true });+ }+ });+it("decodes a remote-safe device login", () => {expect(decodeStartResult({diff --git a/packages/contracts/src/subscriptionAuth.ts b/packages/contracts/src/subscriptionAuth.tsindex c10064754..690d44f71 100644--- a/packages/contracts/src/subscriptionAuth.ts+++ b/packages/contracts/src/subscriptionAuth.ts@@ -6,7 +6,9 @@* contract — the server holds them; clients only see connection status and* login-flow progress.*/+import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";+import { BotId, IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas.ts";export const SubscriptionProviderId = Schema.Literals(["anthropic",@@ -22,14 +24,106 @@ export const SubscriptionProviderStatus = Schema.Struct({connected: Schema.Boolean,/** ms epoch when the current access token expires. Absent when disconnected. */expiresAt: Schema.optional(Schema.Number),+ health: Schema.optional(+ Schema.Literals([+ "missing",+ "detected",+ "healthy",+ "expired",+ "revoked",+ "failed",+ "unsupported",+ "failed-first-request",+ "recovered",+ ]),+ ),+ lastSuccessfulRequestAt: Schema.optional(IsoDateTime),+ lastFailedRequest: Schema.optional(+ Schema.Struct({+ at: IsoDateTime,+ message: TrimmedNonEmptyString,+ }),+ ),+ nextRetryAt: Schema.optional(IsoDateTime),+ reconnectAction: Schema.optional(TrimmedNonEmptyString),+ healthTest: Schema.optional(+ Schema.Struct({+ status: Schema.Literals(["not-run", "passed", "failed"]),+ checkedAt: Schema.optional(IsoDateTime),+ }),+ ),+ oauthCheck: Schema.optional(+ Schema.Struct({+ status: Schema.Literals(["passed", "failed"]),+ checkedAt: IsoDateTime,+ }),+ ),+ dependentBots: Schema.Array(Schema.Struct({ id: BotId, name: TrimmedNonEmptyString })).pipe(+ Schema.withDecodingDefault(Effect.succeed([])),+ ),+ dependentRoutines: Schema.Array(TrimmedNonEmptyString).pipe(+ Schema.withDecodingDefault(Effect.succeed([])),+ ),});export type SubscriptionProviderStatus = typeof SubscriptionProviderStatus.Type;export const SubscriptionAuthStatuses = Schema.Struct({providers: Schema.Array(SubscriptionProviderStatus),+ access: Schema.Array(+ Schema.Struct({+ id: TrimmedNonEmptyString,+ label: TrimmedNonEmptyString,+ accessMethod: Schema.Literals(["subscription-oauth", "api-key", "acp-cli", "browser"]),+ health: Schema.Literals([+ "missing",+ "detected",+ "healthy",+ "expired",+ "revoked",+ "failed",+ "unsupported",+ "failed-first-request",+ "recovered",+ ]),+ apiAccess: Schema.Literals(["separate", "included", "not-applicable"]),+ nextAction: TrimmedNonEmptyString,+ publishedLimit: Schema.optional(TrimmedNonEmptyString),+ temporary: Schema.optional(Schema.Boolean),+ repairAction: Schema.optional(TrimmedNonEmptyString),+ }),+ ).pipe(Schema.withDecodingDefault(Effect.succeed([]))),+ inbox: Schema.Array(+ Schema.Struct({+ id: TrimmedNonEmptyString,+ incidentKey: TrimmedNonEmptyString,+ kind: Schema.Literals([+ "oauth-expired",+ "connector-failure",+ "routine-failure",+ "browser-dead",+ "silence-watchdog-failure",+ "approval-request",+ ]),+ status: Schema.Literals(["open", "resolved"]),+ botId: BotId,+ botName: TrimmedNonEmptyString,+ taskOrRoutine: TrimmedNonEmptyString,+ lastFailure: TrimmedNonEmptyString,+ nextAction: TrimmedNonEmptyString,+ firstSeenAt: IsoDateTime,+ lastSeenAt: IsoDateTime,+ resolvedAt: Schema.optional(IsoDateTime),+ occurrenceCount: Schema.Int.check(Schema.isGreaterThan(0)),+ }),+ ).pipe(Schema.withDecodingDefault(Effect.succeed([]))),});export type SubscriptionAuthStatuses = typeof SubscriptionAuthStatuses.Type;+export const SubscriptionAuthHealthTestInput = Schema.Struct({+ provider: SubscriptionProviderId,+});+export type SubscriptionAuthHealthTestInput = typeof SubscriptionAuthHealthTestInput.Type;+export const SubscriptionAuthStartInput = Schema.Struct({provider: SubscriptionProviderId,});