Files
museion/Museion/MuseionApp.swift
T
AlexKucera 2334afc392 fix(editor): quit rides the departure gate
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
2026-11-19 13:18:19 +01:00

404 lines
15 KiB
Swift

//
// MuseionApp.swift
// Museion
//
// Created by Alexander Kucera on 26.08.26.
//
import AppKit
import SwiftUI
/// App-scoped state. #151: gateless — every launch runs the engine check
/// async beside the workspace (`startLaunchCheck` from ContentView.task);
/// provisioning + backup auto-fire on pass. Nothing blocks; the rail pill
/// and mentor header surface the states. The model is shared so ⌘N during
/// a check can't start a second concurrent one (ticket #41's rule).
@MainActor
@Observable
final class AppGateState {
/// #141: the live prose text view — the window-level drop destination
/// (the ONLY destination that ever fires; nested editor-level SwiftUI
/// targets are never consulted, and AppKit views registered for file
/// drags are starved by it — field-verified 2026-11-02) routes image
/// drops to the editor through this handle.
let proseDrop = ProseDropBridge()
let gateModel = EngineGateModel()
let provisioning = ProvisioningModel()
/// #50: daily backup pass, sequenced after provisioning finishes.
let backup = BackupModel()
/// #14: the app-scoped mentor bridge — the pane renders it; quit tears it down.
let mentor = MentorSessionModel()
/// #18: the app-scoped Posts state — FSEvents watcher + lifecycle ops.
let posts = PostsModel()
/// #77 (Neo triage input): spellcheck posture — off by default, on when
/// asked via Edit ▸ Check Spelling While Typing. Per-launch only, no
/// persistence; markdown on disk already carries the spelling.
var spellChecking = false
/// #21 (map #21): focus mode — transient like reading (#68), per-launch
/// only, no persistence; a fresh open lands unfocused. Recesses the
/// rail/library/mentor and the editor toolbar; overlay panes return on
/// edge hover.
var isFocused = false
/// #162 (Cold Turkey S2, map #158): the writing lock — armed from the
/// focus-mode arm-bar, held while the goal runs. Lock ⇒ focus: while
/// locked, `isFocused` cannot leave true (the ⌥⌘F refusal IS the
/// lock), hover-reveal zones stay suppressed, and the kiosk holds.
let writingLock = WritingLockState()
/// #17: the Museion Home — repoint-only (ADR-0004). #171: fresh installs
/// resolve once through the ladder below and PIN the winner (UserDefaults
/// is the persistence floor: a Home is a plain folder, nothing
/// app-owned to put in a database). Non-file URLs read back as nil (the
/// ladder wins) — the Home is always a folder.
var museionHome: URL {
didSet { Self.storeHome(museionHome, in: UserDefaults.standard) }
}
/// #171: fresh-install Home resolution — runs only when no stored
/// override exists, then pins so the Home never silently moves (the
/// ladder + probes live in HomeResolution.swift). Probes and defaults
/// are injectable: hosted tests drive the ladder without touching the
/// machine's real iCloud state or the runner's real defaults.
/// `defaults` serves resolution + pin only — the repoint `didSet`
/// always writes the real standard defaults.
init(
defaults: UserDefaults = .standard,
legacyHomeExists: () -> Bool = { AppGateState.existingDirectory(AppGateState.defaultMuseionHome) != nil },
cloudDocsDir: () -> URL? = AppGateState.liveCloudDocsDir,
) {
// Explicit init: `Self` in a stored-property initializer trips
// @ObservationTracked's macro expansion (covariant Self).
// #200: the app delegate's quit gate reaches the one posts model
// (the WritingLockState.active precedent).
PostsModel.active = posts
if let stored = Self.fileHomeURL(in: defaults) {
museionHome = stored
return
}
// Default construction under hosted tests (WritingLockTests &
// friends): skip the real probes and the pin alike.
if Self.hostedTestRun, defaults === UserDefaults.standard {
museionHome = Self.defaultMuseionHome
return
}
let resolved = Self.resolvedInitialHome(legacyHomeExists: legacyHomeExists, cloudDocsDir: cloudDocsDir)
museionHome = resolved
Self.storeHome(resolved, in: defaults)
}
/// #151: the gateless launch check — arms the auto-fire chain, then
/// runs the once-per-launch async check (`beginAutomaticCheck`'s
/// `hasStarted` preserves #41's one-check-per-launch, first-window-only
/// rule; ⌘N re-entry no-ops). Called from `ContentView.task`.
func startLaunchCheck() async {
// Hosted unit tests run this app as their runner — the panes'
// guard pattern: never probe or auto-provision there.
guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return }
wireAutoFire()
await gateModel.beginAutomaticCheck()
}
/// #162: Start Cold Turkey — the arm-bar's single commit. The lock ⇒
/// focus invariant is settled here (arming is focus-gated anyway;
/// this is the belt), and the baseline body is the live editor text.
func startWritingLock(goal: WritingGoal) {
guard !writingLock.isLocked else { return }
isFocused = true
writingLock.start(goal: goal, body: posts.editorBodyText ?? "")
}
/// The auto-fire chain — the exact onEnginePass body from the gate era,
/// moved verbatim: provisioning (#47, idempotent — re-fires per passing
/// Re-check are no-ops), then the daily backup (#50 — a failed
/// provision doesn't skip it).
func wireAutoFire() {
gateModel.onPass = { [gateModel, provisioning, backup] in
Task {
await provisioning.runPass(hermesBinary: gateModel.currentBinaryPath)
await backup.runPass()
}
}
}
}
/// #23: no `@main` here — MuseionLauncher (MCPServer.swift) branches
/// between the app and the headless `--serve-mcp` tool server.
struct MuseionApp: App {
@State private var gate = AppGateState()
/// #162: the quit refusal while a Cold Turkey block holds (#159
/// delegate-level coverage — every quit path routes through here).
@NSApplicationDelegateAdaptor(WritingLockAppDelegate.self) private var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
.environment(gate)
// #14: app quit tears down the engine child cleanly (map
// decision: child lifecycle). willTerminate is the real quit
// signal on macOS — scenePhase .inactive also fires on plain
// focus loss, which would kill the engine on every app switch.
.onReceive(NotificationCenter.default.publisher(for: NSApplication.willTerminateNotification)) { _ in
gate.mentor.shutdown()
gate.posts.shutdown()
}
}
Window("About \(AppMetadata.name)", id: "about") {
AboutEngineView()
}
.windowResizability(.contentSize)
// #23 follow-up (dogfood): the Fix Cards palette — a floating
// window for the open piece's stored cards, opened from the
// mentor pass bar. Stays visible while the verdict is worked
// through in the editor.
Window("Fix Cards", id: "fix-cards") {
FixCardsPalette()
.environment(gate)
}
.defaultSize(width: 340, height: 540)
.commands {
// SwiftUI has no About scene on macOS; replace the stock panel with our window.
CommandGroup(replacing: .appInfo) {
OpenAboutButton()
}
// Single-window app: `replacing` kills the stock File ▸ New
// Window item the WindowGroup owns — with `after`, its ⌘N
// fired alongside New Post's (new window AND new post).
// #91/#94: Open…/Import… ride the group — never
// CommandMenu("File"), which doubles it (#84 trap).
CommandGroup(replacing: .newItem) {
// #108/#109: New Post / New Outline / New Project… go FIRST in
// the group — the menu reads New Post / New Outline /
// New Project… / Open… / Import…
NewPostButton(gate: gate)
NewOutlineButton(gate: gate)
NewProjectButton(gate: gate)
OpenExternalButton(gate: gate)
ImportFilesButton(gate: gate)
}
// #77: spellcheck posture — Edit ▸ Check Spelling While Typing,
// default off (Neo posture: on when asked). Explicit rather than
// relying on the stock submenu's presence in a WindowGroup app.
CommandGroup(after: .textEditing) {
EditSpellingToggle(gate: gate)
}
// #84: joins the system View menu — CommandMenu("View") would add a second one beside it.
CommandGroup(after: .toolbar) {
Button("Toggle Reading Mode") {
NotificationCenter.default.post(name: .toggleReadingMode, object: nil)
}
.keyboardShortcut("r", modifiers: .command)
// #162: the editor is the only surface while locked — the
// reading swap would interrupt typing mid-block.
.disabled(gate.writingLock.isLocked)
// #21: focus mode — beside reading, same posture (system View
// menu + shortcut). Transient like reading: no persistence, no
// Esc exit (rejected at charting) — the toggle is the only way.
// ⌥⌘F — ⇧⌘F is taken by a system-wide shortcut on this machine,
// ⌃F shadows the editor's Emacs caret-forward binding.
// #162: disabled while a Cold Turkey block holds — the refusal
// IS the lock (#158 settle 6: completion drops back to focus).
FocusModeToggle(gate: gate)
.disabled(gate.writingLock.isLocked)
// #162 (#160 ruling 6): the second arming path — dot-first,
// menu second. Focus-mode-gated; nothing prose to lock or a
// block already running disables it.
Button("Start Cold Turkey…") {
gate.writingLock.showsArmBar = true
}
.disabled(!gate.isFocused || gate.writingLock.isLocked || !gate.posts.canArmWritingLock)
}
// #50: reveal the snapshots folder in Finder (restore = manual
// copy-back, documented in the bundled help doc).
CommandMenu("Help") {
OpenBackupFolderButton()
}
}
}
}
private struct OpenAboutButton: View {
@Environment(\.openWindow) private var openWindow
var body: some View {
Button("About \(AppMetadata.name)") { openWindow(id: "about") }
}
}
/// #77: the spellcheck posture toggle — binds the app-scoped bool the editor
/// surface reads on every update pass. Takes `gate` as a plain property:
/// commands views don't inherit the window environment (@Environment lookup
/// traps at launch — crash-verified), but observation tracking still works.
private struct EditSpellingToggle: View {
let gate: AppGateState
var body: some View {
Toggle("Check Spelling While Typing", isOn: Binding(
get: { gate.spellChecking },
set: { gate.spellChecking = $0 },
))
}
}
/// #21: the focus-mode toggle — plain property (commands views don't inherit
/// the window environment; observation tracking still invalidates the item).
/// Disabled with nothing open (no session, no draft) — a no-op guard.
private struct FocusModeToggle: View {
let gate: AppGateState
var body: some View {
// Entry guard: nothing open = nothing to focus on. Exit stays armed
// even then (trashing the open post while focused must not trap).
// #92: the external guest counts as open too.
let canFocus = gate.isFocused || gate.posts.session != nil || gate.posts.draft != nil
|| gate.posts.externalSession != nil
Button("Toggle Focus Mode") { gate.isFocused.toggle() }
.keyboardShortcut("f", modifiers: [.command, .option])
.disabled(!canFocus)
}
}
/// #108: File ▸ New Post (⌘N) — same draft path as the library's + button.
/// The stock New Window item is REPLACED above — ⌘N belongs to this item
/// alone (single-window app; no second Museion window).
private struct NewPostButton: View {
let gate: AppGateState
var body: some View {
Button("New Post") { gate.posts.newPost() }
.keyboardShortcut("n", modifiers: .command)
// #162: the open Piece stays stable for counting while a
// Cold Turkey block holds.
.disabled(gate.writingLock.isLocked)
}
}
/// #109: File ▸ New Outline (⇧⌘N) — newPost's draft path with an outline
/// draft (body "- ", type .outline); the outline surface parses the seed.
private struct NewOutlineButton: View {
let gate: AppGateState
var body: some View {
Button("New Outline") { gate.posts.newOutline() }
.keyboardShortcut("n", modifiers: [.command, .shift])
// #162: piece stability while a block holds.
.disabled(gate.writingLock.isLocked)
}
}
/// #108: File ▸ New Project… (⌥⌘N) — stages the ask; WorkspaceView presents
/// the sheet (commands views can't; the pendingImportURLs pattern, #94).
private struct NewProjectButton: View {
let gate: AppGateState
var body: some View {
Button("New Project…") { gate.posts.stageNewProject() }
.keyboardShortcut("n", modifiers: [.command, .option])
// #162: piece stability while a block holds.
.disabled(gate.writingLock.isLocked)
}
}
/// #91: File ▸ Open… (⌘O) — NSOpenPanel (the Settings Home picker pattern),
/// .md/.markdown only (#96). Opens into the single external guest slot.
private struct OpenExternalButton: View {
let gate: AppGateState
var body: some View {
Button("Open…") {
if let url = pickMarkdown(multiple: false, message: "Opens the file as-is — Museion never converts or moves it.").first {
gate.posts.openExternal(url)
}
}
.keyboardShortcut("o", modifiers: .command)
// #162: piece stability while a block holds.
.disabled(gate.writingLock.isLocked)
}
}
/// #94: File ▸ Import… (⇧⌘O) — multi-select, .md/.markdown only; ONE Origin
/// ask per batch, then copy in as Posts.
private struct ImportFilesButton: View {
let gate: AppGateState
var body: some View {
Button("Import…") {
let urls = pickMarkdown(multiple: true, message: "Imports copies as Posts — the original files are untouched.")
if !urls.isEmpty {
gate.posts.stageImport(urls)
}
}
.keyboardShortcut("o", modifiers: [.command, .shift])
// #162: piece stability while a block holds.
.disabled(gate.writingLock.isLocked)
}
}
/// The shared NSOpenPanel for both File-menu entries (#91/#94): local
/// .md/.markdown files only.
private func pickMarkdown(multiple: Bool, message: String) -> [URL] {
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = multiple
panel.allowedContentTypes = PostStore.openableTypes
panel.message = message
return panel.runModal() == .OK ? panel.urls : []
}
/// #50: reveals `~/Library/Application Support/Museion/Backups` in Finder —
/// restore is manual Finder copy-back in v1 (help doc describes it).
private struct OpenBackupFolderButton: View {
var body: some View {
Button("Open Backup Folder") {
NSWorkspace.shared.open(URL(fileURLWithPath: ProfileBackup.defaultBackupsRoot()))
}
}
}
/// Read-only mirror of the last completed check's state.json record (ticket #39).
/// Reads the file when opened; never triggers a check; no re-check button.
struct AboutEngineView: View {
@State private var record: EngineProbe.StateRecord?
var body: some View {
VStack(spacing: 12) {
Image(systemName: "books.vertical")
.font(.largeTitle)
Text(AppMetadata.name)
.font(.title)
.bold()
Text(AppMetadata.tagline)
.foregroundStyle(.secondary)
Divider()
if let record {
VStack(alignment: .leading, spacing: 6) {
aboutRow("Engine", record.status == "pass" ? "Ready" : "Unavailable")
aboutRow("Engine version", record.engineVersion ?? "—")
aboutRow("Last checked", record.checkedAt)
aboutRow("Binary path", record.binaryPath ?? "—")
}
} else {
Text("No engine check recorded yet.")
.foregroundStyle(.secondary)
}
}
.padding(20)
.frame(width: 380)
.onAppear { record = EngineProbe.readStateRecord() }
}
private func aboutRow(_ label: String, _ value: String) -> some View {
HStack(alignment: .firstTextBaseline) {
Text(label)
.foregroundStyle(.secondary)
Spacer(minLength: 12)
Text(value)
.textSelection(.enabled)
.lineLimit(1)
.truncationMode(.middle)
}
.font(.callout)
}
}