Integrate Writer with verified Word status and acknowledged navigation

This commit is contained in:
Nick Beckley 2026-11-16 21:00:50 +00:00
parent 5529e4a3cf
commit 9969c9b47b
36 changed files with 358 additions and 36 deletions

View File

@ -100,3 +100,7 @@ Phase2C qualified: existing micro/quick/full articles, browser popup and PWA dra
`writer3.authoring` reuses the Markdown tag helper for tooltip, quick popup and full article/drawer. Covers optional chapter/scene intentions, section Save/Cancel, stale/conflict recovery, navigation guards, scene-note/checklist/workflow scopes, explicit initialisation, deferred attachment/category editors, saved companion references and session/Reader/native isolation. `writer3.write` now describes the integrated surface without changing the unified Current Work actions. Qualification is recorded in Phase3A-Report.md.
Phase3A qualification exercises the dynamically loaded authoring Help icon in browser and simulated PWA: quick popup, More drawer and full article. Existing site Help initialisation is explicitly applied to loaded fragments. Updated Write and all previous destination articles remain covered by authenticated navigation. See Phase3A-Report.md and its Help evidence.
## Phase 3B Word continuity
`writer3.word` uses existing micro/quick/full Markdown Help in the Write companion. It covers exact manuscript selection, verified position, working-focus/session/Reader independence, acknowledged chapter and optional verified-scene navigation, accepted-content freshness, bounded saved-manuscript checks, recovery, multiple documents and return/adopt. Check controls and additional explanation use optional Connection and update options. Updated `writer3.write` links the concepts; existing native/Reader/standalone Help remains authoritative. Qualification and physical Windows limits are recorded in Phase3B-Report.md.

View File

