Persist canonical AI scene suggestions and integrate scoped PWA presence and review

This commit is contained in:
Nick Beckley 2026-11-05 21:18:36 +00:00
parent 07cd67aeaa
commit b4b58af8e8
28 changed files with 382 additions and 24 deletions

View File

@ -30,7 +30,7 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable
if(job.Characters+f.Text.Length>120000){answer.Status="ai-chapter-too-large";break;}
if(job.Text.Length==0)job.ParagraphStart=f.Start;
job.Characters+=f.Text.Length;job.Text.Append(f.Text);job.Position=f.End;
if(f.CompletesParagraph){job.Paragraphs.Add(new(){Index=job.NextParagraph,Start=job.ParagraphStart,End=f.End,Text=job.Text.ToString(),IsHeading=f.OutlineLevel<=2});job.Text.Clear();job.NextParagraph++;}
if(f.CompletesParagraph){job.Paragraphs.Add(new(){Index=job.NextParagraph,Start=job.ParagraphStart,End=f.End,Text=job.Text.ToString(),IsHeading=f.OutlineLevel is 1 or 2});job.Text.Clear();job.NextParagraph++;}
answer.Progress=(int)(100L*(job.Position-job.Chapter.ChapterStart)/(job.Chapter.ChapterEnd-job.Chapter.ChapterStart));break;
case "ai-submit":
if(job.Submitted)break;

View File

@ -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)return new(){RequestId=chapter.RequestId,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(){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;
@ -105,7 +105,7 @@ public sealed class CloudGateway : IDisposable
await using var stream=await response.Content.ReadAsStreamAsync(cancellation);using var buffer=new MemoryStream();var bytes=new byte[8192];
int count;while((count=await stream.ReadAsync(bytes,cancellation))>0){if(buffer.Length+count>1024*1024)throw new InvalidDataException("AI response too large.");buffer.Write(bytes,0,count);}
buffer.Position=0;var result=await JsonSerializer.DeserializeAsync<AiChapterResult>(buffer,Json,cancellation)??throw new InvalidDataException();
if(result.RequestId!=chapter.RequestId||result.State is not ("complete" or "failed" or "cancelled")||result.Message==null||result.Message.Length>2048||result.Scenes==null||result.Scenes.Length>500||result.Scenes.Any(s=>s==null||s.Start<chapter.ChapterStart||s.End>chapter.ChapterEnd||s.End<=s.Start||s.Title==null||s.Reason==null||s.Confidence==null||s.Confidence.Length>32||s.Kind!="Scene"||s.Origin!="AI"||s.Title.Length>200||s.Reason.Length>600))throw new InvalidDataException("Invalid AI mapping.");
if(result.RequestId!=chapter.RequestId||result.State is not ("complete" or "failed" or "cancelled")||result.Message==null||result.Message.Length>2048||result.Scenes==null||result.Scenes.Length>500||result.Scenes.Any(s=>s==null||s.Start<chapter.ChapterStart||s.End>chapter.ChapterEnd||s.End<=s.Start||s.Title==null||s.Reason==null||s.Summary==null||s.Summary.Length>600||s.Confidence==null||s.Confidence.Length>32||s.Kind!="Scene"||s.Origin!="AI"||s.Title.Length>200||s.Reason.Length>600))throw new InvalidDataException("Invalid AI mapping.");
lock(gate)if(authenticationContext==expectedContext){health.Server="online";health.Authentication="verified";health.VerifiedUtc=DateTime.UtcNow;health.Ai=result.State=="complete"?"last-request-succeeded":"request-failed";health.Explanation=result.Message;if(result.State=="complete"){if(successful.Count>=64||successful.Values.Sum(r=>r.Scenes.Length)+result.Scenes.Length>8192)successful.Clear();successful[fingerprint]=result;}}
return result;
}
@ -142,7 +142,7 @@ public sealed class CloudGateway : IDisposable
private void DisconnectPresence(){Uri? site;string? access;lock(gate){site=origin;access=token;}if(site==null||access==null)return;_ = Task.Run(async()=>{try{using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(5));using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/presence/disconnect"));request.Headers.Authorization=new("Bearer",access);using var response=await http.SendAsync(request,timeout.Token);}catch(Exception e)when(e is HttpRequestException or OperationCanceledException or ObjectDisposedException) {}});}
public void OpenCompanionPage(string path,Guid context)
{lock(gate){Expire();if(context!=authenticationContext||token==null||origin==null)throw new InvalidOperationException("Sign in first.");if(!path.StartsWith("/native-companion/",StringComparison.Ordinal))throw new InvalidDataException();var url=new Uri(origin,path);if(url.GetLeftPart(UriPartial.Authority)!=origin.GetLeftPart(UriPartial.Authority))throw new InvalidDataException();openBrowser(url.AbsoluteUri);}}
public async Task Presence(Guid instance,Guid session,NativePresence presence,Guid context)=>await Post<NativePresence>($"api/native-companion/instances/{instance}/documents/{session}/presence",presence,context);
public async Task<NativePresence> Presence(Guid instance,Guid session,NativePresence presence,Guid context)=>await Post<NativePresence>($"api/native-companion/instances/{instance}/documents/{session}/presence",presence,context);
public async Task RemovePresence(Guid instance,Guid session){Guid context;lock(gate)context=authenticationContext;try{await Send<NativePresence>(HttpMethod.Delete,$"api/native-companion/instances/{instance}/documents/{session}/presence",null,context);}catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException){}}
public async Task CancelRemote(Guid id)
{

View File

@ -55,6 +55,7 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action<st
{
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="unsupported-version"},cancellation); return;
}
var trayAdapter=(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.TrayCapability);
instance = hello.WordInstanceId; sessions.Attach(instance,lease);
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability},cancellation);
log?.Invoke("peer-connected");
@ -67,7 +68,7 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action<st
foreach(var metric in message.Metrics)timings.Record(metric);
var watch = Stopwatch.StartNew();
var answer = sessions.Apply(lease,message);
if(control!=null)answer=control.Exchange(instance,message,answer);
if(control!=null&&trayAdapter)answer=control.Exchange(instance,message,answer);
await FrameCodec.WriteAsync(pipe,answer,cancellation).WaitAsync(TimeSpan.FromSeconds(3),cancellation);
log?.Invoke($"operation={message.Kind} status={answer.Status} elapsedMs={watch.Elapsed.TotalMilliseconds:F2} sessions={sessions.SessionCount} queueDepth={message.QueueDepth} wordInstance={instance:N} session={message.SessionId:N} correlation={message.CorrelationId:N}");
}

View File

