644 lines
43 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using Message = PlotDirector.Companion.Protocol.Message;
using PlotDirector.Companion.Client;
using PlotDirector.Companion.Protocol;
using Word = Microsoft.Office.Interop.Word;
namespace PlotDirector.WordAddIn
{
// This object and every retained RCW are owned exclusively by Word's UI thread.
// AgentLink sees only fresh value DTOs. It never receives this object as a callback.
public sealed class WordAdapter : IDisposable
{
private readonly int ownerThread = Environment.CurrentManagedThreadId;
private readonly Word.Application application;
private readonly Word.ApplicationEvents4_Event events;
private readonly Dictionary<Word.Document, LocalDocument> documents = new Dictionary<Word.Document,LocalDocument>();
private readonly HashSet<Word.Document> pendingOpen = new HashSet<Word.Document>();
private readonly HashSet<Word.Document> closing = new HashSet<Word.Document>();
private readonly WordAccessScheduler scheduler = new WordAccessScheduler();
private readonly Control dispatch = new Control();
private readonly Timer timer = new Timer { Interval = 25 };
private readonly AgentLink link;
private readonly Action invalidateRibbon;
private readonly Queue<double> operationTimes = new Queue<double>();
private readonly Queue<UiMetric> pendingMetrics = new Queue<UiMetric>();
private readonly Stopwatch tickClock = Stopwatch.StartNew();
private readonly Stopwatch metricClock = Stopwatch.StartNew();
private void Metric(string name,double milliseconds)
{
if(pendingMetrics.Count==256)pendingMetrics.Dequeue();
pendingMetrics.Enqueue(new UiMetric{Operation=name,Milliseconds=milliseconds});
}
private UiMetric[] DrainMetrics()
{
var values=new List<UiMetric>();
while(values.Count<32&&pendingMetrics.Count>0)values.Add(pendingMetrics.Dequeue());
return values.ToArray();
}
private LocalDocument active;
private bool disposed;
private long busyFailures;
private string lastWordError;
private int documentCollectionGeneration;
private double lastBatchMs;
private AnalysisWindow analysisWindow;
private string cloudState="Not signed in",serverUrl="";
private CompanionBook[] cloudBooks=Array.Empty<CompanionBook>();
private bool analysisSupported,cloudSupported;
private readonly Stopwatch reviewClock=Stopwatch.StartNew();
private bool reviewDirty;
private readonly object reviewGate=new object();
private readonly Dictionary<Guid,Message> reviewReplies=new Dictionary<Guid,Message>();
private string lastResult = "Waiting for local structural snapshot";
public string ConnectionState { get; private set; } = "Connecting";
public bool HasActiveDocument => active != null;
public string Diagnostics => "PlotDirector by Nick Beckley — Phase 3\nAgent: " + ConnectionState
+ "\nServer: "+cloudState+" · Prose sync: unavailable\nOpen sessions: " + documents.Count
+ "\nIPC queued: " + link.QueueDepth + "\nWord work queued: " + scheduler.Depth
+ "\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;
public WordAdapter(Word.Application application, Action invalidateRibbon)
{
if(System.Threading.Thread.CurrentThread.GetApartmentState()!=System.Threading.ApartmentState.STA)throw new InvalidOperationException("Word adapter requires the Word STA.");
this.application = application; this.invalidateRibbon = invalidateRibbon;
// Force a handle here; BeginInvoke always returns callbacks to this STA.
var handle = dispatch.Handle;
link = new AgentLink(AgentProcess.PipeName(), Guid.NewGuid(), AgentProcess.VerifyOwner, AgentProcess.Start);
link.StateChanged += state => PostToUi(() => {
ConnectionState = state;
if(state!="connected")
{
analysisSupported=false;cloudSupported=false;
foreach(var doc in documents.Values){StopAi(doc,"Agent disconnected. Successful AI suggestions retained; reconnect before retrying.");scheduler.Cancel("analyse:"+doc.Session);if(doc.Review.Running||doc.Review.SnapshotId!=Guid.Empty)doc.Review.Stop("Agent disconnected. Reconnect and analyse again.");}
}
reviewDirty=true;
if (state == "connected")
{
foreach (var doc in documents.Values) { CancelExtraction(doc); doc.NeedsSnapshot = true; }
ScheduleSelection();
}
invalidateRibbon();
});
link.Received += message => {
if(message.Kind=="cloud-status")
{PostToUi(()=>{cloudState=message.Status;cloudBooks=message.Books;serverUrl=message.ServerUrl;reviewDirty=true;});return;}
if(message.Status=="ready")PostToUi(()=>{analysisSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.AnalysisCapability);cloudSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterAiCapability);});
// 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)
lock(reviewGate)
{
if(reviewReplies.TryGetValue(message.SessionId,out var prior))
{
if(message.Revision>=prior.Revision&&(prior.Analysis==null||message.Analysis!=null||message.Revision>prior.Revision))reviewReplies[message.SessionId]=message;
}
else if(reviewReplies.Count<ProtocolVersion.MaxDocuments)reviewReplies.Add(message.SessionId,message);
}
var description = message.Status + (string.IsNullOrEmpty(message.ChapterTitle) ? "" : " · " + message.ChapterTitle)
+ (string.IsNullOrEmpty(message.SceneTitle) ? "" : " / " + message.SceneTitle);
if (message.Status == "awaiting-structure" && message.SnapshotId == Guid.Empty) return;
if (message.Status != "ok" || !string.IsNullOrEmpty(message.ChapterTitle)) PostToUi(() => {
if (message.Status == "awaiting-structure")
description = "Local structure refreshed. No chapter or scene found at the cursor.";
if(message.Status!="ok"&&message.Status!="ready"&&message.Status!="awaiting-structure"&&message.Status!="analysis-complete"&&message.Status!="ai-cancelled")
{
var failed=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);
if(failed?.Extraction!=null&&failed.Extraction.Snapshot==message.SnapshotId){CancelExtraction(failed);failed.NeedsSnapshot=false;}
}
if(active != null && active.Session == message.SessionId && active.Revision == message.Revision)lastResult = description;
});
};
scheduler.Measured += (_, elapsed) => lastBatchMs = elapsed;
scheduler.Failed += error => {
busyFailures++;
lastWordError = error.GetType().Name + " 0x" + error.HResult.ToString("X8");
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;
scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1));
};
events = (Word.ApplicationEvents4_Event)application;
events.DocumentOpen += Open;
events.NewDocument += Open;
events.DocumentChange += ScheduleSelection;
events.WindowActivate += Activate;
events.WindowSelectionChange += SelectionChanged;
events.DocumentBeforeClose += BeforeClose;
events.DocumentBeforeSave += BeforeSave;
timer.Tick += Tick;
timer.Start(); link.Start();
// Already-open documents are registered in bounded UI actions, not a background COM enumeration.
scheduler.Post("discover", DiscoverOpenDocuments);
}
private void PostToUi(Action callback)
{
if (disposed) return;
try { dispatch.BeginInvoke(new Action(() => { if (!disposed) callback(); })); }
catch(InvalidOperationException) { }
}
private T Com<T>(Func<T> read,[CallerMemberName]string operation="")
{
if(Environment.CurrentManagedThreadId!=ownerThread)throw new InvalidOperationException("Cross-thread Word access refused.");
var watch = Stopwatch.StartNew();
try { return read(); }
finally { if(operationTimes.Count == 256)operationTimes.Dequeue(); operationTimes.Enqueue(watch.Elapsed.TotalMilliseconds);Metric(operation,watch.Elapsed.TotalMilliseconds); }
}
private void DiscoverOpenDocuments() => DiscoverAt(1);
private void DiscoverAt(int index)
{
Word.Documents collection = null;
try
{
collection = Com(() => application.Documents);
var count = Math.Min(ProtocolVersion.MaxDocuments,Com(() => collection.Count));
if(index<=count)
{
var doc=Com(()=>collection[index]);Open(doc);
scheduler.Post("discover",()=>DiscoverAt(index+1));
}
else ScheduleSelection();
}
finally { Release(collection); }
}
private void Open(Word.Document document)
{
if (documents.ContainsKey(document) || documents.Count >= ProtocolVersion.MaxDocuments || !pendingOpen.Add(document)) return;
documentCollectionGeneration++;
if (!scheduler.Post("open:" + Guid.NewGuid().ToString("N"), () => {
pendingOpen.Remove(document);
if (documents.ContainsKey(document) || documents.Count >= ProtocolVersion.MaxDocuments) return;
var state = new LocalDocument(document);
state.DisplayName=Com(()=>document.Name);
state.Identity = ReadGuidProperty(document,"PlotDirector.Native.DocumentGuid") ?? Guid.NewGuid();
state.IdentityPersisted = ReadGuidProperty(document,"PlotDirector.Native.DocumentGuid").HasValue;
state.ProjectId = ReadPositiveProperty(document,"PlotDirector.Native.ProjectID");
state.BookId = ReadPositiveProperty(document,"PlotDirector.Native.BookID");
state.End = DocumentEnd(document); state.WasSaved = Com(() => document.Saved);
documents.Add(document,state); link.Register(Descriptor(state));
ScheduleSelection();
})) pendingOpen.Remove(document);
}
private void Activate(Word.Document document,Word.Window window) { Open(document); ScheduleSelection(); }
private void SelectionChanged(Word.Selection selection) { ScheduleSelection(); }
private void ScheduleSelection()
{
if (disposed) return;
// Repeated events collapse to one read. The event's Selection RCW is not retained.
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(120));
scheduler.Post("selection", CaptureSelection);
if(closing.Count>0)scheduler.Post("retire",ReconcileClosedDocuments);
}
private void CaptureSelection()
{
Word.Selection selection = null; Word.Range range = null;
try
{
selection = Com(() => application.Selection);
var document = Com(() => selection.Document);
if (!documents.TryGetValue(document,out var state)) { Open(document); return; }
range = Com(() => selection.Range);
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))
{
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;
CancelExtraction(state); link.Register(Descriptor(state));
}
state.WasSaved = saved;
if(active!=state)reviewDirty=true;
active = state;
link.TryPost(new Message {Kind="active",SessionId=state.Session,Revision=state.Revision});
link.TryPost(new Message {Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
if(state.NeedsSnapshot && ConnectionState == "connected") ScheduleSnapshot(state);
invalidateRibbon();
}
finally { Release(range); Release(selection); }
}
private int DocumentEnd(Word.Document document)
{
Word.Range range = null;
try { range = Com(() => document.Content); return Com(() => range.End); }
finally { Release(range); }
}
private DocumentDescriptor Descriptor(LocalDocument doc) => new DocumentDescriptor {
SessionId=doc.Session,ManuscriptId=doc.Identity,ProjectId=doc.ProjectId,BookId=doc.BookId,
Revision=doc.Revision,IdentityPersisted=doc.IdentityPersisted,AssociationVerified=false
};
public void AnalyseDocument()
{
if(active==null)return;
if(analysisWindow==null||analysisWindow.IsDisposed)
analysisWindow=new AnalysisWindow(()=>StartAnalysis(true),CancelAnalysis,RequestAnalysisPage,StartAi,Navigate);
analysisWindow.Show();analysisWindow.BringToFront();
if(active.Review.Page==null&&!active.Review.Running)StartAnalysis(false);
RenderReview();
}
private void StartAnalysis(bool refresh)
{
var doc=active;if(doc==null)return;
if(ConnectionState!="connected"||!analysisSupported)
{doc.Review.Stop("Connect an updated local agent to analyse this document.");RenderReview();return;}
if(!refresh&&doc.Review.Page!=null){RenderReview();return;}
StopAi(doc,"Detecting updated local structure.");doc.AiResults.Clear();CancelExtraction(doc);doc.Review.Prepare(doc.Session);reviewDirty=true;
// Refresh the descriptor on the Word scheduler, never from a background callback.
if(!scheduler.Post("analyse:"+doc.Session,()=>{
if(active!=doc||closing.Contains(doc.Document)){doc.Review.Stop("Document switched or closing. Analyse again when ready.");reviewDirty=true;return;}
doc.End=DocumentEnd(doc.Document);doc.Revision++;doc.NeedsSnapshot=true;
link.Register(Descriptor(doc));ScheduleSnapshot(doc,true);RenderReview();
})){doc.Review.Stop("Word queue busy. Try analysis again.");RenderReview();}
}
public void CancelAnalysis()
{
var doc=active;if(doc==null)return;
if(doc.AiJob!=Guid.Empty||doc.AiQueue.Count>0){StopAi(doc,"AI analysis cancelled. Successful chapter results retained.");RenderReview();return;}
scheduler.Cancel("analyse:"+doc.Session);CancelExtraction(doc);doc.NeedsSnapshot=false;
doc.Review.Stop("Analysis cancelled. Nothing was imported or changed.");RenderReview();
}
private void RequestAnalysisPage(int direction)
{
var doc=active;var page=doc?.Review.Page;if(page==null)return;
var offset=page.Offset+direction*ProtocolVersion.AnalysisPageSize;
if(offset<0||offset>=page.Total)return;
doc.Review.ExpectPage(offset);
if(!link.TryPost(new Message{Kind="analysis-page",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Review.SnapshotId,Start=offset}))
lastResult="Agent queue busy. Try the results page again.";
}
private void RenderReview()
{if(analysisWindow!=null&&!analysisWindow.IsDisposed)analysisWindow.Render(active?.Review,ConnectionState,active?.Session??Guid.Empty,active?.DisplayName,cloudBooks,cloudState,active?.AiStatus,active?.AiResults,active!=null&&active.AiJob!=Guid.Empty);reviewDirty=false;}
public void RequestSnapshot()
{
if (active == null) return;
StopAi(active,"Local structure refreshed.");active.AiResults.Clear();
scheduler.Cancel("analyse:"+active.Session);
active.Review.Stop("Structure refreshed. Analyse again to review updated suggestions.");reviewDirty=true;
lastResult = ConnectionState == "connected" ? "Refreshing local structure…" : "Waiting for the local agent";
active.Revision++; active.NeedsSnapshot = true; CancelExtraction(active);
link.Register(Descriptor(active)); ScheduleSnapshot(active);
}
private void ScheduleSnapshot(LocalDocument doc,bool analyse=false)
{
if (doc.Extraction != null || ConnectionState != "connected") return;
doc.Extraction = new Extraction { Snapshot = Guid.NewGuid(), Revision=doc.Revision,Analyse=analyse,Limit=doc.End };
if(analyse)doc.Review.Begin(doc.Session,doc.Revision,doc.Extraction.Snapshot);
if (!scheduler.Post("extract:"+doc.Session,() => ExtractBatch(doc)))
{doc.Extraction=null;doc.Review.Stop("Word queue busy. Try analysis again.");}
}
private void ExtractBatch(LocalDocument doc)
{
var extraction = doc.Extraction;
if(extraction == null || !documents.ContainsKey(doc.Document) || extraction.Revision != doc.Revision || closing.Contains(doc.Document)) return;
if(ConnectionState != "connected") { doc.Extraction=null; return; }
var watch=Stopwatch.StartNew();
try
{
if(!extraction.Begun)
{
if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-begin":"snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,Start=extraction.Position,End=extraction.Limit,BookId=doc.AiBook,RequestAnalysis=extraction.Analyse}))return;
extraction.Begun=true;
}
// At most four <=2048-character fragments and a cooperative ~20ms budget.
// A single COM call cannot be preempted; every call is measured separately.
for(var count=0;count<4 && watch.ElapsedMilliseconds<20;count++)
{
if(extraction.Pending == null && extraction.Position<extraction.Limit)
extraction.Pending = ReadFragment(doc,extraction);
if(extraction.Pending != null)
{
if(!link.TryPost(extraction.Pending))return; // Keep this value; do not reread Word under backpressure.
extraction.Pending=null;
}
if(extraction.Position>=extraction.Limit)
{
if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-submit":"snapshot-end",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot}))return;
if(!extraction.IsAi)doc.NeedsSnapshot=false;doc.Extraction=null;
// The committed snapshot resolves the current positional selection.
scheduler.Post("selection",CaptureSelection);return;
}
}
}
catch(COMException)
{ if(extraction.IsAi)StopAi(doc,"Word was busy. AI upload stopped; try again.");doc.Review.Stop("Word was busy. Try analysis again after editing stops.");reviewDirty=true;busyFailures++;CancelExtraction(doc);doc.NeedsSnapshot=true;scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1)); }
catch(InvalidOperationException error)
{ if(extraction.IsAi)StopAi(doc,"Word range unavailable. AI upload stopped.");CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped: " + error.Message;doc.Review.Stop(lastResult);reviewDirty=true; }
catch(NullReferenceException)
{ CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped while reading Word.";doc.Review.Stop(lastResult);reviewDirty=true;throw; }
finally
{
lastBatchMs=watch.Elapsed.TotalMilliseconds;Metric("snapshot-batch",lastBatchMs);
if(doc.Extraction != null)scheduler.Post("extract:"+doc.Session,()=>ExtractBatch(doc));
}
}
private Message ReadFragment(LocalDocument doc,Extraction extraction)
{
Word.Range point=null,paragraphRange=null,textRange=null; Word.Paragraphs paragraphs=null;Word.Paragraph paragraph=null;
try
{
string[] tags=Array.Empty<string>();
if(extraction.Position>=extraction.ParagraphEnd)
{
point=Com(()=>doc.Document.Range(extraction.Position,extraction.Position));
paragraphs=Com(()=>point?.Paragraphs);paragraph=Com(()=>paragraphs?[1]);
if (paragraph == null) throw new InvalidOperationException("Word did not return a paragraph.");
paragraphRange=Com(()=>paragraph.Range);
if (paragraphRange == null) throw new InvalidOperationException("Word did not return a paragraph range.");
extraction.ParagraphEnd=Com(()=>paragraphRange.End);
extraction.OutlineLevel=(int)Com(()=>paragraph.OutlineLevel);
extraction.ParagraphIndex++;
tags=ReadMarkers(paragraphRange);
}
var start=extraction.Position;var end=Math.Min(extraction.Limit,Math.Min(extraction.ParagraphEnd,start+ProtocolVersion.MaxParagraphCharacters));
if(end<=start)throw new InvalidOperationException("Non-advancing Word range.");
textRange=Com(()=>doc.Document.Range(start,end));
if (textRange == null) throw new InvalidOperationException("Word did not return the requested text range.");
var text=Com(()=>textRange.Text) ?? "";
extraction.Position=end;
return new Message{Kind=extraction.IsAi?"ai-fragment":"snapshot-fragment",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,
Metrics=DrainMetrics(),QueueDepth=link.QueueDepth,Fragment=new ParagraphFragment{ParagraphIndex=extraction.ParagraphIndex,Start=start,End=end,OutlineLevel=extraction.OutlineLevel,
Text=text,MarkerTags=tags,CompletesParagraph=end>=extraction.ParagraphEnd}};
}
finally { Release(textRange);Release(paragraphRange);Release(paragraph);Release(paragraphs);Release(point); }
}
private string[] ReadMarkers(Word.Range range)
{
var tags=new List<string>();Word.ContentControls controls=null;Word.Bookmarks bookmarks=null;
try
{
// A PD control may surround this paragraph rather than be a child
// of its Range. Only its start is a structural boundary, never every
// paragraph enclosed by a chapter-spanning control.
Word.ContentControl parent=Com(()=>range.ParentContentControl);
var paragraphStart=Com(()=>range.Start);
try
{
for(var depth=0;parent!=null&&depth<4;depth++)
{
Word.Range parentRange=null;
try
{
parentRange=Com(()=>parent.Range);
if(Com(()=>parentRange.Start)==paragraphStart)
{var tag=Com(()=>parent.Tag);if(!string.IsNullOrEmpty(tag)&&tag.Length<=128)tags.Add(tag);}
}
finally{Release(parentRange);}
Word.ContentControl next=null;
try{next=Com(()=>parent.ParentContentControl);}catch(COMException){ }
Release(parent);parent=next;
}
if(parent!=null)throw new InvalidOperationException("Content-control ancestry exceeds bounded read.");
}
finally{Release(parent);}
controls=Com(()=>range.ContentControls);var count=Com(()=>controls?.Count ?? 0);
if(count>8)throw new InvalidOperationException("Too many nested controls for a bounded marker read.");
for(var index=1;index<=count;index++)
{ Word.ContentControl control=null;try{control=Com(()=>controls[index]);var tag=Com(()=>control?.Tag);if(!string.IsNullOrEmpty(tag)&&tag.Length<=128)tags.Add(tag);}finally{Release(control);} }
bookmarks=Com(()=>range.Bookmarks);
if (bookmarks == null) return tags.Distinct().ToArray();
var hidden=Com(()=>bookmarks.ShowHidden);
try
{
Com(()=>{bookmarks.ShowHidden=true;return true;});count=Com(()=>bookmarks.Count);
if(count>8)throw new InvalidOperationException("Too many bookmarks for a bounded marker read.");
for(var index=1;index<=count;index++)
{ Word.Bookmark bookmark=null;try{object key=index;bookmark=Com(()=>bookmarks.get_Item(ref key));var name=Com(()=>bookmark?.Name);if(!string.IsNullOrEmpty(name)&&name.Length<=128)tags.Add(name);}finally{Release(bookmark);} }
}
finally {Com(()=>{bookmarks.ShowHidden=hidden;return true;});}
if(tags.Distinct().Count()>16)throw new InvalidOperationException("Marker density exceeds bounded read.");
return tags.Distinct().ToArray();
}
finally {Release(bookmarks);Release(controls);}
}
private void CancelExtraction(LocalDocument doc)
{
scheduler.Cancel("extract:"+doc.Session);
if(doc.Extraction!=null&&!link.TryPost(new Message{Kind=doc.Extraction.IsAi?"ai-cancel":"snapshot-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Extraction.Snapshot})&&doc.Extraction.IsAi)link.Reset();
doc.Extraction=null;
}
private void BeforeSave(Word.Document document,ref bool saveAsUI,ref bool cancel)
{
// Never set Cancel, wait for IPC, read prose or force a document save.
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(500));
if(documents.TryGetValue(document,out var state)){StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.NeedsSnapshot=true;state.Review.Stop("Document saved or saving. Analyse again to refresh suggestions.");reviewDirty=true;}
}
private void BeforeClose(Word.Document document,ref bool cancel)
{
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(250));
if(!documents.TryGetValue(document,out var state))return;
StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.Review.Stop("Document closing. Analyse again if close is cancelled.");reviewDirty=true;
documentCollectionGeneration++;
closing.Add(document);
scheduler.Post("retire",ReconcileClosedDocuments);
}
private void ReconcileClosedDocuments() => ProbeOpenDocuments(1,-1,documentCollectionGeneration,new HashSet<Word.Document>());
private void ProbeOpenDocuments(int index,int expectedCount,int generation,HashSet<Word.Document> present)
{
if(generation!=documentCollectionGeneration){scheduler.Post("retire",ReconcileClosedDocuments);return;}
Word.Documents open=null;
try
{
open=Com(()=>application.Documents);var count=Com(()=>open.Count);
if(count>ProtocolVersion.MaxDocuments){lastResult="Document capacity exceeded; close reconciliation waits for at most 32 open documents.";return;}
if(expectedCount>=0&&count!=expectedCount){scheduler.Post("retire",ReconcileClosedDocuments);return;}
if(index<=Math.Min(count,ProtocolVersion.MaxDocuments))
{
present.Add(Com(()=>open[index]));
scheduler.Post("retire",()=>ProbeOpenDocuments(index+1,count,generation,present));return;
}
// No COM in the retirement loop. Cancelled close keeps its exact session.
foreach(var doc in closing.ToArray())
{
if(!present.Contains(doc)&&documents.TryGetValue(doc,out var state))
{CancelExtraction(state);documents.Remove(doc);link.Retire(state.Session);if(active==state)active=null;reviewDirty=true;}
closing.Remove(doc);
}
}
finally{Release(open);invalidateRibbon();}
}
private void Tick(object sender,EventArgs args)
{
Metric("ui-tick-delay",Math.Max(0,tickClock.Elapsed.TotalMilliseconds-25));tickClock.Restart();
if(!disposed)scheduler.Pump();
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;}}
if(reviewDirty&&reviewClock.ElapsedMilliseconds>=250){reviewClock.Restart();RenderReview();}
if(!disposed&&active!=null&&ConnectionState=="connected"&&metricClock.ElapsedMilliseconds>=1000)
{
metricClock.Restart();
if(cloudSupported)link.TryPost(new Message{Kind="cloud-status"});
foreach(var doc in documents.Values)if(doc.AiJob!=Guid.Empty&&doc.Extraction==null)
link.TryPost(new Message{Kind="ai-status",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.AiJob,Start=doc.AiOffset});
link.TryPost(new Message{Kind="metrics",SessionId=active.Session,Revision=active.Revision,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
}
}
public void ConnectToServer(string address)
{if(!cloudSupported){MessageBox.Show("Connect the matching Phase 3 agent first.","PlotDirector");return;}link.TryPost(new Message{Kind="cloud-connect",ServerUrl=address});}
public string ServerUrl=>serverUrl;
public string CloudState=>cloudState;
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 StartAi(StructureSuggestion[] chapters)
{
var doc=active;if(doc==null||doc.Review.Page==null||doc.Review.Running)return;
if(!cloudState.StartsWith("Signed in",StringComparison.Ordinal)){MessageBox.Show("Use Connect / Sign In first.","PlotDirector");return;}
if(doc.AiJob!=Guid.Empty){MessageBox.Show("Cancel the current chapter batch before starting another.","PlotDirector");return;}
doc.AiBook=analysisWindow.SelectedBook;doc.AiCompleted=0;doc.AiFailures.Clear();doc.AiQueue.Clear();
foreach(var chapter in chapters.Where(c=>c.Kind=="Chapter"&&c.Start>=0&&c.End>c.Start).GroupBy(c=>c.Start).Select(g=>g.First()).Take(256))doc.AiQueue.Enqueue(chapter);
doc.AiTotal=doc.AiQueue.Count;if(doc.AiTotal==0){doc.AiStatus="No valid chapter ranges selected. Detect structure again.";reviewDirty=true;return;}NextAi(doc);
}
private void NextAi(LocalDocument doc)
{
doc.AiJob=Guid.Empty;doc.AiOffset=0;doc.AiPartial.Clear();
if(doc.AiQueue.Count==0){doc.AiStatus="AI batch finished: "+doc.AiCompleted+" / "+doc.AiTotal+" chapters processed. Review AI suggestions; failed chapters can be explicitly retried."+(doc.AiFailures.Count>0?" "+doc.AiFailures.Count+" chapter(s) failed; inspect AI suggestions for details.":"");reviewDirty=true;return;}
var chapter=doc.AiQueue.Dequeue();doc.AiChapter=chapter;
if(chapter.End-chapter.Start>120000){AiFailure(doc,"Chapter exceeds the 120,000-character upload limit. Review its boundaries.");doc.AiCompleted++;NextAi(doc);return;}
doc.AiJob=Guid.NewGuid();
doc.AiStatus="Chapter "+(doc.AiCompleted+1)+" of "+doc.AiTotal+": reading "+chapter.Title;
if(!scheduler.Post("ai-read:"+doc.Session,()=>{
if(!documents.ContainsKey(doc.Document)||doc.AiJob==Guid.Empty)return;
if(DocumentEnd(doc.Document)!=doc.End){StopAi(doc,"Document length changed. Detect structure again.");return;}
CancelExtraction(doc);doc.Extraction=new Extraction{Snapshot=doc.AiJob,Revision=doc.Revision,Position=chapter.Start,Limit=chapter.End,IsAi=true};
if(!scheduler.Post("extract:"+doc.Session,()=>ExtractBatch(doc)))StopAi(doc,"Word queue is busy. Try again.");
}))StopAi(doc,"Word queue is busy. Try again.");
reviewDirty=true;
}
private void AcceptAi(LocalDocument doc,Message message)
{
if(message.Revision!=doc.Revision)return;
if(message.Status!="ok"){doc.AiStatus="Chapter failed: "+message.Status;doc.AiCompleted++;AiFailure(doc,message.Status);NextAi(doc);return;}
var result=message.Ai;
if(result==null)return;
if(result.State=="complete"&&result.Offset==doc.AiOffset)
{
foreach(var item in result.Scenes){item.ChapterStart=doc.AiChapter.Start;item.ChapterEnd=doc.AiChapter.End;item.ChapterTitle=doc.AiChapter.Title;doc.AiPartial.Add(item);}
doc.AiOffset=doc.AiPartial.Count;
if(doc.AiOffset>=result.Total)
{
doc.AiResults.RemoveAll(s=>s.ChapterStart==doc.AiChapter.Start);
doc.AiResults.AddRange(doc.AiPartial.Take(Math.Max(0,5000-doc.AiResults.Count)));
doc.AiCompleted++;NextAi(doc);
}
}
else if(result.State=="failed"||result.State=="cancelled")
{AiFailure(doc,result.Message);doc.AiCompleted++;NextAi(doc);}
else doc.AiStatus="Chapter "+(doc.AiCompleted+1)+" / "+doc.AiTotal+": "+(result.State=="reading"?"reading in short batches: "+message.Progress+"%":"AI interpreting scenes…");
reviewDirty=true;
}
private void AiFailure(LocalDocument doc,string reason)
{
doc.AiFailures.Add(doc.AiChapter.Title+": "+reason);
if(doc.AiResults.Count<5000)doc.AiResults.Add(new StructureSuggestion{Kind="Failure",Origin="AI error",Start=doc.AiChapter.Start,End=doc.AiChapter.End,ChapterStart=doc.AiChapter.Start,ChapterEnd=doc.AiChapter.End,ChapterTitle=doc.AiChapter.Title,Title="Analysis failed — "+doc.AiChapter.Title,Reason=reason});
}
private void StopAi(LocalDocument doc,string reason)
{
scheduler.Cancel("ai-read:"+doc.Session);
if(doc.AiJob!=Guid.Empty&&!link.TryPost(new Message{Kind="ai-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.AiJob}))link.Reset();
if(doc.Extraction?.IsAi==true)CancelExtraction(doc);
doc.AiJob=Guid.Empty;doc.AiQueue.Clear();doc.AiPartial.Clear();doc.AiStatus=reason;reviewDirty=true;
}
private void Navigate(StructureSuggestion item)
{
var doc=active;if(doc==null||item.Start<0)return;var revision=doc.Revision;
scheduler.Post("navigate:"+doc.Session,()=>{
if(active!=doc||doc.Revision!=revision||DocumentEnd(doc.Document)!=doc.End||item.Start>doc.End)return;
Word.Range range=null;try{range=Com(()=>doc.Document.Range(item.Start,item.Start));Com(()=>{range.Select();return true;});}finally{Release(range);}
});
}
public void Reconnect() { link.Reset(); }
public void PersistNativeIdentity()
{
var doc=active;if(doc==null||doc.IdentityPersisted)return;
scheduler.Post("identity:"+doc.Session,()=>{
dynamic properties=doc.Document.CustomDocumentProperties;
try{properties.Add("PlotDirector.Native.DocumentGuid",false,Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString,doc.Identity.ToString("D"));}
finally{Release(properties);}
doc.IdentityPersisted=true;link.Register(Descriptor(doc));
});
}
// Future marker writes are explicitly scoped to a known document and exact range.
// No remote mutation command is exposed in protocol v1.
internal void AttachMarker(Word.Document document,int start,int end,string tag)
{
if(!tag.StartsWith("PD-CHAPTER-",StringComparison.Ordinal)||tag.Length>128)
if(!tag.StartsWith("PD-SCENE-",StringComparison.Ordinal)||tag.Length>128)throw new ArgumentException("Invalid marker.");
scheduler.Post("marker",()=>{
Word.Range range=null;Word.ContentControls controls=null;Word.ContentControl control=null;
try{range=document.Range(start,end);controls=document.ContentControls;control=controls.Add(Word.WdContentControlType.wdContentControlRichText,range);control.Tag=tag;control.Title="PlotDirector";control.Appearance=Word.WdContentControlAppearance.wdContentControlHidden;}
finally{Release(control);Release(controls);Release(range);}
});
}
internal void RemoveMarkerPreservingText(Word.ContentControl control)
=> scheduler.Post("marker-remove",()=>control.Delete(false)); // Interop false preserves prose; Office.js uses true.
internal void AttachBookmark(Word.Document document,int position,string name)
{
if(name.Length>40||(!name.StartsWith("_PD_SCENE_",StringComparison.Ordinal)&&!name.StartsWith("_PD_CHAPTER_",StringComparison.Ordinal)))throw new ArgumentException("Invalid bookmark marker.");
scheduler.Post("bookmark",()=>{
Word.Range range=null;Word.Bookmarks bookmarks=null;Word.Bookmark marker=null;
try{range=document.Range(position,position);bookmarks=document.Bookmarks;marker=bookmarks.Add(name,range);}
finally{Release(marker);Release(bookmarks);Release(range);}
});
}
internal void RemoveBookmark(Word.Document document,string name)
{
if(!name.StartsWith("_PD_SCENE_",StringComparison.Ordinal)&&!name.StartsWith("_PD_CHAPTER_",StringComparison.Ordinal))throw new ArgumentException("Invalid bookmark marker.");
scheduler.Post("bookmark-remove",()=>{
Word.Bookmarks bookmarks=null;Word.Bookmark marker=null;
try{bookmarks=document.Bookmarks;object key=name;marker=bookmarks.get_Item(ref key);marker.Delete();}
finally{Release(marker);Release(bookmarks);}
});
}
private Guid? ReadGuidProperty(Word.Document document,string name) {Guid value;return Guid.TryParse(ReadProperty(document,name),out value)&&value!=Guid.Empty?(Guid?)value:null;}
private int? ReadPositiveProperty(Word.Document document,string name) {int value;return int.TryParse(ReadProperty(document,name),out value)&&value>0?(int?)value:null;}
private string ReadProperty(Word.Document document,string name)
{
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))
{
// Word can report a missing named custom property as E_INVALIDARG.
return "";
}
dynamic value = property;
return Com<string>(() => Convert.ToString(value.Value));
}
catch(COMException){return "";}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();
}
private sealed class LocalDocument
{
public readonly Word.Document Document;public readonly Guid Session=Guid.NewGuid();public Guid Identity;public bool IdentityPersisted;
public string DisplayName;
public readonly AnalysisReview Review=new AnalysisReview();
public readonly Queue<StructureSuggestion> AiQueue=new Queue<StructureSuggestion>();
public readonly List<StructureSuggestion> AiResults=new List<StructureSuggestion>();
public readonly List<string> AiFailures=new List<string>();
public Guid AiJob;public int AiBook,AiOffset,AiCompleted,AiTotal;public string AiStatus;
public StructureSuggestion AiChapter;public readonly List<StructureSuggestion> AiPartial=new List<StructureSuggestion>();
public int? ProjectId,BookId;public long Revision;public int End;public bool WasSaved;public bool NeedsSnapshot=true;public Extraction Extraction;
public LocalDocument(Word.Document document){Document=document;}
}
private sealed class Extraction
{public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex,Limit;public int OutlineLevel;public bool Begun,Analyse,IsAi;public Message Pending;}
}
}