Mark remembered Word book associations unsaved and acknowledge verified writes

This commit is contained in:
nick 2026-11-07 15:54:57 +00:00
parent 2cfa88b267
commit ad24165f5f
6 changed files with 34 additions and 13 deletions

View File

@ -72,7 +72,7 @@ internal sealed class CompanionWindow:Form
var session=selected;using var dialog=new Form{Text="Choose a PlotDirector book",Icon=brand,Font=Font,AutoScaleMode=AutoScaleMode.Dpi,MinimumSize=new(440,260),Size=new(540,300),StartPosition=FormStartPosition.CenterParent};
var stack=Stack(20);dialogNotice=Label();stack.Controls.Add(Label("Associate this manuscript with a book in your account. Manuscript text is not sent or changed."));books.DataSource=cloud.Status().Books;books.SelectedItem=cloud.Status().Books.FirstOrDefault(b=>b.BookId==Current.Book);stack.Controls.Add(books);
var remember=new CheckBox{Text="Also remember in Word metadata (save Word normally)",AutoSize=true,Checked=cloud.Preferences.RememberInDocument};stack.Controls.Add(remember);
stack.Controls.Add(Button("Use this book",()=>{if(books.SelectedItem is not Protocol.CompanionBook book)throw new InvalidOperationException("Sign in and choose an available book.");if(!control.Documents.Any(d=>d.Session==session))throw new InvalidOperationException("That Word document is no longer connected.");if(remember.Checked&&MessageBox.Show(dialog,"Write this association to PlotDirector-owned Word metadata? This marks the document modified, without changing prose.","Remember book",MessageBoxButtons.OKCancel)!=DialogResult.OK)return;control.SelectBook(session,book.BookId,remember.Checked);var prefs=cloud.Preferences;prefs.RememberInDocument=remember.Checked;cloud.SavePreferences(prefs);dialog.Close();}));
stack.Controls.Add(Button("Use this book",()=>{if(books.SelectedItem is not Protocol.CompanionBook book)throw new InvalidOperationException("Sign in and choose an available book.");if(!control.Documents.Any(d=>d.Session==session))throw new InvalidOperationException("That Word document is no longer connected.");control.SelectBook(session,book.BookId,remember.Checked);var prefs=cloud.Preferences;prefs.RememberInDocument=remember.Checked;cloud.SavePreferences(prefs);dialog.Close();}));
stack.Controls.Add(dialogNotice);dialog.Controls.Add(stack);PaintTheme(dialog);dialog.ShowDialog(this);stack.Controls.Remove(books);dialogNotice=null;
}
private void ShowSettings()
@ -112,7 +112,7 @@ internal sealed class CompanionWindow:Form
authorise.Visible=CompanionPresentation.NeedsAuthorisation(state.Health);authorise.Enabled=!string.IsNullOrWhiteSpace(state.ServerUrl);
SetText(guidance,doc==null?"Open a manuscript in Microsoft Word. Your words stay in Word until you request an import in PlotDirector.":doc.Book==0?"Choose the PlotDirector book for this manuscript.":"Import, Context and Intent are available in PlotDirector.");
SetText(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.");
SetText(notice,error);if(settingsNotice is {IsDisposed:false}){SetText(settingsNotice,error);settingsNotice.Visible=error!="";}notice.Visible=error!="";tips.SetToolTip(serverStatus,state.Health?.Explanation??"Connect in Settings.");
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;
if(diagnostics is {IsDisposed:false}&&diagnostics.Text!=text)diagnostics.Text=text;
var next=state.AuthenticationContext+":"+(book?.BookId??0);if(next!=coverKey){coverKey=next;coverRetry=DateTime.MinValue;coverStop?.Cancel();cover.SetImage(null);cover.Caption=bookTitle.Text;cover.Invalidate();coverLoading=false;}

View File

@ -23,7 +23,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
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){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);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;
}
@ -33,15 +33,20 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
else{
doc.Observed=DateTime.UtcNow;
if(request.Kind=="active"){foreach(var d in documents.Values)d.Active=false;doc.Active=true;}
if(request.Kind=="selection"){doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;}
if(request.Kind=="selection"){doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}}
CaptureFrame(doc,request,answer);
if(request.Kind=="selection"||request.Kind=="snapshot-end"){doc.ChapterId=answer.ChapterId;doc.SceneId=answer.SceneId;doc.ChapterTitle=answer.ChapterTitle;doc.SceneTitle=answer.SceneTitle;}
if(answer.WordCount.HasValue)doc.Words=answer.WordCount;
if(request.Kind.StartsWith("snapshot-",StringComparison.Ordinal)&&answer.Status is not ("ok" or "analysis-complete" or "awaiting-structure")){Cancel(doc);doc.Status="Local reading failed: "+answer.Status+". Detect chapters again.";}
if(request.Kind=="snapshot-fragment")doc.Progress=answer.Progress;
if(request.Kind=="snapshot-end"&&answer.Status=="analysis-complete"){doc.Chapters=sessions.Chapters(instance,doc.Session);doc.Status=$"Detected {doc.Chapters.Length} Heading 1 / existing-marker chapters. Scenes require explicit server AI analysis.";doc.Progress=100;}
if(request.Kind=="adapter-result"&&maintenance.Remove(request.SnapshotId,out var operation)&&operation.Session==doc.Session){doc.MaintenanceReport=request.OperationMessage;if(request.OperationMessage.StartsWith("Complete:",StringComparison.Ordinal)&&operation.Kind is "reset" or "clean"){cloud.ForgetBinding(operation.Manuscript,operation.Authentication);doc.Book=0;doc.RememberedBook=null;doc.AssociationSite="";doc.ChapterId=null;doc.SceneId=null;doc.LastPresenceKey="";_=cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);} }
else if(request.Kind=="adapter-result"&&request.OperationMessage!="ok"){doc.Status=request.OperationMessage;Cancel(doc);}
if(request.Kind=="adapter-result"&&maintenance.Remove(request.SnapshotId,out var operation)&&operation.Session==doc.Session){doc.MaintenanceReport=request.OperationMessage;if(request.OperationMessage.StartsWith("Complete:",StringComparison.Ordinal)&&operation.Kind is "reset" or "clean"){cloud.ForgetBinding(operation.Manuscript,operation.Authentication);doc.Book=0;doc.AssociationRequest=Guid.Empty;doc.AssociationNeedsSave=false;doc.AssociationNotice="";doc.RememberedBook=null;doc.AssociationSite="";doc.ChapterId=null;doc.SceneId=null;doc.LastPresenceKey="";_=cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);} }
else if(request.Kind=="adapter-result"&&request.SnapshotId==doc.AssociationRequest&&doc.AssociationRequest!=Guid.Empty){
doc.AssociationRequest=Guid.Empty;
doc.AssociationNeedsSave=request.OperationMessage=="association-written";
doc.AssociationNotice=doc.AssociationNeedsSave?"Book remembered in Word. Save the document to keep this association.":request.OperationMessage=="ok"?"Update the Word add-in to confirm the association was written.":request.OperationMessage;
}
else if(request.Kind=="adapter-result"&&request.OperationMessage!="ok"&&request.OperationMessage!="association-written"){doc.Status=request.OperationMessage;Cancel(doc);}
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;
@ -67,8 +72,8 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
public void Detect(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Completed.Clear();doc.FailedChapters.Clear();doc.Status="Reading chapters in bounded Word batches…";doc.Progress=0;Queue(doc,new(){Kind="detect"});}}
public void SelectBook(Guid session,int book,bool remember)
{
lock(gate){if(!documents.TryGetValue(session,out var doc))return;var state=cloud.Status();if(!cloud.Allows(state.AuthenticationContext,book))throw new InvalidOperationException("Sign in and select an authorised book.");Cancel(doc);doc.Book=book;cloud.RememberBinding(doc.Manuscript,book,state.AuthenticationContext);doc.ChapterId=null;doc.SceneId=null;doc.LastPresenceKey="";doc.Authentication=state.AuthenticationContext;lastBook=book;lastAuthentication=doc.Authentication;doc.Status=remember?"Remember requested; save Word normally after confirmation.":"Book association saved for this Windows user and PlotDirector account.";
Queue(doc,new(){Kind="associate",BookId=book,AuthenticationContext=doc.Authentication,Site=state.ServerUrl,Remember=remember});}
lock(gate){if(!documents.TryGetValue(session,out var doc))return;var state=cloud.Status();if(!cloud.Allows(state.AuthenticationContext,book))throw new InvalidOperationException("Sign in and select an authorised book.");Cancel(doc);var command=new AdapterCommand{Kind="associate",BookId=book,AuthenticationContext=state.AuthenticationContext,Site=state.ServerUrl,Remember=remember};if(!Queue(doc,command))throw new InvalidOperationException(doc.Status);doc.Book=book;cloud.RememberBinding(doc.Manuscript,book,state.AuthenticationContext);doc.ChapterId=null;doc.SceneId=null;doc.LastPresenceKey="";doc.Authentication=state.AuthenticationContext;lastBook=book;lastAuthentication=doc.Authentication;doc.Status="Book association selected for this Windows user and PlotDirector account.";doc.AssociationRequest=remember?command.Id:Guid.Empty;doc.AssociationNeedsSave=false;doc.AssociationNotice=remember?"Writing book association to Word…":"";
}
}
public void Analyse(Guid session,IEnumerable<int> starts)
{
@ -136,7 +141,7 @@ 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="";
public ManuscriptCapture? Capture;public List<ParagraphFragment> CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision;
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 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 StructureSuggestion[] Chapters=[];public StructureSuggestion? Current;public Queue<StructureSuggestion> Pending=[];public HashSet<(long,int,int)> Completed=[];public HashSet<(long,int,int)> FailedChapters=[];public List<string> 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)":"");

