208 lines
33 KiB
C#
208 lines
33 KiB
C#
using PlotDirector.Companion.Protocol;
|
|
namespace PlotDirector.Companion.Agent;
|
|
|
|
// One control centre in the existing agent. Exact-session commands only; no COM or UI objects.
|
|
public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway cloud,ChapterAiWork ai)
|
|
{
|
|
private readonly Guid agentInstance=Guid.NewGuid(),agentSession=Guid.NewGuid();private int lastBook;private Guid lastAuthentication;private long agentSequence;private long presenceSequence=DateTime.UtcNow.Ticks;private int uploading;private DateTime lastAgentPresence;private bool agentOnlyPublished;
|
|
private bool ParagraphCapable(Guid instance){lock(gate)return paragraphInstances.Contains(instance);}
|
|
private readonly ParagraphSnapshotCache paragraphSnapshots=new();
|
|
private readonly HashSet<Guid> paragraphInstances=[];private readonly HashSet<Guid> chapterInstances=[];
|
|
private readonly object gate=new();private readonly Dictionary<Guid,TrayDocument> documents=[];
|
|
private readonly Dictionary<Guid,Queue<AdapterCommand>> commands=[];private readonly Dictionary<Guid,Guid> leases=[];private readonly HashSet<Guid> captureInstances=[];private readonly HashSet<Guid> maintenanceInstances=[];private readonly Dictionary<Guid,(Guid Session,Guid Manuscript,Guid Authentication,string Kind,DateTime Started)> maintenance=[];private readonly Dictionary<(Guid,Guid),(Guid Manuscript,Guid Authentication,int Book,DateTime Expires)> reconnectBindings=[];
|
|
public event Action? OpenRequested;
|
|
public TrayDocument[] Documents {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).ToArray();}}
|
|
public TrayDocument[] PresentationDocuments {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).Select(d=>d.Snapshot()).ToArray();}}
|
|
public void Attach(Guid instance,Guid lease,bool capture=false,bool canMaintain=false,bool paragraphs=false,bool chapters=false){lock(gate){Disconnected(instance);if(chapters)chapterInstances.Add(instance);else chapterInstances.Remove(instance);if(paragraphs)paragraphInstances.Add(instance);else paragraphInstances.Remove(instance);leases[instance]=lease;if(canMaintain)maintenanceInstances.Add(instance);else maintenanceInstances.Remove(instance);if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}}
|
|
public Message Exchange(Guid instance,Message request,Message answer,Guid lease=default)
|
|
{
|
|
lock(gate)
|
|
{
|
|
if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return answer;
|
|
if(answer.Status is "wrong-instance" or "stale-sequence" or "stale-revision" or "invalid-documents" or "foreign-session-identity" or "unknown-session")return answer;
|
|
if(request.Kind=="tray-open")OpenRequested?.Invoke();
|
|
if(request.Kind is "document" or "reconcile"){
|
|
if(request.Kind=="reconcile")foreach(var prior in documents.Values.Where(d=>d.Instance==instance&&!request.Documents.Any(v=>v.SessionId==d.Session)).ToArray())Remove(prior.Session);
|
|
foreach(var descriptor in request.Documents){
|
|
if(sessions.Descriptor(instance,descriptor.SessionId)==null)continue;
|
|
if(!documents.TryGetValue(descriptor.SessionId,out var d))documents[descriptor.SessionId]=d=new(){Session=descriptor.SessionId,Instance=instance};
|
|
if(d.Revision!=descriptor.Revision){if(d.AssociationRequest!=Guid.Empty){d.AssociationRequest=Guid.Empty;d.AssociationNotice="Word changed before the association was confirmed. Check the document and retry.";}foreach(var pending in maintenance.Where(p=>p.Value.Session==d.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(pending);d.MaintenanceReport="Stopped: document revision changed; inspect before retrying cleanup.";}Cancel(d,notifyWord:false);d.LastChapterInterruption="Document revision changed; waiting for saved-state evidence.";d.WordSaved=null;d.Chapters=[];d.FailedChapters.Clear();d.Words=null;d.ChapterId=null;d.SceneId=null;d.ChapterTitle="";d.SceneTitle="";d.LastPresenceKey="";d.Status="Document changed. Detect chapters to refresh this snapshot.";}
|
|
if(reconnectBindings.Remove((instance,descriptor.SessionId),out var binding)&&binding.Expires>DateTime.UtcNow&&binding.Manuscript==descriptor.ManuscriptId&&binding.Authentication==cloud.Status().AuthenticationContext){d.Book=binding.Book;d.Authentication=binding.Authentication;}
|
|
d.Revision=descriptor.Revision;d.Manuscript=descriptor.ManuscriptId;d.Title=descriptor.Title;d.RememberedBook=descriptor.RememberedBook;d.AssociationSite=descriptor.AssociationSite;d.Observed=DateTime.UtcNow;
|
|
}
|
|
}
|
|
if(documents.TryGetValue(request.SessionId,out var doc)&&request.Revision==doc.Revision){
|
|
if(request.Kind=="close")Remove(doc.Session);
|
|
else{
|
|
doc.Observed=DateTime.UtcNow;
|
|
if(request.Kind=="active"){foreach(var d in documents.Values)d.Active=false;doc.Active=true;}
|
|
if(request.Kind=="selection"){if(ChapterCapable(instance)&&(doc.Cursor!=request.Start||doc.WordSaved!=request.WordSaved)){ChapterCursorEvidence.Invalidate(doc);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(doc.WordSaved==true&&doc.RibbonNotice?.State=="Save required")doc.RibbonNotice=null;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}}
|
|
ChapterFrame(doc,request,answer);
|
|
if(request.Kind is "tray-sync" or "tray-repair")ReceiveChapterRibbonRequest(doc,request.Kind);
|
|
if ((request.Kind is "tray-context" or "tray-intent") && answer.Status == "ok")
|
|
_ = OpenRibbonWorkspace(doc.Session, request.Revision, request.Kind == "tray-context" ? "context" : "intent");
|
|
if (request.Kind == "tray-workspace" && answer.Status == "ok")
|
|
_ = OpenRibbonWorkspace(doc.Session, request.Revision, "book");
|
|
CaptureFrame(doc,request,answer);
|
|
if((request.Kind=="selection"||request.Kind=="snapshot-end")&&!ChapterCapable(instance)){doc.ChapterId=answer.ChapterId;doc.SceneId=answer.SceneId;doc.ChapterTitle=answer.ChapterTitle;doc.SceneTitle=answer.SceneTitle;}
|
|
if(answer.WordCount.HasValue)doc.Words=answer.WordCount;
|
|
if(request.Kind.StartsWith("snapshot-",StringComparison.Ordinal)&&answer.Status is not ("ok" or "analysis-complete" or "awaiting-structure")){Cancel(doc);doc.Status="Local reading failed: "+answer.Status+". Detect chapters again.";}
|
|
if(request.Kind=="snapshot-fragment")doc.Progress=answer.Progress;
|
|
if(request.Kind=="snapshot-end"&&answer.Status=="analysis-complete"){doc.Chapters=sessions.Chapters(instance,doc.Session);doc.Status=$"Detected {doc.Chapters.Length} Heading 1 / existing-marker chapters. Scenes require explicit server AI analysis.";doc.Progress=100;}
|
|
if(request.Kind=="adapter-result"&&maintenance.Remove(request.SnapshotId,out var operation)&&operation.Session==doc.Session){doc.MaintenanceReport=request.OperationMessage;if(request.OperationMessage.StartsWith("Complete:",StringComparison.Ordinal)&&operation.Kind is "reset" or "clean"){cloud.ForgetBinding(operation.Manuscript,operation.Authentication);doc.Book=0;doc.AssociationRequest=Guid.Empty;doc.AssociationNeedsSave=false;doc.AssociationNotice="";doc.RememberedBook=null;doc.AssociationSite="";doc.ChapterId=null;doc.SceneId=null;doc.LastPresenceKey="";_=cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);} }
|
|
else if(request.Kind=="adapter-result"&&request.SnapshotId==doc.AssociationRequest&&doc.AssociationRequest!=Guid.Empty){
|
|
doc.AssociationRequest=Guid.Empty;
|
|
doc.AssociationNeedsSave=request.OperationMessage=="association-written";
|
|
doc.AssociationNotice=doc.AssociationNeedsSave?"Book remembered in Word. Save the document to keep this association.":request.OperationMessage=="ok"?"Update the Word add-in to confirm the association was written.":request.OperationMessage;
|
|
}
|
|
else if(request.Kind=="adapter-result"&&!IsChapterCommand(doc,request.SnapshotId)&&!request.Action.StartsWith("chapter-",StringComparison.Ordinal)&&request.OperationMessage!="ok"&&request.OperationMessage!="association-written"){doc.Status=request.OperationMessage;Cancel(doc);}
|
|
if(request.Kind=="ai-cancel"){Cancel(doc);doc.Status="Extraction cancelled or document changed. Successful server suggestions are retained.";}
|
|
if(request.Kind=="metrics")doc.WordDiagnostics=request.OperationMessage.Length<=6000?request.OperationMessage:"Diagnostics size exceeded";
|
|
if(request.Kind=="ai-fragment")doc.Progress=answer.Progress;
|
|
if(request.Kind.StartsWith("ai-",StringComparison.Ordinal)&&answer.Status!="ok"){doc.Status="Chapter could not be read: "+answer.Status;Cancel(doc);}
|
|
}
|
|
}
|
|
if(documents.TryGetValue(request.SessionId,out var activeDocument)&&ChapterCapable(instance)&&request.Kind is "selection" or "metrics" or "tray-sync" or "tray-repair"){
|
|
answer.ChapterStatusProvided=true;answer.BookId=activeDocument.Book;answer.BookTitle=cloud.Status().Books.FirstOrDefault(b=>b.BookId==activeDocument.Book)?.BookTitle??"";answer.ChapterTitle=activeDocument.ChapterTitle;answer.SceneTitle=activeDocument.SceneTitle;answer.ChapterProgress=VisibleChapterProgress(activeDocument);
|
|
}
|
|
if(commands.TryGetValue(instance,out var queue)&&queue.Count>0)answer.Command=queue.Dequeue();
|
|
return answer;
|
|
}
|
|
}
|
|
public void Disconnected(Guid instance,Guid lease=default){lock(gate){if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return;leases.Remove(instance);chapterInstances.Remove(instance);paragraphInstances.Remove(instance);captureInstances.Remove(instance);maintenanceInstances.Remove(instance);foreach(var expired in reconnectBindings.Where(p=>p.Value.Expires<=DateTime.UtcNow).Select(p=>p.Key).ToArray())reconnectBindings.Remove(expired);foreach(var doc in documents.Values.Where(d=>d.Instance==instance).ToArray()){if(doc.Book>0&&reconnectBindings.Count<256)reconnectBindings[(instance,doc.Session)]=(doc.Manuscript,doc.Authentication,doc.Book,DateTime.UtcNow.AddMinutes(2));Remove(doc.Session);}commands.Remove(instance);}}
|
|
private void Remove(Guid session){chapterWork.Remove(session);paragraphSnapshots.Remove(session);foreach(var key in maintenance.Where(p=>p.Value.Session==session).Select(p=>p.Key).ToArray())maintenance.Remove(key);if(documents.Remove(session,out var doc)){Cancel(doc);_ = cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);}}
|
|
private bool Queue(TrayDocument doc,AdapterCommand command){if(!commands.TryGetValue(doc.Instance,out var queue))commands[doc.Instance]=queue=new();if(queue.Count>=16){doc.Status="Word request queue is busy. Retry after current operation.";return false;}command.SessionId=doc.Session;command.Revision=doc.Revision;queue.Enqueue(command);return true;}
|
|
public bool CanMaintain(Guid session){lock(gate)return documents.TryGetValue(session,out var d)&&maintenanceInstances.Contains(d.Instance);}
|
|
public void Maintain(Guid session,string kind)
|
|
{
|
|
if(!DocumentMaintenancePolicy.IsAction(kind))throw new ArgumentException("Unknown maintenance action.");
|
|
lock(gate){if(!documents.TryGetValue(session,out var doc)||!maintenanceInstances.Contains(doc.Instance))throw new InvalidOperationException("Update the Word add-in to use document maintenance.");
|
|
foreach(var expired in maintenance.Where(p=>DateTime.UtcNow-p.Value.Started>TimeSpan.FromMinutes(3)).Select(p=>p.Key).ToArray())maintenance.Remove(expired);
|
|
if(maintenance.Values.Any(v=>v.Session==session))throw new InvalidOperationException("Wait for the current document inspection or cleanup.");
|
|
Cancel(doc);var command=new AdapterCommand{Kind="maintenance-"+kind};if(Queue(doc,command)){maintenance[command.Id]=(session,doc.Manuscript,doc.Authentication,kind,DateTime.UtcNow);doc.MaintenanceReport="Working in short Word batches…";}}
|
|
}
|
|
public void Detect(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Completed.Clear();doc.FailedChapters.Clear();doc.Status="Reading chapters in bounded Word batches…";doc.Progress=0;Queue(doc,new(){Kind="detect"});}}
|
|
public void SelectBook(Guid session,int book,bool remember)
|
|
{
|
|
lock(gate){if(!documents.TryGetValue(session,out var doc))return;var state=cloud.Status();if(!cloud.Allows(state.AuthenticationContext,book))throw new InvalidOperationException("Sign in and select an authorised book.");Cancel(doc);var command=new AdapterCommand{Kind="associate",BookId=book,AuthenticationContext=state.AuthenticationContext,Site=state.ServerUrl,Remember=remember};if(!Queue(doc,command))throw new InvalidOperationException(doc.Status);doc.Book=book;cloud.RememberBinding(doc.Manuscript,book,state.AuthenticationContext);doc.ChapterId=null;doc.SceneId=null;doc.LastPresenceKey="";doc.Authentication=state.AuthenticationContext;lastBook=book;lastAuthentication=doc.Authentication;doc.Status="Book association selected for this Windows user and PlotDirector account.";doc.AssociationRequest=remember?command.Id:Guid.Empty;doc.AssociationNeedsSave=false;doc.AssociationNotice=remember?"Writing book association to Word…":"";
|
|
}
|
|
}
|
|
public void Analyse(Guid session,IEnumerable<int> starts)
|
|
{
|
|
lock(gate){if(!documents.TryGetValue(session,out var doc)||!cloud.Allows(doc.Authentication,doc.Book))throw new InvalidOperationException("Connect and select an authorised book first.");if(doc.Job!=Guid.Empty)throw new InvalidOperationException("Cancel the current chapter batch first.");
|
|
var selection=starts.Distinct().ToHashSet();var chapters=doc.Chapters.Where(c=>selection.Contains(c.Start)&&c.End>c.Start).ToArray();if(chapters.Length==0)throw new InvalidOperationException("Detect and select Heading 1 chapters first.");
|
|
doc.Pending.Clear();foreach(var chapter in chapters)if(!doc.Completed.Contains((doc.Revision,doc.Book,chapter.Start)))doc.Pending.Enqueue(chapter);
|
|
doc.Total=doc.Pending.Count;doc.Done=0;doc.Failed=0;doc.Retained=0;Next(doc);
|
|
}
|
|
}
|
|
private void Next(TrayDocument doc)
|
|
{
|
|
doc.Job=Guid.Empty;
|
|
if(doc.Pending.Count>0&&documents.Values.Any(other=>other!=doc&&other.Job!=Guid.Empty)){doc.Status="Waiting for the current manuscript chapter batch; no prose has been sent.";return;}
|
|
if(doc.Pending.Count==0){doc.Status=$"Batch finished: {doc.Done}/{doc.Total} processed; {doc.Failed} failed. Successful suggestions are in PlotDirector. Retry failed chapters explicitly; completed unchanged chapters are skipped. Import-ready captures: {doc.Retained}/{doc.Done-doc.Failed}. Enable encrypted import capture in browser approval if needed.";
|
|
if(doc.Done>0&&!string.IsNullOrEmpty(doc.ReviewPath))_ = Task.Run(()=>{try{cloud.OpenCompanionPage($"/native-companion/workspace?bookId={doc.Book}&instanceId={doc.Instance}&sessionId={doc.Session}",doc.Authentication);}catch(Exception e)when(e is InvalidOperationException or IOException or System.ComponentModel.Win32Exception){}});
|
|
return;}
|
|
doc.Current=doc.Pending.Dequeue();doc.Job=Guid.NewGuid();doc.Started=DateTime.UtcNow;doc.Status=$"Chapter {doc.Done+1}/{doc.Total}: {doc.Current.Title}";doc.Progress=0;
|
|
if(!Queue(doc,new(){Id=doc.Job,Kind="extract-ai",Chapter=doc.Current,BookId=doc.Book,AuthenticationContext=doc.Authentication})){doc.Job=Guid.Empty;doc.Pending.Clear();}
|
|
}
|
|
public void Cancel(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Status="Cancelled. Successful server suggestions remain available.";}}
|
|
private void Cancel(TrayDocument doc,bool notifyWord=true){CancelChapterWork(doc);doc.PendingRibbonCommand="";doc.RibbonPermit=Guid.Empty;doc.RibbonRequestedUtc=default;doc.RibbonNotice=null;doc.RetryCapture=null;foreach(var request in maintenance.Where(p=>p.Value.Session==doc.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(request);doc.MaintenanceReport="Stopped: superseded by a document or account change. Inspect before retrying cleanup.";}if(doc.Capture!=null)_=cloud.FailCapture(doc.Capture.RequestId,doc.Authentication);doc.Capture=null;doc.CaptureFragments.Clear();if(doc.Job!=Guid.Empty)ai.Clear(doc.Session);doc.Job=Guid.Empty;doc.Pending.Clear();if(commands.TryGetValue(doc.Instance,out var q))commands[doc.Instance]=new(q.Where(c=>c.SessionId!=doc.Session));if(notifyWord)Queue(doc,new(){Kind="cancel"});}
|
|
public void Navigate(Guid session,int start){lock(gate)if(documents.TryGetValue(session,out var doc))Queue(doc,new(){Kind="navigate",Chapter=new(){Start=start}});}
|
|
public async Task Tick(CancellationToken cancellation)
|
|
{
|
|
while(!cancellation.IsCancellationRequested){await Task.Delay(500,cancellation);lock(gate){var cloudState=cloud.Status();foreach(var doc in documents.Values){
|
|
if(doc.Authentication!=cloudState.AuthenticationContext){Cancel(doc);doc.Book=0;doc.Completed.Clear();doc.FailedChapters.Clear();doc.Authentication=cloudState.AuthenticationContext;}
|
|
if(doc.Book>0&&cloudState.Health?.Authentication=="verified"&&cloudState.Health.State=="Connected"&&!cloudState.Books.Any(b=>b.BookId==doc.Book)){Cancel(doc);doc.Book=0;doc.Status="Book access is no longer verified. Reconnect and select an authorised book.";}
|
|
if(doc.Book==0&&cloud.RestoreBinding(doc.Manuscript) is int localBook){doc.Book=localBook;doc.Authentication=cloudState.AuthenticationContext;lastBook=localBook;lastAuthentication=doc.Authentication;}
|
|
if(doc.Book==0&&DocumentBindingRestore(doc,cloudState)) {doc.Book=doc.RememberedBook!.Value;doc.Authentication=cloudState.AuthenticationContext;lastBook=doc.Book;lastAuthentication=doc.Authentication;}
|
|
if(doc.Job==Guid.Empty){if(doc.Pending.Count>0&&!documents.Values.Any(other=>other.Job!=Guid.Empty))Next(doc);continue;}var result=ai.Result(doc.Session);
|
|
if(result?.RequestId==doc.Job&&result.State is "complete" or "failed" or "cancelled"){
|
|
if(result.State=="complete"&&!string.IsNullOrEmpty(result.ReviewPath)){if(result.SourceRetained)doc.Retained++;if(doc.Completed.Count>=8192)doc.Completed.RemoveWhere(c=>c.Item1!=doc.Revision);doc.Completed.Add((doc.Revision,doc.Book,doc.Current!.Start));doc.FailedChapters.Remove((doc.Revision,doc.Book,doc.Current.Start));doc.ReviewPath=result.ReviewPath;}
|
|
else{doc.Failed++;if(doc.FailedChapters.Count>=8192)doc.FailedChapters.Clear();doc.FailedChapters.Add((doc.Revision,doc.Book,doc.Current!.Start));if(doc.Errors.Count>=50)doc.Errors.RemoveAt(0);doc.Errors.Add(doc.Current!.Title+": "+(result.State=="complete"?"Server update required: no saved PWA review handoff was returned.":result.Message));}
|
|
doc.Done++;ai.Clear(doc.Session);Next(doc);
|
|
}else if(DateTime.UtcNow-doc.Started>TimeSpan.FromMinutes(7)){doc.Errors.Add("Chapter timed out; retry explicitly.");Cancel(doc);doc.Status="Chapter timed out. Prior suggestions are safe in PlotDirector.";}
|
|
}}}
|
|
}
|
|
private static bool DocumentBindingRestore(TrayDocument doc,Message state)=>doc.RememberedBook>0&&state.Health?.Authentication=="verified"&&Uri.TryCreate(doc.AssociationSite,UriKind.Absolute,out var a)&&Uri.TryCreate(state.ServerUrl,UriKind.Absolute,out var b)&&a==b&&state.Books.Any(book=>book.BookId==doc.RememberedBook);
|
|
private Task OpenRibbonWorkspace(Guid session, long revision, string page) => Task.Run(() =>
|
|
{
|
|
lock (gate)
|
|
{
|
|
if (!documents.TryGetValue(session, out var doc) || doc.Revision != revision) return;
|
|
try { OpenPage(session, page); }
|
|
catch (Exception error) when (error is InvalidOperationException or IOException or System.ComponentModel.Win32Exception)
|
|
{ doc.Status = error.Message; }
|
|
}
|
|
});
|
|
|
|
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.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}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";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,ChapterIssue=ChapterIssue(doc),CanChapterSync=ChapterCapable(doc.Instance),CanParagraphSync=ParagraphCapable(doc.Instance),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);lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc||(ChapterCapable(doc.Instance)&&reply.Revision!=doc.Revision)||doc.Authentication!=cloud.Status().AuthenticationContext)continue;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;doc.ChapterProgress=reply.ChapterProgress;if(ChapterCapable(doc.Instance))ChapterCursorEvidence.Apply(doc,reply);else{doc.ChapterTitle=reply.ChapterTitle;doc.SceneTitle=reply.SceneTitle;}ObserveChapterPresence(doc,reply);}
|
|
if(reply.ParagraphRevision>0&&!ChapterCapable(doc.Instance))lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext){doc.ChapterId=reply.ChapterId;doc.SceneId=reply.SceneId;}
|
|
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 is "wizard-capture" or "paragraph-snapshot")&&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;}var retained=doc.RetryCapture;var reusable=retained!=null&&doc.RetryAuthentication==doc.Authentication&&doc.RetryBook==doc.Book&&retained.ManuscriptId==doc.Manuscript&&retained.Revision==doc.Revision&&retained.ParagraphTracking==reply.Navigation.ParagraphTracking;
|
|
Cancel(doc);doc.Capture=new(){RequestId=reply.Navigation.Id,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,Revision=doc.Revision,ParagraphTracking=reply.Navigation.ParagraphTracking,End=reusable?retained!.End:0};doc.CaptureBaseRevision=reply.Navigation.BaseRevision;doc.CaptureBaseHash=reply.Navigation.BaseSnapshotHash;doc.CaptureFragments.Clear();
|
|
if(reusable){doc.CaptureFragments.AddRange(retained!.Paragraphs);doc.Status="Retrying the retained unchanged manuscript at your import request…";CaptureFrame(doc,new(){Kind="snapshot-end",SnapshotId=reply.Navigation.Id},new(){Status="ok"});}
|
|
else{doc.Status="Reading manuscript for the PlotDirector import wizard…";Queue(doc,reply.Navigation);}}else if(reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);else if(reply.Navigation.Kind=="cancel")Cancel(doc);else if(reply.Navigation.Kind=="chapter-repair"){BeginChapterRepair(doc,reply.Navigation.Id);}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);}
|
|
}
|
|
}
|
|
// Reuses validated bounded snapshot frames; only a browser-requested capture uploads prose.
|
|
private void CaptureFrame(TrayDocument doc,Message request,Message answer)
|
|
{
|
|
var capture=doc.Capture;if(capture==null||capture.RequestId!=request.SnapshotId)return;
|
|
if(request.Kind=="snapshot-cancel"||answer.Status is not ("ok" or "analysis-complete" or "awaiting-structure")){_=cloud.FailCapture(capture.RequestId,doc.Authentication);doc.Capture=null;doc.CaptureFragments.Clear();doc.Status="Manuscript transfer interrupted. Retry from PlotDirector.";return;}
|
|
if(request.Kind=="snapshot-begin"){doc.CaptureFragments.Clear();capture.End=request.End;}
|
|
if(request.Kind=="snapshot-fragment"&&request.Fragment!=null){if(doc.CaptureFragments.Count>=200000){Cancel(doc);return;}doc.CaptureFragments.Add(request.Fragment);}
|
|
if(request.Kind=="snapshot-end"){
|
|
capture.Paragraphs=doc.CaptureFragments.ToArray();doc.CaptureFragments.Clear();doc.Capture=null;var context=doc.Authentication;var baseRevision=doc.CaptureBaseRevision;var baseHash=doc.CaptureBaseHash;uploading=1;
|
|
doc.Status="Sending manuscript to PlotDirector; waiting for durable acceptance…";
|
|
_=Task.Run(async()=>{
|
|
try{
|
|
// Prepare once. Same-request retries must send byte-equivalent identities/delta, not remint IDs.
|
|
var submission=new ManuscriptCapture{RequestId=capture.RequestId,InstanceId=capture.InstanceId,SessionId=capture.SessionId,ManuscriptId=capture.ManuscriptId,Revision=capture.Revision,ParagraphTracking=capture.ParagraphTracking,End=capture.End,Paragraphs=capture.Paragraphs};
|
|
var rows=submission.ParagraphTracking?paragraphSnapshots.Prepare(doc.Session,context,submission,baseRevision,baseHash):null;
|
|
NativePresence reply;
|
|
for(int attempt=0;;attempt++){
|
|
lock(gate)if(documents.GetValueOrDefault(doc.Session)!=doc||doc.Authentication!=context||cloud.Status().AuthenticationContext!=context||doc.Revision!=capture.Revision)throw new InvalidOperationException("Document or account changed; the old upload was stopped.");
|
|
try{reply=await cloud.Capture(submission,context);break;}
|
|
catch(Exception e)when(attempt<2&&RetryableCapture(e)){await Task.Delay(TimeSpan.FromSeconds((attempt+1)*2));}
|
|
}
|
|
if(rows!=null)paragraphSnapshots.Accept(doc.Session,context,capture.ManuscriptId,rows,reply);
|
|
lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&doc.Authentication==context&&cloud.Status().AuthenticationContext==context&&doc.Revision==capture.Revision){doc.RetryCapture=null;doc.AcceptedRevision=capture.Revision;doc.Status=baseRevision>0?"Word snapshot received. Review scene structure and evidence in PlotDirector; Word text is unchanged.":"Manuscript received by PlotDirector. Continue analysis and review in the import wizard. Word text is unchanged.";}
|
|
}catch(Exception e)when(NetworkFailure(e)){
|
|
_=cloud.FailCapture(capture.RequestId,context);
|
|
lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&doc.Authentication==context&&cloud.Status().AuthenticationContext==context&&doc.Revision==capture.Revision){
|
|
// At most one existing bounded source is buffered, in memory only; no plaintext disk queue.
|
|
if(capture.Paragraphs.Sum(p=>(long)p.Text.Length)>16*1024*1024){doc.Status="Manuscript was not acknowledged: "+e.Message+" This source exceeds the bounded retry buffer. Your Word document is unchanged; check the existing import.";return;}
|
|
foreach(var other in documents.Values.Where(d=>d!=doc&&d.RetryCapture!=null)){other.RetryCapture=null;other.Status="Previous unacknowledged upload is no longer buffered. Check the saved import before requesting another read.";}
|
|
doc.RetryCapture=capture;doc.RetryAuthentication=context;doc.RetryBook=doc.Book;
|
|
doc.Status="Manuscript acknowledgement failed: "+e.Message+" Unchanged capture retained in Companion memory. Check the existing import, then retry there. Closing the document, changing account/book or exiting clears this buffer.";
|
|
}
|
|
}finally{lock(gate)uploading=0;}
|
|
});
|
|
}
|
|
}
|
|
public void RefreshPresence(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status="Checking document connection. Use Import manuscript in PlotDirector to transfer prose.";}}
|
|
internal static bool RetryableCapture(Exception e)=>e is CaptureUploadException response?response.Retryable:e is HttpRequestException or IOException or OperationCanceledException;
|
|
private static bool NetworkFailure(Exception e)=>e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or System.Text.Json.JsonException or ObjectDisposedException;
|
|
}
|
|
public sealed class TrayDocument
|
|
{
|
|
public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress;
|
|
public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Link this manuscript to a book, then use Import manuscript in PlotDirector.",ReviewPath="";
|
|
internal ManuscriptCapture? RetryCapture;internal Guid RetryAuthentication;internal int RetryBook;
|
|
public long CaptureBaseRevision;public string CaptureBaseHash="";public ManuscriptCapture? Capture;public List<ParagraphFragment> CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision;
|
|
internal string LastRibbonCommand="",LastRibbonOutcome="",PendingRibbonCommand="",LastChapterInterruption="";
|
|
internal DateTime RibbonRequestedUtc;internal Guid RibbonPermit;internal PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? RibbonNotice;
|
|
public int? ContextCursor;public long ContextRevision=-1;public int ContextBook;public Guid ContextManuscript;
|
|
public readonly DateTime FirstObserved=DateTime.UtcNow;
|
|
public Guid AssociationRequest;public bool AssociationNeedsSave;public string AssociationNotice="";public string MaintenanceReport="";public string WordDiagnostics="";public int Cursor;public int Retained;public int Failed;public int Book,Progress,Total,Done;public int? RememberedBook,Words,ChapterId,SceneId;public bool Active;public DateTime Observed,Started;
|
|
public StructureSuggestion[] Chapters=[];public StructureSuggestion? Current;public Queue<StructureSuggestion> Pending=[];public HashSet<(long,int,int)> Completed=[];public HashSet<(long,int,int)> FailedChapters=[];public List<string> Errors=[];
|
|
internal TrayDocument Snapshot(){var copy=(TrayDocument)MemberwiseClone();copy.Completed=new(Completed);copy.FailedChapters=new(FailedChapters);copy.Errors=new(Errors);copy.Pending=new(Pending);return copy;}
|
|
public override string ToString()=>Title+(Active?" (active in Word)":"");
|
|
}
|