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) { var handler=new Server();using var cloud=new CloudGateway(handler,_=>{});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"); 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}}); 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"); var frontSnapshot=Guid.NewGuid();Apply(new(){Kind="snapshot-begin",SessionId=second.SessionId,Revision=1,SnapshotId=frontSnapshot,End=20,RequestAnalysis=true}); Apply(new(){Kind="snapshot-fragment",SessionId=second.SessionId,Revision=1,SnapshotId=frontSnapshot,Fragment=new(){Start=0,End=10,ParagraphIndex=1,OutlineLevel=1,Text="Contents\r",CompletesParagraph=true}}); Apply(new(){Kind="snapshot-fragment",SessionId=second.SessionId,Revision=1,SnapshotId=frontSnapshot,Fragment=new(){Start=10,End=20,ParagraphIndex=2,OutlineLevel=1,Text="Opening\r",CompletesParagraph=true}}); Apply(new(){Kind="snapshot-end",SessionId=second.SessionId,Revision=1,SnapshotId=frontSnapshot});check(control.Documents.Single(d=>d.Session==second.SessionId).Chapters.Single().Start==10,"tray preserves original leading front-matter exclusions before Heading 1 chapters"); 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"); using(var heartbeatStop=new CancellationTokenSource()){ var heartbeat=control.Heartbeat(heartbeatStop.Token);await Until(()=>handler.Heartbeats==1);await Task.Delay(600); check(handler.Heartbeats==1,"stationary scene does not repeatedly post presence between heartbeats");control.Documents.Single(d=>d.Session==first.SessionId).SceneId=20;await Until(()=>handler.Heartbeats==2); check(true,"changed scene posts lightweight presence before the periodic heartbeat");heartbeatStop.Cancel();try{await heartbeat;}catch(OperationCanceledException){} } 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.SelectBook(second.SessionId,3,false);control.Analyse(second.SessionId,[10]);check(control.Documents.Single(d=>d.Session==second.SessionId).Job==Guid.Empty&&control.Documents.Single(d=>d.Session==second.SessionId).Pending.Count==1,"multiple document AI batches serialize against existing per-author provider limits");control.Cancel(second.SessionId); 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"); var replacementLease=Guid.NewGuid();control.Attach(instance,replacementLease);Apply(new(){Kind="document",Documents=[first]});control.Disconnected(instance,lease);check(control.Documents.Length==1,"late disconnect cannot remove a replacement tray lease"); control.Disconnected(instance,replacementLease);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 { public int Heartbeats; protected override Task SendAsync(HttpRequestMessage request,CancellationToken cancellation) {if(request.Method==HttpMethod.Post&&request.RequestUri!.AbsolutePath.EndsWith("/presence"))Interlocked.Increment(ref Heartbeats);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)});} } }