feat(publish): illustrations travel inline (#34)
CI / ci (push) Canceled after 0s

A piece's assets/ ink-sketch images publish with it: Send as Draft
first uploads every referenced image to Micro.blog's media endpoint
(q=config discovery, one multipart file POST per FILE — duplicate
refs share an upload), then each ![alt](assets/…) ref REWRITES IN
PLACE with its uploaded URL in the wire content. The image renders
exactly where the writer placed it and the alt rides the markdown;
the piece on disk never changes.

The first shape attached uploads as a Micropub photo property with
mp-photo-alt — live dogfood (2026-11-01) showed the theme renders
properties at the bottom of the post, losing position. No property
ships at all now; inline refs are the only transport, which also
makes the parsed body ref the only way an image ships — the alt
floor at the illustration rail is therefore the only gate a photo
needs (G12: a whitespace-empty alt refuses naming the file before
anything touches the wire; the mentor is never consulted).

Pre-flight gates every payload: the endpoint's exact formats
(PNG/JPEG/GIF/WebP/SVG), path containment resolved through symlinks
(a planted link never uploads outside-file bytes under the writer's
token), all-or-nothing uploads. A URL carrying markdown-active
characters rides the angle form ![alt](<url>) — a plain-paren
destination would close at the first ) and smuggle a live link into
the published post; the frontmatter trust gate does not cover
markdown's grammar.

Finish-audit (three reviewers) drove the angle form, the symlink
containment, the per-file upload dedup, and four pins; all four
behavior guards flip-verified in one batch cycle. Suite 546 passed /
0 failed; swiftformat + swiftlint clean. Ingest UX (drop image onto
the editor) is #141, blocked by this issue.
This commit is contained in:
AlexKucera committed 2026-11-01 21:52:58 +01:00
1 parent 414f1392ef
commit 695ec27e11
10 files changed
+840 -19

No files matched your search

