Qualify workspace persistence isolation, editorial flows and repeated navigation
This commit is contained in:
parent
eef4803c38
commit
25a151f958
@ -1,3 +1,3 @@
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),cp=require('node:child_process');
|
||||
(async()=>{const b=await chromium.launch();try{let baseline;const evidence=[];for(const before of [true,false]){const c=await b.newContext({viewport:{width:1666,height:1050}});await c.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));if(before){const css=cp.execFileSync('git',['show','f228d40:PlotLine/wwwroot/css/application-shell.css'],{encoding:'utf8'});await c.route('**/css/application-shell.css*',r=>r.fulfill({contentType:'text/css',body:css}));}const p=await c.newPage();await p.goto('http://127.0.0.1:5238/fixture?page=maps');await p.waitForSelector('[data-pwa-context-controls] .pd-context-command');const toggle=p.locator('[data-ribbon-collapse]');if(await toggle.getAttribute('aria-expanded')==='false')await toggle.click();await p.waitForTimeout(200);const facts=await p.evaluate(()=>{const panel=document.querySelector('.pd-ribbon-panel:not([hidden])'),bounds=panel.getBoundingClientRect(),commands=[...panel.querySelectorAll('.pd-ribbon-command')].filter(n=>n.getBoundingClientRect().width&&n.getBoundingClientRect().height);return{width:panel.clientWidth,scrollWidth:panel.scrollWidth,identities:[...new Set([...panel.querySelectorAll('[data-command-identity],[data-command-operation]')].map(n=>n.dataset.commandIdentity||n.dataset.commandOperation))].sort(),fitting:commands.filter(n=>n.getBoundingClientRect().right<=bounds.right+1).length,lines:commands.map(n=>{const span=n.querySelector(':scope>span');return{label:n.textContent.trim(),height:n.clientHeight,lines:span?Math.round(span.scrollHeight/parseFloat(getComputedStyle(span).lineHeight)):0};})}});if(before)baseline=facts;else{assert.equal(facts.identities.length,baseline.identities.length,'no commands removed');assert(facts.scrollWidth<baseline.scrollWidth,'shared spacing reduces occupied width');assert(facts.fitting>baseline.fitting,'more commands fit at 1666px');for(const x of facts.lines)assert(x.lines<=2,x.label+' exceeds two lines');}const out=process.env.PD_RIBBON_SCREENSHOTS;if(out){fs.mkdirSync(out,{recursive:true});await p.screenshot({path:out+'/Maps-1666-'+(before?'before':'after')+'.png'});}evidence.push({before,...facts});
|
||||
if(!before)for(const width of [1666,1366,1024,800]){await p.setViewportSize({width,height:1050});for(const category of ['project','book','writer','story','characters','world','tools']){const tab=p.locator('#ribbon-tab-'+category);if(!await tab.count())continue;await tab.click();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),category+' page overflow '+width);const heights=await p.locator('#ribbon-panel-'+category+' .pd-ribbon-command:visible').evaluateAll(ns=>ns.filter(n=>!n.closest('.pd-context-menu-content')).map(n=>Math.round(n.getBoundingClientRect().height)));assert(heights.every(h=>h===68),category+' inconsistent command heights '+heights);}}await c.close();}if(process.env.PD_RIBBON_SCREENSHOTS)fs.writeFileSync(process.env.PD_RIBBON_SCREENSHOTS+'/qualification.json',JSON.stringify(evidence,null,2));console.log('PASS shared ribbon: command preservation, greater 1666px Maps fit, two-line labels, uniform heights and primary tabs at 1666/1366/1024/800px; actual Chromium simulated PWA');}finally{await b.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1;});
|
||||
if(!before)for(const width of [1666,1366,1024,800]){await p.setViewportSize({width,height:1050});for(const category of ['project','book','writer','story','characters','world','tools']){const tab=p.locator('#ribbon-tab-'+category);if(!await tab.count())continue;await tab.click();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),category+' page overflow '+width);const heights=await p.locator('#ribbon-panel-'+category+' .pd-ribbon-command:visible').evaluateAll(ns=>ns.filter(n=>!n.closest('.pd-context-menu-content')).map(n=>Math.round(n.getBoundingClientRect().height)));assert(heights.every(h=>h===68),category+' inconsistent command heights '+heights);if(out&&(width===1666||width===800))await p.screenshot({path:out+'/'+category+'-'+width+'.png'});}}await c.close();}if(process.env.PD_RIBBON_SCREENSHOTS)fs.writeFileSync(process.env.PD_RIBBON_SCREENSHOTS+'/qualification.json',JSON.stringify(evidence,null,2));console.log('PASS shared ribbon: command preservation, greater 1666px Maps fit, two-line labels, uniform heights and primary tabs at 1666/1366/1024/800px; actual Chromium simulated PWA');}finally{await b.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1;});
|
||||
|
||||
36
PlotLine.Tests/Browser/writer-phase21-live.cjs
Normal file
36
PlotLine.Tests/Browser/writer-phase21-live.cjs
Normal file
@ -0,0 +1,36 @@
|
||||
// Authenticated Development only; guarded disposable identity and author-owned fixture.
|
||||
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict'),crypto=require('node:crypto');
|
||||
const who=JSON.parse(fs.readFileSync(process.env.PD_PHASE21_IDENTITY)),s=JSON.parse(fs.readFileSync(process.env.PD_PHASE21_SCOPE)),base='https://dev.plotdirector.com',out=process.env.PD_PHASE21_SCREENSHOTS;
|
||||
assert(who.Database==='PlotDirector_Development'&&/^pwa-browser-.*@example\.invalid$/.test(who.Email));
|
||||
(async()=>{const browser=await chromium.launch();try{for(const pwa of [false,true]){const c=await browser.newContext({viewport:{width:1920,height:1100}});await c.addInitScript(({user,pwa})=>{localStorage.setItem('plotdirector.desktop.v1.'+user,JSON.stringify({dismissedAt:Date.now()}));if(pwa)Object.defineProperty(navigator,'standalone',{value:true});},{user:who.UserID,pwa});const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));p.on('dialog',d=>d.accept());let popups=0;c.on('page',page=>{if(page!==p)popups++;});const url=(d,b=s.book)=>`${base}/Writer/${d}?bookId=${b}&projectId=${s.project}`;
|
||||
const shot=async name=>{if(!out||pwa)return;fs.mkdirSync(out,{recursive:true});await p.mouse.move(1,1090);await p.waitForTimeout(120);await p.screenshot({path:out+'/'+name+'.png',animations:'disabled'});};
|
||||
await p.goto(base+'/Account/Login');await p.locator('[name=Email]').fill(who.Email);await p.locator('[name=Password]').fill(who.Password);await Promise.all([p.waitForURL('**/Projects'),p.locator('button[type=submit]').click()]);
|
||||
await p.goto(url('Write'));if(await p.locator('[data-ribbon-collapse]').getAttribute('aria-expanded')==='false')await p.locator('[data-ribbon-collapse]').click();const exportSessions=async()=>await(await p.request.get(base+'/Writer/Work/Export?bookId='+s.book)).json();const before=await exportSessions();
|
||||
if(!await p.locator('[data-focus-wizard]').isVisible())await p.locator('[data-change-focus]').click();const focus=p.locator('[data-focus-wizard]');await focus.locator('[name=Activity]').selectOption('Revising');await focus.locator('[data-focus-next]').click();await focus.locator('[name=ChapterID]').selectOption(String(s.chapter));await focus.locator('[name=SceneID]').selectOption(String(s.scene));await focus.locator('[data-focus-next]').click();await focus.locator('[name=Intention]').fill('Phase21 selected arrival');await focus.locator('[data-save-focus]').click();await p.locator('[data-focus-summary]').filter({hasText:'Phase21 selected arrival'}).waitFor();assert((await p.locator('[data-focus-summary] a').getAttribute('href')).endsWith('/Scenes/Edit/'+s.scene));assert.deepEqual(await exportSessions(),before);
|
||||
const checklist=p.locator('[data-authoring-card][data-kind=Checklist]').first();await checklist.locator('[data-checklist-toggle]').waitFor();const checked=await checklist.locator('[data-checklist-toggle]').isChecked();await checklist.locator('[data-checklist-toggle]').setChecked(!checked);await p.waitForFunction(value=>document.querySelector('[data-authoring-card][data-kind=Checklist] [data-checklist-toggle]')?.checked===value,!checked);await checklist.locator('[data-authoring-edit]').click();await checklist.locator('[name=ItemText]').fill('Check the arrival turning point '+pwa);await checklist.locator('[data-authoring-save]').click();await checklist.locator('[data-authoring-display]').filter({hasText:'Check the arrival turning point '+pwa}).waitFor();assert.equal(await checklist.locator('[data-checklist-toggle]').isChecked(),!checked);await shot('Write-checklist-and-ribbon');
|
||||
const token=await p.locator('input[name=__RequestVerificationToken]').first().inputValue(),session=crypto.randomUUID();assert.equal((await p.request.post(base+'/Writer/Work/Start',{form:{bookId:s.book,kind:'Planning',requestId:session,__RequestVerificationToken:token}})).status(),200);assert.equal((await p.request.post(base+'/Writer/Work/End',{form:{bookId:s.book,sessionId:session,note:'Phase21 explicit session',__RequestVerificationToken:token}})).status(),200);
|
||||
await p.goto(url('Explore'));await p.locator('[data-explore-journey] [name=concern]').first().waitFor();assert.equal(await p.locator('[data-explore-tab=new]').getAttribute('aria-selected'),'true');await shot('Explore-new');const concern=await p.locator('[name=concern]').first().inputValue();let navigations=0;const track=r=>{if(r.isNavigationRequest()&&r.frame()===p.mainFrame())navigations++;};p.on('request',track);await p.locator('[name=concern]').first().check();await p.locator('[data-explore-journey] button[type=submit]').click();await p.locator('[data-inline-investigation]').waitFor();assert(await p.locator('.writer21-investigating').count());await shot('Explore-during');
|
||||
for(let n=0;n<25&&await p.locator('[data-investigation-answer]').count();n++){const form=p.locator('[data-investigation-answer]'),version=await form.locator('[name=version]').inputValue();await form.locator('[name=option]').first().check();await form.locator('button[value=answer]').click();await p.waitForFunction(old=>!document.querySelector('[data-investigation-answer]')||document.querySelector('[data-investigation-answer] [name=version]').value!==old,version);}
|
||||
assert.equal(await p.locator('[data-investigation-answer]').count(),0,'results inline');assert.equal(navigations,0,'questionnaire never navigates the main document');p.off('request',track);await shot('Explore-results');
|
||||
const earlier=p.locator('.investigation-journey aside a[href*="question="]').first();if(await earlier.count()){await earlier.click();await p.locator('[data-investigation-answer]').waitFor();const form=p.locator('[data-investigation-answer]'),version=await form.locator('[name=version]').inputValue();await form.locator('[name=option]').last().check();await form.locator('button[value=answer]').click();await p.waitForFunction(old=>!document.querySelector('[data-investigation-answer]')||document.querySelector('[data-investigation-answer] [name=version]').value!==old,version);}
|
||||
const investigation=new URL(p.url()).searchParams.get('investigation');assert(investigation);
|
||||
if(!pwa)for(let n=0;n<26;n++){const response=await p.request.post(base+'/Writer/Explore/Investigate/Start',{headers:{'X-Writer-Explore':'inline'},form:{bookId:s.book,concern,requestId:crypto.randomUUID(),__RequestVerificationToken:token}});assert.equal(response.status(),200);}
|
||||
await p.locator('[data-explore-tab=saved]').click();await p.waitForFunction(()=>document.querySelectorAll('[data-explore-saved] article').length>=26);const saved=p.locator('[data-explore-saved]');assert(await saved.evaluate(n=>n.scrollHeight>n.clientHeight));await saved.evaluate(n=>n.scrollTop=200);await p.locator('[data-explore-tab=new]').click();await p.locator('[data-explore-tab=saved]').click();await p.waitForTimeout(150);assert((await saved.evaluate(n=>n.scrollTop))>0);await shot('Explore-saved-scroll');await saved.locator('a').first().click();await p.locator('[data-inline-investigation]').waitFor();assert.equal(new URL(p.url()).pathname,'/Writer/Explore');
|
||||
await p.goto(url('Plan'));await p.locator('[data-planner-view]').waitFor();const planner=p.locator('[data-activity-planner]');const countBefore=(await exportSessions()).length;
|
||||
for(const [title,kind,entity,date] of [['Revise arrival '+pwa,'Editing','Scene:'+s.scene,''],['Review crossing '+pwa,'Review','Chapter:'+s.chapter,new Date().toISOString().slice(0,10)],['Think about the route '+pwa,'Planning','','']]){const add=planner.locator('details').filter({has: p.locator('summary').filter({hasText:'Add planned activity'})}).first();await add.locator('summary').click();const f=add.locator('form');await f.locator('[name=Title]').fill(title);await f.locator('[name=Kind]').selectOption(kind);await f.locator('[name=EntityKey]').selectOption(entity);await f.locator('[name=Notes]').fill('Synthetic intended work, not a recording');if(date)await f.locator('[name=TargetDate]').fill(date);await f.locator('button[type=submit]').click();await planner.locator('[data-activity-id]').filter({hasText:title}).waitFor();}
|
||||
for(const view of ['list','board','schedule']){await planner.locator('[data-planner-tab='+view+']').click();await planner.locator('[data-planner-view='+view+']').waitFor();assert((await planner.locator('[data-activity-id]').count())>=3);if(view==='schedule')assert((await planner.textContent()).includes('Undated activities'));await shot('Plan-'+view);}
|
||||
await planner.locator('[data-planner-tab=list]').click();await planner.locator('[data-planner-view=list]').waitFor();const task=planner.locator('[data-activity-id]').filter({hasText:'Revise arrival '+pwa}).first();await task.locator('details').filter({has:p.locator('summary').filter({hasText:'Edit activity'})}).locator('summary').click();const edit=task.locator('[data-activity-save]');await edit.locator('[name=Notes]').fill('Clarify the turning point before leaving');await edit.locator('button[type=submit]').click();await task.filter({hasText:'Clarify the turning point before leaving'}).waitFor();
|
||||
for(const status of ['Completed','Next','Deferred','In progress']){const f=task.locator('[data-activity-change]').filter({has:p.locator('[name=status]')});await f.locator('[name=status]').selectOption(status);await f.locator('button').click();await p.waitForFunction(({title,status})=>[...document.querySelectorAll('[data-activity-id]')].some(n=>n.querySelector('h4').textContent===title&&n.querySelector('[data-activity-change] [name=status]').value===status),{title:'Revise arrival '+pwa,status});}
|
||||
await task.getByRole('button',{name:/Move down/}).click();await p.waitForTimeout(150);assert.equal((await exportSessions()).length,countBefore);assert.equal((await p.request.post(base+'/WriterActivities/Change',{form:{bookId:s.book,id:crypto.randomUUID(),operation:'status',status:'Completed'}})).status(),400);
|
||||
await task.locator('[data-activity-start] button').click();await p.waitForURL('**/Writer/Write?*');assert((await p.locator('[data-focus-summary]').textContent()).includes('Revise arrival '+pwa));assert.equal((await exportSessions()).length,countBefore);
|
||||
await p.goto(url('Review')+'&chapterId='+s.chapter);await p.locator('[data-review-panel]').waitFor();const form=p.locator('[data-review-form]');await p.locator('[data-review-scope-new=Chapter]').click();await form.locator('[name=Observation]').fill('Chapter continuity '+pwa);await form.locator('[name=Classification]').selectOption('Continuity');await form.locator('[data-review-save]').click();await p.locator('[data-chapter-annotations] [data-observation]').filter({hasText:'Chapter continuity '+pwa}).waitFor();
|
||||
const para=p.locator('#reader-content [data-scene-id="'+s.scene+'"]').first();await para.click();await p.waitForFunction(scene=>document.querySelector('[data-review-panel]')?.dataset.selectedScene===String(scene),s.scene);for(const scope of ['Scene','Passage']){await p.locator('[data-review-new]').click();await form.locator('[name=Scope]').selectOption(scope);await form.locator('[name=Observation]').fill(scope+' editorial note '+pwa);await form.locator('[name=Classification]').selectOption('Pacing');await form.locator('[data-review-save]').click();await p.locator('[data-observation]').filter({hasText:scope+' editorial note '+pwa}).waitFor();}
|
||||
const note=p.locator('[data-observation]').filter({hasText:'Passage editorial note '+pwa});await note.locator('[data-review-edit]').click();await form.locator('[name=Classification]').selectOption('Research');await form.locator('[name=Status]').selectOption('Resolved');await form.locator('[data-review-save]').click();await p.locator('[data-observation][data-status=Resolved]').filter({hasText:'Passage editorial note '+pwa}).waitFor();await note.locator('[data-review-revisit]').click();await p.evaluate(()=>scrollTo(0,0));await shot('Review-both-notes');
|
||||
const chapterCard=p.locator('#review-chapter-notes [data-authoring-card][data-kind=Chapter]');await chapterCard.locator('[data-authoring-edit]').click();await chapterCard.locator('[name=Summary]').fill('Synthetic chapter summary edited directly in Review');await chapterCard.locator('[data-authoring-save]').click();await chapterCard.locator('[data-authoring-display]').filter({hasText:'Synthetic chapter summary edited directly in Review'}).waitFor();
|
||||
const companion=p.locator('[data-writer-companion-toggle]');if(await companion.getAttribute('aria-expanded')==='true')await companion.click();await shot('Review-word-hidden');for(const b of await p.locator('[data-editorial-toggle]').all()){await b.click();await b.click();}
|
||||
const records=await(await p.request.get(base+'/InvestigationCompanion/Saved?bookId='+s.book)).json();const selected=records.find(r=>r.id===investigation)||records[0];assert.equal((await p.request.post(base+'/InvestigationCompanion/Update',{headers:{'X-Requested-With':'XMLHttpRequest'},form:{bookId:s.book,id:selected.id,version:selected.guidanceVersion,operation:'activate',__RequestVerificationToken:token}})).status(),200);
|
||||
await p.goto(url('Review')+'&chapterId='+s.chapter);await p.locator('[data-review-panel]').waitFor();await p.waitForFunction(()=>window.PlotDirectorGuidanceSummary?.active);if(await p.locator('[data-guidance-open]').isVisible())await p.locator('[data-guidance-open]').click();await p.evaluate(()=>PlotLineHelpDrawer.open('writer3.review'));await p.locator('.help-drawer-article').waitFor();await shot('Review-investigation-and-help');await p.locator('#reader-focus').click();await shot('Focus-reading');await p.locator('a[rel=next]').first().click();await p.waitForURL(new RegExp('chapterId='+s.secondChapter));assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');await p.locator('a[rel=prev]').first().click();await p.waitForURL(new RegExp('chapterId='+s.chapter));assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');
|
||||
await p.goto(url('Reflect'));await p.locator('.writer-month-grid').waitFor();assert.equal(await p.locator('[data-tab=calendar]').getAttribute('aria-selected'),'true');await shot('Reflect-calendar');await p.locator('[data-tab=sessions]').click();assert(await p.locator('[data-session-history]').isVisible());await p.locator('[data-session-filter]').fill('Synthetic session history');assert(await p.locator('[data-session-history]').evaluate(n=>n.scrollHeight>n.clientHeight));await shot('Reflect-sessions');
|
||||
await p.goto(base+'/Writer/Journey?bookId='+s.book+'&year=2026&month=10&day=2026-10-15');assert.equal(new URL(p.url()).pathname,'/Writer/Reflect');assert(new URL(p.url()).searchParams.get('month')==='10');
|
||||
for(const width of [1440,900,800])for(const destination of ['Write','Explore','Plan','Review','Reflect']){await p.setViewportSize({width,height:1000});await p.goto(url(destination));await p.waitForTimeout(120);assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),destination+' overflow '+width);assert((await p.title()).includes(destination));assert(await p.locator('.writer3-header').count()===0,destination+' redundant intro');}
|
||||
assert.equal(popups,0,'internal flows stay in the same window');assert.deepEqual(errors,[]);console.log('PASS Phase21 authenticated '+(pwa?'simulated PWA':'browser')+': focus/checklist/session independence; inline investigation/recomputation/results/saved scrolling; planner views/status/edit/order/start; editorial scopes and notes; Focus, legacy Reflect, history, same-window and responsive flows');await c.close();}}finally{await browser.close();}})().catch(error=>{console.error(String(error.stack).replaceAll(who.Password,'[redacted]'));process.exitCode=1});
|
||||
7
PlotLine.Tests/Browser/writer-phase21-review.cjs
Normal file
7
PlotLine.Tests/Browser/writer-phase21-review.cjs
Normal file
@ -0,0 +1,7 @@
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict');
|
||||
(async()=>{const browser=await chromium.launch();try{for(const pwa of [false,true]){const context=await browser.newContext({viewport:{width:1920,height:1100}});await context.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()})));if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));await context.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null,defaultPauseOnEdit:true}}));await context.route('**/native-companion/status*',r=>r.fulfill({json:{leases:[]}}));const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto('http://127.0.0.1:5238/Writer/Review?projectId=7&bookId=12&chapterId=21');await page.locator('[data-review-panel]').waitFor();
|
||||
assert.equal(await page.locator('.writer21-editorial').count(),1);const form=page.locator('[data-review-form]');await page.locator('[data-review-scope-new=Chapter]').click();await form.locator('[name=Observation]').fill('Chapter annotation Phase21 '+pwa);await form.locator('[name=Classification]').selectOption('Continuity');await form.locator('[data-review-save]').click();await page.locator('[data-chapter-annotations] [data-observation]').filter({hasText:'Chapter annotation Phase21 '+pwa}).waitFor();
|
||||
const paragraph=page.locator('#reader-content [data-paragraph-id][data-scene-id="31"]').first();await paragraph.click();await page.waitForFunction(()=>document.querySelector('[data-review-panel]').dataset.selectedScene==='31');await page.locator('[data-review-new]').click();await form.locator('[name=Scope]').selectOption('Scene');await form.locator('[name=Observation]').fill('Scene annotation Phase21 '+pwa);await form.locator('[data-review-save]').click();const scene=page.locator('[data-observation][data-scope=Scene]').filter({hasText:'Scene annotation Phase21 '+pwa});await scene.waitFor();await scene.locator('[data-review-edit]').click();await form.locator('[name=Status]').selectOption('Resolved');await form.locator('[name=Classification]').selectOption('Revision needed');await form.locator('[data-review-save]').click();await page.locator('[data-observation][data-status=Resolved][data-classification="Revision needed"]').filter({hasText:'Scene annotation Phase21 '+pwa}).waitFor();
|
||||
await paragraph.click();await page.locator('[data-review-new]').click();await form.locator('[name=Scope]').selectOption('Passage');await form.locator('[name=Observation]').fill('Paragraph annotation Phase21 '+pwa);await form.locator('[data-review-save]').click();const passage=page.locator('[data-observation][data-scope=Passage]').filter({hasText:'Paragraph annotation Phase21 '+pwa});await passage.waitFor();await passage.locator('[data-review-revisit]').click();
|
||||
for(const theme of ['modern-light','modern-dark','warm-light','warm-dark'])for(const width of [1920,1440,800]){await page.setViewportSize({width,height:1100});await page.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);for(const b of await page.locator('[data-editorial-toggle]').all()){await b.click();await b.click();}assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),theme+width);}
|
||||
await page.locator('#reader-focus').click();await page.locator('a[rel=next]').first().click();await page.waitForURL(/chapterId=22/);assert.equal(await page.locator('.manuscript-reader').getAttribute('data-focus'),'true');await page.locator('a[rel=prev]').first().click();await page.waitForURL(/chapterId=21/);assert.equal(await page.locator('.manuscript-reader').getAttribute('data-focus'),'true');assert.deepEqual(errors,[]);await context.close();}console.log('PASS Phase21 Review chapter/scene/passage annotations, classification/resolution, four themes, three widths, panels and Focus navigation; canonical/Word transport simulated');}finally{await browser.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1;});
|
||||
2
PlotLine.Tests/Browser/writer-phase21-word.cjs
Normal file
2
PlotLine.Tests/Browser/writer-phase21-word.cjs
Normal file
@ -0,0 +1,2 @@
|
||||
const{chromium}=require('playwright'),assert=require('node:assert/strict');
|
||||
(async()=>{const browser=await chromium.launch();try{for(const pwa of [false,true]){const c=await browser.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}));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:'Synthetic Word source',expires:new Date(Date.now()+3600000).toISOString()};const packet={leases:[lease],canonical:{manuscriptID:lease.manuscriptId},verifiedPositions:[]};const posts=[];await c.route('**/native-companion/status*',r=>r.fulfill({json:packet}));await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null}}));await c.route('**/WriterWord/Availability?*',r=>r.fulfill({json:{chapter:true,scene:true,paragraph:true}}));await c.route('**/WriterWord/Navigate',r=>{posts.push(Object.fromEntries(new URLSearchParams(r.request().postData())));return r.fulfill({status:202,json:{}})});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));await p.goto('http://127.0.0.1:5238/Writer/Write?projectId=7&bookId=12&objective=true');if(await p.locator('[data-ribbon-collapse]').getAttribute('aria-expanded')==='false')await p.locator('[data-ribbon-collapse]').click();await p.waitForFunction(()=>!document.querySelector('[data-ribbon-word=chapter]').disabled);const times=[];for(let i=0;i<3;i++){const start=Date.now();await p.locator('[data-ribbon-word=chapter]').click();await p.locator('[data-word-command]').filter({hasText:'Word confirmed navigation.'}).waitFor();times.push(Date.now()-start);}assert.equal(new Set(posts.map(x=>x.navigationId)).size,3);assert(posts.every(x=>x.chapterId==='21'));await p.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:focus-saved',{detail:{chapterID:22,sceneID:null}})));await p.locator('[data-ribbon-word=chapter]').click();await p.locator('[data-word-command]').filter({hasText:'Word confirmed navigation.'}).waitFor();assert.equal(posts.at(-1).chapterId,'22');assert(await p.locator('[data-ribbon-word=scene]').isDisabled());await p.evaluate(v=>window.dispatchEvent(new CustomEvent('writer-word-state',{detail:{...v,leases:[{...v.leases[0],bookId:13}]}})),packet);assert(await p.locator('[data-ribbon-word=chapter]').isDisabled());assert.deepEqual(errors,[]);console.log('PASS repeated unique navigation, immediate new focus targets, cross-book refusal, '+(pwa?'simulated PWA':'browser')+'; browser simulated transport confirmation ms '+times.join(','));await c.close();}}finally{await browser.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1});
|
||||
@ -29,6 +29,7 @@ if(args.Contains("--geography")){await GeographyTests.Run();return;}
|
||||
if((args.Contains("--chapter-acceptance-dev")||args.Contains("--chapter-reuse-dev")||args.Contains("--chapter-incremental-dev"))){await ChapterAcceptanceDevelopmentTests.Run(args);return;}
|
||||
if(args.Contains("--chapter-sync-dev")){await ChapterSyncDevelopmentTests.Run(args);return;}
|
||||
if(args.Contains("--writing-activity-database")){await WritingActivityDatabaseTests.Run();return;}
|
||||
if(args.Contains("--writer-phase21-database")){await WriterPhase21DatabaseTests.Run();return;}
|
||||
if(args.Contains("--writer-intelligence-database")){await WriterIntelligenceDatabaseTests.Run();return;}
|
||||
if(args.Contains("--writer-intelligence")){WriterIntelligenceTests.Run();return;}
|
||||
if(args.Contains("--writing-activity")){WritingActivityTests.Run();return;}
|
||||
@ -177,6 +178,7 @@ var tests = new (string Name, Action Test)[]
|
||||
("Guided investigation evidence, validation, revision and deterministic simulation",()=>InvestigationTests.Run()),
|
||||
("Guided investigation diagnostic corrective acceptance",()=>InvestigationDiagnosticTests.Run()),
|
||||
("Production Guided Investigation editorial acceptance",()=>ProductionInvestigationTests.Run()),
|
||||
("Writer Phase21 repeated navigation acknowledgement and book isolation",()=>WriterPhase21Tests.Run()),
|
||||
("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()),
|
||||
|
||||
65
PlotLine.Tests/WriterPhase21DatabaseTests.cs
Normal file
65
PlotLine.Tests/WriterPhase21DatabaseTests.cs
Normal file
@ -0,0 +1,65 @@
|
||||
using System.Diagnostics;
|
||||
using System.Data;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services.Manuscript;
|
||||
using PlotLine.Services.Writer;
|
||||
internal static class WriterPhase21DatabaseTests
|
||||
{
|
||||
public static async Task Run()
|
||||
{
|
||||
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true};foreach(var part in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(part);using var process=Process.Start(start)!;var env=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new Exception("Configuration unavailable");
|
||||
var raw=env.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');var connection=new SqlConnectionStringBuilder(raw);if(connection.InitialCatalog!="PlotDirector_Development")throw new Exception("Unexpected configured database");connection.InitialCatalog="PlotDirector_WriterPhase21_20261118";
|
||||
using var db=new SqlConnection(connection.ConnectionString);await db.OpenAsync();if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!=connection.InitialCatalog)throw new Exception("Wrong disposable target");
|
||||
void Check(bool ok,string text){if(!ok)throw new Exception(text);Console.WriteLine("PASS Phase21 "+text);}
|
||||
async Task Reject(Func<Task> action,string text){try{await action();}catch(Exception e)when(e is SqlException or ArgumentException or KeyNotFoundException or AuthoringConflictException){Check(true,text);return;}throw new Exception(text);}
|
||||
var factory=new SqlConnectionFactory(new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",connection.ConnectionString}}).Build());
|
||||
var rows=await db.QuerySingleAsync<(int UserID,int Other,int ProjectID,int BookID,int ForeignBook,int ChapterID,int EmptyChapter,int SceneID)>("""
|
||||
DECLARE @u int,@o int,@p int,@b int,@f int,@c int,@empty int,@s int,@l int,@revision int=(SELECT TOP(1) RevisionStatusID FROM dbo.RevisionStatuses ORDER BY SortOrder);
|
||||
INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+'@work.invalid','Synthetic work author','not-a-credential');SET @u=SCOPE_IDENTITY();
|
||||
INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+'@work.invalid','Synthetic other','not-a-credential');SET @o=SCOPE_IDENTITY();
|
||||
INSERT dbo.SubscriptionLevel(Name,DisplayName,MaxBooks,MaxChaptersPerBook,MaxScenesPerBook,MaxCharactersPerProject,MaxStorageMB,MaxCollaborators,SortOrder,RequiresStripeSubscription) VALUES(CONVERT(nvarchar(36),NEWID()),'Work fixture',10,100,100,100,100,0,0,0);SET @l=SCOPE_IDENTITY();
|
||||
INSERT dbo.UserSubscription(UserID,SubscriptionLevelID,IsActive,IsTrial,TrialExpiryDateUTC) VALUES(@u,@l,1,1,'2030-01-01');
|
||||
INSERT dbo.Projects(ProjectName) VALUES('Synthetic intelligent Writer');SET @p=SCOPE_IDENTITY();
|
||||
INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@p,@u,'Owner',1);
|
||||
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@p,'Synthetic Writer',1,1);SET @b=SCOPE_IDENTITY();
|
||||
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@p,'Foreign target',2,2);SET @f=SCOPE_IDENTITY();
|
||||
INSERT dbo.Chapters(BookID,ChapterTitle,ChapterNumber,SortOrder,RevisionStatusID) VALUES(@b,'Synthetic chapter',1,1,@revision);SET @c=SCOPE_IDENTITY();
|
||||
INSERT dbo.Chapters(BookID,ChapterTitle,ChapterNumber,SortOrder,RevisionStatusID) VALUES(@b,'Chapter without a scene',2,2,@revision);SET @empty=SCOPE_IDENTITY();
|
||||
INSERT dbo.Scenes(ChapterID,SceneTitle,SceneNumber,SortOrder,RevisionStatusID,TimeModeID,TimeConfidenceID) VALUES(@c,'Synthetic scene',1,1,@revision,(SELECT TOP(1) TimeModeID FROM dbo.TimeModes ORDER BY SortOrder),(SELECT TOP(1) TimeConfidenceID FROM dbo.TimeConfidences ORDER BY SortOrder));SET @s=SCOPE_IDENTITY();
|
||||
SELECT @u UserID,@o Other,@p ProjectID,@b BookID,@f ForeignBook,@c ChapterID,@empty EmptyChapter,@s SceneID;
|
||||
""");
|
||||
var user=rows.UserID;var book=rows.BookID;var planner=new WriterActivityRepository(factory);var id=Guid.NewGuid();
|
||||
var create=new{Action="save",UserID=user,BookID=book,ID=id,Title="Revise arrival",Kind="Editing",EntityKind="Scene",EntityID=rows.SceneID,Notes="Keep the change clear",Status="Next"};
|
||||
await planner.Execute(create);await planner.Execute(create);Check((await planner.Read(user,book)).Count==1,"idempotent create preserves a single activity");
|
||||
await Reject(()=>planner.Execute(new{Action="save",UserID=user,BookID=rows.ForeignBook,ID=Guid.NewGuid(),Title="Wrong scope",Kind="Writing",EntityKind="Scene",EntityID=rows.SceneID}),"cross-book scene reference refused");
|
||||
await Reject(async()=>{await planner.Read(rows.Other,book);},"unrelated author cannot read planner");
|
||||
await db.ExecuteAsync("INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@ProjectID,@Other,'Collaborator',1)",new{rows.ProjectID,rows.Other});
|
||||
Check((await planner.Read(rows.Other,book)).Count==0,"shared project authors do not see each other's private intentions");
|
||||
await Reject(()=>planner.Execute(new{Action="status",UserID=rows.Other,BookID=book,ID=id,Version=1,Status="Completed"}),"shared project author cannot mutate another activity");
|
||||
var second=Guid.NewGuid();await planner.Execute(new{Action="save",UserID=user,BookID=book,ID=second,Title="Review chapter",Kind="Review",TargetDate=DateTime.Today.AddDays(1)});
|
||||
foreach(var state in new[]{"In progress","Completed","Next","Deferred"}){var row=(await planner.Read(user,book)).Single(x=>x.ID==id);await planner.Execute(new{Action="status",UserID=user,BookID=book,ID=id,row.Version,Status=state});Check((await planner.Read(user,book)).Single(x=>x.ID==id).Status==state,"planned activity transitions to "+state);}
|
||||
var current=(await planner.Read(user,book)).Single(x=>x.ID==second);await planner.Execute(new{Action="move",UserID=user,BookID=book,ID=second,current.Version,Direction=-1});Check((await planner.Read(user,book))[0].ID==second,"accessible reorder persists across reads");
|
||||
await Reject(()=>planner.Execute(new{Action="status",UserID=user,BookID=book,ID=second,current.Version,Status="Completed"}),"stale activity mutation is refused");
|
||||
current=(await planner.Read(user,book)).Single(x=>x.ID==second);await planner.Execute(new{Action="archive",UserID=user,BookID=book,ID=second,current.Version});current=(await planner.Read(user,book)).Single(x=>x.ID==second);Check(current.IsArchived,"archive retains activity history");await planner.Execute(new{Action="restore",UserID=user,BookID=book,ID=second,current.Version});Check(!(await planner.Read(user,book)).Single(x=>x.ID==second).IsArchived,"archive can be restored");
|
||||
Check((await planner.Read(user,book)).Any(x=>x.TargetDate==null)&&(await planner.Read(user,book)).Any(x=>x.TargetDate.HasValue),"dated and undated activities share one collection");
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.WriterWorkSessions WHERE UserID=@user",new{user})==0,"planning mutations never fabricate sessions");
|
||||
var paragraphs=new ParagraphManuscriptRepository(factory);var paragraph=Guid.NewGuid();var stableScene=Guid.NewGuid();var text="A quiet arrival changed the traveller's plan.\r";
|
||||
var source=new ParagraphManuscript{BookId=book,ProjectId=rows.ProjectID,ManuscriptId=Guid.NewGuid(),SnapshotHash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))),Scenes=[new(){Id=stableScene,CanonicalId=rows.SceneID,ChapterId=rows.ChapterID}],Paragraphs=[new(){Story=true,PositionVerified=true,ChapterId=rows.ChapterID,SceneId=stableScene,Occurrence=new(){Id=paragraph,Ordinal=0,Start=0,End=text.Length,Text=text}}]};
|
||||
await paragraphs.Save(user,source,-1,Guid.NewGuid());var reader=new ManuscriptReaderService(paragraphs,new BookRepository(factory),new ChapterRepository(factory));var accepted=await reader.Read(user,book,rows.ChapterID);var review=new WriterReviewService(factory,reader,new WriterAuthoringFixture());
|
||||
foreach(var scope in new[]{"Chapter","Scene","Passage"}){
|
||||
var request=new ReviewSave{BookID=book,ChapterID=rows.ChapterID,ID=Guid.NewGuid(),ContentVersion=accepted!.ContentVersion,Scope=scope,SceneID=scope=="Scene"?rows.SceneID:null,Observation="Editorial "+scope,Classification="Continuity"};if(scope=="Passage"){request.StartParagraph=paragraph;request.EndParagraph=paragraph;request.StartOffset=2;request.EndOffset=12;}
|
||||
var row=await review.Save(user,request);Check(row.EffectiveScope==scope&&row.EffectiveClassification=="Continuity","annotation persists explicit "+scope+" scope and classification");
|
||||
var retry=await review.Save(user,request);Check(row.ID==retry.ID,"annotation create retry is idempotent");request.Version=row.Version;request.Classification="Revision needed";request.Status="Dismissed";request.Observation="Reconsidered";var updated=await review.Save(user,request);Check(updated.Status=="Dismissed"&&updated.EffectiveClassification=="Revision needed"&&updated.StartParagraph==row.StartParagraph,"classification/status editing preserves accepted anchor");
|
||||
await Reject(()=>review.Save(rows.Other,new(){BookID=book,ChapterID=rows.ChapterID,ID=row.ID,Version=updated.Version,Observation="Foreign write",Classification="Plot"}),"another author cannot modify annotations");
|
||||
}
|
||||
await Reject(()=>review.Save(user,new(){BookID=book,ChapterID=rows.ChapterID,ID=Guid.NewGuid(),ContentVersion=accepted!.ContentVersion,Scope="Scene",SceneID=999999,Observation="Invented scene"}),"unverified scene association refused");
|
||||
await Reject(()=>review.Save(user,new(){BookID=book,ChapterID=rows.ChapterID,ID=Guid.NewGuid(),ContentVersion=accepted!.ContentVersion,Scope="Passage",StartParagraph=Guid.NewGuid(),EndParagraph=Guid.NewGuid(),StartOffset=0,EndOffset=1,Observation="Foreign anchor"}),"unknown paragraph anchor refused");
|
||||
var after=await paragraphs.Get(user,book);Check(after!.Revision==accepted!.Revision&&after.Paragraphs.Single().Occurrence.Id==paragraph&&after.Paragraphs.Single().Occurrence.Text==text,"planner and annotations preserve canonical text, revision, paragraph and scene identity");
|
||||
}
|
||||
}
|
||||
11
PlotLine.Tests/WriterPhase21Tests.cs
Normal file
11
PlotLine.Tests/WriterPhase21Tests.cs
Normal file
@ -0,0 +1,11 @@
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
internal static class WriterPhase21Tests
|
||||
{
|
||||
public static void Run(){void Check(bool ok,string why){if(!ok)throw new Exception(why);}var presence=new NativePresenceStore(TimeProvider.System);var instance=Guid.NewGuid();var session=Guid.NewGuid();var manuscript=Guid.NewGuid();long sequence=0;
|
||||
NativePresence Value(Guid? ack=null,string result="")=>new(){BookId=12,ManuscriptId=manuscript,Revision=3,Sequence=++sequence,WordAvailable=true,WordSaved=true,CanAcknowledgeNavigation=true,NavigationAcknowledgedId=ack,NavigationResult=result};
|
||||
void Put(Guid? ack=null,string result="")=>Check(presence.Put(4,"grant",DateTimeOffset.UtcNow.AddHours(1),instance,session,Value(ack,result)),"presence accepted");Put();
|
||||
for(var n=0;n<3;n++){var id=Guid.NewGuid();Check(presence.Navigate(4,12,instance,session,manuscript,3,n*10,true,id,true),"fresh repeated request queues");Check(presence.NavigationState(4,12,instance,session,id)=="requested","queuing is not completion");Check(presence.TakeNavigation(4,"grant",instance,session)?.Id==id,"exact current command delivered");Check(presence.TakeNavigation(4,"grant",instance,session)==null,"command delivery is not duplicated");Put(id,"completed");Check(presence.NavigationState(4,12,instance,session,id)=="completed","matching acknowledgement completes request");}
|
||||
var next=Guid.NewGuid();Check(presence.Navigate(4,12,instance,session,manuscript,3,99,true,next,true),"next command accepted");Put(Guid.NewGuid(),"completed");Check(presence.NavigationState(4,12,instance,session,next)=="requested","stale unrelated acknowledgement cannot complete newer navigation");var changed=Value();changed.BookId=13;presence.Put(4,"grant",DateTimeOffset.UtcNow.AddHours(1),instance,session,changed);Check(presence.NavigationState(4,12,instance,session,next)=="invalidated","book switch invalidates pending target");Check(presence.TakeNavigation(4,"grant",instance,session)==null,"stale queued navigation cannot cross books");
|
||||
}
|
||||
}
|
||||
@ -5,6 +5,6 @@ internal sealed class WriterReviewFixture(ManuscriptReaderService reader,IWriter
|
||||
{
|
||||
private static readonly object gate=new();private static readonly Dictionary<Guid,ReviewObservation> rows=[];
|
||||
public async Task<ReviewPanel> 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<ReviewObservation> 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;}}
|
||||
public async Task<ReviewObservation> 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=r.Scope=="Scene"?r.SceneID:anchors.FirstOrDefault()?.SceneID,Scope=string.IsNullOrEmpty(r.Scope)?null:r.Scope,Classification=r.Classification,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.Classification=r.Classification;saved.Version++;saved.UpdatedUtc=DateTime.UtcNow;return saved;}}
|
||||
}
|
||||
|
||||
@ -20,7 +20,7 @@ internal static class WriterWordTests
|
||||
// Exercise actual authorised chapter/scene resolver with procedure proxies: any unexpected call fails.
|
||||
store.Remove(7,"grant",instance,session);Put(State());var heading=Guid.NewGuid();var scene=Guid.NewGuid();var snapshot=new ParagraphManuscript{BookId=12,ManuscriptId=manuscript,SessionId=session,WordRevision=2,Revision=5,Chapters=[new(){CanonicalId=21,HeadingId=heading}],Scenes=[new(){Id=scene,CanonicalId=31,ChapterId=21}],Paragraphs=[new(){PositionVerified=true,Occurrence=new(){Id=heading,Start=0}},new(){PositionVerified=true,Story=true,SceneId=scene,Occurrence=new(){Id=Guid.NewGuid(),Start=100,Ordinal=1}}]};
|
||||
var access=NativeWorkflowTests.Proxy<IWordCompanionRepository>((n,a)=>n=="GetBookStructureAsync"?Task.FromResult<WordCompanionBookStructureResponse?>(new(){BookId=12,Chapters=[new(){ChapterId=21,Scenes=[new(){SceneId=31}]}]}):throw new Exception(n));
|
||||
var repo=NativeWorkflowTests.Proxy<IParagraphManuscriptRepository>((n,a)=>n switch{"Get"=>Task.FromResult<ParagraphManuscript?>(snapshot),"Position"=>Task.FromResult<ParagraphPosition?>(new(){HasSnapshot=true,Revision=5,ChapterID=21,SceneID=(int)a![5]! ==100?31:null}),_=>throw new Exception(n)});
|
||||
var repo=NativeWorkflowTests.Proxy<IParagraphManuscriptRepository>((n,a)=>n switch{"Get"=>Task.FromResult<ParagraphManuscript?>(snapshot),"Status"=>Task.FromResult<ParagraphSyncStatus?>(new(){ManuscriptId=snapshot.ManuscriptId,Revision=snapshot.Revision}),"Position"=>Task.FromResult<ParagraphPosition?>(new(){HasSnapshot=true,Revision=5,ChapterID=21,SceneID=(int)a![5]! ==100?31:null}),_=>throw new Exception(n)});
|
||||
var checkpoints=NativeWorkflowTests.Proxy<IChapterSyncRepository>((n,a)=>throw new Exception("unexpected checkpoint operation "+n));var service=new WriterWordService(null!,access,repo,checkpoints,store);
|
||||
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);
|
||||
|
||||
@ -21,7 +21,7 @@ public sealed class WriterActivitiesController(WriterActivityRepository activiti
|
||||
if(row.EntityID.HasValue&&row.EntityTitle==null)return Conflict(new{message="The linked entity is unavailable. Edit the activity to select another."});
|
||||
var book=await books.GetAsync(bookId);if(book==null)return NotFound();
|
||||
if(row.ChapterID.HasValue)await objectives.Save(Actor,new(){BookID=bookId,ChapterID=row.ChapterID,SceneID=row.SceneID,Activity=row.Kind is "Editing" or "Review" or "AudioReview"?"Revising":row.Kind=="Research"?"Researching":"Drafting",Intention=row.Title});
|
||||
return row.Kind is "Review" or "AudioReview"?RedirectToAction("Review","Writer",new{bookId,chapterId=row.ChapterID}):row.EntityKind=="Character"?RedirectToAction("Edit","Characters",new{id=row.EntityID}):row.EntityKind=="Location"?RedirectToAction("Edit","Locations",new{id=row.EntityID}):row.EntityKind is "PlotLine" or "Thread"||row.Kind=="Plot"?RedirectToAction("Index","PlotLineWorkspace",new{projectId=book.ProjectID,bookId}):RedirectToAction("Write","Writer",new{bookId});
|
||||
return row.Kind is "Review" or "AudioReview"?RedirectToAction("Review","Writer",new{bookId,chapterId=row.ChapterID}):row.Kind=="Character"&&row.EntityKind!="Character"?RedirectToAction("Index","Characters",new{projectId=book.ProjectID,bookId}):row.EntityKind=="Character"?RedirectToAction("Edit","Characters",new{id=row.EntityID}):row.EntityKind=="Location"?RedirectToAction("Edit","Locations",new{id=row.EntityID}):row.EntityKind is "PlotLine" or "Thread"||row.Kind=="Plot"?RedirectToAction("Index","PlotLineWorkspace",new{projectId=book.ProjectID,bookId}):RedirectToAction("Write","Writer",new{bookId});
|
||||
});
|
||||
async Task<IActionResult> Guard(Func<Task<IActionResult>> action){Response.Headers.CacheControl="no-store";try{return await action();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number is 51000 or 51002){return StatusCode(e.Number==51002?409:404,new{message="The activity or book is unavailable or changed. Your entered text is retained; reload before retrying."});}}
|
||||
}
|
||||
|
||||
@ -21,7 +21,7 @@ public sealed class WriterWordService(ISqlConnectionFactory factory,IWordCompani
|
||||
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;
|
||||
ParagraphManuscript? state;
|
||||
if(!scene.HasValue&&!paragraphId.HasValue&&lease.Position.CanChapterSync){var meta=await Metadata(user,book,chapter);state=meta==null?null:new(){ManuscriptId=meta.ManuscriptID,Revision=meta.Revision};}
|
||||
if(!scene.HasValue&&!paragraphId.HasValue&&lease.Position.CanChapterSync){var meta=await paragraphs.Status(user,book);state=meta==null?null:new(){ManuscriptId=meta.ManuscriptId,Revision=meta.Revision};}
|
||||
else state=await Accepted(user,book);
|
||||
if(state==null||state.ManuscriptId!=manuscript)return false;
|
||||
int? start=null;
|
||||
|
||||
@ -3,9 +3,10 @@
|
||||
<section class="writer3-panel writer3-main">
|
||||
<h2>Planned activities</h2><p>What you intend to accomplish. Starting work is separate from recording a session.</p>
|
||||
<div data-activity-planner data-book="@Model.BookID" data-url="@Url.Action("Panel","WriterActivities",new{bookId=Model.BookID})"><p>Loading your activities…</p></div>
|
||||
<section data-planner-schedule-existing hidden>
|
||||
@if(Model.PlannedActivities.Count>0){<h3>Scheduled writing activities</h3><ol class="writer2-activities">@foreach(var item in Model.PlannedActivities.Take(12)){<li><time>@item.ScheduledDate.ToString("ddd d MMM")</time><strong>@item.Kind · @item.Title</strong><span>@item.Status · @item.Minutes planned minutes</span>@if(item.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">Work on this scene</a>}else{<a asp-action="Chapter" asp-route-id="@item.ChapterID">Work on this chapter</a>}</li>}</ol>}
|
||||
else{<h3>Writing time ahead</h3><partial name="_WriterUpcoming" model="Model" />}
|
||||
<details class="writer3-inset"><summary>Schedule and completed work</summary><p>@Model.WritingSchedule.CompletedTasks completed · @Model.WritingSchedule.SkippedTasks skipped · @Model.WritingSchedule.RemainingTasks outstanding scheduled tasks. These are recorded task states, not measured manuscript progress.</p>
|
||||
<div class="button-row"><a asp-action="SchedulePreview" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">View and adjust your schedule</a><a asp-action="WritingPlans" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">Existing plans and activity completion</a><a asp-action="ScheduleSetup" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">@(Model.WritingSchedule.HasActivePlans?"Create another writing plan":"Create a writing schedule")</a></div></details>
|
||||
</section>
|
||||
</section></section>
|
||||
</div>
|
||||
|
||||
@ -16,11 +16,11 @@
|
||||
form.querySelector('[data-authoring-cancel]').addEventListener('click',()=>{if(form.dataset.busy==='true')return;form.reset();card.querySelector('[data-authoring-status]').textContent='';form.dataset.dirty='false';form.hidden=true;display.hidden=false;edit.hidden=false;edit.setAttribute('aria-expanded','false');error.hidden=true;edit.focus();});
|
||||
form.querySelector('[data-authoring-reload]').addEventListener('click',async()=>{if(!confirm('Reload the recorded version? Copy any text you want to keep first.'))return;try{const doc=await read();replaceCard(card,doc);}catch{error.textContent='Could not reload. Your text is still here.';}});
|
||||
card.querySelector('[data-checklist-toggle]')?.addEventListener('change',async event=>{
|
||||
const box=event.target;if(form.dataset.busy==='true'){box.checked=!box.checked;return;}const prior=!box.checked;box.disabled=true;form.dataset.busy='true';
|
||||
const box=event.target;if(form.dataset.busy==='true'){box.checked=!box.checked;return;}const prior=!box.checked;box.disabled=true;edit.disabled=true;form.dataset.busy='true';
|
||||
const data=new FormData(form);for(const input of form.querySelectorAll('input[type=checkbox]'))data.set(input.name,String(input.name==='IsCompleted'?box.checked:input.checked));
|
||||
try{const response=await fetch(form.action,{method:'POST',body:data});if(!response.ok)throw Error();const doc=await read();replaceCard(card,doc);}
|
||||
catch{box.checked=prior;card.querySelector('[data-authoring-status]').textContent='Completion could not be refreshed. Reload the recorded version before retrying.';box.disabled=true;form.querySelector('[data-authoring-reload]').hidden=false;}
|
||||
finally{form.dataset.busy='false';}
|
||||
finally{form.dataset.busy='false';edit.disabled=false;}
|
||||
});
|
||||
form.addEventListener('submit',async e=>{
|
||||
e.preventDefault();if(form.dataset.busy==='true')return;form.dataset.busy='true';const save=form.querySelector('[data-authoring-save]'),cancel=form.querySelector('[data-authoring-cancel]'),reload=form.querySelector('[data-authoring-reload]');let committed=false;save.disabled=true;cancel.disabled=true;reload.disabled=true;error.hidden=true;
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
(()=>{const root=document.querySelector('[data-activity-planner]');if(!root)return;let view=new URLSearchParams(location.search).get('view')||'list',busy=false,dirty=false,allow=false;
|
||||
async function load(){const url=new URL(root.dataset.url,location.href);url.searchParams.set('view',view);const r=await fetch(url,{cache:'no-store'});if(!r.ok)throw Error('The planner could not load. Reload when connected.');const doc=new DOMParser().parseFromString(await r.text(),'text/html'),panel=doc.querySelector('[data-planner-view]');if(!panel)throw Error('Sign in to resume your planner.');root.replaceChildren(panel);dirty=false;}
|
||||
async function load(){const url=new URL(root.dataset.url,location.href);url.searchParams.set('view',view);const r=await fetch(url,{cache:'no-store'});if(!r.ok)throw Error('The planner could not load. Reload when connected.');const doc=new DOMParser().parseFromString(await r.text(),'text/html'),panel=doc.querySelector('[data-planner-view]');if(!panel)throw Error('Sign in to resume your planner.');root.replaceChildren(panel);const schedule=document.querySelector('[data-planner-schedule-existing]');if(schedule)schedule.hidden=view!=='schedule';dirty=false;}
|
||||
root.addEventListener('input',()=>dirty=true);
|
||||
root.addEventListener('click',async event=>{const tab=event.target.closest('[data-planner-tab]');if(!tab||busy)return;if(dirty&&!confirm('Leave unsaved activity edits?'))return;view=tab.dataset.plannerTab;try{await load();}catch(e){root.querySelector('[data-planner-message]').textContent=e.message;}});
|
||||
root.addEventListener('submit',async event=>{const form=event.target;if(form.matches('[data-activity-start]')){if(form.dataset.pending==='true'||dirty&&!confirm('Leave unsaved activity edits and start this work?')){event.preventDefault();return;}form.dataset.pending='true';allow=true;return;}if(!form.matches('[data-activity-change],[data-activity-save]'))return;event.preventDefault();if(busy)return;busy=true;const button=event.submitter;button.disabled=true;let committed=false;const message=form.querySelector('[data-activity-error]')||root.querySelector('[data-planner-message]');message.textContent='Saving…';try{const r=await fetch(form.action,{method:'POST',body:new FormData(form)});if(!r.ok){const data=await r.json().catch(()=>null);throw Error(data?.message||'Save not confirmed. Your text is retained. Reload before retrying.');}committed=true;dirty=false;await load();}catch(e){message.textContent=committed?'Saved, but the refreshed planner could not load. Reload the page before making another change.':e.message;}finally{busy=false;button.disabled=committed&&form.isConnected;}});
|
||||
|
||||
@ -7,12 +7,12 @@ const nodeParagraph=n=>(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.close
|
||||
function capture(){const s=getSelection();if(!s||s.isCollapsed||s.rangeCount!==1)return null;const r=s.getRangeAt(0),first=nodeParagraph(r.startContainer),last=nodeParagraph(r.endContainer);if(!first||!last||!readerContent.contains(first)||!readerContent.contains(last))return null;const before=document.createRange();before.selectNodeContents(first);before.setEnd(r.startContainer,r.startOffset);const after=document.createRange();after.selectNodeContents(last);after.setEnd(r.endContainer,r.endOffset);return{StartParagraph:first.dataset.paragraphId,EndParagraph:last.dataset.paragraphId,StartOffset:before.toString().length,EndOffset:after.toString().length};}
|
||||
function wordReference(id){if(!word)return;word.dataset.paragraphId=id||'';word.dataset.acceptedRevision=reader.dataset.revision;window.dispatchEvent(new Event('review-reference-changed'));}
|
||||
function queueContext(){clearTimeout(selectionTimer);selectionTimer=setTimeout(()=>void load(false),180);}
|
||||
async function load(force=true){if(editorial.querySelector('[data-authoring-form][data-dirty="true"]')){message.textContent="Save or Cancel your chapter/scene note editor before changing review context.";return;}clearTimeout(selectionTimer);const key=[selected,anchor?.EndParagraph,reader.dataset.version,page].join(':');if(!force&&key===lastContext)return;const mine=++generation;controller?.abort();controller=new AbortController();loading=true;const url=new URL(root.dataset.panelUrl,location.href);url.search=new URLSearchParams({bookId:root.dataset.book,chapterId:root.dataset.chapter,version:reader.dataset.version,page:String(page),...(selected?{paragraphId:selected,endParagraphId:anchor?.EndParagraph||selected}:{})});try{const response=await fetch(url,{cache:'no-store',signal:controller.signal});if(!response.ok)throw Error();const doc=new DOMParser().parseFromString(await response.text(),'text/html'),panel=doc.querySelector('[data-review-panel]');if(!panel)throw Error();if(mine===generation){context.replaceChildren(panel);const slot=document.querySelector('[data-review-intentions-slot]');if(slot&&panel.querySelector('[data-review-intentions]'))slot.replaceChildren(panel.querySelector('[data-review-intentions]'));
|
||||
async function load(force=true){if(editorial.querySelector('[data-authoring-form][data-dirty="true"]')){message.textContent="Save or Cancel your chapter/scene note editor before changing review context.";return;}clearTimeout(selectionTimer);const key=[selected,anchor?.EndParagraph,reader.dataset.version,page].join(':');if(!force&&key===lastContext)return;const preserve=reader.readerPreserveView?.();const mine=++generation;controller?.abort();controller=new AbortController();loading=true;const url=new URL(root.dataset.panelUrl,location.href);url.search=new URLSearchParams({bookId:root.dataset.book,chapterId:root.dataset.chapter,version:reader.dataset.version,page:String(page),...(selected?{paragraphId:selected,endParagraphId:anchor?.EndParagraph||selected}:{})});try{const response=await fetch(url,{cache:'no-store',signal:controller.signal});if(!response.ok)throw Error();const doc=new DOMParser().parseFromString(await response.text(),'text/html'),panel=doc.querySelector('[data-review-panel]');if(!panel)throw Error();if(mine===generation){context.replaceChildren(panel);const slot=document.querySelector('[data-review-intentions-slot]');if(slot&&panel.querySelector('[data-review-intentions]'))slot.replaceChildren(panel.querySelector('[data-review-intentions]'));
|
||||
const sceneSlot=document.querySelector('[data-review-scene-context]');if(sceneSlot)sceneSlot.replaceChildren(panel.querySelector('[data-review-scene-intentions]'));
|
||||
const chapterAnnotations=document.querySelector('[data-chapter-annotations]');if(chapterAnnotations){chapterAnnotations.replaceChildren();for(const note of panel.querySelectorAll('[data-observation][data-scope="Chapter"]'))chapterAnnotations.append(note);}
|
||||
const sceneID=panel.dataset.selectedScene||'';if(word){word.dataset.sceneId=sceneID;window.dispatchEvent(new Event('review-reference-changed'));}
|
||||
for(const note of panel.querySelectorAll('[data-observation]'))if(note.dataset.scope==='Scene')note.hidden=note.dataset.scene!==sceneID;
|
||||
window.dispatchEvent(new Event('review:context-loaded'));lastContext=key;}}catch(e){if(e.name!=='AbortError'&&mine===generation){message.textContent='Recorded review information could not load. Your observation text is retained.';}}finally{if(mine===generation)loading=false;}}
|
||||
window.dispatchEvent(new Event('review:context-loaded'));lastContext=key;requestAnimationFrame(()=>preserve?.());}}catch(e){if(e.name!=='AbortError'&&mine===generation){message.textContent='Recorded review information could not load. Your observation text is retained.';}}finally{if(mine===generation)loading=false;}}
|
||||
function pause(enabled){const input=reader.querySelector('#reader-pause');if(enabled){pauseBefore=input.checked;input.checked=true;}else input.checked=pauseBefore;input.dispatchEvent(new Event('change'));}
|
||||
function showEditor(){if(reader.dataset.focus==='true'){const restore=reader.readerPreserveView?.();reader.querySelector('#reader-focus').click();restore?.();}const aside=root.closest('.writer21-notes')||root.closest('.writer3-reference');if(aside?.hidden)document.querySelector('[data-editorial-toggle=review-scene-notes]')?.click();form.hidden=false;newButton.hidden=true;field('Observation').focus();}
|
||||
function begin(){if(busy)return;if(dirty){field('Observation').focus();return;}anchor=capture()||anchor;selected=anchor?.StartParagraph||null;wordReference(selected);void load();field('ID').value=crypto.randomUUID();field('Version').value='0';field('ContentVersion').value=reader.dataset.version;for(const n of['StartParagraph','EndParagraph','StartOffset','EndOffset'])field(n).value=anchor?.[n]??'';field('Observation').value='';field('Decision').value='';field('Status').value='Open';field('Scope').disabled=false;field('Scope').value=anchor?'Passage':'Chapter';field('Classification').value='Observation';field('SceneID').value=document.querySelector('[data-review-panel]')?.dataset.selectedScene||'';error.hidden=true;pause(true);dirty=true;reference.textContent=anchor?'Observation linked to the selected accepted paragraph(s).':'Chapter-level observation; no exact passage is claimed.';showEditor();}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user