shutdown() flushed both sessions best-effort and ignored the results — quitting with an unanswered #67 conflict wrote local text over the foreign disk body (flush() holds for conflicts only in the debounce), and a failed quit-time flush silently dropped the only copy of the edits. Quit now routes through the same departure gate as navigation: documentsMayDepart runs both sessions through sessionMayDepart, and the failed-flush-at-quit posture is BLOCK QUIT — applicationShouldTerminate (quitReply(posts:), before the Cold Turkey ask) refuses termination with one spoken reason via a hosted-guarded alert. PostsModel.active (weak, registered by AppGateState.init — the WritingLockState.active precedent) is the delegate's reachability. Finish-audit fixes folded in: sessionMayDepart refuses a never-loaded session's retyped words (its flush is a vacuous success — the same gap closed for navigation); shutdown stays void (no production reader of a Bool). +5 pins (conflict hold, clean flush, guest flush, never-loaded refusal, delegate refusal incl. chmod-injected flush failure), all flip-verified. Rail 708/708; format+lint clean. Closes #200
304 lines
12 KiB
Swift
304 lines
12 KiB
Swift
//
|
||
// WritingLockTests.swift
|
||
// MuseionTests
|
||
//
|
||
// #162 (Cold Turkey S2, map #158): the writing lock's machine + contract
|
||
// facts. Scenario: arm the state machine over small bodies with injected
|
||
// clocks and drive the decisive ticks by hand (the 1 s ticker's real-now
|
||
// ticks can never fire first — deadlines are minutes out); the arm
|
||
// scales, readout shapes, kiosk recipe, and the canArm mirror of the
|
||
// editor branch are pinned against the #160 contract render and the
|
||
// #159 factsheet. Kiosk calls no-op under hosted tests by construction.
|
||
//
|
||
|
||
import AppKit
|
||
@testable import Museion
|
||
import Testing
|
||
|
||
@Suite("WritingLockTests")
|
||
struct WritingLockTests {
|
||
// MARK: - Machine
|
||
|
||
@Test @MainActor
|
||
func `a words block completes on the tick after the target lands`() {
|
||
let lock = WritingLockState()
|
||
let arm = Date()
|
||
lock.start(goal: .words(2), body: "one two", at: arm, spawnsTicker: false)
|
||
#expect(lock.isLocked)
|
||
#expect(lock.run?.baselineWords == 2)
|
||
#expect(!lock.showsArmBar) // Start consumed the bar
|
||
|
||
lock.feed(text: "one two three four") // net +2 — met
|
||
lock.tick(at: arm.addingTimeInterval(842))
|
||
#expect(!lock.isLocked)
|
||
#expect(lock.run == nil)
|
||
#expect(lock.completionNote == "2 words · 14:02")
|
||
}
|
||
|
||
@Test @MainActor
|
||
func `a minutes block completes exactly on the deadline tick and not a second early`() {
|
||
let lock = WritingLockState()
|
||
let arm = Date()
|
||
lock.start(goal: .minutes(30), body: "", at: arm, spawnsTicker: false)
|
||
lock.tick(at: arm.addingTimeInterval(1799))
|
||
#expect(lock.isLocked)
|
||
lock.tick(at: arm.addingTimeInterval(1800)) // inclusive boundary
|
||
#expect(!lock.isLocked)
|
||
#expect(lock.completionNote == "30 min · 30:00")
|
||
}
|
||
|
||
@Test @MainActor
|
||
func `deleting below baseline keeps the hold — the count is net`() {
|
||
let lock = WritingLockState()
|
||
let arm = Date()
|
||
lock.start(goal: .words(5), body: "one two", at: arm, spawnsTicker: false)
|
||
lock.feed(text: "one") // net −1
|
||
lock.tick(at: arm.addingTimeInterval(10))
|
||
#expect(lock.isLocked) // deleting costs — no completion
|
||
lock.feed(text: "one two three four five six seven eight")
|
||
lock.tick(at: arm.addingTimeInterval(11))
|
||
#expect(!lock.isLocked)
|
||
}
|
||
|
||
@Test @MainActor
|
||
func `a second start while locked is refused`() {
|
||
let lock = WritingLockState()
|
||
let arm = Date()
|
||
lock.start(goal: .words(10), body: "seed", at: arm, spawnsTicker: false)
|
||
lock.start(goal: .minutes(180), body: "seed", at: arm.addingTimeInterval(99), spawnsTicker: false)
|
||
#expect(lock.isLocked)
|
||
#expect(lock.run?.goal == .words(10))
|
||
#expect(lock.run?.armedAt == arm) // one block per moment — unchanged
|
||
}
|
||
|
||
@Test @MainActor
|
||
func `feed and tick at rest are no-ops`() {
|
||
let lock = WritingLockState()
|
||
lock.feed(text: "anything")
|
||
lock.tick(at: Date())
|
||
#expect(!lock.isLocked)
|
||
#expect(lock.run == nil)
|
||
#expect(lock.completionNote == nil)
|
||
}
|
||
|
||
// MARK: - Readout + note formatting (#160 contract)
|
||
|
||
@Test @MainActor
|
||
func `readout shapes the words net and the minutes countdown`() {
|
||
let arm = Date(timeIntervalSince1970: 1_000_000)
|
||
var words = WritingGoalRun(goal: .words(500), armedAt: arm, body: "one two")
|
||
#expect(WritingLockState.readout(words, now: arm).numerals == "0 / 500")
|
||
#expect(WritingLockState.readout(words, now: arm).unit == "words")
|
||
words.update(text: String(repeating: "word ", count: 212) + "one two")
|
||
#expect(WritingLockState.readout(words, now: arm).numerals == "212 / 500")
|
||
|
||
let minutes = WritingGoalRun(goal: .minutes(30), armedAt: arm, body: "")
|
||
let shape = WritingLockState.readout(minutes, now: arm.addingTimeInterval(30 * 60 - 807))
|
||
#expect(shape.numerals == "13:27")
|
||
#expect(shape.unit == "left")
|
||
}
|
||
|
||
@Test
|
||
func `clock spans minutes and hours`() {
|
||
#expect(WritingLockState.clockString(seconds: 0) == "00:00")
|
||
#expect(WritingLockState.clockString(seconds: 59) == "00:59")
|
||
#expect(WritingLockState.clockString(seconds: 60) == "01:00")
|
||
#expect(WritingLockState.clockString(seconds: 842) == "14:02")
|
||
#expect(WritingLockState.clockString(seconds: 3600) == "1:00:00")
|
||
#expect(WritingLockState.clockString(seconds: 3722) == "1:02:02")
|
||
}
|
||
|
||
@Test
|
||
func `near-goal fires inside the last twenty percent`() {
|
||
#expect(!WritingLockState.isNearGoal(progress: 0.79))
|
||
#expect(WritingLockState.isNearGoal(progress: 0.8))
|
||
#expect(WritingLockState.isNearGoal(progress: 1))
|
||
#expect(!WritingLockState.isNearGoal(progress: 0))
|
||
}
|
||
|
||
@Test
|
||
func `completion note names the goal and the elapsed`() {
|
||
#expect(WritingLockState.completionNoteText(goal: .words(500), elapsed: 842) == "500 words · 14:02")
|
||
#expect(WritingLockState.completionNoteText(goal: .minutes(30), elapsed: 1800) == "30 min · 30:00")
|
||
}
|
||
|
||
// MARK: - Kiosk recipe + arm scales (#159 factsheet, #160 render)
|
||
|
||
@Test
|
||
func `kiosk options are the factsheet recipe plus the corner switch`() {
|
||
#expect(WritingLockKiosk.lockOptions == [
|
||
.hideDock,
|
||
.hideMenuBar,
|
||
.disableProcessSwitching,
|
||
.disableForceQuit,
|
||
.disableSessionTermination,
|
||
.disableHideApplication,
|
||
.disableScreenCornerInteractions,
|
||
])
|
||
}
|
||
|
||
@Test
|
||
func `arm scales carry the render's defaults ranges and clamps`() {
|
||
let words = WritingLockState.ArmScale.words
|
||
#expect(words.defaultValue == 250) // 2026-11-04 amendment: 250 words / 5 min
|
||
#expect(words.step == 50)
|
||
#expect(words.range == 1 ... 1000) // what's typed is what arms (2026-11-04 amendment)
|
||
#expect(words.clamp(0) == 1)
|
||
#expect(words.clamp(10) == 10) // the dogfood case — 10 words STAYS 10
|
||
#expect(words.clamp(1001) == 1000)
|
||
|
||
let minutes = WritingLockState.ArmScale.minutes
|
||
#expect(minutes.defaultValue == 5)
|
||
#expect(minutes.step == 5)
|
||
#expect(minutes.range == 1 ... 60)
|
||
#expect(minutes.clamp(0) == 1)
|
||
#expect(minutes.clamp(61) == 60)
|
||
}
|
||
|
||
// MARK: - The canArm mirror (PostsModel)
|
||
|
||
@Test @MainActor
|
||
func `canArmWritingLock gates on the open surface`() async throws {
|
||
let (model, home) = try makeModelHome()
|
||
#expect(!model.canArmWritingLock) // nothing open
|
||
|
||
model.newPost() // prose draft
|
||
#expect(model.canArmWritingLock)
|
||
|
||
model.newOutline() // outline draft replaces it
|
||
#expect(!model.canArmWritingLock)
|
||
|
||
// A prose piece on disk, opened as a session (wait for the scan so
|
||
// the outline routing reads the real type, not the lagging list).
|
||
let post = try PostStore.writeNew(body: "# Prose piece\n\nBody words.\n", home: home)
|
||
try await Self.waitForScan(model, id: post.id)
|
||
model.select(post.id)
|
||
#expect(model.canArmWritingLock)
|
||
#expect(model.editorBodyText == "# Prose piece\n\nBody words.\n")
|
||
|
||
let outline = try PostStore.writeNew(body: "- an outline\n", project: "posts", type: .outline, home: home)
|
||
try await Self.waitForScan(model, id: outline.id)
|
||
model.select(outline.id)
|
||
#expect(!model.canArmWritingLock)
|
||
|
||
// A MIXED outline fires the #111 guard ask instead — the held
|
||
// guard (no session, empty editor) must disarm too: the editor
|
||
// branch's fourth path, pinned so the mirror can't drift.
|
||
let mixed = try PostStore.writeNew(body: "- bullet\nprose between bullets\n", project: "posts", type: .outline, home: home)
|
||
try await Self.waitForScan(model, id: mixed.id)
|
||
model.select(mixed.id)
|
||
#expect(model.outlineGuardPieceID == mixed.id)
|
||
#expect(!model.canArmWritingLock)
|
||
}
|
||
|
||
@Test @MainActor
|
||
func `the external guest can arm and carries its live text`() throws {
|
||
let (model, _) = try makeModelHome()
|
||
let url = FileManager.default.temporaryDirectory
|
||
.appendingPathComponent("guest-\(UUID().uuidString).md", isDirectory: false)
|
||
try "# Guest words\n".write(to: url, atomically: true, encoding: .utf8)
|
||
model.openExternal(url)
|
||
#expect(model.canArmWritingLock)
|
||
#expect(model.editorBodyText == "# Guest words\n")
|
||
}
|
||
|
||
// MARK: - The lock ⇒ focus invariant (AppGateState)
|
||
|
||
@Test @MainActor
|
||
func `startWritingLock forces focus and runs the block over the open draft`() {
|
||
let gate = AppGateState()
|
||
gate.posts.newPost()
|
||
gate.posts.draft?.text = "seed words here"
|
||
#expect(!gate.isFocused)
|
||
gate.startWritingLock(goal: .words(2))
|
||
#expect(gate.isFocused) // the invariant, settled at start
|
||
#expect(gate.writingLock.isLocked)
|
||
gate.writingLock.feed(text: "seed words here plus two more")
|
||
gate.writingLock.tick()
|
||
#expect(!gate.writingLock.isLocked)
|
||
}
|
||
|
||
@Test
|
||
func `the refusal key set matches key codes with the exact modifiers`() {
|
||
// keyCode net: physical key, layout- and case-independent.
|
||
#expect(WritingLockKiosk.refusesKey(keyCode: 13, characters: nil, modifiers: [.command]))
|
||
#expect(WritingLockKiosk.refusesKey(keyCode: 3, characters: nil, modifiers: [.command, .control]))
|
||
#expect(WritingLockKiosk.refusesKey(keyCode: 45, characters: nil, modifiers: [.command]))
|
||
// character net: Caps-Lock case and plain text both match.
|
||
#expect(WritingLockKiosk.refusesKey(keyCode: 0, characters: "W", modifiers: [.command]))
|
||
#expect(WritingLockKiosk.refusesKey(keyCode: 0, characters: "f", modifiers: [.command, .control]))
|
||
// near misses stay live: extra modifiers, wrong keys, bare letters.
|
||
#expect(!WritingLockKiosk.refusesKey(keyCode: 13, characters: nil, modifiers: [.command, .option]))
|
||
#expect(!WritingLockKiosk.refusesKey(keyCode: 3, characters: nil, modifiers: [.command]))
|
||
#expect(!WritingLockKiosk.refusesKey(keyCode: 0, characters: "w", modifiers: []))
|
||
#expect(!WritingLockKiosk.refusesKey(keyCode: 0, characters: "q", modifiers: [.command]))
|
||
}
|
||
|
||
@Test
|
||
func `arm parse falls to the default on garbage and overflow`() {
|
||
let words = WritingLockState.ArmScale.words
|
||
#expect(words.parse("10") == 10)
|
||
#expect(words.parse("") == 250)
|
||
#expect(words.parse("abc") == 250)
|
||
#expect(words.parse("999999999999999999999999999999") == 250) // Int(String) nil on overflow, never traps
|
||
#expect(words.parse("1001") == 1000)
|
||
#expect(WritingLockState.ArmScale.minutes.parse("7") == 7)
|
||
}
|
||
|
||
@Test @MainActor
|
||
func `the quit delegate passes an unlocked app straight through`() {
|
||
// The locked branch is a modal ask — unpinnable headless; the
|
||
// unlocked path is the seam this pins.
|
||
let delegate = WritingLockAppDelegate()
|
||
#expect(delegate.applicationShouldTerminate(NSApplication.shared) == .terminateNow)
|
||
}
|
||
|
||
// MARK: - #200: the quit-time departure gate
|
||
|
||
@Test @MainActor
|
||
func `quit refuses while an open piece cannot depart and proceeds once it can`() throws {
|
||
// The failed-flush-at-quit posture, pinned: block quit (this
|
||
// delegate's own refusal precedent) — never silently drop the
|
||
// only copy of the edits. quitReply is the pure decision seam;
|
||
// the refusal ALERT itself is hosted-guarded like the kiosk.
|
||
let delegate = WritingLockAppDelegate()
|
||
|
||
// No model alive → nothing open, nothing to lose.
|
||
#expect(delegate.quitReply(posts: nil) == .terminateNow)
|
||
|
||
// A dirty-but-clean-writable session departs: quit proceeds and
|
||
// the flush lands.
|
||
let (model, home) = try makeModelHome()
|
||
let post = try PostStore.writeNew(body: "# A\n", home: home)
|
||
model.select(post.id)
|
||
model.session?.edit("# A\n\nlast words before quitting")
|
||
#expect(delegate.quitReply(posts: model) == .terminateNow)
|
||
#expect(PostStore.readBody(id: post.id, home: home) == "# A\n\nlast words before quitting")
|
||
|
||
// An unanswered #67 conflict refuses termination — the foreign
|
||
// disk body must survive the quit attempt.
|
||
try PostStore.overwrite(id: post.id, body: "foreign body from disk", home: home)
|
||
model.session?.diskDidChange(diskText: "foreign body from disk")
|
||
#expect(delegate.quitReply(posts: model) == .terminateCancel)
|
||
#expect(PostStore.readBody(id: post.id, home: home) == "foreign body from disk")
|
||
|
||
// A failed flush refuses termination too — the pinned posture.
|
||
model.session?.keepLocal() // #67 No: the writer keeps their words
|
||
let pieceDir = try #require(PostStore.folder(of: post.id, home: home))
|
||
try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: pieceDir.path)
|
||
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: pieceDir.path) }
|
||
#expect(delegate.quitReply(posts: model) == .terminateCancel)
|
||
#expect(model.lastError != nil)
|
||
}
|
||
|
||
/// Bounded poll for the watched scan to surface a piece (the
|
||
/// PostsModelTests poll pattern — the FSEvents latency window).
|
||
@MainActor
|
||
private static func waitForScan(_ model: PostsModel, id: String) async throws {
|
||
for _ in 0 ..< 200 where !model.posts.contains(where: { $0.id == id }) {
|
||
try await Task.sleep(for: .milliseconds(10))
|
||
}
|
||
#expect(model.posts.contains(where: { $0.id == id }))
|
||
}
|
||
}
|