Files
museion/Museion/WorkspaceView.swift
T
AlexKucera 8b0d43aed8
CI / ci (push) Canceled after 0s
fix(editor): Home repoint rides the departure gate; document identity is (Home, ID)
Settings committed the new Home and bind flipped watchedHome without
departing the open session: the session's immutable target kept the
OLD Home, a same-slug piece in the new library made the ID-only
reselect return it, and autosave/Save/quit wrote the old library
while structural operations resolved against the new one. #198's
departure gate never saw this seam; a no-collision piece was torn
down by the vanish path with its dirty buffer dropped.

The gate runs BEFORE anything commits. PostsModel.repoint(to:) is a
document departure through the same sessionMayDepart (all three legs:
unanswered #67, failed flush, never-loaded retype — no parallel
gate); on refusal nothing changes (preference, watchedHome, the
session's (A, id) target, its buffer), on acceptance the departed
piece's state dies with it. AppGateState.repointMuseionHome(to:)
commits the preference and its persistence only after the gate;
WorkspaceView's Settings binding routes through it and the root
.task(id:) binds the model after that commit — the dumb binder. A
refusal speaks the #198 reason the way #200's quit refusal does
(hosted-guarded alert: no Posts strip is in sight from Settings).
Nothing auto-reopens after an accepted repoint — the writer picks
from the new list; the in-memory draft survives (no Home until first
save; dropping it would drop the only copy).

Document identity is (Home, ID) everywhere — EditorSession.targets
is the pair, PostsModel.openSessionTargets the model-side question;
every ID-only session comparison is retired: select's reselect
no-op, openUnguarded, the structural rail (rename/trash/move/archive/
restore/unarchive + flushOrAbort), conversion, the pass guard (its
answer now carries the Home it validated), Micropub's launch, the
lock's arm/body reads. Async continuations re-validate identity at
COMPLETION: refreshCards (launch and hop-back — the old ID-only guard
let a scan from the previous library land its cards on the new
library's same-slug piece) and rescan (the stale-Home verdict is
hoisted: a scan that outlived a repoint applies nothing, not just
the vanish check; the #67 disk read runs only for a session targeting
the scan's own Home). scanPieceCards is the per-model injectable
scanner the deterministic stale-scan pin needs.

Tests: PostsModelRepointTests (7) move to the gated entry and go
green (17/17 with PostsModelDepartureTests — the #198 matrix stays
green and composes); the stale-scan pin's RED is a mutation check
(completion guard reverted to ID-only → only that pin fails, cards
→ ["Hedging"]; restored byte-exact). The #179 mid-pass repoint pin
drives the real Settings path now (repoint + bind). swiftformat 0/152,
swiftlint 0.
2026-11-23 20:23:57 +01:00

459 lines
17 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// WorkspaceView.swift
// Museion
//
// #17 (S1.1): the workspace shell — nav rail + panes, built from the design
// contract's grid geometry (ref/Web-Prototype/museion-workspace.html):
// rail 56 | library 232 | editor min 420 | mentor 356.
// #108: the Archive rail destination (box icon, above Settings) + the
// New Project ask both live here.
// #193: the split-out files — ArchivePaneView.swift, the house ask
// sheets WorkspaceViewSheets.swift, the shared chrome
// WorkspaceChrome.swift; RailButton stays (the rail is its only caller).
//
import AppKit
import SwiftUI
/// The post-gate main surface. Posts shows the full four-column workspace;
/// Sessions/Learnings/Settings fill the space after the rail until their
/// tickets land (#28/#26; Settings is real here).
struct WorkspaceView: View {
@Environment(AppGateState.self) private var gate
@State private var selection: Pane = .posts
/// #151: the fail card's expansion — auto-expands on each failure
/// arrival (`.onChange` of the visibility); chevron collapses, slot
/// click re-opens.
@State private var statusCardExpanded = false
enum Pane: Hashable {
case posts
case sessions
case learnings
/// #32 (S5.2): the trend view — the writer's arc across unaided
/// first-draft captures, sibling of Learnings (measurement beside
/// memory).
case trends
/// #108: the archive rail destination — archive/ as a first-class
/// pane (prototype variant B/C verdict: a destination, not a
/// library disclosure).
case archive
case settings
}
var body: some View {
GeometryReader { geo in
Group {
if gate.isFocused {
// #21: the rail recedes; the pane takes the full width. The
// measure stays centered — revealed panes float, never push.
paneContent(geo)
} else {
HStack(spacing: 0) {
navRail
paneBorder
paneContent(geo)
}
}
}
// #91: drag a markdown file onto the window — same guest slot as
// File ▸ Open… Non-markdown drops are refused.
.dropDestination(for: URL.self) { urls, _ in
// #162: no new buffers while a Cold Turkey block holds —
// the open Piece is the one being counted.
guard !gate.writingLock.isLocked else { return false }
// #141: the window destination is the only one that ever
// fires (field-verified 2026-11-02 — nested editor-level
// SwiftUI targets are never consulted, and AppKit views
// registered for file drags are starved by it).
// PURE-markdown sets keep #91's open-as-guest; a mixed
// md+image set falls through and ingestDrop refuses it
// loudly (images must not vanish silently behind the md).
// Nil text view: bounce.
if urls.allSatisfy(PostStore.isMarkdown), let url = urls.first {
gate.posts.openExternal(url)
selection = .posts
return true
}
guard let textView = gate.proseDrop.textView else { return false }
return textView.ingestDrop(urls)
}
// #21: left-edge hover slides rail+library back in as an overlay.
// Library only while the window width allows it (#17 verdict stands:
// a collapsed pane is not summoned by focus).
// #162: suppressed while a Cold Turkey block holds — the library
// stays hidden and the open Piece stable for counting (#158).
.overlay {
if gate.isFocused, !gate.writingLock.isLocked {
// #17 verdict: the library reveal honors the width collapse.
let showsLibrary = geo.size.width >= 1100
FocusOverlayPanel(edge: .leading, panelWidth: leftRevealWidth(showsLibrary)) {
HStack(spacing: 0) {
navRail
paneBorder
if showsLibrary {
PostsLibraryColumn(home: gate.museionHome, model: gate.posts)
}
}
}
}
}
// #151: the anchored fail card — floats over content, never
// blocks, never pushes layout (bottom-leading at railWidth + 12,
// bottom 14 — #149's geometry). Fail auto-expands; chevron
// collapses; slot click re-opens. Focus mode recesses the card
// with the rail (chrome recedes for deep work; the pill stays
// hover-reachable, and exiting focus restores the card — the
// expanded state survives).
.overlay(alignment: .bottomLeading) {
if statusVisibility == .failed, statusCardExpanded, !gate.isFocused {
EngineStatusCard(gate: gate) {
statusCardExpanded = false
}
.padding(.leading, DesignTokens.railWidth + 12)
.padding(.bottom, 14)
.transition(.opacity.combined(with: .move(edge: .bottom)))
}
}
.animation(.spring(duration: 0.3), value: statusVisibility)
.background(DesignTokens.background)
// #94: the ONE Origin ask per import batch. Dismissal without an
// answer (Esc/Cancel) drops the batch.
.sheet(isPresented: originAskBinding) {
OriginAskSheet(count: gate.posts.pendingImportURLs?.count ?? 0) { origin in
gate.posts.importFiles(origin: origin)
}
}
// #108: File ▸ New Project… ask — commands can't present sheets, so
// the model stages and this window presents (OriginAsk pattern).
.sheet(isPresented: newProjectAskBinding) {
NewProjectSheet { name in
if let reason = gate.posts.createProject(named: name) {
return reason
}
gate.posts.newProjectPending(named: name)
return nil
}
}
// #111 (S7): the mixed-content outline guard ask — presents over an
// empty editor (select held the open; nothing can edit while it's
// up). Prose = safe open; Outline = explicit consent to the save
// drop; Esc/Cancel backs out with nothing opened.
.sheet(isPresented: outlineGuardBinding) {
OutlineGuardSheet {
gate.posts.openGuardedOutlineInProse()
} openAsOutline: {
gate.posts.openGuardedOutlineAsOutline()
}
}
// #114 (S4): the Convert to Post ask — which body the outline
// piece becomes (verbatim bullets vs headings ladder). Verbatim
// is the default: lossless. Esc/Cancel converts nothing.
.sheet(isPresented: convertAskBinding) {
ConvertSheet(lossy: gate.posts.pendingConversion?.lossy ?? false) { headingsLadder in
gate.posts.convertToPost(headingsLadder: headingsLadder)
}
}
}
// #179 follow-up: the model bind rides the ROOT task — the Archive
// pane and every root sheet (import / new project / convert) call
// library verbs from any pane; a pane-local bind left `watchedHome`
// stale after a Home repoint until Posts remounted.
.task(id: gate.museionHome) {
gate.posts.bind(home: gate.museionHome)
}
// Collapsed floor: rail 56 + editor placeholder (export ≤920 layout).
.frame(minWidth: 480, minHeight: 320)
// #151: every failure arrival auto-expands the card — a fresh
// engine fail, a provisioning fail landing, a Re-check that fails
// again. Collapse is the reader's call (chevron), re-open the
// slot's.
.onChange(of: statusVisibility) { _, newValue in
if newValue == .failed {
statusCardExpanded = true
}
}
// #92/#94: the editor column lives in Posts — a guest buffer or an
// import's opened post surfaces there, whatever pane was showing.
.onChange(of: gate.posts.externalSession != nil) { _, isUp in
if isUp {
selection = .posts
}
}
// #108 audit: ⌘N/New Project open a DRAFT — session is nil, so the
// selectedPostID onChange below can't hop. Hop on the draft itself.
.onChange(of: gate.posts.draft != nil) { _, isDraft in
if isDraft {
selection = .posts
}
}
.onChange(of: gate.posts.selectedPostID) { _, _ in
if gate.posts.session != nil {
selection = .posts
}
}
// #162 audit: View ▸ Start Cold Turkey… can fire while another
// pane is up (the rail is hover-reachable in focus) — the bar
// would pop stale on the next Posts mount. Any pane change
// drops a pending arm-bar.
.onChange(of: selection) { _, _ in
gate.writingLock.showsArmBar = false
}
}
/// #94: the ask presents while a batch is staged.
private var originAskBinding: Binding<Bool> {
Binding(
get: { gate.posts.pendingImportURLs != nil },
set: {
if !$0 {
gate.posts.cancelImport()
}
},
)
}
/// #108: the New Project ask presents while staged.
private var newProjectAskBinding: Binding<Bool> {
Binding(
get: { gate.posts.askNewProject },
set: {
if !$0 {
gate.posts.cancelNewProject()
}
},
)
}
/// #111 (S7): the outline guard ask presents while an open is held.
private var outlineGuardBinding: Binding<Bool> {
Binding(
get: { gate.posts.outlineGuardPieceID != nil },
set: {
if !$0 {
gate.posts.cancelOutlineGuard()
}
},
)
}
/// #114 (S4): the Convert to Post ask — dismissal is the cancel.
private var convertAskBinding: Binding<Bool> {
Binding(
get: { gate.posts.pendingConversion != nil },
set: {
if !$0 {
gate.posts.cancelConversion()
}
},
)
}
/// brief-28 (home-repoint-retains-old-editor-target): a Home repoint is a
/// document departure. The binding's setter IS the gate —
/// `repointMuseionHome` runs the departure gate first and commits the
/// preference (and its persistence) only when every open document
/// landed; the root `.task(id: museionHome)` binds the model after that
/// commit. A refusal keeps Home A and every buffer, and speaks the #198
/// reason the way #200's quit refusal does — the Posts strip that shows
/// `lastError` is not in sight from Settings.
private var homeRepointBinding: Binding<URL> {
Binding(
get: { gate.museionHome },
set: { newHome in
guard gate.repointMuseionHome(to: newHome) else {
presentRepointRefusal()
return
}
},
)
}
/// Hosted tests never present (the quit refusal's guard convention).
private func presentRepointRefusal() {
guard !AppGateState.hostedTestRun else { return }
let alert = NSAlert()
alert.messageText = "Home not changed — a piece needs you first"
alert.informativeText = gate.posts.lastError
?? "An open piece could not be saved. Tend to it, then choose the folder again."
alert.addButton(withTitle: "Back to Museion")
alert.runModal()
}
/// #151: the pill/card state — the gate's phase machine plus the
/// provisioning failure verdict.
private var statusVisibility: EngineStatusSurface.Visibility {
EngineStatusSurface.visibility(
phase: gate.gateModel.phase,
provisioningFailed: gate.provisioning.hasFailure,
)
}
@ViewBuilder
private func paneContent(_ geo: GeometryProxy) -> some View {
switch selection {
case .posts:
// #14: mentor column hands in the app-scoped model + gate's winner.
// Column collapse mirrors the export's media queries (library ≤1100,
// mentor ≤920) as macOS pane collapse per the PRD.
PostsPaneView(
home: gate.museionHome,
mentor: gate.mentor,
mentorBinaryPath: gate.gateModel.currentBinaryPath,
model: gate.posts,
availableWidth: geo.size.width - DesignTokens.railWidth,
// #137: the pass bar's missing-key way out (ArchivePaneView
// closure precedent).
onOpenSettings: { selection = .settings },
)
case .sessions:
// #28: the Sessions pane — roster + active transcript over the
// app-scoped mentor model, the same reach as Learnings' home.
SessionsPaneView(
model: gate.mentor,
posts: gate.posts,
binaryPath: gate.gateModel.currentBinaryPath,
home: gate.museionHome,
gate: gate,
)
case .learnings:
// #26: list-only pane over <home>/learnings/ — read side;
// promoting a fix card (the fix-card rail) writes the files.
LearningsPaneView(home: gate.museionHome)
case .trends:
// #32 (S5.2): the arc — rides PostsModel's watched scan, so
// the pane refreshes with the library, no scan of its own.
TrendsPaneView(model: gate.posts)
case .archive:
// #108: list-only pane — clicking a row selects the piece and
// hops to Posts where its editor lives.
ArchivePaneView(model: gate.posts) {
selection = .posts
}
case .settings:
// #137 (S4): a committed Chat model change restarts the resident
// chat engine in place (slice A's engine-side API; deferred to
// turn end while streaming).
// brief-28: the Home control binds through the repoint gate.
SettingsPaneView(
home: homeRepointBinding,
binaryPath: gate.gateModel.currentBinaryPath,
onChatSurfaceWrite: { gate.mentor.requestRestart() },
)
}
}
/// The left reveal panel's width: rail + border (+ library when the
/// unfocused width verdict grants it).
private func leftRevealWidth(_ showsLibrary: Bool) -> CGFloat {
DesignTokens.railWidth + 1 + (showsLibrary ? DesignTokens.libraryWidth : 0)
}
/// 1px contract border between rail and pane (`.rail { border-right }`).
private var paneBorder: some View {
Rectangle()
.fill(DesignTokens.border)
.frame(width: 1)
}
// MARK: Nav rail
private var navRail: some View {
VStack(spacing: 8) {
RailButton(pane: .posts, selection: $selection, label: "Posts", systemImage: "doc.text")
RailButton(pane: .sessions, selection: $selection, label: "Sessions", systemImage: "bubble.left")
RailButton(pane: .learnings, selection: $selection, label: "Learnings", systemImage: "cube", weight: .light)
// #32: Trends after Learnings — measurement beside memory.
RailButton(pane: .trends, selection: $selection, label: "Trends", systemImage: "chart.xyaxis.line")
Spacer()
// #151: the engine-status slot above Archive (#149 variant A) —
// quiet-when-healthy: nothing renders once the engine answered
// and provisioning finished; the slot collapses and the rail
// spacing closes.
if statusVisibility != .hidden {
EngineStatusPill(visibility: statusVisibility) {
if statusVisibility == .failed {
statusCardExpanded = true
}
}
}
// #108: Archive at the rail bottom, above Settings (prototype's
// box icon).
RailButton(pane: .archive, selection: $selection, label: "Archive", systemImage: "archivebox")
RailButton(pane: .settings, selection: $selection, label: "Settings", systemImage: "gearshape", weight: .light)
}
.padding(.horizontal, 4)
.padding(.vertical, 8)
.frame(width: DesignTokens.railWidth)
.frame(maxHeight: .infinity)
.animation(.easeInOut(duration: 0.2), value: statusVisibility)
}
}
/// Rail button: 44×44 muted icon, hover wash, the current pane raised as
/// a tile. NO visible edge bar — ui-polish r2 re-ruling: the export's
/// `::before` selection bar paints behind the app border in the export's
/// own render, so a visible bar reads as a stray clipped mark;
/// contract-faithful is tile + border + fg-ink icon alone.
/// r5 (sol#40, mercury#54/56 — one final strength step, modest): the
/// selected tile's fill steps from surface (invisible on the chrome
/// background) to a 0.08 foreground wash with a muted-0.4 hairline — the
/// fg-ink glyph reads stronger against it. Icon weight stays constant
/// (sol#45: selection emphasis comes from the tile, never the glyph).
private struct RailButton: View {
let pane: WorkspaceView.Pane
@Binding var selection: WorkspaceView.Pane
let label: String
let systemImage: String
/// sol#45: one explicit size for all six icons; glyph-dense ones (cube,
/// gearshape) opt down a weight so every icon reads the same apparent
/// mass — selection emphasis comes from the tile, never icon weight.
var weight: Font.Weight = .regular
/// r7 (sol#33): the selected glyph's ONE step up (light→regular,
/// regular→medium) — full-ink color on thin strokes still read
/// near-muted; the step puts the current pane's icon at true ink.
private var selectedWeight: Font.Weight {
switch weight {
case .light: .regular
default: .medium
}
}
@State private var hover = false
var body: some View {
let selected = selection == pane
Button {
selection = pane
} label: {
Image(systemName: systemImage)
// r7 (sol#33): the selected glyph steps ONE weight up —
// full ink on a thin-stroke symbol at .light/.regular
// reads near-muted against the 0.08 wash. Unselected
// icons keep their sol#45 mass exactly.
.font(.system(size: 16, weight: selected ? selectedWeight : weight))
.frame(width: 44, height: 44)
}
.buttonStyle(.plain)
.foregroundStyle(selected ? DesignTokens.foreground : DesignTokens.muted)
.background {
if selected || hover {
RoundedRectangle(cornerRadius: DesignTokens.radius)
// r5 (sol#40, mercury#54/56): selected = a 0.08
// foreground wash + muted-0.4 hairline (surface-on-
// chrome was invisible); hover keeps the 0.06 wash,
// borderless. Modest — the hierarchy holds.
.fill(selected ? DesignTokens.foreground.opacity(0.08) : DesignTokens.foreground.opacity(0.06))
.overlay(
RoundedRectangle(cornerRadius: DesignTokens.radius)
.strokeBorder(selected ? DesignTokens.muted.opacity(0.4) : .clear),
)
}
}
.onHover { hover = $0 }
.help(label)
.accessibilityLabel(label)
}
}