Assess SignalR notifications for native Word navigation
This commit is contained in:
parent
ea5a62b147
commit
10a542c00c
102
Docs/Writer/Word-Companion-SignalR-Architecture-Assessment.md
Normal file
102
Docs/Writer/Word-Companion-SignalR-Architecture-Assessment.md
Normal file
@ -0,0 +1,102 @@
|
||||
# Word Companion: SignalR architecture assessment
|
||||
|
||||
21 November 2026. Investigation baseline **`ea5a62b14783316e643e2297357539e9d9fcf707`**. Read the latest checkpoint in [the physical navigation latency report](Writer-Phase3B4-Navigation-Latency-Report.md), not its superseded “.42 not installed” sections. Current native source/installed evidence is .43; the report records a 3373ms median, 3533ms p90 and 3549ms worst across ten warm requests. This assessment changes documentation only: no implementation, database/manuscript access, package, deployment or Windows operation.
|
||||
|
||||
## Recommendation
|
||||
|
||||
**Choose C: SignalR notifications, preserving the existing HTTP command queue and authoritative receipts.** Reuse the browser's existing native-presence SignalR connection; add one native-authenticated SignalR subscription per Windows agent process. A notification means “check your existing queue/receipt”, never “execute this range” or “navigation succeeded”. Also wake the existing Presence worker immediately after a valid adapter result. Do not introduce the proposed custom HTTP long-poll alongside it.
|
||||
|
||||
This is the better fit because the web half already exists, SignalR is deployed infrastructure, and the agent can use the standard .NET client without involving Word COM. It is **not** already connected to native SignalR, nor is its existing authentication automatically suitable for a persistent hub. Those lifecycle/security changes are real implementation work requiring approval. B remains a defensible alternative if the native dependency/lifecycle cost is unacceptable; A is the least code but gives the weakest tail-latency/resource tradeoff.
|
||||
|
||||
## 1. SignalR inventory: implemented versus proposed
|
||||
|
||||
Solution-wide searches covered C#, project/dependency files, JavaScript/TypeScript, Razor and HTML; then traced registered hubs and their publishers/callers. Generated/vendor/node_modules output was excluded from implementation conclusions.
|
||||
|
||||
| Existing infrastructure | Actual use and limits |
|
||||
| --- | --- |
|
||||
| [Program.cs](../../PlotLine/Program.cs), `AddSignalR`, `MapHub` | Three hubs: `/hubs/native-companion`, `/hubs/word-companion-follow`, `/hubs/story-intelligence`. Maximum received message size is 1MB for existing uses. Cookie auth is default; `DesktopPairing.Scheme` is separately registered for native HTTP. `NativePresenceStore` is a singleton in-memory store. No Redis/Azure SignalR scale-out configuration/client package found in the application. |
|
||||
| [NativeCompanionPresenceHub](../../PlotLine/Hubs/NativeCompanionPresenceHub.cs) | `[Authorize]`, cookie-authenticated, server-derived `native-presence:user:{id}` group, no command methods/client-chosen groups. A real browser invalidation stream, **not a native-agent command channel**. |
|
||||
| [NativePresenceController.Update](../../PlotLine/Controllers/NativePresenceController.cs), [NativeInstallationService.Invalidate](../../PlotLine/Services/NativeCompanion/NativeInstallationService.cs) | Publish `NativePresenceChanged` to the user's browser group after accepted presence changes (including acknowledgement ID), or revocation. Payload is a book hint, not command/completion authority. |
|
||||
| [native-companion-status.js](../../PlotLine/wwwroot/js/native-companion-status.js) | Cookie SignalR client, automatic reconnect, 250ms event debounce then authenticated status GET; initial/reconnected/visibility/pageshow refresh and 15s fallback/start retry. Loaded by the shared layouts, including a hidden status root on Writer when needed. Dispatches `writer-word-state`/`native-companion-presence`. Writer consumes status, but its receipt loop does **not** consume this notification as an immediate receipt wake-up. |
|
||||
| [WordCompanionFollowHub](../../PlotLine/Hubs/WordCompanionFollowHub.cs) | Retained Office.js/web Companion presence, writing-window/follow coordination and onboarding notifications. Includes `RegisterCompanion`, `CompanionHeartbeat`, `WatchCompanionPresence`, scan/build methods and server-to-Office.js `ScanCurrentDocument`/marker events. Native onboarding can be requested through this browser hub, but native execution is still acquired by HTTP. Do not route VSTO navigation through legacy user-only registration. |
|
||||
| [word-companion-host.js](../../PlotLine/wwwroot/js/word-companion-host.js), [word-companion-presence.js](../../PlotLine/wwwroot/js/word-companion-presence.js), [writing-workspace.js](../../PlotLine/wwwroot/js/writing-workspace.js), [writing-follow.js](../../PlotLine/wwwroot/js/writing-follow.js) | Wired JavaScript clients for `/hubs/word-companion-follow`: Office.js task-pane registration/25s heartbeat, browser presence/onboarding, and Writer/Context/Intent window coordination. Host view serves the Office.js source; this is separate from the Windows agent. Companion expiry monitor and capture publishers also use this hub. |
|
||||
| [StoryIntelligenceHub](../../PlotLine/Hubs/StoryIntelligenceHub.cs), [StoryIntelligenceProgressNotifier](../../PlotLine/Services/StoryIntelligenceProgressNotifier.cs) | Owned user/job/run/global progress subscriptions and publishers; JS clients in story-intelligence progress/global/review-centre and character-enrichment views. Global client has reconnect/start retry and 15s reconciliation. Existing realtime infrastructure, not a Word navigation queue. |
|
||||
| [Agent project](../../PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj), Client/VSTO projects | No `Microsoft.AspNetCore.SignalR.Client` dependency, `HubConnection`, or native subscription implementation found. A fully qualified server `SignalR.ClientProxyExtensions` call is a **publisher helper**, not a .NET client. No unused native hub-client stub was discovered. |
|
||||
|
||||
The three hubs have registered routes and wired callers; they are not merely plans. [NativeCompanionHttpTests](../../PlotLine.Tests/NativeCompanionHttpTests.cs) includes an authenticated real WebSocket `NativePresenceChanged` regression; browser recovery fixtures also exist. This is existing source/test evidence, **not a claim those tests or all legacy flows were run during this investigation**. Minified Office.js copies are not another native transport. Both the new agent SignalR subscription and Windows' proposed notification long-poll remain **unimplemented proposals**.
|
||||
|
||||
## 2. Actual navigation pipeline and scheduled waits
|
||||
|
||||
| Stage | Source/method | Timing and authority |
|
||||
| --- | --- | --- |
|
||||
| Browser request | [writer-word.js](../../PlotLine/wwwroot/js/writer-word.js), `navigate` | Captures explicit instance/session/manuscript/revision and UUID; POST `/WriterWord/Navigate` with antiforgery. R2 pin and local aborts protect the selected document. |
|
||||
| Validate/enqueue | [WriterWordController.Navigate](../../PlotLine/Controllers/WriterWordController.cs), [WriterWordService.Navigate](../../PlotLine/Services/Writer/WriterWordService.cs), [NativePresenceStore.Navigate](../../PlotLine/Services/NativeCompanion/NativePresenceStore.cs) | Ownership, accepted paragraph/chapter/scene provenance, live saved/revision/identity and acknowledged-navigation capability checked. Exact queue/outcome/duplicate receipt created; command expires in **25s**. 202 means requested. Physical acceptance/target work is hundreds of milliseconds, not the full three seconds. |
|
||||
| Agent acquisition | [TrayCoordinator.Heartbeat](../../PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs), [CloudGateway.Presence](../../PlotDirector.NativeCompanion/Agent/CloudGateway.cs), `NativePresenceController.Update` → `TakeNavigation` | Worker sleeps **500ms** between passes; unchanged acknowledged-capable documents send Presence no more often than roughly **2s** (legacy spacing **15s**). HTTP validates the current native grant and updates presence before taking the exact queue item. Requests/documents are processed serially; HTTP duration/multiple documents can add delay. No server push currently wakes this path. |
|
||||
| Local delivery | `TrayCoordinator.Queue/Exchange`, [PipeHost](../../PlotDirector.NativeCompanion/Agent/PipeHost.cs), [AgentLink](../../PlotDirector.NativeCompanion/Client/AgentLink.cs) | Bounded per-instance queue delivered in a pipe **response**, not unsolicited pipe push. .43 idle ping threshold **100ms**, worker idle sleep **25ms**; queued messages/chapter fast-poll window can deliver sooner. .42 used 1000ms. Local queue→delivery median improved 650.72→61.555ms physically. |
|
||||
| Word execution | [WordAdapter.HandleCommand](../../PlotDirector.NativeCompanion/Vsto/WordAdapter.cs), [WordAccessScheduler.Pump](../../PlotDirector.NativeCompanion/Client/WordAccessScheduler.cs) | Post to STA, then original scheduler (25ms timer; chapter batches bounded by 16 steps/15ms and author-priority scheduling). Recheck session/revision/manuscript/saved state/expiry/range; duplicate-ID guard; actual `Document.Range(...).Select()`. .43 measured selection median **28.765ms**, not the dominant measured span. COM cannot be preempted by a timer. |
|
||||
| Native result/publication | `WordAdapter.Reply` → AgentLink → `TrayCoordinator.Exchange` | Actual matching `adapter-result` sets completed/failed only for current pending ID/revision and unexpired command. Clears presence throttle state; **does not interrupt the worker's 500ms sleep** or an in-flight request. .43 adapter-result→publication median **349.14ms**. Next Presence publishes ack; store `Put` independently checks grant/book/manuscript/revision/ID/outcome expiry. |
|
||||
| Browser confirmation | `NativePresenceController` → existing hub; `writer-word.js.navigate` → `WriterWordController.Navigation` | Existing hub can notify on ack-ID change, but current navigation code sleeps **1000ms before its first receipt GET and each later GET**, for up to 30s. Only a matching authoritative completed receipt displays success. Existing status stream adds 250ms debounce, then status GET; it does not directly complete navigation. |
|
||||
|
||||
Other schedules are **not command polling fixes**: native producer selection observations are approximately 1s (timestamped before COM; R1 age limit 45s), general agent connection/renewal checks run on a 2s loop with installation heartbeat eligibility at 25s, pairing approval polls at 2s only during pairing, browser status fallback is 15s. Chapter saved-edit debounce/periodic verification are roughly 3s/~60s opportunities, not intentional navigation latency, though contention must be measured. The 10s legacy presence monitor is not native command delivery. Coordinator `Tick` also runs every 500ms for existing work/lifecycle processing; Word diagnostics are emitted on an approximately 1s cadence, which can delay log appearance without delaying the actual adapter result. Local pipe exchange timeout is 3s, reconnect backoff grows from 250ms to 5s, and the chapter fast-poll window is capped at 3s; these are failure/chapter paths, not another normal navigation cloud poll. SignalR connection keepalives/reconnect delays are transport maintenance, not normal per-navigation polling.
|
||||
|
||||
The latest physical report proves important waits and actual Word selection cost, but **server enqueue→take residence and exact viewport paint remain unmeasured**; child metric coverage is incomplete. Do not sum overlapping queue/result/selection spans or subtract unsynchronised UTC timestamps.
|
||||
|
||||
## 3. Why polling exists today
|
||||
|
||||
The native implementation is an asynchronous bearer-authenticated HTTP gateway plus request/response local pipes. Presence conveniently performs lease validation, mapping/progress exchange, command pickup and ack publication in one established path. The web retains cookie-based SignalR/Office.js integration from another client architecture. Writer added UUID-correlated receipts while preserving those native HTTP contracts. This explains the topology; source/history does **not** establish that SignalR was evaluated and rejected, or that polling is necessary for correctness. Replacing delays with wake-ups is compatible with the present separation of authorities.
|
||||
|
||||
## 4. Options compared
|
||||
|
||||
All three must retain the same validated queue, expiry, ack and low-frequency recovery/liveness. None creates durable command delivery across a server restart.
|
||||
|
||||
| Dimension | A — optimise existing polling | B — bounded authenticated HTTP notification wait | C — SignalR notification wake-ups |
|
||||
| --- | --- | --- | --- |
|
||||
| Latency | Immediate ack-worker wake and immediate/event-triggered receipt GET help, but next command acquisition still has a ~2s phase unless Presence frequency rises. Tail target uncertain. | Enqueue wakes a held request, then existing Presence acquires command. Comparable acquisition potential to C; ack wake/browser event work still needed. | Enqueue hint wakes Presence; valid adapter result wakes publication; existing browser hub wakes receipt GET. Removes all three avoidable scheduled waits without increasing permanent HTTP frequency. |
|
||||
| Complexity/reuse | Lowest initial code; reuses everything. Short polling bursts cannot reliably start at a browser click the agent has not yet heard about. | Reuses native HTTP auth/HttpClient, no new native client package. New endpoint, bounded waiter registry, subscribe/check race handling, cancellation and timeout policy must be maintained. | Medium: existing server/browser SignalR reused, new .NET client dependency and native hub authentication/lifecycle integration. No second queue or browser hub required. |
|
||||
| Recovery | Simple recurring reconciliation; worst waits persist. | One capped wait per agent/grant (not per paragraph/document), cancellation/backoff and recheck on reconnect; missed hints reconciled by Presence. | Initial-start retry, reconnect/rejoin, token/connection changes and missed-hint reconciliation required; retain Presence fallback. SignalR messages are disposable hints, not delivery guarantees. |
|
||||
| Resources | Stable current ~30 Presence requests/min per ack-capable document. A 500ms permanent spacing would approach 120/min/document before HTTP cost; each runs auth/mapping work. More aggressive rates amplify cost. | One held cancellable request per process plus timeout renewals and existing heartbeats; async waits do not need a blocked thread. Bound waiter capacity and avoid tight reissue loops. | One persistent connection per agent, small hints/keepalives plus existing heartbeats. Additional client assemblies/memory/socket/server connection cost; no claim it is free or reduces current heartbeat traffic. |
|
||||
| Security | Existing per-request auth; increasing load must not weaken checks. | Reuse native bearer; limit each wait by timeout/token lifetime, reauthorise before fulfilment, protect waiter ownership/caps. | Explicit native scheme/process-grant routing, token expiry/revocation handling and server-derived groups required; default browser hub cannot simply accept native credentials. |
|
||||
| Maintenance | Few new concepts but polling tunables and load remain coupled to UX. | Bespoke real-time notification mechanism alongside browser SignalR; own lost-wake/waiter lifecycle tests. | One established real-time framework for both network directions, standard reconnect/transports; retain a small fallback instead of a parallel custom long-poll API. |
|
||||
|
||||
Microsoft documents the native client dependency/reconnect model, authentication lifetime caveats and connection/scale costs: [.NET client](https://learn.microsoft.com/en-us/aspnet/core/signalr/dotnet-client?view=aspnetcore-10.0), [authentication](https://learn.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-10.0), [hosting/scaling](https://learn.microsoft.com/en-us/aspnet/core/signalr/scale?view=aspnetcore-10.0). SignalR may itself fall back to its supported LongPolling transport; that is distinct from implementing another custom command long-poll endpoint. Verify actual transport rather than claiming WebSockets from a library choice.
|
||||
|
||||
B's wait cannot be added unchanged to `CloudGateway.Send`: it currently cancels ordinary requests after **15s**, despite a longer HttpClient-wide timeout. A proposed 20–25s wait needs a dedicated bounded timeout/cancellation policy. Both B and C must cover **all owned live document sessions**: “only active Word document” is insufficient when Writer deliberately selected an inactive document (R2).
|
||||
|
||||
## 5. Proposed C contract and security requirements (not implemented)
|
||||
|
||||
1. **Server enqueue → hint:** after the existing queue accepts a command, publish a bounded/coalesced hint outside its lock, routed using the lease's **server-derived user + native grant/process identity**, with at most document/command identifiers. Never send prose, offsets, credentials or a completion assertion. Cover central `NativePresenceStore.Navigate` callers (Writer, historical native review, Context/Intent) without changing their different success contracts. A hint failure cannot undo valid queueing, stall 202 or fabricate success. No network await under store/coordinator locks and no unbounded fire-and-forget task fan-out.
|
||||
2. **Agent connection:** add a read-only native-scheme hub endpoint (proposed name `/hubs/native-companion-agent`), separate from existing cookie/Office.js hubs. One `Microsoft.AspNetCore.SignalR.Client` connection in the **agent**, not VSTO, using CloudGateway's existing approved access/renewal state. .NET headers can carry its current Bearer token; do not copy browser cookies, turn the Data Protection token into JWT, add a second credential store or open broad query-token support. No caller-chosen user/group/lease memberships. SignalR connection ID is **not** the installation/process `NativeCompanion.Connection` identity.
|
||||
3. **Expiry/revocation:** current `DesktopAuthentication` validates header/user/stamp/installation on HTTP authentication, but puts expiry in a custom claim, **not `AuthenticationProperties.ExpiresUtc`**. Persistent hubs cache principals; the current defaults therefore cannot be assumed to enforce ten-minute token expiry or mid-connection revocation. Establish ticket expiry plus hub `CloseOnAuthenticationExpiration`, renew/reconnect via existing protected state, and explicitly invalidate/remove old hub memberships on sign-out, revocation/account/process changes. Revalidate applicable subscription authority and gate publication to current grants. Every command acquisition still performs existing HTTP authorisation; even a stale/forged hint cannot authorise execution. Test custom-scheme behaviour, not JWT sample assumptions. (Microsoft authentication guidance above.)
|
||||
4. **One bounded wake path:** hints only schedule the existing serialized Presence work for the exact owned session, bypassing idle spacing for pending commands. Matching adapter result schedules that same worker immediately; no direct HTTP/COM from the STA or inside a lock. Coalesce concurrent hints, preserve sequence ordering and fresh snapshot generation, prioritise the hinted session fairly, and recheck pending work after any in-flight response. Do not let another document's slow request starve the selected target or run overlapping same-session sends. Never refresh `WordObservedUtc` from a notification/reconnect/heartbeat.
|
||||
5. **Browser reuse:** extend the existing `NativePresenceChanged` handler/shared stream to wake a **pending** Writer receipt GET immediately, independently of the 250ms general-status debounce. Query `/WriterWord/Navigation` with the captured ID/instance/session/book; do not display success from hub payload. Install pending observation before POST, check once immediately after 202, coalesce fetches and recheck after races. Retain the existing bounded receipt polling/timeout when a hint is lost, and status reconciliation on reconnect/return. No extra permanent poller, extra hub connection, implicit focus change or document choice.
|
||||
|
||||
R1 freshness, R2 pinned exact session, authorised book/manuscript/provenance/revision/saved checks, queue/grant ownership, UUID/idempotency, 25s expiry/cancellation and matching native completion remain unchanged. Old agents continue normal polling; a new agent must safely fall back if the new hub is missing/blocked. Hub failure alone must not flicker an otherwise valid HTTP document connection offline.
|
||||
|
||||
## 6. Reconnection, operations and scoped implementation plan
|
||||
|
||||
**Recovery is reconciliation, not replay.** On initial connection/reconnect, re-establish server-derived routing then check current owned sessions using the existing Presence path; handle enqueue-before-subscribe/disconnect races. Add bounded initial-start and exhausted-reconnect retries; automatic reconnect is opt-in and does not replace initial-start retry. On account/server/process change cancel the old connection and pending hints. Neither SignalR nor long-poll renews producer observations. Server restart loses the existing in-memory queue/outcomes; stale pending browser work becomes unconfirmed/invalidated/missing, never “completed” or automatically replayed. Accepted manuscript persistence is unaffected.
|
||||
|
||||
Read-only Atlas Development Nginx inspection shows HTTP/1.1 Upgrade forwarding to localhost:5050 and 120s proxy read/send timeouts. This supports the existing topology, but does not prove every Windows network negotiates WebSockets. Verify negotiate/auth/WebSocket upgrade/idle survival and managed fallback through Development before packaging. No reverse-proxy change is assumed necessary; Production was not inspected. No broker/service/schema migration is proposed for the current single-process deployment.
|
||||
|
||||
Scale limit is explicit: SignalR consumes persistent connection resources and needs appropriate routing/backplane when scaling. More importantly, the **command/lease store is process-local**: a Redis SignalR backplane or per-connection stickiness alone would not make browser enqueue and agent HTTP take share a queue across replicas. Multi-instance command-store routing/durability is a separate design; do not claim this plan solves it.
|
||||
|
||||
After approval, implement in this order:
|
||||
|
||||
1. Add per-command monotonic **server enqueue→take** timing and browser wake→receipt timing; preserve .42/.43 spans, coverage counts and no-prose diagnostics. Define the tiny hint/lifecycle contract and bounded publisher. Instrumentation must not become command authority.
|
||||
2. Reuse browser SignalR events for pending receipts and wake the existing agent ack publication path. These shared improvements are useful under A/B/C and have isolated tests.
|
||||
3. Add native-scheme hub mapping and lifecycle/expiry/revocation handling; attach one standard .NET client to CloudGateway/TrayCoordinator lifecycle, retaining HTTP fallback. No VSTO/COM transport change, no custom long-poll alongside it.
|
||||
4. Qualify on Atlas in isolated HTTP/SignalR/browser/native fixtures; deploy Development only **under subsequent implementation/deployment authorisation**, verify source/hash and compatibility. Native dependency/publish inventory and existing MSI/CAB/signature checks need requalification. Prepare matched version metadata/package only in the separately authorised implementation/Windows workflow; preserve installed .43 rollback. Windows owns final build/sign/install and physical benchmarks.
|
||||
|
||||
## 7. Expected improvement and acceptance gates
|
||||
|
||||
C should remove the command-acquisition ~0–2s polling phase, ack worker ~0–500ms scheduling phase and browser ~0–1s receipt phase from the healthy warm path. **This is a source-based prediction, not a measured subtraction from 3373ms**: phases overlap and queue residence is not yet measured. Server target validation (~0.14s chapter/~0.4s scene in the retained samples), HTTP trips (~0.09s native), local .43 delivery/execution, browser scheduling, auth/renewal and contention remain. Around **one second warm confirmation is a plausible engineering goal**, not a guaranteed p90/worst or physical click-to-paint claim. Under-two-second warm navigation still needs physical proof; faster receipt display alone is insufficient. The small ten-request samples and .43 having two authenticated document sessions versus one earlier further limit direct before/after percentile predictions.
|
||||
|
||||
Required qualification:
|
||||
|
||||
- Real authenticated hub integration: cookie denied on native endpoint, native token denied where cookie-only is intended; forged/cross-user/process/session hints, expired/revoked/locked/stamp-changed approval, renewal while connected, account/server switches and legacy grants. Verify expiry closes connections with this custom handler, not merely a mocked clock flag.
|
||||
- Queue-before-connect, lost/duplicate/out-of-order hints, notification send failure, reconnect exhaustion, unsupported hub, blocked WebSockets/SignalR fallback, shutdown and server restart. Prove eventual HTTP recovery without duplicate execution or false completion; cap connections/pending hints/retries and measure idle/active resources.
|
||||
- R1 fresh/stale/delayed producer frames and continuing transport; R2 selected/unselected close/reopen, same-property copies and inactive chosen document; multiple Word instances/slow document requests. Hints cannot renew UI proof, guess mapping or choose another session.
|
||||
- Matching/failed/late/expired adapter results, revision change/cancel before take and before execution, duplicate UUIDs, receipt race before POST returns, wrong-user receipts; completed only from authoritative native outcome. Reuse native foundation/chapter/observation, full application executable harness, `NativeCompanionHttpTests`, current Writer Word/Review/F1/F2/chooser and installed-PWA return qualification.
|
||||
- Repeat the controlled .43 target sequence with actual matching Word landing, same document/session count and normal periodic verification. Report cold versus warm, median/p90/worst, every span's sample coverage, enqueue→take, actual foreground/side-by-side and separate visible landing versus confirmed receipt. Confirm the user's <2s warm target (preferably ~1s), using an agreed sample/gate; do not cherry-pick or infer viewport timing from an ack.
|
||||
|
||||
No implementation approval is inferred from this assessment. The architectural recommendation is **C with existing HTTP recovery**, not an additional parallel transport or a second navigation system.
|
||||
Loading…
x
Reference in New Issue
Block a user