From b4a1d4472dc5d105254df3573f73ea0cae28d75e Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Mon, 16 Nov 2026 23:06:36 +0000 Subject: [PATCH] Integrate canonical manuscript review and anchored author observations --- Docs/Writer/Writer3/Help-Coverage.md | 4 + Docs/Writer/Writer3/Implementation-Tracker.md | 7 +- Docs/Writer/Writer3/Phase3C-Execution.md | 27 ++++++ PlotLine.Tests/Browser/writer3-authoring.cjs | 2 +- .../Browser/writer3-layout-explore.cjs | 3 + .../Browser/writer3-navigation-live.cjs | 2 +- PlotLine.Tests/Browser/writer3-navigation.cjs | 2 +- PlotLine.Tests/Browser/writer3-review.cjs | 17 ++++ PlotLine.Tests/ManuscriptReaderTests.cs | 9 +- PlotLine.Tests/Program.cs | 1 + PlotLine.Tests/ToolbarBrowserHost.cs | 6 +- PlotLine.Tests/WriterNavigationTests.cs | 2 +- PlotLine.Tests/WriterReviewFixture.cs | 10 +++ PlotLine.Tests/WriterReviewTests.cs | 18 ++++ PlotLine.Tests/WriterWordTests.cs | 2 + .../Controllers/ManuscriptReaderController.cs | 2 +- PlotLine/Controllers/WriterController.cs | 14 ++- .../Controllers/WriterReviewController.cs | 15 ++++ PlotLine/Controllers/WriterWordController.cs | 4 +- .../Articles/Workspace/Writer3-explore.md | 10 ++- .../Help/Articles/Workspace/Writer3-review.md | 24 +++--- .../Articles/Workspace/Writer3-reviewing.md | 40 +++++++++ PlotLine/Program.cs | 1 + .../Manuscript/ManuscriptReaderService.cs | 14 +-- PlotLine/Services/ProjectAccessFilter.cs | 1 + .../Services/Writer/WriterReviewService.cs | 62 ++++++++++++++ PlotLine/Services/Writer/WriterWordService.cs | 9 +- PlotLine/Sql/272_WriterReviewObservations.sql | 70 +++++++++++++++ PlotLine/ViewModels/CoreViewModels.cs | 2 + PlotLine/Views/ManuscriptReader/Index.cshtml | 79 +---------------- .../Views/ManuscriptReader/_Paragraphs.cshtml | 6 +- .../Views/ManuscriptReader/_Reader.cshtml | 85 +++++++++++++++++++ PlotLine/Views/Writer/Destination.cshtml | 1 + PlotLine/Views/Writer/_ReviewContext.cshtml | 25 ++++++ PlotLine/Views/Writer/_WriterExplore.cshtml | 8 +- PlotLine/Views/Writer/_WriterReview.cshtml | 41 +++++---- PlotLine/Views/Writer/_WriterWord.cshtml | 7 +- PlotLine/wwwroot/css/writer3.css | 18 ++++ PlotLine/wwwroot/js/manuscript-reader.js | 11 ++- PlotLine/wwwroot/js/writer-review.js | 29 +++++++ PlotLine/wwwroot/js/writer-word.js | 11 ++- PlotLine/wwwroot/js/writer3-workspace.js | 2 +- 42 files changed, 552 insertions(+), 151 deletions(-) create mode 100644 Docs/Writer/Writer3/Phase3C-Execution.md create mode 100644 PlotLine.Tests/Browser/writer3-layout-explore.cjs create mode 100644 PlotLine.Tests/Browser/writer3-review.cjs create mode 100644 PlotLine.Tests/WriterReviewFixture.cs create mode 100644 PlotLine.Tests/WriterReviewTests.cs create mode 100644 PlotLine/Controllers/WriterReviewController.cs create mode 100644 PlotLine/Help/Articles/Workspace/Writer3-reviewing.md create mode 100644 PlotLine/Services/Writer/WriterReviewService.cs create mode 100644 PlotLine/Sql/272_WriterReviewObservations.sql create mode 100644 PlotLine/Views/ManuscriptReader/_Reader.cshtml create mode 100644 PlotLine/Views/Writer/_ReviewContext.cshtml create mode 100644 PlotLine/wwwroot/js/writer-review.js diff --git a/Docs/Writer/Writer3/Help-Coverage.md b/Docs/Writer/Writer3/Help-Coverage.md index e22d855c..0cfa6545 100644 --- a/Docs/Writer/Writer3/Help-Coverage.md +++ b/Docs/Writer/Writer3/Help-Coverage.md @@ -106,3 +106,7 @@ Phase3A qualification exercises the dynamically loaded authoring Help icon in br `writer3.word` uses existing micro/quick/full Markdown Help in the Write companion. It covers exact manuscript selection, verified position, working-focus/session/Reader independence, acknowledged chapter and optional verified-scene navigation, accepted-content freshness, bounded saved-manuscript checks, recovery, multiple documents and return/adopt. Check controls and additional explanation use optional Connection and update options. Updated `writer3.write` links the concepts; existing native/Reader/standalone Help remains authoritative. Qualification and physical Windows limits are recorded in Phase3B-Report.md. Phase3B qualified: quick popup, More drawer and full writer3.word article verified in authenticated Development browser/simulated PWA. Current Word status/navigation fixtures also cover hidden title-bar presence and cached return. Physical installed PWA/Word and assistive-technology acceptance remain manual; see Phase3B-Report.md. + +## Phase3C integrated Review + +`writer3.reviewing` covers accepted reading, independent selection, chapter/verified scene context, author-private observations, explicit Save/Cancel/edit/resolve/reopen, original version/paragraph references, missing/changed anchors, verified paragraph-start versus chapter handoff, Audio Review and provenance. `writer3.review` describes the integrated Reader and `writer3.explore` describes the corrected authenticated tools rather than public Solver journeys. Existing micro/quick/full Help infrastructure is reused. Qualification and physical acceptance limits are recorded in Phase3C-Report.md. diff --git a/Docs/Writer/Writer3/Implementation-Tracker.md b/Docs/Writer/Writer3/Implementation-Tracker.md index 8955323c..510259c2 100644 --- a/Docs/Writer/Writer3/Implementation-Tracker.md +++ b/Docs/Writer/Writer3/Implementation-Tracker.md @@ -1,6 +1,6 @@ # Writer 3.0 implementation tracker -Baseline: `9a8b9a3`, shared branch `codex/word-companion-native-phase1-20261104`, 16 November 2026. The original kickoff authorised Phase 1 implementation and Development deployment; the master specification governs product direction even though its header says Proposed. The subsequent Phase2A kickoff explicitly authorised Home, navigation, destination shells and Development deployment; Phase2B was subsequently explicitly authorised for layout infrastructure and Development deployment; Phase2C is implemented and Development-qualified, including the explicit single-focus workflow amendment; Phase3A integrated authoring is implemented and Development-qualified; Phase3B verified Word continuity is implemented and Development-qualified, with physical Windows acceptance outstanding; Phase3C remains unauthorised. No feature is retired. Unrelated investigation file is preserved. +Baseline: `9a8b9a3`, shared branch `codex/word-companion-native-phase1-20261104`, 16 November 2026. The original kickoff authorised Phase 1 implementation and Development deployment; the master specification governs product direction even though its header says Proposed. The subsequent Phase2A kickoff explicitly authorised Home, navigation, destination shells and Development deployment; Phase2B was subsequently explicitly authorised for layout infrastructure and Development deployment; Phase2C is implemented and Development-qualified, including the explicit single-focus workflow amendment; Phase3A integrated authoring is implemented and Development-qualified; Phase3B verified Word continuity is implemented and Development-qualified, with physical Windows acceptance outstanding; Phase3C is explicitly authorised for integrated Review; Phase4 remains unauthorised. No feature is retired. Unrelated investigation file is preserved. ## Phase 1 screen and interaction states before implementation @@ -355,3 +355,8 @@ Application `e9402d0c1673d3dc8afcca26bb344b82fa11caf0`, release `e9402d0-2026111 Batches3B.1–3B.6: native contract audit, shared Word status presentation, explicit acknowledged chapter/scene navigation, accepted Reader freshness, return/recovery, Help/qualification/Development. Existing native identity/range/checkpoint/Reader/session/follow contracts remain authoritative. Additive read-only metadata procedure271 and negotiated acknowledged-navigation-v1; matched native developer source1.0.0.37, no Windows installation. Writer companion shows Word status without displacing intentions or active-session controls. Detailed qualification and final release are in Phase3B-Report.md. Phase3C/4 not started by this authorisation. Phase3B software qualification complete: application/native source9969c9b, Development release9969c9b-20261116T210203Z;599 web,288 native and453 chapter-sync assertions; authenticated read-only data hashes unchanged and disposable fixture removed. Matched1.0.0.37 Windows build/install/physical acceptance remains manual. Phase3C not started. + + +## Phase3C authorised implementation + +Batches3C.1–3C.6 integrate the canonical Reader, pure chapter/scene intentions, author observations and decisions, existing acknowledged Word handoff, Audio Review and optional saved finding tools. Baseline55bdce3 includes Windows1.0.0.40 and Return to Writer/recording fixes; native source is unchanged in3C. Observations use a new author-private anchored store only because scene/session notes and machine findings cannot represent chapter/accepted-version references. Shared compact viewport geometry and bounded authenticated Explore routing are separate corrections. See Phase3C-Execution.md and Phase3C-Report.md for contracts, qualification and release. Phase4 is not started. diff --git a/Docs/Writer/Writer3/Phase3C-Execution.md b/Docs/Writer/Writer3/Phase3C-Execution.md new file mode 100644 index 00000000..aed3ca6d --- /dev/null +++ b/Docs/Writer/Writer3/Phase3C-Execution.md @@ -0,0 +1,27 @@ +# Phase3C execution and persistence contract + +Scope: Phase3C only. Fetched and fast-forwarded81b57a5 to55bdce3 before editing, preserving merged Windows ribbon/Audio Review, typed authenticated Return to Writer and independent recording-control corrections. Native source version1.0.0.40; this phase changes no native binaries/contracts or Windows installation. + +## 3C.1–3C.2 + +Review previously linked to Reader. The existing canonical Reader is now a shared Razor partial embedded in Review, keeping its controller, accepted-version requests, selectable text, paragraph renderer, Focused Reading, refresh/pause/selection/anchor policy and session toolbar. Review URL chapters remain separate from saved objectives and session/Word/pinned/Intent targets. Scene context comes only from accepted paragraph assignments, with chapter fallback for unknown, mixed, stale or unavailable scenes. Existing Phase3A pure authoring service provides intentions, notes/reminders and workflow. Full editing uses existing canonical editors in another window rather than reproducing Write. + +## 3C.3 storage decision + +SceneNotes cannot represent chapter-level observations, accepted version or paragraph ranges. Session return notes require a real session and have separate retention/lifecycle. Story Intelligence/native suggestions carry machine provenance and author approval semantics; they are not free-form reader annotations. No existing suitable anchored author-review store was found. New author-private WriterReviewObservations therefore holds only entered observation/decision, its own Open/Working/Resolved state, immutable accepted manuscript/version/paragraph/offset/hash references and timestamps. No copied quote, manuscript-specific logic or inferred fact is stored. + +Migration272 adds scoped stored procedures, the observation table and a pure paragraph-position lookup reusing existing current checkpoint/hash/identity joins. Chapter/user cascades and book foreign key support existing guarded deletion. Author/book/chapter checks, optimistic versions, client-generated idempotency IDs and canonical-revision locking protect writes. Creation validates the displayed chapter fingerprint and exact range; update cannot change original references. Resolving never changes canonical scene status, sessions or prose. Pagination bounds list payloads. Reads do not seed rows. + +## 3C.4–3C.5 + +Review reuses Phase3B acknowledged navigation. Optional paragraph handoff uses exact current accepted revision/paragraph plus live proof and targets the paragraph start, not an assumed character range. Rejection never automatically falls back; the separate verified chapter action remains explicit. Native identity/session/revision/expiry/ack fences stay intact. Reader metadata-only changes update its revision without replacing text. No observation is resolved by accepted text changing. Missing references never search for similar text. + +Existing Audio Review controls, target/UUID, timing, native media safeguards and return notes remain in the shared Reader toolbar. Observation saves replace only the companion's recorded context/list. Dirty editors pause Reader replacement and restore the prior pause preference on Save/Cancel. Existing findings remain distinct optional Intent/book tool routes; opening Review invokes no analysis. + +## 3C.6 bounded follow-ups + +Five-destination geometry captures at1440,1024 and390 showed normal viewport-bottom fit before changes, with a large header consuming work area. Shared compact header/tools reclaim height; viewport measurement uses rendered rather than document-relative top, fixing scrolled-shell subtraction. Reader is not constrained by a second fixed-height scrollport. Resizing/collapse/overlay/short-window flow remain authoritative. + +Explore's first two choices pointed at public Problem Solver routes. They now use authenticated scoped Write and Plot Lines/threads, with honest tool labels. Timeline remains the distinct authenticated shape tool. No iframe or Phase5 guided engine is introduced. + +Qualification, deployment, data hashes, screenshots, native baseline and remaining physical acceptance are recorded in Phase3C-Report.md. Phase4 is not started. diff --git a/PlotLine.Tests/Browser/writer3-authoring.cjs b/PlotLine.Tests/Browser/writer3-authoring.cjs index 374092f3..e18983f0 100644 --- a/PlotLine.Tests/Browser/writer3-authoring.cjs +++ b/PlotLine.Tests/Browser/writer3-authoring.cjs @@ -15,7 +15,7 @@ const{chromium}=require('playwright'),assert=require('node:assert/strict'); // A second page commits first; the original editor must retain its stale unsaved text with409. await edit('Scene-31');await card('Scene-31').locator('[name=ScenePurposeNotes]').fill('Stale unsaved intention');const q=await c.newPage();await q.goto(url);const other=q.locator('[data-key="Scene-31"]');await other.locator('[data-authoring-edit]').click();await other.locator('[name=ScenePurposeNotes]').fill('Concurrent author change');await other.locator('[data-authoring-save]').click();await other.locator('[data-authoring-status]').filter({hasText:'Saved.'}).waitFor();await q.close();await card('Scene-31').locator('[data-authoring-save]').click();await card('Scene-31').locator('[data-authoring-reload]:visible').waitFor();assert.equal(await card('Scene-31').locator('[name=ScenePurposeNotes]').inputValue(),'Stale unsaved intention'); p.once('dialog',d=>d.dismiss());await p.locator('#ribbon-panel-writer').getByRole('link',{name:'Explore',exact:true}).click();assert(new URL(p.url()).pathname==='/Writer/Write');await card('Scene-31').locator('[data-authoring-cancel]').click(); - const session={sessionID:'33333333-3333-3333-3333-333333333333',kind:'AudioReview',bookID:12,chapterID:22,chapterTitle:'Bound audio chapter',startedUtc:new Date().toISOString(),engagedSeconds:60,playbackSeconds:20,uniqueSeconds:10,pauseOnEdit:true,live:true,playbackState:'playing',capabilities:'play,pause,back15,forward15',sequence:1};await p.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session}}));await p.goto(url);await p.locator('[data-work-audio]:visible').waitFor();await card('Scene-31').waitFor();assert(await p.locator('.writer3-session-block').evaluate(n=>n.nextElementSibling?.matches('[data-writer-authoring]')),'active controls remain above authoring');const work=await p.locator('[data-writer-work]').elementHandle();await p.locator('[data-work-note]').fill('Unsaved audio return note');await edit('Scene-31');await card('Scene-31').locator('[name=SceneOutcomeNotes]').fill('An explicit outcome during audio review');await save('Scene-31');assert(await work.evaluate(n=>n===document.querySelector('[data-writer-work]')));assert.equal(await p.locator('[data-work-note]').inputValue(),'Unsaved audio return note');assert((await p.locator('[data-work-bound]').textContent()).includes('Bound audio chapter'));assert.equal(await p.locator('[data-work-start] select').count(),0); + const session={sessionID:'33333333-3333-3333-3333-333333333333',kind:'AudioReview',bookID:12,chapterID:22,chapterTitle:'Bound audio chapter',startedUtc:new Date().toISOString(),engagedSeconds:60,playbackSeconds:20,uniqueSeconds:10,pauseOnEdit:true,live:true,playbackState:'playing',capabilities:'play,pause,back15,forward15',sequence:1};await p.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session}}));await p.goto(url);await p.locator('[data-work-audio]:visible').waitFor();await card('Scene-31').waitFor();assert(await p.locator('.writer3-session-block').evaluate(n=>n.nextElementSibling?.matches('[data-writer-authoring]')),'active controls remain above authoring');const work=await p.locator('[data-writer-work]').elementHandle();await p.locator('[data-work-note]').fill('Unsaved audio return note');await edit('Scene-31');await card('Scene-31').locator('[name=SceneOutcomeNotes]').fill('An explicit outcome during audio review');await save('Scene-31');assert(await work.evaluate(n=>n===document.querySelector('[data-writer-work]')));assert.equal(await p.locator('[data-work-note]').inputValue(),'Unsaved audio return note');assert((await p.locator('[data-work-bound]').textContent()).includes('Bound audio chapter'));assert.equal(await p.locator('[data-work-start] select').count(),2,'Windows baseline retains independent recording activity and chapter controls'); await p.setViewportSize({width:390,height:844});await p.locator('.writer3-layout-tools button').first().click();assert(await p.locator('[data-authoring-references]').isVisible());await p.keyboard.press('Escape');assert(await p.locator('.writer3-reference').isHidden());assert(await p.locator('[data-authoring-content]').isVisible()); await p.goto(url+'&chapterOnly=true');await p.locator('[data-key="Goals-21"]').waitFor();assert.equal(await p.locator('[data-key="Scene-31"]').count(),0);assert(await p.getByRole('button',{name:'Work on this scene'}).isVisible()); await p.goto('http://127.0.0.1:5238/Writer/Write?projectId=7&bookId=13');assert.equal(await p.locator('[data-writer-authoring]').count(),0,'book switching cannot keep old support fields');assert.equal((await p.request.get('http://127.0.0.1:5238/WriterAuthoring/Inspect?bookId=13&chapterId=21&sceneId=31')).status(),404);assert.deepEqual(errors,[]);await c.close();} diff --git a/PlotLine.Tests/Browser/writer3-layout-explore.cjs b/PlotLine.Tests/Browser/writer3-layout-explore.cjs new file mode 100644 index 00000000..6a81aeb2 --- /dev/null +++ b/PlotLine.Tests/Browser/writer3-layout-explore.cjs @@ -0,0 +1,3 @@ +const{chromium}=require('playwright'),assert=require('node:assert/strict'); +(async()=>{const b=await chromium.launch();try{const p=await b.newPage({viewport:{width:1440,height:1000}});for(const destination of['Write','Explore','Plan','Review','Reflect']){const r=await p.goto(`http://127.0.0.1:5238/Writer/${destination}?projectId=7&bookId=12`);assert.equal(r.status(),200);await p.waitForFunction(()=>document.querySelector('.writer3')?.classList.contains('writer3-viewport'));await p.evaluate(async()=>{await document.fonts.ready;await new Promise(r=>setTimeout(r,50))});const normal=await p.evaluate(()=>({header:document.querySelector('.writer3-header').getBoundingClientRect().height,bottom:document.querySelector('.writer3-workspace').getBoundingClientRect().bottom,height:innerHeight}));assert(normal.header<85,'compact shared header');assert(normal.height-normal.bottom<12,'uses available viewport');await p.evaluate(()=>{document.documentElement.style.overflow='auto';document.documentElement.style.height='auto';document.body.style.overflow='visible';document.body.style.height='auto';document.body.style.minHeight='1800px';document.body.style.paddingTop='180px';window.scrollTo({top:150,behavior:'instant'});window.dispatchEvent(new Event('resize'));});await p.waitForFunction(()=>{const w=document.querySelector('.writer3-workspace');return Math.abs(innerHeight-w.getBoundingClientRect().bottom)<12});assert(await p.evaluate(()=>window.scrollY>100),'scrolled shell fixture');} +await p.goto('http://127.0.0.1:5238/Writer/Explore?projectId=7&bookId=12');const links=await p.locator('.writer3-explore-paths>a').evaluateAll(ns=>ns.map(n=>n.href));assert.equal(links.length,3);for(const href of links){const u=new URL(href);assert(!u.pathname.includes('problem-solver'));assert.equal(u.searchParams.get('projectId'),'7');assert.equal(u.searchParams.get('bookId'),'12');}assert.equal(new Set(links.map(x=>new URL(x).pathname)).size,3);assert.equal(await p.locator('iframe').count(),0);console.log('PASS five destinations compact viewport use and controlled scrolled-shell geometry; Explore has three distinct authenticated scoped tool routes and no public solver/iframe.');}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/PlotLine.Tests/Browser/writer3-navigation-live.cjs b/PlotLine.Tests/Browser/writer3-navigation-live.cjs index 457a2331..5493bef3 100644 --- a/PlotLine.Tests/Browser/writer3-navigation-live.cjs +++ b/PlotLine.Tests/Browser/writer3-navigation-live.cjs @@ -13,7 +13,7 @@ const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('nod assert.equal(await p.locator('[data-writer-destination]').getAttribute('data-writer-destination'),action==='Index'?'Home':action); if(action==='Write'&&book===w.book)assert((await p.getByRole('link',{name:'Open current scene',exact:true}).getAttribute('href')).includes('/'+w.scene)); if(action==='Write'&&book===w.other)assert.equal(await p.getByRole('heading',{name:'Where would you like to begin?',exact:true}).isVisible(),true); - if(action==='Review'&&book===w.other)assert.equal(await p.getByRole('heading',{name:'No chapters to read yet',exact:true}).isVisible(),true); + if(action==='Review'&&book===w.other)assert.equal(await p.getByRole('heading',{name:'No chapters yet',exact:true}).isVisible(),true); if(!pwa&&book===w.book&&process.env.PD_WRITER3_SCREENSHOTS){await p.evaluate(()=>window.PlotDirectorApplyApplicationTheme('modern-dark'));fs.mkdirSync(process.env.PD_WRITER3_SCREENSHOTS,{recursive:true});await p.screenshot({path:`${process.env.PD_WRITER3_SCREENSHOTS}/${action==='Index'?'Home':action}-Development.png`,fullPage:true});} } for(const [index,action]of[[0,'Write'],[1,'Explore'],[2,'Dashboard']]){await p.goto(`${base}/Writer?projectId=${w.project}&bookId=${w.book}`);await p.locator('.writer3-home-choices>a').nth(index).click();await p.waitForURL(`**/Writer/${action}?*`);assert.equal(new URL(p.url()).searchParams.get('bookId'),String(w.book));} diff --git a/PlotLine.Tests/Browser/writer3-navigation.cjs b/PlotLine.Tests/Browser/writer3-navigation.cjs index ca9066c5..a48d2f6a 100644 --- a/PlotLine.Tests/Browser/writer3-navigation.cjs +++ b/PlotLine.Tests/Browser/writer3-navigation.cjs @@ -21,7 +21,7 @@ const base='http://127.0.0.1:5238'; const commands=page.locator('#ribbon-panel-writer [role=group]').first().locator('a'); assert.deepEqual((await commands.locator('span:not([aria-hidden])').allTextContents()).map(x=>x.trim()),['Home','Write','Explore','Plan','Review','Reflect']); assert((await page.locator('#ribbon-panel-writer a[aria-current=page]').allTextContents()).some(t=>t.trim()===(destination==='Index'?'Home':destination==='Dashboard'?'Writing Dashboard':destination))); - assert.equal(await page.locator('.writer3 nav').count(),0,'No duplicate destination navigation bar'); + assert.equal(await page.locator('.writer3 nav:not(.reader-controls)').count(),0,'No duplicate destination navigation bar; canonical Reader chapter navigation is independent'); const contrasts=await page.locator('a.writer3-cta').evaluateAll(nodes=>{const lum=s=>{const rgb=s.match(/[\d.]+/g).slice(0,3).map(Number).map(x=>{x/=255;return x<=.04045?x/12.92:((x+.055)/1.055)**2.4});return rgb[0]*.2126+rgb[1]*.7152+rgb[2]*.0722};return nodes.map(n=>{const c=getComputedStyle(n),a=lum(c.color),b=lum(c.backgroundColor);return (Math.max(a,b)+.05)/(Math.min(a,b)+.05)})});assert(contrasts.every(x=>x>=4.5),'Primary action labels must have readable contrast'); const overflow=await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2);assert.equal(overflow,false,`${pwa}/${theme}/${width}/${kind} horizontal overflow`); if(kind==='Home'){ diff --git a/PlotLine.Tests/Browser/writer3-review.cjs b/PlotLine.Tests/Browser/writer3-review.cjs new file mode 100644 index 00000000..d360ebb4 --- /dev/null +++ b/PlotLine.Tests/Browser/writer3-review.cjs @@ -0,0 +1,17 @@ +const{chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); +(async()=>{const b=await chromium.launch();try{for(const pwa of[false,true]){const c=await b.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()})));if(pwa)await c.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));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 lease={instanceId:'11111111-1111-1111-1111-111111111111',sessionId:'22222222-2222-2222-2222-222222222222',manuscriptId:'33333333-3333-3333-3333-333333333333',bookId:12,wordAvailable:true,wordSaved:true,canAcknowledgeNavigation:true,canChapterSync:true,revision:2,documentTitle:'Simulated review manuscript',chapterId:22,chapterTitle:'Other Word chapter',expires:new Date(Date.now()+3600000).toISOString(),updated:new Date().toISOString()};await c.route('**/native-companion/status*',r=>r.fulfill({json:{leases:[lease],canonical:{manuscriptID:lease.manuscriptId},verifiedPositions:[{instanceId:lease.instanceId,sessionId:lease.sessionId,chapterId:22,chapterTitle:'Other Word chapter'}]}}));await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:{sessionID:'55555555-5555-5555-5555-555555555555',kind:'AudioReview',bookID:12,chapterID:22,chapterTitle:'Bound audio chapter',startedUtc:new Date().toISOString(),engagedSeconds:60,playbackSeconds:20,uniqueSeconds:10,pauseOnEdit:true,live:true,playbackState:'playing',capabilities:'play,pause,back15,forward15',sequence:1},defaultPauseOnEdit:true}})); +let nativePosts=[],rejectParagraph=false,savePosts=0;await c.route('**/WriterWord/Navigate',r=>{const values=Object.fromEntries(new URLSearchParams(r.request().postData()));nativePosts.push(values);return r.fulfill(rejectParagraph&&values.paragraphId?{status:409,json:{message:'Paragraph is no longer verified; use the separate chapter action.'}}:{status:202,json:{message:'requested'}})});await c.route('**/WriterWord/Navigation?*',r=>r.fulfill({json:{state:'completed'}})); +const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));p.on('request',r=>{if(r.method()==='POST'&&new URL(r.url()).pathname==='/WriterReview/Save')savePosts++});const url='http://127.0.0.1:5238/Writer/Review?projectId=7&bookId=12';const initialResponse=await p.goto(url);assert.equal(initialResponse.status(),200);assert.match(initialResponse.headers()['cache-control'],/no-store/);assert.match(initialResponse.headers()['x-robots-tag'],/noindex/);await p.locator('[data-review-panel]').waitFor();assert(await p.locator('.reader-page').isVisible());assert.equal(nativePosts.length,0);assert.equal(savePosts,0); +await p.getByText('Reading & Audio Review',{exact:true}).click();await p.locator('[data-work-audio]:visible').waitFor();await p.locator('[data-work-note]').fill('Retained review return note');const work=await p.locator('[data-writer-work]').elementHandle(); +const passage=p.locator('[data-paragraph-id][data-scene-id="31"]').first();const id=await passage.getAttribute('data-paragraph-id');await passage.evaluate(n=>{const r=document.createRange();r.selectNodeContents(n);r.setStart(n.firstChild,3);r.setEnd(n.firstChild,15);getSelection().removeAllRanges();getSelection().addRange(r)});await p.locator('[data-review-record]').click();const form=p.locator('[data-review-form]');assert(await form.isVisible());assert.equal(await form.locator('[name=StartParagraph]').inputValue(),id);assert.equal(await form.locator('[name=StartOffset]').inputValue(),'3');assert(await p.locator('#reader-pause').isChecked());await p.locator('[data-review-context]').getByText('Scene context comes from accepted paragraph assignments.',{exact:true}).waitFor();assert.equal(savePosts,0,'selection and editor opening never persist'); +await form.locator('[name=Observation]').fill('A review observation — 界 ');await form.locator('[name=Decision]').fill('I want to clarify this detail.');const observationID=await form.locator('[name=ID]').inputValue();await form.evaluate(n=>{n.requestSubmit();n.requestSubmit()});await p.locator('[data-review-message]').filter({hasText:'Observation saved.'}).waitFor();assert.equal(savePosts,1);const row=()=>p.locator(`[data-observation][data-id="${observationID}"]`);await row().waitFor();assert.equal(await row().getAttribute('data-first'),id);assert((await row().textContent()).includes(''));assert(await work.evaluate(n=>n===document.querySelector('[data-writer-work]')));assert.equal(await p.locator('[data-work-note]').inputValue(),'Retained review return note');assert((await p.locator('[data-work-bound]').textContent()).includes('Bound audio chapter')); +for(const state of['Working','Resolved','Open']){await row().locator('[data-review-edit]').click();await form.waitFor({state:'visible'}).catch(async e=>{throw Error(`${e.message}; ${await p.locator('[data-review-message]').textContent()}; hidden=${await form.getAttribute('hidden')}`)});await form.locator('[name=Status]').selectOption(state);await form.locator('[data-review-save]').click();await form.waitFor({state:'hidden'});await row().locator(`[data-review-edit][data-state="${state}"]`).waitFor();assert.equal(await row().getAttribute('data-first'),id);} +await row().locator('[data-review-edit]').click();await form.locator('[name=Observation]').fill('Keep this stale draft');const q=await c.newPage();await q.goto(url);const other=q.locator(`[data-observation][data-id="${observationID}"]`);await other.locator('[data-review-edit]').click();await q.locator('[data-review-form] [name=Observation]').fill('Saved by the other review window');await q.locator('[data-review-save]').click();await q.locator('[data-review-form]').waitFor({state:'hidden'}).catch(async e=>{throw Error(`${e.message}; ${await q.locator('[data-review-error]').textContent()}`)});await q.close();await form.locator('[data-review-save]').click();await form.locator('[data-review-error]:visible').waitFor();assert.equal(await form.locator('[name=Observation]').inputValue(),'Keep this stale draft');await form.locator('[data-review-cancel]').click();await p.locator('[data-review-reload]').click();await row().getByText('Saved by the other review window',{exact:true}).waitFor(); +await p.locator('[data-review-new]').click();await form.locator('[name=Observation]').fill('Draft retained on navigation and failure');p.once('dialog',d=>d.dismiss());await p.locator('a[rel=next]').first().click();assert(new URL(p.url()).pathname==='/Writer/Review'&&!new URL(p.url()).searchParams.has('chapterId'));await p.route('**/WriterReview/Save',r=>r.fulfill({status:503,json:{message:'Temporarily unavailable; text retained.'}}));await form.locator('[data-review-save]').click();await form.locator('[data-review-error]:visible').waitFor();assert.equal(await form.locator('[name=Observation]').inputValue(),'Draft retained on navigation and failure');await p.unroute('**/WriterReview/Save');await form.locator('[data-review-cancel]').click(); +await row().locator('[data-review-revisit]').click();await p.getByText('Return to Word',{exact:true}).click();await p.locator('[data-word-paragraph]:enabled').waitFor();await p.locator('[data-word-paragraph]').click();await p.locator('[data-word-command]').filter({hasText:'paragraph start'}).waitFor();assert.equal(nativePosts.at(-1).paragraphId,id);assert.equal(nativePosts.at(-1).chapterId,'21');rejectParagraph=true;await p.locator('[data-word-paragraph]').click();await p.locator('[data-word-command]').filter({hasText:'no longer verified'}).waitFor();const count=nativePosts.length;await p.locator('[data-word-navigate]').click();await p.locator('[data-word-command]').filter({hasText:'Word confirmed navigation.'}).waitFor();assert.equal(nativePosts.length,count+1);assert(!nativePosts.at(-1).paragraphId); +await p.locator('[data-help-key="writer3.reviewing"] button').click();await p.locator('.plotline-help-popover').waitFor();await p.locator('.plotline-help-more').click();await p.locator('[data-help-content] .help-drawer-article').waitFor();await p.locator('[data-help-close]').click(); +if(!pwa&&process.env.PD_WRITER3_SCREENSHOTS){fs.mkdirSync(process.env.PD_WRITER3_SCREENSHOTS,{recursive:true});await p.evaluate(()=>window.PlotDirectorApplyApplicationTheme('modern-dark'));await p.screenshot({path:process.env.PD_WRITER3_SCREENSHOTS+'/Review-fixture.png',animations:'disabled'});} +await p.locator('#reader-focus').click();assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');await p.locator('a[rel=next]').first().click();await p.waitForURL(/chapterId=22/);assert.equal(new URL(p.url()).pathname,'/Writer/Review');assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');await p.locator('a[rel=prev]').first().click();await p.waitForURL(/chapterId=21/);assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');await p.locator('#reader-focus').click();await p.setViewportSize({width:390,height:844});await p.locator('[data-review-record]').click();assert(await form.isVisible());assert(await p.locator('.writer3-reference').isVisible());await form.locator('[data-review-cancel]').click();await p.keyboard.press('Escape');assert(await p.locator('.writer3-reference').isHidden());assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2)); +await p.goto('http://127.0.0.1:5238/Writer/Review?projectId=7&bookId=13');assert.equal(await p.locator('[data-review-form]').count(),0);assert.equal((await p.request.get('http://127.0.0.1:5238/WriterReview/Panel?bookId=13&chapterId=21')).status(),404);assert.deepEqual(errors,[]);await c.close();} +console.log('PASS integrated Review browser/simulated PWA: canonical Reader, accepted scene context, selection-only no writes, anchored create/edit/resolve/reopen, repeat guard, stale multi-window retained draft, network/navigation guards, paragraph versus explicit chapter handoff and acknowledgement, Audio Review DOM/target/note preservation, Focused Reading Previous/Next, Help, narrow overlay and book isolation. Native and media telemetry simulated.');}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/PlotLine.Tests/ManuscriptReaderTests.cs b/PlotLine.Tests/ManuscriptReaderTests.cs index 7d8ce316..7c6e9f71 100644 --- a/PlotLine.Tests/ManuscriptReaderTests.cs +++ b/PlotLine.Tests/ManuscriptReaderTests.cs @@ -32,20 +32,21 @@ internal static class ManuscriptReaderTests ] }; } - internal static ManuscriptReaderService FixtureService(Func? snapshot = null, Action? onRead = null) + internal static ManuscriptReaderService FixtureService(Func? snapshot = null, Action? onRead = null,bool allowSecondBook=false) { var fixture = Snapshot(); var repository = NativeWorkflowTests.Proxy((name, args) => { if (name is not ("Get" or "Status")) throw new Exception("Reader attempted manuscript mutation: " + name); + if(allowSecondBook&&(int)args![0]! ==4&&(int)args[1]! ==13)return name=="Get"?Task.FromResult(null):Task.FromResult(null); if ((int)args![0]! != 4 || (int)args[1]! != 12) throw new UnauthorizedAccessException(); if (name == "Get") onRead?.Invoke(); var current = snapshot is null ? fixture : snapshot(); return name == "Get" ? Task.FromResult(current) : Task.FromResult(current is null ? null : new ParagraphSyncStatus { Revision = current.Revision }); }); - var books = NativeWorkflowTests.Proxy((name, _) => name == "GetAsync" - ? Task.FromResult(new() { BookID = 12, BookTitle = "A Distant Shore", ProjectID = 7 }) : throw new Exception(name)); + var books = NativeWorkflowTests.Proxy((name, args) => name == "GetAsync" + ? Task.FromResult(new() { BookID = allowSecondBook?(int)args![0]!:12, BookTitle = "A Distant Shore", ProjectID = 7 }) : throw new Exception(name)); var chapters = NativeWorkflowTests.Proxy((name, args) => name switch { - "ListByBookAsync" => Task.FromResult>(Chapters), + "ListByBookAsync" => Task.FromResult>(allowSecondBook&&(int)args![0]! ==13?[]:Chapters), "GetAsync" => Task.FromResult(Chapters.FirstOrDefault(c => c.ChapterID == (int)args![0]!)), _ => throw new Exception(name) }); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 3c2572a4..82ff407a 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -170,6 +170,7 @@ var tests = new (string Name, Action Test)[] ("Release triage and browser-only onboarding preserve author decisions", ReleaseSprintTests.Run), ("Approved native import source and confirmation remain safe", () => NativeImportTests.Run().GetAwaiter().GetResult()), ("Native installation renewal and revocation remain account/security scoped", () => NativeInstallationTests.Run().GetAwaiter().GetResult()), + ("Review accepted anchors, immutable provenance and author decisions",()=>WriterReviewTests.Run()), ("Writer Word verified navigation and acknowledgement",()=>WriterWordTests.Run().GetAwaiter().GetResult()), ("Writer inline authoring validation",()=>WriterAuthoringTests.Run()), ("Writer 3 destination navigation and scope",()=>WriterNavigationTests.Run().GetAwaiter().GetResult()), diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 7186a99d..1c289fc0 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -19,7 +19,8 @@ using PlotLine.ViewModels; // Isolated, loopback-only host: renders real compiled Razor chrome, never starts app workers or connects to a database. internal static class ToolbarBrowserHost { - private static readonly ParagraphManuscript readerFixture = ManuscriptReaderTests.Snapshot(); + private static readonly ParagraphManuscript readerFixture = ReviewSnapshot(); + private static ParagraphManuscript ReviewSnapshot(){var state=ManuscriptReaderTests.Snapshot();var scene=Guid.NewGuid();state.Scenes=[new(){Id=scene,CanonicalId=31,ChapterId=21}];foreach(var p in state.Paragraphs.Where(p=>p.ChapterId==21&&p.Story))p.SceneId=scene;return state;} private static readonly ParagraphManuscript readerLongFixture = ManuscriptReaderTests.LongSnapshot(); private static readonly System.Collections.Concurrent.ConcurrentDictionary<(int User, int Chapter), ChapterGoal> writerGoals = new(); @@ -135,7 +136,7 @@ internal static class ToolbarBrowserHost builder.Services.AddSingleton(); builder.Services.AddScoped(services => ManuscriptReaderTests.FixtureService(() => services.GetRequiredService().HttpContext!.Request.Query["reader-error"] == "true" - ? throw new TimeoutException("Synthetic unavailable manuscript") : services.GetRequiredService().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture)); + ? throw new TimeoutException("Synthetic unavailable manuscript") : services.GetRequiredService().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture,allowSecondBook:true)); builder.Services.AddHttpContextAccessor(); builder.Services.AddSingleton(); builder.Services.AddScoped(services => new ApplicationNavigation( @@ -151,6 +152,7 @@ internal static class ToolbarBrowserHost })); builder.Services.AddSingleton(FixtureProxy((name,args)=>Task.FromResult(name=="CanAccessProjectAsync"?(int)args![0]! == 7:(int)args![1]! is 12 or 13 or 21 or 22 or 31 or 32))); builder.Services.AddSingleton(); + builder.Services.AddScoped(); builder.Services.AddScoped(services => FixtureProxy((name, args) => name switch { "GetDashboardAsync" => Task.FromResult(Writer3Fixture(services.GetRequiredService().HttpContext!)), "GetChapterWorkflowAsync" => Task.FromResult(new() { diff --git a/PlotLine.Tests/WriterNavigationTests.cs b/PlotLine.Tests/WriterNavigationTests.cs index 3de8145e..3d07178a 100644 --- a/PlotLine.Tests/WriterNavigationTests.cs +++ b/PlotLine.Tests/WriterNavigationTests.cs @@ -26,7 +26,7 @@ internal static class WriterNavigationTests _=>throw new Exception(n)}); var schedules=NativeWorkflowTests.Proxy((n,a)=>n=="GetTodayDashboardAsync"?Task.FromResult(new WritingScheduleDashboardViewModel()):throw new Exception("Navigation attempted schedule mutation "+n)); var access=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(allowed)); - var controller=new WriterController(workspace,schedules,books,access); + var controller=new WriterController(workspace,schedules,books,access){ControllerContext=new(){HttpContext=new Microsoft.AspNetCore.Http.DefaultHttpContext{User=new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity([new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.NameIdentifier,"4")],"Fixture"))}}}; var routes=new Dictionary>>{ ["Home"]=b=>controller.Index(7,b),["Write"]=b=>controller.Write(7,b),["Explore"]=b=>controller.Explore(7,b), ["Plan"]=b=>controller.Plan(7,b),["Review"]=b=>controller.Review(7,b),["Reflect"]=b=>controller.Reflect(7,b),["Dashboard"]=b=>controller.Dashboard(7,b)}; diff --git a/PlotLine.Tests/WriterReviewFixture.cs b/PlotLine.Tests/WriterReviewFixture.cs new file mode 100644 index 00000000..60ddd7bf --- /dev/null +++ b/PlotLine.Tests/WriterReviewFixture.cs @@ -0,0 +1,10 @@ +using PlotLine.Services.Writer; +using PlotLine.Services.Manuscript; +using PlotLine.Models; +internal sealed class WriterReviewFixture(ManuscriptReaderService reader,IWriterAuthoringService intentions):IWriterReviewService +{ + private static readonly object gate=new();private static readonly Dictionary rows=[]; + public async Task Read(int actor,int book,int chapter,Guid? paragraph,string? version,int page,Guid? endParagraph=null){var source=await reader.Read(actor,book,chapter)??throw new KeyNotFoundException();var selected=source.ContentVersion==version?source.Paragraphs.FirstOrDefault(p=>p.Id==paragraph):null;var context=await intentions.Read(actor,12,21,selected?.SceneID);if(chapter!=21)context=new(){BookID=12,ChapterID=chapter,Chapter=source.Chapter!,Sections=context.Sections.Where(x=>x.Kind is "Chapter" or "Goals").ToArray()};lock(gate){var found=rows.Values.Where(r=>r.UserID==actor&&r.BookID==book&&r.ChapterID==chapter).OrderByDescending(x=>x.CreatedUtc).Skip((page-1)*50).Take(51).ToArray();foreach(var row in found)row.AnchorState=WriterReviewService.AnchorState(row,source);return new(context,found.Take(50).ToArray(),page,found.Length>50,selected?.SceneID!=null?"Scene context comes from accepted paragraph assignments.":"No verified scene assignment; chapter intentions remain available.");}} + public async Task Save(int actor,ReviewSave r){var source=await reader.Read(actor,r.BookID,r.ChapterID)??throw new KeyNotFoundException();var error=WriterReviewService.Validate(r);if(error.Length>0)throw new ArgumentException(error);lock(gate){if(r.Version==0){if(rows.TryGetValue(r.ID,out var existing)){if(existing.UserID==actor&&existing.Observation==r.Observation)return existing;throw new AuthoringConflictException("Observation changed; your text is retained.");}if(source.ContentVersion!=r.ContentVersion)throw new AuthoringConflictException("Accepted chapter changed; your text is retained.");var anchors=WriterReviewService.Anchor(source,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset);var row=new ReviewObservation{ID=r.ID,UserID=actor,BookID=r.BookID,ChapterID=r.ChapterID,ContentVersion=r.ContentVersion,ManuscriptID=source.ManuscriptID,SnapshotRevision=source.Revision,StartParagraph=r.StartParagraph,EndParagraph=r.EndParagraph,StartOffset=r.StartOffset,EndOffset=r.EndOffset,AnchorHash=anchors.Length>0?WriterReviewService.Hash(anchors):null,SceneID=anchors.FirstOrDefault()?.SceneID,Observation=r.Observation,Decision=r.Decision,Status=r.Status,Version=1,CreatedUtc=DateTime.UtcNow,UpdatedUtc=DateTime.UtcNow};rows[r.ID]=row;return row;} + if(!rows.TryGetValue(r.ID,out var saved)||saved.UserID!=actor||saved.BookID!=r.BookID||saved.ChapterID!=r.ChapterID||saved.Version!=r.Version)throw new AuthoringConflictException("Another window changed this observation; your text is retained.");saved.Observation=r.Observation;saved.Decision=r.Decision;saved.Status=r.Status;saved.Version++;saved.UpdatedUtc=DateTime.UtcNow;return saved;}} +} diff --git a/PlotLine.Tests/WriterReviewTests.cs b/PlotLine.Tests/WriterReviewTests.cs new file mode 100644 index 00000000..6b7374f7 --- /dev/null +++ b/PlotLine.Tests/WriterReviewTests.cs @@ -0,0 +1,18 @@ +using PlotLine.Models; +using PlotLine.Services.Writer; +using PlotLine.Services.Manuscript; +internal static class WriterReviewTests +{ + public static void Run(){void Check(bool ok,string message){if(!ok)throw new Exception(message);}void Reject(Action action){try{action();}catch(ArgumentException){return;}throw new Exception("Invalid accepted reference was accepted");} + var first=Guid.NewGuid();var last=Guid.NewGuid();var manuscript=Guid.NewGuid();var rows=new ReaderParagraph[]{new(first,"A saved paragraph",false,31),new(last,"Another saved paragraph",false,31)}; + var source=new ManuscriptReaderModel{Book=new(){BookID=12,ProjectID=7},Chapter=new(){ChapterID=21,BookID=12},Chapters=[],Paragraphs=rows,ManuscriptID=manuscript,Revision=4}; + Check(WriterReviewService.Anchor(source,first,last,2,7).Length==2,"multi-paragraph accepted range");Reject(()=>WriterReviewService.Anchor(source,Guid.NewGuid(),last,0,3));Reject(()=>WriterReviewService.Anchor(source,last,first,0,3));Reject(()=>WriterReviewService.Anchor(source,first,first,-1,3));Reject(()=>WriterReviewService.Anchor(source,first,first,6,2));Reject(()=>WriterReviewService.Anchor(source,first,last,0,1000));Check(WriterReviewService.Anchor(source,null,null,null,null).Length==0,"chapter observation claims no passage"); + var row=new ReviewObservation{ManuscriptID=manuscript,SnapshotRevision=4,ContentVersion=source.ContentVersion,StartParagraph=first,EndParagraph=last,StartOffset=2,EndOffset=7,AnchorHash=WriterReviewService.Hash(rows)}; + Check(WriterReviewService.AnchorState(row,source)=="Current","same accepted IDs and paragraph content retain anchor");var original=row.ContentVersion; + var changed=new ManuscriptReaderModel{Book=source.Book,Chapter=source.Chapter,Chapters=[],Paragraphs=[new(first,"Changed saved paragraph",false,31),rows[1]],ManuscriptID=manuscript,Revision=5};Check(WriterReviewService.AnchorState(row,changed)=="Changed"&&row.ContentVersion==original&&row.SnapshotRevision==4,"changed prose preserves original accepted reference"); + var replaced=new ManuscriptReaderModel{Book=source.Book,Chapter=source.Chapter,Chapters=[],Paragraphs=[new(Guid.NewGuid(),rows[0].Text,false),rows[1]],ManuscriptID=manuscript};Check(WriterReviewService.AnchorState(row,replaced)=="Missing or changed","same prose under another identity is never silently reanchored"); + var other=new ManuscriptReaderModel{Book=source.Book,Chapter=source.Chapter,Chapters=[],Paragraphs=rows,ManuscriptID=Guid.NewGuid()};Check(WriterReviewService.AnchorState(row,other)=="Different manuscript","document replacement invalidates precise anchor"); + foreach(var state in new[]{"Open","Working","Resolved"})Check(WriterReviewService.Validate(new(){ID=Guid.NewGuid(),Observation="An author observation",Status=state})=="","author lifecycle state");Check(WriterReviewService.Validate(new(){ID=Guid.NewGuid(),Observation=" "}).Length>0,"empty observations rejected");Check(WriterReviewService.Validate(new(){ID=Guid.NewGuid(),Observation="Valid",Status="Drafted"}).Length>0,"scene revision status is not an observation status"); + Check(ManuscriptReaderModel.Fingerprint(rows)!=ManuscriptReaderModel.Fingerprint([new(first,rows[0].Text,false,32),rows[1]]),"scene remapping refreshes accepted Reader context even without changed prose"); + } +} diff --git a/PlotLine.Tests/WriterWordTests.cs b/PlotLine.Tests/WriterWordTests.cs index 766cb9bf..26ecdf2f 100644 --- a/PlotLine.Tests/WriterWordTests.cs +++ b/PlotLine.Tests/WriterWordTests.cs @@ -25,6 +25,8 @@ internal static class WriterWordTests Check(!await service.Navigate(7,12,99,null,instance,session,manuscript,2,Guid.NewGuid()),"foreign chapter rejected before native queue");Check(!await service.Navigate(7,12,21,999,instance,session,manuscript,2,Guid.NewGuid()),"foreign scene rejected");Check(await service.Navigate(7,12,21,null,instance,session,manuscript,2,Guid.NewGuid()),"authorised exact canonical chapter heading navigates without scene guesses"); var queued=store.TakeNavigation(7,"grant",instance,session)!;var completed=State();completed.NavigationAcknowledgedId=queued.Id;completed.NavigationResult="completed";Put(completed); var sceneRequest=Guid.NewGuid();Check(await service.Navigate(7,12,21,31,instance,session,manuscript,2,sceneRequest),"verified canonical scene start navigates without title matching");store.TakeNavigation(7,"grant",instance,session);completed=State();completed.NavigationAcknowledgedId=sceneRequest;completed.NavigationResult="completed";Put(completed); + snapshot.Paragraphs[1].ChapterId=21;var paragraph=snapshot.Paragraphs[1].Occurrence.Id; + Check(!await service.Navigate(7,12,21,null,instance,session,manuscript,2,Guid.NewGuid(),paragraph,4),"stale accepted paragraph version cannot navigate");var paragraphRequest=Guid.NewGuid();Check(await service.Navigate(7,12,21,null,instance,session,manuscript,2,paragraphRequest,paragraph,5),"exact accepted paragraph reuses acknowledged navigation without offset guessing");store.TakeNavigation(7,"grant",instance,session);completed=State();completed.NavigationAcknowledgedId=paragraphRequest;completed.NavigationResult="completed";Put(completed); var modern=State();modern.CanChapterSync=true;Put(modern);bool currentCheckpoint=false; var liveCheckpoints=NativeWorkflowTests.Proxy((n,a)=>n switch{ "List"=>Task.FromResult>([new(){ChapterID=21,SessionID=session,WordRevision=2,StartPosition=200}]), diff --git a/PlotLine/Controllers/ManuscriptReaderController.cs b/PlotLine/Controllers/ManuscriptReaderController.cs index c7309c6a..5ac38786 100644 --- a/PlotLine/Controllers/ManuscriptReaderController.cs +++ b/PlotLine/Controllers/ManuscriptReaderController.cs @@ -52,7 +52,7 @@ public sealed class ManuscriptReaderController(ManuscriptReaderService reader, I { bookId, chapterId, revision = model.Revision.ToString(System.Globalization.CultureInfo.InvariantCulture), version = model.ContentVersion, title = model.Chapter!.ChapterTitle, - paragraphs = model.Paragraphs.Select(p => new { id = p.Id, text = p.Text, isHeading = p.IsHeading }), + paragraphs = model.Paragraphs.Select(p => new { id = p.Id, text = p.Text, isHeading = p.IsHeading, sceneId=p.SceneID }), lastSuccessfulSyncUtc = model.LastSuccessfulSyncUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ"), snapshotCapturedUtc = model.SnapshotCapturedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ") }); diff --git a/PlotLine/Controllers/WriterController.cs b/PlotLine/Controllers/WriterController.cs index 92ae8df6..61fee1be 100644 --- a/PlotLine/Controllers/WriterController.cs +++ b/PlotLine/Controllers/WriterController.cs @@ -19,7 +19,19 @@ public sealed class WriterController( public Task Write(int? projectId, int? bookId = null) => LoadDestination("Write", projectId, bookId); public Task Explore(int? projectId, int? bookId = null) => LoadDestination("Explore", projectId, bookId); public Task Plan(int? projectId, int? bookId = null) => LoadDestination("Plan", projectId, bookId); - public Task Review(int? projectId, int? bookId = null) => LoadDestination("Review", projectId, bookId); + [ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] + public async Task Review(int? projectId,int? bookId=null,int? chapterId=null,bool focus=false,[FromServices] PlotLine.Services.Manuscript.ManuscriptReaderService? reader=null) + { + Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive"; + var result=await LoadDestination("Review",projectId,bookId); + if(result is ViewResult {Model:WriterDashboardViewModel model}&&model.BookID.HasValue&&reader!=null){ + try{model.ReviewReader=await reader.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),model.BookID.Value,chapterId);if(model.ReviewReader==null)return NotFound();model.ReviewReader.FocusReading=focus;model.ReviewReader.IntegratedReview=true;} + catch(UnauthorizedAccessException){return NotFound();} + catch(SqlException e)when(e.Number==51000){return NotFound();} + catch(Exception e)when(e is SqlException or TimeoutException or System.Text.Json.JsonException){Response.StatusCode=503;return View("~/Views/ManuscriptReader/Unavailable.cshtml",new{BookId=model.BookID,ChapterId=chapterId});} + } + return result; + } public Task Reflect(int? projectId, int? bookId = null) => LoadDestination("Reflect", projectId, bookId); public Task Dashboard(int? projectId, int? bookId = null) => LoadDestination("Dashboard", projectId, bookId); public Task Overview(int? projectId, int? bookId = null) => LoadDestination("Legacy", projectId, bookId); diff --git a/PlotLine/Controllers/WriterReviewController.cs b/PlotLine/Controllers/WriterReviewController.cs new file mode 100644 index 00000000..24ce6125 --- /dev/null +++ b/PlotLine/Controllers/WriterReviewController.cs @@ -0,0 +1,15 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using PlotLine.Services.Writer; +namespace PlotLine.Controllers; +[Authorize] +public sealed class WriterReviewController(IWriterReviewService review):Controller +{ + private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); + [HttpGet] + public Task Panel(int bookId,int chapterId,Guid? paragraphId,string? version,int page=1,Guid? endParagraphId=null)=>Run(async()=>PartialView("~/Views/Writer/_ReviewContext.cshtml",await review.Read(Author,bookId,chapterId,paragraphId,version,page,endParagraphId))); + [HttpPost,ValidateAntiForgeryToken] + public Task Save(ReviewSave request)=>Run(async()=>{if(!ModelState.IsValid)return BadRequest(new{message="Review details are invalid. Your text is retained."});var row=await review.Save(Author,request);return Json(new{success=true,id=row.ID,version=row.Version});}); + private async Task Run(Func> work){Response.Headers.CacheControl="no-store";Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";try{return await work();}catch(AuthoringConflictException e){return Conflict(new{message=e.Message});}catch(ArgumentException e){return BadRequest(new{message=e.Message});}catch(Exception e)when(e is UnauthorizedAccessException or KeyNotFoundException){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){return NotFound();}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){return StatusCode(503,new{message="Review information is temporarily unavailable. Your text is retained."});}} +} diff --git a/PlotLine/Controllers/WriterWordController.cs b/PlotLine/Controllers/WriterWordController.cs index 28bb7ecc..fc79ba82 100644 --- a/PlotLine/Controllers/WriterWordController.cs +++ b/PlotLine/Controllers/WriterWordController.cs @@ -10,12 +10,12 @@ public sealed class WriterWordController(WriterWordService words,IWordCompanionR { private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); [HttpPost,ValidateAntiForgeryToken] - public async Task Navigate(int bookId,int chapterId,int? sceneId,Guid instanceId,Guid sessionId,Guid manuscriptId,long revision,Guid navigationId) + public async Task Navigate(int bookId,int chapterId,int? sceneId,Guid instanceId,Guid sessionId,Guid manuscriptId,long revision,Guid navigationId,Guid? paragraphId=null,long? acceptedRevision=null) { Response.Headers.CacheControl="no-store"; if(!ModelState.IsValid||bookId<=0||chapterId<=0||sceneId is <=0||instanceId==Guid.Empty||sessionId==Guid.Empty||manuscriptId==Guid.Empty||navigationId==Guid.Empty||revision<0)return BadRequest(); if(await access.GetBookStructureAsync(bookId,Author)==null)return NotFound(); - try { return await words.Navigate(Author,bookId,chapterId,sceneId,instanceId,sessionId,manuscriptId,revision,navigationId)?Accepted(new{navigationId,message="Requested in Word; waiting for confirmation."}):Conflict(new{message="This Word document or chapter position is not currently verified, or Word is busy. Check Companion and try again. Nothing was moved."}); } + try { return await words.Navigate(Author,bookId,chapterId,sceneId,instanceId,sessionId,manuscriptId,revision,navigationId,paragraphId,acceptedRevision)?Accepted(new{navigationId,message="Requested in Word; waiting for confirmation."}):Conflict(new{message="This Word document or chapter position is not currently verified, or Word is busy. Check Companion and try again. Nothing was moved."}); } catch(UnauthorizedAccessException){return NotFound();} catch(Microsoft.Data.SqlClient.SqlException e) when(e.Number==51000){return NotFound();} catch(Exception e) when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){return StatusCode(503,new{message="Word navigation is temporarily unavailable. Your saved work is retained."});} diff --git a/PlotLine/Help/Articles/Workspace/Writer3-explore.md b/PlotLine/Help/Articles/Workspace/Writer3-explore.md index e90b7a13..dd5ae7cf 100644 --- a/PlotLine/Help/Articles/Workspace/Writer3-explore.md +++ b/PlotLine/Help/Articles/Workspace/Writer3-explore.md @@ -11,12 +11,16 @@ screenshot: # Overview -Explore offers real entry points to the existing Problem Solver questionnaire, its browsable guidance and the story Timeline. It does not generate a new creative analysis merely by opening this page. +Explore offers three distinct entry points to your authenticated writing, plot/thread and timeline workspaces. Project and book context stay visible. If you have no project, choose one before developing its plot; Write can help you begin with a book. -You can use the Problem Solver before you have a project or scenes. Its questions and editorial guidance are separate from manuscript-aware evidence assessment. Saved character, relationship, plot, map, floor-plan and metric tools are linked directly when a project is selected. Some of those tools are project-wide and may include other books. +Saved character, relationship, plot, map, floor-plan and metric tools remain directly available. Some tools are project-wide and may include other books. Existing editing, permissions and source records remain authoritative. Opening Explore runs no manuscript analysis and saves no suggested interpretation as a story fact. -The full specialist workspaces retain their existing editing, permissions and source records. No suggested interpretation silently updates a story fact. Guided idea capture and richer manuscript-aware journeys are later work, not simulated controls here. +Guided idea capture and manuscript-aware exploration remain later work; these links open the actual existing tools. # Arrange your workspace Drag the divider or focus it and use Left/Right arrow keys to resize the contextual companion. Hide companion gives your main task the full width; Show companion restores it. Each destination remembers its width and desktop visibility on this browser. In narrow windows the companion opens as an overlay; use Back to workspace or Escape to return. Workspace Layout Help beside Show/Hide companion explains keyboard controls, storage and the independent standalone Context/Intent windows. + +# Authenticated tools + +Develop a chapter or scene opens Write with the selected project/book; Develop your plot and threads opens the existing authenticated plot workspace; Look at your story's shape opens its timeline. These are distinct existing tools, not the public Problem Solver or a new guided ideation engine. Guided exploration remains a later phase. No analysis runs merely by choosing Explore. diff --git a/PlotLine/Help/Articles/Workspace/Writer3-review.md b/PlotLine/Help/Articles/Workspace/Writer3-review.md index 6f36e61c..3f52ed30 100644 --- a/PlotLine/Help/Articles/Workspace/Writer3-review.md +++ b/PlotLine/Help/Articles/Workspace/Writer3-review.md @@ -1,26 +1,22 @@ --- title: Review Your Writing category: Workspace -tags: writer, navigation, review +tags: writer, review, manuscript, audio contextKey: writer3.review -micro: Read accepted text, revisit intentions and choose revision work. -quickTitle: Review Your Writing -quickSummary: Read accepted text, revisit intentions and choose revision work. +micro: Read accepted manuscript text, inspect intentions and record your own review decisions. +quickTitle: Review your writing +quickSummary: Read in the integrated canonical Reader, select a passage and explicitly record an observation. Your review selection, writing focus, Word position and recording target remain independent. screenshot: --- -# Overview +# Read, notice, decide and return -Review opens the read-only Manuscript Reader and Focused reading, using your saved focus chapter or the first available chapter. The Reader shows accepted server text, not unsynchronised Word edits. Empty/new chapters explain the need to save and synchronise; no source text is invented. +Review begins with the accepted manuscript using the existing Reader. Previous/Next, chapter selection, Focused Reading, selected text, paragraph identities and update controls remain available. Unsynchronised Word changes are not shown. Empty chapters explain how to connect and synchronise Word rather than inventing text. -# Audio Review +The resizable companion shows recorded chapter intentions and scene details only when accepted paragraph assignments support them. Record an observation about what needs attention and optionally what you want to change. Save, edit, resolve or reopen it explicitly. Original accepted-version references remain unchanged when the manuscript changes; missing or changed paragraphs are not silently reanchored by text matching. -Open the Reader and expand Reading & Audio Review. Select/start the activity explicitly. Playback requires compatible Windows Companion and a supported player. Opening Review or Reader does not play audio. Pause stops external playback when supported; End review stops tracking and saves your note. +Return to Word uses the existing verified, acknowledged chapter/paragraph handoff. Paragraph navigation targets its start, not an assumed exact character range. A rejected precise handoff offers a separate chapter action. Reader changes never move Word, retarget a recording or save a working objective. -# Intent and evidence +Reading & Audio Review uses the existing session/media controls and return notes. Observations are separate from session notes, canonical scene revision state and automated findings. Opening Review runs no manuscript analysis. -Open Intent uses the existing standalone reference window. Its Evidence tab loads saved evidence or explicitly assesses saved scene prose and saved intentions when permitted. Intentions, AI interpretation and author-confirmed checklist completion remain separate. Scenes marked for revision opens the existing Revision workspace. No synchronisation or evidence contract is replaced by this shell. - -# Arrange your workspace - -Drag the divider or focus it and use Left/Right arrow keys to resize the contextual companion. Hide companion gives your main task the full width; Show companion restores it. Each destination remembers its width and desktop visibility on this browser. In narrow windows the companion opens as an overlay; use Back to workspace or Escape to return. Workspace Layout Help beside Show/Hide companion explains keyboard controls, storage and the independent standalone Context/Intent windows. +Use Show/Hide companion and keyboard/pointer resizing. On narrow screens the companion opens as an overlay. Each pane scrolls only when its content exceeds the available viewport. See Read, Notice and Decide for observation capture, original references and recovery. diff --git a/PlotLine/Help/Articles/Workspace/Writer3-reviewing.md b/PlotLine/Help/Articles/Workspace/Writer3-reviewing.md new file mode 100644 index 00000000..93b82045 --- /dev/null +++ b/PlotLine/Help/Articles/Workspace/Writer3-reviewing.md @@ -0,0 +1,40 @@ +--- +title: Read, Notice and Decide +category: Workspace +tags: review, reader, observations, revisions, Word, audio +contextKey: writer3.reviewing +micro: Read accepted writing, record what you notice and choose what to change; Word and your working focus stay independent. +quickTitle: Review observations +quickSummary: Select a paragraph or passage, then explicitly record an observation. Save its decision separately from scene revision state. Changed or missing references retain their original accepted-version context. +screenshot: +--- + +# Read accepted writing + +Review embeds the same canonical Manuscript Reader. Choose a chapter, use Previous/Next or enter Focused Reading. These retain Review mode and do not change your saved working focus, actual session target or Word position. Reader contains accepted text, not every unsaved Word keystroke. Accepted manuscript details show available synchronisation times. If there is no accepted text, connect and synchronise the correct manuscript through Word Companion; you can still inspect recorded intentions. + +Reader uses its existing update policy. Selected text and paused updates defer content replacement. Surviving paragraph anchors preserve reading position where possible. While an observation editor is open, automatic content updates pause; Save or Cancel restores your previous pause preference. An update never resolves an observation automatically. + +# Inspect intentions + +The companion shows recorded chapter intentions. A selected accepted passage can show scene intentions, outcome, notes, reminders and state only when its paragraph assignments identify one scene reliably. Otherwise chapter context remains available. Details and editing opens the existing canonical chapter/scene editors in another window; this does not adopt a new working focus. No story facts are invented to fill an empty panel. + +# Record an observation + +Select text or click an accepted paragraph, then choose Record an observation or Something here needs attention. Enter what you noticed and, optionally, what you want to change. Selection alone saves nothing. Use a chapter-level reference explicitly if no precise passage is appropriate. + +Each observation retains its original accepted version and stable paragraph identities, with selection offsets when available. It does not store a duplicate quote. Save records your text; Cancel saves nothing. Failures and stale saves retain your draft. Save or Cancel before changing observation pages or reloading the list. Navigation warns before leaving unsaved work. Observations are private to their author within an accessible book. + +Needs attention, Working on it and Resolved describe your observation, not the scene's canonical revision status. Edit / change decision lets you resolve or reopen it explicitly. Changes to prose, checklist completion or an ended session never resolve it automatically. + +# Revisit or return to Word + +Revisit reference uses the original paragraph identity, never a search for similar text. If it changed or disappeared, the original reference remains recorded. Review explains the limitation instead of attaching it to another passage. + +Return to Word reuses the verified, acknowledged Companion handoff. Open paragraph in Word means the start of a verified current paragraph; it does not claim an exact selected-character location. If that reference is missing, changed or unverified, use the separate chapter action after checking the correct document. A rejected paragraph request does not automatically move Word elsewhere. Only Word confirmed navigation indicates an acknowledgement; requested or timed out is not completion. No save, session start/end, objective update or document replacement is forced. + +# Listen and distinguish sources + +Expand Reading & Audio Review to use the existing recording and supported native playback controls. Record observations while preserving the actual session target, playback and return note. Audio time is not a paragraph anchor. Native pause-on-edit and media safeguards are unchanged. + +Your observations are distinct from recorded intentions and saved automated findings. Saved assessments & other tools opens existing Intent evidence, Context and the book's analysis/review tools. Opening Review starts no analysis. Assessments remain explicit actions with their original provenance and freshness. diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 636a707b..eb72aaa8 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -200,6 +200,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/PlotLine/Services/Manuscript/ManuscriptReaderService.cs b/PlotLine/Services/Manuscript/ManuscriptReaderService.cs index fa731191..021b6c51 100644 --- a/PlotLine/Services/Manuscript/ManuscriptReaderService.cs +++ b/PlotLine/Services/Manuscript/ManuscriptReaderService.cs @@ -5,26 +5,30 @@ using PlotLine.Models; namespace PlotLine.Services.Manuscript; -public sealed record ReaderParagraph(Guid Id, string Text, bool IsHeading); +public sealed record ReaderParagraph(Guid Id, string Text, bool IsHeading,int? SceneID=null); public sealed class ManuscriptReaderModel { public PlotLine.Services.Writer.WriterContext WorkingContext => new PlotLine.Services.Writer.WriterContext(Book.ProjectID, Book.BookID) .Select(PlotLine.Services.Writer.WriterFocusRole.Reader, new(Book.ProjectID, Book.BookID, Chapter?.ChapterID)); public long Revision { get; init; } = -1; public bool FocusReading { get; set; } - public string ContentVersion => Fingerprint(Paragraphs); + public bool IntegratedReview {get;set;} + public Guid? ManuscriptID {get;init;} + public string ContentVersion => Fingerprint(Paragraphs,ManuscriptID); - public static string Fingerprint(IReadOnlyList paragraphs) + public static string Fingerprint(IReadOnlyList paragraphs,Guid? manuscript=null) { using var buffer = new MemoryStream(); using (var writer = new BinaryWriter(buffer, Encoding.UTF8, leaveOpen: true)) { + writer.Write(manuscript.GetValueOrDefault().ToByteArray()); writer.Write(paragraphs.Count); foreach (var paragraph in paragraphs) { writer.Write(paragraph.Id.ToByteArray()); writer.Write(paragraph.Text); writer.Write(paragraph.IsHeading); + writer.Write(paragraph.SceneID??0); } } return Convert.ToHexString(SHA256.HashData(buffer.GetBuffer().AsSpan(0, (int)buffer.Length))); @@ -96,12 +100,12 @@ public sealed class ManuscriptReaderService( } } var rows = source.OrderBy(p => p.Occurrence.Ordinal) - .Select(p => new ReaderParagraph(p.Occurrence.Id, p.Occurrence.Text, p.Occurrence.Id == heading || p.Occurrence.Outline is >= 1 and <= 6)) + .Select(p => new ReaderParagraph(p.Occurrence.Id, p.Occurrence.Text, p.Occurrence.Id == heading || p.Occurrence.Outline is >= 1 and <= 6, state?.Scenes.FirstOrDefault(s=>s.Id==p.SceneId&&!s.Retired&&s.CanonicalId>0&&s.ChapterId==selected?.ChapterID)?.CanonicalId)) .ToArray(); var checkpoint = state?.ChapterCheckpoints.FirstOrDefault(c => c.ChapterId == selected?.ChapterID); return new() { - Revision = state?.Revision ?? -1, + Revision = state?.Revision ?? -1, ManuscriptID=state?.ManuscriptId, Book = book, Chapters = ordered, Chapter = selected, Paragraphs = rows, PreviousId = index > 0 ? ordered[index - 1].ChapterID : null, NextId = index >= 0 && index + 1 < ordered.Count ? ordered[index + 1].ChapterID : null, diff --git a/PlotLine/Services/ProjectAccessFilter.cs b/PlotLine/Services/ProjectAccessFilter.cs index b897c4e1..0c344748 100644 --- a/PlotLine/Services/ProjectAccessFilter.cs +++ b/PlotLine/Services/ProjectAccessFilter.cs @@ -85,6 +85,7 @@ public sealed class ProjectAccessFilter(IProjectAccessService access, ICurrentUs ["Scenarios"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "Scenario", ["scenarioId"] = "Scenario", ["projectId"] = "Project", ["bookId"] = "Book", ["sceneId"] = "Scene", ["anchorSceneId"] = "Scene", ["targetChapterId"] = "Chapter" }, ["StoryAssets"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "StoryAsset", ["returnAssetId"] = "StoryAsset", ["projectId"] = "Project" }, ["Timeline"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "TimelineViewPreset", ["projectId"] = "Project", ["bookId"] = "Book" }, + ["WriterReview"] = new(StringComparer.OrdinalIgnoreCase) { ["bookId"]="Book",["chapterId"]="Chapter" }, ["WriterWord"] = new(StringComparer.OrdinalIgnoreCase) { ["bookId"] = "Book", ["chapterId"] = "Chapter", ["sceneId"] = "Scene" }, ["WriterAuthoring"] = new(StringComparer.OrdinalIgnoreCase) { ["bookId"] = "Book", ["chapterId"] = "Chapter", ["sceneId"] = "Scene" }, ["Writer"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "Chapter", ["projectId"] = "Project" }, diff --git a/PlotLine/Services/Writer/WriterReviewService.cs b/PlotLine/Services/Writer/WriterReviewService.cs new file mode 100644 index 00000000..9c52cfba --- /dev/null +++ b/PlotLine/Services/Writer/WriterReviewService.cs @@ -0,0 +1,62 @@ +using System.Data; +using System.Security.Cryptography; +using System.Text; +using Dapper; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services.Manuscript; +namespace PlotLine.Services.Writer; +public sealed class ReviewObservation +{ + public Guid ID{get;set;}public int UserID{get;set;}public int BookID{get;set;}public int ChapterID{get;set;} + public Guid? ManuscriptID{get;set;}public long SnapshotRevision{get;set;}public string ContentVersion{get;set;}=""; + public Guid? StartParagraph{get;set;}public Guid? EndParagraph{get;set;}public int? StartOffset{get;set;}public int? EndOffset{get;set;}public string? AnchorHash{get;set;}public int? SceneID{get;set;} + public string Observation{get;set;}="";public string? Decision{get;set;}public string Status{get;set;}="Open";public int Version{get;set;}public DateTime CreatedUtc{get;set;}public DateTime UpdatedUtc{get;set;} + public string AnchorState{get;set;}="Chapter"; +} +public sealed class ReviewSave +{ + public int BookID{get;set;}public int ChapterID{get;set;}public Guid ID{get;set;}public int Version{get;set;} + public string ContentVersion{get;set;}="";public Guid? StartParagraph{get;set;}public Guid? EndParagraph{get;set;}public int? StartOffset{get;set;}public int? EndOffset{get;set;} + public string Observation{get;set;}="";public string? Decision{get;set;}public string Status{get;set;}="Open"; +} +public sealed record ReviewPanel(WriterAuthoringPage Intentions,IReadOnlyList Observations,int Page,bool HasMore,string ReferenceMessage); +public interface IWriterReviewService +{ + Task Read(int actor,int book,int chapter,Guid? paragraph,string? version,int page,Guid? endParagraph=null); + Task Save(int actor,ReviewSave request); +} +public sealed class WriterReviewService(ISqlConnectionFactory factory,ManuscriptReaderService reader,IWriterAuthoringService intentions):IWriterReviewService +{ + public static string Hash(IEnumerable paragraphs){using var buffer=new MemoryStream();using(var writer=new BinaryWriter(buffer,Encoding.UTF8,true))foreach(var p in paragraphs){writer.Write(p.Id.ToByteArray());writer.Write(p.Text);}return Convert.ToHexString(SHA256.HashData(buffer.ToArray()));} + public static string Validate(ReviewSave r)=>r.ID==Guid.Empty||r.Version<0?"Choose a valid observation.":r.Status is not("Open" or "Working" or "Resolved")?"Choose a valid observation state.":string.IsNullOrWhiteSpace(r.Observation)?"Record what you noticed before saving.":r.Observation.Length>10000||(r.Decision?.Length??0)>10000?"Keep each observation and decision within 10,000 characters.":""; + public static ReaderParagraph[] Anchor(ManuscriptReaderModel model,Guid? first,Guid? last,int? start,int? end){ + if(first==null&&last==null&&start==null&&end==null)return []; + var rows=model.Paragraphs.ToArray();var from=Array.FindIndex(rows,p=>p.Id==first);var to=Array.FindIndex(rows,p=>p.Id==last); + if(from<0||torows[from].Text.Length||end>rows[to].Text.Length||from==to&&end Read(int actor,int book,int chapter,Guid? paragraph,string? version,int page,Guid? endParagraph=null){ + if(page<1||page>100000)throw new ArgumentException("Choose a valid observations page.");var source=await reader.Read(actor,book,chapter)??throw new KeyNotFoundException(); + var selected=source.ContentVersion==version?source.Paragraphs.SingleOrDefault(p=>p.Id==paragraph):null; + int? selectedScene=selected?.SceneID; + if(selected!=null&&endParagraph.HasValue){var all=source.Paragraphs.ToArray();var first=Array.FindIndex(all,p=>p.Id==selected.Id);var last=Array.FindIndex(all,p=>p.Id==endParagraph);if(lastp.SceneID!=selectedScene))selectedScene=null;} + WriterAuthoringPage context; + try{context=await intentions.Read(actor,book,chapter,selectedScene);} + catch(Exception e)when(selectedScene.HasValue&&(e is KeyNotFoundException||e is Microsoft.Data.SqlClient.SqlException {Number:51000})){selectedScene=null;context=await intentions.Read(actor,book,chapter,null);} + using var db=factory.CreateConnection();var rows=(await db.QueryAsync("dbo.WriterReview_Observations",new{Action="list",UserID=actor,BookID=book,ChapterID=chapter,Page=page},commandType:CommandType.StoredProcedure)).ToArray();foreach(var row in rows)row.AnchorState=AnchorState(row,source); + return new(context,rows.Take(50).ToArray(),page,rows.Length>50,selectedScene!=null?"Scene context comes from accepted paragraph assignments.":paragraph.HasValue?"No current verified scene assignment for this passage. Chapter intentions remain available.":"Chapter intentions; choose a recorded passage for verified scene context."); + } + public async Task Save(int actor,ReviewSave r){ + var error=Validate(r);if(error.Length>0)throw new ArgumentException(error); + ManuscriptReaderModel? source=null;ReaderParagraph[] rows=[]; + if(r.Version==0){source=await reader.Read(actor,r.BookID,r.ChapterID)??throw new KeyNotFoundException();if(r.ContentVersion!=source.ContentVersion)throw new AuthoringConflictException("The accepted chapter changed. Your observation text is retained. Refresh the manuscript before choosing its reference again.");rows=Anchor(source,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset);} + int? scene=rows.Length>0&&rows[0].SceneID.HasValue&&rows.All(p=>p.SceneID==rows[0].SceneID)?rows[0].SceneID:null; + using var db=factory.CreateConnection();try{return await db.QuerySingleAsync("dbo.WriterReview_Observations",new{Action=r.Version==0?"create":"update",UserID=actor,r.BookID,r.ChapterID,r.ID,r.Version,ManuscriptID=source?.ManuscriptID,SnapshotRevision=source?.Revision,ContentVersion=source?.ContentVersion,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset,AnchorHash=rows.Length>0?Hash(rows):null,SceneID=scene,r.Observation,r.Decision,r.Status},commandType:CommandType.StoredProcedure);}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){throw new AuthoringConflictException("The observation or accepted manuscript changed. Your text is retained. Reload the recorded observations before retrying.",e);} + } +} diff --git a/PlotLine/Services/Writer/WriterWordService.cs b/PlotLine/Services/Writer/WriterWordService.cs index 679e967a..6b4c5f20 100644 --- a/PlotLine/Services/Writer/WriterWordService.cs +++ b/PlotLine/Services/Writer/WriterWordService.cs @@ -13,14 +13,19 @@ public sealed class WriterWordService(ISqlConnectionFactory factory,IWordCompani private static T? One(IEnumerable rows) where T:class {var candidates=rows.Take(2).ToArray();return candidates.Length==1?candidates[0]:null;} public async Task Metadata(int user,int book,int? chapter){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync("dbo.WriterWord_Status",new{UserID=user,BookID=book,ChapterID=chapter},commandType:CommandType.StoredProcedure);} public async Task Position(int user,NativeLease lease,WriterWordMetadata? metadata){var p=lease.Position;if(p.WordSaved!=true||!p.WordAvailable||!p.CursorStart.HasValue||metadata?.ManuscriptID!=p.ManuscriptId)return null;var position=p.CanChapterSync?await chapters.Position(user,p.BookId,p.ManuscriptId,lease.Session,p.Revision,p.CursorStart.Value):await paragraphs.Position(user,p.BookId,p.ManuscriptId,lease.Session,p.Revision,p.CursorStart.Value);return position?.HasSnapshot==true&&position.Revision==metadata.Revision?position:null;} - public async Task Navigate(int user,int book,int chapter,int? scene,Guid instance,Guid session,Guid manuscript,long revision,Guid id) + public async Task Navigate(int user,int book,int chapter,int? scene,Guid instance,Guid session,Guid manuscript,long revision,Guid id,Guid? paragraphId=null,long? acceptedRevision=null) { var structure=await access.GetBookStructureAsync(book,user);var target=structure==null?null:One(structure.Chapters.Where(c=>c.ChapterId==chapter));if(target==null||scene.HasValue&&!target.Scenes.Any(s=>s.SceneId==scene))return false; var lease=One(presence.Read(user,book).Where(l=>l.Instance==instance&&l.Session==session&&l.Position.ManuscriptId==manuscript&&l.Position.Revision==revision&&l.Position.WordAvailable&&l.Position.WordSaved==true&&l.Position.CanAcknowledgeNavigation)); if(lease==null)return false; var state=await paragraphs.Get(user,book);if(state==null||state.ManuscriptId!=manuscript)return false; int? start=null; - if(scene.HasValue){ + if(paragraphId.HasValue){ + if(acceptedRevision!=state.Revision)return false; + var targetParagraph=One(state.Paragraphs.Where(p=>p.Occurrence.Id==paragraphId&&p.ChapterId==chapter&&p.PositionVerified));if(targetParagraph==null)return false; + if(lease.Position.CanChapterSync){using var db=factory.CreateConnection();var anchors=await db.QueryAsync("dbo.WriterReview_ParagraphStart",new{UserID=user,BookID=book,ChapterID=chapter,ParagraphID=paragraphId,ManuscriptID=manuscript,SessionID=session,WordRevision=revision,AcceptedRevision=acceptedRevision},commandType:CommandType.StoredProcedure);var anchor=One(anchors);if(anchor?.Revision==state.Revision&&anchor.ChapterID==chapter)start=anchor.StartPosition;} + else if(state.SessionId==session&&state.WordRevision==revision)start=targetParagraph.Occurrence.Start; + }else if(scene.HasValue){ var saved=One(state.Scenes.Where(s=>!s.Retired&&s.CanonicalId==scene&&s.ChapterId==chapter));var first=saved==null?null:state.Paragraphs.Where(p=>p.Story&&p.SceneId==saved.Id).OrderBy(p=>p.Occurrence.Ordinal).FirstOrDefault(); if(first?.PositionVerified!=true)return false; if(lease.Position.CanChapterSync){var anchor=await chapters.SceneStart(user,book,scene.Value,first.Occurrence.Id,manuscript,session,revision);if(anchor?.Revision==state.Revision&&anchor.ChapterID==chapter&&anchor.SceneID==scene)start=anchor.StartPosition;} diff --git a/PlotLine/Sql/272_WriterReviewObservations.sql b/PlotLine/Sql/272_WriterReviewObservations.sql new file mode 100644 index 00000000..eaec407c --- /dev/null +++ b/PlotLine/Sql/272_WriterReviewObservations.sql @@ -0,0 +1,70 @@ +-- Author-private review observations: accepted-version/paragraph references are immutable. +-- Existing scene/session notes have neither chapter-level scope nor accepted-version anchors. +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +IF OBJECT_ID('dbo.WriterReviewObservations','U') IS NULL +BEGIN + CREATE TABLE dbo.WriterReviewObservations( + ID uniqueidentifier NOT NULL PRIMARY KEY,UserID int NOT NULL,BookID int NOT NULL,ChapterID int NOT NULL, + ManuscriptID uniqueidentifier NULL,SnapshotRevision bigint NOT NULL,ContentVersion char(64) NOT NULL, + StartParagraph uniqueidentifier NULL,EndParagraph uniqueidentifier NULL,StartOffset int NULL,EndOffset int NULL, + AnchorHash char(64) NULL,SceneID int NULL,Observation nvarchar(max) NOT NULL,Decision nvarchar(max) NULL, + Status varchar(16) NOT NULL DEFAULT 'Open',Version int NOT NULL DEFAULT 1, + CreatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),UpdatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(), + CONSTRAINT FK_WriterReview_User FOREIGN KEY(UserID) REFERENCES dbo.AppUser(UserID) ON DELETE CASCADE, + CONSTRAINT FK_WriterReview_Chapter FOREIGN KEY(ChapterID) REFERENCES dbo.Chapters(ChapterID) ON DELETE CASCADE, + CONSTRAINT FK_WriterReview_Book FOREIGN KEY(BookID) REFERENCES dbo.Books(BookID), + CONSTRAINT CK_WriterReview_Status CHECK(Status IN('Open','Working','Resolved')), + CONSTRAINT CK_WriterReview_Anchor CHECK((StartParagraph IS NULL AND EndParagraph IS NULL AND StartOffset IS NULL AND EndOffset IS NULL AND AnchorHash IS NULL) OR (StartParagraph IS NOT NULL AND EndParagraph IS NOT NULL AND StartOffset>=0 AND EndOffset>=0 AND AnchorHash IS NOT NULL)) + ); + CREATE INDEX IX_WriterReview_Scope ON dbo.WriterReviewObservations(UserID,BookID,ChapterID,CreatedUtc DESC,ID); +END; +GO +CREATE OR ALTER PROCEDURE dbo.WriterReview_Observations @Action varchar(12),@UserID int,@BookID int,@ChapterID int,@ID uniqueidentifier=NULL,@Version int=0, + @ManuscriptID uniqueidentifier=NULL,@SnapshotRevision bigint=NULL,@ContentVersion char(64)=NULL, + @StartParagraph uniqueidentifier=NULL,@EndParagraph uniqueidentifier=NULL,@StartOffset int=NULL,@EndOffset int=NULL,@AnchorHash char(64)=NULL,@SceneID int=NULL, + @Observation nvarchar(max)=NULL,@Decision nvarchar(max)=NULL,@Status varchar(16)='Open',@Page int=1 +AS +BEGIN + SET NOCOUNT ON;SET XACT_ABORT ON; + IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Chapters c ON c.BookID=b.BookID AND c.ChapterID=@ChapterID AND c.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) THROW 51000,'Review scope unavailable',1; + IF @Action='list' BEGIN + IF @Page<1 OR @Page>100000 THROW 51000,'Invalid review page',1; + SELECT * FROM dbo.WriterReviewObservations WHERE UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID ORDER BY CreatedUtc DESC,ID OFFSET ((@Page-1)*50) ROWS FETCH NEXT 51 ROWS ONLY;RETURN; + END; + IF @Action NOT IN('create','update') OR @ID IS NULL OR @Status NOT IN('Open','Working','Resolved') OR LEN(TRIM(COALESCE(@Observation,N'')))=0 OR LEN(@Observation)>10000 OR LEN(COALESCE(@Decision,N''))>10000 THROW 51000,'Invalid observation',1; + BEGIN TRANSACTION; + IF @Action='create' + BEGIN + IF EXISTS(SELECT 1 FROM dbo.WriterReviewObservations WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID) + BEGIN + IF NOT EXISTS(SELECT 1 FROM dbo.WriterReviewObservations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID AND Observation=@Observation AND ISNULL(Decision,N'')=ISNULL(@Decision,N'') AND ContentVersion=@ContentVersion AND Status=@Status AND ISNULL(CONVERT(varchar(36),StartParagraph),'')=ISNULL(CONVERT(varchar(36),@StartParagraph),'') AND ISNULL(CONVERT(varchar(36),EndParagraph),'')=ISNULL(CONVERT(varchar(36),@EndParagraph),'') AND ISNULL(StartOffset,-1)=ISNULL(@StartOffset,-1) AND ISNULL(EndOffset,-1)=ISNULL(@EndOffset,-1)) THROW 51002,'This observation changed; reload before retrying',1; + END ELSE BEGIN + DECLARE @CurrentRevision bigint,@CurrentManuscript uniqueidentifier; + SELECT @CurrentRevision=Revision,@CurrentManuscript=ManuscriptID FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID; + IF ISNULL(@CurrentRevision,-1)<>@SnapshotRevision OR ISNULL(@CurrentManuscript,'00000000-0000-0000-0000-000000000000')<>ISNULL(@ManuscriptID,'00000000-0000-0000-0000-000000000000') THROW 51002,'Accepted manuscript changed; your text has been retained',1; + INSERT dbo.WriterReviewObservations(ID,UserID,BookID,ChapterID,ManuscriptID,SnapshotRevision,ContentVersion,StartParagraph,EndParagraph,StartOffset,EndOffset,AnchorHash,SceneID,Observation,Decision,Status) + VALUES(@ID,@UserID,@BookID,@ChapterID,@ManuscriptID,@SnapshotRevision,@ContentVersion,@StartParagraph,@EndParagraph,@StartOffset,@EndOffset,@AnchorHash,@SceneID,@Observation,@Decision,@Status); + END; + END ELSE BEGIN + UPDATE dbo.WriterReviewObservations SET Observation=@Observation,Decision=@Decision,Status=@Status,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID AND Version=@Version; + IF @@ROWCOUNT<>1 THROW 51002,'Another window changed this observation; your text has been retained',1; + END; + SELECT * FROM dbo.WriterReviewObservations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID; + COMMIT; +END; +GO +-- The existing verified scene-start join, scoped to any accepted paragraph (including chapter-only prose). +CREATE OR ALTER PROCEDURE dbo.WriterReview_ParagraphStart @UserID int,@BookID int,@ChapterID int,@ParagraphID uniqueidentifier,@ManuscriptID uniqueidentifier,@SessionID uniqueidentifier,@WordRevision bigint,@AcceptedRevision bigint +AS +BEGIN + SET NOCOUNT ON; + IF NOT EXISTS(SELECT 1 FROM dbo.Books b 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) THROW 51000,'Book access denied',1; + SELECT m.Revision,pos.ChapterID,pos.StartPosition + FROM dbo.BookParagraphManuscripts m JOIN dbo.BookChapterValidations v ON v.BookID=m.BookID + CROSS APPLY OPENJSON(m.Payload,'$.ChapterCheckpoints') WITH(ChapterID int '$.ChapterId',ContentHash char(64),IdentityHash char(64),MappingHash char(64)) c + CROSS APPLY OPENJSON(v.Positions) WITH(ParagraphID uniqueidentifier '$.ParagraphId',StartPosition int '$.Start',ChapterID int '$.ChapterId',Verified bit) pos + JOIN dbo.Chapters ch ON ch.ChapterID=pos.ChapterID AND ch.BookID=m.BookID AND ch.IsArchived=0 + WHERE m.BookID=@BookID AND m.ManuscriptID=@ManuscriptID AND m.Revision=@AcceptedRevision AND v.ChapterID=c.ChapterID AND pos.ChapterID=c.ChapterID AND pos.ChapterID=@ChapterID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.ManuscriptID=@ManuscriptID AND v.WordRevision=@WordRevision AND v.ExpiresUtc>SYSUTCDATETIME() AND v.ContentHash=c.ContentHash AND v.IdentityHash=c.IdentityHash AND v.MappingHash=c.MappingHash AND pos.Verified=1 AND pos.ParagraphID=@ParagraphID; +END; diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index 9f353cb7..d03f07f0 100644 --- a/PlotLine/ViewModels/CoreViewModels.cs +++ b/PlotLine/ViewModels/CoreViewModels.cs @@ -927,6 +927,8 @@ public sealed class ChapterWorkflowViewModel public sealed class WriterDashboardViewModel { + public PlotLine.Services.Manuscript.ManuscriptReaderModel? ReviewReader {get;set;} + public string WordNavigationContext {get;set;}="working"; public string Destination { get; set; } = "Legacy"; public PlotLine.Services.Writer.WriterContext? WorkingContext { get; set; } public IReadOnlyList PlannedActivities { get; set; } = []; diff --git a/PlotLine/Views/ManuscriptReader/Index.cshtml b/PlotLine/Views/ManuscriptReader/Index.cshtml index d0a89467..972ea783 100644 --- a/PlotLine/Views/ManuscriptReader/Index.cshtml +++ b/PlotLine/Views/ManuscriptReader/Index.cshtml @@ -1,81 +1,4 @@ @model PlotLine.Services.Manuscript.ManuscriptReaderModel -@{ - ViewData["Title"] = $"Manuscript Reader · {Model.Book.BookTitle}"; - ViewData["DesktopLayout"] = "details"; - var reviewToolbar = new PlotLine.Models.WriterWorkToolbar(Model.Book.BookID, Model.Chapter?.ChapterID, Model.Chapter?.ChapterTitle, DefaultKind: "Reading"); -} - - -
- -
-

