feat(sessions): session lifecycle UI (S2.3) (#28)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Each Session is a conversation Museion UIs, never owns. The mentor bridge hosts multiple engine-owned sessions: per-session transcripts keyed by wire sessionId behind same-named proxies (every existing caller compiles unchanged), a names-only roster at Application Support/sessions.json (0600; id/name/pieceTitle/date — the words stay engine-owned per ADR-0007), and the standard affordances over the wire: session/new, session/load, session/fork, compact as the /compress slash prompt, session/cancel as the Stop rail. The Sessions pane replaces its placeholder: roster list (piece- associated by name when Posts has an open piece), row-click resume with the engine's full-history replay (user turns included), Fork · Compact, live streaming with Stop; every pass auto-creates its rostered session and streams into it; the transcript renderer is shared with the mentor pane. Notification hops ride the main queue (FIFO with the continuation resume) so the adapter's replay-before- response contract is guaranteed, not probabilistic. Resume refusals are honest and entry-attributed (an engine-unknown session never fabricates history); concurrent replays refuse instead of interleaving; restart replays from the engine rather than trusting a diverging local copy. Finish-audit (three reviewers) surfaced the concurrent-resume race, the dead restart branch, the runPass guard window, the 15 s session/load default, and the missing createSession backstop — all fixed and pinned (12 lifecycle pins; 359 tests green). Closes #28
This commit is contained in:
1 parent
78c8844184
commit
9895614b7e
15 files changed
+1523
-245
No files matched your search
+6
-5
@@ -14,19 +14,19 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
- `AppMetadata` is the single source for the displayed app name and tagline; members are `nonisolated` (default-MainActor project).
|
||||
- Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 27.0 (bumped from 26.5 with the Xcode 27 settings pass — all six project configs, tests included, stay aligned or the test targets can't link the app module); bundle id `com.babylondreams.Museion`.
|
||||
- App Sandbox is OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime stays ON for Developer ID notarization. No `.entitlements` file.
|
||||
- No persistence layer yet — the SwiftData template was stripped; vault-vs-database gets an ADR when the need is real. Exception: the engine gate's `state.json` (see below).
|
||||
- No persistence layer yet — the SwiftData template was stripped; vault-vs-database gets an ADR when the need is real. Exceptions (both app metadata, never content): the engine gate's `state.json` and the session roster's `sessions.json` (#28 — names/ids only; transcripts stay engine-owned per ADR-0007).
|
||||
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean.
|
||||
- App icon: `Assets.xcassets/AppIcon.appiconset` — single-size 1024×1024 PNG (`Museion-Logo_1024.png`); Xcode derives all sizes. The built icns tops out at 256 px entries — that matches Apple's own apps on this macOS; larger sizes come from the catalog.
|
||||
|
||||
## Workspace shell (M1, #17 + #18 / S1.1)
|
||||
|
||||
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette.
|
||||
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions stays an honest placeholder until #28; **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `<home>/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `<project>` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included). **#114 (S4):** the fourth ask — `ConvertSheet` (`convertAskBinding`) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (= `cancelConversion`); a ladder-drops-prose warning when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip).
|
||||
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (plain + button; becomes a Menu — "New Session" / "New Session on \<title\>" — when Posts has an open piece; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView`. Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, Fork · Compact bordered mono-11, both disabled on `!canStartSession`) + the liveness row (ProgressView + Stop → `stopStreaming` — cancel works from the pane) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer lives in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates. **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `<home>/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `<project>` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGLine truncated
|
||||
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse.
|
||||
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
|
||||
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; body/origin/type preserved through the existingStamp→stamped round-trip; vanished piece throws). **#27 (S4.2):** `advancePassState` also ticks the decay clock — `try? LearningDecay.recordPass(home:type:)` after the stamped write (every completed pass counts, re-runs included; `try?` because a failed bump must never fail a completed pass, and a lagging clock only delays resurfacLine truncated
|
||||
- `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing line "Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent).
|
||||
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the sessionLine truncated
|
||||
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the sessionLine truncated
|
||||
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here.
|
||||
- `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions.
|
||||
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
|
||||
@@ -71,8 +71,9 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
## ACP bridge (S2.2, #14 map)
|
||||
|
||||
- `ACPEngineClient.swift` — `ACPEngineClient` (nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client for `hermes acp -p museion` (ponytail: no Swift SDK exists; revisit if one appears). Wire facts baked in (verified adapter 0.21.5 + acp SDK): one JSON message per `\n` line, stdout = wire, stderr = logs (never parsed for state); `session/new` **requires `mcpServers`** (list; Museion sends `[]` — the #44 no-MCP-servers invariant on the wire); `session/cancel` is a *notification* (no response); responses camelCase; updates discriminate on `update.sessionUpdate`. `JSONValue` (nonisolated enum) is the decoded-wire value type. Serial queue confines all mutable state; requests time out (15 s default) — a hung engine surfaces as an error → restart prompt, never an eternal await; server→client requests get an auto `-32601` (M0 handles none — the deny option); crash/EOF fail pending requests and fire `onCrash` exactly once (latched — child-exit and stdout-EOF both arrive for one crash; never on explicit `close()`); `close()` = handlers-off → SIGTERM → 1 s grace → SIGKILL → reap (EngineProbe pattern); SIGPIPE ignored.
|
||||
- `MentorSessionModel.swift` — `MentorSessionModel` (@MainActor @Observable): pane state machine (idle/starting/ready/crashed; `isStreaming` Bool). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`), handshake `initialize` → advisory version compare vs state.json (`recordedVersionProvider` injectable; **compares base versions** — the gate records the derived version (`acp --version` → `0.21.5+2177.g735e426`) while the handshake answers the base (`agentInfo.version` → `0.21.5`), so raw string equality fabricates drift on every dev install; `baseVersion(of:)` strips `+`-build metadata; one os_log line + both versions in the pane, never blocks) → `session/new` cwd `~` + `mcpServers: []`. `sendPrompt` (#24 seam: `@discardableResult`, returns `TurnOutcome` — `.ended(stopReason:)` for any completion stopReason incl. `refusal`, `.cancelled` for `cancelled`, `.failed` on a thrown transport error or the not-ready/streaming guard refusal; the model appends NO extra row on cancel — the orchestrator owns pass wording) streams `agent_message_chunk` into a buffer flushed on turn end; **thought lane (#24 dogfood fix): `agent_thought_chunk` streams into its own `streamingThought` buffer** — a pass's thinking runs to hundreds of lines and conflating it with the critique made one giant blob; it flushes to a collapsed `.thought` row FIRST (it preceded the message), and `restart()` clears both buffers; an optional `label:` renders verbatim as the user row INSTEAD of the raw prompt (pass wire stubs never hit the transcript); **#23 dogfood fix: `sendPrompt` sends session/prompt with `promptTimeout` (nonisolated, 1800 s), NOT the client's 15 s request default** — the prompt response arrives when the TURN ends, minutes into a pass; the default abandoned live turns ("connection lost" while the engine kept working, Stop vanished with `isStreaming`; test-pinned `promptTimeout >= 600`); tool calls with fix-card-shaped `rawInput` (pattern+problem minimum) render as `FixCard` (ADR-0006 fields; **audit: the parser takes the nested `submit_fix_cards` argument shape first — `{piece_path, cards:[…]}`, snake_case, anchor as `{quote,occurrence}` object — the LIVE rail; the flat #14-era shape stays as fallback; the old flat-only parser never matched the real tool**); every other update type a collapsible raw-JSON row. **Audit hardening: a prompt response missing `stopReason` maps to `.failed` (a turn without stopReason never advances a pass), and `sendPrompt` guards the client instead of force-unwrapping.** Cancel = `session/cancel` notification, Stop button. Crash keeps transcript + last prompt; Restart re-spawns. `clientRef` mirror exists solely so nonisolated deinit can close the child.
|
||||
- `MentorPaneView.swift` — the debug pane, post-gate main surface (replaces the content placeholder): header (running version + orange drift note, trailing mini **Debug** checkbox — `@AppStorage("mentorDebugRows")`, off by default: the writing-session transcript filters to prose + card events via `isWritingRow` (static, test-pinned); raw session/tool rows, collapsed thinking, and live thinking render only when checked — the model keeps every row either way, so the toggle flips with history intact), transcript (text rows, fix-card tool calls as one-line `FixCardEventRow`s — pattern title only, the detail lives in the palette; RawUpdateRow disclosure; **#24 dogfood fix:** `defaultScrollAnchor(.bottom)` — programmatic `scrollTo` raced the growing lazy rows and mislanded at the TOP; `.thought` rows render collapsed (`ThoughtRow`, the engine's thinking — kept out of the critique text), live thinking shows muted + `lineLimit(3)`), freeform input 1…4 lines + send + Stop while streaming (**#23 dogfood fix:** a liveness row above the input — indeterminate `ProgressView` + "Mentor is working — Stop to interrupt." caption while `isStreaming`; minutes of silent tool work read as dead without it), crash card (Restart, last prompt, stderr tail behind Technical details; input + crash card live in a file-scope `private extension MentorPaneView` — type_body_length posture). **#24 (S3.1):** below the header a segmented **Pass 1 | Pass 2 | Chat** picker (the design contract's `.mentor-tabs`) — pass modes carry the pass bar (`PassBarView`, private): what the pass critiques + `PassContext.estimateTokens` cost line ("· ~N tokens") or "Open a post to run a pass.", the open piece's Pass State chip (library's post-meta voice), and the actions — Cancel (bordered, only while `posts.runningPass` streams) ↔ Run Pass N (borderedProminent; disabled with no open piece, engine not ready, or mid-turn). Chat hides the bar; transcript + input stay shared (the pass's streamed critique renders in the same transcript). `posts: PostsModel?` + `home: URL?` params (nil = previews); PostsPaneView's mentor column passes both. **#23 follow-up (dogfood):** card detail lives in the **Fix Cards palette** — a floating `Window` scene (id `fix-cards`, `FixCardsPalette` in `FixCardsWindow.swift`, `defaultSize` 340×540) beside About, opened via `openWindow` from a mono "Fix Cards · N" row below the pass bar (shown only when cards exist). The palette shows the open piece's title + `posts.openPieceCards` — **#25 (S3.2/S3.3): the card WORK surface, open cards first (scan order preserved: newest pass first, rank ascending), closed cards dimmed at 0.45 with their status in the meta and no actions**; row actions per lane: mechanical + valid → Apply + Skip, demonstration → Done + Skip (never Apply, ADR-0006), stale anchor → Skip only; Apply = ask-before, a BLOCKING sheet showing the exact edit (anchored quote → replacement, "(cut)" when the fix is empty) with Apply/Cancel — .stale swaps the sheet to the stale alert (no retry), .refused shows the reason inline; no apply-all, no batch, the sheet is the only path from Apply to a write (S3.3); meta carries `#rank`, "apply · ask-before" on appliable mechanical cards, and the footer line "apply = ask-before · one card at a time" (S2.5 trust visibility — nothing auto-applies, so never-do needs no control); stale anchors orange + "· stale anchor"; card meta leads with "pass N" when `provenance.pass` is stamped and re-contextualizes via `@Observable` as the open piece changes (**audit: the card scan runs detached off MainActor — typing re-triggers rescan; PostsModel.`title(of:)` + EditorSession.`passPieceURL`/`hasResearch` are the shared facts runPass, the pass bar, and the palette ride — three hand-copies deduped**); painted `DesignTokens.background` — app chrome warm, matching the rail, not document white. The transcript's live tool-call rendering is `FixCardEventRow` — the pattern title alone, one line; the verdict prose carries no card detail (pass-persona v1.2: the card is the finding's only full statement). **#26 (S4.1):** every card row gains Promote (bordered, small) between the primary action and Skip on open cards, alone on closed unpromoted cards — it outlives the card because the Learning is the durable artifact (the design contract's promote-resolved buttons); a promoted card shows `· promoted` in the meta and never re-offers. The ask is `PromoteAskSheet` (own file, OutlineRowTextView extraction precedent): the contract's #promoteDialog — "Promote to Learnings?", the consulted-on-future-Passes body line (type pluralized, "pieces" fallback), learning preview (pattern/problem/provenance via `title(of:)`), Cancel/Promote; ONE confirm → `promoteCard`, refusal inline orange with buttons kept (ApplyAskSheet posture).
|
||||
- `MentorSessionModel.swift` — `MentorSessionModel` (@MainActor @Observable): engine state machine (idle/starting/ready/crashed; `isStreaming` Bool; **#28: `.ready` carries NO sessionId — session ids live in the roster**). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`; **#28: openSession = spawn + ensure ONE session — the default freeform "Mentor" on first launch, the newest roster entry on relaunch, RESUMED (session/load replays its history — the review fix; a fresh transcript over an engine that knows the session would prompt/fork/compact against unloaded state)**), handshake `initialize` → advisory version compare vs state.json (`recordedVersionProvider` injectable; **compares base versions** — the gate records the derived version (`acp --version` → `0.21.5+2177.g735e426`) while the handshake answers the base (`agentInfo.version` → `0.21.5`), so raw string equality fabricates drift on every dev install; `baseVersion(of:)` strips `+`-build metadata; one os_log line + both versions in the pane, never blocks). **#28: the handshake is initialize ONLY — sessions are created separately (`newSession`/`beginPassSession`/`ensureDefaultSession`), the bridge is session-agnostic.** `sendPrompt` (#24 seam: `@discardableResult`, returns `TurnOutcome` — `.ended(stopReason:)` for any completion stopReason incl. `refusal`, `.cancelled` for `cancelled`, `.failed` on a thrown transport error or the not-ready/streaming guard refusal; the model appends NO extra row on cancel — the orchestrator owns pass wording) streams `agent_message_chunk` into a buffer flushed on turn end; **thought lane (#24 dogfood fix): `agent_thought_chunk` streams into its own `streamingThought` buffer** — a pass's thinking runs to hundreds of lines and conflating it with the critique made one giant blob; it flushes to a collapsed `.thought` row FIRST (it preceded the message), and `restart()` clears both buffers; an optional `label:` renders verbatim as the user row INSTEAD of the raw prompt (pass wire stubs never hit the transcript); **#23 dogfood fix: `sendPrompt` sends session/prompt with `promptTimeout` (nonisolated, 1800 s), NOT the client's 15 s request default** — the prompt response arrives when the TURN ends, minutes into a pass; the default abandoned live turns ("connection lost" while the engine kept working, Stop vanished with `isStreaming`; test-pinned `promptTimeout >= 600`); tool calls with fix-card-shaped `rawInput` (pattern+problem minimum) render as `FixCard` (ADR-0006 fields; **audit: the parser takes the nested `submit_fix_cards` argument shape first — `{piece_path, cards:[…]}`, snake_case, anchor as `{quote,occurrence}` object — the LIVE rail; the flat #14-era shape stays as fallback; the old flat-only parser never matched the real tool**); every other update type a collapsible raw-JSON row. **Audit hardening: a prompt response missing `stopReason` maps to `.failed` (a turn without stopReason never advances a pass), and `sendPrompt` guards the client instead of force-unwrapping.** Cancel = `session/cancel` notification, Stop button. Crash keeps transcript + last prompt; Restart re-spawns. `clientRef` mirror exists solely so nonisolated deinit can close the child.
|
||||
**#28 (S2.3) session lifecycle:** the model hosts MULTIPLE engine-owned sessions on the ONE bridge. Transcripts are per-session structs keyed by wire sessionId; `rows`/`streamingText`/`streamingThought` are same-named computed proxies over the ACTIVE session (every existing caller compiles unchanged). `SessionEntry` (nonisolated, Codable: `sessionId`/`name`/`pieceTitle`/`createdAt`) + `SessionRoster` (nonisolated; JSON array at `~/Library/Application Support/Museion/sessions.json`, `rosterDirectory` injectable — `init(binaryPath:rosterDirectory:)`; an injected-nil dir under hosted tests redirects to a unique temp dir so suites never touch the real roster; EngineGate's silent-fail write posture). **The roster persists NAMES ONLY — id/name/pieceTitle/createdAt (the "name/convention" of PRD S2.7); transcripts are engine-owned (ADR-0007: swap the engine, transcripts stay behind), replayed on demand.** API: `newSession(name:pieceTitle:)` (wire session/new, rostered newest-first, activated), `resumeSession(_)` (wire session/load — the adapter replays full history as `session/update` BEFORE responding; user turns arrive as `user_message_chunk` and RENDER on replay, live-turn echoes stay ignored; a result without sessionId = the engine doesn't know it → `false` + an honest row, entry stays rostered — never a fabricated empty session), `forkActiveSession()` (wire session/fork → "<name> (fork)", pieceTitle carried, fresh transcript; the adapter's empty-string sessionId = refusal), `compactActiveSession()` (the `/compress` slash prompt over the existing sendPrompt rail, label "Compact…" — the raw command never renders; refused while streaming), `beginPassSession(kind:pieceTitle:)` ("Pass N · \<title\>", rostered + activated — the pass auto-create rail), `canStartSession` (ready && !isStreaming — the pane's enable-flag), `transcriptRows(of:)` (internal — read any transcript without activating). Notification routing files updates under the PARAMS' sessionId (multi-session safe), not the active one; notification→MainActor hops ride `DispatchQueue.main.async`, NOT `Task { @MainActor }` — the unstructured-Task hops starved behind parallel test work (replay updates landed seconds late or never) and only the main queue gives FIFO ordering with the continuation resume, making the adapter's replay-before-response contract guaranteed rather than probabilistic.
|
||||
- `MentorPaneView.swift` — the debug pane (post #28 no longer the only session surface — Sessions pane shares the transcript renderer): header (running version + orange drift note — **#28: the version shows `activeEntry`'s id alongside, `.ready` no longer carries it**; trailing mini **Debug** checkbox — `@AppStorage("mentorDebugRows")`, off by default: the writing-session transcript filters to prose + card events via `isWritingRow` (static, test-pinned); raw session/tool rows, collapsed thinking, and live thinking render only when checked — the model keeps every row either way, so the toggle flips with history intact), transcript — **#28: rendered by the shared `SessionTranscriptView(model:showsDebugRows:)` (own file); MentorPaneView passes the debug binding** (text rows, fix-card tool calls as one-line `FixCardEventRow`s — pattern title only, the detail lives in the palette; RawUpdateRow disclosure; **#24 dogfood fix:** `defaultScrollAnchor(.bottom)` — programmatic `scrollTo` raced the growing lazy rows and mislanded at the TOP; `.thought` rows render collapsed (`ThoughtRow`, the engine's thinking — kept out of the critique text), live thinking shows muted + `lineLimit(3)`), freeform input 1…4 lines + send + Stop while streaming (**#23 dogfood fix:** a liveness row above the input — indeterminate `ProgressView` + "Mentor is working — Stop to interrupt." caption while `isStreaming`; minutes of silent tool work read as dead without it), crash card (Restart, last prompt, stderr tail behind Technical details; input + crash card live in a file-scope `private extension MentorPaneView` — type_body_length posture). **#24 (S3.1):** below the header a segmented **Pass 1 | Pass 2 | Chat** picker (the design contract's `.mentor-tabs`) — pass modes carry the pass bar (`PassBarView`, private): what the pass critiques + `PassContext.estimateTokens` cost line ("· ~N tokens") or "Open a post to run a pass.", the open piece's Pass State chip (library's post-meta voice), and the actions — Cancel (bordered, only while `posts.runningPass` streams) ↔ Run Pass N (borderedProminent; disabled with no open piece, engine not ready, or mid-turn). Chat hides the bar; transcript + input stay shared (the pass's streamed critique renders in the same transcript). `posts: PostsModel?` + `home: URL?` params (nil = previews); PostsPaneView's mentor column passes both. **#23 follow-up (dogfood):** card detail lives in the **Fix Cards palette** — a floating `Window` scene (id `fix-cards`, `FixCardsPalette` in `FixCardsWindow.swift`, `defaultSize` 340×540) beside About, opened via `openWindow` from a mono "Fix Cards · N" row below the pass bar (shown only when cards exist). The palette shows the open piece's title + `posts.openPieceCards` — **#25 (S3.2/S3.3): the card WORK surface, open cards first (scan order preserved: newest pass first, rank ascending), closed cards dimmed at 0.45 with their status in the meta and no actions**; row actions per lane: mechanical + valid → Apply + Skip, demonstration → Done + Skip (never Apply, ADR-0006), stale anchor → Skip only; Apply = ask-before, a BLOCKING sheet showing the exact edit (anchored quote → replacement, "(cut)" when the fix is empty) with Apply/Cancel — .stale swaps the sheet to the stale alert (no retry), .refused shows the reason inline; no apply-all, no batch, the sheet is the only path from Apply to a write (S3.3); meta carries `#rank`, "apply · ask-before" on appliable mechanical cards, and the footer line "apply = ask-before · one card at a time" (S2.5 trust visibility — nothing auto-applies, so never-do needs no control); stale anchors orange + "· stale anchor"; card meta leads with "pass N" when `provenance.pass` is stamped and re-contextualizes via `@Observable` as the open piece changes (**audit: the card scan runs detached off MainActor — typing re-triggers rescan; PostsModel.`title(of:)` + EditorSession.`passPieceURL`/`hasResearch` are the shared facts runPass, the pass bar, and the palette ride — three hand-copies deduped**); painted `DesignTokens.background` — app chrome warm, matching the rail, not document white. The transcript's live tool-call rendering is `FixCardEventRow` — the pattern title alone, one line; the verdict prose carries no card detail (pass-persona v1.2: the card is the finding's only full statement). **#26 (S4.1):** every card row gains Promote (bordered, small) between the primary action and Skip on open cards, alone on closed unpromoted cards — it outlives the card because the Learning is the durable artifact (the design contract's promote-resolved buttons); a promoted card shows `· promoted` in the meta and never re-offers. The ask is `PromoteAskSheet` (own file, OutlineRowTextView extraction precedent): the contract's #promoteDialog — "Promote to Learnings?", the consulted-on-future-Passes body line (type pluralized, "pieces" fallback), learning preview (pattern/problem/provenance via `titlLine truncated
|
||||
- Wiring: `AppGateState.mentor` is the app-scoped model ( ContentView renders `MentorPaneView(model:binaryPath:)` once `gateModel.currentBinaryPath` exists, handing the gate's winner to `mentor.binaryPath` — no re-probe); quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent; scenePhase `.inactive` would fire on plain focus loss).
|
||||
- Tests: `MuseionTests/ACPClientTests.swift` — fake ACP server (zsh speaking real NDJSON over the real Process path; mode file + base64 card payload beside the binary, self-locating per ProfileProvisionerTests convention). Covers handshake version, streamed updates + fix-card parse (model over the real client+fake path), advisory drift note, crash → onCrash exactly once, cancel fire-and-forget, teardown kills hung child.
|
||||
|
||||
|
||||
@@ -71,7 +71,9 @@ struct MentorPaneView: View {
|
||||
.padding(.vertical, 6)
|
||||
Divider()
|
||||
}
|
||||
transcript
|
||||
// #28: the transcript rendering is shared — the Sessions pane
|
||||
// reads the same surface in the writing voice.
|
||||
SessionTranscriptView(model: model, showsDebugRows: debugRows)
|
||||
Divider()
|
||||
inputBar
|
||||
case let .crashed(lastPrompt):
|
||||
@@ -81,7 +83,10 @@ struct MentorPaneView: View {
|
||||
// #17: the pane lives in the workspace's fixed 356pt mentor column —
|
||||
// no root min frame (it was the full-window M0 surface).
|
||||
.task {
|
||||
model.binaryPath = binaryPath ?? model.binaryPath
|
||||
// #28 review: an honest if-let — the ?? self-assignment was a no-op.
|
||||
if let binaryPath {
|
||||
model.binaryPath = binaryPath
|
||||
}
|
||||
// Hosted unit tests run this app as their runner — never spawn a
|
||||
// real engine child there (it outlives the test session and kills
|
||||
// the runner).
|
||||
@@ -90,16 +95,6 @@ struct MentorPaneView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// The writing-session transcript: prose (verdicts, labels, notes) and
|
||||
/// card events stay; raw session/tool rows and collapsed thinking are
|
||||
/// debug-only. Static — pure, testable.
|
||||
static func isWritingRow(_ row: SessionRow) -> Bool {
|
||||
switch row.content {
|
||||
case .text, .fixCard: true
|
||||
case .thought, .raw: false
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Header
|
||||
|
||||
private var header: some View {
|
||||
@@ -120,7 +115,7 @@ struct MentorPaneView: View {
|
||||
.help(note)
|
||||
}
|
||||
Spacer()
|
||||
if case let .ready(sessionId) = model.phase {
|
||||
if case .ready = model.phase, let sessionId = model.activeEntry?.sessionId {
|
||||
Text("session \(sessionId.prefix(8))")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.tertiary)
|
||||
@@ -160,112 +155,6 @@ struct MentorPaneView: View {
|
||||
.padding(.top, 10)
|
||||
.padding(.bottom, 8)
|
||||
}
|
||||
|
||||
// MARK: Transcript
|
||||
|
||||
private var transcript: some View {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 10) {
|
||||
ForEach(model.rows.filter { debugRows || Self.isWritingRow($0) }) { row in
|
||||
rowView(row)
|
||||
}
|
||||
if debugRows, !model.streamingThought.isEmpty {
|
||||
// Live thinking: quiet, capped — it's transient (the full
|
||||
// text lands in a collapsed row when the turn ends).
|
||||
Text(model.streamingThought)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.lineLimit(3)
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
if !model.streamingText.isEmpty {
|
||||
textRow("Mentor: \(model.streamingText)")
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
// #24 fix: programmatic scrollTo raced the growing lazy rows and
|
||||
// mislanded at the TOP; the native bottom anchor needs no scroll code.
|
||||
.defaultScrollAnchor(.bottom)
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func rowView(_ row: SessionRow) -> some View {
|
||||
switch row.content {
|
||||
case let .text(text):
|
||||
textRow(text)
|
||||
case let .thought(text):
|
||||
ThoughtRow(text: text)
|
||||
case let .fixCard(card):
|
||||
// #23 follow-up: detail lives in the palette window — the
|
||||
// transcript keeps a one-line event, not the card.
|
||||
FixCardEventRow(pattern: card.pattern)
|
||||
case let .raw(kind, json):
|
||||
RawUpdateRow(kind: kind, json: json)
|
||||
}
|
||||
}
|
||||
|
||||
private func textRow(_ text: String) -> some View {
|
||||
Text(text)
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
// MARK: Rows
|
||||
|
||||
/// The tool-call EVENT, not the card: the pattern title alone. The
|
||||
/// card's full statement lives in the Fix Cards palette window.
|
||||
private struct FixCardEventRow: View {
|
||||
let pattern: String
|
||||
|
||||
var body: some View {
|
||||
Label(pattern, systemImage: "rectangle.and.pencil.and.ellipsis")
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
/// #24 fix: the engine's thinking, collapsed — a pass's thought stream runs
|
||||
/// to hundreds of lines and is not the critique (only `agent_message_chunk`
|
||||
/// is). Same shape as RawUpdateRow: quiet mono, expandable, never in the way.
|
||||
private struct ThoughtRow: View {
|
||||
let text: String
|
||||
|
||||
var body: some View {
|
||||
DisclosureGroup {
|
||||
Text(text)
|
||||
.font(.system(size: 10, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.textSelection(.enabled)
|
||||
} label: {
|
||||
Text("thinking")
|
||||
.font(.system(size: 11, design: .monospaced))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private struct RawUpdateRow: View {
|
||||
let kind: String
|
||||
let json: String
|
||||
|
||||
var body: some View {
|
||||
DisclosureGroup {
|
||||
Text(json)
|
||||
.font(.system(size: 10, design: .monospaced))
|
||||
.textSelection(.enabled)
|
||||
} label: {
|
||||
Text(kind)
|
||||
.font(.system(size: 11, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Input + crash card (file-scope extension — type_body_length posture)
|
||||
@@ -322,7 +211,7 @@ private extension MentorPaneView {
|
||||
|
||||
// MARK: Crash → restart prompt (map decision: EOF/crash surfaces an
|
||||
|
||||
// in-pane Restart prompt, never data loss)
|
||||
// in-pane Restart prompt; the transcript replays from the engine (ADR-0007)
|
||||
|
||||
private func crashCard(lastPrompt: String?) -> some View {
|
||||
VStack(spacing: 14) {
|
||||
|
||||
@@ -3,7 +3,11 @@
|
||||
// Museion
|
||||
//
|
||||
// M0 ACP bridge (#14): the pane's @Observable model — lazy bridge lifecycle,
|
||||
// one session, prompt streaming, fix-card render, crash → restart prompt.
|
||||
// prompt streaming, fix-card render, crash → restart prompt.
|
||||
// #28 (S2.3): multi-session — a persisted roster of engine-owned sessions
|
||||
// (session/new, session/load, session/fork, /compress on the wire), one
|
||||
// transcript per session, and the same-named ACTIVE surface (rows, buffers,
|
||||
// sendPrompt, stop) so the pane and every existing test read unchanged.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@@ -50,16 +54,66 @@ enum TurnOutcome: Equatable {
|
||||
case failed
|
||||
}
|
||||
|
||||
/// One rostered mentor session (#28, S2.3). Piece association is by
|
||||
/// convention — the entry's `pieceTitle` field only, no filesystem linkage.
|
||||
/// History is engine-owned; only these four fields persist.
|
||||
nonisolated struct SessionEntry: Identifiable, Equatable, Codable {
|
||||
let sessionId: String
|
||||
let name: String
|
||||
var pieceTitle: String?
|
||||
let createdAt: Date
|
||||
|
||||
var id: String {
|
||||
sessionId
|
||||
}
|
||||
}
|
||||
|
||||
/// The persisted roster (#28) — a JSON array of entries at a
|
||||
/// caller-injectable directory, default `~/Library/Application
|
||||
/// Support/Museion/sessions.json`. EngineGate's state.json posture: wholesale
|
||||
/// replace, atomic, a write failure must never crash the app.
|
||||
nonisolated enum SessionRoster {
|
||||
static func load(directory: String? = nil) -> [SessionEntry] {
|
||||
guard let data = try? Data(contentsOf: rosterURL(directory)) else { return [] }
|
||||
return (try? JSONDecoder().decode([SessionEntry].self, from: data)) ?? []
|
||||
}
|
||||
|
||||
static func save(_ entries: [SessionEntry], directory: String? = nil) {
|
||||
let dir = directory ?? defaultDirectory
|
||||
do {
|
||||
try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
|
||||
try JSONEncoder().encode(entries).write(
|
||||
to: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json"),
|
||||
options: .atomic,
|
||||
)
|
||||
// Finish-audit: names+ids only, but piece titles are the writer's
|
||||
// business — the default umask would hand them to every local user.
|
||||
try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json").path)
|
||||
} catch {
|
||||
// ponytail: the roster is a convenience index; a write failure must not crash the gate.
|
||||
}
|
||||
}
|
||||
|
||||
private static var defaultDirectory: String {
|
||||
("~/Library/Application Support/Museion" as NSString).expandingTildeInPath
|
||||
}
|
||||
|
||||
private static func rosterURL(_ directory: String?) -> URL {
|
||||
URL(fileURLWithPath: directory ?? defaultDirectory).appendingPathComponent("sessions.json")
|
||||
}
|
||||
}
|
||||
|
||||
/// Pane + bridge state machine. Lazy lifecycle: the engine spawns when the
|
||||
/// pane opens its first session and stays alive for the app's life (map
|
||||
/// decision: child lifecycle).
|
||||
/// decision: child lifecycle). The engine bridge is session-agnostic —
|
||||
/// session ids live in the roster (#28), the phase only says the engine is up.
|
||||
@MainActor
|
||||
@Observable
|
||||
final class MentorSessionModel {
|
||||
enum Phase: Equatable {
|
||||
case idle
|
||||
case starting
|
||||
case ready(sessionId: String)
|
||||
case ready
|
||||
case crashed(lastPrompt: String?)
|
||||
|
||||
var isReady: Bool {
|
||||
@@ -70,16 +124,49 @@ final class MentorSessionModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-session transcript state (#28) — the model used to hold ONE
|
||||
/// session's rows and streaming buffers; now keyed by sessionId. The
|
||||
/// active session's entries surface through the same-named proxies below.
|
||||
private struct SessionTranscript {
|
||||
var rows: [SessionRow] = []
|
||||
var streamingText = ""
|
||||
var streamingThought = ""
|
||||
}
|
||||
|
||||
private(set) var phase: Phase = .idle
|
||||
/// True while a turn streams — the Stop button's target.
|
||||
/// True while a turn streams — the Stop button's target. One engine
|
||||
/// child, so at most one turn streams at a time across all sessions.
|
||||
private(set) var isStreaming = false
|
||||
private(set) var rows: [SessionRow] = []
|
||||
/// Streaming buffer for the in-flight agent message; flushed to a row on completion.
|
||||
private(set) var streamingText = ""
|
||||
/// The roster, newest-first (#28). Persisted via SessionRoster.
|
||||
private(set) var roster: [SessionEntry] = []
|
||||
/// The session the pane reads and new prompts target (#28).
|
||||
private(set) var activeEntry: SessionEntry?
|
||||
|
||||
/// The ACTIVE session's transcript — the same-named pane surface over
|
||||
/// the per-session store (#28). MentorPaneView and every existing test
|
||||
/// keep reading these untouched.
|
||||
var rows: [SessionRow] {
|
||||
activeTranscript?.rows ?? []
|
||||
}
|
||||
|
||||
/// Streaming buffer for the in-flight agent message of the ACTIVE
|
||||
/// session; flushed to a row on completion.
|
||||
var streamingText: String {
|
||||
activeTranscript?.streamingText ?? ""
|
||||
}
|
||||
|
||||
/// #24 fix: streaming buffer for the engine's THINKING — kept out of the
|
||||
/// critique stream. A pass runs to hundreds of thought lines; conflating
|
||||
/// them with `agent_message_chunk` made the transcript one giant blob.
|
||||
private(set) var streamingThought = ""
|
||||
var streamingThought: String {
|
||||
activeTranscript?.streamingThought ?? ""
|
||||
}
|
||||
|
||||
/// A new session may start: engine up, no turn in flight (#28).
|
||||
var canStartSession: Bool {
|
||||
phase.isReady && !isStreaming
|
||||
}
|
||||
|
||||
/// Advisory engine-version verdict (map decision: advisory, never blocks).
|
||||
private(set) var versionNote: String?
|
||||
/// The running engine's version, from the initialize handshake (always visible).
|
||||
@@ -87,8 +174,16 @@ final class MentorSessionModel {
|
||||
/// Last stderr lines from the engine — the restart prompt's technical details.
|
||||
private(set) var stderrTail: [String] = []
|
||||
|
||||
private var transcripts: [String: SessionTranscript] = [:]
|
||||
/// While a session/load is in flight, its replayed updates render as rows
|
||||
/// instead of feeding the streaming buffers (#28).
|
||||
private var replayingSessionId: String?
|
||||
/// The resolved roster directory (nil = SessionRoster's default). Under
|
||||
/// hosted tests a unique temp dir keeps suites off the real roster
|
||||
/// (ponytail: redirect here instead of making every rig inject a directory).
|
||||
private let rosterDirectory: String?
|
||||
|
||||
private var client: ACPEngineClient?
|
||||
private var sessionId: String?
|
||||
private var lastPrompt: String?
|
||||
|
||||
/// The gate's winning binary path (no re-probe — map decision). Set by the
|
||||
@@ -100,8 +195,20 @@ final class MentorSessionModel {
|
||||
/// The gate's recorded engine version (state.json) — injectable for tests.
|
||||
var recordedVersionProvider: () -> String? = { EngineProbe.readStateRecord()?.engineVersion }
|
||||
|
||||
init(binaryPath: String? = nil) {
|
||||
init(binaryPath: String? = nil, rosterDirectory: String? = nil) {
|
||||
self.binaryPath = binaryPath
|
||||
if let rosterDirectory {
|
||||
self.rosterDirectory = rosterDirectory
|
||||
} else if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil {
|
||||
self.rosterDirectory = NSTemporaryDirectory() + "museion-roster-\(UUID().uuidString)"
|
||||
} else {
|
||||
self.rosterDirectory = nil
|
||||
}
|
||||
roster = SessionRoster.load(directory: self.rosterDirectory)
|
||||
}
|
||||
|
||||
private var activeTranscript: SessionTranscript? {
|
||||
activeEntry.flatMap { transcripts[$0.sessionId] }
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -109,6 +216,12 @@ final class MentorSessionModel {
|
||||
shutdownClientDirectly()
|
||||
}
|
||||
|
||||
/// The engine child's pid — internal observation surface for the
|
||||
/// finish-audit restart pin (kills the child to drive a real crash).
|
||||
var childProcessIdentifier: pid_t? {
|
||||
client?.childProcessIdentifier
|
||||
}
|
||||
|
||||
/// App-quit teardown (#14): close the engine child cleanly. Idempotent.
|
||||
func shutdown() {
|
||||
shutdownClientDirectly()
|
||||
@@ -128,25 +241,34 @@ final class MentorSessionModel {
|
||||
/// wherever `client` is assigned.
|
||||
private nonisolated(unsafe) var clientRef: ACPEngineClient?
|
||||
|
||||
/// Lazy spawn on first session open. Idempotent per lifecycle.
|
||||
/// Lazy spawn on first session open. Idempotent per lifecycle. Ensures
|
||||
/// ONE session exists: the default freeform 'Mentor' session on first
|
||||
/// open, otherwise the newest rostered entry activated with a FRESH
|
||||
/// transcript — history is engine-owned and comes back on resume (#28).
|
||||
func openSession() async {
|
||||
guard phase == .idle else { return }
|
||||
phase = .starting
|
||||
await startEngine()
|
||||
guard case .starting = phase else { return } // startEngine crashed instead
|
||||
await ensureDefaultSession()
|
||||
}
|
||||
|
||||
/// Restart after a crash — keeps the transcript (never data loss) and
|
||||
/// Restart after a crash — re-spawns the engine and REPLAYS every
|
||||
/// transcript from it (ADR-0007: the engine owns the words), and
|
||||
/// remembers the last prompt so the writer can resend it.
|
||||
func restart() async {
|
||||
guard case .crashed = phase else { return }
|
||||
client?.close()
|
||||
client = nil
|
||||
clientRef = nil
|
||||
sessionId = nil
|
||||
streamingText = ""
|
||||
streamingThought = ""
|
||||
for sid in transcripts.keys {
|
||||
transcripts[sid]?.streamingText = ""
|
||||
transcripts[sid]?.streamingThought = ""
|
||||
}
|
||||
phase = .starting
|
||||
await startEngine()
|
||||
guard case .starting = phase else { return }
|
||||
await ensureDefaultSession()
|
||||
}
|
||||
|
||||
private func startEngine() async {
|
||||
@@ -158,19 +280,24 @@ final class MentorSessionModel {
|
||||
let client = ACPEngineClient(binaryPath: binaryPath)
|
||||
self.client = client
|
||||
clientRef = client
|
||||
// All three hops ride DispatchQueue.main.async, NOT Task { @MainActor }:
|
||||
// a Task must first win cooperative-pool time, which hundreds of
|
||||
// parallel jobs can starve for seconds (#28 test finding); the main
|
||||
// queue is FIFO with the continuation resume, so wire order — replay
|
||||
// updates before the load response — is guaranteed, not probable.
|
||||
client.onCrash = { [weak self] in
|
||||
Task { @MainActor in
|
||||
DispatchQueue.main.async {
|
||||
self?.handleCrash()
|
||||
}
|
||||
}
|
||||
client.onStderrLine = { [weak self] line in
|
||||
Task { @MainActor in
|
||||
DispatchQueue.main.async {
|
||||
self?.appendStderr(line)
|
||||
}
|
||||
}
|
||||
do {
|
||||
try client.start { [weak self] method, params in
|
||||
Task { @MainActor in
|
||||
DispatchQueue.main.async {
|
||||
self?.handleNotification(method: method, params: params)
|
||||
}
|
||||
}
|
||||
@@ -188,7 +315,8 @@ final class MentorSessionModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// initialize + session/new (map decisions: advisory version verify; cwd ~).
|
||||
/// initialize (map decisions: advisory version verify). Sessions are
|
||||
/// created separately (#28) — the bridge is session-agnostic.
|
||||
private func handshake(_ client: ACPEngineClient) async throws {
|
||||
let params: JSONValue = .object([
|
||||
"protocolVersion": .number(1),
|
||||
@@ -218,35 +346,233 @@ final class MentorSessionModel {
|
||||
}
|
||||
}
|
||||
versionNote = note
|
||||
|
||||
// New session — cwd ~ (map decision). Adapter ≥0.21.5 requires mcpServers
|
||||
// (ACP SDK NewSessionRequest); Museion ships none, so the honest empty list.
|
||||
let newResult = try await client.request(
|
||||
"session/new",
|
||||
params: .object([
|
||||
"cwd": .string(cwdProvider()),
|
||||
"mcpServers": .array([]),
|
||||
]),
|
||||
)
|
||||
guard let sid = newResult?.objectValue?["sessionId"]?.stringValue else {
|
||||
throw ACPEngineClient.TransportError(message: "session/new returned no sessionId")
|
||||
}
|
||||
sessionId = sid
|
||||
phase = .ready(sessionId: sid)
|
||||
}
|
||||
|
||||
/// Send a prompt and stream the reply. Appends the user row first — a
|
||||
/// non-nil `label` renders verbatim INSTEAD of the raw prompt (pass prompts
|
||||
/// are long wire stubs that must not land in the transcript); the
|
||||
/// stop_reason response ends the turn (refusal maps to a plain note —
|
||||
/// wire-verified edge semantics). Returns how the turn ended (#24 seam):
|
||||
/// a pass advances only on a completed turn, never on cancel/crash.
|
||||
/// session/prompt's response arrives only when the TURN ends — a pass
|
||||
/// legitimately runs minutes of tool work between prompt and stop reason.
|
||||
/// The client's 15 s request default would abandon the wait mid-stream
|
||||
/// (observed live, #23 dogfood: "connection lost" while the engine kept
|
||||
/// working, Stop vanished with isStreaming). Long-but-finite so a truly
|
||||
/// stuck engine still surfaces; Stop is the live-turn exit.
|
||||
/// After an engine start: exactly one active session (#28). The newest
|
||||
/// rostered entry activates and RESUMES — session/load replays its
|
||||
/// history (user turns included), so prompt/fork/compact never run
|
||||
/// against unloaded state; a first open creates the default freeform
|
||||
/// 'Mentor' session.
|
||||
private func ensureDefaultSession() async {
|
||||
if let newest = roster.first {
|
||||
activate(newest)
|
||||
// The resume REPLAYS, unconditionally (finish-audit): the deleted
|
||||
// rows.isEmpty skip was dead — activate() resets the store one
|
||||
// line above it — and restart()'s kept rows are intentionally
|
||||
// replaced by the engine's replay (ADR-0007: the engine owns the
|
||||
// words; a diverging local copy would lie). An engine-unknown id
|
||||
// lands the honest refusal row; the entry stays rostered.
|
||||
_ = await resumeSession(newest)
|
||||
return
|
||||
}
|
||||
if await createSession(name: "Mentor", pieceTitle: nil) == nil {
|
||||
phase = .crashed(lastPrompt: nil)
|
||||
stderrTail = ["no session — the engine refused session/new"]
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh freeform session (#28): wire session/new, roster it
|
||||
/// newest-first, activate. Nil when the engine isn't ready or refuses.
|
||||
@discardableResult
|
||||
func newSession(name: String, pieceTitle: String?) async -> SessionEntry? {
|
||||
guard phase.isReady, client != nil else { return nil }
|
||||
return await createSession(name: name, pieceTitle: pieceTitle)
|
||||
}
|
||||
|
||||
/// The pass's own session (#28): wire session/new + roster
|
||||
/// 'Pass N · <title>' + activate, so the pass prompt streams into ITS
|
||||
/// transcript. Nil when the engine isn't ready or refuses.
|
||||
@discardableResult
|
||||
func beginPassSession(kind: PassKind, pieceTitle: String) async -> SessionEntry? {
|
||||
guard phase.isReady, client != nil else { return nil }
|
||||
return await createSession(name: "\(kind.rawValue) · \(pieceTitle)", pieceTitle: pieceTitle)
|
||||
}
|
||||
|
||||
/// The shared creation rail behind newSession/beginPassSession.
|
||||
private func createSession(name: String, pieceTitle: String?) async -> SessionEntry? {
|
||||
// Finish-audit backstop: fork guards !isStreaming; the views disable
|
||||
// these controls mid-turn. A programmatic caller must not switch the
|
||||
// active session out from under a live turn — Stop would then cancel
|
||||
// the wrong session.
|
||||
guard !isStreaming else {
|
||||
appendRow(.text("Session refused — the mentor is mid-turn."), to: activeEntry?.sessionId)
|
||||
return nil
|
||||
}
|
||||
guard let client else { return nil }
|
||||
do {
|
||||
// Adapter ≥0.21.5 requires mcpServers on every session/new (#44
|
||||
// invariant); Museion ships none, so the honest empty list.
|
||||
let result = try await client.request(
|
||||
"session/new",
|
||||
params: .object([
|
||||
"cwd": .string(cwdProvider()),
|
||||
"mcpServers": .array([]),
|
||||
]),
|
||||
)
|
||||
guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
|
||||
// #28 review fix: a refused session speaks like its siblings —
|
||||
// resume/fork append honest rows; New Session must never be a
|
||||
// silent nil. (Nothing active yet → the row drops; the crash
|
||||
// posture owns that path in ensureDefaultSession.)
|
||||
appendRow(.text("Session refused — the engine returned no id."), to: activeEntry?.sessionId)
|
||||
return nil
|
||||
}
|
||||
let entry = SessionEntry(sessionId: sid, name: name, pieceTitle: pieceTitle, createdAt: Date())
|
||||
roster.insert(entry, at: 0)
|
||||
transcripts[sid] = SessionTranscript()
|
||||
activeEntry = entry
|
||||
phase = .ready
|
||||
saveRoster()
|
||||
return entry
|
||||
} catch {
|
||||
appendRow(.text("Session refused — \(error.localizedDescription)"), to: activeEntry?.sessionId)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Resume a rostered session (#28): session/load, the engine replays its
|
||||
/// history into the transcript (user turns included), Museion owns none
|
||||
/// of it. A session the engine does NOT know returns false honestly —
|
||||
/// the entry stays and an explanatory row lands; never a fabricated
|
||||
/// empty session.
|
||||
func resumeSession(_ entry: SessionEntry) async -> Bool {
|
||||
guard phase.isReady, let client else { return false }
|
||||
guard !isStreaming else {
|
||||
// "Not now" refusals target the ACTIVE session — they are about
|
||||
// the writer's action right now, not the entry's state.
|
||||
appendRow(.text("Resume refused — the mentor is mid-turn."), to: activeEntry?.sessionId)
|
||||
return false
|
||||
}
|
||||
guard replayingSessionId == nil else {
|
||||
// Finish-audit (converged, 3 reviewers): one replay slot — a
|
||||
// second session/load in flight would divert the first's replayed
|
||||
// chunks into live streaming buffers. Refuse; the winner's
|
||||
// completion frees the slot and the next click just works.
|
||||
appendRow(.text("Resume refused — another session is loading."), to: activeEntry?.sessionId)
|
||||
return false
|
||||
}
|
||||
do {
|
||||
// Replay fills this fresh store; a failed resume leaves nothing fabricated.
|
||||
transcripts[entry.sessionId] = SessionTranscript()
|
||||
replayingSessionId = entry.sessionId
|
||||
// Replay ordering: the adapter writes the history notifications
|
||||
// BEFORE the load response, and the MainActor Task pipeline
|
||||
// preserves that order — same reliance as live streaming.
|
||||
let result = try await client.request(
|
||||
"session/load",
|
||||
params: .object([
|
||||
"cwd": .string(cwdProvider()),
|
||||
"sessionId": .string(entry.sessionId),
|
||||
"mcpServers": .array([]),
|
||||
]),
|
||||
// Finish-audit: the adapter replays the FULL history before
|
||||
// responding — #23's exact shape (response arrives when the
|
||||
// work ends). The client's 15 s default would abort a long
|
||||
// session's resume mid-replay.
|
||||
timeout: Self.promptTimeout,
|
||||
)
|
||||
replayingSessionId = nil
|
||||
// null/absent (or empty) sessionId in the result = the engine does not know it.
|
||||
guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
|
||||
// The refusal belongs to the ENTRY — attributed, and visible
|
||||
// on its next row click (the store is kept, not discarded).
|
||||
appendRow(
|
||||
.text("The engine does not know “\(entry.name)” — its history is no longer on the engine."),
|
||||
to: entry.sessionId,
|
||||
)
|
||||
return false
|
||||
}
|
||||
// Activate WITHOUT resetting the transcript — activate() is for
|
||||
// fresh-transcript activations; the replay already filled this one.
|
||||
activeEntry = entry
|
||||
phase = .ready
|
||||
return true
|
||||
} catch {
|
||||
replayingSessionId = nil
|
||||
// Partial replay rows (if any) + the failure row stay in the
|
||||
// ENTRY's store — attributed, visible on its next row click.
|
||||
appendRow(.text("Resume failed — \(error.localizedDescription)"), to: entry.sessionId)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Fork the active session (#28): the engine copies its history to a NEW
|
||||
/// sessionId (session/fork); Museion rosters '<name> (fork)' with the
|
||||
/// same pieceTitle and activates it with a FRESH transcript — the
|
||||
/// original entry and transcript stay untouched. An empty-string
|
||||
/// sessionId from the wire is a refusal (honest row, nil return).
|
||||
@discardableResult
|
||||
func forkActiveSession() async -> SessionEntry? {
|
||||
guard phase.isReady, let client, let source = activeEntry, !isStreaming else { return nil }
|
||||
do {
|
||||
let result = try await client.request(
|
||||
"session/fork",
|
||||
params: .object([
|
||||
"cwd": .string(cwdProvider()),
|
||||
"sessionId": .string(source.sessionId),
|
||||
"mcpServers": .array([]),
|
||||
]),
|
||||
)
|
||||
guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
|
||||
appendRow(.text("Fork refused — the engine returned no new session."), to: source.sessionId)
|
||||
return nil
|
||||
}
|
||||
let entry = SessionEntry(
|
||||
sessionId: sid,
|
||||
name: "\(source.name) (fork)",
|
||||
pieceTitle: source.pieceTitle,
|
||||
createdAt: Date(),
|
||||
)
|
||||
roster.insert(entry, at: 0)
|
||||
transcripts[sid] = SessionTranscript()
|
||||
activeEntry = entry
|
||||
phase = .ready
|
||||
saveRoster()
|
||||
return entry
|
||||
} catch {
|
||||
appendRow(.text("Fork failed — \(error.localizedDescription)"), to: source.sessionId)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Compact the active idle session (#28): the engine's /compress dispatch
|
||||
/// rides the existing prompt rail; the label keeps the raw slash command
|
||||
/// out of the transcript and the summary streams back as ordinary chunks.
|
||||
/// Refused while a turn streams (idle-only engine-side, too).
|
||||
func compactActiveSession() async {
|
||||
guard canStartSession, activeEntry != nil else { return }
|
||||
_ = await sendPrompt("/compress", label: "Compact…")
|
||||
}
|
||||
|
||||
/// Read-only transcript of ANY rostered session (#28) — the Sessions pane
|
||||
/// and tests read without activating.
|
||||
func transcriptRows(of entry: SessionEntry) -> [SessionRow] {
|
||||
transcripts[entry.sessionId]?.rows ?? []
|
||||
}
|
||||
|
||||
private func activate(_ entry: SessionEntry) {
|
||||
transcripts[entry.sessionId] = SessionTranscript()
|
||||
activeEntry = entry
|
||||
phase = .ready
|
||||
}
|
||||
|
||||
private func saveRoster() {
|
||||
SessionRoster.save(roster, directory: rosterDirectory)
|
||||
}
|
||||
|
||||
/// Send a prompt and stream the reply into the ACTIVE session's
|
||||
/// transcript. Appends the user row first — a non-nil `label` renders
|
||||
/// verbatim INSTEAD of the raw prompt (pass prompts are long wire stubs
|
||||
/// that must not land in the transcript); the stop_reason response ends
|
||||
/// the turn (refusal maps to a plain note — wire-verified edge
|
||||
/// semantics). Returns how the turn ended (#24 seam): a pass advances
|
||||
/// only on a completed turn, never on cancel/crash. session/prompt's
|
||||
/// response arrives only when the TURN ends — a pass legitimately runs
|
||||
/// minutes of tool work between prompt and stop reason. The client's
|
||||
/// 15 s request default would abandon the wait mid-stream (observed
|
||||
/// live, #23 dogfood: "connection lost" while the engine kept working,
|
||||
/// Stop vanished with isStreaming). Long-but-finite so a truly stuck
|
||||
/// engine still surfaces; Stop is the live-turn exit.
|
||||
nonisolated static let promptTimeout: TimeInterval = 1800
|
||||
|
||||
@discardableResult
|
||||
@@ -255,20 +581,22 @@ final class MentorSessionModel {
|
||||
// Guard refusal: the turn never ran — .failed is the closest of the
|
||||
// three buckets (the seam has no "never started" case; callers that
|
||||
// check phase before prompting never land here).
|
||||
guard !prompt.isEmpty, case let .ready(sid) = phase, !isStreaming else { return .failed }
|
||||
guard !prompt.isEmpty, phase.isReady, !isStreaming, let sid = activeEntry?.sessionId else {
|
||||
return .failed
|
||||
}
|
||||
lastPrompt = prompt
|
||||
rows.append(SessionRow(content: .text(label ?? "You: \(prompt)")))
|
||||
appendRow(.text(label ?? "You: \(prompt)"), to: sid)
|
||||
isStreaming = true
|
||||
defer {
|
||||
// Flush the thinking first (it preceded the message), collapsed.
|
||||
if !streamingThought.isEmpty {
|
||||
rows.append(SessionRow(content: .thought(streamingThought)))
|
||||
streamingThought = ""
|
||||
if let pending = transcripts[sid], !pending.streamingThought.isEmpty {
|
||||
appendRow(.thought(pending.streamingThought), to: sid)
|
||||
transcripts[sid]?.streamingThought = ""
|
||||
}
|
||||
// Flush any streamed-but-unfinished agent text into a row.
|
||||
if !streamingText.isEmpty {
|
||||
rows.append(SessionRow(content: .text("Mentor: \(streamingText)")))
|
||||
streamingText = ""
|
||||
if let pending = transcripts[sid], !pending.streamingText.isEmpty {
|
||||
appendRow(.text("Mentor: \(pending.streamingText)"), to: sid)
|
||||
transcripts[sid]?.streamingText = ""
|
||||
}
|
||||
isStreaming = false
|
||||
}
|
||||
@@ -290,7 +618,7 @@ final class MentorSessionModel {
|
||||
// must not advance on a maybe (review: empty-stopReason bug).
|
||||
guard !stopReason.isEmpty else { return .failed }
|
||||
if stopReason == "refusal" {
|
||||
rows.append(SessionRow(content: .text("Mentor: (refused the prompt)")))
|
||||
appendRow(.text("Mentor: (refused the prompt)"), to: sid)
|
||||
}
|
||||
if stopReason == "cancelled" {
|
||||
return .cancelled
|
||||
@@ -302,7 +630,7 @@ final class MentorSessionModel {
|
||||
if case .crashed = phase {
|
||||
// Crash card already owns the failure surface.
|
||||
} else {
|
||||
rows.append(SessionRow(content: .text("Mentor: connection lost — \(error.localizedDescription)")))
|
||||
appendRow(.text("Mentor: connection lost — \(error.localizedDescription)"), to: sid)
|
||||
}
|
||||
return .failed
|
||||
}
|
||||
@@ -312,10 +640,22 @@ final class MentorSessionModel {
|
||||
/// session/cancel, a notification — no response expected). The engine
|
||||
/// ends the turn (PromptResponse) as its acknowledgement.
|
||||
func stopStreaming() {
|
||||
guard isStreaming, let sid = sessionId else { return }
|
||||
guard isStreaming, let sid = activeEntry?.sessionId else { return }
|
||||
client?.notify("session/cancel", params: .object(["sessionId": .string(sid)]))
|
||||
}
|
||||
|
||||
/// Base version of a version string — the part before `+` build metadata
|
||||
/// (PEP 440 local version segment). `0.21.5+2177.g735e426` → `0.21.5`.
|
||||
nonisolated static func baseVersion(of version: String) -> String {
|
||||
version.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? version
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Crash, stderr, and notification decoding (same-file extension —
|
||||
|
||||
// the class body keeps lifecycle + turn operations)
|
||||
|
||||
extension MentorSessionModel {
|
||||
private func handleCrash() {
|
||||
guard case .ready = phase else {
|
||||
// A crash during startup also lands in the restart prompt.
|
||||
@@ -334,53 +674,70 @@ final class MentorSessionModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Base version of a version string — the part before `+` build metadata
|
||||
/// (PEP 440 local version segment). `0.21.5+2177.g735e426` → `0.21.5`.
|
||||
nonisolated static func baseVersion(of version: String) -> String {
|
||||
version.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? version
|
||||
}
|
||||
|
||||
// MARK: - Notification decoding
|
||||
|
||||
/// Route by the session id FROM THE PARAMS (#28) — a replay for a
|
||||
/// background session lands in ITS transcript, never the active one's.
|
||||
private func handleNotification(method: String, params: JSONValue?) {
|
||||
guard method == "session/update",
|
||||
let params,
|
||||
let sessionId = params.objectValue?["sessionId"]?.stringValue,
|
||||
sessionId == self.sessionId else { return }
|
||||
let sid = params.objectValue?["sessionId"]?.stringValue,
|
||||
transcripts[sid] != nil else { return }
|
||||
guard let update = params.objectValue?["update"]?.objectValue else { return }
|
||||
let kind = update["sessionUpdate"]?.stringValue ?? "unknown"
|
||||
let replaying = sid == replayingSessionId
|
||||
switch kind {
|
||||
case "agent_message_chunk":
|
||||
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
|
||||
streamingText += text
|
||||
if replaying {
|
||||
// ponytail: one row per replayed chunk — a chunked engine message
|
||||
// renders as several rows; wire order stays faithful. Coalesce
|
||||
// only if a real adapter chunks replayed turns.
|
||||
appendRow(.text("Mentor: \(text)"), to: sid)
|
||||
} else {
|
||||
transcripts[sid]?.streamingText += text
|
||||
}
|
||||
case "agent_thought_chunk":
|
||||
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
|
||||
streamingThought += text
|
||||
if replaying {
|
||||
appendRow(.thought(text), to: sid)
|
||||
} else {
|
||||
transcripts[sid]?.streamingThought += text
|
||||
}
|
||||
case "user_message_chunk":
|
||||
// The engine echoes the user message; we already rendered it.
|
||||
break
|
||||
// Live: the engine echoes the user message; the label row already
|
||||
// rendered. During replay there IS no rendered row — the engine
|
||||
// owns the turn, so it renders (#28: user turns included).
|
||||
if replaying {
|
||||
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
|
||||
appendRow(.text("You: \(text)"), to: sid)
|
||||
}
|
||||
case "tool_call":
|
||||
appendToolCall(update)
|
||||
appendToolCall(update, to: sid)
|
||||
default:
|
||||
// Every other update type: collapsible raw-JSON row (map decision).
|
||||
let object = params.objectValue?.mapValues { $0.any } ?? [:]
|
||||
let json = (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])) ?? Data()
|
||||
rows.append(SessionRow(content: .raw(kind: kind, json: String(bytes: json, encoding: .utf8) ?? "")))
|
||||
appendRow(.raw(kind: kind, json: String(bytes: json, encoding: .utf8) ?? ""), to: sid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Tool-call decoding — the fix-card rail (ADR-0006): a tool call whose
|
||||
/// `rawInput` decodes to fix-card fields renders as a card; any other tool
|
||||
/// call renders as a raw row.
|
||||
private func appendToolCall(_ update: [String: JSONValue]) {
|
||||
private func appendToolCall(_ update: [String: JSONValue], to sid: String) {
|
||||
let title = update["title"]?.stringValue ?? "tool call"
|
||||
let rawInput = update["rawInput"]
|
||||
if let card = FixCard(rawInput: rawInput) {
|
||||
rows.append(SessionRow(content: .fixCard(card)))
|
||||
appendRow(.fixCard(card), to: sid)
|
||||
return
|
||||
}
|
||||
let json = (try? JSONSerialization.data(withJSONObject: rawInput?.any ?? [:], options: [.sortedKeys])) ?? Data()
|
||||
rows.append(SessionRow(content: .raw(kind: title, json: String(bytes: json, encoding: .utf8) ?? "")))
|
||||
appendRow(.raw(kind: title, json: String(bytes: json, encoding: .utf8) ?? ""), to: sid)
|
||||
}
|
||||
|
||||
/// Append one row to a session's transcript; nil targets the ACTIVE one.
|
||||
private func appendRow(_ content: SessionRow.Content, to sid: String?) {
|
||||
guard let sid else { return }
|
||||
transcripts[sid, default: SessionTranscript()].rows.append(SessionRow(content: content))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -821,6 +821,29 @@ extension PostsModel {
|
||||
lastError = error.localizedDescription
|
||||
return
|
||||
}
|
||||
// #28 (S2.3): every pass auto-creates its own session — rostered
|
||||
// 'Pass N · <title>' and activated, so the pass streams into ITS
|
||||
// transcript. The existing ready-guard above stays the refusal pin.
|
||||
let passSession = await mentor.beginPassSession(kind: kind, pieceTitle: title(of: id))
|
||||
guard passSession != nil else {
|
||||
lastError = "The mentor engine refused a session for the pass."
|
||||
return
|
||||
}
|
||||
// Finish-audit: the beginPassSession await above is these guards'
|
||||
// first suspension — a second Run Pass landing inside it re-passed
|
||||
// every guard (both flags still unset) and minted a second pass
|
||||
// session. Re-check ownership here, before the flag goes live; the
|
||||
// sub-ms window where BOTH awaits are still in flight self-contains
|
||||
// via sendPrompt's isStreaming refusal (one orphan roster entry,
|
||||
// never a double stream — ponytail ceiling).
|
||||
guard runningPass == nil else {
|
||||
lastError = "A pass is already running."
|
||||
return
|
||||
}
|
||||
// runningPass goes live only AFTER the session awaits are done: from
|
||||
// here to sendPrompt's isStreaming there is no suspension, so anything
|
||||
// observing runningPass (the pass bar, the #124 Cancel pin) can rely
|
||||
// on Stop being able to cancel the live turn.
|
||||
runningPass = kind
|
||||
defer { runningPass = nil }
|
||||
let stub = PassContext.stub(kind: kind, pieceURL: session.passPieceURL, hasResearch: session.hasResearch)
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//
|
||||
// SessionTranscriptView.swift
|
||||
// Museion
|
||||
//
|
||||
// #28 (S2.3): the shared session transcript, extracted from MentorPaneView —
|
||||
// one renderer for the ACTIVE session's rows + streaming buffers. The
|
||||
// Mentor pane passes its debug toggle; the Sessions pane reads the writing
|
||||
// voice.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// The shared session transcript — the ACTIVE session's rows + streaming
|
||||
/// buffers, extracted from MentorPaneView in #28 so the Sessions pane reads
|
||||
/// the same surface. Writing voice: pass `showsDebugRows: false` (the debug
|
||||
/// toggle stays the Mentor pane's).
|
||||
struct SessionTranscriptView: View {
|
||||
let model: MentorSessionModel
|
||||
/// Raw session/tool rows, collapsed thinking, and live thinking render
|
||||
/// only when on — the model keeps every row either way.
|
||||
var showsDebugRows = false
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 10) {
|
||||
ForEach(model.rows.filter { showsDebugRows || Self.isWritingRow($0) }) { row in
|
||||
rowView(row)
|
||||
}
|
||||
if showsDebugRows, !model.streamingThought.isEmpty {
|
||||
// Live thinking: quiet, capped — it's transient (the full
|
||||
// text lands in a collapsed row when the turn ends).
|
||||
Text(model.streamingThought)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.lineLimit(3)
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
if !model.streamingText.isEmpty {
|
||||
textRow("Mentor: \(model.streamingText)")
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
// #24 fix: programmatic scrollTo raced the growing lazy rows and
|
||||
// mislanded at the TOP; the native bottom anchor needs no scroll code.
|
||||
.defaultScrollAnchor(.bottom)
|
||||
}
|
||||
|
||||
/// The writing-session filter: prose + card events stay; raw rows and
|
||||
/// thinking are debug-only. Static, nonisolated — pure, testable from
|
||||
/// any context.
|
||||
nonisolated static func isWritingRow(_ row: SessionRow) -> Bool {
|
||||
switch row.content {
|
||||
case .text, .fixCard: true
|
||||
case .thought, .raw: false
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func rowView(_ row: SessionRow) -> some View {
|
||||
switch row.content {
|
||||
case let .text(text):
|
||||
textRow(text)
|
||||
case let .thought(text):
|
||||
ThoughtRow(text: text)
|
||||
case let .fixCard(card):
|
||||
// #23 follow-up: detail lives in the palette window — the
|
||||
// transcript keeps a one-line event, not the card.
|
||||
FixCardEventRow(pattern: card.pattern)
|
||||
case let .raw(kind, json):
|
||||
RawUpdateRow(kind: kind, json: json)
|
||||
}
|
||||
}
|
||||
|
||||
private func textRow(_ text: String) -> some View {
|
||||
Text(text)
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
/// The tool-call EVENT, not the card: the pattern title alone. The
|
||||
/// card's full statement lives in the Fix Cards palette window.
|
||||
private struct FixCardEventRow: View {
|
||||
let pattern: String
|
||||
|
||||
var body: some View {
|
||||
Label(pattern, systemImage: "rectangle.and.pencil.and.ellipsis")
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
/// #24 fix: the engine's thinking, collapsed — a pass's thought stream
|
||||
/// runs to hundreds of lines and is not the critique.
|
||||
private struct ThoughtRow: View {
|
||||
let text: String
|
||||
|
||||
var body: some View {
|
||||
DisclosureGroup {
|
||||
Text(text)
|
||||
.font(.system(size: 10, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.textSelection(.enabled)
|
||||
} label: {
|
||||
Text("thinking")
|
||||
.font(.system(size: 11, design: .monospaced))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private struct RawUpdateRow: View {
|
||||
let kind: String
|
||||
let json: String
|
||||
|
||||
var body: some View {
|
||||
DisclosureGroup {
|
||||
Text(json)
|
||||
.font(.system(size: 10, design: .monospaced))
|
||||
.textSelection(.enabled)
|
||||
} label: {
|
||||
Text(kind)
|
||||
.font(.system(size: 11, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
SessionsPaneView(model: MentorSessionModel(), posts: nil, binaryPath: nil)
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
//
|
||||
// SessionsPaneView.swift
|
||||
// Museion
|
||||
//
|
||||
// #28 (S2.3): the Sessions pane — the roster (newest-first) + the active
|
||||
// session's transcript, with New/Resume/Fork/Compact/Cancel over
|
||||
// MentorSessionModel. Also hosts the shared session transcript extracted
|
||||
// from MentorPaneView (one renderer, two panes; writing voice here, debug
|
||||
// toggle there).
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// The Sessions rail destination: two-column body like Posts — roster list
|
||||
/// (library width) + transcript. Selecting a row resumes that session; the
|
||||
/// engine owns the words, so a fresh activation replays its history.
|
||||
struct SessionsPaneView: View {
|
||||
var model: MentorSessionModel
|
||||
/// The open piece is the New Session control's association target.
|
||||
var posts: PostsModel?
|
||||
/// The gate's winning binary (no re-probe) — this pane can be the first
|
||||
/// to open the engine.
|
||||
var binaryPath: String?
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
PaneHeader(title: "Sessions") {
|
||||
newSessionControl
|
||||
}
|
||||
if model.roster.isEmpty {
|
||||
emptyState
|
||||
} else {
|
||||
HStack(spacing: 0) {
|
||||
rosterList
|
||||
.frame(width: DesignTokens.libraryWidth)
|
||||
paneBorder
|
||||
sessionDetail
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(DesignTokens.background)
|
||||
// Same lazy lifecycle as MentorPaneView: idempotent open — whichever
|
||||
// surface the writer reaches first spawns the engine.
|
||||
.task {
|
||||
if let binaryPath {
|
||||
model.binaryPath = binaryPath
|
||||
}
|
||||
// Hosted unit tests run this app as their runner — never spawn a
|
||||
// real engine child there.
|
||||
guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return }
|
||||
await model.openSession()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Roster list
|
||||
|
||||
private var rosterList: some View {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 4) {
|
||||
ForEach(model.roster) { entry in
|
||||
SessionEntryRow(entry: entry, selected: entry.id == model.activeEntry?.id) {
|
||||
// Resume = activate: the engine replays the history
|
||||
// into the fresh transcript; unknown sessions land
|
||||
// the model's honest refusal row and stay rostered.
|
||||
Task { await model.resumeSession(entry) }
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(.bottom, 12)
|
||||
}
|
||||
}
|
||||
|
||||
private var paneBorder: some View {
|
||||
Rectangle()
|
||||
.fill(DesignTokens.border)
|
||||
.frame(width: 1)
|
||||
}
|
||||
|
||||
// MARK: Detail column
|
||||
|
||||
@ViewBuilder
|
||||
private var sessionDetail: some View {
|
||||
switch model.phase {
|
||||
case .idle, .starting:
|
||||
ProgressView("Starting the mentor engine…")
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
case .crashed:
|
||||
crashedNote
|
||||
case .ready:
|
||||
VStack(spacing: 0) {
|
||||
actionsRow
|
||||
Divider()
|
||||
if model.isStreaming {
|
||||
livenessRow
|
||||
Divider()
|
||||
}
|
||||
SessionTranscriptView(model: model, showsDebugRows: false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The active session's name + engine version, Fork/Compact beside them
|
||||
/// — disabled while a turn streams (canStartSession).
|
||||
private var actionsRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text(model.activeEntry?.name ?? "—")
|
||||
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
if let version = model.engineVersion {
|
||||
Text(version)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.lineLimit(1)
|
||||
.help(model.versionNote ?? version)
|
||||
}
|
||||
Spacer()
|
||||
Button("Fork") {
|
||||
Task { _ = await model.forkActiveSession() }
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.controlSize(.small)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.disabled(!model.canStartSession)
|
||||
.help("Copy this session's history into a new one")
|
||||
.accessibilityLabel("Fork session")
|
||||
Button("Compact") {
|
||||
Task { await model.compactActiveSession() }
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.controlSize(.small)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.disabled(!model.canStartSession)
|
||||
.help("Compress the session's history")
|
||||
.accessibilityLabel("Compact session")
|
||||
}
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.vertical, 8)
|
||||
}
|
||||
|
||||
/// Liveness (the Mentor pane's #23 posture, no input bar here): silent
|
||||
/// tool work must not read as dead, Stop is the pane's Cancel affordance.
|
||||
private var livenessRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
ProgressView()
|
||||
.controlSize(.small)
|
||||
Text("Mentor is working — Stop to interrupt.")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
.lineLimit(1)
|
||||
Spacer()
|
||||
Button("Stop") {
|
||||
model.stopStreaming()
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.controlSize(.small)
|
||||
.accessibilityLabel("Stop the mentor")
|
||||
}
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.vertical, 8)
|
||||
}
|
||||
|
||||
/// No second restart flow — the Mentor pane owns Restart (map decision).
|
||||
private var crashedNote: some View {
|
||||
VStack(spacing: 8) {
|
||||
Image(systemName: "exclamationmark.triangle.fill")
|
||||
.font(.system(size: 30))
|
||||
.foregroundStyle(.orange)
|
||||
Text("The mentor engine stopped")
|
||||
.font(.title3)
|
||||
Text("Restart it in the Mentor pane — nothing is lost.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(24)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
|
||||
// MARK: New Session control
|
||||
|
||||
@ViewBuilder
|
||||
private var newSessionControl: some View {
|
||||
if let piece = Self.openPiece(in: posts) {
|
||||
Menu {
|
||||
Button("New Session") { createSession(associatedWith: nil) }
|
||||
Button("New Session on \(piece.title)") { createSession(associatedWith: piece.title) }
|
||||
} label: {
|
||||
Image(systemName: "plus")
|
||||
}
|
||||
.menuStyle(.button)
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.disabled(!model.canStartSession)
|
||||
.help("New Session")
|
||||
.accessibilityLabel("New Session")
|
||||
} else {
|
||||
Button {
|
||||
createSession(associatedWith: nil)
|
||||
} label: {
|
||||
Image(systemName: "plus")
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.disabled(!model.canStartSession)
|
||||
.help("New Session")
|
||||
.accessibilityLabel("New Session")
|
||||
}
|
||||
}
|
||||
|
||||
private func createSession(associatedWith title: String?) {
|
||||
Task { _ = await model.newSession(name: "New Session", pieceTitle: title) }
|
||||
}
|
||||
|
||||
/// The open piece in Posts — the association target for the New Session
|
||||
/// choice (nil = free-floating only). Static + posts-coupled: test-pinned.
|
||||
static func openPiece(in posts: PostsModel?) -> Post? {
|
||||
guard let posts, let id = posts.session?.postID else { return nil }
|
||||
return posts.posts.first(where: { $0.id == id })
|
||||
}
|
||||
|
||||
private var emptyState: some View {
|
||||
VStack(spacing: 8) {
|
||||
Text("No sessions yet.")
|
||||
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
|
||||
Text("Sessions arrive when a pass runs — or create one with New Session.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
.padding(38)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
|
||||
/// One roster row: the library's post-row language — always-2px leading
|
||||
/// strip (accent when selected, no layout shift), surface card + border on
|
||||
/// selection, serif name over mono-11 meta (piece · created).
|
||||
private struct SessionEntryRow: View {
|
||||
let entry: SessionEntry
|
||||
let selected: Bool
|
||||
let select: () -> Void
|
||||
@State private var hover = false
|
||||
|
||||
var body: some View {
|
||||
// Same shape as LibraryPostRow: leading corners square (the 2px
|
||||
// strip), trailing rounded 8 — only the strip's COLOR changes.
|
||||
let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8))
|
||||
return Button(action: select) {
|
||||
HStack(spacing: 0) {
|
||||
Rectangle()
|
||||
.fill(selected ? DesignTokens.accent : .clear)
|
||||
.frame(width: 2)
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
Text(entry.name)
|
||||
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
Text(metaLine)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.padding(10)
|
||||
}
|
||||
.clipShape(shape)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(DesignTokens.foreground)
|
||||
.background {
|
||||
if selected || hover {
|
||||
shape
|
||||
.fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06))
|
||||
.overlay(
|
||||
shape.strokeBorder(selected ? DesignTokens.border : .clear),
|
||||
)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 8)
|
||||
.onHover { hover = $0 }
|
||||
.help(entry.name)
|
||||
.accessibilityLabel("\(entry.name), \(entry.pieceTitle ?? "free-floating session")")
|
||||
}
|
||||
|
||||
private var metaLine: String {
|
||||
var parts: [String] = []
|
||||
if let piece = entry.pieceTitle {
|
||||
parts.append(piece)
|
||||
}
|
||||
parts.append(FixCardStore.formatted(entry.createdAt, "yyyy-MM-dd HH:mm"))
|
||||
return parts.joined(separator: " · ")
|
||||
}
|
||||
}
|
||||
@@ -196,7 +196,13 @@ struct WorkspaceView: View {
|
||||
availableWidth: geo.size.width - DesignTokens.railWidth,
|
||||
)
|
||||
case .sessions:
|
||||
PlaceholderPane(title: "Sessions", detail: "Session lifecycle arrives with S2.3 (#28).")
|
||||
// #28: the Sessions pane — roster + active transcript over the
|
||||
// app-scoped mentor model, the same reach as Learnings' home.
|
||||
SessionsPaneView(
|
||||
model: gate.mentor,
|
||||
posts: gate.posts,
|
||||
binaryPath: gate.gateModel.currentBinaryPath,
|
||||
)
|
||||
case .learnings:
|
||||
// #26: list-only pane over <home>/learnings/ — read side;
|
||||
// promoting a fix card (the fix-card rail) writes the files.
|
||||
@@ -616,24 +622,3 @@ struct PaneHeader<Trailing: View>: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigation-target placeholder (#17 AC: panes exist as targets; real content
|
||||
/// arrives with their tickets — honest copy, no fake controls).
|
||||
struct PlaceholderPane: View {
|
||||
let title: String
|
||||
let detail: String
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 10) {
|
||||
Image(systemName: "hourglass")
|
||||
.font(.largeTitle)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
Text(title)
|
||||
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
|
||||
Text(detail)
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user