fix: isolate stale AI cancellations and verify update source identity

This commit is contained in:
Nick Beckley 2026-11-05 11:12:23 +00:00
parent baa1326caa
commit cdc75a3666
4 changed files with 20 additions and 8 deletions

View File

@ -24,6 +24,15 @@ internal static class ChapterAiTests
Send("ai-submit");Send("ai-submit");
await Wait(()=>Send("ai-status").Ai?.State=="complete");var result=Send("ai-status").Ai!;
check(handler.Submissions==1&&result.Scenes.Single().Start==100&&handler.Last?.ChapterStart==100&&handler.Last.Paragraphs.Single().Index==1,"duplicate submit uses one HTTP call and preserves exact chapter mapping");
using(var frame=new MemoryStream())
{
var page=new AiChapterResult{State="complete",Scenes=Enumerable.Range(0,40).Select(_=>new StructureSuggestion{Title=new string('界',200),Reason=new string('界',600),ChapterTitle=new string('界',200),Origin="AI"}).ToArray()};
await FrameCodec.WriteAsync(frame,new Message{Ai=page},CancellationToken.None);check(frame.Length<=ProtocolVersion.MaxFrameBytes+4,"worst-case bounded AI page fits IPC framing");frame.Position=0;
check((await FrameCodec.ReadAsync(frame,CancellationToken.None)).Ai?.Scenes.Length==40,"AI result contract round-trips on actual frame codec");
}
var previous=id;id=Guid.NewGuid();Send("ai-begin");
check(jobs.Handle(descriptor,new(){Kind="ai-cancel",SnapshotId=previous},new(){Status="ok"}).Status=="obsolete-ai-request"&&Send("ai-status").Ai?.State=="reading","late cancellation cannot retire a replacement AI chapter");
Send("ai-cancel");
var alien=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid()};
check(jobs.Handle(alien,new(){Kind="ai-status",SnapshotId=id},new(){Status="ok"}).Status=="obsolete-ai-request","another document cannot retrieve an AI result");
id=Guid.NewGuid();handler.Stall=true;Send("ai-begin");Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="Another chapter paragraph.",CompletesParagraph=true});Send("ai-submit");

View File

