Skip to content

Commit bbb3fbe

Browse files
author
filipef101
committed
fix(claude): report unauthenticated Claude instances honestly
A logged-out CLAUDE_CONFIG_DIR still initializes through the Claude Agent SDK and reports {tokenSource: "none", apiProvider: "firstParty"}, which the provider snapshot read as "authenticated". That was survivable when every install had exactly one Claude; a second provider instance points CLAUDE_CONFIG_DIR at a fresh directory that is logged out by construction, so the provider list claimed "Authenticated" while every turn died with "Not logged in - Please run /login". Restore the `claude auth status` probe that #2277 dropped, run it with the instance's own environment, and name that instance's config directory in the login hint so the user logs in the failing instance rather than the default one.
1 parent a3a8cbd commit bbb3fbe

2 files changed

Lines changed: 360 additions & 7 deletions

File tree

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

Lines changed: 145 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
getProviderOptionCurrentValue,
1919
getProviderOptionDescriptors,
2020
} from "@t3tools/shared/model";
21+
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
2122
import { resolveSpawnCommand } from "@t3tools/shared/shell";
2223
import { compareSemverVersions } from "@t3tools/shared/semver";
2324
import {
@@ -31,6 +32,7 @@ import {
3132
import {
3233
buildBooleanOptionDescriptor,
3334
buildSelectOptionDescriptor,
35+
AUTH_PROBE_TIMEOUT_MS,
3436
buildServerProvider,
3537
DEFAULT_TIMEOUT_MS,
3638
isCommandMissingCause,
@@ -40,7 +42,7 @@ import {
4042
type ServerProviderDraft,
4143
} from "../providerSnapshot.ts";
4244
import { resolveClaudeSdkExecutablePath } from "../Drivers/ClaudeExecutable.ts";
43-
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
45+
import { makeClaudeEnvironment, resolveClaudeHomePath } from "../Drivers/ClaudeHome.ts";
4446
import { discoverClaudeSkills } from "../Drivers/ClaudeSkills.ts";
4547

4648
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
@@ -798,6 +800,120 @@ const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (
798800
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
799801
});
800802

803+
/**
804+
* Shape of `claude auth status --json`. Only `loggedIn` is load-bearing; the
805+
* rest is used to label the account when the CLI knows more than the SDK's
806+
* initialization result does.
807+
*/
808+
type ClaudeAuthStatusProbe = {
809+
readonly loggedIn: boolean;
810+
readonly authMethod: string | undefined;
811+
readonly apiProvider: string | undefined;
812+
readonly email: string | undefined;
813+
readonly subscriptionType: string | undefined;
814+
};
815+
816+
function parseClaudeAuthStatus(stdout: string): ClaudeAuthStatusProbe | undefined {
817+
const trimmed = stdout.trim();
818+
if (!trimmed.startsWith("{")) return undefined;
819+
let parsed: unknown;
820+
try {
821+
parsed = JSON.parse(trimmed);
822+
} catch {
823+
return undefined;
824+
}
825+
if (typeof parsed !== "object" || parsed === null) return undefined;
826+
const record = parsed as Record<string, unknown>;
827+
if (typeof record["loggedIn"] !== "boolean") return undefined;
828+
const readString = (key: string): string | undefined =>
829+
typeof record[key] === "string" ? nonEmptyProbeString(record[key]) : undefined;
830+
return {
831+
loggedIn: record["loggedIn"],
832+
authMethod: readString("authMethod"),
833+
apiProvider: readString("apiProvider"),
834+
email: readString("email"),
835+
subscriptionType: readString("subscriptionType"),
836+
};
837+
}
838+
839+
/**
840+
* Ask the CLI itself whether this instance has credentials.
841+
*
842+
* The SDK initialization probe cannot answer this: a logged-out config
843+
* directory still initializes fine and reports
844+
* `{ tokenSource: "none", apiProvider: "firstParty" }`, which the snapshot used
845+
* to read as "authenticated". That mattered little when every install had one
846+
* Claude, but a second instance points `CLAUDE_CONFIG_DIR` at a fresh directory
847+
* that is logged out by construction — so the provider list claimed
848+
* "Authenticated" while every turn died with "Not logged in".
849+
*
850+
* Returns `undefined` when the command is missing or unparseable (older CLIs
851+
* predate `claude auth status`), which leaves the previous behaviour intact.
852+
*/
853+
const probeClaudeAuthStatus = (
854+
claudeSettings: ClaudeSettings,
855+
environment?: NodeJS.ProcessEnv,
856+
): Effect.Effect<
857+
ClaudeAuthStatusProbe | undefined,
858+
never,
859+
ChildProcessSpawner.ChildProcessSpawner | Path.Path
860+
> =>
861+
Effect.gen(function* () {
862+
// `claude auth status` emits JSON by default; the flag is not passed so the
863+
// command still works on CLI versions that predate `--json`.
864+
const probe = yield* runClaudeCommand(claudeSettings, ["auth", "status"], environment).pipe(
865+
// The auth budget, not the generic one: a first run can be slow, and a
866+
// timeout here degrades to the SDK's verdict — which is the false
867+
// "authenticated" this probe exists to correct.
868+
Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),
869+
Effect.result,
870+
);
871+
if (Result.isFailure(probe) || Option.isNone(probe.success)) return undefined;
872+
return parseClaudeAuthStatus(probe.success.value.stdout);
873+
}).pipe(
874+
// A CLI that cannot answer must never take the health check down with it:
875+
// an unknown answer keeps the previous SDK-derived verdict.
876+
Effect.catchCause(() => Effect.succeed(undefined)),
877+
);
878+
879+
/**
880+
* The exact command that logs *this* instance in. Instances with a custom
881+
* `homePath` need the `CLAUDE_CONFIG_DIR` prefix, otherwise the user logs the
882+
* default instance in again and the failing one stays broken.
883+
*/
884+
/**
885+
* Quote a path for the shell the hint will be pasted into. Home directories
886+
* routinely contain spaces ("C:\\Users\\John Doe"), and an unquoted path
887+
* produces a command that cannot run.
888+
*/
889+
function quoteForShell(value: string, platform: NodeJS.Platform): string {
890+
return platform === "win32"
891+
? `'${value.replaceAll("'", "''")}'`
892+
: `'${value.replaceAll("'", `'\\''`)}'`;
893+
}
894+
895+
/**
896+
* The exact command that logs *this* instance in. Instances with a custom
897+
* `homePath` need the `CLAUDE_CONFIG_DIR` prefix, otherwise the user logs the
898+
* default instance in again and the failing one stays broken.
899+
*/
900+
const claudeLoginHint = Effect.fn("claudeLoginHint")(function* (
901+
claudeSettings: ClaudeSettings,
902+
): Effect.fn.Return<string, never, Path.Path> {
903+
const platform = yield* HostProcessPlatform;
904+
if (claudeSettings.homePath.trim().length === 0) {
905+
return "Claude Code is not authenticated. Run `claude auth login` and try again.";
906+
}
907+
const resolvedHomePath = yield* resolveClaudeHomePath(claudeSettings);
908+
const quoted = quoteForShell(resolvedHomePath, platform);
909+
// PowerShell has no inline `VAR=value command` form.
910+
const command =
911+
platform === "win32"
912+
? `$env:CLAUDE_CONFIG_DIR=${quoted}; claude auth login`
913+
: `CLAUDE_CONFIG_DIR=${quoted} claude auth login`;
914+
return `Claude Code is not authenticated for this instance. Run \`${command}\` and try again.`;
915+
});
916+
801917
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
802918
claudeSettings: ClaudeSettings,
803919
resolveCapabilities?: (
@@ -929,6 +1045,25 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
9291045
...(capabilities?.slashCommands ?? []),
9301046
];
9311047
const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
1048+
const authStatus = yield* probeClaudeAuthStatus(claudeSettings, resolvedEnvironment);
1049+
1050+
if (authStatus?.loggedIn === false) {
1051+
return buildServerProvider({
1052+
presentation: CLAUDE_PRESENTATION,
1053+
enabled: claudeSettings.enabled,
1054+
checkedAt,
1055+
models,
1056+
slashCommands: dedupedSlashCommands,
1057+
skills,
1058+
probe: {
1059+
installed: true,
1060+
version: parsedVersion,
1061+
status: "error",
1062+
auth: { status: "unauthenticated" },
1063+
message: yield* claudeLoginHint(claudeSettings),
1064+
},
1065+
});
1066+
}
9321067

