TypeScript
feat: show provider usage limits with /usage-limits (#9875)
Chris Deeming183c3433091c
diff --git a/apps/mobile/src/connection/runtime.ts b/apps/mobile/src/connection/runtime.tsindex deee27ef040..ce478962b8b 100644--- a/apps/mobile/src/connection/runtime.ts+++ b/apps/mobile/src/connection/runtime.ts@@ -31,7 +31,9 @@ type ConnectionLayerSource =| typeof mobileBackgroundActivityReporterLayer;const providedClientConnectionLayer = snapshotLoaderLayer.pipe(- Layer.provideMerge(Connection.layerWithOptions({ usageLimitSources: true })),+ Layer.provideMerge(+ Connection.layerWithOptions({ usageLimitSources: true, usageLimitsCommand: true }),+ ),Layer.provideMerge(Layer.mergeAll(runtimeContextLayer,diff --git a/apps/mobile/src/features/threads/ComposerUsageLimits.tsx b/apps/mobile/src/features/threads/ComposerUsageLimits.tsxnew file mode 100644index 00000000000..bcd76722c8e--- /dev/null+++ b/apps/mobile/src/features/threads/ComposerUsageLimits.tsx@@ -0,0 +1,103 @@+import type { EnvironmentId, UsageLimitsReport } from "@t3tools/contracts";+import { Pressable, ScrollView, useWindowDimensions, View } from "react-native";++import { SymbolView } from "../../components/AppSymbol";+import { AppText as Text } from "../../components/AppText";+import { AccountLimits, ResetCredits } from "../usage/UsageLimitsSection";++const DRIVER_LABEL: Partial<Record<string, string>> = { codex: "Codex", claudeAgent: "Claude" };++/**+ * The /usage-limits result, docked above the composer. It is the Usage → Limits+ * card one size down, so the two read as the same thing. The surface is opaque+ * because nothing blurs the feed behind it.+ */+export function ComposerUsageLimits({+ report,+ environmentId,+ onClose,+}: {+ readonly report: UsageLimitsReport;+ readonly environmentId: EnvironmentId;+ readonly onClose: () => void;+}) {+ const now = Date.parse(report.createdAt);+ const { height } = useWindowDimensions();+ const close = (+ <Pressable+ accessibilityLabel="Dismiss usage limits"+ accessibilityRole="button"+ hitSlop={12}+ onPress={onClose}+ className="-me-1 p-1 active:opacity-60"+ >+ <SymbolView name="xmark" size={14} tintColorClassName="accent-icon-muted" type="monochrome" />+ </Pressable>+ );+ return (+ <View className="overflow-hidden rounded-[20px] border-continuous bg-card">+ <ScrollView+ bounces={false}+ showsVerticalScrollIndicator={false}+ style={{ maxHeight: Math.round(height * 0.4) }}+ >+ {report.accounts.map((account, index) => {+ const driverLabel = DRIVER_LABEL[account.driver] ?? String(account.driver);+ return (+ <AccountLimits+ key={account.id}+ dense+ first={index === 0}+ driver={account.driver}+ label={driverLabel}+ // Siblings need telling apart: a custom instance without a name shows its+ // id, and a pooled account shows its hub and account id.+ instanceLabel={+ account.instanceId+ ? account.displayName?.trim() ||+ (String(account.instanceId) !== String(account.driver)+ ? account.instanceId+ : driverLabel)+ : account.label+ }+ detail={account.plan}+ limits={account.limits}+ now={now}+ trailing={index === 0 ? close : undefined}+ footer={+ account.instanceId && account.limits.resetCredits ? (+ <ResetCredits+ dense+ environmentId={environmentId}+ instanceId={account.instanceId}+ credits={account.limits.resetCredits}+ now={now}+ />+ ) : undefined+ }+ />+ );+ })}+ {report.accounts.length === 0 ? (+ // Nothing but notices, so the close control needs a row of its own.+ <View className="flex-row items-center gap-3 px-4 pt-3">+ <Text className="min-w-0 flex-1 text-base text-foreground">Usage limits</Text>+ {close}+ </View>+ ) : null}+ {report.notices.map((notice) => (+ <Text+ key={notice}+ className={+ report.accounts.length === 0+ ? "px-4 py-3 text-xs text-foreground-muted"+ : "border-t border-border-subtle px-4 py-3 text-xs text-foreground-muted"+ }+ >+ {notice}+ </Text>+ ))}+ </ScrollView>+ </View>+ );+}diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsxindex e1cc7405bde..a50895bd33d 100644--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx@@ -49,6 +49,7 @@ import { VideoPreviewModal, type VideoPreviewSource } from "../../components/Vidimport { ProviderIcon } from "../../components/ProviderIcon";import { SymbolView } from "../../components/AppSymbol";import { AppText as Text } from "../../components/AppText";+import { hasProviderUsageLimits, isUsageLimitsCommand } from "@t3tools/shared/usageLimits";import { COMPOSER_LAYOUT_TRANSITION, ComposerSurface } from "./ThreadComposer";import { ShimmeringWorkContent } from "./thread-work-log";import { ComposerCommandPopover } from "./ComposerCommandPopover";@@ -309,6 +310,14 @@ export function NewTaskDraftScreen(props: {const isComposerInteractionLocked = isIncomingShareTransferPending || flow.submitting;// Also guard while a submit is in flight: an Android back press or iOS// Cancel would otherwise abandon the screen while the task still starts.+ // T3 owns /usage-limits only where Limits has data for the selected provider.+ const offersUsageLimits =+ flow.selectedProviderStatus !== null &&+ hasProviderUsageLimits(+ flow.selectedProviderStatus.driver,+ selectedEnvironmentServerConfig?.providers ?? [],+ selectedEnvironmentServerConfig?.usageLimitSources ?? [],+ );const composerMenu = useComposerCommandMenu({draftMessage: flow.prompt,ownerKey: flow.draftKey,@@ -320,6 +329,7 @@ export function NewTaskDraftScreen(props: {selectedProviderStatus: flow.selectedProviderStatus,hasThread: false,hasCompactableConversation: false,+ offersUsageLimits: offersUsageLimits,enabled: isComposerFocused && !isComposerInteractionLocked,onChangeDraftMessage: flow.setPrompt,onUpdateInteractionMode: flow.planModeEnabled ? flow.setInteractionMode : undefined,@@ -908,6 +918,20 @@ export function NewTaskDraftScreen(props: {);return;}+ // T3's own limits command is answered by the thread composer; a new task would+ // send it to the agent. A provider's same-named command, or a prompt carrying+ // attachments, goes through as usual.+ if (+ offersUsageLimits &&+ isUsageLimitsCommand(initialMessageText) &&+ draft.attachments.length === 0+ ) {+ Alert.alert(+ "Usage limits",+ "Send /usage-limits inside a thread, or open Settings → Usage → Limits.",+ );+ return;+ }// A failed-send restore can leave the draft over the cap on purpose (it// never drops the user's files); starting anyway would upload everything// and have the server reject the turn.diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsxindex af3359ec8c7..d61d7b92d0f 100644--- a/apps/mobile/src/features/threads/ThreadComposer.tsx+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx@@ -7,7 +7,13 @@ import type {ProviderInteractionMode,RuntimeMode,ServerConfig as T3ServerConfig,+ UsageLimitsReport,} from "@t3tools/contracts";+import {+ collectProviderUsageLimits,+ hasProviderUsageLimits,+ isUsageLimitsCommand,+} from "@t3tools/shared/usageLimits";import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";import type { ReactNode } from "react";import {@@ -20,7 +26,7 @@ import {useState,type RefObject,} from "react";-import { ActivityIndicator, Platform, Pressable, View, type ViewStyle } from "react-native";+import { ActivityIndicator, Alert, Platform, Pressable, View, type ViewStyle } from "react-native";import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";import {composerAttachmentUploadBlockReason,@@ -124,6 +130,8 @@ export interface ThreadComposerProps {readonly onRemoveDraftImage: (imageId: string) => void;readonly onStopThread: () => void;readonly onSendMessage: () => Promise<MessageId | null>;+ /** `/usage-limits` resolves locally; the host decides where the report shows. Null clears it. */+ readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;@@ -336,6 +344,30 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer);}, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);+ const { onSendMessage, onChangeDraftMessage, onShowUsageLimits } = props;+ // T3 owns /usage-limits only where Limits has data for the selected provider;+ // elsewhere the name stays the provider's own and is sent through untouched.+ const usageLimitsOffered =+ selectedProviderStatus !== null &&+ hasProviderUsageLimits(+ selectedProviderStatus.driver,+ props.serverConfig?.providers ?? [],+ props.serverConfig?.usageLimitSources ?? [],+ );+ // Answered locally from the last Limits snapshot; the agent never sees it.+ const openUsageLimits = useCallback(() => {+ const report = collectProviderUsageLimits(+ currentModelSelection.instanceId,+ props.serverConfig?.providers ?? [],+ props.serverConfig?.usageLimitSources ?? [],+ Date.now(),+ );+ onShowUsageLimits(report);+ if (!report) {+ Alert.alert("Usage limits unavailable", "This provider does not currently report limits.");+ }+ return report !== null;+ }, [currentModelSelection.instanceId, onShowUsageLimits, props.serverConfig]);const composerMenu = useComposerCommandMenu({draftMessage: props.draftMessage,@@ -350,6 +382,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerselectedProviderStatus?.showInteractionModeToggle === false? undefined: props.onUpdateInteractionMode,+ offersUsageLimits: usageLimitsOffered,+ // With attachments aboard the pick just inserts the text, so it sends as a prompt.+ onUsageLimits:+ usageLimitsOffered && props.draftAttachments.length === 0 ? openUsageLimits : undefined,});const voiceInput = useVoiceInputController({ownerKey: composerOwnerKey,@@ -428,9 +464,17 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer}onEditorFocusChange?.(false);}, [onEditorFocusChange, onExpandedChange, settingsSheetPresentation.isActive]);- const { onSendMessage } = props;-const handleSend = useCallback(async () => {+ // Typed out in full rather than picked from the menu. Attachments mean the+ // user is sending a prompt, so those go through as usual.+ if (+ usageLimitsOffered &&+ isUsageLimitsCommand(props.draftMessage) &&+ props.draftAttachments.length === 0+ ) {+ if (openUsageLimits()) onChangeDraftMessage("");+ return;+ }if (voiceInput.blocksSubmission) return;const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);if (inFlightThreadIdsRef.current.has(threadKey)) return;@@ -453,6 +497,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerinFlightThreadIdsRef.current.delete(threadKey);}}, [+ props.draftMessage,+ props.draftAttachments.length,+ onChangeDraftMessage,+ openUsageLimits,+ usageLimitsOffered,onSendMessage,props.environmentId,props.environmentLabel,diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex d0e553ebdcf..52ab91a5f49 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -19,6 +19,7 @@ import type {RuntimeMode,ServerConfig as T3ServerConfig,ThreadId,+ UsageLimitsReport,UserInputQuestion,} from "@t3tools/contracts";import * as Haptics from "expo-haptics";@@ -57,6 +58,7 @@ import Animated, {import { useSafeAreaInsets } from "react-native-safe-area-context";import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";+import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";import type { ComposerEditorHandle } from "../../components/ComposerEditor";import type { StatusTone } from "../../components/StatusPill";import type { DraftComposerAttachment } from "../../lib/composerImages";@@ -70,6 +72,7 @@ import type {ThreadFeedEntry,} from "../../lib/threadActivity";import { PendingApprovalCard } from "./PendingApprovalCard";+import { ComposerUsageLimits } from "./ComposerUsageLimits";import { PendingUserInputCard } from "./PendingUserInputCard";import {FLOATING_WORKING_CONTROL_COVERAGE,@@ -359,6 +362,68 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Threadconst [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =useState<ApprovalRequestId | null>(null);const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;+ // The open /usage-limits panel for this thread, model and turn. Only the open+ // moment is stored: the rows read live provider data, so a redeemed reset+ // credit or refreshed probe shows through. Anything that spends quota closes+ // it: a new turn from any source, or the agent resuming after an approval or+ // answered question.+ const [usageLimitsPanel, setUsageLimitsPanel] = useState<{+ readonly key: string;+ readonly threadKey: string;+ readonly now: number;+ } | null>(null);+ // A pending approval or question is part of the key: once it is answered,+ // from this client or any other, the agent resumes and spends quota.+ const usageLimitsKey = [+ selectedThreadKey,+ props.selectedThread.modelSelection.instanceId,+ props.selectedThread.latestTurn?.turnId ?? "",+ props.activePendingApproval?.requestId ?? props.activePendingUserInput?.requestId ?? "",+ ].join(":");+ // Drop the snapshot as soon as the key changes so it cannot resurface stale.+ if (usageLimitsPanel !== null && usageLimitsPanel.key !== usageLimitsKey) {+ setUsageLimitsPanel(null);+ }+ const usageLimitsReport = useMemo(+ () =>+ usageLimitsPanel !== null && usageLimitsPanel.key === usageLimitsKey+ ? collectProviderUsageLimits(+ props.selectedThread.modelSelection.instanceId,+ props.serverConfig?.providers ?? [],+ props.serverConfig?.usageLimitSources ?? [],+ usageLimitsPanel.now,+ )+ : null,+ [+ props.selectedThread.modelSelection.instanceId,+ props.serverConfig,+ usageLimitsKey,+ usageLimitsPanel,+ ],+ );+ const showUsageLimits = useCallback(+ (report: UsageLimitsReport | null) =>+ setUsageLimitsPanel(+ report === null+ ? null+ : {+ key: usageLimitsKey,+ threadKey: selectedThreadKey,+ now: Date.parse(report.createdAt),+ },+ ),+ [selectedThreadKey, usageLimitsKey],+ );+ const dismissUsageLimits = useCallback(() => setUsageLimitsPanel(null), []);+ // A send may resolve after navigating away, so only the originating+ // thread's panel is cleared; a panel opened elsewhere in the meantime stays.+ const clearUsageLimitsFor = useCallback(+ (threadKey: string) =>+ setUsageLimitsPanel((current) =>+ current !== null && current.threadKey === threadKey ? null : current,+ ),+ [],+ );const userInputCollapsed =activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;// The card's height RESERVES keyboard space at all times instead of@@ -623,6 +688,9 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Threadreturn messageId;}+ // A sent message makes the snapshot stale; a refused send leaves it in place.+ clearUsageLimitsFor(targetThreadKey);+setSubmittedMessageId(messageId);setAnchorMessageId(resolveThreadFeedSubmissionAnchor({@@ -637,6 +705,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Threadreturn messageId;}, [anchorMessageId,+ clearUsageLimitsFor,props.onSendMessage,props.selectedThread.latestTurn,props.selectedThreadQueueCount,@@ -778,6 +847,19 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadonScrollToEnd={handleScrollToEnd}/><View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>+ {usageLimitsReport && activeUserInputRequestId === null ? (+ <Animated.View+ className="shrink-0 px-4 pb-3"+ entering={FadeInDown.duration(220)}+ exiting={FadeOut.duration(140)}+ >+ <ComposerUsageLimits+ report={usageLimitsReport}+ environmentId={props.environmentId}+ onClose={dismissUsageLimits}+ />+ </Animated.View>+ ) : null}{props.activePendingApproval || props.activePendingUserInput ? (<Animated.ViewclassName="shrink-0 gap-3 px-4 pb-3"@@ -846,6 +928,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadonRemoveDraftImage={props.onRemoveDraftImage}onStopThread={props.onStopThread}onSendMessage={handleSendMessage}+ onShowUsageLimits={showUsageLimits}onReconnectEnvironment={props.onReconnectEnvironment}onUpdateModelSelection={props.onUpdateThreadModelSelection}onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.ts b/apps/mobile/src/features/threads/use-composer-command-menu.tsindex 5900acada91..23c56d28f4c 100644--- a/apps/mobile/src/features/threads/use-composer-command-menu.ts+++ b/apps/mobile/src/features/threads/use-composer-command-menu.ts@@ -1,4 +1,5 @@import type { EnvironmentId, ProviderInteractionMode, ServerProvider } from "@t3tools/contracts";+import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits";import {detectComposerTrigger,replaceTextRange,@@ -36,6 +37,8 @@ export function buildComposerSlashCommandItems(input: {readonly atMessageStart: boolean;readonly hasThread: boolean;readonly hasCompactableConversation?: boolean;+ /** Whether T3 itself offers /usage-limits for the selected provider. */+ readonly offersUsageLimits?: boolean;readonly allowInteractionMode: boolean;readonly selectedProviderStatus: Pick<ServerProvider,@@ -78,6 +81,11 @@ export function buildComposerSlashCommandItems(input: {for (const command of input.selectedProviderStatus?.slashCommands ?? []) {if (!command.name.toLowerCase().includes(query)) continue;if (command.name === "compact" && !input.hasCompactableConversation) continue;+ // T3's own limits command is answered by the thread composer; New Task has+ // nowhere to show it. A provider's same-named command is left alone.+ if (command.name === USAGE_LIMITS_COMMAND.name && input.offersUsageLimits && !input.hasThread) {+ continue;+ }if (!input.hasThread &&input.selectedProviderStatus?.driver === "codex" &&@@ -143,9 +151,11 @@ export function useComposerCommandMenu({selectedProviderStatus,hasThread,hasCompactableConversation,+ offersUsageLimits = false,enabled = true,onChangeDraftMessage,onUpdateInteractionMode,+ onUsageLimits,}: {readonly draftMessage: string;readonly ownerKey: string | null;@@ -154,9 +164,13 @@ export function useComposerCommandMenu({readonly selectedProviderStatus: ServerProvider | null;readonly hasThread: boolean;readonly hasCompactableConversation: boolean;+ /** Whether T3 itself offers /usage-limits for the selected provider. */+ readonly offersUsageLimits?: boolean;readonly enabled?: boolean;readonly onChangeDraftMessage: (value: string) => void;readonly onUpdateInteractionMode?: (mode: ProviderInteractionMode) => void;+ /** Picking /usage-limits is the action itself; the draft keeps nothing of it. */+ readonly onUsageLimits?: () => void;}) {const [selection, setSelection] = useState(() => composerSelectionAtEnd(draftMessage));const previousOwnerKeyRef = useRef(ownerKey);@@ -267,6 +281,7 @@ export function useComposerCommandMenu({atMessageStart: trigger.rangeStart === 0,hasThread,hasCompactableConversation,+ offersUsageLimits,allowInteractionMode: onUpdateInteractionMode !== undefined,selectedProviderStatus,});@@ -390,12 +405,25 @@ export function useComposerCommandMenu({selectedProviderStatus,skills,trigger,+ offersUsageLimits,]);const onSelect = useCallback((item: ComposerCommandItem) => {if (!trigger) return;+ if (+ item.type === "provider-slash-command" &&+ item.command.name === USAGE_LIMITS_COMMAND.name &&+ onUsageLimits+ ) {+ const cleared = replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, "");+ setSelection({ start: cleared.cursor, end: cleared.cursor });+ onChangeDraftMessage(cleared.text);+ onUsageLimits();+ return;+ }+const result = resolveComposerCommandSelection({draftMessage,trigger,@@ -414,6 +442,7 @@ export function useComposerCommandMenu({draftMessage,onChangeDraftMessage,onUpdateInteractionMode,+ onUsageLimits,selectedProviderStatus?.showInteractionModeToggle,trigger,],diff --git a/apps/mobile/src/features/usage/UsageLimitsSection.tsx b/apps/mobile/src/features/usage/UsageLimitsSection.tsxindex 0668efa3005..ca0608738fe 100644--- a/apps/mobile/src/features/usage/UsageLimitsSection.tsx+++ b/apps/mobile/src/features/usage/UsageLimitsSection.tsx@@ -69,9 +69,9 @@ function WindowRow(props: {<ViewclassName={used >= 90- ? "h-full rounded-full bg-destructive"+ ? "h-full rounded-full bg-red-500": used >= 70- ? "h-full rounded-full bg-warning"+ ? "h-full rounded-full bg-amber-500": "h-full rounded-full bg-foreground"}style={[@@ -99,7 +99,7 @@ function WindowRow(props: {}/** One account: icon, name and plan on a single line, then its windows. */-function AccountLimits(props: {+export function AccountLimits(props: {readonly driver: Driver;readonly label: string;readonly instanceLabel: string;@@ -107,14 +107,23 @@ function AccountLimits(props: {readonly limits: ServerProvider["usageLimits"];readonly now: number;readonly first: boolean;+ /** Tighter padding for the composer card. */+ readonly dense?: boolean;+ /** Sits at the end of the heading row, such as a close control. */+ readonly trailing?: ReactNode;readonly footer?: ReactNode;}) {- const { limits, now } = props;+ const { limits, now, dense = false } = props;const color = useBarColor(props.driver);if (!limits) return null;const notice = limitsNotice(limits);+ const padding = dense ? "px-4 py-3" : "p-4";return (- <View className={props.first ? "gap-3 p-4" : "gap-3 border-t border-border-subtle p-4"}>+ <View+ className={+ props.first ? `gap-3 ${padding}` : `gap-3 border-t border-border-subtle ${padding}`+ }+ ><View className="flex-row items-center gap-2"><ProviderIcon provider={props.driver} size={16} /><View className="min-w-0 flex-1 flex-row items-baseline gap-2">@@ -130,6 +139,7 @@ function AccountLimits(props: {</Text>) : null}</View>+ {props.trailing}</View>{notice ? (<Text className="text-sm text-foreground-muted">{notice}</Text>@@ -157,13 +167,15 @@ const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {* credit the provider granted the user, so it goes through the native* confirm alert rather than firing on a bare tap.*/-function ResetCredits(props: {+export function ResetCredits(props: {readonly environmentId: EnvironmentId;readonly instanceId: ProviderInstanceId;readonly credits: ServerProviderResetCredits;readonly now: number;+ /** A smaller pill for the composer card. */+ readonly dense?: boolean;}) {- const { environmentId, instanceId, credits, now } = props;+ const { environmentId, instanceId, credits, now, dense = false } = props;const consume = useAtomCommand(serverEnvironment.consumeResetCredit, {reportFailure: false,});@@ -217,10 +229,20 @@ function ResetCredits(props: {accessibilityState={{ disabled: busy }}disabled={busy}onPress={confirm}- className="rounded-full bg-subtle-strong px-3 py-1.5"+ className={+ dense+ ? "rounded-full bg-subtle-strong px-2.5 py-1"+ : "rounded-full bg-subtle-strong px-3 py-1.5"+ }>- <Text className="text-sm font-t3-medium text-foreground">- {busy ? "Using credit…" : "Use a reset credit"}+ <Text+ className={+ dense+ ? "text-xs font-t3-medium text-foreground"+ : "text-sm font-t3-medium text-foreground"+ }+ >+ {busy ? "Using…" : "Use reset"}</Text></Pressable>) : null}diff --git a/apps/mobile/src/state/server.ts b/apps/mobile/src/state/server.tsindex 2157c72e13e..28cd2af5706 100644--- a/apps/mobile/src/state/server.ts+++ b/apps/mobile/src/state/server.ts@@ -8,6 +8,7 @@ import { environmentSession } from "./session";export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRuntime, {initialConfigValueAtom: environmentSession.initialConfigValueAtom,usageLimitSources: true,+ usageLimitsCommand: true,});export const environmentServerConfigsAtom = createEnvironmentServerConfigsAtom({catalogValueAtom: environmentCatalog.catalogValueAtom,diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.tsindex cfebfcf157c..56889c1e63b 100644--- a/apps/server/src/server.test.ts+++ b/apps/server/src/server.test.ts@@ -39,6 +39,7 @@ import {type ServerLifecycleStreamEvent,ThreadId,TurnId,+ UsageLimitSourceId,WS_METHODS,WsRpcGroup,EditorId,@@ -498,6 +499,7 @@ const buildAppUnderTest = (options?: {keybindings?: Partial<Keybindings.Keybindings["Service"]>;environmentTheme?: Partial<EnvironmentTheme.EnvironmentThemeService["Service"]>;providerRegistry?: Partial<ProviderRegistry.ProviderRegistry["Service"]>;+ usageLimitSources?: Partial<UsageLimitSources.UsageLimitSources["Service"]>;providerService?: Partial<ProviderService.ProviderService["Service"]>;providerAuth?: Partial<ProviderAuthService["Service"]>;providerInstanceRegistry?: Partial<ProviderInstanceRegistry["Service"]>;@@ -756,8 +758,9 @@ const buildAppUnderTest = (options?: {}),Layer.mock(UsageLimitSources.UsageLimitSources)({current: Effect.succeed([]),- streamChanges: Stream.empty,+ streamChanges: Stream.make([]),refresh: Effect.void,+ ...options?.layers?.usageLimitSources,}),),),@@ -6246,10 +6249,94 @@ it.layer(NodeServices.layer)("server router seam", (it) => {}).pipe(Effect.provide(NodeHttpServer.layerTest)),);- it.effect("routes websocket rpc subscribeServerConfig emits provider status updates", () =>- Effect.gen(function* () {- const nextProviders = [- {+ it.effect.each([false, true])(+ "routes websocket rpc subscribeServerConfig emits provider status updates (limits: %s)",+ (hasLimits) =>+ Effect.gen(function* () {+ const nextProviders = [+ {+ instanceId: ProviderInstanceId.make("codex"),+ driver: ProviderDriverKind.make("codex"),+ enabled: true,+ installed: true,+ version: "1.0.0",+ status: "ready" as const,+ auth: { status: "authenticated" as const },+ checkedAt: "2026-04-11T00:00:00.000Z",+ models: [],+ slashCommands: [],+ skills: [],+ ...(hasLimits+ ? {+ usageLimits: {+ checkedAt: "2026-04-11T00:00:00.000Z",+ windows: [+ { id: "weekly", kind: "weekly" as const, label: "Weekly", usedPercent: 25 },+ ],+ },+ }+ : {}),+ },+ ] as const;++ yield* buildAppUnderTest({+ layers: {+ keybindings: {+ loadConfigState: Effect.succeed({+ keybindings: [],+ issues: [],+ }),+ streamChanges: Stream.empty,+ },+ providerRegistry: {+ getProviders: Effect.succeed([]),+ streamChanges: Stream.succeed(nextProviders),+ },+ },+ });++ const wsUrl = yield* getWsServerUrl("/ws");+ const events = yield* Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ client[WS_METHODS.subscribeServerConfig]({ usageLimitsCommand: true }).pipe(+ Stream.take(2),+ Stream.runCollect,+ ),+ ),+ );++ const [first, second] = Array.from(events);+ assert.equal(first?.type, "snapshot");+ if (first?.type === "snapshot") {+ assert.deepEqual(first.config.providers, []);+ }+ assert.deepEqual(second, {+ version: 1,+ type: "providerStatuses",+ payload: {+ providers: hasLimits+ ? [+ {+ ...nextProviders[0],+ slashCommands: [+ {+ name: "usage-limits",+ description: "Show this provider's usage limits",+ },+ ],+ },+ ]+ : nextProviders,+ },+ });+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ );++ it.effect(+ "routes websocket rpc subscribeServerConfig keeps the limits command from clients that do not ask for it",+ () =>+ Effect.gen(function* () {+ const codex = {instanceId: ProviderInstanceId.make("codex"),driver: ProviderDriverKind.make("codex"),enabled: true,@@ -6261,43 +6348,129 @@ it.layer(NodeServices.layer)("server router seam", (it) => {models: [],slashCommands: [],skills: [],- },- ] as const;-- yield* buildAppUnderTest({- layers: {- keybindings: {- loadConfigState: Effect.succeed({- keybindings: [],- issues: [],- }),- streamChanges: Stream.empty,+ usageLimits: {+ checkedAt: "2026-04-11T00:00:00.000Z",+ windows: [{ id: "weekly", kind: "weekly" as const, label: "Weekly", usedPercent: 25 }],},- providerRegistry: {- getProviders: Effect.succeed([]),- streamChanges: Stream.succeed(nextProviders),+ };+ yield* buildAppUnderTest({+ layers: {+ keybindings: {+ loadConfigState: Effect.succeed({ keybindings: [], issues: [] }),+ streamChanges: Stream.empty,+ },+ providerRegistry: {+ getProviders: Effect.succeed([codex]),+ streamChanges: Stream.succeed([{ ...codex, version: "1.0.1" }]),+ },},- },- });+ });- const wsUrl = yield* getWsServerUrl("/ws");- const events = yield* Effect.scoped(- withWsRpcClient(wsUrl, (client) =>- client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(2), Stream.runCollect),- ),- );+ const wsUrl = yield* getWsServerUrl("/ws");+ const events = yield* Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(2), Stream.runCollect),+ ),+ );- const [first, second] = Array.from(events);- assert.equal(first?.type, "snapshot");- if (first?.type === "snapshot") {- assert.deepEqual(first.config.providers, []);- }- assert.deepEqual(second, {- version: 1,- type: "providerStatuses",- payload: { providers: nextProviders },- });- }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ const [first, second] = Array.from(events);+ assert.equal(first?.type, "snapshot");+ if (first?.type === "snapshot") {+ assert.deepEqual(first.config.providers, [codex]);+ }+ assert.deepEqual(second, {+ version: 1,+ type: "providerStatuses",+ payload: { providers: [{ ...codex, version: "1.0.1" }] },+ });+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ );++ it.effect(+ "routes websocket rpc subscribeServerConfig republishes commands when only a limits source changes",+ () =>+ Effect.gen(function* () {+ const codex = {+ instanceId: ProviderInstanceId.make("codex"),+ driver: ProviderDriverKind.make("codex"),+ enabled: true,+ installed: true,+ version: "1.0.0",+ status: "ready" as const,+ auth: { status: "authenticated" as const },+ checkedAt: "2026-04-11T00:00:00.000Z",+ models: [],+ slashCommands: [],+ skills: [],+ };+ const hub = {+ id: UsageLimitSourceId.make("hub"),+ kind: "cliproxy" as const,+ label: "Accounts",+ checkedAt: "2026-04-11T00:00:00.000Z",+ accounts: [+ {+ id: "work",+ driver: ProviderDriverKind.make("codex"),+ usageLimits: {+ checkedAt: "2026-04-11T00:00:00.000Z",+ windows: [+ { id: "weekly", kind: "weekly" as const, label: "Weekly", usedPercent: 25 },+ ],+ },+ },+ ],+ };++ yield* buildAppUnderTest({+ layers: {+ keybindings: {+ loadConfigState: Effect.succeed({ keybindings: [], issues: [] }),+ streamChanges: Stream.empty,+ },+ // The registry emits no change: only the source refresh can carry it.+ providerRegistry: {+ getProviders: Effect.succeed([codex]),+ streamChanges: Stream.empty,+ },+ usageLimitSources: {+ current: Effect.succeed([]),+ // Replay the empty snapshot, then a later refresh, as the live stream does.+ streamChanges: Stream.concat(Stream.make([]), Stream.make([hub])),+ },+ },+ });++ const wsUrl = yield* getWsServerUrl("/ws");+ const events = yield* Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ client[WS_METHODS.subscribeServerConfig]({ usageLimitsCommand: true }).pipe(+ Stream.take(2),+ Stream.runCollect,+ ),+ ),+ );++ const [first, second] = Array.from(events);+ assert.equal(first?.type, "snapshot");+ if (first?.type === "snapshot") {+ assert.deepEqual(first.config.providers, [codex]);+ }+ assert.deepEqual(second, {+ version: 1,+ type: "providerStatuses",+ payload: {+ providers: [+ {+ ...codex,+ slashCommands: [+ { name: "usage-limits", description: "Show this provider's usage limits" },+ ],+ },+ ],+ },+ });+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),);it.effect(diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 6261f7bc528..fa29d5bd984 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -1,3 +1,7 @@+import {+ sameUsageLimitCommandCoverage,+ withUsageLimitsCommands,+} from "@t3tools/shared/usageLimits";import * as Cause from "effect/Cause";import * as Crypto from "effect/Crypto";import * as DateTime from "effect/DateTime";@@ -1221,59 +1225,67 @@ const makeWsRpcLayer = ();};- const loadServerConfig = Effect.gen(function* () {- const keybindingsConfig = yield* keybindings.loadConfigState;- const providers = yield* providerRegistry.getProviders;- const settings = ServerSettings.redactServerSettingsForClient(- yield* serverSettings.getSettings,- );- const environment = yield* serverEnvironment.getDescriptor;- const auth = yield* serverAuth.getDescriptor();- const availableEditors: ReadonlyArray<EditorId> = yield* resolveAvailableEditorsForConfig(- externalLauncher.resolveAvailableEditors(),- );- const fileManagerRevealKind = availableEditors.includes("file-manager")- ? yield* resolveFileManagerRevealKindForConfig(- externalLauncher.resolveFileManagerRevealKind(),- )- : undefined;-- return {- environment,- auth,- cwd: config.cwd,- keybindingsConfigPath: config.keybindingsConfigPath,- keybindings: keybindingsConfig.keybindings,- issues: keybindingsConfig.issues,- providers,- availableEditors,- // Same discovery-with-timeout treatment as editors: a slow probe- // must not stall server.getConfig, so it degrades to no targets.- remoteOpenTargets: yield* resolveAvailableEditorsForConfig(- remoteOpenTargets.resolveTargets(),- ),- observability: {- logsDirectoryPath: config.logsDir,- localTracingEnabled: true,- ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}),- otlpTracesEnabled: config.otlpTracesUrl !== undefined,- ...(config.otlpMetricsUrl !== undefined- ? { otlpMetricsUrl: config.otlpMetricsUrl }- : {}),- otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,- },- settings,- shellResumeCompletionMarker: true,- ...(fileManagerRevealKind === undefined- ? {}- : {- shellRevealInFileManager: true,- shellRevealInFileManagerKind: fileManagerRevealKind,- }),- threadResumeCompletionMarker: true,- threadSnapshotPagination: true,- };- });+ // Only clients that answer /usage-limits themselves see it in the catalogs;+ // an older client would send the injected command to the provider.+ const loadServerConfig = (options: { readonly usageLimitsCommand: boolean }) =>+ Effect.gen(function* () {+ const keybindingsConfig = yield* keybindings.loadConfigState;+ const currentProviders = yield* providerRegistry.getProviders;+ const providers = options.usageLimitsCommand+ ? withUsageLimitsCommands(currentProviders, yield* usageLimitSources.current)+ : currentProviders;+ const settings = ServerSettings.redactServerSettingsForClient(+ yield* serverSettings.getSettings,+ );+ const environment = yield* serverEnvironment.getDescriptor;+ const auth = yield* serverAuth.getDescriptor();+ const availableEditors: ReadonlyArray<EditorId> = yield* resolveAvailableEditorsForConfig(+ externalLauncher.resolveAvailableEditors(),+ );+ const fileManagerRevealKind = availableEditors.includes("file-manager")+ ? yield* resolveFileManagerRevealKindForConfig(+ externalLauncher.resolveFileManagerRevealKind(),+ )+ : undefined;++ return {+ environment,+ auth,+ cwd: config.cwd,+ keybindingsConfigPath: config.keybindingsConfigPath,+ keybindings: keybindingsConfig.keybindings,+ issues: keybindingsConfig.issues,+ providers,+ availableEditors,+ // Same discovery-with-timeout treatment as editors: a slow probe+ // must not stall server.getConfig, so it degrades to no targets.+ remoteOpenTargets: yield* resolveAvailableEditorsForConfig(+ remoteOpenTargets.resolveTargets(),+ ),+ observability: {+ logsDirectoryPath: config.logsDir,+ localTracingEnabled: true,+ ...(config.otlpTracesUrl !== undefined+ ? { otlpTracesUrl: config.otlpTracesUrl }+ : {}),+ otlpTracesEnabled: config.otlpTracesUrl !== undefined,+ ...(config.otlpMetricsUrl !== undefined+ ? { otlpMetricsUrl: config.otlpMetricsUrl }+ : {}),+ otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,+ },+ settings,+ shellResumeCompletionMarker: true,+ ...(fileManagerRevealKind === undefined+ ? {}+ : {+ shellRevealInFileManager: true,+ shellRevealInFileManagerKind: fileManagerRevealKind,+ }),+ threadResumeCompletionMarker: true,+ threadSnapshotPagination: true,+ };+ });const refreshGitStatus = (cwd: string) =>vcsStatusBroadcaster@@ -1750,9 +1762,13 @@ const makeWsRpcLayer = ("rpc.aggregate": "server",}),[WS_METHODS.serverGetConfig]: (_input) =>- observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, {- "rpc.aggregate": "server",- }),+ observeRpcEffect(+ WS_METHODS.serverGetConfig,+ loadServerConfig({ usageLimitsCommand: false }),+ {+ "rpc.aggregate": "server",+ },+ ),[WS_METHODS.serverRefreshProviders]: (input) =>observeRpcEffect(WS_METHODS.serverRefreshProviders,@@ -2692,6 +2708,8 @@ const makeWsRpcLayer = (observeRpcStreamEffect(WS_METHODS.subscribeServerConfig,Effect.gen(function* () {+ const usageLimitsCommand = input.usageLimitsCommand === true;+ const config = yield* loadServerConfig({ usageLimitsCommand });const keybindingsUpdates = keybindings.streamChanges.pipe(Stream.map((event) => ({version: 1 as const,@@ -2702,7 +2720,33 @@ const makeWsRpcLayer = (},})),);- const providerStatuses = providerRegistry.streamChanges.pipe(+ const providerStatuses = Stream.zipLatestWith(+ // The registry stream carries changes only. Seed it with the current+ // providers so a source refresh that lands before any provider change+ // still pairs up and reaches the client.+ Stream.concat(+ Stream.fromEffect(providerRegistry.getProviders),+ providerRegistry.streamChanges,+ ),+ usageLimitSources.streamChanges.pipe(+ // Quota updates already have their own stream. Republish the model+ // catalog only when the set of providers offered the command changes.+ Stream.changesWith(+ usageLimitsCommand ? sameUsageLimitCommandCoverage : () => true,+ ),+ ),+ (providers, sources) =>+ usageLimitsCommand ? withUsageLimitsCommands(providers, sources) : providers,+ ).pipe(+ // Both sides replay their current value, so the first pairing normally+ // repeats the snapshot the client already holds. Compare against that+ // snapshot rather than dropping blindly: a refresh that landed between+ // the snapshot and the subscription still goes out.+ (updates) => Stream.concat(Stream.make(config.providers), updates),+ Stream.changesWith(+ (previous, next) => JSON.stringify(previous) === JSON.stringify(next),+ ),+ Stream.drop(1),Stream.map((providers) => ({version: 1 as const,type: "providerStatuses" as const,@@ -2763,11 +2807,7 @@ const makeWsRpcLayer = ();return Stream.concat(- Stream.make({- version: 1 as const,- type: "snapshot" as const,- config: yield* loadServerConfig,- }),+ Stream.make({ version: 1 as const, type: "snapshot" as const, config }),liveUpdates,);}),diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 6173c760cee..c9c2c60badb 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -1,3 +1,10 @@+import type { UsageLimitSourceSnapshots } from "@t3tools/contracts";+import {+ collectProviderUsageLimits,+ hasProviderUsageLimits,+ isUsageLimitsCommand,+} from "@t3tools/shared/usageLimits";+import { usageLimitsBannerItem } from "./chat/ComposerUsageLimits";import {type AssistantCitation,type ApprovalRequestId,@@ -451,6 +458,7 @@ import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "./chat/composerPromptHistory";const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];const EMPTY_PROVIDERS: ServerProvider[] = [];+const EMPTY_USAGE_LIMIT_SOURCES: UsageLimitSourceSnapshots = [];const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};function useDraftHeroLayoutTransition(isDraftHeroState: boolean) {@@ -1505,6 +1513,11 @@ export default function ChatView(props: ChatViewProps) {const draft = store.getComposerDraft(composerDraftTarget);return (draft?.images.length ?? 0) > 0 || (draft?.files.length ?? 0) > 0;});+ // Anything beyond the prompt text: attachments, terminal or element contexts, annotations.+ const composerHasNonPromptContent = useComposerDraftStore((store) => {+ const draft = store.getComposerDraft(composerDraftTarget);+ return draft ? composerDraftHasUserContent({ ...draft, prompt: "" }) : false;+ });const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);const addComposerDraftFiles = useComposerDraftStore((store) => store.addFiles);@@ -2620,6 +2633,111 @@ export default function ChatView(props: ChatViewProps) {hasComposerAttachments: composerHasAttachments,});const activePendingApproval = pendingApprovals[0] ?? null;+ // The open /usage-limits panel for this thread, model and turn. Only the open+ // moment is stored: the rows read live provider data, so a redeemed reset+ // credit or refreshed probe shows through. Anything that spends quota closes+ // it: a new turn from any source, or the agent resuming after an approval or+ // answered question.+ const [usageLimitsPanel, setUsageLimitsPanel] = useState<{+ readonly key: string;+ readonly threadKey: string;+ readonly now: number;+ } | null>(null);+ // Null while the provider list or the thread itself is unavailable, such as+ // during a reconnect; the panel then stays hidden rather than being dropped.+ // A pending approval or question is part of the key: once it is answered,+ // from this client or any other, the agent resumes and spends quota.+ const usageLimitsKey =+ activeProviderInstanceId === null || (isServerThread && activeThread === undefined)+ ? null+ : [+ routeThreadKey,+ activeProviderInstanceId,+ activeThread?.latestTurn?.turnId ?? "",+ activePendingApproval?.requestId ?? activePendingUserInput?.requestId ?? "",+ ].join(":");+ // Drop the snapshot as soon as the thread or model changes so it cannot resurface stale.+ if (+ usageLimitsPanel !== null &&+ usageLimitsKey !== null &&+ usageLimitsPanel.key !== usageLimitsKey+ ) {+ setUsageLimitsPanel(null);+ }+ const usageLimitSources = serverConfig?.usageLimitSources ?? EMPTY_USAGE_LIMIT_SOURCES;+ const usageLimitsReport = useMemo(+ () =>+ usageLimitsPanel !== null &&+ usageLimitsKey !== null &&+ usageLimitsPanel.key === usageLimitsKey &&+ activeProviderInstanceId !== null+ ? collectProviderUsageLimits(+ activeProviderInstanceId,+ providerStatuses,+ usageLimitSources,+ usageLimitsPanel.now,+ )+ : null,+ [+ activeProviderInstanceId,+ providerStatuses,+ usageLimitSources,+ usageLimitsKey,+ usageLimitsPanel,+ ],+ );+ const usageLimitsBanner = useMemo(+ () =>+ usageLimitsReport !== null && usageLimitsPanel !== null+ ? // A fresh id per opening: the stack keeps the last dismissed id as "exiting".+ usageLimitsBannerItem(+ `usage-limits:${usageLimitsPanel.key}:${usageLimitsPanel.now}`,+ usageLimitsReport,+ environmentId,+ () => setUsageLimitsPanel(null),+ )+ : null,+ [environmentId, usageLimitsPanel, usageLimitsReport],+ );+ // T3 owns /usage-limits only where Limits has data for the selected provider;+ // elsewhere the name stays the provider's own and is sent through untouched.+ const usageLimitsOffered =+ activeProviderStatus !== null &&+ hasProviderUsageLimits(activeProviderStatus.driver, providerStatuses, usageLimitSources);+ // Answered locally from the last Limits snapshot; the agent never sees it.+ const openUsageLimits = useCallback(() => {+ const now = Date.now();+ const report =+ activeProviderInstanceId !== null && usageLimitsKey !== null+ ? collectProviderUsageLimits(+ activeProviderInstanceId,+ providerStatuses,+ usageLimitSources,+ now,+ )+ : null;+ if (report && usageLimitsKey !== null) {+ setUsageLimitsPanel({ key: usageLimitsKey, threadKey: routeThreadKey, now });+ return true;+ }+ setUsageLimitsPanel(null);+ toastManager.add({ type: "info", title: "Usage limits are unavailable for this provider" });+ return false;+ }, [+ activeProviderInstanceId,+ providerStatuses,+ routeThreadKey,+ usageLimitSources,+ usageLimitsKey,+ ]);+ // Responses can resolve after navigating away; only the originating thread's panel clears.+ const clearUsageLimitsFor = useCallback(+ (threadKey: string) =>+ setUsageLimitsPanel((current) =>+ current !== null && current.threadKey === threadKey ? null : current,+ ),+ [],+ );const {beginLocalDispatch,resetLocalDispatch,@@ -5599,8 +5717,11 @@ export default function ChatView(props: ChatViewProps) {resumeCompactionBannerItem === null ? [] : [resumeCompactionBannerItem];const wokeThreadItems = wokeThreadBannerItem === null ? [] : [wokeThreadBannerItem];const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem];+ // The user asked for this one, so it leads the notice tier instead of trailing it.+ const usageLimitsItems = usageLimitsBanner === null ? [] : [usageLimitsBanner];if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {return [+ ...usageLimitsItems,...systemComposerBannerItems,...backgroundLivenessItems,...resumeCompactionItems,@@ -5609,6 +5730,7 @@ export default function ChatView(props: ChatViewProps) {];}return [+ ...usageLimitsItems,...systemComposerBannerItems,...backgroundLivenessItems,...resumeCompactionItems,@@ -5663,6 +5785,7 @@ export default function ChatView(props: ChatViewProps) {resumeCompactionBannerItem,showBranchMismatchBanner,systemComposerBannerItems,+ usageLimitsBanner,wokeThreadBannerItem,]);useEffect(() => {@@ -6076,6 +6199,23 @@ export default function ChatView(props: ChatViewProps) {},) => {e?.preventDefault();+ // Typed out in full rather than picked from the menu. Attachments or contexts+ // mean the user is sending a prompt, so those go through as usual.+ if (+ usageLimitsOffered &&+ usageLimitsKey !== null &&+ !directAnnotation &&+ !composerHasNonPromptContent &&+ isUsageLimitsCommand(promptRef.current)+ ) {+ if (openUsageLimits()) {+ promptRef.current = "";+ setComposerDraftPrompt(composerDraftTarget, "");+ composerRef.current?.resetCursorState();+ }+ return;+ }+const notifyDirectAnnotationAttached = () => {if (!directAnnotation) return;toastManager.add(@@ -6718,6 +6858,10 @@ export default function ChatView(props: ChatViewProps) {failure = startResult;} else {turnStartSucceeded = true;+ // The turn is under way and will spend quota, so that thread's limits+ // snapshot is stale. Uploads may have outlasted a navigation, so only+ // the sending thread's panel clears.+ clearUsageLimitsFor(routeThreadKey);if (turnUsesAttachmentUploads) {releaseDraftAttachments(composerAttachmentsSnapshot);}@@ -7138,6 +7282,7 @@ export default function ChatView(props: ChatViewProps) {}if (failure === null) {+ clearUsageLimitsFor(routeThreadKey);acknowledgeActiveThreadWoke();sendInFlightRef.current = false;return;@@ -7174,6 +7319,8 @@ export default function ChatView(props: ChatViewProps) {startThreadTurn,environmentId,composerRef,+ clearUsageLimitsFor,+ routeThreadKey,],);@@ -7949,6 +8096,15 @@ export default function ChatView(props: ChatViewProps) {}isPreparingWorktree={isPreparingWorktree}bannerItems={composerBannerItems}+ // With attachments or contexts aboard the pick just inserts the+ // text, so it sends as a prompt like the typed path would.+ onUsageLimitsCommand={+ usageLimitsOffered &&+ usageLimitsKey !== null &&+ !composerHasNonPromptContent+ ? openUsageLimits+ : undefined+ }environmentUnavailable={activeEnvironmentUnavailableState}activePendingApproval={activePendingApproval}pendingApprovals={pendingApprovals}diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex 30acb44dd42..9772efc3290 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -22,6 +22,7 @@ import {import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";+import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits";import {Fragment,memo,@@ -1191,6 +1192,8 @@ export interface ChatComposerProps {sendDisabledReason: string | null;isPreparingWorktree: boolean;bannerItems: readonly ComposerBannerStackItem[];+ /** Picking /usage-limits from the menu is the action itself; the draft keeps nothing of it. */+ onUsageLimitsCommand?: (() => void) | undefined;environmentUnavailable: {readonly label: string;readonly connection: EnvironmentConnectionPresentation;@@ -2684,6 +2687,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)};}, [readComposerSnapshot]);+ const { onUsageLimitsCommand } = props;const onSelectComposerItem = useCallback((item: ComposerCommandItem) => {if (composerSelectLockRef.current) return;@@ -2734,6 +2738,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)return;}if (item.type === "provider-slash-command") {+ if (item.command.name === USAGE_LIMITS_COMMAND.name && onUsageLimitsCommand) {+ const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {+ expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),+ focusEditorAfterReplace: false,+ });+ if (applied) {+ setComposerHighlightedItemId(null);+ onUsageLimitsCommand();+ }+ return;+ }const replacement = `/${item.command.name} `;const replacementRangeEnd = extendReplacementRangeForTrailingSpace(snapshot.value,@@ -2774,6 +2789,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)applyPromptReplacement,handleInteractionModeChange,planModeUiEnabled,+ onUsageLimitsCommand,resolveActiveComposerTrigger,],);diff --git a/apps/web/src/components/chat/ComposerUsageLimits.tsx b/apps/web/src/components/chat/ComposerUsageLimits.tsxnew file mode 100644index 00000000000..384492b5789--- /dev/null+++ b/apps/web/src/components/chat/ComposerUsageLimits.tsx@@ -0,0 +1,97 @@+import type { EnvironmentId, UsageLimitsReport } from "@t3tools/contracts";+import { limitsNotice } from "@t3tools/shared/usageLimits";+import { GaugeIcon } from "lucide-react";++import { getDriverOption } from "../settings/providerDriverMeta";+import { LimitWindows, ResetCredits } from "../usage/UsageLimits";+import { ComposerBanner } from "./ComposerBanner";+import type { ComposerBannerStackItem } from "./ComposerBannerStack";++/** Driver name, then the instance when there could be more than one of that driver. */+function accountLabel(account: UsageLimitsReport["accounts"][number]): string {+ if (!account.instanceId) return account.label;+ const driver = getDriverOption(account.driver)?.label ?? String(account.driver);+ const instance =+ account.displayName?.trim() ||+ (String(account.instanceId) !== String(account.driver) ? account.instanceId : "");+ // The default instance is often named after its driver; saying it twice adds nothing.+ return instance && instance.toLowerCase() !== driver.toLowerCase()+ ? `${driver} · ${instance}`+ : driver;+}++/** The /usage-limits result as a composer notice: it stacks under warnings and dismisses like one. */+export function usageLimitsBannerItem(+ id: string,+ report: UsageLimitsReport,+ environmentId: EnvironmentId,+ onDismiss: () => void,+): ComposerBannerStackItem {+ const [first] = report.accounts;+ const single = report.accounts.length === 1 && first ? first : null;+ const summary = single+ ? [accountLabel(single), single.plan].filter(Boolean).join(" · ")+ : `${report.accounts.length} accounts`;+ return {+ id,+ variant: "info",+ priority: "notice",+ icon: <GaugeIcon />,+ title: "Usage limits",+ description: summary,+ dismissLabel: "Dismiss usage limits",+ onDismiss,+ children: <UsageLimitsBannerBody report={report} environmentId={environmentId} />,+ };+}++function UsageLimitsBannerBody({+ report,+ environmentId,+}: {+ readonly report: UsageLimitsReport;+ readonly environmentId: EnvironmentId;+}) {+ const now = Date.parse(report.createdAt);+ return (+ <ComposerBanner.Scroll>+ <ComposerBanner.Body className="flex flex-col gap-2 pt-1 pb-1.5 pe-2">+ {report.accounts.map((account) => {+ const notice = limitsNotice(account.limits);+ return (+ <div key={account.id} className="flex min-w-0 flex-col gap-1">+ {report.accounts.length > 1 ? (+ <span className="truncate text-xs text-muted-foreground">+ {[accountLabel(account), account.plan].filter(Boolean).join(" · ")}+ </span>+ ) : null}+ {notice ? (+ <span className="text-xs text-muted-foreground">{notice}</span>+ ) : (+ <LimitWindows+ compact+ driver={account.driver}+ windows={account.limits.windows}+ now={now}+ />+ )}+ {account.instanceId && account.limits.resetCredits ? (+ <ResetCredits+ environmentId={environmentId}+ instanceId={account.instanceId}+ credits={account.limits.resetCredits}+ now={now}+ />+ ) : null}+ </div>+ );+ })}+ {report.notices.map((notice) => (+ <span key={notice} className="text-xs text-muted-foreground">+ {notice}+ </span>+ ))}+ </ComposerBanner.Body>+ </ComposerBanner.Scroll>+ );+}diff --git a/apps/web/src/components/usage/UsageLimits.tsx b/apps/web/src/components/usage/UsageLimits.tsxindex 77f85953984..5584cfc169f 100644--- a/apps/web/src/components/usage/UsageLimits.tsx+++ b/apps/web/src/components/usage/UsageLimits.tsx@@ -153,24 +153,31 @@ function WindowBar({);}-/** One account's windows as rows: label and percent, bar, pace and countdown. */-function LimitWindows({+/**+ * One account's windows as rows: label and percent, bar, pace and countdown.+ * Compact rows fit the composer panel with narrower columns.+ */+export function LimitWindows({driver,windows,now,+ compact = false,}: {readonly driver: ServerProvider["driver"];readonly windows: ReadonlyArray<ServerProviderUsageWindow>;readonly now: number;+ readonly compact?: boolean;}) {const color = barColor(driver);return (- <div className="grid grid-cols-[11rem_minmax(0,1fr)_7rem] gap-x-4 gap-y-1">- {windows.map((window, index) => {- // Windows that reset together show the countdown once.- const previous = windows[index - 1];- const sharesReset =- previous?.resetsAt !== undefined && previous.resetsAt === window.resetsAt;+ <div+ className={+ compact+ ? "grid grid-cols-[minmax(0,9rem)_minmax(3rem,1fr)_auto] gap-x-3 gap-y-0.5"+ : "grid grid-cols-[11rem_minmax(0,1fr)_7rem] gap-x-4 gap-y-1"+ }+ >+ {windows.map((window) => {const pace = paceOf(window, now);const resetsIn = formatResetsIn(window, now);return (@@ -182,9 +189,9 @@ function LimitWindows({</span></span><WindowBar color={color} window={window} now={now} />- <span className="flex items-center gap-2 text-xs text-muted-foreground tabular-nums">+ <span className="flex items-center gap-2 text-xs whitespace-nowrap text-muted-foreground tabular-nums">{pace ? <PaceIcon pace={pace} /> : null}- <span className="ms-auto shrink-0">{sharesReset ? "" : (resetsIn ?? "")}</span>+ <span className="ms-auto shrink-0">{resetsIn ?? ""}</span></span></Fragment>);@@ -292,7 +299,7 @@ const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {* Banked reset credits with a confirmed redeem action. Redeeming spends a* credit the provider granted the user, so it never fires on a bare click.*/-function ResetCredits({+export function ResetCredits({environmentId,instanceId,credits,@@ -341,7 +348,7 @@ function ResetCredits({<span className="tabular-nums">{summary}</span>{credits.availableCount > 0 ? (<Button size="xs" variant="outline" disabled={busy} onClick={() => setConfirming(true)}>- {busy ? "Using credit…" : "Use a reset credit"}+ {busy ? "Using…" : "Use reset"}</Button>) : null}{status ? <span className="text-foreground">{status}</span> : null}diff --git a/apps/web/src/connection/runtime.ts b/apps/web/src/connection/runtime.tsindex ac2316560d9..b5e78287f26 100644--- a/apps/web/src/connection/runtime.ts+++ b/apps/web/src/connection/runtime.ts@@ -32,7 +32,11 @@ type ConnectionLayerSource =const providedClientConnectionLayer = snapshotLoaderLayer.pipe(Layer.provideMerge(- Connection.layerWithOptions({ environmentThemes: true, usageLimitSources: true }),+ Connection.layerWithOptions({+ environmentThemes: true,+ usageLimitSources: true,+ usageLimitsCommand: true,+ }),),Layer.provideMerge(Layer.mergeAll(diff --git a/apps/web/src/state/server.ts b/apps/web/src/state/server.tsindex 0eacc933da4..31b9436621c 100644--- a/apps/web/src/state/server.ts+++ b/apps/web/src/state/server.ts@@ -29,6 +29,7 @@ export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRuntinitialConfigValueAtom: environmentSession.initialConfigValueAtom,environmentThemes: true,usageLimitSources: true,+ usageLimitsCommand: true,});export const environmentServerConfigsAtom = createEnvironmentServerConfigsAtom({catalogValueAtom: environmentCatalog.catalogValueAtom,diff --git a/docs/user/usage.md b/docs/user/usage.mdindex a0231856ef6..dc92b3f6591 100644--- a/docs/user/usage.md+++ b/docs/user/usage.md@@ -45,6 +45,11 @@ next reset.If a window looks stale, refresh Limits to re-check every provider and hub.+Pick `/usage-limits` from the composer's command menu, or send it as a message, to check the+current model's limits without leaving the conversation. The result opens above the composer and+closes when you dismiss it or send your next message. It uses the same snapshot as **Usage → Limits**, so it does not run the agent or refresh+anything. The command is offered only for providers that appear under **Usage → Limits**.+API-key accounts may not report subscription limits. This also applies to Claude connectionsusing a proxy through `ANTHROPIC_AUTH_TOKEN`.diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.tsindex 2402c132456..3e353f6be4d 100644--- a/packages/client-runtime/src/rpc/session.ts+++ b/packages/client-runtime/src/rpc/session.ts@@ -57,6 +57,8 @@ export interface RpcSession {export interface RpcSessionOptions {readonly environmentThemes?: boolean;readonly usageLimitSources?: boolean;+ /** This client answers /usage-limits itself, so the server may advertise it. */+ readonly usageLimitsCommand?: boolean;}export class RpcSessionFactory extends Context.Service<@@ -153,6 +155,7 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* (const serverConfigInput: ServerConfigSubscriptionInput = {...(options.environmentThemes === true ? { environmentThemes: true } : {}),...(options.usageLimitSources === true ? { usageLimitSources: true } : {}),+ ...(options.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),};const connect = Effect.fnUntraced(function* (connection: PreparedConnection) {diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.tsindex e209acfd1e7..5df29a8629d 100644--- a/packages/client-runtime/src/state/server.ts+++ b/packages/client-runtime/src/state/server.ts@@ -358,6 +358,7 @@ const cachedConfigSnapshotEvent = (config: ServerConfig): ServerConfigStreamEvenexport interface ServerConfigSubscriptionOptions {readonly environmentThemes?: boolean;readonly usageLimitSources?: boolean;+ readonly usageLimitsCommand?: boolean;}export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")(@@ -425,6 +426,7 @@ export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfyield* subscribe(WS_METHODS.subscribeServerConfig, {...(subscription.environmentThemes === true ? { environmentThemes: true } : {}),...(subscription.usageLimitSources === true ? { usageLimitSources: true } : {}),+ ...(subscription.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),}).pipe(Stream.runForEach((event) =>Effect.gen(function* () {@@ -621,6 +623,7 @@ export function createServerEnvironmentAtoms<R, E>(readonly environmentThemes?: boolean;/** Whether this surface renders quota from configured usage-limit sources. */readonly usageLimitSources?: boolean;+ readonly usageLimitsCommand?: boolean;},) {const configScheduler = createAtomCommandScheduler();@@ -636,6 +639,7 @@ export function createServerEnvironmentAtoms<R, E>(serverConfigStateChanges(environmentId, {...(options.environmentThemes === true ? { environmentThemes: true } : {}),...(options.usageLimitSources === true ? { usageLimitSources: true } : {}),+ ...(options.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),}),).pipe(diff --git a/packages/contracts/src/providerUsageLimits.ts b/packages/contracts/src/providerUsageLimits.tsindex 0478b113d61..554e68c1b20 100644--- a/packages/contracts/src/providerUsageLimits.ts+++ b/packages/contracts/src/providerUsageLimits.ts@@ -121,3 +121,24 @@ export const ProviderConsumeResetCreditResult = Schema.Struct({outcome: ProviderConsumeResetCreditOutcome,});export type ProviderConsumeResetCreditResult = typeof ProviderConsumeResetCreditResult.Type;++/** A point-in-time view of one provider's limits, built for the /usage-limits panel. */+export const UsageLimitsReport = Schema.Struct({+ createdAt: IsoDateTime,+ accounts: Schema.Array(+ Schema.Struct({+ id: TrimmedNonEmptyString,+ driver: ProviderDriverKind,+ label: TrimmedNonEmptyString,+ plan: Schema.optional(TrimmedNonEmptyString),+ email: Schema.optional(TrimmedNonEmptyString),+ sourceLabel: Schema.optional(TrimmedNonEmptyString),+ instanceId: Schema.optional(ProviderInstanceId),+ displayName: Schema.optional(Schema.String),+ accentColor: Schema.optional(Schema.String),+ limits: ServerProviderUsageLimits,+ }),+ ),+ notices: Schema.Array(Schema.String),+});+export type UsageLimitsReport = typeof UsageLimitsReport.Type;diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 69c0ab43e89..12c653f70cc 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -1132,6 +1132,12 @@ export const WsSubscribeServerConfigRpc = Rpc.make(WS_METHODS.subscribeServerConenvironmentThemes: Schema.optional(Schema.Boolean),/** Whether this client understands `usageLimitSourcesUpdated` events. */usageLimitSources: Schema.optional(Schema.Boolean),+ /**+ * Whether this client answers `/usage-limits` itself. The server injects+ * that command into provider catalogs only for such clients; an older+ * client would send it to the provider as an ordinary prompt.+ */+ usageLimitsCommand: Schema.optional(Schema.Boolean),}),success: ServerConfigStreamEvent,error: Schema.Union([KeybindingsConfigError, ServerSettingsError, EnvironmentAuthorizationError]),diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.tsindex 83ac6906c61..6b1952199dd 100644--- a/packages/shared/src/usageLimits.test.ts+++ b/packages/shared/src/usageLimits.test.ts@@ -9,6 +9,10 @@ import {import { describe, expect, it } from "vite-plus/test";import {+ isUsageLimitsCommand,+ collectProviderUsageLimits,+ sameUsageLimitCommandCoverage,+ withUsageLimitsCommands,collectLimitSources,collectLimitsGroups,elapsedShare,@@ -304,3 +308,196 @@ describe("collectLimitSources", () => {]);});});++describe("/usage-limits", () => {+ const limits = { checkedAt: "2026-09-03T11:00:00.000Z", windows: [window] };+ const selected = provider({+ usageLimits: limits,+ auth: { status: "authenticated", email: "[email protected]" },+ });+ const sources = [+ {+ id: UsageLimitSourceId.make("hub"),+ kind: "cliproxy" as const,+ label: "Accounts",+ checkedAt: limits.checkedAt,+ accounts: [+ {+ id: "duplicate",+ driver: selected.driver,+ email: "[email protected]",+ usageLimits: limits,+ },+ { id: "oss", driver: selected.driver, plan: "Codex OSS", usageLimits: limits },+ { id: "other-provider", driver: ProviderDriverKind.make("claude"), usageLimits: limits },+ ],+ },+ ];++ it("keeps accounts and custom instances separate, filtering by driver", () => {+ const report = collectProviderUsageLimits(+ selected.instanceId,+ [+ selected,+ provider({+ instanceId: ProviderInstanceId.make("codex-work"),+ displayName: "Work",+ usageLimits: { ...limits, resetCredits: { availableCount: 2 } },+ }),+ provider({+ driver: ProviderDriverKind.make("claude"),+ instanceId: ProviderInstanceId.make("claude"),+ usageLimits: limits,+ }),+ ],+ sources,+ now,+ );+ expect(report?.createdAt).toBe("2026-09-03T12:00:00.000Z");+ expect(report?.accounts.map((account) => account.id)).toEqual([+ "codex",+ "codex-work",+ "hub:oss",+ ]);+ expect(report?.accounts[0]).toMatchObject({+ instanceId: selected.instanceId,+ email: selected.auth.email,+ });+ expect(report?.accounts[1]).toMatchObject({+ displayName: "Work",+ limits: { resetCredits: { availableCount: 2 } },+ });+ expect(report?.accounts[2]).toMatchObject({+ label: "Accounts · oss",+ sourceLabel: "CLI Proxy",+ plan: "Codex OSS",+ });+ expect(report?.notices).toEqual([]);+ });++ it("supports a source-only provider and keeps duplicates when the native probe failed", () => {+ expect(+ collectProviderUsageLimits(selected.instanceId, [provider({})], sources, now)?.accounts.map(+ (account) => account.id,+ ),+ ).toEqual(["hub:duplicate", "hub:oss"]);+ const failed = provider({ usageLimits: { ...limits, unavailable: { reason: "probeFailed" } } });+ expect(+ collectProviderUsageLimits(selected.instanceId, [failed], sources, now)?.accounts.map(+ (account) => account.id,+ ),+ ).toEqual(["codex", "hub:duplicate", "hub:oss"]);+ expect(collectProviderUsageLimits(selected.instanceId, [provider({})], [], now)).toBeNull();+ expect(+ collectProviderUsageLimits(+ selected.instanceId,+ [provider({ enabled: false, usageLimits: limits })],+ [],+ now,+ ),+ ).toBeNull();+ });++ it("surfaces source errors only for sources that carry the selected driver", () => {+ const failing = { ...sources[0]!, error: "token expired" };+ expect(+ collectProviderUsageLimits(selected.instanceId, [selected], [failing], now)?.notices,+ ).toEqual(["Accounts: token expired"]);+ const claudeOnly = { ...failing, accounts: failing.accounts.slice(2) };+ expect(+ collectProviderUsageLimits(selected.instanceId, [selected], [claudeOnly], now)?.notices,+ ).toEqual([]);+ // A read failure clears the accounts, so the error must not depend on a match.+ const unreadable = { ...failing, accounts: [] };+ expect(+ collectProviderUsageLimits(selected.instanceId, [selected], [unreadable], now)?.notices,+ ).toEqual(["Accounts: token expired"]);+ // A source-only provider still gets the report, carrying only the error.+ const sourceOnly = collectProviderUsageLimits(+ selected.instanceId,+ [provider({})],+ [unreadable],+ now,+ );+ expect(sourceOnly?.accounts).toEqual([]);+ expect(sourceOnly?.notices).toEqual(["Accounts: token expired"]);+ });++ it("advertises global and workspace commands only for providers present in Limits", () => {+ const withWorkspace = provider({+ workspaceSnapshots: [+ { cwd: "/tmp/project", checkedAt: limits.checkedAt, slashCommands: [], skills: [] },+ ],+ });+ const [supported] = withUsageLimitsCommands([withWorkspace], sources);+ expect(supported?.slashCommands.map((command) => command.name)).toEqual(["usage-limits"]);+ expect(+ supported?.workspaceSnapshots?.[0]?.slashCommands.map((command) => command.name),+ ).toEqual(["usage-limits"]);+ expect(withUsageLimitsCommands([withWorkspace], [])[0]?.slashCommands).toEqual([]);+ // A provider's own command of the same name is left alone without coverage.+ const ownCommand = provider({+ slashCommands: [{ name: "usage-limits", description: "Provider's own" }],+ });+ expect(withUsageLimitsCommands([ownCommand], [])[0]?.slashCommands).toEqual([+ { name: "usage-limits", description: "Provider's own" },+ ]);+ const unreadable = { ...sources[0]!, accounts: [], error: "token expired" };+ expect(+ withUsageLimitsCommands([withWorkspace], [unreadable])[0]?.slashCommands.map(+ (command) => command.name,+ ),+ ).toEqual(["usage-limits"]);+ expect(+ withUsageLimitsCommands([selected], [])[0]?.slashCommands.map((command) => command.name),+ ).toEqual(["usage-limits"]);+ });+});++describe("sameUsageLimitCommandCoverage", () => {+ const codexAccount = {+ id: "a",+ driver: ProviderDriverKind.make("codex"),+ usageLimits: { checkedAt: "2026-09-03T11:00:00.000Z", windows: [] },+ };+ const base = {+ id: UsageLimitSourceId.make("hub"),+ kind: "cliproxy" as const,+ label: "Accounts",+ checkedAt: "2026-09-03T11:00:00.000Z",+ };+ it("ignores quota movement but not the drivers offered the command", () => {+ const withCodex = [{ ...base, accounts: [codexAccount] }];+ const withCodexLater = [+ {+ ...base,+ accounts: [+ {+ ...codexAccount,+ usageLimits: { ...codexAccount.usageLimits, checkedAt: "2026-09-03T12:00:00.000Z" },+ },+ ],+ },+ ];+ expect(sameUsageLimitCommandCoverage(withCodex, withCodexLater)).toBe(true);+ expect(sameUsageLimitCommandCoverage(withCodex, [{ ...base, accounts: [] }])).toBe(false);+ });+ it("treats a failed read as a change in coverage, in both directions", () => {+ const empty = [{ ...base, accounts: [] }];+ const failed = [{ ...base, accounts: [], error: "token expired" }];+ expect(sameUsageLimitCommandCoverage(empty, failed)).toBe(false);+ expect(sameUsageLimitCommandCoverage(failed, empty)).toBe(false);+ expect(+ sameUsageLimitCommandCoverage(failed, [{ ...base, accounts: [], error: "still down" }]),+ ).toBe(true);+ });+});++describe("isUsageLimitsCommand", () => {+ it("recognizes only the standalone local action", () => {+ expect(isUsageLimitsCommand(" /USAGE-LIMITS\n")).toBe(true);+ expect(isUsageLimitsCommand("/usage-limits explain")).toBe(false);+ expect(isUsageLimitsCommand("Explain /usage-limits")).toBe(false);+ expect(isUsageLimitsCommand("/usage")).toBe(false);+ });+});diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.tsindex e7582b1ecc6..a792b20d6fd 100644--- a/packages/shared/src/usageLimits.ts+++ b/packages/shared/src/usageLimits.ts@@ -7,6 +7,9 @@*/import {type EnvironmentId,+ type UsageLimitsReport,+ type ProviderInstanceId,+ type ServerProviderSlashCommand,isProviderAvailable,type ServerProvider,type ServerProviderUsageLimits,@@ -15,6 +18,8 @@ import {type UsageLimitSourceSnapshots,} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+const MINUTE = 60_000;const HOUR = 60 * MINUTE;const DAY = 24 * HOUR;@@ -144,7 +149,7 @@ function accountKey(driver: ServerProvider["driver"], email: string | undefined)/** The instance's configured name, else the driver's, else its raw kind. */export function providerLimitsLabel(- provider: ServerProvider,+ provider: Pick<ServerProvider, "driver" | "displayName">,driverLabel: (driver: ServerProvider["driver"]) => string | undefined,): string {return provider.displayName?.trim() || driverLabel(provider.driver) || String(provider.driver);@@ -209,3 +214,142 @@ export function formatResetsIn(window: ServerProviderUsageWindow, now: number):if (resetsAt === null) return null;return resetsAt <= now ? "resets now" : `resets in ${formatDuration(resetsAt - now)}`;}++/** Limit commands are served by T3 from the same snapshots as Usage → Limits. */+export const USAGE_LIMITS_COMMAND = {+ name: "usage-limits",+ description: "Show this provider's usage limits",+} satisfies ServerProviderSlashCommand;++/** Handled by the client without sending a turn; anything with arguments stays an ordinary prompt. */+export function isUsageLimitsCommand(prompt: string): boolean {+ return prompt.trim().toLowerCase() === "/usage-limits";+}++/**+ * Whether Limits has anything to say about this driver. A source that failed to+ * read keeps no accounts, so its error counts for every driver rather than+ * disappearing until the next successful refresh.+ */+export function hasProviderUsageLimits(+ driver: ServerProvider["driver"],+ providers: readonly ServerProvider[],+ sources: UsageLimitSourceSnapshots,+): boolean {+ return (+ providersWithLimits(providers).some((provider) => provider.driver === driver) ||+ sources.some(+ (source) =>+ source.accounts.some((account) => account.driver === driver) ||+ (source.error !== undefined && source.accounts.length === 0),+ )+ );+}++/**+ * The drivers a set of sources would offer the command to, where a source that+ * failed to read counts for every driver. Two snapshots with the same coverage+ * need no catalog republish, however much their quotas moved.+ */+export function sameUsageLimitCommandCoverage(+ previous: UsageLimitSourceSnapshots,+ next: UsageLimitSourceSnapshots,+): boolean {+ const coverage = (sources: UsageLimitSourceSnapshots) =>+ new Set(+ sources.flatMap((source) =>+ source.error !== undefined && source.accounts.length === 0+ ? ["*"]+ : source.accounts.map((account) => String(account.driver)),+ ),+ );+ const before = coverage(previous);+ const after = coverage(next);+ return before.size === after.size && [...before].every((driver) => after.has(driver));+}++/** Advertise on workspace catalogs too, which replace the global command list. */+export function withUsageLimitsCommands(+ providers: readonly ServerProvider[],+ sources: UsageLimitSourceSnapshots,+): ServerProvider[] {+ return providers.map((provider) => {+ if (!hasProviderUsageLimits(provider.driver, providers, sources)) return provider;+ const commands = (items: readonly ServerProviderSlashCommand[]) => [+ ...items.filter((command) => command.name !== USAGE_LIMITS_COMMAND.name),+ USAGE_LIMITS_COMMAND,+ ];+ return {+ ...provider,+ slashCommands: commands(provider.slashCommands),+ ...(provider.workspaceSnapshots+ ? {+ workspaceSnapshots: provider.workspaceSnapshots.map((snapshot) => ({+ ...snapshot,+ slashCommands: commands(snapshot.slashCommands),+ })),+ }+ : {}),+ };+ });+}++/** A point-in-time report; never refreshes or guesses which pooled account serves a turn. */+export function collectProviderUsageLimits(+ instanceId: ProviderInstanceId,+ providers: readonly ServerProvider[],+ sources: UsageLimitSourceSnapshots,+ now: number,+): UsageLimitsReport | null {+ const selected = providers.find((provider) => provider.instanceId === instanceId);+ if (!selected || !hasProviderUsageLimits(selected.driver, providers, sources)) return null;+ const native = providersWithLimits(providers).filter(+ (provider) => provider.driver === selected.driver,+ );+ const nativeAccounts = new Set(+ native.flatMap((provider) => {+ const key = accountKey(provider.driver, provider.auth.email);+ return key && provider.usageLimits?.windows.length && !provider.usageLimits.unavailable+ ? [key]+ : [];+ }),+ );+ const accounts: Array<UsageLimitsReport["accounts"][number]> = [];+ const notices: string[] = [];+ for (const provider of native) {+ if (!provider.usageLimits) continue;+ accounts.push({+ id: provider.instanceId,+ driver: provider.driver,+ label: `${providerLimitsLabel(provider, () => undefined)} [${provider.instanceId}]`,+ ...(provider.auth.label ? { plan: provider.auth.label } : {}),+ instanceId: provider.instanceId,+ ...(provider.displayName ? { displayName: provider.displayName } : {}),+ ...(provider.accentColor ? { accentColor: provider.accentColor } : {}),+ ...(provider.auth.email ? { email: provider.auth.email } : {}),+ limits: provider.usageLimits,+ });+ }+ for (const source of sources) {+ const matching = source.accounts.filter((account) => account.driver === selected.driver);+ for (const account of matching) {+ const key = accountKey(account.driver, account.email);+ if (key && nativeAccounts.has(key)) continue;+ accounts.push({+ id: `${source.id}:${account.id}`,+ driver: account.driver,+ label: `${source.label} · ${account.id}`,+ sourceLabel: "CLI Proxy",+ ...(account.plan ? { plan: account.plan } : {}),+ ...(account.email ? { email: account.email } : {}),+ limits: account.usageLimits,+ });+ }+ // A source that failed to read has no accounts left to match on, so its+ // error is reported to every provider rather than silently dropped.+ if (source.error && (matching.length > 0 || source.accounts.length === 0)) {+ notices.push(`${source.label}: ${source.error}`);+ }+ }+ return { createdAt: DateTime.formatIso(DateTime.makeUnsafe(now)), accounts, notices };+}