Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Features/Chat/ChatSession.swift4// Description: State and behaviour of one conversation: loading, sending, streaming, reconnection, branches, outbox.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation11import Observation12import UIKit1314/// A file chosen in the composer, from selection to upload.15struct PendingAttachment: Identifiable, Equatable {16 enum State: Equatable { case uploading(Double), uploaded(Attachment), failed(String) }17 let id = UUID()18 var filename: String19 var mime: String20 var size: Int21 var thumbnail: UIImage?22 var state: State23 var uploaded: Attachment? { if case .uploaded(let a) = state { return a } else { return nil } }24}2526/// Client state of a conversation and of its generation stream.27///28/// The server runs every generation detached from the HTTP connection. This class therefore treats the SSE stream as a29/// *view* of the run: when the connection drops (network, app in the background, phone locked) it re-attaches with the30/// index of the last event it applied; when the run is gone it reloads the conversation, whose rows hold the truth.31/// A message is displayed as sent only once the server confirmed it; text that never reached the server goes back to32/// the composer or, when the device is offline, to the visible outbox.33@MainActor34@Observable35final class ChatSession: Identifiable {36 enum Phase: Equatable { case idle, sending, streaming, reconnecting }3738 nonisolated let id = UUID()39 private(set) var conversationId: String?40 private(set) var conversation: Conversation?41 /// The thread on screen (active branch), including the message being streamed.42 private(set) var messages: [ChatMessage] = []43 private(set) var allMessages: [ChatMessage] = []44 private(set) var attachments: [Attachment] = []45 private(set) var artifacts: [Artifact] = []46 private(set) var phase: Phase = .idle47 private(set) var isLoading = false48 /// True when what is shown comes from the local cache because the server could not be reached.49 private(set) var isShowingCache = false50 private(set) var cacheDate: Date?51 private(set) var loadError: String?52 var error: String?53 var warning: String?54 /// Messages written offline, waiting for the network (never presented as sent).55 private(set) var pending: [OutboxItem] = []56 /// Bumped whenever content arrives; the list uses it to follow the bottom while streaming.57 private(set) var revision = 05859 // composer state lives here so it survives navigation between conversations60 var composerText = "" { didSet { if composerText != oldValue { scheduleDraftSave() } } }61 var composerAttachments: [PendingAttachment] = []62 var projectId: String?6364 var isBusy: Bool { phase != .idle }65 var title: String { conversation?.title ?? Conversation.untitled }6667 @ObservationIgnored private let env: ChatSessionDependencies68 @ObservationIgnored private var working = ThreadState()69 @ObservationIgnored private var streamTask: Task<Void, Never>?70 @ObservationIgnored private var publishTask: Task<Void, Never>?71 @ObservationIgnored private var draftTask: Task<Void, Never>?72 @ObservationIgnored private var uploadTasks: [UUID: Task<Void, Never>] = [:]73 @ObservationIgnored private var lastSavedDraft = ""74 @ObservationIgnored private var hasLoadedOnce = false75 @ObservationIgnored private var backgroundTask: UIBackgroundTaskIdentifier = .invalid7677 init(conversationId: String?, projectId: String? = nil, dependencies: ChatSessionDependencies) {78 self.conversationId = conversationId79 self.projectId = projectId80 self.env = dependencies81 self.isLoading = conversationId != nil82 }8384 // MARK: loading8586 /// Shows the cached copy at once, then the server's version. `attach`: follow a generation still running on the server.87 func load(attach: Bool = true) async {88 guard let id = conversationId else { await loadNewDraft(); return }89 if !hasLoadedOnce, let cached = await env.store.detail(id) {90 apply(cached.detail); isShowingCache = true; cacheDate = cached.fetchedAt; isLoading = false91 }92 hasLoadedOnce = true93 pending = await env.store.outbox().filter { $0.conversationId == id }94 do {95 let detail = try await env.api.conversation(id)96 // while a run is being observed the live state is ahead of the database rows: keep it97 if phase == .idle { apply(detail) } else { applyMetadata(detail) }98 isShowingCache = false; loadError = nil; isLoading = false99 await env.store.saveDetail(detail)100 // lastSavedDraft first: assigning composerText schedules a save unless the text is already known to the server101 if composerText.isEmpty, let draft = detail.draft, !draft.isEmpty { lastSavedDraft = draft; composerText = draft }102 await restoreUnsentDraft()103 if attach, phase == .idle, let run = detail.liveRun { follow(runId: run, after: -1) }104 } catch let e as APIError {105 isLoading = false106 if e.kind == .cancelled || e.kind == .locked { return }107 if e.status == 404 { loadError = String(localized: "Cette conversation n’existe plus."); await env.store.deleteConversation(id); return }108 if conversation == nil { loadError = e.message } else if e.kind == .network { isShowingCache = true }109 if e.kind == .network { await restoreUnsentDraft() }110 } catch { isLoading = false }111 }112113 private func loadNewDraft() async {114 isLoading = false115 pending = await env.store.outbox().filter { $0.conversationId == nil }116 guard !hasLoadedOnce else { return }117 hasLoadedOnce = true118 if composerText.isEmpty, let draft = try? await env.api.draft(scope: draftScope), !draft.isEmpty, composerText.isEmpty { lastSavedDraft = draft; composerText = draft }119 await restoreUnsentDraft()120 }121122 private func apply(_ d: ConversationDetail) {123 conversation = d.conversation; allMessages = d.messages; messages = d.activeMessages124 attachments = d.attachments; artifacts = d.artifacts125 revision += 1126 }127 private func applyMetadata(_ d: ConversationDetail) {128 conversation = d.conversation; attachments = d.attachments129 }130131 /// The app came back to the foreground: refresh, and re-attach to a run that kept going on the server.132 func resume() async {133 guard conversationId != nil else { return }134 if phase == .idle { await load() }135 }136137 // MARK: sending138139 var canSend: Bool {140 guard phase == .idle else { return false }141 let hasText = !composerText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty142 let uploads = composerAttachments143 if uploads.contains(where: { if case .uploading = $0.state { return true } else { return false } }) { return false }144 return hasText || uploads.contains { $0.uploaded != nil }145 }146147 /// Sends what is in the composer.148 func sendComposer(options: SendOptions) {149 guard canSend else { return }150 let text = composerText151 let files = composerAttachments.compactMap(\.uploaded)152 draftTask?.cancel(); lastSavedDraft = ""; composerText = ""; composerAttachments = [] // the server deletes the draft when it accepts the message153 let store = env.store, key = LocalDraft.key(draftScope)154 Task { await store.removeValue(for: key) }155 send(text: text, attachments: files, options: options, requestId: ChatAPI.requestId())156 }157158 func send(text: String, attachments files: [Attachment], options: SendOptions, requestId: String) {159 guard phase == .idle else { return }160 let optimistic = ChatMessage(id: "tmp_\(requestId)", conversationId: conversationId ?? "", parentId: messages.last?.id, role: .user,161 parts: files.map(\.asPart) + (text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? [] : [.text(text)]),162 modelId: nil, provider: nil, applied: nil, routing: nil, usage: nil, costUsd: nil, latencyMs: nil, ttftMs: nil, status: .complete, error: nil, errorCode: nil, active: true, createdAt: Date())163 var payload = options.payload()164 payload["text"] = .string(text)165 payload["clientRequestId"] = .string(requestId)166 if !files.isEmpty { payload["attachmentIds"] = .array(files.map { .string($0.id) }) }167 if let conversationId { payload["conversationId"] = .string(conversationId) } else if let projectId { payload["projectId"] = .string(projectId) }168 let queued = OutboxItem(id: requestId, conversationId: conversationId, projectId: projectId, text: text, attachments: files, options: options, createdAt: Date(), lastError: nil)169 start(path: "/api/chat", payload: payload, context: TurnContext(optimisticUserId: optimistic.id), optimistic: optimistic, unreachable: .queue(queued))170 }171172 func regenerate(_ message: ChatMessage, options: SendOptions) {173 guard phase == .idle else { return }174 var payload = options.payload()175 payload["messageId"] = .string(message.id); payload["clientRequestId"] = .string(ChatAPI.requestId())176 start(path: "/api/chat/regenerate", payload: payload, context: TurnContext(replaceAssistantId: message.id, parentMessageId: message.parentId), optimistic: nil, unreachable: .report)177 }178179 func edit(_ message: ChatMessage, text: String, options: SendOptions) {180 guard phase == .idle, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }181 var optimistic = message182 optimistic.id = "tmp_edit_\(UUID().uuidString)"183 optimistic.parts = message.parts.filter { if case .text = $0 { return false } else { return true } } + [.text(text)]184 var payload = options.payload()185 payload["messageId"] = .string(message.id); payload["text"] = .string(text); payload["clientRequestId"] = .string(ChatAPI.requestId())186 start(path: "/api/chat/edit", payload: payload, context: TurnContext(optimisticUserId: optimistic.id), optimistic: optimistic, unreachable: .report)187 }188189 /// Approves or denies the tool calls an answer left pending, then lets the turn continue.190 func resolveToolCalls(on message: ChatMessage, approve: [String], deny: [String]) {191 guard phase == .idle else { return }192 let payload: [String: JSONValue] = ["messageId": .string(message.id), "approve": .array(approve.map(JSONValue.string)), "deny": .array(deny.map(JSONValue.string)), "clientRequestId": .string(ChatAPI.requestId())]193 start(path: "/api/chat/approve", payload: payload, context: TurnContext(parentMessageId: message.id), optimistic: nil, unreachable: .report)194 }195196 /// Stop: the server cancels the run (the provider call really ends), then the local stream is closed.197 func stop() {198 guard phase != .idle else { return }199 let runId = working.runId200 let streamingId = messages.last(where: \.isStreaming)?.id201 streamTask?.cancel(); streamTask = nil202 for i in working.messages.indices where working.messages[i].status == .streaming { working.messages[i].status = .cancelled }203 phase = .idle; publish(); endBackgroundTask()204 let api = env.api205 let conversation = conversationId206 Task { [weak self] in207 try? await api.cancel(runId: runId, messageId: streamingId)208 try? await Task.sleep(for: .milliseconds(600))209 // Stop pressed before the server announced its run: the run may have started anyway. Ask the server210 // what is alive for this conversation and cancel that too, so "stop" never leaves a generation running.211 if runId == nil, let conversation, let live = (try? await api.conversation(conversation))?.liveRun {212 try? await api.cancel(runId: live, messageId: nil)213 try? await Task.sleep(for: .milliseconds(400))214 }215 await self?.load(attach: false)216 await self?.env.conversationsChanged()217 }218 }219220 // MARK: outbox221222 private enum Unreachable { case queue(OutboxItem), report }223224 /// Posts a message that was waiting in the outbox (same idempotency key as the first attempt).225 func sendQueued(_ item: OutboxItem) {226 guard phase == .idle else { return }227 pending.removeAll { $0.id == item.id }228 send(text: item.text, attachments: item.attachments, options: item.options, requestId: item.id)229 }230231 /// Takes a waiting message back into the composer.232 func recall(_ item: OutboxItem) {233 pending.removeAll { $0.id == item.id }234 let store = env.store235 Task { await store.removeFromOutbox(item.id) }236 composerText = item.text237 composerAttachments = item.attachments.map { PendingAttachment(filename: $0.filename, mime: $0.mime, size: $0.sizeBytes ?? 0, thumbnail: nil, state: .uploaded($0)) }238 }239240 func discard(_ item: OutboxItem) {241 pending.removeAll { $0.id == item.id }242 let store = env.store243 Task { await store.removeFromOutbox(item.id) }244 }245246 // MARK: turn lifecycle247248 private func start(path: String, payload: [String: JSONValue], context: TurnContext, optimistic: ChatMessage?, unreachable: Unreachable) {249 error = nil; warning = nil250 working = ThreadState(conversationId: conversationId, title: conversation?.title, messages: messages + (optimistic.map { [$0] } ?? []), artifacts: artifacts)251 phase = .sending252 publish()253 beginBackgroundTask()254 streamTask = Task { [weak self] in255 await self?.runTurn(path: path, payload: payload, context: context, optimistic: optimistic, unreachable: unreachable)256 }257 }258259 private func runTurn(path: String, payload: [String: JSONValue], context: TurnContext, optimistic: ChatMessage?, unreachable: Unreachable) async {260 var opening: HTTPClient.StreamOpening?261 var failure: APIError?262 // The POST itself may be retried: the idempotency key guarantees one message and one generation.263 for attempt in 0..<3 {264 if Task.isCancelled { return }265 do { opening = try await env.api.openTurn(path: path, payload: payload); failure = nil; break }266 catch let e as APIError {267 failure = e268 if e.kind != .network || !env.isOnline() || attempt == 2 { break }269 phase = .reconnecting270 try? await Task.sleep(for: .milliseconds(800 * (1 << attempt)))271 } catch { failure = .network(offline: false); break }272 }273 if Task.isCancelled { return }274275 guard let opening else {276 // Nothing reached the server: the optimistic bubble is removed; the text is never shown as sent.277 if let optimistic { working.messages.removeAll { $0.id == optimistic.id } }278 let e = failure ?? .network(offline: false)279 if e.kind == .network, case .queue(var item) = unreachable {280 item.lastError = e.message281 await env.store.enqueue(item)282 pending.append(item)283 warning = env.isOnline() ? String(localized: "Serveur injoignable : le message attend dans la file d’envoi.") : String(localized: "Hors ligne : le message partira au retour du réseau.")284 } else if e.kind != .locked && e.kind != .cancelled {285 if case .queue(let item) = unreachable { restoreComposer(text: item.text, attachments: item.attachments) }286 else if let optimistic, path.hasSuffix("/edit") { _ = optimistic }287 error = e.message288 }289 phase = .idle; publish(); endBackgroundTask()290 return291 }292 if case .queue(let item) = unreachable { await env.store.removeFromOutbox(item.id) }293294 switch opening {295 case .json:296 // idempotent replay: the server already processed this request — its rows are the answer297 break298 case .events(let bytes):299 let ended = await consume(bytes, context: context)300 if Task.isCancelled { return }301 if !ended, let run = working.runId {302 await followLoop(runId: run, context: context)303 if Task.isCancelled { return }304 }305 }306 await finishTurn()307 }308309 /// Applies the events of one SSE connection. Returns true when the run reported its end.310 private func consume(_ bytes: URLSession.AsyncBytes, context: TurnContext) async -> Bool {311 if phase != .streaming { phase = working.assistantId == nil ? phase : .streaming }312 do {313 for try await item in SSEStream.items(from: bytes) {314 if Task.isCancelled { return false }315 let structural = StreamReducer.apply(item, to: &working, context: context)316 if case .start = item.event { phase = .streaming; warning = nil }317 if let newId = working.conversationId, newId != conversationId { adoptConversation(id: newId) }318 if working.needsReload {319 working.needsReload = false320 if let id = conversationId, let detail = try? await env.api.conversation(id) { working.messages = detail.activeMessages; applyMetadata(detail) }321 }322 if let t = working.title, t != conversation?.title { conversation?.title = t; await env.conversationsChanged() }323 if let w = working.warning { warning = w; working.warning = nil }324 if let e = working.error { error = e; working.error = nil }325 if structural { publish() } else { schedulePublish() }326 if working.ended { return true }327 }328 } catch {329 // dropped connection or silence: the caller re-attaches to the run330 }331 publish()332 return working.ended333 }334335 private func follow(runId: String, after: Int) {336 guard phase == .idle else { return }337 working = ThreadState(conversationId: conversationId, title: conversation?.title, messages: messages, artifacts: artifacts)338 working.runId = runId; working.lastIndex = after339 // the message being written already exists in the loaded rows: deltas replayed from index 0 rebuild it340 if let live = messages.last(where: \.isStreaming) { working.messages.removeAll { $0.id == live.id } }341 phase = .reconnecting342 beginBackgroundTask()343 streamTask = Task { [weak self] in344 await self?.followLoop(runId: runId, context: TurnContext())345 if Task.isCancelled { return }346 await self?.finishTurn()347 }348 }349350 /// Re-attaches to a run until it ends or is gone, with exponential backoff, waiting for the network when offline.351 private func followLoop(runId: String, context: TurnContext) async {352 var tries = 0353 while !Task.isCancelled {354 await env.waitUntilOnline()355 if Task.isCancelled { return }356 do {357 switch try await env.api.attach(runId: runId, after: working.lastIndex) {358 case .json: return359 case .events(let bytes):360 tries = 0; warning = nil361 if await consume(bytes, context: context) { return }362 }363 } catch let e as APIError {364 // 410 / 404: the run finished and was forgotten — the database has the result365 if e.status == 410 || e.status == 404 || e.kind == .locked || e.kind == .cancelled { return }366 } catch { }367 if Task.isCancelled { return }368 tries += 1369 phase = .reconnecting370 if tries > 6 { warning = String(localized: "Connexion perdue. La réponse continue sur le serveur ; elle s’affichera au retour du réseau.") }371 let delay = min(1000 * (1 << min(tries, 4)), 15_000) + Int.random(in: 0...400)372 try? await Task.sleep(for: .milliseconds(delay))373 }374 }375376 private func finishTurn() async {377 publishTask?.cancel(); publishTask = nil378 let finished = working.messages.last { $0.id == working.assistantId }379 phase = .idle380 publish()381 streamTask = nil382 await load(attach: false)383 await env.conversationsChanged()384 env.turnFinished(conversationId, title, finished)385 endBackgroundTask()386 }387388 private func adoptConversation(id: String) {389 let wasNew = conversationId == nil390 conversationId = id391 if wasNew { env.sessionAdopted(self, id) }392 }393394 private func restoreComposer(text: String, attachments files: [Attachment]) {395 if composerText.isEmpty { composerText = text }396 if composerAttachments.isEmpty { composerAttachments = files.map { PendingAttachment(filename: $0.filename, mime: $0.mime, size: $0.sizeBytes ?? 0, thumbnail: nil, state: .uploaded($0)) } }397 }398399 // MARK: publishing (coalesced)400401 /// Token deltas arrive faster than the display refreshes. Structural events are published at once; text is402 /// published at most ~25 times per second, so SwiftUI lays out once per frame batch instead of once per token.403 private func schedulePublish() {404 guard publishTask == nil else { return }405 publishTask = Task { [weak self] in406 try? await Task.sleep(for: .milliseconds(40))407 guard let self, !Task.isCancelled else { return }408 self.publishTask = nil409 self.publish()410 }411 }412413 private func publish() {414 publishTask?.cancel(); publishTask = nil415 if messages != working.messages { messages = working.messages; revision += 1 }416 if artifacts != working.artifacts { artifacts = working.artifacts }417 }418419 // MARK: branches & metadata420421 /// Versions of a message under the same parent (edit / regenerate history), oldest first.422 func versions(of message: ChatMessage) -> [ChatMessage] {423 allMessages.filter { $0.parentId == message.parentId && $0.role == message.role }.sorted { $0.createdAt < $1.createdAt }424 }425426 func switchBranch(to messageId: String) async {427 guard let id = conversationId, phase == .idle else { return }428 do { try await env.api.activateBranch(conversation: id, messageId: messageId); await load(attach: false) }429 catch { self.error = error.localizedDescription }430 }431432 func update(_ patch: ConversationPatch) async {433 guard let id = conversationId else { return }434 do {435 let c = try await env.api.updateConversation(id, patch)436 conversation = c437 await env.store.upsertConversation(c)438 await env.conversationsChanged()439 } catch { self.error = error.localizedDescription }440 }441442 /// Forks the conversation at a message into a new conversation (optionally named); returns its id.443 func fork(at message: ChatMessage, label: String? = nil) async -> String? {444 guard let id = conversationId else { return nil }445 do { let c = try await env.api.fork(conversation: id, at: message.id, label: label); await env.conversationsChanged(); return c.id }446 catch { self.error = error.localizedDescription; return nil }447 }448449 /// The sync feed says the draft of a scope changed on another device: take it, unless this device has unsaved typing.450 func draftChangedOnServer(scope: String) async {451 guard scope == draftScope, phase == .idle, composerText == lastSavedDraft else { return }452 let next: String453 do { next = try await env.api.draft(scope: scope) ?? "" } catch { return }454 guard composerText == lastSavedDraft, next != composerText else { return }455 lastSavedDraft = next; composerText = next456 }457458 // MARK: drafts459460 private var draftScope: String { conversationId ?? (projectId.map { "new:\($0)" } ?? "new") }461462 /// Unsent text is kept on the server (debounced) so it follows the account to the web and the Mac. Until the463 /// server has it, a copy stays in the local store: typed offline, it survives a relaunch and is pushed when the464 /// network returns.465 private func scheduleDraftSave() {466 draftTask?.cancel()467 let text = composerText468 guard text != lastSavedDraft else { return }469 // a quick command being typed (`/…`) is not a draft: it must not follow the account to the other apps470 if ComposerSuggestion.trigger(in: text).map({ if case .command = $0 { return true } else { return false } }) == true { return }471 let scope = draftScope472 let api = env.api, store = env.store473 draftTask = Task { [weak self] in474 try? await Task.sleep(for: .milliseconds(1500))475 guard !Task.isCancelled else { return }476 await store.setValue(LocalDraft(text: text, updatedAt: Date()), for: LocalDraft.key(scope))477 if (try? await api.saveDraft(scope: scope, text: text)) != nil {478 self?.lastSavedDraft = text479 await store.removeValue(for: LocalDraft.key(scope))480 }481 }482 }483484 /// A draft written while the server was unreachable: shown again, and pushed now if the network is back.485 private func restoreUnsentDraft() async {486 guard let local: LocalDraft = await env.store.value(for: LocalDraft.key(draftScope)) else { return }487 if composerText.isEmpty || composerText == lastSavedDraft { composerText = local.text }488 await pushUnsentDraft()489 }490491 /// Pushes the text the server does not have yet (reconnection, foreground). The newer text wins: this device's492 /// unsent typing is by construction more recent than what it last read from the server.493 func pushUnsentDraft() async {494 let text = composerText, scope = draftScope495 guard text != lastSavedDraft, env.isOnline(), phase == .idle else { return }496 if ComposerSuggestion.trigger(in: text).map({ if case .command = $0 { return true } else { return false } }) == true { return }497 if (try? await env.api.saveDraft(scope: scope, text: text)) != nil {498 if composerText == text { lastSavedDraft = text }499 await env.store.removeValue(for: LocalDraft.key(scope))500 }501 }502503 // MARK: attachments504505 func addAttachment(data: Data, filename: String, mime: String, thumbnail: UIImage?) {506 guard composerAttachments.count < 10 else { error = String(localized: "10 fichiers au maximum par message."); return }507 let item = PendingAttachment(filename: filename, mime: mime, size: data.count, thumbnail: thumbnail, state: .uploading(0))508 composerAttachments.append(item)509 let api = env.api510 let conv = conversationId, proj = conversationId == nil ? projectId : nil511 let itemId = item.id512 uploadTasks[itemId] = Task { [weak self] in513 do {514 let uploaded = try await api.upload(filename: filename, mime: mime, data: data, conversationId: conv, projectId: proj) { [weak self] fraction in515 Task { @MainActor in self?.setAttachment(itemId) { if case .uploading = $0.state { $0.state = .uploading(fraction) } } }516 }517 self?.setAttachment(itemId) { $0.state = .uploaded(uploaded) }518 } catch let e as APIError {519 if e.kind == .cancelled { return }520 self?.setAttachment(itemId) { $0.state = .failed(e.message) }521 } catch { self?.setAttachment(itemId) { $0.state = .failed(error.localizedDescription) } }522 self?.uploadTasks[itemId] = nil523 }524 }525526 private func setAttachment(_ id: UUID, _ body: (inout PendingAttachment) -> Void) {527 guard let i = composerAttachments.firstIndex(where: { $0.id == id }) else { return }528 body(&composerAttachments[i])529 }530531 /// Removes a file from the composer: cancels its upload, or deletes the uploaded copy from the server.532 func removeAttachment(_ item: PendingAttachment) {533 uploadTasks[item.id]?.cancel(); uploadTasks[item.id] = nil534 composerAttachments.removeAll { $0.id == item.id }535 if let uploaded = item.uploaded { let api = env.api; Task { try? await api.deleteAttachment(uploaded.id) } }536 }537538 // MARK: background539540 /// Asks iOS for a little time when the app leaves the foreground mid-answer, so short answers finish and the541 /// last tokens are saved. The run itself never depends on it: it continues on the server.542 private func beginBackgroundTask() {543 guard backgroundTask == .invalid else { return }544 backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "spchat.generation") { [weak self] in545 Task { @MainActor in self?.endBackgroundTask() }546 }547 }548 private func endBackgroundTask() {549 guard backgroundTask != .invalid else { return }550 UIApplication.shared.endBackgroundTask(backgroundTask); backgroundTask = .invalid551 }552553 /// Stops observing (the conversation was deleted or the account signed out). The server run is not cancelled.554 func detach() {555 streamTask?.cancel(); streamTask = nil; publishTask?.cancel(); draftTask?.cancel()556 uploadTasks.values.forEach { $0.cancel() }; uploadTasks.removeAll()557 phase = .idle; endBackgroundTask()558 }559}560561/// What a session needs from the rest of the app (kept narrow so sessions are testable with fakes).562/// Composer text the server has not confirmed yet (kept only until it does).563struct LocalDraft: Codable, Sendable {564 var text: String565 var updatedAt: Date566 static func key(_ scope: String) -> String { "draft.\(scope)" }567}568569@MainActor570struct ChatSessionDependencies {571 var api: ChatAPI572 var store: LocalStore573 var isOnline: () -> Bool574 var waitUntilOnline: () async -> Void575 /// The conversation list should be refreshed (new title, new conversation, new last message).576 var conversationsChanged: () async -> Void577 /// A draft session became a real conversation.578 var sessionAdopted: (ChatSession, String) -> Void579 var turnFinished: (_ conversationId: String?, _ title: String, _ message: ChatMessage?) -> Void580}581