Skip to content

Add DI composition root and navigation/activation seam for tray view models - #1008

Merged
shanselman merged 1 commit into
mainfrom
bkudiess-pr4-di-navigation-seam
Jul 18, 2026
Merged

shanselman merged 1 commit into
mainfrom
bkudiess-pr4-di-navigation-seam

Conversation

@bkudiess

@bkudiess bkudiess commented Jul 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Introduces the dependency-injection and navigation plumbing that page view models will depend on: a root ServiceProvider owned by App, a navigation scope/activation seam, and a UI-thread dispatcher abstraction. This is additive infrastructure only — no page is converted to MVVM and no existing App behavior is moved. Intended runtime behavior change: none.

What this adds

  • DI composition root. Adds Microsoft.Extensions.DependencyInjection (10.0.0). App builds one root ServiceProvider with ValidateScopes + ValidateOnBuild, after tray initialization, and disposes it via an ordered shutdown step. App-owned services (SettingsManager, IAppCommands) are registered as pre-built instances, so the container never disposes them — App keeps sole ownership and there is no double-dispose. A build/validation failure is logged and leaves the provider null, so this plumbing can never prevent the tray from starting.
  • Presentation/ WinUI-free core: IUiDispatcher, INavigationAware, INavigationService, IPageActivator, NavigationScopeManager (owns the per-navigation DI scope and the view-model activate/deactivate/dispose lifetime; navigation is non-re-entrant and exception-safe), AppNavigationService (enforces UI-thread affinity — marshals Navigate/GoBack through IUiDispatcher, fails fast on off-thread CanGoBack reads), and transient SettingsPageViewModel/PermissionsPageViewModel placeholders. Hand-linked into the pure net10 test project.
  • Presentation/Adapters/ WinUI-bound: WinUIDispatcher, FramePageActivator.
  • Navigation activation hook in HubWindow.OnContentFrameNavigated. The page→view-model map is empty, so it is a runtime no-op today: it only advances the navigation scope and never touches a page's DataContext, navigation, back-stack, rail selection, or dedupe. HubWindow's existing navigation is untouched.

Ownership / ledger

Adds three authoritative rows with behavioral guard tests — ui-dispatcher (IUiDispatcher), navigation-scope (NavigationScopeManager), composition-root (AppServiceRegistration) — plus matching single-source-owner entries.

Validation

  • build.ps1: pass (all projects)
  • dotnet test OpenClaw.Shared.Tests: 2866 passed / 31 skipped (incl. architecture-ledger consistency)
  • dotnet test OpenClaw.Tray.Tests: 1780 passed (incl. 38 presentation unit + integration + source-contract tests covering: no double-dispose of App-owned instances, transient view-model disposal with scope, non-re-entrant navigation, Activate/Deactivate-throws scope disposal, Reset() window-close teardown + re-navigation, A→B deactivate/dispose-before-activate ordering, UI-thread marshaling/fail-fast enforcement, full open→navigate→close→reopen→shutdown integration, ValidateOnBuild, the WinUI-free boundary, and the ordered shutdown-disposal step)

Real behavior proof

