From 796786414acf05cf545bfa9b85a6d989fd530d86 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Thu, 5 Nov 2026 23:41:46 +0000 Subject: [PATCH] Integrate browser-approved import capture and guarded imported-scene presence --- ...26-11-05-overnight-development-handover.md | 60 +++++++++++++++++++ .../Agent/ChapterAiWork.cs | 2 +- .../Agent/CloudGateway.cs | 2 +- .../Agent/TrayCoordinator.cs | 13 ++-- .../Protocol/AiContracts.cs | 1 - .../Protocol/Messages.cs | 1 - .../Protocol/TrayContracts.cs | 2 +- .../Vsto/WordAdapter.cs | 6 +- .../Browser/writing-embedded-theme.cjs | 3 + PlotLine.Tests/NativeCompanionHttpTests.cs | 6 +- PlotLine.Tests/NativeCompanionTests.cs | 5 +- PlotLine.Tests/Sql/NativeApprovedImport.sql | 10 +++- .../Sql/NativeApprovedImportRollback.sql | 21 +++++++ .../NativeCompanionAuthController.cs | 4 +- .../Controllers/NativeCompanionController.cs | 5 +- .../Controllers/NativePresenceController.cs | 7 ++- PlotLine/Data/NativeImportRepository.cs | 4 +- PlotLine/Data/NativePositionRepository.cs | 9 +++ PlotLine/Data/NativeReviewRepository.cs | 4 +- PlotLine/Program.cs | 1 + .../NativeCompanion/DesktopPairing.cs | 12 ++-- .../NativeCompanion/NativeImportService.cs | 24 ++++---- PlotLine/Sql/233_NativeImportedPositions.sql | 44 ++++++++++++++ .../Views/NativeCompanionAuth/Approve.cshtml | 1 + .../Views/NativeWorkspace/ImportCommit.cshtml | 2 +- .../NativeWorkspace/ImportPreview.cshtml | 2 +- PlotLine/Views/NativeWorkspace/Review.cshtml | 2 +- .../Shared/_WritingCompanionLayout.cshtml | 4 +- PlotLine/wwwroot/js/writing-embedded-theme.js | 2 + 29 files changed, 208 insertions(+), 51 deletions(-) create mode 100644 Docs/Investigations/2026-11-05-overnight-development-handover.md create mode 100644 PlotLine.Tests/Browser/writing-embedded-theme.cjs create mode 100644 PlotLine.Tests/Sql/NativeApprovedImportRollback.sql create mode 100644 PlotLine/Data/NativePositionRepository.cs create mode 100644 PlotLine/Sql/233_NativeImportedPositions.sql create mode 100644 PlotLine/wwwroot/js/writing-embedded-theme.js diff --git a/Docs/Investigations/2026-11-05-overnight-development-handover.md b/Docs/Investigations/2026-11-05-overnight-development-handover.md new file mode 100644 index 00000000..c76aa7a5 --- /dev/null +++ b/Docs/Investigations/2026-11-05-overnight-development-handover.md @@ -0,0 +1,60 @@ +# Overnight Development handover — 5–6 November 2026 + +Shared branch: `codex/word-companion-native-phase1-20261104`. Started by fetching the configured origin and fast-forwarding to Windows handover `97f5d99`. No Production deployment, author-account changes or Windows installation operations. + +## Workstreams + +| Workstream | Delivered | Commits / qualification | Limits | +|---|---|---|---| +| Word AI review → import | Browser-approved optional encrypted source capture; approved scenes only; target-book preview; explicit confirmation; canonical manuscript build and source/summary services; atomic receipt; retries; incremental new-chapter append | `bf515d2` and final integration commit; service and actual authenticated HTTP tests; Development SQL fixtures | Existing chapters are never overwritten. Changed/overlapping imports and title matches conflict rather than reconcile. A real author must qualify the complete workflow in Word. | +| Context / Intent | Independent saved-scene picker; live-follow/manual pause/return; minimal embedded writing layout; existing calendar, Story Maps, floor-plan, relationship and plot-line navigation; saved Intent progress | `15ea2ba` plus theme inheritance integration; browser live/manual/pinned/stale-response tests | No invented AI fulfilment scores. No automatic map centring without a reliable saved mapping. Imported-position follow requires updated tray and exact observed revision; marker-based follow remains available. | +| Plot Lines | Existing Focus/Weave enriched with intersection/health summary, intersection-only filter, combined text filtering and next-intersection navigation | `caeb90b`; actual Razor browser Focus/Weave/association/theme regressions | Existing suggestions and author confirmation retained; no new AI engine or silent membership changes. | +| Continuity | Severity/rule/entity evidence clusters, active/decided filter, search, expand/collapse and clear detection timestamps | `b8bb089`; pure grouping and real browser interaction tests | Related evidence is not asserted to share a root cause. Existing actions retained; no new persisted Deferred/Resolved states. Detection time is not proof prose was rechecked. | +| Onboarding / release | Browser-first first-book guide and honest Companion installation availability; Home/Help links; public theme/account behaviour checked | `b8bb089`; actual Help routing and public-site browser tests | Verified installer exists only on Windows; no fabricated public download. No live payment/subscription mutation performed. | + +## Import operation and consent + +The browser pairing approval offers an **unchecked** encrypted import-capture permission. Legacy grants default to false. This works with tested Windows agent **1.0.0.10**: sign out/reconnect, approve capture in the browser, select the correct book, explicitly submit the selected chapters again. Identical persisted AI results are reused; review decisions survive, and source capture does not incur another AI request. Existing agent caches may require reconnecting/restarting before resubmission. + +Encrypted selected-chapter source is retained with the existing 30-day review lifecycle, protected by server Data Protection. Confirmed import becomes ordinary saved book data. Keep the existing server Data Protection keys backed up. Logs contain neither manuscript prose nor tokens. + +In the browser workspace, edit titles/summaries and save approved/rejected decisions, select reviews, preview the exact proposed chapter/scene structure and destination, then confirm. Pending/rejected scenes are excluded, explicitly disclosed. The transaction rechecks authorisation, subscription, review version, source identity/hash and duplicates. It uses `dbo.Onboarding_ManuscriptBuild_Create`, then existing source and summary procedures. A receipt is returned only after all source writes commit. No Word prose or markers are changed; marker status is `NotRequestedNative`. + +New chapters append in capture order. Existing relationships and metadata remain untouched. Changed existing imports require a subsequent explicit reconciliation feature. Successful AI chapter results persist; failed chapters are retried explicitly. The tray reports processed/failed/import-ready counts separately. + +## Position and multi-screen safety + +Optional tray 1.0.0.11 sends the already available selection start, without additional Word COM operations. The server resolves only saved imported absolute ranges for the same authorised book, persistent document identity and observed revision. Scene/chapter changes invalidate the browser workspace; cursor heartbeats do not continuously rebuild it. After an observed edit, unmatched ranges are refused rather than guessed. This is not durable bookmark installation: revision resets between sessions and same-length dirty edits require Windows qualification; manual scene choice and existing markers remain the safer fallback. Chapter-relative paragraph indices are not saved as whole-document Word positions. + +## Database and deployment + +Development-only forward migrations: `232_NativeApprovedImport.sql`, `233_NativeImportedPositions.sql`. Both applied after verified COPY_ONLY/CHECKSUM backups: + +- `/var/opt/mssql/backups/PlotDirector_Development-overnight-20261105T225822.bak` +- `/var/opt/mssql/backups/PlotDirector_Development-overnight-position-20261105T232027.bak` + +SQL regression fixtures run inside rollback transactions. Tests cover initial import, exact source/summary, duplicate retry, ordered append, stale revision refusal, and failure after canonical build maps were emitted. Failure leaves no chapter, scene, receipt or fixture behind. No real manuscript import was executed by this sprint. + +Final Development deployment evidence and final regression counts are recorded in the companion verification note. Existing environment configuration, uploads, Data Protection and logs are preserved. Production unchanged. + +## Windows handover and installer preservation + +`WindowsValidation/Setup` remains byte-for-byte unchanged from `97f5d99`. Its builder intentionally pins the Windows-qualified **1.0.0.10** payload/source `6cdb49c`; do not edit that guard to make an unqualified package appear approved. The Windows handover records installer SHA256 `9526E3781EB2EF9936132786E1E2242633349933A553E93E7A7D0B038160A7FF`. Atlas does not possess that artifact, so Help does not offer a fake URL or expose a developer path. + +Native sources are version **1.0.0.11**, for richer import-ready reporting and optional imported cursor mapping. Linux builds include the Windows-targeted managed tray; they do not execute Word/VSTO or qualify an installer upgrade. The VSTO Word adapter implementation remains unchanged from the Windows baseline; version metadata alone advances. Windows Codex owns packaging and upgrade qualification through the existing scripts; no second installer/update mechanism was introduced. + +## Ready for user testing + +1. With existing installed Companion10, reconnect with capture consent; submit one chapter, approve some scenes, preview then confirm; repeat confirmation and verify no duplicates. Test a second new chapter and a changed existing chapter conflict. Check saved exact prose, summaries and existing metadata. +2. Open Context and Intent in separate windows; choose scenes independently without Word; pause and resume follow, switch books/documents, disconnect and verify no stale scene takes over. Try tool links and theme changes. +3. Use Plot Lines intersection filter/search/next; use continuity clusters and active/decided filters; ensure saved decisions remain unchanged until an explicit action. + +## Release recommendation and next actions + +Development is suitable for bounded author testing, **not public-release qualification**. Three next actions: + +1. Qualify the real Word → chapter AI → approved import → saved story-data journey with an author-owned test book, including cancellation/retry and existing-content conflict cases. +2. Windows Codex qualifies tray11, three documents, typing/saving under load, reconnect/revision safety, then builds and upgrade-tests through the preserved installer workflow. +3. Obtain a distributable signed installer artifact, complete download/release gates and real-manuscript/access/subscription acceptance. Decide explicit existing-chapter reconciliation and evidence-backed Intent fulfilment as subsequent work. + +No live provider billing, public account creation, Stripe upgrade/downgrade, full existing-manuscript reconciliation, native Word performance or public installer upgrade was proved by Linux fixtures. diff --git a/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs b/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs index 34e34cba..9dd98bb8 100644 --- a/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs +++ b/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs @@ -17,7 +17,7 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable if(request.SnapshotId==Guid.Empty||request.BookId<=0||request.Start<0||request.End<=request.Start||request.End-request.Start>120000){answer.Status="invalid-ai-chapter";return answer;} if(!jobs.ContainsKey(descriptor.SessionId)&&jobs.Count>=32){answer.Status="ai-capacity";return answer;} Clear(descriptor.SessionId); - var chapter=new AiChapterRequest{RetainForImport=request.RetainForImport,RequestId=request.SnapshotId,BookId=request.BookId,SessionId=descriptor.SessionId,ManuscriptId=descriptor.ManuscriptId,Revision=descriptor.Revision,ChapterTitle=request.ChapterTitle.Length<=200?request.ChapterTitle:request.ChapterTitle[..200],ChapterStart=request.Start,ChapterEnd=request.End}; + var chapter=new AiChapterRequest{RequestId=request.SnapshotId,BookId=request.BookId,SessionId=descriptor.SessionId,ManuscriptId=descriptor.ManuscriptId,Revision=descriptor.Revision,ChapterTitle=request.ChapterTitle.Length<=200?request.ChapterTitle:request.ChapterTitle[..200],ChapterStart=request.Start,ChapterEnd=request.End}; jobs[descriptor.SessionId]=new(chapter,request.AuthenticationContext);return answer; } if(!jobs.TryGetValue(descriptor.SessionId,out var job)||job.Chapter.RequestId!=request.SnapshotId){answer.Status="obsolete-ai-request";return answer;} diff --git a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs index 5550510f..0e81752b 100644 --- a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs +++ b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs @@ -92,7 +92,7 @@ public sealed class CloudGateway : IDisposable { var fingerprint=expectedContext+":"+chapter.BookId+":"+chapter.ManuscriptId+":"+Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{chapter.ChapterStart,chapter.ChapterEnd,chapter.Paragraphs}))); Uri site;string access; - lock(gate){Expire();if(successful.TryGetValue(fingerprint,out var prior)&&authenticationContext==expectedContext&&token!=null&&(!chapter.RetainForImport||prior.SourceRetained))return new(){SourceRetained=prior.SourceRetained,RequestId=chapter.RequestId,DocumentRevision=chapter.Revision,ChapterTitle=chapter.ChapterTitle,State="complete",Message="Unchanged chapter: reused saved AI suggestions without uploading prose.",ReviewPath=prior.ReviewPath,Scenes=prior.Scenes};if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");} + lock(gate){Expire();if(successful.TryGetValue(fingerprint,out var prior)&&authenticationContext==expectedContext&&token!=null)return new(){SourceRetained=prior.SourceRetained,RequestId=chapter.RequestId,DocumentRevision=chapter.Revision,ChapterTitle=chapter.ChapterTitle,State="complete",Message="Unchanged chapter: reused saved AI suggestions without uploading prose.",ReviewPath=prior.ReviewPath,Scenes=prior.Scenes};if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");} using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/analyse-chapter")){Content=JsonContent.Create(chapter,options:Json)}; request.Headers.Authorization=new AuthenticationHeaderValue("Bearer",access); HttpResponseMessage responseValue; diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs index 09a59601..4b0fff9d 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs @@ -31,6 +31,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C else{ doc.Observed=DateTime.UtcNow; if(request.Kind=="active"){foreach(var d in documents.Values)d.Active=false;doc.Active=true;} + if(request.Kind=="selection")doc.Cursor=request.Start; if(request.Kind=="selection"||request.Kind=="snapshot-end"){doc.ChapterId=answer.ChapterId;doc.SceneId=answer.SceneId;doc.ChapterTitle=answer.ChapterTitle;doc.SceneTitle=answer.SceneTitle;} if(answer.WordCount.HasValue)doc.Words=answer.WordCount; if(request.Kind.StartsWith("snapshot-",StringComparison.Ordinal)&&answer.Status is not ("ok" or "analysis-complete" or "awaiting-structure")){Cancel(doc);doc.Status="Local reading failed: "+answer.Status+". Detect chapters again.";} @@ -61,18 +62,18 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C lock(gate){if(!documents.TryGetValue(session,out var doc)||!cloud.Allows(doc.Authentication,doc.Book))throw new InvalidOperationException("Connect and select an authorised book first.");if(doc.Job!=Guid.Empty)throw new InvalidOperationException("Cancel the current chapter batch first."); var selection=starts.Distinct().ToHashSet();var chapters=doc.Chapters.Where(c=>selection.Contains(c.Start)&&c.End>c.Start).ToArray();if(chapters.Length==0)throw new InvalidOperationException("Detect and select Heading 1 chapters first."); doc.Pending.Clear();foreach(var chapter in chapters)if(!doc.Completed.Contains((doc.Revision,doc.Book,chapter.Start)))doc.Pending.Enqueue(chapter); - doc.Total=doc.Pending.Count;doc.Done=0;doc.Failed=0;Next(doc); + doc.Total=doc.Pending.Count;doc.Done=0;doc.Failed=0;doc.Retained=0;Next(doc); } } private void Next(TrayDocument doc) { doc.Job=Guid.Empty; if(doc.Pending.Count>0&&documents.Values.Any(other=>other!=doc&&other.Job!=Guid.Empty)){doc.Status="Waiting for the current manuscript chapter batch; no prose has been sent.";return;} - if(doc.Pending.Count==0){doc.Status=$"Batch finished: {doc.Done}/{doc.Total} processed; {doc.Failed} failed. Successful suggestions are in PlotDirector. Retry failed chapters explicitly; completed unchanged chapters are skipped."; + if(doc.Pending.Count==0){doc.Status=$"Batch finished: {doc.Done}/{doc.Total} processed; {doc.Failed} failed. Successful suggestions are in PlotDirector. Retry failed chapters explicitly; completed unchanged chapters are skipped. Import-ready captures: {doc.Retained}/{doc.Done-doc.Failed}. Enable encrypted import capture in browser approval if needed."; if(doc.Done>0&&!string.IsNullOrEmpty(doc.ReviewPath))_ = Task.Run(()=>{try{cloud.OpenCompanionPage($"/native-companion/workspace?bookId={doc.Book}&instanceId={doc.Instance}&sessionId={doc.Session}",doc.Authentication);}catch(Exception e)when(e is InvalidOperationException or IOException or System.ComponentModel.Win32Exception){}}); return;} doc.Current=doc.Pending.Dequeue();doc.Job=Guid.NewGuid();doc.Started=DateTime.UtcNow;doc.Status=$"Chapter {doc.Done+1}/{doc.Total}: {doc.Current.Title}";doc.Progress=0; - if(!Queue(doc,new(){Id=doc.Job,Kind="extract-ai",RetainForImport=true,Chapter=doc.Current,BookId=doc.Book,AuthenticationContext=doc.Authentication})){doc.Job=Guid.Empty;doc.Pending.Clear();} + if(!Queue(doc,new(){Id=doc.Job,Kind="extract-ai",Chapter=doc.Current,BookId=doc.Book,AuthenticationContext=doc.Authentication})){doc.Job=Guid.Empty;doc.Pending.Clear();} } public void Cancel(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Status="Cancelled. Successful server suggestions remain available.";}} private void Cancel(TrayDocument doc){if(doc.Job!=Guid.Empty)ai.Clear(doc.Session);doc.Job=Guid.Empty;doc.Pending.Clear();if(commands.TryGetValue(doc.Instance,out var q))commands[doc.Instance]=new(q.Where(c=>c.SessionId!=doc.Session));Queue(doc,new(){Kind="cancel"});} @@ -85,7 +86,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C if(doc.Book==0&&DocumentBindingRestore(doc,cloudState)) {doc.Book=doc.RememberedBook!.Value;doc.Authentication=cloudState.AuthenticationContext;lastBook=doc.Book;lastAuthentication=doc.Authentication;} if(doc.Job==Guid.Empty){if(doc.Pending.Count>0&&!documents.Values.Any(other=>other.Job!=Guid.Empty))Next(doc);continue;}var result=ai.Result(doc.Session); if(result?.RequestId==doc.Job&&result.State is "complete" or "failed" or "cancelled"){ - if(result.State=="complete"&&!string.IsNullOrEmpty(result.ReviewPath)){if(doc.Completed.Count>=8192)doc.Completed.RemoveWhere(c=>c.Item1!=doc.Revision);doc.Completed.Add((doc.Revision,doc.Book,doc.Current!.Start));doc.ReviewPath=result.ReviewPath;} + if(result.State=="complete"&&!string.IsNullOrEmpty(result.ReviewPath)){if(result.SourceRetained)doc.Retained++;if(doc.Completed.Count>=8192)doc.Completed.RemoveWhere(c=>c.Item1!=doc.Revision);doc.Completed.Add((doc.Revision,doc.Book,doc.Current!.Start));doc.ReviewPath=result.ReviewPath;} else{doc.Failed++;if(doc.Errors.Count>=50)doc.Errors.RemoveAt(0);doc.Errors.Add(doc.Current!.Title+": "+(result.State=="complete"?"Server update required: no saved PWA review handoff was returned.":result.Message));} doc.Done++;ai.Clear(doc.Session);Next(doc); }else if(DateTime.UtcNow-doc.Started>TimeSpan.FromMinutes(7)){doc.Errors.Add("Chapter timed out; retry explicitly.");Cancel(doc);doc.Status="Chapter timed out. Prior suggestions are safe in PlotDirector.";} @@ -96,7 +97,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C public async Task Heartbeat(CancellationToken cancellation) { while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromMilliseconds(500),cancellation);var available=Documents.Where(d=>d.Book>0).ToArray(); - foreach(var doc in available){var key=$"{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc0&&DateTime.UtcNow-lastAgentPresence>=TimeSpan.FromSeconds(15)){lastAgentPresence=DateTime.UtcNow;agentOnlyPublished=true;try{await cloud.Presence(agentInstance,agentSession,new(){BookId=lastBook,Sequence=Interlocked.Increment(ref agentSequence),WordAvailable=false,DocumentTitle="No Word document"},lastAuthentication);}catch(Exception e)when(NetworkFailure(e)) {}} else if(available.Length>0&&agentOnlyPublished){agentOnlyPublished=false;await cloud.RemovePresence(agentInstance,agentSession);} } @@ -106,7 +107,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C public sealed class TrayDocument { public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Detect chapters to begin.",ReviewPath=""; - public string WordDiagnostics="";public int Failed;public int Book,Progress,Total,Done;public int? RememberedBook,Words,ChapterId,SceneId;public bool Active;public DateTime Observed,Started; + public string WordDiagnostics="";public int Cursor;public int Retained;public int Failed;public int Book,Progress,Total,Done;public int? RememberedBook,Words,ChapterId,SceneId;public bool Active;public DateTime Observed,Started; public StructureSuggestion[] Chapters=[];public StructureSuggestion? Current;public Queue Pending=[];public HashSet<(long,int,int)> Completed=[];public List Errors=[]; public override string ToString()=>Title+(Active?" (active in Word)":""); } diff --git a/PlotDirector.NativeCompanion/Protocol/AiContracts.cs b/PlotDirector.NativeCompanion/Protocol/AiContracts.cs index f777edd7..88ac57f3 100644 --- a/PlotDirector.NativeCompanion/Protocol/AiContracts.cs +++ b/PlotDirector.NativeCompanion/Protocol/AiContracts.cs @@ -4,7 +4,6 @@ namespace PlotDirector.Companion.Protocol; [DataContract] public sealed class AiChapterRequest { - [DataMember] public bool RetainForImport {get;set;} [DataMember] public string ChapterTitle {get;set;}=""; [DataMember] public Guid RequestId { get; set; } [DataMember] public int BookId { get; set; } diff --git a/PlotDirector.NativeCompanion/Protocol/Messages.cs b/PlotDirector.NativeCompanion/Protocol/Messages.cs index ee5816f4..aa173b22 100644 --- a/PlotDirector.NativeCompanion/Protocol/Messages.cs +++ b/PlotDirector.NativeCompanion/Protocol/Messages.cs @@ -25,7 +25,6 @@ public static class ProtocolVersion [DataContract] public sealed class Message { - [DataMember] public bool RetainForImport {get;set;} [DataMember] public AdapterCommand? Command {get;set;} [DataMember] public string OperationMessage {get;set;}=""; [DataMember] public int Version { get; set; } = ProtocolVersion.Current; diff --git a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs index 7b078669..203c98a0 100644 --- a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs +++ b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs @@ -3,7 +3,6 @@ namespace PlotDirector.Companion.Protocol; [DataContract] public sealed class AdapterCommand { - [DataMember] public bool RetainForImport {get;set;} [DataMember] public Guid Id {get;set;}=Guid.NewGuid(); [DataMember] public string Kind {get;set;}=""; [DataMember] public Guid SessionId {get;set;} @@ -17,6 +16,7 @@ public sealed class AdapterCommand [DataContract] public sealed class NativePresence { + [DataMember] public int? CursorStart {get;set;} [DataMember] public AdapterCommand? Navigation {get;set;} [DataMember] public Guid ManuscriptId {get;set;} [DataMember] public int BookId {get;set;} diff --git a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs index dee38c70..e1e46da1 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs @@ -233,7 +233,7 @@ namespace PlotDirector.WordAddIn var chapter=command.Chapter; if(chapter.Start<0||chapter.End<=chapter.Start||chapter.End>doc.End||DocumentEnd(doc.Document)!=doc.End)throw new InvalidOperationException("Chapter changed. Detect chapters again."); CancelExtraction(doc);doc.AiChapter=command.Chapter;doc.AiBook=command.BookId;doc.AiAuthenticationContext=command.AuthenticationContext;doc.AiJob=command.Id; - doc.Extraction=new Extraction{Snapshot=command.Id,Revision=doc.Revision,Position=chapter.Start,Limit=chapter.End,IsAi=true,RetainForImport=command.RetainForImport}; + doc.Extraction=new Extraction{Snapshot=command.Id,Revision=doc.Revision,Position=chapter.Start,Limit=chapter.End,IsAi=true}; if(!scheduler.Post("extract:"+doc.Session,()=>ExtractBatch(doc))){CancelExtraction(doc);throw new InvalidOperationException("Word queue is busy.");} } else if(command.Kind=="cancel"){CancelExtraction(doc);doc.AiJob=Guid.Empty;} @@ -272,7 +272,7 @@ namespace PlotDirector.WordAddIn { if(!extraction.Begun) { - if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-begin":"snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,Start=extraction.Position,End=extraction.Limit,BookId=doc.AiBook,AuthenticationContext=doc.AiAuthenticationContext,RetainForImport=extraction.RetainForImport,RequestAnalysis=extraction.Analyse,ChapterTitle=doc.AiChapter?.Title??""}))return; + if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-begin":"snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,Start=extraction.Position,End=extraction.Limit,BookId=doc.AiBook,AuthenticationContext=doc.AiAuthenticationContext,RequestAnalysis=extraction.Analyse,ChapterTitle=doc.AiChapter?.Title??""}))return; extraction.Begun=true; } // At most four <=2048-character fragments and a cooperative ~20ms budget. @@ -541,6 +541,6 @@ namespace PlotDirector.WordAddIn public LocalDocument(Word.Document document){Document=document;} } private sealed class Extraction - {public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex,Limit;public int OutlineLevel;public bool Begun,Analyse,IsAi,RetainForImport;public Message Pending;} + {public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex,Limit;public int OutlineLevel;public bool Begun,Analyse,IsAi;public Message Pending;} } } diff --git a/PlotLine.Tests/Browser/writing-embedded-theme.cjs b/PlotLine.Tests/Browser/writing-embedded-theme.cjs new file mode 100644 index 00000000..7f894314 --- /dev/null +++ b/PlotLine.Tests/Browser/writing-embedded-theme.cjs @@ -0,0 +1,3 @@ +const {chromium}=require('playwright'); +const path=require('path'); +(async()=>{const browser=await chromium.launch({headless:true});try{const page=await browser.newPage();await page.setContent('');const frame=page.frames()[1];await frame.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/writing-embedded-theme.js')});await frame.waitForFunction(()=>document.documentElement.getAttribute('data-app-theme')==='plum'&&document.documentElement.getAttribute('data-bs-theme')==='dark');await page.evaluate(()=>{document.documentElement.setAttribute('data-app-theme','sage');document.documentElement.removeAttribute('data-bs-theme');});await frame.waitForFunction(()=>document.documentElement.getAttribute('data-app-theme')==='sage'&&!document.documentElement.hasAttribute('data-bs-theme'));console.log('PASS embedded writing screens inherit and track existing PWA theme without separate persistence');}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/NativeCompanionHttpTests.cs b/PlotLine.Tests/NativeCompanionHttpTests.cs index ee87b883..0ef871fa 100644 --- a/PlotLine.Tests/NativeCompanionHttpTests.cs +++ b/PlotLine.Tests/NativeCompanionHttpTests.cs @@ -48,7 +48,7 @@ internal static class NativeCompanionHttpTests builder.Services.AddSingleton(NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(null))); builder.Services.AddSingleton(NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(null))); builder.Services.AddSingleton(users);builder.Services.AddSingleton(repo);builder.Services.AddSingleton(subscriptions); - builder.Services.AddSingleton(new EphemeralDataProtectionProvider());builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddSingleton();builder.Services.AddSingleton();builder.Services.AddSingleton();builder.Services.AddSingleton(new MemoryNativeReviews()); + builder.Services.AddSingleton(new EphemeralDataProtectionProvider());builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddSingleton();builder.Services.AddSingleton();builder.Services.AddSingleton(NativeWorkflowTests.Proxy((n,a)=>n=="List"?Task.FromResult>([]):throw new Exception("Unexpected import write "+n)));builder.Services.AddScoped();builder.Services.AddSingleton();builder.Services.AddSingleton(new MemoryNativeReviews()); builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options=>{options.LoginPath="/fixture-login";options.Cookie.SecurePolicy=Microsoft.AspNetCore.Http.CookieSecurePolicy.None;}) .AddScheme(DesktopPairing.Scheme,_=>{}); builder.Services.AddRateLimiter(o=>o.AddPolicy("native-pair",_=>System.Threading.RateLimiting.RateLimitPartition.GetNoLimiter("fixture"))); @@ -82,7 +82,7 @@ internal static class NativeCompanionHttpTests var approval=await browser.GetAsync("/native-companion/authorize?code="+code);Check(approval.IsSuccessStatusCode&&(await approval.Content.ReadAsStringAsync()).Contains("Approve this Word Companion connection"),"Actual approval view renders before any upload"); Check((await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary{{"code",code}}))).StatusCode==HttpStatusCode.BadRequest,"Approval enforces antiforgery"); var antiforgery=await browser.GetStringAsync("/fixture-antiforgery"); - Check((await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary{{"code",code},{"__RequestVerificationToken",antiforgery}}))).IsSuccessStatusCode,"Authenticated antiforgery approval succeeds"); + Check((await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary{{"code",code},{"retainImport","true"},{"__RequestVerificationToken",antiforgery}}))).IsSuccessStatusCode,"Authenticated antiforgery approval succeeds"); var redeemed=await agent.PostAsJsonAsync("/api/native-companion/token",new{code,verifier});Check(redeemed.IsSuccessStatusCode,"Agent redeems approved pairing"); var token=(await redeemed.Content.ReadFromJsonAsync()).GetProperty("accessToken").GetString();agent.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Bearer",token); Check((await agent.GetFromJsonAsync("/api/native-companion/books"))!.Single().BookId==3,"Grant loads authorized books through actual routing"); @@ -99,6 +99,8 @@ internal static class NativeCompanionHttpTests Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(decisionFields))).StatusCode==HttpStatusCode.Redirect,"Actual antiforgery-protected form binds and saves review decisions"); Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(decisionFields))).StatusCode==HttpStatusCode.Conflict,"Actual stale review form receives conflict without overwriting");reviewHtml=await browser.GetStringAsync("/fixture-render-review/"+reviewId);Check(!reviewHtml.Contains("")&&reviewHtml.Contains("Edited summary"),"Saved title is encoded while edited summary remains reviewable"); request.RequestId=Guid.NewGuid();var reused=await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request);Check(reused.IsSuccessStatusCode&&provider.Prompts.Count==1,"Unchanged chapter content reuses durable suggestion across new request identifiers"); + Check((await reused.Content.ReadFromJsonAsync())?.SourceRetained==true,"Retaining source requires explicit opt-in and reuses analysis without another provider call"); + using(var previewScope=app.Services.CreateScope()){var plan=await previewScope.ServiceProvider.GetRequiredService().Preview(7,3,[reviewId]);Check(plan.Conflicts.Length==0&&plan.Items.Single().Scenes.Single().Text==request.Paragraphs.Single().Text,"Actual HTTP retained source and approved decisions produce an exact-prose import preview");} var negotiation=await browser.PostAsync("/hubs/native-companion/negotiate?negotiateVersion=1",null);Check(negotiation.IsSuccessStatusCode,"Native presence hub requires normal browser authentication and negotiates after sign-in"); var connectionToken=(await negotiation.Content.ReadFromJsonAsync()).GetProperty("connectionToken").GetString(); using var socket=new System.Net.WebSockets.ClientWebSocket();socket.Options.Cookies=browserHandler.CookieContainer;using var socketTimeout=new CancellationTokenSource(TimeSpan.FromSeconds(10)); diff --git a/PlotLine.Tests/NativeCompanionTests.cs b/PlotLine.Tests/NativeCompanionTests.cs index b77148b4..c21868c2 100644 --- a/PlotLine.Tests/NativeCompanionTests.cs +++ b/PlotLine.Tests/NativeCompanionTests.cs @@ -21,14 +21,15 @@ internal static class NativeCompanionTests public static async Task Run() { void Check(bool value,string name){if(!value)throw new Exception(name);} - var clock=new Clock();var pairing=new DesktopPairing(new EphemeralDataProtectionProvider(),clock); + var clock=new Clock();var protection=new EphemeralDataProtectionProvider();var pairing=new DesktopPairing(protection,clock); var verifier=new string('a',64);var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier))); var code=pairing.Start(challenge); Check(pairing.Redeem(code,verifier)==null,"Pairing needs browser approval"); var stamp=Guid.NewGuid();Check(pairing.Approve(code,7,stamp),"First browser approval");Check(!pairing.Approve(code,9,Guid.NewGuid()),"Cannot change approved owner"); Check(pairing.Redeem(code,new string('b',64))==null,"Wrong verifier refused"); var token=pairing.Redeem(code,verifier)!;var grant=pairing.Read(token)!; - Check(grant.UserId==7&&grant.Stamp==stamp&&pairing.Redeem(code,verifier)==null,"One-use code yields correct protected subject"); + Check(grant.UserId==7&&grant.Stamp==stamp&&!grant.RetainImport&&pairing.Redeem(code,verifier)==null,"One-use code yields correct protected subject"); + var legacy=protection.CreateProtector("PlotDirector.NativeCompanion.Access.v1").Protect(System.Text.Json.JsonSerializer.Serialize(new{UserId=7,Stamp=stamp,Expires=clock.GetUtcNow().AddHours(4)}));Check(pairing.Read(legacy) is {RetainImport:false},"Existing grants remain valid without implicitly enabling source retention"); Check(pairing.Read("tampered"+token)==null,"Tampered grant refused");clock.Now=clock.Now.AddHours(5);Check(pairing.Read(token)==null,"Expired grant refused"); var expires=pairing.Start(challenge);clock.Now=clock.Now.AddMinutes(6);Check(!pairing.Approve(expires,7,stamp),"Expired browser request refused"); var request=new AiChapterRequest{RequestId=Guid.NewGuid(),BookId=3,ManuscriptId=Guid.NewGuid(),SessionId=Guid.NewGuid(),ChapterStart=100,ChapterEnd=135,Paragraphs=[new(){Index=1,Start=100,End=110,Text="First scene."},new(){Index=2,Start=110,End=111,Text="\r"},new(){Index=3,Start=111,End=135,Text="Second scene begins."}]}; diff --git a/PlotLine.Tests/Sql/NativeApprovedImport.sql b/PlotLine.Tests/Sql/NativeApprovedImport.sql index 726c0ea1..946f210e 100644 --- a/PlotLine.Tests/Sql/NativeApprovedImport.sql +++ b/PlotLine.Tests/Sql/NativeApprovedImport.sql @@ -8,7 +8,7 @@ INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@Project,N'Nat DECLARE @Review uniqueidentifier=NEWID(),@Doc uniqueidentifier=NEWID(),@Operation uniqueidentifier=NEWID(); DECLARE @Key nvarchar(80)=CONCAT('native:',REPLACE(CONVERT(nvarchar(36),@Doc),'-',''),':10'); INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,EncryptedSource) -VALUES(@Review,@User,@Book,@Doc,10,30,'fixture-hash',N'{"Scenes":[]}',N'[]',N'fixture-encrypted-source'); +VALUES(@Review,@User,@Book,@Doc,10,30,'fixture-hash',N'{"DocumentRevision":2,"Scenes":[{"Start":10,"End":30}]}',N'[]',N'fixture-encrypted-source'); DECLARE @Items nvarchar(max)=(SELECT @Review ReviewID,1 Version,@Key [Key],'fixture-hash' Hash,N'Approved opening' Title,10 Start,30 [End],JSON_QUERY((SELECT CONCAT(@Key,':10') [Key],N'Approved scene' Title,N'An author-approved summary.' Summary,N'Preserved source prose.' [Text],1 StartParagraph,1 EndParagraph,3 Words FOR JSON PATH)) Scenes FOR JSON PATH); EXEC dbo.NativeReviewImport @Action='Commit',@UserID=@User,@BookID=@Book,@OperationID=@Operation,@DocumentGuid=@Doc,@ItemsJson=@Items; IF (SELECT COUNT(*) FROM dbo.Chapters WHERE BookID=@Book AND IsArchived=0)<>1 THROW 51000,'Wrong chapter creation count',1; @@ -18,9 +18,15 @@ EXEC dbo.NativeReviewImport @Action='Commit',@UserID=@User,@BookID=@Book,@Operat IF (SELECT COUNT(*) FROM dbo.Chapters WHERE BookID=@Book AND IsArchived=0)<>1 THROW 51000,'Retry duplicated chapter',1; -- Incremental new chapter appends; existing author relationships/scene are untouched. DECLARE @Review2 uniqueidentifier=NEWID(),@Operation2 uniqueidentifier=NEWID(),@Key2 nvarchar(80)=CONCAT('native:',REPLACE(CONVERT(nvarchar(36),@Doc),'-',''),':30'); -INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,EncryptedSource) VALUES(@Review2,@User,@Book,@Doc,30,50,'next-hash',N'{}',N'[]',N'fixture'); +INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,EncryptedSource) VALUES(@Review2,@User,@Book,@Doc,30,50,'next-hash',N'{"DocumentRevision":2,"Scenes":[{"Start":30,"End":50}]}',N'[]',N'fixture'); SET @Items=(SELECT @Review2 ReviewID,1 Version,@Key2 [Key],'next-hash' Hash,N'Approved continuation' Title,30 Start,50 [End],JSON_QUERY((SELECT CONCAT(@Key2,':30') [Key],N'Next approved scene' Title,N'Next summary.' Summary,N'Next preserved source.' [Text],2 StartParagraph,2 EndParagraph,3 Words FOR JSON PATH)) Scenes FOR JSON PATH); EXEC dbo.NativeReviewImport @Action='Commit',@UserID=@User,@BookID=@Book,@OperationID=@Operation2,@DocumentGuid=@Doc,@ItemsJson=@Items; IF NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE BookID=@Book AND ChapterNumber=2 AND ChapterTitle=N'Approved continuation') THROW 51000,'Incremental chapter ordering failed',1; IF (SELECT COUNT(*) FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@Book AND s.IsArchived=0)<>2 THROW 51000,'Incremental scene count failed',1; +CREATE TABLE #NativePosition(ChapterID int,SceneID int NULL); +INSERT #NativePosition EXEC dbo.NativeImportedPosition @UserID=@User,@BookID=@Book,@DocumentGuid=@Doc,@Revision=2,@Position=12; +IF (SELECT COUNT(*) FROM #NativePosition)<>1 OR NOT EXISTS(SELECT 1 FROM #NativePosition WHERE SceneID IS NOT NULL) THROW 51000,'Imported scene cursor mapping failed',1; +TRUNCATE TABLE #NativePosition; +INSERT #NativePosition EXEC dbo.NativeImportedPosition @UserID=@User,@BookID=@Book,@DocumentGuid=@Doc,@Revision=3,@Position=12; +IF EXISTS(SELECT 1 FROM #NativePosition) THROW 51000,'Stale imported positions accepted',1; SELECT 'PASS canonical native initial import, source/summary preservation, retry and incremental append'; diff --git a/PlotLine.Tests/Sql/NativeApprovedImportRollback.sql b/PlotLine.Tests/Sql/NativeApprovedImportRollback.sql new file mode 100644 index 00000000..ec7e746e --- /dev/null +++ b/PlotLine.Tests/Sql/NativeApprovedImportRollback.sql @@ -0,0 +1,21 @@ +IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Development only',1; +DECLARE @Project int,@Book int,@Operation uniqueidentifier=NEWID(); +BEGIN TRY + BEGIN TRANSACTION; + DECLARE @User int=(SELECT TOP(1) UserID FROM dbo.AppUser ORDER BY UserID),@Review uniqueidentifier=NEWID(),@Doc uniqueidentifier=NEWID(); + INSERT dbo.Projects(ProjectName) VALUES(N'Native rollback isolated fixture');SET @Project=SCOPE_IDENTITY(); + INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole) VALUES(@Project,@User,N'Owner'); + INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@Project,N'Rollback isolated fixture',1,1);SET @Book=SCOPE_IDENTITY(); + INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,EncryptedSource) VALUES(@Review,@User,@Book,@Doc,0,20,'rollback-hash',N'{"DocumentRevision":1,"Scenes":[{"Start":0,"End":20}]}',N'fixture'); + DECLARE @Items nvarchar(max)=(SELECT @Review ReviewID,1 Version,'rollback-chapter' [Key],'rollback-hash' Hash,'Rollback chapter' Title,0 Start,20 [End],JSON_QUERY(N'[{"Key":"rollback-chapter:0","Title":"Rollback scene","Text":null,"StartParagraph":1,"EndParagraph":1,"Words":0}]') Scenes FOR JSON PATH); + -- Deliberately force a canonical source-save constraint failure AFTER the core build emitted its maps. + EXEC dbo.NativeReviewImport @Action='Commit',@UserID=@User,@BookID=@Book,@OperationID=@Operation,@DocumentGuid=@Doc,@ItemsJson=@Items; + THROW 51000,'Expected source-save failure did not occur',1; +END TRY +BEGIN CATCH + DECLARE @Error int=ERROR_NUMBER(); + IF @@TRANCOUNT>0 ROLLBACK; + IF @Error<>515 THROW; + IF EXISTS(SELECT 1 FROM dbo.Projects WHERE ProjectID=@Project) OR EXISTS(SELECT 1 FROM dbo.NativeImportOperations WHERE OperationID=@Operation) OR EXISTS(SELECT 1 FROM dbo.Chapters WHERE BookID=@Book) THROW 51000,'Partial import survived source failure',1; + SELECT 'PASS source-stage failure rolled back core chapters, scenes, receipt and fixture; review/canonical author data untouched'; +END CATCH; diff --git a/PlotLine/Controllers/NativeCompanionAuthController.cs b/PlotLine/Controllers/NativeCompanionAuthController.cs index e23ca0d6..5dcd6455 100644 --- a/PlotLine/Controllers/NativeCompanionAuthController.cs +++ b/PlotLine/Controllers/NativeCompanionAuthController.cs @@ -21,12 +21,12 @@ public sealed class NativeCompanionAuthController(DesktopPairing pairing):Contro public IActionResult Approve(string code) {Response.Headers.CacheControl="no-store";Response.Headers["Referrer-Policy"]="no-referrer";return !string.IsNullOrEmpty(code)&&pairing.Exists(code)?View("Approve",code):BadRequest("This request expired. Start Connect again in Word.");} [Authorize,HttpPost("native-companion/authorize"),ValidateAntiForgeryToken] - public IActionResult ApproveGrant(string code) + public IActionResult ApproveGrant(string code,bool retainImport=false) { if(string.IsNullOrEmpty(code))return BadRequest(); if(!int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var user)||!Guid.TryParse(User.FindFirstValue("PlotLine.SecurityStamp"),out var stamp))return Forbid(); Response.Headers.CacheControl="no-store"; - return pairing.Approve(code,user,stamp)?Content("Word Companion connected. You may close this tab. The grant expires in four hours; signing out in Word discards it."):BadRequest("This request expired or was already approved."); + return pairing.Approve(code,user,stamp,retainImport)?Content("Word Companion connected. You may close this tab. The grant expires in four hours; signing out in Word discards it."):BadRequest("This request expired or was already approved."); } [AllowAnonymous,HttpPost("api/native-companion/token")] public IActionResult Token([FromBody] PairRedeem request) diff --git a/PlotLine/Controllers/NativeCompanionController.cs b/PlotLine/Controllers/NativeCompanionController.cs index 451124fb..977da71f 100644 --- a/PlotLine/Controllers/NativeCompanionController.cs +++ b/PlotLine/Controllers/NativeCompanionController.cs @@ -30,15 +30,16 @@ public sealed class NativeCompanionController(IWordCompanionRepository repositor if(await repository.GetBookStructureAsync(request.BookId,UserId)==null)return Forbid(); try { + var retain=User.HasClaim("NativeCompanion.RetainImport","true"); var mapped=NativeChapterMapping.Build(request,Math.Clamp(configuration.GetValue("NativeCompanion:MaxChapterCharacters",120000),10000,500000)); var contentHash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{request.ChapterStart,request.ChapterEnd,request.Paragraphs}))); - if(reviews!=null){var prior=await reviews.Find(UserId,request.BookId,request.ManuscriptId,contentHash);if(prior!=null){if(request.RetainForImport&&prior.EncryptedSource==null&&importService!=null){prior.EncryptedSource=importService.Protect(request);await reviews.Save(prior);}var saved=JsonSerializer.Deserialize(prior.ResultJson)!;saved.SourceRetained=prior.EncryptedSource!=null;saved.RequestId=request.RequestId;saved.DocumentRevision=request.Revision;saved.ReviewPath=$"/native-companion/reviews/{prior.ReviewID}";return Ok(saved);}} + if(reviews!=null){var prior=await reviews.Find(UserId,request.BookId,request.ManuscriptId,contentHash);if(prior!=null){if(retain&&prior.EncryptedSource==null&&importService!=null){prior.EncryptedSource=importService.Protect(request);prior.SourceRevision=request.Revision;await reviews.Save(prior);}var saved=JsonSerializer.Deserialize(prior.ResultJson)!;saved.SourceRetained=prior.EncryptedSource!=null;saved.RequestId=request.RequestId;saved.DocumentRevision=request.Revision;saved.ReviewPath=$"/native-companion/reviews/{prior.ReviewID}";return Ok(saved);}} var hash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(request))); var author=UserId;var task=cache.Run(author,request.RequestId,hash,async cancellation=>{ await using var scope=scopes.CreateAsyncScope(); var result=await scope.ServiceProvider.GetRequiredService().AnalyseChapterAsync(mapped,cancellation); var mappedResult=NativeChapterMapping.Map(request,result); - if(mappedResult.State=="complete"&&reviews!=null){var row=await scope.ServiceProvider.GetRequiredService().Save(new(){ReviewID=request.RequestId,UserID=author,BookID=request.BookId,ManuscriptID=request.ManuscriptId,ChapterStart=request.ChapterStart,ChapterEnd=request.ChapterEnd,ContentHash=contentHash,ResultJson=JsonSerializer.Serialize(mappedResult),EncryptedSource=request.RetainForImport?importService?.Protect(request):null});mappedResult.SourceRetained=row.EncryptedSource!=null;mappedResult.ReviewPath=$"/native-companion/reviews/{row.ReviewID}";} + if(mappedResult.State=="complete"&&reviews!=null){var row=await scope.ServiceProvider.GetRequiredService().Save(new(){ReviewID=request.RequestId,UserID=author,BookID=request.BookId,ManuscriptID=request.ManuscriptId,ChapterStart=request.ChapterStart,ChapterEnd=request.ChapterEnd,ContentHash=contentHash,ResultJson=JsonSerializer.Serialize(mappedResult),SourceRevision=request.Revision,EncryptedSource=retain?importService?.Protect(request):null});mappedResult.SourceRetained=row.EncryptedSource!=null;mappedResult.ReviewPath=$"/native-companion/reviews/{row.ReviewID}";} return mappedResult; },request.BookId); Response.Headers.CacheControl="no-store"; diff --git a/PlotLine/Controllers/NativePresenceController.cs b/PlotLine/Controllers/NativePresenceController.cs index 89798079..2c5af7cd 100644 --- a/PlotLine/Controllers/NativePresenceController.cs +++ b/PlotLine/Controllers/NativePresenceController.cs @@ -8,7 +8,7 @@ using PlotLine.Data; using PlotLine.Services.NativeCompanion; namespace PlotLine.Controllers; [ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")] -public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext? live=null):ControllerBase +public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext? live=null,INativePositionRepository? positions=null):ControllerBase { private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); private string Grant=>User.FindFirstValue("NativeCompanion.Grant")??throw new InvalidOperationException(); @@ -17,11 +17,14 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC public async Task Update(Guid instance,Guid session,NativePresence input) { input.Navigation=null;var book=await access.GetBookStructureAsync(input.BookId,Author);if(book==null)return Forbid(); + if(input.CursorStart is <0)return BadRequest("Invalid cursor position."); + if(input.WordAvailable&&input.SceneId==null&&input.CursorStart.HasValue&&positions!=null){var mapped=await positions.Resolve(Author,input.BookId,input.ManuscriptId,input.Revision,input.CursorStart.Value);if(mapped!=null&&(!input.ChapterId.HasValue||input.ChapterId==mapped.ChapterID)){input.ChapterId=mapped.ChapterID;input.SceneId=mapped.SceneID;}} var chapter=input.ChapterId.HasValue?book.Chapters.FirstOrDefault(c=>c.ChapterId==input.ChapterId):null; if(input.SceneId.HasValue){var parent=book.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==input.SceneId));if(parent==null||(chapter!=null&&chapter!=parent))return NotFound();chapter=parent;input.ChapterId=parent.ChapterId;} if(input.ChapterId.HasValue&&chapter==null)return NotFound(); + var before=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session); if(!presence.Put(Author,Grant,Expires,instance,session,input))return Conflict(new{message="Stale, revoked or invalid native session."}); - if(live!=null)await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted); + if(live!=null&&(before==null||before.Position.BookId!=input.BookId||before.Position.ManuscriptId!=input.ManuscriptId||before.Position.Revision!=input.Revision||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.Active!=input.Active||before.Position.WordAvailable!=input.WordAvailable))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted); input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);return Ok(input); } [HttpDelete("instances/{instance:guid}/documents/{session:guid}/presence")] diff --git a/PlotLine/Data/NativeImportRepository.cs b/PlotLine/Data/NativeImportRepository.cs index 31f22cb3..0f4f31cd 100644 --- a/PlotLine/Data/NativeImportRepository.cs +++ b/PlotLine/Data/NativeImportRepository.cs @@ -3,7 +3,7 @@ using System.Text.Json; using Dapper; using PlotLine.Services.NativeCompanion; namespace PlotLine.Data; -public sealed class NativeImportedChapter {public string ChapterKey{get;set;}="";public string ContentHash{get;set;}="";public int ReviewVersion{get;set;}} +public sealed class NativeImportedChapter {public Guid? DocumentGuid{get;set;}public int? ChapterStart{get;set;}public int? ChapterEnd{get;set;}public string ChapterKey{get;set;}="";public string ContentHash{get;set;}="";public int ReviewVersion{get;set;}} public interface INativeImportRepository { Task> List(int user,int book); @@ -12,7 +12,7 @@ public interface INativeImportRepository } public sealed class NativeImportRepository(ISqlConnectionFactory factory):INativeImportRepository { - public async Task> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync("dbo.NativeReviewImport",new{Action="List",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();} + public async Task> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync("dbo.NativeImportedCatalog",new{UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();} public async Task Result(int user,Guid operation){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync("dbo.NativeReviewImport",new{Action="Result",UserID=user,OperationID=operation},commandType:CommandType.StoredProcedure);} public async Task Commit(int user,Guid operation,NativeImportPlan plan) { diff --git a/PlotLine/Data/NativePositionRepository.cs b/PlotLine/Data/NativePositionRepository.cs new file mode 100644 index 00000000..807ab0b9 --- /dev/null +++ b/PlotLine/Data/NativePositionRepository.cs @@ -0,0 +1,9 @@ +using System.Data; +using Dapper; +namespace PlotLine.Data; +public sealed class NativeSavedPosition{public int ChapterID{get;set;}public int? SceneID{get;set;}} +public interface INativePositionRepository{Task Resolve(int user,int book,Guid document,long revision,int position);} +public sealed class NativePositionRepository(ISqlConnectionFactory factory):INativePositionRepository +{ + public async Task Resolve(int user,int book,Guid document,long revision,int position){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync("dbo.NativeImportedPosition",new{UserID=user,BookID=book,DocumentGuid=document,Revision=revision,Position=position},commandType:CommandType.StoredProcedure);} +} diff --git a/PlotLine/Data/NativeReviewRepository.cs b/PlotLine/Data/NativeReviewRepository.cs index 3f6a76c8..3b6d9c0a 100644 --- a/PlotLine/Data/NativeReviewRepository.cs +++ b/PlotLine/Data/NativeReviewRepository.cs @@ -3,7 +3,7 @@ using Dapper; namespace PlotLine.Data; public sealed class NativeReview { - public string? EncryptedSource{get;set;}public Guid ReviewID {get;set;}public int UserID {get;set;}public int BookID {get;set;}public Guid ManuscriptID {get;set;}public int ChapterStart {get;set;}public int ChapterEnd {get;set;}public string ContentHash {get;set;}="";public string ResultJson {get;set;}="";public string? DecisionsJson {get;set;}public int Version {get;set;}public DateTime CreatedUtc {get;set;} + public long? SourceRevision{get;set;}public string? EncryptedSource{get;set;}public Guid ReviewID {get;set;}public int UserID {get;set;}public int BookID {get;set;}public Guid ManuscriptID {get;set;}public int ChapterStart {get;set;}public int ChapterEnd {get;set;}public string ContentHash {get;set;}="";public string ResultJson {get;set;}="";public string? DecisionsJson {get;set;}public int Version {get;set;}public DateTime CreatedUtc {get;set;} } public interface INativeReviewRepository { @@ -19,6 +19,6 @@ public sealed class NativeReviewRepository(ISqlConnectionFactory factory):INativ public Task Find(int user,int book,Guid manuscript,string hash)=>Read(new{Action="Find",UserID=user,BookID=book,ManuscriptID=manuscript,ContentHash=hash}); public Task Get(int user,Guid id)=>Read(new{Action="Get",UserID=user,ReviewID=id}); public async Task> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync("dbo.NativeChapterReview_Access",new{Action="List",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();} - public async Task Save(NativeReview r){var saved=await Read(new{Action="Save",r.UserID,r.BookID,r.ReviewID,r.ManuscriptID,r.ChapterStart,r.ChapterEnd,r.ContentHash,r.ResultJson})??throw new InvalidOperationException("Review was not saved.");if(!string.IsNullOrEmpty(r.EncryptedSource)){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.NativeReviewSource_Save",new{r.UserID,ReviewID=saved.ReviewID,r.EncryptedSource},commandType:CommandType.StoredProcedure);saved.EncryptedSource??=r.EncryptedSource;}return saved;} + public async Task Save(NativeReview r){var saved=await Read(new{Action="Save",r.UserID,r.BookID,r.ReviewID,r.ManuscriptID,r.ChapterStart,r.ChapterEnd,r.ContentHash,r.ResultJson})??throw new InvalidOperationException("Review was not saved.");if(!string.IsNullOrEmpty(r.EncryptedSource)){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.NativeReviewSource_Save",new{r.UserID,ReviewID=saved.ReviewID,r.EncryptedSource,ObservedRevision=r.SourceRevision},commandType:CommandType.StoredProcedure);saved.EncryptedSource??=r.EncryptedSource;}return saved;} public async Task Decide(int user,Guid id,int version,string json){using var db=factory.CreateConnection();return await db.ExecuteScalarAsync("dbo.NativeChapterReview_Access",new{Action="Decide",UserID=user,ReviewID=id,Version=version,DecisionsJson=json},commandType:CommandType.StoredProcedure)==1;} } diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 6a91e50f..de91f233 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -97,6 +97,7 @@ public class Program builder.Services.AddSingleton(); builder.Services.AddAuthentication().AddScheme(PlotLine.Services.NativeCompanion.DesktopPairing.Scheme, _ => { }); builder.Services.AddSingleton(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/PlotLine/Services/NativeCompanion/DesktopPairing.cs b/PlotLine/Services/NativeCompanion/DesktopPairing.cs index d7226955..e374116d 100644 --- a/PlotLine/Services/NativeCompanion/DesktopPairing.cs +++ b/PlotLine/Services/NativeCompanion/DesktopPairing.cs @@ -29,8 +29,8 @@ public sealed class DesktopPairing(IDataProtectionProvider protection, TimeProvi } } public bool Exists(string code){lock(gate)return pending.TryGetValue(code,out var p)&&p.Expires>clock.GetUtcNow()&&p.UserId==null;} - public bool Approve(string code,int userId,Guid stamp) - {lock(gate){if(!pending.TryGetValue(code,out var p)||p.Expires<=clock.GetUtcNow()||p.UserId!=null)return false;p.UserId=userId;p.Stamp=stamp;return true;}} + public bool Approve(string code,int userId,Guid stamp,bool retainImport=false) + {lock(gate){if(!pending.TryGetValue(code,out var p)||p.Expires<=clock.GetUtcNow()||p.UserId!=null)return false;p.UserId=userId;p.Stamp=stamp;p.RetainImport=retainImport;return true;}} public string? Redeem(string code,string verifier) { if(verifier.Length<43||verifier.Length>128)return null; @@ -39,7 +39,7 @@ public sealed class DesktopPairing(IDataProtectionProvider protection, TimeProvi if(!pending.TryGetValue(code,out var p)||p.Expires<=clock.GetUtcNow()||!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(p.Challenge),Encoding.ASCII.GetBytes(Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier))))))return null; if(p.UserId is not int user)return null; pending.Remove(code); - return protector.Protect(JsonSerializer.Serialize(new Grant(user,p.Stamp,clock.GetUtcNow().AddHours(4)))); + return protector.Protect(JsonSerializer.Serialize(new Grant(user,p.Stamp,clock.GetUtcNow().AddHours(4),p.RetainImport))); } } public Grant? Read(string token) @@ -47,8 +47,8 @@ public sealed class DesktopPairing(IDataProtectionProvider protection, TimeProvi try{var grant=JsonSerializer.Deserialize(protector.Unprotect(token));return grant?.Expires>clock.GetUtcNow()?grant:null;} catch(Exception e)when(e is CryptographicException or JsonException or FormatException){return null;} } - public sealed record Grant(int UserId,Guid Stamp,DateTimeOffset Expires); - private sealed class Pending(string challenge,DateTimeOffset expires){public string Challenge=challenge;public DateTimeOffset Expires=expires;public int? UserId;public Guid Stamp;} + public sealed record Grant(int UserId,Guid Stamp,DateTimeOffset Expires,bool RetainImport=false); + private sealed class Pending(string challenge,DateTimeOffset expires){public string Challenge=challenge;public DateTimeOffset Expires=expires;public int? UserId;public Guid Stamp;public bool RetainImport;} } public sealed class DesktopAuthentication(IOptionsMonitor options,ILoggerFactory logger,UrlEncoder encoder,DesktopPairing pairing,IUserRepository users) @@ -62,7 +62,7 @@ public sealed class DesktopAuthentication(IOptionsMonitorDateTime.UtcNow)))return AuthenticateResult.Fail("Sign in again."); - var identity=new ClaimsIdentity([new(ClaimTypes.NameIdentifier,grant.UserId.ToString()),new("PlotLine.SecurityStamp",grant.Stamp.ToString()),new("NativeCompanion.Expires",grant.Expires.UtcDateTime.ToString("O")),new("NativeCompanion.Grant",Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(header[7..]))))],DesktopPairing.Scheme); + var identity=new ClaimsIdentity([new(ClaimTypes.NameIdentifier,grant.UserId.ToString()),new("PlotLine.SecurityStamp",grant.Stamp.ToString()),new("NativeCompanion.RetainImport",grant.RetainImport?"true":"false"),new("NativeCompanion.Expires",grant.Expires.UtcDateTime.ToString("O")),new("NativeCompanion.Grant",Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(header[7..]))))],DesktopPairing.Scheme); return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity),DesktopPairing.Scheme)); } } diff --git a/PlotLine/Services/NativeCompanion/NativeImportService.cs b/PlotLine/Services/NativeCompanion/NativeImportService.cs index d51128dd..edd86291 100644 --- a/PlotLine/Services/NativeCompanion/NativeImportService.cs +++ b/PlotLine/Services/NativeCompanion/NativeImportService.cs @@ -6,11 +6,11 @@ using PlotDirector.Companion.Protocol; using PlotLine.Data; namespace PlotLine.Services.NativeCompanion; public sealed record NativeImportItem(Guid ReviewID,int Version,string Key,string Hash,string Title,int Start,int End,NativeImportScene[] Scenes); -public sealed record NativeImportScene(string Key,string Title,string Summary,string Text,int StartParagraph,int EndParagraph,int Words); -public sealed record NativeImportPlan(int BookID,Guid ManuscriptID,NativeImportItem[] Items,string[] Conflicts,int Skipped,string Ticket); +public sealed record NativeImportScene(string Key,string Title,string Summary,string Text,int? StartParagraph,int? EndParagraph,int Words); +public sealed record NativeImportPlan(int BookID,Guid ManuscriptID,NativeImportItem[] Items,string[] Conflicts,int Skipped,string Ticket,string BookTitle="",int ProjectID=0); public sealed record NativeImportTicket(int User,int Book,Guid[] Reviews,int[] Versions,DateTime Expires,Guid Operation); -public sealed class NativeImportResult {public int BuildID{get;set;}public int ChaptersCreated{get;set;}public int ScenesCreated{get;set;}public bool AlreadyBuilt{get;set;}public string Message{get;set;}="";} -public sealed class NativeImportService(INativeReviewRepository reviews,IWordCompanionRepository access,INativeImportRepository imports,IDataProtectionProvider protection,ISubscriptionService subscriptions) +public sealed class NativeImportResult {public int ProjectID{get;set;}public string BookTitle{get;set;}="";public int BookID{get;set;}public int Skipped{get;set;}public int BuildID{get;set;}public int ChaptersCreated{get;set;}public int ScenesCreated{get;set;}public bool AlreadyBuilt{get;set;}public string Message{get;set;}="";} +public sealed class NativeImportService(INativeReviewRepository reviews,IWordCompanionRepository access,INativeImportRepository imports,IDataProtectionProvider protection,ISubscriptionService subscriptions,IBookRepository? books=null) { private readonly IDataProtector ticket=protection.CreateProtector("NativeImport.Confirmation.v1"); private readonly IDataProtector source=protection.CreateProtector("NativeImport.Source.v1"); @@ -20,36 +20,40 @@ public sealed class NativeImportService(INativeReviewRepository reviews,IWordCom if(!(await subscriptions.CanUseFeatureAsync(user,Models.SubscriptionFeature.Import)).Allowed)throw new UnauthorizedAccessException("Import is not available on this account."); var structure=await access.GetBookStructureAsync(book,user)??throw new UnauthorizedAccessException("Book access denied."); if(ids.Length is <1 or >100||ids.Distinct().Count()!=ids.Length)throw new ArgumentException("Select up to 100 different chapter reviews."); + var metadata=books==null?null:await books.GetAsync(book); var items=new List();var conflicts=new List();var skipped=0;Guid manuscript=Guid.Empty;var versions=new List(); foreach(var id in ids){var row=await reviews.Get(user,id)??throw new ArgumentException("A review expired or is unavailable.");if(row.BookID!=book)throw new UnauthorizedAccessException("Reviews must belong to this book.");versions.Add(row.Version); if(manuscript==Guid.Empty)manuscript=row.ManuscriptID;if(manuscript!=row.ManuscriptID)throw new ArgumentException("Select chapters from one manuscript."); var result=JsonSerializer.Deserialize(row.ResultJson)!;var decisions=string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize(row.DecisionsJson)!; var approved=decisions.Where(d=>d.State=="approved").OrderBy(d=>d.Index).ToArray();skipped+=result.Scenes.Length-approved.Length; if(approved.Length==0){conflicts.Add($"{result.ChapterTitle}: no approved scenes. Save review decisions first.");continue;} - if(string.IsNullOrEmpty(row.EncryptedSource)){conflicts.Add($"{result.ChapterTitle}: source prose was not retained. Use the updated Companion and explicitly retain this chapter for import.");continue;} + if(string.IsNullOrEmpty(row.EncryptedSource)){conflicts.Add($"{result.ChapterTitle}: source prose was not retained. Reconnect the Companion, enable encrypted import capture in browser approval, and explicitly resubmit this chapter.");continue;} var capture=JsonSerializer.Deserialize(source.Unprotect(row.EncryptedSource))!;NativeChapterMapping.Build(capture); if(Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{capture.ChapterStart,capture.ChapterEnd,capture.Paragraphs})))!=row.ContentHash)throw new ArgumentException("Source content no longer matches this review."); if(capture.ManuscriptId!=row.ManuscriptID||capture.BookId!=book||capture.ChapterStart!=row.ChapterStart||capture.ChapterEnd!=row.ChapterEnd)throw new ArgumentException("Source identity mismatch."); var title=string.IsNullOrWhiteSpace(result.ChapterTitle)?"Chapter":result.ChapterTitle;var key="native:"+manuscript.ToString("N")+":"+row.ChapterStart; - var scenes=new List();foreach(var choice in approved){if(choice.Index<0||choice.Index>=result.Scenes.Length)throw new ArgumentException("Review boundaries are invalid.");var scene=result.Scenes[choice.Index];var paragraphs=capture.Paragraphs.Where(p=>p.Start>=scene.Start&&p.End<=scene.End&&!p.IsHeading).ToArray();if(paragraphs.Length==0)throw new ArgumentException("A scene has no source paragraphs.");var text=string.Join("",paragraphs.Select(p=>p.Text));scenes.Add(new(key+":"+scene.Start,choice.Title,choice.Summary,text,paragraphs[0].Index,paragraphs[^1].Index,Count(text)));} + // Captures use chapter-relative paragraph indices. Do not mislabel them as + // whole-document Word paragraph positions; native navigation uses absolute ranges. + var scenes=new List();foreach(var choice in approved){if(choice.Index<0||choice.Index>=result.Scenes.Length)throw new ArgumentException("Review boundaries are invalid.");var scene=result.Scenes[choice.Index];var paragraphs=capture.Paragraphs.Where(p=>p.Start>=scene.Start&&p.End<=scene.End&&!p.IsHeading).ToArray();if(paragraphs.Length==0)throw new ArgumentException("A scene has no source paragraphs.");var text=string.Join("",paragraphs.Select(p=>p.Text));scenes.Add(new(key+":"+scene.Start,choice.Title,choice.Summary,text,null,null,Count(text)));} items.Add(new(row.ReviewID,row.Version,key,row.ContentHash,title,row.ChapterStart,row.ChapterEnd,scenes.ToArray())); } var imported=await imports.List(user,book);var pending=new List();foreach(var item in items.OrderBy(i=>i.Start)){ var prior=imported.FirstOrDefault(p=>p.ChapterKey==item.Key);if(prior!=null){if(prior.ContentHash==item.Hash&&prior.ReviewVersion==item.Version){skipped+=item.Scenes.Length;continue;}conflicts.Add(item.Title+": already imported with different content/decisions; existing scenes will not be overwritten.");continue;} + if(imported.Any(p=>p.DocumentGuid==manuscript&&p.ChapterStartstring.Equals(c.Title.Trim(),item.Title.Trim(),StringComparison.OrdinalIgnoreCase)))conflicts.Add(item.Title+": an existing chapter has this title. Resolve the match before importing; no replacement is performed."); if(pending.Any(p=>p.Start Commit(int user,string confirmation) { NativeImportTicket saved;try{saved=JsonSerializer.Deserialize(ticket.Unprotect(confirmation))!;}catch(Exception e)when(e is CryptographicException or JsonException or ArgumentException){throw new ArgumentException("Invalid import confirmation.");} if(saved.User!=user||saved.Expires0)throw new ArgumentException(string.Join(" ",plan.Conflicts));if(plan.Items.Length==0)return new(){AlreadyBuilt=true,Message="All selected approved chapters already match an import. Nothing changed."}; - return await imports.Commit(user,saved.Operation,plan); + if(plan.Conflicts.Length>0)throw new ArgumentException(string.Join(" ",plan.Conflicts));if(plan.Items.Length==0)return new(){BookID=saved.Book,Skipped=plan.Skipped,AlreadyBuilt=true,Message="All selected approved chapters already match an import. Nothing changed."}; + var result=await imports.Commit(user,saved.Operation,plan);result.BookID=saved.Book;result.ProjectID=plan.ProjectID;result.BookTitle=plan.BookTitle;result.Skipped=plan.Skipped;return result; } private static int Count(string text)=>text.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length; } diff --git a/PlotLine/Sql/233_NativeImportedPositions.sql b/PlotLine/Sql/233_NativeImportedPositions.sql new file mode 100644 index 00000000..6c31959b --- /dev/null +++ b/PlotLine/Sql/233_NativeImportedPositions.sql @@ -0,0 +1,44 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +IF COL_LENGTH(N'dbo.NativeReviewImports',N'DocumentGuid') IS NULL + ALTER TABLE dbo.NativeReviewImports ADD DocumentGuid uniqueidentifier NULL,ObservationRevision bigint NULL,ChapterStart int NULL,ChapterEnd int NULL,ScenePositionsJson nvarchar(max) NULL; +GO +CREATE OR ALTER PROCEDURE dbo.NativeReviewSource_Save @UserID int,@ReviewID uniqueidentifier,@EncryptedSource nvarchar(max),@ObservedRevision bigint=NULL +AS +BEGIN + SET NOCOUNT ON; + IF DATALENGTH(@EncryptedSource)>8388608 THROW 51000,'Source capture too large',1; + UPDATE dbo.NativeChapterReviews SET EncryptedSource=@EncryptedSource,ResultJson=CASE WHEN @ObservedRevision IS NOT NULL THEN JSON_MODIFY(ResultJson,'$.DocumentRevision',@ObservedRevision) ELSE ResultJson END WHERE ReviewID=@ReviewID AND UserID=@UserID AND EncryptedSource IS NULL; +END; +GO +CREATE OR ALTER TRIGGER dbo.NativeReviewImports_CapturePositions ON dbo.NativeReviewImports AFTER INSERT +AS +BEGIN + SET NOCOUNT ON; + UPDATE n SET DocumentGuid=r.ManuscriptID,ObservationRevision=TRY_CONVERT(bigint,JSON_VALUE(r.ResultJson,'$.DocumentRevision')),ChapterStart=r.ChapterStart,ChapterEnd=r.ChapterEnd, + ScenePositionsJson=(SELECT p.Start,p.[End],m.SceneID,n.ChapterID FROM OPENJSON(r.ResultJson,'$.Scenes') WITH(Start int,[End] int) p JOIN dbo.OnboardingManuscriptBuildSceneMap m ON m.OnboardingManuscriptBuildID=n.BuildID AND m.TemporarySceneKey=CONCAT(n.ChapterKey,':',p.Start) FOR JSON PATH) + FROM dbo.NativeReviewImports n JOIN inserted i ON i.BookID=n.BookID AND i.ChapterKey=n.ChapterKey JOIN dbo.NativeChapterReviews r ON r.ReviewID=n.ReviewID; + IF EXISTS(SELECT 1 FROM dbo.NativeReviewImports n JOIN inserted i ON i.BookID=n.BookID AND i.ChapterKey=n.ChapterKey JOIN dbo.NativeReviewImports other ON other.BookID=n.BookID AND other.DocumentGuid=n.DocumentGuid AND other.ChapterKey<>n.ChapterKey AND other.ChapterStart=s.Start AND @Position=n.ChapterStart AND @Position @Html.AntiForgeryToken() + diff --git a/PlotLine/Views/NativeWorkspace/ImportCommit.cshtml b/PlotLine/Views/NativeWorkspace/ImportCommit.cshtml index bc8daa2d..068689fe 100644 --- a/PlotLine/Views/NativeWorkspace/ImportCommit.cshtml +++ b/PlotLine/Views/NativeWorkspace/ImportCommit.cshtml @@ -1,3 +1,3 @@ @model PlotLine.Services.NativeCompanion.NativeImportResult @{ViewData["Title"]="Import result";} -