@ -25,7 +25,7 @@ namespace PlotDirector.WordAddIn
private IList<StructureSuggestion> aiItems=new List<StructureSuggestion>();
public AnalysisWindow(Action analyse,Action stop,Action<int> page,Action<StructureSuggestion[]> submit,Action<StructureSuggestion> navigate)
{
Text="PlotDirector — Manuscript review";AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new Size(680,480);Width=980;Height=680;ShowInTaskbar=false;
Text="PlotDirector — Manuscript review";Font=new Font("Segoe UI",9F);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new Size(680,480);Width=980;Height=680;ShowInTaskbar=false;
var layout=new TableLayoutPanel{Dock=DockStyle.Fill,ColumnCount=1,RowCount=6,Padding=new Padding(10)};
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,100));
layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));layout.RowStyles.Add(new RowStyle(SizeType.Absolute,8));layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
@ -52,11 +52,11 @@ namespace PlotDirector.WordAddIn
}
public int SelectedBook=>books.SelectedItem is CompanionBook book?book.BookId:0;
private AnalysisPage current;
public void Render(AnalysisReview review,string connection,Guid document,CompanionBook[] available,string cloud,string aiStatus,IList<StructureSuggestion> results,bool running)
public void Render(AnalysisReview review,string connection,Guid document,string documentName,CompanionBook[] available,string cloud,string aiStatus,IList<StructureSuggestion> results,bool running)
{
if(session!=document){session=document;renderKey="";aiRenderKey="";books.SelectedIndex=-1;aiOffset=0;local.Nodes.Clear();ai.Nodes.Clear();details.Clear();}
current=review?.Page;aiItems=results??new List<StructureSuggestion>();
status.Text="Document "+document.ToString("N").Substring(0,8)+" · "+cloud+"\n"+(string.IsNullOrEmpty(aiStatus)?review?.Status:aiStatus);
status.Text=(documentName??"No active document")+" · Agent: "+connection+" · "+cloud+"\n"+(string.IsNullOrEmpty(aiStatus)?review?.Status:aiStatus);
if(current!=null)status.Text+="\n"+current.WordCount.ToString("N0")+" approximate words · "+current.ChapterCount+" local chapter candidates · "+current.SceneCount+" local scene candidates. "+(current.Truncated?"Result limit reached. ":"")+"Double-click to navigate; select to inspect evidence.";
progress.Value=review?.Progress??0;cancel.Enabled=running||review?.Running==true;
var key=string.Join("|",available.Select(b=>b.BookId+":"+b.Title));

View File

@ -108,10 +108,10 @@ namespace PlotDirector.WordAddIn
if (message.Status != "ok" || !string.IsNullOrEmpty(message.ChapterTitle)) PostToUi(() => {
if (message.Status == "awaiting-structure")
description = "Local structure refreshed. No chapter or scene found at the cursor.";
if(message.Status!="ok"&&message.Status!="ready"&&message.Status!="awaiting-structure"&&message.Status!="analysis-complete")
if(message.Status!="ok"&&message.Status!="ready"&&message.Status!="awaiting-structure"&&message.Status!="analysis-complete"&&message.Status!="ai-cancelled")
{
var failed=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);
if(failed!=null){CancelExtraction(failed);failed.NeedsSnapshot=false;}
if(failed?.Extraction!=null&&failed.Extraction.Snapshot==message.SnapshotId){CancelExtraction(failed);failed.NeedsSnapshot=false;}
}
if(active != null && active.Session == message.SessionId && active.Revision == message.Revision)lastResult = description;
});
@ -176,6 +176,7 @@ namespace PlotDirector.WordAddIn
pendingOpen.Remove(document);
if (documents.ContainsKey(document) || documents.Count >= ProtocolVersion.MaxDocuments) return;
var state = new LocalDocument(document);
state.DisplayName=Com(()=>document.Name);
state.Identity = ReadGuidProperty(document,"PlotDirector.Native.DocumentGuid") ?? Guid.NewGuid();
state.IdentityPersisted = ReadGuidProperty(document,"PlotDirector.Native.DocumentGuid").HasValue;
state.ProjectId = ReadPositiveProperty(document,"PlotDirector.Native.ProjectID");
@ -273,7 +274,7 @@ namespace PlotDirector.WordAddIn
lastResult="Agent queue busy. Try the results page again.";
}
private void RenderReview()
{if(analysisWindow!=null&&!analysisWindow.IsDisposed)analysisWindow.Render(active?.Review,ConnectionState,active?.Session??Guid.Empty,cloudBooks,cloudState,active?.AiStatus,active?.AiResults,active?.AiJob!=Guid.Empty&&active!=null);reviewDirty=false;}
{if(analysisWindow!=null&&!analysisWindow.IsDisposed)analysisWindow.Render(active?.Review,ConnectionState,active?.Session??Guid.Empty,active?.DisplayName,cloudBooks,cloudState,active?.AiStatus,active?.AiResults,active!=null&&active.AiJob!=Guid.Empty);reviewDirty=false;}
public void RequestSnapshot()
{
if (active == null) return;
@ -419,7 +420,7 @@ namespace PlotDirector.WordAddIn
private void CancelExtraction(LocalDocument doc)
{
scheduler.Cancel("extract:"+doc.Session);
if(doc.Extraction!=null)link.TryPost(new Message{Kind=doc.Extraction.IsAi?"ai-cancel":"snapshot-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Extraction.Snapshot});
if(doc.Extraction!=null&&!link.TryPost(new Message{Kind=doc.Extraction.IsAi?"ai-cancel":"snapshot-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Extraction.Snapshot})&&doc.Extraction.IsAi)link.Reset();
doc.Extraction=null;
}
private void BeforeSave(Word.Document document,ref bool saveAsUI,ref bool cancel)
@ -540,7 +541,7 @@ namespace PlotDirector.WordAddIn
private void StopAi(LocalDocument doc,string reason)
{
scheduler.Cancel("ai-read:"+doc.Session);
if(doc.AiJob!=Guid.Empty)link.TryPost(new Message{Kind="ai-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.AiJob});
if(doc.AiJob!=Guid.Empty&&!link.TryPost(new Message{Kind="ai-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.AiJob}))link.Reset();
if(doc.Extraction?.IsAi==true)CancelExtraction(doc);
doc.AiJob=Guid.Empty;doc.AiQueue.Clear();doc.AiPartial.Clear();doc.AiStatus=reason;reviewDirty=true;
}
@ -626,6 +627,7 @@ namespace PlotDirector.WordAddIn
private sealed class LocalDocument
{
public readonly Word.Document Document;public readonly Guid Session=Guid.NewGuid();public Guid Identity;public bool IdentityPersisted;
public string DisplayName;
public readonly AnalysisReview Review=new AnalysisReview();
public readonly Queue<StructureSuggestion> AiQueue=new Queue<StructureSuggestion>();
public readonly List<StructureSuggestion> AiResults=new List<StructureSuggestion>();

View File

@ -46,6 +46,7 @@ try {
New-Item -ItemType Directory -Path $staging -Force | Out-Null
Copy-Item -Path (Join-Path $bin '*') -Destination $staging -Recurse
Invoke-Checked dotnet @('publish','PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj','-c','Release','-r','win-x64','--self-contained','false','-o',(Join-Path $staging 'Agent'))
if((& git rev-parse HEAD).Trim() -ne $commit){throw 'Git HEAD changed during the build. No package was installed; rerun after the repository is stable.'}
if(& git status --porcelain=v1){throw 'Build generated source changes; review them before packaging. No installation was changed.'}
$files=@(Get-ChildItem -LiteralPath $staging -Recurse -File | ForEach-Object { @{path=$_.FullName.Substring($staging.Length+1).Replace('\','/');sha256=(Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash} })
@{version=$version;commit=$commit;publisher='Nick Beckley';certificateThumbprint=$CertificateThumbprint;createdUtc=[DateTime]::UtcNow.ToString('O');files=$files} | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $staging 'package.json') -Encoding UTF8