9331068
if (!capabilities) {
9341069
return buildServerProvider({
@@ -948,11 +1083,16 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
9481083
});
9491084
}
9501085

1086+
// The CLI's own auth status is the better source for account identity: with
1087+
// several instances configured, the email is what tells two Claude accounts
1088+
// apart in the provider list. Fall back to the SDK probe when the CLI is too
1089+
// old to answer.
1090+
const authEmail = authStatus?.email ?? capabilities.email;
9511091
const authMetadata =
9521092
claudeAuthMetadata({
953-
subscriptionType: capabilities.subscriptionType,
954-
authMethod: capabilities.tokenSource,
955-
}) ?? apiProviderAuthMetadata(capabilities.apiProvider);
1093+
subscriptionType: authStatus?.subscriptionType ?? capabilities.subscriptionType,
1094+
authMethod: authStatus?.authMethod ?? capabilities.tokenSource,
1095+
}) ?? apiProviderAuthMetadata(authStatus?.apiProvider ?? capabilities.apiProvider);
9561096
return buildServerProvider({
9571097
presentation: CLAUDE_PRESENTATION,
9581098
enabled: claudeSettings.enabled,
@@ -966,7 +1106,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
9661106
status: "ready",
9671107
auth: {
9681108
status: "authenticated",
969-
...(capabilities.email ? { email: capabilities.email } : {}),
1109+
...(authEmail ? { email: authEmail } : {}),
9701110
...(authMetadata ? authMetadata : {}),
9711111
},
9721112
...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),

0 commit comments

Comments
 (0)