TypeScript
refactor(web): move the /usage-limits panel state out of ChatView (#20296)
Julius Marminge65de56ef902b
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex c94d10c5c6c..98a96142310 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -34,13 +34,9 @@ import {latestRootProviderFailure,} from "@t3tools/shared/orchestrationV2ThreadError";import type { UsageLimitSourceSnapshots } from "@t3tools/contracts";-import {- collectProviderUsageLimits,- hasProviderUsageLimits,- isUsageLimitsCommand,-} from "@t3tools/shared/usageLimits";+import { isUsageLimitsCommand } from "@t3tools/shared/usageLimits";import { feedbackBannerItem } from "./chat/ComposerFeedback";-import { usageLimitsBannerItem } from "./chat/ComposerUsageLimits";+import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel";import { getTerminalLabel } from "@t3tools/shared/terminalLabels";import * as Schema from "effect/Schema";import {@@ -2637,16 +2633,8 @@ export default function ChatView(props: ChatViewProps) {hasActionableProposedPlan: hasActionableProposedPlan(activeProposedPlan),hasComposerAttachments: composerHasAttachments,});- // 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 =activeProviderInstanceId === null || (isServerThread && activeThread === undefined)? null@@ -2656,77 +2644,20 @@ export default function ChatView(props: ChatViewProps) {activeThread?.latestRun?.runId ?? "",activePendingApproval?.requestId ?? activePendingUserInput?.requestId ?? "",].join(":");- 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- ? 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);- const openUsageLimits = () => {- 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;- };- const openUsageLimitsStable = useStableCallback(openUsageLimits);- // Responses can resolve after navigating away; only the originating thread's panel clears.- const clearUsageLimitsFor = (threadKey: string) =>- setUsageLimitsPanel((current) =>- current !== null && current.threadKey === threadKey ? null : current,- );+ const {+ banner: usageLimitsBanner,+ offered: usageLimitsOffered,+ open: openUsageLimits,+ clearFor: clearUsageLimitsFor,+ } = useUsageLimitsPanel({+ environmentId,+ threadKey: routeThreadKey,+ panelKey: usageLimitsKey,+ providerInstanceId: activeProviderInstanceId,+ providerDriver: activeProviderStatus?.driver ?? null,+ providers: providerStatuses,+ sources: serverConfig?.usageLimitSources ?? EMPTY_USAGE_LIMIT_SOURCES,+ });const {beginLocalDispatch,resetLocalDispatch,@@ -10036,7 +9967,7 @@ export default function ChatView(props: ChatViewProps) {usageLimitsOffered &&usageLimitsKey !== null &&!composerHasNonPromptContent- ? openUsageLimitsStable+ ? openUsageLimits: undefined}environmentUnavailable={activeEnvironmentUnavailableState}diff --git a/apps/web/src/components/chat/useUsageLimitsPanel.ts b/apps/web/src/components/chat/useUsageLimitsPanel.tsnew file mode 100644index 00000000000..e0b0071c711--- /dev/null+++ b/apps/web/src/components/chat/useUsageLimitsPanel.ts@@ -0,0 +1,90 @@+import type {+ EnvironmentId,+ ProviderInstanceId,+ ServerProvider,+ UsageLimitSourceSnapshots,+} from "@t3tools/contracts";+import { collectProviderUsageLimits, hasProviderUsageLimits } from "@t3tools/shared/usageLimits";+import { useState } from "react";+import { useStableCallback } from "../../hooks/useStableCallback";+import { toastManager } from "../ui/toast";+import { usageLimitsBannerItem } from "./ComposerUsageLimits";++/**+ * The open /usage-limits panel for one 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.+ *+ * `panelKey` names that thread, model and turn. It is 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.+ */+export function useUsageLimitsPanel(input: {+ readonly environmentId: EnvironmentId;+ readonly threadKey: string;+ readonly panelKey: string | null;+ readonly providerInstanceId: ProviderInstanceId | null;+ readonly providerDriver: ServerProvider["driver"] | null;+ readonly providers: readonly ServerProvider[];+ readonly sources: UsageLimitSourceSnapshots;+}) {+ const {+ environmentId,+ threadKey,+ panelKey,+ providerInstanceId,+ providerDriver,+ providers,+ sources,+ } = input;+ const [panel, setPanel] = useState<{+ readonly key: string;+ readonly threadKey: string;+ readonly now: number;+ } | null>(null);+ // Drop the snapshot as soon as the thread or model changes so it cannot resurface stale.+ if (panel !== null && panelKey !== null && panel.key !== panelKey) {+ setPanel(null);+ }+ const report =+ panel !== null && panelKey !== null && panel.key === panelKey && providerInstanceId !== null+ ? collectProviderUsageLimits(providerInstanceId, providers, sources, panel.now)+ : null;+ const banner =+ report !== null && panel !== null+ ? // A fresh id per opening: the stack keeps the last dismissed id as "exiting".+ usageLimitsBannerItem(`usage-limits:${panel.key}:${panel.now}`, report, environmentId, () =>+ setPanel(null),+ )+ : null;+ // 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 offered =+ providerDriver !== null && hasProviderUsageLimits(providerDriver, providers, sources);++ // Answered locally from the last Limits snapshot; the agent never sees it.+ const open = useStableCallback(() => {+ const now = Date.now();+ const nextReport =+ providerInstanceId !== null && panelKey !== null+ ? collectProviderUsageLimits(providerInstanceId, providers, sources, now)+ : null;+ if (nextReport && panelKey !== null) {+ setPanel({ key: panelKey, threadKey, now });+ return true;+ }+ setPanel(null);+ toastManager.add({ type: "info", title: "Usage limits are unavailable for this provider" });+ return false;+ });+ // Responses can resolve after navigating away; only the originating thread's panel clears.+ const clearFor = useStableCallback((originThreadKey: string) =>+ setPanel((current) =>+ current !== null && current.threadKey === originThreadKey ? null : current,+ ),+ );++ return { banner, offered, open, clearFor };+}diff --git a/vite.config.ts b/vite.config.tsindex 81cae3d0461..5cbfc4cb1ad 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -328,6 +328,7 @@ export default defineConfig({files: ["apps/web/src/components/PersistentThreadTerminals.tsx","apps/web/src/components/chat/usePendingThreadRequests.ts",+ "apps/web/src/components/chat/useUsageLimitsPanel.ts","apps/web/src/components/terminal/**",],rules: {