Add confirmed scoped investigation deletion and active discard

This commit is contained in:
Nick Beckley 2026-11-20 11:17:56 +00:00
parent c2e25438a5
commit c2914db194
15 changed files with 385 additions and 13 deletions

View File

@ -0,0 +1,48 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
(async()=>{const installed=process.argv.includes('--installed'),profile=fs.mkdtempSync('/tmp/pd-icon-pwa-');const c=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1666,height:1050}}):await(await chromium.launch()).newContext({viewport:{width:1666,height:1050}});const b=c.browser(),base='http://127.0.0.1:5238';try{
await c.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()})));
await c.route('**/native-companion/status*',r=>r.fulfill({json:{leases:[]}}));
let p;if(installed){const tab=c.pages()[0];await tab.goto(base+'/fixture');const d=await b.newBrowserCDPSession(),manifestId=base+'/Projects';await d.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture'});await d.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=c.waitForEvent('page');await d.send('PWA.launch',{manifestId,url:base+'/fixture'});p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else p=await c.newPage();
await c.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'))}));
const url=base+'/Writer/Explore?projectId=7&bookId=12',root=p.locator('[data-explore-investigation]'),journey=p.locator('[data-explore-journey]'),layout=p.locator('[data-explore-layout]');
p.setDefaultTimeout(20000);let navigations=0;p.on('request',r=>{if(r.isNavigationRequest()&&r.frame()===p.mainFrame())navigations++;});
const idle=()=>p.waitForFunction(()=>!document.querySelector('[data-explore-investigation]').hasAttribute('aria-busy'));
const start=async()=>{await root.getByRole('tab',{name:'New investigation',exact:true}).click();await journey.locator('[name=concern]').first().check();await journey.getByRole('button',{name:'Begin',exact:true}).click();await idle();await p.waitForFunction(()=>!document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating'));return new URL(p.url()).searchParams.get('investigation');};
const token=()=>root.locator('[name=__RequestVerificationToken]').first().inputValue();
const payload=async id=>({id,projectId:'7',bookId:'12',__RequestVerificationToken:await token()});
const post=(data)=>p.request.post(base+'/Writer/Explore/Investigate/Delete',{form:data});
const landing=async()=>{await journey.getByRole('link',{name:'Return to Explore',exact:true}).evaluate(n=>n.click());await journey.getByRole('button',{name:'Begin',exact:true}).waitFor();await idle();await p.waitForFunction(()=>!document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating'));};
const selectSaved=async()=>{await root.getByRole('tab',{name:'Saved investigations',exact:true}).click();};
let menuCaptured=false;
const openDelete=async id=>{const button=p.locator(`[data-explore-saved] [data-investigation-delete="${id}"]`);if(await button.locator('..').getAttribute('open')===null)await button.locator('..').locator('summary').click();if(!menuCaptured){for(const theme of ['modern-light','modern-dark']){await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);await p.screenshot({path:`/tmp/pd-deletion-evidence/${installed?'pwa':'browser'}-${theme}-actions.png`});}menuCaptured=true;}await button.click();await p.getByRole('dialog',{name:'Delete this investigation?',exact:true}).waitFor();};
const dialog=()=>p.getByRole('dialog',{name:'Delete this investigation?',exact:true});
await p.goto(url);await journey.getByRole('button',{name:'Begin',exact:true}).waitFor();await idle();const initialNav=navigations;
const active=await start(),stale=await journey.locator('[data-investigation-answer]').evaluate(f=>Object.fromEntries(new FormData(f)));
await journey.getByRole('button',{name:'Keep this investigation alongside my work',exact:true}).click();await p.waitForFunction(id=>window.PlotDirectorGuidanceSummary?.summary?.id===id,active);
const sibling=await c.newPage();await sibling.goto(url+'&investigation='+active);await sibling.locator('[data-inline-investigation]').waitFor();await p.bringToFront();
stale.option=await journey.locator('[name=option]').first().inputValue();stale.operation='answer';
const bounds=await layout.boundingBox(),handle=p.locator('[data-explore-divider]'),rect=await handle.boundingBox();await p.mouse.move(rect.x+rect.width/2,rect.y+80);await p.mouse.down();await p.mouse.move(bounds.x+(bounds.width-rect.width)*.4+rect.width/2,rect.y+80,{steps:10});await p.mouse.up();
const pref=()=>p.evaluate(()=>JSON.parse(localStorage.getItem(Object.keys(localStorage).find(k=>k.startsWith('plotdirector.writerExploreLayout.')))).leftRatio);
assert(Math.abs(await pref()-.4)<.005);
await journey.getByRole('button',{name:'Discard investigation',exact:true}).click();fs.mkdirSync('/tmp/pd-deletion-evidence',{recursive:true});await dialog().screenshot({path:`/tmp/pd-deletion-evidence/${installed?'pwa':'browser'}-confirmation.png`});for(const theme of ['modern-light','modern-dark']){await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);await dialog().screenshot({path:`/tmp/pd-deletion-evidence/${installed?'pwa':'browser'}-${theme}-confirmation.png`});}await dialog().locator('[data-dialog-action=cancel]').click();assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+active)).status(),200);
assert.equal((await p.request.post(base+'/Writer/Explore/Investigate/Delete',{form:{id:active,bookId:'12',projectId:'7'}})).status(),400);assert.equal((await post({...await payload(active),projectId:'8'})).status(),404);assert.equal((await post({...await payload(active),bookId:'13'})).status(),404);
const other=await b.newContext();await other.addCookies([{name:'fixture-user',value:'5',url:base}]);const html=await(await other.request.get(base+'/fixture')).text(),otherToken=html.match(/name="__RequestVerificationToken"[^>]*value="([^"]+)"/)[1];assert.equal((await other.request.post(base+'/Writer/Explore/Investigate/Delete',{form:{id:active,projectId:'7',bookId:'12',__RequestVerificationToken:otherToken}})).status(),404);await other.close();
let fail=true;await c.route('**/Writer/Explore/Investigate/Delete',r=>fail?r.fulfill({status:503,json:{message:'Fixture failure'}}):r.continue());
await journey.getByRole('button',{name:'Discard investigation',exact:true}).click();await dialog().locator('[data-dialog-action=delete]').click();await dialog().locator('[data-dialog-error]:not([hidden])').waitFor();assert(await dialog().isVisible());assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+active)).status(),200);fail=false;
await p.evaluate(()=>{window.deletionFrames=[];window.deletionSampling=true;function frame(){window.deletionFrames.push(Number(document.querySelector('[data-explore-layout]').style.getPropertyValue('--explore-ratio')));if(window.deletionSampling)requestAnimationFrame(frame);}requestAnimationFrame(frame);});
await dialog().locator('[data-dialog-action=delete]').click();await dialog().waitFor({state:'detached'});await journey.getByRole('button',{name:'Begin',exact:true}).waitFor();await idle();await p.waitForFunction(()=>!document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating'));await p.evaluate(()=>window.deletionSampling=false);
assert((await p.evaluate(()=>window.deletionFrames)).filter(v=>v>.405&&v<.495).length>=4,'Discard visibly animates back to landing');assert.equal(await layout.getAttribute('data-explore-state'),'landing');assert(Math.abs(await pref()-.4)<.005);assert.equal(await p.evaluate(()=>sessionStorage.getItem('writer.explore.active.12')),null);assert.equal(new URL(p.url()).searchParams.has('investigation'),false);await p.waitForFunction(()=>window.PlotDirectorGuidanceSummary?.active===false);assert.equal(await p.locator('[data-discovery-active] [data-tile]').count(),0);
assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+active)).status(),404);assert.equal((await p.request.post(base+'/Writer/Explore/Investigate/Answer',{form:stale})).status(),404);assert.equal((await post(await payload(active))).status(),200);
await sibling.getByRole('button',{name:'Begin',exact:true}).waitFor();assert.equal(await sibling.evaluate(()=>sessionStorage.getItem('writer.explore.active.12')),null);assert.equal(await sibling.locator('[data-explore-layout]').getAttribute('data-explore-state'),'landing');await sibling.close();
await c.unroute('**/Writer/Explore/Investigate/Delete');
const unrelated=await start();await landing();
for(const completed of [false,true]){
const id=await start();
if(completed){for(let n=0;n<20&&await journey.locator('[data-investigation-answer]').count();n++){await journey.locator('[name=option]').first().check();await journey.locator('button[value=answer]').click();await idle();}assert.equal(await journey.locator('[data-investigation-answer]').count(),0,'Completed investigation fixture');}
else{const area=journey.locator('textarea');if(await area.count())await area.fill('Disposable saved draft');await journey.locator('button[value=save]').click();await idle();}
await landing();await selectSaved();await openDelete(id);await dialog().locator('[data-dialog-action=cancel]').click();assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+id)).status(),200);await openDelete(id);await dialog().locator('[data-dialog-action=delete]').click();await dialog().waitFor({state:'detached'});await p.waitForFunction(id=>!document.querySelector(`[data-explore-saved] [data-investigation-delete="${id}"]`),id);assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+unrelated)).status(),200);
}
await selectSaved();await openDelete(unrelated);await dialog().locator('[data-dialog-action=delete]').click();await dialog().waitFor({state:'detached'});await p.locator('[data-explore-saved]').filter({hasText:'No saved investigations yet.'}).waitFor();assert.equal(navigations,initialNav,'No full document reload during delete/discard');
for(const theme of ['modern-light','modern-dark']){await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);fs.mkdirSync('/tmp/pd-deletion-evidence',{recursive:true});await p.screenshot({path:`/tmp/pd-deletion-evidence/${installed?'pwa':'browser'}-${theme}.png`});}
console.log('PASS '+(installed?'installed PWA':'browser')+' deletion/discard, cancel, error retention/retry, ownership/project/book, stale answer/resume, repeats, saved/completed/partial, empty/unrelated lists, session cleanup and animated landing with retained preference');
}finally{await c.close();await b.close();fs.rmSync(profile,{recursive:true,force:true});}})().catch(e=>{console.error(e);process.exitCode=1});

