53 lines
7.8 KiB
C#
53 lines
7.8 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using PlotDirector.Companion.Agent;
|
|
using PlotDirector.Companion.Protocol;
|
|
using PlotDirector.Companion.Protocol.Manuscript;
|
|
internal static class ChapterAgentTests
|
|
{
|
|
public static async Task Run()
|
|
{
|
|
var handler=new Handler();using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://chapters.test/");await Until(()=>cloud.Status().Books.Any());await cloud.CheckConnection();
|
|
var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var tray=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid();handler.Manuscript=Guid.NewGuid();long sequence=0;
|
|
sessions.Attach(instance,lease,chapters:true);tray.Attach(instance,lease,capture:true,paragraphs:true,chapters:true);
|
|
Message Send(Message message){message.WordInstanceId=instance;message.SessionId=session;message.Revision=1;message.Sequence=++sequence;return tray.Exchange(instance,message,sessions.Apply(lease,message),lease);}
|
|
Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Synthetic chapter manuscript.docx"}]});tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=0,End=0,WordSaved=true});
|
|
using var stop=new CancellationTokenSource();var heartbeats=tray.Heartbeat(stop.Token);
|
|
try{
|
|
AdapterCommand? command=null;for(int n=0;n<200&&command==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")command=pending;await Task.Delay(20);}
|
|
Check(command?.Kind=="chapter-check","Reopened chapter-capable document requests a bounded current-chapter read, never a full snapshot");
|
|
var text="Chapter 1\rExact prose\r";var xml="<w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:w14='http://schemas.microsoft.com/office/word/2010/wordml'><w:body><w:p w14:paraId='00000001'><w:pPr><w:outlineLvl w:val='0'/></w:pPr><w:r><w:t>Chapter 1</w:t></w:r></w:p><w:p w14:paraId='00000002'><w:r><w:t>Exact prose</w:t></w:r></w:p></w:body></w:document>";
|
|
void Frames(AdapterCommand read){Send(new(){Kind="chapter-begin",SnapshotId=read.Id,BookId=3,Start=0,End=text.Length,DocumentEnd=text.Length,WordSaved=true});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="text",Start=0,OperationMessage=text});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="xml",Start=0,OperationMessage=xml});Send(new(){Kind="chapter-end",SnapshotId=read.Id});}
|
|
Frames(command!);await Until(()=>handler.Validations>0);await Until(()=>handler.Finishes>0);
|
|
Check(handler.Bodies.All(b=>JsonSerializer.Deserialize<ChapterObservation>(b,new JsonSerializerOptions(JsonSerializerDefaults.Web))!.Paragraphs.All(p=>p.Text==null)),"Unchanged chapter uploads hashes and native identity evidence, not manuscript prose");
|
|
Check(!handler.Paths.Any(p=>p.Contains("manuscript-capture")),"Chapter lifecycle does not invoke the full manuscript capture endpoint");
|
|
var before=handler.Validations;for(int n=0;n<100;n++){var response=Send(new(){Kind="selection",Start=12,End=12,WordSaved=true});Check(response.Command?.Kind!="navigate","Passive selection never returns a navigation command");}await Task.Delay(650);Check(handler.Validations==before,"Repeated cursor events reuse accepted current-session chapter validation");
|
|
Check(tray.Documents.Single().Status.Contains("accepted"),"Chapter completion is reported only after server acceptance");
|
|
var chunkReply=Send(new(){Kind="chapter-chunk",SnapshotId=Guid.NewGuid(),Action="xml",Start=0,OperationMessage="late"});Check(!chunkReply.ChapterStatusProvided,"Chapter chunks do not schedule repeated ribbon updates or invalidate Word during extraction");
|
|
Frames(command!);await Task.Delay(100);Check(handler.Validations==before,"Delayed duplicate chapter frames cannot resubmit an accepted operation");
|
|
var oldSession=session;session=Guid.NewGuid();Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Second synthetic document.docx"}]});tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=0,End=0,WordSaved=true});
|
|
AdapterCommand? second=null;for(int n=0;n<200&&second==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")second=pending;await Task.Delay(20);}
|
|
Check(second?.Kind=="chapter-check"&&second.SessionId==session,"A second Word document has independent chapter work and cannot inherit the first session's trust");
|
|
Send(new(){Kind="close"});Frames(second!);await Task.Delay(100);Check(handler.Validations==before,"Closing a document rejects late extraction frames and preserves already accepted chapters");session=oldSession;
|
|
var wrong=new Message{Kind="chapter-chunk",SnapshotId=command!.Id,Action="xml",Start=0,OperationMessage="wrong"};var legacySessions=new SessionManager();legacySessions.Attach(instance,lease);long legacySequence=0;Message Legacy(Message m){m.WordInstanceId=instance;m.SessionId=session;m.Sequence=++legacySequence;m.Revision=1;return legacySessions.Apply(lease,m);}Legacy(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Legacy"}]});Check(Legacy(wrong).Status=="invalid-chapter-frame","Chapter frames require negotiated native capability; legacy clients remain isolated");
|
|
}finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}}
|
|
}
|
|
private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);}
|
|
private static async Task Until(Func<bool> condition){for(int i=0;i<300;i++){if(condition())return;await Task.Delay(30);}throw new Exception("Chapter test timed out");}
|
|
private sealed class Handler:HttpMessageHandler
|
|
{
|
|
public Guid Manuscript;public int Validations,Finishes;public List<string> Bodies=[];public List<string> Paths=[];
|
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancel)
|
|
{
|
|
var path=request.RequestUri!.AbsolutePath;Paths.Add(path);HttpResponseMessage Json(object value)=>new(HttpStatusCode.OK){Content=JsonContent.Create(value)};
|
|
if(path.EndsWith("/pair"))return Json(new{code="00112233445566778899AABB"});if(path.EndsWith("/token"))return Json(new{accessToken="fixture"});if(path.EndsWith("/books"))return Json(new[]{new{bookId=3,title="Synthetic book"}});if(path.EndsWith("/connection"))return Json(new{state="Connected",authentication="verified",server="online",expiresUtc=DateTime.UtcNow.AddHours(4)});
|
|
if(path.EndsWith("/presence")){var value=await request.Content!.ReadFromJsonAsync<NativePresence>(cancel);value!.ChapterSyncSupported=true;value.ParagraphRevision=1;return Json(value);}
|
|
if(path.EndsWith("/chapter-sync"))return Json(new ChapterManifest{BookId=3,ManuscriptId=Manuscript,Revision=1,Chapters=[new(){ChapterId=10,HeadingNativeId="00000001",ContentHash=ChapterFingerprint.Content(["Chapter 1\r","Exact prose\r"]),Start=0,End=22,ParagraphCount=2}]});
|
|
if(path.EndsWith("/validate")){var body=await request.Content!.ReadAsStringAsync(cancel);Bodies.Add(body);Validations++;return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",ChapterId=10,Revision=1,Message="Chapter accepted."});}
|
|
if(path.EndsWith("/finish")){Finishes++;return Json(new ChapterSyncProgress{Total=1,Checked=1,Matching=1,State="Synchronised",Message="All chapters accepted."});}
|
|
return Json(new{});
|
|
}
|
|
}
|
|
}
|