feat(editor): drop an image into the prose (#141)
CI / ci (push) Canceled after 0s

Dragging an image onto a saved post's prose editor copies it (never
moves) into the piece's assets/ under a parser-clean slugged name
(collision -2 via the shared uniqueFile helper) and inserts
![alt](assets/<slug>.<ext>) at the drop point with alt selected for
type-over — one edit step, one undo.

Routing rides the window-level SwiftUI drop destination, field-verified
to starve every deeper drag destination (nested SwiftUI targets never
fire; AppKit NSDraggingDestination overrides never fire). Pure-markdown
sets keep the open-as-guest behavior; mixed md+image sets refuse loudly
instead of silently dropping the images behind the opened markdown.

The drop point comes from NSEvent.mouseLocation mapped through the one
geometry source that answers under SwiftUI hosting —
firstRect(forCharacterRange:), bottom-up screen coords. Non-contiguous
layout returns zero/stale rects for off-screen characters, so the solve
(a pure static function, pinned by windowless tests) samples the
document, keeps only viewport-band rects, brackets the drop between two
in-band samples, binary-searches the bracket, and slides to the next
whitespace gap — a landing never splices inside a word or an existing
ref. The typewriter inset re-syncs after the edit so scrolling never
freezes. The source gate refuses folders and symlinks alike: copyItem
would land the LINK itself, and the #34 publish rail would then refuse
the whole send. Type gate = the rail's exact set (PNG/JPEG/GIF/WebP/
SVG) — nothing enters assets/ that can't ship. Drafts, outlines, and
guest surfaces refuse loudly.

Finish-audit (three fresh-context reviewers) drove the mixed-set
routing, the symlink refusal, and the pure-function extraction; every
pin flip-verified in one batched cycle. Eleven ingest tests; suite 557.

Closes #141
This commit is contained in:
AlexKucera committed 2026-11-02 17:47:35 +01:00
1 parent 695ec27e11
commit de1154dacd
12 files changed
+622 -14

No files matched your search