View File

@ -29,6 +29,16 @@ internal static class InvestigationGuidanceTests
r=(await store.Read(4,7,12,i.ID))!;await service.Save(4,r,s,"activate");Check((await store.Read(4,7,12))!.IsActive,"finished investigation can be reactivated");
var afterEvents=await repo.Replay(4,12,i.ID);var after=await repo.Read(4,12,i.ID);
Check(before==JsonSerializer.Serialize(after,CatalogueValidator.Json)&&events.SequenceEqual(afterEvents),"canonical answers, diagnostic scores and event history unchanged");
foreach(var state in new[]{"saved","partial","completed"}){
var owned=new Investigation{ID=Guid.NewGuid(),UserID=4,ProjectID=7,BookID=12,CatalogueVersion=c.Version,Concern=c.Concerns[0].Id,CurrentQuestion=state=="completed"?null:c.Questions[0].Id,Accepted=state=="completed"};
owned.Answers.Add(new(c.Questions[0].Id,c.Questions[0].Options[0].Id,"original"));await repo.Save(owned,0,state,evaluation);owned.Answers[0]=new(c.Questions[0].Id,c.Questions[0].Options.Last().Id,"revised");await repo.Save(owned,owned.Version,"revision",evaluation);
foreach(var scope in new[]{(5,7,12),(4,8,12),(4,7,13)}){try{await repo.Delete(scope.Item1,scope.Item2,scope.Item3,owned.ID);throw new Exception("foreign deletion accepted");}catch(UnauthorizedAccessException){}}
await repo.Delete(4,7,12,owned.ID);await repo.Delete(4,7,12,owned.ID);
Check(await repo.Read(4,12,owned.ID)==null&&(await repo.List(4,12)).All(x=>x.ID!=owned.ID)&&await store.Read(4,7,12,owned.ID)==null,"delete "+state+" removes saved, resume and guidance projections; repeats are safe");
try{await repo.Save(owned,owned.Version,"stale answer",evaluation);throw new Exception("deleted update recreated record");}catch(KeyNotFoundException){}
try{await repo.Save(owned,0,"replayed Begin",evaluation);throw new Exception("deleted Begin recreated record");}catch(KeyNotFoundException){}
}
Check(await repo.Read(4,12,i.ID)!=null,"deletion preserves unrelated investigations and their accepted tool progress");
r.InvestigationJson=JsonSerializer.Serialize(new Investigation{ID=i.ID,UserID=4,ProjectID=7,BookID=12,CatalogueVersion=c.Version,Concern=c.Concerns[0].Id},CatalogueValidator.Json);r.EvaluationJson=null;Check(service.Summary(r,c).Findings.Count==0,"old records without snapshots remain readable without invented advice");
}
}

View File

@ -7,11 +7,13 @@ internal sealed class InvestigationMemoryRepository:IInvestigationRepository
{
readonly Dictionary<string,string> catalogues=[];readonly Dictionary<Guid,string> rows=[];readonly Dictionary<Guid,List<string>> events=[];readonly object sync=new();string current="";
public InvestigationMemoryRepository(){var json=File.ReadAllText(Environment.GetEnvironmentVariable("PD_INV_CATALOGUE")??"Docs/Writer/Investigations/synthetic-catalogue.json");var c=CatalogueValidator.Parse(json);catalogues[c.Version]=json;current=c.Version;}
readonly Dictionary<Guid,(int User,int Project,int Book)> deleted=[];
public Task Delete(int user,int project,int book,Guid id){lock(sync){if(rows.TryGetValue(id,out var json)){var i=Parse(json);if(i.UserID!=user||i.BookID!=book||i.ProjectID!=project)throw new UnauthorizedAccessException();rows.Remove(id);events.Remove(id);deleted[id]=(user,project,book);}else if(!deleted.TryGetValue(id,out var scope)||scope!=(user,project,book))throw new KeyNotFoundException();}return Task.CompletedTask;}
public Task<Catalogue?> Catalogue(string? version=null){lock(sync)return Task.FromResult(catalogues.TryGetValue(version??current,out var json)?CatalogueValidator.Parse(json):null);}
public Task Publish(string json,string actor){lock(sync){var c=CatalogueValidator.Parse(json);if(catalogues.ContainsKey(c.Version))throw new ArgumentException("Version already exists.");catalogues[c.Version]=json;current=c.Version;}return Task.CompletedTask;}
public Task<IReadOnlyList<Investigation>> List(int user,int book){lock(sync)return Task.FromResult<IReadOnlyList<Investigation>>(rows.Values.Select(Parse).Where(i=>i.UserID==user&&i.BookID==book).OrderByDescending(i=>i.UpdatedUtc).ToArray());}
public Task<Investigation?> Read(int user,int book,Guid id){lock(sync){var i=rows.TryGetValue(id,out var json)?Parse(json):null;return Task.FromResult(i?.UserID==user&&i.BookID==book?i:null);}}
public Task Save(Investigation i,int expected,string operation,Evaluation result){lock(sync){if(rows.TryGetValue(i.ID,out var old)){var prior=Parse(old);if(prior.Version!=expected||prior.UserID!=i.UserID||prior.BookID!=i.BookID)throw new ArgumentException("Stale or unavailable investigation");}else if(expected!=0)throw new ArgumentException("Missing investigation");i.Version=expected+1;rows[i.ID]=JsonSerializer.Serialize(i,CatalogueValidator.Json);if(!events.ContainsKey(i.ID))events[i.ID]=[];events[i.ID].Add(JsonSerializer.Serialize(new{operation,state=i,evaluation=result},CatalogueValidator.Json));}return Task.CompletedTask;}
public Task Save(Investigation i,int expected,string operation,Evaluation result){lock(sync){if(deleted.ContainsKey(i.ID))throw new KeyNotFoundException();if(rows.TryGetValue(i.ID,out var old)){var prior=Parse(old);if(prior.Version!=expected||prior.UserID!=i.UserID||prior.BookID!=i.BookID)throw new ArgumentException("Stale or unavailable investigation");}else if(expected!=0)throw new ArgumentException("Missing investigation");i.Version=expected+1;rows[i.ID]=JsonSerializer.Serialize(i,CatalogueValidator.Json);if(!events.ContainsKey(i.ID))events[i.ID]=[];events[i.ID].Add(JsonSerializer.Serialize(new{operation,state=i,evaluation=result},CatalogueValidator.Json));}return Task.CompletedTask;}
public Task<string[]> Replay(int user,int book,Guid id){lock(sync){if(!rows.TryGetValue(id,out var json)||Parse(json).UserID!=user||Parse(json).BookID!=book)throw new UnauthorizedAccessException();return Task.FromResult(events[id].ToArray());}}
static Investigation Parse(string json)=>JsonSerializer.Deserialize<Investigation>(json,CatalogueValidator.Json)!;
}

View File

@ -0,0 +1,51 @@
-- Development only. All fixtures are fresh UUIDs and all data changes roll back.
SET NOCOUNT ON;
IF DB_NAME()<>'PlotDirector_Development' THROW 51000,'Wrong database',1;
DECLARE @user int,@book int,@project int,@catalogue varchar(80);
SELECT TOP(1) @user=a.UserID,@book=b.BookID,@project=b.ProjectID FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE a.IsActive=1 AND b.IsArchived=0 AND p.IsArchived=0 ORDER BY b.BookID;
SELECT TOP(1) @catalogue=Version FROM dbo.WriterInvestigationCatalogues;
IF @user IS NULL OR @catalogue IS NULL THROW 51000,'No authorised fixture scope',1;
DECLARE @phase int=0;
WHILE @phase<7
BEGIN
DECLARE @id uniqueidentifier=NEWID(),@other uniqueidentifier=NEWID(),@json nvarchar(max),@otherJson nvarchar(max),@expected int,@story int;
SET @json=(SELECT @id ID,@user UserID,@project ProjectID,@book BookID,@catalogue CatalogueVersion,1 Version,'Disposable SQL deletion fixture' Concern,JSON_QUERY('[{"Question":"fixture","Option":"one"}]') Answers,JSON_QUERY('["fixture-recommendation"]') Recommendations FOR JSON PATH,WITHOUT_ARRAY_WRAPPER);
SET @otherJson=JSON_MODIFY(@json,'$.ID',CONVERT(nvarchar(36),@other));
BEGIN TRY
BEGIN TRANSACTION;
SELECT @story=CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM dbo.Chapters WITH(HOLDLOCK) WHERE BookID=@book;
EXEC dbo.WriterInvestigation @Action='save',@UserID=@user,@BookID=@book,@ProjectID=@project,@ID=@id,@CatalogueVersion=@catalogue,@ExpectedVersion=0,@Json=@json,@Event=N'{"evaluation":{"Recommendations":["fixture"]}}';
SET @json=JSON_MODIFY(JSON_MODIFY(@json,'$.Version',2),'$.Answers[0].Option','revised');
EXEC dbo.WriterInvestigation @Action='save',@UserID=@user,@BookID=@book,@ProjectID=@project,@ID=@id,@CatalogueVersion=@catalogue,@ExpectedVersion=1,@Json=@json,@Event=N'{"operation":"revision","evaluation":{"Recommendations":["fixture"]}}';
EXEC dbo.WriterInvestigation @Action='save',@UserID=@user,@BookID=@book,@ProjectID=@project,@ID=@other,@CatalogueVersion=@catalogue,@ExpectedVersion=0,@Json=@otherJson,@Event=N'{}';
INSERT dbo.WriterInvestigationGuidance(InvestigationID,UserID,BookID,Version,Json,IsActive) VALUES(@id,@user,@book,1,N'{"Progress":{"fixture":"Done"}}',0);
IF @phase IN(1,2,3)
BEGIN
DECLARE @wrongUser int=CASE WHEN @phase=1 THEN -1 ELSE @user END,@wrongBook int=CASE WHEN @phase=2 THEN -1 ELSE @book END,@wrongProject int=CASE WHEN @phase=3 THEN -1 ELSE @project END;
EXEC dbo.WriterInvestigationDelete @UserID=@wrongUser,@ProjectID=@wrongProject,@BookID=@wrongBook,@ID=@id;
THROW 51999,'Scope violation accepted',1;
END;
EXEC dbo.WriterInvestigationDelete @UserID=@user,@ProjectID=@project,@BookID=@book,@ID=@id;
EXEC dbo.WriterInvestigationDelete @UserID=@user,@ProjectID=@project,@BookID=@book,@ID=@id;
IF EXISTS(SELECT 1 FROM dbo.WriterInvestigations WHERE ID=@id) OR EXISTS(SELECT 1 FROM dbo.WriterInvestigationEvents WHERE InvestigationID=@id) OR EXISTS(SELECT 1 FROM dbo.WriterInvestigationGuidance WHERE InvestigationID=@id) THROW 51999,'Investigation orphan remains',1;
IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations WHERE ID=@other AND Json=@otherJson) THROW 51999,'Unrelated investigation changed',1;
IF ISNULL(@story,0)<>ISNULL((SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM dbo.Chapters WHERE BookID=@book),0) THROW 51999,'Independent story changed',1;
IF @phase=4 BEGIN EXEC dbo.WriterInvestigation @Action='read',@UserID=@user,@BookID=@book,@ID=@id;THROW 51999,'Deleted resume accepted',1;END;
IF @phase IN(5,6)
BEGIN
SET @expected=CASE WHEN @phase=5 THEN 2 ELSE 0 END;
SET @json=JSON_MODIFY(@json,'$.Version',@expected+1);
EXEC dbo.WriterInvestigation @Action='save',@UserID=@user,@BookID=@book,@ProjectID=@project,@ID=@id,@CatalogueVersion=@catalogue,@ExpectedVersion=@expected,@Json=@json,@Event=N'{}';
THROW 51999,'Deleted answer or Begin recreated investigation',1;
END;
ROLLBACK;
END TRY
BEGIN CATCH
DECLARE @error int=ERROR_NUMBER();
IF XACT_STATE()<>0 ROLLBACK;
IF @phase=0 OR @error<>51000 THROW;
END CATCH;
IF EXISTS(SELECT 1 FROM dbo.WriterInvestigations WHERE ID IN(@id,@other)) OR EXISTS(SELECT 1 FROM dbo.WriterInvestigationDeletions WHERE ID=@id) THROW 51999,'SQL fixture leaked',1;
PRINT CONCAT('PASS deletion SQL scope/rollback case ',@phase);
SET @phase+=1;
END;

