From c26a67bec75c2a3b3319681d8a1a3db44b8e2bc8 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Wed, 18 Nov 2026 21:15:15 +0000 Subject: [PATCH] Keep new and saved Guided Investigations inside Explore --- .../WriterInvestigationsController.cs | 5 +- .../Investigations/InvestigationService.cs | 2 +- PlotLine/Views/Writer/_WriterExplore.cshtml | 8 ++- .../WriterInvestigations/_Journey.cshtml | 72 +++++++++++++++++++ .../WriterInvestigations/_Opening.cshtml | 2 +- PlotLine/wwwroot/js/writer-explore.js | 13 ++++ 6 files changed, 96 insertions(+), 6 deletions(-) create mode 100644 PlotLine/Views/WriterInvestigations/_Journey.cshtml create mode 100644 PlotLine/wwwroot/js/writer-explore.js diff --git a/PlotLine/Controllers/WriterInvestigationsController.cs b/PlotLine/Controllers/WriterInvestigationsController.cs index 294e3c94..988b12b1 100644 --- a/PlotLine/Controllers/WriterInvestigationsController.cs +++ b/PlotLine/Controllers/WriterInvestigationsController.cs @@ -26,7 +26,8 @@ public sealed class WriterInvestigationsController(InvestigationAccess gate,IInv if(!old.Synthetic||admin){saved.Add(item);labels[item.ID]=old.Concerns.Single(r=>r.Id==item.Concern).Text;} } ViewData["SavedConcernLabels"]=labels; - return View(new InvestigationPage(row,c,state,saved,project,bookId)); + var model=new InvestigationPage(row,c,state,saved,project,bookId); + return Request.Headers["X-Writer-Explore"]=="inline"?PartialView("_Journey",model):View(model); }); [HttpGet] public Task Opening(int bookId)=>Guard(async()=>{ @@ -34,7 +35,7 @@ public sealed class WriterInvestigationsController(InvestigationAccess gate,IInv return PartialView("_Opening",new InvestigationPage(null,c,null,[],project,bookId)); }); [HttpPost("/Writer/Explore/Investigate/Start"),ValidateAntiForgeryToken] - public Task Start(int bookId,string concern,string? catalogueVersion=null)=>Guard(async()=>{if(catalogueVersion!=null&&!await IsAdmin())return NotFound();var c=await (catalogueVersion==null?service.AuthorCatalogue():repository.Catalogue(catalogueVersion))??throw new ArgumentException("The investigation catalogue is unavailable.");await EnsureCatalogue(c);var row=await service.Start(Author,bookId,concern,c.Version);return RedirectToAction(nameof(Index),new{bookId,id=row.ID});}); + public Task Start(int bookId,string concern,string? catalogueVersion=null,Guid? requestId=null)=>Guard(async()=>{if(catalogueVersion!=null&&!await IsAdmin())return NotFound();var c=await (catalogueVersion==null?service.AuthorCatalogue():repository.Catalogue(catalogueVersion))??throw new ArgumentException("The investigation catalogue is unavailable.");await EnsureCatalogue(c);var row=await service.Start(Author,bookId,concern,c.Version,requestId);return RedirectToAction(nameof(Index),new{bookId,id=row.ID});}); [HttpPost("/Writer/Explore/Investigate/Answer"),ValidateAntiForgeryToken] public Task Answer(int bookId,Guid id,int version,string? question,string? option,string? explanation,string operation="answer")=>Guard(async()=>{ ViewData["Explanation"]=explanation;ViewData["Option"]=option;var(i,c)=await service.Read(Author,bookId,id);await EnsureCatalogue(c);if(version!=i.Version){Response.StatusCode=409;ViewData["Failure"]="Another window changed this investigation. Your answer is retained below. Resume the latest version before submitting again.";ViewData["Explanation"]=explanation;ViewData["Option"]=option;return View("Failure");} diff --git a/PlotLine/Services/Investigations/InvestigationService.cs b/PlotLine/Services/Investigations/InvestigationService.cs index bb2e16b5..fe4e4dfc 100644 --- a/PlotLine/Services/Investigations/InvestigationService.cs +++ b/PlotLine/Services/Investigations/InvestigationService.cs @@ -14,7 +14,7 @@ public sealed class InvestigationService(IInvestigationRepository repository,IBo public Evaluation Current(Catalogue c,Investigation i)=>InvestigationEngine.Evaluate(c,i.Concern,i.Answers,Available(c,i).Where(id=>configuration.GetValue($"WriterInvestigations:Capabilities:{id}:Enabled",true)).ToHashSet(),i.ContinueUntil); public async Task<(Investigation,Catalogue)> Read(int user,int book,Guid id){var project=await Project(book);var row=await repository.Read(user,book,id)??throw new KeyNotFoundException();if(row.UserID!=user||row.BookID!=book||row.ProjectID!=project)throw new UnauthorizedAccessException();return(row,await repository.Catalogue(row.CatalogueVersion)??throw new KeyNotFoundException());} public Task AuthorCatalogue()=>repository.Catalogue(configuration.GetValue("WriterInvestigations:AuthorCatalogue","guided-investigation-production-v0.1")); - public async Task Start(int user,int book,string concern,string? catalogueVersion=null){var project=await Project(book);var c=await (catalogueVersion==null?AuthorCatalogue():repository.Catalogue(catalogueVersion))??throw new ArgumentException("The investigation catalogue is not yet available.");var i=new Investigation{ID=Guid.NewGuid(),UserID=user,ProjectID=project,BookID=book,CatalogueVersion=c.Version,Concern=concern,CreatedUtc=clock.GetUtcNow().UtcDateTime};await Persist(i,c,0,"start");return i;} + public async Task Start(int user,int book,string concern,string? catalogueVersion=null,Guid? requestId=null){var project=await Project(book);if(requestId is {} existing&&existing!=Guid.Empty&&await repository.Read(user,book,existing) is {} prior){if(prior.UserID!=user||prior.BookID!=book||prior.Concern!=concern)throw new ArgumentException("Start request changed. Refresh the starting concerns.");return prior;}var c=await (catalogueVersion==null?AuthorCatalogue():repository.Catalogue(catalogueVersion))??throw new ArgumentException("The investigation catalogue is not yet available.");var i=new Investigation{ID=requestId is {} key&&key!=Guid.Empty?key:Guid.NewGuid(),UserID=user,ProjectID=project,BookID=book,CatalogueVersion=c.Version,Concern=concern,CreatedUtc=clock.GetUtcNow().UtcDateTime};await Persist(i,c,0,"start");return i;} public async Task Persist(Investigation i,Catalogue c,int expected,string operation) { var state=Current(c,i);i.CurrentQuestion=state.NextQuestion; diff --git a/PlotLine/Views/Writer/_WriterExplore.cshtml b/PlotLine/Views/Writer/_WriterExplore.cshtml index bb57bdb1..5959e948 100644 --- a/PlotLine/Views/Writer/_WriterExplore.cshtml +++ b/PlotLine/Views/Writer/_WriterExplore.cshtml @@ -16,8 +16,12 @@

Explore a concern

You do not need to know the answer yet. Start with what is troubling you.

@if(InvestigationAccess.Enabled&&Model.BookID.HasValue){ -

Loading starting concerns…

Open Guided Investigation
-

My Investigations

Continue a saved concern or revisit its original results.

Loading your saved investigations…

+
+
+

+

Loading starting concerns…

+ +
}else{

@(Model.BookID.HasValue?"Guided Investigation is not available in this environment. The story tools remain available.":"Select a book to keep your concerns and investigations with that book.")

}
diff --git a/PlotLine/Views/WriterInvestigations/_Journey.cshtml b/PlotLine/Views/WriterInvestigations/_Journey.cshtml new file mode 100644 index 00000000..4f15662d --- /dev/null +++ b/PlotLine/Views/WriterInvestigations/_Journey.cshtml @@ -0,0 +1,72 @@ +@inject Microsoft.AspNetCore.Authorization.IAuthorizationService Authorization +@using PlotLine.Models.Investigations +@using PlotLine.Services.Investigations +@model InvestigationPage +@{ + ViewData["Title"]="Writer · Explore";ViewData["ProjectSection"]="Writer"; + var row=Model.Investigation;var state=Model.Evaluation;var question=Model.Catalogue.Questions.SingleOrDefault(q=>q.Id==(string?)ViewData["Question"]);var previous=row?.Answers.LastOrDefault(a=>a.Question==question?.Id); +} + @if(Model.Catalogue.Synthetic){

Development preview · This small test catalogue exercises the mechanism. Its suggestions are not production writing guidance. It uses your answers, without AI or manuscript analysis.

} +
+
+ @if(row==null){ + + }else if(question!=null){ +

@row.Answers.Count questions answered · There is no fixed number needed for a useful next step.

+

@question.Text

@if(question.Help!=""){

@question.Help

} +
+ +
Your answer@foreach(var option in question.Options){}
+ @if(question.AllowExplanation){} +
+ @if(row.Answers.LastOrDefault(a=>a.Question!=question.Id) is {} back){Back to an earlier answer} +
+
+ }else{ + @if(Model.Catalogue.Editorial!=null){ + var result=EditorialConclusion.From(Model.Catalogue,state!); +

@result.Title

+

@result.Explanation

@result.Qualification

+ @if(result.Findings.Count==0){

A practical next step

@result.Action

} + @foreach(var finding in result.Findings){ +

@finding.Title

@finding.Explanation

+

A practical next step

@finding.Action

+

Answers that informed this possibility:

    + @foreach(var answer in row.Answers.Where(a=>Model.Catalogue.Questions.Single(q=>q.Id==a.Question).Options.Single(o=>o.Id==a.Option).Contributions.Any(v=>v.Hypothesis==finding.Hypothesis&&v.Weight>0)).Take(3)){ + var q=Model.Catalogue.Questions.Single(q=>q.Id==answer.Question);
  • @q.Text — @q.Options.Single(o=>o.Id==answer.Option).Text
  • + }
+ @if(state!.Recommendations.Contains(finding.Hypothesis)){ + @foreach(var cap in Model.Catalogue.Capabilities.Where(d=>Model.Catalogue.Hypotheses.Single(h=>h.Id==finding.Hypothesis).Capabilities.Contains(d.Id)&&state.AvailableCapabilities.Contains(d.Id))){ +

@cap.Description

+ } + } +
+ } + @if(result.Findings.Count==0){

Your observations so far:

    @foreach(var a in row.Answers.TakeLast(3)){var q=Model.Catalogue.Questions.Single(q=>q.Id==a.Question);
  • @q.Text — @q.Options.Single(o=>o.Id==a.Option).Text
  • }
} + }else{ + var conclusion=InvestigationConclusion.From(Model.Catalogue,state!); +

@conclusion.Title

+

@conclusion.Message

+ @if(conclusion.Areas.Length>0){

Areas your answers touched on:

    @foreach(var area in conclusion.Areas){
  • @area
  • }
} + @if(state!.Recommendations.Count>0){

Opening a tool makes this investigation your active guidance for this book. Your other saved investigations are kept.

} + @if(row.Answers.Count>=Model.Catalogue.MaxAnswers&&state.Recommendations.Count==0){

We've reached the question limit for this test. You can still change earlier answers or save and return later.

} + @foreach(var id in state.Recommendations){var h=Model.Catalogue.Hypotheses.Single(h=>h.Id==id);

@h.Summary

@h.Reason

@h.Uncertainty

+

Answers that informed this suggestion:

    @foreach(var evidence in state.Evidence.Where(e=>e.Hypothesis==id&&e.Raw>0&&!e.Uncertain).DistinctBy(e=>e.Question).Take(3)){var q=Model.Catalogue.Questions.Single(q=>q.Id==evidence.Question);
  • @q.Text — @q.Options.Single(o=>o.Id==evidence.Option).Text
  • }
+ @foreach(var cap in Model.Catalogue.Capabilities.Where(d=>h.Capabilities.Contains(d.Id)&&state.AvailableCapabilities.Contains(d.Id))){

@cap.Description

} +
} + } + @if(row.Accepted){

Your response is saved. Return to this investigation whenever you need it.

} +
+
@if(state!.Recommendations.Count>0){} + + @if(row.Answers.Count0){} +
+ } + @if(row!=null){
} +

Return to Explore · Start another investigation

+
+ +
+ diff --git a/PlotLine/Views/WriterInvestigations/_Opening.cshtml b/PlotLine/Views/WriterInvestigations/_Opening.cshtml index f9623443..17ff9fd9 100644 --- a/PlotLine/Views/WriterInvestigations/_Opening.cshtml +++ b/PlotLine/Views/WriterInvestigations/_Opening.cshtml @@ -1,6 +1,6 @@ @model PlotLine.Models.Investigations.InvestigationPage

@(Model.Catalogue.Editorial is {} editorial?Model.Catalogue.Questions.Single(q=>q.Id==editorial.OpeningQuestion).Text:"What's troubling you about your story?")

@if(Model.Catalogue.Editorial is {} opening){

@Model.Catalogue.Questions.Single(q=>q.Id==opening.OpeningQuestion).Help

} -
@if(Model.Catalogue.Synthetic){}
Choose a starting concern + @if(Model.Catalogue.Synthetic){}
Choose a starting concern @foreach(var concern in Model.Catalogue.Concerns){}
\ No newline at end of file diff --git a/PlotLine/wwwroot/js/writer-explore.js b/PlotLine/wwwroot/js/writer-explore.js new file mode 100644 index 00000000..b6c6624c --- /dev/null +++ b/PlotLine/wwwroot/js/writer-explore.js @@ -0,0 +1,13 @@ +// 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);dirty=false;tab('new');message.textContent='';const address=new URL(location.href);if(current)address.searchParams.set('investigation',current);else address.searchParams.delete('investigation');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');}} +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.closest('[data-explore-journey]')||form.matches('[data-guidance-navigation],[data-guidance-activate]'))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);if(url.origin!==location.origin||!url.pathname.startsWith('/Writer/Explore/Investigate'))return;event.preventDefault();if(dirty&&!confirm('Leave your unsaved answer and load this investigation?'))return;void load(url);}); +window.addEventListener('beforeunload',event=>{if(dirty||busy){event.preventDefault();event.returnValue='';}}); +let id=new URLSearchParams(location.search).get('investigation');if(!id&&document.referrer.startsWith(location.origin))try{id=sessionStorage.getItem('writer.explore.active.'+root.dataset.book);}catch{}void load(id?'/Writer/Explore/Investigate?bookId='+root.dataset.book+'&id='+encodeURIComponent(id):journey.dataset.openingUrl); +})();