diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 852ae55..2c89efa 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -21,7 +21,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro ## 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, and — 2026-11-05 owner ruling — the chat's three face constructors `valkyrie`/`concourse`/`ubuntuMono` (Valkyrie OT B / Concourse OT Book / UbuntuMono NFM, PostScript names mirroring ProseTypography; Font.custom falls back to system when absent). **#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, with the single semantic exception `readyGreen` (#153/#156: the mentor header's ready dot; a meaning, never a style color). -- `WorkspaceView.swift` — the first-frame main surface (#151: gateless — rendered unconditionally by ContentView; the engine check runs async beside it): nav rail (Posts/Sessions/Learnings/Trends + the #151 engine-status pill + Settings at bottom) + active pane. `RailButton` (44×44, muted icon, hover wash, surface tile + hairline border when current, icon in fg ink — **ui-polish r2 re-ruling:** NO visible edge bar; the export's `::before` selection bar paints BEHIND the app border in the export's own render, so contract-faithful is tile + border + fg-ink icon alone). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \
` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView` (ui-polish r1: the document title — first non-blank body line — renders at the 22pt title rung in the SERIF body face (#ui-r2: face change only, Valkyrie not the sans heading face; after-space measured so the title→body ink gap is 24–28pt, editor top padding 40pt), list lines hang at their marker-prefix width MEASURED IN THE EXACT RENDER ATTRIBUTES (#ui-r2: markers render in the body face at foreground-0.8 ink — the r1 mono-render/body-measure drift put continuations ~4pt left), and programmatic caret landings hop past leading blank lines via `caretPastLeadingBlanks` — the r1 stray-caret artifact was the caret parked in an invisible leading blank fragment), toggle wiring (#68) all stand; editing-side spacing obligation lives in #77. - `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`; non-file URLs read back as nil — the Home is always a folder). **#171:** fresh installs (no stored override) resolve once and PIN the winner, so the Home never silently moves: (2) legacy `~/Documents/Museion` exists as a directory (`existingDirectory` gate — a stray plain file is not a Home and falls through) → pin it (existing Homes migrate manually, never silently), (3) `/Museion` when iCloud Drive is present (CloudDocs resolved dynamically at the unprefixed `Library/Mobile Documents/com~apple~CloudDocs` path — never a hard-coded `iCloud~` form; plain FileManager probing, no ubiquity entitlements per ADR-0009), (4) else the silent Documents fallback — no dialog, no rail pill. The ladder + probes live in `HomeResolution.swift` (`resolvedInitialHome`/`liveCloudDocsDir`/`existingDirectory`); init takes injectable probes + defaults — hosted tests drive the ladder without touching the machine's real iCloud state, and the DEFAULT construction under hosted tests takes an early return (legacy fallback Home): neither the real probes nor the pin run, so the runner app's real iCloud state and defaults are never touched. Explicit init: `Self` in a stored-property initializer breaks `@ObservationTracked` (covariant-Self error). diff --git a/Museion/MentorSessionModel.swift b/Museion/MentorSessionModel.swift index 8c4fe76..73ecde7 100644 --- a/Museion/MentorSessionModel.swift +++ b/Museion/MentorSessionModel.swift @@ -551,6 +551,9 @@ final class MentorSessionModel { timeout: Self.promptTimeout, ) replayingSessionId = nil + // Finish-audit: the replay slot is free — a scope switch that + // deferred BEHIND this replay applies now. + firePendingScopeIfRequested() // The real adapter (0.21.5, live-verified #30 dogfood) answers // session/load WITHOUT a top-level sessionId — the id rides // `_meta.hermes.sessionProvenance.acpSessionId`. The fake's @@ -585,6 +588,7 @@ final class MentorSessionModel { return true } catch { replayingSessionId = nil + firePendingScopeIfRequested() // 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) @@ -609,6 +613,14 @@ final class MentorSessionModel { pendingScopePieceTitle = pieceTitle return } + // Finish-audit: a replay in flight defers the switch too — the + // scope rail is an AUTOMATIC action and must never leak a + // "Resume refused" row into the transcript (the replay's + // completion re-fires the pending scope). + guard replayingSessionId == nil else { + pendingScopePieceTitle = pieceTitle + return + } pendingScopePieceTitle = nil let target = SessionRoster.hostedSessionId(forOpenPieceTitle: pieceTitle, in: roster) guard activeEntry?.sessionId != target else { return } diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift index e75f949..c04349d 100644 --- a/Museion/PostEditorView.swift +++ b/Museion/PostEditorView.swift @@ -424,17 +424,7 @@ struct ProseTextView: NSViewRepresentable { /// over leading blanks to the first content line; interactive /// placements (click, drag, typing) never route through here. static func caretPastLeadingBlanks(_ location: Int, in text: String) -> Int { - let buffer = text as NSString - var lineStart = 0 - while lineStart < buffer.length { - let line = buffer.lineRange(for: NSRange(location: lineStart, length: 0)) - let lineText = buffer.substring(with: line) - if !lineText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - return location < line.location ? line.location : location - } - lineStart = NSMaxRange(line) - } - return location + max(location, ProsePresenter.firstContentLocation(text as NSString) ?? location) } func makeNSView(context: Context) -> NSScrollView { diff --git a/Museion/PostsPaneView.swift b/Museion/PostsPaneView.swift index de280ef..4eb1f83 100644 --- a/Museion/PostsPaneView.swift +++ b/Museion/PostsPaneView.swift @@ -409,32 +409,23 @@ struct PostsLibraryColumn: View { /// #144 + mercury#54 (r4): a real field surface — surface fill + hairline /// border on the column's chrome, taller than a text row; the placeholder - /// renders in the palette's muted ink via the under-Text trick (stronger - /// than the system's faint default — it reads as an input, not sidebar - /// text). r5 (argon#44, mercury#52, sol#37): the insertion caret tints + /// r5 (argon#44, mercury#52, sol#37): the insertion caret tints /// terracotta (.tint on the field), and the small magnifier glyph sits at - /// the field's leading edge (icon→text spacing rides the HStack's 6pt). + /// the field's leading edge (icon→text spacing rides the HStack's 6pt); + /// the placeholder is the native prompt wearing the palette's muted ink + /// (the composer's pattern). /// r8 (argon#6, mercury#12): focus draws a QUIET 1pt ring — accent at 0.6, /// present but never the strongest saturation on screen. private var searchField: some View { HStack(spacing: 6) { - Image(systemName: "magnifyinglass") + Image(systemName: "magnifyingglass") .font(.system(size: 11)) .foregroundStyle(DesignTokens.muted) - ZStack(alignment: .leading) { - if query.isEmpty { - Text("Search posts") - .font(.system(size: 12)) - .foregroundStyle(DesignTokens.muted) - .allowsHitTesting(false) - } - TextField("", text: $query) - .textFieldStyle(.plain) - .font(.system(size: 12)) - .focused($searchFocused) - .tint(DesignTokens.accent) - .accessibilityLabel("Search posts") - } + TextField("Search posts", text: $query, prompt: Text("Search posts").foregroundStyle(DesignTokens.muted)) + .textFieldStyle(.plain) + .font(.system(size: 12)) + .focused($searchFocused) + .tint(DesignTokens.accent) if isSearching { Button { query = "" diff --git a/Museion/ProsePresenter.swift b/Museion/ProsePresenter.swift index 804c325..be824ff 100644 --- a/Museion/ProsePresenter.swift +++ b/Museion/ProsePresenter.swift @@ -486,20 +486,9 @@ nonisolated extension ProsePresenter { var lineStart = 0 while lineStart < nsText.length { let line = nsText.lineRange(for: NSRange(location: lineStart, length: 0)) - var len = line.length - while len > 0 { - let char = nsText.character(at: line.location + len - 1) - if char == 0x0A || char == 0x0D { - len -= 1 - } else { - break - } - } - if len > 0 { - let text = nsText.substring(with: NSRange(location: line.location, length: len)) - if !text.trimmingCharacters(in: .whitespaces).isEmpty { - return line.location - } + let lineText = nsText.substring(with: line) + if !lineText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + return line.location } lineStart = NSMaxRange(line) } diff --git a/Museion/SessionTranscriptView.swift b/Museion/SessionTranscriptView.swift index 6d46423..c3f0030 100644 --- a/Museion/SessionTranscriptView.swift +++ b/Museion/SessionTranscriptView.swift @@ -130,8 +130,8 @@ struct SessionTranscriptView: View { // PREDECESSOR in reach — the warning-styling and gap rules // below are pairwise, not per-row. LazyVStack(alignment: .leading, spacing: 18) { - ForEach(visible.indices, id: \.self) { index in - rowView(visible[index], previous: index > 0 ? visible[index - 1] : nil) + ForEach(Array(visible.enumerated()), id: \.element.id) { pair in + rowView(pair.element, previous: pair.offset > 0 ? visible[pair.offset - 1] : nil) } if showsDebugRows, !model.streamingThought.isEmpty { // Live thinking: open while it runs (spinner toggle), diff --git a/Museion/SessionsPaneView.swift b/Museion/SessionsPaneView.swift index 9c4b98a..10ff600 100644 --- a/Museion/SessionsPaneView.swift +++ b/Museion/SessionsPaneView.swift @@ -522,7 +522,14 @@ nonisolated enum WordBoundaryTruncation { /// (lineLimit catches it). static func fit(_ text: String, maxWidth: CGFloat, lines: Int = 2) -> String { let words = text.split(separator: " ", omittingEmptySubsequences: true).map(String.init) - guard !words.isEmpty, lineCount(words, maxWidth) > lines else { return text } + guard !words.isEmpty else { return text } + // Finish-audit: measure each word ONCE — a pathological title (an + // imported post's first line is unbounded) must not turn the + // candidate loop into quadratic glyph measurement on the main actor. + // ponytail: one pass per word is fine to ~10k words; bail to native + // lineLimit if a roster row ever renders slower than a frame. + let widths = words.map { width($0) } + guard lineCount(widths, maxWidth) > lines else { return text } var head = [words[0]] if words.count > 2, words[2] == "·" { head = [words[0], words[1], words[2]] @@ -537,22 +544,24 @@ nonisolated enum WordBoundaryTruncation { index += 1 } let tail = Array(words.dropFirst(head.count)) + let ellipsis = width("…") + let headWidths = Array(widths[0 ..< head.count]) for count in stride(from: tail.count, through: 1, by: -1) { - let candidate = head.joined(separator: " ") + " … " + tail.suffix(count).joined(separator: " ") - if lineCount(candidate.split(separator: " ").map(String.init), maxWidth) <= lines { - return candidate + let candidateWidths = headWidths + [ellipsis] + Array(widths[(words.count - count)...]) + if lineCount(candidateWidths, maxWidth) <= lines { + return head.joined(separator: " ") + " … " + tail.suffix(count).joined(separator: " ") } } return head.joined(separator: " ") + "…" } /// Greedy word wrap (the text system's own algorithm): how many - /// lines `words` need at `maxWidth`. - private static func lineCount(_ words: [String], _ maxWidth: CGFloat) -> Int { + /// lines `widths` (per-word glyph widths, measured once) need at + /// `maxWidth`. + private static func lineCount(_ widths: [CGFloat], _ maxWidth: CGFloat) -> Int { var lines = 1 var used: CGFloat = 0 - for word in words { - let tokenWidth = width(word) + for tokenWidth in widths { if used == 0 { // A word wider than the line keeps its own line — the // mid-word break is SwiftUI's, never the seam's. diff --git a/Museion/SettingsPaneView.swift b/Museion/SettingsPaneView.swift index b2b4623..70c98a7 100644 --- a/Museion/SettingsPaneView.swift +++ b/Museion/SettingsPaneView.swift @@ -328,7 +328,7 @@ struct ElidedPathText: View { /// The candidate ladder, longest first: the full path, then each /// shorter variant with one more leading component kept whole. - static func candidates(_ path: String) -> [String] { + nonisolated static func candidates(_ path: String) -> [String] { let comps = path.split(separator: "/").map(String.init) guard comps.count > 2 else { return [path] } var ladder = [path] @@ -339,7 +339,7 @@ struct ElidedPathText: View { } /// The longest candidate whose glyph-measured width fits `width`. - static func elide(_ path: String, into width: CGFloat) -> String { + nonisolated static func elide(_ path: String, into width: CGFloat) -> String { let font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular) func fits(_ candidate: String) -> Bool { (candidate as NSString).size(withAttributes: [.font: font]).width <= width diff --git a/Museion/WorkspaceView.swift b/Museion/WorkspaceView.swift index 577f752..698a1f0 100644 --- a/Museion/WorkspaceView.swift +++ b/Museion/WorkspaceView.swift @@ -774,12 +774,8 @@ struct SelectedRowStrip: View { /// surface fill with a #E8E5DF hairline (Archive's Unarchive, Settings' /// Choose…). 36pt tall by default — a real hit target, not a text-size /// pill; pass a smaller `minHeight` where the row is compact. -/// r5 (argon#21): `softBorder` halves the hairline's opacity for the one -/// placement that sits INSIDE a field group (Choose…) — a full-strength -/// stroke there read as a double border. struct BorderedSecondaryButtonStyle: ButtonStyle { var minHeight: CGFloat = 36 - var softBorder: Bool = false func makeBody(configuration: Configuration) -> some View { configuration.label @@ -792,7 +788,7 @@ struct BorderedSecondaryButtonStyle: ButtonStyle { .fill(DesignTokens.surface) .overlay( RoundedRectangle(cornerRadius: 8) - .strokeBorder(DesignTokens.border.opacity(softBorder ? 0.5 : 1)), + .strokeBorder(DesignTokens.border), ), ) .opacity(configuration.isPressed ? 0.7 : 1) diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 6a3a089..33847ea 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -34,7 +34,7 @@ Owned by the root AGENTS.md contract. - `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · " renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation. **#137 flip (per #129):** passes are TRANSIENT and never roster — the #28 roster pin died with per-surface engines; the own-engine/spawn-log/reap pins live in `EngineLifecycleTests.swift` (a PassRunTests duplicate of that pin was deleted in the #137 finish audit), the transient-entry pin in `SessionLifecycleTests.swift`; `textRows(of:)` is internal here (the shared-helper convention) for EngineLifecycleTests' rigs. **#31 (S5.1) wiring pins:** a pass on a writer First Draft piece captures the five stats keys AND completes (Pass-1 Done — capture never blocked the pass), a CANCELLED pass (`cancelOnPrompt`) still captured at the invocation with the state untouched, an ai-origin piece runs with NO stats (origin alone decides, never the outcome). **#6 (S3.4) wiring pin** (`DeslopLintWiringTests`, suite member at file tail — the #31/#134 vacuous-filter lesson): a pass invocation on a sloppy piece seeds emitter `lint` cards under ` /cards/` AND the `stats_*` keys — stats capture and lint both fired at the one invocation seam. - `BlindReadTests.swift` (#122 — scenario headers at file top, `@Suite` so suite-filters run it) — the Blind Read pins: `BlindRead.prompt` (both bodies inline under "Version A/B" in the given order, flip swaps, NO origin words — snapshot/current/original/revised never appear, the pick+one-line ask) and `reveal` (exact mapping per kind+flip); `PostStore.latestPassSnapshot` (newest mtime wins across pass-1/pass-2 — decisive +60 s attribute set, the write-order race is real; none → nil); the advisory run over `makeBlindRig` (makeModelHome + `makeFakeACP` + the fake's DIR — makePassRig doesn't expose it): the mentor rail (fresh `acp -p museion` spawn counted in the spawn log — the resident engine is the only other `museion` spawn, pass profiles never; label row "Blind Read · "; reveal lands ONLY on `.ended`, `cancelOnPrompt` leaves none; roster never grows) and the model orchestration (`blindRead`: prompt-log carries both bodies and no path; `pass_state` stays First Draft — records nothing; `runningBlindRead` clears; no-snapshot → `lastError` "run a Pass first" with nothing spawned beyond the resident engine; snapshot == current → "No edits since" refusal). **Finish-audit pins:** a REFUSED read (`refuseOnPrompt`) ends `.ended(stopReason: "refusal")` and reveals nothing (the gate is the stopReason, never the outcome — a refusal still ends .ended; flip-verified), and a held read (`hangOnPrompt`) owns the rail — a concurrent pass refuses "already running", `cancelPass` ends the turn with no reveal and `pass_state` untouched. - `DeslopLintTests.swift` (#6, S3.4 — scenario header at file top, all tests `@Suite` members) — the native deslop lint pins: the exact finding set AND rank order over a known sloppy draft (em-dash first, Tier 1 by first-match position, Tier 2 after; exact owner-facing problem/diagnostic copy, mixed-case anchor preservation `Utilize` with its exact-substring occurrence, mechanical lane for the mapped `utilize`→`use`, demonstration for `delve`, counts inside the problem strings, NO finding for within-allowance `furthermore`), whole-word boundaries (`delved`/`harnessed`/`showcased` never fire their stems), em-dash at budget 4 → silent (0 too), the empty AND whitespace-phrase trust-boundary pin (#6 audit: the `— —` body is space-phrase bait — a plain body passes vacuously; submit's validation trims, so a whitespace phrase would kill the whole submit), the config story (Home override wins when it exists AND decodes, malformed override falls back to the bundled default, `home: nil` → bundled, `bundledConfig()` decodes the two tiers + budget 4 + the mapped replacements), and the store-level emit loop over `PostStore.writeNew` (cards land emitter `lint`/open/pass 1/valid anchors, re-emit dedups against OPEN cards, a `.skipped` close re-emits its still-present finding). -- `SessionScopeTests.swift` (owner ruling 2026-11-07 — scoped mentor hosting) — the pure seam pin: `SessionRoster.hostedSessionId(forOpenPieceTitle:in:)` = the NEWEST exact `pieceTitle` match over the newest-first roster; near-misses, no open piece, or an empty roster → nil (the pane's honest empty presentation). The pane/model rails (`MentorPaneView.scopeToOpenPiece`, `scopeHostedSession` + the stream-end deferral) are engine-path behavior — the seam is what's pinned here. +- `SessionScopeTests.swift` (owner ruling 2026-11-07 — scoped mentor hosting) — the pure seam pin: `SessionRoster.hostedSessionId(forOpenPieceTitle:in:)` = the NEWEST exact `pieceTitle` match over the newest-first roster; near-misses, no open piece, or an empty roster → nil (the pane's honest empty presentation). The pane/model rails (`MentorPaneView.scopeToOpenPiece`, `scopeHostedSession` + the stream-end deferral) are engine-path behavior — the seam is what's pinned here. Finish-audit (2026-11-07) added the deferral's model-level pin over the REAL client path: `loadReplayHold` (the fake parks session/load after a `hold-load` stderr line) parks a replay of piece A while B's session is active; `scopeHostedSession` to A then DEFERS — no `Resume refused` row in `model.rows`, `activeEntry` unchanged (flip-verified) — the parked child dies with teardown, the resume task is never awaited. Same audit: `WordBoundaryTruncationTests` gained degenerate passthrough pins (whitespace-only, space-free CJK one-word, single long word); `PolishSeamTests.swift` (new) pins `ProsePresenter.firstContentLocation` (leading-blank skip / nil on all-blank) and `ElidedPathText.candidates`/`elide` (both `nonisolated` statics since 2026-11-07 — a MainActor-isolated static called off-actor through stdlib `first(where:)` traps the host app at runtime, the compile is clean). - `WordBoundaryTruncationTests.swift` (round-5 ui-polish → round-6 glyph-measured → round-7 middle-eliding → round-8 head-biased ~60/40 split, sol#3 — the roster title's pure truncation seam in SessionsPaneView.swift: NSFont serif-13 semibold measured against the 192pt two-line width) — short-string passthrough, the native mid-word cut ("Markdo…") landing at a word edge ("Markdown…"), and the exact strings for the two live Handoff roster titles ("Pass N · Museion Handoff — … apex) vs. Hand-rolled TextKit") — the head keeps the pass label + leading words into ~60% of the glyph budget (`headShare`), the longest fitting suffix the rest. The round-6 warning-row headline/detail split (`SessionTranscriptView.warningParts`) + the round-8 calm-copy seam (`SessionTranscriptView.calmDetail` — the engine's "waiting for model response (X elapsed)" renders "waiting on the model — X", everything else verbatim) are pinned in ACPClientTests beside the other transcript seams. - `SessionLifecycleTests.swift` (#28, S2.3) — the session-lifecycle scenarios over the real client + fake ACP path (`loadReplay` mode, injectable `rosterDirectory` temp dirs): pass streams into a TRANSIENT unrostered transcript (#137 flip — roster unchanged, the transient entry owns the active surface, entry name "Pass 1 · \ "), freeform new (pieceTitle nil = free-floating; non-nil carries the name), resume replays engine-owned history in wire order WITH user turns rendered (the live-echo ignore does not apply on replay), engine-unknown resume → `false` + honest row + entry stays rostered (never a fabricated empty session), fork (" (fork)", pieceTitle carried, original untouched, empty-string wire id refused), compact (the `/compress` label turn, raw command never renders), and roster persistence round-trip (a fresh model instance over the same directory restores entries — never transcripts); plus `new-session choice reads Posts' open piece` (the pane's `openPiece(in:)` — nil posts / nothing open / open piece). **#30:** the draft-candidate pins over hand-built rows (no engine — the pure `draftCandidateText(in:)` seam): the LAST "Mentor: " text row wins across user/thought/card/research/raw lanes, empty and user-only transcripts yield nil, a trailing blank mentor row doesn't blank the prefill while an earlier real reply exists, and the refusal/connection-shaped rows sharing the display prefix never prefill (an error is not the draft). **#30 audit pins:** `brainstorm opens a rostered session with the labeled opener` (roster head "Brainstorm", piece-associated, the labeled opener renders and the raw prompt never does, the reply streams into ITS transcript) and `resume accepts the legacy top-level sessionId shape` (the `loadReplayLegacy` knob; the dual-shape resume read's second branch — flip-verified: removing the provenance fallback fails the provenance-shape pins, this pin guards the other). `ResearchCandidateTests.swift` (#29, own file — SessionLifecycleTests crossed its type-body ceiling; MCPToolsPromoteTests precedent) holds the research-candidate pins over the same shared fake: the fake's `loadReplay` mode streams one `submit_research_notes` `tool_call` (base64 payload; the research line reuses the fix-card line's exact quoting), and a `strayResearchOnPrompt` mode (ACPClientTests) streams a research batch carrying stray `pattern`/`problem` keys; pins — `ResearchCandidate.batch` (two notes → two candidates with `""` defaults; no piece_path / empty notes / note missing url / whitespace-only title or url → []), resume re-materializes the candidates from the replay (the AC pin — engine-owned cargo), `setResearchDisposition` flips the active session's rows and no-ops unknown ids, `isWritingRow` keeps `.researchNote` in the writing voice, and the stray-key payload renders CANDIDATES, never a card (routing is by the notes-array shape, before the fix-card parse — titles are display text, not a routing key). - `EngineLifecycleTests.swift` (#137, Profiles S4 — scenario headers at file top) — the per-surface engine lifecycle over the shared helpers via a local rig (`makeModelHome` + `makeFakeACP` keeping the fake's DIR — the spawn log beside the fake is the which-engine-ran observable): **A1** a pass run lives on its own engine end-to-end (spawn log carries `acp -p museion-pass1` beside the chat engine's `acp -p museion`, roster count UNCHANGED, `isPassEngineRunning` false after the verdict, the pass child pid reaped via `kill(pid, 0)`, the chat child still alive, snapshot + Pass-1 Done + label row + streamed verdict on the active surface), cancel of a held pass (hangOnPrompt — pid captured mid-run, Cancel rail ends the turn, state stays First Draft with the snapshot landed, child reaped, roster unchanged), **A2** idle `requestRestart` respawns in place (old pid reaped, new alive, phase back to .ready, the PRE-restart active rostered session resumed + replayed) and the deferred-ordering pin (requestRestart mid-turn holds — same pid while streaming — and the pid swap fires only AFTER `stopStreaming` ends the turn). pid capture rides Task + bounded poll (the pid is only observable while the pass engine runs); reaped checks are bounded polls. **B1 (#137 acceptance 3, scenario header mid-file):** readiness pins over the shared `RecordingWriter` injected as `passReadinessWriter` (keyed provider → `.ready`, unkeyed z.ai → `.missingKey("z.ai")`, a canned key landing re-enables on the next refresh — the pane-re-entry path — unreadable surfaces → `.unknown`), plus the PostsModel guard pin: an OPEN piece + `.missingKey` → `lastError` names z.ai and `passes/pass-1.md` never lands (the guard fires before the snapshot; the test #requires the piece open so the open-piece guard can't pass it vacuously); the guard's `readiness(for:)` reads `.unknown` as never-blocking). **#137 finish-audit pins:** `a resume completing mid-pass does not steal the pass surface` — `loadReplayHold` parks a session/load, the mode file flips to `hangOnPrompt` BEFORE the pass engine spawns (each child reads the mode at startup) so the pass holds deterministically, `load-go` completes the load mid-hold → the model's ONE post-await `claimActive` gate refuses (resume false, honest row, activeEntry stays the pass key, roster intact) and Cancel still routes to the pass engine; model-side audit fixes it pins against: activation writers (create/resume/fork) route through `claimActive` (post-await ownership re-check), `ensureDefaultSession` early-outs `phase = .ready` when a turn streams, the pass-profile map guards instead of force-unwrapping, and PostsModel's vanish-kill is `watchedHome`-gated (a scan that outlived a Home repoint never kills a session under the new home). diff --git a/MuseionTests/PolishSeamTests.swift b/MuseionTests/PolishSeamTests.swift new file mode 100644 index 0000000..2a58a08 --- /dev/null +++ b/MuseionTests/PolishSeamTests.swift @@ -0,0 +1,47 @@ +// +// PolishSeamTests.swift +// MuseionTests +// +// Finish-audit pins for the ui-polish loop's pure seams that shipped +// "so a test can pin" them but no pin landed: the editor's +// first-content walker (title detection + the caret hop ride it) and +// the settings path elision ladder. +// + +import Foundation +@testable import Museion +import Testing + +@Suite("PolishSeamTests") +struct PolishSeamTests { + /// Leading blank lines are skipped to the first CONTENT line; a + /// whitespace-only buffer has none (nil); a buffer with no leading + /// blanks returns 0. The same walker styles the title line and hops + /// programmatic carets past the invisible blank fragment. + @Test func `firstContentLocation skips leading blanks`() { + let plain = "Title\n\nbody" as NSString + #expect(ProsePresenter.firstContentLocation(plain) == 0) + let blankLead = "\n\n \nTitle\nbody" as NSString + let loc = ProsePresenter.firstContentLocation(blankLead) + #expect(loc == 5) // three leading blank lines (5 UTF-16 units incl. newline) before "Title" + #expect(ProsePresenter.firstContentLocation("" as NSString) == nil) + #expect(ProsePresenter.firstContentLocation("\n \n\t\n" as NSString) == nil) + } + + /// The ladder keeps the full path, then each shorter variant with one + /// more leading component kept whole; ≤2 components has nothing to + /// elide. `elide` picks the longest candidate that fits. + @Test func `ElidedPathText candidate ladder and elision`() { + let path = "/Users/alex/Library/Mobile Documents/com~apple~CloudDocs/Museion" + let ladder = ElidedPathText.candidates(path) + #expect(ladder.first == path) + #expect(ladder.last == "/Users/…/Museion") + #expect(ladder.count == path.split(separator: "/").count - 1) + // Short paths never elide. + #expect(ElidedPathText.candidates("/a/b") == ["/a/b"]) + // A wide-enough field keeps the full path; a narrow one falls to + // the shortest rung. + #expect(ElidedPathText.elide(path, into: 5000) == path) + #expect(ElidedPathText.elide(path, into: 10) == "/Users/…/Museion") + } +} diff --git a/MuseionTests/SessionScopeTests.swift b/MuseionTests/SessionScopeTests.swift index 9084127..f3e4387 100644 --- a/MuseionTests/SessionScopeTests.swift +++ b/MuseionTests/SessionScopeTests.swift @@ -38,4 +38,55 @@ struct SessionScopeTests { // A title with no roster behind it hosts nothing. #expect(SessionRoster.hostedSessionId(forOpenPieceTitle: "Essay X", in: []) == nil) } + + /// Finish-audit: the scope rail is an AUTOMATIC action — when the one + /// replay slot is busy (another session's session/load in flight), the + /// switch DEFERS like a stream (old behavior: resumeSession refused and + /// appended a user-visible "Resume refused" row for an action the writer + /// never took). Pinned over the real client path with the fake's + /// `loadReplayHold` mode parking the replay; teardown kills the parked + /// child, so the resume task is deliberately never awaited. + @MainActor + @Test func `scope switch defers behind an in-flight replay without refusing`() async throws { + let dir = acpTempDir("scope-defer") + let fake = makeFakeACP(at: dir, mode: "loadReplayHold") + let model = MentorSessionModel(binaryPath: fake, rosterDirectory: dir) + defer { model.shutdown() } + await model.openSession() // empty roster — creates the default session, completes + guard case .ready = model.phase else { + Issue.record("expected ready, got \(model.phase)") + return + } + // Two rostered pieces through the real flow; B's session is active. + guard await model.newSession(name: "On A", pieceTitle: "Piece A") != nil, + await model.newSession(name: "On B", pieceTitle: "Piece B") != nil + else { + Issue.record("session creation refused") + return + } + let entryA = try #require(model.roster.first { $0.pieceTitle == "Piece A" }) + let activeBefore = model.activeEntry?.sessionId + // Park A's replay behind the hold — the load sits in flight, the + // slot stays taken, and B remains the pane's surface. + _ = Task { await model.resumeSession(entryA) } + var held = false + for _ in 0 ..< 250 where !held { + held = model.stderrTail.contains { $0.contains("hold-load") } + if !held { + try await Task.sleep(nanoseconds: 20_000_000) + } + } + #expect(held) + await model.scopeHostedSession(toOpenPieceTitle: "Piece A") + let refused = model.rows.contains { row in + if case let .text(text) = row.content { + return text.contains("Resume refused") + } + return false + } + #expect(!refused) + // The switch applied nowhere yet — deferred, not refused and not + // swapped behind the replay. + #expect(model.activeEntry?.sessionId == activeBefore) + } } diff --git a/MuseionTests/WordBoundaryTruncationTests.swift b/MuseionTests/WordBoundaryTruncationTests.swift index 003c698..15fe715 100644 --- a/MuseionTests/WordBoundaryTruncationTests.swift +++ b/MuseionTests/WordBoundaryTruncationTests.swift @@ -1,6 +1,6 @@ // // WordBoundaryTruncationTests.swift -// Museion +// MuseionTests // // Round-5 (mercury#4/sol#8/argon#16) → Round-6 glyph-measured // (mercury#4/sol#9) → Round-7 middle-eliding (argon#14/sol#32/47) → @@ -53,4 +53,17 @@ struct WordBoundaryTruncationTests { #expect(WordBoundaryTruncation.fit(pass1, maxWidth: 192, lines: 2) == "Pass 1 · Museion Handoff — … apex) vs. Hand-rolled TextKit") } + + /// Finish-audit edge pins: the seam passes degenerate shapes through + /// untouched — whitespace-only splits to no words, a space-free CJK + /// title is ONE word, and a single word wider than the line keeps its + /// own line (lineLimit(2) renders it). None may crash or mangle. + @Test func `degenerate shapes pass through unchanged`() { + let whitespace = " " + #expect(WordBoundaryTruncation.fit(whitespace, maxWidth: 192, lines: 2) == whitespace) + let cjk = "静かなウェブの再考" // no spaces — ONE word, wider than the line + #expect(WordBoundaryTruncation.fit(cjk, maxWidth: 40, lines: 2) == cjk) + let singleLongWord = "Supercalifragilisticexpialidocious" + #expect(WordBoundaryTruncation.fit(singleLongWord, maxWidth: 50, lines: 2) == singleLongWord) + } }