Skip to content

Commit a2c857e

Browse files
authored
fix: model setup detects CLI logins when AI access checks time out (#125114)
* fix(system-agent): detect CLI logins on setup timeout * style(macos): format setup detection timeout * fix(macos): bound setup restart reconciliation
1 parent 1df264d commit a2c857e

18 files changed

Lines changed: 255 additions & 44 deletions

‎apps/macos/Sources/OpenClaw/OnboardingAISetup.swift‎

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ import OpenClawProtocol
1515
@MainActor
1616
@Observable
1717
final class OnboardingAISetupModel {
18+
static let setupDetectionRequestTimeoutMs = 40000
19+
1820
/// Device-code providers advertise windows up to 15 minutes. Keep transport
1921
/// alive long enough for approval plus the post-login inference probe.
2022
static let providerAuthRequestTimeoutMs: Double = 1_200_000
@@ -613,7 +615,7 @@ extension OnboardingAISetupModel {
613615
let data = try await gateway.request(
614616
method: "openclaw.setup.detect",
615617
params: [:],
616-
timeoutMs: 20000,
618+
timeoutMs: Double(Self.setupDetectionRequestTimeoutMs),
617619
ifCurrentServerLease: lease)
618620
guard await self.gateway.isCurrentServerLease(lease),
619621
self.isCurrentAttempt(context),
@@ -1026,15 +1028,11 @@ extension OnboardingAISetupModel {
10261028
before: PersistedActivationState?,
10271029
originalServerLease: GatewayConnection.ServerLease) async -> Bool
10281030
{
1029-
let clock = ContinuousClock()
1030-
let deadline = clock.now.advanced(by: .seconds(30))
1031+
let deadline = ReconciliationDeadline(timeout: .seconds(45))
10311032
var delayMs = 250
1032-
while clock.now < deadline {
1033+
while deadline.hasTimeRemaining {
10331034
guard self.isCurrentAttempt(context), !Task.isCancelled else { return false }
1034-
let leaseTimeoutMs = Self.remainingMilliseconds(
1035-
until: deadline,
1036-
clock: clock,
1037-
cappedAt: 3000)
1035+
let leaseTimeoutMs = deadline.remainingMilliseconds(cappedAt: 3000)
10381036
guard leaseTimeoutMs > 0 else { return false }
10391037
if let replacementLease = try? await gateway.acquireServerLease(
10401038
ifSameRouteAs: originalServerLease,
@@ -1046,18 +1044,12 @@ extension OnboardingAISetupModel {
10461044
activationOwner: activationOwner,
10471045
before: before,
10481046
serverLease: replacementLease,
1049-
timeoutMs: Self.remainingMilliseconds(
1050-
until: deadline,
1051-
clock: clock,
1052-
cappedAt: 10000))
1047+
deadline: deadline)
10531048
{
10541049
self.serverLease = replacementLease
10551050
return true
10561051
}
1057-
let sleepMs = Self.remainingMilliseconds(
1058-
until: deadline,
1059-
clock: clock,
1060-
cappedAt: delayMs)
1052+
let sleepMs = deadline.remainingMilliseconds(cappedAt: delayMs)
10611053
guard sleepMs > 0 else { return false }
10621054
do {
10631055
try await Task.sleep(nanoseconds: UInt64(sleepMs) * 1_000_000)
@@ -1076,9 +1068,11 @@ extension OnboardingAISetupModel {
10761068
activationOwner: OnboardingSystemAgentResumeStore.ActivationOwner,
10771069
before: PersistedActivationState?,
10781070
serverLease: GatewayConnection.ServerLease,
1079-
timeoutMs: Int) async -> Bool
1071+
deadline: ReconciliationDeadline) async -> Bool
10801072
{
1081-
guard timeoutMs > 0,
1073+
let detectTimeoutMs = deadline.remainingMilliseconds(
1074+
cappedAt: Self.setupDetectionRequestTimeoutMs)
1075+
guard detectTimeoutMs > 0,
10821076
self.isCurrentAttempt(context),
10831077
!Task.isCancelled,
10841078
OnboardingSystemAgentResumeStore.isOwned(
@@ -1091,7 +1085,7 @@ extension OnboardingAISetupModel {
10911085
guard let detectData = try? await gateway.request(
10921086
method: "openclaw.setup.detect",
10931087
params: [:],
1094-
timeoutMs: Double(timeoutMs),
1088+
timeoutMs: Double(detectTimeoutMs),
10951089
ifCurrentServerLease: serverLease),
10961090
await gateway.isCurrentServerLease(serverLease),
10971091
isCurrentAttempt(context),
@@ -1102,10 +1096,13 @@ extension OnboardingAISetupModel {
11021096
before: before,
11031097
after: detection.persistedActivationState)
11041098
else { return false }
1099+
let verifyTimeoutMs = deadline.remainingMilliseconds(
1100+
cappedAt: Self.setupDetectionRequestTimeoutMs)
1101+
guard verifyTimeoutMs > 0 else { return false }
11051102
guard let verifyData = try? await gateway.request(
11061103
method: "openclaw.setup.verify",
11071104
params: [:],
1108-
timeoutMs: Double(timeoutMs),
1105+
timeoutMs: Double(verifyTimeoutMs),
11091106
ifCurrentServerLease: serverLease),
11101107
await gateway.isCurrentServerLease(serverLease),
11111108
isCurrentAttempt(context),
@@ -1421,7 +1418,7 @@ extension OnboardingAISetupModel {
14211418
guard let data = try? await gateway.request(
14221419
method: "openclaw.setup.detect",
14231420
params: [:],
1424-
timeoutMs: 10000,
1421+
timeoutMs: Double(Self.setupDetectionRequestTimeoutMs),
14251422
ifCurrentServerLease: lease),
14261423
token == attemptToken,
14271424
let result = try? JSONDecoder().decode(DetectResult.self, from: data),

‎apps/macos/Sources/OpenClaw/OnboardingAISetupSupport.swift‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,28 @@ extension OnboardingAISetupModel {
2424
let activationOwner: OnboardingSystemAgentResumeStore.ActivationOwner?
2525
}
2626

27+
@MainActor
28+
struct ReconciliationDeadline {
29+
private let clock: ContinuousClock
30+
private let deadline: ContinuousClock.Instant
31+
32+
init(timeout: ContinuousClock.Duration, clock: ContinuousClock = .init()) {
33+
self.clock = clock
34+
self.deadline = clock.now.advanced(by: timeout)
35+
}
36+
37+
var hasTimeRemaining: Bool {
38+
self.clock.now < self.deadline
39+
}
40+
41+
func remainingMilliseconds(cappedAt capMs: Int) -> Int {
42+
OnboardingAISetupModel.remainingMilliseconds(
43+
until: self.deadline,
44+
clock: self.clock,
45+
cappedAt: capMs)
46+
}
47+
}
48+
2749
struct DetectResult: Decodable {
2850
struct DetectedCandidate: Decodable {
2951
let brandId: String?

‎apps/macos/Tests/OpenClawIPCTests/OnboardingAISetupTests.swift‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,16 @@ struct OnboardingAISetupTests {
814814
#expect(OnboardingAISetupModel.providerAuthRequestTimeoutMs > 15 * 60 * 1000)
815815
}
816816

817+
@Test func `reconciliation deadline recomputes each RPC budget`() async throws {
818+
let deadline = OnboardingAISetupModel.ReconciliationDeadline(timeout: .seconds(2))
819+
let detectionBudget = deadline.remainingMilliseconds(cappedAt: 10000)
820+
821+
try await Task.sleep(nanoseconds: 50_000_000)
822+
823+
let verificationBudget = deadline.remainingMilliseconds(cappedAt: 10000)
824+
#expect(verificationBudget < detectionBudget)
825+
}
826+
817827
@Test func `prepare choices use wire presentation and hide usable local models`() {
818828
let candidates = [
819829
OnboardingAISetupModel.Candidate(

‎docs/cli/gateway.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,9 @@ openclaw gateway call logs.tail --params '{"limit": 200}'
512512
Machine-readable JSON output.
513513
</ParamField>
514514

515+
`openclaw.setup.detect` uses a 40-second default so the Gateway can finish its
516+
bounded AI-access scan. An explicit `--timeout` still takes precedence.
517+
515518
<Note>
516519
`--params` must be valid JSON, and each method validates its own param shape (extra/misnamed fields are rejected). Use `--port` for a custom-port local Gateway; explicit `--url` targets still require explicit credentials.
517520
</Note>

‎src/agents/cli-credentials.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -176,11 +176,11 @@ function parseClaudeCliOauthCredential(claudeOauth: unknown): ClaudeCliCredentia
176176
};
177177
}
178178

179-
function resolveCodexHomePath(codexHome?: string) {
180-
const configured = codexHome ?? process.env.CODEX_HOME;
179+
export function resolveCodexCliHomePath(codexHome?: string, env: NodeJS.ProcessEnv = process.env) {
180+
const configured = codexHome ?? env.CODEX_HOME;
181181
// External CLI state belongs to the OS user, not OpenClaw's relocatable
182182
// home. Otherwise an isolated OPENCLAW_HOME hides an already logged-in CLI.
183-
const home = resolveOsHomeRelativePath(configured || "~/.codex");
183+
const home = resolveOsHomeRelativePath(configured || "~/.codex", { env });
184184
try {
185185
return fs.realpathSync.native(home);
186186
} catch {
@@ -274,7 +274,7 @@ function resolveCodexKeychainParams(options?: {
274274
return {
275275
platform: options?.platform ?? process.platform,
276276
execSyncImpl: options?.execSync ?? execSync,
277-
codexHome: resolveCodexHomePath(options?.codexHome),
277+
codexHome: resolveCodexCliHomePath(options?.codexHome),
278278
};
279279
}
280280

@@ -703,7 +703,7 @@ function readCodexCliCredentials(options?: {
703703
}
704704
}
705705

706-
const authPath = path.join(resolveCodexHomePath(options?.codexHome), CODEX_CLI_AUTH_FILENAME);
706+
const authPath = path.join(resolveCodexCliHomePath(options?.codexHome), CODEX_CLI_AUTH_FILENAME);
707707
const raw = loadJsonFileThroughSymlink(authPath);
708708
if (!raw || typeof raw !== "object") {
709709
return null;
@@ -727,7 +727,7 @@ export function readCodexCliCredentialsCached(options?: {
727727
}): CodexCliCredential | null {
728728
const platform = options?.platform ?? process.platform;
729729
const ttlMs = options?.ttlMs ?? 0;
730-
const authPath = path.join(resolveCodexHomePath(options?.codexHome), CODEX_CLI_AUTH_FILENAME);
730+
const authPath = path.join(resolveCodexCliHomePath(options?.codexHome), CODEX_CLI_AUTH_FILENAME);
731731
const keychainIntent =
732732
platform === "darwin" && options?.allowKeychainPrompt !== false ? "keychain" : "file";
733733
return readCachedCliCredential({

‎src/cli/gateway-cli/register.option-collisions.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,15 @@ describe("gateway register option collisions", () => {
215215
expect(params).toEqual({});
216216
},
217217
},
218+
{
219+
name: "gives setup detection enough transport grace",
220+
argv: ["gateway", "call", "openclaw.setup.detect", "--json"],
221+
assert: () => {
222+
const [method, opts] = firstGatewayCall();
223+
expect(method).toBe("openclaw.setup.detect");
224+
expect((opts as { timeout?: string } | undefined)?.timeout).toBe("40000");
225+
},
226+
},
218227
{
219228
name: "projects gateway call --port into local config",
220229
argv: ["gateway", "call", "health", "--port", "19084", "--json"],

‎src/cli/gateway-cli/register.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ const daemonStatusGatherModuleLoader = createLazyImportLoader(
5858
);
5959

6060
const DEFAULT_GATEWAY_RPC_TIMEOUT_MS = 10_000;
61+
const SETUP_INFERENCE_DETECT_RPC_TIMEOUT_MS = 40_000;
6162
type GatewayCliDependencies = {
6263
loadGatewayHealthModule?: typeof loadGatewayHealthModule;
6364
loadHealthStyleModule?: typeof loadHealthStyleModule;
@@ -579,7 +580,14 @@ export function registerGatewayCli(program: Command, deps: GatewayCliDependencie
579580
.action(async (method, opts, command) => {
580581
await runGatewayCommand(
581582
async () => {
582-
const rpcOpts = await resolveGatewayRpcOptionsWithLocalPort(opts, command);
583+
// Setup detection owns a 30s worker deadline; its transport must
584+
// leave enough grace for the Gateway to return the typed outcome.
585+
const callOpts =
586+
method === "openclaw.setup.detect" &&
587+
command.getOptionValueSource("timeout") === "default"
588+
? { ...opts, timeout: String(SETUP_INFERENCE_DETECT_RPC_TIMEOUT_MS) }
589+
: opts;
590+
const rpcOpts = await resolveGatewayRpcOptionsWithLocalPort(callOpts, command);
583591
const params = parseGatewayCallParams(String(opts.params ?? "{}"));
584592
const result = await callGatewayCli(method, rpcOpts, params);
585593
if (rpcOpts.json) {
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it } from "vitest";
5+
import { detectAmbientInferenceBackends } from "./onboard-inference-ambient.js";
6+
7+
const tempHomes = new Set<string>();
8+
9+
async function createTempHome(): Promise<string> {
10+
const home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-ambient-")));
11+
tempHomes.add(home);
12+
return home;
13+
}
14+
15+
async function writeCredential(home: string, relativePath: string, value: unknown): Promise<void> {
16+
const filePath = path.join(home, relativePath);
17+
await fs.mkdir(path.dirname(filePath), { recursive: true });
18+
await fs.writeFile(filePath, JSON.stringify(value), "utf8");
19+
}
20+
21+
afterEach(async () => {
22+
await Promise.all([...tempHomes].map((home) => fs.rm(home, { recursive: true, force: true })));
23+
tempHomes.clear();
24+
});
25+
26+
describe("detectAmbientInferenceBackends", () => {
27+
it.each([
28+
{
29+
kind: "claude-cli" as const,
30+
relativePath: ".claude/.credentials.json",
31+
credential: {
32+
claudeAiOauth: {
33+
accessToken: "claude-access",
34+
refreshToken: "claude-refresh",
35+
expiresAt: Date.now() + 60_000,
36+
},
37+
},
38+
},
39+
{
40+
kind: "codex-cli" as const,
41+
relativePath: ".codex/auth.json",
42+
credential: {
43+
auth_mode: "chatgpt",
44+
tokens: { access_token: "codex-access", refresh_token: "codex-refresh" },
45+
},
46+
},
47+
])("returns a verified $kind candidate only for readable file credentials", async (fixture) => {
48+
const home = await createTempHome();
49+
expect(detectAmbientInferenceBackends({ HOME: home })).toEqual([]);
50+
51+
await writeCredential(home, fixture.relativePath, fixture.credential);
52+
53+
expect(detectAmbientInferenceBackends({ HOME: home })).toEqual([
54+
expect.objectContaining({ kind: fixture.kind, credentials: true }),
55+
]);
56+
});
57+
});

‎src/commands/onboard-inference-ambient.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
import os from "node:os";
2+
import {
3+
readClaudeCliCredentialsCached,
4+
readCodexCliCredentialsCached,
5+
resolveCodexCliHomePath,
6+
} from "../agents/cli-credentials.js";
7+
import { resolveOsHomeDir } from "../infra/home-dir.js";
8+
19
export const OPENAI_API_DEFAULT_MODEL_REF = "openai/gpt-5.6-sol";
210
export const ANTHROPIC_API_DEFAULT_MODEL_REF = "anthropic/claude-opus-5";
311
export const CLAUDE_CLI_DEFAULT_MODEL_REF = "claude-cli/claude-opus-5";
@@ -48,5 +56,39 @@ export function detectAmbientInferenceBackends(
4856
credentials: true,
4957
});
5058
}
59+
// An injected environment is authoritative; isolated detection must not
60+
// fall through to another process user's home or prompt a keychain.
61+
const homedir = env === process.env ? os.homedir : () => "";
62+
const homeDir = resolveOsHomeDir(env, homedir);
63+
const claudeCredential = homeDir
64+
? readClaudeCliCredentialsCached({ homeDir, allowKeychainPrompt: false, ttlMs: 0 })
65+
: null;
66+
if (claudeCredential && claudeCredential.type !== "api_key_helper") {
67+
candidates.push({
68+
kind: "claude-cli",
69+
modelRef: CLAUDE_CLI_DEFAULT_MODEL_REF,
70+
label: "Claude Code",
71+
detail: "credential file found",
72+
credentials: true,
73+
});
74+
}
75+
try {
76+
const codexHome =
77+
homeDir || env.CODEX_HOME?.trim() ? resolveCodexCliHomePath(undefined, env) : undefined;
78+
if (
79+
codexHome &&
80+
readCodexCliCredentialsCached({ codexHome, allowKeychainPrompt: false, ttlMs: 0 })
81+
) {
82+
candidates.push({
83+
kind: "codex-cli",
84+
modelRef: CODEX_APP_SERVER_DEFAULT_MODEL_REF,
85+
label: "Codex",
86+
detail: "credential file found",
87+
credentials: true,
88+
});
89+
}
90+
} catch {
91+
// No usable OS home means there is no prompt-free file credential to report.
92+
}
5193
return candidates;
5294
}

‎src/commands/onboard-inference.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,9 @@ export async function detectInferenceBackends(
262262
credentials: true,
263263
});
264264
}
265-
const envCandidates = detectAmbientInferenceBackends(env);
265+
const envCandidates = detectAmbientInferenceBackends(env).filter(
266+
(candidate) => candidate.kind === "openai-api-key" || candidate.kind === "anthropic-api-key",
267+
);
266268

267269
const [claudeProbe, codexProbe, geminiProbe] = await Promise.all([
268270
probe("claude"),

0 commit comments

Comments
 (0)