From 59e17df43f470da64b91a90700e4c3703c76ddf7 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Mon, 9 Nov 2026 12:25:13 +0000 Subject: [PATCH] Integrate bounded native chapter synchronisation and resumable repair --- .../2026-11-09-chapter-sync-contract.md | 4 + .../2026-11-09-chapter-sync-implementation.md | 83 ++++++++++++ .../2026-11-09-chapter-sync.md | 70 ++++++++++ .../Agent/CloudGateway.cs | 6 +- .../Agent/PipeHost.cs | 4 +- .../Agent/SessionManager.cs | 11 +- .../Agent/TrayApplication.cs | 2 +- .../Agent/TrayCoordinator.Chapters.cs | 128 ++++++++++++++++++ .../Agent/TrayCoordinator.cs | 28 ++-- .../Client/AgentLink.cs | 2 +- .../DeveloperVersion.props | 2 +- .../Protocol/Manuscript/ChapterFingerprint.cs | 18 +++ .../Protocol/Messages.cs | 6 + .../Protocol/TrayContracts.cs | 5 + .../Tests/ChapterAgentTests.cs | 52 +++++++ PlotDirector.NativeCompanion/Tests/Program.cs | 1 + .../Vsto/NativeRibbon.cs | 11 +- .../Vsto/PlotDirector.WordAddIn.csproj | 2 +- .../Vsto/Properties/AssemblyInfo.cs | 4 +- PlotDirector.NativeCompanion/Vsto/Ribbon.xml | 6 + .../Vsto/WordAdapter.cs | 16 ++- .../Vsto/WordChapterRead.cs | 80 +++++++++++ .../WindowsValidation/Measure-ChapterSync.ps1 | 4 +- .../WindowsValidation/Setup/Release.json | 6 +- .../Browser/chapter-sync-development.cjs | 33 +++++ .../Browser/writing-context-shell.cjs | 7 +- PlotLine.Tests/ChapterSyncDevelopmentTests.cs | 40 ++++++ PlotLine.Tests/ChapterSynchronisationTests.cs | 20 +++ PlotLine.Tests/ParagraphWorkflowTests.cs | 2 + PlotLine.Tests/Program.cs | 1 + .../NativeChapterSyncController.cs | 4 + .../Controllers/NativePresenceController.cs | 12 +- .../Controllers/NativeWorkspaceController.cs | 4 +- .../ParagraphManuscriptController.cs | 7 +- PlotLine/Controllers/WritingController.cs | 18 ++- PlotLine/Data/ChapterSyncRepository.cs | 9 +- .../Help/Articles/WordCompanion/Install.md | 4 +- .../Manuscript/ChapterCheckpointEngine.cs | 15 +- .../Services/Manuscript/ChapterSyncService.cs | 36 ++++- .../Manuscript/ParagraphManuscriptService.cs | 1 + .../Services/Manuscript/ParagraphRecovery.cs | 3 + .../NativeManuscriptCapture.cs | 10 +- .../NativeCompanion/NativePresenceStore.cs | 19 ++- PlotLine/Sql/245_ChapterSynchronisation.sql | 44 +++++- ..._ChapterReviewInvalidatesLivePositions.sql | 98 ++++++++++++++ .../Sql/247_ChapterAdoptionSnapshotDigest.sql | 102 ++++++++++++++ .../Views/ParagraphManuscript/Index.cshtml | 7 +- .../Shared/_WritingConnectionDetails.cshtml | 1 + .../wwwroot/js/native-companion-status.js | 8 +- 49 files changed, 972 insertions(+), 84 deletions(-) create mode 100644 Docs/WordCompanion/2026-11-09-chapter-sync-implementation.md create mode 100644 Docs/WordCompanion/WindowsHandover/2026-11-09-chapter-sync.md create mode 100644 PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs create mode 100644 PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs create mode 100644 PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs create mode 100644 PlotLine.Tests/Browser/chapter-sync-development.cjs create mode 100644 PlotLine.Tests/ChapterSyncDevelopmentTests.cs create mode 100644 PlotLine/Sql/246_ChapterReviewInvalidatesLivePositions.sql create mode 100644 PlotLine/Sql/247_ChapterAdoptionSnapshotDigest.sql diff --git a/Docs/WordCompanion/2026-11-09-chapter-sync-contract.md b/Docs/WordCompanion/2026-11-09-chapter-sync-contract.md index ee60f95a..44eb3639 100644 --- a/Docs/WordCompanion/2026-11-09-chapter-sync-contract.md +++ b/Docs/WordCompanion/2026-11-09-chapter-sync-contract.md @@ -23,3 +23,7 @@ Implementation, tests, measured portable timings, migration/deployment identity ### First portable milestone Versioned fingerprint/XML reader, accepted-snapshot checkpoint model, read-only unchanged-chapter validation, explicit missing-native-ID adoption, conservative changed-chapter merging through the existing engine, authorised API/service, and forward migration 245 source are implemented. Migration is not yet applied and this milestone is not yet deployed. Solution build passes without warnings. Focused tests cover reordered/split paragraphs, Unicode/control characters, cross-session positions, stale lineage, duplicate IDs, preservation of unrelated GUIDs/scenes, hard boundaries and unsafe XML rejection. Portable SHA-256 measurement: 48 synthetic chapters / 8,640 paragraphs in 26.7 ms on Atlas; excludes Word/COM and is not a Windows performance claim. + +### Integrated candidate + +The subsequent implementation extends the existing native/agent/presence/recovery paths end to end, with optional chapter capability, progressive validation, explicit repair, compact status and version 1.0.0.23 source. Migrations 245–247 have been applied to Development after verified backups; the original 245 ledger above records the earlier source-only milestone. See [the current implementation/deployment evidence](2026-11-09-chapter-sync-implementation.md) and [Windows qualification instructions](WindowsHandover/2026-11-09-chapter-sync.md) for the actual final status. Real Word COM timings and execution are not verified on Atlas. diff --git a/Docs/WordCompanion/2026-11-09-chapter-sync-implementation.md b/Docs/WordCompanion/2026-11-09-chapter-sync-implementation.md new file mode 100644 index 00000000..90ef2319 --- /dev/null +++ b/Docs/WordCompanion/2026-11-09-chapter-sync-implementation.md @@ -0,0 +1,83 @@ +# Chapter-based synchronisation and repair — implementation evidence + +Shared branch: `codex/word-companion-native-phase1-20261104`. Windows baseline `51316f0f834e71319bbca6e93002ffd32314bfe4` / installed 1.0.0.22. First foundation commit: `e6e2a33`. Final implementation/deployment ledger follows below. + +## Implemented behaviour + +The existing canonical paragraph snapshot, GUID reconciliation engine, saved scene assignments, evidence, authenticated presence, command mailbox and Word scheduler remain authoritative. This is an additive chapter path, negotiated with **`chapter-sync-v1`**, not a second import or scene-detection engine. .22 remains compatible and receives its existing commands; fast reopening requires the new **1.0.0.23 candidate** agent and VSTO. Nothing was installed or packaged on Atlas. + +```mermaid +sequenceDiagram + participant W as Word STA / bounded scheduler + participant A as Existing per-user agent + participant S as Authenticated PlotDirector services + participant D as Existing snapshot + chapter validations + participant C as Writing Context / Intent + W->>A: Document, saved state, session/revision, cursor + A->>S: Existing exact-session presence + A->>S: Chapter manifest + S->>D: Accepted source checkpoints / same-session live ranges + A->>W: Bounded chapter-check at current cursor + W->>A: Range text + single chapter XML, bounded IPC chunks + Note over A: Exact XML/text match, native IDs, SHA-256 outside Word + A->>S: Hashes + paragraph identity/length evidence, no prose + alt Existing complete source matches + S->>D: CAS metadata adoption + current physical positions + else Changed chapter and existing mode / explicit repair permits prose + A->>S: Only this chapter's exact paragraphs + S->>D: Existing reconciliation, coherent snapshot CAS + S->>D: Independently accepted chapter positions + else Ambiguous / unapproved / complex + S-->>A: Changed / Needs review, preserve accepted work + end + A->>S: Presence at cursor, no navigation request + S->>D: Resolve only verified live chapter positions + S-->>C: Existing presence/fragment update, retain active tab + A->>W: Next bounded chapter check, current document prioritised +``` + +The current chapter is prioritised. Subsequent reads advance using actual Word range ends, not stale saved absolute positions, and wrap once. Two document reads and native queues are bounded; activating another document can supersede background work. Obsolete frames, revisions, accounts and closed sessions are rejected. A network interruption retains server checkpoints and retries on reconnection. Explicit cancellation revokes the prose permit and keeps committed chapters. New sessions revalidate content/identity evidence cheaply rather than trusting old offsets. + +Changed prose is transferred only under the existing OnSave preference or an explicit owner repair request scoped to installation grant, manuscript, session, Word revision and expiry. Manual mode performs evidence checks without prose upload. Off stops automatic checking. Nothing triggers import or AI. No Word prose or permanent markers are written. Explicit full snapshot fallback remains available for unsupported content. + +Repair is available in the **top-right Word connection dialog** and **book → Manuscript structure and evidence**. The latter also shows saved checkpoints and cancellation. The compact native ribbon adds chapter progress and a Manuscript menu with Synchronise, Repair and Troubleshooting; tray guidance reuses server progress. Saved acceptance is distinguished from live liveness. Newly requested repair cannot inherit an old green completion. Only explicit navigation uses the existing correlated Word command path; passive checking never calls Select or sends navigate. + +## Persistence and identity + +`ParagraphManuscript.ChapterCheckpoints` is additive JSON in the existing snapshot: canonical chapter/heading GUID, native boundary IDs, exact content/identity/mapping digests, ordering, paragraph count, algorithm, accepted lineage, last successful sync and status. Existing imports are not backfilled or declared corrupt. A server-authorised repair can fill missing native IDs only with unique, complete exact chapter evidence; existing IDs, GUIDs and scene assignments cannot be replaced by coincidental text or numeric identity. + +Migration **245** adds `BookChapterValidations` and `dbo.BookChapterSync`: per-user, manuscript, session and Word revision; 12-hour expiring current physical positions; authorisation, owner mutations, protected-job checks, snapshot CAS, bounded JSON, unknown/cross-chapter/duplicate/overlapping-position rejection and conflicting same-revision evidence protection. Reads join accepted source content/identity/mapping digests and canonical nonarchived chapter/scene relationships. Validating one chapter cannot mark unchecked chapters trustworthy. + +Forward migrations **246** and **247** respectively invalidate live chapter ranges when duplicate/ambiguous structure is flagged, and maintain the existing whole-snapshot digest when missing native IDs are adopted. These were found during integration testing after 245 had been applied; existing migrations were not rewritten after application. All three procedures remain compatible with .22. + +Changed-chapter reconciliation reconstructs one coherent logical snapshot using the existing engine, CAS-saves it and clears the full-snapshot live-session claim. Unrelated canonical IDs/evidence remain intact. Its separate live acceptance commit is conservative: interruption after source save leaves valid canonical content but no new green position claim, and retry can complete acceptance. Other chapter position proofs remain reusable only while their source mapping hashes and exact live Word revision match. Canonical ordering and scene boundaries are never silently rewritten for moved/deleted/inserted chapters. + +Existing backup format 1.5 / selective 2.1 carries checkpoint JSON through the established recovery graph. Typed chapter IDs and mapping hashes are remapped; paragraph/native/scene GUID evidence and source text hashes survive. Restore detaches live trust, starts Manual and removes old live validation rows through the snapshot FK. No leases, repair permissions or credentials are restored. + +## Fingerprints and native access + +`sha256-utf16le-paragraphs-v1`: encode version, paragraph count and each string's code-unit length with little-endian Int32 prefixes; write each exact UTF-16 code unit little endian. No whitespace, Unicode composition, CR/LF, paragraph delimiter or Word control-character normalisation. Isolated surrogates remain distinguishable. Splitting/merging, order and changed text alter the digest. Ordered native IDs, lengths and outline levels form a separate digest; GUID/chapter/scene/verification assignments form the mapping digest. Text alone never validates positions. + +The native reader uses read-only Range.GoTo to find Heading 1 boundaries, staged Range.Text and **one chapter Range.WordOpenXML**, plus the next heading's tiny identity range. It never uses Selection/Select or passes COM objects outside the STA. XML parsing, styles, exact text comparison, hashing and network work run in the agent. Transport uses 2,048-character chunks, existing 256 KiB frames and mailbox backpressure. Bounds: 256 Ki UTF-16 code units /10,000 paragraphs per chapter, 8 Mi characters XML, two concurrent document readers and bounded heading search. COM calls and scheduler steps are instrumented. A single COM call remains unpreemptible, so the 20–30 ms goal needs actual measurement. + +Supported XML is deliberately conservative: ordinary main-body paragraphs, styles/outline inheritance, text, tabs and soft breaks with exact equality to Range.Text and complete unique native IDs. Tables, fields, drawings, tracked insert/delete/moves, footnotes and page/column breaks are refused rather than assigned guessed offsets. Word-generated range wrappers and real style/export behaviour require Windows qualification. Unsupported/oversized content can use the explicit proven bounded full-reader fallback; it is not silently invoked during reopening. + +Saved DOCX package inspection was considered: ZIP `/word/document.xml` and styles can be hashed off the STA without per-paragraph COM, but file evidence does not prove the current in-memory Word range, saved state or positions. Unsaved edits, background save, AutoSave/cloud paths, external replacement, fields/revisions and Word's text projection all complicate that correspondence. This delivery deliberately trusts measured live chapter Range evidence, not a file timestamp/hash or an unqualified file cache. No Track Changes dependency or saved-file speed claim is introduced. A later read-only package accelerator must preserve the same exact live validation checks. + +Microsoft API references: [Range.GoTo](https://learn.microsoft.com/en-us/office/vba/api/word.range.goto), [Range.WordOpenXML](https://learn.microsoft.com/en-us/office/vba/api/word.range.wordopenxml). Source evidence is in `Vsto/WordChapterRead.cs`, `Agent/TrayCoordinator.Chapters.cs`, protocol `ChapterFingerprint.cs`, server `ChapterCheckpointEngine.cs`, `ChapterSyncService.cs`, `ChapterSyncRepository.cs` and migrations 245–247. + +## Qualification and deployment ledger + +To be completed with actual final verification; Windows measurements are explicitly outstanding. See [ready-to-use Windows handover](WindowsHandover/2026-11-09-chapter-sync.md). + +### Pre-deployment gates + +- `dotnet build PlotLine.slnx --no-restore --disable-build-servers -m:1 /p:UseSharedCompilation=false`: passed, zero warnings/errors, including the Windows-targeted managed agent; excludes VSTO host compilation. +- Full application executable harness: **455 PASS** results. Native foundation: **271 checks**. Focused chapter engine: **29 PASS** results; agent chapter protocol: **110 PASS** results (including 100 repeated passive selections). Paragraph/recovery/workflow regressions and server Context navigation regressions pass; a new receipt-ordering regression also passes after the full run. +- Chromium: actual compiled Context shell in browser/PWA/dedicated window variants, both legacy Sync and capability-gated Repair form routing, metadata-only acceptance without global revision increment, tab preservation and simulated follow/reconnect/navigation feedback tests pass. These are browser/protocol tests, not real Word. +- Disposable Development account/book: real repository/SP commits validate native-ID adoption, current scene position, stale CAS rollback, separate live-session isolation, preserved paragraph/prose/scene identities, retry/resume and cross-user refusal. The adopted full snapshot digest is checked against actual stored records. +- Portable hashing benchmark: **43.5 ms** for 48 synthetic chapters /8,640 paragraphs on the final focused run (earlier run 26.7 ms). This excludes all Word/COM, XML extraction, network and UI work; it is not a manuscript performance promise. +- Development backup `PlotDirector_Development_before_chapter_sync_245_20261109T120018Z.bak` passed CHECKSUM/VERIFYONLY. Separate verified backups precede 246 and 247 (`before_chapter_review_246_20261109T121300Z.bak`, `before_chapter_digest_247_20261109T122600Z.bak`). Every migration passed a transactionally rolled-back dry run before application. No database was reset/restored. +- Read-only before/after comparison: book **10152** has the identical accepted payload SHA-256, revision and payload length, **48 chapters /290 scenes** after schema work. No real-book backfill, repair, reimport, scene detection or AI operation was run. + +Live deployment/protocol evidence is appended after the release is verified. Source 1.0.0.23 remains a Windows qualification candidate, not an installed/public release. diff --git a/Docs/WordCompanion/WindowsHandover/2026-11-09-chapter-sync.md b/Docs/WordCompanion/WindowsHandover/2026-11-09-chapter-sync.md new file mode 100644 index 00000000..f277caeb --- /dev/null +++ b/Docs/WordCompanion/WindowsHandover/2026-11-09-chapter-sync.md @@ -0,0 +1,70 @@ +# Windows handover: chapter synchronisation, candidate 1.0.0.23 + +Use only `codex/word-companion-native-phase1-20261104`. Atlas implementation/deployment evidence and the exact handover commits are in [the implementation report](../2026-11-09-chapter-sync-implementation.md). Fetch the configured tracking remote, inspect/preserve the worktree, and fast-forward only. Stop on divergence. No branches, worktrees, rebase, force pushes, trust-store changes or installer redesign. + +## Non-interactive build first + +Do not use Computer Use, launch Word, steal focus, close applications or install anything during unattended qualification. Identify the actual Windows user/profile; a sandbox registry does not establish installation for the interactive author. Atlas did not build the VSTO, sign, package or install this candidate. + +The managed/native-source changes are: + +- `Protocol/Manuscript/ChapterFingerprint.cs`, `Messages.cs`, `TrayContracts.cs`: optional `chapter-sync-v1`; exact fingerprints, bounded chapter frames and server-owned progress. +- `Client/AgentLink.cs`, `Agent/PipeHost.cs`, `SessionManager.cs`, `TrayCoordinator.Chapters.cs`, `TrayCoordinator.cs`, `CloudGateway.cs`: negotiated current-chapter checking, progressive/resumable acceptance, changed-chapter-only upload under the existing synchronisation preference or explicit repair permit. +- `Vsto/WordChapterRead.cs` (explicitly included in `PlotDirector.WordAddIn.csproj`), `WordAdapter.cs`, `NativeRibbon.cs`, `Ribbon.xml`: owner-thread staged Range reads, no selection, compact chapter status and Synchronise/Repair/Troubleshooting. No permanent paragraph markers or prose edits. +- `Agent/TrayApplication.cs`: displays the existing server chapter progress in the compact guidance area; authentication/association/installer architecture retained. + +Run serially from the existing checkout: + +```powershell +.\PlotDirector.NativeCompanion\WindowsValidation\Update-WordCompanion.ps1 +# Optional existing signing identity when discovery is ambiguous: +# ... -CertificateThumbprint '' +dotnet run --project PlotDirector.NativeCompanion/Tests -- --chapter-sync +dotnet run --project PlotLine.Tests -- --chapter-sync +dotnet run --project PlotLine.Tests -- --paragraph-manuscripts +``` + +The update script builds the signed VSTO and managed components and prepares a developer package; it does **not** install. Expected package: the real user's Downloads known folder, `PlotDirectorWordCompanion\1.0.0.23-`. Verify `package.json`, both payload versions and clean source SHA. Preserve the installed 1.0.0.22 package. If a Windows compiler/API error occurs, make only a focused native compatibility fix, test, commit and push this same branch. + +Use the existing unified installer, after build validation: + +```powershell +.\PlotDirector.NativeCompanion\WindowsValidation\Setup\Build-Setup.ps1 ` + -PackagePath '' ` + -ExpectedSourceCommit '' ` + -OutputDirectory '' ` + -CertificateThumbprint '' +``` + +`WindowsValidation/Setup/Release.json` selects application **1.0.0.23**, MSI **1.0.23**, a fresh ProductCode and unchanged upgrade family/baseline pins. Keep those qualified baseline pins; they are not invented hashes for .22. Verify using `Setup/README.md` and the existing `Test-SetupPackage.ps1` procedure. Deliver **PlotDirectorCompanionSetup.exe** with both VSTO and agent. Do not substitute a loose `.vsto` file. Installation is a separate explicitly scheduled step; do not open approval prompts unattended. Preserve protected credentials, settings and associations. Do not forcibly close Word or other applications. + +## Native benchmark — scheduled interactive session only + +Use a copy of an author-owned test manuscript, saved, with a representative complete Heading 1 chapter selected by the human. Do not automate that selection. Attach to already running Word: + +```powershell +powershell.exe -STA -File .\PlotDirector.NativeCompanion\WindowsValidation\Measure-ChapterSync.ps1 ` + -ProtocolAssembly '' ` + -OutputFile '' +# Optional explicitly expensive, capped legacy baseline: +# ... -IncludeLegacyParagraphXml -MaximumParagraphs 100 +``` + +The script never launches, selects, saves or closes Word. It records Range.Text, exact SHA-256, one chapter WordOpenXML, portable native-ID parsing and optional capped per-paragraph XML timings. Unsupported XML is recorded as a parse error, not hidden. Cross-process COM wall time is **not** in-add-in UI occupancy: also collect existing `chapter-range-text`, `chapter-range-xml`, `chapter-next-heading-identity` and `chapter-ui-step` metrics from Advanced/Troubleshooting. Report actual chapter sizes, max/median timings, observed typing/scrolling/save/cursor behaviour. No speed claim without measurements. + +## Functional acceptance + +First use disposable books and copied documents; never reimport/reset/delete book 10152 to test this work. + +1. Verify both .23 binaries, retained sign-in/settings/book association and negotiated chapter capability. Development must expose `chapterSyncSupported=true`; .22 remains on its old path. +2. Open a previously indexed, unchanged Heading 1 manuscript in a new Word session. The active chapter should be checked first, then remaining chapters progressively. Confirm current Context scene across chapters, including a chapter not yet checked. No full snapshot request, per-paragraph XML loop, automatic AI call, passive `navigate`, Range.Select or prose edit should occur. +3. Measure the **target**, not an assumed result: current chapter following returns in seconds; individual COM steps aim around 20–30 ms where practical. A single Word COM call cannot be preempted; oversized/complex chapters must report review/fallback rather than freeze or guess. +4. Manual mode: edit/save a chapter, verify `Changed` without prose upload. Explicit Synchronise/Repair authorises that chapter only. On-save mode: verify changed chapter reconciliation, unchanged GUIDs/scenes, later chapters' shifted positions and no AI restart. Word saving must never await Companion. +5. Stop Companion, edit/save, restart. Validate actual chapter evidence again; do not reuse old absolute offsets merely because the book/session looks familiar. +6. Cancel after some chapters are accepted, reconnect/restart and Repair. Previously accepted current-session checkpoints resume; a new session revalidates cheaply. Chapter rename with stable identity may reconcile; inserted/deleted/moved chapter boundaries and duplicate native IDs must require review without canonical reassignment. +7. Switch three documents/books rapidly while checking; close one; terminate/restart the agent. Late frames must not affect another document. No flashing from repeated ribbon invalidation, unexpected focus or selection change. Repeated cursor notifications cannot command Word. +8. Inspect blank/headingless documents, tables/fields/track changes, large chapters and repeated prose. Fast-path refusal is safe; the explicit full snapshot fallback remains available. Do not use fallback automatically or claim unsupported content passed. +9. Check compact progress, book/chapter/scene tooltip, Sync, Repair and Troubleshooting; top-right website Word connection dialog and book → Manuscript structure and evidence show consistent server acceptance. A requested repair must not inherit an earlier green completion. +10. Backup/restore a disposable indexed book. Paragraph/native GUID evidence, canonical remapping, source fingerprints and author decisions must survive. Restored books start Manual and have no live-session trust. + +Only after synthetic qualification, with the author's agreement, use **Repair Manuscript Synchronisation** on the existing 10152 import. Keep its 48 chapters/290 scenes/paragraph GUIDs and SI/author decisions. Missing checkpoints are not corruption. Do not rerun import or analysis. Compare accepted data before/after; stop on ambiguity. Report real Word results separately from automated/HTTP tests, with exact commits and installer hashes. diff --git a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs index 16e36f9f..14bbf793 100644 --- a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs +++ b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs @@ -125,6 +125,10 @@ public sealed partial class CloudGateway : IDisposable =>await Send(HttpMethod.Get,path,null,expectedContext,cancellation); public async Task Post(string path,object body,Guid expectedContext) =>await Send(HttpMethod.Post,path,body,expectedContext); + public Task RequestChapterRepair(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterFinish selected,Guid context)=>Send(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/repair",selected,context); + public Task FinishChapters(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterFinish completion,Guid context)=>Send(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/finish",completion,context); + public Task ChapterManifest(int book,Guid session,long revision,Guid context)=>Send(HttpMethod.Get,$"api/native-companion/books/{book}/chapter-sync?session={session}&wordRevision={revision}",null,context); + public Task ValidateChapter(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterObservation proof,Guid context)=>Send(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/validate",proof,context); 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 static async Task ReadCaptureFailure(HttpResponseMessage response,CancellationToken cancellation) @@ -155,7 +159,7 @@ public sealed partial class CloudGateway : IDisposable lock(gate)if(context==authenticationContext){health.Server=(int)response.StatusCode>=500?"degraded":"online";health.VerifiedUtc=Now.UtcDateTime;health.Explanation=failure.Message;} throw failure; } - 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=Now.UtcDateTime;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.");} + if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")&&!(response.StatusCode==HttpStatusCode.Conflict&&(path.EndsWith("/chapter-sync/validate",StringComparison.Ordinal)||path.EndsWith("/chapter-sync/repair",StringComparison.Ordinal)))){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=Now.UtcDateTime;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>(path=="api/native-companion/manuscript-capture"?4:1)*1024*1024)throw new InvalidDataException();buffer.Write(bytes,0,size);}buffer.Position=0; var result=await JsonSerializer.DeserializeAsync(buffer,Json,stop.Token); diff --git a/PlotDirector.NativeCompanion/Agent/PipeHost.cs b/PlotDirector.NativeCompanion/Agent/PipeHost.cs index 4a35e8db..22bad6ed 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 i.Documents.Count); } } - public void Attach(Guid instance, Guid lease) + public void Attach(Guid instance, Guid lease,bool chapters=false) { lock (gate) { if (instance == Guid.Empty || (!instances.ContainsKey(instance) && instances.Count >= 8)) throw new InvalidDataException("Word instance capacity/identity invalid."); DetachCore(instance); - instances[instance] = new WordInstance(lease); + instances[instance] = new WordInstance(lease){ChapterCapable=chapters}; } } public void Detach(Guid instance, Guid lease) { lock (gate) { if (instances.TryGetValue(instance, out var state) && state.Lease == lease) DetachCore(instance); } } @@ -97,9 +97,14 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai if(message.Kind=="workspace-preview"&&(message.ImportSelection?.SnapshotId!=document.SnapshotId||message.ImportSelection?.ManuscriptId!=document.Descriptor.ManuscriptId)){answer.ImportPreview=new(){RequestId=message.ImportSelection?.RequestId??Guid.Empty,State="rejected",Message="Document snapshot changed. Detect structure and preview again."};return Reject(answer,"stale-preview");} if(message.Kind is "workspace-select" or "workspace-refresh"){var position=new Message();Resolve(document,position);message.ChapterId=position.ChapterId;message.SceneId=position.SceneId;} answer.Kind="workspace-response";return workspace?.Handle(document.Descriptor,message,answer)??Reject(answer,"workspace-unavailable");} + if(message.Kind.StartsWith("chapter-",StringComparison.Ordinal)){ + if(!word.ChapterCapable||message.SnapshotId==Guid.Empty||message.OperationMessage==null||message.OperationMessage.Length>2048||message.Kind is not ("chapter-begin" or "chapter-chunk" or "chapter-end")||(message.Kind=="chapter-begin"&&(message.Start<0||message.End<=message.Start||message.End-message.Start>PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint.MaxCharacters||message.DocumentEnd16000000))||(message.Kind=="chapter-chunk"&&(message.Start<0||message.Start>8*1024*1024||message.Action is not ("text" or "xml"))))return Reject(answer,"invalid-chapter-frame"); + return answer; + } if(message.Kind.StartsWith("ai-",StringComparison.Ordinal))return ai?.Handle(document.Descriptor,message,answer)??Reject(answer,"ai-unavailable"); switch (message.Kind) { + case "tray-sync":case "tray-repair":if(!word.ChapterCapable)return Reject(answer,"unsupported-chapter-capability");break; case "metrics": break; case "adapter-result":break; case "active": word.ActiveSession = message.SessionId; break; @@ -174,7 +179,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai } public Guid? ActiveSession(Guid instance) { lock(gate) return instances.GetValueOrDefault(instance)?.ActiveSession; } public bool HasSession(Guid instance, Guid session) { lock(gate) return instances.TryGetValue(instance,out var word) && word.Documents.ContainsKey(session); } - private sealed class WordInstance(Guid lease) { public Guid Lease = lease; public long LastSequence; public Guid? ActiveSession; public Dictionary Documents = []; } + private sealed class WordInstance(Guid lease) { public bool ChapterCapable;public Guid Lease = lease; public long LastSequence; public Guid? ActiveSession; public Dictionary Documents = []; } private sealed class DocumentState(DocumentDescriptor descriptor) { public DocumentDescriptor Descriptor = descriptor; public int Cursor;public int StructureEnd; public int? WordCount; public Snapshot? Pending; public Guid SnapshotId; public string ContentFingerprint=""; public List Boundaries = []; public DocumentAnalysis? Analysis; } private sealed class Snapshot(Guid id,int expectedEnd,bool analyze) { public readonly DocumentAnalysis Counter=new(analyze); public DocumentAnalysis? Analysis=>analyze?Counter:null; public Guid Id = id; public int ExpectedEnd=expectedEnd; public bool LastComplete; public int End; public int NextParagraph=1; public int Characters; public List Fragments = []; } } diff --git a/PlotDirector.NativeCompanion/Agent/TrayApplication.cs b/PlotDirector.NativeCompanion/Agent/TrayApplication.cs index 45d9b954..6d445c92 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayApplication.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayApplication.cs @@ -116,7 +116,7 @@ internal sealed class CompanionWindow:Form SetText(serverStatus,"PlotDirector · "+CompanionPresentation.Connection(state.Health,DateTime.UtcNow));SetText(account,state.Health?.AccountName??"Not signed in"); SetText(wordStatus,CompanionPresentation.WordStatus(doc!=null,doc?.Book??0,doc?.LastPresenceUtc??DateTime.MinValue,doc?.LastPresenceKey??"",DateTime.UtcNow)); authorise.Visible=CompanionPresentation.NeedsAuthorisation(state.Health);authorise.Enabled=!string.IsNullOrWhiteSpace(state.ServerUrl); - SetText(guidance,doc==null?"Open a manuscript in Microsoft Word. Your words stay in Word until you request an import in PlotDirector.":doc.Book==0?"Choose the PlotDirector book for this manuscript.":"Import, Context and Intent are available in PlotDirector."); + SetText(guidance,doc==null?"Open a manuscript in Microsoft Word. Your words stay in Word until you request an import in PlotDirector.":doc.Book==0?"Choose the PlotDirector book for this manuscript.":doc.ChapterProgress is {} chapters?$"{chapters.State} · {chapters.Matching}/{chapters.Total} chapters accepted. {chapters.Message}":"Import, Context and Intent are available in PlotDirector."); SetText(bookTitle,book==null?"No book associated":string.IsNullOrEmpty(book.BookTitle)?book.Title:book.BookTitle);SetText(projectTitle,book?.ProjectTitle??"Choose a book to connect your writing workspace."); var noticeText=error!=""?error:doc?.AssociationNotice??"";SetText(notice,noticeText);if(settingsNotice is {IsDisposed:false}){SetText(settingsNotice,error);settingsNotice.Visible=error!="";}notice.Visible=noticeText!="";tips.SetToolTip(serverStatus,state.Health?.Explanation??"Connect in Settings."); var text=$"Server: {state.ServerUrl}\r\nAccount: {state.Health?.AccountName}\r\n{state.Health?.Explanation}\r\n"+string.Join("\r\n",displayed.Select(d=>$"{d.Title} · session {d.Session} · book {d.Book}"))+"\r\n"+doc?.WordDiagnostics+"\r\n"+doc?.Status+"\r\n"+doc?.MaintenanceReport; diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs new file mode 100644 index 00000000..33c1cde2 --- /dev/null +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs @@ -0,0 +1,128 @@ +using System.Text; +using PlotDirector.Companion.Protocol; +using PlotDirector.Companion.Protocol.Manuscript; +namespace PlotDirector.Companion.Agent; +public sealed partial class TrayCoordinator +{ + private sealed class ChapterWork + { + public int Book;public Guid Manuscript;public long Revision;public Guid Context,Operation,Command;public bool Busy,Supported,Processing,Begun;public long FailedRevision=-1;public DateTime Started,RetryAfter; + public ChapterManifest? Manifest;public readonly Dictionary Checked=[]; + public StringBuilder Text=new(),Xml=new();public int Start,End,DocumentEnd,FirstStart=-1;public bool Finished;public bool Wrapped;public readonly HashSet Reviewed=[];public readonly HashSet Visited=[];public string Next=""; + } + private readonly Dictionary chapterWork=[]; + private string ChapterIssue(TrayDocument doc){lock(gate)return chapterWork.TryGetValue(doc.Session,out var work)&&work.FailedRevision==doc.Revision?"needs_review":"";} + private bool ChapterCapable(Guid instance){lock(gate)return chapterInstances.Contains(instance);} + private readonly HashSet ribbonRequests=[]; + private async Task RequestChapterFromRibbon(TrayDocument doc,long revision) + { + int book;Guid context,instance,session; + lock(gate){if(ribbonRequests.Count>=32||!ribbonRequests.Add(doc.Session))return;book=doc.Book;context=doc.Authentication;instance=doc.Instance;session=doc.Session;} + try{if(!cloud.Allows(context,book))throw new InvalidOperationException("Connect and select an authorised book first.");var reply=await cloud.RequestChapterRepair(book,new(){InstanceId=instance,SessionId=session,WordRevision=revision},context);lock(gate)if(documents.GetValueOrDefault(session)==doc&&doc.Revision==revision&&doc.Authentication==context){doc.Status=reply.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}} + catch(Exception e)when(NetworkFailure(e)){lock(gate)if(documents.GetValueOrDefault(session)==doc)doc.Status="Chapter request was not accepted: "+e.Message;} + finally{lock(gate)ribbonRequests.Remove(session);} + } + private bool IsChapterCommand(TrayDocument doc,Guid id)=>chapterWork.TryGetValue(doc.Session,out var work)&&id!=Guid.Empty&&work.Command==id; + private void CancelChapterWork(TrayDocument doc){if(chapterWork.TryGetValue(doc.Session,out var work)){work.Command=Guid.Empty;work.Operation=Guid.Empty;work.Text=new();work.Xml=new();doc.ChapterProgress=null;work.Busy=false;work.FailedRevision=doc.Revision;}} + private void BeginChapterRepair(TrayDocument doc,Guid operation) + { + if(!ChapterCapable(doc.Instance))return; + var work=GetChapterWork(doc);work.Operation=operation;work.FailedRevision=-1;work.Manifest=null;work.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.Wrapped=false;work.FirstStart=-1;work.Finished=false;work.Command=Guid.Empty;work.Busy=false; + doc.Status="Repairing existing chapter mappings; accepted scenes and author decisions are retained.";work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work); + } + private ChapterWork GetChapterWork(TrayDocument doc) + { + if(!chapterWork.TryGetValue(doc.Session,out var work)||work.Context!=doc.Authentication||work.Revision!=doc.Revision||work.Book!=doc.Book||work.Manuscript!=doc.Manuscript)chapterWork[doc.Session]=work=new(){Book=doc.Book,Manuscript=doc.Manuscript,Revision=doc.Revision,Context=doc.Authentication};return work; + } + private void ObserveChapterPresence(TrayDocument doc,NativePresence reply) + { + if(!ChapterCapable(doc.Instance))return; + lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc)return;var work=GetChapterWork(doc);work.Supported=reply.ChapterSyncSupported; + if(work.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Manifest=null;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;} + if(DateTime.UtcNowwork.Start&&doc.Active&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor=work.End)){QueueChapter(doc,work,doc.Cursor);return;}if(DateTime.UtcNow-work.Started>TimeSpan.FromMinutes(2)){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Chapter validation timed out. Accepted checkpoints are retained; request Repair to resume.";}return;} + if(work.Manifest==null){work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work);return;} + var here=work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor!work.Checked.ContainsKey(c.ChapterId)&&!work.Reviewed.Contains(c.ChapterId)&&(c.State!="Needs review"||work.Operation!=Guid.Empty)); + if(next!=null)QueueChapter(doc,work,next.Start); + } + } + private async Task LoadChapterManifest(TrayDocument doc,ChapterWork work) + { + try{var manifest=await cloud.ChapterManifest(doc.Book,doc.Session,doc.Revision,doc.Authentication); + lock(gate){if(!CurrentChapterWork(doc,work))return;if(manifest.ManuscriptId!=doc.Manuscript)throw new InvalidOperationException("Saved manuscript identity does not match this Word document.");work.Manifest=manifest;work.Busy=false;if(manifest.Mode=="Off"&&work.Operation==Guid.Empty){work.Finished=true;doc.Status="Automatic synchronisation is off. Use Synchronise or Repair for an explicit chapter check.";return;}foreach(var chapter in manifest.Chapters.Where(c=>c.State=="Synchronised"))work.Checked[chapter.ChapterId]=(chapter.Start,chapter.End);doc.Status=$"Chapter index ready: {work.Checked.Count}/{manifest.Chapters.Length} accepted for this Word session.";if(manifest.Chapters.Length>0&&work.Checked.Count==manifest.Chapters.Length){CompleteChapters(doc,work);}else if(manifest.Chapters.Length>0&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor!work.Checked.ContainsKey(c.ChapterId));if(next!=null)QueueChapter(doc,work,next.Start);}} + }catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;doc.Status="Chapter index unavailable: "+e.Message+" Existing import is retained; no full extraction was started.";}} + } + private bool CurrentChapterWork(TrayDocument doc,ChapterWork work)=>documents.GetValueOrDefault(doc.Session)==doc&&chapterWork.GetValueOrDefault(doc.Session)==work&&doc.Revision==work.Revision&&doc.Authentication==work.Context&&doc.Book==work.Book&&doc.Manuscript==work.Manuscript; + private void QueueChapter(TrayDocument doc,ChapterWork work,int position) + { + if(chapterWork.Values.Count(w=>w!=work&&w.Busy&&w.Command!=Guid.Empty)>=2){ + if(!doc.Active)return; + var background=chapterWork.FirstOrDefault(p=>p.Value!=work&&p.Value.Busy&&p.Value.Command!=Guid.Empty&&documents.TryGetValue(p.Key,out var candidate)&&!candidate.Active); + if(background.Value==null||!documents.TryGetValue(background.Key,out var backgroundDoc))return; + Queue(backgroundDoc,new(){Kind="chapter-cancel"});background.Value.Command=Guid.Empty;background.Value.Busy=false;background.Value.Text=new();background.Value.Xml=new(); + } + var command=new AdapterCommand{Kind="chapter-check",OperationId=work.Operation,BookId=doc.Book,Chapter=new(){Start=position}}; + if(Queue(doc,command)){work.Command=command.Id;work.Busy=true;work.Processing=false;work.Begun=false;work.Start=work.End=0;work.Started=DateTime.UtcNow;work.Text.Clear();work.Xml.Clear();doc.Status=$"Checking chapter positions ({work.Checked.Count}/{work.Manifest!.Chapters.Length} accepted); Word prose is unchanged.";} + } + private void ChapterFrame(TrayDocument doc,Message message,Message answer) + { + if(!chapterWork.TryGetValue(doc.Session,out var work)||!CurrentChapterWork(doc,work)||work.Command!=message.SnapshotId)return; + if(message.Kind=="adapter-result"&&message.OperationMessage!="ok"){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status=message.OperationMessage;return;} + if(!message.Kind.StartsWith("chapter-",StringComparison.Ordinal))return; + if(answer.Status!="ok"){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Chapter reading was rejected; accepted checkpoints are unchanged.";return;} + if(message.Kind=="chapter-begin"){if(work.Begun)return;work.Begun=true;work.Start=message.Start;if(work.FirstStart<0)work.FirstStart=message.Start;work.End=message.End;work.DocumentEnd=message.DocumentEnd;work.Next=message.ChapterTitle;work.Text.Clear();work.Xml.Clear();return;} + if(message.Kind=="chapter-chunk"){if(!work.Begun||work.Processing)return; + var value=message.Action=="text"?work.Text:work.Xml;var limit=message.Action=="text"?ChapterFingerprint.MaxCharacters:8*1024*1024; + if(message.Start!=value.Length||value.Length+message.OperationMessage.Length>limit){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Incomplete or oversized chapter frames; no checkpoint accepted.";return;}value.Append(message.OperationMessage);return; + } + if(message.Kind=="chapter-end"){if(!work.Begun||work.Processing)return;work.Processing=true;var text=work.Text.ToString();var xml=work.Xml.ToString();work.Text=new();work.Xml=new();_ = ProcessChapter(doc,work,text,xml,work.Command,work.Start,work.End,work.Next,work.Operation);} + } + private void AdvanceChapter(TrayDocument doc,ChapterWork work) + { + if(work.Manifest==null)return; + var next=work.End; + for(int count=0;countp.Value.Start==next&&p.Value.End>next); + if(cached.Value.End>next){next=cached.Value.End;continue;} + break; + } + if(work.FirstStart==0&&next>=work.DocumentEnd){CompleteChapters(doc,work);return;} + if(nextid>0).ToArray(),HasIssues=work.Reviewed.Count>0||work.Manifest!.Chapters.Any(c=>!work.Checked.ContainsKey(c.ChapterId))},work.Context);lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;doc.Status=result.Message;}} + catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;work.Finished=false;work.Manifest=null;work.RetryAfter=DateTime.UtcNow.AddSeconds(15);doc.Status="Accepted checkpoints are retained; final chapter status will be retried after reconnect: "+e.Message;}} + } + private async Task ProcessChapter(TrayDocument doc,ChapterWork work,string text,string xml,Guid command,int start,int end,string nextHeading,Guid operation) + { + try{ + lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(work.Wrapped&&start==work.FirstStart){CompleteChapters(doc,work);return;}} + var rows=await Task.Run(()=>ChapterFingerprint.ReadXml(xml,text));xml="";text=""; + ChapterManifest manifest;lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;manifest=work.Manifest!;} + var hash=ChapterFingerprint.Content(rows.Select(p=>p.Text!)); + var candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==rows[0].NativeId).ToArray(); + if(candidates.Length==0&&work.Operation!=Guid.Empty)candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==""&&c.ContentHash==hash&&c.ParagraphCount==rows.Length).ToArray(); + if(candidates.Length!=1){lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;work.Reviewed.Add(-work.Start-1);doc.Status="An unrecognised or ambiguous chapter needs review; no chapter was guessed by name.";AdvanceChapter(doc,work);}return;} + var chapter=candidates[0];lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(!work.Visited.Add(chapter.ChapterId)){work.Busy=false;if(!work.Checked.TryGetValue(chapter.ChapterId,out var earlier)||earlier.Start!=start||earlier.End!=end){work.Reviewed.Add(chapter.ChapterId);work.Checked.Remove(chapter.ChapterId);doc.Status="Duplicate chapter identity at another position; existing canonical structure is retained for review.";}AdvanceChapter(doc,work);return;}}var proof=new ChapterObservation{RequestId=command,OperationId=operation,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,WordRevision=doc.Revision,BaseRevision=manifest.Revision,ChapterId=chapter.ChapterId,Start=start,End=end,NextHeadingId=nextHeading,ContentHash=hash,IdentityHash=ChapterFingerprint.Identity(rows),Paragraphs=rows.Select(p=>new ChapterParagraph{NativeId=p.NativeId,Length=p.Length,Outline=p.Outline}).ToArray()}; + var result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication); + if(!result.Accepted&&result.State=="Changed"&&result.AllowText){proof.Reconcile=true;proof.Paragraphs=rows;result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);} + lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false; + if(result.Accepted){work.Checked[chapter.ChapterId]=(start,end);manifest.Revision=result.Revision;if(result.State=="Needs review")work.Reviewed.Add(chapter.ChapterId);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status=$"{work.Checked.Count}/{manifest.Chapters.Length} chapters accepted · "+result.Message;AdvanceChapter(doc,work);} + else{work.Reviewed.Add(chapter.ChapterId);doc.Status=result.Message+" Accepted chapter repairs are retained.";AdvanceChapter(doc,work);} + } + }catch(Exception e)when(NetworkFailure(e)||e is ArgumentException or System.Xml.XmlException){lock(gate)if(CurrentChapterWork(doc,work)&&work.Command==command){work.Busy=false; + if(e is HttpRequestException or OperationCanceledException||cloud.Status().Health?.Authentication!="verified"){work.Manifest=null;work.Command=Guid.Empty;work.Visited.Clear();work.RetryAfter=DateTime.UtcNow.AddSeconds(15);doc.Status="Chapter connection interrupted; accepted checkpoints are retained and validation will resume after reconnect.";} + else if(e is ArgumentException or System.Xml.XmlException&&end>start){work.Reviewed.Add(-start-1);doc.Status="Chapter content needs review: "+e.Message+" Other chapters can continue.";AdvanceChapter(doc,work);} + else{work.FailedRevision=doc.Revision;doc.Status="Chapter needs review: "+e.Message+" Existing import is unchanged.";}}} + } +} diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs index 9767685b..1f3fd554 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs @@ -2,18 +2,18 @@ using PlotDirector.Companion.Protocol; namespace PlotDirector.Companion.Agent; // One control centre in the existing agent. Exact-session commands only; no COM or UI objects. -public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,ChapterAiWork ai) +public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway cloud,ChapterAiWork ai) { private readonly Guid agentInstance=Guid.NewGuid(),agentSession=Guid.NewGuid();private int lastBook;private Guid lastAuthentication;private long agentSequence;private long presenceSequence=DateTime.UtcNow.Ticks;private int uploading;private DateTime lastAgentPresence;private bool agentOnlyPublished; private bool ParagraphCapable(Guid instance){lock(gate)return paragraphInstances.Contains(instance);} private readonly ParagraphSnapshotCache paragraphSnapshots=new(); - private readonly HashSet paragraphInstances=[]; + private readonly HashSet paragraphInstances=[];private readonly HashSet chapterInstances=[]; private readonly object gate=new();private readonly Dictionary documents=[]; private readonly Dictionary> commands=[];private readonly Dictionary leases=[];private readonly HashSet captureInstances=[];private readonly HashSet maintenanceInstances=[];private readonly Dictionary maintenance=[];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,bool capture=false,bool canMaintain=false,bool paragraphs=false){lock(gate){Disconnected(instance);if(paragraphs)paragraphInstances.Add(instance);else paragraphInstances.Remove(instance);leases[instance]=lease;if(canMaintain)maintenanceInstances.Add(instance);else maintenanceInstances.Remove(instance);if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}} + public void Attach(Guid instance,Guid lease,bool capture=false,bool canMaintain=false,bool paragraphs=false,bool chapters=false){lock(gate){Disconnected(instance);if(chapters)chapterInstances.Add(instance);else chapterInstances.Remove(instance);if(paragraphs)paragraphInstances.Add(instance);else paragraphInstances.Remove(instance);leases[instance]=lease;if(canMaintain)maintenanceInstances.Add(instance);else maintenanceInstances.Remove(instance);if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}} public Message Exchange(Guid instance,Message request,Message answer,Guid lease=default) { lock(gate) @@ -37,8 +37,10 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C 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;doc.WordSaved=request.WordSaved;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}} + ChapterFrame(doc,request,answer); + if(request.Kind is "tray-sync" or "tray-repair")_ = RequestChapterFromRibbon(doc,request.Revision); 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((request.Kind=="selection"||request.Kind=="snapshot-end")&&!ChapterCapable(instance)){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.";} if(request.Kind=="snapshot-fragment")doc.Progress=answer.Progress; @@ -49,19 +51,22 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C doc.AssociationNeedsSave=request.OperationMessage=="association-written"; doc.AssociationNotice=doc.AssociationNeedsSave?"Book remembered in Word. Save the document to keep this association.":request.OperationMessage=="ok"?"Update the Word add-in to confirm the association was written.":request.OperationMessage; } - else if(request.Kind=="adapter-result"&&request.OperationMessage!="ok"&&request.OperationMessage!="association-written"){doc.Status=request.OperationMessage;Cancel(doc);} + else if(request.Kind=="adapter-result"&&!IsChapterCommand(doc,request.SnapshotId)&&request.OperationMessage!="ok"&&request.OperationMessage!="association-written"){doc.Status=request.OperationMessage;Cancel(doc);} if(request.Kind=="ai-cancel"){Cancel(doc);doc.Status="Extraction cancelled or document changed. Successful server suggestions are retained.";} if(request.Kind=="metrics")doc.WordDiagnostics=request.OperationMessage.Length<=6000?request.OperationMessage:"Diagnostics size exceeded"; if(request.Kind=="ai-fragment")doc.Progress=answer.Progress; if(request.Kind.StartsWith("ai-",StringComparison.Ordinal)&&answer.Status!="ok"){doc.Status="Chapter could not be read: "+answer.Status;Cancel(doc);} } } + if(documents.TryGetValue(request.SessionId,out var activeDocument)&&ChapterCapable(instance)&&request.Kind is "selection" or "metrics"){ + answer.ChapterStatusProvided=true;answer.BookId=activeDocument.Book;answer.BookTitle=cloud.Status().Books.FirstOrDefault(b=>b.BookId==activeDocument.Book)?.Title??"";answer.ChapterTitle=activeDocument.ChapterTitle;answer.SceneTitle=activeDocument.SceneTitle;answer.ChapterProgress=activeDocument.ChapterProgress; + } if(commands.TryGetValue(instance,out var queue)&&queue.Count>0)answer.Command=queue.Dequeue(); 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 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){paragraphSnapshots.Remove(session);foreach(var key in maintenance.Where(p=>p.Value.Session==session).Select(p=>p.Key).ToArray())maintenance.Remove(key);if(documents.Remove(session,out var doc)){Cancel(doc);_ = cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);}} + public void Disconnected(Guid instance,Guid lease=default){lock(gate){if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return;leases.Remove(instance);chapterInstances.Remove(instance);paragraphInstances.Remove(instance);captureInstances.Remove(instance);maintenanceInstances.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){chapterWork.Remove(session);paragraphSnapshots.Remove(session);foreach(var key in maintenance.Where(p=>p.Value.Session==session).Select(p=>p.Key).ToArray())maintenance.Remove(key);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 bool CanMaintain(Guid session){lock(gate)return documents.TryGetValue(session,out var d)&&maintenanceInstances.Contains(d.Instance);} public void Maintain(Guid session,string kind) @@ -97,7 +102,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){doc.RetryCapture=null;foreach(var request in maintenance.Where(p=>p.Value.Session==doc.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(request);doc.MaintenanceReport="Stopped: superseded by a document or account change. Inspect before retrying cleanup.";}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"});} + private void Cancel(TrayDocument doc){CancelChapterWork(doc);doc.RetryCapture=null;foreach(var request in maintenance.Where(p=>p.Value.Session==doc.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(request);doc.MaintenanceReport="Stopped: superseded by a document or account change. Inspect before retrying cleanup.";}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) { @@ -119,13 +124,13 @@ 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.Authentication==cloud.Status().AuthenticationContext&&cloud.Status().Health?.Authentication=="verified").ToArray(); - foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc0)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext){if(doc.ChapterId!=reply.ChapterId)doc.ChapterTitle="";if(doc.SceneId!=reply.SceneId)doc.SceneTitle="";doc.ChapterId=reply.ChapterId;doc.SceneId=reply.SceneId;} + foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc0)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext){doc.ChapterId=reply.ChapterId;doc.SceneId=reply.SceneId;} if(reply.Navigation is {Kind:"wizard-capture",BookId:>0} requested&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Book==0){await cloud.CheckConnection();lock(gate){if(doc.Book==0&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext&&cloud.Allows(doc.Authentication,requested.BookId)&&documents.GetValueOrDefault(doc.Session)==doc){doc.Book=requested.BookId;cloud.RememberBinding(doc.Manuscript,doc.Book,doc.Authentication);doc.LastPresenceKey="";}}} if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision){if((reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")&&captureInstances.Contains(doc.Instance)&&(reply.Navigation.BookId==0||reply.Navigation.BookId==doc.Book)&&cloud.Allows(doc.Authentication,doc.Book)){if(uploading!=0||documents.Values.Any(d=>d.Capture!=null)){_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);continue;}var retained=doc.RetryCapture;var reusable=retained!=null&&doc.RetryAuthentication==doc.Authentication&&doc.RetryBook==doc.Book&&retained.ManuscriptId==doc.Manuscript&&retained.Revision==doc.Revision&&retained.ParagraphTracking==reply.Navigation.ParagraphTracking; Cancel(doc);doc.Capture=new(){RequestId=reply.Navigation.Id,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,Revision=doc.Revision,ParagraphTracking=reply.Navigation.ParagraphTracking,End=reusable?retained!.End:0};doc.CaptureBaseRevision=reply.Navigation.BaseRevision;doc.CaptureBaseHash=reply.Navigation.BaseSnapshotHash;doc.CaptureFragments.Clear(); if(reusable){doc.CaptureFragments.AddRange(retained!.Paragraphs);doc.Status="Retrying the retained unchanged manuscript at your import request…";CaptureFrame(doc,new(){Kind="snapshot-end",SnapshotId=reply.Navigation.Id},new(){Status="ok"});} - else{doc.Status="Reading manuscript for the PlotDirector import wizard…";Queue(doc,reply.Navigation);}}else if(reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);else if(reply.Navigation.Kind=="cancel")Cancel(doc);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;}} + else{doc.Status="Reading manuscript for the PlotDirector import wizard…";Queue(doc,reply.Navigation);}}else if(reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);else if(reply.Navigation.Kind=="cancel")Cancel(doc);else if(reply.Navigation.Kind=="chapter-repair"){BeginChapterRepair(doc,reply.Navigation.Id);}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&&cloud.Status().Health?.Authentication=="verified"&&DateTime.UtcNow-lastAgentPresence>=TimeSpan.FromSeconds(15)){lastAgentPresence=DateTime.UtcNow;agentOnlyPublished=true;try{await cloud.Presence(agentInstance,agentSession,new(){WordRunning=leases.Count>0,BookId=0,Sequence=Interlocked.Increment(ref agentSequence),WordAvailable=false,DocumentTitle="No Word document"},cloud.Status().AuthenticationContext);}catch(Exception e)when(NetworkFailure(e)) {}} else if(available.Length>0&&agentOnlyPublished){agentOnlyPublished=false;await cloud.RemovePresence(agentInstance,agentSession);} } @@ -172,6 +177,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C } public sealed class TrayDocument { + public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress; 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=""; internal ManuscriptCapture? RetryCapture;internal Guid RetryAuthentication;internal int RetryBook; public long CaptureBaseRevision;public string CaptureBaseHash="";public ManuscriptCapture? Capture;public List CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision; diff --git a/PlotDirector.NativeCompanion/Client/AgentLink.cs b/PlotDirector.NativeCompanion/Client/AgentLink.cs index aa99a7fb..6eef876c 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+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability }, 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+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability+","+ProtocolVersion.ChapterSyncCapability }, 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 2ff5caa4..c6398c6c 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.22 +1.0.0.23 diff --git a/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs index 04136ff2..d58a15a1 100644 --- a/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs +++ b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs @@ -101,3 +101,21 @@ public sealed class ChapterSyncReply { public bool Accepted{get;set;}public string State{get;set;}="Not yet checked";public string Message{get;set;}="";public int ChapterId{get;set;}public long Revision{get;set;}public bool AllowText{get;set;} } + +[DataContract] +public sealed class ChapterSyncProgress +{ + [DataMember] public int Total {get;set;} + [DataMember] public int Checked {get;set;} + [DataMember] public int Matching {get;set;} + [DataMember] public int Repaired {get;set;} + [DataMember] public int NeedsReview {get;set;} + [DataMember] public int? CurrentChapterId {get;set;} + [DataMember] public string State {get;set;}="Not yet checked"; + [DataMember] public string Message {get;set;}=""; +} +public sealed class ChapterFinish +{ + public Guid InstanceId{get;set;}public Guid SessionId{get;set;}public long WordRevision{get;set;}public Guid OperationId{get;set;}public bool HasIssues{get;set;}public int[] ReviewChapterIds{get;set;}=Array.Empty(); +} +public sealed class ChapterRepairRequested {public Guid OperationId{get;set;}public string Message{get;set;}="";} diff --git a/PlotDirector.NativeCompanion/Protocol/Messages.cs b/PlotDirector.NativeCompanion/Protocol/Messages.cs index 255b058a..ae90c2e9 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 ChapterSyncCapability="chapter-sync-v1"; public const string ParagraphCapability="paragraph-snapshots-v1"; public const string MaintenanceCapability="document-maintenance-v1"; public const string CaptureCapability="wizard-capture-v1"; @@ -28,6 +29,10 @@ public static class ProtocolVersion [DataContract] public sealed class Message { + [DataMember] public bool ChapterStatusProvided {get;set;} + [DataMember] public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress {get;set;} + [DataMember] public string BookTitle {get;set;}=""; + [DataMember] public Guid OperationId {get;set;} [DataMember] public AdapterCommand? Command {get;set;} [DataMember] public string OperationMessage {get;set;}=""; [DataMember] public int Version { get; set; } = ProtocolVersion.Current; @@ -38,6 +43,7 @@ public sealed class Message [DataMember] public long Sequence { get; set; } [DataMember] public long Revision { get; set; } [DataMember] public Guid SnapshotId { get; set; } + [DataMember] public int DocumentEnd {get;set;} [DataMember] public int Start { get; set; } [DataMember] public int End { get; set; } [DataMember] public DocumentDescriptor[] Documents { get; set; } = Array.Empty(); diff --git a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs index e91b4f7b..ac414ef1 100644 --- a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs +++ b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs @@ -3,6 +3,7 @@ namespace PlotDirector.Companion.Protocol; [DataContract] public sealed class AdapterCommand { + [DataMember] public Guid OperationId {get;set;} [DataMember] public bool ParagraphTracking {get;set;} [DataMember] public long BaseRevision {get;set;} [DataMember] public string BaseSnapshotHash {get;set;}=""; @@ -22,6 +23,10 @@ public sealed class NativePresence [DataMember] public Guid[]? CanonicalParagraphIds {get;set;} [DataMember] public long ParagraphRevision {get;set;} [DataMember] public string ParagraphSnapshotHash {get;set;}=""; + [DataMember] public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress {get;set;} + [DataMember] public string ChapterIssue {get;set;}=""; + [DataMember] public string ChapterTitle {get;set;}=""; + [DataMember] public string SceneTitle {get;set;}=""; [DataMember] public bool CanChapterSync {get;set;} [DataMember] public bool ChapterSyncSupported {get;set;} [DataMember] public bool CanParagraphSync {get;set;} diff --git a/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs b/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs new file mode 100644 index 00000000..25ee1a91 --- /dev/null +++ b/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs @@ -0,0 +1,52 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using PlotDirector.Companion.Agent; +using PlotDirector.Companion.Protocol; +using PlotDirector.Companion.Protocol.Manuscript; +internal static class ChapterAgentTests +{ + public static async Task Run() + { + var handler=new Handler();using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://chapters.test/");await Until(()=>cloud.Status().Books.Any());await cloud.CheckConnection(); + var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var tray=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid();handler.Manuscript=Guid.NewGuid();long sequence=0; + sessions.Attach(instance,lease,chapters:true);tray.Attach(instance,lease,capture:true,paragraphs:true,chapters:true); + Message Send(Message message){message.WordInstanceId=instance;message.SessionId=session;message.Revision=1;message.Sequence=++sequence;return tray.Exchange(instance,message,sessions.Apply(lease,message),lease);} + Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Synthetic chapter manuscript.docx"}]});tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}); + using var stop=new CancellationTokenSource();var heartbeats=tray.Heartbeat(stop.Token); + try{ + AdapterCommand? command=null;for(int n=0;n<200&&command==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")command=pending;await Task.Delay(20);} + Check(command?.Kind=="chapter-check","Reopened chapter-capable document requests a bounded current-chapter read, never a full snapshot"); + var text="Chapter 1\rExact prose\r";var xml="Chapter 1Exact prose"; + void Frames(AdapterCommand read){Send(new(){Kind="chapter-begin",SnapshotId=read.Id,BookId=3,Start=0,End=text.Length,DocumentEnd=text.Length,WordSaved=true});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="text",Start=0,OperationMessage=text});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="xml",Start=0,OperationMessage=xml});Send(new(){Kind="chapter-end",SnapshotId=read.Id});} + Frames(command!);await Until(()=>handler.Validations>0);await Until(()=>handler.Finishes>0); + Check(handler.Bodies.All(b=>JsonSerializer.Deserialize(b,new JsonSerializerOptions(JsonSerializerDefaults.Web))!.Paragraphs.All(p=>p.Text==null)),"Unchanged chapter uploads hashes and native identity evidence, not manuscript prose"); + Check(!handler.Paths.Any(p=>p.Contains("manuscript-capture")),"Chapter lifecycle does not invoke the full manuscript capture endpoint"); + var before=handler.Validations;for(int n=0;n<100;n++){var response=Send(new(){Kind="selection",Start=12,End=12,WordSaved=true});Check(response.Command?.Kind!="navigate","Passive selection never returns a navigation command");}await Task.Delay(650);Check(handler.Validations==before,"Repeated cursor events reuse accepted current-session chapter validation"); + Check(tray.Documents.Single().Status.Contains("accepted"),"Chapter completion is reported only after server acceptance"); + var chunkReply=Send(new(){Kind="chapter-chunk",SnapshotId=Guid.NewGuid(),Action="xml",Start=0,OperationMessage="late"});Check(!chunkReply.ChapterStatusProvided,"Chapter chunks do not schedule repeated ribbon updates or invalidate Word during extraction"); + Frames(command!);await Task.Delay(100);Check(handler.Validations==before,"Delayed duplicate chapter frames cannot resubmit an accepted operation"); + var oldSession=session;session=Guid.NewGuid();Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Second synthetic document.docx"}]});tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}); + AdapterCommand? second=null;for(int n=0;n<200&&second==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")second=pending;await Task.Delay(20);} + Check(second?.Kind=="chapter-check"&&second.SessionId==session,"A second Word document has independent chapter work and cannot inherit the first session's trust"); + Send(new(){Kind="close"});Frames(second!);await Task.Delay(100);Check(handler.Validations==before,"Closing a document rejects late extraction frames and preserves already accepted chapters");session=oldSession; + var wrong=new Message{Kind="chapter-chunk",SnapshotId=command!.Id,Action="xml",Start=0,OperationMessage="wrong"};var legacySessions=new SessionManager();legacySessions.Attach(instance,lease);long legacySequence=0;Message Legacy(Message m){m.WordInstanceId=instance;m.SessionId=session;m.Sequence=++legacySequence;m.Revision=1;return legacySessions.Apply(lease,m);}Legacy(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Legacy"}]});Check(Legacy(wrong).Status=="invalid-chapter-frame","Chapter frames require negotiated native capability; legacy clients remain isolated"); + }finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}} + } + private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);} + private static async Task Until(Func condition){for(int i=0;i<300;i++){if(condition())return;await Task.Delay(30);}throw new Exception("Chapter test timed out");} + private sealed class Handler:HttpMessageHandler + { + public Guid Manuscript;public int Validations,Finishes;public List Bodies=[];public List Paths=[]; + protected override async Task SendAsync(HttpRequestMessage request,CancellationToken cancel) + { + var path=request.RequestUri!.AbsolutePath;Paths.Add(path);HttpResponseMessage Json(object value)=>new(HttpStatusCode.OK){Content=JsonContent.Create(value)}; + if(path.EndsWith("/pair"))return Json(new{code="00112233445566778899AABB"});if(path.EndsWith("/token"))return Json(new{accessToken="fixture"});if(path.EndsWith("/books"))return Json(new[]{new{bookId=3,title="Synthetic book"}});if(path.EndsWith("/connection"))return Json(new{state="Connected",authentication="verified",server="online",expiresUtc=DateTime.UtcNow.AddHours(4)}); + if(path.EndsWith("/presence")){var value=await request.Content!.ReadFromJsonAsync(cancel);value!.ChapterSyncSupported=true;value.ParagraphRevision=1;return Json(value);} + if(path.EndsWith("/chapter-sync"))return Json(new ChapterManifest{BookId=3,ManuscriptId=Manuscript,Revision=1,Chapters=[new(){ChapterId=10,HeadingNativeId="00000001",ContentHash=ChapterFingerprint.Content(["Chapter 1\r","Exact prose\r"]),Start=0,End=22,ParagraphCount=2}]}); + if(path.EndsWith("/validate")){var body=await request.Content!.ReadAsStringAsync(cancel);Bodies.Add(body);Validations++;return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",ChapterId=10,Revision=1,Message="Chapter accepted."});} + if(path.EndsWith("/finish")){Finishes++;return Json(new ChapterSyncProgress{Total=1,Checked=1,Matching=1,State="Synchronised",Message="All chapters accepted."});} + return Json(new{}); + } + } +} diff --git a/PlotDirector.NativeCompanion/Tests/Program.cs b/PlotDirector.NativeCompanion/Tests/Program.cs index d77726d9..5ba8d75b 100644 --- a/PlotDirector.NativeCompanion/Tests/Program.cs +++ b/PlotDirector.NativeCompanion/Tests/Program.cs @@ -3,6 +3,7 @@ using PlotDirector.Companion.Agent; using PlotDirector.Companion.Client; using PlotDirector.Companion.Protocol; +if(args.Contains("--chapter-sync")){await ChapterAgentTests.Run();return;} if(args.Contains("--native-capture-upload")){await NativeCaptureUploadTests.Run();return;} var passed = 0; void Check(bool value,string name) {if(!value)throw new Exception(name);passed++;Console.WriteLine("PASS "+name);} diff --git a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs index 7c609266..00be914e 100644 --- a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs +++ b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs @@ -8,11 +8,16 @@ namespace PlotDirector.WordAddIn [ComVisible(true)] public sealed class NativeRibbon:Office.IRibbonExtensibility { - private readonly Func adapter;private Office.IRibbonUI ui;private string lastStatus; + private readonly Func adapter;private Office.IRibbonUI ui;private string lastStatus,lastSync; public NativeRibbon(Func adapter){this.adapter=adapter;} public string GetCustomUI(string ribbonID){using(var reader=new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("PlotDirector.WordAddIn.Ribbon.xml")))return reader.ReadToEnd();} - public void OnLoad(Office.IRibbonUI ribbonUI){ui=ribbonUI;lastStatus=GetStatus(null);} - public void Invalidate(){try{var status=GetStatus(null);if(status==lastStatus)return;lastStatus=status;ui?.InvalidateControl("PlotDirectorStatus");}catch(COMException){}} + public void OnLoad(Office.IRibbonUI ribbonUI){ui=ribbonUI;lastStatus=GetStatus(null);lastSync=GetSyncStatus(null)+GetSyncTip(null);} + public void Invalidate(){try{var status=GetStatus(null);if(status!=lastStatus){lastStatus=status;ui?.InvalidateControl("PlotDirectorStatus");}var sync=GetSyncStatus(null)+GetSyncTip(null);if(sync!=lastSync){lastSync=sync;ui?.InvalidateControl("PlotDirectorSyncStatus");}}catch(COMException){}} + public string GetSyncStatus(Office.IRibbonControl control)=>adapter()?.ChapterStatusLabel??"Chapter index unavailable"; + public string GetSyncTip(Office.IRibbonControl control)=>adapter()?.ChapterStatusTip??"Open Companion to connect this manuscript."; + public void Synchronise(Office.IRibbonControl control)=>adapter()?.RequestChapterSynchronisation(false); + public void Repair(Office.IRibbonControl control)=>adapter()?.RequestChapterSynchronisation(true); + public void Troubleshooting(Office.IRibbonControl control)=>adapter()?.ShowTroubleshooting(); public string GetStatus(Office.IRibbonControl control)=>"Local Companion: "+(adapter()?.ConnectionState??"unavailable"); public void RemoveLegacyMarkers(Office.IRibbonControl control)=>adapter()?.RemoveLegacyMarkers(); public void OpenCompanion(Office.IRibbonControl control)=>adapter()?.OpenCompanion(); diff --git a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj index 1c2679eb..adc4b5eb 100644 --- a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj +++ b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj @@ -23,7 +23,7 @@ PlotDirector.Companion.Protocol PlotDirector.Companion.Client ThisAddIn.cs - + ThisAddIn.cs diff --git a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs index d0864466..a12fd375 100644 --- a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs +++ b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs @@ -3,6 +3,6 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("PlotDirector Word Companion — Native development")] [assembly: AssemblyCompany("Nick Beckley")] [assembly: AssemblyProduct("PlotDirector")] -[assembly: AssemblyVersion("1.0.0.22")] -[assembly: AssemblyFileVersion("1.0.0.22")] +[assembly: AssemblyVersion("1.0.0.23")] +[assembly: AssemblyFileVersion("1.0.0.23")] [assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml index 558076b7..657c0e55 100644 --- a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml +++ b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml @@ -1,6 +1,12 @@ + + +

