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