Approved import result

@Model.Message

New chapters: @Model.ChaptersCreated · New scenes: @Model.ScenesCreated · Existing content overwritten: 0

Word prose and markers are unchanged. Saved PlotDirector scenes are now available in the book workspace. Automatic Word marker linkage is a separate action.

Return to PlotDirector
+

Approved import result

@if(!string.IsNullOrEmpty(Model.BookTitle)){

Book: @Model.BookTitle

}
@Model.Message

@(Model.AlreadyBuilt?"Previously created":"Created") chapters: @Model.ChaptersCreated · Scenes: @Model.ScenesCreated · Skipped selections: @Model.Skipped · Existing content overwritten: 0

Word prose and markers are unchanged. Saved PlotDirector scenes are now available in the book workspace. Automatic Word marker linkage is a separate action.

Open the imported book
diff --git a/PlotLine/Views/NativeWorkspace/ImportPreview.cshtml b/PlotLine/Views/NativeWorkspace/ImportPreview.cshtml index 0737a420..d312e889 100644 --- a/PlotLine/Views/NativeWorkspace/ImportPreview.cshtml +++ b/PlotLine/Views/NativeWorkspace/ImportPreview.cshtml @@ -1,6 +1,6 @@ @model PlotLine.Services.NativeCompanion.NativeImportPlan @{ViewData["Title"]="Preview approved import";} -

