Skip to content

Commit 8e57177

Browse files
StiensWoutclaude
andcommitted
fix(server): one failed Claude probe no longer sticks as an auth warning
One stalled capability probe replaced a ready Claude snapshot with "Could not verify Claude authentication status", cached that result for five minutes, and dropped the cause. The probe now fails with its real error and logs the tag. When a probe fails, the last good probe answers once more, so one stall keeps Claude ready with the same account and slash commands. A second failure in a row, or a failure before any good probe, shows a warning that says whether the probe timed out or the CLI failed. The cache never keeps that failure. Fixes #13635 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 0fcd5f9 commit 8e57177

4 files changed

Lines changed: 169 additions & 63 deletions

File tree

‎apps/server/src/provider/Drivers/ClaudeDriver.ts‎

Lines changed: 8 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@
1313
* @module provider/Drivers/ClaudeDriver
1414
*/
1515
import { ClaudeSettings, ProviderDriverKind } from "@t3tools/contracts";
16-
import * as Cache from "effect/Cache";
17-
import * as Duration from "effect/Duration";
1816
import * as Crypto from "effect/Crypto";
1917
import * as Effect from "effect/Effect";
2018
import * as FileSystem from "effect/FileSystem";
@@ -35,8 +33,8 @@ import * as ClaudeResetCredits from "../Layers/claudeResetCredits.ts";
3533
import * as ResetCreditCoordinator from "../Layers/resetCreditCoordinator.ts";
3634
import {
3735
checkClaudeProviderStatus,
36+
makeClaudeCapabilitiesCache,
3837
makePendingClaudeProvider,
39-
probeClaudeCapabilities,
4038
} from "../Layers/ClaudeProvider.ts";
4139
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
4240
import { resolveClaudeModelCatalog } from "../ClaudeModelCatalog.ts";
@@ -61,16 +59,11 @@ import {
6159
makeProviderSnapshotSettingsSource,
6260
type ProviderSnapshotSettings,
6361
} from "../providerUpdateSettings.ts";
64-
import {
65-
makeClaudeCapabilitiesCacheKey,
66-
makeClaudeContinuationGroupKey,
67-
resolveClaudeHomePath,
68-
} from "./ClaudeHome.ts";
62+
import { makeClaudeContinuationGroupKey, resolveClaudeHomePath } from "./ClaudeHome.ts";
6963
import { discoverClaudeSkills } from "./ClaudeSkills.ts";
7064
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
7165

7266
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
73-
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
7467

7568
function isClaudeNativeCommandPath(commandPath: string): boolean {
7669
const normalized = normalizeCommandPath(commandPath);
@@ -178,21 +171,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
178171
modelCatalog,
179172
);
180173

181-
// Per-instance capabilities cache: keyed on binary + resolved HOME so
182-
// account-specific probes never share auth metadata across instances.
183-
const capabilitiesProbeCache = yield* Cache.make({
184-
capacity: 1,
185-
timeToLive: CAPABILITIES_PROBE_TTL,
186-
lookup: () =>
187-
probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe(
188-
Effect.provideService(Path.Path, path),
189-
),
190-
});
191-
const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(
174+
const capabilities = yield* makeClaudeCapabilitiesCache(
192175
effectiveConfig,
193-
cwd,
194176
processEnv,
195-
);
177+
cwd,
178+
).pipe(Effect.provideService(Path.Path, path));
196179

