Files
museion/Museion/WorkspaceView.swift
T
AlexKucera 3ee6756467
CI / ci (push) Canceled after 0s
feat(stats): trend view — the writer's arc (#32)
A Trends pane (rail destination after Learnings — measurement beside
memory): one line chart per style metric (burstiness, type-token ratio,
sentence variation, trigram repetition) across unaided-first-draft
CAPTURES over time. Points are capture moments, never draft grades —
the pane answers "am I getting better," not "is this draft good." Each
card carries a first-to-last read (improving/steady/slipping at ±0.01,
direction inverted for trigram repetition — the one falling-is-better
metric; one capture shows its value with no verdict), an up/down-better
hint, and a one-line plain-language gloss of the term.

The edited-text leak is closed by construction: Post.scan reads the
five stats_* frontmatter keys into firstDraftStats only when every key
parses to a finite double AND the piece carries the capture gate's
immutable pair (origin writer, type post — not pass_state, which
legitimately advances after the capture). Import carries external YAML
verbatim, so imported ai pieces or outlines with hand-stamped keys
never render, while a migrated writer piece keeps its real arc. The
finite gate also kills a deterministic crash: Double("nan") parses, and
a non-finite peak traps the chart's y-domain construction.

The pane rides PostsModel's watched scan — no scan of its own — so it
refreshes with the library. Fixed y-domains keep single captures
visible (sentence variation scales to its peak); offset-keyed chart
identity and a title tie-break make same-second capture twins
deterministic; the empty state names how the data arrives.

Finish-audit (3 reviewers) fixed the nan/inf crash, the import leak,
same-second ordering, and cut the injectable tolerance parameter and a
label-switch enum down to raw values. Suite 508; the non-finite and
read-back-gate pins are flip-verified.

Closes #32
2026-10-31 15:12:45 +01:00

