Move Word controls into the existing agent tray application and minimal adapter

This commit is contained in:
Nick Beckley 2026-11-05 21:13:08 +00:00
parent b7f1fbcaee
commit 07cd67aeaa
28 changed files with 429 additions and 723 deletions

View File

@ -17,7 +17,7 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable
if(request.SnapshotId==Guid.Empty||request.BookId<=0||request.Start<0||request.End<=request.Start||request.End-request.Start>120000){answer.Status="invalid-ai-chapter";return answer;}
if(!jobs.ContainsKey(descriptor.SessionId)&&jobs.Count>=32){answer.Status="ai-capacity";return answer;}
Clear(descriptor.SessionId);
var chapter=new AiChapterRequest{RequestId=request.SnapshotId,BookId=request.BookId,SessionId=descriptor.SessionId,ManuscriptId=descriptor.ManuscriptId,Revision=descriptor.Revision,ChapterStart=request.Start,ChapterEnd=request.End};
var chapter=new AiChapterRequest{RequestId=request.SnapshotId,BookId=request.BookId,SessionId=descriptor.SessionId,ManuscriptId=descriptor.ManuscriptId,Revision=descriptor.Revision,ChapterTitle=request.ChapterTitle.Length<=200?request.ChapterTitle:request.ChapterTitle[..200],ChapterStart=request.Start,ChapterEnd=request.End};
jobs[descriptor.SessionId]=new(chapter,request.AuthenticationContext);return answer;
}
if(!jobs.TryGetValue(descriptor.SessionId,out var job)||job.Chapter.RequestId!=request.SnapshotId){answer.Status="obsolete-ai-request";return answer;}
@ -30,7 +30,7 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable
if(job.Characters+f.Text.Length>120000){answer.Status="ai-chapter-too-large";break;}
if(job.Text.Length==0)job.ParagraphStart=f.Start;
job.Characters+=f.Text.Length;job.Text.Append(f.Text);job.Position=f.End;
if(f.CompletesParagraph){job.Paragraphs.Add(new(){Index=job.NextParagraph,Start=job.ParagraphStart,End=f.End,Text=job.Text.ToString()});job.Text.Clear();job.NextParagraph++;}
if(f.CompletesParagraph){job.Paragraphs.Add(new(){Index=job.NextParagraph,Start=job.ParagraphStart,End=f.End,Text=job.Text.ToString(),IsHeading=f.OutlineLevel<=2});job.Text.Clear();job.NextParagraph++;}
answer.Progress=(int)(100L*(job.Position-job.Chapter.ChapterStart)/(job.Chapter.ChapterEnd-job.Chapter.ChapterStart));break;
case "ai-submit":
if(job.Submitted)break;
@ -49,10 +49,11 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable
default:answer.Status="unsupported-operation";break;
}
var offset=Math.Max(0,request.Start);var result=job.Result;
answer.Ai=new(){RequestId=result.RequestId,State=result.State,Message=result.Message,Total=result.Scenes.Length,Offset=offset,Scenes=result.Scenes.Skip(offset).Take(ProtocolVersion.AnalysisPageSize).ToArray()};
answer.Ai=new(){RequestId=result.RequestId,State=result.State,Message=result.Message,Total=result.Scenes.Length,Offset=offset,ReviewPath=result.ReviewPath,Scenes=result.Scenes.Skip(offset).Take(ProtocolVersion.AnalysisPageSize).ToArray()};
return answer;
}
}
public AiChapterResult? Result(Guid session){lock(gate)return jobs.GetValueOrDefault(session)?.Result;}
public void Clear(Guid session)
{
lock(gate)if(jobs.Remove(session,out var job)){if(!job.Finished)job.Stop.Cancel();if(!job.Submitted){job.Finished=true;job.Stop.Dispose();}if(job.Submitted)_=cloud.CancelRemote(job.Chapter.RequestId);job.Paragraphs.Clear();}

View File

@ -22,6 +22,7 @@ public sealed class CloudGateway : IDisposable
private string state="Not signed in";
private ConnectionHealth health=new();
private int checking;private DateTime nextCheck;
private readonly Dictionary<string,AiChapterResult> successful=[];
private CompanionBook[] books=[];
private readonly string? settingsPath;
private static readonly JsonSerializerOptions Json=new(JsonSerializerDefaults.Web);
@ -47,7 +48,7 @@ public sealed class CloudGateway : IDisposable
{
if(Interlocked.Exchange(ref checking,1)!=0)return;
Guid context;lock(gate){context=authenticationContext;nextCheck=DateTime.UtcNow.AddMinutes(2);health.Server="checking";}
try{var result=await Get<ConnectionHealth>("api/native-companion/connection",context);lock(gate)if(authenticationContext==context){result.VerifiedUtc=DateTime.UtcNow;health=result;state="Signed in (verified)";}}
try{var result=await Get<ConnectionHealth>("api/native-companion/connection",context);var accessible=await Get<CompanionBook[]>("api/native-companion/books",context);lock(gate)if(authenticationContext==context){books=accessible.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).ToArray();result.VerifiedUtc=DateTime.UtcNow;health=result;state="Signed in (verified)";}}
catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException){lock(gate)if(authenticationContext==context){health.Server=token==null?"unknown":"offline";health.Explanation="Server verification failed. Check connection; local detection remains available.";}}
finally{Volatile.Write(ref checking,0);}
}
@ -84,13 +85,14 @@ public sealed class CloudGateway : IDisposable
{lock(gate)if(pairing==stop){state="Sign-in failed or expired. Check the site address and try Connect again.";health=new(){Server="unverified",Authentication="not-signed-in",Explanation=state};}}
});
}
public void SignOut(){lock(gate){pairing?.Cancel();pairing=null;authenticationContext=Guid.NewGuid();token=null;books=[];state="Not signed in";health=new();}}
public void SignOut(){DisconnectPresence();lock(gate){pairing?.Cancel();pairing=null;authenticationContext=Guid.NewGuid();token=null;books=[];state="Not signed in";health=new();successful.Clear();}}
public bool Allows(Guid context,int bookId)
{lock(gate){Expire();return token!=null&&context==authenticationContext&&books.Any(b=>b.BookId==bookId);}}
public async Task<AiChapterResult> Analyse(AiChapterRequest chapter,CancellationToken cancellation,Guid expectedContext)
{
var fingerprint=expectedContext+":"+chapter.BookId+":"+chapter.ManuscriptId+":"+Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{chapter.ChapterStart,chapter.ChapterEnd,chapter.Paragraphs})));
Uri site;string access;
lock(gate){if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");}
lock(gate){Expire();if(successful.TryGetValue(fingerprint,out var prior)&&authenticationContext==expectedContext&&token!=null)return new(){RequestId=chapter.RequestId,ChapterTitle=chapter.ChapterTitle,State="complete",Message="Unchanged chapter: reused saved AI suggestions without uploading prose.",ReviewPath=prior.ReviewPath,Scenes=prior.Scenes};if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");}
using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/analyse-chapter")){Content=JsonContent.Create(chapter,options:Json)};
request.Headers.Authorization=new AuthenticationHeaderValue("Bearer",access);
HttpResponseMessage responseValue;
@ -104,7 +106,7 @@ public sealed class CloudGateway : IDisposable
int count;while((count=await stream.ReadAsync(bytes,cancellation))>0){if(buffer.Length+count>1024*1024)throw new InvalidDataException("AI response too large.");buffer.Write(bytes,0,count);}
buffer.Position=0;var result=await JsonSerializer.DeserializeAsync<AiChapterResult>(buffer,Json,cancellation)??throw new InvalidDataException();
if(result.RequestId!=chapter.RequestId||result.State is not ("complete" or "failed" or "cancelled")||result.Message==null||result.Message.Length>2048||result.Scenes==null||result.Scenes.Length>500||result.Scenes.Any(s=>s==null||s.Start<chapter.ChapterStart||s.End>chapter.ChapterEnd||s.End<=s.Start||s.Title==null||s.Reason==null||s.Confidence==null||s.Confidence.Length>32||s.Kind!="Scene"||s.Origin!="AI"||s.Title.Length>200||s.Reason.Length>600))throw new InvalidDataException("Invalid AI mapping.");
lock(gate)if(authenticationContext==expectedContext){health.Server="online";health.Authentication="verified";health.VerifiedUtc=DateTime.UtcNow;health.Ai=result.State=="complete"?"last-request-succeeded":"request-failed";health.Explanation=result.Message;}
lock(gate)if(authenticationContext==expectedContext){health.Server="online";health.Authentication="verified";health.VerifiedUtc=DateTime.UtcNow;health.Ai=result.State=="complete"?"last-request-succeeded":"request-failed";health.Explanation=result.Message;if(result.State=="complete"){if(successful.Count>=64||successful.Values.Sum(r=>r.Scenes.Length)+result.Scenes.Length>8192)successful.Clear();successful[fingerprint]=result;}}
return result;
}
public async Task<T> Get<T>(string path,Guid expectedContext)
@ -119,7 +121,7 @@ public sealed class CloudGateway : IDisposable
{
using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,stop.Token);
if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(authenticationContext==context){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";}throw new InvalidOperationException("Sign-in expired. Connect again.");}
if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=DateTime.UtcNow;health.Explanation="Server rejected the saved-data request. See the document result.";}throw new InvalidOperationException(response.StatusCode==HttpStatusCode.Forbidden?"Access denied or subscription unavailable.":response.StatusCode==HttpStatusCode.NotFound?"No saved chapter/scene matches this book and Word marker.":"Server request failed. Check connection or update the server.");}
if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=DateTime.UtcNow;health.Explanation="Server rejected the saved-data request. See the document result.";if(response.StatusCode==HttpStatusCode.Forbidden)books=[];}throw new InvalidOperationException(response.StatusCode==HttpStatusCode.Forbidden?"Access denied or subscription unavailable.":response.StatusCode==HttpStatusCode.NotFound?"No saved chapter/scene matches this book and Word marker.":"Server request failed. Check connection or update the server.");}
await using var stream=await response.Content.ReadAsStreamAsync(stop.Token);using var buffer=new MemoryStream();var bytes=new byte[8192];int size;
while((size=await stream.ReadAsync(bytes,stop.Token))>0){if(buffer.Length+size>1024*1024)throw new InvalidDataException();buffer.Write(bytes,0,size);}buffer.Position=0;
var result=await JsonSerializer.DeserializeAsync<T>(buffer,Json,stop.Token);
@ -135,6 +137,13 @@ public sealed class CloudGateway : IDisposable
if(!path.StartsWith("/Books/Details/",StringComparison.Ordinal)&&!path.StartsWith("/Writing/Context?",StringComparison.Ordinal)&&!path.StartsWith("/Writing/Intent?",StringComparison.Ordinal))throw new InvalidDataException();
var url=new Uri(origin,path);if(url.GetLeftPart(UriPartial.Authority)!=origin.GetLeftPart(UriPartial.Authority))throw new InvalidDataException();openBrowser(url.AbsoluteUri);}
}
public void OpenSite(string page="book")
{Uri target;lock(gate){var site=origin??ValidateOrigin(ReadOrigin());target=new Uri(site,page switch{"context"=>"Writing/Context","intent"=>"Writing/Intent",_=>"/"});}openBrowser(target.AbsoluteUri);}
private void DisconnectPresence(){Uri? site;string? access;lock(gate){site=origin;access=token;}if(site==null||access==null)return;_ = Task.Run(async()=>{try{using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(5));using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/presence/disconnect"));request.Headers.Authorization=new("Bearer",access);using var response=await http.SendAsync(request,timeout.Token);}catch(Exception e)when(e is HttpRequestException or OperationCanceledException or ObjectDisposedException) {}});}
public void OpenCompanionPage(string path,Guid context)
{lock(gate){Expire();if(context!=authenticationContext||token==null||origin==null)throw new InvalidOperationException("Sign in first.");if(!path.StartsWith("/native-companion/",StringComparison.Ordinal))throw new InvalidDataException();var url=new Uri(origin,path);if(url.GetLeftPart(UriPartial.Authority)!=origin.GetLeftPart(UriPartial.Authority))throw new InvalidDataException();openBrowser(url.AbsoluteUri);}}
public async Task Presence(Guid instance,Guid session,NativePresence presence,Guid context)=>await Post<NativePresence>($"api/native-companion/instances/{instance}/documents/{session}/presence",presence,context);
public async Task RemovePresence(Guid instance,Guid session){Guid context;lock(gate)context=authenticationContext;try{await Send<NativePresence>(HttpMethod.Delete,$"api/native-companion/instances/{instance}/documents/{session}/presence",null,context);}catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException){}}
public async Task CancelRemote(Guid id)
{
try

View File

@ -53,7 +53,7 @@ public sealed class DocumentAnalysis(bool collectSuggestions = true)
private void Suggest(string kind,string text,string confidence,string reason)
{
if(suggestions.Count==Limit){truncated=true;return;}
var suggestion=new StructureSuggestion{Start=paragraphStart,Paragraph=paragraphs,Kind=kind,Title=text.Length>200?text[..200]:text,Confidence=confidence,Reason=reason,Origin=reason.StartsWith("Existing PlotDirector")?"Existing marker":"Local structure"};
var suggestion=new StructureSuggestion{Heading1=outline==1,Start=paragraphStart,Paragraph=paragraphs,Kind=kind,Title=text.Length>200?text[..200]:text,Confidence=confidence,Reason=reason,Origin=reason.StartsWith("Existing PlotDirector")?"Existing marker":"Local structure"};
if(kind=="Chapter"){if(chapter!=null)chapter.End=paragraphStart;chapter=suggestion;}
if(chapter!=null){suggestion.ChapterStart=chapter.Start;suggestion.ChapterTitle=chapter.Title;}
suggestions.Add(suggestion);

View File

@ -0,0 +1 @@
global using Message = PlotDirector.Companion.Protocol.Message;

View File

@ -17,7 +17,7 @@ public static class AgentEndpoint
}
}
public sealed class PipeHost(string pipeName, SessionManager sessions, Action<string>? log = null)
public sealed class PipeHost(string pipeName, SessionManager sessions, Action<string>? log = null,TrayCoordinator? control=null)
{
private readonly TimingSummary timings = new();
private int activePeers;
@ -56,7 +56,7 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action<st
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,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability},cancellation);
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability},cancellation);
log?.Invoke("peer-connected");
while (!cancellation.IsCancellationRequested)
{
@ -67,13 +67,14 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action<st
foreach(var metric in message.Metrics)timings.Record(metric);
var watch = Stopwatch.StartNew();
var answer = sessions.Apply(lease,message);
if(control!=null)answer=control.Exchange(instance,message,answer);
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())); }
finally { Interlocked.Decrement(ref activePeers); if(instance != Guid.Empty){sessions.Detach(instance,lease);control?.Disconnected(instance);} log?.Invoke("timing-summary="+System.Text.Json.JsonSerializer.Serialize(timings.Snapshot())); }
}
}
private static async Task<Message> ReadWithTimeout(Stream pipe,CancellationToken cancellation,TimeSpan duration)

View File

@ -1,4 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><Company>Nick Beckley</Company></PropertyGroup>
<Import Project="../DeveloperVersion.props" />
<PropertyGroup><AssemblyVersion>$(ApplicationVersion)</AssemblyVersion><FileVersion>$(ApplicationVersion)</FileVersion><Version>$(ApplicationVersion)</Version></PropertyGroup>
<PropertyGroup><OutputType>Exe</OutputType><TargetFrameworks>net10.0;net10.0-windows</TargetFrameworks><EnableWindowsTargeting>true</EnableWindowsTargeting><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><Company>Nick Beckley</Company></PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net10.0-windows'"><OutputType>WinExe</OutputType><UseWindowsForms>true</UseWindowsForms></PropertyGroup>
<ItemGroup><ProjectReference Include="../Protocol/PlotDirector.Companion.Protocol.csproj" /></ItemGroup>
</Project>

View File

@ -1,50 +1,18 @@
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())
internal static class Program
{
Console.CancelKeyPress += (_,e) => {e.Cancel=true;shutdown.Cancel();};
var log = new AgentLog(directory);
log.Write("agent-start protocol=1 authentication=browser-pairing publisher=Nick-Beckley");
using var cloud=new CloudGateway(settingsPath:Path.Combine(directory,"server-url.txt"));
using var ai=new ChapterAiWork(cloud);
var host=new PipeHost(AgentEndpoint.CurrentUserPipeName(),new SessionManager(cloud,ai,new DocumentWorkspaceWork(cloud)),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)
[STAThread]
private static int Main(string[] args)
{
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) { }
}
#if WINDOWS
return TrayApplication.Run(args);
#else
Console.Error.WriteLine("Run the Windows tray Companion on Windows; portable tests use its net10.0 core.");return 2;
#endif
}
}
internal 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){}}}
}

View File