197180
// Start the TTL-gated refresh without delaying provider readiness. The
198181
// next check observes a remote manifest after the background fetch lands.
@@ -202,7 +185,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
202185
Effect.flatMap((manifest) =>
203186
checkClaudeProviderStatus(
204187
effectiveConfig,
205-
() => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),
188+
() => capabilities.get,
206189
processEnv,
207190
cwd,
208191
resolveClaudeModelCatalog(manifest),
@@ -312,7 +295,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
312295
Effect.tap((outcome) =>
313296
Effect.gen(function* () {
314297
const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
315-
yield* Cache.invalidateAll(capabilitiesProbeCache);
298+
yield* capabilities.invalidate;
316299
const refreshed = yield* snapshot.refresh;
317300
const after = refreshed.usageLimits?.checkedAt;
318301
if (
@@ -343,7 +326,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
343326
accentColor,
344327
enabled,
345328
snapshot,
346-
invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache),
329+
invalidateCaches: capabilities.invalidate,
347330
snapshotForCwd,
348331
adapter,
349332
textGeneration,

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

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import * as Schema from "effect/Schema";
1616
import {
1717
buildClaudeCapabilitiesProbeQueryOptions,
1818
CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES,
19+
makeClaudeCapabilitiesCache,
1920
probeClaudeCapabilities,
2021
} from "./ClaudeProvider.ts";
2122

@@ -223,3 +224,65 @@ it.effect("preserves initialized capabilities when optional usage times out", ()
223224
assert.equal(abortSignal?.aborted, true);
224225
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
225226
);
227+
228+
it.effect("answers one failed probe with the last good account, and never caches a failure", () =>
229+
Effect.gen(function* () {
230+
let initialization: "fails" | "succeeds" = "fails";
231+
const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(
232+
() =>
233+
({
234+
initializationResult: async () => {
235+
if (initialization === "fails") {
236+
throw new Error("Claude Code process exited with code 1");
237+
}
238+
return {
239+
account: {
240+
241+
subscriptionType: "pro",
242+
tokenSource: "oauth",
243+
},
244+
commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }],
245+
};
246+
},
247+
usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async () => ({
248+
rate_limits_available: true,
249+
rate_limits: {},
250+
}),
251+
}) as unknown as ReturnType<typeof ClaudeSdk.query>,
252+
);
253+
yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
254+
const capabilities = yield* makeClaudeCapabilitiesCache(
255+
decodeClaudeSettings({ binaryPath: "claude" }),
256+
);
257+
258+
// Nothing good to fall back on yet, so the caller sees the failure.
259+
const firstFailure = yield* Effect.flip(capabilities.get);
260+
assert.equal(firstFailure._tag, "UnknownError");
261+
262+
initialization = "succeeds";
263+
const good = yield* capabilities.get;
264+
assert.equal(good.email, "[email protected]");
265+
assert.equal(good.usage?.rate_limits_available, true);
266+
yield* capabilities.get;
267+
assert.equal(query.mock.calls.length, 2);
268+
269+
initialization = "fails";
270+
yield* TestClock.adjust("5 minutes");
271+
const lastGood = yield* capabilities.get;
272+
assert.equal(lastGood.email, "[email protected]");
273+
assert.equal(lastGood.subscriptionType, "pro");
274+
assert.deepEqual(lastGood.slashCommands, [
275+
{ name: "review", description: "Review changes", input: { hint: "[path]" } },
276+
]);
277+
// Five-minute-old usage windows would be republished as current.
278+
assert.equal(lastGood.usage, undefined);
279+
yield* capabilities.get;
280+
assert.equal(query.mock.calls.length, 3);
281+
282+
// A second failure in a row reaches the caller, and the next check probes again.
283+
yield* TestClock.adjust("5 minutes");
284+
assert.equal((yield* Effect.flip(capabilities.get))._tag, "UnknownError");
285+
yield* Effect.flip(capabilities.get);
286+
assert.equal(query.mock.calls.length, 5);
287+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
288+
);

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

Lines changed: 77 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,12 @@ import {
44
type ServerProviderSlashCommand,
55
type ServerProviderResetCredits,
66
} from "@t3tools/contracts";
7+
import * as Cache from "effect/Cache";
8+
import * as Cause from "effect/Cause";
79
import * as DateTime from "effect/DateTime";
10+
import * as Duration from "effect/Duration";
811
import * as Effect from "effect/Effect";
12+
import * as Exit from "effect/Exit";
913
import * as FileSystem from "effect/FileSystem";
1014
import * as Option from "effect/Option";
1115
import * as Path from "effect/Path";
@@ -34,7 +38,7 @@ import {
3438
type ServerProviderDraft,
3539
} from "../providerSnapshot.ts";
3640
import { resolveClaudeSdkExecutablePath } from "../Drivers/ClaudeExecutable.ts";
37-
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
41+
import { makeClaudeCapabilitiesCacheKey, makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
3842
import { discoverClaudeSkills } from "../Drivers/ClaudeSkills.ts";
3943
import { makeUnavailableUsageLimits } from "../providerUsageLimits.ts";
4044
import {
@@ -168,9 +172,10 @@ function apiProviderAuthMetadata(
168172

169173
// Amazon Bedrock initializes far slower than first-party auth: the SDK boots the
170174
// Bedrock backend and runs the `awsAuthRefresh` credential hook before returning
171-
// account info. The previous 8s budget expired mid-init, so the probe returned
172-
// `undefined` and left the provider unverified and unselectable in the picker.
175+
// account info. The previous 8s budget expired mid-init, so the probe timed out
176+
// and left the provider unverified and unselectable in the picker.
173177
const CAPABILITIES_PROBE_TIMEOUT_MS = 25_000;
178+
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
174179

175180
/**
176181
* Keep workspace-scoped command discovery intact while isolating the periodic
@@ -237,9 +242,10 @@ type ClaudeCapabilitiesProbe = {
237242
readonly apiProvider: string | undefined;
238243
readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
239244
/**
240-
* Subscription windows from the SDK's `get_usage` control request, or
241-
* `undefined` when the request itself failed. Absent windows on an
242-
* otherwise successful response mean the account has none (API key).
245+
* Subscription windows from the SDK's `get_usage` control request.
246+
* `undefined` when that request failed, or when the last good probe answers
247+
* for a failed one. Absent windows on an otherwise successful response mean
248+
* the account has none (API key).
243249
*/
244250
readonly usage?: Pick<SDKControlGetUsageResponse, "rate_limits_available" | "rate_limits">;
245251
};
@@ -326,8 +332,8 @@ function waitForAbortSignal(signal: AbortSignal): Promise<void> {
326332
* account info and slash commands) but never starts an API request to
327333
* Anthropic. We read the init data and then abort the subprocess.
328334
*
329-
* This is used as a fallback when `claude auth status` does not include
330-
* subscription type information.
335+
* Fails with the timeout or SDK error. `makeClaudeCapabilitiesCache` decides
336+
* what a failed probe means for the provider snapshot.
331337
*/
332338
const probeClaudeCapabilities = (
333339
claudeSettings: ClaudeSettings,
@@ -396,11 +402,58 @@ const probeClaudeCapabilities = (
396402
if (!abort.signal.aborted) abort.abort();
397403
}),
398404
),
399-
Effect.result,
400-
Effect.map((result) => (Result.isSuccess(result) ? result.success : undefined)),
405+
// Log only the tag. SDK errors can quote the CLI's stderr.
406+
Effect.tapError((error) =>
407+
Effect.logWarning("Claude capability probe failed.", { errorTag: error._tag }),
408+
),
401409
);
402410
};
403411

412+
type ClaudeCapabilitiesProbeError = Effect.Error<ReturnType<typeof probeClaudeCapabilities>>;
413+
414+
/**
415+
* One Claude instance's capability probe, as `checkClaudeProviderStatus` reads
416+
* it. Every answer is reused for five minutes. One stalled probe must not turn
417+
* a working Claude into an auth warning, so when a probe fails, the last good
418+
* probe answers once more, without its usage windows. Those would otherwise be
419+
* republished as current. A failure with nothing to fall back on reaches the
420+
* caller and is never cached, so the next status check probes again.
421+
*/
422+
export const makeClaudeCapabilitiesCache = Effect.fn("makeClaudeCapabilitiesCache")(function* (
423+
claudeSettings: ClaudeSettings,
424+
environment?: NodeJS.ProcessEnv,
425+
cwd?: string,
426+
) {
427+
// Keyed on binary + resolved HOME so account metadata never crosses instances.
428+
const key = yield* makeClaudeCapabilitiesCacheKey(claudeSettings, cwd, environment);
429+
// Emptied when it answers for a failed probe, so a second failure in a row surfaces.
430+
const lastGood = yield* Ref.make<ClaudeCapabilitiesProbe | undefined>(undefined);
431+
const cache = yield* Cache.makeWith(
432+
(_key: string) =>
433+
probeClaudeCapabilities(claudeSettings, environment, cwd).pipe(
434+
Effect.tap((capabilities) => Ref.set(lastGood, capabilities)),
435+
Effect.catch((error) =>
436+
Effect.flatMap(Ref.getAndSet(lastGood, undefined), (last) => {
437+
if (!last) return Effect.fail(error);
438+
const { usage: _staleUsage, ...capabilities } = last;
439+
return Effect.succeed<ClaudeCapabilitiesProbe>(capabilities);
440+
}),
441+
),
442+
),
443+
{
444+
capacity: 1,
445+
timeToLive: Exit.match({
446+
onSuccess: () => CAPABILITIES_PROBE_TTL,
447+
onFailure: () => Duration.zero,
448+
}),
449+
},
450+
);
451+
return {
452+
get: Cache.get(cache, key),
453+
invalidate: Cache.invalidateAll(cache),
454+
};
455+
});
456+
404457
const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (
405458
claudeSettings: ClaudeSettings,
406459
args: ReadonlyArray<string>,
@@ -419,9 +472,9 @@ const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (
419472

420473
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
421474
claudeSettings: ClaudeSettings,
422-
resolveCapabilities?: (
475+
resolveCapabilities: (
423476
claudeSettings: ClaudeSettings,
424-
) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
477+
) => Effect.Effect<ClaudeCapabilitiesProbe, ClaudeCapabilitiesProbeError>,
425478
environment?: NodeJS.ProcessEnv,
426479
cwd?: string,
427480
modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
@@ -533,31 +586,35 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
533586
);
534587
const versionUpgradeMessage = formatClaudeVersionUpgradeMessage(modelCatalog, parsedVersion);
535588

536-
const capabilities = resolveCapabilities
537-
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
538-
: undefined;
589+
const probeResult = yield* resolveCapabilities(claudeSettings).pipe(Effect.result);
539590
const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
540-
const slashCommands = [COMPACT_SLASH_COMMAND, ...(capabilities?.slashCommands ?? [])];
541-
const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
542591

543-
if (!capabilities) {
592+
if (Result.isFailure(probeResult)) {
544593
return buildServerProvider({
545594
presentation: CLAUDE_PRESENTATION,
546595
enabled: claudeSettings.enabled,
547596
checkedAt,
548597
models,
549-
slashCommands: dedupedSlashCommands,
598+
slashCommands: [COMPACT_SLASH_COMMAND],
550599
skills,
551600
probe: {
552601
installed: true,
553602
version: parsedVersion,
554603
status: "warning",
555604
auth: { status: "unknown" },
556-
message: "Could not verify Claude authentication status from initialization result.",
605+
// A failed probe says nothing about the login, so name what failed.
606+
message: Cause.isTimeoutError(probeResult.failure)
607+
? `Timed out after ${CAPABILITIES_PROBE_TIMEOUT_MS / 1_000}s while checking Claude account status.`
608+
: "Claude Agent CLI failed while checking account status.",
557609
},
558610
});
559611
}
560612

613+
const capabilities = probeResult.success;
614+
const dedupedSlashCommands = dedupeSlashCommands([
615+
COMPACT_SLASH_COMMAND,
616+
...capabilities.slashCommands,
617+
]);
561618
const authMetadata =
562619
claudeAuthMetadata({
563620
subscriptionType: capabilities.subscriptionType,

0 commit comments

Comments
 (0)