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.
271 lines
10 KiB
Swift
271 lines
10 KiB
Swift
// 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=<plain|defaultFalse|defaultNil|rider>` (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_<variant>[_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<T: NSView>(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
|
|
}
|
|
}
|