diff --git a/Docs/WordCompanion/2026-11-12-context-intent-integration.md b/Docs/WordCompanion/2026-11-12-context-intent-integration.md new file mode 100644 index 00000000..8fe4e56c --- /dev/null +++ b/Docs/WordCompanion/2026-11-12-context-intent-integration.md @@ -0,0 +1,33 @@ +# Writing Context and Intent integration — 12 November 2026 + +The existing VSTO → Windows agent → native workspace redirect → Writing Context/Intent browser contract is retained. No native source, Companion version, installer, synchronisation algorithm, schema or manuscript data changes are included. + +## Findings and implementation + +Context already had scene cards, people, relationships, maps, metrics and plot exploration. Intent already displayed saved scene purpose/outcome, chapter objectives, emotional direction, reader takeaway, continuity requirements, notes, checklist and explicitly requested assessment. Existing Story Point services already provided batched, chronological, verified knowledge and relationship histories. + +Native launch previously fell back to the first scene when the request provided only a book and exact document session. Both Writing pages now resolve that exact user/book/instance/session. Chapter-capable sessions require accepted chapter-position evidence from the existing position stored procedure. Missing, unsaved, stale or disconnected mappings wait instead of choosing another scene. Native fragment requests carry the exact session and recheck acceptance after loading; concurrent changes return 409. The browser cancels older native requests on pending/disconnected mappings and retains the saved fragment with an explicit status. + +Writing uses a read-only scene hydration path rather than loading the full editing form, manuscript statistics, storage quotas, suggestions or per-entity legacy state. Existing Timeline/editor callers retain their original model. Intent avoids chronological history queries entirely. Request-scoped tasks share repeated scene/projection reads; unchanged native observations do not fetch another fragment. + +Context reuses Story Point's canonical narrative ordering and verified knowledge transitions, including earlier scenes and books. It prioritises the recorded viewpoint, limits initial knowledge and thread lists, ranks unresolved threads by current developments, character knowledge and chapter, and shows at most five established nearby scenes in the current book. A later narrative scene is excluded even if its story date is earlier. Historical relationships and other characters' knowledge are labelled author reference rather than viewpoint awareness. Reader knowledge is explicitly not independently recorded; missing viewpoint/knowledge is not inferred. Source links remain available. The full exploratory plot chart is identified as author planning, including future material. + +Intent displays saved purpose types and clearly identifies the author plan and scene reference. Opening either page does not save, analyse, accept suggestions or rewrite author decisions. Project membership and existing authentication/subscription boundaries remain in place; new writing hydration authorises the owning project before scene workspace queries. + +## Validation + +- `dotnet build PlotLine.slnx`: passed, zero warnings/errors. This normal solution gate compiles its existing agent projects; no Windows VSTO package/version/installer was produced. +- Full executable regression harness: passed (484 PASS lines, including nested checks). +- Focused `--writing-integration`: 26 checks passed; exact scene/session resolution, saved Intent preservation, unauthorised scope, stale/unsaved/claimed mappings, concurrent revision changes, chronological knowledge/relationships, relevant threads, missing viewpoint, repeated task reuse and canonical scene order. +- Focused `--writing-context-navigation`: 30 checks passed, including exact-session commands, access, maps/metrics and no passive navigation feedback. +- Chromium follow/recovery: passed native/legacy races, pending response cancellation, server 409 recovery, unverified mapping refusal, unchanged-scene deduplication and no passive Word commands/focus. +- Compiled Razor browser suites: Context shell/PWA and embedded layouts; navigation at three widths/four themes; people/plots/maps/metrics; Context/Intent saved plans and missing metadata; 400-scene chart fixture. The scale fixture retained one chart read across four scene changes (282 ms initial chart / 195 ms changes on this run). +- In-memory navigation projection: 48 chapters / 4,800 scenes in 3.0 ms, no SQL or Word. This is a projection measurement, not a live Discovery database or Word latency claim. The protected Discovery manuscript and accepted chapters were not modified. + +## Development delivery + +Deployment verification is recorded below after installation. No database migration is required. Development activity is checked before stopping the service; deployed settings, uploads, keys and logs are preserved. + +## Remaining Windows check + +Use the already qualified Companion to open Context and Intent at two accepted scenes, including a cross-chapter move. Confirm the current scene and saved objectives, then edit/save and confirm pending-to-verified following. Atlas tests exercise the server/browser contracts and compiled pages; they do not automate real Word. No Companion upgrade is required for this integration. diff --git a/PlotLine.Tests/Browser/writing-context-follow-recovery.cjs b/PlotLine.Tests/Browser/writing-context-follow-recovery.cjs index a024a7e0..6b6ea941 100644 --- a/PlotLine.Tests/Browser/writing-context-follow-recovery.cjs +++ b/PlotLine.Tests/Browser/writing-context-follow-recovery.cjs @@ -4,15 +4,16 @@ const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node: const page=await browser.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message)); const html=`
`; const fragment=(scene)=>`
Overview saved data
People saved data
`; - let current=22,failStatus=false,holdStatus=false,release,reads=0,commands=0,fragmentFailure=false,holdFragment=false,releaseFragment; + let current=22,wordSaved=true,verified=true,fragmentReads=0,failStatus=false,holdStatus=false,release,reads=0,commands=0,fragmentFailure=false,fragmentConflict=false,holdFragment=false,releaseFragment; await page.route('https://context.test/**',async r=>{const u=new URL(r.request().url()); if(u.pathname==='/')return r.fulfill({contentType:'text/html',body:html}); if(u.pathname==='/native-companion/status'){ reads++;const snapshot=current;if(holdStatus){holdStatus=false;await new Promise(resolve=>release=resolve);} - return r.fulfill(failStatus?{status:503}:{json:[{instanceId:'instance',sessionId:'session',bookId:12,chapterId:snapshot===22?10:11,sceneId:snapshot,wordAvailable:true,wordSaved:true,active:true,documentTitle:'Synthetic',expires:new Date(Date.now()+45000).toISOString()}]});} + return r.fulfill(failStatus?{status:503}:{json:[{instanceId:'instance',sessionId:'session',bookId:12,chapterId:snapshot===22?10:11,sceneId:snapshot,wordAvailable:true,wordSaved,positionVerified:verified,active:true,documentTitle:'Synthetic',expires:new Date(Date.now()+45000).toISOString()}]});} if(u.pathname==='/Writing/Context/Scene'){ + fragmentReads++;assert.equal(u.searchParams.get('instanceId')||'instance','instance');assert.equal(u.searchParams.get('sessionId')||'session','session'); if(holdFragment){holdFragment=false;await new Promise(resolve=>releaseFragment=resolve);} - return r.fulfill(fragmentFailure?{status:503}:{contentType:'text/html',body:fragment(Number(u.searchParams.get('sceneId')))});} + return r.fulfill(fragmentConflict?{status:409}:fragmentFailure?{status:503}:{contentType:'text/html',body:fragment(Number(u.searchParams.get('sceneId')))});} if(u.pathname==='/Writing/Context/Navigate'){commands++;assert.ok(new URLSearchParams(r.request().postData()).get('navigationId'));return r.fulfill({json:{message:'Navigation requested in Word.'}});} return r.fulfill({json:{known:false}}); }); @@ -30,7 +31,8 @@ const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node: // A delayed legacy broadcast must not override a live native cursor scene. await page.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:story-position-changed',{detail:{projectId:7,bookId:12,chapterId:10,sceneId:22,source:'WordCompanion'}}))); await page.waitForTimeout(120);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'23','stale legacy position cannot replace live native scene'); - for(let i=0;i<8;i++)await pulse();await page.waitForTimeout(60);assert.equal(commands,0);assert.equal(await page.evaluate(()=>focusCalls),0); + const repeated=fragmentReads; + for(let i=0;i<8;i++)await pulse();await page.waitForTimeout(60);assert.equal(commands,0);assert.equal(await page.evaluate(()=>focusCalls),0);assert.equal(fragmentReads,repeated,'unchanged native scenes do not recompute context fragments'); // Status failure must dispatch disconnection, not throw ReferenceError for an out-of-scope leases variable. failStatus=true;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('disconnected')); failStatus=false;current=22;await pulse();await scene(22);assert.deepEqual(errors,[]); @@ -44,6 +46,13 @@ const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node: // Genuine keyboard action requests exactly one command; its acknowledgement is passive. await page.locator('[data-writing-context-scene-select]').press('Home');await scene(22);await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Navigation requested'));assert.equal(commands,1); current=22;for(let i=0;i<4;i++)await pulse();await page.waitForTimeout(60);assert.equal(commands,1);assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.deepEqual(errors,[]); + // A pending/unsaved mapping must invalidate an older in-flight scene response. + holdFragment=true;current=23;await pulse();while(!releaseFragment)await page.waitForTimeout(10); + wordSaved=false;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Save Word')); + releaseFragment();await page.waitForTimeout(150);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22','late fragment cannot restore an earlier cursor after native mapping becomes pending'); + wordSaved=true;verified=false;await pulse();await page.waitForTimeout(60);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22','unverified claimed native scene cannot replace saved context'); + verified=true;fragmentConflict=true;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('awaiting verification'));assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22');fragmentConflict=false;await pulse();await scene(23);assert.equal(commands,1); + console.log('PASS pending native response cancellation, unverified mapping refusal, exact-session query parameters and no recomputation for repeated unchanged scenes'); console.log('PASS native/legacy race, cross-chapter cursor following, repeated presence without commands/focus, status failure recovery, in-flight invalidation, unchanged-scene fragment retry, trusted explicit navigation and acknowledgement without feedback; simulated Chromium protocol, not Word'); // Native safety source guard: ordinary polling must never invalidate the ribbon or select a range. const adapter=fs.readFileSync(path.resolve(__dirname,'../../PlotDirector.NativeCompanion/Vsto/WordAdapter.cs'),'utf8');const observation=adapter.split('private void CaptureSelection()')[1].split('private int DocumentEnd')[0];assert.doesNotMatch(observation,/invalidateRibbon\(|\.Select\(/);assert.match(adapter,/command.Kind=="navigate"/);console.log('PASS native source invariant: selection observation contains no ribbon invalidation or range selection (not runtime Word proof)'); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 48e754bc..a8ceb381 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -141,6 +141,7 @@ if(args.Contains("--native-import-corrections")){await NativeImportCorrectionTes if(args.Contains("--native-captured-evidence")){await NativeImportCorrectionTests.CapturedEvidence(args[1],args[2]);return;} if(args.Contains("--writing-context-dev-seed")){await WritingContextDevelopmentFixture.Run(args);return;} if(args.Contains("--writing-context-navigation")){await WritingContextNavigationTests.Run();return;} +if(args.Contains("--writing-integration")){await WritingIntegrationTests.Run();return;} if(args.Contains("--native-capture-lifetime")){await NativeCaptureLifetimeTests.Run();return;} if(args.Contains("--native-tray")){await NativeTrayIntegrationTests.Run();await NativeManuscriptCaptureTests.Run();Console.WriteLine("PASS native tray presence, expiry, scope and persistent PWA review decisions");return;} if(args.Contains("--native-workflow")){await NativeWorkflowTests.Run();Console.WriteLine("PASS native saved workspace and safe import preview validation");return;} @@ -501,6 +502,7 @@ var tests = new (string Name, Action Test)[] ("Toolbar preferences, authorisation and contextual routes", ToolbarTests.PreferencesAndRoutes), ("Application navigation resolves authorised project and book context", ApplicationNavigationTests.ContextAndPermissions), ("Writing pair shares canonical follow infrastructure", WritingPairSharesCanonicalFollowInfrastructure), + ("Writing Context and Intent resolve native sessions, preserve decisions and reuse bounded chronological data", () => WritingIntegrationTests.Run().GetAwaiter().GetResult()), ("Writing Context Plot Lines preserves canonical associations, developments and book access", () => WritingContextPlotLinesTests.Run().GetAwaiter().GetResult()), ("Writing workspace presence scopes browser windows", WritingWorkspacePresenceScopesBrowserWindows), ("Writing workspace client uses session window identity and stable names", WritingWorkspaceClientUsesSessionIdentityAndStableNames), diff --git a/PlotLine.Tests/StoryPointTests.cs b/PlotLine.Tests/StoryPointTests.cs index 0b33bd72..84b75597 100644 --- a/PlotLine.Tests/StoryPointTests.cs +++ b/PlotLine.Tests/StoryPointTests.cs @@ -120,7 +120,7 @@ internal static class StoryPointTests private static T Proxy(Func invoke) where T : class { var proxy = DispatchProxy.Create(); ((StoryPointProxy)(object)proxy).Handler = invoke; return proxy; } - private static StoryPointInputs Fixture() => new() + internal static StoryPointInputs Fixture() => new() { Timeline = new TimelineData { Project = new Project { ProjectID = 1 }, Books = [new Book { BookID = 2, BookNumber = 2, SortOrder = 2, BookTitle = "Voyage" }, new Book { BookID = 9, BookNumber = 1, SortOrder = 1, BookTitle = "Departure" }], diff --git a/PlotLine.Tests/WritingIntegrationTests.cs b/PlotLine.Tests/WritingIntegrationTests.cs new file mode 100644 index 00000000..a01b78c6 --- /dev/null +++ b/PlotLine.Tests/WritingIntegrationTests.cs @@ -0,0 +1,133 @@ +using System.Diagnostics; +using System.Reflection; +using System.Security.Claims; +using System.Text.Json; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging.Abstractions; +using PlotDirector.Companion.Protocol; +using PlotLine.Controllers; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; +using PlotLine.Services.NativeCompanion; +using PlotLine.ViewModels; + +internal static class WritingIntegrationTests +{ + private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);} + private static T Stub(Func? handler=null) where T:class + =>NativeWorkflowTests.Proxy(handler??((method,args)=>Default(typeof(T).GetMethods().First(m=>m.Name==method).ReturnType))); + private static object? Default(Type type) + { + if(type==typeof(Task))return Task.CompletedTask; + if(type.IsGenericType&&type.GetGenericTypeDefinition()==typeof(Task<>)) + { + var item=type.GenericTypeArguments[0]; + object? value=item.IsGenericType&&item.GetGenericTypeDefinition()==typeof(IReadOnlyList<>)?Array.CreateInstance(item.GenericTypeArguments[0],0):item.GetConstructor(Type.EmptyTypes)!=null||item.IsValueType?Activator.CreateInstance(item):null; + return typeof(Task).GetMethod(nameof(Task.FromResult))!.MakeGenericMethod(item).Invoke(null,[value]); + } + return type.IsValueType?Activator.CreateInstance(type):null; + } + public static async Task Run() + { + await ReadOnlyScene(); + await ResolutionAndIntent(); + await ChronologyAndReuse(); + } + private static async Task ReadOnlyScene() + { + var allowed=true;var edits=0; + var project=new Project{ProjectID=1};var book=new Book{BookID=2,ProjectID=1};var chapter=new Chapter{ChapterID=2,BookID=2}; + var source=new Scene{SceneID=20,ChapterID=2,ScenePurposeNotes="Author purpose — preserve verbatim",SceneOutcomeNotes="Author outcome"}; + var projects=Stub((n,a)=>n=="GetForUserAsync"?Task.FromResult(allowed&&Equals(a![1],7)?project:null):throw new Exception("Unscoped project access")); + var scene=new SceneService(projects,Stub((n,a)=>Task.FromResult(book)),Stub((n,a)=>Task.FromResult(chapter)), + Stub((n,a)=>n=="GetAsync"?Task.FromResult(source):throw new Exception("Unexpected scene write")),Stub(), + Stub(),Stub(),Stub(),Stub(),Stub(),Stub(),Stub(), + Stub((n,a)=>throw new Exception("No analysis entitlement check needed for saved reads")),Stub((n,a)=>{edits++;throw new Exception("Read must not write activity");}), + Stub((n,a)=>throw new Exception("No editor storage traversal")),Stub((n,a)=>throw new Exception("No legacy per-entity state traversal")), + Stub((n,a)=>throw new Exception("No manuscript statistics recomputation")),Stub((n,a)=>7)); + var model=await scene.GetWritingContextAsync(20); + Check(model?.ScenePurposeNotes==source.ScenePurposeNotes&&model.SceneOutcomeNotes==source.SceneOutcomeNotes&&edits==0,"Read-only scene hydration preserves author intent without editing, analysis or manuscript recomputation"); + allowed=false;Check(await scene.GetWritingContextAsync(20)==null,"Read-only scene hydration rejects another user's project before loading workspace data"); + } + + private static (SceneEditViewModel Scene,StoryPointViewModel Narrative) Data() + { + var input=StoryPointTests.Fixture();var point=StoryPointContextService.Compose(input,20)!; + var scene=new SceneEditViewModel{SceneID=20,ChapterID=2,POVCharacterID=1,StartDateTime=point.Scene.StartDateTime, + Project=input.Timeline.Project,Book=point.Book,Chapter=point.Chapter,SceneTitle="Current saved scene",ScenePurposeNotes="My original scene purpose",SceneOutcomeNotes="My original outcome"}; + return (scene,new(){Project=input.Timeline.Project!,Books=input.Timeline.Books,Chapters=input.Timeline.Chapters,Scenes=StoryStateService.OrderScenes(input.Timeline).ToArray(),Snapshot=point}); + } + private static async Task ChronologyAndReuse() + { + var (scene,narrative)=Data();var reads=0;var projections=0;var legacy=0; + var scenes=Stub((n,a)=>{if(n=="GetWritingContextAsync")reads++;else if(n=="GetEditAsync")legacy++;else throw new Exception(n);return Task.FromResult(scene);}); + var points=Stub((n,a)=>{projections++;return Task.FromResult(narrative);}); + var access=Stub((n,a)=>Task.FromResult(true)); + var service=new StoryContextService(scenes,points,access); + var first=await service.GetForSceneAsync(20,1,2,forWriting:true);await service.GetForSceneAsync(20,1,2,forWriting:true); + Check(reads==1&&projections==1&&legacy==0,"Repeated writing reads share request-scoped scene and chronological projection tasks"); + Check(first!.Narrative!.Snapshot!.ViewpointKnowledge.Single().Description=="The gate code"&&first.Narrative.Snapshot.ViewpointKnowledge.Single().KnowledgeStateName=="Knows","Context retains earlier verified viewpoint knowledge and excludes future transitions"); + Check(first.Narrative.Snapshot.Characters.Single(c=>c.Appearance.CharacterID==2).Knowledge.Count==0,"Another character's future secret is not exposed as current knowledge"); + Check(first.Narrative.Snapshot.Relationships.Single().CurrentStateName=="Trusted"&&first.Narrative.Snapshot.Relationships.All(r=>r.History.All(e=>e.SceneID!=1)),"Relationship reference stops at the current narrative position"); + Check(await service.GetForSceneAsync(20,99,2,forWriting:true)==null&&await service.GetForSceneAsync(20,1,9,forWriting:true)==null,"Context rejects mismatched project and book scopes"); + await service.GetForSceneAsync(20,1,2); + Check(legacy==1,"Existing Timeline and inspector callers retain their full editing model path"); + var intentOnly=new StoryContextService(scenes,Stub((n,a)=>throw new Exception("Intent must not load knowledge histories")),access); + Check((await intentOnly.GetForSceneAsync(20,1,2,forWriting:true,includeNarrative:false))?.Scene?.ScenePurposeNotes==scene.ScenePurposeNotes,"Intent retrieves saved decisions without computing narrative histories"); + var input=StoryPointTests.Fixture();input.Timeline.Scenes.Single(s=>s.SceneID==1).StartDateTime=scene.StartDateTime!.Value.AddHours(-1); + var snapshot=StoryPointContextService.Compose(input,20)!; + var framed=new StoryContextViewModel{Scene=scene,Position=new(1,2,2,20),Narrative=new(){Project=input.Timeline.Project!,Chapters=input.Timeline.Chapters,Scenes=StoryStateService.OrderScenes(input.Timeline).ToArray(),Snapshot=snapshot}}; + Check(WritingContextRelevance.Nearby(framed).All(s=>s.SceneID!=1),"A future narrative scene cannot leak into timeline context even when its story date is earlier"); + Check(WritingContextRelevance.Threads(framed).Select(t=>t.PlotThreadID).SequenceEqual([4]),"Initial thread context ranks current relevant unresolved threads rather than dumping every novel thread"); + input.Timeline.Scenes.Single(s=>s.SceneID==20).POVCharacterID=null; + Check(StoryPointContextService.Compose(input,20)!.ViewpointKnowledge.Count==0,"Missing viewpoint does not invent a knowledge perspective"); + var options=WritingContextRelevance.SceneOptions(narrative,2,20); + Check(options.Select(o=>o.Value).SequenceEqual(["20","1"]),"Scene navigation follows manuscript order rather than numeric IDs or other books"); + var scale=new StoryPointViewModel{Project=new(){ProjectID=1},Chapters=Enumerable.Range(0,48).Select(i=>new Chapter{ChapterID=i+1,BookID=2}).ToArray(),Scenes=Enumerable.Range(0,4800).Select(i=>new Scene{SceneID=i+1,ChapterID=i/100+1}).ToArray()}; + var watch=Stopwatch.StartNew();var list=WritingContextRelevance.SceneOptions(scale,2,2400);watch.Stop(); + Check(list.Count==4800&&list.Count(x=>x.Selected)==1,"Large-manuscript navigation is one bounded in-memory projection with no per-scene database queries"); + Console.WriteLine($"MEASURE writing navigation projection: 48 chapters/4800 scenes, {watch.Elapsed.TotalMilliseconds:F1}ms, no SQL or Word."); + } + + private static async Task ResolutionAndIntent() + { + var (scene,narrative)=Data();var instance=Guid.NewGuid();var session=Guid.NewGuid();var manuscript=Guid.NewGuid();long sequence=0,revision=5; + var presence=new NativePresenceStore(TimeProvider.System);var allowed=true;var mapping=true;var reads=0;Action? onRead=null; + void Beat(int? current=20,bool saved=true,long paragraph=3)=>presence.Put(7,"fixture",DateTimeOffset.UtcNow.AddMinutes(5),instance,session,new(){BookId=2,ManuscriptId=manuscript,Revision=revision,Sequence=++sequence,ChapterId=2,SceneId=current,WordAvailable=true,WordSaved=saved,CanChapterSync=true,ChapterSyncSupported=true,CursorStart=100,ParagraphRevision=paragraph}); + var structure=new WordCompanionBookStructureResponse{BookId=2,Chapters=[new(){ChapterId=2,Scenes=[new(){SceneId=99},new(){SceneId=20}]}]}; + var companion=Stub((n,a)=>Task.FromResult(allowed?structure:null)); + var story=Stub((n,a)=>{reads++;onRead?.Invoke();return Task.FromResult(new(){Position=new(1,2,2,20),Project=scene.Project,Book=scene.Book,Chapter=scene.Chapter,Scene=scene,Narrative=(bool)a![4]!?narrative:null});}); + var goal=new ChapterGoal{GoalSummary="An author's objective",EmotionalGoal="Doubt → commitment",MustInclude="An unresolved promise",ReaderTakeaway="A possibility, not canon"}; + var workflow=new ChapterWorkflowViewModel{Project=scene.Project!,Book=scene.Book!,Chapter=scene.Chapter!,Goal=goal}; + var writer=Stub((n,a)=>n=="GetChapterWorkflowAsync"?Task.FromResult(workflow):throw new Exception("Intent read attempted a write")); + var controller=new WritingController(story,null!,null!,writer,NullLogger.Instance,companion,presence,Stub((n,a)=>Task.FromResult(allowed)), + Stub((n,a)=>n=="Position"?Task.FromResult(mapping?new(){Revision=3,ChapterID=2,SceneID=presence.Read(7,2).Single().Position.SceneId}:null):throw new Exception("Context must not synchronise or reconcile"))) + {ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}}; + Beat(); + var page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!; + Check(page.SceneID==20&&page.Display!.HasScene&&page.Display.FollowStatus=="Following Word","Native launch opens its exact verified scene rather than the book's first scene"); + var before=JsonSerializer.Serialize(new{scene.ScenePurposeNotes,scene.SceneOutcomeNotes,goal}); + var intent=(WritingIntentPageViewModel)((ViewResult)await controller.Intent(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!; + Check(intent.SceneID==20&&intent.Display!.ChapterWorkflow!.Goal==goal&&intent.Display.Context!.Scene!.ScenePurposeNotes==scene.ScenePurposeNotes,"Native Intent retrieves the selected scene's existing purpose and chapter objectives"); + Check(JsonSerializer.Serialize(new{scene.ScenePurposeNotes,scene.SceneOutcomeNotes,goal})==before,"Opening Context and Intent preserves all author-entered decisions verbatim"); + Beat(saved:false);var oldReads=reads; + page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!; + Check(!page.Display!.HasScene&&reads==oldReads,"Unsaved native mapping waits without loading an unrelated saved scene"); + Beat();mapping=false;page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!; + Check(!page.Display!.HasScene&&reads==oldReads,"A stale database checkpoint cannot launch a scene merely claimed by the last heartbeat");mapping=true; + Beat(paragraph:0);page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!; + Check(!page.Display!.HasScene&&reads==oldReads,"Chapter-capable sessions without accepted position evidence cannot launch claimed scene IDs"); + Beat(current:null);intent=(WritingIntentPageViewModel)((ViewResult)await controller.Intent(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!; + Check(intent.Display!.IsChapterOnly&&intent.Display.ChapterWorkflow!.Goal==goal,"A verified chapter with no mapped scene can show its own saved chapter intent"); + Beat();onRead=()=>{revision++;Beat(current:99);}; + page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!; + Check(!page.Display!.HasScene,"A Word cursor/revision change during server loading cannot render the earlier cursor as current"); + Beat();Check(await controller.ContextScene(1,2,2,20,instance,session) is ConflictObjectResult,"Native partial requests reject mappings that change during data loading");onRead=null; + Beat();allowed=false; + Check(await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session) is ForbidResult,"Native Context launch authorises the book before resolving or displaying its scene");allowed=true; + Check(await controller.Intent(1,2,null,null,null,instanceId:Guid.NewGuid(),sessionId:session) is ViewResult missing&&((WritingIntentPageViewModel)missing.Model!).Display!.HasScene==false,"Exact document selection cannot fall back to another connected Word instance"); + Check(await controller.Context(1,2,null,null,null,instanceId:instance) is BadRequestObjectResult,"Incomplete native session identity is rejected"); + } +} diff --git a/PlotLine/Controllers/NativeCompanionWorkflowController.cs b/PlotLine/Controllers/NativeCompanionWorkflowController.cs index d42b8f1b..85dccb12 100644 --- a/PlotLine/Controllers/NativeCompanionWorkflowController.cs +++ b/PlotLine/Controllers/NativeCompanionWorkflowController.cs @@ -27,7 +27,7 @@ public sealed class NativeCompanionWorkflowController(IWordCompanionRepository a var book=await books.GetAsync(bookId);if(book==null)return NotFound(); var parent=sceneId.HasValue?structure.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==sceneId)):chapterId.HasValue?structure.Chapters.FirstOrDefault(c=>c.ChapterId==chapterId):null; if((sceneId.HasValue||chapterId.HasValue)&&(parent==null||(chapterId.HasValue&&parent.ChapterId!=chapterId)))return NotFound(); - var saved=sceneId.HasValue?await context.GetForSceneAsync(sceneId.Value,book.ProjectID,bookId):null; + var saved=sceneId.HasValue?await context.GetForSceneAsync(sceneId.Value,book.ProjectID,bookId,forWriting:true,includeNarrative:false):null; if(sceneId.HasValue&&saved?.Scene==null)return NotFound(); var workflow=parent!=null?await writer.GetChapterWorkflowAsync(parent.ChapterId):null; if(workflow!=null&&(workflow.Book.BookID!=bookId||workflow.Project.ProjectID!=book.ProjectID))return Forbid(); diff --git a/PlotLine/Controllers/NativeWorkspaceController.cs b/PlotLine/Controllers/NativeWorkspaceController.cs index cd457921..c965a004 100644 --- a/PlotLine/Controllers/NativeWorkspaceController.cs +++ b/PlotLine/Controllers/NativeWorkspaceController.cs @@ -37,11 +37,12 @@ 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(); if(paragraphs!=null)foreach(var book in leases.Where(l=>l.Position.WordAvailable&&allowed.Contains(l.Position.BookId)&&l.Position.BookId>0).Select(l=>l.Position.BookId).Distinct())snapshots[book]=await paragraphs.Status(Author,book); - return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.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, + return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.Revision,l.Position.ManuscriptId,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,l.Position.ChapterIssue,l.Position.CanChapterSync,chapterProgress=presence.ChapterProgress(Author,l.Position.BookId,l.Instance,l.Session,l.Position.Revision),l.Position.CanParagraphSync,l.Position.CaptureRequestId,l.Position.CaptureProgress, paragraphTransfer=capture?.ParagraphTransferStatus(Author,l.Position.BookId,l.Instance,l.Session), + positionVerified=l.Position.WordSaved==true&&(!(l.Position.CanChapterSync||l.Position.CanParagraphSync)||l.Position.ParagraphRevision>0)&&l.Position.ChapterId.HasValue, snapshotRevision=snapshots.GetValueOrDefault(l.Position.BookId)?.Revision, mappingCurrent=snapshots.GetValueOrDefault(l.Position.BookId) is {} saved&&saved.ManuscriptId==l.Position.ManuscriptId&&saved.SessionId==l.Session&&saved.WordRevision==l.Position.Revision, - positionMessage=l.Position.WordSaved==false?"Save Word, then synchronise to refresh its scene mapping":l.Position.SceneId.HasValue?null:l.Position.CanChapterSync?(l.Position.ChapterIssue=="needs_review"?"Chapter reading needs review or retry; accepted mappings are preserved":l.Position.ChapterId.HasValue?"Current paragraph is checked but has no scene assignment; move into scene prose":"Checking the current chapter for this Word session; saved scenes remain available"):snapshots.GetValueOrDefault(l.Position.BookId) is {} snapshot?(snapshot.ManuscriptId!=l.Position.ManuscriptId?"This Word document does not match the book's saved manuscript identity":snapshot.SessionId!=l.Session||snapshot.WordRevision!=l.Position.Revision?"Word reopened or changed; synchronise from Word to verify this session's paragraph positions":snapshot.Paused?"Scene mapping is unresolved; synchronisation is paused while existing book processing finishes":"Current paragraph has no verified scene assignment") : "Synchronise from Word to establish a verified paragraph mapping", + positionMessage=l.Position.WordSaved==false?"Save Word before verifying its scene mapping":l.Position.SceneId.HasValue?null:l.Position.CanChapterSync?(l.Position.ChapterIssue=="needs_review"?"Chapter reading needs review or retry; accepted mappings are preserved":l.Position.ChapterId.HasValue?"Current paragraph is checked but has no scene assignment; move into scene prose":"Checking the current chapter for this Word session; saved scenes remain available"):snapshots.GetValueOrDefault(l.Position.BookId) is {} snapshot?(snapshot.ManuscriptId!=l.Position.ManuscriptId?"This Word document does not match the book's saved manuscript identity":snapshot.SessionId!=l.Session||snapshot.WordRevision!=l.Position.Revision?"Word reopened or changed; synchronise from Word to verify this session's paragraph positions":snapshot.Paused?"Scene mapping is unresolved; synchronisation is paused while existing book processing finishes":"Current paragraph has no verified scene assignment") : "Synchronise from Word to establish a verified paragraph mapping", updated=l.Updated,expires=l.Updated.AddSeconds(45)})); } [HttpGet("reviews/{id:guid}")] diff --git a/PlotLine/Controllers/WritingController.cs b/PlotLine/Controllers/WritingController.cs index d42c267e..92eb3e01 100644 --- a/PlotLine/Controllers/WritingController.cs +++ b/PlotLine/Controllers/WritingController.cs @@ -18,7 +18,7 @@ public sealed class WritingController( IRelationshipMapService relationshipMap, IFloorPlanService floorPlans, IWriterWorkspaceService writerWorkspace, - ILogger logger,IStoryCalendarService? calendar=null,IWordCompanionRepository? companion=null) : Controller + ILogger logger,IWordCompanionRepository? companion=null,NativePresenceStore? nativePresence=null,IProjectAccessService? projectAccess=null,IChapterSyncRepository? chapterPositions=null) : Controller { [HttpGet("Context")] public async Task Context(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false,bool embedded=false,Guid? instanceId=null,Guid? sessionId=null) @@ -32,7 +32,21 @@ public sealed class WritingController( sceneId, documentGuid.HasValue); - if(!sceneId.HasValue&&bookId.HasValue&&companion!=null) { + if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest("Choose one complete Word document session."); + var nativeLaunch=!pinned&&(instanceId.HasValue||sessionId.HasValue); + NativeWritingTarget? target=null; + if(nativeLaunch) + { + if(!bookId.HasValue||companion==null)return BadRequest("A linked book is required."); + var structure=await companion.GetBookStructureAsync(bookId.Value,WritingUser); + if(structure==null)return Forbid(); + target=await NativeTarget(bookId,instanceId,sessionId); + var chapter=structure.Chapters.FirstOrDefault(c=>c.ChapterId==target?.ChapterId); + if(target?.SceneId is int current&&chapter?.Scenes.Any(x=>x.SceneId==current)!=true)target=null; + if(target?.ChapterId!=null&&chapter==null)target=null; + chapterId=target?.ChapterId;sceneId=target?.SceneId; + } + if(!nativeLaunch&&!sceneId.HasValue&&bookId.HasValue&&companion!=null) { var structure=await companion.GetBookStructureAsync(bookId.Value,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); sceneId=structure?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault()?.SceneId; } @@ -40,11 +54,17 @@ public sealed class WritingController( ? await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual context") : WaitingContextDisplay(projectId, bookId, documentGuid); + if(nativeLaunch&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId))) + { + sceneId=null;chapterId=null; + display=WaitingContextDisplay(projectId,bookId,documentGuid); + } + if(nativeLaunch&&display!=null)display.FollowStatus=target!=null&&sceneId.HasValue?"Following Word":"Word mapping pending · choose a saved scene to browse manually"; if(pinned&&display!=null){display.FollowStatus="Saved PlotDirector snapshot";if(!sceneId.HasValue){display.EmptyTitle="No saved scene selected";display.EmptyMessage="This is a scoped saved-data view, not live Word following. Select a saved scene in PlotDirector; local markers or AI suggestions do not create saved context.";}} var model = new WritingContextPageViewModel { - ProjectID = projectId, - BookID = bookId, + ProjectID = display?.Context?.Position.ProjectId ?? projectId, + BookID = display?.Context?.Position.BookId ?? bookId, ChapterID = chapterId, SceneID = sceneId, DocumentGuid = documentGuid, @@ -66,7 +86,21 @@ public sealed class WritingController( sceneId, documentGuid.HasValue); - if(!sceneId.HasValue&&!chapterId.HasValue&&bookId.HasValue&&companion!=null) { + if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest("Choose one complete Word document session."); + var nativeLaunch=!pinned&&(instanceId.HasValue||sessionId.HasValue); + NativeWritingTarget? target=null; + if(nativeLaunch) + { + if(!bookId.HasValue||companion==null)return BadRequest("A linked book is required."); + var structure=await companion.GetBookStructureAsync(bookId.Value,WritingUser); + if(structure==null)return Forbid(); + target=await NativeTarget(bookId,instanceId,sessionId); + var chapter=structure.Chapters.FirstOrDefault(c=>c.ChapterId==target?.ChapterId); + if(target?.SceneId is int current&&chapter?.Scenes.Any(x=>x.SceneId==current)!=true)target=null; + if(target?.ChapterId!=null&&chapter==null)target=null; + chapterId=target?.ChapterId;sceneId=target?.SceneId; + } + if(!nativeLaunch&&!sceneId.HasValue&&!chapterId.HasValue&&bookId.HasValue&&companion!=null) { var structure=await companion.GetBookStructureAsync(bookId.Value,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); var first=structure?.Chapters.FirstOrDefault(c=>c.Scenes.Count>0)??structure?.Chapters.FirstOrDefault(); chapterId=first?.ChapterId;sceneId=first?.Scenes.FirstOrDefault()?.SceneId; @@ -75,11 +109,17 @@ public sealed class WritingController( ? await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual intent") : WaitingIntentDisplay(projectId, bookId, documentGuid); + if(nativeLaunch&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId))) + { + sceneId=null;chapterId=null; + display=WaitingIntentDisplay(projectId,bookId,documentGuid); + } + if(nativeLaunch&&display!=null)display.FollowStatus=target!=null&&(sceneId.HasValue||chapterId.HasValue)?"Following Word":"Word mapping pending · choose a saved scene to browse manually"; if(pinned&&display!=null){display.FollowStatus="Saved PlotDirector snapshot";if(!sceneId.HasValue&&!chapterId.HasValue){display.EmptyTitle="No saved writing objective selected";display.EmptyMessage="Choose a saved chapter or scene in PlotDirector. Set its goal/purpose explicitly; this view does not invent or automatically save intent.";}} var model = new WritingIntentPageViewModel { - ProjectID = projectId, - BookID = bookId, + ProjectID = display?.Context?.Position.ProjectId ?? display?.ChapterWorkflow?.Project.ProjectID ?? projectId, + BookID = display?.Context?.Position.BookId ?? display?.ChapterWorkflow?.Book.BookID ?? bookId, ChapterID = chapterId, SceneID = sceneId, DocumentGuid = documentGuid, @@ -90,8 +130,12 @@ public sealed class WritingController( } [HttpGet("Context/Scene")] - public async Task ContextScene(int? projectId, int? bookId, int? chapterId, int? sceneId) + public async Task ContextScene(int? projectId, int? bookId, int? chapterId, int? sceneId,Guid? instanceId=null,Guid? sessionId=null) { + if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest(); + var nativeRequest=instanceId.HasValue||sessionId.HasValue; + var target=nativeRequest?await NativeTarget(bookId,instanceId,sessionId):null; + if(nativeRequest&&(target==null||target.SceneId!=sceneId||(chapterId.HasValue&&target.ChapterId!=chapterId)))return Conflict(new{message="Word position changed or is awaiting verification."}); if (!sceneId.HasValue) { logger.LogWarning("Writing Context partial requested without SceneID. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID}", projectId, bookId, chapterId); @@ -99,6 +143,7 @@ public sealed class WritingController( } var model = await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene"); + if(nativeRequest&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId)))return Conflict(new{message="Word position changed while context was loading."}); if (model?.HasScene == true) { return PartialView("~/Views/Writing/_WritingContextContent.cshtml", model); @@ -109,8 +154,12 @@ public sealed class WritingController( } [HttpGet("Intent/Scene")] - public async Task IntentScene(int? projectId, int? bookId, int? chapterId, int? sceneId) + public async Task IntentScene(int? projectId, int? bookId, int? chapterId, int? sceneId,Guid? instanceId=null,Guid? sessionId=null) { + if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest(); + var nativeRequest=instanceId.HasValue||sessionId.HasValue; + var target=nativeRequest?await NativeTarget(bookId,instanceId,sessionId):null; + if(nativeRequest&&(target==null||target.SceneId!=sceneId||(chapterId.HasValue&&target.ChapterId!=chapterId)))return Conflict(new{message="Word position changed or is awaiting verification."}); if (!sceneId.HasValue && !chapterId.HasValue) { logger.LogWarning("Writing Intent partial requested without ChapterID or SceneID. ProjectID={ProjectID} BookID={BookID}", projectId, bookId); @@ -118,6 +167,7 @@ public sealed class WritingController( } var model = await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene"); + if(nativeRequest&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId)))return Conflict(new{message="Word position changed while context was loading."}); if (model is not null && (model.HasScene || model.HasChapter)) { return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", model); @@ -127,6 +177,26 @@ public sealed class WritingController( return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", MissingIntentDisplay(projectId, bookId, chapterId, sceneId)); } + private int WritingUser=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); + private sealed record NativeWritingTarget(Guid Instance,Guid Session,Guid Manuscript,long Revision,int? ChapterId,int? SceneId,long AcceptedRevision); + private static bool InvalidNativeSelection(Guid? instance,Guid? session)=>instance.HasValue!=session.HasValue||instance==Guid.Empty||session==Guid.Empty; + private async Task NativeTarget(int? book,Guid? instance,Guid? session) + { + if(!book.HasValue||!instance.HasValue||!session.HasValue||nativePresence==null)return null; + var lease=nativePresence.Read(WritingUser,book.Value).SingleOrDefault(l=>l.Instance==instance&&l.Session==session&&l.Position.WordAvailable&&l.Position.WordSaved==true&&(!(l.Position.CanChapterSync||l.Position.CanParagraphSync)||l.Position.ParagraphRevision>0)); + if(lease==null)return null; + var acceptedRevision=lease.Position.ParagraphRevision; + if(lease.Position.CanChapterSync) + { + if(chapterPositions==null||lease.Position.CursorStart is not int cursor)return null; + var accepted=await chapterPositions.Position(WritingUser,book.Value,lease.Position.ManuscriptId,lease.Session,lease.Position.Revision,cursor); + if(accepted?.ChapterID!=lease.Position.ChapterId||accepted?.SceneID!=lease.Position.SceneId||accepted==null||accepted.Revision<=0)return null; + acceptedRevision=accepted.Revision; + } + return new(lease.Instance,lease.Session,lease.Position.ManuscriptId,lease.Position.Revision,lease.Position.ChapterId,lease.Position.SceneId,acceptedRevision); + } + private static bool SameNativeTarget(NativeWritingTarget? before,NativeWritingTarget? after)=>before!=null&&before==after; + private async Task BuildDisplayAsync(int? projectId, int? bookId, int? chapterId, int? sceneId, string followStatus) { if (!sceneId.HasValue) @@ -134,21 +204,26 @@ public sealed class WritingController( return new WritingContextDisplayViewModel { FollowStatus = followStatus }; } - var context = await storyContext.GetForSceneAsync(sceneId.Value, projectId, bookId); - if (context?.Scene is null) + var context = await storyContext.GetForSceneAsync(sceneId.Value, projectId, bookId,forWriting:true); + if (context?.Scene is null||chapterId.HasValue&&context.Position.ChapterId!=chapterId) { return null; } var position = context.Position; - var relationships = await relationshipMap.GetAsync(position, null, true); + var point=context.Narrative?.Snapshot; + var relationships=point!=null?new RelationshipMapViewModel{Relationships=point.Relationships}:await relationshipMap.GetAsync(position,null,true); + if(point!=null) + { + if(context.Scene.POVCharacterID is int pov)context.Scene.CharacterOptions=[new SelectListItem(point.PovName??"Unknown POV",pov.ToString())]; + if(point.Location is {} place)context.Scene.LocationOptions=[new SelectListItem(place.LocationPath.Length>0?place.LocationPath:place.LocationName,place.LocationID.ToString())]; + } var floorPlan = context.Scene.FloorPlanID.HasValue ? await floorPlans.GetEditorAsync(context.Scene.FloorPlanID.Value) : null; - var nearby = calendar is not null && context.Scene.StartDateTime.HasValue - ? (await calendar.GetAsync(position.ProjectId,position.BookId,null,DateOnly.FromDateTime(context.Scene.StartDateTime.Value)))?.DatedScenes.Where(x=>x.SceneID!=sceneId && x.StartDateTime.HasValue && Math.Abs((x.StartDateTime.Value-context.Scene.StartDateTime.Value).TotalDays)<=3).OrderBy(x=>x.StartDateTime).Take(5).ToArray() ?? [] - : []; + if(floorPlan!=null&&floorPlan.FloorPlan.ProjectID!=position.ProjectId)floorPlan=null; + var nearby=WritingContextRelevance.Nearby(context); return new WritingContextDisplayViewModel { NearbyScenes = nearby, @@ -156,7 +231,7 @@ public sealed class WritingController( RelationshipMap = relationships, FloorPlan = floorPlan, FollowStatus = followStatus, - SceneOptions = await ContextSceneOptions(context.Scene) + SceneOptions = await ContextSceneOptions(context.Scene,context.Narrative) }; } @@ -165,8 +240,8 @@ public sealed class WritingController( StoryContextViewModel? context = null; if (sceneId.HasValue) { - context = await storyContext.GetForSceneAsync(sceneId.Value, projectId, bookId); - if (context?.Scene is null) + context = await storyContext.GetForSceneAsync(sceneId.Value, projectId, bookId,forWriting:true,includeNarrative:false); + if (context?.Scene is null||chapterId.HasValue&&context.Position.ChapterId!=chapterId) { return null; } @@ -179,6 +254,7 @@ public sealed class WritingController( if (chapterWorkflow is not null) { + if(projectAccess==null||!await projectAccess.CanAccessProjectAsync(chapterWorkflow.Project.ProjectID))return null; if (projectId.HasValue && chapterWorkflow.Project.ProjectID != projectId.Value) { return null; @@ -241,8 +317,9 @@ public sealed class WritingController( return data.Project==null?NotFound():PartialView("_WritingContextMetrics",WritingContextMetrics.Build(data,recorded)); } - private async Task> ContextSceneOptions(SceneEditViewModel scene) + private async Task> ContextSceneOptions(SceneEditViewModel scene,StoryPointViewModel? narrative=null) { + if(narrative!=null)return WritingContextRelevance.SceneOptions(narrative,scene.Book!.BookID,scene.SceneID); if(companion==null)return BuildSceneOptions(scene); var structure=await companion.GetBookStructureAsync(scene.Book!.BookID,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); return structure?.Chapters.SelectMany(c=>c.Scenes.Select(s=>new SelectListItem($"{c.Title} · {s.Title}",s.SceneId.ToString(),s.SceneId==scene.SceneID))).ToList()??[]; diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index bd47d8a2..e49eada9 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -126,6 +126,7 @@ public interface ISceneService { Task GetCreateAsync(int chapterId); Task GetEditAsync(int sceneId); + Task GetWritingContextAsync(int sceneId); Task SaveAsync(SceneEditViewModel model); Task UpdatePovCharacterAsync(int sceneId, int? povCharacterId, string source = "Author", decimal? confidence = null, string? evidence = null, string? suggestedName = null, bool overwriteAuthor = false); Task ArchiveAsync(int sceneId); @@ -155,11 +156,12 @@ public interface IStoryStateService public interface IStoryContextService { Task GetAsync(StoryPosition position); - Task GetForSceneAsync(int sceneId, int? projectId = null, int? bookId = null); + Task GetForSceneAsync(int sceneId, int? projectId = null, int? bookId = null, bool forWriting = false, bool includeNarrative = true); } public sealed class StoryContextViewModel { + public StoryPointViewModel? Narrative {get;init;} public StoryPosition Position { get; init; } = new(0); public Project? Project { get; init; } public Book? Book { get; init; } @@ -1952,7 +1954,9 @@ public sealed class SceneService( }, lookupData)); } - public async Task GetEditAsync(int sceneId) + public Task GetEditAsync(int sceneId)=>LoadSceneAsync(sceneId,false); + public Task GetWritingContextAsync(int sceneId)=>LoadSceneAsync(sceneId,true); + private async Task LoadSceneAsync(int sceneId,bool writing) { var scene = await scenes.GetAsync(sceneId); if (scene is null) @@ -1960,15 +1964,15 @@ public sealed class SceneService( return null; } - var context = await GetContextAsync(scene.ChapterID); + var context = await GetContextAsync(scene.ChapterID,writing); if (context is null) { return null; } var lookupData = await lookups.GetAllAsync(); - var textStatistics = await manuscriptTextStatistics.GetBySceneAsync(sceneId); - return await PopulateWorkspaceDataAsync(PopulateLists(new SceneEditViewModel + var textStatistics = writing?null:await manuscriptTextStatistics.GetBySceneAsync(sceneId); + var model=PopulateLists(new SceneEditViewModel { SceneID = scene.SceneID, ChapterID = scene.ChapterID, @@ -2006,7 +2010,8 @@ public sealed class SceneService( Chapter = context.Value.Chapter, Book = context.Value.Book, Project = context.Value.Project - }, lookupData)); + }, lookupData); + return writing?await PopulateWritingDataAsync(model):await PopulateWorkspaceDataAsync(model); } public async Task SaveAsync(SceneEditViewModel model) @@ -2091,11 +2096,13 @@ public sealed class SceneService( public Task MoveRelativeAsync(int sceneId, int anchorSceneId, string position) => scenes.MoveRelativeAsync(sceneId, anchorSceneId, position); - private async Task<(Project Project, Book Book, Chapter Chapter)?> GetContextAsync(int chapterId) + private async Task<(Project Project, Book Book, Chapter Chapter)?> GetContextAsync(int chapterId,bool writing=false) { var chapter = await chapters.GetAsync(chapterId); var book = chapter is null ? null : await books.GetAsync(chapter.BookID); - var project = book is null ? null : await projects.GetAsync(book.ProjectID); + var project = book is null ? null : writing + ? currentUser.UserId is int user?await projects.GetForUserAsync(book.ProjectID,user):null + : await projects.GetAsync(book.ProjectID); return chapter is null || book is null || project is null ? null : (project, book, chapter); } @@ -2109,6 +2116,32 @@ public sealed class SceneService( return model; } + private async Task PopulateWritingDataAsync(SceneEditViewModel model) + { + // Read only existing scene records. Do not load editing choices, suggestions, + // storage quotas, or the legacy per-entity whole-project state traversal. + var threads=plots.ListThreadEventsBySceneAsync(model.SceneID); + var events=assets.ListEventsBySceneAsync(model.SceneID); + var custody=assets.ListCustodyBySceneAsync(model.SceneID); + var places=locations.ListSceneAssetLocationsAsync(model.SceneID); + var people=characters.ListSceneCharactersAsync(model.SceneID); + var attributes=characters.ListAttributeEventsBySceneAsync(model.SceneID); + var continuity=warnings.ListBySceneAsync(model.SceneID); + var dependencies=sceneDependencies.ListBySceneAsync(model.SceneID); + var relationships=characters.ListRelationshipEventsBySceneAsync(model.SceneID); + var workflow=writerWorkspace.GetWorkflowAsync(model.SceneID); + var notes=writerWorkspace.ListNotesAsync(model.SceneID); + var checklist=writerWorkspace.ListChecklistItemsAsync(model.SceneID); + await Task.WhenAll(threads,events,custody,places,people,attributes,continuity,dependencies,relationships,workflow,notes,checklist); + model.ThreadEvents=threads.Result;model.AssetEvents=events.Result;model.AssetCustodyEvents=custody.Result; + model.SceneAssetLocations=places.Result;model.SceneCharacters=people.Result;model.CharacterAttributeEvents=attributes.Result; + model.Warnings=continuity.Result;model.RelationshipEvents=relationships.Result.Where(x=>x.EvidenceState=="Verified").ToList(); + model.DependenciesThisSceneNeeds=dependencies.Result.Where(x=>x.TargetSceneID==model.SceneID).ToList(); + model.DependenciesNeedingThisScene=dependencies.Result.Where(x=>x.SourceSceneID==model.SceneID).ToList(); + model.Workflow=workflow.Result;model.Notes=notes.Result;model.ChecklistItems=checklist.Result; + return model; + } + private async Task PopulateWorkspaceDataAsync(SceneEditViewModel model) { if (model.Project is null) @@ -2462,8 +2495,11 @@ public sealed class SceneService( } } -public sealed class StoryContextService(ISceneService scenes) : IStoryContextService +public sealed class StoryContextService(ISceneService scenes,IStoryPointContextService points,IProjectAccessService access) : IStoryContextService { + // Request-scoped memoisation only: no stale cross-request cache of author decisions. + private readonly Dictionary<(int Scene,bool Writing),Task> sceneReads=[]; + private readonly Dictionary> pointReads=[]; public async Task GetAsync(StoryPosition position) { if (!position.IsValid) @@ -2482,16 +2518,18 @@ public sealed class StoryContextService(ISceneService scenes) : IStoryContextSer }; } - public async Task GetForSceneAsync(int sceneId, int? projectId = null, int? bookId = null) + public async Task GetForSceneAsync(int sceneId, int? projectId = null, int? bookId = null,bool forWriting=false,bool includeNarrative=true) { if (sceneId <= 0) { return null; } - var scene = await scenes.GetEditAsync(sceneId); + var key=(sceneId,forWriting); + if(!sceneReads.TryGetValue(key,out var read))sceneReads[key]=read=forWriting?scenes.GetWritingContextAsync(sceneId):scenes.GetEditAsync(sceneId); + var scene=await read; var position = StoryPosition.FromScene(scene); - if (position is null) + if (position is null || scene is null) { return null; } @@ -2506,8 +2544,17 @@ public sealed class StoryContextService(ISceneService scenes) : IStoryContextSer return null; } + if(!forWriting&&!await access.CanAccessProjectAsync(position.ProjectId))return null; + StoryPointViewModel? narrative=null; + if(forWriting&&includeNarrative) + { + if(!pointReads.TryGetValue(sceneId,out var pointRead))pointReads[sceneId]=pointRead=points.GetAsync(position.ProjectId,sceneId); + narrative=await pointRead; + if(narrative?.Snapshot is not {} snapshot||snapshot.ProjectID!=position.ProjectId||snapshot.Book.BookID!=position.BookId||snapshot.Scene.SceneID!=sceneId||snapshot.Chapter.ChapterID!=position.ChapterId||snapshot.Scene.POVCharacterID!=scene.POVCharacterID)return null; + } return new StoryContextViewModel { + Narrative=narrative, Position = position, Project = scene!.Project, Book = scene.Book, diff --git a/PlotLine/Services/IntentAssessmentService.cs b/PlotLine/Services/IntentAssessmentService.cs index b73b397c..32f5b28a 100644 --- a/PlotLine/Services/IntentAssessmentService.cs +++ b/PlotLine/Services/IntentAssessmentService.cs @@ -18,7 +18,7 @@ public sealed class IntentAssessmentService(IStoryContextService context,IWriter public static string Fingerprint(string prose,IEnumerable plan)=>Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes("intent-evidence-v1\n"+JsonSerializer.Serialize(plan)+"\n"+prose))); public async Task Read(int user,int scene) { - var story=await context.GetForSceneAsync(scene,null,null)??throw new UnauthorizedAccessException();var s=story.Scene??throw new UnauthorizedAccessException(); + var story=await context.GetForSceneAsync(scene,null,null,forWriting:true,includeNarrative:false)??throw new UnauthorizedAccessException();var s=story.Scene??throw new UnauthorizedAccessException(); var chapter=await writer.GetChapterWorkflowAsync(story.Position.ChapterId!.Value); var plan=new List();void Add(string key,string? text){if(!string.IsNullOrWhiteSpace(text))plan.Add(new(key,text.Trim()));} Add("purpose",s.ScenePurposeNotes);Add("outcome",s.SceneOutcomeNotes);Add("chapter-goal",chapter?.Goal?.GoalSummary);Add("emotional-goal",chapter?.Goal?.EmotionalGoal);Add("must-include",chapter?.Goal?.MustInclude);Add("reader-takeaway",chapter?.Goal?.ReaderTakeaway); diff --git a/PlotLine/Services/StoryPointContextService.cs b/PlotLine/Services/StoryPointContextService.cs index 5939e1c1..0727b7bf 100644 --- a/PlotLine/Services/StoryPointContextService.cs +++ b/PlotLine/Services/StoryPointContextService.cs @@ -103,6 +103,7 @@ public sealed class StoryPointContextService(IProjectAccessService access, ITime { ProjectID = input.Timeline.Project.ProjectID, Book = book, Chapter = chapter, Scene = scene, Characters = people, PovName = scene.POVCharacterID.HasValue ? characterModels.GetValueOrDefault(scene.POVCharacterID.Value)?.CharacterName ?? scene.POVCharacterName : scene.POVCharacterName, + ViewpointKnowledge = scene.POVCharacterID is int pov && characterModels.ContainsKey(pov) ? knowledge[pov].ToList() : [], Relationships = RelationshipMapService.BuildAtScene(input.Relationships, indexes, sceneId) .Where(x => presentIds.Contains(x.CharacterAID) || presentIds.Contains(x.CharacterBID)).ToList(), Assets = pointAssets, Location = location, PreviousLocationUse = lastLocationScene is null ? null : sources[lastLocationScene.SceneID], diff --git a/PlotLine/Services/WritingContextRelevance.cs b/PlotLine/Services/WritingContextRelevance.cs new file mode 100644 index 00000000..4c1f0948 --- /dev/null +++ b/PlotLine/Services/WritingContextRelevance.cs @@ -0,0 +1,38 @@ +using Microsoft.AspNetCore.Mvc.Rendering; +using PlotLine.ViewModels; + +namespace PlotLine.Services; + +// Presentation of the existing chronological Story Point projection, not another +// knowledge store. Selection never changes author records or generates facts. +public static class WritingContextRelevance +{ + public static IReadOnlyList SceneOptions(StoryPointViewModel narrative,int book,int current) + { + var chapters=narrative.Chapters.Where(c=>c.BookID==book).ToDictionary(c=>c.ChapterID); + return narrative.Scenes.Where(s=>chapters.ContainsKey(s.ChapterID)).Select(s=>new SelectListItem( + $"Chapter {chapters[s.ChapterID].ChapterNumber:0.##} · {s.SceneTitle}",s.SceneID.ToString(),s.SceneID==current)).ToArray(); + } + + public static IReadOnlyList Nearby(StoryContextViewModel context) + { + if(context.Narrative?.Snapshot is not {} point||context.Scene?.StartDateTime is not {} date)return []; + var chapters=context.Narrative.Chapters.Where(c=>c.BookID==point.Book.BookID).ToDictionary(c=>c.ChapterID); + return context.Narrative.Scenes.Where(s=>s.SceneID!=point.Scene.SceneID&&point.Sources.ContainsKey(s.SceneID)&&chapters.ContainsKey(s.ChapterID)&& + s.StartDateTime.HasValue&&Math.Abs((s.StartDateTime.Value-date).TotalDays)<=3) + .OrderBy(s=>Math.Abs((s.StartDateTime!.Value-date).TotalSeconds)).Take(5) + .Select(s=>new StoryCalendarSceneViewModel{SceneID=s.SceneID,BookID=point.Book.BookID,ChapterID=s.ChapterID,ChapterNumber=chapters[s.ChapterID].ChapterNumber, + SceneNumber=s.SceneNumber,Title=s.SceneTitle,StartDateTime=s.StartDateTime}).ToArray(); + } + + public static IReadOnlyList Threads(StoryContextViewModel context) + { + if(context.Narrative?.Snapshot is not {} point)return []; + var current=context.Scene?.ThreadEvents.Select(e=>e.PlotThreadID).ToHashSet()??[]; + var viewpoint=point.ViewpointKnowledge.Where(k=>k.PlotThreadID.HasValue).Select(k=>k.PlotThreadID!.Value).ToHashSet(); + var people=point.Characters.SelectMany(c=>c.Knowledge).Where(k=>k.PlotThreadID.HasValue).Select(k=>k.PlotThreadID!.Value).ToHashSet(); + var chapterScenes=context.Narrative.Scenes.Where(s=>s.ChapterID==point.Chapter.ChapterID).Select(s=>s.SceneID).ToHashSet(); + int Score(StoryPointThread t)=>current.Contains(t.PlotThreadID)?4:viewpoint.Contains(t.PlotThreadID)?3:people.Contains(t.PlotThreadID)?2:t.Source!=null&&chapterScenes.Contains(t.Source.SceneID)?1:0; + return point.Threads.Where(t=>Score(t)>0).OrderByDescending(Score).ThenBy(t=>t.Title).Take(6).ToArray(); + } +} diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index 7fbda74a..828f02bc 100644 --- a/PlotLine/ViewModels/CoreViewModels.cs +++ b/PlotLine/ViewModels/CoreViewModels.cs @@ -477,6 +477,8 @@ public sealed class WritingContextPageViewModel public sealed class WritingContextDisplayViewModel { + public StoryPointSnapshot? AtPoint => Context?.Narrative?.Snapshot; + public IReadOnlyList RelevantThreads => Context==null?[]:WritingContextRelevance.Threads(Context); public IReadOnlyList NearbyScenes {get;set;}=[]; public StoryContextViewModel? Context { get; set; } public RelationshipMapViewModel? RelationshipMap { get; set; } diff --git a/PlotLine/ViewModels/StoryPointViewModel.cs b/PlotLine/ViewModels/StoryPointViewModel.cs index 87a70556..83918d0d 100644 --- a/PlotLine/ViewModels/StoryPointViewModel.cs +++ b/PlotLine/ViewModels/StoryPointViewModel.cs @@ -19,6 +19,7 @@ public sealed class StoryPointSnapshot public Chapter Chapter { get; init; } = new(); public Scene Scene { get; init; } = new(); public string? PovName { get; init; } + public IReadOnlyList ViewpointKnowledge { get; init; } = []; public IReadOnlyList Characters { get; init; } = []; public IReadOnlyList Relationships { get; init; } = []; public IReadOnlyList Assets { get; init; } = []; diff --git a/PlotLine/Views/Writing/_WritingContextContent.cshtml b/PlotLine/Views/Writing/_WritingContextContent.cshtml index 12d8e2d3..38483bb1 100644 --- a/PlotLine/Views/Writing/_WritingContextContent.cshtml +++ b/PlotLine/Views/Writing/_WritingContextContent.cshtml @@ -33,6 +33,7 @@ Chapter @(scene.Chapter?.ChapterNumber.ToString("0.##")) Scene @(scene.SceneNumber.ToString("0.##")) + @if(current>=0){· Manuscript scene @(current+1) of @sequence.Count}

diff --git a/PlotLine/Views/Writing/_WritingContextOverview.cshtml b/PlotLine/Views/Writing/_WritingContextOverview.cshtml index cea717cb..9102e9ac 100644 --- a/PlotLine/Views/Writing/_WritingContextOverview.cshtml +++ b/PlotLine/Views/Writing/_WritingContextOverview.cshtml @@ -1,7 +1,7 @@ @model WritingContextDisplayViewModel @{ var scene = Model.Context!.Scene!; - var pov = scene.CharacterOptions.FirstOrDefault(x => x.Value == scene.POVCharacterID?.ToString())?.Text + var pov = (scene.POVCharacterID.HasValue ? Model.AtPoint?.PovName : null) ?? scene.CharacterOptions.FirstOrDefault(x => x.Value == scene.POVCharacterID?.ToString())?.Text ?? scene.SceneCharacters.FirstOrDefault(x => x.CharacterID == scene.POVCharacterID)?.CharacterName ?? "No POV set"; var primaryLocation = scene.LocationOptions.FirstOrDefault(x => x.Value == scene.PrimaryLocationID?.ToString())?.Text?.Trim() @@ -57,9 +57,10 @@

Continuity

- @if (scene.Warnings.Any() || scene.AgeContinuityWarnings.Any()) + @if (scene.Warnings.Any() || scene.AgeContinuityWarnings.Any() || Model.AtPoint?.Warnings.Any()==true) {
    + @foreach(var check in (Model.AtPoint?.Warnings??[]).Take(4)){
  • Continuity check: @check.Message
  • } @foreach (var warning in scene.Warnings.Concat(scene.AgeContinuityWarnings).Take(4)) {
  • @warning.SeverityName @warning.Message
  • @@ -74,9 +75,9 @@
-

Around this story date

+

Earlier established scenes near this story date

@if(!scene.StartDateTime.HasValue){

No absolute story date saved. Relative timing is shown above; no nearby dates are inferred.

} - else if(!Model.NearbyScenes.Any()){

No other dated scenes in this book within three days.

} + else if(!Model.NearbyScenes.Any()){

No earlier established scenes in this book within three days.

} else{
    @foreach(var item in Model.NearbyScenes){
  • @item.Title
  • }
}

People at this point

@@ -98,3 +99,19 @@ Plot Lines Characters and relationships + +
+
+

Viewpoint knowledge

+

Verified records through this scene in manuscript order. States may include uncertainty or lack of knowledge. Reader knowledge is not independently recorded here.

+ @if(scene.POVCharacterID is null){

No viewpoint character recorded. No viewpoint knowledge is inferred.

} + else if(Model.AtPoint?.ViewpointKnowledge.Any()!=true){

No verified knowledge records for this viewpoint at this point.

} + else{
    @foreach(var fact in Model.AtPoint.ViewpointKnowledge.Take(5)){
  • @fact.KnowledgeStateName: @(fact.Description??fact.AssetName??fact.ThreadTitle??"Recorded knowledge") Source scene
  • }

Open People for other participants’ knowledge records.

} +
+
+

Relevant unresolved threads

+

Established through this scene; prioritised by current events, knowledge records and this chapter. Author reference, not proof of viewpoint awareness.

+ @if(!Model.RelevantThreads.Any()){

No established unresolved threads linked to this scene, its participants or this chapter.

} + else{} +
+
diff --git a/PlotLine/Views/Writing/_WritingContextPeople.cshtml b/PlotLine/Views/Writing/_WritingContextPeople.cshtml index 8a88777a..9bdc52b8 100644 --- a/PlotLine/Views/Writing/_WritingContextPeople.cshtml +++ b/PlotLine/Views/Writing/_WritingContextPeople.cshtml @@ -17,7 +17,8 @@ else
@foreach (var character in scene.SceneCharacters.OrderByDescending(x => x.CharacterID == povCharacterId).ThenBy(x => x.CharacterName)) { - var knowledge = scene.CharacterKnowledge.Where(x => x.CharacterID == character.CharacterID).ToList(); + var known = Model.AtPoint?.Characters.FirstOrDefault(x=>x.Appearance.CharacterID==character.CharacterID); + var knowledge = Model.AtPoint?.Characters.FirstOrDefault(x=>x.Appearance.CharacterID==character.CharacterID)?.Knowledge.ToList() ?? []; var attributes = scene.CharacterAttributeEvents.Where(x => x.CharacterID == character.CharacterID).ToList();
@@ -29,17 +30,19 @@ else
Location
@TextOr(character.LocationPath ?? character.LocationName, "Unknown")
+
Last recorded location
@(known?.State?.CurrentLocation ?? "Not recorded")
Emotional state
@TextOr(character.EmotionalState, "Not recorded")
Physical condition
@TextOr(character.PhysicalCondition, "Not recorded")
Outfit
@TextOr(character.OutfitDescription ?? character.AppearanceNotes, "Not recorded")
Movement
@TextOr(string.Join(" -> ", new[] { character.EntryLocationName, character.ExitLocationName }.Where(x => !string.IsNullOrWhiteSpace(x))), "No entry or exit recorded")
+

@(character.CharacterID==povCharacterId?"Verified viewpoint knowledge at this narrative point":"Author reference: this character’s knowledge, not necessarily the viewpoint character’s")

@if (knowledge.Any() || attributes.Any()) {
@foreach (var item in knowledge.Take(3)) { -

@item.KnowledgeStateName: @TextOr(item.Description, item.AssetName ?? item.ThreadTitle ?? "Knowledge change recorded.")

+

@item.KnowledgeStateName: @TextOr(item.Description, item.AssetName ?? item.ThreadTitle ?? "Knowledge change recorded.") Source scene

} @foreach (var item in attributes.Take(3)) { diff --git a/PlotLine/Views/Writing/_WritingContextPlotLines.cshtml b/PlotLine/Views/Writing/_WritingContextPlotLines.cshtml index 0d230369..2b79b38a 100644 --- a/PlotLine/Views/Writing/_WritingContextPlotLines.cshtml +++ b/PlotLine/Views/Writing/_WritingContextPlotLines.cshtml @@ -13,7 +13,7 @@ }
-

Plot line context for the current scene, showing the previous, current and next developments.

+

Author plot overview, including planned and future developments. This is not viewpoint knowledge.

Show: diff --git a/PlotLine/Views/Writing/_WritingContextRelationships.cshtml b/PlotLine/Views/Writing/_WritingContextRelationships.cshtml index 58d13181..0de43a0d 100644 --- a/PlotLine/Views/Writing/_WritingContextRelationships.cshtml +++ b/PlotLine/Views/Writing/_WritingContextRelationships.cshtml @@ -32,7 +32,8 @@
-

State At This Point

+

Relationships at this point

+

Author reference from established earlier records; not proof of viewpoint knowledge.

@if (!relationships.Any()) {

No visible relationships at this point.

diff --git a/PlotLine/Views/Writing/_WritingContextStory.cshtml b/PlotLine/Views/Writing/_WritingContextStory.cshtml index 38137eda..6e7741e0 100644 --- a/PlotLine/Views/Writing/_WritingContextStory.cshtml +++ b/PlotLine/Views/Writing/_WritingContextStory.cshtml @@ -23,15 +23,15 @@
-

Knowledge

- @if (!scene.CharacterKnowledge.Any()) +

Verified viewpoint knowledge through this scene

+ @if (!(Model.AtPoint?.ViewpointKnowledge ?? []).Any()) { -

No knowledge changes recorded.

+

No verified viewpoint knowledge recorded.

} else {
    - @foreach (var item in scene.CharacterKnowledge) + @foreach (var item in (Model.AtPoint?.ViewpointKnowledge ?? [])) {
  • @item.CharacterName @item.KnowledgeStateName: @TextOr(item.Description, item.AssetName ?? item.ThreadTitle ?? "Knowledge change recorded.")
  • } @@ -40,7 +40,8 @@
-

Dependencies

+

Author continuity dependencies

+

Saved planning references may describe later scenes; they are not character knowledge.

@if (!scene.DependenciesThisSceneNeeds.Any() && !scene.DependenciesNeedingThisScene.Any()) {

No dependencies recorded.

diff --git a/PlotLine/Views/Writing/_WritingIntentPlan.cshtml b/PlotLine/Views/Writing/_WritingIntentPlan.cshtml index 3a5792c6..8f059cc5 100644 --- a/PlotLine/Views/Writing/_WritingIntentPlan.cshtml +++ b/PlotLine/Views/Writing/_WritingIntentPlan.cshtml @@ -7,6 +7,7 @@ static string TextOr(string? value, string fallback) => string.IsNullOrWhiteSpace(value) ? fallback : value.Trim(); } +

Saved author plan and scene reference. Opening this view does not rewrite intent or accept suggestions.

Chapter Plan

@@ -19,7 +20,7 @@
-

Current Scene

+

Saved scene reference

@if (scene is null) {

No current scene. Chapter intent is shown until Word reports a scene.

@@ -33,6 +34,7 @@

Scene Purpose

+ @if(scene!=null){
@foreach(var purpose in scene.ScenePurposeTypes.Where(p=>scene.SelectedPurposeTypeIds.Contains(p.ScenePurposeTypeID)).OrderBy(p=>p.SortOrder)){@purpose.PurposeName}
}

@TextOr(scene?.ScenePurposeNotes, "No scene-specific purpose notes yet.")

diff --git a/PlotLine/wwwroot/js/writing-follow.js b/PlotLine/wwwroot/js/writing-follow.js index 1353b678..e24e52bc 100644 --- a/PlotLine/wwwroot/js/writing-follow.js +++ b/PlotLine/wwwroot/js/writing-follow.js @@ -49,7 +49,7 @@ let loadingSceneId = null; let loadingChapterId = null; let requestGeneration = 0; - let pendingRequest = null, navigationRequest = null; + let pendingRequest = null, pendingNativeRequest = false, navigationRequest = null; let manualGeneration=0; let selectedDocument = root.dataset.wordInstance && root.dataset.wordSession ? root.dataset.wordInstance + '/' + root.dataset.wordSession : ''; let nativePositionKey = '', nativeWasConnected = false, nativeLeases = []; @@ -274,6 +274,7 @@ pendingRequest?.abort(); const controller = new AbortController(); pendingRequest = controller; + pendingNativeRequest = position.source === 'WordCompanion'; loadingSceneId = hasScene ? position.sceneId : null; loadingChapterId = !hasScene ? position.chapterId : null; setStatus(config.updatingStatus); @@ -282,10 +283,15 @@ if (position.bookId) url.searchParams.set("bookId", position.bookId); if (position.chapterId) url.searchParams.set("chapterId", position.chapterId); if (hasScene) url.searchParams.set("sceneId", position.sceneId); + if(position.source==='WordCompanion'&&position.instanceId&&position.sessionId){url.searchParams.set('instanceId',position.instanceId);url.searchParams.set('sessionId',position.sessionId);} try { console.info(`[${config.source}] Loading writing position.`, position); const response = await fetch(url, { signal: controller.signal, headers: { "X-Requested-With": "XMLHttpRequest" } }); + if(response.status===409&&position.source==='WordCompanion'){ + if(generation===requestGeneration)setStatus('Word mapping is awaiting verification · saved scene remains available'); + return; + } if (!response.ok || response.redirected) { throw new Error(`${config.source} request failed: ${response.status}`); } @@ -331,11 +337,16 @@ if (generation === requestGeneration) { loadingSceneId = null; loadingChapterId = null; - pendingRequest = null; + pendingRequest = null;pendingNativeRequest = false; } } }; + const suspendNativeRequest = () => { + if(!pendingNativeRequest)return; + ++requestGeneration;pendingRequest?.abort();pendingRequest=null;pendingNativeRequest=false; + loadingSceneId=null;loadingChapterId=null; + }; const followNative = (leases) => { nativeLeases = leases; if(leases.reconnected)nativeWasConnected=false; @@ -344,12 +355,12 @@ 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) { nativeWasConnected = false; nativePositionKey = ''; setStatus(available.length > 1 && !selectedDocument ? 'Choose a Word document using the connection indicator' : selectedDocument ? 'Selected Word document is disconnected · saved scene remains available' : leases.some(l=>l.wordAvailable) ? 'Saved scene · no live Word position for this book' : 'Word disconnected · saved scene remains available'); return; } - const key = [lease.instanceId, lease.sessionId, lease.chapterId, lease.sceneId, lease.wordSaved].join(':'); - if ((!lease.sceneId && !(config.allowChapterOnly && lease.chapterId)) || lease.wordSaved === false) { nativeWasConnected = true; nativePositionKey = key; setStatus(lease.positionMessage?lease.positionMessage+' · saved scene remains available':lease.wordSaved===false?'Save Word, then synchronise to refresh its scene mapping · saved scene remains available':'Word scene mapping is unavailable · synchronise from Word; saved scene remains available'); return; } + if (!lease) { suspendNativeRequest();nativeWasConnected = false; nativePositionKey = ''; setStatus(available.length > 1 && !selectedDocument ? 'Choose a Word document using the connection indicator' : selectedDocument ? 'Selected Word document is disconnected · saved scene remains available' : leases.some(l=>l.wordAvailable) ? 'Saved scene · no live Word position for this book' : 'Word disconnected · saved scene remains available'); return; } + const key = [lease.instanceId, lease.sessionId, lease.manuscriptId, lease.revision, lease.chapterId, lease.sceneId, lease.wordSaved].join(':'); + if ((!lease.sceneId && !(config.allowChapterOnly && lease.chapterId)) || lease.wordSaved !== true || lease.positionVerified === false) { suspendNativeRequest();nativeWasConnected = true; nativePositionKey = key; setStatus(lease.positionMessage?lease.positionMessage+' · saved scene remains available':lease.wordSaved===false?'Save Word before verifying its scene mapping · saved scene remains available':'Word scene mapping is awaiting verification · saved scene remains available'); return; } if (!nativeWasConnected || key !== nativePositionKey || (!pendingRequest && Number(lease.sceneId)!==currentSceneId)) { nativeWasConnected = true; nativePositionKey = key; - void loadPosition({source:'WordCompanion',projectId:scopedProjectId || parsePositiveInt(currentFragment?.dataset.projectId),bookId:Number(lease.bookId),chapterId:Number(lease.chapterId),sceneId:lease.sceneId?Number(lease.sceneId):null}); + void loadPosition({source:'WordCompanion',instanceId:lease.instanceId,sessionId:lease.sessionId,projectId:scopedProjectId || parsePositiveInt(currentFragment?.dataset.projectId),bookId:Number(lease.bookId),chapterId:Number(lease.chapterId),sceneId:lease.sceneId?Number(lease.sceneId):null}); setStatus('Following Word'); } };