Complete live session coordination, scoped SignalR updates and tray qualification handover
This commit is contained in:
parent
24363e683c
commit
18688fed3a
78
Docs/WordCompanion/2026-11-05-tray-companion.md
Normal file
78
Docs/WordCompanion/2026-11-05-tray-companion.md
Normal file
@ -0,0 +1,78 @@
|
||||
# Windows Tray Companion and Word adapter
|
||||
|
||||
## Result
|
||||
|
||||
Developer version **1.0.0.10** implements the requested direction on the existing shared branch, starting from recovery **b7f1fbc** / tested 1.0.0.9. Word owns manuscript access, the existing .NET 10 agent owns the tray/control centre and orchestration, PlotDirector's existing chapter-analysis service owns narrative interpretation, and the PWA owns scene review and Context/Intent.
|
||||
|
||||
This is a source/build/integration delivery, **not native Windows acceptance**. Atlas can compile the Windows Forms target but cannot run tray activation, Office COM, the signed VSTO build/install or Word performance trials. [One Windows procedure](../../PlotDirector.NativeCompanion/WindowsValidation/Tray-Companion.md) covers update, explicit install and qualification without changing Visual Studio.
|
||||
|
||||
## Implemented milestones
|
||||
|
||||
| Milestone | Implementation |
|
||||
|---|---|
|
||||
| A — adapter and tray | Word ribbon has only local communication status and Open Companion. Old analysis/connect/settings/book/review native-dialog sources are removed. The existing agent adds a `net10.0-windows` WinExe target, per-interactive-user singleton, protected activation pipe, notification icon/menu, one reusable DPI-aware window, hide/reopen and explicit Exit/resume. No second agent or new UI framework. |
|
||||
| B — control workflow | Browser-approved authentication, authorised book choices, optional consented existing document-association metadata, active-versus-working document selection, chapter selection, cancellation, diagnostics and recovery are in the tray. Documents and commands remain isolated by Word instance, live document session and revision. |
|
||||
| C — chapter AI and review | Explicit local Heading 1 detection, selected chapter extraction and consented chapter uploads use existing IPC and `IManuscriptStructureAnalysisService`. AI titles, summaries, confidence and exact paragraph-to-Word positions reach durable personal review suggestions. Batches continue after individual failures, retaining successful chapters; retries/resumption are explicit. The PWA opens after a successful batch. |
|
||||
| D — website | Authenticated/grant-bound native presence leases, checked book and saved-location membership, monotonic sequence/revision, 45-second expiry, 15-second heartbeat, coalesced scene changes, cookie-authenticated user-scoped SignalR invalidation and permission-checked read routes. A PWA badge distinguishes native presence from the independent legacy connector. No prose or file paths are broadcast. |
|
||||
| E — Context/Intent | Existing saved workspaces remain the renderer. A PWA Companion workspace selects an exact live session and offers explicit Follow. Manual navigation pauses it. Ordinary legacy Office.js live following remains intact; pinned native views do not subscribe to the legacy latest-connection route. Context/Intent remain available without Word. Explicit scene navigation is separately scoped, antiforgery-protected and delivered once to the matching Word session/revision. |
|
||||
| F — qualification | Managed/Windows-target compilation, focused native/server/HTTP/WebSocket/browser checks, SQL persistence regression and existing safe package-script checks. Native-only acceptance is explicitly outstanding. |
|
||||
|
||||
## Architecture and communication
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
W[Word VSTO: STA scheduler and bounded COM] <-->|tray-adapter-v1: commands and value fragments| T[Existing agent: Windows tray control centre]
|
||||
T -->|browser-approved bearer HTTPS| S[PlotDirector native API]
|
||||
S --> A[Existing chapter AI service and configured provider]
|
||||
S --> R[Personal review suggestions via Dapper / stored procedure]
|
||||
S -->|account-scoped invalidation only| H[Native presence SignalR hub]
|
||||
H --> P[PlotDirector PWA]
|
||||
P -->|permission-checked session reads| S
|
||||
P --> C[Existing Context / Intent renderers]
|
||||
P -->|explicit scoped navigation POST| S
|
||||
S -->|next exact-session heartbeat response| T
|
||||
```
|
||||
|
||||
No HTTP, authentication, AI, scene parsing, computational comparisons or synchronization scheduling is added to Word. No COM object crosses IPC or a worker boundary. The adapter retains document lifecycle, selection observation, bounded range/marker access and optional metadata writes. A source search/syntax gate supplements, rather than replaces, real Office qualification.
|
||||
|
||||
The new optional `tray-adapter-v1` capability protects older native clients: the tray coordinator observes only capable peers. Core v1 IPC and existing AI/workflow capabilities remain compatible. Office.js manifests, controllers, hub routes and onboarding are retained.
|
||||
|
||||
Word polls its lightweight observed position/length/saved-state through the existing scheduler, but **does not continuously rescan prose**. Detect Chapters is explicit; extraction is also explicit for selected AI chapters. Each extraction batch remains at most four 2,048-character fragments with a cooperative ~20ms target and yields between batches. An individual slow COM call cannot be preempted. Save never waits for IPC/AI and is never cancelled by the Companion.
|
||||
|
||||
## Original workflow evidence and preservation
|
||||
|
||||
The original scan in `word-companion-host.js` (around `isFrontMatterHeading` / paragraph scan) detects built-in Heading 1, excludes leading title/copyright/dedication/contents/acknowledgements/about-author headings, preserves paragraph maps and submits chapter text to the existing onboarding chapter service. `OnboardingService.AnalyseApprovedChaptersAsync` invokes `IManuscriptStructureAnalysisService.AnalyseChapterAsync`; that service uses `Chapter-Structure-Prompt-V2.md`, configured `ChapterStructureModel`, existing parsing/repair and `ChapterStructureValidator`.
|
||||
|
||||
The tray carries the leading front-matter exclusions forward. Heading 1 and existing chapter markers delimit its chapter list; body paragraphs merely saying “Chapter 99” do not create or truncate chapters. Chapter ranges are recomputed from actual accepted chapter boundaries. Headings are excluded from narrative paragraphs supplied to the existing AI map. Local scene heuristics/markers are not presented as AI discoveries or substituted for narrative interpretation.
|
||||
|
||||
`NativeChapterMapping` now preserves `StructuralSummary` independently of `Reason`, along with AI title/confidence and paragraph-mapped positions. No provider/model/key/server address is hard-coded. Existing subscription, user security-stamp, book access, provider limits and chapter validation remain in force.
|
||||
|
||||
## Safety, retry and persistence
|
||||
|
||||
- Upload requires an explicit author selection and cost/prose confirmation in the tray. Opening Word, connecting, selecting a book, detecting chapters and presence updates never submit prose to AI.
|
||||
- Only selected chapter prose is extracted/sent. Agent successful-result fingerprints avoid repeat uploads of unchanged captured chapter content in the same authenticated process (bounded to 64 entries / 8,192 scenes). A server content hash scoped to author/book/manuscript avoids a second provider call after restart. Request IDs still protect ordinary duplicate submissions.
|
||||
- Cancellation stops remaining chapter commands/extraction and requests active server cancellation. Successful chapters are retained independently. Retry reselects failed/unfinished chapters; completed selections are skipped until explicit detection refreshes them. After restart/reopen, detect/select again; durable results are reused. There is no silent restart upload or automatic paid retry.
|
||||
- Network failures can leave a provider outcome unknown. Do not promise exactly-once provider charging across crashes before persistence. Each chapter keeps the established 120,000-character and provider limits; oversized chapters fail individually rather than uploading a novel in one request.
|
||||
- Review rows contain suggestions and decisions, not full manuscript prose or keys. Migration **231** adds `NativeChapterReviews` and `NativeChapterReview_Access`. All application access uses Dapper/stored procedures. Results are personal to the authenticated author, with current book access checked on every read/edit. Unique author/book/manuscript/content hash prevents duplicate review records; decision versions reject stale-tab overwrites. Expired reviews are inaccessible after 30 days and purged for that user on subsequent saves. No FK blocks existing project/book deletion/restore; access is revalidated and expired suggestion retention is independent of canonical story data.
|
||||
- The PWA can approve/edit/reject scene titles/summaries. **Saving review decisions does not import, rewrite or overwrite canonical story data.** Transfer into the established import/build/marker/save-acknowledgement pipeline remains a separate outstanding integration. Existing importing remains usable. Nothing is automatically inserted into Word.
|
||||
- Remember uses the recovery's single atomic association property and existing GUID. It requires consent, marks metadata modified, does not save, and confers no server authority. Read-only/property errors return to the tray. Saved associations are checked against the current site and accessible books after sign-in.
|
||||
|
||||
## Presence, navigation and multi-screen behavior
|
||||
|
||||
Persistent manuscript GUID, live session ID, Word instance ID and authenticated grant are distinct. The server never accepts a payload user ID. Native bearer grants are fingerprinted into a server claim; an old grant cannot replace another grant's live lease. Stale sequence/revision, foreign book and mismatched scene/chapter IDs are rejected. Leases expire after 45 seconds or grant expiry; explicit sign-out/site change revokes the prior grant's presence and late heartbeats cannot revive it.
|
||||
|
||||
Changed saved scene/chapter/active state is coalesced by the agent's 500ms loop; unchanged positions use only a 15-second heartbeat. The PWA gets user-scoped **invalidation**, then rereads authorised state. Visible pages poll at 15 seconds as recovery/expiry fallback. Hidden pages do not poll; reconnect/visibility return refreshes them. No presence event contains prose, diagnostics or filesystem paths. When the tray remains signed in after Word closes it can report Companion connected / Word unavailable against the last selected book.
|
||||
|
||||
Native follow is explicitly selected per PWA window/session. There is no automatic routing to the latest Word instance. Manual scene selection pauses following; ordinary tabs remain usable. Saved IDs from Word are verified inside the selected book. Unmarked prose/AI suggestions do not become trusted canonical scene IDs: without saved markers, these views show book-level state and manual navigation. This is an important boundary, not missing AI context invented locally.
|
||||
|
||||
Explicit Locate in Word requires the matching live manuscript and observed revision. It queues one bounded latest navigation command for that exact authenticated lease, delivered once on its heartbeat; Word selects a zero-length range without changing text. Follow updates do not issue navigation commands. A cached review from an older observed revision remains reviewable but may have navigation disabled; tray chapter navigation is still available. Same-length edits in an already dirty document remain subject to the recovery's explicit-refresh limitation, so captured suggestions are not a complete live edit journal.
|
||||
|
||||
The adapter/tray reconnect lease also has an explicit replacement guard: a late disconnect cannot remove sessions belonging to a replacement pipe lease. Per-instance queues are bounded to 16; chapter/scene result limits and existing IPC/mailbox/Word scheduler bounds remain. Exit pauses automatic relaunch until Open Companion is explicitly used.
|
||||
|
||||
## Verification and handover
|
||||
|
||||
Exact evidence is under `Evidence/2026-11-05-tray/`; deployment outcome is appended below once verified. Windows Forms can be cross-compiled on Atlas with Windows targeting enabled, but **not executed** here. The VSTO host is syntax-checked only on Atlas; it requires Office-equipped Windows MSBuild/signing for acceptance.
|
||||
|
||||
The recovery's word-count algorithm is retained: an **approximate whitespace-based main-story snapshot count**, shown as such. It is not Word's exact statistics (footnotes, punctuation/hyphenation and other stories may differ). Edits mark the count stale; explicit detection refreshes it. No full-document Word statistics call is added to block the UI.
|
||||
|
||||
Remaining native qualification includes tray singleton activation/Exit, actual Word launch and shadow-copy resolution, ribbon callbacks, signed manifests/per-user installation/rollback, read-only metadata, DPI/resizing/focus, three-document behavior, actual narrative AI-to-PWA review and measured 155k/190k/250k typing/scroll/save/close responsiveness. The single [Windows checklist](../../PlotDirector.NativeCompanion/WindowsValidation/Tray-Companion.md) includes these and the existing measurement harness. No Windows laptop, installed add-in, Visual Studio configuration or Production system was modified from Atlas.
|
||||
@ -56,7 +56,7 @@ 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);
|
||||
instance = hello.WordInstanceId; sessions.Attach(instance,lease);if(trayAdapter)control?.Attach(instance,lease);
|
||||
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability},cancellation);
|
||||
log?.Invoke("peer-connected");
|
||||
while (!cancellation.IsCancellationRequested)
|
||||
@ -68,14 +68,14 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action<st
|
||||
foreach(var metric in message.Metrics)timings.Record(metric);
|
||||
var watch = Stopwatch.StartNew();
|
||||
var answer = sessions.Apply(lease,message);
|
||||
if(control!=null&&trayAdapter)answer=control.Exchange(instance,message,answer);
|
||||
if(control!=null&&trayAdapter)answer=control.Exchange(instance,message,answer,lease);
|
||||
await FrameCodec.WriteAsync(pipe,answer,cancellation).WaitAsync(TimeSpan.FromSeconds(3),cancellation);
|
||||
log?.Invoke($"operation={message.Kind} status={answer.Status} elapsedMs={watch.Elapsed.TotalMilliseconds:F2} sessions={sessions.SessionCount} queueDepth={message.QueueDepth} wordInstance={instance:N} session={message.SessionId:N} correlation={message.CorrelationId:N}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or OperationCanceledException or TimeoutException or UnauthorizedAccessException or System.Runtime.Serialization.SerializationException)
|
||||
{ log?.Invoke("peer-disconnected reason="+ex.GetType().Name); }
|
||||
finally { Interlocked.Decrement(ref activePeers); if(instance != Guid.Empty){sessions.Detach(instance,lease);control?.Disconnected(instance);} log?.Invoke("timing-summary="+System.Text.Json.JsonSerializer.Serialize(timings.Snapshot())); }
|
||||
finally { Interlocked.Decrement(ref activePeers); if(instance != Guid.Empty){sessions.Detach(instance,lease);control?.Disconnected(instance,lease);} log?.Invoke("timing-summary="+System.Text.Json.JsonSerializer.Serialize(timings.Snapshot())); }
|
||||
}
|
||||
}
|
||||
private static async Task<Message> ReadWithTimeout(Stream pipe,CancellationToken cancellation,TimeSpan duration)
|
||||
|
||||
@ -6,6 +6,8 @@ namespace PlotDirector.Companion.Agent;
|
||||
|
||||
public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai = null,DocumentWorkspaceWork? workspace = null)
|
||||
{
|
||||
// Same leading front-matter exclusions as word-companion-host.js's established scan.
|
||||
private static readonly HashSet<string> FrontMatter=new(StringComparer.OrdinalIgnoreCase){"title page","copyright","dedication","contents","table of contents","acknowledgements","acknowledgments","about the author"};
|
||||
private readonly object gate = new();
|
||||
private readonly Dictionary<Guid, WordInstance> instances = [];
|
||||
private const int MaxSnapshotCharacters = 16 * 1024 * 1024;
|
||||
@ -156,7 +158,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
|
||||
public StructureSuggestion[] Chapters(Guid instance,Guid session)
|
||||
{
|
||||
lock(gate){var document=instances.GetValueOrDefault(instance)?.Documents.GetValueOrDefault(session);var analysis=document?.Analysis;if(analysis==null)return [];
|
||||
var chapters=Enumerable.Range(0,(analysis.Count+39)/40).SelectMany(i=>analysis.Page(i*40).Items).Where(s=>s.Kind=="Chapter"&&(s.Heading1||s.Origin=="Existing marker")).OrderBy(c=>c.Start).ToArray();
|
||||
var chapters=Enumerable.Range(0,(analysis.Count+39)/40).SelectMany(i=>analysis.Page(i*40).Items).Where(s=>s.Kind=="Chapter"&&(s.Heading1||s.Origin=="Existing marker")).OrderBy(c=>c.Start).SkipWhile(c=>FrontMatter.Contains(c.Title.Trim())).ToArray();
|
||||
return chapters.Select((c,i)=>new StructureSuggestion{Kind="Chapter",Heading1=c.Heading1,Start=c.Start,End=i+1<chapters.Length?chapters[i+1].Start:document!.StructureEnd,Title=c.Title,Origin=c.Origin,Reason=c.Reason,Confidence=c.Confidence}).ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
@ -75,7 +75,8 @@ internal sealed class CompanionWindow:Form
|
||||
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;
|
||||
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: "+(state.Health?.Server??"unknown")+" · Authentication: "+(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");
|
||||
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;cancel.Enabled=d!=null;bookButton.Enabled=d!=null&&state.Books.Length>0&&d.Job==Guid.Empty;review.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();}}
|
||||
|
||||
@ -4,22 +4,25 @@ namespace PlotDirector.Companion.Agent;
|
||||
// One control centre in the existing agent. Exact-session commands only; no COM or UI objects.
|
||||
public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,ChapterAiWork ai)
|
||||
{
|
||||
private readonly Guid agentInstance=Guid.NewGuid(),agentSession=Guid.NewGuid();private int lastBook;private Guid lastAuthentication;private long agentSequence;
|
||||
private readonly Guid agentInstance=Guid.NewGuid(),agentSession=Guid.NewGuid();private int lastBook;private Guid lastAuthentication;private long agentSequence;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,Queue<AdapterCommand>> commands=[];private readonly Dictionary<Guid,Guid> leases=[];
|
||||
public event Action? OpenRequested;
|
||||
public TrayDocument[] Documents {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).ToArray();}}
|
||||
public Message Exchange(Guid instance,Message request,Message answer)
|
||||
public void Attach(Guid instance,Guid lease){lock(gate){Disconnected(instance);leases[instance]=lease;}}
|
||||
public Message Exchange(Guid instance,Message request,Message answer,Guid lease=default)
|
||||
{
|
||||
lock(gate)
|
||||
{
|
||||
if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return answer;
|
||||
if(answer.Status is "wrong-instance" or "stale-sequence" or "stale-revision" or "invalid-documents" or "foreign-session-identity" or "unknown-session")return answer;
|
||||
if(request.Kind=="tray-open")OpenRequested?.Invoke();
|
||||
if(request.Kind is "document" or "reconcile"){
|
||||
if(request.Kind=="reconcile")foreach(var prior in documents.Values.Where(d=>d.Instance==instance).ToArray())Remove(prior.Session);
|
||||
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.Status="Document changed. Detect chapters to refresh this snapshot.";}
|
||||
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.";}
|
||||
d.Revision=descriptor.Revision;d.Manuscript=descriptor.ManuscriptId;d.Title=descriptor.Title;d.RememberedBook=descriptor.RememberedBook;d.AssociationSite=descriptor.AssociationSite;d.Observed=DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
@ -30,6 +33,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
if(request.Kind=="active"){foreach(var d in documents.Values)d.Active=false;doc.Active=true;}
|
||||
if(request.Kind=="selection"||request.Kind=="snapshot-end"){doc.ChapterId=answer.ChapterId;doc.SceneId=answer.SceneId;doc.ChapterTitle=answer.ChapterTitle;doc.SceneTitle=answer.SceneTitle;}
|
||||
if(answer.WordCount.HasValue)doc.Words=answer.WordCount;
|
||||
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);}
|
||||
@ -43,7 +47,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
return answer;
|
||||
}
|
||||
}
|
||||
public void Disconnected(Guid instance){lock(gate){foreach(var doc in documents.Values.Where(d=>d.Instance==instance).ToArray())Remove(doc.Session);commands.Remove(instance);}}
|
||||
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"});}}
|
||||
@ -90,17 +94,17 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
public void OpenPage(Guid session,string page){lock(gate){if(!documents.TryGetValue(session,out var doc)||!cloud.Allows(doc.Authentication,doc.Book))throw new InvalidOperationException("Select an authorised book first.");cloud.OpenCompanionPage(page=="review"&&!string.IsNullOrEmpty(doc.ReviewPath)?doc.ReviewPath:$"/native-companion/workspace?bookId={doc.Book}&instanceId={doc.Instance}&sessionId={doc.Session}&view={page}",doc.Authentication);}}
|
||||
public async Task Heartbeat(CancellationToken cancellation)
|
||||
{
|
||||
while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromSeconds(15),cancellation);var available=Documents.Where(d=>d.Book>0).ToArray();
|
||||
foreach(var doc in available){try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=Interlocked.Increment(ref doc.PresenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision&&reply.Navigation.Kind=="navigate")Queue(doc,reply.Navigation);}catch(Exception e)when(NetworkFailure(e)) {}}
|
||||
if(available.Length==0&&lastBook>0){try{await cloud.Presence(agentInstance,agentSession,new(){BookId=lastBook,Sequence=Interlocked.Increment(ref agentSequence),WordAvailable=false,DocumentTitle="No Word document"},lastAuthentication);}catch(Exception e)when(NetworkFailure(e)) {}}
|
||||
else await cloud.RemovePresence(agentInstance,agentSession);
|
||||
while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromMilliseconds(500),cancellation);var available=Documents.Where(d=>d.Book>0).ToArray();
|
||||
foreach(var doc in available){var key=$"{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=Interlocked.Increment(ref doc.PresenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision&&reply.Navigation.Kind=="navigate")Queue(doc,reply.Navigation);}catch(Exception e)when(NetworkFailure(e)) {}}
|
||||
if(available.Length==0&&lastBook>0&&DateTime.UtcNow-lastAgentPresence>=TimeSpan.FromSeconds(15)){lastAgentPresence=DateTime.UtcNow;agentOnlyPublished=true;try{await cloud.Presence(agentInstance,agentSession,new(){BookId=lastBook,Sequence=Interlocked.Increment(ref agentSequence),WordAvailable=false,DocumentTitle="No Word document"},lastAuthentication);}catch(Exception e)when(NetworkFailure(e)) {}}
|
||||
else if(available.Length>0&&agentOnlyPublished){agentOnlyPublished=false;await cloud.RemovePresence(agentInstance,agentSession);}
|
||||
}
|
||||
}
|
||||
private static bool NetworkFailure(Exception e)=>e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or System.Text.Json.JsonException;
|
||||
}
|
||||
public sealed class TrayDocument
|
||||
{
|
||||
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 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 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 override string ToString()=>Title+(Active?" (active in Word)":"");
|
||||
|
||||
@ -1,3 +1,7 @@
|
||||
# Current architecture: Windows tray Companion (1.0.0.10)
|
||||
|
||||
Word now exposes only local status and Open Companion. Use the existing agent’s tray control centre and PlotDirector PWA for analysis/review, Context and Intent. [Implementation and limitations](../Docs/WordCompanion/2026-11-05-tray-companion.md) · [one Windows update/install/qualification procedure](WindowsValidation/Tray-Companion.md). Earlier phase notes below are historical and describe superseded native dialogs.
|
||||
|
||||
# Current developer build: Phase 3.5
|
||||
|
||||
Version **1.0.0.6** adds per-document book binding, verified connection status, saved Context/Intent and read-only import preview. See [qualification](WindowsValidation/Phase35-Integration.md) and [implementation report](../Docs/WordCompanion/2026-11-05-phase35-integration.md). Native import commit and native live SignalR following remain unavailable.
|
||||
|
||||
@ -6,7 +6,7 @@ internal static class TrayTests
|
||||
{
|
||||
public static async Task Run(Action<bool,string> check)
|
||||
{
|
||||
using var cloud=new CloudGateway(new Server(),_=>{});cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Books.Length>0);
|
||||
var handler=new Server();using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Books.Length>0);
|
||||
using var ai=new ChapterAiWork(cloud);var sessions=new SessionManager(cloud,ai);var control=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var lease=Guid.NewGuid();sessions.Attach(instance,lease);long sequence=0;
|
||||
var first=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Title="One",Revision=1};var second=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Title="Two",Revision=1};
|
||||
Message Apply(Message m){m.WordInstanceId=instance;m.Sequence=++sequence;return control.Exchange(instance,m,sessions.Apply(lease,m));}
|
||||
@ -18,16 +18,27 @@ internal static class TrayTests
|
||||
Apply(new(){Kind="snapshot-fragment",SessionId=first.SessionId,Revision=1,SnapshotId=snapshot,Fragment=new(){Start=20,End=30,ParagraphIndex=3,OutlineLevel=1,Text="Closing\r",CompletesParagraph=true}});
|
||||
Apply(new(){Kind="snapshot-end",SessionId=first.SessionId,Revision=1,SnapshotId=snapshot});
|
||||
check(control.Documents.Single(d=>d.Session==first.SessionId).Chapters.Length==2&&control.Documents.Single(d=>d.Session==first.SessionId).Chapters[0].End==20&&control.Documents.Single(d=>d.Session==second.SessionId).Chapters.Length==0,"tray chapter list uses Heading 1 not paragraph-name heuristics and remains document-isolated");
|
||||
var frontSnapshot=Guid.NewGuid();Apply(new(){Kind="snapshot-begin",SessionId=second.SessionId,Revision=1,SnapshotId=frontSnapshot,End=20,RequestAnalysis=true});
|
||||
Apply(new(){Kind="snapshot-fragment",SessionId=second.SessionId,Revision=1,SnapshotId=frontSnapshot,Fragment=new(){Start=0,End=10,ParagraphIndex=1,OutlineLevel=1,Text="Contents\r",CompletesParagraph=true}});
|
||||
Apply(new(){Kind="snapshot-fragment",SessionId=second.SessionId,Revision=1,SnapshotId=frontSnapshot,Fragment=new(){Start=10,End=20,ParagraphIndex=2,OutlineLevel=1,Text="Opening\r",CompletesParagraph=true}});
|
||||
Apply(new(){Kind="snapshot-end",SessionId=second.SessionId,Revision=1,SnapshotId=frontSnapshot});check(control.Documents.Single(d=>d.Session==second.SessionId).Chapters.Single().Start==10,"tray preserves original leading front-matter exclusions before Heading 1 chapters");
|
||||
control.SelectBook(first.SessionId,3,false);check(control.Documents.Single(d=>d.Session==first.SessionId).Book==3&&control.Documents.Single(d=>d.Session==second.SessionId).Book==0,"tray book association is explicit and isolated");
|
||||
bool refused=false;try{control.SelectBook(second.SessionId,999,false);}catch(InvalidOperationException){refused=true;}check(refused,"tray refuses unauthorised books before Word metadata command");
|
||||
using(var heartbeatStop=new CancellationTokenSource()){
|
||||
var heartbeat=control.Heartbeat(heartbeatStop.Token);await Until(()=>handler.Heartbeats==1);await Task.Delay(600);
|
||||
check(handler.Heartbeats==1,"stationary scene does not repeatedly post presence between heartbeats");control.Documents.Single(d=>d.Session==first.SessionId).SceneId=20;await Until(()=>handler.Heartbeats==2);
|
||||
check(true,"changed scene posts lightweight presence before the periodic heartbeat");heartbeatStop.Cancel();try{await heartbeat;}catch(OperationCanceledException){}
|
||||
}
|
||||
control.Analyse(first.SessionId,[0,20]);check(control.Documents.Single(d=>d.Session==first.SessionId).Job!=Guid.Empty,"explicit tray selection starts chapter-only extraction queue");
|
||||
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");
|
||||
control.Disconnected(instance);check(control.Documents.Length==0,"pipe disconnect removes exact Word instance sessions and pending control work");
|
||||
var replacementLease=Guid.NewGuid();control.Attach(instance,replacementLease);Apply(new(){Kind="document",Documents=[first]});control.Disconnected(instance,lease);check(control.Documents.Length==1,"late disconnect cannot remove a replacement tray lease");
|
||||
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);}
|
||||
private sealed class Server:HttpMessageHandler
|
||||
{
|
||||
public int Heartbeats;
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
|
||||
{object body=request.RequestUri!.AbsolutePath.Split('/').Last() switch{"pair"=>new{code=new string('A',24)},"token"=>new{accessToken="test"},"books"=>new[]{new CompanionBook{BookId=3,Title="Allowed book"}},_=>new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow}};return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(body)});}
|
||||
{if(request.Method==HttpMethod.Post&&request.RequestUri!.AbsolutePath.EndsWith("/presence"))Interlocked.Increment(ref Heartbeats);object body=request.RequestUri!.AbsolutePath.Split('/').Last() switch{"pair"=>new{code=new string('A',24)},"token"=>new{accessToken="test"},"books"=>new[]{new CompanionBook{BookId=3,Title="Allowed book"}},_=>new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow}};return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=JsonContent.Create(body)});}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
Current **1.0.0.10 tray architecture**: use [Tray-Companion.md](Tray-Companion.md). It supersedes the native-dialog qualification below while retaining the same Update/Install scripts and measurement harness.
|
||||
|
||||
Current developer version **1.0.0.6**: [Phase 3.5 integration checklist](Phase35-Integration.md). The original Phase 1 qualification below is historical; use the current checklist for implemented authentication, AI and saved workspace behaviour.
|
||||
|
||||
For current Phase 3 development, use [Phase3-AI.md](Phase3-AI.md). It provides a same-user, command-line update/build and explicit reversible per-user install workflow. A VM/separate profile, IDE launch or IDE repair is not required. The earlier disposable-profile guidance below is historical qualification advice, not a prerequisite for the authorised Phase 3 developer update.
|
||||
|
||||
@ -0,0 +1,43 @@
|
||||
# Windows qualification: tray Companion 1.0.0.10
|
||||
|
||||
This replaces the native dialogs with the existing agent's Windows tray UI. It is not Windows-accepted until the checks below pass. The source retains the 1.0.0.9 shadow-copy resolver, exact registered-DLL hash check, optional document association and installer/rollback repairs.
|
||||
|
||||
## One update/build and explicit install
|
||||
|
||||
In the existing repository on `codex/word-companion-native-phase1-20261104`:
|
||||
|
||||
```powershell
|
||||
# Bootstrap the updated script, preserving changes and refusing divergent history:
|
||||
if ((git branch --show-current).Trim() -ne 'codex/word-companion-native-phase1-20261104') { throw 'Wrong branch' }
|
||||
if (git status --porcelain=v1) { throw 'Preserve your local changes first' }
|
||||
git pull --ff-only
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Git update failed' }
|
||||
& .\PlotDirector.NativeCompanion\WindowsValidation\Update-WordCompanion.ps1
|
||||
```
|
||||
|
||||
Subsequent updates need only the Update command. It uses the configured tracking remote and existing Office MSBuild. It never launches Visual Studio or Installer, changes IDE configuration/workloads/PATH, unregisters the add-in, installs a runtime or runs **Clean**. It checks for .NET 10 **Windows Desktop** runtime, compiles/tests managed code, builds signed VSTO and publishes the existing agent's `net10.0-windows` target into the same complete package structure. Missing prerequisites stop with a diagnostic.
|
||||
|
||||
Preparation leaves the working installation unchanged. Close Word normally, then install the exact printed package:
|
||||
|
||||
```powershell
|
||||
& .\PlotDirector.NativeCompanion\WindowsValidation\Install-WordCompanion.ps1 -PackagePath '<printed Downloads package path>' -StopAgent
|
||||
```
|
||||
|
||||
The existing explicit per-user installer, exact-product ClickOnce handling, retained files and rollback are unchanged. It stops only the authorised user's Companion agent after Word is closed. To restore the previous registration, close Word and use the same script with `-Rollback -StopAgent`. Do not repair Visual Studio or disable VSTO security.
|
||||
|
||||
## Single qualification procedure
|
||||
|
||||
1. Record source SHA/version, Office build/bitness, Windows scaling and tools. Open Word. Ribbon must have **only Local Companion status and Open Companion**. It must not show Analyse, book, Context, Intent, Settings, Diagnostics or review dialogs.
|
||||
2. Click Open Companion. Verify one tray icon/process and one modeless control centre. Click repeatedly and launch the packaged agent EXE again: existing window should activate, without duplicate processes. Close hides the window; tray Open restores it. Exit stops the agent and pauses automatic relaunch; Open Companion explicitly resumes it. Verify Word remains usable throughout.
|
||||
3. Enter the Development HTTPS root; Connect / Sign In opens normal browser approval. Confirm displayed server/auth/AI states, sign-out, refusal, expiry, offline/recovery and an agent restart. No passwords/API keys/doc credentials should be requested or logged.
|
||||
4. Open three manuscripts. Use the working-document selector or **Use active Word document**, select different books, and switch repeatedly. Active-in-Word and the selected working document are distinguished. Optional Remember requires confirmation, writes only the existing metadata property, never saves, and is reauthorised after sign-in/reopen. Test a read-only document and a shadow-copied VSTO installation.
|
||||
5. Detect Chapters explicitly. Headings must use Word's built-in Heading 1 / outline level 1; existing PD chapter markers remain recognised. Body text saying “Chapter 99” must not split prose or truncate a chapter. The tray list must show full titles and select one/several/all. Double-click a chapter to navigate without edits. Detection reads locally in bounded batches; cursor movement/typing must not trigger full prose rescans. Displayed word count is the recovery's **approximate main-story snapshot count**, not Word's exact statistics. Edits mark it stale until another explicit detection.
|
||||
6. Start with a small synthetic multi-scene chapter. Check chapters and explicitly confirm upload/costs. AI must identify narrative scenes and generate titles **and summaries** via the existing server service. Progress identifies each chapter. Cancel during extraction and during AI; retry only failed/unfinished chapters explicitly. Successful earlier chapters remain in the PWA even if later chapters fail. Re-detection/retry of unchanged captured text should avoid another upload while the agent cache remains; after restart server content deduplication should avoid a provider call.
|
||||
7. Completed batches open the correct book's PWA Companion workspace. Review each chapter's scene titles/summaries, approve/edit/reject and Save decisions. Verify antiforgery, stale-tab conflict and foreign-book denial. These are review suggestions only: **nothing is imported and no canonical scene or Word prose is overwritten**. Import remains the established separate workflow; decisions are not yet transferred to a core import build.
|
||||
8. In PWA Context/Intent choose the exact Word session and explicitly enable Follow. Verify saved markers resolve only inside the authorised book. Manual scene selection inside the workspace pauses following; it must not snap back. Unmarked prose/AI suggestions do not invent canonical scene IDs. With Word closed, saved Context/Intent still work and a signed-in tray may report Word unavailable. Kill the agent/network: presence must expire within 45 seconds (plus up to one 15-second visible-page poll). Sign-out revokes late heartbeats. Check multiple browser screens/sessions independently.
|
||||
9. On a fresh matching review, explicitly Locate a suggested scene in Word, choosing its exact live session. It should navigate once, with no selection-feedback loop. Older observed revisions must refuse navigation. An unchanged cached review may remain reviewable while its original revision is no longer navigable; local tray chapter navigation remains available.
|
||||
10. Repeat long-document trials (155k, 190k and 250k words), many short/repeated paragraphs, rapid cursor movement, continuous typing, scrolling, save/close/cancelled-close, three documents and agent termination. Measure COM/batch/tick latency, typing/scroll/save responsiveness, CPU/memory/queues using the existing [measurement harness](README.md). A single COM call cannot be preempted; do not substitute portable tests for these measurements.
|
||||
|
||||
## Outstanding boundaries
|
||||
|
||||
Atlas can compile the Windows Forms target but cannot execute Windows Forms, Office COM, VSTO signing/installation or tray activation. The old same-length edits in an already dirty document limitation remains; explicit Detect rereads content and invalidates prior completion choices. Counts are snapshot approximations. Native review does not yet perform canonical import/marker-write/save acknowledgement. No installer distribution, automatic updates, Production changes or laptop operations are included.
|
||||
@ -52,18 +52,19 @@ internal static class NativeCompanionHttpTests
|
||||
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options=>{options.LoginPath="/fixture-login";options.Cookie.SecurePolicy=Microsoft.AspNetCore.Http.CookieSecurePolicy.None;})
|
||||
.AddScheme<AuthenticationSchemeOptions,DesktopAuthentication>(DesktopPairing.Scheme,_=>{});
|
||||
builder.Services.AddRateLimiter(o=>o.AddPolicy("native-pair",_=>System.Threading.RateLimiting.RateLimitPartition.GetNoLimiter("fixture")));
|
||||
builder.Services.AddAuthorization();builder.Services.AddControllersWithViews().AddApplicationPart(typeof(NativeCompanionController).Assembly);
|
||||
builder.Services.AddSignalR();builder.Services.AddAuthorization();builder.Services.AddControllersWithViews().AddApplicationPart(typeof(NativeCompanionController).Assembly);
|
||||
builder.Services.AddSingleton<IManuscriptStructureAnalysisService>(new ManuscriptStructureAnalysisService(new FakeStoryPromptRepository(),new FakeStoryPromptVersionService(),provider,new ChapterStructureValidator(),NullLogger<ManuscriptStructureAnalysisService>.Instance));
|
||||
await using var app=builder.Build();app.UseRouting();app.UseRateLimiter();app.UseAuthentication();app.UseAuthorization();
|
||||
app.MapGet("/fixture-login",async (Microsoft.AspNetCore.Http.HttpContext context)=>{await context.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity([new(ClaimTypes.NameIdentifier,"7"),new("PlotLine.SecurityStamp",user.SecurityStamp.ToString())],CookieAuthenticationDefaults.AuthenticationScheme)));return "Fixture login";});
|
||||
app.MapGet("/fixture-antiforgery",(IAntiforgery xsrf,Microsoft.AspNetCore.Http.HttpContext context)=>xsrf.GetAndStoreTokens(context).RequestToken);
|
||||
app.MapControllers();await app.StartAsync();
|
||||
app.MapHub<PlotLine.Hubs.NativeCompanionPresenceHub>("/hubs/native-companion");app.MapControllers();await app.StartAsync();
|
||||
try
|
||||
{
|
||||
var address=app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single();
|
||||
using var browser=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false}){BaseAddress=new Uri(address)};
|
||||
using var browserHandler=new HttpClientHandler{AllowAutoRedirect=false};using var browser=new HttpClient(browserHandler){BaseAddress=new Uri(address)};
|
||||
using var agent=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false,UseCookies=false}){BaseAddress=new Uri(address)};
|
||||
Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Native API is not anonymous");
|
||||
var anonymousHub=(await agent.PostAsync("/hubs/native-companion/negotiate?negotiateVersion=1",null)).StatusCode;Check(anonymousHub is HttpStatusCode.Unauthorized or HttpStatusCode.Redirect,"Anonymous native hub subscription refused");
|
||||
var verifier=new string('d',64);var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier)));
|
||||
var oversized=await agent.PostAsJsonAsync("/api/native-companion/pair",new{challenge=new string('A',64),padding=new string('x',5000)});Check(!oversized.IsSuccessStatusCode,"Oversized pairing bodies are refused before pairing state creation");
|
||||
var paired=await agent.PostAsJsonAsync("/api/native-companion/pair",new{challenge});Check(paired.IsSuccessStatusCode,"Pairing start accepts verifier challenge");
|
||||
@ -86,8 +87,15 @@ internal static class NativeCompanionHttpTests
|
||||
Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).IsSuccessStatusCode&&provider.Prompts.Count==1,"HTTP retry reuses successful provider result");
|
||||
Check(result!.ReviewPath.StartsWith("/native-companion/reviews/")&&!string.IsNullOrWhiteSpace(result.Scenes.Single().Summary),"AI summary is preserved and saved PWA review handoff returned");
|
||||
request.RequestId=Guid.NewGuid();var reused=await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request);Check(reused.IsSuccessStatusCode&&provider.Prompts.Count==1,"Unchanged chapter content reuses durable suggestion across new request identifiers");
|
||||
var negotiation=await browser.PostAsync("/hubs/native-companion/negotiate?negotiateVersion=1",null);Check(negotiation.IsSuccessStatusCode,"Native presence hub requires normal browser authentication and negotiates after sign-in");
|
||||
var connectionToken=(await negotiation.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("connectionToken").GetString();
|
||||
using var socket=new System.Net.WebSockets.ClientWebSocket();socket.Options.Cookies=browserHandler.CookieContainer;using var socketTimeout=new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
||||
await socket.ConnectAsync(new Uri(address.Replace("http://","ws://")+"/hubs/native-companion?id="+Uri.EscapeDataString(connectionToken!)),socketTimeout.Token);
|
||||
await socket.SendAsync(Encoding.UTF8.GetBytes("{\"protocol\":\"json\",\"version\":1}\u001e"),System.Net.WebSockets.WebSocketMessageType.Text,true,socketTimeout.Token);
|
||||
var socketBuffer=new byte[4096];await socket.ReceiveAsync(socketBuffer,socketTimeout.Token);
|
||||
var instance=Guid.NewGuid();var document=Guid.NewGuid();var live=new NativePresence{BookId=3,ManuscriptId=request.ManuscriptId,Sequence=1,DocumentTitle="Synthetic manuscript"};
|
||||
Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/presence",live)).IsSuccessStatusCode,"Actual bearer-scoped presence accepted");
|
||||
var notification=await socket.ReceiveAsync(socketBuffer,socketTimeout.Token);Check(Encoding.UTF8.GetString(socketBuffer,0,notification.Count).Contains("NativePresenceChanged"),"Authenticated native hub pushes only invalidation, not prose or navigation feedback");socket.Abort();
|
||||
var leases=await browser.GetFromJsonAsync<JsonElement[]>("/native-companion/presence?bookId=3");Check(leases?.Length==1,"Authenticated browser sees scoped native session without prose");
|
||||
Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/presence",live)).StatusCode==HttpStatusCode.Conflict,"Actual HTTP stale sequence refused");
|
||||
Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(new Dictionary<string,string>{{"version","1"}}))).StatusCode==HttpStatusCode.BadRequest,"Review decisions require antiforgery");
|
||||
@ -98,6 +106,6 @@ internal static class NativeCompanionHttpTests
|
||||
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();}
|
||||
Console.WriteLine("PASS actual HTTP native pairing, antiforgery, bearer/stamp, book/subscription access, canonical AI and idempotency (synthetic provider, no database)");
|
||||
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)");
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,12 +1,14 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using PlotLine.Hubs;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
namespace PlotLine.Controllers;
|
||||
[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")]
|
||||
public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access):ControllerBase
|
||||
public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext<NativeCompanionPresenceHub>? live=null):ControllerBase
|
||||
{
|
||||
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
private string Grant=>User.FindFirstValue("NativeCompanion.Grant")??throw new InvalidOperationException();
|
||||
@ -19,6 +21,7 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC
|
||||
if(input.SceneId.HasValue){var parent=book.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==input.SceneId));if(parent==null||(chapter!=null&&chapter!=parent))return NotFound();chapter=parent;input.ChapterId=parent.ChapterId;}
|
||||
if(input.ChapterId.HasValue&&chapter==null)return NotFound();
|
||||
if(!presence.Put(Author,Grant,Expires,instance,session,input))return Conflict(new{message="Stale, revoked or invalid native session."});
|
||||
if(live!=null)await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted);
|
||||
input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);return Ok(input);
|
||||
}
|
||||
[HttpDelete("instances/{instance:guid}/documents/{session:guid}/presence")]
|
||||
|
||||
11
PlotLine/Hubs/NativeCompanionPresenceHub.cs
Normal file
11
PlotLine/Hubs/NativeCompanionPresenceHub.cs
Normal file
@ -0,0 +1,11 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
namespace PlotLine.Hubs;
|
||||
// Cookie-authenticated invalidation only. No navigation/Word commands or client-chosen groups.
|
||||
[Authorize]
|
||||
public sealed class NativeCompanionPresenceHub:Hub
|
||||
{
|
||||
public static string UserGroup(int user)=>"native-presence:user:"+user;
|
||||
public override async Task OnConnectedAsync(){if(!int.TryParse(Context.User?.FindFirstValue(ClaimTypes.NameIdentifier),out var user)){Context.Abort();return;}await Groups.AddToGroupAsync(Context.ConnectionId,UserGroup(user));await base.OnConnectedAsync();}
|
||||
}
|
||||
@ -353,6 +353,7 @@ public class Program
|
||||
name: "default",
|
||||
pattern: "{controller=Home}/{action=Index}/{id?}")
|
||||
.WithStaticAssets();
|
||||
app.MapHub<PlotLine.Hubs.NativeCompanionPresenceHub>("/hubs/native-companion");
|
||||
app.MapHub<WordCompanionFollowHub>("/hubs/word-companion-follow");
|
||||
app.MapHub<StoryIntelligenceHub>("/hubs/story-intelligence");
|
||||
|
||||
|
||||
@ -7,4 +7,5 @@
|
||||
else if(seen){root.hidden=false;root.dataset.connected='false';link.hidden=true;text.textContent='Native Companion disconnected or stale';}
|
||||
}catch{if(seen){root.dataset.connected='false';link.hidden=true;text.textContent='Native Companion status unavailable';}}finally{pending=false;}}
|
||||
void update();const timer=setInterval(()=>void update(),15000);document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer));
|
||||
if(window.signalR){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();connection.on('NativePresenceChanged',()=>{clearTimeout(refresh);refresh=setTimeout(()=>void update(),250);});connection.onreconnected(()=>void update());void connection.start().then(()=>void update()).catch(()=>{});window.addEventListener('pagehide',()=>{clearTimeout(refresh);void connection.stop();});}
|
||||
})();
|
||||
|
||||
@ -24,4 +24,5 @@
|
||||
finally{loading=false;}
|
||||
}
|
||||
document.addEventListener('visibilitychange',()=>{if(!document.hidden)void poll();});window.addEventListener('pagehide',()=>clearInterval(timer));show(null);void poll();timer=setInterval(()=>void poll(),15000);
|
||||
if(window.signalR){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();connection.on('NativePresenceChanged',()=>{clearTimeout(refresh);refresh=setTimeout(()=>void poll(),250);});connection.onreconnected(()=>void poll());void connection.start().then(()=>void poll()).catch(()=>{});window.addEventListener('pagehide',()=>{clearTimeout(refresh);void connection.stop();});}
|
||||
})();
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user