@ -53,6 +53,7 @@ internal sealed class CompanionWindow:Form
var tabs=new TabControl{Dock=DockStyle.Fill};var chapterTab=new TabPage("Heading 1 chapters");chapterTab.Controls.Add(chapters);var settings=new TabPage("Settings and diagnostics");settings.Controls.Add(diagnostics);var options=new FlowLayoutPanel{Dock=DockStyle.Bottom,AutoSize=true};options.Controls.AddRange([Button("Check connection",()=>_ = cloud.CheckConnection()),Button("Disconnect / forget sign-in",()=>cloud.SignOut()),Button("Open diagnostics folder",()=>System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(directory){UseShellExecute=true}))]);settings.Controls.Add(options);tabs.TabPages.AddRange([chapterTab,settings]);layout.Controls.Add(tabs,0,7);
layout.Controls.Add(new Label{AutoSize=true,Text="Chapter prose is sent only after confirmation. Manuscript text and saved story data are never overwritten."},0,8);Controls.Add(layout);
documents.SelectedIndexChanged+=(_,_)=>{if(!refreshing&&documents.SelectedItem is TrayDocument d){selected=d.Session;chapterKey="";RefreshState();}};
chapters.DoubleClick+=(_,_)=>{if(chapters.SelectedItem is ChapterItem chapter)Safe(()=>control.Navigate(selected,chapter.Start));};
chapters.ItemCheck+=(_,e)=>{if(refreshing||renderedSession==Guid.Empty)return;if(!selections.TryGetValue(renderedSession,out var chosen)){if(selections.Count>=64)selections.Clear();selections[renderedSession]=chosen=[];}var start=((ChapterItem)chapters.Items[e.Index]).Start;if(e.NewValue==CheckState.Checked)chosen.Add(start);else chosen.Remove(start);};
detect.Click+=(_,_)=>Safe(()=>control.Detect(selected));cancel.Click+=(_,_)=>Safe(()=>control.Cancel(selected));
bookButton.Click+=(_,_)=>Safe(()=>{if(books.SelectedItem is not Protocol.CompanionBook book)return;if(remember.Checked&&MessageBox.Show("Remember this book in Word document metadata? This marks the document modified. It does not save or change prose.","Remember association",MessageBoxButtons.OKCancel)!=DialogResult.OK)return;control.SelectBook(selected,book.BookId,remember.Checked);});

View File

@ -57,13 +57,13 @@ 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;Next(doc);
doc.Total=doc.Pending.Count;doc.Done=0;doc.Failed=0;Next(doc);
}
}
private void Next(TrayDocument doc)
{
doc.Job=Guid.Empty;
if(doc.Pending.Count==0){doc.Status=$"Batch finished: {doc.Done}/{doc.Total} processed. 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.";
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;
@ -81,7 +81,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
if(doc.Job==Guid.Empty)continue;var result=ai.Result(doc.Session);
if(result?.RequestId==doc.Job&&result.State is "complete" or "failed" or "cancelled"){
if(result.State=="complete"){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{if(doc.Errors.Count>=50)doc.Errors.RemoveAt(0);doc.Errors.Add(doc.Current!.Title+": "+result.Message);}
else{doc.Failed++;if(doc.Errors.Count>=50)doc.Errors.RemoveAt(0);doc.Errors.Add(doc.Current!.Title+": "+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.";}
}}}
@ -91,7 +91,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
public async Task Heartbeat(CancellationToken cancellation)
{
while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromSeconds(15),cancellation);var available=Documents.Where(d=>d.Book>0).ToArray();
foreach(var doc in available){try{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);}catch(Exception e)when(NetworkFailure(e)) {}}
foreach(var doc in available){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)) {}}
if(available.Length==0&&lastBook>0){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 await cloud.RemovePresence(agentInstance,agentSession);
}
@ -101,7 +101,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
public sealed class TrayDocument
{
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 Book,Progress,Total,Done;public int? RememberedBook,Words,ChapterId,SceneId;public bool Active;public DateTime Observed,Started;
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 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)":"");
}

View File

@ -26,6 +26,7 @@ public sealed class AiParagraph
[DataContract]
public sealed class AiChapterResult
{
[DataMember] public long DocumentRevision {get;set;}
[DataMember] public string ChapterTitle {get;set;}="";
[DataMember] public string ReviewPath {get;set;}="";
[DataMember] public Guid RequestId { get; set; }

View File

@ -16,6 +16,7 @@ public sealed class AdapterCommand
[DataContract]
public sealed class NativePresence
{
[DataMember] public AdapterCommand? Navigation {get;set;}
[DataMember] public Guid ManuscriptId {get;set;}
[DataMember] public int BookId {get;set;}
[DataMember] public long Revision {get;set;}

View File

@ -36,10 +36,12 @@ internal static class ChapterAiTests
check(handler.Submissions==1&&result.Scenes.Single().Start==100&&handler.Last?.ChapterStart==100&&handler.Last.Paragraphs.Single().Index==1,"duplicate submit uses one HTTP call and preserves exact chapter mapping");
using(var frame=new MemoryStream())
{
var page=new AiChapterResult{State="complete",Scenes=Enumerable.Range(0,40).Select(_=>new StructureSuggestion{Title=new string('界',200),Reason=new string('界',600),ChapterTitle=new string('界',200),Origin="AI"}).ToArray()};
var page=new AiChapterResult{State="complete",Scenes=Enumerable.Range(0,40).Select(_=>new StructureSuggestion{Title=new string('界',200),Summary=new string('界',600),Reason=new string('界',600),ChapterTitle=new string('界',200),Origin="AI"}).ToArray()};
await FrameCodec.WriteAsync(frame,new Message{Ai=page},CancellationToken.None);check(frame.Length<=ProtocolVersion.MaxFrameBytes+4,"worst-case bounded AI page fits IPC framing");frame.Position=0;
check((await FrameCodec.ReadAsync(frame,CancellationToken.None)).Ai?.Scenes.Length==40,"AI result contract round-trips on actual frame codec");
}
id=Guid.NewGuid();Send("ai-begin");Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="One chapter paragraph.",CompletesParagraph=true});Send("ai-submit");await Wait(()=>Send("ai-status").Ai?.State=="complete");
check(handler.Submissions==1,"unchanged chapter uses agent content fingerprint without another prose upload");
var previous=id;id=Guid.NewGuid();Send("ai-begin");
check(jobs.Handle(descriptor,new(){Kind="ai-cancel",SnapshotId=previous},new(){Status="ok"}).Status=="obsolete-ai-request"&&Send("ai-status").Ai?.State=="reading","late cancellation cannot retire a replacement AI chapter");
Send("ai-cancel");

View File

@ -44,7 +44,7 @@ namespace PlotDirector.WordAddIn
return values.ToArray();
}
private LocalDocument active;
private bool disposed;private bool activationPending;
private bool disposed;private bool activationPending,traySupported;
public string WordCountSummary=>active?.WordCount?.ToString("N0")??"not read / stale";
private long busyFailures;
private string lastWordError;
@ -71,7 +71,7 @@ namespace PlotDirector.WordAddIn
link.StateChanged += state => PostToUi(() => {
ConnectionState = state;
if(state!="connected")
{
{traySupported=false;
foreach(var doc in documents.Values){StopAi(doc,"Agent disconnected. Successful AI suggestions retained; reconnect before retrying.");}
}
if (state == "connected")
@ -82,6 +82,7 @@ namespace PlotDirector.WordAddIn
invalidateRibbon();
});
link.Received += message => {
if(message.Status=="ready")PostToUi(()=>traySupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.TrayCapability));
if(message.Command!=null)PostToUi(()=>HandleCommand(message.Command));
if(message.WordCount.HasValue)PostToUi(()=>{var doc=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);if(doc!=null)doc.WordCount=message.WordCount;});
if(message.Status!="ok"&&message.Status!="ready")lastResult=message.Status;
@ -215,7 +216,7 @@ namespace PlotDirector.WordAddIn
};
public void OpenCompanion()
{
if(ConnectionState=="connected"){link.TryPost(new Message{Kind="tray-open"});return;}
if(ConnectionState=="connected"){if(!traySupported){MessageBox.Show("The running agent needs updating. Close Word normally and rerun the existing installer with -StopAgent.","PlotDirector Companion recovery");return;}link.TryPost(new Message{Kind="tray-open"});return;}
System.Threading.Tasks.Task.Run(()=>{try{AgentProcess.Start(true);if(!AgentProcess.LaunchStatus.StartsWith("Starting",StringComparison.Ordinal))PostToUi(()=>MessageBox.Show(AgentProcess.LaunchStatus,"PlotDirector Companion recovery"));}catch(Exception){PostToUi(()=>MessageBox.Show("Companion unavailable. Reinstall the complete developer package. Word remains usable.","PlotDirector Companion recovery"));}});
}
private void HandleCommand(AdapterCommand command)