Verified against a local Debug build of this branch (node reports 0.6.13-bkudiess-pr4-di-navigation-seam.1), non-isolated tray, real gateway node.

  • Tray launch — DI root builds at runtime: log emits Service provider initialized. on launch (observed across 3 launches). This is the InitializeServiceProvider() success line, proving BuildServiceProvider(ValidateScopes + ValidateOnBuild) succeeds in a real tray process after tray init, with no validation throw.
  • Node / MCP healthy on this build: gateway handshake caps=6, commands=25; winnode --list-tools returns 52 tools; node connected in node mode.
  • Representative navigation: multiple deep-link navigations handled and ConnectionPage rendered; OnContentFrameNavigated runs the new activation hook each time with no errors — confirming the hook is a safe no-op today.
  • Hub close / reopen (isolated current-head build, HEAD 4ed87980): on an isolated temp profile (EnableMcpServer=true; real %APPDATA% untouched):
    • Provider init across 2 launches: [INFO] Service provider initialized.; startup logs [MCP] HTTP server listening on http://<host>:8765/, Started MCP-only node service without gateway connection, Application started (WinUI 3).
    • Hub opened via winnode --command app.navigate {"page":"permissions"} → navigated:true (Companion window present in list_apps).
    • Hub closed via a computer-use click on the title-bar Close button → window removed from list_apps, i.e. HubWindow.Closed fired and the IPageActivator.Reset() path ran, with no exception logged.
    • Hub reopened via app.navigate {"page":"connection"} → navigated:true (fresh navigation after Reset()), no exception (only a benign, unrelated [WARN] [ConnectionPage] Could not subscribe to High Contrast changes).
    • Full-log error scan: the only [ERROR] is Previous session did not exit cleanly (from an earlier Stop-Process kill of a prior probe instance, not PR code) — no ObjectDisposedException, no failed disposing, no lifecycle exceptions.
  • Clean shutdown — live-proven: this PR adds SafeShutdownStepAsync("service provider", …) which nulls _services and then awaits ServiceProvider.DisposeAsync(). Captured live at current head (4ed87980) by clicking the tray Close on the isolated build:
    [2026-07-17 11:54:40.817] [INFO] Shutdown: disposing service provider
    [2026-07-17 11:54:40.820] [INFO] Shutdown: disposed service provider
    
    The full ordered sequence confirms the intended lifecycle: windows/services torn down first (OpenTelemetry endpoint, node service, ssh tunnel, pairing approval, chat window, setup window, tray menu window, keep-alive window) → then service provider → then tray icon → single-instance mutex → deep link token source → Shutdown complete; calling Exit() now. disposed service provider appears exactly once (no double-dispose), there is no Shutdown: failed disposing line and no ObjectDisposedException, and the _services = null before await DisposeAsync() fix ran cleanly (no late Frame.Navigated fault). Corroborated by PresentationSeamContractTests.App_DisposesServiceProvider_DuringShutdown, App_NullsServiceProviderField_BeforeAwaitingDisposal, and AppServiceRegistrationTests.Dispose_DoesNotDisposeAppOwnedInstanceSingletons.

Follow-ups

  • When pages gain view models, wrap the OnContentFrameNavigated activation-hook body in try/catch-and-log so a misbehaving view model Activate/Deactivate cannot surface as an unhandled exception in the frame-navigated handler.
  • Reintroduce a shutdown-safe awaitable UI-marshaling method on IUiDispatcher if/when a consumer needs it.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P3 Low-risk cleanup, docs, polish, ergonomics, or speculative feature. labels Jul 17, 2026
@clawsweeper

clawsweeper Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Codex review: needs maintainer review before merge. Reviewed July 17, 2026, 6:30 PM ET / 22:30 UTC.

Summary
The branch adds an App-owned DI composition root plus dispatcher, navigation/activation, and view-model scope-lifetime infrastructure for future tray MVVM work.

Reproducibility: not applicable. This PR adds internal tray infrastructure rather than fixing a reported failure. Its intended present-day runtime behavior is explicitly no-op until pages are mapped to view models.

Review metrics: 2 noteworthy metrics.

  • Implementation surface: 24 files affected; 1,780 additions; 0 deletions. This is a broad additive infrastructure change whose main merge question is durable architecture ownership, not a localized behavioral fix.
  • Presentation validation: 38 presentation tests reported. The branch adds focused lifetime, dispatcher, DI-registration, and integration coverage for the new seams.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Obtain explicit maintainer sponsorship for the authoritative DI, dispatcher, and navigation-scope ownership model.

Risk before merge

  • [P1] Merging establishes AppServiceRegistration, IUiDispatcher, and NavigationScopeManager as authoritative architectural boundaries before any production page is converted, so future tray work will inherit these contracts and lifetime semantics.
  • [P1] The new service-provider initialization and disposal path runs in the tray process; although the PR contains containment and lifecycle coverage, regression impact would be process availability rather than an isolated page feature.