View File

@ -13,7 +13,13 @@ public sealed class WriterInvestigationsController(InvestigationAccess gate,IInv
async Task<bool> IsAdmin()=> (await HttpContext.RequestServices.GetRequiredService<IAuthorizationService>().AuthorizeAsync(User,null,"AdminOnly")).Succeeded;
async Task EnsureCatalogue(Catalogue c){if(c.Synthetic&&!await IsAdmin())throw new UnauthorizedAccessException();}
int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
async Task<IActionResult> Guard(Func<Task<IActionResult>> run){if(!gate.Enabled)return NotFound();Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";try{return await run();}catch(Exception e)when(e is UnauthorizedAccessException or KeyNotFoundException){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){Response.StatusCode=409;ViewData["Failure"]=e.Message;return View("Failure");}catch(ArgumentException e){Response.StatusCode=400;ViewData["Failure"]=e.Message;return View("Failure");}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){Response.StatusCode=503;ViewData["Failure"]="Investigations are temporarily unavailable. No unconfirmed save should be assumed successful. Return to Explore to resume.";return View("Failure");}}
async Task<IActionResult> Guard(Func<Task<IActionResult>> run){if(!gate.Enabled)return NotFound();Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";try{return await run();}catch(Exception e)when(e is UnauthorizedAccessException or KeyNotFoundException){return NotFound("This investigation was deleted or is no longer available. Return to Explore to choose another investigation.");}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){return NotFound("This investigation was deleted or is no longer available. Return to Explore to choose another investigation.");}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){Response.StatusCode=409;ViewData["Failure"]=e.Message;return View("Failure");}catch(ArgumentException e){Response.StatusCode=400;ViewData["Failure"]=e.Message;return View("Failure");}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){Response.StatusCode=503;ViewData["Failure"]="Investigations are temporarily unavailable. No unconfirmed save should be assumed successful. Return to Explore to resume.";return View("Failure");}}
[HttpPost("/Writer/Explore/Investigate/Delete"),ValidateAntiForgeryToken]
public Task<IActionResult> Delete(int projectId,int bookId,Guid id)=>Guard(async()=>{
if(id==Guid.Empty||await service.Project(bookId)!=projectId)return NotFound();
await repository.Delete(Author,projectId,bookId,id);
return Json(new{deleted=true,id});
});
[HttpGet("/Writer/Explore/Investigate")]
public Task<IActionResult> Index(int bookId,Guid? id,string? question=null,string? catalogueVersion=null)=>Guard(async()=>{
if(id.HasValue)ViewData["GuidanceVersion"]=(await guidance.Read(Author,null,bookId,id.Value))?.GuidanceVersion??0;

View File

@ -5,9 +5,10 @@ using PlotLine.Models.Investigations;
using PlotLine.Services.Investigations;
namespace PlotLine.Data;
public interface IInvestigationRepository
{Task<Catalogue?> Catalogue(string? version=null);Task Publish(string json,string actor);Task<IReadOnlyList<Investigation>> List(int user,int book);Task<Investigation?> Read(int user,int book,Guid id);Task Save(Investigation row,int expected,string operation,Evaluation result);Task<string[]> Replay(int user,int book,Guid id);}
{Task Delete(int user,int project,int book,Guid id);Task<Catalogue?> Catalogue(string? version=null);Task Publish(string json,string actor);Task<IReadOnlyList<Investigation>> List(int user,int book);Task<Investigation?> Read(int user,int book,Guid id);Task Save(Investigation row,int expected,string operation,Evaluation result);Task<string[]> Replay(int user,int book,Guid id);}
public sealed class InvestigationRepository(ISqlConnectionFactory factory):IInvestigationRepository
{
public async Task Delete(int user,int project,int book,Guid id){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterInvestigationDelete",new{UserID=user,ProjectID=project,BookID=book,ID=id},commandType:CommandType.StoredProcedure);}
public async Task<Catalogue?> Catalogue(string? version=null){using var db=factory.CreateConnection();var json=await db.QuerySingleOrDefaultAsync<string>("dbo.WriterInvestigationCatalogue",new{Action="read",Version=version},commandType:CommandType.StoredProcedure);return json==null?null:CatalogueValidator.Parse(json);}
public async Task Publish(string json,string actor){var c=CatalogueValidator.Parse(json);using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterInvestigationCatalogue",new{Action="publish",c.Version,Json=json,Actor=actor},commandType:CommandType.StoredProcedure);}
public async Task<IReadOnlyList<Investigation>> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync<string>("dbo.WriterInvestigation",new{Action="list",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).Select(Parse).ToArray();}

View File

@ -0,0 +1,106 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
-- Identity-only replay protection: no concern, answers, recommendations or story content.
IF OBJECT_ID('dbo.WriterInvestigationDeletions') IS NULL
CREATE TABLE dbo.WriterInvestigationDeletions(ID uniqueidentifier NOT NULL PRIMARY KEY,UserID int NOT NULL REFERENCES dbo.AppUser(UserID) ON DELETE CASCADE,BookID int NOT NULL REFERENCES dbo.Books(BookID) ON DELETE CASCADE,ProjectID int NOT NULL);
GO
CREATE OR ALTER PROCEDURE dbo.WriterInvestigationDelete @UserID int,@ProjectID int,@BookID int,@ID uniqueidentifier AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0) THROW 51000,'Investigation unavailable',1;
BEGIN TRY
BEGIN TRANSACTION;
DECLARE @lock int,@resource nvarchar(255)=N'WriterInvestigationBook:'+CONVERT(nvarchar(20),@BookID);
EXEC @lock=sys.sp_getapplock @Resource=@resource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000;
IF @lock<0 THROW 51002,'Investigation is busy. Retry deletion.',1;
IF EXISTS(SELECT 1 FROM dbo.WriterInvestigationDeletions WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ProjectID=@ProjectID) BEGIN COMMIT;RETURN;END;
IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ProjectID=@ProjectID) THROW 51000,'Investigation unavailable',1;
INSERT dbo.WriterInvestigationDeletions(ID,UserID,BookID,ProjectID) VALUES(@ID,@UserID,@BookID,@ProjectID);
DELETE FROM dbo.WriterInvestigationGuidance WHERE InvestigationID=@ID;
DELETE FROM dbo.WriterInvestigationEvents WHERE InvestigationID=@ID;
DELETE FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ProjectID=@ProjectID;
COMMIT;
END TRY
BEGIN CATCH
IF XACT_STATE()<>0 ROLLBACK;
THROW;
END CATCH;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterInvestigation @Action varchar(12),@UserID int,@BookID int,@ProjectID int=NULL,@ID uniqueidentifier=NULL,@CatalogueVersion varchar(80)=NULL,@ExpectedVersion int=NULL,@Json nvarchar(max)=NULL,@Event nvarchar(max)=NULL AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
DECLARE @ActualProject int;
SELECT @ActualProject=b.ProjectID FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.IsArchived=0;
IF @ActualProject IS NULL OR (@ProjectID IS NOT NULL AND @ProjectID<>@ActualProject) THROW 51000,'Investigation scope unavailable',1;
IF @Action='list' BEGIN SELECT TOP(100) Json FROM dbo.WriterInvestigations WHERE UserID=@UserID AND BookID=@BookID ORDER BY UpdatedUtc DESC,ID;RETURN;END;
IF @Action IN('read','events') BEGIN
IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID) THROW 51000,'Investigation unavailable',1;
IF @Action='read' SELECT Json FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID;
ELSE SELECT e.Event FROM dbo.WriterInvestigationEvents e JOIN dbo.WriterInvestigations i ON i.ID=e.InvestigationID WHERE i.ID=@ID AND i.UserID=@UserID AND i.BookID=@BookID ORDER BY e.Version;
RETURN;
END;
IF @Action<>'save' OR @ID IS NULL OR @ExpectedVersion<0 OR @ExpectedVersion>1000 OR ISJSON(@Json)<>1 OR ISJSON(@Event)<>1 OR DATALENGTH(@Json)>1000000 OR DATALENGTH(@Event)>2000000 THROW 51000,'Invalid investigation save',1;
IF ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.UserID')),-1)<>@UserID OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.BookID')),-1)<>@BookID OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.ProjectID')),-1)<>@ActualProject OR ISNULL(TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Json,'$.ID')),'00000000-0000-0000-0000-000000000000')<>@ID OR ISNULL(JSON_VALUE(@Json,'$.CatalogueVersion'),'')<>@CatalogueVersion OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.Version')),-1)<>@ExpectedVersion+1 THROW 51000,'Investigation identity mismatch',1;
BEGIN TRY
BEGIN TRANSACTION;
DECLARE @lock int,@resource nvarchar(255)=N'WriterInvestigationBook:'+CONVERT(nvarchar(20),@BookID);
EXEC @lock=sys.sp_getapplock @Resource=@resource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000;
IF @lock<0 THROW 51002,'Investigation is busy. Retry.',1;
IF EXISTS(SELECT 1 FROM dbo.WriterInvestigationDeletions WHERE ID=@ID) THROW 51000,'This investigation was deleted. Return to Explore.',1;
IF @ExpectedVersion=0 BEGIN
IF EXISTS(SELECT 1 FROM dbo.WriterInvestigations WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID) THROW 51002,'Investigation already exists; resume it',1;
INSERT dbo.WriterInvestigations(ID,UserID,ProjectID,BookID,CatalogueVersion,Version,Json) VALUES(@ID,@UserID,@ActualProject,@BookID,@CatalogueVersion,1,@Json);
END ELSE BEGIN
UPDATE dbo.WriterInvestigations SET Json=@Json,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND CatalogueVersion=@CatalogueVersion AND Version=@ExpectedVersion;
IF @@ROWCOUNT<>1 THROW 51002,'Another window changed this investigation. Your submitted answer has not replaced it.',1;
END;
INSERT dbo.WriterInvestigationEvents(InvestigationID,Version,Event) VALUES(@ID,@ExpectedVersion+1,@Event);
COMMIT;
END TRY BEGIN CATCH IF XACT_STATE()<>0 ROLLBACK;THROW;END CATCH;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterInvestigationGuidanceState
@Action varchar(12),@UserID int,@ProjectID int=NULL,@BookID int=NULL,@ID uniqueidentifier=NULL,
@ExpectedVersion int=NULL,@Json nvarchar(max)=NULL AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
IF @Action='read' BEGIN
SELECT TOP(1) i.ID,i.ProjectID,i.BookID,b.BookTitle,
JSON_MODIFY(JSON_MODIFY(JSON_MODIFY(i.Json,'$.Answers',JSON_QUERY((SELECT a.Question,a.[Option] FROM OPENJSON(i.Json,'$.Answers') WITH(Question varchar(100),[Option] varchar(100)) a FOR JSON PATH))),'$.Presented',NULL),'$.Recommendations',NULL) InvestigationJson,
CASE WHEN e.Event IS NULL THEN NULL ELSE (SELECT JSON_VALUE(e.Event,'$.evaluation.Outcome') Outcome,JSON_QUERY(e.Event,'$.evaluation.Recommendations') Recommendations FOR JSON PATH,WITHOUT_ARRAY_WRAPPER) END EvaluationJson,g.Json GuidanceJson,ISNULL(g.Version,0) GuidanceVersion,ISNULL(g.IsActive,0) IsActive,ISNULL(g.Finished,0) Finished
FROM dbo.WriterInvestigations i
JOIN dbo.Books b ON b.BookID=i.BookID AND b.ProjectID=i.ProjectID AND b.IsArchived=0
JOIN dbo.Projects p ON p.ProjectID=i.ProjectID AND p.IsArchived=0
JOIN dbo.ProjectUserAccess a ON a.ProjectID=i.ProjectID AND a.UserID=@UserID AND a.IsActive=1
LEFT JOIN dbo.WriterInvestigationGuidance g ON g.InvestigationID=i.ID AND g.UserID=@UserID AND g.BookID=i.BookID
OUTER APPLY(SELECT TOP(1) Event FROM dbo.WriterInvestigationEvents WHERE InvestigationID=i.ID AND Version=i.Version) e
WHERE i.UserID=@UserID AND (@BookID IS NULL OR i.BookID=@BookID) AND (@ProjectID IS NULL OR i.ProjectID=@ProjectID)
AND ((@ID IS NOT NULL AND i.ID=@ID) OR (@ID IS NULL AND g.IsActive=1))
AND (@ID IS NOT NULL OR @ProjectID IS NOT NULL OR @BookID IS NOT NULL)
ORDER BY g.UpdatedUtc DESC,i.ID;
RETURN;
END;
IF @Action NOT IN('activate','save','dismiss','finish') OR @ID IS NULL OR @BookID IS NULL OR @ExpectedVersion IS NULL OR ISJSON(@Json)<>1 OR DATALENGTH(@Json)>65536 THROW 51000,'Invalid guidance request',1;
BEGIN TRY
BEGIN TRANSACTION;
DECLARE @lock int,@resource nvarchar(255)=N'WriterInvestigationBook:'+CONVERT(nvarchar(20),@BookID);
EXEC @lock=sys.sp_getapplock @Resource=@resource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000;
IF @lock<0 THROW 51002,'Investigation is busy. Retry.',1;
IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations i JOIN dbo.Books b ON b.BookID=i.BookID AND b.ProjectID=i.ProjectID AND b.IsArchived=0 JOIN dbo.Projects p ON p.ProjectID=i.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=i.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE i.ID=@ID AND i.UserID=@UserID AND i.BookID=@BookID AND (@ProjectID IS NULL OR i.ProjectID=@ProjectID)) THROW 51000,'Guidance unavailable',1;
DECLARE @actual int;
SELECT @actual=Version FROM dbo.WriterInvestigationGuidance WITH(UPDLOCK,HOLDLOCK) WHERE InvestigationID=@ID AND UserID=@UserID AND BookID=@BookID;
IF ISNULL(@actual,0)<>@ExpectedVersion THROW 51002,'Guidance changed in another window. Refresh before trying again.',1;
IF @Action='activate' UPDATE dbo.WriterInvestigationGuidance SET IsActive=0 WHERE UserID=@UserID AND BookID=@BookID AND IsActive=1 AND InvestigationID<>@ID;
IF @actual IS NULL BEGIN
IF @Action<>'activate' THROW 51000,'Activate this investigation first',1;
INSERT dbo.WriterInvestigationGuidance(InvestigationID,UserID,BookID,Version,Json) VALUES(@ID,@UserID,@BookID,1,@Json);
END ELSE UPDATE dbo.WriterInvestigationGuidance SET Json=@Json,Version=Version+1,UpdatedUtc=SYSUTCDATETIME(),
IsActive=CASE WHEN @Action='activate' THEN 1 WHEN @Action IN('dismiss','finish') THEN 0 ELSE IsActive END,
Finished=CASE WHEN @Action='activate' THEN 0 WHEN @Action='finish' THEN 1 ELSE Finished END
WHERE InvestigationID=@ID AND UserID=@UserID AND BookID=@BookID;
COMMIT;
END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH;
END;
GO

