Deliver compact Companion interface with book covers and advanced maintenance
This commit is contained in:
parent
82a7272825
commit
57c6bd5ca5
@ -14,9 +14,10 @@ public sealed partial class CloudGateway
|
||||
private DateTimeOffset retryAfter;private int retryFailures;private bool disposed;private bool stateLoaded=true,storageUnavailable;private long credentialVersion,durableCredentialVersion;
|
||||
private DateTimeOffset Now=>clock.GetUtcNow();
|
||||
private DateTimeOffset accessExpires;private DateTimeOffset revocationAfter;
|
||||
public CompanionPreferences Preferences {get{lock(gate)return new(){Width=saved.Preferences.Width,Height=saved.Preferences.Height,RememberInDocument=saved.Preferences.RememberInDocument,LastManuscript=saved.Preferences.LastManuscript};}}
|
||||
public CompanionPreferences Preferences {get{lock(gate)return new(){AdvancedMode=saved.Preferences.AdvancedMode,Width=saved.Preferences.Width,Height=saved.Preferences.Height,RememberInDocument=saved.Preferences.RememberInDocument,LastManuscript=saved.Preferences.LastManuscript};}}
|
||||
public void SavePreferences(CompanionPreferences preferences){lock(gate)saved.Preferences=preferences;_ = PersistSafely();}
|
||||
private static string BindingKey(string site,int account,Guid manuscript)=>$"{site}|{account}|{manuscript:D}";
|
||||
public void ForgetBinding(Guid manuscript,Guid expectedContext){lock(gate){if(authenticationContext==expectedContext&&saved.Active!=null)saved.Bindings.Remove(BindingKey(saved.Active.Site,saved.Active.AccountId,manuscript));}_=PersistSafely();}
|
||||
public void RememberBinding(Guid manuscript,int book,Guid expectedContext=default){lock(gate){if(saved.Active==null)return;if((expectedContext!=Guid.Empty&&expectedContext!=authenticationContext)||!books.Any(b=>b.BookId==book))throw new InvalidOperationException("Account or book access changed; select the book again.");if(saved.Bindings.Count>=2048&&!saved.Bindings.ContainsKey(BindingKey(saved.Active.Site,saved.Active.AccountId,manuscript)))throw new InvalidOperationException("Saved manuscript association limit reached.");saved.Bindings[BindingKey(saved.Active.Site,saved.Active.AccountId,manuscript)]=book;}_=PersistSafely();}
|
||||
public int? RestoreBinding(Guid manuscript){lock(gate){var active=saved.Active;if(active==null||health.Authentication!="verified"||health.State!="Connected"||checking!=0||token==null)return null;return saved.Bindings.TryGetValue(BindingKey(active.Site,active.AccountId,manuscript),out var book)&&books.Any(b=>b.BookId==book)?book:null;}}
|
||||
private async Task PersistSafely(){try{await FlushSettingsAsync();}catch(Exception e)when(StorageFailure(e)){lock(gate){health.State="Action required";health.Explanation="Windows could not save Companion settings securely. Check access to your user profile before restarting.";}}}
|
||||
|
||||
@ -120,17 +120,17 @@ public sealed partial class CloudGateway : IDisposable
|
||||
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)
|
||||
=>await Send<T>(HttpMethod.Get,path,null,expectedContext);
|
||||
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 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 async Task<T> Send<T>(HttpMethod method,string path,object? body,Guid context)
|
||||
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=new CancellationTokenSource(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);
|
||||
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);
|
||||
@ -142,7 +142,7 @@ public sealed partial class CloudGateway : IDisposable
|
||||
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){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(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)
|
||||
|
||||
@ -3,9 +3,13 @@ namespace PlotDirector.Companion.Agent;
|
||||
// Pure presentation policy shared by portable tests and the Windows Forms view.
|
||||
public static class CompanionPresentation
|
||||
{
|
||||
public static bool NeedsAuthorisation(ConnectionHealth? health)=>health==null||(health.State=="Action required"&&health.Authentication!="pending")||(string.IsNullOrEmpty(health.State)&&health.Authentication is "expired" or "unauthorised");
|
||||
public static string WordStatus(bool connected,int book,DateTime verified,string presence,DateTime now)=>!connected?"Microsoft Word · not connected":book==0?"Microsoft Word · connected locally":presence!=""&&now-verified<TimeSpan.FromSeconds(45)?"Microsoft Word · connected to this book":"Microsoft Word · connected locally, registration pending";
|
||||
public static bool Dark(bool? windowsDark)=>windowsDark??false;
|
||||
public static string Connection(ConnectionHealth? health,DateTime now)
|
||||
{
|
||||
if(health?.Authentication=="pending")return "Waiting for browser approval…";
|
||||
if(health?.State=="Connected"&&(now-health.VerifiedUtc>TimeSpan.FromSeconds(90)||health.Server!="online"||health.Authentication!="verified"))return "Reconnecting";
|
||||
if(!string.IsNullOrEmpty(health?.State))return health.State=="Action required"?"Action required · sign in or check connection settings":health.State;
|
||||
if(health==null)return "Welcome · connect to PlotDirector";
|
||||
if(health.Authentication is "expired" or "unauthorised")return "Sign in again";
|
||||
|
||||
@ -14,7 +14,7 @@ public sealed class CredentialRotation
|
||||
}
|
||||
public sealed class CompanionPreferences
|
||||
{
|
||||
public int Width {get;set;}=880;public int Height {get;set;}=820;public bool RememberInDocument {get;set;}public Guid LastManuscript {get;set;}
|
||||
public int Width {get;set;}=540;public int Height {get;set;}=640;public bool AdvancedMode {get;set;}public bool RememberInDocument {get;set;}public Guid LastManuscript {get;set;}
|
||||
}
|
||||
public sealed class CompanionState
|
||||
{
|
||||
|
||||
36
PlotDirector.NativeCompanion/Agent/CompanionSurfaces.cs
Normal file
36
PlotDirector.NativeCompanion/Agent/CompanionSurfaces.cs
Normal file
@ -0,0 +1,36 @@
|
||||
#if WINDOWS
|
||||
using System.Drawing;
|
||||
using System.Drawing.Drawing2D;
|
||||
using System.Windows.Forms;
|
||||
namespace PlotDirector.Companion.Agent;
|
||||
internal sealed class RoundedCard:TableLayoutPanel
|
||||
{
|
||||
[System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
|
||||
public Color Outside {get;set;}
|
||||
public RoundedCard(){DoubleBuffered=true;ColumnStyles.Add(new(SizeType.Percent,100));}
|
||||
protected override void OnPaintBackground(PaintEventArgs e)
|
||||
{
|
||||
e.Graphics.Clear(Outside);e.Graphics.SmoothingMode=SmoothingMode.AntiAlias;
|
||||
var radius=Math.Min(24*DeviceDpi/96,Math.Min(Width,Height));if(radius<2)return;
|
||||
using var path=new GraphicsPath();path.AddArc(0,0,radius,radius,180,90);path.AddArc(Width-radius-1,0,radius,radius,270,90);path.AddArc(Width-radius-1,Height-radius-1,radius,radius,0,90);path.AddArc(0,Height-radius-1,radius,radius,90,90);path.CloseFigure();using var brush=new SolidBrush(BackColor);e.Graphics.FillPath(brush,path);
|
||||
}
|
||||
}
|
||||
internal sealed class CoverView:Control
|
||||
{
|
||||
private Image? image;[System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
|
||||
public string Caption {get;set;}="Your book";
|
||||
public CoverView(){DoubleBuffered=true;AccessibleName="Associated book cover";AccessibleRole=AccessibleRole.Graphic;}
|
||||
public void SetImage(Image? value){var previous=image;image=value;previous?.Dispose();Invalidate();}
|
||||
protected override void OnPaint(PaintEventArgs e)
|
||||
{
|
||||
base.OnPaint(e);var bounds=new Rectangle(2,2,Math.Max(1,Width-8),Math.Max(1,Height-8));var ratio=2d/3;
|
||||
if(bounds.Width>bounds.Height*ratio)bounds.Width=(int)(bounds.Height*ratio);else bounds.Height=(int)(bounds.Width/ratio);
|
||||
e.Graphics.SmoothingMode=SmoothingMode.AntiAlias;using var shadow=new SolidBrush(Color.FromArgb(30,0,0,0));e.Graphics.FillRectangle(shadow,bounds.X+4,bounds.Y+5,bounds.Width,bounds.Height);
|
||||
if(image!=null){var scale=Math.Min((double)bounds.Width/image.Width,(double)bounds.Height/image.Height);var w=(int)(image.Width*scale);var h=(int)(image.Height*scale);e.Graphics.DrawImage(image,new Rectangle(bounds.X+(bounds.Width-w)/2,bounds.Y+(bounds.Height-h)/2,w,h));return;}
|
||||
using var brush=new LinearGradientBrush(bounds,Color.FromArgb(99,63,93),Color.FromArgb(50,41,61),90);e.Graphics.FillRectangle(brush,bounds);
|
||||
using var line=new Pen(Color.FromArgb(130,218,191,166));e.Graphics.DrawRectangle(line,bounds.X+9,bounds.Y+9,Math.Max(1,bounds.Width-18),Math.Max(1,bounds.Height-18));
|
||||
using var titleFont=new Font("Segoe UI",11,FontStyle.Bold);TextRenderer.DrawText(e.Graphics,Caption,titleFont,new Rectangle(bounds.X+16,bounds.Y+30,Math.Max(1,bounds.Width-32),Math.Max(1,bounds.Height-54)),Color.FromArgb(250,240,224),TextFormatFlags.WordBreak|TextFormatFlags.HorizontalCenter|TextFormatFlags.EndEllipsis);
|
||||
}
|
||||
protected override void Dispose(bool disposing){if(disposing)image?.Dispose();base.Dispose(disposing);}
|
||||
}
|
||||
#endif
|
||||
@ -56,8 +56,8 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action<st
|
||||
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="unsupported-version"},cancellation); return;
|
||||
}
|
||||
var trayAdapter=(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.TrayCapability);
|
||||
instance = hello.WordInstanceId; sessions.Attach(instance,lease);if(trayAdapter)control?.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.CaptureCapability));
|
||||
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability},cancellation);
|
||||
instance = hello.WordInstanceId; sessions.Attach(instance,lease);if(trayAdapter)control?.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.CaptureCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.MaintenanceCapability));
|
||||
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability},cancellation);
|
||||
log?.Invoke("peer-connected");
|
||||
while (!cancellation.IsCancellationRequested)
|
||||
{
|
||||
|
||||
@ -27,107 +27,127 @@ internal static class TrayApplication
|
||||
internal sealed class CompanionWindow:Form
|
||||
{
|
||||
private readonly TrayCoordinator control;private readonly CloudGateway cloud;private readonly CancellationTokenSource shutdown;private readonly string directory;
|
||||
private readonly NotifyIcon tray;private readonly Icon brand=CreateBrandIcon();private readonly Dictionary<Guid,HashSet<int>> selections=[];private readonly Dictionary<Guid,long> selectionRevisions=[];private Guid renderedSession;private readonly System.Windows.Forms.Timer timer=new(){Interval=500};private bool exiting,refreshing;
|
||||
private readonly ComboBox documents=new(){DropDownStyle=ComboBoxStyle.DropDownList,Dock=DockStyle.Fill,DisplayMember="Title"};
|
||||
private readonly ComboBox books=new(){DropDownStyle=ComboBoxStyle.DropDownList,Dock=DockStyle.Fill,DisplayMember="Title",DropDownWidth=650};
|
||||
private readonly TextBox site=new(){Dock=DockStyle.Fill,PlaceholderText="https://your-plotdirector-site/"};
|
||||
private readonly Label nextStep=new(){Dock=DockStyle.Fill,AutoSize=true,Padding=new(0,4,0,8)};private readonly ToolTip tips=new();private readonly TabControl tabs=new(){Dock=DockStyle.Fill};
|
||||
private readonly Label status=new(){Dock=DockStyle.Fill,AutoSize=true};private readonly Label progressText=new(){AutoSize=true,Dock=DockStyle.Fill};
|
||||
private readonly ProgressBar progress=new(){Dock=DockStyle.Fill,Maximum=100,Height=5};
|
||||
private readonly CheckedListBox chapters=new(){Dock=DockStyle.Fill,CheckOnClick=true,HorizontalScrollbar=true};
|
||||
private readonly TextBox diagnostics=new(){Multiline=true,ReadOnly=true,Dock=DockStyle.Fill,ScrollBars=ScrollBars.Vertical};
|
||||
private readonly Button detect=new(){Text="Detect Chapters",AutoSize=true},analyse=new(){Text="Analyse selected chapters",AutoSize=true},cancel=new(){Text="Cancel",AutoSize=true},bookButton=new(){Text="Use selected book",AutoSize=true},review=new(){Text="Review in PlotDirector",AutoSize=true};
|
||||
private readonly Button contextAction=new(){Text="Open Context",AutoSize=true},intentAction=new(){Text="Open Intent",AutoSize=true};
|
||||
private readonly CheckBox remember=new(){Text="Remember in document metadata (save Word normally)",AutoSize=true};
|
||||
private string documentKey="",bookKey="",chapterKey="";private int displayedBook=-1;private Guid displayedSession;private Guid selected;private string error="";
|
||||
private TrayDocument[] displayedDocuments=[];
|
||||
private TrayDocument? Current=>displayedDocuments.FirstOrDefault(d=>d.Session==selected);
|
||||
private readonly Icon brand=CreateBrandIcon();private readonly NotifyIcon tray;private readonly System.Windows.Forms.Timer timer=new(){Interval=750};
|
||||
private readonly ToolTip tips=new();private bool exiting,refreshing,advanced;private Guid selected,lastActive;private TrayDocument[] displayed=[];private string docsKey="",error="";
|
||||
private readonly ComboBox documents=new(){DropDownStyle=ComboBoxStyle.DropDownList,Dock=DockStyle.Top,AccessibleName="Word manuscript"};
|
||||
private readonly ComboBox books=new(){DropDownStyle=ComboBoxStyle.DropDownList,Dock=DockStyle.Top,DisplayMember="Title",AccessibleName="PlotDirector book",DropDownWidth=620};
|
||||
private readonly Label serverStatus=Label(),wordStatus=Label(),account=Label(),bookTitle=Label(),projectTitle=Label(),guidance=Label(),notice=Label();
|
||||
private readonly Button authorise=new(){Text="Sign in with your browser",AutoSize=true};private readonly CoverView cover=new(){Dock=DockStyle.Fill,MinimumSize=new(110,164)};
|
||||
private Label? settingsNotice;private Label? dialogNotice;private Form? settings;private CheckBox? advancedToggle;private TextBox? site,diagnostics;private Panel? advancedPanel;
|
||||
private string coverKey="";private DateTime coverRetry;private CancellationTokenSource? coverStop;private bool coverLoading;
|
||||
private TrayDocument? Current=>displayed.FirstOrDefault(d=>d.Session==selected);
|
||||
public CompanionWindow(TrayCoordinator control,CloudGateway cloud,CancellationTokenSource shutdown,string directory)
|
||||
{
|
||||
this.control=control;this.cloud=cloud;this.shutdown=shutdown;this.directory=directory;
|
||||
Icon=brand;Text="PlotDirector Companion";Font=new("Segoe UI",10);BackColor=Color.FromArgb(249,246,240);ForeColor=Color.FromArgb(58,49,44);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new(660,640);Size=new(Math.Clamp(cloud.Preferences.Width,660,4096),Math.Clamp(cloud.Preferences.Height,640,2160));DoubleBuffered=true;remember.Checked=cloud.Preferences.RememberInDocument;ResizeEnd+=(_,_)=>SavePreferences();remember.CheckedChanged+=(_,_)=>{if(!refreshing)SavePreferences();};
|
||||
var layout=new TableLayoutPanel{Dock=DockStyle.Fill,Padding=new(24),ColumnCount=1,RowCount=8};layout.ColumnStyles.Add(new(SizeType.Percent,100));for(int i=0;i<8;i++)layout.RowStyles.Add(new(i==6?SizeType.Percent:SizeType.AutoSize,i==6?100:0));
|
||||
var header=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,WrapContents=true};
|
||||
header.Controls.Add(new Label{Text="PlotDirector",Font=new("Segoe UI",22,FontStyle.Bold),AutoSize=true,Margin=new(0,0,20,12)});
|
||||
header.Controls.Add(Button("Connect / Sign in",()=>{tabs.SelectedIndex=0;site.Focus();}));header.Controls.Add(Button("Settings",()=>tabs.SelectedIndex=0));header.Controls.Add(Button("Help",()=>cloud.OpenSite("help")));layout.Controls.Add(header,0,0);
|
||||
layout.Controls.Add(status,0,1);layout.Controls.Add(nextStep,0,2);
|
||||
var manuscript=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=2,Padding=new(12)};manuscript.ColumnStyles.Add(new(SizeType.Percent,100));manuscript.ColumnStyles.Add(new(SizeType.AutoSize));
|
||||
manuscript.Controls.Add(new Label{Text="CURRENT MANUSCRIPT",AutoSize=true,Font=new(Font,FontStyle.Bold)},0,0);
|
||||
manuscript.Controls.Add(Button("Use active Word document",()=>{var active=control.Documents.FirstOrDefault(d=>d.Active);if(active!=null){selected=active.Session;documents.SelectedItem=active;chapterKey="";}}),1,0);
|
||||
manuscript.Controls.Add(documents,0,1);manuscript.SetColumnSpan(documents,2);manuscript.Controls.Add(books,0,2);manuscript.Controls.Add(bookButton,1,2);manuscript.Controls.Add(remember,0,3);manuscript.SetColumnSpan(remember,2);layout.Controls.Add(manuscript,0,3);
|
||||
remember.Text="Remember this book when I save the document";bookButton.Text="Link book";detect.Text="Find chapters";review.Text="Review scenes in PlotDirector";
|
||||
var actions=new FlowLayoutPanel{AutoSize=true,Dock=DockStyle.Fill,WrapContents=true,Padding=new(0,8,0,8)};actions.Controls.AddRange([Button("Open PlotDirector",()=>cloud.OpenSite()),Button("Check document connection",()=>control.RefreshPresence(selected))]);layout.Controls.Add(actions,0,4);
|
||||
analyse.Tag="primary";
|
||||
var activity=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=1,Padding=new(0,4,0,10)};activity.ColumnStyles.Add(new(SizeType.Percent,100));activity.Controls.Add(progressText);activity.Controls.Add(progress);layout.Controls.Add(activity,0,5);
|
||||
var chapterTab=new TabPage("Your chapters"){Padding=new(12)};chapterTab.Controls.Add(chapters);chapters.DrawMode=DrawMode.OwnerDrawFixed;chapters.ItemHeight=(int)Math.Round(52*DeviceDpi/96d);DpiChanged+=(_,_)=>{chapters.ItemHeight=(int)Math.Round(52*DeviceDpi/96d);chapters.Invalidate();};chapters.IntegralHeight=false;chapters.BorderStyle=BorderStyle.None;
|
||||
chapters.DrawItem+=DrawChapter;chapters.MouseMove+=(_,e)=>{var index=chapters.IndexFromPoint(e.Location);var title=index>=0?((ChapterItem)chapters.Items[index]).Title:"";if(tips.GetToolTip(chapters)!=title)tips.SetToolTip(chapters,title);};
|
||||
var choices=new FlowLayoutPanel{Dock=DockStyle.Top,AutoSize=true};choices.Controls.AddRange([Button("Select all",()=>{for(var i=0;i<chapters.Items.Count;i++)chapters.SetItemChecked(i,true);}),Button("Clear selection",()=>{for(var i=0;i<chapters.Items.Count;i++)chapters.SetItemChecked(i,false);})]);chapterTab.Controls.Add(choices);
|
||||
var settings=new TabPage("Connection & troubleshooting"){Padding=new(12)};
|
||||
var settingsLayout=new TableLayoutPanel{Dock=DockStyle.Fill,ColumnCount=1,RowCount=4};settingsLayout.RowStyles.Add(new(SizeType.AutoSize));settingsLayout.RowStyles.Add(new(SizeType.AutoSize));settingsLayout.RowStyles.Add(new(SizeType.Percent,100));settingsLayout.RowStyles.Add(new(SizeType.AutoSize));settingsLayout.ColumnStyles.Add(new(SizeType.Percent,100));
|
||||
settingsLayout.Controls.Add(new Label{Text="Your PlotDirector website · enter its HTTPS address, then approve sign-in in your browser.",AutoSize=true,Dock=DockStyle.Fill});
|
||||
var connection=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=2};connection.ColumnStyles.Add(new(SizeType.Percent,100));connection.ColumnStyles.Add(new(SizeType.AutoSize));connection.Controls.Add(site,0,0);connection.Controls.Add(Button("Connect / Sign in",()=>cloud.Connect(site.Text.Trim())),1,0);settingsLayout.Controls.Add(connection);settingsLayout.Controls.Add(diagnostics);
|
||||
var options=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true};options.Controls.AddRange([Button("Check connection",()=>_ = cloud.ReconnectAsync()),Button("Change account",()=>cloud.ChangeAccount(site.Text.Trim())),Button("Sign out",()=>cloud.SignOut()),Button("Open support folder",()=>System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(directory){UseShellExecute=true}))]);settingsLayout.Controls.Add(options);settings.Controls.Add(settingsLayout);tabs.TabPages.Add(settings);layout.Controls.Add(tabs,0,6);
|
||||
layout.Controls.Add(new Label{AutoSize=true,Dock=DockStyle.Fill,Padding=new(0,12,0,0),Text="Import, analysis, Context and Intent are available in PlotDirector. Word text changes only through your own authoring actions."},0,7);Controls.Add(layout);
|
||||
tips.SetToolTip(analyse,"Choose a linked book and select chapters first. Sends prose only after you confirm.");tips.SetToolTip(review,"Open saved scene suggestions and approve them before importing.");tips.SetToolTip(detect,"Reads Heading 1 chapter boundaries without changing your words.");
|
||||
ApplyTheme();Microsoft.Win32.SystemEvents.UserPreferenceChanged+=OnPreferences;
|
||||
documents.SelectedIndexChanged+=(_,_)=>{if(!refreshing&&documents.SelectedItem is TrayDocument d){selected=d.Session;chapterKey="";SavePreferences();RefreshState();}};
|
||||
chapters.DoubleClick+=(_,_)=>{if(chapters.SelectedItem is ChapterItem chapter)Safe(()=>control.Navigate(selected,chapter.Start));};
|
||||
chapters.ItemCheck+=(_,e)=>{if(refreshing||renderedSession==Guid.Empty)return;if(!selections.TryGetValue(renderedSession,out var chosen)){if(selections.Count>=64)selections.Clear();selections[renderedSession]=chosen=[];}var start=((ChapterItem)chapters.Items[e.Index]).Start;if(e.NewValue==CheckState.Checked)chosen.Add(start);else chosen.Remove(start);};
|
||||
detect.Click+=(_,_)=>Safe(()=>control.Detect(selected));cancel.Click+=(_,_)=>Safe(()=>control.Cancel(selected));
|
||||
bookButton.Click+=(_,_)=>Safe(()=>{if(books.SelectedItem is not Protocol.CompanionBook book)return;if(remember.Checked&&MessageBox.Show("Remember this book in Word document metadata? This marks the document modified. It does not save or change prose.","Remember association",MessageBoxButtons.OKCancel)!=DialogResult.OK)return;control.SelectBook(selected,book.BookId,remember.Checked);});
|
||||
analyse.Click+=(_,_)=>Safe(()=>{var chosen=chapters.CheckedItems.Cast<ChapterItem>().ToArray();if(chosen.Length==0)throw new InvalidOperationException("Select one or more chapters first.");var d=Current??throw new InvalidOperationException("Open a Word document.");if(MessageBox.Show($"Send {chosen.Length} selected chapters for the chosen book to PlotDirector AI? This uploads manuscript prose, may retain an encrypted import capture if you approved that permission at sign-in, and may incur AI costs. Existing Word text and saved story records will not change.","Confirm chapter analysis",MessageBoxButtons.OKCancel)==DialogResult.OK)control.Analyse(d.Session,chosen.Select(c=>c.Start));});
|
||||
review.Click+=(_,_)=>Safe(()=>Open("review"));contextAction.Click+=(_,_)=>Safe(()=>Open("context"));intentAction.Click+=(_,_)=>Safe(()=>Open("intent"));tips.SetToolTip(contextAction,"Link an authorised book to open its reference workspace.");tips.SetToolTip(intentAction,"Link an authorised book to open its writing objectives.");
|
||||
var menu=new ContextMenuStrip();menu.Items.Add("Open PlotDirector Companion",null,(_,_)=>Reveal());menu.Items.Add("Open PlotDirector",null,(_,_)=>Safe(()=>Open("book")));menu.Items.Add("Help & connection",null,(_,_)=>{Reveal();tabs.SelectedIndex=0;});menu.Items.Add(new ToolStripSeparator());menu.Items.Add("Quit Companion",null,(_,_)=>Exit());
|
||||
tray=new(){Icon=brand,Text="PlotDirector Companion",ContextMenuStrip=menu,Visible=true};tray.DoubleClick+=(_,_)=>Reveal();FormClosing+=(_,e)=>{if(!exiting){e.Cancel=true;Hide();}};timer.Tick+=(_,_)=>RefreshState();timer.Start();RefreshState();
|
||||
this.control=control;this.cloud=cloud;this.shutdown=shutdown;this.directory=directory;advanced=cloud.Preferences.AdvancedMode;
|
||||
Text="PlotDirector Companion";Icon=brand;Font=new("Segoe UI",10);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new(460,590);Size=new(Math.Clamp(cloud.Preferences.Width,460,1000),Math.Clamp(cloud.Preferences.Height,590,1100));DoubleBuffered=true;
|
||||
var layout=Stack(22);layout.Dock=DockStyle.Fill;layout.AutoSize=false;layout.AutoScroll=true;Controls.Add(layout);
|
||||
var header=new TableLayoutPanel{Dock=DockStyle.Top,AutoSize=true,ColumnCount=2,Margin=new(0,0,0,16)};header.ColumnStyles.Add(new(SizeType.Percent,100));header.ColumnStyles.Add(new(SizeType.AutoSize));
|
||||
var name=Label("PlotDirector");name.Font=new("Segoe UI",24,FontStyle.Bold);header.Controls.Add(name,0,0);header.Controls.Add(Button("Settings",ShowSettings),1,0);
|
||||
var version=Label("COMPANION · "+typeof(CompanionWindow).Assembly.GetName().Version);version.Font=new("Segoe UI",9);header.Controls.Add(version,0,1);layout.Controls.Add(header);
|
||||
var connection=Card();connection.Controls.Add(Heading("YOUR CONNECTIONS"));connection.Controls.Add(serverStatus);connection.Controls.Add(account);connection.Controls.Add(wordStatus);connection.Controls.Add(authorise);layout.Controls.Add(connection);
|
||||
authorise.Click+=(_,_)=>Safe(()=>cloud.Connect(cloud.Status().ServerUrl));
|
||||
var manuscript=Card();manuscript.Controls.Add(Heading("CURRENT MANUSCRIPT"));manuscript.Controls.Add(documents);manuscript.Controls.Add(guidance);
|
||||
var bookLayout=new TableLayoutPanel{Dock=DockStyle.Top,AutoSize=true,ColumnCount=2,Margin=new(0,12,0,8),MinimumSize=new(0,180)};bookLayout.ColumnStyles.Add(new(SizeType.Absolute,124));bookLayout.ColumnStyles.Add(new(SizeType.Percent,100));bookLayout.Controls.Add(cover,0,0);
|
||||
var details=Stack(8);details.Controls.Add(Heading("PLOTDIRECTOR BOOK"));bookTitle.Font=new("Segoe UI",14,FontStyle.Bold);details.Controls.Add(bookTitle);details.Controls.Add(projectTitle);details.Controls.Add(Button("Change book…",ChangeBook));bookLayout.Controls.Add(details,1,0);manuscript.Controls.Add(bookLayout);layout.Controls.Add(manuscript);
|
||||
var open=Button("Open PlotDirector ↗",()=>cloud.OpenSite());open.Tag="primary";open.Dock=DockStyle.Top;open.MinimumSize=new(0,44);layout.Controls.Add(open);
|
||||
notice.Margin=new(0,12,0,0);layout.Controls.Add(notice);
|
||||
documents.SelectedIndexChanged+=(_,_)=>{if(!refreshing&&documents.SelectedItem is TrayDocument doc){selected=doc.Session;SavePreferences();RefreshState();}};
|
||||
ResizeEnd+=(_,_)=>SavePreferences();
|
||||
var menu=new ContextMenuStrip();menu.Items.Add("Open Companion",null,(_,_)=>Reveal());menu.Items.Add("Open PlotDirector",null,(_,_)=>Safe(()=>cloud.OpenSite()));menu.Items.Add("Settings",null,(_,_)=>{Reveal();ShowSettings();});menu.Items.Add(new ToolStripSeparator());menu.Items.Add("Exit Companion",null,(_,_)=>Exit());
|
||||
tray=new(){Icon=brand,Text="PlotDirector Companion",ContextMenuStrip=menu,Visible=true};tray.DoubleClick+=(_,_)=>Reveal();
|
||||
FormClosing+=(_,e)=>{if(!exiting){e.Cancel=true;SavePreferences();settings?.Hide();Hide();}};
|
||||
ApplyTheme();Microsoft.Win32.SystemEvents.UserPreferenceChanged+=OnPreferences;timer.Tick+=(_,_)=>RefreshState();timer.Start();RefreshState();
|
||||
}
|
||||
private Button Button(string text,Action action){var button=new Button{Text=text,AutoSize=true};button.Click+=(_,_)=>Safe(action);return button;}
|
||||
private void SavePreferences(){var size=WindowState==FormWindowState.Normal?Size:RestoreBounds.Size;cloud.SavePreferences(new(){Width=size.Width,Height=size.Height,RememberInDocument=remember.Checked,LastManuscript=Current?.Manuscript??Guid.Empty});}
|
||||
private void Safe(Action action){try{error="";action();}catch(Exception e)when(e is InvalidOperationException or ArgumentException or IOException or System.ComponentModel.Win32Exception){error=e.Message;}RefreshState();}
|
||||
private void Open(string page){if(Current==null)cloud.OpenSite(page);else control.OpenPage(selected,page);}
|
||||
private static Label Label(string text="")=>new(){Text=text,AutoSize=true,Dock=DockStyle.Top,MaximumSize=new(1600,0),Margin=new(0,3,0,5)};
|
||||
private static Label Heading(string text){var label=Label(text);label.Font=new("Segoe UI",9,FontStyle.Bold);label.Margin=new(0,0,0,9);return label;}
|
||||
private static TableLayoutPanel Stack(int padding=0){var panel=new TableLayoutPanel{Dock=DockStyle.Top,AutoSize=true,AutoSizeMode=AutoSizeMode.GrowAndShrink,ColumnCount=1,Padding=new(padding),Margin=new(0)};panel.ColumnStyles.Add(new(SizeType.Percent,100));return panel;}
|
||||
private static RoundedCard Card()=>new(){Dock=DockStyle.Top,AutoSize=true,AutoSizeMode=AutoSizeMode.GrowAndShrink,Padding=new(16),Margin=new(0,0,0,14),ColumnCount=1};
|
||||
private Button Button(string text,Action action){var button=new Button{Text=text,AutoSize=true,MinimumSize=new(0,34)};button.Click+=(_,_)=>Safe(action);return button;}
|
||||
private void Safe(Action action){try{error="";action();}catch(Exception e)when(e is InvalidOperationException or ArgumentException or IOException or System.ComponentModel.Win32Exception){error=e.Message;}if(dialogNotice is {IsDisposed:false})SetText(dialogNotice,error);RefreshState();}
|
||||
private void SavePreferences(){var size=WindowState==FormWindowState.Normal?Size:RestoreBounds.Size;var prefs=cloud.Preferences;prefs.Width=size.Width;prefs.Height=size.Height;prefs.AdvancedMode=advanced;prefs.LastManuscript=Current?.Manuscript??prefs.LastManuscript;cloud.SavePreferences(prefs);}
|
||||
public void Reveal(){Show();WindowState=FormWindowState.Normal;Activate();}
|
||||
private void ChangeBook()
|
||||
{
|
||||
if(Current==null){error="Open a manuscript in Word before choosing a book.";return;}
|
||||
var session=selected;using var dialog=new Form{Text="Choose a PlotDirector book",Icon=brand,Font=Font,AutoScaleMode=AutoScaleMode.Dpi,MinimumSize=new(440,260),Size=new(540,300),StartPosition=FormStartPosition.CenterParent};
|
||||
var stack=Stack(20);dialogNotice=Label();stack.Controls.Add(Label("Associate this manuscript with a book in your account. Manuscript text is not sent or changed."));books.DataSource=cloud.Status().Books;books.SelectedItem=cloud.Status().Books.FirstOrDefault(b=>b.BookId==Current.Book);stack.Controls.Add(books);
|
||||
var remember=new CheckBox{Text="Also remember in Word metadata (save Word normally)",AutoSize=true,Checked=cloud.Preferences.RememberInDocument};stack.Controls.Add(remember);
|
||||
stack.Controls.Add(Button("Use this book",()=>{if(books.SelectedItem is not Protocol.CompanionBook book)throw new InvalidOperationException("Sign in and choose an available book.");if(!control.Documents.Any(d=>d.Session==session))throw new InvalidOperationException("That Word document is no longer connected.");if(remember.Checked&&MessageBox.Show(dialog,"Write this association to PlotDirector-owned Word metadata? This marks the document modified, without changing prose.","Remember book",MessageBoxButtons.OKCancel)!=DialogResult.OK)return;control.SelectBook(session,book.BookId,remember.Checked);var prefs=cloud.Preferences;prefs.RememberInDocument=remember.Checked;cloud.SavePreferences(prefs);dialog.Close();}));
|
||||
stack.Controls.Add(dialogNotice);dialog.Controls.Add(stack);PaintTheme(dialog);dialog.ShowDialog(this);stack.Controls.Remove(books);dialogNotice=null;
|
||||
}
|
||||
private void ShowSettings()
|
||||
{
|
||||
if(settings!=null&&!settings.IsDisposed){settings.Show(this);settings.Activate();return;}
|
||||
settings=new Form{Text="PlotDirector · Settings",Icon=brand,Font=Font,AutoScaleMode=AutoScaleMode.Dpi,MinimumSize=new(480,420),Size=new(640,620),StartPosition=FormStartPosition.CenterParent};
|
||||
var root=Stack(20);root.Dock=DockStyle.Fill;root.AutoScroll=true;settings.Controls.Add(root);
|
||||
settingsNotice=Label();root.Controls.Add(settingsNotice);root.Controls.Add(Heading("CONNECTION & ACCOUNT"));site=new(){Text=cloud.Status().ServerUrl,Dock=DockStyle.Top,AccessibleName="PlotDirector server HTTPS address"};root.Controls.Add(site);
|
||||
root.Controls.Add(Label("Your approved connection reconnects automatically. Changing account requires browser approval."));
|
||||
var accountActions=new FlowLayoutPanel{Dock=DockStyle.Top,AutoSize=true};accountActions.Controls.Add(Button("Change account…",()=>cloud.ChangeAccount(site.Text.Trim())));accountActions.Controls.Add(Button("Sign out",()=>{if(MessageBox.Show(settings,"Sign out and revoke this Companion’s approval? You will need browser approval to connect again.","Sign out",MessageBoxButtons.OKCancel)==DialogResult.OK)cloud.SignOut();}));root.Controls.Add(accountActions);
|
||||
root.Controls.Add(Button("Use server address",()=>{if(site.Text.Trim().TrimEnd('/')!=cloud.Status().ServerUrl.TrimEnd('/'))cloud.Connect(site.Text.Trim());}));
|
||||
advancedToggle=new(){Text="Advanced mode · troubleshooting and document maintenance",AutoSize=true,Checked=advanced,Dock=DockStyle.Top,Margin=new(0,16,0,10)};
|
||||
root.Controls.Add(advancedToggle);advancedPanel=Stack();advancedPanel.Visible=advanced;root.Controls.Add(advancedPanel);
|
||||
advancedPanel.Controls.Add(Heading("TROUBLESHOOTING"));diagnostics=new(){Multiline=true,ReadOnly=true,Dock=DockStyle.Top,Height=160,ScrollBars=ScrollBars.Vertical,AccessibleName="Connection and document diagnostics"};advancedPanel.Controls.Add(diagnostics);
|
||||
var checks=new FlowLayoutPanel{Dock=DockStyle.Top,AutoSize=true};checks.Controls.Add(Button("Check connection",()=>_ = cloud.ReconnectAsync()));checks.Controls.Add(Button("Check Word registration",()=>{if(Current==null)throw new InvalidOperationException("Open and select a Word document first.");control.RefreshPresence(selected);}));checks.Controls.Add(Button("Open logs folder",()=>System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(directory){UseShellExecute=true})));advancedPanel.Controls.Add(checks);
|
||||
advancedPanel.Controls.Add(Heading("SELECTED WORD DOCUMENT"));advancedPanel.Controls.Add(Label("Maintenance touches only PlotDirector-owned markers and association properties. Word is never saved automatically. If interrupted, inspect again before retrying."));
|
||||
foreach(var entry in new[]{("Inspect hidden identifiers","inspect"),("Remove PlotDirector markers…","markers"),("Reset document association…","reset"),("Clean and unlink…","clean")}){var kind=entry.Item2;advancedPanel.Controls.Add(Button(entry.Item1,()=>Maintenance(kind)));}
|
||||
advancedToggle.CheckedChanged+=(_,_)=>{advanced=advancedToggle.Checked;advancedPanel.Visible=advanced;SavePreferences();};
|
||||
root.Controls.Add(Button("Help",()=>cloud.OpenSite("help")));settings.FormClosing+=(_,_)=>SavePreferences();PaintTheme(settings);RefreshState();settings.Show(this);
|
||||
}
|
||||
private void Maintenance(string kind)
|
||||
{
|
||||
var doc=Current??throw new InvalidOperationException("Select a connected Word document in the Companion first.");
|
||||
if(!control.CanMaintain(doc.Session))throw new InvalidOperationException("This Word add-in does not support maintenance. Install the matching updated version first.");
|
||||
if(kind!="inspect"&&MessageBox.Show(settings??this,$"{(kind=="markers"?"Remove PlotDirector markers from":kind=="reset"?"Reset the PlotDirector association of":"Clean and unlink")} “{doc.Title}”?\n\nOnly PlotDirector-owned metadata will be removed. Manuscript words and formatting are retained. This cannot be undone through the Companion; keep a saved copy first. Word will not be saved automatically.","Confirm document maintenance",MessageBoxButtons.OKCancel,MessageBoxIcon.Warning)!=DialogResult.OK)return;
|
||||
control.Maintain(doc.Session,kind);
|
||||
}
|
||||
private void RefreshState()
|
||||
{
|
||||
var state=cloud.Status();var docs=control.PresentationDocuments;displayedDocuments=docs;var key=string.Join("|",docs.Select(d=>d.Session+":"+d.Title+":"+d.Active));refreshing=true;
|
||||
try{if(key!=documentKey){documentKey=key;documents.DataSource=docs;if(!docs.Any(d=>d.Session==selected))selected=docs.FirstOrDefault(d=>d.Active)?.Session??docs.FirstOrDefault(d=>d.Manuscript==cloud.Preferences.LastManuscript)?.Session??docs.FirstOrDefault()?.Session??Guid.Empty;documents.SelectedItem=docs.FirstOrDefault(d=>d.Session==selected);}
|
||||
var bkey=state.AuthenticationContext+string.Join("|",state.Books.Select(b=>b.BookId+":"+b.Title));if(bookKey!=bkey){bookKey=bkey;books.DataSource=state.Books;books.SelectedIndex=-1;displayedBook=-1;}
|
||||
var d=Current;if(displayedSession!=selected||displayedBook!=(d?.Book??0)){displayedSession=selected;displayedBook=d?.Book??0;books.SelectedItem=state.Books.FirstOrDefault(b=>b.BookId==d?.Book);}
|
||||
if(string.IsNullOrWhiteSpace(site.Text)&&!string.IsNullOrEmpty(state.ServerUrl))site.Text=state.ServerUrl;
|
||||
var server=state.Health==null?"unknown":DateTime.UtcNow-state.Health.VerifiedUtc>TimeSpan.FromSeconds(90)&&state.Health.Server=="online"?"unverified (check connection)":state.Health.Server;
|
||||
SetText(status,CompanionPresentation.Connection(state.Health,DateTime.UtcNow)+(string.IsNullOrEmpty(state.Health?.AccountName)?"":" · "+state.Health.AccountName)+" · "+(d==null?"Word not connected":d.Book==0?"Word available locally · link a book":!string.IsNullOrEmpty(d.LastPresenceKey)&&DateTime.UtcNow-d.LastPresenceUtc<TimeSpan.FromSeconds(45)?"Word document registered with PlotDirector":"Word available locally · document registration pending"));
|
||||
SetText(nextStep,d==null?"Open a manuscript in Word to begin.":d.Book==0?"Choose the PlotDirector book for this manuscript.":"Use Import manuscript in PlotDirector. Open Context and Intent from the website writing workspace.");
|
||||
SetText(progressText,string.IsNullOrEmpty(error)?(d?.Status??"Waiting for your manuscript.")+(d==null?"":"\r\n"+(d.WordSaved==true?"Word reports saved.":d.WordSaved==false?"Word has unsaved changes.":"Word save state not yet reported.")+(d.AcceptedRevision==d.Revision?" PlotDirector acknowledged this captured revision.":" This revision has not been acknowledged by PlotDirector.")):error);progress.Value=Math.Clamp(d?.Progress??0,0,100);
|
||||
detect.Enabled=d!=null&&d.Job==Guid.Empty;analyse.Enabled=d!=null&&d.Book>0&&d.Chapters.Length>0&&d.Job==Guid.Empty&&d.Pending.Count==0&&state.Health?.Authentication=="verified"&&state.Health?.Ai is not ("not-configured" or "not-entitled");cancel.Enabled=d!=null&&(d.Job!=Guid.Empty||d.Pending.Count>0);bookButton.Enabled=d!=null&&state.Books.Length>0&&d.Job==Guid.Empty;review.Enabled=d?.Book>0;contextAction.Enabled=intentAction.Enabled=d?.Book>0;
|
||||
var ckey=d==null?"":d.Session+":"+d.Revision+string.Join("|",d.Chapters.Select(c=>c.Start+":"+c.End+":"+c.Title));if(chapterKey!=ckey){chapterKey=ckey;chapters.BeginUpdate();try{chapters.Items.Clear();renderedSession=d?.Session??Guid.Empty;if(d!=null){if(selectionRevisions.TryGetValue(d.Session,out var revision)&&revision!=d.Revision)selections.Remove(d.Session);if(selectionRevisions.Count>=64)selectionRevisions.Clear();selectionRevisions[d.Session]=d.Revision;}if(d!=null){chapters.Items.AddRange(d.Chapters.Select(c=>(object)new ChapterItem(c.Start,c.Title)).ToArray());if(selections.TryGetValue(d.Session,out var checkedStarts))for(int i=0;i<chapters.Items.Count;i++)chapters.SetItemChecked(i,checkedStarts.Contains(((ChapterItem)chapters.Items[i]).Start));}}finally{chapters.EndUpdate();}}
|
||||
var diagnosticText="PlotDirector Companion by Nick Beckley\r\n"+typeof(CompanionWindow).Assembly.GetName().Version+"\r\n"+state.Health?.Explanation+"\r\nManuscript transfer is requested by the PlotDirector import wizard. No automatic prose synchronisation.\r\n"+(d==null?"No Word session.":d.WordDiagnostics+"\r\n"+$"Session {d.Session}\r\nRevision {d.Revision}\r\nErrors: "+string.Join("\r\n",d.Errors.TakeLast(10)))+"\r\nClose hides this window; Exit stops the tray process. Open Companion resumes it.";if(diagnostics.Text!=diagnosticText)diagnostics.Text=diagnosticText;var appearance=d==null?"":d.Job+":"+d.Done+":"+d.Completed.Count+":"+d.FailedChapters.Count;if(chapters.Tag as string!=appearance){chapters.Tag=appearance;chapters.Invalidate();}
|
||||
var state=cloud.Status();displayed=control.PresentationDocuments;refreshing=true;
|
||||
try{
|
||||
var active=displayed.FirstOrDefault(d=>d.Active)?.Session??Guid.Empty;if(active!=Guid.Empty&&active!=lastActive)selected=active;lastActive=active;
|
||||
var key=string.Join("|",displayed.Select(d=>d.Session+":"+d.Title+":"+d.Active));if(key!=docsKey){docsKey=key;if(!displayed.Any(d=>d.Session==selected))selected=displayed.FirstOrDefault(d=>d.Active)?.Session??displayed.FirstOrDefault(d=>d.Manuscript==cloud.Preferences.LastManuscript)?.Session??displayed.FirstOrDefault()?.Session??Guid.Empty;documents.DataSource=displayed;documents.SelectedItem=Current;}
|
||||
var doc=Current;var book=state.Books.FirstOrDefault(b=>b.BookId==doc?.Book);
|
||||
SetText(serverStatus,"PlotDirector · "+CompanionPresentation.Connection(state.Health,DateTime.UtcNow));SetText(account,state.Health?.AccountName??"Not signed in");
|
||||
SetText(wordStatus,CompanionPresentation.WordStatus(doc!=null,doc?.Book??0,doc?.LastPresenceUtc??DateTime.MinValue,doc?.LastPresenceKey??"",DateTime.UtcNow));
|
||||
authorise.Visible=CompanionPresentation.NeedsAuthorisation(state.Health);authorise.Enabled=!string.IsNullOrWhiteSpace(state.ServerUrl);
|
||||
SetText(guidance,doc==null?"Open a manuscript in Microsoft Word. Your words stay in Word until you request an import in PlotDirector.":doc.Book==0?"Choose the PlotDirector book for this manuscript.":"Import, Context and Intent are available in PlotDirector.");
|
||||
SetText(bookTitle,book==null?"No book associated":string.IsNullOrEmpty(book.BookTitle)?book.Title:book.BookTitle);SetText(projectTitle,book?.ProjectTitle??"Choose a book to connect your writing workspace.");
|
||||
SetText(notice,error);if(settingsNotice is {IsDisposed:false}){SetText(settingsNotice,error);settingsNotice.Visible=error!="";}notice.Visible=error!="";tips.SetToolTip(serverStatus,state.Health?.Explanation??"Connect in Settings.");
|
||||
var text=$"Server: {state.ServerUrl}\r\nAccount: {state.Health?.AccountName}\r\n{state.Health?.Explanation}\r\n"+string.Join("\r\n",displayed.Select(d=>$"{d.Title} · session {d.Session} · book {d.Book}"))+"\r\n"+doc?.WordDiagnostics+"\r\n"+doc?.Status+"\r\n"+doc?.MaintenanceReport;
|
||||
if(diagnostics is {IsDisposed:false}&&diagnostics.Text!=text)diagnostics.Text=text;
|
||||
var next=state.AuthenticationContext+":"+(book?.BookId??0);if(next!=coverKey){coverKey=next;coverRetry=DateTime.MinValue;coverStop?.Cancel();cover.SetImage(null);cover.Caption=bookTitle.Text;cover.Invalidate();coverLoading=false;}
|
||||
if(book!=null&&!coverLoading&&DateTime.UtcNow>=coverRetry&&state.Health?.State=="Connected")_ = LoadCover(book.BookId,state.AuthenticationContext,next);
|
||||
var trayText="PlotDirector · "+(state.Health?.State??"Disconnected");if(tray.Text!=trayText)tray.Text=trayText.Length>63?trayText[..63]:trayText;
|
||||
}finally{refreshing=false;}
|
||||
}
|
||||
private static void SetText(Label label,string value){if(label.Text!=value)label.Text=value;}
|
||||
private async Task LoadCover(int book,Guid context,string key)
|
||||
{
|
||||
coverLoading=true;coverRetry=DateTime.UtcNow.AddMinutes(5);var stop=new CancellationTokenSource();coverStop=stop;
|
||||
try{var reply=await cloud.Get<Protocol.BookCoverReply>($"api/native-companion/books/{book}/cover",context,stop.Token);if(stop.IsCancellationRequested||IsDisposed||key!=coverKey)return;
|
||||
Image? image=null;if(reply.Png!=""){using var stream=new MemoryStream(Convert.FromBase64String(reply.Png));using var decoded=Image.FromStream(stream);if(decoded.Width>600||decoded.Height>900)throw new InvalidDataException("Cover dimensions exceeded.");image=new Bitmap(decoded);}cover.SetImage(image);coverRetry=DateTime.MaxValue;
|
||||
}catch(Exception e)when(e is HttpRequestException or IOException or InvalidOperationException or OperationCanceledException or System.Text.Json.JsonException or ArgumentException or FormatException){/* Cover absence/failure never interrupts authoring or changes account trust. */}
|
||||
finally{if(key==coverKey)coverLoading=false;stop.Dispose();if(ReferenceEquals(coverStop,stop))coverStop=null;}
|
||||
}
|
||||
private static void SetText(Label label,string text){if(label.Text!=text)label.Text=text;}
|
||||
private void OnPreferences(object sender,Microsoft.Win32.UserPreferenceChangedEventArgs e){if(IsHandleCreated&&!IsDisposed)BeginInvoke(new Action(ApplyTheme));}
|
||||
private void ApplyTheme()
|
||||
private void ApplyTheme(){PaintTheme(this);if(settings is {IsDisposed:false})PaintTheme(settings);}
|
||||
private void PaintTheme(Control root)
|
||||
{
|
||||
bool? dark=null;try{using var key=Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize");if(key?.GetValue("AppsUseLightTheme") is int value)dark=value==0;}catch(System.Security.SecurityException){}
|
||||
var night=CompanionPresentation.Dark(dark);var background=night?Color.FromArgb(30,27,34):Color.FromArgb(249,246,240);var surface=night?Color.FromArgb(44,39,48):Color.FromArgb(255,253,249);var ink=night?Color.FromArgb(243,236,226):Color.FromArgb(54,43,55);var accent=night?Color.FromArgb(213,183,211):Color.FromArgb(100,55,92);
|
||||
void Paint(Control parent){parent.BackColor=parent is TextBox or ComboBox or CheckedListBox or TabPage?surface:background;parent.ForeColor=ink;foreach(Control child in parent.Controls)Paint(child);if(parent is Button button){button.FlatStyle=FlatStyle.Flat;button.FlatAppearance.BorderSize=0;button.Padding=new(10,6,10,6);button.Margin=new(3);button.BackColor=button.Tag as string=="primary"?accent:surface;button.ForeColor=button.Tag as string=="primary"?(night?Color.FromArgb(30,27,34):Color.White):ink;}}
|
||||
Paint(this);chapters.Invalidate();
|
||||
}
|
||||
private void DrawChapter(object? sender,DrawItemEventArgs e)
|
||||
{
|
||||
if(e.Index<0||e.Index>=chapters.Items.Count)return;var item=(ChapterItem)chapters.Items[e.Index];var d=Current;e.DrawBackground();
|
||||
var selectedRow=(e.State&DrawItemState.Selected)!=0;var ink=selectedRow?SystemColors.HighlightText:chapters.ForeColor;
|
||||
int Px(int value)=>(int)Math.Round(value*DeviceDpi/96d);var box=new Rectangle(e.Bounds.Left+Px(6),e.Bounds.Top+Px(17),Px(16),Px(16));ControlPaint.DrawCheckBox(e.Graphics,box,chapters.GetItemChecked(e.Index)?ButtonState.Checked:ButtonState.Normal);
|
||||
TextRenderer.DrawText(e.Graphics,item.Title,Font,new Rectangle(e.Bounds.Left+Px(32),e.Bounds.Top+Px(4),e.Bounds.Width-Px(40),Px(24)),ink,TextFormatFlags.EndEllipsis|TextFormatFlags.SingleLine);
|
||||
var analysed=d?.Completed.Any(c=>c.Item1==d.Revision&&c.Item2==d.Book&&c.Item3==item.Start)==true;
|
||||
var working=d?.Current?.Start==item.Start&&d.Job!=Guid.Empty;
|
||||
TextRenderer.DrawText(e.Graphics,CompanionPresentation.Chapter(working,analysed,d?.FailedChapters.Contains((d.Revision,d.Book,item.Start))==true),Font,new Rectangle(e.Bounds.Left+Px(32),e.Bounds.Top+Px(28),e.Bounds.Width-Px(40),Px(22)),ink,TextFormatFlags.EndEllipsis|TextFormatFlags.SingleLine);e.DrawFocusRectangle();
|
||||
var night=CompanionPresentation.Dark(dark);var background=night?Color.FromArgb(27,25,31):Color.FromArgb(246,243,238);var surface=night?Color.FromArgb(42,38,46):Color.FromArgb(255,253,250);var ink=night?Color.FromArgb(240,233,225):Color.FromArgb(49,40,51);var accent=night?Color.FromArgb(207,178,204):Color.FromArgb(100,60,96);
|
||||
void Paint(Control item,bool card=false){card|=item is RoundedCard;item.BackColor=card?surface:background;item.ForeColor=ink;if(item is RoundedCard rounded)rounded.Outside=background;
|
||||
if(item is Button button){button.FlatStyle=FlatStyle.Flat;button.FlatAppearance.BorderSize=0;button.Padding=new(10,5,10,5);button.Margin=new(0,4,8,4);button.BackColor=button.Tag as string=="primary"?accent:surface;button.ForeColor=button.Tag as string=="primary"?(night?background:Color.White):ink;}
|
||||
if(item is TextBox or ComboBox)item.BackColor=surface;foreach(Control child in item.Controls)Paint(child,card);item.Invalidate();}
|
||||
Paint(root);
|
||||
}
|
||||
private void Exit(){SavePreferences();exiting=true;File.WriteAllText(Path.Combine(directory,"paused"),"User exited Companion");shutdown.Cancel();tray.Visible=false;Application.Exit();}
|
||||
protected override void Dispose(bool disposing){if(disposing){Microsoft.Win32.SystemEvents.UserPreferenceChanged-=OnPreferences;timer.Dispose();tips.Dispose();tray.Dispose();brand.Dispose();}base.Dispose(disposing);}
|
||||
protected override void Dispose(bool disposing){if(disposing){Microsoft.Win32.SystemEvents.UserPreferenceChanged-=OnPreferences;coverStop?.Cancel();timer.Dispose();settings?.Dispose();tips.Dispose();tray.Dispose();brand.Dispose();}base.Dispose(disposing);}
|
||||
private static Icon CreateBrandIcon()
|
||||
{
|
||||
using var bitmap=new Bitmap(32,32);using(var graphics=Graphics.FromImage(bitmap)){graphics.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.AntiAlias;graphics.Clear(Color.Transparent);using var brush=new SolidBrush(Color.FromArgb(108,58,47));graphics.FillEllipse(brush,0,0,31,31);using var font=new Font("Segoe UI",19,FontStyle.Bold,GraphicsUnit.Pixel);using var ink=new SolidBrush(Color.FromArgb(255,244,223));graphics.DrawString("P",font,ink,7,3);}
|
||||
var handle=bitmap.GetHicon();try{using var borrowed=Icon.FromHandle(handle);return (Icon)borrowed.Clone();}finally{DestroyIcon(handle);}
|
||||
}
|
||||
[System.Runtime.InteropServices.DllImport("user32.dll")]private static extern bool DestroyIcon(IntPtr handle);
|
||||
private sealed record ChapterItem(int Start,string Title){public override string ToString()=>Title;}
|
||||
|
||||
}
|
||||
#endif
|
||||
|
||||
@ -6,11 +6,11 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
{
|
||||
private readonly Guid agentInstance=Guid.NewGuid(),agentSession=Guid.NewGuid();private int lastBook;private Guid lastAuthentication;private long agentSequence;private long presenceSequence=DateTime.UtcNow.Ticks;private int uploading;private DateTime lastAgentPresence;private bool agentOnlyPublished;
|
||||
private readonly object gate=new();private readonly Dictionary<Guid,TrayDocument> documents=[];
|
||||
private readonly Dictionary<Guid,Queue<AdapterCommand>> commands=[];private readonly Dictionary<Guid,Guid> leases=[];private readonly HashSet<Guid> captureInstances=[];private readonly Dictionary<(Guid,Guid),(Guid Manuscript,Guid Authentication,int Book,DateTime Expires)> reconnectBindings=[];
|
||||
private readonly Dictionary<Guid,Queue<AdapterCommand>> commands=[];private readonly Dictionary<Guid,Guid> leases=[];private readonly HashSet<Guid> captureInstances=[];private readonly HashSet<Guid> maintenanceInstances=[];private readonly Dictionary<Guid,(Guid Session,Guid Manuscript,Guid Authentication,string Kind,DateTime Started)> maintenance=[];private readonly Dictionary<(Guid,Guid),(Guid Manuscript,Guid Authentication,int Book,DateTime Expires)> reconnectBindings=[];
|
||||
public event Action? OpenRequested;
|
||||
public TrayDocument[] Documents {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).ToArray();}}
|
||||
public TrayDocument[] PresentationDocuments {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).Select(d=>d.Snapshot()).ToArray();}}
|
||||
public void Attach(Guid instance,Guid lease,bool capture=false){lock(gate){Disconnected(instance);leases[instance]=lease;if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}}
|
||||
public void Attach(Guid instance,Guid lease,bool capture=false,bool canMaintain=false){lock(gate){Disconnected(instance);leases[instance]=lease;if(canMaintain)maintenanceInstances.Add(instance);else maintenanceInstances.Remove(instance);if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}}
|
||||
public Message Exchange(Guid instance,Message request,Message answer,Guid lease=default)
|
||||
{
|
||||
lock(gate)
|
||||
@ -23,7 +23,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
foreach(var descriptor in request.Documents){
|
||||
if(sessions.Descriptor(instance,descriptor.SessionId)==null)continue;
|
||||
if(!documents.TryGetValue(descriptor.SessionId,out var d))documents[descriptor.SessionId]=d=new(){Session=descriptor.SessionId,Instance=instance};
|
||||
if(d.Revision!=descriptor.Revision){Cancel(d);d.WordSaved=null;d.Chapters=[];d.FailedChapters.Clear();d.Words=null;d.ChapterId=null;d.SceneId=null;d.ChapterTitle="";d.SceneTitle="";d.LastPresenceKey="";d.Status="Document changed. Detect chapters to refresh this snapshot.";}
|
||||
if(d.Revision!=descriptor.Revision){foreach(var pending in maintenance.Where(p=>p.Value.Session==d.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(pending);d.MaintenanceReport="Stopped: document revision changed; inspect before retrying cleanup.";}Cancel(d);d.WordSaved=null;d.Chapters=[];d.FailedChapters.Clear();d.Words=null;d.ChapterId=null;d.SceneId=null;d.ChapterTitle="";d.SceneTitle="";d.LastPresenceKey="";d.Status="Document changed. Detect chapters to refresh this snapshot.";}
|
||||
if(reconnectBindings.Remove((instance,descriptor.SessionId),out var binding)&&binding.Expires>DateTime.UtcNow&&binding.Manuscript==descriptor.ManuscriptId&&binding.Authentication==cloud.Status().AuthenticationContext){d.Book=binding.Book;d.Authentication=binding.Authentication;}
|
||||
d.Revision=descriptor.Revision;d.Manuscript=descriptor.ManuscriptId;d.Title=descriptor.Title;d.RememberedBook=descriptor.RememberedBook;d.AssociationSite=descriptor.AssociationSite;d.Observed=DateTime.UtcNow;
|
||||
}
|
||||
@ -40,7 +40,8 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
if(request.Kind.StartsWith("snapshot-",StringComparison.Ordinal)&&answer.Status is not ("ok" or "analysis-complete" or "awaiting-structure")){Cancel(doc);doc.Status="Local reading failed: "+answer.Status+". Detect chapters again.";}
|
||||
if(request.Kind=="snapshot-fragment")doc.Progress=answer.Progress;
|
||||
if(request.Kind=="snapshot-end"&&answer.Status=="analysis-complete"){doc.Chapters=sessions.Chapters(instance,doc.Session);doc.Status=$"Detected {doc.Chapters.Length} Heading 1 / existing-marker chapters. Scenes require explicit server AI analysis.";doc.Progress=100;}
|
||||
if(request.Kind=="adapter-result"&&request.OperationMessage!="ok"){doc.Status=request.OperationMessage;Cancel(doc);}
|
||||
if(request.Kind=="adapter-result"&&maintenance.Remove(request.SnapshotId,out var operation)&&operation.Session==doc.Session){doc.MaintenanceReport=request.OperationMessage;if(request.OperationMessage.StartsWith("Complete:",StringComparison.Ordinal)&&operation.Kind is "reset" or "clean"){cloud.ForgetBinding(operation.Manuscript,operation.Authentication);doc.Book=0;doc.RememberedBook=null;doc.AssociationSite="";doc.ChapterId=null;doc.SceneId=null;doc.LastPresenceKey="";_=cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);} }
|
||||
else if(request.Kind=="adapter-result"&&request.OperationMessage!="ok"){doc.Status=request.OperationMessage;Cancel(doc);}
|
||||
if(request.Kind=="ai-cancel"){Cancel(doc);doc.Status="Extraction cancelled or document changed. Successful server suggestions are retained.";}
|
||||
if(request.Kind=="metrics")doc.WordDiagnostics=request.OperationMessage.Length<=6000?request.OperationMessage:"Diagnostics size exceeded";
|
||||
if(request.Kind=="ai-fragment")doc.Progress=answer.Progress;
|
||||
@ -52,8 +53,17 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
}
|
||||
}
|
||||
public void Disconnected(Guid instance,Guid lease=default){lock(gate){if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return;leases.Remove(instance);foreach(var expired in reconnectBindings.Where(p=>p.Value.Expires<=DateTime.UtcNow).Select(p=>p.Key).ToArray())reconnectBindings.Remove(expired);foreach(var doc in documents.Values.Where(d=>d.Instance==instance).ToArray()){if(doc.Book>0&&reconnectBindings.Count<256)reconnectBindings[(instance,doc.Session)]=(doc.Manuscript,doc.Authentication,doc.Book,DateTime.UtcNow.AddMinutes(2));Remove(doc.Session);}commands.Remove(instance);}}
|
||||
private void Remove(Guid session){if(documents.Remove(session,out var doc)){Cancel(doc);_ = cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);}}
|
||||
private void Remove(Guid session){foreach(var key in maintenance.Where(p=>p.Value.Session==session).Select(p=>p.Key).ToArray())maintenance.Remove(key);if(documents.Remove(session,out var doc)){Cancel(doc);_ = cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);}}
|
||||
private bool Queue(TrayDocument doc,AdapterCommand command){if(!commands.TryGetValue(doc.Instance,out var queue))commands[doc.Instance]=queue=new();if(queue.Count>=16){doc.Status="Word request queue is busy. Retry after current operation.";return false;}command.SessionId=doc.Session;command.Revision=doc.Revision;queue.Enqueue(command);return true;}
|
||||
public bool CanMaintain(Guid session){lock(gate)return documents.TryGetValue(session,out var d)&&maintenanceInstances.Contains(d.Instance);}
|
||||
public void Maintain(Guid session,string kind)
|
||||
{
|
||||
if(!DocumentMaintenancePolicy.IsAction(kind))throw new ArgumentException("Unknown maintenance action.");
|
||||
lock(gate){if(!documents.TryGetValue(session,out var doc)||!maintenanceInstances.Contains(doc.Instance))throw new InvalidOperationException("Update the Word add-in to use document maintenance.");
|
||||
foreach(var expired in maintenance.Where(p=>DateTime.UtcNow-p.Value.Started>TimeSpan.FromMinutes(3)).Select(p=>p.Key).ToArray())maintenance.Remove(expired);
|
||||
if(maintenance.Values.Any(v=>v.Session==session))throw new InvalidOperationException("Wait for the current document inspection or cleanup.");
|
||||
Cancel(doc);var command=new AdapterCommand{Kind="maintenance-"+kind};if(Queue(doc,command)){maintenance[command.Id]=(session,doc.Manuscript,doc.Authentication,kind,DateTime.UtcNow);doc.MaintenanceReport="Working in short Word batches…";}}
|
||||
}
|
||||
public void Detect(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Completed.Clear();doc.FailedChapters.Clear();doc.Status="Reading chapters in bounded Word batches…";doc.Progress=0;Queue(doc,new(){Kind="detect"});}}
|
||||
public void SelectBook(Guid session,int book,bool remember)
|
||||
{
|
||||
@ -79,7 +89,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){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){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)
|
||||
{
|
||||
@ -126,7 +136,7 @@ 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="";
|
||||
public ManuscriptCapture? Capture;public List<ParagraphFragment> CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision;
|
||||
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 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<StructureSuggestion> Pending=[];public HashSet<(long,int,int)> Completed=[];public HashSet<(long,int,int)> FailedChapters=[];public List<string> Errors=[];
|
||||
internal TrayDocument Snapshot(){var copy=(TrayDocument)MemberwiseClone();copy.Completed=new(Completed);copy.FailedChapters=new(FailedChapters);copy.Errors=new(Errors);copy.Pending=new(Pending);return copy;}
|
||||
public override string ToString()=>Title+(Active?" (active in Word)":"");
|
||||
|
||||
@ -97,7 +97,7 @@ public sealed class AgentLink : IDisposable
|
||||
lock (gate) activePipe = pipe;
|
||||
await pipe.ConnectAsync(700, stop.Token).ConfigureAwait(false);
|
||||
if (!verifyServer(pipe)) throw new UnauthorizedAccessException("Unexpected agent owner.");
|
||||
await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability }, stop.Token).ConfigureAwait(false);
|
||||
await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability }, stop.Token).ConfigureAwait(false);
|
||||
mailbox.Clear(); // Reconcile authoritative open documents; never replay stale extraction fragments.
|
||||
await ExchangeAsync(pipe, Reconcile(), stop.Token).ConfigureAwait(false);
|
||||
attempt = 0; StateChanged?.Invoke("connected");
|
||||
|
||||
@ -1 +1 @@
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.14</ApplicationVersion></PropertyGroup></Project>
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.15</ApplicationVersion></PropertyGroup></Project>
|
||||
|
||||
@ -41,5 +41,9 @@ public sealed class AiChapterResult
|
||||
public sealed class CompanionBook
|
||||
{
|
||||
[DataMember] public int BookId { get; set; }
|
||||
[DataMember] public string ProjectTitle { get; set; }="";
|
||||
[DataMember] public string BookTitle { get; set; }="";
|
||||
[DataMember] public string Title { get; set; }="";
|
||||
}
|
||||
|
||||
public sealed class BookCoverReply { public string Png {get;set;}=""; }
|
||||
|
||||
@ -0,0 +1,9 @@
|
||||
namespace PlotDirector.Companion.Protocol;
|
||||
// Match the established Office.js ownership prefixes; never infer ownership from titles or ranges.
|
||||
public static class DocumentMaintenancePolicy
|
||||
{
|
||||
public static bool IsAction(string action)=>action is "inspect" or "markers" or "reset" or "clean";
|
||||
public static bool OwnsControl(string? tag){var value=(tag??"").Trim();return value.StartsWith("PD-CHAPTER-",System.StringComparison.OrdinalIgnoreCase)||value.StartsWith("PD-SCENE-",System.StringComparison.OrdinalIgnoreCase);}
|
||||
public static bool OwnsBookmark(string? name)=>name!=null&&(name.StartsWith("_PD_CHAPTER_",System.StringComparison.Ordinal)||name.StartsWith("_PD_SCENE_",System.StringComparison.Ordinal));
|
||||
public static readonly string[] Properties={"PlotDirector.Native.Association","PlotDirector.Native.DocumentGuid","PlotDirector.Native.ProjectID","PlotDirector.Native.BookID","PlotDirector.Native.ServerUrl"};
|
||||
}
|
||||
@ -5,6 +5,7 @@ namespace PlotDirector.Companion.Protocol;
|
||||
public static class ProtocolVersion
|
||||
{
|
||||
public const int Current = 1;
|
||||
public const string MaintenanceCapability="document-maintenance-v1";
|
||||
public const string CaptureCapability="wizard-capture-v1";
|
||||
public const string TrayCapability="tray-adapter-v1";
|
||||
public const string WorkflowCapability = "workspace-review-v1";
|
||||
|
||||
@ -12,7 +12,7 @@ internal static class PersistentConnectionTests
|
||||
var clock=new Clock();var server=new Server(clock);var store=new MemoryStore();int approvals=0;var manuscript=Guid.NewGuid();
|
||||
using(var cloud=new CloudGateway(server,_=>approvals++,stateStore:store,timeProvider:clock)){
|
||||
cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Health?.State=="Connected");
|
||||
cloud.RememberBinding(manuscript,3);cloud.SavePreferences(new(){Width=975,Height=725,RememberInDocument=true,LastManuscript=manuscript});await cloud.FlushSettingsAsync();
|
||||
cloud.RememberBinding(manuscript,3);cloud.SavePreferences(new(){AdvancedMode=true,Width=975,Height=725,RememberInDocument=true,LastManuscript=manuscript});await cloud.FlushSettingsAsync();
|
||||
check(approvals==1&&store.Load().Active!=null,"first pairing saves approved installation, not a four-hour-only sign-in");
|
||||
check(!JsonSerializer.Serialize(store.Load()).Contains("access:"),"short-lived access tokens are never persisted in settings");
|
||||
}
|
||||
@ -20,7 +20,7 @@ internal static class PersistentConnectionTests
|
||||
server.Offline=true;using(var cloud=new CloudGateway(server,_=>approvals++,stateStore:store,timeProvider:clock)){
|
||||
using var stop=new CancellationTokenSource();var loop=cloud.RunConnectionLoop(stop.Token);await Until(()=>cloud.Status().Health?.State=="Reconnecting");await Task.Delay(200);check(server.RenewAttempts==1,"offline startup makes a bounded renewal attempt without browser approval");
|
||||
server.Offline=false;clock.Advance(TimeSpan.FromMinutes(1));await Until(()=>cloud.Status().Health?.State=="Connected");stop.Cancel();await loop;
|
||||
check(approvals==1&&cloud.RestoreBinding(manuscript)==3&&cloud.Preferences.Width==975&&cloud.Preferences.RememberInDocument,"process/network recovery restores scoped association and preferences without interaction");
|
||||
check(approvals==1&&cloud.RestoreBinding(manuscript)==3&&cloud.Preferences.Width==975&&cloud.Preferences.RememberInDocument&&cloud.Preferences.AdvancedMode,"process/network recovery restores scoped association and preferences without interaction");
|
||||
var context=cloud.Status().AuthenticationContext;clock.Advance(TimeSpan.FromMinutes(11));await cloud.ReconnectAsync();
|
||||
check(cloud.Status().AuthenticationContext==context&&cloud.Status().Health?.State=="Connected"&&approvals==1,"access expiry renews without changing account context or asking for browser approval");
|
||||
server.AllowBook=false;await cloud.CheckConnection();check(cloud.RestoreBinding(manuscript)==null,"persisted association is not restored when current book permission is missing");server.AllowBook=true;await cloud.CheckConnection();
|
||||
|
||||
@ -167,6 +167,16 @@ Check(CompanionPresentation.Connection(new(){Authentication="expired"},DateTime.
|
||||
Check(CompanionPresentation.Next(false,false,0,false).Contains("browser"),"first run remains useful without Word");
|
||||
Check(CompanionPresentation.Next(true,false,0,false).Contains("Choose"),"book association precedes analysis");
|
||||
Check(CompanionPresentation.Chapter(false,true).Contains("review")&&!CompanionPresentation.Chapter(false,true).Contains("imported"),"analysis completion never claims import completion");
|
||||
Check(!CompanionPresentation.NeedsAuthorisation(new(){State="Action required",Authentication="pending"})&&CompanionPresentation.Connection(new(){Authentication="pending"},DateTime.UtcNow).Contains("Waiting"),"pending browser approval has no duplicate sign-in action");
|
||||
Check(CompanionPresentation.Connection(new(){State="Connected",Server="online",Authentication="verified",VerifiedUtc=DateTime.UtcNow.AddMinutes(-5)},DateTime.UtcNow)=="Reconnecting","explicit connected state still requires current verification");
|
||||
Check(!new CompanionPreferences().AdvancedMode,"Advanced mode is off for new installations");
|
||||
Check(!CompanionPresentation.NeedsAuthorisation(new(){State="Reconnecting",Authentication="expired"}),"trusted access renewal does not offer repeated browser sign-in");
|
||||
Check(CompanionPresentation.NeedsAuthorisation(new(){State="Action required"}),"invalid installation offers the existing browser sign-in action");
|
||||
Check(CompanionPresentation.WordStatus(false,3,DateTime.UtcNow,"ok",DateTime.UtcNow).Contains("not connected"),"server success never implies Word is connected");
|
||||
Check(CompanionPresentation.WordStatus(true,3,DateTime.UtcNow.AddMinutes(-2),"ok",DateTime.UtcNow).Contains("pending"),"stale Word registration cannot be displayed as connected to book");
|
||||
Check(DocumentMaintenancePolicy.OwnsControl(" pd-scene-12 ")&&DocumentMaintenancePolicy.OwnsBookmark("_PD_CHAPTER_9"),"maintenance recognises established PlotDirector marker ownership");
|
||||
Check(!DocumentMaintenancePolicy.OwnsControl("Author chapter")&&!DocumentMaintenancePolicy.OwnsControl("OTHER-PD-SCENE-1")&&!DocumentMaintenancePolicy.OwnsBookmark("AuthorBookmark"),"maintenance leaves unrelated controls and bookmarks alone");
|
||||
Check(DocumentMaintenancePolicy.Properties.Length==5&&!DocumentMaintenancePolicy.Properties.Contains("Author"),"document-property deletion uses an explicit owned allowlist");
|
||||
await AnalysisTests.Run(Check);
|
||||
await ChapterAiTests.Run(Check);
|
||||
await WorkflowTests.Run(Check);
|
||||
|
||||
@ -46,6 +46,24 @@ internal static class TrayTests
|
||||
control.SelectBook(second.SessionId,3,false);control.Analyse(second.SessionId,[10]);check(control.Documents.Single(d=>d.Session==second.SessionId).Job==Guid.Empty&&control.Documents.Single(d=>d.Session==second.SessionId).Pending.Count==1,"multiple document AI batches serialize against existing per-author provider limits");control.Cancel(second.SessionId);
|
||||
control.Cancel(first.SessionId);check(control.Documents.Single(d=>d.Session==first.SessionId).Job==Guid.Empty&&control.Documents.Single(d=>d.Session==first.SessionId).Pending.Count==0,"tray cancellation stops queued chapters without affecting another document");
|
||||
var replacementLease=Guid.NewGuid();control.Attach(instance,replacementLease);Apply(new(){Kind="document",Documents=[first]});control.Disconnected(instance,lease);check(control.Documents.Length==1&&control.Documents[0].Book==3,"late disconnect cannot remove a replacement tray lease or its verified session-only book association");
|
||||
check(!control.CanMaintain(first.SessionId),"older Word adapter cannot receive unsupported maintenance commands");
|
||||
control.Attach(instance,replacementLease,true,true);Apply(new(){Kind="reconcile",Documents=[first,second]});
|
||||
check(control.CanMaintain(first.SessionId),"maintenance requires explicit adapter capability negotiation");
|
||||
control.Maintain(first.SessionId,"inspect");AdapterCommand? maintenance=null;
|
||||
for(var i=0;i<16;i++){var queued=Apply(new(){Kind="ping"}).Command;if(queued?.Kind=="maintenance-inspect"){maintenance=queued;break;}}
|
||||
check(maintenance?.SessionId==first.SessionId&&maintenance.Revision==1,"inspection command targets exact selected document and revision");
|
||||
Apply(new(){Kind="adapter-result",SessionId=second.SessionId,Revision=1,SnapshotId=Guid.NewGuid(),OperationMessage="Complete: unrelated"});
|
||||
check(control.Documents.Single(d=>d.Session==first.SessionId).MaintenanceReport.Contains("Working"),"another document cannot replace pending inspection results");
|
||||
Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=1,SnapshotId=maintenance!.Id,OperationMessage="Complete: inspected"});
|
||||
check(control.Documents.Single(d=>d.Session==first.SessionId).MaintenanceReport=="Complete: inspected","correlated inspection result is available in Advanced settings");
|
||||
var maintained=control.Documents.Single(d=>d.Session==first.SessionId);maintained.Book=3;
|
||||
control.Maintain(first.SessionId,"clean");maintenance=null;for(var i=0;i<16;i++){var queued=Apply(new(){Kind="ping"}).Command;if(queued?.Kind=="maintenance-clean"){maintenance=queued;break;}}
|
||||
check(maintained.Book==3,"unlink does not claim success before Word acknowledges cleanup");
|
||||
Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=1,SnapshotId=maintenance!.Id,OperationMessage="Stopped: read-only"});
|
||||
check(maintained.Book==3,"failed cleanup preserves document association");
|
||||
control.Maintain(first.SessionId,"reset");maintenance=null;for(var i=0;i<16;i++){var queued=Apply(new(){Kind="ping"}).Command;if(queued?.Kind=="maintenance-reset"){maintenance=queued;break;}}
|
||||
Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=1,SnapshotId=maintenance!.Id,OperationMessage="Complete: reset"});
|
||||
check(maintained.Book==0&&control.Documents.Single(d=>d.Session==second.SessionId).MaintenanceReport!="Complete: reset","acknowledged reset unlinks only the selected session");
|
||||
control.Disconnected(instance,replacementLease);check(control.Documents.Length==0,"pipe disconnect removes exact Word instance sessions and pending control work");
|
||||
}
|
||||
private static async Task Until(Func<bool> condition){using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(10));while(!condition())await Task.Delay(20,timeout.Token);}
|
||||
|
||||
@ -3,6 +3,6 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyTitle("PlotDirector Word Companion — Native development")]
|
||||
[assembly: AssemblyCompany("Nick Beckley")]
|
||||
[assembly: AssemblyProduct("PlotDirector")]
|
||||
[assembly: AssemblyVersion("1.0.0.14")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.14")]
|
||||
[assembly: AssemblyVersion("1.0.0.15")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.15")]
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
@ -226,7 +226,9 @@ namespace PlotDirector.WordAddIn
|
||||
if(!scheduler.Post("command:"+doc.Session,()=>{
|
||||
if(!documents.ContainsKey(doc.Document)||doc.Revision!=command.Revision){Reply(command,"Document changed; request again.");return;}
|
||||
try{
|
||||
if(command.Kind=="wizard-capture"){
|
||||
if(doc.Maintenance!=null){var previous=doc.Maintenance;scheduler.Cancel("maintenance:"+doc.Session);Reply(previous,"Stopped: superseded by a new document request. Inspect before retrying cleanup.");}
|
||||
if(command.Kind.StartsWith("maintenance-",StringComparison.Ordinal)){StartMaintenance(doc,command);return;}
|
||||
else if(command.Kind=="wizard-capture"){
|
||||
CancelExtraction(doc);doc.End=DocumentEnd(doc.Document);if(!ScheduleSnapshot(doc,true,command.Id))throw new InvalidOperationException("Word queue unavailable. Retry import from PlotDirector.");
|
||||
}
|
||||
else if(command.Kind=="detect"){
|
||||
@ -256,7 +258,49 @@ namespace PlotDirector.WordAddIn
|
||||
}catch(Exception e)when(e is COMException||e is InvalidOperationException||e is ArgumentException){Reply(command,"Word operation unavailable: "+e.GetType().Name+". Retry or select without Remember.");}
|
||||
}))Reply(command,"Word queue busy. Retry from Companion.");
|
||||
}
|
||||
private void Reply(AdapterCommand command,string result)=>link.TryPost(new Message{Kind="adapter-result",SessionId=command.SessionId,Revision=command.Revision,SnapshotId=command.Id,OperationMessage=result});
|
||||
// Retain no collection/range RCWs between scheduler turns. One marker per turn; typing/save/close take priority.
|
||||
private void StartMaintenance(LocalDocument doc,AdapterCommand command)
|
||||
{
|
||||
var kind=command.Kind.Substring("maintenance-".Length);
|
||||
if(!DocumentMaintenancePolicy.IsAction(kind))throw new ArgumentException("Unknown maintenance operation.");
|
||||
if(kind!="inspect"&&Com(()=>doc.Document.ReadOnly))throw new InvalidOperationException("Document is read-only.");
|
||||
CancelExtraction(doc);
|
||||
doc.Maintenance=command;var started=Stopwatch.StartNew();
|
||||
var stage=kind=="reset"?2:0;var index=kind=="reset"?0:-1;var count=0;var inspected=0;var removed=0;var report=new System.Text.StringBuilder();
|
||||
Action next=null;
|
||||
next=()=>{
|
||||
if(doc.Maintenance!=command)return;
|
||||
if(started.Elapsed>TimeSpan.FromMinutes(2)||!documents.ContainsKey(doc.Document)||closing.Contains(doc.Document)||doc.Revision!=command.Revision){Reply(command,"Stopped: document closed, saved or changed. Some markers may already be removed; inspect again.");return;}
|
||||
try{
|
||||
if(++inspected>100000)throw new InvalidOperationException("Maintenance limit reached; inspect again.");
|
||||
if(stage==0){
|
||||
Word.ContentControls controls=null;Word.ContentControl marker=null;
|
||||
try{controls=Com(()=>doc.Document.ContentControls);count=Com(()=>controls.Count);if(index<0)index=count;
|
||||
if(index>count)throw new InvalidOperationException("Marker collection changed; inspect again.");
|
||||
if(index==0){stage=1;index=-1;}
|
||||
else{marker=Com(()=>controls[index--]);var tag=Com(()=>marker.Tag);if(DocumentMaintenancePolicy.OwnsControl(tag)){if(report.Length<3500)report.AppendLine("Control: "+tag);if(kind is "markers" or "clean"){Com(()=>{marker.Delete(false);return true;});removed++;}}}
|
||||
}finally{Release(marker);Release(controls);}
|
||||
}else if(stage==1){
|
||||
Word.Bookmarks bookmarks=null;Word.Bookmark marker=null;bool hidden=false;bool read=false;
|
||||
try{bookmarks=Com(()=>doc.Document.Bookmarks);hidden=Com(()=>bookmarks.ShowHidden);read=true;Com(()=>{bookmarks.ShowHidden=true;return true;});count=Com(()=>bookmarks.Count);if(index<0)index=count;
|
||||
if(index>count)throw new InvalidOperationException("Bookmarks changed; inspect again.");
|
||||
if(index==0){stage=2;index=0;}
|
||||
else{object key=index--;marker=Com(()=>bookmarks.get_Item(ref key));var name=Com(()=>marker.Name);if(DocumentMaintenancePolicy.OwnsBookmark(name)){if(report.Length<3500)report.AppendLine("Bookmark: "+name);if(kind is "markers" or "clean"){Com(()=>{marker.Delete();return true;});removed++;}}}
|
||||
}finally{if(read)Com(()=>{bookmarks.ShowHidden=hidden;return true;});Release(marker);Release(bookmarks);}
|
||||
}else if(index<DocumentMaintenancePolicy.Properties.Length){
|
||||
var name=DocumentMaintenancePolicy.Properties[index++];var value=ReadProperty(doc.Document,name);
|
||||
if(value!=""){if(report.Length<3500)report.AppendLine(name+": "+value.Substring(0,Math.Min(512,value.Length)));
|
||||
if(kind is "reset" or "clean"){object properties=null,property=null;try{properties=Com(()=>doc.Document.CustomDocumentProperties);dynamic collection=properties;property=Com<object>(()=>collection[name]);dynamic item=property;Com(()=>{item.Delete();return true;});}finally{Release(property);Release(properties);}}}
|
||||
}else{
|
||||
if(kind is "reset" or "clean"){doc.Identity=Guid.NewGuid();doc.IdentityPersisted=false;doc.BookId=null;doc.ProjectId=null;doc.AssociationSite="";link.Register(Descriptor(doc));}
|
||||
Reply(command,"Complete: "+(kind=="inspect"?"PlotDirector identifiers (only owned metadata shown)":$"{removed} owned markers removed. Prose retained. Save Word normally if you wish to keep changes.")+"\r\n"+report);return;
|
||||
}
|
||||
if(!scheduler.Post("maintenance:"+doc.Session,next))Reply(command,"Stopped: Word queue busy; inspect before retrying.");
|
||||
}catch(Exception e)when(e is COMException||e is InvalidOperationException||e is ArgumentException){Reply(command,"Stopped: Word maintenance could not complete ("+e.GetType().Name+"). Some metadata may already be removed; inspect before retrying. No prose was deliberately edited.");}
|
||||
};
|
||||
if(!scheduler.Post("maintenance:"+doc.Session,next))Reply(command,"Stopped: Word queue busy.");
|
||||
}
|
||||
private void Reply(AdapterCommand command,string result){var doc=documents.Values.FirstOrDefault(d=>d.Session==command.SessionId);if(doc?.Maintenance==command)doc.Maintenance=null;link.TryPost(new Message{Kind="adapter-result",SessionId=command.SessionId,Revision=command.Revision,SnapshotId=command.Id,OperationMessage=result});}
|
||||
private bool ScheduleSnapshot(LocalDocument doc,bool analyse=false,Guid? snapshot=null)
|
||||
{
|
||||
if (doc.Extraction != null || ConnectionState != "connected") return false;
|
||||
@ -534,7 +578,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 AdapterCommand Maintenance;public readonly Word.Document Document;public readonly Guid Session=Guid.NewGuid();public Guid Identity;public bool IdentityPersisted;
|
||||
|
||||
public string DisplayName;
|
||||
public string AssociationSite="",ChapterTitle="",SceneTitle="";
|
||||
|
||||
@ -41,9 +41,13 @@ internal static class NativeCompanionHttpTests
|
||||
var subscriptions=Proxy<ISubscriptionService>((name,args)=>Task.FromResult(new EntitlementDecision{Allowed=allowed}));
|
||||
var json="""{"schemaVersion":"1.0","chapterSummary":"A fictional chapter.","sceneBoundaries":[{"sceneNumber":1,"startParagraph":1,"endParagraph":1,"suggestedTitle":"A narrative scene","structuralSummary":"The characters encounter a new problem and make a decision to resolve the immediate situation.","confidence":0.8,"reason":"A coherent dramatic unit."}]}""";
|
||||
var provider=new FakeStoryIntelligenceClient(JsonSerializer.Serialize(new{output=new[]{new{content=new[]{new{type="output_text",text=json}}}}}));
|
||||
var coverFile=Path.Combine(Path.GetTempPath(),"pd-native-cover-"+Guid.NewGuid()+".png");
|
||||
using(var bitmap=new SkiaSharp.SKBitmap(20,30)){using var image=SkiaSharp.SKImage.FromBitmap(bitmap);using var png=image.Encode(SkiaSharp.SKEncodedImageFormat.Png,90);File.WriteAllBytes(coverFile,png.ToArray());}
|
||||
var coverReads=0;
|
||||
var builder=WebApplication.CreateBuilder(new WebApplicationOptions{EnvironmentName="Development"});builder.Logging.ClearProviders();builder.WebHost.UseUrls("http://127.0.0.1:0");
|
||||
builder.Services.AddSingleton<IStoryIntelligenceClient>(provider);
|
||||
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IBookRepository>((n,a)=>Task.FromResult<Book?>(new(){BookID=3,ProjectID=1,BookTitle="Fixture book"})));
|
||||
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IBookRepository>((n,a)=>{if(n=="GetCoverPathsAsync")coverReads++;return Task.FromResult<Book?>(new(){BookID=3,ProjectID=1,BookTitle="Fixture book",CoverThumbnailPath="/uploads/books/3/cover.webp"});}));
|
||||
builder.Services.AddSingleton(Proxy<IUploadStorageService>((n,a)=>n=="TryResolvePublicPath"&&Equals(a![1],"uploads/books/3")?coverFile:throw new Exception("Unexpected cover path lookup")));
|
||||
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IWordCompanionService>((n,a)=>n=="AnalyseManuscriptAsync"?Task.FromResult<WordCompanionManuscriptAnalyseResponse?>(new(){CanImport=true,Message="Preview eligible"}):throw new Exception("Unexpected write "+n)));
|
||||
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IStoryContextService>((n,a)=>Task.FromResult<StoryContextViewModel?>(null)));
|
||||
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IWriterWorkspaceService>((n,a)=>Task.FromResult<PlotLine.ViewModels.ChapterWorkflowViewModel?>(null)));
|
||||
@ -86,6 +90,9 @@ internal static class NativeCompanionHttpTests
|
||||
var redeemed=await agent.PostAsJsonAsync("/api/native-companion/token",new{code,verifier});Check(redeemed.IsSuccessStatusCode,"Agent redeems approved pairing");
|
||||
var token=(await redeemed.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("accessToken").GetString();agent.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Bearer",token);
|
||||
Check((await agent.GetFromJsonAsync<CompanionBook[]>("/api/native-companion/books"))!.Single().BookId==3,"Grant loads authorized books through actual routing");
|
||||
var listed=(await agent.GetFromJsonAsync<CompanionBook[]>("/api/native-companion/books"))!.Single();Check(listed.ProjectTitle=="Fixture"&&listed.BookTitle=="Test book","Native book selection includes author-facing project and book names");
|
||||
Check((await agent.GetAsync("/api/native-companion/books/999/cover")).StatusCode==HttpStatusCode.Forbidden&&coverReads==0,"Foreign book cover denied before private file lookup");
|
||||
var cover=await agent.GetFromJsonAsync<BookCoverReply>("/api/native-companion/books/3/cover");Check(coverReads==1&&Convert.FromBase64String(cover!.Png).Take(4).SequenceEqual(new byte[]{137,80,78,71}),"Authorised cover uses an actual bounded PNG suitable for Windows");
|
||||
Check((await agent.GetFromJsonAsync<ConnectionHealth>("/api/native-companion/connection"))?.Authentication=="verified","Authenticated health verifies current session and configuration without paid AI request");
|
||||
Check((await agent.GetFromJsonAsync<SavedWorkspace>("/api/native-companion/books/3/workspace"))?.State=="saved-book","Saved workspace is scoped to accessible book over actual HTTP");
|
||||
var preview=await agent.PostAsJsonAsync("/api/native-companion/import-preview",NativeWorkflowTests.Selection());Check(preview.IsSuccessStatusCode&&(await preview.Content.ReadFromJsonAsync<PlotDirector.Companion.Protocol.ImportPreview>())?.CommitAvailable==false,"HTTP import preview is read-only with commit explicitly unavailable");
|
||||
@ -128,7 +135,7 @@ internal static class NativeCompanionHttpTests
|
||||
agent.DefaultRequestHeaders.Authorization=new("Bearer",token);
|
||||
user.SecurityStamp=Guid.NewGuid();Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Revoked grant rejected through HTTP handler");
|
||||
}
|
||||
finally{await app.StopAsync();}
|
||||
finally{await app.StopAsync();File.Delete(coverFile);}
|
||||
Console.WriteLine("PASS actual HTTP native pairing, antiforgery, bearer/stamp, book/subscription access, canonical AI/idempotency, persistent review and live WebSocket invalidation (synthetic provider, no database)");
|
||||
}
|
||||
}
|
||||
|
||||
@ -19,9 +19,29 @@ public sealed class NativeCompanionController(IWordCompanionRepository repositor
|
||||
{
|
||||
var result=new List<CompanionBook>();
|
||||
foreach(var project in await repository.ListProjectsAsync(UserId))
|
||||
result.AddRange((await repository.ListBooksAsync(project.ProjectId,UserId)).Select(b=>new CompanionBook{BookId=b.BookId,Title=project.Title+" / "+b.DisplayTitle}));
|
||||
result.AddRange((await repository.ListBooksAsync(project.ProjectId,UserId)).Select(b=>new CompanionBook{BookId=b.BookId,Title=project.Title+" / "+b.DisplayTitle,ProjectTitle=project.Title,BookTitle=b.DisplayTitle}));
|
||||
return Ok(result.Take(500));
|
||||
}
|
||||
// Ownership is checked before looking up a private cover path. No public URLs or client paths accepted.
|
||||
[HttpGet("books/{bookId:int}/cover")]
|
||||
public async Task<IActionResult> Cover(int bookId,[FromServices] IBookRepository books,[FromServices] IUploadStorageService storage)
|
||||
{
|
||||
if(await repository.GetBookStructureAsync(bookId,UserId)==null)return Forbid();
|
||||
Response.Headers.CacheControl="no-store";
|
||||
var book=await books.GetCoverPathsAsync(bookId);
|
||||
var path=storage.TryResolvePublicPath(book?.CoverThumbnailPath,$"uploads/books/{bookId}");
|
||||
if(path==null||!System.IO.File.Exists(path))return Ok(new BookCoverReply());
|
||||
if(new FileInfo(path).Length>2*1024*1024)return StatusCode(413);
|
||||
using var input=System.IO.File.OpenRead(path);
|
||||
using var codec=SkiaSharp.SKCodec.Create(input);
|
||||
if(codec==null||codec.Info.Width>600||codec.Info.Height>900)return Ok(new BookCoverReply());
|
||||
using var bitmap=SkiaSharp.SKBitmap.Decode(codec);
|
||||
if(bitmap==null||bitmap.Width>600||bitmap.Height>900)return Ok(new BookCoverReply());
|
||||
using var image=SkiaSharp.SKImage.FromBitmap(bitmap);
|
||||
using var png=image.Encode(SkiaSharp.SKEncodedImageFormat.Png,90);
|
||||
if(png.Size>700000)return StatusCode(413);
|
||||
return Ok(new BookCoverReply{Png=Convert.ToBase64String(png.ToArray())});
|
||||
}
|
||||
[HttpPost("analyse-chapter"),RequestSizeLimit(2*1024*1024)]
|
||||
public async Task<IActionResult> Analyse(AiChapterRequest request)
|
||||
{
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user