@ -1,6 +1,6 @@
# Writer 3.0 implementation tracker
Baseline: `9a8b9a3`, shared branch `codex/word-companion-native-phase1-20261104`, 16 November 2026. The original kickoff authorised Phase 1 implementation and Development deployment; the master specification governs product direction even though its header says Proposed. The subsequent Phase2A kickoff explicitly authorised Home, navigation, destination shells and Development deployment; Phase2B was subsequently explicitly authorised for layout infrastructure and Development deployment; Phase2C is implemented and Development-qualified, including the explicit single-focus workflow amendment; Phase3A integrated authoring is implemented and Development-qualified; Phase3B remains unauthorised. No feature is retired. Unrelated investigation file is preserved.
Baseline: `9a8b9a3`, shared branch `codex/word-companion-native-phase1-20261104`, 16 November 2026. The original kickoff authorised Phase 1 implementation and Development deployment; the master specification governs product direction even though its header says Proposed. The subsequent Phase2A kickoff explicitly authorised Home, navigation, destination shells and Development deployment; Phase2B was subsequently explicitly authorised for layout infrastructure and Development deployment; Phase2C is implemented and Development-qualified, including the explicit single-focus workflow amendment; Phase3A integrated authoring is implemented and Development-qualified; Phase3B is now explicitly authorised for verified Word continuity; Phase3C remains unauthorised. No feature is retired. Unrelated investigation file is preserved.
## Phase 1 screen and interaction states before implementation
@ -37,7 +37,7 @@ No new workspace shell in this phase. Existing Overview/Journey/Workspaces route
### Phase 3 — Write and Review integration
- Objective/deliverables: Inline chapter goals, purpose/outcome, notes/checklist/workflow/attachments; Reader/Audio Review and revision handoff.
- Current authorised batches: 3A.1 current focus; 3A.2 inline chapter/scene editing; 3A.3 notes/checklist/workflow; 3A.4 saved companion references; 3A.5 Help/qualification/Development. These supersede the original provisional labels. Phase3B requires separate authorisation.
- Current authorised batches: 3A.1 current focus; 3A.2 inline chapter/scene editing; 3A.3 notes/checklist/workflow; 3A.4 saved companion references; 3A.5 Help/qualification/Development. These supersede the original provisional labels. Phase3B is subsequently authorised for verified Word integration in batches3B.1–3B.6.
- Reuse: ChapterGoal/Scene repositories, SceneInspectorV2 editors, Reader, IntentAssessmentService, WriterWork toolbar
- New/change: implement the batch deliverables inside the existing MVC application; no parallel Writer.
- Database: Reuse authoritative storage; new revision-task storage only after gap review.
@ -348,3 +348,8 @@ Application `e9402d0c1673d3dc8afcca26bb344b82fa11caf0`, release `e9402d0-2026111
## Phase3A authorised implementation
[Execution and canonical-data contract](Phase3A-Execution.md). Current Work remains unified; optional chapter/scene intentions, notes, reminders and working details use existing records through pure inspection and scoped concurrency-safe saves. Companion shows only saved references. Full native/context redesign, manuscript editing, new planning and AI engines remain out of scope. Help,598-regression, transactional SQL, browser/PWA and real authenticated authoring qualification passed. Development release64e1782-20261116T202418Z; see [completion report](Phase3A-Report.md), screenshots and evidence for endpoint distinctions, invariants, cleanup and physical acceptance. Phase3B not started.
## Phase3B authorised implementation
Batches3B.1–3B.6: native contract audit, shared Word status presentation, explicit acknowledged chapter/scene navigation, accepted Reader freshness, return/recovery, Help/qualification/Development. Existing native identity/range/checkpoint/Reader/session/follow contracts remain authoritative. Additive read-only metadata procedure271 and negotiated acknowledged-navigation-v1; matched native developer source1.0.0.37, no Windows installation. Writer companion shows Word status without displacing intentions or active-session controls. Detailed qualification and final release are in Phase3B-Report.md. Phase3C/4 not started by this authorisation.

View File

@ -0,0 +1,23 @@
# Phase3B authoritative contract and execution ledger
Authorised Phase3B only, shared branch retained; fetched remote and verified no incoming commits before editing. The unrelated canonical-manuscript investigation is untouched. No Windows software installation is authorised by this implementation task.
## 3B.1 findings
The current VSTO/agent chapter-range implementation, rather than historical README claims, is authoritative. Saved-state fences, paragraph identities, checkpoint/hash joins, three-second saved-change debounce, periodic bounded range verification and per-document/session/revision cancellation remain intact. Unsaved observations do not accept prose or verify navigation positions. Reader already preserves Focused Reading in Previous/Next, selected text and paragraph anchors, with pause/update controls; no replacement Reader is needed.
NativePresenceStore carries expiring authenticated document leases. NativeWorkspace status already supplies accepted revision, mapping state and chapter progress through one existing status loop/SignalR invalidation. Writing.Context/Navigate already verifies scene anchors but reports only requested; VSTO returns adapter-result locally, and the agent did not expose correlated navigation completion to the web. The minimum extension is capability-negotiated acknowledged navigation plus an expiry/manuscript fence, reusing existing exact-session delivery and adapter-result.
ChapterSync.List supplies bounded live chapter starts, but a list row alone is not proof: Writer rechecks its first position with ChapterSync.Position against current accepted hashes, manuscript, session and revision. Existing verified scene-start and paragraph position procedures remain authoritative. No scene title/order approximation or synthetic marker is introduced.
## 3B.2–3B.5 composition
Write consumes an optional Writer envelope on the existing status request. A new pure metadata procedure returns only accepted snapshot/chapter times; no manuscript payload is sent for routine status. Verified cursor labels come from current server position lookups and authorised structure names. Several matching documents require explicit choice; an exact live Word-origin session hint can select its own document without changing working focus. A separate explicit canonical SaveObjective action adopts its verified chapter if desired.
Explicit chapter/scene handoff requires acknowledged-navigation capability. Server, agent and VSTO fence exact session/revision/document and command expiry; only the correlated adapter result completes the receipt. Bounded receipt checks exist only during that explicit action. No second background native poller or reconciliation engine is created. Check saved manuscript uses the established snapshot endpoint's bounded chapter check; it never requests fullSnapshot or forces a save.
Reader consumes accepted-revision notifications through existing presence and refreshes timestamps without replacing unchanged prose. Existing accepted-text replacement/pause/selection/anchor policy is preserved. Native Return to Writer reuses the authenticated launcher; standalone Context/Intent placement/follow/pinned behavior is unchanged.
## 3B.6 gates
Build, full web/native executable harnesses, scoped resolver/receipt/adapter-policy assertions, browser/PWA status/navigation/recovery, Reader freshness, existing authoring/focus/layout and standalone follow tests; verified backup and additive metadata procedure; authenticated Development no-Word/permission/rejection checks; scoped author-data hashes and guarded fixture cleanup; final release/report/evidence. Physical VSTO compile/load, real Word navigation/UI timing/media and multiple monitors remain explicitly manual.

View File

@ -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,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterSyncCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.NativeChapterTextCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.NativeChapterPositionsCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.LiveChapterTextCapability));if(trayAdapter)control?.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.CaptureCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.MaintenanceCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ParagraphCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterSyncCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterRangeCapability));
instance = hello.WordInstanceId; sessions.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterSyncCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.NativeChapterTextCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.NativeChapterPositionsCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.LiveChapterTextCapability));if(trayAdapter)control?.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.CaptureCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.MaintenanceCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ParagraphCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterSyncCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterRangeCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.AcknowledgedNavigationCapability));
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability+","+ProtocolVersion.ChapterSyncCapability+","+ProtocolVersion.NativeChapterTextCapability+","+ProtocolVersion.NativeChapterPositionsCapability+","+ProtocolVersion.LiveChapterTextCapability+","+ProtocolVersion.ChapterRangeCapability},cancellation);
log?.Invoke("peer-connected");
while (!cancellation.IsCancellationRequested)

View File

@ -55,6 +55,7 @@ internal sealed class CompanionWindow:Form
var name=Label("PlotDirector");name.Font=new("Segoe UI",24,FontStyle.Bold);header.Controls.Add(name,0,0);header.Controls.Add(Button("Settings",ShowSettings),1,0);
var version=Label("COMPANION · "+typeof(CompanionWindow).Assembly.GetName().Version);version.Font=new("Segoe UI",9);header.Controls.Add(version,0,1);layout.Controls.Add(header);
var connection=Card();connection.Controls.Add(Heading("YOUR CONNECTIONS"));connection.Controls.Add(serverStatus);connection.Controls.Add(account);connection.Controls.Add(wordStatus);connection.Controls.Add(authorise);layout.Controls.Add(connection);
layout.Controls.Add(Button("Return to Writer",()=>{if(Current==null)throw new InvalidOperationException("Open an associated manuscript first.");control.OpenPage(Current.Session,"writer");}));
authorise.Click+=(_,_)=>Safe(()=>cloud.Connect(cloud.Status().ServerUrl));
var manuscript=Card();manuscript.Controls.Add(Heading("CURRENT MANUSCRIPT"));manuscript.Controls.Add(documents);manuscript.Controls.Add(guidance);
var bookLayout=new TableLayoutPanel{Dock=DockStyle.Top,AutoSize=true,ColumnCount=2,Margin=new(0,6,0,4),MinimumSize=new(0,164)};bookLayout.ColumnStyles.Add(new(SizeType.Absolute,110));bookLayout.ColumnStyles.Add(new(SizeType.Percent,100));bookLayout.Controls.Add(cover,0,0);

View File

@ -7,7 +7,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
private readonly Guid agentInstance=Guid.NewGuid(),agentSession=Guid.NewGuid();private int lastBook;private Guid lastAuthentication;private long agentSequence;private long presenceSequence=DateTime.UtcNow.Ticks;private int uploading;private DateTime lastAgentPresence;private bool agentOnlyPublished;
private bool ParagraphCapable(Guid instance){lock(gate)return paragraphInstances.Contains(instance);}
private readonly ParagraphSnapshotCache paragraphSnapshots=new();
private readonly HashSet<Guid> rangeInstances=[];private readonly HashSet<Guid> paragraphInstances=[];private readonly HashSet<Guid> chapterInstances=[];
private readonly HashSet<Guid> acknowledgedNavigationInstances=[];private readonly HashSet<Guid> rangeInstances=[];private readonly HashSet<Guid> paragraphInstances=[];private readonly HashSet<Guid> chapterInstances=[];
private readonly object gate=new();private readonly Dictionary<Guid,TrayDocument> documents=[];
private readonly Dictionary<Guid,Queue<AdapterCommand>> commands=[];private readonly Dictionary<Guid,Guid> leases=[];private readonly HashSet<Guid> captureInstances=[];private readonly HashSet<Guid> maintenanceInstances=[];private readonly Dictionary<Guid,(Guid Session,Guid Manuscript,Guid Authentication,string Kind,DateTime Started)> maintenance=[];private readonly Dictionary<(Guid,Guid),(Guid Manuscript,Guid Authentication,int Book,DateTime Expires)> reconnectBindings=[];
public event Action? OpenRequested;
@ -15,7 +15,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
internal Func<Guid,(string State,string[] Operations)>? AudioStatus { get; set; }
public TrayDocument[] Documents {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).ToArray();}}
public TrayDocument[] PresentationDocuments {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).Select(d=>d.Snapshot()).ToArray();}}
public void Attach(Guid instance,Guid lease,bool capture=false,bool canMaintain=false,bool paragraphs=false,bool chapters=false,bool rangeChecks=false){lock(gate){Disconnected(instance);if(rangeChecks)rangeInstances.Add(instance);if(chapters)chapterInstances.Add(instance);else chapterInstances.Remove(instance);if(paragraphs)paragraphInstances.Add(instance);else paragraphInstances.Remove(instance);leases[instance]=lease;if(canMaintain)maintenanceInstances.Add(instance);else maintenanceInstances.Remove(instance);if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}}
public void Attach(Guid instance,Guid lease,bool capture=false,bool canMaintain=false,bool paragraphs=false,bool chapters=false,bool rangeChecks=false,bool acknowledgedNavigation=false){lock(gate){Disconnected(instance);if(acknowledgedNavigation)acknowledgedNavigationInstances.Add(instance);if(rangeChecks)rangeInstances.Add(instance);if(chapters)chapterInstances.Add(instance);else chapterInstances.Remove(instance);if(paragraphs)paragraphInstances.Add(instance);else paragraphInstances.Remove(instance);leases[instance]=lease;if(canMaintain)maintenanceInstances.Add(instance);else maintenanceInstances.Remove(instance);if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}}
public Message Exchange(Guid instance,Message request,Message answer,Guid lease=default)
{
lock(gate)
@ -55,7 +55,10 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
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"&&maintenance.Remove(request.SnapshotId,out var operation)&&operation.Session==doc.Session){doc.MaintenanceReport=request.OperationMessage;if(request.OperationMessage.StartsWith("Complete:",StringComparison.Ordinal)&&operation.Kind is "reset" or "clean"){cloud.ForgetBinding(operation.Manuscript,operation.Authentication);doc.Book=0;doc.AssociationRequest=Guid.Empty;doc.AssociationNeedsSave=false;doc.AssociationNotice="";doc.RememberedBook=null;doc.AssociationSite="";doc.ChapterId=null;doc.SceneId=null;doc.LastPresenceKey="";_=cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);} }
if(request.Kind=="adapter-result"&&doc.PendingNavigation!=Guid.Empty&&request.SnapshotId==doc.PendingNavigation){
if(request.Revision==doc.NavigationRevision&&request.Revision==doc.Revision&&DateTime.UtcNow<=doc.NavigationExpires){doc.NavigationAcknowledgedId=request.SnapshotId;doc.NavigationResult=request.OperationMessage=="ok"?"completed":"failed";doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}doc.PendingNavigation=Guid.Empty;
}
else if(request.Kind=="adapter-result"&&maintenance.Remove(request.SnapshotId,out var operation)&&operation.Session==doc.Session){doc.MaintenanceReport=request.OperationMessage;if(request.OperationMessage.StartsWith("Complete:",StringComparison.Ordinal)&&operation.Kind is "reset" or "clean"){cloud.ForgetBinding(operation.Manuscript,operation.Authentication);doc.Book=0;doc.AssociationRequest=Guid.Empty;doc.AssociationNeedsSave=false;doc.AssociationNotice="";doc.RememberedBook=null;doc.AssociationSite="";doc.ChapterId=null;doc.SceneId=null;doc.LastPresenceKey="";_=cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);} }
else if(request.Kind=="adapter-result"&&request.SnapshotId==doc.AssociationRequest&&doc.AssociationRequest!=Guid.Empty){
doc.AssociationRequest=Guid.Empty;
doc.AssociationNeedsSave=request.OperationMessage=="association-written";
@ -79,7 +82,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
return answer;
}
}
public void Disconnected(Guid instance,Guid lease=default){lock(gate){if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return;leases.Remove(instance);rangeInstances.Remove(instance);chapterInstances.Remove(instance);paragraphInstances.Remove(instance);captureInstances.Remove(instance);maintenanceInstances.Remove(instance);foreach(var expired in reconnectBindings.Where(p=>p.Value.Expires<=DateTime.UtcNow).Select(p=>p.Key).ToArray())reconnectBindings.Remove(expired);foreach(var doc in documents.Values.Where(d=>d.Instance==instance).ToArray()){if(doc.Book>0&&reconnectBindings.Count<256)reconnectBindings[(instance,doc.Session)]=(doc.Manuscript,doc.Authentication,doc.Book,DateTime.UtcNow.AddMinutes(2));Remove(doc.Session);}commands.Remove(instance);}}
public void Disconnected(Guid instance,Guid lease=default){lock(gate){if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return;leases.Remove(instance);acknowledgedNavigationInstances.Remove(instance);rangeInstances.Remove(instance);chapterInstances.Remove(instance);paragraphInstances.Remove(instance);captureInstances.Remove(instance);maintenanceInstances.Remove(instance);foreach(var expired in reconnectBindings.Where(p=>p.Value.Expires<=DateTime.UtcNow).Select(p=>p.Key).ToArray())reconnectBindings.Remove(expired);foreach(var doc in documents.Values.Where(d=>d.Instance==instance).ToArray()){if(doc.Book>0&&reconnectBindings.Count<256)reconnectBindings[(instance,doc.Session)]=(doc.Manuscript,doc.Authentication,doc.Book,DateTime.UtcNow.AddMinutes(2));Remove(doc.Session);}commands.Remove(instance);}}
private void Remove(Guid session){chapterWork.Remove(session);paragraphSnapshots.Remove(session);foreach(var key in maintenance.Where(p=>p.Value.Session==session).Select(p=>p.Key).ToArray())maintenance.Remove(key);if(documents.Remove(session,out var doc)){Cancel(doc);_ = cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);}}
private bool Queue(TrayDocument doc,AdapterCommand command){if(!commands.TryGetValue(doc.Instance,out var queue))commands[doc.Instance]=queue=new();if(queue.Count>=16){doc.Status="Word request queue is busy. Retry after current operation.";return false;}command.SessionId=doc.Session;command.Revision=doc.Revision;queue.Enqueue(command);return true;}
public bool CanMaintain(Guid session){lock(gate)return documents.TryGetValue(session,out var d)&&maintenanceInstances.Contains(d.Instance);}
@ -116,7 +119,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
if(!Queue(doc,new(){Id=doc.Job,Kind="extract-ai",Chapter=doc.Current,BookId=doc.Book,AuthenticationContext=doc.Authentication})){doc.Job=Guid.Empty;doc.Pending.Clear();}
}
public void Cancel(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Status="Cancelled. Successful server suggestions remain available.";}}
private void Cancel(TrayDocument doc,bool notifyWord=true){CancelChapterWork(doc);doc.PendingRibbonCommand="";doc.RibbonPermit=Guid.Empty;doc.RibbonRequestedUtc=default;doc.RibbonNotice=null;doc.RetryCapture=null;foreach(var request in maintenance.Where(p=>p.Value.Session==doc.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(request);doc.MaintenanceReport="Stopped: superseded by a document or account change. Inspect before retrying cleanup.";}if(doc.Capture!=null)_=cloud.FailCapture(doc.Capture.RequestId,doc.Authentication);doc.Capture=null;doc.CaptureFragments.Clear();if(doc.Job!=Guid.Empty)ai.Clear(doc.Session);doc.Job=Guid.Empty;doc.Pending.Clear();if(commands.TryGetValue(doc.Instance,out var q))commands[doc.Instance]=new(q.Where(c=>c.SessionId!=doc.Session));if(notifyWord)Queue(doc,new(){Kind="cancel"});}
private void Cancel(TrayDocument doc,bool notifyWord=true){doc.PendingNavigation=Guid.Empty;doc.NavigationAcknowledgedId=null;doc.NavigationResult="";CancelChapterWork(doc);doc.PendingRibbonCommand="";doc.RibbonPermit=Guid.Empty;doc.RibbonRequestedUtc=default;doc.RibbonNotice=null;doc.RetryCapture=null;foreach(var request in maintenance.Where(p=>p.Value.Session==doc.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(request);doc.MaintenanceReport="Stopped: superseded by a document or account change. Inspect before retrying cleanup.";}if(doc.Capture!=null)_=cloud.FailCapture(doc.Capture.RequestId,doc.Authentication);doc.Capture=null;doc.CaptureFragments.Clear();if(doc.Job!=Guid.Empty)ai.Clear(doc.Session);doc.Job=Guid.Empty;doc.Pending.Clear();if(commands.TryGetValue(doc.Instance,out var q))commands[doc.Instance]=new(q.Where(c=>c.SessionId!=doc.Session));if(notifyWord)Queue(doc,new(){Kind="cancel"});}
public void Navigate(Guid session,int start){lock(gate)if(documents.TryGetValue(session,out var doc))Queue(doc,new(){Kind="navigate",Chapter=new(){Start=start}});}
public async Task Tick(CancellationToken cancellation)
{
@ -147,17 +150,19 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
}
});
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 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=="writer"?$"/Writer/Write?bookId={doc.Book}&wordInstanceId={doc.Instance}&wordSessionId={doc.Session}":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.FromMilliseconds(500),cancellation);var available=Documents.Where(d=>d.Authentication==cloud.Status().AuthenticationContext&&cloud.Status().Health?.Authentication=="verified").ToArray();
foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))continue;var key=$"{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,ChapterIssue=ChapterIssue(doc),CanChapterSync=ChapterCapable(doc.Instance),CanParagraphSync=ParagraphCapable(doc.Instance),CanCapture=captureInstances.Contains(doc.Instance),WordRunning=true,WordSaved=doc.WordSaved,CursorStart=doc.Cursor,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc||(ChapterCapable(doc.Instance)&&reply.Revision!=doc.Revision)||doc.Authentication!=cloud.Status().AuthenticationContext)continue;if(ChapterCapable(doc.Instance)&&chapterWork.TryGetValue(doc.Session,out var currentChapters)&&currentChapters.Manifest!=null&&reply.ParagraphRevision>0&&reply.ParagraphRevision<currentChapters.Manifest.Revision)continue;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;doc.ChapterProgress=reply.ChapterProgress;if(ChapterCapable(doc.Instance))ChapterCursorEvidence.Apply(doc,reply);else{doc.ChapterTitle=reply.ChapterTitle;doc.SceneTitle=reply.SceneTitle;}ObserveChapterPresence(doc,reply);}
foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))continue;var key=$"{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CanAcknowledgeNavigation=acknowledgedNavigationInstances.Contains(doc.Instance),NavigationAcknowledgedId=doc.NavigationAcknowledgedId,NavigationResult=doc.NavigationResult,CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,ChapterIssue=ChapterIssue(doc),CanChapterSync=ChapterCapable(doc.Instance),CanParagraphSync=ParagraphCapable(doc.Instance),CanCapture=captureInstances.Contains(doc.Instance),WordRunning=true,WordSaved=doc.WordSaved,CursorStart=doc.Cursor,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc||(ChapterCapable(doc.Instance)&&reply.Revision!=doc.Revision)||doc.Authentication!=cloud.Status().AuthenticationContext)continue;if(ChapterCapable(doc.Instance)&&chapterWork.TryGetValue(doc.Session,out var currentChapters)&&currentChapters.Manifest!=null&&reply.ParagraphRevision>0&&reply.ParagraphRevision<currentChapters.Manifest.Revision)continue;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;doc.ChapterProgress=reply.ChapterProgress;if(ChapterCapable(doc.Instance))ChapterCursorEvidence.Apply(doc,reply);else{doc.ChapterTitle=reply.ChapterTitle;doc.SceneTitle=reply.SceneTitle;}ObserveChapterPresence(doc,reply);}
if(reply.ParagraphRevision>0&&!ChapterCapable(doc.Instance))lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext){doc.ChapterId=reply.ChapterId;doc.SceneId=reply.SceneId;}
if(reply.Navigation is {Kind:"wizard-capture",BookId:>0} requested&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Book==0){await cloud.CheckConnection();lock(gate){if(doc.Book==0&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext&&cloud.Allows(doc.Authentication,requested.BookId)&&documents.GetValueOrDefault(doc.Session)==doc){doc.Book=requested.BookId;cloud.RememberBinding(doc.Manuscript,doc.Book,doc.Authentication);doc.LastPresenceKey="";}}}
if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision){if((reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")&&captureInstances.Contains(doc.Instance)&&(reply.Navigation.BookId==0||reply.Navigation.BookId==doc.Book)&&cloud.Allows(doc.Authentication,doc.Book)){if(uploading!=0||documents.Values.Any(d=>d.Capture!=null)){_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);continue;}var retained=doc.RetryCapture;var reusable=retained!=null&&doc.RetryAuthentication==doc.Authentication&&doc.RetryBook==doc.Book&&retained.ManuscriptId==doc.Manuscript&&retained.Revision==doc.Revision&&retained.ParagraphTracking==reply.Navigation.ParagraphTracking;
Cancel(doc);doc.Capture=new(){RequestId=reply.Navigation.Id,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,Revision=doc.Revision,ParagraphTracking=reply.Navigation.ParagraphTracking,End=reusable?retained!.End:0};doc.CaptureBaseRevision=reply.Navigation.BaseRevision;doc.CaptureBaseHash=reply.Navigation.BaseSnapshotHash;doc.CaptureFragments.Clear();
if(reusable){doc.CaptureFragments.AddRange(retained!.Paragraphs);doc.Status="Retrying the retained unchanged manuscript at your import request…";CaptureFrame(doc,new(){Kind="snapshot-end",SnapshotId=reply.Navigation.Id},new(){Status="ok"});}
else{doc.Status="Reading manuscript for the PlotDirector import wizard…";Queue(doc,reply.Navigation);}}else if(reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);else if(reply.Navigation.Kind=="cancel")Cancel(doc);else if(reply.Navigation.Kind=="chapter-repair"){BeginChapterRepair(doc,reply.Navigation.Id);}else if(reply.Navigation.Kind=="navigate")Queue(doc,reply.Navigation);}}catch(Exception e)when(NetworkFailure(e)) {doc.Status=e.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.UtcNow;}}
else{doc.Status="Reading manuscript for the PlotDirector import wizard…";Queue(doc,reply.Navigation);}}else if(reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);else if(reply.Navigation.Kind=="cancel")Cancel(doc);else if(reply.Navigation.Kind=="chapter-repair"){BeginChapterRepair(doc,reply.Navigation.Id);}else if(reply.Navigation.Kind=="navigate"&&(reply.Navigation.BookId==0||reply.Navigation.BookId==doc.Book)&&(reply.Navigation.ManuscriptId==Guid.Empty||reply.Navigation.ManuscriptId==doc.Manuscript)&&(reply.Navigation.ExpiresUtc==default||reply.Navigation.ExpiresUtc>DateTime.UtcNow)){
if(Queue(doc,reply.Navigation)){doc.PendingNavigation=reply.Navigation.Id;doc.NavigationRevision=doc.Revision;doc.NavigationExpires=reply.Navigation.ExpiresUtc==default?DateTime.UtcNow.AddSeconds(25):reply.Navigation.ExpiresUtc;}
}}}catch(Exception e)when(NetworkFailure(e)) {doc.Status=e.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.UtcNow;}}
if(available.Length==0&&cloud.Status().Health?.Authentication=="verified"&&DateTime.UtcNow-lastAgentPresence>=TimeSpan.FromSeconds(15)){lastAgentPresence=DateTime.UtcNow;agentOnlyPublished=true;try{await cloud.Presence(agentInstance,agentSession,new(){WordRunning=leases.Count>0,BookId=0,Sequence=Interlocked.Increment(ref agentSequence),WordAvailable=false,DocumentTitle="No Word document"},cloud.Status().AuthenticationContext);}catch(Exception e)when(NetworkFailure(e)) {}}
else if(available.Length>0&&agentOnlyPublished){agentOnlyPublished=false;await cloud.RemovePresence(agentInstance,agentSession);}
}
@ -206,7 +211,7 @@ public sealed class TrayDocument
{
internal long AudioTextChanges;
public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress;
public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Link this manuscript to a book, then use Import manuscript in PlotDirector.",ReviewPath="";
public Guid? NavigationAcknowledgedId;public string NavigationResult="";public Guid PendingNavigation;public long NavigationRevision;public DateTime NavigationExpires;public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Link this manuscript to a book, then use Import manuscript in PlotDirector.",ReviewPath="";
internal ManuscriptCapture? RetryCapture;internal Guid RetryAuthentication;internal int RetryBook;
public long CaptureBaseRevision;public string CaptureBaseHash="";public ManuscriptCapture? Capture;public List<ParagraphFragment> CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision;
internal string LastRibbonCommand="",LastRibbonOutcome="",PendingRibbonCommand="",LastChapterInterruption="";

View File

@ -119,7 +119,7 @@ public sealed class AgentLink : IDisposable
lock (gate) activePipe = pipe;
await pipe.ConnectAsync(700, stop.Token).ConfigureAwait(false);
if (!verifyServer(pipe)) throw new UnauthorizedAccessException("Unexpected agent owner.");
await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability+","+ProtocolVersion.ChapterSyncCapability+","+ProtocolVersion.NativeChapterTextCapability+","+ProtocolVersion.NativeChapterPositionsCapability+","+ProtocolVersion.LiveChapterTextCapability+","+ProtocolVersion.ChapterRangeCapability }, stop.Token).ConfigureAwait(false);
await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability+","+ProtocolVersion.ChapterSyncCapability+","+ProtocolVersion.NativeChapterTextCapability+","+ProtocolVersion.NativeChapterPositionsCapability+","+ProtocolVersion.LiveChapterTextCapability+","+ProtocolVersion.ChapterRangeCapability+","+ProtocolVersion.AcknowledgedNavigationCapability }, stop.Token).ConfigureAwait(false);
mailbox.Clear(); // Reconcile authoritative open documents; never replay stale extraction fragments.
await ExchangeAsync(pipe, Reconcile(), stop.Token).ConfigureAwait(false);
attempt = 0; StateChanged?.Invoke("connected");

View File

@ -1 +1 @@
<Project><PropertyGroup><ApplicationVersion>1.0.0.36</ApplicationVersion></PropertyGroup></Project>
<Project><PropertyGroup><ApplicationVersion>1.0.0.37</ApplicationVersion></PropertyGroup></Project>

View File

@ -5,6 +5,7 @@ namespace PlotDirector.Companion.Protocol;
public static class ProtocolVersion
{
public const int Current = 1;
public const string AcknowledgedNavigationCapability="acknowledged-navigation-v1";
public const string ChapterRangeCapability="chapter-range-verification-v1";
public const string LiveChapterTextCapability="chapter-live-text-v1";
public const string NativeChapterPositionsCapability="chapter-native-positions-v1";

View File

@ -0,0 +1,9 @@
namespace PlotDirector.Companion.Protocol;
// Pure gate, also used on Word's UI thread immediately before selection. Never opens or saves a document.
public static class NavigationPolicy
{
public static bool Current(AdapterCommand command,Guid session,long revision,Guid manuscript,DateTime utcNow,bool saved)=>
command.SessionId==session&&command.Revision==revision&&
(command.ManuscriptId==Guid.Empty||command.ManuscriptId==manuscript&&saved)&&
(command.ExpiresUtc==default||command.ExpiresUtc>utcNow);
}

View File

@ -4,6 +4,8 @@ namespace PlotDirector.Companion.Protocol;
public sealed class AdapterCommand
{
[DataMember] public PlotDirector.Companion.Protocol.Manuscript.ChapterManifestItem? RangeBaseline {get;set;}
[DataMember] public DateTime ExpiresUtc {get;set;}
[DataMember] public Guid ManuscriptId {get;set;}
[DataMember] public bool RecheckRevision {get;set;}
[DataMember] public bool ObserveOnly {get;set;}
[DataMember] public Guid OperationId {get;set;}
@ -24,6 +26,9 @@ public sealed class AdapterCommand
[DataContract]
public sealed class NativePresence
{
[DataMember] public bool CanAcknowledgeNavigation {get;set;}
[DataMember] public Guid? NavigationAcknowledgedId {get;set;}
[DataMember] public string NavigationResult {get;set;}="";
[DataMember] public Guid[]? CanonicalParagraphIds {get;set;}
[DataMember] public long ParagraphRevision {get;set;}
[DataMember] public string ParagraphSnapshotHash {get;set;}="";

View File

@ -31,7 +31,12 @@ internal static class TrayTests
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){}
}
var registered=control.Documents.Single(d=>d.Session==first.SessionId);var priorSequence=registered.PresenceSequence;Apply(new(){Kind="reconcile",Documents=[first,second]});check(control.Documents.Single(d=>d.Session==first.SessionId).Book==3&&control.Documents.Single(d=>d.Session==first.SessionId).PresenceSequence==priorSequence,"reconciliation preserves verified book and monotonic heartbeat state");
var registered=control.Documents.Single(d=>d.Session==first.SessionId);
var navigation=Guid.NewGuid();registered.PendingNavigation=navigation;registered.NavigationRevision=1;registered.NavigationExpires=DateTime.UtcNow.AddSeconds(20);
Apply(new(){Kind="adapter-result",SessionId=second.SessionId,Revision=1,SnapshotId=navigation,OperationMessage="ok"});check(registered.NavigationAcknowledgedId==null,"another Word document cannot acknowledge this navigation");
Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=1,SnapshotId=navigation,OperationMessage="ok"});check(registered.NavigationAcknowledgedId==navigation&&registered.NavigationResult=="completed"&&registered.PendingNavigation==Guid.Empty,"exact adapter result reaches document-scoped presence acknowledgement");
registered.PendingNavigation=Guid.NewGuid();registered.NavigationRevision=0;registered.NavigationExpires=DateTime.UtcNow.AddSeconds(20);Apply(new(){Kind="adapter-result",SessionId=first.SessionId,Revision=0,SnapshotId=registered.PendingNavigation,OperationMessage="ok"});check(registered.NavigationAcknowledgedId==navigation,"stale native acknowledgement cannot replace completed navigation");
var fenced=new AdapterCommand{SessionId=first.SessionId,Revision=1,ManuscriptId=first.ManuscriptId,ExpiresUtc=DateTime.UtcNow.AddSeconds(10)};check(NavigationPolicy.Current(fenced,first.SessionId,1,first.ManuscriptId,DateTime.UtcNow,true)&&!NavigationPolicy.Current(fenced,second.SessionId,1,first.ManuscriptId,DateTime.UtcNow,true)&&!NavigationPolicy.Current(fenced,first.SessionId,1,first.ManuscriptId,DateTime.UtcNow,false)&&!NavigationPolicy.Current(fenced,first.SessionId,1,first.ManuscriptId,DateTime.UtcNow.AddSeconds(11),true),"native execution gate rejects foreign session, dirty state and expired UI queue without COM work");var priorSequence=registered.PresenceSequence;Apply(new(){Kind="reconcile",Documents=[first,second]});check(control.Documents.Single(d=>d.Session==first.SessionId).Book==3&&control.Documents.Single(d=>d.Session==first.SessionId).PresenceSequence==priorSequence,"reconciliation preserves verified book and monotonic heartbeat state");
handler.Command=new(){Id=Guid.NewGuid(),Kind="wizard-capture",SessionId=first.SessionId,Revision=1};var captureId=handler.Command.Id;registered.SceneId=null;registered.LastPresenceKey="";registered.LastPresenceUtc=DateTime.MinValue;
using(var stop=new CancellationTokenSource()){
var heartbeats=control.Heartbeat(stop.Token);await Until(()=>control.Documents.Single(d=>d.Session==first.SessionId).Capture!=null);

View File

@ -276,6 +276,7 @@ namespace PlotDirector.WordAddIn
}
else if(command.Kind=="cancel"){CancelChapterRead(doc);CancelExtraction(doc);doc.AiJob=Guid.Empty;}
else if(command.Kind=="navigate"&&command.Chapter!=null){
if(!NavigationPolicy.Current(command,doc.Session,doc.Revision,doc.Identity,DateTime.UtcNow,Com(()=>doc.Document.Saved)))throw new InvalidOperationException("Navigation expired or document changed.");
if(completedNavigationIds.Contains(command.Id)){Reply(command,"ok");return;}
var position=command.Chapter.Start;if(position<0||position>DocumentEnd(doc.Document))throw new InvalidOperationException("Position no longer exists.");
Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));Com(()=>{range.Select();return true;});navigationExecutions++;lastNavigationId=command.Id;if(completedNavigationIds.Count==64)completedNavigationIds.Dequeue();completedNavigationIds.Enqueue(command.Id);}finally{Release(range);}

View File

@ -0,0 +1,2 @@
const{chromium}=require('playwright'),assert=require('node:assert/strict');
(async()=>{const b=await chromium.launch();try{for(const pwa of[false,true]){const c=await b.newContext();if(pwa)await c.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const p=await c.newPage();let stamp='2026-11-16T12:00:00Z',checks=0;await p.route('**/manuscript/reader/changes?*',r=>{checks++;const u=new URL(r.request().url());return r.fulfill({json:{revision:u.searchParams.get('knownRevision'),version:u.searchParams.get('knownVersion'),changed:false,lastSuccessfulSyncUtc:stamp,snapshotCapturedUtc:'2026-11-15T12:00:00Z'}})});await p.goto('http://127.0.0.1:5238/manuscript/reader?bookId=12&chapterId=21&focus=true');await p.locator('#reader-timestamps time[datetime="'+stamp+'"]').waitFor();const row=await p.locator('[data-paragraph-id]').first().elementHandle();await row.evaluate(n=>{const r=document.createRange();r.selectNodeContents(n);getSelection().removeAllRanges();getSelection().addRange(r)});const selected=await p.evaluate(()=>getSelection().toString());const before=checks;stamp='2026-11-16T13:00:00Z';await p.evaluate(()=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[{bookId:12,snapshotRevision:99999}]})));await p.locator('#reader-timestamps time[datetime="'+stamp+'"]').waitFor();assert(checks>before);assert(await row.evaluate(n=>n===document.querySelector('[data-paragraph-id]')));assert.equal(await p.evaluate(()=>getSelection().toString()),selected);assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');const next=p.locator('a[rel=next]');if(await next.count())assert(new URL(await next.getAttribute('href'),'http://fixture').searchParams.get('focus')==='true');await c.close();}console.log('PASS Reader accepted-metadata notification updates timestamps without replacing prose, selected text or Focused Reading; Next preserves focus. Browser/simulated PWA.');}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});

View File

@ -0,0 +1,24 @@
const{chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
(async()=>{const browser=await chromium.launch();try{for(const pwa of[false,true]){
const c=await browser.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()})));if(pwa)await c.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));await c.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'))}));await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:{sessionID:'55555555-5555-5555-5555-555555555555',kind:'AudioReview',bookID:12,chapterID:22,chapterTitle:'Bound audio chapter',startedUtc:new Date().toISOString(),engagedSeconds:60,playbackSeconds:20,uniqueSeconds:10,pauseOnEdit:true,live:true,playbackState:'playing',capabilities:'play,pause,back15,forward15',sequence:1},defaultPauseOnEdit:true}}));
const lease={instanceId:'11111111-1111-1111-1111-111111111111',sessionId:'22222222-2222-2222-2222-222222222222',manuscriptId:'33333333-3333-3333-3333-333333333333',bookId:12,wordAvailable:true,wordSaved:true,canAcknowledgeNavigation:true,canChapterSync:true,revision:2,documentTitle:'Disposable verified manuscript',chapterId:22,chapterTitle:'Other chapter',expires:new Date(Date.now()+3600000).toISOString(),updated:new Date().toISOString(),chapterProgress:{state:'Synchronised'}};
let packet={leases:[lease],canonical:{manuscriptID:lease.manuscriptId,revision:5,chapterAcceptedUtc:'2026-11-16T12:00:00Z'},verifiedPositions:[{instanceId:lease.instanceId,sessionId:lease.sessionId,chapterId:22,chapterTitle:'Other chapter'}]},posts=0,statusCalls=0,receipt='requested',syncs=0;
await c.route('**/native-companion/status*',r=>{statusCalls++;return r.fulfill({json:packet})});await c.route('**/WriterWord/Navigate',r=>{posts++;const body=new URLSearchParams(r.request().postData());assert.equal(body.get('chapterId'),'21');assert.equal(body.get('bookId'),'12');assert.equal(body.get('sessionId'),lease.sessionId);return r.fulfill({status:202,json:{message:'requested'}})});await c.route('**/WriterWord/Navigation?*',r=>r.fulfill({json:{state:receipt}}));await c.route('**/manuscript/paragraphs/snapshot',r=>{syncs++;assert(!new URLSearchParams(r.request().postData()).has('fullSnapshot'));return r.fulfill({json:{requestId:'request',message:'Bounded check requested'}})});
const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));const url='http://127.0.0.1:5238/Writer/Write?projectId=7&bookId=12&objective=true';await p.goto(url);await p.locator('[data-word-state]').filter({hasText:'Disposable verified manuscript'}).waitFor().catch(async e=>{throw Error(`${e.message}; state=${await p.locator('[data-word-state]').textContent()}; errors=${errors.join(';')}`)});assert((await p.locator('[data-word-position]').textContent()).includes('Other chapter'));assert((await p.locator('[data-writer-focus] h2').first().textContent()).includes('Arrival'));assert((await p.locator('[data-word-freshness]').textContent()).includes('last accepted'));assert(!/up to date/i.test(await p.locator('[data-word-freshness]').textContent()));
const count=statusCalls;const resumed=p.waitForResponse(r=>r.url().includes('/native-companion/status'));await p.evaluate(()=>{window.dispatchEvent(new PageTransitionEvent('pagehide',{persisted:true}));window.dispatchEvent(new PageTransitionEvent('pageshow',{persisted:true}));});await resumed;assert(statusCalls>count,'shared status resumes after cached return');
const update=async value=>{packet=value;await p.evaluate(v=>window.dispatchEvent(new CustomEvent('writer-word-state',{detail:v})),value)};const initial=structuredClone(packet);
await p.locator('[data-help-key="writer3.word"] button').click();await p.locator('.plotline-help-popover').waitFor();await p.locator('.plotline-help-more').click();await p.locator('[data-help-content] .help-drawer-article').waitFor();await p.locator('[data-help-close]').click();
await p.locator('[data-work-note]').evaluate(n=>n.value='Unsaved return note');const work=await p.locator('[data-writer-work]').elementHandle();await p.locator('[data-word-navigate]').evaluate(b=>{b.click();b.click()});await p.locator('[data-word-command]').filter({hasText:'waiting for confirmation'}).waitFor();assert.equal(posts,1);assert(!(await p.locator('[data-word-command]').textContent()).includes('confirmed navigation'));receipt='completed';await p.locator('[data-word-command]').filter({hasText:'Word confirmed navigation.'}).waitFor();assert(await work.evaluate(n=>n===document.querySelector('[data-writer-work]')));assert.equal(await p.locator('[data-work-note]').inputValue(),'Unsaved return note');assert((await p.locator('[data-work-bound]').textContent()).includes('Bound audio chapter'));assert(await p.locator('[data-work-audio]').isVisible());
receipt='timed-out';await p.locator('[data-word-navigate]').click();await p.locator('[data-word-command]').filter({hasText:'expired'}).waitFor();
await p.getByText('Connection and update options',{exact:true}).click();await p.locator('[data-word-sync]').click();await p.locator('[data-word-command]').filter({hasText:'acceptance has not yet been confirmed'}).waitFor();assert.equal(syncs,1);
await update({...initial,leases:[{...lease,canAcknowledgeNavigation:false}]});assert(await p.locator('[data-word-navigate]').isDisabled());assert((await p.locator('[data-word-position]').textContent()).includes('Update the Word add-in'));
await update({...initial,canonical:{manuscriptID:'foreign'}});assert(await p.locator('[data-word-navigate]').isDisabled());assert((await p.locator('[data-word-state]').textContent()).includes('not been verified'));
await update({...initial,leases:[{...lease,wordSaved:false}],verifiedPositions:[]});assert(await p.locator('[data-word-navigate]').isDisabled());assert((await p.locator('[data-word-position]').textContent()).includes('unsaved'));
await update({...initial,leases:[{...lease,bookId:99}],verifiedPositions:[]});assert(await p.locator('[data-word-navigate]').isDisabled());assert((await p.locator('[data-word-state]').textContent()).includes('another book'));
await update({unavailable:true});assert((await p.locator('[data-word-state]').textContent()).includes('unavailable'));assert.equal(await p.locator('[data-work-note]').inputValue(),'Unsaved return note');
const second={...lease,sessionId:'44444444-4444-4444-4444-444444444444',documentTitle:'Second manuscript'};await update({...initial,leases:[lease,second]});assert(await p.locator('[data-word-choose]').isVisible());assert(await p.locator('[data-word-navigate]').isDisabled());await p.locator('[data-word-document]').selectOption(lease.instanceId+'/'+lease.sessionId);assert(await p.locator('[data-word-navigate]').isEnabled());
receipt='requested';await p.locator('[data-word-navigate]').click();await p.locator('[data-word-command]').filter({hasText:'waiting for confirmation'}).waitFor();await update({...initial,leases:[second],verifiedPositions:[]});await p.locator('[data-word-command]').filter({hasText:'not confirmed'}).waitFor();
await p.goto(url+'&wordInstanceId='+lease.instanceId+'&wordSessionId='+lease.sessionId);packet=initial;await update(initial);await p.locator('[data-word-adopt]').waitFor().catch(async e=>{throw Error(`${e.message}; ${JSON.stringify(await p.locator('[data-writer-word]').evaluate(n=>({chapter:n.dataset.chapterId,adoptHidden:n.querySelector('[data-word-adopt]').hidden,state:n.querySelector('[data-word-state]').textContent,position:n.querySelector('[data-word-position]').textContent,asideHidden:n.closest('aside').hidden})))}`)});assert.equal(await p.locator('[data-word-adopt] [name=ChapterID]').inputValue(),'22');assert((await p.locator('[data-word-origin]').textContent()).includes('unchanged'));
if(!pwa&&process.env.PD_WRITER3_SCREENSHOTS){fs.mkdirSync(process.env.PD_WRITER3_SCREENSHOTS,{recursive:true});await p.evaluate(()=>window.PlotDirectorApplyApplicationTheme('modern-dark'));await p.screenshot({path:process.env.PD_WRITER3_SCREENSHOTS+'/Write-verified-simulated.png',animations:'disabled'});}
await p.setViewportSize({width:390,height:844});await p.locator('.writer3-layout-tools button').first().click();await p.locator('[data-writer-word]').scrollIntoViewIfNeeded();assert(await p.locator('[data-word-navigate]').isVisible());assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));assert(await p.locator('.writer3-reference').isVisible());await p.keyboard.press('Escape');assert(await p.locator('.writer3-reference').isHidden());assert.deepEqual(errors,[]);await c.close();}
console.log('PASS Writer Word browser/simulated PWA: exact document status, focus isolation, old/uncertain/unsaved/cross-book rejection, explicit chapter handoff, acknowledgement versus request, timeout, repeat guard, bounded check, multi-document selection, disconnect, retained notes/DOM, verified-origin adoption, Help and narrow overlay. Native events and acknowledgements simulated.');}finally{await browser.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});

View File

@ -170,6 +170,7 @@ var tests = new (string Name, Action Test)[]
("Release triage and browser-only onboarding preserve author decisions", ReleaseSprintTests.Run),
("Approved native import source and confirmation remain safe", () => NativeImportTests.Run().GetAwaiter().GetResult()),
("Native installation renewal and revocation remain account/security scoped", () => NativeInstallationTests.Run().GetAwaiter().GetResult()),
("Writer Word verified navigation and acknowledgement",()=>WriterWordTests.Run().GetAwaiter().GetResult()),
("Writer inline authoring validation",()=>WriterAuthoringTests.Run()),
("Writer 3 destination navigation and scope",()=>WriterNavigationTests.Run().GetAwaiter().GetResult()),
("Writer foundation context, queue scope and planning",()=>WriterFoundationTests.Run().GetAwaiter().GetResult()),

View File

@ -0,0 +1,36 @@
using PlotDirector.Companion.Protocol;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services.Writer;
using PlotLine.Services.NativeCompanion;
internal static class WriterWordTests
{
private sealed class Clock:TimeProvider{public DateTimeOffset Now=DateTimeOffset.UtcNow;public override DateTimeOffset GetUtcNow()=>Now;}
public static async Task Run()
{
void Check(bool value,string message){if(!value)throw new Exception(message);}
var clock=new Clock();var store=new NativePresenceStore(clock);var instance=Guid.NewGuid();var session=Guid.NewGuid();var manuscript=Guid.NewGuid();long sequence=0;
NativePresence State(bool capable=true,long revision=2)=>new(){BookId=12,ManuscriptId=manuscript,Revision=revision,Sequence=++sequence,WordSaved=true,WordAvailable=true,CanAcknowledgeNavigation=capable,DocumentTitle="Disposable document"};
void Put(NativePresence p)=>Check(store.Put(7,"grant",clock.Now.AddHours(1),instance,session,p),"heartbeat");
Put(State(false));var id=Guid.NewGuid();Check(!store.Navigate(7,12,instance,session,manuscript,2,100,true,id,true),"old clients cannot promise confirmed navigation");
Put(State());Check(store.Navigate(7,12,instance,session,manuscript,2,100,true,id,true),"exact capable saved document accepts explicit navigation");Check(store.NavigationState(7,12,instance,session,id)=="requested","queued is not completed");Check(!store.Navigate(7,12,instance,session,manuscript,2,200,true,Guid.NewGuid(),true),"another window cannot replace pending navigation");
var command=store.TakeNavigation(7,"grant",instance,session)!;Check(command.Id==id&&command.ManuscriptId==manuscript&&command.BookId==12,"wire command carries exact identity and expiry");Check(NavigationPolicy.Current(command,session,2,manuscript,clock.Now.UtcDateTime,true)&&!NavigationPolicy.Current(command,session,2,Guid.NewGuid(),clock.Now.UtcDateTime,true)&&!NavigationPolicy.Current(command,session,2,manuscript,clock.Now.UtcDateTime,false),"adapter rejects replaced or unsaved document");Check(!NavigationPolicy.Current(command,session,3,manuscript,clock.Now.UtcDateTime,true)&&!NavigationPolicy.Current(command,Guid.NewGuid(),2,manuscript,clock.Now.UtcDateTime,true),"adapter rejects revision and session changes");
var wrong=State();wrong.NavigationAcknowledgedId=Guid.NewGuid();wrong.NavigationResult="completed";Put(wrong);Check(store.NavigationState(7,12,instance,session,id)=="requested","uncorrelated ack ignored");var ack=State();ack.NavigationAcknowledgedId=id;ack.NavigationResult="completed";Put(ack);Check(store.NavigationState(7,12,instance,session,id)=="completed","only matching authenticated native ack completes");Check(store.NavigationState(8,12,instance,session,id)==null&&store.NavigationState(7,13,instance,session,id)==null,"receipt author/book isolation");
id=Guid.NewGuid();Check(store.Navigate(7,12,instance,session,manuscript,2,100,true,id,true),"next explicit request");clock.Now=clock.Now.AddSeconds(26);Check(store.TakeNavigation(7,"grant",instance,session)==null&&store.NavigationState(7,12,instance,session,id)=="timed-out","expired queue cannot execute later");Check(!NavigationPolicy.Current(command,session,2,manuscript,clock.Now.UtcDateTime,true),"UI queue expiry enforced");Put(State());id=Guid.NewGuid();Check(store.Navigate(7,12,instance,session,manuscript,2,100,true,id,true),"reconnect request");Put(State(revision:3));Check(store.TakeNavigation(7,"grant",instance,session)==null&&store.NavigationState(7,12,instance,session,id)=="invalidated","changed revision invalidates old queue and receipt");
// Exercise actual authorised chapter/scene resolver with procedure proxies: any unexpected call fails.
store.Remove(7,"grant",instance,session);Put(State());var heading=Guid.NewGuid();var scene=Guid.NewGuid();var snapshot=new ParagraphManuscript{BookId=12,ManuscriptId=manuscript,SessionId=session,WordRevision=2,Revision=5,Chapters=[new(){CanonicalId=21,HeadingId=heading}],Scenes=[new(){Id=scene,CanonicalId=31,ChapterId=21}],Paragraphs=[new(){PositionVerified=true,Occurrence=new(){Id=heading,Start=0}},new(){PositionVerified=true,Story=true,SceneId=scene,Occurrence=new(){Id=Guid.NewGuid(),Start=100,Ordinal=1}}]};
var access=NativeWorkflowTests.Proxy<IWordCompanionRepository>((n,a)=>n=="GetBookStructureAsync"?Task.FromResult<WordCompanionBookStructureResponse?>(new(){BookId=12,Chapters=[new(){ChapterId=21,Scenes=[new(){SceneId=31}]}]}):throw new Exception(n));
var repo=NativeWorkflowTests.Proxy<IParagraphManuscriptRepository>((n,a)=>n switch{"Get"=>Task.FromResult<ParagraphManuscript?>(snapshot),"Position"=>Task.FromResult<ParagraphPosition?>(new(){HasSnapshot=true,Revision=5,ChapterID=21,SceneID=(int)a![5]! ==100?31:null}),_=>throw new Exception(n)});
var checkpoints=NativeWorkflowTests.Proxy<IChapterSyncRepository>((n,a)=>throw new Exception("unexpected checkpoint operation "+n));var service=new WriterWordService(null!,access,repo,checkpoints,store);
Check(!await service.Navigate(7,12,99,null,instance,session,manuscript,2,Guid.NewGuid()),"foreign chapter rejected before native queue");Check(!await service.Navigate(7,12,21,999,instance,session,manuscript,2,Guid.NewGuid()),"foreign scene rejected");Check(await service.Navigate(7,12,21,null,instance,session,manuscript,2,Guid.NewGuid()),"authorised exact canonical chapter heading navigates without scene guesses");
var queued=store.TakeNavigation(7,"grant",instance,session)!;var completed=State();completed.NavigationAcknowledgedId=queued.Id;completed.NavigationResult="completed";Put(completed);
var sceneRequest=Guid.NewGuid();Check(await service.Navigate(7,12,21,31,instance,session,manuscript,2,sceneRequest),"verified canonical scene start navigates without title matching");store.TakeNavigation(7,"grant",instance,session);completed=State();completed.NavigationAcknowledgedId=sceneRequest;completed.NavigationResult="completed";Put(completed);
var modern=State();modern.CanChapterSync=true;Put(modern);bool currentCheckpoint=false;
var liveCheckpoints=NativeWorkflowTests.Proxy<IChapterSyncRepository>((n,a)=>n switch{
"List"=>Task.FromResult<IReadOnlyList<ChapterLiveValidation>>([new(){ChapterID=21,SessionID=session,WordRevision=2,StartPosition=200}]),
"Position"=>Task.FromResult<ParagraphPosition?>(new(){HasSnapshot=true,Revision=currentCheckpoint?5:4,ChapterID=21}),_=>throw new Exception(n)});
service=new WriterWordService(null!,access,repo,liveCheckpoints,store);Check(!await service.Navigate(7,12,21,null,instance,session,manuscript,2,Guid.NewGuid()),"list row alone cannot navigate with stale accepted checkpoint hashes");currentCheckpoint=true;Check(await service.Navigate(7,12,21,null,instance,session,manuscript,2,Guid.NewGuid()),"reopened chapter uses checked live position rather than old absolute heading offset");
var watch=System.Diagnostics.Stopwatch.StartNew();for(int i=0;i<10000;i++)Check(NavigationPolicy.Current(command,session,2,manuscript,command.ExpiresUtc.AddSeconds(-1),true),"navigation fence");watch.Stop();Console.WriteLine($"MEASURE 10000 navigation execution gates: {watch.Elapsed.TotalMilliseconds:F2}ms; pure managed checks, no Word/COM benchmark.");
}
}

View File

@ -40,7 +40,7 @@ public sealed class ManuscriptReaderController(ManuscriptReaderService reader, I
{
if (bookId <= 0 || chapterId <= 0 || knownVersion is null || knownVersion.Length != 64) return NotFound();
var change = await reader.Check(user, bookId, chapterId, knownRevision, knownVersion);
return change is null ? NotFound() : Json(new { revision = change.Revision.ToString(System.Globalization.CultureInfo.InvariantCulture), changed = change.Changed, version = change.Version });
return change is null ? NotFound() : Json(new { revision = change.Revision.ToString(System.Globalization.CultureInfo.InvariantCulture), changed = change.Changed, version = change.Version,lastSuccessfulSyncUtc=change.LastSuccessfulSyncUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ"),snapshotCapturedUtc=change.SnapshotCapturedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ") });
});
[HttpGet("chapter")]

View File

@ -37,7 +37,7 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC
if(!presence.Put(Author,Grant,Expires,instance,session,input))return Conflict(new{message="Stale, revoked or invalid native session."});
if(before==null||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.WordSaved!=input.WordSaved||before.Position.Revision!=input.Revision)
logger?.LogInformation("Native cursor observation User={User} Book={Book} Instance={Instance} Session={Session} Sequence={Sequence} Manuscript={Manuscript} WordRevision={WordRevision} Saved={Saved} Cursor={Cursor} Chapter={Chapter} Scene={Scene} ParagraphSnapshot={HasSnapshot} ParagraphRevision={ParagraphRevision}; observation does not request navigation",Author,input.BookId,instance,session,input.Sequence,input.ManuscriptId,input.Revision,input.WordSaved,input.CursorStart,input.ChapterId,input.SceneId,paragraphPosition?.HasSnapshot,paragraphPosition?.Revision);
if(live!=null&&(before==null||before.Position.BookId!=input.BookId||before.Position.ManuscriptId!=input.ManuscriptId||before.Position.Revision!=input.Revision||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.Active!=input.Active||before.Position.WordAvailable!=input.WordAvailable||before.Position.WordRunning!=input.WordRunning||before.Position.WordSaved!=input.WordSaved||before.Position.CaptureRequestId!=input.CaptureRequestId||before.Position.CaptureProgress/5!=input.CaptureProgress/5))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted);
if(live!=null&&(before==null||before.Position.NavigationAcknowledgedId!=input.NavigationAcknowledgedId||before.Position.ParagraphRevision!=input.ParagraphRevision||before.Position.BookId!=input.BookId||before.Position.ManuscriptId!=input.ManuscriptId||before.Position.Revision!=input.Revision||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.Active!=input.Active||before.Position.WordAvailable!=input.WordAvailable||before.Position.WordRunning!=input.WordRunning||before.Position.WordSaved!=input.WordSaved||before.Position.CaptureRequestId!=input.CaptureRequestId||before.Position.CaptureProgress/5!=input.CaptureProgress/5))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted);
if(input.CaptureRequestId.HasValue&&capture!=null&&wizard!=null){var progress=await capture.Progress(Author,Grant,input.CaptureRequestId.Value,input.CaptureProgress,instance,session,input.ManuscriptId,input.Revision);if(progress!=null)await wizard.Clients.Group(WordCompanionFollowHub.PresenceGroup(Author)).SendAsync("OnboardingScanProgress",progress,HttpContext.RequestAborted);}
if(input.CanParagraphSync&&!input.CanChapterSync&&capture!=null){var lease=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session);if(lease!=null)await capture.ObserveParagraphSave(Author,lease);}
if(input.CanChapterSync&&input.ChapterIssue=="needs_review"){

View File

@ -31,19 +31,38 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB
public async Task<IActionResult> ImportCommit(string confirmation,bool confirm,[FromServices] NativeImportService importer)
{if(!confirm)return BadRequest("Explicit import confirmation is required.");try{return View(await importer.Commit(Author,confirmation));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return Conflict(e.Message);}catch(Microsoft.Data.SqlClient.SqlException){return Conflict("Import could not commit. Review decisions are preserved. Preview again; existing story data has not been replaced.");}}
[HttpGet("status")]
public async Task<IActionResult> Status([FromServices] IParagraphManuscriptRepository? paragraphs=null,[FromServices] NativeManuscriptCapture? capture=null)
public async Task<IActionResult> Status([FromServices] IParagraphManuscriptRepository? paragraphs=null,[FromServices] NativeManuscriptCapture? capture=null,int? writerBookId=null,int? writerChapterId=null,[FromServices] PlotLine.Services.Writer.WriterWordService? writerWords=null)
{
Response.Headers.CacheControl="no-store";var leases=presence.Read(Author,0);var allowed=new HashSet<int>{0};
foreach(var book in leases.Select(l=>l.Position.BookId).Where(b=>b>0).Distinct())if(await access.GetBookStructureAsync(book,Author)!=null)allowed.Add(book);
var snapshots=new Dictionary<int,ParagraphSyncStatus?>();
if(paragraphs!=null)foreach(var book in leases.Where(l=>l.Position.WordAvailable&&allowed.Contains(l.Position.BookId)&&l.Position.BookId>0).Select(l=>l.Position.BookId).Distinct())snapshots[book]=await paragraphs.Status(Author,book);
return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.Revision,l.Position.ManuscriptId,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,l.Position.ChapterIssue,l.Position.CanChapterSync,chapterProgress=presence.ChapterProgress(Author,l.Position.BookId,l.Instance,l.Session,l.Position.Revision),l.Position.CanParagraphSync,l.Position.CaptureRequestId,l.Position.CaptureProgress,
var result=leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{l.Position.CanAcknowledgeNavigation,chapterTitle=l.Position.ChapterTitle,sceneTitle=l.Position.SceneTitle,instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.Revision,l.Position.ManuscriptId,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,l.Position.ChapterIssue,l.Position.CanChapterSync,chapterProgress=presence.ChapterProgress(Author,l.Position.BookId,l.Instance,l.Session,l.Position.Revision),l.Position.CanParagraphSync,l.Position.CaptureRequestId,l.Position.CaptureProgress,
paragraphTransfer=capture?.ParagraphTransferStatus(Author,l.Position.BookId,l.Instance,l.Session),
positionVerified=l.Position.WordSaved==true&&(!(l.Position.CanChapterSync||l.Position.CanParagraphSync)||l.Position.ParagraphRevision>0)&&l.Position.ChapterId.HasValue,
snapshotRevision=snapshots.GetValueOrDefault(l.Position.BookId)?.Revision,
mappingCurrent=snapshots.GetValueOrDefault(l.Position.BookId) is {} saved&&saved.ManuscriptId==l.Position.ManuscriptId&&saved.SessionId==l.Session&&saved.WordRevision==l.Position.Revision,
positionMessage=l.Position.WordSaved==false?"Save Word before verifying its scene mapping":l.Position.SceneId.HasValue?null:l.Position.CanChapterSync?(l.Position.ChapterIssue=="needs_review"?"Chapter reading needs review or retry; accepted mappings are preserved":l.Position.ChapterId.HasValue?"Current paragraph is checked but has no scene assignment; move into scene prose":"Checking the current chapter for this Word session; saved scenes remain available"):snapshots.GetValueOrDefault(l.Position.BookId) is {} snapshot?(snapshot.ManuscriptId!=l.Position.ManuscriptId?"This Word document does not match the book's saved manuscript identity":snapshot.SessionId!=l.Session||snapshot.WordRevision!=l.Position.Revision?"Word reopened or changed; synchronise from Word to verify this session's paragraph positions":snapshot.Paused?"Scene mapping is unresolved; synchronisation is paused while existing book processing finishes":"Current paragraph has no verified scene assignment") : "Synchronise from Word to establish a verified paragraph mapping",
updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
updated=l.Updated,expires=l.Updated.AddSeconds(45)}).ToArray();
if(writerBookId.HasValue)
{
if(writerBookId<=0||writerChapterId is <=0||writerWords==null)return NotFound();
var writerStructure=await access.GetBookStructureAsync(writerBookId.Value,Author);
if(writerStructure==null||writerChapterId.HasValue&&!writerStructure.Chapters.Any(c=>c.ChapterId==writerChapterId))return NotFound();
var metadata=await writerWords.Metadata(Author,writerBookId.Value,writerChapterId);
var verified=new List<object>();
foreach(var lease in leases.Where(l=>l.Position.BookId==writerBookId))
{
var position=await writerWords.Position(Author,lease,metadata);
if(position?.ChapterID is not int chapter)continue;
var selected=writerStructure.Chapters.FirstOrDefault(c=>c.ChapterId==chapter);
if(selected==null)continue;
verified.Add(new{instanceId=lease.Instance,sessionId=lease.Session,chapterId=chapter,sceneId=position.SceneID,
chapterTitle=selected.Title,sceneTitle=selected.Scenes.FirstOrDefault(s=>s.SceneId==position.SceneID)?.Title});
}
return Json(new{leases=result,bookId=writerBookId,chapterId=writerChapterId,canonical=metadata==null?null:new{metadata.ManuscriptID,revision=metadata.Revision.ToString(System.Globalization.CultureInfo.InvariantCulture),snapshotUtc=metadata.SnapshotUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ"),chapterAcceptedUtc=metadata.ChapterAcceptedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ")},verifiedPositions=verified});
}
return Json(result);
}
[HttpGet("reviews/{id:guid}")]
public async Task<IActionResult> Review(Guid id)

View File

@ -0,0 +1,28 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Data;
using PlotLine.Services.Writer;
using PlotLine.Services.NativeCompanion;
namespace PlotLine.Controllers;
[Authorize]
public sealed class WriterWordController(WriterWordService words,IWordCompanionRepository access,NativePresenceStore presence):Controller
{
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpPost,ValidateAntiForgeryToken]
public async Task<IActionResult> Navigate(int bookId,int chapterId,int? sceneId,Guid instanceId,Guid sessionId,Guid manuscriptId,long revision,Guid navigationId)
{
Response.Headers.CacheControl="no-store";
if(!ModelState.IsValid||bookId<=0||chapterId<=0||sceneId is <=0||instanceId==Guid.Empty||sessionId==Guid.Empty||manuscriptId==Guid.Empty||navigationId==Guid.Empty||revision<0)return BadRequest();
if(await access.GetBookStructureAsync(bookId,Author)==null)return NotFound();
try { return await words.Navigate(Author,bookId,chapterId,sceneId,instanceId,sessionId,manuscriptId,revision,navigationId)?Accepted(new{navigationId,message="Requested in Word; waiting for confirmation."}):Conflict(new{message="This Word document or chapter position is not currently verified, or Word is busy. Check Companion and try again. Nothing was moved."}); }
catch(UnauthorizedAccessException){return NotFound();}
catch(Microsoft.Data.SqlClient.SqlException e) when(e.Number==51000){return NotFound();}
catch(Exception e) when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){return StatusCode(503,new{message="Word navigation is temporarily unavailable. Your saved work is retained."});}
}
[HttpGet]
public async Task<IActionResult> Navigation(int bookId,Guid instanceId,Guid sessionId,Guid navigationId)
{
Response.Headers.CacheControl="no-store";if(await access.GetBookStructureAsync(bookId,Author)==null)return NotFound();var state=presence.NavigationState(Author,bookId,instanceId,sessionId,navigationId);return state==null?NotFound():Json(new{state});
}
}

View File

@ -0,0 +1,36 @@
---
title: Word and Your Writing Focus
category: Workspace
tags: writer, Word, companion, manuscript, connection, reader
contextKey: writer3.word
micro: Keep your working focus separate from Word's verified chapter; move Word only when you choose.
quickTitle: Your manuscript in Word
quickSummary: Check the correct document and verified position. Open this chapter in Word waits for Word's confirmation. Accepted Reader content may lag later edits.
screenshot:
---
# Connect the correct manuscript
Open Word Companion, sign in to Development and associate the manuscript with the correct book. Writer uses the same connection information as the existing connection control. If several manuscripts for this book are open, choose one explicitly. A document name alone is not verification. Disconnected, uncertain or unsaved documents cannot receive confirmed navigation. Install the matched Word add-in and agent update to enable this feature; a web release alone does not update Windows software.
# Your focus and Word's position
Your saved working chapter or scene, the actual chapter in Word, your recording target and the Reader chapter can differ. This is valid. Moving Word does not save a new working focus, start or end a session, change a pinned Context reference or retarget Intent. Existing explicitly selected follow modes remain authoritative.
# Open a chapter or scene in Word
Choose Open this chapter in Word. PlotDirector checks your access, the exact connected document and its verified chapter start. It does not guess positions from titles or ordering. Open this scene uses a verified saved scene start when available; an unresolved scene remains available for metadata editing, but cannot be navigated safely. Synchronise or check it in Companion before retrying.
Requested means the command was sent for the selected document. Only Word confirmed navigation means Word acknowledged the selection. Timeout, changed document, stale mapping or disconnection leaves completion unconfirmed. Inspect Word before retrying. Navigation never forces a save, opens a replacement document, imports a manuscript or changes a session. Word may select the target range in its document window; normal Windows foreground behaviour requires physical qualification.
# Accepted content and updates
A local save is not confirmation that PlotDirector accepted the changes. Writer shows the last reported checking state and accepted chapter/snapshot time when available. Later edits may still be pending, including unsaved edits. Check connection & updates refreshes reported information. Check saved manuscript explicitly requests the existing bounded saved-manuscript check; it does not force a save or bypass author decisions. Detailed recovery remains in Companion and the existing connection/structure tools.
Reader contains accepted prose. Its existing update policy retains selected text, Focused Reading and paragraph anchors where possible; pause automatic updates for uninterrupted reading or apply the discreet available update. Previous/Next retain Focused Reading. Reader navigation never moves Word.
# Return and recover
Return to Writer in Companion opens your saved working focus through the existing authenticated launcher. A verified Word-origin chapter can be adopted only through the explicit Use Word chapter as working focus action. Merely opening a link does not change it. A stale origin is never treated as proof.
If Word closes, the agent restarts or another document replaces it, wait for current verification. Timed-out navigation is not replayed against another manuscript. Keep your return notes and any inline text; they remain independent. Reopen the correct manuscript and use the existing Companion sign-in/check/recovery controls. Context and Intent can remain in separate windows or monitors with their own follow/pinned selections.

View File

@ -40,3 +40,7 @@ A saved focus is shown on return; use Change working focus to edit it. During an
With a saved chapter/scene focus, Write now shows existing intentions and optional inline editors for chapter purpose/summary/goals, scene purpose/outcome, scene notes, reminders and working details. Save and Cancel affect one section at a time. Failed or stale saves retain text, and navigation warns about unsaved inline edits. Opening Write does not initialise missing goals, workflow or checklists. Whole-manuscript focus remains supported.
The companion shows concise saved references rather than inferred story facts. Full specialist tools, attachments management and standalone Context/Intent remain available. The Intentions and Reminders Help icon explains field scope, stale-update handling and the distinction between scene notes, chapter goals and session return notes.
# Word continuity
Your manuscript in Word distinguishes the selected working focus from the exact verified Word position. Explicit chapter/scene navigation waits for acknowledgement and never starts a session or forces a save. Check saved manuscript uses the existing bounded check; Reader retains accepted prose and may lag later edits. See Word and Your Writing Focus for document selection, disconnected recovery and returning from Companion.

View File

@ -199,6 +199,7 @@ public class Program
builder.Services.AddScoped<IImportRepository, ImportRepository>();
builder.Services.AddScoped<IWordCompanionRepository, WordCompanionRepository>();
builder.Services.AddScoped<WritingActivityRepository>();
builder.Services.AddScoped<PlotLine.Services.Writer.WriterWordService>();
builder.Services.AddScoped<PlotLine.Services.Writer.IWriterAuthoringService, PlotLine.Services.Writer.WriterAuthoringService>();
builder.Services.AddScoped<WriterObjectiveRepository>();
builder.Services.AddScoped<WriterWorkRepository>();

View File

@ -42,7 +42,7 @@ public sealed class ManuscriptReaderModel
// Read only: deliberately bypasses the manuscript workspace, which may bootstrap tracking.
public sealed class ManuscriptReaderService(
IParagraphManuscriptRepository manuscripts, IBookRepository books, IChapterRepository chapters)
IParagraphManuscriptRepository manuscripts, IBookRepository books, IChapterRepository chapters, PlotLine.Services.Writer.WriterWordService? wordMetadata=null)
{
public async Task<ManuscriptReaderModel?> Read(int user, int bookId, int? chapterId)
{
@ -66,9 +66,9 @@ public sealed class ManuscriptReaderService(
var chapter = await chapters.GetAsync(chapterId);
if (book is null || book.IsArchived || chapter is null || chapter.IsArchived || chapter.BookID != bookId) return null;
var revision = status?.Revision ?? -1;
if (revision == knownRevision) return new(revision, false, knownVersion);
if (revision == knownRevision) { var metadata=wordMetadata==null?null:await wordMetadata.Metadata(user,bookId,chapterId);return new(revision,false,knownVersion,metadata?.ChapterAcceptedUtc,metadata?.SnapshotUtc); }
var model = await Read(user, bookId, chapterId);
return model is null ? null : new(model.Revision, model.ContentVersion != knownVersion, model.ContentVersion);
return model is null ? null : new(model.Revision, model.ContentVersion != knownVersion, model.ContentVersion,model.LastSuccessfulSyncUtc,model.SnapshotCapturedUtc);
}
public static ManuscriptReaderModel Project(Book book, IReadOnlyList<Chapter> ordered, Chapter? selected, ParagraphManuscript? state)
@ -111,4 +111,4 @@ public sealed class ManuscriptReaderService(
}
}
public sealed record ReaderChange(long Revision, bool Changed, string Version);
public sealed record ReaderChange(long Revision, bool Changed, string Version,DateTime? LastSuccessfulSyncUtc=null,DateTime? SnapshotCapturedUtc=null);

View File

@ -9,8 +9,10 @@ public sealed class NativePresenceStore(TimeProvider clock)
public void BooksChanged(int user){lock(gate){if(catalogs.Count>=4096)catalogs.Clear();catalogs[user]=Guid.NewGuid();}}
private readonly Dictionary<(int,Guid,Guid),AdapterCommand> navigation=[];
private readonly Dictionary<(int,Guid,Guid,Guid),(DateTimeOffset Expires,long Revision,int Start)> navigationReceipts=[];
private readonly Dictionary<(int,Guid,Guid,Guid),NavigationOutcome> outcomes=[];
public sealed record NavigationOutcome(int Book,Guid Manuscript,long Revision,string Grant,DateTimeOffset Expires,string State);
private readonly object gate=new();private readonly Dictionary<(int,Guid,Guid),NativeLease> leases=[];private readonly Dictionary<string,DateTimeOffset> revoked=[];
private void Prune(){var now=clock.GetUtcNow();foreach(var receipt in navigationReceipts.Where(p=>p.Value.Expires<=now).Select(p=>p.Key).ToArray())navigationReceipts.Remove(receipt);foreach(var key in leases.Where(p=>now-p.Value.Updated>=TimeSpan.FromSeconds(45)||p.Value.GrantExpires<=now).Select(p=>p.Key).ToArray()){leases.Remove(key);navigation.Remove(key);}foreach(var key in revoked.Where(p=>p.Value<=now).Select(p=>p.Key).ToArray())revoked.Remove(key);}
private void Prune(){var now=clock.GetUtcNow();foreach(var key in outcomes.Where(p=>p.Value.Expires.AddMinutes(2)<now).Select(p=>p.Key).ToArray())outcomes.Remove(key);foreach(var receipt in navigationReceipts.Where(p=>p.Value.Expires<=now).Select(p=>p.Key).ToArray())navigationReceipts.Remove(receipt);foreach(var key in leases.Where(p=>now-p.Value.Updated>=TimeSpan.FromSeconds(45)||p.Value.GrantExpires<=now).Select(p=>p.Key).ToArray()){leases.Remove(key);navigation.Remove(key);}foreach(var key in revoked.Where(p=>p.Value<=now).Select(p=>p.Key).ToArray())revoked.Remove(key);}
private readonly Dictionary<(int User,int Book,Guid Manuscript,Guid Session,long Revision),(int End,(int Start,int Chapter,int? Scene)[] Items)> mappings=[];
public void Map(int user,int book,Guid manuscript,Guid session,long revision,int end,(int Start,int Chapter,int? Scene)[] items){lock(gate){if(items.Length>8192)return;foreach(var key in mappings.Keys.Where(k=>k.User==user&&k.Session==session).ToArray())mappings.Remove(key);if(mappings.Count>=64)mappings.Remove(mappings.Keys.First());mappings[(user,book,manuscript,session,revision)]=(end,items);}}
public (int Chapter,int? Scene)? Resolve(int user,NativePresence position,Guid session){lock(gate){if(position.WordSaved!=true||!position.CursorStart.HasValue||!mappings.TryGetValue((user,position.BookId,position.ManuscriptId,session,position.Revision),out var map)||position.CursorStart<0||position.CursorStart>=map.End)return null;var boundary=map.Items.LastOrDefault(i=>i.Start<=position.CursorStart);return boundary.Chapter>0?(boundary.Chapter,boundary.Scene):null;}}
@ -19,11 +21,14 @@ public sealed class NativePresenceStore(TimeProvider clock)
lock(gate){Prune();var key=(user,instance,session);if(instance==Guid.Empty||session==Guid.Empty||(value.WordAvailable&&value.ManuscriptId==Guid.Empty)||(value.ChapterIssue is not ("" or "needs_review"))||value.Revision<0||value.Sequence<=0||value.BookId<0||value.DocumentTitle==null||value.DocumentTitle.Length>260||value.DocumentTitle.IndexOfAny(['\\','/'])>=0||expires<=clock.GetUtcNow()||revoked.ContainsKey(grant))return false;
if(leases.TryGetValue(key,out var prior)){if(prior.Grant!=grant||value.Sequence<=prior.Position.Sequence||value.Revision<prior.Position.Revision)return false;}
else if(leases.Count>=4096||leases.Values.Count(p=>p.User==user)>=64)return false;
leases[key]=new(user,grant,expires,instance,session,new NativePresence{ChapterIssue=value.ChapterIssue,ChapterTitle=value.ChapterTitle,SceneTitle=value.SceneTitle,CanChapterSync=value.CanChapterSync,CaptureRequestId=value.CaptureRequestId,CaptureProgress=value.CaptureProgress,ParagraphRevision=value.ParagraphRevision,CanCapture=value.CanCapture,CanParagraphSync=value.CanParagraphSync,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordRunning=value.WordRunning,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;}
foreach(var pending in outcomes.Where(p=>p.Key.Item1==user&&p.Key.Item2==instance&&p.Key.Item3==session&&p.Value.State=="requested"&&(p.Value.Revision!=value.Revision||p.Value.Book!=value.BookId||p.Value.Manuscript!=value.ManuscriptId)).ToArray())outcomes[pending.Key]=pending.Value with{State="invalidated"};
leases[key]=new(user,grant,expires,instance,session,new NativePresence{CanAcknowledgeNavigation=value.CanAcknowledgeNavigation,NavigationAcknowledgedId=value.NavigationAcknowledgedId,NavigationResult=value.NavigationResult,ChapterIssue=value.ChapterIssue,ChapterTitle=value.ChapterTitle,SceneTitle=value.SceneTitle,CanChapterSync=value.CanChapterSync,CaptureRequestId=value.CaptureRequestId,CaptureProgress=value.CaptureProgress,ParagraphRevision=value.ParagraphRevision,CanCapture=value.CanCapture,CanParagraphSync=value.CanParagraphSync,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordRunning=value.WordRunning,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());
if(value.NavigationAcknowledgedId is Guid ack&&outcomes.TryGetValue((user,instance,session,ack),out var op)&&op.Grant==grant&&op.Book==value.BookId&&op.Manuscript==value.ManuscriptId&&op.Revision==value.Revision&&op.Expires>clock.GetUtcNow()&&op.State=="requested"&&value.NavigationResult is "completed" or "failed")outcomes[(user,instance,session,ack)]=op with{State=value.NavigationResult};
return true;}
}
public NativeLease[] Read(int user,int book){lock(gate){Prune();return leases.Values.Where(p=>p.User==user&&(book==0||p.Position.BookId==book)).OrderByDescending(p=>p.Updated).ToArray();}}
public bool Navigate(int user,int book,Guid instance,Guid session,Guid manuscript,long revision,int start,bool requireSaved=false,Guid? navigationId=null)
{lock(gate){Prune();var key=(user,instance,session);if(!leases.TryGetValue(key,out var lease)||!lease.Position.WordAvailable||lease.Position.BookId!=book||lease.Position.ManuscriptId!=manuscript||lease.Position.Revision!=revision||(requireSaved&&lease.Position.WordSaved!=true)||start<0||(navigation.TryGetValue(key,out var queued)&&queued.Kind!="navigate"))return false;var id=navigationId??Guid.NewGuid();if(id==Guid.Empty)return false;var receipt=(user,instance,session,id);if(navigationReceipts.TryGetValue(receipt,out var prior))return prior.Revision==revision&&prior.Start==start;if(navigationReceipts.Count>=8192)return false;navigationReceipts[receipt]=(clock.GetUtcNow().AddMinutes(15),revision,start);navigation[key]=new(){Id=id,Kind="navigate",SessionId=session,Revision=revision,Chapter=new(){Start=start}};return true;}}
public bool Navigate(int user,int book,Guid instance,Guid session,Guid manuscript,long revision,int start,bool requireSaved=false,Guid? navigationId=null,bool requireAcknowledgement=false)
{lock(gate){Prune();var key=(user,instance,session);if(!leases.TryGetValue(key,out var lease)||!lease.Position.WordAvailable||lease.Position.BookId!=book||lease.Position.ManuscriptId!=manuscript||lease.Position.Revision!=revision||(requireSaved&&lease.Position.WordSaved!=true)||start<0||(requireAcknowledgement&&!lease.Position.CanAcknowledgeNavigation)||(outcomes.Any(p=>p.Key.Item1==user&&p.Key.Item2==instance&&p.Key.Item3==session&&p.Key.Item4!=navigationId&&p.Value.State=="requested"&&p.Value.Expires>clock.GetUtcNow()))||(navigation.TryGetValue(key,out var queued)&&queued.Kind!="navigate"))return false;var id=navigationId??Guid.NewGuid();if(id==Guid.Empty)return false;var receipt=(user,instance,session,id);if(navigationReceipts.TryGetValue(receipt,out var prior))return prior.Revision==revision&&prior.Start==start;if(navigationReceipts.Count>=8192)return false;navigationReceipts[receipt]=(clock.GetUtcNow().AddMinutes(15),revision,start);if(requireAcknowledgement){if(outcomes.Count>=8192)return false;outcomes[receipt]=new(book,manuscript,revision,lease.Grant,clock.GetUtcNow().AddSeconds(25),"requested");}navigation[key]=new(){Id=id,BookId=book,ManuscriptId=manuscript,ExpiresUtc=clock.GetUtcNow().AddSeconds(25).UtcDateTime,Kind="navigate",SessionId=session,Revision=revision,Chapter=new(){Start=start}};return true;}}
public void RequestCancellation(int user,NativeLease selected){lock(gate){var key=(user,selected.Instance,selected.Session);if(leases.TryGetValue(key,out var current)&&current.Grant==selected.Grant&&current.Position.Revision==selected.Position.Revision)navigation[key]=new(){Kind="cancel",SessionId=selected.Session,Revision=selected.Position.Revision};}}
private readonly Dictionary<Guid,(int User,int Book,Guid Instance,Guid Session,long Revision,string Grant,DateTimeOffset Expires)> chapterRepairs=[];private readonly HashSet<Guid> cancelledChapterRepairs=[];
private readonly Dictionary<(int User,int Book,Guid Instance,Guid Session,long Revision),PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress> chapterProgress=[];
@ -41,7 +46,8 @@ public sealed class NativePresenceStore(TimeProvider clock)
public bool RequestCapture(int user,NativeLease selected,Guid request,int book=0,bool paragraphs=false,bool synchronise=false,long baseRevision=0,string baseHash="")
{lock(gate){Prune();var key=(user,selected.Instance,selected.Session);if(!leases.TryGetValue(key,out var lease)||lease.Grant!=selected.Grant||lease.Position.Revision!=selected.Position.Revision||lease.Position.ManuscriptId!=selected.Position.ManuscriptId||(book>0&&lease.Position.BookId!=0&&lease.Position.BookId!=book)||!lease.Position.CanCapture||navigation.ContainsKey(key))return false;navigation[key]=new(){Id=request,BaseRevision=baseRevision,BaseSnapshotHash=baseHash,BookId=book,ParagraphTracking=paragraphs,Kind=synchronise?"paragraph-snapshot":"wizard-capture",SessionId=lease.Session,Revision=lease.Position.Revision};return true;}}
public AdapterCommand? TakeNavigation(int user,string grant,Guid instance,Guid session)
{lock(gate){Prune();var key=(user,instance,session);return leases.TryGetValue(key,out var lease)&&lease.Grant==grant&&navigation.Remove(key,out var command)?command:null;}}
{lock(gate){Prune();var key=(user,instance,session);return leases.TryGetValue(key,out var lease)&&lease.Grant==grant&&navigation.Remove(key,out var command)&&command.SessionId==session&&command.Revision==lease.Position.Revision&&(command.Kind!="navigate"||command.BookId==0||command.BookId==lease.Position.BookId)&&(command.Kind!="navigate"||command.ManuscriptId==Guid.Empty||command.ManuscriptId==lease.Position.ManuscriptId)&&(command.ExpiresUtc==default||command.ExpiresUtc>clock.GetUtcNow().UtcDateTime)?command:null;}}
public string? NavigationState(int user,int book,Guid instance,Guid session,Guid id){lock(gate){Prune();if(!outcomes.TryGetValue((user,instance,session,id),out var op)||op.Book!=book)return null;var lease=leases.GetValueOrDefault((user,instance,session));if(lease==null||lease.Grant!=op.Grant||lease.Position.BookId!=book||lease.Position.ManuscriptId!=op.Manuscript||lease.Position.Revision!=op.Revision)return "invalidated";return op.State=="requested"&&op.Expires<=clock.GetUtcNow()?"timed-out":op.State;}}
public void Remove(int user,string grant,Guid instance,Guid session,long? throughSequence=null){lock(gate)if(leases.TryGetValue((user,instance,session),out var prior)&&prior.Grant==grant&&(!throughSequence.HasValue||prior.Position.Sequence<=throughSequence.Value)){leases.Remove((user,instance,session));navigation.Remove((user,instance,session));}}
public void DisconnectGrant(int user,string grant){lock(gate)foreach(var key in leases.Where(p=>p.Value.User==user&&p.Value.Grant==grant).Select(p=>p.Key).ToArray()){leases.Remove(key);navigation.Remove(key);}}
public void Revoke(int user,string grant,DateTimeOffset expiry){lock(gate){Prune();if(revoked.Count<8192)revoked[grant]=expiry;foreach(var key in leases.Where(p=>p.Value.User==user&&p.Value.Grant==grant).Select(p=>p.Key).ToArray())leases.Remove(key);}}

View File

@ -85,6 +85,7 @@ public sealed class ProjectAccessFilter(IProjectAccessService access, ICurrentUs
["Scenarios"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "Scenario", ["scenarioId"] = "Scenario", ["projectId"] = "Project", ["bookId"] = "Book", ["sceneId"] = "Scene", ["anchorSceneId"] = "Scene", ["targetChapterId"] = "Chapter" },
["StoryAssets"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "StoryAsset", ["returnAssetId"] = "StoryAsset", ["projectId"] = "Project" },
["Timeline"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "TimelineViewPreset", ["projectId"] = "Project", ["bookId"] = "Book" },
["WriterWord"] = new(StringComparer.OrdinalIgnoreCase) { ["bookId"] = "Book", ["chapterId"] = "Chapter", ["sceneId"] = "Scene" },
["WriterAuthoring"] = new(StringComparer.OrdinalIgnoreCase) { ["bookId"] = "Book", ["chapterId"] = "Chapter", ["sceneId"] = "Scene" },
["Writer"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "Chapter", ["projectId"] = "Project" },
["Warnings"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "ContinuityWarning", ["projectId"] = "Project", ["bookId"] = "Book", ["sceneId"] = "Scene" },

View File

@ -0,0 +1,37 @@
using System.Data;
using Dapper;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services.NativeCompanion;
namespace PlotLine.Services.Writer;
public sealed class WriterWordMetadata
{
public Guid ManuscriptID{get;set;}public long Revision{get;set;}public DateTime? SnapshotUtc{get;set;}public DateTime? ChapterAcceptedUtc{get;set;}
}
public sealed class WriterWordService(ISqlConnectionFactory factory,IWordCompanionRepository access,IParagraphManuscriptRepository paragraphs,IChapterSyncRepository chapters,NativePresenceStore presence)
{
private static T? One<T>(IEnumerable<T> rows) where T:class {var candidates=rows.Take(2).ToArray();return candidates.Length==1?candidates[0]:null;}
public async Task<WriterWordMetadata?> Metadata(int user,int book,int? chapter){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<WriterWordMetadata>("dbo.WriterWord_Status",new{UserID=user,BookID=book,ChapterID=chapter},commandType:CommandType.StoredProcedure);}
public async Task<ParagraphPosition?> Position(int user,NativeLease lease,WriterWordMetadata? metadata){var p=lease.Position;if(p.WordSaved!=true||!p.WordAvailable||!p.CursorStart.HasValue||metadata?.ManuscriptID!=p.ManuscriptId)return null;var position=p.CanChapterSync?await chapters.Position(user,p.BookId,p.ManuscriptId,lease.Session,p.Revision,p.CursorStart.Value):await paragraphs.Position(user,p.BookId,p.ManuscriptId,lease.Session,p.Revision,p.CursorStart.Value);return position?.HasSnapshot==true&&position.Revision==metadata.Revision?position:null;}
public async Task<bool> Navigate(int user,int book,int chapter,int? scene,Guid instance,Guid session,Guid manuscript,long revision,Guid id)
{
var structure=await access.GetBookStructureAsync(book,user);var target=structure==null?null:One(structure.Chapters.Where(c=>c.ChapterId==chapter));if(target==null||scene.HasValue&&!target.Scenes.Any(s=>s.SceneId==scene))return false;
var lease=One(presence.Read(user,book).Where(l=>l.Instance==instance&&l.Session==session&&l.Position.ManuscriptId==manuscript&&l.Position.Revision==revision&&l.Position.WordAvailable&&l.Position.WordSaved==true&&l.Position.CanAcknowledgeNavigation));
if(lease==null)return false;
var state=await paragraphs.Get(user,book);if(state==null||state.ManuscriptId!=manuscript)return false;
int? start=null;
if(scene.HasValue){
var saved=One(state.Scenes.Where(s=>!s.Retired&&s.CanonicalId==scene&&s.ChapterId==chapter));var first=saved==null?null:state.Paragraphs.Where(p=>p.Story&&p.SceneId==saved.Id).OrderBy(p=>p.Occurrence.Ordinal).FirstOrDefault();
if(first?.PositionVerified!=true)return false;
if(lease.Position.CanChapterSync){var anchor=await chapters.SceneStart(user,book,scene.Value,first.Occurrence.Id,manuscript,session,revision);if(anchor?.Revision==state.Revision&&anchor.ChapterID==chapter&&anchor.SceneID==scene)start=anchor.StartPosition;}
else if(state.SessionId==session&&state.WordRevision==revision)start=first.Occurrence.Start;
}else if(lease.Position.CanChapterSync){
var live=One((await chapters.List(user,book,session,revision)).Where(c=>c.ChapterID==chapter&&c.SessionID==session&&c.WordRevision==revision));if(live!=null)start=live.StartPosition;
}else if(state.SessionId==session&&state.WordRevision==revision){var heading=One(state.Chapters.Where(c=>c.CanonicalId==chapter))?.HeadingId;start=One(state.Paragraphs.Where(p=>p.Occurrence.Id==heading&&p.PositionVerified))?.Occurrence.Start;}
if(!start.HasValue||start<0)return false;
// The live lookup joins current accepted checkpoint hashes and manuscript identity. A stale list is never proof.
var position=lease.Position.CanChapterSync?await chapters.Position(user,book,manuscript,session,revision,start.Value):await paragraphs.Position(user,book,manuscript,session,revision,start.Value);
if(position?.HasSnapshot!=true||position.Revision!=state.Revision||position.ChapterID!=chapter||scene.HasValue&&position.SceneID!=scene)return false;
return presence.Navigate(user,book,instance,session,manuscript,revision,start.Value,requireSaved:true,navigationId:id,requireAcknowledgement:true);
}
}

View File

@ -0,0 +1,14 @@
-- Read-only metadata projection; no paragraph payload or initialisation.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.WriterWord_Status @UserID int,@BookID int,@ChapterID int=NULL
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.IsArchived=0) THROW 51000,'Book access denied',1;
IF @ChapterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChapterID AND BookID=@BookID AND IsArchived=0) THROW 51000,'Chapter access denied',1;
SELECT m.ManuscriptID,m.Revision,m.UpdatedUtc AS SnapshotUtc,c.LastSuccessfulSyncUtc AS ChapterAcceptedUtc
FROM dbo.BookParagraphManuscripts m OUTER APPLY(SELECT TOP(1) LastSuccessfulSyncUtc FROM OPENJSON(m.Payload,'$.ChapterCheckpoints') WITH(ChapterID int '$.ChapterId',LastSuccessfulSyncUtc datetime2) WHERE ChapterID=@ChapterID) c
WHERE m.BookID=@BookID;
END;

View File

@ -7,7 +7,7 @@
<p id="native-presence-status" role="status">Checking Companion presence…</p>
<label for="native-session">Word document session</label><select id="native-session" class="form-select mb-2"><option value="">Choose a connected manuscript</option></select>
<p class="small text-muted">Connection diagnostics only. Open Context or Intent to follow the manuscript and navigate saved scenes.</p>
<nav class="d-flex gap-3"><a target="_blank" rel="noopener" href="/Books/Details/@Model.Book">Book workspace</a><a href="/manuscript/paragraphs?bookId=@Model.Book" target="_blank" rel="noopener">Manuscript structure and evidence</a><button class="btn btn-link p-0" type="button" data-native-open-role="Context">Open Context</button><button class="btn btn-link p-0" type="button" data-native-open-role="Intent">Open Intent</button></nav>
<nav class="d-flex gap-3"><a href="/Writer/Write?bookId=@Model.Book&amp;wordInstanceId=@Model.Instance&amp;wordSessionId=@Model.Session">Return to Writer working focus</a><a target="_blank" rel="noopener" href="/Books/Details/@Model.Book">Book workspace</a><a href="/manuscript/paragraphs?bookId=@Model.Book" target="_blank" rel="noopener">Manuscript structure and evidence</a><button class="btn btn-link p-0" type="button" data-native-open-role="Context">Open Context</button><button class="btn btn-link p-0" type="button" data-native-open-role="Intent">Open Intent</button></nav>
</div></div>
@if(Model.Mode=="book"){
<h2 class="h4 mt-4">AI chapter suggestions</h2><p>Generated by PlotDirector’s existing chapter-analysis service. Review titles and summaries before any import. Successful chapters remain available for 30 days.</p>

View File

@ -26,6 +26,7 @@
<script src="~/js/writing-workspace.js" asp-append-version="true"></script>
<script src="~/js/writing-workspace-launcher.js" asp-append-version="true"></script>
@if(Model.Destination == "Write"){
<script src="~/js/writer-word.js" asp-append-version="true"></script>
<script src="~/js/writer-authoring.js" asp-append-version="true"></script>
<script src="~/js/writer-focus.js" asp-append-version="true"></script>
<script src="~/js/writer-objective.js" asp-append-version="true"></script>

View File

@ -0,0 +1,20 @@
@model WriterDashboardViewModel
@{var focus=Model.Objective;}
<section class="writer3-word writer3-inset" data-writer-word data-book-id="@Model.BookID" data-chapter-id="@focus?.ChapterID" data-scene-id="@focus?.SceneID" data-status-url="/native-companion/status?writerBookId=@Model.BookID&amp;writerChapterId=@focus?.ChapterID" aria-label="Word Companion">
<div class="writer3-authoring-heading"><h3>Your manuscript in Word</h3><help-icon key="writer3.word" /></div>
<p data-word-state role="status">Checking Word Companion…</p>
<label data-word-choose hidden>Choose the manuscript in Word<select class="form-select" data-word-document><option value="">Choose a document</option></select></label>
<p class="writer3-caption" data-word-position>Word position has not been verified.</p>
<p class="writer3-caption" data-word-freshness>Your latest changes have not yet been confirmed in PlotDirector.</p>
<div class="button-row">
@if(focus?.ChapterID.HasValue==true){<button type="button" class="btn btn-sm btn-outline-primary" data-word-navigate disabled>Open this chapter in Word</button>@if(focus.SceneID.HasValue){<button type="button" class="btn btn-sm btn-outline-secondary" data-word-scene disabled>Open this scene in Word</button>}}
</div>
<details><summary>Connection and update options</summary><p class="writer3-caption">Working focus and Word position can differ. Navigation does not save Word or change your session. Reader shows accepted content.</p><div class="button-row"><button type="button" class="btn btn-sm btn-outline-secondary" data-word-sync disabled>Check saved manuscript</button><button type="button" class="btn btn-sm btn-outline-secondary" data-word-check>Check connection &amp; updates</button></div></details>
<p data-word-command role="status" aria-live="polite"></p>
<form method="post" asp-action="SaveObjective" asp-controller="Writer" data-word-adopt hidden>
<input type="hidden" name="BookID" value="@Model.BookID"/><input type="hidden" name="ChapterID"/><input type="hidden" name="SceneID"/><input type="hidden" name="Activity" value="@(focus?.Activity??"Drafting")"/>
<p data-word-origin></p><button type="submit" class="btn btn-sm btn-outline-secondary">Use Word chapter as working focus</button>
</form>
<div hidden data-word-token>@Html.AntiForgeryToken()</div>
</section>

View File

@ -25,7 +25,7 @@
@if(focus?.ChapterID.HasValue==true && !editing){<div class="writer3-authoring" data-writer-authoring data-inspect-url="@Url.Action("Inspect","WriterAuthoring",new{bookId=Model.BookID,chapterId=focus.ChapterID,sceneId=focus.SceneID})" aria-live="polite"><p>Loading your recorded intentions…</p></div>}
</section>
<aside class="writer3-panel writer3-reference" tabindex="0" aria-label="Writing tools">
<h2>Keep your story close</h2><div class="button-row writer3-window-actions"><button type="button" class="btn btn-sm btn-outline-secondary" data-open-writing-context>Open Context <span aria-hidden="true">↗</span></button><button type="button" class="btn btn-sm btn-outline-secondary" data-open-writing-intent>Open Intent <span aria-hidden="true">↗</span></button></div><p data-writing-workspace-message role="status"></p><div data-authoring-references></div><p>Open the existing tools when you need more detail.</p>
<h2>Keep your story close</h2><div class="button-row writer3-window-actions"><button type="button" class="btn btn-sm btn-outline-secondary" data-open-writing-context>Open Context <span aria-hidden="true">↗</span></button><button type="button" class="btn btn-sm btn-outline-secondary" data-open-writing-intent>Open Intent <span aria-hidden="true">↗</span></button></div><p data-writing-workspace-message role="status"></p><partial name="_WriterWord" model="Model" /><div data-authoring-references></div><p>Open the existing tools when you need more detail.</p>
<div class="writer3-link-list">
<a asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID" asp-fragment="chapters">Chapters &amp; scenes <span aria-hidden="true">↗</span></a>
@if(focus?.ChapterID.HasValue==true){<a asp-action="Chapter" asp-route-id="@focus.ChapterID">Chapter goals &amp; workflow <span aria-hidden="true">↗</span></a>}

View File

@ -188,6 +188,7 @@
const data = await fetchJson(url);
if (stopped || document.hidden) return;
revision = data.revision; observedVersion = data.version;
if (!pending() && (data.lastSuccessfulSyncUtc || data.snapshotCapturedUtc)) timestamps(data);
indicate();
await update();
} catch (error) {
@ -213,11 +214,12 @@
if (document.hidden) request?.abort();
else if (busy) resumePending = true; else void check();
});
on(window, 'native-companion-presence', event => { if (!busy && !stopped && (event.detail?.reconnected || event.detail?.some(l => Number(l.bookId) === Number(bookId) && l.snapshotRevision != null && String(l.snapshotRevision) !== String(revision)))) void check(); });
on(window, 'online', () => { if (!busy) void check(); });
on(window, 'pagehide', stop);
on(window, 'pageshow', event => {
loading.hidden = true;
if (event.persisted) { stopped = false; root.scrollTop = 0; window.scrollTo({ top: 0, behavior: 'instant' }); void check(); }
if (event.persisted) { stopped = false; void check(); }
});
if (chapterId) {
root.querySelector('.reader-live-controls').hidden = false;

View File

@ -1,5 +1,8 @@
(() => {
'use strict';const root=document.querySelector('#native-companion-status');if(!root)return;
'use strict';let root=document.querySelector('#native-companion-status');
// The title-bar presence preference must not disable Writer's shared status stream.
if(!root&&document.querySelector('[data-writer-word]')){root=document.createElement('span');root.id='native-companion-status';root.hidden=true;const label=document.createElement('span');label.id='native-companion-status-text';root.append(label);document.querySelector('[data-writer-word]').append(root);}
if(!root||root.nativeStatusStarted)return;root.nativeStatusStarted=true;
const text=root.querySelector('#native-companion-status-text');let pending=false,seen=false,refreshAgain=false,reconnectPending=false;
const details=document.querySelector('#writing-connection-details'), documents=details?.querySelector('#writing-word-document');
const syncForm=details?.querySelector('[data-word-sync-form]'),syncButton=syncForm?.querySelector('[data-word-sync-button]'),syncFeedback=syncForm?.querySelector('[data-word-sync-feedback]');
@ -52,7 +55,7 @@
}
function offline(message){root.dataset.nativeAuthority=root.dataset.officeConnected==='true'?'false':'true';root.dataset.connected='false';root.classList.remove('is-connected');root.classList.add('is-offline');text.textContent=message;root.title=message+' · saved PlotDirector information remains available.';}
async function update(reconnected=false){reconnectPending ||= reconnected;if(document.hidden)return;if(pending){refreshAgain=true;return;}pending=true;const reconnect=reconnectPending;reconnectPending=false;try{
const response=await fetch('/native-companion/status',{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw new Error();const leases=(await response.json()).filter(l=>Date.parse(l.expires)>Date.now());const active=leases.filter(l=>l.active&&l.wordAvailable),words=leases.filter(l=>l.wordAvailable);const lease=active.length===1?active[0]:words.length===1?words[0]:words.length===0?leases[0]:null;if(words.length>1&&active.length!==1){seen=true;offline('Choose an active Word document');}
const response=await fetch(document.querySelector('[data-writer-word]')?.dataset.statusUrl||'/native-companion/status',{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw new Error();const packet=await response.json();const leases=(Array.isArray(packet)?packet:packet.leases).filter(l=>Date.parse(l.expires)>Date.now());if(!Array.isArray(packet)){root.writerWordState=packet;window.dispatchEvent(new CustomEvent('writer-word-state',{detail:packet}));}const active=leases.filter(l=>l.active&&l.wordAvailable),words=leases.filter(l=>l.wordAvailable);const lease=active.length===1?active[0]:words.length===1?words[0]:words.length===0?leases[0]:null;if(words.length>1&&active.length!==1){seen=true;offline('Choose an active Word document');}
if(lease){leases.connectionState="Connected";leases.known=true;seen=true;root.dataset.nativeAuthority='true';root.dataset.connectionState='Connected';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');text.textContent=lease.wordAvailable?'Word connected':'Companion connected';root.title=lease.wordAvailable?lease.documentTitle+' · verified document heartbeat · last update '+new Date(lease.updated).toLocaleTimeString():'Companion connected; open a linked manuscript in Word.';}
else {
const stateResponse=await fetch('/native-companion/connection-state',{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});
@ -60,7 +63,7 @@
if(device?.known){seen=true;const label=device.state==='Connected'?'Companion connected · Word not connected':device.state;offline(label);root.dataset.connectionState=device.state;if(device.state==='Connected'){root.dataset.nativeAuthority='true';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');root.title='Approved Companion is connected. No live Word document is registered.';}}
else if(seen)offline('Word disconnected or stale');else if(text.textContent==='Checking Word…')offline('Word disconnected');
}leases.reconnected=reconnect;root.nativePresence=leases;renderDetails(leases);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases}));
}catch{offline('Companion status unavailable');const unavailable=[];unavailable.connectionState='Disconnected';unavailable.reconnected=reconnect;root.nativePresence=unavailable;renderDetails(unavailable);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:unavailable}));}finally{pending=false;if(refreshAgain){refreshAgain=false;void update();}}}
let reconnectHub=()=>{};void update();const timer=setInterval(()=>{reconnectHub();void update();},15000);document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer));
}catch{window.dispatchEvent(new CustomEvent('writer-word-state',{detail:{unavailable:true}}));offline('Companion status unavailable');const unavailable=[];unavailable.connectionState='Disconnected';unavailable.reconnected=reconnect;root.nativePresence=unavailable;renderDetails(unavailable);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:unavailable}));}finally{pending=false;if(refreshAgain){refreshAgain=false;void update();}}}
let reconnectHub=()=>{};void update();let timer;const startTimer=()=>{clearInterval(timer);timer=setInterval(()=>{reconnectHub();void update();},15000);};startTimer();window.addEventListener('pageshow',event=>{if(event.persisted){startTimer();reconnectHub();void update(true);}});document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer));window.addEventListener('plotdirector:refresh-word-status',()=>void update());
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(true));let starting=false;reconnectHub=()=>{if(starting||connection.state&&connection.state!=='Disconnected')return;starting=true;void connection.start().then(()=>void update(true)).catch(()=>{}).finally(()=>starting=false);};reconnectHub();window.addEventListener('pagehide',()=>{clearTimeout(refresh);void connection.stop();});}
})();

View File

@ -0,0 +1,28 @@
// Consumes the existing native presence/status stream. No second background poller or global selection.
(()=>{'use strict';const root=document.querySelector('[data-writer-word]');if(!root)return;
const book=Number(root.dataset.bookId),chapter=Number(root.dataset.chapterId),scene=Number(root.dataset.sceneId),state=root.querySelector('[data-word-state]'),position=root.querySelector('[data-word-position]'),freshness=root.querySelector('[data-word-freshness]'),message=root.querySelector('[data-word-command]'),choose=root.querySelector('[data-word-choose]'),select=root.querySelector('[data-word-document]'),nav=root.querySelector('[data-word-navigate]'),sceneNav=root.querySelector('[data-word-scene]'),adopt=root.querySelector('[data-word-adopt]');
let packet=null,current=null,busy=false,abort=null,checkBusy=false,syncPending=null;const sync=root.querySelector('[data-word-sync]');
const key=l=>l.instanceId+'/'+l.sessionId;
const verified=l=>(packet?.verifiedPositions||[]).find(p=>key(p)===key(l));
const requestStatus=()=>window.dispatchEvent(new Event('plotdirector:refresh-word-status'));
function render(data){packet=data;const old=current;const leases=(data.leases||[]).filter(l=>l.wordAvailable&&l.bookId===book&&Date.parse(l.expires)>Date.now());const originParams=new URLSearchParams(location.search);const originKey=originParams.get('wordInstanceId')+'/'+originParams.get('wordSessionId');const selected=select.value||originKey;select.replaceChildren(new Option('Choose a document',''),...leases.map(l=>new Option(l.documentTitle,key(l))));if(leases.some(l=>key(l)===selected))select.value=selected;else if(leases.length===1)select.value=key(leases[0]);current=leases.find(l=>key(l)===select.value)||null;choose.hidden=leases.length<2;
if(old&&(!current||key(old)!==key(current)||old.revision!==current.revision||old.manuscriptId!==current.manuscriptId)&&busy){abort?.abort();message.textContent='Word document changed or disconnected. Navigation was not confirmed.';}
if(syncPending&&(!current||syncPending.key!==key(current)||Date.now()-syncPending.started>120000||(syncPending.requestId&&current.paragraphTransfer?.requestId===syncPending.requestId&&['accepted','needs-review','failed','cancelled'].includes(current.paragraphTransfer.state))))syncPending=null;
const identity=current&&data.canonical?.manuscriptID===current.manuscriptId;const observed=current&&verified(current);
state.textContent=data.unavailable?'Word Companion status unavailable. Your saved work is retained.':!current?(leases.length>1?'Choose the correct Word manuscript.':(data.leases||[]).some(l=>l.wordAvailable)?'The open Word manuscript is for another book.':'Word Companion is not connected to this manuscript.'):!identity?'Word is connected, but this manuscript has not been verified.':`Manuscript: ${current.documentTitle}`;
position.textContent=observed?`Word is showing ${observed.chapterTitle||'the verified chapter'}${observed.sceneId&&observed.sceneTitle?' · '+observed.sceneTitle:''}. ${observed.chapterId!==chapter?'Your working focus is separate.':''}`:current?.wordSaved===false?'Word has unsaved changes. Current positions await verification; no save will be forced.':'Word position has not been verified.';
let status=!identity?'Your latest changes have not yet been confirmed in PlotDirector.':current.chapterProgress?.state==='Needs review'||current.chapterIssue==='needs_review'?'Manuscript checking needs attention in Companion. Accepted content is retained.':current.paragraphTransfer?.state==='failed'?'Manuscript update failed. Accepted content is retained.':current.chapterProgress?.state==='Synchronised'&&current.wordSaved===true?'The last manuscript check completed. Later edits may still be pending.':current.chapterProgress?.state?`${current.chapterProgress.state}: ${current.chapterProgress.message||'Latest changes are not yet confirmed.'}`:'Latest changes are not yet confirmed. Check synchronisation in Companion.';
if(data.canonical?.chapterAcceptedUtc)status+=' This chapter last accepted: '+new Date(data.canonical.chapterAcceptedUtc).toLocaleString()+'.';else if(data.canonical?.snapshotUtc)status+=' Accepted snapshot recorded: '+new Date(data.canonical.snapshotUtc).toLocaleString()+'.';freshness.textContent=status;
sync.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!(current.canChapterSync||current.canParagraphSync);
for(const button of [nav,sceneNav])if(button)button.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!current.canAcknowledgeNavigation;
if(identity&&!current.canAcknowledgeNavigation)position.textContent+=' Update the Word add-in and Companion together to enable confirmed navigation.';
const params=new URLSearchParams(location.search),origin=current&&params.get('wordInstanceId')===current.instanceId&&params.get('wordSessionId')===current.sessionId;
adopt.hidden=!(origin&&observed&&observed.chapterId!==chapter);if(!adopt.hidden){adopt.querySelector('[name=ChapterID]').value=observed.chapterId;adopt.querySelector('[name=SceneID]').value=observed.sceneId||'';adopt.querySelector('[data-word-origin]').textContent='Opened from verified Word chapter '+(observed.chapterTitle||'in this manuscript')+'. Your saved working focus is unchanged.';}
}
select.addEventListener('change',()=>render(packet));
async function navigate(toScene){if(busy||!current||!chapter)return;if(Date.parse(current.expires)<=Date.now()){message.textContent='Word connection expired. Check the connection before navigating.';render({...packet,leases:[]});requestStatus();return;}busy=true;abort=new AbortController();const selected={...current},id=crypto.randomUUID();render(packet);message.textContent='Requesting navigation in Word…';const form=new URLSearchParams({bookId:String(book),chapterId:String(chapter),instanceId:selected.instanceId,sessionId:selected.sessionId,manuscriptId:selected.manuscriptId,revision:String(selected.revision),navigationId:id,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});if(toScene)form.set('sceneId',String(scene));try{const response=await fetch('/WriterWord/Navigate',{method:'POST',body:form,signal:abort.signal});const data=await response.json().catch(()=>null);if(!response.ok)throw Error(data?.message||'Navigation could not be requested. Check your connection and sign-in.');message.textContent='Requested in Word; waiting for confirmation.';const start=Date.now();let done=false;while(Date.now()-start<30000){await new Promise((resolve,reject)=>{const signal=abort.signal;const cancel=()=>{clearTimeout(timer);reject(new Error('Navigation was not confirmed. Word changed or disconnected.'));};const timer=setTimeout(()=>{signal.removeEventListener('abort',cancel);resolve();},1000);signal.addEventListener('abort',cancel,{once:true});});const receipt=await fetch(`/WriterWord/Navigation?bookId=${book}&instanceId=${selected.instanceId}&sessionId=${selected.sessionId}&navigationId=${id}`,{signal:abort.signal,cache:'no-store'});if(!receipt.ok)throw Error('Navigation confirmation unavailable.');const result=await receipt.json();if(result.state!=='requested'){message.textContent=result.state==='completed'?'Word confirmed navigation.':result.state==='failed'?'Word could not navigate. Your work was retained.':'Navigation expired or the document changed. No completion was confirmed.';done=true;break;}}if(!done)message.textContent='Word did not confirm navigation in time. Check the manuscript before retrying.';}catch(error){message.textContent=error.name==='AbortError'?'Navigation was not confirmed. Check Word before retrying.':error.message;}finally{busy=false;abort=null;if(packet)render(packet);requestStatus();}}
sync.addEventListener('click',async()=>{if(sync.disabled||!current)return;const selected={...current};syncPending={key:key(selected),started:Date.now()};sync.disabled=true;const body=new URLSearchParams({bookId:String(book),instanceId:selected.instanceId,sessionId:selected.sessionId,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});try{const response=await fetch('/manuscript/paragraphs/snapshot',{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)});const result=await response.json();if(!response.ok||response.redirected)throw Error(result.message||'Manuscript check unavailable.');if(syncPending)syncPending.requestId=result.requestId;message.textContent='Saved manuscript check requested; acceptance has not yet been confirmed. '+(result.message||'');}catch(error){syncPending=null;message.textContent=error.message||'Could not request manuscript check.';}finally{requestStatus();}});
nav?.addEventListener('click',()=>void navigate(false));sceneNav?.addEventListener('click',()=>void navigate(true));
root.querySelector('[data-word-check]').addEventListener('click',()=>{if(checkBusy)return;checkBusy=true;message.textContent='Checking reported connection and accepted updates. Use Synchronise in Companion to request a bounded manuscript check.';requestStatus();setTimeout(()=>checkBusy=false,2000);});
window.addEventListener('writer-word-state',event=>render(event.detail));window.addEventListener('native-companion-presence',event=>{if(!event.detail.length&&packet&&!packet.leases?.length&&event.detail.connectionState==='Connected')state.textContent='Companion is connected; open and verify this manuscript in Word.';});window.addEventListener('pagehide',()=>abort?.abort());const initial=document.querySelector('#native-companion-status')?.writerWordState;if(initial)render(initial);
})();