Refresh Companion control centre with Windows themes and chapter activity

This commit is contained in:
Nick Beckley 2026-11-06 10:36:11 +00:00
parent a2e891c917
commit d909960fd5
7 changed files with 90 additions and 30 deletions

View File

@ -138,7 +138,7 @@ public sealed class CloudGateway : IDisposable
var url=new Uri(origin,path);if(url.GetLeftPart(UriPartial.Authority)!=origin.GetLeftPart(UriPartial.Authority))throw new InvalidDataException();openBrowser(url.AbsoluteUri);}
}
public void OpenSite(string page="book")
{Uri target;lock(gate){var site=origin??ValidateOrigin(ReadOrigin());target=new Uri(site,page switch{"context"=>"Writing/Context","intent"=>"Writing/Intent",_=>"/"});}openBrowser(target.AbsoluteUri);}
{Uri target;lock(gate){var site=origin??ValidateOrigin(ReadOrigin());target=new Uri(site,page switch{"help"=>"help/word-companion/install","context"=>"Writing/Context","intent"=>"Writing/Intent",_=>"/"});}openBrowser(target.AbsoluteUri);}
private void DisconnectPresence(){Uri? site;string? access;lock(gate){site=origin;access=token;}if(site==null||access==null)return;_ = Task.Run(async()=>{try{using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(5));using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/presence/disconnect"));request.Headers.Authorization=new("Bearer",access);using var response=await http.SendAsync(request,timeout.Token);}catch(Exception e)when(e is HttpRequestException or OperationCanceledException or ObjectDisposedException) {}});}
public void OpenCompanionPage(string path,Guid context)
{lock(gate){Expire();if(context!=authenticationContext||token==null||origin==null)throw new InvalidOperationException("Sign in first.");if(!path.StartsWith("/native-companion/",StringComparison.Ordinal))throw new InvalidDataException();var url=new Uri(origin,path);if(url.GetLeftPart(UriPartial.Authority)!=origin.GetLeftPart(UriPartial.Authority))throw new InvalidDataException();openBrowser(url.AbsoluteUri);}}

View File

@ -0,0 +1,18 @@
using PlotDirector.Companion.Protocol;
namespace PlotDirector.Companion.Agent;
// Pure presentation policy shared by portable tests and the Windows Forms view.
public static class CompanionPresentation
{
public static bool Dark(bool? windowsDark)=>windowsDark??false;
public static string Connection(ConnectionHealth? health,DateTime now)
{
if(health==null)return "Welcome · connect to PlotDirector";
if(health.Authentication is "expired" or "unauthorised")return "Sign in again";
if(health.Server=="checking")return "Checking your connection…";
if(health.Server!="online")return health.Server=="offline"?"Offline · Word is still available":"Connect to PlotDirector";
if(now-health.VerifiedUtc>TimeSpan.FromSeconds(90))return "Connection needs checking";
return health.Authentication=="verified"?"Connected to PlotDirector":"Sign in to continue";
}
public static string Next(bool document,bool book,int chapters,bool busy)=>!document?"Open a manuscript in Word to begin. You can still use PlotDirector in your browser.":!book?"Choose the PlotDirector book for this manuscript.":busy?"Your manuscript stays editable while the Companion works.":chapters==0?"Find chapters using your document’s Heading 1 styles.":"Select chapters to analyse. Review and import are separate steps in PlotDirector.";
public static string Chapter(bool analysing,bool analysed,bool failed=false)=>analysing?"Analysing…":analysed?"Analysed · review in PlotDirector":failed?"Could not analyse · select to retry":"Ready to analyse";
}

View File

@ -31,37 +31,52 @@ internal sealed class CompanionWindow:Form
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? Current=>control.Documents.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(640,550);Size=new(850,720);
var layout=new TableLayoutPanel{Dock=DockStyle.Fill,Padding=new(18),ColumnCount=1,RowCount=9};layout.ColumnStyles.Add(new(SizeType.Percent,100));for(int i=0;i<9;i++)layout.RowStyles.Add(new(i==7?SizeType.Percent:SizeType.AutoSize,i==7?100:0));
layout.Controls.Add(new Label{Text="PlotDirector · Word at your side",Font=new(Font,FontStyle.Bold),AutoSize=true},0,0);
var connection=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=2};connection.ColumnStyles.Add(new(SizeType.Percent,100));connection.ColumnStyles.Add(new(SizeType.AutoSize));var signIn=Button("Connect / Sign In",()=>cloud.Connect(site.Text.Trim()));connection.Controls.Add(site,0,0);connection.Controls.Add(signIn,1,0);layout.Controls.Add(connection,0,1);
layout.Controls.Add(status,0,2);layout.Controls.Add(documents,0,3);
var association=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=2};association.ColumnStyles.Add(new(SizeType.Percent,100));association.ColumnStyles.Add(new(SizeType.AutoSize));association.Controls.Add(books,0,0);association.Controls.Add(bookButton,1,0);association.Controls.Add(remember,0,1);association.SetColumnSpan(remember,2);layout.Controls.Add(association,0,4);
var actions=new FlowLayoutPanel{AutoSize=true,Dock=DockStyle.Fill,WrapContents=true};actions.Controls.AddRange([detect,analyse,cancel,review,Button("Use active Word document",()=>{var active=control.Documents.FirstOrDefault(d=>d.Active);if(active!=null){selected=active.Session;documents.SelectedItem=active;chapterKey="";}}),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);}),Button("Context",()=>Open("context")),Button("Intent",()=>Open("intent"))]);layout.Controls.Add(actions,0,5);
var p=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,RowCount=2};p.Controls.Add(progressText);p.Controls.Add(progress);layout.Controls.Add(p,0,6);
var tabs=new TabControl{Dock=DockStyle.Fill};var chapterTab=new TabPage("Heading 1 chapters");chapterTab.Controls.Add(chapters);var settings=new TabPage("Settings and diagnostics");settings.Controls.Add(diagnostics);var options=new FlowLayoutPanel{Dock=DockStyle.Bottom,AutoSize=true};options.Controls.AddRange([Button("Check connection",()=>_ = cloud.CheckConnection()),Button("Disconnect / forget sign-in",()=>cloud.SignOut()),Button("Open diagnostics folder",()=>System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(directory){UseShellExecute=true}))]);settings.Controls.Add(options);tabs.TabPages.AddRange([chapterTab,settings]);layout.Controls.Add(tabs,0,7);
layout.Controls.Add(new Label{AutoSize=true,Text="Chapter prose is sent only after confirmation. Manuscript text and saved story data are never overwritten."},0,8);Controls.Add(layout);
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(880,820);DoubleBuffered=true;
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=1;site.Focus();}));header.Controls.Add(Button("Settings",()=>tabs.SelectedIndex=1));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([detect,analyse,cancel,review,contextAction,intentAction]);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.CheckConnection()),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.AddRange([chapterTab,settings]);layout.Controls.Add(tabs,0,6);
layout.Controls.Add(new Label{AutoSize=true,Dock=DockStyle.Fill,Padding=new(0,12,0,0),Text="Your words stay yours. Analysis uploads only chapters you confirm. Import needs a separate preview and confirmation."},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="";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, retains an encrypted capture for your reviewed import, 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"));
var menu=new ContextMenuStrip();menu.Items.Add("Open Companion",null,(_,_)=>Reveal());menu.Items.Add("Connect / Sign In",null,(_,_)=>{Reveal();site.Focus();});menu.Items.Add("Select Book",null,(_,_)=>{Reveal();books.Focus();});
var detectMenu=menu.Items.Add("Detect Chapters",null,(_,_)=>Safe(()=>control.Detect(selected)));var analyseMenu=menu.Items.Add("Analyse Manuscript",null,(_,_)=>{Reveal();chapters.Focus();});var openMenu=menu.Items.Add("Open PlotDirector",null,(_,_)=>Safe(()=>Open("book")));menu.Items.Add("Connection Status",null,(_,_)=>Reveal());menu.Items.Add("Settings",null,(_,_)=>{Reveal();tabs.SelectedIndex=1;});menu.Items.Add("Exit",null,(_,_)=>Exit());
menu.Opening+=(_,_)=>{detectMenu.Enabled=Current!=null;analyseMenu.Enabled=Current?.Book>0;openMenu.Enabled=!string.IsNullOrWhiteSpace(cloud.Status().ServerUrl);};
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=1;});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();
}
private Button Button(string text,Action action){var button=new Button{Text=text,AutoSize=true};button.Click+=(_,_)=>Safe(action);return button;}
@ -76,15 +91,35 @@ internal sealed class CompanionWindow:Form
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;
status.Text="Active in Word: "+(docs.FirstOrDefault(item=>item.Active)?.Title??"no document")+" · Working document: "+(d?.Title??"none")+"\r\nWord: "+(d==null?"unavailable":"connected")+" · Server: "+server+" · Authentication: "+(server.StartsWith("unverified")&&state.Health?.Authentication=="verified"?"cached grant":state.Health?.Authentication??"signed-out")+"\r\n"+state.Status+" · AI: "+(state.Health?.Ai??"unknown")+"\r\nBook: "+(state.Books.FirstOrDefault(b=>b.BookId==d?.Book)?.Title??"not selected")+"\r\nLocation: "+(d==null?"No document":string.Join(" / ",new[]{d.ChapterTitle,d.SceneTitle}.Where(t=>t.Length>0)))+" · Snapshot words (approx.): "+(d?.Words?.ToString("N0")??"not read / stale");
progressText.Text=string.IsNullOrEmpty(error)?d?.Status??"Open Word or sign in independently.":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;cancel.Enabled=d!=null;bookButton.Enabled=d!=null&&state.Books.Length>0&&d.Job==Guid.Empty;review.Enabled=d?.Book>0;
SetText(status,CompanionPresentation.Connection(state.Health,DateTime.UtcNow)+" · "+(d==null?"Word not connected":"Word connected"));
SetText(nextStep,CompanionPresentation.Next(d!=null,d?.Book>0,d?.Chapters.Length??0,d!=null&&(d.Job!=Guid.Empty||d.Pending.Count>0)));
SetText(progressText,string.IsNullOrEmpty(error)?d?.Status??"Waiting for your manuscript.":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();}}
diagnostics.Text="PlotDirector Companion by Nick Beckley\r\n"+typeof(CompanionWindow).Assembly.GetName().Version+"\r\n"+state.Health?.Explanation+"\r\nManual chapter upload only. 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.";
var diagnosticText="PlotDirector Companion by Nick Beckley\r\n"+typeof(CompanionWindow).Assembly.GetName().Version+"\r\n"+state.Health?.Explanation+"\r\nManual chapter upload only. 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();}
}finally{refreshing=false;}
}
private static void SetText(Label label,string value){if(label.Text!=value)label.Text=value;}
private void OnPreferences(object sender,Microsoft.Win32.UserPreferenceChangedEventArgs e){if(IsHandleCreated&&!IsDisposed)BeginInvoke(new Action(ApplyTheme));}
private void ApplyTheme()
{
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();
}
private void Exit(){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){timer.Dispose();tray.Dispose();brand.Dispose();}base.Dispose(disposing);}
protected override void Dispose(bool disposing){if(disposing){Microsoft.Win32.SystemEvents.UserPreferenceChanged-=OnPreferences;timer.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);}

