diff --git a/Docs/WordCompanion/WindowsHandover/2026-11-08-capture-upload-recovery.md b/Docs/WordCompanion/WindowsHandover/2026-11-08-capture-upload-recovery.md new file mode 100644 index 00000000..9bef2122 --- /dev/null +++ b/Docs/WordCompanion/WindowsHandover/2026-11-08-capture-upload-recovery.md @@ -0,0 +1,38 @@ +# Windows follow-up: capture upload recovery + +Use the existing `codex/word-companion-native-phase1-20261104` branch. Preserve local changes, fetch the configured remote and fast-forward safely. Do not create another branch or replace the existing unified installer workflow. + +## What is already fixed on Development + +Server commit `099792c` changes a capture request's fixed 20-minute deadline into an inactivity deadline renewed by its exact authenticated document/session progress. Healthy extraction may continue for up to four hours. The installed 1.0.0.20 Companion already sends this heartbeat; **this server correction does not require a new installer**. No manuscript properties, marker GUIDs or paragraph identities need cleaning. + +## Agent changes requiring the next Windows build + +- `PlotDirector.NativeCompanion/Agent/CloudGateway.cs`: safely parses bounded capture rejection codes/messages, distinguishes transient failures, and retains existing authentication/renewal mechanisms. +- `PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs`: prepares a capture once, retries transient uploads at most three times with short backoff, and retains at most one failed unchanged source in bounded process memory. A subsequent explicit request from the existing web import wizard may reuse it. Changing document revision, book, account, closing the document or exiting invalidates the buffer. It is not a plaintext disk queue and does not automatically upload prose on reconnect. +- `PlotDirector.NativeCompanion/Tests/NativeCaptureUploadTests.cs`: portable regressions for retries, meaningful failure reporting, explicit retained-source replay and revision invalidation. + +There is **no VSTO/COM/IPC-contract change**, no version bump, no signing/packaging/install operation performed on Atlas. Follow existing version and unified-installer procedures for a later release; do not assume a new installation is necessary just to retry the server-corrected import. + +## Portable checks + +Run serially from the repository root: + +```powershell +dotnet build PlotLine.slnx +dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj --no-build -- --native-capture-lifetime +dotnet run --project PlotDirector.NativeCompanion/Tests --no-build -- --native-capture-upload +dotnet run --project PlotDirector.NativeCompanion/Tests --no-build +``` + +## Native acceptance, in an explicitly scheduled interactive session + +Do not open Word, drive the desktop, install software or close documents during unattended checks. + +1. In an author-owned disposable Development import, start capture through the existing wizard. Verify progress and, for a long manuscript, successful transfer after more than 20 minutes. +2. Confirm a server acknowledgement precedes “received” status and the wizard can continue. Capture acceptance alone does not mean chapter/scene import or AI has completed. +3. For a controlled transient upload outage, verify bounded retries and meaningful status. If acceptance is uncertain, inspect the existing import before retrying; do not start another import. +4. When a capture was not acknowledged, retry through that same wizard. An unchanged retained source should not require another Word read. An edited/switched/closed document or different account/book must never reuse it. +5. Verify ordinary typing, saving and document switching remain responsive and manuscript prose is unchanged. + +The original failed 10152 capture was not durably accepted and was cleaned up by the old client. These changes cannot reconstruct text no longer retained. The author must explicitly request a new capture; no automatic retry of that book or Reckoning was initiated on Atlas. diff --git a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs index f5c181d6..16e36f9f 100644 --- a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs +++ b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs @@ -127,6 +127,20 @@ public sealed partial class CloudGateway : IDisposable =>await Send(HttpMethod.Post,path,body,expectedContext); public async Task FailCapture(Guid id,Guid context){try{await Send(HttpMethod.Delete,"api/native-companion/manuscript-capture/"+id,null,context);}catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException or ObjectDisposedException){}} public async Task Capture(ManuscriptCapture capture,Guid context){var result=await Send(HttpMethod.Post,"api/native-companion/manuscript-capture",capture,context);if(result.CaptureRequestId!=capture.RequestId||result.Revision!=capture.Revision)throw new InvalidDataException("Server did not acknowledge this manuscript capture. Update or reconnect before retrying.");return result;} + private static async Task ReadCaptureFailure(HttpResponseMessage response,CancellationToken cancellation) + { + string code="capture_rejected",message=$"PlotDirector did not acknowledge the manuscript (HTTP {(int)response.StatusCode}). Check the existing import before retrying."; + bool retryable=(int)response.StatusCode>=500||response.StatusCode is HttpStatusCode.RequestTimeout or HttpStatusCode.TooManyRequests; + try{ + await using var stream=await response.Content.ReadAsStreamAsync(cancellation);var data=new byte[8193];int count=0,read; + while(count0)count+=read; + if(count<=8192){using var json=JsonDocument.Parse(data.AsMemory(0,count));var root=json.RootElement; + if(root.TryGetProperty("code",out var c)&&c.ValueKind==JsonValueKind.String&&c.GetString() is {Length:>0 and <=80} text&&text.All(ch=>char.IsAsciiLetterOrDigit(ch)||ch=='_'))code=text; + if(root.TryGetProperty("message",out var m)&&m.ValueKind==JsonValueKind.String&&m.GetString() is {Length:>0 and <=1024} description)message=description; + } + }catch(Exception e)when(e is JsonException or IOException or InvalidOperationException){/* Keep bounded generic response; never echo raw HTML or server internals. */} + return new(code,message,retryable); + } private async Task Send(HttpMethod method,string path,object? body,Guid context,CancellationToken cancellation=default) { await EnsureAccess(context); @@ -136,6 +150,11 @@ public sealed partial class CloudGateway : IDisposable { using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,stop.Token); if(response.StatusCode==HttpStatusCode.Unauthorized){InvalidateAccess(context);throw new InvalidOperationException("Connection needs renewal. Retry after Companion reconnects automatically.");} + if(!response.IsSuccessStatusCode&&path=="api/native-companion/manuscript-capture"){ + var failure=await ReadCaptureFailure(response,stop.Token); + lock(gate)if(context==authenticationContext){health.Server=(int)response.StatusCode>=500?"degraded":"online";health.VerifiedUtc=Now.UtcDateTime;health.Explanation=failure.Message;} + throw failure; + } if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=Now.UtcDateTime;health.Explanation=$"PlotDirector rejected { (path.EndsWith("/presence",StringComparison.Ordinal)?"document registration":"the request") } (HTTP {(int)response.StatusCode}). Reconnect or check the selected book.";if(response.StatusCode==HttpStatusCode.Forbidden){if(body is NativePresence denied)books=books.Where(b=>b.BookId!=denied.BookId).ToArray();else if(path=="api/native-companion/books")books=[];}}throw new InvalidOperationException(response.StatusCode==HttpStatusCode.Forbidden?"Access denied or subscription unavailable.":response.StatusCode==HttpStatusCode.NotFound?"No saved chapter/scene matches this book and Word marker.":"Server request failed. Check connection or update the server.");} await using var stream=await response.Content.ReadAsStreamAsync(stop.Token);using var buffer=new MemoryStream();var bytes=new byte[8192];int size; while((size=await stream.ReadAsync(bytes,stop.Token))>0){if(buffer.Length+size>(path=="api/native-companion/manuscript-capture"?4:1)*1024*1024)throw new InvalidDataException();buffer.Write(bytes,0,size);}buffer.Position=0; @@ -174,3 +193,9 @@ public sealed partial class CloudGateway : IDisposable private sealed record PairStart(string Code); private sealed record TokenReply(string AccessToken,DateTimeOffset ExpiresUtc=default,Guid InstallationId=default,int AccountId=0,string AccountName="",DateTimeOffset RefreshExpiresUtc=default,Guid ConnectionId=default,string? DeviceSecret=null); } + +public sealed class CaptureUploadException(string code,string message,bool retryable):InvalidOperationException(message) +{ + public string Code {get;}=code; + public bool Retryable {get;}=retryable; +} diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs index e857ad81..9767685b 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs @@ -97,7 +97,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C 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){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));Queue(doc,new(){Kind="cancel"});} + private void Cancel(TrayDocument doc){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));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) { @@ -122,7 +122,10 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc0)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext){if(doc.ChapterId!=reply.ChapterId)doc.ChapterTitle="";if(doc.SceneId!=reply.SceneId)doc.SceneTitle="";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;}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};doc.CaptureBaseRevision=reply.Navigation.BaseRevision;doc.CaptureBaseHash=reply.Navigation.BaseSnapshotHash;doc.CaptureFragments.Clear();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=="navigate")Queue(doc,reply.Navigation);}}catch(Exception e)when(NetworkFailure(e)) {doc.Status=e.Message;doc.LastPresenceKey="";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 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=="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);} } @@ -137,15 +140,40 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C 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{var rows=capture.ParagraphTracking?paragraphSnapshots.Prepare(doc.Session,context,capture,baseRevision,baseHash):null;var reply=await cloud.Capture(capture,context);if(rows!=null)paragraphSnapshots.Accept(doc.Session,context,capture.ManuscriptId,rows,reply);lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc){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.Status="Manuscript was not acknowledged: "+e.Message+" Retry from PlotDirector.";}finally{lock(gate)uploading=0;}}); + _=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 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 CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision; 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 Pending=[];public HashSet<(long,int,int)> Completed=[];public HashSet<(long,int,int)> FailedChapters=[];public List Errors=[]; diff --git a/PlotDirector.NativeCompanion/Tests/NativeCaptureUploadTests.cs b/PlotDirector.NativeCompanion/Tests/NativeCaptureUploadTests.cs new file mode 100644 index 00000000..6f5a6468 --- /dev/null +++ b/PlotDirector.NativeCompanion/Tests/NativeCaptureUploadTests.cs @@ -0,0 +1,67 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using PlotDirector.Companion.Agent; +using PlotDirector.Companion.Protocol; +internal static class NativeCaptureUploadTests +{ + public static async Task Run() + { + var handler=new Handler();using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://capture.test/"); + await Until(()=>cloud.Status().Books.Any(b=>b.BookId==3));await cloud.CheckConnection(); + var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var tray=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var lease=Guid.NewGuid();var session=Guid.NewGuid();var manuscript=Guid.NewGuid();long sequence=0; + sessions.Attach(instance,lease);tray.Attach(instance,lease,capture:true,paragraphs:true); + long revision=1; + Message Send(Message request){request.WordInstanceId=instance;request.SessionId=session;request.Sequence=++sequence;request.Revision=revision;return tray.Exchange(instance,request,sessions.Apply(lease,request),lease);} + void Register()=>Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=manuscript,Revision=revision,Title="Synthetic upload.docx"}]}); + Register();tray.SelectBook(session,3,false);using var cancel=new CancellationTokenSource();var heartbeats=tray.Heartbeat(cancel.Token); + async Task Request(){handler.Next=Guid.NewGuid();tray.RefreshPresence(session);await Until(()=>tray.Documents.Single().Capture?.RequestId==handler.LastRequest);} + void Frames(){var id=tray.Documents.Single().Capture!.RequestId;Send(new(){Kind="snapshot-begin",SnapshotId=id,End=22});Send(new(){Kind="snapshot-fragment",SnapshotId=id,Fragment=new(){ParagraphIndex=1,Start=0,End=10,OutlineLevel=1,Text="Chapter 1\r",CompletesParagraph=true}});Send(new(){Kind="snapshot-fragment",SnapshotId=id,Fragment=new(){ParagraphIndex=2,Start=10,End=22,OutlineLevel=10,Text="Exact prose\r",CompletesParagraph=true}});Send(new(){Kind="snapshot-end",SnapshotId=id});} + try{ + handler.Transient=2;await Request();Frames();await Until(()=>tray.Documents.Single().AcceptedRevision==1); + Check(handler.Bodies.Count==3&&handler.Bodies.Distinct().Count()==1,"Transient capture uploads retry the exact prepared request and canonical-ID proposal, without rereading Word"); + handler.Permanent=true;await Request();Frames();await Until(()=>tray.Documents.Single().Status.Contains("retained in Companion memory")); + Check(tray.Documents.Single().Status.Contains("capture_timeout")||tray.Documents.Single().Status.Contains("expired"),"Companion reports bounded server rejection detail instead of generic subscription/access denial"); + var before=handler.Bodies.Count;handler.Permanent=false;handler.Next=Guid.NewGuid();tray.RefreshPresence(session);await Until(()=>handler.Bodies.Count==before+1);await Until(()=>tray.Documents.Single().Status.Contains("Manuscript received")); + Check(JsonSerializer.Deserialize(handler.Bodies[^1],new JsonSerializerOptions(JsonSerializerDefaults.Web))!.Paragraphs.Length==2,"Fresh explicit wizard authorisation can resubmit retained unchanged raw paragraphs without new Word frames"); + handler.Permanent=true;await Request();Frames();await Until(()=>tray.Documents.Single().Status.Contains("retained in Companion memory")); + before=handler.Bodies.Count;revision=2;Register();handler.Permanent=false;await Request();await Task.Delay(800); + Check(handler.Bodies.Count==before,"Document revision change clears the failed upload buffer; old prose is not replayed against new Word state"); + handler.Permanent=true;Frames();await Until(()=>tray.Documents.Single().Status.Contains("retained in Companion memory")); + before=handler.Bodies.Count;tray.SelectBook(session,4,false);handler.Book=4;handler.Permanent=false;await Request();await Task.Delay(800); + Check(handler.Bodies.Count==before,"Book association change clears the failed buffer; no prose is replayed into another book"); + handler.Permanent=true;Frames();await Until(()=>tray.Documents.Single().Status.Contains("retained in Companion memory")); + before=handler.Bodies.Count;await cloud.SignOutAsync();cloud.Connect("https://capture.test/");await Until(()=>cloud.Status().Books.Any(b=>b.BookId==3));await cloud.CheckConnection();tray.SelectBook(session,4,false);handler.Permanent=false;await Request();await Task.Delay(800); + Check(handler.Bodies.Count==before,"Account context change clears the failed buffer; fresh pairing cannot replay the previous account source"); + + }finally{cancel.Cancel();try{await heartbeats;}catch(OperationCanceledException){}} + } + private static async Task Until(Func condition){for(int n=0;n<400;n++){if(condition())return;await Task.Delay(50);}throw new Exception("Capture upload state timed out");} + private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);} + private sealed class Handler:HttpMessageHandler + { + public int Book=3;public int Transient;public bool Permanent;public Guid Next,LastRequest;public List Bodies=[]; + protected override async Task SendAsync(HttpRequestMessage request,CancellationToken cancellation) + { + var path=request.RequestUri!.AbsolutePath; + HttpResponseMessage Json(object value,HttpStatusCode status=HttpStatusCode.OK)=>new(status){Content=JsonContent.Create(value)}; + if(path.EndsWith("/pair"))return Json(new{code="00112233445566778899AABB"}); + if(path.EndsWith("/token"))return Json(new{accessToken="fixture-access"}); + if(path.EndsWith("/books"))return Json(new[]{new{bookId=3,title="Synthetic book"},new{bookId=4,title="Other authorised book"}}); + if(path.EndsWith("/connection"))return Json(new{state="Connected",authentication="verified",server="online",expiresUtc=DateTime.UtcNow.AddHours(4)}); + if(path.EndsWith("/presence")){ + var input=await request.Content!.ReadFromJsonAsync(cancellation); + if(Next!=Guid.Empty){input!.Navigation=new(){Kind="wizard-capture",Id=Next,BookId=Book,SessionId=Guid.Parse(path.Split('/')[6]),Revision=input.Revision,ParagraphTracking=true};LastRequest=Next;Next=Guid.Empty;} + return Json(input!); + } + if(path.EndsWith("/manuscript-capture")){ + var body=await request.Content!.ReadAsStringAsync(cancellation);Bodies.Add(body);var capture=JsonSerializer.Deserialize(body,new JsonSerializerOptions(JsonSerializerDefaults.Web))!; + if(Transient-->0)return Json(new{code="capture_storage_unavailable",message="Durable save temporarily unavailable",retryable=true},HttpStatusCode.ServiceUnavailable); + if(Permanent)return Json(new{code="capture_timeout",message="Capture authorisation expired; request capture again",retryable=false},HttpStatusCode.Gone); + return Json(new NativePresence{CaptureRequestId=capture.RequestId,Revision=capture.Revision,ParagraphRevision=1,CanonicalParagraphIds=[Guid.Parse("11111111-1111-4111-8111-111111111111"),Guid.Parse("22222222-2222-4222-8222-222222222222")]}); + } + if(request.Method==HttpMethod.Delete)return Json(new NativePresence()); + return Json(new{},HttpStatusCode.NotFound); + } + } +} diff --git a/PlotDirector.NativeCompanion/Tests/Program.cs b/PlotDirector.NativeCompanion/Tests/Program.cs index e18c0128..d77726d9 100644 --- a/PlotDirector.NativeCompanion/Tests/Program.cs +++ b/PlotDirector.NativeCompanion/Tests/Program.cs @@ -3,6 +3,7 @@ using PlotDirector.Companion.Agent; using PlotDirector.Companion.Client; using PlotDirector.Companion.Protocol; +if(args.Contains("--native-capture-upload")){await NativeCaptureUploadTests.Run();return;} var passed = 0; void Check(bool value,string name) {if(!value)throw new Exception(name);passed++;Console.WriteLine("PASS "+name);} async Task Until(Func condition,string name) {using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(12));while(!condition()){await Task.Delay(20,timeout.Token);}Check(true,name);}