From baa1326caa4ddf871c0ad2b8e62c59b439bcb428 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Thu, 5 Nov 2026 11:06:54 +0000 Subject: [PATCH] feat: add hierarchical chapter AI review and safe Windows developer workflow --- .../Agent/ChapterAiWork.cs | 15 +- .../Agent/CloudGateway.cs | 2 +- .../DeveloperVersion.props | 1 + .../Protocol/README.md | 9 ++ PlotDirector.NativeCompanion/README.md | 10 +- .../Tests/ChapterAiTests.cs | 58 ++++++++ PlotDirector.NativeCompanion/Tests/Program.cs | 1 + .../Vsto/AnalysisWindow.cs | 99 ++++++++++--- .../Vsto/ConnectWindow.cs | 18 +++ .../Vsto/NativeRibbon.cs | 6 +- .../Vsto/PlotDirector.WordAddIn.csproj | 5 +- .../Vsto/Properties/AssemblyInfo.cs | 3 +- PlotDirector.NativeCompanion/Vsto/Ribbon.xml | 4 +- .../Vsto/WordAdapter.cs | 135 ++++++++++++++---- .../WindowsValidation/DeveloperPackage.ps1 | 65 +++++++++ .../Install-WordCompanion.ps1 | 53 +++++++ .../WindowsValidation/Phase3-AI.md | 69 +++++++++ .../Test-DeveloperPackage.ps1 | 21 +++ .../Update-WordCompanion.ps1 | 58 ++++++++ PlotLine.Tests/NativeCompanionHttpTests.cs | 85 +++++++++++ PlotLine.Tests/NativeCompanionTests.cs | 42 ++++++ PlotLine.Tests/Program.cs | 1 + .../Controllers/NativeCompanionController.cs | 2 +- PlotLine/Program.cs | 1 + .../NativeCompanion/NativeAnalysisCache.cs | 14 +- .../StoryIntelligenceOpenAIInfrastructure.cs | 4 +- .../StoryIntelligenceRequestLimiter.cs | 12 ++ .../Views/NativeCompanionAuth/Approve.cshtml | 6 +- 28 files changed, 722 insertions(+), 77 deletions(-) create mode 100644 PlotDirector.NativeCompanion/DeveloperVersion.props create mode 100644 PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs create mode 100644 PlotDirector.NativeCompanion/Vsto/ConnectWindow.cs create mode 100644 PlotDirector.NativeCompanion/WindowsValidation/DeveloperPackage.ps1 create mode 100644 PlotDirector.NativeCompanion/WindowsValidation/Install-WordCompanion.ps1 create mode 100644 PlotDirector.NativeCompanion/WindowsValidation/Phase3-AI.md create mode 100644 PlotDirector.NativeCompanion/WindowsValidation/Test-DeveloperPackage.ps1 create mode 100644 PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1 create mode 100644 PlotLine.Tests/NativeCompanionHttpTests.cs create mode 100644 PlotLine/Services/StoryIntelligenceRequestLimiter.cs diff --git a/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs b/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs index 2ad7ba67..2e0ec49e 100644 --- a/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs +++ b/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs @@ -36,11 +36,11 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable job.Submitted=true;job.Chapter.Paragraphs=job.Paragraphs.ToArray();job.Result.State="analysing"; _=Task.Run(async()=>{ AiChapterResult result; - try{result=await cloud.Analyse(job.Chapter,job.Stop.Token);} + try{result=await cloud.Analyse(job.Chapter,job.Token);} catch(OperationCanceledException){result=new(){RequestId=job.Chapter.RequestId,State="cancelled",Message="AI analysis cancelled."};} catch(Exception e)when(e is HttpRequestException or IOException or InvalidOperationException or System.Text.Json.JsonException) {result=new(){RequestId=job.Chapter.RequestId,State="failed",Message=e is InvalidOperationException?e.Message:"Connection failed. Outcome may be unknown; explicit retry may incur another AI charge."};} - lock(gate){job.Result=result;job.Chapter.Paragraphs=[];job.Paragraphs.Clear();} + lock(gate){job.Result=result;job.Chapter.Paragraphs=[];job.Paragraphs.Clear();job.Finished=true;job.Stop.Dispose();} });break; case "ai-cancel": Clear(descriptor.SessionId);answer.Status="ai-cancelled";return answer; case "ai-status":break; @@ -53,14 +53,15 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable } public void Clear(Guid session) { - lock(gate)if(jobs.Remove(session,out var job)){job.Stop.Cancel();if(job.Submitted)_=cloud.CancelRemote(job.Chapter.RequestId);job.Paragraphs.Clear();} + 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();} } public void Dispose(){lock(gate)foreach(var session in jobs.Keys.ToArray())Clear(session);} - private sealed class Job(AiChapterRequest chapter) + private sealed class Job { - public AiChapterRequest Chapter=chapter;public CancellationTokenSource Stop=new(TimeSpan.FromMinutes(6));public bool Submitted; - public int Characters;public int Position=chapter.ChapterStart,NextParagraph=1,ParagraphStart; + public Job(AiChapterRequest chapter){Chapter=chapter;Position=chapter.ChapterStart;Token=Stop.Token;Result.RequestId=chapter.RequestId;} + public AiChapterRequest Chapter;public CancellationTokenSource Stop=new(TimeSpan.FromMinutes(6));public CancellationToken Token {get;}public bool Submitted,Finished; + public int Characters;public int Position,NextParagraph=1,ParagraphStart; public StringBuilder Text=new();public List Paragraphs=[]; - public AiChapterResult Result=new(){RequestId=chapter.RequestId,State="reading"}; + public AiChapterResult Result=new(){State="reading"}; } } diff --git a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs index 4727fd44..1af64c07 100644 --- a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs +++ b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs @@ -75,7 +75,7 @@ public sealed class CloudGateway : IDisposable 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); using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellation); - if(response.StatusCode==HttpStatusCode.Unauthorized){SignOut();throw new InvalidOperationException("Sign-in expired. Connect again.");} + if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(token==access){token=null;books=[];state="Sign-in expired. Connect again.";}throw new InvalidOperationException("Sign-in expired. Connect again.");} if(!response.IsSuccessStatusCode)throw new InvalidOperationException(response.StatusCode switch{HttpStatusCode.Forbidden=>"Book/subscription access denied.",HttpStatusCode.TooManyRequests=>"Server busy. Retry this chapter later.",HttpStatusCode.BadRequest=>"Chapter mapping or size was rejected. Check boundaries.",_=>"Server unavailable. Check the deployed native API."}); // Bound server response before deserializing; never log a body/provider message. await using var stream=await response.Content.ReadAsStreamAsync(cancellation);using var buffer=new MemoryStream();var bytes=new byte[8192]; diff --git a/PlotDirector.NativeCompanion/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props new file mode 100644 index 00000000..a1899b58 --- /dev/null +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -0,0 +1 @@ +1.0.0.5 diff --git a/PlotDirector.NativeCompanion/Protocol/README.md b/PlotDirector.NativeCompanion/Protocol/README.md index 268baa88..533ae9b6 100644 --- a/PlotDirector.NativeCompanion/Protocol/README.md +++ b/PlotDirector.NativeCompanion/Protocol/README.md @@ -37,3 +37,12 @@ Protocol v1 exposes **no remote Word mutation operation** and no server integrat Analysis uses the same bounded paragraph stream. `snapshot-fragment` acknowledgements include progress percentage. A successful requested `snapshot-end` replies `analysis-complete`, `Progress=100` and the first `AnalysisPage`. `analysis-page` requires exact session/revision/snapshot and uses `Start` as zero-based row offset; it returns at most 40 rows. Candidate rows are suggestions (kind, Word position, paragraph ordinal, bounded title, confidence, evidence), never authorization to import or navigate a server scene. Summary includes approximate words, paragraphs, candidate totals and truncation notice. See Phase 2 report for heuristics and limits. Analysis is incremental in the agent; no COM object crosses IPC and no analysis operation mutates Word. Candidate counts are bounded to 8,192/document and 32,768 globally. Cancellation uses existing `snapshot-cancel`; late replies are refused by the review's session/revision/snapshot guard. Disconnect invalidates the cache: reanalyse after reconnect. Native Context/Intent/server authentication is still deferred. + + +## Optional Phase 3 chapter AI + +`chapter-ai-v1` advertises the additive native feature. `cloud-connect` sends only an author-selected HTTPS root; `cloud-status` returns sign-in status and at most 200 authorized book choices; `cloud-signout` discards the agent's memory-only grant and cancels native AI jobs. Credentials never enter IPC. The agent performs verifier-bound browser pairing over HTTPS; the browser uses normal PlotDirector cookie login and antiforgery approval. + +After explicit author upload confirmation, `ai-begin` specifies one chapter's Start/End, book and request SnapshotId under the exact existing document session/revision. `ai-fragment` reuses the bounded paragraph DTO and chapter-local paragraph ordinals. `ai-submit` starts asynchronous agent HTTP processing and returns promptly; duplicate submits do not create another call. `ai-status` polls that request and pages results using Start as zero-based result offset (40 rows). `ai-cancel` cancels the exact job and best-effort server request. Lifecycle/revision retirement also cancels the job. The live session ID must be unique across Word instances; a foreign duplicate is refused. + +Chapter capture is limited to 120,000 positions/text characters and 10,000 paragraphs. The server returns at most 500 validated AI scenes per chapter; the agent frames only 40 at a time. Suggested boundaries retain actual Word positions, provenance `AI`, confidence and bounded reasoning. Local/marker suggestions remain separate; their chapter ranges provide the upload bounds. No API or IPC operation imports scenes, rewrites text or inserts markers. Network uncertainty is not auto-replayed; explicit author retry is required and may incur a charge. Server deduplication is bounded to its process lifetime and a 30-minute cache. diff --git a/PlotDirector.NativeCompanion/README.md b/PlotDirector.NativeCompanion/README.md index 7ba02763..76c393ff 100644 --- a/PlotDirector.NativeCompanion/README.md +++ b/PlotDirector.NativeCompanion/README.md @@ -1,8 +1,10 @@ -# Native Word Companion — Phase 1 foundation and Phase 2 analysis +# Native Word Companion — developer foundation, structure and AI review + +Phase 3 adds explicit chapter-by-chapter AI review through the existing PlotDirector chapter service, browser-approved sign-in, a hierarchical native review and safe update/build plus explicit per-user installation scripts. See [Phase 3 Windows workflow](WindowsValidation/Phase3-AI.md). The baseline implementation details below describe the foundation; Phase 3's native API does not provide prose synchronization or native Context/Intent/SignalR following. Phase 2 adds optional local structural analysis through the existing snapshot/pipe path, with a native modeless review, progress, cancellation and per-document results. See the [Phase 2 report](../Docs/WordCompanion/2026-11-04-phase2-document-analysis.md) and [Windows analysis checklist](WindowsValidation/Phase2-Analysis.md). The author's Phase 1 Windows smoke test is build `1.0.0.3` at `726a3d5`; the Linux limitations below describe the original foundation. New Phase 2 Word integration still requires Windows qualification. -Publisher: **Nick Beckley**. Architecture: minimal Windows VSTO adapter → per-user modern .NET agent → existing PlotDirector server (native authentication/session-aware server integration deferred). +Publisher: **Nick Beckley**. Architecture: minimal Windows VSTO adapter → per-user modern .NET agent → existing PlotDirector server (native browser-paired chapter preview implemented; session-aware SignalR deferred). This is a development foundation, **not a publicly installable replacement**. Office.js, its manifest, onboarding, Context/Intent and multi-screen UI remain present. Nothing in this tree automatically deploys or installs a component. The .NET Framework VSTO host has not been built or run in Word on the Linux development host. @@ -41,11 +43,11 @@ Selection reads are prioritized and repeated events coalesced. A completed snaps Under IPC backpressure the pending value is retained and the UI yields; it does not reread Word or wait for agent space. Disconnect cancels extraction and reconnect schedules new snapshots. Documents are not retained in an unbounded agent or UI queue. On shutdown the add-in requests worker cancellation without joining it. No HTTP/SignalR/authentication, database, AI, prose parser, entity detector or sync retry runs inside VSTO. -The ribbon has status, Connect / Sign In, Synchronise Now, Settings and Diagnostics. Native server sign-in and prose sync are explicitly unavailable; Synchronise Now means **local structure refresh only**. No large pane/embedded website. Native metadata/marker helpers do not expose a remote mutation operation in protocol v1; no Word prose writer exists. Interop marker removal uses `Delete(false)` to preserve text. +The ribbon has status, Connect / Sign In, Synchronise Now, Settings and Diagnostics. Native server sign-in is available through Connect; prose sync is unavailable; Synchronise Now means **local structure refresh only**. No large pane/embedded website. Native metadata/marker helpers do not expose a remote mutation operation in protocol v1; no Word prose writer exists. Interop marker removal uses `Delete(false)` to preserve text. ## Server and protocol boundaries -The agent is not connected to the old user-only Word presence hub. Authentication and document-session-aware routing must be added in a subsequent reviewed phase. Browser cookie scraping, password storage and forged authentication are not implemented. Do not claim Context/Intent/native live synchronization; existing Office.js/browser coordination stays intact. +The agent is not connected to the old user-only Word presence hub. Native chapter preview now uses browser-approved, verifier-bound four-hour Data Protection grants with current security-stamp and book/subscription checks. No token or cookie crosses IPC or is saved in a Word document. Session-aware SignalR routing remains a subsequent phase. Browser cookie scraping, password storage and forged authentication are not implemented. Do not claim Context/Intent/native live synchronization; existing Office.js/browser coordination stays intact. Server fixes in this branch independently retain hub signatures and event names. Migration 230 adds an atomic owned-build acknowledgement procedure. Old browser/Office.js callers may omit preview/document fields; the server still verifies authenticated build ownership, current access and the exact active manuscript/book/project association. Supplied identifiers must match. Completed acknowledgements are idempotent and cannot be regressed by a late failure. Code depends on migration 230 before any future server deployment; no live migration/deployment is performed by this prototype. diff --git a/PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs b/PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs new file mode 100644 index 00000000..49a945f2 --- /dev/null +++ b/PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs @@ -0,0 +1,58 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using PlotDirector.Companion.Agent; +using PlotDirector.Companion.Protocol; + +internal static class ChapterAiTests +{ + public static async Task Run(Action check) + { + foreach(var bad in new[]{"http://example.invalid/","file:///tmp/site","https://user:password@example.invalid/","https://example.invalid/path","https://example.invalid/?query=1"}) + {try{CloudGateway.ValidateOrigin(bad);throw new Exception("Accepted unsafe origin");}catch(ArgumentException){check(true,"native connection rejects unsafe site root");}} + var handler=new Provider();string browser="";using var cloud=new CloudGateway(handler,url=>browser=url); + cloud.Connect("https://example.invalid/"); + await Wait(()=>cloud.Status().Status.StartsWith("Signed in")); + check(browser.StartsWith("https://example.invalid/native-companion/authorize?code=")&&cloud.Status().Books.Single().BookId==11,"browser-approved sign-in loads only authorised book choices"); + check(handler.Submissions==0,"sign-in and local work never upload chapter prose"); + using var jobs=new ChapterAiWork(cloud);var descriptor=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Revision=4}; + var id=Guid.NewGuid(); + Message Send(string kind,ParagraphFragment? f=null,int offset=0)=>jobs.Handle(descriptor,new(){Kind=kind,SnapshotId=id,BookId=11,Start=kind=="ai-begin"?100:offset,End=120,Fragment=f},new(){Status="ok"}); + check(Send("ai-begin").Status=="ok","AI chapter capture starts only after an explicit command"); + var progress=Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="One chapter paragraph.",CompletesParagraph=true}); + check(progress.Progress==100&&handler.Submissions==0,"bounded chapter capture reports progress without submitting early"); + Send("ai-submit");Send("ai-submit"); + await Wait(()=>Send("ai-status").Ai?.State=="complete");var result=Send("ai-status").Ai!; + check(handler.Submissions==1&&result.Scenes.Single().Start==100&&handler.Last?.ChapterStart==100&&handler.Last.Paragraphs.Single().Index==1,"duplicate submit uses one HTTP call and preserves exact chapter mapping"); + var alien=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid()}; + check(jobs.Handle(alien,new(){Kind="ai-status",SnapshotId=id},new(){Status="ok"}).Status=="obsolete-ai-request","another document cannot retrieve an AI result"); + id=Guid.NewGuid();handler.Stall=true;Send("ai-begin");Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="Another chapter paragraph.",CompletesParagraph=true});Send("ai-submit"); + await Wait(()=>handler.Submissions==2);Send("ai-cancel"); + check(Send("ai-status").Status=="obsolete-ai-request","cancelled network chapter cannot reappear in review"); + handler.Stall=false;handler.Deny=true;id=Guid.NewGuid();Send("ai-begin");Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="Paragraph.",CompletesParagraph=true});Send("ai-submit"); + await Wait(()=>Send("ai-status").Ai?.State=="failed");check(Send("ai-status").Ai!.Message.Contains("denied"),"authorisation failure is isolated and actionable"); + cloud.SignOut();check(cloud.Status().Books.Length==0&&!cloud.Status().Status.StartsWith("Signed in"),"sign-out forgets credential and book list"); + var analysis=new DocumentAnalysis();analysis.Add(new(){ParagraphIndex=1,Start=0,End=12,Text="Chapter One\r",OutlineLevel=1,CompletesParagraph=true});analysis.Add(new(){ParagraphIndex=2,Start=12,End=17,Text="Body\r",OutlineLevel=10,CompletesParagraph=true});analysis.Add(new(){ParagraphIndex=3,Start=17,End=29,Text="Chapter Two\r",OutlineLevel=1,CompletesParagraph=true}); + var chapters=analysis.Page(0).Items.Where(i=>i.Kind=="Chapter").ToArray();check(chapters[0].End==17&&chapters[1].End==29,"local chapters supply explicit nonoverlapping AI extraction ranges"); + var manager=new SessionManager();var a=Guid.NewGuid();var b=Guid.NewGuid();var la=Guid.NewGuid();var lb=Guid.NewGuid();manager.Attach(a,la);manager.Attach(b,lb); + manager.Apply(la,new(){Kind="document",WordInstanceId=a,Sequence=1,Documents=[descriptor]}); + check(manager.Apply(lb,new(){Kind="document",WordInstanceId=b,Sequence=1,Documents=[descriptor]}).Status=="foreign-session-identity","duplicate live session identity cannot cross Word instances"); + } + private static async Task Wait(Func ready){using var stop=new CancellationTokenSource(TimeSpan.FromSeconds(12));while(!ready())await Task.Delay(20,stop.Token);} + private sealed class Provider:HttpMessageHandler + { + public int Submissions;public AiChapterRequest? Last;public bool Stall,Deny; + protected override async Task SendAsync(HttpRequestMessage request,CancellationToken cancellation) + { + var path=request.RequestUri!.AbsolutePath; + if(path.EndsWith("/pair"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new{code=new string('A',24)})}; + if(path.EndsWith("/token"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new{accessToken="test-only-grant"})}; + if(path.EndsWith("/books"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new[]{new CompanionBook{BookId=11,Title="Synthetic test book"}})}; + if(path.EndsWith("/cancel"))return new(HttpStatusCode.NoContent); + Last=await request.Content!.ReadFromJsonAsync(cancellation);Interlocked.Increment(ref Submissions); + if(Stall)await Task.Delay(Timeout.Infinite,cancellation); + if(Deny)return new(HttpStatusCode.Forbidden); + return new(HttpStatusCode.OK){Content=JsonContent.Create(new AiChapterResult{RequestId=Last!.RequestId,State="complete",Scenes=[new(){Start=100,End=120,Kind="Scene",Origin="AI",Title="Narrative interpretation",Reason="A change in narrative focus."}]})}; + } + } +} diff --git a/PlotDirector.NativeCompanion/Tests/Program.cs b/PlotDirector.NativeCompanion/Tests/Program.cs index 5eff8a3e..7213b3a2 100644 --- a/PlotDirector.NativeCompanion/Tests/Program.cs +++ b/PlotDirector.NativeCompanion/Tests/Program.cs @@ -161,4 +161,5 @@ using(var stalledClient=new AgentLink(stalledName,Guid.NewGuid(),_=>true)) stalledClient.Dispose();await stalledClient.Completion.WaitAsync(TimeSpan.FromSeconds(5)); } await AnalysisTests.Run(Check); +await ChapterAiTests.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/Vsto/AnalysisWindow.cs b/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs index 4ee9eb33..5ac77085 100644 --- a/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs +++ b/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs @@ -1,40 +1,93 @@ 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 { - // Small modeless review window. No Word references and no network activity. + // 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{Dock=DockStyle.Top,Height=76,Padding=new Padding(8)}; - private readonly ProgressBar progress=new ProgressBar{Dock=DockStyle.Top,Height=16}; - private readonly ListView rows=new ListView{Dock=DockStyle.Fill,View=View.Details,FullRowSelect=true}; + 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{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 results",AutoSize=true}; - private readonly Button previous=new Button{Text="Previous results",AutoSize=true}; - public AnalysisWindow(Action analyse,Action stop,Action page) + 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 int aiOffset;private Guid session;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) { - Text="PlotDirector — Document structure review";Width=880;Height=500;ShowInTaskbar=false; - rows.Columns.Add("Type",70);rows.Columns.Add("Paragraph",75);rows.Columns.Add("Title / separator",240);rows.Columns.Add("Evidence",320); - var buttons=new FlowLayoutPanel{Dock=DockStyle.Bottom,Height=42,Padding=new Padding(5)}; - var repeat=new Button{Text="Analyse again",AutoSize=true};repeat.Click+=(_,__)=>analyse(); - cancel.Click+=(_,__)=>stop();next.Click+=(_,__)=>page(1);previous.Click+=(_,__)=>page(-1); - buttons.Controls.AddRange(new Control[]{repeat,cancel,previous,next}); - Controls.Add(rows);Controls.Add(progress);Controls.Add(status);Controls.Add(buttons); + Text="PlotDirector — Manuscript review";AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new Size(680,480);Width=980;Height=680;ShowInTaskbar=false; + 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(); + var ask=new Button{Text="AI: analyse checked chapters",AutoSize=true};ask.Click+=(_,__)=>{ + var chosen=local.Nodes.Cast().Where(n=>n.Checked&&n.Tag is StructureSuggestion).Select(n=>(StructureSuggestion)n.Tag).ToArray(); + if(chosen.Length==0){MessageBox.Show("Check one or more chapter nodes in Local structure first.","PlotDirector");return;} + if(SelectedBook<=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(chosen); + }; + cancel.Click+=(_,__)=>stop();actions.Controls.AddRange(new Control[]{repeat,books,ask,cancel}); + var localTab=new TabPage("Local structure");localTab.Controls.Add(local);var aiTab=new TabPage("AI scene suggestions");aiTab.Controls.Add(ai);tabs.TabPages.AddRange(new[]{localTab,aiTab}); + 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{aiOffset=Math.Max(0,aiOffset-40);RenderAi();}}; + next.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(1);else{aiOffset+=40;RenderAi();}}; + tabs.SelectedIndexChanged+=(_,__)=>{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 Render(AnalysisReview review,string connection,Guid session) + public int SelectedBook=>books.SelectedItem is CompanionBook book?book.BookId:0; + private AnalysisPage current; + public void Render(AnalysisReview review,string connection,Guid document,CompanionBook[] available,string cloud,string aiStatus,IList results,bool running) { - var page=review?.Page; - status.Text="Document session "+session.ToString("N").Substring(0,8)+" · Agent: "+connection+"\n"+(review?.Status??"No active document."); - if(page!=null)status.Text+="\n"+page.WordCount.ToString("N0")+" approximate words · "+page.ParagraphCount.ToString("N0")+" paragraphs · "+page.ChapterCount+" chapter / "+page.SceneCount+" scene suggestions. "+(page.Truncated?"Result limit reached. ":"")+page.Notice; - progress.Value=review?.Progress??0;cancel.Enabled=review?.Running==true; - previous.Enabled=page!=null&&page.Offset>0;next.Enabled=page!=null&&page.Offset+page.Items.Length(); + status.Text="Document "+document.ToString("N").Substring(0,8)+" · "+cloud+"\n"+(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; + var key=string.Join("|",available.Select(b=>b.BookId+":"+b.Title)); + if(bookKey!=key){var selected=SelectedBook;bookKey=key;books.DataSource=available;books.SelectedIndex=-1;if(available.Any(b=>b.BookId==selected))books.SelectedValue=selected;} + var newKey=(review?.SnapshotId.ToString()??"")+":"+(current?.Offset??-1); + if(renderKey!=newKey){renderKey=newKey;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) + { + 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){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+"]"){Tag=item,ToolTipText=item.Title}); + } + tree.ExpandAll();}finally{tree.EndUpdate();} + } + 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 UpdatePages() + { + 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; + previous.Enabled=offset>0;next.Enabled=offset+40{adapter.ConnectToServer(address.Text.Trim());Close();}; + var signout=new Button{Text="Disconnect / forget sign-in",AutoSize=true};signout.Click+=(_,__)=>{adapter.SignOut();Close();}; + layout.Controls.Add(connect);layout.Controls.Add(signout);Controls.Add(layout); + } + } +} diff --git a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs index e8690051..2e3b7fe4 100644 --- a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs +++ b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs @@ -17,16 +17,16 @@ namespace PlotDirector.WordAddIn { using (var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("PlotDirector.WordAddIn.Ribbon.xml"))) return reader.ReadToEnd(); } public void OnLoad(Office.IRibbonUI ribbonUI) { ui = ribbonUI; } public void Invalidate() { try { ui?.Invalidate(); } catch(COMException) { } } - public string GetStatus(Office.IRibbonControl _) => "Agent: " + (getAdapter()?.ConnectionState ?? "Unavailable") + " · Server: unavailable"; + public string GetStatus(Office.IRibbonControl _) => "Agent: " + (getAdapter()?.ConnectionState ?? "Unavailable")+" · "+(getAdapter()?.CloudState??"Not signed in"); public bool CanSynchronize(Office.IRibbonControl _) => getAdapter()?.HasActiveDocument == true; - public void Connect(Office.IRibbonControl _) { getAdapter()?.Reconnect(); MessageBox.Show("The local agent reconnects in the background. Native server sign-in is not available yet; no browser credentials are reused.","PlotDirector — Nick Beckley"); } + 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()?.RequestSnapshot(); } public void Settings(Office.IRibbonControl _) { if (getAdapter() == null) return; - var choice = MessageBox.Show("Local analysis and Manual structural refresh are available. Automatic / On Save prose synchronization is not available.\n\nPersist a native identity in this document's metadata? This will mark the document modified; it will not save or change prose. Existing Office.js bindings are untouched.","PlotDirector Settings",MessageBoxButtons.YesNo); + var choice = MessageBox.Show("Local analysis and Manual structural refresh are available. AI scene review requires explicit chapter upload. Automatic / On Save prose synchronization is not available.\n\nPersist a native identity in this document's metadata? This will mark the document modified; it will not save or change prose. Existing Office.js bindings are untouched.","PlotDirector Settings",MessageBoxButtons.YesNo); if (choice == DialogResult.Yes) getAdapter().PersistNativeIdentity(); } public void Diagnostics(Office.IRibbonControl _) => MessageBox.Show(getAdapter()?.Diagnostics ?? "Companion did not initialize. Word remains usable. Check the Windows validation prerequisites.","PlotDirector Diagnostics — Nick Beckley"); diff --git a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj index 4d91c394..61e399e3 100644 --- a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj +++ b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj @@ -1,5 +1,6 @@ + {42996908-DB24-4A55-AFF1-1017A31D7206} {BAA0C2D2-18E2-41B9-852F-F413020CAA33};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} @@ -7,7 +8,7 @@ trueLibraryv4.8latest PlotDirector.WordAddInPlotDirector.WordAddIn Word15.0true - 3PlotDirector Word Companion (Phase 1)PlotDirector by Nick Beckley — native prototype + 3PlotDirector Word CompanionPlotDirector by Nick Beckley — native prototype PlotDirector Word CompanionNick Beckleyfalsetrue bin\$(Configuration)\true $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) @@ -22,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 4fd76f91..6f637e04 100644 --- a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs +++ b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs @@ -1,7 +1,8 @@ using System.Reflection; using System.Runtime.InteropServices; -[assembly: AssemblyTitle("PlotDirector Word Companion — Phase 1")] +[assembly: AssemblyTitle("PlotDirector Word Companion — Native development")] [assembly: AssemblyCompany("Nick Beckley")] [assembly: AssemblyProduct("PlotDirector")] [assembly: AssemblyVersion("0.1.0.0")] +[assembly: AssemblyFileVersion("1.0.0.5")] [assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml index 72beb1b8..1d894576 100644 --- a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml +++ b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml @@ -2,8 +2,8 @@ - + +