View File

@ -0,0 +1,112 @@
-- Serialize UUID reuse across authorised books as well as writes within a book.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.WriterInvestigationDelete @UserID int,@ProjectID int,@BookID int,@ID uniqueidentifier AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0) THROW 51000,'Investigation unavailable',1;
BEGIN TRY
BEGIN TRANSACTION;
DECLARE @lock int,@resource nvarchar(255)=N'WriterInvestigationBook:'+CONVERT(nvarchar(20),@BookID);
EXEC @lock=sys.sp_getapplock @Resource=@resource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000;
IF @lock<0 THROW 51002,'Investigation is busy. Retry deletion.',1;
DECLARE @identityResource nvarchar(255)=N'WriterInvestigation:'+CONVERT(nvarchar(36),@ID);
EXEC @lock=sys.sp_getapplock @Resource=@identityResource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000;
IF @lock<0 THROW 51002,'Investigation identity is busy. Retry.',1;
IF EXISTS(SELECT 1 FROM dbo.WriterInvestigationDeletions WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ProjectID=@ProjectID) BEGIN COMMIT;RETURN;END;
IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ProjectID=@ProjectID) THROW 51000,'Investigation unavailable',1;
INSERT dbo.WriterInvestigationDeletions(ID,UserID,BookID,ProjectID) VALUES(@ID,@UserID,@BookID,@ProjectID);
DELETE FROM dbo.WriterInvestigationGuidance WHERE InvestigationID=@ID;
DELETE FROM dbo.WriterInvestigationEvents WHERE InvestigationID=@ID;
DELETE FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ProjectID=@ProjectID;
COMMIT;
END TRY
BEGIN CATCH
IF XACT_STATE()<>0 ROLLBACK;
THROW;
END CATCH;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterInvestigation @Action varchar(12),@UserID int,@BookID int,@ProjectID int=NULL,@ID uniqueidentifier=NULL,@CatalogueVersion varchar(80)=NULL,@ExpectedVersion int=NULL,@Json nvarchar(max)=NULL,@Event nvarchar(max)=NULL AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
DECLARE @ActualProject int;
SELECT @ActualProject=b.ProjectID FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.IsArchived=0;
IF @ActualProject IS NULL OR (@ProjectID IS NOT NULL AND @ProjectID<>@ActualProject) THROW 51000,'Investigation scope unavailable',1;
IF @Action='list' BEGIN SELECT TOP(100) Json FROM dbo.WriterInvestigations WHERE UserID=@UserID AND BookID=@BookID ORDER BY UpdatedUtc DESC,ID;RETURN;END;
IF @Action IN('read','events') BEGIN
IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID) THROW 51000,'Investigation unavailable',1;
IF @Action='read' SELECT Json FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID;
ELSE SELECT e.Event FROM dbo.WriterInvestigationEvents e JOIN dbo.WriterInvestigations i ON i.ID=e.InvestigationID WHERE i.ID=@ID AND i.UserID=@UserID AND i.BookID=@BookID ORDER BY e.Version;
RETURN;
END;
IF @Action<>'save' OR @ID IS NULL OR @ExpectedVersion<0 OR @ExpectedVersion>1000 OR ISJSON(@Json)<>1 OR ISJSON(@Event)<>1 OR DATALENGTH(@Json)>1000000 OR DATALENGTH(@Event)>2000000 THROW 51000,'Invalid investigation save',1;
IF ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.UserID')),-1)<>@UserID OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.BookID')),-1)<>@BookID OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.ProjectID')),-1)<>@ActualProject OR ISNULL(TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Json,'$.ID')),'00000000-0000-0000-0000-000000000000')<>@ID OR ISNULL(JSON_VALUE(@Json,'$.CatalogueVersion'),'')<>@CatalogueVersion OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.Version')),-1)<>@ExpectedVersion+1 THROW 51000,'Investigation identity mismatch',1;
BEGIN TRY
BEGIN TRANSACTION;
DECLARE @lock int,@resource nvarchar(255)=N'WriterInvestigationBook:'+CONVERT(nvarchar(20),@BookID);
EXEC @lock=sys.sp_getapplock @Resource=@resource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000;
IF @lock<0 THROW 51002,'Investigation is busy. Retry.',1;
DECLARE @identityResource nvarchar(255)=N'WriterInvestigation:'+CONVERT(nvarchar(36),@ID);
EXEC @lock=sys.sp_getapplock @Resource=@identityResource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000;
IF @lock<0 THROW 51002,'Investigation identity is busy. Retry.',1;
IF EXISTS(SELECT 1 FROM dbo.WriterInvestigationDeletions WHERE ID=@ID) THROW 51000,'This investigation was deleted. Return to Explore.',1;
IF @ExpectedVersion=0 BEGIN
IF EXISTS(SELECT 1 FROM dbo.WriterInvestigations WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID) THROW 51002,'Investigation already exists; resume it',1;
INSERT dbo.WriterInvestigations(ID,UserID,ProjectID,BookID,CatalogueVersion,Version,Json) VALUES(@ID,@UserID,@ActualProject,@BookID,@CatalogueVersion,1,@Json);
END ELSE BEGIN
UPDATE dbo.WriterInvestigations SET Json=@Json,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND CatalogueVersion=@CatalogueVersion AND Version=@ExpectedVersion;
IF @@ROWCOUNT<>1 THROW 51002,'Another window changed this investigation. Your submitted answer has not replaced it.',1;
END;
INSERT dbo.WriterInvestigationEvents(InvestigationID,Version,Event) VALUES(@ID,@ExpectedVersion+1,@Event);
COMMIT;
END TRY BEGIN CATCH IF XACT_STATE()<>0 ROLLBACK;THROW;END CATCH;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterInvestigationGuidanceState
@Action varchar(12),@UserID int,@ProjectID int=NULL,@BookID int=NULL,@ID uniqueidentifier=NULL,
@ExpectedVersion int=NULL,@Json nvarchar(max)=NULL AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
IF @Action='read' BEGIN
SELECT TOP(1) i.ID,i.ProjectID,i.BookID,b.BookTitle,
JSON_MODIFY(JSON_MODIFY(JSON_MODIFY(i.Json,'$.Answers',JSON_QUERY((SELECT a.Question,a.[Option] FROM OPENJSON(i.Json,'$.Answers') WITH(Question varchar(100),[Option] varchar(100)) a FOR JSON PATH))),'$.Presented',NULL),'$.Recommendations',NULL) InvestigationJson,
CASE WHEN e.Event IS NULL THEN NULL ELSE (SELECT JSON_VALUE(e.Event,'$.evaluation.Outcome') Outcome,JSON_QUERY(e.Event,'$.evaluation.Recommendations') Recommendations FOR JSON PATH,WITHOUT_ARRAY_WRAPPER) END EvaluationJson,g.Json GuidanceJson,ISNULL(g.Version,0) GuidanceVersion,ISNULL(g.IsActive,0) IsActive,ISNULL(g.Finished,0) Finished
FROM dbo.WriterInvestigations i
JOIN dbo.Books b ON b.BookID=i.BookID AND b.ProjectID=i.ProjectID AND b.IsArchived=0
JOIN dbo.Projects p ON p.ProjectID=i.ProjectID AND p.IsArchived=0
JOIN dbo.ProjectUserAccess a ON a.ProjectID=i.ProjectID AND a.UserID=@UserID AND a.IsActive=1
LEFT JOIN dbo.WriterInvestigationGuidance g ON g.InvestigationID=i.ID AND g.UserID=@UserID AND g.BookID=i.BookID
OUTER APPLY(SELECT TOP(1) Event FROM dbo.WriterInvestigationEvents WHERE InvestigationID=i.ID AND Version=i.Version) e
WHERE i.UserID=@UserID AND (@BookID IS NULL OR i.BookID=@BookID) AND (@ProjectID IS NULL OR i.ProjectID=@ProjectID)
AND ((@ID IS NOT NULL AND i.ID=@ID) OR (@ID IS NULL AND g.IsActive=1))
AND (@ID IS NOT NULL OR @ProjectID IS NOT NULL OR @BookID IS NOT NULL)
ORDER BY g.UpdatedUtc DESC,i.ID;
RETURN;
END;
IF @Action NOT IN('activate','save','dismiss','finish') OR @ID IS NULL OR @BookID IS NULL OR @ExpectedVersion IS NULL OR ISJSON(@Json)<>1 OR DATALENGTH(@Json)>65536 THROW 51000,'Invalid guidance request',1;
BEGIN TRY
BEGIN TRANSACTION;
DECLARE @lock int,@resource nvarchar(255)=N'WriterInvestigationBook:'+CONVERT(nvarchar(20),@BookID);
EXEC @lock=sys.sp_getapplock @Resource=@resource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000;
IF @lock<0 THROW 51002,'Investigation is busy. Retry.',1;
DECLARE @identityResource nvarchar(255)=N'WriterInvestigation:'+CONVERT(nvarchar(36),@ID);
EXEC @lock=sys.sp_getapplock @Resource=@identityResource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000;
IF @lock<0 THROW 51002,'Investigation identity is busy. Retry.',1;
IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations i JOIN dbo.Books b ON b.BookID=i.BookID AND b.ProjectID=i.ProjectID AND b.IsArchived=0 JOIN dbo.Projects p ON p.ProjectID=i.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=i.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE i.ID=@ID AND i.UserID=@UserID AND i.BookID=@BookID AND (@ProjectID IS NULL OR i.ProjectID=@ProjectID)) THROW 51000,'Guidance unavailable',1;
DECLARE @actual int;
SELECT @actual=Version FROM dbo.WriterInvestigationGuidance WITH(UPDLOCK,HOLDLOCK) WHERE InvestigationID=@ID AND UserID=@UserID AND BookID=@BookID;
IF ISNULL(@actual,0)<>@ExpectedVersion THROW 51002,'Guidance changed in another window. Refresh before trying again.',1;
IF @Action='activate' UPDATE dbo.WriterInvestigationGuidance SET IsActive=0 WHERE UserID=@UserID AND BookID=@BookID AND IsActive=1 AND InvestigationID<>@ID;
IF @actual IS NULL BEGIN
IF @Action<>'activate' THROW 51000,'Activate this investigation first',1;
INSERT dbo.WriterInvestigationGuidance(InvestigationID,UserID,BookID,Version,Json) VALUES(@ID,@UserID,@BookID,1,@Json);
END ELSE UPDATE dbo.WriterInvestigationGuidance SET Json=@Json,Version=Version+1,UpdatedUtc=SYSUTCDATETIME(),
IsActive=CASE WHEN @Action='activate' THEN 1 WHEN @Action IN('dismiss','finish') THEN 0 ELSE IsActive END,
Finished=CASE WHEN @Action='activate' THEN 0 WHEN @Action='finish' THEN 1 ELSE Finished END
WHERE InvestigationID=@ID AND UserID=@UserID AND BookID=@BookID;
COMMIT;
END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH;
END;
GO

