Expose native book connection workflow and consented document persistence

This commit is contained in:
nick 2026-11-05 20:17:03 +00:00
parent 6bb5b0ffde
commit 8a658eaa8c
16 changed files with 336 additions and 29 deletions

View File

@ -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.

View File

@ -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<StructureSuggestion> 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;

View File

@ -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<Guid,DocumentState> 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<StructuralBoundary> 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<ParagraphFragment> 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<StructuralBoundary> 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<ParagraphFragment> Fragments = []; }
}
public sealed record StructuralBoundary(int Start, int? ChapterId, int? SceneId, string ChapterTitle, string SceneTitle);

View File

@ -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<CompanionBook> 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;}

View File

@ -1 +1 @@
<Project><PropertyGroup><ApplicationVersion>1.0.0.6</ApplicationVersion></PropertyGroup></Project>
<Project><PropertyGroup><ApplicationVersion>1.0.0.7</ApplicationVersion></PropertyGroup></Project>

View File

@ -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]

View File

@ -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;}

View File

@ -8,6 +8,15 @@ internal static class WorkflowTests
{
public static async Task Run(Action<bool,string> 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");

View File

@ -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<StructureSuggestion> results,bool running,DocumentBinding binding,ConnectionHealth health,bool workflowSupported)
{

View File

@ -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<CompanionBook>();
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);}
}
}

View File

@ -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");
}

View File

@ -23,7 +23,7 @@
<ProjectReference Include="..\Protocol\PlotDirector.Companion.Protocol.csproj"><Name>PlotDirector.Companion.Protocol</Name></ProjectReference>
<ProjectReference Include="..\Client\PlotDirector.Companion.Client.csproj"><Name>PlotDirector.Companion.Client</Name></ProjectReference>
<Compile Include="ThisAddIn.cs" /><Compile Include="ThisAddIn.Designer.cs"><DependentUpon>ThisAddIn.cs</DependentUpon></Compile>
<Compile Include="WordAdapter.cs" /><Compile Include="AnalysisWindow.cs" /><Compile Include="ConnectWindow.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="WordAdapter.cs" /><Compile Include="AnalysisWindow.cs" /><Compile Include="ConnectWindow.cs" /><Compile Include="CompanionSettingsWindow.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
<None Include="ThisAddIn.Designer.xml"><DependentUpon>ThisAddIn.cs</DependentUpon></None>
<EmbeddedResource Include="Ribbon.xml" />
</ItemGroup>

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.6")]
[assembly: AssemblyFileVersion("1.0.0.6")]
[assembly: AssemblyVersion("1.0.0.7")]
[assembly: AssemblyFileVersion("1.0.0.7")]
[assembly: ComVisible(false)]

View File

