Coordinate manuscript focus and independent Hold across workspaces
This commit is contained in:
parent
2fe1d85e95
commit
a85d6ed532
64
Docs/Writer/Unified-Manuscript-Focus-20261123.md
Normal file
64
Docs/Writer/Unified-Manuscript-Focus-20261123.md
Normal file
@ -0,0 +1,64 @@
|
||||
# Unified manuscript focus — implementation and qualification
|
||||
|
||||
Development only, 23 November 2026. Existing feature branch: `codex/word-companion-native-phase1-20261104`. The application commit, release directory, hashes and post-deployment results are recorded in the deployment evidence linked below.
|
||||
|
||||
## Audit and architectural choice
|
||||
|
||||
Previously, `NarrativeFocus` stored personal chapter/scene navigation, with browser storage/focus events supplying recovery. Review's chapter GET could change that state. Context principally followed native/Office presence and its navigation endpoint requested a Word command, which made it ineffective without Word. Review's paragraph selection updated review tools and the explicit Word target, but did not publish a common manuscript position.
|
||||
|
||||
Context already owned one native-presence SignalR connection per window, independent cached tabs, split panes, layout persistence, window identity and duplicate-window detection. Its invalidation handler already allowed an earlier-scene change to invalidate later-scene projections; it must remain independent of navigation. Snapshot windows previously skipped connection setup. The main application already had a shared native-presence connection, and the native tray Companion already had a validated command queue, asynchronous agent wake notifications, exact document sessions and acknowledgements.
|
||||
|
||||
The implementation extends these paths. It does not introduce another hub, Context connection, manuscript copy, editor owner, focus polling loop or Intent surface. Existing content/status checks remain. The current Windows VSTO/tray architecture is the Word implementation target; the older Office.js task-pane shell remains unchanged and is not advertised as a shared-focus client.
|
||||
|
||||
## Server contract
|
||||
|
||||
Forward-only migrations **314–316** extend the existing `NarrativeFocus` row with canonical manuscript/paragraph and originating-window IDs; add a per-origin sequence replay ledger; replace implicit objective seeding and read-time redirection; and resolve Word positions from exact-session verified chapter evidence. Backup `/var/opt/mssql/backup/shared-manuscript-focus-20261123T125506Z.bak` completed with COPY_ONLY/CHECKSUM and passed VERIFYONLY before migration. VERIFYONLY is not a restore test.
|
||||
|
||||
`GET /NarrativeFocus/Shared?projectID=…&bookID=…` retrieves authoritative focus. Antiforgery-protected POSTs to `/NarrativeFocus/Shared/Publish`, `/Resolve` and `/Validate` accept existing identifiers. `Resolve` performs held local navigation; `Validate` checks a retained reference; neither publishes. Every operation verifies active authenticated access, project/book membership, canonical manuscript identity and chapter/scene/paragraph compatibility in stored procedures accessed through Dapper. Navigation remains available to read-only subscription accounts.
|
||||
|
||||
The packet contains `ProjectID`, `BookID`, `ManuscriptID`, `ChapterID`, optional `SceneID`/`ParagraphID`, `OriginWindowID`, `Version`, `IsValid` and `Changed`. It contains no prose, Word offsets or contextual datasets. The server locks the existing focus row and assigns increasing revisions atomically. Different clients are ordered by accepted server revisions, without client timestamps. Duplicate/older per-window sequences and unchanged effective targets do not create another revision. A stale stored reference is returned as invalid, without silently moving it.
|
||||
|
||||
`ManuscriptFocusChanged` uses the existing authenticated `NativeCompanionPresenceHub.UserGroup`. `ManuscriptFocusDelivery` reports unavailable Word mapping without blocking other clients. Browser clients scope-filter messages, reject obsolete/duplicate revisions, serialize rapid local intent and recover on connect/reconnect. Ordinary GETs, refreshes, passive observations and received navigation do not publish. Existing explicit browser navigation delegates to the coordinator; server GET hooks no longer write focus.
|
||||
|
||||
A future editor can use the same identifier-only contract and existing authenticated transport without changing manuscript content ownership.
|
||||
|
||||
## Clients and Hold
|
||||
|
||||
Review publishes deliberate paragraph clicks, paragraph keyboard navigation and chapter/scene selectors, including when Word is closed. Accepted content remains authoritative. Incoming focus uses the existing partial chapter/scene positioning pipeline, preserves open editors and review tools, and explains missing precise paragraph/scene mapping before showing a deterministic scene/chapter fallback. Scrolling does not publish.
|
||||
|
||||
Context dropdown, Previous, Next and Go to Focus use shared focus directly, without a Word navigation request. Each window retains its panes, tools, divider, cached tab state and layout. Snapshot windows also keep data notifications. Focus changes only invalidate panels whose scope changed. Data invalidation is independent of Hold and conservatively refreshes affected visible relationship/character panels across scenes; hidden panels are marked stale until activated. Structural invalidation retains the held reference and offers another local selection or Release Hold.
|
||||
|
||||
Browser Hold is stored in session storage under authenticated-user/window identity, separately from global book preferences. An ordinary refresh retains Hold and local position. Existing Context identity arbitration plus browser identity claims prevent duplicated storage from sharing Hold. New windows default to Follow. Release obtains current authoritative focus, then follows it; it never publishes the held position. With no valid shared focus, it retains the local position and follows without creating one. Failed recovery retains Hold.
|
||||
|
||||
The static Hold control and status appear in Review/application ribbons and Context. Hold remains visible when the installed PWA compacts Previous/Go/Next into its existing menu. Labels explicitly say Following/Held and Release Hold; colour is supplementary.
|
||||
|
||||
Native Word adds Hold/Follow to the existing ribbon and uses a distinct state/identity for each actual Word window. The adapter distinguishes foreground mouse/navigation-key selection events from passive observations and suppresses incoming-navigation publication. Deliberate observations pass through existing framed IPC and native presence, then resolve canonical paragraph IDs using saved, fresh, exact-session verified chapter positions. Existing agent wake/command/receipt delivery supplies background following. Shared commands use `Window.ScrollIntoView`, not `Select`, `Activate` or a foreground-window call; editing selection/content ownership is retained. Unmapped, unsaved and busy states are explicit. Word Outline view cannot use this API and requires changing view before retrying ([Microsoft API contract](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.window.scrollintoview?view=word-pia)). Window state rejects old/duplicate deliveries and Release can catch the same window's own previously published shared position.
|
||||
|
||||
Explicit Open in Word controls are retained, including paragraph navigation: physical native replacement qualification is not complete, so removing these controls would be premature. They remain useful for unsupported/disconnected/held/unmapped Word sessions and opening the manuscript. Shared paragraph/Context selection never automatically launches Word.
|
||||
|
||||
## Verification
|
||||
|
||||
- Solution build: zero warnings/errors; full executable regression harness: **786 passing checks**.
|
||||
- Native portable regression harness: **320 passing checks**, including the dedicated per-window Hold/revision cases. These exercise managed production logic and IPC, not Word COM.
|
||||
- Development rollback-only SQL tests cover no initial publication, canonical paragraph resolution, monotonic revisions, unchanged-target suppression, replay rejection, held resolution without mutation, canonical cross-chapter stepping, invalid references, verified Word offsets, exact-session isolation and authorisation. The updated historical six-phase SQL regression also passes with no implicit seed/redirection.
|
||||
- Sixteen real concurrent SQL connections verify contiguous unique accepted revisions and a final durable read equal to the highest revision. Real coordinator/SQL/native-queue integration also verifies Word-only publication, browser-to-Word chapter crossing, passive suppression, Hold/release, failed receipts, unsaved documents and exact-session isolation through a recording transport.
|
||||
- Real authenticated Chromium and installed standalone Chromium PWA tests use the actual controllers, SQL and SignalR with a synthetic isolated project/manuscript. They cover Context alone; Review/Context without Word; local scrolling; exact paragraphs and chapter crossing; independent Hold; local held Review navigation; refresh and release without publication; rapid and obsolete ordering; new/duplicated-window isolation; reconnect; responsive widths; hidden tabs; and relationship edits in an earlier scene refreshing both held panes. The refreshed later-scene graph is checked for the new note, not just a refresh request.
|
||||
- Actual loopback server restart passed: durable focus recovered, SignalR reconnected, and the held window detected an offline structural change without redirecting. Browser structural archival acceptance passed. Final public Development smoke results are recorded in deployment evidence. Browser fixtures are isolated and archived after testing; no real manuscript text or relationships are edited.
|
||||
|
||||
Reproducible entry points: `PlotLine.Tests --shared-focus-database <disposable-scope-file>` (rollback); `--shared-focus-browser-setup <disposable-scope-file>`; `--shared-focus-browser-host` (loopback only, real auth/SQL/hub, no hosted workers); `--shared-focus-concurrent`; `--shared-focus-cleanup`. Browser: `PlotLine.Tests/Browser/shared-manuscript-focus.cjs`, optionally `--installed`, `--structure`, or the externally coordinated `--restart` case, with private disposable identity supplied through `PD_CONTEXT_IDENTITY`. Portable native: `--shared-focus`. No credentials are in the report or repository.
|
||||
|
||||
## Windows qualification still required
|
||||
|
||||
This Linux host cannot compile/load the Office/VSTO project or run physical Word, Windows foreground handling or multiple monitors. The main .NET build deliberately excludes that project. Browser and portable native passes are **not physical Word acceptance**; no new Word binary has been installed or published by this task.
|
||||
|
||||
1. On an Office-equipped Windows development machine, use the existing shared branch and `PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1` workflow at the recorded commit. Build/sign/verify the package, then use its existing explicit development installation procedure. Verify the loaded add-in/agent commit before testing.
|
||||
2. Associate/save a disposable Development manuscript and complete chapter position verification. With Word alone, click and keyboard-select paragraphs across chapter/scene boundaries. Inspect shared revisions, then open Review/Context and verify initialization at the latest position without a new publication.
|
||||
3. Exercise Word+Review, Word+Context and all three, with two Context windows (one Held) and split panes. Scroll Word and Review without changing shared focus. Select paragraphs/chapter/scene deliberately in each client and verify only followers move.
|
||||
4. Keep Review foreground on another monitor. Select a paragraph there; verify Word reveals the exact target while the Windows foreground process, insertion point, selection and manuscript text remain unchanged. Repeat while Word has a dialog, protected view or editing activity; verify explicit busy/unmapped handling without activation.
|
||||
5. Hold each Word window independently, including two windows on the same document. Navigate/edit locally; verify content synchronization continues and shared revision is unchanged. Release to the latest shared point, including one originally published by that same window. Close/reopen a window and verify new Follow identity.
|
||||
6. Close each client in turn, including Word unexpectedly, and verify remaining pairs still navigate. Reconnect/restart the agent/service, rapidly alternate publications, and replay/delay notifications; verify newest accepted focus wins without an echo. Test saved/unsaved and stale/expired mapping transitions and independent manuscripts/accounts.
|
||||
7. Repeat the earlier-scene relationship edit while a later-scene diagram is Held; verify data changes without movement. Archive a disposable held scene and verify explicit invalid-reference recovery. Confirm existing editing, synchronization, review tools, launch actions and ribbon layout.
|
||||
|
||||
Older native installations do not advertise the new capability and retain their existing behavior. Precise native following requires fresh verified saved chapter positions; legacy paragraph-only offsets are not guessed. Historical Office.js hosting requires separate host-specific implementation/qualification before shared-focus support can be claimed there.
|
||||
|
||||
Deployment evidence: [Unified-Manuscript-Focus-Deployment-20261123.md](Unified-Manuscript-Focus-Deployment-20261123.md).
|
||||
@ -42,7 +42,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
|
||||
else{
|
||||
doc.Observed=DateTime.UtcNow;
|
||||
if(request.Kind=="active"){foreach(var d in documents.Values)d.Active=false;doc.Active=true;}
|
||||
if(request.Kind=="selection"){doc.WordObservedUtc=request.WordObservedUtc.HasValue?(request.WordObservedUtc.Value.ToUniversalTime()<=ChapterNow?request.WordObservedUtc.Value.ToUniversalTime():null):ChapterNow;if(doc.WordSaved!=request.WordSaved&&request.WordSaved==true&&doc.NextChapterCheckUtc!=default)doc.NextChapterCheckUtc=ChapterNow.AddSeconds(3);if(ChapterCapable(instance)&&(doc.Cursor!=request.Start||doc.WordSaved!=request.WordSaved)){ChapterCursorEvidence.Invalidate(doc);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(doc.WordSaved==true&&doc.RibbonNotice?.State=="Save required")doc.RibbonNotice=null;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}}
|
||||
if(request.Kind=="selection"){if(doc.FocusWindowID!=request.FocusWindowID||doc.FocusModeRequest!=request.FocusModeRequest)doc.DeliberateFocusSequence=0;doc.CanSharedFocus=request.CanSharedFocus;doc.FocusHeld=request.FocusHeld;doc.AnyFollowingWindows=request.AnyFollowingWindows;doc.FocusWindowID=request.FocusWindowID;doc.FocusModeRequest=request.FocusModeRequest;if(request.DeliberateFocusSequence>0)doc.DeliberateFocusSequence=request.DeliberateFocusSequence;if(request.CanSharedFocus&&(request.DeliberateFocusSequence>0||doc.LastFocusModeRequest!=request.FocusModeRequest)){doc.PresenceRequested=true;doc.LastFocusModeRequest=request.FocusModeRequest;}doc.WordObservedUtc=request.WordObservedUtc.HasValue?(request.WordObservedUtc.Value.ToUniversalTime()<=ChapterNow?request.WordObservedUtc.Value.ToUniversalTime():null):ChapterNow;if(doc.WordSaved!=request.WordSaved&&request.WordSaved==true&&doc.NextChapterCheckUtc!=default)doc.NextChapterCheckUtc=ChapterNow.AddSeconds(3);if(ChapterCapable(instance)&&(doc.Cursor!=request.Start||doc.WordSaved!=request.WordSaved)){ChapterCursorEvidence.Invalidate(doc);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(doc.WordSaved==true&&doc.RibbonNotice?.State=="Save required")doc.RibbonNotice=null;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}}
|
||||
if(request.Kind=="selection"&&doc.LastPresenceKey!=""&&chapterWork.TryGetValue(doc.Session,out var localWork)&&CurrentChapterWork(doc,localWork)&&localWork.Supported)
|
||||
PumpChapterWork(doc,localWork);
|
||||
ChapterFrame(doc,request,answer);
|
||||
@ -54,6 +54,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
|
||||
if (request.Kind == "tray-workspace" && answer.Status == "ok")
|
||||
_ = OpenRibbonWorkspace(doc.Session, request.Revision, "book");
|
||||
CaptureFrame(doc,request,answer);
|
||||
answer.SharedFocusStatus=doc.SharedFocusStatus;
|
||||
if((request.Kind=="selection"||request.Kind=="snapshot-end")&&!ChapterCapable(instance)){doc.ChapterId=answer.ChapterId;doc.SceneId=answer.SceneId;doc.ChapterTitle=answer.ChapterTitle;doc.SceneTitle=answer.SceneTitle;}
|
||||
if(answer.WordCount.HasValue)doc.Words=answer.WordCount;
|
||||
if(request.Kind.StartsWith("snapshot-",StringComparison.Ordinal)&&answer.Status is not ("ok" or "analysis-complete" or "awaiting-structure")){Cancel(doc);doc.Status="Local reading failed: "+answer.Status+". Detect chapters again.";}
|
||||
@ -193,7 +194,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
|
||||
}
|
||||
private async Task PublishPresence(TrayDocument doc,bool force,CancellationToken cancellation)
|
||||
{
|
||||
var freshObservation=FreshWordObservation(doc);if(!force&&doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))return;var key=$"{freshObservation}:{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{doc.NavigationAcknowledgedId}:{doc.NavigationResult}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";if(!force&&key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(acknowledgedNavigationInstances.Contains(doc.Instance)?2:15))return;try{var presenceClock=System.Diagnostics.Stopwatch.StartNew();Guid? publishedNavigation;long publishedAckTimestamp;string publishedResult;lock(gate){publishedNavigation=doc.NavigationAcknowledgedId;publishedAckTimestamp=doc.NavigationAckTimestamp;publishedResult=doc.NavigationResult;}var presenceStarted=System.Diagnostics.Stopwatch.GetTimestamp();var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CanAcknowledgeNavigation=acknowledgedNavigationInstances.Contains(doc.Instance),NavigationAcknowledgedId=publishedNavigation,NavigationResult=publishedResult,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=freshObservation?doc.WordSaved:null,CursorStart=freshObservation?doc.Cursor:null,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=freshObservation?doc.ChapterId:null,SceneId=freshObservation?doc.SceneId:null,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication,cancellation);if(reply.Navigation?.Kind=="navigate")TraceNavigation(reply.Navigation.Id,"presence-acquisition-roundtrip",presenceClock.Elapsed.TotalMilliseconds);if(publishedNavigation.HasValue&&doc.LastTracedNavigationAck!=publishedNavigation.Value){if(publishedAckTimestamp!=0)TraceNavigation(publishedNavigation.Value,"adapter-result-to-ack-presence",System.Diagnostics.Stopwatch.GetElapsedTime(publishedAckTimestamp,presenceStarted).TotalMilliseconds);TraceNavigation(publishedNavigation.Value,"ack-presence-roundtrip",presenceClock.Elapsed.TotalMilliseconds);doc.LastTracedNavigationAck=publishedNavigation.Value;}lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc||(ChapterCapable(doc.Instance)&&reply.Revision!=doc.Revision)||doc.Authentication!=cloud.Status().AuthenticationContext)return;if(ChapterCapable(doc.Instance)&&chapterWork.TryGetValue(doc.Session,out var currentChapters)&¤tChapters.Manifest!=null&&reply.ParagraphRevision>0&&reply.ParagraphRevision<currentChapters.Manifest.Revision)return;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);}
|
||||
var freshObservation=FreshWordObservation(doc);if(!force&&doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))return;var key=$"{freshObservation}:{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{doc.NavigationAcknowledgedId}:{doc.NavigationResult}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";if(!force&&key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(acknowledgedNavigationInstances.Contains(doc.Instance)?2:15))return;try{var presenceClock=System.Diagnostics.Stopwatch.StartNew();Guid? publishedNavigation;long publishedAckTimestamp;string publishedResult;lock(gate){publishedNavigation=doc.NavigationAcknowledgedId;publishedAckTimestamp=doc.NavigationAckTimestamp;publishedResult=doc.NavigationResult;}var focusPublication=new NativePresence{CanSharedFocus=doc.CanSharedFocus,FocusHeld=doc.FocusHeld,AnyFollowingWindows=doc.AnyFollowingWindows,FocusWindowID=doc.FocusWindowID,FocusModeRequest=doc.FocusModeRequest,DeliberateFocusSequence=doc.DeliberateFocusSequence};var presenceStarted=System.Diagnostics.Stopwatch.GetTimestamp();var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CanSharedFocus=focusPublication.CanSharedFocus,FocusHeld=focusPublication.FocusHeld,AnyFollowingWindows=focusPublication.AnyFollowingWindows,FocusWindowID=focusPublication.FocusWindowID,FocusModeRequest=focusPublication.FocusModeRequest,DeliberateFocusSequence=focusPublication.DeliberateFocusSequence,CanAcknowledgeNavigation=acknowledgedNavigationInstances.Contains(doc.Instance),NavigationAcknowledgedId=publishedNavigation,NavigationResult=publishedResult,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=freshObservation?doc.WordSaved:null,CursorStart=freshObservation?doc.Cursor:null,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=freshObservation?doc.ChapterId:null,SceneId=freshObservation?doc.SceneId:null,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication,cancellation);if(reply.Navigation?.Kind=="navigate")TraceNavigation(reply.Navigation.Id,"presence-acquisition-roundtrip",presenceClock.Elapsed.TotalMilliseconds);if(publishedNavigation.HasValue&&doc.LastTracedNavigationAck!=publishedNavigation.Value){if(publishedAckTimestamp!=0)TraceNavigation(publishedNavigation.Value,"adapter-result-to-ack-presence",System.Diagnostics.Stopwatch.GetElapsedTime(publishedAckTimestamp,presenceStarted).TotalMilliseconds);TraceNavigation(publishedNavigation.Value,"ack-presence-roundtrip",presenceClock.Elapsed.TotalMilliseconds);doc.LastTracedNavigationAck=publishedNavigation.Value;}lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc||(ChapterCapable(doc.Instance)&&reply.Revision!=doc.Revision)||doc.Authentication!=cloud.Status().AuthenticationContext)return;if(ChapterCapable(doc.Instance)&&chapterWork.TryGetValue(doc.Session,out var currentChapters)&¤tChapters.Manifest!=null&&reply.ParagraphRevision>0&&reply.ParagraphRevision<currentChapters.Manifest.Revision)return;if(doc.FocusWindowID==focusPublication.FocusWindowID&&doc.DeliberateFocusSequence==focusPublication.DeliberateFocusSequence)doc.DeliberateFocusSequence=0;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;if(!string.IsNullOrEmpty(reply.SharedFocusStatus))doc.SharedFocusStatus=reply.SharedFocusStatus;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);return;}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;
|
||||
@ -244,6 +245,7 @@ var freshObservation=FreshWordObservation(doc);if(!force&&doc.LastPresenceKey=="
|
||||
}
|
||||
public sealed class TrayDocument
|
||||
{
|
||||
public string SharedFocusStatus="";public bool CanSharedFocus,FocusHeld,AnyFollowingWindows;public Guid FocusWindowID,FocusModeRequest,LastFocusModeRequest;public long DeliberateFocusSequence;
|
||||
internal long AudioTextChanges;
|
||||
public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress;
|
||||
public long NavigationQueuedTimestamp,NavigationAckTimestamp;public Guid LastTracedNavigationAck;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="";
|
||||
|
||||
10
PlotDirector.NativeCompanion/Protocol/FocusWindowState.cs
Normal file
10
PlotDirector.NativeCompanion/Protocol/FocusWindowState.cs
Normal file
@ -0,0 +1,10 @@
|
||||
namespace PlotDirector.Companion.Protocol;
|
||||
// Per actual editor window; independent of content synchronisation and document ownership.
|
||||
public sealed class FocusWindowState
|
||||
{
|
||||
public Guid Id {get;}=Guid.NewGuid();public bool Held{get;private set;}public long Sequence{get;private set;}public long LastSharedRevision{get;private set;}public Guid ModeRequest{get;private set;}=Guid.NewGuid();
|
||||
private int start=-1,end=-1;private long appliedRevision=-1;private bool catchup;
|
||||
public void Hold(bool held){if(Held==held)return;Held=held;if(!held){appliedRevision=-1;catchup=true;}ModeRequest=Guid.NewGuid();}
|
||||
public long Observe(int nextStart,int nextEnd,bool deliberate){var changed=start!=nextStart||end!=nextEnd;start=nextStart;end=nextEnd;return changed&&deliberate&&!Held?++Sequence:0;}
|
||||
public bool Accept(long revision,Guid origin){if(revision<LastSharedRevision||revision<=appliedRevision)return false;LastSharedRevision=revision;if(Held)return false;appliedRevision=revision;var follow=catchup||origin!=Id;catchup=false;return follow;}
|
||||
}
|
||||
@ -34,6 +34,13 @@ public static class ProtocolVersion
|
||||
[DataContract]
|
||||
public sealed class Message
|
||||
{
|
||||
[DataMember] public string SharedFocusStatus{get;set;}="";
|
||||
[DataMember] public bool CanSharedFocus{get;set;}
|
||||
[DataMember] public bool FocusHeld{get;set;}
|
||||
[DataMember] public bool AnyFollowingWindows{get;set;}
|
||||
[DataMember] public Guid FocusWindowID{get;set;}
|
||||
[DataMember] public Guid FocusModeRequest{get;set;}
|
||||
[DataMember] public long DeliberateFocusSequence{get;set;}
|
||||
[DataMember] public bool ChapterStatusProvided {get;set;}
|
||||
[DataMember(EmitDefaultValue=false)] public string? AudioState { get; set; }
|
||||
[DataMember(EmitDefaultValue=false)] public string[]? AudioOperations { get; set; }
|
||||
|
||||
@ -3,6 +3,9 @@ namespace PlotDirector.Companion.Protocol;
|
||||
[DataContract]
|
||||
public sealed class AdapterCommand
|
||||
{
|
||||
[DataMember] public bool BackgroundFocus{get;set;}
|
||||
[DataMember] public long FocusVersion{get;set;}
|
||||
[DataMember] public Guid FocusOriginWindowID{get;set;}
|
||||
[DataMember] public PlotDirector.Companion.Protocol.Manuscript.ChapterManifestItem? RangeBaseline {get;set;}
|
||||
[DataMember] public DateTime ExpiresUtc {get;set;}
|
||||
[DataMember] public Guid ManuscriptId {get;set;}
|
||||
@ -26,6 +29,13 @@ public sealed class AdapterCommand
|
||||
[DataContract]
|
||||
public sealed class NativePresence
|
||||
{
|
||||
[DataMember] public string SharedFocusStatus{get;set;}="";
|
||||
[DataMember] public bool CanSharedFocus{get;set;}
|
||||
[DataMember] public bool FocusHeld{get;set;}
|
||||
[DataMember] public bool AnyFollowingWindows{get;set;}
|
||||
[DataMember] public Guid FocusWindowID{get;set;}
|
||||
[DataMember] public Guid FocusModeRequest{get;set;}
|
||||
[DataMember] public long DeliberateFocusSequence{get;set;}
|
||||
[DataMember] public bool CanAcknowledgeNavigation {get;set;}
|
||||
[DataMember] public Guid? NavigationAcknowledgedId {get;set;}
|
||||
[DataMember] public string NavigationResult {get;set;}="";
|
||||
|
||||
@ -3,6 +3,7 @@ using PlotDirector.Companion.Agent;
|
||||
using PlotDirector.Companion.Client;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
|
||||
if(args.Contains("--shared-focus")){SharedFocusTests.Run((ok,name)=>{if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);});return;}
|
||||
if(args.Contains("--word-observation")){await WordObservationTests.Run((ok,name)=>{if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);});return;}
|
||||
if(args.Contains("--chapter-sync")){ChapterRangeVerificationTests.Run();ChapterReopenTests.Run();await ChapterAgentTests.Run();await ChapterHandshakeTests.Run();await WordReopeningWorkTests.Run();return;}
|
||||
if(args.Contains("--native-capture-upload")){await NativeCaptureUploadTests.Run();return;}
|
||||
@ -28,6 +29,7 @@ void SchedulerChecks()
|
||||
var rejected=false;var thread=new Thread(()=>{try{scheduler.Pump();}catch(InvalidOperationException){rejected=true;}});thread.Start();thread.Join();Check(rejected,"Word scheduler rejects wrong thread");
|
||||
scheduler.PrioritizeAuthor(TimeSpan.FromMinutes(1));scheduler.Post("low",()=>value=0);Check(!scheduler.Pump()&&value==999,"author activity suspends low priority work");
|
||||
}
|
||||
SharedFocusTests.Run(Check);
|
||||
SchedulerChecks();
|
||||
var mailbox=new BoundedMailbox();var id=Guid.NewGuid();
|
||||
for(var i=0;i<10000;i++)mailbox.TryPost(new Message{Kind="selection",SessionId=id,Start=i});
|
||||
|
||||
22
PlotDirector.NativeCompanion/Tests/SharedFocusTests.cs
Normal file
22
PlotDirector.NativeCompanion/Tests/SharedFocusTests.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using PlotDirector.Companion.Protocol;
|
||||
|
||||
internal static class SharedFocusTests
|
||||
{
|
||||
public static void Run(Action<bool,string> check)
|
||||
{
|
||||
var a=new FocusWindowState();var b=new FocusWindowState();var origin=Guid.NewGuid();
|
||||
check(!a.Held&&!b.Held&&a.Id!=b.Id,"new Word windows follow with independent identities");
|
||||
check(a.Observe(10,10,false)==0&&a.Observe(20,20,false)==0,"passive Word observations never publish");
|
||||
check(a.Observe(30,30,true)==1&&a.Observe(30,30,true)==0,"deliberate changed selection publishes once");
|
||||
var mode=a.ModeRequest;a.Hold(true);
|
||||
check(a.Held&&!b.Held&&a.ModeRequest!=mode,"holding Word affects only that window");
|
||||
check(a.Observe(40,40,true)==0&&a.Sequence==1,"held selection remains local without consuming a publication");
|
||||
check(!a.Accept(4,origin)&&a.LastSharedRevision==4,"held window records latest shared revision without navigation");
|
||||
a.Hold(false);
|
||||
check(a.Sequence==1&&a.Accept(4,origin),"release catches latest focus without publishing held position");
|
||||
check(!a.Accept(4,origin)&&!a.Accept(3,origin),"duplicate and delayed Word focus deliveries cannot navigate again");
|
||||
check(!a.Accept(5,a.Id)&&a.LastSharedRevision==5,"originating Word window does not echo its own selection");
|
||||
a.Hold(true);a.Observe(50,50,true);a.Hold(false);check(a.Accept(5,a.Id),"release returns to shared reference even when this same Word window originally published it");
|
||||
check(b.Accept(5,a.Id),"another following Word window can receive that selection");
|
||||
}
|
||||
}
|
||||
@ -37,6 +37,7 @@ namespace PlotDirector.WordAddIn
|
||||
try
|
||||
{
|
||||
Refresh("PlotDirectorStatus", GetStatus(null));
|
||||
Refresh("PlotDirectorHold",GetFocusHeld(null).ToString());Refresh("PlotDirectorFocusState",GetFocusState(null));
|
||||
Refresh("PlotDirectorBook", GetBookTip(null));
|
||||
Refresh("PlotDirectorChapter", GetChapterTip(null));
|
||||
Refresh("PlotDirectorScene", GetSceneTip(null));
|
||||
@ -68,6 +69,10 @@ namespace PlotDirector.WordAddIn
|
||||
ui?.InvalidateControl(control.Id);
|
||||
}
|
||||
|
||||
public bool GetFocusHeld(Office.IRibbonControl control)=>adapter()?.FocusHeld==true;
|
||||
public string GetFocusState(Office.IRibbonControl control)=>adapter()?.FocusStateLabel??"Following";
|
||||
public string GetFocusTip(Office.IRibbonControl control)=>GetFocusHeld(control)?"Release Hold: catch up to shared manuscript focus. Content synchronisation stays active.":"Hold this Word window at its local position. Other windows and content synchronisation continue.";
|
||||
public void ToggleFocusHold(Office.IRibbonControl control,bool pressed){adapter()?.SetFocusHeld(pressed);Invalidate();}
|
||||
public bool CanOpenBook(Office.IRibbonControl control) => adapter()?.HasRibbonBook == true;
|
||||
public string GetBookTip(Office.IRibbonControl control) => adapter()?.RibbonBook ?? "No linked book";
|
||||
public string GetChapterTip(Office.IRibbonControl control) => adapter()?.RibbonChapter ?? "Chapter unverified";
|
||||
|
||||
@ -23,7 +23,7 @@
|
||||
<ProjectReference Include="..\Protocol\PlotDirector.Companion.Protocol.csproj"><Name>PlotDirector.Companion.Protocol</Name></ProjectReference>
|
||||
<ProjectReference Include="..\Client\PlotDirector.Companion.Client.csproj"><Name>PlotDirector.Companion.Client</Name></ProjectReference>
|
||||
<Compile Include="ThisAddIn.cs" /><Compile Include="ThisAddIn.Designer.cs"><DependentUpon>ThisAddIn.cs</DependentUpon></Compile>
|
||||
<Compile Include="WordAdapter.cs" /><Compile Include="WordChapterRead.cs" />
|
||||
<Compile Include="WordAdapter.cs" /><Compile Include="WordFocus.cs" /><Compile Include="WordChapterRead.cs" />
|
||||
<Compile Include="WordChapterPositions.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<None Include="ThisAddIn.Designer.xml"><DependentUpon>ThisAddIn.cs</DependentUpon></None>
|
||||
<EmbeddedResource Include="Ribbon.xml" />
|
||||
|
||||
@ -7,6 +7,7 @@
|
||||
<editBox id="PlotDirectorChapter" label="Chapter" getText="GetChapterTip" getSupertip="GetChapterTip" onChange="RestoreTitle" sizeString="MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" />
|
||||
<editBox id="PlotDirectorScene" label="Scene" getText="GetSceneTip" getSupertip="GetSceneTip" onChange="RestoreTitle" sizeString="MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" />
|
||||
</group>
|
||||
<group id="PlotDirectorSharedFocus" label="Manuscript focus"><toggleButton id="PlotDirectorHold" label="Hold / Follow" imageMso="Lock" getPressed="GetFocusHeld" onAction="ToggleFocusHold" getSupertip="GetFocusTip"/><editBox id="PlotDirectorFocusState" label="State" getText="GetFocusState" onChange="RestoreTitle" sizeString="MMMMMMMMMMMMMMMMMMMMMMMM"/></group>
|
||||
<group id="PlotDirectorWriting" label="Writing">
|
||||
<button id="PlotDirectorContext" label="Writing Context" size="large" imageMso="ReadingMode" onAction="OpenContext" getEnabled="CanOpenBook" />
|
||||
<button id="PlotDirectorIntent" label="Writing Intent" size="large" imageMso="ReviewNewComment" onAction="OpenIntent" getEnabled="CanOpenBook" />
|
||||
|
||||
@ -102,6 +102,7 @@ namespace PlotDirector.WordAddIn
|
||||
invalidateRibbon();
|
||||
});
|
||||
link.Received += message => {
|
||||
if(!string.IsNullOrEmpty(message.SharedFocusStatus))PostToUi(()=>{sharedFocusStatus=message.SharedFocusStatus;invalidateRibbon?.Invoke();});
|
||||
if(message.Status=="ready")PostToUi(()=>{var capabilities=(message.Capabilities??"").Split(',');traySupported=capabilities.Contains(ProtocolVersion.TrayCapability);liveChapterTextSupported=capabilities.Contains(ProtocolVersion.LiveChapterTextCapability);nativeChapterTextSupported=capabilities.Contains(ProtocolVersion.NativeChapterTextCapability);nativeChapterPositionsSupported=capabilities.Contains(ProtocolVersion.NativeChapterPositionsCapability);});
|
||||
if(message.ChapterStatusProvided&&message.SessionId!=Guid.Empty)PostToUi(()=>ReceiveChapterStatus(message));
|
||||
if((message.Action=="tray-sync"||message.Action=="tray-repair")&&message.Status!="ok")PostToUi(()=>{
|
||||
@ -189,7 +190,7 @@ namespace PlotDirector.WordAddIn
|
||||
})) pendingOpen.Remove(document);
|
||||
}
|
||||
private void Activate(Word.Document document,Word.Window window) { activationPending=true;Open(document); ScheduleSelection(); }
|
||||
private void SelectionChanged(Word.Selection selection) { selectionNotifications++;ScheduleSelection(); }
|
||||
private void SelectionChanged(Word.Selection selection) { selectionNotifications++;MarkDeliberateFocus();ScheduleSelection(); }
|
||||
private void ScheduleSelection()
|
||||
{
|
||||
if (disposed) return;
|
||||
@ -226,7 +227,8 @@ namespace PlotDirector.WordAddIn
|
||||
|
||||
if(active!=state||activationPending){link.TryPost(new Message {Kind="active",SessionId=state.Session,Revision=state.Revision});activationPending=false;}
|
||||
ChangeActiveDocument(state);
|
||||
link.TryPost(new Message {Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,WordSaved=saved&&Com(()=>application.BackgroundSavingStatus)==0,WordObservedUtc=observationStartedUtc,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
|
||||
var focusObservation=FocusObservation(document,start,end);
|
||||
link.TryPost(new Message {CanSharedFocus=focusObservation.CanSharedFocus,FocusHeld=focusObservation.FocusHeld,AnyFollowingWindows=focusObservation.AnyFollowingWindows,FocusWindowID=focusObservation.FocusWindowID,FocusModeRequest=focusObservation.FocusModeRequest,DeliberateFocusSequence=focusObservation.DeliberateFocusSequence,Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,WordSaved=saved&&Com(()=>application.BackgroundSavingStatus)==0,WordObservedUtc=observationStartedUtc,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
|
||||
// Prose is read only on an explicit Companion request; cursor observations never rescan it.
|
||||
|
||||
}
|
||||
@ -283,7 +285,7 @@ namespace PlotDirector.WordAddIn
|
||||
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.");
|
||||
Metric("navigation-identity-and-target",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationClock.Restart();Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));Com(()=>{range.Select();return true;});Metric("navigation-word-selection",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationExecutions++;lastNavigationId=command.Id;if(completedNavigationIds.Count==64)completedNavigationIds.Dequeue();completedNavigationIds.Enqueue(command.Id);}finally{Release(range);}
|
||||
Metric("navigation-identity-and-target",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationClock.Restart();Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));if(command.BackgroundFocus)FollowSharedFocus(doc.Document,command,range);else Com(()=>{range.Select();return true;});Metric("navigation-word-selection",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationExecutions++;lastNavigationId=command.Id;if(completedNavigationIds.Count==64)completedNavigationIds.Dequeue();completedNavigationIds.Enqueue(command.Id);}finally{Release(range);}
|
||||
}
|
||||
else if(command.Kind=="associate"){
|
||||
if(command.Remember){
|
||||
|
||||
29
PlotDirector.NativeCompanion/Vsto/WordFocus.cs
Normal file
29
PlotDirector.NativeCompanion/Vsto/WordFocus.cs
Normal file
@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using Word=Microsoft.Office.Interop.Word;
|
||||
namespace PlotDirector.WordAddIn
|
||||
{
|
||||
public sealed partial class WordAdapter
|
||||
{
|
||||
[DllImport("user32.dll")]private static extern short GetAsyncKeyState(int key);
|
||||
[DllImport("user32.dll")]private static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")]private static extern uint GetWindowThreadProcessId(IntPtr window,out uint process);
|
||||
private readonly Dictionary<int,FocusWindowState> focusWindows=new Dictionary<int,FocusWindowState>();
|
||||
private readonly uint focusProcessId=(uint)Process.GetCurrentProcess().Id;private Guid deliberateFocusWindow;private bool deliberateFocusPending,applyingFocus;private string sharedFocusStatus="";
|
||||
private FocusWindowState FocusWindow(Word.Window window){var handle=Com(()=>window.Hwnd);FocusWindowState state;if(!focusWindows.TryGetValue(handle,out state))focusWindows[handle]=state=new FocusWindowState();return state;}
|
||||
private FocusWindowState ActiveFocusWindow(){Word.Window window=null;try{window=Com(()=>application.ActiveWindow);return window==null?null:FocusWindow(window);}catch(COMException){return null;}finally{Release(window);}}
|
||||
public bool FocusHeld=>ActiveFocusWindow()?.Held==true;
|
||||
public string FocusStateLabel=>FocusHeld?"Held · Release Hold":sharedFocusStatus=="word-unmapped"?"Following · mapping unavailable":sharedFocusStatus=="save-required"?"Following · save Word first":sharedFocusStatus=="word-busy"?"Following · Word busy":"Following · Hold available";
|
||||
public void SetFocusHeld(bool held){var state=ActiveFocusWindow();if(state==null)return;state.Hold(held);deliberateFocusPending=false;scheduler.Post("selection",CaptureSelection);invalidateRibbon?.Invoke();}
|
||||
private void MarkDeliberateFocus(){uint process;GetWindowThreadProcessId(GetForegroundWindow(),out process);if(applyingFocus||process!=focusProcessId)return;foreach(var key in new[]{1,37,38,39,40,33,34,35,36,9})if((GetAsyncKeyState(key)&0x8000)!=0){deliberateFocusPending=true;deliberateFocusWindow=ActiveFocusWindow()?.Id??Guid.Empty;break;}}
|
||||
private Message FocusObservation(Word.Document document,int start,int end){var state=ActiveFocusWindow();var pending=deliberateFocusPending&&state?.Id==deliberateFocusWindow;deliberateFocusPending=false;bool any=false;Word.Windows windows=null;var alive=new HashSet<int>();try{windows=Com(()=>application.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);alive.Add(Com(()=>window.Hwnd));}finally{Release(window);}}foreach(var handle in focusWindows.Keys.Where(k=>!alive.Contains(k)).ToArray())focusWindows.Remove(handle);Release(windows);windows=Com(()=>document.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);if(!FocusWindow(window).Held)any=true;}finally{Release(window);}}}finally{Release(windows);}return new Message{CanSharedFocus=true,FocusWindowID=state?.Id??Guid.Empty,FocusHeld=state?.Held==true,AnyFollowingWindows=any,FocusModeRequest=state?.ModeRequest??Guid.Empty,DeliberateFocusSequence=state?.Observe(start,end,pending&&!applyingFocus)??0};}
|
||||
private void FollowSharedFocus(Word.Document document,AdapterCommand command,Word.Range range)
|
||||
{
|
||||
Word.Windows windows=null;bool eligible=false,followed=false;applyingFocus=true;try{windows=Com(()=>document.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);var state=FocusWindow(window);if(!state.Accept(command.FocusVersion,command.FocusOriginWindowID))continue;eligible=true;Com(()=>{object atStart=true;window.ScrollIntoView(range,ref atStart);return true;});followed=true;}finally{Release(window);}}if(eligible&&!followed)throw new InvalidOperationException("Word could not follow in the background; its editing selection was retained.");}finally{applyingFocus=false;Release(windows);invalidateRibbon?.Invoke();}
|
||||
}
|
||||
}
|
||||
}
|
||||
48
PlotLine.Tests/Browser/shared-manuscript-focus.cjs
Normal file
48
PlotLine.Tests/Browser/shared-manuscript-focus.cjs
Normal file
@ -0,0 +1,48 @@
|
||||
// Real authenticated Development database + SignalR acceptance; synthetic fixture only.
|
||||
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
|
||||
const base=process.env.PD_SHARED_FOCUS_URL||'http://127.0.0.1:5258';
|
||||
(async()=>{
|
||||
const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync('/tmp/shared-focus-browser-scope.json'));
|
||||
assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-'));
|
||||
const installed=process.argv.includes('--installed');const profile=installed?fs.mkdtempSync('/tmp/pd-shared-focus-pwa-'):null;const persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1500,height:1000}}):null;const browser=persistent?.browser()||await chromium.launch();let step='login';const errors=[];
|
||||
try{
|
||||
const c=persistent||await browser.newContext({viewport:{width:1500,height:1000}});
|
||||
await c.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
|
||||
await c.addInitScript(user=>{try{localStorage.setItem('plotdirector.desktop.v1.'+user,JSON.stringify({dismissedAt:Date.now()}));}catch{}},who.UserID);
|
||||
const sockets=new WeakMap();let wordCommands=0;c.on('request',r=>{if(/\/(WriterWord|Writing\/Context)\/Navigate/.test(new URL(r.url()).pathname))wordCommands++;});c.on('page',p=>{const rows=[];sockets.set(p,rows);p.on('websocket',socket=>{const row={url:socket.url(),closed:false};rows.push(row);socket.on('close',()=>row.closed=true);});p.on('pageerror',e=>{errors.push(e.message);console.error('Browser error: '+e.message);});});
|
||||
const login=await c.newPage();await login.goto(base+'/Account/Login');await login.locator('[name=Email]').fill(who.Email);await login.locator('[name=Password]').fill(who.Password);await Promise.all([login.waitForURL(u=>u.pathname!='/Account/Login'),login.locator('button[type=submit]').click()]);
|
||||
let desktop;if(installed){await login.goto(`${base}/Projects/Details/${s.project}`);desktop=await browser.newBrowserCDPSession();await desktop.send('PWA.install',{manifestId:base+'/Projects',installUrlOrBundleUrl:`${base}/Projects/Details/${s.project}`});await desktop.send('PWA.changeAppUserSettings',{manifestId:base+'/Projects',displayMode:'standalone'});}
|
||||
async function surface(url){if(!installed){const p=await c.newPage();await p.goto(url);return p;}const opened=c.waitForEvent('page');await desktop.send('PWA.launch',{manifestId:base+'/Projects',url});const p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));return p;}
|
||||
const contextURL=`${base}/Writing/Context?projectId=${s.project}&bookId=${s.book}&sceneId=${s.scene1}`;
|
||||
const ready=async p=>{await p.waitForFunction(()=>window.PlotDirectorSharedFocus&&document.querySelector('[data-context-workspace]')?.contextController?.connection?.state==='Connected');await p.waitForSelector('[data-context-tab-fragment]');};
|
||||
const scene=async(p,id)=>p.waitForFunction(id=>document.querySelector('[data-context-workspace]').contextController.position.sceneId===id,id);
|
||||
const current=p=>p.evaluate(()=>window.PlotDirectorSharedFocus.shared);
|
||||
const a=await surface(contextURL);await ready(a);
|
||||
step='Context alone publishes without Word';await a.selectOption('[data-context-scene]',String(s.scene2));await a.waitForFunction(id=>window.PlotDirectorSharedFocus.shared?.sceneID===id,s.scene2);await a.selectOption('[data-context-scene]',String(s.scene1));await a.waitForFunction(id=>window.PlotDirectorSharedFocus.shared?.sceneID===id,s.scene1);
|
||||
await a.click('[data-shared-focus-hold]');await a.selectOption('[data-context-scene]',String(s.scene2));await scene(a,s.scene2);assert.equal((await current(a)).sceneID,s.scene1);
|
||||
const b=await surface(contextURL);await ready(b);await scene(b,s.scene1);assert.equal(await b.evaluate(()=>PlotDirectorSharedFocus.held),false);
|
||||
assert.notEqual(await a.evaluate(()=>PlotDirectorSharedFocus.windowID),await b.evaluate(()=>PlotDirectorSharedFocus.windowID));
|
||||
await a.waitForTimeout(450);let heldFocusFetches=0;a.on('request',r=>{if(new URL(r.url()).pathname.startsWith('/Writing/Context/Tabs/'))heldFocusFetches++;});step='Review alone/Context paragraph publication';const review=await surface(`${base}/Writer/Review?projectId=${s.project}&bookId=${s.book}&chapterId=${s.chapter1}`);await review.waitForFunction(()=>window.PlotDirectorSharedFocus?.shared?.chapterID);await review.waitForSelector(`.manuscript-reader [data-paragraph-id="${s.paragraph2}"]`);
|
||||
const before=(await current(review)).version;await review.mouse.wheel(0,200);await review.waitForTimeout(300);assert.equal((await current(review)).version,before,'scroll is local');
|
||||
await review.locator(`.manuscript-reader [data-paragraph-id="${s.paragraph2}"]`).click();await scene(b,s.scene2);await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);await review.waitForFunction(p=>PlotDirectorSharedFocus.shared.paragraphID===p,s.paragraph2);
|
||||
step='Next crosses chapters without Word';await b.locator('[data-context-next]').click();await scene(b,s.scene3);await review.waitForSelector(`.manuscript-reader [data-paragraph-id="${s.paragraph3}"]`);await scene(a,s.scene2);
|
||||
assert.equal(heldFocusFetches,0,'shared focus alone does not refetch a held pane');await b.click('[data-context-previous]');await scene(b,s.scene2);await b.click('[data-context-next]');await scene(b,s.scene3);const latest=(await current(b)).version;await a.click('[data-context-go-focus]');await scene(a,s.scene3);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);assert.equal((await current(a)).version,latest);await a.selectOption('[data-context-scene]',String(s.scene2));await scene(a,s.scene2);await a.reload();await ready(a);await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);
|
||||
step='release catches latest without publishing';await a.click('[data-shared-focus-hold]');await scene(a,s.scene3);assert.equal((await current(a)).version,latest);assert.equal((await current(b)).version,latest);
|
||||
step='held Review local navigation';await review.locator('[data-shared-focus-hold]:visible').first().click();await review.evaluate(s=>PlotDirectorSharedFocus.navigate({chapterID:s.chapter1,paragraphID:s.paragraph1}),s);await review.waitForSelector(`.manuscript-reader [data-paragraph-id="${s.paragraph1}"]`);assert.equal((await current(review)).version,latest);await scene(b,s.scene3);await review.locator('[data-shared-focus-hold]:visible').first().click();await review.waitForSelector(`.manuscript-reader [data-paragraph-id="${s.paragraph3}"]`);
|
||||
step='rapid navigation serializes latest intent';await b.evaluate(async s=>{void PlotDirectorSharedFocus.navigate({sceneID:s.scene1});void PlotDirectorSharedFocus.navigate({sceneID:s.scene2});void PlotDirectorSharedFocus.navigate({sceneID:s.scene3});},s);await b.waitForFunction(s=>PlotDirectorSharedFocus.shared.sceneID===s.scene3&&PlotDirectorSharedFocus.shared.version>0,s);await b.waitForTimeout(700);assert.equal((await current(b)).sceneID,s.scene3);
|
||||
step='duplicate/delayed events cannot overwrite';const stable=await current(b);await b.evaluate(p=>{const conn=document.querySelector('[data-context-workspace]').contextController.connection;const handlers=Object.values(conn).find(v=>Array.isArray(v?.manuscriptfocuschanged))?.manuscriptfocuschanged;if(!handlers)throw Error('Focus receiver was not registered');for(const handler of handlers)handler({...p,version:p.version-1,sceneID:1});},stable);assert.equal((await current(b)).sceneID,s.scene3);
|
||||
step='held cross-scene relationship invalidation in split panes';await a.click('[data-shared-focus-hold]');await a.selectOption('[data-context-scene]',String(s.scene2));await scene(a,s.scene2);await a.selectOption('[data-context-layout]','columns');await a.selectOption('[data-context-pane="0"] [data-context-tab]','relationships');await a.selectOption('[data-context-pane="1"] [data-context-tab]','characters');await a.waitForSelector('[data-context-pane="0"] [data-context-tab-fragment]');await a.waitForSelector('[data-context-pane="1"] [data-context-tab-fragment]');
|
||||
await a.click('[data-relationship-lens=story]');await a.waitForTimeout(400);let graphAfter=null;let invalidated=0,refreshed=new Set();a.on('response',async r=>{const u=new URL(r.url());if(u.pathname==='/Writing/Context/Relationships/Graph'&&r.ok())graphAfter=await r.json().catch(()=>null);if(u.pathname.startsWith('/Writing/Context/Tabs/')){invalidated++;refreshed.add(u.pathname);}});
|
||||
const edit=await surface(`${base}/Characters/Workspace/Operation/${s.character1}?relationshipId=${s.relationship}&eventId=${s.relationshipEvent}&operation=event-edit`);const changeNote='Changed earlier-scene fixture '+Date.now();await edit.locator('[name=Notes]').fill(changeNote);await edit.locator('[name=Intensity]').fill('8');
|
||||
const saved=await edit.evaluate(async()=>{const form=document.querySelector('form');const response=await fetch(form.action,{method:'POST',body:new FormData(form)});return {status:response.status,text:await response.text()};});assert.equal(saved.status,200,saved.text.slice(0,200));assert.match(saved.text,/saved/);
|
||||
await a.waitForFunction(()=>window.PlotDirectorSharedFocus.held===true);await a.waitForTimeout(1800);assert(refreshed.has('/Writing/Context/Tabs/relationships')&&refreshed.has('/Writing/Context/Tabs/characters'),'both affected visible panes refreshed');assert.equal(graphAfter?.links?.find(l=>l.id===s.relationship)?.notes,changeNote,'held later-scene graph contains the new earlier-scene note');await scene(a,s.scene2);assert.equal((await current(a)).sceneID,s.scene3);
|
||||
step='reconnect catches current shared reference';await b.evaluate(async()=>{const c=document.querySelector('[data-context-workspace]').contextController.connection;await c.stop();await c.start();await PlotDirectorSharedFocus.refresh(true);});await scene(b,s.scene3);
|
||||
step='new window does not inherit Hold';const fresh=await surface(contextURL);await ready(fresh);await scene(fresh,s.scene3);assert.equal(await fresh.evaluate(()=>PlotDirectorSharedFocus.held),false);
|
||||
step='duplicated session state cannot inherit Hold';const clone=await c.newPage();const storage=await a.evaluate(()=>Object.fromEntries(Object.entries(sessionStorage).filter(([k])=>k.startsWith('pd.shared-focus')||k==='plotdirector.context.window.v1')));await clone.addInitScript(values=>{for(const[k,v]of Object.entries(values))sessionStorage.setItem(k,v);},storage);await clone.goto(contextURL);await ready(clone);await clone.waitForFunction(id=>!PlotDirectorSharedFocus.held&&PlotDirectorSharedFocus.windowID!==id,await a.evaluate(()=>PlotDirectorSharedFocus.windowID));await scene(clone,s.scene3);
|
||||
step='hidden affected tab is fetched when activated';const beforeHidden=invalidated;await a.selectOption('[data-context-pane="1"] [data-context-tab]','overview');await a.waitForTimeout(600);assert(invalidated>beforeHidden);await scene(a,s.scene2);
|
||||
step='responsive Hold control';for(const width of[1500,760,390]){await a.setViewportSize({width,height:900});assert(await a.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),'Context overflow at '+width);}await a.setViewportSize({width:1500,height:1000});
|
||||
if(process.argv.includes('--restart')){step='actual server restart recovery';const revision=(await current(b)).version;await b.evaluate(()=>{const root=document.querySelector('[data-context-workspace]');root.contextController.connection.onreconnected(()=>window.__sharedFocusRestartRecovered=true);root.addEventListener('context-connection-ready',()=>window.__sharedFocusRestartRecovered=true,{once:true});});fs.writeFileSync('/tmp/shared-focus-restart-ready','ready');await b.waitForFunction(()=>window.__sharedFocusRestartRecovered,null,{timeout:55000});await scene(b,s.scene3);await a.waitForFunction(()=>[...document.querySelectorAll('[data-shared-focus-status]')].some(n=>/no longer valid/.test(n.textContent)));await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);assert.equal((await current(b)).version,revision);await a.selectOption('[data-context-scene]',String(s.scene1));await scene(a,s.scene1);assert.equal((await current(a)).version,revision);console.log('PASS actual loopback server restart: latest focus persisted, SignalR reconnected, held scene retained and an offline structural change was validated without redirect.');}
|
||||
if(process.argv.includes('--structure')){step='structural archive retains held reference';const result=await edit.evaluate(async s=>{const token=document.querySelector('[name=__RequestVerificationToken]').value;const response=await fetch('/Scenes/Archive',{method:'POST',body:new URLSearchParams({id:s.scene2,chapterId:s.chapter1,__RequestVerificationToken:token})});return response.status;},s);assert.equal(result,200);await a.waitForFunction(()=>[...document.querySelectorAll('[data-shared-focus-status]')].some(n=>/no longer valid/.test(n.textContent)));await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);await a.selectOption('[data-context-scene]',String(s.scene1));await scene(a,s.scene1);assert.equal((await current(a)).sceneID,s.scene3);}
|
||||
assert.equal(wordCommands,0,'shared navigation never depends on or automatically invokes Word navigation');for(const p of[a,b,fresh,clone])assert.equal(sockets.get(p).filter(s=>!s.closed&&s.url.includes('/hubs/native-companion')).length,1,'one existing SignalR connection per Context window');assert.deepEqual(errors,[]);console.log('PASS real authenticated browser + SQL + SignalR: Context alone, Review↔Context without Word, scroll local, exact paragraphs/chapter crossing, per-window Hold, refresh/release, rapid/obsolete ordering, cross-scene relationship save refreshes both held panes, reconnect, new/duplicated-window isolation, Previous/Go without Word, hidden tabs and responsive Hold.');
|
||||
}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await persistent?.close();await browser.close();if(profile)fs.rmSync(profile,{recursive:true,force:true});}
|
||||
})();
|
||||
@ -25,7 +25,7 @@ internal static class NarrativeFocusDatabaseTests
|
||||
var factory=new Factory(builder.ConnectionString);var focus=new NarrativeFocus(factory);var objectives=new WriterObjectiveRepository(factory);
|
||||
var before=(await objectives.Read(fixture.UserID,fixture.BookID)).Objective!;
|
||||
var state=await focus.Read(fixture.UserID,fixture.ProjectID,fixture.BookID);
|
||||
if(state.SceneID!=fixture.SceneID||state.Positions.Count!=1||state.Recent.Single().SceneID!=fixture.SceneID)throw new Exception("Repository seed/position/history mapping failed");
|
||||
if(state.SceneID!=null||state.ChapterID!=null||state.Version!=0||state.Positions.Count!=1||state.Recent.Count!=0)throw new Exception("Read must not manufacture focus from a working objective");
|
||||
state=await focus.Set(fixture.UserID,fixture.ProjectID,fixture.BookID,fixture.ChapterID,null,state.Version);
|
||||
if(state.SceneID!=null||state.ChapterID!=fixture.ChapterID)throw new Exception("Repository chapter navigation failed");
|
||||
if(await focus.Open(fixture.UserID,null,fixture.SceneID,fixture.ProjectID,fixture.BookID+1)!=null)throw new Exception("Repository accepted an explicit destination in the wrong book");
|
||||
|
||||
@ -26,23 +26,25 @@ internal static class NarrativeNavigationTests
|
||||
var http=new DefaultHttpContext();http.Request.Method=item.Item3;http.Request.QueryString=new(item.Item4);
|
||||
if(item.Item4=="?ajax")http.Request.Headers["Sec-Fetch-Mode"]="cors";if(item.Item4=="?prefetch")http.Request.Headers["Sec-Purpose"]="prefetch";
|
||||
var route=new RouteData();route.Values["controller"]=item.Item1;route.Values["action"]=item.Item2;
|
||||
var action=new ActionContext(http,route,new ActionDescriptor());var filter=new NarrativeNavigationFilter(focus,user);
|
||||
var action=new ActionContext(http,route,new ActionDescriptor());var filter=new NarrativeNavigationFilter(user);
|
||||
var executing=new ActionExecutingContext(action,[],new Dictionary<string,object?>{{"id",31}},new object());
|
||||
var executed=new ActionExecutedContext(action,[],new object()){Result=item.Item5?new ViewResult():new NotFoundResult()};
|
||||
var before=writes;await filter.OnActionExecutionAsync(executing,()=>Task.FromResult(executed));
|
||||
if(writes-before!=(item.Item6?1:0))throw new Exception($"Narrative navigation classification failed: {item}");
|
||||
if(writes-before!=0)throw new Exception($"Narrative navigation classification failed: {item}");
|
||||
}
|
||||
var savedContext=new DefaultHttpContext();savedContext.Request.Method="POST";var savedRoute=new RouteData();savedRoute.Values["controller"]="Scenes";
|
||||
var saveAction=new ActionContext(savedContext,savedRoute,new ActionDescriptor());var redirect=new RedirectToActionResult("Edit","Scenes",new{id=31});
|
||||
var savedResult=new ActionExecutedContext(saveAction,[],new object()){Result=redirect};
|
||||
await new NarrativeNavigationFilter(focus,user).OnActionExecutionAsync(new(saveAction,[],new Dictionary<string,object?>(),new object()),()=>Task.FromResult(savedResult));
|
||||
await new NarrativeNavigationFilter(user).OnActionExecutionAsync(new(saveAction,[],new Dictionary<string,object?>(),new object()),()=>Task.FromResult(savedResult));
|
||||
if(redirect.RouteValues?["retainNarrativeFocus"] is not true)throw new Exception("Saving an editor must preserve independently navigated focus");
|
||||
var navigationController=new PlotLine.Controllers.NarrativeFocusController(focus,user);
|
||||
var navigationAction=new ActionExecutingContext(saveAction,[],new Dictionary<string,object?>(),navigationController);
|
||||
bool allowedNavigation=false;
|
||||
await new SubscriptionEnforcementFilter(user,NativeWorkflowTests.Proxy<ISubscriptionService>((_,_)=>throw new Exception("Narrative navigation must not require content-edit entitlement")))
|
||||
.OnActionExecutionAsync(navigationAction,()=>{allowedNavigation=true;return Task.FromResult(new ActionExecutedContext(saveAction,[],navigationController));});
|
||||
if(!allowedNavigation)throw new Exception("Read-only accounts must retain narrative navigation");
|
||||
Console.WriteLine("PASS deliberate narrative destinations commit focus; local visualisation, filtering, failed opens and edits submitted by POST do not");
|
||||
foreach(var navigationController in new Controller[]{new PlotLine.Controllers.NarrativeFocusController(focus,user),new PlotLine.Controllers.SharedFocusController(null!,user)})
|
||||
{
|
||||
var navigationAction=new ActionExecutingContext(saveAction,[],new Dictionary<string,object?>(),navigationController);
|
||||
bool allowedNavigation=false;
|
||||
await new SubscriptionEnforcementFilter(user,NativeWorkflowTests.Proxy<ISubscriptionService>((_,_)=>throw new Exception("Narrative navigation must not require content-edit entitlement")))
|
||||
.OnActionExecutionAsync(navigationAction,()=>{allowedNavigation=true;return Task.FromResult(new ActionExecutedContext(saveAction,[],navigationController));});
|
||||
if(!allowedNavigation)throw new Exception("Read-only accounts must retain narrative navigation");
|
||||
}
|
||||
Console.WriteLine("PASS page loads, refreshes, local inspection and editor return redirects never publish shared focus");
|
||||
}
|
||||
}
|
||||
|
||||
@ -15,6 +15,11 @@ using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.ViewModels;
|
||||
|
||||
if(args.Contains("--shared-focus-concurrent")){await SharedFocusDatabaseTests.Concurrent();return;}
|
||||
if(args.Contains("--shared-focus-cleanup")){await SharedFocusDatabaseTests.Concurrent(true);return;}
|
||||
if(args.Contains("--shared-focus-browser-host")){await SharedFocusBrowserHost.Run();return;}
|
||||
if(args.Contains("--shared-focus-database")){await SharedFocusDatabaseTests.Run(args.Last());return;}
|
||||
if(args.Contains("--shared-focus-browser-setup")){await SharedFocusDatabaseTests.Run(args.Last(),true);return;}
|
||||
if(args.Contains("--narrative-focus-database")){await NarrativeFocusDatabaseTests.Run(args.Last());return;}
|
||||
if(args.Contains("--production-investigation")){ProductionInvestigationTests.Run(args.Last());return;}
|
||||
if(args.Contains("--writer-investigation-diagnostics")){if(args.Contains("--acceptance"))InvestigationDiagnosticTests.Run();InvestigationDiagnosticTests.Export(args[^2],args[^1]);return;}
|
||||
|
||||
25
PlotLine.Tests/SharedFocusBrowserHost.cs
Normal file
25
PlotLine.Tests/SharedFocusBrowserHost.cs
Normal file
@ -0,0 +1,25 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
// Real authentication, controllers, stored procedures and SignalR, loopback only.
|
||||
// Never starts import, mail, AI, retention or other background workers.
|
||||
internal static class SharedFocusBrowserHost
|
||||
{
|
||||
public static async Task Run()
|
||||
{
|
||||
var line=File.ReadLines("/etc/plotdirector/plotdirector.env").Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection="));
|
||||
var value=line[(line.IndexOf('=')+1)..].Trim().Trim('"','\'');
|
||||
var sql=new SqlConnectionStringBuilder(value);
|
||||
if(sql.InitialCatalog!="PlotDirector_Development")throw new Exception("Development only");
|
||||
await using(var db=new SqlConnection(value)){await db.OpenAsync();using var command=db.CreateCommand();command.CommandText="SELECT DB_NAME()";if((string?)await command.ExecuteScalarAsync()!="PlotDirector_Development")throw new Exception("Wrong effective database");}
|
||||
Environment.SetEnvironmentVariable("ConnectionStrings__DefaultConnection",value);
|
||||
var app=PlotLine.Program.BuildApplication(["--environment=Development","--applicationName=PlotLine","--contentRoot="+Path.GetFullPath("PlotLine"),"--DataProtection:KeysPath=/tmp/shared-focus-test-keys"],builder=>{
|
||||
foreach(var item in builder.Services.Where(s=>s.ServiceType==typeof(IHostedService)).ToArray())builder.Services.Remove(item);
|
||||
builder.Configuration["SqlDiagnostics:Enabled"]="false";
|
||||
});
|
||||
app.Urls.Clear();app.Urls.Add("http://127.0.0.1:5258");await app.RunAsync();
|
||||
}
|
||||
}
|
||||
82
PlotLine.Tests/SharedFocusDatabaseTests.cs
Normal file
82
PlotLine.Tests/SharedFocusDatabaseTests.cs
Normal file
@ -0,0 +1,82 @@
|
||||
using System.Data;
|
||||
using System.Text.Json;
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Services.Manuscript;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
internal static class SharedFocusDatabaseTests
|
||||
{
|
||||
internal sealed record Fixture(int user,int project,int book,int chapter1,int chapter2,int scene1,int scene2,int scene3,Guid paragraph1,Guid paragraph2,Guid paragraph3,Guid manuscript,Guid session,int character1,int character2,int relationship,int relationshipEvent);
|
||||
public static async Task Concurrent(bool cleanup=false)
|
||||
{
|
||||
var fixture=JsonSerializer.Deserialize<Fixture>(File.ReadAllText("/tmp/shared-focus-browser-scope.json"))!;
|
||||
var line=File.ReadLines("/etc/plotdirector/plotdirector.env").Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection="));
|
||||
var connection=new SqlConnectionStringBuilder(line[(line.IndexOf('=')+1)..].Trim().Trim('"','\''));
|
||||
if(connection.InitialCatalog!="PlotDirector_Development")throw new Exception("Development only");
|
||||
await using var db=new SqlConnection(connection.ConnectionString);await db.OpenAsync();
|
||||
if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!="PlotDirector_Development")throw new Exception("Wrong effective database");
|
||||
if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID JOIN dbo.AppUser u ON u.UserID=a.UserID WHERE p.ProjectID=@project AND p.ProjectName=N'Disposable shared-focus integration' AND a.UserID=@user AND u.Email LIKE N'pwa-browser-%'",fixture)!=1)throw new Exception("Disposable fixture scope required");
|
||||
if(cleanup){await db.ExecuteAsync("UPDATE dbo.Books SET IsArchived=1 WHERE BookID=@book AND ProjectID=@project;UPDATE dbo.Characters SET IsArchived=1 WHERE ProjectID=@project;UPDATE dbo.Projects SET IsArchived=1 WHERE ProjectID=@project;",fixture);Console.WriteLine("PASS isolated browser fixture archived; no real project/content changed.");return;}
|
||||
async Task<SharedFocusPosition> Run(SqlConnection sql,string action,Guid window,int scene)=>await sql.QuerySingleAsync<SharedFocusPosition>("dbo.NarrativeFocus_Coordinate",new{Action=action,UserID=fixture.user,ProjectID=fixture.project,BookID=fixture.book,WindowID=window,Sequence=1,SceneID=scene},commandType:CommandType.StoredProcedure);
|
||||
var before=await Run(db,"read",Guid.NewGuid(),fixture.scene1);
|
||||
var pending=Enumerable.Range(0,16).Select(async index=>{await using var sql=new SqlConnection(connection.ConnectionString);await sql.OpenAsync();return await Run(sql,"publish",Guid.NewGuid(),index%2==0?fixture.scene1:fixture.scene3);}).ToArray();
|
||||
var results=await Task.WhenAll(pending);var after=await Run(db,"read",Guid.NewGuid(),fixture.scene1);var changed=results.Where(r=>r.Changed).Select(r=>r.Version).Order().ToArray();
|
||||
if(changed.Length<2||!changed.SequenceEqual(Enumerable.Range(1,changed.Length).Select(n=>before.Version+n))||after.Version!=changed.Last())throw new Exception("Concurrent publications lost/duplicated revision order");
|
||||
Console.WriteLine("PASS sixteen real concurrent SQL connections: accepted changes receive contiguous unique revisions, final durable read equals highest accepted revision.");
|
||||
await SharedFocusNativeDeliveryTests.Run(connection.ConnectionString,fixture);
|
||||
}
|
||||
public static async Task Run(string scopePath,bool persist=false)
|
||||
{
|
||||
var line=File.ReadLines("/etc/plotdirector/plotdirector.env").Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection="));var builder=new SqlConnectionStringBuilder(line[(line.IndexOf('=')+1)..].Trim().Trim('"','\''));if(builder.InitialCatalog!="PlotDirector_Development")throw new Exception("Development only");await using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!="PlotDirector_Development")throw new Exception("Wrong effective database");var scope=JsonDocument.Parse(File.ReadAllText(scopePath)).RootElement;int project=scope.GetProperty("project").GetInt32(),user=scope.GetProperty("user").GetInt32();if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.ProjectUserAccess a JOIN dbo.AppUser u ON u.UserID=a.UserID WHERE a.ProjectID=@project AND a.UserID=@user AND a.AccessRole=N'Owner' AND a.IsActive=1 AND u.Email LIKE N'pwa-browser-%'",new{project,user})!=1)throw new Exception("Explicit disposable account required");
|
||||
using var tx=db.BeginTransaction();
|
||||
try{
|
||||
// Isolated collaborator fixture: no existing project/content or subscription is modified.
|
||||
project=await db.QuerySingleAsync<int>("INSERT dbo.Projects(ProjectName) VALUES(N'Disposable shared-focus integration');SELECT CAST(SCOPE_IDENTITY() AS int)",transaction:tx);
|
||||
await db.ExecuteAsync("INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole) VALUES(@project,@user,N'Collaborator')",new{project,user},tx);
|
||||
var ids=await db.QuerySingleAsync<(int Book,int C1,int C2,int S1,int S2,int S3)>("""
|
||||
DECLARE @revision int=(SELECT TOP(1) RevisionStatusID FROM dbo.RevisionStatuses ORDER BY RevisionStatusID),@time int=(SELECT TOP(1) TimeModeID FROM dbo.TimeModes),@confidence int=(SELECT TOP(1) TimeConfidenceID FROM dbo.TimeConfidences);
|
||||
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@project,N'Shared focus disposable fixture',999999,999999);DECLARE @book int=SCOPE_IDENTITY();
|
||||
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,2,N'Focus fixture first',10,@revision);DECLARE @c1 int=SCOPE_IDENTITY();
|
||||
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,1,N'Focus fixture second',20,@revision);DECLARE @c2 int=SCOPE_IDENTITY();
|
||||
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@c1,200,N'Focus fixture early',10,@time,@confidence,@revision);DECLARE @s1 int=SCOPE_IDENTITY();
|
||||
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@c1,1,N'Focus fixture late',20,@time,@confidence,@revision);DECLARE @s2 int=SCOPE_IDENTITY();
|
||||
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@c2,1,N'Focus fixture next chapter',10,@time,@confidence,@revision);DECLARE @s3 int=SCOPE_IDENTITY();
|
||||
SELECT @book Book,@c1 C1,@c2 C2,@s1 S1,@s2 S2,@s3 S3;
|
||||
""",new{project},tx);
|
||||
Guid manuscript=Guid.NewGuid(),session=Guid.NewGuid(),p1=Guid.NewGuid(),p2=Guid.NewGuid(),p3=Guid.NewGuid(),sk1=Guid.NewGuid(),sk2=Guid.NewGuid(),sk3=Guid.NewGuid();string hash=new('A',64);
|
||||
var state=new ParagraphManuscript{BookId=ids.Book,ProjectId=project,ManuscriptId=manuscript,SessionId=session,WordRevision=1,Revision=1,LastRequestId=Guid.NewGuid(),UpdatedUtc=DateTime.UtcNow,Paragraphs=[new(){ChapterId=ids.C1,SceneId=sk1,Story=true,PositionVerified=true,Occurrence=new(){Id=p1,Start=10,End=20,Text="Isolated focus paragraph one."}},new(){ChapterId=ids.C1,SceneId=sk2,Story=true,PositionVerified=true,Occurrence=new(){Id=p2,Start=20,End=30,Text="Isolated focus paragraph two."}},new(){ChapterId=ids.C2,SceneId=sk3,Story=true,PositionVerified=true,Occurrence=new(){Id=p3,Start=40,End=50,Text="Isolated focus paragraph three."}}],Scenes=[new(){Id=sk1,CanonicalId=ids.S1,ChapterId=ids.C1},new(){Id=sk2,CanonicalId=ids.S2,ChapterId=ids.C1},new(){Id=sk3,CanonicalId=ids.S3,ChapterId=ids.C2}],ChapterCheckpoints=[new(){ChapterId=ids.C1,ContentHash=hash,IdentityHash=hash,MappingHash=hash},new(){ChapterId=ids.C2,ContentHash=hash,IdentityHash=hash,MappingHash=hash}]};
|
||||
await db.ExecuteAsync("INSERT dbo.BookParagraphManuscripts(BookID,ManuscriptID,Revision,RequestID,Payload) VALUES(@book,@manuscript,1,NEWID(),@payload)",new{book=ids.Book,manuscript,payload=JsonSerializer.Serialize(state)},tx);
|
||||
foreach(var chapter in new[]{ids.C1,ids.C2})await db.ExecuteAsync("""
|
||||
INSERT dbo.BookChapterValidations(BookID,ChapterID,UserID,SessionID,ManuscriptID,WordRevision,RequestID,ContentHash,IdentityHash,MappingHash,Positions,SourceRevision,ValidatedUtc,ExpiresUtc)
|
||||
VALUES(@book,@chapter,@user,@session,@manuscript,1,NEWID(),@hash,@hash,@hash,@positions,1,SYSUTCDATETIME(),DATEADD(hour,2,SYSUTCDATETIME()));
|
||||
""",new{book=ids.Book,chapter,user,session,manuscript,hash,positions=JsonSerializer.Serialize(state.Paragraphs.Where(p=>p.ChapterId==chapter).Select(p=>new ChapterPosition(p.Occurrence.Id,p.Occurrence.Start,p.Occurrence.End,chapter,state.Scenes.Single(s=>s.Id==p.SceneId).CanonicalId,true)))},tx);
|
||||
int ca=await db.QuerySingleAsync<int>("dbo.Character_Save",new{ProjectID=project,CharacterName="Shared focus fixture A "+ids.Book},tx,commandType:CommandType.StoredProcedure),cb=await db.QuerySingleAsync<int>("dbo.Character_Save",new{ProjectID=project,CharacterName="Shared focus fixture B "+ids.Book},tx,commandType:CommandType.StoredProcedure);
|
||||
int type=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Friend'",transaction:tx),rs=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipStateID FROM dbo.RelationshipStates ORDER BY SortOrder,RelationshipStateID",transaction:tx);
|
||||
int rel=await db.QuerySingleAsync<int>("dbo.Relationship_Save",new{ProjectID=project,CharacterAID=ca,CharacterBID=cb,RelationshipTypeID=type,IsPermanent=true,IsKnownToReader=false,IsInitialRelationship=true,InitialBookID=ids.Book,InitialRelationshipStateID=rs,Notes="Disposable shared focus fixture"},tx,commandType:CommandType.StoredProcedure);
|
||||
int ev=await db.QuerySingleAsync<int>("dbo.RelationshipEvent_Save",new{CharacterRelationshipID=rel,SceneID=ids.S1,RelationshipStateID=rs,Intensity=3,IsKnownToOtherCharacter=true,Description="Disposable earlier-scene event"},tx,commandType:CommandType.StoredProcedure);
|
||||
await db.ExecuteAsync("""
|
||||
DECLARE @role int=(SELECT TOP(1) CharacterRoleInSceneTypeID FROM dbo.CharacterRoleInSceneTypes ORDER BY CharacterRoleInSceneTypeID),@presence int=(SELECT TOP(1) PresenceTypeID FROM dbo.PresenceTypes WHERE TypeName=N'Present');
|
||||
INSERT dbo.SceneCharacters(SceneID,CharacterID,RoleInSceneTypeID,PresenceTypeID) SELECT s.ID,c.ID,@role,@presence FROM (VALUES(@s1),(@s2),(@s3))s(ID) CROSS JOIN(VALUES(@ca),(@cb))c(ID);
|
||||
""",new{s1=ids.S1,s2=ids.S2,s3=ids.S3,ca,cb},tx);
|
||||
var fixture=new Fixture(user,project,ids.Book,ids.C1,ids.C2,ids.S1,ids.S2,ids.S3,p1,p2,p3,manuscript,session,ca,cb,rel,ev);
|
||||
if(persist){tx.Commit();File.WriteAllText("/tmp/shared-focus-browser-scope.json",JsonSerializer.Serialize(fixture));Console.WriteLine("PASS isolated shared-focus browser fixture prepared; no real manuscript used.");return;}
|
||||
void Check(bool condition,string name){if(!condition)throw new Exception(name);Console.WriteLine("PASS shared focus SQL: "+name);}
|
||||
async Task<SharedFocusPosition> Run(string action,Guid? window=null,long sequence=0,int? chapter=null,int? scene=null,Guid? paragraph=null,int direction=0)=>await db.QuerySingleAsync<SharedFocusPosition>("dbo.NarrativeFocus_Coordinate",new{Action=action,UserID=user,ProjectID=project,BookID=ids.Book,WindowID=window,Sequence=sequence,ChapterID=chapter,SceneID=scene,ParagraphID=paragraph,Direction=direction},tx,commandType:CommandType.StoredProcedure);
|
||||
var a=Guid.NewGuid();var b=Guid.NewGuid();var empty=await Run("read");Check(empty.Version==0&&!empty.IsValid,"new clients do not manufacture or publish initial focus");
|
||||
var first=await Run("publish",a,1,scene:ids.S1);Check(first.Version==1&&first.Changed&&first.ChapterID==ids.C1,"scene resolves its canonical chapter and receives atomic revision one");
|
||||
var same=await Run("publish",a,2,scene:ids.S1);Check(!same.Changed&&same.Version==1,"unchanged effective focus does not broadcast or increment revision");
|
||||
var second=await Run("publish",b,1,paragraph:p2);Check(second.Version==2&&second.ParagraphID==p2&&second.SceneID==ids.S2,"accepted paragraph resolves canonical chapter and scene without text in the packet");
|
||||
var duplicate=await Run("publish",a,1,scene:ids.S1);Check(duplicate.Version==2&&duplicate.ParagraphID==p2&&!duplicate.Changed,"replayed older client sequence cannot overwrite a newer window");
|
||||
var held=await Run("resolve",a,3,scene:ids.S3);var still=await Run("read");Check(held.ChapterID==ids.C2&&still.Version==2&&still.ParagraphID==p2,"held local navigation validates without changing shared state");
|
||||
var next=await Run("publish",b,2,direction:1);Check(next.SceneID==ids.S3&&next.Version==3,"scene stepping uses canonical sort order across chapter boundaries");
|
||||
await db.ExecuteAsync("UPDATE dbo.Scenes SET IsArchived=1 WHERE SceneID=@id",new{id=ids.S3},tx);var invalid=await Run("validate",scene:ids.S3,chapter:ids.C2);Check(!invalid.IsValid&&(await Run("read")).Version==3,"structural invalidation is explicit and never redirects a held reference");
|
||||
var mapped=await db.QuerySingleAsync<FocusWordPosition>("dbo.NarrativeFocus_WordPosition",new{Action="position",UserID=user,BookID=ids.Book,ManuscriptID=manuscript,SessionID=session,WordRevision=1,Cursor=12},tx,commandType:CommandType.StoredProcedure);Check(mapped.ParagraphID==p1,"native deliberate selection maps only through exact verified live evidence");
|
||||
var missing=await db.QueryAsync<FocusWordPosition>("dbo.NarrativeFocus_WordPosition",new{Action="target",UserID=user,BookID=ids.Book,ManuscriptID=manuscript,SessionID=Guid.NewGuid(),WordRevision=1,ParagraphID=p1},tx,commandType:CommandType.StoredProcedure);Check(!missing.Any(),"a different Word session never receives another session's offsets");
|
||||
var bad=await Run("validate",chapter:ids.C2,paragraph:p1);Check(!bad.IsValid,"incompatible paragraph/chapter references are rejected");
|
||||
try{await db.QuerySingleAsync<SharedFocusPosition>("dbo.NarrativeFocus_Coordinate",new{Action="read",UserID=-99,ProjectID=project,BookID=ids.Book},tx,commandType:CommandType.StoredProcedure);throw new Exception("Unauthorized scope accepted");}catch(SqlException e)when(e.Number==51000){Check(true,"ownership enforced for every focus read/write");}
|
||||
}finally{try{tx.Rollback();}catch(InvalidOperationException){}}
|
||||
Console.WriteLine("PASS shared focus fixture completely rolled back.");
|
||||
}
|
||||
}
|
||||
52
PlotLine.Tests/SharedFocusNativeDeliveryTests.cs
Normal file
52
PlotLine.Tests/SharedFocusNativeDeliveryTests.cs
Normal file
@ -0,0 +1,52 @@
|
||||
using System.Data;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Hubs;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
|
||||
// Real coordinator/SQL and the existing native queue, with a recording transport instead of Word.
|
||||
internal static class SharedFocusNativeDeliveryTests
|
||||
{
|
||||
private sealed class Factory(string value):ISqlConnectionFactory
|
||||
{public IDbConnection CreateConnection()=>new SqlConnection(value);}
|
||||
public static async Task Run(string value,SharedFocusDatabaseTests.Fixture f)
|
||||
{
|
||||
void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS shared native delivery: "+name);}
|
||||
var packets=new List<(string Name,object? Packet)>();
|
||||
var client=NativeWorkflowTests.Proxy<IClientProxy>((_,args)=>{packets.Add(((string)args![0]!,((object?[])args[1]!)[0]));return Task.CompletedTask;});
|
||||
var clients=NativeWorkflowTests.Proxy<IHubClients>((_,args)=>{Check((string)args![0]! ==NativeCompanionPresenceHub.UserGroup(f.user),"notifications use only the authenticated author group");return client;});
|
||||
var hub=NativeWorkflowTests.Proxy<IHubContext<NativeCompanionPresenceHub>>((_,_)=>clients);
|
||||
var store=new NativePresenceStore(TimeProvider.System);var instance=Guid.NewGuid();var window=Guid.NewGuid();var mode=Guid.NewGuid();
|
||||
var service=new SharedManuscriptFocus(new Factory(value),hub,store,NullLogger<SharedManuscriptFocus>.Instance);
|
||||
NativePresence Position(long sequence,bool held=false,bool saved=true)=>new(){BookId=f.book,ManuscriptId=f.manuscript,Revision=1,Sequence=sequence,WordSaved=saved,WordAvailable=true,WordRunning=true,CanAcknowledgeNavigation=true,CanSharedFocus=true,FocusHeld=held,AnyFollowingWindows=!held,FocusWindowID=window,FocusModeRequest=mode,CursorStart=12,DocumentTitle="Synthetic shared-focus fixture"};
|
||||
NativeLease Put(NativePresence position){Check(store.Put(f.user,"synthetic-focus-grant",DateTimeOffset.UtcNow.AddMinutes(10),instance,f.session,position),"exact native lease accepted");return store.Read(f.user,f.book).Single();}
|
||||
AdapterCommand? Take()=>store.TakeNavigation(f.user,"synthetic-focus-grant",instance,f.session);
|
||||
var first=Position(1);first.DeliberateFocusSequence=1;
|
||||
await service.NativeObservation(f.user,f.project,Put(first),false);
|
||||
var current=await service.Run(f.user,new(){ProjectID=f.project,BookID=f.book},"read");
|
||||
Check(current.ParagraphID==f.paragraph1&¤t.OriginWindowID==window,"Word alone publishes the verified canonical paragraph");
|
||||
var command=Take();Check(command?.BackgroundFocus==true&&command.Chapter?.Start==10&&command.FocusVersion==current.Version,"shared navigation uses the existing exact-session background command");
|
||||
var ack=Position(2);ack.NavigationAcknowledgedId=command!.Id;ack.NavigationResult="completed";Put(ack);
|
||||
var count=packets.Count;
|
||||
await service.NativeObservation(f.user,f.project,Put(Position(3)),false);
|
||||
Check(packets.Count==count&&(await service.Run(f.user,new(){ProjectID=f.project,BookID=f.book},"read")).Version==current.Version,"passive native presence neither publishes nor polls shared focus");
|
||||
var browserWindow=Guid.NewGuid();
|
||||
var next=await service.Run(f.user,new(){ProjectID=f.project,BookID=f.book,WindowID=browserWindow,Sequence=1,ParagraphID=f.paragraph3},"publish");
|
||||
command=Take();Check(command?.BackgroundFocus==true&&command.Chapter?.Start==40&&command.FocusVersion==next.Version&&command.FocusOriginWindowID==browserWindow,"browser focus queues the exact verified paragraph across chapters without activation semantics");
|
||||
ack=Position(4);ack.NavigationAcknowledgedId=command!.Id;ack.NavigationResult="completed";Put(ack);
|
||||
mode=Guid.NewGuid();var held=await service.NativeObservation(f.user,f.project,Put(Position(5,true)),true);
|
||||
Check(held=="held"&&Take()==null,"held Word consumes no shared navigation command");
|
||||
mode=Guid.NewGuid();await service.NativeObservation(f.user,f.project,Put(Position(6)),true);command=Take();
|
||||
Check(command?.BackgroundFocus==true&&command.FocusVersion==next.Version&&(await service.Run(f.user,new(){ProjectID=f.project,BookID=f.book},"read")).Version==next.Version,"Word release queues latest revision without publishing its old cursor");
|
||||
var failed=Position(7);failed.NavigationAcknowledgedId=command!.Id;failed.NavigationResult="failed";Check(await service.NativeObservation(f.user,f.project,Put(failed),true)=="word-busy"&&Take()==null,"failed background receipt is reported as busy rather than successful following");
|
||||
Check(await service.NativeObservation(f.user,f.project,Put(Position(8,saved:false)),true)=="save-required","unsaved Word reports its limitation while the coordinator stays available");
|
||||
var otherInstance=Guid.NewGuid();var otherSession=Guid.NewGuid();var other=Position(1);other.Sequence=1;
|
||||
Check(store.Put(f.user,"synthetic-other-session",DateTimeOffset.UtcNow.AddMinutes(10),otherInstance,otherSession,other),"independent native session accepted");
|
||||
var unmapped=await service.NativeObservation(f.user,f.project,store.Read(f.user,f.book).Single(l=>l.Instance==otherInstance),true);
|
||||
Check(unmapped=="word-unmapped"&&store.TakeNavigation(f.user,"synthetic-other-session",otherInstance,otherSession)==null,"unmapped sessions receive an explicit limitation and never another session's offsets");
|
||||
}
|
||||
}
|
||||
@ -11,6 +11,8 @@ BEGIN
|
||||
DECLARE @book int,@otherBook int,@chapter int,@otherChapter int,@empty int,@tail int,@first int,@last int,@version bigint,@i int=1;
|
||||
BEGIN TRY
|
||||
BEGIN TRANSACTION;
|
||||
INSERT dbo.Projects(ProjectName) VALUES(N'Disposable narrative focus regression');SET @project=SCOPE_IDENTITY();
|
||||
INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole) VALUES(@project,@user,N'Collaborator');
|
||||
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@project,N'Disposable narrative focus fixture',99999,99999);SET @book=SCOPE_IDENTITY();
|
||||
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@project,N'Disposable other scope',99999,99999);SET @otherBook=SCOPE_IDENTITY();
|
||||
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,1,N'Fixture first chapter',1,@revision);SET @chapter=SCOPE_IDENTITY();
|
||||
@ -26,12 +28,13 @@ BEGIN
|
||||
END;
|
||||
INSERT dbo.WriterWorkingObjectives(UserID,BookID,ChapterID,SceneID,Activity,Intention) VALUES(@user,@book,@chapter,@first,N'Revising',N'Independent original objective');
|
||||
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter AND SceneID=@first) THROW 51999,'Initial valid objective was not seeded',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID IS NULL AND SceneID IS NULL AND Version=0) THROW 51999,'Initial read manufactured focus from an objective',1;
|
||||
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@SceneID=@first,@ExpectedVersion=0;
|
||||
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@otherBook;
|
||||
IF @phase IN(1,2,3)
|
||||
BEGIN
|
||||
DECLARE @wrongUser int=CASE WHEN @phase=1 THEN -1 ELSE @user END,@wrongProject int=CASE WHEN @phase=2 THEN -1 ELSE @project END,@wrongBook int=CASE WHEN @phase=3 THEN @otherBook ELSE @book END;
|
||||
EXEC dbo.NarrativeFocus_Set @UserID=@wrongUser,@ProjectID=@wrongProject,@BookID=@wrongBook,@SceneID=@first,@ExpectedVersion=1;
|
||||
DECLARE @wrongUser int=CASE WHEN @phase=1 THEN -1 ELSE @user END,@wrongProject int=CASE WHEN @phase=2 THEN -1 ELSE @project END,@wrongBook int=CASE WHEN @phase=3 THEN @otherBook ELSE @book END,@wrongVersion bigint=CASE WHEN @phase=3 THEN 0 ELSE 1 END;
|
||||
EXEC dbo.NarrativeFocus_Set @UserID=@wrongUser,@ProjectID=@wrongProject,@BookID=@wrongBook,@SceneID=@first,@ExpectedVersion=@wrongVersion;
|
||||
THROW 51999,'Unauthorised focus accepted',1;
|
||||
END;
|
||||
IF @phase=4
|
||||
@ -80,18 +83,18 @@ BEGIN
|
||||
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@SceneID=@first,@ExpectedVersion=@version;
|
||||
UPDATE dbo.Scenes SET ChapterID=@otherChapter WHERE SceneID=@first;
|
||||
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter AND SceneID IS NULL) THROW 51999,'Moved scene was silently followed',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter AND SceneID=@first) THROW 51999,'Read redirected an invalid moved scene',1;
|
||||
IF EXISTS(SELECT 1 FROM dbo.NarrativeFocusHistory WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter AND SceneID=@first) THROW 51999,'Invalid history survived',1;
|
||||
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
|
||||
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@SceneID=@last,@ExpectedVersion=@version;
|
||||
DELETE dbo.Scenes WHERE SceneID=@last;
|
||||
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@otherChapter AND SceneID IS NULL) THROW 51999,'Deleted scene retained or silently retargeted',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@otherChapter AND SceneID=@last) THROW 51999,'Read redirected a deleted scene reference',1;
|
||||
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
|
||||
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@ChapterID=@chapter,@ExpectedVersion=@version;
|
||||
UPDATE dbo.Chapters SET IsArchived=1 WHERE ChapterID=@chapter;
|
||||
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
|
||||
IF EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID IS NOT NULL) THROW 51999,'Archived chapter retained',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter) THROW 51999,'Read redirected an archived chapter reference',1;
|
||||
EXEC dbo.WriterObjective @UserID=@user,@BookID=@book;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.WriterWorkingObjectives WHERE UserID=@user AND BookID=@book AND SceneID=@first AND ChapterID=@chapter) THROW 51999,'Invalid objective target mutated',1;
|
||||
ROLLBACK;
|
||||
|
||||
@ -10,6 +10,8 @@ DECLARE @user int,@project int,@book int,@chapter int,@scene int,@revision int,@
|
||||
SELECT TOP(1) @user=a.UserID,@project=p.ProjectID FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.IsActive=1 WHERE p.IsArchived=0 ORDER BY p.ProjectID;
|
||||
SELECT TOP(1) @revision=RevisionStatusID,@time=TimeModeID,@confidence=TimeConfidenceID FROM dbo.Scenes;
|
||||
IF @user IS NULL OR @revision IS NULL THROW 51999,'No fixture scope',1;
|
||||
INSERT dbo.Projects(ProjectName) VALUES(N'Disposable focus repository regression');SET @project=SCOPE_IDENTITY();
|
||||
INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole) VALUES(@project,@user,N'Collaborator');
|
||||
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@project,N'Disposable repository focus fixture',99999,99999);SET @book=SCOPE_IDENTITY();
|
||||
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,1,N'Repository fixture chapter',1,@revision);SET @chapter=SCOPE_IDENTITY();
|
||||
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@chapter,1,N'Repository fixture scene',1,@time,@confidence,@revision);SET @scene=SCOPE_IDENTITY();
|
||||
|
||||
@ -4,13 +4,13 @@ using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Services;
|
||||
namespace PlotLine.Controllers;
|
||||
[Authorize,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
|
||||
public sealed class NarrativeFocusController(INarrativeFocus focus,ICurrentUserService currentUser) : Controller
|
||||
public sealed class NarrativeFocusController(INarrativeFocus focus,ICurrentUserService currentUser,SharedManuscriptFocus? shared=null) : Controller
|
||||
{
|
||||
[HttpGet]
|
||||
public Task<IActionResult> Read(int projectId,int bookId) => Execute(() => focus.Read(currentUser.UserId!.Value,projectId,bookId));
|
||||
[HttpPost,ValidateAntiForgeryToken]
|
||||
public Task<IActionResult> Set(int projectId,int bookId,int? chapterId,int? sceneId,long version,int direction=0) =>
|
||||
Execute(() => focus.Set(currentUser.UserId!.Value,projectId,bookId,chapterId,sceneId,version,direction));
|
||||
Execute(async () => {var state=await focus.Set(currentUser.UserId!.Value,projectId,bookId,chapterId,sceneId,version,direction);if(shared!=null)await shared.Announce(currentUser.UserId.Value,projectId,bookId);return state;});
|
||||
private async Task<IActionResult> Execute(Func<Task<NarrativeFocusState>> operation)
|
||||
{
|
||||
if(currentUser.UserId is null)return Challenge();
|
||||
|
||||
@ -8,7 +8,7 @@ using PlotLine.Data;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
namespace PlotLine.Controllers;
|
||||
[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")]
|
||||
public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext<NativeCompanionPresenceHub>? live=null,INativePositionRepository? positions=null,NativeManuscriptCapture? capture=null,IHubContext<WordCompanionFollowHub>? wizard=null,ILogger<NativePresenceController>? logger=null,IChapterSyncRepository? chapterPositions=null):ControllerBase
|
||||
public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext<NativeCompanionPresenceHub>? live=null,INativePositionRepository? positions=null,NativeManuscriptCapture? capture=null,IHubContext<WordCompanionFollowHub>? wizard=null,ILogger<NativePresenceController>? logger=null,IChapterSyncRepository? chapterPositions=null,PlotLine.Services.SharedManuscriptFocus? sharedFocus=null,IBookRepository? focusBooks=null):ControllerBase
|
||||
{
|
||||
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
private string Grant=>User.FindFirstValue("NativeCompanion.Grant")??throw new InvalidOperationException();
|
||||
@ -45,6 +45,7 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC
|
||||
// ChapterIssue is the agent's current reading failure, not server chapter acceptance.
|
||||
// Do not overwrite accepted/checking progress with a sticky synthetic Needs review state.
|
||||
input.ChapterProgress=presence.ChapterProgress(Author,input.BookId,instance,session,input.Revision);
|
||||
if(sharedFocus!=null&&focusBooks!=null&&input.CanSharedFocus&&input.BookId>0){var scopedBook=await focusBooks.GetAsync(input.BookId);var lease=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session);if(scopedBook!=null&&lease!=null)try{input.SharedFocusStatus=await sharedFocus.NativeObservation(Author,scopedBook.ProjectID,lease,before==null||before.Position.FocusModeRequest!=input.FocusModeRequest||before.Position.FocusWindowID!=input.FocusWindowID||before.Position.WordSaved!=input.WordSaved||before.Position.ParagraphRevision!=input.ParagraphRevision||before.Position.NavigationAcknowledgedId!=input.NavigationAcknowledgedId);}catch(Exception e){input.SharedFocusStatus="word-unmapped";logger?.LogWarning("Shared focus observation unavailable ({Type}); manuscript synchronisation retained.",e.GetType().Name);}}
|
||||
input.CatalogVersion=presence.CatalogVersion(Author);input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);
|
||||
if(input.Navigation is {Kind:"navigate"} command)logger?.LogInformation("Deliver explicit Word navigation Id={NavigationId} User={User} Book={Book} Instance={Instance} Session={Session} Revision={Revision} Position={Position}",command.Id,Author,input.BookId,instance,session,command.Revision,command.Chapter?.Start);
|
||||
return Ok(input);
|
||||
|
||||
@ -37,7 +37,7 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB
|
||||
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);
|
||||
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,
|
||||
var result=leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{l.Position.CanSharedFocus,l.Position.FocusHeld,l.Position.SharedFocusStatus,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,
|
||||
|
||||
14
PlotLine/Controllers/SharedFocusController.cs
Normal file
14
PlotLine/Controllers/SharedFocusController.cs
Normal file
@ -0,0 +1,14 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Services;
|
||||
namespace PlotLine.Controllers;
|
||||
[Authorize,Route("NarrativeFocus/Shared"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
|
||||
public sealed class SharedFocusController(SharedManuscriptFocus focus,ICurrentUserService user):Controller
|
||||
{
|
||||
[HttpGet]public Task<IActionResult> Read(int projectID,int bookID)=>Run(new(){ProjectID=projectID,BookID=bookID},"read");
|
||||
[HttpPost("Publish"),ValidateAntiForgeryToken]public Task<IActionResult> Publish(SharedFocusRequest request)=>Run(request,"publish");
|
||||
[HttpPost("Resolve"),ValidateAntiForgeryToken]public Task<IActionResult> Resolve(SharedFocusRequest request)=>Run(request,"resolve");
|
||||
[HttpPost("Validate"),ValidateAntiForgeryToken]public Task<IActionResult> Validate(SharedFocusRequest request)=>Run(request,"validate");
|
||||
private async Task<IActionResult> Run(SharedFocusRequest request,string action){if(user.UserId is not int author)return Challenge();if(!ModelState.IsValid)return BadRequest(new{message="Choose valid manuscript identifiers."});try{return Ok(await focus.Run(author,request,action));}catch(SqlException e)when(e.Number==51000){return NotFound(new{message="This manuscript reference is unavailable. Choose another position."});}}
|
||||
}
|
||||
@ -31,11 +31,7 @@ public sealed class WriterController(
|
||||
var result=await LoadDestination("Review",projectId,bookId);
|
||||
if(result is ViewResult {Model:WriterDashboardViewModel model}&&model.BookID.HasValue&&reader!=null){
|
||||
try{
|
||||
if(chapterId.HasValue && narrativeFocus != null && model.ProjectID is int project && int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var author))
|
||||
{
|
||||
var current=model.NarrativeFocus!;
|
||||
if(current.ChapterID!=chapterId) {model.NarrativeFocus=await narrativeFocus.Set(author,project,model.BookID.Value,chapterId,null,current.Version);if(model.WorkingContext!=null)model.WorkingContext=model.WorkingContext.Select(PlotLine.Services.Writer.WriterFocusRole.Working,new(project,model.BookID.Value,model.NarrativeFocus.ChapterID,model.NarrativeFocus.SceneID));}
|
||||
}
|
||||
// Initial/deep-link chapter loading is local; deliberate navigation publishes through SharedFocus.
|
||||
chapterId ??= model.NarrativeFocus?.ChapterID;
|
||||
model.ReviewReader=await reader.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),model.BookID.Value,chapterId);if(model.ReviewReader==null)return NotFound();model.ReviewReader.FocusReading=focus;model.ReviewReader.IntegratedReview=true;model.ReviewReader.ReadingMode=reading;}
|
||||
catch(UnauthorizedAccessException){return NotFound();}
|
||||
@ -46,12 +42,12 @@ public sealed class WriterController(
|
||||
return result;
|
||||
}
|
||||
[HttpGet,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
|
||||
public async Task<IActionResult> ReviewContent(int projectId,int bookId,long version,bool focus=false,bool reading=false,[FromServices] PlotLine.Services.Manuscript.ManuscriptReaderService? reader=null)
|
||||
public async Task<IActionResult> ReviewContent(int projectId,int bookId,long version,bool focus=false,bool reading=false,int? chapterId=null,bool localFocus=false,[FromServices] PlotLine.Services.Manuscript.ManuscriptReaderService? reader=null)
|
||||
{
|
||||
var result=await Review(projectId,bookId,null,focus,reading,reader);
|
||||
var result=await Review(projectId,bookId,chapterId,focus,reading,reader);
|
||||
if(result is ViewResult {Model:WriterDashboardViewModel model})
|
||||
{
|
||||
if(model.NarrativeFocus?.Version!=version)return Conflict(new{message="Current focus changed. Retry the current location."});
|
||||
if(!localFocus&&model.NarrativeFocus?.Version!=version)return Conflict(new{message="Current focus changed. Retry the current location."});
|
||||
return PartialView("_WriterReview",model);
|
||||
}
|
||||
return result;
|
||||
|
||||
@ -221,6 +221,7 @@ public class Program
|
||||
builder.Services.AddScoped<PlotLine.Services.Writer.IWriterAuthoringService, PlotLine.Services.Writer.WriterAuthoringService>();
|
||||
builder.Services.AddScoped<WriterObjectiveRepository>();
|
||||
builder.Services.AddScoped<INarrativeFocus, NarrativeFocus>();
|
||||
builder.Services.AddScoped<SharedManuscriptFocus>();
|
||||
builder.Services.AddScoped<WriterWorkRepository>();
|
||||
builder.Services.AddScoped<WriterPlanningRepository>();
|
||||
builder.Services.AddScoped<WriterActivityRepository>();
|
||||
|
||||
@ -58,10 +58,10 @@ public sealed class CharacterWorkspace(ICharacterRepository characters,IProjectR
|
||||
var frame=await Operation(input.CharacterID,input.RelationshipID,input.EventID,input.Action,ct);if(input.Version!=frame.Version)throw new InvalidOperationException("This relationship or its history changed. Cancel and reopen to review current values.");if(input.Action is "archive" or "event-remove"&&!input.Confirmed)throw new ArgumentException("Confirm the identified removal.");if(input.Notes?.Length>4000||input.Intensity is <1 or >10)throw new ArgumentException("Use valid notes and intensity.");
|
||||
if(input.Action.StartsWith("event-")&&frame.Event?.ProtectedSource==true)throw new ArgumentException("This event has source/review dependencies. Manage it through its source workflow.");
|
||||
try{await reader.Change(input,user.UserId!.Value,ct);}catch(SqlException ex)when(ex.Number==51020){throw new UnauthorizedAccessException();}catch(SqlException ex)when(ex.Number==51021){throw new InvalidOperationException(ex.Message);}catch(SqlException ex)when(ex.Number==51022){throw new ArgumentException(ex.Message);}
|
||||
var scope=await Scope(input.CharacterID);await activity.RecordAsync(scope.Project.ProjectID,input.Action=="archive"?"Archived":input.Action=="event-remove"?"Deleted":"Updated","Relationship",input.RelationshipID,"Character workspace relationship operation");await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID);
|
||||
var scope=await Scope(input.CharacterID);await activity.RecordAsync(scope.Project.ProjectID,input.Action=="archive"?"Archived":input.Action=="event-remove"?"Deleted":"Updated","Relationship",input.RelationshipID,"Character workspace relationship operation");await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID,kind:"relationships");
|
||||
}
|
||||
public async Task<CharacterDetailViewModel> AddForm(int id,CancellationToken ct,InitialRelationshipEditViewModel? input=null)
|
||||
{var model=await Header(id,null,ct);if(!model.WorkspaceCanEdit)throw new UnauthorizedAccessException();var lookup=await characters.GetLookupsAsync(model.Project.ProjectID);model.RelationshipTypeOptions=lookup.RelationshipTypes.Select(t=>new SelectListItem(t.RelationshipCategoryName+" · "+t.TypeName,t.RelationshipTypeID.ToString())).ToArray();model.RelationshipStateOptions=lookup.RelationshipStates.Select(t=>new SelectListItem(t.StateName,t.RelationshipStateID.ToString())).ToArray();model.BookOptions=(await books.ListByProjectAsync(model.Project.ProjectID)).Select(b=>new SelectListItem(b.BookDisplayTitle,b.BookID.ToString())).ToArray();if(input!=null){model.NewInitialRelationship=input;var target=await characters.GetReferenceCharacterAsync(input.RelatedCharacterID,user.UserId!.Value);if(target?.ProjectID==model.Project.ProjectID)model.CharacterOptions=[new(target.CharacterName,target.CharacterID.ToString())];}return model;}
|
||||
public async Task Add(int id,InitialRelationshipEditViewModel input,CancellationToken ct)
|
||||
{var scope=await Scope(id);if(!scope.CanEdit||input.CharacterID!=id||input.CharacterRelationshipID!=0)throw new UnauthorizedAccessException();if((await characters.GetReferenceCharacterAsync(input.RelatedCharacterID,user.UserId!.Value))?.ProjectID!=scope.Project.ProjectID||input.RelatedCharacterID==id)throw new ArgumentException("Choose another character in this project.");if(input.Notes?.Length>4000||input.InitialIntensity is <1 or >10)throw new ArgumentException("Use valid notes and intensity.");var lookups=await characters.GetLookupsAsync(scope.Project.ProjectID);if(!lookups.RelationshipTypes.Any(t=>t.RelationshipTypeID==input.RelationshipTypeID)||(input.InitialRelationshipStateID.HasValue&&!lookups.RelationshipStates.Any(t=>t.RelationshipStateID==input.InitialRelationshipStateID)))throw new ArgumentException("Choose a recorded relationship type and state.");if(input.InitialBookID.HasValue&&!(await books.ListByProjectAsync(scope.Project.ProjectID)).Any(b=>b.BookID==input.InitialBookID))throw new UnauthorizedAccessException();input.ProjectID=scope.Project.ProjectID;input.ReturnCharacterID=id;await canonical.SaveInitialRelationshipAsync(input);await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID);}
|
||||
{var scope=await Scope(id);if(!scope.CanEdit||input.CharacterID!=id||input.CharacterRelationshipID!=0)throw new UnauthorizedAccessException();if((await characters.GetReferenceCharacterAsync(input.RelatedCharacterID,user.UserId!.Value))?.ProjectID!=scope.Project.ProjectID||input.RelatedCharacterID==id)throw new ArgumentException("Choose another character in this project.");if(input.Notes?.Length>4000||input.InitialIntensity is <1 or >10)throw new ArgumentException("Use valid notes and intensity.");var lookups=await characters.GetLookupsAsync(scope.Project.ProjectID);if(!lookups.RelationshipTypes.Any(t=>t.RelationshipTypeID==input.RelationshipTypeID)||(input.InitialRelationshipStateID.HasValue&&!lookups.RelationshipStates.Any(t=>t.RelationshipStateID==input.InitialRelationshipStateID)))throw new ArgumentException("Choose a recorded relationship type and state.");if(input.InitialBookID.HasValue&&!(await books.ListByProjectAsync(scope.Project.ProjectID)).Any(b=>b.BookID==input.InitialBookID))throw new UnauthorizedAccessException();input.ProjectID=scope.Project.ProjectID;input.ReturnCharacterID=id;await canonical.SaveInitialRelationshipAsync(input);await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID,kind:"relationships");}
|
||||
}
|
||||
|
||||
@ -62,7 +62,7 @@ public sealed class ContextRelationshipEditing(ICharacterRepository repository,I
|
||||
var edit=new RelationshipEventCreateViewModel{RelationshipEventID=frame.Event?.RelationshipEventID??0,CharacterRelationshipID=r?.CharacterRelationshipID,SceneID=input.SceneID,CharacterAID=input.SourceID,CharacterBID=input.TargetID,RelationshipTypeID=input.TypeID,RelationshipStateID=input.StateID,Intensity=input.Intensity,IsReciprocal=input.Mutual,IsKnownToOtherCharacter=input.Known,Description=input.Notes,ReturnProjectID=frame.ProjectID,ReturnBookID=input.BookID};
|
||||
if(frame.Event==null)await characters.AddRelationshipEventAsync(edit);else await characters.UpdateRelationshipEventAsync(edit);
|
||||
}
|
||||
await notifications.Invalidate(user.UserId!.Value,projectId:frame.ProjectID);
|
||||
await notifications.Invalidate(user.UserId!.Value,projectId:frame.ProjectID,kind:"relationships");
|
||||
}finally{mutex.Release();}
|
||||
}
|
||||
}
|
||||
|
||||
@ -10,10 +10,10 @@ public sealed class ContextReferenceInvalidationFilter(ContextWorkspaceNotificat
|
||||
var result = await next();
|
||||
var controller = context.RouteData.Values["controller"]?.ToString();
|
||||
if (controller == "Writer" && context.RouteData.Values["action"]?.ToString() != "SaveChapterGoal") return;
|
||||
if (!HttpMethods.IsPost(context.HttpContext.Request.Method) || controller is not ("Scenes" or "Writer") ||
|
||||
if (!HttpMethods.IsPost(context.HttpContext.Request.Method) || controller is not ("Scenes" or "Writer" or "Characters" or "CharacterWorkspace" or "RelationshipMap" or "Chapters" or "PlotLines" or "PlotLineWorkspace" or "Timeline" or "Locations" or "WriterAuthoring" or "WriterReview" or "IntelligenceReview" or "ParagraphManuscript") ||
|
||||
currentUser.UserId is not int user || result.Exception != null || !context.ModelState.IsValid) return;
|
||||
if (result.Result is ForbidResult or ChallengeResult) return;
|
||||
var status = result.Result switch { ObjectResult value => value.StatusCode ?? 200, StatusCodeResult value => value.StatusCode, _ => 200 };
|
||||
if (status < 400) await notifications.Invalidate(user);
|
||||
if(status<400&&!notifications.AlreadyInvalidated){var kind=controller switch{"RelationshipMap"=>"relationships","Characters"=>context.RouteData.Values["action"]?.ToString()?.Contains("Relationship")==true?"relationships":"characters","Chapters" or "Scenes"=>"structure",_=>null};await notifications.Invalidate(user,kind:kind);}
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,11 +3,13 @@ using PlotLine.Hubs;
|
||||
namespace PlotLine.Services;
|
||||
|
||||
// Presentation hints only. A notification failure must never turn a durable save into a failed write.
|
||||
public sealed class ContextWorkspaceNotifications(IHubContext<NativeCompanionPresenceHub> hub, ILogger<ContextWorkspaceNotifications> logger)
|
||||
public sealed class ContextWorkspaceNotifications(IHubContext<NativeCompanionPresenceHub> hub, ILogger<ContextWorkspaceNotifications> logger,IHttpContextAccessor? accessor=null)
|
||||
{
|
||||
private const string Marker="PlotDirector.ContextInvalidated";
|
||||
public bool AlreadyInvalidated=>accessor?.HttpContext?.Items.ContainsKey(Marker)==true;
|
||||
public Task Position(int user) => Send(user, "ContextPositionChanged", new { });
|
||||
public Task Invalidate(int user, int? bookId = null, int? chapterId = null, int? sceneId = null, int? projectId = null)
|
||||
=> Send(user, "ContextInvalidated", new { bookId, chapterId, sceneId, projectId });
|
||||
public Task Invalidate(int user,int? bookId=null,int? chapterId=null,int? sceneId=null,int? projectId=null,string? kind=null)
|
||||
{if(AlreadyInvalidated)return Task.CompletedTask;if(accessor?.HttpContext is {} context)context.Items[Marker]=true;return Send(user,"ContextInvalidated",new{bookId,chapterId,sceneId,projectId,kind});}
|
||||
private async Task Send(int user, string name, object hint)
|
||||
{
|
||||
try { await hub.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync(name, hint); }
|
||||
|
||||
@ -21,6 +21,7 @@ public sealed record NarrativeFocusState
|
||||
public int BookID { get; init; }
|
||||
public int? ChapterID { get; init; }
|
||||
public int? SceneID { get; init; }
|
||||
public Guid? ParagraphID{get;init;}public Guid? ManuscriptID{get;init;}public Guid? OriginWindowID{get;init;}
|
||||
public long Version { get; init; }
|
||||
public IReadOnlyList<NarrativePosition> Positions { get; init; } = [];
|
||||
public IReadOnlyList<NarrativeRecent> Recent { get; init; } = [];
|
||||
|
||||
@ -2,12 +2,10 @@ using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using Microsoft.Data.SqlClient;
|
||||
namespace PlotLine.Services;
|
||||
|
||||
// Only successfully opened narrative destinations commit focus. Inspection, filters,
|
||||
// partial rendering, Word observation and visualisation requests are deliberately absent.
|
||||
public sealed class NarrativeNavigationFilter(INarrativeFocus focus,ICurrentUserService currentUser) : IAsyncActionFilter
|
||||
// Preserve editor redirects without turning a page load into a focus publication.
|
||||
public sealed class NarrativeNavigationFilter(ICurrentUserService currentUser) : IAsyncActionFilter
|
||||
{
|
||||
public async Task OnActionExecutionAsync(ActionExecutingContext context,ActionExecutionDelegate next)
|
||||
{
|
||||
@ -23,21 +21,9 @@ public sealed class NarrativeNavigationFilter(INarrativeFocus focus,ICurrentUser
|
||||
{var parts=uri.AbsolutePath.Split('/',StringSplitOptions.RemoveEmptyEntries);if(parts.Length>=2&&IsEditorDestination(parts[0],parts[1])&&!QueryHelpers.ParseQuery(uri.Query).ContainsKey("retainNarrativeFocus"))local.Url=QueryHelpers.AddQueryString(local.Url,"retainNarrativeFocus","true");}
|
||||
return;
|
||||
}
|
||||
if(result.Result is not ViewResult||request.Query["retainNarrativeFocus"].Any(v=>string.Equals(v,"true",StringComparison.OrdinalIgnoreCase))||
|
||||
!HttpMethods.IsGet(request.Method)||request.Headers["X-Requested-With"]=="XMLHttpRequest"||
|
||||
(request.Headers["Sec-Fetch-Mode"].Count>0&&request.Headers["Sec-Fetch-Mode"]!="navigate")||request.Headers["Sec-Purpose"].ToString().Contains("prefetch",StringComparison.OrdinalIgnoreCase))return;
|
||||
var controller=context.RouteData.Values["controller"]?.ToString();
|
||||
var action=context.RouteData.Values["action"]?.ToString();
|
||||
int? chapter=null,scene=null;
|
||||
int? ID(string name)=>context.ActionArguments.TryGetValue(name,out var value)&&int.TryParse(value?.ToString(),out var id)&&id>0?id:null;
|
||||
if(controller=="Scenes"&&action=="Edit")scene=ID("id");
|
||||
else if((controller=="Chapters"&&action is ("Details" or "Edit"))||(controller=="Writer"&&action=="Chapter"))chapter=ID("id");
|
||||
else if(controller=="Timeline"&&action=="Index"&&request.Query["navigateFocus"]=="true"&&int.TryParse(request.Query["SelectedSceneID"],out var selected))scene=selected;
|
||||
if(chapter is null&&scene is null)return;
|
||||
var scope=controller=="Timeline"&&context.ActionArguments.TryGetValue("filter",out var value)?value as PlotLine.ViewModels.TimelineFilterViewModel:null;
|
||||
try{var selectedFocus=await focus.Open(user,chapter,scene,scope?.ProjectID,scope?.BookID);if(selectedFocus is null)result.Result=new NotFoundResult();else context.HttpContext.Items["NarrativeFocus.Navigation"]=selectedFocus;}
|
||||
catch(SqlException e)when(e.Number==51000){result.Result=new NotFoundResult();}
|
||||
catch(NarrativeFocusConflictException){result.Result=new ConflictObjectResult(new{message="Current focus changed in another window. Reopen this destination to navigate explicitly."});}
|
||||
// GETs include refreshes, restored tabs and incoming navigation. They must never
|
||||
// publish saved positions. Deliberate link navigation uses the shared coordinator.
|
||||
|
||||
}
|
||||
private static bool IsEditorDestination(string? controller,string? action) =>
|
||||
(controller?.ToLowerInvariant(),action?.ToLowerInvariant()) is ("scenes","edit") or ("chapters","edit" or "details") or ("writer","chapter");
|
||||
|
||||
@ -26,13 +26,13 @@ public sealed class NativePresenceStore(TimeProvider clock,NativeCommandWakeQueu
|
||||
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;
|
||||
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());
|
||||
leases[key]=new(user,grant,expires,instance,session,new NativePresence{CanSharedFocus=value.CanSharedFocus,FocusHeld=value.FocusHeld,AnyFollowingWindows=value.AnyFollowingWindows,FocusWindowID=value.FocusWindowID,FocusModeRequest=value.FocusModeRequest,DeliberateFocusSequence=value.DeliberateFocusSequence,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,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}};queuedAt[key]=(id,System.Diagnostics.Stopwatch.GetTimestamp());Wake(user,lease,navigation[key]);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,bool backgroundFocus=false,long focusVersion=0,Guid focusOriginWindowID=default)
|
||||
{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(){BackgroundFocus=backgroundFocus,FocusVersion=focusVersion,FocusOriginWindowID=focusOriginWindowID,Id=id,BookId=book,ManuscriptId=manuscript,ExpiresUtc=clock.GetUtcNow().AddSeconds(25).UtcDateTime,Kind="navigate",SessionId=session,Revision=revision,Chapter=new(){Start=start}};queuedAt[key]=(id,System.Diagnostics.Stopwatch.GetTimestamp());Wake(user,lease,navigation[key]);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)&¤t.Grant==selected.Grant&¤t.Position.Revision==selected.Position.Revision){navigation[key]=new(){Kind="cancel",SessionId=selected.Session,Revision=selected.Position.Revision};queuedAt.Remove(key);Wake(user,current,navigation[key]);}}}
|
||||
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=[];
|
||||
|
||||
52
PlotLine/Services/SharedManuscriptFocus.cs
Normal file
52
PlotLine/Services/SharedManuscriptFocus.cs
Normal file
@ -0,0 +1,52 @@
|
||||
using System.Data;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Dapper;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Hubs;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
namespace PlotLine.Services;
|
||||
public sealed record SharedFocusPosition
|
||||
{
|
||||
public int ProjectID{get;init;}public int BookID{get;init;}public int? ChapterID{get;init;}public int? SceneID{get;init;}public Guid? ParagraphID{get;init;}public Guid? ManuscriptID{get;init;}public Guid? OriginWindowID{get;init;}public long Version{get;init;}public bool IsValid{get;init;}public bool Changed{get;init;}
|
||||
}
|
||||
public sealed class SharedFocusRequest
|
||||
{
|
||||
public int ProjectID{get;set;}public int BookID{get;set;}public int? ChapterID{get;set;}public int? SceneID{get;set;}public Guid? ParagraphID{get;set;}public Guid? ManuscriptID{get;set;}public Guid WindowID{get;set;}public long Sequence{get;set;}public int Direction{get;set;}
|
||||
}
|
||||
public sealed class FocusWordPosition {public Guid ParagraphID{get;set;}public int ChapterID{get;set;}public int? SceneID{get;set;}public int StartPosition{get;set;}}
|
||||
// Extends the existing persisted NarrativeFocus, never manuscript content authority.
|
||||
public sealed class SharedManuscriptFocus(ISqlConnectionFactory factory,IHubContext<NativeCompanionPresenceHub> hub,NativePresenceStore native,ILogger<SharedManuscriptFocus> logger)
|
||||
{
|
||||
public async Task Announce(int user,int project,int book)
|
||||
{
|
||||
var state=await Run(user,new(){ProjectID=project,BookID=book},"read");
|
||||
try{await hub.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync("ManuscriptFocusChanged",state);}catch(Exception e){logger.LogWarning("Focus notification unavailable: {Type}",e.GetType().Name);}
|
||||
foreach(var lease in native.Read(user,book).Where(l=>l.Position.CanSharedFocus))try{await FollowWord(user,state,lease);}catch(Exception e){logger.LogWarning("Word focus delivery unavailable: {Type}",e.GetType().Name);}
|
||||
}
|
||||
|
||||
public async Task<SharedFocusPosition> Run(int user,SharedFocusRequest request,string action)
|
||||
{
|
||||
using var db=factory.CreateConnection();var result=await db.QuerySingleAsync<SharedFocusPosition>("dbo.NarrativeFocus_Coordinate",new{Action=action,UserID=user,request.ProjectID,request.BookID,request.WindowID,request.Sequence,request.ChapterID,request.SceneID,request.ParagraphID,request.ManuscriptID,request.Direction},commandType:CommandType.StoredProcedure);
|
||||
if(result.Changed){try{await hub.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync("ManuscriptFocusChanged",result);}catch(Exception e){logger.LogWarning("Focus notification unavailable: {Type}",e.GetType().Name);}foreach(var lease in native.Read(user,result.BookID).Where(l=>l.Position.CanSharedFocus))try{await FollowWord(user,result,lease);}catch(Exception e){logger.LogWarning("Word focus delivery unavailable: {Type}",e.GetType().Name);}}
|
||||
return result;
|
||||
}
|
||||
public async Task<FocusWordPosition?> WordPosition(int user,NativeLease lease,string action,SharedFocusPosition? focus=null)
|
||||
{using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<FocusWordPosition>("dbo.NarrativeFocus_WordPosition",new{Action=action,UserID=user,BookID=lease.Position.BookId,ManuscriptID=lease.Position.ManuscriptId,SessionID=lease.Session,WordRevision=lease.Position.Revision,Cursor=lease.Position.CursorStart,focus?.ChapterID,focus?.SceneID,focus?.ParagraphID},commandType:CommandType.StoredProcedure);}
|
||||
public async Task<string> NativeObservation(int user,int project,NativeLease lease,bool recover)
|
||||
{
|
||||
var p=lease.Position;if(!p.CanSharedFocus)return "unsupported";
|
||||
if(p.DeliberateFocusSequence>0&&!p.FocusHeld&&p.WordSaved==true&&p.FocusWindowID!=Guid.Empty){var point=await WordPosition(user,lease,"position");if(point==null)return "word-unmapped";await Run(user,new(){ProjectID=project,BookID=p.BookId,ChapterID=point.ChapterID,SceneID=point.SceneID,ParagraphID=point.ParagraphID,ManuscriptID=p.ManuscriptId,WindowID=p.FocusWindowID,Sequence=p.DeliberateFocusSequence},"publish");}
|
||||
if(recover){var latest=await Run(user,new(){ProjectID=project,BookID=p.BookId},"read");if(latest.IsValid)return await FollowWord(user,latest,lease);}
|
||||
return p.FocusHeld?"held":p.WordSaved!=true?"save-required":p.DeliberateFocusSequence>0?"following":"";
|
||||
}
|
||||
private async Task<string> FollowWord(int user,SharedFocusPosition focus,NativeLease lease)
|
||||
{
|
||||
var p=lease.Position;if(!p.CanSharedFocus)return "unsupported";if(!p.AnyFollowingWindows)return "held";if(p.WordSaved!=true)return "save-required";if(focus.ManuscriptID!=p.ManuscriptId)return "word-unmapped";
|
||||
var target=await WordPosition(user,lease,"target",focus);if(target==null){await hub.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync("ManuscriptFocusDelivery",new{focus.BookID,focus.Version,state="word-unmapped"});return "word-unmapped";}
|
||||
var bytes=SHA256.HashData(Encoding.UTF8.GetBytes($"{user}/{focus.BookID}/{lease.Instance}/{lease.Session}/{p.FocusWindowID}/{p.FocusModeRequest}/{focus.Version}"));var command=new Guid(bytes.AsSpan(0,16));
|
||||
var known=native.NavigationState(user,focus.BookID,lease.Instance,lease.Session,command,p.ManuscriptId,p.Revision);if(known is "failed" or "timed-out" or "invalidated")return "word-busy";
|
||||
var sent=native.Navigate(user,focus.BookID,lease.Instance,lease.Session,p.ManuscriptId,p.Revision,target.StartPosition,true,command,true,backgroundFocus:true,focusVersion:focus.Version,focusOriginWindowID:focus.OriginWindowID??Guid.Empty);return sent?"following":"word-busy";
|
||||
}
|
||||
}
|
||||
@ -11,7 +11,7 @@ public sealed class SubscriptionEnforcementFilter(
|
||||
private static readonly HashSet<string> ReadOnlySafeControllers = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"Account", "ManageAccount", "Pricing", "Exports", "Admin", "StripeWebhook",
|
||||
"NarrativeFocus" // Personal navigation context, never story-content editing.
|
||||
"NarrativeFocus", "SharedFocus" // Personal navigation context, never story-content editing.
|
||||
};
|
||||
|
||||
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||
|
||||
68
PlotLine/Sql/314_UnifiedManuscriptFocus.sql
Normal file
68
PlotLine/Sql/314_UnifiedManuscriptFocus.sql
Normal file
@ -0,0 +1,68 @@
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
IF COL_LENGTH('dbo.NarrativeFocus','ParagraphID') IS NULL ALTER TABLE dbo.NarrativeFocus ADD ParagraphID uniqueidentifier NULL,ManuscriptID uniqueidentifier NULL,OriginWindowID uniqueidentifier NULL;
|
||||
IF OBJECT_ID('dbo.NarrativeFocusClients','U') IS NULL CREATE TABLE dbo.NarrativeFocusClients(UserID int NOT NULL,BookID int NOT NULL,WindowID uniqueidentifier NOT NULL,LastSequence bigint NOT NULL,PRIMARY KEY(UserID,BookID,WindowID),FOREIGN KEY(UserID,BookID) REFERENCES dbo.NarrativeFocus(UserID,BookID) ON DELETE CASCADE);
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.NarrativeFocus_Coordinate @Action varchar(12),@UserID int,@ProjectID int,@BookID int,@WindowID uniqueidentifier=NULL,@Sequence bigint=0,@ChapterID int=NULL,@SceneID int=NULL,@ParagraphID uniqueidentifier=NULL,@ManuscriptID uniqueidentifier=NULL,@Direction int=0
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
IF @Action NOT IN('read','publish','resolve','validate') OR @Direction NOT IN(-1,0,1) THROW 51000,'Invalid focus operation.',1;
|
||||
BEGIN TRY
|
||||
BEGIN TRANSACTION;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Books b WITH(HOLDLOCK) JOIN dbo.Projects p WITH(HOLDLOCK) ON p.ProjectID=b.ProjectID JOIN dbo.ProjectUserAccess a WITH(HOLDLOCK) ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0 AND p.IsArchived=0) THROW 51000,'Focus unavailable in this book.',1;
|
||||
DECLARE @version bigint,@oldChapter int,@oldScene int,@oldParagraph uniqueidentifier,@oldManuscript uniqueidentifier,@canonical uniqueidentifier,@payload nvarchar(max),@last bigint,@changed bit=0;
|
||||
SELECT @canonical=ManuscriptID,@payload=Payload FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;
|
||||
IF @ManuscriptID IS NOT NULL AND (@canonical IS NULL OR @ManuscriptID<>@canonical) THROW 51000,'Manuscript identity changed.',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID) INSERT dbo.NarrativeFocus(UserID,BookID,Version) VALUES(@UserID,@BookID,0);
|
||||
SELECT @version=Version,@oldChapter=ChapterID,@oldScene=SceneID,@oldParagraph=ParagraphID,@oldManuscript=ManuscriptID FROM dbo.NarrativeFocus WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID;
|
||||
IF @Action='publish'
|
||||
BEGIN
|
||||
IF @WindowID IS NULL OR @WindowID='00000000-0000-0000-0000-000000000000' OR @Sequence<1 OR @Sequence>9007199254740991 THROW 51000,'Invalid focus origin.',1;
|
||||
SELECT @last=LastSequence FROM dbo.NarrativeFocusClients WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID AND WindowID=@WindowID;
|
||||
IF @Sequence<=COALESCE(@last,0) SET @Action='read';
|
||||
ELSE IF @last IS NULL INSERT dbo.NarrativeFocusClients VALUES(@UserID,@BookID,@WindowID,@Sequence);
|
||||
ELSE UPDATE dbo.NarrativeFocusClients SET LastSequence=@Sequence WHERE UserID=@UserID AND BookID=@BookID AND WindowID=@WindowID;
|
||||
END;
|
||||
IF @Action IN('read','validate') AND @Action<>'validate' BEGIN SET @ChapterID=@oldChapter;SET @SceneID=@oldScene;SET @ParagraphID=@oldParagraph;END;
|
||||
IF @Direction<>0 AND @Action IN('publish','resolve')
|
||||
BEGIN
|
||||
IF @Action='publish' BEGIN SET @SceneID=@oldScene;SET @ChapterID=@oldChapter;END;
|
||||
DECLARE @at bigint=(SELECT Ordinal FROM dbo.CharacterWorkspace_SceneOrder(@ProjectID) WHERE BookID=@BookID AND SceneID=@SceneID);
|
||||
SELECT TOP(1) @SceneID=SceneID,@ChapterID=ChapterID FROM dbo.CharacterWorkspace_SceneOrder(@ProjectID) WHERE BookID=@BookID AND (@at IS NULL OR (@Direction=1 AND Ordinal>@at) OR (@Direction=-1 AND Ordinal<@at)) ORDER BY CASE WHEN @Direction=1 THEN Ordinal ELSE -Ordinal END;
|
||||
SET @ParagraphID=NULL;
|
||||
END;
|
||||
DECLARE @valid bit=1;
|
||||
IF @ParagraphID IS NOT NULL
|
||||
BEGIN
|
||||
DECLARE @paraChapter int,@sceneKey uniqueidentifier;
|
||||
SELECT @paraChapter=ChapterID,@sceneKey=CASE WHEN PositionVerified=1 THEN SceneKey END FROM OPENJSON(@payload,'$.Paragraphs') WITH(ID uniqueidentifier '$.Occurrence.Id',ChapterID int '$.ChapterId',SceneKey uniqueidentifier '$.SceneId',PositionVerified bit) WHERE ID=@ParagraphID;
|
||||
IF @paraChapter IS NULL OR (@ChapterID IS NOT NULL AND @ChapterID<>@paraChapter) SET @valid=0;
|
||||
SET @ChapterID=@paraChapter;
|
||||
DECLARE @paraScene int=(SELECT CanonicalID FROM OPENJSON(@payload,'$.Scenes') WITH(ID uniqueidentifier '$.Id',CanonicalID int '$.CanonicalId',Retired bit) WHERE ID=@sceneKey AND Retired=0);
|
||||
IF @SceneID IS NOT NULL AND (@paraScene IS NULL OR @SceneID<>@paraScene) SET @valid=0;
|
||||
SET @SceneID=@paraScene;
|
||||
END;
|
||||
IF @SceneID IS NOT NULL
|
||||
BEGIN
|
||||
DECLARE @parent int=(SELECT s.ChapterID FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE s.SceneID=@SceneID AND c.BookID=@BookID AND s.IsArchived=0 AND c.IsArchived=0);
|
||||
IF @parent IS NULL OR (@ChapterID IS NOT NULL AND @ChapterID<>@parent) SET @valid=0;ELSE SET @ChapterID=@parent;
|
||||
END;
|
||||
IF @ChapterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChapterID AND BookID=@BookID AND IsArchived=0) SET @valid=0;
|
||||
IF @ChapterID IS NULL SET @valid=0;
|
||||
IF @Action IN('publish','resolve') AND @valid=0 THROW 51000,'This manuscript reference is no longer valid. Select another chapter or scene.',1;
|
||||
IF @Action='read' AND @oldManuscript IS NOT NULL AND (@canonical IS NULL OR @oldManuscript<>@canonical) SET @valid=0;
|
||||
IF @Action='publish' AND (ISNULL(@oldChapter,0)<>ISNULL(@ChapterID,0) OR ISNULL(@oldScene,0)<>ISNULL(@SceneID,0) OR ISNULL(CONVERT(varchar(36),@oldParagraph),'')<>ISNULL(CONVERT(varchar(36),@ParagraphID),'') OR ISNULL(CONVERT(varchar(36),@oldManuscript),'')<>ISNULL(CONVERT(varchar(36),@canonical),''))
|
||||
BEGIN
|
||||
SET @changed=1;SET @version=@version+1;
|
||||
UPDATE dbo.NarrativeFocus SET ChapterID=@ChapterID,SceneID=@SceneID,ParagraphID=@ParagraphID,ManuscriptID=@canonical,OriginWindowID=@WindowID,Version=@version WHERE UserID=@UserID AND BookID=@BookID;
|
||||
DELETE dbo.NarrativeFocusHistory WHERE UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID AND ISNULL(SceneID,0)=ISNULL(@SceneID,0);
|
||||
INSERT dbo.NarrativeFocusHistory VALUES(@UserID,@BookID,@version,@ChapterID,@SceneID);
|
||||
DELETE h FROM dbo.NarrativeFocusHistory h WHERE h.UserID=@UserID AND h.BookID=@BookID AND h.Sequence NOT IN(SELECT TOP(20) Sequence FROM dbo.NarrativeFocusHistory WHERE UserID=@UserID AND BookID=@BookID ORDER BY Sequence DESC);
|
||||
END;
|
||||
SELECT @ProjectID ProjectID,@BookID BookID,@ChapterID ChapterID,@SceneID SceneID,@ParagraphID ParagraphID,@canonical ManuscriptID,@version Version,@valid IsValid,@changed Changed,CASE WHEN @changed=1 THEN @WindowID ELSE (SELECT OriginWindowID FROM dbo.NarrativeFocus WHERE UserID=@UserID AND BookID=@BookID) END OriginWindowID;
|
||||
COMMIT;
|
||||
END TRY BEGIN CATCH IF XACT_STATE()<>0 ROLLBACK;THROW;END CATCH;
|
||||
END;
|
||||
GO
|
||||
87
PlotLine/Sql/315_SharedFocusCanonicalRead.sql
Normal file
87
PlotLine/Sql/315_SharedFocusCanonicalRead.sql
Normal file
@ -0,0 +1,87 @@
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.NarrativeFocus_Read
|
||||
@UserID int,@ProjectID int,@BookID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID
|
||||
JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1
|
||||
WHERE b.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0 AND p.IsArchived=0)
|
||||
THROW 51000,'Narrative focus is unavailable in this book.',1;
|
||||
BEGIN TRANSACTION;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID)
|
||||
BEGIN
|
||||
INSERT dbo.NarrativeFocus(UserID,BookID,Version) VALUES(@UserID,@BookID,0);
|
||||
END;
|
||||
-- Reads retain stale references. Coordinate reports invalidity without silently redirecting.
|
||||
DELETE h FROM dbo.NarrativeFocusHistory h
|
||||
WHERE h.UserID=@UserID AND h.BookID=@BookID AND
|
||||
(NOT EXISTS(SELECT 1 FROM dbo.Chapters c WHERE c.ChapterID=h.ChapterID AND c.BookID=@BookID AND c.IsArchived=0)
|
||||
OR(h.SceneID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Scenes s WHERE s.SceneID=h.SceneID AND s.ChapterID=h.ChapterID AND s.IsArchived=0)));
|
||||
COMMIT;
|
||||
SELECT @ProjectID ProjectID,BookID,ChapterID,SceneID,ParagraphID,ManuscriptID,OriginWindowID,Version FROM dbo.NarrativeFocus WHERE UserID=@UserID AND BookID=@BookID;
|
||||
SELECT c.ChapterID,c.ChapterTitle,c.ChapterNumber,n.SceneID,n.SceneTitle,n.SceneNumber,n.BookSceneIndex
|
||||
FROM dbo.Chapters c LEFT JOIN dbo.NarrativeSceneOrder n ON n.ChapterID=c.ChapterID
|
||||
WHERE c.BookID=@BookID AND c.IsArchived=0
|
||||
ORDER BY c.SortOrder,c.ChapterNumber,CASE WHEN n.SceneID IS NULL THEN 1 ELSE 0 END,n.BookSceneIndex,c.ChapterID;
|
||||
SELECT TOP(20) h.ChapterID,h.SceneID,h.Sequence FROM dbo.NarrativeFocusHistory h
|
||||
WHERE h.UserID=@UserID AND h.BookID=@BookID ORDER BY h.Sequence DESC;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.NarrativeFocus_Set
|
||||
@UserID int,@ProjectID int,@BookID int,@ChapterID int=NULL,@SceneID int=NULL,@ExpectedVersion bigint,@Direction int=0
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID
|
||||
JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1
|
||||
WHERE b.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0 AND p.IsArchived=0)
|
||||
THROW 51000,'Narrative focus is unavailable in this book.',1;
|
||||
IF @Direction NOT IN(-1,0,1) THROW 51000,'Invalid narrative direction.',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @version bigint,@oldChapter int,@oldScene int;
|
||||
SELECT @version=Version,@oldChapter=ChapterID,@oldScene=SceneID FROM dbo.NarrativeFocus WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID;
|
||||
IF @version IS NULL OR @version<>@ExpectedVersion THROW 51001,'Current focus changed in another window. Review it and try again.',1;
|
||||
IF @Direction<>0
|
||||
BEGIN
|
||||
DECLARE @index bigint=(SELECT BookSceneIndex FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID AND SceneID=@oldScene AND ChapterID=@oldChapter);
|
||||
SET @ChapterID=NULL;SET @SceneID=NULL;
|
||||
IF @index IS NOT NULL
|
||||
SELECT @ChapterID=ChapterID,@SceneID=SceneID FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID AND BookSceneIndex=@index+@Direction;
|
||||
ELSE IF @Direction=1
|
||||
SELECT TOP(1) @ChapterID=n.ChapterID,@SceneID=n.SceneID FROM dbo.NarrativeSceneOrder n
|
||||
LEFT JOIN dbo.Chapters currentChapter ON currentChapter.ChapterID=@oldChapter AND currentChapter.BookID=@BookID AND currentChapter.IsArchived=0
|
||||
WHERE n.BookID=@BookID AND(currentChapter.ChapterID IS NULL OR n.ChapterID=currentChapter.ChapterID OR
|
||||
(NOT EXISTS(SELECT 1 FROM dbo.NarrativeSceneOrder present WHERE present.BookID=@BookID AND present.ChapterID=currentChapter.ChapterID)
|
||||
AND(n.ChapterSortOrder>currentChapter.SortOrder OR(n.ChapterSortOrder=currentChapter.SortOrder AND n.ChapterNumber>currentChapter.ChapterNumber))))
|
||||
ORDER BY n.BookSceneIndex;
|
||||
ELSE
|
||||
SELECT TOP(1) @ChapterID=n.ChapterID,@SceneID=n.SceneID FROM dbo.NarrativeSceneOrder n
|
||||
LEFT JOIN dbo.Chapters currentChapter ON currentChapter.ChapterID=@oldChapter AND currentChapter.BookID=@BookID AND currentChapter.IsArchived=0
|
||||
WHERE n.BookID=@BookID AND(currentChapter.ChapterID IS NULL OR n.ChapterID=currentChapter.ChapterID OR
|
||||
(NOT EXISTS(SELECT 1 FROM dbo.NarrativeSceneOrder present WHERE present.BookID=@BookID AND present.ChapterID=currentChapter.ChapterID)
|
||||
AND(n.ChapterSortOrder<currentChapter.SortOrder OR(n.ChapterSortOrder=currentChapter.SortOrder AND n.ChapterNumber<=currentChapter.ChapterNumber))))
|
||||
ORDER BY n.BookSceneIndex DESC;
|
||||
IF @SceneID IS NULL BEGIN COMMIT;RETURN;END;
|
||||
END;
|
||||
IF @SceneID IS NOT NULL
|
||||
BEGIN
|
||||
DECLARE @actualChapter int=(SELECT ChapterID FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID AND SceneID=@SceneID);
|
||||
IF @actualChapter IS NULL OR(@ChapterID IS NOT NULL AND @actualChapter<>@ChapterID) THROW 51000,'Scene is unavailable in this book and chapter.',1;
|
||||
SET @ChapterID=@actualChapter;
|
||||
END;
|
||||
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 is unavailable in this book.',1;
|
||||
IF ISNULL(@ChapterID,0)<>ISNULL(@oldChapter,0) OR ISNULL(@SceneID,0)<>ISNULL(@oldScene,0)
|
||||
BEGIN
|
||||
UPDATE dbo.NarrativeFocus SET ChapterID=@ChapterID,SceneID=@SceneID,ParagraphID=NULL,OriginWindowID=NULL,Version=Version+1 WHERE UserID=@UserID AND BookID=@BookID;
|
||||
DELETE dbo.NarrativeFocusHistory WHERE UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID AND ISNULL(SceneID,0)=ISNULL(@SceneID,0);
|
||||
IF @ChapterID IS NOT NULL INSERT dbo.NarrativeFocusHistory VALUES(@UserID,@BookID,@version+1,@ChapterID,@SceneID);
|
||||
DELETE h FROM dbo.NarrativeFocusHistory h WHERE UserID=@UserID AND BookID=@BookID AND Sequence NOT IN
|
||||
(SELECT TOP(20) Sequence FROM dbo.NarrativeFocusHistory WHERE UserID=@UserID AND BookID=@BookID ORDER BY Sequence DESC);
|
||||
END;
|
||||
COMMIT;
|
||||
END;
|
||||
GO
|
||||
18
PlotLine/Sql/316_SharedFocusWordPositions.sql
Normal file
18
PlotLine/Sql/316_SharedFocusWordPositions.sql
Normal file
@ -0,0 +1,18 @@
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.NarrativeFocus_WordPosition @Action varchar(10),@UserID int,@BookID int,@ManuscriptID uniqueidentifier,@SessionID uniqueidentifier,@WordRevision bigint,@Cursor int=NULL,@ChapterID int=NULL,@SceneID int=NULL,@ParagraphID uniqueidentifier=NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE b.BookID=@BookID AND b.IsArchived=0 AND p.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1) THROW 51000,'Book unavailable',1;
|
||||
SELECT TOP(1) pos.ParagraphID,pos.ChapterID,CASE WHEN scene.SceneID IS NOT NULL THEN pos.SceneID END SceneID,pos.StartPosition
|
||||
FROM dbo.BookParagraphManuscripts m JOIN dbo.BookChapterValidations v ON v.BookID=m.BookID
|
||||
CROSS APPLY OPENJSON(m.Payload,'$.ChapterCheckpoints') WITH(ChapterID int '$.ChapterId',ContentHash char(64),IdentityHash char(64),MappingHash char(64)) c
|
||||
CROSS APPLY OPENJSON(v.Positions) WITH(ParagraphID uniqueidentifier '$.ParagraphId',ChapterID int '$.ChapterId',SceneID int '$.SceneId',StartPosition int '$.Start',EndPosition int '$.End',Verified bit) pos
|
||||
JOIN dbo.Chapters ch ON ch.ChapterID=pos.ChapterID AND ch.BookID=m.BookID AND ch.IsArchived=0
|
||||
LEFT JOIN dbo.Scenes scene ON scene.SceneID=pos.SceneID AND scene.ChapterID=ch.ChapterID AND scene.IsArchived=0
|
||||
WHERE m.BookID=@BookID AND m.ManuscriptID=@ManuscriptID AND v.ChapterID=c.ChapterID AND pos.ChapterID=c.ChapterID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.ManuscriptID=@ManuscriptID AND v.WordRevision=@WordRevision AND v.ExpiresUtc>SYSUTCDATETIME() AND v.ContentHash=c.ContentHash AND v.IdentityHash=c.IdentityHash AND v.MappingHash=c.MappingHash AND pos.Verified=1
|
||||
AND ((@Action='position' AND pos.StartPosition<=@Cursor AND pos.EndPosition>@Cursor) OR (@Action='target' AND (@ChapterID IS NULL OR pos.ChapterID=@ChapterID) AND (@SceneID IS NULL OR pos.SceneID=@SceneID) AND (@ParagraphID IS NULL OR pos.ParagraphID=@ParagraphID))) ORDER BY pos.StartPosition,pos.ParagraphID;
|
||||
END;
|
||||
GO
|
||||
2
PlotLine/Views/Shared/_FocusFollowControl.cshtml
Normal file
2
PlotLine/Views/Shared/_FocusFollowControl.cshtml
Normal file
@ -0,0 +1,2 @@
|
||||
@{var embedded=ViewContext.RouteData.Values["controller"]?.ToString()=="Writing";}
|
||||
<button type="button" class="@(embedded?"btn btn-outline-secondary btn-sm":"pd-ribbon-command")" data-shared-focus-hold aria-pressed="false" title="Hold this window independently; saved data continues updating"><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M8 4v16 M16 4v16"/></svg><span>Following · Hold</span></button><span class="small" data-shared-focus-status role="status"></span>
|
||||
@ -1,5 +1,6 @@
|
||||
@* One shared global navigation group; workspace adapters only control Go to Focus. *@
|
||||
<div class="pd-ribbon-group pd-ribbon-focus" role="group" aria-label="Focus">
|
||||
<div class="pd-ribbon-focus-mode"><partial name="_FocusFollowControl"/></div>
|
||||
<div class="pd-ribbon-commands">
|
||||
@foreach(var command in new[]{("previous","Previous","chevron-left","Previous scene in manuscript order"),("go","Go to Focus","focus","Display Current Focus in this workspace"),("next","Next","chevron-right","Next scene in manuscript order")}){
|
||||
<button type="button" class="pd-ribbon-command" data-global-focus="@command.Item1" data-ribbon-icon="@command.Item3" title="@command.Item4" aria-label="@command.Item4" disabled><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon(command.Item3).IconPath" /></svg><span>@command.Item2</span></button>
|
||||
|
||||
@ -189,6 +189,7 @@
|
||||
{
|
||||
<template data-pwa-initial-contributions>@PlotLine.TagHelpers.RibbonContributionTagHelper.Snapshot(Context)</template>
|
||||
<script src="~/js/scene-explorer.js" asp-append-version="true"></script>
|
||||
<script src="~/js/shared-manuscript-focus.js" asp-append-version="true" defer></script>
|
||||
<script src="~/js/narrative-focus.js" asp-append-version="true" defer></script>
|
||||
<script src="~/js/narrative-focus-workspaces.js" asp-append-version="true" defer></script>
|
||||
<script src="~/js/application-page-context.js" asp-append-version="true"></script>
|
||||
|
||||
@ -5,4 +5,4 @@
|
||||
var appearance=userID>0?await AppearancePreferences.GetAsync(userID):new ApplicationAppearance();
|
||||
}
|
||||
<!DOCTYPE html><html lang="en" data-theme="light" data-bs-theme="light"><head><meta charset="utf-8" /><partial name="_ApplicationThemeBootstrap" model="appearance" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>@ViewData["Title"] · PlotDirector</title><link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /><link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /><link rel="stylesheet" href="~/css/plotline-theme.css" asp-append-version="true" /><link rel="stylesheet" href="~/css/application-shell.css" asp-append-version="true" /><link rel="stylesheet" href="~/css/notifications.css" asp-append-version="true" /></head>
|
||||
<body class="app-layout writing-embedded" data-pd-user-id="@User.FindFirstValue(ClaimTypes.NameIdentifier)"><div class="writing-window-bar"><a href="/Writer" target="_blank" rel="noopener">PlotDirector</a><button type="button" id="native-companion-status" class="pd-presence" aria-haspopup="dialog" aria-controls="writing-connection-details" data-word-companion-presence><span class="word-companion-presence-dot"></span><span id="native-companion-status-text">Checking Word…</span></button></div><partial name="_WritingConnectionDetails" />@RenderBody()<partial name="_ToastHost" model="appearance" /><script src="~/js/notifications.js" asp-append-version="true"></script><script src="~/js/word-notifications.js" asp-append-version="true"></script><script src="https://cdn.jsdelivr.net/npm/@@microsoft/signalr@8.0.7/dist/browser/signalr.min.js"></script><script src="~/js/application-theme-sync.js" asp-append-version="true"></script><script src="~/js/story-position.js" asp-append-version="true"></script><script src="~/js/native-companion-status.js" asp-append-version="true" defer></script>@await RenderSectionAsync("Scripts",required:false)</body></html>
|
||||
<body class="app-layout writing-embedded" data-pd-user-id="@User.FindFirstValue(ClaimTypes.NameIdentifier)"><div class="writing-window-bar"><a href="/Writer" target="_blank" rel="noopener">PlotDirector</a><button type="button" id="native-companion-status" class="pd-presence" aria-haspopup="dialog" aria-controls="writing-connection-details" data-word-companion-presence><span class="word-companion-presence-dot"></span><span id="native-companion-status-text">Checking Word…</span></button></div><partial name="_WritingConnectionDetails" />@RenderBody()<partial name="_ToastHost" model="appearance" /><script src="~/js/notifications.js" asp-append-version="true"></script><script src="~/js/word-notifications.js" asp-append-version="true"></script><script src="https://cdn.jsdelivr.net/npm/@@microsoft/signalr@8.0.7/dist/browser/signalr.min.js"></script><script src="~/js/application-theme-sync.js" asp-append-version="true"></script><script src="~/js/story-position.js" asp-append-version="true"></script><script src="~/js/native-companion-status.js" asp-append-version="true" defer></script><script src="~/js/shared-manuscript-focus.js" asp-append-version="true" defer></script>@await RenderSectionAsync("Scripts",required:false)</body></html>
|
||||
|
||||
@ -21,6 +21,7 @@
|
||||
<header class="context-toolbar">
|
||||
<h1>Context</h1>
|
||||
<label>Layout <select data-context-layout class="form-select form-select-sm"><option value="single">Single pane</option><option value="columns">Side by side</option><option value="rows">Stacked</option></select></label>
|
||||
<partial name="_FocusFollowControl"/>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-context-new>New Context window</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-context-refresh>Refresh saved data</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-context-windows>My Windows</button>
|
||||
@ -29,7 +30,7 @@
|
||||
<nav class="context-navigation" aria-label="Saved manuscript scenes">
|
||||
<label>Scene <select data-context-scene class="form-select form-select-sm"><option value="">Choose a saved scene</option>@foreach(var item in Model.Display?.SceneOptions ?? []){<option value="@item.Value" selected="@item.Selected">@item.Text</option>}</select></label>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-context-previous>Previous</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-context-next>Next</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-context-next>Next</button><button type="button" class="btn btn-outline-secondary btn-sm" data-context-go-focus>Go to Focus</button>
|
||||
<a data-context-editor data-context-workspace-target="scene" data-context-entity="@Model.SceneID" class="btn btn-outline-secondary btn-sm" href="@(Model.SceneID.HasValue ? $"/Scenes/Edit/{Model.SceneID}" : "/Writer")" target="_blank" rel="noopener">Open scene editor</a>
|
||||
</nav>
|
||||
<div class="context-panes" data-context-panes data-layout="single">
|
||||
|
||||
@ -857,3 +857,14 @@ html[data-app-theme] .scenario-workspace :is(h1, h2, h3) {
|
||||
}
|
||||
.scenario-workspace .attention-list p { grid-column: 1 / -1; }
|
||||
.scenario-workspace .scenario-warning-badge { justify-self: start; }
|
||||
/* Static focus commands reserve their width in both modes; no delayed ribbon insertion. */
|
||||
.pd-shell [data-shared-focus-hold]{width:104px;min-width:104px;max-width:104px}
|
||||
.pd-ribbon-focus [data-shared-focus-status]{width:140px;min-width:140px;max-height:68px;overflow:auto;white-space:normal;overflow-wrap:anywhere;font-size:11px;line-height:1.2;align-self:center}
|
||||
[data-context-workspace] [data-shared-focus-hold]{min-width:190px}
|
||||
|
||||
/* Hold remains visible when the PWA compacts Previous/Go/Next into its existing menu. */
|
||||
.pd-shell .pd-ribbon-focus{display:grid;grid-template-columns:auto auto;grid-template-rows:1fr auto;column-gap:4px}
|
||||
.pd-ribbon-focus-mode{grid-column:1;grid-row:1;display:flex;align-items:flex-start;gap:4px}
|
||||
.pd-ribbon-focus>.pd-ribbon-commands,.pd-ribbon-focus>.pd-base-overflow{grid-column:2;grid-row:1}
|
||||
.pd-ribbon-focus>.pd-ribbon-group-label{grid-column:1/-1;grid-row:2}
|
||||
@media(max-width:760px){.pd-ribbon-focus [data-shared-focus-status]{width:90px;min-width:90px}}
|
||||
|
||||
@ -128,6 +128,8 @@
|
||||
generation++;cancelRequests();
|
||||
for(const pane of panes){for(const record of pane.records.values()){
|
||||
if(record.tab.contentRefresh==='none')continue;
|
||||
if(hint.kind==='relationships'&&!['overview','characters','relationships'].includes(record.tab.id))continue;
|
||||
if(hint.kind==='characters'&&!['overview','characters','relationships','names'].includes(record.tab.id))continue;
|
||||
// Scene projections can depend on established earlier records: book-level is conservative.
|
||||
record.stale=true;
|
||||
}void refreshPane(pane);}
|
||||
@ -144,45 +146,9 @@
|
||||
for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');for(const record of pane.records.values())if(force||scopeChanged(record.tab,before,position))record.stale=true;void refreshPane(pane);}
|
||||
announce();
|
||||
}
|
||||
async function recoverOffice(force=false) {
|
||||
if(pinned||selectedDocument||nativeLeases.some(l=>l.wordAvailable&&(!scope.bookId||Number(l.bookId)===scope.bookId)))return;
|
||||
if(recoveryPending){recoveryAgain ||= force;return;}
|
||||
recoveryPending=true;const epoch=recoveryGeneration;
|
||||
try {
|
||||
const url=new URL('/Writing/Context/Position',location.origin);for(const [key,value]of Object.entries(scope))if(value)url.searchParams.set(key,value);
|
||||
const response=await fetch(url,{cache:'no-store',signal:AbortSignal.timeout(8000),headers:{'X-Requested-With':'XMLHttpRequest'}});
|
||||
if(!response.ok||response.redirected)throw Error();const packet=await response.json();
|
||||
if(epoch!==recoveryGeneration||selectedDocument||nativeLeases.some(l=>l.wordAvailable&&(!scope.bookId||Number(l.bookId)===scope.bookId)))return;
|
||||
const office=packet.position;
|
||||
window.PlotDirector?.wordNotifications?.connection('office',packet.connected);
|
||||
const indicator=document.querySelector('[data-word-companion-presence]');if(indicator)indicator.dataset.officeConnected=String(packet.connected);
|
||||
if(packet.connected&&office){unavailable=false;status.textContent='Following Word · saved reference data';setPosition(office,force);}
|
||||
else {unavailable=true;status.textContent='Word disconnected · saved scene browsing remains available';if(force)invalidate();}
|
||||
} catch {if(epoch===recoveryGeneration){unavailable=true;status.textContent='Word status unavailable · saved reference remains available';if(force)invalidate();}}
|
||||
finally {recoveryPending=false;if(recoveryAgain){recoveryAgain=false;void recoverOffice(true);}}
|
||||
}
|
||||
function followNative(leases,force=false) {
|
||||
nativeLeases=leases.filter(l=>Date.parse(l.expires)>Date.now());recoveryGeneration++;
|
||||
const available=nativeLeases.filter(l=>l.wordAvailable&&(!scope.bookId||Number(l.bookId)===scope.bookId));
|
||||
const active=available.filter(l=>l.active);
|
||||
const chosen=selectedDocument?available.filter(l=>`${l.instanceId}/${l.sessionId}`===selectedDocument):active.length===1?active:available;
|
||||
const lease=chosen.length===1?chosen[0]:null;
|
||||
if(!lease){
|
||||
if(selectedDocument||available.length){unavailable=true;nativeKey='';status.textContent=available.length>1&&!selectedDocument?'Choose a Word document using the connection indicator':'Selected Word document disconnected · saved reference remains available';if(position.instanceId){generation++;cancelRequests();for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');if(current(pane))current(pane).stale=true;pane.status.textContent='Live position unavailable · displayed reference may be stale.';}}return;}
|
||||
nativeKey='';void recoverOffice(force);return;
|
||||
}
|
||||
if(lease.wordSaved!==true||lease.positionVerified===false||!lease.sceneId){
|
||||
unavailable=true;nativeKey='';if(position.instanceId){generation++;cancelRequests();for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');if(current(pane))current(pane).stale=true;pane.status.textContent='Displayed reference is saved data · current Word scene is unavailable.';}}
|
||||
status.textContent=lease.positionMessage||'Save Word and verify its scene mapping · saved reference remains available';return;
|
||||
}
|
||||
unavailable=false;
|
||||
const key=[lease.instanceId,lease.sessionId,lease.manuscriptId,lease.revision,lease.snapshotRevision,lease.chapterId,lease.sceneId].join(':');
|
||||
const changed=nativeKey!==key;nativeKey=key;
|
||||
status.textContent='Following Word · saved reference data';
|
||||
// Observed revision alone is not accepted content. It only causes position verification.
|
||||
setPosition({ ...scope,bookId:Number(lease.bookId),chapterId:Number(lease.chapterId),sceneId:Number(lease.sceneId),instanceId:lease.instanceId,sessionId:lease.sessionId },force||leases.reconnected);
|
||||
if(changed&&lease.mappingCurrent)invalidate({bookId:lease.bookId});
|
||||
}
|
||||
async function recoverOffice(){if(window.PlotDirectorSharedFocus)await window.PlotDirectorSharedFocus.refresh();}
|
||||
function followNative(leases){const changed=leases.some(l=>Number(l.bookId)===scope.bookId&&l.snapshotRevision&&nativeLeases.find(old=>old.instanceId===l.instanceId&&old.sessionId===l.sessionId)?.snapshotRevision!==l.snapshotRevision);nativeLeases=leases.filter(l=>Date.parse(l.expires)>Date.now());if(changed||leases.reconnected){invalidate({bookId:scope.bookId});void refreshStructure();void window.PlotDirectorSharedFocus?.validateLocal();}}
|
||||
async function refreshStructure(){try{const response=await fetch(`/NarrativeFocus/Read?projectId=${scope.projectId}&bookId=${scope.bookId}`,{cache:'no-store'});if(!response.ok||response.redirected)return;const data=await response.json(),id=position.sceneId,options=[new Option('Choose a saved scene',''),...data.positions.filter(p=>p.sceneID).map(p=>new Option(p.label,String(p.sceneID)))];if(id&&!options.some(o=>Number(o.value)===id)){const missing=new Option('Reference unavailable · choose another scene',String(id));missing.disabled=true;options.push(missing);}sceneSelect.replaceChildren(...options);sceneSelect.value=id||'';}catch{/* Saved reference remains visible. */}}
|
||||
function applyLayout() {
|
||||
grid.dataset.layout=state.layout;layoutSelect.value=state.layout;
|
||||
panes[1].element.hidden=state.layout==='single';divider.hidden=state.layout==='single';
|
||||
@ -215,23 +181,16 @@
|
||||
const record=current(pane);if(!record)return;record.dirty=!!event.detail?.dirty;record.busy=!!event.detail?.busy;if(!guarded(record)&&record.stale&&!event.detail?.deferRefresh)void refreshPane(pane);announce();
|
||||
});
|
||||
}
|
||||
async function navigate(sceneId,sendWord=false) {
|
||||
const id=number(sceneId);if(!id)return;
|
||||
const manual=++manualGeneration;navigationRequest?.abort();
|
||||
setPosition({...scope,chapterId:null,sceneId:id});status.textContent=pinned?'Saved PlotDirector snapshot · manual selection':'Saved scene selected';
|
||||
if(!sendWord||pinned||!scope.bookId)return;
|
||||
navigationRequest=new AbortController();
|
||||
const token=document.querySelector('[data-word-sync-form] [name=__RequestVerificationToken]')?.value;
|
||||
const body=new URLSearchParams({bookId:scope.bookId,sceneId:id,navigationId:uuid(),__RequestVerificationToken:token||''});
|
||||
if(selectedDocument){const [instanceId,sessionId]=selectedDocument.split('/');body.set('instanceId',instanceId);body.set('sessionId',sessionId);}
|
||||
try{const response=await fetch('/Writing/Context/Navigate',{method:'POST',body,signal:navigationRequest.signal,headers:{'X-Requested-With':'XMLHttpRequest'}});const packet=await response.json();if(manual===manualGeneration)status.textContent=packet.message||'Saved scene selected';}catch(error){if(error.name!=='AbortError'&&manual===manualGeneration)status.textContent='Saved scene selected · Word navigation unavailable';}
|
||||
}
|
||||
async function navigate(sceneId){const id=number(sceneId);if(!id)return;if(windowBusy||panes.some(p=>guarded(current(p)))){status.textContent='Save or cancel the current editor before changing manuscript position.';return;}if(!window.PlotDirectorSharedFocus){status.textContent='Focus is initialising; retry this selection.';return;}const moved=await window.PlotDirectorSharedFocus.navigate({projectID:scope.projectId,bookID:scope.bookId,sceneID:id});if(!moved)sceneSelect.value=position.sceneId||'';}
|
||||
function sharedPosition(event){const p=event.detail.position;setPosition({projectId:p.projectID,bookId:p.bookID,chapterId:p.chapterID,sceneId:p.sceneID,paragraphId:p.paragraphID});status.textContent=window.PlotDirectorSharedFocus?.held?'Held at local manuscript position · saved data remains live':'Following shared manuscript focus · saved reference data';}
|
||||
window.addEventListener('plotdirector:shared-focus',sharedPosition);
|
||||
root.querySelector('[data-context-go-focus]')?.addEventListener('click',()=>void window.PlotDirectorSharedFocus?.go());
|
||||
sceneSelect.addEventListener('change',event=>void navigate(sceneSelect.value,event.isTrusted));
|
||||
for(const [selector,step]of [['[data-context-previous]',-1],['[data-context-next]',1]])root.querySelector(selector).addEventListener('click',event=>{const at=[...sceneSelect.options].findIndex(o=>Number(o.value)===position.sceneId);const next=sceneSelect.options[at+step];if(next?.value)void navigate(next.value,event.isTrusted);});
|
||||
for(const [selector,step]of [['[data-context-previous]',-1],['[data-context-next]',1]])root.querySelector(selector).addEventListener('click',()=>{const choices=[...sceneSelect.options].filter(o=>number(o.value)),at=choices.findIndex(o=>Number(o.value)===position.sceneId),next=at<0?(step>0?choices[0]:choices.at(-1)):choices[at+step];if(next)void navigate(next.value);});
|
||||
root.querySelector('[data-context-new]').addEventListener('click',()=>window.PlotDirectorWritingWorkspace.openContext({...position,pinned}));
|
||||
root.querySelector('[data-context-refresh]').addEventListener('click',()=>invalidate());
|
||||
window.addEventListener('native-companion-presence',event=>{if(!pinned)followNative(event.detail||[],!!event.detail?.reconnected);});
|
||||
window.addEventListener('plotdirector:word-document-selected',event=>{if(pinned)return;selectedDocument=event.detail||'';presentSelectedDocument();const url=new URL(location.href);if(selectedDocument){url.searchParams.set('instanceId',root.dataset.wordInstance);url.searchParams.set('sessionId',root.dataset.wordSession);}else{url.searchParams.delete('instanceId');url.searchParams.delete('sessionId');}history.replaceState(null,'',url);nativeKey='';save();followNative(nativeLeases,true);});
|
||||
window.addEventListener('native-companion-presence',event=>{followNative(event.detail||[]);});
|
||||
window.addEventListener('plotdirector:word-document-selected',event=>{selectedDocument=event.detail||'';presentSelectedDocument();const url=new URL(location.href);if(selectedDocument){url.searchParams.set('instanceId',root.dataset.wordInstance);url.searchParams.set('sessionId',root.dataset.wordSession);}else{url.searchParams.delete('instanceId');url.searchParams.delete('sessionId');}history.replaceState(null,'',url);nativeKey='';save();followNative(nativeLeases,true);});
|
||||
window.addEventListener('plotdirector:word-return-to-current',()=>{if(!pinned){nativeKey='';followNative(nativeLeases,true);}});
|
||||
function wakeStatus(reconnected=false){window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status',{detail:{reconnected}}));}
|
||||
async function startConnection(){
|
||||
@ -239,17 +198,17 @@
|
||||
connectionStarting=true;
|
||||
try{await connection.start();wakeStatus(true);void recoverOffice(true);root.dispatchEvent(new Event('context-connection-ready'));}catch{status.textContent='Context notifications disconnected · retrying; saved browsing remains available';}finally{connectionStarting=false;}
|
||||
}
|
||||
if(!pinned&&window.signalR){
|
||||
if(window.signalR){
|
||||
connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();
|
||||
connection.on('NativePresenceChanged',hint=>{window.dispatchEvent(new CustomEvent('plotdirector:native-presence-changed',{detail:hint}));wakeStatus();});
|
||||
connection.on('ContextPositionChanged',()=>void recoverOffice());
|
||||
connection.on('ContextInvalidated',hint=>{invalidate(hint);wakeStatus();});
|
||||
connection.on('ContextInvalidated',hint=>{invalidate(hint);if(hint.kind==='structure')void refreshStructure();wakeStatus();});
|
||||
connection.onreconnecting(()=>status.textContent='Context notifications reconnecting · saved reference may be stale');
|
||||
connection.onreconnected(()=>{wakeStatus(true);void recoverOffice(true);invalidate();root.dispatchEvent(new Event('context-connection-ready'));});
|
||||
connection.onclose(()=>status.textContent='Context notifications disconnected · saved browsing remains available');
|
||||
void startConnection();
|
||||
}
|
||||
const timer=pinned?null:setInterval(()=>{void startConnection();void recoverOffice();announce();},15000);
|
||||
const timer=setInterval(()=>{void startConnection();announce();},15000);
|
||||
document.addEventListener('visibilitychange',()=>{if(!document.hidden&&!pinned){void startConnection();wakeStatus(true);void recoverOffice(true);}});
|
||||
window.addEventListener('pageshow',event=>{if(event.persisted)location.reload();});
|
||||
// Duplicated browser tabs clone both URL and session storage. The live owner answers claims.
|
||||
@ -274,5 +233,5 @@
|
||||
root.contextController={ get windowId(){return windowId;}, get position(){return {...position};}, invalidate,setPosition,get connection(){return connection;},get announcement(){return {version:1,bookID:position.bookId,windowID:windowId,panes:panes.filter(visible).map(pane=>({paneID:String(pane.index),toolID:state.panes[pane.index].tab,actions:registry.get(state.panes[pane.index].tab).actions||[],available:!windowBusy&&!!current(pane)?.node&&!current(pane).stale&&!guarded(current(pane))}))};},receiveInteraction:async delivery=>{if(windowBusy)return 'busy';const pane=panes.find(p=>String(p.index)===delivery.paneID);if(!pane||!visible(pane))return 'not-visible';const record=current(pane);if(guarded(record))return 'busy';if(!record?.node||record.stale)return 'unavailable';record.stale=true;await refreshPane(pane);if(record.stale||guarded(record))return 'unavailable';return await lifecycles[record.tab.lifecycle]?.onInteraction?.(record.node,delivery.command,{position:{...position},pane})||'not-visible';},registerLifecycle:(name,hooks)=>lifecycles[name]=hooks };
|
||||
window.addEventListener('pagehide',()=>{stopped=true;panes.forEach(pane=>{remember(pane);dispose(current(pane));});save();cancelRequests();navigationRequest?.abort();clearInterval(timer);observer.disconnect();channel?.close();void connection?.stop();});
|
||||
save();applyLayout();
|
||||
if(pinned)status.textContent='Saved PlotDirector snapshot · manual selection · live follow disabled';
|
||||
status.textContent='Shared manuscript focus initialising · local saved data remains available';
|
||||
})();
|
||||
|
||||
@ -103,8 +103,9 @@ function initialiseManuscriptReader() {
|
||||
root.readerPreserveView=()=>{const mine=narrativePosition,anchors=rememberPosition();return ()=>{if(root.isConnected&&mine===narrativePosition)restorePosition(anchors);};};
|
||||
root.readerResolveFocus=target=>{
|
||||
if(Number(bookId)!==target.bookID||Number(chapterId)!==target.chapterID)return null;
|
||||
const paragraph=target.sceneID?[...content.querySelectorAll('[data-paragraph-id][data-scene-id]')].find(n=>Number(n.dataset.sceneId)===target.sceneID):null;
|
||||
return {paragraph,precise:!!paragraph,version:root.dataset.version,revision:root.dataset.revision};
|
||||
const exact=target.paragraphID?content.querySelector(`[data-paragraph-id="${CSS.escape(target.paragraphID)}"]`):null;
|
||||
const paragraph=exact||(target.sceneID?[...content.querySelectorAll('[data-paragraph-id][data-scene-id]')].find(n=>Number(n.dataset.sceneId)===target.sceneID):null);
|
||||
return {paragraph,precise:target.paragraphID?!!exact:!!paragraph,version:root.dataset.version,revision:root.dataset.revision};
|
||||
};
|
||||
root.readerLocateFocus=target=>{
|
||||
const resolved=root.readerResolveFocus(target);if(!resolved)return null;
|
||||
|
||||
@ -15,7 +15,7 @@
|
||||
if(!canChange()){offer('Save or cancel open editors, clear any text selection and close dialogs before changing the displayed chapter or scene. Your original references are retained.');return;}
|
||||
try{
|
||||
if(focus.chapterID!==Number(reader.dataset.chapterId)){
|
||||
request=new AbortController();const url=new URL('/Writer/ReviewContent',location.origin);url.search=new URLSearchParams({projectId:focus.projectID,bookId:focus.bookID,version:focus.version,focus:reader.dataset.focus==='true',reading:reader.dataset.reading==='true'});
|
||||
request=new AbortController();const url=new URL('/Writer/ReviewContent',location.origin);url.search=new URLSearchParams({projectId:focus.projectID,bookId:focus.bookID,version:focus.version,focus:reader.dataset.focus==='true',reading:reader.dataset.reading==='true',chapterId:focus.chapterID,localFocus:window.PlotDirectorSharedFocus?.held===true});
|
||||
const response=await fetch(url,{cache:'no-store',signal:request.signal});if(!response.ok||response.redirected)throw Error('The chapter could not be refreshed.');
|
||||
const doc=new DOMParser().parseFromString(await response.text(),'text/html'),fresh=doc.querySelector('[data-review-columns]'),nextReader=fresh?.querySelector('.manuscript-reader');
|
||||
if(!nextReader||Number(nextReader.dataset.bookId)!==focus.bookID||Number(nextReader.dataset.chapterId)!==focus.chapterID)throw Error('The requested chapter is unavailable.');
|
||||
@ -36,8 +36,8 @@
|
||||
if(mine!==generation||!same(focus,current())||!canChange())return;
|
||||
for(const [name,value]of reader._focusFilters||[]){const select=columns.querySelector(`[data-annotation-filter="${name}"]`);if(select){select.value=value;select.dispatchEvent(new Event('change',{bubbles:true}));}}delete reader._focusFilters;
|
||||
const resolved=reader.readerResolveFocus(focus);
|
||||
notice.hidden=!focus.sceneID||resolved.precise;
|
||||
if(!notice.hidden)notice.textContent='Current Focus: '+focus.label+'. Precise scene positioning is unavailable: no accepted paragraph is mapped to this scene. Chapter context is shown; select an accepted passage for verified scene context.';
|
||||
notice.hidden=!(focus.sceneID||focus.paragraphID)||resolved.precise;
|
||||
if(!notice.hidden)notice.textContent=(focus.paragraphID?'The requested paragraph is unavailable in this accepted chapter. The mapped scene or chapter is shown. ':'')+'Current Focus: '+focus.label+'. Precise scene positioning is unavailable: no accepted paragraph is mapped to this scene. Chapter context is shown; select an accepted passage for verified scene context.';
|
||||
window.dispatchEvent(new Event('plotdirector:context-changed'));
|
||||
await frame();await frame();
|
||||
if(mine!==generation||!same(focus,current())||!reader.isConnected||!canChange())return;
|
||||
@ -45,9 +45,15 @@
|
||||
reader.dispatchEvent(new CustomEvent('reader:focus-positioned',{bubbles:true,detail:{chapterID:focus.chapterID,sceneID:focus.sceneID,paragraphID:reader.dataset.focusParagraph||null,version:reader.dataset.version}}));
|
||||
}catch(error){if(error.name!=='AbortError'&&mine===generation)offer((error.message||'Current Focus could not be displayed.')+' Your content and edits are retained.');}
|
||||
}
|
||||
window.addEventListener('plotdirector:narrative-focus-changed',event=>void apply(event.detail));
|
||||
window.PlotDirectorFocusWorkspace.register({canGo:focus=>focus.bookID===Number(document.querySelector('.manuscript-reader')?.dataset.bookId)&&!!focus.chapterID,unavailable:'Choose a chapter in this Review book to display Current Focus',go:apply});
|
||||
window.addEventListener('plotdirector:narrative-focus-changed',event=>{if(window.PlotDirectorSharedFocus)void apply(event.detail);});
|
||||
window.PlotDirectorFocusWorkspace.register({canGo:focus=>focus.bookID===Number(document.querySelector('.manuscript-reader')?.dataset.bookId)&&!!focus.chapterID,beforeChange:()=>canChange(),unavailable:'Choose a chapter in this Review book to display Current Focus',go:apply});
|
||||
document.addEventListener('reader:updated',()=>void apply(current()));
|
||||
if(current())void apply(current());
|
||||
if(current()&&window.PlotDirectorSharedFocus)void apply(current());
|
||||
window.addEventListener('pagehide',()=>{++generation;request?.abort();});
|
||||
function selectParagraph(p){const r=p.closest('.manuscript-reader');if(!r||document.querySelector('[data-writer-review]')?.canChangeNarrative?.()===false)return;for(const item of r.querySelectorAll('[data-paragraph-id]'))item.tabIndex=item===p?0:-1;void window.PlotDirectorSharedFocus?.navigate({projectID:current()?.projectID,bookID:Number(r.dataset.bookId),chapterID:Number(r.dataset.chapterId),sceneID:Number(p.dataset.sceneId)||null,paragraphID:p.dataset.paragraphId,localSelection:true});}
|
||||
document.addEventListener('click',event=>{if(!event.isTrusted)return;const p=event.target.closest('.manuscript-reader [data-paragraph-id]');if(p)selectParagraph(p);const link=event.target.closest('.reader-chapter-navigation a[href]');if(link){event.preventDefault();const chapter=Number(new URL(link.href).searchParams.get('chapterId'));if(chapter)void window.PlotDirectorSharedFocus?.navigate({chapterID:chapter});}});
|
||||
document.addEventListener('submit',event=>{if(event.defaultPrevented)return;const form=event.target;if(form.closest('.reader-chapter-navigation')){event.preventDefault();const chapter=Number(new FormData(form).get('chapterId'));if(chapter)void window.PlotDirectorSharedFocus?.navigate({chapterID:chapter});}});
|
||||
document.addEventListener('keydown',event=>{if(!event.target.matches('.manuscript-reader [data-paragraph-id]')||!['ArrowUp','ArrowDown','Home','End'].includes(event.key))return;event.preventDefault();const paragraphs=[...event.target.closest('.manuscript-reader').querySelectorAll('[data-paragraph-id]')],index=paragraphs.indexOf(event.target),next=event.key==='Home'?0:event.key==='End'?paragraphs.length-1:Math.max(0,Math.min(paragraphs.length-1,index+(event.key==='ArrowDown'?1:-1)));const p=paragraphs[next];p.focus({preventScroll:true});p.scrollIntoView({block:'nearest'});p.click();selectParagraph(p);});
|
||||
document.querySelector('.manuscript-reader [data-paragraph-id]')?.setAttribute('tabindex','0');
|
||||
|
||||
})();
|
||||
|
||||
@ -38,7 +38,7 @@
|
||||
window.addEventListener('plotdirector:narrative-focus-changed',e=>align(e.detail));
|
||||
window.addEventListener('beforeunload',e=>{if(!leaving&&dirty()){e.preventDefault();e.returnValue='';}});
|
||||
window.addEventListener('pageshow',()=>{leaving=false;});
|
||||
const initial=window.PlotDirectorNarrativeFocus?.state;if(initial)align(initial);
|
||||
const initial=window.PlotDirectorNarrativeFocus?.state;if(initial&&window.PlotDirectorSharedFocus)align(initial);
|
||||
}
|
||||
const chapterPage=document.querySelector('[data-focus-chapter]');
|
||||
if(chapterPage){
|
||||
@ -63,7 +63,7 @@
|
||||
}
|
||||
registry.register({canGo:scope,unavailable:'Choose a chapter in this chapter page’s book',go:align});
|
||||
window.addEventListener('plotdirector:narrative-focus-changed',e=>align(e.detail));
|
||||
const initial=window.PlotDirectorNarrativeFocus?.state;if(initial)align(initial);
|
||||
const initial=window.PlotDirectorNarrativeFocus?.state;if(initial&&window.PlotDirectorSharedFocus)align(initial);
|
||||
window.addEventListener('beforeunload',e=>{if(chapterPage.querySelector('form[data-focus-dirty=true]')&&!submitting){e.preventDefault();e.returnValue='';}});
|
||||
}
|
||||
if(controller==='Books'&&action==='Details')registry.register({canGo:focus=>!!focus.chapterID,go:focus=>location.assign(`/Chapters/Details/${focus.chapterID}?retainNarrativeFocus=true`)});
|
||||
|
||||
@ -8,7 +8,7 @@
|
||||
const dismiss=(restore=false)=>{restore=restore===true||root.querySelector('.pd-focus-picker').contains(document.activeElement);bootstrap.Dropdown.getOrCreateInstance(toggle).hide();if(restore)toggle.focus({preventScroll:true});};
|
||||
const scopeKey=`pd-narrative-book:${document.body.dataset.pdUserId}:${state.projectID}`;
|
||||
const notificationKey=()=>`pd-narrative-focus:${document.body.dataset.pdUserId}:${state.projectID}:${state.bookID}`;
|
||||
async function loadScope(book){if(!book){render();return;}const mine=++epoch;busy=true;render();try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const result=await response.json();if(mine!==epoch)return;state=result;publish();status.textContent='';}catch{status.textContent='This focus book is unavailable. Your workspace is unchanged.';}finally{busy=false;render();if(refreshQueued){refreshQueued=false;void refresh();}}}
|
||||
async function loadScope(book){if(!book){render();return;}const mine=++epoch;busy=true;render();try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const result=await response.json();if(mine!==epoch)return;state=result;if(window.PlotDirectorSharedFocus)await window.PlotDirectorSharedFocus.scope(state);publish();status.textContent='';}catch{status.textContent='This focus book is unavailable. Your workspace is unchanged.';}finally{busy=false;render();if(refreshQueued){refreshQueued=false;void refresh();}}}
|
||||
bookPicker?.addEventListener('change',()=>void loadScope(Number(bookPicker.value)));
|
||||
const key=p=>`${p.chapterID||''}/${p.sceneID||''}`;
|
||||
const selected=()=>key(state);
|
||||
@ -28,12 +28,13 @@
|
||||
for(const card of document.querySelectorAll('.timeline-scene-card[data-scene-id]')){const current=Number(card.dataset.sceneId)===state.sceneID;card.classList.toggle('pd-current-narrative-focus',current);if(current)card.setAttribute('aria-current','location');else if(card.getAttribute('aria-current')==='location')card.removeAttribute('aria-current');}
|
||||
for(const link of document.querySelectorAll('[data-focus-reference-link]')){const url=new URL(link.href);url.searchParams.delete('chapterId');url.searchParams.delete('sceneId');if(state.chapterID)url.searchParams.set('chapterId',state.chapterID);if(state.sceneID)url.searchParams.set('sceneId',state.sceneID);link.href=url;}
|
||||
window.dispatchEvent(new CustomEvent('plotdirector:narrative-focus-changed',{detail:state}));}
|
||||
async function refresh(){if(!state.bookID)return;if(busy){refreshQueued=true;return;}refreshQueued=false;const mine=++epoch;try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${state.bookID}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const fresh=await response.json();if(mine!==epoch||busy)return;if(fresh.version!==state.version){state=fresh;publish();}else{state=fresh;render();}}catch{if(mine===epoch&&!busy)status.textContent='Current focus could not be refreshed. Your edits are retained.';}}
|
||||
async function refresh(){if(window.PlotDirectorSharedFocus){await window.PlotDirectorSharedFocus.refresh();return;}if(!state.bookID)return;if(busy){refreshQueued=true;return;}refreshQueued=false;const mine=++epoch;try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${state.bookID}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const fresh=await response.json();if(mine!==epoch||busy)return;if(fresh.version!==state.version){state=fresh;publish();}else{state=fresh;render();}}catch{if(mine===epoch&&!busy)status.textContent='Current focus could not be refreshed. Your edits are retained.';}}
|
||||
async function set(target={}){
|
||||
if(busy||!state.bookID){status.textContent='Choose a focus book first.';return false;}
|
||||
if(target.bookID&&Number(target.bookID)!==state.bookID||target.projectID&&Number(target.projectID)!==state.projectID){status.textContent='Choose this book in the header before setting its focus.';return false;}
|
||||
const adapter=window.PlotDirectorFocusWorkspace?.adapter;
|
||||
if(adapter?.beforeChange&&!adapter.beforeChange(target)){render();return false;}
|
||||
if(window.PlotDirectorSharedFocus?.ownsScope(state)){busy=true;render();try{const result=await window.PlotDirectorSharedFocus.navigate(target);if(result)dismiss();return result;}finally{adapter?.changeFinished?.();busy=false;render();}}
|
||||
const fromPicker=root.querySelector('.pd-focus-picker').contains(document.activeElement);
|
||||
busy=true;++epoch;render();status.textContent='Updating current focus…';
|
||||
const body=new URLSearchParams({projectId:state.projectID,bookId:state.bookID,version:state.version,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});
|
||||
@ -51,11 +52,13 @@
|
||||
function closeRibbonMenu(button){const menu=button.closest('details[data-compact=true]');if(menu){const restore=menu.contains(document.activeElement)||document.activeElement===document.body;menu.open=false;if(restore)menu.querySelector('summary').focus({preventScroll:true});}else if(document.activeElement===document.body){const target=button.disabled?button.closest('.pd-ribbon-focus').querySelector('button:not(:disabled)'):button;target?.focus({preventScroll:true});}}
|
||||
document.querySelectorAll('[data-global-focus=previous],[data-global-focus=next]').forEach(b=>b.addEventListener('click',async()=>{if(await set({direction:(b.dataset.globalFocus==='previous'?-1:1)}))closeRibbonMenu(b);}));
|
||||
window.addEventListener('plotdirector:focus-adapter-ready',render);
|
||||
document.querySelectorAll('[data-global-focus=go]').forEach(b=>b.addEventListener('click',async()=>{const adapter=window.PlotDirectorFocusWorkspace?.adapter;if(busy)return;if(!adapter?.canGo(state)){showWorkspaceMessage(adapter?.unavailable||'Current Focus is unavailable in this workspace.');render();return;}document.querySelector('[data-focus-workspace-status]')?.remove();busy=true;render();let succeeded=false;try{await adapter.go(state);succeeded=true;}catch(error){showWorkspaceMessage(error.message||'Current Focus could not be displayed.');}finally{busy=false;render();if(succeeded)closeRibbonMenu(b);if(refreshQueued){refreshQueued=false;void refresh();}}}));
|
||||
document.querySelectorAll('[data-global-focus=go]').forEach(b=>b.addEventListener('click',async()=>{const adapter=window.PlotDirectorFocusWorkspace?.adapter;if(busy)return;if(window.PlotDirectorSharedFocus?.ownsScope(state)){await window.PlotDirectorSharedFocus.go();return;}if(!adapter?.canGo(state)){showWorkspaceMessage(adapter?.unavailable||'Current Focus is unavailable in this workspace.');render();return;}document.querySelector('[data-focus-workspace-status]')?.remove();busy=true;render();let succeeded=false;try{await adapter.go(state);succeeded=true;}catch(error){showWorkspaceMessage(error.message||'Current Focus could not be displayed.');}finally{busy=false;render();if(succeeded)closeRibbonMenu(b);if(refreshQueued){refreshQueued=false;void refresh();}}}));
|
||||
function showWorkspaceMessage(message){let output=document.querySelector('[data-focus-workspace-status]');if(!output){output=document.createElement('p');output.dataset.focusWorkspaceStatus='';output.setAttribute('role','status');document.querySelector('.pd-shell').after(output);}output.textContent=message;}
|
||||
window.addEventListener('pagehide',dismiss);
|
||||
document.addEventListener('click',e=>{const b=e.target.closest('[data-go-objective],[data-narrative-scene]');if(!b)return;void set({bookID:Number(b.dataset.narrativeBook)||state.bookID,chapterID:Number(b.dataset.chapter||b.dataset.narrativeChapter)||null,sceneID:Number(b.dataset.scene||b.dataset.narrativeScene)||null});});
|
||||
window.addEventListener('storage',e=>{if(e.key===notificationKey())void refresh();});window.addEventListener('focus',()=>void refresh());window.addEventListener('pageshow',()=>void refresh());root.addEventListener('shown.bs.dropdown',()=>void refresh());
|
||||
window.addEventListener('plotdirector:shared-focus',event=>{const p=event.detail.position;if(p.bookID!==state.bookID||p.projectID!==state.projectID)return;const position=state.positions.find(x=>x.chapterID===p.chapterID&&(!p.sceneID||x.sceneID===p.sceneID));state={...state,...p,label:position?(p.sceneID?position.label:`Ch ${position.chapterNumber}: ${position.chapterTitle}`):'Choose chapter or scene'};if(event.detail.reason==='selection')render();else publish();});
|
||||
root.addEventListener('shown.bs.dropdown',async()=>{if(!state.bookID)return;try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${state.bookID}`,{cache:'no-store'});if(response.ok&&!response.redirected){const data=await response.json();state.positions=data.positions;state.recent=data.recent;render();}}catch{}});
|
||||
window.PlotDirectorNarrativeFocus={set,refresh,get state(){return state;}};
|
||||
publish();
|
||||
if(!state.bookID&&bookPicker){try{const book=localStorage.getItem(scopeKey);if([...bookPicker.options].some(o=>o.value===book))void loadScope(Number(book));}catch{}}
|
||||
|
||||
13
PlotLine/wwwroot/js/shared-manuscript-focus.js
Normal file
13
PlotLine/wwwroot/js/shared-manuscript-focus.js
Normal file
@ -0,0 +1,13 @@
|
||||
// One user/book/canonical-manuscript focus stream over the window's existing presence connection.
|
||||
(()=>{'use strict';function start(){const context=document.querySelector('[data-context-workspace]'),header=document.querySelector('[data-narrative-focus]'),reader=document.querySelector('.manuscript-reader');if(!context&&!header)return;const initial=window.PlotDirectorNarrativeFocus?.state||(header?JSON.parse(header.querySelector('[data-narrative-initial]').textContent):{});let project=Number(context?.dataset.scopeProjectId||initial.projectID),book=Number(context?.dataset.scopeBookId||initial.bookID),connection,disconnected=false,latest=null,local=null,epoch=0,sequence=0,held=false,publishing=false,selectionPublishing=false,queuedTarget=null;const user=document.body.dataset.pdUserId||context?.dataset.user||'',page=crypto.randomUUID(),buttons=[...document.querySelectorAll('[data-shared-focus-hold]')],outputs=[...document.querySelectorAll('[data-shared-focus-status]')];let id=context?.contextController?.windowId||sessionStorage.getItem('pd.shared-focus.window');if(!/^[\da-f-]{36}$/i.test(id||''))id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);const normal=p=>({projectID:Number(p.projectID||p.projectId||project),bookID:Number(p.bookID||p.bookId||book),chapterID:Number(p.chapterID||p.chapterId)||null,sceneID:Number(p.sceneID||p.sceneId)||null,paragraphID:p.paragraphID||p.paragraphId||null,manuscriptID:p.manuscriptID||p.manuscriptId||null,originWindowID:p.originWindowID||p.originWindowId||null,version:Number(p.version||0),isValid:p.isValid!==false});const key=()=>`pd.shared-focus.${user}.${id}`;const positionKey=p=>p&&[p.projectID,p.bookID,p.manuscriptID,p.chapterID,p.sceneID,p.paragraphID].join('/');function save(){try{sessionStorage.setItem(key(),JSON.stringify({held,local,sequence}));}catch{}}function restore(){try{const data=JSON.parse(sessionStorage.getItem(key())||'null');held=data?.held??context?.dataset.followMode==='snapshot';local=data?.local||normal(context?.contextController?.position||{...initial,chapterID:Number(reader?.dataset.chapterId)||initial.chapterID});sequence=data?.sequence||0;}catch{held=false;}}
|
||||
function status(message=''){buttons.forEach(b=>{(b.querySelector('span')||b).textContent=held?'Held · Release Hold':'Following · Hold';b.setAttribute('aria-pressed',String(held));b.disabled=!book;});outputs.forEach(n=>n.textContent=message||(held?'Held at local manuscript position · data updates remain live':'Following shared manuscript focus'));document.documentElement.dataset.manuscriptFocusMode=held?'held':'follow';}function apply(position,reason){local=normal(position);save();window.dispatchEvent(new CustomEvent('plotdirector:shared-focus',{detail:{position:local,reason}}));status();}function accept(packet,force=false){const next=normal(packet);if(next.bookID!==book||next.projectID!==project)return false;if(latest&&(next.version<latest.version||!force&&next.version===latest.version))return false;latest=next;if(publishing&&queuedTarget)return true;if(!held&&next.isValid&&next.chapterID&&(force||positionKey(local)!==positionKey(next)))apply(next,next.originWindowID===id&&selectionPublishing?'selection':'shared');else if(!next.isValid&&!held)status('Shared focus is unavailable. Select a valid chapter or scene; your local position is retained.');return true;}
|
||||
async function request(action,target={}){const token=document.querySelector('[name=__RequestVerificationToken]')?.value;if(!token)throw Error('Refresh this authenticated window before changing focus.');const body=new URLSearchParams({projectID:project,bookID:book,windowID:id,sequence:++sequence,__RequestVerificationToken:token});for(const[k,v]of Object.entries(target))if(v!=null&&['chapterID','sceneID','paragraphID','manuscriptID','direction'].includes(k))body.set(k,v);save();const response=await fetch('/NarrativeFocus/Shared/'+action,{method:'POST',body,cache:'no-store'});const packet=await response.json().catch(()=>null);if(!response.ok||response.redirected)throw Error(packet?.message||'Focus could not be changed. Your local reference is retained.');return normal(packet);}
|
||||
async function refresh(force=false){if(!book)return;const mine=++epoch;try{const response=await fetch(`/NarrativeFocus/Shared?projectID=${project}&bookID=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const packet=await response.json();if(mine===epoch){const recovering=disconnected;disconnected=false;accept(packet,force);if(recovering){status();void validateLocal();}return true;}return false;}catch{disconnected=true;status('Shared focus disconnected · local position and data are retained. Reconnect to catch up.');return false;}}
|
||||
async function navigate(target,forcePublication=false){const priorLocal=local;if(target.localSelection&&Number(target.bookID||book)===book){local=normal({...local,projectID:project,bookID:book,chapterID:target.chapterID,sceneID:target.sceneID||null,paragraphID:target.paragraphID});save();}if(publishing){queuedTarget=target;return true;}const effective=held?priorLocal:latest?.isValid?latest:null;if(!forcePublication&&Number(target.sceneID||target.sceneId)>0&&Number(target.sceneID||target.sceneId)===effective?.sceneID&&!effective.paragraphID&&!target.paragraphID&&!target.paragraphId)return true;const paragraph=target.paragraphID||target.paragraphId;if(!forcePublication&¶graph&¶graph===effective?.paragraphID&&Number(target.chapterID||target.chapterId)===effective.chapterID)return true;if(publishing)return false;if(target.bookID&&Number(target.bookID)!==book)return false;publishing=true;const localRequest=held;selectionPublishing=target.localSelection===true;try{const normalized={chapterID:target.chapterID||target.chapterId||null,sceneID:target.sceneID||target.sceneId||null,paragraphID:target.paragraphID||target.paragraphId||null,...(target.direction?{direction:target.direction}:{}),...(target.manuscriptID?{manuscriptID:target.manuscriptID}:{})};if(held&&target.direction)Object.assign(normalized,{chapterID:local.chapterID,sceneID:local.sceneID});const result=await request(localRequest?'Resolve':'Publish',normalized);if(result.bookID!==book||result.projectID!==project)return false;if(localRequest){if(held)apply(result,selectionPublishing?'selection':'local');else await refresh(true);}else accept(result,true);return true;}catch(error){status(error.message);return false;}finally{publishing=false;selectionPublishing=false;if(queuedTarget){const next=queuedTarget;queuedTarget=null;void navigate(next,true);}}}
|
||||
async function toggle(){queuedTarget=null;if(held){if(!await refresh()){status('Hold retained: reconnect before catching up to authoritative shared focus.');return;}held=false;save();if(latest?.isValid&&latest.chapterID)apply(latest,'release');else status('Following · no valid shared focus; local position retained.');}else{held=true;save();status();}window.dispatchEvent(new CustomEvent('plotdirector:focus-mode',{detail:{held}}));}
|
||||
async function validateLocal(){if(!held||!local?.chapterID)return;try{const result=await request('Validate',local);if(!result.isValid)status('Held reference is no longer valid. Select another local position or Release Hold.');}catch{status('Held reference cannot be resolved. Select another position; data updates remain connected.');}}
|
||||
function wire(c){if(!c||connection)return;connection=c;c.on('ManuscriptFocusChanged',packet=>accept(packet));c.on('ManuscriptFocusDelivery',packet=>{if(Number(packet.bookID||packet.bookId)===book&&Number(packet.version)===latest?.version)status('Word cannot follow this reference in the background. Save and synchronise Word; other windows remain independent.');});c.on('ContextInvalidated',hint=>{if(hint.bookId&&Number(hint.bookId)!==book||hint.projectId&&Number(hint.projectId)!==project)return;window.dispatchEvent(new CustomEvent('plotdirector:reference-invalidated',{detail:hint}));void validateLocal();});c.onreconnecting(()=>{disconnected=true;status('Shared focus reconnecting · local position retained.');});c.onclose(()=>{disconnected=true;status('Shared focus disconnected · local position retained.');});c.onreconnected(()=>{void refresh().then(()=>validateLocal());});void refresh();}
|
||||
const channel=!context&&window.BroadcastChannel?new BroadcastChannel('pd.shared-focus.identity.'+user):null;channel?.addEventListener('message',event=>{const m=event.data;if(m.id!==id||m.page===page)return;if(m.kind==='claim')channel.postMessage({kind:'occupied',id,page,target:m.page});if(m.kind==='occupied'&&m.target===page){id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);held=false;sequence=0;save();status();void refresh(true);}});channel?.postMessage({kind:'claim',id,page});
|
||||
context?.addEventListener('context-capabilities-changed',()=>{const next=context.contextController?.windowId;if(next&&next!==id){id=next;held=false;sequence=0;save();status();void refresh(true);}});
|
||||
restore();status();buttons.forEach(b=>b.addEventListener('click',()=>void toggle()));document.addEventListener('pd-presence-connection',e=>wire(e.detail));document.addEventListener('pd-presence-ready',()=>wire(window.PlotDirectorPresenceConnection));context?.addEventListener('context-connection-ready',()=>wire(context.contextController?.connection));wire(context?.contextController?.connection||window.PlotDirectorPresenceConnection);window.addEventListener('focus',()=>void refresh());window.addEventListener('pagehide',()=>{save();channel?.close();});window.PlotDirectorSharedFocus={navigate,refresh,toggle,validateLocal,get held(){return held;},get local(){return local;},get shared(){return latest;},get windowID(){return id;},async go(){if(await refresh(true)&&held&&latest?.isValid)apply(latest,'local');},ownsScope:p=>Number(p.bookID)===book&&Number(p.projectID)===project,async scope(p){project=Number(p.projectID);book=Number(p.bookID);queuedTarget=null;latest=null;const wasHeld=held;restore();held=wasHeld;local=normal(p);save();status();if(held)apply(local,'local');await refresh(true);}};document.addEventListener('click',async event=>{if(!event.isTrusted||event.defaultPrevented||event.button!==0||event.ctrlKey||event.metaKey||event.shiftKey||event.altKey)return;const link=event.target.closest('a[href]');if(!link||link.target&&link.target!=='_self'||link.closest('.reader-chapter-navigation'))return;const url=new URL(link.href,location.href);if(url.origin!==location.origin||url.searchParams.get('retainNarrativeFocus')==='true')return;const match=url.pathname.match(/^\/(Scenes\/Edit|Chapters\/(?:Details|Edit)|Writer\/Chapter)\/(\d+)$/i),timeline=/^\/Timeline(?:\/Index)?$/i.test(url.pathname)&&url.searchParams.get('navigateFocus')==='true';if(!match&&!timeline)return;const selectedScene=Number([...url.searchParams].find(([key])=>key.toLowerCase()==='selectedsceneid')?.[1]);const target=timeline?{sceneID:selectedScene}:match[1].toLowerCase()==='scenes/edit'?{sceneID:Number(match[2])}:{chapterID:Number(match[2])};if(timeline&&!selectedScene)return;event.preventDefault();const adapter=window.PlotDirectorFocusWorkspace?.adapter;try{if(adapter?.beforeChange&&await adapter.beforeChange(target)===false)return;await navigate(target);url.searchParams.delete('navigateFocus');url.searchParams.set('retainNarrativeFocus','true');location.assign(url);}finally{adapter?.changeFinished?.();}});window.dispatchEvent(new Event('plotdirector:shared-focus-ready'));void refresh();if(held&&local?.chapterID){apply(local,'restore');void validateLocal();}}
|
||||
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();
|
||||
@ -44,6 +44,6 @@ readerContent.addEventListener('keyup',()=>{if(dirty||busy)return;const choice=c
|
||||
reader.addEventListener('reader:metadata',()=>{if(!dirty)wordReference(selected);});
|
||||
reader.addEventListener('reader:updated',()=>{if(dirty)return;if(selected&&!readerContent.querySelector(`[data-paragraph-id="${CSS.escape(selected)}"]`)){selected=null;anchor=null;wordReference(null);message.textContent='The selected paragraph is no longer in the accepted chapter. Original observation references remain recorded.';}else wordReference(selected);void load();});
|
||||
function guard(e){if(!dirty&&!busy)return;const target=e.target.closest('a,form');if(!target||target===form||target.matches('[data-work-start]')||target.target==='_blank'||target.matches('.plotline-help-more')&&window.PlotLineHelpDrawer)return;if(!confirm(busy?'An observation save may still finish. Leave this Review page?':'Leave without saving your review observation?')){e.preventDefault();e.stopImmediatePropagation();}else allowLeave=true;}
|
||||
onDocument('click',e=>{if(e.target.closest('a'))guard(e);},true);onDocument('submit',guard,true);onWindow('beforeunload',e=>{if((dirty||busy)&&!allowLeave){e.preventDefault();e.returnValue='';}});onWindow('pageshow',e=>{allowLeave=false;if(e.persisted&&!dirty)void load();});onWindow('pagehide',()=>{clearTimeout(selectionTimer);controller?.abort();});for(const b of document.querySelectorAll('[data-review-scope-new]'))b.addEventListener('click',()=>{begin(b.dataset.reviewScopeNew);});onWindow('review:notes-saved',()=>void load());void load();
|
||||
onDocument('click',e=>{if(e.target.closest('a'))guard(e);},true);onDocument('submit',guard,true);onWindow('beforeunload',e=>{if((dirty||busy)&&!allowLeave){e.preventDefault();e.returnValue='';}});onWindow('pageshow',e=>{allowLeave=false;if(e.persisted&&!dirty)void load();});onWindow('pagehide',()=>{clearTimeout(selectionTimer);controller?.abort();});for(const b of document.querySelectorAll('[data-review-scope-new]'))b.addEventListener('click',()=>{begin(b.dataset.reviewScopeNew);});onWindow('plotdirector:reference-invalidated',event=>{const hint=event.detail||{};if(hint.bookId&&Number(hint.bookId)!==Number(root.dataset.book))return;if(root.canChangeNarrative())void load(true,true);else message.textContent='Saved information changed. Your local reference and edits are retained; reload observations when ready.';});onWindow('review:notes-saved',()=>void load());void load();
|
||||
}
|
||||
window.PlotDirectorReview={mount:initialiseReview};initialiseReview();
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user