From 0075bb5299a9aab46cceb7d587d6e872891fac22 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Thu, 5 Nov 2026 14:18:06 +0000 Subject: [PATCH] Integrate native workspace status, saved Context and Intent, and safe import preview --- .../2026-11-05-phase35-integration.md | 83 ++++ .../2026-11-05-phase35/application.txt | 408 ++++++++++++++++++ .../Evidence/2026-11-05-phase35/browser.txt | 5 + .../Evidence/2026-11-05-phase35/native.txt | 183 ++++++++ .../2026-11-05-phase35/powershell.txt | 8 + .../2026-11-05-phase35/vsto-syntax.txt | 8 + .../Evidence/2026-11-05-phase35/workflow.txt | 1 + .../Agent/CloudGateway.cs | 66 ++- .../Agent/DocumentWorkspaceWork.cs | 78 ++++ .../Agent/PipeHost.cs | 2 +- PlotDirector.NativeCompanion/Agent/Program.cs | 2 +- .../Agent/SessionManager.cs | 16 +- .../Client/AgentLink.cs | 2 +- .../Client/ConnectionPresentation.cs | 14 + .../Client/DocumentBinding.cs | 33 ++ .../DeveloperVersion.props | 2 +- .../Protocol/Messages.cs | 6 + .../Protocol/WorkflowContracts.cs | 51 +++ PlotDirector.NativeCompanion/README.md | 4 + .../Tests/ChapterAiTests.cs | 1 + PlotDirector.NativeCompanion/Tests/Program.cs | 1 + .../Tests/WorkflowTests.cs | 60 +++ .../Vsto/AnalysisWindow.cs | 81 +++- .../Vsto/NativeRibbon.cs | 9 +- .../Vsto/Properties/AssemblyInfo.cs | 4 +- PlotDirector.NativeCompanion/Vsto/Ribbon.xml | 4 +- .../Vsto/WordAdapter.cs | 61 ++- .../WindowsValidation/Phase3-AI.md | 8 +- .../WindowsValidation/Phase35-Integration.md | 27 ++ .../WindowsValidation/README.md | 2 + .../Update-WordCompanion.ps1 | 1 + .../Browser/word-companion-regressions.cjs | 9 + PlotLine.Tests/NativeCompanionHttpTests.cs | 8 + PlotLine.Tests/NativeWorkflowTests.cs | 51 +++ PlotLine.Tests/Program.cs | 2 + .../NativeCompanionWorkflowController.cs | 58 +++ PlotLine/Controllers/WritingController.cs | 8 +- .../NativeCompanion/DesktopPairing.cs | 2 +- .../NativeCompanion/NativeImportPreview.cs | 30 ++ PlotLine/Services/WordCompanionService.cs | 11 +- PlotLine/Views/Writing/Context.cshtml | 9 +- PlotLine/Views/Writing/Intent.cshtml | 9 +- PlotLine/wwwroot/js/writing-follow.js | 9 +- 43 files changed, 1360 insertions(+), 77 deletions(-) create mode 100644 Docs/WordCompanion/2026-11-05-phase35-integration.md create mode 100644 Docs/WordCompanion/Evidence/2026-11-05-phase35/application.txt create mode 100644 Docs/WordCompanion/Evidence/2026-11-05-phase35/browser.txt create mode 100644 Docs/WordCompanion/Evidence/2026-11-05-phase35/native.txt create mode 100644 Docs/WordCompanion/Evidence/2026-11-05-phase35/powershell.txt create mode 100644 Docs/WordCompanion/Evidence/2026-11-05-phase35/vsto-syntax.txt create mode 100644 Docs/WordCompanion/Evidence/2026-11-05-phase35/workflow.txt create mode 100644 PlotDirector.NativeCompanion/Agent/DocumentWorkspaceWork.cs create mode 100644 PlotDirector.NativeCompanion/Client/ConnectionPresentation.cs create mode 100644 PlotDirector.NativeCompanion/Client/DocumentBinding.cs create mode 100644 PlotDirector.NativeCompanion/Protocol/WorkflowContracts.cs create mode 100644 PlotDirector.NativeCompanion/Tests/WorkflowTests.cs create mode 100644 PlotDirector.NativeCompanion/WindowsValidation/Phase35-Integration.md create mode 100644 PlotLine.Tests/NativeWorkflowTests.cs create mode 100644 PlotLine/Controllers/NativeCompanionWorkflowController.cs create mode 100644 PlotLine/Services/NativeCompanion/NativeImportPreview.cs diff --git a/Docs/WordCompanion/2026-11-05-phase35-integration.md b/Docs/WordCompanion/2026-11-05-phase35-integration.md new file mode 100644 index 00000000..73f601c1 --- /dev/null +++ b/Docs/WordCompanion/2026-11-05-phase35-integration.md @@ -0,0 +1,83 @@ +# Native Word Companion Phase 3.5 integration + +## Outcome and boundaries + +Developer build **1.0.0.6** extends Phase 3 on the same shared branch. Existing authenticated chapter AI, bounded extraction, local detection, named pipes and separate .NET 10 agent are retained. There is no replacement architecture, new UI framework, schema migration, native live SignalR protocol or manuscript rewriting. + +The useful integrated path is: local detection → explicit chapter AI → source-labelled review → bounded cross-page chapter/scene selection → authenticated **read-only import preview**. Native commit is deliberately unavailable. This is the largest safe import portion delivered under the assignment's fallback; it must not be described as completed native importing. + +## Architecture and ownership + +```mermaid +flowchart LR + W[Word STA scheduler and ribbon] <-->|value-only bounded IPC| A[Per-user .NET 10 agent] + W --> R[Modeless review: per-document book binding] + A -->|bearer HTTPS| N[Existing native API plus workflow endpoints] + N --> P[Existing book ownership and subscription checks] + N --> C[Existing Context and chapter workflow services] + N --> I[Existing manuscript eligibility and validation] + N --> AI[Existing chapter AI service] + A -->|explicit open only| B[Pinned saved Context / Intent or book browser page] + L[Existing Office.js SignalR connection] --> V[Ordinary live browser Context / Intent] +``` + +No HTTP, credentials, parsing, database operations or AI execute in VSTO. New saved-data/preview responses use optional `workspace-review-v1` capability negotiation. Existing core IPC and `chapter-ai-v2` remain compatible. Existing Office.js routes, hub methods, event contracts and ordinary multi-screen live following are retained. + +## Experience audit and repairs + +| Finding | Repair / actual resulting behaviour | +|---|---| +| A previous successful sign-in string could look current after outages | Shared `ConnectionHealth` / `ConnectionPresentation`; IPC failure overrides cached server/auth/book state, server checks have a freshness limit, 401 rotates the authentication scope and clears access. | +| One book combo was not an authorised per-document context | `DocumentBinding` and `DocumentWorkspaceWork` bind exact session/revision/book/authentication/binding IDs. Switching clears prior saved data immediately; delayed replies are discarded. | +| Native Context / Intent had no useful saved-data integration | Read-only summaries from existing scene Context and chapter workflow/goals, with source labels, book/chapter/scene title and explicit missing-data messages. Foreign saved markers are rejected. | +| Opening a browser URL could start following the legacy latest Word connection | Explicit `pinned=true` snapshot mode suppresses live subscription, global story-position listeners and window registration for these views. Manual scene/tab navigation remains; ordinary live views are unchanged. | +| Review and import were disconnected | Checked rows survive page changes and document switching (80-row bound), target is authorised, metadata-only upload requires confirmation, existing validation/eligibility reports conflicts. No commit is implied. | +| Duplicate Analyse / Synchronise alias controls confused local detection with sync | Removed the duplicate ribbon action. Detect structure remains local; explicit chapter AI is separately labelled. | +| Ribbon Cancel could be active without work; save could leave an old preview loading | Cancel enabled only for active work; client cancellation invalidates request ID immediately, agent generation suppresses delayed completion. Save never waits or cancels Word's save. | +| Status text could be too wide; large selections lost across pages | Ribbon status split across two labels; modeless wrapping action layout, long book dropdown, hierarchical 40-row pages, full inspector, bounded selection shared across tabs. DPI/layout still requires Word qualification. | + +### Connection semantics + +- `Word loaded` is local host state; connected means successful local IPC, never server or AI health. +- `/api/native-companion/connection` is bearer-authenticated and verifies current entitlement/configuration. It does **not** submit a paid AI probe. +- Server/auth verification is considered current for 90 seconds. Status reads may initiate at most one health check per two minutes; an explicit Check connection initiates a check immediately. The deliberate intervening `unverified` state avoids a stale success claim without frequent network polling. +- Cached grants/books remain distinguishable from live verification. Known four-hour expiry and server 401 invalidate authentication scope; book data must be reselected/revalidated after sign-out/restart. +- AI `configured`, `not-configured`, `not-entitled`, `unknown`, `last-request-succeeded` and `request-failed` describe evidence, not a guarantee of provider availability. Local analysis remains available offline. +- Saved-data requests have 15-second timeouts, bounded 1MiB responses, four concurrent workspace fetches, 350ms position coalescing and replacement suppression. Preview has at most four in-flight requests, no automatic retries or commits. Cancelled read-only HTTP may finish within its timeout; its result cannot restore UI state. +- No diagnostics contain prose or credentials. Health explanatory text is available in the protocol; native status displays the distinct states and operation-specific result/error text. + +### Document lifecycle + +The existing persistent manuscript GUID and live session remain distinct. Word-derived positional scene/chapter markers are verified against the selected book through `GetBookStructureAsync`, not trusted as arbitrary database IDs. Book selection remains per open document; account/agent change invalidates it. Observed revision changes reset the saved binding and reauthorise the retained book. Document close/revision clearing releases agent workspace state. Existing limited same-length-edit detection remains: review results describe a captured snapshot, so re-detect after editing. + +## Import: what works and what does not + +`NativeImportPreview.Build` checks bounded current identity/selection, nonblank bounded titles, positive/nonoverlapping ranges, unique boundaries, parent chapters and at least one selected scene per selected chapter. It orders by Word positions, never invents placeholder scenes, and invokes the same `WordCompanionService.ValidImportStructure` validator used by the existing importer. The controller checks authenticated ownership and Import entitlement before the existing `AnalyseManuscriptAsync` eligibility operation. Linked manuscript counts, existing planned chapters/scenes and refusal reasons are returned. Metadata contains titles/positions and identity only; prose is not uploaded, and word counts are explicitly unknown/zero. + +The old `WordCompanionService.ImportManuscriptAsync` and SQL import (migration 219) also own document binding/structure and planned-content decisions; its existing linked/planned checks precede its transaction. Canonical onboarding additionally owns prose sources, chapter AI review, resumable marker build and save acknowledgement. Calling that write path directly from the native preview would not provide safe idempotent prose/binding/recovery semantics. No unsafe direct database path, automatic replacement or new partial-import retry mechanism was added. + +The UI always reports **Created: 0 / Replaced: 0**, `CommitAvailable=false`. Continue in PlotDirector opens the authorised book in the existing application. **Selections are not transferred**. Existing web importing remains the committing workflow, with its existing author confirmation. Repeated native previews are read-only and cannot create duplicates; they do not claim to solve transaction/idempotency guarantees for a future native commit. Full commit is a separate remaining capability, not a hidden success state. + +## Context and Intent + +Native tabs distinguish saved information from local structural/AI suggestions. Context uses saved scene summary, then chapter/book summary where applicable. Intent uses saved scene-purpose notes and chapter goal/emotional-goal/reader-takeaway/must-include fields. Neither generates AI information nor saves changes. Book-level absence is useful explicit guidance, not a fabricated writing objective. + +Full browser views reuse existing rendering and access validation. Native links pin project/book/verified chapter/scene and opt out of legacy latest-connection follow. Multiple independently opened pinned views keep their scopes. This is **saved snapshot integration**, not native live multi-screen SignalR following. Existing Office.js live Context/Intent multi-screen behaviour is preserved for its ordinary views. A future native live protocol still requires session-aware routing and explicit follow policy. + +## Main evidence references + +- `Protocol/WorkflowContracts.cs`, `Protocol/Messages.cs`: optional capability and bounded value contracts. +- `Agent/CloudGateway.cs`: auth expiry, HTTP verification, status, scoped browser opening; `DocumentWorkspaceWork.cs`: per-session saved scope, coalescing and preview suppression; `SessionManager.cs`: current snapshot/identity checks and lifecycle. +- `Client/DocumentBinding.cs`, `ConnectionPresentation.cs`: shared presentation and stale-response guards. +- `Vsto/WordAdapter.cs`: UI-thread value exchange, exact-document commands, save/cancel safety; `AnalysisWindow.cs`, `NativeRibbon.cs`, `Ribbon.xml`: native experience. +- `PlotLine/Controllers/NativeCompanionWorkflowController.cs`: authenticated connection/workspace/preview; `Services/NativeCompanion/NativeImportPreview.cs`; existing `Services/WordCompanionService.cs` shared validation/eligibility. +- `WritingController.cs`, Context/Intent Razor views, `wwwroot/js/writing-follow.js`: pinned mode with preserved live mode. +- Existing investigation: `Docs/Investigations/2026-11-04-word-companion-investigation.md`; previous report: `2026-11-05-phase3-ai-integration.md`. + +## Verification and remaining qualification + +Evidence and exact final checks/deployment outcome are recorded alongside this report under `Evidence/2026-11-05-phase35/`. Automated checks exercise real controller/HTTP routes with synthetic authenticated principals/provider and fail-on-write repositories, agent lifecycle/state, browser response races, package tamper refusal and VSTO source syntax. They do not claim a live author's database import, provider availability or real Office execution. + +There are no new database migrations or configuration secrets/settings. The server needs the existing desktop pairing/auth infrastructure, subscription entitlement and configured existing AI provider; the Phase 3 migration 230 prerequisite remains. Preparing Windows packages does not alter the working laptop installation. + +Windows COM semantics, compilation against installed Office, signed manifests, installation, visual DPI/layout and actual typing/scroll/save responsiveness remain unverified on Atlas. Native import commit, native live SignalR following, full prose sync and a complete edit journal remain out of scope. [Windows steps and tonight's checklist](../../PlotDirector.NativeCompanion/WindowsValidation/Phase35-Integration.md) use the existing Update/Install scripts and version 1.0.0.6. diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase35/application.txt b/Docs/WordCompanion/Evidence/2026-11-05-phase35/application.txt new file mode 100644 index 00000000..43c2fe97 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase35/application.txt @@ -0,0 +1,408 @@ +PASS Native saved workspace and established import eligibility remain scoped and read-only +PASS Native companion authentication, canonical AI mapping and isolated chapter retry +PASS Solver never discards a corroborated concern or exhausts navigation before verification +PASS Solver result evidence covers all reachable diagnoses without changing Stage 1 semantics +PASS Solver result copy follows actual answers, intention, variants and revision +PASS Solver workspace CTAs resolve authorised project/character context and real routes +PASS Stage 1 preserves all 60 strict conversations, corroboration, intent, reachability and adoption +PASS Stage 1 evidence gates, required follow-ups, bounded multi-select and neutral choices are enforced +PASS Neutral endpoints require explicit valid terminal declarations +PASS Neutral reassurance follows selected concerns without evidence and survives revision +PASS Scene navigation does not invent purpose evidence; genuine D05 witnesses survive +PASS D50 requires actual series evidence and preserves D50/D51 witnesses +PASS Curated V2 preserves 60 literal paths and enforces eight explicit Development review exceptions +PASS Curated V2 exhausts real-engine states and preserves revision/multi-select behaviour +PASS Curated V2 passes normal validation and invalid publication stays guarded +PASS Payoff covers all 52 diagnoses with seven archetypes and semantic uncertainty ordering without graph changes +PASS Development review observes every acceptance prefix without changing signals, results or graph; access and durable capture stay isolated +PASS All permanent writing problems have distinct editorial content, intent, metadata, links and real images +PASS Clean solver completion preserves private evidence and permanent indexable URLs +PASS Writing Solver anonymous state is protected, expires and rejects stale versions +PASS Writing Solver scoring, multi-select, revision, fallback and graph routes +PASS Writing Solver import rejects invalid graphs and editorial identities +PASS Project export and restore access gates enforce author and ownership boundaries +PASS Retired checklist bookmarks redirect without report access +PASS Ribbon operation identity and semantic icons stay consistent +PASS Maps Story projects canonical hierarchy, sequence, journeys and evidence without changing geography +PASS Maps Story scales to 500 scenes and 5,000 appearances +PASS Maps Story enforces access and uses bounded repository batches +PASS Maps appearance validates colours, normalized raster images and portable backups +PASS Maps reference assets enforce access +PASS Maps validate rough geometry, relationships, Location intent and access boundaries +PASS Subscription entitlement evaluates trials, paid access, overrides and real plan limits +PASS Subscription overrides control access and dashboard presentation without trial contradictions +PASS Subscription enforcement is concurrent, audited and admin-authorised +PASS Plot Health stays scene-based with 12,000 contributions +PASS Plot Health preserves Discovery planning and boundary contradictions +PASS Plot Health separates stored status and meaningful-progress clocks +PASS Plot Health explains question, payoff, closure and boundary evidence +PASS Plot Health evaluates explicit targets and scoped line rollups +PASS Plot Health respects scenario coverage and ordered chapter identities +PASS Plot Lines Focus and Weave preserve gaps and shared-scene identity +PASS Plot Lines thread, enrichment and Timeline inspector contracts hold +PASS Plot Lines composition remains bounded with a large generated weave +PASS Exception review uses evidence, identity, consequence and directional conflicts +PASS Exception assessment preserves author decisions and scene history +PASS Character card widths reflect displayed text without changing character data +PASS Relationships workspace large cast, temporal states and canonical edits +PASS Scene relationship proposals preserve direction and validate acceptance +PASS Location and asset merges require confirmation and distinct records +PASS Location persisted analysis preserves contextual bedrooms and setting provenance +PASS Location consequence outranks capped recurrence +PASS Location scene significance is attributed only to actual settings +PASS Location significance preserves hierarchy and independent uncertainty +PASS Character profile age uses canonical reference chronology +PASS Character detail and date-only save retain canonical DOB +PASS Story Point presence, previous appearances and age cross book boundaries +PASS Story Point knowledge stops at selected narrative position +PASS Story Point relationships and independent asset state are historical +PASS Story Point threads and continuity warnings respect future evidence +PASS Story Point ownership, AJAX and bounded batch loading require no AI +PASS Story Point narrative tie breakers match canonical order +PASS Malformed confidence 0. is repaired to 0.0 +PASS Markdown fences are stripped +PASS Unescaped backslash in evidence is repaired +PASS Truncated JSON is rejected +PASS Repaired JSON deserialises into SceneIntelligenceScene +PASS Chapter Structure confidence 0. repairs and deserialises +PASS Chapter Structure confidence 0. 8 repairs and deserialises +PASS Chapter Structure confidence 7 .5 repairs when unambiguous +PASS JSON repair leaves decimal-looking prose unchanged +PASS Chapter Structure semantic validation still rejects out-of-range repaired confidence +PASS Structural scene detection parser failure uses friendly diagnostics and retry +PASS Chapter Structure boundary normaliser repairs gaps and overlaps +PASS Chapter Structure boundary normaliser preserves valid coverage +PASS Chapter Structure boundary normaliser handles terminal ghost paragraph +PASS Chapter Structure boundary normaliser discards multiple terminal ghost paragraphs +PASS Chapter Structure boundary normaliser replays full book terminal empty failure +PASS Chapter Structure boundary normaliser keeps meaningful end overflow repair +PASS Chapter Structure boundary normaliser preserves genuine inverted ranges for validation +PASS Structural Word mapping uses paragraph map as authoritative text +PASS Structural Word mapping includes filtered Word paragraphs in source coverage +PASS Structural Word mapping fails precisely when map metadata is incomplete +PASS Structural Word mapping keeps trailing empty normalisation mapped +PASS Shared parser reports raw chapter output on unrecoverable JSON +PASS Character filtering rejects generic groups +PASS Character filtering preserves titled names +PASS Location filtering rejects merged phrases +PASS Location filtering preserves story locations +PASS Location canonical keys merge trivial variants +PASS Location contextual names use POV and structural setting +PASS Location canonical keys merge punctuation and safe plurals +PASS Location candidate consolidation handles generic review variants +PASS Location candidate identity is parent-aware for generic sub-locations +PASS Locations page uses hierarchical sort order +PASS Location review UX supports large candidate sets +PASS Story Intelligence auto resolves exact known locations before review +PASS Story Intelligence location review uses single identity decision +PASS Asset filtering rejects generic objects +PASS Asset filtering preserves story assets +PASS Asset canonical keys merge trivial variants +PASS Asset canonical keys merge contextual vehicle variants +PASS Asset canonical keys keep unrelated owned cars distinct +PASS Asset candidate keys attach unique unowned variants +PASS Asset filtering rejects relationship facts +PASS Asset contextual names resolve POV ownership +PASS Asset structural phrases trim neighbouring nouns +PASS Asset significance is generic and not fixture-specific +PASS Story Intelligence asset review applies current identity rules +PASS Relationship review requires pair evidence and distinguishes social types +PASS Relationship signals map to broad lookup types +PASS Relationship signals infer friendship without romance +PASS Relationship events preserve chronological story order +PASS Relationship progression keeps chronological state +PASS Relationship observations do not create event spam +PASS Relationship review orders by first story appearance +PASS Relationship evidence priority preserves explicit semantics +PASS Relationship evidence handles retained hostile and incidental examples +PASS Knowledge signals map to existing knowledge states +PASS Knowledge recipient resolves narrator through POV +PASS Knowledge identity reveal preserves subjective timing +PASS Knowledge duplicate statements share canonical keys +PASS Knowledge suspicion and certainty remain distinct +PASS Illustration prompt builder separates spec and prompt +PASS Illustration prompt builder uses realistic image direction +PASS Illustration specification validation catches missing typed fields +PASS Illustration category validation rejects unknown values +PASS Illustration status transitions protect approval flow +PASS Illustration status transitions support archive flow +PASS Illustration metadata flags fallback location labels +PASS Illustration location matching rejects vehicle living room reuse +PASS Illustration automatic generation policy blocks vague fallbacks +PASS Story Memory import image generation defaults are safe +PASS Illustration storage codes are normalised safely +PASS Illustration starter batch has required category counts +PASS Illustration starter generation plan skips successful items +PASS Story Intelligence visualisation archive is preserved +PASS Story Intelligence visualisation runtime is removed +PASS Story Intelligence does not retry exhausted billing quota +PASS Illustration bulk retry result reports counts +PASS Illustration bulk retry skips blocking duplicate stable codes +PASS Illustration provider reports missing image model +PASS Illustration provider omits GPT image response format +PASS Illustration matching rejects adult masculine unknown art for Beth +PASS Illustration matching treats Mrs title as hard feminine evidence +PASS Illustration matching infers mother and aunt as mature feminine +PASS Illustration matching rejects duplicate named portrait allocation +PASS Illustration semantic types prevent bathroom office and ambulance car mismatches +PASS Illustration demand archetypes stay broad and use active template +PASS Story Intelligence evidence extraction prevents observed attribute leakage +PASS Story Intelligence scene call uses strict structured output +PASS Story Intelligence scene schema constrains confidence numbers +PASS Story Intelligence scene schema constrains evidence strings +PASS Story Intelligence temporal resolves chapter anchor and afternoon +PASS Story Intelligence temporal rolls over after midnight +PASS Story Intelligence temporal resolves following morning +PASS Story Intelligence temporal resolves exact day offsets +PASS Story Intelligence temporal resolves following weekday +PASS Story Intelligence temporal resolves evening clock time +PASS Story Intelligence temporal rejects unanchored clock time +PASS Story Intelligence temporal preserves yearless calendar date clues +PASS Story Intelligence temporal resolves yearless calendar dates from context +PASS Story Intelligence temporal inherits previous morning when extraction is empty +PASS Story Intelligence temporal inherits previous evening when extraction is empty +PASS Story Intelligence temporal inherits previous night when extraction is empty +PASS Story Intelligence temporal inherits after midnight advancement +PASS Story Intelligence temporal inherits chapter anchor when extraction is empty +PASS Story Intelligence temporal stays unknown without context or extraction +PASS Story Intelligence temporal explicit date overrides previous context +PASS Story Intelligence temporal preserves vague few days +PASS Core import applies structural chronology to canonical scenes +PASS Story Intelligence temporal importer preserves manual chronology +PASS Story Intelligence temporal materialisation saves canonical chronology +PASS Story Intelligence temporal malformed values are discarded +PASS Story Calendar useful months and sparse navigation +PASS Story Calendar places dated scenes on Monday-first month grid +PASS Story Calendar separates unplaced scenes without guessing +PASS Story Calendar book filter and all books scope work +PASS Story Calendar month navigation uses story dates across years +PASS Story Calendar month dropdown follows displayed month +PASS Story Calendar handles no dated scenes +PASS Story Calendar day details endpoint returns partial +PASS Story Calendar day details endpoint respects book filter +PASS Story Calendar day details endpoint handles empty story date +PASS Story Calendar day details endpoint rejects invalid project +PASS Story Calendar index returns surface partial for AJAX +PASS Story Calendar day selection uses progressive AJAX hooks +PASS Story Intelligence structured metric values validate and import +PASS Story Intelligence structured schema covers complete response model +PASS Story Intelligence structured schema remains fixture agnostic +PASS Illustration assignment repair enforces explicit evidence groups and strict subtypes +PASS Lean import removes replay links while retaining progress +PASS Story Intelligence progress does not prematurely report safe close +PASS Structural import creates scenes before Word sync +PASS Structural import creates first scene without placeholder +PASS Structural import persists paragraph mapping and source text +PASS Structural import persists canonical scene source text +PASS Structural import adds summaries without extra scene AI calls +PASS Core import scan stage defers scenes and characters +PASS Core import basic location detector is conservative +PASS Core import basic location detector consolidates and skips existing matches +PASS Core import basic location detector supports pending parent candidates +PASS Core import character discovery protects accepted locations +PASS Core import gates characters behind basic location review +PASS Core import hides exact existing character names from review +PASS Core import hides exact existing character aliases from review +PASS Core import keeps suspected unknown aliases in review +PASS Core import keeps ambiguous existing character matches in review +PASS Core import keeps new characters in review +PASS Core import auto resolved character evidence is preserved +PASS Core import character evidence is candidate specific +PASS Core import deterministically maps known characters +PASS Core import wizard orders scenes before characters +PASS Core import remaps characters after review +PASS Scan review separates known matches from unresolved names +PASS Story Intelligence uses persisted scene source after restart +PASS Story Intelligence canonical mode bypasses duplicate boundary analysis +PASS Story Intelligence progress uses canonical scene summaries +PASS Story Intelligence downstream imports prefer canonical SceneIDs +PASS Story Intelligence scene prompt no longer asks for duplicate factual summary +PASS Story Intelligence review uses canonical structural summaries and counts +PASS Story Intelligence review centre completion is category scoped +PASS Word sync requires save acknowledgement +PASS Word sync retry resumes existing structure +PASS Story Intelligence enriches existing structural scenes +PASS Core import scene titles ride existing structural AI call +PASS Core import scene title preference is review scoped +PASS Core import scene title preference moved to Detect Scenes +PASS Core import Review Chapters is compact and chapter only +PASS Core import Detect Scenes is compact and owns title option +PASS Book context is canonical import metadata +PASS Names defaults from selected book context +PASS Story Intelligence starts from core import complete +PASS Generated scene titles persist with provenance +PASS Scene title display keeps scene numbers visible +PASS Manuscript text statistics handles pure prose +PASS Manuscript text statistics handles pure dialogue +PASS Manuscript text statistics splits narrative before dialogue +PASS Manuscript text statistics splits dialogue before narrative +PASS Manuscript text statistics handles multiple dialogue passages +PASS Manuscript text statistics supports smart quotes +PASS Manuscript text statistics supports straight quotes +PASS Manuscript text statistics carries multi-paragraph dialogue +PASS Manuscript text statistics returns to prose after continued dialogue +PASS Manuscript text statistics ignores empty paragraphs +PASS Manuscript text statistics reconciles scene totals +PASS Manuscript text statistics aggregates chapter scenes +PASS Manuscript text statistics recalculates existing scene sources +PASS Manuscript text statistics does not invoke AI +PASS Phase 21T repairs durable character understanding +PASS Phase 21U extracts mandatory character appearance fixtures +PASS Character sex hints are conservative and reviewable +PASS Character discovery does not truncate scan review candidates +PASS Character discovery rejects sentence-start words +PASS Character discovery rejects fragments and location names +PASS Manuscript scan preview keeps only auto-selected character candidates +PASS Word Companion scan completion uses chunked transport +PASS Word Companion scan chunks assemble full novel payloads +PASS Word Companion scan chunks reject partial and conflicting payloads +PASS Onboarding wizard keeps character pages inside one main step +PASS Scan review aliases feed Story Intelligence known character context +PASS Name Intelligence package contract is present +PASS Name Intelligence reference data is copied on publish +PASS Name Intelligence repository uses stored procedures +PASS Name Intelligence review warning is wired +PASS Name Intelligence library defaults to all locales +PASS Story Intelligence new-format context uses canonical characters +PASS Story Intelligence character defaults link proposed existing matches +PASS Story Intelligence character defaults ignore generic references +PASS Story Intelligence character defaults keep descriptive identities +PASS Story Intelligence character review uses single identity decision +PASS Story Intelligence auto resolves exact known identities before review +PASS Story Intelligence character matching keeps ambiguous known names visible +PASS Story Intelligence descriptive references consolidate articles +PASS Story Intelligence review omits character metrics dashboard +PASS Story Intelligence resumed chapters use canonical labels +PASS Story Intelligence character review posts selected existing match +PASS Story Intelligence character default changes preserve persisted results +PASS Structural POV rides existing chapter analysis +PASS Structural POV persists through import resolution +PASS Chapter POV derives from canonical scenes +PASS Permanent Analyse My Book starts from saved book +PASS Story Intelligence canonical context carries provenance +PASS Scene prompt protects canonical scene context +PASS Structural setting rides existing chapter analysis +PASS Explicit narrator labels detect deterministic POV +PASS AI POV JSON parses into structural models +PASS Post character review resolves persisted structural POV +PASS Normal scene and chapter saves persist POV +PASS Character merge is a reusable stored procedure workflow +PASS Story Intelligence character review suppresses resolved narrator POV +PASS Story Intelligence character review reuses structured appearance aliases +PASS Entity preferred names are peer aliases +PASS Story Intelligence review evidence includes chapter scene labels +PASS Story Intelligence import enables project metric defaults before save +PASS Project metrics add defaults backfills scene values +PASS Story Intelligence scene prompt uses configured metrics +PASS Story Intelligence scene prompt uses scene characters terminology +PASS Story Intelligence downstream imports support canonical scene results +PASS Story Intelligence runner supplies metrics and Plot Lines +PASS Story Intelligence metric persistence uses configured keys +PASS Story Intelligence stabilisation gate materialises strict and legacy metrics +PASS Story Intelligence modern materialisation owns finalisation boundary +PASS Story Intelligence narrative materialisation reads strict scene results +PASS Story Intelligence stabilisation routes normal users to book +PASS Story Intelligence narrative candidates require review +PASS Story Intelligence discovers Plot Lines without preconfiguration +PASS Story Intelligence matches existing Plot Lines without duplicates +PASS Narrative research prototype fixture builds hierarchy +PASS Narrative sibling hotel fixture generalises hierarchy +PASS Narrative trivial one-scene question is suppressed +PASS Narrative short significant thread survives +PASS Narrative semantic evolution consolidates by continuity +PASS Narrative existing thread matching is supported +PASS Narrative candidate merge and parent fields are persisted +PASS Narrative prompt uses one scene call with compact schema +PASS Narrative production code remains fixture agnostic +PASS Whole-book Plot Intelligence prompt carries full manuscript context +PASS Whole-book Plot Intelligence schema requires timeline event types +PASS Whole-book Plot Intelligence author seed inputs persist safely +PASS Whole-book Plot Intelligence structured author seed match survives +PASS Whole-book Plot Intelligence unmatched seeds become review candidates +PASS Whole-book Plot Intelligence uses dedicated output token headroom +PASS Story Intelligence narrative review displays author seed provenance +PASS Story Intelligence narrative review avoids raw author-facing IDs +PASS Story Intelligence author seed decisions are preserved +PASS Whole-book Plot Intelligence production code remains fixture agnostic +PASS Story Intelligence narrative review creates canonical records via existing procs +PASS Story Intelligence narrative stage follows knowledge +PASS Word Companion replays live current scene to writing panes +PASS Scan review post supports full-book form submissions +PASS StoryPosition rejects incomplete or invalid runtime scene positions +PASS StoryPosition builds canonical runtime scene navigation +PASS StoryPosition derives canonical scene context identity +PASS Writing Context route uses canonical story context service +PASS Writing Context client follows canonical story position events +PASS Writing Context preserves selected tab and avoids event loops +PASS Writing Intent route uses canonical story context and planning data +PASS Writing Intent client uses shared writing follow helper +PASS Obsolete global Word navigation is removed while writing windows remain live +PASS Appearance preferences and ribbon destinations +PASS Toolbar preferences, authorisation and contextual routes +PASS Application navigation resolves authorised project and book context +PASS Writing pair shares canonical follow infrastructure +PASS Writing workspace presence scopes browser windows +PASS Writing workspace client uses session window identity and stable names +PASS Writing workspace launcher uses progressive screen placement +PASS Writing workspace pages register roles without changing follow behavior +PASS Word marker client acknowledgements require authenticated ownership +PASS Word Companion exposes writing workspace launch actions +PASS Word Companion writing screens receive resolved context identifiers +PASS Word Companion canonical markers drive runtime follow +PASS Word Companion runtime follows multiple imported scene anchors +PASS Word Companion existing project book linking remains available +PASS Word Companion document identity survives reconnect +PASS Word Companion multiscreen launch and follow remain reachable +PASS Word Companion modes remain distinct +PASS Writing pages do not require Story Intelligence +PASS Word Companion host script has valid tab mapping +PASS Writing screens show diagnostic empty states +PASS Word Companion three-screen flow logs connection identifiers +PASS Admin Story Intelligence reset returns to diagnostics with messages +PASS Project hard delete clears Story Intelligence dependencies in transaction +PASS Permanent project delete keeps archive and name safety gates +PASS Word manuscript cleanup classifies PlotDirector markers by tag only +PASS Word manuscript cleanup preserves content controls content +PASS Word manuscript cleanup UI separates unlink from clean unlink +PASS Word manuscript unlink keeps Story Intelligence data untouched +PASS Word manuscript cleanup remains relinkable and idempotent +PASS Story Intelligence Review Centre route replaces linear review resume +PASS Story Intelligence obsolete create scene workflow is removed +PASS Story Intelligence Review Centre counts only needs-attention categories +PASS Story Intelligence Review Centre uses independent tile grid +PASS Story Intelligence Review Centre opens with character gate +PASS Story Intelligence review modules are independent after character gate +PASS Story Intelligence review module completion is durable and independent +PASS Story Intelligence review module pages omit wizard chrome +PASS Story Intelligence downstream review uses completed scene analysis +PASS Story Intelligence review posts do not use success interstitials +PASS Story Intelligence legacy review completion routes are deleted +PASS Story Intelligence review forms share busy submit guard +PASS Story Intelligence heavy review modules offer bounded rendering +PASS Story Intelligence Review Centre adds no AI calls +PASS Story Intelligence Review Centre uses bounded summary query +PASS Story Intelligence character review queues enrichment beside plot synthesis +PASS Story Intelligence character enrichment uses persisted SignalR progress +PASS Story Intelligence character enrichment preserves author fields +PASS Story Intelligence character enrichment batches by prompt size +PASS Story Intelligence character enrichment promotes structured facts +PASS Character detail can queue single-character enrichment +PASS Single-character enrichment is persisted and duplicate safe +PASS Character detail enrichment status uses scoped SignalR +PASS Story Intelligence detailed review GETs use selected module paths +PASS Story Intelligence completed Character review remains inspectable +PASS Story Intelligence Review Centre completed modules use canonical destinations +PASS Story Intelligence detailed reviews read persisted candidate pages +PASS Story Intelligence module completion lifecycle uses persisted candidates +PASS Story Intelligence Job 6 uses bounded concurrent chapter execution +PASS Story Intelligence global progress uses whole run scene totals +PASS Story Intelligence recovered provider failures stay operational +PASS Story Intelligence recovered JSON repair stays operational +PASS Story Intelligence terminal failures remain user visible +PASS Story Intelligence global banner remains visible through finalising gaps +PASS Story Intelligence global banner rejects stale live snapshots +PASS Story Intelligence live global progress publishes authoritative scene aggregates +PASS Story Intelligence global progress survives initial SignalR start races +PASS Story Intelligence scene analysis completion barrier releases review +PASS Story Intelligence active progress only appears in global strip +PASS Story Intelligence book actions do not open review centre while running diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase35/browser.txt b/Docs/WordCompanion/Evidence/2026-11-05-phase35/browser.txt new file mode 100644 index 00000000..31269016 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase35/browser.txt @@ -0,0 +1,5 @@ +PASS context actual browser delayed responses, abort, current-scene return, old failure and chapter identity +PASS intent actual browser delayed responses, abort, current-scene return, old failure and chapter identity +PASS pinned context retains scoped saved content without SignalR/latest Word/window registration +PASS pinned intent retains scoped saved content without SignalR/latest Word/window registration +PASS fresh Writer launcher opens both missing role windows without undeclared currentRole diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase35/native.txt b/Docs/WordCompanion/Evidence/2026-11-05-phase35/native.txt new file mode 100644 index 00000000..f670cb38 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase35/native.txt @@ -0,0 +1,183 @@ +PASS selection scheduler coalesces bursts +PASS Word operation timing recorded +PASS only latest selection executes on owner +PASS obsolete Word work cancelled +PASS bounded Word queue accepts capacity slot 0 +PASS bounded Word queue accepts capacity slot 1 +PASS bounded Word queue accepts capacity slot 2 +PASS bounded Word queue accepts capacity slot 3 +PASS bounded Word queue accepts capacity slot 4 +PASS bounded Word queue accepts capacity slot 5 +PASS bounded Word queue accepts capacity slot 6 +PASS bounded Word queue accepts capacity slot 7 +PASS bounded Word queue accepts capacity slot 8 +PASS bounded Word queue accepts capacity slot 9 +PASS bounded Word queue accepts capacity slot 10 +PASS bounded Word queue accepts capacity slot 11 +PASS bounded Word queue accepts capacity slot 12 +PASS bounded Word queue accepts capacity slot 13 +PASS bounded Word queue accepts capacity slot 14 +PASS bounded Word queue accepts capacity slot 15 +PASS bounded Word queue accepts capacity slot 16 +PASS bounded Word queue accepts capacity slot 17 +PASS bounded Word queue accepts capacity slot 18 +PASS bounded Word queue accepts capacity slot 19 +PASS bounded Word queue accepts capacity slot 20 +PASS bounded Word queue accepts capacity slot 21 +PASS bounded Word queue accepts capacity slot 22 +PASS bounded Word queue accepts capacity slot 23 +PASS bounded Word queue accepts capacity slot 24 +PASS bounded Word queue accepts capacity slot 25 +PASS bounded Word queue accepts capacity slot 26 +PASS bounded Word queue accepts capacity slot 27 +PASS bounded Word queue accepts capacity slot 28 +PASS bounded Word queue accepts capacity slot 29 +PASS bounded Word queue accepts capacity slot 30 +PASS bounded Word queue accepts capacity slot 31 +PASS bounded Word queue accepts capacity slot 32 +PASS bounded Word queue accepts capacity slot 33 +PASS bounded Word queue accepts capacity slot 34 +PASS bounded Word queue accepts capacity slot 35 +PASS bounded Word queue accepts capacity slot 36 +PASS bounded Word queue accepts capacity slot 37 +PASS bounded Word queue accepts capacity slot 38 +PASS bounded Word queue accepts capacity slot 39 +PASS bounded Word queue accepts capacity slot 40 +PASS bounded Word queue accepts capacity slot 41 +PASS bounded Word queue accepts capacity slot 42 +PASS bounded Word queue accepts capacity slot 43 +PASS bounded Word queue accepts capacity slot 44 +PASS bounded Word queue accepts capacity slot 45 +PASS bounded Word queue accepts capacity slot 46 +PASS bounded Word queue accepts capacity slot 47 +PASS bounded Word queue accepts capacity slot 48 +PASS bounded Word queue accepts capacity slot 49 +PASS bounded Word queue accepts capacity slot 50 +PASS bounded Word queue accepts capacity slot 51 +PASS bounded Word queue accepts capacity slot 52 +PASS bounded Word queue accepts capacity slot 53 +PASS bounded Word queue accepts capacity slot 54 +PASS bounded Word queue accepts capacity slot 55 +PASS bounded Word queue accepts capacity slot 56 +PASS bounded Word queue accepts capacity slot 57 +PASS bounded Word queue accepts capacity slot 58 +PASS bounded Word queue accepts capacity slot 59 +PASS bounded Word queue accepts capacity slot 60 +PASS bounded Word queue accepts capacity slot 61 +PASS bounded Word queue accepts capacity slot 62 +PASS bounded Word queue accepts capacity slot 63 +PASS Word queue rejects overflow without waiting +PASS Word scheduler rejects wrong thread +PASS author activity suspends low priority work +PASS IPC coalesces selection storm to latest value +PASS coalesced position is latest +PASS IPC snapshot queue backpressure bounded +PASS IPC selection session slots bounded +PASS missing required protocol capabilities refused +PASS three books have independent live sessions +PASS commit structural snapshot Discovery +PASS positional scene resolution independent of repeated text Discovery +PASS commit structural snapshot Reckoning +PASS positional scene resolution independent of repeated text Reckoning +PASS commit structural snapshot Redemption +PASS positional scene resolution independent of repeated text Redemption +PASS rapid three-document switching preserves active identity +PASS cancelled snapshot cannot commit +PASS partial snapshot cannot masquerade as complete +PASS oversized extraction fragment refused +PASS stale revision refused +PASS peer cannot address another instance lease +PASS duplicate/out-of-order sequence refused +PASS closing one document retires only its state +PASS old disconnect cannot retire replacement lease +PASS disconnect releases all owned sessions and snapshots +PASS one Word process cannot route into another process document +PASS terminating one Word process preserves another instance +PASS new observation revision invalidates in-flight old extraction +PASS malformed null document cannot crash agent session processing +PASS oversized frame rejected before allocation +PASS versioned frame round-trip retains identity +PASS offline work persisted without manuscript prose +PASS On Save mode cannot be triggered by automatic quiet period +PASS offline work survives agent restart +PASS new scene revision supersedes queued older work +PASS stale offline revision cannot replace newer work +PASS old acknowledgement cannot remove newer work +PASS matching idempotency acknowledgement retires work +PASS durable queue rejects capacity overflow +PASS real pipe rejects incompatible handshake +PASS same-version optional capabilities remain compatible +PASS agent advertises optional structural review capability +PASS real named-pipe handshake reconciles three documents +PASS agent receives actual asynchronous positional/lifecycle traffic +PASS real pipe returns document analysis results +PASS agent shutdown retires peer sessions +PASS idle keepalive detects agent loss without a Word event +PASS agent restart reconnects and reconciles without UI waits +PASS analysis can be repeated after actual pipe host restart +PASS real pipe document close is isolated +PASS link shutdown cancels background worker promptly +PASS untrusted agent owner callback rejects connection before handshake +PASS unresponsive agent handshake times out off producer thread +PASS blank document has an explicit empty analysis +PASS plain chapter labels and separators become review suggestions +PASS ambiguous text and heading levels explain uncertainty instead of approving import +PASS analysis reuses existing PlotDirector marker interpretation +PASS fragment splits do not inflate word or paragraph counts +PASS 250000-word many-paragraph manuscript analysed incrementally +PASS review suggestion storage is bounded with explicit truncation +PASS analysis results are paginated +PASS review page fits bounded IPC frame +PASS analysis result contract round-trips over framing +PASS document-specific analysis returns structured results and progress +PASS document-specific analysis returns structured results and progress +PASS document-specific analysis returns structured results and progress +PASS another document's snapshot cannot retrieve results +PASS analysis acknowledges bounded partial progress before cancellation +PASS cancelled analysis cannot complete +PASS analysis waiting for Word scheduler is cancellable +PASS pending analysis cancellation does not require extraction +PASS review rejects results from a different document +PASS late results cannot replace cancellation +PASS new analysis rejects obsolete revision and snapshot +PASS review completes only matching analysis +PASS selection replies cannot regress completed review progress +PASS late page zero cannot replace requested later page +PASS agent restart releases document analysis state +PASS native connection rejects unsafe site root +PASS native connection rejects unsafe site root +PASS native connection rejects unsafe site root +PASS native connection rejects unsafe site root +PASS native connection rejects unsafe site root +PASS incompatible agent handshake enters recovery instead of killing the client worker +PASS browser-approved sign-in loads only authorised book choices +PASS sign-in and local work never upload chapter prose +PASS AI chapter capture starts only after an explicit command +PASS bounded chapter capture reports progress without submitting early +PASS duplicate submit uses one HTTP call and preserves exact chapter mapping +PASS worst-case bounded AI page fits IPC framing +PASS AI result contract round-trips on actual frame codec +PASS late cancellation cannot retire a replacement AI chapter +PASS another document cannot retrieve an AI result +PASS cancelled network chapter cannot reappear in review +PASS authorisation failure is isolated and actionable +PASS malformed AI fields fail safely instead of leaving a chapter spinning +PASS upload consent pins document snapshot and authentication context +PASS account/site change refuses old consent before any chapter HTTP upload +PASS sign-out forgets credential and book list +PASS local chapters supply explicit nonoverlapping AI extraction ranges +PASS duplicate live session identity cannot cross Word instances +PASS expired verification never presents cached sign-in/book as live +PASS IPC outage overrides previously successful server state +PASS book switch rejects late saved data +PASS late successful response cannot revive a cancelled client preview +PASS one parent chapter is retained across local and AI pages +PASS cross-page preview selection is bounded without silently dropping selected rows +PASS multiple document saved contexts remain isolated +PASS older workspace binding cannot fetch or overwrite a replacement +PASS cancelled import preview cannot reappear after delayed completion +PASS server loss clears a previously verified online indicator +PASS explicit connection check detects recovery +PASS authentication expiry rotates scope and removes verified authentication +PASS expired credentials cannot display an old authenticated workspace +Native foundation: 182 checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified. diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase35/powershell.txt b/Docs/WordCompanion/Evidence/2026-11-05-phase35/powershell.txt new file mode 100644 index 00000000..eaf5a2ac --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase35/powershell.txt @@ -0,0 +1,8 @@ +PASS parse Build-Developer.ps1 +PASS parse DeveloperPackage.ps1 +PASS parse Generate-Fixtures.ps1 +PASS parse Install-WordCompanion.ps1 +PASS parse Measure-Processes.ps1 +PASS parse Test-DeveloperPackage.ps1 +PASS parse Update-WordCompanion.ps1 +PASS portable package validation, tamper refusal and non-Windows fail-closed guards. Fixture signatures are placeholders; no Office trust/Windows installation validation claimed. diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase35/vsto-syntax.txt b/Docs/WordCompanion/Evidence/2026-11-05-phase35/vsto-syntax.txt new file mode 100644 index 00000000..2c0b6546 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase35/vsto-syntax.txt @@ -0,0 +1,8 @@ +Syntax only PASS AnalysisWindow.cs +Syntax only PASS ThisAddIn.cs +Syntax only PASS AgentProcess.cs +Syntax only PASS ConnectWindow.cs +Syntax only PASS WordAdapter.cs +Syntax only PASS NativeRibbon.cs +Syntax only PASS ThisAddIn.Designer.cs +Syntax only PASS AssemblyInfo.cs diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase35/workflow.txt b/Docs/WordCompanion/Evidence/2026-11-05-phase35/workflow.txt new file mode 100644 index 00000000..aff6da18 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase35/workflow.txt @@ -0,0 +1 @@ +PASS native saved workspace and safe import preview validation diff --git a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs index 57bf3974..5e796364 100644 --- a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs +++ b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs @@ -20,6 +20,8 @@ public sealed class CloudGateway : IDisposable private string? token; private Guid authenticationContext=Guid.NewGuid(); private string state="Not signed in"; + private ConnectionHealth health=new(); + private int checking;private DateTime nextCheck; private CompanionBook[] books=[]; private readonly string? settingsPath; private static readonly JsonSerializerOptions Json=new(JsonSerializerDefaults.Web); @@ -34,12 +36,26 @@ public sealed class CloudGateway : IDisposable return uri; } public Message Status() - {lock(gate)return new(){Status=state,Books=books,AuthenticationContext=authenticationContext,ServerUrl=origin?.AbsoluteUri??ReadOrigin()};} + { + bool refresh;Message answer; + lock(gate){Expire();refresh=token!=null&&DateTime.UtcNow>=nextCheck;answer=new(){Status=state,Books=books,AuthenticationContext=authenticationContext,ServerUrl=origin?.AbsoluteUri??ReadOrigin(),Health=CopyHealth()};} + if(refresh)_=CheckConnection();return answer; + } + private ConnectionHealth CopyHealth()=>new(){Server=health.Server,Authentication=health.Authentication,Ai=health.Ai,Explanation=health.Explanation,VerifiedUtc=health.VerifiedUtc,ExpiresUtc=health.ExpiresUtc}; + private void Expire(){if(token!=null&&health.ExpiresUtc!=default&&DateTime.UtcNow>=health.ExpiresUtc){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";health.Ai="unknown";}} + public async Task CheckConnection() + { + if(Interlocked.Exchange(ref checking,1)!=0)return; + Guid context;lock(gate){context=authenticationContext;nextCheck=DateTime.UtcNow.AddMinutes(2);health.Server="checking";} + try{var result=await Get("api/native-companion/connection",context);lock(gate)if(authenticationContext==context){result.VerifiedUtc=DateTime.UtcNow;health=result;state="Signed in (verified)";}} + catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException){lock(gate)if(authenticationContext==context){health.Server=token==null?"unknown":"offline";health.Explanation="Server verification failed. Check connection; local detection remains available.";}} + finally{Volatile.Write(ref checking,0);} + } private string ReadOrigin(){try{return settingsPath!=null&&File.Exists(settingsPath)?File.ReadAllText(settingsPath):"";}catch(IOException){return "";}} public void Connect(string address) { var uri=ValidateOrigin(address);CancellationTokenSource stop; - lock(gate){pairing?.Cancel();pairing=stop=new(TimeSpan.FromMinutes(5));origin=uri;authenticationContext=Guid.NewGuid();token=null;books=[];state="Starting browser sign-in…";} + lock(gate){pairing?.Cancel();pairing=stop=new(TimeSpan.FromMinutes(5));origin=uri;authenticationContext=Guid.NewGuid();token=null;books=[];health=new(){Server="connecting",Authentication="pending"};state="Starting browser sign-in…";} _=Task.Run(async()=>{ try { @@ -60,33 +76,65 @@ public sealed class CloudGateway : IDisposable using var request=new HttpRequestMessage(HttpMethod.Get,new Uri(uri,"api/native-companion/books"));request.Headers.Authorization=new("Bearer",grant.AccessToken); using var list=await http.SendAsync(request,stop.Token);list.EnsureSuccessStatusCode(); var available=await list.Content.ReadFromJsonAsync(Json,stop.Token)??[]; - lock(gate)if(pairing==stop&&!stop.IsCancellationRequested){token=grant.AccessToken;books=available.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).Select(b=>new CompanionBook{BookId=b.BookId,Title=b.Title.Length>160?b.Title[..160]:b.Title}).ToArray();state="Signed in (four-hour grant)";} + lock(gate)if(pairing==stop&&!stop.IsCancellationRequested){token=grant.AccessToken;books=available.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).Select(b=>new CompanionBook{BookId=b.BookId,Title=b.Title.Length>160?b.Title[..160]:b.Title}).ToArray();state="Signed in (four-hour grant)";health=new(){Server="online",Authentication="verified",VerifiedUtc=DateTime.UtcNow,ExpiresUtc=DateTime.UtcNow.AddHours(4),Ai="unknown",Explanation="Book list verified; checking AI configuration."};nextCheck=DateTime.MinValue;} return; } } catch(Exception e)when(e is HttpRequestException or OperationCanceledException or IOException or InvalidDataException or JsonException or System.ComponentModel.Win32Exception or UnauthorizedAccessException or InvalidOperationException or ArgumentException) - {lock(gate)if(pairing==stop)state="Sign-in failed or expired. Check the site address and try Connect again.";} + {lock(gate)if(pairing==stop){state="Sign-in failed or expired. Check the site address and try Connect again.";health=new(){Server="unverified",Authentication="not-signed-in",Explanation=state};}} }); } - public void SignOut(){lock(gate){pairing?.Cancel();pairing=null;authenticationContext=Guid.NewGuid();token=null;books=[];state="Not signed in";}} + public void SignOut(){lock(gate){pairing?.Cancel();pairing=null;authenticationContext=Guid.NewGuid();token=null;books=[];state="Not signed in";health=new();}} public bool Allows(Guid context,int bookId) - {lock(gate)return token!=null&&context==authenticationContext&&books.Any(b=>b.BookId==bookId);} + {lock(gate){Expire();return token!=null&&context==authenticationContext&&books.Any(b=>b.BookId==bookId);}} public async Task Analyse(AiChapterRequest chapter,CancellationToken cancellation,Guid expectedContext) { Uri site;string access; lock(gate){if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");} using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/analyse-chapter")){Content=JsonContent.Create(chapter,options:Json)}; request.Headers.Authorization=new AuthenticationHeaderValue("Bearer",access); - using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellation); - if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(token==access){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";}throw new InvalidOperationException("Sign-in expired. Connect again.");} - if(!response.IsSuccessStatusCode)throw new InvalidOperationException(response.StatusCode switch{HttpStatusCode.Forbidden=>"Book/subscription access denied.",HttpStatusCode.TooManyRequests=>"Server busy. Retry this chapter later.",HttpStatusCode.BadRequest=>"Chapter mapping or size was rejected. Check boundaries.",_=>"Server unavailable. Check the deployed native API."}); + HttpResponseMessage responseValue; + try{responseValue=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellation);} + catch(HttpRequestException){lock(gate)if(authenticationContext==expectedContext){health.Server="offline";health.Explanation="AI request could not reach the server.";}throw;} + using var response=responseValue; + if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(token==access){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";health.Server="online";health.Ai="unknown";}throw new InvalidOperationException("Sign-in expired. Connect again.");} + if(!response.IsSuccessStatusCode){lock(gate)if(authenticationContext==expectedContext){health.Server="degraded";health.Ai="request-failed";health.Explanation="AI request rejected or unavailable; see chapter results.";}throw new InvalidOperationException(response.StatusCode switch{HttpStatusCode.Forbidden=>"Book/subscription access denied.",HttpStatusCode.TooManyRequests=>"Server busy. Retry this chapter later.",HttpStatusCode.BadRequest=>"Chapter mapping or size was rejected. Check boundaries.",_=>"Server unavailable. Check the deployed native API."});} // Bound server response before deserializing; never log a body/provider message. await using var stream=await response.Content.ReadAsStreamAsync(cancellation);using var buffer=new MemoryStream();var bytes=new byte[8192]; int count;while((count=await stream.ReadAsync(bytes,cancellation))>0){if(buffer.Length+count>1024*1024)throw new InvalidDataException("AI response too large.");buffer.Write(bytes,0,count);} buffer.Position=0;var result=await JsonSerializer.DeserializeAsync(buffer,Json,cancellation)??throw new InvalidDataException(); if(result.RequestId!=chapter.RequestId||result.State is not ("complete" or "failed" or "cancelled")||result.Message==null||result.Message.Length>2048||result.Scenes==null||result.Scenes.Length>500||result.Scenes.Any(s=>s==null||s.Startchapter.ChapterEnd||s.End<=s.Start||s.Title==null||s.Reason==null||s.Confidence==null||s.Confidence.Length>32||s.Kind!="Scene"||s.Origin!="AI"||s.Title.Length>200||s.Reason.Length>600))throw new InvalidDataException("Invalid AI mapping."); + lock(gate)if(authenticationContext==expectedContext){health.Server="online";health.Authentication="verified";health.VerifiedUtc=DateTime.UtcNow;health.Ai=result.State=="complete"?"last-request-succeeded":"request-failed";health.Explanation=result.Message;} return result; } + public async Task Get(string path,Guid expectedContext) + =>await Send(HttpMethod.Get,path,null,expectedContext); + public async Task Post(string path,object body,Guid expectedContext) + =>await Send(HttpMethod.Post,path,body,expectedContext); + private async Task Send(HttpMethod method,string path,object? body,Guid context) + { + Uri site;string access;lock(gate){Expire();if(context!=authenticationContext||token==null)throw new InvalidOperationException("Sign in again and reselect the book.");site=origin!;access=token;} + using var stop=new CancellationTokenSource(TimeSpan.FromSeconds(15));using var request=new HttpRequestMessage(method,new Uri(site,path));request.Headers.Authorization=new("Bearer",access);if(body!=null)request.Content=JsonContent.Create(body,options:Json); + try + { + using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,stop.Token); + if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(authenticationContext==context){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";}throw new InvalidOperationException("Sign-in expired. Connect again.");} + if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=DateTime.UtcNow;health.Explanation="Server rejected the saved-data request. See the document result.";}throw new InvalidOperationException(response.StatusCode==HttpStatusCode.Forbidden?"Access denied or subscription unavailable.":response.StatusCode==HttpStatusCode.NotFound?"No saved chapter/scene matches this book and Word marker.":"Server request failed. Check connection or update the server.");} + await using var stream=await response.Content.ReadAsStreamAsync(stop.Token);using var buffer=new MemoryStream();var bytes=new byte[8192];int size; + while((size=await stream.ReadAsync(bytes,stop.Token))>0){if(buffer.Length+size>1024*1024)throw new InvalidDataException();buffer.Write(bytes,0,size);}buffer.Position=0; + var result=await JsonSerializer.DeserializeAsync(buffer,Json,stop.Token); + lock(gate){if(context!=authenticationContext)throw new InvalidOperationException("Connection changed; discarded old response.");health.Server="online";health.Authentication="verified";health.VerifiedUtc=DateTime.UtcNow;} + return result??throw new InvalidDataException(); + } + catch(OperationCanceledException){lock(gate)if(context==authenticationContext){health.Server="degraded";health.Explanation="Server verification timed out. Check connection before continuing.";}throw;} + catch(HttpRequestException){lock(gate)if(context==authenticationContext){health.Server="offline";health.Explanation="Server unreachable. Saved information is not current.";}throw;} + } + public void OpenSavedPage(string path,Guid context) + { + lock(gate){Expire();if(context!=authenticationContext||token==null||origin==null)throw new InvalidOperationException("Sign in first."); + if(!path.StartsWith("/Books/Details/",StringComparison.Ordinal)&&!path.StartsWith("/Writing/Context?",StringComparison.Ordinal)&&!path.StartsWith("/Writing/Intent?",StringComparison.Ordinal))throw new InvalidDataException(); + var url=new Uri(origin,path);if(url.GetLeftPart(UriPartial.Authority)!=origin.GetLeftPart(UriPartial.Authority))throw new InvalidDataException();openBrowser(url.AbsoluteUri);} + } public async Task CancelRemote(Guid id) { try diff --git a/PlotDirector.NativeCompanion/Agent/DocumentWorkspaceWork.cs b/PlotDirector.NativeCompanion/Agent/DocumentWorkspaceWork.cs new file mode 100644 index 00000000..3513cedb --- /dev/null +++ b/PlotDirector.NativeCompanion/Agent/DocumentWorkspaceWork.cs @@ -0,0 +1,78 @@ +using PlotDirector.Companion.Protocol; +namespace PlotDirector.Companion.Agent; + +// Bounded value-only per-document saved workspace/preview. No import commit operation exists. +public sealed class DocumentWorkspaceWork(CloudGateway cloud) +{ + private readonly SemaphoreSlim requests=new(4); + private int previewJobs; + private readonly object gate=new();private readonly Dictionary states=[]; + public Message Handle(DocumentDescriptor descriptor,Message request,Message answer) + { + lock(gate) + { + if(request.Kind=="workspace-select") + { + Clear(descriptor.SessionId); + if(request.BookId==0){answer.Workspace=new();return answer;} + if(states.Count>=256||!cloud.Allows(request.AuthenticationContext,request.BookId)){answer.Status="authentication-changed";return answer;} + var state=new State(request.BookId,request.AuthenticationContext,descriptor.Revision,request.SnapshotId);states[descriptor.SessionId]=state;Refresh(descriptor.SessionId,state,request.ChapterId,request.SceneId); + } + if(!states.TryGetValue(descriptor.SessionId,out var current)){answer.Workspace=new();return answer;} + if(request.SnapshotId!=current.Binding){answer.Status="obsolete-workspace";return answer;} + answer.SnapshotId=current.Binding;answer.BookId=current.Book;answer.AuthenticationContext=current.Context; + if(!cloud.Allows(current.Context,current.Book)){Clear(descriptor.SessionId);answer.Status="authentication-changed";answer.Workspace=new();return answer;} + if(request.Kind=="workspace-refresh")Refresh(descriptor.SessionId,current,request.ChapterId,request.SceneId); + if(request.Kind=="workspace-preview") + { + var selection=request.ImportSelection; + if(selection==null||selection.BookId!=current.Book||selection.SessionId!=descriptor.SessionId||selection.SnapshotId==Guid.Empty||selection.Items==null||selection.Items.Length is <1 or >80){answer.Status="invalid-preview";return answer;} + if(previewJobs>=4||current.Preview?.State=="loading"){answer.ImportPreview=new(){RequestId=selection.RequestId,State="rejected",Message="Preview already running or server preview capacity is busy. Cancel or wait, then retry."};answer.Workspace=current.Workspace;return answer;} + previewJobs++;var generation=++current.PreviewGeneration;current.Preview=new(){RequestId=selection.RequestId,State="loading",Message="Validating selected structure with PlotDirector. No records are created."}; + _=Task.Run(async()=>{ + ImportPreview result; + try{result=await cloud.Post("api/native-companion/import-preview",selection,current.Context);} + catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or System.Text.Json.JsonException){result=new(){State="rejected",Message=e is InvalidOperationException?e.Message:"Preview unavailable. Check connection and retry; no import was committed."};} + lock(gate){previewJobs--;if(states.GetValueOrDefault(descriptor.SessionId)==current&&generation==current.PreviewGeneration){result.RequestId=selection.RequestId;current.Preview=result;}} + }); + } + if(request.Kind=="workspace-cancel-preview"){current.PreviewGeneration++;current.Preview=null;} + if(request.Kind=="workspace-open") + { + if(!current.Workspace.State.StartsWith("saved-",StringComparison.Ordinal)){answer.Status="workspace-unavailable";return answer;} + var path=request.Action switch{"context"=>current.Workspace.ContextPath,"intent"=>current.Workspace.IntentPath,"book"=>current.Workspace.BookPath,_=>""}; + _=Task.Run(()=>{try{cloud.OpenSavedPage(path,current.Context);}catch(Exception e)when(e is InvalidOperationException or IOException or InvalidDataException or System.ComponentModel.Win32Exception){ }}); + } + answer.Workspace=current.Workspace;answer.ImportPreview=current.Preview;answer.BookId=current.Book;return answer; + } + } + public void Position(Guid session,int? chapter,int? scene) + {lock(gate)if(states.TryGetValue(session,out var state)&&(state.Chapter!=chapter||state.Scene!=scene))Refresh(session,state,chapter,scene);} + private void Refresh(Guid session,State state,int? chapter,int? scene) + { + state.Chapter=chapter;state.Scene=scene;state.Generation++; + state.Workspace=new(){BookId=state.Book,State="loading",Context="Loading saved book/position…",Intent="Loading saved objectives…"}; + if(state.Running)return;state.Running=true; + _=Task.Run(async()=>{ + while(true) + { + await Task.Delay(350);long generation;int? chapterId,sceneId; + lock(gate){if(states.GetValueOrDefault(session)!=state)return;generation=state.Generation;chapterId=state.Chapter;sceneId=state.Scene;} + SavedWorkspace result; + await requests.WaitAsync(); + try + { + lock(gate){if(states.GetValueOrDefault(session)!=state)return;} + result=await cloud.Get($"api/native-companion/books/{state.Book}/workspace"+(chapterId.HasValue||sceneId.HasValue?$"?chapterId={chapterId}&sceneId={sceneId}":""),state.Context); + } + catch(Exception e){result=new(){BookId=state.Book,State="unavailable",Context=e is InvalidOperationException?e.Message:"Saved context could not be loaded. Check connection.",Intent="No saved intent is displayed. Refresh after reconnecting."};} + finally{requests.Release();} + lock(gate){if(states.GetValueOrDefault(session)!=state)return;if(state.Generation==generation){state.Workspace=result;state.Running=false;return;}} + } + }); + } + public void Clear(Guid session){lock(gate)states.Remove(session);} + public void ClearAll(){lock(gate)states.Clear();} + private sealed class State(int book,Guid context,long revision,Guid binding) + {public Guid Binding=binding;public int Book=book;public Guid Context=context;public long Revision=revision;public bool Running;public long Generation,PreviewGeneration;public int? Chapter,Scene;public SavedWorkspace Workspace=new();public ImportPreview? Preview;} +} diff --git a/PlotDirector.NativeCompanion/Agent/PipeHost.cs b/PlotDirector.NativeCompanion/Agent/PipeHost.cs index 64f4e258..c0bf03cd 100644 --- a/PlotDirector.NativeCompanion/Agent/PipeHost.cs +++ b/PlotDirector.NativeCompanion/Agent/PipeHost.cs @@ -56,7 +56,7 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action{ var lastPeer=DateTime.UtcNow; diff --git a/PlotDirector.NativeCompanion/Agent/SessionManager.cs b/PlotDirector.NativeCompanion/Agent/SessionManager.cs index 59bfd709..7a560ea7 100644 --- a/PlotDirector.NativeCompanion/Agent/SessionManager.cs +++ b/PlotDirector.NativeCompanion/Agent/SessionManager.cs @@ -4,7 +4,7 @@ using PlotDirector.Companion.Protocol; namespace PlotDirector.Companion.Agent; -public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai = null) +public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai = null,DocumentWorkspaceWork? workspace = null) { private readonly object gate = new(); private readonly Dictionary instances = []; @@ -37,7 +37,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai } private void ClearDocument(DocumentState document) { - ai?.Clear(document.Descriptor.SessionId); + ai?.Clear(document.Descriptor.SessionId);workspace?.Clear(document.Descriptor.SessionId); totalSuggestions -= document.Analysis?.Count ?? 0;document.Analysis=null; ClearPending(document);totalBoundaries -= document.Boundaries.Count;document.Boundaries=[]; } @@ -50,12 +50,12 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai if (message.Sequence <= word.LastSequence) return Reject(answer,"stale-sequence"); word.LastSequence = message.Sequence; if (message.Kind == "ping") return answer; - if(message.Kind is "cloud-status" or "cloud-connect" or "cloud-signout") + if(message.Kind is "cloud-status" or "cloud-check" or "cloud-connect" or "cloud-signout") { answer.Kind="cloud-status";if(cloud==null)return Reject(answer,"cloud-unavailable"); - try{if(message.Kind=="cloud-connect"){ai?.Dispose();cloud.Connect(message.ServerUrl);}if(message.Kind=="cloud-signout"){ai?.Dispose();cloud.SignOut();}} + try{if(message.Kind=="cloud-check")_=cloud.CheckConnection();if(message.Kind=="cloud-connect"){ai?.Dispose();workspace?.ClearAll();cloud.Connect(message.ServerUrl);}if(message.Kind=="cloud-signout"){ai?.Dispose();workspace?.ClearAll();cloud.SignOut();}} catch(ArgumentException){return Reject(answer,"invalid-server-url");} - var status=cloud.Status();answer.Kind="cloud-status";answer.Status=status.Status;answer.Books=status.Books;answer.AuthenticationContext=status.AuthenticationContext;answer.ServerUrl=status.ServerUrl;return answer; + var status=cloud.Status();answer.Kind="cloud-status";answer.Status=status.Status;answer.Books=status.Books;answer.Health=status.Health;answer.AuthenticationContext=status.AuthenticationContext;answer.ServerUrl=status.ServerUrl;return answer; } if (message.Kind is "document" or "reconcile") { @@ -90,6 +90,10 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai return answer; } if (message.Revision != document.Descriptor.Revision) return Reject(answer,"stale-revision"); + if(message.Kind.StartsWith("workspace-",StringComparison.Ordinal)){answer.Kind="workspace-response";answer.BookId=message.BookId;answer.AuthenticationContext=message.AuthenticationContext; + if(message.Kind=="workspace-preview"&&(message.ImportSelection?.SnapshotId!=document.SnapshotId||message.ImportSelection?.ManuscriptId!=document.Descriptor.ManuscriptId)){answer.ImportPreview=new(){RequestId=message.ImportSelection?.RequestId??Guid.Empty,State="rejected",Message="Document snapshot changed. Detect structure and preview again."};return Reject(answer,"stale-preview");} + if(message.Kind is "workspace-select" or "workspace-refresh"){var position=new Message();Resolve(document,position);message.ChapterId=position.ChapterId;message.SceneId=position.SceneId;} + answer.Kind="workspace-response";return workspace?.Handle(document.Descriptor,message,answer)??Reject(answer,"workspace-unavailable");} if(message.Kind.StartsWith("ai-",StringComparison.Ordinal))return ai?.Handle(document.Descriptor,message,answer)??Reject(answer,"ai-unavailable"); switch (message.Kind) { @@ -97,7 +101,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai case "active": word.ActiveSession = message.SessionId; break; case "selection": if (message.Start < 0 || message.End < message.Start) return Reject(answer,"invalid-position"); - document.Cursor = message.Start; Resolve(document, answer); break; + document.Cursor = message.Start; Resolve(document, answer);workspace?.Position(message.SessionId,answer.ChapterId,answer.SceneId);break; case "snapshot-begin": if (message.SnapshotId == Guid.Empty || message.End < 0 || message.End > MaxSnapshotCharacters) return Reject(answer,"invalid-snapshot"); ClearPending(document); diff --git a/PlotDirector.NativeCompanion/Client/AgentLink.cs b/PlotDirector.NativeCompanion/Client/AgentLink.cs index 704d1446..3e4f1d92 100644 --- a/PlotDirector.NativeCompanion/Client/AgentLink.cs +++ b/PlotDirector.NativeCompanion/Client/AgentLink.cs @@ -97,7 +97,7 @@ public sealed class AgentLink : IDisposable lock (gate) activePipe = pipe; await pipe.ConnectAsync(700, stop.Token).ConfigureAwait(false); if (!verifyServer(pipe)) throw new UnauthorizedAccessException("Unexpected agent owner."); - await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability }, stop.Token).ConfigureAwait(false); + await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability }, stop.Token).ConfigureAwait(false); mailbox.Clear(); // Reconcile authoritative open documents; never replay stale extraction fragments. await ExchangeAsync(pipe, Reconcile(), stop.Token).ConfigureAwait(false); attempt = 0; StateChanged?.Invoke("connected"); diff --git a/PlotDirector.NativeCompanion/Client/ConnectionPresentation.cs b/PlotDirector.NativeCompanion/Client/ConnectionPresentation.cs new file mode 100644 index 00000000..97ab1d60 --- /dev/null +++ b/PlotDirector.NativeCompanion/Client/ConnectionPresentation.cs @@ -0,0 +1,14 @@ +using PlotDirector.Companion.Protocol; +namespace PlotDirector.Companion.Client; + +public static class ConnectionPresentation +{ + public static string Describe(string ipc,ConnectionHealth? health,int book,string workspace) + { + if(ipc!="connected")return "Word loaded · Local agent/IPC: "+ipc+" · Server/authentication: unverified"; + if(health==null)return "Word loaded · Agent/IPC connected · Server/authentication: checking"; + var server=health.VerifiedUtc==default||DateTime.UtcNow-health.VerifiedUtc>TimeSpan.FromSeconds(90)?(health.Server=="offline"?"offline":"unverified"):health.Server; + var authentication=server!="online"&&health.Authentication=="verified"?"cached grant; check connection":health.Authentication; + return "Agent/IPC connected · Server: "+server+" · Sign-in: "+authentication+" · Book: "+(book<=0?"not selected":server=="online"?workspace:"cached/unverified")+" · AI: "+health.Ai; + } +} diff --git a/PlotDirector.NativeCompanion/Client/DocumentBinding.cs b/PlotDirector.NativeCompanion/Client/DocumentBinding.cs new file mode 100644 index 00000000..32fcbb0d --- /dev/null +++ b/PlotDirector.NativeCompanion/Client/DocumentBinding.cs @@ -0,0 +1,33 @@ +using PlotDirector.Companion.Protocol; +namespace PlotDirector.Companion.Client; + +public sealed class DocumentBinding +{ + public int BookId {get;private set;} + public Guid Id {get;private set;} + public Guid AuthenticationContext {get;private set;} + public SavedWorkspace Workspace {get;private set;}=new(); + public Guid PendingPreview {get;private set;} + public void BeginPreview(Guid id){PendingPreview=id;Preview=new(){RequestId=id,State="loading",Message="Validating selected structure…"};} + public void CancelPreview(){PendingPreview=Guid.Empty;Preview=new(){State="cancelled",Message="Preview cancelled; nothing was imported."};} + public ImportPreview? Preview {get;private set;} + public void Select(int book,Guid authentication) + {BookId=book;AuthenticationContext=authentication;Id=Guid.NewGuid();Workspace=new(){BookId=book,State=book==0?"unselected":"loading"};Preview=null;PendingPreview=Guid.Empty;} + public void Reset()=>Select(0,Guid.Empty); + public bool Accept(Message response) + { + if(response.SnapshotId!=Id||response.AuthenticationContext!=AuthenticationContext||response.BookId!=BookId)return false; + if(response.Workspace!=null)Workspace=response.Workspace; + if(response.ImportPreview!=null&&response.ImportPreview.RequestId==PendingPreview&&PendingPreview!=Guid.Empty)Preview=response.ImportPreview;return true; + } +} +public sealed class StructureSelection +{ + private readonly Dictionary rows=new(); + public static string Key(StructureSuggestion item)=>item.Kind+":"+item.Start+(item.Kind=="Chapter"?"":":"+item.Origin); + public bool Contains(StructureSuggestion item)=>rows.ContainsKey(Key(item)); + public bool Set(StructureSuggestion item,bool selected) + {var key=Key(item);if(!selected){rows.Remove(key);return true;}if(rows.Count>=80&&!rows.ContainsKey(key))return false;rows[key]=item;return true;} + public StructureSuggestion[] Items=>rows.Values.OrderBy(s=>s.Start).ThenBy(s=>s.Kind).ToArray(); + public void Clear()=>rows.Clear(); +} diff --git a/PlotDirector.NativeCompanion/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props index a1899b58..a8e52b28 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.5 +1.0.0.6 diff --git a/PlotDirector.NativeCompanion/Protocol/Messages.cs b/PlotDirector.NativeCompanion/Protocol/Messages.cs index b5e4fc0b..c7a43241 100644 --- a/PlotDirector.NativeCompanion/Protocol/Messages.cs +++ b/PlotDirector.NativeCompanion/Protocol/Messages.cs @@ -5,6 +5,7 @@ namespace PlotDirector.Companion.Protocol; public static class ProtocolVersion { public const int Current = 1; + public const string WorkflowCapability = "workspace-review-v1"; public const string ChapterAiCapability = "chapter-ai-v2"; public const string AnalysisCapability = "structure-review-v1"; public const int AnalysisPageSize = 40; @@ -43,6 +44,11 @@ public sealed class Message [DataMember] public int? SceneId { get; set; } [DataMember] public string ChapterTitle { get; set; } = ""; [DataMember] public string SceneTitle { get; set; } = ""; + [DataMember] public ConnectionHealth? Health {get;set;} + [DataMember] public SavedWorkspace? Workspace {get;set;} + [DataMember] public ImportPreviewRequest? ImportSelection {get;set;} + [DataMember] public ImportPreview? ImportPreview {get;set;} + [DataMember] public string Action {get;set;}=""; [DataMember] public Guid AuthenticationContext { get; set; } [DataMember] public string ServerUrl { get; set; } = ""; [DataMember] public AiChapterResult? Ai { get; set; } diff --git a/PlotDirector.NativeCompanion/Protocol/WorkflowContracts.cs b/PlotDirector.NativeCompanion/Protocol/WorkflowContracts.cs new file mode 100644 index 00000000..a15f0598 --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/WorkflowContracts.cs @@ -0,0 +1,51 @@ +using System.Runtime.Serialization; +namespace PlotDirector.Companion.Protocol; + +[DataContract] +public sealed class ConnectionHealth +{ + [DataMember] public string Server {get;set;}="unknown"; + [DataMember] public string Authentication {get;set;}="signed-out"; + [DataMember] public string Ai {get;set;}="unknown"; + [DataMember] public string Explanation {get;set;}="Use Connect to sign in; local structure detection works offline."; + [DataMember] public DateTime VerifiedUtc {get;set;} + [DataMember] public DateTime ExpiresUtc {get;set;} +} +[DataContract] +public sealed class SavedWorkspace +{ + [DataMember] public int BookId {get;set;} + [DataMember] public int ProjectId {get;set;} + [DataMember] public int? ChapterId {get;set;} + [DataMember] public int? SceneId {get;set;} + [DataMember] public string Title {get;set;}=""; + [DataMember] public string Context {get;set;}=""; + [DataMember] public string Intent {get;set;}=""; + [DataMember] public string ContextPath {get;set;}=""; + [DataMember] public string IntentPath {get;set;}=""; + [DataMember] public string BookPath {get;set;}=""; + [DataMember] public string State {get;set;}="unselected"; +} +[DataContract] +public sealed class ImportPreviewRequest +{ + [DataMember] public Guid RequestId {get;set;} + [DataMember] public Guid SessionId {get;set;} + [DataMember] public Guid SnapshotId {get;set;} + [DataMember] public Guid ManuscriptId {get;set;} + [DataMember] public int BookId {get;set;} + [DataMember] public StructureSuggestion[] Items {get;set;}=Array.Empty(); +} +[DataContract] +public sealed class ImportPreview +{ + [DataMember] public Guid RequestId {get;set;} + [DataMember] public string State {get;set;}=""; + [DataMember] public string Message {get;set;}=""; + [DataMember] public int Chapters {get;set;} + [DataMember] public int Scenes {get;set;} + [DataMember] public int ExistingChapters {get;set;} + [DataMember] public int ExistingScenes {get;set;} + [DataMember] public string BookPath {get;set;}=""; + [DataMember] public bool CommitAvailable {get;set;} +} diff --git a/PlotDirector.NativeCompanion/README.md b/PlotDirector.NativeCompanion/README.md index 19fd3241..8356f824 100644 --- a/PlotDirector.NativeCompanion/README.md +++ b/PlotDirector.NativeCompanion/README.md @@ -1,3 +1,7 @@ +# Current developer build: Phase 3.5 + +Version **1.0.0.6** adds per-document book binding, verified connection status, saved Context/Intent and read-only import preview. See [qualification](WindowsValidation/Phase35-Integration.md) and [implementation report](../Docs/WordCompanion/2026-11-05-phase35-integration.md). Native import commit and native live SignalR following remain unavailable. + # Native Word Companion — developer foundation, structure and AI review Phase 3 adds explicit chapter-by-chapter AI review through the existing PlotDirector chapter service, browser-approved sign-in, a hierarchical native review and safe update/build plus explicit per-user installation scripts. See the [Phase 3 implementation report](../Docs/WordCompanion/2026-11-05-phase3-ai-integration.md) and [Windows workflow](WindowsValidation/Phase3-AI.md). The baseline implementation details below describe the foundation; Phase 3's native API does not provide prose synchronization or native Context/Intent/SignalR following. diff --git a/PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs b/PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs index 0d24ec47..142cb0ba 100644 --- a/PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs +++ b/PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs @@ -70,6 +70,7 @@ internal static class ChapterAiTests protected override async Task SendAsync(HttpRequestMessage request,CancellationToken cancellation) { var path=request.RequestUri!.AbsolutePath; + if(path.EndsWith("/connection"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow,ExpiresUtc=DateTime.UtcNow.AddHours(4)})}; if(path.EndsWith("/pair"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new{code=new string('A',24)})}; if(path.EndsWith("/token"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new{accessToken="test-only-grant"})}; if(path.EndsWith("/books"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new[]{new CompanionBook{BookId=11,Title="Synthetic test book"}})}; diff --git a/PlotDirector.NativeCompanion/Tests/Program.cs b/PlotDirector.NativeCompanion/Tests/Program.cs index 7213b3a2..3a74233a 100644 --- a/PlotDirector.NativeCompanion/Tests/Program.cs +++ b/PlotDirector.NativeCompanion/Tests/Program.cs @@ -162,4 +162,5 @@ using(var stalledClient=new AgentLink(stalledName,Guid.NewGuid(),_=>true)) } await AnalysisTests.Run(Check); await ChapterAiTests.Run(Check); +await WorkflowTests.Run(Check); Console.WriteLine($"Native foundation: {passed} checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified."); diff --git a/PlotDirector.NativeCompanion/Tests/WorkflowTests.cs b/PlotDirector.NativeCompanion/Tests/WorkflowTests.cs new file mode 100644 index 00000000..9c3e4703 --- /dev/null +++ b/PlotDirector.NativeCompanion/Tests/WorkflowTests.cs @@ -0,0 +1,60 @@ +using System.Net; +using System.Net.Http.Json; +using PlotDirector.Companion.Agent; +using PlotDirector.Companion.Client; +using PlotDirector.Companion.Protocol; + +internal static class WorkflowTests +{ + public static async Task Run(Action check) + { + var health=new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow.AddMinutes(-3)}; + check(ConnectionPresentation.Describe("connected",health,11,"saved-book").Contains("unverified")&&ConnectionPresentation.Describe("connected",health,11,"saved-book").Contains("cached grant"),"expired verification never presents cached sign-in/book as live"); + check(ConnectionPresentation.Describe("offline",health,11,"saved-book").Contains("Server/authentication: unverified"),"IPC outage overrides previously successful server state"); + var binding=new DocumentBinding();var auth=Guid.NewGuid();binding.Select(11,auth);var old=binding.Id;binding.Select(12,auth); + check(!binding.Accept(new(){SnapshotId=old,AuthenticationContext=auth,BookId=11,Workspace=new(){Title="old"}})&&binding.Workspace.Title=="","book switch rejects late saved data"); + var requestId=Guid.NewGuid();binding.BeginPreview(requestId);binding.CancelPreview();binding.Accept(new(){SnapshotId=binding.Id,AuthenticationContext=auth,BookId=12,ImportPreview=new(){RequestId=requestId,State="validated-preview"}}); + check(binding.Preview?.State=="cancelled","late successful response cannot revive a cancelled client preview"); + var selection=new StructureSelection();var parent=new StructureSuggestion{Kind="Chapter",Start=0,Origin="Existing marker"};selection.Set(parent,true);selection.Set(new(){Kind="Chapter",Start=0,Origin="Local structure"},true); + check(selection.Items.Length==1,"one parent chapter is retained across local and AI pages"); + for(var i=1;i<80;i++)selection.Set(new(){Kind="Scene",Start=i,Origin="AI"},true); + check(!selection.Set(new(){Kind="Scene",Start=100,Origin="AI"},true)&&selection.Items.Length==80,"cross-page preview selection is bounded without silently dropping selected rows"); + var handler=new Server();using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://fixture.invalid/");await Wait(()=>cloud.Status().Status.StartsWith("Signed in"));await cloud.CheckConnection(); + await Wait(()=>cloud.Status().Health?.Ai=="configured");var context=cloud.Status().AuthenticationContext; + var work=new DocumentWorkspaceWork(cloud);var one=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Revision=1};var two=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Revision=1}; + var first=Guid.NewGuid();var second=Guid.NewGuid(); + Message Send(DocumentDescriptor d,string kind,int book,Guid id,ImportPreviewRequest? plan=null)=>work.Handle(d,new(){Kind=kind,BookId=book,SnapshotId=id,AuthenticationContext=context,ImportSelection=plan},new(){Status="ok",SnapshotId=id}); + Send(one,"workspace-select",11,first);Send(two,"workspace-select",12,second); + await Wait(()=>Send(one,"workspace-status",11,first).Workspace?.State=="saved-book"&&Send(two,"workspace-status",12,second).Workspace?.State=="saved-book"); + check(Send(one,"workspace-status",11,first).Workspace?.BookId==11&&Send(two,"workspace-status",12,second).Workspace?.BookId==12,"multiple document saved contexts remain isolated"); + var replacement=Guid.NewGuid();Send(one,"workspace-select",12,replacement); + check(Send(one,"workspace-status",11,first).Status=="obsolete-workspace","older workspace binding cannot fetch or overwrite a replacement"); + Send(one,"workspace-preview",12,replacement,new(){BookId=12,SessionId=one.SessionId,SnapshotId=Guid.NewGuid(),RequestId=Guid.NewGuid(),Items=[new(){Kind="Chapter",Title="Chapter",Start=0,End=10}]}); + await Wait(()=>Send(one,"workspace-status",12,replacement).ImportPreview!=null); + Send(one,"workspace-cancel-preview",12,replacement);await Task.Delay(100); + check(Send(one,"workspace-status",12,replacement).ImportPreview==null,"cancelled import preview cannot reappear after delayed completion"); + handler.Offline=true;await cloud.CheckConnection();check(cloud.Status().Health?.Server=="offline","server loss clears a previously verified online indicator"); + handler.Offline=false;await cloud.CheckConnection();check(cloud.Status().Health?.Server=="online","explicit connection check detects recovery"); + handler.Expired=true;await cloud.CheckConnection();check(cloud.Status().AuthenticationContext!=context&&cloud.Status().Health?.Authentication=="expired","authentication expiry rotates scope and removes verified authentication"); + check(Send(two,"workspace-status",12,second).Status=="authentication-changed","expired credentials cannot display an old authenticated workspace"); + work.Clear(one.SessionId);work.Clear(two.SessionId); + } + private static async Task Wait(Func ready){using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(12));while(!ready())await Task.Delay(20,timeout.Token);} + private sealed class Server:HttpMessageHandler + { + public bool Offline,Expired; + protected override async Task SendAsync(HttpRequestMessage request,CancellationToken token) + { + if(Offline)throw new HttpRequestException();var path=request.RequestUri!.AbsolutePath; + if(path.EndsWith("/pair"))return Ok(new{code=new string('A',24)}); + if(path.EndsWith("/token"))return Ok(new{accessToken="test"}); + if(Expired)return new(HttpStatusCode.Unauthorized); + if(path.EndsWith("/books"))return Ok(new[]{new CompanionBook{BookId=11,Title="One"},new CompanionBook{BookId=12,Title="Two"}}); + if(path.EndsWith("/connection"))return Ok(new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow,ExpiresUtc=DateTime.UtcNow.AddHours(4)}); + if(path.EndsWith("/workspace")){var id=int.Parse(path.Split('/')[4]);return Ok(new SavedWorkspace{BookId=id,State="saved-book",Title="Saved book "+id,Context="Saved context",Intent="Saved goals"});} + if(path.EndsWith("/import-preview")){await Task.Delay(80,token);return Ok(new ImportPreview{State="validated-preview",CommitAvailable=false});} + return new(HttpStatusCode.NotFound); + } + private static HttpResponseMessage Ok(T value)=>new(HttpStatusCode.OK){Content=JsonContent.Create(value)}; + } +} diff --git a/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs b/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs index e483a5fc..a629a655 100644 --- a/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs +++ b/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs @@ -14,16 +14,26 @@ namespace PlotDirector.WordAddIn private readonly Label status=new Label{AutoSize=true,MaximumSize=new Size(1100,0),Margin=new Padding(8)}; private readonly ProgressBar progress=new ProgressBar{Dock=DockStyle.Fill,Height=6,Maximum=100}; private readonly TreeView local=new TreeView{Dock=DockStyle.Fill,CheckBoxes=true,HideSelection=false,ShowNodeToolTips=true}; - private readonly TreeView ai=new TreeView{Dock=DockStyle.Fill,HideSelection=false,ShowNodeToolTips=true}; + private readonly TreeView ai=new TreeView{CheckBoxes=true,Dock=DockStyle.Fill,HideSelection=false,ShowNodeToolTips=true}; private readonly TextBox details=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical}; private readonly ComboBox books=new ComboBox{DropDownStyle=ComboBoxStyle.DropDownList,Width=300,DisplayMember="Title",ValueMember="BookId"}; private readonly Label pages=new Label{AutoSize=true,Margin=new Padding(8)}; private readonly Button cancel=new Button{Text="Cancel",AutoSize=true}; private readonly Button next=new Button{Text="Next",AutoSize=true},previous=new Button{Text="Previous",AutoSize=true}; private readonly TabControl tabs=new TabControl{Dock=DockStyle.Fill}; + private bool rebinding; + private readonly Dictionary selectionSnapshots=new Dictionary(); + private readonly Dictionary choices=new Dictionary(); + private StructureSelection selection=new StructureSelection(); + private readonly TextBox savedContext=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical}; + private readonly TextBox savedIntent=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical}; + private readonly TextBox previewText=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical}; + private readonly Button ask=new Button{Text="AI: analyse checked chapters",AutoSize=true}; + private readonly Button previewButton=new Button{Text="Preview selected import",AutoSize=true}; + private readonly Button openContext=new Button{Text="Open full saved Context",AutoSize=true},openIntent=new Button{Text="Open saved Intent",AutoSize=true},openBook=new Button{Text="Continue in PlotDirector",AutoSize=true}; private int aiOffset;private Guid session,authenticationContext,localSnapshot;private string renderKey="";private string bookKey="";private string aiRenderKey=""; private IList aiItems=new List(); - public AnalysisWindow(Action analyse,Action stop,Action page,Action submit,Action navigate) + public AnalysisWindow(Action analyse,Action stop,Action page,Action submit,Action navigate,Action selectBook,Action previewImport,Action open,Action checkConnection) { Text="PlotDirector — Manuscript review";Font=new Font("Segoe UI",9F);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new Size(680,480);Width=980;Height=680;ShowInTaskbar=false; status.MaximumSize=new Size(Math.Max(400,ClientSize.Width-40),0); @@ -33,18 +43,33 @@ namespace PlotDirector.WordAddIn layout.RowStyles.Add(new RowStyle(SizeType.Percent,70));layout.RowStyles.Add(new RowStyle(SizeType.Percent,30));layout.RowStyles.Add(new RowStyle(SizeType.AutoSize)); var actions=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,WrapContents=true,Padding=new Padding(0,6,0,6)}; var repeat=new Button{Text="Detect structure",AutoSize=true};repeat.Click+=(_,__)=>analyse(); - var ask=new Button{Text="AI: analyse checked chapters",AutoSize=true};ask.Click+=(_,__)=>{ - var chosen=local.Nodes.Cast().Where(n=>n.Checked&&n.Tag is StructureSuggestion).Select(n=>(StructureSuggestion)n.Tag).ToArray(); + ask.Click+=(_,__)=>{ + var chosen=selection.Items.Where(item=>item.Kind=="Chapter").ToArray(); if(chosen.Length==0){MessageBox.Show("Check one or more chapter nodes in Local structure first.","PlotDirector");return;} var consent=new AiConsent{SessionId=session,SnapshotId=localSnapshot,AuthenticationContext=authenticationContext,BookId=SelectedBook,Chapters=chosen}; if(consent.BookId<=0){MessageBox.Show("Connect, then select an authorised PlotDirector book.","PlotDirector");return;} if(MessageBox.Show("Send "+chosen.Length+" selected chapter(s) for book "+(books.SelectedItem as CompanionBook)?.Title+" to PlotDirector's configured AI provider? This may incur AI costs. Existing markers and manuscript text will not change.","Confirm chapter upload",MessageBoxButtons.OKCancel)==DialogResult.OK)submit(consent); }; - cancel.Click+=(_,__)=>stop();actions.Controls.AddRange(new Control[]{repeat,books,ask,cancel}); - var localTab=new TabPage("Local structure");localTab.Controls.Add(local);var aiTab=new TabPage("AI scene suggestions");aiTab.Controls.Add(ai);tabs.TabPages.AddRange(new[]{localTab,aiTab}); + cancel.Click+=(_,__)=>{if(tabs.SelectedIndex==4)previewText.Text="Preview cancelled; no records changed.";stop();}; + books.SelectedIndexChanged+=(_,__)=>{if(!rebinding){selectBook(SelectedBook);previewText.Clear();}}; + var check=new Button{Text="Check connection",AutoSize=true};check.Click+=(_,__)=>checkConnection(); + previewButton.Click+=(_,__)=>{ + var chosen=selection.Items;if(chosen.Length==0){details.Text="Check chapter and scene rows to preview. Parent chapters are required; choose one local/AI interpretation at each position.";return;} + var consent=new AiConsent{SessionId=session,SnapshotId=localSnapshot,AuthenticationContext=authenticationContext,BookId=SelectedBook,Chapters=chosen}; + if(MessageBox.Show("Send selected titles and structural positions to PlotDirector for a read-only import preview? No prose is uploaded and nothing is committed.","Preview import",MessageBoxButtons.OKCancel)==DialogResult.OK){previewImport(consent);tabs.SelectedIndex=4;previewText.Text="Preparing a read-only server preview…";} + }; + var clear=new Button{Text="Clear selection",AutoSize=true};clear.Click+=(_,__)=>{selection.Clear();rebinding=true;foreach(TreeNode node in local.Nodes){node.Checked=false;foreach(TreeNode child in node.Nodes)child.Checked=false;}foreach(TreeNode node in ai.Nodes){node.Checked=false;foreach(TreeNode child in node.Nodes)child.Checked=false;}rebinding=false;}; + actions.Controls.AddRange(new Control[]{repeat,books,ask,previewButton,clear,cancel,check}); + var localTab=new TabPage("Local structure");localTab.Controls.Add(local);var aiTab=new TabPage("AI scene suggestions");aiTab.Controls.Add(ai);var contextTab=new TabPage("Context · saved data");var intentTab=new TabPage("Intent · saved objectives");var importTab=new TabPage("Import preview"); + contextTab.Controls.Add(savedContext);openContext.Dock=DockStyle.Bottom;contextTab.Controls.Add(openContext); + intentTab.Controls.Add(savedIntent);openIntent.Dock=DockStyle.Bottom;intentTab.Controls.Add(openIntent); + importTab.Controls.Add(previewText);openBook.Dock=DockStyle.Bottom;importTab.Controls.Add(openBook); + openContext.Click+=(_,__)=>open("context");openIntent.Click+=(_,__)=>open("intent");openBook.Click+=(_,__)=>open("book"); + tabs.TabPages.AddRange(new[]{localTab,aiTab,contextTab,intentTab,importTab}); + local.AfterCheck+=Checked;ai.AfterCheck+=Checked; var footer=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true};footer.Controls.AddRange(new Control[]{previous,next,pages}); - previous.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(-1);else{aiOffset=Math.Max(0,aiOffset-40);RenderAi();}}; - next.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(1);else{aiOffset+=40;RenderAi();}}; + previous.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(-1);else if(tabs.SelectedIndex==1){aiOffset=Math.Max(0,aiOffset-40);RenderAi();}}; + next.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(1);else if(tabs.SelectedIndex==1){aiOffset+=40;RenderAi();}}; tabs.SelectedIndexChanged+=(_,__)=>{details.Text="Select a result to inspect its source and reasoning.";if(tabs.SelectedIndex==1)RenderAi();else UpdatePages();}; local.AfterSelect+=(_,e)=>Inspect(e.Node);ai.AfterSelect+=(_,e)=>Inspect(e.Node); local.NodeMouseDoubleClick+=(_,e)=>{if(e.Node.Tag is StructureSuggestion item)navigate(item);}; @@ -52,19 +77,32 @@ namespace PlotDirector.WordAddIn layout.Controls.Add(status,0,0);layout.Controls.Add(progress,0,1);layout.Controls.Add(actions,0,2);layout.Controls.Add(tabs,0,3);layout.Controls.Add(details,0,4);layout.Controls.Add(footer,0,5);Controls.Add(layout); Resize+=(_,__)=>status.MaximumSize=new Size(Math.Max(400,ClientSize.Width-40),0); } - public void ForgetBookSelection(){books.SelectedIndex=-1;} + public void ForgetBookSelection(){rebinding=true;try{books.SelectedIndex=-1;}finally{rebinding=false;}} public int SelectedBook=>books.SelectedItem is CompanionBook book?book.BookId:0; private AnalysisPage current; - public void Render(AnalysisReview review,string connection,Guid document,string documentName,Guid authentication,CompanionBook[] available,string cloud,string aiStatus,IList results,bool running) + public void Render(AnalysisReview review,string connection,Guid document,string documentName,Guid authentication,CompanionBook[] available,string cloud,string aiStatus,IList results,bool running,DocumentBinding binding,ConnectionHealth health,bool workflowSupported) { - if(session!=document){session=document;renderKey="";aiRenderKey="";books.SelectedIndex=-1;aiOffset=0;local.Nodes.Clear();ai.Nodes.Clear();details.Clear();} + if(session!=document){session=document;renderKey="";aiRenderKey="";ForgetBookSelection();aiOffset=0;local.Nodes.Clear();ai.Nodes.Clear();details.Clear();} + if(!choices.TryGetValue(document,out selection)){if(choices.Count>=32){choices.Clear();selectionSnapshots.Clear();}selection=new StructureSelection();choices[document]=selection;} + var snapshot=review?.SnapshotId??Guid.Empty;if(selectionSnapshots.TryGetValue(document,out var previousSnapshot)&&previousSnapshot!=snapshot)selection.Clear();selectionSnapshots[document]=snapshot; authenticationContext=authentication;localSnapshot=review?.SnapshotId??Guid.Empty; current=review?.Page;aiItems=results??new List(); - status.Text=(documentName??"No active document")+" · Agent: "+connection+" · "+cloud+"\n"+(string.IsNullOrEmpty(aiStatus)?review?.Status:aiStatus); + status.Text=(documentName??"No active document")+" · Agent: "+connection+" · "+cloud+"\n"+(review?.Running==true?review.Status:string.IsNullOrEmpty(aiStatus)?review?.Status:aiStatus); if(current!=null)status.Text+="\n"+current.WordCount.ToString("N0")+" approximate words · "+current.ChapterCount+" local chapter candidates · "+current.SceneCount+" local scene candidates. "+(current.Truncated?"Result limit reached. ":"")+"Double-click to navigate; select to inspect evidence."; - progress.Value=review?.Progress??0;cancel.Enabled=running||review?.Running==true; + progress.Value=review?.Progress??0;cancel.Enabled=running||review?.Running==true||binding?.Preview?.State=="loading"; + var workspace=binding?.Workspace; + var verified=workspace?.State?.StartsWith("saved-",StringComparison.Ordinal)==true; + savedContext.Text=(workspace?.Title??"No book selected")+"\r\nSaved PlotDirector data · read-only · "+(workspace?.State??"unselected")+"\r\n\r\n"+(string.IsNullOrWhiteSpace(workspace?.Context)?"No saved context for this location. Select a book; recognised saved chapter/scene markers are verified against that book. Local/AI suggestions do not create saved context.":workspace.Context); + savedIntent.Text=(workspace?.Title??"No book selected")+"\r\nSaved writing objectives · read-only · "+(workspace?.State??"unselected")+"\r\n\r\n"+(string.IsNullOrWhiteSpace(workspace?.Intent)?"No saved writing objective at this location. Set chapter goals or scene purpose in PlotDirector; no intent is invented or silently saved here.":workspace.Intent); + openContext.Enabled=verified&&!string.IsNullOrEmpty(workspace.ContextPath);openIntent.Enabled=verified&&!string.IsNullOrEmpty(workspace.IntentPath);openBook.Enabled=verified; + var plan=binding?.Preview; + if(plan!=null)previewText.Text=plan.State+"\r\nSelected: "+plan.Chapters+" chapters / "+plan.Scenes+" scenes\r\nAlready saved: "+plan.ExistingChapters+" chapters / "+plan.ExistingScenes+" scenes\r\n\r\n"+plan.Message+"\r\n\r\nCreated: 0. Replaced: 0. Native commit is unavailable; use the established PlotDirector workflow."; + else previewText.Text="Select chapter and scene rows, then Preview selected import. This validates the target through PlotDirector's existing importer. Native commit is unavailable; selections are not silently transferred to onboarding."; + var fresh=health!=null&&DateTime.UtcNow-health.VerifiedUtcb.BookId+":"+b.Title)); - if(bookKey!=key){var selected=SelectedBook;bookKey=key;books.DataSource=available;books.SelectedIndex=-1;if(available.Any(b=>b.BookId==selected))books.SelectedValue=selected;} + rebinding=true;try{if(bookKey!=key){bookKey=key;books.DataSource=available;books.DropDownWidth=650;}var selected=binding?.BookId??0;if(available.Any(b=>b.BookId==selected))books.SelectedValue=selected;else books.SelectedIndex=-1;}finally{rebinding=false;} var newKey=(review?.SnapshotId.ToString()??"")+":"+(current?.Offset??-1); if(renderKey!=newKey){renderKey=newKey;details.Text="Select a result to inspect its source and reasoning.";Fill(local,current?.Items??Array.Empty());} if(tabs.SelectedIndex==1)RenderAi();else UpdatePages(); @@ -73,22 +111,29 @@ namespace PlotDirector.WordAddIn {if(node.Tag is StructureSuggestion item)details.Text=item.Title+Environment.NewLine+item.Origin+" · "+item.Confidence+Environment.NewLine+item.Reason+Environment.NewLine+"Word position "+item.Start+". Double-click to navigate without changing text.";} private void Fill(TreeView tree,IEnumerable values) { - tree.BeginUpdate();try{tree.Nodes.Clear();var parents=new Dictionary(); + rebinding=true;tree.BeginUpdate();try{tree.Nodes.Clear();var parents=new Dictionary(); foreach(var item in values) { var chapterStart=item.Kind=="Chapter"?item.Start:item.ChapterStart; if(!parents.TryGetValue(chapterStart,out var parent)) { var chapter=item.Kind=="Chapter"?item:new StructureSuggestion{Kind="Chapter",Start=chapterStart,End=item.ChapterEnd,Title=string.IsNullOrEmpty(item.ChapterTitle)?"Before first chapter / unassigned":item.ChapterTitle,Origin="Local structure",Reason="Chapter context for this results page."}; - parent=new TreeNode("Chapter · "+chapter.Title){Tag=chapterStart>=0?(object)chapter:null,ToolTipText=chapter.Title};parents.Add(chapterStart,parent);tree.Nodes.Add(parent); + parent=new TreeNode("Chapter · "+chapter.Title){Checked=selection.Contains(chapter),Tag=chapterStart>=0?(object)chapter:null,ToolTipText=chapter.Title};parents.Add(chapterStart,parent);tree.Nodes.Add(parent); } - if(item.Kind!="Chapter")parent.Nodes.Add(new TreeNode(item.Title+" ["+item.Origin+"]"){Tag=item,ToolTipText=item.Title}); + if(item.Kind!="Chapter")parent.Nodes.Add(new TreeNode(item.Title+" ["+item.Origin+"]"){Checked=selection.Contains(item),Tag=item,ToolTipText=item.Title}); } - tree.ExpandAll();}finally{tree.EndUpdate();} + tree.ExpandAll();}finally{tree.EndUpdate();rebinding=false;} } private void RenderAi(){if(aiOffset>=aiItems.Count)aiOffset=0;var key=aiOffset+":"+aiItems.Count+":"+session+string.Join("|",aiItems.Skip(aiOffset).Take(40).Select(s=>s.Start+":"+s.Title+":"+s.Reason));if(aiRenderKey!=key){aiRenderKey=key;Fill(ai,aiItems.Skip(aiOffset).Take(40));}UpdatePages();} + private void Checked(object sender,TreeViewEventArgs args) + { + if(rebinding||!(args.Node.Tag is StructureSuggestion item))return; + if(!selection.Set(item,args.Node.Checked)){rebinding=true;args.Node.Checked=false;rebinding=false;details.Text="Preview selection is limited to 80 rows. Use smaller batches.";} + if(args.Action!=TreeViewAction.Unknown)foreach(TreeNode child in args.Node.Nodes)child.Checked=args.Node.Checked; + } private void UpdatePages() { + if(tabs.SelectedIndex>1){previous.Enabled=false;next.Enabled=false;pages.Text="Read-only saved data / preview; no automatic changes";return;} var offset=tabs.SelectedIndex==0?(current?.Offset??0):aiOffset;var total=tabs.SelectedIndex==0?(current?.Total??0):aiItems.Count; pages.Text=total==0?"No results":"Showing "+(offset+1)+"–"+Math.Min(total,offset+40)+" of "+total; previous.Enabled=offset>0;next.Enabled=offset+40 "Agent: " + (getAdapter()?.ConnectionState ?? "Unavailable")+" · "+(getAdapter()?.CloudState??"Not signed in"); - public bool CanSynchronize(Office.IRibbonControl _) => getAdapter()?.HasActiveDocument == true; + public string GetStatus(Office.IRibbonControl _) => string.Join(" · ",(getAdapter()?.StatusSummary??"Word add-in unavailable").Split('·').Take(3)); + public string GetScopeStatus(Office.IRibbonControl _) => string.Join(" · ",(getAdapter()?.StatusSummary??"").Split('·').Skip(3)); + public bool CanSynchronize(Office.IRibbonControl _) => getAdapter()?.HasActiveDocument == true&&getAdapter()?.ConnectionState=="connected"; + public bool CanCancel(Office.IRibbonControl _) => getAdapter()?.HasActiveWork==true; public void Connect(Office.IRibbonControl _) { var adapter=getAdapter();if(adapter!=null)new ConnectWindow(adapter).Show(); } public void Analyse(Office.IRibbonControl _) { getAdapter()?.AnalyseDocument(); } public void Cancel(Office.IRibbonControl _) { getAdapter()?.CancelAnalysis(); } - public void Synchronize(Office.IRibbonControl _) { getAdapter()?.RequestSnapshot(); } + public void Synchronize(Office.IRibbonControl _) { getAdapter()?.AnalyseDocument(); } public void Settings(Office.IRibbonControl _) { if (getAdapter() == null) return; diff --git a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs index 9e8fe54d..70c3f7c4 100644 --- a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs +++ b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs @@ -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.5")] -[assembly: AssemblyFileVersion("1.0.0.5")] +[assembly: AssemblyVersion("1.0.0.6")] +[assembly: AssemblyFileVersion("1.0.0.6")] [assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml index 1d894576..d6173393 100644 --- a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml +++ b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml @@ -2,10 +2,10 @@ +