Keep new and saved Guided Investigations inside Explore

This commit is contained in:
Nick Beckley 2026-11-18 21:15:15 +00:00
parent 88f224a059
commit c26a67bec7
6 changed files with 96 additions and 6 deletions

View File

@ -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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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");}

View File

@ -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<Catalogue?> AuthorCatalogue()=>repository.Catalogue(configuration.GetValue("WriterInvestigations:AuthorCatalogue","guided-investigation-production-v0.1"));
public async Task<Investigation> 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<Investigation> 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;

View File

@ -16,8 +16,12 @@
</section>
<section 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-investigation-opening data-url="@Url.Action("Opening","WriterInvestigations",new{bookId=Model.BookID})"><p>Loading starting concerns…</p><a asp-controller="WriterInvestigations" asp-action="Index" asp-route-bookId="@Model.BookID">Open Guided Investigation</a></div>
<section class="writer3-inset" data-my-investigations data-book="@Model.BookID" data-url="@Url.Action("Saved","InvestigationCompanion")"><h2>My Investigations</h2><p>Continue a saved concern or revisit its original results.</p><div class="pd-investigation-list" data-saved-investigations><p>Loading your saved investigations…</p></div></section>
<div data-explore-investigation data-book="@Model.BookID">
<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>
<div data-explore-pane="saved" hidden><h3>Saved investigations</h3><div class="writer21-bounded" data-explore-saved></div></div>
</div>
}else{<p>@(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.")</p>}
</section>
</div>

View File

@ -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){<p class="alert alert-info">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.</p>}
<div class="investigation-journey" data-inline-investigation="@row?.ID">
<section class="writer3-panel" aria-labelledby="investigation-question">
@if(row==null){
<partial name="_Opening" model="Model" />
}else if(question!=null){
<p class="writer3-caption">@row.Answers.Count questions answered · There is no fixed number needed for a useful next step.</p>
<h2 id="investigation-question">@question.Text</h2>@if(question.Help!=""){<p id="question-help">@question.Help</p>}
<form asp-action="Answer" method="post" data-investigation-answer>
<input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/><input type="hidden" name="question" value="@question.Id"/>
<fieldset><legend class="visually-hidden">Your answer</legend>@foreach(var option in question.Options){<label class="investigation-choice"><input type="radio" name="option" value="@option.Id" checked="@(previous?.Option==option.Id)" /> @option.Text</label>}</fieldset>
@if(question.AllowExplanation){<label for="investigation-explanation">Anything you'd like to explain? <span class="muted">Optional</span></label><textarea class="form-control" id="investigation-explanation" name="explanation" maxlength="2000" rows="3">@(previous?.Explanation??(row.DraftQuestion==question.Id?row.DraftExplanation:null))</textarea>}
<div class="investigation-actions">
@if(row.Answers.LastOrDefault(a=>a.Question!=question.Id) is {} back){<a asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-id="@row.ID" asp-route-question="@back.Question">Back to an earlier answer</a>}
<button class="btn btn-primary" name="operation" value="answer">Continue</button><button class="btn btn-outline-secondary" name="operation" value="save">Save for later</button></div>
</form>
}else{
@if(Model.Catalogue.Editorial!=null){
var result=EditorialConclusion.From(Model.Catalogue,state!);
<h2 id="investigation-question" data-conclusion="@result.Kind">@result.Title</h2>
<p>@result.Explanation</p><p class="writer3-caption">@result.Qualification</p>
@if(result.Findings.Count==0){<h3>A practical next step</h3><p data-writing-action>@result.Action</p>}
@foreach(var finding in result.Findings){
<section class="writer3-inset"><h3>@finding.Title</h3><p>@finding.Explanation</p>
<h4>A practical next step</h4><p data-writing-action>@finding.Action</p>
<p>Answers that informed this possibility:</p><ul data-supporting-observations>
@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);<li>@q.Text — @q.Options.Single(o=>o.Id==answer.Option).Text</li>
}</ul>
@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))){
<p>@cap.Description</p><form asp-action="Open" method="post" data-guidance-navigation><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/><input type="hidden" name="finding" value="@finding.Hypothesis"/><button class="btn btn-primary" name="capability" value="@cap.Id">@cap.ActionText</button></form>
}
}
</section>
}
@if(result.Findings.Count==0){<p>Your observations so far:</p><ul data-supporting-observations>@foreach(var a in row.Answers.TakeLast(3)){var q=Model.Catalogue.Questions.Single(q=>q.Id==a.Question);<li>@q.Text — @q.Options.Single(o=>o.Id==a.Option).Text</li>}</ul>}
}else{
var conclusion=InvestigationConclusion.From(Model.Catalogue,state!);
<h2 id="investigation-question" data-conclusion="@conclusion.Kind">@conclusion.Title</h2>
<p>@conclusion.Message</p>
@if(conclusion.Areas.Length>0){<p>Areas your answers touched on:</p><ul>@foreach(var area in conclusion.Areas){<li>@area</li>}</ul>}
@if(state!.Recommendations.Count>0){<p class="writer3-caption">Opening a tool makes this investigation your active guidance for this book. Your other saved investigations are kept.</p>}
@if(row.Answers.Count>=Model.Catalogue.MaxAnswers&&state.Recommendations.Count==0){<p>We've reached the question limit for this test. You can still change earlier answers or save and return later.</p>}
@foreach(var id in state.Recommendations){var h=Model.Catalogue.Hypotheses.Single(h=>h.Id==id);<section class="writer3-inset"><h3>@h.Summary</h3><p>@h.Reason</p><p class="muted">@h.Uncertainty</p>
<p>Answers that informed this suggestion:</p><ul>@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);<li>@q.Text — @q.Options.Single(o=>o.Id==evidence.Option).Text</li>}</ul>
@foreach(var cap in Model.Catalogue.Capabilities.Where(d=>h.Capabilities.Contains(d.Id)&&state.AvailableCapabilities.Contains(d.Id))){<p>@cap.Description</p><form asp-action="Open" method="post" data-guidance-navigation><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/><input type="hidden" name="finding" value="@id"/><button class="btn btn-primary" name="capability" value="@cap.Id">@cap.ActionText</button></form>}
</section>}
}
@if(row.Accepted){<p role="status">Your response is saved. Return to this investigation whenever you need it.</p>}
<form asp-action="Answer" method="post"><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/>
<div class="investigation-actions">@if(state!.Recommendations.Count>0){<button class="btn btn-outline-secondary" name="operation" value="accept">That sounds right</button>}
<button class="btn btn-outline-secondary" name="operation" value="disagree">That's not quite what I meant</button>
@if(row.Answers.Count<Model.Catalogue.MaxAnswers&&state.Candidates.Count>0){<button class="btn btn-outline-secondary" name="operation" value="further">I'd like to investigate further</button>}
<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 asp-controller="Writer" asp-action="Explore" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">Return to Explore</a> · <a asp-action="Index" asp-route-bookId="@Model.BookID">Start another investigation</a></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>}
</aside>
</div>
</div>

View File

@ -1,6 +1,6 @@
@model PlotLine.Models.Investigations.InvestigationPage
<h2 id="investigation-question">@(Model.Catalogue.Editorial is {} editorial?Model.Catalogue.Questions.Single(q=>q.Id==editorial.OpeningQuestion).Text:"What's troubling you about your story?")</h2>
@if(Model.Catalogue.Editorial is {} opening){<p>@Model.Catalogue.Questions.Single(q=>q.Id==opening.OpeningQuestion).Help</p>}
<form asp-controller="WriterInvestigations" asp-action="Start" method="post"><input type="hidden" name="bookId" value="@Model.BookID" />@if(Model.Catalogue.Synthetic){<input type="hidden" name="catalogueVersion" value="@Model.Catalogue.Version" />}<fieldset><legend class="visually-hidden">Choose a starting concern</legend>
<form asp-controller="WriterInvestigations" asp-action="Start" method="post"><input type="hidden" name="bookId" value="@Model.BookID" />@if(Model.Catalogue.Synthetic){<input type="hidden" name="catalogueVersion" value="@Model.Catalogue.Version" />}<input type="hidden" name="requestId" value="@Guid.NewGuid()"/><fieldset><legend class="visually-hidden">Choose a starting concern</legend>
@foreach(var concern in Model.Catalogue.Concerns){<label class="investigation-choice"><input type="radio" name="concern" value="@concern.Id" required /> @concern.Text</label>}
</fieldset><button class="btn btn-primary" type="submit">Begin</button></form>

View File

@ -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);
})();