Expose existing Word synchronisation in connection controls with verified transfer feedback
This commit is contained in:
parent
1ffd3fcf54
commit
3754ff5ac7
@ -67,6 +67,18 @@ Synthetic installation revoked. Normal account/project deletion removed the test
|
||||
This is a **real Development protocol/browser test**, not proof of Windows caret behaviour or Word `Range.Select()` execution. The exact reason this morning's native refresh captures failed remains unavailable from the pre-existing server logs; do not describe safe refusal of their stale map as restored live mapping for the author's current session. The new diagnostics distinguish that state, and a successful existing synchronisation/native qualification remains required for that session.
|
||||
No database migration is required. Deployment uses the existing idle-work guard and preserves configuration, uploads, keys and the previous application release. Production is untouched.
|
||||
|
||||
## Follow-up: make the existing synchronisation action accessible
|
||||
|
||||
The user could not find a synchronisation control. Investigation found it only inside `/manuscript/paragraphs?bookId=…` (**Manuscript structure and evidence**), behind a secondary link. Referring users to an undiscoverable action was insufficient.
|
||||
|
||||
The shared top-right Word connection dialog now includes a direct **Synchronise from Word** button. It posts to the existing `/manuscript/paragraphs/snapshot` controller and `NativeManuscriptCapture.RequestParagraphSnapshot`, retaining normal form/redirect compatibility while adding an antiforgery-protected JSON response for that button. No second sync service, prose upload policy, AI job or authentication mechanism.
|
||||
|
||||
The current selected document's exact instance/session is validated by the existing service; an unavailable or incomplete explicit selection is refused rather than falling back to another document. Unsaved/unavailable/non-capable connections explain why the button is disabled. The request ID and existing ephemeral transfer metadata distinguish waiting/reading, actual accepted snapshot, and failure/removal; the UI never reports completion just because the POST succeeded. Reading progress reuses existing native capture notifications and the existing status updater, without another polling loop. A pending read cannot be silently submitted twice from the dialog.
|
||||
|
||||
The original full manuscript workspace still provides mode preferences and explicit cancellation/review. Its normal author form remains supported. Native diagnostics also count selection events versus read observations so Windows can distinguish event storms, ordinary polling and actual navigation executions.
|
||||
|
||||
The final follow-up deployment/protocol result is recorded below.
|
||||
|
||||
## Windows qualification / handover
|
||||
|
||||
Use the same shared branch `codex/word-companion-native-phase1-20261104`; inspect/preserve the worktree, discover its tracking remote, fetch and fast-forward safely. Do not use desktop automation, launch Word or install unattended while the user is working.
|
||||
|
||||
@ -47,6 +47,7 @@ namespace PlotDirector.WordAddIn
|
||||
private bool disposed;private bool activationPending,traySupported;
|
||||
public string WordCountSummary=>active?.WordCount?.ToString("N0")??"not read / stale";
|
||||
private long busyFailures;
|
||||
private long selectionNotifications,selectionReads;
|
||||
private long navigationExecutions;private Guid lastNavigationId;private readonly Queue<Guid> completedNavigationIds=new Queue<Guid>();
|
||||
private string lastWordError;
|
||||
private int documentCollectionGeneration;
|
||||
@ -55,6 +56,7 @@ namespace PlotDirector.WordAddIn
|
||||
public string ConnectionState { get; private set; } = "Connecting";
|
||||
public bool HasActiveDocument => active != null;
|
||||
public string Diagnostics => "PlotDirector " + typeof(WordAdapter).Assembly.GetName().Version + "\nAgent: " + ConnectionState
|
||||
+ "\nSelection events / observations: " + selectionNotifications + " / " + selectionReads
|
||||
+ "\nWord navigation executions: " + navigationExecutions + " · last command: " + lastNavigationId
|
||||
+ "\nOpen sessions: " + documents.Count
|
||||
+ "\nIPC queued: " + link.QueueDepth + "\nWord work queued: " + scheduler.Depth
|
||||
@ -164,7 +166,7 @@ namespace PlotDirector.WordAddIn
|
||||
})) pendingOpen.Remove(document);
|
||||
}
|
||||
private void Activate(Word.Document document,Word.Window window) { activationPending=true;Open(document); ScheduleSelection(); }
|
||||
private void SelectionChanged(Word.Selection selection) { ScheduleSelection(); }
|
||||
private void SelectionChanged(Word.Selection selection) { selectionNotifications++;ScheduleSelection(); }
|
||||
private void ScheduleSelection()
|
||||
{
|
||||
if (disposed) return;
|
||||
@ -175,6 +177,7 @@ namespace PlotDirector.WordAddIn
|
||||
}
|
||||
private void CaptureSelection()
|
||||
{
|
||||
selectionReads++;
|
||||
Word.Selection selection = null; Word.Range range = null;
|
||||
try
|
||||
{
|
||||
|
||||
@ -35,6 +35,12 @@ const base='https://dev.plotdirector.com';let step='validate fixture files';
|
||||
step='actual saved metrics and empty plot data';await page.click('[data-writing-context-tab=metrics]');await page.waitForSelector('[data-writing-component=metrics][data-loaded=true]');assert.ok(await page.locator('[data-context-metric-select] option').count()>0);await page.click('[data-writing-context-tab=plots]');await page.waitForSelector('[data-writing-component=plots][data-loaded=true]');assert.ok(await page.getByText('No saved plot-line developments are available for this book.').isVisible());
|
||||
step='disconnect and saved navigation';clearInterval(keepalive);keepalive=null;await page.request.delete(presencePath(),{headers});await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('disconnected'),null,{timeout:25000});await page.click('[data-writing-context-tab=people]');await page.locator('[data-writing-context-scene-select]').press('Home');await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[0]}"]`);
|
||||
step='reconnect actual cursor wins';cursor=scope.SceneStarts[1];sequence=0;presence=await heartbeat();assert.equal(presence.sceneId,scope.Scenes[1]);await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[1]}"]`);assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.ok(await page.evaluate(()=>originalContextShell===document.querySelector('[data-writing-context]')));assert.equal(commands.length,1,'Reconnect cannot manufacture navigation commands');
|
||||
step='direct existing synchronisation action and exact document selection';const syncToken=await page.locator('[data-word-sync-form] [name=__RequestVerificationToken]').inputValue();
|
||||
response=await page.request.post(base+'/manuscript/paragraphs/snapshot',{headers:{'X-Requested-With':'XMLHttpRequest'},form:{bookId:String(scope.Book),instanceId:scope.Instance,sessionId:crypto.randomUUID(),__RequestVerificationToken:syncToken}});assert.equal(response.status(),409);assert.match((await response.json()).message,/selected Word document/i);
|
||||
await page.click('#native-companion-status');await page.locator('[data-word-sync-button]').waitFor({state:'visible'});await page.waitForFunction(()=>!document.querySelector('[data-word-sync-button]').disabled);
|
||||
const submitted=page.waitForResponse(r=>r.url().endsWith('/manuscript/paragraphs/snapshot')&&r.request().method()==='POST');await page.click('[data-word-sync-button]');response=await submitted;assert.equal(response.status(),200);const requestedSnapshot=await response.json();assert.match(requestedSnapshot.requestId,/^[0-9a-f-]{36}$/i);
|
||||
const snapshotCommand=(await heartbeat()).navigation;assert.equal(snapshotCommand.kind,'paragraph-snapshot');assert.equal(snapshotCommand.id,requestedSnapshot.requestId);assert.equal(snapshotCommand.sessionId,scope.Session);assert.equal(commands.filter(c=>c.kind==='navigate').length,1);assert.ok(!(await page.locator('[data-word-sync-feedback]').textContent()).includes('accepted.'),'request alone is not acceptance');
|
||||
await page.request.delete(base+'/api/native-companion/manuscript-capture/'+snapshotCommand.id,{headers});await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('ended without an accepted snapshot'));await page.click('[data-close-word-details]');
|
||||
step='anonymous and antiforgery refusal';const bare=await browser.newContext();const unauthorised=await bare.request.get(base+`/Writing/Context/Metrics?projectId=${scope.Project}&bookId=${scope.Book}`,{maxRedirects:0});assert.ok([302,401].includes(unauthorised.status()));await bare.close();response=await page.request.post(base+'/Writing/Context/Navigate',{form:{bookId:String(scope.Book),sceneId:String(scope.Scenes[0])}});assert.equal(response.status(),400);
|
||||
step='sign out test installation';await page.request.post(base+'/api/native-companion/revoke',{data:{installationId:tokens.installationId,credential:tokens.deviceSecret,connectionId,nextCredential:'',rotationId:crypto.randomUUID()}});response=await page.request.get(base+'/api/native-companion/books',{headers});assert.equal(response.status(),401);
|
||||
console.log('PASS live Development: normal browser approval, real native presence and persisted paragraph mapping, direct iframe-free Context, cross-chapter explicit command at exact saved position, cursor acknowledgement without loops, stable People tab/shell, stale revision refusal, read-only metrics/plots, disconnected browsing, reconnect precedence, authentication/antiforgery and revocation. Includes repeated passive cursor observations and duplicate explicit-request refusal after acknowledgement. Protocol client only; actual Word execution remains unverified.');
|
||||
|
||||
@ -3,11 +3,13 @@ const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
|
||||
(async()=>{const browser=await chromium.launch();try{
|
||||
for(const embedded of [false,true])for(const installed of [false,true]){
|
||||
const page=await browser.newPage({viewport:{width:1280,height:900}});await page.addInitScript(installed=>{if(installed){const match=window.matchMedia.bind(window);window.matchMedia=query=>query==='(display-mode: standalone)'?{matches:true,media:query,addEventListener(){},removeEventListener(){},addListener(){},removeListener(){}}:match(query);}},installed);
|
||||
await page.route('**/native-companion/status',r=>r.fulfill({json:[{instanceId:'fixture',sessionId:'doc',bookId:12,chapterId:10,sceneId:22,active:true,wordAvailable:true,wordSaved:true,documentTitle:'Synthetic manuscript.docx',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}]}));
|
||||
let snapshotRevision=1,syncFailure=false,syncRequests=0;
|
||||
await page.route('**/manuscript/paragraphs/snapshot',async r=>{syncRequests++;const body=new URLSearchParams(r.request().postData());assert.equal(body.get('bookId'),'12');assert.equal(body.get('instanceId'),'fixture');assert.equal(body.get('sessionId'),'doc');assert.ok(body.get('__RequestVerificationToken'));await r.fulfill({status:syncFailure?409:200,json:{requestId:'11111111-1111-4111-8111-111111111111',message:syncFailure?'Word is unavailable; saved snapshot preserved.':'Word snapshot requested; awaiting acceptance.'}});});
|
||||
await page.route('**/native-companion/status',r=>r.fulfill({json:[{instanceId:'fixture',sessionId:'doc',bookId:12,chapterId:10,sceneId:22,active:true,wordAvailable:true,wordSaved:true,canParagraphSync:true,snapshotRevision,mappingCurrent:true,paragraphTransfer:syncRequests?{requestId:'11111111-1111-4111-8111-111111111111',state:'pending'}:null,documentTitle:'Synthetic manuscript.docx',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}]}));
|
||||
await page.route('**/Writing/Context/Scene?*',async r=>r.fulfill({response:await r.fetch({url:base+'/writing-desk-fixture/context?fragment=true&sceneId='+new URL(r.request().url()).searchParams.get('sceneId')})}));
|
||||
await page.route(/\/Writing\/Context\/(PlotLines|Metrics|Map)\?/,async r=>{const url=new URL(r.request().url()),kind=url.pathname.endsWith('PlotLines')?'plots':url.pathname.endsWith('Metrics')?'metrics':'map';await r.fulfill({response:await r.fetch({url:base+'/writing-context-component/'+kind+url.search})});});
|
||||
const response=await page.goto(base+'/Writing/Context?bookId=12'+(embedded?'&embedded=true':''));assert.equal(response.status(),200);
|
||||
await page.waitForSelector('[data-writing-context-fragment][data-scene-id="22"]');assert.equal(await page.locator('iframe').count(),0);assert.equal(await page.locator('#native-companion-status').count(),1);await page.click('#native-companion-status');assert.ok(await page.locator('#writing-connection-details').isVisible());assert.ok(await page.getByRole('option',{name:'Synthetic manuscript.docx · active in Word'}).count());await page.click('[data-close-word-details]');
|
||||
await page.waitForSelector('[data-writing-context-fragment][data-scene-id="22"]');assert.equal(await page.locator('iframe').count(),0);assert.equal(await page.locator('#native-companion-status').count(),1);await page.click('#native-companion-status');assert.ok(await page.locator('#writing-connection-details').isVisible());assert.ok(await page.getByRole('option',{name:'Synthetic manuscript.docx · active in Word'}).count());await page.locator('[data-word-sync-button]').click();await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('requested'));assert.equal(syncRequests,1);assert.ok(await page.locator('[data-word-sync-button]').isDisabled(),'request is not completion');snapshotRevision=2;await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('accepted'));assert.ok(await page.locator('[data-word-sync-button]').isEnabled());syncFailure=true;await page.locator('[data-word-sync-button]').click();await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('unavailable'));assert.equal(syncRequests,2);await page.click('[data-close-word-details]');
|
||||
await page.click('[data-writing-context-tab=people]');await page.selectOption('[data-writing-context-scene-select]','23');await page.waitForSelector('[data-writing-context-fragment][data-scene-id="23"]');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.equal(await page.locator('iframe').count(),0);
|
||||
await page.click('#native-companion-status');await page.click('[data-word-return-to-current]');await page.waitForSelector('[data-writing-context-fragment][data-scene-id="22"]');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());
|
||||
if(embedded)assert.equal(await page.locator('.pd-application-header').count(),0,'dedicated workspace has no normal ribbon');
|
||||
|
||||
@ -33,7 +33,7 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC
|
||||
if(!presence.Put(Author,Grant,Expires,instance,session,input))return Conflict(new{message="Stale, revoked or invalid native session."});
|
||||
if(before==null||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.WordSaved!=input.WordSaved||before.Position.Revision!=input.Revision)
|
||||
logger?.LogInformation("Native cursor observation User={User} Book={Book} Instance={Instance} Session={Session} Sequence={Sequence} Manuscript={Manuscript} WordRevision={WordRevision} Saved={Saved} Cursor={Cursor} Chapter={Chapter} Scene={Scene} ParagraphSnapshot={HasSnapshot} ParagraphRevision={ParagraphRevision}; observation does not request navigation",Author,input.BookId,instance,session,input.Sequence,input.ManuscriptId,input.Revision,input.WordSaved,input.CursorStart,input.ChapterId,input.SceneId,paragraphPosition?.HasSnapshot,paragraphPosition?.Revision);
|
||||
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||before.Position.WordRunning!=input.WordRunning||before.Position.WordSaved!=input.WordSaved))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||before.Position.WordRunning!=input.WordRunning||before.Position.WordSaved!=input.WordSaved||before.Position.CaptureRequestId!=input.CaptureRequestId||before.Position.CaptureProgress/5!=input.CaptureProgress/5))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted);
|
||||
if(input.CaptureRequestId.HasValue&&capture!=null&&wizard!=null){var progress=await capture.Progress(Author,Grant,input.CaptureRequestId.Value,input.CaptureProgress,instance,session,input.ManuscriptId,input.Revision);if(progress!=null)await wizard.Clients.Group(WordCompanionFollowHub.PresenceGroup(Author)).SendAsync("OnboardingScanProgress",progress,HttpContext.RequestAborted);}
|
||||
if(input.CanParagraphSync&&capture!=null){var lease=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session);if(lease!=null)await capture.ObserveParagraphSave(Author,lease);}
|
||||
input.CatalogVersion=presence.CatalogVersion(Author);input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);
|
||||
|
||||
@ -31,13 +31,16 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB
|
||||
public async Task<IActionResult> ImportCommit(string confirmation,bool confirm,[FromServices] NativeImportService importer)
|
||||
{if(!confirm)return BadRequest("Explicit import confirmation is required.");try{return View(await importer.Commit(Author,confirmation));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return Conflict(e.Message);}catch(Microsoft.Data.SqlClient.SqlException){return Conflict("Import could not commit. Review decisions are preserved. Preview again; existing story data has not been replaced.");}}
|
||||
[HttpGet("status")]
|
||||
public async Task<IActionResult> Status([FromServices] IParagraphManuscriptRepository? paragraphs=null)
|
||||
public async Task<IActionResult> Status([FromServices] IParagraphManuscriptRepository? paragraphs=null,[FromServices] NativeManuscriptCapture? capture=null)
|
||||
{
|
||||
Response.Headers.CacheControl="no-store";var leases=presence.Read(Author,0);var allowed=new HashSet<int>{0};
|
||||
foreach(var book in leases.Select(l=>l.Position.BookId).Where(b=>b>0).Distinct())if(await access.GetBookStructureAsync(book,Author)!=null)allowed.Add(book);
|
||||
var snapshots=new Dictionary<int,ParagraphSyncStatus?>();
|
||||
if(paragraphs!=null)foreach(var book in leases.Where(l=>l.Position.WordAvailable&&allowed.Contains(l.Position.BookId)&&l.Position.BookId>0).Select(l=>l.Position.BookId).Distinct())snapshots[book]=await paragraphs.Status(Author,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,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,l.Position.CanParagraphSync,
|
||||
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,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,l.Position.CanParagraphSync,l.Position.CaptureRequestId,l.Position.CaptureProgress,
|
||||
paragraphTransfer=capture?.ParagraphTransferStatus(Author,l.Position.BookId,l.Instance,l.Session),
|
||||
snapshotRevision=snapshots.GetValueOrDefault(l.Position.BookId)?.Revision,
|
||||
mappingCurrent=snapshots.GetValueOrDefault(l.Position.BookId) is {} saved&&saved.ManuscriptId==l.Position.ManuscriptId&&saved.SessionId==l.Session&&saved.WordRevision==l.Position.Revision,
|
||||
positionMessage=l.Position.WordSaved==false?"Save Word, then synchronise to refresh its scene mapping":l.Position.SceneId.HasValue?null:snapshots.GetValueOrDefault(l.Position.BookId) is {} snapshot?(snapshot.ManuscriptId!=l.Position.ManuscriptId?"This Word document does not match the book's saved manuscript identity":snapshot.SessionId!=l.Session||snapshot.WordRevision!=l.Position.Revision?"Word reopened or changed; synchronise from Word to verify this session's paragraph positions":snapshot.Paused?"Scene mapping is unresolved; synchronisation is paused while existing book processing finishes":"Current paragraph has no verified scene assignment") : "Synchronise from Word to establish a verified paragraph mapping",
|
||||
updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
|
||||
}
|
||||
|
||||
@ -18,20 +18,27 @@ public sealed class ParagraphManuscriptController(ParagraphManuscriptService man
|
||||
[HttpPost("enable"),ValidateAntiForgeryToken]
|
||||
public Task<IActionResult> Enable(int bookId,string mode)=>Run(bookId,async()=>{await manuscripts.Enable(Author,bookId,mode);return "Paragraph tracking preference saved. Word prose is never rewritten by PlotDirector.";});
|
||||
[HttpPost("snapshot"),ValidateAntiForgeryToken]
|
||||
public Task<IActionResult> Snapshot(int bookId)=>Run(bookId,async()=>{var id=await capture.RequestParagraphSnapshot(Author,bookId);return id==Guid.Empty?"A transfer is already pending. Refresh after it finishes.":"Word snapshot requested. Keep Word open until the transfer is acknowledged, then refresh this page.";});
|
||||
public Task<IActionResult> Snapshot(int bookId,Guid? instanceId=null,Guid? sessionId=null)
|
||||
{
|
||||
Guid requested=Guid.Empty;
|
||||
return Run(bookId,async()=>{if(!ModelState.IsValid)throw new ArgumentException("Invalid Word document selection.");requested=await capture.RequestParagraphSnapshot(Author,bookId,instanceId:instanceId,sessionId:sessionId);return requested==Guid.Empty?"A transfer is already pending. Refresh after it finishes.":"Word snapshot requested. Keep Word open until the transfer is acknowledged.";},()=>requested);
|
||||
}
|
||||
[HttpPost("cancel"),ValidateAntiForgeryToken]
|
||||
public Task<IActionResult> Cancel(int bookId)=>Run(bookId,async()=>{await capture.CancelParagraphSnapshot(Author,bookId);return "Pending snapshot cancelled. Already acknowledged snapshots remain saved.";});
|
||||
[HttpPost("change"),ValidateAntiForgeryToken]
|
||||
public Task<IActionResult> Change(int bookId,long revision,string action,Guid target,Guid other,string? text,string? eventKey,bool primary,int from,int to,int? startOffset,int? endOffset)=>Run(bookId,async()=>{
|
||||
string? kind=null;int eventId=0;if(action=="anchor"){var pieces=eventKey?.Split(':');if(pieces?.Length!=2||pieces[0] is not ("Knowledge" or "Relationship")||!int.TryParse(pieces[1],out eventId))throw new ArgumentException("Choose a saved knowledge or relationship event.");kind=pieces[0];}
|
||||
await manuscripts.Change(Author,bookId,revision,action,target,other,text,kind,eventId,primary,from-1,to-1,startOffset,endOffset);presence.BooksChanged(Author);return "Manuscript structure and evidence updated. Word prose is unchanged.";});
|
||||
private async Task<IActionResult> Run(int book,Func<Task<string>> work)
|
||||
private async Task<IActionResult> Run(int book,Func<Task<string>> work,Func<Guid>? requestId=null)
|
||||
{
|
||||
if(!manuscripts.Enabled)return NotFound();
|
||||
try{TempData["ParagraphMessage"]=await work();}catch(UnauthorizedAccessException){return Forbid();}
|
||||
catch(Exception e)when(e is ArgumentException or InvalidOperationException){TempData["ParagraphMessage"]=e.Message;}
|
||||
catch(SqlException e)when(e.Number==51000){TempData["ParagraphMessage"]=e.Message;}
|
||||
catch(SqlException){TempData["ParagraphMessage"]="The change was refused. Check your owner permissions, finish any active import, then refresh before retrying.";}
|
||||
return RedirectToAction(nameof(Index),new{bookId=book});
|
||||
var ajax=Request.Headers["X-Requested-With"]=="XMLHttpRequest";
|
||||
string message;var status=200;
|
||||
try{message=await work();}catch(UnauthorizedAccessException){return ajax?StatusCode(403,new{message="Only the authorised book owner can synchronise this manuscript."}):Forbid();}
|
||||
catch(Exception e)when(e is ArgumentException or InvalidOperationException){message=e.Message;status=409;}
|
||||
catch(SqlException e)when(e.Number==51000){message=e.Message;status=409;}
|
||||
catch(SqlException){message="The change was refused. Check your owner permissions, finish any active import, then refresh before retrying.";status=409;}
|
||||
if(ajax)return StatusCode(status,new{message,requestId=requestId?.Invoke()});
|
||||
TempData["ParagraphMessage"]=message;return RedirectToAction(nameof(Index),new{bookId=book});
|
||||
}
|
||||
}
|
||||
|
||||
@ -39,8 +39,14 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc
|
||||
}
|
||||
public async Task<ParagraphPosition?> ResolveParagraphPosition(int user,int book,Guid manuscript,Guid session,long revision,int position){if(configuration?.GetValue<bool>("Features:ParagraphManuscripts")!=true)return null;using var scope=scopes.CreateScope();return await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IParagraphManuscriptRepository>().Position(user,book,manuscript,session,revision,position);}
|
||||
public async Task CancelParagraphSnapshot(int user,int book){using var scope=scopes.CreateScope();var status=await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IParagraphManuscriptRepository>().Status(user,book);if(status?.CanWrite!=true)throw new UnauthorizedAccessException();foreach(var item in pending.Where(p=>p.Value.User==user&&p.Value.Book==book&&p.Value.Sync&&p.Value.Hash==null).ToArray()){presence.RequestCancellation(user,item.Value.Lease);await Fail(user,item.Value.Lease.Grant,item.Key);}}
|
||||
public sealed record ParagraphTransfer(Guid RequestId,string State);
|
||||
public ParagraphTransfer? ParagraphTransferStatus(int user,int book,Guid instance,Guid session)
|
||||
{
|
||||
var latest=pending.Where(p=>p.Value.User==user&&p.Value.Book==book&&p.Value.Sync&&p.Value.Lease.Instance==instance&&p.Value.Lease.Session==session).OrderByDescending(p=>p.Value.Created).FirstOrDefault();
|
||||
return latest.Value==null?null:new(latest.Key,latest.Value.Hash!=null?"accepted":latest.Value.FailureCode!=null||latest.Value.Expires<=clock.GetUtcNow()?"failed":"pending");
|
||||
}
|
||||
private readonly Dictionary<(int,Guid,Guid),DateTimeOffset> autoChecks=[];
|
||||
public async Task<Guid> RequestParagraphSnapshot(int user,int book,NativeLease? automatic=null)
|
||||
public async Task<Guid> RequestParagraphSnapshot(int user,int book,NativeLease? automatic=null,Guid? instanceId=null,Guid? sessionId=null)
|
||||
{
|
||||
if(configuration?.GetValue<bool>("Features:ParagraphManuscripts")!=true)throw new InvalidOperationException("Paragraph tracking is not enabled.");
|
||||
await acceptance.WaitAsync();try{
|
||||
@ -49,7 +55,9 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc
|
||||
if(!status.CanWrite)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("The existing book import is still active. Synchronisation is paused to protect it.");
|
||||
var documents=presence.Read(user,book).Where(l=>l.Position.WordAvailable&&l.Position.CanParagraphSync).ToArray();
|
||||
if(automatic!=null&&(status.Mode!="OnSave"||documents.Length!=1||!automatic.Position.WordSaved.GetValueOrDefault()||(status.SessionId==automatic.Session&&status.WordRevision==automatic.Position.Revision)))return Guid.Empty;
|
||||
var active=documents.Where(l=>l.Position.Active).ToArray();var selected=automatic??(active.Length==1?active[0]:documents.Length==1?documents[0]:throw new InvalidOperationException("Activate the intended Word manuscript. Multiple or no eligible documents are connected."));
|
||||
if(instanceId.HasValue!=sessionId.HasValue)throw new InvalidOperationException("Select a complete Word document session before synchronising.");
|
||||
var active=documents.Where(l=>l.Position.Active).ToArray();
|
||||
var selected=instanceId.HasValue?documents.SingleOrDefault(l=>l.Instance==instanceId&&l.Session==sessionId)??throw new InvalidOperationException("The selected Word document is no longer connected. Select it again before synchronising."):automatic??(active.Length==1?active[0]:documents.Length==1?documents[0]:throw new InvalidOperationException("Activate the intended Word manuscript. Multiple or no eligible documents are connected."));
|
||||
if(selected.Position.ManuscriptId!=status.ManuscriptId)throw new InvalidOperationException("This is a different document. Import a different manuscript into a separate book; automatic cross-document evidence matching is refused.");
|
||||
if(pending.Values.Any(p=>p.User==user&&p.Hash==null&&p.FailureCode==null&&p.Expires>clock.GetUtcNow()))return Guid.Empty;
|
||||
if(pending.Count>=128)throw new InvalidOperationException("Manuscript transfer capacity is busy.");var id=Guid.NewGuid();
|
||||
|
||||
@ -19,7 +19,7 @@ public sealed class NativePresenceStore(TimeProvider clock)
|
||||
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{ParagraphRevision=value.ParagraphRevision,CanCapture=value.CanCapture,CanParagraphSync=value.CanParagraphSync,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordRunning=value.WordRunning,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;}
|
||||
leases[key]=new(user,grant,expires,instance,session,new NativePresence{CaptureRequestId=value.CaptureRequestId,CaptureProgress=value.CaptureProgress,ParagraphRevision=value.ParagraphRevision,CanCapture=value.CanCapture,CanParagraphSync=value.CanParagraphSync,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordRunning=value.WordRunning,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,bool requireSaved=false,Guid? navigationId=null)
|
||||
|
||||
@ -7,6 +7,12 @@
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm mt-2" data-word-return-to-current disabled>Show current Word scene</button>
|
||||
</div>
|
||||
<p class="small mt-2">Only current, authorised document sessions are listed. Saved story information remains available when Word is disconnected.</p>
|
||||
<form action="/manuscript/paragraphs/snapshot" method="post" data-word-sync-form class="mb-3">
|
||||
@Html.AntiForgeryToken()
|
||||
<input type="hidden" name="bookId" data-word-sync-book />
|
||||
<button type="submit" class="btn btn-primary" data-word-sync-button disabled>Synchronise from Word</button>
|
||||
<p class="small mt-2 mb-0" data-word-sync-feedback role="status">Select a connected, saved manuscript to refresh its paragraph positions. Word prose is never rewritten and AI analysis is not started.</p>
|
||||
</form>
|
||||
<p data-word-connection-diagnostics class="small text-muted"></p>
|
||||
<nav class="d-flex flex-wrap gap-3 mb-3" data-word-book-links hidden><a data-word-book-link target="_blank" rel="noopener">Open book workspace</a><a data-word-structure-link target="_blank" rel="noopener">Manuscript structure and evidence</a></nav>
|
||||
<a href="/Writer" target="_blank" rel="noopener" class="btn btn-outline-secondary btn-sm">Workspace and display settings</a>
|
||||
|
||||
@ -2,6 +2,18 @@
|
||||
'use strict';const root=document.querySelector('#native-companion-status');if(!root)return;
|
||||
const text=root.querySelector('#native-companion-status-text');let pending=false,seen=false,refreshAgain=false,reconnectPending=false;
|
||||
const details=document.querySelector('#writing-connection-details'), documents=details?.querySelector('#writing-word-document');
|
||||
const syncForm=details?.querySelector('[data-word-sync-form]'),syncButton=syncForm?.querySelector('[data-word-sync-button]'),syncFeedback=syncForm?.querySelector('[data-word-sync-feedback]');
|
||||
let syncCurrent=null,syncPending=null;
|
||||
syncForm?.addEventListener('submit',async event=>{
|
||||
event.preventDefault();if(!event.isTrusted||!syncCurrent||syncButton.disabled)return;
|
||||
const selected=syncCurrent;syncPending={key:selected.instanceId+'/'+selected.sessionId,revision:selected.snapshotRevision||0,started:Date.now()};syncButton.disabled=true;
|
||||
syncFeedback.textContent='Requesting a saved paragraph snapshot from Word…';
|
||||
const body=new URLSearchParams(new FormData(syncForm));body.set('instanceId',selected.instanceId);body.set('sessionId',selected.sessionId);
|
||||
try{const response=await fetch(syncForm.action,{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)});
|
||||
if(response.redirected||!response.headers.get('content-type')?.includes('application/json'))throw Error('Sign in to PlotDirector again before requesting synchronisation.');
|
||||
const result=await response.json();if(!response.ok)throw Error(result.message||'Synchronisation could not be requested.');syncFeedback.textContent=result.message;if(syncPending)syncPending.requestId=result.requestId&&result.requestId!=='00000000-0000-0000-0000-000000000000'?result.requestId:null;if(!syncPending?.requestId){syncPending=null;syncButton.disabled=false;}void update();
|
||||
}catch(error){syncPending=null;syncButton.disabled=false;syncFeedback.textContent=error.message||'Could not contact PlotDirector. Your saved manuscript is unchanged.';}
|
||||
});
|
||||
root.addEventListener('click',()=>details?.showModal());
|
||||
details?.querySelector('[data-close-word-details]')?.addEventListener('click',()=>details.close());
|
||||
details?.querySelector('[data-word-return-to-current]')?.addEventListener('click',()=>{window.dispatchEvent(new Event('plotdirector:word-return-to-current'));details.close();});
|
||||
@ -18,6 +30,18 @@
|
||||
details.querySelector('[data-word-document-picker]')?.toggleAttribute('hidden',!workspace);
|
||||
const activeInScope=selectable.filter(l=>l.active),selection=documents.value?selectable.find(l=>l.instanceId+'/'+l.sessionId===documents.value):activeInScope.length===1?activeInScope[0]:selectable.length===1?selectable[0]:null;
|
||||
const returnButton=details.querySelector('[data-word-return-to-current]');if(returnButton)returnButton.disabled=!selection?.sceneId||selection.wordSaved===false;
|
||||
syncCurrent=selection;
|
||||
if(syncForm){syncForm.querySelector('[data-word-sync-book]').value=selection?.bookId||'';syncButton.disabled=!!syncPending||!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;
|
||||
if(syncPending){const observed=selectable.find(l=>l.instanceId+'/'+l.sessionId===syncPending.key);
|
||||
if(observed?.mappingCurrent&&Number(observed.snapshotRevision)>syncPending.revision){syncPending=null;syncButton.disabled=!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;syncFeedback.textContent='Word snapshot accepted. This session’s paragraph positions are verified; current scene following can resume.';}
|
||||
else if(syncPending.requestId&&(!observed||observed.paragraphTransfer?.requestId!==syncPending.requestId||observed.paragraphTransfer.state==='failed')){syncPending=null;syncButton.disabled=!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;syncFeedback.textContent='Word transfer ended without an accepted snapshot. Saved paragraphs are unchanged. Check Companion Troubleshooting, then retry.';}
|
||||
else if(observed?.captureRequestId)syncFeedback.textContent='Reading Word: '+Math.max(0,Math.min(100,Number(observed.captureProgress)||0))+'%. Keep Word open until PlotDirector acknowledges the snapshot.';
|
||||
else if(Date.now()-syncPending.started>120000){syncPending=null;syncButton.disabled=false;syncFeedback.textContent='No accepted snapshot has been confirmed. Open Manuscript structure and evidence below or Companion Troubleshooting before retrying.';}
|
||||
}else if(!selection)syncFeedback.textContent='Open the intended manuscript in Word and select its current connection. Saved scene browsing remains available.';
|
||||
else if(selection.wordSaved!==true)syncFeedback.textContent='Save the manuscript in Word before requesting synchronisation.';
|
||||
else if(selection.canParagraphSync!==true)syncFeedback.textContent='The connected add-in has not advertised paragraph synchronisation. Check the installed Companion and Word connection.';
|
||||
}
|
||||
|
||||
const active=leases.filter(l=>l.active&&l.wordAvailable),available=leases.filter(l=>l.wordAvailable);
|
||||
const current=leases.find(l=>l.instanceId+'/'+l.sessionId===documents.value)||(active.length===1?active[0]:available.length===1?available[0]:null);
|
||||
const book=Number(workspace?.dataset.scopeBookId||current?.bookId),links=details.querySelector('[data-word-book-links]');
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user