From e34c9a53ba234ab89dba2b5a777b99bfba5e97b1 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Fri, 6 Nov 2026 10:42:09 +0000 Subject: [PATCH] Isolate desktop presentation state and harden saved Intent evidence review --- PlotDirector.NativeCompanion/Agent/TrayApplication.cs | 5 +++-- PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs | 2 ++ PlotDirector.NativeCompanion/Tests/TrayTests.cs | 2 ++ PlotLine.Tests/Browser/writing-desks.cjs | 2 +- PlotLine.Tests/IntentAssessmentTests.cs | 1 + PlotLine.Tests/ToolbarBrowserHost.cs | 4 ++-- PlotLine/Services/IntentAssessmentService.cs | 2 +- 7 files changed, 12 insertions(+), 6 deletions(-) diff --git a/PlotDirector.NativeCompanion/Agent/TrayApplication.cs b/PlotDirector.NativeCompanion/Agent/TrayApplication.cs index be36bae4..6581c487 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayApplication.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayApplication.cs @@ -40,7 +40,8 @@ internal sealed class CompanionWindow:Form private readonly Button contextAction=new(){Text="Open Context",AutoSize=true},intentAction=new(){Text="Open Intent",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); + private TrayDocument[] displayedDocuments=[]; + private TrayDocument? Current=>displayedDocuments.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; @@ -85,7 +86,7 @@ internal sealed class CompanionWindow:Form 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; + var state=cloud.Status();var docs=control.PresentationDocuments;displayedDocuments=docs;var key=string.Join("|",docs.Select(d=>d.Session+":"+d.Title+":"+d.Active));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);} diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs index c6e7a57a..b8b2d513 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs @@ -9,6 +9,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C private readonly Dictionary> commands=[];private readonly Dictionary leases=[]; public event Action? OpenRequested; public TrayDocument[] Documents {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).ToArray();}} + public TrayDocument[] PresentationDocuments {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).Select(d=>d.Snapshot()).ToArray();}} public void Attach(Guid instance,Guid lease){lock(gate){Disconnected(instance);leases[instance]=lease;}} public Message Exchange(Guid instance,Message request,Message answer,Guid lease=default) { @@ -109,5 +110,6 @@ public sealed class TrayDocument public string LastPresenceKey="";public DateTime LastPresenceUtc;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 Cursor;public int Retained;public int Failed;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 HashSet<(long,int,int)> FailedChapters=[];public List Errors=[]; + internal TrayDocument Snapshot(){var copy=(TrayDocument)MemberwiseClone();copy.Completed=new(Completed);copy.FailedChapters=new(FailedChapters);copy.Errors=new(Errors);copy.Pending=new(Pending);return copy;} public override string ToString()=>Title+(Active?" (active in Word)":""); } diff --git a/PlotDirector.NativeCompanion/Tests/TrayTests.cs b/PlotDirector.NativeCompanion/Tests/TrayTests.cs index d4b41084..b179abee 100644 --- a/PlotDirector.NativeCompanion/Tests/TrayTests.cs +++ b/PlotDirector.NativeCompanion/Tests/TrayTests.cs @@ -11,6 +11,8 @@ internal static class TrayTests 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"); + var presentation=control.PresentationDocuments.Single(d=>d.Session==first.SessionId);presentation.Completed.Add((1,3,0));presentation.FailedChapters.Add((1,3,0));presentation.Errors.Add("UI copy"); + check(control.Documents.Single(d=>d.Session==first.SessionId).Completed.Count==0&&control.Documents.Single(d=>d.Session==first.SessionId).FailedChapters.Count==0&&control.Documents.Single(d=>d.Session==first.SessionId).Errors.Count==0,"presentation collections are isolated from background chapter updates"); 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}}); diff --git a/PlotLine.Tests/Browser/writing-desks.cjs b/PlotLine.Tests/Browser/writing-desks.cjs index 7125a5e6..d5c7d559 100644 --- a/PlotLine.Tests/Browser/writing-desks.cjs +++ b/PlotLine.Tests/Browser/writing-desks.cjs @@ -1,2 +1,2 @@ const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('path'); -(async()=>{const browser=await chromium.launch();try{for(const role of ['context','intent'])for(const width of [400,760,1440])for(const theme of ['modern-light','modern-dark','warm-light','warm-dark']){const page=await browser.newPage({viewport:{width,height:1000}});const response=await page.goto(`http://127.0.0.1:5238/writing-desk-fixture/${role}`);assert.equal(response.status(),200);await page.evaluate(({role,theme})=>{document.documentElement.setAttribute('data-app-theme',theme);document.documentElement.setAttribute('data-theme',theme.endsWith('dark')?'dark':'light');const main=document.querySelector('main');main.setAttribute('data-writing-'+role,'');main.dataset.followMode='snapshot';const wrap=document.createElement('div');wrap.setAttribute('data-writing-'+role+'-content','');while(main.firstChild)wrap.append(main.firstChild);main.append(wrap);},{role,theme});await page.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/writing-follow.js')});await page.addScriptTag({path:path.resolve(__dirname,`../../PlotLine/wwwroot/js/writing-${role}.js`)});assert.ok(await page.getByText('A deliberately long scene title for a narrow reference screen',{exact:true}).count());assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`${role} overflow ${width} ${theme}`);if(role==='context'){assert.ok(await page.getByText('People at this point',{exact:true}).isVisible());assert.ok(await page.getByText('No participants saved for this scene.',{exact:true}).isVisible());await page.click('[data-writing-context-tab="place"]');assert.equal(await page.locator('[data-writing-context-panel="place"]').isVisible(),true);}else{await page.click('[data-writing-intent-tab="evidence"]');assert.equal(await page.locator('[data-intent-assessment]').isVisible(),true);assert.ok(await page.getByText('Edit intentions and objective completion',{exact:true}).isVisible());}await page.close();}const empty=await browser.newPage();await empty.goto('http://127.0.0.1:5238/writing-desk-fixture/context?empty=true');assert.ok(await empty.getByText('No current Word scene',{exact:true}).isVisible());console.log('PASS actual Context/Intent Razor, tab navigation, missing metadata, objective edit link, 400/760/1440 layouts and four light/dark/warm themes');}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);}); +(async()=>{const browser=await chromium.launch();try{for(const role of ['context','intent'])for(const width of [400,760,1440])for(const theme of ['modern-light','modern-dark','warm-light','warm-dark']){const page=await browser.newPage({viewport:{width,height:1000}});const response=await page.goto(`http://127.0.0.1:5238/writing-desk-fixture/${role}`);assert.equal(response.status(),200);await page.evaluate(({role,theme})=>{document.documentElement.setAttribute('data-app-theme',theme);document.documentElement.setAttribute('data-theme',theme.endsWith('dark')?'dark':'light');const main=document.querySelector('main');main.setAttribute('data-writing-'+role,'');main.dataset.followMode='snapshot';const wrap=document.createElement('div');wrap.setAttribute('data-writing-'+role+'-content','');while(main.firstChild)wrap.append(main.firstChild);main.append(wrap);},{role,theme});await page.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/writing-follow.js')});await page.addScriptTag({path:path.resolve(__dirname,`../../PlotLine/wwwroot/js/writing-${role}.js`)});assert.ok(await page.getByText('A deliberately long scene title for a narrow reference screen',{exact:true}).count());assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`${role} overflow ${width} ${theme}`);if(role==='context'){assert.ok(await page.getByText('People at this point',{exact:true}).isVisible());assert.ok(await page.getByText('No participants saved for this scene.',{exact:true}).isVisible());await page.click('[data-writing-context-tab="place"]');assert.equal(await page.locator('[data-writing-context-panel="place"]').isVisible(),true);}else{await page.click('[data-writing-intent-tab="evidence"]');assert.equal(await page.locator('[data-intent-assessment]').isVisible(),true);assert.ok(await page.getByText('Edit intentions and objective completion',{exact:true}).isVisible());}await page.close();}const empty=await browser.newPage();await empty.goto('http://127.0.0.1:5238/writing-desk-fixture/context?empty=true');assert.ok(await empty.getByText('No current Word scene',{exact:true}).isVisible());const evidence=await browser.newPage();await evidence.goto('http://127.0.0.1:5238/writing-desk-fixture/evidence');assert.ok(await evidence.getByText('Evidence matches the saved prose and plan.',{exact:false}).isVisible());assert.equal(await evidence.locator('[data-intent-decision]').count(),4);await evidence.goto('http://127.0.0.1:5238/writing-desk-fixture/evidence?stale=true');assert.ok(await evidence.getByText('Out of date',{exact:false}).isVisible());assert.equal(await evidence.locator('[data-intent-decision]').count(),0,'stale suggestions cannot be decided');console.log('PASS actual Context/Intent Razor, tab navigation, missing metadata, objective edit link, 400/760/1440 layouts and four light/dark/warm themes');}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);}); diff --git a/PlotLine.Tests/IntentAssessmentTests.cs b/PlotLine.Tests/IntentAssessmentTests.cs index db1b09b9..92204ad8 100644 --- a/PlotLine.Tests/IntentAssessmentTests.cs +++ b/PlotLine.Tests/IntentAssessmentTests.cs @@ -15,6 +15,7 @@ internal static class IntentAssessmentTests Check(IntentAssessmentService.Fingerprint(prose,plan)!=IntentAssessmentService.Fingerprint(prose+"Changed",plan),"Source revisions invalidate evidence"); Check(IntentAssessmentService.Fingerprint(prose,plan)!=IntentAssessmentService.Fingerprint(prose,[new("purpose","Hide the letter")]),"Plan changes invalidate evidence"); try{IntentAssessmentService.Validate("{\"items\":[]}",plan,prose);throw new Exception("Missing objectives accepted");}catch(ArgumentException){} + try{IntentAssessmentService.Validate("{}",plan,prose);throw new Exception("Missing evidence accepted");}catch(ArgumentException){} var scene=new SceneEditViewModel{SceneID=22,ScenePurposeNotes=plan[0].Text}; var context=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult((int)a![0]! ==22?new StoryContextViewModel{Position=new StoryPosition(1,3,10,22),Scene=scene}:null)); var writer=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(null)); diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 6206a180..7b49fb84 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -243,8 +243,8 @@ internal static class ToolbarBrowserHost var role=context.Request.RouteValues["role"]?.ToString();var empty=context.Request.Query["empty"]=="true"; var scene=new SceneEditViewModel{SceneID=22,SceneTitle="A deliberately long scene title for a narrow reference screen",ChapterID=10,ScenePurposeNotes="Reveal the letter",Summary="Saved scene summary",Project=new Project{ProjectID=7,ProjectName="Fixture project"},Book=new Book{BookID=12,BookTitle="Fixture book"},Chapter=new Chapter{ChapterID=10,ChapterTitle="Opening",ChapterNumber=1}}; var story=new StoryContextViewModel{Position=new StoryPosition(7,12,10,22),Scene=scene}; - object model=role=="context"?new WritingContextDisplayViewModel{Context=empty?null:story}:new WritingIntentDisplayViewModel{Context=empty?null:story}; - var writingRoute=new RouteData();writingRoute.Values["controller"]="Writing";var action=new ActionContext(context,writingRoute,new ActionDescriptor());var path=role=="context"?"/Views/Writing/_WritingContextContent.cshtml":"/Views/Writing/_WritingIntentContent.cshtml"; + object model=role=="evidence"?new IntentAssessmentFrame(22,context.Request.Query["stale"]=="true"?"new-hash":"saved-hash",[new("purpose","Reveal the letter")],"Saved prose",new IntentAssessment{InputHash="saved-hash",CreatedUtc=DateTime.UtcNow,ResultsJson=System.Text.Json.JsonSerializer.Serialize(new[]{new IntentEvidence("purpose","partial","A qualified suggestion","Saved prose","Reveal the letter")}),DecisionsJson="{\"purpose\":\"deferred\"}"}):role=="context"?new WritingContextDisplayViewModel{Context=empty?null:story}:new WritingIntentDisplayViewModel{Context=empty?null:story}; + var writingRoute=new RouteData();writingRoute.Values["controller"]="Writing";var action=new ActionContext(context,writingRoute,new ActionDescriptor());var path=role=="evidence"?"/Views/Writing/_IntentAssessment.cshtml":role=="context"?"/Views/Writing/_WritingContextContent.cshtml":"/Views/Writing/_WritingIntentContent.cshtml"; var view=context.RequestServices.GetRequiredService().GetView(null,path,false);using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model}; await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions())); context.Response.ContentType="text/html";await context.Response.WriteAsync("
"+writer+"
"); diff --git a/PlotLine/Services/IntentAssessmentService.cs b/PlotLine/Services/IntentAssessmentService.cs index 4610aba2..b73b397c 100644 --- a/PlotLine/Services/IntentAssessmentService.cs +++ b/PlotLine/Services/IntentAssessmentService.cs @@ -46,7 +46,7 @@ public sealed class IntentAssessmentService(IStoryContextService context,IWriter } public static IntentEvidence[] Validate(string json,IntentObjective[] objectives,string source) { - using var document=JsonDocument.Parse(json);var rows=document.RootElement.GetProperty("items").Deserialize()??[]; + using var document=JsonDocument.Parse(json);if(!document.RootElement.TryGetProperty("items",out var items))throw new ArgumentException("AI returned no objective evidence. Retry.");var rows=items.Deserialize()??[]; if(rows.Any(x=>x is null)||rows.Length!=objectives.Length||rows.Select(x=>x.Key).Distinct().Count()!=rows.Length||rows.Any(x=>!objectives.Any(o=>o.Key==x.Key)))throw new ArgumentException("AI returned an incomplete objective set. Retry; previous evidence is preserved."); return rows.Select(x=>{ if(x.Reason==null||x.Quote==null||x.Reason.Length>1600||x.Quote.Length>2000||x.Status is not ("achieved" or "partial" or "not-evidenced" or "contradicted" or "cannot-assess"))throw new ArgumentException("AI returned an invalid evidence format. Retry.");