Deliver grounded Writer guidance, work rhythm, reviewed schedules and Audio Review server foundation

This commit is contained in:
Nick Beckley 2026-11-15 17:08:32 +00:00
parent fe8c6d8f04
commit 6bc42036e4
42 changed files with 1147 additions and 36 deletions

View File

@ -0,0 +1,54 @@
# Audio Review v1: Atlas / Windows handoff
Status: PlotDirector server/UI and optional shared DTOs only. No Windows GSMTC control, Word text-change detection, ElevenReader integration or native installer is implemented by this sprint. Existing agents remain compatible and media controls remain disabled until valid telemetry advertises operations.
## Shared transport and security
Use the existing authenticated HTTPS client, installation grants, normal bearer refresh/revocation and native document presence. Do not introduce a public local web server, unauthenticated named pipe, arbitrary executable/URL operation or second pairing system. Keep protocol v1 required capabilities unchanged. The shared optional DTOs are `PlotDirector.NativeCompanion/Protocol/AudioReview.cs`; they do not activate any native operation or change local pipe framing.
POST `/api/native-companion/instances/{instance}/documents/{document}/audio-review` with the existing DesktopPairing bearer token. The instance/document must have a live, matching native presence lease for the same actor, grant and book. Server also checks current project/book ownership. Request size is bounded to 4 KiB. Read/control browser routes use normal cookie authentication and antiforgery. For Reader-only listening, Windows may register a media-only context through the existing native presence endpoint with an opaque nonempty instance/session, the explicitly selected book, `wordAvailable: false` and `wordRunning: false`. Existing book authorization and lease expiry still apply; it must not claim a Word manuscript/position. The author then starts/restarts review to bind this context.
The author explicitly starts an Audio Review for a chapter in Writer or Reader. If there is exactly one native session for the book (or exactly one active session), server binds that exact instance/session/grant to the review. A session may represent Word or an explicitly registered media-only review context. An ambiguous or absent document produces an unbound session: elapsed duration can be recorded, but controls and observed playback remain unavailable. End and restart after registering/selecting the native book session; server never silently retargets an existing review.
## Discovery and observations
Poll using `version: 1`, the selected `bookID`, positive monotonically increasing `sequence`, `reviewID: null`, `state: "unavailable"`, and no operations. The reply supplies the active bound `reviewID`, `chapterID` and `pauseOnEdit`, or a null review ID when none matches. Once associated, POST observations with that review ID. A different review ID is refused.
Fields follow ASP.NET's camel-case JSON naming, e.g. `reviewID`, `bookID`, `mediaKey`, `positionSeconds`, `durationSeconds`, `playbackRate`, `operations`, `acknowledgedCommandID`, `textModified`, `seeked`. Set `seeked` only for an observed seek event or successfully applied seek command, never merely because telemetry has a gap. Missing positions/duration remain null. State is one of `playing`, `paused`, `stopped`, `unavailable`, `error`. Operations are a subset of `play`, `pause`, `back15`, `forward15`. Times are finite seconds, bounded to a 24-hour media source; rates are 0.25–4. Sequence is scoped to the review, independent of Word revision/presence sequence. Send every 2–5 seconds while reviewing, plus state/seek/text-change observations. Do not replay a disconnected backlog as if it were current playback.
`mediaKey` is an opaque identifier (at most 100 characters) for the explicitly selected media source. Do not send a browser URL, local path, credentials or media content. Position/duration unavailable is a valid state. The UI expires telemetry after 45 seconds and also requires a live native lease. The agent must report unavailable when discovery fails.
Chrome/GSMTC may expose its most recently active source rather than independent tabs. If that source changes, stop control, report unavailable and require explicit end/restart. Once established, the review's nonempty media key is immutable. Server refuses a different source rather than merging its coverage into the first. Play state is evidence of playback, not proof of attention or alignment to manuscript text.
## Commands and acknowledgements
Browser controls request only `play`, `pause`, `back15`, `forward15`, only when a fresh telemetry capability and matching lease exist. Server creates a command UUID; reply includes `commandID`, `command`, `relativeSeconds` (-15/+15 for seek), the expected `mediaKey` and `expiresUtc` (ten seconds). There is one pending command slot per review; newer explicit intent supersedes an older slot.
Before acting, Windows must verify instance/document/review association, current selected media key, capability, expiry and command UUID. Deduplicate UUIDs locally; repeat polling is delivery retry, not permission to repeat a seek. Acknowledge using `acknowledgedCommandID` and report actual resulting state/position. Never claim success merely because the OS call was queued. Report bounded error text for diagnostics; server displays a generic failure rather than retaining OS/source details. The agent should preserve terminal command receipts long enough to handle acknowledgement loss. An expired command is ignored and acknowledged as an error; it must never run later after reconnection.
These are narrowly scoped commands for the user's selected media source. They do not permit remote shell/OS control, opening URLs, choosing arbitrary browser tabs or manipulating Word content.
## Pause on Edit
Consume `pauseOnEdit` from the bound review. Detect **actual Word text modification**, not selection, cursor movement, scrolling, browser activity or a document staying open. Perform local Pause immediately when supported, then report `textModified: true` on the corresponding new observation. The server also requests a bounded Pause if a mutation is reported while still playing and pause capability is available; repeated observations retain the pending Pause UUID. Never automatically Play after an idle/typing timeout. Only an explicit author Play resumes.
The preference is recorded with each review; the latest review preference supplies the next session default. Older agents advertise nothing and do nothing. No current installation should be updated until Windows qualification/packaging is complete.
## Accounting and privacy
`WriterWorkSessions` stores compact session metadata, notes and a union of observed audio intervals. It is not canonical prose storage. Native telemetry sequence is monotonic and locked transactionally; exact/older retries do not add measurements. Gross word additions/deletions continue to come solely from the existing accepted-change ledger.
Only consecutive same-key, same-rate **playing** samples no more than 30 seconds apart establish playback. Position jumps, gaps, pauses, changed rate/source and duplicate sequence do not manufacture intervals. Playback seconds are bounded by receipt-time elapsed and position advance / rate. Unique coverage is the union of position ranges, so replay can increase playback time without increasing unique seconds. At 4,096 disjoint ranges, coverage remains an explicit partial lower bound rather than growing without limit. End-state tails and missing telemetry are conservatively unmeasured.
Explicit browser sessions measure visible, recently interacted browser engagement separately from elapsed time. They do not measure Word active time. Browser engagement and playback may overlap; UI never sums them into inflated active time. Calendar intervals are attributed to UTC receipt day, including an interval received just after midnight. Native capture/session clocks do not backfill earlier history. Explicit sessions expire after twelve hours; the author starts another session to continue.
Start/end checkpoints reference the accepted book revision and paragraph count. Journey can associate retained accepted changes and changed paragraph identities with the review's time interval and selected chapter, without claiming playback caused the changes. Gross counts shown for such an interval are labelled book-wide, not arbitrarily allocated to chapters. Notes are explicit author-entered text. Normal recording pause, retention and confirmed history erase also cover work/review sessions; account/book deletion cascades new records. Exports/backups remain separate copies.
## Required Windows acceptance
1. Implement optional HTTPS polling/DTO handling using the existing authenticated client; keep required local protocol and old agents compatible.
2. Implement current-user GSMTC media discovery, capability/state/position reporting and explicit media-key selection. Handle Chrome source changes conservatively.
3. Implement bounded Play/Pause/relative ±15-second seek, expiry checks and durable UUID deduplication/acknowledgements.
4. Implement actual Word mutation detection on the established UI/worker boundary. No blocking media/network call on Word callbacks; no pause for scrolling/selection; no auto-resume.
5. Qualify Word foreground/background, Chrome background, pause/seek/replay, multiple media sources/documents, token refresh/revocation, disconnect/reconnect, agent restart, stale command/ack loss, Windows/PWA and real monitors as appropriate.
6. Package/version/sign and distribute only after those tests. Atlas qualification does not establish physical Windows acceptance.

View File

@ -0,0 +1,23 @@
# Deferred audiobook-production architecture
Architecture only. No audiobook schema, API call, credential storage or background worker is introduced here. Audio Review is a separate listening/review feature and does not generate or approve audiobook audio.
## Future author workflow
Chapters may be explicitly marked Ready for Audio. Audio Generated and Audio Approved remain separate states. A changed manuscript invalidates affected generated audio and requires review; readiness is not proof of publication suitability. Final assembly, pronunciation/voice continuity, mastering and publication checks are distinct stages.
Use the author's existing ElevenLabs subscription credits after explicit account connection in a future authorised implementation. Background generation is permitted only from available credits **above** a configurable reserve; the requested default reserve is **100,000 credits**. For example, a 120,000 balance permits at most 20,000 credits of authorised background work, subject to a fresh verified balance and the provider's actual charging rules. A balance at/below the reserve schedules no automatic generation. Do not promise prices, API limits or credit calculations until official provider contracts are verified during that implementation.
A future Finish Audiobook command may use remaining subscription credits. Paid overage is a separate action requiring explicit user approval, a visible estimate and a hard spending cap. Failed/retried requests must never become implicit approval to exceed the cap.
## Stable cache and invalidation
Use the existing canonical manuscript identity and stable paragraph occurrence GUIDs. A generation key includes manuscript identity, paragraph GUID, normalized text hash, voice identity/version and complete generation settings/model version. Text changes invalidate that paragraph's cached audio; ordering changes can reuse unchanged eligible chunks. Hash equality alone must not merge separate author/book contexts or expose another author's audio. Voice/settings changes invalidate the relevant key. Maintain source revision/provenance so approval is tied to exact audio and text.
Generation is a resumable state machine with a durable intent/job ID, provider idempotency where available, charge reservation, submission receipt, reconciliation and completed artifact. Persist the provider request/charge identity before retry decisions. After timeout, reconcile the provider outcome before issuing a potentially billable duplicate. A per-user/account budget lock and reservation ledger prevent concurrent workers consuming the same above-reserve credits. Unknown balances/costs fail closed for background billing. An explicit spending cap is enforced across retries and concurrent work, not merely checked once in the UI.
Audio artifacts are private, content-addressed within authorised scope, and stored separately from canonical prose. Restore/export, retention, deletion, provider copies, consent, license rights and generated-voice privacy require explicit future policy. The Writer working objective, accepted activity history and paragraph identities remain the shared foundation; the new review-session table is not a billing ledger or generation queue.
## Integration boundaries
Future author-approved readiness/approval commands belong alongside chapter workflows and Writer. A future audio-generation service consumes accepted checkpoints asynchronously; it never rewrites canonical manuscript synchronisation or infers author approval from playback. Review sessions may later reference an approved generated artifact, but external media review continues to work independently. Do not couple the current media-control contract to any provider URL, credentials or paid API.

View File

@ -0,0 +1,34 @@
using System;
namespace PlotDirector.Companion.Protocol;
// Optional HTTPS contract. No Windows implementation or new required pipe capability.
public sealed class AudioReviewObservation
{
public int Version { get; set; } = 1;
public Guid? ReviewID { get; set; }
public int BookID { get; set; }
public long Sequence { get; set; }
public string State { get; set; } = "unavailable";
public string MediaKey { get; set; } = "";
public double? PositionSeconds { get; set; }
public double? DurationSeconds { get; set; }
public double PlaybackRate { get; set; } = 1;
public string[] Operations { get; set; } = [];
public Guid? AcknowledgedCommandID { get; set; }
public string? Error { get; set; }
// True only for actual text mutation, never cursor/selection/scroll activity.
public bool TextModified { get; set; }
// An actual player seek event or successfully applied seek command, not a telemetry gap.
public bool Seeked { get; set; }
}
public sealed class AudioReviewReply
{
public int Version { get; set; } = 1;
public Guid? ReviewID { get; set; }
public int? ChapterID { get; set; }
public bool PauseOnEdit { get; set; }
public Guid? CommandID { get; set; }
public string? Command { get; set; }
public int? RelativeSeconds { get; set; }
public string? MediaKey { get; set; }
public DateTime? ExpiresUtc { get; set; }
}

View File

