87 lines
9.9 KiB
C#

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<bool,string> 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 incompatibleName="pd-incompatible-"+Guid.NewGuid().ToString("N");
using(var incompatible=new System.IO.Pipes.NamedPipeServerStream(incompatibleName,System.IO.Pipes.PipeDirection.InOut,1,System.IO.Pipes.PipeTransmissionMode.Byte,System.IO.Pipes.PipeOptions.Asynchronous|System.IO.Pipes.PipeOptions.CurrentUserOnly))
using(var link=new PlotDirector.Companion.Client.AgentLink(incompatibleName,Guid.NewGuid(),_=>true))
{
var offline=0;link.StateChanged+=s=>{if(s=="offline")Interlocked.Exchange(ref offline,1);};link.Start();await incompatible.WaitForConnectionAsync();
var hello=await FrameCodec.ReadAsync(incompatible,CancellationToken.None);await FrameCodec.WriteAsync(incompatible,new(){CorrelationId=hello.CorrelationId,Status="unsupported-version"},CancellationToken.None);
await Wait(()=>Volatile.Read(ref offline)==1);check(!link.Completion.IsCompleted,"incompatible agent handshake enters recovery instead of killing the client worker");
link.Dispose();await link.Completion.WaitAsync(TimeSpan.FromSeconds(5));
}
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");
var approvedContext=cloud.Status().AuthenticationContext;
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,AuthenticationContext=approvedContext,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");
using(var frame=new MemoryStream())
{
var page=new AiChapterResult{State="complete",Scenes=Enumerable.Range(0,40).Select(_=>new StructureSuggestion{Title=new string('界',200),Summary=new string('界',600),Reason=new string('界',600),ChapterTitle=new string('界',200),Origin="AI"}).ToArray()};
await FrameCodec.WriteAsync(frame,new Message{Ai=page},CancellationToken.None);check(frame.Length<=ProtocolVersion.MaxFrameBytes+4,"worst-case bounded AI page fits IPC framing");frame.Position=0;
check((await FrameCodec.ReadAsync(frame,CancellationToken.None)).Ai?.Scenes.Length==40,"AI result contract round-trips on actual frame codec");
}
id=Guid.NewGuid();Send("ai-begin");Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="One chapter paragraph.",CompletesParagraph=true});Send("ai-submit");await Wait(()=>Send("ai-status").Ai?.State=="complete");
check(handler.Submissions==1,"unchanged chapter uses agent content fingerprint without another prose upload");
var previous=id;id=Guid.NewGuid();Send("ai-begin");
check(jobs.Handle(descriptor,new(){Kind="ai-cancel",SnapshotId=previous},new(){Status="ok"}).Status=="obsolete-ai-request"&&Send("ai-status").Ai?.State=="reading","late cancellation cannot retire a replacement AI chapter");
Send("ai-cancel");
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");
handler.Deny=false;handler.Malformed=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?.State=="failed","malformed AI fields fail safely instead of leaving a chapter spinning");
var consent=new PlotDirector.Companion.Client.AiConsent{SessionId=descriptor.SessionId,SnapshotId=Guid.NewGuid(),AuthenticationContext=approvedContext,BookId=11};
check(consent.Matches(descriptor.SessionId,consent.SnapshotId,approvedContext)&&!consent.Matches(Guid.NewGuid(),consent.SnapshotId,approvedContext)&&!consent.Matches(descriptor.SessionId,consent.SnapshotId,Guid.NewGuid()),"upload consent pins document snapshot and authentication context");
id=Guid.NewGuid();Send("ai-begin");Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="Consented text.",CompletesParagraph=true});var submissionsBeforeSwitch=handler.Submissions;
cloud.SignOut();check(Send("ai-submit").Status=="authentication-changed"&&handler.Submissions==submissionsBeforeSwitch,"account/site change refuses old consent before any chapter HTTP upload");
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<bool> 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,Malformed;
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
{
var path=request.RequestUri!.AbsolutePath;
if(path.EndsWith("/connection"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow,ExpiresUtc=DateTime.UtcNow.AddHours(4)})};
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<AiChapterRequest>(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=Malformed?null!:"Narrative interpretation",Reason="A change in narrative focus."}]})};
}
}
}