diff --git a/Docs/WordCompanion/2026-11-05-usability-recovery.md b/Docs/WordCompanion/2026-11-05-usability-recovery.md new file mode 100644 index 00000000..e67c2508 --- /dev/null +++ b/Docs/WordCompanion/2026-11-05-usability-recovery.md @@ -0,0 +1,40 @@ +# Word Companion usability recovery + +Developer version 1.0.0.7, continuing the shared Phase 1 branch. Scope is the native author workflow and additive local protocol fields. + +## Findings and corrections + +Book selection, saved Context/Intent and navigation were implemented inside the modeless analysis review. The ribbon did not expose them, so signed-in authors had no visible remedy for an unselected book. The ribbon now exposes Select Book, the selected title and detected location, Open PlotDirector, Context, Intent, Review structure, Settings and Diagnostics. Select Book has search, explicit confirmation and account/document change checks. Opening saved Context or Intent does not itself start a manuscript analysis or upload prose. + +The existing per-document book binding was deliberately cleared on reconnect and was never persisted. Identity was not a prerequisite for session-only selection. The new optional Remember checkbox authorises one custom-property write, explained before confirmation. It does not save the document. Authors save normally when they want persistence. The property PlotDirector.Native.Association holds GUID|positive-book-ID|HTTPS-site-root. It is one value so a failed partial multi-property update cannot connect the wrong site/book. Existing Office.js settings, markers and older native properties are retained. A copied/Save As document retains its selected book; live sessions are still distinct. Changing copies to another book requires explicit selection. On reopen/reconnect, metadata is revalidated against the current HTTPS site and the current account's accessible book list. It confers no server authority. Missing/revoked access leaves saved data unavailable; the author can sign in or change books. + +Settings now displays account/site, current manuscript, current book, location, metadata permissions, analysis modes and recovery controls. Remember is optional. Read-only/property-write failures explain how to select a book for the session. No automatic prose synchronization or implicit AI upload was enabled. + +Normal snapshots did not return a word count. Explicit analysis alone computed an approximate count. The recovery counts words incrementally on the agent during the existing normal snapshot, returns a nullable count and reuses it for selection. No additional Word full-document statistics call or rescan was introduced. Null is unavailable, zero is a completed empty document, and edits/revisions invalidate the count. Display explicitly identifies this as an approximate whitespace-based main-story count, which may differ from Word's own statistics. + +The reported historic NullReferenceException has no recorded stack, so its exact origin cannot be established retrospectively. Unchecked application.Selection/selection.Document access during startup or no-document transitions is guarded, as are missing optional custom properties. New failures include the bounded operation/method and source line in Diagnostics. This is a correction to unsafe accesses and improved evidence, not proof of the old exception's cause. Marker/outline detection resolving the author's chapter title was genuine local detection; it did not establish a server scene match. Saved markers continue to be checked against the selected book by the existing server workspace endpoint. + +The existing live agent returned a ready handshake and a verified Development authentication state with Server=online and one accessible book during investigation. No token or manuscript prose was read from that response. This established the existing book API path was available to the account. + +## Server / Atlas contract still required + +The deployed native API supports authentication, book enumeration and saved workspace reads, but there is no native presence route or subscription to make the website show a live Word session. The legacy Office.js user-only presence route must not be reused. + +Atlas integration contract for the next server change: + +- Add bearer-authenticated POST /api/native-companion/instances/{instanceId}/documents/{sessionId}/presence and DELETE for the same exact session. The request carries stable manuscript GUID, book ID, observation revision, monotonic sequence, optional validated chapter/scene IDs and whether the document is active. Never accept a user ID from the payload. +- Recheck book ownership/collaborator access through the existing stored-procedure-backed access service. Require chapter/scene membership in that book. Reject stale sequence/revision updates. Bind the lease to the authenticated account and native grant, not a client assertion. Use the existing server environment boundary. +- Use bounded per-account session leases and a server timestamp, with a 15-second agent heartbeat and 45-second expiry. Revoke on sign-out/expiry/access loss. A dropped process/network must expire to stale/disconnected. Do not store manuscript prose or filesystem paths. +- Expose authenticated read-only presence for the authorised book workspace. Render selected book and validated location, last-seen and freshness. Scope any future browser event to account, book and explicit native instance/session. Multiple documents/processes must remain distinguishable. The browser may choose which session to follow. Presence events must not navigate or write back to Word. +- Capability-negotiate this as native-presence-v1. The current client must continue to show only verified saved information until both server and agent support it. Existing Office.js behavior remains independent. +- For unmarked chapters/scenes, expose an authorised bounded structure list and an explicit per-session manual mapping operation. Validate all IDs and expected observation revision. Display unmatched/uncertain local candidates until an author confirms a mapping. Do not fuzzy-match prose or promote a heading into a trusted server ID. + +This recovery does not claim website presence or manual server scene mapping is implemented/deployed. Existing pinned Context/Intent navigation provides saved information; authors may navigate to another saved scene in that browser view. Development deployment requires the Atlas integration above. No server or Production deployment, migration, stored-procedure or configuration change is part of this native package. + +## Verification + +The Windows managed Release solution and signed VSTO host compile with the existing command-line Office-equipped MSBuild. Native regression tests cover count-only snapshot framing, unavailable/valid counts, split words, revision invalidation, metadata round-trip, renamed authorised book IDs and cross-site/unauthorised restoration refusal, in addition to existing session, cancellation, paging and security tests. Detailed final counts and installed package evidence are recorded after qualification. No IDE operation, tooling installation or trust-store change is used. + +The author's Word UI checks remain distinct from automation. In particular, real book persistence across save/reopen, modeless focus/DPI, historic COM error reproduction and 155k/190k/250k responsiveness require actual Word interaction. A successful build is not desktop acceptance. + +Automated Windows results for recovery source: managed Release build and VSTO compile passed with zero warnings/errors; 192 native assertions passed; native pairing, actual HTTP pairing/auth/AI gates and saved-workspace/import-preview checks passed. The full application harness reproduced the previously observed Windows CoreImportWizardOrdersScenesBeforeCharacters assertion, “Saving chapter review should validate only structure before scene import.” That importer path was not changed. PowerShell parsing and ribbon XML parsing passed. diff --git a/PlotDirector.NativeCompanion/Agent/DocumentAnalysis.cs b/PlotDirector.NativeCompanion/Agent/DocumentAnalysis.cs index ed1e7489..2d1472db 100644 --- a/PlotDirector.NativeCompanion/Agent/DocumentAnalysis.cs +++ b/PlotDirector.NativeCompanion/Agent/DocumentAnalysis.cs @@ -6,7 +6,7 @@ namespace PlotDirector.Companion.Agent; // Incremental, local structural review. No server identities, AI or import decisions. // Keeps a bounded paragraph prefix and suggestions, not a second manuscript copy. -public sealed class DocumentAnalysis +public sealed class DocumentAnalysis(bool collectSuggestions = true) { private const int Limit = 8192; private readonly List suggestions = []; @@ -20,6 +20,7 @@ public sealed class DocumentAnalysis private int documentEnd; private StructureSuggestion? chapter; public int Count => suggestions.Count; + public int WordCount => words; public void Add(ParagraphFragment fragment) { if (paragraphLength == 0) { paragraphStart=fragment.Start; outline=fragment.OutlineLevel; tags=fragment.MarkerTags; } @@ -34,6 +35,7 @@ public sealed class DocumentAnalysis documentEnd=fragment.End; if(!fragment.CompletesParagraph)return; paragraphs++; inWord=false; + if (!collectSuggestions) { prefix.Clear(); paragraphLength=0; tags=[]; return; } var text=prefix.ToString().Trim('\r','\n','\a',' ','\t'); var chapter=StructuralParser.MarkerId(tags,"PD-CHAPTER-").HasValue; var scene=StructuralParser.MarkerId(tags,"PD-SCENE-").HasValue; diff --git a/PlotDirector.NativeCompanion/Agent/SessionManager.cs b/PlotDirector.NativeCompanion/Agent/SessionManager.cs index cfdbb9dc..30ce2fe7 100644 --- a/PlotDirector.NativeCompanion/Agent/SessionManager.cs +++ b/PlotDirector.NativeCompanion/Agent/SessionManager.cs @@ -39,6 +39,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai { ai?.Clear(document.Descriptor.SessionId);workspace?.Clear(document.Descriptor.SessionId); totalSuggestions -= document.Analysis?.Count ?? 0;document.Analysis=null; + document.WordCount=null; ClearPending(document);totalBoundaries -= document.Boundaries.Count;document.Boundaries=[]; } public Message Apply(Guid lease, Message message) @@ -117,7 +118,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai var cost = fragment.Text.Length + fragment.MarkerTags.Sum(t=>t.Length) + 128; if (pending.Characters + cost > MaxSnapshotCharacters || totalCharacters + cost > MaxTotalCharacters || totalFragments >= 200_000) return Reject(answer,"snapshot-capacity"); pending.Characters += cost; totalCharacters += cost; totalFragments++; - pending.End = fragment.End; pending.LastComplete = fragment.CompletesParagraph; if(fragment.CompletesParagraph)pending.NextParagraph++; pending.Fragments.Add(fragment); pending.Analysis?.Add(fragment); + pending.End = fragment.End; pending.LastComplete = fragment.CompletesParagraph; if(fragment.CompletesParagraph)pending.NextParagraph++; pending.Fragments.Add(fragment); pending.Counter.Add(fragment); answer.Progress=pending.ExpectedEnd==0?100:(int)(100L*pending.End/pending.ExpectedEnd); break; case "snapshot-end": if (document.Pending == null || document.Pending.Id != message.SnapshotId) return Reject(answer,"obsolete-snapshot"); @@ -133,6 +134,8 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai document.Boundaries = boundaries; document.SnapshotId = snapshot.Id; document.ContentFingerprint = StructuralParser.Fingerprint(snapshot.Fragments); + document.WordCount=snapshot.Counter.WordCount; + answer.WordCount=document.WordCount; ClearPending(document); Resolve(document, answer);workspace?.Position(message.SessionId,answer.ChapterId,answer.SceneId); if(document.Analysis!=null){answer.Analysis=document.Analysis.Page(0);answer.Status="analysis-complete";answer.Progress=100;} break; @@ -151,6 +154,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai private static Message Reject(Message answer,string status) { answer.Status = status; return answer; } private static void Resolve(DocumentState document, Message answer) { + answer.WordCount=document.WordCount; var boundary = document.Boundaries.LastOrDefault(b => b.Start <= document.Cursor); if (boundary == null) { answer.Status = "awaiting-structure"; return; } answer.ChapterId = boundary.ChapterId; answer.SceneId = boundary.SceneId; @@ -160,8 +164,8 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai public Guid? ActiveSession(Guid instance) { lock(gate) return instances.GetValueOrDefault(instance)?.ActiveSession; } public bool HasSession(Guid instance, Guid session) { lock(gate) return instances.TryGetValue(instance,out var word) && word.Documents.ContainsKey(session); } private sealed class WordInstance(Guid lease) { public Guid Lease = lease; public long LastSequence; public Guid? ActiveSession; public Dictionary Documents = []; } - private sealed class DocumentState(DocumentDescriptor descriptor) { public DocumentDescriptor Descriptor = descriptor; public int Cursor; public Snapshot? Pending; public Guid SnapshotId; public string ContentFingerprint=""; public List Boundaries = []; public DocumentAnalysis? Analysis; } - private sealed class Snapshot(Guid id,int expectedEnd,bool analyze) { public DocumentAnalysis? Analysis=analyze?new DocumentAnalysis():null; public Guid Id = id; public int ExpectedEnd=expectedEnd; public bool LastComplete; public int End; public int NextParagraph=1; public int Characters; public List Fragments = []; } + private sealed class DocumentState(DocumentDescriptor descriptor) { public DocumentDescriptor Descriptor = descriptor; public int Cursor; public int? WordCount; public Snapshot? Pending; public Guid SnapshotId; public string ContentFingerprint=""; public List Boundaries = []; public DocumentAnalysis? Analysis; } + private sealed class Snapshot(Guid id,int expectedEnd,bool analyze) { public readonly DocumentAnalysis Counter=new(analyze); public DocumentAnalysis? Analysis=>analyze?Counter:null; public Guid Id = id; public int ExpectedEnd=expectedEnd; public bool LastComplete; public int End; public int NextParagraph=1; public int Characters; public List Fragments = []; } } public sealed record StructuralBoundary(int Start, int? ChapterId, int? SceneId, string ChapterTitle, string SceneTitle); diff --git a/PlotDirector.NativeCompanion/Client/DocumentBinding.cs b/PlotDirector.NativeCompanion/Client/DocumentBinding.cs index 32fcbb0d..217f2a00 100644 --- a/PlotDirector.NativeCompanion/Client/DocumentBinding.cs +++ b/PlotDirector.NativeCompanion/Client/DocumentBinding.cs @@ -3,6 +3,26 @@ namespace PlotDirector.Companion.Client; public sealed class DocumentBinding { + public const string AssociationProperty="PlotDirector.Native.Association"; + public static string AssociationValue(Guid identity,int book,string site)=>identity.ToString("D")+"|"+book.ToString(System.Globalization.CultureInfo.InvariantCulture)+"|"+site; + public static bool ReadAssociation(string value,out Guid identity,out int book,out string site) + { + identity=Guid.Empty;book=0;site=""; + if(value==null||value.Length>512)return false; + var fields=value.Split('|'); + if(fields.Length!=3||!Guid.TryParse(fields[0],out identity)||identity==Guid.Empty||!int.TryParse(fields[1],out book)||book<=0)return false; + site=fields[2]; + return CanRestore(book,site,site,new[]{new CompanionBook{BookId=book}}); + } + public static bool CanRestore(int book,string savedSite,string currentSite,IEnumerable accessible) + { + return book>0 && Uri.TryCreate(savedSite,UriKind.Absolute,out var saved) + && Uri.TryCreate(currentSite,UriKind.Absolute,out var current) + && saved.Scheme==Uri.UriSchemeHttps && current.Scheme==Uri.UriSchemeHttps + && saved.AbsolutePath=="/" && current.AbsolutePath=="/" + && string.IsNullOrEmpty(saved.UserInfo) && string.IsNullOrEmpty(saved.Query) && string.IsNullOrEmpty(saved.Fragment) + && saved==current && accessible.Any(b=>b.BookId==book); + } public int BookId {get;private set;} public Guid Id {get;private set;} public Guid AuthenticationContext {get;private set;} diff --git a/PlotDirector.NativeCompanion/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props index a8e52b28..0c8a70c6 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.6 +1.0.0.7 diff --git a/PlotDirector.NativeCompanion/Protocol/Messages.cs b/PlotDirector.NativeCompanion/Protocol/Messages.cs index c7a43241..f6c8c002 100644 --- a/PlotDirector.NativeCompanion/Protocol/Messages.cs +++ b/PlotDirector.NativeCompanion/Protocol/Messages.cs @@ -57,6 +57,8 @@ public sealed class Message [DataMember] public bool RequestAnalysis { get; set; } [DataMember] public AnalysisPage? Analysis { get; set; } [DataMember] public int Progress { get; set; } + // Null means no completed current snapshot. This is a whitespace-based main-story count. + [DataMember] public int? WordCount { get; set; } } [DataContract] diff --git a/PlotDirector.NativeCompanion/Tests/AnalysisTests.cs b/PlotDirector.NativeCompanion/Tests/AnalysisTests.cs index 494d487b..29e41ebe 100644 --- a/PlotDirector.NativeCompanion/Tests/AnalysisTests.cs +++ b/PlotDirector.NativeCompanion/Tests/AnalysisTests.cs @@ -10,6 +10,10 @@ internal static class AnalysisTests ParagraphFragment Fragment(string text,int index=1,int start=0,int outline=10,string[]? tags=null) => new(){Text=text,Start=start,End=start+text.Length,ParagraphIndex=index,OutlineLevel=outline,MarkerTags=tags??[],CompletesParagraph=true}; var blank=new DocumentAnalysis();blank.Add(Fragment("\r")); check(blank.Page(0).WordCount==0&&blank.Page(0).Total==0&&blank.Page(0).Notice.Contains("No manuscript"),"blank document has an explicit empty analysis"); + var countOnly=new DocumentAnalysis(false); + countOnly.Add(new(){Text="hel",Start=0,End=3,CompletesParagraph=false}); + countOnly.Add(new(){Text="lo world\r",Start=3,End=12,CompletesParagraph=true}); + check(countOnly.WordCount==2&&countOnly.Count==0,"normal snapshot counts across split fragments without retaining review candidates"); var ordinary=new DocumentAnalysis();var position=0;var index=0; foreach(var text in new[]{"Chapter One\r","Ordinary manuscript prose.\r","* * *\r","Another scene.\r","Chapter 2: Return\r","More prose.\r"}) {ordinary.Add(Fragment(text,++index,position));position+=text.Length;} diff --git a/PlotDirector.NativeCompanion/Tests/WorkflowTests.cs b/PlotDirector.NativeCompanion/Tests/WorkflowTests.cs index e98d9dc8..0f032a3c 100644 --- a/PlotDirector.NativeCompanion/Tests/WorkflowTests.cs +++ b/PlotDirector.NativeCompanion/Tests/WorkflowTests.cs @@ -8,6 +8,15 @@ internal static class WorkflowTests { public static async Task Run(Action check) { + var rememberedIdentity=Guid.NewGuid(); + var encoded=DocumentBinding.AssociationValue(rememberedIdentity,11,"https://fixture.invalid/"); + check(DocumentBinding.ReadAssociation(encoded,out var decodedIdentity,out var decodedBook,out var decodedSite) + &&decodedIdentity==rememberedIdentity&&decodedBook==11&&decodedSite=="https://fixture.invalid/","book association round-trips stable identity and server in one metadata value"); + check(DocumentBinding.CanRestore(11,decodedSite,decodedSite,[new(){BookId=11,Title="Renamed book"}]),"remembered book restores by authorised identifier after a title change"); + check(!DocumentBinding.CanRestore(11,decodedSite,"https://other.invalid/",[new(){BookId=11}]) + &&!DocumentBinding.CanRestore(11,decodedSite,decodedSite,[new(){BookId=12}]),"saved association cannot cross server or bypass accessible-book permissions"); + check(!DocumentBinding.ReadAssociation("bad|11|https://fixture.invalid/",out _,out _,out _) + &&!DocumentBinding.ReadAssociation(DocumentBinding.AssociationValue(rememberedIdentity,11,"https://fixture.invalid/?token=x"),out _,out _,out _),"invalid identity and non-root saved site are rejected"); var health=new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow.AddMinutes(-3)}; check(ConnectionPresentation.Describe("connected",health,11,"saved-book").Contains("unverified")&&ConnectionPresentation.Describe("connected",health,11,"saved-book").Contains("cached grant"),"expired verification never presents cached sign-in/book as live"); check(ConnectionPresentation.Describe("offline",health,11,"saved-book").Contains("Server/authentication: unverified"),"IPC outage overrides previously successful server state"); @@ -40,9 +49,16 @@ internal static class WorkflowTests Apply(new(){Kind="selection",Start=15,End=15});Apply(new(){Kind="snapshot-begin",SnapshotId=snapshot,End=20}); Apply(new(){Kind="snapshot-fragment",SnapshotId=snapshot,Fragment=new(){ParagraphIndex=1,Start=0,End=10,Text="Chapter",OutlineLevel=1,MarkerTags=["PD-CHAPTER-10"],CompletesParagraph=true}}); Apply(new(){Kind="snapshot-fragment",SnapshotId=snapshot,Fragment=new(){ParagraphIndex=2,Start=10,End=20,Text="Scene",OutlineLevel=2,MarkerTags=["_PD_SCENE_20"],CompletesParagraph=true}}); - Apply(new(){Kind="snapshot-end",SnapshotId=snapshot}); + check(Apply(new(){Kind="selection",Start=15,End=15}).WordCount==null,"unfinished snapshot reports count unavailable rather than zero"); + var completed=Apply(new(){Kind="snapshot-end",SnapshotId=snapshot}); + check(completed.WordCount==2,"ordinary structural snapshots report a count without explicit analysis"); + check(Apply(new(){Kind="selection",Start=15,End=15}).WordCount==2,"selection reuses completed count without another extraction"); await Wait(()=>Apply(new(){Kind="workspace-status",BookId=11,SnapshotId=thirdBinding,AuthenticationContext=context}).Workspace?.SceneId==20); check(true,"new structural snapshot refreshes saved scene at stationary cursor without a selection event"); + var changed=new DocumentDescriptor{SessionId=third.SessionId,ManuscriptId=third.ManuscriptId,Revision=2}; + var updated=new Message{Kind="document",WordInstanceId=instance,Sequence=++sequence,Documents=[changed]}; + manager.Apply(lease,updated); + check(manager.Apply(lease,new(){Kind="selection",WordInstanceId=instance,SessionId=third.SessionId,Revision=2,Sequence=++sequence,Start=0,End=0}).WordCount==null,"document revision invalidates completed snapshot word count"); manager.Detach(instance,lease); handler.Offline=true;await cloud.CheckConnection();check(cloud.Status().Health?.Server=="offline","server loss clears a previously verified online indicator"); handler.Offline=false;await cloud.CheckConnection();check(cloud.Status().Health?.Server=="online","explicit connection check detects recovery"); diff --git a/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs b/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs index 0c42826f..7d1c7c14 100644 --- a/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs +++ b/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs @@ -79,6 +79,7 @@ namespace PlotDirector.WordAddIn } public void ForgetBookSelection(){rebinding=true;try{books.SelectedIndex=-1;}finally{rebinding=false;}} public int SelectedBook=>books.SelectedItem is CompanionBook book?book.BookId:0; + public void ShowSavedTab(bool intent){tabs.SelectedIndex=intent?3:2;} private AnalysisPage current; public void Render(AnalysisReview review,string connection,Guid document,string documentName,Guid authentication,CompanionBook[] available,string cloud,string aiStatus,IList results,bool running,DocumentBinding binding,ConnectionHealth health,bool workflowSupported) { diff --git a/PlotDirector.NativeCompanion/Vsto/CompanionSettingsWindow.cs b/PlotDirector.NativeCompanion/Vsto/CompanionSettingsWindow.cs new file mode 100644 index 00000000..313754ac --- /dev/null +++ b/PlotDirector.NativeCompanion/Vsto/CompanionSettingsWindow.cs @@ -0,0 +1,97 @@ +using System; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; +using PlotDirector.Companion.Protocol; + +namespace PlotDirector.WordAddIn +{ + public sealed class BookSelectionWindow : Form + { + private readonly WordAdapter adapter; + private readonly Guid session; + private Guid authentication; + private readonly TextBox search=new TextBox{Dock=DockStyle.Fill}; + private readonly ListBox books=new ListBox{Dock=DockStyle.Fill,DisplayMember="Title"}; + private readonly Label status=new Label{AutoSize=true,MaximumSize=new Size(620,0)}; + private readonly Button confirm=new Button{Text="Connect this manuscript",AutoSize=true}; + private readonly CheckBox remember=new CheckBox{Text="Remember this book in the document",AutoSize=true}; + private readonly Timer refresh=new Timer{Interval=500}; + private string bookKey=""; + private int selected; + public BookSelectionWindow(WordAdapter adapter,int selected) + { + this.adapter=adapter;session=adapter.ActiveSession;authentication=adapter.AuthenticationContext;this.selected=selected; + Text="Select PlotDirector book";Font=new Font("Segoe UI",10);AutoScaleMode=AutoScaleMode.Dpi; + Width=700;Height=580;MinimumSize=new Size(540,470); + var layout=new TableLayoutPanel{Dock=DockStyle.Fill,Padding=new Padding(16),ColumnCount=1,RowCount=7}; + layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,100)); + for(var i=0;i<7;i++)layout.RowStyles.Add(new RowStyle(i==3?SizeType.Percent:SizeType.AutoSize,i==3?100:0)); + layout.Controls.Add(new Label{Text="Choose the PlotDirector book for "+adapter.DocumentName,AutoSize=true},0,0); + layout.Controls.Add(status,0,1); + search.Margin=new Padding(0,10,0,6);layout.Controls.Add(search,0,2); + layout.Controls.Add(books,0,3);layout.Controls.Add(remember,0,4); + layout.Controls.Add(new Label{Text="Search by book title above. Connecting a book does not upload manuscript text.\nRemember stores the book, site and document identifier in one custom property. It marks the document modified. Save normally to keep it after reopening. Leaving Remember unchecked keeps the selection for this session and preserves any previously saved association.",AutoSize=true,MaximumSize=new Size(620,0),Margin=new Padding(0,8,0,8)},0,5); + var actions=new FlowLayoutPanel{AutoSize=true,Dock=DockStyle.Fill}; + var check=new Button{Text="Refresh connection",AutoSize=true};check.Click+=(_,__)=>adapter.CheckConnection(); + var connect=new Button{Text="Sign in",AutoSize=true};connect.Click+=(_,__)=>new ConnectWindow(adapter).Show(); + var cancel=new Button{Text="Cancel",AutoSize=true};cancel.Click+=(_,__)=>Close(); + confirm.Click+=(_,__)=>{ + if(books.SelectedItem is CompanionBook book&&adapter.ConfirmBookSelection(session,authentication,book.BookId,remember.Checked))Close(); + }; + actions.Controls.AddRange(new Control[]{confirm,check,connect,cancel});layout.Controls.Add(actions,0,6);Controls.Add(layout); + search.TextChanged+=(_,__)=>{bookKey="";Render();};books.SelectedIndexChanged+=(_,__)=>{if(books.SelectedItem is CompanionBook book)selected=book.BookId;}; + refresh.Tick+=(_,__)=>Render();refresh.Start();Render(); + } + private void Render() + { + if(adapter.ActiveSession!=session){status.Text="The active manuscript changed. Close this window and select a book for that document.";confirm.Enabled=false;return;} + if(authentication!=adapter.AuthenticationContext){authentication=adapter.AuthenticationContext;selected=0;bookKey="";} + var available=adapter.AccessibleBooks??Array.Empty(); + var filtered=available.Where(b=>(b.Title??"").IndexOf(search.Text.Trim(),StringComparison.CurrentCultureIgnoreCase)>=0).OrderBy(b=>b.Title).ToArray(); + var key=authentication+"|"+string.Join("|",filtered.Select(b=>b.BookId+":"+b.Title)); + if(key!=bookKey) + { + bookKey=key;var previous=selected;books.DataSource=filtered; + books.SelectedIndex=Array.FindIndex(filtered,b=>b.BookId==previous); + selected=previous; + } + confirm.Enabled=adapter.CanSelectBook&&books.SelectedItem is CompanionBook; + status.Text=adapter.CanSelectBook?available.Length+" accessible books. Current book: "+adapter.BookTitle: + "Sign in and refresh connection to load books you can access. "+adapter.CloudState; + } + protected override void Dispose(bool disposing){if(disposing)refresh.Dispose();base.Dispose(disposing);} + } + + public sealed class CompanionSettingsWindow : Form + { + private readonly WordAdapter adapter; + private readonly TextBox summary=new TextBox{Multiline=true,ReadOnly=true,Dock=DockStyle.Fill,ScrollBars=ScrollBars.Vertical}; + private readonly Timer refresh=new Timer{Interval=1000}; + public CompanionSettingsWindow(WordAdapter adapter) + { + this.adapter=adapter;Text="PlotDirector settings";Font=new Font("Segoe UI",10);AutoScaleMode=AutoScaleMode.Dpi; + Width=720;Height=560;MinimumSize=new Size(560,430); + var layout=new TableLayoutPanel{Dock=DockStyle.Fill,Padding=new Padding(16),ColumnCount=1,RowCount=2}; + layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,100));layout.RowStyles.Add(new RowStyle(SizeType.Percent,100));layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));layout.Controls.Add(summary,0,0); + var actions=new FlowLayoutPanel{AutoSize=true,Dock=DockStyle.Fill,WrapContents=true}; + Add(actions,"Sign in / account",()=>new ConnectWindow(adapter).Show()); + Add(actions,"Select / change book",()=>adapter.ShowBookSelection()); + Add(actions,"Check connection",adapter.CheckConnection); + Add(actions,"Reconnect local agent",adapter.Reconnect); + Add(actions,"Sign out",adapter.SignOut); + Add(actions,"Close",Close); + layout.Controls.Add(actions,0,1);Controls.Add(layout);refresh.Tick+=(_,__)=>Render();refresh.Start();Render(); + } + private static void Add(FlowLayoutPanel panel,string text,Action action){var button=new Button{Text=text,AutoSize=true};button.Click+=(_,__)=>action();panel.Controls.Add(button);} + private void Render() + { + var text="ACCOUNT AND CONNECTION\r\n"+adapter.ServerUrl+"\r\n"+adapter.CloudState+"\r\nLocal agent: "+adapter.ConnectionState+ + "\r\n\r\nCURRENT MANUSCRIPT\r\n"+adapter.DocumentName+"\r\nBook: "+adapter.BookTitle+"\r\n"+adapter.LocationSummary+"\r\n"+adapter.WordCountSummary+ + "\r\n\r\nREMEMBERING THIS BOOK\r\n"+adapter.AssociationSummary+ + "\r\n\r\nANALYSIS AND SAVED INFORMATION\r\nReview structure detects chapters and scenes locally. Double-click a result to navigate. AI chapter review requires a separate explicit upload confirmation. Context and Intent show saved PlotDirector information for authorised markers; unmatched structure needs review.\r\n\r\nAutomatic prose synchronisation is unavailable. Book selection does not upload text or import records. Open PlotDirector to view this book in your browser. Views opened here stay on the chosen book."; + if(summary.Text!=text)summary.Text=text; + } + protected override void Dispose(bool disposing){if(disposing)refresh.Dispose();base.Dispose(disposing);} + } +} diff --git a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs index 73b1d6c2..baa81020 100644 --- a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs +++ b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs @@ -18,8 +18,16 @@ namespace PlotDirector.WordAddIn { using (var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("PlotDirector.WordAddIn.Ribbon.xml"))) return reader.ReadToEnd(); } public void OnLoad(Office.IRibbonUI ribbonUI) { ui = ribbonUI; } public void Invalidate() { try { ui?.Invalidate(); } catch(COMException) { } } - public string GetStatus(Office.IRibbonControl _) => string.Join(" · ",(getAdapter()?.StatusSummary??"Word add-in unavailable").Split('·').Take(3)); - public string GetScopeStatus(Office.IRibbonControl _) => string.Join(" · ",(getAdapter()?.StatusSummary??"").Split('·').Skip(3)); + public string GetStatus(Office.IRibbonControl _) => getAdapter()?.ConnectionLabel??"PlotDirector unavailable"; + public string GetScopeStatus(Office.IRibbonControl _) => Compact(getAdapter()?.BookTitle??"Select Book"); + public string GetLocation(Office.IRibbonControl _) => Compact(getAdapter()?.LocationSummary??"Open a manuscript"); + private static string Compact(string value)=>value.Length>75?value.Substring(0,72)+"…":value; + public bool HasDocument(Office.IRibbonControl _) => getAdapter()?.HasActiveDocument==true; + public bool CanOpenWorkspace(Office.IRibbonControl _) => getAdapter()?.CanOpenWorkspace==true; + public void SelectBook(Office.IRibbonControl _) => getAdapter()?.ShowBookSelection(); + public void Workspace(Office.IRibbonControl _) => getAdapter()?.OpenBookWorkspace(); + public void Context(Office.IRibbonControl _) => getAdapter()?.ShowContext(); + public void Intent(Office.IRibbonControl _) => getAdapter()?.ShowIntent(); public bool CanSynchronize(Office.IRibbonControl _) => getAdapter()?.HasActiveDocument == true&&getAdapter()?.ConnectionState=="connected"; public bool CanCancel(Office.IRibbonControl _) => getAdapter()?.HasActiveWork==true; public void Connect(Office.IRibbonControl _) { var adapter=getAdapter();if(adapter!=null)new ConnectWindow(adapter).Show(); } @@ -28,9 +36,7 @@ namespace PlotDirector.WordAddIn public void Synchronize(Office.IRibbonControl _) { getAdapter()?.AnalyseDocument(); } public void Settings(Office.IRibbonControl _) { - if (getAdapter() == null) return; - var choice = MessageBox.Show("Local analysis and Manual structural refresh are available. AI scene review requires explicit chapter upload. Automatic / On Save prose synchronization is not available.\n\nPersist a native identity in this document's metadata? This will mark the document modified; it will not save or change prose. Existing Office.js bindings are untouched.","PlotDirector Settings",MessageBoxButtons.YesNo); - if (choice == DialogResult.Yes) getAdapter().PersistNativeIdentity(); + getAdapter()?.ShowSettings(); } public void Diagnostics(Office.IRibbonControl _) => MessageBox.Show(getAdapter()?.Diagnostics ?? "Companion did not initialize. Word remains usable. Check the Windows validation prerequisites.","PlotDirector Diagnostics — Nick Beckley"); } diff --git a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj index 61e399e3..5cc22c4e 100644 --- a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj +++ b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj @@ -23,7 +23,7 @@ PlotDirector.Companion.Protocol PlotDirector.Companion.Client ThisAddIn.cs - + ThisAddIn.cs diff --git a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs index 70c3f7c4..4060ee9e 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.6")] -[assembly: AssemblyFileVersion("1.0.0.6")] +[assembly: AssemblyVersion("1.0.0.7")] +[assembly: AssemblyFileVersion("1.0.0.7")] [assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml index d6173393..c211df45 100644 --- a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml +++ b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml @@ -1,11 +1,22 @@ - + -