Add unsaved-changes save prompt and crash-recovery draft

Replaces heuristic auto-save (goodbye-phrase detection, idle timeout,
min-message count, on-model-switch) with a standard macOS unsaved-changes
gate (Save/Don't Save/Cancel) on New Chat, Clear Chat, Load Conversation,
and Quit. The Save dialog gained a folder picker with inline "New Folder…"
creation.

Separately, the in-progress conversation is periodically mirrored to disk
(DraftRecoveryService, configurable interval in Settings, default 10s) and
offered back on next launch if oAI crashes or is force-quit, including the
model that was selected.

Two real bugs found via ObjectIdentifier/log-based diagnosis before this
worked correctly:
- oAIApp.init() wired AppDelegate.chatViewModel from its own @State read,
  which returned a throwaway ChatViewModel instance distinct from the one
  ContentView actually renders. Wiring moved to ContentView.onAppear.
- NSApplication.shared.delegate as? AppDelegate always failed silently:
  @NSApplicationDelegateAdaptor registers an internal SwiftUI.AppDelegate
  wrapper as the real NSApp.delegate (same name, different type in a
  different module), which forwards protocol methods but isn't castable
  to our type. AppDelegate now tracks itself via a static `shared`.

Also guards checkForCrashRecoveryDraft() against running under
XCTestConfigurationFilePath — oAITests is app-hosted, so xcodebuild test
launches this same app, and a leftover draft file on disk would otherwise
hang the entire test run on a blocking NSAlert with no one to click it.
This commit is contained in:
2026-07-31 08:11:12 +02:00
parent a306aaef9a
commit e3557a87df
12 changed files with 585 additions and 490 deletions
+16 -76
View File
@@ -11,33 +11,6 @@ import Testing
@Suite("ChatViewModel pure static helpers")
struct ChatViewModelPureLogicTests {
// MARK: - detectGoodbyePhrase
@Test("Recognizes a clear farewell phrase")
func detectsGoodbye() {
#expect(ChatViewModel.detectGoodbyePhrase(in: "OK, bye!"))
#expect(ChatViewModel.detectGoodbyePhrase(in: "That's all, thanks."))
#expect(ChatViewModel.detectGoodbyePhrase(in: "Have a good day"))
}
@Test("Does not false-positive on a word that merely contains a phrase as a substring")
func doesNotMatchSubstring() {
// "bye" is a whole-word match target -- "goodbyeee" should not match "bye"
// as a substring because of the \b word-boundary regex.
#expect(!ChatViewModel.detectGoodbyePhrase(in: "goodbyeee is not a real word"))
}
@Test("Does not match ordinary polite phrases that aren't farewells")
func doesNotMatchPoliteRequests() {
#expect(!ChatViewModel.detectGoodbyePhrase(in: "Thanks, that's helpful!"))
#expect(!ChatViewModel.detectGoodbyePhrase(in: "Done with step one, what's next?"))
}
@Test("Matching is case-insensitive")
func matchIsCaseInsensitive() {
#expect(ChatViewModel.detectGoodbyePhrase(in: "BYE BYE"))
}
// MARK: - inferProvider
@Test("Model ID with a slash is inferred as OpenRouter")
@@ -109,59 +82,26 @@ struct ChatViewModelPureLogicTests {
#expect(ChatViewModel.calculateCost(usage: usage, pricing: pricing) == 0.0)
}
// MARK: - shouldAutoSave
// MARK: - draftFingerprint
private func autoSaveEligible(
syncEnabled: Bool = true,
syncAutoSave: Bool = true,
syncConfigured: Bool = true,
isCloned: Bool = true,
chatMessageCount: Int = 10,
minMessages: Int = 4,
lastSavedConversationId: String? = nil,
currentConversationHash: String = "hash-a"
) -> Bool {
ChatViewModel.shouldAutoSave(
syncEnabled: syncEnabled,
syncAutoSave: syncAutoSave,
syncConfigured: syncConfigured,
isCloned: isCloned,
chatMessageCount: chatMessageCount,
minMessages: minMessages,
lastSavedConversationId: lastSavedConversationId,
currentConversationHash: currentConversationHash
)
@Test("Identical message content produces the same fingerprint")
func draftFingerprintStableForSameContent() {
let messages = [
Message(role: .user, content: "Hello there"),
Message(role: .assistant, content: "Hi! How can I help?")
]
#expect(ChatViewModel.draftFingerprint(for: messages) == ChatViewModel.draftFingerprint(for: messages))
}
@Test("Eligible when every criterion is satisfied")
func autoSaveEligibleWhenAllCriteriaMet() {
#expect(autoSaveEligible())
@Test("Changed message content produces a different fingerprint")
func draftFingerprintChangesWithContent() {
let before = [Message(role: .user, content: "Hello there")]
let after = [Message(role: .user, content: "Hello there"), Message(role: .assistant, content: "Hi!")]
#expect(ChatViewModel.draftFingerprint(for: before) != ChatViewModel.draftFingerprint(for: after))
}
@Test("Not eligible when sync or auto-save is disabled")
func autoSaveIneligibleWhenDisabled() {
#expect(!autoSaveEligible(syncEnabled: false))
#expect(!autoSaveEligible(syncAutoSave: false))
}
@Test("Not eligible when sync isn't configured or the repo isn't cloned")
func autoSaveIneligibleWhenNotConfiguredOrCloned() {
#expect(!autoSaveEligible(syncConfigured: false))
#expect(!autoSaveEligible(isCloned: false))
}
@Test("Not eligible below the minimum message count")
func autoSaveIneligibleBelowMinimumMessages() {
#expect(!autoSaveEligible(chatMessageCount: 2, minMessages: 4))
}
@Test("Not eligible if this exact conversation was already auto-saved")
func autoSaveIneligibleWhenAlreadySaved() {
#expect(!autoSaveEligible(lastSavedConversationId: "hash-a", currentConversationHash: "hash-a"))
}
@Test("Eligible when the last saved hash differs from the current conversation")
func autoSaveEligibleWhenConversationChanged() {
#expect(autoSaveEligible(lastSavedConversationId: "hash-a", currentConversationHash: "hash-b"))
@Test("Empty message list has a stable fingerprint")
func draftFingerprintEmptyIsStable() {
#expect(ChatViewModel.draftFingerprint(for: []) == ChatViewModel.draftFingerprint(for: []))
}
}
+58
View File
@@ -0,0 +1,58 @@
//
// DraftRecoveryServiceTests.swift
// oAITests
//
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
// Copyright (C) 2026 Rune Olsen
import Testing
import Foundation
@testable import oAI
@Suite("DraftRecoveryService")
struct DraftRecoveryServiceTests {
private func makeService() -> (DraftRecoveryService, URL) {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("oai-draft-test-\(UUID().uuidString).json")
return (DraftRecoveryService(fileURL: url), url)
}
@Test("load() returns nil when no draft file exists")
func loadReturnsNilForMissingFile() {
let (service, _) = makeService()
#expect(service.load() == nil)
}
@Test("save() then load() round-trips the draft")
func saveThenLoadRoundTrips() {
let (service, url) = makeService()
defer { try? FileManager.default.removeItem(at: url) }
let draft = DraftConversation(
messages: [Message(role: .user, content: "Hello"), Message(role: .assistant, content: "Hi there")],
conversationId: UUID(),
conversationName: "Test Conversation",
modelId: "anthropic/claude-sonnet-4-5",
savedAt: Date()
)
service.save(draft)
let loaded = service.load()
#expect(loaded?.messages.count == 2)
#expect(loaded?.messages.first?.content == "Hello")
#expect(loaded?.conversationId == draft.conversationId)
#expect(loaded?.conversationName == "Test Conversation")
#expect(loaded?.modelId == "anthropic/claude-sonnet-4-5")
}
@Test("clear() removes the draft file")
func clearRemovesFile() {
let (service, _) = makeService()
service.save(DraftConversation(messages: [Message(role: .user, content: "Hi")], conversationId: nil, conversationName: nil, modelId: nil, savedAt: Date()))
#expect(service.load() != nil)
service.clear()
#expect(service.load() == nil)
}
}