View File

@ -22,7 +22,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.Chapters=[];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){Cancel(d);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.";}
d.Revision=descriptor.Revision;d.Manuscript=descriptor.ManuscriptId;d.Title=descriptor.Title;d.RememberedBook=descriptor.RememberedBook;d.AssociationSite=descriptor.AssociationSite;d.Observed=DateTime.UtcNow;
}
}
@ -51,7 +51,7 @@ 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 doc in documents.Values.Where(d=>d.Instance==instance).ToArray())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);}}
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 void Detect(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Completed.Clear();doc.Status="Reading chapters in bounded Word batches…";doc.Progress=0;Queue(doc,new(){Kind="detect"});}}
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)
{
lock(gate){if(!documents.TryGetValue(session,out var doc))return;var state=cloud.Status();if(!cloud.Allows(state.AuthenticationContext,book))throw new InvalidOperationException("Sign in and select an authorised book.");Cancel(doc);doc.Book=book;doc.Authentication=state.AuthenticationContext;lastBook=book;lastAuthentication=doc.Authentication;doc.Status=remember?"Remember requested; save Word normally after confirmation.":"Book selected for this session.";
@ -81,13 +81,13 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
public async Task Tick(CancellationToken cancellation)
{
while(!cancellation.IsCancellationRequested){await Task.Delay(500,cancellation);lock(gate){var cloudState=cloud.Status();foreach(var doc in documents.Values){
if(doc.Authentication!=cloudState.AuthenticationContext){Cancel(doc);doc.Book=0;doc.Completed.Clear();doc.Authentication=cloudState.AuthenticationContext;}
if(doc.Authentication!=cloudState.AuthenticationContext){Cancel(doc);doc.Book=0;doc.Completed.Clear();doc.FailedChapters.Clear();doc.Authentication=cloudState.AuthenticationContext;}
if(doc.Book>0&&!cloud.Allows(doc.Authentication,doc.Book)){Cancel(doc);doc.Book=0;doc.Status="Book access is no longer verified. Reconnect and select an authorised book.";}
if(doc.Book==0&&DocumentBindingRestore(doc,cloudState)) {doc.Book=doc.RememberedBook!.Value;doc.Authentication=cloudState.AuthenticationContext;lastBook=doc.Book;lastAuthentication=doc.Authentication;}
if(doc.Job==Guid.Empty){if(doc.Pending.Count>0&&!documents.Values.Any(other=>other.Job!=Guid.Empty))Next(doc);continue;}var result=ai.Result(doc.Session);
if(result?.RequestId==doc.Job&&result.State is "complete" or "failed" or "cancelled"){
if(result.State=="complete"&&!string.IsNullOrEmpty(result.ReviewPath)){if(result.SourceRetained)doc.Retained++;if(doc.Completed.Count>=8192)doc.Completed.RemoveWhere(c=>c.Item1!=doc.Revision);doc.Completed.Add((doc.Revision,doc.Book,doc.Current!.Start));doc.ReviewPath=result.ReviewPath;}
else{doc.Failed++;if(doc.Errors.Count>=50)doc.Errors.RemoveAt(0);doc.Errors.Add(doc.Current!.Title+": "+(result.State=="complete"?"Server update required: no saved PWA review handoff was returned.":result.Message));}
if(result.State=="complete"&&!string.IsNullOrEmpty(result.ReviewPath)){if(result.SourceRetained)doc.Retained++;if(doc.Completed.Count>=8192)doc.Completed.RemoveWhere(c=>c.Item1!=doc.Revision);doc.Completed.Add((doc.Revision,doc.Book,doc.Current!.Start));doc.FailedChapters.Remove((doc.Revision,doc.Book,doc.Current.Start));doc.ReviewPath=result.ReviewPath;}
else{doc.Failed++;if(doc.FailedChapters.Count>=8192)doc.FailedChapters.Clear();doc.FailedChapters.Add((doc.Revision,doc.Book,doc.Current!.Start));if(doc.Errors.Count>=50)doc.Errors.RemoveAt(0);doc.Errors.Add(doc.Current!.Title+": "+(result.State=="complete"?"Server update required: no saved PWA review handoff was returned.":result.Message));}
doc.Done++;ai.Clear(doc.Session);Next(doc);
}else if(DateTime.UtcNow-doc.Started>TimeSpan.FromMinutes(7)){doc.Errors.Add("Chapter timed out; retry explicitly.");Cancel(doc);doc.Status="Chapter timed out. Prior suggestions are safe in PlotDirector.";}
}}}
@ -108,6 +108,6 @@ 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="Detect chapters to begin.",ReviewPath="";
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 List<string> Errors=[];
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=[];
public override string ToString()=>Title+(Active?" (active in Word)":"");
}

View File

@ -1 +1 @@
<Project><PropertyGroup><ApplicationVersion>1.0.0.11</ApplicationVersion></PropertyGroup></Project>
<Project><PropertyGroup><ApplicationVersion>1.0.0.12</ApplicationVersion></PropertyGroup></Project>

View File

@ -160,6 +160,13 @@ using(var stalledClient=new AgentLink(stalledName,Guid.NewGuid(),_=>true))
await Until(()=>timedOut,"unresponsive agent handshake times out off producer thread");
stalledClient.Dispose();await stalledClient.Completion.WaitAsync(TimeSpan.FromSeconds(5));
}
Check(!CompanionPresentation.Dark(null)&&!CompanionPresentation.Dark(false)&&CompanionPresentation.Dark(true),"theme policy follows Windows with accessible light fallback");
Check(CompanionPresentation.Connection(new(){Server="online",Authentication="verified",VerifiedUtc=DateTime.UtcNow},DateTime.UtcNow)=="Connected to PlotDirector","connection requires verified fresh health");
Check(CompanionPresentation.Connection(new(){Server="online",Authentication="verified",VerifiedUtc=DateTime.UtcNow.AddMinutes(-3)},DateTime.UtcNow)=="Connection needs checking","cached server success never produces stale green state");
Check(CompanionPresentation.Connection(new(){Authentication="expired"},DateTime.UtcNow)=="Sign in again","expired sign-in has actionable explanation");
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");
await AnalysisTests.Run(Check);
await ChapterAiTests.Run(Check);
await WorkflowTests.Run(Check);

View File

@ -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.11")]
[assembly: AssemblyFileVersion("1.0.0.11")]
[assembly: AssemblyVersion("1.0.0.12")]
[assembly: AssemblyFileVersion("1.0.0.12")]
[assembly: ComVisible(false)]