diff --git a/Docs/WordCompanion/WindowsHandover/2026-11-12-v1.0.0.33-post-edit-synchronisation.md b/Docs/WordCompanion/WindowsHandover/2026-11-12-v1.0.0.33-post-edit-synchronisation.md new file mode 100644 index 00000000..e4486c22 --- /dev/null +++ b/Docs/WordCompanion/WindowsHandover/2026-11-12-v1.0.0.33-post-edit-synchronisation.md @@ -0,0 +1,30 @@ +# Word Companion 1.0.0.33 post-edit synchronisation + +Windows observed the regression in **1.0.0.32**, built from `d68314b83eb1a17a5e33e02feb2497fb814de32d`. The signed installer, installed binaries and established packaging gates had passed. Discovery (Development book 10152) initially verified all 48 chapters in approximately **16 seconds**, with working Writing Context, as reported by the author. The 1.0.0.31 baseline was **49.526 seconds**. The 5–10-second target remains unmet and this change addresses correctness. + +## Observed failure and Undo + +Word invalidated the current snapshot on edit, registered newer revisions, and reported the current Context as unsaved or unknown. The current revision showed zero chapter reads, fingerprints, submissions and server requests, with completion at -1. The legacy `awaiting-structure` string describes local boundary lookup. The chapter path uses saved-state presence and the accepted canonical mapping. + +The agent IPC log for session `d1d52eda-00d8-402b-bbf1-d8bc93cd931d` shows repeated `document status=ok` followed immediately by `adapter-result status=stale-revision` at 19:33 UTC. `TrayCoordinator.Exchange` called `Cancel` before updating the descriptor revision, so the outbound Word cancel carried the old revision. Word already cancels the local extraction when it registers a changed revision. The stale responses are evidence of that ordering issue. They do not establish a general queue deadlock. + +Two `tray-sync` frames at 19:37:20.729 and 19:37:28.148 UTC and one `tray-repair` frame at 19:38:10.742 UTC reached the agent with `status=ok`. That status acknowledged IPC receipt. Both commands could immediately call the existing server repair endpoint without first publishing fresh saved-state presence. The endpoint requires a saved, current-revision lease. The ribbon discarded progress when posting the request, and the agent held the outcome in text that was not surfaced as ribbon progress. An HTTP conflict could deserialize as a repair reply with an empty permit. The specific HTTP response to each historical click is unavailable. + +There were **zero chapter frames** from 19:33:18 to 19:40:27 UTC. The first new chapter began at 19:40:29.392 UTC and the log records **48 new successful chapter-end frames** after activity resumed. The live Companion panel subsequently reported **48 calculated, 48 matches, 0 mismatches, 48 reuses, 2 reuse requests, 0 individual submissions, 0 reconciliations**, and a verified scene at cursor 706307. This was genuine fresh verification with matching fingerprints. No edited-state fingerprint was calculated during the stall, so there is no evidence of a mismatch being ignored or of missing structural evidence at that point. The captured evidence does not distinguish Undo restoring the saved flag from a later saved observation. The manuscript was saved when subsequently inspected read-only. + +The recovered pass recorded recognition/Context/completion values of 892386.2/895560.3/912001.4 ms relative to the original document registration. The intervals from the new recognition measurement are **3.174 s to the first verified scene** and **19.615 s to completion**. The process totals include both passes and must not be assigned exclusively to either. Server round trips for the recovered pass totalled **1,926.1 ms**, with **47 live-text / 1 XML** reads and **4 chapter-protocol requests**. The process recorded **1,757 plain collection setups**, **1,078 UI batches**, and **0 COM busy/errors** across both passes. At capture, Word reported **1 Word work item and 1 IPC item queued** while Companion showed completed verification. + +## Corrected command lifecycle + +- Word keeps the existing edit detection, cancels local chapter work on revision change, and registers the new revision. The agent retires the old work and queued commands without echoing an obsolete cancel. Late chapter replies remain scoped to the current command and revision. Before requesting prose reconciliation, the agent rechecks that the work and command are current and Word still reports saved. +- Synchronise and Repair return immediate ribbon feedback. An unsaved document shows **Save to synchronise** with retry instructions. This is an existing technical requirement in the live reader and server. Commands on a saved revision wait for a matching server presence reply before requesting the existing permit. Duplicate clicks coalesce, and Synchronise joins an explicitly authorised cycle already running. A refusal or undelivered permit surfaces an actionable status. Repair starts a fresh work instance, preserving accepted checkpoints and isolating old asynchronous replies. +- Existing automatic verification follows a fresh saved observation. OnSave may reconcile changed prose under existing authority, while Manual requires the explicit permit. There is no unsaved quiet-period reconciliation path in this release. No per-keystroke verification was added. +- Troubleshooting records the last ribbon command and outcome, pending restart and permit, verification and Word-read state, latest interruption, and the Word queue head, age and time since the last scheduler wake. Batch reuse, live identity and floating-anchor validation, scheduler limits, and the command polling optimisation remain in place. + +## Qualification + +The Windows Release solution build passed with zero warnings or errors. The focused executable suites passed **363 native**, **66 chapter/structural**, and **54 paragraph/workflow** checks. The disposable protocol fixture covers unsaved command feedback, repeated clicks, server conflict feedback, a fresh saved-revision repair permit, joining active work, and retiring an old command after another revision. Existing isolated handshake cases cover unchanged reuse, single-chapter selective reconciliation, Context before completion, structural geometry fallback, and interruption during final acknowledgement. These checks did not operate Word or modify Development. + +Required upgrade is **1.0.0.33** (MSI **1.0.33**) with the existing upgrade family. The implementation and qualification fixture are identified by the shared-branch source commit that introduces this handover. Record the exact signed package source and hashes with the Windows build results. + +After explicit installation approval, use an authorised disposable manuscript and Development book. Establish a verified baseline, edit one chapter, confirm the save-required status, save, and exercise Synchronise and Repair separately. Check duplicate clicks, an active cycle, another edit or save during verification, and interruption. Capture the new queue and command diagnostics, 47 unchanged checkpoint reuses, exactly one reconciled chapter, preserved paragraph/scene identities and current and later Writing Context. Include a real Word structural case with a floating-picture anchor. Perform one unchanged reopen to check that the earlier reopening performance is preserved. The protected Discovery document and checkpoints were not changed by this investigation. No Development or Production service or database changes are needed. diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs index b6aa5bf9..7597d8a7 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs @@ -27,6 +27,10 @@ public sealed partial class TrayCoordinator { if (cloud.Status().Health?.Authentication != "verified") return new() { State = "Sign-in required", Message = "Sign in to resume synchronisation. The manuscript's saved book association is retained." }; + if (doc.RibbonNotice != null) + return doc.RibbonNotice; + if (doc.Book>0 && doc.WordSaved != true && ChapterCapable(doc.Instance)) + return new() { State = "Save required", Message = "Save the manuscript in Word to verify the edited chapters." }; if (!chapterWork.TryGetValue(doc.Session, out var work) || !CurrentChapterWork(doc, work)) return doc.ChapterProgress; @@ -45,8 +49,10 @@ public sealed partial class TrayCoordinator { lock(gate) { - if(!chapterWork.TryGetValue(session,out var w))return "Chapter timings: awaiting recognised saved document."; - return $"Current Context: {ChapterCursorEvidence.State(documents[session],w.Completion?.State=="Synchronised"&&w.Checked.Count==w.Manifest?.Chapters.Length,w.Checked.Values.Any(p=>documents[session].Cursor>=p.Start&&documents[session].Cursorc.DurableAccepted)??0}; calculated/match/mismatch/missing/incompatible={w.Calculated}/{w.Matching}/{w.Mismatching}/{w.Missing}/{w.Incompatible}; reused={w.Reused}, pending={w.PendingReuse.Count}, reconciled={w.Reconciled}, reuseRequests={w.ReuseRequests}, requests={w.Requests}, bytes={w.RequestBytes}, reuse server read/process/validation/persistence ms={w.ReuseReadMs:F1}/{w.ReuseProcessingMs:F1}/{w.ReuseValidationMs:F1}/{w.ReusePersistenceMs:F1}. Negative timing means not observed."; + if(!documents.TryGetValue(session,out var doc))return "Chapter timings: awaiting recognised saved document."; + var lifecycle=$"Last ribbon command: {doc.LastRibbonCommand} · outcome: {doc.LastRibbonOutcome} · pending restart: {doc.PendingRibbonCommand} · permit pending: {doc.RibbonPermit!=Guid.Empty}. Last interruption: {doc.LastChapterInterruption}."; + if(!chapterWork.TryGetValue(session,out var w))return lifecycle+" Chapter timings: awaiting recognised saved document."; + return lifecycle+$" Verification: {(w.Busy?"running":w.Finished?"finished":"idle")}, Word read pending: {w.Command!=Guid.Empty}. Current Context: {ChapterCursorEvidence.State(documents[session],w.Completion?.State=="Synchronised"&&w.Checked.Count==w.Manifest?.Chapters.Length,w.Checked.Values.Any(p=>documents[session].Cursor>=p.Start&&documents[session].Cursorc.DurableAccepted)??0}; calculated/match/mismatch/missing/incompatible={w.Calculated}/{w.Matching}/{w.Mismatching}/{w.Missing}/{w.Incompatible}; reused={w.Reused}, pending={w.PendingReuse.Count}, reconciled={w.Reconciled}, reuseRequests={w.ReuseRequests}, requests={w.Requests}, bytes={w.RequestBytes}, reuse server read/process/validation/persistence ms={w.ReuseReadMs:F1}/{w.ReuseProcessingMs:F1}/{w.ReuseValidationMs:F1}/{w.ReusePersistenceMs:F1}. Negative timing means not observed."; } } @@ -57,6 +63,7 @@ public sealed partial class TrayCoordinator work.Command = Guid.Empty; work.FailedRevision = doc.Revision; doc.Status = reason; + doc.LastChapterInterruption=reason; doc.LastPresenceKey = ""; Queue(doc, new() { Kind = "chapter-cancel" }); } @@ -76,16 +83,57 @@ public sealed partial class TrayCoordinator work.Manifest = null; work.RetryAfter = DateTime.UtcNow.AddSeconds(15); doc.Status = reason; + doc.LastChapterInterruption=reason; } private bool ChapterCapable(Guid instance){lock(gate)return chapterInstances.Contains(instance);} private readonly HashSet ribbonRequests=[]; + private void ReceiveChapterRibbonRequest(TrayDocument doc,string kind) + { + doc.LastRibbonCommand=kind; + if(doc.PendingRibbonCommand!=""||ribbonRequests.Contains(doc.Session)||doc.RibbonPermit!=Guid.Empty){doc.LastRibbonOutcome="Already awaiting the current verification request.";return;} + if(doc.Capture!=null){SetRibbonOutcome(doc,"Needs review","Wait for the current manuscript transfer to finish, then retry.");return;} + if(doc.WordSaved==false){SetRibbonOutcome(doc,"Save required","Save the manuscript in Word, then retry "+(kind=="tray-repair"?"Repair Synchronisation.":"Synchronise."));return;} + if(kind=="tray-sync"&&chapterWork.TryGetValue(doc.Session,out var work)&&CurrentChapterWork(doc,work)&&work.Busy&&work.Operation!=Guid.Empty) + {SetRibbonOutcome(doc,"Checking","Synchronisation is already running.");doc.RibbonNotice=null;return;} + doc.PendingRibbonCommand=kind; + doc.RibbonRequestedUtc=DateTime.UtcNow; + SetRibbonOutcome(doc,"Checking","Waiting for the current saved Word revision to be confirmed."); + doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue; + } + private static void SetRibbonOutcome(TrayDocument doc,string state,string message) + { + doc.LastRibbonOutcome=message; + doc.RibbonNotice=new(){State=state,Message=message}; + } + private void DispatchChapterRibbonRequest(TrayDocument doc,NativePresence reply) + { + if(doc.PendingRibbonCommand=="")return; + if(!reply.ChapterSyncSupported||doc.Book<=0||doc.Capture!=null||doc.WordSaved==false|| + DateTime.UtcNow-doc.RibbonRequestedUtc>TimeSpan.FromSeconds(15)) + { + doc.PendingRibbonCommand=""; + SetRibbonOutcome(doc,doc.WordSaved==false?"Save required":"Needs review",doc.WordSaved==false + ?"Save the manuscript in Word, then retry.":"The saved document connection is not ready. Check Companion and retry."); + return; + } + if(doc.WordSaved!=true||reply.WordSaved!=true||reply.Revision!=doc.Revision)return; + if(ribbonRequests.Count>=32||!ribbonRequests.Add(doc.Session))return; + doc.PendingRibbonCommand=""; + _=RequestChapterFromRibbon(doc,doc.Revision); + } private async Task RequestChapterFromRibbon(TrayDocument doc,long revision) { - int book;Guid context,instance,session; - lock(gate){if(ribbonRequests.Count>=32||!ribbonRequests.Add(doc.Session))return;book=doc.Book;context=doc.Authentication;instance=doc.Instance;session=doc.Session;} - try{if(!cloud.Allows(context,book))throw new InvalidOperationException("Connect and select an authorised book first.");var reply=await cloud.RequestChapterRepair(book,new(){InstanceId=instance,SessionId=session,WordRevision=revision},context);lock(gate)if(documents.GetValueOrDefault(session)==doc&&doc.Revision==revision&&doc.Authentication==context){doc.Status=reply.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}} - catch(Exception e)when(NetworkFailure(e)){lock(gate)if(documents.GetValueOrDefault(session)==doc)doc.Status="Chapter request was not accepted: "+e.Message;} + var book=doc.Book;var context=doc.Authentication;var instance=doc.Instance;var session=doc.Session;var requested=doc.RibbonRequestedUtc; + bool Current()=>documents.GetValueOrDefault(session)==doc&&doc.Revision==revision&&doc.Book==book&&doc.Authentication==context&&doc.RibbonRequestedUtc==requested; + try + { + if(!cloud.Allows(context,book))throw new InvalidOperationException("Connect and select an authorised book first."); + var reply=await cloud.RequestChapterRepair(book,new(){InstanceId=instance,SessionId=session,WordRevision=revision},context); + if(reply.OperationId==Guid.Empty)throw new InvalidOperationException(string.IsNullOrWhiteSpace(reply.Message)?"Check the saved manuscript connection and retry.":reply.Message); + lock(gate)if(Current()&&GetChapterWork(doc).Operation!=reply.OperationId){doc.RibbonPermit=reply.OperationId;doc.RibbonRequestedUtc=DateTime.UtcNow;SetRibbonOutcome(doc,"Checking",reply.Message);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;} + } + catch(Exception e)when(NetworkFailure(e)){lock(gate)if(Current())SetRibbonOutcome(doc,"Needs review","Chapter request was not accepted: "+e.Message);} finally{lock(gate)ribbonRequests.Remove(session);} } private bool IsChapterCommand(TrayDocument doc,Guid id)=>chapterWork.TryGetValue(doc.Session,out var work)&&id!=Guid.Empty&&work.Command==id; @@ -93,7 +141,12 @@ public sealed partial class TrayCoordinator private void BeginChapterRepair(TrayDocument doc,Guid operation) { if(!ChapterCapable(doc.Instance))return; - var work=GetChapterWork(doc);work.Completion=null;work.Operation=operation;work.FailedRevision=-1;work.Attempts=0;work.Retries=0;work.ReviewReason="";work.Manifest=null;work.PendingReuse.Clear();work.ReuseFinishing=false;work.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.Wrapped=false;work.FirstStart=-1;work.Finished=false;work.Command=Guid.Empty;work.Busy=false; + doc.RibbonPermit=Guid.Empty;doc.RibbonNotice=null; + doc.LastRibbonOutcome="Accepted: verification restarted with an explicit repair permit."; + if(commands.TryGetValue(doc.Instance,out var queue))commands[doc.Instance]=new(queue.Where(c=>c.SessionId!=doc.Session||c.Kind!="chapter-check")); + Queue(doc,new(){Kind="chapter-cancel"}); + chapterWork.Remove(doc.Session); + var work=GetChapterWork(doc);work.Operation=operation; doc.Status="Repairing existing chapter mappings; accepted scenes and author decisions are retained.";work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work); } private ChapterWork GetChapterWork(TrayDocument doc) @@ -104,6 +157,10 @@ public sealed partial class TrayCoordinator { if(!ChapterCapable(doc.Instance))return; lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc)return;var work=GetChapterWork(doc);work.Supported=reply.ChapterSyncSupported;if(work.ContextMs<0&&ChapterCursorEvidence.Ready(doc))work.ContextMs=work.RecognitionMs+work.Elapsed.Elapsed.TotalMilliseconds; + if(doc.RibbonPermit!=Guid.Empty&&reply.Navigation?.Id!=doc.RibbonPermit&&DateTime.UtcNow-doc.RibbonRequestedUtc>TimeSpan.FromSeconds(15)) + {doc.RibbonPermit=Guid.Empty;SetRibbonOutcome(doc,"Needs review","The repair permit was not delivered. Check the connection and retry.");} + DispatchChapterRibbonRequest(doc,reply); + if(doc.PendingRibbonCommand!=""||doc.RibbonPermit!=Guid.Empty||ribbonRequests.Contains(doc.Session))return; if(work.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Completion=null;work.Manifest=null;work.PendingReuse.Clear();work.ReuseFinishing=false;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;} if(DateTime.UtcNowwork.Start&&doc.Active&&doc.Cursor!=work.CursorWhenQueued&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor=work.End)){QueueChapter(doc,work,doc.Cursor);return;}if(DateTime.UtcNow-work.Started>TimeSpan.FromMinutes(2)){StopChapterWork(doc,work,"Chapter validation timed out. Accepted checkpoints are retained. Check the connection before retrying.");}return;} @@ -225,7 +282,15 @@ public sealed partial class TrayCoordinator CountChapterRequest(work,proof); var validation=System.Diagnostics.Stopwatch.StartNew();work.Submissions++; var result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication); - if(!result.Accepted&&result.State=="Changed"&&result.AllowText){proof.Reconcile=true;proof.Paragraphs=rows;work.Submissions++;CountChapterRequest(work,proof);result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);} + if(!result.Accepted&&result.State=="Changed"&&result.AllowText) + { + lock(gate) + { + if(!CurrentChapterWork(doc,work)||work.Command!=command||doc.WordSaved!=true)return; + proof.Reconcile=true;proof.Paragraphs=rows;work.Submissions++;CountChapterRequest(work,proof); + } + result=await cloud.ValidateChapter(work.Book,proof,work.Context); + } lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.ServerMs+=validation.Elapsed.TotalMilliseconds;if(result.Accepted&&proof.Reconcile&&proof.Paragraphs.Any(p=>p.Text!=null))work.Reconciled++;work.Busy=false; if(result.Accepted){work.Retries=0;work.Checked[chapter.ChapterId]=(start,end);manifest.Revision=result.Revision;if(result.State=="Needs review")work.Reviewed.Add(chapter.ChapterId);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status=$"{work.Checked.Count}/{manifest.Chapters.Length} chapters accepted · "+result.Message;AdvanceChapter(doc,work);} else{work.Reviewed.Add(chapter.ChapterId);work.ReviewReason=result.Message;doc.Status=result.Message+" Accepted chapter repairs are retained.";AdvanceChapter(doc,work);} diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs index 68873c86..7d9f904f 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs @@ -26,7 +26,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway foreach(var descriptor in request.Documents){ if(sessions.Descriptor(instance,descriptor.SessionId)==null)continue; if(!documents.TryGetValue(descriptor.SessionId,out var d))documents[descriptor.SessionId]=d=new(){Session=descriptor.SessionId,Instance=instance}; - if(d.Revision!=descriptor.Revision){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);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.";d.WordSaved=null;d.Chapters=[];d.FailedChapters.Clear();d.Words=null;d.ChapterId=null;d.SceneId=null;d.ChapterTitle="";d.SceneTitle="";d.LastPresenceKey="";d.Status="Document changed. Detect chapters to refresh this snapshot.";} if(reconnectBindings.Remove((instance,descriptor.SessionId),out var binding)&&binding.Expires>DateTime.UtcNow&&binding.Manuscript==descriptor.ManuscriptId&&binding.Authentication==cloud.Status().AuthenticationContext){d.Book=binding.Book;d.Authentication=binding.Authentication;} d.Revision=descriptor.Revision;d.Manuscript=descriptor.ManuscriptId;d.Title=descriptor.Title;d.RememberedBook=descriptor.RememberedBook;d.AssociationSite=descriptor.AssociationSite;d.Observed=DateTime.UtcNow; } @@ -36,9 +36,9 @@ 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(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(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}} + if(request.Kind=="selection"){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="";}} ChapterFrame(doc,request,answer); - if(request.Kind is "tray-sync" or "tray-repair")_ = RequestChapterFromRibbon(doc,request.Revision); + if(request.Kind is "tray-sync" or "tray-repair")ReceiveChapterRibbonRequest(doc,request.Kind); if ((request.Kind is "tray-context" or "tray-intent") && answer.Status == "ok") _ = OpenRibbonWorkspace(doc.Session, request.Revision, request.Kind == "tray-context" ? "context" : "intent"); if (request.Kind == "tray-workspace" && answer.Status == "ok") @@ -55,14 +55,14 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway doc.AssociationNeedsSave=request.OperationMessage=="association-written"; doc.AssociationNotice=doc.AssociationNeedsSave?"Book remembered in Word. Save the document to keep this association.":request.OperationMessage=="ok"?"Update the Word add-in to confirm the association was written.":request.OperationMessage; } - else if(request.Kind=="adapter-result"&&!IsChapterCommand(doc,request.SnapshotId)&&request.OperationMessage!="ok"&&request.OperationMessage!="association-written"){doc.Status=request.OperationMessage;Cancel(doc);} + else if(request.Kind=="adapter-result"&&!IsChapterCommand(doc,request.SnapshotId)&&!request.Action.StartsWith("chapter-",StringComparison.Ordinal)&&request.OperationMessage!="ok"&&request.OperationMessage!="association-written"){doc.Status=request.OperationMessage;Cancel(doc);} if(request.Kind=="ai-cancel"){Cancel(doc);doc.Status="Extraction cancelled or document changed. Successful server suggestions are retained.";} if(request.Kind=="metrics")doc.WordDiagnostics=request.OperationMessage.Length<=6000?request.OperationMessage:"Diagnostics size exceeded"; if(request.Kind=="ai-fragment")doc.Progress=answer.Progress; if(request.Kind.StartsWith("ai-",StringComparison.Ordinal)&&answer.Status!="ok"){doc.Status="Chapter could not be read: "+answer.Status;Cancel(doc);} } } - if(documents.TryGetValue(request.SessionId,out var activeDocument)&&ChapterCapable(instance)&&request.Kind is "selection" or "metrics"){ + if(documents.TryGetValue(request.SessionId,out var activeDocument)&&ChapterCapable(instance)&&request.Kind is "selection" or "metrics" or "tray-sync" or "tray-repair"){ answer.ChapterStatusProvided=true;answer.BookId=activeDocument.Book;answer.BookTitle=cloud.Status().Books.FirstOrDefault(b=>b.BookId==activeDocument.Book)?.BookTitle??"";answer.ChapterTitle=activeDocument.ChapterTitle;answer.SceneTitle=activeDocument.SceneTitle;answer.ChapterProgress=VisibleChapterProgress(activeDocument); } if(commands.TryGetValue(instance,out var queue)&&queue.Count>0)answer.Command=queue.Dequeue(); @@ -106,7 +106,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway 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){CancelChapterWork(doc);doc.RetryCapture=null;foreach(var request in maintenance.Where(p=>p.Value.Session==doc.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(request);doc.MaintenanceReport="Stopped: superseded by a document or account change. Inspect before retrying cleanup.";}if(doc.Capture!=null)_=cloud.FailCapture(doc.Capture.RequestId,doc.Authentication);doc.Capture=null;doc.CaptureFragments.Clear();if(doc.Job!=Guid.Empty)ai.Clear(doc.Session);doc.Job=Guid.Empty;doc.Pending.Clear();if(commands.TryGetValue(doc.Instance,out var q))commands[doc.Instance]=new(q.Where(c=>c.SessionId!=doc.Session));Queue(doc,new(){Kind="cancel"});} + private void Cancel(TrayDocument doc,bool notifyWord=true){CancelChapterWork(doc);doc.PendingRibbonCommand="";doc.RibbonPermit=Guid.Empty;doc.RibbonRequestedUtc=default;doc.RibbonNotice=null;doc.RetryCapture=null;foreach(var request in maintenance.Where(p=>p.Value.Session==doc.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(request);doc.MaintenanceReport="Stopped: superseded by a document or account change. Inspect before retrying cleanup.";}if(doc.Capture!=null)_=cloud.FailCapture(doc.Capture.RequestId,doc.Authentication);doc.Capture=null;doc.CaptureFragments.Clear();if(doc.Job!=Guid.Empty)ai.Clear(doc.Session);doc.Job=Guid.Empty;doc.Pending.Clear();if(commands.TryGetValue(doc.Instance,out var q))commands[doc.Instance]=new(q.Where(c=>c.SessionId!=doc.Session));if(notifyWord)Queue(doc,new(){Kind="cancel"});} public void Navigate(Guid session,int start){lock(gate)if(documents.TryGetValue(session,out var doc))Queue(doc,new(){Kind="navigate",Chapter=new(){Start=start}});} public async Task Tick(CancellationToken cancellation) { @@ -196,6 +196,8 @@ 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="Link this manuscript to a book, then use Import manuscript in PlotDirector.",ReviewPath=""; internal ManuscriptCapture? RetryCapture;internal Guid RetryAuthentication;internal int RetryBook; public long CaptureBaseRevision;public string CaptureBaseHash="";public ManuscriptCapture? Capture;public List CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision; + internal string LastRibbonCommand="",LastRibbonOutcome="",PendingRibbonCommand="",LastChapterInterruption=""; + 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 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; diff --git a/PlotDirector.NativeCompanion/Client/AgentLink.cs b/PlotDirector.NativeCompanion/Client/AgentLink.cs index ef952315..0fdbd983 100644 --- a/PlotDirector.NativeCompanion/Client/AgentLink.cs +++ b/PlotDirector.NativeCompanion/Client/AgentLink.cs @@ -102,6 +102,7 @@ public sealed class AgentLink : IDisposable foreach(var wait in chapterWaits.Values)wait.ExchangeMs+=exchangeWatch.Elapsed.TotalMilliseconds; if(response.Command!=null)EndChapterWait(response.Command.SessionId,"next-command"); if(response.ChapterStatusProvided&&response.ChapterProgress?.State is "Synchronised" or "Needs review")EndChapterWait(response.SessionId,"terminal-status"); + if(message.Kind is "tray-sync" or "tray-repair")response.Action=message.Kind; Received?.Invoke(response); } } diff --git a/PlotDirector.NativeCompanion/Client/WordAccessScheduler.cs b/PlotDirector.NativeCompanion/Client/WordAccessScheduler.cs index d58c3089..a9a87eb1 100644 --- a/PlotDirector.NativeCompanion/Client/WordAccessScheduler.cs +++ b/PlotDirector.NativeCompanion/Client/WordAccessScheduler.cs @@ -20,6 +20,18 @@ public sealed class WordAccessScheduler private double QuietAt(double time)=>quietCompleted+Math.Max(0,Math.Min(time,quietUntil)-quietStart); private double ActiveAt(double time)=>activeMs+(running?time-actionStarted:0); public bool HasRunnableChapterWork{get{AssertOwner();return now()>=quietUntil&&work.Keys.Any(k=>k.StartsWith("chapter:",StringComparison.Ordinal));}} + private double? lastWake; + public string HeadDescription + { + get + { + AssertOwner(); + var time=now(); + var key=work.ContainsKey("selection")?"selection":order.Count>0?order.Peek():null; + var head=key==null?"empty":$"{key.Split(':')[0]}, age {Math.Max(0,time-work[key].Queued):F0} ms"; + return head+(lastWake.HasValue?$"; last scheduler wake {Math.Max(0,time-lastWake.Value):F0} ms ago":"; scheduler has not woken"); + } + } public const int Capacity=64;public int Depth=>work.Count;public long Superseded{get;private set;} public event Action? Measured;public event Action? Waited;public event Action? Failed; private void AssertOwner(){if(Environment.CurrentManagedThreadId!=ownerThread)throw new InvalidOperationException("Word work must stay on its owning UI thread.");} @@ -33,7 +45,7 @@ public sealed class WordAccessScheduler public void PrioritizeAuthor(TimeSpan period){AssertOwner();var time=now();quietCompleted=QuietAt(time);quietStart=time;quietUntil=time+period.TotalMilliseconds;} public bool Pump() { - AssertOwner();if(running||now()1.0.0.32 +1.0.0.33 diff --git a/PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs b/PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs index 9a9ec956..475a6b1c 100644 --- a/PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs +++ b/PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs @@ -9,6 +9,7 @@ internal static class ChapterHandshakeTests private static void Check(bool value,string name){if(!value)throw new Exception(name);Console.WriteLine("PASS "+name);} public static async Task Run() { + await RibbonLifecycle(); foreach(var scenario in new[]{(Edited:Array.Empty(),Missing:-1,Geometry:-1),(Edited:new[]{17},Missing:-1,Geometry:-1),(Edited:new[]{7,22,47},Missing:-1,Geometry:-1),(Edited:Array.Empty(),Missing:31,Geometry:-1),(Edited:Array.Empty(),Missing:-1,Geometry:47),(Edited:Array.Empty(),Missing:-2,Geometry:-1)}) { var changed=scenario.Edited;var fallback=(scenario.Missing>=0?1:0)+(scenario.Geometry>=0?1:0);var handler=new Handler(changed,scenario.Missing,scenario.Geometry);using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://handshake.test/");await Until(()=>cloud.Status().Books.Any());await cloud.CheckConnection(); @@ -45,12 +46,52 @@ internal static class ChapterHandshakeTests finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}} } } + private static async Task RibbonLifecycle() + { + var handler=new Handler([17],-1,-1); + using var cloud=new CloudGateway(handler,_=>{}); + cloud.Connect("https://handshake.test/"); + await Until(()=>cloud.Status().Books.Any()); + await cloud.CheckConnection(); + var sessions=new SessionManager(); + using var ai=new ChapterAiWork(cloud); + var tray=new TrayCoordinator(sessions,cloud,ai); + var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid();long sequence=0,revision=1; + sessions.Attach(instance,lease,chapters:true,liveChapterText:true);tray.Attach(instance,lease,chapters:true); + Message Send(Message m){m.WordInstanceId=instance;m.SessionId=session;m.Revision=revision;m.Sequence=++sequence;return tray.Exchange(instance,m,sessions.Apply(lease,m),lease);} + Message Register()=>Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=revision,Title="Disposable edit fixture.docx"}]}); + Register();tray.SelectBook(session,3,false);Send(new(){Kind="active"}); + Send(new(){Kind="selection",WordSaved=false}); + Check(Send(new(){Kind="tray-sync"}).ChapterProgress?.State=="Save required","Synchronise on an unsaved edit shows the save requirement"); + Check(Send(new(){Kind="tray-repair"}).ChapterProgress?.Message.Contains("Repair Synchronisation")==true&&handler.RepairRequests==0,"Repair reports its saved-state refusal without submitting stale evidence"); + revision++;Check(Register().Command==null,"Revision change clears old commands without emitting a stale cancel"); + Send(new(){Kind="tray-sync"});Send(new(){Kind="tray-sync"}); + using var stop=new CancellationTokenSource(); + var heartbeats=tray.Heartbeat(stop.Token); + try + { + Send(new(){Kind="selection",WordSaved=true}); + await Until(()=>tray.ChapterDiagnostics(session).Contains("Fixture repair refused")); + Check(handler.RepairRequests==1&&tray.ChapterProgressForDisplay(session)?.State=="Needs review","Repeated clicks coalesce and an HTTP repair refusal reaches the ribbon"); + Send(new(){Kind="tray-repair"}); + AdapterCommand? command=null; + await Until(()=>{var reply=Send(new(){Kind="selection",WordSaved=true});if(reply.Command?.Kind=="chapter-check")command=reply.Command;return command!=null;}); + Check(handler.RepairRequests==2&&command!.Revision==revision&&command.OperationId!=Guid.Empty,"Repair starts verification against the freshly confirmed saved revision"); + Send(new(){Kind="tray-sync"}); + Check(tray.ChapterDiagnostics(session).Contains("already running")&&handler.RepairRequests==2,"Synchronise joins an active explicitly authorised verification"); + revision++;Register(); + Check(Send(new(){Kind="chapter-end",Revision=revision,SnapshotId=command!.Id}).Command==null,"Further edits retire the old chapter command"); + Check(tray.ChapterDiagnostics(session).Contains("Document revision changed"),"Interrupted verification reports the revision change"); + } + finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}} + } private static async Task Until(Func ready){for(var n=0;n<3000;n++){if(ready())return;await Task.Delay(5);}throw new Exception("Handshake fixture timed out");} private sealed class Handler:HttpMessageHandler { public readonly Guid Manuscript=Guid.NewGuid();public readonly string[] Current;public readonly int[] Starts;private readonly string[] hashes;private readonly int missing,geometry;private long revision=1; public readonly TaskCompletionSource ReleaseSecond=new(TaskCreationOptions.RunContinuationsAsynchronously); public int ReuseRequests,Reused,AcceptRequests,Reconciled,Finishes;public long Bytes;private bool currentReady; + public int RepairRequests;private AdapterCommand? repair; public Handler(int[] changed,int missing,int geometry) { this.missing=missing;this.geometry=geometry; @@ -62,7 +103,15 @@ internal static class ChapterHandshakeTests { var path=request.RequestUri!.AbsolutePath;HttpResponseMessage Json(object value)=>new(HttpStatusCode.OK){Content=JsonContent.Create(value)}; if(path.EndsWith("/pair"))return Json(new{code="00112233445566778899AABB"});if(path.EndsWith("/token"))return Json(new{accessToken="fixture"});if(path.EndsWith("/books"))return Json(new[]{new{bookId=3,title="Synthetic book"}});if(path.EndsWith("/connection"))return Json(new{state="Connected",authentication="verified",server="online",expiresUtc=DateTime.UtcNow.AddHours(4)}); - if(path.EndsWith("/presence")){var p=(await request.Content!.ReadFromJsonAsync(cancellation))!;p.ChapterSyncSupported=true;p.ParagraphRevision=revision;if(currentReady){p.ChapterId=1;p.SceneId=10;p.ChapterTitle="Chapter 0";p.SceneTitle="Verified scene";}return Json(p);} + if(path.EndsWith("/presence")){var p=(await request.Content!.ReadFromJsonAsync(cancellation))!;p.ChapterSyncSupported=true;p.ParagraphRevision=revision;p.Navigation=Interlocked.Exchange(ref repair,null);if(currentReady){p.ChapterId=1;p.SceneId=10;p.ChapterTitle="Chapter 0";p.SceneTitle="Verified scene";}return Json(p);} + if(path.EndsWith("/repair")) + { + if(++RepairRequests==1)return new(HttpStatusCode.Conflict){Content=JsonContent.Create(new{message="Fixture repair refused."})}; + var target=(await request.Content!.ReadFromJsonAsync(cancellation))!; + var operation=Guid.NewGuid(); + repair=new(){Id=operation,Kind="chapter-repair",SessionId=target.SessionId,Revision=target.WordRevision}; + return Json(new ChapterRepairRequested{OperationId=operation,Message="Fixture repair accepted."}); + } if(path.EndsWith("/chapter-sync"))return Json(new ChapterManifest{CheckpointReuseSupported=true,NativePositionsSupported=true,BookId=3,Mode="OnSave",ManuscriptId=Manuscript,Revision=revision,Chapters=Enumerable.Range(0,48).Select(c=>new ChapterManifestItem{ChapterId=c+1,DurableAccepted=c!=missing,PositionHash=c==geometry?new string('A',64):"",Algorithm=ChapterFingerprint.Version,HeadingNativeId=(c*2+1).ToString("X8"),ContentHash=hashes[c],IdentityHash=ChapterFingerprint.Identity([new(){NativeId=(c*2+1).ToString("X8"),Length=($"Chapter {c}\r").Length,Outline=1},new(){NativeId=(c*2+2).ToString("X8"),Length=Current[c].Length-($"Chapter {c}\r").Length,Outline=10}]),NextHeadingId=c==47?"":((c+1)*2+1).ToString("X8"),Start=Starts[c],End=Starts[c]+Current[c].Length,ParagraphCount=2}).ToArray()}); if(path.EndsWith("/reuse")){var data=await request.Content!.ReadAsByteArrayAsync(cancellation);Bytes+=data.Length;var batch=JsonSerializer.Deserialize(data,new JsonSerializerOptions(JsonSerializerDefaults.Web))!;if(batch.Chapters.Any(p=>p.Paragraphs.Any(r=>r.Text!=null)))throw new Exception("Reuse leaked prose");ReuseRequests++;if(missing==-2&&ReuseRequests==2)await ReleaseSecond.Task.WaitAsync(cancellation);Reused+=batch.Chapters.Length;if(batch.Chapters.Any(p=>p.ChapterId==1))currentReady=true;return Json(new ChapterReuseReply{ChapterIds=batch.Chapters.Select(p=>p.ChapterId).ToArray(),Revision=revision});} if(path.EndsWith("/validate")){var data=await request.Content!.ReadAsByteArrayAsync(cancellation);Bytes+=data.Length;AcceptRequests++;var p=JsonSerializer.Deserialize(data,new JsonSerializerOptions(JsonSerializerDefaults.Web))!;if(p.ContentHash==hashes[p.ChapterId-1])return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",Revision=revision,ChapterId=p.ChapterId});if(p.Paragraphs.All(r=>r.Text==null))return Json(new ChapterSyncReply{State="Changed",AllowText=true,Revision=revision,ChapterId=p.ChapterId});Reconciled++;hashes[p.ChapterId-1]=p.ContentHash;return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",Revision=++revision,ChapterId=p.ChapterId});} diff --git a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs index b37260b5..8027c94c 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.32")] -[assembly: AssemblyFileVersion("1.0.0.32")] +[assembly: AssemblyVersion("1.0.0.33")] +[assembly: AssemblyFileVersion("1.0.0.33")] [assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs index 4f726399..b5dbe590 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs @@ -66,6 +66,7 @@ namespace PlotDirector.WordAddIn + "\nWord navigation executions: " + navigationExecutions + " · last command: " + lastNavigationId + "\nOpen sessions: " + documents.Count + "\nIPC queued: " + link.QueueDepth + "\nWord work queued: " + scheduler.Depth + + "\nWord queue head: " + scheduler.HeadDescription + "\nAgent startup: " + AgentProcess.LaunchStatus + "\nMain document words: " + WordCountSummary + "\nLast UI batch ms: " + lastBatchMs.ToString("F2") + "\nMax recorded COM call ms: " + (operationTimes.Count == 0 ? 0 : operationTimes.Max()).ToString("F2") @@ -100,6 +101,9 @@ namespace PlotDirector.WordAddIn link.Received += message => { if(message.Status=="ready")PostToUi(()=>{var capabilities=(message.Capabilities??"").Split(',');traySupported=capabilities.Contains(ProtocolVersion.TrayCapability);liveChapterTextSupported=capabilities.Contains(ProtocolVersion.LiveChapterTextCapability);nativeChapterTextSupported=capabilities.Contains(ProtocolVersion.NativeChapterTextCapability);nativeChapterPositionsSupported=capabilities.Contains(ProtocolVersion.NativeChapterPositionsCapability);}); if(message.ChapterStatusProvided&&message.SessionId!=Guid.Empty)PostToUi(()=>ReceiveChapterStatus(message)); + if((message.Action=="tray-sync"||message.Action=="tray-repair")&&message.Status!="ok")PostToUi(()=>{ + if(active?.Session==message.SessionId)ShowChapterCommandFailure("Companion could not accept this command ("+message.Status+"). Check the current document and retry."); + }); if(message.Command!=null){var delivery=Stopwatch.StartNew();PostToUi(()=>{if(message.Command.Kind=="chapter-check")Metric("chapter-command-ui-dispatch",delivery.Elapsed.TotalMilliseconds);HandleCommand(message.Command);});} if(message.WordCount.HasValue)PostToUi(()=>{var doc=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);if(doc!=null)doc.WordCount=message.WordCount;}); if(message.Status!="ok"&&message.Status!="ready")lastResult=message.Status; @@ -397,7 +401,7 @@ namespace PlotDirector.WordAddIn }; if(!scheduler.Post("maintenance:"+doc.Session,next))Finish("Stopped: Word queue busy."); } - private void Reply(AdapterCommand command,string result){var doc=documents.Values.FirstOrDefault(d=>d.Session==command.SessionId);if(doc?.Maintenance==command)doc.Maintenance=null;link.TryPost(new Message{Kind="adapter-result",SessionId=command.SessionId,Revision=command.Revision,SnapshotId=command.Id,OperationMessage=result});} + private void Reply(AdapterCommand command,string result){var doc=documents.Values.FirstOrDefault(d=>d.Session==command.SessionId);if(doc?.Maintenance==command)doc.Maintenance=null;link.TryPost(new Message{Kind="adapter-result",SessionId=command.SessionId,Revision=command.Revision,SnapshotId=command.Id,Action=command.Kind.StartsWith("chapter-",StringComparison.Ordinal)?command.Kind:"",OperationMessage=result});} private bool ScheduleSnapshot(LocalDocument doc,bool analyse=false,Guid? snapshot=null,bool paragraphs=false) { if (doc.Extraction != null || ConnectionState != "connected") return false; diff --git a/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs b/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs index 9649388a..cd2292a6 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs @@ -15,6 +15,7 @@ namespace PlotDirector.WordAddIn private long chapterLiveReads,chapterXmlReads,chapterComCalls,chapterParagraphVisits,chapterCommandPolls,chapterRcwReleases,chapterPlainBatches; private bool nativeChapterTextSupported,nativeChapterPositionsSupported,liveChapterTextSupported; private ChapterSyncProgress serverChapterProgress; + private string lastRibbonCommand=""; public bool HasRibbonBook => active != null && ConnectionState == "connected" && serverBookId > 0 && serverChapterProgress?.State != "Sign-in required"; public string RibbonBook => active != null && serverBook.Length > 0 ? serverBook @@ -39,6 +40,7 @@ namespace PlotDirector.WordAddIn switch (serverChapterProgress.State) { case "Checking": return "Synchronising"; + case "Save required": return "Save to synchronise"; case "Synchronised": if (serverChapterProgress.Total > 0 && serverChapterProgress.Matching == serverChapterProgress.Total) return "Up to date"; @@ -65,16 +67,22 @@ namespace PlotDirector.WordAddIn public void RequestChapterSynchronisation(bool repair) { - if (!HasRibbonBook) { lastResult = "Open a linked manuscript and connect Companion first."; return; } + lastRibbonCommand=repair?"Repair Synchronisation":"Synchronise"; + if (!HasRibbonBook) { ShowChapterCommandFailure("Open a linked manuscript and connect Companion first."); return; } if (!link.TryPost(new Message { Kind = repair ? "tray-repair" : "tray-sync", SessionId = active.Session, Revision = active.Revision })) { - lastResult = "Local queue is busy. Word remains usable; retry shortly."; + ShowChapterCommandFailure("The local queue is busy. Retry shortly."); return; } - serverChapterProgress = null; + serverChapterProgress = new ChapterSyncProgress{State="Checking",Message="Request sent to Companion."}; invalidateRibbon(); } + private void ShowChapterCommandFailure(string reason) + { + System.Windows.Forms.MessageBox.Show(reason,lastRibbonCommand); + } + public void ShowTroubleshooting() => System.Windows.Forms.MessageBox.Show(Diagnostics, "PlotDirector Troubleshooting"); private void ReceiveChapterStatus(Message message) diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json index bbbdc5a5..94ea1441 100644 --- a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json +++ b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json @@ -1,7 +1,7 @@ { - "version": "1.0.0.32", - "msiVersion": "1.0.32", - "productCode": "{F1D84AC4-AD05-444B-8D98-FA0B39ACCA50}", + "version": "1.0.0.33", + "msiVersion": "1.0.33", + "productCode": "{E22C7013-055E-4BB2-ACCB-A52E660C0194}", "upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}", "atlasBaseline": "9fed339879887964d526cff00772ffc4dc522c5d", "baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",