@ -0,0 +1,61 @@
// Explicit authenticated Development acceptance. Only a disposable account/owned fixture.
const {chromium}=require('playwright');
const fs=require('node:fs');
const assert=require('node:assert/strict');
let privatePassword='';
(async()=>{
const identityPath=process.env.PD_WRITER_IDENTITY,scopePath=process.env.PD_WRITER_SCOPE,output=process.env.PD_WRITER_SCREENSHOTS;
assert(identityPath?.startsWith('/tmp/pd-dev-browser-writer2-')&&scopePath&&output);
const who=JSON.parse(fs.readFileSync(identityPath)),scope=JSON.parse(fs.readFileSync(scopePath));privatePassword=who.Password;
assert(who.Database==='PlotDirector_Development'&&/^pwa-browser-.*@example\.invalid$/.test(who.Email));
for(const key of ['project','book','chapter','scene','other','secondChapter'])assert(Number.isSafeInteger(scope[key])&&scope[key]>0);
const base='https://dev.plotdirector.com',url=book=>`${base}/Writer?projectId=${scope.project}&bookId=${book}`;
const browser=await chromium.launch();
try{for(const pwa of [false,true]){
const context=await browser.newContext({viewport:{width:1440,height:1000}});if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
const page=await context.newPage(),failed=[];
page.on('response',r=>{if(r.request().isNavigationRequest()&&r.request().frame()===page.mainFrame()&&r.status()>=400)failed.push(r.status()+' '+new URL(r.url()).pathname);});
await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(who.Email);await page.locator('[name=Password]').fill(who.Password);await Promise.all([page.waitForURL('**/Projects'),page.locator('button[type=submit]').click()]);
await page.goto(url(scope.book));
await page.getByRole('button',{name:'Help Me',exact:true}).click();assert.equal(await page.locator('#writer-help-options').isVisible(),true);
if(!pwa)await page.screenshot({path:output+'/Overview-Help-Live.png',fullPage:true});
await page.getByRole('link',{name:'Read or start Audio Review',exact:true}).click();await page.waitForURL('**/manuscript/reader?*');assert((await page.locator('#reader-content').textContent()).includes('A small boat crossed the harbour.'));
await page.getByRole('link',{name:'Return to Writing',exact:true}).click();await page.waitForURL('**/Writer?*');
if(!pwa){
await page.getByRole('link',{name:/Continue an existing manuscript/}).click();await page.locator('[name=Activity]').selectOption('Revising');await page.locator('[data-objective-chapter]').selectOption(String(scope.chapter));await page.locator('[data-objective-scene]').selectOption(String(scope.scene));
await Promise.all([page.waitForURL(`**/Writer?bookId=${scope.book}`),page.getByRole('button',{name:'Save objective · start without a schedule'}).click()]);
}
assert.equal(await page.getByRole('heading',{name:'Continue Writing',exact:true}).isVisible(),true);
const toolbar=page.locator('[data-writer-work]');
await toolbar.locator('[name=kind]').selectOption('Reading');await toolbar.locator('[name=chapterId]').selectOption(String(scope.chapter));await toolbar.getByRole('button',{name:'Start session',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('[data-work-current]').hidden);
await toolbar.locator('[data-work-note]').fill('Review the arrival objective next');await toolbar.locator('[data-work-end]').click();await page.waitForFunction(()=>document.querySelector('[data-work-current]').hidden);
await toolbar.locator('[name=kind]').selectOption('AudioReview');await toolbar.getByRole('button',{name:'Start Audio Review',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('[data-work-audio]').hidden);
for(const button of await toolbar.locator('[data-media-command]').all())assert.equal(await button.isDisabled(),true);
assert((await toolbar.locator('[data-audio-state]').textContent()).includes('Updated Windows Companion'));
if(!pwa)await page.screenshot({path:output+'/Audio-Unavailable-Live.png',fullPage:true});
await toolbar.locator('[data-work-note]').fill('Audio controls require Windows qualification');await toolbar.locator('[data-work-end]').click();await page.waitForFunction(()=>document.querySelector('[data-work-current]').hidden);
const exported=await(await page.request.get(`${base}/Writer/Work/Export?bookId=${scope.book}`)).json();assert(exported.some(x=>x.kind==='Reading'&&x.note==='Review the arrival objective next'));assert(exported.filter(x=>x.kind==='AudioReview').every(x=>x.playbackSeconds===0&&x.uniqueSeconds===0));
if(!pwa){
await page.getByRole('link',{name:'Create a writing plan',exact:true}).click();await page.waitForURL('**/Writer/ScheduleSetup?*');assert.equal(await page.locator('[name=GoalType]').inputValue(),'Revision');assert.equal(await page.locator('[name=BookID]').inputValue(),String(scope.book));
await page.locator('[name=PlanName]').fill('Seventeen-hour revision availability');
const budget={Monday:240,Tuesday:240,Wednesday:240,Thursday:240,Friday:60};
for(const row of await page.locator('tbody tr').all()){const day=await row.locator('input[name$=".Day"]').inputValue();await row.locator('input[type=checkbox]').setChecked(Boolean(budget[day]));if(budget[day])await row.locator('select').selectOption(String(budget[day]));}
await Promise.all([page.waitForURL('**/Writer/PlanActivities?*'),page.getByRole('button',{name:'Review activities',exact:true}).click()]);
assert.equal(await page.locator('[name$=".Minutes"]').count(),2);await page.locator('[name="Candidates[0].Minutes"]').fill('45');await page.locator('[name="Candidates[1].Minutes"]').fill('90');await page.locator('[name=Confirm]').check();
await Promise.all([page.waitForURL('**/Writer/SchedulePreview?*'),page.getByRole('button',{name:'Commit reviewed schedule',exact:true}).click()]);
assert.equal(await page.getByRole('heading',{name:'Reviewed writing activities',exact:true}).isVisible(),true);assert((await page.locator('body').textContent()).includes('135 planned minutes'));assert.equal(await page.locator('.writer-kpi').count(),0);
await page.screenshot({path:output+'/Reviewed-Schedule-Live.png',fullPage:true});
await page.locator('form[action*="PlanActivities/Complete"] button').first().click();await page.waitForURL('**/Writer/SchedulePreview?*');assert((await page.locator('body').textContent()).includes('Done'));
await page.goto(url(scope.book));await page.locator('.writer-next-grid').getByRole('link',{name:'The harbour',exact:true}).click();await page.waitForURL(`**/Writer/Chapter/${scope.secondChapter}`);assert((await page.locator('body').textContent()).includes('The harbour'));
await page.goto(`${base}/Writer/ScheduleSetup?projectId=${scope.project}&bookId=${scope.book}`);await page.locator('[name=BookID]').selectOption('');await page.locator('[name=PlanName]').fill('Project-wide review');await page.getByRole('button',{name:'Review activities',exact:true}).click();await page.waitForURL('**/Writer/PlanActivities?*');assert((await page.locator('body').textContent()).includes('All Books'));await page.locator('[name=Confirm]').check();await page.getByRole('button',{name:'Commit reviewed schedule',exact:true}).click();await page.waitForURL('**/Writer/SchedulePreview?*');
}
await page.goto(`${base}/Writer/Journey?projectId=${scope.project}&bookId=${scope.book}`);assert.equal(await page.locator('.writer-month-grid').count(),1);assert((await page.locator('body').textContent()).includes('Review the arrival objective next'));
if(!pwa)await page.screenshot({path:output+'/Journey-Live.png',fullPage:true});
const today=new Date().toISOString().slice(0,10);await page.locator(`.writer-month-grid a[href*="day=${today}"]`).click();assert((await page.locator('body').textContent()).includes('Sessions on this day'));
await page.goto(url(scope.other));const other=page.locator('[data-writer-work]');await other.locator('[name=kind]').selectOption('Planning');await other.getByRole('button',{name:'Start session',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('[data-work-current]').hidden);await other.locator('[data-work-end]').click();await page.waitForFunction(()=>document.querySelector('[data-work-current]').hidden);await page.reload();assert.equal(await page.getByRole('heading',{name:'Start Here',exact:true}).isVisible(),true);assert.equal(await page.locator('.writer-day-observed').count(),1,'Planning works without any accepted manuscript baseline');
await page.goto(url(scope.book));assert.equal(await page.getByRole('heading',{name:'Continue Writing',exact:true}).isVisible(),true);
assert.equal((await page.request.post(base+'/Writer/Work/Command',{form:{bookId:scope.book,sessionId:'00000000-0000-0000-0000-000000000001',command:'play'}})).status(),400,'Media command requires antiforgery');
assert.deepEqual(failed,[]);console.log(`PASS live intelligent Writer: ${pwa?'simulated PWA':'browser'}; real Help/Reader destination, saved focus, private sessions/notes, unavailable audio, 17-hour revision planning, reviewed chapter/scene tasks, completion, month/day Journey and empty-history planning`);
await context.close();
}}finally{await browser.close();}
})().catch(error=>{const message=error.stack||String(error);console.error(privatePassword?message.replaceAll(privatePassword,'[redacted]'):message);process.exitCode=1;});

View File

@ -0,0 +1,41 @@
const {chromium}=require('playwright');
const assert=require('node:assert/strict');
const fs=require('node:fs');
(async()=>{const browser=await chromium.launch();try{for(const pwa of [false,true]){
const context=await browser.newContext();if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
await context.route('**/signalr.min.js',route=>route.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
let session=null;const requests=[];
await context.route('**/Writer/Work/**',async route=>{
const request=route.request(),action=new URL(request.url()).pathname.split('/').pop();
if(action==='State')return route.fulfill({json:{session,defaultPauseOnEdit:true}});
const data=new URLSearchParams(request.postData());requests.push({action,...Object.fromEntries(data)});
assert(data.get('__RequestVerificationToken'));
if(action==='Start')session={sessionID:data.get('requestId'),kind:data.get('kind'),bookID:12,chapterID:Number(data.get('chapterId')),chapterTitle:'The crossing',startedUtc:new Date().toISOString(),engagedSeconds:0,playbackSeconds:0,uniqueSeconds:0,pauseOnEdit:true,live:false,sequence:0};
if(action==='End')session=null;
await route.fulfill({status:200,body:''});
});
const page=await context.newPage();const errors=[];page.on('pageerror',error=>errors.push(error.message));
for(const theme of ['modern-light','modern-dark','warm-light','warm-dark'])for(const width of [390,1440]){
await page.setViewportSize({width,height:1000});await page.goto('http://127.0.0.1:5238/writer2-fixture?populated=true&objective=true');await page.evaluate(theme=>window.PlotDirectorApplyApplicationTheme(theme),theme);
await page.getByRole('button',{name:'Help Me',exact:true}).click();assert.equal(await page.locator('#writer-help-options').isVisible(),true);assert((await page.locator('#writer-help-options').textContent()).includes('Your saved activity is revising'));
assert((await page.locator('#writer-help-options a').first().getAttribute('href')).includes('/Scenes/Edit/31'));
await page.getByRole('button',{name:'Dismiss suggestions'}).click();assert.equal(await page.locator('#writer-help-options').isVisible(),false);
const toolbar=page.locator('[data-writer-work]');await toolbar.locator('[name=kind]').selectOption('AudioReview');await toolbar.locator('[name=chapterId]').selectOption('21');
await toolbar.getByRole('button',{name:'Start Audio Review',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('[data-work-current]').hidden);
assert.equal(await toolbar.locator('[data-work-audio]').isVisible(),true);
for(const button of await toolbar.locator('[data-media-command]').all())assert.equal(await button.isDisabled(),true);
assert((await toolbar.locator('[data-audio-state]').textContent()).includes('Updated Windows Companion'));
await toolbar.locator('[data-work-note]').fill('Return to the chapter objective');await toolbar.getByRole('button',{name:'End Audio Review & save note'}).click();await page.waitForFunction(()=>document.querySelector('[data-work-current]').hidden);
assert.equal(requests.at(-1).note,'Return to the chapter objective');
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,theme+' '+width+' overflow');
await page.goto('http://127.0.0.1:5238/writer2-fixture?journey=true');await page.evaluate(theme=>window.PlotDirectorApplyApplicationTheme(theme),theme);
assert.equal(await page.locator('.writer-month-grid>a').count(),30);
const revisionDay=page.locator('.writer-month-grid>a').filter({hasText:'+2000 / −2000'});assert.equal(await revisionDay.count(),1);assert(!(await revisionDay.getAttribute('class')).includes('work-level-0'));
assert((await page.locator('.writer-month-grid').textContent()).includes('Audio review'));
assert.equal(await page.locator('.writer-year-grid>a').count(),365);
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,'calendar overflow '+width);
if(!pwa&&theme==='warm-light'&&width===1440)await page.screenshot({path:'/home/nick/writer-intelligent/journey-fixture.png',fullPage:true});
}
await page.goto('http://127.0.0.1:5238/writer2-fixture?workOnly=true');assert.equal(await page.locator('h1').textContent(),'A Distant Shore');assert.equal(await page.locator('.writer-day-observed').count(),1,'Planning-only history appears without accepted snapshot totals');
assert.deepEqual(errors,[]);assert(requests.every(x=>x.action!=='Command'),'Unsupported native controls never issue commands');await context.close();
}console.log('PASS Writer intelligence UI: four themes, two widths, browser/PWA; grounded Help Me, explicit audio start/end/note, disabled unsupported controls, month/year calendar and zero-net revision intensity');}finally{await browser.close();}})().catch(error=>{console.error(error);process.exitCode=1;});

View File

@ -45,7 +45,9 @@ const assert=require('node:assert/strict');
await page.goto(`${base}/Writer/ScheduleSetup?projectId=${scope.project}&bookId=${scope.book}`);
await page.locator('[name=PlanName]').fill(allBooks?'Synthetic project-wide plan':'Synthetic book plan');
if(allBooks)await page.locator('[name=BookID]').selectOption('');
await Promise.all([page.waitForURL('**/Writer/SchedulePreview?writingPlanId=*'),page.getByRole('button',{name:'Create Plan and Generate Schedule'}).click()]);
await Promise.all([page.waitForURL('**/Writer/PlanActivities?writingPlanId=*'),page.getByRole('button',{name:'Review activities',exact:true}).click()]);
await page.locator('[name=Confirm]').check();
await Promise.all([page.waitForURL('**/Writer/SchedulePreview?writingPlanId=*'),page.getByRole('button',{name:'Commit reviewed schedule',exact:true}).click()]);
await page.getByRole('link',{name:'Edit Plan',exact:true}).click();await page.waitForURL('**/Writer/EditWritingPlan?writingPlanId=*');
assert.equal(await page.locator('input[readonly]').nth(1).inputValue(),allBooks?'All Books':'Writer verification book');
await page.locator('[name=PlanName]').fill(allBooks?'Updated project-wide plan':'Updated book plan');

View File

@ -47,6 +47,7 @@ internal static class NativeCompanionHttpTests
var builder=WebApplication.CreateBuilder(new WebApplicationOptions{EnvironmentName="Development"});builder.Logging.ClearProviders();builder.WebHost.UseUrls("http://127.0.0.1:0");
builder.Services.AddSingleton<ISqlConnectionFactory>(Proxy<ISqlConnectionFactory>((name,args)=>throw new Exception("Activity HTTP admission must not reach a database")));
builder.Services.AddScoped<WritingActivityRepository>();
builder.Services.AddScoped<WriterWorkRepository>();
builder.Services.AddSingleton<IStoryIntelligenceClient>(provider);
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IBookRepository>((n,a)=>{if(n=="GetCoverPathsAsync")coverReads++;return Task.FromResult<Book?>(new(){BookID=3,ProjectID=1,BookTitle="Fixture book",CoverThumbnailPath="/uploads/books/3/cover.webp"});}));
builder.Services.AddSingleton(Proxy<IUploadStorageService>((n,a)=>n=="TryResolvePublicPath"&&Equals(a![1],"uploads/books/3")?coverFile:throw new Exception("Unexpected cover path lookup")));
@ -79,6 +80,7 @@ internal static class NativeCompanionHttpTests
using var agent=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false,UseCookies=false}){BaseAddress=new Uri(address)};
Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Native API is not anonymous");
Check((await agent.PostAsJsonAsync("/api/native-companion/writing-activity",new{})).StatusCode==HttpStatusCode.Unauthorized,"Activity observation requires a native grant before any database access");
Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{Guid.NewGuid()}/documents/{Guid.NewGuid()}/audio-review",new AudioReviewObservation{BookID=3,Sequence=1})).StatusCode==HttpStatusCode.Unauthorized,"Audio media observations require native authentication before database access");
var anonymousHub=(await agent.PostAsync("/hubs/native-companion/negotiate?negotiateVersion=1",null)).StatusCode;Check(anonymousHub is HttpStatusCode.Unauthorized or HttpStatusCode.Redirect,"Anonymous native hub subscription refused");
var verifier=new string('d',64);var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier)));
var oversized=await agent.PostAsJsonAsync("/api/native-companion/pair",new{challenge=new string('A',64),padding=new string('x',5000)});Check(!oversized.IsSuccessStatusCode,"Oversized pairing bodies are refused before pairing state creation");
@ -92,6 +94,7 @@ internal static class NativeCompanionHttpTests
Check((await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary<string,string>{{"code",code},{"retainImport","true"},{"__RequestVerificationToken",antiforgery}}))).IsSuccessStatusCode,"Authenticated antiforgery approval succeeds");
var redeemed=await agent.PostAsJsonAsync("/api/native-companion/token",new{code,verifier});Check(redeemed.IsSuccessStatusCode,"Agent redeems approved pairing");
var token=(await redeemed.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("accessToken").GetString();agent.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Bearer",token);
Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{Guid.NewGuid()}/documents/{Guid.NewGuid()}/audio-review",new AudioReviewObservation{BookID=3,Sequence=1})).StatusCode==HttpStatusCode.Forbidden,"Audio media observations require an exact current native lease before database access");
Check((await agent.PostAsJsonAsync("/api/native-companion/writing-activity",new{})).StatusCode==HttpStatusCode.BadRequest,"Native activity rejects malformed identities before database access");
Check((await agent.GetFromJsonAsync<CompanionBook[]>("/api/native-companion/books"))!.Single().BookId==3,"Grant loads authorized books through actual routing");
var listed=(await agent.GetFromJsonAsync<CompanionBook[]>("/api/native-companion/books"))!.Single();Check(listed.ProjectTitle=="Fixture"&&listed.BookTitle=="Test book","Native book selection includes author-facing project and book names");
@ -125,6 +128,7 @@ internal static class NativeCompanionHttpTests
await agent.DeleteAsync($"/api/native-companion/instances/{firstInstance}/documents/{firstSession}/presence");
var instance=Guid.NewGuid();var document=Guid.NewGuid();var live=new NativePresence{BookId=3,ManuscriptId=request.ManuscriptId,Sequence=1,DocumentTitle="Synthetic manuscript"};
Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/presence",live)).IsSuccessStatusCode,"Actual bearer-scoped presence accepted");
Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/audio-review",new AudioReviewObservation{BookID=3,Sequence=1,Version=2})).StatusCode==HttpStatusCode.BadRequest,"Audio media rejects unsupported versions before database access");
var notification=await socket.ReceiveAsync(socketBuffer,socketTimeout.Token);Check(Encoding.UTF8.GetString(socketBuffer,0,notification.Count).Contains("NativePresenceChanged"),"Authenticated native hub pushes only invalidation, not prose or navigation feedback");socket.Abort();
var leases=await browser.GetFromJsonAsync<JsonElement[]>("/native-companion/presence?bookId=3");Check(leases?.Length==1,"Authenticated browser sees scoped native session without prose");
Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/presence",live)).StatusCode==HttpStatusCode.Conflict,"Actual HTTP stale sequence refused");

View File

@ -26,6 +26,8 @@ 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-intelligence-database")){await WriterIntelligenceDatabaseTests.Run();return;}
if(args.Contains("--writer-intelligence")){WriterIntelligenceTests.Run();return;}
if(args.Contains("--writing-activity")){WritingActivityTests.Run();return;}
if(args.Contains("--chapter-sync")){ChapterSynchronisationTests.Run();return;}
if(args.Contains("--manuscript-reader")){await ManuscriptReaderTests.Run();return;}
@ -170,6 +172,7 @@ var tests = new (string Name, Action Test)[]
("Native installation renewal and revocation remain account/security scoped", () => NativeInstallationTests.Run().GetAwaiter().GetResult()),
("Writer dashboard book scope",()=>WriterDashboardTests.Run().GetAwaiter().GetResult()),
("Writing activity measurement", WritingActivityTests.Run),
("Writer intelligence and measured review", WriterIntelligenceTests.Run),
("Manuscript Reader", () => ManuscriptReaderTests.Run().GetAwaiter().GetResult()),
("Paragraph manuscript identity, evidence and exact-session synchronisation", () => { ParagraphManuscriptTests.Run();ParagraphWorkflowTests.Run().GetAwaiter().GetResult(); }),
("Native wizard capture is scoped, durable and independent of Word", () => NativeManuscriptCaptureTests.Run().GetAwaiter().GetResult()),

View File

@ -179,6 +179,12 @@ internal static class ToolbarBrowserHost
var now=DateTime.UtcNow;
model.Activity=new(){BookID=12,Totals=new(){Added=120,Removed=30,ActiveDays=2,RecordedEvents=3,AcceptedEvents=3,HasAcceptedEvidence=true,CoverageSinceUtc=now.AddDays(-2)},Days=[new(){Day=now.Date.AddDays(-1),Added=80,Removed=20,Changes=1},new(){Day=now.Date,Added=40,Removed=10,Changes=1}],Events=[new(){BookID=12,ReceivedUtc=now,Kind="Change",Source="WordCompanion",Added=40,Removed=10}]};
}
if(context.Request.Query["workOnly"]=="true"){model.Activity=null;model.Work=new(){BookID=12,Year=DateTime.UtcNow.Year,Month=DateTime.UtcNow.Month,Days=[new(){Day=DateTime.UtcNow.Date,Planning=1}]};}
model.Suggestions = new PlotLine.Services.Writer.WriterSuggestionProvider().Suggest(model);
if(context.Request.Query["journey"]=="true"){
model.Journey=true;
model.Work=new(){BookID=12,Year=2026,Month=11,Days=[new(){Day=new(2026,11,14),Added=2000,Removed=2000,Changes=4,Editing=1,EngagedSeconds=300},new(){Day=new(2026,11,15),AudioReview=1,PlaybackSeconds=600}]};
}
model.Workspace=context.Request.Query["workspace"].ToString() is "Revision"?"Revision":"WriteNext";
await RenderFullAsync(context,"Writer","Index",model);
});

View File

@ -0,0 +1,108 @@
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using PlotDirector.Companion.Protocol;
using PlotLine.Data;
using PlotLine.Models;
internal static class WriterIntelligenceDatabaseTests
{
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_WriterIntelligent_20261115";
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 Writer database "+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;
// This owned disposable database is removed after qualification; never retarget this test.
var work=new WriterWorkRepository(factory,TimeProvider.System);var id=Guid.NewGuid();
await work.Execute(new{Action="start",UserID=user,BookID=book,SessionID=id,ChapterID=rows.ChapterID,Kind="Editing"});
await work.Execute(new{Action="start",UserID=user,BookID=book,SessionID=id,ChapterID=rows.ChapterID,Kind="Editing"});
Check((await work.Read(user,book)).Count==1,"idempotent starts do not duplicate sessions");
var refused=false;try{await work.Read(rows.Other,book);}catch(SqlException e)when(e.Number==51000){refused=true;}Check(refused,"private work history denies another author");
refused=false;try{await work.Execute(new{Action="start",UserID=user,BookID=rows.ForeignBook,SessionID=Guid.NewGuid(),ChapterID=rows.ChapterID,Kind="Reading"});}catch(SqlException e)when(e.Number==51000){refused=true;}Check(refused,"a chapter cannot be attached to another book");
await db.ExecuteAsync("UPDATE dbo.WriterWorkSessions SET BrowserReceivedUtc=DATEADD(second,-12,SYSUTCDATETIME()) WHERE SessionID=@id",new{id});
await work.Execute(new{Action="heartbeat",UserID=user,BookID=book,SessionID=id,Sequence=1,Engaged=true});
var engaged=(await work.Read(user,book)).Single().EngagedSeconds;
await work.Execute(new{Action="heartbeat",UserID=user,BookID=book,SessionID=id,Sequence=1,Engaged=true});
Check(engaged is >=11 and <=14&&(await work.Read(user,book)).Single().EngagedSeconds==engaged,"engaged time is server-bounded and duplicate heartbeat is inert");
await db.ExecuteAsync("UPDATE dbo.WriterWorkSessions SET BrowserReceivedUtc=DATEADD(hour,-1,SYSUTCDATETIME()) WHERE SessionID=@id",new{id});
await work.Execute(new{Action="heartbeat",UserID=user,BookID=book,SessionID=id,Sequence=2,Engaged=true});
Check((await work.Read(user,book)).Single().EngagedSeconds==engaged,"long idle or network gap does not become active time");
await Task.WhenAll(work.Execute(new{Action="heartbeat",UserID=user,BookID=book,SessionID=id,Sequence=3,Engaged=true}),work.Execute(new{Action="heartbeat",UserID=user,BookID=book,SessionID=id,Sequence=4,Engaged=true}));
Check((await work.Read(user,book)).Single().BrowserSequence==4,"concurrent out-of-order heartbeats retain the highest sequence");
var audio=Guid.NewGuid();var instance=Guid.NewGuid();var document=Guid.NewGuid();
await work.Execute(new{Action="start",UserID=user,BookID=book,SessionID=audio,ChapterID=rows.ChapterID,Kind="AudioReview",NativeInstance=instance,NativeDocument=document,NativeGrant="synthetic-grant"});
Check((await work.Read(user,book)).Count(x=>x.EndedUtc==null)==1,"starting another activity closes the prior session without overlapping book timers");
var value=new AudioReviewObservation{BookID=book,ReviewID=audio,Sequence=1,State="playing",MediaKey="synthetic-media",PositionSeconds=100,DurationSeconds=1000,Operations=["play","pause","back15","forward15"]};
await work.Media(user,book,instance,document,"synthetic-grant",value);
Check((await work.Read(user,book)).First(x=>x.SessionID==audio).PlaybackSeconds==0,"initial playing position alone establishes no listening interval");
await db.ExecuteAsync("UPDATE dbo.WriterWorkSessions SET MediaReceivedUtc=DATEADD(second,-10,SYSUTCDATETIME()) WHERE SessionID=@audio",new{audio});
value.Sequence=2;value.PositionSeconds=110;await work.Media(user,book,instance,document,"synthetic-grant",value);
var measured=(await work.Read(user,book)).First(x=>x.SessionID==audio);
Check(measured.PlaybackSeconds is >9 and <=10.1&&measured.UniqueSeconds==10,"consecutive native telemetry records playback and unique coverage");
await work.Media(user,book,instance,document,"synthetic-grant",value);
Check((await work.Read(user,book)).First(x=>x.SessionID==audio).PlaybackSeconds==measured.PlaybackSeconds,"retry after lost media acknowledgement cannot inflate time");
await db.ExecuteAsync("UPDATE dbo.WriterWorkSessions SET MediaReceivedUtc=DATEADD(second,-10,SYSUTCDATETIME()),PositionSeconds=100 WHERE SessionID=@audio",new{audio});
value.Sequence=3;await work.Media(user,book,instance,document,"synthetic-grant",value);measured=(await work.Read(user,book)).First(x=>x.SessionID==audio);
Check(measured.PlaybackSeconds>19&&measured.UniqueSeconds==10,"replay increments listening duration while unique coverage remains unchanged");
refused=false;try{await work.Media(user,book,Guid.NewGuid(),document,"synthetic-grant",value);}catch(UnauthorizedAccessException){refused=true;}Check(refused,"media ingestion pins exact instance, document and grant");
value.Sequence=4;value.TextModified=true;var reply=await work.Media(user,book,instance,document,"synthetic-grant",value);
Check(reply.Command=="pause"&&reply.CommandID.HasValue,"real text modification requests pause when preference is enabled");
value.Sequence=5;value.TextModified=false;value.State="paused";value.AcknowledgedCommandID=reply.CommandID;reply=await work.Media(user,book,instance,document,"synthetic-grant",value);
Check(reply.Command==null,"pause acknowledgement never causes automatic resume");
await work.Execute(new{Action="preference",UserID=user,BookID=book,SessionID=audio,PauseOnEdit=false});
Check((await work.State(user,book)).Current?.SessionID==audio&&!(await work.State(user,book)).PauseOnEdit,"lightweight state reads the active session and saved audio preference");
await work.Execute(new{Action="end",UserID=user,BookID=book,SessionID=audio,Note="Return to the scene objective"});
Check((await work.Read(user,book)).First(x=>x.SessionID==audio).Note=="Return to the scene objective","explicit return note and end are retained");
Check((await work.State(user,book)).Current==null&&!(await work.State(user,book)).PauseOnEdit,"audio preference survives the end of a review without loading history");
var days=await work.Calendar(user,book,DateTime.UtcNow.Year);Check(days.Any(x=>x.AudioReview>0&&x.PlaybackSeconds>19)&&days.Any(x=>x.Editing>0),"calendar includes editing and audio even without word growth");
var schedule=new WritingScheduleRepository(factory);var planning=new WriterPlanningRepository(factory);
var plan=await schedule.CreateWritingPlanAsync(new(){UserID=user,ProjectID=rows.ProjectID,BookID=book,PlanName="Synthetic reviewed plan",GoalType="Revision",StartDate=DateTime.Today,DeadlineDate=DateTime.Today.AddDays(30),AvailableDaysJson="[{\"day\":\"Monday\",\"minutes\":120}]",SessionLengthMinutes=120,IsActive=true});
var context=await planning.Context(user,plan);Check(context.Chapters==2&&context.Scenes==1&&context.ExistingTasks==0,"empty-schedule diagnostics report actual chapter, scene and existing-task counts");
var candidates=await planning.Read(user,plan,"candidates");Check(candidates.Any(x=>x.SceneID==rows.SceneID)&&candidates.Any(x=>x.ChapterID==rows.EmptyChapter&&x.SceneID==null),"planning includes imported statuses and chapters without manual scene tasks");
var item=new WriterPlanActivity{BookID=book,ChapterID=rows.EmptyChapter,Minutes=30,ScheduledDate=DateTime.Today,Kind="Edit"};
await planning.Save(user,plan,[item]);var saved=await planning.Read(user,plan);
Check(saved.Count==1&&(await schedule.GetWritingPlansForManagementAsync(user)).Single().PlannedTaskCount==1,"chapter activity persists in the existing plan and management totals");
await planning.Complete(user,plan,saved[0].ActivityID);
refused=false;try{await planning.Save(user,plan,[item]);}catch(SqlException e)when(e.Number==51000){refused=true;}Check(refused,"regeneration cannot discard completed activities");
var manuscript=new ParagraphManuscriptRepository(factory);var paragraphText=string.Join(' ',Enumerable.Repeat("word",1000))+"\r";var text=string.Concat(Enumerable.Repeat(paragraphText,250));var state=new ParagraphManuscript{BookId=book,ProjectId=rows.ProjectID,ManuscriptId=Guid.NewGuid(),SnapshotHash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))),Paragraphs=Enumerable.Range(0,250).Select(i=>new StoryParagraph{ChapterId=rows.ChapterID,Occurrence=new(){Id=Guid.NewGuid(),Ordinal=i,Start=i*paragraphText.Length,End=(i+1)*paragraphText.Length,Text=paragraphText}}).ToList()};
var canonical=await manuscript.Save(user,state,-1,Guid.NewGuid());var clock=Stopwatch.StartNew();
var checkpoint=Guid.NewGuid();await work.Execute(new{Action="start",UserID=user,BookID=book,SessionID=checkpoint,ChapterID=rows.ChapterID,Kind="Reading"});await work.Execute(new{Action="end",UserID=user,BookID=book,SessionID=checkpoint});await work.Calendar(user,book,DateTime.UtcNow.Year);clock.Stop();
var recorded=(await work.Read(user,book)).First(x=>x.SessionID==checkpoint);
Check(recorded.StartRevision==canonical.Revision&&recorded.EndRevision==canonical.Revision&&recorded.StartParagraphCount==250,"250,000-word manuscript checkpoints preserve accepted revision and paragraph count");
Console.WriteLine($"Writer 250,000-word explicit checkpoint + calendar measurement: {clock.ElapsedMilliseconds} ms; dashboard never tokenises this prose.");
var after=await manuscript.Get(user,book);Check(after!.Revision==canonical.Revision&&after.SnapshotHash==state.SnapshotHash,"activity and planning leave canonical manuscript unchanged");
var reviewEdits=Guid.NewGuid();await work.Execute(new{Action="start",UserID=user,BookID=book,SessionID=reviewEdits,ChapterID=rows.ChapterID,Kind="AudioReview",NativeInstance=instance,NativeDocument=document,NativeGrant="synthetic-grant"});
value=new(){BookID=book,ReviewID=reviewEdits,Sequence=1,State="playing",MediaKey="review-edits",PositionSeconds=0,PlaybackRate=1};await work.Media(user,book,instance,document,"synthetic-grant",value);
state.Paragraphs[0].Occurrence.Text="edit"+state.Paragraphs[0].Occurrence.Text[4..];state.SnapshotHash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(string.Concat(state.Paragraphs.Select(p=>p.Occurrence.Text)))));
var acceptedEdit=await manuscript.Save(user,state,canonical.Revision,Guid.NewGuid());
await db.ExecuteAsync("UPDATE dbo.WriterWorkSessions SET MediaReceivedUtc=DATEADD(second,-10,SYSUTCDATETIME()) WHERE SessionID=@reviewEdits",new{reviewEdits});value.Sequence=2;value.PositionSeconds=10;await work.Media(user,book,instance,document,"synthetic-grant",value);await work.Execute(new{Action="end",UserID=user,BookID=book,SessionID=reviewEdits});
var evidence=(await work.History(user,book)).Single(x=>x.SessionID==reviewEdits);
Check(evidence.ChangesDuringSession==1&&evidence.AdditionsDuringSession==1&&evidence.RemovalsDuringSession==1&&evidence.ChangedParagraphs==1&&evidence.PlaybackSeconds>9,"audio review links actual zero-net accepted revision and paragraph changes without duplicate word counting");
await new WritingActivityRepository(factory).Configure(user,book,false,365);
refused=false;try{await work.Execute(new{Action="start",UserID=user,BookID=book,SessionID=Guid.NewGuid(),Kind="Planning"});}catch(SqlException e)when(e.Number==51000){refused=true;}Check(refused,"existing recording pause also prevents new work sessions");
await work.Execute(new{Action="erase",UserID=user,BookID=book});Check((await work.Read(user,book)).Count==0,"erasure removes work, notes and cascaded daily measurements");
}
}

