Open History to see the last commit
1import type {
2 EnvironmentId,
3 ServerProvider,
4 UsageSummary,
5 UsageSummaryInput,
6} from "@t3tools/contracts";
7import * as Schema from "effect/Schema";
8import type { AtomRegistry } from "effect/unstable/reactivity";
9
10import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
11import type { createEnvironmentPresentationAtoms } from "./presentation.ts";
12import { executeAtomQuery, runAtomCommand, squashAtomCommandFailure } from "./runtime.ts";
13import type { createServerEnvironmentAtoms } from "./server.ts";
14
15const isEnvironmentRpcUnavailable = Schema.is(EnvironmentRpcUnavailableError);
16
17/** Offer the Cursor Keychain prompt only where a working Cursor provider could use it. */
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 );
27}
28
29const limitsRefreshAfter = new Map<EnvironmentId, number>();
30const limitsRefreshes = new Map<EnvironmentId, Promise<unknown>>();
31
32export async function refreshUsageLimits<A>(
33 environmentId: EnvironmentId,
34 refresh: () => Promise<A>,
35 automatic = false,
36 afterPending = false,
37): Promise<A | undefined> {
38 const pending = limitsRefreshes.get(environmentId);
39 if (pending !== undefined) {
40 if (afterPending) {
41 try {
42 await pending;
43 } catch {
44 // The new check still needs to run if the earlier one failed.
45 }
46 return refreshUsageLimits(environmentId, refresh, false, true);
47 }
48 // Manual refresh waits for the current check; automatic refresh does not repeat it.
49 return automatic ? undefined : ((await pending) as A);
50 }
51 const refreshAfter = limitsRefreshAfter.get(environmentId) ?? 0;
52 // @effect-diagnostics-next-line globalDate:off
53 if (automatic && Date.now() < refreshAfter) return;
54 const current = Promise.resolve()
55 .then(refresh)
56 .finally(() => {
57 limitsRefreshes.delete(environmentId);
58 // @effect-diagnostics-next-line globalDate:off
59 limitsRefreshAfter.set(environmentId, Date.now() + 5 * 60_000);
60 });
61 limitsRefreshes.set(environmentId, current);
62 return await current;
63}
64
65/** Refresh pricing, then await each selected environment's rescan while it remains connected. */
66export async function refreshUsage({
67 registry,
68 server,
69 presentations,
70 environmentIds,
71 input,
72}: {
73 registry: AtomRegistry.AtomRegistry;
74 server: Pick<
75 ReturnType<typeof createServerEnvironmentAtoms>,
76 "usageSummary" | "refreshUsageRates"
77 >;
78 presentations: Pick<ReturnType<typeof createEnvironmentPresentationAtoms>, "presentationAtom">;
79 environmentIds: readonly EnvironmentId[];
80 input: UsageSummaryInput;
81}): Promise<void> {
82 await Promise.all(
83 environmentIds.map(async (environmentId) => {
84 const query = server.usageSummary({ environmentId, input });
85 const presentation = presentations.presentationAtom(environmentId);
86 const controller = new AbortController();
87 const abortWhenDisconnected = () => {
88 if (registry.get(presentation)?.connection.phase !== "connected") controller.abort();
89 };
90 const unsubscribe = registry.subscribe(presentation, abortWhenDisconnected);
91 abortWhenDisconnected();
92 try {
93 const ratesResult = await runAtomCommand(
94 registry,
95 server.refreshUsageRates,
96 { environmentId, input: {} },
97 { reportFailure: false },
98 );
99 const sessionUnavailable =
100 ratesResult._tag === "Failure" &&
101 isEnvironmentRpcUnavailable(squashAtomCommandFailure(ratesResult));
102 // Invalidate even on failure so reconnects cannot reuse the old summary.
103 registry.refresh(query);
104 if (sessionUnavailable || controller.signal.aborted) return;
105 await executeAtomQuery(registry, query, {
106 reportFailure: false,
107 signal: controller.signal,
108 });
109 } finally {
110 unsubscribe();
111 }
112 }),
113 );
114}