@ -50,7 +50,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
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 "ping" or "tray-open") return answer;
if(message.Kind is "cloud-status" or "cloud-check" or "cloud-connect" or "cloud-signout")
{
answer.Kind="cloud-status";if(cloud==null)return Reject(answer,"cloud-unavailable");
@ -61,7 +61,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
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");
|| message.Documents.Any(d => d.Title==null||d.Title.Length>260||d.AssociationSite==null||d.AssociationSite.Length>2048||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.Documents.Any(d=>instances.Any(i=>i.Key!=message.WordInstanceId&&i.Value.Documents.ContainsKey(d.SessionId))))return Reject(answer,"foreign-session-identity");
if (message.Kind == "reconcile")
{
@ -99,6 +99,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
switch (message.Kind)
{
case "metrics": break;
case "adapter-result":break;
case "active": word.ActiveSession = message.SessionId; break;
case "selection":
if (message.Start < 0 || message.End < message.Start) return Reject(answer,"invalid-position");
@ -132,7 +133,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
document.Analysis=snapshot.Analysis;
totalBoundaries += boundaries.Count-document.Boundaries.Count;
document.Boundaries = boundaries;
document.SnapshotId = snapshot.Id;
document.SnapshotId = snapshot.Id;document.StructureEnd=snapshot.ExpectedEnd;
document.ContentFingerprint = StructuralParser.Fingerprint(snapshot.Fragments);
document.WordCount=snapshot.Counter.WordCount;
answer.WordCount=document.WordCount;
@ -151,6 +152,14 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
return answer;
}
}
public DocumentDescriptor? Descriptor(Guid instance,Guid session){lock(gate)return instances.GetValueOrDefault(instance)?.Documents.GetValueOrDefault(session)?.Descriptor;}
public StructureSuggestion[] Chapters(Guid instance,Guid session)
{
lock(gate){var document=instances.GetValueOrDefault(instance)?.Documents.GetValueOrDefault(session);var analysis=document?.Analysis;if(analysis==null)return [];
var chapters=Enumerable.Range(0,(analysis.Count+39)/40).SelectMany(i=>analysis.Page(i*40).Items).Where(s=>s.Kind=="Chapter"&&(s.Heading1||s.Origin=="Existing marker")).OrderBy(c=>c.Start).ToArray();
return chapters.Select((c,i)=>new StructureSuggestion{Kind="Chapter",Heading1=c.Heading1,Start=c.Start,End=i+1<chapters.Length?chapters[i+1].Start:document!.StructureEnd,Title=c.Title,Origin=c.Origin,Reason=c.Reason,Confidence=c.Confidence}).ToArray();
}
}
private static Message Reject(Message answer,string status) { answer.Status = status; return answer; }
private static void Resolve(DocumentState document, Message answer)
{
@ -164,7 +173,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
public Guid? ActiveSession(Guid instance) { lock(gate) return instances.GetValueOrDefault(instance)?.ActiveSession; }
public bool HasSession(Guid instance, Guid session) { lock(gate) return instances.TryGetValue(instance,out var word) && word.Documents.ContainsKey(session); }
private sealed class WordInstance(Guid lease) { public Guid Lease = lease; public long LastSequence; public Guid? ActiveSession; public Dictionary<Guid,DocumentState> Documents = []; }
private sealed class DocumentState(DocumentDescriptor descriptor) { public DocumentDescriptor Descriptor = descriptor; public int Cursor; public int? WordCount; public Snapshot? Pending; public Guid SnapshotId; public string ContentFingerprint=""; public List<StructuralBoundary> Boundaries = []; public DocumentAnalysis? Analysis; }
private sealed class DocumentState(DocumentDescriptor descriptor) { public DocumentDescriptor Descriptor = descriptor; public int Cursor;public int StructureEnd; public int? WordCount; public Snapshot? Pending; public Guid SnapshotId; public string ContentFingerprint=""; public List<StructuralBoundary> Boundaries = []; public DocumentAnalysis? Analysis; }
private sealed class Snapshot(Guid id,int expectedEnd,bool analyze) { public readonly DocumentAnalysis Counter=new(analyze); public DocumentAnalysis? Analysis=>analyze?Counter:null; public Guid Id = id; public int ExpectedEnd=expectedEnd; public bool LastComplete; public int End; public int NextParagraph=1; public int Characters; public List<ParagraphFragment> Fragments = []; }
}

View File

@ -0,0 +1,94 @@
#if WINDOWS
using System.Drawing;
using System.IO.Pipes;
using System.Windows.Forms;
namespace PlotDirector.Companion.Agent;
internal static class TrayApplication
{
public static int Run(string[] args)
{
var directory=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"PlotDirector","Companion");Directory.CreateDirectory(directory);
var endpoint=AgentEndpoint.CurrentUserPipeName();FileStream singleton;
try{singleton=new(Path.Combine(directory,"agent-"+System.Diagnostics.Process.GetCurrentProcess().SessionId+".lock"),FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None);}
catch(IOException){try{using var pipe=new NamedPipeClientStream(".",endpoint+".activate",PipeDirection.Out,PipeOptions.CurrentUserOnly);pipe.Connect(2000);pipe.WriteByte(1);}catch(IOException){}catch(TimeoutException){}return 0;}
using(singleton)using(var shutdown=new CancellationTokenSource())using(var cloud=new CloudGateway(settingsPath:Path.Combine(directory,"server-url.txt")))using(var ai=new ChapterAiWork(cloud)){
Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);
var log=new AgentLog(directory);var sessions=new SessionManager(cloud,ai,new DocumentWorkspaceWork(cloud));var control=new TrayCoordinator(sessions,cloud,ai);
using var window=new CompanionWindow(control,cloud,shutdown,directory);var handle=window.Handle;
control.OpenRequested+=()=>{if(!window.IsDisposed)window.BeginInvoke(new Action(window.Reveal));};
var host=new PipeHost(endpoint,sessions,log.Write,control);var serve=host.RunAsync(shutdown.Token);
var work=control.Tick(shutdown.Token);var heartbeat=control.Heartbeat(shutdown.Token);
var activate=Task.Run(async()=>{while(!shutdown.IsCancellationRequested){await using var pipe=new NamedPipeServerStream(endpoint+".activate",PipeDirection.In,1,PipeTransmissionMode.Byte,PipeOptions.Asynchronous|PipeOptions.CurrentUserOnly);await pipe.WaitForConnectionAsync(shutdown.Token);var value=new byte[1];if(await pipe.ReadAsync(value,shutdown.Token)>0)window.BeginInvoke(new Action(window.Reveal));}});
log.Write("tray-start publisher=Nick-Beckley");if(args.Contains("--open"))window.Reveal();
Application.Run();shutdown.Cancel();try{Task.WhenAll(serve,work,heartbeat,activate).Wait(TimeSpan.FromSeconds(3));}catch(AggregateException){}log.Write("tray-stop");
}return 0;
}
}
internal sealed class CompanionWindow:Form
{
private readonly TrayCoordinator control;private readonly CloudGateway cloud;private readonly CancellationTokenSource shutdown;private readonly string directory;
private readonly NotifyIcon tray;private readonly Icon brand=CreateBrandIcon();private readonly Dictionary<Guid,HashSet<int>> selections=[];private Guid renderedSession;private readonly System.Windows.Forms.Timer timer=new(){Interval=500};private bool exiting,refreshing;
private readonly ComboBox documents=new(){DropDownStyle=ComboBoxStyle.DropDownList,Dock=DockStyle.Fill,DisplayMember="Title"};
private readonly ComboBox books=new(){DropDownStyle=ComboBoxStyle.DropDownList,Dock=DockStyle.Fill,DisplayMember="Title",DropDownWidth=650};
private readonly TextBox site=new(){Dock=DockStyle.Fill,PlaceholderText="https://your-plotdirector-site/"};
private readonly Label status=new(){Dock=DockStyle.Fill,AutoSize=true};private readonly Label progressText=new(){AutoSize=true,Dock=DockStyle.Fill};
private readonly ProgressBar progress=new(){Dock=DockStyle.Fill,Maximum=100,Height=5};
private readonly CheckedListBox chapters=new(){Dock=DockStyle.Fill,CheckOnClick=true,HorizontalScrollbar=true};
private readonly TextBox diagnostics=new(){Multiline=true,ReadOnly=true,Dock=DockStyle.Fill,ScrollBars=ScrollBars.Vertical};
private readonly Button detect=new(){Text="Detect Chapters",AutoSize=true},analyse=new(){Text="Analyse selected chapters",AutoSize=true},cancel=new(){Text="Cancel",AutoSize=true},bookButton=new(){Text="Use selected book",AutoSize=true},review=new(){Text="Review in PlotDirector",AutoSize=true};
private readonly CheckBox remember=new(){Text="Remember in document metadata (save Word normally)",AutoSize=true};
private string documentKey="",bookKey="",chapterKey="";private int displayedBook=-1;private Guid displayedSession;private Guid selected;private string error="";
private TrayDocument? Current=>control.Documents.FirstOrDefault(d=>d.Session==selected);
public CompanionWindow(TrayCoordinator control,CloudGateway cloud,CancellationTokenSource shutdown,string directory)
{
this.control=control;this.cloud=cloud;this.shutdown=shutdown;this.directory=directory;
Icon=brand;Text="PlotDirector Companion";Font=new("Segoe UI",10);BackColor=Color.FromArgb(249,246,240);ForeColor=Color.FromArgb(58,49,44);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new(640,550);Size=new(850,720);
var layout=new TableLayoutPanel{Dock=DockStyle.Fill,Padding=new(18),ColumnCount=1,RowCount=9};layout.ColumnStyles.Add(new(SizeType.Percent,100));for(int i=0;i<9;i++)layout.RowStyles.Add(new(i==7?SizeType.Percent:SizeType.AutoSize,i==7?100:0));
layout.Controls.Add(new Label{Text="PlotDirector · Word at your side",Font=new(Font,FontStyle.Bold),AutoSize=true},0,0);
var connection=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=2};connection.ColumnStyles.Add(new(SizeType.Percent,100));connection.ColumnStyles.Add(new(SizeType.AutoSize));var signIn=Button("Connect / Sign In",()=>cloud.Connect(site.Text.Trim()));connection.Controls.Add(site,0,0);connection.Controls.Add(signIn,1,0);layout.Controls.Add(connection,0,1);
layout.Controls.Add(status,0,2);layout.Controls.Add(documents,0,3);
var association=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=2};association.ColumnStyles.Add(new(SizeType.Percent,100));association.ColumnStyles.Add(new(SizeType.AutoSize));association.Controls.Add(books,0,0);association.Controls.Add(bookButton,1,0);association.Controls.Add(remember,0,1);association.SetColumnSpan(remember,2);layout.Controls.Add(association,0,4);
var actions=new FlowLayoutPanel{AutoSize=true,Dock=DockStyle.Fill,WrapContents=true};actions.Controls.AddRange([detect,analyse,cancel,review,Button("Select all",()=>{for(var i=0;i<chapters.Items.Count;i++)chapters.SetItemChecked(i,true);}),Button("Clear selection",()=>{for(var i=0;i<chapters.Items.Count;i++)chapters.SetItemChecked(i,false);}),Button("Context",()=>Open("context")),Button("Intent",()=>Open("intent"))]);layout.Controls.Add(actions,0,5);
var p=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,RowCount=2};p.Controls.Add(progressText);p.Controls.Add(progress);layout.Controls.Add(p,0,6);
var tabs=new TabControl{Dock=DockStyle.Fill};var chapterTab=new TabPage("Heading 1 chapters");chapterTab.Controls.Add(chapters);var settings=new TabPage("Settings and diagnostics");settings.Controls.Add(diagnostics);var options=new FlowLayoutPanel{Dock=DockStyle.Bottom,AutoSize=true};options.Controls.AddRange([Button("Check connection",()=>_ = cloud.CheckConnection()),Button("Disconnect / forget sign-in",()=>cloud.SignOut()),Button("Open diagnostics folder",()=>System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(directory){UseShellExecute=true}))]);settings.Controls.Add(options);tabs.TabPages.AddRange([chapterTab,settings]);layout.Controls.Add(tabs,0,7);
layout.Controls.Add(new Label{AutoSize=true,Text="Chapter prose is sent only after confirmation. Manuscript text and saved story data are never overwritten."},0,8);Controls.Add(layout);
documents.SelectedIndexChanged+=(_,_)=>{if(!refreshing&&documents.SelectedItem is TrayDocument d){selected=d.Session;chapterKey="";RefreshState();}};
chapters.ItemCheck+=(_,e)=>{if(refreshing||renderedSession==Guid.Empty)return;if(!selections.TryGetValue(renderedSession,out var chosen)){if(selections.Count>=64)selections.Clear();selections[renderedSession]=chosen=[];}var start=((ChapterItem)chapters.Items[e.Index]).Start;if(e.NewValue==CheckState.Checked)chosen.Add(start);else chosen.Remove(start);};
detect.Click+=(_,_)=>Safe(()=>control.Detect(selected));cancel.Click+=(_,_)=>Safe(()=>control.Cancel(selected));
bookButton.Click+=(_,_)=>Safe(()=>{if(books.SelectedItem is not Protocol.CompanionBook book)return;if(remember.Checked&&MessageBox.Show("Remember this book in Word document metadata? This marks the document modified. It does not save or change prose.","Remember association",MessageBoxButtons.OKCancel)!=DialogResult.OK)return;control.SelectBook(selected,book.BookId,remember.Checked);});
analyse.Click+=(_,_)=>Safe(()=>{var chosen=chapters.CheckedItems.Cast<ChapterItem>().ToArray();if(chosen.Length==0)throw new InvalidOperationException("Select one or more chapters first.");var d=Current??throw new InvalidOperationException("Open a Word document.");if(MessageBox.Show($"Send {chosen.Length} selected chapters for the chosen book to PlotDirector AI? This uploads manuscript prose and may incur AI costs. Existing Word text and saved story records will not change.","Confirm chapter analysis",MessageBoxButtons.OKCancel)==DialogResult.OK)control.Analyse(d.Session,chosen.Select(c=>c.Start));});
review.Click+=(_,_)=>Safe(()=>Open("review"));
var menu=new ContextMenuStrip();menu.Items.Add("Open Companion",null,(_,_)=>Reveal());menu.Items.Add("Connect / Sign In",null,(_,_)=>{Reveal();site.Focus();});menu.Items.Add("Select Book",null,(_,_)=>{Reveal();books.Focus();});
var detectMenu=menu.Items.Add("Detect Chapters",null,(_,_)=>Safe(()=>control.Detect(selected)));var analyseMenu=menu.Items.Add("Analyse Manuscript",null,(_,_)=>{Reveal();chapters.Focus();});var openMenu=menu.Items.Add("Open PlotDirector",null,(_,_)=>Safe(()=>Open("book")));menu.Items.Add("Connection Status",null,(_,_)=>Reveal());menu.Items.Add("Settings",null,(_,_)=>{Reveal();tabs.SelectedIndex=1;});menu.Items.Add("Exit",null,(_,_)=>Exit());
menu.Opening+=(_,_)=>{detectMenu.Enabled=Current!=null;analyseMenu.Enabled=Current?.Book>0;openMenu.Enabled=!string.IsNullOrWhiteSpace(cloud.Status().ServerUrl);};
tray=new(){Icon=brand,Text="PlotDirector Companion",ContextMenuStrip=menu,Visible=true};tray.DoubleClick+=(_,_)=>Reveal();FormClosing+=(_,e)=>{if(!exiting){e.Cancel=true;Hide();}};timer.Tick+=(_,_)=>RefreshState();timer.Start();RefreshState();
}
private Button Button(string text,Action action){var button=new Button{Text=text,AutoSize=true};button.Click+=(_,_)=>Safe(action);return button;}
private void Safe(Action action){try{error="";action();}catch(Exception e)when(e is InvalidOperationException or ArgumentException or IOException or System.ComponentModel.Win32Exception){error=e.Message;}RefreshState();}
private void Open(string page){if(Current==null)cloud.OpenSite(page);else control.OpenPage(selected,page);}
public void Reveal(){Show();WindowState=FormWindowState.Normal;Activate();}
private void RefreshState()
{
var state=cloud.Status();var docs=control.Documents;var key=string.Join("|",docs.Select(d=>d.Session+":"+d.Title));refreshing=true;
try{if(key!=documentKey){documentKey=key;documents.DataSource=docs;if(!docs.Any(d=>d.Session==selected))selected=docs.FirstOrDefault(d=>d.Active)?.Session??docs.FirstOrDefault()?.Session??Guid.Empty;documents.SelectedItem=docs.FirstOrDefault(d=>d.Session==selected);}
var bkey=state.AuthenticationContext+string.Join("|",state.Books.Select(b=>b.BookId+":"+b.Title));if(bookKey!=bkey){bookKey=bkey;books.DataSource=state.Books;books.SelectedIndex=-1;displayedBook=-1;}
var d=Current;if(displayedSession!=selected||displayedBook!=(d?.Book??0)){displayedSession=selected;displayedBook=d?.Book??0;books.SelectedItem=state.Books.FirstOrDefault(b=>b.BookId==d?.Book);}
if(string.IsNullOrWhiteSpace(site.Text)&&!string.IsNullOrEmpty(state.ServerUrl))site.Text=state.ServerUrl;
status.Text="Word: "+(d==null?"unavailable":"connected")+" · Server: "+(state.Health?.Server??"unknown")+" · Authentication: "+(state.Health?.Authentication??"signed-out")+"\r\n"+state.Status+" · AI: "+(state.Health?.Ai??"unknown")+"\r\nBook: "+(state.Books.FirstOrDefault(b=>b.BookId==d?.Book)?.Title??"not selected")+"\r\nLocation: "+(d==null?"No document":string.Join(" / ",new[]{d.ChapterTitle,d.SceneTitle}.Where(t=>t.Length>0)))+" · Snapshot words (approx.): "+(d?.Words?.ToString("N0")??"not read / stale");
progressText.Text=string.IsNullOrEmpty(error)?d?.Status??"Open Word or sign in independently.":error;progress.Value=Math.Clamp(d?.Progress??0,0,100);
detect.Enabled=d!=null&&d.Job==Guid.Empty;analyse.Enabled=d!=null&&d.Book>0&&d.Chapters.Length>0&&d.Job==Guid.Empty;cancel.Enabled=d!=null;bookButton.Enabled=d!=null&&state.Books.Length>0&&d.Job==Guid.Empty;review.Enabled=d?.Book>0;
var ckey=d==null?"":d.Session+":"+d.Revision+string.Join("|",d.Chapters.Select(c=>c.Start+":"+c.End+":"+c.Title));if(chapterKey!=ckey){chapterKey=ckey;chapters.BeginUpdate();try{chapters.Items.Clear();renderedSession=d?.Session??Guid.Empty;if(d!=null){chapters.Items.AddRange(d.Chapters.Select(c=>(object)new ChapterItem(c.Start,c.Title)).ToArray());if(selections.TryGetValue(d.Session,out var checkedStarts))for(int i=0;i<chapters.Items.Count;i++)chapters.SetItemChecked(i,checkedStarts.Contains(((ChapterItem)chapters.Items[i]).Start));}}finally{chapters.EndUpdate();}}
diagnostics.Text="PlotDirector Companion by Nick Beckley\r\n"+typeof(CompanionWindow).Assembly.GetName().Version+"\r\n"+state.Health?.Explanation+"\r\nManual chapter upload only. No automatic prose synchronisation.\r\n"+(d==null?"No Word session.":d.WordDiagnostics+"\r\n"+$"Session {d.Session}\r\nRevision {d.Revision}\r\nErrors: "+string.Join("\r\n",d.Errors.TakeLast(10)))+"\r\nClose hides this window; Exit stops the tray process. Open Companion resumes it.";
}finally{refreshing=false;}
}
private void Exit(){exiting=true;File.WriteAllText(Path.Combine(directory,"paused"),"User exited Companion");shutdown.Cancel();tray.Visible=false;Application.Exit();}
protected override void Dispose(bool disposing){if(disposing){timer.Dispose();tray.Dispose();brand.Dispose();}base.Dispose(disposing);}
private static Icon CreateBrandIcon()
{
using var bitmap=new Bitmap(32,32);using(var graphics=Graphics.FromImage(bitmap)){graphics.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.AntiAlias;graphics.Clear(Color.Transparent);using var brush=new SolidBrush(Color.FromArgb(108,58,47));graphics.FillEllipse(brush,0,0,31,31);using var font=new Font("Segoe UI",19,FontStyle.Bold,GraphicsUnit.Pixel);using var ink=new SolidBrush(Color.FromArgb(255,244,223));graphics.DrawString("P",font,ink,7,3);}
var handle=bitmap.GetHicon();try{using var borrowed=Icon.FromHandle(handle);return (Icon)borrowed.Clone();}finally{DestroyIcon(handle);}
}
[System.Runtime.InteropServices.DllImport("user32.dll")]private static extern bool DestroyIcon(IntPtr handle);
private sealed record ChapterItem(int Start,string Title){public override string ToString()=>Title;}
}
#endif

View File

@ -0,0 +1,107 @@
using PlotDirector.Companion.Protocol;
namespace PlotDirector.Companion.Agent;
// One control centre in the existing agent. Exact-session commands only; no COM or UI objects.
public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,ChapterAiWork ai)
{
private readonly Guid agentInstance=Guid.NewGuid(),agentSession=Guid.NewGuid();private int lastBook;private Guid lastAuthentication;private long agentSequence;
private readonly object gate=new();private readonly Dictionary<Guid,TrayDocument> documents=[];
private readonly Dictionary<Guid,Queue<AdapterCommand>> commands=[];
public event Action? OpenRequested;
public TrayDocument[] Documents {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).ToArray();}}
public Message Exchange(Guid instance,Message request,Message answer)
{
lock(gate)
{
if(request.Kind=="tray-open")OpenRequested?.Invoke();
if(request.Kind is "document" or "reconcile"){
if(request.Kind=="reconcile")foreach(var prior in documents.Values.Where(d=>d.Instance==instance).ToArray())Remove(prior.Session);
foreach(var descriptor in request.Documents){
if(sessions.Descriptor(instance,descriptor.SessionId)==null)continue;
if(!documents.TryGetValue(descriptor.SessionId,out var d))documents[descriptor.SessionId]=d=new(){Session=descriptor.SessionId,Instance=instance};
if(d.Revision!=descriptor.Revision){Cancel(d);d.Chapters=[];d.Words=null;d.Status="Document changed. Detect chapters to refresh this snapshot.";}
d.Revision=descriptor.Revision;d.Manuscript=descriptor.ManuscriptId;d.Title=descriptor.Title;d.RememberedBook=descriptor.RememberedBook;d.AssociationSite=descriptor.AssociationSite;d.Observed=DateTime.UtcNow;
}
}
if(documents.TryGetValue(request.SessionId,out var doc)&&request.Revision==doc.Revision){
if(request.Kind=="close")Remove(doc.Session);
else{
doc.Observed=DateTime.UtcNow;
if(request.Kind=="active"){foreach(var d in documents.Values)d.Active=false;doc.Active=true;}
if(request.Kind=="selection"||request.Kind=="snapshot-end"){doc.ChapterId=answer.ChapterId;doc.SceneId=answer.SceneId;doc.ChapterTitle=answer.ChapterTitle;doc.SceneTitle=answer.SceneTitle;}
if(answer.WordCount.HasValue)doc.Words=answer.WordCount;
if(request.Kind=="snapshot-fragment")doc.Progress=answer.Progress;
if(request.Kind=="snapshot-end"&&answer.Status=="analysis-complete"){doc.Chapters=sessions.Chapters(instance,doc.Session);doc.Status=$"Detected {doc.Chapters.Length} Heading 1 / existing-marker chapters. Scenes require explicit server AI analysis.";doc.Progress=100;}
if(request.Kind=="adapter-result"&&request.OperationMessage!="ok"){doc.Status=request.OperationMessage;Cancel(doc);}
if(request.Kind=="ai-cancel"){Cancel(doc);doc.Status="Extraction cancelled or document changed. Successful server suggestions are retained.";}
if(request.Kind=="metrics")doc.WordDiagnostics=request.OperationMessage.Length<=6000?request.OperationMessage:"Diagnostics size exceeded";
if(request.Kind=="ai-fragment")doc.Progress=answer.Progress;
if(request.Kind.StartsWith("ai-",StringComparison.Ordinal)&&answer.Status!="ok"){doc.Status="Chapter could not be read: "+answer.Status;Cancel(doc);}
}
}
if(commands.TryGetValue(instance,out var queue)&&queue.Count>0)answer.Command=queue.Dequeue();
return answer;
}
}
public void Disconnected(Guid instance){lock(gate){foreach(var doc in documents.Values.Where(d=>d.Instance==instance).ToArray())Remove(doc.Session);commands.Remove(instance);}}
private void Remove(Guid session){if(documents.Remove(session,out var doc)){Cancel(doc);_ = cloud.RemovePresence(doc.Instance,doc.Session);}}
private bool Queue(TrayDocument doc,AdapterCommand command){if(!commands.TryGetValue(doc.Instance,out var queue))commands[doc.Instance]=queue=new();if(queue.Count>=16){doc.Status="Word request queue is busy. Retry after current operation.";return false;}command.SessionId=doc.Session;command.Revision=doc.Revision;queue.Enqueue(command);return true;}
public void Detect(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Completed.Clear();doc.Status="Reading chapters in bounded Word batches…";doc.Progress=0;Queue(doc,new(){Kind="detect"});}}
public void SelectBook(Guid session,int book,bool remember)
{
lock(gate){if(!documents.TryGetValue(session,out var doc))return;var state=cloud.Status();if(!cloud.Allows(state.AuthenticationContext,book))throw new InvalidOperationException("Sign in and select an authorised book.");Cancel(doc);doc.Book=book;doc.Authentication=state.AuthenticationContext;lastBook=book;lastAuthentication=doc.Authentication;doc.Status=remember?"Remember requested; save Word normally after confirmation.":"Book selected for this session.";
Queue(doc,new(){Kind="associate",BookId=book,AuthenticationContext=doc.Authentication,Site=state.ServerUrl,Remember=remember});}
}
public void Analyse(Guid session,IEnumerable<int> starts)
{
lock(gate){if(!documents.TryGetValue(session,out var doc)||!cloud.Allows(doc.Authentication,doc.Book))throw new InvalidOperationException("Connect and select an authorised book first.");if(doc.Job!=Guid.Empty)throw new InvalidOperationException("Cancel the current chapter batch first.");
var selection=starts.Distinct().ToHashSet();var chapters=doc.Chapters.Where(c=>selection.Contains(c.Start)&&c.End>c.Start).ToArray();if(chapters.Length==0)throw new InvalidOperationException("Detect and select Heading 1 chapters first.");
doc.Pending.Clear();foreach(var chapter in chapters)if(!doc.Completed.Contains((doc.Revision,doc.Book,chapter.Start)))doc.Pending.Enqueue(chapter);
doc.Total=doc.Pending.Count;doc.Done=0;Next(doc);
}
}
private void Next(TrayDocument doc)
{
doc.Job=Guid.Empty;
if(doc.Pending.Count==0){doc.Status=$"Batch finished: {doc.Done}/{doc.Total} processed. Successful suggestions are in PlotDirector. Retry failed chapters explicitly; completed unchanged chapters are skipped.";
if(doc.Done>0&&!string.IsNullOrEmpty(doc.ReviewPath))_ = Task.Run(()=>{try{cloud.OpenCompanionPage($"/native-companion/workspace?bookId={doc.Book}&instanceId={doc.Instance}&sessionId={doc.Session}",doc.Authentication);}catch(Exception e)when(e is InvalidOperationException or IOException or System.ComponentModel.Win32Exception){}});
return;}
doc.Current=doc.Pending.Dequeue();doc.Job=Guid.NewGuid();doc.Started=DateTime.UtcNow;doc.Status=$"Chapter {doc.Done+1}/{doc.Total}: {doc.Current.Title}";doc.Progress=0;
if(!Queue(doc,new(){Id=doc.Job,Kind="extract-ai",Chapter=doc.Current,BookId=doc.Book,AuthenticationContext=doc.Authentication})){doc.Job=Guid.Empty;doc.Pending.Clear();}
}
public void Cancel(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Status="Cancelled. Successful server suggestions remain available.";}}
private void Cancel(TrayDocument doc){if(doc.Job!=Guid.Empty)ai.Clear(doc.Session);doc.Job=Guid.Empty;doc.Pending.Clear();if(commands.TryGetValue(doc.Instance,out var q))commands[doc.Instance]=new(q.Where(c=>c.SessionId!=doc.Session));Queue(doc,new(){Kind="cancel"});}
public void Navigate(Guid session,int start){lock(gate)if(documents.TryGetValue(session,out var doc))Queue(doc,new(){Kind="navigate",Chapter=new(){Start=start}});}
public async Task Tick(CancellationToken cancellation)
{
while(!cancellation.IsCancellationRequested){await Task.Delay(500,cancellation);lock(gate){var cloudState=cloud.Status();foreach(var doc in documents.Values){
if(doc.Authentication!=cloudState.AuthenticationContext){Cancel(doc);doc.Book=0;doc.Completed.Clear();doc.Authentication=cloudState.AuthenticationContext;}
if(doc.Book>0&&!cloud.Allows(doc.Authentication,doc.Book)){Cancel(doc);doc.Book=0;doc.Status="Book access is no longer verified. Reconnect and select an authorised book.";}
if(doc.Book==0&&DocumentBindingRestore(doc,cloudState)) {doc.Book=doc.RememberedBook!.Value;doc.Authentication=cloudState.AuthenticationContext;lastBook=doc.Book;lastAuthentication=doc.Authentication;}
if(doc.Job==Guid.Empty)continue;var result=ai.Result(doc.Session);
if(result?.RequestId==doc.Job&&result.State is "complete" or "failed" or "cancelled"){
if(result.State=="complete"){if(doc.Completed.Count>=8192)doc.Completed.RemoveWhere(c=>c.Item1!=doc.Revision);doc.Completed.Add((doc.Revision,doc.Book,doc.Current!.Start));doc.ReviewPath=result.ReviewPath;}
else{if(doc.Errors.Count>=50)doc.Errors.RemoveAt(0);doc.Errors.Add(doc.Current!.Title+": "+result.Message);}
doc.Done++;ai.Clear(doc.Session);Next(doc);
}else if(DateTime.UtcNow-doc.Started>TimeSpan.FromMinutes(7)){doc.Errors.Add("Chapter timed out; retry explicitly.");Cancel(doc);doc.Status="Chapter timed out. Prior suggestions are safe in PlotDirector.";}
}}}
}
private static bool DocumentBindingRestore(TrayDocument doc,Message state)=>doc.RememberedBook>0&&state.Health?.Authentication=="verified"&&Uri.TryCreate(doc.AssociationSite,UriKind.Absolute,out var a)&&Uri.TryCreate(state.ServerUrl,UriKind.Absolute,out var b)&&a==b&&state.Books.Any(book=>book.BookId==doc.RememberedBook);
public void OpenPage(Guid session,string page){lock(gate){if(!documents.TryGetValue(session,out var doc)||!cloud.Allows(doc.Authentication,doc.Book))throw new InvalidOperationException("Select an authorised book first.");cloud.OpenCompanionPage(page=="review"&&!string.IsNullOrEmpty(doc.ReviewPath)?doc.ReviewPath:$"/native-companion/workspace?bookId={doc.Book}&instanceId={doc.Instance}&sessionId={doc.Session}&view={page}",doc.Authentication);}}
public async Task Heartbeat(CancellationToken cancellation)
{
while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromSeconds(15),cancellation);var available=Documents.Where(d=>d.Book>0).ToArray();
foreach(var doc in available){try{await cloud.Presence(doc.Instance,doc.Session,new(){ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=Interlocked.Increment(ref doc.PresenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);}catch(Exception e)when(NetworkFailure(e)) {}}
if(available.Length==0&&lastBook>0){try{await cloud.Presence(agentInstance,agentSession,new(){BookId=lastBook,Sequence=Interlocked.Increment(ref agentSequence),WordAvailable=false,DocumentTitle="No Word document"},lastAuthentication);}catch(Exception e)when(NetworkFailure(e)) {}}
else await cloud.RemovePresence(agentInstance,agentSession);
}
}
private static bool NetworkFailure(Exception e)=>e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or System.Text.Json.JsonException;
}
public sealed class TrayDocument
{
public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Detect chapters to begin.",ReviewPath="";
public string WordDiagnostics="";public int Book,Progress,Total,Done;public int? RememberedBook,Words,ChapterId,SceneId;public bool Active;public DateTime Observed,Started;
public StructureSuggestion[] Chapters=[];public StructureSuggestion? Current;public Queue<StructureSuggestion> Pending=[];public HashSet<(long,int,int)> Completed=[];public List<string> Errors=[];
public override string ToString()=>Title+(Active?" (active in Word)":"");
}

View File

@ -97,7 +97,7 @@ public sealed class AgentLink : IDisposable
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, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability }, stop.Token).ConfigureAwait(false);
await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability }, 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");

View File

@ -1 +1 @@
<Project><PropertyGroup><ApplicationVersion>1.0.0.9</ApplicationVersion></PropertyGroup></Project>
<Project><PropertyGroup><ApplicationVersion>1.0.0.10</ApplicationVersion></PropertyGroup></Project>

View File

@ -4,6 +4,7 @@ namespace PlotDirector.Companion.Protocol;
[DataContract]
public sealed class AiChapterRequest
{
[DataMember] public string ChapterTitle {get;set;}="";
[DataMember] public Guid RequestId { get; set; }
[DataMember] public int BookId { get; set; }
[DataMember] public Guid ManuscriptId { get; set; }
@ -16,6 +17,7 @@ public sealed class AiChapterRequest
[DataContract]
public sealed class AiParagraph
{
[DataMember] public bool IsHeading {get;set;}
[DataMember] public int Index { get; set; }
[DataMember] public int Start { get; set; }
[DataMember] public int End { get; set; }
@ -24,6 +26,8 @@ public sealed class AiParagraph
[DataContract]
public sealed class AiChapterResult
{
[DataMember] public string ChapterTitle {get;set;}="";
[DataMember] public string ReviewPath {get;set;}="";
[DataMember] public Guid RequestId { get; set; }
[DataMember] public int Total { get; set; }
[DataMember] public int Offset { get; set; }

View File

@ -5,6 +5,7 @@ namespace PlotDirector.Companion.Protocol;
public static class ProtocolVersion
{
public const int Current = 1;
public const string TrayCapability="tray-adapter-v1";
public const string WorkflowCapability = "workspace-review-v1";
public const string ChapterAiCapability = "chapter-ai-v2";
public const string AnalysisCapability = "structure-review-v1";
@ -24,6 +25,8 @@ public static class ProtocolVersion
[DataContract]
public sealed class Message
{
[DataMember] public AdapterCommand? Command {get;set;}
[DataMember] public string OperationMessage {get;set;}="";
[DataMember] public int Version { get; set; } = ProtocolVersion.Current;
[DataMember] public Guid CorrelationId { get; set; } = Guid.NewGuid();
[DataMember] public string Kind { get; set; } = "";
@ -64,6 +67,9 @@ public sealed class Message
[DataContract]
public sealed class DocumentDescriptor
{
[DataMember] public string Title {get;set;}="";
[DataMember] public int? RememberedBook {get;set;}
[DataMember] public string AssociationSite {get;set;}="";
[DataMember] public Guid SessionId { get; set; }
[DataMember] public Guid ManuscriptId { get; set; }
[DataMember] public int? ProjectId { get; set; }
@ -113,6 +119,8 @@ public sealed class AnalysisPage
[DataContract]
public sealed class StructureSuggestion
{
[DataMember] public bool Heading1 {get;set;}
[DataMember] public string Summary {get;set;}="";
[DataMember] public int Start { get; set; }
[DataMember] public int Paragraph { get; set; }
[DataMember] public string Kind { get; set; } = "";

View File

@ -0,0 +1,28 @@
using System.Runtime.Serialization;
namespace PlotDirector.Companion.Protocol;
[DataContract]
public sealed class AdapterCommand
{
[DataMember] public Guid Id {get;set;}=Guid.NewGuid();
[DataMember] public string Kind {get;set;}="";
[DataMember] public Guid SessionId {get;set;}
[DataMember] public long Revision {get;set;}
[DataMember] public Guid AuthenticationContext {get;set;}
[DataMember] public int BookId {get;set;}
[DataMember] public string Site {get;set;}="";
[DataMember] public bool Remember {get;set;}
[DataMember] public StructureSuggestion? Chapter {get;set;}
}
[DataContract]
public sealed class NativePresence
{
[DataMember] public Guid ManuscriptId {get;set;}
[DataMember] public int BookId {get;set;}
[DataMember] public long Revision {get;set;}
[DataMember] public long Sequence {get;set;}
[DataMember] public int? ChapterId {get;set;}
[DataMember] public int? SceneId {get;set;}
[DataMember] public bool Active {get;set;}
[DataMember] public bool WordAvailable {get;set;}=true;
[DataMember] public string DocumentTitle {get;set;}="";
}

View File

@ -163,4 +163,5 @@ using(var stalledClient=new AgentLink(stalledName,Guid.NewGuid(),_=>true))
await AnalysisTests.Run(Check);
await ChapterAiTests.Run(Check);
await WorkflowTests.Run(Check);
await TrayTests.Run(Check);
Console.WriteLine($"Native foundation: {passed} checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified.");

View File

@ -0,0 +1,33 @@
using System.Net;
using System.Net.Http.Json;
using PlotDirector.Companion.Agent;
using PlotDirector.Companion.Protocol;
internal static class TrayTests
{
public static async Task Run(Action<bool,string> check)
{
using var cloud=new CloudGateway(new Server(),_=>{});cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Books.Length>0);
using var ai=new ChapterAiWork(cloud);var sessions=new SessionManager(cloud,ai);var control=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var lease=Guid.NewGuid();sessions.Attach(instance,lease);long sequence=0;
var first=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Title="One",Revision=1};var second=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Title="Two",Revision=1};
Message Apply(Message m){m.WordInstanceId=instance;m.Sequence=++sequence;return control.Exchange(instance,m,sessions.Apply(lease,m));}
Apply(new(){Kind="reconcile",Documents=[first,second]});var opened=false;control.OpenRequested+=()=>opened=true;Apply(new(){Kind="tray-open"});check(opened,"Open Companion activates existing agent without another UI process");
control.Detect(first.SessionId);var cancel=Apply(new(){Kind="ping"}).Command;var detect=Apply(new(){Kind="ping"}).Command;check(cancel?.Kind=="cancel"&&detect?.Kind=="detect"&&detect.SessionId==first.SessionId,"tray detection command addresses exact document session and follows cancellation");
var snapshot=Guid.NewGuid();Apply(new(){Kind="snapshot-begin",SessionId=first.SessionId,Revision=1,SnapshotId=snapshot,End=30,RequestAnalysis=true});
Apply(new(){Kind="snapshot-fragment",SessionId=first.SessionId,Revision=1,SnapshotId=snapshot,Fragment=new(){Start=0,End=10,ParagraphIndex=1,OutlineLevel=1,Text="Opening\r",CompletesParagraph=true}});
Apply(new(){Kind="snapshot-fragment",SessionId=first.SessionId,Revision=1,SnapshotId=snapshot,Fragment=new(){Start=10,End=20,ParagraphIndex=2,OutlineLevel=10,Text="Chapter 99\r",CompletesParagraph=true}});
Apply(new(){Kind="snapshot-fragment",SessionId=first.SessionId,Revision=1,SnapshotId=snapshot,Fragment=new(){Start=20,End=30,ParagraphIndex=3,OutlineLevel=1,Text="Closing\r",CompletesParagraph=true}});
Apply(new(){Kind="snapshot-end",SessionId=first.SessionId,Revision=1,SnapshotId=snapshot});
check(control.Documents.Single(d=>d.Session==first.SessionId).Chapters.Length==2&&control.Documents.Single(d=>d.Session==first.SessionId).Chapters[0].End==20&&control.Documents.Single(d=>d.Session==second.SessionId).Chapters.Length==0,"tray chapter list uses Heading 1 not paragraph-name heuristics and remains document-isolated");
control.SelectBook(first.SessionId,3,false);check(control.Documents.Single(d=>d.Session==first.SessionId).Book==3&&control.Documents.Single(d=>d.Session==second.SessionId).Book==0,"tray book association is explicit and isolated");
bool refused=false;try{control.SelectBook(second.SessionId,999,false);}catch(InvalidOperationException){refused=true;}check(refused,"tray refuses unauthorised books before Word metadata command");
control.Analyse(first.SessionId,[0,20]);check(control.Documents.Single(d=>d.Session==first.SessionId).Job!=Guid.Empty,"explicit tray selection starts chapter-only extraction queue");
control.Cancel(first.SessionId);check(control.Documents.Single(d=>d.Session==first.SessionId).Job==Guid.Empty&&control.Documents.Single(d=>d.Session==first.SessionId).Pending.Count==0,"tray cancellation stops queued chapters without affecting another document");
control.Disconnected(instance);check(control.Documents.Length==0,"pipe disconnect removes exact Word instance sessions and pending control work");
}
private static async Task Until(Func<bool> condition){using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(10));while(!condition())await Task.Delay(20,timeout.Token);}
private sealed class Server:HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
{object body=request.RequestUri!.AbsolutePath.Split('/').Last() switch{"pair"=>new{code=new string('A',24)},"token"=>new{accessToken="test"},"books"=>new[]{new CompanionBook{BookId=3,Title="Allowed book"}},_=>new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow}};return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(body)});}
}
}

View File

@ -21,14 +21,18 @@ namespace PlotDirector.WordAddIn
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()
internal static void Start()=>Start(false);
internal static void Start(bool activate)
{
var paused=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"PlotDirector","Companion","paused");
if(!activate&&File.Exists(paused)){LaunchStatus="Companion exited by author; use Open Companion to resume.";return;}
if(activate&&File.Exists(paused))File.Delete(paused);
var assembly=Assembly.GetExecutingAssembly().Location;
var executable=Path.Combine(Path.GetDirectoryName(assembly),"Agent","PlotDirector.Companion.Agent.exe");
if(!File.Exists(executable))executable=FindRegisteredAgent(assembly);
if(string.IsNullOrEmpty(executable)){LaunchStatus="Matching agent missing from the registered package. Reinstall the complete package.";return;}
LaunchStatus="Starting the matching local agent";
using (Process.Start(new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(executable) })) { }
using (Process.Start(new ProcessStartInfo(executable) { Arguments=activate?"--open":"",UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(executable) })) { }
}
private static string FindRegisteredAgent(string loadedAssembly)
{

View File

@ -1,147 +0,0 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using PlotDirector.Companion.Client;
using PlotDirector.Companion.Protocol;
namespace PlotDirector.WordAddIn
{
// Modeless, DPI-aware value-only review. Rendering is bounded to two 40-row pages.
public sealed class AnalysisWindow : Form
{
private readonly Label status=new Label{AutoSize=true,MaximumSize=new Size(1100,0),Margin=new Padding(8)};
private readonly ProgressBar progress=new ProgressBar{Dock=DockStyle.Fill,Height=6,Maximum=100};
private readonly TreeView local=new TreeView{Dock=DockStyle.Fill,CheckBoxes=true,HideSelection=false,ShowNodeToolTips=true};
private readonly TreeView ai=new TreeView{CheckBoxes=true,Dock=DockStyle.Fill,HideSelection=false,ShowNodeToolTips=true};
private readonly TextBox details=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical};
private readonly ComboBox books=new ComboBox{DropDownStyle=ComboBoxStyle.DropDownList,Width=300,DisplayMember="Title",ValueMember="BookId"};
private readonly Label pages=new Label{AutoSize=true,Margin=new Padding(8)};
private readonly Button cancel=new Button{Text="Cancel",AutoSize=true};
private readonly Button next=new Button{Text="Next",AutoSize=true},previous=new Button{Text="Previous",AutoSize=true};
private readonly TabControl tabs=new TabControl{Dock=DockStyle.Fill};
private bool rebinding;
private readonly Dictionary<Guid,Guid> selectionSnapshots=new Dictionary<Guid,Guid>();
private readonly Dictionary<Guid,StructureSelection> choices=new Dictionary<Guid,StructureSelection>();
private StructureSelection selection=new StructureSelection();
private readonly TextBox savedContext=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical};
private readonly TextBox savedIntent=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical};
private readonly TextBox previewText=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical};
private readonly Button ask=new Button{Text="AI: analyse checked chapters",AutoSize=true};
private readonly Button previewButton=new Button{Text="Preview selected import",AutoSize=true};
private readonly Button openContext=new Button{Text="Open full saved Context",AutoSize=true},openIntent=new Button{Text="Open saved Intent",AutoSize=true},openBook=new Button{Text="Continue in PlotDirector",AutoSize=true};
private int aiOffset;private Guid session,authenticationContext,localSnapshot;private string renderKey="";private string bookKey="";private string aiRenderKey="";
private IList<StructureSuggestion> aiItems=new List<StructureSuggestion>();
public AnalysisWindow(Action analyse,Action stop,Action<int> page,Action<AiConsent> submit,Action<StructureSuggestion> navigate,Action<int> selectBook,Action<AiConsent> previewImport,Action<string> open,Action checkConnection)
{
Text="PlotDirector — Manuscript review";Font=new Font("Segoe UI",9F);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new Size(680,480);Width=980;Height=680;ShowInTaskbar=false;
status.MaximumSize=new Size(Math.Max(400,ClientSize.Width-40),0);
var layout=new TableLayoutPanel{Dock=DockStyle.Fill,ColumnCount=1,RowCount=6,Padding=new Padding(10)};
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,100));
layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));layout.RowStyles.Add(new RowStyle(SizeType.Absolute,8));layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
layout.RowStyles.Add(new RowStyle(SizeType.Percent,70));layout.RowStyles.Add(new RowStyle(SizeType.Percent,30));layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
var actions=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,WrapContents=true,Padding=new Padding(0,6,0,6)};
var repeat=new Button{Text="Detect structure",AutoSize=true};repeat.Click+=(_,__)=>analyse();
ask.Click+=(_,__)=>{
var chosen=selection.Items.Where(item=>item.Kind=="Chapter").ToArray();
if(chosen.Length==0){MessageBox.Show("Check one or more chapter nodes in Local structure first.","PlotDirector");return;}
var consent=new AiConsent{SessionId=session,SnapshotId=localSnapshot,AuthenticationContext=authenticationContext,BookId=SelectedBook,Chapters=chosen};
if(consent.BookId<=0){MessageBox.Show("Connect, then select an authorised PlotDirector book.","PlotDirector");return;}
if(MessageBox.Show("Send "+chosen.Length+" selected chapter(s) for book "+(books.SelectedItem as CompanionBook)?.Title+" to PlotDirector's configured AI provider? This may incur AI costs. Existing markers and manuscript text will not change.","Confirm chapter upload",MessageBoxButtons.OKCancel)==DialogResult.OK)submit(consent);
};
cancel.Click+=(_,__)=>{if(tabs.SelectedIndex==4)previewText.Text="Preview cancelled; no records changed.";stop();};
books.SelectedIndexChanged+=(_,__)=>{if(!rebinding){selectBook(SelectedBook);previewText.Clear();}};
var check=new Button{Text="Check connection",AutoSize=true};check.Click+=(_,__)=>checkConnection();
previewButton.Click+=(_,__)=>{
var chosen=selection.Items;if(chosen.Length==0){details.Text="Check chapter and scene rows to preview. Parent chapters are required; choose one local/AI interpretation at each position.";return;}
var consent=new AiConsent{SessionId=session,SnapshotId=localSnapshot,AuthenticationContext=authenticationContext,BookId=SelectedBook,Chapters=chosen};
if(MessageBox.Show("Send selected titles and structural positions to PlotDirector for a read-only import preview? No prose is uploaded and nothing is committed.","Preview import",MessageBoxButtons.OKCancel)==DialogResult.OK){previewImport(consent);tabs.SelectedIndex=4;previewText.Text="Preparing a read-only server preview…";}
};
var clear=new Button{Text="Clear selection",AutoSize=true};clear.Click+=(_,__)=>{selection.Clear();rebinding=true;foreach(TreeNode node in local.Nodes){node.Checked=false;foreach(TreeNode child in node.Nodes)child.Checked=false;}foreach(TreeNode node in ai.Nodes){node.Checked=false;foreach(TreeNode child in node.Nodes)child.Checked=false;}rebinding=false;};
actions.Controls.AddRange(new Control[]{repeat,books,ask,previewButton,clear,cancel,check});
var localTab=new TabPage("Local structure");localTab.Controls.Add(local);var aiTab=new TabPage("AI scene suggestions");aiTab.Controls.Add(ai);var contextTab=new TabPage("Context · saved data");var intentTab=new TabPage("Intent · saved objectives");var importTab=new TabPage("Import preview");
contextTab.Controls.Add(savedContext);openContext.Dock=DockStyle.Bottom;contextTab.Controls.Add(openContext);
intentTab.Controls.Add(savedIntent);openIntent.Dock=DockStyle.Bottom;intentTab.Controls.Add(openIntent);
importTab.Controls.Add(previewText);openBook.Dock=DockStyle.Bottom;importTab.Controls.Add(openBook);
openContext.Click+=(_,__)=>open("context");openIntent.Click+=(_,__)=>open("intent");openBook.Click+=(_,__)=>open("book");
tabs.TabPages.AddRange(new[]{localTab,aiTab,contextTab,intentTab,importTab});
local.AfterCheck+=Checked;ai.AfterCheck+=Checked;
var footer=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true};footer.Controls.AddRange(new Control[]{previous,next,pages});
previous.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(-1);else if(tabs.SelectedIndex==1){aiOffset=Math.Max(0,aiOffset-40);RenderAi();}};
next.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(1);else if(tabs.SelectedIndex==1){aiOffset+=40;RenderAi();}};
tabs.SelectedIndexChanged+=(_,__)=>{details.Text="Select a result to inspect its source and reasoning.";if(tabs.SelectedIndex==1)RenderAi();else UpdatePages();};
local.AfterSelect+=(_,e)=>Inspect(e.Node);ai.AfterSelect+=(_,e)=>Inspect(e.Node);
local.NodeMouseDoubleClick+=(_,e)=>{if(e.Node.Tag is StructureSuggestion item)navigate(item);};
ai.NodeMouseDoubleClick+=(_,e)=>{if(e.Node.Tag is StructureSuggestion item)navigate(item);};
layout.Controls.Add(status,0,0);layout.Controls.Add(progress,0,1);layout.Controls.Add(actions,0,2);layout.Controls.Add(tabs,0,3);layout.Controls.Add(details,0,4);layout.Controls.Add(footer,0,5);Controls.Add(layout);
Resize+=(_,__)=>status.MaximumSize=new Size(Math.Max(400,ClientSize.Width-40),0);
}
public void ForgetBookSelection(){rebinding=true;try{books.SelectedIndex=-1;}finally{rebinding=false;}}
public int SelectedBook=>books.SelectedItem is CompanionBook book?book.BookId:0;
public void ShowSavedTab(bool intent){tabs.SelectedIndex=intent?3:2;}
private AnalysisPage current;
public void Render(AnalysisReview review,string connection,Guid document,string documentName,Guid authentication,CompanionBook[] available,string cloud,string aiStatus,IList<StructureSuggestion> results,bool running,DocumentBinding binding,ConnectionHealth health,bool workflowSupported)
{
if(session!=document){session=document;renderKey="";aiRenderKey="";ForgetBookSelection();aiOffset=0;local.Nodes.Clear();ai.Nodes.Clear();details.Clear();}
if(!choices.TryGetValue(document,out selection)){if(choices.Count>=32){choices.Clear();selectionSnapshots.Clear();}selection=new StructureSelection();choices[document]=selection;}
var snapshot=review?.SnapshotId??Guid.Empty;if(selectionSnapshots.TryGetValue(document,out var previousSnapshot)&&previousSnapshot!=snapshot)selection.Clear();selectionSnapshots[document]=snapshot;
authenticationContext=authentication;localSnapshot=review?.SnapshotId??Guid.Empty;
current=review?.Page;aiItems=results??new List<StructureSuggestion>();
status.Text=(documentName??"No active document")+" · Agent: "+connection+" · "+cloud+"\n"+(review?.Running==true?review.Status:string.IsNullOrEmpty(aiStatus)?review?.Status:aiStatus);
if(current!=null)status.Text+="\n"+current.WordCount.ToString("N0")+" approximate words · "+current.ChapterCount+" local chapter candidates · "+current.SceneCount+" local scene candidates. "+(current.Truncated?"Result limit reached. ":"")+"Double-click to navigate; select to inspect evidence.";
progress.Value=review?.Progress??0;cancel.Enabled=running||review?.Running==true||binding?.Preview?.State=="loading";
var workspace=binding?.Workspace;
var verified=workspace?.State?.StartsWith("saved-",StringComparison.Ordinal)==true;
var cached=health==null||health.Server!="online"||DateTime.UtcNow-health.VerifiedUtc>=TimeSpan.FromSeconds(90)?" · cached/unverified; Check connection":"";
savedContext.Text=(workspace?.Title??"No book selected")+"\r\nSaved PlotDirector data · read-only · "+(workspace?.State??"unselected")+cached+"\r\n\r\n"+(string.IsNullOrWhiteSpace(workspace?.Context)?"No saved context for this location. Select a book; recognised saved chapter/scene markers are verified against that book. Local/AI suggestions do not create saved context.":workspace.Context);
savedIntent.Text=(workspace?.Title??"No book selected")+"\r\nSaved writing objectives · read-only · "+(workspace?.State??"unselected")+cached+"\r\n\r\n"+(string.IsNullOrWhiteSpace(workspace?.Intent)?"No saved writing objective at this location. Set chapter goals or scene purpose in PlotDirector; no intent is invented or silently saved here.":workspace.Intent);
openContext.Enabled=verified&&!string.IsNullOrEmpty(workspace.ContextPath);openIntent.Enabled=verified&&!string.IsNullOrEmpty(workspace.IntentPath);openBook.Enabled=verified;
var plan=binding?.Preview;
if(plan!=null)previewText.Text=plan.State+"\r\nSelected: "+plan.Chapters+" chapters / "+plan.Scenes+" scenes\r\nAlready saved: "+plan.ExistingChapters+" chapters / "+plan.ExistingScenes+" scenes\r\n\r\n"+plan.Message+"\r\n\r\nCreated: 0. Replaced: 0. Native commit is unavailable; use the established PlotDirector workflow.";
else previewText.Text="Select chapter and scene rows, then Preview selected import. This validates the target through PlotDirector's existing importer. Native commit is unavailable; selections are not silently transferred to onboarding.";
var fresh=health!=null&&DateTime.UtcNow-health.VerifiedUtc<TimeSpan.FromSeconds(90)&&health.Authentication=="verified"&&health.Server=="online";
ask.Enabled=fresh&&verified&&!running&&review?.Running!=true&&review?.Page!=null&&(health.Ai=="configured"||health.Ai=="last-request-succeeded");
previewButton.Enabled=workflowSupported&&fresh&&verified&&!running&&review?.Running!=true&&plan?.State!="loading"&&review?.Page!=null;
var key=string.Join("|",available.Select(b=>b.BookId+":"+b.Title));
rebinding=true;try{if(bookKey!=key){bookKey=key;books.DataSource=available;books.DropDownWidth=650;}var selected=binding?.BookId??0;if(available.Any(b=>b.BookId==selected))books.SelectedValue=selected;else books.SelectedIndex=-1;}finally{rebinding=false;}
var newKey=(review?.SnapshotId.ToString()??"")+":"+(current?.Offset??-1);
if(renderKey!=newKey){renderKey=newKey;details.Text="Select a result to inspect its source and reasoning.";Fill(local,current?.Items??Array.Empty<StructureSuggestion>());}
if(tabs.SelectedIndex==1)RenderAi();else UpdatePages();
}
private void Inspect(TreeNode node)
{if(node.Tag is StructureSuggestion item)details.Text=item.Title+Environment.NewLine+item.Origin+" · "+item.Confidence+Environment.NewLine+item.Reason+Environment.NewLine+"Word position "+item.Start+". Double-click to navigate without changing text.";}
private void Fill(TreeView tree,IEnumerable<StructureSuggestion> values)
{
rebinding=true;tree.BeginUpdate();try{tree.Nodes.Clear();var parents=new Dictionary<int,TreeNode>();
foreach(var item in values)
{
var chapterStart=item.Kind=="Chapter"?item.Start:item.ChapterStart;
if(!parents.TryGetValue(chapterStart,out var parent))
{
var chapter=item.Kind=="Chapter"?item:new StructureSuggestion{Kind="Chapter",Start=chapterStart,End=item.ChapterEnd,Title=string.IsNullOrEmpty(item.ChapterTitle)?"Before first chapter / unassigned":item.ChapterTitle,Origin="Local structure",Reason="Chapter context for this results page."};
parent=new TreeNode("Chapter · "+chapter.Title){Checked=selection.Contains(chapter),Tag=chapterStart>=0?(object)chapter:null,ToolTipText=chapter.Title};parents.Add(chapterStart,parent);tree.Nodes.Add(parent);
}
if(item.Kind!="Chapter")parent.Nodes.Add(new TreeNode(item.Title+" ["+item.Origin+"]"){Checked=selection.Contains(item),Tag=item,ToolTipText=item.Title});
}
tree.ExpandAll();}finally{tree.EndUpdate();rebinding=false;}
}
private void RenderAi(){if(aiOffset>=aiItems.Count)aiOffset=0;var key=aiOffset+":"+aiItems.Count+":"+session+string.Join("|",aiItems.Skip(aiOffset).Take(40).Select(s=>s.Start+":"+s.Title+":"+s.Reason));if(aiRenderKey!=key){aiRenderKey=key;Fill(ai,aiItems.Skip(aiOffset).Take(40));}UpdatePages();}
private void Checked(object sender,TreeViewEventArgs args)
{
if(rebinding||!(args.Node.Tag is StructureSuggestion item))return;
if(item.Kind!="Chapter"&&item.Kind!="Scene"){rebinding=true;args.Node.Checked=false;rebinding=false;details.Text="Error/evidence rows cannot be selected for upload or import.";return;}
if(!selection.Set(item,args.Node.Checked)){rebinding=true;args.Node.Checked=false;rebinding=false;details.Text="Preview selection is limited to 80 rows. Use smaller batches.";}
if(args.Action!=TreeViewAction.Unknown)foreach(TreeNode child in args.Node.Nodes)child.Checked=args.Node.Checked;
rebinding=true;try{foreach(var tree in new[]{local,ai})foreach(TreeNode node in tree.Nodes){if(node.Tag is StructureSuggestion parent)node.Checked=selection.Contains(parent);foreach(TreeNode child in node.Nodes)if(child.Tag is StructureSuggestion row)child.Checked=selection.Contains(row);}}finally{rebinding=false;}UpdatePages();
}
private void UpdatePages()
{
if(tabs.SelectedIndex>1){previous.Enabled=false;next.Enabled=false;pages.Text="Read-only saved data / preview; no automatic changes";return;}
var offset=tabs.SelectedIndex==0?(current?.Offset??0):aiOffset;var total=tabs.SelectedIndex==0?(current?.Total??0):aiItems.Count;
pages.Text=total==0?"No results":"Showing "+(offset+1)+"–"+Math.Min(total,offset+40)+" of "+total;
pages.Text+=" · "+selection.Items.Length+" selected across pages (limit 80)";
previous.Enabled=offset>0;next.Enabled=offset+40<total;
}
}
}

View File

@ -1,102 +0,0 @@
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using PlotDirector.Companion.Protocol;
namespace PlotDirector.WordAddIn
{
public sealed class BookSelectionWindow : Form
{
private readonly WordAdapter adapter;
private readonly Guid session;
private Guid authentication;
private readonly TextBox search=new TextBox{Dock=DockStyle.Fill};
private readonly ListBox books=new ListBox{Dock=DockStyle.Fill,DisplayMember="Title"};
private readonly Label status=new Label{AutoSize=true,MaximumSize=new Size(620,0)};
private readonly Button confirm=new Button{Text="Connect this manuscript",AutoSize=true};
private readonly CheckBox remember=new CheckBox{Text="Remember this book in the document",AutoSize=true};
private readonly Timer refresh=new Timer{Interval=500};
private string bookKey="";
private int selected;
public BookSelectionWindow(WordAdapter adapter,int selected)
{
this.adapter=adapter;session=adapter.ActiveSession;authentication=adapter.AuthenticationContext;this.selected=selected;
Text="Select PlotDirector book";Font=new Font("Segoe UI",10);AutoScaleMode=AutoScaleMode.Dpi;
Width=700;Height=580;MinimumSize=new Size(540,470);
var layout=new TableLayoutPanel{Dock=DockStyle.Fill,Padding=new Padding(16),ColumnCount=1,RowCount=7};
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,100));
for(var i=0;i<7;i++)layout.RowStyles.Add(new RowStyle(i==3?SizeType.Percent:SizeType.AutoSize,i==3?100:0));
layout.Controls.Add(new Label{Text="Choose the PlotDirector book for "+adapter.DocumentName,AutoSize=true},0,0);
layout.Controls.Add(status,0,1);
var searchLayout=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=1,RowCount=2,Margin=new Padding(0,10,0,6)};
searchLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,100));
searchLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));searchLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
search.AccessibleName="Search books by title";
searchLayout.Controls.Add(new Label{Text="Search books by title (leave empty to show all)",AutoSize=true},0,0);
searchLayout.Controls.Add(search,0,1);layout.Controls.Add(searchLayout,0,2);
layout.Controls.Add(books,0,3);layout.Controls.Add(remember,0,4);
layout.Controls.Add(new Label{Text="Search by book title above. Connecting a book does not upload manuscript text.\nRemember stores the book, site and document identifier in one custom property. It marks the document modified. Save normally to keep it after reopening. Leaving Remember unchecked keeps the selection for this session and preserves any previously saved association.",AutoSize=true,MaximumSize=new Size(620,0),Margin=new Padding(0,8,0,8)},0,5);
var actions=new FlowLayoutPanel{AutoSize=true,Dock=DockStyle.Fill};
var check=new Button{Text="Refresh connection",AutoSize=true};check.Click+=(_,__)=>adapter.CheckConnection();
var connect=new Button{Text="Sign in",AutoSize=true};connect.Click+=(_,__)=>new ConnectWindow(adapter).Show();
var cancel=new Button{Text="Cancel",AutoSize=true};cancel.Click+=(_,__)=>Close();
confirm.Click+=(_,__)=>{
if(books.SelectedItem is CompanionBook book&&adapter.ConfirmBookSelection(session,authentication,book.BookId,remember.Checked))Close();
};
actions.Controls.AddRange(new Control[]{confirm,check,connect,cancel});layout.Controls.Add(actions,0,6);Controls.Add(layout);
search.TextChanged+=(_,__)=>{bookKey="";Render();};books.SelectedIndexChanged+=(_,__)=>{if(books.SelectedItem is CompanionBook book)selected=book.BookId;};
refresh.Tick+=(_,__)=>Render();refresh.Start();Render();
}
private void Render()
{
if(adapter.ActiveSession!=session){status.Text="The active manuscript changed. Close this window and select a book for that document.";confirm.Enabled=false;return;}
if(authentication!=adapter.AuthenticationContext){authentication=adapter.AuthenticationContext;selected=0;bookKey="";}
var available=adapter.AccessibleBooks??Array.Empty<CompanionBook>();
var filtered=available.Where(b=>(b.Title??"").IndexOf(search.Text.Trim(),StringComparison.CurrentCultureIgnoreCase)>=0).OrderBy(b=>b.Title).ToArray();
var key=authentication+"|"+string.Join("|",filtered.Select(b=>b.BookId+":"+b.Title));
if(key!=bookKey)
{
bookKey=key;var previous=selected;books.DataSource=filtered;
books.SelectedIndex=Array.FindIndex(filtered,b=>b.BookId==previous);
selected=previous;
}
confirm.Enabled=adapter.CanSelectBook&&books.SelectedItem is CompanionBook;
status.Text=adapter.CanSelectBook?available.Length+" accessible books. Current book: "+adapter.BookTitle+(available.Length>0&&filtered.Length==0?". No books match your search; clear the search field to show all.":""):
"Sign in and refresh connection to load books you can access. "+adapter.CloudState;
}
protected override void Dispose(bool disposing){if(disposing)refresh.Dispose();base.Dispose(disposing);}
}
public sealed class CompanionSettingsWindow : Form
{
private readonly WordAdapter adapter;
private readonly TextBox summary=new TextBox{Multiline=true,ReadOnly=true,Dock=DockStyle.Fill,ScrollBars=ScrollBars.Vertical};
private readonly Timer refresh=new Timer{Interval=1000};
public CompanionSettingsWindow(WordAdapter adapter)
{
this.adapter=adapter;Text="PlotDirector settings";Font=new Font("Segoe UI",10);AutoScaleMode=AutoScaleMode.Dpi;
Width=720;Height=560;MinimumSize=new Size(560,430);
var layout=new TableLayoutPanel{Dock=DockStyle.Fill,Padding=new Padding(16),ColumnCount=1,RowCount=2};
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,100));layout.RowStyles.Add(new RowStyle(SizeType.Percent,100));layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));layout.Controls.Add(summary,0,0);
var actions=new FlowLayoutPanel{AutoSize=true,Dock=DockStyle.Fill,WrapContents=true};
Add(actions,"Sign in / account",()=>new ConnectWindow(adapter).Show());
Add(actions,"Select / change book",()=>adapter.ShowBookSelection());
Add(actions,"Check connection",adapter.CheckConnection);
Add(actions,"Reconnect local agent",adapter.Reconnect);
Add(actions,"Sign out",adapter.SignOut);
Add(actions,"Close",Close);
layout.Controls.Add(actions,0,1);Controls.Add(layout);refresh.Tick+=(_,__)=>Render();refresh.Start();Render();
}
private static void Add(FlowLayoutPanel panel,string text,Action action){var button=new Button{Text=text,AutoSize=true};button.Click+=(_,__)=>action();panel.Controls.Add(button);}
private void Render()
{
var text="ACCOUNT AND CONNECTION\r\n"+adapter.ServerUrl+"\r\n"+adapter.CloudState+"\r\nLocal agent: "+adapter.ConnectionState+
"\r\n\r\nCURRENT MANUSCRIPT\r\n"+adapter.DocumentName+"\r\nBook: "+adapter.BookTitle+"\r\n"+adapter.LocationSummary+"\r\n"+adapter.WordCountSummary+
"\r\n\r\nREMEMBERING THIS BOOK\r\n"+adapter.AssociationSummary+
"\r\n\r\nANALYSIS AND SAVED INFORMATION\r\nReview structure detects chapters and scenes locally. Double-click a result to navigate. AI chapter review requires a separate explicit upload confirmation. Context and Intent show saved PlotDirector information for authorised markers; unmatched structure needs review.\r\n\r\nAutomatic prose synchronisation is unavailable. Book selection does not upload text or import records. Open PlotDirector to view this book in your browser. Views opened here stay on the chosen book.";
if(summary.Text!=text)summary.Text=text;
}
protected override void Dispose(bool disposing){if(disposing)refresh.Dispose();base.Dispose(disposing);}
}
}

View File

@ -1,29 +0,0 @@
using System;
using System.Drawing;
using System.Windows.Forms;
namespace PlotDirector.WordAddIn
{
public sealed class ConnectWindow:Form
{
public ConnectWindow(WordAdapter adapter)
{
Text="Connect PlotDirector";Font=new Font("Segoe UI",9F);Width=640;Height=290;MinimumSize=new Size(520,270);AutoScaleMode=AutoScaleMode.Dpi;
var layout=new TableLayoutPanel{Dock=DockStyle.Fill,Padding=new Padding(12),ColumnCount=1,RowCount=5};
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,100));
for(var row=0;row<4;row++)layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
layout.RowStyles.Add(new RowStyle(SizeType.Percent,100));
layout.Controls.Add(new Label{Text="PlotDirector HTTPS site address (no password or API key):",AutoSize=true},0,0);
var address=new TextBox{Dock=DockStyle.Fill,Text=adapter.ServerUrl,Margin=new Padding(0,8,0,8)};layout.Controls.Add(address,0,1);
var actions=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,WrapContents=true};
var feedback=new Label{Dock=DockStyle.Fill,AutoSize=true,Text="Approve the connection in your normal browser, then check the ribbon or manuscript review for connection status."};
var connect=new Button{Text="Sign in in browser",AutoSize=true};connect.Click+=(_,__)=>{
var value=address.Text.Trim();Uri site;
if(!Uri.TryCreate(value,UriKind.Absolute,out site)||site.Scheme!=Uri.UriSchemeHttps||site.AbsolutePath!="/"||!string.IsNullOrEmpty(site.UserInfo)||!string.IsNullOrEmpty(site.Query)||!string.IsNullOrEmpty(site.Fragment))
{feedback.Text="Enter the HTTPS site root, with no username, password, page path or query. No sign-in request was sent.";address.Focus();return;}
adapter.ConnectToServer(value);Close();
};
var signout=new Button{Text="Disconnect / forget sign-in",AutoSize=true};signout.Click+=(_,__)=>{adapter.SignOut();Close();};
actions.Controls.Add(connect);actions.Controls.Add(signout);layout.Controls.Add(actions,0,2);layout.Controls.Add(feedback,0,4);Controls.Add(layout);
}
}
}

View File

@ -1,43 +1,19 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Office = Microsoft.Office.Core;
using Office=Microsoft.Office.Core;
namespace PlotDirector.WordAddIn
{
[ComVisible(true)]
public sealed class NativeRibbon : Office.IRibbonExtensibility
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 _) => getAdapter()?.ConnectionLabel??"PlotDirector unavailable";
public string GetScopeStatus(Office.IRibbonControl _) => Compact(getAdapter()?.BookTitle??"Select Book");
public string GetLocation(Office.IRibbonControl _) => Compact(getAdapter()?.LocationSummary??"Open a manuscript");
private static string Compact(string value)=>value.Length>75?value.Substring(0,72)+"…":value;
public bool HasDocument(Office.IRibbonControl _) => getAdapter()?.HasActiveDocument==true;
public bool CanOpenWorkspace(Office.IRibbonControl _) => getAdapter()?.CanOpenWorkspace==true;
public void SelectBook(Office.IRibbonControl _) => getAdapter()?.ShowBookSelection();
public void Workspace(Office.IRibbonControl _) => getAdapter()?.OpenBookWorkspace();
public void Context(Office.IRibbonControl _) => getAdapter()?.ShowContext();
public void Intent(Office.IRibbonControl _) => getAdapter()?.ShowIntent();
public bool CanSynchronize(Office.IRibbonControl _) => getAdapter()?.HasActiveDocument == true&&getAdapter()?.ConnectionState=="connected";
public bool CanCancel(Office.IRibbonControl _) => getAdapter()?.HasActiveWork==true;
public void Connect(Office.IRibbonControl _) { var adapter=getAdapter();if(adapter!=null)new ConnectWindow(adapter).Show(); }
public void Analyse(Office.IRibbonControl _) { getAdapter()?.AnalyseDocument(); }
public void Cancel(Office.IRibbonControl _) { getAdapter()?.CancelAnalysis(); }
public void Synchronize(Office.IRibbonControl _) { getAdapter()?.AnalyseDocument(); }
public void Settings(Office.IRibbonControl _)
{
getAdapter()?.ShowSettings();
}
public void Diagnostics(Office.IRibbonControl _) => MessageBox.Show(getAdapter()?.Diagnostics ?? "Companion did not initialize. Word remains usable. Check the Windows validation prerequisites.","PlotDirector Diagnostics — Nick Beckley");
private readonly Func<WordAdapter> adapter;private Office.IRibbonUI ui;
public NativeRibbon(Func<WordAdapter> adapter){this.adapter=adapter;}
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 control)=>"Local Companion: "+(adapter()?.ConnectionState??"unavailable");
public void OpenCompanion(Office.IRibbonControl control)=>adapter()?.OpenCompanion();
}
}

View File

@ -23,7 +23,7 @@
<ProjectReference Include="..\Protocol\PlotDirector.Companion.Protocol.csproj"><Name>PlotDirector.Companion.Protocol</Name></ProjectReference>
<ProjectReference Include="..\Client\PlotDirector.Companion.Client.csproj"><Name>PlotDirector.Companion.Client</Name></ProjectReference>
<Compile Include="ThisAddIn.cs" /><Compile Include="ThisAddIn.Designer.cs"><DependentUpon>ThisAddIn.cs</DependentUpon></Compile>
<Compile Include="WordAdapter.cs" /><Compile Include="AnalysisWindow.cs" /><Compile Include="ConnectWindow.cs" /><Compile Include="CompanionSettingsWindow.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
<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>

View File

@ -3,6 +3,6 @@ using System.Runtime.InteropServices;
[assembly: AssemblyTitle("PlotDirector Word Companion — Native development")]
[assembly: AssemblyCompany("Nick Beckley")]
[assembly: AssemblyProduct("PlotDirector")]
[assembly: AssemblyVersion("1.0.0.9")]
[assembly: AssemblyFileVersion("1.0.0.9")]
[assembly: AssemblyVersion("1.0.0.10")]
[assembly: AssemblyFileVersion("1.0.0.10")]
[assembly: ComVisible(false)]

View File

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

View File