@ -1,11 +1,22 @@
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="OnLoad">
<ribbon><tabs><tab id="PlotDirectorTab" label="PlotDirector">
<group id="PlotDirectorConnection" label="Word Companion">
<group id="PlotDirectorConnection" label="Connection">
<labelControl id="PlotDirectorStatus" getLabel="GetStatus" />
<labelControl id="PlotDirectorScopeStatus" getLabel="GetScopeStatus" />
<button id="PlotDirectorConnect" label="Connect / Sign In" imageMso="ConnectToExternalData" onAction="Connect" screentip="Reconnect local agent" supertip="Approve a short-lived native connection in your browser. No passwords are stored in Word." />
<button id="PlotDirectorAnalyse" label="Analyse" imageMso="ReviewShowMarkup" onAction="Analyse" getEnabled="CanSynchronize" supertip="Detect local structure, then explicitly select chapters for AI scene analysis. No import or manuscript changes." />
</group>
<group id="PlotDirectorManuscript" label="This manuscript">
<labelControl id="PlotDirectorScopeStatus" getLabel="GetScopeStatus" />
<labelControl id="PlotDirectorLocation" getLabel="GetLocation" />
<button id="PlotDirectorSelectBook" label="Select Book" size="large" imageMso="FileOpen" onAction="SelectBook" getEnabled="HasDocument" supertip="Search your accessible PlotDirector books and explicitly connect this manuscript. Remembering the association requires your consent." />
<button id="PlotDirectorWorkspace" label="Open PlotDirector" imageMso="HyperlinkInsert" onAction="Workspace" getEnabled="CanOpenWorkspace" />
<button id="PlotDirectorContext" label="Context" imageMso="Info" onAction="Context" getEnabled="HasDocument" />
<button id="PlotDirectorIntent" label="Intent" imageMso="ReviewShowMarkup" onAction="Intent" getEnabled="HasDocument" />
</group>
<group id="PlotDirectorReview" label="Structure and analysis">
<button id="PlotDirectorAnalyse" label="Review structure" size="large" imageMso="ReviewShowMarkup" onAction="Analyse" getEnabled="CanSynchronize" supertip="Read chapters and scenes locally and double-click to navigate. AI review requires a separate chapter upload confirmation." />
<button id="PlotDirectorCancelAnalysis" label="Cancel Analysis" imageMso="CancelRequest" onAction="Cancel" getEnabled="CanCancel" />
</group>
<group id="PlotDirectorOptions" label="Options">
<button id="PlotDirectorSettings" label="Settings" imageMso="PropertySheet" onAction="Settings" />
<button id="PlotDirectorDiagnostics" label="Diagnostics" imageMso="Info" onAction="Diagnostics" />
</group>

View File