View File

@ -1 +1 @@
<Project><PropertyGroup><ApplicationVersion>1.0.0.15</ApplicationVersion></PropertyGroup></Project>
<Project><PropertyGroup><ApplicationVersion>1.0.0.16</ApplicationVersion></PropertyGroup></Project>

View File

@ -57,6 +57,16 @@ internal static class TrayTests
Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=1,SnapshotId=maintenance!.Id,OperationMessage="Complete: inspected"});
check(control.Documents.Single(d=>d.Session==first.SessionId).MaintenanceReport=="Complete: inspected","correlated inspection result is available in Advanced settings");
var maintained=control.Documents.Single(d=>d.Session==first.SessionId);maintained.Book=3;
control.SelectBook(first.SessionId,3,true);
AdapterCommand? association=null;
for(var i=0;i<16;i++){var queued=Apply(new(){Kind="ping"}).Command;if(queued?.Kind=="associate"){association=queued;break;}}
check(association is {Remember:true}&&association.SessionId==first.SessionId&&association.BookId==3&&!maintained.AssociationNeedsSave,"remember targets the selected document and waits for Word acknowledgement");
Apply(new(){Kind="adapter-result",SessionId=second.SessionId,Revision=1,SnapshotId=association!.Id,OperationMessage="association-written"});
check(!maintained.AssociationNeedsSave,"another Word document cannot acknowledge the association");
Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=1,SnapshotId=association.Id,OperationMessage="association-written"});
check(maintained.AssociationNeedsSave&&maintained.AssociationNotice.Contains("Save the document"),"matching Word acknowledgement shows a save reminder");
Apply(new(){Kind="selection",SessionId=first.SessionId,Revision=1,WordSaved=true});
check(!maintained.AssociationNeedsSave&&maintained.AssociationNotice=="","normal Word save clears the reminder");
control.Maintain(first.SessionId,"clean");maintenance=null;for(var i=0;i<16;i++){var queued=Apply(new(){Kind="ping"}).Command;if(queued?.Kind=="maintenance-clean"){maintenance=queued;break;}}
check(maintained.Book==3,"unlink does not claim success before Word acknowledges cleanup");
Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=1,SnapshotId=maintenance!.Id,OperationMessage="Stopped: read-only"});