View File

@ -0,0 +1,16 @@
const {chromium}=require('playwright');const fs=require('node:fs');const path=require('node:path');const assert=require('node:assert/strict');
(async()=>{const browser=await chromium.launch();try{
const page=await browser.newPage();await page.goto('about:blank');await page.setContent('<main id="native-workspace" data-book="3" data-project="1" data-instance="instance" data-session="session" data-mode="context"><p id="native-presence-status"></p><select id="native-session"></select><input type="checkbox" id="native-follow"><iframe id="native-story-workspace" hidden></iframe></main>');
await page.evaluate(()=>{window.polls=[];window.setInterval=f=>{polls.push(f);return 1;};window.live=[{instanceId:'instance',sessionId:'session',bookId:3,chapterId:10,sceneId:20,documentTitle:'Synthetic manuscript',wordAvailable:true,updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];window.fetch=async()=>({ok:true,json:async()=>live});const OriginalURL=URL;window.URL=class extends OriginalURL{constructor(url,base){super(url,base==='null'?'https://fixture.invalid':base);}};});
await page.addScriptTag({content:fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/native-companion-workspace.js'),'utf8')});
await assert.doesNotReject(()=>page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('connected')));
await page.check('#native-follow');await page.waitForFunction(()=>document.querySelector('iframe').src.includes('sceneId=20'));assert.ok((await page.locator('iframe').getAttribute('src')).includes('pinned=true'));
await page.evaluate(()=>{document.querySelector('#native-follow').checked=false;live[0].sceneId=21;polls[0]();});await page.waitForTimeout(30);assert.ok((await page.locator('iframe').getAttribute('src')).includes('sceneId=20'),'manual mode does not snap back to Word');
await page.evaluate(()=>{live=[];polls[0]();});await page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('disconnected'));assert.equal(await page.isChecked('#native-follow'),false);
await page.evaluate(()=>{live=[{wordAvailable:false,updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];polls[0]();});await page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('Word unavailable'));
console.log('PASS native PWA exact-session following, pinned scope, manual pause, disconnection and Word-unavailable states');
const badge=await browser.newPage();await badge.goto('about:blank');await badge.setContent('<div id="native-companion-status" hidden><a id="native-companion-status-link"></a><span id="native-companion-status-text"></span></div>');await badge.evaluate(()=>{window.tick=null;window.setInterval=f=>(tick=f,1);window.live=[];window.fetch=async()=>({ok:true,json:async()=>live});});
await badge.addScriptTag({content:fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/native-companion-status.js'),'utf8')});assert.equal(await badge.locator('#native-companion-status').isHidden(),true);
await badge.evaluate(()=>{live=[{bookId:3,instanceId:'a',sessionId:'b',wordAvailable:true,documentTitle:'Title <script>no</script>',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];tick();});await badge.waitForFunction(()=>document.querySelector('#native-companion-status').dataset.connected==='true');assert.equal(await badge.locator('#native-companion-status script').count(),0);
await badge.evaluate(()=>{live=[];tick();});await badge.waitForFunction(()=>document.querySelector('#native-companion-status').dataset.connected==='false');assert.equal(await badge.locator('#native-companion-status-link').isHidden(),true);console.log('PASS native presence badge never infers connection from associations and clears stale links safely');
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1)});

View File

@ -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<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.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")));
@ -84,6 +84,15 @@ internal static class NativeCompanionHttpTests
var response=await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request);Check(response.IsSuccessStatusCode,"Authenticated chapter API calls canonical service");
var result=await response.Content.ReadFromJsonAsync<AiChapterResult>();Check(result?.State=="complete"&&result.Scenes.Single().Start==20&&provider.Prompts.Count==1,"Actual HTTP response maps scene to Word position");
Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).IsSuccessStatusCode&&provider.Prompts.Count==1,"HTTP retry reuses successful provider result");
Check(result!.ReviewPath.StartsWith("/native-companion/reviews/")&&!string.IsNullOrWhiteSpace(result.Scenes.Single().Summary),"AI summary is preserved and saved PWA review handoff returned");
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");
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");
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");
Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(new Dictionary<string,string>{{"version","1"}}))).StatusCode==HttpStatusCode.BadRequest,"Review decisions require antiforgery");
Check((await agent.PostAsync("/api/native-companion/presence/disconnect",null)).IsSuccessStatusCode,"Signout disconnect revokes grant presence");
live.Sequence=2;Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/presence",live)).StatusCode==HttpStatusCode.Conflict,"Late heartbeat cannot restore signed-out presence");
request.BookId=999;Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).StatusCode==HttpStatusCode.Forbidden&&provider.Prompts.Count==1,"Foreign book rejected without provider charge");request.BookId=3;
allowed=false;Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).StatusCode==HttpStatusCode.Forbidden,"Subscription access enforced on HTTP path");allowed=true;
user.SecurityStamp=Guid.NewGuid();Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Revoked grant rejected through HTTP handler");

View File

