Restore existing global progress strip for core import and preserve resume navigation
This commit is contained in:
parent
016dbb1632
commit
90492f65f0
43
Docs/WordCompanion/2026-11-08-import-progress-navigation.md
Normal file
43
Docs/WordCompanion/2026-11-08-import-progress-navigation.md
Normal file
@ -0,0 +1,43 @@
|
||||
# Existing import progress and resume regression — 8 November 2026
|
||||
|
||||
## Today's actual import (read-only investigation)
|
||||
|
||||
Project **8174**, book **10152**, **The Alpha Flame**. All times below are London/GMT.
|
||||
|
||||
The Development access log records:
|
||||
|
||||
- 18:10:15 — start import; writing software/project selected; book saved at 18:11:00.
|
||||
- **18:39:06 — Word capture POST returned HTTP 403**, followed immediately by the existing client's request-cleanup DELETE, which returned 200.
|
||||
- 18:49:25 and 18:56:10 — the normal `POST /onboarding/start-import` action was used again. The old implementation cleared scan state and software selection instead of resuming.
|
||||
- 18:56:13–14 — Back actions left the saved wizard at **Welcome**.
|
||||
|
||||
Before any changes/deployment, the database had **zero accepted captures, zero manuscript builds and no Story Intelligence jobs/runs**. Book 10152 has not completed import or scene detection. The prior transfer **failed**, rather than continuing in the background. Its intermediate reading/chapter-discovery progress is not recoverable from an accepted server snapshot. The source Word document was not changed by this investigation. No scan, import or analysis was restarted, cancelled, reset or duplicated by Atlas.
|
||||
|
||||
The precise 403 validation reason was not logged. The existing native capture request has a fixed 20-minute lifetime; elapsed time from book selection to submission was approximately 28 minutes, making expiry a plausible cause, not a proven diagnosis. User/project/document/session/grant checks can also reject submission. This navigation correction does not weaken those checks, claim to recover the rejected payload or silently retry it.
|
||||
|
||||
## Why the bar disappeared
|
||||
|
||||
The strip with the right-hand **Book** button still existed in `_Layout.cshtml`, `StoryIntelligenceGlobalProgressService` and `story-intelligence-global-progress.js`. Its discovery/visibility logic queried only active Story Intelligence run summaries. Word scanning and core chapter/scene review do not create those run records, so the strip was hidden during that earlier phase. Recent migrations **242/243 did not remove it**; today's onboarding completion timestamp was null. The former long-running analysis strip and the early Word capture stage were different states in the existing flow.
|
||||
|
||||
A second confirmed navigation defect made the failure look like nothing had started: the Projects/ribbon **Import a manuscript** action called `StartManuscriptImportSetupAsync`, which unconditionally cleared the existing scan and reset setup. Access history confirms that reset action was invoked after the failed submission.
|
||||
|
||||
## Correction — existing components only
|
||||
|
||||
- The existing global progress model/service now also projects the current authorised unfinished wizard, scan and build state. No new session store, import engine, hub, database table or parallel progress strip.
|
||||
- The same strip and button area show Word reading, chapter review, scene detection, location/character review, failure or saved setup as appropriate. Both the strip text and action link navigate to the existing matching wizard route/preview. Pending setup is not labelled as running analysis.
|
||||
- Core capture completion alone does not remove the strip: it remains through mandatory review, and disappears when persistent core completion is recorded. Optional Story Intelligence continues to use its existing counts, events and **Book** action independently.
|
||||
- Existing in-memory scene-build progress has a read-only getter and is hydrated on wizard reload. The existing scene-detection button stays disabled while that build is running; re-entry does not launch another build.
|
||||
- While core work exists, the existing authoritative SignalR watcher refreshes its snapshot every 15 seconds on a visible page and on return/reconnect. No extra connection or scanning request is created.
|
||||
- The normal Import action resumes an unfinished selected-book setup without clearing capture/session/preferences. Explicit creation of a new setup after completed onboarding remains available through the existing flow.
|
||||
|
||||
## Returning to today's book
|
||||
|
||||
`https://dev.plotdirector.com/onboarding` opens the existing saved setup. **For this attempt it is Welcome**, not the lost scan progress screen. There is no accepted capture to link to chapter review. The change prevents another navigation reset and restores visibility/resume for future in-flight stages; it does not manufacture missing progress or automatically restart the failed transfer. Project/book selection is retained.
|
||||
|
||||
## Verification
|
||||
|
||||
Focused managed regressions use the real existing scan store and durable-capture interface: navigation/refresh retain the same ScanID; Import never invokes Clear; accepted capture reload restores its exact review preview; running scene detection and required location/character review remain discoverable; genuine core completion removes core progress; optional analysis retains the original Book link; revoked permission hides stale book information.
|
||||
|
||||
Browser regression exercises the actual shared progress script with its existing SignalR watcher, recreated-page restore, correct links and core-to-optional transition, and asserts that no Start/Scan/Build request is invoked by progress navigation. Existing native import connectivity tests are retained.
|
||||
|
||||
Deployment evidence is appended after rollout. The failed transfer was already cleaned up before this task; service replacement is permitted only after checking that no new import or running job has started.
|
||||
9
PlotLine.Tests/Browser/import-progress-navigation.cjs
Normal file
9
PlotLine.Tests/Browser/import-progress-navigation.cjs
Normal file
@ -0,0 +1,9 @@
|
||||
const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
|
||||
(async()=>{const browser=await chromium.launch();try{const page=await browser.newPage();const core={BookID:10,BookTitle:'Fixture',Stage:'Scanning Word',Message:'Reading paragraphs',PercentComplete:42,ResumeUrl:'/onboarding'};
|
||||
async function boot(seed){await page.goto('about:blank');await page.setContent(`<div data-story-intelligence-global-strip hidden><a data-story-intelligence-global-link><strong data-story-intelligence-global-title></strong><span data-story-intelligence-global-detail></span></a><span data-story-intelligence-global-bar></span><a data-story-intelligence-global-link data-story-intelligence-global-action></a><div data-story-intelligence-global-runs></div></div>`);await page.evaluate(seed=>{const strip=document.querySelector('[data-story-intelligence-global-strip]');strip.dataset.coreImport=JSON.stringify(seed);window.snapshot={coreImport:seed,books:[]};window.calls=[];window.handlers={};window.signalR={HubConnectionBuilder:class{withUrl(){return this;}withAutomaticReconnect(){return this;}build(){return{state:'Connected',on(n,f){handlers[n]=f;},onreconnected(){},onclose(){},start:async()=>{},invoke:async n=>{calls.push(n);return snapshot;}}}}};},seed);await page.addScriptTag({content:fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/story-intelligence-global-progress.js'),'utf8')});await page.waitForFunction(()=>calls.includes('WatchGlobalStoryIntelligenceProgress'));}
|
||||
await boot(core);const strip=page.locator('[data-story-intelligence-global-strip]'),link=page.locator('[data-story-intelligence-global-action]');await page.waitForTimeout(50);assert.equal(await strip.isVisible(),true);assert.match(await strip.innerText(),/Scanning Word/);assert.equal(await link.getAttribute('href'),'/onboarding');assert.equal(await link.innerText(),'Return to import');assert.match(await page.locator('[data-story-intelligence-global-bar]').getAttribute('style'),/42%/);
|
||||
await boot(core);assert.equal(await strip.isVisible(),true);assert.equal(await link.getAttribute('href'),'/onboarding');
|
||||
await page.evaluate(()=>handlers.StoryIntelligenceGlobalProgressChanged({coreImport:{bookTitle:'Fixture',stage:'Review chapters',message:'Capture saved',resumeUrl:'/onboarding/scan-review?previewId=123'},books:[]}));assert.match(await link.getAttribute('href'),/scan-review\?previewId=123/);assert.match(await strip.innerText(),/Review chapters/);
|
||||
await page.evaluate(()=>handlers.StoryIntelligenceGlobalProgressChanged({coreImport:null,books:[]}));assert.equal(await strip.isVisible(),false);
|
||||
await page.evaluate(()=>handlers.StoryIntelligenceGlobalProgressChanged({coreImport:null,books:[{bookID:10,projectID:9,bookTitle:'Fixture',status:'Pending',pendingRunCount:1,hasActiveRuns:true,totalExpectedScenes:4,completedScenes:0,updatedUtc:new Date().toISOString()}],hasActiveWork:true,activeBookCount:1,status:'Running',totalExpectedScenes:4,completedScenes:0}));assert.equal(await strip.isVisible(),true);assert.equal(await link.getAttribute('href'),'/Books/Details/10');assert.equal(await link.innerText(),'Book');
|
||||
assert.equal(await page.evaluate(()=>calls.some(n=>/Start|Scan|Build/.test(n))),false);console.log('PASS existing global strip: Word scan visibility, recreated-page restore, exact review navigation, core completion hiding, independent optional AI Book link, and watch-only requests');}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);});
|
||||
56
PlotLine.Tests/ImportProgressNavigationTests.cs
Normal file
56
PlotLine.Tests/ImportProgressNavigationTests.cs
Normal file
@ -0,0 +1,56 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
internal static class ImportProgressNavigationTests
|
||||
{
|
||||
private sealed class Capture : IManuscriptCaptureRepository
|
||||
{
|
||||
public ManuscriptScanPreview? Saved;public int Clears;
|
||||
public Task Save(ManuscriptScanPreview p){Saved=p;return Task.CompletedTask;}
|
||||
public Task<ManuscriptScanPreview?> Get(int user,Guid? preview=null,int? onboarding=null)=>Task.FromResult(Saved?.UserID==user&&(!preview.HasValue||Saved.PreviewID==preview)&&(!onboarding.HasValue||Saved.OnboardingID==onboarding)?Saved:null);
|
||||
public Task Clear(int user,int onboarding){Clears++;throw new Exception("Navigation must not clear a capture");}
|
||||
public Task CompleteBuild(int user,Guid preview)=>Task.CompletedTask;
|
||||
public Task<string?> GetAnalysis(int user,Guid preview,string hash)=>Task.FromResult<string?>(null);
|
||||
public Task SaveAnalysis(int user,Guid preview,string hash,string result)=>Task.CompletedTask;
|
||||
}
|
||||
public static async Task Run()
|
||||
{
|
||||
var state=new UserOnboardingState{UserID=7,UserOnboardingStateID=8,ProjectID=9,BookID=10,WritingJourney=WritingJourneyValues.ManuscriptMostlyComplete,WritingSoftware=WritingSoftwareValues.MicrosoftWord,CurrentStep=OnboardingSteps.NextPathPreview};
|
||||
var calls=new List<string>();var onboarding=NativeWorkflowTests.Proxy<IOnboardingRepository>((n,a)=>{calls.Add(n);return n=="GetAsync"?Task.FromResult<UserOnboardingState?>(state):throw new Exception("Unexpected onboarding mutation: "+n);});
|
||||
var user=NativeWorkflowTests.Proxy<ICurrentUserService>((n,a)=>n=="get_UserId"?(int?)7:throw new Exception(n));
|
||||
bool optional=false,locationsDone=false,owner=true;
|
||||
var runs=NativeWorkflowTests.Proxy<IStoryIntelligenceResultRepository>((n,a)=>n switch{
|
||||
"ListActiveBookRunSummariesForUserAsync"=>(object)Task.FromResult<IReadOnlyList<StoryIntelligenceActiveBookRunSummary>>(optional?[new(){UserID=7,ProjectID=9,BookID=10,BookTitle="Fixture",PendingRunCount=1,Status="Pending"}]:[]),
|
||||
"ListRunsByBookForUserAsync"=>Task.FromResult<IReadOnlyList<StoryIntelligenceSavedRun>>([]),_=>throw new Exception(n)});
|
||||
var books=NativeWorkflowTests.Proxy<IBookRepository>((n,a)=>Task.FromResult<Book?>(new(){BookID=10,ProjectID=9,BookTitle="Fixture"}));
|
||||
var projects=NativeWorkflowTests.Proxy<IProjectRepository>((n,a)=>Task.FromResult<Project?>(owner?new(){ProjectID=9,AccessRole="Owner"}:null));
|
||||
OnboardingManuscriptBuildResult? built=null;
|
||||
var builds=NativeWorkflowTests.Proxy<IOnboardingBuildRepository>((n,a)=>Task.FromResult(built));
|
||||
var locations=NativeWorkflowTests.Proxy<ICoreImportBasicLocationService>((n,a)=>Task.FromResult(locationsDone));
|
||||
var capture=new Capture();using var provider=new ServiceCollection().AddSingleton<IManuscriptCaptureRepository>(capture).BuildServiceProvider();
|
||||
ManuscriptScanPreviewStore Store()=>new(provider.GetRequiredService<IServiceScopeFactory>(),NullLogger<ManuscriptScanPreviewStore>.Instance);
|
||||
var scans=Store();StoryIntelligenceGlobalProgressService Progress()=>new(user,runs,onboarding,scans,builds,books,locations,projects);
|
||||
var started=await scans.StartAsync(7,8,9,10);await scans.ProgressAsync(7,new(){OnboardingID=8,Message="Reading paragraphs",PercentComplete=42});
|
||||
var first=await Progress().GetForCurrentUserAsync();var second=await Progress().GetForCurrentUserAsync();
|
||||
Check(first.HasActiveWork&&first.CoreImport?.Stage=="Scanning Word"&&second.CoreImport?.PercentComplete==42&&(await scans.GetStateAsync(7,8)).ScanID==started.ScanID,"navigation away and refresh keep the same running Word scan and expose it through existing global progress");
|
||||
var ctor=typeof(OnboardingService).GetConstructors().Single();var deps=new Dictionary<Type,object>{{typeof(IOnboardingRepository),onboarding},{typeof(ICurrentUserService),user},{typeof(IManuscriptScanPreviewStore),scans}};
|
||||
var service=(OnboardingService)ctor.Invoke(ctor.GetParameters().Select(p=>deps.GetValueOrDefault(p.ParameterType)).ToArray());
|
||||
await service.StartManuscriptImportSetupAsync();Check(calls.All(c=>c=="GetAsync")&&capture.Clears==0&&(await scans.GetStateAsync(7,8)).ScanID==started.ScanID,"existing Import action resumes unfinished book without resetting preferences, scan ID or capture");
|
||||
var preview=new ManuscriptScanPreview{UserID=7,OnboardingID=8,ProjectID=9,BookID=10,Source="NativeWordCompanion",ChapterCount=2};await scans.CompleteAsync(7,preview);
|
||||
Check((await Progress().GetForCurrentUserAsync()).CoreImport?.ResumeUrl=="/onboarding/scan-review?previewId="+preview.PreviewID.ToString("D"),"capture completion keeps global indicator visible and returns to exact chapter-review preview");
|
||||
scans=Store();Check((await Progress().GetForCurrentUserAsync()).CoreImport?.Stage=="Review chapters","reopening restores accepted capture navigation from existing durable repository");
|
||||
var review=await scans.GetReviewAsync(7,preview.PreviewID);await scans.SaveReviewAsync(7,new(){PreviewID=preview.PreviewID,Status=ManuscriptScanReviewStatuses.ReadyToImport});
|
||||
await scans.BuildProgressAsync(7,preview.PreviewID,"Detecting chapter scenes",38);
|
||||
Check((await Progress().GetForCurrentUserAsync()).CoreImport is {Stage:"Detecting scenes",PercentComplete:38},"existing in-flight scene detection progress survives page navigation without starting another build");
|
||||
await scans.BuildProgressAsync(7,preview.PreviewID,"Built",100,new(){BookID=10});built=new(){BookID=10,ProjectID=9};
|
||||
Check((await Progress().GetForCurrentUserAsync()).CoreImport?.ResumeUrl.Contains("scan-locations")==true,"core import returns to required location review after structure build");locationsDone=true;
|
||||
Check((await Progress().GetForCurrentUserAsync()).CoreImport?.ResumeUrl.Contains("scan-characters")==true,"core import remains visible until character review and durable completion");
|
||||
state.OnboardingCompletedUtc=DateTime.UtcNow;
|
||||
Check(!(await Progress().GetForCurrentUserAsync()).HasActiveWork,"genuine core completion removes core indicator independently of optional analysis");optional=true;
|
||||
var ai=await Progress().GetForCurrentUserAsync();Check(ai.HasActiveWork&&ai.CoreImport==null&&ai.Books.Count==1,"optional Story Intelligence retains existing global strip and book navigation after core completion");
|
||||
state.OnboardingCompletedUtc=null;owner=false;Check((await Progress().GetForCurrentUserAsync()).CoreImport==null,"revoked project permission does not expose a stale core import");
|
||||
}
|
||||
private static void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);}
|
||||
}
|
||||
@ -129,6 +129,7 @@ if(args.Contains("--native-installation")){await NativeInstallationTests.Run();C
|
||||
if(args.Contains("--paragraph-view")){await ParagraphViewTests.Run();return;}
|
||||
if(args.Contains("--paragraph-live-ai")){await ParagraphLiveAiTests.Run();return;}
|
||||
if(args.Contains("--paragraph-backups")){ParagraphBackupTests.Run();return;}
|
||||
if(args.Contains("--import-progress-navigation")){await ImportProgressNavigationTests.Run();return;}
|
||||
if(args.Contains("--core-import-completion")){await CoreImportCompletionTests.Run();return;}
|
||||
if(args.Contains("--paragraph-chapter-dev")){await ParagraphChapterQualificationTests.Run(args.Contains("--repair"));return;}
|
||||
if(args.Contains("--paragraph-chapters")){ParagraphChapterTests.Run();return;}
|
||||
|
||||
@ -21,6 +21,7 @@ public interface IManuscriptScanPreviewStore
|
||||
Task<ManuscriptScanReviewDecision?> SaveReviewAsync(int userId, ManuscriptScanReviewDecision review);
|
||||
Task<ManuscriptScanPreview?> SaveCharacterCandidatesAsync(int userId, Guid previewId, IReadOnlyList<ManuscriptScanCharacterCandidatePreview> candidates);
|
||||
Task<OnboardingBuildProgress> BuildProgressAsync(int userId, Guid previewId, string message, int percentComplete, OnboardingManuscriptBuildResult? result = null);
|
||||
Task<OnboardingBuildProgress?> GetBuildProgressAsync(int userId, Guid previewId) => Task.FromResult<OnboardingBuildProgress?>(null);
|
||||
Task<OnboardingManuscriptBuildResult?> GetBuildResultAsync(int userId, Guid previewId);
|
||||
Task<OnboardingManuscriptBuildResult?> SaveBuildResultAsync(int userId, OnboardingManuscriptBuildResult result);
|
||||
}
|
||||
@ -349,6 +350,10 @@ public sealed class ManuscriptScanPreviewStore(
|
||||
return Task.FromResult(progress);
|
||||
}
|
||||
|
||||
public Task<OnboardingBuildProgress?> GetBuildProgressAsync(int userId, Guid previewId)
|
||||
=> Task.FromResult(previews.TryGetValue(previewId, out var preview) && preview.UserID == userId
|
||||
&& buildProgress.TryGetValue(previewId, out var progress) ? progress : null);
|
||||
|
||||
public Task<OnboardingManuscriptBuildResult?> GetBuildResultAsync(int userId, Guid previewId)
|
||||
=> Task.FromResult(previews.TryGetValue(previewId, out var preview)
|
||||
&& preview.UserID == userId
|
||||
|
||||
@ -105,6 +105,7 @@ public sealed class OnboardingService(
|
||||
SelectedBookTitle = selectedBook is null ? null : BookOptionTitle(selectedBook),
|
||||
CompanionPresence = ToPresenceViewModel(presence),
|
||||
ScanState = ToScanStateViewModel(scanState),
|
||||
BuildProgress = scanState.PreviewID is Guid activePreview ? await scanPreviews.GetBuildProgressAsync(RequireUserId(),activePreview) : null,
|
||||
ProjectOptions = projectOptions,
|
||||
BookOptions = bookOptions,
|
||||
ProjectForm = new ProjectOnboardingForm
|
||||
@ -1765,6 +1766,10 @@ public sealed class OnboardingService(
|
||||
public async Task StartManuscriptImportSetupAsync()
|
||||
{
|
||||
var userId = RequireUserId();
|
||||
var existing = await onboarding.GetAsync(userId);
|
||||
// The normal Import action resumes unfinished work; it must not clear a scan on navigation.
|
||||
if (existing is { OnboardingCompletedUtc: null, BookID: not null, ProjectID: not null }
|
||||
&& existing.WritingJourney == WritingJourneyValues.ManuscriptMostlyComplete) return;
|
||||
var state = await onboarding.SaveWritingJourneyAsync(userId, WritingJourneyValues.ManuscriptMostlyComplete);
|
||||
state = await onboarding.ClearWritingSoftwareAsync(userId);
|
||||
await scanPreviews.ClearAsync(userId, state.UserOnboardingStateID);
|
||||
|
||||
@ -12,7 +12,8 @@ public interface IStoryIntelligenceGlobalProgressService
|
||||
|
||||
public sealed class StoryIntelligenceGlobalProgressService(
|
||||
ICurrentUserService currentUser,
|
||||
IStoryIntelligenceResultRepository runs) : IStoryIntelligenceGlobalProgressService
|
||||
IStoryIntelligenceResultRepository runs, IOnboardingRepository? onboarding=null, IManuscriptScanPreviewStore? scans=null,
|
||||
IOnboardingBuildRepository? builds=null, IBookRepository? bookRepository=null, ICoreImportBasicLocationService? locations=null, IProjectRepository? projects=null) : IStoryIntelligenceGlobalProgressService
|
||||
{
|
||||
public async Task<StoryIntelligenceGlobalProgressViewModel> GetForCurrentUserAsync()
|
||||
{
|
||||
@ -79,7 +80,34 @@ public sealed class StoryIntelligenceGlobalProgressService(
|
||||
|
||||
return new StoryIntelligenceGlobalProgressViewModel
|
||||
{
|
||||
Books = books
|
||||
Books = books, CoreImport = await CoreImport(userId)
|
||||
};
|
||||
}
|
||||
private async Task<CoreImportGlobalProgress?> CoreImport(int user)
|
||||
{
|
||||
if(onboarding==null||scans==null||bookRepository==null)return null;
|
||||
var state=await onboarding.GetAsync(user);
|
||||
if(state==null||state.OnboardingCompletedUtc.HasValue||state.WritingJourney!=WritingJourneyValues.ManuscriptMostlyComplete||state.BookID is not int book)return null;
|
||||
if(projects!=null&&state.ProjectID is int project&&(await projects.GetForUserAsync(project,user))?.IsOwner!=true)return null;
|
||||
var title=await bookRepository.GetAsync(book);
|
||||
if(title==null||title.ProjectID!=state.ProjectID)return null;
|
||||
var scan=await scans.GetStateAsync(user,state.UserOnboardingStateID);
|
||||
if(scan.PreviewID is Guid scoped && (await scans.GetPreviewAsync(user,scoped))?.BookID!=book)return null;
|
||||
CoreImportGlobalProgress Item(string stage,string message,int? percent=null,string url="/onboarding")=>new(book,title.BookDisplayTitle,stage,message,percent,url);
|
||||
if(scan.Status==ManuscriptScanStatuses.Running)return Item("Scanning Word",scan.Message??"Reading your manuscript from Word",scan.PercentComplete);
|
||||
if(scan.Status==ManuscriptScanStatuses.Failed)return Item("Scan needs attention",scan.Message??"Return to the existing import to review the problem");
|
||||
if(scan.PreviewID is not Guid preview)return Item("Continue manuscript setup",state.CurrentStep==OnboardingSteps.WritingSoftware?"Choose your writing software to continue the saved setup":"Return to your saved manuscript setup");
|
||||
var progress=await scans.GetBuildProgressAsync(user,preview);
|
||||
if(progress?.Status=="Running")return Item("Detecting scenes",progress.Message,progress.PercentComplete);
|
||||
if(progress?.Status=="Failed")return Item("Scene detection needs attention",progress.Message);
|
||||
var build=builds==null?null:await builds.GetByPreviewAsync(user,preview);
|
||||
if(build!=null&&build.BookID==book){
|
||||
var done=locations!=null&&await locations.IsCompleteAsync(user,preview);
|
||||
return Item(done?"Review characters":"Review locations","Finish the remaining core import review",url:$"/onboarding/{(done?"scan-characters":"scan-locations")}?previewId={preview:D}");
|
||||
}
|
||||
return scan.ReviewStatus==ManuscriptScanReviewStatuses.ReadyToImport
|
||||
?Item("Ready to detect scenes","Continue scene detection using the accepted manuscript")
|
||||
:Item("Review chapters","Your Word capture is saved; review the detected chapters",url:$"/onboarding/scan-review?previewId={preview:D}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -18,6 +18,7 @@ public sealed class OnboardingWizardViewModel
|
||||
public bool IsMicrosoftWordPath => string.Equals(WritingSoftware, WritingSoftwareValues.MicrosoftWord, StringComparison.Ordinal);
|
||||
public CompanionPresenceViewModel CompanionPresence { get; set; } = new();
|
||||
public ManuscriptScanStateViewModel ScanState { get; set; } = new();
|
||||
public OnboardingBuildProgress? BuildProgress { get; set; }
|
||||
public IReadOnlyList<OnboardingOptionViewModel> Options { get; set; } = [];
|
||||
public IReadOnlyList<OnboardingProjectOptionViewModel> ProjectOptions { get; set; } = [];
|
||||
public IReadOnlyList<OnboardingBookOptionViewModel> BookOptions { get; set; } = [];
|
||||
|
||||
@ -5,7 +5,8 @@ namespace PlotLine.ViewModels;
|
||||
public sealed class StoryIntelligenceGlobalProgressViewModel
|
||||
{
|
||||
public IReadOnlyList<StoryIntelligenceGlobalProgressBookViewModel> Books { get; init; } = [];
|
||||
public bool HasActiveWork => Books.Any(book => book.HasActiveRuns);
|
||||
public CoreImportGlobalProgress? CoreImport { get; init; }
|
||||
public bool HasActiveWork => CoreImport is not null || Books.Any(book => book.HasActiveRuns);
|
||||
public int ActiveBookCount => Books.Count(book => book.HasActiveRuns);
|
||||
public int ActiveRunCount => Books.Sum(book => book.PendingRunCount + book.RunningRunCount);
|
||||
public int TotalExpectedScenes => Books.Sum(book => book.TotalExpectedScenes);
|
||||
@ -106,3 +107,6 @@ public sealed class StoryIntelligenceGlobalProgressRunViewModel
|
||||
or StoryIntelligenceRunStatuses.Failed
|
||||
or StoryIntelligenceRunStatuses.Cancelled;
|
||||
}
|
||||
|
||||
// Projection of the existing wizard/capture/build state, not another import session.
|
||||
public sealed record CoreImportGlobalProgress(int BookID, string BookTitle, string Stage, string Message, int? PercentComplete, string ResumeUrl);
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
ViewData["Title"] = "Set up PlotDirector";
|
||||
var currentJourneyOrder = CurrentJourneyOrder(Model);
|
||||
var structureReadyToImport = string.Equals(Model.ScanState.ReviewStatus, ManuscriptScanReviewStatuses.ReadyToImport, StringComparison.Ordinal);
|
||||
var buildRunning = Model.BuildProgress?.Status == "Running";
|
||||
var reviewedScanAvailable = Model.ScanState.IsComplete || structureReadyToImport;
|
||||
}
|
||||
|
||||
@ -297,14 +298,14 @@
|
||||
<p>@(ViewData["NativeCapture"] is true
|
||||
? "Once your manuscript has been received, scene detection runs on PlotDirector’s server. You may close Word. Native Companion imports do not write scene markers to Word."
|
||||
: "Keep Word open while PlotDirector detects scenes and writes the scene markers.")</p>
|
||||
<div class="onboarding-build-panel" data-onboarding-build-panel hidden>
|
||||
<div class="onboarding-build-panel @(buildRunning?"is-running":"")" data-onboarding-build-panel hidden="@(Model.BuildProgress is null)">
|
||||
<div>
|
||||
<p class="onboarding-scan-next">Detecting scenes</p>
|
||||
<p class="onboarding-build-message" data-onboarding-build-message>Analysing scene boundaries...</p>
|
||||
<p class="onboarding-build-message" data-onboarding-build-message>@(Model.BuildProgress?.Message ?? "Analysing scene boundaries...")</p>
|
||||
</div>
|
||||
<strong data-onboarding-build-percent></strong>
|
||||
<strong data-onboarding-build-percent>@(Model.BuildProgress?.PercentComplete is int percent ? percent + "%" : "")</strong>
|
||||
<div class="onboarding-scan-progress onboarding-build-progress" aria-hidden="true">
|
||||
<span data-onboarding-build-progress></span>
|
||||
<span data-onboarding-build-progress style="width:@(Model.BuildProgress?.PercentComplete ?? 0)%"></span>
|
||||
</div>
|
||||
<div class="onboarding-manual-save-actions" data-onboarding-manual-save-actions hidden>
|
||||
<button class="btn btn-primary btn-sm" type="button" data-onboarding-build-save-confirm disabled>
|
||||
@ -393,9 +394,10 @@
|
||||
<button class="btn btn-primary"
|
||||
type="button"
|
||||
data-onboarding-build-start
|
||||
data-running="@buildRunning.ToString().ToLowerInvariant()"
|
||||
data-onboarding-build-action
|
||||
data-preview-id="@Model.ScanState.PreviewID"
|
||||
disabled="@(!Model.ScanState.PreviewID.HasValue)">
|
||||
disabled="@(!Model.ScanState.PreviewID.HasValue || buildRunning)">
|
||||
Detect Scenes
|
||||
</button>
|
||||
}
|
||||
|
||||
@ -199,9 +199,12 @@
|
||||
@if (User.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
var primaryBook = storyIntelligenceProgress.Books.FirstOrDefault(book => book.HasActiveRuns);
|
||||
var coreImport = storyIntelligenceProgress.CoreImport;
|
||||
var progressUrl = coreImport?.ResumeUrl ?? (primaryBook?.BookID is int activeBook ? $"/Books/Details/{activeBook}" : "/onboarding");
|
||||
var progressUpdatedUtc = storyIntelligenceProgress.UpdatedUtc?.ToUniversalTime().ToString("O", System.Globalization.CultureInfo.InvariantCulture);
|
||||
<div class="story-intelligence-global-strip"
|
||||
data-story-intelligence-global-strip
|
||||
data-core-import="@System.Text.Json.JsonSerializer.Serialize(coreImport)"
|
||||
data-progress-percent="@storyIntelligenceProgress.ProgressPercent"
|
||||
data-total-expected-scenes="@storyIntelligenceProgress.TotalExpectedScenes"
|
||||
data-completed-scenes="@storyIntelligenceProgress.CompletedScenes"
|
||||
@ -215,10 +218,12 @@
|
||||
aria-live="polite"
|
||||
hidden="@(!storyIntelligenceProgress.HasActiveWork)">
|
||||
<div class="story-intelligence-global-strip__inner">
|
||||
<div class="story-intelligence-global-strip__copy">
|
||||
<a class="story-intelligence-global-strip__copy" data-story-intelligence-global-link href="@progressUrl">
|
||||
<span class="story-intelligence-global-strip__dot" aria-hidden="true"></span>
|
||||
<strong data-story-intelligence-global-title>@storyIntelligenceProgress.SummaryText</strong>
|
||||
<strong data-story-intelligence-global-title>@(coreImport is null ? storyIntelligenceProgress.SummaryText : coreImport.BookTitle + " · " + coreImport.Stage)</strong>
|
||||
<span data-story-intelligence-global-detail>
|
||||
@if(coreImport is not null){<text>@coreImport.Message</text>}else{
|
||||
<span>
|
||||
@storyIntelligenceProgress.CompletedScenes.ToString("N0") of @storyIntelligenceProgress.TotalExpectedScenes.ToString("N0") scenes analysed
|
||||
@if (storyIntelligenceProgress.FailedScenes > 0)
|
||||
{
|
||||
@ -228,15 +233,13 @@
|
||||
{
|
||||
<text> · @primaryBook.EstimatedRemaining remaining</text>
|
||||
}
|
||||
</span>}
|
||||
</span>
|
||||
</div>
|
||||
</a>
|
||||
<div class="story-intelligence-global-strip__meter" aria-hidden="true">
|
||||
<span data-story-intelligence-global-bar style="width: @storyIntelligenceProgress.ProgressPercent%"></span>
|
||||
<span data-story-intelligence-global-bar style="width: @(coreImport?.PercentComplete ?? storyIntelligenceProgress.ProgressPercent)%"></span>
|
||||
</div>
|
||||
@if (primaryBook?.BookID is int progressBookId)
|
||||
{
|
||||
<a class="btn btn-outline-secondary btn-sm" asp-controller="Books" asp-action="Details" asp-route-id="@progressBookId">Book</a>
|
||||
}
|
||||
<a class="btn btn-outline-secondary btn-sm" data-story-intelligence-global-link data-story-intelligence-global-action href="@progressUrl">@(coreImport is null ? "Book" : "Return to import")</a>
|
||||
</div>
|
||||
<div hidden aria-hidden="true" data-story-intelligence-global-runs>
|
||||
@foreach (var book in storyIntelligenceProgress.Books)
|
||||
|
||||
@ -85,3 +85,6 @@
|
||||
max-width: calc(100vw - 7rem);
|
||||
}
|
||||
}
|
||||
|
||||
a.story-intelligence-global-strip__copy { color: inherit; text-decoration: none; }
|
||||
a.story-intelligence-global-strip__copy:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; }
|
||||
|
||||
@ -33,6 +33,22 @@
|
||||
const formatCount = (value) => new Intl.NumberFormat().format(Math.max(0, value || 0));
|
||||
const keyFor = (projectId, bookId) => `${projectId || ""}:${bookId || ""}`;
|
||||
const field = (state, camel, pascal) => state?.[camel] ?? state?.[pascal] ?? null;
|
||||
let coreImport = null;
|
||||
try { coreImport = JSON.parse(strip.dataset.coreImport || "null"); } catch { /* Legacy page without a core snapshot. */ }
|
||||
const setLink = (url, label) => {
|
||||
if (typeof url !== "string" || !/^\/(onboarding(?:[/?]|$)|Books\/Details\/\d+)/i.test(url) || url.startsWith("//")) return;
|
||||
strip.querySelectorAll("[data-story-intelligence-global-link]").forEach(node => { node.href = url; });
|
||||
const action = strip.querySelector("[data-story-intelligence-global-action]"); if (action) action.textContent = label;
|
||||
};
|
||||
const renderCore = () => {
|
||||
if (!coreImport) return false;
|
||||
strip.hidden = false; strip.dataset.storyIntelligenceHasActiveWork = "true";
|
||||
if (title) title.textContent = `${field(coreImport,"bookTitle","BookTitle") || "Manuscript"} · ${field(coreImport,"stage","Stage") || "Import"}`;
|
||||
if (detail) detail.textContent = field(coreImport,"message","Message") || "Return to your existing import";
|
||||
if (bar) bar.style.width = `${Math.max(0, Math.min(100, readNumber(field(coreImport,"percentComplete","PercentComplete")) || 0))}%`;
|
||||
setLink(field(coreImport,"resumeUrl","ResumeUrl"), "Return to import");
|
||||
return true;
|
||||
};
|
||||
const isActiveStatus = (status) => status === "Pending" || status === "Running";
|
||||
const isFailedStatus = (status) => status === "Failed" || status === "Cancelled";
|
||||
const estimateRemaining = (elapsedMs, completed, failed, total, status) => {
|
||||
@ -180,6 +196,8 @@
|
||||
};
|
||||
|
||||
const render = (progress) => {
|
||||
if (progress && (Object.hasOwn(progress, "coreImport") || Object.hasOwn(progress, "CoreImport"))) coreImport = field(progress, "coreImport", "CoreImport");
|
||||
if (renderCore()) return;
|
||||
const snapshotBooks = progress?.books || progress?.Books || [];
|
||||
if (!snapshotBooks.length) {
|
||||
books.clear();
|
||||
@ -192,6 +210,7 @@
|
||||
seedRunsFromSnapshot(progress);
|
||||
const primarySnapshot = snapshotBooks.find((book) => book.hasActiveRuns || book.HasActiveRuns) || snapshotBooks[0];
|
||||
const primary = books.get(keyFor(primarySnapshot.projectID ?? primarySnapshot.projectId, primarySnapshot.bookID ?? primarySnapshot.bookId)) || seedBook(primarySnapshot);
|
||||
setLink(`/Books/Details/${primary.bookId}`, "Book");
|
||||
const runSummary = runSummaryForBook(primary);
|
||||
const activeBookCount = readNumber(progress.activeBookCount ?? progress.ActiveBookCount) || snapshotBooks.length;
|
||||
const status = progress.status || progress.Status || primary.status || primary.Status || "";
|
||||
@ -389,5 +408,14 @@
|
||||
});
|
||||
};
|
||||
|
||||
renderCore();
|
||||
// Reuse the authoritative global watcher while core work exists; no new session or transport.
|
||||
const coreRefresh = () => { if (coreImport && !document.hidden && connection.state === "Connected") refresh(); };
|
||||
let coreTimer = null;
|
||||
const startCoreTimer = () => { if (coreTimer === null) coreTimer = window.setInterval(coreRefresh, 15000); };
|
||||
startCoreTimer();
|
||||
window.addEventListener("pageshow", () => { startCoreTimer(); if (connection.state === "Connected") refresh(); });
|
||||
document.addEventListener("visibilitychange", () => { if (!document.hidden && connection.state === "Connected") refresh(); });
|
||||
window.addEventListener("pagehide", () => { window.clearInterval(coreTimer); coreTimer = null; });
|
||||
startWithRetry();
|
||||
})();
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user