TypeScript
fix(provider-grok): recheck Grok login once after a logged-out probe (#20358)
Victor Vogela2157eced708
diff --git a/apps/server/src/provider/GrokProvider.test.ts b/apps/server/src/provider/GrokProvider.test.tsindex 6f532f00bbb..314d8c59ebd 100644--- a/apps/server/src/provider/GrokProvider.test.ts+++ b/apps/server/src/provider/GrokProvider.test.ts@@ -402,8 +402,9 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {// A stand-in for the Grok CLI: `--version` and `models` print canned text,// and `agent stdio` execs the mock ACP agent so `initialize` returns model metadata.+ // A list of `models` outputs is served in call order, repeating the last one.const writeFakeGrokCli = (input: {- readonly modelsOutput: string;+ readonly modelsOutput: string | ReadonlyArray<string>;readonly acp: boolean;readonly updateLogPath?: string;}) =>@@ -428,7 +429,12 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {" process.exit(0);","}",'if (process.argv[2] === "models") {',- ` process.stdout.write(${JSON.stringify(input.modelsOutput)});`,+ ' const fs = await import("node:fs");',+ ` const callsPath = ${JSON.stringify(NodePath.join(dir, "models-calls"))};`,+ ' const calls = fs.existsSync(callsPath) ? fs.readFileSync(callsPath, "utf8").length : 0;',+ ' fs.appendFileSync(callsPath, ".");',+ ` const outputs = ${JSON.stringify([input.modelsOutput].flat())};`,+ " process.stdout.write(outputs[Math.min(calls, outputs.length - 1)]);"," process.exit(0);","}",'if (process.argv[2] !== "agent") process.exit(1);',@@ -498,6 +504,28 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {}),);+ // An expired access token prints the logged-out banner, then the CLI refreshes it in the+ // same run, so the next `grok models` reports the login (#14285).+ it.effect("reports authenticated when `grok models` logs in after refreshing a token", () =>+ Effect.gen(function* () {+ const snapshot = yield* Effect.scoped(+ Effect.gen(function* () {+ const grokPath = yield* writeFakeGrokCli({+ modelsOutput: [LOGGED_OUT_MODELS_OUTPUT, LOGGED_IN_MODELS_OUTPUT],+ acp: true,+ });+ return yield* checkGrokProviderStatus(+ decodeGrokSettings({ enabled: true, binaryPath: grokPath }),+ { ...process.env, XAI_API_KEY: "" },+ );+ }),+ );++ expect(snapshot.status).toBe("ready");+ expect(snapshot.auth.status).toBe("authenticated");+ }),+ );+it.effect("falls back to CLI-listed models with a warning when ACP initialize fails", () =>Effect.gen(function* () {const snapshot = yield* Effect.scoped(diff --git a/packages/provider-grok/src/server/status.ts b/packages/provider-grok/src/server/status.tsindex 58fbc59e0c1..dfa9163ec36 100644--- a/packages/provider-grok/src/server/status.ts+++ b/packages/provider-grok/src/server/status.ts@@ -304,6 +304,37 @@ const runGrokCliCommand = Effect.fn("GrokProviderStatus.runGrokCliCommand")(func);});+const probeGrokModels = Effect.fn("GrokProviderStatus.probeGrokModels")(function* (+ grokSettings: GrokSettings,+ environment: NodeJS.ProcessEnv,+) {+ const modelsResult = yield* runGrokCliCommand(grokSettings, ["models"], environment).pipe(+ Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),+ Effect.result,+ );+ // Only a clean exit is parsed. Failed invocations print help or error text that+ // must not be read as model slugs or as a login verdict.+ const modelsOutput =+ Result.isSuccess(modelsResult) &&+ Option.isSome(modelsResult.success) &&+ modelsResult.success.value.code === 0+ ? modelsResult.success.value+ : undefined;+ const cliModels: GrokModelsCliOutput = modelsOutput+ ? parseGrokModelsCliOutput(`${modelsOutput.stdout}\n${modelsOutput.stderr}`)+ : { authenticated: null, models: [] };+ if (!modelsOutput) {+ yield* Effect.logWarning("Grok CLI model listing failed or timed out.", {+ errorTag: Result.isFailure(modelsResult)+ ? modelsResult.failure._tag+ : Option.isNone(modelsResult.success)+ ? "Timeout"+ : `ExitCode${modelsResult.success.value.code}`,+ });+ }+ return cliModels;+});+const decodeAvailableCommands = Schema.decodeUnknownOption(Schema.Array(Schema.Unknown));const decodeAvailableCommand = Schema.decodeUnknownOption(Schema.Struct({@@ -388,6 +419,7 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func}const probeEnvironment = grokProbeEnvironment(environment);+ const apiKey = environment[GROK_API_KEY_ENV]?.trim();const versionResult = yield* runGrokCliCommand(grokSettings,@@ -457,32 +489,17 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func}// `grok models` reports login state and model slugs without starting the agent.- const modelsResult = yield* runGrokCliCommand(grokSettings, ["models"], probeEnvironment).pipe(- Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),- Effect.result,- );- // Only a clean exit is parsed. Failed invocations print help or error text that- // must not be read as model slugs or as a login verdict.- const modelsOutput =- Result.isSuccess(modelsResult) &&- Option.isSome(modelsResult.success) &&- modelsResult.success.value.code === 0- ? modelsResult.success.value- : undefined;- const cliModels: GrokModelsCliOutput = modelsOutput- ? parseGrokModelsCliOutput(`${modelsOutput.stdout}\n${modelsOutput.stderr}`)- : { authenticated: null, models: [] };- if (!modelsOutput) {- yield* Effect.logWarning("Grok CLI model listing failed or timed out.", {- errorTag: Result.isFailure(modelsResult)- ? modelsResult.failure._tag- : Option.isNone(modelsResult.success)- ? "Timeout"- : `ExitCode${modelsResult.success.value.code}`,- });+ let cliModels = yield* probeGrokModels(grokSettings, probeEnvironment);+ // An expired access token prints the logged-out line, then the CLI refreshes it in the same+ // process. Probing again after that process exited tells a refresh from a real logout.+ if (cliModels.authenticated === false && !apiKey) {+ const recheck = yield* probeGrokModels(grokSettings, probeEnvironment);+ if (recheck.authenticated !== null) {+ cliModels = recheck;+ }}- const auth: ServerProviderAuth = environment[GROK_API_KEY_ENV]?.trim()+ const auth: ServerProviderAuth = apiKey? { status: "authenticated", type: "api_key", label: "xAI API key" }: cliModels.authenticated === true? { status: "authenticated", type: "cached_token", label: "Grok account" }