@ -0,0 +1,50 @@
using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using PlotDirector.Companion.Protocol;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services.NativeCompanion;
internal static class NativeTrayIntegrationTests
{
public static async Task Run()
{
void Check(bool value,string message){if(!value)throw new Exception(message);}
var clock=new Clock();var store=new NativePresenceStore(clock);var instance=Guid.NewGuid();var session=Guid.NewGuid();var manuscript=Guid.NewGuid();
NativePresence Position(long seq)=>new(){BookId=3,ManuscriptId=manuscript,Sequence=seq,Revision=2,DocumentTitle="A manuscript",ChapterId=10,SceneId=20};
Check(store.Put(7,"grant",clock.Now.AddHours(4),instance,session,Position(1)),"First scoped heartbeat accepted");
Check(!store.Put(7,"grant",clock.Now.AddHours(4),instance,session,Position(1))&&!store.Put(7,"different",clock.Now.AddHours(4),instance,session,Position(2)),"Duplicate sequence and different grant cannot replace a live document");
Check(store.Read(8,3).Length==0&&store.Read(7,4).Length==0,"Presence read scoped to account and book");
Check(store.Navigate(7,3,instance,session,manuscript,2,10)&&!store.Navigate(8,3,instance,session,manuscript,2,10)&&!store.Navigate(7,3,instance,session,manuscript,1,10),"Navigation requires exact author, manuscript and observed revision");
Check(store.TakeNavigation(7,"different",instance,session)==null&&store.TakeNavigation(7,"grant",instance,session)?.Chapter?.Start==10&&store.TakeNavigation(7,"grant",instance,session)==null,"Explicit navigation delivered once only to its authenticated lease");
clock.Now=clock.Now.AddSeconds(46);Check(store.Read(7,3).Length==0,"Lost heartbeat expires without relying on old book association");
Check(store.Put(7,"grant",clock.Now.AddHours(4),instance,session,Position(2)),"Connection can recover after expiry");store.Revoke(7,"grant",clock.Now.AddHours(4));Check(store.Read(7,3).Length==0&&!store.Put(7,"grant",clock.Now.AddHours(4),instance,session,Position(3)),"Signout revokes late in-flight heartbeat");
var access=NativeWorkflowTests.Proxy<IWordCompanionRepository>((n,a)=>n=="GetBookStructureAsync"?Task.FromResult((int)a![0]! ==3?new WordCompanionBookStructureResponse{BookId=3,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=20}]}]}:null):throw new Exception("Unexpected canonical write "+n));
var http=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7"),new("NativeCompanion.Grant","fresh"),new("NativeCompanion.Expires",clock.Now.AddHours(4).ToString("O"))],DesktopPairing.Scheme))};
var presence=new NativePresenceController(store,access){ControllerContext=new(){HttpContext=http}};
var invalid=Position(4);invalid.SceneId=999;Check(await presence.Update(instance,session,invalid) is NotFoundResult,"Presence rejects foreign scene markers");invalid=Position(4);invalid.BookId=999;Check(await presence.Update(instance,session,invalid) is ForbidResult,"Presence rejects inaccessible books");
Check(await presence.Update(instance,session,Position(5)) is OkObjectResult,"Validated saved chapter/scene presence works");
var repo=new MemoryNativeReviews();var result=new AiChapterResult{State="complete",ChapterTitle="Opening",Scenes=[new(){Kind="Scene",Origin="AI",Title="Arrival",Summary="A saved AI summary.",Start=0,End=100}]};
var row=await repo.Save(new(){ReviewID=Guid.NewGuid(),UserID=7,BookID=3,ManuscriptID=manuscript,ContentHash="hash",ResultJson=JsonSerializer.Serialize(result)});
var books=NativeWorkflowTests.Proxy<IBookRepository>((n,a)=>Task.FromResult<Book?>(new(){BookID=3,ProjectID=1}));var workspace=new NativeWorkspaceController(access,books,repo,store){ControllerContext=new(){HttpContext=http},TempData=new TempDataDictionary(http,new TempData())};
Check(await workspace.Review(row.ReviewID) is ViewResult,"Saved AI title and summary can be reviewed in PWA without Word");
Check(await workspace.Decide(row.ReviewID,1,[new(){Index=0,State="approved",Title="Edited title",Summary="Edited summary"}]) is RedirectToActionResult,"Explicit approval/edit saves suggestions only");
Check(await workspace.Decide(row.ReviewID,1,[new(){Index=0,State="rejected",Title="Late edit",Summary=""}]) is ConflictObjectResult,"Stale review window cannot overwrite decisions");
Check(await workspace.Decide(row.ReviewID,2,[new(){Index=0,State="invented",Title="No",Summary=""}]) is BadRequestObjectResult,"Invalid decisions are refused");
http.User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"8")],"fixture"));Check(await workspace.Review(row.ReviewID) is NotFoundResult,"Other author cannot read saved chapter suggestions");
}
private sealed class TempData:ITempDataProvider{public IDictionary<string,object> LoadTempData(HttpContext context)=>new Dictionary<string,object>();public void SaveTempData(HttpContext context,IDictionary<string,object> values){}}
private sealed class Clock:TimeProvider{public DateTimeOffset Now=new(2026,11,5,12,0,0,TimeSpan.Zero);public override DateTimeOffset GetUtcNow()=>Now;}
}
internal sealed class MemoryNativeReviews:INativeReviewRepository
{
private readonly Dictionary<Guid,NativeReview> rows=[];
public Task<NativeReview?> Find(int user,int book,Guid manuscript,string hash)=>Task.FromResult(rows.Values.FirstOrDefault(r=>r.UserID==user&&r.BookID==book&&r.ManuscriptID==manuscript&&r.ContentHash==hash));
public Task<NativeReview?> Get(int user,Guid id)=>Task.FromResult(rows.TryGetValue(id,out var row)&&row.UserID==user?row:null);
public Task<IReadOnlyList<NativeReview>> List(int user,int book)=>Task.FromResult<IReadOnlyList<NativeReview>>(rows.Values.Where(r=>r.UserID==user&&r.BookID==book).ToArray());
public async Task<NativeReview> Save(NativeReview row){var prior=await Find(row.UserID,row.BookID,row.ManuscriptID,row.ContentHash);if(prior!=null)return prior;row.Version=1;row.CreatedUtc=DateTime.UtcNow;rows[row.ReviewID]=row;return row;}
public Task<bool> Decide(int user,Guid id,int version,string json){if(rows.TryGetValue(id,out var row)&&row.UserID==user&&row.Version==version){row.DecisionsJson=json;row.Version++;return Task.FromResult(true);}return Task.FromResult(false);}
}

View File

@ -122,12 +122,14 @@ if (args.Contains("--plot-lines"))
return;
}
if(args.Contains("--native-tray")){await NativeTrayIntegrationTests.Run();Console.WriteLine("PASS native tray presence, expiry, scope and persistent PWA review decisions");return;}
if(args.Contains("--native-workflow")){await NativeWorkflowTests.Run();Console.WriteLine("PASS native saved workspace and safe import preview validation");return;}
if(args.Contains("--native-companion-http")){await NativeCompanionHttpTests.Run();return;}
if(args.Contains("--native-companion")){await NativeCompanionTests.Run();Console.WriteLine("PASS native desktop pairing, canonical chapter AI/mapping, idempotency and cancellation");return;}
var tests = new (string Name, Action Test)[]
{
("Native tray presence and PWA review remain scoped, expiring and non-destructive", () => NativeTrayIntegrationTests.Run().GetAwaiter().GetResult()),
("Native saved workspace and established import eligibility remain scoped and read-only", () => NativeWorkflowTests.Run().GetAwaiter().GetResult()),
("Native companion authentication, canonical AI mapping and isolated chapter retry", () => NativeCompanionTests.Run().GetAwaiter().GetResult()),
("Solver never discards a corroborated concern or exhausts navigation before verification", WritingSolverDeadEndTests.Regression),

View File

@ -11,7 +11,7 @@ using PlotLine.Services.NativeCompanion;
namespace PlotLine.Controllers;
[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")]
public sealed class NativeCompanionController(IWordCompanionRepository repository,NativeAnalysisCache cache,IServiceScopeFactory scopes,IConfiguration configuration,ISubscriptionService subscriptions):ControllerBase
public sealed class NativeCompanionController(IWordCompanionRepository repository,NativeAnalysisCache cache,IServiceScopeFactory scopes,IConfiguration configuration,ISubscriptionService subscriptions,INativeReviewRepository? reviews=null):ControllerBase
{
private int UserId=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet("books")]
@ -31,11 +31,15 @@ public sealed class NativeCompanionController(IWordCompanionRepository repositor
try
{
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){var saved=JsonSerializer.Deserialize<AiChapterResult>(prior.ResultJson)!;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 task=cache.Run(UserId,request.RequestId,hash,async cancellation=>{
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);
return NativeChapterMapping.Map(request,result);
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)});mappedResult.ReviewPath=$"/native-companion/reviews/{row.ReviewID}";}
return mappedResult;
},request.BookId);
Response.Headers.CacheControl="no-store";
return Ok(await task.WaitAsync(HttpContext.RequestAborted));

View File

@ -0,0 +1,28 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotDirector.Companion.Protocol;
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):ControllerBase
{
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
private string Grant=>User.FindFirstValue("NativeCompanion.Grant")??throw new InvalidOperationException();
private DateTimeOffset Expires=>DateTimeOffset.Parse(User.FindFirstValue("NativeCompanion.Expires")!,System.Globalization.CultureInfo.InvariantCulture);
[HttpPost("instances/{instance:guid}/documents/{session:guid}/presence"),RequestSizeLimit(4096)]
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();
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();
if(!presence.Put(Author,Grant,Expires,instance,session,input))return Conflict(new{message="Stale, revoked or invalid native session."});
input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);return Ok(input);
}
[HttpDelete("instances/{instance:guid}/documents/{session:guid}/presence")]
public IActionResult Remove(Guid instance,Guid session){presence.Remove(Author,Grant,instance,session);return Ok(new NativePresence());}
[HttpPost("presence/disconnect")]
public IActionResult Disconnect(){presence.Revoke(Author,Grant,Expires);return NoContent();}
}

