Repository navigation
fix(macos): authenticate app-hosted first run and speed up setup - #169403
Conversation
Persist missing local token auth before starting the app-owned Gateway, preserving explicit credentials and invalid config. Use one directory clone with a copy fallback for bundled runtime seeds. Release-note context: fresh macOS app installs can authenticate to their child Gateway and seed the bundled runtime faster. Focused sandboxed Swift tests cover auth eligibility, config persistence and clone fallback.
Clear the existing channel connect-failure delay before local startup health probes. Preserve auth pauses, protocol mismatch handling, watchdog behavior and remote reconnect policy. Release-note context: local Gateway startup can connect promptly once ready instead of waiting behind boot-time exponential backoff. Deterministic regression covers queued and active delays; focused channel and network recovery tests pass.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. What this changesThis PR initializes missing app-hosted Gateway credentials and speeds up runtime preparation and readiness checks. Example: A fresh 2026.10.1 Mac installation selects “On this Mac” with gateway.mode=local and no credentials.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 4 items remain Keep this PR open: current main still needs the shipped macOS first-run repair, and the prior credential-preservation finding is resolved. Priority: P0 Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherThe macOS process manager prepares the bundled runtime, initializes profile authentication, launches its child Gateway, and checks readiness through the shared WebSocket client. flowchart TD
A[Mac onboarding] --> B[Gateway process manager]
B --> C[Bundled runtime preparation]
B --> D[Credential initialization]
D --> E[Profile configuration]
C --> F[Child Gateway]
E --> F
B --> G[WebSocket readiness client]
G --> F
Technical reviewBest possible solution: Recover local onboarding automatically through the existing startup and config owners while preserving configured credentials and service ownership. Do we have a high-confidence way to reproduce the issue? The report identifies release 2026.10.1 and an unauthorized handshake, while current-main hosting omits credential persistence and Gateway startup generates a runtime-only token unavailable to the native credential resolver; no runtime reproduction was executed during this read-only review. Is this the best way to solve the issue? Initializing genuinely absent credentials before app-owned launch addresses the cause without changing Gateway startup authorization, and the clone and readiness changes target the reported setup delays through existing owners. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 9605dd68cb6d. Merge-risk optionsMaintainer options:
Provenance checked
TestingProof path: in-process harness. SecurityNeeds attention: The correction preserves identified credential sources, but durable shared authentication requires final-effect authorization evidence. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +232, Tests +320, Docs +17. Total +569 across 11 files. Added test files: 2. View PR surface stats
LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (3 earlier review cycles)
Reviewed October 11, 2026, 7:26 PM ET / 23:26 UTC (Revision 4). |
|
Accepted; conservative preservation is implemented in 0ec6e59. It preserves Denied-client/rotation: the app initializes only when credentials are absent from the supported authored sources; it never rewrites or rotates an existing token/password, so existing clients are unaffected. Upgrade compatibility: service installs and configured credentials are untouched. Affected 2026.10.1 installs with |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Accepted; implemented in aba2d89. The credential-source table now covers every source identified in the Gateway startup trace: authored local/remote credentials and SecretRefs, includes, child/config env, trusted profile/default dotenv files, and login-shell import. The guard preserves unreadable or unresolved sources and discovery-path controls, and persists only when none can supply a credential. Existing credentials are never rewritten or rotated; Gateway-generated tokens remain runtime-only. Focused tests: 6 passed, 2.19 s wall, including byte-for-byte config preservation with dotenv token/exported password, shell import, unreadable dotenv and default gateway.env, plus initialization with an unrelated API key. SwiftFormat/SwiftLint passed. Independent P0-P1 autoreview: scoped-clean. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…nclaw#169403) * fix(macos): authenticate app-hosted first run and clone runtime seeds Persist missing local token auth before starting the app-owned Gateway, preserving explicit credentials and invalid config. Use one directory clone with a copy fallback for bundled runtime seeds. Release-note context: fresh macOS app installs can authenticate to their child Gateway and seed the bundled runtime faster. Focused sandboxed Swift tests cover auth eligibility, config persistence and clone fallback. * fix(macos): keep local readiness probes out of connect backoff Clear the existing channel connect-failure delay before local startup health probes. Preserve auth pauses, protocol mismatch handling, watchdog behavior and remote reconnect policy. Release-note context: local Gateway startup can connect promptly once ready instead of waiting behind boot-time exponential backoff. Deterministic regression covers queued and active delays; focused channel and network recovery tests pass. * fix(macos): preserve included and config-env Gateway credentials on first run * fix(macos): preserve dotenv and shell-env Gateway credentials on first run
…9403) Backport of a020759 (#169403) adapted for 2026.10.3. 10.3 lacks the cancellable connect-failure backoff wait from #168024, so the channel gains the minimal owned wait task (cancelled on clear and shutdown) that clearConnectFailureBackoff needs; backoffMs becomes internal for that extension. (cherry picked from commit a020759)
…9403) * fix(macos): authenticate app-hosted first run and clone runtime seeds Persist missing local token auth before starting the app-owned Gateway, preserving explicit credentials and invalid config. Use one directory clone with a copy fallback for bundled runtime seeds. Release-note context: fresh macOS app installs can authenticate to their child Gateway and seed the bundled runtime faster. Focused sandboxed Swift tests cover auth eligibility, config persistence and clone fallback. * fix(macos): keep local readiness probes out of connect backoff Clear the existing channel connect-failure delay before local startup health probes. Preserve auth pauses, protocol mismatch handling, watchdog behavior and remote reconnect policy. Release-note context: local Gateway startup can connect promptly once ready instead of waiting behind boot-time exponential backoff. Deterministic regression covers queued and active delays; focused channel and network recovery tests pass. * fix(macos): preserve included and config-env Gateway credentials on first run * fix(macos): preserve dotenv and shell-env Gateway credentials on first run (cherry picked from commit a020759)
What Problem This Solves
On a fresh Mac, the default onboarding path ("On this Mac") fails with the shipped 2026.10.1 app: Getting things ready ends with "The Gateway didn't start … Gateway on port N rejected auth". The app-hosted Bun Gateway is actually running and ready; it rejects the app's own clients (
[ws] unauthorized … role=operator auth=none device=yes, every 30 s). First run was also slow: ~11 s copying the bundled runtime, plus up to ~16 s of idle waiting after the Gateway was already ready.User Impact
Fresh Mac installs can complete the default local setup, and existing 2026.10.1 installs stuck on the authentication error recover on the next app-hosted start. Runtime preparation and the first connection are faster.
Why This Change Was Made
Root cause
openclaw gateway install, but it skipped the step that install performs: persisting a generatedgateway.auth.tokenwhen config has none (src/commands/gateway-install-token.tsmaybePersistAutoGeneratedGatewayInstallToken). With config{"gateway":{"mode":"local"}}, Gateway startup generates a deliberately runtime-only token (src/gateway/startup-auth.ts) and silently pairs only the CLI's SQLite-backed device identity (src/gateway/startup-local-cli-pairing.ts). The app has a separate identity (device.json) and reads its local credential only from config/env/launchd (GatewayEndpointStore.resolveGatewayCredential), so it connects with no credential.FileManager.copyItem, which clones each of the ~42k files individually (~9–11 s for ~600–680 MB), despite a comment claiming clone-on-write.Fix
SecRandomCopyBytes, same shape as the CLI) withgateway.auth.mode = "token"through the existing guarded config writer, only when the config is missing or readable, auth mode is absent/token, no token or password exists in any form (plain, env ref, SecretRef), and the child environment has noOPENCLAW_GATEWAY_TOKEN/OPENCLAW_GATEWAY_PASSWORD. Authored$includesources at root,gateway,gateway.auth,env, orenv.varsare preserved, as are Gateway token/password credentials in eitherenv.varsor directenvstring keys (case-insensitive, checking both sources independently). Malformedenvorenv.varsshapes are left to config validation. The final guard also preserves remote fallback credentials, trusted dotenv sources, login-shell env imports, and opaque path selectors; it writes only after the source checks below establish that none can supply credentials. Unreadable/invalid configs and every existing credential or other auth mode are left untouched; a failed save stops setup with a retryable message instead of launching a Gateway the app cannot authenticate to. Gateway runtime-only token semantics, CLI pairing and service installation are unchanged. Users already stuck on 2026.10.1 are repaired on the next app-hosted start.clonefile(2)call, removing any partial output and falling back tocopyItemon failure.docs/platforms/mac/bundled-gateway.md.Accepted edge: in Nix mode the app's config writer refuses writes, so app hosting now stops with a clear "could not save the local Gateway authentication token" error instead of the later auth rejection.
Gateway credential-source coverage
The app remains the explicit installer. Gateway startup-generated tokens remain runtime-only. This trace applies to the app-hosted child command
gateway run --port Nand its constructed environment.gateway.auth.token/password, explicit modes, env substitutions and env/file/exec SecretRefsgateway.remote.token/passwordfallback inresolveGatewayAuthForConfigOPENCLAW_GATEWAY_TOKENorOPENCLAW_GATEWAY_PASSWORDbefore child launch.$includeat root,gateway,gateway.auth,gateway.remote,env,env.varsorenv.shellEnv; it does not guess included contents.env.varsand directenvstring keys<resolveConfigDir(childEnv)>/.env;OPENCLAW_STATE_DIRwins, then the directory ofOPENCLAW_CONFIG_PATH, then effective-home.openclaw. Gateway pre-bootstrap's default-state.envis also covered if only config is overridden. App-hosted state/config paths normally coincide.<effectiveHome>/.config/openclaw/gateway.envwhen the state directory is default. Named/custom explicit state skips this fallback, matchingresolveGlobalDotEnvFiles.export; does not parse credential values or expansion. Missing files permit initialization.env.shellEnv.enabled=trueand truthy child/configOPENCLAW_LOAD_SHELL_ENV(true,1,yes,on, trimmed/case-insensitive); keeps dotenv shell-import controls conservatively without evaluating values.OPENCLAW_HOME,HOME/USERPROFILE, tilde expansion and the child state/config paths. Unavailable or relative paths keep rather than guessing the child's cwd. Config/dotenv path selectors keep because they can redirect later reads.authOverride(--auth,--token,--password,--password-file)GatewayChildSupervisor.Configuration.argumentspasses onlygateway run --port Nand optional--allow-unconfigured..envOPENCLAW_*key.Source owners:
src/gateway/auth-resolve.ts,src/gateway/startup-auth.ts,src/gateway/credential-planner.ts,src/cli/gateway-cli/run.ts,src/cli/gateway-cli/pre-bootstrap.ts,src/infra/dotenv.ts,src/infra/dotenv-global-core.ts,src/infra/config-dir.ts,src/infra/shell-env.ts, andsrc/config/config-env-values.ts.Evidence
Live, release-identity arm64 build (
ai.openclaw.mac) at0f52cbcc2dc27fece2e57a573897d7b02e791f7d, before the conservative credential-preservation correction, fresh named profile, real onboarding clicks:unauthorizedunauthorizedunauthorizedready→ first app connectionThe final live run reached Connect your AI with no runtime-token warning; config held
gateway.auth.mode=tokenand a 48-char token. Isolated benchmark of the seed copy on the same runtime tree: per-file clone 10.45 s vs one directoryclonefile0.55 s.Tests (Swift, sandboxed, under the shared Mac build slot): app-hosted auth decision/persistence + clone tests 6 passed, 2.19 s wall (final source-coverage correction; build 21.55 s); readiness/channel suite 25 passed, 9.28 s wall; shared OpenClawKit tests 9 passed, 1.87 s wall. The new readiness regression fails against a no-op control. The preservation table covers root/Gateway/auth/env/env.vars includes, direct and nested env credentials, lowercase keys, direct/vars collisions, malformed env/vars, and whitespace-only credentials; the first seven preservation regressions failed on the pre-fix decision. SwiftFormat and SwiftLint passed for all three Swift correction files with zero violations. Persistence-boundary fixtures cover profile dotenv tokens, exported passwords, unrelated API keys, unreadable dotenv, shell import, and default-profile gateway.env. A first fixture attempt correctly hit the process-HOME isolation guard; the fixture now keeps process HOME fixed and passes only synthetic child-env inputs. A five-field fixture tuple was reduced after SwiftLint flagged it. No CI-time impact beyond the existing macOS Swift lane. Independent autoreview (P0–P1): scoped-clean for the original two commits and for both preservation corrections, including final source coverage at
aba2d89a60d7c687e1ee5fb30c342eb1ff77c3df.Release-note context
macOS: a fresh install's default local Gateway now authenticates the app instead of failing with "rejected auth"; first-run setup is faster (runtime prepared by one APFS clone, and the app connects as soon as the Gateway is ready). Existing 2026.10.1 installs stuck on this error recover on the next launch.
Follow-ups (separate work): fresh Gateway boot time on Bun (6 s main-thread stall, synchronous read-only SQLite helper spawns),
openclaw.setup.detectlatency on the Connect your AI page (5–9 s), and named profiles prepending their CLI bin to shell profile files.