using System.Net; using System.Net.Http.Json; using System.Text.Json; using PlotDirector.Companion.Agent; using PlotDirector.Companion.Protocol; using PlotDirector.Companion.Protocol.Manuscript; internal static class ChapterHandshakeTests { private static void Check(bool value,string name){if(!value)throw new Exception(name);Console.WriteLine("PASS "+name);} public static async Task Run() { await AutomaticRangeLifecycle(); await RibbonLifecycle(); foreach(var scenario in new[]{(Edited:Array.Empty(),Missing:-1,Geometry:-1),(Edited:new[]{17},Missing:-1,Geometry:-1),(Edited:new[]{7,22,47},Missing:-1,Geometry:-1),(Edited:Array.Empty(),Missing:31,Geometry:-1),(Edited:Array.Empty(),Missing:-1,Geometry:47),(Edited:Array.Empty(),Missing:-2,Geometry:-1)}) { var changed=scenario.Edited;var fallback=(scenario.Missing>=0?1:0)+(scenario.Geometry>=0?1:0);var handler=new Handler(changed,scenario.Missing,scenario.Geometry);using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://handshake.test/");await Until(()=>cloud.Status().Books.Any());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 session=Guid.NewGuid();var lease=Guid.NewGuid();long sequence=0;var pendingCommands=new Queue(); sessions.Attach(instance,lease,chapters:true,liveChapterText:true);tray.Attach(instance,lease,chapters:true); Message Send(Message m){m.WordInstanceId=instance;m.SessionId=session;m.Revision=1;m.Sequence=++sequence;var answer=tray.Exchange(instance,m,sessions.Apply(lease,m),lease);if(answer.Command?.Kind=="chapter-check")pendingCommands.Enqueue(answer.Command);return answer;} Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Synthetic reopen.docx"}]});tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",WordSaved=true}); using var stop=new CancellationTokenSource();var heartbeats=tray.Heartbeat(stop.Token);var watch=System.Diagnostics.Stopwatch.StartNew(); try { for(var c=0;c<48;c++) { AdapterCommand? command=null;await Until(()=>{Send(new(){Kind="selection",WordSaved=true});if(pendingCommands.Count>0)command=pendingCommands.Dequeue();return command!=null;}); var body=handler.Current[c];var start=handler.Starts[c]; Send(new(){Kind="chapter-begin",SnapshotId=command!.Id,BookId=3,Start=start,End=start+body.Length,DocumentEnd=handler.Starts[47]+handler.Current[47].Length,WordSaved=true,ChapterTitle=c==47?"":((c+1)*2+1).ToString("X8")}); void Chunks(string action,string value){for(var offset=0;offsethandler.Reused==1);await Until(()=>tray.PresentationDocuments.Single().SceneId.HasValue);Check(handler.Finishes==0,"Writing Context is available before the other 47 chapters are acknowledged"); var progress=tray.ChapterProgressForDisplay(session); Check(progress?.Matching==1&&progress.Total==48&&progress.Message.Contains("1 verified ยท 47 pending"),"Progress counts acknowledged checkpoints rather than completed Word reads");} } if(scenario.Missing==-2) { await Until(()=>handler.ReuseRequests==2); Check(tray.ChapterProgressForDisplay(session)?.Matching==1,"Forty-seven calculated fingerprints remain pending until the server acknowledges their checkpoints"); Send(new(){Kind="close"});handler.ReleaseSecond.SetResult();await Task.Delay(100); Check(tray.PresentationDocuments.All(d=>d.Session!=session),"Closing during final batch rejects the late reuse acknowledgement"); Check(handler.Finishes==0,"Interrupted reuse cannot report whole-manuscript completion after close");continue; } await Until(()=>tray.ChapterProgressForDisplay(session)?.State=="Synchronised");await Until(()=>tray.PresentationDocuments.Single().SceneId.HasValue); Check(handler.ReuseRequests==2&&handler.Reused==48-changed.Length-fallback,"Matching chapters use two bounded acknowledgements, including early current-chapter readiness"); Check(handler.AcceptRequests==changed.Length*2+fallback&&handler.Reconciled==changed.Length,"Actual request counts prove only changed chapters submit reconciliation prose"); Check(tray.ChapterProgressForDisplay(session)?.State=="Synchronised","Batch reuse reaches independently confirmed Up to date"); Check(tray.ChapterDiagnostics(session).Contains($"reused={48-changed.Length-fallback}")&&tray.ChapterDiagnostics(session).Contains($"reconciled={changed.Length}"),"Diagnostics distinguish reused, submitted and reconciled chapters"); Console.WriteLine($"MEASURE agent HTTP-contract fixture: chapters=48 changed={changed.Length} reuseRequests={handler.ReuseRequests} acceptanceRequests={handler.AcceptRequests} reconciled={handler.Reconciled} payloadBytes={handler.Bytes} totalMs={watch.Elapsed.TotalMilliseconds:F1}; HTTP in-memory, no Word/real network/SQL."); } finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}} } } private sealed class SyncClock:TimeProvider { private DateTimeOffset value=DateTimeOffset.UtcNow; public override DateTimeOffset GetUtcNow()=>value; public void Advance(double seconds)=>value=value.AddSeconds(seconds); } private static async Task AutomaticRangeLifecycle() { var handler=new Handler([],-1,-1);using var cloud=new CloudGateway(handler,_=>{}); cloud.Connect("https://handshake.test/");await Until(()=>cloud.Status().Books.Any());await cloud.CheckConnection(); var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var clock=new SyncClock(); var tray=new TrayCoordinator(sessions,cloud,ai,clock);var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid(); long sequence=0,revision=1;var commands=new Queue();var detailed=0;var probes=0;var saved=true; sessions.Attach(instance,lease,chapters:true,liveChapterText:true);tray.Attach(instance,lease,chapters:true,rangeChecks:true); Message Send(Message message) { message.WordInstanceId=instance;message.SessionId=session;message.Revision=revision;message.Sequence=++sequence; var answer=tray.Exchange(instance,message,sessions.Apply(lease,message),lease); if(answer.Command is {Kind:"chapter-check"} command)commands.Enqueue(command); if(answer.Command is {Kind:"chapter-recheck-revision"}){revision++;Register();} return answer; } void Register()=>Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=revision,Title="Disposable periodic range fixture.docx"}]}); void Select()=>Send(new(){Kind="selection",WordSaved=saved}); async Task ReadNext() { await Until(()=>{Select();return commands.Count>0;});var command=commands.Dequeue(); var c=Array.FindIndex(handler.Starts,p=>p==command.Chapter!.Start); if(c<0)throw new Exception("Fixture received a non-boundary chapter request"); var text=handler.Current[c];var xml=ChapterRangeVerificationTests.Xml(c,text);var next=c==47?"":((c+1)*2+1).ToString("X8"); if(command.ObserveOnly) { Send(new(){Kind="chapter-observe",SnapshotId=command.Id,ChapterId=command.RangeBaseline!.ChapterId,Start=handler.Starts[c],End=handler.Starts[c]+text.Length, Action=ChapterRangeVerification.Content(text)==command.RangeBaseline.ContentHash?"matching":"changed",WordSaved=false}); return; } var light=command.RangeBaseline!=null&&ChapterRangeVerification.Compare(text,xml,command.RangeBaseline,next)==ChapterRangeResult.Matching; if(command.RangeBaseline!=null)probes++; if(!light&&command.RecheckRevision){revision++;Register();Select();return;} if(!light)detailed++; Send(new(){Kind="chapter-begin",SnapshotId=command.Id,Start=handler.Starts[c],End=handler.Starts[c]+text.Length,DocumentEnd=handler.Starts[47]+handler.Current[47].Length,WordSaved=true,ChapterTitle=next}); void Chunk(string action,string value){for(var n=0;ntray.ChapterProgressForDisplay(session)?.State=="Synchronised"); Check(detailed==48&&probes==0,"Initial reopen retains the existing qualified native identity reader"); var baselineReused=handler.Reused;var baselineAccept=handler.AcceptRequests;var finish=handler.Finishes; detailed=probes=0; handler.Current[13]=handler.Current[13].Replace("synthetic","different"); // Three edits in the same chapter coalesce. Cursor is deliberately in // Chapter 1, so it cannot serve as evidence that Chapter 14 changed. for(var i=0;i<3;i++){revision++;Register();Select();clock.Advance(1);} Select();await Task.Delay(100); Check(commands.Count==0,"Automatic chapter checking waits for three seconds of edit inactivity"); clock.Advance(2); var watch=System.Diagnostics.Stopwatch.StartNew(); for(var i=0;i<48;i++) { await ReadNext(); if(i==0) { await Until(()=>handler.Reused>baselineReused); handler.HoldNextPresence=1;Send(new(){Kind="selection",Start=1,WordSaved=true}); await handler.HeldPresence.Task.WaitAsync(TimeSpan.FromSeconds(5)); } } await Until(()=>handler.Finishes==finish+1&&tray.ChapterProgressForDisplay(session)?.State=="Synchronised"); var manifests=handler.ManifestRequests;handler.ReleasePresence.TrySetResult();await Task.Delay(100);Select(); Check(handler.ManifestRequests==manifests&&commands.Count==0,"An older in-flight presence revision cannot discard newly accepted chapter work or restart verification"); Check(detailed==1&&probes==48,"A single saved chapter edit performs forty-seven lightweight checks and one detailed chapter read"); Check(handler.Reused-baselineReused==47&&handler.AcceptRequests-baselineAccept==2&&handler.Reconciled==1,"Automatic lifecycle reuses forty-seven checkpoints in batches and reconciles only Chapter 14"); Check(tray.ChapterProgressForDisplay(session) is {Matching:48,Total:48,State:"Synchronised"},"Automatic saved edit returns to forty-eight verified without a ribbon command"); Console.WriteLine($"MEASURE incremental HTTP fixture: debounce=3s virtual, rangeChecks={probes}, detailedReads={detailed}, reused=47, reconciled=1, processingMs={watch.Elapsed.TotalMilliseconds:F1}; includes held presence reply, synthetic XML, no Word extraction or COM."); var reuse=handler.ReuseRequests;var accept=handler.AcceptRequests;finish=handler.Finishes;detailed=probes=0; clock.Advance(59);Select();await Task.Delay(50);Check(commands.Count==0,"Periodic verification does not run continuously after a completed cycle"); clock.Advance(1); for(var i=0;i<48;i++)await ReadNext(); await Until(()=>tray.ChapterDiagnostics(session).Contains("retained=48")); Check(detailed==0&&probes==48&&handler.ReuseRequests==reuse&&handler.AcceptRequests==accept&&handler.Finishes==finish,"Sixty-second unchanged checks retain all live checkpoints without any server reacceptance"); // Manual Synchronise immediately enters the same periodic range path. Send(new(){Kind="tray-sync"}); for(var i=0;i<48;i++)await ReadNext(); await Until(()=>tray.ChapterDiagnostics(session).Contains("retained=48")); Check(handler.RepairRequests==0&&handler.AcceptRequests==accept,"Manual Synchronise uses the range pipeline without invoking Repair"); // A periodic probe, without a length/saved/selection revision signal, // discovers changed content and requests a new Word revision first. handler.Current[22]=handler.Current[22].Replace("synthetic","different"); var oldRevision=revision;clock.Advance(60); while(revision==oldRevision)await ReadNext(); Check(revision>oldRevision,"Periodic range checks discover same-length edits without relying on Word change notifications"); clock.Advance(3);detailed=probes=0;var priorReconciled=handler.Reconciled;finish=handler.Finishes; for(var i=0;i<48;i++)await ReadNext(); await Until(()=>handler.Finishes==finish+1); Check(detailed==1&&handler.Reconciled==priorReconciled+1,"A detected periodic mismatch is reconciled only under the newly registered revision"); // Undo before synchronisation restores accepted content; no prose // reconciliation should be necessary for that revision. handler.Current[7]=handler.Current[7].Replace("synthetic","different"); revision++;Register();Select(); handler.Current[7]=handler.Current[7].Replace("different","synthetic"); revision++;Register();Select();clock.Advance(3);detailed=0;priorReconciled=handler.Reconciled;finish=handler.Finishes; for(var i=0;i<48;i++)await ReadNext();await Until(()=>handler.Finishes==finish+1); Check(detailed==0&&handler.Reconciled==priorReconciled,"Undo restoring accepted chapter content reuses checkpoints without reconciliation"); handler.Current[7]=handler.Current[7].Replace("synthetic","different"); revision++;Register();Select();clock.Advance(3);detailed=0;finish=handler.Finishes; for(var i=0;i<48;i++)await ReadNext();await Until(()=>handler.Finishes==finish+1); Check(detailed==1&&handler.Reconciled==priorReconciled+1,"Redo takes the same selective automatic lifecycle"); // Length changes require live position updates downstream, not prose // reconciliation or native paragraph walks in unaffected chapters. handler.Current[2]=handler.Current[2].Replace("synthetic synthetic","extra",StringComparison.Ordinal); handler.Current[35]=handler.Current[35].TrimEnd('\r')+" Longer paragraph.\r"; for(var i=1;i<48;i++)handler.Starts[i]=handler.Starts[i-1]+handler.Current[i-1].Length; revision++;Register();Select();clock.Advance(3);detailed=0;priorReconciled=handler.Reconciled;finish=handler.Finishes; for(var i=0;i<48;i++)await ReadNext();await Until(()=>handler.Finishes==finish+1); Check(detailed==2&&handler.Reconciled==priorReconciled+2,"Edits in two chapters rebase later seek hints and reconcile only the two changed chapters"); saved=false;handler.Current[9]=handler.Current[9].Replace("synthetic","different");revision++;Register();Select();clock.Advance(3); accept=handler.AcceptRequests;reuse=handler.ReuseRequests;priorReconciled=handler.Reconciled; for(var i=0;i<48;i++)await ReadNext(); Check(tray.ChapterDiagnostics(session).Contains("editedInMemory=1")&&handler.AcceptRequests==accept&&handler.ReuseRequests==reuse,"Unsaved range observations detect edited content without submitting incoherent native positions"); handler.Current[9]=handler.Current[9].Replace("different","synthetic"); handler.Current[41]=handler.Current[41].Replace("synthetic","different"); clock.Advance(60); for(var i=0;i<48;i++)await ReadNext(); Check(tray.ChapterDiagnostics(session).Contains("editedInMemory=1")&&handler.Reconciled==priorReconciled,"Periodic observations detect same-length changes and Undo while Word remains already unsaved"); saved=true;revision++;Register();Select();clock.Advance(3);detailed=0;finish=handler.Finishes; for(var i=0;i<48;i++)await ReadNext();await Until(()=>handler.Finishes==finish+1); Check(detailed==1&&handler.Reconciled==priorReconciled+1,"Saving observed in-memory edits automatically reconciles only the remaining changed chapter"); } finally{handler.ReleasePresence.TrySetResult();stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}} } private static async Task RibbonLifecycle() { var handler=new Handler([17],-1,-1); using var cloud=new CloudGateway(handler,_=>{}); cloud.Connect("https://handshake.test/"); await Until(()=>cloud.Status().Books.Any()); 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 session=Guid.NewGuid();var lease=Guid.NewGuid();long sequence=0,revision=1; sessions.Attach(instance,lease,chapters:true,liveChapterText:true);tray.Attach(instance,lease,chapters:true); Message Send(Message m){m.WordInstanceId=instance;m.SessionId=session;m.Revision=revision;m.Sequence=++sequence;return tray.Exchange(instance,m,sessions.Apply(lease,m),lease);} Message Register()=>Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=revision,Title="Disposable edit fixture.docx"}]}); Register(); Check(tray.ChapterDiagnostics(session).Contains("Book association missing"),"An unassociated session diagnoses the missing book instead of implying verification is underway"); tray.SelectBook(session,3,false);Send(new(){Kind="active"}); Send(new(){Kind="selection",WordSaved=false}); Check(Send(new(){Kind="tray-sync"}).ChapterProgress?.State=="Save required","Synchronise on an unsaved edit shows the save requirement"); Check(Send(new(){Kind="tray-repair"}).ChapterProgress?.Message.Contains("Repair Synchronisation")==true&&handler.RepairRequests==0,"Repair reports its saved-state refusal without submitting stale evidence"); revision++;Check(Register().Command==null,"Revision change clears old commands without emitting a stale cancel"); Send(new(){Kind="tray-sync"});Send(new(){Kind="tray-sync"}); using var stop=new CancellationTokenSource(); var heartbeats=tray.Heartbeat(stop.Token); try { Send(new(){Kind="selection",WordSaved=true}); await Until(()=>tray.ChapterDiagnostics(session).Contains("Fixture repair refused")); Check(handler.RepairRequests==1&&tray.ChapterProgressForDisplay(session)?.State=="Needs review","Repeated clicks coalesce and an HTTP repair refusal reaches the ribbon"); Send(new(){Kind="tray-repair"}); AdapterCommand? command=null; await Until(()=>{var reply=Send(new(){Kind="selection",WordSaved=true});if(reply.Command?.Kind=="chapter-check")command=reply.Command;return command!=null;}); Check(handler.RepairRequests==2&&command!.Revision==revision&&command.OperationId!=Guid.Empty,"Repair starts verification against the freshly confirmed saved revision"); Send(new(){Kind="tray-sync"}); Check(tray.ChapterDiagnostics(session).Contains("already running")&&handler.RepairRequests==2,"Synchronise joins an active explicitly authorised verification"); revision++;Register(); Check(Send(new(){Kind="chapter-end",Revision=revision,SnapshotId=command!.Id}).Command==null,"Further edits retire the old chapter command"); Check(tray.ChapterDiagnostics(session).Contains("Document revision changed"),"Interrupted verification reports the revision change"); } finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}} } private static async Task Until(Func ready){for(var n=0;n<3000;n++){if(ready())return;await Task.Delay(5);}throw new Exception("Handshake fixture timed out");} private sealed class Handler:HttpMessageHandler { public readonly Guid Manuscript=Guid.NewGuid();public readonly string[] Current;public readonly int[] Starts;private readonly string[] hashes;private readonly int[] acceptedLengths;private readonly int missing,geometry;private long revision=1; public readonly TaskCompletionSource ReleaseSecond=new(TaskCreationOptions.RunContinuationsAsynchronously); public int ReuseRequests,Reused,AcceptRequests,Reconciled,Finishes;public long Bytes;private bool currentReady; public int HoldNextPresence,ManifestRequests; public readonly TaskCompletionSource HeldPresence=new(TaskCreationOptions.RunContinuationsAsynchronously),ReleasePresence=new(TaskCreationOptions.RunContinuationsAsynchronously); public int RepairRequests;private AdapterCommand? repair; public Handler(int[] changed,int missing,int geometry) { this.missing=missing;this.geometry=geometry; var original=Enumerable.Range(0,48).Select(c=>$"Chapter {c}\r"+string.Join(" ",Enumerable.Repeat("synthetic",3187))+"\r").ToArray(); acceptedLengths=original.Select(p=>p.Length).ToArray(); Current=original.Select((s,c)=>changed.Contains(c)?s.Replace("synthetic","different"):s).ToArray();Starts=new int[48];for(var c=1;c<48;c++)Starts[c]=Starts[c-1]+Current[c-1].Length; hashes=original.Select((s,c)=>ChapterFingerprint.Content([$"Chapter {c}\r",s[($"Chapter {c}\r").Length..]])).ToArray(); } protected override async Task SendAsync(HttpRequestMessage request,CancellationToken cancellation) { var path=request.RequestUri!.AbsolutePath;HttpResponseMessage Json(object value)=>new(HttpStatusCode.OK){Content=JsonContent.Create(value)}; if(path.EndsWith("/pair"))return Json(new{code="00112233445566778899AABB"});if(path.EndsWith("/token"))return Json(new{accessToken="fixture"});if(path.EndsWith("/books"))return Json(new[]{new{bookId=3,title="Synthetic book"}});if(path.EndsWith("/connection"))return Json(new{state="Connected",authentication="verified",server="online",expiresUtc=DateTime.UtcNow.AddHours(4)}); if(path.EndsWith("/presence")){var p=(await request.Content!.ReadFromJsonAsync(cancellation))!;p.ChapterSyncSupported=true;p.ParagraphRevision=revision;p.Navigation=Interlocked.Exchange(ref repair,null);if(currentReady){p.ChapterId=1;p.SceneId=10;p.ChapterTitle="Chapter 0";p.SceneTitle="Verified scene";}if(Interlocked.Exchange(ref HoldNextPresence,0)==1){HeldPresence.TrySetResult();await ReleasePresence.Task.WaitAsync(cancellation);}return Json(p);} if(path.EndsWith("/repair")) { if(++RepairRequests==1)return new(HttpStatusCode.Conflict){Content=JsonContent.Create(new{message="Fixture repair refused."})}; var target=(await request.Content!.ReadFromJsonAsync(cancellation))!; var operation=Guid.NewGuid(); repair=new(){Id=operation,Kind="chapter-repair",SessionId=target.SessionId,Revision=target.WordRevision}; return Json(new ChapterRepairRequested{OperationId=operation,Message="Fixture repair accepted."}); } if(path.EndsWith("/chapter-sync")){ManifestRequests++;return Json(new ChapterManifest{CheckpointReuseSupported=true,NativePositionsSupported=true,BookId=3,Mode="OnSave",ManuscriptId=Manuscript,Revision=revision,Chapters=Enumerable.Range(0,48).Select(c=>new ChapterManifestItem{ChapterId=c+1,DurableAccepted=c!=missing,PositionHash=c==geometry?new string('A',64):"",Algorithm=ChapterFingerprint.Version,HeadingNativeId=(c*2+1).ToString("X8"),ContentHash=hashes[c],IdentityHash=ChapterFingerprint.Identity([new(){NativeId=(c*2+1).ToString("X8"),Length=($"Chapter {c}\r").Length,Outline=1},new(){NativeId=(c*2+2).ToString("X8"),Length=acceptedLengths[c]-($"Chapter {c}\r").Length,Outline=10}]),NextHeadingId=c==47?"":((c+1)*2+1).ToString("X8"),Start=acceptedLengths.Take(c).Sum(),End=acceptedLengths.Take(c+1).Sum(),ParagraphCount=2}).ToArray()});} if(path.EndsWith("/reuse")){var data=await request.Content!.ReadAsByteArrayAsync(cancellation);Bytes+=data.Length;var batch=JsonSerializer.Deserialize(data,new JsonSerializerOptions(JsonSerializerDefaults.Web))!;if(batch.Chapters.Any(p=>p.Paragraphs.Any(r=>r.Text!=null)))throw new Exception("Reuse leaked prose");ReuseRequests++;if(missing==-2&&ReuseRequests==2)await ReleaseSecond.Task.WaitAsync(cancellation);Reused+=batch.Chapters.Length;if(batch.Chapters.Any(p=>p.ChapterId==1))currentReady=true;return Json(new ChapterReuseReply{ChapterIds=batch.Chapters.Select(p=>p.ChapterId).ToArray(),Revision=revision});} if(path.EndsWith("/validate")){var data=await request.Content!.ReadAsByteArrayAsync(cancellation);Bytes+=data.Length;AcceptRequests++;var p=JsonSerializer.Deserialize(data,new JsonSerializerOptions(JsonSerializerDefaults.Web))!;if(p.ContentHash==hashes[p.ChapterId-1])return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",Revision=revision,ChapterId=p.ChapterId});if(p.Paragraphs.All(r=>r.Text==null))return Json(new ChapterSyncReply{State="Changed",AllowText=true,Revision=revision,ChapterId=p.ChapterId});Reconciled++;acceptedLengths[p.ChapterId-1]=p.End-p.Start;hashes[p.ChapterId-1]=p.ContentHash;return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",Revision=++revision,ChapterId=p.ChapterId});} if(path.EndsWith("/finish")){Finishes++;return Json(new ChapterSyncProgress{State="Synchronised",Matching=48,Total=48});} return Json(new{}); } } }