View File

@ -0,0 +1,57 @@
using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotDirector.Companion.Protocol;
using PlotLine.Data;
using PlotLine.Services.NativeCompanion;
namespace PlotLine.Controllers;
[Authorize,Route("native-companion")]
public sealed class NativeWorkspaceController(IWordCompanionRepository access,IBookRepository books,INativeReviewRepository reviews,NativePresenceStore presence):Controller
{
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet("workspace")]
public async Task<IActionResult> Workspace(int bookId,Guid? instanceId,Guid? sessionId,string view="book")
{
if(await access.GetBookStructureAsync(bookId,Author)==null)return Forbid();var book=await books.GetAsync(bookId);if(book==null)return NotFound();
return View(new NativeWorkspaceModel(bookId,book.ProjectID,book.BookDisplayTitle,instanceId,sessionId,view is "context" or "intent"?view:"book",await reviews.List(Author,bookId)));
}
[HttpGet("presence")]
public async Task<IActionResult> Presence(int bookId)
{
if(await access.GetBookStructureAsync(bookId,Author)==null)return Forbid();Response.Headers.CacheControl="no-store";
return Json(presence.Read(Author,bookId).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,manuscriptId=l.Position.ManuscriptId,l.Position.BookId,l.Position.ChapterId,l.Position.SceneId,l.Position.DocumentTitle,l.Position.Active,l.Position.WordAvailable,updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
}
[HttpGet("status")]
public async Task<IActionResult> Status()
{
Response.Headers.CacheControl="no-store";var leases=presence.Read(Author,0);var allowed=new HashSet<int>();
foreach(var book in leases.Select(l=>l.Position.BookId).Distinct())if(await access.GetBookStructureAsync(book,Author)!=null)allowed.Add(book);
return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
}
[HttpGet("reviews/{id:guid}")]
public async Task<IActionResult> Review(Guid id)
{
var row=await reviews.Get(Author,id);if(row==null)return NotFound();if(await access.GetBookStructureAsync(row.BookID,Author)==null)return Forbid();
return View(new NativeReviewModel(row,JsonSerializer.Deserialize<AiChapterResult>(row.ResultJson)!,string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize<NativeSceneDecision[]>(row.DecisionsJson)!,presence.Read(Author,row.BookID).Where(l=>l.Position.WordAvailable&&l.Position.ManuscriptId==row.ManuscriptID&&l.Position.Revision==JsonSerializer.Deserialize<AiChapterResult>(row.ResultJson)!.DocumentRevision).ToArray()));
}
[HttpPost("reviews/{id:guid}/navigate"),ValidateAntiForgeryToken]
public async Task<IActionResult> Navigate(Guid id,int index,Guid instanceId,Guid sessionId)
{
var row=await reviews.Get(Author,id);if(row==null)return NotFound();if(await access.GetBookStructureAsync(row.BookID,Author)==null)return Forbid();var result=JsonSerializer.Deserialize<AiChapterResult>(row.ResultJson)!;
if(index<0||index>=result.Scenes.Length)return BadRequest();if(!presence.Navigate(Author,row.BookID,instanceId,sessionId,row.ManuscriptID,result.DocumentRevision,result.Scenes[index].Start))return Conflict("Word session is unavailable or this snapshot changed. Detect and review again.");
TempData["NativeReviewSaved"]="Navigation requested for the selected Word session. No text changes.";return RedirectToAction(nameof(Review),new{id});
}
[HttpPost("reviews/{id:guid}"),ValidateAntiForgeryToken,RequestSizeLimit(2*1024*1024)]
public async Task<IActionResult> Decide(Guid id,int version,List<NativeSceneDecision> scenes)
{
var row=await reviews.Get(Author,id);if(row==null)return NotFound();if(await access.GetBookStructureAsync(row.BookID,Author)==null)return Forbid();
var result=JsonSerializer.Deserialize<AiChapterResult>(row.ResultJson)!;
if(scenes.Count!=result.Scenes.Length||scenes.Select(s=>s.Index).Distinct().Count()!=scenes.Count||scenes.Any(s=>s.Index<0||s.Index>=result.Scenes.Length||s.State is not ("pending" or "approved" or "rejected")||string.IsNullOrWhiteSpace(s.Title)||s.Title.Length>200||s.Summary==null||s.Summary.Length>600))return BadRequest("Invalid review. Refresh and retry; nothing was imported.");
if(!await reviews.Decide(Author,id,version,JsonSerializer.Serialize(scenes)))return Conflict("This review changed in another window. Reload before saving; nothing was overwritten.");
TempData["NativeReviewSaved"]="Review decisions saved. No manuscript or canonical story records were changed.";return RedirectToAction(nameof(Review),new{id});
}
}
public sealed record NativeWorkspaceModel(int Book,int Project,string Title,Guid? Instance,Guid? Session,string Mode,IReadOnlyList<NativeReview> Reviews);
public sealed record NativeReviewModel(NativeReview Row,AiChapterResult Result,NativeSceneDecision[] Decisions,NativeLease[] Sessions);
public sealed class NativeSceneDecision {public int Index {get;set;}public string State {get;set;}="pending";public string Title {get;set;}="";public string Summary {get;set;}="";}

View File

@ -0,0 +1,24 @@
using System.Data;
using Dapper;
namespace PlotLine.Data;
public sealed class NativeReview
{
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
{
Task<NativeReview?> Find(int user,int book,Guid manuscript,string hash);
Task<NativeReview?> Get(int user,Guid id);
Task<IReadOnlyList<NativeReview>> List(int user,int book);
Task<NativeReview> Save(NativeReview review);
Task<bool> Decide(int user,Guid id,int version,string json);
}
public sealed class NativeReviewRepository(ISqlConnectionFactory factory):INativeReviewRepository
{
private async Task<NativeReview?> Read(object parameters){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<NativeReview>("dbo.NativeChapterReview_Access",parameters,commandType:CommandType.StoredProcedure);}
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)=>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.");
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;}
}

View File

@ -97,6 +97,8 @@ 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.INativeReviewRepository,PlotLine.Data.NativeReviewRepository>();
builder.Services.AddSingleton<PlotLine.Services.NativeCompanion.NativePresenceStore>();
builder.Services.AddSingleton<StoryIntelligenceRequestLimiter>();
builder.Services.AddAuthorization(options =>
{

View File

@ -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"))],DesktopPairing.Scheme);
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);
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity),DesktopPairing.Scheme));
}
}

View File

