From 269bb324ca4533d547e9838b3c51a30416b3c05d Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Fri, 6 Nov 2026 22:11:34 +0000 Subject: [PATCH] Integrate native manuscript capture with the existing import wizard --- ...026-11-06-native-integration-correction.md | 108 +++++++++++++++++ Docs/WordCompanion/WindowsHandover/README.md | 10 ++ .../Agent/CloudGateway.cs | 10 +- .../Agent/PipeHost.cs | 4 +- .../Agent/TrayApplication.cs | 18 +-- .../Agent/TrayCoordinator.cs | 43 ++++--- .../Client/AgentLink.cs | 2 +- .../DeveloperVersion.props | 2 +- .../Protocol/ManuscriptCapture.cs | 13 +++ .../Protocol/Messages.cs | 2 + .../Protocol/TrayContracts.cs | 4 + .../Tests/TrayTests.cs | 19 ++- .../Vsto/WordAdapter.cs | 13 ++- .../Browser/native-companion-workspace.cjs | 6 +- .../Browser/word-companion-regressions.cjs | 5 +- .../NativeManuscriptCaptureTests.cs | 53 +++++++++ PlotLine.Tests/NativeTrayIntegrationTests.cs | 3 +- PlotLine.Tests/Program.cs | 7 +- .../Sql/NativeManuscriptCapture.sql | 43 +++++++ PlotLine.Tests/WordMarkerSecurityTests.cs | 8 ++ .../NativeManuscriptCaptureController.cs | 21 ++++ .../Controllers/NativePresenceController.cs | 13 ++- .../Controllers/NativeWorkspaceController.cs | 4 +- PlotLine/Controllers/OnboardingController.cs | 3 +- PlotLine/Data/ManuscriptCaptureRepository.cs | 19 +++ .../Help/Articles/WordCompanion/Install.md | 12 +- PlotLine/Hubs/WordCompanionFollowHub.cs | 35 ++++-- PlotLine/Models/ManuscriptScanModels.cs | 5 + PlotLine/Program.cs | 3 + .../Services/ManuscriptScanPreviewStore.cs | 44 +++---- .../NativeManuscriptCapture.cs | 110 ++++++++++++++++++ .../NativeCompanion/NativePresenceStore.cs | 9 +- PlotLine/Sql/237_DurableManuscriptCapture.sql | 51 ++++++++ .../Views/NativeWorkspace/Workspace.cshtml | 7 +- .../Views/Onboarding/BuildComplete.cshtml | 7 +- PlotLine/Views/Onboarding/Index.cshtml | 4 +- .../Views/Shared/_ApplicationShell.cshtml | 2 +- PlotLine/Views/Shared/_Layout.cshtml | 1 - .../Shared/_WritingCompanionLayout.cshtml | 2 +- PlotLine/wwwroot/css/site.css | 5 + .../wwwroot/js/native-companion-status.js | 11 +- .../wwwroot/js/native-companion-workspace.js | 18 +-- .../wwwroot/js/word-companion-presence.js | 22 +++- PlotLine/wwwroot/js/writing-workspace.js | 15 ++- 44 files changed, 676 insertions(+), 120 deletions(-) create mode 100644 Docs/WordCompanion/2026-11-06-native-integration-correction.md create mode 100644 PlotDirector.NativeCompanion/Protocol/ManuscriptCapture.cs create mode 100644 PlotLine.Tests/NativeManuscriptCaptureTests.cs create mode 100644 PlotLine.Tests/Sql/NativeManuscriptCapture.sql create mode 100644 PlotLine/Controllers/NativeManuscriptCaptureController.cs create mode 100644 PlotLine/Data/ManuscriptCaptureRepository.cs create mode 100644 PlotLine/Services/NativeCompanion/NativeManuscriptCapture.cs create mode 100644 PlotLine/Sql/237_DurableManuscriptCapture.sql diff --git a/Docs/WordCompanion/2026-11-06-native-integration-correction.md b/Docs/WordCompanion/2026-11-06-native-integration-correction.md new file mode 100644 index 00000000..7b1503b4 --- /dev/null +++ b/Docs/WordCompanion/2026-11-06-native-integration-correction.md @@ -0,0 +1,108 @@ +# Native Companion integration correction — 6 November 2026 + +## Scope and delivery + +Shared branch: `codex/word-companion-native-phase1-20261104`. Clean Atlas checkout was fetched and fast-forwarded from bda826b to Windows handover **dcaab6e** before development. No alternate branch/worktree, Production change, Windows package build or installation. Existing Windows maintenance/installer fixes are preserved. + +Managed/VSTO source version: **1.0.0.13**. This is source awaiting Windows qualification, not an installed or qualified release. `WindowsValidation/Setup/Release.json` remains pinned to **1.0.0.12** deliberately; the unified installer must be aligned and qualified on Windows. The fetched maintenance report records an unresolved MSI payload-copy blocker; this work does not claim to fix it. + +## Implemented communication path + +```mermaid +sequenceDiagram + participant W as Word STA scheduler + participant A as Existing per-user agent + participant P as PlotDirector presence + participant I as Existing manuscript wizard + participant D as SQL accepted-source store + participant S as Existing analysis/review services + A->>P: authenticated heartbeat (exact instance/session/manuscript/book/revision) + I->>P: explicit Import manuscript request + P-->>A: negotiated wizard-capture command on heartbeat + A->>W: existing bounded snapshot request with capture ID + W-->>A: validated paragraph fragments in scheduled batches + A->>I: authenticated complete capture (no AI inside Word) + I->>D: immutable source preview + hash + D-->>I: committed acceptance + I-->>A: acknowledgement of exact capture ID/revision + I-->>I: existing chapter review + Note over W,I: Word and agent may disconnect after acceptance + I->>S: explicit existing scene analysis and subsequent review stages + S->>D: existing canonical manuscript sources/build persistence +``` + +The new endpoint is an intake adapter, not another importer or AI engine. `NativeManuscriptCapture.Build` maps native fragments into existing `ManuscriptScanPreview`/source paragraphs. Wizard coordinates are **one-based paragraph indices**; actual Word character positions are kept separately. Existing chapter and scene marker IDs are reused only when they belong to the authorised book. Heading 1/marker detection is not labelled AI analysis. Character, location, asset, summary and existing review services are retained. + +`StartOnboardingManuscriptScan` keeps its Office.js signature and fallback. Native capture is negotiated with `wizard-capture-v1`; old native installations receive an update-required explanation rather than an unsupported command. Routing requires one unambiguous active document for the wizard's book. It never selects an arbitrary latest Word connection. + +## Registration and save-state corrections + +- Reconciliation preserves live document records, association and heartbeat sequence instead of unregistering/recreating every document. +- Short pipe reconnects can restore a verified session-only association for the same manuscript/session/authentication context for two minutes. This is not credential persistence across agent restarts. +- Process-wide monotonic sequences avoid per-document counter reset on reconnect. Sequence-conditioned removal prevents delayed disconnect requests deleting a newer registration. +- Invalid/foreign saved markers are cleared without rejecting otherwise authorised document liveness. Book authorisation remains mandatory. Cursor coordinates are retained in accepted leases. +- Presence success updates the local acknowledgement timestamp only after HTTP success. Failures retry at a bounded interval and identify registration/HTTP failure instead of calling everything a “saved-data request.” +- Website header and writing-workspace Hub status consume the native lease store, with Office.js compatibility fallback. Website connectivity is unchanged. The redundant strip below the ribbon is removed. +- Word selection observations include `Document.Saved` with `BackgroundSavingStatus == 0`, on the Word thread. BeforeSave never cancels, waits for network, forces a save or claims success. It invalidates the observation revision and pending extraction conservatively. +- Word's saved-state observation is distinct from PlotDirector's exact capture acknowledgement. Checking connection does not upload prose. A fresh, explicitly requested wizard capture is the manual synchronisation fallback. + +## Durable acceptance and safety + +Migration **237_DurableManuscriptCapture.sql** adds `OnboardingManuscriptCaptures` and the Dapper-only `OnboardingManuscriptCapture` procedure. These are accepted onboarding staging sources, not a second canonical manuscript store. Canonical chapter/scene sources continue to be written by existing import services. + +Persistence checks active project access, scopes source retrieval by author, validates JSON, hashes immutable payloads and rejects conflicting reuse of a preview ID. Book deletion cascades staging-source removal. Wizard reset clears the current pointer without destroying explicitly addressable accepted sources; starting a new scan cannot resurrect an older preview while the scan is running. No credentials or server-bound encrypted capture are put into Word or the source record. + +Transfer requests expire after 20 minutes, or when their exact Word lease disappears before acceptance. Failures/cancellation notify the existing wizard. Once accepted, source retrieval does not depend on live presence and can recover after a server restart. Transfer instructions in progress are intentionally ephemeral and are not automatically replayed after restart. + +The agent permits one pending extraction/upload at a time, uses the existing 16 Mi-character/fragment-budget limits and 200,000-fragment ceiling, and uses a 120-second HTTP intake timeout. Request bodies are bounded at 100 MiB; these are maxima, not a guarantee that every document below a word count fits. No prose enters diagnostics. Explicit browser wizard requests authorise only that exact transfer; the older optional retained-AI-capture permission is not silently expanded into a standing upload permission. + +Repeated delivery of the same capture ID/content is idempotent; altered content is rejected. Acceptance failure cannot become a successful tray acknowledgement. Review and build are still explicit actions; capture completion alone does not create canonical story records or automatically start AI. + +## Normal Companion and writing windows + +The normal tray UI now contains sign-in, connection checks, active document, authorised book association, settings and diagnostics. Chapter detection/selection/AI controls and Context/Intent launch controls are removed from the visible interface. Existing extraction, AI and historic review contracts remain for compatibility; they are not a competing normal author workflow. + +Website launchers use one stable named window for Context and one for Intent across book changes. Repeated launches from the launcher reuse/focus the existing window without unnecessarily reloading an unchanged scope. Book scope stays in the URL. Dedicated windows reuse the existing theme-aware `_WritingCompanionLayout`, register their roles with existing writing-window infrastructure, and subscribe to native presence invalidations. The iframe fills remaining viewport height instead of a fixed `vh` panel. + +Each workspace has independent manual scene selection and following. Manual selection pauses following; no unresolved scene is guessed from stale positions. Saved data remains available without Word. Context and Intent remain distinct; no new AI intent engine or planning records were introduced. + +## Material limitations — do not call this full native migration + +1. **No real Word/VSTO execution or Windows visual/performance qualification on Atlas.** The managed Windows target compiles; the VSTO host and packages have not been built here. +2. **Newly imported markers are not written back into Word by this change.** Native server builds record `MarkerStatus=NotRequested`, separately from completed canonical import. Office.js marker/save acknowledgement remains unchanged. +3. Scene mappings made from an approved native capture are valid only for its exact document session, manuscript, revision and saved state. Dirty/changed documents do not reuse positional evidence. Existing marks can be read through bounded snapshots; this is not proven continuous scene tracking while typing. Fresh capture/manual saved-scene navigation is required when no trustworthy mapping exists. +4. `Document.Saved` observation is not an independently verified filesystem save-completion event. Native revision observation has the existing limitations for same-length edits between observations; BeforeSave invalidation and conservative dirty-state handling avoid treating that as acknowledged prose synchronisation. +5. Accepted **source** is durable. Existing later-stage review/job persistence semantics are retained, not rewritten; this is not a guarantee that every in-flight analysis resumes after an application-server crash. No live paid-provider analysis was requested for this handoff. +6. Browser popup/PWA focus is subject to browser policy. Actual installed-PWA window chrome and monitor placement need the normal Windows human pass. +7. Setup's version12 maintenance/copy blocker and version13 installer alignment remain Windows work. Do not substitute direct `.vsto` registration or another installer. + +## Verification + +- `dotnet build PlotLine.slnx --no-restore`: zero warnings/errors. +- Normal executable regression harness: **415 passed**. +- Native portable harness: **217 passed**, including actual named-pipe foundations, exact-document capture frames, reconciliation/reconnect association, background handoff and acknowledgement. +- Native intake tests: blank and 220,000-word fragmented source, exact prose, one-based paragraph/character mapping, incomplete input, wrong author/grant, persistence failure, immutable retries, disconnected Word, simulated server recovery and stale/dirty scene mapping. +- Actual loopback HTTP/WebSocket security regression passed with a synthetic provider: browser-approved pairing, antiforgery, bearer/security-stamp checks, book/subscription access, AI idempotency and presence invalidation. No live paid-provider call. +- Browser: `native-companion-workspace.cjs` and `word-companion-regressions.cjs`: following/manual pause, disconnection, stale responses, scene scope, shared badge, distinct/reused role windows and book changes. +- Guarded real SQL regression: `PlotLine.Tests/Sql/NativeManuscriptCapture.sql` on **PlotDirector_Phase2_20261103_2305**; exact recovered prose, duplicate safety, other-account denial, revoked-access denial, current-pointer reset, book-deletion cleanup and unauthorised write refusal. Fixtures rolled back. +- Development migration applied only after idle-work gates and copy-only/checksummed backup with `RESTORE VERIFYONLY`: `/var/opt/mssql/backup/PlotDirector_Development_before_native_capture_20261106T220229Z.bak`. +- Development deployment and authenticated smoke results are recorded in the delivery addendum after deployment; nothing here claims live Windows integration. + +## Windows qualification pass + +Keep the shared branch, inspect/preserve local work, identify the configured remote, fetch and fast-forward. Build the exact pushed source using the existing entry point: + +```powershell +.\PlotDirector.NativeCompanion\WindowsValidation\Update-WordCompanion.ps1 -CertificateThumbprint '' +``` + +It prepares a signed developer package, not an installation. Do not run installation unattended, launch Word, close applications or invoke Computer Use during the build pass. Preserve the actual qualified installation and settings. In the existing `WindowsValidation/Setup` architecture, align release/version/product identity to the newly qualified 1.0.0.13 payload, resolve/verify the already reported maintenance-copy blocker and exercise existing payload/package/upgrade tests. Do not bypass source/version guards or introduce another installer. Installer outputs must contain both VSTO and tray; inspect the real interactive user's installation rather than sandbox-local registry evidence. + +Human Word checks on an isolated test book: + +1. Link a saved test manuscript; verify top-right website status and tray registration agree. Reconnect the pipe/agent and recheck association. Try three open books. +2. From website Import manuscript, read the correct selected Word document; observe progress/cancellation, then accepted chapter review. Check exact prose and paragraph mapping. Do not confirm import against a populated primary book. +3. Close Word/agent after acceptance; run existing scene/location/character/asset/summary review stages in the browser. Confirm import only into the isolated test book and test duplicate/conflict handling. +4. Open Context and Intent twice each; verify separate reused windows, full-height layout, correct book and independent manual pause. Check saved information with Word disconnected. +5. Observe saved/dirty Word state. Edit/save during extraction; verify interruption/retry and no false acknowledgement. Do not mistake marker-free snapshot mapping for continuous live following after edits. +6. Inspect native COM timings, typing/scroll/save/close responsiveness on a 200,000+ word document. Confirm no unrequested manuscript edits or uploads. diff --git a/Docs/WordCompanion/WindowsHandover/README.md b/Docs/WordCompanion/WindowsHandover/README.md index 49684b14..2e41febc 100644 --- a/Docs/WordCompanion/WindowsHandover/README.md +++ b/Docs/WordCompanion/WindowsHandover/README.md @@ -1,3 +1,13 @@ +# Current integration handover — 6 November + +Read [the native integration correction report](../2026-11-06-native-integration-correction.md) first. It supersedes the historical version12 UI/workflow instructions below: current application source is **1.0.0.13**, with manuscript import owned by the existing website wizard and a simplified tray. Do not restore the duplicate tray analyser or redesign the managed UI on Windows. + +The fetched Windows baseline is **dcaab6e**. Existing Setup maintenance fixes are preserved; its release metadata remains **1.0.0.12** and its reported MSI copy blocker still requires Windows qualification. Align and test the existing unified installer for version13 deliberately. No installation, Word launch, Computer Use, sandbox-local installation claim or forced application closure is authorised by an unattended build pass. The report contains the current commands, limits and acceptance checks; its delivery addendum records the exact application commit. + +The older prompts below remain useful for non-interactive environment/installer safety, but their version pins and former tray-analysis instructions are historical. + +--- + # Controlled Windows handover Execute in order: diff --git a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs index c8a9ec69..9b2abb6a 100644 --- a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs +++ b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs @@ -113,19 +113,21 @@ public sealed class CloudGateway : IDisposable =>await Send(HttpMethod.Get,path,null,expectedContext); public async Task Post(string path,object body,Guid expectedContext) =>await Send(HttpMethod.Post,path,body,expectedContext); + public async Task FailCapture(Guid id,Guid context){try{await Send(HttpMethod.Delete,"api/native-companion/manuscript-capture/"+id,null,context);}catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException or ObjectDisposedException){}} + public async Task Capture(ManuscriptCapture capture,Guid context){var result=await Send(HttpMethod.Post,"api/native-companion/manuscript-capture",capture,context);if(result.CaptureRequestId!=capture.RequestId||result.Revision!=capture.Revision)throw new InvalidDataException("Server did not acknowledge this manuscript capture. Update or reconnect before retrying.");return result;} private async Task Send(HttpMethod method,string path,object? body,Guid context) { Uri site;string access;lock(gate){Expire();if(context!=authenticationContext||token==null)throw new InvalidOperationException("Sign in again and reselect the book.");site=origin!;access=token;} - using var stop=new CancellationTokenSource(TimeSpan.FromSeconds(15));using var request=new HttpRequestMessage(method,new Uri(site,path));request.Headers.Authorization=new("Bearer",access);if(body!=null)request.Content=JsonContent.Create(body,options:Json); + using var stop=new CancellationTokenSource(TimeSpan.FromSeconds(path=="api/native-companion/manuscript-capture"?120:15));using var request=new HttpRequestMessage(method,new Uri(site,path));request.Headers.Authorization=new("Bearer",access);if(body!=null)request.Content=JsonContent.Create(body,options:Json); try { using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,stop.Token); if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(authenticationContext==context){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";}throw new InvalidOperationException("Sign-in expired. Connect again.");} - if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=DateTime.UtcNow;health.Explanation="Server rejected the saved-data request. See the document result.";if(response.StatusCode==HttpStatusCode.Forbidden)books=[];}throw new InvalidOperationException(response.StatusCode==HttpStatusCode.Forbidden?"Access denied or subscription unavailable.":response.StatusCode==HttpStatusCode.NotFound?"No saved chapter/scene matches this book and Word marker.":"Server request failed. Check connection or update the server.");} + if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=DateTime.UtcNow;health.Explanation=$"PlotDirector rejected { (path.EndsWith("/presence",StringComparison.Ordinal)?"document registration":"the request") } (HTTP {(int)response.StatusCode}). Reconnect or check the selected book.";if(response.StatusCode==HttpStatusCode.Forbidden){if(body is NativePresence denied)books=books.Where(b=>b.BookId!=denied.BookId).ToArray();else if(path=="api/native-companion/books")books=[];}}throw new InvalidOperationException(response.StatusCode==HttpStatusCode.Forbidden?"Access denied or subscription unavailable.":response.StatusCode==HttpStatusCode.NotFound?"No saved chapter/scene matches this book and Word marker.":"Server request failed. Check connection or update the server.");} await using var stream=await response.Content.ReadAsStreamAsync(stop.Token);using var buffer=new MemoryStream();var bytes=new byte[8192];int size; while((size=await stream.ReadAsync(bytes,stop.Token))>0){if(buffer.Length+size>1024*1024)throw new InvalidDataException();buffer.Write(bytes,0,size);}buffer.Position=0; var result=await JsonSerializer.DeserializeAsync(buffer,Json,stop.Token); - lock(gate){if(context!=authenticationContext)throw new InvalidOperationException("Connection changed; discarded old response.");health.Server="online";health.Authentication="verified";health.VerifiedUtc=DateTime.UtcNow;} + lock(gate){if(context!=authenticationContext)throw new InvalidOperationException("Connection changed; discarded old response.");health.Server="online";health.Authentication="verified";health.VerifiedUtc=DateTime.UtcNow;if(path.EndsWith("/presence",StringComparison.Ordinal))health.Explanation="Document heartbeat verified by PlotDirector.";} return result??throw new InvalidDataException(); } catch(OperationCanceledException){lock(gate)if(context==authenticationContext){health.Server="degraded";health.Explanation="Server verification timed out. Check connection before continuing.";}throw;} @@ -143,7 +145,7 @@ public sealed class CloudGateway : IDisposable public void OpenCompanionPage(string path,Guid context) {lock(gate){Expire();if(context!=authenticationContext||token==null||origin==null)throw new InvalidOperationException("Sign in first.");if(!path.StartsWith("/native-companion/",StringComparison.Ordinal))throw new InvalidDataException();var url=new Uri(origin,path);if(url.GetLeftPart(UriPartial.Authority)!=origin.GetLeftPart(UriPartial.Authority))throw new InvalidDataException();openBrowser(url.AbsoluteUri);}} public async Task Presence(Guid instance,Guid session,NativePresence presence,Guid context)=>await Post($"api/native-companion/instances/{instance}/documents/{session}/presence",presence,context); - public async Task RemovePresence(Guid instance,Guid session){Guid context;lock(gate)context=authenticationContext;try{await Send(HttpMethod.Delete,$"api/native-companion/instances/{instance}/documents/{session}/presence",null,context);}catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException or ObjectDisposedException){}} + public async Task RemovePresence(Guid instance,Guid session,long? throughSequence=null){Guid context;lock(gate)context=authenticationContext;try{await Send(HttpMethod.Delete,$"api/native-companion/instances/{instance}/documents/{session}/presence?throughSequence={throughSequence}",null,context);}catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException or ObjectDisposedException){}} public async Task CancelRemote(Guid id) { try diff --git a/PlotDirector.NativeCompanion/Agent/PipeHost.cs b/PlotDirector.NativeCompanion/Agent/PipeHost.cs index 6b5c44b2..be2c6b08 100644 --- a/PlotDirector.NativeCompanion/Agent/PipeHost.cs +++ b/PlotDirector.NativeCompanion/Agent/PipeHost.cs @@ -56,8 +56,8 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action{tabs.SelectedIndex=1;site.Focus();}));header.Controls.Add(Button("Settings",()=>tabs.SelectedIndex=1));header.Controls.Add(Button("Help",()=>cloud.OpenSite("help")));layout.Controls.Add(header,0,0); + header.Controls.Add(Button("Connect / Sign in",()=>{tabs.SelectedIndex=0;site.Focus();}));header.Controls.Add(Button("Settings",()=>tabs.SelectedIndex=0));header.Controls.Add(Button("Help",()=>cloud.OpenSite("help")));layout.Controls.Add(header,0,0); layout.Controls.Add(status,0,1);layout.Controls.Add(nextStep,0,2); var manuscript=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=2,Padding=new(12)};manuscript.ColumnStyles.Add(new(SizeType.Percent,100));manuscript.ColumnStyles.Add(new(SizeType.AutoSize)); manuscript.Controls.Add(new Label{Text="CURRENT MANUSCRIPT",AutoSize=true,Font=new(Font,FontStyle.Bold)},0,0); manuscript.Controls.Add(Button("Use active Word document",()=>{var active=control.Documents.FirstOrDefault(d=>d.Active);if(active!=null){selected=active.Session;documents.SelectedItem=active;chapterKey="";}}),1,0); manuscript.Controls.Add(documents,0,1);manuscript.SetColumnSpan(documents,2);manuscript.Controls.Add(books,0,2);manuscript.Controls.Add(bookButton,1,2);manuscript.Controls.Add(remember,0,3);manuscript.SetColumnSpan(remember,2);layout.Controls.Add(manuscript,0,3); remember.Text="Remember this book when I save the document";bookButton.Text="Link book";detect.Text="Find chapters";review.Text="Review scenes in PlotDirector"; - var actions=new FlowLayoutPanel{AutoSize=true,Dock=DockStyle.Fill,WrapContents=true,Padding=new(0,8,0,8)};actions.Controls.AddRange([detect,analyse,cancel,review,contextAction,intentAction]);layout.Controls.Add(actions,0,4); + var actions=new FlowLayoutPanel{AutoSize=true,Dock=DockStyle.Fill,WrapContents=true,Padding=new(0,8,0,8)};actions.Controls.AddRange([Button("Open PlotDirector",()=>cloud.OpenSite()),Button("Check document connection",()=>control.RefreshPresence(selected))]);layout.Controls.Add(actions,0,4); analyse.Tag="primary"; var activity=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=1,Padding=new(0,4,0,10)};activity.ColumnStyles.Add(new(SizeType.Percent,100));activity.Controls.Add(progressText);activity.Controls.Add(progress);layout.Controls.Add(activity,0,5); var chapterTab=new TabPage("Your chapters"){Padding=new(12)};chapterTab.Controls.Add(chapters);chapters.DrawMode=DrawMode.OwnerDrawFixed;chapters.ItemHeight=(int)Math.Round(52*DeviceDpi/96d);DpiChanged+=(_,_)=>{chapters.ItemHeight=(int)Math.Round(52*DeviceDpi/96d);chapters.Invalidate();};chapters.IntegralHeight=false;chapters.BorderStyle=BorderStyle.None; @@ -66,8 +66,8 @@ internal sealed class CompanionWindow:Form var settingsLayout=new TableLayoutPanel{Dock=DockStyle.Fill,ColumnCount=1,RowCount=4};settingsLayout.RowStyles.Add(new(SizeType.AutoSize));settingsLayout.RowStyles.Add(new(SizeType.AutoSize));settingsLayout.RowStyles.Add(new(SizeType.Percent,100));settingsLayout.RowStyles.Add(new(SizeType.AutoSize));settingsLayout.ColumnStyles.Add(new(SizeType.Percent,100)); settingsLayout.Controls.Add(new Label{Text="Your PlotDirector website · enter its HTTPS address, then approve sign-in in your browser.",AutoSize=true,Dock=DockStyle.Fill}); var connection=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=2};connection.ColumnStyles.Add(new(SizeType.Percent,100));connection.ColumnStyles.Add(new(SizeType.AutoSize));connection.Controls.Add(site,0,0);connection.Controls.Add(Button("Connect / Sign in",()=>cloud.Connect(site.Text.Trim())),1,0);settingsLayout.Controls.Add(connection);settingsLayout.Controls.Add(diagnostics); - var options=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true};options.Controls.AddRange([Button("Check connection",()=>_ = cloud.CheckConnection()),Button("Sign out",()=>cloud.SignOut()),Button("Open support folder",()=>System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(directory){UseShellExecute=true}))]);settingsLayout.Controls.Add(options);settings.Controls.Add(settingsLayout);tabs.TabPages.AddRange([chapterTab,settings]);layout.Controls.Add(tabs,0,6); - layout.Controls.Add(new Label{AutoSize=true,Dock=DockStyle.Fill,Padding=new(0,12,0,0),Text="Your words stay yours. Analysis uploads only chapters you confirm. Import needs a separate preview and confirmation."},0,7);Controls.Add(layout); + var options=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true};options.Controls.AddRange([Button("Check connection",()=>_ = cloud.CheckConnection()),Button("Sign out",()=>cloud.SignOut()),Button("Open support folder",()=>System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(directory){UseShellExecute=true}))]);settingsLayout.Controls.Add(options);settings.Controls.Add(settingsLayout);tabs.TabPages.Add(settings);layout.Controls.Add(tabs,0,6); + layout.Controls.Add(new Label{AutoSize=true,Dock=DockStyle.Fill,Padding=new(0,12,0,0),Text="Import, analysis, Context and Intent are available in PlotDirector. Word text changes only through your own authoring actions."},0,7);Controls.Add(layout); tips.SetToolTip(analyse,"Choose a linked book and select chapters first. Sends prose only after you confirm.");tips.SetToolTip(review,"Open saved scene suggestions and approve them before importing.");tips.SetToolTip(detect,"Reads Heading 1 chapter boundaries without changing your words."); ApplyTheme();Microsoft.Win32.SystemEvents.UserPreferenceChanged+=OnPreferences; documents.SelectedIndexChanged+=(_,_)=>{if(!refreshing&&documents.SelectedItem is TrayDocument d){selected=d.Session;chapterKey="";RefreshState();}}; @@ -77,7 +77,7 @@ internal sealed class CompanionWindow:Form bookButton.Click+=(_,_)=>Safe(()=>{if(books.SelectedItem is not Protocol.CompanionBook book)return;if(remember.Checked&&MessageBox.Show("Remember this book in Word document metadata? This marks the document modified. It does not save or change prose.","Remember association",MessageBoxButtons.OKCancel)!=DialogResult.OK)return;control.SelectBook(selected,book.BookId,remember.Checked);}); analyse.Click+=(_,_)=>Safe(()=>{var chosen=chapters.CheckedItems.Cast().ToArray();if(chosen.Length==0)throw new InvalidOperationException("Select one or more chapters first.");var d=Current??throw new InvalidOperationException("Open a Word document.");if(MessageBox.Show($"Send {chosen.Length} selected chapters for the chosen book to PlotDirector AI? This uploads manuscript prose, may retain an encrypted import capture if you approved that permission at sign-in, and may incur AI costs. Existing Word text and saved story records will not change.","Confirm chapter analysis",MessageBoxButtons.OKCancel)==DialogResult.OK)control.Analyse(d.Session,chosen.Select(c=>c.Start));}); review.Click+=(_,_)=>Safe(()=>Open("review"));contextAction.Click+=(_,_)=>Safe(()=>Open("context"));intentAction.Click+=(_,_)=>Safe(()=>Open("intent"));tips.SetToolTip(contextAction,"Link an authorised book to open its reference workspace.");tips.SetToolTip(intentAction,"Link an authorised book to open its writing objectives."); - var menu=new ContextMenuStrip();menu.Items.Add("Open PlotDirector Companion",null,(_,_)=>Reveal());menu.Items.Add("Open PlotDirector",null,(_,_)=>Safe(()=>Open("book")));menu.Items.Add("Help & connection",null,(_,_)=>{Reveal();tabs.SelectedIndex=1;});menu.Items.Add(new ToolStripSeparator());menu.Items.Add("Quit Companion",null,(_,_)=>Exit()); + var menu=new ContextMenuStrip();menu.Items.Add("Open PlotDirector Companion",null,(_,_)=>Reveal());menu.Items.Add("Open PlotDirector",null,(_,_)=>Safe(()=>Open("book")));menu.Items.Add("Help & connection",null,(_,_)=>{Reveal();tabs.SelectedIndex=0;});menu.Items.Add(new ToolStripSeparator());menu.Items.Add("Quit Companion",null,(_,_)=>Exit()); tray=new(){Icon=brand,Text="PlotDirector Companion",ContextMenuStrip=menu,Visible=true};tray.DoubleClick+=(_,_)=>Reveal();FormClosing+=(_,e)=>{if(!exiting){e.Cancel=true;Hide();}};timer.Tick+=(_,_)=>RefreshState();timer.Start();RefreshState(); } private Button Button(string text,Action action){var button=new Button{Text=text,AutoSize=true};button.Click+=(_,_)=>Safe(action);return button;} @@ -92,12 +92,12 @@ internal sealed class CompanionWindow:Form var d=Current;if(displayedSession!=selected||displayedBook!=(d?.Book??0)){displayedSession=selected;displayedBook=d?.Book??0;books.SelectedItem=state.Books.FirstOrDefault(b=>b.BookId==d?.Book);} if(string.IsNullOrWhiteSpace(site.Text)&&!string.IsNullOrEmpty(state.ServerUrl))site.Text=state.ServerUrl; var server=state.Health==null?"unknown":DateTime.UtcNow-state.Health.VerifiedUtc>TimeSpan.FromSeconds(90)&&state.Health.Server=="online"?"unverified (check connection)":state.Health.Server; - SetText(status,CompanionPresentation.Connection(state.Health,DateTime.UtcNow)+" · "+(d==null?"Word not connected":"Word connected")); - SetText(nextStep,CompanionPresentation.Next(d!=null,d?.Book>0,d?.Chapters.Length??0,d!=null&&(d.Job!=Guid.Empty||d.Pending.Count>0))); - SetText(progressText,string.IsNullOrEmpty(error)?d?.Status??"Waiting for your manuscript.":error);progress.Value=Math.Clamp(d?.Progress??0,0,100); + SetText(status,CompanionPresentation.Connection(state.Health,DateTime.UtcNow)+" · "+(d==null?"Word not connected":d.Book==0?"Word available locally · link a book":!string.IsNullOrEmpty(d.LastPresenceKey)&&DateTime.UtcNow-d.LastPresenceUtc0&&d.Chapters.Length>0&&d.Job==Guid.Empty&&d.Pending.Count==0&&state.Health?.Authentication=="verified"&&state.Health?.Ai is not ("not-configured" or "not-entitled");cancel.Enabled=d!=null&&(d.Job!=Guid.Empty||d.Pending.Count>0);bookButton.Enabled=d!=null&&state.Books.Length>0&&d.Job==Guid.Empty;review.Enabled=d?.Book>0;contextAction.Enabled=intentAction.Enabled=d?.Book>0; var ckey=d==null?"":d.Session+":"+d.Revision+string.Join("|",d.Chapters.Select(c=>c.Start+":"+c.End+":"+c.Title));if(chapterKey!=ckey){chapterKey=ckey;chapters.BeginUpdate();try{chapters.Items.Clear();renderedSession=d?.Session??Guid.Empty;if(d!=null){if(selectionRevisions.TryGetValue(d.Session,out var revision)&&revision!=d.Revision)selections.Remove(d.Session);if(selectionRevisions.Count>=64)selectionRevisions.Clear();selectionRevisions[d.Session]=d.Revision;}if(d!=null){chapters.Items.AddRange(d.Chapters.Select(c=>(object)new ChapterItem(c.Start,c.Title)).ToArray());if(selections.TryGetValue(d.Session,out var checkedStarts))for(int i=0;i documents=[]; - private readonly Dictionary> commands=[];private readonly Dictionary leases=[]; + private readonly Dictionary> commands=[];private readonly Dictionary leases=[];private readonly HashSet captureInstances=[];private readonly Dictionary<(Guid,Guid),(Guid Manuscript,Guid Authentication,int Book,DateTime Expires)> reconnectBindings=[]; public event Action? OpenRequested; public TrayDocument[] Documents {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).ToArray();}} public TrayDocument[] PresentationDocuments {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).Select(d=>d.Snapshot()).ToArray();}} - public void Attach(Guid instance,Guid lease){lock(gate){Disconnected(instance);leases[instance]=lease;}} + public void Attach(Guid instance,Guid lease,bool capture=false){lock(gate){Disconnected(instance);leases[instance]=lease;if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}} public Message Exchange(Guid instance,Message request,Message answer,Guid lease=default) { lock(gate) @@ -19,11 +19,12 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C if(answer.Status is "wrong-instance" or "stale-sequence" or "stale-revision" or "invalid-documents" or "foreign-session-identity" or "unknown-session")return answer; if(request.Kind=="tray-open")OpenRequested?.Invoke(); if(request.Kind is "document" or "reconcile"){ - if(request.Kind=="reconcile")foreach(var prior in documents.Values.Where(d=>d.Instance==instance).ToArray())Remove(prior.Session); + if(request.Kind=="reconcile")foreach(var prior in documents.Values.Where(d=>d.Instance==instance&&!request.Documents.Any(v=>v.SessionId==d.Session)).ToArray())Remove(prior.Session); foreach(var descriptor in request.Documents){ if(sessions.Descriptor(instance,descriptor.SessionId)==null)continue; if(!documents.TryGetValue(descriptor.SessionId,out var d))documents[descriptor.SessionId]=d=new(){Session=descriptor.SessionId,Instance=instance}; - if(d.Revision!=descriptor.Revision){Cancel(d);d.Chapters=[];d.FailedChapters.Clear();d.Words=null;d.ChapterId=null;d.SceneId=null;d.ChapterTitle="";d.SceneTitle="";d.LastPresenceKey="";d.Status="Document changed. Detect chapters to refresh this snapshot.";} + if(d.Revision!=descriptor.Revision){Cancel(d);d.WordSaved=null;d.Chapters=[];d.FailedChapters.Clear();d.Words=null;d.ChapterId=null;d.SceneId=null;d.ChapterTitle="";d.SceneTitle="";d.LastPresenceKey="";d.Status="Document changed. Detect chapters to refresh this snapshot.";} + if(reconnectBindings.Remove((instance,descriptor.SessionId),out var binding)&&binding.Expires>DateTime.UtcNow&&binding.Manuscript==descriptor.ManuscriptId&&binding.Authentication==cloud.Status().AuthenticationContext){d.Book=binding.Book;d.Authentication=binding.Authentication;} d.Revision=descriptor.Revision;d.Manuscript=descriptor.ManuscriptId;d.Title=descriptor.Title;d.RememberedBook=descriptor.RememberedBook;d.AssociationSite=descriptor.AssociationSite;d.Observed=DateTime.UtcNow; } } @@ -32,7 +33,8 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C else{ doc.Observed=DateTime.UtcNow; if(request.Kind=="active"){foreach(var d in documents.Values)d.Active=false;doc.Active=true;} - if(request.Kind=="selection")doc.Cursor=request.Start; + if(request.Kind=="selection"){doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;} + CaptureFrame(doc,request,answer); if(request.Kind=="selection"||request.Kind=="snapshot-end"){doc.ChapterId=answer.ChapterId;doc.SceneId=answer.SceneId;doc.ChapterTitle=answer.ChapterTitle;doc.SceneTitle=answer.SceneTitle;} if(answer.WordCount.HasValue)doc.Words=answer.WordCount; if(request.Kind.StartsWith("snapshot-",StringComparison.Ordinal)&&answer.Status is not ("ok" or "analysis-complete" or "awaiting-structure")){Cancel(doc);doc.Status="Local reading failed: "+answer.Status+". Detect chapters again.";} @@ -49,13 +51,13 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C return answer; } } - public void Disconnected(Guid instance,Guid lease=default){lock(gate){if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return;leases.Remove(instance);foreach(var doc in documents.Values.Where(d=>d.Instance==instance).ToArray())Remove(doc.Session);commands.Remove(instance);}} - private void Remove(Guid session){if(documents.Remove(session,out var doc)){Cancel(doc);_ = cloud.RemovePresence(doc.Instance,doc.Session);}} + public void Disconnected(Guid instance,Guid lease=default){lock(gate){if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return;leases.Remove(instance);foreach(var expired in reconnectBindings.Where(p=>p.Value.Expires<=DateTime.UtcNow).Select(p=>p.Key).ToArray())reconnectBindings.Remove(expired);foreach(var doc in documents.Values.Where(d=>d.Instance==instance).ToArray()){if(doc.Book>0&&reconnectBindings.Count<256)reconnectBindings[(instance,doc.Session)]=(doc.Manuscript,doc.Authentication,doc.Book,DateTime.UtcNow.AddMinutes(2));Remove(doc.Session);}commands.Remove(instance);}} + private void Remove(Guid session){if(documents.Remove(session,out var doc)){Cancel(doc);_ = cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);}} private bool Queue(TrayDocument doc,AdapterCommand command){if(!commands.TryGetValue(doc.Instance,out var queue))commands[doc.Instance]=queue=new();if(queue.Count>=16){doc.Status="Word request queue is busy. Retry after current operation.";return false;}command.SessionId=doc.Session;command.Revision=doc.Revision;queue.Enqueue(command);return true;} public void Detect(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Completed.Clear();doc.FailedChapters.Clear();doc.Status="Reading chapters in bounded Word batches…";doc.Progress=0;Queue(doc,new(){Kind="detect"});}} public void SelectBook(Guid session,int book,bool remember) { - lock(gate){if(!documents.TryGetValue(session,out var doc))return;var state=cloud.Status();if(!cloud.Allows(state.AuthenticationContext,book))throw new InvalidOperationException("Sign in and select an authorised book.");Cancel(doc);doc.Book=book;doc.Authentication=state.AuthenticationContext;lastBook=book;lastAuthentication=doc.Authentication;doc.Status=remember?"Remember requested; save Word normally after confirmation.":"Book selected for this session."; + lock(gate){if(!documents.TryGetValue(session,out var doc))return;var state=cloud.Status();if(!cloud.Allows(state.AuthenticationContext,book))throw new InvalidOperationException("Sign in and select an authorised book.");Cancel(doc);doc.Book=book;doc.ChapterId=null;doc.SceneId=null;doc.LastPresenceKey="";doc.Authentication=state.AuthenticationContext;lastBook=book;lastAuthentication=doc.Authentication;doc.Status=remember?"Remember requested; save Word normally after confirmation.":"Book selected for this session."; Queue(doc,new(){Kind="associate",BookId=book,AuthenticationContext=doc.Authentication,Site=state.ServerUrl,Remember=remember});} } public void Analyse(Guid session,IEnumerable starts) @@ -77,7 +79,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C if(!Queue(doc,new(){Id=doc.Job,Kind="extract-ai",Chapter=doc.Current,BookId=doc.Book,AuthenticationContext=doc.Authentication})){doc.Job=Guid.Empty;doc.Pending.Clear();} } public void Cancel(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Status="Cancelled. Successful server suggestions remain available.";}} - private void Cancel(TrayDocument doc){if(doc.Job!=Guid.Empty)ai.Clear(doc.Session);doc.Job=Guid.Empty;doc.Pending.Clear();if(commands.TryGetValue(doc.Instance,out var q))commands[doc.Instance]=new(q.Where(c=>c.SessionId!=doc.Session));Queue(doc,new(){Kind="cancel"});} + private void Cancel(TrayDocument doc){if(doc.Capture!=null)_=cloud.FailCapture(doc.Capture.RequestId,doc.Authentication);doc.Capture=null;doc.CaptureFragments.Clear();if(doc.Job!=Guid.Empty)ai.Clear(doc.Session);doc.Job=Guid.Empty;doc.Pending.Clear();if(commands.TryGetValue(doc.Instance,out var q))commands[doc.Instance]=new(q.Where(c=>c.SessionId!=doc.Session));Queue(doc,new(){Kind="cancel"});} public void Navigate(Guid session,int start){lock(gate)if(documents.TryGetValue(session,out var doc))Queue(doc,new(){Kind="navigate",Chapter=new(){Start=start}});} public async Task Tick(CancellationToken cancellation) { @@ -98,16 +100,31 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C public async Task Heartbeat(CancellationToken cancellation) { while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromMilliseconds(500),cancellation);var available=Documents.Where(d=>d.Book>0).ToArray(); - foreach(var doc in available){var key=$"{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{(doc.SceneId.HasValue?0:doc.Cursor)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtcd.Capture!=null)){_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);continue;}Cancel(doc);doc.Capture=new(){RequestId=reply.Navigation.Id,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,Revision=doc.Revision};doc.CaptureFragments.Clear();doc.Status="Reading manuscript for the PlotDirector import wizard…";Queue(doc,reply.Navigation);}else if(reply.Navigation.Kind=="navigate")Queue(doc,reply.Navigation);}}catch(Exception e)when(NetworkFailure(e)) {doc.Status=e.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.UtcNow;}} if(available.Length==0&&lastBook>0&&DateTime.UtcNow-lastAgentPresence>=TimeSpan.FromSeconds(15)){lastAgentPresence=DateTime.UtcNow;agentOnlyPublished=true;try{await cloud.Presence(agentInstance,agentSession,new(){BookId=lastBook,Sequence=Interlocked.Increment(ref agentSequence),WordAvailable=false,DocumentTitle="No Word document"},lastAuthentication);}catch(Exception e)when(NetworkFailure(e)) {}} else if(available.Length>0&&agentOnlyPublished){agentOnlyPublished=false;await cloud.RemovePresence(agentInstance,agentSession);} } } - private static bool NetworkFailure(Exception e)=>e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or System.Text.Json.JsonException; + // Reuses validated bounded snapshot frames; only a browser-requested capture uploads prose. + private void CaptureFrame(TrayDocument doc,Message request,Message answer) + { + var capture=doc.Capture;if(capture==null||capture.RequestId!=request.SnapshotId)return; + if(request.Kind=="snapshot-cancel"||answer.Status is not ("ok" or "analysis-complete" or "awaiting-structure")){_=cloud.FailCapture(capture.RequestId,doc.Authentication);doc.Capture=null;doc.CaptureFragments.Clear();doc.Status="Manuscript transfer interrupted. Retry from PlotDirector.";return;} + if(request.Kind=="snapshot-begin"){doc.CaptureFragments.Clear();capture.End=request.End;} + if(request.Kind=="snapshot-fragment"&&request.Fragment!=null){if(doc.CaptureFragments.Count>=200000){Cancel(doc);return;}doc.CaptureFragments.Add(request.Fragment);} + if(request.Kind=="snapshot-end"){ + capture.Paragraphs=doc.CaptureFragments.ToArray();doc.CaptureFragments.Clear();doc.Capture=null;var context=doc.Authentication;uploading=1; + doc.Status="Sending manuscript to PlotDirector; waiting for durable acceptance…"; + _=Task.Run(async()=>{try{await cloud.Capture(capture,context);lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc){doc.AcceptedRevision=capture.Revision;doc.Status="Manuscript received by PlotDirector. Continue analysis and review in the import wizard. Word text is unchanged.";}}catch(Exception e)when(NetworkFailure(e)){_=cloud.FailCapture(capture.RequestId,context);lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc)doc.Status="Manuscript was not acknowledged: "+e.Message+" Retry from PlotDirector.";}finally{lock(gate)uploading=0;}}); + } + } + public void RefreshPresence(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status="Checking document connection. Use Import manuscript in PlotDirector to transfer prose.";}} + private static bool NetworkFailure(Exception e)=>e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or System.Text.Json.JsonException or ObjectDisposedException; } public sealed class TrayDocument { - public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Detect chapters to begin.",ReviewPath=""; + public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Link this manuscript to a book, then use Import manuscript in PlotDirector.",ReviewPath=""; + public ManuscriptCapture? Capture;public List CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision; public string WordDiagnostics="";public int Cursor;public int Retained;public int Failed;public int Book,Progress,Total,Done;public int? RememberedBook,Words,ChapterId,SceneId;public bool Active;public DateTime Observed,Started; public StructureSuggestion[] Chapters=[];public StructureSuggestion? Current;public Queue Pending=[];public HashSet<(long,int,int)> Completed=[];public HashSet<(long,int,int)> FailedChapters=[];public List Errors=[]; internal TrayDocument Snapshot(){var copy=(TrayDocument)MemberwiseClone();copy.Completed=new(Completed);copy.FailedChapters=new(FailedChapters);copy.Errors=new(Errors);copy.Pending=new(Pending);return copy;} diff --git a/PlotDirector.NativeCompanion/Client/AgentLink.cs b/PlotDirector.NativeCompanion/Client/AgentLink.cs index 084b1137..4a52a225 100644 --- a/PlotDirector.NativeCompanion/Client/AgentLink.cs +++ b/PlotDirector.NativeCompanion/Client/AgentLink.cs @@ -97,7 +97,7 @@ public sealed class AgentLink : IDisposable lock (gate) activePipe = pipe; await pipe.ConnectAsync(700, stop.Token).ConfigureAwait(false); if (!verifyServer(pipe)) throw new UnauthorizedAccessException("Unexpected agent owner."); - await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability }, stop.Token).ConfigureAwait(false); + await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability }, stop.Token).ConfigureAwait(false); mailbox.Clear(); // Reconcile authoritative open documents; never replay stale extraction fragments. await ExchangeAsync(pipe, Reconcile(), stop.Token).ConfigureAwait(false); attempt = 0; StateChanged?.Invoke("connected"); diff --git a/PlotDirector.NativeCompanion/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props index 334c5eb3..0620b80c 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.12 +1.0.0.13 diff --git a/PlotDirector.NativeCompanion/Protocol/ManuscriptCapture.cs b/PlotDirector.NativeCompanion/Protocol/ManuscriptCapture.cs new file mode 100644 index 00000000..4d10dc1c --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/ManuscriptCapture.cs @@ -0,0 +1,13 @@ +using System.Runtime.Serialization; +namespace PlotDirector.Companion.Protocol; +[DataContract] +public sealed class ManuscriptCapture +{ + [DataMember] public Guid RequestId {get;set;} + [DataMember] public Guid InstanceId {get;set;} + [DataMember] public Guid SessionId {get;set;} + [DataMember] public Guid ManuscriptId {get;set;} + [DataMember] public long Revision {get;set;} + [DataMember] public int End {get;set;} + [DataMember] public ParagraphFragment[] Paragraphs {get;set;}=Array.Empty(); +} diff --git a/PlotDirector.NativeCompanion/Protocol/Messages.cs b/PlotDirector.NativeCompanion/Protocol/Messages.cs index aa173b22..43343bd1 100644 --- a/PlotDirector.NativeCompanion/Protocol/Messages.cs +++ b/PlotDirector.NativeCompanion/Protocol/Messages.cs @@ -5,6 +5,7 @@ namespace PlotDirector.Companion.Protocol; public static class ProtocolVersion { public const int Current = 1; + public const string CaptureCapability="wizard-capture-v1"; public const string TrayCapability="tray-adapter-v1"; public const string WorkflowCapability = "workspace-review-v1"; public const string ChapterAiCapability = "chapter-ai-v2"; @@ -61,6 +62,7 @@ public sealed class Message [DataMember] public AnalysisPage? Analysis { get; set; } [DataMember] public int Progress { get; set; } // Null means no completed current snapshot. This is a whitespace-based main-story count. + [DataMember] public bool? WordSaved {get;set;} [DataMember] public int? WordCount { get; set; } } diff --git a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs index 203c98a0..85b207ae 100644 --- a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs +++ b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs @@ -16,6 +16,10 @@ public sealed class AdapterCommand [DataContract] public sealed class NativePresence { + [DataMember] public Guid? CaptureRequestId {get;set;} + [DataMember] public int CaptureProgress {get;set;} + [DataMember] public bool CanCapture {get;set;} + [DataMember] public bool? WordSaved {get;set;} [DataMember] public int? CursorStart {get;set;} [DataMember] public AdapterCommand? Navigation {get;set;} [DataMember] public Guid ManuscriptId {get;set;} diff --git a/PlotDirector.NativeCompanion/Tests/TrayTests.cs b/PlotDirector.NativeCompanion/Tests/TrayTests.cs index b179abee..d7a333b3 100644 --- a/PlotDirector.NativeCompanion/Tests/TrayTests.cs +++ b/PlotDirector.NativeCompanion/Tests/TrayTests.cs @@ -7,7 +7,7 @@ internal static class TrayTests public static async Task Run(Action check) { var handler=new Server();using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Books.Length>0); - using var ai=new ChapterAiWork(cloud);var sessions=new SessionManager(cloud,ai);var control=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var lease=Guid.NewGuid();sessions.Attach(instance,lease);long sequence=0; + using var ai=new ChapterAiWork(cloud);var sessions=new SessionManager(cloud,ai);var control=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var lease=Guid.NewGuid();sessions.Attach(instance,lease);control.Attach(instance,lease,true);long sequence=0; var first=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Title="One",Revision=1};var second=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Title="Two",Revision=1}; Message Apply(Message m){m.WordInstanceId=instance;m.Sequence=++sequence;return control.Exchange(instance,m,sessions.Apply(lease,m));} Apply(new(){Kind="reconcile",Documents=[first,second]});var opened=false;control.OpenRequested+=()=>opened=true;Apply(new(){Kind="tray-open"});check(opened,"Open Companion activates existing agent without another UI process"); @@ -31,17 +31,28 @@ internal static class TrayTests check(handler.Heartbeats==1,"stationary scene does not repeatedly post presence between heartbeats");control.Documents.Single(d=>d.Session==first.SessionId).SceneId=20;await Until(()=>handler.Heartbeats==2); check(true,"changed scene posts lightweight presence before the periodic heartbeat");heartbeatStop.Cancel();try{await heartbeat;}catch(OperationCanceledException){} } + var registered=control.Documents.Single(d=>d.Session==first.SessionId);var priorSequence=registered.PresenceSequence;Apply(new(){Kind="reconcile",Documents=[first,second]});check(control.Documents.Single(d=>d.Session==first.SessionId).Book==3&&control.Documents.Single(d=>d.Session==first.SessionId).PresenceSequence==priorSequence,"reconciliation preserves verified book and monotonic heartbeat state"); + handler.Command=new(){Id=Guid.NewGuid(),Kind="wizard-capture",SessionId=first.SessionId,Revision=1};var captureId=handler.Command.Id;registered.SceneId=null;registered.LastPresenceKey="";registered.LastPresenceUtc=DateTime.MinValue; + using(var stop=new CancellationTokenSource()){ + var heartbeats=control.Heartbeat(stop.Token);await Until(()=>control.Documents.Single(d=>d.Session==first.SessionId).Capture!=null); + Apply(new(){Kind="snapshot-begin",SessionId=first.SessionId,Revision=1,SnapshotId=captureId,End=20,RequestAnalysis=true}); + Apply(new(){Kind="snapshot-fragment",SessionId=first.SessionId,Revision=1,SnapshotId=captureId,Fragment=new(){Start=0,End=10,ParagraphIndex=1,OutlineLevel=1,Text="Opening\r",CompletesParagraph=true}}); + Apply(new(){Kind="snapshot-fragment",SessionId=first.SessionId,Revision=1,SnapshotId=captureId,Fragment=new(){Start=10,End=20,ParagraphIndex=2,OutlineLevel=10,Text="Body text\r",CompletesParagraph=true}}); + Apply(new(){Kind="snapshot-end",SessionId=first.SessionId,Revision=1,SnapshotId=captureId});await Until(()=>registered.AcceptedRevision==1); + check(handler.Captures==1,"wizard request reuses bounded snapshot IPC and acknowledges only the completed server transfer");stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){} + } + handler.DenyPresence=true;try{await cloud.Presence(instance,first.SessionId,new(){BookId=3},cloud.Status().AuthenticationContext);}catch(InvalidOperationException){}check(!cloud.Status().Books.Any(b=>b.BookId==3)&&cloud.Status().Books.Any(b=>b.BookId==4),"one rejected book registration does not disconnect other authorised books");handler.DenyPresence=false;await cloud.CheckConnection(); control.Analyse(first.SessionId,[0,20]);check(control.Documents.Single(d=>d.Session==first.SessionId).Job!=Guid.Empty,"explicit tray selection starts chapter-only extraction queue"); control.SelectBook(second.SessionId,3,false);control.Analyse(second.SessionId,[10]);check(control.Documents.Single(d=>d.Session==second.SessionId).Job==Guid.Empty&&control.Documents.Single(d=>d.Session==second.SessionId).Pending.Count==1,"multiple document AI batches serialize against existing per-author provider limits");control.Cancel(second.SessionId); control.Cancel(first.SessionId);check(control.Documents.Single(d=>d.Session==first.SessionId).Job==Guid.Empty&&control.Documents.Single(d=>d.Session==first.SessionId).Pending.Count==0,"tray cancellation stops queued chapters without affecting another document"); - var replacementLease=Guid.NewGuid();control.Attach(instance,replacementLease);Apply(new(){Kind="document",Documents=[first]});control.Disconnected(instance,lease);check(control.Documents.Length==1,"late disconnect cannot remove a replacement tray lease"); + var replacementLease=Guid.NewGuid();control.Attach(instance,replacementLease);Apply(new(){Kind="document",Documents=[first]});control.Disconnected(instance,lease);check(control.Documents.Length==1&&control.Documents[0].Book==3,"late disconnect cannot remove a replacement tray lease or its verified session-only book association"); control.Disconnected(instance,replacementLease);check(control.Documents.Length==0,"pipe disconnect removes exact Word instance sessions and pending control work"); } private static async Task Until(Func condition){using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(10));while(!condition())await Task.Delay(20,timeout.Token);} private sealed class Server:HttpMessageHandler { - public int Heartbeats; + public int Heartbeats,Captures;public bool DenyPresence;public AdapterCommand? Command;private Guid captureReply; protected override Task SendAsync(HttpRequestMessage request,CancellationToken cancellation) - {if(request.Method==HttpMethod.Post&&request.RequestUri!.AbsolutePath.EndsWith("/presence"))Interlocked.Increment(ref Heartbeats);object body=request.RequestUri!.AbsolutePath.Split('/').Last() switch{"pair"=>new{code=new string('A',24)},"token"=>new{accessToken="test"},"books"=>new[]{new CompanionBook{BookId=3,Title="Allowed book"}},_=>new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow}};return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(body)});} + {if(request.Method==HttpMethod.Post&&request.RequestUri!.AbsolutePath.EndsWith("/presence")){Interlocked.Increment(ref Heartbeats);if(DenyPresence)return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Forbidden));var reply=new NativePresence{Navigation=Command};if(Command!=null)captureReply=Command.Id;Command=null;return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(reply)});}if(request.RequestUri!.AbsolutePath.EndsWith("/manuscript-capture")){Interlocked.Increment(ref Captures);return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(new NativePresence{CaptureRequestId=captureReply,Revision=1})});}object body=request.RequestUri!.AbsolutePath.Split('/').Last() switch{"pair"=>new{code=new string('A',24)},"token"=>new{accessToken="test"},"books"=>new[]{new CompanionBook{BookId=3,Title="Allowed book"},new CompanionBook{BookId=4,Title="Other allowed book"}},_=>new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow}};return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(body)});} } } diff --git a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs index e1e46da1..e41bb79b 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs @@ -197,7 +197,7 @@ namespace PlotDirector.WordAddIn if(active!=state||activationPending){link.TryPost(new Message {Kind="active",SessionId=state.Session,Revision=state.Revision});activationPending=false;} active = state; - link.TryPost(new Message {Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth}); + link.TryPost(new Message {Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,WordSaved=saved&&Com(()=>application.BackgroundSavingStatus)==0,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth}); // Prose is read only on an explicit Companion request; cursor observations never rescan it. invalidateRibbon(); } @@ -226,7 +226,10 @@ namespace PlotDirector.WordAddIn if(!scheduler.Post("command:"+doc.Session,()=>{ if(!documents.ContainsKey(doc.Document)||doc.Revision!=command.Revision){Reply(command,"Document changed; request again.");return;} try{ - if(command.Kind=="detect"){ + if(command.Kind=="wizard-capture"){ + CancelExtraction(doc);doc.End=DocumentEnd(doc.Document);if(!ScheduleSnapshot(doc,true,command.Id))throw new InvalidOperationException("Word queue unavailable. Retry import from PlotDirector."); + } + else if(command.Kind=="detect"){ CancelExtraction(doc);doc.End=DocumentEnd(doc.Document);if(!ScheduleSnapshot(doc,true))throw new InvalidOperationException("Word queue unavailable. Retry detection."); } else if(command.Kind=="extract-ai"&&command.Chapter!=null){ @@ -254,10 +257,10 @@ namespace PlotDirector.WordAddIn }))Reply(command,"Word queue busy. Retry from Companion."); } private void Reply(AdapterCommand command,string result)=>link.TryPost(new Message{Kind="adapter-result",SessionId=command.SessionId,Revision=command.Revision,SnapshotId=command.Id,OperationMessage=result}); - private bool ScheduleSnapshot(LocalDocument doc,bool analyse=false) + private bool ScheduleSnapshot(LocalDocument doc,bool analyse=false,Guid? snapshot=null) { if (doc.Extraction != null || ConnectionState != "connected") return false; - doc.Extraction = new Extraction { Snapshot = Guid.NewGuid(), Revision=doc.Revision,Analyse=analyse,Limit=doc.End }; + doc.Extraction = new Extraction { Snapshot = snapshot??Guid.NewGuid(), Revision=doc.Revision,Analyse=analyse,Limit=doc.End }; if (!scheduler.Post("extract:"+doc.Session,() => ExtractBatch(doc))) {doc.Extraction=null;return false;} return true; @@ -396,7 +399,7 @@ namespace PlotDirector.WordAddIn { // Never set Cancel, wait for IPC, read prose or force a document save. scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(500)); - if(documents.TryGetValue(document,out var state)){StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.NeedsSnapshot=true;} + if(documents.TryGetValue(document,out var state)){StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.NeedsSnapshot=true;state.Revision++;state.WordCount=null;state.ChapterTitle="";state.SceneTitle="";RegisterState(state);} } private void BeforeClose(Word.Document document,ref bool cancel) { diff --git a/PlotLine.Tests/Browser/native-companion-workspace.cjs b/PlotLine.Tests/Browser/native-companion-workspace.cjs index 371a8955..34b696e2 100644 --- a/PlotLine.Tests/Browser/native-companion-workspace.cjs +++ b/PlotLine.Tests/Browser/native-companion-workspace.cjs @@ -11,8 +11,8 @@ const {chromium}=require('playwright');const fs=require('node:fs');const path=re await page.evaluate(()=>{window.beforeEvents=requestCount;for(let i=0;i<20;i++)hubHandlers.NativePresenceChanged();});await page.waitForTimeout(350);assert.equal(await page.evaluate(()=>requestCount-beforeEvents),1,'SignalR burst coalesces to one authorised refresh'); await page.selectOption('#native-manual-scene','33');await page.waitForFunction(()=>document.querySelector('iframe').src.includes('sceneId=33'));await page.click('#native-return');assert.ok((await page.locator('iframe').getAttribute('src')).includes('sceneId=33'),'return without Word preserves manual exploration'); console.log('PASS native PWA exact-session following, pinned scope, manual pause, disconnection and Word-unavailable states'); - const badge=await browser.newPage();await badge.goto('about:blank');await badge.setContent('');await badge.evaluate(()=>{window.tick=null;window.setInterval=f=>(tick=f,1);window.live=[];window.fetch=async()=>({ok:true,json:async()=>live});}); - await badge.addScriptTag({content:fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/native-companion-status.js'),'utf8')});assert.equal(await badge.locator('#native-companion-status').isHidden(),true); + const badge=await browser.newPage();await badge.goto('about:blank');await badge.setContent('
');await badge.evaluate(()=>{window.tick=null;window.setInterval=f=>(tick=f,1);window.live=[];window.fetch=async()=>({ok:true,json:async()=>live});}); + await badge.addScriptTag({content:fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/native-companion-status.js'),'utf8')});assert.equal(await badge.locator('#native-companion-status').getAttribute('data-connected'),null); await badge.evaluate(()=>{live=[{bookId:3,instanceId:'a',sessionId:'b',wordAvailable:true,documentTitle:'Title ',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];tick();});await badge.waitForFunction(()=>document.querySelector('#native-companion-status').dataset.connected==='true');assert.equal(await badge.locator('#native-companion-status script').count(),0); - await badge.evaluate(()=>{live=[];tick();});await badge.waitForFunction(()=>document.querySelector('#native-companion-status').dataset.connected==='false');assert.equal(await badge.locator('#native-companion-status-link').isHidden(),true);console.log('PASS native presence badge never infers connection from associations and clears stale links safely'); + await badge.evaluate(()=>{live=[];tick();});await badge.waitForFunction(()=>document.querySelector('#native-companion-status').dataset.connected==='false');assert.equal(await badge.locator('#native-companion-status').getAttribute('data-native-authority'),'true');assert.match(await badge.locator('#native-companion-status-text').textContent(),/disconnected/);console.log('PASS native presence badge never infers connection from associations and clears stale links safely'); }finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/PlotLine.Tests/Browser/word-companion-regressions.cjs b/PlotLine.Tests/Browser/word-companion-regressions.cjs index 43f73433..5c826e70 100644 --- a/PlotLine.Tests/Browser/word-companion-regressions.cjs +++ b/PlotLine.Tests/Browser/word-companion-regressions.cjs @@ -51,14 +51,15 @@ const scripts=path.join(__dirname,'../../PlotLine/wwwroot/js'); console.log('PASS pinned '+mode+' retains scoped saved content without SignalR/latest Word/window registration');await pinned.close(); } const page=await browser.newPage();await page.goto('about:blank'); - await page.addScriptTag({content:`window.__opened=[];window.open=(url,name)=>{__opened.push(name);return{focus(){}}};const peer={on(){},onreconnected(){},onclose(){},start:async()=>{},invoke:async()=>({projectID:1,bookID:2,windows:[]})};window.signalR={HubConnectionBuilder:class{withUrl(){return this}withAutomaticReconnect(){return this}build(){return peer}}};`}); + await page.addScriptTag({content:`window.__opened=[];window.open=(url,name)=>{__opened.push(name);const target=new URL(url,'https://fixture.invalid');return{location:{pathname:target.pathname,search:target.search,assign(value){const next=new URL(value,'https://fixture.invalid');this.pathname=next.pathname;this.search=next.search;}},focus(){}}};const peer={on(){},onreconnected(){},onclose(){},start:async()=>{},invoke:async()=>({projectID:1,bookID:2,windows:[]})};window.signalR={HubConnectionBuilder:class{withUrl(){return this}withAutomaticReconnect(){return this}build(){return peer}}};`}); await page.addScriptTag({content:fs.readFileSync(path.join(scripts,'writing-workspace.js'),'utf8')}); await page.evaluate(async()=>{ const NativeURL=URL;window.URL=class extends NativeURL{constructor(url,base){super(url,base==='null'?'https://fixture.invalid':base);}}; await PlotDirectorWritingWorkspace.registerWindow({projectID:1,bookID:2,writingRole:'Launcher'}); window.__started=await PlotDirectorWritingWorkspace.startWorkspace({projectID:1,bookID:2}); }); - assert.equal(await page.evaluate(()=>__started.ok),true);assert.deepEqual(await page.evaluate(()=>__opened),['PlotDirectorContext_Book_2','PlotDirectorIntent_Book_2']); + assert.equal(await page.evaluate(()=>__started.ok),true);assert.deepEqual(await page.evaluate(()=>__opened),['PlotDirectorContext','PlotDirectorIntent']); + await page.evaluate(()=>{PlotDirectorWritingWorkspace.openRoleWindow('Context',{projectID:1,bookID:2});PlotDirectorWritingWorkspace.openRoleWindow('Context',{projectID:1,bookID:3});});assert.equal(await page.evaluate(()=>__opened.length),2,'Repeated launches and book changes reuse one Context window'); console.log('PASS fresh Writer launcher opens both missing role windows without undeclared currentRole');await page.close(); }finally{await browser.close();} })().catch(error=>{console.error(error);process.exitCode=1}); diff --git a/PlotLine.Tests/NativeManuscriptCaptureTests.cs b/PlotLine.Tests/NativeManuscriptCaptureTests.cs new file mode 100644 index 00000000..2d04d2f2 --- /dev/null +++ b/PlotLine.Tests/NativeManuscriptCaptureTests.cs @@ -0,0 +1,53 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using PlotDirector.Companion.Protocol; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; +using PlotLine.Services.NativeCompanion; +internal static class NativeManuscriptCaptureTests +{ + public static async Task Run() + { + void Check(bool ok,string message){if(!ok)throw new Exception(message);} + var source=new ManuscriptCapture{RequestId=Guid.NewGuid(),InstanceId=Guid.NewGuid(),SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Revision=1,End=30,Paragraphs=[new(){Start=0,End=10,ParagraphIndex=1,OutlineLevel=1,Text="Chapter 1\r",CompletesParagraph=true},new(){Start=10,End=30,ParagraphIndex=2,OutlineLevel=10,Text="Words remain exact.\r",CompletesParagraph=true}]}; + var preview=NativeManuscriptCapture.Build(source,7,4,1,3,"Synthetic manuscript"); + Check(preview.Chapters.Count==1&&preview.Chapters[0].ChapterText=="Words remain exact.\r"&&preview.Chapters[0].StartPosition==1&&preview.Chapters[0].ParagraphMap[0].WordParagraphIndex==2,"Native source uses the wizard's one-based paragraph coordinates and preserves body prose"); + Check(preview.NativeParagraphPositions[2]==10,"Word character positions remain distinct from wizard paragraph ordinals"); + var tagged=NativeManuscriptCapture.Build(new(){End=10,Paragraphs=[new(){Start=0,End=10,ParagraphIndex=1,OutlineLevel=10,MarkerTags=["PD-CHAPTER-10"],Text="Real prose",CompletesParagraph=true}]},7,4,1,3,"Tagged body");Check(tagged.Chapters[0].ChapterText=="Real prose"&&tagged.Chapters[0].SourceParagraphs[0].IncludeInSourceText,"A chapter marker on body text is not permission to discard manuscript prose"); + var blank=NativeManuscriptCapture.Build(new(){End=0},7,4,1,3,"Blank");Check(blank.Chapters.Count==0,"Blank capture contains no invented chapter"); + var bad=false;try{NativeManuscriptCapture.Build(new(){End=31,Paragraphs=source.Paragraphs},7,4,1,3,"Incomplete");}catch(ArgumentException){bad=true;}Check(bad,"Incomplete streams fail before acceptance"); + var largeText=string.Concat(Enumerable.Repeat("word ",220000));var pieces=new List(); + for(int offset=0;offset(repo).BuildServiceProvider(); + var scans=new ManuscriptScanPreviewStore(services.GetRequiredService(),NullLogger.Instance); + var store=new NativePresenceStore(TimeProvider.System);var lease=new NativePresence{BookId=3,ManuscriptId=source.ManuscriptId,Sequence=1,Revision=1,WordSaved=true,CanCapture=true,Active=true,DocumentTitle="Synthetic manuscript"}; + store.Put(7,"grant",DateTimeOffset.UtcNow.AddHours(1),source.InstanceId,source.SessionId,lease); + var access=NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){BookId=3,Chapters=[]})); + var onboarding=NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){UserOnboardingStateID=4,ProjectID=1,BookID=3})); + using var captureServices=new ServiceCollection().AddSingleton(access).AddSingleton(onboarding).BuildServiceProvider(); + var transfer=new NativeManuscriptCapture(store,scans,TimeProvider.System,captureServices.GetRequiredService()); + var state=await transfer.Start(7,4,1,3);Check(state?.ScanID!=null,"Existing wizard can request exact active native session");source.RequestId=state!.ScanID!.Value; + Check(store.TakeNavigation(7,"grant",source.InstanceId,source.SessionId)?.Kind=="wizard-capture","Capture command follows existing exact-session channel"); + bad=false;try{await transfer.Accept(8,"grant",source);}catch(UnauthorizedAccessException){bad=true;}Check(bad,"Other account cannot submit capture"); + bad=false;try{await transfer.Accept(7,"other",source);}catch(UnauthorizedAccessException){bad=true;}Check(bad,"Different desktop grant cannot submit capture"); + repo.Fail=true;bad=false;try{await transfer.Accept(7,"grant",source);}catch(IOException){bad=true;}Check(bad&&(await scans.GetStateAsync(7,4)).Status==ManuscriptScanStatuses.Running,"Durability failure never reports success");repo.Fail=false; + state=await transfer.Accept(7,"grant",source);Check(state.Status==ManuscriptScanStatuses.Complete&&repo.Values.ContainsKey(source.RequestId),"Acceptance follows durable source persistence"); + await transfer.Accept(7,"grant",source);Check(repo.Writes==1,"Same capture retransmission is idempotent"); + var priorText=source.Paragraphs[1].Text;source.Paragraphs[1].Text="Conflicting text";bad=false;try{await transfer.Accept(7,"grant",source);}catch(ArgumentException){bad=true;}source.Paragraphs[1].Text=priorText;Check(bad&&repo.Writes==1,"Changed same-ID submission cannot overwrite accepted source"); + store.Remove(7,"grant",source.InstanceId,source.SessionId);Check((await scans.GetPreviewAsync(7,source.RequestId))?.Chapters[0].ChapterText=="Words remain exact.\r","Accepted manuscript survives Word/agent disconnection"); + var restarted=new ManuscriptScanPreviewStore(services.GetRequiredService(),NullLogger.Instance);Check((await restarted.GetStateAsync(7,4)).PreviewID==source.RequestId&&(await restarted.GetLatestPreviewAsync(7,4))?.NativeParagraphPositions[2]==10,"Server restart reloads accepted source and coordinate provenance"); + Check(await restarted.GetPreviewAsync(8,source.RequestId)==null,"Recovered source remains account scoped"); + store.Map(7,3,source.ManuscriptId,source.SessionId,1,30,[(0,10,null),(10,10,20)]);lease.CursorStart=11; + Check(store.Resolve(7,lease,source.SessionId)?.Scene==20,"Approved saved capture resolves an exact-session scene");lease.WordSaved=false;Check(store.Resolve(7,lease,source.SessionId)==null,"Dirty Word state cannot reuse positional evidence");lease.WordSaved=true;lease.Revision=2;Check(store.Resolve(7,lease,source.SessionId)==null,"Changed revision cannot reuse positional evidence"); + } + private sealed class Memory:IManuscriptCaptureRepository + { + public readonly Dictionary Values=[];public bool Fail;public int Writes; + public Task Clear(int user,int onboarding)=>Task.CompletedTask; + public Task CompleteBuild(int user,Guid preview)=>Task.CompletedTask; + public Task Save(ManuscriptScanPreview preview){if(Fail)throw new IOException("Synthetic durable-store failure");if(!Values.ContainsKey(preview.PreviewID))Writes++;Values[preview.PreviewID]=preview;return Task.CompletedTask;} + public Task Get(int user,Guid? preview=null,int? onboarding=null)=>Task.FromResult(Values.Values.FirstOrDefault(p=>p.UserID==user&&(!preview.HasValue||p.PreviewID==preview)&&(!onboarding.HasValue||p.OnboardingID==onboarding))); + } +} diff --git a/PlotLine.Tests/NativeTrayIntegrationTests.cs b/PlotLine.Tests/NativeTrayIntegrationTests.cs index 0509e480..a70a3af7 100644 --- a/PlotLine.Tests/NativeTrayIntegrationTests.cs +++ b/PlotLine.Tests/NativeTrayIntegrationTests.cs @@ -17,6 +17,7 @@ internal static class NativeTrayIntegrationTests NativePresence Position(long seq)=>new(){BookId=3,ManuscriptId=manuscript,Sequence=seq,Revision=2,DocumentTitle="A manuscript",ChapterId=10,SceneId=20}; Check(store.Put(7,"grant",clock.Now.AddHours(4),instance,session,Position(1)),"First scoped heartbeat accepted"); Check(!store.Put(7,"grant",clock.Now.AddHours(4),instance,session,Position(1))&&!store.Put(7,"different",clock.Now.AddHours(4),instance,session,Position(2)),"Duplicate sequence and different grant cannot replace a live document"); + store.Remove(7,"grant",instance,session,0);Check(store.Read(7,3).Length==1,"Delayed disconnect cannot remove a newer heartbeat"); Check(store.Read(8,3).Length==0&&store.Read(7,4).Length==0,"Presence read scoped to account and book"); Check(store.Navigate(7,3,instance,session,manuscript,2,10)&&!store.Navigate(8,3,instance,session,manuscript,2,10)&&!store.Navigate(7,3,instance,session,manuscript,1,10),"Navigation requires exact author, manuscript and observed revision"); Check(store.TakeNavigation(7,"different",instance,session)==null&&store.TakeNavigation(7,"grant",instance,session)?.Chapter?.Start==10&&store.TakeNavigation(7,"grant",instance,session)==null,"Explicit navigation delivered once only to its authenticated lease"); @@ -25,7 +26,7 @@ internal static class NativeTrayIntegrationTests var access=NativeWorkflowTests.Proxy((n,a)=>n=="GetBookStructureAsync"?Task.FromResult((int)a![0]! ==3?new WordCompanionBookStructureResponse{BookId=3,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=20}]}]}:null):throw new Exception("Unexpected canonical write "+n)); var http=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7"),new("NativeCompanion.Grant","fresh"),new("NativeCompanion.Expires",clock.Now.AddHours(4).ToString("O"))],DesktopPairing.Scheme))}; var presence=new NativePresenceController(store,access){ControllerContext=new(){HttpContext=http}}; - var invalid=Position(4);invalid.SceneId=999;Check(await presence.Update(instance,session,invalid) is NotFoundResult,"Presence rejects foreign scene markers");invalid=Position(4);invalid.BookId=999;Check(await presence.Update(instance,session,invalid) is ForbidResult,"Presence rejects inaccessible books"); + var invalid=Position(4);invalid.SceneId=999;Check(await presence.Update(instance,session,invalid) is OkObjectResult&&invalid.SceneId==null&&invalid.ChapterId==null,"Foreign scene markers are cleared without rejecting authenticated document liveness");invalid=Position(4);invalid.BookId=999;Check(await presence.Update(instance,session,invalid) is ForbidResult,"Presence rejects inaccessible books"); Check(await presence.Update(instance,session,Position(5)) is OkObjectResult,"Validated saved chapter/scene presence works"); var repo=new MemoryNativeReviews();var result=new AiChapterResult{State="complete",ChapterTitle="Opening",Scenes=[new(){Kind="Scene",Origin="AI",Title="Arrival",Summary="A saved AI summary.",Start=0,End=100}]}; var row=await repo.Save(new(){ReviewID=Guid.NewGuid(),UserID=7,BookID=3,ManuscriptID=manuscript,ContentHash="hash",ResultJson=JsonSerializer.Serialize(result)}); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 3e15fc97..4c344118 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -125,7 +125,7 @@ if (args.Contains("--plot-lines")) if(args.Contains("--intent-assessment")){await IntentAssessmentTests.Run();Console.WriteLine("PASS persisted Intent evidence, exact quotes, cache, stale plans, ownership, cancellation and entitlement");return;} if(args.Contains("--release-sprint")){ReleaseSprintTests.Run();Console.WriteLine("PASS continuity triage and public onboarding/installer guidance");return;} if(args.Contains("--native-import")){await NativeImportTests.Run();Console.WriteLine("PASS approved native import preview, source preservation, ownership, version and retry");return;} -if(args.Contains("--native-tray")){await NativeTrayIntegrationTests.Run();Console.WriteLine("PASS native tray presence, expiry, scope and persistent PWA review decisions");return;} +if(args.Contains("--native-tray")){await NativeTrayIntegrationTests.Run();await NativeManuscriptCaptureTests.Run();Console.WriteLine("PASS native tray presence, expiry, scope and persistent PWA review decisions");return;} if(args.Contains("--native-workflow")){await NativeWorkflowTests.Run();Console.WriteLine("PASS native saved workspace and safe import preview validation");return;} if(args.Contains("--native-companion-http")){await NativeCompanionHttpTests.Run();return;} if(args.Contains("--native-companion")){await NativeCompanionTests.Run();Console.WriteLine("PASS native desktop pairing, canonical chapter AI/mapping, idempotency and cancellation");return;} @@ -135,6 +135,7 @@ var tests = new (string Name, Action Test)[] ("Intent evidence preserves provenance and author control", () => IntentAssessmentTests.Run().GetAwaiter().GetResult()), ("Release triage and browser-only onboarding preserve author decisions", ReleaseSprintTests.Run), ("Approved native import source and confirmation remain safe", () => NativeImportTests.Run().GetAwaiter().GetResult()), + ("Native wizard capture is scoped, durable and independent of Word", () => NativeManuscriptCaptureTests.Run().GetAwaiter().GetResult()), ("Native tray presence and PWA review remain scoped, expiring and non-destructive", () => NativeTrayIntegrationTests.Run().GetAwaiter().GetResult()), ("Native saved workspace and established import eligibility remain scoped and read-only", () => NativeWorkflowTests.Run().GetAwaiter().GetResult()), ("Native companion authentication, canonical AI mapping and isolated chapter retry", () => NativeCompanionTests.Run().GetAwaiter().GetResult()), @@ -2109,8 +2110,8 @@ static void WritingWorkspaceClientUsesSessionIdentityAndStableNames() Assert(script.Contains("sessionStorage.getItem(storageKeys.windowId)", StringComparison.Ordinal), "Browser window IDs must come from sessionStorage."); Assert(script.Contains("sessionStorage.setItem(storageKeys.windowId", StringComparison.Ordinal), "Browser window IDs must be stored per tab/window."); Assert(!script.Contains("localStorage.getItem(storageKeys.windowId)", StringComparison.Ordinal), "Browser window IDs must not be shared through localStorage."); - Assert(script.Contains("PlotDirector${role}_${suffix}", StringComparison.Ordinal), "Context and Intent windows should use stable named targets."); - Assert(script.Contains("Book_${bookId}", StringComparison.Ordinal), "Stable writing window names should be book scoped."); + Assert(script.Contains("PlotDirector${role}", StringComparison.Ordinal), "Context and Intent windows should use stable named targets."); + Assert(script.Contains("url.searchParams.set(\"bookId\", bookId)", StringComparison.Ordinal), "Workspace URLs retain book scope while one named window is reused per role."); Assert(script.Contains("windowRefs = new Map()", StringComparison.Ordinal), "Launcher-created window references should be retained for focus."); Assert(script.Contains("RequestWritingWindowFocus", StringComparison.Ordinal), "Launcher should fall back to SignalR focus requests."); Assert(script.Contains("connection.onreconnected", StringComparison.Ordinal), "Writing workspace windows should re-register after SignalR reconnect."); diff --git a/PlotLine.Tests/Sql/NativeManuscriptCapture.sql b/PlotLine.Tests/Sql/NativeManuscriptCapture.sql new file mode 100644 index 00000000..693a7ab4 --- /dev/null +++ b/PlotLine.Tests/Sql/NativeManuscriptCapture.sql @@ -0,0 +1,43 @@ +-- Disposable synthetic database only. New author/book fixture is always rolled back. +IF DB_NAME()<>N'PlotDirector_Phase2_20261103_2305' OR NOT EXISTS(SELECT 1 FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true') THROW 51000,'Guarded synthetic target required',1; +SET XACT_ABORT OFF; +BEGIN TRANSACTION; +DECLARE @Level int,@User int,@Other int,@Project int,@Book int,@Preview uniqueidentifier=NEWID(); +INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@capture.invalid',N'Capture fixture',N'not-a-credential');SET @User=SCOPE_IDENTITY(); +INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@capture.invalid',N'Other capture fixture',N'not-a-credential');SET @Other=SCOPE_IDENTITY(); +INSERT dbo.SubscriptionLevel(Name,DisplayName,MaxBooks,MaxChaptersPerBook,MaxScenesPerBook,MaxCharactersPerProject,MaxStorageMB,MaxCollaborators,SortOrder,RequiresStripeSubscription) VALUES(CONVERT(nvarchar(36),NEWID()),N'Capture fixture',2,100,100,100,100,0,0,0);SET @Level=SCOPE_IDENTITY(); +INSERT dbo.UserSubscription(UserID,SubscriptionLevelID,IsActive,IsTrial,TrialExpiryDateUTC) VALUES(@User,@Level,1,1,'2030-01-01'); +INSERT dbo.Projects(ProjectName) VALUES(N'Native capture fixture');SET @Project=SCOPE_IDENTITY(); +INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@Project,@User,N'Owner',1); +INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@Project,N'Native capture fixture',1,1);SET @Book=SCOPE_IDENTITY(); +DECLARE @Payload nvarchar(max)=N'{"Chapters":[{"ChapterText":"Exact prose.\r\nSecond line."}],"NativeRevision":3}'; +EXEC dbo.OnboardingManuscriptCapture @Action='save',@UserID=@User,@PreviewID=@Preview,@OnboardingID=4,@BookID=@Book,@Payload=@Payload; +EXEC dbo.OnboardingManuscriptCapture @Action='save',@UserID=@User,@PreviewID=@Preview,@OnboardingID=4,@BookID=@Book,@Payload=@Payload; +IF (SELECT COUNT(*) FROM dbo.OnboardingManuscriptCaptures WHERE PreviewID=@Preview)<>1 THROW 51000,'Duplicate capture',1; +CREATE TABLE #Recovered(Payload nvarchar(max)); +INSERT #Recovered EXEC dbo.OnboardingManuscriptCapture @Action='get',@UserID=@User,@PreviewID=@Preview; +IF NOT EXISTS(SELECT 1 FROM #Recovered WHERE Payload=@Payload) THROW 51000,'Prose was not recovered exactly',1; +TRUNCATE TABLE #Recovered; +INSERT #Recovered EXEC dbo.OnboardingManuscriptCapture @Action='get',@UserID=@Other,@PreviewID=@Preview; +IF EXISTS(SELECT 1 FROM #Recovered) THROW 51000,'Cross-account capture leak',1; +EXEC dbo.OnboardingManuscriptCapture @Action='clear',@UserID=@User,@OnboardingID=4; +TRUNCATE TABLE #Recovered; +INSERT #Recovered EXEC dbo.OnboardingManuscriptCapture @Action='get',@UserID=@User,@OnboardingID=4; +IF EXISTS(SELECT 1 FROM #Recovered) THROW 51000,'Cleared wizard resurrected an older capture',1; +INSERT #Recovered EXEC dbo.OnboardingManuscriptCapture @Action='get',@UserID=@User,@PreviewID=@Preview; +IF NOT EXISTS(SELECT 1 FROM #Recovered) THROW 51000,'Explicit source recovery was destroyed by wizard reset',1; +DELETE dbo.ProjectUserAccess WHERE ProjectID=@Project AND UserID=@User; +TRUNCATE TABLE #Recovered; +INSERT #Recovered EXEC dbo.OnboardingManuscriptCapture @Action='get',@UserID=@User,@PreviewID=@Preview; +IF EXISTS(SELECT 1 FROM #Recovered) THROW 51000,'Revoked access still reads prose',1; +DELETE dbo.Books WHERE BookID=@Book; +IF EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptCaptures WHERE PreviewID=@Preview) THROW 51000,'Book deletion left source prose behind',1; +ROLLBACK; +PRINT 'PASS durable exact prose, idempotency, account boundaries, revoked access and book-deletion cleanup; fixtures rolled back'; +-- Invalid writes are separate rollback-safe probes because XACT_ABORT is enabled by the procedure. +DECLARE @Denied bit=0; +BEGIN TRY + EXEC dbo.OnboardingManuscriptCapture @Action='save',@UserID=-1,@PreviewID=@Preview,@OnboardingID=4,@BookID=-1,@Payload=N'{}'; +END TRY BEGIN CATCH SET @Denied=1;IF @@TRANCOUNT>0 ROLLBACK;END CATCH; +IF @Denied=0 THROW 51000,'Inaccessible book accepted source',1; +PRINT 'PASS unauthorised persistence refused without mutation'; diff --git a/PlotLine.Tests/WordMarkerSecurityTests.cs b/PlotLine.Tests/WordMarkerSecurityTests.cs index 837f5082..1f74930f 100644 --- a/PlotLine.Tests/WordMarkerSecurityTests.cs +++ b/PlotLine.Tests/WordMarkerSecurityTests.cs @@ -40,6 +40,14 @@ internal static class WordMarkerSecurityTests var before=calls; try{await hub.FailOnboardingBuildMarkerSync(99,"bad",new(){DocumentGuid="not-a-guid"});throw new Exception("Malformed identity accepted");}catch(HubException){} Check(calls==before,"Malformed document identity must fail before persistence"); + var native=new PlotLine.Services.NativeCompanion.NativePresenceStore(TimeProvider.System);var instance=Guid.NewGuid();var session=Guid.NewGuid(); + native.Put(4,"grant",DateTimeOffset.UtcNow.AddHours(1),instance,session,new(){BookId=3,Sequence=1,Revision=1,ManuscriptId=Guid.NewGuid(),Active=true,DocumentTitle="Native fixture",ChapterId=10,SceneId=20}); + var legacy=new PlotLine.Services.WordCompanionPresenceService(); + var books=Proxy((_,_)=>Task.FromResult(new(){BookID=3,ProjectID=1})); + var access=Proxy((_,_)=>Task.FromResult(new(){BookId=3})); + var combined=new WordCompanionFollowHub(legacy,null!,null!,null!,null!,repository,NullLogger.Instance,nativePresence:native,nativeBooks:books,nativeAccess:access){Context=new Caller(),Groups=Proxy((_,_)=>Task.CompletedTask)}; + var status=await combined.WatchCompanionPresence();Check(status.IsConnected&&status.CompanionVersion=="Native"&&status.LinkedBookID==3&&status.CurrentStoryPosition?.SceneId==20,"Existing website status must use the authoritative native session"); + native.Remove(4,"grant",instance,session);Check(!(await combined.WatchCompanionPresence()).IsConnected,"Website status cannot keep a native session green after disconnect"); } private sealed class Caller : HubCallerContext { diff --git a/PlotLine/Controllers/NativeManuscriptCaptureController.cs b/PlotLine/Controllers/NativeManuscriptCaptureController.cs new file mode 100644 index 00000000..ba44f427 --- /dev/null +++ b/PlotLine/Controllers/NativeManuscriptCaptureController.cs @@ -0,0 +1,21 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.SignalR; +using PlotDirector.Companion.Protocol; +using PlotLine.Hubs; +using PlotLine.Services.NativeCompanion; +namespace PlotLine.Controllers; +[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion/manuscript-capture")] +public sealed class NativeManuscriptCaptureController(NativeManuscriptCapture capture,IHubContext live):ControllerBase +{ + [HttpDelete("{id:guid}")] + public async Task Cancel(Guid id){var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);var state=await capture.Fail(user,User.FindFirstValue("NativeCompanion.Grant")??"",id);if(state!=null)await live.Clients.Group(WordCompanionFollowHub.PresenceGroup(user)).SendAsync("OnboardingScanFailed",state);return Ok(new NativePresence());} + [HttpPost,RequestSizeLimit(100*1024*1024)] + public async Task Accept(ManuscriptCapture input) + { + var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); + try{var state=await capture.Accept(user,User.FindFirstValue("NativeCompanion.Grant")??"",input);await live.Clients.Group(WordCompanionFollowHub.PresenceGroup(user)).SendAsync("OnboardingScanCompleted",state);return Ok(new NativePresence{CaptureRequestId=input.RequestId,Revision=input.Revision});} + catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}catch(InvalidOperationException){return Conflict(new{message="The import wizard changed. Refresh it before retrying the transfer."});} + } +} diff --git a/PlotLine/Controllers/NativePresenceController.cs b/PlotLine/Controllers/NativePresenceController.cs index d3e9af6a..653d1492 100644 --- a/PlotLine/Controllers/NativePresenceController.cs +++ b/PlotLine/Controllers/NativePresenceController.cs @@ -8,7 +8,7 @@ using PlotLine.Data; using PlotLine.Services.NativeCompanion; namespace PlotLine.Controllers; [ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")] -public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext? live=null,INativePositionRepository? positions=null):ControllerBase +public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext? live=null,INativePositionRepository? positions=null,NativeManuscriptCapture? capture=null,IHubContext? wizard=null):ControllerBase { private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); private string Grant=>User.FindFirstValue("NativeCompanion.Grant")??throw new InvalidOperationException(); @@ -18,17 +18,20 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC { input.Navigation=null;var book=await access.GetBookStructureAsync(input.BookId,Author);if(book==null)return Forbid(); if(input.CursorStart is <0)return BadRequest("Invalid cursor position."); - if(input.WordAvailable&&input.SceneId==null&&input.CursorStart.HasValue&&positions!=null){var mapped=await positions.Resolve(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value);if(mapped!=null&&(!input.ChapterId.HasValue||input.ChapterId==mapped.ChapterID)){input.ChapterId=mapped.ChapterID;input.SceneId=mapped.SceneID;}} + if(input.CanCapture&&input.WordSaved!=true){input.ChapterId=null;input.SceneId=null;} + if(input.WordAvailable&&input.SceneId==null&&presence.Resolve(Author,input,session) is {} known){input.ChapterId=known.Chapter;input.SceneId=known.Scene;} + if(input.WordAvailable&&input.SceneId==null&&input.CursorStart.HasValue&&positions!=null&&(!input.CanCapture||input.WordSaved==true)){var mapped=await positions.Resolve(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value);if(mapped!=null&&(!input.ChapterId.HasValue||input.ChapterId==mapped.ChapterID)){input.ChapterId=mapped.ChapterID;input.SceneId=mapped.SceneID;}} var chapter=input.ChapterId.HasValue?book.Chapters.FirstOrDefault(c=>c.ChapterId==input.ChapterId):null; - if(input.SceneId.HasValue){var parent=book.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==input.SceneId));if(parent==null||(chapter!=null&&chapter!=parent))return NotFound();chapter=parent;input.ChapterId=parent.ChapterId;} - if(input.ChapterId.HasValue&&chapter==null)return NotFound(); + if(input.SceneId.HasValue){var parent=book.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==input.SceneId));if(parent==null||(chapter!=null&&chapter!=parent)){input.SceneId=null;input.ChapterId=null;chapter=null;}else{chapter=parent;input.ChapterId=parent.ChapterId;}} + if(input.ChapterId.HasValue&&chapter==null){input.ChapterId=null;input.SceneId=null;} var before=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session); if(!presence.Put(Author,Grant,Expires,instance,session,input))return Conflict(new{message="Stale, revoked or invalid native session."}); if(live!=null&&(before==null||before.Position.BookId!=input.BookId||before.Position.ManuscriptId!=input.ManuscriptId||before.Position.Revision!=input.Revision||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.Active!=input.Active||before.Position.WordAvailable!=input.WordAvailable))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted); + if(input.CaptureRequestId.HasValue&&capture!=null&&wizard!=null){var progress=await capture.Progress(Author,Grant,input.CaptureRequestId.Value,input.CaptureProgress);if(progress!=null)await wizard.Clients.Group(WordCompanionFollowHub.PresenceGroup(Author)).SendAsync("OnboardingScanProgress",progress,HttpContext.RequestAborted);} input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);return Ok(input); } [HttpDelete("instances/{instance:guid}/documents/{session:guid}/presence")] - public IActionResult Remove(Guid instance,Guid session){presence.Remove(Author,Grant,instance,session);return Ok(new NativePresence());} + public IActionResult Remove(Guid instance,Guid session,long? throughSequence=null){presence.Remove(Author,Grant,instance,session,throughSequence);return Ok(new NativePresence());} [HttpPost("presence/disconnect")] public IActionResult Disconnect(){presence.Revoke(Author,Grant,Expires);return NoContent();} } diff --git a/PlotLine/Controllers/NativeWorkspaceController.cs b/PlotLine/Controllers/NativeWorkspaceController.cs index 2ba981cf..4c760254 100644 --- a/PlotLine/Controllers/NativeWorkspaceController.cs +++ b/PlotLine/Controllers/NativeWorkspaceController.cs @@ -20,7 +20,7 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB public async Task Presence(int bookId) { if(await access.GetBookStructureAsync(bookId,Author)==null)return Forbid();Response.Headers.CacheControl="no-store"; - return Json(presence.Read(Author,bookId).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,manuscriptId=l.Position.ManuscriptId,l.Position.BookId,l.Position.ChapterId,l.Position.SceneId,l.Position.DocumentTitle,l.Position.Active,l.Position.WordAvailable,updated=l.Updated,expires=l.Updated.AddSeconds(45)})); + return Json(presence.Read(Author,bookId).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,manuscriptId=l.Position.ManuscriptId,l.Position.BookId,l.Position.ChapterId,l.Position.SceneId,l.Position.DocumentTitle,l.Position.Active,l.Position.WordAvailable,l.Position.WordSaved,l.Position.CanCapture,updated=l.Updated,expires=l.Updated.AddSeconds(45)})); } [HttpPost("import/preview"),ValidateAntiForgeryToken] public async Task ImportPreview(int bookId,Guid[] reviews,[FromServices] NativeImportService importer) @@ -33,7 +33,7 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB { Response.Headers.CacheControl="no-store";var leases=presence.Read(Author,0);var allowed=new HashSet(); foreach(var book in leases.Select(l=>l.Position.BookId).Distinct())if(await access.GetBookStructureAsync(book,Author)!=null)allowed.Add(book); - return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,updated=l.Updated,expires=l.Updated.AddSeconds(45)})); + return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordSaved,l.Position.CanCapture,updated=l.Updated,expires=l.Updated.AddSeconds(45)})); } [HttpGet("reviews/{id:guid}")] public async Task Review(Guid id) diff --git a/PlotLine/Controllers/OnboardingController.cs b/PlotLine/Controllers/OnboardingController.cs index 1a703ada..ab7e248f 100644 --- a/PlotLine/Controllers/OnboardingController.cs +++ b/PlotLine/Controllers/OnboardingController.cs @@ -15,7 +15,7 @@ public sealed class OnboardingController( IWholeBookPlotIntelligenceService wholeBookPlotIntelligence, ICharacterEnrichmentService characterEnrichment, ICurrentUserService currentUser, - ILogger logger) : Controller + ILogger logger,IManuscriptScanPreviewStore? scanPreviews=null) : Controller { [HttpGet("")] public async Task Index() @@ -149,6 +149,7 @@ public sealed class OnboardingController( [HttpGet("build-complete")] public async Task BuildComplete(Guid previewId) { + if(scanPreviews!=null&¤tUser.UserId.HasValue)ViewData["NativeCapture"]=(await scanPreviews.GetPreviewAsync(currentUser.UserId.Value,previewId))?.Source=="NativeWordCompanion"; var model = await onboarding.GetBuildResultAsync(previewId); return model is null ? NotFound() : View(model); } diff --git a/PlotLine/Data/ManuscriptCaptureRepository.cs b/PlotLine/Data/ManuscriptCaptureRepository.cs new file mode 100644 index 00000000..e13c98d7 --- /dev/null +++ b/PlotLine/Data/ManuscriptCaptureRepository.cs @@ -0,0 +1,19 @@ +using System.Data; +using System.Text.Json; +using Dapper; +using PlotLine.Models; +namespace PlotLine.Data; +public interface IManuscriptCaptureRepository +{ + Task Save(ManuscriptScanPreview preview); + Task Clear(int user,int onboarding); + Task CompleteBuild(int user,Guid preview); + Task Get(int user,Guid? preview=null,int? onboarding=null); +} +public sealed class ManuscriptCaptureRepository(ISqlConnectionFactory factory):IManuscriptCaptureRepository +{ + public async Task Clear(int user,int onboarding){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.OnboardingManuscriptCapture",new{Action="clear",UserID=user,OnboardingID=onboarding},commandType:CommandType.StoredProcedure);} + public async Task CompleteBuild(int user,Guid preview){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.OnboardingManuscriptCapture",new{Action="built",UserID=user,PreviewID=preview},commandType:CommandType.StoredProcedure);} + public async Task Save(ManuscriptScanPreview preview){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.OnboardingManuscriptCapture",new{Action="save",UserID=preview.UserID,preview.PreviewID,preview.OnboardingID,preview.BookID,Payload=JsonSerializer.Serialize(preview)},commandType:CommandType.StoredProcedure);} + public async Task Get(int user,Guid? preview=null,int? onboarding=null){using var db=factory.CreateConnection();var json=await db.QuerySingleOrDefaultAsync("dbo.OnboardingManuscriptCapture",new{Action="get",UserID=user,PreviewID=preview,OnboardingID=onboarding},commandType:CommandType.StoredProcedure);return json==null?null:JsonSerializer.Deserialize(json);} +} diff --git a/PlotLine/Help/Articles/WordCompanion/Install.md b/PlotLine/Help/Articles/WordCompanion/Install.md index fc52aa85..b3bd0fd8 100644 --- a/PlotLine/Help/Articles/WordCompanion/Install.md +++ b/PlotLine/Help/Articles/WordCompanion/Install.md @@ -26,20 +26,24 @@ When an approved release is published, use its verified download and close Word Open Companion, sign in through your normal PlotDirector browser session and select the authorised book. Remembering a book association is optional and requires permission to modify document metadata; it never saves or rewrites manuscript prose. -Use Heading 1 for chapter headings. Detect Chapters reads locally. Select chapters and confirm before sending prose for AI analysis. When approving a connection in your browser, you may enable encrypted import capture for chapters you explicitly submit. This option defaults off and does not upload anything automatically. Older suggestions without source need a newly consented submission; unchanged analysis can be reused. +Use Heading 1 for chapter headings. In the website’s existing manuscript import wizard, choose the same book as the linked Word document, then select **Import manuscript**. This explicitly requests a bounded reading of that document and uploads a server-side capture. Wait for PlotDirector to acknowledge receipt before closing Word. Chapter and scene analysis, locations, characters, assets, summaries and the existing review stages remain in PlotDirector; the Companion does not provide a second importer. -Review scene titles, summaries and decisions in PlotDirector. Preview an approved import before confirming it. Existing content is not silently replaced. If Word or the Companion disconnects, the browser still works and saved reviews remain available. +Review the detected chapters before starting server analysis. Once the capture has been accepted, analysis and review do not require Word or the Companion to remain connected. Existing story records and Word prose are not silently replaced. If transfer is interrupted before acceptance, reconnect and retry from the wizard. + +Save Word normally before capturing when you want live positional scene mapping. **Word reports saved** and **PlotDirector acknowledged this captured revision** are separate states. Saving does not upload prose. After editing or saving again, use a fresh wizard capture when synchronisation is needed; automatic prose synchronisation is not implemented. The Companion’s **Check document connection** verifies presence only. [Get started without Word](/help/getting-started/first-book) ## Your writing control centre -The Companion keeps the working manuscript and linked PlotDirector book together. Find Heading 1 chapters, select the chapters you want to analyse, then review the saved scene suggestions in PlotDirector. Analysis is not an import: importing still requires a preview and explicit confirmation. Troubleshooting contains connection details and support logs; they are not needed for ordinary writing. +The Companion provides browser-approved sign-in, the active Word document, its authorised book association, connection checks and troubleshooting. Import, analysis, Context and Intent are launched from PlotDirector. The normal tray interface no longer contains chapter selection or a separate analysis workflow. -The updated managed interface follows Windows light or dark appearance. Synchronising every PlotDirector application colour theme to the desktop is not available yet. Native version12 and its installer upgrade still require Windows qualification before distribution; this guide is not a download announcement. +The managed interface follows Windows light or dark appearance. Full PlotDirector theme synchronisation is not available. Source version **1.0.0.13** needs a new Windows build, unified installer qualification and real Word tests; Atlas has not installed or qualified it. ## Context and Intent beside Word +Open Context and Intent from the website writing-workspace launcher. Each role reuses its own window, with no PlotDirector ribbon or navigation around the reference workspace. Manual navigation pauses following independently in each window. Live positional following requires trustworthy mappings for the same saved document session and revision; otherwise choose saved scenes manually. + Context shows saved scene details, nearby dated scenes, participants, thread developments and linked floor-plan information. Its People, Relationships, Place and Story tabs provide more detail. Missing dates and mappings stay visibly missing. Use manual selection to explore without Word pulling you back, then return to following when ready. Intent shows your saved plan and objectives. On **Evidence**, **Show saved evidence** loads an existing assessment without requesting AI. **Assess saved prose with AI** explicitly compares saved manuscript prose with your intentions and may incur AI costs. Unchanged prose and plans reuse the saved result. Evidence can be kept, dismissed or deferred; objective completion is still your decision in the scene editor. A stale assessment is labelled when the saved plan or prose changes. diff --git a/PlotLine/Hubs/WordCompanionFollowHub.cs b/PlotLine/Hubs/WordCompanionFollowHub.cs index 3b824cc7..55f78850 100644 --- a/PlotLine/Hubs/WordCompanionFollowHub.cs +++ b/PlotLine/Hubs/WordCompanionFollowHub.cs @@ -16,7 +16,9 @@ public sealed class WordCompanionFollowHub( IManuscriptScanPreviewStore scanStore, IOnboardingService onboardingService, IOnboardingBuildRepository onboardingBuilds, - ILogger logger) : Hub + ILogger logger, + PlotLine.Services.NativeCompanion.NativeManuscriptCapture? nativeCapture=null, + PlotLine.Services.NativeCompanion.NativePresenceStore? nativePresence=null,IBookRepository? nativeBooks=null,IWordCompanionRepository? nativeAccess=null) : Hub { public override async Task OnConnectedAsync() { @@ -32,7 +34,7 @@ public sealed class WordCompanionFollowHub( { var userId = RequireUserId(); await Groups.AddToGroupAsync(Context.ConnectionId, PresenceGroup(userId)); - return await presence.GetStatusAsync(userId); + return await CombinedPresence(userId); } public async Task RegisterCompanion(WordCompanionPresenceRegistration registration) @@ -86,7 +88,7 @@ public sealed class WordCompanionFollowHub( { var userId = RequireUserId(); await Groups.AddToGroupAsync(Context.ConnectionId, PresenceGroup(userId)); - var status = await writingPresence.RegisterAsync(userId, Context.ConnectionId, registration, await presence.GetStatusAsync(userId)); + var status = await writingPresence.RegisterAsync(userId, Context.ConnectionId, registration, await CombinedPresence(userId)); logger.LogInformation( "Writing window registered. UserID={UserID} Role={Role} ProjectID={ProjectID} BookID={BookID} Route={Route}", userId, @@ -101,7 +103,7 @@ public sealed class WordCompanionFollowHub( public async Task WritingWindowHeartbeat(WritingWindowHeartbeat heartbeat) { var userId = RequireUserId(); - var status = await writingPresence.HeartbeatAsync(userId, Context.ConnectionId, heartbeat, await presence.GetStatusAsync(userId)); + var status = await writingPresence.HeartbeatAsync(userId, Context.ConnectionId, heartbeat, await CombinedPresence(userId)); await Clients.Group(PresenceGroup(userId)).SendAsync("WritingWorkspacePresenceChanged", status); return status; } @@ -135,10 +137,14 @@ public sealed class WordCompanionFollowHub( throw new HubException("Finish choosing a Project and Book before scanning."); } + if(nativeCapture!=null){ + try{var native=await nativeCapture.Start(userId,state.UserOnboardingStateID,state.ProjectID.Value,state.BookID.Value);if(native!=null){await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingScanStateChanged",native);return native;}} + catch(InvalidOperationException e){throw new HubException(e.Message);} + } var presenceStatus = await presence.GetStatusAsync(userId); if (!presenceStatus.IsConnected) { - throw new HubException("The Word Companion is not connected. Open Word and try again."); + throw new HubException(nativePresence?.Read(userId,state.BookID.Value).Any(l=>l.Position.WordAvailable)==true?"Update the native Word add-in and agent together to enable manuscript transfer. No content was sent.":"The Word Companion is not connected. Open Word and try again."); } if (!presenceStatus.DocumentOpen) @@ -273,6 +279,11 @@ public sealed class WordCompanionFollowHub( throw new HubException("The reviewed scan could not be found."); } + if(nativeCapture!=null&&await nativeCapture.Built(userId,previewId,result)){ + await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildProgress",new OnboardingBuildProgress{Status="Complete",Message="Chapters, scenes and manuscript sources are saved in PlotDirector. Continue the existing review stages. Word text and markers have not been rewritten; live scene mapping is limited to this unchanged saved capture.",PercentComplete=100,PreviewID=previewId,BuildID=result.BuildID}); + await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildCompleted",result); + return result; + } var companionConnectionId = await presence.GetCompanionConnectionIdAsync(userId); if (!string.IsNullOrWhiteSpace(companionConnectionId)) { @@ -431,8 +442,18 @@ public sealed class WordCompanionFollowHub( await base.OnDisconnectedAsync(exception); } + private async Task CombinedPresence(int userId) + { + if(nativePresence!=null&&nativeBooks!=null&&nativeAccess!=null){ + var docs=nativePresence.Read(userId,0).Where(l=>l.Position.WordAvailable).ToArray();var active=docs.Where(l=>l.Position.Active).ToArray(); + var lease=active.Length==1?active[0]:docs.Length==1?docs[0]:null; + if(lease!=null&&await nativeAccess.GetBookStructureAsync(lease.Position.BookId,userId)!=null&&await nativeBooks.GetAsync(lease.Position.BookId) is {} book) + return new(){UserID=userId,IsConnected=true,Status=WordCompanionPresenceStatuses.Connected,CompanionVersion="Native",DocumentOpen=true,CurrentDocumentName=lease.Position.DocumentTitle,LinkedProjectID=book.ProjectID,LinkedBookID=book.BookID,LastHeartbeatUtc=lease.Updated.UtcDateTime,CurrentStoryPosition=new(book.ProjectID,book.BookID,lease.Position.ChapterId,lease.Position.SceneId)}; + } + return await presence.GetStatusAsync(userId); + } private async Task WritingWorkspaceStatusAsync(int userId, WritingWorkspaceScope scope) - => await writingPresence.GetStatusAsync(userId, scope, await presence.GetStatusAsync(userId)); + => await writingPresence.GetStatusAsync(userId, scope, await CombinedPresence(userId)); private async Task BroadcastWritingWorkspaceStatusAsync(int userId, int? projectId, int? bookId) { @@ -450,7 +471,7 @@ public sealed class WordCompanionFollowHub( private bool TryGetUserId(out int userId) => int.TryParse(Context.User?.FindFirstValue(ClaimTypes.NameIdentifier), out userId); - private static string PresenceGroup(int userId) => $"word-companion-presence:{userId}"; + public static string PresenceGroup(int userId) => $"word-companion-presence:{userId}"; private static bool IsMicrosoftWordState(UserOnboardingState state) => string.Equals(state.WritingSoftware, WritingSoftwareValues.MicrosoftWord, StringComparison.Ordinal) diff --git a/PlotLine/Models/ManuscriptScanModels.cs b/PlotLine/Models/ManuscriptScanModels.cs index f232a28c..ebc09828 100644 --- a/PlotLine/Models/ManuscriptScanModels.cs +++ b/PlotLine/Models/ManuscriptScanModels.cs @@ -72,6 +72,11 @@ public sealed class ManuscriptScanPreview public string Source { get; init; } = ManuscriptScanSources.WordCompanion; public string? DocumentTitle { get; init; } public string? CompanionDocumentIdentifier { get; init; } + public Guid? NativeInstanceID {get;init;} + public Guid? NativeSessionID {get;init;} + public long? NativeRevision {get;init;} + public int NativeDocumentEnd {get;init;} + public IReadOnlyDictionary NativeParagraphPositions {get;init;}=new Dictionary(); public int TotalWordCount { get; init; } public int ChapterCount { get; init; } public int SceneCount { get; init; } diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 401e7a1f..9fd0c133 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -107,6 +107,9 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddHostedService(); + builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddAuthorization(options => { diff --git a/PlotLine/Services/ManuscriptScanPreviewStore.cs b/PlotLine/Services/ManuscriptScanPreviewStore.cs index 3d162b1d..996711df 100644 --- a/PlotLine/Services/ManuscriptScanPreviewStore.cs +++ b/PlotLine/Services/ManuscriptScanPreviewStore.cs @@ -53,10 +53,10 @@ public sealed class ManuscriptScanPreviewStore( return Task.FromResult(ToState(session)); } - public Task ClearAsync(int userId, int onboardingId) + public async Task ClearAsync(int userId, int onboardingId) { sessions.TryRemove((userId, onboardingId), out _); - return Task.CompletedTask; + using var scope=scopeFactory.CreateScope();var repo=scope.ServiceProvider.GetService();if(repo!=null)await repo.Clear(userId,onboardingId); } public Task ProgressAsync(int userId, ManuscriptScanProgress progress) @@ -152,8 +152,10 @@ public sealed class ManuscriptScanPreviewStore( return CompleteAsync(userId, preview); } - public Task CompleteAsync(int userId, ManuscriptScanPreview preview) + public async Task CompleteAsync(int userId, ManuscriptScanPreview preview) { + // A native transfer is acknowledged only after the existing preview is durably saved. + if(preview.Source=="NativeWordCompanion"){using var scope=scopeFactory.CreateScope();await scope.ServiceProvider.GetRequiredService().Save(preview);} var stored = preview.WithUser(userId); previews[stored.PreviewID] = stored; var session = sessions.GetOrAdd((userId, stored.OnboardingID), _ => new ScanSession @@ -175,7 +177,7 @@ public sealed class ManuscriptScanPreviewStore( session.PreviewID = stored.PreviewID; session.UpdatedUtc = stored.CreatedUtc; session.Chunks.Clear(); - return Task.FromResult(ToState(session)); + return ToState(session); } public Task FailAsync(int userId, int onboardingId, string message) @@ -222,23 +224,25 @@ public sealed class ManuscriptScanPreviewStore( && now - pair.Value.UpdatedUtc.Value <= maxAge)); } - public Task GetStateAsync(int userId, int onboardingId) - => Task.FromResult(sessions.TryGetValue((userId, onboardingId), out var session) - ? ToState(session) - : new ManuscriptScanState()); - - public Task GetLatestPreviewAsync(int userId, int onboardingId) + public async Task GetStateAsync(int userId,int onboardingId) { - if (!sessions.TryGetValue((userId, onboardingId), out var session) || !session.PreviewID.HasValue) - { - return Task.FromResult(null); - } - - return GetPreviewAsync(userId, session.PreviewID.Value); + if(sessions.TryGetValue((userId,onboardingId),out var session))return ToState(session); + var saved=await LoadCapture(userId,null,onboardingId);return saved==null?new ManuscriptScanState():await CompleteAsync(userId,saved); } - public Task GetPreviewAsync(int userId, Guid previewId) - => Task.FromResult(previews.TryGetValue(previewId, out var preview) && preview.UserID == userId ? preview : null); + public async Task GetLatestPreviewAsync(int userId, int onboardingId) + { + if (!sessions.TryGetValue((userId, onboardingId), out var session))return await LoadCapture(userId,null,onboardingId); + return session.PreviewID.HasValue?await GetPreviewAsync(userId, session.PreviewID.Value):null; + } + + public async Task GetPreviewAsync(int userId,Guid previewId) + => previews.TryGetValue(previewId,out var preview)&&preview.UserID==userId?preview:await LoadCapture(userId,previewId,null); + private async Task LoadCapture(int user,Guid? id,int? onboarding) + { + using var scope=scopeFactory.CreateScope();var repo=scope.ServiceProvider.GetService(); + if(repo==null)return null;var result=await repo.Get(user,id,onboarding);if(result!=null)previews[result.PreviewID]=result;return result; + } public async Task GetReviewAsync(int userId, Guid previewId) { @@ -301,7 +305,7 @@ public sealed class ManuscriptScanPreviewStore( OnboardingID = preview.OnboardingID, ProjectID = preview.ProjectID, BookID = preview.BookID, - Source = preview.Source, + Source = preview.Source,NativeInstanceID=preview.NativeInstanceID,NativeSessionID=preview.NativeSessionID,NativeRevision=preview.NativeRevision,NativeDocumentEnd=preview.NativeDocumentEnd,NativeParagraphPositions=preview.NativeParagraphPositions, DocumentTitle = preview.DocumentTitle, CompanionDocumentIdentifier = preview.CompanionDocumentIdentifier, TotalWordCount = preview.TotalWordCount, @@ -475,7 +479,7 @@ file static class ManuscriptScanPreviewExtensions OnboardingID = preview.OnboardingID, ProjectID = preview.ProjectID, BookID = preview.BookID, - Source = preview.Source, + Source = preview.Source,NativeInstanceID=preview.NativeInstanceID,NativeSessionID=preview.NativeSessionID,NativeRevision=preview.NativeRevision,NativeDocumentEnd=preview.NativeDocumentEnd,NativeParagraphPositions=preview.NativeParagraphPositions, DocumentTitle = preview.DocumentTitle, CompanionDocumentIdentifier = preview.CompanionDocumentIdentifier, TotalWordCount = preview.TotalWordCount, diff --git a/PlotLine/Services/NativeCompanion/NativeManuscriptCapture.cs b/PlotLine/Services/NativeCompanion/NativeManuscriptCapture.cs new file mode 100644 index 00000000..7c7797a9 --- /dev/null +++ b/PlotLine/Services/NativeCompanion/NativeManuscriptCapture.cs @@ -0,0 +1,110 @@ +using System.Collections.Concurrent; +using System.Text; +using PlotDirector.Companion.Protocol; +using PlotLine.Models; +namespace PlotLine.Services.NativeCompanion; + +// Short-lived transfer authorisation, issued only by the authenticated existing import wizard. +// Prose acceptance is durable through IManuscriptScanPreviewStore, not through this dictionary. +public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManuscriptScanPreviewStore scans,TimeProvider clock,IServiceScopeFactory scopes) +{ + private sealed record Pending(int User,int Onboarding,int Project,int Book,NativeLease Lease,DateTimeOffset Expires,string? Hash=null); + private readonly ConcurrentDictionary pending=new(); + private readonly SemaphoreSlim acceptance=new(1,1); + public async Task Start(int user,int onboarding,int project,int book) + { + await acceptance.WaitAsync();try{ + using var scope=scopes.CreateScope();var access=scope.ServiceProvider.GetRequiredService(); + if(await access.GetBookStructureAsync(book,user)==null)throw new InvalidOperationException("The selected book is not accessible."); + foreach(var expired in pending.Where(p=>p.Value.Expires<=clock.GetUtcNow()).Select(p=>p.Key))pending.TryRemove(expired,out _); + var documents=presence.Read(user,book).Where(l=>l.Position.WordAvailable&&l.Position.CanCapture).ToArray(); + if(documents.Length==0)return null; + var active=documents.Where(l=>l.Position.Active).ToArray(); + var selected=active.Length==1?active[0]:documents.Length==1?documents[0]:throw new InvalidOperationException("More than one Word document is linked to this book. Activate the intended document, then retry."); + if(pending.Values.Any(p=>p.User==user&&p.Hash==null))throw new InvalidOperationException("A manuscript transfer is already pending. Wait for it to finish or expire before retrying."); + if(pending.Count>=128)throw new InvalidOperationException("Manuscript transfers are busy. Try again later."); + var state=await scans.StartAsync(user,onboarding,project,book);var id=state.ScanID!.Value; + pending[id]=new(user,onboarding,project,book,selected,clock.GetUtcNow().AddMinutes(20)); + if(!presence.RequestCapture(user,selected,id)){pending.TryRemove(id,out _);await scans.FailAsync(user,onboarding,"Word changed or is busy. Retry the manuscript transfer.");throw new InvalidOperationException("Word changed or is busy. Retry the manuscript transfer.");} + return state; + }finally{acceptance.Release();} + } + public async Task Accept(int user,string grant,ManuscriptCapture capture) + { + await acceptance.WaitAsync();try{ + if(!pending.TryGetValue(capture.RequestId,out var request)||request.Expires<=clock.GetUtcNow()||request.User!=user||request.Lease.Grant!=grant||capture.InstanceId!=request.Lease.Instance||capture.SessionId!=request.Lease.Session||capture.ManuscriptId!=request.Lease.Position.ManuscriptId||capture.Revision!=request.Lease.Position.Revision)throw new UnauthorizedAccessException(); + using var scope=scopes.CreateScope();var access=scope.ServiceProvider.GetRequiredService();var onboardingState=scope.ServiceProvider.GetRequiredService(); + var current=await onboardingState.GetAsync(user); + if(current==null||current.UserOnboardingStateID!=request.Onboarding||current.ProjectID!=request.Project||current.BookID!=request.Book)throw new UnauthorizedAccessException(); + var structure=await access.GetBookStructureAsync(request.Book,user)??throw new UnauthorizedAccessException(); + var hash=Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(capture))); + if(request.Hash!=null){if(request.Hash!=hash)throw new ArgumentException("Capture identity conflict. Start a new transfer.");return await scans.GetStateAsync(user,request.Onboarding);} + var preview=Build(capture,user,request.Onboarding,request.Project,request.Book,request.Lease.Position.DocumentTitle,structure); + var state=await scans.CompleteAsync(user,preview); + pending[capture.RequestId]=request with{Hash=hash}; + // Retain request until expiry for idempotent same-ID retransmission; no import is committed here. + return state; + }finally{acceptance.Release();} + } + public async Task Progress(int user,string grant,Guid id,int percent) + { + if(!pending.TryGetValue(id,out var request)||request.User!=user||request.Lease.Grant!=grant||request.Hash!=null)return null; + return await scans.ProgressAsync(user,new(){OnboardingID=request.Onboarding,PercentComplete=Math.Clamp(percent,0,100)*9/10,Message="Reading Word manuscript in bounded batches. Keep Word open until PlotDirector acknowledges receipt."}); + } + public async Task> Expire() + { + var failures=new List<(int,ManuscriptScanState)>(); + foreach(var item in pending.ToArray())if(item.Value.Hash==null&&(item.Value.Expires<=clock.GetUtcNow()||!presence.Read(item.Value.User,item.Value.Book).Any(l=>l.Instance==item.Value.Lease.Instance&&l.Session==item.Value.Lease.Session))){var state=await Fail(item.Value.User,item.Value.Lease.Grant,item.Key);if(state!=null)failures.Add((item.Value.User,state));} + return failures; + } + public async Task Built(int user,Guid previewId,OnboardingManuscriptBuildResult result) + { + var preview=await scans.GetPreviewAsync(user,previewId);if(preview?.Source!="NativeWordCompanion")return false; + using var scope=scopes.CreateScope();await scope.ServiceProvider.GetRequiredService().CompleteBuild(user,previewId); + if(preview.NativeSessionID.HasValue&&preview.NativeRevision.HasValue&&Guid.TryParse(preview.CompanionDocumentIdentifier,out var manuscript)){ + var chapterMarkers=result.ChapterMarkerInstructions.Where(i=>preview.NativeParagraphPositions.ContainsKey(i.WordParagraphIndex)).Select(i=>(Start:preview.NativeParagraphPositions[i.WordParagraphIndex],Chapter:i.EntityID,Scene:(int?)null)); + var boundaries=chapterMarkers.OrderBy(i=>i.Start).ToArray(); + var sceneMarkers=result.SceneMarkerInstructions.Where(i=>preview.NativeParagraphPositions.ContainsKey(i.WordParagraphIndex)).Select(i=>{var start=preview.NativeParagraphPositions[i.WordParagraphIndex];return(Start:start,Chapter:boundaries.LastOrDefault(c=>c.Start<=start).Chapter,Scene:(int?)i.EntityID);}).Where(i=>i.Chapter>0); + presence.Map(user,preview.BookID,manuscript,preview.NativeSessionID.Value,preview.NativeRevision.Value,preview.NativeDocumentEnd,boundaries.Concat(sceneMarkers).OrderBy(i=>i.Start).ThenBy(i=>i.Scene.HasValue?1:0).ToArray()); + } + return true; + } + public async Task Fail(int user,string grant,Guid id) + { + await acceptance.WaitAsync();try{ + if(!pending.TryGetValue(id,out var request)||request.User!=user||request.Lease.Grant!=grant||request.Hash!=null)return null; + pending.TryRemove(id,out _);var state=await scans.GetStateAsync(user,request.Onboarding); + return state.ScanID==id?await scans.FailAsync(user,request.Onboarding,"Word transfer interrupted before server acceptance. Retry Import manuscript; existing story data is unchanged."):null; + }finally{acceptance.Release();} + } + public static ManuscriptScanPreview Build(ManuscriptCapture capture,int user,int onboarding,int project,int book,string title,WordCompanionBookStructureResponse? structure=null) + { + if(capture.End<0||capture.End>16*1024*1024||capture.Paragraphs==null||capture.Paragraphs.Length>200000)throw new ArgumentException("Manuscript exceeds the bounded capture limit."); + var paragraphs=new List<(int Start,int Index,int Outline,string Text,string[] Tags)>();var text=new StringBuilder();int position=0,index=1,start=0,outline=10,totalCharacters=0;string[] tags=[]; + foreach(var fragment in capture.Paragraphs){ + if(fragment==null||fragment.Text==null||fragment.Text.Length>ProtocolVersion.MaxParagraphCharacters||fragment.Start!=position||fragment.End<=position||fragment.End>capture.End||fragment.End-fragment.Start>ProtocolVersion.MaxParagraphCharacters||fragment.ParagraphIndex!=index||fragment.OutlineLevel is <1 or >10||fragment.MarkerTags==null||fragment.MarkerTags.Length>16||fragment.MarkerTags.Any(t=>t==null||t.Length>128))throw new ArgumentException("Incomplete or invalid Word paragraph stream."); + if(text.Length==0){start=fragment.Start;outline=fragment.OutlineLevel;tags=fragment.MarkerTags;} + totalCharacters+=fragment.Text.Length;if(totalCharacters>16*1024*1024)throw new ArgumentException("Capture text exceeds limit."); + text.Append(fragment.Text);if(text.Length>16*1024*1024)throw new ArgumentException("Paragraph too large.");position=fragment.End; + if(fragment.CompletesParagraph){paragraphs.Add((start,index++,outline,text.ToString(),tags));text.Clear();} + } + if(position!=capture.End||text.Length!=0)throw new ArgumentException("Manuscript transfer is incomplete."); + var chapters=new List();var scenes=new List(); + var starts=paragraphs.Select((p,i)=>(p,i)).Where(x=>x.p.Outline==1||Marker(x.p.Tags,"PD-CHAPTER-").HasValue).Select(x=>x.i).ToList(); + if(paragraphs.Count>0&&(starts.Count==0||starts[0]!=0))starts.Insert(0,0); + for(int c=0;c!(p.Index==first.Index&&heading)&&p.Outline!=2&&!Separator(p.Text)).ToArray();var chapterText=string.Concat(body.Select(p=>p.Text)); + chapters.Add(new(){TemporaryChapterKey=key,ChapterNumber=c+1,Title=heading?first.Text.Trim():Marker(first.Tags,"PD-CHAPTER-").HasValue?"Chapter "+(c+1):"Opening material",ChapterText=chapterText,WordCount=Words(chapterText),StartPosition=first.Index,ExistingChapterID=structure?.Chapters.FirstOrDefault(c=>c.ChapterId==Marker(first.Tags,"PD-CHAPTER-"))?.ChapterId,ParagraphMap=body.Where(p=>!string.IsNullOrWhiteSpace(p.Text)).Select((p,i)=>new ManuscriptScanParagraphMap{StructuralParagraphOrdinal=i+1,WordParagraphIndex=p.Index,Text=p.Text}).ToArray(),SourceParagraphs=rows.Select(p=>new ManuscriptScanSourceParagraph{WordParagraphIndex=p.Index,Text=p.Text,IsBlank=string.IsNullOrWhiteSpace(p.Text),IsChapterHeading=p.Index==first.Index&&heading,IsSceneHeading=p.Outline==2,IsSceneSeparator=Separator(p.Text),IncludeInSourceText=!(p.Index==first.Index&&heading)&&p.Outline!=2&&!Separator(p.Text)}).ToArray()}); + foreach(var row in rows.Where(p=>p.Outline==2||Marker(p.Tags,"PD-SCENE-").HasValue))scenes.Add(new(){TemporaryChapterKey=key,TemporarySceneKey="scene-"+(scenes.Count+1),SceneNumberWithinChapter=scenes.Count(s=>s.TemporaryChapterKey==key)+1,Title=row.Text.Trim(),StartPosition=row.Index,ExistingSceneID=structure?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault(s=>s.SceneId==Marker(row.Tags,"PD-SCENE-"))?.SceneId}); + } + return new(){NativeInstanceID=capture.InstanceId,NativeSessionID=capture.SessionId,NativeRevision=capture.Revision,NativeDocumentEnd=capture.End,NativeParagraphPositions=paragraphs.ToDictionary(p=>p.Index,p=>p.Start),Source="NativeWordCompanion",PreviewID=capture.RequestId,UserID=user,OnboardingID=onboarding,ProjectID=project,BookID=book,DocumentTitle=title,CompanionDocumentIdentifier=capture.ManuscriptId.ToString("D"),ChapterCount=chapters.Count,SceneCount=scenes.Count,TotalWordCount=chapters.Sum(c=>c.WordCount),Chapters=chapters,Scenes=scenes}; + } + private static int? Marker(string[] tags,string prefix)=>tags.Where(t=>t.StartsWith(prefix,StringComparison.Ordinal)).Select(t=>int.TryParse(t[prefix.Length..],out var id)&&id>0?(int?)id:null).FirstOrDefault(id=>id.HasValue); + private static bool Separator(string text)=>text.Trim() is "***" or "* * *" or "#"; + private static int Words(string text)=>text.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length; +} + +public sealed class NativeCaptureExpiry(NativeManuscriptCapture capture,Microsoft.AspNetCore.SignalR.IHubContext live):BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken){using var timer=new PeriodicTimer(TimeSpan.FromSeconds(15));while(await timer.WaitForNextTickAsync(stoppingToken)){foreach(var failure in await capture.Expire())await Microsoft.AspNetCore.SignalR.ClientProxyExtensions.SendAsync(live.Clients.Group(PlotLine.Hubs.WordCompanionFollowHub.PresenceGroup(failure.User)),"OnboardingScanFailed",failure.State,stoppingToken);}} +} diff --git a/PlotLine/Services/NativeCompanion/NativePresenceStore.cs b/PlotLine/Services/NativeCompanion/NativePresenceStore.cs index 51715942..809e9745 100644 --- a/PlotLine/Services/NativeCompanion/NativePresenceStore.cs +++ b/PlotLine/Services/NativeCompanion/NativePresenceStore.cs @@ -7,18 +7,23 @@ public sealed class NativePresenceStore(TimeProvider clock) private readonly Dictionary<(int,Guid,Guid),AdapterCommand> navigation=[]; private readonly object gate=new();private readonly Dictionary<(int,Guid,Guid),NativeLease> leases=[];private readonly Dictionary revoked=[]; private void Prune(){var now=clock.GetUtcNow();foreach(var key in leases.Where(p=>now-p.Value.Updated>=TimeSpan.FromSeconds(45)||p.Value.GrantExpires<=now).Select(p=>p.Key).ToArray()){leases.Remove(key);navigation.Remove(key);}foreach(var key in revoked.Where(p=>p.Value<=now).Select(p=>p.Key).ToArray())revoked.Remove(key);} + private readonly Dictionary<(int User,int Book,Guid Manuscript,Guid Session,long Revision),(int End,(int Start,int Chapter,int? Scene)[] Items)> mappings=[]; + public void Map(int user,int book,Guid manuscript,Guid session,long revision,int end,(int Start,int Chapter,int? Scene)[] items){lock(gate){if(items.Length>8192)return;foreach(var key in mappings.Keys.Where(k=>k.User==user&&k.Session==session).ToArray())mappings.Remove(key);if(mappings.Count>=64)mappings.Remove(mappings.Keys.First());mappings[(user,book,manuscript,session,revision)]=(end,items);}} + public (int Chapter,int? Scene)? Resolve(int user,NativePresence position,Guid session){lock(gate){if(position.WordSaved!=true||!position.CursorStart.HasValue||!mappings.TryGetValue((user,position.BookId,position.ManuscriptId,session,position.Revision),out var map)||position.CursorStart<0||position.CursorStart>=map.End)return null;var boundary=map.Items.LastOrDefault(i=>i.Start<=position.CursorStart);return boundary.Chapter>0?(boundary.Chapter,boundary.Scene):null;}} public bool Put(int user,string grant,DateTimeOffset expires,Guid instance,Guid session,NativePresence value) { lock(gate){Prune();var key=(user,instance,session);if(instance==Guid.Empty||session==Guid.Empty||(value.WordAvailable&&value.ManuscriptId==Guid.Empty)||value.Revision<0||value.Sequence<=0||value.BookId<=0||value.DocumentTitle==null||value.DocumentTitle.Length>260||value.DocumentTitle.IndexOfAny(['\\','/'])>=0||expires<=clock.GetUtcNow()||revoked.ContainsKey(grant))return false; if(leases.TryGetValue(key,out var prior)){if(prior.Grant!=grant||value.Sequence<=prior.Position.Sequence||value.Revision=4096||leases.Values.Count(p=>p.User==user)>=64)return false; - leases[key]=new(user,grant,expires,instance,session,new NativePresence{ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;} + leases[key]=new(user,grant,expires,instance,session,new NativePresence{CanCapture=value.CanCapture,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;} } public NativeLease[] Read(int user,int book){lock(gate){Prune();return leases.Values.Where(p=>p.User==user&&(book==0||p.Position.BookId==book)).OrderByDescending(p=>p.Updated).ToArray();}} public bool Navigate(int user,int book,Guid instance,Guid session,Guid manuscript,long revision,int start) {lock(gate){Prune();var key=(user,instance,session);if(!leases.TryGetValue(key,out var lease)||!lease.Position.WordAvailable||lease.Position.BookId!=book||lease.Position.ManuscriptId!=manuscript||lease.Position.Revision!=revision||start<0)return false;navigation[key]=new(){Kind="navigate",SessionId=session,Revision=revision,Chapter=new(){Start=start}};return true;}} + public bool RequestCapture(int user,NativeLease selected,Guid request) + {lock(gate){Prune();var key=(user,selected.Instance,selected.Session);if(!leases.TryGetValue(key,out var lease)||lease.Grant!=selected.Grant||!lease.Position.CanCapture||navigation.ContainsKey(key))return false;navigation[key]=new(){Id=request,Kind="wizard-capture",SessionId=lease.Session,Revision=lease.Position.Revision};return true;}} public AdapterCommand? TakeNavigation(int user,string grant,Guid instance,Guid session) {lock(gate){Prune();var key=(user,instance,session);return leases.TryGetValue(key,out var lease)&&lease.Grant==grant&&navigation.Remove(key,out var command)?command:null;}} - public void Remove(int user,string grant,Guid instance,Guid session){lock(gate)if(leases.TryGetValue((user,instance,session),out var prior)&&prior.Grant==grant){leases.Remove((user,instance,session));navigation.Remove((user,instance,session));}} + public void Remove(int user,string grant,Guid instance,Guid session,long? throughSequence=null){lock(gate)if(leases.TryGetValue((user,instance,session),out var prior)&&prior.Grant==grant&&(!throughSequence.HasValue||prior.Position.Sequence<=throughSequence.Value)){leases.Remove((user,instance,session));navigation.Remove((user,instance,session));}} public void Revoke(int user,string grant,DateTimeOffset expiry){lock(gate){Prune();if(revoked.Count<8192)revoked[grant]=expiry;foreach(var key in leases.Where(p=>p.Value.User==user&&p.Value.Grant==grant).Select(p=>p.Key).ToArray())leases.Remove(key);}} } diff --git a/PlotLine/Sql/237_DurableManuscriptCapture.sql b/PlotLine/Sql/237_DurableManuscriptCapture.sql new file mode 100644 index 00000000..b37b6223 --- /dev/null +++ b/PlotLine/Sql/237_DurableManuscriptCapture.sql @@ -0,0 +1,51 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +-- Temporary, accepted onboarding source, not a new manuscript/import engine. +IF OBJECT_ID('dbo.OnboardingManuscriptCaptures','U') IS NULL +BEGIN + CREATE TABLE dbo.OnboardingManuscriptCaptures( + PreviewID uniqueidentifier NOT NULL PRIMARY KEY,UserID int NOT NULL,OnboardingID int NOT NULL, + BookID int NOT NULL,Payload nvarchar(max) NOT NULL,PayloadHash varbinary(32) NOT NULL, + CreatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(), + CONSTRAINT FK_OnboardingManuscriptCaptures_Book FOREIGN KEY(BookID) REFERENCES dbo.Books(BookID) ON DELETE CASCADE); + CREATE INDEX IX_OnboardingManuscriptCaptures_Author ON dbo.OnboardingManuscriptCaptures(UserID,OnboardingID,CreatedUtc DESC); +END; +IF COL_LENGTH('dbo.OnboardingManuscriptCaptures','IsCurrent') IS NULL ALTER TABLE dbo.OnboardingManuscriptCaptures ADD IsCurrent bit NOT NULL CONSTRAINT DF_OnboardingManuscriptCaptures_IsCurrent DEFAULT(1); +GO +CREATE OR ALTER PROCEDURE dbo.OnboardingManuscriptCapture @Action varchar(12),@UserID int,@PreviewID uniqueidentifier=NULL,@OnboardingID int=NULL,@BookID int=NULL,@Payload nvarchar(max)=NULL +AS +BEGIN + SET NOCOUNT ON;SET XACT_ABORT ON; + IF @Action='save' + BEGIN + IF ISJSON(@Payload)<>1 OR DATALENGTH(@Payload)>100*1024*1024 THROW 51000,'Invalid capture',1; + IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE b.BookID=@BookID AND a.UserID=@UserID AND a.IsActive=1) THROW 51000,'Book access denied',1; + BEGIN TRANSACTION; + IF EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptCaptures WITH(UPDLOCK,HOLDLOCK) WHERE PreviewID=@PreviewID) + BEGIN + IF NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptCaptures WHERE PreviewID=@PreviewID AND UserID=@UserID AND BookID=@BookID AND OnboardingID=@OnboardingID AND PayloadHash=HASHBYTES('SHA2_256',@Payload)) THROW 51000,'Capture identity conflict',1; + END + ELSE BEGIN + UPDATE dbo.OnboardingManuscriptCaptures SET IsCurrent=0 WHERE UserID=@UserID AND OnboardingID=@OnboardingID; + INSERT dbo.OnboardingManuscriptCaptures(PreviewID,UserID,OnboardingID,BookID,Payload,PayloadHash) VALUES(@PreviewID,@UserID,@OnboardingID,@BookID,@Payload,HASHBYTES('SHA2_256',@Payload)); + END; + COMMIT;RETURN; + END; + IF @Action='clear' BEGIN UPDATE dbo.OnboardingManuscriptCaptures SET IsCurrent=0 WHERE UserID=@UserID AND OnboardingID=@OnboardingID;RETURN;END; + IF @Action='built' + BEGIN + UPDATE b SET Status=N'Complete',MarkerStatus=N'NotRequested',MarkerSyncMessage=N'Native capture imported on server. Word markers were not rewritten; no Word save acknowledgement claimed.',UpdatedUtc=SYSUTCDATETIME() + FROM dbo.OnboardingManuscriptBuilds b JOIN dbo.OnboardingManuscriptCaptures c ON c.PreviewID=b.PreviewID AND c.UserID=b.UserID AND c.BookID=b.BookID + WHERE b.PreviewID=@PreviewID AND b.UserID=@UserID + AND EXISTS(SELECT 1 FROM dbo.Books k JOIN dbo.ProjectUserAccess a ON a.ProjectID=k.ProjectID WHERE k.BookID=c.BookID AND a.UserID=@UserID AND a.IsActive=1); + IF @@ROWCOUNT<>1 THROW 51000,'Native capture build does not match',1; + RETURN; + END; + IF @Action<>'get' THROW 51000,'Unknown capture operation',1; + SELECT TOP(1) c.Payload FROM dbo.OnboardingManuscriptCaptures c + WHERE c.UserID=@UserID AND (@PreviewID IS NOT NULL OR c.IsCurrent=1) AND (@PreviewID IS NULL OR c.PreviewID=@PreviewID) AND (@OnboardingID IS NULL OR c.OnboardingID=@OnboardingID) + AND EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE b.BookID=c.BookID AND a.UserID=@UserID AND a.IsActive=1) + ORDER BY c.CreatedUtc DESC; +END; +GO diff --git a/PlotLine/Views/NativeWorkspace/Workspace.cshtml b/PlotLine/Views/NativeWorkspace/Workspace.cshtml index 1f713439..29dba2b1 100644 --- a/PlotLine/Views/NativeWorkspace/Workspace.cshtml +++ b/PlotLine/Views/NativeWorkspace/Workspace.cshtml @@ -1,5 +1,5 @@ @model PlotLine.Controllers.NativeWorkspaceModel -@{ ViewData["Title"]="Word Companion · "+Model.Title; } +@{ ViewData["Title"]="Word Companion · "+Model.Title;if(Model.Mode is "context" or "intent"){Layout="_WritingCompanionLayout";} }

