Integrate browser-approved import capture and guarded imported-scene presence
This commit is contained in:
parent
b8bb08948d
commit
796786414a
@ -0,0 +1,60 @@
|
||||
# Overnight Development handover — 5–6 November 2026
|
||||
|
||||
Shared branch: `codex/word-companion-native-phase1-20261104`. Started by fetching the configured origin and fast-forwarding to Windows handover `97f5d99`. No Production deployment, author-account changes or Windows installation operations.
|
||||
|
||||
## Workstreams
|
||||
|
||||
| Workstream | Delivered | Commits / qualification | Limits |
|
||||
|---|---|---|---|
|
||||
| Word AI review → import | Browser-approved optional encrypted source capture; approved scenes only; target-book preview; explicit confirmation; canonical manuscript build and source/summary services; atomic receipt; retries; incremental new-chapter append | `bf515d2` and final integration commit; service and actual authenticated HTTP tests; Development SQL fixtures | Existing chapters are never overwritten. Changed/overlapping imports and title matches conflict rather than reconcile. A real author must qualify the complete workflow in Word. |
|
||||
| Context / Intent | Independent saved-scene picker; live-follow/manual pause/return; minimal embedded writing layout; existing calendar, Story Maps, floor-plan, relationship and plot-line navigation; saved Intent progress | `15ea2ba` plus theme inheritance integration; browser live/manual/pinned/stale-response tests | No invented AI fulfilment scores. No automatic map centring without a reliable saved mapping. Imported-position follow requires updated tray and exact observed revision; marker-based follow remains available. |
|
||||
| Plot Lines | Existing Focus/Weave enriched with intersection/health summary, intersection-only filter, combined text filtering and next-intersection navigation | `caeb90b`; actual Razor browser Focus/Weave/association/theme regressions | Existing suggestions and author confirmation retained; no new AI engine or silent membership changes. |
|
||||
| Continuity | Severity/rule/entity evidence clusters, active/decided filter, search, expand/collapse and clear detection timestamps | `b8bb089`; pure grouping and real browser interaction tests | Related evidence is not asserted to share a root cause. Existing actions retained; no new persisted Deferred/Resolved states. Detection time is not proof prose was rechecked. |
|
||||
| Onboarding / release | Browser-first first-book guide and honest Companion installation availability; Home/Help links; public theme/account behaviour checked | `b8bb089`; actual Help routing and public-site browser tests | Verified installer exists only on Windows; no fabricated public download. No live payment/subscription mutation performed. |
|
||||
|
||||
## Import operation and consent
|
||||
|
||||
The browser pairing approval offers an **unchecked** encrypted import-capture permission. Legacy grants default to false. This works with tested Windows agent **1.0.0.10**: sign out/reconnect, approve capture in the browser, select the correct book, explicitly submit the selected chapters again. Identical persisted AI results are reused; review decisions survive, and source capture does not incur another AI request. Existing agent caches may require reconnecting/restarting before resubmission.
|
||||
|
||||
Encrypted selected-chapter source is retained with the existing 30-day review lifecycle, protected by server Data Protection. Confirmed import becomes ordinary saved book data. Keep the existing server Data Protection keys backed up. Logs contain neither manuscript prose nor tokens.
|
||||
|
||||
In the browser workspace, edit titles/summaries and save approved/rejected decisions, select reviews, preview the exact proposed chapter/scene structure and destination, then confirm. Pending/rejected scenes are excluded, explicitly disclosed. The transaction rechecks authorisation, subscription, review version, source identity/hash and duplicates. It uses `dbo.Onboarding_ManuscriptBuild_Create`, then existing source and summary procedures. A receipt is returned only after all source writes commit. No Word prose or markers are changed; marker status is `NotRequestedNative`.
|
||||
|
||||
New chapters append in capture order. Existing relationships and metadata remain untouched. Changed existing imports require a subsequent explicit reconciliation feature. Successful AI chapter results persist; failed chapters are retried explicitly. The tray reports processed/failed/import-ready counts separately.
|
||||
|
||||
## Position and multi-screen safety
|
||||
|
||||
Optional tray 1.0.0.11 sends the already available selection start, without additional Word COM operations. The server resolves only saved imported absolute ranges for the same authorised book, persistent document identity and observed revision. Scene/chapter changes invalidate the browser workspace; cursor heartbeats do not continuously rebuild it. After an observed edit, unmatched ranges are refused rather than guessed. This is not durable bookmark installation: revision resets between sessions and same-length dirty edits require Windows qualification; manual scene choice and existing markers remain the safer fallback. Chapter-relative paragraph indices are not saved as whole-document Word positions.
|
||||
|
||||
## Database and deployment
|
||||
|
||||
Development-only forward migrations: `232_NativeApprovedImport.sql`, `233_NativeImportedPositions.sql`. Both applied after verified COPY_ONLY/CHECKSUM backups:
|
||||
|
||||
- `/var/opt/mssql/backups/PlotDirector_Development-overnight-20261105T225822.bak`
|
||||
- `/var/opt/mssql/backups/PlotDirector_Development-overnight-position-20261105T232027.bak`
|
||||
|
||||
SQL regression fixtures run inside rollback transactions. Tests cover initial import, exact source/summary, duplicate retry, ordered append, stale revision refusal, and failure after canonical build maps were emitted. Failure leaves no chapter, scene, receipt or fixture behind. No real manuscript import was executed by this sprint.
|
||||
|
||||
Final Development deployment evidence and final regression counts are recorded in the companion verification note. Existing environment configuration, uploads, Data Protection and logs are preserved. Production unchanged.
|
||||
|
||||
## Windows handover and installer preservation
|
||||
|
||||
`WindowsValidation/Setup` remains byte-for-byte unchanged from `97f5d99`. Its builder intentionally pins the Windows-qualified **1.0.0.10** payload/source `6cdb49c`; do not edit that guard to make an unqualified package appear approved. The Windows handover records installer SHA256 `9526E3781EB2EF9936132786E1E2242633349933A553E93E7A7D0B038160A7FF`. Atlas does not possess that artifact, so Help does not offer a fake URL or expose a developer path.
|
||||
|
||||
Native sources are version **1.0.0.11**, for richer import-ready reporting and optional imported cursor mapping. Linux builds include the Windows-targeted managed tray; they do not execute Word/VSTO or qualify an installer upgrade. The VSTO Word adapter implementation remains unchanged from the Windows baseline; version metadata alone advances. Windows Codex owns packaging and upgrade qualification through the existing scripts; no second installer/update mechanism was introduced.
|
||||
|
||||
## Ready for user testing
|
||||
|
||||
1. With existing installed Companion10, reconnect with capture consent; submit one chapter, approve some scenes, preview then confirm; repeat confirmation and verify no duplicates. Test a second new chapter and a changed existing chapter conflict. Check saved exact prose, summaries and existing metadata.
|
||||
2. Open Context and Intent in separate windows; choose scenes independently without Word; pause and resume follow, switch books/documents, disconnect and verify no stale scene takes over. Try tool links and theme changes.
|
||||
3. Use Plot Lines intersection filter/search/next; use continuity clusters and active/decided filters; ensure saved decisions remain unchanged until an explicit action.
|
||||
|
||||
## Release recommendation and next actions
|
||||
|
||||
Development is suitable for bounded author testing, **not public-release qualification**. Three next actions:
|
||||
|
||||
1. Qualify the real Word → chapter AI → approved import → saved story-data journey with an author-owned test book, including cancellation/retry and existing-content conflict cases.
|
||||
2. Windows Codex qualifies tray11, three documents, typing/saving under load, reconnect/revision safety, then builds and upgrade-tests through the preserved installer workflow.
|
||||
3. Obtain a distributable signed installer artifact, complete download/release gates and real-manuscript/access/subscription acceptance. Decide explicit existing-chapter reconciliation and evidence-backed Intent fulfilment as subsequent work.
|
||||
|
||||
No live provider billing, public account creation, Stripe upgrade/downgrade, full existing-manuscript reconciliation, native Word performance or public installer upgrade was proved by Linux fixtures.
|
||||
@ -17,7 +17,7 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable
|
||||
if(request.SnapshotId==Guid.Empty||request.BookId<=0||request.Start<0||request.End<=request.Start||request.End-request.Start>120000){answer.Status="invalid-ai-chapter";return answer;}
|
||||
if(!jobs.ContainsKey(descriptor.SessionId)&&jobs.Count>=32){answer.Status="ai-capacity";return answer;}
|
||||
Clear(descriptor.SessionId);
|
||||
var chapter=new AiChapterRequest{RetainForImport=request.RetainForImport,RequestId=request.SnapshotId,BookId=request.BookId,SessionId=descriptor.SessionId,ManuscriptId=descriptor.ManuscriptId,Revision=descriptor.Revision,ChapterTitle=request.ChapterTitle.Length<=200?request.ChapterTitle:request.ChapterTitle[..200],ChapterStart=request.Start,ChapterEnd=request.End};
|
||||
var chapter=new AiChapterRequest{RequestId=request.SnapshotId,BookId=request.BookId,SessionId=descriptor.SessionId,ManuscriptId=descriptor.ManuscriptId,Revision=descriptor.Revision,ChapterTitle=request.ChapterTitle.Length<=200?request.ChapterTitle:request.ChapterTitle[..200],ChapterStart=request.Start,ChapterEnd=request.End};
|
||||
jobs[descriptor.SessionId]=new(chapter,request.AuthenticationContext);return answer;
|
||||
}
|
||||
if(!jobs.TryGetValue(descriptor.SessionId,out var job)||job.Chapter.RequestId!=request.SnapshotId){answer.Status="obsolete-ai-request";return answer;}
|
||||
|
||||
@ -92,7 +92,7 @@ public sealed class CloudGateway : IDisposable
|
||||
{
|
||||
var fingerprint=expectedContext+":"+chapter.BookId+":"+chapter.ManuscriptId+":"+Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{chapter.ChapterStart,chapter.ChapterEnd,chapter.Paragraphs})));
|
||||
Uri site;string access;
|
||||
lock(gate){Expire();if(successful.TryGetValue(fingerprint,out var prior)&&authenticationContext==expectedContext&&token!=null&&(!chapter.RetainForImport||prior.SourceRetained))return new(){SourceRetained=prior.SourceRetained,RequestId=chapter.RequestId,DocumentRevision=chapter.Revision,ChapterTitle=chapter.ChapterTitle,State="complete",Message="Unchanged chapter: reused saved AI suggestions without uploading prose.",ReviewPath=prior.ReviewPath,Scenes=prior.Scenes};if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");}
|
||||
lock(gate){Expire();if(successful.TryGetValue(fingerprint,out var prior)&&authenticationContext==expectedContext&&token!=null)return new(){SourceRetained=prior.SourceRetained,RequestId=chapter.RequestId,DocumentRevision=chapter.Revision,ChapterTitle=chapter.ChapterTitle,State="complete",Message="Unchanged chapter: reused saved AI suggestions without uploading prose.",ReviewPath=prior.ReviewPath,Scenes=prior.Scenes};if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");}
|
||||
using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/analyse-chapter")){Content=JsonContent.Create(chapter,options:Json)};
|
||||
request.Headers.Authorization=new AuthenticationHeaderValue("Bearer",access);
|
||||
HttpResponseMessage responseValue;
|
||||
|
||||
@ -31,6 +31,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
else{
|
||||
doc.Observed=DateTime.UtcNow;
|
||||
if(request.Kind=="active"){foreach(var d in documents.Values)d.Active=false;doc.Active=true;}
|
||||
if(request.Kind=="selection")doc.Cursor=request.Start;
|
||||
if(request.Kind=="selection"||request.Kind=="snapshot-end"){doc.ChapterId=answer.ChapterId;doc.SceneId=answer.SceneId;doc.ChapterTitle=answer.ChapterTitle;doc.SceneTitle=answer.SceneTitle;}
|
||||
if(answer.WordCount.HasValue)doc.Words=answer.WordCount;
|
||||
if(request.Kind.StartsWith("snapshot-",StringComparison.Ordinal)&&answer.Status is not ("ok" or "analysis-complete" or "awaiting-structure")){Cancel(doc);doc.Status="Local reading failed: "+answer.Status+". Detect chapters again.";}
|
||||
@ -61,18 +62,18 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
lock(gate){if(!documents.TryGetValue(session,out var doc)||!cloud.Allows(doc.Authentication,doc.Book))throw new InvalidOperationException("Connect and select an authorised book first.");if(doc.Job!=Guid.Empty)throw new InvalidOperationException("Cancel the current chapter batch first.");
|
||||
var selection=starts.Distinct().ToHashSet();var chapters=doc.Chapters.Where(c=>selection.Contains(c.Start)&&c.End>c.Start).ToArray();if(chapters.Length==0)throw new InvalidOperationException("Detect and select Heading 1 chapters first.");
|
||||
doc.Pending.Clear();foreach(var chapter in chapters)if(!doc.Completed.Contains((doc.Revision,doc.Book,chapter.Start)))doc.Pending.Enqueue(chapter);
|
||||
doc.Total=doc.Pending.Count;doc.Done=0;doc.Failed=0;Next(doc);
|
||||
doc.Total=doc.Pending.Count;doc.Done=0;doc.Failed=0;doc.Retained=0;Next(doc);
|
||||
}
|
||||
}
|
||||
private void Next(TrayDocument doc)
|
||||
{
|
||||
doc.Job=Guid.Empty;
|
||||
if(doc.Pending.Count>0&&documents.Values.Any(other=>other!=doc&&other.Job!=Guid.Empty)){doc.Status="Waiting for the current manuscript chapter batch; no prose has been sent.";return;}
|
||||
if(doc.Pending.Count==0){doc.Status=$"Batch finished: {doc.Done}/{doc.Total} processed; {doc.Failed} failed. Successful suggestions are in PlotDirector. Retry failed chapters explicitly; completed unchanged chapters are skipped.";
|
||||
if(doc.Pending.Count==0){doc.Status=$"Batch finished: {doc.Done}/{doc.Total} processed; {doc.Failed} failed. Successful suggestions are in PlotDirector. Retry failed chapters explicitly; completed unchanged chapters are skipped. Import-ready captures: {doc.Retained}/{doc.Done-doc.Failed}. Enable encrypted import capture in browser approval if needed.";
|
||||
if(doc.Done>0&&!string.IsNullOrEmpty(doc.ReviewPath))_ = Task.Run(()=>{try{cloud.OpenCompanionPage($"/native-companion/workspace?bookId={doc.Book}&instanceId={doc.Instance}&sessionId={doc.Session}",doc.Authentication);}catch(Exception e)when(e is InvalidOperationException or IOException or System.ComponentModel.Win32Exception){}});
|
||||
return;}
|
||||
doc.Current=doc.Pending.Dequeue();doc.Job=Guid.NewGuid();doc.Started=DateTime.UtcNow;doc.Status=$"Chapter {doc.Done+1}/{doc.Total}: {doc.Current.Title}";doc.Progress=0;
|
||||
if(!Queue(doc,new(){Id=doc.Job,Kind="extract-ai",RetainForImport=true,Chapter=doc.Current,BookId=doc.Book,AuthenticationContext=doc.Authentication})){doc.Job=Guid.Empty;doc.Pending.Clear();}
|
||||
if(!Queue(doc,new(){Id=doc.Job,Kind="extract-ai",Chapter=doc.Current,BookId=doc.Book,AuthenticationContext=doc.Authentication})){doc.Job=Guid.Empty;doc.Pending.Clear();}
|
||||
}
|
||||
public void Cancel(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Status="Cancelled. Successful server suggestions remain available.";}}
|
||||
private void Cancel(TrayDocument doc){if(doc.Job!=Guid.Empty)ai.Clear(doc.Session);doc.Job=Guid.Empty;doc.Pending.Clear();if(commands.TryGetValue(doc.Instance,out var q))commands[doc.Instance]=new(q.Where(c=>c.SessionId!=doc.Session));Queue(doc,new(){Kind="cancel"});}
|
||||
@ -85,7 +86,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
if(doc.Book==0&&DocumentBindingRestore(doc,cloudState)) {doc.Book=doc.RememberedBook!.Value;doc.Authentication=cloudState.AuthenticationContext;lastBook=doc.Book;lastAuthentication=doc.Authentication;}
|
||||
if(doc.Job==Guid.Empty){if(doc.Pending.Count>0&&!documents.Values.Any(other=>other.Job!=Guid.Empty))Next(doc);continue;}var result=ai.Result(doc.Session);
|
||||
if(result?.RequestId==doc.Job&&result.State is "complete" or "failed" or "cancelled"){
|
||||
if(result.State=="complete"&&!string.IsNullOrEmpty(result.ReviewPath)){if(doc.Completed.Count>=8192)doc.Completed.RemoveWhere(c=>c.Item1!=doc.Revision);doc.Completed.Add((doc.Revision,doc.Book,doc.Current!.Start));doc.ReviewPath=result.ReviewPath;}
|
||||
if(result.State=="complete"&&!string.IsNullOrEmpty(result.ReviewPath)){if(result.SourceRetained)doc.Retained++;if(doc.Completed.Count>=8192)doc.Completed.RemoveWhere(c=>c.Item1!=doc.Revision);doc.Completed.Add((doc.Revision,doc.Book,doc.Current!.Start));doc.ReviewPath=result.ReviewPath;}
|
||||
else{doc.Failed++;if(doc.Errors.Count>=50)doc.Errors.RemoveAt(0);doc.Errors.Add(doc.Current!.Title+": "+(result.State=="complete"?"Server update required: no saved PWA review handoff was returned.":result.Message));}
|
||||
doc.Done++;ai.Clear(doc.Session);Next(doc);
|
||||
}else if(DateTime.UtcNow-doc.Started>TimeSpan.FromMinutes(7)){doc.Errors.Add("Chapter timed out; retry explicitly.");Cancel(doc);doc.Status="Chapter timed out. Prior suggestions are safe in PlotDirector.";}
|
||||
@ -96,7 +97,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
public async Task Heartbeat(CancellationToken cancellation)
|
||||
{
|
||||
while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromMilliseconds(500),cancellation);var available=Documents.Where(d=>d.Book>0).ToArray();
|
||||
foreach(var doc in available){var key=$"{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=Interlocked.Increment(ref doc.PresenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision&&reply.Navigation.Kind=="navigate")Queue(doc,reply.Navigation);}catch(Exception e)when(NetworkFailure(e)) {}}
|
||||
foreach(var doc in available){var key=$"{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{(doc.SceneId.HasValue?0:doc.Cursor)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CursorStart=doc.Cursor,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=Interlocked.Increment(ref doc.PresenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision&&reply.Navigation.Kind=="navigate")Queue(doc,reply.Navigation);}catch(Exception e)when(NetworkFailure(e)) {}}
|
||||
if(available.Length==0&&lastBook>0&&DateTime.UtcNow-lastAgentPresence>=TimeSpan.FromSeconds(15)){lastAgentPresence=DateTime.UtcNow;agentOnlyPublished=true;try{await cloud.Presence(agentInstance,agentSession,new(){BookId=lastBook,Sequence=Interlocked.Increment(ref agentSequence),WordAvailable=false,DocumentTitle="No Word document"},lastAuthentication);}catch(Exception e)when(NetworkFailure(e)) {}}
|
||||
else if(available.Length>0&&agentOnlyPublished){agentOnlyPublished=false;await cloud.RemovePresence(agentInstance,agentSession);}
|
||||
}
|
||||
@ -106,7 +107,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
public sealed class TrayDocument
|
||||
{
|
||||
public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Detect chapters to begin.",ReviewPath="";
|
||||
public string WordDiagnostics="";public int Failed;public int Book,Progress,Total,Done;public int? RememberedBook,Words,ChapterId,SceneId;public bool Active;public DateTime Observed,Started;
|
||||
public string WordDiagnostics="";public int Cursor;public int Retained;public int Failed;public int Book,Progress,Total,Done;public int? RememberedBook,Words,ChapterId,SceneId;public bool Active;public DateTime Observed,Started;
|
||||
public StructureSuggestion[] Chapters=[];public StructureSuggestion? Current;public Queue<StructureSuggestion> Pending=[];public HashSet<(long,int,int)> Completed=[];public List<string> Errors=[];
|
||||
public override string ToString()=>Title+(Active?" (active in Word)":"");
|
||||
}
|
||||
|
||||
@ -4,7 +4,6 @@ namespace PlotDirector.Companion.Protocol;
|
||||
[DataContract]
|
||||
public sealed class AiChapterRequest
|
||||
{
|
||||
[DataMember] public bool RetainForImport {get;set;}
|
||||
[DataMember] public string ChapterTitle {get;set;}="";
|
||||
[DataMember] public Guid RequestId { get; set; }
|
||||
[DataMember] public int BookId { get; set; }
|
||||
|
||||
@ -25,7 +25,6 @@ public static class ProtocolVersion
|
||||
[DataContract]
|
||||
public sealed class Message
|
||||
{
|
||||
[DataMember] public bool RetainForImport {get;set;}
|
||||
[DataMember] public AdapterCommand? Command {get;set;}
|
||||
[DataMember] public string OperationMessage {get;set;}="";
|
||||
[DataMember] public int Version { get; set; } = ProtocolVersion.Current;
|
||||
|
||||
@ -3,7 +3,6 @@ namespace PlotDirector.Companion.Protocol;
|
||||
[DataContract]
|
||||
public sealed class AdapterCommand
|
||||
{
|
||||
[DataMember] public bool RetainForImport {get;set;}
|
||||
[DataMember] public Guid Id {get;set;}=Guid.NewGuid();
|
||||
[DataMember] public string Kind {get;set;}="";
|
||||
[DataMember] public Guid SessionId {get;set;}
|
||||
@ -17,6 +16,7 @@ public sealed class AdapterCommand
|
||||
[DataContract]
|
||||
public sealed class NativePresence
|
||||
{
|
||||
[DataMember] public int? CursorStart {get;set;}
|
||||
[DataMember] public AdapterCommand? Navigation {get;set;}
|
||||
[DataMember] public Guid ManuscriptId {get;set;}
|
||||
[DataMember] public int BookId {get;set;}
|
||||
|
||||
@ -233,7 +233,7 @@ namespace PlotDirector.WordAddIn
|
||||
var chapter=command.Chapter;
|
||||
if(chapter.Start<0||chapter.End<=chapter.Start||chapter.End>doc.End||DocumentEnd(doc.Document)!=doc.End)throw new InvalidOperationException("Chapter changed. Detect chapters again.");
|
||||
CancelExtraction(doc);doc.AiChapter=command.Chapter;doc.AiBook=command.BookId;doc.AiAuthenticationContext=command.AuthenticationContext;doc.AiJob=command.Id;
|
||||
doc.Extraction=new Extraction{Snapshot=command.Id,Revision=doc.Revision,Position=chapter.Start,Limit=chapter.End,IsAi=true,RetainForImport=command.RetainForImport};
|
||||
doc.Extraction=new Extraction{Snapshot=command.Id,Revision=doc.Revision,Position=chapter.Start,Limit=chapter.End,IsAi=true};
|
||||
if(!scheduler.Post("extract:"+doc.Session,()=>ExtractBatch(doc))){CancelExtraction(doc);throw new InvalidOperationException("Word queue is busy.");}
|
||||
}
|
||||
else if(command.Kind=="cancel"){CancelExtraction(doc);doc.AiJob=Guid.Empty;}
|
||||
@ -272,7 +272,7 @@ namespace PlotDirector.WordAddIn
|
||||
{
|
||||
if(!extraction.Begun)
|
||||
{
|
||||
if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-begin":"snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,Start=extraction.Position,End=extraction.Limit,BookId=doc.AiBook,AuthenticationContext=doc.AiAuthenticationContext,RetainForImport=extraction.RetainForImport,RequestAnalysis=extraction.Analyse,ChapterTitle=doc.AiChapter?.Title??""}))return;
|
||||
if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-begin":"snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,Start=extraction.Position,End=extraction.Limit,BookId=doc.AiBook,AuthenticationContext=doc.AiAuthenticationContext,RequestAnalysis=extraction.Analyse,ChapterTitle=doc.AiChapter?.Title??""}))return;
|
||||
extraction.Begun=true;
|
||||
}
|
||||
// At most four <=2048-character fragments and a cooperative ~20ms budget.
|
||||
@ -541,6 +541,6 @@ namespace PlotDirector.WordAddIn
|
||||
public LocalDocument(Word.Document document){Document=document;}
|
||||
}
|
||||
private sealed class Extraction
|
||||
{public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex,Limit;public int OutlineLevel;public bool Begun,Analyse,IsAi,RetainForImport;public Message Pending;}
|
||||
{public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex,Limit;public int OutlineLevel;public bool Begun,Analyse,IsAi;public Message Pending;}
|
||||
}
|
||||
}
|
||||
|
||||
3
PlotLine.Tests/Browser/writing-embedded-theme.cjs
Normal file
3
PlotLine.Tests/Browser/writing-embedded-theme.cjs
Normal file
@ -0,0 +1,3 @@
|
||||
const {chromium}=require('playwright');
|
||||
const path=require('path');
|
||||
(async()=>{const browser=await chromium.launch({headless:true});try{const page=await browser.newPage();await page.setContent('<html data-app-theme="plum" data-bs-theme="dark"><iframe srcdoc="<!doctype html><html><body>Writing screen</body></html>"></iframe></html>');const frame=page.frames()[1];await frame.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/writing-embedded-theme.js')});await frame.waitForFunction(()=>document.documentElement.getAttribute('data-app-theme')==='plum'&&document.documentElement.getAttribute('data-bs-theme')==='dark');await page.evaluate(()=>{document.documentElement.setAttribute('data-app-theme','sage');document.documentElement.removeAttribute('data-bs-theme');});await frame.waitForFunction(()=>document.documentElement.getAttribute('data-app-theme')==='sage'&&!document.documentElement.hasAttribute('data-bs-theme'));console.log('PASS embedded writing screens inherit and track existing PWA theme without separate persistence');}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
@ -48,7 +48,7 @@ internal static class NativeCompanionHttpTests
|
||||
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IStoryContextService>((n,a)=>Task.FromResult<StoryContextViewModel?>(null)));
|
||||
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IWriterWorkspaceService>((n,a)=>Task.FromResult<PlotLine.ViewModels.ChapterWorkflowViewModel?>(null)));
|
||||
builder.Services.AddSingleton(users);builder.Services.AddSingleton(repo);builder.Services.AddSingleton(subscriptions);
|
||||
builder.Services.AddSingleton<IDataProtectionProvider>(new EphemeralDataProtectionProvider());builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddSingleton<DesktopPairing>();builder.Services.AddSingleton<NativeAnalysisCache>();builder.Services.AddSingleton<NativePresenceStore>();builder.Services.AddSingleton<INativeReviewRepository>(new MemoryNativeReviews());
|
||||
builder.Services.AddSingleton<IDataProtectionProvider>(new EphemeralDataProtectionProvider());builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddSingleton<DesktopPairing>();builder.Services.AddSingleton<NativeAnalysisCache>();builder.Services.AddSingleton(NativeWorkflowTests.Proxy<INativeImportRepository>((n,a)=>n=="List"?Task.FromResult<IReadOnlyList<NativeImportedChapter>>([]):throw new Exception("Unexpected import write "+n)));builder.Services.AddScoped<NativeImportService>();builder.Services.AddSingleton<NativePresenceStore>();builder.Services.AddSingleton<INativeReviewRepository>(new MemoryNativeReviews());
|
||||
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options=>{options.LoginPath="/fixture-login";options.Cookie.SecurePolicy=Microsoft.AspNetCore.Http.CookieSecurePolicy.None;})
|
||||
.AddScheme<AuthenticationSchemeOptions,DesktopAuthentication>(DesktopPairing.Scheme,_=>{});
|
||||
builder.Services.AddRateLimiter(o=>o.AddPolicy("native-pair",_=>System.Threading.RateLimiting.RateLimitPartition.GetNoLimiter("fixture")));
|
||||
@ -82,7 +82,7 @@ internal static class NativeCompanionHttpTests
|
||||
var approval=await browser.GetAsync("/native-companion/authorize?code="+code);Check(approval.IsSuccessStatusCode&&(await approval.Content.ReadAsStringAsync()).Contains("Approve this Word Companion connection"),"Actual approval view renders before any upload");
|
||||
Check((await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary<string,string>{{"code",code}}))).StatusCode==HttpStatusCode.BadRequest,"Approval enforces antiforgery");
|
||||
var antiforgery=await browser.GetStringAsync("/fixture-antiforgery");
|
||||
Check((await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary<string,string>{{"code",code},{"__RequestVerificationToken",antiforgery}}))).IsSuccessStatusCode,"Authenticated antiforgery approval succeeds");
|
||||
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.GetFromJsonAsync<CompanionBook[]>("/api/native-companion/books"))!.Single().BookId==3,"Grant loads authorized books through actual routing");
|
||||
@ -99,6 +99,8 @@ internal static class NativeCompanionHttpTests
|
||||
Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(decisionFields))).StatusCode==HttpStatusCode.Redirect,"Actual antiforgery-protected form binds and saves review decisions");
|
||||
Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(decisionFields))).StatusCode==HttpStatusCode.Conflict,"Actual stale review form receives conflict without overwriting");reviewHtml=await browser.GetStringAsync("/fixture-render-review/"+reviewId);Check(!reviewHtml.Contains("<script>not-executable</script>")&&reviewHtml.Contains("Edited summary"),"Saved title is encoded while edited summary remains reviewable");
|
||||
request.RequestId=Guid.NewGuid();var reused=await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request);Check(reused.IsSuccessStatusCode&&provider.Prompts.Count==1,"Unchanged chapter content reuses durable suggestion across new request identifiers");
|
||||
Check((await reused.Content.ReadFromJsonAsync<AiChapterResult>())?.SourceRetained==true,"Retaining source requires explicit opt-in and reuses analysis without another provider call");
|
||||
using(var previewScope=app.Services.CreateScope()){var plan=await previewScope.ServiceProvider.GetRequiredService<NativeImportService>().Preview(7,3,[reviewId]);Check(plan.Conflicts.Length==0&&plan.Items.Single().Scenes.Single().Text==request.Paragraphs.Single().Text,"Actual HTTP retained source and approved decisions produce an exact-prose import preview");}
|
||||
var negotiation=await browser.PostAsync("/hubs/native-companion/negotiate?negotiateVersion=1",null);Check(negotiation.IsSuccessStatusCode,"Native presence hub requires normal browser authentication and negotiates after sign-in");
|
||||
var connectionToken=(await negotiation.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("connectionToken").GetString();
|
||||
using var socket=new System.Net.WebSockets.ClientWebSocket();socket.Options.Cookies=browserHandler.CookieContainer;using var socketTimeout=new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
||||
|
||||
@ -21,14 +21,15 @@ internal static class NativeCompanionTests
|
||||
public static async Task Run()
|
||||
{
|
||||
void Check(bool value,string name){if(!value)throw new Exception(name);}
|
||||
var clock=new Clock();var pairing=new DesktopPairing(new EphemeralDataProtectionProvider(),clock);
|
||||
var clock=new Clock();var protection=new EphemeralDataProtectionProvider();var pairing=new DesktopPairing(protection,clock);
|
||||
var verifier=new string('a',64);var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier)));
|
||||
var code=pairing.Start(challenge);
|
||||
Check(pairing.Redeem(code,verifier)==null,"Pairing needs browser approval");
|
||||
var stamp=Guid.NewGuid();Check(pairing.Approve(code,7,stamp),"First browser approval");Check(!pairing.Approve(code,9,Guid.NewGuid()),"Cannot change approved owner");
|
||||
Check(pairing.Redeem(code,new string('b',64))==null,"Wrong verifier refused");
|
||||
var token=pairing.Redeem(code,verifier)!;var grant=pairing.Read(token)!;
|
||||
Check(grant.UserId==7&&grant.Stamp==stamp&&pairing.Redeem(code,verifier)==null,"One-use code yields correct protected subject");
|
||||
Check(grant.UserId==7&&grant.Stamp==stamp&&!grant.RetainImport&&pairing.Redeem(code,verifier)==null,"One-use code yields correct protected subject");
|
||||
var legacy=protection.CreateProtector("PlotDirector.NativeCompanion.Access.v1").Protect(System.Text.Json.JsonSerializer.Serialize(new{UserId=7,Stamp=stamp,Expires=clock.GetUtcNow().AddHours(4)}));Check(pairing.Read(legacy) is {RetainImport:false},"Existing grants remain valid without implicitly enabling source retention");
|
||||
Check(pairing.Read("tampered"+token)==null,"Tampered grant refused");clock.Now=clock.Now.AddHours(5);Check(pairing.Read(token)==null,"Expired grant refused");
|
||||
var expires=pairing.Start(challenge);clock.Now=clock.Now.AddMinutes(6);Check(!pairing.Approve(expires,7,stamp),"Expired browser request refused");
|
||||
var request=new AiChapterRequest{RequestId=Guid.NewGuid(),BookId=3,ManuscriptId=Guid.NewGuid(),SessionId=Guid.NewGuid(),ChapterStart=100,ChapterEnd=135,Paragraphs=[new(){Index=1,Start=100,End=110,Text="First scene."},new(){Index=2,Start=110,End=111,Text="\r"},new(){Index=3,Start=111,End=135,Text="Second scene begins."}]};
|
||||
|
||||
@ -8,7 +8,7 @@ INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@Project,N'Nat
|
||||
DECLARE @Review uniqueidentifier=NEWID(),@Doc uniqueidentifier=NEWID(),@Operation uniqueidentifier=NEWID();
|
||||
DECLARE @Key nvarchar(80)=CONCAT('native:',REPLACE(CONVERT(nvarchar(36),@Doc),'-',''),':10');
|
||||
INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,EncryptedSource)
|
||||
VALUES(@Review,@User,@Book,@Doc,10,30,'fixture-hash',N'{"Scenes":[]}',N'[]',N'fixture-encrypted-source');
|
||||
VALUES(@Review,@User,@Book,@Doc,10,30,'fixture-hash',N'{"DocumentRevision":2,"Scenes":[{"Start":10,"End":30}]}',N'[]',N'fixture-encrypted-source');
|
||||
DECLARE @Items nvarchar(max)=(SELECT @Review ReviewID,1 Version,@Key [Key],'fixture-hash' Hash,N'Approved opening' Title,10 Start,30 [End],JSON_QUERY((SELECT CONCAT(@Key,':10') [Key],N'Approved scene' Title,N'An author-approved summary.' Summary,N'Preserved source prose.' [Text],1 StartParagraph,1 EndParagraph,3 Words FOR JSON PATH)) Scenes FOR JSON PATH);
|
||||
EXEC dbo.NativeReviewImport @Action='Commit',@UserID=@User,@BookID=@Book,@OperationID=@Operation,@DocumentGuid=@Doc,@ItemsJson=@Items;
|
||||
IF (SELECT COUNT(*) FROM dbo.Chapters WHERE BookID=@Book AND IsArchived=0)<>1 THROW 51000,'Wrong chapter creation count',1;
|
||||
@ -18,9 +18,15 @@ EXEC dbo.NativeReviewImport @Action='Commit',@UserID=@User,@BookID=@Book,@Operat
|
||||
IF (SELECT COUNT(*) FROM dbo.Chapters WHERE BookID=@Book AND IsArchived=0)<>1 THROW 51000,'Retry duplicated chapter',1;
|
||||
-- Incremental new chapter appends; existing author relationships/scene are untouched.
|
||||
DECLARE @Review2 uniqueidentifier=NEWID(),@Operation2 uniqueidentifier=NEWID(),@Key2 nvarchar(80)=CONCAT('native:',REPLACE(CONVERT(nvarchar(36),@Doc),'-',''),':30');
|
||||
INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,EncryptedSource) VALUES(@Review2,@User,@Book,@Doc,30,50,'next-hash',N'{}',N'[]',N'fixture');
|
||||
INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,EncryptedSource) VALUES(@Review2,@User,@Book,@Doc,30,50,'next-hash',N'{"DocumentRevision":2,"Scenes":[{"Start":30,"End":50}]}',N'[]',N'fixture');
|
||||
SET @Items=(SELECT @Review2 ReviewID,1 Version,@Key2 [Key],'next-hash' Hash,N'Approved continuation' Title,30 Start,50 [End],JSON_QUERY((SELECT CONCAT(@Key2,':30') [Key],N'Next approved scene' Title,N'Next summary.' Summary,N'Next preserved source.' [Text],2 StartParagraph,2 EndParagraph,3 Words FOR JSON PATH)) Scenes FOR JSON PATH);
|
||||
EXEC dbo.NativeReviewImport @Action='Commit',@UserID=@User,@BookID=@Book,@OperationID=@Operation2,@DocumentGuid=@Doc,@ItemsJson=@Items;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE BookID=@Book AND ChapterNumber=2 AND ChapterTitle=N'Approved continuation') THROW 51000,'Incremental chapter ordering failed',1;
|
||||
IF (SELECT COUNT(*) FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@Book AND s.IsArchived=0)<>2 THROW 51000,'Incremental scene count failed',1;
|
||||
CREATE TABLE #NativePosition(ChapterID int,SceneID int NULL);
|
||||
INSERT #NativePosition EXEC dbo.NativeImportedPosition @UserID=@User,@BookID=@Book,@DocumentGuid=@Doc,@Revision=2,@Position=12;
|
||||
IF (SELECT COUNT(*) FROM #NativePosition)<>1 OR NOT EXISTS(SELECT 1 FROM #NativePosition WHERE SceneID IS NOT NULL) THROW 51000,'Imported scene cursor mapping failed',1;
|
||||
TRUNCATE TABLE #NativePosition;
|
||||
INSERT #NativePosition EXEC dbo.NativeImportedPosition @UserID=@User,@BookID=@Book,@DocumentGuid=@Doc,@Revision=3,@Position=12;
|
||||
IF EXISTS(SELECT 1 FROM #NativePosition) THROW 51000,'Stale imported positions accepted',1;
|
||||
SELECT 'PASS canonical native initial import, source/summary preservation, retry and incremental append';
|
||||
|
||||
21
PlotLine.Tests/Sql/NativeApprovedImportRollback.sql
Normal file
21
PlotLine.Tests/Sql/NativeApprovedImportRollback.sql
Normal file
@ -0,0 +1,21 @@
|
||||
IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Development only',1;
|
||||
DECLARE @Project int,@Book int,@Operation uniqueidentifier=NEWID();
|
||||
BEGIN TRY
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @User int=(SELECT TOP(1) UserID FROM dbo.AppUser ORDER BY UserID),@Review uniqueidentifier=NEWID(),@Doc uniqueidentifier=NEWID();
|
||||
INSERT dbo.Projects(ProjectName) VALUES(N'Native rollback isolated fixture');SET @Project=SCOPE_IDENTITY();
|
||||
INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole) VALUES(@Project,@User,N'Owner');
|
||||
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@Project,N'Rollback isolated fixture',1,1);SET @Book=SCOPE_IDENTITY();
|
||||
INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,EncryptedSource) VALUES(@Review,@User,@Book,@Doc,0,20,'rollback-hash',N'{"DocumentRevision":1,"Scenes":[{"Start":0,"End":20}]}',N'fixture');
|
||||
DECLARE @Items nvarchar(max)=(SELECT @Review ReviewID,1 Version,'rollback-chapter' [Key],'rollback-hash' Hash,'Rollback chapter' Title,0 Start,20 [End],JSON_QUERY(N'[{"Key":"rollback-chapter:0","Title":"Rollback scene","Text":null,"StartParagraph":1,"EndParagraph":1,"Words":0}]') Scenes FOR JSON PATH);
|
||||
-- Deliberately force a canonical source-save constraint failure AFTER the core build emitted its maps.
|
||||
EXEC dbo.NativeReviewImport @Action='Commit',@UserID=@User,@BookID=@Book,@OperationID=@Operation,@DocumentGuid=@Doc,@ItemsJson=@Items;
|
||||
THROW 51000,'Expected source-save failure did not occur',1;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
DECLARE @Error int=ERROR_NUMBER();
|
||||
IF @@TRANCOUNT>0 ROLLBACK;
|
||||
IF @Error<>515 THROW;
|
||||
IF EXISTS(SELECT 1 FROM dbo.Projects WHERE ProjectID=@Project) OR EXISTS(SELECT 1 FROM dbo.NativeImportOperations WHERE OperationID=@Operation) OR EXISTS(SELECT 1 FROM dbo.Chapters WHERE BookID=@Book) THROW 51000,'Partial import survived source failure',1;
|
||||
SELECT 'PASS source-stage failure rolled back core chapters, scenes, receipt and fixture; review/canonical author data untouched';
|
||||
END CATCH;
|
||||
@ -21,12 +21,12 @@ public sealed class NativeCompanionAuthController(DesktopPairing pairing):Contro
|
||||
public IActionResult Approve(string code)
|
||||
{Response.Headers.CacheControl="no-store";Response.Headers["Referrer-Policy"]="no-referrer";return !string.IsNullOrEmpty(code)&&pairing.Exists(code)?View("Approve",code):BadRequest("This request expired. Start Connect again in Word.");}
|
||||
[Authorize,HttpPost("native-companion/authorize"),ValidateAntiForgeryToken]
|
||||
public IActionResult ApproveGrant(string code)
|
||||
public IActionResult ApproveGrant(string code,bool retainImport=false)
|
||||
{
|
||||
if(string.IsNullOrEmpty(code))return BadRequest();
|
||||
if(!int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var user)||!Guid.TryParse(User.FindFirstValue("PlotLine.SecurityStamp"),out var stamp))return Forbid();
|
||||
Response.Headers.CacheControl="no-store";
|
||||
return pairing.Approve(code,user,stamp)?Content("Word Companion connected. You may close this tab. The grant expires in four hours; signing out in Word discards it."):BadRequest("This request expired or was already approved.");
|
||||
return pairing.Approve(code,user,stamp,retainImport)?Content("Word Companion connected. You may close this tab. The grant expires in four hours; signing out in Word discards it."):BadRequest("This request expired or was already approved.");
|
||||
}
|
||||
[AllowAnonymous,HttpPost("api/native-companion/token")]
|
||||
public IActionResult Token([FromBody] PairRedeem request)
|
||||
|
||||
@ -30,15 +30,16 @@ public sealed class NativeCompanionController(IWordCompanionRepository repositor
|
||||
if(await repository.GetBookStructureAsync(request.BookId,UserId)==null)return Forbid();
|
||||
try
|
||||
{
|
||||
var retain=User.HasClaim("NativeCompanion.RetainImport","true");
|
||||
var mapped=NativeChapterMapping.Build(request,Math.Clamp(configuration.GetValue("NativeCompanion:MaxChapterCharacters",120000),10000,500000));
|
||||
var contentHash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{request.ChapterStart,request.ChapterEnd,request.Paragraphs})));
|
||||
if(reviews!=null){var prior=await reviews.Find(UserId,request.BookId,request.ManuscriptId,contentHash);if(prior!=null){if(request.RetainForImport&&prior.EncryptedSource==null&&importService!=null){prior.EncryptedSource=importService.Protect(request);await reviews.Save(prior);}var saved=JsonSerializer.Deserialize<AiChapterResult>(prior.ResultJson)!;saved.SourceRetained=prior.EncryptedSource!=null;saved.RequestId=request.RequestId;saved.DocumentRevision=request.Revision;saved.ReviewPath=$"/native-companion/reviews/{prior.ReviewID}";return Ok(saved);}}
|
||||
if(reviews!=null){var prior=await reviews.Find(UserId,request.BookId,request.ManuscriptId,contentHash);if(prior!=null){if(retain&&prior.EncryptedSource==null&&importService!=null){prior.EncryptedSource=importService.Protect(request);prior.SourceRevision=request.Revision;await reviews.Save(prior);}var saved=JsonSerializer.Deserialize<AiChapterResult>(prior.ResultJson)!;saved.SourceRetained=prior.EncryptedSource!=null;saved.RequestId=request.RequestId;saved.DocumentRevision=request.Revision;saved.ReviewPath=$"/native-companion/reviews/{prior.ReviewID}";return Ok(saved);}}
|
||||
var hash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(request)));
|
||||
var author=UserId;var task=cache.Run(author,request.RequestId,hash,async cancellation=>{
|
||||
await using var scope=scopes.CreateAsyncScope();
|
||||
var result=await scope.ServiceProvider.GetRequiredService<IManuscriptStructureAnalysisService>().AnalyseChapterAsync(mapped,cancellation);
|
||||
var mappedResult=NativeChapterMapping.Map(request,result);
|
||||
if(mappedResult.State=="complete"&&reviews!=null){var row=await scope.ServiceProvider.GetRequiredService<INativeReviewRepository>().Save(new(){ReviewID=request.RequestId,UserID=author,BookID=request.BookId,ManuscriptID=request.ManuscriptId,ChapterStart=request.ChapterStart,ChapterEnd=request.ChapterEnd,ContentHash=contentHash,ResultJson=JsonSerializer.Serialize(mappedResult),EncryptedSource=request.RetainForImport?importService?.Protect(request):null});mappedResult.SourceRetained=row.EncryptedSource!=null;mappedResult.ReviewPath=$"/native-companion/reviews/{row.ReviewID}";}
|
||||
if(mappedResult.State=="complete"&&reviews!=null){var row=await scope.ServiceProvider.GetRequiredService<INativeReviewRepository>().Save(new(){ReviewID=request.RequestId,UserID=author,BookID=request.BookId,ManuscriptID=request.ManuscriptId,ChapterStart=request.ChapterStart,ChapterEnd=request.ChapterEnd,ContentHash=contentHash,ResultJson=JsonSerializer.Serialize(mappedResult),SourceRevision=request.Revision,EncryptedSource=retain?importService?.Protect(request):null});mappedResult.SourceRetained=row.EncryptedSource!=null;mappedResult.ReviewPath=$"/native-companion/reviews/{row.ReviewID}";}
|
||||
return mappedResult;
|
||||
},request.BookId);
|
||||
Response.Headers.CacheControl="no-store";
|
||||
|
||||
@ -8,7 +8,7 @@ using PlotLine.Data;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
namespace PlotLine.Controllers;
|
||||
[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")]
|
||||
public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext<NativeCompanionPresenceHub>? live=null):ControllerBase
|
||||
public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext<NativeCompanionPresenceHub>? live=null,INativePositionRepository? positions=null):ControllerBase
|
||||
{
|
||||
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
private string Grant=>User.FindFirstValue("NativeCompanion.Grant")??throw new InvalidOperationException();
|
||||
@ -17,11 +17,14 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC
|
||||
public async Task<IActionResult> Update(Guid instance,Guid session,NativePresence input)
|
||||
{
|
||||
input.Navigation=null;var book=await access.GetBookStructureAsync(input.BookId,Author);if(book==null)return Forbid();
|
||||
if(input.CursorStart is <0)return BadRequest("Invalid cursor position.");
|
||||
if(input.WordAvailable&&input.SceneId==null&&input.CursorStart.HasValue&&positions!=null){var mapped=await positions.Resolve(Author,input.BookId,input.ManuscriptId,input.Revision,input.CursorStart.Value);if(mapped!=null&&(!input.ChapterId.HasValue||input.ChapterId==mapped.ChapterID)){input.ChapterId=mapped.ChapterID;input.SceneId=mapped.SceneID;}}
|
||||
var chapter=input.ChapterId.HasValue?book.Chapters.FirstOrDefault(c=>c.ChapterId==input.ChapterId):null;
|
||||
if(input.SceneId.HasValue){var parent=book.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==input.SceneId));if(parent==null||(chapter!=null&&chapter!=parent))return NotFound();chapter=parent;input.ChapterId=parent.ChapterId;}
|
||||
if(input.ChapterId.HasValue&&chapter==null)return NotFound();
|
||||
var before=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session);
|
||||
if(!presence.Put(Author,Grant,Expires,instance,session,input))return Conflict(new{message="Stale, revoked or invalid native session."});
|
||||
if(live!=null)await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted);
|
||||
if(live!=null&&(before==null||before.Position.BookId!=input.BookId||before.Position.ManuscriptId!=input.ManuscriptId||before.Position.Revision!=input.Revision||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.Active!=input.Active||before.Position.WordAvailable!=input.WordAvailable))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted);
|
||||
input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);return Ok(input);
|
||||
}
|
||||
[HttpDelete("instances/{instance:guid}/documents/{session:guid}/presence")]
|
||||
|
||||
@ -3,7 +3,7 @@ using System.Text.Json;
|
||||
using Dapper;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
namespace PlotLine.Data;
|
||||
public sealed class NativeImportedChapter {public string ChapterKey{get;set;}="";public string ContentHash{get;set;}="";public int ReviewVersion{get;set;}}
|
||||
public sealed class NativeImportedChapter {public Guid? DocumentGuid{get;set;}public int? ChapterStart{get;set;}public int? ChapterEnd{get;set;}public string ChapterKey{get;set;}="";public string ContentHash{get;set;}="";public int ReviewVersion{get;set;}}
|
||||
public interface INativeImportRepository
|
||||
{
|
||||
Task<IReadOnlyList<NativeImportedChapter>> List(int user,int book);
|
||||
@ -12,7 +12,7 @@ public interface INativeImportRepository
|
||||
}
|
||||
public sealed class NativeImportRepository(ISqlConnectionFactory factory):INativeImportRepository
|
||||
{
|
||||
public async Task<IReadOnlyList<NativeImportedChapter>> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync<NativeImportedChapter>("dbo.NativeReviewImport",new{Action="List",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();}
|
||||
public async Task<IReadOnlyList<NativeImportedChapter>> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync<NativeImportedChapter>("dbo.NativeImportedCatalog",new{UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();}
|
||||
public async Task<NativeImportResult?> Result(int user,Guid operation){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<NativeImportResult>("dbo.NativeReviewImport",new{Action="Result",UserID=user,OperationID=operation},commandType:CommandType.StoredProcedure);}
|
||||
public async Task<NativeImportResult> Commit(int user,Guid operation,NativeImportPlan plan)
|
||||
{
|
||||
|
||||
9
PlotLine/Data/NativePositionRepository.cs
Normal file
9
PlotLine/Data/NativePositionRepository.cs
Normal file
@ -0,0 +1,9 @@
|
||||
using System.Data;
|
||||
using Dapper;
|
||||
namespace PlotLine.Data;
|
||||
public sealed class NativeSavedPosition{public int ChapterID{get;set;}public int? SceneID{get;set;}}
|
||||
public interface INativePositionRepository{Task<NativeSavedPosition?> Resolve(int user,int book,Guid document,long revision,int position);}
|
||||
public sealed class NativePositionRepository(ISqlConnectionFactory factory):INativePositionRepository
|
||||
{
|
||||
public async Task<NativeSavedPosition?> Resolve(int user,int book,Guid document,long revision,int position){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<NativeSavedPosition>("dbo.NativeImportedPosition",new{UserID=user,BookID=book,DocumentGuid=document,Revision=revision,Position=position},commandType:CommandType.StoredProcedure);}
|
||||
}
|
||||
@ -3,7 +3,7 @@ using Dapper;
|
||||
namespace PlotLine.Data;
|
||||
public sealed class NativeReview
|
||||
{
|
||||
public string? EncryptedSource{get;set;}public Guid ReviewID {get;set;}public int UserID {get;set;}public int BookID {get;set;}public Guid ManuscriptID {get;set;}public int ChapterStart {get;set;}public int ChapterEnd {get;set;}public string ContentHash {get;set;}="";public string ResultJson {get;set;}="";public string? DecisionsJson {get;set;}public int Version {get;set;}public DateTime CreatedUtc {get;set;}
|
||||
public long? SourceRevision{get;set;}public string? EncryptedSource{get;set;}public Guid ReviewID {get;set;}public int UserID {get;set;}public int BookID {get;set;}public Guid ManuscriptID {get;set;}public int ChapterStart {get;set;}public int ChapterEnd {get;set;}public string ContentHash {get;set;}="";public string ResultJson {get;set;}="";public string? DecisionsJson {get;set;}public int Version {get;set;}public DateTime CreatedUtc {get;set;}
|
||||
}
|
||||
public interface INativeReviewRepository
|
||||
{
|
||||
@ -19,6 +19,6 @@ public sealed class NativeReviewRepository(ISqlConnectionFactory factory):INativ
|
||||
public Task<NativeReview?> Find(int user,int book,Guid manuscript,string hash)=>Read(new{Action="Find",UserID=user,BookID=book,ManuscriptID=manuscript,ContentHash=hash});
|
||||
public Task<NativeReview?> Get(int user,Guid id)=>Read(new{Action="Get",UserID=user,ReviewID=id});
|
||||
public async Task<IReadOnlyList<NativeReview>> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync<NativeReview>("dbo.NativeChapterReview_Access",new{Action="List",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();}
|
||||
public async Task<NativeReview> Save(NativeReview r){var saved=await Read(new{Action="Save",r.UserID,r.BookID,r.ReviewID,r.ManuscriptID,r.ChapterStart,r.ChapterEnd,r.ContentHash,r.ResultJson})??throw new InvalidOperationException("Review was not saved.");if(!string.IsNullOrEmpty(r.EncryptedSource)){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.NativeReviewSource_Save",new{r.UserID,ReviewID=saved.ReviewID,r.EncryptedSource},commandType:CommandType.StoredProcedure);saved.EncryptedSource??=r.EncryptedSource;}return saved;}
|
||||
public async Task<NativeReview> Save(NativeReview r){var saved=await Read(new{Action="Save",r.UserID,r.BookID,r.ReviewID,r.ManuscriptID,r.ChapterStart,r.ChapterEnd,r.ContentHash,r.ResultJson})??throw new InvalidOperationException("Review was not saved.");if(!string.IsNullOrEmpty(r.EncryptedSource)){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.NativeReviewSource_Save",new{r.UserID,ReviewID=saved.ReviewID,r.EncryptedSource,ObservedRevision=r.SourceRevision},commandType:CommandType.StoredProcedure);saved.EncryptedSource??=r.EncryptedSource;}return saved;}
|
||||
public async Task<bool> Decide(int user,Guid id,int version,string json){using var db=factory.CreateConnection();return await db.ExecuteScalarAsync<int>("dbo.NativeChapterReview_Access",new{Action="Decide",UserID=user,ReviewID=id,Version=version,DecisionsJson=json},commandType:CommandType.StoredProcedure)==1;}
|
||||
}
|
||||
|
||||
@ -97,6 +97,7 @@ public class Program
|
||||
builder.Services.AddSingleton<PlotLine.Services.NativeCompanion.DesktopPairing>();
|
||||
builder.Services.AddAuthentication().AddScheme<Microsoft.AspNetCore.Authentication.AuthenticationSchemeOptions, PlotLine.Services.NativeCompanion.DesktopAuthentication>(PlotLine.Services.NativeCompanion.DesktopPairing.Scheme, _ => { });
|
||||
builder.Services.AddSingleton<PlotLine.Services.NativeCompanion.NativeAnalysisCache>();
|
||||
builder.Services.AddScoped<PlotLine.Data.INativePositionRepository,PlotLine.Data.NativePositionRepository>();
|
||||
builder.Services.AddScoped<PlotLine.Data.INativeImportRepository,PlotLine.Data.NativeImportRepository>();
|
||||
builder.Services.AddScoped<PlotLine.Services.NativeCompanion.NativeImportService>();
|
||||
builder.Services.AddScoped<PlotLine.Data.INativeReviewRepository,PlotLine.Data.NativeReviewRepository>();
|
||||
|
||||
@ -29,8 +29,8 @@ public sealed class DesktopPairing(IDataProtectionProvider protection, TimeProvi
|
||||
}
|
||||
}
|
||||
public bool Exists(string code){lock(gate)return pending.TryGetValue(code,out var p)&&p.Expires>clock.GetUtcNow()&&p.UserId==null;}
|
||||
public bool Approve(string code,int userId,Guid stamp)
|
||||
{lock(gate){if(!pending.TryGetValue(code,out var p)||p.Expires<=clock.GetUtcNow()||p.UserId!=null)return false;p.UserId=userId;p.Stamp=stamp;return true;}}
|
||||
public bool Approve(string code,int userId,Guid stamp,bool retainImport=false)
|
||||
{lock(gate){if(!pending.TryGetValue(code,out var p)||p.Expires<=clock.GetUtcNow()||p.UserId!=null)return false;p.UserId=userId;p.Stamp=stamp;p.RetainImport=retainImport;return true;}}
|
||||
public string? Redeem(string code,string verifier)
|
||||
{
|
||||
if(verifier.Length<43||verifier.Length>128)return null;
|
||||
@ -39,7 +39,7 @@ public sealed class DesktopPairing(IDataProtectionProvider protection, TimeProvi
|
||||
if(!pending.TryGetValue(code,out var p)||p.Expires<=clock.GetUtcNow()||!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(p.Challenge),Encoding.ASCII.GetBytes(Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier))))))return null;
|
||||
if(p.UserId is not int user)return null;
|
||||
pending.Remove(code);
|
||||
return protector.Protect(JsonSerializer.Serialize(new Grant(user,p.Stamp,clock.GetUtcNow().AddHours(4))));
|
||||
return protector.Protect(JsonSerializer.Serialize(new Grant(user,p.Stamp,clock.GetUtcNow().AddHours(4),p.RetainImport)));
|
||||
}
|
||||
}
|
||||
public Grant? Read(string token)
|
||||
@ -47,8 +47,8 @@ public sealed class DesktopPairing(IDataProtectionProvider protection, TimeProvi
|
||||
try{var grant=JsonSerializer.Deserialize<Grant>(protector.Unprotect(token));return grant?.Expires>clock.GetUtcNow()?grant:null;}
|
||||
catch(Exception e)when(e is CryptographicException or JsonException or FormatException){return null;}
|
||||
}
|
||||
public sealed record Grant(int UserId,Guid Stamp,DateTimeOffset Expires);
|
||||
private sealed class Pending(string challenge,DateTimeOffset expires){public string Challenge=challenge;public DateTimeOffset Expires=expires;public int? UserId;public Guid Stamp;}
|
||||
public sealed record Grant(int UserId,Guid Stamp,DateTimeOffset Expires,bool RetainImport=false);
|
||||
private sealed class Pending(string challenge,DateTimeOffset expires){public string Challenge=challenge;public DateTimeOffset Expires=expires;public int? UserId;public Guid Stamp;public bool RetainImport;}
|
||||
}
|
||||
|
||||
public sealed class DesktopAuthentication(IOptionsMonitor<AuthenticationSchemeOptions> options,ILoggerFactory logger,UrlEncoder encoder,DesktopPairing pairing,IUserRepository users)
|
||||
@ -62,7 +62,7 @@ public sealed class DesktopAuthentication(IOptionsMonitor<AuthenticationSchemeOp
|
||||
var grant=pairing.Read(header[7..]);if(grant==null)return AuthenticateResult.Fail("Sign in again.");
|
||||
var user=await users.GetByIdAsync(grant.UserId);
|
||||
if(user==null||user.SecurityStamp!=grant.Stamp||(user.IsLocked&&(!user.LockoutEndUtc.HasValue||user.LockoutEndUtc>DateTime.UtcNow)))return AuthenticateResult.Fail("Sign in again.");
|
||||
var identity=new ClaimsIdentity([new(ClaimTypes.NameIdentifier,grant.UserId.ToString()),new("PlotLine.SecurityStamp",grant.Stamp.ToString()),new("NativeCompanion.Expires",grant.Expires.UtcDateTime.ToString("O")),new("NativeCompanion.Grant",Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(header[7..]))))],DesktopPairing.Scheme);
|
||||
var identity=new ClaimsIdentity([new(ClaimTypes.NameIdentifier,grant.UserId.ToString()),new("PlotLine.SecurityStamp",grant.Stamp.ToString()),new("NativeCompanion.RetainImport",grant.RetainImport?"true":"false"),new("NativeCompanion.Expires",grant.Expires.UtcDateTime.ToString("O")),new("NativeCompanion.Grant",Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(header[7..]))))],DesktopPairing.Scheme);
|
||||
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity),DesktopPairing.Scheme));
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,11 +6,11 @@ using PlotDirector.Companion.Protocol;
|
||||
using PlotLine.Data;
|
||||
namespace PlotLine.Services.NativeCompanion;
|
||||
public sealed record NativeImportItem(Guid ReviewID,int Version,string Key,string Hash,string Title,int Start,int End,NativeImportScene[] Scenes);
|
||||
public sealed record NativeImportScene(string Key,string Title,string Summary,string Text,int StartParagraph,int EndParagraph,int Words);
|
||||
public sealed record NativeImportPlan(int BookID,Guid ManuscriptID,NativeImportItem[] Items,string[] Conflicts,int Skipped,string Ticket);
|
||||
public sealed record NativeImportScene(string Key,string Title,string Summary,string Text,int? StartParagraph,int? EndParagraph,int Words);
|
||||
public sealed record NativeImportPlan(int BookID,Guid ManuscriptID,NativeImportItem[] Items,string[] Conflicts,int Skipped,string Ticket,string BookTitle="",int ProjectID=0);
|
||||
public sealed record NativeImportTicket(int User,int Book,Guid[] Reviews,int[] Versions,DateTime Expires,Guid Operation);
|
||||
public sealed class NativeImportResult {public int BuildID{get;set;}public int ChaptersCreated{get;set;}public int ScenesCreated{get;set;}public bool AlreadyBuilt{get;set;}public string Message{get;set;}="";}
|
||||
public sealed class NativeImportService(INativeReviewRepository reviews,IWordCompanionRepository access,INativeImportRepository imports,IDataProtectionProvider protection,ISubscriptionService subscriptions)
|
||||
public sealed class NativeImportResult {public int ProjectID{get;set;}public string BookTitle{get;set;}="";public int BookID{get;set;}public int Skipped{get;set;}public int BuildID{get;set;}public int ChaptersCreated{get;set;}public int ScenesCreated{get;set;}public bool AlreadyBuilt{get;set;}public string Message{get;set;}="";}
|
||||
public sealed class NativeImportService(INativeReviewRepository reviews,IWordCompanionRepository access,INativeImportRepository imports,IDataProtectionProvider protection,ISubscriptionService subscriptions,IBookRepository? books=null)
|
||||
{
|
||||
private readonly IDataProtector ticket=protection.CreateProtector("NativeImport.Confirmation.v1");
|
||||
private readonly IDataProtector source=protection.CreateProtector("NativeImport.Source.v1");
|
||||
@ -20,36 +20,40 @@ public sealed class NativeImportService(INativeReviewRepository reviews,IWordCom
|
||||
if(!(await subscriptions.CanUseFeatureAsync(user,Models.SubscriptionFeature.Import)).Allowed)throw new UnauthorizedAccessException("Import is not available on this account.");
|
||||
var structure=await access.GetBookStructureAsync(book,user)??throw new UnauthorizedAccessException("Book access denied.");
|
||||
if(ids.Length is <1 or >100||ids.Distinct().Count()!=ids.Length)throw new ArgumentException("Select up to 100 different chapter reviews.");
|
||||
var metadata=books==null?null:await books.GetAsync(book);
|
||||
var items=new List<NativeImportItem>();var conflicts=new List<string>();var skipped=0;Guid manuscript=Guid.Empty;var versions=new List<int>();
|
||||
foreach(var id in ids){var row=await reviews.Get(user,id)??throw new ArgumentException("A review expired or is unavailable.");if(row.BookID!=book)throw new UnauthorizedAccessException("Reviews must belong to this book.");versions.Add(row.Version);
|
||||
if(manuscript==Guid.Empty)manuscript=row.ManuscriptID;if(manuscript!=row.ManuscriptID)throw new ArgumentException("Select chapters from one manuscript.");
|
||||
var result=JsonSerializer.Deserialize<AiChapterResult>(row.ResultJson)!;var decisions=string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize<Controllers.NativeSceneDecision[]>(row.DecisionsJson)!;
|
||||
var approved=decisions.Where(d=>d.State=="approved").OrderBy(d=>d.Index).ToArray();skipped+=result.Scenes.Length-approved.Length;
|
||||
if(approved.Length==0){conflicts.Add($"{result.ChapterTitle}: no approved scenes. Save review decisions first.");continue;}
|
||||
if(string.IsNullOrEmpty(row.EncryptedSource)){conflicts.Add($"{result.ChapterTitle}: source prose was not retained. Use the updated Companion and explicitly retain this chapter for import.");continue;}
|
||||
if(string.IsNullOrEmpty(row.EncryptedSource)){conflicts.Add($"{result.ChapterTitle}: source prose was not retained. Reconnect the Companion, enable encrypted import capture in browser approval, and explicitly resubmit this chapter.");continue;}
|
||||
var capture=JsonSerializer.Deserialize<AiChapterRequest>(source.Unprotect(row.EncryptedSource))!;NativeChapterMapping.Build(capture);
|
||||
if(Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{capture.ChapterStart,capture.ChapterEnd,capture.Paragraphs})))!=row.ContentHash)throw new ArgumentException("Source content no longer matches this review.");
|
||||
if(capture.ManuscriptId!=row.ManuscriptID||capture.BookId!=book||capture.ChapterStart!=row.ChapterStart||capture.ChapterEnd!=row.ChapterEnd)throw new ArgumentException("Source identity mismatch.");
|
||||
var title=string.IsNullOrWhiteSpace(result.ChapterTitle)?"Chapter":result.ChapterTitle;var key="native:"+manuscript.ToString("N")+":"+row.ChapterStart;
|
||||
var scenes=new List<NativeImportScene>();foreach(var choice in approved){if(choice.Index<0||choice.Index>=result.Scenes.Length)throw new ArgumentException("Review boundaries are invalid.");var scene=result.Scenes[choice.Index];var paragraphs=capture.Paragraphs.Where(p=>p.Start>=scene.Start&&p.End<=scene.End&&!p.IsHeading).ToArray();if(paragraphs.Length==0)throw new ArgumentException("A scene has no source paragraphs.");var text=string.Join("",paragraphs.Select(p=>p.Text));scenes.Add(new(key+":"+scene.Start,choice.Title,choice.Summary,text,paragraphs[0].Index,paragraphs[^1].Index,Count(text)));}
|
||||
// Captures use chapter-relative paragraph indices. Do not mislabel them as
|
||||
// whole-document Word paragraph positions; native navigation uses absolute ranges.
|
||||
var scenes=new List<NativeImportScene>();foreach(var choice in approved){if(choice.Index<0||choice.Index>=result.Scenes.Length)throw new ArgumentException("Review boundaries are invalid.");var scene=result.Scenes[choice.Index];var paragraphs=capture.Paragraphs.Where(p=>p.Start>=scene.Start&&p.End<=scene.End&&!p.IsHeading).ToArray();if(paragraphs.Length==0)throw new ArgumentException("A scene has no source paragraphs.");var text=string.Join("",paragraphs.Select(p=>p.Text));scenes.Add(new(key+":"+scene.Start,choice.Title,choice.Summary,text,null,null,Count(text)));}
|
||||
items.Add(new(row.ReviewID,row.Version,key,row.ContentHash,title,row.ChapterStart,row.ChapterEnd,scenes.ToArray()));
|
||||
}
|
||||
var imported=await imports.List(user,book);var pending=new List<NativeImportItem>();foreach(var item in items.OrderBy(i=>i.Start)){
|
||||
var prior=imported.FirstOrDefault(p=>p.ChapterKey==item.Key);if(prior!=null){if(prior.ContentHash==item.Hash&&prior.ReviewVersion==item.Version){skipped+=item.Scenes.Length;continue;}conflicts.Add(item.Title+": already imported with different content/decisions; existing scenes will not be overwritten.");continue;}
|
||||
if(imported.Any(p=>p.DocumentGuid==manuscript&&p.ChapterStart<item.End&&item.Start<p.ChapterEnd))conflicts.Add(item.Title+": overlaps an imported chapter. Reconcile before importing.");
|
||||
if(structure.Chapters.Any(c=>string.Equals(c.Title.Trim(),item.Title.Trim(),StringComparison.OrdinalIgnoreCase)))conflicts.Add(item.Title+": an existing chapter has this title. Resolve the match before importing; no replacement is performed.");
|
||||
if(pending.Any(p=>p.Start<item.End&&item.Start<p.End))conflicts.Add(item.Title+": competing or overlapping chapter captures selected.");pending.Add(item);
|
||||
}
|
||||
var payload=new NativeImportTicket(user,book,ids,versions.ToArray(),DateTime.UtcNow.AddMinutes(20),operation??Guid.NewGuid());
|
||||
return new(book,manuscript,pending.ToArray(),conflicts.ToArray(),skipped,ticket.Protect(JsonSerializer.Serialize(payload)));
|
||||
return new(book,manuscript,pending.ToArray(),conflicts.ToArray(),skipped,ticket.Protect(JsonSerializer.Serialize(payload)),metadata?.BookDisplayTitle??"Book "+book,metadata?.ProjectID??0);
|
||||
}
|
||||
public async Task<NativeImportResult> Commit(int user,string confirmation)
|
||||
{
|
||||
NativeImportTicket saved;try{saved=JsonSerializer.Deserialize<NativeImportTicket>(ticket.Unprotect(confirmation))!;}catch(Exception e)when(e is CryptographicException or JsonException or ArgumentException){throw new ArgumentException("Invalid import confirmation.");}
|
||||
if(saved.User!=user||saved.Expires<DateTime.UtcNow)throw new UnauthorizedAccessException("Import confirmation expired or belongs to another account.");
|
||||
var prior=await imports.Result(user,saved.Operation);if(prior!=null){if(await access.GetBookStructureAsync(saved.Book,user)==null)throw new UnauthorizedAccessException();return prior;}
|
||||
var prior=await imports.Result(user,saved.Operation);if(prior!=null){if(await access.GetBookStructureAsync(saved.Book,user)==null)throw new UnauthorizedAccessException();prior.BookID=saved.Book;return prior;}
|
||||
var plan=await Preview(user,saved.Book,saved.Reviews,saved.Operation);for(var i=0;i<saved.Reviews.Length;i++)if((await reviews.Get(user,saved.Reviews[i]))?.Version!=saved.Versions[i])throw new ArgumentException("Review decisions changed. Preview again.");
|
||||
if(plan.Conflicts.Length>0)throw new ArgumentException(string.Join(" ",plan.Conflicts));if(plan.Items.Length==0)return new(){AlreadyBuilt=true,Message="All selected approved chapters already match an import. Nothing changed."};
|
||||
return await imports.Commit(user,saved.Operation,plan);
|
||||
if(plan.Conflicts.Length>0)throw new ArgumentException(string.Join(" ",plan.Conflicts));if(plan.Items.Length==0)return new(){BookID=saved.Book,Skipped=plan.Skipped,AlreadyBuilt=true,Message="All selected approved chapters already match an import. Nothing changed."};
|
||||
var result=await imports.Commit(user,saved.Operation,plan);result.BookID=saved.Book;result.ProjectID=plan.ProjectID;result.BookTitle=plan.BookTitle;result.Skipped=plan.Skipped;return result;
|
||||
}
|
||||
private static int Count(string text)=>text.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length;
|
||||
}
|
||||
|
||||
44
PlotLine/Sql/233_NativeImportedPositions.sql
Normal file
44
PlotLine/Sql/233_NativeImportedPositions.sql
Normal file
@ -0,0 +1,44 @@
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
IF COL_LENGTH(N'dbo.NativeReviewImports',N'DocumentGuid') IS NULL
|
||||
ALTER TABLE dbo.NativeReviewImports ADD DocumentGuid uniqueidentifier NULL,ObservationRevision bigint NULL,ChapterStart int NULL,ChapterEnd int NULL,ScenePositionsJson nvarchar(max) NULL;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.NativeReviewSource_Save @UserID int,@ReviewID uniqueidentifier,@EncryptedSource nvarchar(max),@ObservedRevision bigint=NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF DATALENGTH(@EncryptedSource)>8388608 THROW 51000,'Source capture too large',1;
|
||||
UPDATE dbo.NativeChapterReviews SET EncryptedSource=@EncryptedSource,ResultJson=CASE WHEN @ObservedRevision IS NOT NULL THEN JSON_MODIFY(ResultJson,'$.DocumentRevision',@ObservedRevision) ELSE ResultJson END WHERE ReviewID=@ReviewID AND UserID=@UserID AND EncryptedSource IS NULL;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER TRIGGER dbo.NativeReviewImports_CapturePositions ON dbo.NativeReviewImports AFTER INSERT
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
UPDATE n SET DocumentGuid=r.ManuscriptID,ObservationRevision=TRY_CONVERT(bigint,JSON_VALUE(r.ResultJson,'$.DocumentRevision')),ChapterStart=r.ChapterStart,ChapterEnd=r.ChapterEnd,
|
||||
ScenePositionsJson=(SELECT p.Start,p.[End],m.SceneID,n.ChapterID FROM OPENJSON(r.ResultJson,'$.Scenes') WITH(Start int,[End] int) p JOIN dbo.OnboardingManuscriptBuildSceneMap m ON m.OnboardingManuscriptBuildID=n.BuildID AND m.TemporarySceneKey=CONCAT(n.ChapterKey,':',p.Start) FOR JSON PATH)
|
||||
FROM dbo.NativeReviewImports n JOIN inserted i ON i.BookID=n.BookID AND i.ChapterKey=n.ChapterKey JOIN dbo.NativeChapterReviews r ON r.ReviewID=n.ReviewID;
|
||||
IF EXISTS(SELECT 1 FROM dbo.NativeReviewImports n JOIN inserted i ON i.BookID=n.BookID AND i.ChapterKey=n.ChapterKey JOIN dbo.NativeReviewImports other ON other.BookID=n.BookID AND other.DocumentGuid=n.DocumentGuid AND other.ChapterKey<>n.ChapterKey AND other.ChapterStart<n.ChapterEnd AND n.ChapterStart<other.ChapterEnd)
|
||||
THROW 51000,'An imported chapter overlaps this capture. Reconcile before importing.',1;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.NativeImportedCatalog @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 b.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1) THROW 51000,'Book access denied',1;
|
||||
SELECT ChapterKey,ContentHash,ReviewVersion,DocumentGuid,ChapterStart,ChapterEnd FROM dbo.NativeReviewImports WHERE BookID=@BookID;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.NativeImportedPosition @UserID int,@BookID int,@DocumentGuid uniqueidentifier,@Revision bigint,@Position 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 b.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1) RETURN;
|
||||
SELECT TOP(1) n.ChapterID,p.SceneID FROM dbo.NativeReviewImports n
|
||||
JOIN dbo.Chapters c ON c.ChapterID=n.ChapterID AND c.BookID=@BookID AND c.IsArchived=0
|
||||
OUTER APPLY(SELECT TOP(1) s.SceneID FROM OPENJSON(n.ScenePositionsJson) WITH(Start int,[End] int,SceneID int) s JOIN dbo.Scenes sc ON sc.SceneID=s.SceneID AND sc.ChapterID=n.ChapterID AND sc.IsArchived=0 WHERE @Position>=s.Start AND @Position<s.[End]) p
|
||||
WHERE n.BookID=@BookID AND n.DocumentGuid=@DocumentGuid AND n.ObservationRevision=@Revision AND @Position>=n.ChapterStart AND @Position<n.ChapterEnd;
|
||||
END;
|
||||
GO
|
||||
@ -9,6 +9,7 @@
|
||||
<form method="post" action="/native-companion/authorize">
|
||||
@Html.AntiForgeryToken()
|
||||
<input type="hidden" name="code" value="@Model" />
|
||||
<label class="form-check mb-3"><input class="form-check-input" type="checkbox" name="retainImport" value="true" /><span class="form-check-label">For this connection, retain encrypted copies of chapters I explicitly submit, so I can review and import them. Captures expire after 30 days; confirmed imports become my saved book data. This does not upload anything automatically.</span></label>
|
||||
<button type="submit" class="btn btn-primary">Approve this Word Companion connection</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@ -1,3 +1,3 @@
|
||||
@model PlotLine.Services.NativeCompanion.NativeImportResult
|
||||
@{ViewData["Title"]="Import result";}
|
||||
<div class="container py-4"><h1 class="h3">Approved import result</h1><div class="alert alert-success" role="status">@Model.Message</div><p>New chapters: @Model.ChaptersCreated · New scenes: @Model.ScenesCreated · Existing content overwritten: 0</p><p>Word prose and markers are unchanged. Saved PlotDirector scenes are now available in the book workspace. Automatic Word marker linkage is a separate action.</p><a href="/">Return to PlotDirector</a></div>
|
||||
<div class="container py-4"><h1 class="h3">Approved import result</h1>@if(!string.IsNullOrEmpty(Model.BookTitle)){<p>Book: @Model.BookTitle</p>}<div class="alert alert-success" role="status">@Model.Message</div><p>@(Model.AlreadyBuilt?"Previously created":"Created") chapters: @Model.ChaptersCreated · Scenes: @Model.ScenesCreated · Skipped selections: @Model.Skipped · Existing content overwritten: 0</p><p>Word prose and markers are unchanged. Saved PlotDirector scenes are now available in the book workspace. Automatic Word marker linkage is a separate action.</p><a asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID">Open the imported book</a></div>
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
@model PlotLine.Services.NativeCompanion.NativeImportPlan
|
||||
@{ViewData["Title"]="Preview approved import";}
|
||||
<div class="container py-4"><h1 class="h3">Preview approved import</h1><p>Creates @Model.Items.Length new chapters and @Model.Items.Sum(i=>i.Scenes.Length) scenes. @Model.Skipped rejected, pending or already imported scenes are skipped. Word remains unchanged.</p>
|
||||
<div class="container py-4"><h1 class="h3">Preview approved import</h1><h2 class="h5">Target book: @Model.BookTitle</h2><p>Creates @Model.Items.Length new chapters and @Model.Items.Sum(i=>i.Scenes.Length) scenes. @Model.Skipped rejected, pending or already imported scenes are skipped. Word remains unchanged.</p>
|
||||
<p>New chapters append in manuscript order. Existing chapters, relationships, plot lines and author metadata are preserved. Matching imported captures are skipped; competing changes require reconciliation.</p>
|
||||
@if(Model.Conflicts.Length>0){<div class="alert alert-warning"><h2 class="h5">Resolve before importing</h2><ul>@foreach(var conflict in Model.Conflicts){<li>@conflict</li>}</ul></div>}
|
||||
@foreach(var chapter in Model.Items){<section class="card mb-3"><h2 class="card-header h5">Create chapter: @chapter.Title</h2><ul class="list-group list-group-flush">@foreach(var scene in chapter.Scenes){<li class="list-group-item"><strong>Create scene: @scene.Title</strong><p>@scene.Summary</p><small>@scene.Words words</small></li>}</ul></section>}
|
||||
|
||||
@ -21,5 +21,5 @@
|
||||
<label class="form-label">Word session</label><select class="form-select mb-2" id="native-review-session">@foreach(var lease in Model.Sessions){<option data-instance="@lease.Instance" value="@lease.Session">@lease.Position.DocumentTitle</option>}</select>
|
||||
<input type="hidden" name="instanceId" id="native-review-instance" /><input type="hidden" name="sessionId" id="native-review-session-id" />
|
||||
<label class="form-label">Scene</label><select class="form-select mb-2" name="index">@for(var i=0;i<Model.Result.Scenes.Length;i++){<option value="@i">@(i+1) · @Model.Result.Scenes[i].Title</option>}</select><button class="btn btn-outline-secondary">Locate without changing text</button><p class="small">Requires the exact live manuscript and observed revision. Navigation is explicit and never triggered by following.</p></form></details><script src="~/js/native-companion-review.js" asp-append-version="true" defer></script>}
|
||||
<p class="mt-3">After saving decisions, return to the Companion workspace, select the reviewed chapters and preview the approved import. Only approved scenes are included. No import occurs until you confirm the preview. Older captures require the updated Companion to retain source prose explicitly.</p>
|
||||
<p class="mt-3">After saving decisions, return to the Companion workspace, select the reviewed chapters and preview the approved import. Only approved scenes are included. No import occurs until you confirm the preview. For older captures, reconnect the Companion, enable encrypted import capture in browser approval, then explicitly resubmit the chapter. Unchanged analysis can be reused.</p>
|
||||
</div>
|
||||
|
||||
@ -1,3 +1,3 @@
|
||||
@using System.Security.Claims
|
||||
<!DOCTYPE html><html lang="en" data-theme="light" data-bs-theme="light"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>@ViewData["Title"] · PlotDirector</title><link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /><link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /></head>
|
||||
<body class="writing-embedded" data-pd-user-id="@User.FindFirstValue(ClaimTypes.NameIdentifier)">@RenderBody()<script src="~/js/application-theme-sync.js" asp-append-version="true"></script>@await RenderSectionAsync("Scripts",required:false)</body></html>
|
||||
<!DOCTYPE html><html lang="en" data-theme="light" data-bs-theme="light"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>@ViewData["Title"] · PlotDirector</title><link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /><link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /><link rel="stylesheet" href="~/css/plotline-theme.css" asp-append-version="true" /></head>
|
||||
<body class="writing-embedded" data-pd-user-id="@User.FindFirstValue(ClaimTypes.NameIdentifier)">@RenderBody()<script src="~/js/writing-embedded-theme.js" asp-append-version="true"></script><script src="~/js/application-theme-sync.js" asp-append-version="true"></script>@await RenderSectionAsync("Scripts",required:false)</body></html>
|
||||
|
||||
2
PlotLine/wwwroot/js/writing-embedded-theme.js
Normal file
2
PlotLine/wwwroot/js/writing-embedded-theme.js
Normal file
@ -0,0 +1,2 @@
|
||||
// Reuse the surrounding PWA's theme policy; no separate theme settings or persistence.
|
||||
(()=>{if(parent===window)return;try{const outer=parent.document.documentElement;const sync=()=>{for(const name of ['data-app-theme','data-theme','data-bs-theme']){const value=outer.getAttribute(name);if(value)document.documentElement.setAttribute(name,value);else document.documentElement.removeAttribute(name);}};sync();const observer=new MutationObserver(sync);observer.observe(outer,{attributes:true,attributeFilter:['data-app-theme','data-theme','data-bs-theme']});window.addEventListener('pagehide',()=>observer.disconnect());}catch{/* A foreign embedding page cannot supply trusted appearance state. */}})();
|
||||
Loading…
x
Reference in New Issue
Block a user