@ -6,7 +6,7 @@ public static class NativeChapterMapping
{
public static ManuscriptStructureAnalysisRequest Build(AiChapterRequest request,int maxCharacters=120000)
{
if(request.RequestId==Guid.Empty||request.ManuscriptId==Guid.Empty||request.SessionId==Guid.Empty||request.BookId<=0||request.Revision<0||request.Paragraphs==null||request.Paragraphs.Length is <1 or >10000||request.ChapterStart<0||request.ChapterEnd<=request.ChapterStart)throw new ArgumentException("Invalid chapter identity or range.");
if(request.ChapterTitle==null||request.ChapterTitle.Length>200||request.RequestId==Guid.Empty||request.ManuscriptId==Guid.Empty||request.SessionId==Guid.Empty||request.BookId<=0||request.Revision<0||request.Paragraphs==null||request.Paragraphs.Length is <1 or >10000||request.ChapterStart<0||request.ChapterEnd<=request.ChapterStart)throw new ArgumentException("Invalid chapter identity or range.");
var end=request.ChapterStart;var previousIndex=-1;var characters=0;
foreach(var p in request.Paragraphs)
{
@ -15,12 +15,12 @@ public static class NativeChapterMapping
previousIndex=p.Index;end=p.End;
}
if(end!=request.ChapterEnd)throw new ArgumentException("Incomplete chapter.");
var readable=request.Paragraphs.Where(p=>!string.IsNullOrWhiteSpace(p.Text.Trim('\a','\r','\n'))).ToArray();
var readable=request.Paragraphs.Where(p=>!p.IsHeading&&!string.IsNullOrWhiteSpace(p.Text.Trim('\a','\r','\n'))).ToArray();
if(readable.Length==0)throw new ArgumentException("This chapter contains no readable paragraphs.");
return new(){BookID=request.BookId,PreviewID=request.RequestId,TemporaryChapterKey=request.RequestId.ToString("N"),ChapterNumber=1,SourceLabel="Native Word chapter",PrivateAnalysis=true,
ChapterText=string.Join("\n\n",readable.Select(p=>p.Text)),
ParagraphMap=readable.Select((p,i)=>new ManuscriptScanParagraphMap{StructuralParagraphOrdinal=i+1,WordParagraphIndex=p.Index,Text=p.Text}).ToArray(),
SourceParagraphs=request.Paragraphs.Select(p=>new ManuscriptScanSourceParagraph{WordParagraphIndex=p.Index,Text=p.Text,IsBlank=string.IsNullOrWhiteSpace(p.Text),IncludeInSourceText=true}).ToArray()};
SourceParagraphs=request.Paragraphs.Select(p=>new ManuscriptScanSourceParagraph{WordParagraphIndex=p.Index,Text=p.Text,IsBlank=string.IsNullOrWhiteSpace(p.Text),IsChapterHeading=p.IsHeading,IncludeInSourceText=!p.IsHeading}).ToArray()};
}
public static AiChapterResult Map(AiChapterRequest request,ManuscriptStructureAnalysisResult result)
{
@ -33,8 +33,8 @@ public static class NativeChapterMapping
var end=request.Paragraphs.FirstOrDefault(p=>p.Index==scene.WordEndPosition);
if(start==null||end==null||end.End<=start.Start)throw new ArgumentException("AI scene could not be mapped to Word.");
string Bound(string? text,int length)=>string.IsNullOrEmpty(text)?"":text.Length<=length?text:text[..length];
scenes.Add(new(){Kind="Scene",Origin="AI",Start=start.Start,End=end.End,Paragraph=start.Index,Title=Bound(scene.Title,200),Reason=Bound(scene.Reason??scene.StructuralSummary,600),Confidence=scene.Confidence?.ToString("0.00",System.Globalization.CultureInfo.InvariantCulture)??"Unspecified"});
scenes.Add(new(){Kind="Scene",Origin="AI",Start=start.Start,End=end.End,Paragraph=start.Index,Title=Bound(scene.Title,200),Reason=Bound(scene.Reason??scene.StructuralSummary,600),Summary=Bound(scene.StructuralSummary,600),Confidence=scene.Confidence?.ToString("0.00",System.Globalization.CultureInfo.InvariantCulture)??"Unspecified"});
}
return new(){RequestId=request.RequestId,State="complete",Message="AI suggestions only. Manuscript and existing markers are unchanged.",Scenes=scenes.ToArray()};
return new(){RequestId=request.RequestId,State="complete",DocumentRevision=request.Revision,ChapterTitle=request.ChapterTitle,Message="AI suggestions only. Manuscript and existing markers are unchanged.",Scenes=scenes.ToArray()};
}
}

View File

