From 77470058fe1a369e2d7c5570b6a2e8866a4c9c13 Mon Sep 17 00:00:00 2001 From: Atlas Development Worker Date: Mon, 30 Nov 2026 23:32:28 +0000 Subject: [PATCH] Honor committed saves from composite editors --- .../context-saved-data-development.cjs | 10 +++--- PlotLine.Tests/ContextSavedDataTests.cs | 10 +++--- PlotLine/Controllers/ScenesController.cs | 32 +++++++++---------- .../ContextReferenceInvalidationFilter.cs | 5 ++- 4 files changed, 30 insertions(+), 27 deletions(-) diff --git a/PlotLine.Tests/Browser/context-saved-data-development.cjs b/PlotLine.Tests/Browser/context-saved-data-development.cjs index 0b3280ff..ab097260 100644 --- a/PlotLine.Tests/Browser/context-saved-data-development.cjs +++ b/PlotLine.Tests/Browser/context-saved-data-development.cjs @@ -12,7 +12,7 @@ let session,stage='login'; const sceneId=await scene(chapter,'Held acceptance scene'),otherScene=await scene(otherChapter,'Isolated acceptance scene'); stage='map creation';await session.goto('/Maps?projectId='+project);await p.locator('#mapsWelcomeNew').click();await p.locator('#mapsNewForm [name=Name]').fill('Acceptance geometry');await p.locator('#mapsNewForm [name=Starter]').selectOption('land');await p.locator('#mapsNewForm button[type=submit]').click();await p.waitForFunction(()=>window.PlotDirectorMapWorkspace?.document?.features.length>0&&!window.PlotDirectorMapWorkspace.busy);const map=await p.evaluate(()=>PlotDirectorMapWorkspace.document.map.mapID); stage='floor plan creation';await session.goto('/FloorPlans?projectId='+project);const create=p.locator('form[action="/FloorPlans/Create"]');await create.locator('[name=Name]').fill('Acceptance plan');await create.locator('[name=LocationID]').selectOption(String(place));await create.locator('button[type=submit]').click();await p.waitForURL('**/FloorPlans/Edit/*');const plan=Number(new URL(p.url()).pathname.split('/').at(-1)); - const context=p.context(),a=await context.newPage(),b=await context.newPage(),c=await context.newPage(),reads=[]; + stage='Context split windows';const context=p.context(),a=await context.newPage(),b=await context.newPage(),c=await context.newPage(),reads=[]; for(const page of [a,b,c])page.on('request',r=>{const path=new URL(r.url()).pathname;if(path.startsWith('/SpatialContext/')||path.includes('/Context/Tabs/'))reads.push({page,path});}); const url=(bk,ch,sc)=>`https://dev.plotdirector.com/Writing/Context?projectId=${project}&bookId=${bk}&chapterId=${ch}&sceneId=${sc}&pinned=true`; const setTab=(page,i,tool)=>page.selectOption(`[data-context-pane="${i}"] [data-context-tab]`,tool); @@ -20,7 +20,7 @@ let session,stage='login'; await a.locator('[data-context-pane="0"] [data-spatial-resource]').selectOption(String(map));await a.locator('[data-context-pane="1"] [data-spatial-resource]').selectOption(String(plan)); await a.waitForFunction(()=>document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document); await a.locator('[data-floor-grid]').first().waitFor(); - await b.goto(url(book,chapter,sceneId));await b.selectOption('[data-context-layout]','columns');await setTab(b,0,'locations');await setTab(b,1,'overview');await b.getByRole('heading',{name:'Acceptance room',exact:true}).waitFor(); + await b.goto(url(book,chapter,sceneId));await b.selectOption('[data-context-layout]','columns');await setTab(b,0,'locations');await setTab(b,1,'overview');await b.locator('[data-context-pane="0"]').getByRole('heading',{name:'Acceptance room',exact:true}).waitFor(); await c.goto(url(otherBook,otherChapter,otherScene));await c.locator('[data-context-tab-fragment]').waitFor(); await Promise.all([a,b,c].map(page=>page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected'))); await a.locator('[data-context-pane="0"] [data-spatial-zoom="in"]').click();await a.locator('[data-context-pane="1"] [data-spatial-zoom="in"]').click();await a.waitForTimeout(400); @@ -31,11 +31,11 @@ let session,stage='login'; await a.waitForFunction(w=>document.querySelector('iframe')?.contentWindow.PlotDirectorMapWorkspace?.document.features[0].width===w,savedWidth);await a.waitForTimeout(300); assert.equal(reads.filter(r=>r.path==='/SpatialContext/Floor').length,0);assert.equal(reads.filter(r=>r.page===c).length,0,'project-wide geometry does not refresh unrelated Overview');assert.deepEqual(await snapshot(),before); stage='failed save does not invalidate';reads.length=0;const failed=await p.evaluate(async()=>{const doc=structuredClone(PlotDirectorMapWorkspace.document);doc.map.revision=-1;const token=document.querySelector('[name=__RequestVerificationToken]').value;return (await fetch('/Maps/Save',{method:'POST',headers:{'Content-Type':'application/json','RequestVerificationToken':token},body:JSON.stringify(doc)})).status;});assert(failed>=400);await a.waitForTimeout(400);assert.equal(reads.length,0); - stage='floor layout persistence and viewport retention';await session.goto('/FloorPlans/Edit/'+plan);const floorWidth=p.locator('[data-floor-width]').first();await floorWidth.evaluate(e=>{for(let node=e.parentElement;node;node=node.parentElement)if(node.tagName==='DETAILS')node.open=true;});const savedFloorWidth=Number(await floorWidth.inputValue())+1;await floorWidth.fill(String(savedFloorWidth));reads.length=0;await Promise.all([p.waitForResponse(r=>r.url().includes('/FloorPlans/SaveLayout')&&r.status()===200),p.locator('[data-save-layout-button]').first().click()]);await a.waitForFunction(w=>Number(document.querySelector('[data-floor-grid]').dataset.gridWidth)===w,savedFloorWidth);await a.waitForTimeout(300);assert.equal(reads.filter(r=>r.path==='/SpatialContext/Map').length,0);assert.equal(reads.filter(r=>r.page===b||r.page===c).length,0);assert.deepEqual(await snapshot(),before); - stage='held location saved-data update';await session.goto('/Locations/Edit/'+place);await p.locator('[name=Description]').fill('Saved description after refresh');await p.locator('form.pd-record-form button[type=submit]').first().click();await p.waitForURL('**/Locations/Details/*');await b.getByText('Saved description after refresh',{exact:true}).waitFor();assert.equal(await b.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),sceneId); + stage='floor layout persistence and viewport retention';await session.goto('/FloorPlans/Edit/'+plan);await p.locator('[data-toolbox-tab=floors]').click();const floorWidth=p.locator('[data-floor-width]').first();await floorWidth.evaluate(e=>{for(let node=e.parentElement;node;node=node.parentElement)if(node.tagName==='DETAILS')node.open=true;});const savedFloorWidth=Number(await floorWidth.inputValue())+1;await floorWidth.fill(String(savedFloorWidth));reads.length=0;await Promise.all([p.waitForResponse(r=>r.url().includes('/FloorPlans/SaveLayout')&&r.status()===200),p.locator('[data-save-layout-button]').first().click()]);await a.waitForFunction(w=>Number(document.querySelector('[data-floor-grid]').dataset.gridWidth)===w,savedFloorWidth);await a.waitForTimeout(300);assert.equal(reads.filter(r=>r.path==='/SpatialContext/Map').length,0);assert.equal(reads.filter(r=>r.page===b||r.page===c).length,0);assert.deepEqual(await snapshot(),before); + stage='held location saved-data update';await session.goto('/Locations/Edit/'+place);await p.locator('[name=Description]').fill('Saved description after refresh');await p.locator('form.pd-record-form button[type=submit]').first().click();await p.waitForURL('**/Locations/Details/*');await b.locator('[data-context-pane="0"]').getByText('Saved description after refresh',{exact:true}).waitFor();assert.equal(await b.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),sceneId); stage='date-only save targets Overview and preserves book isolation';await session.goto('/Scenes/SceneDetailsEditor?sceneId='+sceneId);const exact=await p.locator('[name=TimeModeID] option').evaluateAll(options=>options.find(o=>/exact/i.test(o.textContent))?.value);assert(exact);await p.locator('[name=TimeModeID]').selectOption(exact);await p.locator('[name=StartDateTime]').fill('2030-05-06T10:00');reads.length=0;await Promise.all([p.waitForResponse(r=>r.url().includes('/Scenes/SaveSceneDetails')&&r.status()===200),p.getByRole('button',{name:'Save details',exact:true}).click()]);await b.waitForFunction(()=>document.querySelector('[data-context-pane="1"]').textContent.includes('2030'));await b.waitForTimeout(300);assert.equal(reads.filter(r=>r.page===a||r.page===c).length,0,'date-only save does not refresh spatial or other-book panes'); stage='book-scoped intent and isolation';await session.goto('/Scenes/Edit/'+sceneId);reads.length=0;await session.post('/Scenes/SaveScenePurpose',{SceneID:sceneId,ScenePurposeNotes:'Saved acceptance purpose',SceneOutcomeNotes:'Saved acceptance outcome'});await b.waitForTimeout(700);assert.equal(reads.filter(r=>r.page===c).length,0);assert.equal(reads.filter(r=>r.page===a).length,0,'intent does not refresh spatial panes'); - stage='existing main window navigation';await p.waitForTimeout(600);const held=b.url();await b.getByRole('link',{name:'Location Details',exact:true}).click();await p.waitForURL('**/Locations/Details/'+place);assert.equal(b.url(),held);assert.equal(await b.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),sceneId); + stage='existing main window navigation';await p.waitForTimeout(600);const held=b.url();await b.locator('[data-context-pane="0"]').getByRole('link',{name:'Location Details',exact:true}).click();await p.waitForURL('**/Locations/Details/'+place);assert.equal(b.url(),held);assert.equal(await b.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),sceneId); await session.close();session=null; stage='fresh normal login and durable reload';session=await open();await session.goto(`/Maps?projectId=${project}&id=${map}`);await session.page.waitForFunction(w=>window.PlotDirectorMapWorkspace?.document.features[0].width===w,savedWidth);await session.goto('/FloorPlans/Edit/'+plan);assert.equal(Number(await session.page.locator('[data-floor-width]').first().inputValue()),savedFloorWidth);await session.goto('/Locations/Edit/'+place);assert.equal(await session.page.locator('[name=Description]').inputValue(),'Saved description after refresh');await session.goto('/Scenes/SceneDetailsEditor?sceneId='+sceneId);assert.match(await session.page.locator('[name=StartDateTime]').inputValue(),/^2030-05-06T10:00/);await session.goto('/Scenes/ScenePurposeEditor?sceneId='+sceneId);assert.equal(await session.page.locator('[name=ScenePurposeNotes]').inputValue(),'Saved acceptance purpose'); console.log(JSON.stringify({passed:true,project,book,otherBook,sceneId,map,plan,checks:['real committed map geometry','unsaved and failed saves silent','floor layout and map/floor viewport retention','held saved location refresh','book isolation','date-only targeting','relevant panels only','existing main navigation','fresh-login persistence'],featureUrl:`https://dev.plotdirector.com/Writing/Context?bookId=${book}&sceneId=${sceneId}&pinned=true`})); diff --git a/PlotLine.Tests/ContextSavedDataTests.cs b/PlotLine.Tests/ContextSavedDataTests.cs index 536676b9..c758bc87 100644 --- a/PlotLine.Tests/ContextSavedDataTests.cs +++ b/PlotLine.Tests/ContextSavedDataTests.cs @@ -29,7 +29,7 @@ internal static class ContextSavedDataTests var accessor = new HttpContextAccessor(); var notices = new ContextWorkspaceNotifications(hub, NullLogger.Instance, accessor); var filter = new ContextReferenceInvalidationFilter(notices); - foreach (var outcome in new[] { "preview", "saved", "badrequest", "invalid", "response400", "exception" }) + foreach (var outcome in new[] { "preview", "saved", "badrequest", "invalid", "unrelated-validation", "response400", "exception" }) { accessor.HttpContext = new DefaultHttpContext(); var action = new ActionContext(accessor.HttpContext, new RouteData(), new ActionDescriptor()); @@ -45,17 +45,17 @@ internal static class ContextSavedDataTests await notices.Invalidate(7, bookId:12, projectId:3, kind:"maps", entityId:44, entityType:"Map"); if (packets.Count != before) throw new Exception("Hint escaped before action completed."); } - if (outcome == "invalid") action.ModelState.AddModelError("Name", "Invalid"); + if (outcome is "invalid" or "unrelated-validation") action.ModelState.AddModelError("Name", "Invalid"); if (outcome == "response400") accessor.HttpContext.Response.StatusCode = 400; return new ActionExecutedContext(action, filters, controller) { - Result = outcome == "badrequest" ? new BadRequestResult() : new JsonResult(new { saved = true }), + Result = outcome == "badrequest" ? new BadRequestResult() : outcome == "invalid" ? new ViewResult() : new JsonResult(new { saved = true }), Exception = outcome == "exception" ? new InvalidOperationException("Synthetic failed save") : null }; }); - if (packets.Count - before != (outcome == "saved" ? 1 : 0)) throw new Exception("Save/failed/preview notification boundary: " + outcome); + if (packets.Count - before != (outcome is "saved" or "unrelated-validation" ? 1 : 0)) throw new Exception("Save/failed/preview notification boundary: " + outcome); } - using var json = JsonDocument.Parse(packets.Single()); + using var json = JsonDocument.Parse(packets.First()); var hint = json.RootElement; if (hint.GetProperty("projectId").GetInt32()!=3 || hint.GetProperty("bookId").GetInt32()!=12 || hint.GetProperty("kind").GetString()!="maps" || hint.GetProperty("entityId").GetInt32()!=44 || diff --git a/PlotLine/Controllers/ScenesController.cs b/PlotLine/Controllers/ScenesController.cs index 2d64937d..4d9e93bd 100644 --- a/PlotLine/Controllers/ScenesController.cs +++ b/PlotLine/Controllers/ScenesController.cs @@ -663,7 +663,7 @@ public sealed class ScenesController( if (note.Remove) { await writerWorkspace.DeleteNoteAsync(note.SceneNoteID); - if (savedData is not null) await savedData.Scene(model.SceneID, "structure"); + if (savedData is not null) await savedData.Scene(model.SceneID, "overview"); continue; } @@ -689,7 +689,7 @@ public sealed class ScenesController( IsPinned = note.IsPinned, IsResolved = note.IsResolved }); - if (savedData is not null) await savedData.Scene(model.SceneID, "structure"); + if (savedData is not null) await savedData.Scene(model.SceneID, "overview"); } var hasNewNoteContent = !string.IsNullOrWhiteSpace(model.NewNote.NoteTitle) @@ -708,7 +708,7 @@ public sealed class ScenesController( model.NewNote.SceneID = model.SceneID; await writerWorkspace.SaveNoteAsync(model.NewNote); - if (savedData is not null) await savedData.Scene(model.SceneID, "structure"); + if (savedData is not null) await savedData.Scene(model.SceneID, "overview"); } var updated = await scenes.GetEditAsync(model.SceneID); @@ -753,7 +753,7 @@ public sealed class ScenesController( if (item.Remove) { await writerWorkspace.DeleteChecklistItemAsync(item.SceneChecklistItemID); - if (savedData is not null) await savedData.Scene(model.SceneID, "structure"); + if (savedData is not null) await savedData.Scene(model.SceneID, "overview"); continue; } @@ -771,14 +771,14 @@ public sealed class ScenesController( IsCompleted = item.IsCompleted, SortOrder = item.SortOrder }); - if (savedData is not null) await savedData.Scene(model.SceneID, "structure"); + if (savedData is not null) await savedData.Scene(model.SceneID, "overview"); } if (!string.IsNullOrWhiteSpace(model.NewChecklistItem.ItemText)) { model.NewChecklistItem.SceneID = model.SceneID; await writerWorkspace.SaveChecklistItemAsync(model.NewChecklistItem); - if (savedData is not null) await savedData.Scene(model.SceneID, "structure"); + if (savedData is not null) await savedData.Scene(model.SceneID, "overview"); } var updated = await scenes.GetEditAsync(model.SceneID); @@ -813,7 +813,7 @@ public sealed class ScenesController( } await writerWorkspace.SaveSceneWorkflowAsync(model); - if (savedData is not null) await savedData.Scene(model.SceneID, "structure"); + if (savedData is not null) await savedData.Scene(model.SceneID, "overview"); var updated = await scenes.GetEditAsync(model.SceneID); if (updated is null) @@ -1197,7 +1197,7 @@ public sealed class ScenesController( public async Task AddSceneDependency(SceneDependencyCreateViewModel model) { await scenes.AddDependencyAsync(model); - if (savedData is not null) await savedData.Scene(model.CurrentSceneID, "structure"); + if (savedData is not null) await savedData.Scene(model.CurrentSceneID, "overview"); if (IsAjaxRequest()) { return await SceneStoryRefreshJsonAsync(model.CurrentSceneID); @@ -1211,7 +1211,7 @@ public sealed class ScenesController( public async Task DeleteSceneDependency(int id, int sceneId, int? projectId, int? bookId) { await scenes.DeleteDependencyAsync(id); - if (savedData is not null) await savedData.Scene(sceneId, "structure"); + if (savedData is not null) await savedData.Scene(sceneId, "overview"); if (IsAjaxRequest()) { return await SceneStoryRefreshJsonAsync(sceneId); @@ -1442,7 +1442,7 @@ public sealed class ScenesController( public async Task SaveWorkflow(SceneWorkflowEditViewModel model) { await writerWorkspace.SaveSceneWorkflowAsync(model); - if (savedData is not null) await savedData.Scene(model.SceneID, "structure"); + if (savedData is not null) await savedData.Scene(model.SceneID, "overview"); return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID); } @@ -1457,7 +1457,7 @@ public sealed class ScenesController( } await writerWorkspace.SaveNoteAsync(model); - if (savedData is not null) await savedData.Scene(model.SceneID, "structure"); + if (savedData is not null) await savedData.Scene(model.SceneID, "overview"); return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID); } @@ -1466,7 +1466,7 @@ public sealed class ScenesController( public async Task DeleteNote(int id, int sceneId, int? projectId, int? bookId) { await writerWorkspace.DeleteNoteAsync(id); - if (savedData is not null) await savedData.Scene(sceneId, "structure"); + if (savedData is not null) await savedData.Scene(sceneId, "overview"); return RedirectForScene(sceneId, projectId, bookId); } @@ -1481,7 +1481,7 @@ public sealed class ScenesController( } await writerWorkspace.SaveChecklistItemAsync(model); - if (savedData is not null) await savedData.Scene(model.SceneID, "structure"); + if (savedData is not null) await savedData.Scene(model.SceneID, "overview"); return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID); } @@ -1490,7 +1490,7 @@ public sealed class ScenesController( public async Task DeleteChecklistItem(int id, int sceneId, int? projectId, int? bookId) { await writerWorkspace.DeleteChecklistItemAsync(id); - if (savedData is not null) await savedData.Scene(sceneId, "structure"); + if (savedData is not null) await savedData.Scene(sceneId, "overview"); return RedirectForScene(sceneId, projectId, bookId); } @@ -1563,7 +1563,7 @@ public sealed class ScenesController( } var attachmentId = await writerWorkspace.SaveAttachmentAsync(model); - if (savedData is not null) await savedData.Scene(model.SceneID, "structure"); + if (savedData is not null) await savedData.Scene(model.SceneID, "overview"); if (fileSizeBytes > 0 && !string.IsNullOrWhiteSpace(model.FilePath)) { await storage.TrackSceneAttachmentAsync( @@ -1595,7 +1595,7 @@ public sealed class ScenesController( public async Task DeleteAttachment(int id, int sceneId, int? projectId, int? bookId, string? filePath) { await writerWorkspace.DeleteAttachmentAsync(id); - if (savedData is not null) await savedData.Scene(sceneId, "structure"); + if (savedData is not null) await savedData.Scene(sceneId, "overview"); await storage.MarkDeletedByStoragePathAsync(filePath); uploadStorage.TryDeleteFile(filePath, "uploads/scenes"); if (IsAjaxRequest()) diff --git a/PlotLine/Services/ContextReferenceInvalidationFilter.cs b/PlotLine/Services/ContextReferenceInvalidationFilter.cs index 0f0fe70b..78b4d1ab 100644 --- a/PlotLine/Services/ContextReferenceInvalidationFilter.cs +++ b/PlotLine/Services/ContextReferenceInvalidationFilter.cs @@ -9,8 +9,11 @@ public sealed class ContextReferenceInvalidationFilter(ContextWorkspaceNotificat public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var result = await next(); - if (!notifications.AlreadyInvalidated || result.Exception != null || !context.ModelState.IsValid || + if (!notifications.AlreadyInvalidated || result.Exception != null || result.Result is ForbidResult or ChallengeResult || context.HttpContext.Response.StatusCode >= 400) return; + // Composite editors validate unused creation forms too. Their successful + // save markers are authoritative even when those unrelated fields are invalid. + if (!context.ModelState.IsValid && result.Result is ViewResult) return; var status = result.Result switch { ObjectResult value => value.StatusCode ?? 200,