Skip to content

fix(local-ai): keep routing safe across endpoint restarts - #1390

Merged
shanselman merged 27 commits into
mainfrom
pr/1321
Sep 10, 2026
Merged

shanselman merged 27 commits into
mainfrom
pr/1321

Conversation

@shanselman

Copy link
Copy Markdown
Collaborator

Supersedes #1321 (fix(local-ai): stop routing to OpenAI while the endpoint restarts).

What Problem This Solves

Fixes an issue where Local AI-only users could have a prompt routed toward the Gateway's built-in OpenAI default while the managed llama.cpp endpoint was restarting or being rebound.

Why This Change Was Made

Endpoint cycles now withdraw the llamacpp provider while retaining the managed Local AI primary, so requests fail locally instead of falling through to OpenAI. Terminal stop, startup failure, cancellation, retry exhaustion, and disposal paths restore the recorded fallback or unset the managed primary, and process-shutdown failures remain visible and retryable.

Ownership transfer: none. Runtime sequencing remains in LlamaServerRuntimeService and LocalAiEndpointLifecycle; Gateway route mutation remains in LocalAiGatewayProviderCoordinator; setup repair/rollback remains in LocalAiGatewayConfiguration; UI action policy remains in LocalAiPageViewModel. App.xaml.cs is unchanged.

User Impact

Local AI users keep privacy-safe routing while the endpoint cycles. If restart or cleanup cannot complete, the app reports an actionable failed state and exposes Stop when a managed listener still needs cleanup.

Evidence

  • Endpoint-cycle tests assert EndpointCycle retains the managed primary and terminal Teardown restores fallback or unsets it.
  • Lifecycle stress covers startup failure, cancellation, refresh recovery, explicit restart/stop races, automatic retry exhaustion, unsafe listeners, and process-shutdown failures.
  • Setup rollback tests reject restoring a provider-less managed primary.
  • Presentation tests expose Stop for production-shaped failed/conflict cleanup states and keep preserved listeners Stop-only.
  • Final Codex autoreview and full-branch rubber-duck review reported no actionable findings.

Change Type

  • Bug fix
  • Feature
  • Refactor
  • Docs or instructions
  • Tests or validation
  • Security hardening
  • Chore or infrastructure

Scope

  • Tray or WinUI UX
  • Windows node capability
  • Local MCP or winnode
  • Gateway, connection, or pairing
  • Setup or onboarding
  • Permissions, privacy, or security
  • Tests, CI, or docs

Required proof pools

  • windows-wsl-dgx-blackwell: validate a real managed Local AI restart and fixed-prompt inference without cloud fallback.
  • windows-wsl-gateway-e2e: validate Gateway prompt routing while the local provider is temporarily withdrawn.
  • windows-winui-interactive: validate visible Stop recovery actions for failed/conflict Local AI cleanup states.

Validation

Exact head: 8d1553395c70fa358c78584dc4b03de2b200b36d

  • .\build.ps1: passed.
  • dotnet test .\tests\OpenClaw.Connection.Tests\OpenClaw.Connection.Tests.csproj --no-restore --filter "FullyQualifiedName~LocalAiPortLifecycleTests": 79 passed, 0 failed, repeated 3 times.
  • dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --no-restore: 3,991 passed, 32 skipped, 0 failed.
  • dotnet test .\tests\OpenClaw.Tray.Tests\OpenClaw.Tray.Tests.csproj --no-restore: 2,897 passed, 0 failed.
  • dotnet test .\tests\OpenClaw.Connection.Tests\OpenClaw.Connection.Tests.csproj --no-restore: 790 passed, 1 skipped, 0 failed.
  • dotnet test .\tests\OpenClaw.SetupEngine.Tests\OpenClaw.SetupEngine.Tests.csproj --no-restore: 1,136 passed, 0 failed.
  • SetupEngine Local AI filter: 7 passed, 0 failed.
  • Gateway provider coordinator filter: 25 passed, 0 failed.
  • Autoreview: the full branch review found one retained-process state defect; it was fixed. The exact fix commit and final cleanup commit both exited clean with no actionable findings. The full branch exceeds the helper's 180,000-byte single-bundle ceiling, so final review used the helper's split-target guidance.
  • Rubber-duck: final full-branch review at 8d155339 reported no actionable findings.

