Skip to content

Commit d5318fb

Browse files
committed
fix(shared): merge OpenCode Go limits by credential
- Fingerprint Go API keys to identify matching accounts across environments - Keep email-based account matching as the preferred identity
1 parent d2c9281 commit d5318fb

5 files changed

Lines changed: 128 additions & 32 deletions

File tree

‎apps/server/src/provider/Layers/OpenCodeProvider.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as NodeAssert from "node:assert/strict";
2+
import * as NodeCrypto from "node:crypto";
23

34
import * as NodeServices from "@effect/platform-node/NodeServices";
45
import { it } from "@effect/vitest";
@@ -71,6 +72,10 @@ it.effect("reads Go limits with the instance's XDG credentials and preserves res
7172
Effect.provide(NodeServices.layer),
7273
);
7374
NodeAssert.equal(limits.unavailable, undefined);
75+
NodeAssert.equal(
76+
limits.credentialFingerprint,
77+
NodeCrypto.createHash("sha256").update("opencode-go\0instance-key").digest("hex"),
78+
);
7479
NodeAssert.deepEqual(
7580
limits.windows.map(({ kind, usedPercent, resetsAt: reset }) => ({
7681
kind,
@@ -139,6 +144,7 @@ it.effect("keeps Go entitlement absence distinct from failed or malformed usage
139144
Effect.provide(NodeServices.layer),
140145
);
141146
NodeAssert.equal(limits.unavailable?.reason, reason);
147+
NodeAssert.equal(limits.credentialFingerprint, undefined);
142148
NodeAssert.deepEqual(limits.windows, []);
143149
}
144150
}),

‎apps/server/src/provider/Layers/openCodeUsageLimits.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as NodeOS from "node:os";
2+
import * as NodeCrypto from "node:crypto";
23

34
import type { ServerProviderUsageWindow } from "@t3tools/contracts";
45
import * as DateTime from "effect/DateTime";
@@ -95,7 +96,15 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(
9596
resetsAt: DateTime.formatIso(body.usage.monthly.resetsAt),
9697
},
9798
];
98-
return makeUsageLimits({ checkedAt, windows });
99+
return {
100+
...makeUsageLimits({ checkedAt, windows }),
101+
// Go's usage response has no account ID, so identical keys are the only
102+
// cross-environment identity we can establish from this probe.
103+
credentialFingerprint: NodeCrypto.createHash("sha256")
104+
.update("opencode-go\0")
105+
.update(apiKey)
106+
.digest("hex"),
107+
};
99108
}).pipe(
100109
Effect.timeout("5 seconds"),
101110
Effect.orElseSucceed(() =>

‎packages/contracts/src/providerUsageLimits.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ export type ServerProviderResetCredits = typeof ServerProviderResetCredits.Type;
5050
export const ServerProviderUsageLimits = Schema.Struct({
5151
checkedAt: IsoDateTime,
5252
windows: ForwardCompatibleArray(ServerProviderUsageWindow),
53+
/** Opaque credential identity when the provider does not report an account. */
54+
credentialFingerprint: Schema.optional(TrimmedNonEmptyString),
5355
resetCredits: Schema.optional(ServerProviderResetCredits),
5456
unavailable: Schema.optional(
5557
Schema.Struct({

‎packages/shared/src/usageLimits.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,74 @@ describe("pools", () => {
202202
expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(55);
203203
});
204204

205+
it("merges OpenCode Go limits from machines with the same API key", () => {
206+
const go = provider({
207+
driver: ProviderDriverKind.make("opencode"),
208+
instanceId: ProviderInstanceId.make("opencode"),
209+
auth: { status: "authenticated" },
210+
usageLimits: {
211+
checkedAt,
212+
credentialFingerprint: "shared-go-key",
213+
windows: [{ ...window, id: "go_rolling", usedPercent: 3 }],
214+
},
215+
});
216+
const input = new Map([
217+
[EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [go] } }],
218+
[
219+
EnvironmentId.make("env-b"),
220+
{
221+
entry: { target: { label: "Desktop" } },
222+
serverConfig: {
223+
providers: [
224+
{
225+
...go,
226+
usageLimits: {
227+
...go.usageLimits!,
228+
checkedAt: "2026-09-03T11:30:00.000Z",
229+
windows: [{ ...window, id: "go_rolling", usedPercent: 4 }],
230+
},
231+
},
232+
],
233+
},
234+
},
235+
],
236+
]);
237+
const accounts = collectLimitAccounts(input);
238+
expect(accounts).toHaveLength(1);
239+
expect(accounts[0]?.environments).toEqual([
240+
{ environmentId: "env-a", label: "Laptop" },
241+
{ environmentId: "env-b", label: "Desktop" },
242+
]);
243+
expect(collectLimitPools(accounts, now)[0]?.windows[0]?.members).toHaveLength(1);
244+
expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(4);
245+
246+
const differentKey = {
247+
...go,
248+
usageLimits: { ...go.usageLimits!, credentialFingerprint: "other-go-key" },
249+
};
250+
input.set(EnvironmentId.make("env-b"), {
251+
entry: { target: { label: "Desktop" } },
252+
serverConfig: { providers: [differentKey] },
253+
});
254+
expect(collectLimitAccounts(input)).toHaveLength(2);
255+
256+
input.set(EnvironmentId.make("env-a"), {
257+
...laptop,
258+
serverConfig: {
259+
providers: [{ ...go, auth: { status: "authenticated", email: "[email protected]" } }],
260+
},
261+
});
262+
input.set(EnvironmentId.make("env-b"), {
263+
entry: { target: { label: "Desktop" } },
264+
serverConfig: {
265+
providers: [
266+
{ ...differentKey, auth: { status: "authenticated", email: "[email protected]" } },
267+
],
268+
},
269+
});
270+
expect(collectLimitAccounts(input)).toHaveLength(1);
271+
});
272+
205273
it("takes windows from a fresher hub read but credits and redeem from the native instance", () => {
206274
const native = provider({
207275
driver: claude,

‎packages/shared/src/usageLimits.ts‎

Lines changed: 42 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -79,16 +79,23 @@ export type LimitPresentations = ReadonlyMap<
7979
}
8080
>;
8181

82-
function accountKey(driver: ServerProvider["driver"], email: string | undefined): string | null {
82+
function accountKey(
83+
driver: ServerProvider["driver"],
84+
email: string | undefined,
85+
limits?: ServerProviderUsageLimits,
86+
): string | null {
8387
const normalizedEmail = email?.trim().toLowerCase();
84-
return normalizedEmail ? `${driver}:${normalizedEmail}` : null;
88+
if (normalizedEmail) return `${driver}:${normalizedEmail}`;
89+
return limits?.credentialFingerprint
90+
? `${driver}:credential:${limits.credentialFingerprint}`
91+
: null;
8592
}
8693

8794
/**
8895
* One subscription account as the pooled views see it, whichever way it was
89-
* reported. The same email signed in natively on two environments, or reported
90-
* by a hub as well as natively, is one account: its quota is one bucket, so
91-
* counting it twice would misstate what is left.
96+
* reported. Matching emails or credentials across environments name
97+
* one account. Its quota is one bucket, so counting it twice would misstate
98+
* what is left.
9299
*/
93100
export interface LimitAccount {
94101
readonly key: string;
@@ -186,7 +193,7 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl
186193
for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
187194
if (!provider.usageLimits || limitsNotice(provider.usageLimits) !== null) continue;
188195
merge(
189-
accountKey(provider.driver, provider.auth.email) ??
196+
accountKey(provider.driver, provider.auth.email, provider.usageLimits) ??
190197
`${environmentId}:${provider.instanceId}`,
191198
{
192199
key: `${environmentId}:${provider.instanceId}`,
@@ -214,27 +221,31 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl
214221
: source.label;
215222
for (const account of source.accounts) {
216223
if (limitsNotice(account.usageLimits) !== null) continue;
217-
merge(accountKey(account.driver, account.email) ?? `${source.id}:${account.id}`, {
218-
key: `${source.id}:${account.id}`,
219-
driver: account.driver,
220-
displayName: account.email ? null : account.id.replace(/\.json$/i, ""),
221-
email: account.email,
222-
plan: account.plan,
223-
accentColor: undefined,
224-
environments: [],
225-
sourceLabel,
226-
redeem: account.usageLimits.resetCredits?.nextCreditId
227-
? {
228-
environmentId,
229-
input: {
230-
sourceId: source.id,
231-
accountId: account.id,
232-
creditId: account.usageLimits.resetCredits.nextCreditId,
233-
},
234-
}
235-
: null,
236-
limits: account.usageLimits,
237-
});
224+
merge(
225+
accountKey(account.driver, account.email, account.usageLimits) ??
226+
`${source.id}:${account.id}`,
227+
{
228+
key: `${source.id}:${account.id}`,
229+
driver: account.driver,
230+
displayName: account.email ? null : account.id.replace(/\.json$/i, ""),
231+
email: account.email,
232+
plan: account.plan,
233+
accentColor: undefined,
234+
environments: [],
235+
sourceLabel,
236+
redeem: account.usageLimits.resetCredits?.nextCreditId
237+
? {
238+
environmentId,
239+
input: {
240+
sourceId: source.id,
241+
accountId: account.id,
242+
creditId: account.usageLimits.resetCredits.nextCreditId,
243+
},
244+
}
245+
: null,
246+
limits: account.usageLimits,
247+
},
248+
);
238249
}
239250
}
240251
}
@@ -590,7 +601,7 @@ export function collectProviderUsageLimits(
590601
);
591602
const nativeAccounts = new Set(
592603
native.flatMap((provider) => {
593-
const key = accountKey(provider.driver, provider.auth.email);
604+
const key = accountKey(provider.driver, provider.auth.email, provider.usageLimits);
594605
return key && provider.usageLimits?.windows.length && !provider.usageLimits.unavailable
595606
? [key]
596607
: [];
@@ -600,13 +611,13 @@ export function collectProviderUsageLimits(
600611
const notices: string[] = [];
601612
for (const provider of native) {
602613
if (!provider.usageLimits) continue;
603-
const key = accountKey(provider.driver, provider.auth.email);
614+
const key = accountKey(provider.driver, provider.auth.email, provider.usageLimits);
604615
const hubCredits = sources
605616
.flatMap((source) => source.accounts.map((account) => ({ source, account })))
606617
.filter(
607618
({ account }) =>
608619
key !== null &&
609-
accountKey(account.driver, account.email) === key &&
620+
accountKey(account.driver, account.email, account.usageLimits) === key &&
610621
account.usageLimits.resetCredits &&
611622
!limitsNotice(account.usageLimits),
612623
)
@@ -653,7 +664,7 @@ export function collectProviderUsageLimits(
653664
for (const source of sources) {
654665
const matching = source.accounts.filter((account) => account.driver === selected.driver);
655666
for (const account of matching) {
656-
const key = accountKey(account.driver, account.email);
667+
const key = accountKey(account.driver, account.email, account.usageLimits);
657668
if (key && nativeAccounts.has(key)) continue;
658669
accounts.push({
659670
id: `${source.id}:${account.id}`,

0 commit comments

Comments
 (0)