From 80f7cb516b52bcf1a0d42493700f0bde85ac776c Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Fri, 20 Nov 2026 22:44:47 +0000 Subject: [PATCH] Preserve explicit Word choices and expire stale UI observations --- .../Agent/TrayCoordinator.cs | 15 +++++---- .../DeveloperVersion.props | 2 +- .../Protocol/Messages.cs | 2 ++ PlotDirector.NativeCompanion/Tests/Program.cs | 2 ++ .../Tests/TrayTests.cs | 6 ++-- .../Tests/WordObservationTests.cs | 31 +++++++++++++++++++ .../Vsto/Properties/AssemblyInfo.cs | 4 +-- .../Vsto/WordAdapter.cs | 3 +- .../WindowsValidation/Setup/Release.json | 6 ++-- .../Browser/writer-word-selection.cjs | 21 +++++++++++++ PlotLine.Tests/Browser/writer3-navigation.cjs | 4 +-- PlotLine.Tests/WriterWordTests.cs | 4 +++ PlotLine/wwwroot/js/writer-word.js | 10 +++--- 13 files changed, 88 insertions(+), 22 deletions(-) create mode 100644 PlotDirector.NativeCompanion/Tests/WordObservationTests.cs create mode 100644 PlotLine.Tests/Browser/writer-word-selection.cjs diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs index eb33d2b8..e641e1aa 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs @@ -4,6 +4,9 @@ namespace PlotDirector.Companion.Agent; // One control centre in the existing agent. Exact-session commands only; no COM or UI objects. public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway cloud,ChapterAiWork ai,TimeProvider? synchronisationClock=null) { + // Match the existing server lease window; transport heartbeats cannot renew UI evidence indefinitely. + private static readonly TimeSpan WordObservationLifetime=TimeSpan.FromSeconds(45); + private bool FreshWordObservation(TrayDocument doc)=>doc.WordObservedUtc.HasValue&&ChapterNow>=doc.WordObservedUtc.Value&&ChapterNow-doc.WordObservedUtc.Valuep.Value.Session==d.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(pending);d.MaintenanceReport="Stopped: document revision changed; inspect before retrying cleanup.";}Cancel(d,notifyWord:false);d.LastChapterInterruption="Document revision changed; waiting for saved-state evidence.";if(existed&&rangeInstances.Contains(instance))d.NextChapterCheckUtc=ChapterNow.AddSeconds(3);d.WordSaved=null;d.Chapters=[];d.FailedChapters.Clear();d.Words=null;d.ChapterId=null;d.SceneId=null;d.ChapterTitle="";d.SceneTitle="";d.LastPresenceKey="";d.Status="Document changed. Detect chapters to refresh this snapshot.";} + if(d.Revision!=descriptor.Revision){if(d.AssociationRequest!=Guid.Empty){d.AssociationRequest=Guid.Empty;d.AssociationNotice="Word changed before the association was confirmed. Check the document and retry.";}foreach(var pending in maintenance.Where(p=>p.Value.Session==d.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(pending);d.MaintenanceReport="Stopped: document revision changed; inspect before retrying cleanup.";}Cancel(d,notifyWord:false);d.LastChapterInterruption="Document revision changed; waiting for saved-state evidence.";if(existed&&rangeInstances.Contains(instance))d.NextChapterCheckUtc=ChapterNow.AddSeconds(3);d.WordSaved=null;d.WordObservedUtc=null;d.Chapters=[];d.FailedChapters.Clear();d.Words=null;d.ChapterId=null;d.SceneId=null;d.ChapterTitle="";d.SceneTitle="";d.LastPresenceKey="";d.Status="Document changed. Detect chapters to refresh this snapshot.";} if(reconnectBindings.Remove((instance,descriptor.SessionId),out var binding)&&binding.Expires>DateTime.UtcNow&&binding.Manuscript==descriptor.ManuscriptId&&binding.Authentication==cloud.Status().AuthenticationContext){d.Book=binding.Book;d.Authentication=binding.Authentication;} d.Revision=descriptor.Revision;d.Manuscript=descriptor.ManuscriptId;d.Title=descriptor.Title;d.RememberedBook=descriptor.RememberedBook;d.AssociationSite=descriptor.AssociationSite;d.Observed=DateTime.UtcNow; } @@ -38,7 +41,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway 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"){if(doc.WordSaved!=request.WordSaved&&request.WordSaved==true&&doc.NextChapterCheckUtc!=default)doc.NextChapterCheckUtc=ChapterNow.AddSeconds(3);if(ChapterCapable(instance)&&(doc.Cursor!=request.Start||doc.WordSaved!=request.WordSaved)){ChapterCursorEvidence.Invalidate(doc);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(doc.WordSaved==true&&doc.RibbonNotice?.State=="Save required")doc.RibbonNotice=null;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}} + if(request.Kind=="selection"){doc.WordObservedUtc=request.WordObservedUtc.HasValue?(request.WordObservedUtc.Value.ToUniversalTime()<=ChapterNow?request.WordObservedUtc.Value.ToUniversalTime():null):ChapterNow;if(doc.WordSaved!=request.WordSaved&&request.WordSaved==true&&doc.NextChapterCheckUtc!=default)doc.NextChapterCheckUtc=ChapterNow.AddSeconds(3);if(ChapterCapable(instance)&&(doc.Cursor!=request.Start||doc.WordSaved!=request.WordSaved)){ChapterCursorEvidence.Invalidate(doc);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(doc.WordSaved==true&&doc.RibbonNotice?.State=="Save required")doc.RibbonNotice=null;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}} if(request.Kind=="selection"&&doc.LastPresenceKey!=""&&chapterWork.TryGetValue(doc.Session,out var localWork)&&CurrentChapterWork(doc,localWork)&&localWork.Supported) PumpChapterWork(doc,localWork); ChapterFrame(doc,request,answer); @@ -78,13 +81,13 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway if(connection.Health?.Authentication=="verified"&&AudioStatus?.Invoke(activeDocument.Session) is { } audio) { answer.AudioState=audio.State;answer.AudioOperations=audio.Operations; } } - if(commands.TryGetValue(instance,out var queue)&&queue.Count>0)answer.Command=queue.Dequeue(); + if(commands.TryGetValue(instance,out var queue))while(queue.Count>0){var queued=queue.Dequeue();if(queued.Kind=="navigate"&&(!documents.TryGetValue(queued.SessionId,out var target)||!FreshWordObservation(target)))continue;answer.Command=queued;break;} return answer; } } public void Disconnected(Guid instance,Guid lease=default){lock(gate){if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return;leases.Remove(instance);acknowledgedNavigationInstances.Remove(instance);rangeInstances.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;} + private bool Queue(TrayDocument doc,AdapterCommand command){if(command.Kind=="navigate"&&!FreshWordObservation(doc)){doc.Status="Word position awaits a fresh UI observation. Nothing was requested.";return false;}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) { @@ -165,7 +168,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway 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&&reply.ParagraphRevision0&&reply.ParagraphRevision0&&!ChapterCapable(doc.Instance))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; @@ -229,7 +232,7 @@ public sealed class TrayDocument internal DateTime RibbonRequestedUtc;internal Guid RibbonPermit;internal PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? RibbonNotice; public int? ContextCursor;public long ContextRevision=-1;public int ContextBook;public Guid ContextManuscript; public readonly DateTime FirstObserved=DateTime.UtcNow; - public DateTime NextChapterCheckUtc,LastChapterPollUtc;public bool RequestChapterPoll;public Guid AssociationRequest;public bool AssociationNeedsSave;public string AssociationNotice="";public string MaintenanceReport="";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 DateTime NextChapterCheckUtc,LastChapterPollUtc;public bool RequestChapterPoll;public Guid AssociationRequest;public bool AssociationNeedsSave;public string AssociationNotice="";public string MaintenanceReport="";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? WordObservedUtc;public DateTime Observed,Started; public StructureSuggestion[] Chapters=[];public StructureSuggestion? Current;public Queue Pending=[];public HashSet<(long,int,int)> Completed=[];public HashSet<(long,int,int)> FailedChapters=[];public List Errors=[]; internal TrayDocument Snapshot(){var copy=(TrayDocument)MemberwiseClone();copy.Completed=new(Completed);copy.FailedChapters=new(FailedChapters);copy.Errors=new(Errors);copy.Pending=new(Pending);return copy;} public override string ToString()=>Title+(Active?" (active in Word)":""); diff --git a/PlotDirector.NativeCompanion/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props index 8cc685a3..5087bbf3 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.40 +1.0.0.41 diff --git a/PlotDirector.NativeCompanion/Protocol/Messages.cs b/PlotDirector.NativeCompanion/Protocol/Messages.cs index 3ca1768c..830d0303 100644 --- a/PlotDirector.NativeCompanion/Protocol/Messages.cs +++ b/PlotDirector.NativeCompanion/Protocol/Messages.cs @@ -47,6 +47,8 @@ public sealed class Message [DataMember] public string Kind { get; set; } = ""; [DataMember] public Guid WordInstanceId { get; set; } [DataMember] public Guid SessionId { get; set; } + // Captured before COM reads on Word STA; optional for older clients. Never stamped by agent heartbeats. + [DataMember] public DateTime? WordObservedUtc { get; set; } [DataMember] public long Sequence { get; set; } [DataMember] public long Revision { get; set; } [DataMember] public Guid SnapshotId { get; set; } diff --git a/PlotDirector.NativeCompanion/Tests/Program.cs b/PlotDirector.NativeCompanion/Tests/Program.cs index 20dea20e..f6c343e3 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("--word-observation")){await WordObservationTests.Run((ok,name)=>{if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);});return;} if(args.Contains("--chapter-sync")){ChapterRangeVerificationTests.Run();ChapterReopenTests.Run();await ChapterAgentTests.Run();await ChapterHandshakeTests.Run();await WordReopeningWorkTests.Run();return;} if(args.Contains("--native-capture-upload")){await NativeCaptureUploadTests.Run();return;} var passed = 0; @@ -192,6 +193,7 @@ await ChapterAiTests.Run(Check); await WorkflowTests.Run(Check); ParagraphSnapshotTests.Run(Check); await TrayTests.Run(Check); +await WordObservationTests.Run(Check); await NativeConnectionRefreshTests.Run(Check); await PersistentConnectionTests.Run(Check); Console.WriteLine($"Native foundation: {passed} checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified."); diff --git a/PlotDirector.NativeCompanion/Tests/TrayTests.cs b/PlotDirector.NativeCompanion/Tests/TrayTests.cs index 20865076..e4209904 100644 --- a/PlotDirector.NativeCompanion/Tests/TrayTests.cs +++ b/PlotDirector.NativeCompanion/Tests/TrayTests.cs @@ -98,10 +98,10 @@ internal static class TrayTests control.Disconnected(instance,replacementLease);check(control.Documents.Length==0,"pipe disconnect removes exact Word instance sessions and pending control work"); } private static async Task Until(Func condition){using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(10));while(!condition())await Task.Delay(20,timeout.Token);} - private sealed class Server:HttpMessageHandler + internal sealed class Server:HttpMessageHandler { - public int Heartbeats,Captures;public bool DenyPresence;public AdapterCommand? Command;private Guid captureReply; + public readonly System.Collections.Concurrent.ConcurrentQueue Observations=new();public int Heartbeats,Captures;public bool DenyPresence;public AdapterCommand? Command;private Guid captureReply; protected override Task SendAsync(HttpRequestMessage request,CancellationToken cancellation) - {if(request.Method==HttpMethod.Post&&request.RequestUri!.AbsolutePath.EndsWith("/presence")){Interlocked.Increment(ref Heartbeats);if(DenyPresence)return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Forbidden));var reply=new NativePresence{Navigation=Command};if(Command!=null)captureReply=Command.Id;Command=null;return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(reply)});}if(request.RequestUri!.AbsolutePath.EndsWith("/manuscript-capture")){Interlocked.Increment(ref Captures);return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(new NativePresence{CaptureRequestId=captureReply,Revision=1})});}object body=request.RequestUri!.AbsolutePath.Split('/').Last() switch{"pair"=>new{code=new string('A',24)},"token"=>new{accessToken="test"},"books"=>new[]{new CompanionBook{BookId=3,Title="Allowed book"},new CompanionBook{BookId=4,Title="Other allowed book"}},_=>new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow}};return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(body)});} + {if(request.Method==HttpMethod.Post&&request.RequestUri!.AbsolutePath.EndsWith("/presence")){Observations.Enqueue(System.Text.Json.JsonSerializer.Deserialize(request.Content!.ReadAsStringAsync(cancellation).GetAwaiter().GetResult(),new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web))!);Interlocked.Increment(ref Heartbeats);if(DenyPresence)return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Forbidden));var reply=new NativePresence{Navigation=Command};if(Command!=null)captureReply=Command.Id;Command=null;return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(reply)});}if(request.RequestUri!.AbsolutePath.EndsWith("/manuscript-capture")){Interlocked.Increment(ref Captures);return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(new NativePresence{CaptureRequestId=captureReply,Revision=1})});}object body=request.RequestUri!.AbsolutePath.Split('/').Last() switch{"pair"=>new{code=new string('A',24)},"token"=>new{accessToken="test"},"books"=>new[]{new CompanionBook{BookId=3,Title="Allowed book"},new CompanionBook{BookId=4,Title="Other allowed book"}},_=>new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow}};return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(body)});} } } diff --git a/PlotDirector.NativeCompanion/Tests/WordObservationTests.cs b/PlotDirector.NativeCompanion/Tests/WordObservationTests.cs new file mode 100644 index 00000000..91cde836 --- /dev/null +++ b/PlotDirector.NativeCompanion/Tests/WordObservationTests.cs @@ -0,0 +1,31 @@ +using PlotDirector.Companion.Agent; +using PlotDirector.Companion.Protocol; +internal static class WordObservationTests +{ + private sealed class Clock:TimeProvider {public DateTimeOffset Now=DateTimeOffset.FromUnixTimeMilliseconds(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());public override DateTimeOffset GetUtcNow()=>Now;} + private static async Task Until(Func condition){using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(12));while(!condition())await Task.Delay(20,timeout.Token);} + public static async Task Run(Action check) + { + var clock=new Clock();using(var wire=new MemoryStream()){await FrameCodec.WriteAsync(wire,new Message{Kind="selection",WordObservedUtc=clock.Now.UtcDateTime},CancellationToken.None);wire.Position=0;check((await FrameCodec.ReadAsync(wire,CancellationToken.None)).WordObservedUtc?.ToUniversalTime()==clock.Now.UtcDateTime,"Word observation timestamp survives actual IPC encoding");} + using var handler=new TrayTests.Server();using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Books.Length>0);using var ai=new ChapterAiWork(cloud);var sessions=new SessionManager(cloud,ai);var tray=new TrayCoordinator(sessions,cloud,ai,clock); + var instance=Guid.NewGuid();var lease=Guid.NewGuid();var session=Guid.NewGuid();var manuscript=Guid.NewGuid();long sequence=0; + sessions.Attach(instance,lease);tray.Attach(instance,lease,true,acknowledgedNavigation:true); + Message Send(Message value){if(value.Kind=="selection"&&!value.WordObservedUtc.HasValue)value.WordObservedUtc=clock.Now.UtcDateTime;value.WordInstanceId=instance;value.Sequence=++sequence;return tray.Exchange(instance,value,sessions.Apply(lease,value),lease);} + var descriptor=new DocumentDescriptor{SessionId=session,ManuscriptId=manuscript,Title="Isolated Word observation",Revision=1};Send(new(){Kind="document",Documents=[descriptor]});tray.SelectBook(session,3,false);Send(new(){Kind="selection",SessionId=session,Revision=1,Start=10,WordSaved=true});for(int i=0;i<5;i++)Send(new(){Kind="ping"}); + var doc=tray.Documents.Single();using var stop=new CancellationTokenSource();var loop=tray.Heartbeat(stop.Token); + try{ + await Until(()=>handler.Observations.Any(p=>p.BookId==3));check(handler.Observations.Last(p=>p.BookId==3).WordSaved==true,"fresh UI observation supplies saved-state evidence"); + var previous=handler.Observations.Last().Sequence;clock.Now=clock.Now.AddSeconds(46);Send(new(){Kind="ping"});Send(new(){Kind="metrics",SessionId=session,Revision=1,OperationMessage="Transport alive; no new COM observation"});doc.LastPresenceUtc=DateTime.MinValue;doc.LastPresenceKey=""; + await Until(()=>handler.Observations.Any(p=>p.Sequence>previous&&p.BookId==3));var stale=handler.Observations.Last(p=>p.BookId==3); + Console.WriteLine($"OBSERVATION age=46s transportAlive=true publishedSaved={stale.WordSaved} cursor={stale.CursorStart}"); + check(stale.WordSaved==null&&stale.CursorStart==null&&stale.ChapterId==null&&stale.SceneId==null,"agent heartbeat and metrics cannot renew stale UI position/saved-state proof");check(stale.WordAvailable&&stale.WordRunning,"stale UI preserves connected document transport identity"); + Send(new(){Kind="selection",SessionId=session,Revision=1,Start=12,WordSaved=true,WordObservedUtc=clock.Now.AddSeconds(-46).UtcDateTime});doc.LastPresenceUtc=DateTime.MinValue;doc.LastPresenceKey="";var beforeDelayed=handler.Observations.Last().Sequence;await Until(()=>handler.Observations.Last().Sequence>beforeDelayed);check(handler.Observations.Last().WordSaved==null,"delayed captured UI frame cannot acquire a fresh timestamp from transport delivery"); + handler.Command=new(){Id=Guid.NewGuid(),Kind="navigate",BookId=3,ManuscriptId=manuscript,SessionId=session,Revision=1,ExpiresUtc=DateTime.UtcNow.AddSeconds(20),Chapter=new(){Start=10}};doc.LastPresenceUtc=DateTime.MinValue;doc.LastPresenceKey="";await Until(()=>handler.Command==null&&doc.Status.Contains("fresh UI"));check(Send(new(){Kind="ping"}).Command==null,"precise navigation is not queued from stale observation");check(doc.NavigationAcknowledgedId==null,"a stalled UI cannot fabricate a completed acknowledgement"); + Send(new(){Kind="selection",SessionId=session,Revision=1,Start=15,WordSaved=true});await Until(()=>handler.Observations.Last(p=>p.BookId==3).CursorStart==15);check(handler.Observations.Last(p=>p.BookId==3).WordSaved==true,"new UI observation recovers without reconnect or reimport"); + handler.Command=new(){Id=Guid.NewGuid(),Kind="navigate",BookId=3,ManuscriptId=manuscript,SessionId=session,Revision=1,ExpiresUtc=DateTime.UtcNow.AddSeconds(20),Chapter=new(){Start=15}};doc.LastPresenceUtc=DateTime.MinValue;doc.LastPresenceKey="";await Until(()=>handler.Command==null&&doc.PendingNavigation!=Guid.Empty);var command=Send(new(){Kind="ping"}).Command;check(command?.Kind=="navigate","recovered exact-session navigation works"); + var ack=Send(new(){Kind="adapter-result",SessionId=session,Revision=1,SnapshotId=command!.Id,OperationMessage="ok"});Console.WriteLine($"ACK status={ack.Status} expected={command.Id} pending={doc.PendingNavigation} received={doc.NavigationAcknowledgedId} result={doc.NavigationResult} expiresIn={(doc.NavigationExpires-DateTime.UtcNow).TotalSeconds:F1}s");check(doc.NavigationAcknowledgedId==command.Id&&doc.NavigationResult=="completed","only correlated native execution result completes navigation"); + var acknowledged=doc.NavigationAcknowledgedId;doc.PendingNavigation=Guid.NewGuid();doc.NavigationRevision=1;doc.NavigationExpires=DateTime.UtcNow.AddSeconds(-1);Send(new(){Kind="adapter-result",SessionId=session,Revision=1,SnapshotId=doc.PendingNavigation,OperationMessage="ok"});check(doc.NavigationAcknowledgedId==acknowledged,"late expired acknowledgement cannot claim new completion"); + tray.Disconnected(instance,lease);var replacement=Guid.NewGuid();sessions.Attach(instance,replacement);tray.Attach(instance,replacement,true,acknowledgedNavigation:true);lease=replacement;Send(new(){Kind="reconcile",Documents=[descriptor]});check(tray.Documents.Single().WordSaved==null,"agent restart/reconcile cannot mint saved UI observations"); + }finally{stop.Cancel();try{await loop;}catch(OperationCanceledException){}} + } +} diff --git a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs index 1db7554e..2b676d08 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.40")] -[assembly: AssemblyFileVersion("1.0.0.40")] +[assembly: AssemblyVersion("1.0.0.41")] +[assembly: AssemblyFileVersion("1.0.0.41")] [assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs index b3dc9cf7..bfbaaef1 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs @@ -201,6 +201,7 @@ namespace PlotDirector.WordAddIn private void CaptureSelection() { selectionReads++; + var observationStartedUtc = DateTime.UtcNow; Word.Selection selection = null; Word.Range range = null; try { @@ -225,7 +226,7 @@ namespace PlotDirector.WordAddIn if(active!=state||activationPending){link.TryPost(new Message {Kind="active",SessionId=state.Session,Revision=state.Revision});activationPending=false;} ChangeActiveDocument(state); - link.TryPost(new Message {Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,WordSaved=saved&&Com(()=>application.BackgroundSavingStatus)==0,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth}); + link.TryPost(new Message {Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,WordSaved=saved&&Com(()=>application.BackgroundSavingStatus)==0,WordObservedUtc=observationStartedUtc,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth}); // Prose is read only on an explicit Companion request; cursor observations never rescan it. } diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json index 9b3a927b..6b0ccdfc 100644 --- a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json +++ b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json @@ -1,7 +1,7 @@ { - "version": "1.0.0.40", - "msiVersion": "1.0.40", - "productCode": "{BA2E0C19-E8D2-4EF8-90B0-C4F2CEB93B15}", + "version": "1.0.0.41", + "msiVersion": "1.0.41", + "productCode": "{EF24354B-9ADC-4C69-9F8C-9BD261CB0291}", "upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}", "atlasBaseline": "9fed339879887964d526cff00772ffc4dc522c5d", "baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}", diff --git a/PlotLine.Tests/Browser/writer-word-selection.cjs b/PlotLine.Tests/Browser/writer-word-selection.cjs new file mode 100644 index 00000000..f7f9a240 --- /dev/null +++ b/PlotLine.Tests/Browser/writer-word-selection.cjs @@ -0,0 +1,21 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'); +const base=process.env.PD_BROWSER_FIXTURE_URL||'http://127.0.0.1:5238'; +(async()=>{const browser=await chromium.launch();try{for(const pwa of [false,true]){ + const c=await browser.newContext();await c.addInitScript(pwa=>{localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()}));if(pwa)Object.defineProperty(navigator,'standalone',{value:true});},pwa); + const a={instanceId:'11111111-1111-1111-1111-111111111111',sessionId:'22222222-2222-2222-2222-222222222222',manuscriptId:'33333333-3333-3333-3333-333333333333',revision:2,bookId:12,wordSaved:true,wordAvailable:true,canAcknowledgeNavigation:true,canChapterSync:true,documentTitle:'Same manuscript name',expires:new Date(Date.now()+3600000).toISOString()},b={...a,sessionId:'44444444-4444-4444-4444-444444444444',active:true}; + let packet={leases:[a],canonical:{manuscriptID:a.manuscriptId},verifiedPositions:[]};let posts=0; + await c.route('**/native-companion/status*',r=>r.fulfill({json:packet}));await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null}}));await c.route('**/WriterWord/Availability?*',r=>r.fulfill({json:{chapter:true,scene:true,paragraph:true}}));await c.route('**/WriterWord/Navigate',r=>{posts++;return r.fulfill({status:202,json:{}})});await c.route('**/hubs/**',r=>r.abort()); + const p=await c.newPage();await p.goto(base+'/Writer/Write?projectId=7&bookId=12&objective=true');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await p.evaluate(()=>window.PlotDirectorNarrativeFocus.set({bookID:12,chapterID:21,sceneID:31})); + const select=p.locator('[data-word-document]'),key=l=>l.instanceId+'/'+l.sessionId;const update=async leases=>{packet={...packet,leases};await p.evaluate(value=>window.dispatchEvent(new CustomEvent('writer-word-state',{detail:value})),packet);}; + await p.waitForFunction(()=>!document.querySelector('[data-ribbon-word=chapter]').disabled);assert.equal(await select.inputValue(),key(a),'single-document startup is convenient'); + await update([a,b]);await select.selectOption(key(a));await update([{...a,wordSaved:null},b]);assert.equal(await select.inputValue(),key(a));assert(await p.locator('[data-ribbon-word=chapter]').isDisabled());assert.match(await p.locator('[data-word-position]').textContent(),/fresh observation/);await update([a,b]);await update([b]); + assert.equal(await select.inputValue(),key(a),'explicit selection must remain disconnected, never silently become the remaining copy'); + assert(await p.locator('[data-ribbon-word=chapter]').isDisabled());assert(await p.locator('[data-word-choose]').isVisible());assert.match(await p.locator('[data-word-state]').textContent(),/selected.*(disconnected|unavailable)/i); + await update([{...a,active:false},b]);assert.equal(await select.inputValue(),key(a),'same live session recovers');await update([a]);assert.equal(await select.inputValue(),key(a),'unselected close retains selection'); + await update([b]);await p.reload();await p.waitForFunction(()=>document.querySelector('[data-word-state]').textContent.toLowerCase().includes('selected'));assert.equal(await select.inputValue(),key(a),'refresh retains explicit unavailable identity');assert(await p.locator('[data-ribbon-word=chapter]').isDisabled()); + const reopened={...a,sessionId:'55555555-5555-5555-5555-555555555555'};await update([reopened,b]);assert.equal(await select.inputValue(),key(a),'new session, same properties/name, requires author choice'); + await select.selectOption(key(reopened));await p.waitForFunction(()=>!document.querySelector('[data-ribbon-word=chapter]').disabled);assert.equal(await select.inputValue(),key(reopened));await update([{...reopened,active:false},{...b,active:true}]);assert.equal(await select.inputValue(),key(reopened),'active Word window is independent'); + await update([]);await update([b]);assert.equal(await select.inputValue(),key(reopened),'agent reconnect cannot redirect explicit selection');assert(await p.locator('[data-ribbon-word=chapter]').isDisabled()); + await p.evaluate(()=>{window.dispatchEvent(new PageTransitionEvent('pagehide',{persisted:true}));window.dispatchEvent(new PageTransitionEvent('pageshow',{persisted:true}));});assert.equal(await select.inputValue(),key(reopened));assert.equal(posts,0,'presence and selection never navigate Word'); + await c.close();console.log('PASS Word document selection '+(pwa?'simulated PWA':'Chromium')+': initial choice, explicit close/reopen/refresh/reconnect, identical names/properties and independent active window; zero automatic navigation.'); +}}finally{await browser.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/PlotLine.Tests/Browser/writer3-navigation.cjs b/PlotLine.Tests/Browser/writer3-navigation.cjs index 47f4f953..fa3d1ce0 100644 --- a/PlotLine.Tests/Browser/writer3-navigation.cjs +++ b/PlotLine.Tests/Browser/writer3-navigation.cjs @@ -47,8 +47,8 @@ const base='http://127.0.0.1:5238'; const denied=await page.request.get(base+'/Writer/Explore?bookId=999');assert.equal(denied.status(),404); await page.goto(base+'/Writer#display-setup');await page.waitForURL('**/Writer/Overview*#display-setup');assert(await page.locator('#display-setup').evaluate(n=>n.open)); await page.goto(base+'/Writer/Review?projectId=7&bookId=12'); - if(pwa){await page.locator('[data-help-open="writer3.review"]:visible').click();await page.waitForFunction(()=>document.querySelector('[data-help-drawer]')?.innerText.includes('Review Your Writing'));} - else{await page.locator('[data-help-key="writer3.review"] button').click();await page.locator('.plotline-help-popover').waitFor();} + // Both contexts now use the shared Help drawer; the former inline popover was superseded. + await page.evaluate(()=>PlotLineHelpDrawer.open('writer3.review'));await page.locator('.help-drawer-article').waitFor(); const help=await page.request.get(base+'/Help/Article/writer3.review');assert.equal(help.status(),200); await page.goto(base+'/Writer?projectId=7&bookId=12');await page.locator('.writer3-home-choices>a').first().focus();assert(await page.locator('.writer3-home-choices>a').first().evaluate(n=>n.matches(':focus-visible')));await page.keyboard.press('Enter');await page.waitForURL('**/Writer/Write?*'); assert.deepEqual(errors,[]);await context.close(); diff --git a/PlotLine.Tests/WriterWordTests.cs b/PlotLine.Tests/WriterWordTests.cs index 5679989d..faeee81d 100644 --- a/PlotLine.Tests/WriterWordTests.cs +++ b/PlotLine.Tests/WriterWordTests.cs @@ -17,6 +17,10 @@ internal static class WriterWordTests var command=store.TakeNavigation(7,"grant",instance,session)!;Check(command.Id==id&&command.ManuscriptId==manuscript&&command.BookId==12,"wire command carries exact identity and expiry");Check(NavigationPolicy.Current(command,session,2,manuscript,clock.Now.UtcDateTime,true)&&!NavigationPolicy.Current(command,session,2,Guid.NewGuid(),clock.Now.UtcDateTime,true)&&!NavigationPolicy.Current(command,session,2,manuscript,clock.Now.UtcDateTime,false),"adapter rejects replaced or unsaved document");Check(!NavigationPolicy.Current(command,session,3,manuscript,clock.Now.UtcDateTime,true)&&!NavigationPolicy.Current(command,Guid.NewGuid(),2,manuscript,clock.Now.UtcDateTime,true),"adapter rejects revision and session changes"); var wrong=State();wrong.NavigationAcknowledgedId=Guid.NewGuid();wrong.NavigationResult="completed";Put(wrong);Check(store.NavigationState(7,12,instance,session,id)=="requested","uncorrelated ack ignored");var ack=State();ack.NavigationAcknowledgedId=id;ack.NavigationResult="completed";Put(ack);Check(store.NavigationState(7,12,instance,session,id)=="completed","only matching authenticated native ack completes");Check(store.NavigationState(8,12,instance,session,id)==null&&store.NavigationState(7,13,instance,session,id)==null,"receipt author/book isolation"); id=Guid.NewGuid();Check(store.Navigate(7,12,instance,session,manuscript,2,100,true,id,true),"next explicit request");clock.Now=clock.Now.AddSeconds(26);Check(store.TakeNavigation(7,"grant",instance,session)==null&&store.NavigationState(7,12,instance,session,id)=="timed-out","expired queue cannot execute later");Check(!NavigationPolicy.Current(command,session,2,manuscript,clock.Now.UtcDateTime,true),"UI queue expiry enforced");Put(State());id=Guid.NewGuid();Check(store.Navigate(7,12,instance,session,manuscript,2,100,true,id,true),"reconnect request");Put(State(revision:3));Check(store.TakeNavigation(7,"grant",instance,session)==null&&store.NavigationState(7,12,instance,session,id)=="invalidated","changed revision invalidates old queue and receipt"); + // A connected agent may keep a document lease alive while its UI observation is unavailable. + var uncertain=State(revision:3);uncertain.WordSaved=null;uncertain.CursorStart=null;Put(uncertain); + Check(store.Read(7,12).Length==1&&!store.Navigate(7,12,instance,session,manuscript,3,100,true,Guid.NewGuid(),true),"connected transport without saved UI proof cannot authorise precise navigation"); + clock.Now=clock.Now.AddSeconds(46);Check(store.Read(7,12).Length==0,"transport lease still expires independently when heartbeats stop"); // Exercise actual authorised chapter/scene resolver with procedure proxies: any unexpected call fails. store.Remove(7,"grant",instance,session);Put(State());var heading=Guid.NewGuid();var scene=Guid.NewGuid();var snapshot=new ParagraphManuscript{BookId=12,ManuscriptId=manuscript,SessionId=session,WordRevision=2,Revision=5,Chapters=[new(){CanonicalId=21,HeadingId=heading}],Scenes=[new(){Id=scene,CanonicalId=31,ChapterId=21}],Paragraphs=[new(){PositionVerified=true,Occurrence=new(){Id=heading,Start=0}},new(){PositionVerified=true,Story=true,SceneId=scene,Occurrence=new(){Id=Guid.NewGuid(),Start=100,Ordinal=1}}]}; var access=NativeWorkflowTests.Proxy((n,a)=>n=="GetBookStructureAsync"?Task.FromResult(new(){BookId=12,Chapters=[new(){ChapterId=21,Scenes=[new(){SceneId=31}]}]}):throw new Exception(n)); diff --git a/PlotLine/wwwroot/js/writer-word.js b/PlotLine/wwwroot/js/writer-word.js index e2ccfd0e..f436e773 100644 --- a/PlotLine/wwwroot/js/writer-word.js +++ b/PlotLine/wwwroot/js/writer-word.js @@ -4,15 +4,17 @@ document.querySelector('[data-review-diagnostics-open]')?.addEventListener('clic const book=Number(root.dataset.bookId);let chapter=Number(root.dataset.chapterId),scene=Number(root.dataset.sceneId);const state=root.querySelector('[data-word-state]'),position=root.querySelector('[data-word-position]'),freshness=root.querySelector('[data-word-freshness]'),message=root.querySelector('[data-word-command]'),choose=root.querySelector('[data-word-choose]'),select=root.querySelector('[data-word-document]'),nav=root.querySelector('[data-word-navigate]'),sceneNav=root.querySelector('[data-word-scene]'),adopt=root.querySelector('[data-word-adopt]'); const reviewing=root.dataset.wordContext==='review',paragraphButton=root.querySelector('[data-word-paragraph]'); let availabilityKey='',availability={},availabilityEpoch=0,availabilityChecked=0;let packet=null,current=null,busy=false,abort=null,checkBusy=false,syncPending=null;const sync=root.querySelector('[data-word-sync]'); +const selectionKey='plotdirector.writer.word-selection.'+(document.body.dataset.pdUserId||'')+'.'+book; +let explicitSelection=null;try{const saved=JSON.parse(sessionStorage.getItem(selectionKey)||'null');if(typeof saved?.key==='string'&&/^[0-9a-f-]{36}\/[0-9a-f-]{36}$/i.test(saved.key)&&typeof saved.title==='string'&&saved.title.length<=260)explicitSelection=saved;}catch{} const key=l=>l.instanceId+'/'+l.sessionId;new MutationObserver(()=>{for(const status of document.querySelectorAll('[data-word-ribbon-status]'))status.textContent=message.textContent;}).observe(message,{childList:true,subtree:true,characterData:true}); const verified=l=>(packet?.verifiedPositions||[]).find(p=>key(p)===key(l)); const requestStatus=()=>window.dispatchEvent(new Event('plotdirector:refresh-word-status')); -function render(data){chapter=Number(root.dataset.chapterId);scene=Number(root.dataset.sceneId);packet=data;const old=current;const leases=(data.leases||[]).filter(l=>l.wordAvailable&&l.bookId===book&&Date.parse(l.expires)>Date.now());const originParams=new URLSearchParams(location.search);const originKey=originParams.get('wordInstanceId')+'/'+originParams.get('wordSessionId');const selected=select.value||originKey;select.replaceChildren(new Option('Choose a document',''),...leases.map(l=>new Option(l.documentTitle,key(l))));if(leases.some(l=>key(l)===selected))select.value=selected;else if(leases.length===1)select.value=key(leases[0]);current=leases.find(l=>key(l)===select.value)||null;choose.hidden=leases.length<2; +function render(data){chapter=Number(root.dataset.chapterId);scene=Number(root.dataset.sceneId);packet=data;const old=current;const leases=(data.leases||[]).filter(l=>l.wordAvailable&&l.bookId===book&&Date.parse(l.expires)>Date.now());const originParams=new URLSearchParams(location.search);const originKey=originParams.get('wordInstanceId')+'/'+originParams.get('wordSessionId');const selected=explicitSelection?.key||select.value||originKey;select.replaceChildren(new Option('Choose a document',''),...leases.map(l=>new Option(l.documentTitle,key(l))));const missingSelection=!!explicitSelection&&!leases.some(l=>key(l)===explicitSelection.key);if(missingSelection){const missing=new Option(explicitSelection.title+' · disconnected',explicitSelection.key);missing.disabled=true;select.add(missing);select.value=explicitSelection.key;}else if(leases.some(l=>key(l)===selected))select.value=selected;else if(leases.length===1)select.value=key(leases[0]);current=leases.find(l=>key(l)===select.value)||null;choose.hidden=leases.length<2&&!missingSelection; if(old&&(!current||key(old)!==key(current)||old.revision!==current.revision||old.manuscriptId!==current.manuscriptId)&&busy){abort?.abort();message.textContent='Word document changed or disconnected. Navigation was not confirmed.';} if(syncPending&&(!current||syncPending.key!==key(current)||Date.now()-syncPending.started>120000||(syncPending.requestId&¤t.paragraphTransfer?.requestId===syncPending.requestId&&['accepted','needs-review','failed','cancelled'].includes(current.paragraphTransfer.state))))syncPending=null; const identity=current&&data.canonical?.manuscriptID===current.manuscriptId;const observed=current&&verified(current); -state.textContent=data.unavailable?'Word Companion status unavailable. Your saved work is retained.':!current?(leases.length>1?'Choose the correct Word manuscript.':(data.leases||[]).some(l=>l.wordAvailable)?'The open Word manuscript is for another book.':'Word Companion is not connected to this manuscript.'):!identity?'Word is connected, but this manuscript has not been verified.':`Manuscript: ${current.documentTitle}`; -position.textContent=observed?`Word is showing ${observed.chapterTitle||'the verified chapter'}${observed.sceneId&&observed.sceneTitle?' · '+observed.sceneTitle:''}. ${observed.chapterId!==chapter?(reviewing?'Your review selection is separate.':'Your working focus is separate.'):''}`:current?.wordSaved===false?'Word has unsaved changes. Current positions await verification; no save will be forced.':'Word position has not been verified.'; +state.textContent=data.unavailable?'Word Companion status unavailable. Your saved work is retained.':!current?(missingSelection?'Selected Word document is disconnected. Choose another document explicitly.':leases.length>1?'Choose the correct Word manuscript.':(data.leases||[]).some(l=>l.wordAvailable)?'The open Word manuscript is for another book.':'Word Companion is not connected to this manuscript.'):!identity?'Word is connected, but this manuscript has not been verified.':`Manuscript: ${current.documentTitle}`; +position.textContent=observed?`Word is showing ${observed.chapterTitle||'the verified chapter'}${observed.sceneId&&observed.sceneTitle?' · '+observed.sceneTitle:''}. ${observed.chapterId!==chapter?(reviewing?'Your review selection is separate.':'Your working focus is separate.'):''}`:current?.wordSaved===false?'Word has unsaved changes. Current positions await verification; no save will be forced.':current?.wordSaved===null?'Word position awaits a fresh observation. Check the intended document in Word; accepted text is retained.':'Word position has not been verified.'; let status=!identity?'Your latest changes have not yet been confirmed in PlotDirector.':current.chapterProgress?.state==='Needs review'||current.chapterIssue==='needs_review'?'Manuscript checking needs attention in Companion. Accepted content is retained.':current.paragraphTransfer?.state==='failed'?'Manuscript update failed. Accepted content is retained.':current.chapterProgress?.state==='Synchronised'&¤t.wordSaved===true?'The last manuscript check completed. Later edits may still be pending.':current.chapterProgress?.state?`${current.chapterProgress.state}: ${current.chapterProgress.message||'Latest changes are not yet confirmed.'}`:'Latest changes are not yet confirmed. Check synchronisation in Companion.'; if(data.canonical?.chapterAcceptedUtc)status+=' This chapter last accepted: '+new Date(data.canonical.chapterAcceptedUtc).toLocaleString()+'.';else if(data.canonical?.snapshotUtc)status+=' Accepted snapshot recorded: '+new Date(data.canonical.snapshotUtc).toLocaleString()+'.';freshness.textContent=status;const warning=document.querySelector('[data-review-word-warning]');if(warning)warning.textContent='Showing accepted text. '+(!current?state.textContent:current.wordSaved===false?'Word has unsaved changes; they are not shown here.':status); sync.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!(current.canChapterSync||current.canParagraphSync); @@ -29,7 +31,7 @@ for(const button of document.querySelectorAll('[data-ribbon-word]')){const origi const params=new URLSearchParams(location.search),origin=current&¶ms.get('wordInstanceId')===current.instanceId&¶ms.get('wordSessionId')===current.sessionId; adopt.hidden=reviewing||!(origin&&observed&&observed.chapterId!==chapter);if(!adopt.hidden){adopt.querySelector('[name=ChapterID]').value=observed.chapterId;adopt.querySelector('[name=SceneID]').value=observed.sceneId||'';adopt.querySelector('[data-word-origin]').textContent='Opened from verified Word chapter '+(observed.chapterTitle||'in this manuscript')+'. Your saved objective is unchanged.';} } -select.addEventListener('change',()=>render(packet)); +select.addEventListener('change',()=>{const lease=packet?.leases?.find(l=>key(l)===select.value);explicitSelection=lease?{key:key(lease),title:lease.documentTitle}:null;try{if(explicitSelection)sessionStorage.setItem(selectionKey,JSON.stringify(explicitSelection));else sessionStorage.removeItem(selectionKey);}catch{}render(packet);}); adopt.addEventListener('submit',async event=>{event.preventDefault();if(adopt.hidden||!window.PlotDirectorNarrativeFocus)return;await window.PlotDirectorNarrativeFocus.set({bookID:book,chapterID:Number(adopt.querySelector('[name=ChapterID]').value),sceneID:Number(adopt.querySelector('[name=SceneID]').value)||null});}); window.addEventListener('plotdirector:narrative-focus-changed',event=>{if(event.detail.bookID!==book||reviewing)return;applyNarrative(event);}); window.addEventListener('review:narrative-applied',event=>{if(reviewing&&event.detail.bookID===book)applyNarrative(event);});