feat(microblog): show Micro.blog publish status

The publish sheet flipped a draft live and remembered nothing, so
nothing on disk said a piece was out and the library could not show
it. A successful Publish now stamps `micropub_published` in the
piece's frontmatter; the row and the sheet read `published <date>`
or `draft on Micro.blog`, and a published piece's menu opens the
live post.

Sending a piece again no longer creates a second post: a piece that
remembers its post updates it in place (name and content only, so
categories set on Micro.blog survive). An image whose bytes are
unchanged rides its earlier upload through a per-piece memo. When
Micro.blog answers 404 the piece forgets both keys and the sheet
offers a fresh draft; a clear that cannot land says so instead of
claiming the link is gone.

Museion's micropub keys are dropped at the import boundary. An
imported `micropub_url` passes the format gate and would aim the
in-place update at one of the writer's own posts under their token,
so the keys are treated like `origin`: ours to set, never a foreign
file's to carry in. Publish is model-owned and trust-gates its URL
before anything is stamped.

Tests read recorded requests through an optional accessor: an
out-of-range subscript after a failed count expectation trapped the
hosted runner and reported every queued test as crashed.

+16 tests net (17 new pins in MicropubStatusTests, one retired whose
premise the in-place design voids); every new pin was watched fail
on its own guard. Rail 752/752; SwiftFormat and SwiftLint clean.
Reviews: standards + spec during the build, then a three-reviewer
finish audit. Docs: AGENTS.md bullets and learnings, GLOSSARY
terms, CHANGELOG [Unreleased], README, and the devlog.

Closes #206
This commit is contained in:
AlexKucera committed 2026-12-04 17:45:35 +01:00
1 parent 6938826101
commit 6aa31a419a
21 files changed
+1151 -225

No files matched your search