@Model.Title

Word Companion · live manuscript connection and saved PlotDirector workspaces

@@ -7,15 +7,16 @@

Manual navigation pauses following. No Word commands or manuscript text are sent by this page. Context and Intent remain available without Word.

- +
@if(Model.Mode is "context" or "intent"){ } @if(Model.Mode=="book"){

AI chapter suggestions

Generated by PlotDirector’s existing chapter-analysis service. Review titles and summaries before any import. Successful chapters remain available for 30 days.

- @if(Model.Reviews.Count==0){
No saved AI suggestions yet. Detect Heading 1 chapters in the tray Companion, select chapters and explicitly confirm analysis.
} + @if(Model.Reviews.Count==0){
No saved AI suggestions yet. Use Import manuscript in PlotDirector to read and review your manuscript.
} else {
@Html.AntiForgeryToken()
} }
+ diff --git a/PlotLine/Views/Onboarding/BuildComplete.cshtml b/PlotLine/Views/Onboarding/BuildComplete.cshtml index 624bdbae..acbb22f9 100644 --- a/PlotLine/Views/Onboarding/BuildComplete.cshtml +++ b/PlotLine/Views/Onboarding/BuildComplete.cshtml @@ -1,6 +1,7 @@ @model OnboardingManuscriptBuildResult @{ ViewData["Title"] = "Manuscript imported"; + var nativeCapture=ViewData["NativeCapture"] is true; var coreComplete = string.Equals(Model.Status, "CoreImportComplete", StringComparison.OrdinalIgnoreCase); } @@ -93,8 +94,8 @@
-

Need to repair the Word document?

-

Resync Word markers uses the existing imported chapters and scenes. Scene detection is not rerun.

+

@(nativeCapture?"Refresh the captured scene mapping":"Need to repair the Word document?")

+

@(nativeCapture?"Refreshes saved scene positions for the same unchanged document session. Word text and markers are not rewritten. If you have edited or saved Word again, import a fresh capture before using live positions.":"Resync Word markers uses the existing imported chapters and scenes. Scene detection is not rerun.")