Fix native import scene parsing, resumable analysis and live book association
This commit is contained in:
parent
25c75ad6cd
commit
a0cee0d1f0
@ -35,7 +35,7 @@ public sealed partial class CloudGateway
|
||||
public async Task RunConnectionLoop(CancellationToken cancellation)
|
||||
{
|
||||
using var stop=CancellationTokenSource.CreateLinkedTokenSource(cancellation,lifetime.Token);
|
||||
try{while(!stop.IsCancellationRequested){try{await DrainRevocations();bool approved;lock(gate)approved=saved.Active!=null;if(approved&&Now>=retryAfter){await EnsureAccess(authenticationContext);if(health.State!="Connected"||Now.UtcDateTime>=nextCheck)await CheckConnection();else if(health.State=="Connected"&&Now.UtcDateTime-health.VerifiedUtc>=TimeSpan.FromSeconds(25))await Post<HeartbeatReply>("api/native-companion/heartbeat",new{},authenticationContext);}}catch(Exception e)when(AuthFailure(e)){ConnectionFailure(e);}await Task.Delay(TimeSpan.FromSeconds(2),stop.Token);}}
|
||||
try{while(!stop.IsCancellationRequested){try{await DrainRevocations();bool approved;lock(gate)approved=saved.Active!=null;if(approved&&Now>=retryAfter){await EnsureAccess(authenticationContext);if(health.State!="Connected"||Now.UtcDateTime>=nextCheck)await CheckConnection();else if(health.State=="Connected"&&Now.UtcDateTime-health.VerifiedUtc>=TimeSpan.FromSeconds(25)){var context=authenticationContext;var beat=await Post<HeartbeatReply>("api/native-companion/heartbeat",new{},context);await ObserveCatalog(beat.CatalogVersion,context);}}}catch(Exception e)when(AuthFailure(e)){ConnectionFailure(e);}await Task.Delay(TimeSpan.FromSeconds(2),stop.Token);}}
|
||||
catch(OperationCanceledException)when(stop.IsCancellationRequested){}
|
||||
}
|
||||
public async Task ReconnectAsync(){if(storageUnavailable)RestoreState();lock(gate){retryAfter=DateTimeOffset.MinValue;nextCheck=DateTime.MinValue;}try{await EnsureAccess(authenticationContext);await CheckConnection();}catch(Exception e)when(AuthFailure(e)){ConnectionFailure(e);}}
|
||||
@ -88,5 +88,5 @@ public sealed partial class CloudGateway
|
||||
public void ChangeAccount(string address){ValidateOrigin(address);_=CompleteAccountChange(SignOutAsync(),address);}
|
||||
private async Task CompleteAccountChange(Task signout,string address){try{await signout;Connect(address,true);}catch(Exception e)when(AuthFailure(e)){lock(gate){health.State="Action required";health.Explanation="Could not safely change account. Check protected settings and retry.";}}}
|
||||
public async Task StopAsync(){try{Guid context;lock(gate)context=authenticationContext;if(token!=null&&saved.Active!=null){using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(origin!,"api/native-companion/disconnect"));request.Headers.Authorization=new("Bearer",token);using var stop=new CancellationTokenSource(TimeSpan.FromSeconds(3));using var response=await http.SendAsync(request,stop.Token);}else DisconnectPresence();}catch(Exception e)when(AuthFailure(e)){}try{await FlushSettingsAsync();}catch(Exception e)when(StorageFailure(e)){ConnectionFailure(e);}}
|
||||
private sealed record HeartbeatReply(bool Connected);
|
||||
private sealed record HeartbeatReply(bool Connected,Guid CatalogVersion);
|
||||
}
|
||||
|
||||
@ -21,7 +21,7 @@ public sealed partial class CloudGateway : IDisposable
|
||||
private Guid authenticationContext=Guid.NewGuid();
|
||||
private string state="Not signed in";
|
||||
private ConnectionHealth health=new();
|
||||
private int checking;private DateTime nextCheck;
|
||||
private Task connectionCheck=Task.CompletedTask;private Guid catalogVersion;private int checking;private DateTime nextCheck;
|
||||
private readonly Dictionary<string,AiChapterResult> successful=[];
|
||||
private CompanionBook[] books=[];
|
||||
private readonly string? settingsPath;
|
||||
@ -44,11 +44,12 @@ public sealed partial class CloudGateway : IDisposable
|
||||
}
|
||||
private ConnectionHealth CopyHealth()=>new(){State=health.State,AccountName=health.AccountName,Server=health.Server,Authentication=health.Authentication,Ai=health.Ai,Explanation=health.Explanation,VerifiedUtc=health.VerifiedUtc,ExpiresUtc=health.ExpiresUtc};
|
||||
private void Expire(){if(token!=null&&health.ExpiresUtc!=default&&Now.UtcDateTime>=health.ExpiresUtc){InvalidateAccess(authenticationContext);health.Ai="unknown";}}
|
||||
public async Task CheckConnection()
|
||||
public Task CheckConnection(){lock(gate){if(!connectionCheck.IsCompleted)return connectionCheck;return connectionCheck=CheckConnectionCore();}}
|
||||
private async Task CheckConnectionCore()
|
||||
{
|
||||
if(Interlocked.Exchange(ref checking,1)!=0)return;
|
||||
Guid context;lock(gate){context=authenticationContext;nextCheck=Now.UtcDateTime.AddMinutes(2);health.Server="checking";}
|
||||
try{var result=await Get<ConnectionHealth>("api/native-companion/connection",context);var accessible=await Get<CompanionBook[]>("api/native-companion/books",context);lock(gate)if(authenticationContext==context){books=accessible.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).ToArray();result.VerifiedUtc=Now.UtcDateTime;result.State="Connected";result.AccountName=saved.AccountName;health=result;state="Signed in (verified)";retryFailures=0;retryAfter=DateTimeOffset.MinValue;}}
|
||||
try{var result=await Get<ConnectionHealth>("api/native-companion/connection",context);var accessible=await Get<CompanionBook[]>("api/native-companion/books",context);lock(gate)if(authenticationContext==context){books=accessible.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(500).ToArray();result.VerifiedUtc=Now.UtcDateTime;result.State="Connected";result.AccountName=saved.AccountName;health=result;state="Signed in (verified)";retryFailures=0;retryAfter=DateTimeOffset.MinValue;}}
|
||||
catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException){lock(gate)if(authenticationContext==context){health.Server=token==null?"unknown":"offline";health.State=saved.Active!=null?"Reconnecting":"Action required";health.Explanation=saved.Active!=null?"Server unavailable. Reconnecting automatically; Word remains available.":"Sign in or check the server address.";if(e is CompanionStorageException)ConnectionFailure(e);else if(saved.Active!=null)TransientFailure();}}
|
||||
finally{Volatile.Write(ref checking,0);}
|
||||
}
|
||||
@ -86,7 +87,7 @@ public sealed partial class CloudGateway : IDisposable
|
||||
using var request=new HttpRequestMessage(HttpMethod.Get,new Uri(uri,"api/native-companion/books"));request.Headers.Authorization=new("Bearer",grant.AccessToken);
|
||||
using var list=await http.SendAsync(request,stop.Token);list.EnsureSuccessStatusCode();
|
||||
var available=await list.Content.ReadFromJsonAsync<CompanionBook[]>(Json,stop.Token)??[];
|
||||
lock(gate)if(pairing==stop&&!stop.IsCancellationRequested){token=grant.AccessToken;books=available.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).Select(b=>new CompanionBook{BookId=b.BookId,Title=b.Title.Length>160?b.Title[..160]:b.Title}).ToArray();state="Signed in (four-hour grant)";health=new(){State="Connected",Server="online",Authentication="verified",VerifiedUtc=Now.UtcDateTime,ExpiresUtc=Now.UtcDateTime.AddHours(4),Ai="unknown",Explanation="Book list verified; checking AI configuration."};nextCheck=DateTime.MinValue;}
|
||||
lock(gate)if(pairing==stop&&!stop.IsCancellationRequested){token=grant.AccessToken;books=available.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(500).Select(b=>new CompanionBook{BookId=b.BookId,Title=b.Title.Length>160?b.Title[..160]:b.Title}).ToArray();state="Signed in (four-hour grant)";health=new(){State="Connected",Server="online",Authentication="verified",VerifiedUtc=Now.UtcDateTime,ExpiresUtc=Now.UtcDateTime.AddHours(4),Ai="unknown",Explanation="Book list verified; checking AI configuration."};nextCheck=DateTime.MinValue;}
|
||||
return;
|
||||
}
|
||||
}
|
||||
@ -156,7 +157,8 @@ public sealed partial class CloudGateway : IDisposable
|
||||
private void DisconnectPresence(){Uri? site;string? access;lock(gate){site=origin;access=token;}if(site==null||access==null)return;_ = Task.Run(async()=>{try{using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(5));using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/presence/disconnect"));request.Headers.Authorization=new("Bearer",access);using var response=await http.SendAsync(request,timeout.Token);}catch(Exception e)when(e is HttpRequestException or OperationCanceledException or ObjectDisposedException) {}});}
|
||||
public void OpenCompanionPage(string path,Guid context)
|
||||
{lock(gate){Expire();if(context!=authenticationContext||token==null||origin==null)throw new InvalidOperationException("Sign in first.");if(!path.StartsWith("/native-companion/",StringComparison.Ordinal))throw new InvalidDataException();var url=new Uri(origin,path);if(url.GetLeftPart(UriPartial.Authority)!=origin.GetLeftPart(UriPartial.Authority))throw new InvalidDataException();openBrowser(url.AbsoluteUri);}}
|
||||
public async Task<NativePresence> Presence(Guid instance,Guid session,NativePresence presence,Guid context)=>await Post<NativePresence>($"api/native-companion/instances/{instance}/documents/{session}/presence",presence,context);
|
||||
public async Task<NativePresence> Presence(Guid instance,Guid session,NativePresence presence,Guid context){var reply=await Post<NativePresence>($"api/native-companion/instances/{instance}/documents/{session}/presence",presence,context);await ObserveCatalog(reply.CatalogVersion,context);return reply;}
|
||||
private async Task ObserveCatalog(Guid version,Guid context){if(version==Guid.Empty)return;Task running;lock(gate){if(context!=authenticationContext||catalogVersion==version)return;catalogVersion=version;running=connectionCheck;}await running;lock(gate)if(context!=authenticationContext)return;await CheckConnection();}
|
||||
public async Task RemovePresence(Guid instance,Guid session,long? throughSequence=null){Guid context;lock(gate)context=authenticationContext;try{await Send<NativePresence>(HttpMethod.Delete,$"api/native-companion/instances/{instance}/documents/{session}/presence?throughSequence={throughSequence}",null,context);}catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException or ObjectDisposedException){}}
|
||||
public async Task CancelRemote(Guid id)
|
||||
{
|
||||
|
||||
@ -28,7 +28,7 @@ internal sealed class CompanionWindow:Form
|
||||
{
|
||||
private readonly TrayCoordinator control;private readonly CloudGateway cloud;private readonly CancellationTokenSource shutdown;private readonly string directory;
|
||||
private readonly Icon brand=CreateBrandIcon();private readonly NotifyIcon tray;private readonly System.Windows.Forms.Timer timer=new(){Interval=750};
|
||||
private readonly ToolTip tips=new();private bool exiting,refreshing,advanced;private Guid selected,lastActive;private TrayDocument[] displayed=[];private string docsKey="",error="";
|
||||
private readonly ToolTip tips=new();private bool exiting,refreshing,advanced,choosingBook;private Guid selected,lastActive;private TrayDocument[] displayed=[];private string docsKey="",error="";
|
||||
private readonly ComboBox documents=new(){DropDownStyle=ComboBoxStyle.DropDownList,Dock=DockStyle.Top,AccessibleName="Word manuscript"};
|
||||
private readonly ComboBox books=new(){DropDownStyle=ComboBoxStyle.DropDownList,Dock=DockStyle.Top,DisplayMember="Title",AccessibleName="PlotDirector book",DropDownWidth=620};
|
||||
private readonly Label serverStatus=Label(),wordStatus=Label(),account=Label(),bookTitle=Label(),projectTitle=Label(),guidance=Label(),notice=Label();
|
||||
@ -66,14 +66,20 @@ internal sealed class CompanionWindow:Form
|
||||
private void Safe(Action action){try{error="";action();}catch(Exception e)when(e is InvalidOperationException or ArgumentException or IOException or System.ComponentModel.Win32Exception){error=e.Message;}if(dialogNotice is {IsDisposed:false})SetText(dialogNotice,error);RefreshState();}
|
||||
private void SavePreferences(){var size=WindowState==FormWindowState.Normal?Size:RestoreBounds.Size;var prefs=cloud.Preferences;prefs.Width=size.Width;prefs.Height=size.Height;prefs.AdvancedMode=advanced;prefs.LastManuscript=Current?.Manuscript??prefs.LastManuscript;cloud.SavePreferences(prefs);}
|
||||
public void Reveal(){Show();WindowState=FormWindowState.Normal;Activate();}
|
||||
private void ChangeBook()
|
||||
private async void ChangeBook()
|
||||
{
|
||||
if(choosingBook)return;choosingBook=true;
|
||||
try{
|
||||
if(Current==null){error="Open a manuscript in Word before choosing a book.";return;}
|
||||
var session=selected;using var dialog=new Form{Text="Choose a PlotDirector book",Icon=brand,Font=Font,AutoScaleMode=AutoScaleMode.Dpi,MinimumSize=new(440,260),Size=new(540,300),StartPosition=FormStartPosition.CenterParent};
|
||||
var stack=Stack(20);dialogNotice=Label();stack.Controls.Add(Label("Associate this manuscript with a book in your account. Manuscript text is not sent or changed."));books.DataSource=cloud.Status().Books;books.SelectedItem=cloud.Status().Books.FirstOrDefault(b=>b.BookId==Current.Book);stack.Controls.Add(books);
|
||||
var session=selected;await cloud.CheckConnection();if(IsDisposed)return;
|
||||
var current=control.PresentationDocuments.FirstOrDefault(d=>d.Session==session);if(current==null)throw new InvalidOperationException("That Word document closed while books were refreshing.");
|
||||
using var dialog=new Form{Text="Choose a PlotDirector book",Icon=brand,Font=Font,AutoScaleMode=AutoScaleMode.Dpi,MinimumSize=new(440,260),Size=new(540,300),StartPosition=FormStartPosition.CenterParent};
|
||||
var stack=Stack(20);dialogNotice=Label();stack.Controls.Add(Label("Associate this manuscript with a book in your account. Manuscript text is not sent or changed."));books.DataSource=cloud.Status().Books;books.SelectedItem=cloud.Status().Books.FirstOrDefault(b=>b.BookId==current.Book);stack.Controls.Add(books);
|
||||
var remember=new CheckBox{Text="Also remember in Word metadata (save Word normally)",AutoSize=true,Checked=cloud.Preferences.RememberInDocument};stack.Controls.Add(remember);
|
||||
stack.Controls.Add(Button("Use this book",()=>{if(books.SelectedItem is not Protocol.CompanionBook book)throw new InvalidOperationException("Sign in and choose an available book.");if(!control.Documents.Any(d=>d.Session==session))throw new InvalidOperationException("That Word document is no longer connected.");control.SelectBook(session,book.BookId,remember.Checked);var prefs=cloud.Preferences;prefs.RememberInDocument=remember.Checked;cloud.SavePreferences(prefs);dialog.Close();}));
|
||||
stack.Controls.Add(dialogNotice);dialog.Controls.Add(stack);PaintTheme(dialog);dialog.ShowDialog(this);stack.Controls.Remove(books);dialogNotice=null;
|
||||
}catch(Exception e)when(e is InvalidOperationException or ArgumentException or IOException or System.ComponentModel.Win32Exception){if(!IsDisposed){error=e.Message;RefreshState();}}
|
||||
finally{choosingBook=false;}
|
||||
}
|
||||
private void ShowSettings()
|
||||
{
|
||||
@ -115,6 +121,7 @@ internal sealed class CompanionWindow:Form
|
||||
var noticeText=error!=""?error:doc?.AssociationNotice??"";SetText(notice,noticeText);if(settingsNotice is {IsDisposed:false}){SetText(settingsNotice,error);settingsNotice.Visible=error!="";}notice.Visible=noticeText!="";tips.SetToolTip(serverStatus,state.Health?.Explanation??"Connect in Settings.");
|
||||
var text=$"Server: {state.ServerUrl}\r\nAccount: {state.Health?.AccountName}\r\n{state.Health?.Explanation}\r\n"+string.Join("\r\n",displayed.Select(d=>$"{d.Title} · session {d.Session} · book {d.Book}"))+"\r\n"+doc?.WordDiagnostics+"\r\n"+doc?.Status+"\r\n"+doc?.MaintenanceReport;
|
||||
if(diagnostics is {IsDisposed:false}&&diagnostics.Text!=text)diagnostics.Text=text;
|
||||
if(books.Parent!=null&&!books.IsDisposed){var signature=state.AuthenticationContext+":"+string.Join("|",state.Books.Select(b=>b.BookId+":"+b.Title));if(books.Tag as string!=signature){var chosen=(books.SelectedItem as Protocol.CompanionBook)?.BookId;books.Tag=signature;books.DataSource=state.Books;books.SelectedItem=state.Books.FirstOrDefault(b=>b.BookId==chosen);}}
|
||||
var next=state.AuthenticationContext+":"+(book?.BookId??0);if(next!=coverKey){coverKey=next;coverRetry=DateTime.MinValue;coverStop?.Cancel();cover.SetImage(null);cover.Caption=bookTitle.Text;cover.Invalidate();coverLoading=false;}
|
||||
if(book!=null&&!coverLoading&&DateTime.UtcNow>=coverRetry&&state.Health?.State=="Connected")_ = LoadCover(book.BookId,state.AuthenticationContext,next);
|
||||
var trayText="PlotDirector · "+(state.Health?.State??"Disconnected");if(tray.Text!=trayText)tray.Text=trayText.Length>63?trayText[..63]:trayText;
|
||||
|
||||
@ -115,9 +115,11 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
public void OpenPage(Guid session,string page){lock(gate){if(!documents.TryGetValue(session,out var doc)||!cloud.Allows(doc.Authentication,doc.Book))throw new InvalidOperationException("Select an authorised book first.");cloud.OpenCompanionPage(page=="review"&&!string.IsNullOrEmpty(doc.ReviewPath)?doc.ReviewPath:$"/native-companion/workspace?bookId={doc.Book}&instanceId={doc.Instance}&sessionId={doc.Session}&view={page}",doc.Authentication);}}
|
||||
public async Task Heartbeat(CancellationToken cancellation)
|
||||
{
|
||||
while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromMilliseconds(500),cancellation);var available=Documents.Where(d=>d.Book>0).ToArray();
|
||||
foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))continue;var key=$"{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{(doc.SceneId.HasValue?0:doc.Cursor)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,CanCapture=captureInstances.Contains(doc.Instance),WordSaved=doc.WordSaved,CursorStart=doc.Cursor,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision){if(reply.Navigation.Kind=="wizard-capture"&&captureInstances.Contains(doc.Instance)){if(uploading!=0||documents.Values.Any(d=>d.Capture!=null)){_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);continue;}Cancel(doc);doc.Capture=new(){RequestId=reply.Navigation.Id,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,Revision=doc.Revision};doc.CaptureFragments.Clear();doc.Status="Reading manuscript for the PlotDirector import wizard…";Queue(doc,reply.Navigation);}else if(reply.Navigation.Kind=="navigate")Queue(doc,reply.Navigation);}}catch(Exception e)when(NetworkFailure(e)) {doc.Status=e.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.UtcNow;}}
|
||||
if(available.Length==0&&lastBook>0&&DateTime.UtcNow-lastAgentPresence>=TimeSpan.FromSeconds(15)){lastAgentPresence=DateTime.UtcNow;agentOnlyPublished=true;try{await cloud.Presence(agentInstance,agentSession,new(){BookId=lastBook,Sequence=Interlocked.Increment(ref agentSequence),WordAvailable=false,DocumentTitle="No Word document"},lastAuthentication);}catch(Exception e)when(NetworkFailure(e)) {}}
|
||||
while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromMilliseconds(500),cancellation);var available=Documents.Where(d=>d.Authentication==cloud.Status().AuthenticationContext&&cloud.Status().Health?.Authentication=="verified").ToArray();
|
||||
foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))continue;var key=$"{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{(doc.SceneId.HasValue?0:doc.Cursor)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,CanCapture=captureInstances.Contains(doc.Instance),WordRunning=true,WordSaved=doc.WordSaved,CursorStart=doc.Cursor,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;
|
||||
if(reply.Navigation is {Kind:"wizard-capture",BookId:>0} requested&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Book==0){await cloud.CheckConnection();lock(gate){if(doc.Book==0&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext&&cloud.Allows(doc.Authentication,requested.BookId)&&documents.GetValueOrDefault(doc.Session)==doc){doc.Book=requested.BookId;cloud.RememberBinding(doc.Manuscript,doc.Book,doc.Authentication);doc.LastPresenceKey="";}}}
|
||||
if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision){if(reply.Navigation.Kind=="wizard-capture"&&captureInstances.Contains(doc.Instance)&&(reply.Navigation.BookId==0||reply.Navigation.BookId==doc.Book)&&cloud.Allows(doc.Authentication,doc.Book)){if(uploading!=0||documents.Values.Any(d=>d.Capture!=null)){_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);continue;}Cancel(doc);doc.Capture=new(){RequestId=reply.Navigation.Id,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,Revision=doc.Revision};doc.CaptureFragments.Clear();doc.Status="Reading manuscript for the PlotDirector import wizard…";Queue(doc,reply.Navigation);}else if(reply.Navigation.Kind=="wizard-capture")_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);else if(reply.Navigation.Kind=="navigate")Queue(doc,reply.Navigation);}}catch(Exception e)when(NetworkFailure(e)) {doc.Status=e.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.UtcNow;}}
|
||||
if(available.Length==0&&cloud.Status().Health?.Authentication=="verified"&&DateTime.UtcNow-lastAgentPresence>=TimeSpan.FromSeconds(15)){lastAgentPresence=DateTime.UtcNow;agentOnlyPublished=true;try{await cloud.Presence(agentInstance,agentSession,new(){WordRunning=leases.Count>0,BookId=0,Sequence=Interlocked.Increment(ref agentSequence),WordAvailable=false,DocumentTitle="No Word document"},cloud.Status().AuthenticationContext);}catch(Exception e)when(NetworkFailure(e)) {}}
|
||||
else if(available.Length>0&&agentOnlyPublished){agentOnlyPublished=false;await cloud.RemovePresence(agentInstance,agentSession);}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1 +1 @@
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.16</ApplicationVersion></PropertyGroup></Project>
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.17</ApplicationVersion></PropertyGroup></Project>
|
||||
|
||||
@ -16,6 +16,7 @@ public sealed class AdapterCommand
|
||||
[DataContract]
|
||||
public sealed class NativePresence
|
||||
{
|
||||
[DataMember] public Guid CatalogVersion {get;set;}
|
||||
[DataMember] public Guid? CaptureRequestId {get;set;}
|
||||
[DataMember] public int CaptureProgress {get;set;}
|
||||
[DataMember] public bool CanCapture {get;set;}
|
||||
@ -29,6 +30,7 @@ public sealed class NativePresence
|
||||
[DataMember] public int? ChapterId {get;set;}
|
||||
[DataMember] public int? SceneId {get;set;}
|
||||
[DataMember] public bool Active {get;set;}
|
||||
[DataMember] public bool WordRunning {get;set;}
|
||||
[DataMember] public bool WordAvailable {get;set;}=true;
|
||||
[DataMember] public string DocumentTitle {get;set;}="";
|
||||
}
|
||||
|
||||
@ -0,0 +1,46 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using PlotDirector.Companion.Agent;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
internal static class NativeConnectionRefreshTests
|
||||
{
|
||||
public static async Task Run(Action<bool,string> check)
|
||||
{
|
||||
var server=new Server();var approvals=0;using var cloud=new CloudGateway(server,_=>approvals++);cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Books.Length==1);
|
||||
var context=cloud.Status().AuthenticationContext;var position=new NativePresence{BookId=0,WordRunning=true,ManuscriptId=Guid.NewGuid(),DocumentTitle="Unassociated manuscript",Sequence=1};
|
||||
await cloud.Presence(Guid.NewGuid(),Guid.NewGuid(),position,context);
|
||||
server.BlockNextBooks=new(TaskCreationOptions.RunContinuationsAsynchronously);var before=server.BookLoads;var inFlight=cloud.CheckConnection();await Until(()=>server.BookLoads>before);
|
||||
server.Created=true;server.Version=Guid.NewGuid();var changed=cloud.Presence(Guid.NewGuid(),Guid.NewGuid(),position,context);server.BlockNextBooks.SetResult();await inFlight;await changed;
|
||||
check(cloud.Status().Books.Any(b=>b.BookId==5)&&approvals==1,"new book invalidation during an in-flight check is not lost; existing presence refreshes without restart or approval");
|
||||
var loads=server.BookLoads;await cloud.Presence(Guid.NewGuid(),Guid.NewGuid(),position,context);check(server.BookLoads==loads,"unchanged catalogue does not trigger repeated book-list polling");
|
||||
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 doc=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Title="First manuscript",Revision=1};
|
||||
Message Apply(Message request){request.WordInstanceId=instance;request.Sequence=++sequence;return control.Exchange(instance,request,sessions.Apply(lease,request));}
|
||||
Apply(new(){Kind="document",Documents=[doc]});var local=control.Documents.Single();local.Authentication=context;
|
||||
using var stop=new CancellationTokenSource();var heartbeat=control.Heartbeat(stop.Token);
|
||||
try{
|
||||
await Until(()=>server.LastPresence?.ManuscriptId==doc.ManuscriptId);
|
||||
check(server.LastPresence!.BookId==0&&server.LastPresence.WordAvailable&&server.LastPresence.WordRunning&&server.Captures==0,"unassociated Word manuscript is visible without automatically uploading prose");
|
||||
server.Command=new(){Kind="wizard-capture",SessionId=doc.SessionId,Revision=1,BookId=5};control.RefreshPresence(doc.SessionId);
|
||||
await Until(()=>control.Documents.Single().Capture!=null);
|
||||
check(local.Book==5&&local.Capture!.SessionId==doc.SessionId&&server.Captures==0,"explicit wizard request associates a new authorised book and queues extraction for the exact existing session");
|
||||
}finally{stop.Cancel();try{await heartbeat;}catch(OperationCanceledException){}}
|
||||
}
|
||||
private static async Task Until(Func<bool> condition){using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(12));while(!condition())await Task.Delay(20,timeout.Token);}
|
||||
private sealed class Server:HttpMessageHandler
|
||||
{
|
||||
public TaskCompletionSource? BlockNextBooks;public bool Created;public Guid Version=Guid.NewGuid();public int BookLoads,Captures;public NativePresence? LastPresence;public AdapterCommand? Command;
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
|
||||
{
|
||||
var path=request.RequestUri!.AbsolutePath;object value;
|
||||
if(path.EndsWith("/presence")&&request.Method==HttpMethod.Post){LastPresence=await request.Content!.ReadFromJsonAsync<NativePresence>(cancellation);value=new NativePresence{CatalogVersion=Version,Navigation=Command};Command=null;}
|
||||
else if(path.EndsWith("/books")){BookLoads++;var block=BlockNextBooks;value=Created?new[]{new CompanionBook{BookId=3,Title="Existing"},new CompanionBook{BookId=5,Title="New"}}:[new CompanionBook{BookId=3,Title="Existing"}];if(block!=null){await block.Task.WaitAsync(cancellation);BlockNextBooks=null;}}
|
||||
else if(path.EndsWith("/pair"))value=new{code=new string('A',24)};
|
||||
else if(path.EndsWith("/token"))value=new{accessToken="fixture"};
|
||||
else if(path.EndsWith("/manuscript-capture")){Captures++;value=new NativePresence();}
|
||||
else value=new ConnectionHealth{State="Connected",Server="online",Authentication="verified",VerifiedUtc=DateTime.UtcNow};
|
||||
return new(HttpStatusCode.OK){Content=JsonContent.Create(value)};
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -181,5 +181,6 @@ await AnalysisTests.Run(Check);
|
||||
await ChapterAiTests.Run(Check);
|
||||
await WorkflowTests.Run(Check);
|
||||
await TrayTests.Run(Check);
|
||||
await NativeConnectionRefreshTests.Run(Check);
|
||||
await PersistentConnectionTests.Run(Check);
|
||||
Console.WriteLine($"Native foundation: {passed} checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified.");
|
||||
|
||||
@ -3,6 +3,6 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyTitle("PlotDirector Word Companion — Native development")]
|
||||
[assembly: AssemblyCompany("Nick Beckley")]
|
||||
[assembly: AssemblyProduct("PlotDirector")]
|
||||
[assembly: AssemblyVersion("1.0.0.16")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.16")]
|
||||
[assembly: AssemblyVersion("1.0.0.17")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.17")]
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
25
PlotLine.Tests/Browser/native-import-connection.cjs
Normal file
25
PlotLine.Tests/Browser/native-import-connection.cjs
Normal file
@ -0,0 +1,25 @@
|
||||
const {chromium}=require('playwright');const fs=require('node:fs');const path=require('node:path');const assert=require('node:assert/strict');
|
||||
(async()=>{const browser=await chromium.launch();try{
|
||||
const page=await browser.newPage();await page.goto('about:blank');await page.setContent(`<div data-word-companion-presence="true"><span data-word-companion-compact-status-label></span><p data-word-companion-connected-copy></p></div><section data-onboarding-scan-panel data-book-id="5" data-scan-status="NotStarted"><button data-onboarding-scan-start>Import manuscript</button></section>`);
|
||||
await page.evaluate(()=>{
|
||||
window.invocations=[];window.handlers={};
|
||||
window.signalR={HubConnectionBuilder:class{
|
||||
withUrl(){return this;}withAutomaticReconnect(){return this;}
|
||||
build(){return {on(name,handler){handlers[name]=handler;},onreconnecting(){},onreconnected(){},onclose(){},start:async()=>{},invoke:async(name)=>{invocations.push(name);return name==='WatchCompanionPresence'?{isConnected:false}:{status:'Running'};}};}
|
||||
}};
|
||||
});
|
||||
await page.addScriptTag({content:fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/word-companion-presence.js'),'utf8')});
|
||||
const label=page.locator('[data-word-companion-compact-status-label]'),button=page.locator('[data-onboarding-scan-start]');
|
||||
async function state(leases,connectionState='Connected'){await page.evaluate(({leases,connectionState})=>{leases.known=true;leases.connectionState=connectionState;window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases}));},{leases,connectionState});}
|
||||
await state([],'Disconnected');await assert.match(await label.textContent(),/disconnected/i);assert.equal(await button.isDisabled(),true);
|
||||
await state([]);assert.match(await label.textContent(),/authenticated.*Word unavailable/);assert.equal(await button.isDisabled(),true);
|
||||
await state([{wordAvailable:false,wordRunning:true}]);assert.match(await label.textContent(),/Word connected.*open a manuscript/);assert.equal(await button.isDisabled(),true);
|
||||
const manuscript={bookId:0,wordAvailable:true,wordRunning:true,canCapture:true,active:true,documentTitle:'Title <script>not HTML</script>',expires:new Date(Date.now()+45000).toISOString()};
|
||||
await state([manuscript]);assert.match(await label.textContent(),/not yet associated/);assert.equal(await button.isDisabled(),false,'first-time import must not deadlock on missing association');assert.match(await page.locator('[data-word-companion-connected-copy]').textContent(),/only after your request/);assert.equal(await page.locator('script:not([src])').count(),1,'filename must not inject script markup');
|
||||
await state([{...manuscript,bookId:5}]);assert.match(await label.textContent(),/ready to import/);assert.equal(await button.isDisabled(),false);
|
||||
await state([{...manuscript,bookId:7}]);assert.match(await label.textContent(),/another book/);assert.equal(await button.isDisabled(),true);
|
||||
await state([{...manuscript,expires:new Date(Date.now()-1000).toISOString()}]);assert.equal(await button.isDisabled(),true,'stale document cannot enable import');
|
||||
await page.evaluate(()=>handlers.WordCompanionPresenceChanged({isConnected:true,documentOpen:true,currentDocumentName:'Legacy Word'}));assert.equal(await button.isDisabled(),false,'connected Office.js workflow remains available when native manuscript is stale');await page.evaluate(()=>handlers.WordCompanionPresenceChanged({isConnected:false}));
|
||||
await state([{...manuscript,bookId:5}]);assert.equal(await page.evaluate(()=>invocations.includes('StartOnboardingManuscriptScan')),false,'presence updates never upload prose');await button.click();await page.waitForFunction(()=>invocations.includes('StartOnboardingManuscriptScan'));
|
||||
console.log('PASS browser wizard states: disconnected, authenticated/no Word, Word/no manuscript, unassociated first import, selected book, wrong book, stale lease and explicit-only transfer');
|
||||
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1)});
|
||||
@ -6,24 +6,25 @@ let step='initialise';const analyse=process.argv.includes('--analyse');
|
||||
const context=await browser.newContext({viewport:{width:1400,height:1000}});await context.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
|
||||
const page=await context.newPage();const base='https://dev.plotdirector.com';step='normal login';await page.goto(base+'/Account/Login');await page.locator('input[name=Email]').fill(identity.Email);await page.locator('input[name=Password]').fill(identity.Password);await Promise.all([page.waitForURL(u=>u.pathname!='/Account/Login'),page.locator('form:has(input[name=Password]) button[type=submit]').click()]);
|
||||
async function post(path,fields={}){const csrf=await page.locator('input[name=__RequestVerificationToken]').first().inputValue();const response=await context.request.post(base+path,{form:{...fields,__RequestVerificationToken:csrf}});assert.ok(response.ok(),`Form failed: ${path} HTTP ${response.status()}`);await page.goto(base+'/onboarding');}
|
||||
step='normal browser-approved desktop pairing';const verifier=crypto.randomBytes(32).toString('hex'),challenge=crypto.createHash('sha256').update(verifier).digest('hex').toUpperCase();const bare=await request.newContext({baseURL:base});let response=await bare.post('/api/native-companion/pair',{data:{challenge}});assert.ok(response.ok());const {code}=await response.json();const approval=await context.newPage();await approval.goto(base+'/native-companion/authorize?code='+encodeURIComponent(code));const csrf=await approval.locator('input[name=__RequestVerificationToken]').inputValue();response=await context.request.post(base+'/native-companion/authorize',{form:{code,__RequestVerificationToken:csrf}});assert.ok(response.ok());response=await bare.post('/api/native-companion/token',{data:{code,verifier}});assert.ok(response.ok());const {accessToken}=await response.json();assert.ok(accessToken);agent=await request.newContext({baseURL:base,extraHTTPHeaders:{Authorization:'Bearer '+accessToken}});await bare.dispose();await approval.close();
|
||||
const instanceId=crypto.randomUUID(),sessionId=crypto.randomUUID(),manuscriptId=crypto.randomUUID();let sequence=0;const presence={bookId:0,wordRunning:true,manuscriptId,revision:1,active:true,wordAvailable:true,wordSaved:true,canCapture:true,documentTitle:'Synthetic native handoff verification'};
|
||||
async function heartbeat(){const reply=await agent.post(`/api/native-companion/instances/${instanceId}/documents/${sessionId}/presence`,{data:{...presence,sequence:++sequence}});assert.ok(reply.ok(),'Presence rejected');return reply.json();}
|
||||
const initialCatalog=(await heartbeat()).catalogVersion;
|
||||
step='isolated wizard project and book';await page.goto(base+'/onboarding');await post('/onboarding/start-import');await post('/onboarding/writing-journey',{WritingJourney:'AlreadyStarted'});await post('/onboarding/writing-software',{WritingSoftware:'MicrosoftWord'});const existingPanel=page.locator('[data-onboarding-scan-panel]');if(await existingPanel.count()===0){const projects=page.locator('input[name=SelectedProjectID]');if(analyse)assert.equal(await projects.count(),0,'AI smoke requires a fresh fixture identity, not a populated test book');await post('/onboarding/project',await projects.count()?{Mode:'Select',SelectedProjectID:await projects.first().inputValue()}:{Mode:'Create',ProjectName:'Native integration isolated verification'});const books=page.locator('input[name=SelectedBookID]');await post('/onboarding/book',await books.count()?{Mode:'Select',SelectedBookID:await books.first().inputValue()}:{Mode:'Create',BookTitle:'Native integration synthetic manuscript'});}
|
||||
const bookId=Number(await page.locator('[data-onboarding-scan-panel]').getAttribute('data-book-id'));assert.ok(bookId>0,'Wizard did not create an authorised test book');
|
||||
step='normal browser-approved desktop pairing';const verifier=crypto.randomBytes(32).toString('hex'),challenge=crypto.createHash('sha256').update(verifier).digest('hex').toUpperCase();const bare=await request.newContext({baseURL:base});let response=await bare.post('/api/native-companion/pair',{data:{challenge}});assert.ok(response.ok());const {code}=await response.json();const approval=await context.newPage();await approval.goto(base+'/native-companion/authorize?code='+encodeURIComponent(code));const csrf=await approval.locator('input[name=__RequestVerificationToken]').inputValue();response=await context.request.post(base+'/native-companion/authorize',{form:{code,__RequestVerificationToken:csrf}});assert.ok(response.ok());response=await bare.post('/api/native-companion/token',{data:{code,verifier}});assert.ok(response.ok());const {accessToken}=await response.json();assert.ok(accessToken);agent=await request.newContext({baseURL:base,extraHTTPHeaders:{Authorization:'Bearer '+accessToken}});await bare.dispose();await approval.close();
|
||||
const instanceId=crypto.randomUUID(),sessionId=crypto.randomUUID(),manuscriptId=crypto.randomUUID();let sequence=0;const presence={bookId,manuscriptId,revision:1,active:true,wordAvailable:true,wordSaved:true,canCapture:true,documentTitle:'Synthetic native handoff verification'};
|
||||
async function heartbeat(){const reply=await agent.post(`/api/native-companion/instances/${instanceId}/documents/${sessionId}/presence`,{data:{...presence,sequence:++sequence}});assert.ok(reply.ok(),'Presence rejected');return reply.json();}
|
||||
step='live native registration and header';await heartbeat();await page.reload();await page.waitForFunction(()=>document.querySelector('#native-companion-status')?.dataset.connected==='true');assert.equal(await page.locator('#native-companion-status').count(),1);
|
||||
const statuses=await(await context.request.get(base+'/native-companion/status')).json();assert.ok(statuses.some(s=>s.bookId===bookId&&s.sessionId===sessionId&&s.wordSaved===true));
|
||||
step='live native registration and newly created book catalogue';const refreshed=await heartbeat();assert.notEqual(refreshed.catalogVersion,initialCatalog,'Book creation did not invalidate the existing native catalogue');const bookList=await(await agent.get('/api/native-companion/books')).json();assert.ok(bookList.some(b=>b.bookId===bookId),'Created book unavailable to the already approved agent');await page.waitForFunction(()=>document.querySelector('#native-companion-status')?.dataset.connected==='true');assert.equal(await page.locator('#native-companion-status').count(),1);
|
||||
const statuses=await(await context.request.get(base+'/native-companion/status')).json();assert.ok(statuses.some(s=>s.bookId===0&&s.sessionId===sessionId&&s.wordSaved===true));
|
||||
step='existing wizard capture command';await page.locator('[data-onboarding-scan-start]').waitFor({state:'visible'});await page.waitForFunction(()=>!document.querySelector('[data-onboarding-scan-start]').disabled);await page.locator('[data-onboarding-scan-start]').click();let command;
|
||||
for(let i=0;i<30&&!command;i++){await new Promise(r=>setTimeout(r,150));command=(await heartbeat()).navigation;}assert.equal(command?.kind,'wizard-capture');assert.equal(command.sessionId,sessionId);
|
||||
for(let i=0;i<30&&!command;i++){await new Promise(r=>setTimeout(r,150));command=(await heartbeat()).navigation;}assert.equal(command?.kind,'wizard-capture');assert.equal(command.sessionId,sessionId);assert.equal(command.bookId,bookId,'First import did not carry the authorised destination book');presence.bookId=bookId;await heartbeat();
|
||||
const heading='Synthetic Chapter One\r',body=(analyse?'At dawn, a traveller reached the closed station and found a porter waiting beside the locked gate. The last train had gone during the night. A storm had damaged the road, and the traveller carried medicine intended for the village beyond the hills. The porter explained that the bridge was unsafe. He could offer a dry room and a place beside the fire, but he would not open the gate. The traveller set the parcel on the bench and asked whether anyone knew another way across. For a moment neither spoke. Rain tapped against the roof. Then the porter took an old map from his coat and pointed to a narrow crossing upstream. It would take most of the morning to reach it. He warned that the path was steep and offered to accompany the traveller as far as the river. The traveller accepted, divided the parcel between two bags, and helped the porter gather a rope and two lamps. Before leaving, they wrote a note for the next railway worker and fastened it to the office door. Their plan was uncertain, but they now had a route and a shared reason to attempt it.':'This is isolated synthetic manuscript prose. It must survive the native handoff exactly.')+'\r';const end=heading.length+body.length;
|
||||
step='durable authenticated native intake';response=await agent.post('/api/native-companion/manuscript-capture',{data:{requestId:command.id,instanceId,sessionId,manuscriptId,revision:1,end,paragraphs:[{start:0,end:heading.length,paragraphIndex:1,outlineLevel:1,text:heading,completesParagraph:true,markerTags:[]},{start:heading.length,end,paragraphIndex:2,outlineLevel:10,text:body,completesParagraph:true,markerTags:[]}]}});assert.ok(response.ok(),'Capture was not accepted');assert.equal((await response.json()).captureRequestId,command.id);
|
||||
await page.waitForURL(u=>u.pathname==='/onboarding/scan-review');assert.match(await page.locator('main').innerText(),/Synthetic Chapter One/);
|
||||
step='review survives companion disconnection';response=await agent.delete(`/api/native-companion/instances/${instanceId}/documents/${sessionId}/presence?throughSequence=${sequence}`);assert.ok(response.ok());await page.reload();assert.match(await page.locator('main').innerText(),/Synthetic Chapter One/);assert.deepEqual(await(await context.request.get(base+'/native-companion/status')).json(),[]);
|
||||
fs.writeFileSync('/tmp/native-integration-live-check.sql',`IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Wrong database',1;\nIF NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptCaptures WHERE UserID=${identity.UserID} AND PreviewID='${command.id}' AND JSON_VALUE(Payload,'$.Chapters[0].ChapterText')=N'${body.replaceAll("'","''")}') THROW 51000,'Durable native source mismatch',1;\nPRINT 'PASS live wizard capture persisted exact synthetic prose in Development';\n`,{mode:0o600});
|
||||
if(analyse){
|
||||
step='explicit existing server analysis with Word disconnected';await page.getByRole('button',{name:'Continue to Scene Detection',exact:true}).click();await page.waitForURL(u=>u.pathname==='/onboarding');await page.waitForFunction(()=>{const b=document.querySelector('[data-onboarding-build-start]');return b&&!b.disabled;});await page.locator('[data-onboarding-build-start]').click();await page.waitForURL(u=>u.pathname==='/onboarding/build-complete',{timeout:240000});assert.match(await page.locator('main').innerText(),/Scene structure has been detected/);
|
||||
step='explicit existing server analysis with Word disconnected';await page.getByRole('button',{name:'Continue to Scene Detection',exact:true}).click();await page.waitForURL(u=>u.pathname==='/onboarding');assert.match(await page.locator('main').innerText(),/Native Companion imports do not write scene markers/);await page.waitForFunction(()=>{const b=document.querySelector('[data-onboarding-build-start]');return b&&!b.disabled;});await page.locator('[data-onboarding-build-start]').click();await page.waitForURL(u=>u.pathname==='/onboarding/build-complete',{timeout:240000});assert.match(await page.locator('main').innerText(),/Scene structure has been detected/);
|
||||
presence.cursorStart=heading.length+1;const mapped=await heartbeat();assert.ok(mapped.sceneId>0&&mapped.chapterId>0,'Approved source did not resolve a trustworthy saved scene');await agent.delete(`/api/native-companion/instances/${instanceId}/documents/${sessionId}/presence?throughSequence=${sequence}`);
|
||||
fs.appendFileSync('/tmp/native-integration-live-check.sql',`IF NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds WHERE UserID=${identity.UserID} AND PreviewID='${command.id}' AND Status=N'Complete' AND MarkerStatus=N'NotRequested' AND ScenesCreated>0) THROW 51000,'Native server build did not complete independently',1;\nIF NOT EXISTS(SELECT 1 FROM dbo.SceneManuscriptSources WHERE BookID=${bookId} AND HASHBYTES('SHA2_256',LTRIM(RTRIM(REPLACE(SourceText,CHAR(13),N''))))=0x${crypto.createHash('sha256').update(Buffer.from(body.trim(),'utf16le')).digest('hex')}) THROW 51000,'Canonical manuscript prose differs from the accepted source',1;\nPRINT 'PASS actual existing AI scene analysis completed after Word disconnection; canonical prose retained and trusted scene mapping resolved';\n`);
|
||||
fs.appendFileSync('/tmp/native-integration-live-check.sql',`IF NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds WHERE UserID=${identity.UserID} AND PreviewID='${command.id}' AND Status=N'Complete' AND MarkerStatus=N'NotRequested' AND ScenesCreated>0) THROW 51000,'Native server build did not complete independently',1;\nIF NOT EXISTS(SELECT 1 FROM dbo.SceneManuscriptSources WHERE BookID=${bookId} AND HASHBYTES('SHA2_256',LTRIM(RTRIM(REPLACE(SourceText,CHAR(13),N''))))=0x${crypto.createHash('sha256').update(Buffer.from(body.trim(),'utf16le')).digest('hex')}) THROW 51000,'Canonical manuscript prose differs from the accepted source',1;\nIF NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptCaptures WHERE PreviewID='${command.id}' AND EXISTS(SELECT 1 FROM OPENJSON(AnalysisCheckpoints) a WHERE JSON_VALUE(a.value,'$.Success')='true')) THROW 51000,'Successful chapter analysis was not checkpointed',1;\nPRINT 'PASS actual existing AI scene analysis completed after Word disconnection; canonical prose retained and trusted scene mapping resolved';\n`);
|
||||
}
|
||||
step='real dedicated Context and Intent windows';await page.goto(base+'/native-companion/workspace?bookId='+bookId);const opened=[];context.on('page',p=>opened.push(p));await page.locator('[data-native-open-role=Context]').click();await page.waitForTimeout(700);await page.locator('[data-native-open-role=Intent]').click();await page.waitForTimeout(700);await page.locator('[data-native-open-role=Context]').click();await page.locator('[data-native-open-role=Intent]').click();await page.waitForTimeout(400);assert.equal(opened.length,2,'Repeated launches created duplicate windows');
|
||||
for(const popup of opened){await popup.waitForSelector('#native-workspace');assert.equal(await popup.locator('.pd-ribbon,.pd-titlebar').count(),0,'Dedicated window contains application chrome');await popup.waitForSelector('#native-story-workspace',{state:'visible'});assert.ok((await popup.locator('#native-story-workspace').boundingBox()).height>=250);assert.match(await popup.locator('#native-presence-status').innerText(),/disconnected|unavailable/);}
|
||||
|
||||
@ -114,6 +114,11 @@ internal static class NativeCompanionHttpTests
|
||||
await socket.ConnectAsync(new Uri(address.Replace("http://","ws://")+"/hubs/native-companion?id="+Uri.EscapeDataString(connectionToken!)),socketTimeout.Token);
|
||||
await socket.SendAsync(Encoding.UTF8.GetBytes("{\"protocol\":\"json\",\"version\":1}\u001e"),System.Net.WebSockets.WebSocketMessageType.Text,true,socketTimeout.Token);
|
||||
var socketBuffer=new byte[4096];await socket.ReceiveAsync(socketBuffer,socketTimeout.Token);
|
||||
var firstInstance=Guid.NewGuid();var firstSession=Guid.NewGuid();var firstDocument=new NativePresence{BookId=0,ManuscriptId=Guid.NewGuid(),WordRunning=true,CanCapture=true,Sequence=1,DocumentTitle="Unassociated manuscript",ChapterId=999,SceneId=999};
|
||||
var firstPresence=await agent.PostAsJsonAsync($"/api/native-companion/instances/{firstInstance}/documents/{firstSession}/presence",firstDocument);
|
||||
var firstReply=await firstPresence.Content.ReadFromJsonAsync<NativePresence>();Check(firstPresence.IsSuccessStatusCode&&firstReply?.ChapterId==null&&firstReply?.SceneId==null,"Authenticated unassociated Word session is visible but cannot claim saved chapter/scene data");
|
||||
var status=await browser.GetFromJsonAsync<JsonElement>("/native-companion/status");Check(status.EnumerateArray().Any(l=>l.GetProperty("bookId").GetInt32()==0&&l.GetProperty("wordRunning").GetBoolean()),"Browser sees its own unassociated manuscript without requiring a pre-existing book association");
|
||||
await agent.DeleteAsync($"/api/native-companion/instances/{firstInstance}/documents/{firstSession}/presence");
|
||||
var instance=Guid.NewGuid();var document=Guid.NewGuid();var live=new NativePresence{BookId=3,ManuscriptId=request.ManuscriptId,Sequence=1,DocumentTitle="Synthetic manuscript"};
|
||||
Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/presence",live)).IsSuccessStatusCode,"Actual bearer-scoped presence accepted");
|
||||
var notification=await socket.ReceiveAsync(socketBuffer,socketTimeout.Token);Check(Encoding.UTF8.GetString(socketBuffer,0,notification.Count).Contains("NativePresenceChanged"),"Authenticated native hub pushes only invalidation, not prose or navigation feedback");socket.Abort();
|
||||
|
||||
83
PlotLine.Tests/NativeImportCorrectionTests.cs
Normal file
83
PlotLine.Tests/NativeImportCorrectionTests.cs
Normal file
@ -0,0 +1,83 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
internal static class NativeImportCorrectionTests
|
||||
{
|
||||
private static void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);}
|
||||
private static string Response(int count,bool malformedConfidence=true)=>JsonSerializer.Serialize(new{
|
||||
schemaVersion="1.0",chapterSummary="Synthetic structural regression, not a proposed author scene plan.",
|
||||
sceneBoundaries=Enumerable.Range(1,count).Select(i=>new{sceneNumber=i,startParagraph=i,endParagraph=i,suggestedTitle="Test scene",structuralSummary="A synthetic narrative event for paragraph mapping verification.",confidence=i==count?0.9m:0.8m,reason="Synthetic boundary fixture."})
|
||||
}).Replace("\"confidence\":0.9",malformedConfidence?"\"confidence\":0. Nine":"\"confidence\":0.9");
|
||||
private static (ManuscriptStructureAnalysisService Service,FakeStoryIntelligenceClient Client) Analysis(string json){var client=new FakeStoryIntelligenceClient(JsonSerializer.Serialize(new{output=new[]{new{content=new[]{new{type="output_text",text=json}}}}}));return(new(new FakeStoryPromptRepository(),new FakeStoryPromptVersionService(),client,new ChapterStructureValidator(),NullLogger<ManuscriptStructureAnalysisService>.Instance),client);}
|
||||
public static async Task Run()
|
||||
{
|
||||
await CheckpointRetry();
|
||||
var options=new JsonSerializerOptions(JsonSerializerDefaults.Web);
|
||||
var parsed=StoryIntelligenceAiJsonParser.Parse<ChapterStructureModel>(Response(4),options);
|
||||
Check(parsed.Success&&parsed.Parsed!.SceneBoundaries![3].Confidence==0.9m&&parsed.Warnings.Count>0,"Observed Counting the Days confidence token 0. Nine is repaired transparently without changing paragraph coordinates");
|
||||
Check(parsed.Parsed!.SceneBoundaries!.Select(s=>s.StartParagraph).SequenceEqual(new int?[]{1,2,3,4}),"Confidence repair does not invent or move any scene boundary");
|
||||
var bad=Response(4,false).Replace("\"endParagraph\":4","\"endParagraph\":0. Nine");
|
||||
Check(!StoryIntelligenceAiJsonParser.Parse<ChapterStructureModel>(bad,options).Success,"Malformed paragraph coordinates remain an error, never inferred");
|
||||
var quoted=Response(4).Replace("Synthetic boundary fixture.","The string 0. nine remains literal.");
|
||||
Check(StoryIntelligenceAiJsonParser.Parse<ChapterStructureModel>(quoted,options).Parsed!.SceneBoundaries![0].Reason=="The string 0. nine remains literal.","Confidence repair leaves quoted narrative strings unchanged");
|
||||
var fragments=new List<ParagraphFragment>();var position=0;int ordinal=0;
|
||||
foreach(var row in new[]{(1,"Title page\r"),(10,"Copyright prose.\r"),(1,"– Counting the Days\r"),(10,"Repeated paragraph.\r"),(10,"\r"),(10,"Repeated paragraph.\r"),(10,"Manual\vline break.\r"),(10,"\f\r"),(10,"Final paragraph.\r")}){
|
||||
fragments.Add(new(){Start=position,End=position+row.Item2.Length,ParagraphIndex=++ordinal,OutlineLevel=row.Item1,Text=row.Item2,CompletesParagraph=true});position+=row.Item2.Length;
|
||||
}
|
||||
var preview=NativeManuscriptCapture.Build(new(){End=position,Paragraphs=fragments.ToArray()},7,1,2,3,"Synthetic manuscript");
|
||||
Check(preview.Chapters[0].IsFrontMatter&&preview.Chapters[0].ChapterNumber==0&&preview.Chapters[1].ChapterNumber==1,"Leading title/copyright material is retained separately without shifting story chapter numbering");
|
||||
using(var provider=new ServiceCollection().BuildServiceProvider()){
|
||||
var scans=new ManuscriptScanPreviewStore(provider.GetRequiredService<IServiceScopeFactory>(),NullLogger<ManuscriptScanPreviewStore>.Instance);var reviewSource=new ManuscriptScanPreview{UserID=7,Chapters=preview.Chapters};
|
||||
await scans.CompleteAsync(7,reviewSource);var defaults=await scans.GetReviewAsync(7,reviewSource.PreviewID);
|
||||
Check(preview.ChapterCount==1&&defaults!.Chapters[0].Include==false&&defaults.Chapters[1].Include,"Canonical chapter review excludes front matter by default while preserving it for explicit author review");
|
||||
}
|
||||
var chapter=preview.Chapters[1];Check(chapter.ParagraphMap.Select(p=>p.WordParagraphIndex).SequenceEqual(new[]{4,6,7,9}),"Blank paragraphs and page breaks do not consume structural ordinals; repeated text keeps distinct source indices");
|
||||
var (service,client)=Analysis(Response(4));var result=await service.AnalyseChapterAsync(new(){TemporaryChapterKey=chapter.TemporaryChapterKey,SourceLabel="Synthetic: – Counting the Days",ChapterText=chapter.ChapterText!,ParagraphMap=chapter.ParagraphMap,SourceParagraphs=chapter.SourceParagraphs});
|
||||
Check(result.Success&&client.Prompts.Count==1&&result.Scenes.Count==4,"Native canonical paragraph map passes the established analysis service with the observed malformed confidence response");
|
||||
Check(result.Scenes.Select(s=>s.WordStartPosition).SequenceEqual(new int[]{4,6,7,9})&&result.Scenes[0].SourceText==result.Scenes[1].SourceText,"Scene boundaries map by original paragraph identity, never by repeated text matching");
|
||||
var (invalid,invalidClient)=Analysis(bad);var failure=await invalid.AnalyseChapterAsync(new(){TemporaryChapterKey=chapter.TemporaryChapterKey,ChapterText=chapter.ChapterText!,ParagraphMap=chapter.ParagraphMap,SourceParagraphs=chapter.SourceParagraphs});
|
||||
Check(!failure.Success&&failure.Scenes.Count==0&&invalidClient.Prompts.Count==2,"Unrepairable analysis uses bounded retry then reports failure without fabricated scenes");
|
||||
}
|
||||
private static async Task CheckpointRetry()
|
||||
{
|
||||
var values=new Dictionary<(int,Guid,string),string>();var calls=new Dictionary<string,int>();var previewId=Guid.NewGuid();
|
||||
var repo=NativeWorkflowTests.Proxy<PlotLine.Data.IManuscriptCaptureRepository>((name,args)=>name switch{
|
||||
"GetAnalysis"=>Task.FromResult(values.GetValueOrDefault(((int)args![0]!, (Guid)args[1]!, (string)args[2]!))),
|
||||
"SaveAnalysis"=>Save((int)args![0]!, (Guid)args[1]!, (string)args[2]!, (string)args[3]!),
|
||||
_=>throw new Exception("Unexpected source mutation during retry: "+name)});
|
||||
Task Save(int user,Guid preview,string hash,string result){values[(user,preview,hash)]=result;return Task.CompletedTask;}
|
||||
var ai=NativeWorkflowTests.Proxy<IManuscriptStructureAnalysisService>((_,args)=>{
|
||||
var request=(ManuscriptStructureAnalysisRequest)args![0]!;calls[request.TemporaryChapterKey]=calls.GetValueOrDefault(request.TemporaryChapterKey)+1;
|
||||
return Task.FromResult(request.TemporaryChapterKey=="second"&&calls["second"]==1?ManuscriptStructureAnalysisResult.Failed("second","Synthetic provider failure"):
|
||||
ManuscriptStructureAnalysisResult.Succeeded(request.TemporaryChapterKey,[new(){TemporaryChapterKey=request.TemporaryChapterKey,SceneNumberWithinChapter=1,SourceText=request.ChapterText,StartParagraph=1,EndParagraph=1,WordStartPosition=1,WordEndPosition=1}],"{}"));
|
||||
});
|
||||
var people=NativeWorkflowTests.Proxy<PlotLine.Data.ICharacterRepository>((_,_)=>Task.FromResult<IReadOnlyList<Character>>([]));
|
||||
var scans=NativeWorkflowTests.Proxy<IManuscriptScanPreviewStore>((_,_)=>Task.FromResult(new OnboardingBuildProgress()));
|
||||
OnboardingService NewService(){var constructor=typeof(OnboardingService).GetConstructors().Single();return (OnboardingService)constructor.Invoke(constructor.GetParameters().Select(p=>p.ParameterType==typeof(PlotLine.Data.IManuscriptCaptureRepository)?(object)repo:p.ParameterType==typeof(IManuscriptStructureAnalysisService)?ai:p.ParameterType==typeof(PlotLine.Data.ICharacterRepository)?people:p.ParameterType==typeof(IManuscriptScanPreviewStore)?scans:null).ToArray());}
|
||||
var source=new ManuscriptScanPreview{PreviewID=previewId,UserID=7,ProjectID=1,BookID=3,Source="NativeWordCompanion",Chapters=new[]{"first","second"}.Select((key,i)=>new ManuscriptScanChapterPreview{TemporaryChapterKey=key,ChapterNumber=i+1,ChapterText="Exact source "+key,ParagraphMap=[new(){StructuralParagraphOrdinal=1,WordParagraphIndex=1,Text="Exact source "+key}]}).ToArray()};
|
||||
ManuscriptScanReviewDecision Review(string title)=>new(){PreviewID=previewId,Chapters=[new(){TemporaryChapterKey="first",ChapterNumber=1,Title=title,Include=true},new(){TemporaryChapterKey="second",ChapterNumber=2,Title="Second",Include=true}]};
|
||||
var method=typeof(OnboardingService).GetMethod("AnalyseApprovedChaptersAsync",System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.NonPublic)!;
|
||||
async Task Analyse(OnboardingService service,ManuscriptScanReviewDecision review)=>await (Task<IReadOnlyList<ManuscriptStructureSceneBoundary>>)method.Invoke(service,[7,source,review,new Book{BookID=3},null])!;
|
||||
var failed=false;try{await Analyse(NewService(),Review("First"));}catch(InvalidOperationException){failed=true;}
|
||||
Check(failed&&calls["first"]==1&&calls["second"]==1&&values.Count==2,"Failed second chapter retains first success and diagnostic result without mutating captured source");
|
||||
await Analyse(NewService(),Review("First"));Check(calls["first"]==1&&calls["second"]==2,"New service resumes from persisted success and retries only the failed chapter without Word capture");
|
||||
await Analyse(NewService(),Review("Edited intention"));Check(calls["first"]==2&&calls["second"]==2,"Changed reviewed chapter context invalidates only its analysis checkpoint");
|
||||
}
|
||||
// Private, non-network evidence probe. Reads an explicitly supplied protected local capture; prints no prose.
|
||||
public static async Task CapturedEvidence(string file,string key)
|
||||
{
|
||||
var preview=JsonSerializer.Deserialize<ManuscriptScanPreview>(await File.ReadAllTextAsync(file))!;
|
||||
var chapter=preview.Chapters.Single(c=>c.TemporaryChapterKey==key);
|
||||
var map=chapter.ParagraphMap;
|
||||
Check(map.Count>0&&map.Select(p=>p.StructuralParagraphOrdinal).SequenceEqual(Enumerable.Range(1,map.Count))&&map.Zip(map.Skip(1)).All(p=>p.First.WordParagraphIndex<p.Second.WordParagraphIndex),"Privately inspected failing chapter has contiguous structural ordinals and monotonic original paragraph identities");
|
||||
// One fixture boundary only, never persisted or represented as real AI output.
|
||||
var json=JsonSerializer.Serialize(new{schemaVersion="1.0",chapterSummary="Synthetic mapping probe only.",sceneBoundaries=new[]{new{sceneNumber=1,startParagraph=1,endParagraph=map.Count,suggestedTitle="Mapping probe",structuralSummary="Synthetic mapping validation only, not an analysis of the author manuscript.",confidence=0.9m,reason="Private non-network mapping regression."}}}).Replace("\"confidence\":0.9","\"confidence\":0. Nine");
|
||||
var (service,_)=Analysis(json);var result=await service.AnalyseChapterAsync(new(){PrivateAnalysis=true,TemporaryChapterKey=key,ChapterText=chapter.ChapterText!,ParagraphMap=map,SourceParagraphs=chapter.SourceParagraphs});
|
||||
Check(result.Success&&result.Scenes.Single().WordStartPosition==map.First().WordParagraphIndex&&result.Scenes.Single().WordEndPosition==map.Last().WordParagraphIndex,"Actual privately read captured chapter passes canonical source mapping with a synthetic response containing the observed malformed token");
|
||||
Console.WriteLine($"Evidence: structural paragraphs {map.Count}; source paragraphs {chapter.SourceParagraphs.Count}; no provider call, source write, import or story mutation.");
|
||||
}
|
||||
}
|
||||
@ -36,6 +36,15 @@ internal static class NativeManuscriptCaptureTests
|
||||
state=await transfer.Accept(7,"grant",source);Check(state.Status==ManuscriptScanStatuses.Complete&&repo.Values.ContainsKey(source.RequestId),"Acceptance follows durable source persistence");
|
||||
await transfer.Accept(7,"grant",source);Check(repo.Writes==1,"Same capture retransmission is idempotent");
|
||||
var priorText=source.Paragraphs[1].Text;source.Paragraphs[1].Text="Conflicting text";bad=false;try{await transfer.Accept(7,"grant",source);}catch(ArgumentException){bad=true;}source.Paragraphs[1].Text=priorText;Check(bad&&repo.Writes==1,"Changed same-ID submission cannot overwrite accepted source");
|
||||
// First-time import: no existing book association is required, but another book is never silently reassigned.
|
||||
var freshId=Guid.NewGuid();var freshSession=Guid.NewGuid();var freshManuscript=Guid.NewGuid();
|
||||
store.Put(7,"fresh-grant",DateTimeOffset.UtcNow.AddHours(1),freshId,freshSession,new(){BookId=0,WordRunning=true,ManuscriptId=freshManuscript,Sequence=1,CanCapture=true,Active=true,DocumentTitle="First manuscript"});
|
||||
store.Remove(7,"grant",source.InstanceId,source.SessionId);
|
||||
var firstImport=await transfer.Start(7,4,1,3);var command=store.TakeNavigation(7,"fresh-grant",freshId,freshSession);
|
||||
Check(firstImport?.ScanID!=null&&command?.BookId==3&&command.SessionId==freshSession,"First-time import targets the active unassociated manuscript and carries the authorised destination book");
|
||||
await transfer.Fail(7,"fresh-grant",command!.Id);store.Remove(7,"fresh-grant",freshId,freshSession);
|
||||
store.Put(7,"fresh-grant",DateTimeOffset.UtcNow.AddHours(1),freshId,freshSession,new(){BookId=99,ManuscriptId=freshManuscript,Sequence=2,CanCapture=true,Active=true,DocumentTitle="Another book"});
|
||||
Check(await transfer.Start(7,4,1,3)==null,"First-time import never silently takes a manuscript associated with a different book");store.Remove(7,"fresh-grant",freshId,freshSession);
|
||||
store.Remove(7,"grant",source.InstanceId,source.SessionId);Check((await scans.GetPreviewAsync(7,source.RequestId))?.Chapters[0].ChapterText=="Words remain exact.\r","Accepted manuscript survives Word/agent disconnection");
|
||||
var restarted=new ManuscriptScanPreviewStore(services.GetRequiredService<IServiceScopeFactory>(),NullLogger<ManuscriptScanPreviewStore>.Instance);Check((await restarted.GetStateAsync(7,4)).PreviewID==source.RequestId&&(await restarted.GetLatestPreviewAsync(7,4))?.NativeParagraphPositions[2]==10,"Server restart reloads accepted source and coordinate provenance");
|
||||
Check(await restarted.GetPreviewAsync(8,source.RequestId)==null,"Recovered source remains account scoped");
|
||||
@ -45,6 +54,9 @@ internal static class NativeManuscriptCaptureTests
|
||||
private sealed class Memory:IManuscriptCaptureRepository
|
||||
{
|
||||
public readonly Dictionary<Guid,ManuscriptScanPreview> Values=[];public bool Fail;public int Writes;
|
||||
private readonly Dictionary<(int,Guid,string),string> analyses=[];
|
||||
public Task<string?> GetAnalysis(int user,Guid preview,string hash)=>Task.FromResult(analyses.GetValueOrDefault((user,preview,hash)));
|
||||
public Task SaveAnalysis(int user,Guid preview,string hash,string result){analyses[(user,preview,hash)]=result;return Task.CompletedTask;}
|
||||
public Task Clear(int user,int onboarding)=>Task.CompletedTask;
|
||||
public Task CompleteBuild(int user,Guid preview)=>Task.CompletedTask;
|
||||
public Task Save(ManuscriptScanPreview preview){if(Fail)throw new IOException("Synthetic durable-store failure");if(!Values.ContainsKey(preview.PreviewID))Writes++;Values[preview.PreviewID]=preview;return Task.CompletedTask;}
|
||||
|
||||
@ -126,6 +126,8 @@ if(args.Contains("--intent-assessment")){await IntentAssessmentTests.Run();Conso
|
||||
if(args.Contains("--release-sprint")){ReleaseSprintTests.Run();Console.WriteLine("PASS continuity triage and public onboarding/installer guidance");return;}
|
||||
if(args.Contains("--native-import")){await NativeImportTests.Run();Console.WriteLine("PASS approved native import preview, source preservation, ownership, version and retry");return;}
|
||||
if(args.Contains("--native-installation")){await NativeInstallationTests.Run();Console.WriteLine("PASS trusted installation access, renewal, process replacement, account isolation and revocation");return;}
|
||||
if(args.Contains("--native-import-corrections")){await NativeImportCorrectionTests.Run();return;}
|
||||
if(args.Contains("--native-captured-evidence")){await NativeImportCorrectionTests.CapturedEvidence(args[1],args[2]);return;}
|
||||
if(args.Contains("--native-tray")){await NativeTrayIntegrationTests.Run();await NativeManuscriptCaptureTests.Run();Console.WriteLine("PASS native tray presence, expiry, scope and persistent PWA review decisions");return;}
|
||||
if(args.Contains("--native-workflow")){await NativeWorkflowTests.Run();Console.WriteLine("PASS native saved workspace and safe import preview validation");return;}
|
||||
if(args.Contains("--native-companion-http")){await NativeCompanionHttpTests.Run();return;}
|
||||
@ -5515,7 +5517,8 @@ static void CoreImportDetectScenesIsCompactAndOwnsTitleOption()
|
||||
Assert(detectScenesBlock.Contains("data-onboarding-generate-scene-titles checked", StringComparison.Ordinal), "Detect Scenes should keep the existing ON default.");
|
||||
Assert(detectScenesBlock.Contains("data-word-companion-compact-status-label", StringComparison.Ordinal), "Detect Scenes should render compact Word connection status.");
|
||||
Assert(detectScenesBlock.Contains("data-word-companion-document", StringComparison.Ordinal), "Detect Scenes should include the current Word document name.");
|
||||
Assert(detectScenesBlock.Contains("Keep Word open while PlotDirector detects scenes and writes the scene markers.", StringComparison.Ordinal), "Detect Scenes should give the required concise Word-open instruction.");
|
||||
Assert(detectScenesBlock.Contains("Keep Word open while PlotDirector detects scenes and writes the scene markers.", StringComparison.Ordinal), "Legacy Office.js imports retain their Word marker/save instruction.");
|
||||
Assert(detectScenesBlock.Contains("NativeCapture",StringComparison.Ordinal)&&detectScenesBlock.Contains("Native Companion imports do not write scene markers to Word",StringComparison.Ordinal),"Native capture must explain server-side processing without claiming marker write-back.");
|
||||
Assert(detectScenesBlock.Contains("data-onboarding-build-panel hidden", StringComparison.Ordinal), "Detect Scenes should hide processing progress until detection starts.");
|
||||
Assert(!detectScenesBlock.Contains("onboarding-companion-card", StringComparison.Ordinal), "Detect Scenes should not render the large Word Companion card.");
|
||||
Assert(!detectScenesBlock.Contains("Word Companion Connected", StringComparison.Ordinal), "Detect Scenes should not render the old dashboard heading.");
|
||||
|
||||
@ -17,6 +17,19 @@ IF (SELECT COUNT(*) FROM dbo.OnboardingManuscriptCaptures WHERE PreviewID=@Previ
|
||||
CREATE TABLE #Recovered(Payload nvarchar(max));
|
||||
INSERT #Recovered EXEC dbo.OnboardingManuscriptCapture @Action='get',@UserID=@User,@PreviewID=@Preview;
|
||||
IF NOT EXISTS(SELECT 1 FROM #Recovered WHERE Payload=@Payload) THROW 51000,'Prose was not recovered exactly',1;
|
||||
-- Checkpoints must never change the accepted source or its idempotency hash.
|
||||
DECLARE @SourceHash varbinary(32)=(SELECT PayloadHash FROM dbo.OnboardingManuscriptCaptures WHERE PreviewID=@Preview),@Request varchar(64)=REPLICATE('A',64);
|
||||
EXEC dbo.OnboardingManuscriptChapterAnalysis @Action='save',@UserID=@User,@PreviewID=@Preview,@RequestHash=@Request,@Result=N'{"Success":true,"Scenes":[{"SourceText":"Exact prose."}]}';
|
||||
EXEC dbo.OnboardingManuscriptChapterAnalysis @Action='save',@UserID=@User,@PreviewID=@Preview,@RequestHash=@Request,@Result=N'{"Success":true,"Scenes":[{"SourceText":"Exact prose."}]}';
|
||||
CREATE TABLE #Analysis(Result nvarchar(max));
|
||||
INSERT #Analysis EXEC dbo.OnboardingManuscriptChapterAnalysis @Action='get',@UserID=@User,@PreviewID=@Preview,@RequestHash=@Request;
|
||||
IF NOT EXISTS(SELECT 1 FROM #Analysis WHERE JSON_VALUE(Result,'$.Success')='true') THROW 51000,'Successful chapter checkpoint did not round-trip',1;
|
||||
IF (SELECT COUNT(*) FROM dbo.OnboardingManuscriptCaptures c CROSS APPLY OPENJSON(c.AnalysisCheckpoints) WHERE c.PreviewID=@Preview)<>1 THROW 51000,'Retry duplicated checkpoint',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptCaptures WHERE PreviewID=@Preview AND Payload=@Payload AND PayloadHash=@SourceHash) THROW 51000,'Analysis changed immutable source',1;
|
||||
DECLARE @Different varchar(64)=REPLICATE('B',64);TRUNCATE TABLE #Analysis;
|
||||
INSERT #Analysis EXEC dbo.OnboardingManuscriptChapterAnalysis @Action='get',@UserID=@User,@PreviewID=@Preview,@RequestHash=@Different;
|
||||
IF EXISTS(SELECT 1 FROM #Analysis WHERE Result IS NOT NULL) THROW 51000,'Changed request reused stale analysis',1;
|
||||
PRINT 'PASS analysis checkpoint source immutability, idempotency, real JSON/prose round-trip and request revision isolation';
|
||||
TRUNCATE TABLE #Recovered;
|
||||
INSERT #Recovered EXEC dbo.OnboardingManuscriptCapture @Action='get',@UserID=@Other,@PreviewID=@Preview;
|
||||
IF EXISTS(SELECT 1 FROM #Recovered) THROW 51000,'Cross-account capture leak',1;
|
||||
@ -41,3 +54,28 @@ BEGIN TRY
|
||||
END TRY BEGIN CATCH SET @Denied=1;IF @@TRANCOUNT>0 ROLLBACK;END CATCH;
|
||||
IF @Denied=0 THROW 51000,'Inaccessible book accepted source',1;
|
||||
PRINT 'PASS unauthorised persistence refused without mutation';
|
||||
-- Real populated checkpoint access probes; each disposable transaction is rolled back after denial.
|
||||
DECLARE @Probe int=1;
|
||||
WHILE @Probe<=3
|
||||
BEGIN
|
||||
BEGIN TRANSACTION;
|
||||
INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@checkpoint.invalid',N'Checkpoint owner',N'not-a-credential');SET @User=SCOPE_IDENTITY();
|
||||
INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@checkpoint.invalid',N'Checkpoint other',N'not-a-credential');SET @Other=SCOPE_IDENTITY();
|
||||
INSERT dbo.SubscriptionLevel(Name,DisplayName,MaxBooks,MaxChaptersPerBook,MaxScenesPerBook,MaxCharactersPerProject,MaxStorageMB,MaxCollaborators,SortOrder,RequiresStripeSubscription) VALUES(CONVERT(nvarchar(36),NEWID()),N'Checkpoint fixture',2,100,100,100,100,0,0,0);SET @Level=SCOPE_IDENTITY();
|
||||
INSERT dbo.UserSubscription(UserID,SubscriptionLevelID,IsActive,IsTrial,TrialExpiryDateUTC) VALUES(@User,@Level,1,1,'2030-01-01');
|
||||
INSERT dbo.Projects(ProjectName) VALUES(N'Checkpoint ownership fixture');SET @Project=SCOPE_IDENTITY();
|
||||
INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@Project,@User,N'Owner',1);
|
||||
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@Project,N'Checkpoint fixture',1,1);SET @Book=SCOPE_IDENTITY();SET @Preview=NEWID();
|
||||
EXEC dbo.OnboardingManuscriptCapture @Action='save',@UserID=@User,@PreviewID=@Preview,@OnboardingID=4,@BookID=@Book,@Payload=N'{"Chapters":[]}';
|
||||
EXEC dbo.OnboardingManuscriptChapterAnalysis @Action='save',@UserID=@User,@PreviewID=@Preview,@RequestHash=@Request,@Result=N'{"Success":true,"Scenes":[{"SourceText":"Private fixture"}]}';
|
||||
SET @Denied=0;
|
||||
DECLARE @ProbeUser int=CASE WHEN @Probe=3 THEN @User ELSE @Other END,@ProbeAction varchar(8)=CASE WHEN @Probe=2 THEN 'save' ELSE 'get' END;
|
||||
IF @Probe=3 UPDATE dbo.ProjectUserAccess SET IsActive=0 WHERE ProjectID=@Project AND UserID=@User;
|
||||
BEGIN TRY
|
||||
EXEC dbo.OnboardingManuscriptChapterAnalysis @Action=@ProbeAction,@UserID=@ProbeUser,@PreviewID=@Preview,@RequestHash=@Request,@Result=N'{"Success":true}';
|
||||
END TRY BEGIN CATCH IF ERROR_MESSAGE()='Capture access denied' SET @Denied=1;END CATCH;
|
||||
IF @@TRANCOUNT>0 ROLLBACK;
|
||||
IF @Denied=0 THROW 51000,'Checkpoint crossed author or revoked project boundary',1;
|
||||
SET @Probe+=1;
|
||||
END;
|
||||
PRINT 'PASS populated cross-account checkpoint read/write and revoked-membership refusal; all fixtures rolled back';
|
||||
|
||||
@ -25,7 +25,7 @@ public sealed class NativeInstallationController(INativeInstallationRepository i
|
||||
public sealed class NativeConnectionController(INativeInstallationRepository installations,NativePresenceStore presence):ControllerBase
|
||||
{
|
||||
[HttpPost("heartbeat")]
|
||||
public IActionResult Heartbeat()=>Ok(new{connected=true}); // Authentication validates live installation/security stamp.
|
||||
public IActionResult Heartbeat()=>Ok(new{connected=true,catalogVersion=presence.CatalogVersion(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!))}); // Authentication validates live installation/security stamp.
|
||||
[HttpPost("disconnect")]
|
||||
public async Task<IActionResult> Disconnect(){if(Guid.TryParse(User.FindFirstValue("NativeCompanion.Installation"),out var id)&&Guid.TryParse(User.FindFirstValue("NativeCompanion.Connection"),out var connection)){var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);await installations.Run("disconnect",id,user,connection:connection);presence.DisconnectGrant(user,User.FindFirstValue("NativeCompanion.Grant")!);}return NoContent();}
|
||||
}
|
||||
|
||||
@ -16,19 +16,22 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC
|
||||
[HttpPost("instances/{instance:guid}/documents/{session:guid}/presence"),RequestSizeLimit(4096)]
|
||||
public async Task<IActionResult> Update(Guid instance,Guid session,NativePresence input)
|
||||
{
|
||||
input.Navigation=null;var book=await access.GetBookStructureAsync(input.BookId,Author);if(book==null)return Forbid();
|
||||
input.Navigation=null;
|
||||
if(input.BookId<0)return BadRequest();
|
||||
var book=input.BookId>0?await access.GetBookStructureAsync(input.BookId,Author):null;if(input.BookId>0&&book==null)return Forbid();
|
||||
if(book==null){input.ChapterId=null;input.SceneId=null;}
|
||||
if(input.CursorStart is <0)return BadRequest("Invalid cursor position.");
|
||||
if(input.CanCapture&&input.WordSaved!=true){input.ChapterId=null;input.SceneId=null;}
|
||||
if(input.WordAvailable&&input.SceneId==null&&presence.Resolve(Author,input,session) is {} known){input.ChapterId=known.Chapter;input.SceneId=known.Scene;}
|
||||
if(input.WordAvailable&&input.SceneId==null&&input.CursorStart.HasValue&&positions!=null&&(!input.CanCapture||input.WordSaved==true)){var mapped=await positions.Resolve(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value);if(mapped!=null&&(!input.ChapterId.HasValue||input.ChapterId==mapped.ChapterID)){input.ChapterId=mapped.ChapterID;input.SceneId=mapped.SceneID;}}
|
||||
var chapter=input.ChapterId.HasValue?book.Chapters.FirstOrDefault(c=>c.ChapterId==input.ChapterId):null;
|
||||
if(input.SceneId.HasValue){var parent=book.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==input.SceneId));if(parent==null||(chapter!=null&&chapter!=parent)){input.SceneId=null;input.ChapterId=null;chapter=null;}else{chapter=parent;input.ChapterId=parent.ChapterId;}}
|
||||
if(book!=null&&input.WordAvailable&&input.SceneId==null&&presence.Resolve(Author,input,session) is {} known){input.ChapterId=known.Chapter;input.SceneId=known.Scene;}
|
||||
if(book!=null&&input.WordAvailable&&input.SceneId==null&&input.CursorStart.HasValue&&positions!=null&&(!input.CanCapture||input.WordSaved==true)){var mapped=await positions.Resolve(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value);if(mapped!=null&&(!input.ChapterId.HasValue||input.ChapterId==mapped.ChapterID)){input.ChapterId=mapped.ChapterID;input.SceneId=mapped.SceneID;}}
|
||||
var chapter=input.ChapterId.HasValue?book!.Chapters.FirstOrDefault(c=>c.ChapterId==input.ChapterId):null;
|
||||
if(input.SceneId.HasValue){var parent=book!.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==input.SceneId));if(parent==null||(chapter!=null&&chapter!=parent)){input.SceneId=null;input.ChapterId=null;chapter=null;}else{chapter=parent;input.ChapterId=parent.ChapterId;}}
|
||||
if(input.ChapterId.HasValue&&chapter==null){input.ChapterId=null;input.SceneId=null;}
|
||||
var before=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session);
|
||||
if(!presence.Put(Author,Grant,Expires,instance,session,input))return Conflict(new{message="Stale, revoked or invalid native session."});
|
||||
if(live!=null&&(before==null||before.Position.BookId!=input.BookId||before.Position.ManuscriptId!=input.ManuscriptId||before.Position.Revision!=input.Revision||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.Active!=input.Active||before.Position.WordAvailable!=input.WordAvailable))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted);
|
||||
if(live!=null&&(before==null||before.Position.BookId!=input.BookId||before.Position.ManuscriptId!=input.ManuscriptId||before.Position.Revision!=input.Revision||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.Active!=input.Active||before.Position.WordAvailable!=input.WordAvailable||before.Position.WordRunning!=input.WordRunning))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted);
|
||||
if(input.CaptureRequestId.HasValue&&capture!=null&&wizard!=null){var progress=await capture.Progress(Author,Grant,input.CaptureRequestId.Value,input.CaptureProgress);if(progress!=null)await wizard.Clients.Group(WordCompanionFollowHub.PresenceGroup(Author)).SendAsync("OnboardingScanProgress",progress,HttpContext.RequestAborted);}
|
||||
input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);return Ok(input);
|
||||
input.CatalogVersion=presence.CatalogVersion(Author);input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);return Ok(input);
|
||||
}
|
||||
[HttpDelete("instances/{instance:guid}/documents/{session:guid}/presence")]
|
||||
public IActionResult Remove(Guid instance,Guid session,long? throughSequence=null){presence.Remove(Author,Grant,instance,session,throughSequence);return Ok(new NativePresence());}
|
||||
|
||||
@ -20,7 +20,7 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB
|
||||
public async Task<IActionResult> Presence(int bookId)
|
||||
{
|
||||
if(await access.GetBookStructureAsync(bookId,Author)==null)return Forbid();Response.Headers.CacheControl="no-store";
|
||||
return Json(presence.Read(Author,bookId).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,manuscriptId=l.Position.ManuscriptId,l.Position.BookId,l.Position.ChapterId,l.Position.SceneId,l.Position.DocumentTitle,l.Position.Active,l.Position.WordAvailable,l.Position.WordSaved,l.Position.CanCapture,updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
|
||||
return Json(presence.Read(Author,bookId).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,manuscriptId=l.Position.ManuscriptId,l.Position.BookId,l.Position.ChapterId,l.Position.SceneId,l.Position.DocumentTitle,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
|
||||
}
|
||||
[HttpPost("import/preview"),ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> ImportPreview(int bookId,Guid[] reviews,[FromServices] NativeImportService importer)
|
||||
@ -31,9 +31,9 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB
|
||||
[HttpGet("status")]
|
||||
public async Task<IActionResult> Status()
|
||||
{
|
||||
Response.Headers.CacheControl="no-store";var leases=presence.Read(Author,0);var allowed=new HashSet<int>();
|
||||
foreach(var book in leases.Select(l=>l.Position.BookId).Distinct())if(await access.GetBookStructureAsync(book,Author)!=null)allowed.Add(book);
|
||||
return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordSaved,l.Position.CanCapture,updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
|
||||
Response.Headers.CacheControl="no-store";var leases=presence.Read(Author,0);var allowed=new HashSet<int>{0};
|
||||
foreach(var book in leases.Select(l=>l.Position.BookId).Where(b=>b>0).Distinct())if(await access.GetBookStructureAsync(book,Author)!=null)allowed.Add(book);
|
||||
return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
|
||||
}
|
||||
[HttpGet("reviews/{id:guid}")]
|
||||
public async Task<IActionResult> Review(Guid id)
|
||||
|
||||
@ -21,6 +21,8 @@ public sealed class OnboardingController(
|
||||
public async Task<IActionResult> Index()
|
||||
{
|
||||
var model = await onboarding.GetWizardAsync();
|
||||
if(scanPreviews!=null&¤tUser.UserId is int user&&model.ScanState.PreviewID is Guid preview)
|
||||
ViewData["NativeCapture"]=(await scanPreviews.GetPreviewAsync(user,preview))?.Source=="NativeWordCompanion";
|
||||
return View(model);
|
||||
}
|
||||
|
||||
|
||||
@ -6,12 +6,16 @@ namespace PlotLine.Data;
|
||||
public interface IManuscriptCaptureRepository
|
||||
{
|
||||
Task Save(ManuscriptScanPreview preview);
|
||||
Task<string?> GetAnalysis(int user,Guid preview,string hash);
|
||||
Task SaveAnalysis(int user,Guid preview,string hash,string result);
|
||||
Task Clear(int user,int onboarding);
|
||||
Task CompleteBuild(int user,Guid preview);
|
||||
Task<ManuscriptScanPreview?> Get(int user,Guid? preview=null,int? onboarding=null);
|
||||
}
|
||||
public sealed class ManuscriptCaptureRepository(ISqlConnectionFactory factory):IManuscriptCaptureRepository
|
||||
{
|
||||
public async Task<string?> GetAnalysis(int user,Guid preview,string hash){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<string>("dbo.OnboardingManuscriptChapterAnalysis",new{Action="get",UserID=user,PreviewID=preview,RequestHash=hash},commandType:CommandType.StoredProcedure);}
|
||||
public async Task SaveAnalysis(int user,Guid preview,string hash,string result){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.OnboardingManuscriptChapterAnalysis",new{Action="save",UserID=user,PreviewID=preview,RequestHash=hash,Result=result},commandType:CommandType.StoredProcedure);}
|
||||
public async Task Clear(int user,int onboarding){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.OnboardingManuscriptCapture",new{Action="clear",UserID=user,OnboardingID=onboarding},commandType:CommandType.StoredProcedure);}
|
||||
public async Task CompleteBuild(int user,Guid preview){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.OnboardingManuscriptCapture",new{Action="built",UserID=user,PreviewID=preview},commandType:CommandType.StoredProcedure);}
|
||||
public async Task Save(ManuscriptScanPreview preview){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.OnboardingManuscriptCapture",new{Action="save",UserID=preview.UserID,preview.PreviewID,preview.OnboardingID,preview.BookID,Payload=JsonSerializer.Serialize(preview)},commandType:CommandType.StoredProcedure);}
|
||||
|
||||
@ -89,6 +89,7 @@ public sealed class ManuscriptScanPreview
|
||||
|
||||
public sealed class ManuscriptScanChapterPreview
|
||||
{
|
||||
public bool IsFrontMatter {get;init;}
|
||||
public string TemporaryChapterKey { get; init; } = string.Empty;
|
||||
public int ChapterNumber { get; init; }
|
||||
public string Title { get; init; } = string.Empty;
|
||||
|
||||
@ -1402,7 +1402,7 @@ public sealed class BookService(
|
||||
IProjectActivityService activity,
|
||||
IStoryIntelligencePipelineStateService storyIntelligencePipeline,
|
||||
IStoryIntelligenceResultRepository storyIntelligenceRuns,
|
||||
ICurrentUserService currentUser) : IBookService
|
||||
ICurrentUserService currentUser,PlotLine.Services.NativeCompanion.NativePresenceStore? nativePresence=null) : IBookService
|
||||
{
|
||||
public async Task<BookDetailViewModel?> GetDetailAsync(int bookId)
|
||||
{
|
||||
@ -1566,6 +1566,7 @@ public sealed class BookService(
|
||||
await subscriptions.ReleaseBookSlotReservationAsync(bookReservationId.Value);
|
||||
}
|
||||
}
|
||||
if(currentUser.UserId is int author)nativePresence?.BooksChanged(author);
|
||||
await activity.RecordAsync(model.ProjectID, isNew ? "Created" : "Updated", "Book", bookId, model.BookTitle);
|
||||
|
||||
if (model.CoverUpload is { Length: > 0 })
|
||||
|
||||
@ -401,7 +401,7 @@ public sealed class ManuscriptScanPreviewStore(
|
||||
.Select(chapter => new ManuscriptScanChapterReviewDecision
|
||||
{
|
||||
TemporaryChapterKey = chapter.TemporaryChapterKey,
|
||||
Include = !string.IsNullOrWhiteSpace(chapter.Title) && chapter.WordCount > 0,
|
||||
Include = !chapter.IsFrontMatter && !string.IsNullOrWhiteSpace(chapter.Title) && chapter.WordCount > 0,
|
||||
Title = chapter.Title,
|
||||
ChapterNumber = chapter.ChapterNumber
|
||||
})
|
||||
|
||||
@ -17,7 +17,7 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc
|
||||
using var scope=scopes.CreateScope();var access=scope.ServiceProvider.GetRequiredService<PlotLine.Data.IWordCompanionRepository>();
|
||||
if(await access.GetBookStructureAsync(book,user)==null)throw new InvalidOperationException("The selected book is not accessible.");
|
||||
foreach(var expired in pending.Where(p=>p.Value.Expires<=clock.GetUtcNow()).Select(p=>p.Key))pending.TryRemove(expired,out _);
|
||||
var documents=presence.Read(user,book).Where(l=>l.Position.WordAvailable&&l.Position.CanCapture).ToArray();
|
||||
var documents=presence.Read(user,0).Where(l=>(l.Position.BookId==book||l.Position.BookId==0)&&l.Position.WordAvailable&&l.Position.CanCapture).ToArray();
|
||||
if(documents.Length==0)return null;
|
||||
var active=documents.Where(l=>l.Position.Active).ToArray();
|
||||
var selected=active.Length==1?active[0]:documents.Length==1?documents[0]:throw new InvalidOperationException("More than one Word document is linked to this book. Activate the intended document, then retry.");
|
||||
@ -25,7 +25,7 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc
|
||||
if(pending.Count>=128)throw new InvalidOperationException("Manuscript transfers are busy. Try again later.");
|
||||
var state=await scans.StartAsync(user,onboarding,project,book);var id=state.ScanID!.Value;
|
||||
pending[id]=new(user,onboarding,project,book,selected,clock.GetUtcNow().AddMinutes(20));
|
||||
if(!presence.RequestCapture(user,selected,id)){pending.TryRemove(id,out _);await scans.FailAsync(user,onboarding,"Word changed or is busy. Retry the manuscript transfer.");throw new InvalidOperationException("Word changed or is busy. Retry the manuscript transfer.");}
|
||||
if(!presence.RequestCapture(user,selected,id,book)){pending.TryRemove(id,out _);await scans.FailAsync(user,onboarding,"Word changed or is busy. Retry the manuscript transfer.");throw new InvalidOperationException("Word changed or is busy. Retry the manuscript transfer.");}
|
||||
return state;
|
||||
}finally{acceptance.Release();}
|
||||
}
|
||||
@ -54,7 +54,7 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc
|
||||
public async Task<IReadOnlyList<(int User,ManuscriptScanState State)>> Expire()
|
||||
{
|
||||
var failures=new List<(int,ManuscriptScanState)>();
|
||||
foreach(var item in pending.ToArray())if(item.Value.Hash==null&&(item.Value.Expires<=clock.GetUtcNow()||!presence.Read(item.Value.User,item.Value.Book).Any(l=>l.Instance==item.Value.Lease.Instance&&l.Session==item.Value.Lease.Session))){var state=await Fail(item.Value.User,item.Value.Lease.Grant,item.Key);if(state!=null)failures.Add((item.Value.User,state));}
|
||||
foreach(var item in pending.ToArray())if(item.Value.Hash==null&&(item.Value.Expires<=clock.GetUtcNow()||!presence.Read(item.Value.User,0).Any(l=>l.Instance==item.Value.Lease.Instance&&l.Session==item.Value.Lease.Session))){var state=await Fail(item.Value.User,item.Value.Lease.Grant,item.Key);if(state!=null)failures.Add((item.Value.User,state));}
|
||||
return failures;
|
||||
}
|
||||
public async Task<bool> Built(int user,Guid previewId,OnboardingManuscriptBuildResult result)
|
||||
@ -90,15 +90,19 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc
|
||||
}
|
||||
if(position!=capture.End||text.Length!=0)throw new ArgumentException("Manuscript transfer is incomplete.");
|
||||
var chapters=new List<ManuscriptScanChapterPreview>();var scenes=new List<ManuscriptScanScenePreview>();
|
||||
var starts=paragraphs.Select((p,i)=>(p,i)).Where(x=>x.p.Outline==1||Marker(x.p.Tags,"PD-CHAPTER-").HasValue).Select(x=>x.i).ToList();
|
||||
var starts=new List<int>();
|
||||
// Same front-heading vocabulary as the established Office.js importer, only before story starts.
|
||||
for(var i=0;i<paragraphs.Count;i++){var p=paragraphs[i];if(Marker(p.Tags,"PD-CHAPTER-").HasValue||(p.Outline==1&&(starts.Count>0||!FrontMatterHeading(p.Text))))starts.Add(i);}
|
||||
var hasStoryHeading=starts.Count>0;var opening=hasStoryHeading&&starts[0]>0;
|
||||
if(paragraphs.Count>0&&(starts.Count==0||starts[0]!=0))starts.Insert(0,0);
|
||||
for(int c=0;c<starts.Count;c++){
|
||||
var rows=paragraphs.Skip(starts[c]).Take((c+1<starts.Count?starts[c+1]:paragraphs.Count)-starts[c]).ToArray();var first=rows[0];bool heading=first.Outline==1;var key="chapter-"+(c+1);var body=rows.Where(p=>!(p.Index==first.Index&&heading)&&p.Outline!=2&&!Separator(p.Text)).ToArray();var chapterText=string.Concat(body.Select(p=>p.Text));
|
||||
chapters.Add(new(){TemporaryChapterKey=key,ChapterNumber=c+1,Title=heading?first.Text.Trim():Marker(first.Tags,"PD-CHAPTER-").HasValue?"Chapter "+(c+1):"Opening material",ChapterText=chapterText,WordCount=Words(chapterText),StartPosition=first.Index,ExistingChapterID=structure?.Chapters.FirstOrDefault(c=>c.ChapterId==Marker(first.Tags,"PD-CHAPTER-"))?.ChapterId,ParagraphMap=body.Where(p=>!string.IsNullOrWhiteSpace(p.Text)).Select((p,i)=>new ManuscriptScanParagraphMap{StructuralParagraphOrdinal=i+1,WordParagraphIndex=p.Index,Text=p.Text}).ToArray(),SourceParagraphs=rows.Select(p=>new ManuscriptScanSourceParagraph{WordParagraphIndex=p.Index,Text=p.Text,IsBlank=string.IsNullOrWhiteSpace(p.Text),IsChapterHeading=p.Index==first.Index&&heading,IsSceneHeading=p.Outline==2,IsSceneSeparator=Separator(p.Text),IncludeInSourceText=!(p.Index==first.Index&&heading)&&p.Outline!=2&&!Separator(p.Text)}).ToArray()});
|
||||
var rows=paragraphs.Skip(starts[c]).Take((c+1<starts.Count?starts[c+1]:paragraphs.Count)-starts[c]).ToArray();var first=rows[0];bool front=opening&&c==0;bool heading=first.Outline==1&&!front;var number=c+1-(opening?1:0);var key="chapter-"+(c+1);var body=rows.Where(p=>!(p.Index==first.Index&&heading)&&p.Outline!=2&&!Separator(p.Text)).ToArray();var chapterText=string.Concat(body.Select(p=>p.Text));
|
||||
chapters.Add(new(){IsFrontMatter=front,TemporaryChapterKey=key,ChapterNumber=number,Title=front?"Opening material (not a story chapter)":heading?first.Text.Trim():Marker(first.Tags,"PD-CHAPTER-").HasValue?"Chapter "+number:"Manuscript",ChapterText=chapterText,WordCount=Words(chapterText),StartPosition=first.Index,ExistingChapterID=structure?.Chapters.FirstOrDefault(c=>c.ChapterId==Marker(first.Tags,"PD-CHAPTER-"))?.ChapterId,ParagraphMap=body.Where(p=>!string.IsNullOrWhiteSpace(p.Text)).Select((p,i)=>new ManuscriptScanParagraphMap{StructuralParagraphOrdinal=i+1,WordParagraphIndex=p.Index,Text=p.Text}).ToArray(),SourceParagraphs=rows.Select(p=>new ManuscriptScanSourceParagraph{WordParagraphIndex=p.Index,Text=p.Text,IsBlank=string.IsNullOrWhiteSpace(p.Text),IsChapterHeading=p.Index==first.Index&&heading,IsSceneHeading=p.Outline==2,IsSceneSeparator=Separator(p.Text),IncludeInSourceText=!(p.Index==first.Index&&heading)&&p.Outline!=2&&!Separator(p.Text)}).ToArray()});
|
||||
foreach(var row in rows.Where(p=>p.Outline==2||Marker(p.Tags,"PD-SCENE-").HasValue))scenes.Add(new(){TemporaryChapterKey=key,TemporarySceneKey="scene-"+(scenes.Count+1),SceneNumberWithinChapter=scenes.Count(s=>s.TemporaryChapterKey==key)+1,Title=row.Text.Trim(),StartPosition=row.Index,ExistingSceneID=structure?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault(s=>s.SceneId==Marker(row.Tags,"PD-SCENE-"))?.SceneId});
|
||||
}
|
||||
return new(){NativeInstanceID=capture.InstanceId,NativeSessionID=capture.SessionId,NativeRevision=capture.Revision,NativeDocumentEnd=capture.End,NativeParagraphPositions=paragraphs.ToDictionary(p=>p.Index,p=>p.Start),Source="NativeWordCompanion",PreviewID=capture.RequestId,UserID=user,OnboardingID=onboarding,ProjectID=project,BookID=book,DocumentTitle=title,CompanionDocumentIdentifier=capture.ManuscriptId.ToString("D"),ChapterCount=chapters.Count,SceneCount=scenes.Count,TotalWordCount=chapters.Sum(c=>c.WordCount),Chapters=chapters,Scenes=scenes};
|
||||
return new(){NativeInstanceID=capture.InstanceId,NativeSessionID=capture.SessionId,NativeRevision=capture.Revision,NativeDocumentEnd=capture.End,NativeParagraphPositions=paragraphs.ToDictionary(p=>p.Index,p=>p.Start),Source="NativeWordCompanion",PreviewID=capture.RequestId,UserID=user,OnboardingID=onboarding,ProjectID=project,BookID=book,DocumentTitle=title,CompanionDocumentIdentifier=capture.ManuscriptId.ToString("D"),ChapterCount=chapters.Count(c=>!c.IsFrontMatter),SceneCount=scenes.Count,TotalWordCount=chapters.Sum(c=>c.WordCount),Chapters=chapters,Scenes=scenes};
|
||||
}
|
||||
private static bool FrontMatterHeading(string text)=>new[]{"title page","copyright","dedication","contents","table of contents","acknowledgements","acknowledgments","about the author"}.Contains(text.Trim(),StringComparer.OrdinalIgnoreCase);
|
||||
private static int? Marker(string[] tags,string prefix)=>tags.Where(t=>t.StartsWith(prefix,StringComparison.Ordinal)).Select(t=>int.TryParse(t[prefix.Length..],out var id)&&id>0?(int?)id:null).FirstOrDefault(id=>id.HasValue);
|
||||
private static bool Separator(string text)=>text.Trim() is "***" or "* * *" or "#";
|
||||
private static int Words(string text)=>text.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length;
|
||||
|
||||
@ -4,6 +4,9 @@ public sealed record NativeLease(int User,string Grant,DateTimeOffset GrantExpir
|
||||
// Ephemeral liveness, never a persisted association. Server restart means disconnected.
|
||||
public sealed class NativePresenceStore(TimeProvider clock)
|
||||
{
|
||||
private readonly Guid catalogEpoch=Guid.NewGuid();private readonly Dictionary<int,Guid> catalogs=[];
|
||||
public Guid CatalogVersion(int user){lock(gate)return catalogs.GetValueOrDefault(user,catalogEpoch);}
|
||||
public void BooksChanged(int user){lock(gate){if(catalogs.Count>=4096)catalogs.Clear();catalogs[user]=Guid.NewGuid();}}
|
||||
private readonly Dictionary<(int,Guid,Guid),AdapterCommand> navigation=[];
|
||||
private readonly object gate=new();private readonly Dictionary<(int,Guid,Guid),NativeLease> leases=[];private readonly Dictionary<string,DateTimeOffset> revoked=[];
|
||||
private void Prune(){var now=clock.GetUtcNow();foreach(var key in leases.Where(p=>now-p.Value.Updated>=TimeSpan.FromSeconds(45)||p.Value.GrantExpires<=now).Select(p=>p.Key).ToArray()){leases.Remove(key);navigation.Remove(key);}foreach(var key in revoked.Where(p=>p.Value<=now).Select(p=>p.Key).ToArray())revoked.Remove(key);}
|
||||
@ -12,16 +15,16 @@ public sealed class NativePresenceStore(TimeProvider clock)
|
||||
public (int Chapter,int? Scene)? Resolve(int user,NativePresence position,Guid session){lock(gate){if(position.WordSaved!=true||!position.CursorStart.HasValue||!mappings.TryGetValue((user,position.BookId,position.ManuscriptId,session,position.Revision),out var map)||position.CursorStart<0||position.CursorStart>=map.End)return null;var boundary=map.Items.LastOrDefault(i=>i.Start<=position.CursorStart);return boundary.Chapter>0?(boundary.Chapter,boundary.Scene):null;}}
|
||||
public bool Put(int user,string grant,DateTimeOffset expires,Guid instance,Guid session,NativePresence value)
|
||||
{
|
||||
lock(gate){Prune();var key=(user,instance,session);if(instance==Guid.Empty||session==Guid.Empty||(value.WordAvailable&&value.ManuscriptId==Guid.Empty)||value.Revision<0||value.Sequence<=0||value.BookId<=0||value.DocumentTitle==null||value.DocumentTitle.Length>260||value.DocumentTitle.IndexOfAny(['\\','/'])>=0||expires<=clock.GetUtcNow()||revoked.ContainsKey(grant))return false;
|
||||
lock(gate){Prune();var key=(user,instance,session);if(instance==Guid.Empty||session==Guid.Empty||(value.WordAvailable&&value.ManuscriptId==Guid.Empty)||value.Revision<0||value.Sequence<=0||value.BookId<0||value.DocumentTitle==null||value.DocumentTitle.Length>260||value.DocumentTitle.IndexOfAny(['\\','/'])>=0||expires<=clock.GetUtcNow()||revoked.ContainsKey(grant))return false;
|
||||
if(leases.TryGetValue(key,out var prior)){if(prior.Grant!=grant||value.Sequence<=prior.Position.Sequence||value.Revision<prior.Position.Revision)return false;}
|
||||
else if(leases.Count>=4096||leases.Values.Count(p=>p.User==user)>=64)return false;
|
||||
leases[key]=new(user,grant,expires,instance,session,new NativePresence{CanCapture=value.CanCapture,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;}
|
||||
leases[key]=new(user,grant,expires,instance,session,new NativePresence{CanCapture=value.CanCapture,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordRunning=value.WordRunning,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;}
|
||||
}
|
||||
public NativeLease[] Read(int user,int book){lock(gate){Prune();return leases.Values.Where(p=>p.User==user&&(book==0||p.Position.BookId==book)).OrderByDescending(p=>p.Updated).ToArray();}}
|
||||
public bool Navigate(int user,int book,Guid instance,Guid session,Guid manuscript,long revision,int start)
|
||||
{lock(gate){Prune();var key=(user,instance,session);if(!leases.TryGetValue(key,out var lease)||!lease.Position.WordAvailable||lease.Position.BookId!=book||lease.Position.ManuscriptId!=manuscript||lease.Position.Revision!=revision||start<0)return false;navigation[key]=new(){Kind="navigate",SessionId=session,Revision=revision,Chapter=new(){Start=start}};return true;}}
|
||||
public bool RequestCapture(int user,NativeLease selected,Guid request)
|
||||
{lock(gate){Prune();var key=(user,selected.Instance,selected.Session);if(!leases.TryGetValue(key,out var lease)||lease.Grant!=selected.Grant||!lease.Position.CanCapture||navigation.ContainsKey(key))return false;navigation[key]=new(){Id=request,Kind="wizard-capture",SessionId=lease.Session,Revision=lease.Position.Revision};return true;}}
|
||||
public bool RequestCapture(int user,NativeLease selected,Guid request,int book=0)
|
||||
{lock(gate){Prune();var key=(user,selected.Instance,selected.Session);if(!leases.TryGetValue(key,out var lease)||lease.Grant!=selected.Grant||lease.Position.Revision!=selected.Position.Revision||lease.Position.ManuscriptId!=selected.Position.ManuscriptId||(book>0&&lease.Position.BookId!=0&&lease.Position.BookId!=book)||!lease.Position.CanCapture||navigation.ContainsKey(key))return false;navigation[key]=new(){Id=request,BookId=book,Kind="wizard-capture",SessionId=lease.Session,Revision=lease.Position.Revision};return true;}}
|
||||
public AdapterCommand? TakeNavigation(int user,string grant,Guid instance,Guid session)
|
||||
{lock(gate){Prune();var key=(user,instance,session);return leases.TryGetValue(key,out var lease)&&lease.Grant==grant&&navigation.Remove(key,out var command)?command:null;}}
|
||||
public void Remove(int user,string grant,Guid instance,Guid session,long? throughSequence=null){lock(gate)if(leases.TryGetValue((user,instance,session),out var prior)&&prior.Grant==grant&&(!throughSequence.HasValue||prior.Position.Sequence<=throughSequence.Value)){leases.Remove((user,instance,session));navigation.Remove((user,instance,session));}}
|
||||
|
||||
@ -53,7 +53,7 @@ public sealed class OnboardingService(
|
||||
IManuscriptTextStatisticsService manuscriptTextStatistics,
|
||||
ICoreImportCharacterMappingService coreImportCharacterMapping,
|
||||
ICoreImportBasicLocationService coreImportBasicLocations,
|
||||
ICurrentUserService currentUser) : IOnboardingService
|
||||
ICurrentUserService currentUser,IManuscriptCaptureRepository? captureRepository=null) : IOnboardingService
|
||||
{
|
||||
private static readonly HashSet<string> WritingJourneys = new(StringComparer.Ordinal)
|
||||
{
|
||||
@ -346,7 +346,7 @@ public sealed class OnboardingService(
|
||||
var repairedSceneSources = missingSceneSources.Count > 0;
|
||||
if (repairedSceneSources)
|
||||
{
|
||||
await PublishBuildProgress(userId, preview.PreviewID, "Completing saved scene source text before updating Word markers...", 65, progress, existingBuild);
|
||||
await PublishBuildProgress(userId, preview.PreviewID, preview.Source=="NativeWordCompanion"?"Completing saved scene source text on PlotDirector...":"Completing saved scene source text before updating Word markers...", 65, progress, existingBuild);
|
||||
var recoveredScenes = await AnalyseApprovedChaptersAsync(userId, preview, review, book, progress);
|
||||
await SaveStructuralChapterSourcesAsync(preview, existingBuild, recoveredScenes);
|
||||
await SaveSceneManuscriptSourcesAsync(preview, recoveredScenes, existingBuild);
|
||||
@ -365,9 +365,9 @@ public sealed class OnboardingService(
|
||||
userId,
|
||||
preview.PreviewID,
|
||||
repairedSceneSources
|
||||
? "Scene source text recovered. Updating Word markers."
|
||||
? preview.Source=="NativeWordCompanion"?"Scene source text recovered on PlotDirector. Word markers were not rewritten.":"Scene source text recovered. Updating Word markers."
|
||||
: await coreImportBasicLocations.IsCompleteAsync(userId, preview.PreviewID)
|
||||
? "Resuming Word marker sync. No scene detection was rerun."
|
||||
? preview.Source=="NativeWordCompanion"?"Saved structure recovered. Word markers were not rewritten.":"Resuming Word marker sync. No scene detection was rerun."
|
||||
: "Basic location review is ready. Review locations before character candidates.",
|
||||
90,
|
||||
progress,
|
||||
@ -427,7 +427,7 @@ public sealed class OnboardingService(
|
||||
CharactersReused = result.CharactersReused,
|
||||
SceneAppearancesCreated = result.SceneAppearancesCreated,
|
||||
AlreadyBuilt = result.AlreadyBuilt,
|
||||
Message = "Manuscript structure created. Updating and saving Word markers...",
|
||||
Message = preview.Source=="NativeWordCompanion"?"Manuscript structure created on PlotDirector. Word markers were not rewritten.":"Manuscript structure created. Updating and saving Word markers...",
|
||||
ChapterMappings = result.ChapterMappings,
|
||||
SceneMappings = result.SceneMappings,
|
||||
CharacterMappings = result.CharacterMappings,
|
||||
@ -460,7 +460,7 @@ public sealed class OnboardingService(
|
||||
preview.PreviewID,
|
||||
locationReview is not null && !await coreImportBasicLocations.IsCompleteAsync(userId, preview.PreviewID)
|
||||
? "Basic location review is ready. Review locations before character candidates."
|
||||
: "Updating Word document with scene markers. Keep Word open while the document is saved.",
|
||||
: preview.Source=="NativeWordCompanion"?"Structure saved on PlotDirector. Native Word markers have not been rewritten.":"Updating Word document with scene markers. Keep Word open while the document is saved.",
|
||||
90,
|
||||
progress);
|
||||
return result;
|
||||
@ -498,7 +498,7 @@ public sealed class OnboardingService(
|
||||
$"Analysing Chapter {chapterIndex + 1:N0} of {chapterDecisions.Count:N0} - {chapterDecision.Title}",
|
||||
analysisPercent,
|
||||
progress);
|
||||
var analysis = await structureAnalysis.AnalyseChapterAsync(new ManuscriptStructureAnalysisRequest
|
||||
var request = new ManuscriptStructureAnalysisRequest
|
||||
{
|
||||
ProjectID = preview.ProjectID,
|
||||
BookID = preview.BookID,
|
||||
@ -512,7 +512,16 @@ public sealed class OnboardingService(
|
||||
ChapterText = chapterPreview.ChapterText,
|
||||
ParagraphMap = chapterPreview.ParagraphMap,
|
||||
SourceParagraphs = chapterPreview.SourceParagraphs
|
||||
});
|
||||
};
|
||||
// The request hash includes prose, paragraph maps, review title/number and story context.
|
||||
// Only successful identical requests are reused; failed chapters remain explicitly retryable.
|
||||
var fingerprint=Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(request)));
|
||||
var checkpoint=preview.Source=="NativeWordCompanion"&&captureRepository!=null?await captureRepository.GetAnalysis(userId,preview.PreviewID,fingerprint):null;
|
||||
var analysis=checkpoint==null?null:JsonSerializer.Deserialize<ManuscriptStructureAnalysisResult>(checkpoint);
|
||||
if(analysis?.Success!=true){
|
||||
analysis=await structureAnalysis.AnalyseChapterAsync(request);
|
||||
if(preview.Source=="NativeWordCompanion"&&captureRepository!=null)await captureRepository.SaveAnalysis(userId,preview.PreviewID,fingerprint,JsonSerializer.Serialize(analysis));
|
||||
}
|
||||
|
||||
if (!analysis.Success)
|
||||
{
|
||||
@ -936,7 +945,7 @@ public sealed class OnboardingService(
|
||||
CharactersReused = existingBuild.CharactersReused,
|
||||
SceneAppearancesCreated = existingBuild.SceneAppearancesCreated,
|
||||
AlreadyBuilt = true,
|
||||
Message = "Manuscript structure already exists. Updating and saving Word markers...",
|
||||
Message = preview.Source=="NativeWordCompanion"?"Manuscript structure already exists on PlotDirector. Word markers were not rewritten.":"Manuscript structure already exists. Updating and saving Word markers...",
|
||||
ChapterMappings = existingBuild.ChapterMappings,
|
||||
SceneMappings = existingBuild.SceneMappings,
|
||||
CharacterMappings = existingBuild.CharacterMappings,
|
||||
@ -1445,7 +1454,7 @@ public sealed class OnboardingService(
|
||||
ChapterNumber = chapter.ChapterNumber,
|
||||
Title = chapter.Title,
|
||||
ReviewTitle = decision?.Title ?? chapter.Title,
|
||||
Include = decision?.Include ?? (!string.IsNullOrWhiteSpace(chapter.Title) && chapter.WordCount > 0),
|
||||
Include = decision?.Include ?? (!chapter.IsFrontMatter && !string.IsNullOrWhiteSpace(chapter.Title) && chapter.WordCount > 0),
|
||||
WordCount = chapter.WordCount,
|
||||
Scenes = scenes
|
||||
};
|
||||
|
||||
@ -394,7 +394,12 @@ public static class StoryIntelligenceAiJsonParser
|
||||
}
|
||||
catch (JsonException strictEx)
|
||||
{
|
||||
var repair = StoryIntelligenceJsonRepair.Repair(rawAssistantOutput);
|
||||
// Only an unambiguous spelled decimal digit in a confidence field is repaired.
|
||||
// Scene numbers and paragraph coordinates are never inferred or repaired here.
|
||||
var confidenceWarnings=new List<string>();
|
||||
var repairInput=typeof(T)==typeof(PlotLine.Models.ChapterStructureModel)&&strictEx.Path?.EndsWith(".confidence",StringComparison.OrdinalIgnoreCase)==true
|
||||
? RepairConfidenceDigits(extraction.Json,confidenceWarnings):rawAssistantOutput;
|
||||
var repair = StoryIntelligenceJsonRepair.Repair(repairInput);
|
||||
if (!repair.Success)
|
||||
{
|
||||
return StoryIntelligenceAiJsonParseResult<T>.Failed(
|
||||
@ -407,7 +412,7 @@ public static class StoryIntelligenceAiJsonParser
|
||||
try
|
||||
{
|
||||
var parsed = JsonSerializer.Deserialize<T>(repair.RepairedJson, jsonOptions);
|
||||
var warnings = BuildRepairWarnings(repair.Warnings, strictEx.Path);
|
||||
var warnings = BuildRepairWarnings(confidenceWarnings.Concat(repair.Warnings).ToArray(), strictEx.Path);
|
||||
return StoryIntelligenceAiJsonParseResult<T>.Ok(
|
||||
extraction.Json,
|
||||
repair.RepairedJson,
|
||||
@ -423,6 +428,24 @@ public static class StoryIntelligenceAiJsonParser
|
||||
}
|
||||
}
|
||||
|
||||
private static string RepairConfidenceDigits(string json,List<string> warnings)
|
||||
{
|
||||
var result=new StringBuilder(json.Length);var cursor=0;
|
||||
for(var i=0;i<json.Length;i++){
|
||||
if(json[i]!='"')continue;
|
||||
var start=i++;while(i<json.Length){if(json[i]=='\\'){i+=2;continue;}if(json[i]=='"')break;i++;}
|
||||
if(i>=json.Length)break;
|
||||
if(json.Substring(start,i-start+1)!="\"confidence\"")continue;
|
||||
var match=Regex.Match(json[(i+1)..],@"^\s*:\s*0\.\s*(zero|one|two|three|four|five|six|seven|eight|nine)(?=\s*[,}])",RegexOptions.IgnoreCase|RegexOptions.CultureInvariant,TimeSpan.FromSeconds(1));
|
||||
if(!match.Success)continue;
|
||||
var digit=Array.IndexOf(new[]{"zero","one","two","three","four","five","six","seven","eight","nine"},match.Groups[1].Value.ToLowerInvariant());
|
||||
result.Append(json,cursor,i+1-cursor).Append(": 0.").Append(digit);
|
||||
i+=match.Length;cursor=i+1;
|
||||
warnings.Add("Normalised a spelled decimal digit in confidence; scene boundaries unchanged.");
|
||||
}
|
||||
return result.Append(json,cursor,json.Length-cursor).ToString();
|
||||
}
|
||||
|
||||
private static IReadOnlyList<string> BuildRepairWarnings(IReadOnlyList<string> repairWarnings, string? strictErrorPath)
|
||||
{
|
||||
var warnings = new List<string>();
|
||||
|
||||
28
PlotLine/Sql/239_ManuscriptAnalysisCheckpoints.sql
Normal file
28
PlotLine/Sql/239_ManuscriptAnalysisCheckpoints.sql
Normal file
@ -0,0 +1,28 @@
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
-- Analysis is a sidecar to the immutable accepted source. Never rewrite Payload or PayloadHash.
|
||||
IF COL_LENGTH('dbo.OnboardingManuscriptCaptures','AnalysisCheckpoints') IS NULL
|
||||
ALTER TABLE dbo.OnboardingManuscriptCaptures ADD AnalysisCheckpoints nvarchar(max) NOT NULL CONSTRAINT DF_ManuscriptCapture_Analysis DEFAULT(N'{}');
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.OnboardingManuscriptChapterAnalysis
|
||||
@Action varchar(8),@UserID int,@PreviewID uniqueidentifier,@RequestHash varchar(64),@Result nvarchar(max)=NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
IF LEN(@RequestHash)<>64 OR @RequestHash COLLATE Latin1_General_100_BIN2 LIKE '%[^0-9A-F]%' THROW 51000,'Invalid analysis identity',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptCaptures c JOIN dbo.Books b ON b.BookID=c.BookID JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE c.PreviewID=@PreviewID AND c.UserID=@UserID) THROW 51000,'Capture access denied',1;
|
||||
DECLARE @path nvarchar(100)=N'$."'+@RequestHash+N'"';
|
||||
IF @Action='get' BEGIN SELECT JSON_QUERY(AnalysisCheckpoints,@path) FROM dbo.OnboardingManuscriptCaptures WHERE PreviewID=@PreviewID AND UserID=@UserID;RETURN;END;
|
||||
IF @Action<>'save' THROW 51000,'Unknown analysis operation',1;
|
||||
IF ISJSON(@Result)<>1 OR DATALENGTH(@Result)>2*1024*1024 THROW 51000,'Invalid analysis result',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @json nvarchar(max);
|
||||
SELECT @json=AnalysisCheckpoints FROM dbo.OnboardingManuscriptCaptures WITH(UPDLOCK,HOLDLOCK) WHERE PreviewID=@PreviewID AND UserID=@UserID;
|
||||
IF @json IS NULL THROW 51000,'Capture no longer available',1;
|
||||
SET @json=JSON_MODIFY(@json,@path,JSON_QUERY(@Result));
|
||||
IF DATALENGTH(@json)>32*1024*1024 THROW 51000,'Analysis checkpoint limit reached',1;
|
||||
UPDATE dbo.OnboardingManuscriptCaptures SET AnalysisCheckpoints=@json WHERE PreviewID=@PreviewID AND UserID=@UserID;
|
||||
COMMIT;
|
||||
END;
|
||||
GO
|
||||
@ -293,7 +293,9 @@
|
||||
<small>Adds optional PlotDirector-only titles such as "Behind the Fire Exit". Titles can be edited later and do not change the manuscript.</small>
|
||||
</span>
|
||||
</label>
|
||||
<p>Keep Word open while PlotDirector detects scenes and writes the scene markers.</p>
|
||||
<p>@(ViewData["NativeCapture"] is true
|
||||
? "Once your manuscript has been received, scene detection runs on PlotDirector’s server. You may close Word. Native Companion imports do not write scene markers to Word."
|
||||
: "Keep Word open while PlotDirector detects scenes and writes the scene markers.")</p>
|
||||
<div class="onboarding-build-panel" data-onboarding-build-panel hidden>
|
||||
<div>
|
||||
<p class="onboarding-scan-next">Detecting scenes</p>
|
||||
|
||||
@ -134,7 +134,7 @@
|
||||
<input type="hidden" name="Chapters[@chapterIndex].Include" value="false" />
|
||||
<input type="hidden" name="Chapters[@chapterIndex].Title" value="@chapter.ReviewTitle" />
|
||||
<span class="onboarding-review-chapter-row__title">
|
||||
<strong>Chapter @chapter.ChapterNumber</strong>
|
||||
<strong>@(chapter.ChapterNumber==0?"Front matter":$"Chapter {chapter.ChapterNumber}")</strong>
|
||||
<span>@chapter.ReviewTitle</span>
|
||||
</span>
|
||||
<small>@chapter.WordCount.ToString("N0") words</small>
|
||||
|
||||
@ -4,10 +4,10 @@
|
||||
function offline(message){root.dataset.nativeAuthority=root.dataset.officeConnected==='true'?'false':'true';root.dataset.connected='false';root.classList.remove('is-connected');root.classList.add('is-offline');text.textContent=message;root.title=message+' · saved PlotDirector information remains available.';}
|
||||
async function update(){if(pending||document.hidden)return;pending=true;try{
|
||||
const response=await fetch('/native-companion/status',{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw new Error();const leases=(await response.json()).filter(l=>Date.parse(l.expires)>Date.now());const active=leases.filter(l=>l.active&&l.wordAvailable),words=leases.filter(l=>l.wordAvailable);const lease=active.length===1?active[0]:words.length===1?words[0]:words.length===0?leases[0]:null;if(words.length>1&&active.length!==1){seen=true;offline('Choose an active Word document');}
|
||||
if(lease){seen=true;root.dataset.nativeAuthority='true';root.dataset.connectionState='Connected';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');text.textContent=lease.wordAvailable?'Word connected':'Companion connected';root.title=lease.wordAvailable?lease.documentTitle+' · verified document heartbeat · last update '+new Date(lease.updated).toLocaleTimeString():'Companion connected; open a linked manuscript in Word.';}
|
||||
if(lease){leases.connectionState="Connected";leases.known=true;seen=true;root.dataset.nativeAuthority='true';root.dataset.connectionState='Connected';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');text.textContent=lease.wordAvailable?'Word connected':'Companion connected';root.title=lease.wordAvailable?lease.documentTitle+' · verified document heartbeat · last update '+new Date(lease.updated).toLocaleTimeString():'Companion connected; open a linked manuscript in Word.';}
|
||||
else {
|
||||
const stateResponse=await fetch('/native-companion/connection-state',{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});
|
||||
const device=stateResponse.ok?await stateResponse.json():null;
|
||||
const device=stateResponse.ok?await stateResponse.json():null;leases.connectionState=device?.state||"Disconnected";leases.known=!!device?.known;
|
||||
if(device?.known){seen=true;const label=device.state==='Connected'?'Companion connected · Word not connected':device.state;offline(label);root.dataset.connectionState=device.state;if(device.state==='Connected'){root.dataset.nativeAuthority='true';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');root.title='Approved Companion is connected. No live Word document is registered.';}}
|
||||
else if(seen)offline('Word disconnected or stale');
|
||||
}window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases}));
|
||||
|
||||
@ -1,4 +1,13 @@
|
||||
(() => {
|
||||
// Uses the existing native presence stream; no extra polling or authentication flow.
|
||||
window.PlotDirectorNativeImportState=(leases,book,now=Date.now())=>{
|
||||
const live=(leases||[]).filter(l=>!l.expires||Date.parse(l.expires)>now),words=live.filter(l=>l.wordAvailable);
|
||||
const candidates=words.filter(l=>l.canCapture&&(l.bookId===0||!book||l.bookId===book)),active=candidates.filter(l=>l.active);
|
||||
const doc=active.length===1?active[0]:candidates.length===1?candidates[0]:null;
|
||||
const connected=live.length>0||leases?.connectionState==='Connected';
|
||||
const label=doc?(doc.bookId===0?'Manuscript open · not yet associated with this book':'Manuscript connected · ready to import'):candidates.length>1?'Choose the active Word manuscript':words.length?'Manuscript belongs to another book · change its association':live.some(l=>l.wordRunning)?'Word connected · open a manuscript':connected?'Companion authenticated · Word unavailable':leases?.connectionState==='Reconnecting'?'Companion reconnecting':leases?.connectionState==='Action required'?'Companion needs authorisation':'Companion disconnected';
|
||||
return {known:!!leases?.known||live.length>0,connected,document:doc,ready:!!doc,label};
|
||||
};
|
||||
const roots = [...document.querySelectorAll("[data-word-companion-presence]")]
|
||||
.filter((node) => node.dataset.wordCompanionPresence !== "false");
|
||||
if (roots.length === 0 || !window.signalR) {
|
||||
@ -21,17 +30,17 @@
|
||||
return Number.isNaN(date.getTime()) ? "No heartbeat yet" : `Last heartbeat ${date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`;
|
||||
};
|
||||
|
||||
let nativeDocument=null,lastOfficeStatus=null;
|
||||
let nativeDocument=null,nativeState=null,lastOfficeStatus=null;
|
||||
window.addEventListener('native-companion-presence',event=>{
|
||||
const book=Number(document.querySelector('[data-onboarding-scan-panel]')?.dataset.bookId);
|
||||
const candidates=(event.detail||[]).filter(l=>l.wordAvailable&&(!book||l.bookId===book));
|
||||
const active=candidates.filter(l=>l.active);nativeDocument=active.length===1?active[0]:candidates.length===1?candidates[0]:null;
|
||||
nativeState=window.PlotDirectorNativeImportState(event.detail,book);nativeDocument=nativeState.document;
|
||||
applyStatus(lastOfficeStatus||{isConnected:false});
|
||||
});
|
||||
const applyStatus = (status) => {
|
||||
lastOfficeStatus=status;
|
||||
for(const root of roots)root.dataset.officeConnected=String(!!field(status,"isConnected","IsConnected"));
|
||||
if(nativeDocument) status={isConnected:true,documentOpen:true,currentDocumentName:nativeDocument.documentTitle,companionVersion:'Native',lastHeartbeatUtc:nativeDocument.updated};
|
||||
const nativeMode=nativeState?.known&&(nativeState.ready||!field(status,"isConnected","IsConnected"));
|
||||
if(nativeMode)status={isConnected:nativeState.connected,documentOpen:nativeState.ready,currentDocumentName:nativeDocument?.documentTitle,companionVersion:'Native',lastHeartbeatUtc:nativeDocument?.updated};
|
||||
const connected = !!field(status, "isConnected", "IsConnected");
|
||||
const documentOpen = !!field(status, "documentOpen", "DocumentOpen");
|
||||
const version = field(status, "companionVersion", "CompanionVersion") || "Waiting";
|
||||
@ -59,12 +68,15 @@
|
||||
node.textContent = label;
|
||||
});
|
||||
document.querySelectorAll("[data-word-companion-compact-status-label]").forEach((node) => {
|
||||
node.textContent = connected ? "Word Companion connected" : "Word Companion disconnected";
|
||||
node.textContent = nativeMode?nativeState.label:connected ? "Word Companion connected" : "Word Companion disconnected";
|
||||
});
|
||||
document.querySelectorAll("[data-word-companion-waiting-status]").forEach((node) => {
|
||||
node.textContent = connected ? "Word Companion Connected" : "Word Companion disconnected. Waiting for reconnection...";
|
||||
});
|
||||
document.querySelectorAll("[data-word-companion-connected-copy]").forEach((node) => {
|
||||
if(nativeMode&¤tScanStatus!=="Complete"&¤tScanStatus!=="Running"){
|
||||
node.textContent=nativeState.ready&&nativeDocument.bookId===0?"Import manuscript will link this document to the selected book and transfer it only after your request.":nativeState.label;return;
|
||||
}
|
||||
if (!connected) {
|
||||
node.textContent = "Open Word and start the Companion. This page will update automatically.";
|
||||
} else if (!documentOpen) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user