Files
museion/Museion/MicropubPublishSheet.swift
T
AlexKucera eca90a981c fix(microblog): publish sheet opens unfocused
Since the categories field landed, the Micro.blog publish sheet
opened with that field focused and its completion menu popping. A
sheet window takes its initial first responder like any window — its
first text input — and textInputSuggestions shows its list when the
editing interface is activated, so the menu popped the moment the
sheet opened.

The sheet now rides the launch-focus-reset rider from r8, once per
window: it resigns the auto-focus at the sheet's first become-key,
and a later re-key keeps whatever the writer focused. The rider is
InitialFocusReset(scope:) in the shared chrome; the library column
mounts the once-per-process scope exactly as before. The SwiftUI door
is closed: defaultFocus with false or nil changes nothing for this
assignment on macOS 27.2.1.

Verified with a bundle-launched OS-behaviour probe kept under
prototypes/ (re-run it after every macOS point release): the three
non-fix variants reproduce the auto-focus and the suggestions
window, the rider variant never shows either, and a run whose sheet
never became key exits 2 instead of printing the green verdict.
Owner live check passed.

Reviewed (three-reviewer finish-audit): the probe's false-green
verdict, a snippet missing its scope label, and duplicated mechanism
comments were found and fixed before this commit. Rail 814/814;
SwiftFormat and SwiftLint clean.

Docs: Museion/AGENTS.md bullets, an AGENTS.md learning, CHANGELOG
[Unreleased], the devlog, and the swift wiki (a sheet hands its
initial focus to its first text input).

Unticketed follow-up to the Micro.blog categories work; owner
report 2026-12-05.
2026-12-05 14:59:16 +01:00

630 lines
23 KiB
Swift