Maintainer options:

  1. Sponsor the authoritative seams (recommended)
    Approve the documented DI, dispatcher, and navigation-scope ownership model after confirming it is the intended tray direction.
  2. Defer until a page migration
    Pause this infrastructure-only PR if maintainers prefer to choose the contracts alongside the first production view-model conversion.

Next step before merge

  • [P2] No narrow mechanical repair remains; a maintainer must choose whether to make the new DI, dispatcher, and navigation-lifetime seams the tray’s permanent ownership model.

Maintainer decision needed

  • Question: Should the tray adopt AppServiceRegistration, IUiDispatcher, and NavigationScopeManager as the authoritative DI, UI-dispatch, and page-lifetime model before the first page is migrated to view models?
  • Rationale: The patch is intentionally additive and well-covered, but selecting durable ownership boundaries for future tray work is an architectural direction decision rather than a mechanical correctness question.
  • Likely owner: bkudiess — They are the most directly connected collaborator in the available history, having authored the proposed ownership transfer and its validation.
  • Options:
    • Sponsor the seam and merge (recommended): Adopt the documented ownership model now, keeping future page conversions constrained to these single owners.
    • Defer the foundation: Keep the current tray architecture unchanged until a concrete page migration can justify and validate the permanent DI/navigation contracts.

Security
Cleared: The diff adds a pinned Microsoft DI dependency and local tray lifecycle code; no concrete credential, permission, secret-handling, supply-chain, or execution-boundary regression is evident.

Review details

Best possible solution:

Have a tray architecture owner explicitly sponsor the three authoritative seams, then merge this additive foundation and require later page-MVVM work to use these owners rather than creating parallel navigation or dispatcher paths.

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

Not applicable: this PR adds internal tray infrastructure rather than fixing a reported failure. Its intended present-day runtime behavior is explicitly no-op until pages are mapped to view models.

Is this the best way to solve the issue?

Unclear: the implementation is internally coherent and addresses the prior lifecycle review, but whether these three seams are the best permanent tray ownership model requires maintainer architectural intent.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 4518dd87ed2b.

Label changes

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🦞 diamond lobster: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: This is a normal-priority tray architecture improvement with no current user-facing regression established.
  • merge-risk: 🚨 availability: The PR adds provider construction and disposal to the live tray startup/shutdown lifecycle, where an integration regression could affect process availability.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The PR body provides live tray launch, navigation, Hub close/reopen, MCP health, and clean-shutdown logs showing provider initialization/disposal without lifecycle exceptions; redact private host or gateway details if that evidence is reposted.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides live tray launch, navigation, Hub close/reopen, MCP health, and clean-shutdown logs showing provider initialization/disposal without lifecycle exceptions; redact private host or gateway details if that evidence is reposted.
Evidence reviewed

What I checked:

  • Architecture ownership transfer: The PR updates the architecture ledger to make UI-thread marshaling, page view-model activation/disposal, and presentation DI composition authoritative responsibilities, so this is an intentional repository-level ownership decision rather than a narrow bug fix. (docs/ARCHITECTURE.md:57, 3ff1f4370626)
  • Lifecycle integration: App creates the validated root provider after tray initialization, exposes the page activator through the nullable provider, and disposes the provider as an ordered shutdown step; the associated tests cover provider ownership and shutdown ordering. (src/OpenClaw.Tray.WinUI/App.xaml.cs:55, 3ff1f4370626)
  • Frame safety boundary: The HubWindow navigation handler contains page-activation exceptions and the added reset path is intended to end the navigation scope when the Hub closes, addressing the lifecycle failures raised in prior review. (src/OpenClaw.Tray.WinUI/Windows/HubWindow.xaml.cs:1025, 3ff1f4370626)
  • Behavioral coverage: The added presentation tests exercise UI-thread marshaling, navigation ordering, reset/reopen behavior, activation failure containment, App-owned singleton disposal, and the composed open→navigate→close→reopen→shutdown lifecycle. (tests/OpenClaw.Tray.Tests/Presentation/NavigationIntegrationTests.cs:27, 3ff1f4370626)
  • Prior review follow-up: The contributor’s latest follow-up describes the rebased head as addressing the previous UI-thread and behavioral-integration requests, while the supplied check state reports successful build, test, analysis, and setup E2E workflows. (3ff1f4370626)