View File

@ -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.15")]
[assembly: AssemblyFileVersion("1.0.0.15")]
[assembly: AssemblyVersion("1.0.0.16")]
[assembly: AssemblyFileVersion("1.0.0.16")]
[assembly: ComVisible(false)]

View File

@ -249,8 +249,14 @@ namespace PlotDirector.WordAddIn
else if(command.Kind=="associate"){
if(command.Remember){
if(Com(()=>doc.Document.ReadOnly))throw new InvalidOperationException("Document is read-only; select for this session without Remember.");
WriteProperty(doc.Document,DocumentBinding.AssociationProperty,DocumentBinding.AssociationValue(doc.Identity,command.BookId,command.Site),Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString);
var association=DocumentBinding.AssociationValue(doc.Identity,command.BookId,command.Site);
WriteProperty(doc.Document,DocumentBinding.AssociationProperty,association,Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString);
// Custom properties can change without Word marking the document dirty.
Com(()=>{doc.Document.Saved=false;return true;});
if(ReadProperty(doc.Document,DocumentBinding.AssociationProperty)!=association||Com(()=>doc.Document.Saved))
throw new InvalidOperationException("Word did not verify the association and its unsaved state.");
doc.IdentityPersisted=true;doc.BookId=command.BookId;doc.AssociationSite=command.Site;link.Register(Descriptor(doc));
Reply(command,"association-written");return;
}
}
else throw new InvalidOperationException("Unsupported adapter request.");