Remove redundant Word verification setup and chapter handoff waits
This commit is contained in:
parent
7bd98194b2
commit
aeffbb90ce
@ -0,0 +1,106 @@
|
||||
# Candidate 1.0.0.32: bounded Word verification and chapter handoff
|
||||
|
||||
Continue `codex/word-companion-native-phase1-20261104`, fetch and fast-forward only. No branches/worktrees, author-data repair, Windows operation or installation on Atlas. Preserve the installed .31 package and the successful checkpoint-reuse handshake. No Development server deployment or SQL change is required by this candidate.
|
||||
|
||||
Baseline: **`7bd98194b2cc92466f36f3276e0996c089dfab45`**, including the .31 Windows build/installation handover. That repository report still leaves live acceptance pending. The **49,526.4 ms real Word result supplied in this task's attached instructions** is the performance evidence used below; it is not a new Atlas measurement.
|
||||
|
||||
## Investigation: execution, waiting and necessary evidence
|
||||
|
||||
The current sequence is recognition/association → manifest → queued chapter command → UI dispatch → boundary/text/structure reads → native paragraph evidence → framed local IPC → agent hashing/comparison → next queued chapter command → final unchanged reuse/finish. The .31 server handshake is working and is unchanged here.
|
||||
|
||||
The .31 Word reader phase 7 creates a point Document.Range, obtains its Paragraphs collection and first Paragraph, obtains its Range, then reads start/end/ParaID/outline and releases every RCW for **every paragraph**. It also checks Document.Saved and BackgroundSavingStatus per step. A successful pass reads each body paragraph identity once, with additional next-heading identity reads for boundary proofs (up to 47 in this 48-chapter pass). The ID counter does not by itself equal the body paragraph count; the new completed-body-visit counter makes that distinction explicit.
|
||||
|
||||
The 9,187 UI steps consist predominantly of that one-paragraph action, with boundary seeking, structure checks, anchor/segment work and bounded text/XML/identity transport steps. WordAccessScheduler runs at most 16 chapter actions/15 ms per Pump; WordAdapter pumps it from a nominal 25 ms Forms timer. Thus even a cheap paragraph action repeatedly crosses scheduling, collection-creation, saved-state and RCW-release boundaries. The 652 batches include the paragraph walk plus those other steps; they are not 652 independent full manuscript scans.
|
||||
|
||||
There is a separate confirmed transport stall: AgentLink sends queued frames immediately, but when its producer mailbox is empty it sends an ordinary ping only after **one second**. PipeHost writes only a response to a request. TrayCoordinator.ProcessChapter computes hashes asynchronously after chapter-end; AdvanceChapter queues the next command only after that work. If the chapter-end response has already left, the command cannot reach Word until a later selection/metrics frame or idle ping. Word's passive observations run approximately once per second. This is a command-delivery gap, not slow COM or server reconciliation.
|
||||
|
||||
### What the reported .31 durations establish
|
||||
|
||||
| Measurement | Actual supplied Word result | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| End-to-end | 49,526.4 ms | Document registration to completion |
|
||||
| Recognition / manifest | 491.8 / 341.8 ms | Separate recognition and HTTP manifest intervals |
|
||||
| Fingerprints / server phase | 56.8 / 1,215.7 ms | Agent verification and accumulated server round trips |
|
||||
| UI step / batch active work | 10,400.9 / 10,471.8 ms | Overlapping execution counters, not additional independent stages |
|
||||
| Live / XML chapter completion | 23,258.7 / 935.2 ms | Read wall windows including their internal scheduling/transport waits |
|
||||
| Native ID / chapter text calls | 68.5 / 54.5 ms | Only those named COM operations; **not all Word COM time** |
|
||||
| Reuse / submissions / reconciliations | 48 / 0 / 0 | The .31 handshake already reuses the accepted source |
|
||||
|
||||
The approximately 24.194 s of chapter read wall windows overlap active UI work. Treating recognition, manifest, fingerprint, server and chapter read windows as serial leaves approximately **23.226 s unassigned**; the old counters do not prove an exact exclusive partition. Finish, dispatch and command-delivery gaps are in that residual. Forty-seven handoffs averaging half the old one-second poll interval would yield about 23.5 s: this is a source-based explanation consistent with the residual, **not a measured attribution**. New timings separate those waits. No claim that COM consumed 23 s is justified.
|
||||
|
||||
### Why paragraph identities cannot simply be skipped
|
||||
|
||||
Durable checkpoints contain content/identity/mapping digests, chapter order/boundaries and optional native geometry digest. The canonical snapshot contains the paragraph GUID/native ID ordering and scene assignments; current-session validations contain live absolute positions. The compact manifest does not provide a new live-document identity witness. A matching chapter content hash proves exact paragraph text partition, not ParaID equality or native geometry. Moving two identical-text paragraphs, replacing IDs without changing prose, or moving a zero-text picture anchor can preserve prose while invalidating identity/positions. Saved state and document association alone cannot rule those changes out.
|
||||
|
||||
Existing v1 Identity and native PositionHash are already sufficient fingerprints once trustworthy **current live** evidence has been read. No parallel hash, saved-DOCX cache or protocol redesign is required. Reading a saved package without an established binding to the in-memory Word IDs would not justify skipping the live checks. There is no supported, qualified bulk live-ID API in this implementation; range XML on the qualified Word build previously omitted those IDs.
|
||||
|
||||
| Category | Work and decision |
|
||||
| --- | --- |
|
||||
| Essential before whole-book readiness | Current association/session/saved/revision checks, complete current native identity/order/outline/span evidence, exact text hash, live boundaries, required structural geometry, existing server acknowledgement and finish |
|
||||
| Essential for current-cursor Context | Only its safely verified mapped chapter/scene evidence; .31 already flushes the current chapter first. A cursor in unmapped front matter is not assigned the first scene. |
|
||||
| Necessary but deferrable | Other chapters can remain untrusted while the current verified scene is usable; existing progressive behaviour is retained. Their checks still precede whole-book Up to date. |
|
||||
| Redundant setup eliminated | Thousands of point-range/Paragraphs acquisitions, per-paragraph saved/background-save probes, generic per-COM metric queue entries subsequently dropped, one-second idle waits for an already queued command |
|
||||
| Retained conservative work | Fresh per-paragraph IDs and geometry, boundary cross-checks, per-chapter structural detection and the qualified picture/XML path. No long-lived COM or shape cache with unqualified invalidation rules is introduced. |
|
||||
|
||||
## Focused implementation
|
||||
|
||||
1. **Plain native collection batches.** ChapterIdentityRead bounds one step to at most 32 paragraphs and a nominal 8 ms, always allowing one unpreemptible paragraph call to make progress. WordChapterRead creates a range/collection **once per batch**, indexes only those bounded paragraphs (no Count/full enumeration), and releases each Paragraph/Range immediately. No RCW survives a scheduler turn. Native start/end, normalised ID and live outline are still read for every paragraph; strict contiguity, chapter coverage and existing size limits remain. Saved/background-save checks bracket each batch, and the managed document revision/closing checks also run inside the loop. The existing v1 frames/hashes and .31 reuse proof are unchanged.
|
||||
2. **No generic metric flood.** All Com delegates in a chapter are counted/timed in its bounded aggregate; named metrics such as paragraph ID/text/XML remain. Generic chapter accessor calls no longer allocate individual UiMetric entries that would mostly be evicted from the bounded queue. Failure operation names and recent-call peak diagnostics remain available.
|
||||
3. **Bounded command polling.** After chapter-end, the existing pipe worker uses ordinary ping requests at a nominal 25 ms only while waiting for a command, for at most three seconds per session. A command, terminal status, close or reconnect ends the window. The ordinary one-second idle keepalive remains outside this window. No Word COM runs on this worker and no server HTTP request is added. This removes the need to wait for another cursor/metrics event. The small number of extra local pings is deliberately distinguished from manuscript/server submissions.
|
||||
4. **Runnable-work timer.** The Word timer requests 5 ms only while chapter work is runnable; it returns to 25 ms when finished, waiting for another command, or inside an author quiet period. Pump still limits chapter work to 16 callbacks/15 ms, prioritises selection and rejects reentrant Pump calls. Native plain batches have their own 8 ms/32-paragraph limit. The interval is a request, not a promise of Windows timer resolution; actual host/timer waits must be measured in Word. No single long manuscript COM operation or busy UI spin is introduced.
|
||||
5. **Structural path retained.** The .28 physical-position/XML, exact native paragraph text, zero-text picture anchor and segment gates are unchanged. Only their existing scheduling shares the shorter runnable cadence. No image/outline/native-position safeguard is bypassed because prose matches.
|
||||
|
||||
Canonical paragraph GUIDs, scene/chapter mappings, stored checkpoints, fingerprint formats, saved revision semantics, authentication, ribbon layout, Writing Intent and server/database code are unchanged. Version metadata is .32 for both components and MSI, with a fresh ProductCode and unchanged upgrade family/baseline pins. The scheduler's original parameterless constructor is retained for binary compatibility.
|
||||
|
||||
## Context readiness: actual state, not a green label
|
||||
|
||||
`awaiting-structure` originates in SessionManager's legacy local boundary list. Chapter synchronisation does not populate that list; the authoritative scene comes from scoped server positions. A local status string is not the Context readiness state machine.
|
||||
|
||||
In the client, a genuine race existed: a presence response for an older cursor could overwrite the chapter/scene after a newer selection, as long as the Word revision matched. ChapterCursorEvidence now applies scene evidence only for the current saved cursor, Word revision, book, manuscript with a server-reported paragraph revision. Changing cursor/saved state invalidates old local scene evidence and schedules a fresh observation. Chapter work/manifest processing and explicit operations are preserved; the server handshake is untouched.
|
||||
|
||||
The diagnostic now distinguishes current verified scene, pending current-cursor evidence, and no resolved scene. A response with no chapter/scene alone cannot distinguish front matter from pending verification; it does **not** claim a verified unmapped position. Once whole-manuscript verification has completed, the known current chapter ranges can identify an outside-chapter cursor accurately. Context=-1 remains correct if no canonical scene has actually resolved. The Word-side old string is labelled **Last local protocol status**, and the agent separately reports current Context evidence. No first-scene fallback or invented readiness transition is added.
|
||||
|
||||
## New stage timings
|
||||
|
||||
Completed reads report wall time (existing live/XML completion), active UI execution, every Com delegate's wall time and call count, separately timed RCW release calls, actual plain collection batches/body paragraphs visited, and per-action queue delay split into author quiet time, other scheduled active work, and eligible timer/host idle. The latter includes main-message-pump/host activity and is **not proven pure timer sleep**. Monotonic counters account for self-posting inside a callback and overlapping quiet intervals without summing overlapping waits twice.
|
||||
|
||||
Successful next-command handoffs separately report wall time, pipe exchange time and worker idle time; window closure/expiry is a separate metric. Dispatch from pipe response to the Word UI is recorded separately. Completed-read aggregates exclude abandoned partial reads; the existing named ID/structure metrics still include attempts. Process counters can cover more than one document, so collect a fresh, single-document qualification session. These metrics overlap where documented and must not be summed indiscriminately.
|
||||
|
||||
## Synthetic comparison and correctness coverage
|
||||
|
||||
The portable read fixture contains **48 chapters, 8,457 paragraphs, 153,139 words**. At zero synthetic time cost per paragraph (count limit only), collection setups fall **8,457 → 288**; saved-state calls for that walk fall **16,914 → 1,152**. Every native identity is still visited once. The candidate's nominal removable setup/state COM calls are reduced by **32,100** in this fixture; actual time-limited Word batches may be smaller, so actual savings must use measured counts. Exact content/identity frames remain compatible. This is an operation-count comparison, not Word COM timing or a prediction of 288 actual Word batches.
|
||||
|
||||
A separate executable benchmark compiled the exact .31 AgentLink source from baseline 7bd9819 beside the candidate, using the same Linux named-pipe fixture with an idle producer, 48 asynchronous handoffs and a controlled 40 ms readiness gap:
|
||||
|
||||
| Transport-only measurement | .31 source | .32 candidate |
|
||||
| --- | ---: | ---: |
|
||||
| Handoff wall time | 48,614.6 ms | 2,596.4 ms |
|
||||
| Chapter-end frames | 48 | 48 |
|
||||
| Local ping frames | 48 | 95 |
|
||||
|
||||
This benchmark deliberately leaves the producer idle: .31 has to use its full idle-ping interval. Real Word's periodic selection/metrics traffic can shorten that wait. It proves the transport mechanism and eliminated polling floor under that condition; it does **not** reproduce Word, its COM cost, Windows IPC, HTTP/SQL or end-to-end reopening. The actual .31 Word baseline remains **49,526.4 ms**. No .32 real Word speed or achieved 5–10-second target is claimed. Remaining mandatory live-ID/position and structural work is measured by the new counters, not guessed away.
|
||||
|
||||
Regression coverage combines the existing chapter/native/paragraph suites with new tests: unchanged exact evidence across 48 chapters; altered native ID with identical prose; identical-text paragraph reorder; contiguous/native coverage refusal; count/time budget boundaries; deterministic author/other-work/timer-host accounting; no nested COM pump; asynchronous command arrival without a selection; polling expiry; stale-cursor/revision/unsaved Context refusal; valid current scene before full book acceptance; and outside-chapter versus pending verification. Existing suites retain edited paragraph/chapter, insert/delete/split/merge, inserted/moved/deleted heading/structure refusal, scene boundaries/canonical decisions, native image/anchor geometry, missing/stale checkpoints, new sessions, resume and delayed acknowledgements. These fixtures cannot certify live Word collection behaviour or responsiveness.
|
||||
|
||||
Final build/test counts and pushed implementation identity are recorded below when complete.
|
||||
|
||||
## Focused Windows qualification — one specific candidate
|
||||
|
||||
Prepare .32 from the clean pushed source and retain .31. Use the established signed developer payload, VSTO build, MSI/CAB and upgrade gates, confirming both component versions. Do not launch/close Word, change trust stores or install unattended. No server deployment/migration is required; the existing .31 reuse capability must remain enabled.
|
||||
|
||||
After coordinating normal installation, use a saved previously synchronised Development test document:
|
||||
|
||||
1. Open once with a cursor inside a known mapped scene. Record actual total/local wall, active UI, all COM, queue/quiet/other/timer-host waits, pipe handoff/dispatch, body visits, collection/batch counts, live/XML reads, matches, reuse/individual/HTTP/reconciliation counts, Context resolution and Up-to-date time. Expect valid native identities for every paragraph, the same one structural read where required, checkpoint reuse with zero individual submissions/reconciliations, prompt current-scene Context. The 5–10-second total remains a target, not a pass inferred from Linux. Also observe typing/selection/scrolling/save responsiveness and maximum callback occupancy.
|
||||
2. If reopening at cursor zero/front matter instead, verify the scoped diagnostic accurately says no resolved scene/outside mapped chapters and does not invent a scene. Move normally into a known scene; confirm first valid scene evidence makes Context usable. Check the existing final chapter before/after its zero-text floating anchor.
|
||||
3. In an authorised disposable copy, edit a paragraph, save/reopen and confirm only the affected chapter reconciles under the existing mode/permit. Retain the .31 handshake counts, GUIDs/scenes and later shifted-position accuracy. Stop on a specific structural refusal; do not reset/reimport Discovery or run repeated author-manuscript repair cycles.
|
||||
|
||||
If the candidate remains above 10 seconds, report the measured remaining native, active and idle/handoff costs. Do not remove identity or anchor checks to force the number down. Word collection indexing, scheduler cadence and responsiveness require actual Windows observations before performance/compatibility acceptance.
|
||||
|
||||
## Final Atlas gates
|
||||
|
||||
- Solution build passed with **zero warnings/errors** (final recorded build 7.85 s).
|
||||
- Focused native/reopening/handshake: **355 PASS**; chapter/structural engine: **66 PASS**; paragraph/scene/recovery/workflow: **54 PASS**; full native foundation/authentication: **273 PASS**; full application harness: **457 PASS**. Focused tests and native foundation were rerun after the final client timing/readiness guards. One earlier foundation attempt hit a Linux broken-pipe error during the standalone compatibility handshake, before AgentLink construction; the clean rerun passed all 273 checks. No server pipe/protocol change was made to mask it.
|
||||
- The final portable 48-chapter evidence-generation/verification fixture took **96.0 ms**, with the operation counts above; this excludes Word and cannot quantify saved native milliseconds. The independent asynchronous pipe test delivered a next command in **115.5 ms** without selection/metrics traffic and confirmed that rapid polling subsequently expires rather than continuing permanently. These small samples are functional latency checks, not Windows performance gates.
|
||||
- Roslyn syntax inspection passed for all seven VSTO adapter source files, zero syntax errors. Actual Office/VSTO binding, collection behaviour and human responsiveness remain Windows qualification work. No claim of a signed/installed .32 build is made on Atlas.
|
||||
- Existing native HTTP-contract tests retain the .31 handshake counts: zero individual acceptance/reconciliation calls for unchanged chapters, only changed-chapter prose reconciliation, missing/geometry fallback, current chapter Context before other acknowledgements and rejection of late reuse after close.
|
||||
- No database was inspected, migrated, restored, reset or mutated in this task; no Development/Production service was deployed or restarted. Author data/documents and durable checkpoints were not used as mutation fixtures.
|
||||
23
PlotDirector.NativeCompanion/Agent/ChapterCursorEvidence.cs
Normal file
23
PlotDirector.NativeCompanion/Agent/ChapterCursorEvidence.cs
Normal file
@ -0,0 +1,23 @@
|
||||
using PlotDirector.Companion.Protocol;
|
||||
namespace PlotDirector.Companion.Agent;
|
||||
public static class ChapterCursorEvidence
|
||||
{
|
||||
public static void Invalidate(TrayDocument doc)
|
||||
{
|
||||
doc.ContextCursor=null;doc.ChapterId=null;doc.SceneId=null;doc.ChapterTitle="";doc.SceneTitle="";
|
||||
}
|
||||
public static bool Apply(TrayDocument doc,NativePresence reply)
|
||||
{
|
||||
if(doc.WordSaved!=true||reply.WordSaved!=true||reply.CursorStart!=doc.Cursor||reply.Revision!=doc.Revision||reply.BookId!=doc.Book||reply.ManuscriptId!=doc.Manuscript||reply.ParagraphRevision<=0)return false;
|
||||
doc.ContextCursor=doc.Cursor;doc.ContextRevision=doc.Revision;doc.ContextBook=doc.Book;doc.ContextManuscript=doc.Manuscript;doc.ChapterId=reply.ChapterId;doc.SceneId=reply.SceneId;doc.ChapterTitle=reply.ChapterTitle;doc.SceneTitle=reply.SceneTitle;return true;
|
||||
}
|
||||
public static bool Ready(TrayDocument doc)=>doc.Book>0&&doc.ContextBook==doc.Book&&doc.ContextManuscript==doc.Manuscript&&doc.WordSaved==true&&doc.ContextCursor==doc.Cursor&&doc.ContextRevision==doc.Revision&&doc.SceneId.HasValue;
|
||||
public static string State(TrayDocument doc,bool manuscriptVerified=false,bool cursorInsideChapter=false)
|
||||
{
|
||||
if(doc.WordSaved!=true)return "Unsaved or saved state unknown";
|
||||
if(doc.ContextBook!=doc.Book||doc.ContextManuscript!=doc.Manuscript||doc.ContextCursor!=doc.Cursor||doc.ContextRevision!=doc.Revision)return "Awaiting evidence for current cursor";
|
||||
if(Ready(doc))return "Verified scene at cursor "+doc.Cursor;
|
||||
if(manuscriptVerified)return cursorInsideChapter?"Verified manuscript; no scene resolved at cursor "+doc.Cursor:"Verified manuscript; cursor outside mapped chapters";
|
||||
return doc.ChapterId.HasValue?"Verified chapter; no scene resolved at cursor "+doc.Cursor:"No scene resolved at current cursor (unmapped or not yet verified)";
|
||||
}
|
||||
}
|
||||
@ -46,7 +46,7 @@ public sealed partial class TrayCoordinator
|
||||
lock(gate)
|
||||
{
|
||||
if(!chapterWork.TryGetValue(session,out var w))return "Chapter timings: awaiting recognised saved document.";
|
||||
return $"Chapter timings since document registration (ms): recognition={w.RecognitionMs:F1}, manifest={w.ManifestMs:F1}, fingerprints={w.VerificationMs:F1}, server={w.ServerMs:F1}, Context={w.ContextMs:F1}, complete={w.CompleteMs:F1}. Reads live/XML={w.LiveReads}/{w.XmlReads}, submissions={w.Submissions}. manifest/valid={w.Manifest?.Chapters.Length??0}/{w.Manifest?.Chapters.Count(c=>c.DurableAccepted)??0}; calculated/match/mismatch/missing/incompatible={w.Calculated}/{w.Matching}/{w.Mismatching}/{w.Missing}/{w.Incompatible}; reused={w.Reused}, pending={w.PendingReuse.Count}, reconciled={w.Reconciled}, reuseRequests={w.ReuseRequests}, requests={w.Requests}, bytes={w.RequestBytes}, reuse server read/process/validation/persistence ms={w.ReuseReadMs:F1}/{w.ReuseProcessingMs:F1}/{w.ReuseValidationMs:F1}/{w.ReusePersistenceMs:F1}. Negative timing means not observed.";
|
||||
return $"Current Context: {ChapterCursorEvidence.State(documents[session],w.Completion?.State=="Synchronised"&&w.Checked.Count==w.Manifest?.Chapters.Length,w.Checked.Values.Any(p=>documents[session].Cursor>=p.Start&&documents[session].Cursor<p.End))}. Chapter timings since document registration (ms): recognition={w.RecognitionMs:F1}, manifest={w.ManifestMs:F1}, fingerprints={w.VerificationMs:F1}, server={w.ServerMs:F1}, Context={w.ContextMs:F1}, complete={w.CompleteMs:F1}. Reads live/XML={w.LiveReads}/{w.XmlReads}, submissions={w.Submissions}. manifest/valid={w.Manifest?.Chapters.Length??0}/{w.Manifest?.Chapters.Count(c=>c.DurableAccepted)??0}; calculated/match/mismatch/missing/incompatible={w.Calculated}/{w.Matching}/{w.Mismatching}/{w.Missing}/{w.Incompatible}; reused={w.Reused}, pending={w.PendingReuse.Count}, reconciled={w.Reconciled}, reuseRequests={w.ReuseRequests}, requests={w.Requests}, bytes={w.RequestBytes}, reuse server read/process/validation/persistence ms={w.ReuseReadMs:F1}/{w.ReuseProcessingMs:F1}/{w.ReuseValidationMs:F1}/{w.ReusePersistenceMs:F1}. Negative timing means not observed.";
|
||||
}
|
||||
}
|
||||
|
||||
@ -89,7 +89,7 @@ public sealed partial class TrayCoordinator
|
||||
finally{lock(gate)ribbonRequests.Remove(session);}
|
||||
}
|
||||
private bool IsChapterCommand(TrayDocument doc,Guid id)=>chapterWork.TryGetValue(doc.Session,out var work)&&id!=Guid.Empty&&work.Command==id;
|
||||
private void CancelChapterWork(TrayDocument doc){if(chapterWork.TryGetValue(doc.Session,out var work)){work.Command=Guid.Empty;work.Operation=Guid.Empty;work.PendingReuse.Clear();work.ReuseFinishing=false;work.Text=new();work.Xml=new();work.Identities=new();doc.ChapterProgress=null;work.Busy=false;work.FailedRevision=doc.Revision;}}
|
||||
private void CancelChapterWork(TrayDocument doc){if(ChapterCapable(doc.Instance))ChapterCursorEvidence.Invalidate(doc);if(chapterWork.TryGetValue(doc.Session,out var work)){work.Command=Guid.Empty;work.Operation=Guid.Empty;work.PendingReuse.Clear();work.ReuseFinishing=false;work.Text=new();work.Xml=new();work.Identities=new();doc.ChapterProgress=null;work.Busy=false;work.FailedRevision=doc.Revision;}}
|
||||
private void BeginChapterRepair(TrayDocument doc,Guid operation)
|
||||
{
|
||||
if(!ChapterCapable(doc.Instance))return;
|
||||
@ -103,7 +103,7 @@ public sealed partial class TrayCoordinator
|
||||
private void ObserveChapterPresence(TrayDocument doc,NativePresence reply)
|
||||
{
|
||||
if(!ChapterCapable(doc.Instance))return;
|
||||
lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc)return;var work=GetChapterWork(doc);work.Supported=reply.ChapterSyncSupported;if(work.ContextMs<0&&!string.IsNullOrEmpty(reply.SceneTitle))work.ContextMs=work.RecognitionMs+work.Elapsed.Elapsed.TotalMilliseconds;
|
||||
lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc)return;var work=GetChapterWork(doc);work.Supported=reply.ChapterSyncSupported;if(work.ContextMs<0&&ChapterCursorEvidence.Ready(doc))work.ContextMs=work.RecognitionMs+work.Elapsed.Elapsed.TotalMilliseconds;
|
||||
if(work.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Completion=null;work.Manifest=null;work.PendingReuse.Clear();work.ReuseFinishing=false;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;}
|
||||
if(DateTime.UtcNow<work.RetryAfter||work.Finished||!work.Supported||doc.WordSaved!=true||doc.Book<=0||work.FailedRevision==doc.Revision||doc.Capture!=null)return;
|
||||
if(work.Busy){if(!work.Processing&&work.Command!=Guid.Empty&&work.End>work.Start&&doc.Active&&doc.Cursor!=work.CursorWhenQueued&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End)&&(doc.Cursor<work.Start||doc.Cursor>=work.End)){QueueChapter(doc,work,doc.Cursor);return;}if(DateTime.UtcNow-work.Started>TimeSpan.FromMinutes(2)){StopChapterWork(doc,work,"Chapter validation timed out. Accepted checkpoints are retained. Check the connection before retrying.");}return;}
|
||||
|
||||
@ -36,7 +36,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
|
||||
else{
|
||||
doc.Observed=DateTime.UtcNow;
|
||||
if(request.Kind=="active"){foreach(var d in documents.Values)d.Active=false;doc.Active=true;}
|
||||
if(request.Kind=="selection"){doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}}
|
||||
if(request.Kind=="selection"){if(ChapterCapable(instance)&&(doc.Cursor!=request.Start||doc.WordSaved!=request.WordSaved)){ChapterCursorEvidence.Invalidate(doc);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}}
|
||||
ChapterFrame(doc,request,answer);
|
||||
if(request.Kind is "tray-sync" or "tray-repair")_ = RequestChapterFromRibbon(doc,request.Revision);
|
||||
if ((request.Kind is "tray-context" or "tray-intent") && answer.Status == "ok")
|
||||
@ -139,8 +139,8 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
|
||||
public async Task Heartbeat(CancellationToken cancellation)
|
||||
{
|
||||
while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromMilliseconds(500),cancellation);var available=Documents.Where(d=>d.Authentication==cloud.Status().AuthenticationContext&&cloud.Status().Health?.Authentication=="verified").ToArray();
|
||||
foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))continue;var key=$"{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,ChapterIssue=ChapterIssue(doc),CanChapterSync=ChapterCapable(doc.Instance),CanParagraphSync=ParagraphCapable(doc.Instance),CanCapture=captureInstances.Contains(doc.Instance),WordRunning=true,WordSaved=doc.WordSaved,CursorStart=doc.Cursor,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc||(ChapterCapable(doc.Instance)&&reply.Revision!=doc.Revision)||doc.Authentication!=cloud.Status().AuthenticationContext)continue;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;doc.ChapterProgress=reply.ChapterProgress;doc.ChapterTitle=reply.ChapterTitle;doc.SceneTitle=reply.SceneTitle;ObserveChapterPresence(doc,reply);}
|
||||
if(reply.ParagraphRevision>0)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext){doc.ChapterId=reply.ChapterId;doc.SceneId=reply.SceneId;}
|
||||
foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))continue;var key=$"{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,ChapterIssue=ChapterIssue(doc),CanChapterSync=ChapterCapable(doc.Instance),CanParagraphSync=ParagraphCapable(doc.Instance),CanCapture=captureInstances.Contains(doc.Instance),WordRunning=true,WordSaved=doc.WordSaved,CursorStart=doc.Cursor,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc||(ChapterCapable(doc.Instance)&&reply.Revision!=doc.Revision)||doc.Authentication!=cloud.Status().AuthenticationContext)continue;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;doc.ChapterProgress=reply.ChapterProgress;if(ChapterCapable(doc.Instance))ChapterCursorEvidence.Apply(doc,reply);else{doc.ChapterTitle=reply.ChapterTitle;doc.SceneTitle=reply.SceneTitle;}ObserveChapterPresence(doc,reply);}
|
||||
if(reply.ParagraphRevision>0&&!ChapterCapable(doc.Instance))lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext){doc.ChapterId=reply.ChapterId;doc.SceneId=reply.SceneId;}
|
||||
if(reply.Navigation is {Kind:"wizard-capture",BookId:>0} requested&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Book==0){await cloud.CheckConnection();lock(gate){if(doc.Book==0&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext&&cloud.Allows(doc.Authentication,requested.BookId)&&documents.GetValueOrDefault(doc.Session)==doc){doc.Book=requested.BookId;cloud.RememberBinding(doc.Manuscript,doc.Book,doc.Authentication);doc.LastPresenceKey="";}}}
|
||||
if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision){if((reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")&&captureInstances.Contains(doc.Instance)&&(reply.Navigation.BookId==0||reply.Navigation.BookId==doc.Book)&&cloud.Allows(doc.Authentication,doc.Book)){if(uploading!=0||documents.Values.Any(d=>d.Capture!=null)){_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);continue;}var retained=doc.RetryCapture;var reusable=retained!=null&&doc.RetryAuthentication==doc.Authentication&&doc.RetryBook==doc.Book&&retained.ManuscriptId==doc.Manuscript&&retained.Revision==doc.Revision&&retained.ParagraphTracking==reply.Navigation.ParagraphTracking;
|
||||
Cancel(doc);doc.Capture=new(){RequestId=reply.Navigation.Id,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,Revision=doc.Revision,ParagraphTracking=reply.Navigation.ParagraphTracking,End=reusable?retained!.End:0};doc.CaptureBaseRevision=reply.Navigation.BaseRevision;doc.CaptureBaseHash=reply.Navigation.BaseSnapshotHash;doc.CaptureFragments.Clear();
|
||||
@ -196,6 +196,7 @@ public sealed class TrayDocument
|
||||
public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Link this manuscript to a book, then use Import manuscript in PlotDirector.",ReviewPath="";
|
||||
internal ManuscriptCapture? RetryCapture;internal Guid RetryAuthentication;internal int RetryBook;
|
||||
public long CaptureBaseRevision;public string CaptureBaseHash="";public ManuscriptCapture? Capture;public List<ParagraphFragment> CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision;
|
||||
public int? ContextCursor;public long ContextRevision=-1;public int ContextBook;public Guid ContextManuscript;
|
||||
public readonly DateTime FirstObserved=DateTime.UtcNow;
|
||||
public Guid AssociationRequest;public bool AssociationNeedsSave;public string AssociationNotice="";public string MaintenanceReport="";public string WordDiagnostics="";public int Cursor;public int Retained;public int Failed;public int Book,Progress,Total,Done;public int? RememberedBook,Words,ChapterId,SceneId;public bool Active;public DateTime Observed,Started;
|
||||
public StructureSuggestion[] Chapters=[];public StructureSuggestion? Current;public Queue<StructureSuggestion> Pending=[];public HashSet<(long,int,int)> Completed=[];public HashSet<(long,int,int)> FailedChapters=[];public List<string> Errors=[];
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
using System.IO;
|
||||
using System.Diagnostics;
|
||||
using System.IO.Pipes;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@ -8,6 +9,22 @@ namespace PlotDirector.Companion.Client;
|
||||
|
||||
public sealed class AgentLink : IDisposable
|
||||
{
|
||||
private sealed class ChapterWait
|
||||
{
|
||||
public readonly Stopwatch Wall=Stopwatch.StartNew();public int Polls;public double ExchangeMs,IdleMs;
|
||||
}
|
||||
private readonly Dictionary<Guid,ChapterWait> chapterWaits=new(); // Worker thread only, bounded by open-document capacity.
|
||||
public event Action<ChapterHandoffTiming>? ChapterHandoff;
|
||||
private void EndChapterWait(Guid session,string reason)
|
||||
{
|
||||
if(!chapterWaits.TryGetValue(session,out var wait))return;chapterWaits.Remove(session);
|
||||
ChapterHandoff?.Invoke(new ChapterHandoffTiming{Session=session,Reason=reason,WallMs=wait.Wall.Elapsed.TotalMilliseconds,ExchangeMs=wait.ExchangeMs,IdleMs=wait.IdleMs,Polls=wait.Polls});
|
||||
}
|
||||
private bool PollChapterCommands()
|
||||
{
|
||||
foreach(var session in chapterWaits.Where(p=>p.Value.Wall.ElapsedMilliseconds>=3000).Select(p=>p.Key).ToArray())EndChapterWait(session,"window-ended");
|
||||
return chapterWaits.Count>0;
|
||||
}
|
||||
private readonly string pipeName;
|
||||
private readonly Guid instanceId;
|
||||
private readonly Func<NamedPipeClientStream, bool> verifyServer;
|
||||
@ -67,6 +84,7 @@ public sealed class AgentLink : IDisposable
|
||||
}
|
||||
private async Task ExchangeAsync(Stream pipe, Message message, CancellationToken cancellation)
|
||||
{
|
||||
var exchangeWatch=Stopwatch.StartNew();
|
||||
using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation))
|
||||
{
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(3));
|
||||
@ -81,6 +99,9 @@ public sealed class AgentLink : IDisposable
|
||||
throw new InvalidDataException("IPC response identity/version mismatch.");
|
||||
if (response.Status == "unsupported-version" || (message.Kind == "hello" && (response.Status != "ready" || !ProtocolVersion.SupportsRequiredCapabilities(response.Capabilities))))
|
||||
throw new InvalidDataException("Incompatible agent protocol/capabilities.");
|
||||
foreach(var wait in chapterWaits.Values)wait.ExchangeMs+=exchangeWatch.Elapsed.TotalMilliseconds;
|
||||
if(response.Command!=null)EndChapterWait(response.Command.SessionId,"next-command");
|
||||
if(response.ChapterStatusProvided&&response.ChapterProgress?.State is "Synchronised" or "Needs review")EndChapterWait(response.SessionId,"terminal-status");
|
||||
Received?.Invoke(response);
|
||||
}
|
||||
}
|
||||
@ -106,15 +127,27 @@ public sealed class AgentLink : IDisposable
|
||||
{
|
||||
if (mailbox.TryTake(out var message))
|
||||
{
|
||||
if(message!.Kind=="chapter-end"&&chapterWaits.Count<ProtocolVersion.MaxDocuments)chapterWaits[message.SessionId]=new ChapterWait();
|
||||
if(message.Kind=="close")EndChapterWait(message.SessionId,"closed");
|
||||
await ExchangeAsync(pipe, message!, stop.Token).ConfigureAwait(false);
|
||||
lastExchange = DateTime.UtcNow;
|
||||
}
|
||||
else if (PollChapterCommands() && DateTime.UtcNow-lastExchange>=TimeSpan.FromMilliseconds(25))
|
||||
{
|
||||
foreach(var wait in chapterWaits.Values)wait.Polls++;
|
||||
await ExchangeAsync(pipe,new Message{Kind="ping",WordInstanceId=instanceId},stop.Token).ConfigureAwait(false);
|
||||
lastExchange=DateTime.UtcNow;
|
||||
}
|
||||
else if (DateTime.UtcNow - lastExchange > TimeSpan.FromSeconds(1))
|
||||
{
|
||||
await ExchangeAsync(pipe,new Message { Kind="ping", WordInstanceId=instanceId },stop.Token).ConfigureAwait(false);
|
||||
lastExchange = DateTime.UtcNow;
|
||||
}
|
||||
else await Task.Delay(25, stop.Token).ConfigureAwait(false);
|
||||
else
|
||||
{
|
||||
var idle=Stopwatch.StartNew();await Task.Delay(25,stop.Token).ConfigureAwait(false);
|
||||
foreach(var wait in chapterWaits.Values)wait.IdleMs+=idle.Elapsed.TotalMilliseconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -129,7 +162,7 @@ public sealed class AgentLink : IDisposable
|
||||
}
|
||||
try { await Task.Delay(Math.Min(5000, 250 * ++attempt), stop.Token).ConfigureAwait(false); } catch (OperationCanceledException) { }
|
||||
}
|
||||
finally { lock (gate) activePipe = null; }
|
||||
finally { chapterWaits.Clear();lock (gate) activePipe = null; }
|
||||
}
|
||||
}
|
||||
// Never join the worker from an Office callback or hold the Word thread for shutdown.
|
||||
@ -140,3 +173,8 @@ public sealed class AgentLink : IDisposable
|
||||
}
|
||||
public Task Completion => worker ?? Task.CompletedTask;
|
||||
}
|
||||
|
||||
public sealed class ChapterHandoffTiming
|
||||
{
|
||||
public Guid Session{get;set;}public string Reason{get;set;}="";public double WallMs{get;set;}public double ExchangeMs{get;set;}public double IdleMs{get;set;}public int Polls{get;set;}
|
||||
}
|
||||
|
||||
20
PlotDirector.NativeCompanion/Client/ChapterIdentityRead.cs
Normal file
20
PlotDirector.NativeCompanion/Client/ChapterIdentityRead.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using System.Text;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
namespace PlotDirector.Companion.Client;
|
||||
|
||||
// Bounds one live plain-text collection read, not an entire chapter/Word callback.
|
||||
public static class ChapterIdentityRead
|
||||
{
|
||||
public const int MaximumParagraphsPerStep=32;
|
||||
public const double MaximumMillisecondsPerStep=8;
|
||||
public static bool CanContinue(int count,double elapsedMilliseconds)=>count<MaximumParagraphsPerStep&&(count==0||elapsedMilliseconds<MaximumMillisecondsPerStep);
|
||||
public static int Append(StringBuilder frames,int expectedStart,int chapterEnd,int start,int end,string nativeId,int outline)
|
||||
{
|
||||
if(start!=expectedStart||end<=start||end>chapterEnd||frames.Length/24>=ChapterFingerprint.MaxParagraphs||outline<1||outline>10)
|
||||
throw new InvalidOperationException("Live Word paragraph boundaries or outline do not match the chapter.");
|
||||
if(WordParagraphIdentity.Normalise(nativeId)!=nativeId||nativeId.Length==0)throw new InvalidOperationException("Complete native paragraph identity is required.");
|
||||
frames.Append(nativeId);frames.Append((end-start).ToString("X8",System.Globalization.CultureInfo.InvariantCulture));frames.Append(outline.ToString("X8",System.Globalization.CultureInfo.InvariantCulture));
|
||||
return end;
|
||||
}
|
||||
}
|
||||
@ -1,51 +1,53 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace PlotDirector.Companion.Client;
|
||||
|
||||
// Pumped by a Windows Forms timer on Word's original UI thread. Actions never
|
||||
// execute on producers/Task.Run. Each action must itself bound its COM access.
|
||||
public sealed class WordQueueWait
|
||||
{
|
||||
public double TotalMs{get;set;}public double AuthorQuietMs{get;set;}public double OtherWorkMs{get;set;}public double TimerHostIdleMs{get;set;}
|
||||
}
|
||||
// Pumped only on Word's original UI thread. The optional monotonic clock supports
|
||||
// deterministic scheduling tests; actions still bound their own COM access.
|
||||
public sealed class WordAccessScheduler
|
||||
{
|
||||
private readonly Dictionary<string, Action> work = new();
|
||||
private Queue<string> order = new();
|
||||
private readonly int ownerThread = Environment.CurrentManagedThreadId;
|
||||
private DateTime quietUntil;
|
||||
public const int Capacity = 64;
|
||||
public int Depth => work.Count;
|
||||
public long Superseded { get; private set; }
|
||||
public event Action<string, double>? Measured;
|
||||
public event Action<Exception>? Failed;
|
||||
private void AssertOwner() { if (Environment.CurrentManagedThreadId != ownerThread) throw new InvalidOperationException("Word work must stay on its owning UI thread."); }
|
||||
public bool Post(string key, Action action)
|
||||
private sealed class Work(Action action,double queued,double active,double quiet)
|
||||
{public Action Action=action;public double Queued=queued,Active=active,Quiet=quiet;}
|
||||
private readonly Dictionary<string,Work> work=new();private Queue<string> order=new();
|
||||
private readonly int ownerThread=Environment.CurrentManagedThreadId;
|
||||
private readonly Func<double> now;
|
||||
private double quietStart,quietUntil,quietCompleted,activeMs,actionStarted;private bool running;
|
||||
public WordAccessScheduler():this(null){}
|
||||
public WordAccessScheduler(Func<double>? milliseconds){now=milliseconds??(()=>Stopwatch.GetTimestamp()*1000d/Stopwatch.Frequency);}
|
||||
private double QuietAt(double time)=>quietCompleted+Math.Max(0,Math.Min(time,quietUntil)-quietStart);
|
||||
private double ActiveAt(double time)=>activeMs+(running?time-actionStarted:0);
|
||||
public bool HasRunnableChapterWork{get{AssertOwner();return now()>=quietUntil&&work.Keys.Any(k=>k.StartsWith("chapter:",StringComparison.Ordinal));}}
|
||||
public const int Capacity=64;public int Depth=>work.Count;public long Superseded{get;private set;}
|
||||
public event Action<string,double>? Measured;public event Action<string,WordQueueWait>? Waited;public event Action<Exception>? Failed;
|
||||
private void AssertOwner(){if(Environment.CurrentManagedThreadId!=ownerThread)throw new InvalidOperationException("Word work must stay on its owning UI thread.");}
|
||||
public bool Post(string key,Action action)
|
||||
{
|
||||
AssertOwner();
|
||||
if (work.ContainsKey(key)) Superseded++;
|
||||
else { if (work.Count >= Capacity) return false; order.Enqueue(key); }
|
||||
work[key] = action; return true;
|
||||
AssertOwner();if(work.ContainsKey(key))Superseded++;else{if(work.Count>=Capacity)return false;order.Enqueue(key);}
|
||||
var time=now();work[key]=new(action,time,ActiveAt(time),QuietAt(time));return true;
|
||||
}
|
||||
public void Cancel(string key) { AssertOwner(); work.Remove(key); order = new Queue<string>(order.Where(k => k != key)); }
|
||||
public void Clear() { AssertOwner(); work.Clear(); order.Clear(); }
|
||||
public void PrioritizeAuthor(TimeSpan quietPeriod) { AssertOwner(); quietUntil = DateTime.UtcNow + quietPeriod; }
|
||||
public void Cancel(string key){AssertOwner();work.Remove(key);order=new Queue<string>(order.Where(k=>k!=key));}
|
||||
public void Clear(){AssertOwner();work.Clear();order.Clear();}
|
||||
public void PrioritizeAuthor(TimeSpan period){AssertOwner();var time=now();quietCompleted=QuietAt(time);quietStart=time;quietUntil=time+period.TotalMilliseconds;}
|
||||
public bool Pump()
|
||||
{
|
||||
AssertOwner();
|
||||
if (DateTime.UtcNow < quietUntil || work.Count == 0) return false;
|
||||
var batch = Stopwatch.StartNew();var chapterBatch=false;
|
||||
// Only chapter continuations may share a tick. Other operations retain one-action
|
||||
// semantics, and selection/author quiet periods are reconsidered after every step.
|
||||
AssertOwner();if(running||now()<quietUntil||work.Count==0)return false;
|
||||
var batch=now();var chapterBatch=false;
|
||||
for(var steps=0;steps<16;steps++)
|
||||
{
|
||||
var key = work.ContainsKey("selection") ? "selection" : order.Peek();
|
||||
var chapter=key.StartsWith("chapter:",StringComparison.Ordinal);
|
||||
if(steps>0&&!chapter)break;
|
||||
if(chapter)chapterBatch=true;
|
||||
var action = work[key]; Cancel(key);
|
||||
var watch = Stopwatch.StartNew();
|
||||
try { action(); } catch (Exception ex) { Failed?.Invoke(ex); }
|
||||
finally { Measured?.Invoke(key.Split(':')[0], watch.Elapsed.TotalMilliseconds); }
|
||||
if(!chapter||batch.ElapsedMilliseconds>=15||DateTime.UtcNow<quietUntil||work.Count==0||work.ContainsKey("selection"))break;
|
||||
var key=work.ContainsKey("selection")?"selection":order.Peek();var chapter=key.StartsWith("chapter:",StringComparison.Ordinal);
|
||||
if(steps>0&&!chapter)break;if(chapter)chapterBatch=true;
|
||||
var item=work[key];Cancel(key);var time=now();var delay=Math.Max(0,time-item.Queued);
|
||||
var quiet=Math.Min(delay,Math.Max(0,QuietAt(time)-item.Quiet));
|
||||
var other=Math.Min(delay-quiet,Math.Max(0,ActiveAt(time)-item.Active));
|
||||
Waited?.Invoke(key,new(){TotalMs=delay,AuthorQuietMs=quiet,OtherWorkMs=other,TimerHostIdleMs=Math.Max(0,delay-quiet-other)});
|
||||
actionStarted=now();running=true;
|
||||
try{item.Action();}catch(Exception ex){Failed?.Invoke(ex);}
|
||||
finally{var duration=now()-actionStarted;activeMs+=duration;running=false;Measured?.Invoke(key.Split(':')[0],duration);}
|
||||
if(!chapter||now()-batch>=15||now()<quietUntil||work.Count==0||work.ContainsKey("selection"))break;
|
||||
}
|
||||
if(chapterBatch)Measured?.Invoke("chapter-batch",batch.Elapsed.TotalMilliseconds);
|
||||
return true;
|
||||
if(chapterBatch)Measured?.Invoke("chapter-batch",now()-batch);return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1 +1 @@
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.31</ApplicationVersion></PropertyGroup></Project>
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.32</ApplicationVersion></PropertyGroup></Project>
|
||||
|
||||
@ -3,7 +3,7 @@ using PlotDirector.Companion.Agent;
|
||||
using PlotDirector.Companion.Client;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
|
||||
if(args.Contains("--chapter-sync")){ChapterReopenTests.Run();await ChapterAgentTests.Run();await ChapterHandshakeTests.Run();return;}
|
||||
if(args.Contains("--chapter-sync")){ChapterReopenTests.Run();await ChapterAgentTests.Run();await ChapterHandshakeTests.Run();await WordReopeningWorkTests.Run();return;}
|
||||
if(args.Contains("--native-capture-upload")){await NativeCaptureUploadTests.Run();return;}
|
||||
var passed = 0;
|
||||
void Check(bool value,string name) {if(!value)throw new Exception(name);passed++;Console.WriteLine("PASS "+name);}
|
||||
|
||||
80
PlotDirector.NativeCompanion/Tests/WordReopeningWorkTests.cs
Normal file
80
PlotDirector.NativeCompanion/Tests/WordReopeningWorkTests.cs
Normal file
@ -0,0 +1,80 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO.Pipes;
|
||||
using System.Text;
|
||||
using PlotDirector.Companion.Agent;
|
||||
using PlotDirector.Companion.Client;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
internal static class WordReopeningWorkTests
|
||||
{
|
||||
private static void Check(bool value,string text){if(!value)throw new Exception(text);Console.WriteLine("PASS "+text);}
|
||||
private static void Reject(Action action,string text){try{action();}catch(InvalidOperationException){Check(true,text);return;}throw new Exception(text);}
|
||||
public static async Task Run()
|
||||
{
|
||||
double time=0;var scheduler=new WordAccessScheduler(()=>time);WordQueueWait? wait=null;
|
||||
scheduler.Waited+=(key,delay)=>{if(key=="chapter:proof")wait=delay;};
|
||||
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(10));scheduler.Post("chapter:proof",()=>time+=2);
|
||||
time=5;Check(!scheduler.HasRunnableChapterWork,"Author quiet periods suppress accelerated chapter scheduling");Check(!scheduler.Pump(),"Chapter work respects an outstanding author quiet period");time=25;Check(scheduler.HasRunnableChapterWork,"Only runnable chapter work requests the shorter timer cadence");scheduler.Pump();
|
||||
Check(wait is {TotalMs:25,AuthorQuietMs:10,OtherWorkMs:0,TimerHostIdleMs:15},"Monotonic queue timings separate author delay and eligible timer/host idle");
|
||||
time=0;scheduler=new WordAccessScheduler(()=>time);wait=null;scheduler.Waited+=(key,delay)=>{if(key=="chapter:proof")wait=delay;};
|
||||
scheduler.Post("selection",()=>time+=4);scheduler.Post("chapter:proof",()=>{});scheduler.Pump();time=10;scheduler.Pump();
|
||||
Check(wait is {TotalMs:10,OtherWorkMs:4,TimerHostIdleMs:6},"Queue timing separates earlier scheduled active work from idle waiting");
|
||||
Check(ChapterIdentityRead.CanContinue(0,100)&&!ChapterIdentityRead.CanContinue(1,8)&&!ChapterIdentityRead.CanContinue(32,0),"Paragraph batches always make bounded progress and stop on either time or count limit");
|
||||
var paragraphCount=0;var batches=0;var words=0;var watch=Stopwatch.StartNew();
|
||||
for(var chapter=0;chapter<48;chapter++)
|
||||
{
|
||||
var count=chapter==47?8457-47*176:176;var paragraphs=Enumerable.Range(0,count).Select(n=>n==0?$"Chapter {chapter}\r":string.Join(" ",Enumerable.Repeat("synthetic",18+(n%5==0?1:0)))+"\r").ToArray();
|
||||
var text=string.Concat(paragraphs);var frames=new StringBuilder();var position=0;
|
||||
for(var offset=0;offset<count;)
|
||||
{
|
||||
batches++;for(var n=0;offset<count&&ChapterIdentityRead.CanContinue(n,0);n++,offset++)
|
||||
{var next=position+paragraphs[offset].Length;position=ChapterIdentityRead.Append(frames,position,text.Length,position,next,(++paragraphCount).ToString("X8"),offset==0?1:10);}
|
||||
}
|
||||
var decoded=ChapterFingerprint.ReadLiveText(text,frames.ToString());words+=paragraphs.Sum(p=>p.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length);
|
||||
Check(ChapterFingerprint.Content(decoded.Select(p=>p.Text!))==ChapterFingerprint.Content(paragraphs),"Bounded native identity batches preserve exact accepted paragraph partition and content hash");
|
||||
var changed=frames.ToString();var changedId="7FFFFFFF"+changed[8..];
|
||||
Check(ChapterFingerprint.Identity(ChapterFingerprint.ReadLiveText(text,changedId))!=ChapterFingerprint.Identity(decoded),"Changed native identity with unchanged prose cannot reuse the checkpoint");
|
||||
}
|
||||
Check(paragraphCount==8457&&batches==288,"Scale fixture visits every required native identity once with 288 collection acquisitions instead of 8457");
|
||||
Console.WriteLine($"PORTABLE read fixture: 48 chapters / {paragraphCount} paragraphs / {words} words, {watch.Elapsed.TotalMilliseconds:F1}ms. Point/collection setups 8457 -> {batches}; saved-state calls for the paragraph walk 16914 -> {batches*4}. No Word/COM timing.");
|
||||
Reject(()=>ChapterIdentityRead.Append(new(),0,10,1,10,"00000001",10),"Inserted/deleted/moved native paragraph gaps cannot be accepted as contiguous evidence");
|
||||
Reject(()=>ChapterIdentityRead.Append(new(),0,10,0,11,"00000001",10),"A paragraph extending across the live chapter boundary is refused");
|
||||
var repeated=new[]{"Heading\r","Repeated\r","Repeated\r"};var stableFrames=new StringBuilder();var cursor=0;
|
||||
for(var i=0;i<3;i++){var end=cursor+repeated[i].Length;cursor=ChapterIdentityRead.Append(stableFrames,cursor,repeated.Sum(t=>t.Length),cursor,end,(i+1).ToString("X8"),i==0?1:10);}
|
||||
var stable=ChapterFingerprint.ReadLiveText(string.Concat(repeated),stableFrames.ToString());
|
||||
var moved=stableFrames.ToString()[..24]+stableFrames.ToString().Substring(48,24)+stableFrames.ToString().Substring(24,24);
|
||||
var movedRows=ChapterFingerprint.ReadLiveText(string.Concat(repeated),moved);
|
||||
Check(ChapterFingerprint.Content(movedRows.Select(p=>p.Text!))==ChapterFingerprint.Content(repeated)&&ChapterFingerprint.Identity(movedRows)!=ChapterFingerprint.Identity(stable),"Moving identical prose paragraphs changes identity evidence even when the chapter text fingerprint matches");
|
||||
var doc=new TrayDocument{Book=1,Manuscript=Guid.NewGuid(),Cursor=100,Revision=2,WordSaved=true};
|
||||
NativePresence Proof(int cursor,int? scene)=>new(){BookId=doc.Book,ManuscriptId=doc.Manuscript,CursorStart=cursor,Revision=2,WordSaved=true,ParagraphRevision=3,ChapterId=4,SceneId=scene,SceneTitle=scene.HasValue?"Verified scene":""};
|
||||
Check(ChapterCursorEvidence.Apply(doc,Proof(100,5))&&ChapterCursorEvidence.Ready(doc),"Writing Context becomes ready from verified current-cursor scene evidence before book completion");
|
||||
doc.Cursor=200;ChapterCursorEvidence.Invalidate(doc);
|
||||
Check(!ChapterCursorEvidence.Apply(doc,Proof(100,5))&&!ChapterCursorEvidence.Ready(doc),"A late presence reply cannot restore the scene at a previous cursor");
|
||||
Check(ChapterCursorEvidence.Apply(doc,Proof(200,null))&&!ChapterCursorEvidence.Ready(doc)&&ChapterCursorEvidence.State(doc).StartsWith("Verified chapter; no scene"),"A verified chapter without a mapped scene never acquires a first-scene fallback");
|
||||
var unmapped=Proof(200,null);unmapped.ChapterId=null;ChapterCursorEvidence.Apply(doc,unmapped);
|
||||
Check(ChapterCursorEvidence.State(doc).Contains("not yet verified")&&ChapterCursorEvidence.State(doc,true,false).Contains("outside mapped chapters"),"Only whole-manuscript verification can distinguish an outside-chapter cursor from pending verification");
|
||||
time=0;scheduler=new WordAccessScheduler(()=>time);scheduler.Post("chapter:outer",()=>Check(!scheduler.Pump(),"A reentrant timer cannot nest Word COM work inside an active callback"));scheduler.Pump();
|
||||
var stale=Proof(200,5);stale.Revision--;Check(!ChapterCursorEvidence.Apply(doc,stale),"Stale Word revision cannot make Context ready");
|
||||
doc.WordSaved=false;Check(!ChapterCursorEvidence.Apply(doc,Proof(200,5)),"Unsaved Word state cannot claim a verified Context scene");
|
||||
await PipeHandoff();
|
||||
}
|
||||
private static async Task PipeHandoff()
|
||||
{
|
||||
var name="pd-reopen-"+Guid.NewGuid().ToString("N");var session=Guid.NewGuid();var instance=Guid.NewGuid();
|
||||
using var stop=new CancellationTokenSource(TimeSpan.FromSeconds(10));using var server=new NamedPipeServerStream(name,PipeDirection.InOut,1,PipeTransmissionMode.Byte,PipeOptions.Asynchronous|PipeOptions.CurrentUserOnly);
|
||||
var received=0;var polls=0;var expired=0;var ends=0;var ready=DateTime.MaxValue;
|
||||
var host=Task.Run(async()=>{await server.WaitForConnectionAsync(stop.Token);while(!stop.IsCancellationRequested){var request=await FrameCodec.ReadAsync(server,stop.Token);var answer=new Message{CorrelationId=request.CorrelationId,Status=request.Kind=="hello"?"ready":"ok",Capabilities=ProtocolVersion.Capabilities};if(request.Kind=="chapter-end")ready=++ends==1?DateTime.UtcNow.AddMilliseconds(40):DateTime.MaxValue;if(request.Kind=="ping"){polls++;if(DateTime.UtcNow>=ready){ready=DateTime.MaxValue;answer.Command=new(){Kind="chapter-check",SessionId=session,Revision=1};}}await FrameCodec.WriteAsync(server,answer,stop.Token);}});
|
||||
using var link=new AgentLink(name,instance,_=>true);var measured=0;var connected=false;
|
||||
link.ChapterHandoff+=m=>{if(m.Reason=="window-ended")Interlocked.Increment(ref expired);if(m.Reason=="next-command"){Interlocked.Increment(ref measured);Check(m.Polls>0&&m.ExchangeMs>=0&&m.IdleMs>=0,"Chapter handoff exposes actual pipe and worker-idle timing");}};
|
||||
link.StateChanged+=state=>connected=state=="connected";
|
||||
link.Received+=reply=>{if(reply.Command?.Kind=="chapter-check")Interlocked.Increment(ref received);};link.Start();while(!connected)await Task.Delay(5,stop.Token);
|
||||
link.TryPost(new(){Kind="chapter-end",SessionId=session,Revision=1,SnapshotId=Guid.NewGuid()});
|
||||
var watch=Stopwatch.StartNew();while(received==0){await Task.Delay(5,stop.Token);}
|
||||
Check(measured==1&&polls>0,"Next asynchronous chapter command arrives without another selection or metrics frame");
|
||||
Console.WriteLine($"PORTABLE real pipe handoff (Linux sockets): {watch.Elapsed.TotalMilliseconds:F1}ms, {polls} polls; not Windows IPC/Word performance.");
|
||||
link.TryPost(new(){Kind="chapter-end",SessionId=session,Revision=1,SnapshotId=Guid.NewGuid()});
|
||||
while(expired==0)await Task.Delay(5,stop.Token);var stoppedAt=polls;await Task.Delay(250,stop.Token);
|
||||
Check(stoppedAt>0&&polls==stoppedAt,"Fast command polling expires after a bounded window instead of running permanently");
|
||||
link.Dispose();await link.Completion.WaitAsync(TimeSpan.FromSeconds(5));stop.Cancel();try{await host;}catch(Exception e)when(e is OperationCanceledException or IOException or ObjectDisposedException){}
|
||||
}
|
||||
}
|
||||
@ -3,6 +3,6 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyTitle("PlotDirector Word Companion — Native development")]
|
||||
[assembly: AssemblyCompany("Nick Beckley")]
|
||||
[assembly: AssemblyProduct("PlotDirector")]
|
||||
[assembly: AssemblyVersion("1.0.0.31")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.31")]
|
||||
[assembly: AssemblyVersion("1.0.0.32")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.32")]
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
@ -69,9 +69,12 @@ namespace PlotDirector.WordAddIn
|
||||
+ "\nAgent startup: " + AgentProcess.LaunchStatus
|
||||
+ "\nMain document words: " + WordCountSummary
|
||||
+ "\nLast UI batch ms: " + lastBatchMs.ToString("F2") + "\nMax recorded COM call ms: " + (operationTimes.Count == 0 ? 0 : operationTimes.Max()).ToString("F2")
|
||||
+ "\nCompleted plain collection batches / RCW releases (process): " + chapterPlainBatches + " / " + chapterRcwReleases
|
||||
+ "\nCompleted chapter command polls (process): " + chapterCommandPolls
|
||||
+ "\nCompleted chapter native paragraphs / COM calls (process): " + chapterParagraphVisits + " / " + chapterComCalls
|
||||
+ "\nChapter reads live / XML (process): " + chapterLiveReads + " / " + chapterXmlReads
|
||||
+ "\n" + string.Join("\n",chapterMetrics.Select(p=>p.Key+": count="+p.Value[0]+", total ms="+p.Value[1].ToString("F1")+", max ms="+p.Value[2].ToString("F1")))
|
||||
+ "\nCOM busy/errors: " + busyFailures + (lastWordError == null ? "" : " (last: " + lastWordError + ")") + "\n" + lastResult;
|
||||
+ "\nCOM busy/errors: " + busyFailures + (lastWordError == null ? "" : " (last: " + lastWordError + ")") + "\nLast local protocol status: " + lastResult;
|
||||
|
||||
public WordAdapter(Word.Application application, Action invalidateRibbon)
|
||||
{
|
||||
@ -80,6 +83,7 @@ namespace PlotDirector.WordAddIn
|
||||
// Force a handle here; BeginInvoke always returns callbacks to this STA.
|
||||
var handle = dispatch.Handle;
|
||||
link = new AgentLink(AgentProcess.PipeName(), Guid.NewGuid(), AgentProcess.VerifyOwner, AgentProcess.Start);
|
||||
link.ChapterHandoff += timing=>PostToUi(()=>{if(timing.Reason=="next-command"){Metric("chapter-handoff-wall",timing.WallMs);Metric("chapter-handoff-ipc",timing.ExchangeMs);Metric("chapter-handoff-worker-idle",timing.IdleMs);chapterCommandPolls+=timing.Polls;}else Metric("chapter-handoff-window",timing.WallMs);});
|
||||
link.StateChanged += state => PostToUi(() => {
|
||||
ConnectionState = state;
|
||||
if(state!="connected")
|
||||
@ -96,10 +100,11 @@ namespace PlotDirector.WordAddIn
|
||||
link.Received += message => {
|
||||
if(message.Status=="ready")PostToUi(()=>{var capabilities=(message.Capabilities??"").Split(',');traySupported=capabilities.Contains(ProtocolVersion.TrayCapability);liveChapterTextSupported=capabilities.Contains(ProtocolVersion.LiveChapterTextCapability);nativeChapterTextSupported=capabilities.Contains(ProtocolVersion.NativeChapterTextCapability);nativeChapterPositionsSupported=capabilities.Contains(ProtocolVersion.NativeChapterPositionsCapability);});
|
||||
if(message.ChapterStatusProvided&&message.SessionId!=Guid.Empty)PostToUi(()=>ReceiveChapterStatus(message));
|
||||
if(message.Command!=null)PostToUi(()=>HandleCommand(message.Command));
|
||||
if(message.Command!=null){var delivery=Stopwatch.StartNew();PostToUi(()=>{if(message.Command.Kind=="chapter-check")Metric("chapter-command-ui-dispatch",delivery.Elapsed.TotalMilliseconds);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;
|
||||
};
|
||||
scheduler.Waited += (key,wait)=>{Guid session;ChapterRead read;if(key.StartsWith("chapter:",StringComparison.Ordinal)&&Guid.TryParse(key.Substring(8),out session)&&chapterReads.TryGetValue(session,out read)){read.QueueMs+=wait.TotalMs;read.QuietMs+=wait.AuthorQuietMs;read.OtherWorkMs+=wait.OtherWorkMs;read.TimerHostMs+=wait.TimerHostIdleMs;}};
|
||||
scheduler.Measured += (operation, elapsed) => {lastBatchMs=elapsed;if(operation=="chapter-batch")Metric("chapter-ui-batch",elapsed);};
|
||||
scheduler.Failed += error => {
|
||||
busyFailures++;
|
||||
@ -133,7 +138,7 @@ namespace PlotDirector.WordAddIn
|
||||
var watch = Stopwatch.StartNew();
|
||||
try { return read(); }
|
||||
catch(Exception error){error.Data["WordOperation"]=operation;throw;}
|
||||
finally { if(operationTimes.Count == 256)operationTimes.Dequeue(); operationTimes.Enqueue(watch.Elapsed.TotalMilliseconds);Metric(operation,watch.Elapsed.TotalMilliseconds); }
|
||||
finally { if(executingChapterRead!=null){executingChapterRead.ComCalls++;executingChapterRead.ComMs+=watch.Elapsed.TotalMilliseconds;}if(operationTimes.Count == 256)operationTimes.Dequeue(); operationTimes.Enqueue(watch.Elapsed.TotalMilliseconds);if(executingChapterRead==null||operation.StartsWith("chapter-",StringComparison.Ordinal))Metric(operation,watch.Elapsed.TotalMilliseconds); }
|
||||
}
|
||||
private void DiscoverOpenDocuments() => DiscoverAt(1);
|
||||
private void DiscoverAt(int index)
|
||||
@ -581,12 +586,12 @@ namespace PlotDirector.WordAddIn
|
||||
}
|
||||
private void Tick(object sender,EventArgs args)
|
||||
{
|
||||
Metric("ui-tick-delay",Math.Max(0,tickClock.Elapsed.TotalMilliseconds-25));tickClock.Restart();
|
||||
Metric("ui-tick-delay",Math.Max(0,tickClock.Elapsed.TotalMilliseconds-timer.Interval));tickClock.Restart();
|
||||
// Paste and some Word edits do not raise WindowSelectionChange. Probe only
|
||||
// position/length/saved state; reuse the existing bounded reader if changed.
|
||||
if(!disposed&&active!=null&&selectionClock.ElapsedMilliseconds>=1000)
|
||||
{selectionClock.Restart();scheduler.Post("selection",CaptureSelection);}
|
||||
if(!disposed)scheduler.Pump();
|
||||
if(!disposed){scheduler.Pump();RefreshChapterTimer();}
|
||||
if(!disposed&&ConnectionState=="connected"&&metricClock.ElapsedMilliseconds>=1000)
|
||||
{
|
||||
metricClock.Restart();scheduler.Post("selection",CaptureSelection);
|
||||
|
||||
@ -51,7 +51,7 @@ namespace PlotDirector.WordAddIn
|
||||
{
|
||||
throw new InvalidOperationException("Cannot measure native floating picture anchors in paragraph at " + read.PendingStart + " (COM 0x" + error.HResult.ToString("X8") + "). Existing mappings are retained.", error);
|
||||
}
|
||||
finally { Release(mode); Release(unit); Release(anchor); Release(shape); Release(shapes); Release(paragraph); }
|
||||
finally { ReleaseChapter(mode); ReleaseChapter(unit); ReleaseChapter(anchor); ReleaseChapter(shape); ReleaseChapter(shapes); ReleaseChapter(paragraph); }
|
||||
}
|
||||
|
||||
private void ReadChapterPositionSegment(LocalDocument doc, ChapterRead read)
|
||||
@ -79,7 +79,7 @@ namespace PlotDirector.WordAddIn
|
||||
throw new InvalidOperationException("Measured native text segments do not equal the paragraph text; no position was inferred.");
|
||||
CompleteChapterNativeParagraph(read, read.PendingPosition, read.PendingText, read.PendingEnd);
|
||||
}
|
||||
finally { Release(segment); }
|
||||
finally { ReleaseChapter(segment); }
|
||||
}
|
||||
|
||||
private void CompleteChapterNativeParagraph(ChapterRead read, ChapterParagraph evidence, string text, int end)
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using PlotDirector.Companion.Client;
|
||||
using Word=Microsoft.Office.Interop.Word;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
@ -11,7 +12,7 @@ namespace PlotDirector.WordAddIn
|
||||
private string serverBook = "", serverChapter = "", serverScene = "";
|
||||
private int serverBookId;
|
||||
private long serverRevision = -1;
|
||||
private long chapterLiveReads,chapterXmlReads;
|
||||
private long chapterLiveReads,chapterXmlReads,chapterComCalls,chapterParagraphVisits,chapterCommandPolls,chapterRcwReleases,chapterPlainBatches;
|
||||
private bool nativeChapterTextSupported,nativeChapterPositionsSupported,liveChapterTextSupported;
|
||||
private ChapterSyncProgress serverChapterProgress;
|
||||
|
||||
@ -106,20 +107,22 @@ namespace PlotDirector.WordAddIn
|
||||
}
|
||||
private sealed class ChapterRead
|
||||
{
|
||||
public readonly Stopwatch Total=Stopwatch.StartNew();public AdapterCommand Command;public int Phase,Seek,Steps,Start,End,Offset;public string Text="",Xml="",NextId="";public bool Begun; public int IdentityPosition; public readonly System.Text.StringBuilder Identities = new System.Text.StringBuilder(); public string IdentityFrames = ""; public bool NativeTextRequired,PhysicalPositions,LiveText;
|
||||
public readonly Stopwatch Total=Stopwatch.StartNew();public double ActiveMs,ComMs,ReleaseMs,QueueMs,QuietMs,OtherWorkMs,TimerHostMs;public long ComCalls,ParagraphVisits,ReleaseCalls,PlainBatches;public AdapterCommand Command;public int Phase,Seek,Steps,Start,End,Offset;public string Text="",Xml="",NextId="";public bool Begun; public int IdentityPosition; public readonly System.Text.StringBuilder Identities = new System.Text.StringBuilder(); public string IdentityFrames = ""; public bool NativeTextRequired,PhysicalPositions,LiveText;
|
||||
public readonly List<ChapterParagraph> NativePositions=new List<ChapterParagraph>();
|
||||
public int PendingStart,PendingEnd,ShapeIndex,SegmentPosition,SegmentAnchor;public string PendingText="";public ChapterParagraph PendingPosition;
|
||||
public readonly Dictionary<int,ChapterPictureAnchor> PendingAnchors=new Dictionary<int,ChapterPictureAnchor>();
|
||||
public readonly System.Text.StringBuilder SegmentText=new System.Text.StringBuilder(); public readonly System.Text.StringBuilder NativeText = new System.Text.StringBuilder();
|
||||
}
|
||||
private readonly Dictionary<Guid,ChapterRead> chapterReads=new Dictionary<Guid,ChapterRead>();
|
||||
private void CancelChapterRead(LocalDocument doc){chapterReads.Remove(doc.Session);scheduler.Cancel("chapter:"+doc.Session);}
|
||||
private void RefreshChapterTimer(){if(disposed)return;var interval=scheduler.HasRunnableChapterWork?5:25;if(timer.Interval!=interval)timer.Interval=interval;}
|
||||
private void CancelChapterRead(LocalDocument doc){chapterReads.Remove(doc.Session);scheduler.Cancel("chapter:"+doc.Session);RefreshChapterTimer();}
|
||||
private void StartChapterRead(LocalDocument doc,AdapterCommand command)
|
||||
{
|
||||
if(doc.Extraction!=null||doc.Maintenance!=null)throw new InvalidOperationException("Word already has an explicit read or maintenance request. Retry chapter validation afterwards.");
|
||||
if(chapterReads.Count>=2&&!chapterReads.ContainsKey(doc.Session))throw new InvalidOperationException("Two document chapter reads are already pending. Activate this manuscript and retry.");
|
||||
CancelChapterRead(doc);chapterReads[doc.Session]=new ChapterRead{Command=command,Seek=Math.Max(0,Math.Min(command.Chapter==null?0:command.Chapter.Start,doc.End-1))};
|
||||
if(!scheduler.Post("chapter:"+doc.Session,()=>ReadChapterStep(doc))){CancelChapterRead(doc);throw new InvalidOperationException("Word queue is busy; accepted checkpoints are preserved. Retry shortly.");}
|
||||
RefreshChapterTimer();
|
||||
}
|
||||
private string ReadLiveParagraphId(Word.Paragraph paragraph)
|
||||
{
|
||||
@ -128,6 +131,11 @@ namespace PlotDirector.WordAddIn
|
||||
if (id.Length == 0) throw new InvalidOperationException("Word did not provide a native paragraph ID. Review this chapter or use the explicit fallback.");
|
||||
return id;
|
||||
}
|
||||
private void ReleaseChapter(object value)
|
||||
{
|
||||
if(value==null)return;var started=Stopwatch.GetTimestamp();
|
||||
try{Release(value);}finally{if(executingChapterRead!=null){executingChapterRead.ReleaseCalls++;executingChapterRead.ReleaseMs+=(Stopwatch.GetTimestamp()-started)*1000d/Stopwatch.Frequency;}}
|
||||
}
|
||||
// Conservative accelerator: structural/picture chapters retain the qualified XML/position reader.
|
||||
// Collection RCWs are released before returning to the scheduler.
|
||||
private bool IsPlainChapter(Word.Range range)
|
||||
@ -145,7 +153,7 @@ namespace PlotDirector.WordAddIn
|
||||
return true;
|
||||
}
|
||||
catch(System.Runtime.InteropServices.COMException){return false;}
|
||||
finally{Release(inline);Release(endnotes);Release(footnotes);Release(revisions);Release(fields);Release(tables);}
|
||||
finally{ReleaseChapter(inline);ReleaseChapter(endnotes);ReleaseChapter(footnotes);ReleaseChapter(revisions);ReleaseChapter(fields);ReleaseChapter(tables);}
|
||||
}
|
||||
private void CheckChapterShape(LocalDocument doc,ChapterRead read)
|
||||
{
|
||||
@ -160,13 +168,47 @@ namespace PlotDirector.WordAddIn
|
||||
if(start>=read.Start&&start<read.End){read.Phase=12;return;}
|
||||
read.ShapeIndex++;
|
||||
}
|
||||
finally{Release(anchor);Release(shape);Release(shapes);}
|
||||
finally{ReleaseChapter(anchor);ReleaseChapter(shape);ReleaseChapter(shapes);}
|
||||
}
|
||||
// Keep collection/range RCWs only within this bounded STA step. No count or
|
||||
// full collection enumeration, and no cached native identity from an older session.
|
||||
private void ReadPlainChapterBatch(LocalDocument doc,ChapterRead read)
|
||||
{
|
||||
Word.Range remaining=null,paragraphRange=null;Word.Paragraphs collection=null;Word.Paragraph paragraph=null;
|
||||
var budget=Stopwatch.StartNew();
|
||||
try
|
||||
{
|
||||
read.PlainBatches++;remaining=Com(()=>doc.Document.Range(read.IdentityPosition,read.End));collection=Com(()=>remaining.Paragraphs);
|
||||
for(var index=1;ChapterIdentityRead.CanContinue(index-1,budget.Elapsed.TotalMilliseconds);index++)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(doc.Revision!=read.Command.Revision||closing.Contains(doc.Document))throw new InvalidOperationException("Word changed during native paragraph verification.");
|
||||
paragraph=Com(()=>collection[index]);paragraphRange=Com(()=>paragraph.Range);
|
||||
var start=Com(()=>paragraphRange.Start);var end=Com(()=>paragraphRange.End);
|
||||
read.IdentityPosition=ChapterIdentityRead.Append(read.Identities,read.IdentityPosition,read.End,start,end,ReadLiveParagraphId(paragraph),(int)Com(()=>paragraph.OutlineLevel));
|
||||
read.ParagraphVisits++;
|
||||
if(end==read.End){read.IdentityFrames=read.Identities.ToString();read.Phase=4;break;}
|
||||
}
|
||||
finally{ReleaseChapter(paragraphRange);paragraphRange=null;ReleaseChapter(paragraph);paragraph=null;}
|
||||
}
|
||||
if(!Com(()=>doc.Document.Saved)||Com(()=>application.BackgroundSavingStatus)!=0)throw new InvalidOperationException("Save Word before accepting native paragraph evidence.");
|
||||
}
|
||||
finally{ReleaseChapter(paragraphRange);ReleaseChapter(paragraph);ReleaseChapter(collection);ReleaseChapter(remaining);}
|
||||
}
|
||||
private ChapterRead executingChapterRead;
|
||||
private void CompleteChapterReadMetrics(ChapterRead read,double finalStepMs)
|
||||
{
|
||||
Metric("chapter-read-active",read.ActiveMs+finalStepMs);Metric("chapter-read-rcw-release",read.ReleaseMs);Metric("chapter-read-com",read.ComMs);
|
||||
Metric("chapter-read-queue",read.QueueMs);Metric("chapter-read-author-wait",read.QuietMs);
|
||||
Metric("chapter-read-other-work",read.OtherWorkMs);Metric("chapter-read-timer-host-wait",read.TimerHostMs);
|
||||
chapterComCalls+=read.ComCalls;chapterParagraphVisits+=read.ParagraphVisits;chapterRcwReleases+=read.ReleaseCalls;chapterPlainBatches+=read.PlainBatches;
|
||||
}
|
||||
private void ReadChapterStep(LocalDocument doc)
|
||||
{
|
||||
ChapterRead read;if(!chapterReads.TryGetValue(doc.Session,out read))return;
|
||||
if(!documents.ContainsKey(doc.Document)||doc.Revision!=read.Command.Revision||closing.Contains(doc.Document)||ConnectionState!="connected"){CancelChapterRead(doc);return;}
|
||||
var watch=Stopwatch.StartNew();Word.Range point=null,heading=null,range=null;Word.Paragraphs paragraphs=null;Word.Paragraph paragraph=null;
|
||||
var watch=Stopwatch.StartNew();executingChapterRead=read;Word.Range point=null,heading=null,range=null;Word.Paragraphs paragraphs=null;Word.Paragraph paragraph=null;
|
||||
try
|
||||
{
|
||||
if((read.Phase<4||read.Phase==6||read.Phase==7||read.Phase==9||read.Phase==10||read.Phase==11||read.Phase==12)&&(!Com(()=>doc.Document.Saved)||Com(()=>application.BackgroundSavingStatus)!=0))throw new InvalidOperationException("Save Word and wait for background saving before validating chapters.");
|
||||
@ -215,7 +257,8 @@ namespace PlotDirector.WordAddIn
|
||||
if(read.NativeTextRequired&&!nativeChapterTextSupported)throw new InvalidOperationException("Update the Companion agent to verify picture paragraphs. Existing mappings are retained.");
|
||||
read.IdentityPosition=read.Start;read.Phase=7;
|
||||
}else if(read.Phase==7){
|
||||
// One paragraph per bounded step; the scheduler may batch short steps. COM stays on the STA.
|
||||
if(read.LiveText){ReadPlainChapterBatch(doc,read);return;}
|
||||
// Structural/native-position extraction retains its qualified one-paragraph step.
|
||||
point=Com(()=>doc.Document.Range(read.IdentityPosition,read.IdentityPosition));
|
||||
paragraphs=Com(()=>point.Paragraphs);paragraph=Com(()=>paragraphs[1]);range=Com(()=>paragraph.Range);
|
||||
var start=Com(()=>range.Start);var end=Com(()=>range.End);
|
||||
@ -223,7 +266,7 @@ namespace PlotDirector.WordAddIn
|
||||
throw new InvalidOperationException("Live Word paragraph boundaries do not match the chapter.");
|
||||
if(read.PhysicalPositions)
|
||||
{
|
||||
var nativeText=Com(()=>range.Text,"chapter-native-paragraph-text")??"";
|
||||
read.ParagraphVisits++;var nativeText=Com(()=>range.Text,"chapter-native-paragraph-text")??"";
|
||||
var evidence=new ChapterParagraph{NativeId=ReadLiveParagraphId(paragraph),Length=nativeText.Length,WordLength=end-start,Outline=(int)Com(()=>paragraph.OutlineLevel)};
|
||||
if(nativeText.Length<=0||nativeText.Length>end-start)throw new InvalidOperationException("Unsupported native paragraph text at Word position "+start+": span "+(end-start)+", text units "+nativeText.Length+".");
|
||||
if(nativeText.Length==end-start)CompleteChapterNativeParagraph(read,evidence,nativeText,end);
|
||||
@ -236,7 +279,7 @@ namespace PlotDirector.WordAddIn
|
||||
if(nativeText.Length!=end-start)throw new InvalidOperationException("Native paragraph text and Word span disagree; picture positions were not guessed.");
|
||||
read.NativeText.Append(nativeText);
|
||||
}
|
||||
read.Identities.Append(ReadLiveParagraphId(paragraph));
|
||||
read.ParagraphVisits++;read.Identities.Append(ReadLiveParagraphId(paragraph));
|
||||
read.Identities.Append((end-start).ToString("X8",System.Globalization.CultureInfo.InvariantCulture));
|
||||
if(read.LiveText)read.Identities.Append(((int)Com(()=>paragraph.OutlineLevel)).ToString("X8",System.Globalization.CultureInfo.InvariantCulture));
|
||||
read.IdentityPosition=end;
|
||||
@ -249,12 +292,12 @@ namespace PlotDirector.WordAddIn
|
||||
var source=read.Phase==4?read.Text:read.Phase==5?read.Xml:read.IdentityFrames;
|
||||
if(read.Offset<source.Length){var count=Math.Min(2048,source.Length-read.Offset);if(!link.TryPost(new Message{Kind="chapter-chunk",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,Action=read.Phase==4?"text":read.Phase==5?"xml":read.LiveText?"live-text":read.PhysicalPositions?"positions":read.NativeTextRequired?"ids-exact":"ids",Start=read.Offset,OperationMessage=source.Substring(read.Offset,count)}))return;read.Offset+=count;}
|
||||
else if(read.Phase<8){read.Phase=read.Phase==4&&!read.LiveText?5:8;read.Offset=0;}
|
||||
else{if(!link.TryPost(new Message{Kind="chapter-end",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id}))return;Metric(read.LiveText?"chapter-live-text-complete":"chapter-xml-complete",read.Total.Elapsed.TotalMilliseconds);if(read.LiveText)chapterLiveReads++;else chapterXmlReads++;CancelChapterRead(doc);return;}
|
||||
else{if(!link.TryPost(new Message{Kind="chapter-end",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id}))return;CompleteChapterReadMetrics(read,watch.Elapsed.TotalMilliseconds);Metric(read.LiveText?"chapter-live-text-complete":"chapter-xml-complete",read.Total.Elapsed.TotalMilliseconds);if(read.LiveText)chapterLiveReads++;else chapterXmlReads++;CancelChapterRead(doc);return;}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(Exception error)when(error is System.Runtime.InteropServices.COMException||error is InvalidOperationException||error is ArgumentException||error is NullReferenceException){CancelChapterRead(doc);Reply(read.Command,"Chapter validation stopped: "+error.Message);lastResult="Chapter validation stopped: "+error.Message;}
|
||||
finally{Release(range);Release(paragraph);Release(paragraphs);Release(heading);Release(point);Metric("chapter-ui-step",watch.Elapsed.TotalMilliseconds);if(chapterReads.ContainsKey(doc.Session)&&!scheduler.Post("chapter:"+doc.Session,()=>ReadChapterStep(doc))){CancelChapterRead(doc);Reply(read.Command,"Chapter validation stopped: Word queue is busy. Accepted checkpoints are preserved.");}}
|
||||
finally{ReleaseChapter(range);ReleaseChapter(paragraph);ReleaseChapter(paragraphs);ReleaseChapter(heading);ReleaseChapter(point);read.ActiveMs+=watch.Elapsed.TotalMilliseconds;executingChapterRead=null;Metric("chapter-ui-step",watch.Elapsed.TotalMilliseconds);if(chapterReads.ContainsKey(doc.Session)&&!scheduler.Post("chapter:"+doc.Session,()=>ReadChapterStep(doc))){CancelChapterRead(doc);Reply(read.Command,"Chapter validation stopped: Word queue is busy. Accepted checkpoints are preserved.");}}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"version": "1.0.0.31",
|
||||
"msiVersion": "1.0.31",
|
||||
"productCode": "{9E8E1907-7842-4001-99F4-EE1BE9FD35FA}",
|
||||
"version": "1.0.0.32",
|
||||
"msiVersion": "1.0.32",
|
||||
"productCode": "{F1D84AC4-AD05-444B-8D98-FA0B39ACCA50}",
|
||||
"upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}",
|
||||
"atlasBaseline": "9fed339879887964d526cff00772ffc4dc522c5d",
|
||||
"baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user