View File

@ -17,7 +17,8 @@
<div class="writer3-divider writer-explore-divider" data-explore-divider role="separator" tabindex="0" aria-orientation="vertical" aria-label="Resize discovery and investigation panels" aria-controls="explore-discovery explore-concern" aria-describedby="explore-resize-help" aria-valuemin="25" aria-valuemax="75" aria-valuenow="50"><span id="explore-resize-help" class="visually-hidden">Left and right arrows resize the discovery panel. Shift uses larger steps. Home and End move to the width limits.</span></div>
<section id="explore-concern" tabindex="-1" class="writer3-panel" aria-label="Explore a concern"><h2>Explore a concern</h2><p>You do not need to know the answer yet. Start with what is troubling you.</p>
@if(InvestigationAccess.Enabled&&Model.BookID.HasValue){
<div data-explore-investigation data-book="@Model.BookID">
<div data-explore-investigation data-book="@Model.BookID" data-project="@Model.ProjectID" data-delete-url="@Url.Action("Delete","WriterInvestigations")">
@Html.AntiForgeryToken()
<div class="writer21-tabs" role="tablist" aria-label="Investigations"><button type="button" role="tab" aria-selected="true" data-explore-tab="new">New investigation</button><button type="button" role="tab" aria-selected="false" data-explore-tab="saved">Saved investigations</button></div>
<p data-explore-message role="status"></p>
<div data-explore-pane="new"><div data-explore-journey data-opening-url="@Url.Action("Opening","WriterInvestigations",new{bookId=Model.BookID})"><p>Loading starting concerns…</p></div></div>

View File

@ -63,7 +63,7 @@
<button class="btn btn-outline-secondary" name="operation" value="save">Save for later</button></div></form>
}
@if(row!=null){<form asp-controller="InvestigationCompanion" asp-action="Update" method="post" data-guidance-activate><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@ViewData["GuidanceVersion"]"/><button class="btn btn-outline-secondary" name="operation" value="activate">Keep this investigation alongside my work</button></form>}
<p class="writer3-caption"><a data-explore-landing asp-controller="Writer" asp-action="Explore" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">Return to Explore</a> · <a data-explore-landing asp-action="Index" asp-route-bookId="@Model.BookID">Start another investigation</a></p>
<p class="writer3-caption"><a data-explore-landing asp-controller="Writer" asp-action="Explore" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">Return to Explore</a> · <a data-explore-landing asp-action="Index" asp-route-bookId="@Model.BookID">Start another investigation</a> @if(row!=null){<button type="button" class="btn btn-link btn-sm" data-investigation-delete="@row.ID" data-investigation-title="@Model.Catalogue.Concerns.Single(x=>x.Id==row.Concern).Text">Discard investigation</button>}</p>
</section>
<aside class="writer3-panel" aria-label="Your investigations">
@if(row!=null){<h2>Your answers</h2><p>Your answers are saved when you continue. Changing one recomputes the investigation; earlier versions remain in its history.</p><ol>@foreach(var a in row.Answers){var q=Model.Catalogue.Questions.Single(q=>q.Id==a.Question);<li><a asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-id="@row.ID" asp-route-question="@a.Question">@q.Text</a><p>@q.Options.Single(o=>o.Id==a.Option).Text</p></li>}</ol>}

View File

@ -28,3 +28,10 @@
.writer21-task p{white-space:pre-wrap}
@media(max-width:1150px){.investigation-journey{grid-template-columns:1fr}.writer21-board{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:800px){[data-explore-layout]{grid-template-columns:minmax(0,1fr);gap:1rem}[data-explore-divider]{display:none}.writer21-board{grid-template-columns:1fr}}
[data-explore-saved] article{position:relative;padding-right:3rem}
.writer-investigation-actions{position:absolute;right:0;top:.75rem}
.writer-investigation-actions>summary{list-style:none;cursor:pointer;padding:.25rem .65rem;border-radius:4px}
.writer-investigation-actions>summary::-webkit-details-marker{display:none}
.writer-investigation-actions[open]>button{position:absolute;right:0;z-index:2;min-width:210px;display:flex;align-items:center;gap:.4rem;background:var(--pd-surface);border:1px solid var(--pd-border);box-shadow:var(--pd-shadow)}
@media(pointer:coarse){.writer-investigation-actions>summary{min-width:44px;min-height:44px}}

View File

@ -3,6 +3,7 @@
const root=document.querySelector('[data-investigation-companion]');if(!root)return;
const layout=root.closest('[data-help-layout]'),content=root.querySelector('[data-guidance-content]'),message=root.querySelector('[data-guidance-message]'),tab=root.querySelector('[data-guidance-expand]'),splitter=layout.querySelector('[data-guidance-resize]');
const token=root.querySelector('[name=__RequestVerificationToken]').value;
const deletedIds=new Set();
let current=null,resultsUrl=null,epoch=0,request,busy=false,preference={},hydrated=false,hasSnapshot=true;
const storageKey=()=>`plotdirector.investigationPanel.v1.${root.dataset.user}.${current?.bookID||root.dataset.book||root.dataset.project||'none'}`;
const read=()=>{try{const value=JSON.parse(localStorage.getItem(storageKey()));if(!value||typeof value!=='object'||Array.isArray(value))return {};if(!value.positions||typeof value.positions!=='object'||Array.isArray(value.positions))value.positions={};return value;}catch{return {};}};
@ -48,12 +49,12 @@
const priorId=current?.id;const stamp=++epoch;request?.abort();request=new AbortController();
try{const url=new URL(root.dataset.summaryUrl,location.origin);if(root.dataset.project)url.searchParams.set('projectId',root.dataset.project);if(root.dataset.book)url.searchParams.set('bookId',root.dataset.book);
const response=await fetch(url,{cache:'no-store',signal:request.signal});if(response.redirected||response.status===401){throw Error('Sign in again to resume your saved investigation.');}if(!response.ok)throw Error('Saved guidance could not be loaded. Retry when your connection returns.');const data=await response.json();if(stamp!==epoch)return;
current=data.active?data.summary:null;hasSnapshot=data.hasSnapshot!==false;resultsUrl=data.resultsUrl;preference=read();render();restorePanel(!hydrated||priorId!==current?.id);hydrated=true;window.PlotDirectorGuidanceSummary=data;window.dispatchEvent(new CustomEvent("plotdirector:guidance-summary",{detail:data}));
if(data.active&&deletedIds.has(data.summary?.id)){current=null;render();panel.hide();window.PlotDirectorGuidanceSummary={active:false};window.dispatchEvent(new CustomEvent('plotdirector:guidance-summary',{detail:{active:false}}));return;}current=data.active?data.summary:null;hasSnapshot=data.hasSnapshot!==false;resultsUrl=data.resultsUrl;preference=read();render();restorePanel(!hydrated||priorId!==current?.id);hydrated=true;window.PlotDirectorGuidanceSummary=data;window.dispatchEvent(new CustomEvent("plotdirector:guidance-summary",{detail:data}));
}catch(e){if(e.name==='AbortError'||stamp!==epoch)return;current=null;content.replaceChildren(element('p',e.message),btn('Retry',load),startLink());panel.hide();}
}
async function mutate(operation,extra={}){
if(busy||!current)return;busy=true;const selected=current.id;failure('Saving…');root.querySelectorAll('[data-guidance-content] button,[data-guidance-content] select,[data-guidance-picker] select').forEach(n=>n.disabled=true);
try{const data=new URLSearchParams({__RequestVerificationToken:token,bookId:current.bookID,id:current.id,version:current.version,operation,...extra});const response=await fetch(root.dataset.updateUrl,{method:'POST',body:data,cache:'no-store'});if(!response.ok){let body;try{body=await response.json();}catch{}throw Error(body?.message||'Your change was not confirmed. Retry or refresh your saved guidance.');}if(current?.id===selected){if(operation==='dismiss'||operation==='finish')panel.hide();await load();await discover();}}
try{const data=new URLSearchParams({__RequestVerificationToken:token,bookId:current.bookID,id:current.id,version:current.version,operation,...extra});const response=await fetch(root.dataset.updateUrl,{method:'POST',body:data,cache:'no-store'});if(response.status===404){const id=current?.id,book=current?.bookID;if(id)window.dispatchEvent(new CustomEvent('plotdirector:investigation-deleted',{detail:{id,book}}));await load();failure('This investigation was deleted or is no longer available.');return;}if(!response.ok){let body;try{body=await response.json();}catch{}throw Error(body?.message||'Your change was not confirmed. Retry or refresh your saved guidance.');}if(current?.id===selected){if(operation==='dismiss'||operation==='finish')panel.hide();await load();await discover();}}
catch(e){render();failure(e.message);}finally{busy=false;}
}
let scrollFrame=0;content.addEventListener('scroll',()=>{if(scrollFrame||!current)return;scrollFrame=requestAnimationFrame(()=>{scrollFrame=0;if(!current||panel.state!=='open')return;preference.positions||={};preference.positions[current.id]=content.scrollTop;const keys=Object.keys(preference.positions);if(keys.length>20)delete preference.positions[keys[0]];save();});});
@ -63,5 +64,7 @@
async function discover(){const area=document.querySelector('[data-my-investigations]');if(!area)return;const list=area.querySelector('[data-saved-investigations]');try{const rows=await saved(area.dataset.book);list.replaceChildren();if(!rows.length)list.append(element('p','No saved investigations for this book yet. Begin a concern above.'));for(const item of rows){const card=element('article');card.append(element('h3',item.concern),element('p',item.status+' · Last activity: '+new Date(item.updatedUtc).toLocaleString()+' · '+item.id.slice(0,8)));const form=element('form');form.method='post';form.action=item.continueUrl;form.dataset.guidanceActivate='';for(const[name,value]of Object.entries({__RequestVerificationToken:token,bookId:item.bookID,id:item.id,version:item.guidanceVersion,operation:'activate'})){const input=element('input');input.type='hidden';input.name=name;input.value=value;form.append(input);}form.append(element('button','Continue','btn btn-primary'));const results=element('a',item.hasResults?'Original results':'View saved investigation');results.href=item.resultsUrl;card.append(form,results);list.append(card);}}catch{list.replaceChildren(element('p','Your saved investigations could not be loaded.'),btn('Retry',discover));}}
document.addEventListener('submit',e=>{const form=e.target;if(!form.matches('[data-guidance-navigation],[data-guidance-activate]'))return;if(form.dataset.pending==='true'){e.preventDefault();return;}form.dataset.pending='true';form.setAttribute('aria-busy','true');const submit=e.submitter;if(submit?.name){const hidden=element('input');hidden.type='hidden';hidden.name=submit.name;hidden.value=submit.value;form.append(hidden);}const id=form.querySelector('[name=id]')?.value||new URL(form.action).searchParams.get('id');if(id)try{sessionStorage.setItem(pendingKey,id);}catch{}requestAnimationFrame(()=>{form.querySelectorAll('button').forEach(b=>{b.dataset.originalText=b.textContent;b.textContent='Opening…';b.disabled=true;});});});
window.addEventListener('pageshow',()=>document.querySelectorAll('[data-pending=true]').forEach(f=>{delete f.dataset.pending;f.removeAttribute('aria-busy');f.querySelectorAll('button').forEach(b=>{b.disabled=false;b.textContent=b.dataset.originalText||b.textContent;});}));discover();
window.addEventListener('plotdirector:investigation-deleted',event=>{const {id,book}=event.detail;deletedIds.add(id);try{const key=`plotdirector.investigationPanel.v1.${root.dataset.user}.${book}`,prefs=JSON.parse(localStorage.getItem(key));if(prefs?.positions){delete prefs.positions[id];localStorage.setItem(key,JSON.stringify(prefs));}const active='writer.explore.active.'+book;if(sessionStorage.getItem(active)===id)sessionStorage.removeItem(active);if(sessionStorage.getItem(pendingKey)===id)sessionStorage.removeItem(pendingKey);}catch{}if(current?.id===id){++epoch;request?.abort();current=null;content.replaceChildren();panel.hide();window.PlotDirectorGuidanceSummary={active:false};window.dispatchEvent(new CustomEvent('plotdirector:guidance-summary',{detail:{active:false}}));}});
window.addEventListener('storage',event=>{if(event.key!=='plotdirector.investigation.deleted.'+root.dataset.user||!event.newValue)return;try{const data=JSON.parse(event.newValue),selected=data.id===current?.id;window.dispatchEvent(new CustomEvent('plotdirector:investigation-deleted',{detail:data}));if(selected){current=null;content.replaceChildren();panel.hide();window.PlotDirectorGuidanceSummary={active:false};window.dispatchEvent(new CustomEvent('plotdirector:guidance-summary',{detail:{active:false}}));load();}}catch{}});
window.addEventListener('investigation-guidance-updated',()=>load());window.addEventListener('pageshow',e=>{if(e.persisted)load();});load();
})();

