|
|
|
|
@ -6,13 +6,64 @@ public sealed partial class TrayCoordinator
|
|
|
|
|
{
|
|
|
|
|
private sealed class ChapterWork
|
|
|
|
|
{
|
|
|
|
|
public int Book;public Guid Manuscript;public long Revision;public Guid Context,Operation,Command;public bool Busy,Supported,Processing,Begun;public long FailedRevision=-1;public DateTime Started,RetryAfter;
|
|
|
|
|
public ChapterManifest? Manifest;public readonly Dictionary<int,(int Start,int End)> Checked=[];
|
|
|
|
|
public StringBuilder Text=new(),Xml=new(),Identities=new();public int Start,End,DocumentEnd,FirstStart=-1;public bool Finished;public bool Wrapped;public readonly HashSet<int> Reviewed=[];public readonly HashSet<int> Visited=[];public string Next="";
|
|
|
|
|
public int Book, Attempts, Retries; public string ReviewReason = "";public Guid Manuscript;public long Revision;public Guid Context,Operation,Command;public bool Busy,Supported,Processing,Begun;public long FailedRevision=-1;public DateTime Started,RetryAfter;
|
|
|
|
|
public ChapterManifest? Manifest; public ChapterSyncProgress? Completion;public readonly Dictionary<int,(int Start,int End)> Checked=[];
|
|
|
|
|
public StringBuilder Text=new(),Xml=new(),Identities=new();public int Start,End,DocumentEnd,CursorWhenQueued,FirstStart=-1;public bool Finished;public bool Wrapped;public readonly HashSet<int> Reviewed=[];public readonly HashSet<int> Visited=[];public string Next="";
|
|
|
|
|
}
|
|
|
|
|
private readonly Dictionary<Guid,ChapterWork> chapterWork=[];
|
|
|
|
|
private readonly SemaphoreSlim chapterProcessing=new(2,2);
|
|
|
|
|
private string ChapterIssue(TrayDocument doc){lock(gate)return chapterWork.TryGetValue(doc.Session,out var work)&&work.FailedRevision==doc.Revision?"needs_review":"";}
|
|
|
|
|
public ChapterSyncProgress? ChapterProgressForDisplay(Guid session)
|
|
|
|
|
{
|
|
|
|
|
lock (gate)
|
|
|
|
|
return documents.TryGetValue(session, out var doc) ? VisibleChapterProgress(doc) : null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private ChapterSyncProgress? VisibleChapterProgress(TrayDocument doc)
|
|
|
|
|
{
|
|
|
|
|
if (!chapterWork.TryGetValue(doc.Session, out var work) || !CurrentChapterWork(doc, work))
|
|
|
|
|
return doc.ChapterProgress;
|
|
|
|
|
|
|
|
|
|
var total = work.Manifest?.Chapters.Length ?? doc.ChapterProgress?.Total ?? 0;
|
|
|
|
|
var accepted = work.Checked.Count;
|
|
|
|
|
if (work.FailedRevision == doc.Revision)
|
|
|
|
|
return new() { State = "Needs review", Total = total, Matching = accepted, Message = doc.Status };
|
|
|
|
|
if (work.Busy || !work.Finished && work.Attempts > 0)
|
|
|
|
|
{
|
|
|
|
|
var step = work.Processing ? "Verifying chapter with PlotDirector" : "Checking Word chapter";
|
|
|
|
|
if (work.Attempts > 0 && work.Attempts <= total) step += $" {work.Attempts} of {total}";
|
|
|
|
|
return new() { State = "Checking", Total = total, Matching = accepted, Message = step };
|
|
|
|
|
}
|
|
|
|
|
return doc.ChapterProgress;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void StopChapterWork(TrayDocument doc, ChapterWork work, string reason)
|
|
|
|
|
{
|
|
|
|
|
work.Busy = false;
|
|
|
|
|
work.Processing = false;
|
|
|
|
|
work.Command = Guid.Empty;
|
|
|
|
|
work.FailedRevision = doc.Revision;
|
|
|
|
|
doc.Status = reason;
|
|
|
|
|
doc.LastPresenceKey = "";
|
|
|
|
|
Queue(doc, new() { Kind = "chapter-cancel" });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void RetryChapterWork(TrayDocument doc, ChapterWork work, string reason)
|
|
|
|
|
{
|
|
|
|
|
if (++work.Retries > 2)
|
|
|
|
|
{
|
|
|
|
|
StopChapterWork(doc, work, reason);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
work.Busy = false;
|
|
|
|
|
work.Processing = false;
|
|
|
|
|
work.Command = Guid.Empty;
|
|
|
|
|
work.Finished = false;
|
|
|
|
|
work.Manifest = null;
|
|
|
|
|
work.RetryAfter = DateTime.UtcNow.AddSeconds(15);
|
|
|
|
|
doc.Status = reason;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private bool ChapterCapable(Guid instance){lock(gate)return chapterInstances.Contains(instance);}
|
|
|
|
|
private readonly HashSet<Guid> ribbonRequests=[];
|
|
|
|
|
private async Task RequestChapterFromRibbon(TrayDocument doc,long revision)
|
|
|
|
|
@ -28,7 +79,7 @@ public sealed partial class TrayCoordinator
|
|
|
|
|
private void BeginChapterRepair(TrayDocument doc,Guid operation)
|
|
|
|
|
{
|
|
|
|
|
if(!ChapterCapable(doc.Instance))return;
|
|
|
|
|
var work=GetChapterWork(doc);work.Operation=operation;work.FailedRevision=-1;work.Manifest=null;work.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.Wrapped=false;work.FirstStart=-1;work.Finished=false;work.Command=Guid.Empty;work.Busy=false;
|
|
|
|
|
var work=GetChapterWork(doc);work.Completion=null;work.Operation=operation;work.FailedRevision=-1;work.Attempts=0;work.Retries=0;work.ReviewReason="";work.Manifest=null;work.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.Wrapped=false;work.FirstStart=-1;work.Finished=false;work.Command=Guid.Empty;work.Busy=false;
|
|
|
|
|
doc.Status="Repairing existing chapter mappings; accepted scenes and author decisions are retained.";work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work);
|
|
|
|
|
}
|
|
|
|
|
private ChapterWork GetChapterWork(TrayDocument doc)
|
|
|
|
|
@ -39,9 +90,9 @@ public sealed partial class TrayCoordinator
|
|
|
|
|
{
|
|
|
|
|
if(!ChapterCapable(doc.Instance))return;
|
|
|
|
|
lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc)return;var work=GetChapterWork(doc);work.Supported=reply.ChapterSyncSupported;
|
|
|
|
|
if(work.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Manifest=null;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;}
|
|
|
|
|
if(work.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Completion=null;work.Manifest=null;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;}
|
|
|
|
|
if(DateTime.UtcNow<work.RetryAfter||work.Finished||!work.Supported||doc.WordSaved!=true||doc.Book<=0||work.FailedRevision==doc.Revision||doc.Capture!=null)return;
|
|
|
|
|
if(work.Busy){if(work.Command!=Guid.Empty&&work.End>work.Start&&doc.Active&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End)&&(doc.Cursor<work.Start||doc.Cursor>=work.End)){QueueChapter(doc,work,doc.Cursor);return;}if(DateTime.UtcNow-work.Started>TimeSpan.FromMinutes(2)){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Chapter validation timed out. Accepted checkpoints are retained; request Repair to resume.";}return;}
|
|
|
|
|
if(work.Busy){if(!work.Processing&&work.Command!=Guid.Empty&&work.End>work.Start&&doc.Active&&doc.Cursor!=work.CursorWhenQueued&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End)&&(doc.Cursor<work.Start||doc.Cursor>=work.End)){QueueChapter(doc,work,doc.Cursor);return;}if(DateTime.UtcNow-work.Started>TimeSpan.FromMinutes(2)){StopChapterWork(doc,work,"Chapter validation timed out. Accepted checkpoints are retained. Check the connection before retrying.");}return;}
|
|
|
|
|
if(work.Manifest==null){work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work);return;}
|
|
|
|
|
var here=work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End);
|
|
|
|
|
if(!here){QueueChapter(doc,work,doc.Cursor);return;}
|
|
|
|
|
@ -52,8 +103,8 @@ public sealed partial class TrayCoordinator
|
|
|
|
|
private async Task LoadChapterManifest(TrayDocument doc,ChapterWork work)
|
|
|
|
|
{
|
|
|
|
|
try{var manifest=await cloud.ChapterManifest(doc.Book,doc.Session,doc.Revision,doc.Authentication);
|
|
|
|
|
lock(gate){if(!CurrentChapterWork(doc,work))return;if(manifest.ManuscriptId!=doc.Manuscript)throw new InvalidOperationException("Saved manuscript identity does not match this Word document.");work.Manifest=manifest;work.Busy=false;if(manifest.Mode=="Off"&&work.Operation==Guid.Empty){work.Finished=true;doc.Status="Automatic synchronisation is off. Use Synchronise or Repair for an explicit chapter check.";return;}foreach(var chapter in manifest.Chapters.Where(c=>c.State=="Synchronised"))work.Checked[chapter.ChapterId]=(chapter.Start,chapter.End);doc.Status=$"Chapter index ready: {work.Checked.Count}/{manifest.Chapters.Length} accepted for this Word session.";if(manifest.Chapters.Length>0&&work.Checked.Count==manifest.Chapters.Length){CompleteChapters(doc,work);}else if(manifest.Chapters.Length>0&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End))QueueChapter(doc,work,doc.Cursor);else{var next=manifest.Chapters.FirstOrDefault(c=>!work.Checked.ContainsKey(c.ChapterId));if(next!=null)QueueChapter(doc,work,next.Start);}}
|
|
|
|
|
}catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;doc.Status="Chapter index unavailable: "+e.Message+" Existing import is retained; no full extraction was started.";}}
|
|
|
|
|
lock(gate){if(!CurrentChapterWork(doc,work))return;if(manifest.ManuscriptId!=doc.Manuscript)throw new InvalidOperationException("Saved manuscript identity does not match this Word document.");work.Manifest=manifest;work.Busy=false;if(manifest.Chapters.Length==0){StopChapterWork(doc,work,"No accepted chapter boundaries are available. Review the existing manuscript structure.");return;}if(work.Operation==Guid.Empty&&manifest.Chapters.All(c=>string.IsNullOrEmpty(c.HeadingNativeId))){StopChapterWork(doc,work,"This existing import has no native chapter identities. Use Repair Synchronisation to verify and adopt identities without reimporting.");return;}if(manifest.Mode=="Off"&&work.Operation==Guid.Empty){work.Finished=true;doc.Status="Automatic synchronisation is off. Use Synchronise or Repair for an explicit chapter check.";return;}foreach(var chapter in manifest.Chapters.Where(c=>c.State=="Synchronised"))work.Checked[chapter.ChapterId]=(chapter.Start,chapter.End);doc.Status=$"Chapter index ready: {work.Checked.Count}/{manifest.Chapters.Length} accepted for this Word session.";if(manifest.Chapters.Length>0&&work.Checked.Count==manifest.Chapters.Length){CompleteChapters(doc,work);}else if(manifest.Chapters.Length>0&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End))QueueChapter(doc,work,doc.Cursor);else{var next=manifest.Chapters.FirstOrDefault(c=>!work.Checked.ContainsKey(c.ChapterId));if(next!=null)QueueChapter(doc,work,next.Start);}}
|
|
|
|
|
}catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){RetryChapterWork(doc,work,"Chapter index unavailable: "+e.Message);}}
|
|
|
|
|
}
|
|
|
|
|
private bool CurrentChapterWork(TrayDocument doc,ChapterWork work)=>documents.GetValueOrDefault(doc.Session)==doc&&chapterWork.GetValueOrDefault(doc.Session)==work&&doc.Revision==work.Revision&&doc.Authentication==work.Context&&doc.Book==work.Book&&doc.Manuscript==work.Manuscript;
|
|
|
|
|
private void QueueChapter(TrayDocument doc,ChapterWork work,int position)
|
|
|
|
|
@ -64,8 +115,13 @@ public sealed partial class TrayCoordinator
|
|
|
|
|
if(background.Value==null||!documents.TryGetValue(background.Key,out var backgroundDoc))return;
|
|
|
|
|
Queue(backgroundDoc,new(){Kind="chapter-cancel"});background.Value.Command=Guid.Empty;background.Value.Busy=false;background.Value.Text=new();background.Value.Xml=new();
|
|
|
|
|
}
|
|
|
|
|
if (work.Attempts >= (work.Manifest?.Chapters.Length ?? 0) * 2 + 2)
|
|
|
|
|
{
|
|
|
|
|
StopChapterWork(doc, work, "Chapter checks reached the retry limit. " + work.ReviewReason);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
var command=new AdapterCommand{Kind="chapter-check",OperationId=work.Operation,BookId=doc.Book,Chapter=new(){Start=position}};
|
|
|
|
|
if(Queue(doc,command)){work.Command=command.Id;work.Busy=true;work.Processing=false;work.Begun=false;work.Start=work.End=0;work.Started=DateTime.UtcNow;work.Text.Clear();work.Xml.Clear();work.Identities.Clear();doc.Status=$"Checking chapter positions ({work.Checked.Count}/{work.Manifest!.Chapters.Length} accepted); Word prose is unchanged.";}
|
|
|
|
|
if(Queue(doc,command)){work.Command=command.Id;work.Attempts++;work.CursorWhenQueued=doc.Cursor;work.Busy=true;work.Processing=false;work.Begun=false;work.Start=work.End=0;work.Started=DateTime.UtcNow;work.Text.Clear();work.Xml.Clear();work.Identities.Clear();doc.Status=$"Checking chapter positions ({work.Checked.Count}/{work.Manifest!.Chapters.Length} accepted); Word prose is unchanged.";}
|
|
|
|
|
}
|
|
|
|
|
private void ChapterFrame(TrayDocument doc,Message message,Message answer)
|
|
|
|
|
{
|
|
|
|
|
@ -102,8 +158,8 @@ public sealed partial class TrayCoordinator
|
|
|
|
|
}
|
|
|
|
|
private async Task CompleteChapterOperation(TrayDocument doc,ChapterWork work)
|
|
|
|
|
{
|
|
|
|
|
try{var result=await cloud.FinishChapters(doc.Book,new(){InstanceId=doc.Instance,SessionId=doc.Session,WordRevision=work.Revision,OperationId=work.Operation,ReviewChapterIds=work.Reviewed.Where(id=>id>0).ToArray(),HasIssues=work.Reviewed.Count>0||work.Manifest!.Chapters.Any(c=>!work.Checked.ContainsKey(c.ChapterId))},work.Context);lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;doc.Status=result.Message;}}
|
|
|
|
|
catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;work.Finished=false;work.Manifest=null;work.RetryAfter=DateTime.UtcNow.AddSeconds(15);doc.Status="Accepted checkpoints are retained; final chapter status will be retried after reconnect: "+e.Message;}}
|
|
|
|
|
try{var result=await cloud.FinishChapters(doc.Book,new(){InstanceId=doc.Instance,SessionId=doc.Session,WordRevision=work.Revision,OperationId=work.Operation,ReviewChapterIds=work.Reviewed.Where(id=>id>0).ToArray(),HasIssues=work.Reviewed.Count>0||work.Manifest!.Chapters.Any(c=>!work.Checked.ContainsKey(c.ChapterId))},work.Context);lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;work.Processing=false;work.Completion=result;doc.ChapterProgress=result;doc.Status=result.Message;if(result.State=="Needs review" && work.ReviewReason.Length>0){result.Message=work.ReviewReason;}}}
|
|
|
|
|
catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){RetryChapterWork(doc,work,"Could not confirm chapter completion: "+e.Message);}}
|
|
|
|
|
}
|
|
|
|
|
private async Task ProcessChapter(TrayDocument doc,ChapterWork work,string text,string xml,string? identities,Guid command,int start,int end,string nextHeading,Guid operation)
|
|
|
|
|
{
|
|
|
|
|
@ -115,17 +171,17 @@ public sealed partial class TrayCoordinator
|
|
|
|
|
var hash=ChapterFingerprint.Content(rows.Select(p=>p.Text!));
|
|
|
|
|
var candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==rows[0].NativeId).ToArray();
|
|
|
|
|
if(candidates.Length==0&&work.Operation!=Guid.Empty)candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==""&&c.ContentHash==hash&&c.ParagraphCount==rows.Length).ToArray();
|
|
|
|
|
if(candidates.Length!=1){lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;work.Reviewed.Add(-work.Start-1);doc.Status="An unrecognised or ambiguous chapter needs review; no chapter was guessed by name.";AdvanceChapter(doc,work);}return;}
|
|
|
|
|
if(candidates.Length!=1){lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;work.Reviewed.Add(-work.Start-1);work.ReviewReason="A chapter identity is unrecognised or ambiguous. Review its Word heading and saved mapping.";doc.Status=work.ReviewReason;AdvanceChapter(doc,work);}return;}
|
|
|
|
|
var chapter=candidates[0];lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(!work.Visited.Add(chapter.ChapterId)){work.Busy=false;if(!work.Checked.TryGetValue(chapter.ChapterId,out var earlier)||earlier.Start!=start||earlier.End!=end){work.Reviewed.Add(chapter.ChapterId);work.Checked.Remove(chapter.ChapterId);doc.Status="Duplicate chapter identity at another position; existing canonical structure is retained for review.";}AdvanceChapter(doc,work);return;}}var proof=new ChapterObservation{RequestId=command,OperationId=operation,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,WordRevision=doc.Revision,BaseRevision=manifest.Revision,ChapterId=chapter.ChapterId,Start=start,End=end,NextHeadingId=nextHeading,ContentHash=hash,IdentityHash=ChapterFingerprint.Identity(rows),Paragraphs=rows.Select(p=>new ChapterParagraph{NativeId=p.NativeId,Length=p.Length,Outline=p.Outline}).ToArray()};
|
|
|
|
|
var result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);
|
|
|
|
|
if(!result.Accepted&&result.State=="Changed"&&result.AllowText){proof.Reconcile=true;proof.Paragraphs=rows;result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);}
|
|
|
|
|
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;
|
|
|
|
|
if(result.Accepted){work.Checked[chapter.ChapterId]=(start,end);manifest.Revision=result.Revision;if(result.State=="Needs review")work.Reviewed.Add(chapter.ChapterId);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status=$"{work.Checked.Count}/{manifest.Chapters.Length} chapters accepted · "+result.Message;AdvanceChapter(doc,work);}
|
|
|
|
|
else{work.Reviewed.Add(chapter.ChapterId);doc.Status=result.Message+" Accepted chapter repairs are retained.";AdvanceChapter(doc,work);}
|
|
|
|
|
if(result.Accepted){work.Retries=0;work.Checked[chapter.ChapterId]=(start,end);manifest.Revision=result.Revision;if(result.State=="Needs review")work.Reviewed.Add(chapter.ChapterId);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status=$"{work.Checked.Count}/{manifest.Chapters.Length} chapters accepted · "+result.Message;AdvanceChapter(doc,work);}
|
|
|
|
|
else{work.Reviewed.Add(chapter.ChapterId);work.ReviewReason=result.Message;doc.Status=result.Message+" Accepted chapter repairs are retained.";AdvanceChapter(doc,work);}
|
|
|
|
|
}
|
|
|
|
|
}catch(Exception e)when(NetworkFailure(e)||e is ArgumentException or System.Xml.XmlException){lock(gate)if(CurrentChapterWork(doc,work)&&work.Command==command){work.Busy=false;
|
|
|
|
|
if(e is HttpRequestException or OperationCanceledException||cloud.Status().Health?.Authentication!="verified"){work.Manifest=null;work.Command=Guid.Empty;work.Visited.Clear();work.RetryAfter=DateTime.UtcNow.AddSeconds(15);doc.Status="Chapter connection interrupted; accepted checkpoints are retained and validation will resume after reconnect.";}
|
|
|
|
|
else if(e is ArgumentException or System.Xml.XmlException&&end>start){work.Reviewed.Add(-start-1);doc.Status="Chapter content needs review: "+e.Message+" Other chapters can continue.";AdvanceChapter(doc,work);}
|
|
|
|
|
if(e is HttpRequestException or OperationCanceledException||cloud.Status().Health?.Authentication!="verified"){work.Visited.Clear();RetryChapterWork(doc,work,"Chapter connection interrupted. Accepted checkpoints are retained.");}
|
|
|
|
|
else if(e is ArgumentException or System.Xml.XmlException&&end>start){work.Reviewed.Add(-start-1);work.ReviewReason="Chapter content needs review: "+e.Message;doc.Status=work.ReviewReason;AdvanceChapter(doc,work);}
|
|
|
|
|
else{work.FailedRevision=doc.Revision;doc.Status="Chapter needs review: "+e.Message+" Existing import is unchanged.";}}}
|
|
|
|
|
finally{chapterProcessing.Release();}
|
|
|
|
|
}
|
|
|
|
|
|