Save/reconnect mode explicitly permits manuscript updates from this book's associated Word document. Only changed prose is transmitted when the agent has a matching snapshot. It never starts AI analysis.

-
Refresh saved snapshot
+
Refresh saved snapshot
+
Full snapshot fallback

For content which cannot be validated chapter by chapter, the existing bounded full reader is available. Large manuscripts can take substantially longer. It never reimports the book or reruns AI.

A different Word manuscript must be imported into a separate book. This preview never guesses evidence identity across documents.

+
Accepted chapter checkpoints +

These are saved evidence checkpoints, not proof that the current Word session is connected. Live session validation appears in the Word connection dialog. Older imports acquire checkpoints through verified repair; they do not need to be reimported.

+ @if(state.ChapterCheckpoints.Count==0){

No chapter checkpoints have been adopted yet.

}else{
@foreach(var checkpoint in state.ChapterCheckpoints.OrderBy(c=>c.Order)){}
ChapterParagraphsLast acceptedState
@(state.Chapters.FirstOrDefault(c=>c.CanonicalId==checkpoint.ChapterId)?.Title??"Saved chapter")@checkpoint.ParagraphCount@(checkpoint.LastSuccessfulSyncUtc!=DateTime.MinValue?checkpoint.LastSuccessfulSyncUtc.ToString("u"):"Not yet accepted")@checkpoint.Status
@checkpoint.Message
} +