View File

@ -0,0 +1,36 @@
using PlotDirector.Companion.Protocol;
using PlotLine.Models;
using PlotLine.ViewModels;
using PlotLine.Services.Writer;
internal static class WriterIntelligenceTests
{
public static void Run()
{
void Check(bool ok,string why){if(!ok)throw new Exception(why);Console.WriteLine("PASS Writer intelligence "+why);}
var now=new DateTime(2026,11,15,12,0,0,DateTimeKind.Utc);
var previous=new WriterWorkSession{MediaSequence=1,MediaReceivedUtc=now.AddSeconds(-10),PositionSeconds=100,PlaybackState="playing",MediaKey="chosen",PlaybackRate=1};
AudioReviewObservation Value(double position,long sequence=2)=>new(){BookID=1,Sequence=sequence,State="playing",PositionSeconds=position,MediaKey="chosen"};
var measured=AudioReviewMetrics.Measure(previous,Value(110),now);
Check(measured.Seconds==10&&measured.UniqueSeconds==10,"consecutive playing observations produce actual bounded playback coverage");
previous.RangesJson=measured.Ranges;
var replay=AudioReviewMetrics.Measure(previous,Value(110),now);
Check(replay.Seconds==10&&replay.UniqueSeconds==10,"replaying ten seconds adds playback but does not duplicate unique coverage");
Check(AudioReviewMetrics.Measure(previous,Value(110,1),now).Seconds==0,"duplicate sequence never creates more playback time");
Check(AudioReviewMetrics.Measure(previous,Value(140),now).Seconds==0,"seek jump is not listening coverage");
Check(AudioReviewMetrics.Measure(previous,Value(110),now.AddMinutes(1)).Seconds==0,"interrupted telemetry does not invent activity across a gap");
var seek=Value(110);seek.Seeked=true;Check(AudioReviewMetrics.Measure(previous,seek,now).Seconds==0,"an explicit seek never bridges playback coverage even when positions look continuous");
var paused=Value(110);paused.State="paused";Check(AudioReviewMetrics.Measure(previous,paused,now).Seconds==0,"paused state does not manufacture playback intervals");
var foreign=Value(110);foreign.MediaKey="other";Check(AudioReviewMetrics.Measure(previous,foreign,now).Seconds==0,"different media source does not contribute to current coverage");
var expiry=PlotLine.Data.WriterWorkRepository.Reply(new(){CommandID=Guid.NewGuid(),Command="pause",CommandUtc=DateTime.SpecifyKind(now,DateTimeKind.Unspecified)},now);Check(expiry.ExpiresUtc?.Kind==DateTimeKind.Utc,"command expiry is explicitly UTC across browser and Windows time zones");
var invalid=Value(double.NaN);var refused=false;try{AudioReviewMetrics.Validate(invalid);}catch(ArgumentException){refused=true;}Check(refused,"nonfinite media position is refused");
var plan=new WritingPlanSettingsEditViewModel{StartDate=new(2026,11,16),DeadlineDate=new(2026,11,17),WritingDayAvailability=[new(){Day="Monday",IsAvailable=true,Minutes=120},new(){Day="Tuesday",IsAvailable=true,Minutes=60}]};
var activities=WriterPlanning.Allocate(plan,[new(){BookID=1,ChapterID=1,Title="One",Minutes=150,Kind="Edit"},new(){BookID=1,ChapterID=2,Title="Two",Minutes=30,Kind="Review"}]);
Check(activities.Count==3&&activities.Sum(x=>x.Minutes)==180&&activities.Where(x=>x.ScheduledDate.Day==17).Sum(x=>x.Minutes)==60,"activities share daily capacity and split across dates without exceeding availability");
refused=false;try{WriterPlanning.Allocate(plan,[new(){Minutes=181}]);}catch(ArgumentException){refused=true;}Check(refused,"insufficient capacity explains failure before persistence");
Check(WriterPlanning.StartingBudget(1000)!=WriterPlanning.StartingBudget(10000),"known lengths produce distinct adjustable budgets rather than equal chapter effort");
var provider=new WriterSuggestionProvider();Check(provider.Suggest(new()).Count==0,"empty context produces no invented manuscript observations");
var model=new WriterDashboardViewModel{BookID=2,Book=new(){ChapterCount=3},ObjectiveChoices=[new(){ChapterID=12,ChapterTitle="Actual chapter"}],RevisionQueue=[new(){SceneID=22,SceneTitle="Actual scene"}],Activity=new(){Totals=new(){Added=2000,Removed=2000}}};
var suggestions=provider.Suggest(model);Check(suggestions.Any(x=>x.Key=="changes")&&suggestions.Any(x=>x.Key=="listen")&&suggestions.Count<=4,"zero-net revision and actual chapter evidence supply bounded actionable suggestions");
Check(suggestions.All(x=>!x.Observation.Contains("block",StringComparison.OrdinalIgnoreCase)),"recommendations do not diagnose writer block from observations");
}
}

View File

@ -12,9 +12,9 @@ namespace PlotLine.Controllers;
public sealed class WriterController(
IWriterWorkspaceService writerWorkspace,
IWritingScheduleService writingSchedule,
IBookRepository? bookRepository=null, IProjectAccessService? access=null, WritingActivityRepository? activity=null, WriterObjectiveRepository? objectives=null) : Controller
IBookRepository? bookRepository=null, IProjectAccessService? access=null, WritingActivityRepository? activity=null, WriterObjectiveRepository? objectives=null, WriterWorkRepository? work=null, PlotLine.Services.Writer.IWriterSuggestionProvider? suggestions=null, WriterPlanningRepository? planning=null) : Controller
{
public async Task<IActionResult> Index(int? projectId,int? bookId=null,string? workspace=null,bool journey=false)
public async Task<IActionResult> Index(int? projectId,int? bookId=null,string? workspace=null,bool journey=false,int? year=null,int? month=null,DateTime? day=null)
{
if(bookId.HasValue&&!projectId.HasValue&&bookRepository!=null)
{
@ -54,10 +54,20 @@ public sealed class WriterController(
model.WritingSchedule = await writingSchedule.GetTodayDashboardAsync(projectId,model.BookID);
if(model.BookID.HasValue)
{ model.WritingSchedule.TodayTasks=model.WritingSchedule.TodayTasks.Where(x=>x.BookID==model.BookID).ToArray();model.WritingSchedule.UpcomingTasks=model.WritingSchedule.UpcomingTasks.Where(x=>x.BookID==model.BookID).ToArray(); }
if (work != null && model.BookID.HasValue && int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), out var workAuthor) && !model.ActivityIsPrivate)
{
var selectedYear = journey && year is >=2000 and <=2100 ? year.Value : DateTime.UtcNow.Year;
var sessions = journey ? await work.History(workAuthor, model.BookID.Value,day) : Array.Empty<PlotLine.Models.WriterWorkSession>();
var calendar = await work.Calendar(workAuthor,model.BookID.Value,selectedYear);
if(!journey&&DateTime.UtcNow.DayOfYear<28)calendar=calendar.Concat(await work.Calendar(workAuthor,model.BookID.Value,selectedYear-1)).ToArray();
model.Work = new(){BookID=model.BookID.Value,Year=selectedYear,Month=month is >=1 and <=12 ? month.Value : DateTime.UtcNow.Month,Day=day,Sessions=sessions,Current=sessions.FirstOrDefault(x=>x.EndedUtc==null),Days=calendar};
}
if(planning!=null&&model.BookID.HasValue&&int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var planner)) model.PlannedActivities=await planning.Upcoming(planner,model.BookID.Value);
model.Suggestions = (suggestions ?? new PlotLine.Services.Writer.WriterSuggestionProvider()).Suggest(model);
return View("Index",model);
}
public Task<IActionResult> Workspaces(int? projectId,int? bookId,string? workspace=null)=>Index(projectId,bookId,workspace);
public Task<IActionResult> Journey(int? projectId,int? bookId)=>Index(projectId,bookId,journey:true);
public Task<IActionResult> Journey(int? projectId,int? bookId,int? year=null,int? month=null,DateTime? day=null)=>Index(projectId,bookId,journey:true,year:year,month:month,day:day);
public IActionResult DisplaySetup(int? projectId,int? bookId)=>Redirect(Url.Action(nameof(Index),new{projectId,bookId})+"#display-setup");
[HttpGet("Write"),HttpGet("Write/Index")]
public IActionResult LegacyWrite(int? projectId,int? bookId)=>RedirectToAction(nameof(Index),new{projectId,bookId});
@ -83,6 +93,7 @@ public sealed class WriterController(
public async Task<IActionResult> SchedulePreview(int? writingPlanId)
{
var model = await writingSchedule.GetSchedulePreviewAsync(writingPlanId);
if(planning!=null&&model.SelectedPlan!=null)model.DerivedActivities=await planning.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),model.SelectedPlan.WritingPlanID);
return View(model);
}
@ -178,6 +189,7 @@ public sealed class WriterController(
}
var model = await writingSchedule.GetScheduleSetupAsync(projectId);
model.BookID = bookId;
if(objectives!=null&&bookId.HasValue&&int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var author)){var objective=(await objectives.Read(author,bookId.Value)).Objective;if(objective?.Activity is "Revising" or "Editing" or "Proofreading")model.GoalType="Revision";}
await writingSchedule.PopulateScheduleSetupOptionsAsync(model);
return View(model);
}
@ -215,6 +227,7 @@ public sealed class WriterController(
TempData["SchedulePreviewError"] = result.ValidationMessage;
}
if(result.GeneratedItemCount==0){TempData.Remove("SchedulePreviewMessage");return RedirectToAction("Index","WriterPlanning",new{writingPlanId=result.WritingPlanID});}
return RedirectToAction(nameof(SchedulePreview), new { writingPlanId = result.WritingPlanID });
}
catch (InvalidOperationException ex)
@ -229,6 +242,7 @@ public sealed class WriterController(
[ValidateAntiForgeryToken]
public async Task<IActionResult> GenerateSchedule(int writingPlanId)
{
try{if(planning!=null&&(await planning.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),writingPlanId)).Count>0)return RedirectToAction("Index","WriterPlanning",new{writingPlanId});}catch(SqlException e)when(e.Number==51000){return NotFound();}
try
{
var items = await writingSchedule.GenerateSchedule(writingPlanId);
@ -335,6 +349,7 @@ public sealed class WriterController(
[ValidateAntiForgeryToken]
public async Task<IActionResult> RegenerateWritingPlanSchedule(int writingPlanId)
{
try{if(planning!=null&&(await planning.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),writingPlanId)).Count>0)return RedirectToAction("Index","WriterPlanning",new{writingPlanId});}catch(SqlException e)when(e.Number==51000){return NotFound();}
try
{
var items = await writingSchedule.RegenerateScheduleAsync(writingPlanId);

View File

@ -0,0 +1,47 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System.Security.Claims;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.Writer;
namespace PlotLine.Controllers;
[Authorize,Route("Writer/PlanActivities")]
public sealed class WriterPlanningController(WriterPlanningRepository repository,IWritingScheduleService schedule):Controller
{
private int Actor=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet]
public async Task<IActionResult> Index(int writingPlanId)
{try{return View(await Load(writingPlanId));}catch(InvalidOperationException){return NotFound();}catch(SqlException e)when(e.Number==51000){return NotFound();}}
[HttpPost,ValidateAntiForgeryToken,RequestFormLimits(ValueCountLimit=20000)]
public async Task<IActionResult> Index(WriterPlanningPage input)
{
WriterPlanningPage model;
try{model=await Load(input.WritingPlanID);}catch(InvalidOperationException){return NotFound();}catch(SqlException e)when(e.Number==51000){return NotFound();}
try
{
if(!input.Confirm)throw new ArgumentException("Review the activity budgets and confirm before saving.");
var chosen=input.Candidates.Where(x=>x.Selected).ToArray();var selected=new List<WriterPlanActivity>();
foreach(var row in chosen){var actual=model.Candidates.SingleOrDefault(x=>x.ChapterID==row.ChapterID&&x.SceneID==row.SceneID);if(actual==null)throw new ArgumentException("A chapter or scene is no longer available. Reload the preview.");if(selected.Any(x=>x.ChapterID==row.ChapterID&&x.SceneID==row.SceneID))throw new ArgumentException("Choose each activity once.");actual.Minutes=row.Minutes;actual.Kind=row.Kind;selected.Add(actual);}
await repository.Save(Actor,input.WritingPlanID,WriterPlanning.Allocate(model.Plan,selected));
TempData["SchedulePreviewMessage"]="Reviewed activities were allocated within your saved availability.";
return RedirectToAction("SchedulePreview","Writer",new{writingPlanId=input.WritingPlanID});
}
catch(ArgumentException e){model.Error=e.Message;}
catch(SqlException e)when(e.Number==51000){model.Error="Activities changed or this plan already contains completed work. Reload, or create a plan for a new pass.";}
return View(model);
}
[HttpPost("Complete"),ValidateAntiForgeryToken]
public async Task<IActionResult> Complete(int writingPlanId,int activityId)
{try{await repository.Complete(Actor,writingPlanId,activityId);return RedirectToAction("SchedulePreview","Writer",new{writingPlanId});}catch(SqlException e)when(e.Number==51000){return NotFound();}}
private async Task<WriterPlanningPage> Load(int id)
{
var plan=await schedule.GetWritingPlanSettingsAsync(id);
var rows=(await repository.Read(Actor,id,"candidates")).ToList();
foreach(var row in rows){row.Minutes=WriterPlanning.StartingBudget(row.Words);row.Kind=plan.GoalType=="FirstDraft"?"Draft":plan.GoalType=="Revision"?"Edit":"Review";}
string? reason=null;
if(rows.Count==0){var context=await repository.Context(Actor,id);reason=context.Chapters==0?"There are no active chapters in this plan's scope. Add a chapter or choose a different book.":$"No unscheduled eligible scene remains: {context.Blocked} scenes are marked blocked and {context.ExistingTasks} already have manual tasks in this plan. Review the existing schedule, or change the blocked-scene setting in Edit availability / deadline.";}
return new(){WritingPlanID=id,Plan=plan,Candidates=rows,Scheduled=await repository.Read(Actor,id),EmptyReason=reason};
}
}

View File

@ -0,0 +1,75 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services.NativeCompanion;
using PlotDirector.Companion.Protocol;
namespace PlotLine.Controllers;
[Authorize,Route("Writer/Work")]
public sealed class WriterWorkController(WriterWorkRepository work,NativePresenceStore presence):Controller
{
private int Actor=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet("State")]
public async Task<IActionResult> State(int bookId)
{
Response.Headers.CacheControl="no-store";
try {var state=await work.State(Actor,bookId);var current=state.Current;if(current?.StartedUtc<DateTime.UtcNow.AddHours(-12))current=null;return Json(new{defaultPauseOnEdit=state.PauseOnEdit,session=current==null?null:new{current.SessionID,current.BookID,current.ChapterID,current.ChapterTitle,current.Kind,startedUtc=DateTime.SpecifyKind(current.StartedUtc,DateTimeKind.Utc),current.EngagedSeconds,current.PlaybackSeconds,current.UniqueSeconds,current.PauseOnEdit,current.PlaybackState,current.PositionSeconds,current.DurationSeconds,current.Pauses,current.Seeks,current.LastError,capabilities=current.MediaReceivedUtc>DateTime.UtcNow.AddSeconds(-45)?current.Capabilities:null,live=current.MediaReceivedUtc>DateTime.UtcNow.AddSeconds(-45)&&presence.Read(Actor,bookId).Any(l=>l.Instance==current.NativeInstance&&l.Session==current.NativeDocument&&l.Grant==current.NativeGrant),coveragePartial=current.CoveragePartial,sequence=current.BrowserSequence}});}
catch(SqlException e)when(e.Number==51000){return NotFound();}
}
[HttpPost("Start"),ValidateAntiForgeryToken]
public async Task<IActionResult> Start(int bookId,int? chapterId,string kind,Guid requestId,bool pauseOnEdit=true)
{
if(requestId==Guid.Empty||kind is not("Writing" or "Editing" or "Planning" or "Reading" or "AudioReview")||kind=="AudioReview"&&!chapterId.HasValue)return BadRequest("Choose a chapter and activity.");
var leases=presence.Read(Actor,bookId).ToArray();var lease=leases.Length==1?leases[0]:leases.Count(x=>x.Position.Active)==1?leases.Single(x=>x.Position.Active):null;
try {await work.Execute(new{Action="start",UserID=Actor,BookID=bookId,ChapterID=chapterId,Kind=kind,SessionID=requestId,PauseOnEdit=pauseOnEdit,NativeInstance=kind=="AudioReview"?lease?.Instance:null,NativeDocument=kind=="AudioReview"?lease?.Session:null,NativeGrant=kind=="AudioReview"?lease?.Grant:null});return Ok(new{sessionID=requestId});}
catch(SqlException e)when(e.Number==51000){return Conflict(new{message="Session could not start. Check book access, chapter availability and Reports recording settings."});}
}
[HttpPost("Heartbeat"),ValidateAntiForgeryToken]
public Task<IActionResult> Heartbeat(int bookId,Guid sessionId,long sequence,bool engaged)=>sequence<=0?Task.FromResult<IActionResult>(BadRequest()):Change(new{Action="heartbeat",UserID=Actor,BookID=bookId,SessionID=sessionId,Sequence=sequence,Engaged=engaged});
[HttpPost("End"),ValidateAntiForgeryToken]
public Task<IActionResult> End(int bookId,Guid sessionId,string? note)
{if(note?.Length>2000)return Task.FromResult<IActionResult>(BadRequest());return Change(new{Action="end",UserID=Actor,BookID=bookId,SessionID=sessionId,Note=note});}
[HttpPost("Preference"),ValidateAntiForgeryToken]
public Task<IActionResult> Preference(int bookId,Guid sessionId,bool pauseOnEdit)=>Change(new{Action="preference",UserID=Actor,BookID=bookId,SessionID=sessionId,PauseOnEdit=pauseOnEdit});
[HttpPost("Command"),ValidateAntiForgeryToken]
public async Task<IActionResult> Command(int bookId,Guid sessionId,string command)
{
try {
var current=(await work.State(Actor,bookId)).Current;if(current?.SessionID!=sessionId)current=null;
if(current==null||!presence.Read(Actor,bookId).Any(l=>l.Instance==current.NativeInstance&&l.Session==current.NativeDocument&&l.Grant==current.NativeGrant)||command is not("play" or "pause" or "back15" or "forward15")||!(current.Capabilities??"").Split(',').Contains(command))return Conflict(new{message="This media operation is unavailable."});
return await Change(new{Action="command",UserID=Actor,BookID=bookId,SessionID=sessionId,CommandID=Guid.NewGuid(),Command=command});
} catch(SqlException e)when(e.Number==51000){return NotFound();}
}
[HttpGet("Export")]
public async Task<IActionResult> Export(int bookId,DateTime? day=null)
{try{return Json((await work.History(Actor,bookId,day)).Select(x=>new{x.SessionID,x.BookID,x.ChapterID,x.Kind,startedUtc=DateTime.SpecifyKind(x.StartedUtc,DateTimeKind.Utc),endedUtc=x.EndedUtc.HasValue?DateTime.SpecifyKind(x.EndedUtc.Value,DateTimeKind.Utc):(DateTime?)null,x.EngagedSeconds,x.PlaybackSeconds,x.UniqueSeconds,x.CoveragePartial,x.Pauses,x.Seeks,x.Note,x.StartRevision,x.EndRevision,x.StartParagraphCount,x.EndParagraphCount,x.ChangesDuringSession,x.AdditionsDuringSession,x.RemovalsDuringSession,x.ChangedParagraphs}));}catch(SqlException e)when(e.Number==51000){return NotFound();}}
[HttpPost("Erase"),ValidateAntiForgeryToken]
public Task<IActionResult> Erase(int bookId,bool confirm)=>confirm?Change(new{Action="erase",UserID=Actor,BookID=bookId}):Task.FromResult<IActionResult>(BadRequest("Confirm erasure."));
private async Task<IActionResult> Change(object values)
{try{await work.Execute(values);return Ok();}catch(SqlException e)when(e.Number==51000){return Conflict(new{message="Session ended, expired, or recording is paused. Check Reports or start a new session."});}}
}
[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion/instances/{instance:guid}/documents/{document:guid}/audio-review")]
public sealed class NativeAudioReviewController(WriterWorkRepository work,NativePresenceStore presence):ControllerBase
{
[HttpPost,RequestSizeLimit(4096)]
public async Task<IActionResult> Observe(Guid instance,Guid document,AudioReviewObservation value)
{
var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);var grant=User.FindFirstValue("NativeCompanion.Grant");
var lease=presence.Read(user,value.BookID).SingleOrDefault(x=>x.Instance==instance&&x.Session==document&&x.Grant==grant);
if(lease==null||value.BookID<=0)return Forbid();
try
{
PlotLine.Services.Writer.AudioReviewMetrics.Validate(value);
var current=(await work.State(user,value.BookID)).Current;if(current?.Kind!="AudioReview"||current.NativeInstance!=instance||current.NativeDocument!=document||current.NativeGrant!=grant)current=null;
if(current==null||current.StartedUtc<DateTime.UtcNow.AddHours(-12))return Ok(new AudioReviewReply());
if(value.ReviewID==null)return Ok(WriterWorkRepository.Reply(current,DateTime.UtcNow));
if(value.ReviewID!=current.SessionID)return Conflict(new{code="review_scope"});
return Ok(await work.Media(user,value.BookID,instance,document,grant!,value));
}
catch(ArgumentException){return BadRequest(new{code="audio_contract"});}
catch(UnauthorizedAccessException){return Forbid();}
catch(SqlException e)when(e.Number==51000){return Conflict(new{code="review_unavailable"});}
}
}