Likely related people:

  • bkudiess: Authored the current DI/navigation seam, the architecture-ledger transfer, and the lifecycle/ownership test coverage; no longer-lived merged-main owner was identifiable from the supplied history. (role: recent architecture proposer; confidence: medium; commits: 3ff1f4370626; files: docs/ARCHITECTURE.md, src/OpenClaw.Tray.WinUI/App.xaml.cs, src/OpenClaw.Tray.WinUI/Presentation/NavigationScopeManager.cs)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (9 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-17T06:06:26.837Z sha cc86db2 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-17T16:25:20.054Z sha 1293894 :: found issues before merge. :: [P1] Contain activation failures at the frame event boundary | [P1] Make the provider unreachable before disposing it | [P2] End the navigation scope when HubWindow closes | [P2] Define truthful UI-thread navigation semantics
  • reviewed 2026-07-17T16:48:15.579Z sha 4ed8798 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-17T18:07:11.316Z sha 4ed8798 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-17T18:48:59.887Z sha 4ed8798 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-17T18:58:49.077Z sha 4ed8798 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-17T19:40:26.200Z sha 4ed8798 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-17T21:49:12.699Z sha 3ff1f43 :: needs maintainer review before merge. :: none

@bkudiess
bkudiess force-pushed the bkudiess-pr4-di-navigation-seam branch from 4f5c74a to cc86db2 Compare July 17, 2026 06:00
@bkudiess bkudiess changed the title PR 4: Minimal DI + navigation/activation seam (Phase 2 kickoff) Add DI composition root and navigation/activation seam for tray view models Jul 17, 2026
@shanselman

Copy link
Copy Markdown
Collaborator

GitHub Copilot maintainer-assistant review — this is automated feedback, not a comment written personally by Scott.

Reviewed head: cc86db2d81c27ea1d8218a44797150310205ae2d

The DI/navigation direction is reasonable, and the repository-wide reuse check found no existing service container, navigation service, dispatcher abstraction, or navigation-scope owner that this should have reused. The concern is lifecycle correctness before the first real page mapping makes this currently no-op seam active.

Please address these items before merge:

  1. Dispose ordering: clear App._services before awaiting ServiceProvider.DisposeAsync(). Today PageActivator can resolve against a disposed provider during the small interval between disposal and _services = null, especially if a queued Frame.Navigated callback runs during shutdown.
  2. Navigation fault containment: OnContentFrameNavigated calls PageActivator.OnNavigatedTo without an exception boundary. A future view model throwing from activation/deactivation—or the shutdown race above—can escape the XAML event handler and crash the app. Catch, log, and contain activation failures consistently with existing app error handling.
  3. Window/scope lifetime: closing HubWindow does not clear/deactivate the current navigation scope. Once pages are mapped, their view models, subscriptions, and timers can survive window close until reopen or process shutdown. Add an explicit reset/deactivate/dispose path on Hub close, or make navigation-scope ownership window-scoped rather than app-scoped.
  4. Navigation contract/threading: INavigationService.Navigate returns true unconditionally and does not enforce UI-thread affinity. Either make the contract void with documented UI-thread ownership, return the real frame navigation result, or marshal through IUiDispatcher with a truthful async result.

Please strengthen behavioral tests rather than adding more source-shape assertions:

  • map fake Page A and B view models; navigate A → B and prove A deactivates/disposes exactly once before B activates;
  • close and reopen the Hub and prove the old scope is gone;
  • shut down with a queued navigation callback and prove no service is resolved from a disposed provider;
  • make Activate and Deactivate throw independently and prove exceptions do not escape the frame event handler or leak scopes;
  • exercise navigation from a background caller if the interface intends to support it, or explicitly reject/document that use;
  • verify app-owned singleton instances are still not disposed by the container.

Current-head Windows proof should include launch, navigation/back navigation, Hub close/reopen, and clean process shutdown with service-provider initialization/disposal logs and no activation/disposal exceptions.

The source-shape tests are acceptable as secondary architecture guards, but they do not prove runtime ownership. Fixing these lifecycle seams now is important because the empty page map only postpones the bugs until the next PR wires the first view model.

@bkudiess
bkudiess force-pushed the bkudiess-pr4-di-navigation-seam branch from cc86db2 to 1293894 Compare July 17, 2026 16:19
@bkudiess

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review — added ## Validation and ## Real behavior proof: current-head runtime evidence of DI composition-root build at launch (Service provider initialized. across 3 launches, ValidateOnBuild passing in a real tray process), node/MCP health (handshake commands=25, winnode --list-tools = 52 tools), and representative deep-link navigation (ConnectionPage rendered, activation hook a safe no-op). The live clean-shutdown disposal line could not be captured because validation ran in a switched Windows session (session 2, not the active console), so the tray Close menu couldn't be driven; the ordered service provider disposal step and no-double-dispose ownership are covered by source-contract + unit tests.

@clawsweeper

clawsweeper Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. P2 Normal priority bug or improvement with limited blast radius. merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. P3 Low-risk cleanup, docs, polish, ergonomics, or speculative feature. labels Jul 17, 2026
@bkudiess
bkudiess force-pushed the bkudiess-pr4-di-navigation-seam branch from 1293894 to 4ed8798 Compare July 17, 2026 16:44
@bkudiess

Copy link
Copy Markdown
Collaborator Author

Thanks — addressed all four lifecycle items in 4ed87980, with behavioral tests rather than source-shape assertions where possible.

1. Dispose ordering. Shutdown now nulls App._services before awaiting ServiceProvider.DisposeAsync(), so a queued Frame.Navigated callback during shutdown resolves the page activator against null (_services?.GetService<IPageActivator>()), never a disposing provider. Guarded by PresentationSeamContractTests.App_NullsServiceProviderField_BeforeAwaitingDisposal.

2. Navigation fault containment. OnContentFrameNavigated now wraps the PageActivator.OnNavigatedTo call in try/catch and logs via Logger.Error, consistent with the existing page-init error handling, so a future activation throw can't escape the XAML handler. NavigationScopeManager also already disposes the scope and clears state when Activate/Deactivate throw (Navigate_WhenActivateThrows_..., NavigatingAway_DisposesScope_EvenWhenDeactivateThrows). Guarded by HubWindow_ContainsActivationHook_InTryCatch.

3. Window/scope lifetime. Added NavigationScopeManager.Reset() (deactivate + dispose the current scope, keep the manager alive) exposed via IPageActivator.Reset(), and wired it into the HubWindow.Closed handler. Closing the Hub now tears down the current navigation scope so page view models/subscriptions can't outlive the window. Guarded by Reset_DeactivatesAndDisposesCurrent_AndAllowsRenavigation, Reset_IsNoOp_WhenNothingActive, and App_ResetsNavigationScope_OnHubClose.

4. Navigation contract/threading. INavigationService.Navigate is now void (it forwarded tag-based navigation that has no meaningful success result — returning true was dishonest) and the interface documents UI-thread affinity on all members. AppNavigationService takes an Action<string>.

Behavioral tests added: map A/B view models and assert A deactivates + disposes exactly once before B activates (Navigate_AtoB_DeactivatesAndDisposesA_BeforeActivatingB); Reset (Hub-close analog) disposes the old scope and allows re-navigation; navigation is non-re-entrant from both Activate and Deactivate; Activate/Deactivate throwing independently disposes the scope without leaking; app-owned singleton instances are not disposed by the container (Dispose_DoesNotDisposeAppOwnedInstanceSingletons).

Validation: build.ps1 pass; OpenClaw.Shared.Tests 2865 passed / 31 skipped; OpenClaw.Tray.Tests 1772 passed (30 presentation tests).

Note on runtime proof: live Hub close/reopen + clean-shutdown disposal logs couldn't be captured from the automation host because it runs in a switched Windows session (session 2, not the active console), so the tray Close menu can't be driven there; those paths are covered by the tests above and can be captured from an interactive console session.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Jul 17, 2026
@bkudiess

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review — added live current-head (HEAD 4ed8798) runtime proof for the Hub close/reopen path to the PR body's Real behavior proof section:

  • Provider init across 2 launches (Service provider initialized.), MCP HTTP server listening, Application started (WinUI 3).
  • Hub opened (app.navigate {"page":"permissions"} → navigated:true), closed via a title-bar Close click (window removed from the window list → HubWindow.Closed → IPageActivator.Reset() ran, no exception), then reopened (app.navigate {"page":"connection"} → navigated:true, fresh navigation after Reset, no exception).
  • Full-log error scan clean of lifecycle exceptions (the only [ERROR] is a prior Stop-Process "did not exit cleanly", unrelated to this change).

Still test-covered (not live): the Shutdown: disposing/disposed service provider disposal log line. The exit path fires only from the OS notification-area tray flyout, which isn't drivable in the agent harness; the ordered disposal (nulls _services before await DisposeAsync()) and no-double-dispose are verified by App_DisposesServiceProvider_DuringShutdown, App_NullsServiceProviderField_BeforeAwaitingDisposal, and Dispose_DoesNotDisposeAppOwnedInstanceSingletons.

@clawsweeper

clawsweeper Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 17, 2026
@bkudiess

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review — the clean-shutdown provider init/disposal live logs are now captured at current head (4ed8798) with no lifecycle exceptions. Driven by an interactive tray Close on the isolated build:

[2026-07-17 11:54:40.817] [INFO] Shutdown: disposing service provider
[2026-07-17 11:54:40.820] [INFO] Shutdown: disposed service provider

Ordered sequence confirms the invariants live: windows/services disposed first → then service provider → then tray icon → single-instance mutex → deep link token source → Shutdown complete; calling Exit() now. disposed service provider appears exactly once (no double-dispose), no Shutdown: failed disposing, no ObjectDisposedException, and the _services = null before await DisposeAsync() fix ran cleanly. Combined with the earlier live launch + Hub close/reopen + navigation + MCP evidence, the full lifecycle (init → navigate → close/reopen → clean shutdown) is now proven at current head.

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jul 17, 2026
@shanselman

Copy link
Copy Markdown
Collaborator

GitHub Copilot maintainer-assistant follow-up — automated, not written personally by Scott.

Re-reviewed head: 4ed87980

The updated head resolves the major lifecycle concerns: _services is cleared before provider disposal, activation is exception-contained, Hub close resets the current scope, Navigate no longer returns a fake success boolean, and the pure scope tests now cover ordering, reset, reentrancy, and activation/deactivation failures.

Two items remain before this is uniformly above 90%:

  1. INavigationService documents UI-thread-only use but AppNavigationService neither marshals nor enforces it. Please use the existing IUiDispatcher seam to marshal navigation, or fail fast with an explicit thread-access check and test the contract. Documentation alone will not prevent a future background view model command from touching HubWindow/Frame off-thread.
  2. App/Hub integration guarantees are still primarily source-shape assertions. Add at least one behavioral current-head proof/test covering Hub open → navigate A/B → close → reopen → shutdown, showing the old scope is disposed, activation exceptions do not escape the frame handler, and no service resolves from a disposed provider. A short Windows smoke transcript/log is acceptable where pure tests cannot host HubWindow.

Please also remove the duplicated <summary> block on NavigationScopeManager.Navigate.

Once those are addressed and the branch is rebased onto current main with green build/Tray tests, this should be ready for a quick final review.

…models

Introduce the dependency-injection and navigation plumbing that page view
models will depend on: a root ServiceProvider owned by App, a navigation
scope/activation seam, and a UI-thread dispatcher abstraction. This is
additive infrastructure only -- no page is converted to MVVM and no existing
App behavior is moved. Intended runtime behavior change: none.

- Add Microsoft.Extensions.DependencyInjection (10.0.0). App builds one
  validated root ServiceProvider (ValidateScopes + ValidateOnBuild) after
  tray init, disposed via an ordered shutdown step. App-owned services
  (SettingsManager, IAppCommands) are registered as pre-built instances so
  the container never disposes them (no double-dispose).
- Presentation/ WinUI-free core: IUiDispatcher, INavigationAware,
  INavigationService, IPageActivator, NavigationScopeManager,
  AppNavigationService, transient Settings/Permissions page-view-model
  placeholders.
- Presentation/Adapters/ WinUI-bound: WinUIDispatcher, FramePageActivator.
- HubWindow activation hook (empty page-to-view-model map => runtime no-op).
- Ledger: three authoritative rows (ui-dispatcher, navigation-scope,
  composition-root) with behavioral guard tests; single-source-owner entries.
- 20 presentation tests (unit + source-contract, incl. WinUI-free guard).

Co-authored-by: Copilot App <[email protected]>
@bkudiess
bkudiess force-pushed the bkudiess-pr4-di-navigation-seam branch from 4ed8798 to 3ff1f43 Compare July 17, 2026 21:46
@bkudiess

Copy link
Copy Markdown
Collaborator Author

Thanks — both remaining items and the nit are addressed in 3ff1f437 (rebased onto current main, green build.ps1 + Shared/Tray tests).

1. UI-thread enforcement (now enforced via IUiDispatcher). AppNavigationService takes the IUiDispatcher seam. Navigate and GoBack run directly when HasThreadAccess is true and otherwise marshal onto the UI thread via TryEnqueue, so a background view model can never touch HubWindow/Frame off-thread. CanGoBack reflects live frame state, so it fails fast with InvalidOperationException when read off-thread. Contract is tested by AppNavigationServiceTests (on-thread synchronous, off-thread marshaled for both Navigate and GoBack, CanGoBack throws off-thread / returns on-thread).

2. Integration proof (behavioral, current head). Added NavigationIntegrationTests composing the real composition root (AddOpenClawTrayCore), the NavigationScopeManager, and the registered transient page view models:

  • FullLifecycle_OpenNavigateCloseReopenShutdown_HonorsOwnership: open → navigate A(Settings) → B(Permissions) proves A deactivates + disposes before B activates; Reset() (Hub-close) disposes B and clears current; reopen yields a fresh instance; provider dispose (shutdown) disposes the manager and the current view model.
  • FrameHandlerSimulation_ContainsActivationException_AndDisposesScope: mirrors the OnContentFrameNavigated try/catch and proves an activation throw does not escape the handler and the half-activated scope is disposed, not leaked.
  • AfterShutdown_LateNavigation_DoesNotResolveFromDisposedProvider: after provider dispose, a late navigation throws ObjectDisposedException rather than resolving from a disposed provider.

These complement the live Windows smoke transcript in the PR body (open → navigate → close → reopen → clean shutdown with the Shutdown: disposing/disposed service provider logs and no lifecycle exceptions), which covers the HubWindow-hosted parts pure tests can't host.

Nit: removed the duplicated <summary> block on NavigationScopeManager.Navigate.

Validation: build.ps1 pass; OpenClaw.Shared.Tests 2866 passed / 31 skipped; OpenClaw.Tray.Tests 1780 passed (38 presentation tests).

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Jul 17, 2026
@shanselman
shanselman merged commit 2de791e into main Jul 18, 2026
19 checks passed
@shanselman
shanselman deleted the bkudiess-pr4-di-navigation-seam branch July 18, 2026 05:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary 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.

2 participants