68 lines
6.9 KiB
C#
68 lines
6.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 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");
|
|
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,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),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");
|
|
}
|
|
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");
|
|
cloud.SignOut();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;
|
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
|
|
{
|
|
var path=request.RequestUri!.AbsolutePath;
|
|
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="Narrative interpretation",Reason="A change in narrative focus."}]})};
|
|
}
|
|
}
|
|
}
|