Real Behavior Proof

  • Environment tested: Windows x64 isolated worktree on current main (3ce56b89).
  • PR head or commit tested: 8d1553395c70fa358c78584dc4b03de2b200b36d.
  • Exact steps or command run: the lifecycle suite above, repeated three times, plus full Shared, Tray, Connection, and SetupEngine suites.
  • Evidence after fix: all 79 lifecycle tests passed on each run, including deterministic event-order assertions for endpoint-cycle retention, terminal teardown, restart exhaustion with successful and failed cleanup, held-manifest-lock cancellation recovery, and retryable process-shutdown failure.
  • Observed result: terminal paths end in teardown-aware state; a retained process is reported as Failed/CompanionManaged; exhausted retries do not remain in endpoint-cycle routing state.
  • Screenshot or artifact links verified? N/A.
  • Not verified or blocked: real Gateway prompt traffic during a GPU-backed llama.cpp restart and current-head interactive WinUI screenshots require the declared capacity-dependent proof pools.

Security Impact

  • New permissions or capabilities? No
  • Secrets or tokens handling changed? No
  • New or changed network calls? Yes
  • Command or tool execution surface changed? No
  • Data access scope changed? No
  • If any answer is Yes, explain the risk and mitigation: Gateway model routing during Local AI endpoint cycles is intentionally changed to retain the managed local primary and prevent unintended fallback toward OpenAI. Terminal cleanup restores the recorded prior route or unsets the managed primary.

Compatibility and Migration

  • Backward compatible? Yes
  • Config or environment changes? No
  • Migration needed? No
  • If yes, list the exact upgrade steps: N/A

Review Conversations

  • I replied to or resolved every bot review conversation addressed by this PR.
  • I left unresolved only conversations that still need maintainer judgment.

plarroy-nv and others added 27 commits September 10, 2026 00:21
On every companion start, EnsureStartedCoreAsync quiesced the gateway
route, started llama-server, probed it, and only then republished. With
no prior model to restore, quiesce unset agents.defaults.model.primary
outright -- and an absent primary is not "no routing", it is the
gateway's built-in default:

    parseModelRef(... ?? "gpt-5.6-sol", "openai", ...)

So any prompt sent during that window was dispatched to openai and
failed with ProviderAuthError / missing-provider-auth on a Local
AI-only install. The window was ~10s and reproduced on every launch,
because requestedPort is 0 and the OS-assigned port made the previously
published baseUrl stale by construction.

Retain the managed primary across an endpoint cycle. QuiesceAsync now
takes a LocalAiQuiesceReason: EndpointCycle keeps llamacpp/<alias> in
place so a mid-cycle request fails as Local AI rather than as an
unrelated provider, while Teardown (stop, shutdown, failed publish)
still restores whatever preceded Local AI.

Reuse the last verified port when it is free, and skip the quiesce
entirely when the published route already names the port about to be
bound. The normal restart now performs zero config writes; PublishAsync
re-verifies and no-ops. A route is only withdrawn when the endpoint
genuinely moves.

Deciding the port before touching routing exposed a latent bug: the
port-conflict and ownership-unknown paths returned Conflict without
withdrawing the published route, leaving the gateway aimed at a port a
foreign process owns. FailStartupAsync now takes a route to withdraw,
and every startup-failure path passes it when one was left standing.

Refs #1293

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
ClawSweeper review of PR #1321 identified two terminal lifecycle paths
that could leave the gateway configured for a Local AI provider nothing
would serve:

1. With a retained route (last-verified port reuse), a process-launch
   exception, immediate child exit, probe failure, or cancellation hit
   the catch handlers in EnsureStartedCoreAsync, which only disposed the
   child. The gateway kept routing to the retained port with no listener.
   Both catch paths now withdraw the retained route with teardown
   semantics before the child's listener disappears.

2. HandleManagedProcessExitedAsync always quiesced with EndpointCycle
   semantics even when automatic restart attempts were exhausted, so the
   managed primary stayed selected with its provider absent and no
   republish to follow. The exit handler now picks the quiesce reason
   from whether a restart will actually run: EndpointCycle for a pending
   restart, Teardown once the retry budget is spent.

FailStartupAsync also now withdraws a retained route before disposing
the child (previously after), matching the lifecycle contract that
managed routing is removed before a listener can disappear.

Tests: three new regression tests cover launch exception, retry
exhaustion, and cancellation with a retained route; the publish-failure
and startup-timeout tests were updated for the withdraw-before-stop
ordering.

Validation: build.ps1 clean; OpenClaw.Connection.Tests 724/724,
OpenClaw.Tray.Tests 2864/2864, OpenClaw.SetupEngine.Tests
LocalAiGpu 8/8 pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: d0dbb47f-7bb0-4294-bda6-60b2a8b5fc55
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Bound post-cancellation route recovery, publish retryable ownership when process shutdown fails, and cover teardown failure after retry exhaustion.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Make endpoint-cycle recovery state explicit and drive the manifest-lock cancellation test causally.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
@clawsweeper

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@shanselman shanselman added merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. P1 Urgent regression or broken agent/channel workflow affecting real users now. labels Sep 10, 2026
@shanselman shanselman added proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. status: 🚢 actively landing A maintainer or agent is actively driving this item through implementation, validation, or merge. labels Sep 10, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. labels Sep 10, 2026
@clawsweeper

