Files
museion/Museion/WritingLockState.swift
T
AlexKucera a9e199fce4
CI / ci (push) Canceled after 0s
feat(cold-turkey): the writing lock (#162)
Wires #161's goal engine and #160's contract into the app: armed
from a corner dot or View ▸ Start Cold Turkey…, enforced by the
macOS app-kiosk (7-option presentation combo + fullscreen, restored
on completion), readout with hairline + near-goal terracotta, and
a completion note fading back into focus. While held: focus exit,
reading, new buffers, ⌘W/⌃⌘F/⌘N refused (key-code-matched monitor
— character matching is layout/Caps-blind; no .closeItem placement
exists), ⌘Q asks once per #163's ruling. Typing continuity holds by
construction — lock ⇒ focus freezes the branch under the editor and
chrome mounts as overlays only. Arm values type directly (1…1000
words / 1…60 min, defaults 250/5). Nothing persists.

Wayfinder map #158 Build S2; suite 620, flip-verified pins.
2026-11-04 15:58:47 +01:00

346 lines
14 KiB
Swift

//
// WritingLockState.swift
// Museion
//
// #162 (Cold Turkey S2, map #158): the writing lock's state machine —
// arms from the quiet arm-bar, holds while the goal engine runs, and
// completes quietly back into focus. The kiosk recipe, the quit
// refusal, and the readout formatting live here; the chrome views
// grow FocusChrome.swift (one chrome lineage, #158 settle 6).
//
import AppKit
import SwiftUI
/// #162: the Cold Turkey lock machine. One block per launch moment:
/// `start` arms from the focus-mode arm-bar, the ticker asks the goal
/// engine (`WritingGoalRun`, #161) whether the block is met on every
/// 1 s tick plus every keystroke feed, and `complete` exits the kiosk
/// and leaves the completion note fading on the focus ground. Nothing
/// persists — the block dies quietly with the process (#158 settle 3).
@Observable
final class WritingLockState {
/// The process's one lock (AppGateState owns it). The app delegate's
/// quit refusal reads it — AppKit asks before SwiftUI state is handy.
weak static var active: WritingLockState?
/// The armed block while locked; nil at rest.
private(set) var run: WritingGoalRun?
/// True while the block holds: focus exit refused (the refusal IS the
/// lock), hover-reveal zones suppressed, kiosk options set.
private(set) var isLocked = false
/// The readout clock — bumped by the ticker each second so a minutes
/// countdown renders without a UI-owned timer.
private(set) var now = Date()
/// #160 contract: the completion note on quiet return to focus,
/// bare mono in the readout's seat, fading after ~6 s.
private(set) var completionNote: String?
/// The arm-bar's presentation flag — the corner dot and the View ▸
/// Start Cold Turkey… item both set it; Esc dismisses; `start`
/// consumes it (#160: dot-first, menu second).
var showsArmBar = false
private var ticker: Task<Void, Never>?
private var noteFade: Task<Void, Never>?
/// Whether the lock itself toggled fullscreen at entry (an already-
/// fullscreen window is left alone — exit only toggles back what
/// entry toggled).
private var enteredFullscreen = false
init() {
Self.active = self
}
/// Arm the block. Focus is forced by the caller (AppGateState —
/// lock ⇒ focus is the invariant, #158 settle 6); `at` is injectable
/// so tests drive deterministic deadlines. `spawnsTicker` lets the
/// machine tests opt out of the real 1 s ticker (audit 2026-11-04:
/// a >1 s main-actor stall let the live ticker complete a met words
/// goal before the injected tick, flipping the note pin — the repo's
/// own #30/#147 flake family).
func start(goal: WritingGoal, body: String, at armedAt: Date = Date(), spawnsTicker: Bool = true) {
guard !isLocked else { return }
run = WritingGoalRun(goal: goal, armedAt: armedAt, body: body)
now = armedAt
isLocked = true
showsArmBar = false
enteredFullscreen = WritingLockKiosk.enter()
guard spawnsTicker else { return }
ticker = Task { [weak self] in
while true {
try? await Task.sleep(for: .seconds(1))
guard let self, !Task.isCancelled, isLocked else { return }
tick()
}
}
}
/// The per-keystroke feed: whole-document text from the live editor
/// surface (#161's `update(text:)` contract — typing, deleting,
/// pasting, undo all land the same way). No-op at rest.
func feed(text: String) {
run?.update(text: text)
}
/// One heartbeat: record `now`, ask the engine, complete on the
/// first met tick. Internal seam — the ticker drives it with the
/// real clock, tests inject the decisive moments.
func tick(at date: Date = Date()) {
guard isLocked, let armed = run else { return }
now = date
if armed.isMet(now: date) {
complete()
}
}
/// Quiet return to focus: kiosk off, block cleared, note left in the
/// readout's seat. Typing is never touched — the fullscreen round
/// trip preserves the first responder (#159 probe), and the editor
/// column's identity is unchanged by design.
private func complete() {
guard let armed = run else { return }
ticker?.cancel()
ticker = nil
WritingLockKiosk.exit(toggledFullscreen: enteredFullscreen)
enteredFullscreen = false
isLocked = false
run = nil
completionNote = Self.completionNoteText(
goal: armed.goal,
elapsed: now.timeIntervalSince(armed.armedAt),
)
noteFade?.cancel()
noteFade = Task { [weak self] in
try? await Task.sleep(for: .seconds(6))
guard let self, !Task.isCancelled else { return }
// Plain assignment — the seat's value-scoped animation owns
// both fade directions with one curve (audit: a withAnimation
// here ran a SECOND, different curve over the same flip).
completionNote = nil
}
}
// MARK: - Readout formatting (#160 contract: numerals + unit + hairline)
nonisolated struct ArmScale {
/// Amended 2026-11-04 (live dogfood): defaults 250 words / 5 min;
/// ranges widened DOWN and capped — what the writer types is what
/// arms (a 10-word sprint is legal), the ceilings are 1000 words /
/// 60 min. Floor 1: a zero/empty entry falls back to the default,
/// never an already-met block.
static let words = ArmScale(defaultValue: 250, step: 50, range: 1 ... 1000)
static let minutes = ArmScale(defaultValue: 5, step: 5, range: 1 ... 60)
let defaultValue: Int
let step: Int
let range: ClosedRange<Int>
func clamp(_ value: Int) -> Int {
min(max(value, range.lowerBound), range.upperBound)
}
/// The arm-bar's read pipeline: typed text → Int, empty/garbage/
/// overflow falling to the default (Swift's failable `Int(String)`
/// returns nil on a 30-digit string — never traps), clamped to
/// the range. Extracted pure so the fallback cases pin.
func parse(_ text: String) -> Int {
clamp(Int(text) ?? defaultValue)
}
}
/// The readout's numerals + trailing unit. Words: live net over
/// target. Minutes: the countdown, never paused (#158 settle 4).
nonisolated static func readout(_ run: WritingGoalRun, now: Date) -> (numerals: String, unit: String) {
switch run.goal {
case let .words(target):
return ("\(run.netNewWords) / \(target)", "words")
case .minutes:
let seconds = run.secondsRemaining(now: now) ?? 0
return (clockString(seconds: seconds), "left")
}
}
/// Near-goal: terracotta numerals inside the last 20 % (#160 ruling 4).
nonisolated static func isNearGoal(progress: Double) -> Bool {
progress >= 0.8
}
/// The completion note's text: `● 500 words · 14:02` shape (the dot
/// and the uppercase are the view's; the string stays lowercase).
nonisolated static func completionNoteText(goal: WritingGoal, elapsed: TimeInterval) -> String {
let clock = clockString(seconds: max(0, Int(elapsed.rounded())))
switch goal {
case let .words(target):
return "\(target) words · \(clock)"
case let .minutes(total):
return "\(total) min · \(clock)"
}
}
/// mm:ss under an hour, h:mm:ss above (the 180-min ceiling needs it).
nonisolated static func clockString(seconds: Int) -> String {
let total = max(0, seconds)
let hours = total / 3600
let minutes = (total % 3600) / 60
let secs = total % 60
if hours > 0 {
return String(format: "%d:%02d:%02d", hours, minutes, secs)
}
return String(format: "%02d:%02d", minutes, secs)
}
}
/// #159 factsheet recipe, verbatim: the six-option kiosk combo plus the
/// macOS 27 hot-corner kill switch (`.disableScreenCornerInteractions`,
/// deployment target 27 — no availability dance). Build the option set
/// ONLY from this validated recipe; an invalid combo is an ObjC
/// exception, i.e. a crash, not a degradation.
@MainActor
enum WritingLockKiosk {
/// The recipe is data — nonisolated so any context can pin it.
nonisolated static let lockOptions: NSApplication.PresentationOptions = [
.hideDock, // rider bit — enables the rest
.hideMenuBar, // requires .hideDock (never the autoHide pair for a lock)
.disableProcessSwitching, // ⌘Tab / Mission Control / Spaces / App Exposé
.disableForceQuit, // ⌥⌘⎋ panel
.disableSessionTermination, // Restart / Shut Down / Log Out / power-key panel
.disableHideApplication, // ⌘H fires even with the menu bar hidden
.disableScreenCornerInteractions, // macOS 27: the official Hot Corners switch
]
/// Hosted tests run in this app — never kiosk the test machine
/// (the panes' XCTest guard pattern).
@MainActor
static var hostedTests: Bool {
ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil
}
/// Options before the toggle (invalid combos throw; ordering per the
/// probe: set-then-toggle is the clean order). Returns whether WE
/// toggled fullscreen — an already-fullscreen window is entered in
/// place, and exit only replays what entry toggled (#158 settle 9:
/// completion restores the previous window size, which the native
/// fullscreen round trip does by itself).
static func enter() -> Bool {
guard !hostedTests else { return false }
installRefusalMonitor()
NSApp.activate(ignoringOtherApps: true) // options take effect only while frontmost
NSApp.presentationOptions = lockOptions
let window = NSApp.keyWindow
lockedWindow = window
let alreadyFullscreen = window?.styleMask.contains(.fullScreen) ?? true
if !alreadyFullscreen {
window?.toggleFullScreen(nil)
}
return !alreadyFullscreen
}
/// Clear options FIRST, then the fullscreen toggle back — never churn
/// options mid-transition (the probe's D1/D3 anomaly). On macOS 27
/// the exit auto-clears anyway; the explicit clear is the 26.x belt.
/// The window ENTERED is the window EXITED (audit 2026-11-04: reading
/// the key window at exit could un-fullscreen the wrong window if
/// focus moved mid-block).
static func exit(toggledFullscreen: Bool) {
guard !hostedTests else { return }
removeRefusalMonitor()
NSApp.presentationOptions = []
let window = lockedWindow ?? NSApp.keyWindow
lockedWindow = nil
if toggledFullscreen {
window?.toggleFullScreen(nil)
}
}
/// The window the block entered (cleared at exit) — see `exit`.
static var lockedWindow: NSWindow?
/// #159's `windowShouldClose` refusal, expressed where SwiftUI allows
/// it: the stock Close item has no `CommandGroupPlacement` to replace
/// and SwiftUI owns the window delegate, so while a block holds the
/// local key monitor swallows ⌘W (close) and ⌃⌘F (the system
/// fullscreen toggle) — the OutlineDrag monitor pattern, running
/// before menu key equivalents resolve. ⌃⌘F matters because the
/// kiosk options hold even windowed (the #159 probe's own finding):
/// without this swallow the writer can toggle fullscreen off
/// mid-block, "escape" the lock's looks while it still holds, and
/// land in a windowed kiosk with no menu bar and quit refused — the
/// 2026-11-04 dogfood trap. Fullscreen now leaves ONLY via
/// completion. Quiet by design: nil, no beep, no dialog.
static var refusalMonitor: Any?
/// The refusal key set, matched the way AppKit's menu machinery
/// matches key equivalents: by KEY CODE (physical, layout- and
/// case-independent) with the exact modifier set, plus the
/// lowercased character as a second net. Audit 2026-11-04:
/// `charactersIgnoringModifiers == "w"` is layout- and Caps-Lock
/// dependent — a Cyrillic ⌘W or a caps-on "W" slipped past while the
/// stock Close still fired, wedging a windowless kiosk. 13 =
/// kVK_ANSI_W (⌘W close), 3 = kVK_ANSI_F (⌃⌘F fullscreen), 45 =
/// kVK_ANSI_N (⌘N — the stock File ▸ New Window item SwiftUI owns
/// stays enabled mid-lock; a second window would strand the count).
nonisolated static func refusesKey(keyCode: UInt16, characters: String?, modifiers: NSEvent.ModifierFlags) -> Bool {
let exact = modifiers.intersection([.command, .control, .option, .shift])
let key = characters?.lowercased()
if exact == [.command], keyCode == 13 || key == "w" {
return true
}
if exact == [.command, .control], keyCode == 3 || key == "f" {
return true
}
if exact == [.command], keyCode == 45 || key == "n" {
return true
}
return false
}
private static func installRefusalMonitor() {
guard refusalMonitor == nil else { return }
refusalMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
if WritingLockState.active?.isLocked == true,
Self.refusesKey(keyCode: event.keyCode, characters: event.charactersIgnoringModifiers, modifiers: event.modifierFlags)
{
return nil // swallowed — the lock holds
}
return event
}
}
private static func removeRefusalMonitor() {
if let refusalMonitor {
NSEvent.removeMonitor(refusalMonitor)
}
refusalMonitor = nil
}
}
/// #162: quit mid-block asks once — #163's ruling (2026-11-04, live
/// dogfood): self-aware friction, not silence. Every quit path (⌘Q, the
/// Quit menu, AppleEvents) routes through `applicationShouldTerminate`;
/// unlocked quits proceed, a held block gets ONE modal ask — walk away
/// (the block dies quietly with the process, nothing kept — #158 settle
/// 3) or keep writing.
@MainActor
final class WritingLockAppDelegate: NSObject, NSApplicationDelegate {
func applicationShouldTerminate(_: NSApplication) -> NSApplication.TerminateReply {
guard WritingLockState.active?.isLocked == true else { return .terminateNow }
let alert = NSAlert()
alert.messageText = "Walk away from the block?"
alert.informativeText = "A Cold Turkey block is still running. Quitting ends it — nothing is kept, no record."
alert.addButton(withTitle: "Walk Away")
alert.addButton(withTitle: "Keep Writing")
let walkAway = alert.runModal() == .alertFirstButtonReturn
if walkAway {
// Belt: the process is about to die; clear the kiosk + monitor
// so nothing lingers through the termination dance.
WritingLockKiosk.exit(toggledFullscreen: false)
return .terminateNow
}
return .terminateCancel
}
}