@Model.Book.BookTitle

Manuscript Reader

Read only
-
- - - -
- @if (Model.LastSuccessfulSyncUtc is DateTime sync) - {

Last successful chapter synchronisation:

} - else {

No successful chapter synchronisation timestamp is recorded.

} - @if (Model.SnapshotCapturedUtc is DateTime captured) - {

Accepted manuscript snapshot captured:

} -

Showing accepted server text. Changes are checked automatically while this page is visible.

-
-
Reading & Audio Review
- Return to Writing -
- @if (Model.Paragraphs.Count == 0) - { -

@(Model.Chapter?.ChapterTitle ?? "No chapters yet")

-

No accepted manuscript text is available for this chapter. Save and successfully synchronise it using Word Companion, then refresh this page.

- Refresh manuscript -
- } - else - { -
-

Chapter @Model.Chapter?.ChapterNumber

- @if (!Model.Paragraphs[0].IsHeading) - {

@Model.Chapter?.ChapterTitle

} -
- -
- } -
-

Captured paragraph text and headings are preserved. Word formatting such as bold, italics, images and page layout is not available in this capture.

- Return to Chapters - Refresh manuscript -
-
+ - diff --git a/PlotLine/Views/ManuscriptReader/_Paragraphs.cshtml b/PlotLine/Views/ManuscriptReader/_Paragraphs.cshtml index bb399df5..05684304 100644 --- a/PlotLine/Views/ManuscriptReader/_Paragraphs.cshtml +++ b/PlotLine/Views/ManuscriptReader/_Paragraphs.cshtml @@ -3,9 +3,9 @@ { var paragraph = Model[index]; if (paragraph.IsHeading && index == 0) - {

@paragraph.Text

} + {

@paragraph.Text

} else if (paragraph.IsHeading) - {

@paragraph.Text

} + {

@paragraph.Text

} else - {

@paragraph.Text

} + {

@paragraph.Text

} } diff --git a/PlotLine/Views/ManuscriptReader/_Reader.cshtml b/PlotLine/Views/ManuscriptReader/_Reader.cshtml new file mode 100644 index 00000000..fef975a6 --- /dev/null +++ b/PlotLine/Views/ManuscriptReader/_Reader.cshtml @@ -0,0 +1,85 @@ +@model PlotLine.Services.Manuscript.ManuscriptReaderModel +@{ + if(!Model.IntegratedReview){ViewData["Title"] = $"Manuscript Reader · {Model.Book.BookTitle}";ViewData["DesktopLayout"] = "details";} + var routeAction=Model.IntegratedReview?"Review":"Index";var routeController=Model.IntegratedReview?"Writer":"ManuscriptReader"; + var reviewToolbar = new PlotLine.Models.WriterWorkToolbar(Model.Book.BookID, Model.Chapter?.ChapterID, Model.Chapter?.ChapterTitle, DefaultKind: "Reading"); +} + + +
+ @if(!Model.IntegratedReview){ + +
+

@Model.Book.BookTitle

Manuscript Reader

Read only
+
+ } + + @if(Model.IntegratedReview){} + + + +
Reading & Audio Review
+ @if(!Model.IntegratedReview){Return to Writing} +
+ @if (Model.Paragraphs.Count == 0) + { +

@(Model.Chapter?.ChapterTitle ?? "No chapters yet")

+

No accepted manuscript text is available for this chapter. Save and successfully synchronise it using Word Companion, then refresh this page.

+ Refresh manuscript +
+ } + else + { +
+

Chapter @Model.Chapter?.ChapterNumber

+ @if (!Model.Paragraphs[0].IsHeading) + {

@Model.Chapter?.ChapterTitle

} +
+ +
+ } +
+