@@ -0,0 +1,78 @@
# #141 — Drop an image onto the prose editor: illustration ingest
> **Date:** 2026-11-02
> **Type:** issue
> **Reference:** Gitea issue #141 (museion)
## Goal
Drag an image file onto a saved post's prose editor → the file is **copied** (never moved) into the piece's `assets/` under a parser-clean slugged name, and `![alt](assets/<slug>.<ext>)` is inserted at the drop point with `alt` selected for type-over. Type gate = exactly #34's publishable set (PNG/JPEG/GIF/WebP/SVG via `Micropub.mimeType`); drafts/outlines/guest refuse loudly; markdown drops keep #91's open-as-guest behavior. Followed by a full finish-audit pass (three fresh-context reviewers) with all accepted findings fixed and flip-verified.
## What Was Done
- `PostStore.swift` — `IngestError` (LocalizedError: `notPublishable` / `isFolder` / `isLink` / `hostileAssets`), `illustrationRef(_:)` (the one `![alt](…)` builder), `ingestImage(from:pieceFolder:)`: extension+mimeType gate → plain-file gate (folder AND symlink refuse — `copyItem` copies the link itself) → `hostileAssets` destination gate → slug + `FixCardStore.uniqueFile` collision (`-2`/`-3`) → copy → returns the ref destination.
- `ProseListTextView.swift` — `ingestFolder`, `ingestDrop(_:)` (gates → copy each → one `shouldChangeText` insert → select `alt` → `syncTypewriterInset` → `scrollRangeToVisible`), `dropIndex(...)` — the drop-point solve extracted as a `nonisolated static` pure function, `showIngestNotice` transient rust strip (auto-hide ~4 s).
- `WorkspaceView.swift` — the window-level `.dropDestination` is the sole routing surface: PURE-markdown sets (`allSatisfy`) open as guest, everything else bridges to `ingestDrop`.
- `MuseionApp.swift` / `PostEditorView.swift` — app-scoped `ProseDropBridge` (weak live text-view handle) on `AppGateState.proseDrop`, pointed at the live view by `ProseTextView` make/updateNSView; non-optional at both constructor call sites.
- `MuseionTests/ImageIngestTests.swift` — 11 tests: slug/copy/rail-parse, `-2` collision, refusal matrix (HEIC/PDF/folder-with-png-ext), `ingestDrop` insert+alt-select, loud refusal, symlink source, mixed md+image set, and 4 windowless `dropIndex` pins (banded synthetic rectY).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Window-level `.dropDestination` as the only drag surface | Field-verified: it starves EVERY deeper destination — NSTextView's `NSDraggingDestination` overrides and a nested editor-level SwiftUI destination both never fire. One window target routes both markdown and images. |
| Drop point from `NSEvent.mouseLocation`, not the closure's `location` | The SwiftUI closure's location proved unusable under this hosting (every conversion chain mis-mapped by ~⅓ document). The live pointer during perform IS the drop point. |
| Viewport-banded sample→bracket→binary-search over `firstRect` | #115 extension: `firstRect(forCharacterRange:)` is the only geometry source that answers under SwiftUI hosting; its y is bottom-up screen coords like the mouse (no flip); non-contiguous layout makes off-screen chars return garbage rects, so only in-viewport-band rects are trusted (plain NSView geometry). Pointer above band → first visible char; below → band tail; no evidence → 0. |
| Whitespace-gap slide after landing | Line-grain y-only mapping can land inside a word or an existing ref token; slide to the next gap (a drop ON a ref appends after it). |
| `syncTypewriterInset` after the insert | Dogfood: without it the typewriter inset is stale and the editor freezes scrolling until the next keypress — leave the scroll stack as a keystroke would. |
| Symlink source refuses (`isLink`) | Finish-audit (empirically verified): `copyItem` lands the LINK itself; the #34 rail then refuses the whole publish (all-or-nothing) — a publish DoS plus a latent exfil if the rail ever loosens. |
| PURE-markdown routing (`allSatisfy`) | Finish-audit: `first(where:)` silently dropped images in mixed md+image drags behind the opened guest. Mixed sets now hit the loud refusal. |
| Collisions via `FixCardStore.uniqueFile` | House helper with identical `-2` semantics (finish-audit ponytail finding); deleted the bespoke loop. |
| `dropIndex` extracted pure | Makes the geometry solve testable without a window — the HIGH finish-audit finding (silent index-0 landing) lived exactly in the untestable part. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Image drops did nothing (green copy badge, silent refusal) | Window-level SwiftUI `.dropDestination` starves all deeper drag destinations — nested SwiftUI targets never fire, AppKit `NSDraggingDestination` never fires | Route everything through the window destination; bridge to the live text view via app-scoped `ProseDropBridge` |
| Ref landed at start/end/one-paragraph-off through every conversion chain | SwiftUI closure location + `characterIndex(for:)` mis-map under SwiftUI hosting (#115 family) | Read `NSEvent.mouseLocation`, map via `firstRect` rects (bottom-up screen coords — NO flip) |
| Ref landed at the layout boundary / document start | Non-contiguous layout: off-screen characters return zero/stale rects; whole-doc binary search converged on garbage; `lastAbove=0` trusted without in-band evidence | Viewport-band filter (sample→bracket→search) + in-band-evidence guards + pure-function extraction with tests |
| Ref spliced INSIDE an existing `![alt](…)` token | Line-grain insert + links carry no whitespace | Whitespace-gap slide |
| Editor jumped and scrolling froze until next keypress | Insert left the typewriter inset stale; next keystroke's `syncTypewriterInset` healed it | Call `syncTypewriterInset` right after the edit |
| Mixed md+image drags silently dropped the images | `urls.first(where: isMarkdown)` forwarded any set containing an md | `allSatisfy` gate; mixed falls through to the loud refusal |
| `CharacterSet.characterIsMember` suggested by a reviewer | Not bridged to Swift — compile error this session | Keep the `Unicode.Scalar` membership helper |
| `log stream`/`log show` unreliable for the app's NSLog | — | Capture stderr directly: run the binary with `> scratch/museion-stderr*.log 2>&1` |
| xcresult summary read fails with "doesn't exist" | Reading the bundle while xcodebuild finalizes it (#33, known) | Read only after the process exits |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/PostStore.swift` | `IngestError`, `illustrationRef`, `ingestImage` (symlink/folder/mime gates, uniqueFile collision) |
| `Museion/ProseListTextView.swift` | `ingestFolder`, pure `dropIndex`, `ingestDrop`, `showIngestNotice` |
| `Museion/WorkspaceView.swift` | Window destination routing: pure-markdown → guest, else → ingestDrop |
| `Museion/MuseionApp.swift` | `AppGateState.proseDrop` app-scoped bridge |
| `Museion/PostEditorView.swift` | `ProseDropBridge` class + non-optional `dropBridge` plumbing |
| `MuseionTests/ImageIngestTests.swift` | New: 11 tests incl. finish-audit pins (all flip-verified batched) |
| `Museion/AGENTS.md` | #141 contracts rewritten to final architecture (routing, gates, drop-point solve, audit pins) |
| `MuseionTests/AGENTS.md` | ImageIngestTests description incl. finish-audit pins |
| `AGENTS.md` | Session-log window refresh |
## Verification
- Full suite **557/557** (551 baseline + 6 new), xcresult executed-count verified, idle machine
- Flip cycle: all 3 new guards flipped off in one batch — each pin failed on its own guard; restored, green
- swiftformat clean; swiftlint zero new violations (PostEditorView's 6 warnings byte-identical at HEAD)
- Dogfood: drop lands within one line of the pointer; scrolling stays live
- GitNexus detect-changes (high — index-relative; the diff-scope review covered the real blast radius) + analyze refreshed
## Open Items & Next Steps
- [ ] Drop placement is line-grain (no x-axis refinement within the line) — v2 knob if it bothers
- [ ] Deferred finish-audit LOWs: dangling-symlink name squat, main-actor copy size cap, `isFolder` message catch-all (vanished/web URLs), `assets/` vs `Assets/` case split-brain
- [ ] The window destination's pure-markdown routing is unpinned (no SwiftUI drop harness) — ingest-side gate is pinned
- [ ] User's scratch: `prompt-order-probe` test post still carries the spliced line-9 refs from the buggy round
---
*Log written by write-log skill*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-11-02 | issue | [20261102-issue141-image-drop-illustration-ingest_log.md](20261102-issue141-image-drop-illustration-ingest_log.md) | Image drop → assets/ ingest at drop point; window-destination routing, firstRect viewport-band solve, finish-audit fixes |
| 2026-11-01 | issue | [20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md](20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md) | #34 illustrations: media-endpoint upload, refs rewrite INLINE with URLs (dogfood killed the photo property); audit: injection/symlink/dedup — 546 tests |
| 2026-10-31 | issue | [20261031-issue33-m6-micropub-draft-publish-s6-1_log.md](20261031-issue33-m6-micropub-draft-publish-s6-1_log.md) | Two-step Micro.blog publish: Micropub draft→update, Keychain token, trustworthyURL gate, category inert |
| 2026-10-31 | issue | [20261031-issue32-m4-trend-view-s5-2_log.md](20261031-issue32-m4-trend-view-s5-2_log.md) | #32 trend view: four metric charts over first-draft captures, read-back origin/type gate + finite parse; audit fixed nan/inf crash — 508 tests |