Open History to see the last commit
1import { msg, useMessages } from "gt-react";
2import { m } from "~/i18n/messages";
3import type {
4 EnvironmentId,
5 ProviderInstanceId,
6 ServerProvider,
7 UsageLimitSourceSnapshots,
8} from "@t3tools/contracts";
9import { collectProviderUsageLimits, hasProviderUsageLimits } from "@t3tools/shared/usageLimits";
10import { useState } from "react";
11import { useStableCallback } from "../../hooks/useStableCallback";
12import { toastManager } from "../ui/toast";
13import { usageLimitsBannerItem } from "./ComposerUsageLimits";
14
15/** Keep opened data live. Retain hidden panels during reconnect; clear when quota-spending work resumes. */
16export function useUsageLimitsPanel(input: {
17 readonly environmentId: EnvironmentId;
18 readonly threadKey: string;
19 readonly panelKey: string | null;
20 readonly providerInstanceId: ProviderInstanceId | null;
21 readonly providerDriver: ServerProvider["driver"] | null;
22 readonly providers: readonly ServerProvider[];
23 readonly sources: UsageLimitSourceSnapshots;
24}) {
25 const {
26 environmentId,
27 threadKey,
28 panelKey,
29 providerInstanceId,
30 providerDriver,
31 providers,
32 sources,
33 } = input;
34 const messages = useMessages();
35 const [panel, setPanel] = useState<{
36 readonly key: string;
37 readonly threadKey: string;
38 readonly now: number;
39 } | null>(null);
40 if (panel !== null && panelKey !== null && panel.key !== panelKey) {
41 setPanel(null);
42 }
43 const report =
44 panel !== null && panelKey !== null && panel.key === panelKey && providerInstanceId !== null
45 ? collectProviderUsageLimits(providerInstanceId, providers, sources, panel.now)
46 : null;
47 const banner =
48 report !== null && panel !== null
49 ? // A fresh id per opening: the stack keeps the last dismissed id as "exiting".
50 usageLimitsBannerItem(
51 `usage-limits:${panel.key}:${panel.now}`,
52 report,
53 environmentId,
54 () => setPanel(null),
55 messages,
56 )
57 : null;
58 // Intercept /usage-limits only when Limits has selected-provider data.
59 const offered =
60 providerDriver !== null && hasProviderUsageLimits(providerDriver, providers, sources);
61
62 const open = useStableCallback(() => {
63 const now = Date.now();
64 const nextReport =
65 providerInstanceId !== null && panelKey !== null
66 ? collectProviderUsageLimits(providerInstanceId, providers, sources, now)
67 : null;
68 if (nextReport && panelKey !== null) {
69 setPanel({ key: panelKey, threadKey, now });
70 return true;
71 }
72 setPanel(null);
73 toastManager.add({
74 type: "info",
75 title: m(msg("Usage limits are unavailable for this provider")),
76 });
77 return false;
78 });
79 // Async responses may clear only their originating thread's panel.
80 const clearFor = useStableCallback((originThreadKey: string) =>
81 setPanel((current) =>
82 current !== null && current.threadKey === originThreadKey ? null : current,
83 ),
84 );
85
86 return { banner, offered, open, clearFor };
87}