-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathChatSessionManager.swift
More file actions
58 lines (52 loc) · 1.98 KB
/
ChatSessionManager.swift
File metadata and controls
58 lines (52 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import Foundation
import SwiftData
/// App-wide cache of ChatViewModels, keyed by chat UUID.
/// Keeps streams alive across chat switches and sprite navigation so connections
/// are only torn down on explicit actions (interrupt, chat deletion, app termination).
@Observable
@MainActor
final class ChatSessionManager {
private var cache: [UUID: ChatViewModel] = [:]
/// Returns the cached VM for a chat, or creates and loads a new one.
func viewModel(
for chat: SpriteChat,
spriteName: String,
apiClient: SpritesAPIClient,
modelContext: ModelContext
) -> ChatViewModel {
if let existing = cache[chat.id] {
return existing
}
let vm = ChatViewModel(
spriteName: spriteName,
chatId: chat.id,
currentServiceName: chat.currentServiceName,
workingDirectory: chat.workingDirectory
)
vm.loadSession(apiClient: apiClient, modelContext: modelContext)
cache[chat.id] = vm
return vm
}
func isStreaming(chatId: UUID) -> Bool {
cache[chatId]?.isStreaming ?? false
}
/// Called when the app returns to the foreground — reconnects any VM that had a live stream.
func resumeAllAfterBackground(apiClient: SpritesAPIClient, modelContext: ModelContext) {
for vm in cache.values {
vm.resumeAfterBackground(apiClient: apiClient, modelContext: modelContext)
vm.reconnectIfNeeded(apiClient: apiClient, modelContext: modelContext)
}
}
/// Removes and detaches a VM when its chat is deleted.
func remove(chatId: UUID, modelContext: ModelContext) {
cache[chatId]?.detach(modelContext: modelContext)
cache.removeValue(forKey: chatId)
}
/// Detaches and removes all cached VMs. Call when clearing all chats.
func detachAll(modelContext: ModelContext) {
for vm in cache.values {
vm.detach(modelContext: modelContext)
}
cache.removeAll()
}
}