Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usage.ts

138 lines4.7 KB

1import type {
2 EnvironmentId,
3 ServerProvider,
4 UsageModelFilter,
5 UsageSummary,
6 UsageSummaryInput,
7} from "@t3tools/contracts";
8import * as Schema from "effect/Schema";
9import type { AtomRegistry } from "effect/reactivity";
10​
11import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
12import type { createEnvironmentPresentationAtoms } from "./presentation.ts";
13import { executeAtomQuery, runAtomCommand, squashAtomCommandFailure } from "./runtime.ts";
14import type { createServerEnvironmentAtoms } from "./server.ts";
15​
16const isEnvironmentRpcUnavailable = Schema.is(EnvironmentRpcUnavailableError);
17​
18export function needsCursorKeychainAccess(
19 summary: UsageSummary | null,
20 providers: readonly ServerProvider[] | null,
21): boolean {
22 return (
23 summary?.sources.some((source) => source.action === "enableCursorKeychain") === true &&
24 providers?.some((provider) => provider.driver === "cursor" && provider.status === "ready") ===
25 true
26 );
28​
29/**
30 * Any environment reading a Cursor account already reports that account's
31 * history from every machine, so the prompt only adds duplicates there.
32 */
33export function cursorKeychainAccessEnvironments<
34 E extends { readonly summary: UsageSummary | null; readonly needsCursorKeychainAccess: boolean },
35>(environments: readonly E[]): readonly E[] {
36 const hasCursorAccount = environments.some((environment) =>
37 environment.summary?.sources.some(
38 (source) =>
39 source.fingerprint.provider === "cursor" && source.fingerprint.hostId === "cursor.com",
40 ),
41 );
42 return hasCursorAccount
43 ? []
44 : environments.filter((environment) => environment.needsCursorKeychainAccess);
46​
47/** The Usage tab asks each environment with that environment's configured model filter. */
48export function usageSummaryInput(
49 input: UsageSummaryInput,
50 modelFilter: UsageModelFilter | undefined,
51): UsageSummaryInput {
52 return modelFilter === undefined ? input : { ...input, modelFilter };
54​
55const limitsRefreshAfter = new Map<EnvironmentId, number>();
56const limitsRefreshes = new Map<EnvironmentId, Promise<unknown>>();
57​
58export async function refreshUsageLimits<A>(
59 environmentId: EnvironmentId,
60 refresh: () => Promise<A>,
61 automatic = false,
62 afterPending = false,
63): Promise<A | undefined> {
64 const pending = limitsRefreshes.get(environmentId);
65 if (pending !== undefined) {
66 if (afterPending) {
67 try {
68 await pending;
69 } catch {}
70 return refreshUsageLimits(environmentId, refresh, false, true);
71 }
72 return automatic ? undefined : ((await pending) as A);
73 }
74 const refreshAfter = limitsRefreshAfter.get(environmentId) ?? 0;
75 // @effect-diagnostics-next-line globalDate:off
76 if (automatic && Date.now() < refreshAfter) return;
77 const current = Promise.resolve()
78 .then(refresh)
79 .finally(() => {
80 limitsRefreshes.delete(environmentId);
81 // @effect-diagnostics-next-line globalDate:off
82 limitsRefreshAfter.set(environmentId, Date.now() + 5 * 60_000);
83 });
84 limitsRefreshes.set(environmentId, current);
85 return await current;
87​
88export async function refreshUsage({
89 registry,
90 server,
91 presentations,
92 environmentIds,
93 input,
94}: {
95 registry: AtomRegistry.AtomRegistry;
96 server: Pick<
97 ReturnType<typeof createServerEnvironmentAtoms>,
98 "usageSummary" | "refreshUsageRates" | "usageModelFilterAtom"
99 >;
100 presentations: Pick<ReturnType<typeof createEnvironmentPresentationAtoms>, "presentationAtom">;
101 environmentIds: readonly EnvironmentId[];
102 input: UsageSummaryInput;
103}): Promise<void> {
104 await Promise.all(
105 environmentIds.map(async (environmentId) => {
106 const query = server.usageSummary({
107 environmentId,
108 input: usageSummaryInput(input, registry.get(server.usageModelFilterAtom(environmentId))),
109 });
110 const presentation = presentations.presentationAtom(environmentId);
111 const controller = new AbortController();
112 const abortWhenDisconnected = () => {
113 if (registry.get(presentation)?.connection.phase !== "connected") controller.abort();
114 };
115 const unsubscribe = registry.subscribe(presentation, abortWhenDisconnected);
116 abortWhenDisconnected();
117 try {
118 const ratesResult = await runAtomCommand(
119 registry,
120 server.refreshUsageRates,
121 { environmentId, input: {} },
122 { reportFailure: false },
123 );
124 const sessionUnavailable =
125 ratesResult._tag === "Failure" &&
126 isEnvironmentRpcUnavailable(squashAtomCommandFailure(ratesResult));
127 registry.refresh(query);
128 if (sessionUnavailable || controller.signal.aborted) return;
129 await executeAtomQuery(registry, query, {
130 reportFailure: false,
131 signal: controller.signal,
132 });
133 } finally {
134 unsubscribe();
135 }
136 }),
137 );