clawsweeper Bot commented Sep 10, 2026

Copy link
Copy Markdown

Codex review: blocked before merge. Reviewed September 10, 2026, 4:40 AM ET / 08:40 UTC.

ClawSweeper review

What this changes

Keeps Local AI selected while its endpoint restarts, strengthens interrupted cleanup and fallback restoration, and exposes Stop for failed cleanup states.

Merge readiness

⛔ Blocked before merge - 3 items remain

This remains necessary, and the earlier cleanup findings are addressed. No definite introduced defect was found, but the maintainer-requested real restart evidence remains outstanding.

Priority: P1
Reviewed head: 8d1553395c70fa358c78584dc4b03de2b200b36d

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) PR readiness rating was derived from proof quality, review findings, security review, and reviewer confidence.
Proof confidence 🌊 off-meta tidepool Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Evidence reviewed 10 items Current main still needs the fix: At the pinned main revision, QuiesceAsync restores the recorded fallback or unsets the primary on every cycle, without distinguishing temporary endpoint replacement.
Latest release comparison: The supplied latest release, v2026.7.1-4, also contains unconditional fallback restoration or primary removal during quiescence.
Introduced routing behavior: EndpointCycle now retains the managed primary even when a recorded fallback exists; Teardown still restores that fallback. Publication accepts the retained managed primary while preserving checks against externally changed configuration.
Findings None None.
Security None None.

How this fits together

The Windows companion manages the local llama-server process and configures the WSL Gateway to send requests to its verified endpoint. Runtime transitions update Gateway routing and the Local AI settings page.

flowchart TD
 A[Startup or restart] --> B[Withdraw local provider]
 B --> C[Keep Local AI selected]
 C --> D[Start and verify endpoint]
 D -->|Ready| E[Publish Gateway route]
 D -->|Terminal failure| F[Restore prior routing]
 F --> G[Show cleanup status and Stop]
 E --> H[Gateway inference requests]
Loading

Before merge

  • Resolve merge risk (P2) - Existing installations with a recorded fallback now keep Local AI selected during endpoint cycles, so requests can fail locally where they previously used the prior provider; fresh-install and upgrade behavior still lack current-head Gateway proof.
  • Resolve merge risk (P1) - The declared WinUI proof remains blocked, so visible recovery through Stop has only presentation-test coverage.
  • Complete next step (P2) - Complete the declared current-head Windows/Gateway and WinUI proof, including fresh-install and upgrade routing behavior, and attach redacted results before merge.
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production and test growth Production +666 net lines; tests +2,045 net lines The stated growth supports interrupted lifecycle recovery and its regression coverage across five production and four test files.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #1293
Summary: The issue discussion identifies companion-side primary removal; this PR carries the candidate repair forward from the closed predecessor.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Verify the routing transition before landing (recommended)
    Complete the declared Windows proof with real Gateway dispatch during restart and after recovery, covering installations with and without a recorded fallback.

Technical review

Best possible solution:

Preserve local selection through recoverable cycles and terminal fallback restoration, with real Gateway verification on fresh and upgraded installations.

Do we have a high-confidence way to reproduce the issue?

Yes, from source and the linked configuration-audit reproduction: main removes the managed primary during startup, exposing the Gateway default before republishing. This review did not execute that path.

Is this the best way to solve the issue?

Yes in direction: the existing lifecycle and coordinator are the appropriate owners, and the patch covers the previously reported cleanup gaps without introducing a parallel routing implementation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 3ce56b8902d5.

Labels

Label changes:

  • add merge-risk: 🚨 compatibility: Existing installations stop temporarily restoring their recorded fallback during endpoint cycles.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🌊 off-meta tidepool and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.
  • remove proof: 📸 screenshot: Current real behavior proof evidence kind is not_applicable.

Label justifications:

  • P1: The linked reproduction establishes a broken Local AI prompt workflow that incorrectly requests OpenAI authentication.
  • merge-risk: 🚨 auth-provider: The patch changes Gateway provider selection during restarts, and actual dispatch and recovery remain unverified.
  • merge-risk: 🚨 compatibility: Existing installations stop temporarily restoring their recorded fallback during endpoint cycles.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🌊 off-meta tidepool and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.

Evidence

What I checked:

Likely related people:

  • joelagnel: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • karkarl: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@shanselman
shanselman merged commit 621f410 into main Sep 10, 2026
37 of 40 checks passed
@shanselman
shanselman deleted the pr/1321 branch September 10, 2026 14:48
@shanselman shanselman removed the status: 🚢 actively landing A maintainer or agent is actively driving this item through implementation, validation, or merge. label Sep 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P1 Urgent regression or broken agent/channel workflow affecting real users now. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants