From 07cd67aeaa48310e50f26d693da9a57f5031df32 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Thu, 5 Nov 2026 21:13:08 +0000 Subject: [PATCH] Move Word controls into the existing agent tray application and minimal adapter --- .../Agent/ChapterAiWork.cs | 7 +- .../Agent/CloudGateway.cs | 19 +- .../Agent/DocumentAnalysis.cs | 2 +- .../Agent/GlobalUsings.cs | 1 + .../Agent/PipeHost.cs | 7 +- .../Agent/PlotDirector.Companion.Agent.csproj | 5 +- PlotDirector.NativeCompanion/Agent/Program.cs | 58 +-- .../Agent/SessionManager.cs | 17 +- .../Agent/TrayApplication.cs | 94 +++++ .../Agent/TrayCoordinator.cs | 107 +++++ .../Client/AgentLink.cs | 2 +- .../DeveloperVersion.props | 2 +- .../Protocol/AiContracts.cs | 4 + .../Protocol/Messages.cs | 8 + .../Protocol/TrayContracts.cs | 28 ++ PlotDirector.NativeCompanion/Tests/Program.cs | 1 + .../Tests/TrayTests.cs | 33 ++ .../Vsto/AgentProcess.cs | 8 +- .../Vsto/AnalysisWindow.cs | 147 ------- .../Vsto/CompanionSettingsWindow.cs | 102 ----- .../Vsto/ConnectWindow.cs | 29 -- .../Vsto/NativeRibbon.cs | 42 +- .../Vsto/PlotDirector.WordAddIn.csproj | 2 +- .../Vsto/Properties/AssemblyInfo.cs | 4 +- PlotDirector.NativeCompanion/Vsto/Ribbon.xml | 26 +- .../Vsto/WordAdapter.cs | 390 ++++-------------- .../WindowsValidation/Build-Developer.ps1 | 2 +- .../Update-WordCompanion.ps1 | 5 +- 28 files changed, 429 insertions(+), 723 deletions(-) create mode 100644 PlotDirector.NativeCompanion/Agent/GlobalUsings.cs create mode 100644 PlotDirector.NativeCompanion/Agent/TrayApplication.cs create mode 100644 PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs create mode 100644 PlotDirector.NativeCompanion/Protocol/TrayContracts.cs create mode 100644 PlotDirector.NativeCompanion/Tests/TrayTests.cs delete mode 100644 PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs delete mode 100644 PlotDirector.NativeCompanion/Vsto/CompanionSettingsWindow.cs delete mode 100644 PlotDirector.NativeCompanion/Vsto/ConnectWindow.cs diff --git a/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs b/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs index c4f56f87..3b8793c6 100644 --- a/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs +++ b/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs @@ -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();} diff --git a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs index 5e796364..ead128d1 100644 --- a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs +++ b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs @@ -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 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("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("api/native-companion/connection",context);var accessible=await Get("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 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(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.Startchapter.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 Get(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(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($"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(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 diff --git a/PlotDirector.NativeCompanion/Agent/DocumentAnalysis.cs b/PlotDirector.NativeCompanion/Agent/DocumentAnalysis.cs index 2d1472db..6b90b3a7 100644 --- a/PlotDirector.NativeCompanion/Agent/DocumentAnalysis.cs +++ b/PlotDirector.NativeCompanion/Agent/DocumentAnalysis.cs @@ -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); diff --git a/PlotDirector.NativeCompanion/Agent/GlobalUsings.cs b/PlotDirector.NativeCompanion/Agent/GlobalUsings.cs new file mode 100644 index 00000000..05672c27 --- /dev/null +++ b/PlotDirector.NativeCompanion/Agent/GlobalUsings.cs @@ -0,0 +1 @@ +global using Message = PlotDirector.Companion.Protocol.Message; diff --git a/PlotDirector.NativeCompanion/Agent/PipeHost.cs b/PlotDirector.NativeCompanion/Agent/PipeHost.cs index c0bf03cd..0818e189 100644 --- a/PlotDirector.NativeCompanion/Agent/PipeHost.cs +++ b/PlotDirector.NativeCompanion/Agent/PipeHost.cs @@ -17,7 +17,7 @@ public static class AgentEndpoint } } -public sealed class PipeHost(string pipeName, SessionManager sessions, Action? log = null) +public sealed class PipeHost(string pipeName, SessionManager sessions, Action? 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 - Exenet10.0enableenableNick Beckley + + $(ApplicationVersion)$(ApplicationVersion)$(ApplicationVersion) + Exenet10.0;net10.0-windowstrueenableenableNick Beckley + WinExetrue diff --git a/PlotDirector.NativeCompanion/Agent/Program.cs b/PlotDirector.NativeCompanion/Agent/Program.cs index 7f658fff..2fcbf82a 100644 --- a/PlotDirector.NativeCompanion/Agent/Program.cs +++ b/PlotDirector.NativeCompanion/Agent/Program.cs @@ -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){}}} +} diff --git a/PlotDirector.NativeCompanion/Agent/SessionManager.cs b/PlotDirector.NativeCompanion/Agent/SessionManager.cs index 30ce2fe7..4f4f8257 100644 --- a/PlotDirector.NativeCompanion/Agent/SessionManager.cs +++ b/PlotDirector.NativeCompanion/Agent/SessionManager.cs @@ -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 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 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 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 Fragments = []; } } diff --git a/PlotDirector.NativeCompanion/Agent/TrayApplication.cs b/PlotDirector.NativeCompanion/Agent/TrayApplication.cs new file mode 100644 index 00000000..52e03285 --- /dev/null +++ b/PlotDirector.NativeCompanion/Agent/TrayApplication.cs @@ -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> 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{for(var i=0;iOpen("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().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;iTitle;} +} +#endif diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs new file mode 100644 index 00000000..dee59c2a --- /dev/null +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs @@ -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 documents=[]; + private readonly Dictionary> 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 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 Pending=[];public HashSet<(long,int,int)> Completed=[];public List Errors=[]; + public override string ToString()=>Title+(Active?" (active in Word)":""); +} diff --git a/PlotDirector.NativeCompanion/Client/AgentLink.cs b/PlotDirector.NativeCompanion/Client/AgentLink.cs index 3e4f1d92..084b1137 100644 --- a/PlotDirector.NativeCompanion/Client/AgentLink.cs +++ b/PlotDirector.NativeCompanion/Client/AgentLink.cs @@ -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"); diff --git a/PlotDirector.NativeCompanion/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props index aaceeb43..8078395d 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.9 +1.0.0.10 diff --git a/PlotDirector.NativeCompanion/Protocol/AiContracts.cs b/PlotDirector.NativeCompanion/Protocol/AiContracts.cs index 90518092..700ec78f 100644 --- a/PlotDirector.NativeCompanion/Protocol/AiContracts.cs +++ b/PlotDirector.NativeCompanion/Protocol/AiContracts.cs @@ -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; } diff --git a/PlotDirector.NativeCompanion/Protocol/Messages.cs b/PlotDirector.NativeCompanion/Protocol/Messages.cs index f6c8c002..aa173b22 100644 --- a/PlotDirector.NativeCompanion/Protocol/Messages.cs +++ b/PlotDirector.NativeCompanion/Protocol/Messages.cs @@ -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; } = ""; diff --git a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs new file mode 100644 index 00000000..bd88188a --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs @@ -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;}=""; +} diff --git a/PlotDirector.NativeCompanion/Tests/Program.cs b/PlotDirector.NativeCompanion/Tests/Program.cs index 3a74233a..319550d1 100644 --- a/PlotDirector.NativeCompanion/Tests/Program.cs +++ b/PlotDirector.NativeCompanion/Tests/Program.cs @@ -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."); diff --git a/PlotDirector.NativeCompanion/Tests/TrayTests.cs b/PlotDirector.NativeCompanion/Tests/TrayTests.cs new file mode 100644 index 00000000..379e70d9 --- /dev/null +++ b/PlotDirector.NativeCompanion/Tests/TrayTests.cs @@ -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 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 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 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)});} + } +} diff --git a/PlotDirector.NativeCompanion/Vsto/AgentProcess.cs b/PlotDirector.NativeCompanion/Vsto/AgentProcess.cs index 33edc708..cb874634 100644 --- a/PlotDirector.NativeCompanion/Vsto/AgentProcess.cs +++ b/PlotDirector.NativeCompanion/Vsto/AgentProcess.cs @@ -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) { diff --git a/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs b/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs deleted file mode 100644 index 7d1c7c14..00000000 --- a/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs +++ /dev/null @@ -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 selectionSnapshots=new Dictionary(); - private readonly Dictionary choices=new Dictionary(); - 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 aiItems=new List(); - public AnalysisWindow(Action analyse,Action stop,Action page,Action submit,Action navigate,Action selectBook,Action previewImport,Action 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 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(); - 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.VerifiedUtcb.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());} - 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 values) - { - rebinding=true;tree.BeginUpdate();try{tree.Nodes.Clear();var parents=new Dictionary(); - 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+40adapter.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(); - 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);} - } -} diff --git a/PlotDirector.NativeCompanion/Vsto/ConnectWindow.cs b/PlotDirector.NativeCompanion/Vsto/ConnectWindow.cs deleted file mode 100644 index 8ae75c1f..00000000 --- a/PlotDirector.NativeCompanion/Vsto/ConnectWindow.cs +++ /dev/null @@ -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); - } - } -} diff --git a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs index baa81020..79b41ef5 100644 --- a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs +++ b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs @@ -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 getAdapter; - private Office.IRibbonUI ui; - public NativeRibbon(Func getAdapter) { this.getAdapter = getAdapter; } - public string GetCustomUI(string ribbonID) - { using (var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("PlotDirector.WordAddIn.Ribbon.xml"))) return reader.ReadToEnd(); } - public void OnLoad(Office.IRibbonUI ribbonUI) { ui = ribbonUI; } - public void Invalidate() { try { ui?.Invalidate(); } catch(COMException) { } } - public string GetStatus(Office.IRibbonControl _) => 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 adapter;private Office.IRibbonUI ui; + public NativeRibbon(Func 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(); } } diff --git a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj index 5cc22c4e..1c2679eb 100644 --- a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj +++ b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj @@ -23,7 +23,7 @@ PlotDirector.Companion.Protocol PlotDirector.Companion.Client ThisAddIn.cs - + ThisAddIn.cs diff --git a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs index 3e0bf079..d097f02b 100644 --- a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs +++ b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs @@ -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)] diff --git a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml index c211df45..cc7b9a77 100644 --- a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml +++ b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml @@ -1,24 +1,6 @@ - - - -