// // EditorSessionTests.swift // Museion // // #19 (S1.2): one runnable check per piece of session logic — debounce → // flush, save-state transitions, sidecar round-trip + Trash death, conflict // alert (echo suppression, Yes-reload, No-keep-local). // import Foundation @testable import Museion import Testing @MainActor private func makeSessionHome() -> URL { let dir = FileManager.default.temporaryDirectory .appendingPathComponent("museion-editor-\(UUID().uuidString)", isDirectory: true) try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) return dir } @MainActor private func seedPost(_ home: URL, id: String, body: String) { let dir = home.appendingPathComponent("projects/posts/\(id)", isDirectory: true) try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) try? PostStore.stamped(body: body, passState: .firstDraft, origin: .writer) .write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) } @Suite(.serialized) @MainActor struct EditorSessionTests { @Test func `debounce flushes after idle and stamps the sidecar`() async throws { let home = makeSessionHome() seedPost(home, id: "alpha", body: "# Alpha\n\nOne.") let session = EditorSession(postID: "alpha", home: home, debounce: .milliseconds(50)) #expect(session.saveState == .saved) session.edit("# Alpha\n\nOne. Two.") #expect(session.saveState == .changed) // #83: dirty shows while the debounce holds // Await the flush rather than sleeping a fixed window — under suite // load the main actor can starve the debounce Task past any constant. let deadline = ContinuousClock.now.advanced(by: .seconds(5)) while session.saveState != .saved, ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) } #expect(session.saveState == .saved) // Changed → flush → Saved lands here #expect(PostStore.readBody(id: "alpha", home: home) == "# Alpha\n\nOne. Two.") // Sidecar: written on flush, reads back. let cursor = PostStore.CursorState(selectionLocation: 3, selectionLength: 2, scrollOffset: 128) session.cursorUpdate(cursor) session.edit("# Alpha\n\nOne. Two. Three.") try await Task.sleep(for: .milliseconds(200)) let restored = PostStore.readCursor(id: "alpha", home: home) #expect(restored == cursor) } @Test func `flush is a no-op when clean and immediate when dirty via command-S path`() { let home = makeSessionHome() seedPost(home, id: "beta", body: "# Beta\n\nBody.") let session = EditorSession(postID: "beta", home: home) // Clean: flush does nothing (no throw, no write churn). session.flush() #expect(session.saveState == .saved) // Dirty + immediate flush (⌘S) — disk updated synchronously. session.edit("# Beta\n\nChanged.") session.flush() #expect(PostStore.readBody(id: "beta", home: home) == "# Beta\n\nChanged.") } @Test func `external change alerts, echo suppressed; Yes reloads, No keeps local`() throws { let home = makeSessionHome() seedPost(home, id: "gamma", body: "# Gamma\n\nOriginal.") let session = EditorSession(postID: "gamma", home: home) // Watcher echo of our own write: disk == lastFlushedText → no alert. session.edit("# Gamma\n\nMine now.") session.flush() session.diskDidChange(diskText: "# Gamma\n\nMine now.") #expect(!session.conflictAlert) // Genuine external edit → alert. try PostStore.overwrite(id: "gamma", body: "# Gamma\n\nExternal.", home: home) session.diskDidChange(diskText: "# Gamma\n\nExternal.") #expect(session.conflictAlert) // Yes-reload: text = disk, load generation moved (surface reloads). session.reloadFromDisk() #expect(!session.conflictAlert) #expect(session.text == "# Gamma\n\nExternal.") #expect(session.loadGeneration == 1) // Second external edit → No: keep local; next flush overwrites. try PostStore.overwrite(id: "gamma", body: "# Gamma\n\nNewer external.", home: home) session.diskDidChange(diskText: "# Gamma\n\nNewer external.") #expect(session.conflictAlert) session.keepLocal() #expect(!session.conflictAlert) #expect(session.text == "# Gamma\n\nExternal.") // local kept session.edit("# Gamma\n\nLocal wins.") session.flush() #expect(PostStore.readBody(id: "gamma", home: home) == "# Gamma\n\nLocal wins.") } @Test func `dirty edits show Changed until flushed; reverting to flushed text clears it`() { let home = makeSessionHome() seedPost(home, id: "eta", body: "# Eta\n\nBase.") let session = EditorSession(postID: "eta", home: home) // Dirty while the debounce holds (#83) — never a lying "Saved". session.edit("# Eta\n\nDirty.") #expect(session.saveState == .changed) // Flush lands → Saved. session.flush() #expect(session.saveState == .saved) // Editing back to the flushed text = clean again (undo counts); // anything else still differs from disk → stays Changed. session.edit("# Eta\n\nBase.") #expect(session.saveState == .changed) session.edit("# Eta\n\nDirty.") // back to the flushed content #expect(session.saveState == .saved) // Keep Local after a conflict: local ≠ disk → dirty. session.edit("# Eta\n\nLocal mine.") session.flush() try? PostStore.overwrite(id: "eta", body: "# Eta\n\nExternal.", home: home) session.diskDidChange(diskText: "# Eta\n\nExternal.") session.keepLocal() #expect(session.saveState == .changed) // #83: Keep Local with the post vanished mid-alert — the session must // stay dirty (never a lying "Saved"), ⌘S still attempts the write. try? FileManager.default.removeItem( at: home.appendingPathComponent("projects/posts/eta", isDirectory: true), ) session.diskDidChange(diskText: "# Eta\n\nExternal 2.") // alert raised; disk now unreadable session.keepLocal() #expect(session.saveState == .changed) session.flush() // still dirty → write attempted → folder gone → failed #expect(session.saveState == .failed) } @Test func `write failure flips saveState to failed and retries on next flush`() throws { let home = makeSessionHome() seedPost(home, id: "delta", body: "# Delta\n\nBody.") let session = EditorSession(postID: "delta", home: home) // Vanish the post: overwrite throws (no resurrection), state = failed. try FileManager.default.removeItem( at: home.appendingPathComponent("projects/posts/delta", isDirectory: true), ) var reported: String? session.onError = { reported = $0 } session.edit("# Delta\n\nOrphan.") session.flush() #expect(session.saveState == .failed) #expect(reported != nil) // Next flush retries (still failed until the post returns). session.flush() #expect(session.saveState == .failed) // #83: failed is sticky — reverting to the flushed text never shows // "Saved" over a file whose last write threw; only a write clears it. session.edit("# Delta\n\nBody.") // back to on-disk content session.flush() #expect(session.saveState == .failed) // …and sticky across further edits: still failed, never "Changed". session.edit("# Delta\n\nDifferent.") #expect(session.saveState == .failed) } @Test func `debounce does not clobber while the conflict alert is unanswered`() async throws { let home = makeSessionHome() seedPost(home, id: "epsilon", body: "# Epsilon\n\nMine.") let session = EditorSession(postID: "epsilon", home: home, debounce: .milliseconds(50)) // External change lands mid-typing → alert up; debounce must hold fire. session.edit("# Epsilon\n\nMy newer local.") try PostStore.overwrite(id: "epsilon", body: "# Epsilon\n\nExternal.", home: home) session.diskDidChange(diskText: "# Epsilon\n\nExternal.") #expect(session.conflictAlert) try await Task.sleep(for: .milliseconds(200)) // debounce window passes #expect(PostStore.readBody(id: "epsilon", home: home) == "# Epsilon\n\nExternal.") // external edit intact #expect(session.saveState == .changed) // #83: pending local edits, alert held the write // Keep Local → next explicit flush overwrites (the writer's choice). session.keepLocal() session.flush() #expect(PostStore.readBody(id: "epsilon", home: home) == "# Epsilon\n\nMy newer local.") } @Test func `teardown flushFirst writes pending edits and cancels the debounce`() async throws { let home = makeSessionHome() seedPost(home, id: "zeta", body: "# Zeta\n\nBase.") let session = EditorSession(postID: "zeta", home: home, debounce: .milliseconds(50)) // flushFirst=true: pending text lands (rename reads disk next). session.edit("# Zeta\n\nReworked.") session.teardown(flushFirst: true) #expect(PostStore.readBody(id: "zeta", home: home) == "# Zeta\n\nReworked.") // flushFirst=false (trash path): the armed debounce never fires. session.edit("# Zeta\n\nDoomed.") // session dropped by owner after teardown; debounce armed session.teardown(flushFirst: false) try await Task.sleep(for: .milliseconds(200)) #expect(PostStore.readBody(id: "zeta", home: home) == "# Zeta\n\nReworked.") // unwritten #expect(session.saveState != .failed) // no spurious failure fired } @Test func `unresolvable id falls back to the default-project path`() { // #107: folderURL is resolved once at init; a piece that exists // nowhere still gets a sane path (image resolution, crumbs) — the // default-project shape, never a crash. let home = makeSessionHome() let session = EditorSession(postID: "ghost", home: home) let expected = home.appendingPathComponent("projects/posts/ghost", isDirectory: true) #expect(session.folderURL == expected) #expect(session.loadFailed) // nothing to read there either } }