//
// MicropubPublishSheet.swift
// Museion
//
// #33 (S6.1): the publish ask — draft first, then publish (G9:
// publish is ask-before; each step is its own explicit click). The
// sheet owns the whole two-step flow over the OPEN piece: Send as
// Draft (h=entry, name, markdown content) → review on Micro.blog →
// Publish (the post-status update against the piece's remembered
// draft URL). The app token is entered here when none is saved and
// lives in the Keychain (G11; re-offered only on an auth failure —
// Settings → Micro.blog is the standing manager). Refusals show
// inline with the buttons kept (ApplyAskSheet posture).
// #206: the sheet opens on the piece's publish record. A published
// piece says so (and links its live post) and offers Update Live
// Post; a draft offers Publish / Update Draft. Both re-sends update
// the remembered post IN PLACE — never a second post.
// #207: a Categories field — the piece's `category:` line as a
// comma list, edited with the system completion menu over the
// blog's own categories (`Micropub.blogCategories`, fetched on
// open; a failed fetch is silent). The system REPLACES the whole
// field text with a completion, so `MicropubCategoryField` (the
// enum above the view) carries the merge: a pick ADDS, a
// half-typed last word is replaced. The edit lands on disk AT THE
// SEND (the model's `categories:`), never before — Cancel/Done
// discard it and a refused send puts nothing on the wire; the field
// syncs from disk on open and after a forget, settles to the
// canonical text after a successful send, and after a failed step
// only its baseline re-syncs (the send writes the line before the
// wire — a later clear must still count as an edit).
// #208: a Summary field — the piece's `summary:` scalar, typed or
// drafted by the `AI summary` button (a one-shot chat-profile
// engine; the reply fills the field, the writer edits). Same
// discipline as Categories: the edit lands AT THE SEND, the field
// syncs on open/forget and settles from disk after a send. While the
// turn runs the button is the sheet's own Stop (the sheet is modal).
// #207 follow-up: the sheet opens with NOTHING focused — a sheet window
// takes its initial first responder like any window (the Categories field,
// so the completion menu popped on open). `InitialFocusReset`
// (WorkspaceChrome) resigns it at the sheet's first become-key; the
// mechanism and its probe are documented there.
//
import SwiftUI
/// #207: the publish sheet's Categories field — its pure rules over
/// the one-line category codec (`PostFrontmatter.categoryList` /
/// `categoryListValue`: the ONE quote-aware comma-list parser — the
/// field holds exactly the bracket-inner text). The system completion
/// menu REPLACES the whole field text with a completion, so a
/// completion IS the merge: a pick ADDS, a half-typed last word is
/// replaced, a present name is never offered.
nonisolated enum MicropubCategoryField {
/// The word being typed — the LAST comma segment (a comma inside
/// double quotes never splits), trimmed, one pair of quotes off
/// (the codec's own step: the field reads `Tech, "Tech, general"`
/// after that pick, and the word is the name). SwiftUI exposes no
/// caret, so the end of the text is the only place a writer can be
/// typing. "" when the text is empty or ends with a comma.
static func partial(_ text: String) -> String {
// The codec's own segment scanner splits (ONE quote-aware walk);
// its `categoryList` trims, unquotes and unescapes the segment.
PostFrontmatter.categoryList(PostFrontmatter.categorySegments(text).last ?? "").first ?? ""
}
/// The last thing typed is itself a known category — nothing is
/// half-typed.
static func finished(_ text: String, blog: [String]) -> Bool {
let word = partial(text)
return !word.isEmpty && blog.contains { same($0, word) }
}
/// The menu over the blog's categories, blog order kept: ALL of
/// them when nothing or a finished name is typed, else the names
/// starting with the half-typed word (case-insensitive); a name
/// already in the field is never offered.
static func suggestions(text: String, blog: [String]) -> [String] {
let word = partial(text)
let present = Set(PostFrontmatter.categoryList(text).map { $0.lowercased() })
let all = word.isEmpty || finished(text, blog: blog)
return blog.filter { name in
!present.contains(name.lowercased()) && (all || name.lowercased().hasPrefix(word.lowercased()))
}
}
/// What the WHOLE field becomes when `name` is picked: a
/// half-typed last word makes room (the pick extends it, and the
/// word is not itself a category), then `name` is appended unless
/// present — never a duplicate.
static func completion(text: String, picking name: String, blog: [String]) -> String {
var names = PostFrontmatter.categoryList(text)
let word = partial(text)
let halfTyped = !word.isEmpty && !finished(text, blog: blog) && same(names.last ?? "", word)
if halfTyped, !same(word, name), name.lowercased().hasPrefix(word.lowercased()) {
names.removeLast()
}
if !names.contains(where: { same($0, name) }) {
names.append(name)
}
return PostFrontmatter.categoryListValue(names)
}
/// The sheet's edit for the model: nil when the field's list IS the
/// settled one — LISTS, so a trailing comma is not an edit, and
/// equal empties stay nil (a piece without a line never gains an
/// empty key); else the field's list (`[]` = cleared — the model
/// writes `category: []`).
static func pendingCategories(field: String, settled: String) -> [String]? {
let list = PostFrontmatter.categoryList(field)
return list == PostFrontmatter.categoryList(settled) ? nil : list
}
/// ponytail: case-insensitive on purpose — the writer's spelling stays
/// in the field, the menu just never re-offers a name that's there in
/// any case; the codec's own dedup stays exact (it records what was
/// written, it never rewrites a spelling).
private static func same(_ a: String, _ b: String) -> Bool {
a.caseInsensitiveCompare(b) == .orderedSame
}
}
/// #208: the publish sheet's Summary field — its pure rules. The
/// edit-for-send test is a STRING compare (not a list), so a
/// trailing-space difference is not an edit and equal empties stay
/// nil (a piece without a line never gains an empty key).
nonisolated enum MicropubSummaryField {
/// The sheet's edit for the model: nil when the field IS the
/// settled one (both trimmed — whitespace alone is not an edit);
/// else the field's text ("" = cleared — the model writes
/// `summary:` empty and the re-send clears the post's).
static func pendingSummary(field: String, settled: String) -> String? {
let f = field.trimmingCharacters(in: .whitespacesAndNewlines)
return f == settled.trimmingCharacters(in: .whitespacesAndNewlines) ? nil : f
}
}
/// #33 (S6.1): the two-step Micro.blog ask over the open piece.
struct MicropubPublishSheet: View {
let posts: PostsModel
let mentor: MentorSessionModel
@Environment(\.dismiss) private var dismiss
private enum Phase: Equatable {
/// Never sent — nothing on Micro.blog yet.
case idle
case drafting
/// A draft is on Micro.blog, not published (fresh or remembered).
case drafted
case updating
case updated
case publishing
/// The publish record — this session's Publish, or the piece's stamp.
case published
}
@State private var phase: Phase = .idle
/// The post URL this sheet knows: fresh from a send, or the piece's
/// remembered `micropub_url` (sent in an earlier session) — a draft's
/// until it is published, the live post's after.
@State private var postURL: String?
/// #206: when the piece was published — its stamp, or this session's
/// Publish. Nil while it is a draft.
@State private var publishedAt: Date?
@State private var previewURL: String?
@State private var refusal: String?
@State private var tokenField = ""
@State private var reentry = false
/// #207: the Categories field as typed, the text it rests on (the
/// disk read on open, or a successful send's canonical form — the
/// pending-edit baseline), and the blog's categories the menu offers.
@State private var categoryField = ""
@State private var settledCategoryField = ""
@State private var blogCategories: [String] = []
/// Whether the blog's categories were ever fetched in this sheet
/// (a blog with none is not re-asked after every send).
@State private var suggestionsLoaded = false
/// #208: the Summary field as typed, and the text it rests on (the
/// disk read on open, or a successful send's canonical form — the
/// pending-edit baseline).
@State private var summaryField = ""
@State private var settledSummaryField = ""
/// Token entry shows when none is saved — or again after an auth
/// failure (the entered-once token can be replaced, never a dead end).
private var showsTokenField: Bool {
reentry || MicropubTokenStore.read() == nil
}
private var busy: Bool {
phase == .drafting || phase == .updating || phase == .publishing
}
/// #207: the field's edit for the send — nil when nothing changed.
private var pendingCategories: [String]? {
MicropubCategoryField.pendingCategories(field: categoryField, settled: settledCategoryField)
}
/// #208: the Summary field's edit for the send — nil when nothing changed.
private var pendingSummary: String? {
MicropubSummaryField.pendingSummary(field: summaryField, settled: settledSummaryField)
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text(publishedAt == nil ? "Publish to Micro.blog?" : "On Micro.blog")
.font(.headline)
Text(pieceTitle)
.font(.callout.weight(.semibold))
.lineLimit(2)
if phase == .idle {
Text("Museion sends it as a draft first — nothing goes out until you publish.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
}
// #207: the Categories field, in every phase — a send is possible in all of them.
VStack(alignment: .leading, spacing: 4) {
Text("Categories")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
TextField("Tech, Notes", text: $categoryField)
.textFieldStyle(.roundedBorder)
.font(.system(size: 12, design: DesignTokens.mono))
.disabled(busy)
.accessibilityLabel("Categories")
.textInputSuggestions {
ForEach(MicropubCategoryField.suggestions(text: categoryField, blog: blogCategories), id: \.self) { name in
Text(name).textInputCompletion(MicropubCategoryField.completion(text: categoryField, picking: name, blog: blogCategories))
}
}
Text("Comma-separated. A name Micro.blog doesn't know is created when the post is sent.")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
// #208: the Summary field, in every phase — a send is possible in all of them.
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 6) {
Text("Summary")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
Spacer()
Button {
draftSummary()
} label: {
if summarizing {
ProgressView().controlSize(.small)
} else {
Text("AI summary")
}
}
.buttonStyle(.bordered)
.controlSize(.small)
// Disabled-with-reason (the pass bar's idiom) while ANOTHER
// rider owns the rail or a send runs — but never while this
// sheet's own summary turn runs: the spinner is the Stop.
.disabled(busy || (!summarizing && posts.oneShotRailBusy))
.help(summarizing ? "Stop the summary turn." : summaryButtonHelp)
.accessibilityLabel(summarizing ? "Stop summary" : "AI summary")
}
TextEditor(text: $summaryField)
.font(.system(size: 11, design: DesignTokens.mono))
.frame(height: 72)
.scrollContentBackground(.hidden)
.background(RoundedRectangle(cornerRadius: 6).stroke(DesignTokens.muted.opacity(0.35)))
.disabled(busy || posts.summarizing)
.accessibilityLabel("Summary")
Text("Shown by Micro.blog in feeds and cross-posts. One or two sentences, first person — line breaks become spaces.")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
if showsTokenField {
SecureField("App token", text: $tokenField)
.textFieldStyle(.roundedBorder)
.font(.system(size: 12, design: DesignTokens.mono))
Text("From micro.blog → Account → App Tokens. Stored in your Keychain.")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
} else {
// A stored token is in use — the field's absence alone
// never said which token a send carries.
Text("Sends with the app token in your Keychain — Settings → Micro.blog manages it.")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
if busy {
ProgressView()
}
if let label = statusLabel {
// A published piece's link is the post itself; a draft's
// is its review page.
VStack(alignment: .leading, spacing: 4) {
Text(label)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
if let link = statusLink {
Link(destination: link) {
Text(link.absoluteString)
.font(.system(size: 11, design: DesignTokens.mono))
.lineLimit(1)
.truncationMode(.middle)
}
}
}
}
if let refusal {
Text(refusal)
.font(.callout)
.foregroundStyle(.orange)
}
HStack(spacing: 8) {
if publishedAt != nil {
// The piece is out: the only send left edits the live
// post, immediately — the label says so. A stamp with no
// remembered link (a hand-added key) has no post to
// update: that send is a fresh draft, and says so.
Button(postURL == nil ? "Send as Draft" : "Update Live Post") { send() }
.buttonStyle(.bordered)
.disabled(busy)
Button("Done") { dismiss() }
.buttonStyle(.borderedProminent)
} else {
Button("Publish") { publish() }
.buttonStyle(.borderedProminent)
.disabled(postURL == nil || busy)
// The piece changed since the draft — a re-send
// updates that same draft (never a second post).
Button(postURL == nil ? "Send as Draft" : "Update Draft") { send() }
.buttonStyle(.bordered)
.disabled(busy)
Button("Cancel") { dismiss() }
.buttonStyle(.bordered)
}
}
.frame(maxWidth: .infinity, alignment: .trailing)
}
.padding(16)
.frame(width: 420, alignment: .leading)
// Opens unfocused — InitialFocusReset's doc has the mechanism.
.background(InitialFocusReset(scope: .oncePerWindow))
.onAppear {
// A piece sent in an earlier session still has its record:
// the remembered URL, and (#206) its publish stamp.
guard postURL == nil, let id = posts.session?.postID,
let post = posts.posts.first(where: { $0.id == id })
else { return }
postURL = post.micropubURL
publishedAt = post.micropubPublished
phase = settledPhase
syncFieldFromDisk()
syncSummaryFromDisk()
loadSuggestions()
}
}
// MARK: Status
/// The open piece's Title (the sheet is only reachable with a piece
/// open; the id is the honest fallback).
private var pieceTitle: String {
posts.session?.postID.map { posts.title(of: $0) } ?? "This piece"
}
private var statusLabel: String? {
switch phase {
case .idle:
nil
case .drafting:
"Sending draft…"
case .drafted:
"Draft on Micro.blog — not published yet"
case .updating:
publishedAt == nil ? "Updating draft…" : "Updating live post…"
case .updated:
publishedAt.map { "Updated live — published \(Micropub.shortDate($0))" } ?? "Draft updated — not published yet"
case .publishing:
"Publishing…"
case .published:
publishedAt.map { "Published \(Micropub.shortDate($0))" }
}
}
/// A published piece links its live post; a draft links the review
/// page — only the send that created it carries one, so a draft
/// remembered from an earlier session shows no (dead) link.
private var statusLink: URL? {
if publishedAt != nil {
return postURL.flatMap { URL(string: $0) }
}
return previewURL.flatMap { URL(string: $0) }
}
/// Where the sheet rests on the piece's record: published, draft,
/// or never sent.
private var settledPhase: Phase {
if publishedAt != nil {
return .published
}
if postURL != nil {
return .drafted
}
return .idle
}
// MARK: Steps
/// Resolve the token: a freshly entered one is saved ONCE (rotation
/// replaces); otherwise the Keychain's. Nil → the inline ask, never
/// a silent send.
private func resolveToken() -> String? {
if !tokenField.trimmingCharacters(in: .whitespaces).isEmpty {
let token = tokenField.trimmingCharacters(in: .whitespaces)
MicropubTokenStore.save(token)
reentry = false
return token
}
guard let saved = MicropubTokenStore.read() else { return nil }
return saved
}
/// A failed step: the message shows inline with the buttons kept, and
/// the sheet rests on the piece's record (a rejected token re-opens
/// entry — the entered-once token may be wrong). #207: the category
/// baseline follows the disk (the field keeps the text as typed).
private func fail(_ message: String, tokenRejected: Bool = false) {
if tokenRejected {
reentry = true
}
refusal = message
phase = settledPhase
syncSettledFromDisk()
syncSettledSummaryFromDisk()
}
/// Step 1 — the model decides create-vs-update by the piece's
/// remembered URL: a first send creates the draft, every later one
/// updates that post in place.
private func send() {
guard let token = resolveToken() else {
refusal = "Paste your Micro.blog app token first."
return
}
refusal = nil
phase = postURL == nil ? .drafting : .updating
Task {
switch await posts.micropubSend(token: token, categories: pendingCategories, summary: pendingSummary) {
case let .drafted(url, preview):
postURL = url
previewURL = preview
phase = .drafted
sendLanded()
case let .updated(url):
postURL = url
phase = .updated
sendLanded()
case let .authFailed(detail):
fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
case let .refused(reason), let .unreachable(reason):
fail(reason)
case let .requestFailed(status, detail):
fail("Micro.blog said \(status): \(detail)")
case let .forgotten(reason):
forgot(reason)
case .published:
break
}
}
}
private func publish() {
guard let url = postURL, let token = resolveToken() else {
refusal = "Paste your Micro.blog app token first."
return
}
refusal = nil
phase = .publishing
Task {
switch await posts.micropubPublish(url: url, token: token, categories: pendingCategories, summary: pendingSummary) {
case .published:
publishedAt = Date()
phase = .published
settle()
syncSummaryFromDisk()
case let .authFailed(detail):
fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
case let .refused(reason), let .unreachable(reason):
fail(reason)
case let .requestFailed(status, detail):
fail("Micro.blog said \(status): \(detail)")
case let .forgotten(reason):
forgot(reason)
case .drafted, .updated:
break
}
}
}
/// #206: Micro.blog lost the post and the piece forgot it — the
/// sheet is back on a never-sent piece (a fresh draft is one click
/// away).
private func forgot(_ reason: String) {
refusal = reason
postURL = nil
publishedAt = nil
previewURL = nil
phase = .idle
// #207: the forget clears only the micropub keys — a category
// line the failed send already wrote stays on the piece, so the
// field re-syncs to it (no false pending state).
syncFieldFromDisk()
syncSummaryFromDisk()
}
// MARK: Categories (#207)
/// The piece's `category:` line as it is on DISK (the model's read —
/// never the scan snapshot), in the codec's unbracketed form. No
/// open saved piece, or an unreadable file → "".
private var diskCategoryText: String {
PostFrontmatter.categoryListValue(posts.openPieceCategories())
}
/// The field AND its baseline take the disk's line (on open, after a
/// forget).
private func syncFieldFromDisk() {
categoryField = diskCategoryText
settledCategoryField = categoryField
}
/// Only the BASELINE follows the disk (a failed step). The send
/// writes the category line BEFORE the wire, so a refusal or a
/// failed publish may leave the edit on the piece; the pending test
/// must compare against what the piece really holds — a later clear
/// of the field has to count as an edit. The field keeps the text as
/// typed.
private func syncSettledFromDisk() {
settledCategoryField = diskCategoryText
}
/// The blog's categories for the menu, over the Keychain's token.
/// A failure is silent — no suggestions is a normal state (the
/// field still works: a typed new name creates the category).
private func loadSuggestions() {
guard let token = MicropubTokenStore.read() else { return }
Task {
blogCategories = await Micropub.blogCategories(token: token)
suggestionsLoaded = true
}
}
/// A send landed: the writer sees the canonical text, and the
/// edit is no longer pending. (A REFUSED send keeps the text as typed.)
private func settle() {
categoryField = PostFrontmatter.categoryListValue(PostFrontmatter.categoryList(categoryField))
settledCategoryField = categoryField
}
/// A successful send: the fields settle, and a token first entered
/// in this sheet gets its suggestions now — once. A blog WITH no
/// categories is not asked again after every send.
private func sendLanded() {
settle()
syncSummaryFromDisk()
if !suggestionsLoaded {
loadSuggestions()
}
}
// MARK: Summary (#208)
/// The piece's `summary:` line as it is on DISK (the model's read).
private var diskSummaryText: String {
posts.openPieceSummary()
}
/// The field AND its baseline take the disk's line (on open, after a forget).
private func syncSummaryFromDisk() {
summaryField = diskSummaryText
settledSummaryField = summaryField
}
/// Only the BASELINE follows the disk (a failed step — the send
/// writes the line before the wire; the Categories discipline).
private func syncSettledSummaryFromDisk() {
settledSummaryField = diskSummaryText
}
/// #208: the AI button's hover reason — the disabled state says why
/// (the pass bar's idiom).
private var summaryButtonHelp: String {
posts.oneShotRailBusy
? "A Pass, Blind Read, or summary is running — the engine is busy."
: "Drafts a first-person teaser from the piece — edit it before sending."
}
/// #208: the AI draft — a fresh one-shot chat-profile engine reads
/// the piece and the reply fills the field for the writer to edit.
/// A refusal shows inline (the field keeps its text). While the turn
/// runs the button is the sheet's OWN Stop (the sheet is modal — the
/// pass bar's Cancel sits behind it): `cancelPass` ends the turn on
/// the shared rail, and `summarizing` follows the model's flag so a
/// stop from anywhere clears the spinner.
private var summarizing: Bool {
posts.summarizing
}
private func draftSummary() {
guard !summarizing else {
// The spinner IS the stop: a hung engine must not hold the
// sheet.
posts.cancelPass(mentor: mentor)
return
}
refusal = nil
Task {
// The model owns the flag; the reply fills the field, a
// refusal lands inline.
if let text = await posts.summarize(mentor: mentor) {
summaryField = text
} else {
refusal = posts.lastError ?? "The engine didn't return a summary — try again."
}
}
}
}