From 5e5edfce9b30df8489bc7561037537358292ddfc Mon Sep 17 00:00:00 2001 From: nick Date: Mon, 9 Nov 2026 14:47:44 +0000 Subject: [PATCH] Bound chapter validation and surface actionable synchronisation progress --- .../Agent/TrayApplication.cs | 2 +- .../Agent/TrayCoordinator.Chapters.cs | 88 +++++++++++++++---- .../Agent/TrayCoordinator.cs | 2 +- .../DeveloperVersion.props | 2 +- .../Tests/ChapterAgentTests.cs | 14 ++- .../Vsto/Properties/AssemblyInfo.cs | 4 +- .../Vsto/WordChapterRead.cs | 4 +- .../WindowsValidation/Setup/Release.json | 6 +- 8 files changed, 94 insertions(+), 28 deletions(-) diff --git a/PlotDirector.NativeCompanion/Agent/TrayApplication.cs b/PlotDirector.NativeCompanion/Agent/TrayApplication.cs index 6d445c92..76cd8bbd 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayApplication.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayApplication.cs @@ -116,7 +116,7 @@ internal sealed class CompanionWindow:Form SetText(serverStatus,"PlotDirector · "+CompanionPresentation.Connection(state.Health,DateTime.UtcNow));SetText(account,state.Health?.AccountName??"Not signed in"); SetText(wordStatus,CompanionPresentation.WordStatus(doc!=null,doc?.Book??0,doc?.LastPresenceUtc??DateTime.MinValue,doc?.LastPresenceKey??"",DateTime.UtcNow)); authorise.Visible=CompanionPresentation.NeedsAuthorisation(state.Health);authorise.Enabled=!string.IsNullOrWhiteSpace(state.ServerUrl); - SetText(guidance,doc==null?"Open a manuscript in Microsoft Word. Your words stay in Word until you request an import in PlotDirector.":doc.Book==0?"Choose the PlotDirector book for this manuscript.":doc.ChapterProgress is {} chapters?$"{chapters.State} · {chapters.Matching}/{chapters.Total} chapters accepted. {chapters.Message}":"Import, Context and Intent are available in PlotDirector."); + SetText(guidance,doc==null?"Open a manuscript in Microsoft Word. Your words stay in Word until you request an import in PlotDirector.":doc.Book==0?"Choose the PlotDirector book for this manuscript.":control.ChapterProgressForDisplay(doc.Session) is {} chapters?(chapters.State=="Synchronised"?"Up to date":chapters.Message):"Import, Context and Intent are available in PlotDirector."); SetText(bookTitle,book==null?"No book associated":string.IsNullOrEmpty(book.BookTitle)?book.Title:book.BookTitle);SetText(projectTitle,book?.ProjectTitle??"Choose a book to connect your writing workspace."); var noticeText=error!=""?error:doc?.AssociationNotice??"";SetText(notice,noticeText);if(settingsNotice is {IsDisposed:false}){SetText(settingsNotice,error);settingsNotice.Visible=error!="";}notice.Visible=noticeText!="";tips.SetToolTip(serverStatus,state.Health?.Explanation??"Connect in Settings."); var text=$"Server: {state.ServerUrl}\r\nAccount: {state.Health?.AccountName}\r\n{state.Health?.Explanation}\r\n"+string.Join("\r\n",displayed.Select(d=>$"{d.Title} · session {d.Session} · book {d.Book}"))+"\r\n"+doc?.WordDiagnostics+"\r\n"+doc?.Status+"\r\n"+doc?.MaintenanceReport; diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs index c2bb6a15..ef414d07 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs @@ -6,13 +6,64 @@ public sealed partial class TrayCoordinator { private sealed class ChapterWork { - public int Book;public Guid Manuscript;public long Revision;public Guid Context,Operation,Command;public bool Busy,Supported,Processing,Begun;public long FailedRevision=-1;public DateTime Started,RetryAfter; - public ChapterManifest? Manifest;public readonly Dictionary Checked=[]; - public StringBuilder Text=new(),Xml=new(),Identities=new();public int Start,End,DocumentEnd,FirstStart=-1;public bool Finished;public bool Wrapped;public readonly HashSet Reviewed=[];public readonly HashSet Visited=[];public string Next=""; + public int Book, Attempts, Retries; public string ReviewReason = "";public Guid Manuscript;public long Revision;public Guid Context,Operation,Command;public bool Busy,Supported,Processing,Begun;public long FailedRevision=-1;public DateTime Started,RetryAfter; + public ChapterManifest? Manifest; public ChapterSyncProgress? Completion;public readonly Dictionary Checked=[]; + public StringBuilder Text=new(),Xml=new(),Identities=new();public int Start,End,DocumentEnd,CursorWhenQueued,FirstStart=-1;public bool Finished;public bool Wrapped;public readonly HashSet Reviewed=[];public readonly HashSet Visited=[];public string Next=""; } private readonly Dictionary chapterWork=[]; private readonly SemaphoreSlim chapterProcessing=new(2,2); private string ChapterIssue(TrayDocument doc){lock(gate)return chapterWork.TryGetValue(doc.Session,out var work)&&work.FailedRevision==doc.Revision?"needs_review":"";} + public ChapterSyncProgress? ChapterProgressForDisplay(Guid session) + { + lock (gate) + return documents.TryGetValue(session, out var doc) ? VisibleChapterProgress(doc) : null; + } + + private ChapterSyncProgress? VisibleChapterProgress(TrayDocument doc) + { + if (!chapterWork.TryGetValue(doc.Session, out var work) || !CurrentChapterWork(doc, work)) + return doc.ChapterProgress; + + var total = work.Manifest?.Chapters.Length ?? doc.ChapterProgress?.Total ?? 0; + var accepted = work.Checked.Count; + if (work.FailedRevision == doc.Revision) + return new() { State = "Needs review", Total = total, Matching = accepted, Message = doc.Status }; + if (work.Busy || !work.Finished && work.Attempts > 0) + { + var step = work.Processing ? "Verifying chapter with PlotDirector" : "Checking Word chapter"; + if (work.Attempts > 0 && work.Attempts <= total) step += $" {work.Attempts} of {total}"; + return new() { State = "Checking", Total = total, Matching = accepted, Message = step }; + } + return doc.ChapterProgress; + } + + private void StopChapterWork(TrayDocument doc, ChapterWork work, string reason) + { + work.Busy = false; + work.Processing = false; + work.Command = Guid.Empty; + work.FailedRevision = doc.Revision; + doc.Status = reason; + doc.LastPresenceKey = ""; + Queue(doc, new() { Kind = "chapter-cancel" }); + } + + private void RetryChapterWork(TrayDocument doc, ChapterWork work, string reason) + { + if (++work.Retries > 2) + { + StopChapterWork(doc, work, reason); + return; + } + work.Busy = false; + work.Processing = false; + work.Command = Guid.Empty; + work.Finished = false; + work.Manifest = null; + work.RetryAfter = DateTime.UtcNow.AddSeconds(15); + doc.Status = reason; + } + private bool ChapterCapable(Guid instance){lock(gate)return chapterInstances.Contains(instance);} private readonly HashSet ribbonRequests=[]; private async Task RequestChapterFromRibbon(TrayDocument doc,long revision) @@ -28,7 +79,7 @@ public sealed partial class TrayCoordinator private void BeginChapterRepair(TrayDocument doc,Guid operation) { if(!ChapterCapable(doc.Instance))return; - var work=GetChapterWork(doc);work.Operation=operation;work.FailedRevision=-1;work.Manifest=null;work.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.Wrapped=false;work.FirstStart=-1;work.Finished=false;work.Command=Guid.Empty;work.Busy=false; + 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.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.Wrapped=false;work.FirstStart=-1;work.Finished=false;work.Command=Guid.Empty;work.Busy=false; doc.Status="Repairing existing chapter mappings; accepted scenes and author decisions are retained.";work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work); } private ChapterWork GetChapterWork(TrayDocument doc) @@ -39,9 +90,9 @@ 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.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Manifest=null;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;} + if(work.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Completion=null;work.Manifest=null;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;} if(DateTime.UtcNowwork.Start&&doc.Active&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor=work.End)){QueueChapter(doc,work,doc.Cursor);return;}if(DateTime.UtcNow-work.Started>TimeSpan.FromMinutes(2)){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Chapter validation timed out. Accepted checkpoints are retained; request Repair to resume.";}return;} + if(work.Busy){if(!work.Processing&&work.Command!=Guid.Empty&&work.End>work.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;} if(work.Manifest==null){work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work);return;} var here=work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursorc.State=="Synchronised"))work.Checked[chapter.ChapterId]=(chapter.Start,chapter.End);doc.Status=$"Chapter index ready: {work.Checked.Count}/{manifest.Chapters.Length} accepted for this Word session.";if(manifest.Chapters.Length>0&&work.Checked.Count==manifest.Chapters.Length){CompleteChapters(doc,work);}else if(manifest.Chapters.Length>0&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor!work.Checked.ContainsKey(c.ChapterId));if(next!=null)QueueChapter(doc,work,next.Start);}} - }catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;doc.Status="Chapter index unavailable: "+e.Message+" Existing import is retained; no full extraction was started.";}} + lock(gate){if(!CurrentChapterWork(doc,work))return;if(manifest.ManuscriptId!=doc.Manuscript)throw new InvalidOperationException("Saved manuscript identity does not match this Word document.");work.Manifest=manifest;work.Busy=false;if(manifest.Chapters.Length==0){StopChapterWork(doc,work,"No accepted chapter boundaries are available. Review the existing manuscript structure.");return;}if(work.Operation==Guid.Empty&&manifest.Chapters.All(c=>string.IsNullOrEmpty(c.HeadingNativeId))){StopChapterWork(doc,work,"This existing import has no native chapter identities. Use Repair Synchronisation to verify and adopt identities without reimporting.");return;}if(manifest.Mode=="Off"&&work.Operation==Guid.Empty){work.Finished=true;doc.Status="Automatic synchronisation is off. Use Synchronise or Repair for an explicit chapter check.";return;}foreach(var chapter in manifest.Chapters.Where(c=>c.State=="Synchronised"))work.Checked[chapter.ChapterId]=(chapter.Start,chapter.End);doc.Status=$"Chapter index ready: {work.Checked.Count}/{manifest.Chapters.Length} accepted for this Word session.";if(manifest.Chapters.Length>0&&work.Checked.Count==manifest.Chapters.Length){CompleteChapters(doc,work);}else if(manifest.Chapters.Length>0&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor!work.Checked.ContainsKey(c.ChapterId));if(next!=null)QueueChapter(doc,work,next.Start);}} + }catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){RetryChapterWork(doc,work,"Chapter index unavailable: "+e.Message);}} } private bool CurrentChapterWork(TrayDocument doc,ChapterWork work)=>documents.GetValueOrDefault(doc.Session)==doc&&chapterWork.GetValueOrDefault(doc.Session)==work&&doc.Revision==work.Revision&&doc.Authentication==work.Context&&doc.Book==work.Book&&doc.Manuscript==work.Manuscript; private void QueueChapter(TrayDocument doc,ChapterWork work,int position) @@ -64,8 +115,13 @@ public sealed partial class TrayCoordinator if(background.Value==null||!documents.TryGetValue(background.Key,out var backgroundDoc))return; Queue(backgroundDoc,new(){Kind="chapter-cancel"});background.Value.Command=Guid.Empty;background.Value.Busy=false;background.Value.Text=new();background.Value.Xml=new(); } + if (work.Attempts >= (work.Manifest?.Chapters.Length ?? 0) * 2 + 2) + { + StopChapterWork(doc, work, "Chapter checks reached the retry limit. " + work.ReviewReason); + return; + } var command=new AdapterCommand{Kind="chapter-check",OperationId=work.Operation,BookId=doc.Book,Chapter=new(){Start=position}}; - if(Queue(doc,command)){work.Command=command.Id;work.Busy=true;work.Processing=false;work.Begun=false;work.Start=work.End=0;work.Started=DateTime.UtcNow;work.Text.Clear();work.Xml.Clear();work.Identities.Clear();doc.Status=$"Checking chapter positions ({work.Checked.Count}/{work.Manifest!.Chapters.Length} accepted); Word prose is unchanged.";} + if(Queue(doc,command)){work.Command=command.Id;work.Attempts++;work.CursorWhenQueued=doc.Cursor;work.Busy=true;work.Processing=false;work.Begun=false;work.Start=work.End=0;work.Started=DateTime.UtcNow;work.Text.Clear();work.Xml.Clear();work.Identities.Clear();doc.Status=$"Checking chapter positions ({work.Checked.Count}/{work.Manifest!.Chapters.Length} accepted); Word prose is unchanged.";} } private void ChapterFrame(TrayDocument doc,Message message,Message answer) { @@ -102,8 +158,8 @@ public sealed partial class TrayCoordinator } private async Task CompleteChapterOperation(TrayDocument doc,ChapterWork work) { - try{var result=await cloud.FinishChapters(doc.Book,new(){InstanceId=doc.Instance,SessionId=doc.Session,WordRevision=work.Revision,OperationId=work.Operation,ReviewChapterIds=work.Reviewed.Where(id=>id>0).ToArray(),HasIssues=work.Reviewed.Count>0||work.Manifest!.Chapters.Any(c=>!work.Checked.ContainsKey(c.ChapterId))},work.Context);lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;doc.Status=result.Message;}} - catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;work.Finished=false;work.Manifest=null;work.RetryAfter=DateTime.UtcNow.AddSeconds(15);doc.Status="Accepted checkpoints are retained; final chapter status will be retried after reconnect: "+e.Message;}} + try{var result=await cloud.FinishChapters(doc.Book,new(){InstanceId=doc.Instance,SessionId=doc.Session,WordRevision=work.Revision,OperationId=work.Operation,ReviewChapterIds=work.Reviewed.Where(id=>id>0).ToArray(),HasIssues=work.Reviewed.Count>0||work.Manifest!.Chapters.Any(c=>!work.Checked.ContainsKey(c.ChapterId))},work.Context);lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;work.Processing=false;work.Completion=result;doc.ChapterProgress=result;doc.Status=result.Message;if(result.State=="Needs review" && work.ReviewReason.Length>0){result.Message=work.ReviewReason;}}} + catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){RetryChapterWork(doc,work,"Could not confirm chapter completion: "+e.Message);}} } private async Task ProcessChapter(TrayDocument doc,ChapterWork work,string text,string xml,string? identities,Guid command,int start,int end,string nextHeading,Guid operation) { @@ -115,17 +171,17 @@ public sealed partial class TrayCoordinator var hash=ChapterFingerprint.Content(rows.Select(p=>p.Text!)); var candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==rows[0].NativeId).ToArray(); if(candidates.Length==0&&work.Operation!=Guid.Empty)candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==""&&c.ContentHash==hash&&c.ParagraphCount==rows.Length).ToArray(); - if(candidates.Length!=1){lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;work.Reviewed.Add(-work.Start-1);doc.Status="An unrecognised or ambiguous chapter needs review; no chapter was guessed by name.";AdvanceChapter(doc,work);}return;} + if(candidates.Length!=1){lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;work.Reviewed.Add(-work.Start-1);work.ReviewReason="A chapter identity is unrecognised or ambiguous. Review its Word heading and saved mapping.";doc.Status=work.ReviewReason;AdvanceChapter(doc,work);}return;} var chapter=candidates[0];lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(!work.Visited.Add(chapter.ChapterId)){work.Busy=false;if(!work.Checked.TryGetValue(chapter.ChapterId,out var earlier)||earlier.Start!=start||earlier.End!=end){work.Reviewed.Add(chapter.ChapterId);work.Checked.Remove(chapter.ChapterId);doc.Status="Duplicate chapter identity at another position; existing canonical structure is retained for review.";}AdvanceChapter(doc,work);return;}}var proof=new ChapterObservation{RequestId=command,OperationId=operation,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,WordRevision=doc.Revision,BaseRevision=manifest.Revision,ChapterId=chapter.ChapterId,Start=start,End=end,NextHeadingId=nextHeading,ContentHash=hash,IdentityHash=ChapterFingerprint.Identity(rows),Paragraphs=rows.Select(p=>new ChapterParagraph{NativeId=p.NativeId,Length=p.Length,Outline=p.Outline}).ToArray()}; var result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication); if(!result.Accepted&&result.State=="Changed"&&result.AllowText){proof.Reconcile=true;proof.Paragraphs=rows;result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);} lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false; - if(result.Accepted){work.Checked[chapter.ChapterId]=(start,end);manifest.Revision=result.Revision;if(result.State=="Needs review")work.Reviewed.Add(chapter.ChapterId);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status=$"{work.Checked.Count}/{manifest.Chapters.Length} chapters accepted · "+result.Message;AdvanceChapter(doc,work);} - else{work.Reviewed.Add(chapter.ChapterId);doc.Status=result.Message+" Accepted chapter repairs are retained.";AdvanceChapter(doc,work);} + 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);} } }catch(Exception e)when(NetworkFailure(e)||e is ArgumentException or System.Xml.XmlException){lock(gate)if(CurrentChapterWork(doc,work)&&work.Command==command){work.Busy=false; - if(e is HttpRequestException or OperationCanceledException||cloud.Status().Health?.Authentication!="verified"){work.Manifest=null;work.Command=Guid.Empty;work.Visited.Clear();work.RetryAfter=DateTime.UtcNow.AddSeconds(15);doc.Status="Chapter connection interrupted; accepted checkpoints are retained and validation will resume after reconnect.";} - else if(e is ArgumentException or System.Xml.XmlException&&end>start){work.Reviewed.Add(-start-1);doc.Status="Chapter content needs review: "+e.Message+" Other chapters can continue.";AdvanceChapter(doc,work);} + if(e is HttpRequestException or OperationCanceledException||cloud.Status().Health?.Authentication!="verified"){work.Visited.Clear();RetryChapterWork(doc,work,"Chapter connection interrupted. Accepted checkpoints are retained.");} + else if(e is ArgumentException or System.Xml.XmlException&&end>start){work.Reviewed.Add(-start-1);work.ReviewReason="Chapter content needs review: "+e.Message;doc.Status=work.ReviewReason;AdvanceChapter(doc,work);} else{work.FailedRevision=doc.Revision;doc.Status="Chapter needs review: "+e.Message+" Existing import is unchanged.";}}} finally{chapterProcessing.Release();} } diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs index 7e6858f3..cca89997 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs @@ -61,7 +61,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway } } if(documents.TryGetValue(request.SessionId,out var activeDocument)&&ChapterCapable(instance)&&request.Kind is "selection" or "metrics"){ - answer.ChapterStatusProvided=true;answer.BookId=activeDocument.Book;answer.BookTitle=cloud.Status().Books.FirstOrDefault(b=>b.BookId==activeDocument.Book)?.Title??"";answer.ChapterTitle=activeDocument.ChapterTitle;answer.SceneTitle=activeDocument.SceneTitle;answer.ChapterProgress=activeDocument.ChapterProgress; + answer.ChapterStatusProvided=true;answer.BookId=activeDocument.Book;answer.BookTitle=cloud.Status().Books.FirstOrDefault(b=>b.BookId==activeDocument.Book)?.Title??"";answer.ChapterTitle=activeDocument.ChapterTitle;answer.SceneTitle=activeDocument.SceneTitle;answer.ChapterProgress=VisibleChapterProgress(activeDocument); } if(commands.TryGetValue(instance,out var queue)&&queue.Count>0)answer.Command=queue.Dequeue(); return answer; diff --git a/PlotDirector.NativeCompanion/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props index af1a2ead..1de70159 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.24 +1.0.0.25 diff --git a/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs b/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs index 25ee1a91..7f95bde2 100644 --- a/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs +++ b/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs @@ -30,6 +30,16 @@ internal static class ChapterAgentTests AdapterCommand? second=null;for(int n=0;n<200&&second==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")second=pending;await Task.Delay(20);} Check(second?.Kind=="chapter-check"&&second.SessionId==session,"A second Word document has independent chapter work and cannot inherit the first session's trust"); Send(new(){Kind="close"});Frames(second!);await Task.Delay(100);Check(handler.Validations==before,"Closing a document rejects late extraction frames and preserves already accepted chapters");session=oldSession; + handler.LegacyManifest = true; + session = Guid.NewGuid(); + Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Legacy indexed fixture.docx"}]}); + tray.SelectBook(session,3,false); + Send(new(){Kind="active"}); + Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}); + await Until(() => tray.ChapterProgressForDisplay(session)?.State == "Needs review"); + Check(tray.ChapterProgressForDisplay(session)!.Message.Contains("native chapter identities"), "Unindexed legacy identity displays actionable review instead of a zero-count scan"); + Check(Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command?.Kind != "chapter-check" && handler.Validations == before, "No automatic chapter read is queued when every legacy heading lacks a native ID"); + session = oldSession; var wrong=new Message{Kind="chapter-chunk",SnapshotId=command!.Id,Action="xml",Start=0,OperationMessage="wrong"};var legacySessions=new SessionManager();legacySessions.Attach(instance,lease);long legacySequence=0;Message Legacy(Message m){m.WordInstanceId=instance;m.SessionId=session;m.Sequence=++legacySequence;m.Revision=1;return legacySessions.Apply(lease,m);}Legacy(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Legacy"}]});Check(Legacy(wrong).Status=="invalid-chapter-frame","Chapter frames require negotiated native capability; legacy clients remain isolated"); }finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}} } @@ -37,13 +47,13 @@ internal static class ChapterAgentTests private static async Task Until(Func condition){for(int i=0;i<300;i++){if(condition())return;await Task.Delay(30);}throw new Exception("Chapter test timed out");} private sealed class Handler:HttpMessageHandler { - public Guid Manuscript;public int Validations,Finishes;public List Bodies=[];public List Paths=[]; + public Guid Manuscript;public bool LegacyManifest;public int Validations,Finishes;public List Bodies=[];public List Paths=[]; protected override async Task SendAsync(HttpRequestMessage request,CancellationToken cancel) { var path=request.RequestUri!.AbsolutePath;Paths.Add(path);HttpResponseMessage Json(object value)=>new(HttpStatusCode.OK){Content=JsonContent.Create(value)}; if(path.EndsWith("/pair"))return Json(new{code="00112233445566778899AABB"});if(path.EndsWith("/token"))return Json(new{accessToken="fixture"});if(path.EndsWith("/books"))return Json(new[]{new{bookId=3,title="Synthetic book"}});if(path.EndsWith("/connection"))return Json(new{state="Connected",authentication="verified",server="online",expiresUtc=DateTime.UtcNow.AddHours(4)}); if(path.EndsWith("/presence")){var value=await request.Content!.ReadFromJsonAsync(cancel);value!.ChapterSyncSupported=true;value.ParagraphRevision=1;return Json(value);} - if(path.EndsWith("/chapter-sync"))return Json(new ChapterManifest{BookId=3,ManuscriptId=Manuscript,Revision=1,Chapters=[new(){ChapterId=10,HeadingNativeId="00000001",ContentHash=ChapterFingerprint.Content(["Chapter 1\r","Exact prose\r"]),Start=0,End=22,ParagraphCount=2}]}); + if(path.EndsWith("/chapter-sync"))return Json(new ChapterManifest{BookId=3,ManuscriptId=Manuscript,Revision=1,Chapters=[new(){ChapterId=10,HeadingNativeId=LegacyManifest?"":"00000001",ContentHash=ChapterFingerprint.Content(["Chapter 1\r","Exact prose\r"]),Start=0,End=22,ParagraphCount=2}]}); if(path.EndsWith("/validate")){var body=await request.Content!.ReadAsStringAsync(cancel);Bodies.Add(body);Validations++;return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",ChapterId=10,Revision=1,Message="Chapter accepted."});} if(path.EndsWith("/finish")){Finishes++;return Json(new ChapterSyncProgress{Total=1,Checked=1,Matching=1,State="Synchronised",Message="All chapters accepted."});} return Json(new{}); diff --git a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs index 4e331750..e5b08f5c 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.24")] -[assembly: AssemblyFileVersion("1.0.0.24")] +[assembly: AssemblyVersion("1.0.0.25")] +[assembly: AssemblyFileVersion("1.0.0.25")] [assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs b/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs index 483ce3b5..bd7ec691 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs @@ -43,8 +43,8 @@ namespace PlotDirector.WordAddIn } public string RibbonSyncProgress => ChapterStatusLabel == "Synchronising" && serverChapterProgress.Total > 0 - ? string.Format("{0} of {1} chapters accepted", serverChapterProgress.Matching, serverChapterProgress.Total) - : " "; + ? serverChapterProgress.Message + : ChapterStatusLabel == "Review needed" ? "See status tooltip" : " "; public string ChapterStatusTip => (HasCurrentRibbonState ? serverChapterProgress?.Message : null) ?? "Synchronise to verify the manuscript position."; diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json index 20e7013e..5ddc2cae 100644 --- a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json +++ b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json @@ -1,7 +1,7 @@ { - "version": "1.0.0.24", - "msiVersion": "1.0.24", - "productCode": "{6BBBF1AE-F38C-492D-BDB0-981B5D7E5E1D}", + "version": "1.0.0.25", + "msiVersion": "1.0.25", + "productCode": "{CF38BE16-F30A-46B0-9242-5A7B9197AEFD}", "upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}", "atlasBaseline": "c6cdfbc3b17107a8d269561c319d946c8e337835", "baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",