Preview approved import

Creates @Model.Items.Length new chapters and @Model.Items.Sum(i=>i.Scenes.Length) scenes. @Model.Skipped rejected, pending or already imported scenes are skipped. Word remains unchanged.

+

Preview approved import

Target book: @Model.BookTitle

Creates @Model.Items.Length new chapters and @Model.Items.Sum(i=>i.Scenes.Length) scenes. @Model.Skipped rejected, pending or already imported scenes are skipped. Word remains unchanged.

New chapters append in manuscript order. Existing chapters, relationships, plot lines and author metadata are preserved. Matching imported captures are skipped; competing changes require reconciliation.

@if(Model.Conflicts.Length>0){

Resolve before importing

    @foreach(var conflict in Model.Conflicts){
  • @conflict
  • }
} @foreach(var chapter in Model.Items){

Create chapter: @chapter.Title

    @foreach(var scene in chapter.Scenes){
  • Create scene: @scene.Title

    @scene.Summary

    @scene.Words words
  • }
} diff --git a/PlotLine/Views/NativeWorkspace/Review.cshtml b/PlotLine/Views/NativeWorkspace/Review.cshtml index 9cb89b36..6372a866 100644 --- a/PlotLine/Views/NativeWorkspace/Review.cshtml +++ b/PlotLine/Views/NativeWorkspace/Review.cshtml @@ -21,5 +21,5 @@