@ -44,30 +44,17 @@ namespace PlotDirector.WordAddIn
return values.ToArray();
}
private LocalDocument active;
private bool disposed;
private bool disposed;private bool activationPending;
public string WordCountSummary=>active?.WordCount?.ToString("N0")??"not read / stale";
private long busyFailures;
private string lastWordError;
private int documentCollectionGeneration;
private double lastBatchMs;
private AnalysisWindow analysisWindow;
private CompanionSettingsWindow settingsWindow;
private BookSelectionWindow bookWindow;
private Guid cloudContext;
private ConnectionHealth cloudHealth;
private bool workflowSupported;
private string cloudState="Not signed in",serverUrl="";
private CompanionBook[] cloudBooks=Array.Empty<CompanionBook>();
private bool analysisSupported,cloudSupported;
private readonly Stopwatch reviewClock=Stopwatch.StartNew();
private bool reviewDirty;
private readonly object reviewGate=new object();
private readonly Dictionary<Guid,Message> reviewReplies=new Dictionary<Guid,Message>();
private string lastResult = "Waiting for local structural snapshot";
public string ConnectionState { get; private set; } = "Connecting";
public bool HasActiveDocument => active != null;
public bool HasActiveWork => active!=null&&(active.Review.Running||active.AiJob!=Guid.Empty||active.Binding.Preview?.State=="loading");
public string Diagnostics => "PlotDirector " + typeof(WordAdapter).Assembly.GetName().Version + "\nAgent: " + ConnectionState
+ "\nServer: "+cloudState+" · Prose sync: unavailable\nOpen sessions: " + documents.Count
+ "\nOpen sessions: " + documents.Count
+ "\nIPC queued: " + link.QueueDepth + "\nWord work queued: " + scheduler.Depth
+ "\nAgent startup: " + AgentProcess.LaunchStatus
+ "\nMain document words: " + WordCountSummary
@ -85,11 +72,8 @@ namespace PlotDirector.WordAddIn
ConnectionState = state;
if(state!="connected")
{
analysisSupported=false;cloudSupported=false;workflowSupported=false;
foreach(var doc in documents.Values){StopAi(doc,"Agent disconnected. Successful AI suggestions retained; reconnect before retrying.");scheduler.Cancel("analyse:"+doc.Session);if(doc.Review.Running||doc.Review.SnapshotId!=Guid.Empty)doc.Review.Stop("Agent disconnected. Reconnect and analyse again.");}
foreach(var doc in documents.Values){StopAi(doc,"Agent disconnected. Successful AI suggestions retained; reconnect before retrying.");}
}
foreach(var doc in documents.Values)doc.Binding.Reset();
reviewDirty=true;
if (state == "connected")
{
foreach (var doc in documents.Values) { CancelExtraction(doc); doc.NeedsSnapshot = true; }
@ -98,44 +82,16 @@ namespace PlotDirector.WordAddIn
invalidateRibbon();
});
link.Received += message => {
if(message.Kind=="cloud-status")
{PostToUi(()=>{if(cloudContext!=message.AuthenticationContext){foreach(var doc in documents.Values)if(doc.AiJob!=Guid.Empty||doc.AiQueue.Count>0)StopAi(doc,"Connection/account changed. Review and confirm chapters again.");analysisWindow?.ForgetBookSelection();}if(cloudContext!=message.AuthenticationContext)foreach(var doc in documents.Values)doc.Binding.Reset();cloudContext=message.AuthenticationContext;cloudHealth=message.Health;cloudState=message.Status;cloudBooks=message.Books??Array.Empty<CompanionBook>();serverUrl=message.ServerUrl;RestoreAssociations();reviewDirty=true;invalidateRibbon();});return;}
if(message.Status=="ready")PostToUi(()=>{analysisSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.AnalysisCapability);cloudSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterAiCapability);workflowSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.WorkflowCapability);});
if(message.Kind=="workspace-response")
{PostToUi(()=>{var doc=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);if(doc!=null){if(message.Status=="authentication-changed")doc.Binding.Reset();else doc.Binding.Accept(message);reviewDirty=true;invalidateRibbon();}});return;}
// Bound/coalesce progress independently of the Word message pump.
// Never accumulate one BeginInvoke callback per manuscript fragment.
if(message.SessionId!=Guid.Empty&&(message.SnapshotId!=Guid.Empty||message.WordCount.HasValue))
lock(reviewGate)
{
if(reviewReplies.TryGetValue(message.SessionId,out var prior))
{
if(message.Revision>=prior.Revision&&(prior.Analysis==null||message.Analysis!=null||message.Revision>prior.Revision))reviewReplies[message.SessionId]=message;
}
else if(reviewReplies.Count<ProtocolVersion.MaxDocuments)reviewReplies.Add(message.SessionId,message);
}
var description = message.Status + (string.IsNullOrEmpty(message.ChapterTitle) ? "" : " · " + message.ChapterTitle)
+ (string.IsNullOrEmpty(message.SceneTitle) ? "" : " / " + message.SceneTitle);
if (message.Status == "awaiting-structure" && message.SnapshotId == Guid.Empty) return;
if (message.Status != "ok" || !string.IsNullOrEmpty(message.ChapterTitle)) PostToUi(() => {
if (message.Status == "awaiting-structure")
description = "Local structure refreshed. No chapter or scene found at the cursor.";
if(message.Status!="ok"&&message.Status!="ready"&&message.Status!="awaiting-structure"&&message.Status!="analysis-complete"&&message.Status!="ai-cancelled")
{
var failed=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);
if(failed?.Extraction!=null&&failed.Extraction.Snapshot==message.SnapshotId){CancelExtraction(failed);failed.NeedsSnapshot=false;}
}
if(active != null && active.Session == message.SessionId && active.Revision == message.Revision)lastResult = description;
});
if(message.Command!=null)PostToUi(()=>HandleCommand(message.Command));
if(message.WordCount.HasValue)PostToUi(()=>{var doc=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);if(doc!=null)doc.WordCount=message.WordCount;});
if(message.Status!="ok"&&message.Status!="ready")lastResult=message.Status;
};
scheduler.Measured += (_, elapsed) => lastBatchMs = elapsed;
scheduler.Failed += error => {
busyFailures++;
var frame=new StackTrace(error,true).GetFrames()?.FirstOrDefault(f=>f.GetMethod()?.DeclaringType?.FullName?.Contains("WordAdapter")==true);
lastWordError = error.GetType().Name + " 0x" + error.HResult.ToString("X8") + " · " + (error.Data["WordOperation"]??frame?.GetMethod()?.Name??error.TargetSite?.Name??"Word callback")+" line "+(frame?.GetFileLineNumber()??0);
foreach(var doc in documents.Values)if(doc.Review.Running)
{CancelExtraction(doc);doc.NeedsSnapshot=false;doc.Review.Stop("Word could not finish this operation. Try analysis again; see Diagnostics.");}
reviewDirty=true;
foreach(var doc in documents.Values)if(doc.Extraction!=null)ReportReadFailure(doc,"Word access failed; retry after editing stops.");
scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1));
};
events = (Word.ApplicationEvents4_Event)application;
@ -201,11 +157,10 @@ namespace PlotDirector.WordAddIn
{state.Identity=identity;state.IdentityPersisted=true;state.ProjectId=null;state.BookId=rememberedBook;state.AssociationSite=rememberedSite;}
state.End = DocumentEnd(document); state.WasSaved = Com(() => document.Saved);
documents.Add(document,state); RegisterState(state);
RestoreAssociations();
ScheduleSelection();
})) pendingOpen.Remove(document);
}
private void Activate(Word.Document document,Word.Window window) { Open(document); ScheduleSelection(); }
private void Activate(Word.Document document,Word.Window window) { activationPending=true;Open(document); ScheduleSelection(); }
private void SelectionChanged(Word.Selection selection) { ScheduleSelection(); }
private void ScheduleSelection()
{
@ -231,18 +186,18 @@ namespace PlotDirector.WordAddIn
var documentEnd = DocumentEnd(document); var saved = Com(() => document.Saved);
if (documentEnd != state.End || (state.WasSaved && !saved))
{
StopAi(state,"Document changed. Detect structure again before AI analysis.");state.AiResults.Clear();
state.Review.Stop("Document changed. Analyse again to refresh suggestions.");reviewDirty=true;
StopAi(state,"Document changed. Detect chapters again before analysis.");
state.End = documentEnd; state.Revision++; state.NeedsSnapshot = true;
state.WordCount=null;state.ChapterTitle="";state.SceneTitle="";
CancelExtraction(state); RegisterState(state);
}
state.WasSaved = saved;
if(active!=state)reviewDirty=true;
if(active!=state||activationPending){link.TryPost(new Message {Kind="active",SessionId=state.Session,Revision=state.Revision});activationPending=false;}
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);
// Prose is read only on an explicit Companion request; cursor observations never rescan it.
invalidateRibbon();
}
finally { Release(range); Release(selection); }
@ -254,71 +209,57 @@ namespace PlotDirector.WordAddIn
finally { Release(range); }
}
private DocumentDescriptor Descriptor(LocalDocument doc) => new DocumentDescriptor {
SessionId=doc.Session,ManuscriptId=doc.Identity,
SessionId=doc.Session,ManuscriptId=doc.Identity,Title=doc.DisplayName,RememberedBook=doc.BookId,AssociationSite=doc.AssociationSite,
ProjectId=doc.BookId.HasValue?doc.ProjectId:null,BookId=doc.ProjectId.HasValue?doc.BookId:null,
Revision=doc.Revision,IdentityPersisted=doc.IdentityPersisted,AssociationVerified=false
};
public void AnalyseDocument()
{ShowReview(true);}
private void ShowReview(bool analyse)
public void OpenCompanion()
{
if(active==null)return;
if(analysisWindow==null||analysisWindow.IsDisposed)
analysisWindow=new AnalysisWindow(()=>StartAnalysis(true),CancelAnalysis,RequestAnalysisPage,StartAi,Navigate,SelectBook,PreviewImport,OpenWorkspace,CheckConnection);
analysisWindow.Show();analysisWindow.BringToFront();
if(analyse&&active.Review.Page==null&&!active.Review.Running)StartAnalysis(false);
RenderReview();
if(ConnectionState=="connected"){link.TryPost(new Message{Kind="tray-open"});return;}
System.Threading.Tasks.Task.Run(()=>{try{AgentProcess.Start(true);if(!AgentProcess.LaunchStatus.StartsWith("Starting",StringComparison.Ordinal))PostToUi(()=>MessageBox.Show(AgentProcess.LaunchStatus,"PlotDirector Companion recovery"));}catch(Exception){PostToUi(()=>MessageBox.Show("Companion unavailable. Reinstall the complete developer package. Word remains usable.","PlotDirector Companion recovery"));}});
}
private void StartAnalysis(bool refresh)
private void HandleCommand(AdapterCommand command)
{
var doc=active;if(doc==null)return;
if(ConnectionState!="connected"||!analysisSupported)
{doc.Review.Stop("Connect an updated local agent to analyse this document.");RenderReview();return;}
if(!refresh&&doc.Review.Page!=null){RenderReview();return;}
StopAi(doc,"Detecting updated local structure.");doc.AiStatus=null;doc.AiResults.Clear();CancelExtraction(doc);doc.Review.Prepare(doc.Session);reviewDirty=true;
// Refresh the descriptor on the Word scheduler, never from a background callback.
if(!scheduler.Post("analyse:"+doc.Session,()=>{
if(active!=doc||closing.Contains(doc.Document)){doc.Review.Stop("Document switched or closing. Analyse again when ready.");reviewDirty=true;return;}
doc.End=DocumentEnd(doc.Document);doc.Revision++;doc.NeedsSnapshot=true;
RegisterState(doc);ScheduleSnapshot(doc,true);RenderReview();
})){doc.Review.Stop("Word queue busy. Try analysis again.");RenderReview();}
var doc=documents.Values.FirstOrDefault(d=>d.Session==command.SessionId);
if(doc==null||doc.Revision!=command.Revision){Reply(command,"Document closed or changed; request again.");return;}
if(!scheduler.Post("command:"+doc.Session,()=>{
if(!documents.ContainsKey(doc.Document)||doc.Revision!=command.Revision){Reply(command,"Document changed; request again.");return;}
try{
if(command.Kind=="detect"){
CancelExtraction(doc);doc.End=DocumentEnd(doc.Document);if(!ScheduleSnapshot(doc,true))throw new InvalidOperationException("Word queue unavailable. Retry detection.");
}
else if(command.Kind=="extract-ai"&&command.Chapter!=null){
var chapter=command.Chapter;
if(chapter.Start<0||chapter.End<=chapter.Start||chapter.End>doc.End||DocumentEnd(doc.Document)!=doc.End)throw new InvalidOperationException("Chapter changed. Detect chapters again.");
CancelExtraction(doc);doc.AiChapter=command.Chapter;doc.AiBook=command.BookId;doc.AiAuthenticationContext=command.AuthenticationContext;doc.AiJob=command.Id;
doc.Extraction=new Extraction{Snapshot=command.Id,Revision=doc.Revision,Position=chapter.Start,Limit=chapter.End,IsAi=true};
if(!scheduler.Post("extract:"+doc.Session,()=>ExtractBatch(doc))){CancelExtraction(doc);throw new InvalidOperationException("Word queue is busy.");}
}
else if(command.Kind=="cancel"){CancelExtraction(doc);doc.AiJob=Guid.Empty;}
else if(command.Kind=="navigate"&&command.Chapter!=null){
var position=command.Chapter.Start;if(position<0||position>DocumentEnd(doc.Document))throw new InvalidOperationException("Position no longer exists.");
Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));Com(()=>{range.Select();return true;});}finally{Release(range);}
}
else if(command.Kind=="associate"){
if(command.Remember){
if(Com(()=>doc.Document.ReadOnly))throw new InvalidOperationException("Document is read-only; select for this session without Remember.");
WriteProperty(doc.Document,DocumentBinding.AssociationProperty,DocumentBinding.AssociationValue(doc.Identity,command.BookId,command.Site),Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString);
doc.IdentityPersisted=true;doc.BookId=command.BookId;doc.AssociationSite=command.Site;link.Register(Descriptor(doc));
}
}
else throw new InvalidOperationException("Unsupported adapter request.");
Reply(command,"ok");
}catch(Exception e)when(e is COMException||e is InvalidOperationException||e is ArgumentException){Reply(command,"Word operation unavailable: "+e.GetType().Name+". Retry or select without Remember.");}
}))Reply(command,"Word queue busy. Retry from Companion.");
}
public void CancelAnalysis()
private void Reply(AdapterCommand command,string result)=>link.TryPost(new Message{Kind="adapter-result",SessionId=command.SessionId,Revision=command.Revision,SnapshotId=command.Id,OperationMessage=result});
private bool ScheduleSnapshot(LocalDocument doc,bool analyse=false)
{
var doc=active;if(doc==null)return;
if(doc.Binding.Preview?.State=="loading"){doc.Binding.CancelPreview();reviewDirty=true;WorkspacePost(doc,"workspace-cancel-preview");return;}
if(doc.AiJob!=Guid.Empty||doc.AiQueue.Count>0){StopAi(doc,"AI analysis cancelled. Successful chapter results retained.");RenderReview();return;}
scheduler.Cancel("analyse:"+doc.Session);CancelExtraction(doc);doc.NeedsSnapshot=false;
doc.Review.Stop("Analysis cancelled. Nothing was imported or changed.");RenderReview();
}
private void RequestAnalysisPage(int direction)
{
var doc=active;var page=doc?.Review.Page;if(page==null)return;
var offset=page.Offset+direction*ProtocolVersion.AnalysisPageSize;
if(offset<0||offset>=page.Total)return;
doc.Review.ExpectPage(offset);
if(!link.TryPost(new Message{Kind="analysis-page",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Review.SnapshotId,Start=offset}))
lastResult="Agent queue busy. Try the results page again.";
}
private void RenderReview()
{if(analysisWindow!=null&&!analysisWindow.IsDisposed)analysisWindow.Render(active?.Review,ConnectionState,active?.Session??Guid.Empty,active?.DisplayName,cloudContext,cloudBooks,StatusSummary,active?.AiStatus,active?.AiResults,active!=null&&active.AiJob!=Guid.Empty,active?.Binding,cloudHealth,workflowSupported);reviewDirty=false;}
public void RequestSnapshot()
{
if (active == null) return;
StopAi(active,"Local structure refreshed.");active.AiResults.Clear();
scheduler.Cancel("analyse:"+active.Session);
active.Review.Stop("Structure refreshed. Analyse again to review updated suggestions.");reviewDirty=true;
lastResult = ConnectionState == "connected" ? "Refreshing local structure…" : "Waiting for the local agent";
active.Revision++; active.NeedsSnapshot = true; CancelExtraction(active);
RegisterState(active); ScheduleSnapshot(active);
}
private void ScheduleSnapshot(LocalDocument doc,bool analyse=false)
{
if (doc.Extraction != null || ConnectionState != "connected") return;
if (doc.Extraction != null || ConnectionState != "connected") return false;
doc.Extraction = new Extraction { Snapshot = Guid.NewGuid(), Revision=doc.Revision,Analyse=analyse,Limit=doc.End };
if(analyse)doc.Review.Begin(doc.Session,doc.Revision,doc.Extraction.Snapshot);
if (!scheduler.Post("extract:"+doc.Session,() => ExtractBatch(doc)))
{doc.Extraction=null;doc.Review.Stop("Word queue busy. Try analysis again.");}
{doc.Extraction=null;return false;}
return true;
}
private void ExtractBatch(LocalDocument doc)
{
@ -330,7 +271,7 @@ namespace PlotDirector.WordAddIn
{
if(!extraction.Begun)
{
if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-begin":"snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,Start=extraction.Position,End=extraction.Limit,BookId=doc.AiBook,AuthenticationContext=doc.AiAuthenticationContext,RequestAnalysis=extraction.Analyse}))return;
if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-begin":"snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,Start=extraction.Position,End=extraction.Limit,BookId=doc.AiBook,AuthenticationContext=doc.AiAuthenticationContext,RequestAnalysis=extraction.Analyse,ChapterTitle=doc.AiChapter?.Title??""}))return;
extraction.Begun=true;
}
// At most four <=2048-character fragments and a cooperative ~20ms budget.
@ -354,11 +295,11 @@ namespace PlotDirector.WordAddIn
}
}
catch(COMException)
{ if(extraction.IsAi)StopAi(doc,"Word was busy. AI upload stopped; try again.");doc.Review.Stop("Word was busy. Try analysis again after editing stops.");reviewDirty=true;busyFailures++;CancelExtraction(doc);doc.NeedsSnapshot=true;scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1)); }
{ if(extraction.IsAi)StopAi(doc,"Word was busy. AI upload stopped; try again.");busyFailures++;ReportReadFailure(doc,"Word was busy; request chapters again.");doc.NeedsSnapshot=true;scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1)); }
catch(InvalidOperationException error)
{ if(extraction.IsAi)StopAi(doc,"Word range unavailable. AI upload stopped.");CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped: " + error.Message;doc.Review.Stop(lastResult);reviewDirty=true; }
{ if(extraction.IsAi)StopAi(doc,"Word range unavailable. AI upload stopped.");ReportReadFailure(doc,"Word range unavailable; detect chapters again.");doc.NeedsSnapshot=false;lastResult="Snapshot stopped: " + error.Message; }
catch(NullReferenceException)
{ CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped while reading Word.";doc.Review.Stop(lastResult);reviewDirty=true;throw; }
{ CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped while reading Word.";throw; }
finally
{
lastBatchMs=watch.Elapsed.TotalMilliseconds;Metric("snapshot-batch",lastBatchMs);
@ -454,13 +395,13 @@ namespace PlotDirector.WordAddIn
{
// Never set Cancel, wait for IPC, read prose or force a document save.
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(500));
if(documents.TryGetValue(document,out var state)){StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.NeedsSnapshot=true;state.Review.Stop("Document saved or saving. Analyse again to refresh suggestions.");state.Binding.CancelPreview();WorkspacePost(state,"workspace-cancel-preview");reviewDirty=true;}
if(documents.TryGetValue(document,out var state)){StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.NeedsSnapshot=true;}
}
private void BeforeClose(Word.Document document,ref bool cancel)
{
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(250));
if(!documents.TryGetValue(document,out var state))return;
StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.Review.Stop("Document closing. Analyse again if close is cancelled.");reviewDirty=true;
StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);
documentCollectionGeneration++;
closing.Add(document);
scheduler.Post("retire",ReconcileClosedDocuments);
@ -484,7 +425,7 @@ namespace PlotDirector.WordAddIn
foreach(var doc in closing.ToArray())
{
if(!present.Contains(doc)&&documents.TryGetValue(doc,out var state))
{CancelExtraction(state);documents.Remove(doc);link.Retire(state.Session);if(active==state)active=null;reviewDirty=true;}
{CancelExtraction(state);documents.Remove(doc);link.Retire(state.Session);if(active==state)active=null;}
closing.Remove(doc);
}
}
@ -498,202 +439,18 @@ namespace PlotDirector.WordAddIn
if(!disposed&&active!=null&&selectionClock.ElapsedMilliseconds>=1000)
{selectionClock.Restart();scheduler.Post("selection",CaptureSelection);}
if(!disposed)scheduler.Pump();
Message[] responses;
lock(reviewGate){responses=reviewReplies.Values.Take(4).ToArray();foreach(var response in responses)reviewReplies.Remove(response.SessionId);}
foreach(var response in responses)
if(!disposed&&ConnectionState=="connected"&&metricClock.ElapsedMilliseconds>=1000)
{
var doc=documents.Values.FirstOrDefault(d=>d.Session==response.SessionId&&d.Revision==response.Revision);
if(doc==null)continue;
if(response.WordCount.HasValue)doc.WordCount=response.WordCount;
if(response.Kind=="response"&&(response.WordCount.HasValue||!string.IsNullOrEmpty(response.ChapterTitle)))
{doc.ChapterTitle=response.ChapterTitle;doc.SceneTitle=response.SceneTitle;invalidateRibbon();}
if(doc.AiJob==response.SnapshotId&&doc.AiJob!=Guid.Empty)AcceptAi(doc,response);
else if(doc.Review.Accept(response))reviewDirty=true;
}
if(reviewDirty&&reviewClock.ElapsedMilliseconds>=250){reviewClock.Restart();RenderReview();}
if(!disposed&&active!=null&&ConnectionState=="connected"&&metricClock.ElapsedMilliseconds>=1000)
{
metricClock.Restart();
if(cloudSupported)link.TryPost(new Message{Kind="cloud-status"});
foreach(var doc in documents.Values)if(doc.Binding.BookId>0)WorkspacePost(doc,"workspace-status");
foreach(var doc in documents.Values)if(doc.AiJob!=Guid.Empty&&doc.Extraction==null)
link.TryPost(new Message{Kind="ai-status",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.AiJob,Start=doc.AiOffset});
link.TryPost(new Message{Kind="metrics",SessionId=active.Session,Revision=active.Revision,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
metricClock.Restart();scheduler.Post("selection",CaptureSelection);
if(active!=null)link.TryPost(new Message{Kind="metrics",SessionId=active.Session,Revision=active.Revision,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth,OperationMessage=Diagnostics});
}
}
public void ConnectToServer(string address)
{foreach(var doc in documents.Values)if(doc.AiJob!=Guid.Empty||doc.AiQueue.Count>0)StopAi(doc,"Connecting a different account/site. Confirm chapters again.");if(!cloudSupported){MessageBox.Show("Connect the matching Phase 3 agent first.","PlotDirector");return;}link.TryPost(new Message{Kind="cloud-connect",ServerUrl=address});}
public string ServerUrl=>serverUrl;
public string CloudState=>cloudState;
public string StatusSummary=>ConnectionPresentation.Describe(ConnectionState,cloudHealth,active?.Binding.BookId??0,active?.Binding.Workspace.State??"unselected");
public string ConnectionLabel => ConnectionState!="connected"?"Connecting local agent…":
cloudHealth?.Authentication!="verified"?"Sign in to PlotDirector":
cloudHealth.Server!="online"||DateTime.UtcNow-cloudHealth.VerifiedUtc>=TimeSpan.FromSeconds(90)?"Check server connection":"Connected to PlotDirector";
public void CheckConnection(){if(cloudSupported)link.TryPost(new Message{Kind="cloud-check"});if(active?.Binding.BookId>0)WorkspacePost(active,"workspace-refresh");}
public void SignOut(){foreach(var doc in documents.Values)StopAi(doc,"Signed out. Successful results retained.");link.TryPost(new Message{Kind="cloud-signout"});}
private void RegisterState(LocalDocument doc)
{
var book=doc.Binding.BookId;link.Register(Descriptor(doc));
if(book>0){doc.Binding.Select(book,cloudContext);WorkspacePost(doc,"workspace-select");}
}
private void SelectBook(int book) => ShowBookSelection(book);
public Guid ActiveSession => active?.Session??Guid.Empty;
public Guid AuthenticationContext => cloudContext;
public CompanionBook[] AccessibleBooks => cloudBooks;
public bool CanSelectBook => active!=null&&ConnectionState=="connected"&&workflowSupported&&cloudHealth?.Authentication=="verified"&&cloudHealth.Server=="online"&&DateTime.UtcNow-cloudHealth.VerifiedUtc<TimeSpan.FromSeconds(90);
public bool CanOpenWorkspace => CanSelectBook&&active?.Binding.Workspace.State?.StartsWith("saved-",StringComparison.Ordinal)==true;
public string DocumentName => active?.DisplayName??"No document open";
public string BookTitle => active==null?"No document open":cloudBooks.FirstOrDefault(b=>b.BookId==active.Binding.BookId)?.Title??"Select Book to connect this manuscript";
public string LocationSummary => active==null?"Open a document":
!string.IsNullOrEmpty(active.Binding.Workspace.Title)&&active.Binding.Workspace.State!="saved-book"?active.Binding.Workspace.Title:
string.Join(" / ",new[]{active.ChapterTitle,active.SceneTitle}.Where(t=>!string.IsNullOrWhiteSpace(t))).Length>0?
string.Join(" / ",new[]{active.ChapterTitle,active.SceneTitle}.Where(t=>!string.IsNullOrWhiteSpace(t))):"Chapter / scene not yet detected";
public string WordCountSummary => active==null?"unavailable (no document)":active.WordCount.HasValue?active.WordCount.Value.ToString("N0")+" approximate words in the latest snapshot":"unavailable until local reading completes";
public string AssociationSummary => active==null?"Open a manuscript to select a book.":
active.BookId>0&&active.IdentityPersisted?"A book association is stored in this document. Save normally after changing it. Access is checked again after sign-in.":
"Book selection lasts for this Word session. Select Book offers an explicit option to remember it in document metadata.";
public void ShowSettings()
{if(settingsWindow==null||settingsWindow.IsDisposed)settingsWindow=new CompanionSettingsWindow(this);settingsWindow.Show();settingsWindow.BringToFront();}
public void ShowBookSelection(int suggested=0)
{
if(active==null){MessageBox.Show("Open a manuscript first.","Select PlotDirector book");return;}
if(bookWindow!=null&&!bookWindow.IsDisposed){bookWindow.BringToFront();return;}
bookWindow=new BookSelectionWindow(this,suggested>0?suggested:active.Binding.BookId);bookWindow.Show();
CheckConnection();
}
public void ShowContext(){ShowReview(false);analysisWindow?.ShowSavedTab(false);}
public void ShowIntent(){ShowReview(false);analysisWindow?.ShowSavedTab(true);}
public void OpenBookWorkspace()=>OpenWorkspace("book");
public bool ConfirmBookSelection(Guid session,Guid authentication,int book,bool remember)
{
var doc=active;
if(doc==null||doc.Session!=session||cloudContext!=authentication||!CanSelectBook||!cloudBooks.Any(b=>b.BookId==book))
{MessageBox.Show("Document, account or available books changed. Check connection and select the book again.","PlotDirector");return false;}
if(remember)
{
var site=serverUrl;
if(!scheduler.Post("association:"+doc.Session,()=>{
if(active!=doc||cloudContext!=authentication||!CanSelectBook)return;
if(Com(()=>doc.Document.ReadOnly)){MessageBox.Show("This document is read-only. Select the book without Remember, or use a writable copy.","PlotDirector");return;}
// One metadata value keeps identity, site and book consistent if an operation fails.
try{WriteProperty(doc.Document,DocumentBinding.AssociationProperty,DocumentBinding.AssociationValue(doc.Identity,book,site),Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString);}
catch(Exception error) when(error is COMException||error is ArgumentException||error is InvalidOperationException)
{MessageBox.Show("Word could not remember the book in this document. You can select it again with Remember unchecked for this session. Nothing was uploaded or saved.","PlotDirector");throw;}
doc.IdentityPersisted=true;doc.ProjectId=null;doc.BookId=book;doc.AssociationSite=site;
ApplyBookSelection(doc,book);link.Register(Descriptor(doc));
MessageBox.Show("Book connected. Save the document normally to remember this association after reopening. No manuscript text was uploaded.","PlotDirector");
})){MessageBox.Show("Word is busy. Please select the book again.","PlotDirector");return false;}
}
else ApplyBookSelection(doc,book);
return true;
}
private void RestoreAssociations()
{
if(!workflowSupported||cloudHealth?.Authentication!="verified"||cloudHealth.Server!="online"||DateTime.UtcNow-cloudHealth.VerifiedUtc>=TimeSpan.FromSeconds(90))return;
foreach(var doc in documents.Values)
if(doc.Binding.BookId==0&&doc.IdentityPersisted&&DocumentBinding.CanRestore(doc.BookId??0,doc.AssociationSite,serverUrl,cloudBooks))
ApplyBookSelection(doc,doc.BookId.Value);
}
private void ApplyBookSelection(LocalDocument doc,int book)
{
if(doc.Binding.BookId==book&&doc.Binding.AuthenticationContext==cloudContext)return;
StopAi(doc,"Book selection changed; confirm AI chapters again.");doc.AiStatus=null;
doc.Binding.Select(book,cloudContext);WorkspacePost(doc,"workspace-select");reviewDirty=true;invalidateRibbon();
}
private void WorkspacePost(LocalDocument doc,string kind,ImportPreviewRequest selection=null,string action="")
{
if(!workflowSupported)return;
var accepted=link.TryPost(new Message{Kind=kind,SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Binding.Id,BookId=doc.Binding.BookId,AuthenticationContext=doc.Binding.AuthenticationContext,ImportSelection=selection,Action=action});
if(!accepted){lastResult="Local queue busy. Check connection/refresh and try again.";if(kind=="workspace-preview")doc.Binding.CancelPreview();}
}
private void PreviewImport(AiConsent consent)
{
var doc=active;if(doc==null||!consent.Matches(doc.Session,doc.Review.SnapshotId,cloudContext)||consent.BookId!=doc.Binding.BookId)return;
var id=Guid.NewGuid();doc.Binding.BeginPreview(id);WorkspacePost(doc,"workspace-preview",new ImportPreviewRequest{RequestId=id,BookId=consent.BookId,SessionId=doc.Session,SnapshotId=consent.SnapshotId,ManuscriptId=doc.Identity,Items=consent.Chapters.Select(s=>new StructureSuggestion{Kind=s.Kind,Title=s.Title,Start=s.Start,End=s.End,Origin=s.Origin}).ToArray()});
reviewDirty=true;
}
private void OpenWorkspace(string action)
{if(active!=null)WorkspacePost(active,"workspace-open",action:action);}
private void StartAi(AiConsent consent)
{
var doc=active;if(doc==null||doc.Review.Page==null||doc.Review.Running)return;
if(!consent.Matches(doc.Session,doc.Review.SnapshotId,cloudContext)||!cloudBooks.Any(b=>b.BookId==consent.BookId)){MessageBox.Show("Document, connection or book changed during confirmation. Review the target and confirm again.","PlotDirector");return;}
if(!cloudState.StartsWith("Signed in",StringComparison.Ordinal)){MessageBox.Show("Use Connect / Sign In first.","PlotDirector");return;}
if(doc.AiJob!=Guid.Empty){MessageBox.Show("Cancel the current chapter batch before starting another.","PlotDirector");return;}
doc.AiBook=consent.BookId;doc.AiAuthenticationContext=consent.AuthenticationContext;doc.AiCompleted=0;doc.AiFailures.Clear();doc.AiQueue.Clear();
foreach(var chapter in consent.Chapters.Where(c=>c.Kind=="Chapter"&&c.Start>=0&&c.End>c.Start).GroupBy(c=>c.Start).Select(g=>g.First()).Take(256))doc.AiQueue.Enqueue(chapter);
doc.AiTotal=doc.AiQueue.Count;if(doc.AiTotal==0){doc.AiStatus="No valid chapter ranges selected. Detect structure again.";reviewDirty=true;return;}NextAi(doc);
}
private void NextAi(LocalDocument doc)
{
doc.AiJob=Guid.Empty;doc.AiOffset=0;doc.AiPartial.Clear();
if(doc.AiQueue.Count==0){doc.AiStatus="AI batch finished: "+doc.AiCompleted+" / "+doc.AiTotal+" chapters processed. Review AI suggestions; failed chapters can be explicitly retried."+(doc.AiResults.Count>=5000?" Review limit reached; additional suggestions were not retained.":"")+(doc.AiFailures.Count>0?" "+doc.AiFailures.Count+" chapter(s) failed; inspect AI suggestions for details.":"");reviewDirty=true;return;}
if(doc.AiResults.Count>=5000){StopAi(doc,"Review limit reached (5,000 rows). Remaining selected chapters were not uploaded.");return;}
var chapter=doc.AiQueue.Dequeue();doc.AiChapter=chapter;
if(chapter.End-chapter.Start>120000){AiFailure(doc,"Chapter exceeds the 120,000-character upload limit. Review its boundaries.");doc.AiCompleted++;NextAi(doc);return;}
doc.AiJob=Guid.NewGuid();
doc.AiStatus="Chapter "+(doc.AiCompleted+1)+" of "+doc.AiTotal+": reading "+chapter.Title;
if(!scheduler.Post("ai-read:"+doc.Session,()=>{
if(!documents.ContainsKey(doc.Document)||doc.AiJob==Guid.Empty)return;
if(DocumentEnd(doc.Document)!=doc.End){StopAi(doc,"Document length changed. Detect structure again.");return;}
CancelExtraction(doc);doc.Extraction=new Extraction{Snapshot=doc.AiJob,Revision=doc.Revision,Position=chapter.Start,Limit=chapter.End,IsAi=true};
if(!scheduler.Post("extract:"+doc.Session,()=>ExtractBatch(doc)))StopAi(doc,"Word queue is busy. Try again.");
}))StopAi(doc,"Word queue is busy. Try again.");
reviewDirty=true;
}
private void AcceptAi(LocalDocument doc,Message message)
{
if(message.Revision!=doc.Revision)return;
if(message.Status=="authentication-changed"){StopAi(doc,"Connection/account changed. Confirm the upload again after signing in.");return;}
if(message.Status!="ok"){doc.AiStatus="Chapter failed: "+message.Status;doc.AiCompleted++;AiFailure(doc,message.Status);NextAi(doc);return;}
var result=message.Ai;
if(result==null)return;
if(result.State=="complete"&&result.Offset==doc.AiOffset)
{
foreach(var item in result.Scenes){item.ChapterStart=doc.AiChapter.Start;item.ChapterEnd=doc.AiChapter.End;item.ChapterTitle=doc.AiChapter.Title;doc.AiPartial.Add(item);}
doc.AiOffset=doc.AiPartial.Count;
if(doc.AiOffset>=result.Total)
{
doc.AiResults.RemoveAll(s=>s.ChapterStart==doc.AiChapter.Start);
doc.AiResults.AddRange(doc.AiPartial.Take(Math.Max(0,5000-doc.AiResults.Count)));
doc.AiCompleted++;NextAi(doc);
}
}
else if(result.State=="failed"||result.State=="cancelled")
{AiFailure(doc,result.Message);doc.AiCompleted++;NextAi(doc);}
else doc.AiStatus="Chapter "+(doc.AiCompleted+1)+" / "+doc.AiTotal+": "+(result.State=="reading"?"reading in short batches: "+message.Progress+"%":"AI interpreting scenes…");
reviewDirty=true;
}
private void AiFailure(LocalDocument doc,string reason)
{
doc.AiFailures.Add(doc.AiChapter.Title+": "+reason);
if(doc.AiResults.Count<5000)doc.AiResults.Add(new StructureSuggestion{Kind="Failure",Origin="AI error",Start=doc.AiChapter.Start,End=doc.AiChapter.End,ChapterStart=doc.AiChapter.Start,ChapterEnd=doc.AiChapter.End,ChapterTitle=doc.AiChapter.Title,Title="Analysis failed — "+doc.AiChapter.Title,Reason=reason});
}
private void RegisterState(LocalDocument doc)=>link.Register(Descriptor(doc));
private void ReportReadFailure(LocalDocument doc,string reason){CancelExtraction(doc);link.TryPost(new Message{Kind="adapter-result",SessionId=doc.Session,Revision=doc.Revision,OperationMessage=reason});lastResult=reason;}
private void StopAi(LocalDocument doc,string reason)
{
scheduler.Cancel("ai-read:"+doc.Session);
if(doc.AiJob!=Guid.Empty&&!link.TryPost(new Message{Kind="ai-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.AiJob}))link.Reset();
if(doc.Extraction?.IsAi==true)CancelExtraction(doc);
doc.AiJob=Guid.Empty;doc.AiQueue.Clear();doc.AiPartial.Clear();doc.AiStatus=reason;reviewDirty=true;
}
private void Navigate(StructureSuggestion item)
{
var doc=active;if(doc==null||item.Start<0)return;var revision=doc.Revision;
scheduler.Post("navigate:"+doc.Session,()=>{
if(active!=doc||doc.Revision!=revision||DocumentEnd(doc.Document)!=doc.End||item.Start>doc.End)return;
Word.Range range=null;try{range=Com(()=>doc.Document.Range(item.Start,item.Start));Com(()=>{range.Select();return true;});}finally{Release(range);}
});
}
public void Reconnect() { link.Reset(); }
public void PersistNativeIdentity()
{
var doc=active;if(doc==null||doc.IdentityPersisted)return;
scheduler.Post("identity:"+doc.Session,()=>{
dynamic properties=doc.Document.CustomDocumentProperties;
try{properties.Add("PlotDirector.Native.DocumentGuid",false,Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString,doc.Identity.ToString("D"));}
finally{Release(properties);}
doc.IdentityPersisted=true;RegisterState(doc);
});
doc.AiJob=Guid.Empty;lastResult=reason;
}
// Future marker writes are explicitly scoped to a known document and exact range.
// No remote mutation command is exposed in protocol v1.
@ -769,21 +526,16 @@ namespace PlotDirector.WordAddIn
if(disposed)return;disposed=true;timer.Stop();timer.Dispose();scheduler.Clear();
events.DocumentOpen-=Open;events.NewDocument-=Open;events.DocumentChange-=ScheduleSelection;events.WindowActivate-=Activate;
events.WindowSelectionChange-=SelectionChanged;events.DocumentBeforeClose-=BeforeClose;events.DocumentBeforeSave-=BeforeSave;
analysisWindow?.Dispose();settingsWindow?.Dispose();bookWindow?.Dispose();link.Dispose();documents.Clear();pendingOpen.Clear();closing.Clear();dispatch.Dispose();
link.Dispose();documents.Clear();pendingOpen.Clear();closing.Clear();dispatch.Dispose();
}
private sealed class LocalDocument
{
public readonly Word.Document Document;public readonly Guid Session=Guid.NewGuid();public Guid Identity;public bool IdentityPersisted;
public readonly DocumentBinding Binding=new DocumentBinding();
public string DisplayName;
public string AssociationSite="",ChapterTitle="",SceneTitle="";
public int? WordCount;
public readonly AnalysisReview Review=new AnalysisReview();
public readonly Queue<StructureSuggestion> AiQueue=new Queue<StructureSuggestion>();
public readonly List<StructureSuggestion> AiResults=new List<StructureSuggestion>();
public readonly List<string> AiFailures=new List<string>();
public Guid AiAuthenticationContext;public Guid AiJob;public int AiBook,AiOffset,AiCompleted,AiTotal;public string AiStatus;
public StructureSuggestion AiChapter;public readonly List<StructureSuggestion> AiPartial=new List<StructureSuggestion>();
public Guid AiAuthenticationContext,AiJob;public int AiBook;public StructureSuggestion AiChapter;
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;}
}

View File

@ -9,6 +9,6 @@ $project=Join-Path $root 'Vsto\PlotDirector.WordAddIn.csproj'
& $msbuild $project /restore '/t:Build;VisualStudioForApplicationsBuild' /p:PrepareForRunDependsOn=CopyFilesToOutputDirectory /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
dotnet publish (Join-Path $root 'Agent\PlotDirector.Companion.Agent.csproj') -f net10.0-windows -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.'

View File

@ -37,18 +37,21 @@ try {
if(!(Test-Path -LiteralPath $vswhere)){throw 'vswhere is missing. Existing Visual Studio Office tools are required. No installer will be launched.'}
$msbuild=& $vswhere -latest -requires Microsoft.VisualStudio.Workload.Office -find 'MSBuild\**\Bin\amd64\MSBuild.exe' | Select-Object -First 1
if(!$msbuild){throw 'Office-equipped MSBuild was not found. No workloads or IDE settings were changed.'}
$desktopRuntime=& dotnet --list-runtimes
if($LASTEXITCODE -ne 0 -or !($desktopRuntime -match '^Microsoft.WindowsDesktop.App 10\.')){throw 'The .NET 10 Windows Desktop runtime is required for the tray Companion. No runtime or Visual Studio installation was attempted.'}
Invoke-Checked dotnet @('build','PlotLine.slnx','-c','Release','--disable-build-servers','-m:1','/p:UseSharedCompilation=false')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-companion')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-companion-http')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-workflow')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-tray')
# Office Clean unregisters the installed add-in. Build signed outputs without that target or F5 registration.
Invoke-Checked $msbuild @('PlotDirector.NativeCompanion\Vsto\PlotDirector.WordAddIn.csproj','/restore','/t:Build;VisualStudioForApplicationsBuild','/p:Configuration=Release','/p:PrepareForRunDependsOn=CopyFilesToOutputDirectory','/p:SignManifests=true',"/p:ManifestCertificateThumbprint=$CertificateThumbprint","/p:ApplicationVersion=$version")
$bin=Join-Path $repo 'PlotDirector.NativeCompanion\Vsto\bin\Release'
$staging=$output+'.preparing-'+[guid]::NewGuid().ToString('N')
New-Item -ItemType Directory -Path $staging -Force | Out-Null
Copy-Item -Path (Join-Path $bin '*') -Destination $staging -Recurse
Invoke-Checked dotnet @('publish','PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj','-c','Release','-r','win-x64','--self-contained','false','-o',(Join-Path $staging 'Agent'))
Invoke-Checked dotnet @('publish','PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj','-f','net10.0-windows','-c','Release','-r','win-x64','--self-contained','false','-o',(Join-Path $staging 'Agent'))
if((& git rev-parse HEAD).Trim() -ne $commit){throw 'Git HEAD changed during the build. No package was installed; rerun after the repository is stable.'}
if(& git status --porcelain=v1){throw 'Build generated source changes; review them before packaging. No installation was changed.'}
$files=@(Get-ChildItem -LiteralPath $staging -Recurse -File | ForEach-Object { @{path=$_.FullName.Substring($staging.Length+1).Replace('\','/');sha256=(Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash} })