Scenes

Split at a paragraph or move a boundary using the paragraph list. Move prose and reorder scenes in Word, then synchronise.

@foreach(var scene in current){var sceneIndex=Array.IndexOf(current,scene);var adjacent=sceneIndex+1@scene.Title @if(scene.NeedsRefinement){Needs refinement}

@state.Paragraphs.Count(p=>p.SceneId==scene.Id) paragraphs

diff --git a/PlotLine/Views/Shared/_WritingConnectionDetails.cshtml b/PlotLine/Views/Shared/_WritingConnectionDetails.cshtml index a46ffccd..8ce481b3 100644 --- a/PlotLine/Views/Shared/_WritingConnectionDetails.cshtml +++ b/PlotLine/Views/Shared/_WritingConnectionDetails.cshtml @@ -11,6 +11,7 @@ @Html.AntiForgeryToken() +

Select a connected, saved manuscript to refresh its paragraph positions. Word prose is never rewritten and AI analysis is not started.

diff --git a/PlotLine/wwwroot/js/native-companion-status.js b/PlotLine/wwwroot/js/native-companion-status.js index 731e852a..0f5d67d3 100644 --- a/PlotLine/wwwroot/js/native-companion-status.js +++ b/PlotLine/wwwroot/js/native-companion-status.js @@ -9,7 +9,7 @@ const selected=syncCurrent;syncPending={key:selected.instanceId+'/'+selected.sessionId,revision:selected.snapshotRevision||0,started:Date.now()};syncButton.disabled=true; syncFeedback.textContent='Requesting a saved paragraph snapshot from Word…'; const body=new URLSearchParams(new FormData(syncForm));body.set('instanceId',selected.instanceId);body.set('sessionId',selected.sessionId); - try{const response=await fetch(syncForm.action,{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)}); + try{const response=await fetch((event.submitter?.hasAttribute('formaction')?event.submitter.formAction:syncForm.action),{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)}); if(response.redirected||!response.headers.get('content-type')?.includes('application/json'))throw Error('Sign in to PlotDirector again before requesting synchronisation.'); const result=await response.json();if(!response.ok)throw Error(result.message||'Synchronisation could not be requested.');syncFeedback.textContent=result.message;if(syncPending)syncPending.requestId=result.requestId&&result.requestId!=='00000000-0000-0000-0000-000000000000'?result.requestId:null;if(!syncPending?.requestId){syncPending=null;syncButton.disabled=false;}void update(); }catch(error){syncPending=null;syncButton.disabled=false;syncFeedback.textContent=error.message||'Could not contact PlotDirector. Your saved manuscript is unchanged.';} @@ -30,14 +30,16 @@ details.querySelector('[data-word-document-picker]')?.toggleAttribute('hidden',!workspace); const activeInScope=selectable.filter(l=>l.active),selection=documents.value?selectable.find(l=>l.instanceId+'/'+l.sessionId===documents.value):activeInScope.length===1?activeInScope[0]:selectable.length===1?selectable[0]:null; const returnButton=details.querySelector('[data-word-return-to-current]');if(returnButton)returnButton.disabled=!selection?.sceneId||selection.wordSaved===false; + const repairButton=details.querySelector('[data-word-repair-button]');if(repairButton)repairButton.disabled=!!syncPending||!selection?.bookId||selection.wordSaved!==true||selection.canChapterSync!==true; syncCurrent=selection; if(syncForm){syncForm.querySelector('[data-word-sync-book]').value=selection?.bookId||'';syncButton.disabled=!!syncPending||!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true; if(syncPending){const observed=selectable.find(l=>l.instanceId+'/'+l.sessionId===syncPending.key); - if(observed?.mappingCurrent&&Number(observed.snapshotRevision)>syncPending.revision&&observed.paragraphTransfer?.requestId===syncPending.requestId&&observed.paragraphTransfer.state==='accepted'){syncPending=null;syncButton.disabled=!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;syncFeedback.textContent='Word snapshot accepted. This session’s paragraph positions are verified; current scene following can resume.';} + if(observed?.paragraphTransfer?.requestId===syncPending.requestId&&observed.paragraphTransfer.state==='accepted'&&(observed.paragraphTransfer.kind==='chapter'||observed.mappingCurrent&&Number(observed.snapshotRevision)>syncPending.revision)){syncPending=null;syncButton.disabled=!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;syncFeedback.textContent=observed.paragraphTransfer.message||'Word snapshot accepted. This session’s paragraph positions are verified; current scene following can resume.';} + else if(observed?.paragraphTransfer?.requestId===syncPending.requestId&&observed.paragraphTransfer.kind==='chapter'){syncFeedback.textContent=observed.paragraphTransfer.message;if(observed.paragraphTransfer.state==='needs-review'){syncPending=null;syncButton.disabled=false;}} else if(syncPending.requestId&&(!observed||observed.paragraphTransfer?.requestId!==syncPending.requestId||observed.paragraphTransfer.state==='failed')){syncPending=null;syncButton.disabled=!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;syncFeedback.textContent='Word transfer ended without an accepted snapshot. Saved paragraphs are unchanged. Check Companion Troubleshooting, then retry.';} else if(observed?.captureRequestId)syncFeedback.textContent='Reading Word: '+Math.max(0,Math.min(100,Number(observed.captureProgress)||0))+'%. Keep Word open until PlotDirector acknowledges the snapshot.'; else if(Date.now()-syncPending.started>120000){syncPending=null;syncButton.disabled=false;syncFeedback.textContent='No accepted snapshot has been confirmed. Open Manuscript structure and evidence below or Companion Troubleshooting before retrying.';} - }else if(!selection)syncFeedback.textContent='Open the intended manuscript in Word and select its current connection. Saved scene browsing remains available.'; + }else if(selection?.chapterProgress){const progress=selection.chapterProgress;syncFeedback.textContent=progress.state+' · '+progress.matching+'/'+progress.total+' chapter mappings accepted. '+progress.message;}else if(!selection)syncFeedback.textContent='Open the intended manuscript in Word and select its current connection. Saved scene browsing remains available.'; else if(selection.wordSaved!==true)syncFeedback.textContent='Save the manuscript in Word before requesting synchronisation.'; else if(selection.canParagraphSync!==true)syncFeedback.textContent='The connected add-in has not advertised paragraph synchronisation. Check the installed Companion and Word connection.'; }