Requires the exact live manuscript and observed revision. Navigation is explicit and never triggered by following.

} -

After saving decisions, return to the Companion workspace, select the reviewed chapters and preview the approved import. Only approved scenes are included. No import occurs until you confirm the preview. Older captures require the updated Companion to retain source prose explicitly.

+

After saving decisions, return to the Companion workspace, select the reviewed chapters and preview the approved import. Only approved scenes are included. No import occurs until you confirm the preview. For older captures, reconnect the Companion, enable encrypted import capture in browser approval, then explicitly resubmit the chapter. Unchanged analysis can be reused.

diff --git a/PlotLine/Views/Shared/_WritingCompanionLayout.cshtml b/PlotLine/Views/Shared/_WritingCompanionLayout.cshtml index 37a3fa78..c7c63947 100644 --- a/PlotLine/Views/Shared/_WritingCompanionLayout.cshtml +++ b/PlotLine/Views/Shared/_WritingCompanionLayout.cshtml @@ -1,3 +1,3 @@ @using System.Security.Claims -@ViewData["Title"] · PlotDirector -@RenderBody()@await RenderSectionAsync("Scripts",required:false) +@ViewData["Title"] · PlotDirector +@RenderBody()@await RenderSectionAsync("Scripts",required:false) diff --git a/PlotLine/wwwroot/js/writing-embedded-theme.js b/PlotLine/wwwroot/js/writing-embedded-theme.js new file mode 100644 index 00000000..f5785e02 --- /dev/null +++ b/PlotLine/wwwroot/js/writing-embedded-theme.js @@ -0,0 +1,2 @@ +// Reuse the surrounding PWA's theme policy; no separate theme settings or persistence. +(()=>{if(parent===window)return;try{const outer=parent.document.documentElement;const sync=()=>{for(const name of ['data-app-theme','data-theme','data-bs-theme']){const value=outer.getAttribute(name);if(value)document.documentElement.setAttribute(name,value);else document.documentElement.removeAttribute(name);}};sync();const observer=new MutationObserver(sync);observer.observe(outer,{attributes:true,attributeFilter:['data-app-theme','data-theme','data-bs-theme']});window.addEventListener('pagehide',()=>observer.disconnect());}catch{/* A foreign embedding page cannot supply trusted appearance state. */}})();