112 lines
18 KiB
C#
112 lines
18 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using PlotDirector.Companion.Agent;
|
|
using PlotDirector.Companion.Protocol;
|
|
internal static class TrayTests
|
|
{
|
|
public static async Task Run(Action<bool,string> check)
|
|
{
|
|
var handler=new Server();var launched=new List<string>();using var cloud=new CloudGateway(handler,launched.Add);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);control.Attach(instance,lease,true);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");
|
|
var writerPath=$"/Writer/Write?bookId=3&wordInstanceId={instance:D}&wordSessionId={first.SessionId:D}";
|
|
var auth=cloud.Status().AuthenticationContext;
|
|
launched.Clear();
|
|
var invalidData=false;
|
|
try{cloud.OpenCompanionPage(writerPath,auth);}catch(InvalidDataException){invalidData=true;}
|
|
check(invalidData&&launched.Count==0,"native workspace allowlist rejects Writer before URI decoding or browser invocation");
|
|
control.OpenPage(first.SessionId,"writer");
|
|
check(launched.Single()=="https://fixture.invalid"+writerPath,"Return to Writer launches the authenticated same-origin URL for the exact bound document");
|
|
invalidData=false;
|
|
try{cloud.OpenCompanionPage("//other.invalid/native-companion/workspace",auth);}catch(InvalidDataException){invalidData=true;}
|
|
check(invalidData&&launched.Count==1,"malformed or foreign launch path never reaches the browser");
|
|
bool staleLaunch=false;
|
|
try{control.OpenPage(Guid.NewGuid(),"writer");}catch(InvalidOperationException){staleLaunch=true;}
|
|
check(staleLaunch&&launched.Count==1,"Return to Writer rejects a stale document without launching a page");
|
|
var retired=Apply(new(){Kind="tray-intent",SessionId=first.SessionId,Revision=1});
|
|
check(retired.Status!="ok"&&launched.Count==1,"retired Intent ribbon IPC cannot launch a separate workspace");
|
|
control.OpenPage(first.SessionId,"context");
|
|
check(launched.Last().EndsWith("&view=context",StringComparison.Ordinal)&&launched.Last().Contains("sessionId="+first.SessionId),"Context launch retains authorised exact-session routing for browser window reuse");
|
|
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){}
|
|
}
|
|
var registered=control.Documents.Single(d=>d.Session==first.SessionId);
|
|
var navigation=Guid.NewGuid();registered.PendingNavigation=navigation;registered.NavigationRevision=1;registered.NavigationExpires=DateTime.UtcNow.AddSeconds(20);
|
|
Apply(new(){Kind="adapter-result",SessionId=second.SessionId,Revision=1,SnapshotId=navigation,OperationMessage="ok"});check(registered.NavigationAcknowledgedId==null,"another Word document cannot acknowledge this navigation");
|
|
Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=1,SnapshotId=navigation,OperationMessage="ok"});check(registered.NavigationAcknowledgedId==navigation&®istered.NavigationResult=="completed"&®istered.PendingNavigation==Guid.Empty,"exact adapter result reaches document-scoped presence acknowledgement");
|
|
registered.PendingNavigation=Guid.NewGuid();registered.NavigationRevision=0;registered.NavigationExpires=DateTime.UtcNow.AddSeconds(20);Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=0,SnapshotId=registered.PendingNavigation,OperationMessage="ok"});check(registered.NavigationAcknowledgedId==navigation,"stale native acknowledgement cannot replace completed navigation");
|
|
var fenced=new AdapterCommand{SessionId=first.SessionId,Revision=1,ManuscriptId=first.ManuscriptId,ExpiresUtc=DateTime.UtcNow.AddSeconds(10)};check(NavigationPolicy.Current(fenced,first.SessionId,1,first.ManuscriptId,DateTime.UtcNow,true)&&!NavigationPolicy.Current(fenced,second.SessionId,1,first.ManuscriptId,DateTime.UtcNow,true)&&!NavigationPolicy.Current(fenced,first.SessionId,1,first.ManuscriptId,DateTime.UtcNow,false)&&!NavigationPolicy.Current(fenced,first.SessionId,1,first.ManuscriptId,DateTime.UtcNow.AddSeconds(11),true),"native execution gate rejects foreign session, dirty state and expired UI queue without COM work");var priorSequence=registered.PresenceSequence;Apply(new(){Kind="reconcile",Documents=[first,second]});check(control.Documents.Single(d=>d.Session==first.SessionId).Book==3&&control.Documents.Single(d=>d.Session==first.SessionId).PresenceSequence==priorSequence,"reconciliation preserves verified book and monotonic heartbeat state");
|
|
handler.Command=new(){Id=Guid.NewGuid(),Kind="wizard-capture",SessionId=first.SessionId,Revision=1};var captureId=handler.Command.Id;registered.SceneId=null;registered.LastPresenceKey="";registered.LastPresenceUtc=DateTime.MinValue;
|
|
using(var stop=new CancellationTokenSource()){
|
|
var heartbeats=control.Heartbeat(stop.Token);await Until(()=>control.Documents.Single(d=>d.Session==first.SessionId).Capture!=null);
|
|
Apply(new(){Kind="snapshot-begin",SessionId=first.SessionId,Revision=1,SnapshotId=captureId,End=20,RequestAnalysis=true});
|
|
Apply(new(){Kind="snapshot-fragment",SessionId=first.SessionId,Revision=1,SnapshotId=captureId,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=captureId,Fragment=new(){Start=10,End=20,ParagraphIndex=2,OutlineLevel=10,Text="Body text\r",CompletesParagraph=true}});
|
|
Apply(new(){Kind="snapshot-end",SessionId=first.SessionId,Revision=1,SnapshotId=captureId});await Until(()=>registered.AcceptedRevision==1);
|
|
check(handler.Captures==1,"wizard request reuses bounded snapshot IPC and acknowledges only the completed server transfer");stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}
|
|
}
|
|
handler.DenyPresence=true;try{await cloud.Presence(instance,first.SessionId,new(){BookId=3},cloud.Status().AuthenticationContext);}catch(InvalidOperationException){}check(!cloud.Status().Books.Any(b=>b.BookId==3)&&cloud.Status().Books.Any(b=>b.BookId==4),"one rejected book registration does not disconnect other authorised books");handler.DenyPresence=false;await cloud.CheckConnection();
|
|
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&&control.Documents[0].Book==3,"late disconnect cannot remove a replacement tray lease or its verified session-only book association");
|
|
check(!control.CanMaintain(first.SessionId),"older Word adapter cannot receive unsupported maintenance commands");
|
|
control.Attach(instance,replacementLease,true,true);Apply(new(){Kind="reconcile",Documents=[first,second]});
|
|
check(control.CanMaintain(first.SessionId),"maintenance requires explicit adapter capability negotiation");
|
|
control.Maintain(first.SessionId,"inspect");AdapterCommand? maintenance=null;
|
|
for(var i=0;i<16;i++){var queued=Apply(new(){Kind="ping"}).Command;if(queued?.Kind=="maintenance-inspect"){maintenance=queued;break;}}
|
|
check(maintenance?.SessionId==first.SessionId&&maintenance.Revision==1,"inspection command targets exact selected document and revision");
|
|
Apply(new(){Kind="adapter-result",SessionId=second.SessionId,Revision=1,SnapshotId=Guid.NewGuid(),OperationMessage="Complete: unrelated"});
|
|
check(control.Documents.Single(d=>d.Session==first.SessionId).MaintenanceReport.Contains("Working"),"another document cannot replace pending inspection results");
|
|
Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=1,SnapshotId=maintenance!.Id,OperationMessage="Complete: inspected"});
|
|
check(control.Documents.Single(d=>d.Session==first.SessionId).MaintenanceReport=="Complete: inspected","correlated inspection result is available in Advanced settings");
|
|
var maintained=control.Documents.Single(d=>d.Session==first.SessionId);maintained.Book=3;
|
|
control.SelectBook(first.SessionId,3,true);
|
|
AdapterCommand? association=null;
|
|
for(var i=0;i<16;i++){var queued=Apply(new(){Kind="ping"}).Command;if(queued?.Kind=="associate"){association=queued;break;}}
|
|
check(association is {Remember:true}&&association.SessionId==first.SessionId&&association.BookId==3&&!maintained.AssociationNeedsSave,"remember targets the selected document and waits for Word acknowledgement");
|
|
Apply(new(){Kind="adapter-result",SessionId=second.SessionId,Revision=1,SnapshotId=association!.Id,OperationMessage="association-written"});
|
|
check(!maintained.AssociationNeedsSave,"another Word document cannot acknowledge the association");
|
|
Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=1,SnapshotId=association.Id,OperationMessage="association-written"});
|
|
check(maintained.AssociationNeedsSave&&maintained.AssociationNotice.Contains("Save the document"),"matching Word acknowledgement shows a save reminder");
|
|
Apply(new(){Kind="selection",SessionId=first.SessionId,Revision=1,WordSaved=true});
|
|
check(!maintained.AssociationNeedsSave&&maintained.AssociationNotice=="","normal Word save clears the reminder");
|
|
control.Maintain(first.SessionId,"clean");maintenance=null;for(var i=0;i<16;i++){var queued=Apply(new(){Kind="ping"}).Command;if(queued?.Kind=="maintenance-clean"){maintenance=queued;break;}}
|
|
check(maintained.Book==3,"unlink does not claim success before Word acknowledges cleanup");
|
|
Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=1,SnapshotId=maintenance!.Id,OperationMessage="Stopped: read-only"});
|
|
check(maintained.Book==3,"failed cleanup preserves document association");
|
|
control.Maintain(first.SessionId,"reset");maintenance=null;for(var i=0;i<16;i++){var queued=Apply(new(){Kind="ping"}).Command;if(queued?.Kind=="maintenance-reset"){maintenance=queued;break;}}
|
|
var resetRegistration=Apply(new(){Kind="document",Documents=[new(){SessionId=first.SessionId,ManuscriptId=first.ManuscriptId,Title=first.Title,Revision=1,IdentityPersisted=false}]});
|
|
check(resetRegistration.Status=="ok","association reset retains live-session manuscript identity while removing persisted metadata");
|
|
Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=1,SnapshotId=maintenance!.Id,OperationMessage="Complete: reset"});
|
|
check(maintained.Book==0&&control.Documents.Single(d=>d.Session==second.SessionId).MaintenanceReport!="Complete: reset","acknowledged reset unlinks only the selected session");
|
|
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<bool> condition){using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(10));while(!condition())await Task.Delay(20,timeout.Token);}
|
|
internal sealed class Server:HttpMessageHandler
|
|
{
|
|
public readonly System.Collections.Concurrent.ConcurrentQueue<NativePresence> Observations=new();public int Heartbeats,Captures;public bool DenyPresence;public AdapterCommand? Command;private Guid captureReply;
|
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
|
|
{if(request.Method==HttpMethod.Post&&request.RequestUri!.AbsolutePath.EndsWith("/presence")){Observations.Enqueue(System.Text.Json.JsonSerializer.Deserialize<NativePresence>(request.Content!.ReadAsStringAsync(cancellation).GetAwaiter().GetResult(),new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web))!);Interlocked.Increment(ref Heartbeats);if(DenyPresence)return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Forbidden));var reply=new NativePresence{Navigation=Command};if(Command!=null)captureReply=Command.Id;Command=null;return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(reply)});}if(request.RequestUri!.AbsolutePath.EndsWith("/manuscript-capture")){Interlocked.Increment(ref Captures);return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(new NativePresence{CaptureRequestId=captureReply,Revision=1})});}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 CompanionBook{BookId=4,Title="Other allowed book"}},_=>new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow}};return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(body)});}
|
|
}
|
|
}
|