From eca90a981cab16c6bd14400c20d889b59473ae1c Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sat, 5 Dec 2026 14:59:16 +0100 Subject: [PATCH] fix(microblog): publish sheet opens unfocused MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- AGENTS.md | 3 +- CHANGELOG.md | 2 + Museion/AGENTS.md | 6 +- Museion/MicropubPublishSheet.swift | 7 + Museion/PostsLibraryColumn.swift | 65 +---- Museion/WorkspaceChrome.swift | 72 ++++- ...61205-publish-sheet-opens-unfocused_log.md | 76 +++++ docs/devlog/INDEX.md | 1 + prototypes/MicropubSheetFocusProbe.swift | 270 ++++++++++++++++++ 9 files changed, 438 insertions(+), 64 deletions(-) create mode 100644 docs/devlog/20261205-publish-sheet-opens-unfocused_log.md create mode 100644 prototypes/MicropubSheetFocusProbe.swift diff --git a/AGENTS.md b/AGENTS.md index 7991909..75411e8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -171,6 +171,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d - `value of type 'X' has no member` while the emitted module DOES carry the symbol is a spelling drift between targets, not a stale build — grep the exact name across app AND tests before hunting binaries: a fresh test file's `microblogStatus` against the code's `micropubStatus` reads exactly like the stale-binary signature above and cost a DerivedData dive (#206) - A flip proves a guard only when it SOLELY causes a red pin — two flips on one pin mask each other (split-off hid dedupe; never-append hid `finished`); re-flip masked guards alone (#207) - A flip that reddens NOTHING means the pin observes a downstream state another guard also holds — assert the guard's own output (`lastError` text), then re-flip; `runningPass == nil` held through the host's one-shot lock while the refusal under test was disabled (#208) +- A SwiftUI sheet opens on its FIRST text input (`.defaultFocus` is a no-op, 27.2.1) — mount `InitialFocusReset(scope: .oncePerWindow)`, re-probe per OS release (`publish-sheet-opens-unfocused`) ### Trust boundaries - A guard defending against a downstream validation must mirror its EXACT emptiness/shape semantics — FixCardStore validates TRIMMED emptiness, so an `isEmpty` guard passes whitespace-only phrases through and the whole-call failure silently kills the entire submit (#6) - A trust gate matches its SINK's grammar, not just its own format check — `trustworthyURL` (built for line-bounded frontmatter) passed URLs whose `)` injects a live link once the sink became markdown; gate at the sink (angle-form destination), never trust the reused gate (#34) @@ -187,6 +188,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-12-05 | [20261205-publish-sheet-opens-unfocused_log.md](20261205-publish-sheet-opens-unfocused_log.md) | | 2026-12-05 | [20261205-issue208-post-summary-for-micro-blog_log.md](20261205-issue208-post-summary-for-micro-blog_log.md) | | 2026-12-04 | [20261204-issue207-allow-setting-and-creating-micro-blog-categories_log.md](20261204-issue207-allow-setting-and-creating-micro-blog-categories_log.md) | | 2026-12-04 | [20261204-issue206-display-micro-blog-published-status_log.md](20261204-issue206-display-micro-blog-published-status_log.md) | @@ -196,5 +198,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 2026-12-03 | [20261203-release-012-image-drop-fix_log.md](20261203-release-012-image-drop-fix_log.md) | | 2026-12-03 | [20261203-image-drop-27-2-drag-routing-pastes-path_log.md](20261203-image-drop-27-2-drag-routing-pastes-path_log.md) | | 2026-12-03 | [20261203-release-011-apex-refresh-is-step-one_log.md](20261203-release-011-apex-refresh-is-step-one_log.md) | -| 2026-12-01 | [20261201-release-010-readme-notes-packaging_log.md](20261201-release-010-readme-notes-packaging_log.md) | \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c1caf95..6da52ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ All notable changes to this project will be documented in this file. The format ### Fixed +- **publish:** The publish sheet opens with nothing focused (unticketed; owner report 2026-12-05; #207 follow-up) — the **Categories** field was the sheet's first text input, and a sheet window hands its initial focus to that field exactly as a window does at launch, so the completion menu popped the moment the sheet opened. The sheet now rides the launch-focus-reset rider (once per window) and resigns that auto-focus at its first become-key; the menu still appears the moment you click into the field. `.defaultFocus(…, false)` does not stop the assignment on macOS 27.2.1 (probed), and the rider is the same one the library search field has used since launch. No new pins (view wiring; the OS-behaviour probe is `prototypes/MicropubSheetFocusProbe.swift`). Suite 814 + - **publish:** A Micro.blog 5xx names their outage instead of a bare `HTTP 503` (unticketed; owner report 2026-12-04) — their errors arrive as HTML pages, never Micropub JSON, so `decodeFailure` fell through to the status code and the sheet read "Micro.blog said 503: HTTP 503", which says nothing about whose side it is on. A live probe at report time found the endpoint healthy (25/25 tokenless POSTs answered the usual 400; their news feed logs repeated 503 incidents), so the 503 was theirs and transient. The decode now answers `unavailable on their side — retry in a few minutes (status.micro.blog)` for any 5xx that carries no JSON description — ONE decode, so create, publish, q=config, and media uploads all speak it; a described 5xx keeps its description, a 4xx keeps the bare status. +1 test (a 503 over an HTML body → the their-side wording; a 422 over the same body → `HTTP 422`; a 502 with `error_description` → the description), flip-verified — the guard off reddens exactly that pin with `detail → "HTTP 503"`. Suite 736 ## [0.1.2] - 2026-12-03 diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index f53e317..5187d48 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -26,9 +26,9 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te - `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination`: the drop surface for drags that land OUTSIDE the editor — macOS 27.2.1 routes a drag to the DEEPEST destination, so over the editor the text view takes the drag itself (`FileDropTextView`'s drag handlers) and this destination never fires (the inverse of the 27.0.1 ruling #141 was verified on); both route through `AppGateState.routeFileDrop` — the ONE file-drop router (pure-markdown → external guest, anything else → `ingestDrop`, Cold Turkey–guarded; a mixed md+image set and web URLs refuse loudly). A landed drop hops to Posts (unreachable for images today — the editor mounts only there). The house ask sheets present here (pending-state + binding pattern; the sheet structs live in `WorkspaceViewSheets.swift`, #193). #193 splits: `ArchivePaneView` → `ArchivePaneView.swift`, shared chrome (`SelectedRowStrip`/`BorderedSecondaryButtonStyle`/`PaneHeader`) → `WorkspaceChrome.swift`; `RailButton` stays here (the rail is its only caller). - `ArchivePaneView.swift` — #193: the #108 Archive pane (moved from WorkspaceView.swift) — archive/ as a rail destination, List-only: clicking a piece selects it and hops to Posts (where the editor column lives); reuses `LibraryPostRow`. Row menu: Move Back / Rename / Convert, plus #205 Reveal in Finder / Copy Path and #206 Open on Micro.blog. - `WorkspaceViewSheets.swift` — #193: the house ask sheets (moved from WorkspaceView.swift) — `OriginAskSheet` (the ONE origin ask per import batch, #94), `OutlineGuardSheet` (#111 mixed-content), `ConvertSheet` (#114), `NewProjectSheet` (#108). -- `WorkspaceChrome.swift` — #193: the shared chrome (moved from WorkspaceView.swift) — `SelectedRowStrip` (the selected-row capsule), `BorderedSecondaryButtonStyle` (the bordered secondary button), `PaneHeader` (the 52pt pane-head row); every pane reuses them. #205 `FinderHandOffButtons` — the ONE Reveal in Finder / Copy Path fragment every piece-listing row menu mounts directly (library column, Archive pane); both act on `model.fileURL(for:)`, a nil URL no-ops. #206 `MicroblogHandOffButton` — Open on Micro.blog, only for a PUBLISHED piece (a draft's final URL answers Not Found until the post is published — owner-verified 2026-12-04); mounted beside the Finder pair in both menus. +- `WorkspaceChrome.swift` — #193: the shared chrome (moved from WorkspaceView.swift) — `SelectedRowStrip` (the selected-row capsule), `BorderedSecondaryButtonStyle` (the bordered secondary button), `PaneHeader` (the 52pt pane-head row); every pane reuses them. #205 `FinderHandOffButtons` — the ONE Reveal in Finder / Copy Path fragment every piece-listing row menu mounts directly (library column, Archive pane); both act on `model.fileURL(for:)`, a nil URL no-ops. #206 `MicroblogHandOffButton` — Open on Micro.blog, only for a PUBLISHED piece (a draft's final URL answers Not Found until the post is published — owner-verified 2026-12-04); mounted beside the Finder pair in both menus. `InitialFocusReset` (r8, moved here in the #207 follow-up once the publish sheet needed it) — the ONE window-focus rider: at the window's FIRST become-key it resigns AppKit's initial first responder (the first text input) back to the window; `.oncePerProcess` = the library column's launch reset, `.oncePerWindow` = the publish sheet. - `PostsPaneView.swift` — Posts destination (#193: the library column and the row live in their own files): editor column, mentor column (fixed 356). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column. -- `PostsLibraryColumn.swift` — #193: the library column (moved from PostsPaneView.swift), shared by the unfocused layout and the focus-mode left reveal — one implementation, both surfaces. Project section heads + Pass-State groups, collapse toggle per-view; owns the rename + move sheets (`RenamePostSheet`, `MoveToProjectSheet`) and the row context menu (#205: the shared hand-off fragment — #206 `MicroblogHandOffButton`, then #205 `FinderHandOffButtons` — between Move to Archive and Trash). Library search: debounced, title+body over non-archived pieces through the file-scope `librarySearch` mount, body scan off-main through `readBody` (frontmatter never searched). `LaunchFocusReset` (r8) rides the column: the window's first become-key resigns focus back to the window, once per process. +- `PostsLibraryColumn.swift` — #193: the library column (moved from PostsPaneView.swift), shared by the unfocused layout and the focus-mode left reveal — one implementation, both surfaces. Project section heads + Pass-State groups, collapse toggle per-view; owns the rename + move sheets (`RenamePostSheet`, `MoveToProjectSheet`) and the row context menu (#205: the shared hand-off fragment — #206 `MicroblogHandOffButton`, then #205 `FinderHandOffButtons` — between Move to Archive and Trash). Library search: debounced, title+body over non-archived pieces through the file-scope `librarySearch` mount, body scan off-main through `readBody` (frontmatter never searched). `InitialFocusReset(scope: .oncePerProcess)` (r8 — the rider itself lives in `WorkspaceChrome.swift`) rides the column: the window's first become-key resigns focus back to the window, once per process. - `LibraryPostRow.swift` — #193: the post row (moved from PostsPaneView.swift) — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Reveal in Finder/Copy Path/Open on Micro.blog (#206, published pieces)/Trash (the menu is attached by the callers — `PostsLibraryColumn.swift`, `ArchivePaneView.swift`); the Archive pane reuses it. #206: the mono-11 micro-label shows the piece's Micro.blog status when it has one (`published ` / `draft on Micro.blog`) in origin's place — 178pt of row content cannot carry both — and VoiceOver reads both (`accessibilityText`); origin stays one hover away (the label's tooltip). - `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects///post.md` AND `archive///post.md` (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, `untitled` fallbacks; runs off-main. `stats_*` keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the named immutable pair (`PostFrontmatter.isUnaidedFirstDraftPair` — origin writer, type post; never pass_state, which legitimately advances). `scan(home:cache:)` takes a `PostScanCache` (path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh). `micropubURL` through the ONE trust gate (`Micropub.rememberedURL`, format-only — ownership is settled upstream: the import boundary drops the key, so only Museion or the writer's own hand writes one); #206 `micropubPublished` (frontmatter `micropub_published`, the `stats_captured` stamp shape, read by the shared `parseStamp`) and the row label `micropubStatus` (`published ` / `draft on Micro.blog` / nil). - `PostFrontmatter.swift` — #180: the Post frontmatter codec — the ONE lenient read (`parse`/`split`/`decoded`), `stampFormat` (the frontmatter timestamp shape both stamp writers and the reader share), and the three write postures behind one known-key table (`ownedKeys`: type, pass_state, origin — one insertion-order rule): fresh stamp (`stamped`), merge-import (`mergingImport` — external keys verbatim, ours win, and the Micro.blog bookkeeping dropped: `micropubKeys` — #206, a foreign file carries no post of this library), update-keys (`updating` — the in-place line-walk, every other line byte-identical; `dropping:` removes named keys' lines — the import and the 404 forget). Absorbed and deleted `PostStore.stamped/splitFrontmatter/mergedFrontmatter` and `LearningDecay.stampingFrontmatter` byte-identically (merge-import's documented prefix-preservation divergence excepted). Owns the two named eligibility predicates both gates consume: `isUnaidedFirstDraftPair` (writer ∧ post — the scan's read-back gate) and `isCaptureEligible` (pair ∧ First Draft — the capture gate). Learning/Fix Card documents stay out of scope; the learnings dismiss stamp rides the generic update posture. #207 the one-line `category:` list codec: `categories(in:)` reads the line (bracketed list, a bare scalar = ONE category, empty/absent = none) and `categoryValue(_:)` renders it — both over the unbracketed `categoryList`/`categoryListValue` and the one segment scanner `categorySegments` the publish sheet's field also speaks (ONE quote-aware comma-list parser: commas outside double quotes split, one pair of quotes stripped, `\\` and `\"` escaped on render and unescaped on read, empties dropped, first occurrence wins; newlines/control characters never reach the line-bounded sink). #208 the one-line `summary:` scalar: `summaryValue(_:)` renders it (every run of whitespace — a newline included — collapses to one space, control characters drop; a value holding a quote or backslash renders QUOTED with both escaped — the category codec's own escape, ONE grammar for both keys) and `summary(inText:)` reads it back off the RAW line, never through `parse`: the lenient decode trims EVERY edge quote, so a teaser's closing `"why"` would vanish through that door — the wire (`updateRememberedOrCreate`, `openPieceSummary`) and the sheet's settle all read the raw line. The read walks the block the way `parse` does (past the opening fence to the next `---`) — NOT via `split`, whose closing-fence check a mixed-ending file defeats (a stray `\r` fuses `---` onto the last block line: `parse` sees the key, `split` sees no block) — and cuts a fused `\r\n---` tail off the value; a BODY line named `summary:` never claims the key (no fence, no block). Empty/blank/absent = `""` — the field's settled empty. @@ -41,7 +41,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te - `Pass.swift` — `PassKind` (pass1/pass2 — the app's own names) + `PassContext.stub` (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + `estimateTokens` (chars/4). - `BlindRead.swift` — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; `reveal` mapping appended by the model ONLY after the turn ends. - `SummaryPrompt.swift` — #208: the AI post summary's prompt vocabulary (pure) — `prompt(title:body:)` carries the Title and body inline and asks for a first-person teaser that entices the reader to read the full piece; `cleaned(_:)` is the reply as the field's text (trimmed, ONE leading `Summary:` label dropped — colon required, so prose opening with the word keeps it; one pair of surrounding quotes stripped; then the codec's round-trip — `summaryValue` → the raw-line read — so the FIELD shows exactly the text the wire will carry, one line, no escapes). The model half is `PostsModelMicropubSummary.swift`; the summary's HOME is the frontmatter `summary:` line the SEND stamps — this half only drafts text for the publish sheet's field. -- Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubCategories.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; #207 the piece's `category:` list travels — a create carries `category` ONLY when non-empty, and naming a category Micro.blog doesn't know CREATES it there (no separate create call); #208 the piece's `summary:` line travels the same way — a create carries `properties.summary` ONLY when non-empty, a re-send carries `summary` in `replace` only when the piece has the line (opt-in by key, `""` is sent and CLEARS the post's summary); NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; #206 the remembered URL is also an OWNERSHIP question the format gate cannot answer — the import boundary drops both micropub keys (`PostFrontmatter.micropubKeys`), so a foreign file never aims a send at one of the writer's posts); 401/403 → authFailed with `error_description`; a 5xx over Micro.blog's HTML error page names their outage (`unavailable on their side — retry in a few minutes`), never a bare `HTTP 503` — ONE decode (`decodeFailure`), every step; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys) — entered in the sheet on first use, managed from Settings → Micro.blog (saved status, replace, remove; the page reads the slot back after every write — a locked keychain fails visibly, never a false "stored"; the status is a standing `✓ Token saved in your Keychain` row in the Settings verdict idiom, not an intro-line swap). Media: `illustrations(in:)` parses only `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form; `queryRequest(_:token:)` is the one `GET ?q=…` builder (config + the category list). Categories: `blogCategories(token:)` (`q=category`, `MicropubCategories.swift`) = the blog's own category names for the sheet's suggestions — the root `categories` strings, else `microblog-categories`'s `name` fields, trimmed, empties dropped; any failure or non-2xx is `[]` (no suggestions is not an error — the sheet stays silent, and a rejected token surfaces on the send itself). The sheet's Categories field (`MicropubPublishSheet.swift`) is a comma list in the codec's unbracketed form with the system completion menu over `blogCategories` (fetched on open; a failed fetch is silent — a typed new name creates the category at the send); the system REPLACES the whole field text with a completion, so `MicropubCategoryField.completion` IS the merge — a pick ADDS, a half-typed last word is replaced, a present name is never offered; the edit lands at the send via `micropubSend(categories:)` (Publish applies it first and flips the post that send touched — never the sheet's possibly-stale URL); the field syncs from disk over `openPieceCategories()` (the model's read of the open piece — never the scan snapshot) 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, so a later clear of the field must still count as an edit). #208 the sheet's Summary field — the same discipline over the one-line `summary:` scalar: a multi-line `TextEditor` with an `AI summary` button (a bordered small control in the label row) that runs `posts.summarize(mentor:)` — the sheet holds `let mentor: MentorSessionModel` (PostsPaneView passes its own; the ONE construction site) and the reply fills the field for the writer to edit; the button and the field hold still while the turn runs; the button is ALSO disabled while a Pass or Blind Read owns the one-shot rail, with the hover reason saying so (the pass bar's disabled-with-reason idiom — the guard behind it is `guardOpenPieceRun`), and a refusal shows inline with the field's text kept. The sheet is MODAL — the pass bar's Cancel sits behind it — so while this sheet's own summary turn runs the AI button IS the Stop (the spinner stays clickable, `cancelPass` ends the turn on the shared rail); `summarizing` is the MODEL's flag (`PostsModel.summarizing`, the third rider beside `runningPass`/`runningBlindRead`), read by the sheet, the pass bar's Cancel visibility, and `cancelPass`/`guardOpenPieceRun` through the ONE `oneShotRailBusy` predicate — a fourth rider joins the predicate and every site follows. The edit-for-send test is `MicropubSummaryField.pendingSummary` — a STRING compare on trimmed text, so whitespace alone is not an edit and equal empties stay nil (a piece without a line never gains an empty key); `""` is the clear — the model writes `summary:` empty and the re-send clears the post's. Sync points mirror the Categories field: disk on open and after a forget, canonical one-line text after a successful send or publish, baseline only after a failed step. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author; #206 an UNCHANGED image never uploads twice — `.museion-uploads.json` in the piece folder maps `sha256(bytes) → URL` (trust-gated on read-back, a symlinked memo never reads, written as each upload lands), so a re-send with untouched images is ONE request. The sheet owns every explicit click and opens on the piece's publish record (#206): Send as Draft → Publish for a never-sent piece, Update Draft for a draft, Update Live Post for a published one (status line + the live link; a remembered draft shows no link — its final URL answers Not Found until published; a publish stamp with no remembered link offers Send as Draft — there is no post to update). #206 a re-send never duplicates — a piece that remembers a post UPDATES it in place (`action=update` + `replace` name/content: same URL, no second post; a draft stays a draft, a live post edits live; #207 `replace` carries `category` ONLY when the piece has the `category:` line — opt-in by key, `[]` is sent and clears the post's categories, no line leaves the blog's); a 404 means the post is gone there, so the piece forgets both stamps — their lines removed (`.forgotten`) — and the sheet is back to Send as Draft — a forget that cannot land refuses with the by-hand instruction instead; refusals inline with buttons kept; with a stored token in use it names it (the field's absence alone never said which token a send carries). +- Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubCategories.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; #207 the piece's `category:` list travels — a create carries `category` ONLY when non-empty, and naming a category Micro.blog doesn't know CREATES it there (no separate create call); #208 the piece's `summary:` line travels the same way — a create carries `properties.summary` ONLY when non-empty, a re-send carries `summary` in `replace` only when the piece has the line (opt-in by key, `""` is sent and CLEARS the post's summary); NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; #206 the remembered URL is also an OWNERSHIP question the format gate cannot answer — the import boundary drops both micropub keys (`PostFrontmatter.micropubKeys`), so a foreign file never aims a send at one of the writer's posts); 401/403 → authFailed with `error_description`; a 5xx over Micro.blog's HTML error page names their outage (`unavailable on their side — retry in a few minutes`), never a bare `HTTP 503` — ONE decode (`decodeFailure`), every step; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys) — entered in the sheet on first use, managed from Settings → Micro.blog (saved status, replace, remove; the page reads the slot back after every write — a locked keychain fails visibly, never a false "stored"; the status is a standing `✓ Token saved in your Keychain` row in the Settings verdict idiom, not an intro-line swap). Media: `illustrations(in:)` parses only `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form; `queryRequest(_:token:)` is the one `GET ?q=…` builder (config + the category list). Categories: `blogCategories(token:)` (`q=category`, `MicropubCategories.swift`) = the blog's own category names for the sheet's suggestions — the root `categories` strings, else `microblog-categories`'s `name` fields, trimmed, empties dropped; any failure or non-2xx is `[]` (no suggestions is not an error — the sheet stays silent, and a rejected token surfaces on the send itself). The sheet's Categories field (`MicropubPublishSheet.swift`) is a comma list in the codec's unbracketed form with the system completion menu over `blogCategories` (fetched on open; a failed fetch is silent — a typed new name creates the category at the send); the sheet opens with NOTHING focused — a sheet window takes its initial first responder like any window (its first text input, the Categories field — the completion menu popped on open), and `InitialFocusReset(scope: .oncePerWindow)` resigns it at the sheet's first become-key (`.defaultFocus(…, false)` does not; macOS 27.2.1, `prototypes/MicropubSheetFocusProbe.swift`); the system REPLACES the whole field text with a completion, so `MicropubCategoryField.completion` IS the merge — a pick ADDS, a half-typed last word is replaced, a present name is never offered; the edit lands at the send via `micropubSend(categories:)` (Publish applies it first and flips the post that send touched — never the sheet's possibly-stale URL); the field syncs from disk over `openPieceCategories()` (the model's read of the open piece — never the scan snapshot) 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, so a later clear of the field must still count as an edit). #208 the sheet's Summary field — the same discipline over the one-line `summary:` scalar: a multi-line `TextEditor` with an `AI summary` button (a bordered small control in the label row) that runs `posts.summarize(mentor:)` — the sheet holds `let mentor: MentorSessionModel` (PostsPaneView passes its own; the ONE construction site) and the reply fills the field for the writer to edit; the button and the field hold still while the turn runs; the button is ALSO disabled while a Pass or Blind Read owns the one-shot rail, with the hover reason saying so (the pass bar's disabled-with-reason idiom — the guard behind it is `guardOpenPieceRun`), and a refusal shows inline with the field's text kept. The sheet is MODAL — the pass bar's Cancel sits behind it — so while this sheet's own summary turn runs the AI button IS the Stop (the spinner stays clickable, `cancelPass` ends the turn on the shared rail); `summarizing` is the MODEL's flag (`PostsModel.summarizing`, the third rider beside `runningPass`/`runningBlindRead`), read by the sheet, the pass bar's Cancel visibility, and `cancelPass`/`guardOpenPieceRun` through the ONE `oneShotRailBusy` predicate — a fourth rider joins the predicate and every site follows. The edit-for-send test is `MicropubSummaryField.pendingSummary` — a STRING compare on trimmed text, so whitespace alone is not an edit and equal empties stay nil (a piece without a line never gains an empty key); `""` is the clear — the model writes `summary:` empty and the re-send clears the post's. Sync points mirror the Categories field: disk on open and after a forget, canonical one-line text after a successful send or publish, baseline only after a failed step. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author; #206 an UNCHANGED image never uploads twice — `.museion-uploads.json` in the piece folder maps `sha256(bytes) → URL` (trust-gated on read-back, a symlinked memo never reads, written as each upload lands), so a re-send with untouched images is ONE request. The sheet owns every explicit click and opens on the piece's publish record (#206): Send as Draft → Publish for a never-sent piece, Update Draft for a draft, Update Live Post for a published one (status line + the live link; a remembered draft shows no link — its final URL answers Not Found until published; a publish stamp with no remembered link offers Send as Draft — there is no post to update). #206 a re-send never duplicates — a piece that remembers a post UPDATES it in place (`action=update` + `replace` name/content: same URL, no second post; a draft stays a draft, a live post edits live; #207 `replace` carries `category` ONLY when the piece has the `category:` line — opt-in by key, `[]` is sent and clears the post's categories, no line leaves the blog's); a 404 means the post is gone there, so the piece forgets both stamps — their lines removed (`.forgotten`) — and the sheet is back to Send as Draft — a forget that cannot land refuses with the by-hand instruction instead; refusals inline with buttons kept; with a stored token in use it names it (the field's absence alone never said which token a send carries). - `PostsModelMicropubSummary.swift` — #208: the AI summary's model half — `summarize(mentor:)`: the shared open-piece guard rail (`guardOpenPieceRun`, the brief-28 Home identity) → flush-first → ONE disk read feeds the prompt → `mentor.runSummary` on a fresh one-shot chat-profile engine → `SummaryPrompt.cleaned`. Returns the text or nil with `lastError` naming the blocker; a stale guard refusal never survives into the strip (`lastError` cleared once the guards pass). Writes NOTHING — the text is the publish sheet's to place, and the SEND stamps the `summary:` line. - `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`, write rail+structural ops `PostsModelWrites.swift`, external guest+imports `PostsModelImports.swift`, watcher+rescan `PostsModelWatcher.swift` (home of `PostsWatcher`), (Home, ID) identity `PostsModelIdentity.swift` — `openSessionTargets` + #205 `fileURL(for:)`, the row menus' post.md path, a pure read) — the #146/#193 splits. **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome` — written only by the watcher extension's `startWatching` behind `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text; #204 `revealCard` stamps ONE `revealRequest` (the anchor's span in the LIVE session text + a per-jump token) — a view act, nothing written; the editor column feeds it into the #71 caret rail (`caretHint`, now a `FixCardRevealRequest` — a non-zero range selects the span). `micropubSend` (#206; was `micropubSendDraft`) = guards → flush → (#207 a non-nil `categories:` edit lands as the piece's `category:` line FIRST — a failed write REFUSES the send with nothing on the wire; #208 a non-nil `summary:` edit lands the same way, sanitized through `summaryValue`) → ONE disk read serves the wire fields, the categories, the summary, and the remembered URL — no URL → create + stamp `micropub_url`, a remembered URL → the in-place update (`stampCategories` + `stampSummary` + `updateRememberedOrCreate` are its steps); `micropubPublish` (step 2, model-owned since #206) trust-gates its URL (`trustworthyURL` — it lands in frontmatter), #207/#208 runs `micropubSend` FIRST when `categories:` or `summary:` is non-nil — the remembered post, or the fresh draft a create returned, is what gets published, and a failed send returns its outcome with NO publish (disk and blog never silently disagree) — then stamps the publish record `micropub_published` and heals `micropub_url` in the same write; both share the (Home, ID) identity guard `openMicropubPiece`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). #200: quit is a document departure — `shutdown()` routes both sessions through `documentsMayDepart` (void — the verdict channel is quitReply's); `PostsModel.active` (weak static, registered by `AppGateState.init` — the `WritingLockState.active` precedent) is the quit gate's reachability, bare test rigs never register. - `PostsModelWatcher.swift` — #193: the watching domain of PostsModel (moved from PostsModel.swift) — `PostsWatcher` (recursive FSEvents stream, file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; `bind(home:)` (WorkspaceView's root `.task(id: museionHome)` drives it); `startWatching` (the one `watchedHome` writer); `rescan` off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes), bumping `contentRevision` on list change OR cache miss (#144), handing the session the open post's disk text (the #67 check, watcher echo suppressed by equality), riding the cards refresh at the tail. diff --git a/Museion/MicropubPublishSheet.swift b/Museion/MicropubPublishSheet.swift index dbdac7b..1e56e6a 100644 --- a/Museion/MicropubPublishSheet.swift +++ b/Museion/MicropubPublishSheet.swift @@ -34,6 +34,11 @@ // 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 @@ -335,6 +340,8 @@ struct MicropubPublishSheet: View { } .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. diff --git a/Museion/PostsLibraryColumn.swift b/Museion/PostsLibraryColumn.swift index 2db865f..d290e27 100644 --- a/Museion/PostsLibraryColumn.swift +++ b/Museion/PostsLibraryColumn.swift @@ -4,11 +4,9 @@ // // #193: the Posts library column, moved from PostsPaneView.swift // (file-length ceiling) — PostsLibraryColumn with its rename/move -// sheets, the file-scope librarySearch mount (#144), and -// LaunchFocusReset (r8), code unchanged. +// sheets and the file-scope librarySearch mount (#144). The r8 focus +// rider is InitialFocusReset (WorkspaceChrome.swift). // - -import AppKit import SwiftUI /// #21: the library column, shared by the unfocused layout and the focus-mode @@ -36,8 +34,8 @@ struct PostsLibraryColumn: View { /// onAppear-unfocus could never work — the launch focus is AppKit /// assigning the window's INITIAL first responder to its first text /// input (this field), at window-become-key, AFTER onAppear. FocusState - /// merely mirrors that back as true. LaunchFocusReset (below) resigns - /// it at the first become-key; from then on only the user drives this. + /// merely mirrors that back as true. InitialFocusReset (WorkspaceChrome) + /// resigns it at the first become-key; from then on only the user drives this. @FocusState private var searchFocused: Bool private var trimmedQuery: String { @@ -156,8 +154,8 @@ struct PostsLibraryColumn: View { } .frame(width: DesignTokens.libraryWidth) // r8 (argon#6, mercury#12): the focus-rider replaces the r6/r7 - // onAppear-unfocus — see LaunchFocusReset below for the mechanism. - .background(LaunchFocusReset()) + // onAppear-unfocus — see InitialFocusReset (WorkspaceChrome) for the mechanism. + .background(InitialFocusReset(scope: .oncePerProcess)) .sheet(item: $renamingPost) { post in RenamePostSheet(post: post) { title in model.rename(post, to: title) @@ -384,57 +382,6 @@ private nonisolated func librarySearch( } } -/// r8 (argon#6, mercury#12 — the launch auto-focus ROOT CAUSE, killed at -/// the source): the search field is the window's first — and at launch, -/// only — text input, and AppKit assigns the window's initial first -/// responder to it when the window becomes key. That happens AFTER -/// onAppear, so the r6/r7 `searchFocused = false` writes were always -/// overridden (FocusState mirrors the assignment back as true: terracotta -/// ring + caret, the strongest element on screen). This invisible rider -/// rides the library column and, at the window's FIRST become-key, -/// resigns focus back to the window itself (`makeFirstResponder(nil)` — -/// the neutral state; nothing gains focus instead). ONCE per process: a -/// pane-switch remount must never steal a focus the user set on return. -/// The second, next-runloop resign covers an assignment that lands after -/// the notification (the PostEditorView layout-race precedent). -private struct LaunchFocusReset: NSViewRepresentable { - /// Process-wide once-flag — launch is a once-per-process event. - private static var hasRun = false - - final class RiderView: NSView { - private var keyObserver: NSObjectProtocol? - - override func viewDidMoveToWindow() { - if let keyObserver { - NotificationCenter.default.removeObserver(keyObserver) - } - keyObserver = nil - guard let window else { return } - keyObserver = NotificationCenter.default.addObserver( - forName: NSWindow.didBecomeKeyNotification, - object: window, - queue: .main, - ) { _ in - MainActor.assumeIsolated { - // The observer is scoped to `window` (object:), so the - // notification carries nothing we don't already hold — - // reading `note` here would cross a Sendable boundary. - guard !LaunchFocusReset.hasRun else { return } - LaunchFocusReset.hasRun = true - window.makeFirstResponder(nil) - DispatchQueue.main.async { window.makeFirstResponder(nil) } - } - } - } - } - - func makeNSView(context _: Context) -> RiderView { - RiderView() - } - - func updateNSView(_: RiderView, context _: Context) {} -} - /// #108: Move to Project ask — radio list of the non-archived projects, /// default = the piece's current project. Matches RenamePostSheet's shape. struct MoveToProjectSheet: View { diff --git a/Museion/WorkspaceChrome.swift b/Museion/WorkspaceChrome.swift index cb684e3..2fe9ab4 100644 --- a/Museion/WorkspaceChrome.swift +++ b/Museion/WorkspaceChrome.swift @@ -5,7 +5,9 @@ // #193: the shared workspace chrome, moved from WorkspaceView.swift // (file-length ceiling) — SelectedRowStrip, BorderedSecondaryButtonStyle, // PaneHeader; every pane reuses them, code unchanged. #205 adds -// FinderHandOffButtons, #206 MicroblogHandOffButton (both born here). +// FinderHandOffButtons, #206 MicroblogHandOffButton (both born here), and +// InitialFocusReset (the r8 launch-focus rider — #207 follow-up: once per +// window for the publish sheet too). // import AppKit @@ -136,3 +138,71 @@ struct MicroblogHandOffButton: View { } } } + +/// r8 (argon#6, mercury#12 — the launch auto-focus ROOT CAUSE, killed at the source): AppKit assigns a +/// window's INITIAL first responder to its first text input when the window becomes key — AFTER onAppear, +/// so a FocusState write can't undo it (FocusState merely mirrors the assignment back as true: terracotta +/// ring + caret, the strongest element on screen). This invisible rider, at the window's FIRST become-key, +/// resigns focus back to the window itself (`makeFirstResponder(nil)` — the neutral state; nothing gains +/// focus instead). The second, next-runloop resign covers an assignment that lands after the notification +/// (the PostEditorView layout-race precedent). #207 follow-up: a SHEET window takes the focus the same way +/// (the publish sheet's Categories field — its completion menu popped on open; `.defaultFocus(…, false)` +/// changes nothing on macOS 27.2.1, `prototypes/MicropubSheetFocusProbe.swift`), so the rider carries a +/// scope — the library column's launch reset and the sheet's, two callers. +struct InitialFocusReset: NSViewRepresentable { + /// `.oncePerProcess` — the launch: a pane-switch remount must never steal a focus the user set on + /// return. `.oncePerWindow` — a sheet: every presentation is a new window, and its later re-keys keep + /// the user's focus. + enum Scope { + case oncePerProcess + case oncePerWindow + } + + private static var processHasRun = false + let scope: Scope + + final class RiderView: NSView { + var scope: Scope = .oncePerProcess + private var windowHasRun = false + private var keyObserver: NSObjectProtocol? + + override func viewDidMoveToWindow() { + if let keyObserver { + NotificationCenter.default.removeObserver(keyObserver) + } + keyObserver = nil + guard let window else { return } + keyObserver = NotificationCenter.default.addObserver( + forName: NSWindow.didBecomeKeyNotification, + object: window, + queue: .main, + ) { _ in + MainActor.assumeIsolated { + // The observer is scoped to `window` (object:), so the + // notification carries nothing we don't already hold — + // reading `note` here would cross a Sendable boundary. + switch self.scope { + case .oncePerProcess: + guard !InitialFocusReset.processHasRun else { return } + InitialFocusReset.processHasRun = true + case .oncePerWindow: + guard !self.windowHasRun else { return } + self.windowHasRun = true + } + window.makeFirstResponder(nil) + DispatchQueue.main.async { window.makeFirstResponder(nil) } + } + } + } + } + + func makeNSView(context _: Context) -> RiderView { + // The scope is set once at creation: it is a `let` on the representable and never changes + // for the view's lifetime. + let view = RiderView() + view.scope = scope + return view + } + + func updateNSView(_: RiderView, context _: Context) {} +} diff --git a/docs/devlog/20261205-publish-sheet-opens-unfocused_log.md b/docs/devlog/20261205-publish-sheet-opens-unfocused_log.md new file mode 100644 index 0000000..e08fbb3 --- /dev/null +++ b/docs/devlog/20261205-publish-sheet-opens-unfocused_log.md @@ -0,0 +1,76 @@ +# Publish sheet opens unfocused — the Categories field stops taking focus + +> **Date:** 2026-12-05 +> **Type:** generic +> **Reference:** follow-up to #207 (unticketed; owner report 2026-12-05) + +## Goal + +Since #207 the Micro.blog publish sheet opens with its **Categories** field focused, and the native completion menu pops with the focus. The owner asked for the sheet to open without focusing that field. + +## What Was Done + +- Root-caused it as the launch auto-focus (r8) in a second window: a `.sheet` is its own `NSWindow`, and at its first become-key the focus system makes the sheet's FIRST text input first responder — which the Categories field now is (it sits ahead of the Summary editor and the token field). `textInputSuggestions` presents its list when the editing interface is activated, so the menu popped on open. +- Probed the fix candidates on macOS 27.2.1 before touching the app (`prototypes/MicropubSheetFocusProbe.swift`, new): a `WindowGroup` → `.sheet(isPresented:)` mock of the sheet's control order, a 4 ms sampler over the sheet's `firstResponder` and `NSApp.windows`, then a user-focus + second `didBecomeKey` phase. + - `plain`, `.defaultFocus(Bool, false)`, `.defaultFocus(Enum?, nil)`: Categories field editor first responder, `SwiftUISuggestionsWindow` visible from the first sample (seeded and unseeded field alike). + - the rider: never a field editor, never the menu; the re-key keeps the focus the "user" set. +- Reused the r8 rider instead of writing a new mechanism: `LaunchFocusReset` became `InitialFocusReset(scope:)` (`.oncePerProcess` / `.oncePerWindow`), moved from `PostsLibraryColumn.swift` to `WorkspaceChrome.swift` (two callers now, so it is shared chrome). The library column mounts `.oncePerProcess` exactly as before; the publish sheet mounts `.oncePerWindow` in its content's `.background`. +- Verified: lint clean on the four touched Swift files; rail run `20261205T114641Z-Museion` compiled all three changed app files (`SwiftCompile` lines at 12:46:45) and passed 814/814; owner live check in the built app 2026-12-05: approved. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Rider at the sheet's first `didBecomeKey`, not a SwiftUI focus API | The SwiftUI door is closed: `.defaultFocus(…, false)` and `(…, nil)` changed nothing in the probe, and an `onAppear` focus write lands BEFORE AppKit's assignment (the r8 finding). The rider is the mechanism this app has shipped since r8. | +| Generalize the existing rider (scope) rather than add a sibling | One mechanism, two call sites; a copy would have left two places to fix when the OS moves. Per-window flag is what a sheet needs (every presentation is a new window; a later re-key must not steal a focus the user set). | +| Neutral state (window is first responder), not "focus the Summary editor" | Nothing in the sheet is the thing the writer came to type; the launch posture (`makeFirstResponder(nil)`) already models "review, then click". | +| Keep the probe in `prototypes/` | Focus routing is an OS-version claim (the drag-routing precedent): re-run the bundle after every macOS point release. | +| Other ask sheets untouched | Rename / New Project / Move want typing — their auto-focus is the feature. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| `.defaultFocus($focused, false)` and `.defaultFocus($field, nil)` had no effect | On macOS 27.2.1 SwiftUI falls back to the first text input when no view matches the default-focus value | The rider; both non-fixes are recorded in the probe header so nobody retries them | +| Probe segfaulted at the first timer tick (`objc_opt_respondsToSelector` at 0x1) | A Swift `Bool` passed to `String(format:)` under `%@` — bridged as a non-object | Pass a string (`? "yes" : "no"`) | +| swiftformat + swiftlint disagreed on the sampler's `if` | The known wrapped-condition trap (#142/#179) | Hoisted the predicate (`summaryEditor(in:)`) | +| The rail's second run showed zero `SwiftCompile` lines | My first `start` was piped through `tail` and its run dir went unseen; the re-start found everything already built | Compile evidence read from the FIRST run's log (`20261205T114641Z-Museion`); second run 814/814 as well | +| Driving the real app: the terminal re-grabbed focus between calls | Hermes TUI is the frontmost app on this machine | The owner offered to drive — handed a four-step checklist instead of walking the AX tree | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/WorkspaceChrome.swift` | `InitialFocusReset(scope:)` — the r8 rider, moved here, with `.oncePerProcess` / `.oncePerWindow` | +| `Museion/PostsLibraryColumn.swift` | Mounts `InitialFocusReset(scope: .oncePerProcess)`; the private `LaunchFocusReset` and its stranded `import AppKit` removed | +| `Museion/MicropubPublishSheet.swift` | Mounts `InitialFocusReset(scope: .oncePerWindow)`; header note | +| `Museion/AGENTS.md` | DOX pass: the rider's new home and scope, the sheet's unfocused open | +| `prototypes/MicropubSheetFocusProbe.swift` | New OS-behaviour probe (four variants, 4 ms sampler, re-key phase) | +| `CHANGELOG.md` | `[Unreleased]` → Fixed entry | +| `AGENTS.md`, `docs/devlog/INDEX.md` | Learning bullet; this log's row + window | + +## Verification + +- Finish-audit gates (final tree): whole-repo `swiftformat --lint .` 0/162 and `swiftlint --strict .` 0 violations before dispatch; the four touched Swift files re-linted after the audit fixes (0/4, 0 violations); `full-test.sh` **814/814** (run `20261205T134019Z-Museion`, pid-matched — the three app files edited in the audit compiled in it, SwiftCompile lines at 14:40:25). Pre-audit baseline on the same shape: run `20261205T114641Z-Museion`, 814/814. +- Finish-up gates (the committed tree): `swiftformat --lint .` exit 0, 0/162 · `swiftlint --strict .` exit 0, 0 violations in 151 files · `full-test.sh` **814/814**, 0 failed (run `20261205T135748Z-Museion`, pid-matched; 814 → 814 — no new pins, the probe is the check). That run compiled nothing by design (the tree was already built): the sources' last edits (14:39) predate run `20261205T134019Z-Museion`, which holds the SwiftCompile lines. +- Probe (the change's only check — an OS-behaviour claim): all four variants, seeded and unseeded, re-run after the audit fix. plain / defaultFalse / defaultNil auto-focus the Categories field with the suggestions window visible; rider never focuses a field and shows no menu; the re-key keeps the user-set focus in every variant. The INVALID path exercised with a bare (unbundled) launch: the sheet never becomes key there, and the probe now exits 2 with `PROBE INVALID` instead of the green string. +- Owner live check in the built app, 2026-12-05: approved. + +## Finish Audit + +Three fresh-context reviewers (ponytail-review, security-review, review) over the working tree. + +- Security: no findings — the diff's one runtime act is `makeFirstResponder(nil)`; the observer is registered once per view↔window attachment and removed on every window change. +- General, MEDIUM — accepted: the probe's green verdict could not tell "rider worked" from "sheet never became key". `finish()` now requires a key sample and a landed user-focus step, else `PROBE INVALID` + exit 2. +- General, LOW — accepted: the root learning's snippet lacked the `scope:` label (fixed, 192 chars); the probe header now says its two `@FocusState` bindings exist for the defaultFocus variants only. +- General, INFO — no action: the AGENTS.md window holds exactly 10 data rows (the reviewer's 12 counted the header and separator). +- Ponytail — accepted in part: the dead `updateNSView` scope write is gone (the scope is set once at creation); the sheet's header and mount comments were cut to pointers, so `InitialFocusReset`'s doc is the one home of the mechanism; the move-history clauses left the code comments (the DOX keeps them). +- Ponytail — declined: `let scope` + `RiderView(scope:)` — an init pair for a nested class only this representable constructs, +3 lines to remove a default no other caller can reach. + +## Open Items & Next Steps + +- [ ] Re-run `prototypes/MicropubSheetFocusProbe.swift` after every macOS point release. + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index b44e712..c0e77b5 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-12-05 | generic | [20261205-publish-sheet-opens-unfocused_log.md](20261205-publish-sheet-opens-unfocused_log.md) | Publish sheet opens unfocused: the Categories field no longer takes focus, so the completion menu stops popping (rail 814/814) | | 2026-12-05 | issue | [20261205-issue208-post-summary-for-micro-blog_log.md](20261205-issue208-post-summary-for-micro-blog_log.md) | Micro.blog summary travels with the piece; publish sheet Summary field + AI summary button on the one-shot rail (rail 814/814) | | 2026-12-04 | issue | [20261204-issue207-allow-setting-and-creating-micro-blog-categories_log.md](20261204-issue207-allow-setting-and-creating-micro-blog-categories_log.md) | Micro.blog categories travel with the piece; comma field with native completion; publish targets the post the send touched (rail 791/791) | | 2026-12-04 | issue | [20261204-issue206-display-micro-blog-published-status_log.md](20261204-issue206-display-micro-blog-published-status_log.md) | Micro.blog publish is remembered and shown: row status, in-place re-send, upload memo, 404 forget; Import drops micropub keys (rail 752/752) | diff --git a/prototypes/MicropubSheetFocusProbe.swift b/prototypes/MicropubSheetFocusProbe.swift new file mode 100644 index 0000000..bc61348 --- /dev/null +++ b/prototypes/MicropubSheetFocusProbe.swift @@ -0,0 +1,270 @@ +// PROBE — #207 follow-up: the publish sheet's Categories field takes focus when the sheet opens, and the +// native completion menu pops with it. THROWAWAY; not part of the app target. An OS-behaviour probe: re-run +// after every macOS point release (the drag-routing precedent, #141 follow-up). +// Build: swiftc -O -parse-as-library prototypes/MicropubSheetFocusProbe.swift -o /tmp/micropub_sheet_focus_probe +// Run: copy the binary into /tmp/MicropubSheetFocusProbe.app/Contents/MacOS/ (Info.plist: CFBundleExecutable= +// micropub_sheet_focus_probe, CFBundlePackageType=APPL) and `open -W -n` that bundle with +// `--env PROTO_VARIANT=` (a bare binary never gets real key-window +// status). The probe presents a mock of MicropubPublishSheet (same control ORDER, the same onAppear +// disk-sync write into the Categories field), samples the sheet's first responder and the app's window +// list every 4 ms for ~0.8 s (a one-frame flash cannot hide between samples), then focuses the Summary +// editor and posts the sheet a SECOND didBecomeKey (a focus the user set must survive a re-key); the +// transitions land in /tmp/sheet_focus_[_seed].log and the probe quits. PROTO_SEED=1 opens on +// a piece that already has categories. The sheet mock's two @FocusState bindings exist only for the +// defaultFocus variants — the rider variant never reads them. +// Variants: plain = today's sheet · defaultFalse = .defaultFocus(Bool, false) · defaultNil = .defaultFocus(Enum?, nil) +// · rider = the InitialFocusReset posture, once per window (resign at the sheet's first become-key). +// Verdict (macOS 27.2.1): plain / defaultFalse / defaultNil auto-focus the Categories field with the +// SwiftUISuggestionsWindow visible from the first sample; rider never shows a field editor or the menu, +// and the re-key keeps the Summary editor focused. A run whose sheet never became key, or whose +// user-focus step failed, prints PROBE INVALID and exits 2 — never the green verdict. + +import AppKit +import SwiftUI + +enum Variant: String { + case plain, defaultFalse, defaultNil, rider + + static var current: Variant { + Variant(rawValue: ProcessInfo.processInfo.environment["PROTO_VARIANT"] ?? "") ?? .plain + } +} + +// MARK: - Mock sheet (mirrors MicropubPublishSheet's control order) + +private enum Field: Hashable { + case categories, summary +} + +struct SheetMock: View { + @State private var categoryField = "" + @State private var summaryField = "" + @FocusState private var categoryFocused: Bool + @FocusState private var focused: Field? + private static let blog = ["Tech", "Notes", "Essays", "Fieldwork"] + + var body: some View { + switch Variant.current { + case .plain, .rider: + content + case .defaultFalse: + content.defaultFocus($categoryFocused, false) + case .defaultNil: + content.defaultFocus($focused, nil) + } + } + + private var content: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Publish to Micro.blog?") + .font(.headline) + Text("The expected value of showing") + .font(.callout.weight(.semibold)) + Text("Museion sends it as a draft first — nothing goes out until you publish.") + .font(.callout) + + VStack(alignment: .leading, spacing: 4) { + Text("Categories") + .font(.system(size: 11, design: .monospaced)) + TextField("Tech, Notes", text: $categoryField) + .textFieldStyle(.roundedBorder) + .font(.system(size: 12, design: .monospaced)) + .accessibilityLabel("Categories") + .focused($categoryFocused) + .focused($focused, equals: .categories) + .textInputSuggestions { + ForEach(Self.blog.filter { !categoryField.contains($0) }, id: \.self) { name in + Text(name).textInputCompletion(categoryField.isEmpty ? name : "\(categoryField), \(name)") + } + } + } + + VStack(alignment: .leading, spacing: 4) { + Text("Summary") + .font(.system(size: 11, design: .monospaced)) + TextEditor(text: $summaryField) + .font(.system(size: 11, design: .monospaced)) + .frame(height: 72) + .accessibilityLabel("Summary") + .focused($focused, equals: .summary) + } + + HStack { + Button("Publish") {} + Button("Send as Draft") {} + Button("Cancel") {} + } + } + .padding(16) + .frame(width: 420, alignment: .leading) + .background { + if Variant.current == .rider { + FocusResignRider() + } + } + // The sheet's disk sync lands in onAppear — the field's text changes under the auto-focus. + .onAppear { + categoryField = ProcessInfo.processInfo.environment["PROTO_SEED"] != nil ? "Tech, Notes" : "" + } + } +} + +/// The InitialFocusReset (WorkspaceChrome.swift) mechanism, in its once-per-WINDOW shape — the one the +/// publish sheet mounts. +struct FocusResignRider: NSViewRepresentable { + func makeNSView(context _: Context) -> RiderView { + RiderView() + } + + func updateNSView(_: RiderView, context _: Context) {} + + final class RiderView: NSView { + private var windowHasRun = false + private var keyObserver: NSObjectProtocol? + + override func viewDidMoveToWindow() { + if let keyObserver { + NotificationCenter.default.removeObserver(keyObserver) + } + keyObserver = nil + guard let window else { return } + keyObserver = NotificationCenter.default.addObserver( + forName: NSWindow.didBecomeKeyNotification, + object: window, + queue: .main, + ) { _ in + MainActor.assumeIsolated { + guard !self.windowHasRun else { return } + self.windowHasRun = true + window.makeFirstResponder(nil) + DispatchQueue.main.async { window.makeFirstResponder(nil) } + } + } + } + } +} + +// MARK: - App: one window, one sheet, a sampler + +@main +struct SheetFocusProbeApp: App { + @State private var showingSheet = false + + init() { + UserDefaults.standard.register(defaults: ["NSQuitAlwaysKeepsWindows": false]) + } + + var body: some Scene { + WindowGroup("Focus probe parent") { + Text("Parent window") + .frame(width: 400, height: 200) + .sheet(isPresented: $showingSheet) { + SheetMock() + } + .task { + try? await Task.sleep(for: .seconds(0.4)) + showingSheet = true + Sampler.start() + } + } + } +} + +/// Ticks every 4 ms (a one-frame flash cannot hide between samples), logs state TRANSITIONS, then exercises +/// the re-key case (a focus the user set must survive the window becoming key again); writes the log; quits. +private enum Sampler { + private static var lines: [String] = [] + private static var lastState = "" + private static var started = CFAbsoluteTimeGetCurrent() + + static func start() { + started = CFAbsoluteTimeGetCurrent() + var ticks = 0 + Timer.scheduledTimer(withTimeInterval: 0.004, repeats: true) { timer in + ticks += 1 + let now = CFAbsoluteTimeGetCurrent() - started + sample(at: now) + let sheet = NSApp.windows.first { $0.isSheet } + // ~0.4 s in: the user clicks into the Summary editor. + if ticks == 100, let sheet, let editor = summaryEditor(in: sheet) { + lines.append(String(format: "t=%.3f USER focuses the Summary editor -> %@", now, sheet.makeFirstResponder(editor) ? "yes" : "no")) + } + if ticks == 160, let sheet { + // ~0.64 s in: the window becomes key AGAIN (an app switch and back). + lines.append(String(format: "t=%.3f sheet didBecomeKey AGAIN", now)) + NotificationCenter.default.post(name: NSWindow.didBecomeKeyNotification, object: sheet) + } + if ticks >= 200 { + timer.invalidate() + finish() + } + } + } + + /// The Summary editor's text view: the first NSTextView that is not a field editor. + private static func summaryEditor(in sheet: NSWindow) -> NSTextView? { + sheet.contentView?.firstDescendant(of: NSTextView.self, where: { !$0.isFieldEditor }) + } + + private static func sample(at now: Double) { + let sheet = NSApp.windows.first { $0.isSheet } + guard let sheet else { return } + var state = "firstResponder=" + if sheet.firstResponder === sheet { + state += "WINDOW (nothing focused)" + } else if (sheet.firstResponder as? NSTextView)?.delegate is NSTextField { + state += "Categories FIELD EDITOR" + } else if sheet.firstResponder is NSTextView { + state += "Summary TEXT VIEW" + } else { + state += String(describing: type(of: sheet.firstResponder!)) + } + state += NSApp.windows.contains { $0.isVisible && String(describing: type(of: $0)).contains("Suggestions") } + ? " +SUGGESTIONS WINDOW VISIBLE" + : "" + guard state != lastState else { return } + lastState = state + lines.append(String(format: "t=%.3f key=%d %@", now, sheet.isKeyWindow ? 1 : 0, state)) + } + + private static func finish() { + let seed = ProcessInfo.processInfo.environment["PROTO_SEED"] != nil + let path = "/tmp/sheet_focus_\(Variant.current.rawValue)\(seed ? "_seed" : "").log" + var text = "variant=\(Variant.current.rawValue) seed=\(seed)\n" + // The verdict is only as good as its preconditions: a run whose sheet never became key, or + // whose user-focus step failed, would print the green string for a BROKEN rider. + let sawKey = lines.contains { $0.contains("key=1") } + let userFocusLanded = lines.contains { $0.contains("Summary editor -> yes") } + guard sawKey, userFocusLanded else { + text += "PROBE INVALID (not a verdict): the sheet never became key (\(sawKey)) or the user focus failed (\(userFocusLanded))\n" + text += lines.joined(separator: "\n") + try? text.write(toFile: path, atomically: true, encoding: .utf8) + exit(2) + } + let sheet = NSApp.windows.first { $0.isSheet } + let focused = lines.contains { $0.contains("FIELD EDITOR") || $0.contains("SUGGESTIONS") } + let editor = sheet?.firstResponder as? NSTextView + let final = editor.map { $0.isFieldEditor ? "Categories FIELD EDITOR" : "Summary TEXT VIEW" } + ?? (sheet?.firstResponder === sheet ? "WINDOW (nothing focused)" : "other") + let verdict = focused ? "Categories field auto-focused / menu shown" : "Categories field never focused, no menu" + text += "verdict: \(verdict) · after the re-key, first responder = \(final)\n" + text += lines.joined(separator: "\n") + try? text.write(toFile: path, atomically: true, encoding: .utf8) + exit(0) + } +} + +extension NSView { + /// The first descendant view of a type satisfying `where` (depth-first). + func firstDescendant(of type: T.Type, where predicate: (T) -> Bool) -> T? { + for child in subviews { + if let match = child as? T, predicate(match) { + return match + } + if let match = child.firstDescendant(of: type, where: predicate) { + return match + } + } + return nil + } +}