@ -0,0 +1,24 @@
using PlotDirector.Companion.Protocol;
namespace PlotLine.Services.NativeCompanion;
public sealed record NativeLease(int User,string Grant,DateTimeOffset GrantExpires,Guid Instance,Guid Session,NativePresence Position,DateTimeOffset Updated);
// Ephemeral liveness, never a persisted association. Server restart means disconnected.
public sealed class NativePresenceStore(TimeProvider clock)
{
private readonly Dictionary<(int,Guid,Guid),AdapterCommand> navigation=[];
private readonly object gate=new();private readonly Dictionary<(int,Guid,Guid),NativeLease> leases=[];private readonly Dictionary<string,DateTimeOffset> revoked=[];
private void Prune(){var now=clock.GetUtcNow();foreach(var key in leases.Where(p=>now-p.Value.Updated>=TimeSpan.FromSeconds(45)||p.Value.GrantExpires<=now).Select(p=>p.Key).ToArray()){leases.Remove(key);navigation.Remove(key);}foreach(var key in revoked.Where(p=>p.Value<=now).Select(p=>p.Key).ToArray())revoked.Remove(key);}
public bool Put(int user,string grant,DateTimeOffset expires,Guid instance,Guid session,NativePresence value)
{
lock(gate){Prune();var key=(user,instance,session);if(instance==Guid.Empty||session==Guid.Empty||(value.WordAvailable&&value.ManuscriptId==Guid.Empty)||value.Revision<0||value.Sequence<=0||value.BookId<=0||value.DocumentTitle==null||value.DocumentTitle.Length>260||value.DocumentTitle.IndexOfAny(['\\','/'])>=0||expires<=clock.GetUtcNow()||revoked.ContainsKey(grant))return false;
if(leases.TryGetValue(key,out var prior)){if(prior.Grant!=grant||value.Sequence<=prior.Position.Sequence||value.Revision<prior.Position.Revision)return false;}
else if(leases.Count>=4096||leases.Values.Count(p=>p.User==user)>=64)return false;
leases[key]=new(user,grant,expires,instance,session,new NativePresence{ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;}
}
public NativeLease[] Read(int user,int book){lock(gate){Prune();return leases.Values.Where(p=>p.User==user&&(book==0||p.Position.BookId==book)).OrderByDescending(p=>p.Updated).ToArray();}}
public bool Navigate(int user,int book,Guid instance,Guid session,Guid manuscript,long revision,int start)
{lock(gate){Prune();var key=(user,instance,session);if(!leases.TryGetValue(key,out var lease)||!lease.Position.WordAvailable||lease.Position.BookId!=book||lease.Position.ManuscriptId!=manuscript||lease.Position.Revision!=revision||start<0)return false;navigation[key]=new(){Kind="navigate",SessionId=session,Revision=revision,Chapter=new(){Start=start}};return true;}}
public AdapterCommand? TakeNavigation(int user,string grant,Guid instance,Guid session)
{lock(gate){Prune();var key=(user,instance,session);return leases.TryGetValue(key,out var lease)&&lease.Grant==grant&&navigation.Remove(key,out var command)?command:null;}}
public void Remove(int user,string grant,Guid instance,Guid session){lock(gate)if(leases.TryGetValue((user,instance,session),out var prior)&&prior.Grant==grant){leases.Remove((user,instance,session));navigation.Remove((user,instance,session));}}
public void Revoke(int user,string grant,DateTimeOffset expiry){lock(gate){Prune();if(revoked.Count<8192)revoked[grant]=expiry;foreach(var key in leases.Where(p=>p.Value.User==user&&p.Value.Grant==grant).Select(p=>p.Key).ToArray())leases.Remove(key);}}
}

View File

@ -0,0 +1,53 @@
-- Additive native chapter suggestions only. No canonical chapter/scene/prose writes.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
IF OBJECT_ID(N'dbo.NativeChapterReviews',N'U') IS NULL
BEGIN
CREATE TABLE dbo.NativeChapterReviews(
ReviewID uniqueidentifier NOT NULL PRIMARY KEY,
UserID int NOT NULL,BookID int NOT NULL,ManuscriptID uniqueidentifier NOT NULL,
ChapterStart int NOT NULL,ChapterEnd int NOT NULL,ContentHash varchar(64) NOT NULL,
ResultJson nvarchar(max) NOT NULL,DecisionsJson nvarchar(max) NULL,
Version int NOT NULL DEFAULT 1,CreatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME());
CREATE UNIQUE INDEX UX_NativeChapterReviews_Content ON dbo.NativeChapterReviews(UserID,BookID,ManuscriptID,ContentHash);
END;
-- No foreign keys: suggestions must not block existing project/book deletion or restore.
-- Controllers revalidate live book access for every read/write. Expired rows are purged on save.
GO
CREATE OR ALTER PROCEDURE dbo.NativeChapterReview_Access
@Action varchar(16),@UserID int,@BookID int=0,@ReviewID uniqueidentifier=NULL,
@ManuscriptID uniqueidentifier=NULL,@ChapterStart int=0,@ChapterEnd int=0,
@ContentHash varchar(64)=NULL,@ResultJson nvarchar(max)=NULL,@DecisionsJson nvarchar(max)=NULL,@Version int=0
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
IF @Action='Find'
SELECT TOP(1) * FROM dbo.NativeChapterReviews WHERE UserID=@UserID AND BookID=@BookID AND ManuscriptID=@ManuscriptID AND ContentHash=@ContentHash AND CreatedUtc>DATEADD(day,-30,SYSUTCDATETIME());
ELSE IF @Action='Get'
SELECT * FROM dbo.NativeChapterReviews WHERE UserID=@UserID AND ReviewID=@ReviewID AND CreatedUtc>DATEADD(day,-30,SYSUTCDATETIME());
ELSE IF @Action='List'
SELECT TOP(500) * FROM dbo.NativeChapterReviews WHERE UserID=@UserID AND BookID=@BookID AND CreatedUtc>DATEADD(day,-30,SYSUTCDATETIME()) ORDER BY CreatedUtc DESC;
ELSE IF @Action='Save'
BEGIN
IF ISJSON(@ResultJson)<>1 OR DATALENGTH(@ResultJson)>2097152 THROW 51000,'Invalid review payload',1;
BEGIN TRANSACTION;
DELETE FROM dbo.NativeChapterReviews WHERE UserID=@UserID AND CreatedUtc<=DATEADD(day,-30,SYSUTCDATETIME());
IF NOT EXISTS(SELECT 1 FROM dbo.NativeChapterReviews WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID AND ManuscriptID=@ManuscriptID AND ContentHash=@ContentHash)
BEGIN
IF (SELECT COUNT(*) FROM dbo.NativeChapterReviews WHERE UserID=@UserID)>=1000 THROW 51000,'Review capacity reached',1;
INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson)
VALUES(@ReviewID,@UserID,@BookID,@ManuscriptID,@ChapterStart,@ChapterEnd,@ContentHash,@ResultJson);
END;
COMMIT;
SELECT TOP(1) * FROM dbo.NativeChapterReviews WHERE UserID=@UserID AND BookID=@BookID AND ManuscriptID=@ManuscriptID AND ContentHash=@ContentHash;
END
ELSE IF @Action='Decide'
BEGIN
IF ISJSON(@DecisionsJson)<>1 OR DATALENGTH(@DecisionsJson)>2097152 THROW 51000,'Invalid decision payload',1;
UPDATE dbo.NativeChapterReviews SET DecisionsJson=@DecisionsJson,Version=Version+1
WHERE UserID=@UserID AND ReviewID=@ReviewID AND Version=@Version AND CreatedUtc>DATEADD(day,-30,SYSUTCDATETIME());
SELECT @@ROWCOUNT;
END;
END;
GO

View File

@ -0,0 +1,25 @@
@model PlotLine.Controllers.NativeReviewModel
@{ViewData["Title"]="Review AI scene suggestions";}
<div class="container py-4">
<a href="/native-companion/workspace?bookId=@Model.Row.BookID">← Companion workspace and other chapters</a>
<h1 class="h3 mt-3">@(string.IsNullOrWhiteSpace(Model.Result.ChapterTitle)?"Chapter scene review":Model.Result.ChapterTitle)</h1>
<p>AI scene suggestions · Word remains authoritative. Edit, approve or reject below. Saving decisions does not import scenes, change prose or overwrite existing story data.</p>
@if(TempData["NativeReviewSaved"] is string message){<div class="alert alert-success" role="status">@message</div>}
<form method="post" action="/native-companion/reviews/@Model.Row.ReviewID">
@Html.AntiForgeryToken()<input type="hidden" name="version" value="@Model.Row.Version" />
@for(var i=0;i<Model.Result.Scenes.Length;i++){var scene=Model.Result.Scenes[i];var decision=Model.Decisions.FirstOrDefault(d=>d.Index==i);
<details class="card mb-3" open><summary class="card-header">Scene @(i+1) · @scene.Title</summary><div class="card-body">
<input type="hidden" name="scenes[@i].Index" value="@i" />
<label class="form-label" for="title-@i">Scene title</label><input class="form-control mb-2" id="title-@i" name="scenes[@i].Title" maxlength="200" required value="@(decision?.Title??scene.Title)" />
<label class="form-label" for="summary-@i">Summary</label><textarea class="form-control mb-2" id="summary-@i" name="scenes[@i].Summary" maxlength="600" rows="4">@(decision?.Summary??scene.Summary)</textarea>
<label class="form-label" for="decision-@i">Decision</label><select class="form-select" id="decision-@i" name="scenes[@i].State">@foreach(var state in new[]{"pending","approved","rejected"}){<option value="@state" selected="@((decision?.State??"pending")==state)">@state</option>}</select>
<p class="small text-muted mt-2">Word positions @scene.Start–@scene.End · confidence @scene.Confidence · @scene.Reason</p>
</div></details>}
<button class="btn btn-primary" type="submit">Save review decisions</button>
</form>
@if(Model.Sessions.Length>0){<details class="card mt-3"><summary class="card-header">Locate a suggested scene in Word</summary><form class="card-body" method="post" action="/native-companion/reviews/@Model.Row.ReviewID/navigate">@Html.AntiForgeryToken()
<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">Import remains a separate, explicit operation through the established manuscript import. These decisions are retained as suggestions; this page does not yet transfer them into an import build.</p>
</div>

View File

@ -0,0 +1,17 @@
@model PlotLine.Controllers.NativeWorkspaceModel
@{ ViewData["Title"]="Word Companion · "+Model.Title; }
<div class="container py-4" id="native-workspace" data-book="@Model.Book" data-project="@Model.Project" data-instance="@Model.Instance" data-session="@Model.Session" data-mode="@Model.Mode">
<h1 class="h3">@Model.Title</h1><p>Word Companion · live manuscript connection and saved PlotDirector workspaces</p>
<div class="card mb-3"><div class="card-body">
<p id="native-presence-status" role="status">Checking Companion presence…</p>
<label for="native-session">Word document session</label><select id="native-session" class="form-select mb-2"><option value="">Choose a connected manuscript</option></select>
<label><input type="checkbox" id="native-follow" /> Follow this manuscript’s saved chapter and scene</label>
<p class="small text-muted">Manual navigation pauses following. No Word commands or manuscript text are sent by this page. Context and Intent remain available without Word.</p>
<nav class="d-flex gap-3"><a href="/Books/Details/@Model.Book">Book workspace</a><a href="/Writing/Context?projectId=@Model.Project&bookId=@Model.Book&pinned=true">Saved Context</a><a href="/Writing/Intent?projectId=@Model.Project&bookId=@Model.Book&pinned=true">Saved Intent</a></nav>
</div></div>
<iframe id="native-story-workspace" title="Saved story workspace" class="w-100 border rounded" style="height:65vh" hidden></iframe>
<h2 class="h4 mt-4">AI chapter suggestions</h2><p>Generated by PlotDirector’s existing chapter-analysis service. Review titles and summaries before any import. Successful chapters remain available for 30 days.</p>
@if(Model.Reviews.Count==0){<div class="alert alert-secondary">No saved AI suggestions yet. Detect Heading 1 chapters in the tray Companion, select chapters and explicitly confirm analysis.</div>}
else {<ul class="list-group">@foreach(var review in Model.Reviews){var result=System.Text.Json.JsonSerializer.Deserialize<PlotDirector.Companion.Protocol.AiChapterResult>(review.ResultJson);<li class="list-group-item"><a href="/native-companion/reviews/@review.ReviewID">@(string.IsNullOrWhiteSpace(result?.ChapterTitle)?"Chapter at position "+review.ChapterStart:result.ChapterTitle)</a> · @(result?.Scenes.Length??0) scene suggestions · @review.CreatedUtc.ToString("u")</li>}</ul>}
</div>
<script src="~/js/native-companion-workspace.js" asp-append-version="true" defer></script>

View File

@ -286,6 +286,7 @@
{
<div class="alert alert-info">@importMessage</div>
}
@if(User.Identity?.IsAuthenticated==true&&!isMarketingPage){<div id="native-companion-status" class="small px-3 py-2 border-bottom" hidden role="status"><a id="native-companion-status-link" href="/">Native Companion</a><span id="native-companion-status-text"></span></div>}
@RenderBody()
</main>
@if (isApplication)
@ -354,6 +355,7 @@
<script src="~/js/application-toolbar.js" asp-append-version="true"></script>
<script src="~/js/application-shell.js" asp-append-version="true"></script>
}
<script src="~/js/native-companion-status.js" asp-append-version="true" defer></script>
<script src="~/js/word-companion-presence.js" asp-append-version="true"></script>
<script src="~/js/story-intelligence-global-progress.js" asp-append-version="true"></script>
}