646 lines
21 KiB
Swift
Raw 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.
//
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
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
guard let url = urls.first(where: PostStore.isMarkdown) else { return false }
gate.posts.openExternal(url)
selection = .posts
return true
}
// #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).
.overlay {
if gate.isFocused {
// #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)
}
}
}
}
}
.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, home: gate.museionHome)
}
}
// #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, home: gate.museionHome) {
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(home: gate.museionHome)
} openAsOutline: {
gate.posts.openGuardedOutlineAsOutline(home: gate.museionHome)
}
}
// #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, home: gate.museionHome)
}
}
}
// Collapsed floor: rail 56 + editor placeholder (export ≤920 layout).
.frame(minWidth: 480, minHeight: 320)
// #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
}
}
}
/// #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()
}
},
)
}
@ViewBuilder
private func paneContent(_ geo: GeometryProxy) -> some View {
@Bindable var gate = gate
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,
)
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(home: gate.museionHome, 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).
SettingsPaneView(
home: $gate.museionHome,
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")
// #32: Trends after Learnings — measurement beside memory.
RailButton(pane: .trends, selection: $selection, label: "Trends", systemImage: "chart.xyaxis.line")
Spacer()
// #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")
}
.padding(.horizontal, 4)
.padding(.vertical, 8)
.frame(width: DesignTokens.railWidth)
.frame(maxHeight: .infinity)
}
}
/// #108: the Archive pane — archive/ as a rail destination (prototype
/// verdict: a destination, not a library disclosure). List-only: clicking a
/// piece selects it and hops to Posts, where the editor column lives.
private struct ArchivePaneView: View {
let home: URL
var model: PostsModel
/// Fired after a row select — the pane can't reach WorkspaceView's
/// selection itself.
let onOpenPiece: () -> Void
@State private var renamingPost: Post?
/// #108: collapsed project sections — per-view state, not persisted
/// (mirrors the library column).
@State private var collapsed: Set<String> = []
private var archivedByProject: [String: [Post]] {
Dictionary(grouping: model.posts.filter(\.isArchived), by: \.project)
}
/// #108: the prototype's toggle — click the project name (or chevron).
private func toggle(_ project: String) {
if collapsed.contains(project) {
collapsed.remove(project)
} else {
collapsed.insert(project)
}
}
var body: some View {
VStack(spacing: 0) {
// No New button — things arrive here by being moved, not created.
PaneHeader(title: "Archive")
if archivedByProject.isEmpty {
emptyState
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: 4) {
// #108 audit: Finder order, matching the library's sort.
ForEach(archivedByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in
let pieces = archivedByProject[project] ?? []
// Same section-head shape as the library (#108
// variant B), plus the project-level way out.
HStack(alignment: .firstTextBaseline, spacing: 8) {
Image(systemName: "chevron.down")
.font(.system(size: 9, weight: .semibold))
.rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0))
.foregroundStyle(DesignTokens.muted)
.onTapGesture {
withAnimation { toggle(project) }
}
.accessibilityLabel("Toggle \(project)")
.accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded")
Text(project)
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
.textCase(.lowercase) // #108: display-only — the folder name keeps its case
.lineLimit(1)
.truncationMode(.tail)
.onTapGesture {
withAnimation { toggle(project) }
}
Text("· \(pieces.count)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
Spacer(minLength: 0)
Button("Unarchive") {
model.unarchiveProject(project, home: home)
}
.buttonStyle(.plain)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.help("Move the whole project back to projects/")
.accessibilityLabel("Unarchive \(project)")
}
.padding(.top, 16)
.padding(.horizontal, 14)
.padding(.bottom, 6)
if !collapsed.contains(project) {
ForEach(pieces) { post in
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
model.select(post.id, home: home)
onOpenPiece()
}
.contextMenu {
Button("Move Back to \(post.project)") {
model.restorePost(post, home: home)
}
Button("Rename…") { renamingPost = post }
// #114 (S4): works archived too — the piece
// stays where it is, only type + body flip.
if post.type == .outline {
Button("Convert to Post…") {
model.stageConversion(post, home: home)
}
}
}
}
}
}
}
.padding(.bottom, 12)
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(DesignTokens.background)
.sheet(item: $renamingPost) { post in
RenamePostSheet(post: post) { title in
model.rename(post, to: title, home: home)
}
}
}
private var emptyState: some View {
VStack(spacing: 8) {
Text("Nothing archived")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
Text("Finished projects and pieces fold away here. Move things here from their context menu; they stay openable and editable.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
}
.padding(38)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
/// #94: the ONE Origin ask per import batch — writer (default) / ai, with the
/// immutability line (CONTEXT.md: Origin). Answering runs the batch.
private struct OriginAskSheet: View {
let count: Int
let answer: (Post.Origin) -> Void
@Environment(\.dismiss) private var dismiss
@State private var origin: Post.Origin = .writer
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Who wrote this?")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text(count == 1
? "Importing 1 file as a Post — the original is untouched."
: "Importing \(count) files as Posts — the originals are untouched.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
Picker("Origin", selection: $origin) {
Text("I wrote it (writer)").tag(Post.Origin.writer)
Text("AI-assisted (ai)").tag(Post.Origin.ai)
}
.pickerStyle(.radioGroup)
Text("Origin is stamped once and never asked again — it decides whether the draft's stats can measure you.")
.font(.caption)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
Button("Cancel", role: .cancel) { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Import") {
answer(origin)
dismiss()
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 380)
}
}
/// #111 (S7): the mixed-content outline guard ask. The piece has prose
/// lines the outliner can't show — opening it as an outline would drop
/// them on the next save. Prose = nothing drops; Outline = the explicit
/// choice the ruling requires.
private struct OutlineGuardSheet: View {
let openInProse: () -> Void
let openAsOutline: () -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Open as outline or prose?")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("This outline has paragraph lines between its bullets. The outliner can't show them — opening as an outline drops them on the next save. Prose mode shows everything.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
Text("Outline mode keeps its bullets, indentation, and folding. You can convert or clean up later.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
// Dismissal itself is the cancel (binding set(false) →
// cancelOutlineGuard) — Esc and ⌘. land here too.
Button("Cancel", role: .cancel) {}
.keyboardShortcut(.cancelAction)
Button("Open as Outline") {
openAsOutline()
}
Button("Open in Prose") {
openInProse()
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 420)
}
}
/// #114 (S4): the Convert to Post ask — which body the piece becomes.
/// Verbatim (default) keeps every line; the ladder re-maps outline levels
/// to headings. On mixed content the ladder would drop prose lines —
/// the sheet says so.
private struct ConvertSheet: View {
let lossy: Bool
/// false = verbatim bullets, true = headings ladder — one decision,
/// one model call.
let convert: (Bool) -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Convert to Post")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("The piece keeps its name, project, and Pass State — it becomes a prose post. How should the outline body read?")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
if lossy {
Text("This outline has paragraph lines between its bullets. The headings ladder drops them; verbatim keeps every line.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
}
Text("Verbatim keeps the bullets as they are; Headings turns top-level blocks into section headings, deeper levels step down.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
// Dismissal itself is the cancel (binding set(false) →
// cancelConversion) — Esc and ⌘. land here too.
Button("Cancel", role: .cancel) {}
.keyboardShortcut(.cancelAction)
Button("Headings") {
convert(true)
}
Button("Verbatim Bullets") {
convert(false)
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 440)
}
}
/// #108: New Project ask — the sheet behind File ▸ New Project… (and any
/// future materialize path). Create runs through the model's raw op; the
/// thrown reason is shown inline and the sheet stays up.
private struct NewProjectSheet: View {
/// Create + open a draft in it; nil = success, a string = the failure
/// reason to show inline (keeps the sheet up).
let create: (String) -> String?
@Environment(\.dismiss) private var dismiss
@State private var name = ""
@State private var failure: String?
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("New Project")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("Pieces land here when it's selected.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
TextField("Name", text: $name)
.textFieldStyle(.roundedBorder)
.onSubmit { confirm() }
if let failure {
Text(failure)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.accent)
}
HStack {
Spacer()
Button("Cancel", role: .cancel) { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Create", action: confirm)
.keyboardShortcut(.defaultAction)
.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}
.padding(20)
.frame(width: 360)
}
private func confirm() {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
if let reason = create(trimmed) {
failure = reason
} else {
dismiss()
}
}
}
/// Rail button per the export: 44×44 muted icon, hover wash, and the current
/// pane raised as a surface card with a 2px selection bar on the rail's edge.
private struct RailButton: View {
let pane: WorkspaceView.Pane
@Binding var selection: WorkspaceView.Pane
let label: String
let systemImage: String
@State private var hover = false
var body: some View {
let selected = selection == pane
Button {
selection = pane
} label: {
Image(systemName: systemImage)
.frame(width: 44, height: 44)
}
.buttonStyle(.plain)
.foregroundStyle(selected ? DesignTokens.foreground : DesignTokens.muted)
.background {
if selected || hover {
RoundedRectangle(cornerRadius: DesignTokens.radius)
.fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06))
.overlay(
RoundedRectangle(cornerRadius: DesignTokens.radius)
.strokeBorder(selected ? DesignTokens.border : .clear),
)
}
}
.overlay(alignment: .leading) {
// Selection bar (`.rail-btn[aria-current]::before`); offset to sit
// on the rail's leading edge like the export's negative inset.
if selected {
Rectangle()
.fill(DesignTokens.foreground)
.frame(width: 2, height: 22)
.offset(x: -6)
}
}
.onHover { hover = $0 }
.help(label)
.accessibilityLabel(label)
}
}
/// Pane-head row per the export (52pt, serif 15 semibold title, bottom border).
/// Trailing slot carries #18's New Post button (export `.pane-head .icon-btn`).
struct PaneHeader<Trailing: View>: View {
let title: String
@ViewBuilder var trailing: () -> Trailing
init(title: String, @ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() }) {
self.title = title
self.trailing = trailing
}
var body: some View {
VStack(spacing: 0) {
HStack {
Text(title)
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Spacer()
trailing()
}
.padding(.horizontal, 14)
.frame(minHeight: 52)
Rectangle()
.fill(DesignTokens.border)
.frame(height: 1)
}
}
}