+242 -65
View File
@@ -11,7 +11,13 @@
// #34 (S6.2): uploaded illustrations rewrite their asset refs IN
// PLACE with the uploaded URLs (position is the writer's) — the
// media surface (parse/upload/config/rewrite) lives in
// MicropubMedia.swift, the orchestration in micropubSendDraft below.
// MicropubMedia.swift, the orchestration in micropubSend below.
// #206: a piece that remembers its post re-sends as an IN-PLACE
// update (action=update + replace name/content — never a second
// post), Publish is remembered on the piece (`micropub_published`),
// and a 404 forgets the link. Wire facts live-verified 2026-12-04
// (microblog.dev/api/posting): `replace` sets name and content;
// updates answer 200 with an empty body, 404 when the URL is gone.
//
// Wire facts live-verified 2026-10-31 (microblog.dev/api/posting,
// book.micro.blog/micropub): JSON create = type/properties; the
@@ -32,9 +38,17 @@ nonisolated enum Micropub {
/// header, body url as fallback) — what `publish` targets and
/// what the piece remembers.
case drafted(url: String, preview: String?)
/// #206: an in-place update landed — `url` is the post the piece
/// already remembered (a draft refreshed, a live post edited).
/// No second post, no new URL.
case updated(url: String)
case published
/// No open saved piece (model guard) — nothing went out.
case refused(String)
/// #206 (model-level): Micro.blog answered 404 — the post is gone
/// there. The piece has forgotten it (both stamps cleared); the
/// payload says so. The next send is a fresh draft.
case forgotten(String)
case authFailed(String)
case requestFailed(status: Int, detail: String)
case unreachable(String)
@@ -52,12 +66,19 @@ nonisolated enum Micropub {
// MARK: Requests (JSON Micropub — sorted keys keep the wire deterministic)
static func makeDraftRequest(title: String, body: String, token: String) -> URLRequest {
/// The one JSON POST shape every request rides: the fixed endpoint,
/// Bearer token, 30 s, sorted keys.
private static func jsonPost(_ object: [String: Any], token: String) -> URLRequest {
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.timeoutInterval = 30
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.httpBody = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])
return request
}
static func makeDraftRequest(title: String, body: String, token: String) -> URLRequest {
// h=entry with markdown content and name for the title; the
// Title publishes as the entry's name, the body ships verbatim
// (GLOSSARY: never stripped) — the one carve-out is #34's asset
@@ -66,32 +87,40 @@ nonisolated enum Micropub {
// disk never changes). No photo property: it would render
// wherever the theme decides, not where placed (2026-11-01).
// category: never sent in v1.
request.httpBody = try? JSONSerialization.data(withJSONObject: [
jsonPost([
"type": ["h-entry"],
"properties": [
"name": [title],
"content": [body],
"post-status": ["draft"],
] as [String: Any],
], options: [.sortedKeys])
return request
], token: token)
}
static func makePublishRequest(url: String, token: String) -> URLRequest {
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.timeoutInterval = 30
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.httpBody = try? JSONSerialization.data(withJSONObject: [
jsonPost([
"action": "update",
"url": url,
"replace": ["post-status": ["published"]],
], options: [.sortedKeys])
return request
], token: token)
}
// MARK: The two steps
/// #206: refresh the post the piece remembers — title and content
/// replaced IN PLACE over the remembered URL (wire-verified
/// 2026-12-04: `replace` sets name and content, JSON-only). Never
/// a status flip: a draft stays a draft, a published post stays live.
static func makeUpdateRequest(url: String, title: String, body: String, token: String) -> URLRequest {
jsonPost([
"action": "update",
"url": url,
"replace": [
"name": [title],
"content": [body],
],
], token: token)
}
// MARK: The steps
/// Step 1: send the piece as a draft. The piece's Title is the
/// entry's name; the markdown body is the content; #34's uploaded
@@ -116,6 +145,25 @@ nonisolated enum Micropub {
return await run(makePublishRequest(url: url, token: token), transport: transport, decodeDraftURL: false)
}
/// #206: step 1 again, in place — the piece's current title and
/// body replace the remembered post's (a draft refreshed for
/// review; a live post edited). Needs the remembered URL.
static func update(
url: String,
title: String,
body: String,
token: String,
transport: Transport = urlSessionTransport,
) async -> Outcome {
let outcome = await run(makeUpdateRequest(url: url, title: title, body: body, token: token), transport: transport, decodeDraftURL: false)
// `run` has one success word for the URL-less steps; the update's
// carries the URL it touched.
if outcome == .published {
return .updated(url: url)
}
return outcome
}
/// One POST + the honest decode: 2xx → drafted/published (drafts
/// need a URL — Location header first, body `url` second; the
/// preview link is display-only, never the publish target; a create
@@ -152,10 +200,12 @@ nonisolated enum Micropub {
/// the frontmatter block on the next parse and re-parse as BODY
/// (arbitrary markdown in the writer's piece, shipped under their
/// token by the next send). Applied at both ends: the decode above
/// and `Post.scan`'s read-back (imported frontmatter rides verbatim).
/// Format-only by design — ponytail: a well-formed foreign URL still
/// passes (the label shows its full text); host-allowlist when v2's
/// q=config surface names the blog's real domains.
/// and `Post.scan`'s read-back. Format-only by design — ownership is
/// settled upstream, not here: the import boundary drops the micropub
/// keys (`PostFrontmatter.micropubKeys`, #206 — since the in-place
/// update a well-formed foreign URL would aim a content replace), so
/// only Museion or the writer's own hand writes one. ponytail:
/// host-allowlist stays the upgrade if another way in ever appears.
static func trustworthyURL(_ string: String) -> Bool {
guard !string.isEmpty,
string.rangeOfCharacter(from: .newlines.union(.controlCharacters)) == nil,
@@ -166,6 +216,21 @@ nonisolated enum Micropub {
return true
}
/// The remembered post URL read from frontmatter — the ONE read the
/// scan and the send share, gated like the decode: a hand-written
/// broken value is no memory at all (an imported one never arrives —
/// the boundary drops the key).
static func rememberedURL(_ matter: [String: String]) -> String? {
guard let raw = matter["micropub_url"], trustworthyURL(raw) else { return nil }
return raw
}
/// #206: the short date the library row and the publish sheet both
/// show (`Dec 4, 2026`) — one format, so the two can't drift.
static func shortDate(_ date: Date) -> String {
FixCardStore.formatted(date, "MMM d, yyyy")
}
/// Internal for MicropubMedia's media steps (#34) — the one failure
/// decode this client speaks; extensions share it rather than fork it.
/// A 5xx is Micro.blog's side (their nginx front with the app not
@@ -240,29 +305,15 @@ nonisolated enum MicropubTokenStore {
}
}
// MARK: - #33 (S6.1) Micropub draft → publish
// MARK: - #33 (S6.1) / #206 Micropub draft → publish
extension PostsModel {
/// Step 1 of the two-step publish: send the OPEN piece to Micro.blog
/// as a draft (h=entry, name = Title, markdown content, post-status
/// draft — category frontmatter never travels). runPass's guard set
/// minus the engine gates (no engine involved); flush-first so the
/// wire carries the editor's latest. On success the piece remembers
/// the draft URL (`micropub_url` stamp) — a stamp failure never
/// un-sends the draft; it lands in lastError while the outcome stays
/// honest. Publishing (step 2) is stateless: the sheet calls
/// `Micropub.publish` against the remembered URL directly.
/// #179: outside the write rail by design — publish is not a library
/// verb, and a stamp failure must never un-send the draft.
func micropubSendDraft(
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
// brief-28: identity — the open session must target THIS library's
// selected piece (Home, ID); the wire below reads the session's OWN
// library, never the current Home's same-slug file. The completion
// stamp targets the same captured pair — the piece actually sent,
// wherever the writer has since pointed the app.
/// The OPEN saved library piece as the micropub pair (id, Home) —
/// the identity guard both publish steps share. brief-28: the open
/// session must target THIS library's selected piece; the wire and
/// every stamp below act on the piece actually sent (Home, ID),
/// never the current Home's same-slug file. Nil = nothing to send.
private var openMicropubPiece: (id: String, home: URL)? {
guard let session,
let id = session.postID,
let home = watchedHome,
@@ -271,18 +322,39 @@ extension PostsModel {
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
else { return nil }
return (id, home)
}
/// Step 1 of the two-step publish: send the OPEN piece to Micro.blog
/// (name = Title, markdown content — category frontmatter never
/// travels). runPass's guard set minus the engine gates (no engine
/// involved); flush-first so the wire carries the editor's latest.
/// #206: a piece that remembers no post is CREATED as a draft
/// (h=entry, post-status draft) and remembers its URL
/// (`micropub_url` stamp); a piece that remembers one UPDATES that
/// post in place — same URL, no second post — so a draft refreshes
/// for review and a published piece edits live. A stamp failure
/// never un-sends the draft.
/// #179: outside the write rail by design — publish is not a library
/// verb, and a stamp failure must never un-send the draft.
func micropubSend(
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let piece = openMicropubPiece else {
return .refused("Open a saved post to publish.")
}
guard flushOrAbort(id) else {
guard flushOrAbort(piece.id) else {
return .refused(lastError ?? "Couldn't save the piece before sending.")
}
// Disk is the truth post-flush — ONE read serves both wire fields:
// Disk is the truth post-flush — ONE read serves the wire fields:
// Title (heading markers stripped — it publishes as the entry's
// name) and the frontmatter-stripped body (the stamp is
// name), the frontmatter-stripped body (the stamp is
// bookkeeping, never prose; the body itself is never stripped,
// GLOSSARY). No scan dependency: the list can lag the open piece.
guard let dir = PostStore.folder(of: id, home: home),
// GLOSSARY), and the remembered URL. No scan dependency: the
// list can lag the open piece.
guard let dir = PostStore.folder(of: piece.id, home: piece.home),
let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else {
return .refused("Couldn't read the piece before sending.")
@@ -303,25 +375,91 @@ extension PostsModel {
return outcome
}
}
let title = Post.title(of: raw)
// #206: the piece remembers its post → update THAT post in
// place (the remembered URL never moves; nothing new to stamp).
// A 404 means the post is gone on Micro.blog — the piece forgets
// it rather than fail forever against a dead URL.
if let remembered = Micropub.rememberedURL(PostFrontmatter.parse(raw)) {
let outcome = await Micropub.update(url: remembered, title: title, body: wireBody, token: token, transport: transport)
if case .requestFailed(404, _) = outcome {
return micropubPostGone(id: piece.id, home: piece.home)
}
return outcome
}
let outcome = await Micropub.sendDraft(
title: Post.title(of: raw),
title: title,
body: wireBody,
token: token,
transport: transport,
)
if case let .drafted(url, _) = outcome {
// Remember the draft URL for the publish step. A stamp
// failure can't un-send the draft; the sheet still holds
// the URL for this session — the piece just loses the
// memory across a reopen (re-send the draft then). Kept
// quiet: lastError's setter stays PostsModel-file-private,
// and the same disk accepted the flush moments before.
try? PostStore.stampMicropubURL(id: id, url: url, home: home)
// Remember the draft's URL for the publish step and every
// later in-place update. A stamp failure can't un-send the
// draft; the sheet still holds the URL for this session —
// the piece just loses the memory across a reopen (it
// would create a second draft then). Kept quiet: the same
// disk accepted the flush moments before.
try? PostStore.stampMicropub(piece.id, home: piece.home, [("micropub_url", url)])
}
return outcome
}
/// #34 (S6.2): the illustration rail of `micropubSendDraft`. The
/// Step 2: flip the remembered draft to published. #206: the model
/// owns it — the sheet used to call the client directly, so nothing
/// remembered a publish. Success is the piece's publish record:
/// `micropub_published` stamped now (first publish wins — a later
/// in-place update of the live post never moves it) and
/// `micropub_url` healed in the same write should the send's stamp
/// have failed. A stamp failure never un-publishes. No flush: no
/// content travels, and the editor never writes frontmatter. The URL
/// is trust-gated HERE — it lands in frontmatter (the heal), and a
/// caller's value is external until proven.
func micropubPublish(
url: String,
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let piece = openMicropubPiece else {
return .refused("Open a saved post to publish.")
}
guard Micropub.trustworthyURL(url) else {
return .refused("That post address isn't a clean https URL — nothing was sent or remembered.")
}
let outcome = await Micropub.publish(url: url, token: token, transport: transport)
switch outcome {
case .published:
try? PostStore.stampMicropub(piece.id, home: piece.home, [
("micropub_url", url),
("micropub_published", FixCardStore.formatted(Date(), PostFrontmatter.stampFormat)),
])
case .requestFailed(404, _):
return micropubPostGone(id: piece.id, home: piece.home)
default:
break
}
return outcome
}
/// #206: Micro.blog answered 404 — the post is gone there, so the
/// piece is no longer on Micro.blog: it forgets both stamps and the
/// writer hears why (the next send is a fresh draft). A forget that
/// cannot land refuses instead — never a "cleared" the disk
/// contradicts: the link is still on the piece, so the sheet stays
/// on it and says what to do by hand.
private func micropubPostGone(id: String, home: URL) -> Micropub.Outcome {
do {
try PostStore.forgetMicropub(id: id, home: home)
} catch {
return .refused(
"Micro.blog no longer has this post — it was deleted there — but its link couldn't be cleared from this piece "
+ "(\(error.localizedDescription)). Delete the `micropub_url` line from its frontmatter, then send it as a draft.",
)
}
return .forgotten("Micro.blog no longer has this post — it was deleted there. Its link is cleared; send it as a draft again.")
}
/// #34 (S6.2): the illustration rail of `micropubSend`. The
/// FLOOR first (G12): a photo without alt text never ships, and
/// nothing touches the wire until every illustration clears it —
/// the ONLY gate (the only way an image ships is a parsed body ref,
@@ -350,11 +488,6 @@ extension PostsModel {
// `../` ref or a symlinked asset is out of shape) before the
// first upload. One payload per FILE: duplicate refs to one
// destination upload once and share the URL.
struct Payload {
let destination: String
let mimeType: String
let data: Data
}
let root = dir.resolvingSymlinksInPath().path + "/"
var payloads: [Payload] = []
for illustration in illustrations where !payloads.contains(where: { $0.destination == illustration.destination }) {
@@ -369,8 +502,36 @@ extension PostsModel {
}
payloads.append(Payload(destination: illustration.destination, mimeType: mimeType, data: data))
}
// ponytail: a re-send re-uploads (Micro.blog keeps both
// copies) — dedup via q=source listing is v2's call.
return await uploadRemembered(payloads, dir: dir, body: body, token: token, transport: transport)
}
/// One asset about to travel: its ref destination (the rewrite's
/// map key), its wire content type, its bytes.
private struct Payload {
let destination: String
let mimeType: String
let data: Data
}
/// #206: the piece's upload memo answers first — an image whose
/// bytes uploaded before rides that URL again (Micro.blog keeps
/// every copy, and their listing carries no hash to match against,
/// so the memory is local). Only what the memo lacks touches the
/// wire: q=config, then one upload per pending payload, each
/// remembered as it lands.
private func uploadRemembered(
_ payloads: [Payload],
dir: URL,
body: String,
token: String,
transport: Micropub.Transport,
) async -> IllustrationRail {
var memo = Micropub.readUploadMemo(in: dir)
let remembered = uploadedDestinations(payloads, memo: memo)
let pending = payloads.filter { remembered[$0.destination] == nil }
guard !pending.isEmpty else {
return .ready(Micropub.rewritingIllustrations(body, uploaded: remembered))
}
let mediaEndpoint: String
switch await Micropub.mediaEndpoint(token: token, transport: transport) {
case let .url(named):
@@ -378,8 +539,9 @@ extension PostsModel {
case let .failed(outcome):
return .blocked(outcome)
}
var uploaded: [String: String] = [:]
for payload in payloads {
// The `where` skips a later payload with the same bytes as one
// uploaded earlier in this batch.
for payload in pending where memo[Micropub.uploadKey(payload.data)] == nil {
let outcome = await Micropub.uploadMedia(
mediaEndpoint: mediaEndpoint,
filename: URL(fileURLWithPath: payload.destination).lastPathComponent,
@@ -390,11 +552,26 @@ extension PostsModel {
)
switch outcome {
case let .url(url):
uploaded[payload.destination] = url
// Remembered as it lands: a later failure in the batch
// keeps the earlier uploads (a retry never repeats them).
memo[Micropub.uploadKey(payload.data)] = url
Micropub.writeUploadMemo(memo, in: dir)
case let .failed(failure):
return .blocked(failure) // all-or-nothing: a failed upload never sends a half-illustrated piece
}
}
return .ready(Micropub.rewritingIllustrations(body, uploaded: uploaded))
// Every payload is memoized now — the earlier uploads and this batch's.
return .ready(Micropub.rewritingIllustrations(body, uploaded: uploadedDestinations(payloads, memo: memo)))
}
/// The rewrite's map: each payload's ref destination → its upload URL.
private func uploadedDestinations(_ payloads: [Payload], memo: [String: String]) -> [String: String] {
var uploaded: [String: String] = [:]
for payload in payloads {
if let url = memo[Micropub.uploadKey(payload.data)] {
uploaded[payload.destination] = url
}
}
return uploaded
}
}