235 lines
29 KiB
C#

using System.Diagnostics;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using PlotDirector.Companion.Protocol;
namespace PlotDirector.Companion.Agent;
// Network/authentication stay in the agent. Access tokens are memory-only; installation credentials use Windows-protected storage.
public sealed partial class CloudGateway : IDisposable
{
private readonly object gate=new();
private readonly HttpClient http;
private readonly Action<string> openBrowser;
private CancellationTokenSource? pairing;
private Uri? origin;
private string? token;
private Guid authenticationContext=Guid.NewGuid();
private string state="Not signed in";
private ConnectionHealth health=new();
private Task connectionCheck=Task.CompletedTask;private Guid catalogVersion;private int checking;private DateTime nextCheck;
private readonly Dictionary<string,AiChapterResult> successful=[];
private CompanionBook[] books=[];
private readonly string? settingsPath;
private static readonly JsonSerializerOptions Json=new(JsonSerializerDefaults.Web);
public CloudGateway(HttpMessageHandler? handler=null,Action<string>? browser=null,string? settingsPath=null,ICompanionStateStore? stateStore=null,TimeProvider? timeProvider=null,Func<Uri,Func<Task<string?>>,Microsoft.AspNetCore.SignalR.Client.HubConnection>? notificationConnectionFactory=null)
{
notificationFactory=notificationConnectionFactory??CreateNotificationConnection;
http=new(handler??new HttpClientHandler{AllowAutoRedirect=false}){Timeout=TimeSpan.FromMinutes(6)};
openBrowser=browser??(url=>Process.Start(new ProcessStartInfo(url){UseShellExecute=true}));this.settingsPath=settingsPath;clock=timeProvider??TimeProvider.System;storage=stateStore??(settingsPath!=null&&OperatingSystem.IsWindows()?new ProtectedCompanionStateStore(Path.Combine(Path.GetDirectoryName(settingsPath)!,"installation-state.dat"),new WindowsUserProtection()):null);RestoreState();
}
public static Uri ValidateOrigin(string value)
{
if(!Uri.TryCreate(value,UriKind.Absolute,out var uri)||uri.Scheme!=Uri.UriSchemeHttps||!string.IsNullOrEmpty(uri.UserInfo)||uri.AbsolutePath!="/"||!string.IsNullOrEmpty(uri.Query)||!string.IsNullOrEmpty(uri.Fragment))throw new ArgumentException("Enter the HTTPS PlotDirector site root.");
return uri;
}
public Message Status()
{
bool refresh;Message answer;
lock(gate){Expire();refresh=token!=null&&Now.UtcDateTime>=nextCheck;answer=new(){Status=state,Books=books,AuthenticationContext=authenticationContext,ServerUrl=origin?.AbsoluteUri??ReadOrigin(),Health=CopyHealth()};}
if(refresh)_=CheckConnection();return answer;
}
private ConnectionHealth CopyHealth()=>new(){State=health.State,AccountName=health.AccountName,Server=health.Server,Authentication=health.Authentication,Ai=health.Ai,Explanation=health.Explanation,VerifiedUtc=health.VerifiedUtc,ExpiresUtc=health.ExpiresUtc};
private void Expire(){if(token!=null&&health.ExpiresUtc!=default&&Now.UtcDateTime>=health.ExpiresUtc){InvalidateAccess(authenticationContext);health.Ai="unknown";}}
public Task CheckConnection(){lock(gate){if(!connectionCheck.IsCompleted)return connectionCheck;return connectionCheck=CheckConnectionCore();}}
private async Task CheckConnectionCore()
{
if(Interlocked.Exchange(ref checking,1)!=0)return;
Guid context;lock(gate){context=authenticationContext;nextCheck=Now.UtcDateTime.AddMinutes(2);health.Server="checking";}
try{var result=await Get<ConnectionHealth>("api/native-companion/connection",context);var accessible=await Get<CompanionBook[]>("api/native-companion/books",context);lock(gate)if(authenticationContext==context){books=accessible.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(500).ToArray();result.VerifiedUtc=Now.UtcDateTime;result.State="Connected";result.AccountName=saved.AccountName;health=result;state="Signed in (verified)";retryFailures=0;retryAfter=DateTimeOffset.MinValue;}}
catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException){lock(gate)if(authenticationContext==context){health.Server=token==null?"unknown":"offline";health.State=saved.Active!=null?"Reconnecting":"Action required";health.Explanation=saved.Active!=null?"Server unavailable. Reconnecting automatically; Word remains available.":"Sign in or check the server address.";if(e is CompanionStorageException)ConnectionFailure(e);else if(saved.Active!=null)TransientFailure();}}
finally{Volatile.Write(ref checking,0);}
}
private string ReadOrigin(){try{return !string.IsNullOrEmpty(saved.Server)?saved.Server:settingsPath!=null&&File.Exists(settingsPath)?File.ReadAllText(settingsPath):"";}catch(IOException){return "";}}
public void Connect(string address,bool forcePairing=false)
{
var uri=ValidateOrigin(address);
if(storage!=null&&!stateLoaded){RestoreState();if(storageUnavailable)throw new InvalidOperationException("Protected settings are unavailable or another Windows session owns the Companion. Close that Companion or fix the user profile first.");if(!stateLoaded)stateLoaded=true;}
lock(gate){if(!forcePairing&&saved.Active!=null&&ValidateOrigin(saved.Active.Site)==uri){_=ReconnectAsync();return;}if(saved.Revocations.Count>=15)throw new InvalidOperationException("Reconnect to complete pending sign-outs before approving another account.");}
if(saved.Active!=null){ChangeAccount(address);return;}
DisconnectPresence();CancellationTokenSource stop;
lock(gate){pairing?.Cancel();pairing=stop=new(TimeSpan.FromMinutes(5));origin=uri;authenticationContext=Guid.NewGuid();token=null;books=[];health=new(){Server="connecting",Authentication="pending",State="Action required"};state="Starting browser sign-in…";}
_=Task.Run(async()=>{
try
{
if(settingsPath!=null){Directory.CreateDirectory(Path.GetDirectoryName(settingsPath)!);await File.WriteAllTextAsync(settingsPath,uri.AbsoluteUri,stop.Token);}
var verifier=Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier)));
using var start=await http.PostAsJsonAsync(new Uri(uri,"api/native-companion/pair"),new{challenge,persistent=storage!=null,connectionId,deviceName=Environment.MachineName},stop.Token);start.EnsureSuccessStatusCode();
var data=await start.Content.ReadFromJsonAsync<PairStart>(Json,stop.Token)??throw new InvalidDataException();
if(data.Code==null||data.Code.Length!=24||!data.Code.All(Uri.IsHexDigit))throw new InvalidDataException();
lock(gate)if(pairing==stop)state="Approve in browser · code "+data.Code[^6..];
openBrowser(new Uri(uri,"native-companion/authorize?code="+data.Code).AbsoluteUri);
while(!stop.IsCancellationRequested)
{
await Task.Delay(2000,stop.Token);
using var response=await http.PostAsJsonAsync(new Uri(uri,"api/native-companion/token"),new{code=data.Code,verifier},stop.Token);
if(response.StatusCode==HttpStatusCode.Accepted)continue;
response.EnsureSuccessStatusCode();var grant=await response.Content.ReadFromJsonAsync<TokenReply>(Json,stop.Token)??throw new InvalidDataException();
if(storage!=null){
if(grant.InstallationId==Guid.Empty||grant.AccountId<=0||grant.ConnectionId!=connectionId||grant.DeviceSecret==null||grant.DeviceSecret.Length!=64||!grant.DeviceSecret.All(Uri.IsHexDigit)||string.IsNullOrEmpty(grant.AccessToken)||grant.ExpiresUtc<=Now)throw new InvalidDataException("Update PlotDirector for persistent Companion approval.");
lock(gate){if(pairing!=stop||stop.IsCancellationRequested||disposed)return;credentialVersion++;saved.Server=uri.AbsoluteUri;saved.AccountId=grant.AccountId;saved.AccountName=grant.AccountName;saved.Active=new(){InstallationId=grant.InstallationId,AccountId=grant.AccountId,AccountName=grant.AccountName,Site=uri.AbsoluteUri,Credential=grant.DeviceSecret,RefreshExpiresUtc=grant.RefreshExpiresUtc};token=grant.AccessToken;accessExpires=grant.ExpiresUtc;health.ExpiresUtc=grant.ExpiresUtc.UtcDateTime;health.AccountName=grant.AccountName;}
await FlushSettingsAsync();await CheckConnection();return;
}
using var request=new HttpRequestMessage(HttpMethod.Get,new Uri(uri,"api/native-companion/books"));request.Headers.Authorization=new("Bearer",grant.AccessToken);
using var list=await http.SendAsync(request,stop.Token);list.EnsureSuccessStatusCode();
var available=await list.Content.ReadFromJsonAsync<CompanionBook[]>(Json,stop.Token)??[];
lock(gate)if(pairing==stop&&!stop.IsCancellationRequested){token=grant.AccessToken;books=available.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(500).Select(b=>new CompanionBook{BookId=b.BookId,Title=b.Title.Length>160?b.Title[..160]:b.Title}).ToArray();state="Signed in (four-hour grant)";health=new(){State="Connected",Server="online",Authentication="verified",VerifiedUtc=Now.UtcDateTime,ExpiresUtc=Now.UtcDateTime.AddHours(4),Ai="unknown",Explanation="Book list verified; checking AI configuration."};nextCheck=DateTime.MinValue;}
return;
}
}
catch(Exception e)when(e is HttpRequestException or OperationCanceledException or IOException or InvalidDataException or JsonException or System.ComponentModel.Win32Exception or UnauthorizedAccessException or InvalidOperationException or ArgumentException or CryptographicException)
{lock(gate)if(pairing==stop){state="Sign-in failed or expired. Check the site address and try Connect again.";health=new(){State="Action required",Server="unverified",Authentication="not-signed-in",Explanation=state};}}
});
}
public void SignOut(){_=ObserveSignOut(SignOutAsync());}
private async Task ObserveSignOut(Task operation){try{await operation;}catch(Exception e)when(AuthFailure(e)){lock(gate){health.State="Action required";health.Explanation="Sign-out could not be saved securely. Check your Windows user profile and retry.";}}}
public bool Allows(Guid context,int bookId)
{lock(gate){Expire();return token!=null&&(storage==null||(health.State=="Connected"&&checking==0&&credentialVersion==durableCredentialVersion))&&context==authenticationContext&&books.Any(b=>b.BookId==bookId);}}
public async Task<AiChapterResult> Analyse(AiChapterRequest chapter,CancellationToken cancellation,Guid expectedContext)
{
await EnsureAccess(expectedContext);
var fingerprint=expectedContext+":"+chapter.BookId+":"+chapter.ManuscriptId+":"+Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{chapter.ChapterStart,chapter.ChapterEnd,chapter.Paragraphs})));
Uri site;string access;
lock(gate){Expire();if(successful.TryGetValue(fingerprint,out var prior)&&authenticationContext==expectedContext&&token!=null)return new(){SourceRetained=prior.SourceRetained,RequestId=chapter.RequestId,DocumentRevision=chapter.Revision,ChapterTitle=chapter.ChapterTitle,State="complete",Message="Unchanged chapter: reused saved AI suggestions without uploading prose.",ReviewPath=prior.ReviewPath,Scenes=prior.Scenes};if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");}
using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/analyse-chapter")){Content=JsonContent.Create(chapter,options:Json)};
request.Headers.Authorization=new AuthenticationHeaderValue("Bearer",access);
HttpResponseMessage responseValue;
try{responseValue=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellation);}
catch(HttpRequestException){lock(gate)if(authenticationContext==expectedContext){health.Server="offline";health.Explanation="AI request could not reach the server.";}throw;}
using var response=responseValue;
if(response.StatusCode==HttpStatusCode.Unauthorized){InvalidateAccess(expectedContext);throw new InvalidOperationException("Connection needs renewal. Retry this explicit analysis after reconnection.");}
if(!response.IsSuccessStatusCode){lock(gate)if(authenticationContext==expectedContext){health.Server="degraded";health.Ai="request-failed";health.Explanation="AI request rejected or unavailable; see chapter results.";}throw new InvalidOperationException(response.StatusCode switch{HttpStatusCode.Forbidden=>"Book/subscription access denied.",HttpStatusCode.TooManyRequests=>"Server busy. Retry this chapter later.",HttpStatusCode.BadRequest=>"Chapter mapping or size was rejected. Check boundaries.",_=>"Server unavailable. Check the deployed native API."});}
// Bound server response before deserializing; never log a body/provider message.
await using var stream=await response.Content.ReadAsStreamAsync(cancellation);using var buffer=new MemoryStream();var bytes=new byte[8192];
int count;while((count=await stream.ReadAsync(bytes,cancellation))>0){if(buffer.Length+count>1024*1024)throw new InvalidDataException("AI response too large.");buffer.Write(bytes,0,count);}
buffer.Position=0;var result=await JsonSerializer.DeserializeAsync<AiChapterResult>(buffer,Json,cancellation)??throw new InvalidDataException();
if(result.RequestId!=chapter.RequestId||result.State is not ("complete" or "failed" or "cancelled")||result.Message==null||result.Message.Length>2048||result.Scenes==null||result.Scenes.Length>500||result.Scenes.Any(s=>s==null||s.Start<chapter.ChapterStart||s.End>chapter.ChapterEnd||s.End<=s.Start||s.Title==null||s.Reason==null||s.Summary==null||s.Summary.Length>600||s.Confidence==null||s.Confidence.Length>32||s.Kind!="Scene"||s.Origin!="AI"||s.Title.Length>200||s.Reason.Length>600))throw new InvalidDataException("Invalid AI mapping.");
lock(gate)if(authenticationContext==expectedContext){health.Server="online";health.Authentication="verified";health.State="Connected";health.VerifiedUtc=Now.UtcDateTime;health.Ai=result.State=="complete"?"last-request-succeeded":"request-failed";health.Explanation=result.Message;if(result.State=="complete"){if(successful.Count>=64||successful.Values.Sum(r=>r.Scenes.Length)+result.Scenes.Length>8192)successful.Clear();successful[fingerprint]=result;}}
return result;
}
public async Task<T> Get<T>(string path,Guid expectedContext,CancellationToken cancellation=default)
=>await Send<T>(HttpMethod.Get,path,null,expectedContext,cancellation);
public async Task<T> Post<T>(string path,object body,Guid expectedContext)
=>await Send<T>(HttpMethod.Post,path,body,expectedContext);
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterRepairRequested> RequestChapterRepair(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterFinish selected,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterRepairRequested>(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/repair",selected,context);
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress> FinishChapters(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterFinish completion,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress>(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/finish",completion,context);
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterManifest> ChapterManifest(int book,Guid session,long revision,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterManifest>(HttpMethod.Get,$"api/native-companion/books/{book}/chapter-sync?session={session}&wordRevision={revision}",null,context);
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterReuseReply> ReuseChapters(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterReuseRequest proof,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterReuseReply>(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/reuse",proof,context);
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterSyncReply> ValidateChapter(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterObservation proof,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterSyncReply>(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/validate",proof,context);
public async Task FailCapture(Guid id,Guid context){try{await Send<NativePresence>(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<NativePresence> Capture(ManuscriptCapture capture,Guid context){var result=await Send<NativePresence>(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<CaptureUploadException> 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(count<data.Length&&(read=await stream.ReadAsync(data.AsMemory(count),cancellation))>0)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<T> Send<T>(HttpMethod method,string path,object? body,Guid context,CancellationToken cancellation=default)
{
await EnsureAccess(context);
Uri site;string access;lock(gate){Expire();if(context!=authenticationContext||token==null)throw new InvalidOperationException("Sign in again and reselect the book.");site=origin!;access=token;}
using var stop=CancellationTokenSource.CreateLinkedTokenSource(cancellation);stop.CancelAfter(TimeSpan.FromSeconds(path=="api/native-companion/manuscript-capture"?120:15));using var request=new HttpRequestMessage(method,new Uri(site,path));request.Headers.Authorization=new("Bearer",access);if(body!=null)request.Content=JsonContent.Create(body,options:Json);
try
{
using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,stop.Token);
if(path.EndsWith("/audio-review",StringComparison.Ordinal)&&response.StatusCode==HttpStatusCode.Forbidden)
throw new InvalidOperationException("The Audio Review document lease or book access is unavailable.");
if(response.StatusCode==HttpStatusCode.Conflict&&path.EndsWith("/chapter-sync/reuse",StringComparison.Ordinal))throw new ChapterReuseConflictException();
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")&&!(response.StatusCode==HttpStatusCode.Conflict&&(path.EndsWith("/chapter-sync/validate",StringComparison.Ordinal)||path.EndsWith("/chapter-sync/repair",StringComparison.Ordinal)))){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;
var result=await JsonSerializer.DeserializeAsync<T>(buffer,Json,stop.Token);
lock(gate){if(context!=authenticationContext)throw new InvalidOperationException("Connection changed; discarded old response.");health.Server="online";health.Authentication="verified";health.State="Connected";health.VerifiedUtc=Now.UtcDateTime;if(path.EndsWith("/presence",StringComparison.Ordinal))health.Explanation="Document heartbeat verified by PlotDirector.";}
return result??throw new InvalidDataException();
}
catch(OperationCanceledException)when(!cancellation.IsCancellationRequested){lock(gate)if(context==authenticationContext){health.Server="degraded";health.State=saved.Active!=null?"Reconnecting":"Disconnected";health.Explanation="Server verification timed out. Check connection before continuing.";}throw;}
catch(HttpRequestException){lock(gate)if(context==authenticationContext){health.Server="offline";health.State=saved.Active!=null?"Reconnecting":"Disconnected";health.Explanation="Server unreachable. Saved information is not current.";}throw;}
}
public void OpenSavedPage(string path,Guid context)
{
lock(gate){Expire();if(context!=authenticationContext||token==null||origin==null)throw new InvalidOperationException("Sign in first.");
if(!path.StartsWith("/Books/Details/",StringComparison.Ordinal)&&!path.StartsWith("/Writing/Context?",StringComparison.Ordinal)&&!path.StartsWith("/Writing/Intent?",StringComparison.Ordinal))throw new InvalidDataException();
var url=new Uri(origin,path);if(url.GetLeftPart(UriPartial.Authority)!=origin.GetLeftPart(UriPartial.Authority))throw new InvalidDataException();openBrowser(url.AbsoluteUri);}
}
public void OpenSite(string page="book")
{Uri target;lock(gate){var site=origin??ValidateOrigin(ReadOrigin());target=new Uri(site,page switch{"help"=>"help/word-companion/install","context"=>"Writing/Context","intent"=>"Writing/Intent",_=>"/"});}openBrowser(target.AbsoluteUri);}
private void DisconnectPresence(){Uri? site;string? access;lock(gate){site=origin;access=token;}if(site==null||access==null)return;_ = Task.Run(async()=>{try{using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(5));using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/presence/disconnect"));request.Headers.Authorization=new("Bearer",access);using var response=await http.SendAsync(request,timeout.Token);}catch(Exception e)when(e is HttpRequestException or OperationCanceledException or ObjectDisposedException) {}});}
public void OpenCompanionPage(string path,Guid context)
{
if (string.IsNullOrEmpty(path) || !path.StartsWith("/native-companion/", StringComparison.Ordinal))
throw new InvalidDataException("The Companion page link is invalid. Reopen the manuscript and try again.");
OpenAuthenticatedPage(path, context);
}
internal void OpenWriterPage(int book, Guid instance, Guid session, Guid context)
{
if (book <= 0 || instance == Guid.Empty || session == Guid.Empty)
throw new InvalidOperationException("Open an associated manuscript before returning to Writer.");
OpenAuthenticatedPage(FormattableString.Invariant($"/Writer/Write?bookId={book}&wordInstanceId={instance:D}&wordSessionId={session:D}"), context);
}
private void OpenAuthenticatedPage(string path, Guid context)
{
lock (gate)
{
Expire();
if (context != authenticationContext || token == null || origin == null)
throw new InvalidOperationException("Sign in and reconnect Word before opening PlotDirector.");
if (!Uri.TryCreate(origin, path, out var url) || url.GetLeftPart(UriPartial.Authority) != origin.GetLeftPart(UriPartial.Authority))
throw new InvalidDataException("The PlotDirector page link is invalid. Reconnect and try again.");
openBrowser(url.AbsoluteUri);
}
}
public async Task<NativePresence> Presence(Guid instance,Guid session,NativePresence presence,Guid context,CancellationToken cancellation=default){var reply=await Send<NativePresence>(HttpMethod.Post,$"api/native-companion/instances/{instance}/documents/{session}/presence",presence,context,cancellation);await ObserveCatalog(reply.CatalogVersion,context);return reply;}
private async Task ObserveCatalog(Guid version,Guid context){if(version==Guid.Empty)return;Task running;lock(gate){if(context!=authenticationContext||catalogVersion==version)return;catalogVersion=version;running=connectionCheck;}await running;lock(gate)if(context!=authenticationContext)return;await CheckConnection();}
public async Task RemovePresence(Guid instance,Guid session,long? throughSequence=null){Guid context;lock(gate)context=authenticationContext;try{await Send<NativePresence>(HttpMethod.Delete,$"api/native-companion/instances/{instance}/documents/{session}/presence?throughSequence={throughSequence}",null,context);}catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException or ObjectDisposedException){}}
public async Task CancelRemote(Guid id)
{
try
{
Uri? site;string? access;lock(gate){site=origin;access=token;}if(site==null||access==null)return;
using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(5));using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,$"api/native-companion/analysis/{id}/cancel"));request.Headers.Authorization=new("Bearer",access);
using var response=await http.SendAsync(request,timeout.Token);
}
catch(Exception e)when(e is HttpRequestException or OperationCanceledException){ }
}
public void Dispose(){lock(gate){disposed=true;pairing?.Cancel();lifetime.Cancel();}try{FlushSettingsAsync().GetAwaiter().GetResult();}catch(Exception e)when(StorageFailure(e)){}http.Dispose();(storage as IDisposable)?.Dispose();}
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;
}
public sealed class ChapterReuseConflictException():InvalidOperationException("Checkpoint changed; refresh the accepted manifest before reusing positions.");