View File

@ -111,7 +111,7 @@
new ResizeObserver(() => {
if (workspace.clientWidth === measuredWidth) return;
measuredWidth = workspace.clientWidth;
endDrag(); stop(); measure();
endDrag(); measure(); // Keep an in-flight glide when a deleted guidance panel changes available width.
}).observe(workspace);
window.addEventListener('resize', () => { endDrag(); stop(); measure(); });
window.addEventListener('pageshow', event => {

View File

@ -1,12 +1,36 @@
// Uses the established versioned investigation engine; only the presentation is replaced.
(()=>{const root=document.querySelector('[data-explore-investigation]');if(!root)return;
const journey=root.querySelector('[data-explore-journey]'),message=root.querySelector('[data-explore-message]'),saved=root.querySelector('[data-explore-saved]'),workspace=root.closest('.writer3-workspace');let busy=false,dirty=false,current=null;
function tab(name){for(const b of root.querySelectorAll('[data-explore-tab]'))b.setAttribute('aria-selected',String(b.dataset.exploreTab===name));for(const p of root.querySelectorAll('[data-explore-pane]'))p.hidden=p.dataset.explorePane!==name;}
async function history(){const scroll=saved.scrollTop;try{const response=await fetch('/InvestigationCompanion/Saved?bookId='+root.dataset.book,{cache:'no-store'});if(!response.ok)throw Error();const rows=await response.json();saved.replaceChildren();if(!rows.length)saved.textContent='No saved investigations yet.';for(const row of rows){const card=document.createElement('article'),h=document.createElement('h4'),p=document.createElement('p'),a=document.createElement('a');h.textContent=row.concern;p.textContent=row.status+' · '+new Date(row.updatedUtc).toLocaleString();a.textContent=row.hasResults?'Continue / view results':'Continue';a.href=row.resultsUrl;card.append(h,p,a);saved.append(card);}saved.scrollTop=scroll;}catch{saved.textContent='Saved investigations could not load. Select this tab to retry.';}}
async function load(url,options={}){if(busy)return;busy=true;root.setAttribute('aria-busy','true');message.textContent='Loading investigation…';try{const response=await fetch(url,{...options,cache:'no-store',headers:{'X-Writer-Explore':'inline','X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw Error(response.status===409?'Another window changed this investigation. Your text is retained. Open Saved investigations to resume the latest version.':response.status===401?'Sign in again, then resume your saved investigation.':'The investigation could not be updated. Your entered answer remains here. Retry when connected.');const doc=new DOMParser().parseFromString(await response.text(),'text/html'),inline=doc.querySelector('[data-inline-investigation]');if(!inline&&!doc.querySelector('form[action*="Investigate/Start"]'))throw Error('Your session may have expired. Sign in and resume from Saved investigations.');journey.replaceChildren(...(inline?[inline]:doc.body.childNodes));current=inline?.dataset.inlineInvestigation||null;workspace.classList.toggle('writer21-investigating',!!current);workspace.dispatchEvent(new CustomEvent('writer-explore:state',{detail:{active:!!current}}));dirty=false;tab('new');message.textContent='';const address=new URL(location.href);if(current)address.searchParams.set('investigation',current);else address.searchParams.delete('investigation');if(address.hash==='#new-investigation')address.hash='';window.history.replaceState(window.history.state,'',address);try{if(current)sessionStorage.setItem('writer.explore.active.'+root.dataset.book,current);else sessionStorage.removeItem('writer.explore.active.'+root.dataset.book);}catch{}await history();}catch(error){message.textContent=error.message;}finally{busy=false;root.removeAttribute('aria-busy');}}
const journey=root.querySelector('[data-explore-journey]'),message=root.querySelector('[data-explore-message]'),saved=root.querySelector('[data-explore-saved]'),workspace=root.closest('.writer3-workspace');let busy=false,dirty=false,current=null,pendingDeleted=false,deleteDialogOpen=false;
function release(){busy=false;if(pendingDeleted){pendingDeleted=false;void load(journey.dataset.openingUrl);}}
const deletedIds=new Set();
function tab(name){const deletionKey='plotdirector.investigation.deleted.'+workspace.closest('[data-layout-owner]').dataset.layoutOwner;
async function removed(id){
deletedIds.add(id);
window.dispatchEvent(new CustomEvent("plotdirector:investigation-deleted",{detail:{id,book:root.dataset.book}}));
try{const key='writer.explore.active.'+root.dataset.book;if(sessionStorage.getItem(key)===id)sessionStorage.removeItem(key);const pending='plotdirector.guidance.open.'+workspace.closest('[data-layout-owner]').dataset.layoutOwner;if(sessionStorage.getItem(pending)===id)sessionStorage.removeItem(pending);}catch{}
if(window.PlotDirectorGuidanceSummary?.summary?.id===id){window.PlotDirectorGuidanceSummary={active:false};window.dispatchEvent(new CustomEvent('plotdirector:guidance-summary',{detail:{active:false}}));}
window.dispatchEvent(new Event('investigation-guidance-updated'));
if(current===id){dirty=false;if(busy){pendingDeleted=true;return;}await load(journey.dataset.openingUrl);}else await history();
}
root.addEventListener('click',async event=>{
const button=event.target.closest('[data-investigation-delete]');if(!button)return;event.preventDefault();if(busy||deleteDialogOpen)return;deleteDialogOpen=true;
const listOpen=root.querySelector('[data-explore-tab="saved"]').getAttribute('aria-selected')==='true',listScroll=saved.scrollTop;
const id=button.dataset.investigationDelete,title=button.dataset.investigationTitle||'Current investigation';
const result=await window.PlotDirectorDialogs.choose({title:'Delete this investigation?',message:title+'\n\nThis will permanently delete the investigation, its answers and its investigation history. This cannot be undone. Changes you have already made to your story will not be affected.',actions:[{value:'cancel',label:'Cancel'},{value:'delete',label:'Delete investigation',className:'btn-danger',run:async()=>{
if(busy)throw Error('Wait for the current investigation request to finish, then retry.');busy=true;
try{const body=new URLSearchParams({id,bookId:root.dataset.book,projectId:root.dataset.project,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});const response=await fetch(root.dataset.deleteUrl,{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(30000)}).catch(()=>{throw Error('Deletion was not confirmed. Check your connection, then refresh or retry.');});if(response.redirected||response.status===401)throw Error('Sign in again before deleting this investigation. No deletion was confirmed.');if(!response.ok)throw Error('Deletion could not be confirmed. The investigation remains listed. Retry or refresh before continuing.');const data=await response.json().catch(()=>null);if(data?.deleted!==true||data.id!==id)throw Error('Deletion was not confirmed. Refresh before retrying.');return true;}finally{release();}
}}]}).finally(()=>deleteDialogOpen=false);
if(result?.value!=='delete')return;
try{localStorage.setItem(deletionKey,JSON.stringify({id,book:root.dataset.book,at:Date.now()}));}catch{}
await removed(id);if(listOpen){tab('saved');saved.scrollTop=listScroll;root.querySelector('[data-explore-tab="saved"]')?.focus({preventScroll:true});}else journey.querySelector('[name=concern]')?.focus({preventScroll:true});
});
window.addEventListener('storage',event=>{if(event.key!==deletionKey||!event.newValue)return;try{const data=JSON.parse(event.newValue);if(String(data.book)===root.dataset.book)void removed(data.id);}catch{}});
for(const b of root.querySelectorAll('[data-explore-tab]'))b.setAttribute('aria-selected',String(b.dataset.exploreTab===name));for(const p of root.querySelectorAll('[data-explore-pane]'))p.hidden=p.dataset.explorePane!==name;}
async function history(){const scroll=saved.scrollTop;try{const response=await fetch('/InvestigationCompanion/Saved?bookId='+root.dataset.book,{cache:'no-store'});if(!response.ok)throw Error();const rows=await response.json();saved.replaceChildren();if(!rows.length)saved.textContent='No saved investigations yet.';for(const row of rows){const card=document.createElement('article'),h=document.createElement('h4'),p=document.createElement('p'),a=document.createElement('a');h.textContent=row.concern;p.textContent=row.status+' · '+new Date(row.updatedUtc).toLocaleString();a.textContent=row.hasResults?'Continue / view results':'Continue';a.href=row.resultsUrl;const menu=document.createElement('details'),toggle=document.createElement('summary'),remove=document.createElement('button');menu.className='writer-investigation-actions';toggle.textContent='⋯';toggle.setAttribute('aria-label','Actions for '+row.concern);remove.type='button';remove.className='btn btn-link btn-sm text-danger';remove.dataset.investigationDelete=row.id;remove.dataset.investigationTitle=row.concern+' · '+new Date(row.updatedUtc).toLocaleString();const trash=document.querySelector('[data-pwa-icon-catalog]').content.querySelector('[data-icon-key=remove]').cloneNode(true);trash.removeAttribute('data-icon-key');remove.append(trash,document.createTextNode(' Delete investigation'));menu.append(toggle,remove);card.append(h,p,a,menu);saved.append(card);}saved.scrollTop=scroll;}catch{saved.textContent='Saved investigations could not load. Select this tab to retry.';}}
async function load(url,options={}){if(busy)return;busy=true;root.setAttribute('aria-busy','true');message.textContent='Loading investigation…';try{const response=await fetch(url,{...options,cache:'no-store',headers:{'X-Writer-Explore':'inline','X-Requested-With':'XMLHttpRequest'}});if(response.status===404&&current&&(options.body?.get?.('id')||new URL(url,location.origin).searchParams.get('id'))===current){journey.replaceChildren();await removed(current);}if(!response.ok)throw Error(response.status===404?'This investigation was deleted or is no longer available. Return to Explore or choose another saved investigation.':response.status===409?'Another window changed this investigation. Your text is retained. Open Saved investigations to resume the latest version.':response.status===401?'Sign in again, then resume your saved investigation.':'The investigation could not be updated. Your entered answer remains here. Retry when connected.');const doc=new DOMParser().parseFromString(await response.text(),'text/html'),inline=doc.querySelector('[data-inline-investigation]');if(!inline&&!doc.querySelector('form[action*="Investigate/Start"]'))throw Error('Your session may have expired. Sign in and resume from Saved investigations.');if(inline?.dataset.inlineInvestigation&&deletedIds.has(inline.dataset.inlineInvestigation)){pendingDeleted=true;journey.replaceChildren();dirty=false;return;}journey.replaceChildren(...(inline?[inline]:doc.body.childNodes));current=inline?.dataset.inlineInvestigation||null;workspace.classList.toggle('writer21-investigating',!!current);workspace.dispatchEvent(new CustomEvent('writer-explore:state',{detail:{active:!!current}}));dirty=false;tab('new');message.textContent='';const address=new URL(location.href);if(current)address.searchParams.set('investigation',current);else address.searchParams.delete('investigation');if(address.hash==='#new-investigation')address.hash='';window.history.replaceState(window.history.state,'',address);try{if(current)sessionStorage.setItem('writer.explore.active.'+root.dataset.book,current);else sessionStorage.removeItem('writer.explore.active.'+root.dataset.book);}catch{}await history();}catch(error){message.textContent=error.message;}finally{root.removeAttribute('aria-busy');release();}}
for(const b of root.querySelectorAll('[data-explore-tab]'))b.addEventListener('click',()=>{tab(b.dataset.exploreTab);if(b.dataset.exploreTab==='saved')void history();});
root.addEventListener('input',()=>dirty=true);
root.addEventListener('submit',event=>{const form=event.target;if(form.matches('[data-guidance-activate]')){event.preventDefault();event.stopPropagation();if(busy)return;busy=true;fetch(form.action,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:new FormData(form)}).then(response=>{if(!response.ok)throw Error();message.textContent='This investigation is saved alongside your work.';window.dispatchEvent(new Event('investigation-guidance-updated'));}).catch(()=>message.textContent='Saved guidance could not be updated. Your investigation is retained; reload Saved investigations before retrying.').finally(()=>busy=false);return;}if(!form.closest('[data-explore-journey]')||form.matches('[data-guidance-navigation]'))return;event.preventDefault();event.stopPropagation();if(busy)return;if(!form.reportValidity())return;const data=new FormData(form);if(event.submitter?.name)data.set(event.submitter.name,event.submitter.value);if(event.submitter?.value==='answer'&&!data.get('option')){message.textContent='Choose an answer before continuing.';return;}void load(form.action,{method:'POST',body:data});},true);
root.addEventListener('submit',event=>{const form=event.target;if(form.matches('[data-guidance-activate]')){event.preventDefault();event.stopPropagation();if(busy)return;busy=true;const activation=new FormData(form);if(event.submitter?.name)activation.set(event.submitter.name,event.submitter.value);fetch(form.action,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:activation}).then(response=>{if(!response.ok)throw Error();message.textContent='This investigation is saved alongside your work.';window.dispatchEvent(new Event('investigation-guidance-updated'));}).catch(()=>message.textContent='Saved guidance could not be updated. Your investigation is retained; reload Saved investigations before retrying.').finally(release);return;}if(!form.closest('[data-explore-journey]')||form.matches('[data-guidance-navigation]'))return;event.preventDefault();event.stopPropagation();if(busy)return;if(!form.reportValidity())return;const data=new FormData(form);if(event.submitter?.name)data.set(event.submitter.name,event.submitter.value);if(event.submitter?.value==='answer'&&!data.get('option')){message.textContent='Choose an answer before continuing.';return;}void load(form.action,{method:'POST',body:data});},true);
root.addEventListener('click',event=>{const a=event.target.closest('a');if(!a)return;const url=new URL(a.href,location.href);const landing=a.matches('[data-explore-landing]');if(url.origin!==location.origin||!landing&&!url.pathname.startsWith('/Writer/Explore/Investigate'))return;event.preventDefault();if(dirty&&!confirm('Leave your unsaved answer and load this investigation?'))return;void load(landing?journey.dataset.openingUrl:url);});
window.addEventListener('beforeunload',event=>{if(dirty||busy){event.preventDefault();event.returnValue='';}});
window.addEventListener('hashchange',()=>{if(location.hash==='#new-investigation'&&(!dirty||confirm('Leave your unsaved answer and start another investigation?')))void load(journey.dataset.openingUrl);});let id=new URLSearchParams(location.search).get('investigation');if(location.hash==='#new-investigation')id=null;workspace.dispatchEvent(new CustomEvent('writer-explore:state',{detail:{active:!!id,initial:true}}));void load(id?'/Writer/Explore/Investigate?bookId='+root.dataset.book+'&id='+encodeURIComponent(id):journey.dataset.openingUrl);

View File

@ -14,6 +14,7 @@
const message=discovery.querySelector('[data-discovery-message]');
function render(){if(!tiles)return;let shown=0;for(const card of [...discovery.querySelectorAll('[data-tile]')].sort((a,b)=>Number(b.dataset.rank)-Number(a.dataset.rank)||a.dataset.tile.localeCompare(b.dataset.tile))){if(card.parentElement===tiles)tiles.append(card);const value=preferences[card.dataset.tile],hidden=value==='dismissed'||Number(value)>Date.now();card.hidden=hidden||shown>=4;if(!card.hidden)shown++;}if(message)message.textContent=shown?'':'All suggestions are set aside. Reconsider them whenever you like.';}
discovery.addEventListener('click',e=>{const card=e.target.closest('[data-tile]');if(card&&(e.target.matches('[data-dismiss]')||e.target.matches('[data-defer]'))){preferences[card.dataset.tile]=e.target.matches('[data-dismiss]')?'dismissed':Date.now()+7*86400000;try{localStorage.setItem(key,JSON.stringify(preferences));}catch{}render();discovery.querySelector('[data-reconsider]')?.focus();}if(e.target.matches('[data-reconsider]')){preferences={};try{localStorage.removeItem(key);}catch{}render();}});render();
window.addEventListener('plotdirector:investigation-deleted',e=>{const prefix='investigation-'+e.detail.id+'-';for(const tile of Object.keys(preferences))if(tile.startsWith(prefix))delete preferences[tile];for(const card of discovery.querySelectorAll('[data-discovery-active] [data-tile]'))if(card.dataset.tile.startsWith(prefix))card.remove();try{localStorage.setItem(key,JSON.stringify(preferences));}catch{}render();});
// Reuse the companion's authorised compact summary and native recommendation forms.
const guidance=e=>{const area=discovery.querySelector('[data-discovery-active]');if(!area)return;area.replaceChildren();if(!e.detail?.active){render();return;}const seen=new Set();const summary=e.detail.summary;if(String(summary.bookID)!==discovery.dataset.book)return;
for(const finding of summary.findings.slice(0,2)){const available=finding.tools.filter(t=>t.available&&t.progress!=='Skipped'&&t.progress!=='Done').slice(0,2);for(const tool of available){if(seen.has(tool.id)||seen.size>=2)continue;seen.add(tool.id);const source=[...document.querySelectorAll('.pd-guidance-tool')].find(x=>x.dataset.capability===tool.id);const native=source?.querySelector('form');if(!native)continue;const article=document.createElement('article');article.className='writer2-tile';article.dataset.tile='investigation-'+summary.id+'-'+tool.id;article.dataset.rank='100';const h=document.createElement('h3');h.textContent=tool.name;const p=document.createElement('p');p.textContent='From your active investigation: '+finding.explanation;article.append(h,p,native.cloneNode(true));const controls=document.createElement('div');controls.className='button-row';for(const [attribute,text]of [['data-defer','Later'],['data-dismiss','Not now']]){const b=document.createElement('button');b.type='button';b.setAttribute(attribute,'');b.textContent=text;controls.append(b);}article.append(controls);area.append(article);}}