@ -49,6 +49,8 @@ namespace PlotDirector.WordAddIn
private int documentCollectionGeneration;
private double lastBatchMs;
private AnalysisWindow analysisWindow;
private CompanionSettingsWindow settingsWindow;
private BookSelectionWindow bookWindow;
private Guid cloudContext;
private ConnectionHealth cloudHealth;
private bool workflowSupported;
@ -63,9 +65,10 @@ namespace PlotDirector.WordAddIn
public string ConnectionState { get; private set; } = "Connecting";
public bool HasActiveDocument => active != null;
public bool HasActiveWork => active!=null&&(active.Review.Running||active.AiJob!=Guid.Empty||active.Binding.Preview?.State=="loading");
public string Diagnostics => "PlotDirector by Nick Beckley — Phase 3\nAgent: " + ConnectionState
public string Diagnostics => "PlotDirector " + typeof(WordAdapter).Assembly.GetName().Version + "\nAgent: " + ConnectionState
+ "\nServer: "+cloudState+" · Prose sync: unavailable\nOpen sessions: " + documents.Count
+ "\nIPC queued: " + link.QueueDepth + "\nWord work queued: " + scheduler.Depth
+ "\nMain document words: " + WordCountSummary
+ "\nLast UI batch ms: " + lastBatchMs.ToString("F2") + "\nMax recorded COM call ms: " + (operationTimes.Count == 0 ? 0 : operationTimes.Max()).ToString("F2")
+ "\nCOM busy/errors: " + busyFailures + (lastWordError == null ? "" : " (last: " + lastWordError + ")") + "\n" + lastResult;
@ -94,13 +97,13 @@ namespace PlotDirector.WordAddIn
});
link.Received += message => {
if(message.Kind=="cloud-status")
{PostToUi(()=>{if(cloudContext!=message.AuthenticationContext){foreach(var doc in documents.Values)if(doc.AiJob!=Guid.Empty||doc.AiQueue.Count>0)StopAi(doc,"Connection/account changed. Review and confirm chapters again.");analysisWindow?.ForgetBookSelection();}if(cloudContext!=message.AuthenticationContext)foreach(var doc in documents.Values)doc.Binding.Reset();cloudContext=message.AuthenticationContext;cloudHealth=message.Health;cloudState=message.Status;cloudBooks=message.Books;serverUrl=message.ServerUrl;reviewDirty=true;invalidateRibbon();});return;}
{PostToUi(()=>{if(cloudContext!=message.AuthenticationContext){foreach(var doc in documents.Values)if(doc.AiJob!=Guid.Empty||doc.AiQueue.Count>0)StopAi(doc,"Connection/account changed. Review and confirm chapters again.");analysisWindow?.ForgetBookSelection();}if(cloudContext!=message.AuthenticationContext)foreach(var doc in documents.Values)doc.Binding.Reset();cloudContext=message.AuthenticationContext;cloudHealth=message.Health;cloudState=message.Status;cloudBooks=message.Books??Array.Empty<CompanionBook>();serverUrl=message.ServerUrl;RestoreAssociations();reviewDirty=true;invalidateRibbon();});return;}
if(message.Status=="ready")PostToUi(()=>{analysisSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.AnalysisCapability);cloudSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterAiCapability);workflowSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.WorkflowCapability);});
if(message.Kind=="workspace-response")
{PostToUi(()=>{var doc=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);if(doc!=null){if(message.Status=="authentication-changed")doc.Binding.Reset();else doc.Binding.Accept(message);reviewDirty=true;invalidateRibbon();}});return;}
// Bound/coalesce progress independently of the Word message pump.
// Never accumulate one BeginInvoke callback per manuscript fragment.
if(message.SessionId!=Guid.Empty&&message.SnapshotId!=Guid.Empty)
if(message.SessionId!=Guid.Empty&&(message.SnapshotId!=Guid.Empty||message.WordCount.HasValue))
lock(reviewGate)
{
if(reviewReplies.TryGetValue(message.SessionId,out var prior))
@ -126,7 +129,8 @@ namespace PlotDirector.WordAddIn
scheduler.Measured += (_, elapsed) => lastBatchMs = elapsed;
scheduler.Failed += error => {
busyFailures++;
lastWordError = error.GetType().Name + " 0x" + error.HResult.ToString("X8");
var frame=new StackTrace(error,true).GetFrames()?.FirstOrDefault(f=>f.GetMethod()?.DeclaringType?.FullName?.Contains("WordAdapter")==true);
lastWordError = error.GetType().Name + " 0x" + error.HResult.ToString("X8") + " · " + (error.Data["WordOperation"]??frame?.GetMethod()?.Name??error.TargetSite?.Name??"Word callback")+" line "+(frame?.GetFileLineNumber()??0);
foreach(var doc in documents.Values)if(doc.Review.Running)
{CancelExtraction(doc);doc.NeedsSnapshot=false;doc.Review.Stop("Word could not finish this operation. Try analysis again; see Diagnostics.");}
reviewDirty=true;
@ -156,6 +160,7 @@ namespace PlotDirector.WordAddIn
if(Environment.CurrentManagedThreadId!=ownerThread)throw new InvalidOperationException("Cross-thread Word access refused.");
var watch = Stopwatch.StartNew();
try { return read(); }
catch(Exception error){error.Data["WordOperation"]=operation;throw;}
finally { if(operationTimes.Count == 256)operationTimes.Dequeue(); operationTimes.Enqueue(watch.Elapsed.TotalMilliseconds);Metric(operation,watch.Elapsed.TotalMilliseconds); }
}
private void DiscoverOpenDocuments() => DiscoverAt(1);
@ -177,6 +182,7 @@ namespace PlotDirector.WordAddIn
}
private void Open(Word.Document document)
{
if(document==null)return;
if (documents.ContainsKey(document) || documents.Count >= ProtocolVersion.MaxDocuments || !pendingOpen.Add(document)) return;
documentCollectionGeneration++;
if (!scheduler.Post("open:" + Guid.NewGuid().ToString("N"), () => {
@ -188,8 +194,12 @@ namespace PlotDirector.WordAddIn
state.IdentityPersisted = ReadGuidProperty(document,"PlotDirector.Native.DocumentGuid").HasValue;
state.ProjectId = ReadPositiveProperty(document,"PlotDirector.Native.ProjectID");
state.BookId = ReadPositiveProperty(document,"PlotDirector.Native.BookID");
state.AssociationSite=ReadProperty(document,"PlotDirector.Native.ServerUrl");
if(DocumentBinding.ReadAssociation(ReadProperty(document,DocumentBinding.AssociationProperty),out var identity,out var rememberedBook,out var rememberedSite))
{state.Identity=identity;state.IdentityPersisted=true;state.BookId=rememberedBook;state.AssociationSite=rememberedSite;}
state.End = DocumentEnd(document); state.WasSaved = Com(() => document.Saved);
documents.Add(document,state); RegisterState(state);
RestoreAssociations();
ScheduleSelection();
})) pendingOpen.Remove(document);
}
@ -209,9 +219,12 @@ namespace PlotDirector.WordAddIn
try
{
selection = Com(() => application.Selection);
if(selection==null){active=null;invalidateRibbon();return;}
var document = Com(() => selection.Document);
if(document==null){active=null;invalidateRibbon();return;}
if (!documents.TryGetValue(document,out var state)) { Open(document); return; }
range = Com(() => selection.Range);
if(range==null)return;
var start = Com(() => range.Start); var end = Com(() => range.End);
var documentEnd = DocumentEnd(document); var saved = Com(() => document.Saved);
if (documentEnd != state.End || (state.WasSaved && !saved))
@ -219,6 +232,7 @@ namespace PlotDirector.WordAddIn
StopAi(state,"Document changed. Detect structure again before AI analysis.");state.AiResults.Clear();
state.Review.Stop("Document changed. Analyse again to refresh suggestions.");reviewDirty=true;
state.End = documentEnd; state.Revision++; state.NeedsSnapshot = true;
state.WordCount=null;state.ChapterTitle="";state.SceneTitle="";
CancelExtraction(state); RegisterState(state);
}
state.WasSaved = saved;
@ -242,12 +256,14 @@ namespace PlotDirector.WordAddIn
Revision=doc.Revision,IdentityPersisted=doc.IdentityPersisted,AssociationVerified=false
};
public void AnalyseDocument()
{ShowReview(true);}
private void ShowReview(bool analyse)
{
if(active==null)return;
if(analysisWindow==null||analysisWindow.IsDisposed)
analysisWindow=new AnalysisWindow(()=>StartAnalysis(true),CancelAnalysis,RequestAnalysisPage,StartAi,Navigate,SelectBook,PreviewImport,OpenWorkspace,CheckConnection);
analysisWindow.Show();analysisWindow.BringToFront();
if(active.Review.Page==null&&!active.Review.Running)StartAnalysis(false);
if(analyse&&active.Review.Page==null&&!active.Review.Running)StartAnalysis(false);
RenderReview();
}
private void StartAnalysis(bool refresh)
@ -478,7 +494,15 @@ namespace PlotDirector.WordAddIn
Message[] responses;
lock(reviewGate){responses=reviewReplies.Values.Take(4).ToArray();foreach(var response in responses)reviewReplies.Remove(response.SessionId);}
foreach(var response in responses)
{var doc=documents.Values.FirstOrDefault(d=>d.Session==response.SessionId);if(doc!=null){if(doc.AiJob==response.SnapshotId&&doc.AiJob!=Guid.Empty)AcceptAi(doc,response);else if(doc.Review.Accept(response))reviewDirty=true;}}
{
var doc=documents.Values.FirstOrDefault(d=>d.Session==response.SessionId&&d.Revision==response.Revision);
if(doc==null)continue;
if(response.WordCount.HasValue)doc.WordCount=response.WordCount;
if(response.Kind=="response"&&(response.WordCount.HasValue||!string.IsNullOrEmpty(response.ChapterTitle)))
{doc.ChapterTitle=response.ChapterTitle;doc.SceneTitle=response.SceneTitle;invalidateRibbon();}
if(doc.AiJob==response.SnapshotId&&doc.AiJob!=Guid.Empty)AcceptAi(doc,response);
else if(doc.Review.Accept(response))reviewDirty=true;
}
if(reviewDirty&&reviewClock.ElapsedMilliseconds>=250){reviewClock.Restart();RenderReview();}
if(!disposed&&active!=null&&ConnectionState=="connected"&&metricClock.ElapsedMilliseconds>=1000)
{
@ -495,6 +519,9 @@ namespace PlotDirector.WordAddIn
public string ServerUrl=>serverUrl;
public string CloudState=>cloudState;
public string StatusSummary=>ConnectionPresentation.Describe(ConnectionState,cloudHealth,active?.Binding.BookId??0,active?.Binding.Workspace.State??"unselected");
public string ConnectionLabel => ConnectionState!="connected"?"Connecting local agent…":
cloudHealth?.Authentication!="verified"?"Sign in to PlotDirector":
cloudHealth.Server!="online"||DateTime.UtcNow-cloudHealth.VerifiedUtc>=TimeSpan.FromSeconds(90)?"Check server connection":"Connected to PlotDirector";
public void CheckConnection(){if(cloudSupported)link.TryPost(new Message{Kind="cloud-check"});if(active?.Binding.BookId>0)WorkspacePost(active,"workspace-refresh");}
public void SignOut(){foreach(var doc in documents.Values)StopAi(doc,"Signed out. Successful results retained.");link.TryPost(new Message{Kind="cloud-signout"});}
private void RegisterState(LocalDocument doc)
@ -502,9 +529,66 @@ namespace PlotDirector.WordAddIn
var book=doc.Binding.BookId;link.Register(Descriptor(doc));
if(book>0){doc.Binding.Select(book,cloudContext);WorkspacePost(doc,"workspace-select");}
}
private void SelectBook(int book)
private void SelectBook(int book) => ShowBookSelection(book);
public Guid ActiveSession => active?.Session??Guid.Empty;
public Guid AuthenticationContext => cloudContext;
public CompanionBook[] AccessibleBooks => cloudBooks;
public bool CanSelectBook => active!=null&&ConnectionState=="connected"&&workflowSupported&&cloudHealth?.Authentication=="verified"&&cloudHealth.Server=="online"&&DateTime.UtcNow-cloudHealth.VerifiedUtc<TimeSpan.FromSeconds(90);
public bool CanOpenWorkspace => CanSelectBook&&active?.Binding.Workspace.State?.StartsWith("saved-",StringComparison.Ordinal)==true;
public string DocumentName => active?.DisplayName??"No document open";
public string BookTitle => active==null?"No document open":cloudBooks.FirstOrDefault(b=>b.BookId==active.Binding.BookId)?.Title??"Select Book to connect this manuscript";
public string LocationSummary => active==null?"Open a document":
!string.IsNullOrEmpty(active.Binding.Workspace.Title)&&active.Binding.Workspace.State!="saved-book"?active.Binding.Workspace.Title:
string.Join(" / ",new[]{active.ChapterTitle,active.SceneTitle}.Where(t=>!string.IsNullOrWhiteSpace(t))).Length>0?
string.Join(" / ",new[]{active.ChapterTitle,active.SceneTitle}.Where(t=>!string.IsNullOrWhiteSpace(t))):"Chapter / scene not yet detected";
public string WordCountSummary => active==null?"unavailable (no document)":active.WordCount.HasValue?active.WordCount.Value.ToString("N0")+" approximate words in the latest snapshot":"unavailable until local reading completes";
public string AssociationSummary => active==null?"Open a manuscript to select a book.":
active.BookId>0&&active.IdentityPersisted?"A book association is stored in this document. Save normally after changing it. Access is checked again after sign-in.":
"Book selection lasts for this Word session. Select Book offers an explicit option to remember it in document metadata.";
public void ShowSettings()
{if(settingsWindow==null||settingsWindow.IsDisposed)settingsWindow=new CompanionSettingsWindow(this);settingsWindow.Show();settingsWindow.BringToFront();}
public void ShowBookSelection(int suggested=0)
{
if(active==null){MessageBox.Show("Open a manuscript first.","Select PlotDirector book");return;}
if(bookWindow!=null&&!bookWindow.IsDisposed){bookWindow.BringToFront();return;}
bookWindow=new BookSelectionWindow(this,suggested>0?suggested:active.Binding.BookId);bookWindow.Show();
CheckConnection();
}
public void ShowContext(){ShowReview(false);analysisWindow?.ShowSavedTab(false);}
public void ShowIntent(){ShowReview(false);analysisWindow?.ShowSavedTab(true);}
public void OpenBookWorkspace()=>OpenWorkspace("book");
public bool ConfirmBookSelection(Guid session,Guid authentication,int book,bool remember)
{
var doc=active;
if(doc==null||doc.Session!=session||cloudContext!=authentication||!CanSelectBook||!cloudBooks.Any(b=>b.BookId==book))
{MessageBox.Show("Document, account or available books changed. Check connection and select the book again.","PlotDirector");return false;}
if(remember)
{
var site=serverUrl;
if(!scheduler.Post("association:"+doc.Session,()=>{
if(active!=doc||cloudContext!=authentication||!CanSelectBook)return;
if(Com(()=>doc.Document.ReadOnly)){MessageBox.Show("This document is read-only. Select the book without Remember, or use a writable copy.","PlotDirector");return;}
// One metadata value keeps identity, site and book consistent if an operation fails.
try{WriteProperty(doc.Document,DocumentBinding.AssociationProperty,DocumentBinding.AssociationValue(doc.Identity,book,site),Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString);}
catch(Exception error) when(error is COMException||error is ArgumentException||error is InvalidOperationException)
{MessageBox.Show("Word could not remember the book in this document. You can select it again with Remember unchecked for this session. Nothing was uploaded or saved.","PlotDirector");throw;}
doc.IdentityPersisted=true;doc.BookId=book;doc.AssociationSite=site;
ApplyBookSelection(doc,book);link.Register(Descriptor(doc));
MessageBox.Show("Book connected. Save the document normally to remember this association after reopening. No manuscript text was uploaded.","PlotDirector");
})){MessageBox.Show("Word is busy. Please select the book again.","PlotDirector");return false;}
}
else ApplyBookSelection(doc,book);
return true;
}
private void RestoreAssociations()
{
if(!workflowSupported||cloudHealth?.Authentication!="verified"||cloudHealth.Server!="online"||DateTime.UtcNow-cloudHealth.VerifiedUtc>=TimeSpan.FromSeconds(90))return;
foreach(var doc in documents.Values)
if(doc.Binding.BookId==0&&doc.IdentityPersisted&&DocumentBinding.CanRestore(doc.BookId??0,doc.AssociationSite,serverUrl,cloudBooks))
ApplyBookSelection(doc,doc.BookId.Value);
}
private void ApplyBookSelection(LocalDocument doc,int book)
{
var doc=active;if(doc==null)return;
if(doc.Binding.BookId==book&&doc.Binding.AuthenticationContext==cloudContext)return;
StopAi(doc,"Book selection changed; confirm AI chapters again.");doc.AiStatus=null;
doc.Binding.Select(book,cloudContext);WorkspacePost(doc,"workspace-select");reviewDirty=true;invalidateRibbon();
@ -652,23 +736,41 @@ namespace PlotDirector.WordAddIn
return "";
}
dynamic value = property;
if(property==null)return "";
return Com<string>(() => Convert.ToString(value.Value));
}
catch(COMException){return "";}finally{Release(property);Release(properties);}
}
private void WriteProperty(Word.Document document,string name,object value,Microsoft.Office.Core.MsoDocProperties type)
{
object properties=null,property=null;
try
{
properties=Com(()=>document.CustomDocumentProperties);
dynamic collection=properties;
try{property=Com<object>(()=>collection[name]);}
catch(ArgumentException error) when(error.HResult==unchecked((int)0x80070057)){}
catch(COMException error) when(error.HResult==unchecked((int)0x8002000B)||error.HResult==unchecked((int)0x80070057)){}
if(property==null)property=Com<object>(()=>collection.Add(name,false,type,value));
else {dynamic existing=property;Com(()=>{existing.Value=value;return true;});}
}
finally{Release(property);Release(properties);}
}
private static void Release(object value) {if(value!=null&&Marshal.IsComObject(value))Marshal.ReleaseComObject(value);}
public void Dispose()
{
if(disposed)return;disposed=true;timer.Stop();timer.Dispose();scheduler.Clear();
events.DocumentOpen-=Open;events.NewDocument-=Open;events.DocumentChange-=ScheduleSelection;events.WindowActivate-=Activate;
events.WindowSelectionChange-=SelectionChanged;events.DocumentBeforeClose-=BeforeClose;events.DocumentBeforeSave-=BeforeSave;
analysisWindow?.Dispose();link.Dispose();documents.Clear();pendingOpen.Clear();closing.Clear();dispatch.Dispose();
analysisWindow?.Dispose();settingsWindow?.Dispose();bookWindow?.Dispose();link.Dispose();documents.Clear();pendingOpen.Clear();closing.Clear();dispatch.Dispose();
}
private sealed class LocalDocument
{
public readonly Word.Document Document;public readonly Guid Session=Guid.NewGuid();public Guid Identity;public bool IdentityPersisted;
public readonly DocumentBinding Binding=new DocumentBinding();
public string DisplayName;
public string AssociationSite="",ChapterTitle="",SceneTitle="";
public int? WordCount;
public readonly AnalysisReview Review=new AnalysisReview();
public readonly Queue<StructureSuggestion> AiQueue=new Queue<StructureSuggestion>();
public readonly List<StructureSuggestion> AiResults=new List<StructureSuggestion>();

View File

@ -11,10 +11,12 @@ try {
$dirty=& git status --porcelain=v1;if($LASTEXITCODE -ne 0){throw 'Cannot inspect Git status.'}
if($dirty){throw 'Working tree has local changes. Preserve/commit them before updating; nothing was discarded.'}
$scriptHash=(Get-FileHash -Algorithm SHA256 -LiteralPath $PSCommandPath).Hash
Invoke-Checked git @('fetch','origin')
$ahead=(& git rev-list --left-right --count "HEAD...origin/$sharedBranch") -split '\s+'
$remote=(& git config --get "branch.$sharedBranch.remote").Trim()
if($LASTEXITCODE -ne 0 -or !$remote -or $remote -eq '.'){throw 'The shared branch must have an external tracking remote configured. No remote was guessed.'}
Invoke-Checked git @('fetch',$remote)
$ahead=(& git rev-list --left-right --count "HEAD...$remote/$sharedBranch") -split '\s+'
if($LASTEXITCODE -ne 0 -or [int]$ahead[0] -gt 0){throw 'Local commits are not on the shared remote branch. Push/reconcile them safely before updating.'}
Invoke-Checked git @('merge','--ff-only',"origin/$sharedBranch")
Invoke-Checked git @('merge','--ff-only',"$remote/$sharedBranch")
if((Get-FileHash -Algorithm SHA256 -LiteralPath $PSCommandPath).Hash -ne $scriptHash){& $PSCommandPath @PSBoundParameters;return}
Invoke-Checked git @('merge-base','--is-ancestor','726a3d5','HEAD')
$commit=(& git rev-parse HEAD).Trim();if($LASTEXITCODE -ne 0){throw 'Cannot read commit SHA.'}