PlotDirector/PlotLine.Tests/NativeWorkflowTests.cs

52 lines
5.4 KiB
C#

using System.Reflection;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PlotDirector.Companion.Protocol;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.NativeCompanion;
using PlotLine.ViewModels;
using ImportPreview=PlotDirector.Companion.Protocol.ImportPreview;
internal static class NativeWorkflowTests
{
internal static T Proxy<T>(Func<string,object?[]?,object?> handler)where T:class{var item=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)item).Handler=handler;return item;}
public static ImportPreviewRequest Selection()=>new(){BookId=3,SessionId=Guid.NewGuid(),SnapshotId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Items=[new(){Kind="Chapter",Title="Second",Start=100,End=200},new(){Kind="Scene",Title="Last",Start=150,End=200,Origin="AI"},new(){Kind="Scene",Title="First",Start=100,End=150,Origin="Existing marker"}]};
public static async Task Run()
{
void Check(bool value,string message){if(!value)throw new Exception(message);}
var input=Selection();var plan=NativeImportPreview.Build(input,1);
Check(WordCompanionService.ValidImportStructure(plan)&&plan.Chapters[0].Scenes[0].Title=="First"&&plan.Chapters[0].Scenes[1].SortOrder==2&&!plan.ReplacePlanned,"Preview reuses existing importer validation and source-position ordering without replacement");
void Refuse(ImportPreviewRequest request){try{NativeImportPreview.Build(request,1);throw new Exception("Unsafe preview accepted");}catch(ArgumentException){}}
var duplicate=Selection();duplicate.Items=[..duplicate.Items,duplicate.Items[1]];Refuse(duplicate);
var overlap=Selection();overlap.Items[2].End=190;Refuse(overlap);
var backwards=Selection();backwards.Items[1].End=149;Refuse(backwards);
var orphan=Selection();orphan.Items=orphan.Items.Where(i=>i.Kind=="Scene").ToArray();Refuse(orphan);
var empty=Selection();empty.Items=[empty.Items[0]];Refuse(empty);
var linked=0;var planned=false;var allow=true;var calls=0;
var access=Proxy<IWordCompanionRepository>((name,args)=>{
if(name!="GetBookStructureAsync")throw new Exception("Unexpected access/write: "+name);
Check((int)args![1]! ==7,"Authenticated subject owns access check");return Task.FromResult((int)args[0]! ==3?new WordCompanionBookStructureResponse{BookId=3,Chapters=[new(){ChapterId=10,Title="Saved chapter",Scenes=[new(){SceneId=20,Title="Saved scene"}]}]}:null);
});
var books=Proxy<IBookRepository>((n,a)=>n=="GetAsync"?Task.FromResult<Book?>(new(){BookID=3,ProjectID=1,BookTitle="Saved book",Description="Saved book description"}):throw new Exception(n));
var companion=Proxy<IWordCompanionService>((n,a)=>{
if(n!="AnalyseManuscriptAsync")throw new Exception("Native preview attempted an import/write: "+n);calls++;
return Task.FromResult<WordCompanionManuscriptAnalyseResponse?>(new(){CanImport=linked==0,LinkedChapterCount=linked,RequiresReplaceConfirmation=planned,ExistingChapterCount=linked+ (planned?1:0),Message="Existing import eligibility check"});
});
var context=Proxy<IStoryContextService>((n,a)=>Task.FromResult<StoryContextViewModel?>(new(){Position=new(1,3,10,20),Scene=new(){SceneID=20,SceneTitle="Saved scene",Summary="Saved context, not AI",ScenePurposeNotes="Saved scene intent"}}));
var writer=Proxy<IWriterWorkspaceService>((n,a)=>Task.FromResult<ChapterWorkflowViewModel?>(new(){Project=new(){ProjectID=1},Book=new(){BookID=3,ProjectID=1},Chapter=new(){ChapterID=10,BookID=3,Summary="Saved chapter summary"},Goal=new(){GoalSummary="Saved chapter goal"}}));
var subscriptions=Proxy<ISubscriptionService>((n,a)=>Task.FromResult(new EntitlementDecision{Allowed=allow}));
var api=new NativeCompanionWorkflowController(access,books,companion,context,writer,new FakeStoryIntelligenceClient(""),subscriptions){ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],DesktopPairing.Scheme))}}};
var saved=(SavedWorkspace)((OkObjectResult)await api.Workspace(3,10,20)).Value!;
Check(saved.Context=="Saved context, not AI"&&saved.Intent.Contains("Saved chapter goal")&&saved.ContextPath.Contains("pinned=true"),"Context/Intent reuse saved scene and chapter objective with pinned browser navigation");
Check(await api.Workspace(3,999,20) is NotFoundResult&&await api.Workspace(99,null,null) is ForbidResult,"Foreign book and mismatched marker cannot display saved context");
var result=(ImportPreview)((OkObjectResult)await api.Preview(input)).Value!;Check(!result.CommitAvailable&&result.State=="validated-preview"&&calls==1,"Validated preview never commits or creates canonical records");
linked=1;result=(ImportPreview)((OkObjectResult)await api.Preview(input)).Value!;Check(result.State=="already-linked","Duplicate manuscript import is blocked by existing linked state");
linked=0;planned=true;result=(ImportPreview)((OkObjectResult)await api.Preview(input)).Value!;Check(result.State=="existing-content"&&!result.CommitAvailable,"Planned content is never silently replaced");
allow=false;var before=calls;Check(await api.Preview(input) is ForbidResult&&before==calls,"Import entitlement denies before preview service call");
}
}