feat: add native Word VSTO and isolated companion agent foundation
This commit is contained in:
parent
15062813b4
commit
7d1810c7bc
57
PlotDirector.NativeCompanion/Agent/DeferredWorkQueue.cs
Normal file
57
PlotDirector.NativeCompanion/Agent/DeferredWorkQueue.cs
Normal file
@ -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<DeferredWork[]>(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<DeferredWork> 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.");
|
||||
}
|
||||
}
|
||||
102
PlotDirector.NativeCompanion/Agent/PipeHost.cs
Normal file
102
PlotDirector.NativeCompanion/Agent/PipeHost.cs
Normal file
@ -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<string>? 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<Task>();
|
||||
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<Message> 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<string,Summary> 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<string,Summary> 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;}}
|
||||
}
|
||||
@ -0,0 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><Company>Nick Beckley</Company></PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../Protocol/PlotDirector.Companion.Protocol.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
48
PlotDirector.NativeCompanion/Agent/Program.cs
Normal file
48
PlotDirector.NativeCompanion/Agent/Program.cs
Normal file
@ -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) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
170
PlotDirector.NativeCompanion/Agent/SessionManager.cs
Normal file
170
PlotDirector.NativeCompanion/Agent/SessionManager.cs
Normal file
@ -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<Guid, WordInstance> 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<Guid,DocumentState> Documents = []; }
|
||||
private sealed class DocumentState(DocumentDescriptor descriptor) { public DocumentDescriptor Descriptor = descriptor; public int Cursor; public Snapshot? Pending; public Guid SnapshotId; public string ContentFingerprint=""; public List<StructuralBoundary> Boundaries = []; }
|
||||
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<ParagraphFragment> Fragments = []; }
|
||||
}
|
||||
|
||||
public sealed record StructuralBoundary(int Start, int? ChapterId, int? SceneId, string ChapterTitle, string SceneTitle);
|
||||
public static class StructuralParser
|
||||
{
|
||||
public static List<StructuralBoundary> Parse(IReadOnlyList<ParagraphFragment> fragments)
|
||||
{
|
||||
List<StructuralBoundary> 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<ParagraphFragment> 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());
|
||||
}
|
||||
}
|
||||
142
PlotDirector.NativeCompanion/Client/AgentLink.cs
Normal file
142
PlotDirector.NativeCompanion/Client/AgentLink.cs
Normal file
@ -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<NamedPipeClientStream, bool> verifyServer;
|
||||
private readonly Action? startAgent;
|
||||
private readonly object gate = new();
|
||||
private readonly Dictionary<Guid, DocumentDescriptor> 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<Message>? Received;
|
||||
public event Action<string>? StateChanged;
|
||||
public AgentLink(string pipeName, Guid instanceId, Func<NamedPipeClientStream, bool> 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;
|
||||
}
|
||||
44
PlotDirector.NativeCompanion/Client/BoundedMailbox.cs
Normal file
44
PlotDirector.NativeCompanion/Client/BoundedMailbox.cs
Normal file
@ -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<Message> ordered = new();
|
||||
private Message? active;
|
||||
private readonly Dictionary<Guid, Message> 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; } }
|
||||
}
|
||||
@ -0,0 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><TargetFramework>netstandard2.0</TargetFramework><LangVersion>latest</LangVersion><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings><Company>Nick Beckley</Company></PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../Protocol/PlotDirector.Companion.Protocol.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
40
PlotDirector.NativeCompanion/Client/WordAccessScheduler.cs
Normal file
40
PlotDirector.NativeCompanion/Client/WordAccessScheduler.cs
Normal file
@ -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<string, Action> work = new();
|
||||
private Queue<string> 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<string, double>? Measured;
|
||||
public event Action<Exception>? 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<string>(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;
|
||||
}
|
||||
}
|
||||
30
PlotDirector.NativeCompanion/NativeCompanion.Windows.sln
Normal file
30
PlotDirector.NativeCompanion/NativeCompanion.Windows.sln
Normal file
@ -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
|
||||
53
PlotDirector.NativeCompanion/Protocol/FrameCodec.cs
Normal file
53
PlotDirector.NativeCompanion/Protocol/FrameCodec.cs
Normal file
@ -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<Message> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
77
PlotDirector.NativeCompanion/Protocol/Messages.cs
Normal file
77
PlotDirector.NativeCompanion/Protocol/Messages.cs
Normal file
@ -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<DocumentDescriptor>();
|
||||
[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<UiMetric>();
|
||||
[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<string>();
|
||||
[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; }
|
||||
}
|
||||
@ -0,0 +1,3 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><TargetFramework>netstandard2.0</TargetFramework><LangVersion>latest</LangVersion><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings><Company>Nick Beckley</Company></PropertyGroup>
|
||||
</Project>
|
||||
30
PlotDirector.NativeCompanion/Protocol/README.md
Normal file
30
PlotDirector.NativeCompanion/Protocol/README.md
Normal file
@ -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.
|
||||
69
PlotDirector.NativeCompanion/README.md
Normal file
69
PlotDirector.NativeCompanion/README.md
Normal file
@ -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.
|
||||
@ -0,0 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../Agent/PlotDirector.Companion.Agent.csproj" /><ProjectReference Include="../Client/PlotDirector.Companion.Client.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
151
PlotDirector.NativeCompanion/Tests/Program.cs
Normal file
151
PlotDirector.NativeCompanion/Tests/Program.cs
Normal file
@ -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<bool> 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<WordAccessScheduler.Capacity;i++)Check(scheduler.Post("work"+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;i<BoundedMailbox.Capacity;i++)mailbox.TryPost(new Message{Kind="snapshot-fragment"});
|
||||
Check(!mailbox.TryPost(new Message{Kind="snapshot-fragment"})&&mailbox.Depth==64,"IPC snapshot queue backpressure bounded");mailbox.Clear();
|
||||
for(var i=0;i<ProtocolVersion.MaxDocuments;i++)mailbox.TryPost(new Message{Kind="selection",SessionId=Guid.NewGuid()});
|
||||
Check(!mailbox.TryPost(new Message{Kind="selection",SessionId=Guid.NewGuid()}),"IPC selection session slots bounded");
|
||||
|
||||
Check(!ProtocolVersion.SupportsRequiredCapabilities("sessions-v1"),"missing required protocol capabilities refused");
|
||||
var sessions=new SessionManager();var instance=Guid.NewGuid();var lease=Guid.NewGuid();sessions.Attach(instance,lease);long seq=0;
|
||||
Message Apply(Message m) {m.WordInstanceId=instance;m.Sequence=++seq;return sessions.Apply(lease,m);}
|
||||
var books=new[]{"Discovery","Reckoning","Redemption"}; // Synthetic fixture labels only; never production recognition.
|
||||
var descriptors=books.Select((_,i)=>new 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;book<descriptors.Length;book++)
|
||||
{
|
||||
var doc=descriptors[book];var snapshot=Guid.NewGuid();
|
||||
Apply(new Message{Kind="snapshot-begin",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot,End=40});
|
||||
Apply(new Message{Kind="snapshot-fragment",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot,Fragment=new(){ParagraphIndex=1,Start=0,End=20,OutlineLevel=1,Text=books[book],MarkerTags=["PD-CHAPTER-"+(100+book)],CompletesParagraph=true}});
|
||||
Apply(new Message{Kind="snapshot-fragment",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot,Fragment=new(){ParagraphIndex=2,Start=20,End=40,OutlineLevel=2,Text="Repeated paragraph text",MarkerTags=["_PD_SCENE_"+(200+book)],CompletesParagraph=true}});
|
||||
Check(Apply(new Message{Kind="snapshot-end",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot}).Status=="ok","commit structural snapshot "+books[book]);
|
||||
var answer=Apply(new Message{Kind="selection",SessionId=doc.SessionId,Revision=1,Start=30,End=30});
|
||||
Check(answer.ChapterId==100+book&&answer.SceneId==200+book,"positional scene resolution independent of repeated text "+books[book]);
|
||||
}
|
||||
for(var pass=0;pass<50;pass++)foreach(var doc in descriptors){Apply(new Message{Kind="active",SessionId=doc.SessionId,Revision=1});if(sessions.ActiveSession(instance)!=doc.SessionId)throw new Exception("Wrong active document");}
|
||||
Check(true,"rapid three-document switching preserves active identity");
|
||||
var pendingId=Guid.NewGuid();var first=descriptors[0];Apply(new Message{Kind="snapshot-begin",SessionId=first.SessionId,Revision=1,SnapshotId=pendingId});
|
||||
Apply(new Message{Kind="snapshot-cancel",SessionId=first.SessionId,Revision=1,SnapshotId=pendingId});
|
||||
Check(Apply(new Message{Kind="snapshot-end",SessionId=first.SessionId,Revision=1,SnapshotId=pendingId}).Status=="obsolete-snapshot","cancelled snapshot cannot commit");
|
||||
var incomplete=Guid.NewGuid();Apply(new Message{Kind="snapshot-begin",SessionId=first.SessionId,Revision=1,SnapshotId=incomplete,End=40});
|
||||
Check(Apply(new Message{Kind="snapshot-end",SessionId=first.SessionId,Revision=1,SnapshotId=incomplete}).Status=="incomplete-snapshot","partial snapshot cannot masquerade as complete");
|
||||
Check(Apply(new Message{Kind="snapshot-fragment",SessionId=first.SessionId,Revision=1,SnapshotId=incomplete,Fragment=new(){ParagraphIndex=1,Start=0,End=2049,Text=new string('x',2049),OutlineLevel=10}}).Status=="invalid-fragment","oversized extraction fragment refused");
|
||||
Check(Apply(new Message{Kind="selection",SessionId=first.SessionId,Revision=0}).Status=="stale-revision","stale revision refused");
|
||||
var foreign=Guid.NewGuid();Check(sessions.Apply(foreign,new Message{WordInstanceId=instance,Sequence=++seq}).Status=="wrong-instance","peer cannot address another instance lease");
|
||||
Check(sessions.Apply(lease,new Message{WordInstanceId=instance,Sequence=seq-1}).Status=="stale-sequence","duplicate/out-of-order sequence refused");
|
||||
Apply(new Message{Kind="close",SessionId=first.SessionId});Check(!sessions.HasSession(instance,first.SessionId)&&sessions.SessionCount==2,"closing one document retires only its state");
|
||||
var newLease=Guid.NewGuid();sessions.Attach(instance,newLease);sessions.Detach(instance,lease);Check(sessions.Apply(newLease,new Message{Kind="reconcile",WordInstanceId=instance,Sequence=1,Documents=descriptors}).Status=="ok","old disconnect cannot retire replacement lease");
|
||||
sessions.Detach(instance,newLease);Check(sessions.SessionCount==0,"disconnect releases all owned sessions and snapshots");
|
||||
|
||||
var multiple=new SessionManager();var wordA=Guid.NewGuid();var wordB=Guid.NewGuid();var peerA=Guid.NewGuid();var peerB=Guid.NewGuid();
|
||||
multiple.Attach(wordA,peerA);multiple.Attach(wordB,peerB);
|
||||
multiple.Apply(peerA,new Message{Kind="reconcile",WordInstanceId=wordA,Sequence=1,Documents=[descriptors[0]]});
|
||||
multiple.Apply(peerB,new Message{Kind="reconcile",WordInstanceId=wordB,Sequence=1,Documents=[descriptors[1]]});
|
||||
Check(multiple.Apply(peerA,new Message{Kind="selection",WordInstanceId=wordA,SessionId=descriptors[1].SessionId,Sequence=2,Revision=1}).Status=="unknown-session","one Word process cannot route into another process document");
|
||||
multiple.Detach(wordA,peerA);Check(multiple.SessionCount==1&&multiple.HasSession(wordB,descriptors[1].SessionId),"terminating one Word process preserves another instance");
|
||||
var revisionSession=descriptors[1];var oldSnapshot=Guid.NewGuid();
|
||||
multiple.Apply(peerB,new Message{Kind="snapshot-begin",WordInstanceId=wordB,SessionId=revisionSession.SessionId,Sequence=2,Revision=1,SnapshotId=oldSnapshot,End=40});
|
||||
multiple.Apply(peerB,new Message{Kind="document",WordInstanceId=wordB,Sequence=3,Documents=[new(){SessionId=revisionSession.SessionId,ManuscriptId=revisionSession.ManuscriptId,Revision=2,ProjectId=revisionSession.ProjectId,BookId=revisionSession.BookId}]});
|
||||
Check(multiple.Apply(peerB,new Message{Kind="snapshot-end",WordInstanceId=wordB,SessionId=revisionSession.SessionId,Sequence=4,Revision=1,SnapshotId=oldSnapshot}).Status=="stale-revision","new observation revision invalidates in-flight old extraction");
|
||||
|
||||
Check(multiple.Apply(peerB,new Message{Kind="document",WordInstanceId=wordB,Sequence=5,Documents=[null!]}).Status=="invalid-documents","malformed null document cannot crash agent session processing");
|
||||
|
||||
using(var malformed=new MemoryStream(new byte[]{255,255,255,127}))
|
||||
{
|
||||
try{await FrameCodec.ReadAsync(malformed,CancellationToken.None);throw new Exception("Accepted oversized prefix");}catch(InvalidDataException){Check(true,"oversized frame rejected before allocation");}
|
||||
}
|
||||
using(var frame=new MemoryStream())
|
||||
{
|
||||
var original=new Message{Kind="selection",WordInstanceId=Guid.NewGuid(),SessionId=Guid.NewGuid(),Start=99};await FrameCodec.WriteAsync(frame,original,CancellationToken.None);frame.Position=0;
|
||||
var copy=await FrameCodec.ReadAsync(frame,CancellationToken.None);Check(copy.CorrelationId==original.CorrelationId&©.Start==99,"versioned frame round-trip retains identity");
|
||||
}
|
||||
|
||||
var queueDirectory=Path.Combine(Path.GetTempPath(),"pd-phase1-outbox-"+Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
var queue=new DeferredWorkQueue(queueDirectory);var manuscript=Guid.NewGuid();
|
||||
var item=new DeferredWork(manuscript,1,1,Guid.NewGuid(),ProseSynchronizationMode.OnSave,"revision-1",DateTime.UtcNow);
|
||||
Check(queue.TryEnqueue(item),"offline work persisted without manuscript prose");
|
||||
Check(queue.Ready(ProseSynchronizationMode.Automatic,DateTime.UtcNow).Length==0,"On Save mode cannot be triggered by automatic quiet period");
|
||||
Check(new DeferredWorkQueue(queueDirectory).Ready(ProseSynchronizationMode.OnSave,DateTime.UtcNow).Length==1,"offline work survives agent restart");
|
||||
Check(queue.TryEnqueue(item with {Revision=2,IdempotencyKey="revision-2"})&&queue.Count==1,"new scene revision supersedes queued older work");
|
||||
Check(!queue.TryEnqueue(item),"stale offline revision cannot replace newer work");
|
||||
queue.Acknowledge("revision-1");Check(queue.Count==1,"old acknowledgement cannot remove newer work");
|
||||
queue.Acknowledge("revision-2");Check(queue.Count==0,"matching idempotency acknowledgement retires work");
|
||||
for(var n=1;n<=DeferredWorkQueue.Capacity;n++)queue.TryEnqueue(item with{SceneId=n,IdempotencyKey="scene-"+n});
|
||||
Check(!queue.TryEnqueue(item with{SceneId=999}),"durable queue rejects capacity overflow");
|
||||
}
|
||||
finally{Directory.Delete(queueDirectory,true);}
|
||||
|
||||
var pipeName="pd-phase1-test-"+Guid.NewGuid().ToString("N");var serverSessions=new SessionManager();var stopHost=new CancellationTokenSource();
|
||||
Task StartHost(CancellationToken token)=>Task.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.");
|
||||
48
PlotDirector.NativeCompanion/Vsto/AgentProcess.cs
Normal file
48
PlotDirector.NativeCompanion/Vsto/AgentProcess.cs
Normal file
@ -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);
|
||||
}
|
||||
}
|
||||
32
PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs
Normal file
32
PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs
Normal file
@ -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<WordAdapter> getAdapter;
|
||||
private Office.IRibbonUI ui;
|
||||
public NativeRibbon(Func<WordAdapter> 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");
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
<Project ToolsVersion="Current" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<ProjectGuid>{42996908-DB24-4A55-AFF1-1017A31D7206}</ProjectGuid>
|
||||
<ProjectTypeGuids>{BAA0C2D2-18E2-41B9-852F-F413020CAA33};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
|
||||
<Configuration Condition="'$(Configuration)'==''">Debug</Configuration><Platform Condition="'$(Platform)'==''">AnyCPU</Platform>
|
||||
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects><OutputType>Library</OutputType><TargetFrameworkVersion>v4.8</TargetFrameworkVersion><LangVersion>latest</LangVersion>
|
||||
<RootNamespace>PlotDirector.WordAddIn</RootNamespace><AssemblyName>PlotDirector.WordAddIn</AssemblyName>
|
||||
<OfficeApplication>Word</OfficeApplication><OfficeVersion>15.0</OfficeVersion><VSTO_TrustAssembliesLocation>true</VSTO_TrustAssembliesLocation>
|
||||
<LoadBehavior>3</LoadBehavior><FriendlyName>PlotDirector Word Companion (Phase 1)</FriendlyName><Description>PlotDirector by Nick Beckley — native prototype</Description>
|
||||
<ProductName>PlotDirector Word Companion</ProductName><PublisherName>Nick Beckley</PublisherName><SignManifests>false</SignManifests><GenerateManifests>true</GenerateManifests>
|
||||
<OutputPath>bin\$(Configuration)\</OutputPath><DebugSymbols>true</DebugSymbols>
|
||||
<VSToolsPath Condition="'$(VSToolsPath)'==''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" /><Reference Include="System.Core" /><Reference Include="System.Windows.Forms" /><Reference Include="System.Drawing" /><Reference Include="System.Xml" /><Reference Include="Microsoft.CSharp" /><Reference Include="netstandard" />
|
||||
<Reference Include="Microsoft.Office.Interop.Word"><EmbedInteropTypes>true</EmbedInteropTypes></Reference>
|
||||
<Reference Include="office"><EmbedInteropTypes>true</EmbedInteropTypes></Reference>
|
||||
<Reference Include="Microsoft.Office.Tools" /><Reference Include="Microsoft.Office.Tools.Common" /><Reference Include="Microsoft.Office.Tools.Common.v4.0.Utilities"><Private>true</Private></Reference>
|
||||
<Reference Include="Microsoft.Office.Tools.Word" /><Reference Include="Microsoft.Office.Tools.Word.v4.0.Utilities" />
|
||||
<Reference Include="Microsoft.VisualStudio.Tools.Applications.Runtime" />
|
||||
<ProjectReference Include="..\Protocol\PlotDirector.Companion.Protocol.csproj"><Name>PlotDirector.Companion.Protocol</Name></ProjectReference>
|
||||
<ProjectReference Include="..\Client\PlotDirector.Companion.Client.csproj"><Name>PlotDirector.Companion.Client</Name></ProjectReference>
|
||||
<Compile Include="ThisAddIn.cs" /><Compile Include="ThisAddIn.Designer.cs"><DependentUpon>ThisAddIn.cs</DependentUpon></Compile>
|
||||
<Compile Include="WordAdapter.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<None Include="ThisAddIn.Designer.xml"><DependentUpon>ThisAddIn.cs</DependentUpon></None>
|
||||
<EmbeddedResource Include="Ribbon.xml" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<Import Project="$(VSToolsPath)\OfficeTools\Microsoft.VisualStudio.Tools.Office.targets" />
|
||||
<ProjectExtensions><VisualStudio><FlavorProperties GUID="{BAA0C2D2-18E2-41B9-852F-F413020CAA33}">
|
||||
<ProjectProperties HostName="Word" HostPackage="{29A7B9D7-A7F1-4328-8EF0-6B2D1A56B2C1}" OfficeVersion="15.0" VstxVersion="4.0" ApplicationType="Word" Language="cs" DebugInfoExeName="#Software\Microsoft\Office\16.0\Word\InstallRoot\Path#WINWORD.EXE" DebugInfoCommandLine="/x" />
|
||||
<Host Name="Word" GeneratedCodeNamespace="PlotDirector.WordAddIn" IconIndex="0"><HostItem Name="ThisAddIn" Code="ThisAddIn.cs" CanonicalName="AddIn" CanActivate="false" IconIndex="1" Blueprint="ThisAddIn.Designer.xml" GeneratedCode="ThisAddIn.Designer.cs" /></Host>
|
||||
</FlavorProperties></VisualStudio></ProjectExtensions>
|
||||
</Project>
|
||||
@ -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)]
|
||||
11
PlotDirector.NativeCompanion/Vsto/Ribbon.xml
Normal file
11
PlotDirector.NativeCompanion/Vsto/Ribbon.xml
Normal file
@ -0,0 +1,11 @@
|
||||
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="OnLoad">
|
||||
<ribbon><tabs><tab id="PlotDirectorTab" label="PlotDirector">
|
||||
<group id="PlotDirectorConnection" label="Word Companion · Phase 1">
|
||||
<labelControl id="PlotDirectorStatus" getLabel="GetStatus" />
|
||||
<button id="PlotDirectorConnect" label="Connect / Sign In" imageMso="ConnectToExternalData" onAction="Connect" screentip="Reconnect local agent" supertip="Native server sign-in is not yet available. Existing Office.js sign-in remains unchanged." />
|
||||
<button id="PlotDirectorSync" label="Synchronise Now" imageMso="RefreshAll" onAction="Synchronize" getEnabled="CanSynchronize" supertip="Refresh local structural snapshot only. Server/prose sync is unavailable in Phase 1." />
|
||||
<button id="PlotDirectorSettings" label="Settings" imageMso="PropertySheet" onAction="Settings" />
|
||||
<button id="PlotDirectorDiagnostics" label="Diagnostics" imageMso="Info" onAction="Diagnostics" />
|
||||
</group>
|
||||
</tab></tabs></ribbon>
|
||||
</customUI>
|
||||
18
PlotDirector.NativeCompanion/Vsto/ThisAddIn.Designer.cs
generated
Normal file
18
PlotDirector.NativeCompanion/Vsto/ThisAddIn.Designer.cs
generated
Normal file
@ -0,0 +1,18 @@
|
||||
// VSTO host-item plumbing. Validate/regenerate against the supported Windows VS
|
||||
// Office template before accepting a desktop build; this is not a COM add-in shim.
|
||||
namespace PlotDirector.WordAddIn
|
||||
{
|
||||
[Microsoft.VisualStudio.Tools.Applications.Runtime.StartupObject(0)]
|
||||
public sealed partial class ThisAddIn : Microsoft.Office.Tools.AddInBase
|
||||
{
|
||||
internal Microsoft.Office.Interop.Word.Application Application;
|
||||
public ThisAddIn(Microsoft.Office.Tools.Word.ApplicationFactory factory, System.IServiceProvider provider)
|
||||
: base(factory, provider, "AddIn", "ThisAddIn") { }
|
||||
protected override void Initialize()
|
||||
{
|
||||
base.Initialize();
|
||||
Application = GetHostItem<Microsoft.Office.Interop.Word.Application>(typeof(Microsoft.Office.Interop.Word.Application), "Application");
|
||||
}
|
||||
protected override void FinishInitialization() { InternalStartup(); OnStartup(); }
|
||||
}
|
||||
}
|
||||
3
PlotDirector.NativeCompanion/Vsto/ThisAddIn.Designer.xml
Normal file
3
PlotDirector.NativeCompanion/Vsto/ThisAddIn.Designer.xml
Normal file
@ -0,0 +1,3 @@
|
||||
<hostitem:hostItem hostitem:baseType="Microsoft.Office.Tools.AddInBase" hostitem:namespace="PlotDirector.WordAddIn" hostitem:className="ThisAddIn" hostitem:identifier="ThisAddIn" hostitem:primaryCookie="AddIn" hostitem:master="true" hostitem:factoryType="Microsoft.Office.Tools.Word.ApplicationFactory" hostitem:startupIndex="0" xmlns:hostitem="http://schemas.microsoft.com/2004/VisualStudio/Tools/Applications/HostItem.xsd">
|
||||
<hostitem:hostObject hostitem:name="Application" hostitem:identifier="Application" hostitem:type="Microsoft.Office.Interop.Word.Application" hostitem:cookie="Application" hostitem:modifier="Internal" />
|
||||
</hostitem:hostItem>
|
||||
22
PlotDirector.NativeCompanion/Vsto/ThisAddIn.cs
Normal file
22
PlotDirector.NativeCompanion/Vsto/ThisAddIn.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Windows.Forms;
|
||||
using Office = Microsoft.Office.Core;
|
||||
|
||||
namespace PlotDirector.WordAddIn
|
||||
{
|
||||
public sealed partial class ThisAddIn
|
||||
{
|
||||
private WordAdapter adapter;
|
||||
private NativeRibbon ribbon;
|
||||
private void InternalStartup()
|
||||
{
|
||||
Startup += (_, __) => {
|
||||
try { adapter = new WordAdapter(Application, () => ribbon?.Invalidate()); }
|
||||
catch (Exception) { /* Companion failure must not prevent Word startup. Diagnostics remains available. */ }
|
||||
};
|
||||
Shutdown += (_, __) => { try { adapter?.Dispose(); } catch (Exception) { } };
|
||||
}
|
||||
protected override Office.IRibbonExtensibility CreateRibbonExtensibilityObject()
|
||||
=> ribbon = new NativeRibbon(() => adapter);
|
||||
}
|
||||
}
|
||||
443
PlotDirector.NativeCompanion/Vsto/WordAdapter.cs
Normal file
443
PlotDirector.NativeCompanion/Vsto/WordAdapter.cs
Normal file
@ -0,0 +1,443 @@
|
||||
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 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> 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 int documentCollectionGeneration;
|
||||
private double lastBatchMs;
|
||||
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 1\nAgent: " + ConnectionState
|
||||
+ "\nServer authentication / 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 + "\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")
|
||||
{
|
||||
foreach (var doc in documents.Values) { CancelExtraction(doc); doc.NeedsSnapshot = true; }
|
||||
ScheduleSelection();
|
||||
}
|
||||
invalidateRibbon();
|
||||
});
|
||||
link.Received += message => {
|
||||
var description = message.Status + (string.IsNullOrEmpty(message.ChapterTitle) ? "" : " · " + message.ChapterTitle)
|
||||
+ (string.IsNullOrEmpty(message.SceneTitle) ? "" : " / " + message.SceneTitle);
|
||||
if (message.Status != "ok" || !string.IsNullOrEmpty(message.ChapterTitle)) PostToUi(() => {
|
||||
if(message.Status!="ok"&&message.Status!="ready"&&message.Status!="awaiting-structure")
|
||||
{
|
||||
var failed=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);
|
||||
if(failed!=null){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 += _ => { busyFailures++; 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) return;
|
||||
documentCollectionGeneration++;
|
||||
scheduler.Post("open:" + Guid.NewGuid().ToString("N"), () => {
|
||||
if (documents.ContainsKey(document) || documents.Count >= ProtocolVersion.MaxDocuments) return;
|
||||
var state = new LocalDocument(document);
|
||||
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));
|
||||
invalidateRibbon();
|
||||
});
|
||||
}
|
||||
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); ScheduleSelection(); 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))
|
||||
{
|
||||
state.End = documentEnd; state.Revision++; state.NeedsSnapshot = true;
|
||||
CancelExtraction(state); link.Register(Descriptor(state));
|
||||
}
|
||||
state.WasSaved = saved;
|
||||
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 RequestSnapshot()
|
||||
{
|
||||
if (active == null) return;
|
||||
active.Revision++; active.NeedsSnapshot = true; CancelExtraction(active);
|
||||
link.Register(Descriptor(active)); ScheduleSnapshot(active);
|
||||
}
|
||||
private void ScheduleSnapshot(LocalDocument doc)
|
||||
{
|
||||
if (doc.Extraction != null || ConnectionState != "connected") return;
|
||||
doc.Extraction = new Extraction { Snapshot = Guid.NewGuid(), Revision=doc.Revision };
|
||||
scheduler.Post("extract:"+doc.Session,() => ExtractBatch(doc));
|
||||
}
|
||||
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="snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,End=doc.End}))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<doc.End)
|
||||
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>=doc.End)
|
||||
{
|
||||
if(!link.TryPost(new Message{Kind="snapshot-end",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot}))return;
|
||||
doc.NeedsSnapshot=false;doc.Extraction=null;
|
||||
// The committed snapshot resolves the current positional selection.
|
||||
scheduler.Post("selection",CaptureSelection);return;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(COMException)
|
||||
{ busyFailures++;CancelExtraction(doc);doc.NeedsSnapshot=true;scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1)); }
|
||||
catch(InvalidOperationException)
|
||||
{ CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped: unsupported range/marker density. Use Diagnostics; Word remains usable."; }
|
||||
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]);
|
||||
paragraphRange=Com(()=>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(doc.End,Math.Min(extraction.ParagraphEnd,start+ProtocolVersion.MaxParagraphCharacters));
|
||||
if(end<=start)throw new InvalidOperationException("Non-advancing Word range.");
|
||||
textRange=Com(()=>doc.Document.Range(start,end));var text=Com(()=>textRange.Text) ?? "";
|
||||
extraction.Position=end;
|
||||
return new Message{Kind="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);
|
||||
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);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(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="snapshot-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Extraction.Snapshot});
|
||||
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)){CancelExtraction(state);state.NeedsSnapshot=true;}
|
||||
}
|
||||
private void BeforeClose(Word.Document document,ref bool cancel)
|
||||
{
|
||||
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(250));
|
||||
if(!documents.TryGetValue(document,out var state))return;
|
||||
CancelExtraction(state);
|
||||
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;}
|
||||
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();
|
||||
if(!disposed&&active!=null&&ConnectionState=="connected"&&metricClock.ElapsedMilliseconds>=1000)
|
||||
{
|
||||
metricClock.Restart();
|
||||
link.TryPost(new Message{Kind="metrics",SessionId=active.Session,Revision=active.Revision,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
|
||||
}
|
||||
}
|
||||
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 p=properties;property=Com<object>(()=>p[name]);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;
|
||||
link.Dispose();documents.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 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;public int OutlineLevel;public bool Begun;public Message Pending;}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,13 @@
|
||||
param([Parameter(Mandatory=$true)][string]$CertificateThumbprint)
|
||||
$ErrorActionPreference='Stop'
|
||||
$root=Split-Path $PSScriptRoot -Parent
|
||||
$vswhere=Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
|
||||
$msbuild=& $vswhere -latest -products '*' -find 'MSBuild\**\Bin\MSBuild.exe' | Select-Object -First 1
|
||||
if(!$msbuild){throw 'Visual Studio MSBuild with Office/VSTO development tools is required.'}
|
||||
$project=Join-Path $root 'Vsto\PlotDirector.WordAddIn.csproj'
|
||||
& $msbuild $project /restore /t:Build /p:Configuration=Debug /p:SignManifests=true "/p:ManifestCertificateThumbprint=$CertificateThumbprint"
|
||||
if($LASTEXITCODE -ne 0){throw 'VSTO build failed; do not register or install the add-in.'}
|
||||
$agent=Join-Path $root 'Vsto\bin\Debug\Agent'
|
||||
dotnet publish (Join-Path $root 'Agent\PlotDirector.Companion.Agent.csproj') -c Debug -r win-x64 --self-contained false -o $agent
|
||||
if($LASTEXITCODE -ne 0){throw 'Agent publish failed.'}
|
||||
Write-Output 'Developer outputs prepared only. Review/trust the signed test manifest in Visual Studio. No installation or automatic update was performed.'
|
||||
@ -0,0 +1,46 @@
|
||||
# Pure OOXML fixture generation: does not start Word, connect to PlotDirector or alter existing files.
|
||||
param([Parameter(Mandatory=$true)][string]$OutputDirectory)
|
||||
$ErrorActionPreference='Stop'
|
||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
New-Item -ItemType Directory -Force -Path $OutputDirectory | Out-Null
|
||||
function New-Fixture([string]$Name,[int]$Words,[int]$WordsPerParagraph,[int]$Book) {
|
||||
$target=Join-Path $OutputDirectory "$Name.docx"
|
||||
if(Test-Path $target){throw "Refusing to overwrite $target"}
|
||||
$guid=[Guid]::NewGuid().ToString('D')
|
||||
$builder=New-Object System.Text.StringBuilder
|
||||
[void]$builder.Append('<?xml version="1.0" encoding="utf-8"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>')
|
||||
$remaining=$Words;$chapter=0;$scene=0;$paragraph=0
|
||||
while($remaining -gt 0){
|
||||
if($paragraph % 100 -eq 0){
|
||||
$chapter++
|
||||
[void]$builder.Append("<w:sdt><w:sdtPr><w:tag w:val=`"PD-CHAPTER-$($Book*1000+$chapter)`"/></w:sdtPr><w:sdtContent><w:p><w:pPr><w:pStyle w:val=`"Heading1`"/></w:pPr><w:r><w:t>Chapter $chapter</w:t></w:r></w:p></w:sdtContent></w:sdt>")
|
||||
}
|
||||
if($paragraph % 20 -eq 0){
|
||||
$scene++
|
||||
[void]$builder.Append("<w:sdt><w:sdtPr><w:tag w:val=`"PD-SCENE-$($Book*10000+$scene)`"/></w:sdtPr><w:sdtContent><w:p><w:pPr><w:pStyle w:val=`"Heading2`"/></w:pPr><w:r><w:t>Scene $scene</w:t></w:r></w:p></w:sdtContent></w:sdt>")
|
||||
}
|
||||
$take=[Math]::Min($WordsPerParagraph,$remaining)
|
||||
$text=(1..$take | ForEach-Object {'word'}) -join ' '
|
||||
[void]$builder.Append("<w:p><w:r><w:t>$text</w:t></w:r></w:p>")
|
||||
$remaining-=$take;$paragraph++
|
||||
}
|
||||
[void]$builder.Append('<w:sectPr/></w:body></w:document>')
|
||||
$entries=@{
|
||||
'[Content_Types].xml'='<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/><Override PartName="/docProps/custom.xml" ContentType="application/vnd.openxmlformats-officedocument.custom-properties+xml"/></Types>'
|
||||
'_rels/.rels'='<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rDoc" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/><Relationship Id="rProps" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties" Target="docProps/custom.xml"/></Relationships>'
|
||||
'word/_rels/document.xml.rels'='<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>'
|
||||
'word/styles.xml'='<?xml version="1.0"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:style w:type="paragraph" w:styleId="Normal"><w:name w:val="Normal"/></w:style><w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:pPr><w:outlineLvl w:val="0"/></w:pPr></w:style><w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:pPr><w:outlineLvl w:val="1"/></w:pPr></w:style></w:styles>'
|
||||
'word/document.xml'=$builder.ToString()
|
||||
'docProps/custom.xml'="<?xml version=`"1.0`"?><Properties xmlns=`"http://schemas.openxmlformats.org/officeDocument/2006/custom-properties`" xmlns:vt=`"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes`"><property fmtid=`"{D5CDD505-2E9C-101B-9397-08002B2CF9AE}`" pid=`"2`" name=`"PlotDirector.Native.DocumentGuid`"><vt:lpwstr>$guid</vt:lpwstr></property><property fmtid=`"{D5CDD505-2E9C-101B-9397-08002B2CF9AE}`" pid=`"3`" name=`"PlotDirector.Native.ProjectID`"><vt:lpwstr>1</vt:lpwstr></property><property fmtid=`"{D5CDD505-2E9C-101B-9397-08002B2CF9AE}`" pid=`"4`" name=`"PlotDirector.Native.BookID`"><vt:lpwstr>$Book</vt:lpwstr></property></Properties>"
|
||||
}
|
||||
$stream=[System.IO.File]::Open($target,[System.IO.FileMode]::CreateNew)
|
||||
$zip=New-Object System.IO.Compression.ZipArchive($stream,[System.IO.Compression.ZipArchiveMode]::Create)
|
||||
try{foreach($item in $entries.GetEnumerator()){$entry=$zip.CreateEntry($item.Key);$writer=New-Object System.IO.StreamWriter($entry.Open(),(New-Object System.Text.UTF8Encoding($false)));try{$writer.Write($item.Value)}finally{$writer.Dispose()}}}finally{$zip.Dispose();$stream.Dispose()}
|
||||
[pscustomobject]@{File=$target;ProseWords=$Words;Paragraphs=$paragraph;Book=$Book;ManuscriptGuid=$guid}
|
||||
}
|
||||
@(
|
||||
New-Fixture 'Discovery-190k' 190000 60 101
|
||||
New-Fixture 'Reckoning-250k' 250000 60 102
|
||||
New-Fixture 'Redemption-many-short' 250000 10 103
|
||||
New-Fixture 'Long-paragraph-250k' 250000 250000 104
|
||||
) | ConvertTo-Json | Set-Content (Join-Path $OutputDirectory 'fixtures.json')
|
||||
@ -0,0 +1,10 @@
|
||||
param([Parameter(Mandatory=$true)][string]$OutputFile,[int]$Seconds=300)
|
||||
$ErrorActionPreference='Stop'
|
||||
if(Test-Path $OutputFile){throw 'Choose a new measurement filename'}
|
||||
$rows=for($i=0;$i -lt $Seconds;$i++){
|
||||
foreach($p in Get-Process -ErrorAction SilentlyContinue | Where-Object {$_.ProcessName -in @('WINWORD','PlotDirector.Companion.Agent')}){
|
||||
[pscustomobject]@{Utc=[DateTime]::UtcNow.ToString('o');Process=$p.ProcessName;PID=$p.Id;WorkingSetBytes=$p.WorkingSet64;PrivateBytes=$p.PrivateMemorySize64;TotalCpuSeconds=$p.TotalProcessorTime.TotalSeconds;Handles=$p.HandleCount}
|
||||
}
|
||||
Start-Sleep -Seconds 1
|
||||
}
|
||||
$rows | Export-Csv -NoTypeInformation -Path $OutputFile
|
||||
76
PlotDirector.NativeCompanion/WindowsValidation/README.md
Normal file
76
PlotDirector.NativeCompanion/WindowsValidation/README.md
Normal file
@ -0,0 +1,76 @@
|
||||
# Windows / real Word validation gate
|
||||
|
||||
**Not executed on the Linux implementation host.** Passing managed tests or generating these sources does not prove VSTO compilation/loading, COM behaviour, Windows pipe ACLs or Word responsiveness. Do not install for authors or distribute until this gate is reviewed and passed.
|
||||
|
||||
## 1. Build prerequisites and isolated developer setup
|
||||
|
||||
Use a disposable Windows desktop user/profile with supported desktop Word, Visual Studio with Office/VSTO development workload, Office PIAs/VSTO Runtime, .NET Framework 4.8 developer pack and .NET 10 SDK/runtime. Record OS/Word build, Office bitness, Visual Studio/MSBuild versions, installed add-ins and CPU/RAM/storage. Test both supported Office bitnesses on separate machines if both will be supported. The add-in DLL is AnyCPU; the agent is independent win-x64 in the developer helper (qualify Windows ARM64/x86 separately).
|
||||
|
||||
1. Clone the exact Phase 1 commit. Build the managed `PlotLine.slnx`; run portable native tests. These do not register an add-in or connect to the server.
|
||||
2. Open `NativeCompanion.Windows.sln` in Visual Studio. Confirm Office Tools resolves all Microsoft.Office.Tools and PIAs, and inspect/validate the ThisAddIn host-item/designer against a new Word VSTO template from that installed VS version. The checked-in host plumbing is source foundation, not a Linux-verified generated artifact. If regeneration is required, review its diff; do not replace adapter logic or switch to a COM shim.
|
||||
3. Create/select a **local developer test signing certificate** in the Windows certificate store (never add private keys to Git). Run `Build-Developer.ps1 -CertificateThumbprint <your-test-thumbprint>` from PowerShell. It builds the VSTO project through VS MSBuild and places a framework-dependent win-x64 agent under `Vsto/bin/Debug/Agent/`. No installer/updater is created.
|
||||
4. Do not sideload an unsigned/untrusted manifest by weakening machine security policy. Use normal Visual Studio F5/developer trust with the signed local test output. If manifest generation, designer activation, registration or loading fails, capture the failure and stop native acceptance; source presence is not a successful VSTO build.
|
||||
5. Launch Word under the debugger with this prototype only and a new **synthetic** document. Confirm the small PlotDirector ribbon. Record VSTO load/startup time, Word thread/STA and agent PID. Never use a real author manuscript for marker writes in this phase. No Production or Development deployment is part of this procedure.
|
||||
|
||||
## 2. Create deterministic synthetic manuscripts
|
||||
|
||||
Run `Generate-Fixtures.ps1 -OutputDirectory <new-empty-directory>`. It constructs DOCX ZIP/XML without automating Word or making server calls, refuses existing filenames, and writes a manifest with GUIDs and arbitrary test project/book IDs.
|
||||
|
||||
- Discovery: 190,000 prose words, 60-word paragraphs.
|
||||
- Reckoning: 250,000 prose words, 60-word paragraphs.
|
||||
- Redemption: 250,000 prose words, ten-word paragraphs (many short/repeated paragraphs).
|
||||
- Long paragraph: 250,000 words in one prose paragraph, to verify bounded range extraction.
|
||||
|
||||
Headings add extra words beyond those prose totals. Every document has native GUID/project/book test properties and unique PD chapter/scene tags. These IDs are local test metadata and **not server-verified**. Also prepare: a blank document, a read-only copy, a close-cancel case, a copied/Save As GUID case, nested controls, bookmark fallback markers, a document with >8 controls/bookmarks in one paragraph (must stop safely), comments, tracked changes and protected content. Preserve original ZIPs for later no-prose-change comparisons. Metadata persistence must not be confused with save confirmation.
|
||||
|
||||
The generator itself has not been executed with Windows PowerShell/Word on Linux. Validate OOXML opens without repair before accepting any performance result; malformed fixture generation is a fixture failure, not a Word adapter result.
|
||||
|
||||
## 3. Functional and security cases
|
||||
|
||||
| Case | Required observable result |
|
||||
|---|---|
|
||||
| Word startup with agent absent | Ribbon loads; no synchronous UI wait. Worker launches/contacts one agent; Word typing/scrolling remains usable. |
|
||||
| Open three generated books | Three distinct live SessionIds, three persistent ManuscriptIds and correct book associations. No document reuses another session. |
|
||||
| Switch repeatedly (50+ cycles) | Latest active session and positional chapter/scene correspond to the active document; repeated text cannot choose another occurrence. Agent instance/session/correlation records identify each event. |
|
||||
| Second Word process (`winword /x`) | Same per-user agent; a different WordInstanceId; no old disconnect/close retires the other process's sessions. |
|
||||
| Cursor movement / selection | Lightweight Range.Start/End event, latest coalesced event; completed structural snapshot resolves tags/heading positions. No full-document text match. |
|
||||
| Empty/unknown location | Awaiting-structure/unresolved state, never a guessed trusted server scene ID. |
|
||||
| Edit/insert/delete during extraction | Cancel/supersede obsolete snapshot; no stale revision commit. Rebuild after quiet period or manual command. Record the documented same-length-already-dirty limitation; this phase is not a complete edit journal. |
|
||||
| Save during pending work | Word save proceeds immediately; handler never sets Cancel or awaits agent/network. No automatic AI or prose upload. |
|
||||
| Close then cancel | Same session retained after cancelled close; no use-after-close COM calls. |
|
||||
| Actual close | Exact session retired, pending snapshot released; other books continue. |
|
||||
| Kill/restart agent at extraction midpoint | Word remains responsive; link reports offline; bounded work does not grow; restart reconciles open docs and starts fresh snapshot, never replays old fragments into a different document. |
|
||||
| Kill one Word process | Agent retires that lease/session state; other Word process continues. Agent exits after five minutes with no peers, not while another Word process remains attached. |
|
||||
| Missing/wrong agent executable | Only expected local Agent path used; Word remains functional, bounded reconnect/launch backoff; no shell/path search or network login inside VSTO. |
|
||||
| Pipe version mismatch | Explicit incompatible handshake, no document registration or mutation. |
|
||||
| Unauthorized Windows user | From a separate nonprivileged user, attempt connecting to the first user's pipe name: Windows ACL denies access. Record actual identities/result; Linux test delegate does not prove this. |
|
||||
| Pipe name squatting | A pipe server owned by a different user must fail the add-in's server-process SID verification. Same-user malicious software remains outside a meaningful OS-user boundary; signed packaging is a later hardening requirement. |
|
||||
| Bounded/invalid frames | Oversized prefix rejected before allocation, malformed JSON closes only offending peer, invalid revision/instance/session refused, capacity limits fail explicitly. |
|
||||
| Existing Office.js | Existing manifest/task pane and onboarding still work. New custom properties do not alter its settings bag. No native cookie scraping/token injection. |
|
||||
| Native server integration | Explicitly unavailable: no native sign-in or old user-only SignalR presence registration. Context/Intent/native synchronization is **not** accepted based on local position resolution. |
|
||||
|
||||
## 4. Measure responsiveness, extraction and recovery
|
||||
|
||||
Measure an add-in-disabled baseline first, then enabled trials (at least three per manuscript and operation). Keep same Word settings, device, document and other add-ins. Record warm/cold startup separately. Run `Measure-Processes.ps1 -OutputFile <new.csv> -Seconds 600` while exercising the trials; it records CPU totals and memory/handles for Word/agent, without COM reads.
|
||||
|
||||
Collect `%LOCALAPPDATA%/PlotDirector/Companion/agent.jsonl` and `.previous`, ribbon Diagnostics, VS debugger timings/thread IDs and Windows Performance Recorder/UI delay traces where available. Agent logs contain per-operation IPC elapsed time, queue depth, instance/session/correlation IDs; UI COM call/batch/tick timings are bounded telemetry. Timing summaries record call counts, total/max and counts over 30/100ms. No prose/token/path should appear in logs. Copy logs between trials to preserve rotation boundaries; live measurement is not guaranteed by the source code alone.
|
||||
|
||||
For each document/three-document run record:
|
||||
|
||||
- Individual COM call and extraction batch p50/p95/p99/max where complete samples are available; summary counts over 30ms/100ms. Initial practical target: ~20–30ms work slices. Flag any >100ms and investigate its exact COM call; do not claim the scheduler can preempt a slow Office call.
|
||||
- UI timer delay plus externally measured keystroke-to-display, scrolling latency, ribbon click response, save/close latency and visible hangs relative to baseline. A timer alone is not proof of typing latency.
|
||||
- Snapshot fragments/total characters/time/cancel count; completed vs cancelled revisions and no hidden repeated full-body reads on cursor-only movement.
|
||||
- Agent CPU, working/private memory and peak queue depth (FIFO ≤64, coalesced selections ≤32; agent snapshot character caps stated in README).
|
||||
- Time to offline detection/reconnect/reconciled state; no duplicate agents; no stale snapshot commit after restart.
|
||||
|
||||
Exercise continuous typing for two minutes during extraction, rapid cursor movement, scrolling while a large snapshot is pending, Save and Save As during pending work, close-cancel, three books switching and agent termination/restart. Add long paragraphs and many short/repeated paragraphs. Structural snapshot timing is **local**, not server manuscript synchronization timing.
|
||||
|
||||
Use a results CSV with columns: `commit, machine, OS, WordBuild, OfficeBitness, fixture, trial, action, wordCallP95Ms, wordCallMaxMs, batchP95Ms, typingLatencyP95Ms, scrollLatencyP95Ms, saveLatencyMs, closeLatencyMs, agentPeakCpu, agentPeakPrivateBytes, queuePeak, reconnectMs, result, evidencePath`.
|
||||
|
||||
Stop acceptance if typing, scroll/save/close is noticeably degraded, unsupported range handling loops, stale content appears as current, or a COM object crosses threads. Capture evidence and repair before moving to deployment/distribution. Do not replace missing measurements with green portable tests.
|
||||
|
||||
## 5. Separate server fixes
|
||||
|
||||
Before any future server deployment, apply migration 230 using the repository's verified Development backup/migration procedures and idle-work gate. This prototype does not apply it to the live database. Run the isolated marker security test and existing Office.js browser/Writer regressions. Hub names/signatures/events remain compatible, with stricter rejection for inaccessible/mismatched/stale build acknowledgements.
|
||||
|
||||
Phase 1 review must explicitly decide whether Windows measurements and auth/session dependencies are satisfied before full migration. No automatic updating, installer distribution or Production release is authorized here.
|
||||
@ -4,4 +4,10 @@
|
||||
<Project Path="Tools/WritingSolver/WritingSolver.csproj" />
|
||||
</Folder>
|
||||
<Project Path="PlotLine.Tests/PlotLine.Tests.csproj" />
|
||||
<Folder Name="/Native Companion/">
|
||||
<Project Path="PlotDirector.NativeCompanion/Protocol/PlotDirector.Companion.Protocol.csproj" />
|
||||
<Project Path="PlotDirector.NativeCompanion/Client/PlotDirector.Companion.Client.csproj" />
|
||||
<Project Path="PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj" />
|
||||
<Project Path="PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj" />
|
||||
</Folder>
|
||||
</Solution>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user