Captured paragraph text and headings are preserved. Word formatting such as bold, italics, images and page layout is not available in this capture.

+ Return to Chapters + Refresh manuscript +
+
+ + + diff --git a/PlotLine/Views/Writer/Destination.cshtml b/PlotLine/Views/Writer/Destination.cshtml index 30edeee1..5c3a137a 100644 --- a/PlotLine/Views/Writer/Destination.cshtml +++ b/PlotLine/Views/Writer/Destination.cshtml @@ -25,6 +25,7 @@ + @if(Model.Destination=="Review"){} @if(Model.Destination == "Write"){ diff --git a/PlotLine/Views/Writer/_ReviewContext.cshtml b/PlotLine/Views/Writer/_ReviewContext.cshtml new file mode 100644 index 00000000..97cc8a13 --- /dev/null +++ b/PlotLine/Views/Writer/_ReviewContext.cshtml @@ -0,0 +1,25 @@ +@model PlotLine.Services.Writer.ReviewPanel +@{var data=Model.Intentions;var goal=data.Sections.First(x=>x.Kind=="Goals");var scene=data.Sections.FirstOrDefault(x=>x.Kind=="Scene");string Compact(string value)=>value.Length>360?value[..360]+"…":value;} +
+

What did I want this to achieve?

@Model.ReferenceMessage

+ @if(scene!=null){

@data.Scene?.SceneTitle

@(string.IsNullOrWhiteSpace(scene.Value("ScenePurposeNotes"))?"No scene intention recorded.":Compact(scene.Value("ScenePurposeNotes")))

@Compact(scene.Value("SceneOutcomeNotes"))

Recorded scene state: @data.Scene?.RevisionStatusName

} +

@(string.IsNullOrWhiteSpace(goal.Value("GoalSummary"))?"No chapter intention recorded. You can review without one.":Compact(goal.Value("GoalSummary")))

+
Chapter details, reminders & editing + @foreach(var section in data.Sections.Where(x=>x.Kind is "Chapter" or "Goals")){@foreach(var field in section.Fields){var value=section.Value(field.Name);if(field.Type=="purpose"&&!string.IsNullOrWhiteSpace(value))value=section.Purposes.FirstOrDefault(p=>p.Value==value).Label??"Recorded purpose is unavailable";@if(!string.IsNullOrWhiteSpace(value)){

@field.Label@value

}}} + @foreach(var note in data.Sections.Where(x=>x.Kind=="Note"&&x.Value("IsResolved")!="true"||x.Kind=="Checklist"&&x.Value("IsCompleted")!="true").Take(10)){

@(note.Kind=="Note"?note.Value("NoteText"):note.Value("ItemText"))

} + @{var flow=data.Sections.FirstOrDefault(x=>x.Kind=="Workflow");}@if(flow!=null){

Priority: @flow.Value("Priority"). @flow.Value("BlockedReason")

} + Edit chapter intentions in the existing editor + @if(data.SceneID.HasValue){Edit scene intentions, notes and working details} +
+

Your observations

+ @if(Model.Observations.Count==0){

No observations on this page. Record something when it helps your review.

} + @foreach(var row in Model.Observations){ +
+

@(row.Status=="Open"?"Needs attention":row.Status=="Working"?"Working on it":"Resolved")

+

@row.Observation

@row.Decision

+

@row.AnchorState reference · @(row.SnapshotRevision<0?"No accepted version at capture":"Accepted version "+row.SnapshotRevision) · created @row.CreatedUtc.ToString("dd MMM yyyy HH:mm:ss") UTC · updated @row.UpdatedUtc.ToString("dd MMM yyyy HH:mm:ss") UTC

+
@if(row.StartParagraph.HasValue){}
+
} +
@if(Model.Page>1){}@if(Model.HasMore){}
+
+
diff --git a/PlotLine/Views/Writer/_WriterExplore.cshtml b/PlotLine/Views/Writer/_WriterExplore.cshtml index faacf867..24d88a54 100644 --- a/PlotLine/Views/Writer/_WriterExplore.cshtml +++ b/PlotLine/Views/Writer/_WriterExplore.cshtml @@ -3,11 +3,11 @@

Start with your question

What would you like to explore?

You do not need a finished outline or a linked manuscript. Choose a starting point.

-

The Problem Solver offers structured guidance. It does not automatically analyse your manuscript.

+

These open your authenticated writing and story tools. Guided exploration is planned for a later update; no manuscript analysis runs here.

diff --git a/PlotLine/Views/Writer/_WriterReview.cshtml b/PlotLine/Views/Writer/_WriterReview.cshtml index e94cf76e..3f73cc78 100644 --- a/PlotLine/Views/Writer/_WriterReview.cshtml +++ b/PlotLine/Views/Writer/_WriterReview.cshtml @@ -1,18 +1,29 @@ @model WriterDashboardViewModel -@{var chapter = Model.Objective?.ChapterID ?? Model.ObjectiveChoices.FirstOrDefault()?.ChapterID;} +@{var reader=Model.ReviewReader;var word=new WriterDashboardViewModel{BookID=Model.BookID,ProjectID=Model.ProjectID,WordNavigationContext="review",Objective=reader?.Chapter==null?null:new(){ChapterID=reader.Chapter.ChapterID,ChapterTitle=reader.Chapter.ChapterTitle,Activity="Revising"}};}
-
-

Read with a purpose

Review your writing

The Manuscript Reader shows accepted server text. Unsynchronised Word edits are not shown; save and synchronise the linked manuscript to update it.

- @if(chapter.HasValue){} - else{

No chapters to read yet

Add a chapter or import your manuscript from the book’s existing tools.

Open your book
} -

Listen and review

In the Reader, expand Reading & Audio Review to start a review session. Playback controls require compatible Windows Companion and a supported player. Opening the Reader does not start playback.

-
- +
+ @if(reader!=null){} + else{

Read the accepted manuscript

Select a book with chapters to review your accepted writing.

Open your book} +
+
diff --git a/PlotLine/Views/Writer/_WriterWord.cshtml b/PlotLine/Views/Writer/_WriterWord.cshtml index 1b6e6edd..c0cf1c43 100644 --- a/PlotLine/Views/Writer/_WriterWord.cshtml +++ b/PlotLine/Views/Writer/_WriterWord.cshtml @@ -1,16 +1,17 @@ @model WriterDashboardViewModel -@{var focus=Model.Objective;} -
+@{var focus=Model.Objective;var reviewing=Model.WordNavigationContext=="review";} +

Your manuscript in Word

Checking Word Companion…

Word position has not been verified.

Your latest changes have not yet been confirmed in PlotDirector.

+ @if(reviewing){} @if(focus?.ChapterID.HasValue==true){@if(focus.SceneID.HasValue){}}
-
Connection and update options

Working focus and Word position can differ. Navigation does not save Word or change your session. Reader shows accepted content.

+
Connection and update options

@(reviewing?"Review selection":"Working focus") and Word position can differ. Navigation does not save Word or change your session. Reader shows accepted content.