View File

@ -0,0 +1 @@
(()=>{const select=document.querySelector('#native-review-session');if(!select)return;function choose(){const option=select.selectedOptions[0];document.querySelector('#native-review-instance').value=option?.dataset.instance||'';document.querySelector('#native-review-session-id').value=option?.value||'';}select.addEventListener('change',choose);choose();})();

View File

@ -0,0 +1,10 @@
(() => {
'use strict';const root=document.querySelector('#native-companion-status');if(!root)return;
const link=root.querySelector('#native-companion-status-link'),text=root.querySelector('#native-companion-status-text');let pending=false,seen=false;
async function update(){if(pending||document.hidden)return;pending=true;try{
const response=await fetch('/native-companion/status',{cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw new Error();const leases=(await response.json()).filter(l=>Date.parse(l.expires)>Date.now());const lease=leases.find(l=>l.active&&l.wordAvailable)||leases.find(l=>l.wordAvailable)||leases[0];
if(lease){seen=true;root.hidden=false;root.dataset.connected='true';link.hidden=false;link.href='/native-companion/workspace?bookId='+encodeURIComponent(lease.bookId)+'&instanceId='+encodeURIComponent(lease.instanceId)+'&sessionId='+encodeURIComponent(lease.sessionId);text.textContent=' · connected · Word '+(lease.wordAvailable?'available · '+lease.documentTitle:'unavailable')+' · last update '+new Date(lease.updated).toLocaleTimeString();}
else if(seen){root.hidden=false;root.dataset.connected='false';link.hidden=true;text.textContent='Native Companion disconnected or stale';}
}catch{if(seen){root.dataset.connected='false';link.hidden=true;text.textContent='Native Companion status unavailable';}}finally{pending=false;}}
void update();const timer=setInterval(()=>void update(),15000);document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer));
})();

View File

@ -0,0 +1,27 @@
(() => {
'use strict';
const root=document.querySelector('#native-workspace');if(!root)return;
const sessions=root.querySelector('#native-session'),follow=root.querySelector('#native-follow'),status=root.querySelector('#native-presence-status'),frame=root.querySelector('#native-story-workspace');
let selected=root.dataset.instance&&root.dataset.session?root.dataset.instance+'/'+root.dataset.session:'',generation=0,position='',timer,loading=false;
const setStatus=text=>{if(status.textContent!==text)status.textContent=text;};
const show=lease=>{
if(!['context','intent'].includes(root.dataset.mode))return;
const key=lease?[lease.chapterId,lease.sceneId].join(':'):'manual';if(position===key)return;position=key;
const url=new URL('/Writing/'+(root.dataset.mode==='intent'?'Intent':'Context'),location.origin);url.searchParams.set('projectId',root.dataset.project);url.searchParams.set('bookId',root.dataset.book);url.searchParams.set('pinned','true');if(lease?.chapterId)url.searchParams.set('chapterId',lease.chapterId);if(lease?.sceneId)url.searchParams.set('sceneId',lease.sceneId);frame.src=url.pathname+url.search;frame.hidden=false;
};
frame.addEventListener('load',()=>{try{frame.contentDocument.addEventListener('change',()=>{follow.checked=false;setStatus('Manual navigation · following paused');});}catch{follow.checked=false;}});
sessions.addEventListener('change',()=>{selected=sessions.value;position='';follow.checked=false;void poll();});follow.addEventListener('change',()=>{position='';void poll();});
async function poll(){
if(loading||document.hidden)return;loading=true;const current=++generation;
try{
const response=await fetch('/native-companion/presence?bookId='+encodeURIComponent(root.dataset.book),{cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw new Error('unavailable');const leases=await response.json();if(current!==generation)return;
const live=leases.filter(l=>Date.parse(l.expires)>Date.now());const signature=live.map(l=>l.instanceId+'/'+l.sessionId+':'+l.documentTitle).join('|');
if(sessions.dataset.signature!==signature){sessions.dataset.signature=signature;sessions.replaceChildren(new Option('Choose a connected manuscript',''));for(const lease of live.filter(l=>l.wordAvailable))sessions.add(new Option(lease.documentTitle+(lease.active?' (active in Word)':''),lease.instanceId+'/'+lease.sessionId));sessions.value=selected;}
const lease=live.find(l=>l.instanceId+'/'+l.sessionId===selected);
if(lease){setStatus('Companion connected · Word '+(lease.wordAvailable?'available':'unavailable')+' · '+lease.documentTitle+' · last update '+new Date(lease.updated).toLocaleTimeString()+(follow.checked?' · following saved position':' · manual navigation'));if(follow.checked)show(lease);else if(!position)show(null);}
else{setStatus(live.some(l=>!l.wordAvailable)?'Companion connected · Word unavailable. Saved Context and Intent remain available.':'Companion disconnected or stale for the selected manuscript. Saved workspaces remain available.');follow.checked=false;if(!position)show(null);}
}catch{setStatus('Connection status unavailable · following paused; saved data remains available');follow.checked=false;}
finally{loading=false;}
}
document.addEventListener('visibilitychange',()=>{if(!document.hidden)void poll();});window.addEventListener('pagehide',()=>clearInterval(timer));show(null);void poll();timer=setInterval(()=>void poll(),15000);
})();