perf(editor): scope fold re-key to the edit (#142)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
With a fold open, every keystroke re-scanned the buffer, rebuilt the full attributed string through setAttributedString (invalidating TextKit layout for the ENTIRE document — O(n²) typing on folded documents), and rasterized a chrome image the size of the document (~35M pixels on a 700×50,000pt doc) to paint a handful of chevrons. Single-line edits now re-key folds in place: a shouldChangeText override records the edit (range + UTF-16 delta) and a pure rekey function shifts surviving folds, kills folds whose marker line was edited (un-hiding just that scope), and re-hides a line edited inside a hidden scope — no parents rescan, no storage swap. Structural edits, multi-line pastes, and wholesale loads keep the full pass; a font probe at each survivor's scope head falls back to it whenever hidden styling was wiped (the fence-flip restyle self-heals this way). Chrome renders as one tiny cached layer per list parent (same glyph rasters at ~15×18pt, geometry-flipped into the existing document-space overlay) instead of the document-sized bitmap; an edit at/after every parent line skips the rebuild outright, so writing at the document end does zero geometry queries. Full-buffer scans per keystroke drop from 2–3 to one. Finish-audit hardening: the single-line gate checks Character.isNewline (a literal newline compare passes CRLF — one grapheme equal to neither scalar), and apply() clears the recorded edit so structural indent/ outdent always takes the full pass (a childless unterminated block's shift-tab is a single-line replacement that would otherwise keep a dead fold's scope hidden — apparent line loss). Closes #142
This commit is contained in:
1 parent
de1154dacd
commit
cc317b65b9
9 files changed
+687
-114
No files matched your search
@@ -44,6 +44,7 @@ Owned by the root AGENTS.md contract.
|
||||
- `OutlineDragTests.swift` (#112) — the drag plumbing pins: the tracker holds its OWN arm-time copies of the callbacks (a post-arm swap of the view's closures never fires — the gesture is self-contained, so a mid-drag scroll that drops the origin row's catcher can't strand the surface's drag state; a true dealloc can't be reproduced in the host — AppKit keeps internal retains on once-installed views, so the swap is the observable), arming a second drag cancels a stuck predecessor as a cancel, and `rowFrames` prefers the grip catcher's full-row frame over the body catcher's text-only frame in both subview orders.
|
||||
- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
|
||||
- `ProseListTests.swift` (#115 / S5) — the prose list model + fold rendering: scan pins (item basics, nested children + fold scope, lazy continuation, blank-separated child folds the blank too, fences end blocks, parents scan), indent/outdent (dash content column, caret ride + park, ordered-marker unit, boundary nils), move (subtree swap with between-text, boundary no-ops); `ProseFoldRenderingTests` (@MainActor, plain `ProseListTextView()` — no window, chrome never installs) — folding never edits the buffer, hidden scopes carry `foldedAttributes`, parent stays body-size, unfold restores, folds re-key to the nearest same-marker parent after an edit above, and a fold dies when its marker text vanishes.
|
||||
- `ProseRekeyTests.swift` (#142, F1 — scenario header at file top; own file, split from ProseListTests at the file-length ceiling) — `ProseFoldRekeyTests` drives the keystroke pipeline through the REAL seams (`shouldChangeText` records → storage mutates → `refreshFolds`): a single-line edit above re-keys in place with hidden styling intact (no storage swap), typing on the marker line kills the fold AND restores its scope to view, a multi-line edit still takes the full pass, and a wholesale restyle (the fence-flip shape) self-heals into the full pass via the font probe; `ProseRekeyMathTests` pins the pure `rekey` math exactly (shift above, untouched below, death + translated diedScope, boundary-insertion deaths at both marker-content edges, scope-interior deletion → shrunk scope + rehide range + caret park). The painted-layer chrome skip itself is unpinnable headless (needs a window) — dogfood owns it.
|
||||
- `SettingsModelTests.swift` (#135, Profiles S2 — scenario headers at file top) — the Settings view-model mapping over a live-shaped registry fixture (claude-sonnet-5-5 deliberately ABSENT — custom is the default state): provider → effort ladders (zai low/high/max; OpenAI + Anthropic low/medium/high/xhigh/max) + effort-unset default + provider-switch reset; custom-model state (seed custom, registry id known, per-provider pinned switch defaults, empty registry = all custom free text, blank edits never commit); z.ai key-type → endpoint family (both defaults, toggle swaps, custom endpoint survives, cleared endpoint adopts the family); the `SettingsWriting` seam via a `RecordingWriter` double (surface writes carry config, key writes carry keyType only for zai — struct record, not a tuple, #134 ConfigWrite precedent; `cannedKeys` feeds `readProviderKey(provider:)` — #136 dogfood amendment: keys land in ALL THREE `.env` files, so hydration refills every key field with no per-provider profile list; `failSurfaceWrites` knob pins the failure path — `lastWriteError` surfaces, next success clears it); write-sync via `awaitPendingWrites()` (deterministic, never sleeps); the hydration clamp (an effort outside the provider's ladder reads nil); `ModelRegistry.load` lenient decode (unknown providers skipped, missing file → empty, never fatal); the ModelComboBox commit rails (list pick via `comboBoxSelectionDidChange`, Enter via the action, blur via end-editing — idempotent through the echo guard, blanks never commit; the dogfood #135 pin: a bare dropdown pick fires neither action nor end-editing). **#136 (Profiles S3):** the RecordingWriter double carries the new protocol shape (surface records include `zaiEndpoint`, key records the fan-out `profiles`, `cannedReads` feeds `readSurface`); the #136 model-side pins live in `SettingsModelWritePathTests.swift` (own file, file-length ceiling) sharing the now-internal `RecordingWriter` + `liveShapedRegistry` — a provider switch to a keyed zai threads the endpoint family into the surface write WITHOUT re-firing keys (they pre-landed in all three `.env` files at entry time), key writes carry the surfaces-on-provider list as the zai base_url write-through targets (chat first), rapid key edits coalesce into one write (superseded writes never spawn — partial key prefixes never reach `.env`; `writeDebounce: 0` keeps the suite deterministic), hydrate maps profile reads + infers the zai key type from the coding base_url (unread/unknown-provider surfaces stay seeded) and SEEDS a custom zai base_url instead of clobbering it, an edit made mid-hydrate never gets stomped, a second edit WAITS for the in-flight write (record order pinned `old → new`), and an unkeyed Test Connection authFails fast off the network; `probeModel` picks the first surface on a provider else its flagship. `HermesSettingsWriterTests.swift` (own file) — the real write path against the fake CLI (Real-Process pattern): write→`config get` round-trip, the exact config-set ORDER (provider → model → effort → base_url LAST, because setting model.provider clears base_url — live-probed), nil-effort unset + idempotent unset-when-absent, the `.env` writes over temp profile dirs (the key lands in ALL THREE profiles — a key with no surface on its provider still persists; foreign lines + comments preserved byte-for-byte, 0600 — hermes' own posture, the zai base_url config-set rides ONLY the listed profiles, an empty key leaves bytes alone but still writes the zai base_url, non-zai providers never config-set; readProviderKey round-trips, a line-broken key value is refused with nothing written — the env-injection guard), profile-named failures, missing-binary refusals + nil reads, and pure `upsertEnv` edges (in-place replace, append, trailing-newline, empty). `ProviderProbeTests.swift` (own file) — the factsheet decode matrix: zai 1113 → wrongKeyType, 401s per provider (Anthropic detail carries `request_id`), 429/foreign bodies → requestFailed; the three SSE dialects (zai chat-completions content + reasoning channels, Anthropic text_delta/stop_reason, OpenAI Responses output_text.delta/completed/incomplete/failed) — works carries reply + model count, `finish=length`/`max_tokens`/`incomplete` + empty → starved, response.failed → requestFailed, and the live 2026-10-28 z.ai **200-carried error envelope** (wrong content-type) decodes as the provider error; `ssePayloads` skipping event/DONE/blank lines; `decodeModelsCount` shapes; free `probeHTTPResponse`/`probeData` canned-response helpers live here (shared-helper convention). `ProviderProbeTransportTests.swift` (own file — the decode suite crossed its type-body ceiling, MCPToolsPromoteTests precedent) — the request builders (the 2026-10-28 Content-Type pin across all providers; Anthropic `x-api-key` + pinned version + required max_tokens; zai `thinking:enabled`+`reasoning_effort:low` wire at the 512 cap; **OpenAI in the ResponseLine truncated
|
||||
- `PersonaLoadOrderTests.swift` (#1) — persona-content pins over the REAL bundled payload (`ProfileProvisioner.defaultPayloadRoot()`): both personas carry the `## Draft first, rules last` load-order doctrine (pass-persona 1.5 / session-persona 1.2, the PRD prompt-end rule), and the section is verbatim-shared between the pair (the four-shared-sections contract, ref/writing skills/AGENTS.md). Verified layout lives in `docs/research/prompt-layout-factsheet.md`.
|
||||
|
||||
|
||||
@@ -283,7 +283,13 @@ struct ProseFoldRenderingTests {
|
||||
// an edit above shifts every line down by 3 ("x\n\n" prefix)
|
||||
textView.textStorage?.replaceCharacters(in: NSRange(location: 0, length: 0), with: "x\n\n")
|
||||
textView.refreshFoldRendering()
|
||||
#expect(textView.folds == [ProseListTextView.Fold(key: 3, lineText: "- parent")])
|
||||
#expect(textView.folds == [
|
||||
ProseListTextView.Fold(
|
||||
key: parent.markerLine.location + 3,
|
||||
lineText: "- parent",
|
||||
scope: NSRange(location: parent.foldScope.location + 3, length: parent.foldScope.length),
|
||||
),
|
||||
])
|
||||
let font = try #require(textView.textStorage?.attribute(.font, at: 13, effectiveRange: nil) as? NSFont)
|
||||
#expect(font.pointSize < 1) // the shifted child stays hidden
|
||||
}
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
//
|
||||
// ProseRekeyTests.swift
|
||||
// Museion
|
||||
//
|
||||
// #142 (F1): "a keystroke beside a fold re-keys it in place" — Given a
|
||||
// folded list and the caret elsewhere, When a single-line edit lands,
|
||||
// Then the fold survives with key + hidden scope shifted by the edit
|
||||
// delta (no whole-document rescan or restyle), and a fold whose marker
|
||||
// line was edited dies with its scope restored to view.
|
||||
//
|
||||
// Two suites: the view-level pipeline (shouldChangeText records →
|
||||
// storage mutates → refreshFolds re-keys in place) and the pure
|
||||
// `rekey` math.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
struct ProseFoldRekeyTests {
|
||||
private func makeView(_ text: String) -> ProseListTextView {
|
||||
let textView = ProseListTextView()
|
||||
textView.isRichText = false
|
||||
textView.textStorage?.setAttributedString(ProsePresenter.attribute(text))
|
||||
return textView
|
||||
}
|
||||
|
||||
/// The coordinator's keystroke pipeline — shouldChangeText records the
|
||||
/// single-line edit, the storage mutates, refreshFolds re-keys in place.
|
||||
private func type(
|
||||
_ replacement: String, in range: NSRange,
|
||||
of textView: ProseListTextView,
|
||||
) {
|
||||
textView.shouldChangeText(in: range, replacementString: replacement)
|
||||
textView.textStorage?.replaceCharacters(in: range, with: replacement)
|
||||
textView.refreshFolds()
|
||||
}
|
||||
|
||||
@Test func `single-line edit above rekeys fold in place`() throws {
|
||||
let text = "intro\n\n- parent\n - child\n"
|
||||
let textView = makeView(text)
|
||||
let parent = try #require(ProseList.parents(in: text).first)
|
||||
textView.toggleFold(parent)
|
||||
type("xx", in: NSRange(location: 0, length: 0), of: textView) // in the intro line
|
||||
#expect(textView.folds == [
|
||||
ProseListTextView.Fold(
|
||||
key: parent.markerLine.location + 2,
|
||||
lineText: "- parent",
|
||||
scope: NSRange(location: parent.foldScope.location + 2, length: parent.foldScope.length),
|
||||
),
|
||||
])
|
||||
// the shifted scope is still hidden — nothing swapped it away
|
||||
let font = try #require(
|
||||
textView.textStorage?.attribute(.font, at: parent.foldScope.location + 2, effectiveRange: nil) as? NSFont,
|
||||
)
|
||||
#expect(font.pointSize < 1)
|
||||
}
|
||||
|
||||
@Test func `typing on the marker line kills the fold and restores its scope`() throws {
|
||||
let text = "- parent\n - child\n"
|
||||
let textView = makeView(text)
|
||||
let parent = try #require(ProseList.parents(in: text).first)
|
||||
textView.toggleFold(parent)
|
||||
type("x", in: NSRange(location: 0, length: 0), of: textView) // at the line head
|
||||
#expect(textView.folds.isEmpty)
|
||||
let font = try #require(
|
||||
textView.textStorage?.attribute(.font, at: parent.foldScope.location + 1, effectiveRange: nil) as? NSFont,
|
||||
)
|
||||
#expect(font.pointSize > 10) // the dead scope is visible again
|
||||
}
|
||||
|
||||
@Test func `multi-line edit still takes the full pass`() throws {
|
||||
let text = "- parent\n - child\n"
|
||||
let textView = makeView(text)
|
||||
let parent = try #require(ProseList.parents(in: text).first)
|
||||
textView.toggleFold(parent)
|
||||
type("x\n\n", in: NSRange(location: 0, length: 0), of: textView)
|
||||
#expect(textView.folds == [
|
||||
ProseListTextView.Fold(
|
||||
key: parent.markerLine.location + 3,
|
||||
lineText: "- parent",
|
||||
scope: NSRange(location: parent.foldScope.location + 3, length: parent.foldScope.length),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
@Test func `newline deletion routes to the full pass`() throws {
|
||||
// Forward-delete at the parked caret removes the marker line's \n and
|
||||
// merges the child into it — the OLD text contains a line break, so
|
||||
// the edit must NOT take the cheap path. The cheap path's delta math
|
||||
// would keep the fold alive on a no-longer-parent line; the full pass
|
||||
// re-scans and kills it. Pins the isSingleLine(old) guard.
|
||||
let text = "intro\n\n- parent\n - child\n"
|
||||
let textView = makeView(text)
|
||||
let parent = try #require(ProseList.parents(in: text).first)
|
||||
textView.toggleFold(parent)
|
||||
type("", in: NSRange(location: 15, length: 1), of: textView) // delete the \n
|
||||
#expect(textView.string == "intro\n\n- parent - child\n")
|
||||
#expect(textView.folds.isEmpty) // merged line has no children → fold dies
|
||||
}
|
||||
|
||||
@Test func `crlf in the edited text routes to the full pass`() throws {
|
||||
// "\r\n" is ONE Swift grapheme equal to neither "\n" nor "\r" — a
|
||||
// literal line-break compare lets this deletion ride the cheap path,
|
||||
// keeping a stale fold whose hidden scope eats half the merged line.
|
||||
// The isNewline gate must route it to the full pass (the #142 audit's
|
||||
// converged finding).
|
||||
let text = "intro\r\n\r\n- parent\r\n - child\r\n"
|
||||
let textView = makeView(text)
|
||||
let parent = try #require(ProseList.parents(in: text).first)
|
||||
textView.toggleFold(parent)
|
||||
type("", in: NSRange(location: 17, length: 2), of: textView) // delete the CRLF after "- parent"
|
||||
#expect(textView.string == "intro\r\n\r\n- parent - child\r\n")
|
||||
#expect(textView.folds.isEmpty) // merged line has no children → fold dies
|
||||
let font = try #require(
|
||||
textView.textStorage?.attribute(.font, at: 17, effectiveRange: nil) as? NSFont,
|
||||
)
|
||||
#expect(font.pointSize > 10) // the merged line is fully visible
|
||||
}
|
||||
|
||||
@Test func `structural outdent always takes the full pass`() throws {
|
||||
// #142 audit: a childless UNTERMINATED block's outdent is a single-line
|
||||
// replacement — apply() must clear pendingPlainEdit or the cheap path
|
||||
// keeps the dead fold's scope hidden (the line appears lost).
|
||||
let text = "- p\n - c1"
|
||||
let textView = makeView(text)
|
||||
let parent = try #require(ProseList.parents(in: text).first)
|
||||
textView.toggleFold(parent)
|
||||
let child = try #require(ProseList.item(at: 6, in: text))
|
||||
textView.setSelectedRange(NSRange(location: 6, length: 0))
|
||||
textView.performOutdent(child)
|
||||
textView.refreshFolds() // the coordinator's tail — no delegate headless
|
||||
#expect(textView.string == "- p\n- c1")
|
||||
#expect(textView.folds.isEmpty) // "- p" lost its only child → fold dies
|
||||
let font = try #require(
|
||||
textView.textStorage?.attribute(.font, at: 4, effectiveRange: nil) as? NSFont,
|
||||
)
|
||||
#expect(font.pointSize > 10) // the outdented line is visible
|
||||
}
|
||||
|
||||
@Test func `scope interior edit rehides the line and parks the caret`() throws {
|
||||
// The cheap path's view glue, with the coordinator simulated: the
|
||||
// paragraph reattribute un-hides the edited hidden line, then
|
||||
// refreshFolds must re-hide it and park the caret at the marker end.
|
||||
// The edit lands in the SECOND hidden line — the scope-head probe
|
||||
// can't catch this damage (the first hidden line is untouched), so
|
||||
// only the rehide glue covers it.
|
||||
let text = "intro\n\n- parent\n - c1\n - c2\n"
|
||||
let textView = makeView(text)
|
||||
let parent = try #require(ProseList.parents(in: text).first)
|
||||
textView.toggleFold(parent)
|
||||
let edit = NSRange(location: 25, length: 0) // inside the second hidden line " - c2"
|
||||
textView.setSelectedRange(edit)
|
||||
textView.shouldChangeText(in: edit, replacementString: "x")
|
||||
textView.textStorage?.replaceCharacters(in: edit, with: "x")
|
||||
// the coordinator's paragraph reattribute (PostEditorView order)
|
||||
let paragraph = (textView.string as NSString).paragraphRange(for: textView.selectedRange())
|
||||
try ProsePresenter.reattribute(#require(textView.textStorage as? NSMutableAttributedString), paragraphRange: paragraph)
|
||||
textView.refreshFolds()
|
||||
#expect(textView.folds == [
|
||||
ProseListTextView.Fold(key: 7, lineText: "- parent", scope: NSRange(location: 16, length: 15)),
|
||||
])
|
||||
let font = try #require(
|
||||
textView.textStorage?.attribute(.font, at: 25, effectiveRange: nil) as? NSFont,
|
||||
)
|
||||
#expect(font.pointSize < 1) // re-hidden by the glue
|
||||
#expect(textView.selectedRange().location == 15) // parked at the marker end
|
||||
}
|
||||
|
||||
@Test func `wholesale restyle self-heals into the full pass`() throws {
|
||||
// The fence-flip branch replaces the whole storage AFTER the edit was
|
||||
// recorded — the cheap path's probe must notice the hidden styling is
|
||||
// gone and fall back, or the fold would render open-but-invisible.
|
||||
// (Edit lands in the intro line, above the fold, so the fold itself
|
||||
// survives the re-key and only the probe can catch the damage.)
|
||||
let text = "intro\n\n- parent\n - child\n"
|
||||
let textView = makeView(text)
|
||||
let parent = try #require(ProseList.parents(in: text).first)
|
||||
textView.toggleFold(parent)
|
||||
textView.shouldChangeText(in: NSRange(location: 0, length: 0), replacementString: "x")
|
||||
textView.textStorage?.setAttributedString(ProsePresenter.attribute(textView.string))
|
||||
textView.refreshFolds()
|
||||
#expect(textView.folds.count == 1)
|
||||
let font = try #require(
|
||||
textView.textStorage?.attribute(.font, at: textView.folds[0].scope.location, effectiveRange: nil) as? NSFont,
|
||||
)
|
||||
#expect(font.pointSize < 1) // re-hidden by the full pass
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
struct ProseRekeyMathTests {
|
||||
/// intro | blank | parent + two children | tail — one foldable parent.
|
||||
private let text = "intro\n\n- parent\n - child one\n - child two\n- tail\n"
|
||||
// layout: marker line (7,9), content end 15, scope (16,28), tail at 44.
|
||||
|
||||
private func makeFold() throws -> ProseListTextView.Fold {
|
||||
let parent = try #require(ProseList.parents(in: text).first)
|
||||
return ProseListTextView.Fold(key: parent.markerLine.location, lineText: "- parent", scope: parent.foldScope)
|
||||
}
|
||||
|
||||
@Test func `edit above shifts key and scope`() throws {
|
||||
let fold = try makeFold()
|
||||
let result = ProseListTextView.rekey(
|
||||
folds: [fold], edit: NSRange(location: 0, length: 0), delta: 2, in: "xx" + text,
|
||||
)
|
||||
#expect(result.folds == [ProseListTextView.Fold(key: 9, lineText: "- parent", scope: NSRange(location: 18, length: 28))])
|
||||
#expect(result.diedScopes.isEmpty)
|
||||
#expect(result.rehide == nil)
|
||||
#expect(result.park == nil)
|
||||
}
|
||||
|
||||
@Test func `edit below the scope leaves the fold untouched`() throws {
|
||||
let fold = try makeFold()
|
||||
let result = ProseListTextView.rekey(
|
||||
folds: [fold], edit: NSRange(location: 44, length: 0), delta: 1, in: text + "z",
|
||||
)
|
||||
#expect(result.folds == [fold])
|
||||
#expect(result.diedScopes.isEmpty)
|
||||
#expect(result.rehide == nil)
|
||||
}
|
||||
|
||||
@Test func `editing the marker line kills the fold`() throws {
|
||||
let fold = try makeFold()
|
||||
let result = ProseListTextView.rekey(
|
||||
folds: [fold], edit: NSRange(location: 7, length: 8), delta: -3,
|
||||
in: "intro\n\n- god\n - child one\n - child two\n- tail\n",
|
||||
)
|
||||
#expect(result.folds.isEmpty)
|
||||
#expect(result.diedScopes == [NSRange(location: 13, length: 28)]) // translated for the un-hide
|
||||
#expect(result.rehide == nil)
|
||||
#expect(result.park == nil)
|
||||
}
|
||||
|
||||
@Test func `insertions at either marker-content boundary kill too`() throws {
|
||||
let fold = try makeFold()
|
||||
// at the head (el == key) and at the park position (el == contentEnd)
|
||||
for location in [7, 15] {
|
||||
let result = ProseListTextView.rekey(
|
||||
folds: [fold], edit: NSRange(location: location, length: 0), delta: 1,
|
||||
in: "intro\n\n- parentx\n - child one\n - child two\n- tail\n",
|
||||
)
|
||||
#expect(result.folds.isEmpty, "insertion at \(location) should kill the fold")
|
||||
#expect(result.diedScopes.count == 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `deletion inside the scope shrinks it and flags a re-hide`() throws {
|
||||
let fold = try makeFold()
|
||||
// delete "one" (26,3) inside the first hidden line
|
||||
let result = ProseListTextView.rekey(
|
||||
folds: [fold], edit: NSRange(location: 26, length: 3), delta: -3,
|
||||
in: "intro\n\n- parent\n - child \n - child two\n- tail\n",
|
||||
)
|
||||
#expect(result.folds == [ProseListTextView.Fold(key: 7, lineText: "- parent", scope: NSRange(location: 16, length: 25))])
|
||||
#expect(result.diedScopes.isEmpty)
|
||||
// the edited line, clipped to the scope — the paragraph reattribute
|
||||
// un-hid it and it must go back under
|
||||
#expect(result.rehide == NSRange(location: 16, length: 11))
|
||||
#expect(result.park == 15) // caret parks at the marker line's content end
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user