View File

@ -9,7 +9,7 @@ using PlotLine.Services.NativeCompanion;
using PlotDirector.Companion.Protocol;
namespace PlotLine.Controllers;
[Authorize]
public sealed class WritingActivityController(WritingActivityRepository activity,IBookRepository books):Controller
public sealed class WritingActivityController(WritingActivityRepository activity,IBookRepository books,WriterWorkRepository? work=null):Controller
{
private int Actor => int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet("Writer/Activity")]
@ -34,7 +34,7 @@ public sealed class WritingActivityController(WritingActivityRepository activity
public async Task<IActionResult> Erase(int bookId,bool confirm)
{
if(!confirm)return BadRequest("Confirm deletion of activity history.");
try{await activity.Erase(Actor,bookId);return RedirectToAction(nameof(Index),new{bookId});}catch(SqlException e)when(e.Number==51000){return NotFound();}
try{await activity.Erase(Actor,bookId);if(work!=null)await work.Execute(new{Action="erase",UserID=Actor,BookID=bookId});return RedirectToAction(nameof(Index),new{bookId});}catch(SqlException e)when(e.Number==51000){return NotFound();}
}
[HttpGet("Writer/Activity/Export")]
public async Task<IActionResult> Export(int bookId,long? before=null)

View File

@ -0,0 +1,18 @@
using System.Data;
using System.Text.Json;
using Dapper;
using PlotLine.Models;
namespace PlotLine.Data;
public sealed class WriterPlanningRepository(ISqlConnectionFactory factory)
{
public async Task<IReadOnlyList<WriterPlanActivity>> Read(int user,int plan,string action="list")
{using var db=factory.CreateConnection();return(await db.QueryAsync<WriterPlanActivity>("dbo.WriterPlanning",new{Action=action,UserID=user,WritingPlanID=plan},commandType:CommandType.StoredProcedure)).ToArray();}
public async Task<WriterPlanningContext> Context(int user,int plan)
{using var db=factory.CreateConnection();return await db.QuerySingleAsync<WriterPlanningContext>("dbo.WriterPlanning",new{Action="context",UserID=user,WritingPlanID=plan},commandType:CommandType.StoredProcedure);}
public async Task Save(int user,int plan,IReadOnlyList<WriterPlanActivity> items)
{using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterPlanning",new{Action="save",UserID=user,WritingPlanID=plan,Items=JsonSerializer.Serialize(items)},commandType:CommandType.StoredProcedure);}
public async Task Complete(int user,int plan,int activity)
{using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterPlanning",new{Action="complete",UserID=user,WritingPlanID=plan,ActivityID=activity},commandType:CommandType.StoredProcedure);}
public async Task<IReadOnlyList<WriterPlanActivity>> Upcoming(int user,int book)
{using var db=factory.CreateConnection();return(await db.QueryAsync<WriterPlanActivity>("dbo.WriterPlanningUpcoming",new{UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();}
}

View File

@ -0,0 +1,50 @@
using System.Data;
using Dapper;
using PlotLine.Models;
using PlotLine.Services.Writer;
using PlotDirector.Companion.Protocol;
namespace PlotLine.Data;
public sealed class WriterWorkRepository(ISqlConnectionFactory factory,TimeProvider clock)
{
public async Task<IReadOnlyList<WriterWorkSession>> Read(int user,int book,DateTime? day=null)
{using var db=factory.CreateConnection();return (await db.QueryAsync<WriterWorkSession>("dbo.WriterWork",new{Action="read",UserID=user,BookID=book,Day=day?.Date},commandType:CommandType.StoredProcedure)).ToArray();}
public async Task<(WriterWorkSession? Current,bool PauseOnEdit)> State(int user,int book)
{
using var db=factory.CreateConnection();using var results=await db.QueryMultipleAsync("dbo.WriterWork",new{Action="state",UserID=user,BookID=book},commandType:CommandType.StoredProcedure);
var preference=await results.ReadSingleOrDefaultAsync<bool?>();var current=await results.ReadSingleOrDefaultAsync<WriterWorkSession>();return(current,preference??true);
}
public async Task<IReadOnlyList<WriterWorkSession>> History(int user,int book,DateTime? day=null)
{
var rows=await Read(user,book,day);
using var db=factory.CreateConnection();
var evidence=(await db.QueryAsync<WriterWorkSession>("dbo.WriterWorkEvidence",new{UserID=user,BookID=book,Day=day?.Date},commandType:CommandType.StoredProcedure)).ToDictionary(x=>x.SessionID);
foreach(var row in rows)if(evidence.TryGetValue(row.SessionID,out var measured)){row.ChangesDuringSession=measured.ChangesDuringSession;row.AdditionsDuringSession=measured.AdditionsDuringSession;row.RemovalsDuringSession=measured.RemovalsDuringSession;row.ChangedParagraphs=measured.ChangedParagraphs;}
return rows;
}
public async Task<IReadOnlyList<WriterWorkDay>> Calendar(int user,int book,int year)
{using var db=factory.CreateConnection();return (await db.QueryAsync<WriterWorkDay>("dbo.WriterWorkCalendar",new{UserID=user,BookID=book,Year=year},commandType:CommandType.StoredProcedure)).ToArray();}
public async Task Execute(object values)
{using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterWork",values,commandType:CommandType.StoredProcedure);}
public async Task<AudioReviewReply> Media(int user,int book,Guid instance,Guid document,string grant,AudioReviewObservation value)
{
AudioReviewMetrics.Validate(value);
using var db=factory.CreateConnection();db.Open();using var tx=db.BeginTransaction();
var row=await db.QuerySingleOrDefaultAsync<WriterWorkSession>("dbo.WriterWork",new{Action="lock",UserID=user,BookID=book,SessionID=value.ReviewID},tx,commandType:CommandType.StoredProcedure);
if(row==null||row.Kind!="AudioReview"||row.NativeInstance!=instance||row.NativeDocument!=document||row.NativeGrant!=grant)throw new UnauthorizedAccessException();
var now=clock.GetUtcNow().UtcDateTime;
if(value.Sequence>row.MediaSequence)
{
if(!string.IsNullOrEmpty(row.MediaKey)&&!string.IsNullOrEmpty(value.MediaKey)&&row.MediaKey!=value.MediaKey)throw new ArgumentException("Media source changed; end and restart review.");
if(string.IsNullOrEmpty(value.MediaKey))value.MediaKey=row.MediaKey??"";
value.Seeked = value.Seeked || value.AcknowledgedCommandID.HasValue && value.AcknowledgedCommandID == row.CommandID && row.Command is "back15" or "forward15";
var measure=AudioReviewMetrics.Measure(row,value,now);
var command=row.Command;var id=row.CommandID;var sent=row.CommandUtc;
if(value.AcknowledgedCommandID==id||sent<now.AddSeconds(-10)){command=null;id=null;sent=null;}
if(value.TextModified&&row.PauseOnEdit&&value.Operations.Contains("pause")&&value.State=="playing"&&command!="pause") {command="pause";id=Guid.NewGuid();sent=now;}
await db.ExecuteAsync("dbo.WriterWork",new{Action="media",UserID=user,BookID=book,row.SessionID,value.Sequence,PlaybackSeconds=measure.Seconds,measure.UniqueSeconds,RangesJson=measure.Ranges,CoveragePartial=measure.Partial,PlaybackState=value.State,value.PositionSeconds,value.DurationSeconds,value.PlaybackRate,value.MediaKey,Capabilities=string.Join(',',value.Operations),CommandID=id,Command=command,CommandUtc=sent,LastError=value.Error==null?null:"Native media operation failed; see Companion diagnostics.",Pauses=row.PlaybackState=="playing"&&value.State=="paused"?1:0,Seeks=value.Seeked?1:0},tx,commandType:CommandType.StoredProcedure);
row.CommandID=id;row.Command=command;row.CommandUtc=sent;row.MediaKey=value.MediaKey;
}
tx.Commit();return Reply(row,now);
}
public static AudioReviewReply Reply(WriterWorkSession row,DateTime now)=>new(){ReviewID=row.SessionID,ChapterID=row.ChapterID,PauseOnEdit=row.PauseOnEdit,MediaKey=row.MediaKey,CommandID=row.CommandUtc>=now.AddSeconds(-10)?row.CommandID:null,Command=row.CommandUtc>=now.AddSeconds(-10)?row.Command:null,RelativeSeconds=row.Command=="back15"?-15:row.Command=="forward15"?15:null,ExpiresUtc=row.CommandUtc.HasValue?DateTime.SpecifyKind(row.CommandUtc.Value.AddSeconds(10),DateTimeKind.Utc):null};
}

View File

@ -0,0 +1,31 @@
namespace PlotLine.Models;
public sealed class WriterPlanActivity
{
public int ActivityID { get; set; }
public int BookID { get; set; }
public int ChapterID { get; set; }
public int? SceneID { get; set; }
public string Title { get; set; } = "";
public string BookTitle { get; set; } = "";
public string RevisionStatus { get; set; } = "";
public int? Words { get; set; }
public int Minutes { get; set; } = 30;
public DateTime ScheduledDate { get; set; }
public string Status { get; set; } = "Planned";
public string Kind { get; set; } = "Review";
public bool Selected { get; set; } = true;
}
public sealed class WriterPlanningPage
{
public int ProjectID => Plan.ProjectID;
public int? BookID => Plan.BookID;
public int WritingPlanID { get; set; }
public PlotLine.ViewModels.WritingPlanSettingsEditViewModel Plan { get; set; } = new();
public List<WriterPlanActivity> Candidates { get; set; } = [];
public IReadOnlyList<WriterPlanActivity> Scheduled { get; set; } = [];
public bool Confirm { get; set; }
public string? Error { get; set; }
public string? EmptyReason { get; set; }
}
public sealed class WriterPlanningContext { public int Chapters { get; set; } public int Scenes { get; set; } public int Blocked { get; set; } public int ExistingTasks { get; set; } }

View File

@ -0,0 +1,72 @@
namespace PlotLine.Models;
public sealed class WriterWorkSession
{
public int ChangesDuringSession { get; set; }
public long AdditionsDuringSession { get; set; }
public long RemovalsDuringSession { get; set; }
public int ChangedParagraphs { get; set; }
public Guid SessionID { get; set; }
public int BookID { get; set; }
public int? ChapterID { get; set; }
public string? ChapterTitle { get; set; }
public long? StartRevision { get; set; }
public long? EndRevision { get; set; }
public int? StartParagraphCount { get; set; }
public int? EndParagraphCount { get; set; }
public string Kind { get; set; } = "Planning";
public DateTime StartedUtc { get; set; }
public DateTime? EndedUtc { get; set; }
public DateTime LastSeenUtc { get; set; }
public int EngagedSeconds { get; set; }
public double PlaybackSeconds { get; set; }
public double UniqueSeconds { get; set; }
public string RangesJson { get; set; } = "[]";
public bool CoveragePartial { get; set; }
public bool PauseOnEdit { get; set; } = true;
public string? Note { get; set; }
public long BrowserSequence { get; set; }
public long MediaSequence { get; set; }
public DateTime? MediaReceivedUtc { get; set; }
public string PlaybackState { get; set; } = "unavailable";
public double? PositionSeconds { get; set; }
public double? DurationSeconds { get; set; }
public double PlaybackRate { get; set; } = 1;
public string? MediaKey { get; set; }
public string? Capabilities { get; set; }
public Guid? NativeInstance { get; set; }
public Guid? NativeDocument { get; set; }
public string? NativeGrant { get; set; }
public Guid? CommandID { get; set; }
public string? Command { get; set; }
public DateTime? CommandUtc { get; set; }
public string? LastError { get; set; }
public int Pauses { get; set; }
public int Seeks { get; set; }
}
public sealed class WriterWorkDay
{
public DateTime Day { get; set; }
public long Added { get; set; }
public long Removed { get; set; }
public int Changes { get; set; }
public int Writing { get; set; }
public int Editing { get; set; }
public int Planning { get; set; }
public int Reading { get; set; }
public int AudioReview { get; set; }
public int EngagedSeconds { get; set; }
public double PlaybackSeconds { get; set; }
public int Intensity => Changes + Writing + Editing + Planning + Reading + AudioReview + (int)Math.Min(24, Math.Floor(Math.Max(EngagedSeconds, PlaybackSeconds)/300));
}
public sealed record WriterSuggestion(string Key,string Observation,string Action,string Controller,string RouteAction,int? EntityID=null,int? ChapterID=null,string? Interpretation=null);
public sealed class WriterWorkPage
{
public int BookID { get; set; }
public int Year { get; set; } = DateTime.UtcNow.Year;
public int Month { get; set; } = DateTime.UtcNow.Month;
public DateTime? Day { get; set; }
public WriterWorkSession? Current { get; set; }
public IReadOnlyList<WriterWorkSession> Sessions { get; set; } = [];
public IReadOnlyList<WriterWorkDay> Days { get; set; } = [];
}
public sealed record WriterWorkToolbar(int BookID,int? ChapterID,string? ChapterTitle,IReadOnlyList<WriterObjectiveChoice>? Choices=null,string DefaultKind="Writing");

View File

@ -200,6 +200,9 @@ public class Program
builder.Services.AddScoped<IWordCompanionRepository, WordCompanionRepository>();
builder.Services.AddScoped<WritingActivityRepository>();
builder.Services.AddScoped<WriterObjectiveRepository>();
builder.Services.AddScoped<WriterWorkRepository>();
builder.Services.AddScoped<WriterPlanningRepository>();
builder.Services.AddSingleton<PlotLine.Services.Writer.IWriterSuggestionProvider, PlotLine.Services.Writer.WriterSuggestionProvider>();
builder.Services.AddHostedService<PlotLine.Services.WritingActivity.WritingActivityRetention>();
builder.Services.AddScoped<IOnboardingRepository, OnboardingRepository>();
builder.Services.AddScoped<IOnboardingBuildRepository, OnboardingBuildRepository>();

View File

@ -6393,8 +6393,7 @@ public sealed class WritingScheduleService(
var scenes = await writingSchedule.GetSchedulingScenesAsync(plan.ProjectID, plan.BookID, plan.IncludeBlockedScenes);
if (scenes.Count == 0)
{
await writingSchedule.ReplaceScheduleItemsAsync(plan.WritingPlanID, []);
return [];
throw new InvalidOperationException("No scenes currently have schedulable workflow statuses. Review activities derived from your chapters and scenes instead; existing tasks were preserved.");
}
var availableDates = GetAvailableDates(plan.StartDate, plan.DeadlineDate, availability);
@ -6639,23 +6638,8 @@ public sealed class WritingScheduleService(
IsActive = true
});
try
{
var generatedItems = await GenerateSchedule(planId);
return new WritingScheduleSetupResult
{
WritingPlanID = planId,
GeneratedItemCount = generatedItems.Count
};
}
catch (InvalidOperationException ex)
{
return new WritingScheduleSetupResult
{
WritingPlanID = planId,
ValidationMessage = ex.Message
};
}
// Availability is saved first; chapters/scenes and budgets are reviewed before allocation.
return new WritingScheduleSetupResult { WritingPlanID = planId, GeneratedItemCount = 0 };
}
public async Task<WritingScheduleDashboardViewModel> GetTodayDashboardAsync(int? projectId = null, int? bookId = null)

View File

@ -0,0 +1,32 @@
using System.Text.Json;
using PlotDirector.Companion.Protocol;
using PlotLine.Models;
namespace PlotLine.Services.Writer;
public sealed record AudioInterval(double Start,double End);
public sealed record AudioMeasurement(double Seconds,double UniqueSeconds,string Ranges,bool Partial);
public static class AudioReviewMetrics
{
public static void Validate(AudioReviewObservation value)
{
if(value.MediaKey==null||value.Operations==null||value.State is "playing" or "paused" or "stopped" && string.IsNullOrWhiteSpace(value.MediaKey)||value.Version!=1||value.Sequence<=0||value.BookID<=0||value.MediaKey.Length>100||value.Operations.Length>4||value.Operations.Any(x=>x is not("play" or "pause" or "back15" or "forward15"))||value.State is not("playing" or "paused" or "stopped" or "unavailable" or "error")||!double.IsFinite(value.PlaybackRate)||value.PlaybackRate is <0.25 or >4||value.PositionSeconds is {} p&&(!double.IsFinite(p)||p<0||p>86400)||value.DurationSeconds is {} d&&(!double.IsFinite(d)||d<0||d>86400)||value.PositionSeconds>value.DurationSeconds||value.Error?.Length>200)throw new ArgumentException("Invalid audio-review v1 observation.");
}
public static AudioMeasurement Measure(WriterWorkSession previous,AudioReviewObservation value,DateTime now)
{
var ranges=JsonSerializer.Deserialize<List<AudioInterval>>(previous.RangesJson)??[];
var seconds=0d;
var elapsed=previous.MediaReceivedUtc.HasValue?(now-previous.MediaReceivedUtc.Value).TotalSeconds:0;
// Only consecutive, same-source playing observations establish a bounded interval.
// Gaps, seek jumps, rate changes and pauses do not establish playback coverage.
if(!value.Seeked&&value.Sequence>previous.MediaSequence&&previous.PlaybackState=="playing"&&value.State=="playing"&&previous.MediaKey==value.MediaKey&&previous.PositionSeconds is {} start&&value.PositionSeconds is {} end&&elapsed is >0 and <=30&&value.PlaybackRate==previous.PlaybackRate&&end>=start&&end-start<=elapsed*value.PlaybackRate+1)
{
seconds=Math.Min(elapsed,(end-start)/value.PlaybackRate);
if(end>start)ranges.Add(new(start,end));
}
var merged=new List<AudioInterval>();
foreach(var range in ranges.OrderBy(x=>x.Start))
{if(merged.Count==0||range.Start>merged[^1].End)merged.Add(range);else merged[^1]=new(merged[^1].Start,Math.Max(merged[^1].End,range.End));}
var partial=previous.CoveragePartial||merged.Count>4096;
if(merged.Count>4096)return new(seconds,previous.UniqueSeconds,previous.RangesJson,true);
return new(seconds,merged.Sum(x=>x.End-x.Start),JsonSerializer.Serialize(merged),partial);
}
}

View File

@ -0,0 +1,29 @@
using PlotLine.Models;
using PlotLine.ViewModels;
namespace PlotLine.Services.Writer;
public static class WriterPlanning
{
public static IReadOnlyList<WriterPlanActivity> Allocate(WritingPlanSettingsEditViewModel plan,IReadOnlyList<WriterPlanActivity> selected)
{
if(selected.Count==0)throw new ArgumentException("Select at least one chapter or scene. Add a chapter to the selected book if none exists.");
if(plan.DeadlineDate.Date<plan.StartDate.Date||(plan.DeadlineDate-plan.StartDate).TotalDays>3650)throw new ArgumentException("Choose a planning window of at most ten years.");
var availability=plan.WritingDayAvailability.Where(x=>x.IsAvailable).ToDictionary(x=>Enum.Parse<DayOfWeek>(x.Day),x=>x.Minutes);
if(availability.Count==0||availability.Values.Any(x=>x is <1 or >720))throw new ArgumentException("Choose valid writing availability.");
var result=new List<WriterPlanActivity>();var date=plan.StartDate.Date;var used=0;
foreach(var candidate in selected)
{
if(candidate.Minutes is <5 or >1440)throw new ArgumentException("Choose a working budget between 5 and 1,440 minutes for each activity.");
if(candidate.Kind is not("Draft" or "Edit" or "Plan" or "Review" or "AudioReview"))throw new ArgumentException("Choose a supported activity.");
var remaining=candidate.Minutes;
while(remaining>0)
{
while(date<=plan.DeadlineDate.Date&&(!availability.TryGetValue(date.DayOfWeek,out var capacity)||used>=capacity)){date=date.AddDays(1);used=0;}
if(date>plan.DeadlineDate.Date)throw new ArgumentException("Selected working budgets exceed the available time before your deadline. Reduce budgets, deselect activities, extend the deadline or edit availability. No schedule was changed.");
var minutes=Math.Min(remaining,availability[date.DayOfWeek]-used);remaining-=minutes;used+=minutes;
result.Add(new(){BookID=candidate.BookID,ChapterID=candidate.ChapterID,SceneID=candidate.SceneID,Title=candidate.Title,BookTitle=candidate.BookTitle,Minutes=minutes,ScheduledDate=date,Kind=candidate.Kind});
}
}
return result;
}
public static int StartingBudget(int? words)=>words is >0?Math.Clamp((int)Math.Ceiling(words.Value/200d/5)*5,5,120):30;
}

View File

@ -0,0 +1,29 @@
using PlotLine.Models;
using PlotLine.ViewModels;
namespace PlotLine.Services.Writer;
public interface IWriterSuggestionProvider { IReadOnlyList<WriterSuggestion> Suggest(WriterDashboardViewModel model); }
// Data-only rules. Advanced providers can implement the same interface without changing the UI.
public sealed class WriterSuggestionProvider:IWriterSuggestionProvider
{
public IReadOnlyList<WriterSuggestion> Suggest(WriterDashboardViewModel model)
{
var result=new List<WriterSuggestion>();
if(model.Objective is {} objective)result.Add(new("focus",$"Your saved activity is {objective.Activity.ToLowerInvariant()}.","Return to your current focus",objective.SceneID.HasValue?"Scenes":"Writer",objective.SceneID.HasValue?"Edit":objective.ChapterID.HasValue?"Chapter":"Index",objective.SceneID??objective.ChapterID));
if(model.PlannedActivities.FirstOrDefault() is {} reviewed)result.Add(new("reviewed",$"Your reviewed plan includes {reviewed.Title} on {reviewed.ScheduledDate:d MMM}.","Open your next planned activity",reviewed.SceneID.HasValue?"Scenes":"Writer",reviewed.SceneID.HasValue?"Edit":"Chapter",reviewed.SceneID??reviewed.ChapterID));
var planned=model.WritingSchedule.TodayTasks.Concat(model.WritingSchedule.UpcomingTasks).FirstOrDefault();
if(planned!=null)result.Add(new("planned",$"Your plan includes {planned.SceneTitle} on {planned.ScheduledDate:d MMM}.","Open this planned scene","Scenes","Edit",planned.SceneID));
var reminder=model.StoryHealthReminders.FirstOrDefault(x=>x.EntityType=="Chapter"&&x.Category=="Chapter Goal");
if(reminder!=null)result.Add(new("intent",reminder.Detail??"This chapter has no saved goal summary.","Set this chapter's Intent","Writer","Chapter",reminder.EntityID));
var revision=model.RevisionQueue.FirstOrDefault();
if(revision!=null)result.Add(new("revision",$"{revision.SceneTitle} is marked Needs Work.","Review this scene","Scenes","Edit",revision.SceneID,Interpretation:"This is a workflow label, not a new diagnosis."));
var next=model.WriteNext.FirstOrDefault();
if(next!=null)result.Add(new("draft",$"{next.SceneTitle} is marked Outlined.","Work on the next outlined scene","Scenes","Edit",next.SceneID));
if(model.Activity?.Totals is {Removed:>0} totals)result.Add(new("changes",$"Accepted changes record {totals.Added:N0} additions and {totals.Removed:N0} removals in 30 days.","Review the change evidence","WritingActivity","Index",Interpretation:"Revision may be substantial even when net growth is small."));
var chapter=model.ObjectiveChoices.FirstOrDefault(x=>x.ChapterID==model.Objective?.ChapterID)??model.ObjectiveChoices.FirstOrDefault();
if(chapter!=null)result.Add(new("listen",$"{chapter.ChapterTitle} is available in this book.","Read or start Audio Review","ManuscriptReader","Index",ChapterID:chapter.ChapterID,Interpretation:"Listening is an alternative review activity; media controls require updated Windows Companion."));
var note=model.StoryHealthReminders.FirstOrDefault(x=>x.SceneID.HasValue&&x.Category=="Writer Note");
if(note!=null)result.Add(new("note",note.Detail??"A note is available for this scene.","Review this captured note","Scenes","Edit",note.SceneID));
if(model.BookID.HasValue&&result.Count<3)result.Add(new("explore",$"This book contains {model.Book?.ChapterCount??0} chapters.","Explore or add chapters","Books","Details",model.BookID));
return result.DistinctBy(x=>(x.Controller,x.RouteAction,x.EntityID,x.ChapterID)).Take(4).ToArray();
}
}

View File

@ -25,7 +25,7 @@ public sealed class WritingActivityRetention(IServiceScopeFactory scopes,ILogger
}
catch(OperationCanceledException)when(stoppingToken.IsCancellationRequested){break;}
catch(Exception e){logger.LogWarning("Writing baseline discovery could not run ({FailureKind}); retrying on next daily pass.",e.GetType().Name);}
try { using var scope=scopes.CreateScope();using var db=scope.ServiceProvider.GetRequiredService<ISqlConnectionFactory>().CreateConnection();await db.ExecuteAsync(new CommandDefinition("dbo.WritingActivity_Prune",commandType:CommandType.StoredProcedure,cancellationToken:stoppingToken)); }
try { using var scope=scopes.CreateScope();using var db=scope.ServiceProvider.GetRequiredService<ISqlConnectionFactory>().CreateConnection();await db.ExecuteAsync(new CommandDefinition("dbo.WritingActivity_Prune",commandType:CommandType.StoredProcedure,cancellationToken:stoppingToken));await db.ExecuteAsync(new CommandDefinition("dbo.WriterWork_Prune",commandType:CommandType.StoredProcedure,cancellationToken:stoppingToken)); }
catch(OperationCanceledException)when(stoppingToken.IsCancellationRequested){break;}
catch(Exception e){logger.LogWarning("Writing activity retention could not run ({FailureKind}); retrying on next daily pass.",e.GetType().Name);}
try{await Task.Delay(TimeSpan.FromDays(1),stoppingToken);}catch(OperationCanceledException)when(stoppingToken.IsCancellationRequested){break;}

View File

@ -0,0 +1,137 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
IF OBJECT_ID(N'dbo.WriterWorkSessions',N'U') IS NULL
BEGIN
CREATE TABLE dbo.WriterWorkSessions(
SessionID uniqueidentifier NOT NULL PRIMARY KEY,UserID int NOT NULL REFERENCES dbo.AppUser(UserID) ON DELETE CASCADE,
BookID int NOT NULL REFERENCES dbo.Books(BookID) ON DELETE CASCADE,ChapterID int NULL,
Kind varchar(20) NOT NULL CHECK(Kind IN('Writing','Editing','Planning','Reading','AudioReview')),
StartedUtc datetime2 NOT NULL,EndedUtc datetime2 NULL,LastSeenUtc datetime2 NOT NULL,
EngagedSeconds int NOT NULL DEFAULT 0,PlaybackSeconds float NOT NULL DEFAULT 0,UniqueSeconds float NOT NULL DEFAULT 0,
RangesJson nvarchar(max) NOT NULL DEFAULT N'[]' CHECK(ISJSON(RangesJson)=1),CoveragePartial bit NOT NULL DEFAULT 0,
PauseOnEdit bit NOT NULL DEFAULT 1,Note nvarchar(2000) NULL,BrowserSequence bigint NOT NULL DEFAULT 0,MediaSequence bigint NOT NULL DEFAULT 0,
BrowserReceivedUtc datetime2 NULL,MediaReceivedUtc datetime2 NULL,PlaybackState varchar(20) NOT NULL DEFAULT 'unavailable',PositionSeconds float NULL,DurationSeconds float NULL,PlaybackRate float NOT NULL DEFAULT 1,
MediaKey nvarchar(100) NULL,Capabilities varchar(100) NULL,NativeInstance uniqueidentifier NULL,NativeDocument uniqueidentifier NULL,NativeGrant nvarchar(200) NULL,
CommandID uniqueidentifier NULL,Command varchar(20) NULL,CommandUtc datetime2 NULL,LastError nvarchar(200) NULL,Pauses int NOT NULL DEFAULT 0,Seeks int NOT NULL DEFAULT 0);
CREATE UNIQUE INDEX IX_WriterWork_Open ON dbo.WriterWorkSessions(UserID,BookID) WHERE EndedUtc IS NULL;
CREATE INDEX IX_WriterWork_History ON dbo.WriterWorkSessions(BookID,UserID,StartedUtc DESC);
CREATE TABLE dbo.WriterWorkDays(SessionID uniqueidentifier NOT NULL REFERENCES dbo.WriterWorkSessions(SessionID) ON DELETE CASCADE,Day date NOT NULL,EngagedSeconds int NOT NULL DEFAULT 0,PlaybackSeconds float NOT NULL DEFAULT 0,PRIMARY KEY(SessionID,Day));
END;
IF NOT EXISTS(SELECT 1 FROM sys.indexes WHERE object_id=OBJECT_ID('dbo.WriterWorkSessions') AND name='IX_WriterWork_AudioPreference') CREATE INDEX IX_WriterWork_AudioPreference ON dbo.WriterWorkSessions(BookID,UserID,StartedUtc DESC) INCLUDE(PauseOnEdit) WHERE Kind='AudioReview';
IF COL_LENGTH('dbo.WriterWorkSessions','StartRevision') IS NULL ALTER TABLE dbo.WriterWorkSessions ADD StartRevision bigint NULL,EndRevision bigint NULL,StartParagraphCount int NULL,EndParagraphCount int NULL;
GO
CREATE OR ALTER PROCEDURE dbo.WriterWork
@Action varchar(20),@UserID int,@BookID int,@SessionID uniqueidentifier=NULL,@ChapterID int=NULL,@Kind varchar(20)=NULL,
@Sequence bigint=0,@Engaged bit=0,@Day date=NULL,@Note nvarchar(2000)=NULL,@PauseOnEdit bit=1,@NativeInstance uniqueidentifier=NULL,@NativeDocument uniqueidentifier=NULL,@NativeGrant nvarchar(200)=NULL,
@PlaybackSeconds float=0,@UniqueSeconds float=0,@RangesJson nvarchar(max)=N'[]',@CoveragePartial bit=0,@PlaybackState varchar(20)='unavailable',@PositionSeconds float=NULL,@DurationSeconds float=NULL,@PlaybackRate float=1,
@MediaKey nvarchar(100)=NULL,@Capabilities varchar(100)=NULL,@CommandID uniqueidentifier=NULL,@Command varchar(20)=NULL,@CommandUtc datetime2=NULL,@LastError nvarchar(200)=NULL,@Pauses int=0,@Seeks int=0
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE b.BookID=@BookID AND b.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole='Owner') THROW 51000,'Owner authority required',1;
DECLARE @now datetime2=SYSUTCDATETIME();
IF @Action IN('read','state') BEGIN IF @Action='state' SELECT TOP(1) PauseOnEdit FROM dbo.WriterWorkSessions WHERE UserID=@UserID AND BookID=@BookID AND Kind='AudioReview' ORDER BY StartedUtc DESC;SELECT TOP(CASE WHEN @Action='state' THEN 1 ELSE 50 END) s.SessionID,s.UserID,s.BookID,s.ChapterID,s.Kind,s.StartedUtc,s.EndedUtc,s.LastSeenUtc,s.EngagedSeconds,s.PlaybackSeconds,s.UniqueSeconds,s.CoveragePartial,s.PauseOnEdit,s.Note,s.BrowserSequence,s.MediaSequence,s.MediaReceivedUtc,s.PlaybackState,s.PositionSeconds,s.DurationSeconds,s.PlaybackRate,s.MediaKey,s.Capabilities,s.NativeInstance,s.NativeDocument,s.NativeGrant,s.CommandID,s.Command,s.CommandUtc,s.LastError,s.Pauses,s.Seeks,s.StartRevision,s.EndRevision,s.StartParagraphCount,s.EndParagraphCount,c.ChapterTitle FROM dbo.WriterWorkSessions s LEFT JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID AND c.BookID=s.BookID WHERE s.UserID=@UserID AND s.BookID=@BookID AND (@Action<>'state' OR s.EndedUtc IS NULL) AND (@Day IS NULL OR CONVERT(date,s.StartedUtc)=@Day OR EXISTS(SELECT 1 FROM dbo.WriterWorkDays d WHERE d.SessionID=s.SessionID AND d.Day=@Day)) ORDER BY s.StartedUtc DESC OPTION(RECOMPILE);RETURN;END;
IF @Action='erase' BEGIN DELETE dbo.WriterWorkSessions WHERE UserID=@UserID AND BookID=@BookID;RETURN;END;
IF @Action='start'
BEGIN
IF @SessionID IS NULL OR @Kind IS NULL OR @Kind NOT IN('Writing','Editing','Planning','Reading','AudioReview') THROW 51000,'Invalid session',1;
IF @ChapterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChapterID AND BookID=@BookID AND IsArchived=0) THROW 51000,'Chapter unavailable',1;
IF EXISTS(SELECT 1 FROM dbo.WritingActivitySettings WHERE BookID=@BookID AND Enabled=0) THROW 51000,'Activity recording is paused in Reports',1;
BEGIN TRANSACTION;
-- Serialize starts for this book without touching canonical manuscript rows.
SELECT BookID FROM dbo.Books WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
IF EXISTS(SELECT 1 FROM dbo.WriterWorkSessions WHERE SessionID=@SessionID)
BEGIN
IF NOT EXISTS(SELECT 1 FROM dbo.WriterWorkSessions WHERE SessionID=@SessionID AND UserID=@UserID AND BookID=@BookID AND Kind=@Kind AND ISNULL(ChapterID,0)=ISNULL(@ChapterID,0)) THROW 51000,'Session identity conflict',1;
END
ELSE
BEGIN
UPDATE dbo.WriterWorkSessions SET EndedUtc=LastSeenUtc WHERE UserID=@UserID AND BookID=@BookID AND EndedUtc IS NULL;
DECLARE @startRevision bigint,@startParagraphs int;
SELECT @startRevision=Revision,@startParagraphs=(SELECT COUNT(*) FROM OPENJSON(Payload,'$.Paragraphs')) FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;
INSERT dbo.WriterWorkSessions(StartRevision,StartParagraphCount,SessionID,UserID,BookID,ChapterID,Kind,StartedUtc,LastSeenUtc,PauseOnEdit,NativeInstance,NativeDocument,NativeGrant) VALUES(@startRevision,@startParagraphs,@SessionID,@UserID,@BookID,@ChapterID,@Kind,@now,@now,@PauseOnEdit,@NativeInstance,@NativeDocument,@NativeGrant);
END;
COMMIT;RETURN;
END;
IF @Action='lock' BEGIN SELECT * FROM dbo.WriterWorkSessions WITH(UPDLOCK,HOLDLOCK) WHERE SessionID=@SessionID AND UserID=@UserID AND BookID=@BookID AND EndedUtc IS NULL;RETURN;END;
IF @Action='command'
BEGIN
IF @Command NOT IN('play','pause','back15','forward15') THROW 51000,'Unsupported media operation',1;
UPDATE dbo.WriterWorkSessions SET CommandID=@CommandID,Command=@Command,CommandUtc=@now WHERE SessionID=@SessionID AND UserID=@UserID AND BookID=@BookID AND EndedUtc IS NULL AND Kind='AudioReview' AND StartedUtc>DATEADD(hour,-12,@now) AND MediaReceivedUtc>DATEADD(second,-45,@now) AND PlaybackState NOT IN('unavailable','error');
IF @@ROWCOUNT=0 THROW 51000,'No live supported media session',1;RETURN;
END;
IF @Action='end' BEGIN DECLARE @endRevision bigint,@endParagraphs int;SELECT @endRevision=Revision,@endParagraphs=(SELECT COUNT(*) FROM OPENJSON(Payload,'$.Paragraphs')) FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;UPDATE dbo.WriterWorkSessions SET EndRevision=COALESCE(EndRevision,@endRevision),EndParagraphCount=COALESCE(EndParagraphCount,@endParagraphs), EndedUtc=COALESCE(EndedUtc,CASE WHEN StartedUtc<DATEADD(hour,-12,@now) THEN LastSeenUtc ELSE @now END),Note=@Note,CommandID=NULL,Command=NULL WHERE SessionID=@SessionID AND UserID=@UserID AND BookID=@BookID;RETURN;END;
IF @Action='preference' BEGIN UPDATE dbo.WriterWorkSessions SET PauseOnEdit=@PauseOnEdit WHERE SessionID=@SessionID AND UserID=@UserID AND BookID=@BookID AND EndedUtc IS NULL;RETURN;END;
IF @Action NOT IN('heartbeat','media') THROW 51000,'Unknown session action',1;
IF @Sequence<=0 THROW 51000,'Invalid observation sequence',1;
IF EXISTS(SELECT 1 FROM dbo.WritingActivitySettings WHERE BookID=@BookID AND Enabled=0) THROW 51000,'Activity recording is paused in Reports',1;
BEGIN TRANSACTION;
DECLARE @last datetime2,@prior bigint,@started datetime2;
SELECT @last=CASE WHEN @Action='heartbeat' THEN COALESCE(BrowserReceivedUtc,StartedUtc) ELSE COALESCE(MediaReceivedUtc,StartedUtc) END,@prior=CASE WHEN @Action='heartbeat' THEN BrowserSequence ELSE MediaSequence END,@started=StartedUtc FROM dbo.WriterWorkSessions WITH(UPDLOCK,HOLDLOCK) WHERE SessionID=@SessionID AND UserID=@UserID AND BookID=@BookID AND EndedUtc IS NULL;
IF @last IS NULL OR @started<DATEADD(hour,-12,@now) THROW 51000,'Session ended or expired; start a new session',1;
IF @Sequence<=@prior BEGIN COMMIT;RETURN;END;
DECLARE @seconds int=CASE WHEN @Action='heartbeat' AND @Engaged=1 AND DATEDIFF(second,@last,@now) BETWEEN 1 AND 35 THEN DATEDIFF(second,@last,@now) ELSE 0 END;
IF @seconds>30 SET @seconds=30;
IF @PlaybackSeconds<0 OR @PlaybackSeconds>30 OR @UniqueSeconds<0 OR @UniqueSeconds>86400 OR ISJSON(@RangesJson)<>1 OR LEN(@RangesJson)>250000 THROW 51000,'Invalid playback measurements',1;
UPDATE dbo.WriterWorkSessions SET LastSeenUtc=@now,EngagedSeconds=EngagedSeconds+@seconds,
BrowserSequence=CASE WHEN @Action='heartbeat' THEN @Sequence ELSE BrowserSequence END,BrowserReceivedUtc=CASE WHEN @Action='heartbeat' THEN @now ELSE BrowserReceivedUtc END,
MediaSequence=CASE WHEN @Action='media' THEN @Sequence ELSE MediaSequence END,
PlaybackSeconds=PlaybackSeconds+CASE WHEN @Action='media' THEN @PlaybackSeconds ELSE 0 END,
UniqueSeconds=CASE WHEN @Action='media' THEN @UniqueSeconds ELSE UniqueSeconds END,
RangesJson=CASE WHEN @Action='media' THEN @RangesJson ELSE RangesJson END,CoveragePartial=CASE WHEN @Action='media' THEN @CoveragePartial ELSE CoveragePartial END,
MediaReceivedUtc=CASE WHEN @Action='media' THEN @now ELSE MediaReceivedUtc END,
PlaybackState=CASE WHEN @Action='media' THEN @PlaybackState ELSE PlaybackState END,
PositionSeconds=CASE WHEN @Action='media' THEN @PositionSeconds ELSE PositionSeconds END,DurationSeconds=CASE WHEN @Action='media' THEN @DurationSeconds ELSE DurationSeconds END,
PlaybackRate=CASE WHEN @Action='media' THEN @PlaybackRate ELSE PlaybackRate END,MediaKey=CASE WHEN @Action='media' THEN @MediaKey ELSE MediaKey END,Capabilities=CASE WHEN @Action='media' THEN @Capabilities ELSE Capabilities END,
CommandID=CASE WHEN @Action='media' THEN @CommandID ELSE CommandID END,Command=CASE WHEN @Action='media' THEN @Command ELSE Command END,CommandUtc=CASE WHEN @Action='media' THEN @CommandUtc ELSE CommandUtc END,
LastError=CASE WHEN @Action='media' THEN @LastError ELSE LastError END,Pauses=Pauses+@Pauses,Seeks=Seeks+@Seeks
WHERE SessionID=@SessionID;
-- Receipt-day accounting: each bounded interval is attributed to its receipt day (UTC).
IF EXISTS(SELECT 1 FROM dbo.WriterWorkDays WHERE SessionID=@SessionID AND Day=CONVERT(date,@now)) UPDATE dbo.WriterWorkDays SET EngagedSeconds=EngagedSeconds+@seconds,PlaybackSeconds=PlaybackSeconds+@PlaybackSeconds WHERE SessionID=@SessionID AND Day=CONVERT(date,@now);
ELSE INSERT dbo.WriterWorkDays(SessionID,Day,EngagedSeconds,PlaybackSeconds) VALUES(@SessionID,CONVERT(date,@now),@seconds,@PlaybackSeconds);
COMMIT;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterWorkCalendar @UserID int,@BookID int,@Year int
AS
BEGIN
SET NOCOUNT ON;
IF @Year NOT BETWEEN 2000 AND 2100 THROW 51000,'Invalid year',1;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE b.BookID=@BookID AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole='Owner') THROW 51000,'Owner authority required',1;
DECLARE @start date=DATEFROMPARTS(@Year,1,1),@end date=DATEFROMPARTS(@Year+1,1,1);
WITH measurements AS(
SELECT CONVERT(date,ReceivedUtc) Day,SUM(CONVERT(bigint,Added)) Added,SUM(CONVERT(bigint,Removed)) Removed,COUNT(*) Changes,0 Writing,0 Editing,0 Planning,0 Reading,0 AudioReview,0 EngagedSeconds,CONVERT(float,0) PlaybackSeconds
FROM dbo.WritingActivityEvents WHERE BookID=@BookID AND Kind='Change' AND ReceivedUtc>=@start AND ReceivedUtc<@end GROUP BY CONVERT(date,ReceivedUtc)
UNION ALL
SELECT d.Day,0,0,0,COUNT(CASE WHEN s.Kind='Writing' THEN 1 END),COUNT(CASE WHEN s.Kind='Editing' THEN 1 END),COUNT(CASE WHEN s.Kind='Planning' THEN 1 END),COUNT(CASE WHEN s.Kind='Reading' THEN 1 END),COUNT(CASE WHEN s.Kind='AudioReview' AND d.PlaybackSeconds>0 THEN 1 END),SUM(d.EngagedSeconds),SUM(d.PlaybackSeconds)
FROM dbo.WriterWorkDays d JOIN dbo.WriterWorkSessions s ON s.SessionID=d.SessionID WHERE s.UserID=@UserID AND s.BookID=@BookID AND d.Day>=@start AND d.Day<@end GROUP BY d.Day
UNION ALL
SELECT CONVERT(date,StartedUtc),0,0,0,COUNT(CASE WHEN Kind='Writing' THEN 1 END),COUNT(CASE WHEN Kind='Editing' THEN 1 END),COUNT(CASE WHEN Kind='Planning' THEN 1 END),COUNT(CASE WHEN Kind='Reading' THEN 1 END),0,0,0
FROM dbo.WriterWorkSessions s WHERE UserID=@UserID AND BookID=@BookID AND StartedUtc>=@start AND StartedUtc<@end AND NOT EXISTS(SELECT 1 FROM dbo.WriterWorkDays d WHERE d.SessionID=s.SessionID AND d.Day=CONVERT(date,s.StartedUtc)) GROUP BY CONVERT(date,StartedUtc)
) SELECT Day,SUM(Added) Added,SUM(Removed) Removed,SUM(Changes) Changes,SUM(Writing) Writing,SUM(Editing) Editing,SUM(Planning) Planning,SUM(Reading) Reading,SUM(AudioReview) AudioReview,SUM(EngagedSeconds) EngagedSeconds,SUM(PlaybackSeconds) PlaybackSeconds FROM measurements GROUP BY Day ORDER BY Day;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterWork_Prune AS
BEGIN
SET NOCOUNT ON;
DELETE s FROM dbo.WriterWorkSessions s LEFT JOIN dbo.WritingActivitySettings p ON p.BookID=s.BookID WHERE s.StartedUtc<DATEADD(day,-COALESCE(p.RetentionDays,365),SYSUTCDATETIME());
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterWorkEvidence @UserID int,@BookID int,@Day date=NULL
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE b.BookID=@BookID AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole='Owner') THROW 51000,'Owner authority required',1;
WITH recent AS(SELECT TOP(50) * FROM dbo.WriterWorkSessions WHERE UserID=@UserID AND BookID=@BookID AND (@Day IS NULL OR CONVERT(date,StartedUtc)=@Day OR EXISTS(SELECT 1 FROM dbo.WriterWorkDays d WHERE d.SessionID=WriterWorkSessions.SessionID AND d.Day=@Day)) ORDER BY StartedUtc DESC)
SELECT s.SessionID,e.ChangesDuringSession,e.AdditionsDuringSession,e.RemovalsDuringSession,paragraphs.ChangedParagraphs
FROM recent s OUTER APPLY(
SELECT COUNT(*) ChangesDuringSession,COALESCE(SUM(CONVERT(bigint,Added)),0) AdditionsDuringSession,COALESCE(SUM(CONVERT(bigint,Removed)),0) RemovalsDuringSession FROM dbo.WritingActivityEvents e
WHERE e.BookID=@BookID AND e.UserID=@UserID AND e.Kind='Change' AND e.ReceivedUtc>=s.StartedUtc AND e.ReceivedUtc<=COALESCE(s.EndedUtc,s.LastSeenUtc)
) e OUTER APPLY(
SELECT COUNT(DISTINCT JSON_VALUE(p.value,'$.ParagraphID')) ChangedParagraphs FROM dbo.WritingActivityEvents event CROSS APPLY OPENJSON(event.Scopes) p
WHERE event.BookID=@BookID AND event.UserID=@UserID AND event.Kind='Change' AND event.ReceivedUtc>=s.StartedUtc AND event.ReceivedUtc<=COALESCE(s.EndedUtc,s.LastSeenUtc)
AND (s.ChapterID IS NULL OR TRY_CONVERT(int,JSON_VALUE(p.value,'$.ChapterID'))=s.ChapterID OR TRY_CONVERT(int,JSON_VALUE(p.value,'$.BeforeChapterID'))=s.ChapterID)
) paragraphs;
END;
GO

View File

@ -0,0 +1,74 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
IF OBJECT_ID(N'dbo.WriterPlannedActivities',N'U') IS NULL
BEGIN
CREATE TABLE dbo.WriterPlannedActivities(ActivityID int IDENTITY PRIMARY KEY,WritingPlanID int NOT NULL REFERENCES dbo.WritingPlans(WritingPlanID) ON DELETE CASCADE,BookID int NOT NULL,ChapterID int NOT NULL,SceneID int NULL,Kind varchar(20) NOT NULL,Minutes int NOT NULL CHECK(Minutes BETWEEN 1 AND 1440),ScheduledDate date NOT NULL,Status varchar(20) NOT NULL DEFAULT 'Planned' CHECK(Status IN('Planned','Done')));
CREATE INDEX IX_WriterPlanned_Plan ON dbo.WriterPlannedActivities(WritingPlanID,ScheduledDate);
END;
IF NOT EXISTS(SELECT 1 FROM sys.foreign_keys WHERE name='FK_WriterPlanned_Book') ALTER TABLE dbo.WriterPlannedActivities ADD CONSTRAINT FK_WriterPlanned_Book FOREIGN KEY(BookID) REFERENCES dbo.Books(BookID) ON DELETE CASCADE;
IF NOT EXISTS(SELECT 1 FROM sys.foreign_keys WHERE name='FK_WriterPlanned_Chapter') ALTER TABLE dbo.WriterPlannedActivities ADD CONSTRAINT FK_WriterPlanned_Chapter FOREIGN KEY(ChapterID) REFERENCES dbo.Chapters(ChapterID) ON DELETE CASCADE;
IF NOT EXISTS(SELECT 1 FROM sys.foreign_keys WHERE name='FK_WriterPlanned_Scene') ALTER TABLE dbo.WriterPlannedActivities ADD CONSTRAINT FK_WriterPlanned_Scene FOREIGN KEY(SceneID) REFERENCES dbo.Scenes(SceneID) ON DELETE CASCADE;
GO
CREATE OR ALTER PROCEDURE dbo.WriterPlanning @Action varchar(20),@UserID int,@WritingPlanID int,@Items nvarchar(max)=NULL,@ActivityID int=NULL
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
DECLARE @project int,@book int,@start date,@end date,@blocked bit;
SELECT @project=p.ProjectID,@book=p.BookID,@start=p.StartDate,@end=p.DeadlineDate,@blocked=p.IncludeBlockedScenes FROM dbo.WritingPlans p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE p.WritingPlanID=@WritingPlanID AND p.UserID=@UserID;
IF @project IS NULL THROW 51000,'Plan access denied',1;
IF @Action='context'
BEGIN
SELECT COUNT(DISTINCT c.ChapterID) Chapters,COUNT(s.SceneID) Scenes,COALESCE(SUM(CASE WHEN sw.IsBlocked=1 THEN 1 ELSE 0 END),0) Blocked,
COALESCE(SUM(CASE WHEN scheduled.SceneID IS NOT NULL THEN 1 ELSE 0 END),0) ExistingTasks
FROM dbo.Books b JOIN dbo.Chapters c ON c.BookID=b.BookID AND c.IsArchived=0 LEFT JOIN dbo.Scenes s ON s.ChapterID=c.ChapterID AND s.IsArchived=0 LEFT JOIN dbo.SceneWorkflow sw ON sw.SceneID=s.SceneID
LEFT JOIN(SELECT DISTINCT SceneID FROM dbo.WritingScheduleItems WHERE WritingPlanID=@WritingPlanID) scheduled ON scheduled.SceneID=s.SceneID
WHERE b.ProjectID=@project AND b.IsArchived=0 AND (@book IS NULL OR b.BookID=@book);RETURN;
END;
IF @Action='candidates'
BEGIN
SELECT TOP(1000) b.BookID,c.ChapterID,s.SceneID,COALESCE(s.SceneTitle,c.ChapterTitle) Title,b.BookTitle,rs.StatusName RevisionStatus,sw.EstimatedWordCount Words
FROM dbo.Books b JOIN dbo.Chapters c ON c.BookID=b.BookID AND c.IsArchived=0 LEFT JOIN dbo.Scenes s ON s.ChapterID=c.ChapterID AND s.IsArchived=0 LEFT JOIN dbo.SceneWorkflow sw ON sw.SceneID=s.SceneID LEFT JOIN dbo.RevisionStatuses rs ON rs.RevisionStatusID=COALESCE(s.RevisionStatusID,c.RevisionStatusID)
WHERE b.ProjectID=@project AND b.IsArchived=0 AND (@book IS NULL OR b.BookID=@book) AND (@blocked=1 OR COALESCE(sw.IsBlocked,0)=0)
AND NOT EXISTS(SELECT 1 FROM dbo.WritingScheduleItems existing WHERE existing.WritingPlanID=@WritingPlanID AND existing.SceneID=s.SceneID)
ORDER BY COALESCE(sw.Priority,0) DESC,b.SortOrder,c.SortOrder,s.SortOrder,c.ChapterID,s.SceneID;
RETURN;
END;
IF @Action='list'
BEGIN
SELECT a.*,COALESCE(s.SceneTitle,c.ChapterTitle) Title,b.BookTitle FROM dbo.WriterPlannedActivities a JOIN dbo.Books b ON b.BookID=a.BookID AND b.IsArchived=0 JOIN dbo.Chapters c ON c.ChapterID=a.ChapterID AND c.BookID=b.BookID AND c.IsArchived=0 LEFT JOIN dbo.Scenes s ON s.SceneID=a.SceneID AND s.ChapterID=c.ChapterID AND s.IsArchived=0 WHERE a.WritingPlanID=@WritingPlanID AND (a.SceneID IS NULL OR s.SceneID IS NOT NULL) ORDER BY a.ScheduledDate,a.ActivityID;RETURN;
END;
IF @Action='complete' BEGIN UPDATE dbo.WriterPlannedActivities SET Status='Done' WHERE WritingPlanID=@WritingPlanID AND ActivityID=@ActivityID;RETURN;END;
IF @Action<>'save' OR ISJSON(@Items)<>1 THROW 51000,'Invalid planned activities',1;
DECLARE @rows TABLE(BookID int,ChapterID int,SceneID int,Kind varchar(20),Minutes int,ScheduledDate date);
INSERT @rows SELECT BookID,ChapterID,SceneID,Kind,Minutes,ScheduledDate FROM OPENJSON(@Items) WITH(BookID int,ChapterID int,SceneID int,Kind varchar(20),Minutes int,ScheduledDate date);
IF NOT EXISTS(SELECT 1 FROM @rows) OR (SELECT COUNT(*) FROM @rows)>20000 THROW 51000,'Choose activities',1;
IF EXISTS(SELECT 1 FROM @rows r LEFT JOIN dbo.Books b ON b.BookID=r.BookID LEFT JOIN dbo.Chapters c ON c.ChapterID=r.ChapterID LEFT JOIN dbo.Scenes s ON s.SceneID=r.SceneID LEFT JOIN dbo.SceneWorkflow sw ON sw.SceneID=r.SceneID
WHERE b.ProjectID<>@project OR b.BookID IS NULL OR b.IsArchived=1 OR (@book IS NOT NULL AND r.BookID<>@book) OR c.ChapterID IS NULL OR c.BookID<>b.BookID OR c.IsArchived=1 OR (r.SceneID IS NOT NULL AND (s.SceneID IS NULL OR s.ChapterID<>c.ChapterID OR s.IsArchived=1)) OR (@blocked=0 AND COALESCE(sw.IsBlocked,0)=1) OR r.Kind IS NULL OR r.Kind NOT IN('Draft','Edit','Plan','Review','AudioReview') OR r.Minutes IS NULL OR r.Minutes NOT BETWEEN 1 AND 1440 OR r.ScheduledDate IS NULL OR r.ScheduledDate NOT BETWEEN @start AND @end) THROW 51000,'Activities no longer match this plan',1;
BEGIN TRANSACTION;
DECLARE @locked int;SELECT @locked=WritingPlanID FROM dbo.WritingPlans WITH(UPDLOCK,HOLDLOCK) WHERE WritingPlanID=@WritingPlanID;
IF EXISTS(SELECT 1 FROM dbo.WriterPlannedActivities WHERE WritingPlanID=@WritingPlanID AND Status='Done') THROW 51000,'Completed activities are preserved; create a new plan for another pass',1;
DELETE dbo.WriterPlannedActivities WHERE WritingPlanID=@WritingPlanID;
INSERT dbo.WriterPlannedActivities(WritingPlanID,BookID,ChapterID,SceneID,Kind,Minutes,ScheduledDate) SELECT @WritingPlanID,BookID,ChapterID,SceneID,Kind,Minutes,ScheduledDate FROM @rows;
COMMIT;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterPlanningUpcoming @UserID int,@BookID int
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE b.BookID=@BookID AND a.UserID=@UserID AND a.IsActive=1) THROW 51000,'Book access denied',1;
SELECT TOP(10) a.*,COALESCE(s.SceneTitle,c.ChapterTitle) Title,b.BookTitle FROM dbo.WriterPlannedActivities a JOIN dbo.WritingPlans p ON p.WritingPlanID=a.WritingPlanID AND p.UserID=@UserID AND p.IsActive=1 JOIN dbo.Books b ON b.BookID=a.BookID AND b.IsArchived=0 JOIN dbo.Chapters c ON c.ChapterID=a.ChapterID AND c.BookID=b.BookID AND c.IsArchived=0 LEFT JOIN dbo.Scenes s ON s.SceneID=a.SceneID AND s.ChapterID=c.ChapterID AND s.IsArchived=0 WHERE a.BookID=@BookID AND a.Status='Planned' AND (a.SceneID IS NULL OR s.SceneID IS NOT NULL) ORDER BY a.ScheduledDate,a.ActivityID;
END;
GO
-- Preserve existing manual scene-task management while including reviewed chapter activities.
CREATE OR ALTER PROCEDURE dbo.WritingPlan_ListForManagement @UserID int
AS
BEGIN
SET NOCOUNT ON;
SELECT p.WritingPlanID,p.UserID,p.ProjectID,project.ProjectName,p.BookID,b.BookTitle,b.Subtitle BookSubtitle,p.PlanName,p.GoalType,p.StartDate,p.DeadlineDate,p.AvailableDaysJson,p.SessionLengthMinutes,p.IsActive,
(SELECT COUNT(*) FROM dbo.WritingScheduleItems WHERE WritingPlanID=p.WritingPlanID AND ScheduleStatus='Planned')+(SELECT COUNT(*) FROM dbo.WriterPlannedActivities WHERE WritingPlanID=p.WritingPlanID AND Status='Planned') PlannedTaskCount,
(SELECT MAX(d) FROM(SELECT ScheduledDate d FROM dbo.WritingScheduleItems WHERE WritingPlanID=p.WritingPlanID AND ScheduleStatus='Planned' UNION ALL SELECT ScheduledDate FROM dbo.WriterPlannedActivities WHERE WritingPlanID=p.WritingPlanID AND Status='Planned') dates) ProjectedFinishDate
FROM dbo.WritingPlans p JOIN dbo.Projects project ON project.ProjectID=p.ProjectID LEFT JOIN dbo.Books b ON b.BookID=p.BookID WHERE p.UserID=@UserID ORDER BY p.IsActive DESC,p.DeadlineDate,p.PlanName,p.WritingPlanID;
END;
GO

View File

@ -925,6 +925,9 @@ public sealed class ChapterWorkflowViewModel
public sealed class WriterDashboardViewModel
{
public IReadOnlyList<WriterPlanActivity> PlannedActivities { get; set; } = [];
public WriterWorkPage? Work { get; set; }
public IReadOnlyList<WriterSuggestion> Suggestions { get; set; } = [];
public WriterObjective? Objective { get; set; }
public IReadOnlyList<WriterObjectiveChoice> ObjectiveChoices { get; set; } = [];
public int? BookID { get; set; }
@ -1052,6 +1055,7 @@ public sealed class WritingScheduleItemViewModel
public sealed class WritingSchedulePreviewViewModel
{
public IReadOnlyList<WriterPlanActivity> DerivedActivities { get; set; } = [];
public int? SelectedWritingPlanID { get; set; }
public IReadOnlyList<WritingPlanSummary> Plans { get; set; } = [];
public IReadOnlyList<WritingPlanSummary> PlansRequiringRebalance { get; set; } = [];

View File

@ -2,7 +2,9 @@
@{
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");
}
<link rel="stylesheet" href="~/css/writer-work.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/manuscript-reader.css" asp-append-version="true" />
<div class="manuscript-reader" data-focus="@(Model.FocusReading ? "true" : "false")"
data-book-id="@Model.Book.BookID" data-chapter-id="@Model.Chapter?.ChapterID" data-chapter-number="@Model.Chapter?.ChapterNumber"
@ -48,6 +50,8 @@
{ <p>Accepted manuscript snapshot captured: <time datetime="@captured.ToString("yyyy-MM-ddTHH:mm:ssZ")">@captured.ToString("dd MMM yyyy HH:mm:ss") UTC</time></p> }
<p>Showing accepted server text. Changes are checked automatically while this page is visible.</p>
</div>
<details><summary>Reading &amp; Audio Review</summary><partial name="_WriterWorkToolbar" model="reviewToolbar" /></details>
<a asp-controller="Writer" asp-action="Index" asp-route-bookId="@Model.Book.BookID">Return to Writing</a>
<div id="reader-content">
@if (Model.Paragraphs.Count == 0)
{
@ -73,3 +77,5 @@
</footer>
</div>
<script src="~/js/manuscript-reader.js" asp-append-version="true" defer></script>
<script src="~/js/writer-work.js" asp-append-version="true" defer></script>

View File

@ -0,0 +1,25 @@
@model PlotLine.Models.WriterWorkToolbar
<section class="writer-work-toolbar" data-writer-work data-book-id="@Model.BookID" data-fixed-chapter="@Model.ChapterID" aria-label="Writing Rhythm and Audio Review">
<form data-work-start>
@Html.AntiForgeryToken()
<div class="button-row">
<label>Activity<select name="kind" class="form-select"><option value="Writing" selected="@(Model.DefaultKind=="Writing")">Writing</option><option value="Editing" selected="@(Model.DefaultKind=="Editing")">Editing</option><option value="Planning" selected="@(Model.DefaultKind=="Planning")">Planning</option><option value="Reading" selected="@(Model.DefaultKind=="Reading")">Reading review</option><option value="AudioReview" selected="@(Model.DefaultKind=="AudioReview")">Audio Review</option></select></label>
@if(Model.Choices!=null){<label>Chapter<select name="chapterId" class="form-select"><option value="">Whole book</option>@foreach(var choice in Model.Choices.DistinctBy(x=>x.ChapterID)){<option value="@choice.ChapterID" selected="@(Model.ChapterID==choice.ChapterID)">@choice.ChapterTitle</option>}</select></label>}
else{<span>@Model.ChapterTitle</span><input type="hidden" name="chapterId" value="@Model.ChapterID" />}
<button class="btn btn-primary" type="submit">Start session</button>
</div>
</form>
<div data-work-current hidden><strong data-work-label></strong><span data-work-elapsed></span><span data-work-measured></span>
<label>Return / review note (optional)<textarea data-work-note class="form-control" maxlength="2000" rows="2"></textarea></label>
<button class="btn btn-outline-secondary" data-work-end type="button">End session &amp; save note</button>
</div>
<div data-work-audio hidden>
<h3>Audio Review <small data-audio-chapter>@Model.ChapterTitle</small></h3>
<p data-audio-state role="status">Windows media support has not been reported.</p>
<div class="button-row"><button type="button" class="btn btn-outline-primary" data-media-command="play" disabled>Play</button><button type="button" class="btn btn-outline-primary" data-media-command="pause" disabled>Pause</button><button type="button" class="btn btn-outline-secondary" data-media-command="back15" disabled>Back 15 seconds</button><button type="button" class="btn btn-outline-secondary" data-media-command="forward15" disabled>Forward 15 seconds</button></div>
<p data-audio-position></p><label><input type="checkbox" data-pause-on-edit checked /> Pause on Edit</label>
<p class="muted">End review stops tracking; Pause first to stop external playback. Actual text changes pause playback when supported by Companion. Scrolling and cursor movement do not. Resume is always explicit. Start again after Companion registers a session for this book if the review began without one.</p>
</div>
<p class="muted">Explicit sessions record browser engagement separately from elapsed time. Audio time requires consecutive player observations; playback does not prove attention. Overlapping browser and audio durations are not added together.</p>
<p role="status" data-work-message></p><a asp-controller="Writer" asp-action="Journey" asp-route-bookId="@Model.BookID">Writing Rhythm &amp; Journey</a>
</section>

View File

@ -18,6 +18,7 @@
</div>
</div>
<p>Changing availability does not silently move reviewed chapter activities. <a asp-controller="WriterPlanning" asp-action="Index" asp-route-writingPlanId="@Model.WritingPlanID">Review and reallocate them</a> after saving; completed activities are preserved.</p>
<section class="story-bible-section">
<form asp-action="EditWritingPlan" method="post" class="story-bible-card chapter-goal-form pd-record-form">
<div asp-validation-summary="ModelOnly" class="alert alert-warning"></div>

View File

@ -3,11 +3,13 @@
ViewData["Title"] = Model.Journey ? "Writing Journey" : "Writer";
ViewData["ShellClass"] = "pd-writer";
ViewData["ProjectSection"] = "Writer";
var toolbarKind = Model.Objective?.Activity is "Revising" or "Editing" or "Proofreading" ? "Editing" : Model.Objective?.Activity == "Researching" ? "Planning" : "Writing";
var seed=Model.WriteNext.Concat(Model.ContinueWriting).Concat(Model.RevisionQueue).Concat(Model.PolishingQueue).FirstOrDefault();
var bookId=Model.BookID??seed?.BookID;
var bookTitle=Model.Book?.BookDisplayTitle??seed?.BookDisplayTitle??"Choose a book";
if(string.IsNullOrWhiteSpace(bookTitle)) bookTitle = Model.BookID.HasValue ? "Untitled book" : "Choose a book";
var opportunity=Model.WritingSchedule.TodayTasks.FirstOrDefault()??Model.WritingSchedule.UpcomingTasks.FirstOrDefault();
var showOpportunity = Model.Objective != null || opportunity != null || Model.PlannedActivities.Count > 0;
var totals=Model.Activity?.Totals.HasAcceptedEvidence==true?Model.Activity.Totals:null;
var showWorkspace = Context.Request.RouteValues["action"]?.ToString() == "Workspaces";
var queues=new[]{("WriteNext","Write Next",Model.WriteNext),("InProgress","In Progress",Model.ContinueWriting),("Revision","Revision",Model.RevisionQueue),("FinalPass","Final Pass",Model.PolishingQueue)};
@ -16,6 +18,7 @@
var days=Model.Activity?.Days??Array.Empty<PlotLine.Models.WritingActivityDay>();
var maximum=Math.Max(1L,days.Select(x=>x.Added+x.Removed).DefaultIfEmpty(1).Max());
}
<link rel="stylesheet" href="~/css/writer-work.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/writer-dashboard.css" asp-append-version="true" />
<div class="writer-studio" data-writing-workspace-launcher data-compact-writer="true" data-project-id="@Model.ProjectID" data-book-id="@bookId">
<header class="writer-heading" data-pwa-task>
@ -27,13 +30,18 @@
@if(TempData["WriterWorkspaceError"] is string error){<p class="alert alert-warning" role="alert">@error</p>}
@if(!Model.Journey)
{
<section class="writer-next-grid" aria-label="Current work and next opportunity">
<partial name="_HelpMe" model="Model" />
<div id="working-focus"></div>
<section class="writer-next-grid @(showOpportunity ? "" : "writer-next-single")" aria-label="Current work and next opportunity">
<partial name="_WorkingObjective" model="Model" />
@if(showOpportunity){
<article class="writer-card"><p class="eyebrow">Next Planned Session</p>
@if(opportunity!=null){<h2>@opportunity.ScheduledDate.ToString("ddd d MMM")</h2><p>@opportunity.TaskType · @opportunity.EstimatedMinutes estimated minutes</p><a asp-controller="Scenes" asp-action="Edit" asp-route-id="@opportunity.SceneID">@opportunity.SceneTitle</a><p class="muted">Planned capacity, not measured writing time.</p>}
@if(Model.PlannedActivities.FirstOrDefault() is {} reviewed){<h2>@reviewed.ScheduledDate.ToString("ddd d MMM")</h2><p>@reviewed.Kind · @reviewed.Minutes planned minutes</p>@if(reviewed.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@reviewed.SceneID">@reviewed.Title</a>}else{<a asp-action="Chapter" asp-route-id="@reviewed.ChapterID">@reviewed.Title</a>}}
else if(opportunity!=null){<h2>@opportunity.ScheduledDate.ToString("ddd d MMM")</h2><p>@opportunity.TaskType · @opportunity.EstimatedMinutes estimated minutes</p><a asp-controller="Scenes" asp-action="Edit" asp-route-id="@opportunity.SceneID">@opportunity.SceneTitle</a><p class="muted">Planned capacity, not measured writing time.</p>}
else{<h2>Plan your writing time</h2><p>No upcoming writing task is scheduled for this book.</p><a class="btn btn-outline-primary" asp-action="ScheduleSetup" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@bookId">Create a writing plan</a>}
<a class="writer-text-link" asp-action="WritingPlans" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@bookId">Manage writing plans</a>
</article>
}
</section>
@if(!Model.ActivityIsPrivate)
{
@ -44,7 +52,7 @@
{
<div class="writer-activity-graphic"><div class="writer-change-track"><span class="writer-change-added" style="flex:@totals.Added"></span><span class="writer-change-removed" style="flex:@totals.Removed"></span></div><p><strong>+@totals.Added.ToString("N0")</strong> added · <strong>−@totals.Removed.ToString("N0")</strong> removed · <strong>@totals.Net.ToString("+0;-0;0")</strong> net</p></div>
}
else{<p class="writer-empty">@(totals?.HasAcceptedEvidence == true ? "Tracking begins at your manuscript baseline. New accepted changes will appear here." : "Activity begins with your first accepted manuscript baseline. Earlier writing cannot be reconstructed.")</p>}
else{<p class="writer-empty">@(totals?.HasAcceptedEvidence == true ? "Tracking begins at your manuscript baseline. New accepted changes will appear here." : "Manuscript change tracking begins with an accepted baseline. Earlier writing cannot be reconstructed.")</p>}
@if(queues.Any(q=>q.Item3.Count>0)){
<div class="writer-workflow-progress" aria-label="Scenes in writing workspace queues">@foreach(var q in queues.Where(x=>x.Item3.Count>0)){<span class="writer-stage-@q.Item1" style="flex:@q.Item3.Count" title="@q.Item2: @q.Item3.Count scenes"></span>}</div>
<div class="writer-workflow-strip" aria-label="Scene workflow stages">@foreach(var q in queues){<a asp-action="Workspaces" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@bookId" asp-route-workspace="@q.Item1"><strong>@q.Item3.Count</strong> @q.Item2</a>}</div>
@ -53,9 +61,11 @@
</section>
}
}
@if(Model.Journey){<partial name="_JourneyCalendar" model="Model" />}
else{
<section class="writer-card writer-journey @(Model.Journey ? "" : "writer-journey-compact")" aria-labelledby="writer-journey-title">
<div class="writer-section-heading"><div><p class="eyebrow">@(Model.Journey ? "Writing calendar · last 28 days" : "Activity summary · last 28 days")</p><h2 id="writer-journey-title">Recent Activity</h2></div><a asp-action="Journey" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@bookId">Writing Journey</a></div>
@if(totals==null||totals.RecordedEvents==0)
@if((totals==null||totals.RecordedEvents==0)&&!(Model.Work?.Days.Any(d=>d.Day>=DateTime.UtcNow.Date.AddDays(-27)&&d.Intensity>0)??false))
{
<p class="writer-empty">@(!Model.Journey?"No new accepted changes yet.":Model.Activity?.Totals.HasAcceptedEvidence==true?"No accepted change is recorded in this period. Retained baseline evidence is available in activity settings.":"Your accepted manuscript can become the starting point. Earlier writing will not be counted as new activity.")</p>
@if(Model.Journey&&bookId.HasValue&&!Model.ActivityIsPrivate){<a class="btn btn-outline-primary" asp-controller="WritingActivity" asp-action="Index" asp-route-bookId="@bookId">Activity &amp; baseline settings</a>}
@ -63,10 +73,8 @@
else
{
<div class="writer-calendar" aria-label="Daily observed changes; receipt dates in UTC">
@for(var i=27;i>=0;i--){var date=DateTime.UtcNow.Date.AddDays(-i);var day=days.FirstOrDefault(x=>x.Day.Date==date);<a class="writer-day @(day==null?"writer-day-unobserved":"writer-day-observed")" asp-controller="WritingActivity" asp-action="Index" asp-route-bookId="@bookId" asp-route-day="@date.ToString("yyyy-MM-dd")" aria-label="@date.ToString("d MMM yyyy"): @(day==null?"no recorded change":$"{day.Changes} changes, {day.Added} added, {day.Removed} removed")">@if(Model.Journey){<span>@date.ToString("ddd")</span><strong>@date.Day</strong><small>@(day==null?"—":$"+{day.Added} / −{day.Removed}")</small>}</a>}
@for(var i=27;i>=0;i--){var date=DateTime.UtcNow.Date.AddDays(-i);var day=days.FirstOrDefault(x=>x.Day.Date==date);var rhythm=Model.Work?.Days.FirstOrDefault(x=>x.Day.Date==date);var observed=day!=null||rhythm?.Intensity>0;<a class="writer-day @(!observed?"writer-day-unobserved":"writer-day-observed")" asp-controller="Writer" asp-action="Journey" asp-route-bookId="@bookId" asp-route-year="@date.Year" asp-route-month="@date.Month" asp-route-day="@date.ToString("yyyy-MM-dd")" aria-label="@date.ToString("d MMM yyyy"): @(!observed?"no retained activity":rhythm!=null?$"{rhythm.Changes} accepted changes, {rhythm.Planning} planning, {rhythm.Reading} reading and {rhythm.PlaybackSeconds:0} observed audio seconds":$"{day!.Changes} changes, {day.Added} added, {day.Removed} removed")">@if(Model.Journey){<span>@date.ToString("ddd")</span><strong>@date.Day</strong><small>@(day==null?"—":$"+{day.Added} / −{day.Removed}")</small>}</a>}
</div>
<p class="writer-coverage" hidden="@(!Model.Journey)"><strong>@totals.ActiveDays observed change days in the last 30 days.</strong> Receipt dates use UTC; they do not establish when the author wrote each word. Grey means no recorded change, not a missed opportunity. @if(totals.PartialComparisons>0){<span>@totals.PartialComparisons comparisons contain qualified minimum estimates.</span>}</p>
<details hidden="@(!Model.Journey)"><summary>Manuscript changes by day</summary><div class="writer-change-chart" aria-label="Observed additions and deletions with numeric labels">@foreach(var day in days){<a class="writer-change-row" asp-controller="WritingActivity" asp-action="Index" asp-route-bookId="@bookId" asp-route-day="@day.Day.ToString("yyyy-MM-dd")"><span>@day.Day.ToString("d MMM")</span><span class="writer-bar-track"><i class="writer-bar-added" style="width:@((100m*day.Added/maximum).ToString("0.##",System.Globalization.CultureInfo.InvariantCulture))%"></i><i class="writer-bar-removed" style="width:@((100m*day.Removed/maximum).ToString("0.##",System.Globalization.CultureInfo.InvariantCulture))%"></i></span><span>+@day.Added / −@day.Removed</span></a>}</div></details>
}
@if(Model.ActivityIsPrivate){<p class="muted">Activity evidence is private to the book owner. Your existing writing workspaces remain available.</p>}
@if(Model.Journey&&Model.Activity?.Events.Count>0)
@ -75,6 +83,8 @@ else
}
@if(Model.Journey&&Model.WritingSchedule.UpcomingTasks.Count>0){<h3 class="mt-3">Planned work ahead</h3><ul>@foreach(var item in Model.WritingSchedule.UpcomingTasks){<li>@item.ScheduledDate.ToString("ddd d MMM") · <a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">@item.SceneTitle</a> · @item.TaskType</li>}</ul>}
</section>
}
@if(bookId.HasValue&&!Model.ActivityIsPrivate){<partial name="_WriterWorkToolbar" model="new PlotLine.Models.WriterWorkToolbar(bookId.Value, Model.Objective?.ChapterID, Model.Objective?.ChapterTitle, Model.ObjectiveChoices, toolbarKind)" />}
<section class="writer-card writer-workspaces" id="workspaces" aria-labelledby="writer-workspace-title">
<div class="writer-section-heading"><div><p class="eyebrow">Workspaces</p><h2 id="writer-workspace-title">Choose your next step</h2></div>@if(bookId.HasValue){<a asp-controller="Books" asp-action="Details" asp-route-id="@bookId" asp-fragment="chapters">Browse chapters</a>}</div>
<details class="writer-queue-details" open="@showWorkspace"><summary>Chapter and scene workspaces</summary>
@ -95,6 +105,7 @@ else
@section Scripts {
<script src="~/js/writing-workspace.js" asp-append-version="true"></script>
<script src="~/js/writing-workspace-launcher.js" asp-append-version="true"></script>
<script src="~/js/writer-work.js" asp-append-version="true"></script>
<script src="~/js/writer-objective.js" asp-append-version="true"></script>
<script>(()=>{const open=()=>{if(location.hash==='#display-setup')document.getElementById('display-setup').open=true;};window.addEventListener('hashchange',open);open();})();</script>
}

View File

@ -1,6 +1,7 @@
@model WritingSchedulePreviewViewModel
@{
ViewData["Title"] = "Schedule Preview";
ViewData["WritingPlanID"] = Model.SelectedWritingPlanID;
var message = TempData["SchedulePreviewMessage"] as string;
var error = TempData["SchedulePreviewError"] as string;
}
@ -110,6 +111,9 @@ else
<div class="alert alert-warning">Schedule requires attention.</div>
}
<partial name="_PlannedActivities" model="Model.DerivedActivities" />
<a asp-controller="WriterPlanning" asp-action="Index" asp-route-writingPlanId="@Model.SelectedPlan.WritingPlanID">Review activities from chapters and scenes</a>
@if(Model.Items.Count>0){
<section class="story-bible-section">
<div class="story-bible-section-heading">
<div>
@ -127,6 +131,7 @@ else
</div>
</section>
}
<section class="story-bible-section">
<div class="story-bible-section-heading">
<div>
@ -138,7 +143,7 @@ else
@if (!Model.Items.Any())
{
<p class="muted">No schedule generated.</p>
@if(Model.DerivedActivities.Count==0){<p>No workflow scene tasks were generated. Review chapter and scene activities above, choose working budgets, then commit a schedule. If no candidates exist, add a chapter or review blocked-scene settings.</p>}
}
else
{

View File

@ -112,7 +112,7 @@
</div>
<div data-pwa-context="Record" data-pwa-priority="0" class="button-row mt-3">
<button class="btn btn-primary" data-pwa-icon="save" type="submit">Create Plan and Generate Schedule</button>
<button class="btn btn-primary" data-pwa-icon="save" type="submit">Review activities</button>
<a class="btn btn-outline-secondary" asp-action="SchedulePreview">Schedule Preview</a>
</div>
</form>

View File

@ -97,9 +97,10 @@
<button class="btn btn-sm btn-outline-secondary" type="submit">Activate Plan</button>
</form>
}
<a class="btn btn-sm btn-outline-primary" asp-controller="WriterPlanning" asp-action="Index" asp-route-writingPlanId="@plan.WritingPlanID">Review chapter activities</a>
<form asp-action="RegenerateWritingPlanSchedule" method="post">
<input type="hidden" name="writingPlanId" value="@plan.WritingPlanID" />
<button class="btn btn-sm btn-outline-primary" type="submit">Regenerate Schedule</button>
<button class="btn btn-sm btn-outline-primary" type="submit">Regenerate workflow scene tasks</button>
</form>
<button class="btn btn-sm btn-outline-danger" type="button" data-bs-toggle="modal" data-bs-target="#deleteWritingPlanModal-@plan.WritingPlanID">Delete Plan</button>
</div>

View File

@ -0,0 +1,16 @@
@model WriterDashboardViewModel
<section class="writer-help" aria-label="Help Me">
<button class="btn btn-danger btn-lg" type="button" data-writer-help aria-expanded="false" aria-controls="writer-help-options">Help Me</button>
<span>Choose a useful next action, or stay with your current work.</span>
<div id="writer-help-options" hidden>
<div class="writer-section-heading"><h2>What could I do next?</h2><button class="btn btn-outline-secondary" type="button" data-writer-help-close>Dismiss suggestions</button></div>
<div class="writer-help-grid">@foreach(var suggestion in Model.Suggestions){<article>
<p><strong>Observation:</strong> @suggestion.Observation</p>
@if(suggestion.Interpretation!=null){<p class="muted">Possible interpretation: @suggestion.Interpretation</p>}
<a class="btn btn-outline-primary" asp-controller="@suggestion.Controller" asp-action="@suggestion.RouteAction" asp-route-id="@suggestion.EntityID" asp-route-chapterId="@suggestion.ChapterID" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">@suggestion.Action</a>
</article>}</div>
@if(Model.Suggestions.Count==0){<p>Select a book to get suggestions based on its chapters and plans.</p>}
<a asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID" asp-fragment="working-focus">Return to Writing</a>
<p class="muted">For a break, end your session below and leave a return note. No time away is counted as engaged work.</p>
</div>
</section>

View File

@ -0,0 +1,13 @@
@model WriterDashboardViewModel
@{var work=Model.Work??new PlotLine.Models.WriterWorkPage{BookID=Model.BookID??0};var first=new DateTime(work.Year,work.Month,1);var offset=((int)first.DayOfWeek+6)%7;var days=work.Days.ToDictionary(x=>x.Day.Date);var maximum=Math.Max(1,days.Values.Select(x=>x.Intensity).DefaultIfEmpty(1).Max());int Level(PlotLine.Models.WriterWorkDay? day)=>day==null||day.Intensity==0?0:Math.Clamp((int)Math.Ceiling(day.Intensity*4d/maximum),1,4);string Description(PlotLine.Models.WriterWorkDay? value)=>value==null?"No retained activity":$"{value.Changes} accepted changes; {value.Writing+value.Editing} writing/editing sessions; {value.Planning} planning sessions; {value.Reading} reading sessions; {value.EngagedSeconds} browser-engaged seconds; {value.PlaybackSeconds:0} observed audio seconds";var previous=first.AddMonths(-1);var next=first.AddMonths(1);}
<section class="writer-card" aria-label="Writing Journey calendar">
<div class="writer-section-heading"><h2>@first.ToString("MMMM yyyy")</h2><div class="button-row"><a asp-action="Journey" asp-route-bookId="@work.BookID" asp-route-year="@previous.Year" asp-route-month="@previous.Month">Previous month</a><a asp-action="Journey" asp-route-bookId="@work.BookID" asp-route-year="@next.Year" asp-route-month="@next.Month">Next month</a></div></div>
<p>Green shows relative observed activity, including revision with zero net growth. Unavailable audio without playback evidence does not add listening activity. Neutral days mean no retained observation. Receipt dates use UTC; historical coverage is incomplete.</p>
<div class="writer-month-grid">@foreach(var name in new[]{"Mon","Tue","Wed","Thu","Fri","Sat","Sun"}){<strong>@name</strong>}@for(var i=0;i<offset;i++){<span></span>}@for(var date=first;date.Month==first.Month;date=date.AddDays(1)){days.TryGetValue(date,out var day);<a class="work-level-@Level(day) @(work.Day?.Date==date?"writer-day-selected":"")" asp-action="Journey" asp-route-bookId="@work.BookID" asp-route-year="@date.Year" asp-route-month="@date.Month" asp-route-day="@date.ToString("yyyy-MM-dd")" aria-label="@date.ToString("d MMMM yyyy"): @Description(day)"><strong>@date.Day</strong>@if(day!=null){<small>+@day.Added / −@day.Removed words</small>@if(day.Writing>0||day.Editing>0){<small>Writing / editing</small>}@if(day.EngagedSeconds>=60){<small>@Math.Floor(day.EngagedSeconds/60d) browser-engaged min</small>}@if(day.Planning>0){<small>Planning</small>}@if(day.Reading>0){<small>Reading review</small>}@if(day.AudioReview>0){<small>Audio review · @Math.Floor(day.PlaybackSeconds/60) observed min</small>}}</a>}</div>
<details><summary>@work.Year year overview</summary><div class="writer-year-grid">@for(var date=new DateTime(work.Year,1,1);date.Year==work.Year;date=date.AddDays(1)){days.TryGetValue(date,out var day);<a class="work-level-@Level(day)" asp-action="Journey" asp-route-bookId="@work.BookID" asp-route-year="@date.Year" asp-route-month="@date.Month" asp-route-day="@date.ToString("yyyy-MM-dd")" aria-label="@date.ToString("d MMM yyyy"): @Description(day)" title="@date.ToString("d MMM"): @Description(day)"></a>}</div></details>
@if(work.Day is {} selected){days.TryGetValue(selected.Date,out var observed);<h3 class="mt-3">@selected.ToString("d MMMM yyyy")</h3>@if(observed==null){<p>No retained observation for this day. This does not establish that no work took place.</p>}else{<p>@observed.Changes accepted changes · +@observed.Added / −@observed.Removed words · @(observed.Added-observed.Removed) net.</p><p>@Math.Floor(observed.EngagedSeconds/60d) browser-engaged minutes · @Math.Floor(observed.PlaybackSeconds/60) observed playback minutes. These may overlap and are not added.</p>}<a asp-controller="WritingActivity" asp-action="Index" asp-route-bookId="@work.BookID" asp-route-day="@selected.ToString("yyyy-MM-dd")">Accepted-change evidence</a>}
<h3 class="mt-3">@(work.Day.HasValue?"Sessions on this day":"Recent sessions")</h3>
@foreach(var session in work.Sessions.Take(20)){<article class="writer-reminder"><strong>@session.Kind · @(session.ChapterTitle??(session.ChapterID.HasValue?"Chapter no longer available":"Whole book"))</strong><p>@session.StartedUtc.ToString("d MMM HH:mm") UTC · @session.EngagedSeconds browser-engaged seconds · @Math.Round(session.PlaybackSeconds) observed playback seconds · @Math.Round(session.UniqueSeconds) unique audio seconds.</p>@if(session.EndedUtc.HasValue){<span>@Math.Round((session.EndedUtc.Value-session.StartedUtc).TotalMinutes) minutes elapsed (not active time).</span>}@if(session.ChangesDuringSession>0){<p>@session.ChangesDuringSession accepted changes during this interval · +@session.AdditionsDuringSession / −@session.RemovalsDuringSession words across the book · @session.ChangedParagraphs changed paragraph identities associated with this chapter. Overlap in time does not prove that playback caused edits.</p>}@if(session.StartRevision.HasValue){<p>Accepted checkpoint @session.StartRevision → @(session.EndRevision?.ToString()??"session open") · @session.StartParagraphCount → @(session.EndParagraphCount?.ToString()??"—") paragraphs (whole book).</p>}@if(session.Note!=null){<p>@session.Note</p>}</article>}
<a asp-controller="WriterWork" asp-action="Export" asp-route-bookId="@work.BookID" asp-route-day="@work.Day?.ToString("yyyy-MM-dd")">Export recent session evidence (up to 50)</a>
</section>
@if(Model.WritingSchedule.UpcomingTasks.Count>0||Model.PlannedActivities.Count>0){<section class="writer-card"><h2>Planned work ahead</h2><ul>@foreach(var task in Model.WritingSchedule.UpcomingTasks){<li>@task.ScheduledDate.ToString("d MMM") · <a asp-controller="Scenes" asp-action="Edit" asp-route-id="@task.SceneID">@task.SceneTitle</a> · @task.TaskType</li>}@foreach(var task in Model.PlannedActivities){<li>@task.ScheduledDate.ToString("d MMM") · @if(task.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@task.SceneID">@task.Title</a>}else{<a asp-action="Chapter" asp-route-id="@task.ChapterID">@task.Title</a>} · @task.Kind · @task.Minutes planned minutes</li>}</ul></section>}

View File

@ -0,0 +1,2 @@
@model IReadOnlyList<PlotLine.Models.WriterPlanActivity>
@if(Model.Count>0){<section class="story-bible-section"><h2>Reviewed writing activities</h2><p>@Model.Count allocations · @Model.Sum(x=>x.Minutes) planned minutes · these budgets are not measured work.</p><div class="table-responsive"><table class="table"><thead><tr><th>Date</th><th>Work</th><th>Activity</th><th>Minutes</th><th>Status</th></tr></thead><tbody>@foreach(var item in Model){<tr><td>@item.ScheduledDate.ToString("d MMM yyyy")</td><td>@if(item.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">@item.Title</a>}else{<a asp-controller="Writer" asp-action="Chapter" asp-route-id="@item.ChapterID">@item.Title</a>}</td><td>@item.Kind</td><td>@item.Minutes</td><td>@item.Status @if(item.Status=="Planned"){<form asp-controller="WriterPlanning" asp-action="Complete" method="post"><input type="hidden" name="writingPlanId" value="@ViewData["WritingPlanID"]" /><input type="hidden" name="activityId" value="@item.ActivityID" /><button class="btn btn-sm btn-outline-primary">Mark complete</button></form>}</td></tr>}</tbody></table></div></section>}

View File

@ -0,0 +1,13 @@
@model PlotLine.Models.WriterPlanningPage
@{ViewData["Title"]="Review writing activities";ViewData["ProjectSection"]="Writer";ViewData["ShellClass"]="pd-writer";}
<header data-pwa-task><h1>Review writing activities</h1><p>@Model.Plan.PlanName · @Model.Plan.BookName · @Model.Plan.StartDate.ToString("d MMM")–@Model.Plan.DeadlineDate.ToString("d MMM yyyy")</p></header>
<p>These candidates come from your actual chapters and scenes, without requiring manual tasks or status changes. Minutes are adjustable working budgets, not predicted completion times or a promise to fill every available hour. Known estimated scene length supplies a starting budget; otherwise 30 minutes is only a starting allocation.</p>
@if(Model.Scheduled.Count>0){<p>Saving replaces this plan’s uncompleted reviewed allocations after confirmation. Manual scene tasks are preserved. Completed reviewed activities require a new plan for another pass.</p>}
@if(Model.Error!=null){<p class="alert alert-warning" role="alert">@Model.Error</p>}
@if(Model.Candidates.Count==1000){<p class="alert alert-info">Showing the first 1,000 candidates. Use book-specific plans to keep this review manageable.</p>}
@if(Model.Candidates.Count==0){<p>@Model.EmptyReason</p>@if(Model.Plan.BookID.HasValue){<a asp-controller="Books" asp-action="Details" asp-route-id="@Model.Plan.BookID" asp-fragment="chapters">Review chapters and scenes</a>}else{<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Plan.ProjectID">Review the project’s books</a>}<div class="button-row"><a asp-controller="Writer" asp-action="EditWritingPlan" asp-route-writingPlanId="@Model.WritingPlanID">Edit availability / deadline / blocked scenes</a><a asp-controller="Writer" asp-action="SchedulePreview" asp-route-writingPlanId="@Model.WritingPlanID">View existing schedule</a></div>}
else{
<form method="post" asp-action="Index"><input type="hidden" asp-for="WritingPlanID" />
<div class="table-responsive"><table class="table"><thead><tr><th>Include</th><th>Chapter / scene</th><th>Activity</th><th>Working budget (minutes)</th></tr></thead><tbody>
@for(var i=0;i<Model.Candidates.Count;i++){var row=Model.Candidates[i];<tr><td><input asp-for="Candidates[i].Selected" /><input type="hidden" asp-for="Candidates[i].ChapterID" /><input type="hidden" asp-for="Candidates[i].SceneID" /></td><td>@row.BookTitle · @row.Title <small>@row.RevisionStatus</small></td><td><select class="form-select" asp-for="Candidates[i].Kind"><option value="Draft">Draft</option><option value="Edit">Edit</option><option value="Plan">Plan</option><option value="Review">Read / review</option><option value="AudioReview">Audio Review</option></select></td><td><input class="form-control" type="number" min="5" max="1440" asp-for="Candidates[i].Minutes" /></td></tr>}
</tbody></table></div><label><input asp-for="Confirm" /> I have reviewed these activities and budgets. Allocate them within my saved availability.</label><div class="button-row mt-3"><button class="btn btn-primary">Commit reviewed schedule</button><a asp-controller="Writer" asp-action="EditWritingPlan" asp-route-writingPlanId="@Model.WritingPlanID">Edit availability / deadline</a><a asp-controller="Writer" asp-action="Index" asp-route-projectId="@Model.Plan.ProjectID" asp-route-bookId="@Model.Plan.BookID">Return to Writing</a></div></form>}

View File

@ -7,6 +7,7 @@
<div><p class="eyebrow">Writer · Evidence</p><h1>Writing activity</h1><p class="lead-text">@(Model.Book?.BookDisplayTitle ?? "Selected manuscript")</p></div>
<a class="btn btn-outline-primary" asp-controller="Writer" asp-action="Index" asp-route-projectId="@Model.Book?.ProjectID" asp-route-bookId="@Model.BookID">Back to Writer</a>
</div>
<p><a asp-controller="WriterWork" asp-action="Export" asp-route-bookId="@Model.BookID">Export recent work and Audio Review sessions (up to 50)</a>. Session observations use the same recording pause and retention settings below. Erasing history also removes your work/review sessions and notes.</p>
<p>These are accepted snapshot differences and separately labelled native observations. They do not measure writing time or prove authorship. Earlier writing and changes between observations may be unavailable.</p>
@if(Model.Events.Count == 0 && Model.Day.HasValue)
{

View File

@ -0,0 +1,7 @@
.writer-work-toolbar{padding:1.25rem;margin-block:1rem;border-block:1px solid var(--pd-border);color:var(--pd-text);background:var(--pd-surface)}.writer-work-toolbar label{display:grid;gap:.4rem}.writer-work-toolbar .button-row{align-items:end;flex-wrap:wrap}.writer-work-toolbar [data-work-current]>span{margin-inline:.3rem}.writer-work-toolbar [data-work-current]>label{margin-block:.8rem}.writer-help{margin:1rem 0 1.5rem;display:flex;gap:1rem;align-items:center;flex-wrap:wrap}.writer-help>.btn-danger{font-weight:700;font-size:1.35rem;min-width:145px;padding:.9rem 1.7rem}.writer-help>div{width:100%;padding:1rem;background:var(--pd-surface);border:1px solid var(--pd-border);border-radius:12px}.writer-help-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem}.writer-help-grid article{padding:1rem;border-left:3px solid var(--pd-accent)}.writer-month-grid{display:grid;grid-template-columns:repeat(7,minmax(0,1fr));gap:.35rem;margin-block:1rem}.writer-month-grid>a{min-height:100px;display:flex;flex-direction:column;gap:.3rem;padding:.6rem;text-decoration:none;border:1px solid var(--pd-border);border-radius:5px;background:var(--pd-surface)}.writer-month-grid small{font-size:.75rem}.writer-year-grid{display:grid;grid-auto-flow:column;grid-template-rows:repeat(7,12px);gap:3px;overflow:auto;padding:5px}.writer-year-grid a{width:12px;height:12px;background:var(--pd-surface);border:1px solid var(--pd-border);border-radius:2px}.writer-month-grid .work-level-1,.writer-year-grid .work-level-1{background:color-mix(in srgb,var(--bs-success) 20%,var(--pd-surface))}.writer-month-grid .work-level-2,.writer-year-grid .work-level-2{background:color-mix(in srgb,var(--bs-success) 35%,var(--pd-surface))}.writer-month-grid .work-level-3,.writer-year-grid .work-level-3{background:color-mix(in srgb,var(--bs-success) 50%,var(--pd-surface))}.writer-month-grid .work-level-4,.writer-year-grid .work-level-4{background:color-mix(in srgb,var(--bs-success) 65%,var(--pd-surface))}.writer-day-selected{outline:2px solid var(--pd-focus)}@media(max-width:700px){.writer-help-grid{grid-template-columns:1fr}.writer-month-grid>a{min-height:65px;padding:.25rem}.writer-month-grid small{font-size:.6rem}.writer-month-grid{gap:.2rem}}
.writer-next-grid.writer-next-single{grid-template-columns:1fr}
.writer-help-grid article{min-width:0;overflow-wrap:anywhere}
html[data-app-theme] .writer-month-grid>a:is(:link,:visited,:hover,:focus-visible){color:var(--pd-text)}

View File

@ -0,0 +1,38 @@
(() => {
for(const root of document.querySelectorAll('[data-writer-work]')){
const start=root.querySelector('[data-work-start]'),message=root.querySelector('[data-work-message]'),token=start.querySelector('[name=__RequestVerificationToken]').value;
const bookId=root.dataset.bookId;let current=null,busy=false,lastInput=0,startRequest=null,lastChoice=null;
const notify=text=>{message.textContent=text;};
const post=async(action,values)=>{const body=new URLSearchParams({bookId,__RequestVerificationToken:token,...values});const response=await fetch('/Writer/Work/'+action,{method:'POST',body});if(!response.ok){let data;try{data=await response.json();}catch{}throw Error(data?.message||'The session could not be updated. Check access and Reports recording settings.');}return response;};
for(const type of ['keydown','pointerdown','wheel','touchstart'])document.addEventListener(type,event=>{if(event.isTrusted)lastInput=Date.now();},{passive:true});
const render=session=>{
const changed=current?.sessionID!==session?.sessionID;current=session;
root.querySelector('[data-work-current]').hidden=!session;start.hidden=!!session;
root.querySelector('[data-work-audio]').hidden=session?.kind!=='AudioReview';
if(!session)return;
root.querySelector('[data-work-end]').textContent=session.kind==='AudioReview'?'End Audio Review & save note':'End session & save note';
root.querySelector('[data-work-label]').textContent=session.kind+' session';
root.querySelector('[data-work-elapsed]').textContent=' · '+Math.max(0,Math.round((Date.now()-new Date(session.startedUtc))/60000))+' minutes elapsed';
root.querySelector('[data-work-measured]').textContent=' · '+Math.floor(session.engagedSeconds/60)+' browser-engaged minutes';
if(changed)root.querySelector('[data-work-note]').value='';
if(session.kind==='AudioReview'){
root.querySelector('[data-audio-chapter]').textContent=session.chapterTitle||'Selected chapter';
root.querySelector('[data-audio-state]').textContent=session.live?session.playbackState+(session.lastError?' · '+session.lastError:''):'Media controls unavailable. Updated Windows Companion with Audio Review support is required.';
root.querySelector('[data-audio-position]').textContent=(session.positionSeconds==null?'Position unavailable':Math.round(session.positionSeconds)+' seconds'+(session.durationSeconds==null?'':' / '+Math.round(session.durationSeconds)+' seconds'))+' · '+Math.floor(session.playbackSeconds/60)+' observed playback minutes · '+Math.floor(session.uniqueSeconds/60)+' unique coverage minutes'+(session.coveragePartial?' (partial)':'');
root.querySelector('[data-pause-on-edit]').checked=session.pauseOnEdit;
for(const button of root.querySelectorAll('[data-media-command]'))button.disabled=!session.live||['unavailable','error'].includes(session.playbackState)||!session.capabilities?.split(',').includes(button.dataset.mediaCommand)||busy;
}
};
const refresh=async()=>{const response=await fetch('/Writer/Work/State?bookId='+encodeURIComponent(bookId));if(!response.ok)throw Error('Session history is private or temporarily unavailable.');const data=await response.json();render(data.session);if(!data.session)root.querySelector('[data-pause-on-edit]').checked=data.defaultPauseOnEdit;};
start.querySelector('[name=kind]').addEventListener('change',event=>{start.querySelector('button[type=submit]').textContent=event.target.value==='AudioReview'?'Start Audio Review':'Start session';});
start.addEventListener('submit',async event=>{event.preventDefault();if(busy)return;busy=true;try{const data=new FormData(start);const kind=data.get('kind'),chapterId=data.get('chapterId');if(kind==='AudioReview'&&!chapterId)throw Error('Choose a chapter for Audio Review.');const choice=kind+'/'+chapterId;if(lastChoice!==choice){startRequest=null;lastChoice=choice;}startRequest??=crypto.randomUUID();await post('Start',{kind,chapterId:chapterId||'',requestId:startRequest,pauseOnEdit:String(root.querySelector('[data-pause-on-edit]').checked)});startRequest=null;lastInput=Date.now();await refresh();notify('Session started. Leave it open only while you want to record this activity.');}catch(error){notify(error.message);}finally{busy=false;}});
root.querySelector('[data-work-end]').addEventListener('click',async()=>{if(!current||busy)return;busy=true;try{await post('End',{sessionId:current.sessionID,note:root.querySelector('[data-work-note]').value});await refresh();notify('Session ended. Your note was saved.');}catch(error){notify(error.message);}finally{busy=false;}});
root.querySelector('[data-pause-on-edit]').addEventListener('change',async event=>{if(!current)return;try{await post('Preference',{sessionId:current.sessionID,pauseOnEdit:String(event.target.checked)});}catch(error){notify(error.message);}});
for(const button of root.querySelectorAll('[data-media-command]'))button.addEventListener('click',async()=>{if(!current||busy)return;busy=true;try{await post('Command',{sessionId:current.sessionID,command:button.dataset.mediaCommand});notify('Command requested; waiting for the selected media session.');}catch(error){notify(error.message);}finally{busy=false;}});
let tick=0;const timer=setInterval(async()=>{if(busy||document.visibilityState!=='visible')return;busy=true;try{if(current&&++tick%3===0)await post('Heartbeat',{sessionId:current.sessionID,sequence:current.sequence+1,engaged:String(document.hasFocus()&&Date.now()-lastInput<60000)});await refresh();}catch(error){notify(error.message);}finally{busy=false;}},10000);
window.addEventListener('pagehide',()=>clearInterval(timer),{once:true});
refresh().catch(error=>notify(error.message));
}
document.querySelector('[data-writer-help]')?.addEventListener('click',event=>{document.getElementById('writer-help-options').hidden=false;event.currentTarget.setAttribute('aria-expanded','true');});
document.querySelector('[data-writer-help-close]')?.addEventListener('click',()=>{document.getElementById('writer-help-options').hidden=true;document.querySelector('[data-writer-help]').setAttribute('aria-expanded','false');document.querySelector('[data-writer-help]').focus();});
})();