fix: address usage limits and merge settlement regressions (#9784)

This commit is contained in:
maria authored and GitHub committed 2026-09-04 17:46:12 -04:00
1 parent 91c66ac43d
commit 98a29cbaa1
9 files changed
+308 -93

No files matched your search

+4 -1
View File
@@ -30,7 +30,10 @@ type ConnectionLayerSource =
| typeof mobileBackgroundActivityObserverLayer
| typeof mobileBackgroundActivityReporterLayer;
const providedClientConnectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
const providedClientConnectionLayer = Layer.merge(
Connection.layerWithOptions({ usageLimitSources: true }),
snapshotLoaderLayer,
).pipe(
Layer.provideMerge(
Layer.mergeAll(
runtimeContextLayer,
@@ -1,4 +1,9 @@
// @effect-diagnostics nodeBuiltinImport:off - cleanup uses Node's retrying rm, which the FileSystem service does not expose.
import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk";
import { vi } from "vite-plus/test";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as TestClock from "effect/testing/TestClock";
import { ClaudeSettings } from "@t3tools/contracts";
import * as NodeFSP from "node:fs/promises";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -14,6 +19,8 @@ import {
probeClaudeCapabilities,
} from "./ClaudeProvider.ts";
vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
it("isolates Claude capability probes without dropping workspace setting sources", () => {
@@ -181,3 +188,38 @@ it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => {
}).pipe(Effect.scoped),
);
});
it.effect("preserves initialized capabilities when optional usage times out", () =>
Effect.gen(function* () {
const usageStarted = yield* Deferred.make<void>();
let abortSignal: AbortSignal | undefined;
const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
abortSignal = options?.abortController?.signal;
return {
initializationResult: async () => ({
account: { email: "[email protected]", subscriptionType: "pro", tokenSource: "oauth" },
commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }],
}),
usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: () => {
Deferred.doneUnsafe(usageStarted, Effect.void);
return new Promise(() => {});
},
} as ReturnType<typeof ClaudeSdk.query>;
});
yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
const probe = yield* probeClaudeCapabilities(
decodeClaudeSettings({ binaryPath: "claude" }),
).pipe(Effect.forkChild);
yield* Deferred.await(usageStarted);
yield* TestClock.adjust("4 seconds");
const capabilities = yield* Fiber.join(probe);
assert.equal(capabilities?.email, "[email protected]");
assert.equal(capabilities?.subscriptionType, "pro");
assert.equal(capabilities?.tokenSource, "oauth");
assert.deepEqual(capabilities?.slashCommands, [
{ name: "review", description: "Review changes", input: { hint: "[path]" } },
]);
assert.equal(capabilities?.usage, undefined);
assert.equal(abortSignal?.aborted, true);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
@@ -355,44 +355,47 @@ const probeClaudeCapabilities = (
}),
});
const init = await q.initializationResult();
// Usage is a second control round trip on the same process; a failure
// there must not cost the slash commands and account we already have.
const usage = await q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET().then(
(response) => ({
rate_limits_available: response.rate_limits_available,
rate_limits: response.rate_limits,
}),
() => undefined,
);
const account = init.account as
| {
readonly email?: string;
readonly subscriptionType?: string;
readonly tokenSource?: string;
readonly apiProvider?: string;
}
| undefined;
return {
email: account?.email,
subscriptionType: account?.subscriptionType,
tokenSource: account?.tokenSource,
apiProvider: account?.apiProvider,
slashCommands: parseClaudeInitializationCommands(init.commands),
...(usage ? { usage } : {}),
} satisfies ClaudeCapabilitiesProbe;
return { q, init };
});
}).pipe(
Effect.timeout(CAPABILITIES_PROBE_TIMEOUT_MS),
Effect.flatMap(({ q, init }) =>
Effect.gen(function* () {
// Usage has its own deadline so a slow optional request cannot discard initialization.
const usageResult = yield* Effect.tryPromise(() =>
q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(),
).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result);
const usage = Result.isSuccess(usageResult)
? {
rate_limits_available: usageResult.success.rate_limits_available,
rate_limits: usageResult.success.rate_limits,
}
: undefined;
const account = init.account as
| {
readonly email?: string;
readonly subscriptionType?: string;
readonly tokenSource?: string;
readonly apiProvider?: string;
}
| undefined;
return {
email: account?.email,
subscriptionType: account?.subscriptionType,
tokenSource: account?.tokenSource,
apiProvider: account?.apiProvider,
slashCommands: parseClaudeInitializationCommands(init.commands),
...(usage ? { usage } : {}),
} satisfies ClaudeCapabilitiesProbe;
}),
),
Effect.ensuring(
Effect.sync(() => {
if (!abort.signal.aborted) abort.abort();
}),
),
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
Effect.result,
Effect.map((result) => {
if (Result.isFailure(result)) return undefined;
return Option.isSome(result.success) ? result.success.value : undefined;
}),
Effect.map((result) => (Result.isSuccess(result) ? result.success : undefined)),
);
};
@@ -1005,10 +1005,12 @@ it.effect("refuses an action the host never claimed it could run", () =>
}),
);
it.effect("publishes a successful merge for immediate settlement", () =>
it.effect("publishes a merge for immediate settlement only after host confirmation", () =>
Effect.scoped(
Effect.gen(function* () {
const mergedAt = "2026-09-03T02:00:00.000Z";
let state: "open" | "merged" = "open";
let confirmationFails = false;
const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
const service = yield* makeService({
projects: [
@@ -1016,7 +1018,17 @@ it.effect("publishes a successful merge for immediate settlement", () =>
],
providers: [
fakeProvider("github", {
runAction: () => TestClock.setTime(Date.parse(mergedAt)),
getChangeRequestSummary: () =>
confirmationFails
? Effect.fail(
new PullRequestProviderError({
provider: "github",
operation: "getChangeRequestSummary",
reason: "failed",
detail: "HTTP 504",
}),
)
: Effect.succeed({ ...changeRequest(1, mergedAt), state }),
}),
],
});
@@ -1025,6 +1037,13 @@ it.effect("publishes a successful merge for immediate settlement", () =>
Effect.forkChild({ startImmediately: true }),
);
// Queueing succeeds while the host still reports an open PR.
yield* service.runAction({ ...reference, action: "merge" });
confirmationFails = true;
yield* service.runAction({ ...reference, action: "merge" });
confirmationFails = false;
state = "merged";
yield* TestClock.setTime(Date.parse(mergedAt));
yield* service.runAction({
...reference,
repository: " ACME/WEB ",
@@ -1965,6 +1984,7 @@ it.effect("refuses a merge strategy the host does not offer", () =>
review: FULL_REVIEW,
reviewers: FULL_REVIEWERS,
},
getChangeRequestSummary: () => Effect.succeed(changeRequest(1, "2026-07-02T00:00:00Z")),
runAction: (input) => {
ranWith = input.mergeMethod ?? "merge";
return Effect.void;
@@ -2432,6 +2432,15 @@ export const make = Effect.gen(function* () {
bumpRefEpoch({ ...input, repository });
listingsEpoch = ++epochCounter;
if (input.action === "merge") {
// A successful merge action can merely enqueue the PR or enable auto-merge.
const confirmed = yield* summaryUncached({ ...input, repository }).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to confirm pull request merge", { error }).pipe(
Effect.as(null),
),
),
);
if (confirmed?.state !== "merged") return;
yield* PubSub.publish(mergedPullRequests, {
projectId: input.projectId,
repository,
+7 -7
View File
@@ -1,3 +1,4 @@
import { useAtomValue } from "@effect/atom-react";
import type { UsageProviderKind } from "@t3tools/contracts";
import { CheckIcon, RefreshCwIcon, XIcon } from "lucide-react";
import { useMemo, useState } from "react";
@@ -6,7 +7,7 @@ import type { DailyTotals, HourlyTotals } from "@t3tools/shared/usageMerge";
import { isElectron } from "../../env";
import { cn } from "../../lib/utils";
import { usePrimaryEnvironmentId } from "../../state/environments";
import { environmentPresentations } from "../../state/presentation";
import { serverEnvironment } from "../../state/server";
import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -69,7 +70,7 @@ export function UsagePage() {
const { days: windowDays, window } = windowSelection;
const isPast24Hours = windowDays === 1;
const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
const primaryEnvironmentId = usePrimaryEnvironmentId();
const presentations = useAtomValue(environmentPresentations.presentationsAtom);
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
reportFailure: false,
});
@@ -115,12 +116,11 @@ export function UsagePage() {
});
};
const refreshWindow = () => {
// On Limits the button re-probes every provider (and usage-limit source)
// on the primary environment; the live snapshots then flow in over the
// config stream, so nothing else needs to move.
if (showingLimits) {
if (primaryEnvironmentId) {
void refreshProviders({ environmentId: primaryEnvironmentId, input: {} });
for (const [environmentId, presentation] of presentations) {
if (presentation.connection.phase === "connected" && presentation.serverConfig !== null) {
void refreshProviders({ environmentId, input: {} });
}
}
return;
}
+1 -1
View File
@@ -31,7 +31,7 @@ type ConnectionLayerSource =
| typeof backgroundActivityReporterLayer;
const providedClientConnectionLayer = Layer.merge(
Connection.layerWithOptions({ environmentThemes: true }),
Connection.layerWithOptions({ environmentThemes: true, usageLimitSources: true }),
snapshotLoaderLayer,
).pipe(
Layer.provideMerge(
+168 -49
View File
@@ -8,6 +8,7 @@ import {
ServerConfigStreamEvent,
type ServerConfigStreamEvent as ServerConfigStreamEventType,
WS_METHODS,
UsageLimitSourceId,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
@@ -174,6 +175,29 @@ const THEME_SERVER_CONFIG: ServerConfigType = {
},
};
const ENCODED_THEME_SERVER_CONFIG = encodeServerConfig(THEME_SERVER_CONFIG);
const SOURCE_SERVER_CONFIG: ServerConfigType = {
...THEME_SERVER_CONFIG,
environment: {
...THEME_SERVER_CONFIG.environment,
capabilities: { ...THEME_SERVER_CONFIG.environment.capabilities, usageLimitSources: true },
},
};
const SOURCE_EVENT: ServerConfigStreamEventType = {
version: 1,
type: "usageLimitSourcesUpdated",
payload: {
sources: [
{
id: UsageLimitSourceId.make("proxy"),
kind: "cliproxy",
label: "Proxy",
checkedAt: "2026-09-04T00:00:00Z",
accounts: [],
},
],
},
};
const LEGACY_SERVER_CONFIG = {
...ENCODED_SERVER_CONFIG,
environment: {
@@ -402,52 +426,133 @@ describe("RpcSessionFactory", () => {
),
);
it.effect("shares only a config subscription with the same theme opt-in", () =>
for (const options of [
{ environmentThemes: true },
{ usageLimitSources: true },
{ environmentThemes: true, usageLimitSources: true },
]) {
it.effect(
`shares only a config subscription with the same opt-ins: ${JSON.stringify(options)}`,
() =>
Effect.scoped(
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory(options);
const session = yield* factory.connect(PREPARED);
const readyFiber = yield* Effect.forkChild(session.ready);
const socket = yield* awaitSocket(sockets);
socket.open();
yield* completeInitialConfig(socket, ENCODED_THEME_SERVER_CONFIG, options);
yield* Fiber.join(readyFiber);
const shared = yield* session.subscribeServerConfig(options).pipe(Stream.runHead);
expect(shared).toMatchObject({ _tag: "Some", value: { type: "snapshot" } });
expect(
socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest),
).toHaveLength(1);
const fallbackFiber = yield* session
.subscribeServerConfig({})
.pipe(Stream.runHead, Effect.forkChild);
const fallbackRequest = yield* awaitRequest(socket, 1);
expect(fallbackRequest).toMatchObject({
tag: WS_METHODS.subscribeServerConfig,
payload: {},
});
socket.serverMessage(
encodeJson({
_tag: "Chunk",
requestId: fallbackRequest.id,
values: [
{
version: 1,
type: "snapshot",
config: ENCODED_THEME_SERVER_CONFIG,
},
],
}),
);
expect(yield* Fiber.join(fallbackFiber)).toMatchObject({
_tag: "Some",
value: { type: "snapshot" },
});
}),
),
);
}
it.effect.each([
{ usageLimitSources: true },
{ environmentThemes: true, usageLimitSources: true },
])("replays usage sources, removal, and capability downgrade with %j", (options) =>
Effect.scoped(
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory({ environmentThemes: true });
const { factory, sockets } = yield* makeFactory(options);
const session = yield* factory.connect(PREPARED);
const readyFiber = yield* Effect.forkChild(session.ready);
const ready = yield* Effect.forkChild(session.ready);
const socket = yield* awaitSocket(sockets);
socket.open();
yield* completeInitialConfig(socket, ENCODED_THEME_SERVER_CONFIG, {
environmentThemes: true,
});
yield* Fiber.join(readyFiber);
const shared = yield* session
.subscribeServerConfig({ environmentThemes: true })
.pipe(Stream.runHead);
expect(shared).toMatchObject({ _tag: "Some", value: { type: "snapshot" } });
yield* completeInitialConfig(socket, encodeServerConfig(SOURCE_SERVER_CONFIG), options);
yield* Fiber.join(ready);
const observed = yield* Queue.unbounded<ServerConfigStreamEventType>();
yield* session.subscribeServerConfig(options).pipe(
Stream.runForEach((event) => Queue.offer(observed, event)),
Effect.forkChild,
);
expect((yield* Queue.take(observed)).type).toBe("snapshot");
const themes: ServerConfigStreamEventType[] = options.environmentThemes
? [{ version: 1, type: "environmentThemesUpdated", payload: { themes: [] } }]
: [];
for (const event of themes) {
yield* publishConfigEvents(socket, [event]);
expect(yield* Queue.take(observed)).toEqual(event);
}
const events: ServerConfigStreamEventType[] = [
SOURCE_EVENT,
{ version: 1, type: "usageLimitSourcesUpdated", payload: { sources: [] } },
SOURCE_EVENT,
{ version: 1, type: "snapshot", config: THEME_SERVER_CONFIG },
];
for (const event of events) {
yield* publishConfigEvents(socket, [event]);
expect(yield* Queue.take(observed)).toEqual(event);
const started = yield* Deferred.make<void>();
const replay = yield* session.subscribeServerConfig(options).pipe(
Stream.tap(() => Deferred.succeed(started, undefined)),
Stream.takeUntil((item) => item.type === "keybindingsUpdated"),
Stream.runCollect,
Effect.forkChild,
);
yield* Deferred.await(started);
// A live end marker makes a missing or stale replay event fail without a timeout.
const marker: ServerConfigStreamEventType = {
version: 1,
type: "keybindingsUpdated",
payload: { keybindings: [], issues: [] },
};
yield* publishConfigEvents(socket, [marker]);
expect(yield* Queue.take(observed)).toEqual(marker);
const replayed = Array.from(yield* Fiber.join(replay));
expect(replayed.slice(1)).toEqual([
...themes,
...(event.type === "snapshot" ? [] : [event]),
marker,
]);
let projection = applyServerConfigProjection(Option.none(), {
version: 1,
type: "snapshot",
config: SOURCE_SERVER_CONFIG,
});
projection = applyServerConfigProjection(projection, SOURCE_EVENT);
for (const item of replayed) projection = applyServerConfigProjection(projection, item);
expect(Option.getOrThrow(projection).config.usageLimitSources).toEqual(
event.type === "usageLimitSourcesUpdated" && event.payload.sources.length > 0
? event.payload.sources
: undefined,
);
}
expect(socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest)).toHaveLength(
1,
);
const fallbackFiber = yield* session
.subscribeServerConfig({})
.pipe(Stream.runHead, Effect.forkChild);
const fallbackRequest = yield* awaitRequest(socket, 1);
expect(fallbackRequest).toMatchObject({
tag: WS_METHODS.subscribeServerConfig,
payload: {},
});
socket.serverMessage(
encodeJson({
_tag: "Chunk",
requestId: fallbackRequest.id,
values: [
{
version: 1,
type: "snapshot",
config: ENCODED_THEME_SERVER_CONFIG,
},
],
}),
);
expect(yield* Fiber.join(fallbackFiber)).toMatchObject({
_tag: "Some",
value: { type: "snapshot" },
});
}),
),
);
@@ -546,16 +651,20 @@ describe("RpcSessionFactory", () => {
),
);
it.effect("recovers a slow subscriber after it misses theme deletion", () =>
it.effect("recovers a slow subscriber after it misses theme and usage-source deletion", () =>
Effect.scoped(
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory({ environmentThemes: true });
const { factory, sockets } = yield* makeFactory({
environmentThemes: true,
usageLimitSources: true,
});
const session = yield* factory.connect(PREPARED);
const readyFiber = yield* Effect.forkChild(session.ready);
const socket = yield* awaitSocket(sockets);
socket.open();
yield* completeInitialConfig(socket, ENCODED_THEME_SERVER_CONFIG, {
yield* completeInitialConfig(socket, encodeServerConfig(SOURCE_SERVER_CONFIG), {
environmentThemes: true,
usageLimitSources: true,
});
yield* Fiber.join(readyFiber);
@@ -563,7 +672,7 @@ describe("RpcSessionFactory", () => {
const releaseSlowSubscriber = yield* Deferred.make<void>();
let firstEvent = true;
const slowSubscriber = yield* session
.subscribeServerConfig({ environmentThemes: true })
.subscribeServerConfig({ environmentThemes: true, usageLimitSources: true })
.pipe(
Stream.mapEffect((event) => {
if (!firstEvent) return Effect.succeed(event);
@@ -573,7 +682,7 @@ describe("RpcSessionFactory", () => {
Effect.as(event),
);
}),
Stream.take(3),
Stream.take(4),
Stream.runCollect,
Effect.forkChild,
);
@@ -612,12 +721,18 @@ describe("RpcSessionFactory", () => {
type: "settingsUpdated",
payload: { settings: DEFAULT_SERVER_SETTINGS },
}));
const allEvents = [...themeEvents, ...settingsEvents];
const sourceEvents: ServerConfigStreamEventType[] = [
SOURCE_EVENT,
{ version: 1, type: "usageLimitSourcesUpdated", payload: { sources: [] } },
];
const allEvents = [...themeEvents, ...sourceEvents, ...settingsEvents];
const observedByFastSubscriber = yield* Queue.unbounded<ServerConfigStreamEventType>();
yield* session.subscribeServerConfig({ environmentThemes: true }).pipe(
Stream.runForEach((event) => Queue.offer(observedByFastSubscriber, event)),
Effect.forkChild,
);
yield* session
.subscribeServerConfig({ environmentThemes: true, usageLimitSources: true })
.pipe(
Stream.runForEach((event) => Queue.offer(observedByFastSubscriber, event)),
Effect.forkChild,
);
expect((yield* Queue.take(observedByFastSubscriber)).type).toBe("snapshot");
for (const event of allEvents) {
yield* publishConfigEvents(socket, [event]);
@@ -630,19 +745,23 @@ describe("RpcSessionFactory", () => {
"snapshot",
"snapshot",
"environmentThemesUpdated",
"usageLimitSourcesUpdated",
]);
expect(recovered[2]).toMatchObject({ payload: { themes: [] } });
expect(recovered[3]).toMatchObject({ payload: { sources: [] } });
let projection = applyServerConfigProjection(Option.none(), {
version: 1,
type: "snapshot",
config: THEME_SERVER_CONFIG,
config: SOURCE_SERVER_CONFIG,
});
projection = applyServerConfigProjection(projection, themeEvents[0]!);
projection = applyServerConfigProjection(projection, SOURCE_EVENT);
for (const event of recovered.slice(1)) {
projection = applyServerConfigProjection(projection, event);
}
expect(Option.getOrThrow(projection).config.environmentThemes).toBeUndefined();
expect(Option.getOrThrow(projection).config.usageLimitSources).toBeUndefined();
}),
),
);
+22 -3
View File
@@ -54,6 +54,7 @@ export interface RpcSession {
export interface RpcSessionOptions {
readonly environmentThemes?: boolean;
readonly usageLimitSources?: boolean;
}
export class RpcSessionFactory extends Context.Service<
@@ -83,11 +84,16 @@ type EnvironmentThemesUpdatedEvent = Extract<
ServerConfigStreamEvent,
{ readonly type: "environmentThemesUpdated" }
>;
type UsageLimitSourcesUpdatedEvent = Extract<
ServerConfigStreamEvent,
{ readonly type: "usageLimitSourcesUpdated" }
>;
interface ServerConfigReplayState {
readonly projection: ServerConfigProjection;
readonly revision: number;
readonly themesEvent: EnvironmentThemesUpdatedEvent | undefined;
readonly sourcesEvent: UsageLimitSourcesUpdatedEvent | undefined;
}
interface BufferedServerConfigEvent {
@@ -104,7 +110,11 @@ function serverConfigReplayEvents(
type: "snapshot" as const,
config: withoutEnvironmentThemes(state.projection.config),
};
return state.themesEvent === undefined ? [snapshot] : [snapshot, state.themesEvent];
return [
snapshot,
...(state.themesEvent === undefined ? [] : [state.themesEvent]),
...(state.sourcesEvent === undefined ? [] : [state.sourcesEvent]),
];
}
function mapSessionRpcError(
@@ -134,8 +144,10 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* (
options: RpcSessionOptions = {},
) {
const webSocketConstructor = yield* Socket.WebSocketConstructor;
const serverConfigInput: ServerConfigSubscriptionInput =
options.environmentThemes === true ? { environmentThemes: true } : {};
const serverConfigInput: ServerConfigSubscriptionInput = {
...(options.environmentThemes === true ? { environmentThemes: true } : {}),
...(options.usageLimitSources === true ? { usageLimitSources: true } : {}),
};
const connect = Effect.fnUntraced(function* (connection: PreparedConnection) {
yield* Effect.annotateCurrentSpan({
@@ -218,6 +230,13 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* (
event.config.environment.capabilities.environmentThemes !== true
? undefined
: Option.getOrUndefined(current)?.themesEvent,
sourcesEvent:
event.type === "usageLimitSourcesUpdated"
? event
: event.type === "snapshot" &&
event.config.environment.capabilities.usageLimitSources !== true
? undefined
: Option.getOrUndefined(current)?.sourcesEvent,
} satisfies ServerConfigReplayState;
return [
Option.some({ event, replay: next, revision: next.revision }),