From 7d1810c7bc25308d1c2f4179b92fb551dd6f60a7 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Wed, 4 Nov 2026 16:54:45 +0000 Subject: [PATCH] feat: add native Word VSTO and isolated companion agent foundation --- .../Agent/DeferredWorkQueue.cs | 57 +++ .../Agent/PipeHost.cs | 102 ++++ .../Agent/PlotDirector.Companion.Agent.csproj | 4 + PlotDirector.NativeCompanion/Agent/Program.cs | 48 ++ .../Agent/SessionManager.cs | 170 +++++++ .../Client/AgentLink.cs | 142 ++++++ .../Client/BoundedMailbox.cs | 44 ++ .../PlotDirector.Companion.Client.csproj | 4 + .../Client/WordAccessScheduler.cs | 40 ++ .../NativeCompanion.Windows.sln | 30 ++ .../Protocol/FrameCodec.cs | 53 +++ .../Protocol/Messages.cs | 77 +++ .../PlotDirector.Companion.Protocol.csproj | 3 + .../Protocol/README.md | 30 ++ PlotDirector.NativeCompanion/README.md | 69 +++ .../Tests/PlotDirector.Companion.Tests.csproj | 4 + PlotDirector.NativeCompanion/Tests/Program.cs | 151 ++++++ .../Vsto/AgentProcess.cs | 48 ++ .../Vsto/NativeRibbon.cs | 32 ++ .../Vsto/PlotDirector.WordAddIn.csproj | 35 ++ .../Vsto/Properties/AssemblyInfo.cs | 7 + PlotDirector.NativeCompanion/Vsto/Ribbon.xml | 11 + .../Vsto/ThisAddIn.Designer.cs | 18 + .../Vsto/ThisAddIn.Designer.xml | 3 + .../Vsto/ThisAddIn.cs | 22 + .../Vsto/WordAdapter.cs | 443 ++++++++++++++++++ .../WindowsValidation/Build-Developer.ps1 | 13 + .../WindowsValidation/Generate-Fixtures.ps1 | 46 ++ .../WindowsValidation/Measure-Processes.ps1 | 10 + .../WindowsValidation/README.md | 76 +++ PlotLine.slnx | 6 + 31 files changed, 1798 insertions(+) create mode 100644 PlotDirector.NativeCompanion/Agent/DeferredWorkQueue.cs create mode 100644 PlotDirector.NativeCompanion/Agent/PipeHost.cs create mode 100644 PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj create mode 100644 PlotDirector.NativeCompanion/Agent/Program.cs create mode 100644 PlotDirector.NativeCompanion/Agent/SessionManager.cs create mode 100644 PlotDirector.NativeCompanion/Client/AgentLink.cs create mode 100644 PlotDirector.NativeCompanion/Client/BoundedMailbox.cs create mode 100644 PlotDirector.NativeCompanion/Client/PlotDirector.Companion.Client.csproj create mode 100644 PlotDirector.NativeCompanion/Client/WordAccessScheduler.cs create mode 100644 PlotDirector.NativeCompanion/NativeCompanion.Windows.sln create mode 100644 PlotDirector.NativeCompanion/Protocol/FrameCodec.cs create mode 100644 PlotDirector.NativeCompanion/Protocol/Messages.cs create mode 100644 PlotDirector.NativeCompanion/Protocol/PlotDirector.Companion.Protocol.csproj create mode 100644 PlotDirector.NativeCompanion/Protocol/README.md create mode 100644 PlotDirector.NativeCompanion/README.md create mode 100644 PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj create mode 100644 PlotDirector.NativeCompanion/Tests/Program.cs create mode 100644 PlotDirector.NativeCompanion/Vsto/AgentProcess.cs create mode 100644 PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs create mode 100644 PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj create mode 100644 PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs create mode 100644 PlotDirector.NativeCompanion/Vsto/Ribbon.xml create mode 100644 PlotDirector.NativeCompanion/Vsto/ThisAddIn.Designer.cs create mode 100644 PlotDirector.NativeCompanion/Vsto/ThisAddIn.Designer.xml create mode 100644 PlotDirector.NativeCompanion/Vsto/ThisAddIn.cs create mode 100644 PlotDirector.NativeCompanion/Vsto/WordAdapter.cs create mode 100644 PlotDirector.NativeCompanion/WindowsValidation/Build-Developer.ps1 create mode 100644 PlotDirector.NativeCompanion/WindowsValidation/Generate-Fixtures.ps1 create mode 100644 PlotDirector.NativeCompanion/WindowsValidation/Measure-Processes.ps1 create mode 100644 PlotDirector.NativeCompanion/WindowsValidation/README.md diff --git a/PlotDirector.NativeCompanion/Agent/DeferredWorkQueue.cs b/PlotDirector.NativeCompanion/Agent/DeferredWorkQueue.cs new file mode 100644 index 00000000..edc9dd76 --- /dev/null +++ b/PlotDirector.NativeCompanion/Agent/DeferredWorkQueue.cs @@ -0,0 +1,57 @@ +using System.Text.Json; +using PlotDirector.Companion.Protocol; + +namespace PlotDirector.Companion.Agent; + +// Phase 1 durable scheduling foundation, deliberately not attached to a server +// sender until native authentication/revision contracts exist. Contains no prose. +public sealed record DeferredWork(Guid ManuscriptId,int SceneId,long Revision,Guid SnapshotId, + ProseSynchronizationMode Mode,string IdempotencyKey,DateTime NotBeforeUtc); +public sealed class DeferredWorkQueue +{ + private readonly string path; + private readonly object gate=new(); + private readonly Dictionary<(Guid,int),DeferredWork> work=[]; + public const int Capacity=128; + public int Count {get{lock(gate)return work.Count;}} + public DeferredWorkQueue(string directory) + { + Directory.CreateDirectory(directory);path=Path.Combine(directory,"deferred-work.json"); + if(!File.Exists(path))return; + if(new FileInfo(path).Length>128*1024)throw new InvalidDataException("Offline queue file exceeds limit."); + foreach(var entry in JsonSerializer.Deserialize(File.ReadAllText(path))??[]) + {Validate(entry);if(work.Count>=Capacity)throw new InvalidDataException("Offline queue exceeds capacity.");work[(entry.ManuscriptId,entry.SceneId)]=entry;} + } + public bool TryEnqueue(DeferredWork entry) + { + Validate(entry);lock(gate) + { + var key=(entry.ManuscriptId,entry.SceneId); + if(work.TryGetValue(key,out var old)&&old.Revision>=entry.Revision)return old.IdempotencyKey==entry.IdempotencyKey; + if(!work.ContainsKey(key)&&work.Count>=Capacity)return false; + var replacement=new Dictionary<(Guid,int),DeferredWork>(work){[key]=entry};Persist(replacement.Values); + work[key]=entry;return true; + } + } + public DeferredWork[] Ready(ProseSynchronizationMode trigger,DateTime now) + {lock(gate)return work.Values.Where(w=>w.Mode==trigger&&w.NotBeforeUtc<=now).ToArray();} + public void Acknowledge(string idempotencyKey) + { + lock(gate) + { + var pending=work.Where(p=>p.Value.IdempotencyKey!=idempotencyKey).ToDictionary(); + Persist(pending.Values);work.Clear();foreach(var p in pending)work.Add(p.Key,p.Value); + } + } + private void Persist(IEnumerable entries) + { + var temp=path+".new"; + File.WriteAllText(temp,JsonSerializer.Serialize(entries));File.Move(temp,path,true); + } + private static void Validate(DeferredWork entry) + { + if(entry.ManuscriptId==Guid.Empty||entry.SceneId<=0||entry.Revision<0||entry.SnapshotId==Guid.Empty + ||string.IsNullOrWhiteSpace(entry.IdempotencyKey)||entry.IdempotencyKey.Length>128||!Enum.IsDefined(entry.Mode)||entry.NotBeforeUtc.Kind!=DateTimeKind.Utc) + throw new InvalidDataException("Invalid deferred synchronization work."); + } +} diff --git a/PlotDirector.NativeCompanion/Agent/PipeHost.cs b/PlotDirector.NativeCompanion/Agent/PipeHost.cs new file mode 100644 index 00000000..49a8db4b --- /dev/null +++ b/PlotDirector.NativeCompanion/Agent/PipeHost.cs @@ -0,0 +1,102 @@ +using System.IO.Pipes; +using System.Security.Principal; +using System.Diagnostics; +using System.Security.Cryptography; +using System.Text; +using PlotDirector.Companion.Protocol; + +namespace PlotDirector.Companion.Agent; + +public static class AgentEndpoint +{ + public static string CurrentUserPipeName() + { + if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException("Interactive agent is Windows-only. Tests explicitly supply a private pipe name."); + var sid = WindowsIdentity.GetCurrent().User?.Value ?? throw new InvalidOperationException("Missing Windows identity."); + return "PlotDirector.Companion.v1." + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(sid + ":" + Process.GetCurrentProcess().SessionId)))[..24]; + } +} + +public sealed class PipeHost(string pipeName, SessionManager sessions, Action? log = null) +{ + private readonly TimingSummary timings = new(); + private int activePeers; + public int ActivePeers => Volatile.Read(ref activePeers); + public async Task RunAsync(CancellationToken cancellation) + { + var peers = new List(); + try + { + while (!cancellation.IsCancellationRequested) + { + peers.RemoveAll(t => t.IsCompleted); + if (peers.Count >= 8) { await Task.WhenAny(peers).WaitAsync(cancellation); continue; } + var pipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 8, PipeTransmissionMode.Byte, + PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly, 16 * 1024, 16 * 1024); + try { await pipe.WaitForConnectionAsync(cancellation); } + catch { await pipe.DisposeAsync(); throw; } + peers.Add(HandleAsync(pipe,cancellation)); + } + } + catch (OperationCanceledException) when (cancellation.IsCancellationRequested) { } + finally { await Task.WhenAll(peers); } + } + private async Task HandleAsync(NamedPipeServerStream pipe, CancellationToken cancellation) + { + Interlocked.Increment(ref activePeers); + var lease = Guid.NewGuid(); var instance = Guid.Empty; + await using (pipe) + { + try + { + var hello = await ReadWithTimeout(pipe,cancellation,TimeSpan.FromSeconds(3)); + if (hello.Version != ProtocolVersion.Current || hello.Kind != "hello" || hello.WordInstanceId == Guid.Empty + || !ProtocolVersion.SupportsRequiredCapabilities(hello.Capabilities)) + { + await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="unsupported-version"},cancellation); return; + } + instance = hello.WordInstanceId; sessions.Attach(instance,lease); + await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance},cancellation); + log?.Invoke("peer-connected"); + while (!cancellation.IsCancellationRequested) + { + // Client has a short request timeout; idle peers expire without affecting Word. + var message = await ReadWithTimeout(pipe,cancellation,TimeSpan.FromMinutes(2)); + if (message.Version != ProtocolVersion.Current || message.WordInstanceId != instance) throw new InvalidDataException("Peer changed protocol/instance."); + if(message.Metrics==null||message.Metrics.Length>32||message.Metrics.Any(m=>m==null||m.Operation==null||m.Operation.Length>48||!double.IsFinite(m.Milliseconds)||m.Milliseconds<0||m.Milliseconds>600000))throw new InvalidDataException("Invalid metric frame."); + foreach(var metric in message.Metrics)timings.Record(metric); + var watch = Stopwatch.StartNew(); + var answer = sessions.Apply(lease,message); + await FrameCodec.WriteAsync(pipe,answer,cancellation).WaitAsync(TimeSpan.FromSeconds(3),cancellation); + log?.Invoke($"operation={message.Kind} status={answer.Status} elapsedMs={watch.Elapsed.TotalMilliseconds:F2} sessions={sessions.SessionCount} queueDepth={message.QueueDepth} wordInstance={instance:N} session={message.SessionId:N} correlation={message.CorrelationId:N}"); + } + } + catch (Exception ex) when (ex is IOException or InvalidDataException or OperationCanceledException or TimeoutException or UnauthorizedAccessException or System.Runtime.Serialization.SerializationException) + { log?.Invoke("peer-disconnected reason="+ex.GetType().Name); } + finally { Interlocked.Decrement(ref activePeers); if(instance != Guid.Empty) sessions.Detach(instance,lease); log?.Invoke("timing-summary="+System.Text.Json.JsonSerializer.Serialize(timings.Snapshot())); } + } + } + private static async Task ReadWithTimeout(Stream pipe,CancellationToken cancellation,TimeSpan duration) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation); timeout.CancelAfter(duration); + return await FrameCodec.ReadAsync(pipe,timeout.Token); + } +} + +public sealed class TimingSummary +{ + private readonly object gate=new(); + private readonly Dictionary values=[]; + public void Record(UiMetric metric) + { + lock(gate) + { + var key=values.ContainsKey(metric.Operation)||values.Count<32?metric.Operation:"other"; + if(!values.TryGetValue(key,out var summary))values[key]=summary=new Summary(); + summary.Count++;summary.TotalMs+=metric.Milliseconds;summary.MaxMs=Math.Max(summary.MaxMs,metric.Milliseconds); + if(metric.Milliseconds>30)summary.Over30Ms++;if(metric.Milliseconds>100)summary.Over100Ms++; + } + } + public Dictionary Snapshot(){lock(gate)return values.ToDictionary(p=>p.Key,p=>new Summary{Count=p.Value.Count,TotalMs=p.Value.TotalMs,MaxMs=p.Value.MaxMs,Over30Ms=p.Value.Over30Ms,Over100Ms=p.Value.Over100Ms});} + public sealed class Summary{public long Count{get;set;}public double TotalMs{get;set;}public double MaxMs{get;set;}public long Over30Ms{get;set;}public long Over100Ms{get;set;}} +} diff --git a/PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj b/PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj new file mode 100644 index 00000000..9b1b28e8 --- /dev/null +++ b/PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj @@ -0,0 +1,4 @@ + + Exenet10.0enableenableNick Beckley + + diff --git a/PlotDirector.NativeCompanion/Agent/Program.cs b/PlotDirector.NativeCompanion/Agent/Program.cs new file mode 100644 index 00000000..ab82511d --- /dev/null +++ b/PlotDirector.NativeCompanion/Agent/Program.cs @@ -0,0 +1,48 @@ +using PlotDirector.Companion.Agent; + +if (!OperatingSystem.IsWindows()) { Console.Error.WriteLine("The interactive Companion agent requires Windows. Run the portable test harness on Linux."); return 2; } +var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"PlotDirector","Companion"); +Directory.CreateDirectory(directory); +// FileShare.None is held for process lifetime; no cross-thread named-mutex ownership. +FileStream singleton; +try { singleton = new FileStream(Path.Combine(directory,"agent-"+System.Diagnostics.Process.GetCurrentProcess().SessionId+".lock"),FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None); } +catch(IOException) { return 0; } +using(singleton) +using(var shutdown = new CancellationTokenSource()) +{ + Console.CancelKeyPress += (_,e) => {e.Cancel=true;shutdown.Cancel();}; + var log = new AgentLog(directory); + log.Write("agent-start protocol=1 authentication=unavailable publisher=Nick-Beckley"); + var host=new PipeHost(AgentEndpoint.CurrentUserPipeName(),new SessionManager(),log.Write); + var serve=host.RunAsync(shutdown.Token); + var idle=Task.Run(async()=>{ + var lastPeer=DateTime.UtcNow; + while(!shutdown.IsCancellationRequested) + { + await Task.Delay(TimeSpan.FromSeconds(15),shutdown.Token); + if(host.ActivePeers>0)lastPeer=DateTime.UtcNow; + else if(DateTime.UtcNow-lastPeer>TimeSpan.FromMinutes(5)){shutdown.Cancel();return;} + } + }); + try {await serve;} finally {shutdown.Cancel();try{await idle;}catch(OperationCanceledException){}} + +} +return 0; + +sealed class AgentLog(string directory) +{ + private readonly object gate = new(); + public void Write(string message) + { + lock(gate) + { + try + { + var path=Path.Combine(directory,"agent.jsonl"); + if(File.Exists(path)&&new FileInfo(path).Length>2*1024*1024)File.Move(path,path+".previous",true); + File.AppendAllText(path,System.Text.Json.JsonSerializer.Serialize(new{utc=DateTime.UtcNow,component="agent",message})+Environment.NewLine); + } + catch(IOException) { } catch(UnauthorizedAccessException) { } + } + } +} diff --git a/PlotDirector.NativeCompanion/Agent/SessionManager.cs b/PlotDirector.NativeCompanion/Agent/SessionManager.cs new file mode 100644 index 00000000..1f69e556 --- /dev/null +++ b/PlotDirector.NativeCompanion/Agent/SessionManager.cs @@ -0,0 +1,170 @@ +using System.Security.Cryptography; +using System.Text; +using PlotDirector.Companion.Protocol; + +namespace PlotDirector.Companion.Agent; + +public sealed class SessionManager +{ + private readonly object gate = new(); + private readonly Dictionary instances = []; + private const int MaxSnapshotCharacters = 16 * 1024 * 1024; + private const int MaxTotalCharacters = 64 * 1024 * 1024; + private int totalCharacters; + private int totalFragments; + private int totalBoundaries; + public int SessionCount { get { lock (gate) return instances.Values.Sum(i => i.Documents.Count); } } + public void Attach(Guid instance, Guid lease) + { + lock (gate) + { + if (instance == Guid.Empty || (!instances.ContainsKey(instance) && instances.Count >= 8)) throw new InvalidDataException("Word instance capacity/identity invalid."); + DetachCore(instance); + instances[instance] = new WordInstance(lease); + } + } + public void Detach(Guid instance, Guid lease) { lock (gate) { if (instances.TryGetValue(instance, out var state) && state.Lease == lease) DetachCore(instance); } } + private void DetachCore(Guid instance) + { + if (instances.Remove(instance, out var old)) foreach(var document in old.Documents.Values) ClearDocument(document); + } + private void ClearPending(DocumentState document) + { + totalCharacters -= document.Pending?.Characters ?? 0; + totalFragments -= document.Pending?.Fragments.Count ?? 0; + document.Pending = null; + } + private void ClearDocument(DocumentState document) + { + ClearPending(document);totalBoundaries -= document.Boundaries.Count;document.Boundaries=[]; + } + public Message Apply(Guid lease, Message message) + { + lock (gate) + { + var answer = new Message { Kind = "response", CorrelationId = message.CorrelationId, WordInstanceId = message.WordInstanceId, SessionId = message.SessionId, Revision = message.Revision, SnapshotId=message.SnapshotId, Status = "ok" }; + if (!instances.TryGetValue(message.WordInstanceId, out var word) || word.Lease != lease) return Reject(answer,"wrong-instance"); + if (message.Sequence <= word.LastSequence) return Reject(answer,"stale-sequence"); + word.LastSequence = message.Sequence; + if (message.Kind == "ping") return answer; + if (message.Kind is "document" or "reconcile") + { + if (message.Documents == null || message.Documents.Length > ProtocolVersion.MaxDocuments || message.Documents.Any(d=>d==null) || message.Documents.Select(d => d.SessionId).Distinct().Count() != message.Documents.Length + || message.Documents.Any(d => d.SessionId == Guid.Empty || d.ManuscriptId == Guid.Empty || d.Revision < 0 || d.ProjectId is <= 0 || d.BookId is <= 0 || d.ProjectId.HasValue != d.BookId.HasValue)) return Reject(answer,"invalid-documents"); + if (message.Kind == "reconcile") + { + foreach(var prior in word.Documents.Values)ClearDocument(prior); word.Documents.Clear(); word.ActiveSession = null; + } + foreach (var descriptor in message.Documents) + { + if (word.Documents.TryGetValue(descriptor.SessionId, out var existing)) + { + if (descriptor.Revision < existing.Descriptor.Revision || descriptor.ManuscriptId != existing.Descriptor.ManuscriptId) return Reject(answer,"stale-document"); + if (descriptor.Revision > existing.Descriptor.Revision) { ClearDocument(existing); } + existing.Descriptor = descriptor; + } + else + { + if (word.Documents.Count >= ProtocolVersion.MaxDocuments) return Reject(answer,"document-capacity"); + word.Documents.Add(descriptor.SessionId, new DocumentState(descriptor)); + } + } + return answer; + } + if (!word.Documents.TryGetValue(message.SessionId, out var document)) return Reject(answer,"unknown-session"); + if (message.Kind == "close") + { + ClearDocument(document); word.Documents.Remove(message.SessionId); + if (word.ActiveSession == message.SessionId) word.ActiveSession = null; + return answer; + } + if (message.Revision != document.Descriptor.Revision) return Reject(answer,"stale-revision"); + switch (message.Kind) + { + case "metrics": break; + case "active": word.ActiveSession = message.SessionId; break; + case "selection": + if (message.Start < 0 || message.End < message.Start) return Reject(answer,"invalid-position"); + document.Cursor = message.Start; Resolve(document, answer); break; + case "snapshot-begin": + if (message.SnapshotId == Guid.Empty || message.End < 0 || message.End > MaxSnapshotCharacters) return Reject(answer,"invalid-snapshot"); + ClearPending(document); + document.Pending = new Snapshot(message.SnapshotId,message.End); break; + case "snapshot-fragment": + var pending = document.Pending; var fragment = message.Fragment; + if (pending == null || pending.Id != message.SnapshotId) return Reject(answer,"obsolete-snapshot"); + if (fragment == null || fragment.Text == null || fragment.Text.Length > ProtocolVersion.MaxParagraphCharacters || fragment.Start != pending.End || fragment.End <= fragment.Start || fragment.End-fragment.Start > ProtocolVersion.MaxParagraphCharacters || fragment.ParagraphIndex != pending.NextParagraph || fragment.OutlineLevel < 1 || fragment.OutlineLevel > 10 + || fragment.MarkerTags == null || fragment.MarkerTags.Length > 16 || fragment.MarkerTags.Any(t => t == null || t.Length > 128) || pending.Fragments.Count >= 200_000) + return Reject(answer,"invalid-fragment"); + // Include marker text and a per-fragment metadata allowance so + // tiny paragraphs/large marker lists cannot bypass the global budget. + 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); break; + case "snapshot-end": + if (document.Pending == null || document.Pending.Id != message.SnapshotId) return Reject(answer,"obsolete-snapshot"); + var snapshot = document.Pending; + if(snapshot.End != snapshot.ExpectedEnd || (snapshot.End > 0 && !snapshot.LastComplete)) return Reject(answer,"incomplete-snapshot"); + var boundaries = StructuralParser.Parse(snapshot.Fragments); + if(boundaries.Count>8192 || totalBoundaries-document.Boundaries.Count+boundaries.Count>32768)return Reject(answer,"structure-capacity"); + totalBoundaries += boundaries.Count-document.Boundaries.Count; + document.Boundaries = boundaries; + document.SnapshotId = snapshot.Id; + document.ContentFingerprint = StructuralParser.Fingerprint(snapshot.Fragments); + ClearPending(document); Resolve(document, answer); break; + case "snapshot-cancel": + if (document.Pending?.Id == message.SnapshotId) { ClearPending(document); } + break; + default: return Reject(answer,"unsupported-operation"); + } + return answer; + } + } + private static Message Reject(Message answer,string status) { answer.Status = status; return answer; } + private static void Resolve(DocumentState document, Message answer) + { + 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; + answer.ChapterTitle = boundary.ChapterTitle; answer.SceneTitle = boundary.SceneTitle; + answer.SnapshotId = document.SnapshotId; answer.Revision = document.Descriptor.Revision; + } + 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 = []; } + private sealed class Snapshot(Guid id,int expectedEnd) { 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); +public static class StructuralParser +{ + public static List Parse(IReadOnlyList fragments) + { + List result = []; int? chapterId = null; var chapterTitle = ""; var previousParagraph = -1; + foreach (var fragment in fragments) + { + if (fragment.ParagraphIndex == previousParagraph) continue; + previousParagraph = fragment.ParagraphIndex; + int? Id(string prefix) => fragment.MarkerTags.Select(t => t.Replace("_", "-").TrimStart('-')).Where(t => t.StartsWith(prefix,StringComparison.OrdinalIgnoreCase)) + .Select(t => int.TryParse(t[prefix.Length..],out var id) && id > 0 ? (int?)id : null).FirstOrDefault(id => id.HasValue); + var chapter = Id("PD-CHAPTER-"); var scene = Id("PD-SCENE-"); + if (fragment.OutlineLevel == 1 || chapter.HasValue) + { + chapterId = chapter; chapterTitle = Title(fragment.Text); + result.Add(new(fragment.Start,chapterId,scene,chapterTitle,scene.HasValue ? "Scene" : "")); + } + else if (fragment.OutlineLevel == 2 || scene.HasValue) + result.Add(new(fragment.Start,chapterId,scene,chapterTitle,fragment.OutlineLevel == 2 ? Title(fragment.Text) : "Scene")); + } + return result; + } + private static string Title(string value) {var title=value.Trim();return title.Length>200?title[..200]:title;} + public static string Fingerprint(IReadOnlyList fragments) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + foreach (var fragment in fragments) hash.AppendData(Encoding.UTF8.GetBytes(fragment.Text)); + return Convert.ToHexString(hash.GetHashAndReset()); + } +} diff --git a/PlotDirector.NativeCompanion/Client/AgentLink.cs b/PlotDirector.NativeCompanion/Client/AgentLink.cs new file mode 100644 index 00000000..87d4f840 --- /dev/null +++ b/PlotDirector.NativeCompanion/Client/AgentLink.cs @@ -0,0 +1,142 @@ +using System.IO; +using System.IO.Pipes; +using System.Threading; +using System.Threading.Tasks; +using PlotDirector.Companion.Protocol; + +namespace PlotDirector.Companion.Client; + +public sealed class AgentLink : IDisposable +{ + private readonly string pipeName; + private readonly Guid instanceId; + private readonly Func verifyServer; + private readonly Action? startAgent; + private readonly object gate = new(); + private readonly Dictionary documents = new(); + private readonly CancellationTokenSource stop = new(); + private readonly BoundedMailbox mailbox = new(); + private long sequence; + private int disposed; + private int resetRequested; + private Task? worker; + private DateTime lastLaunch; + public int QueueDepth => mailbox.Depth; + public event Action? Received; + public event Action? StateChanged; + public AgentLink(string pipeName, Guid instanceId, Func verifyServer, Action? startAgent = null) + { this.pipeName = pipeName; this.instanceId = instanceId; this.verifyServer = verifyServer; this.startAgent = startAgent; } + public void Start() { lock (gate) { if (worker == null) worker = Task.Run(RunAsync); } } + public bool Register(DocumentDescriptor descriptor) + { + lock (gate) + { + if (!documents.ContainsKey(descriptor.SessionId) && documents.Count >= ProtocolVersion.MaxDocuments) return false; + documents[descriptor.SessionId] = descriptor; + } + var accepted = TryPost(new Message { Kind = "document", Documents = new[] { descriptor } }); + if (!accepted) Reset(); + return accepted; + } + public void Retire(Guid sessionId) + { + lock (gate) documents.Remove(sessionId); + // If lifecycle delivery is backpressured, force a reconciled connection. + if (!TryPost(new Message { Kind = "close", SessionId = sessionId })) Reset(); + } + private NamedPipeClientStream? activePipe; + public void Reset() + { + // Even handle cancellation/closure stays off the Office callback thread. + if (Interlocked.Exchange(ref resetRequested,1) != 0) return; + _ = Task.Run(() => { + try { NamedPipeClientStream? pipe; lock (gate) pipe = activePipe; try { pipe?.Dispose(); } catch (IOException) { } } + finally { Volatile.Write(ref resetRequested,0); } + }); + } + public bool TryPost(Message message) + { + if (Volatile.Read(ref disposed) != 0 || stop.IsCancellationRequested) return false; + message.WordInstanceId = instanceId; + + return mailbox.TryPost(message); + } + private Message Reconcile() + { + lock (gate) return new Message { Kind = "reconcile", WordInstanceId = instanceId, Sequence = Interlocked.Increment(ref sequence), Documents = documents.Values.ToArray() }; + } + private async Task ExchangeAsync(Stream pipe, Message message, CancellationToken cancellation) + { + using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation)) + { + timeout.CancelAfter(TimeSpan.FromSeconds(3)); + if (message.Kind != "hello") message.Sequence = Interlocked.Increment(ref sequence); + // Framework pipe cancellation can depend on the underlying operation. Closing + // the pipe on expiry is the final bound, and runs off Word's UI thread. + using (timeout.Token.Register(() => { try { pipe.Dispose(); } catch (IOException) { } })) + { + await FrameCodec.WriteAsync(pipe, message, timeout.Token).ConfigureAwait(false); + var response = await FrameCodec.ReadAsync(pipe, timeout.Token).ConfigureAwait(false); + if (response.CorrelationId != message.CorrelationId || response.Version != ProtocolVersion.Current) + throw new InvalidDataException("IPC response identity/version mismatch."); + if (response.Status == "unsupported-version" || (message.Kind == "hello" && (response.Status != "ready" || !ProtocolVersion.SupportsRequiredCapabilities(response.Capabilities)))) + throw new InvalidDataException("Incompatible agent protocol/capabilities."); + Received?.Invoke(response); + } + } + } + private async Task RunAsync() + { + var attempt = 0; + while (!stop.IsCancellationRequested) + { + try + { + using (var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) + { + lock (gate) activePipe = pipe; + await pipe.ConnectAsync(700, stop.Token).ConfigureAwait(false); + if (!verifyServer(pipe)) throw new UnauthorizedAccessException("Unexpected agent owner."); + await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId }, stop.Token).ConfigureAwait(false); + mailbox.Clear(); // Reconcile authoritative open documents; never replay stale extraction fragments. + await ExchangeAsync(pipe, Reconcile(), stop.Token).ConfigureAwait(false); + attempt = 0; StateChanged?.Invoke("connected"); + var lastExchange = DateTime.UtcNow; + while (!stop.IsCancellationRequested) + { + if (mailbox.TryTake(out var message)) + { + await ExchangeAsync(pipe, message!, stop.Token).ConfigureAwait(false); + lastExchange = DateTime.UtcNow; + } + else if (DateTime.UtcNow - lastExchange > TimeSpan.FromSeconds(1)) + { + await ExchangeAsync(pipe,new Message { Kind="ping", WordInstanceId=instanceId },stop.Token).ConfigureAwait(false); + lastExchange = DateTime.UtcNow; + } + else await Task.Delay(25, stop.Token).ConfigureAwait(false); + } + } + } + catch (Exception ex) when (ex is IOException || ex is TimeoutException || ex is OperationCanceledException || ex is UnauthorizedAccessException || ex is ObjectDisposedException || ex is System.Runtime.Serialization.SerializationException) + { + if (stop.IsCancellationRequested) break; + StateChanged?.Invoke("offline"); + if (DateTime.UtcNow - lastLaunch > TimeSpan.FromSeconds(30)) + { + lastLaunch = DateTime.UtcNow; + try { startAgent?.Invoke(); } catch (Exception launchError) when (launchError is IOException || launchError is System.ComponentModel.Win32Exception || launchError is InvalidOperationException) { } + } + try { await Task.Delay(Math.Min(5000, 250 * ++attempt), stop.Token).ConfigureAwait(false); } catch (OperationCanceledException) { } + } + finally { lock (gate) activePipe = null; } + } + } + // Never join the worker from an Office callback or hold the Word thread for shutdown. + public void Dispose() + { + if (Interlocked.Exchange(ref disposed,1) != 0) return; + mailbox.Clear(); _ = Task.Run(() => { stop.Cancel(); Reset(); }); + } + public Task Completion => worker ?? Task.CompletedTask; +} diff --git a/PlotDirector.NativeCompanion/Client/BoundedMailbox.cs b/PlotDirector.NativeCompanion/Client/BoundedMailbox.cs new file mode 100644 index 00000000..c8dfc051 --- /dev/null +++ b/PlotDirector.NativeCompanion/Client/BoundedMailbox.cs @@ -0,0 +1,44 @@ +using PlotDirector.Companion.Protocol; + +namespace PlotDirector.Companion.Client; + +// UI producers never wait for space. Lifecycle/snapshot messages preserve FIFO; +// selection events have one latest slot per session and are sent after lifecycle work. +public sealed class BoundedMailbox +{ + private readonly object gate = new(); + private readonly Queue ordered = new(); + private Message? active; + private readonly Dictionary selections = new(); + public const int Capacity = 64; + public int Depth { get { lock (gate) return ordered.Count + selections.Count + (active == null ? 0 : 1); } } + public long Coalesced { get; private set; } + public bool TryPost(Message message) + { + lock (gate) + { + if (message.Kind == "active") { active = message; return true; } + if (message.Kind == "selection") + { + if (selections.ContainsKey(message.SessionId)) Coalesced++; + else if (selections.Count >= ProtocolVersion.MaxDocuments) return false; + selections[message.SessionId] = message; + return true; + } + if (ordered.Count >= Capacity) return false; + ordered.Enqueue(message); + return true; + } + } + public bool TryTake(out Message? message) + { + lock (gate) + { + if (ordered.Count > 0) { message = ordered.Dequeue(); return true; } + if (active != null) { message = active; active = null; return true; } + if (selections.Count > 0) { var pair = selections.First(); message = pair.Value; selections.Remove(pair.Key); return true; } + message = null; return false; + } + } + public void Clear() { lock (gate) { ordered.Clear(); selections.Clear(); active = null; } } +} diff --git a/PlotDirector.NativeCompanion/Client/PlotDirector.Companion.Client.csproj b/PlotDirector.NativeCompanion/Client/PlotDirector.Companion.Client.csproj new file mode 100644 index 00000000..2eb558f5 --- /dev/null +++ b/PlotDirector.NativeCompanion/Client/PlotDirector.Companion.Client.csproj @@ -0,0 +1,4 @@ + + netstandard2.0latestenableenableNick Beckley + + diff --git a/PlotDirector.NativeCompanion/Client/WordAccessScheduler.cs b/PlotDirector.NativeCompanion/Client/WordAccessScheduler.cs new file mode 100644 index 00000000..12b9123a --- /dev/null +++ b/PlotDirector.NativeCompanion/Client/WordAccessScheduler.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; + +namespace PlotDirector.Companion.Client; + +// Pumped by a Windows Forms timer on Word's original UI thread. Actions never +// execute on producers/Task.Run. Each action must itself bound its COM access. +public sealed class WordAccessScheduler +{ + private readonly Dictionary work = new(); + private Queue order = new(); + private readonly int ownerThread = Environment.CurrentManagedThreadId; + private DateTime quietUntil; + public const int Capacity = 64; + public int Depth => work.Count; + public long Superseded { get; private set; } + public event Action? Measured; + public event Action? Failed; + private void AssertOwner() { if (Environment.CurrentManagedThreadId != ownerThread) throw new InvalidOperationException("Word work must stay on its owning UI thread."); } + public bool Post(string key, Action action) + { + AssertOwner(); + if (work.ContainsKey(key)) Superseded++; + else { if (work.Count >= Capacity) return false; order.Enqueue(key); } + work[key] = action; return true; + } + public void Cancel(string key) { AssertOwner(); work.Remove(key); order = new Queue(order.Where(k => k != key)); } + public void Clear() { AssertOwner(); work.Clear(); order.Clear(); } + public void PrioritizeAuthor(TimeSpan quietPeriod) { AssertOwner(); quietUntil = DateTime.UtcNow + quietPeriod; } + public bool Pump() + { + AssertOwner(); + if (DateTime.UtcNow < quietUntil || work.Count == 0) return false; + var key = work.ContainsKey("selection") ? "selection" : order.Peek(); + var action = work[key]; Cancel(key); + var watch = Stopwatch.StartNew(); + try { action(); } catch (Exception ex) { Failed?.Invoke(ex); } + finally { Measured?.Invoke(key.Split(':')[0], watch.Elapsed.TotalMilliseconds); } + return true; + } +} diff --git a/PlotDirector.NativeCompanion/NativeCompanion.Windows.sln b/PlotDirector.NativeCompanion/NativeCompanion.Windows.sln new file mode 100644 index 00000000..862efb37 --- /dev/null +++ b/PlotDirector.NativeCompanion/NativeCompanion.Windows.sln @@ -0,0 +1,30 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlotDirector.Companion.Protocol", "Protocol\PlotDirector.Companion.Protocol.csproj", "{5DCEDFB2-B775-4B09-8431-E253C9B12A10}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlotDirector.Companion.Client", "Client\PlotDirector.Companion.Client.csproj", "{DC2B7CCF-B29B-4AAE-BAD4-3528CB2B751A}" +EndProject +Project("{BAA0C2D2-18E2-41B9-852F-F413020CAA33}") = "PlotDirector.WordAddIn", "Vsto\PlotDirector.WordAddIn.csproj", "{42996908-DB24-4A55-AFF1-1017A31D7206}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5DCEDFB2-B775-4B09-8431-E253C9B12A10}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5DCEDFB2-B775-4B09-8431-E253C9B12A10}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5DCEDFB2-B775-4B09-8431-E253C9B12A10}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5DCEDFB2-B775-4B09-8431-E253C9B12A10}.Release|Any CPU.Build.0 = Release|Any CPU + {DC2B7CCF-B29B-4AAE-BAD4-3528CB2B751A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DC2B7CCF-B29B-4AAE-BAD4-3528CB2B751A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DC2B7CCF-B29B-4AAE-BAD4-3528CB2B751A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DC2B7CCF-B29B-4AAE-BAD4-3528CB2B751A}.Release|Any CPU.Build.0 = Release|Any CPU + {42996908-DB24-4A55-AFF1-1017A31D7206}.Debug|Any CPU.ActiveCfg = Debug|AnyCPU + {42996908-DB24-4A55-AFF1-1017A31D7206}.Debug|Any CPU.Build.0 = Debug|AnyCPU + {42996908-DB24-4A55-AFF1-1017A31D7206}.Release|Any CPU.ActiveCfg = Release|AnyCPU + {42996908-DB24-4A55-AFF1-1017A31D7206}.Release|Any CPU.Build.0 = Release|AnyCPU + EndGlobalSection +EndGlobal diff --git a/PlotDirector.NativeCompanion/Protocol/FrameCodec.cs b/PlotDirector.NativeCompanion/Protocol/FrameCodec.cs new file mode 100644 index 00000000..f0e54b92 --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/FrameCodec.cs @@ -0,0 +1,53 @@ +using System.IO; +using System.Runtime.Serialization.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace PlotDirector.Companion.Protocol; + +public static class FrameCodec +{ + public static async Task WriteAsync(Stream stream, Message message, CancellationToken cancellation) + { + byte[] payload; + using (var buffer = new MemoryStream()) + { + new DataContractJsonSerializer(typeof(Message)).WriteObject(buffer, message); + if (buffer.Length > ProtocolVersion.MaxFrameBytes) throw new InvalidDataException("IPC frame too large."); + payload = buffer.ToArray(); + } + var length = payload.Length; + var header = new[] { (byte)length, (byte)(length >> 8), (byte)(length >> 16), (byte)(length >> 24) }; + await stream.WriteAsync(header, 0, 4, cancellation).ConfigureAwait(false); + await stream.WriteAsync(payload, 0, payload.Length, cancellation).ConfigureAwait(false); + await stream.FlushAsync(cancellation).ConfigureAwait(false); + } + + public static async Task ReadAsync(Stream stream, CancellationToken cancellation) + { + var header = new byte[4]; + await ReadExactlyAsync(stream, header, cancellation).ConfigureAwait(false); + var length = header[0] | header[1] << 8 | header[2] << 16 | header[3] << 24; + if (length <= 0 || length > ProtocolVersion.MaxFrameBytes) throw new InvalidDataException("Invalid IPC frame length."); + var payload = new byte[length]; + await ReadExactlyAsync(stream, payload, cancellation).ConfigureAwait(false); + using (var buffer = new MemoryStream(payload, false)) + { + var message = (Message?)new DataContractJsonSerializer(typeof(Message)).ReadObject(buffer) + ?? throw new InvalidDataException("Empty IPC message."); + if (message.CorrelationId == Guid.Empty) throw new InvalidDataException("Missing correlation ID."); + return message; + } + } + + private static async Task ReadExactlyAsync(Stream stream, byte[] bytes, CancellationToken cancellation) + { + var offset = 0; + while (offset < bytes.Length) + { + var count = await stream.ReadAsync(bytes, offset, bytes.Length - offset, cancellation).ConfigureAwait(false); + if (count == 0) throw new EndOfStreamException("IPC peer disconnected."); + offset += count; + } + } +} diff --git a/PlotDirector.NativeCompanion/Protocol/Messages.cs b/PlotDirector.NativeCompanion/Protocol/Messages.cs new file mode 100644 index 00000000..a8729ccc --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/Messages.cs @@ -0,0 +1,77 @@ +using System.Runtime.Serialization; + +namespace PlotDirector.Companion.Protocol; + +public static class ProtocolVersion +{ + public const int Current = 1; + public const int MaxFrameBytes = 256 * 1024; + public const int MaxDocuments = 32; + public const int MaxParagraphCharacters = 2048; + public const string Capabilities = "sessions-v1,positional-selection-v1,batched-snapshot-v1"; + public static bool SupportsRequiredCapabilities(string? offered) + { + var available = (offered ?? "").Split(new[]{','},StringSplitOptions.RemoveEmptyEntries); + return Capabilities.Split(',').All(required => available.Contains(required)); + } +} + +// Only values cross the boundary. Never add an Office reference or arbitrary object payload. +[DataContract] +public sealed class Message +{ + [DataMember] public int Version { get; set; } = ProtocolVersion.Current; + [DataMember] public Guid CorrelationId { get; set; } = Guid.NewGuid(); + [DataMember] public string Kind { get; set; } = ""; + [DataMember] public Guid WordInstanceId { get; set; } + [DataMember] public Guid SessionId { get; set; } + [DataMember] public long Sequence { get; set; } + [DataMember] public long Revision { get; set; } + [DataMember] public Guid SnapshotId { get; set; } + [DataMember] public int Start { get; set; } + [DataMember] public int End { get; set; } + [DataMember] public DocumentDescriptor[] Documents { get; set; } = Array.Empty(); + [DataMember] public ParagraphFragment? Fragment { get; set; } + [DataMember] public string Capabilities { get; set; } = ProtocolVersion.Capabilities; + [DataMember] public string Status { get; set; } = ""; + [DataMember] public UiMetric[] Metrics { get; set; } = Array.Empty(); + [DataMember] public int QueueDepth { get; set; } + [DataMember] public int? ChapterId { get; set; } + [DataMember] public int? SceneId { get; set; } + [DataMember] public string ChapterTitle { get; set; } = ""; + [DataMember] public string SceneTitle { get; set; } = ""; +} + +[DataContract] +public sealed class DocumentDescriptor +{ + [DataMember] public Guid SessionId { get; set; } + [DataMember] public Guid ManuscriptId { get; set; } + [DataMember] public int? ProjectId { get; set; } + [DataMember] public int? BookId { get; set; } + [DataMember] public long Revision { get; set; } + [DataMember] public bool IdentityPersisted { get; set; } + // Association is local metadata, not proof of server authorization. + [DataMember] public bool AssociationVerified { get; set; } +} + +[DataContract] +public sealed class ParagraphFragment +{ + [DataMember] public int ParagraphIndex { get; set; } + [DataMember] public int Start { get; set; } + [DataMember] public int End { get; set; } + [DataMember] public int OutlineLevel { get; set; } + [DataMember] public string Text { get; set; } = ""; + [DataMember] public string[] MarkerTags { get; set; } = Array.Empty(); + [DataMember] public bool CompletesParagraph { get; set; } +} + +public enum ProseSynchronizationMode { Automatic, OnSave, Manual } + +[DataContract] +public sealed class UiMetric +{ + [DataMember] public string Operation { get; set; } = ""; + [DataMember] public double Milliseconds { get; set; } +} diff --git a/PlotDirector.NativeCompanion/Protocol/PlotDirector.Companion.Protocol.csproj b/PlotDirector.NativeCompanion/Protocol/PlotDirector.Companion.Protocol.csproj new file mode 100644 index 00000000..9078eb6a --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/PlotDirector.Companion.Protocol.csproj @@ -0,0 +1,3 @@ + + netstandard2.0latestenableenableNick Beckley + diff --git a/PlotDirector.NativeCompanion/Protocol/README.md b/PlotDirector.NativeCompanion/Protocol/README.md new file mode 100644 index 00000000..7369cf44 --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/README.md @@ -0,0 +1,30 @@ +# Local protocol v1 + +Shared `.NET Standard 2.0` value contracts; no Office references, RCWs, arbitrary object graphs or BinaryFormatter. Transport is asynchronous local Windows named pipes with current-user server ACL and independent server-process SID verification in the add-in. Portable tests use private pipe names; Linux's underlying Unix-domain sockets do not prove Windows security. + +Each frame: four-byte unsigned little-endian payload length, then DataContract JSON. Length must be 1–262,144 bytes before payload allocation. ReadExactly handles partial reads. All requests/responses have protocol version and nonempty CorrelationId; client accepts only the matching response. One exchange per connection is in flight. Three-second handshake/exchange deadline closes hung I/O on a worker; one-second idle ping detects a vanished idle agent. No Word callback performs transport I/O or waits for it. + +Handshake offers Version=1 and capabilities `sessions-v1,positional-selection-v1,batched-snapshot-v1`. Both sides require these capabilities, accept additional optional capabilities and reject incompatible versions. Future required features need a negotiated version/capability, not inferred compatibility. Native protocol negotiation does not change existing browser/Office.js SignalR signatures. + +| Kind | Identity and effect | +|---|---| +| hello | WordInstanceId; server binds it to this connection's generated lease and replies ready. Current-user access is not server authentication. | +| reconcile | Complete current list of at most 32 DocumentDescriptors for this Word instance. Replaces this instance's state after reconnect. Descriptor contains separate SessionId / ManuscriptId, nullable project/book, observation Revision, IdentityPersisted and untrusted AssociationVerified. No raw document path/name. | +| document | Add/update descriptor. Older revision or changed persistent identity within the same session is refused. Increasing revision invalidates pending/completed structural state. | +| close | Retire this exact instance/session and pending snapshots; never another Word process. Cancelled Word close must not emit this message. | +| active | Current session for this Word instance. Latest per-client active slot coalesces bursts. Future browser active-manuscript policy is separate and is not inferred from latest-connected Word presence. | +| selection | Range.Start/End, session and exact observation Revision. Agent resolves from completed structural boundaries; repeated prose is not used for positional matching. Latest selection per session is coalesced. | +| snapshot-begin | Nonempty SnapshotId, observation Revision, expected final document End. Replaces unfinished snapshot for this session. | +| snapshot-fragment | Same snapshot/revision; ordered contiguous Word positions; paragraph ordinal, OutlineLevel, at most 2,048 text characters, bounded raw control/bookmark tags, completes-paragraph flag. | +| snapshot-end | Commits only if snapshot/revision still current, positions reach declared end and the final paragraph fragment is complete. Agent parses structure, retains bounded boundaries and a fingerprint, and releases assembling prose. | +| snapshot-cancel | Drops only matching pending snapshot; an older cancellation cannot cancel a replacement snapshot. | +| metrics | Bounded COM-call/batch/UI tick timing measurements and queue depth; no prose. | +| ping | Worker keepalive; no Word access. | + +Non-hello requests are assigned increasing Sequence at actual send time (not producer time, because queues coalesce/reorder selection vs lifecycle work). Repeated/older sequence, wrong connection lease, foreign session, stale revision and obsolete snapshot are refused. Errors return explicit statuses; native extraction stops on refusal rather than pretending partial completion. Responses identify instance/session/revision/snapshot and may contain resolved chapter/scene IDs/titles. Native display accepts results only for the currently active matching session/revision. + +Resource bounds: eight Word connections, 32 documents per instance, 64 FIFO frames + 32 latest-selection slots + one active slot per client, 64 UI scheduler actions. Assembling snapshots share a global 200k-fragment limit and 64 Mi storage-budget units, with 16 Mi per document; units include text/marker characters and a fixed metadata allowance. Completed structures have at most 8,192 boundaries/document and 32,768 globally; titles are limited to 200 characters. These are defensive limits, not measured Word capacity promises. + +Disconnect detaches only the connection's current instance lease. Old disconnect callbacks cannot retire a replacement lease. Client reconnect discards stale transport backlog, reconciles still-open documents and requests fresh extraction on the UI scheduler. A pending snapshot frame under backpressure is retained as a value; Word is not reread or blocked. Lifecycle backpressure forces reconciliation rather than silently forgetting a closed/open document. + +Protocol v1 exposes **no remote Word mutation operation** and no server integration. Native marker helper code is UI-only and not callable through IPC. Any future command requires explicit target instance/session, document binding, expected revision, bounded ranges, authorization and acknowledgement states. Existing Office.js markers/settings and server business rules remain authoritative for the legacy path until a reviewed migration exists. diff --git a/PlotDirector.NativeCompanion/README.md b/PlotDirector.NativeCompanion/README.md new file mode 100644 index 00000000..72cd5aab --- /dev/null +++ b/PlotDirector.NativeCompanion/README.md @@ -0,0 +1,69 @@ +# Native Word Companion — Phase 1 + +Publisher: **Nick Beckley**. Architecture: minimal Windows VSTO adapter → per-user modern .NET agent → existing PlotDirector server (native authentication/session-aware server integration deferred). + +This is a development foundation, **not a publicly installable replacement**. Office.js, its manifest, onboarding, Context/Intent and multi-screen UI remain present. Nothing in this tree automatically deploys or installs a component. The .NET Framework VSTO host has not been built or run in Word on the Linux development host. + +```mermaid +flowchart LR + Word[Word UI / STA: lifecycle, positional selection, bounded ranges] --> VSTO[VSTO native ribbon and bounded UI scheduler] + VSTO <-->|asynchronous bounded named-pipe protocol v1| Agent[Per-user .NET 10 agent] + Agent --> Sessions[Word instance + live session + persistent manuscript identity] + Agent --> Processing[Structure resolution, snapshots, diagnostics] + Agent --> Outbox[Bounded metadata-only durable scheduling foundation] + Agent -.->|future native authentication and explicit session contracts| Server[Existing PlotDirector HTTP / SignalR / domain services] + Server --> Screens[Existing browser Context / Intent / multi-screen workspace] +``` + +## Projects + +- `Protocol` targets .NET Standard 2.0 for the VSTO/modern runtime boundary. Value-only data contracts; 256 KiB length-prefixed frames, protocol/capability handshake, correlation/instance/session/revision/snapshot identities. No Office or server-domain references. +- `Client` targets .NET Standard 2.0. Background pipe I/O/recovery; Word callback producers never wait for space or replies. A 64-message FIFO plus at most 32 coalesced selection slots and one latest active-session slot; 3s exchanges, cancellation closes hung I/O on a worker; idle keepalive every second, retry capped at 5s, launch attempts limited to once per 30s. Open-document descriptors are authoritative reconciliation state; stale snapshot fragments are discarded after reconnect. `WordAccessScheduler` is UI-thread-only, fair FIFO low-priority work, latest selection priority, 64 actions, author quiet windows and timings. +- `Agent` targets .NET 10. Windows interactive executable, one process per user/logon session using an exclusive local lock; named-pipe ACL restricts current user, add-in independently checks server process SID. Up to eight connected Word instances and 32 documents each; 16 Mi storage-budget units per assembling document snapshot / 64 Mi globally (text + marker text + per-fragment overhead allowance); 200k assembling fragments globally; 8,192 boundaries per document / 32,768 globally, with 200-character titles. Session routing always requires the connection's instance lease and exact session ID. No server command is routed to a “latest Word” connection. Idle exit after five minutes with no peers; no privileged service. +- `Vsto` is a classic .NET Framework 4.8 **Word VSTO** project, host-item/designer metadata and native ribbon. Requires Visual Studio Office tools/PIAs/runtime on Windows. It is intentionally excluded from the Linux/main managed build; `NativeCompanion.Windows.sln` and `WindowsValidation/Build-Developer.ps1` provide the Windows path. The host-item plumbing must be validated/regenerated against the installed VS Office template if toolchain generation differs; no Windows compile/load claim is made. +- `Tests` is a portable executable regression harness. It runs actual framed named-pipe traffic and managed production logic, including three synthetic book sessions and agent restart. Linux implements named pipes via Unix-domain sockets; these results do not establish Windows ACL, COM or Word performance. + +## Identity and data ownership + +`WordInstanceId` is generated once per add-in load. `SessionId` is generated per open document and is distinct from `ManuscriptId`. The latter reads `PlotDirector.Native.DocumentGuid` from custom properties or is provisionally generated for an uninitialized document. Settings explicitly offers to persist that native identity; no implicit save occurs. Until persisted, a provisional identity is **not** reopen-stable; diagnostics/protocol flag `IdentityPersisted=false`. `PlotDirector.Native.ProjectID/BookID` can be read from prepared test metadata, with `AssociationVerified=false`: local values never grant server authorization. + +The Office.js settings bag is not reinterpreted as custom properties. Automatic migration/read-back of existing Office.js binding storage remains a documented follow-on compatibility dependency requiring real linked DOCX fixtures. Native metadata uses a separate namespace and never overwrites an existing Office.js binding. This phase is not a switchover for real linked manuscripts. + +A descriptor carries an observation revision; snapshots carry a new snapshot ID and the exact revision. Agent refuses stale sequences, leases, revisions, retired sessions and cancelled snapshot commits. Word uses Range.Start/End, OutlineLevel and PD control/bookmark tags, not repeated paragraph text matching. Agent resolves structural positions from completed snapshots; no guessed server scene title is promoted into a trusted scene ID. Structural IDs originate from metadata; server authorization remains required before any future server update. + +## Responsiveness and safe failure + +Word events enqueue/coalesce work; all COM remains on the original thread, driven by a 25ms WinForms timer. The extractor reads at most 2,048 Word range characters per fragment, up to four fragments or a cooperative ~20ms batch, yielding between batches. A single COM call cannot be preempted; 20–30ms is a **measurement target**, not a guarantee. Every wrapped COM call and batch is timed; UI tick delay and queue depth are sent as bounded diagnostics. COM busy/errors back off, and unsupported marker density/ranges stop extraction instead of looping indefinitely. + +Selection reads are prioritized and repeated events coalesced. A completed snapshot is reused on cursor movement. Length changes or the first Saved→dirty transition invalidate it; manual Synchronise Now explicitly rebuilds it. **Same-length structural edits while already dirty are not fully detected in Phase 1**; use manual refresh. This is a read-only structural proof, not a complete edit journal or safe prose-sync implementation. Save/close handlers never set Cancel, wait for IPC, read prose or force a save. Cancelled document close retains its session; actual close retires the exact session after a bounded UI-side reconciliation. + +Under IPC backpressure the pending value is retained and the UI yields; it does not reread Word or wait for agent space. Disconnect cancels extraction and reconnect schedules new snapshots. Documents are not retained in an unbounded agent or UI queue. On shutdown the add-in requests worker cancellation without joining it. No HTTP/SignalR/authentication, database, AI, prose parser, entity detector or sync retry runs inside VSTO. + +The ribbon has status, Connect / Sign In, Synchronise Now, Settings and Diagnostics. Native server sign-in and prose sync are explicitly unavailable; Synchronise Now means **local structure refresh only**. No large pane/embedded website. Native metadata/marker helpers do not expose a remote mutation operation in protocol v1; no Word prose writer exists. Interop marker removal uses `Delete(false)` to preserve text. + +## Server and protocol boundaries + +The agent is not connected to the old user-only Word presence hub. Authentication and document-session-aware routing must be added in a subsequent reviewed phase. Browser cookie scraping, password storage and forged authentication are not implemented. Do not claim Context/Intent/native live synchronization; existing Office.js/browser coordination stays intact. + +Server fixes in this branch independently retain hub signatures and event names. Migration 230 adds an atomic owned-build acknowledgement procedure. Old browser/Office.js callers may omit preview/document fields; the server still verifies authenticated build ownership, current access and the exact active manuscript/book/project association. Supplied identifiers must match. Completed acknowledgements are idempotent and cannot be regressed by a late failure. Code depends on migration 230 before any future server deployment; no live migration/deployment is performed by this prototype. + +## Future prose synchronization contract + +`ProseSynchronizationMode`: Automatic / OnSave / Manual. Word remains prose authority. Future agent work will compare scene-level snapshots/hashes, enqueue only changed scenes after the chosen trigger, submit expected server revision and idempotency key, and refuse stale acknowledgements. No full-novel upload, server-to-Word prose rewrite or automatic expensive AI reanalysis is implied. A save event must return immediately and only enqueue a later trigger; never wait for sync. + +`DeferredWorkQueue` implements the bounded durable scheduling substrate for metadata-only intents: 128 scene slots, newer-revision supersession, mode/quiet-time gating, atomic file replacement and idempotency acknowledgement. It is deliberately **not wired to a prose sender or authenticated account** in Phase 1. Account/environment isolation, encrypted optional prose caching, expiry/retention policy, scene hash mapping and server revision API remain required before activating offline prose synchronization. + +## Verification + +From repository root, serially: + +```sh +dotnet build PlotLine.slnx +dotnet run --no-build --project PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj +dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj +node PlotLine.Tests/Browser/word-companion-regressions.cjs +``` + +The explicit `--word-marker-security` specialist command applies migration 230 only to the hard-coded existing synthetic database `PlotDirector_Phase2_20261103_2305` after checking its synthetic-only marker, then rolls back all security fixture mutations. Never repoint it at Development or Production. + +See [Windows validation](WindowsValidation/README.md) before any desktop acceptance or distribution. Phase 1 requires review; full migration is not authorized by this implementation. diff --git a/PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj b/PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj new file mode 100644 index 00000000..57189a22 --- /dev/null +++ b/PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj @@ -0,0 +1,4 @@ + + Exenet10.0enableenable + + diff --git a/PlotDirector.NativeCompanion/Tests/Program.cs b/PlotDirector.NativeCompanion/Tests/Program.cs new file mode 100644 index 00000000..9fad0c8d --- /dev/null +++ b/PlotDirector.NativeCompanion/Tests/Program.cs @@ -0,0 +1,151 @@ +using System.IO.Pipes; +using PlotDirector.Companion.Agent; +using PlotDirector.Companion.Client; +using PlotDirector.Companion.Protocol; + +var passed = 0; +void Check(bool value,string name) {if(!value)throw new Exception(name);passed++;Console.WriteLine("PASS "+name);} +async Task Until(Func condition,string name) {using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(12));while(!condition()){await Task.Delay(20,timeout.Token);}Check(true,name);} +void SchedulerChecks() +{ + var scheduler=new WordAccessScheduler();var value=0;var measured=0; + scheduler.Measured+=(_,ms)=>{Check(ms>=0,"Word operation timing recorded");measured++;}; + for(var i=0;i<1000;i++){var latest=i;scheduler.Post("selection",()=>value=latest);} + Check(scheduler.Depth==1&&scheduler.Superseded==999,"selection scheduler coalesces bursts");scheduler.Pump();Check(value==999&&measured==1,"only latest selection executes on owner"); + scheduler.Post("obsolete",()=>throw new Exception("Should be cancelled"));scheduler.Cancel("obsolete");Check(!scheduler.Pump(),"obsolete Word work cancelled"); + for(var i=0;i{}),"bounded Word queue accepts capacity slot "+i); + Check(!scheduler.Post("overflow",()=>{}),"Word queue rejects overflow without waiting");scheduler.Clear(); + var rejected=false;var thread=new Thread(()=>{try{scheduler.Pump();}catch(InvalidOperationException){rejected=true;}});thread.Start();thread.Join();Check(rejected,"Word scheduler rejects wrong thread"); + scheduler.PrioritizeAuthor(TimeSpan.FromMinutes(1));scheduler.Post("low",()=>value=0);Check(!scheduler.Pump()&&value==999,"author activity suspends low priority work"); +} +SchedulerChecks(); +var mailbox=new BoundedMailbox();var id=Guid.NewGuid(); +for(var i=0;i<10000;i++)mailbox.TryPost(new Message{Kind="selection",SessionId=id,Start=i}); +Check(mailbox.Depth==1&&mailbox.Coalesced==9999,"IPC coalesces selection storm to latest value");mailbox.TryTake(out var latestMessage);Check(latestMessage!.Start==9999,"coalesced position is latest"); +for(var i=0;inew DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),ProjectId=10+i,BookId=20+i,Revision=1}).ToArray(); +Check(Apply(new Message{Kind="reconcile",Documents=descriptors}).Status=="ok"&&sessions.SessionCount==3,"three books have independent live sessions"); +for(var book=0;bookTask.Run(()=>new PipeHost(pipeName,serverSessions).RunAsync(token)); +var host=StartHost(stopHost.Token); +using(var bad=new NamedPipeClientStream(".",pipeName,PipeDirection.InOut,PipeOptions.Asynchronous)) +{ + await bad.ConnectAsync(3000);var hello=new Message{Kind="hello",Version=99,WordInstanceId=Guid.NewGuid()};await FrameCodec.WriteAsync(bad,hello,CancellationToken.None); + Check((await FrameCodec.ReadAsync(bad,CancellationToken.None)).Status=="unsupported-version","real pipe rejects incompatible handshake"); +} +using(var compatible=new NamedPipeClientStream(".",pipeName,PipeDirection.InOut,PipeOptions.Asynchronous)) +{ + await compatible.ConnectAsync(3000);var hello=new Message{Kind="hello",WordInstanceId=Guid.NewGuid(),Capabilities=ProtocolVersion.Capabilities+",future-optional"}; + await FrameCodec.WriteAsync(compatible,hello,CancellationToken.None); + Check((await FrameCodec.ReadAsync(compatible,CancellationToken.None)).Status=="ready","same-version optional capabilities remain compatible"); +} +var connected=0;var replies=0;var offline=0; +using(var link=new AgentLink(pipeName,Guid.NewGuid(),_=>true)) // Windows SID peer validation is exercised by the desktop procedure, not faked as proved here. +{ + link.StateChanged+=state=>{if(state=="connected")Interlocked.Increment(ref connected);else if(state=="offline")Interlocked.Increment(ref offline);}; + link.Received+=_=>Interlocked.Increment(ref replies); + foreach(var descriptor in descriptors)link.Register(descriptor); + link.Start();await Until(()=>Volatile.Read(ref connected)==1&&serverSessions.SessionCount==3,"real named-pipe handshake reconciles three documents"); + link.TryPost(new Message{Kind="active",SessionId=descriptors[1].SessionId,Revision=1}); + link.TryPost(new Message{Kind="selection",SessionId=descriptors[1].SessionId,Revision=1,Start=30,End=30}); + await Until(()=>Volatile.Read(ref replies)>=4,"agent receives actual asynchronous positional/lifecycle traffic"); + stopHost.Cancel();await host;await Until(()=>serverSessions.SessionCount==0,"agent shutdown retires peer sessions"); + await Until(()=>Volatile.Read(ref offline)>0,"idle keepalive detects agent loss without a Word event"); + stopHost.Dispose();stopHost=new CancellationTokenSource();host=StartHost(stopHost.Token); + await Until(()=>Volatile.Read(ref connected)>=2&&serverSessions.SessionCount==3,"agent restart reconnects and reconciles without UI waits"); + link.Retire(descriptors[2].SessionId);await Until(()=>serverSessions.SessionCount==2,"real pipe document close is isolated"); + link.Dispose();await link.Completion.WaitAsync(TimeSpan.FromSeconds(5)); + Check(true,"link shutdown cancels background worker promptly"); +} +var deniedOwner=false; +using(var untrusted=new AgentLink(pipeName,Guid.NewGuid(),_=>false)) +{ + untrusted.StateChanged+=state=>{if(state=="offline")deniedOwner=true;};untrusted.Start(); + await Until(()=>deniedOwner,"untrusted agent owner callback rejects connection before handshake"); + untrusted.Dispose();await untrusted.Completion.WaitAsync(TimeSpan.FromSeconds(5)); +} +stopHost.Cancel();await host;stopHost.Dispose(); +var stalledName="pd-phase1-stalled-"+Guid.NewGuid().ToString("N"); +using(var stalled=new NamedPipeServerStream(stalledName,PipeDirection.InOut,1,PipeTransmissionMode.Byte,PipeOptions.Asynchronous|PipeOptions.CurrentUserOnly)) +using(var stalledClient=new AgentLink(stalledName,Guid.NewGuid(),_=>true)) +{ + var timedOut=false;stalledClient.StateChanged+=state=>{if(state=="offline")timedOut=true;}; + stalledClient.Start();await stalled.WaitForConnectionAsync(); + await FrameCodec.ReadAsync(stalled,CancellationToken.None); // Deliberately never acknowledge hello. + await Until(()=>timedOut,"unresponsive agent handshake times out off producer thread"); + stalledClient.Dispose();await stalledClient.Completion.WaitAsync(TimeSpan.FromSeconds(5)); +} +Console.WriteLine($"Native foundation: {passed} checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified."); diff --git a/PlotDirector.NativeCompanion/Vsto/AgentProcess.cs b/PlotDirector.NativeCompanion/Vsto/AgentProcess.cs new file mode 100644 index 00000000..1abd0386 --- /dev/null +++ b/PlotDirector.NativeCompanion/Vsto/AgentProcess.cs @@ -0,0 +1,48 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.IO.Pipes; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Security.Principal; +using System.Text; + +namespace PlotDirector.WordAddIn +{ + internal static class AgentProcess + { + internal static string PipeName() + { + var value = WindowsIdentity.GetCurrent().User.Value + ":" + Process.GetCurrentProcess().SessionId; + using (var hash = SHA256.Create()) return "PlotDirector.Companion.v1." + BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(value))).Replace("-", "").Substring(0,24); + } + // Called only on the IPC worker. No Word objects, UI calls or shell search paths. + internal static void Start() + { + var root = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var executable = Path.Combine(root,"Agent","PlotDirector.Companion.Agent.exe"); + if (!File.Exists(executable)) return; + using (Process.Start(new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(executable) })) { } + } + internal static bool VerifyOwner(NamedPipeClientStream pipe) + { + uint processId; + if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle.DangerousGetHandle(),out processId)) return false; + var process = OpenProcess(0x1000,false,processId); + if (process == IntPtr.Zero) return false; + IntPtr token = IntPtr.Zero; + try + { + if (!OpenProcessToken(process,8,out token)) return false; + using (var identity = new WindowsIdentity(token)) + using (var current = WindowsIdentity.GetCurrent()) return identity.User == current.User; + } + finally { if(token != IntPtr.Zero)CloseHandle(token); CloseHandle(process); } + } + [DllImport("kernel32.dll",SetLastError=true)] private static extern bool GetNamedPipeServerProcessId(IntPtr pipe,out uint processId); + [DllImport("kernel32.dll",SetLastError=true)] private static extern IntPtr OpenProcess(uint access,bool inherit,uint processId); + [DllImport("advapi32.dll",SetLastError=true)] private static extern bool OpenProcessToken(IntPtr process,uint access,out IntPtr token); + [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle); + } +} diff --git a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs new file mode 100644 index 00000000..7d72c6a7 --- /dev/null +++ b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs @@ -0,0 +1,32 @@ +using System; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using Office = Microsoft.Office.Core; + +namespace PlotDirector.WordAddIn +{ + [ComVisible(true)] + public sealed class NativeRibbon : Office.IRibbonExtensibility + { + private readonly Func getAdapter; + private Office.IRibbonUI ui; + public NativeRibbon(Func getAdapter) { this.getAdapter = getAdapter; } + public string GetCustomUI(string ribbonID) + { 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 _) => "Agent: " + (getAdapter()?.ConnectionState ?? "Unavailable") + " · Server: unavailable"; + public bool CanSynchronize(Office.IRibbonControl _) => getAdapter()?.HasActiveDocument == true; + public void Connect(Office.IRibbonControl _) { getAdapter()?.Reconnect(); MessageBox.Show("The local agent reconnects in the background. Native server sign-in is not implemented in Phase 1; no browser credentials are reused.","PlotDirector — Nick Beckley"); } + public void Synchronize(Office.IRibbonControl _) { getAdapter()?.RequestSnapshot(); } + public void Settings(Office.IRibbonControl _) + { + if (getAdapter() == null) return; + var choice = MessageBox.Show("Phase 1 uses Manual local snapshot refresh. 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(); + } + 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 new file mode 100644 index 00000000..5322afaa --- /dev/null +++ b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj @@ -0,0 +1,35 @@ + + + + {42996908-DB24-4A55-AFF1-1017A31D7206} + {BAA0C2D2-18E2-41B9-852F-F413020CAA33};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + DebugAnyCPU + trueLibraryv4.8latest + PlotDirector.WordAddInPlotDirector.WordAddIn + Word15.0true + 3PlotDirector Word Companion (Phase 1)PlotDirector by Nick Beckley — native prototype + PlotDirector Word CompanionNick Beckleyfalsetrue + bin\$(Configuration)\true + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + true + true + true + + + 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 new file mode 100644 index 00000000..4fd76f91 --- /dev/null +++ b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs @@ -0,0 +1,7 @@ +using System.Reflection; +using System.Runtime.InteropServices; +[assembly: AssemblyTitle("PlotDirector Word Companion — Phase 1")] +[assembly: AssemblyCompany("Nick Beckley")] +[assembly: AssemblyProduct("PlotDirector")] +[assembly: AssemblyVersion("0.1.0.0")] +[assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml new file mode 100644 index 00000000..995a793c --- /dev/null +++ b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml @@ -0,0 +1,11 @@ + + + + +