+1 -1
View File
@@ -23,7 +23,7 @@ Owned by the root AGENTS.md contract.
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved — through the in-place `pass_state` stamp since #31, formerly the block rewrite; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`.
- `DraftStatsTests.swift` (#31, S5.1) — the four metrics pinned over hand-derived expectations (the scenario header lives in the file top): sentences [3,2,1] → burstiness ≈ −0.4202 / variation ≈ 0.4082 / TTR 1 / trigram 0, regular sentences → burstiness −1 with trigram 0.25, empty body → all zeros, single sentence → −1, case folding (`Dog dog DOG` → 1/3) + the no-apostrophe-joining ceiling pinned as TTR facts.
- `MicropubTests.swift` (#33, S6.1 — scenario header at file top, `@Suite`; shared helpers `MicropubRequestLog`/`micropubHTTP`/`micropubCanned`/`micropubJSON` internal) — the wire contract pinned over canned transports (ProviderProbeTransportTests pattern): draft request = h=entry with name/content/post-status draft and Bearer auth; publish request = the post-status update; Location-then-body-url decode with preview, preview-only = requestFailed (display-only, never the publish target), an injection-carrying URL = requestFailed (trustworthyURL gate), a scan-side untrustworthy `micropub_url` reads nil, no-URL create = requestFailed, 401/403 → authFailed with the error_description, non-2xx → requestFailed, transport throw → unreachable; `MicropubTokenStore` round-trips the REAL login keychain against its OWN injected account slot (a live production token is never read, replaced, or deleted — the finish-audit #33 clobber fix); `stampMicropubURL` pins (in-place stamp: foreign `category:` key + body byte-preserved, scan reads `micropub_url` back, vanished throws); and the model flow over `makeModelHome` (flush-first — the wire carries the edited text, Title publishes as name from the ONE disk read, refused-without-open-piece and refused-on-unsaved-draft and refused-on-whitespace-only-body send nothing, **the AC pin: a piece carrying `category:` frontmatter drafts with NO category key on the wire**, a failed draft stamps nothing, re-draft overwrites the remembered URL — the model pins live in `MicropubModelTests.swift` (own file, the decode suite crossed its type-body ceiling; finish-audit split)).
- `MicropubTests.swift` (#33, S6.1 — scenario header at file top, `@Suite`; shared helpers `MicropubRequestLog`/`micropubHTTP`/`micropubCanned`/`micropubJSON` internal) — the wire contract pinned over canned transports (ProviderProbeTransportTests pattern): draft request = h=entry with name/content/post-status draft and Bearer auth; publish request = the post-status update; Location-then-body-url decode with preview, preview-only = requestFailed (display-only, never the publish target), an injection-carrying URL = requestFailed (trustworthyURL gate), a scan-side untrustworthy `micropub_url` reads nil, no-URL create = requestFailed, 401/403 → authFailed with the error_description, non-2xx → requestFailed, transport throw → unreachable; `MicropubTokenStore` round-trips the REAL login keychain against its OWN injected account slot (a live production token is never read, replaced, or deleted — the finish-audit #33 clobber fix); `stampMicropubURL` pins (in-place stamp: foreign `category:` key + body byte-preserved, scan reads `micropub_url` back, vanished throws); and the model flow over `makeModelHome` (flush-first — the wire carries the edited text, Title publishes as name from the ONE disk read, refused-without-open-piece and refused-on-unsaved-draft and refused-on-whitespace-only-body send nothing, **the AC pin: a piece carrying `category:` frontmatter drafts with NO category key on the wire**, a failed draft stamps nothing, re-draft overwrites the remembered URL — the model pins live in `MicropubModelTests.swift` (own file, the decode suite crossed its type-body ceiling; finish-audit split)). **#34 (S6.2):** `MicropubMediaTests.swift` (own file — `micropubPNG()`/`micropubMediaScripted` helpers internal, the scripted transport routes config → upload → create by target URL) pins the media surface: illustration parse (plain + inline + quoted-title + empty-alt refs captured honestly; remote http(s) and non-`assets/` refs left alone), rewrite (each UPLOADED ref swaps in place with its uploaded URL — position and alt preserved, quoted titles drop, foreign images and unuploaded refs byte-identical, a URL carrying markdown-active chars rides the ANGLE form `![alt](<url>)` — a plain dest would close early and smuggle a live link), the mime matrix (all six formats + the refusal), the config request + `media-endpoint` decode (trust-gated — an injection-carrying endpoint is requestFailed), the multipart `file` POST asserted over BYTES (part head, payload, closing delimiter, per-request boundary), `uploadMedia`'s create-mirroring decode (Location → body url → trust gate; authFailed on 403), the no-photo-keys-EVER create pin (images travel inline in content — a photo property renders wherever the theme decides, live-verified 2026-11-01), the boundary pin (empty map passes through verbatim, adjacent start/end refs rewrite with clean cursor math), and the multi-line-alt agreement pin (a ref whose alt spans lines doesn't parse at all — a parsed-but-unrewritten ref would ship a broken relative link); the #34 model pins live in `MicropubModelTests.swift` — the three-hop ORDER (q=config, multipart carrying the PNG bytes, create with the ref REWRITTEN to its uploaded URL exactly where placed while the disk body keeps the local ref — no photo property keys), the AC2 floor (WHITESPACE-empty alt — the #6 trimmed-emptiness class — refuses naming the destination with ZERO requests served, nothing stamped), missing-file + SYMLINKED-asset refusals pre-wire (containment resolves symlinks — never read through a planted link), DUPLICATE refs to one asset uploading once and sharing the URL, and a piece without illustrations sending exactly ONE request (#33's wire unchanged).
- `TrendViewTests.swift` (#32, S5.2 — scenario header at file top, `@Suite` so suite filters run it) — the trend view's pure facts: scan reads a REAL capture back (`writeNew` + `captureFirstDraftStats` → `firstDraftStats` values match `DraftStats.compute` at %.3f grain; the parsed date round-trips through the exact stamp format via `FixCardStore.formatted` — locale-independent proof), never-captured pieces scan nil BY CONSTRUCTION (an ai piece whose capture RAN and was refused at the gate + an outline + an untouched writer post — no filtering, the keys just never exist), partial/malformed `stats_*` keys never half-load, `TrendMetric.verdict` pins (improving/steady/slipping at ±0.01, trigram inverted), and the y-domain pins (burstiness −1…1 / TTR + trigram fixed 0…1 / sentenceVariation scales to 1.2× peak with floor 1), the explain pin (every metric carries a distinct, non-empty gloss naming its better-direction — a fifth metric without one fails), the finish-audit pins — `non-finite stats values never load` (`nan`/`inf` in one key, all else valid, via the `writeStamped(id:overriding:home:)` shared fixture whose per-key overrides keep each test's one varying fact visible), `read-back gates on the immutable pair` (imported ai/outline pieces carrying hand-stamped keys scan nil; a Pass-1-Done writer piece keeps its arc — pass_state never gates) — both flip-verified (each pin fails on its own guard) — and the exact-tolerance verdict boundary (delta == 0.01 reads steady, strict comparisons).
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), `submit refuses a symlinked cards dir` (#6 audit — throws with nothing written through the link, promote's posture), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#29:** all three tools listed with required arrays (research schema: piece_path+notes at top, title+url per note); a well-formed `submit_research_notes` round-trip replies `{"received": N}` with isError absent and lands NOTHING on disk (the candidates rail writes nothing); a note missing `title` answers isError (the trust boundary). **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses.
- `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve).
+295
View File
@@ -0,0 +1,295 @@
//
// MicropubMediaTests.swift
// MuseionTests
//
// #34 (S6.2): illustrations travel with it. Scenario:
//
// Given a saved Post whose body references ink-sketch PNGs from its
// assets/ with alt text
// When the writer sends the piece as a draft and publishes
// Then each PNG uploads once via the media endpoint (q=config →
// multipart → 202 + Location) and its ref REWRITES IN PLACE with
// the uploaded URL — the image renders exactly where the writer
// placed it, alt travels in the markdown — and a photo without
// alt text never ships: the send refuses naming the illustration
// before anything touches the wire.
// The mentor never assesses images (G12) — the flow consults no
// engine anywhere.
//
// Wire facts (microblog.dev/api/posting, book.micro.blog/micropub):
// `q=config` names the media endpoint; `POST /micropub/media`
// multipart → 202 + Location = the upload URL. No photo property:
// it renders wherever the THEME decides, not where placed
// (live-verified 2026-11-01 — bottom of the post, position lost).
//
import Foundation
@testable import Museion
import Testing
// MARK: Shared helpers (shared-helper convention)
/// A tiny deterministic PNG payload — the client never inspects the
/// bytes (the server does); tests only need recognizable ones.
nonisolated func micropubPNG() -> Data {
Data([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x01, 0x02, 0x03])
}
/// A transport that routes the #34 three-step flow by target:
/// q=config → media upload → create. Records every request it served.
nonisolated func micropubMediaScripted(log: MicropubRequestLog) -> Micropub.Transport {
{ request in
log.append(request)
let target = request.url?.absoluteString ?? ""
if target.contains("q=config") {
return (Data(#"{"media-endpoint":"https://micro.blog/micropub/media"}"#.utf8), micropubHTTP(200))
}
if target.contains("/micropub/media") {
return (Data("{}".utf8), micropubHTTP(202, headers: ["Location": "https://micro.blog/uploads/2026/ink.png"]))
}
return (Data("{}".utf8), micropubHTTP(201, headers: ["Location": "https://example.micro.blog/inked"]))
}
}
@Suite("MicropubMediaTests")
struct MicropubMediaTests {
// MARK: Parsing the body's illustration refs (G12: plain refs into assets/)
@Test func `illustrations finds asset refs and leaves foreign images alone`() {
let body = """
# Title
Prose with ![an inline ref](assets/inline.png) inside.
![A winding path.](assets/path.png "The agora at dusk")
![remote](https://example.com/x.png)
![not ours](images/other.png)
![](assets/blank.png)
"""
let found = Micropub.illustrations(in: body)
// Honest parse: every assets/ ref, alt captured verbatim (the
// floor judges trimmed emptiness — the parse never hides one).
#expect(found == [
.init(alt: "an inline ref", destination: "assets/inline.png"),
.init(alt: "A winding path.", destination: "assets/path.png"),
.init(alt: "", destination: "assets/blank.png"),
])
}
@Test func `rewriting swaps each ref for its uploaded url in place`() {
let body = """
# Title
Prose with ![an inline ref](assets/inline.png) inside.
![A winding path.](assets/path.png "The agora at dusk")
![remote](https://example.com/x.png)
![not ours](images/other.png)
![no upload yet](assets/pending.png)
"""
let wire = Micropub.rewritingIllustrations(body, uploaded: [
"assets/inline.png": "https://micro.blog/uploads/a.png",
"assets/path.png": "https://micro.blog/uploads/b.png",
])
// Position is the writer's: each ref rewrites exactly where it
// stands, alt + surrounding text verbatim; foreign images and
// refs without an upload stay put; a quoted title drops.
#expect(wire.contains("Prose with ![an inline ref](https://micro.blog/uploads/a.png) inside."))
#expect(wire.contains("![A winding path.](https://micro.blog/uploads/b.png)"))
#expect(wire.contains("![remote](https://example.com/x.png)"))
#expect(wire.contains("![not ours](images/other.png)"))
#expect(wire.contains("![no upload yet](assets/pending.png)"))
#expect(wire.hasPrefix("# Title"))
// Only the uploaded refs' assets/ destinations leave.
#expect(!wire.contains("assets/inline.png"))
#expect(!wire.contains("assets/path.png"))
}
@Test func `mime types cover the media endpoint's formats and refuse the rest`() {
#expect(Micropub.mimeType(forDestination: "assets/ink.png") == "image/png")
#expect(Micropub.mimeType(forDestination: "assets/ink.PNG") == "image/png")
#expect(Micropub.mimeType(forDestination: "assets/photo.jpeg") == "image/jpeg")
#expect(Micropub.mimeType(forDestination: "assets/anim.gif") == "image/gif")
#expect(Micropub.mimeType(forDestination: "assets/modern.webp") == "image/webp")
#expect(Micropub.mimeType(forDestination: "assets/vector.svg") == "image/svg+xml")
#expect(Micropub.mimeType(forDestination: "assets/note.md") == nil)
}
@Test func `a url carrying markdown-active characters rides the angle form`() {
// The uploaded URL is server-controlled data landing in the
// wire body as markdown — a `)` in a plain-paren destination
// would close the image early and smuggle a live attacker
// link into the post (the trustworthyURL gate was built for
// frontmatter, not this sink). Angle form caps the worst
// case at broken rendering.
let wire = Micropub.rewritingIllustrations(
"![alt](assets/a.png)",
uploaded: ["assets/a.png": "https://x.example/x)[evil](https://evil.example"],
)
#expect(wire == "![alt](<https://x.example/x)[evil](https://evil.example>)")
// A clean URL keeps the plain form (pinned by the rewrite test).
}
@Test func `rewriting passes through untouched bodies and handles boundary refs`() {
// Empty map (and all-matches-skipped — same guard) returns the
// body verbatim; adjacent refs at string start/end rewrite
// with clean cursor math.
let adjacent = "![a](assets/a.png)![b](assets/b.png)"
#expect(Micropub.rewritingIllustrations(adjacent, uploaded: [:]) == adjacent)
let one = Micropub.rewritingIllustrations(adjacent, uploaded: ["assets/a.png": "https://micro.blog/uploads/a.png"])
#expect(one == "![a](https://micro.blog/uploads/a.png)![b](assets/b.png)")
}
@Test func `a multi-line alt never parses so both passes agree`() {
// A ref whose alt spans lines must NOT parse — if it parsed but
// didn't rewrite, the local assets/ ref would ride the wire as
// a broken relative link. It rides as prose, never uploaded.
let body = "# Title\n\n![two\nlines](assets/path.png)\n\n![fine](assets/ok.png)"
#expect(Micropub.illustrations(in: body) == [.init(alt: "fine", destination: "assets/ok.png")])
let wire = Micropub.rewritingIllustrations(body, uploaded: [
"assets/path.png": "https://micro.blog/uploads/a.png",
"assets/ok.png": "https://micro.blog/uploads/b.png",
])
#expect(wire.contains("![two\nlines](assets/path.png)")) // untouched
#expect(wire.contains("![fine](https://micro.blog/uploads/b.png)")) // the well-formed ref still rewrites
}
// MARK: q=config (hop 1)
@Test func `config request asks the endpoint for its media endpoint`() {
let request = Micropub.makeConfigRequest(token: "tok")
let components = URLComponents(url: request.url ?? Micropub.endpoint, resolvingAgainstBaseURL: false)
#expect(components?.queryItems?.contains(URLQueryItem(name: "q", value: "config")) == true)
#expect(request.httpMethod == nil || request.httpMethod == "GET") // GET is the default
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok")
}
@Test func `mediaEndpoint decodes the discovered endpoint and refuses honestly`() async {
let log = MicropubRequestLog()
// The named endpoint, trust-gated.
let named = await Micropub.mediaEndpoint(
token: "tok",
transport: micropubCanned(200, body: #"{"media-endpoint":"https://micro.blog/micropub/media"}"#, log: log),
)
#expect(named == .url("https://micro.blog/micropub/media"))
// A config that names nothing usable is a failed request, never
// a silent default.
let bare = await Micropub.mediaEndpoint(token: "tok", transport: micropubCanned(200, body: "{}", log: log))
guard case .failed(.requestFailed) = bare else {
Issue.record("expected requestFailed, got \(bare)")
return
}
// An injection-carrying endpoint is refused (the writer's PNG
// and token would POST to it) — the trustworthyURL gate.
let hostile = await Micropub.mediaEndpoint(
token: "tok",
transport: micropubCanned(200, body: "{\"media-endpoint\":\"https://x.example/a\\n---\\ninjected\"}", log: log),
)
guard case .failed(.requestFailed) = hostile else {
Issue.record("expected requestFailed for the injected endpoint, got \(hostile)")
return
}
let denied = await Micropub.mediaEndpoint(
token: "tok",
transport: micropubCanned(401, body: #"{"error_description":"bad token"}"#, log: log),
)
guard case .failed(.authFailed) = denied else {
Issue.record("expected authFailed, got \(denied)")
return
}
}
// MARK: The multipart upload (hop 2)
@Test func `media upload request is a multipart file post to the discovered endpoint`() {
let request = Micropub.makeMediaUploadRequest(
mediaEndpoint: "https://micro.blog/micropub/media",
filename: "ink.png",
mimeType: "image/png",
data: micropubPNG(),
token: "tok",
)
#expect(request.url?.absoluteString == "https://micro.blog/micropub/media")
#expect(request.httpMethod == "POST")
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok")
let contentType = request.value(forHTTPHeaderField: "Content-Type") ?? ""
#expect(contentType.hasPrefix("multipart/form-data; boundary="))
let boundary = contentType.components(separatedBy: "boundary=").last ?? ""
// The multipart shape, asserted over bytes: part head, payload,
// closing delimiter.
let body = request.httpBody ?? Data()
let head = Data((
"--\(boundary)\r\n"
+ "Content-Disposition: form-data; name=\"file\"; filename=\"ink.png\"\r\n"
+ "Content-Type: image/png\r\n\r\n"
).utf8)
#expect(body.firstRange(of: head) != nil)
#expect(body.firstRange(of: micropubPNG()) != nil) // the bytes ride intact
#expect(body.suffix(Data("--\(boundary)--\r\n".utf8).count) == Data("--\(boundary)--\r\n".utf8))
}
@Test func `uploadMedia reads Location then body url and gates the url`() async {
let log = MicropubRequestLog()
// Location wins; body url is the fallback.
let located = await Micropub.uploadMedia(
mediaEndpoint: "https://micro.blog/micropub/media",
filename: "ink.png", mimeType: "image/png", data: micropubPNG(), token: "tok",
transport: micropubCanned(
202, body: #"{"url":"https://ignored.example/should-not-win"}"#,
headers: ["Location": "https://micro.blog/uploads/ink.png"], log: log,
),
)
#expect(located == .url("https://micro.blog/uploads/ink.png"))
let fallback = await Micropub.uploadMedia(
mediaEndpoint: "https://micro.blog/micropub/media",
filename: "ink.png", mimeType: "image/png", data: micropubPNG(), token: "tok",
transport: micropubCanned(202, body: #"{"url":"https://micro.blog/uploads/from-body"}"#, log: log),
)
#expect(fallback == .url("https://micro.blog/uploads/from-body"))
// No URL anywhere → request failure, never a silent success.
let bare = await Micropub.uploadMedia(
mediaEndpoint: "https://micro.blog/micropub/media",
filename: "ink.png", mimeType: "image/png", data: micropubPNG(), token: "tok",
transport: micropubCanned(202, body: "{}", log: log),
)
guard case .failed(.requestFailed) = bare else {
Issue.record("expected requestFailed, got \(bare)")
return
}
let denied = await Micropub.uploadMedia(
mediaEndpoint: "https://micro.blog/micropub/media",
filename: "ink.png", mimeType: "image/png", data: micropubPNG(), token: "tok",
transport: micropubCanned(403, body: "{}", log: log),
)
guard case .failed(.authFailed) = denied else {
Issue.record("expected authFailed, got \(denied)")
return
}
}
// MARK: The create (hop 3)
@Test func `draft request carries no photo keys ever`() {
// #34 amendment (2026-11-01): images travel INLINE — the rail
// rewrites each asset ref to its uploaded URL inside content.
// A photo property would render wherever the theme decides.
let request = Micropub.makeDraftRequest(title: "T", body: "![alt](https://micro.blog/uploads/a.png)", token: "tok")
let props = micropubJSON(request)["properties"] as? [String: Any]
#expect(props?["photo"] == nil)
#expect(props?["mp-photo-alt"] == nil)
#expect(props?["content"] as? [String] == ["![alt](https://micro.blog/uploads/a.png)"])
}
}
+146
View File
@@ -141,4 +141,150 @@ struct MicropubModelTests {
#expect(Post.scan(home: home).first?.micropubURL == "https://example.micro.blog/second")
}
// MARK: #34 (S6.2) — illustrations travel with it
/// Plants a PNG beside the piece; returns the piece's post.md URL.
@MainActor private func plantIllustratedPiece(_ model: PostsModel, _ home: URL, body: String) throws -> URL {
let post = try PostStore.writeNew(body: body, home: home)
model.select(post.id, home: home)
let dir = try #require(PostStore.folder(of: post.id, home: home))
try FileManager.default.createDirectory(at: dir.appendingPathComponent("assets", isDirectory: true), withIntermediateDirectories: true)
try micropubPNG().write(to: dir.appendingPathComponent("assets/path.png"))
return dir.appendingPathComponent("post.md")
}
@Test @MainActor func `illustrations upload once and travel inline where placed`() async throws {
let (model, home) = try makeModelHome()
let fileURL = try plantIllustratedPiece(
model, home,
body: "# Inked\n\nProse before.\n\n![A winding path.](assets/path.png)\n\nProse after.",
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
// The three hops, in order: q=config → upload → create.
#expect(log.requests.count == 3)
let config = URLComponents(url: log.requests[0].url ?? Micropub.endpoint, resolvingAgainstBaseURL: false)
#expect(config?.queryItems?.contains(URLQueryItem(name: "q", value: "config")) == true)
#expect(log.requests[1].url?.absoluteString == "https://micro.blog/micropub/media")
#expect(log.requests[1].httpBody?.firstRange(of: micropubPNG()) != nil) // the PNG rode the multipart
// The create: the ref REWRITTEN in place with its uploaded URL
// — exactly where the writer placed it (2026-11-01: the photo
// PROPERTY rendered at the bottom, position lost), alt in the
// markdown, NO photo property keys.
let props = try #require(micropubJSON(log.requests[2])["properties"] as? [String: Any])
let expected = "# Inked\n\nProse before.\n\n![A winding path.](https://micro.blog/uploads/2026/ink.png)\n\nProse after."
#expect(props["content"] as? [String] == [expected])
#expect(props["photo"] == nil)
#expect(props["mp-photo-alt"] == nil)
// The piece on disk is untouched — only the wire rewrote the ref.
let disk = try String(contentsOf: fileURL, encoding: .utf8)
#expect(disk.contains("![A winding path.](assets/path.png)"))
#expect(Post.scan(home: home).first?.micropubURL == "https://example.micro.blog/inked")
}
@Test @MainActor func `a photo without alt text never ships`() async throws {
let (model, home) = try makeModelHome()
// Whitespace-only alt, not just empty — the floor mirrors the
// TRIMMED emptiness (#6: an isEmpty guard would pass this).
let fileURL = try plantIllustratedPiece(
model, home,
body: "# Inked\n\n![ ](assets/path.png)\n\nProse.",
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(reason.contains("assets/path.png")) // names the illustration
#expect(log.requests.isEmpty) // the floor holds BEFORE anything touches the wire
#expect(Post.scan(home: home).first?.micropubURL == nil)
// The piece is untouched — the ref still rides it on disk.
let disk = try String(contentsOf: fileURL, encoding: .utf8)
#expect(disk.contains("![ ](assets/path.png)"))
}
@Test @MainActor func `a symlinked illustration refuses before anything goes out`() async throws {
let (model, home) = try makeModelHome()
let fileURL = try plantIllustratedPiece(
model, home,
body: "# Inked\n\n![Linked.](assets/link.png)\n\nProse.",
)
// link.png is a symlink OUT of the piece — containment must
// refuse it (the cards/learnings posture: never read through
// a planted link), never upload the target's bytes.
let outside = home.appendingPathComponent("secret.png")
try micropubPNG().write(to: outside)
try FileManager.default.createSymbolicLink(
at: fileURL.deletingLastPathComponent().appendingPathComponent("assets/link.png"),
withDestinationURL: outside,
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
guard case let .refused(reason) = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(reason.contains("assets/link.png"))
#expect(log.requests.isEmpty)
}
@Test @MainActor func `duplicate refs to one asset upload once and share the url`() async throws {
let (model, home) = try makeModelHome()
_ = try plantIllustratedPiece(
model, home,
body: "# Inked\n\n![A path.](assets/path.png)\n\nTail.\n\n![A path again.](assets/path.png)",
)
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
// config + ONE upload + create — the FILE uploads once, not once per ref.
#expect(log.requests.count == 3)
#expect(log.requests.filter { $0.url?.absoluteString.contains("/micropub/media") == true }.count == 1)
let props = try #require(micropubJSON(log.requests[2])["properties"] as? [String: Any])
let content = try #require((props["content"] as? [String])?.first)
// Both refs share the one uploaded URL.
#expect(content.components(separatedBy: "https://micro.blog/uploads/2026/ink.png").count == 3)
}
@Test @MainActor func `a missing illustration refuses before anything goes out`() async throws {
let (model, home) = try makeModelHome()
_ = try plantIllustratedPiece(
model, home,
body: "# Inked\n\n![A ghost.](assets/ghost.png)\n\nProse.",
) // path.png planted, ghost.png never
let log = MicropubRequestLog()
let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
guard case .refused = outcome else {
Issue.record("expected refused, got \(outcome)")
return
}
#expect(log.requests.isEmpty)
}
@Test @MainActor func `a piece without illustrations sends exactly one request`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Plain\n\nBody.", home: home)
model.select(post.id, home: home)
let log = MicropubRequestLog()
_ = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log))
// The #33 path unchanged: no config round-trip, straight to the create.
#expect(log.requests.count == 1)
#expect(log.requests[0].url == Micropub.endpoint)
}
}