Repository navigation
Expand file tree
/
Copy pathBackgroundTaskManager.swift
More file actions
2669 lines (2450 loc) · 123 KB
/
Copy pathBackgroundTaskManager.swift
File metadata and controls
2669 lines (2450 loc) · 123 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// BackgroundTaskManager.swift
// osaurus
//
// Single owner of all backgrounded work — dispatched chat tasks (from
// schedules, shortcuts, plugins, HTTP, watchers). Drives the sidebar Activity section,
// provides completion signaling, and handles lazy window creation.
//
import Combine
import Foundation
/// Durable metadata for a user-owned terminal Activity tab. The live chat
/// session is deliberately not encoded; `ChatSessionStore` remains the
/// canonical transcript store and is hydrated on demand.
private struct RetainedActivityTabRecord: Codable {
enum TerminalKind: String, Codable {
case completed
case failed
case cancelled
}
let id: UUID
let title: String
let agentId: UUID
let kind: TerminalKind
let summary: String?
let createdAt: Date
let source: SessionSource
let sourcePluginId: String?
let externalSessionKey: String?
let contextPreview: [BackgroundTaskContextMessage]
/// Optional for records written before inbound shared-agent runs
/// became retained tabs.
let isInboundRun: Bool?
/// Trigger kind for `.automation` tabs; nil for older records.
let automationKind: EventSourceKind?
@MainActor
init?(state: BackgroundTaskState) {
let kind: TerminalKind
let summary: String?
switch state.status {
case .completed(let value):
kind = .completed
summary = value
case .failed(let value):
kind = .failed
summary = value
case .cancelled:
kind = .cancelled
summary = nil
case .queued, .running, .waitingForInput:
return nil
}
self.id = state.id
self.title = state.taskTitle
self.agentId = state.agentId
self.kind = kind
self.summary = summary
self.createdAt = state.createdAt
self.source = state.source
self.sourcePluginId = state.sourcePluginId
self.externalSessionKey = state.externalSessionKey
self.contextPreview = state.contextPreview
self.isInboundRun = state.isInboundRun
self.automationKind = state.automationKind
}
var status: BackgroundTaskStatus {
switch kind {
case .completed: return .completed(summary: summary ?? "Chat completed")
case .failed: return .failed(summary: summary ?? "Chat failed")
case .cancelled: return .cancelled
}
}
}
/// Ordered off-main writes of immutable retained-tab snapshots. UserDefaults
/// supports concurrent use; this wrapper serializes this manager's mutations so
/// an older completion cannot overwrite a newer update or resurrect a clear.
/// Actor-owned task/session state never crosses onto the writing queue.
private final class RetainedActivityTabWriter: @unchecked Sendable {
private let defaults: UserDefaults
private let key: String
private let queue = DispatchQueue(label: "ai.osaurus.retained-activity-tabs", qos: .utility)
init(defaults: UserDefaults, key: String) {
self.defaults = defaults
self.key = key
}
func enqueue(_ data: Data?) {
queue.async { [self] in
if let data {
defaults.set(data, forKey: key)
} else {
defaults.removeObject(forKey: key)
}
}
}
/// Drain calls enqueued so far. Quit invokes this on a flush worker,
/// within the app's existing overall deadline; never wait on main here.
func flush(timeout: TimeInterval) -> Bool {
let done = DispatchSemaphore(value: 0)
queue.async { done.signal() }
return done.wait(timeout: .now() + timeout) == .success
}
}
// MARK: - Background Task Manager
/// Single owner of all backgrounded chat tasks (dispatched).
@MainActor
public final class BackgroundTaskManager: ObservableObject {
public static let shared: BackgroundTaskManager = {
let manager = BackgroundTaskManager()
sharedIfInitialized = manager
return manager
}()
/// Canonical chat renames must synchronize a retained owner when one
/// exists, without paying this registry's initial defaults read otherwise.
private(set) static var sharedIfInitialized: BackgroundTaskManager?
// MARK: - Published State
/// All background tasks keyed by task ID
@Published public private(set) var backgroundTasks: [UUID: BackgroundTaskState] = [:]
/// Why the most recent `dispatchChat` for a workspace target returned
/// nil, per agent. `dispatchChat`'s nil is otherwise silent (the local
/// guards log and drop); the spawn tools, schedule and watcher managers
/// read this once to report the real reason (offline host, lapsed key…).
private var workspaceDispatchRefusals: [WorkspaceAgentRef: String] = [:]
/// Take (and clear) the refusal reason recorded for `ref`.
public func consumeWorkspaceDispatchRefusal(for ref: WorkspaceAgentRef) -> String? {
workspaceDispatchRefusals.removeValue(forKey: ref)
}
/// Ordering of visible tasks (`showToast == true`) not currently shown
/// in a chat window, sorted by status priority then recency. Background
/// runs surface as tabs of their agent, so no view lists this directly
/// any more; it still backs `closeAgentTaskGroup` and tests. Recomputed
/// only when the task set or a task's observable state changes;
/// refreshes piggyback on the manager's `objectWillChange`, so this
/// stays a plain stored property.
public private(set) var sortedToastTasks: [BackgroundTaskState] = []
/// Fires synchronously from `registerTask` for every run a chat window
/// should surface as a tab of its agent: visible (`showToast`), not a
/// mirror, and backed by a live `ChatSession`. `ChatWindowManager`
/// listens and attaches the run to the frontmost window's strip.
public let taskRegistered = PassthroughSubject<BackgroundTaskState, Never>()
// MARK: - Private State
/// Combined cancellables for each task (session + state observers)
private var taskObservers: [UUID: Set<AnyCancellable>] = [:]
/// Continuations for callers awaiting task completion (e.g. AgentTurnWorker)
/// Value-only terminal metadata is copied while the task still owns its
/// live session. It cannot be lost when cleanup releases that session.
struct CompletionWithToolFailure: Sendable {
let result: DispatchResult
let terminalToolFailure: DelegatedToolFailure?
}
private var completionContinuations: [UUID: CheckedContinuation<CompletionWithToolFailure, Never>] = [:]
/// Tracks the number of turns already processed per chat task so we only log new tool calls.
private var chatTurnCounts: [UUID: Int] = [:]
/// Scheduled auto-finalize timers for completed/cancelled tasks
private var autoFinalizeTasks: [UUID: Task<Void, Never>] = [:]
/// Production managers persist terminal Activity tabs across relaunches.
/// Isolated test managers disable this so suites never read or mutate the
/// user's retained-tab defaults.
private let persistsRetainedTabs: Bool
private let retainedTabsDefaults: UserDefaults
private let retainedTabsWriter: RetainedActivityTabWriter
private static let retainedTabsDefaultsKey = "retainedNotchTabs.v1"
/// Production managers hold an idle-sleep assertion while work is
/// running or queued. Isolated test managers inject nil so unit tests
/// never alter the host machine's power state.
private let powerManager: AgentRunPowerManager?
/// Tasks whose dispatch() hasn't returned to the plugin yet; events are
/// buffered in `heldTaskEvents` until `releaseEventsForDispatch` flushes them.
private var dispatchHoldTasks: Set<UUID> = []
private var heldTaskEvents: [UUID: [(type: TaskEventType, json: String)]] = [:]
/// Tasks for which `ChatSession.isStreaming` has flipped to `true` at
/// least once. Guards `markCompleted` against the synchronous initial
/// `(false, nil)` tuple that `Publishers.CombineLatest` emits the instant
/// `observeChatTask` subscribes (well before `ChatSession.send`'s async
/// Task body runs). See `handleChatStreamingChange`.
private var streamingObserved: Set<UUID> = []
/// Background-task id keyed by the chat window currently bound to it.
/// Populated by `detachChatWindow`, `openTaskWindow`, and
/// `bindWindow(_:toTask:)`; consulted by `ChatWindowManager` in
/// `windowWillClose` to decide whether to skip `cleanup()` (which would
/// otherwise call `session.stop()` and kill the in-flight stream).
/// Window attachment is pure view state — it never affects execution.
private var taskIdByWindow: [UUID: UUID] = [:]
/// Admission for every dispatched run: the Default (or requested) queue's
/// concurrency limit plus the per-agent safety cap. Each run's slots
/// follow its status (see `schedulingStatusChanged`).
let scheduler: TaskScheduler
/// Scheduler task id by background-task id, when they differ (an
/// automation's task reattached to an earlier session).
private var schedulerTaskIds: [UUID: UUID] = [:]
/// Background tasks whose task record this manager owns. The rest were
/// admitted by another owner (an automation), which ends the record and
/// frees the lane when its worker returns.
private var ownedTaskRecords: Set<UUID> = []
/// Last lease renewal per background-task id (see `renewLease`).
private var leaseRenewedAt: [UUID: Date] = [:]
/// Subject for batching view updates with throttling
private let viewUpdateSubject = PassthroughSubject<Void, Never>()
private var viewUpdateCancellable: AnyCancellable?
// MARK: - Initialization
private init(
persistsRetainedTabs: Bool = true,
retainedTabsDefaults: UserDefaults = .standard,
powerManager: AgentRunPowerManager? = .shared,
scheduler: TaskScheduler? = nil
) {
self.persistsRetainedTabs = persistsRetainedTabs
self.retainedTabsDefaults = retainedTabsDefaults
self.retainedTabsWriter = RetainedActivityTabWriter(
defaults: retainedTabsDefaults, key: Self.retainedTabsDefaultsKey
)
self.powerManager = powerManager
self.scheduler = scheduler ?? .shared
viewUpdateCancellable =
viewUpdateSubject
.throttle(for: .milliseconds(50), scheduler: DispatchQueue.main, latest: true)
.sink { [weak self] in
guard let self else { return }
// A task's own state (status / createdAt-relative ordering)
// may have changed, so refresh the cached ordering before
// driving the throttled view update.
self.recomputeSortedToastTasks()
self.objectWillChange.send()
}
restoreRetainedTabs()
}
// MARK: - Toast Ordering
/// Status ordering for the Activity section: awaiting input first, then running,
/// then queued, then terminal states. Lower sorts earlier.
private static func statusSortPriority(_ status: BackgroundTaskStatus) -> Int {
switch status {
case .waitingForInput: return 0
case .running: return 1
case .queued: return 2
case .completed: return 3
case .failed: return 3
case .cancelled: return 4
}
}
/// Rebuild `sortedToastTasks` from the current task set. Cheap (the set
/// is capped at a handful of tasks) but kept off the per-render path by
/// only running when the set or a task's state actually changes.
private func recomputeSortedToastTasks() {
sortedToastTasks =
backgroundTasks.values
// Headless dispatchers (e.g. webhook responders) opt out of the
// Activity section by setting `showToast = false`. The task is still tracked
// for completion signaling — it just doesn't render.
.filter { $0.showToast }
// A task attached to a live chat window surfaces its state in
// that window; the Activity section/toast only reports detached work so
// completion/failure never double-announces (or leaks into) the
// chat the user is currently looking at.
.filter { !isTaskAttachedToWindow($0.id) }
// Same rule for spawned-helper mirrors: while the launching chat
// is visible in a window, its in-chat spawn card already reports
// the run, so the Activity section stays quiet. Detached launchers
// (closed windows) surface the helper here.
.filter { !isMirrorParentVisibleInChatWindow($0) }
.sorted { a, b in
let ap = Self.statusSortPriority(a.status), bp = Self.statusSortPriority(b.status)
if ap != bp { return ap < bp }
return a.createdAt > b.createdAt
}
refreshPowerAssertion()
}
// MARK: - Public API
/// Re-evaluate idle-sleep prevention after task state or the user
/// preference changes. Waiting-for-input sessions intentionally do not
/// keep the Mac awake indefinitely.
func refreshPowerAssertion() {
powerManager?.update(for: backgroundTasks.values.map(\.status))
}
var isPreventingIdleSystemSleep: Bool {
powerManager?.isPreventingIdleSystemSleep ?? false
}
/// Check if a task ID corresponds to a background task
public func isBackgroundTask(_ id: UUID) -> Bool {
backgroundTasks[id] != nil
}
/// Get background task state by ID
public func taskState(for id: UUID) -> BackgroundTaskState? {
backgroundTasks[id]
}
/// An approval card for a running task is waiting on a person
/// (`AttentionProducers.markWaiting`). Waiting releases the task's
/// execution slot like a clarification; answering it resumes the run.
func setAwaitingApproval(_ id: UUID, waiting: Bool, step: String) {
guard let state = backgroundTasks[id] else { return }
if waiting {
guard state.status == .running else { return }
state.status = .waitingForInput
state.currentStep = step
pumpQueue()
} else if state.status == .waitingForInput, state.chatSession?.awaitingClarify == nil {
// The caller only ends a wait once none of this task's cards are
// open; a clarification still showing keeps the task waiting.
state.status = .running
state.currentStep = "Running..."
}
}
/// Resolve a still-retained channel conversation so an inbound follow-up
/// can answer a clarification or continue the same task without creating
/// a second session.
public func replyableTaskId(
source: SessionSource,
externalSessionKey: String,
agentId: UUID
) -> UUID? {
replyableTaskId(source: source, externalSessionKey: externalSessionKey, target: .local(agentId))
}
/// `replyableTaskId` keyed by dispatch target so a channel conversation
/// routed to a shared workspace agent reattaches the same way a local
/// one does.
public func replyableTaskId(
source: SessionSource,
externalSessionKey: String,
target: AgentDispatchTarget
) -> UUID? {
backgroundTasks.values.first { state in
guard state.source == source,
state.externalSessionKey == externalSessionKey,
state.target == target
else { return false }
switch state.status {
case .waitingForInput, .completed:
return true
case .queued, .running, .failed, .cancelled:
return false
}
}?.id
}
/// Rename an Activity session and its canonical persisted conversation.
/// There is intentionally no Activity-only alias: the same title appears in
/// the Activity section, Chat window, and conversation sidebar.
@discardableResult
public func renameTask(_ id: UUID, title: String) -> Bool {
guard let state = backgroundTasks[id] else { return false }
let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return false }
state.taskTitle = trimmed
if let session = state.chatSession {
session.title = trimmed
session.save()
}
ChatSessionsManager.shared.rename(id: id, title: trimmed)
persistRetainedTabs()
recomputeSortedToastTasks()
objectWillChange.send()
return true
}
/// Follow a canonical Chat rename without calling `renameTask` back into
/// ChatSessionsManager. The canonical store already owns that title write
/// and its updatedAt policy; only this registry's alias needs persistence.
func synchronizeCanonicalTitle(_ id: UUID, title: String) {
guard let state = backgroundTasks[id] else { return }
let changed = state.taskTitle != title
if changed { state.taskTitle = title }
if let session = state.chatSession, session.title != title {
session.title = title
}
guard changed else { return }
persistRetainedTabs()
recomputeSortedToastTasks()
objectWillChange.send()
}
/// Background-task id (if any) the given window is bound to. Returns
/// nil for plain chat windows that were never detached.
public func taskId(forWindowId windowId: UUID) -> UUID? {
taskIdByWindow[windowId]
}
/// Whether this window is bound to a still-tracked background task.
/// False if the window was never detached or its task already finalized.
public func isWindowDetachedToBackground(windowId: UUID) -> Bool {
guard let id = taskIdByWindow[windowId] else { return false }
return backgroundTasks[id] != nil
}
/// Whether a spawned-helper mirror's launching chat session is currently
/// visible in an open chat window (where the in-chat spawn card already
/// reports the run). Always false for non-mirror tasks.
private func isMirrorParentVisibleInChatWindow(_ state: BackgroundTaskState) -> Bool {
guard let parent = state.subagentParentSessionId,
let sessionId = UUID(uuidString: parent)
else { return false }
return ChatWindowManager.shared.findWindow(bySessionId: sessionId) != nil
}
/// Whether any live chat window is currently bound to (viewing) this
/// task. Attached tasks surface their state in the window instead of
/// the Activity section/toast.
func isTaskAttachedToWindow(_ taskId: UUID) -> Bool {
taskIdByWindow.contains { windowId, boundTask in
boundTask == taskId && ChatWindowManager.shared.windowExists(id: windowId)
}
}
/// Bind a window to a task so closing/switching that window is treated
/// as detaching the view rather than stopping execution, and so the
/// Activity section/toast stops double-reporting a chat the user can already see.
public func bindWindow(_ windowId: UUID, toTask taskId: UUID) {
taskIdByWindow[windowId] = taskId
recomputeSortedToastTasks()
viewUpdateSubject.send()
}
/// Remove a window's task binding (window closed or switched to another
/// chat). The task itself is untouched; if it is still active it
/// resurfaces in the Activity section/toast.
public func unbindWindow(_ windowId: UUID) {
guard taskIdByWindow.removeValue(forKey: windowId) != nil else { return }
recomputeSortedToastTasks()
viewUpdateSubject.send()
}
/// The live (active) registry task currently driving the given persisted
/// session id, if any. Used by chat windows to re-attach the exact
/// in-memory `ChatSession` when the user reopens a running chat instead
/// of hydrating a stale copy from disk.
public func liveTask(forSessionId sessionId: UUID) -> BackgroundTaskState? {
backgroundTasks.values.first { state in
state.status.isActive && state.chatSession?.sessionId == sessionId
}
}
/// Sessions of all still-active registry tasks. Residency GC uses this
/// so a detached run's model counts as "still wanted" exactly like a
/// model selected in an open window.
func activeTaskSessions() -> [ChatSession] {
backgroundTasks.values.compactMap { state in
guard state.status.isActive else { return nil }
return state.chatSession
}
}
/// True when any registry-owned session is mid-stream on a local model.
/// Feeds the "one local generation at a time" admission check so a run
/// detached from its window still blocks a competing local send — the
/// shared inference context can only run one, and loading a second
/// would evict the first and cancel its stream. Sessions currently
/// attached to a window are excluded (the window-scan side of the check
/// already counts those).
func isAnyDetachedTaskStreamingLocalModel(excludingSession excluded: ChatSession? = nil) -> Bool {
detachedTaskStreamingLocalModel(excludingSession: excluded) != nil
}
/// The detached task currently holding the single local-model slot, if any.
///
/// Same predicate as ``isAnyDetachedTaskStreamingLocalModel(excludingSession:)``,
/// but returning the id instead of a bool, because a caller that has just
/// refused the user's send needs to be able to *act* on that run — stop it,
/// or reopen its window. Answering only "yes, something is running" is what
/// left the busy alert telling people to wait for a window that no longer
/// exists.
func detachedTaskStreamingLocalModel(excludingSession excluded: ChatSession? = nil) -> UUID? {
backgroundTasks.values.first { state in
guard let session = state.chatSession, session !== excluded else { return false }
guard !isTaskAttachedToWindow(state.id) else { return false }
return session.isStreamingLocalModel
}?.id
}
/// Adopt a live in-flight `ChatSession` into the registry so its
/// execution lifecycle is owned here, independent of any window. Reuses
/// the existing instance verbatim (no new session, no disk hydration) so
/// all publishers keep firing uninterrupted.
///
/// Returns the task id, or nil if the session isn't streaming. If the
/// session is already registry-owned, returns the existing task id.
@discardableResult
func adoptSession(_ session: ChatSession, windowId: UUID? = nil) -> UUID? {
// Already tracked? Just (re)bind the window.
if let existing = backgroundTasks.values.first(where: { $0.chatSession === session }) {
if let windowId { taskIdByWindow[windowId] = existing.id }
return existing.id
}
// Adoptable while executing OR paused on a clarify prompt — a run
// waiting for input is still alive and must survive the view going
// away. (The clarify observer installed below immediately replays
// the pause into `.waitingForInput`.)
guard session.isStreaming || session.awaitingClarify != nil || !session.awaitingWorkflowRuns.isEmpty
else { return nil }
// Registry-shared sessions are co-owned by their registering
// owner, which keeps an in-flight run alive after every window
// stops viewing it; adopting one here would create a second
// execution owner (double stop/finalize/save). Refusing makes the
// window-close path fall through to `ChatWindowState.cleanup()`,
// whose shared branch unlinks without stopping the run.
guard !LiveChatSessionRegistry.shared.isShared(session) else { return nil }
// Persist before adopting so the sidebar and `openTaskWindow` reload
// path both see a real saved row for this session.
session.save()
let context = ExecutionContext(adopting: session)
let state = BackgroundTaskState(
id: context.id,
taskTitle: session.title,
agentId: context.agentId,
chatSession: session,
executionContext: context,
status: .running,
currentStep: "Running...",
source: .chat,
sourcePluginId: nil,
externalSessionKey: nil,
showToast: true
)
registerTask(state)
observeChatTask(state, session: session)
if let windowId { taskIdByWindow[windowId] = state.id }
recomputeSortedToastTasks()
return state.id
}
/// Detach a streaming chat window's session into a background task so
/// the user can close the window without killing the in-flight stream.
/// The detached task keeps its agent's sidebar row live, comes back as a
/// tab of that agent in the next window that opens, and can be re-opened
/// via `openTaskWindow(_:)`.
///
/// No-op if the window doesn't exist, isn't streaming, or was already
/// detached.
public func detachChatWindow(windowId: UUID) {
guard taskIdByWindow[windowId] == nil,
let session = ChatWindowManager.shared.windowState(id: windowId)?.session
else { return }
if let taskId = adoptSession(session, windowId: windowId) {
print("[BackgroundTaskManager] Detached chat window \(windowId) as task \(taskId)")
}
}
/// Bring a background task's conversation on screen: the tab that already
/// shows it is focused, else it opens as a tab of its agent in the
/// frontmost chat window (a window is created only when none is open).
public func openTaskWindow(_ backgroundId: UUID) {
guard let state = backgroundTasks[backgroundId] else { return }
// A spawned-helper mirror has no chat of its own to open — its
// transcript lives inside the launching turn. Tapping a finished
// mirror just dismisses it; an active one is a no-op.
if state.isSubagentMirror {
if !state.status.isActive { finalizeTask(backgroundId) }
return
}
ChatWindowManager.shared.revealTask(backgroundId)
}
/// Remove a background task from management, cancelling all observers and timers.
public func finalizeTask(_ backgroundId: UUID) {
guard let state = backgroundTasks[backgroundId] else { return }
// Ensure plugins always receive a terminal event before cleanup.
if state.status.isActive, state.sourcePluginId != nil {
state.status = .cancelled
emitPluginEvent(
state,
type: .cancelled,
json: PluginHostContext.serializeCancelledEvent(taskTitle: state.taskTitle)
)
state.agentRunId = nil
}
dispatchHoldTasks.remove(backgroundId)
if let events = heldTaskEvents.removeValue(forKey: backgroundId) {
for event in events {
emitPluginEvent(state, type: event.type, json: event.json)
}
}
resumeCompletion(for: backgroundId, result: resultFromState(state))
cancelAutoFinalize(backgroundId)
taskObservers[backgroundId]?.forEach { $0.cancel() }
taskObservers.removeValue(forKey: backgroundId)
chatTurnCounts.removeValue(forKey: backgroundId)
streamingObserved.remove(backgroundId)
// Drop any window→task bindings pointing here so a still-open
// window's close path stops thinking the task is alive.
taskIdByWindow = taskIdByWindow.filter { $0.value != backgroundId }
// Free its slots and drop any deferred start so a finalized queued
// task can't launch.
scheduler.cancelPending(schedulerTaskId(backgroundId))
detachScheduling(state)
state.releaseReferences()
backgroundTasks.removeValue(forKey: backgroundId)
persistRetainedTabs()
recomputeSortedToastTasks()
pumpQueue()
}
/// Cancel all active background tasks. Called during app termination.
/// Queued requests are cancelled FIRST: cancelling a running task frees
/// its slot and pumps the queue, so doing it the other way around would
/// briefly promote (and start) queued work mid-shutdown.
public func cancelAllTasks() {
for (id, state) in backgroundTasks where state.status == .queued {
cancelTask(id)
}
for (id, state) in backgroundTasks where state.status.isActive {
cancelTask(id)
}
}
/// Update a task's running token / cost counters and cancel the
/// task when either dimension crosses its configured ceiling (spec
/// §11.3). Safe to call from any actor — we hop to MainActor
/// internally because `BackgroundTaskState` is `@MainActor`.
///
/// Streaming engines call this after each provider chunk. When the
/// per-chunk USD cost isn't known, callers may pass nil and rely
/// on token counts alone.
public func recordUsage(
backgroundId: UUID,
tokensInDelta: Int = 0,
tokensOutDelta: Int = 0,
costUSDDelta: Double = 0
) {
guard let state = backgroundTasks[backgroundId] else { return }
state.tokensIn += max(0, tokensInDelta)
state.tokensOut += max(0, tokensOutDelta)
state.costUSD += max(0, costUSDDelta)
renewLease(backgroundId)
if let reason = state.budgetExceededReason() {
state.budgetExhaustedReason = reason
print("[BackgroundTaskManager] budget exhausted (\(reason)) — cancelling \(backgroundId)")
cancelTask(backgroundId)
}
}
/// Cancel a background task (queued or running)
public func cancelTask(_ backgroundId: UUID) {
guard let state = backgroundTasks[backgroundId] else { return }
// A spawned-helper mirror has no session to stop — trip the run's
// interrupt token (same path as the in-chat card's Stop button) and
// mark the row cancelled immediately for a responsive Activity section. The
// feed's terminal status arrives later and is ignored because the
// mirror is no longer active.
if let toolCallId = state.subagentToolCallId {
SubagentInterruptCenter.shared.interrupt(toolCallId)
if state.status.isActive {
state.status = .cancelled
state.appendActivity(kind: .info, title: "Stopped")
}
scheduleAutoFinalize(backgroundId)
recomputeSortedToastTasks()
return
}
// An inbound shared-agent run: the session here is a read-only
// transcript with no stream of its own to stop. The bridge trips the
// run's interrupt token and ends the SSE response so the host really
// stops serving the remote caller; the row is marked cancelled right
// away for a responsive tab, and the run's late `finish` is a no-op.
if state.isInboundRun {
InboundSharedRunBridge.shared.stopRequested(taskId: backgroundId)
if state.status.isActive {
state.status = .cancelled
state.currentStep = nil
state.appendActivity(kind: .info, title: "Stopped")
state.captureContextPreview()
state.chatSession?.save()
}
scheduleAutoFinalize(backgroundId)
persistRetainedTabs()
recomputeSortedToastTasks()
return
}
finishChatCancellation(state, stopSession: true)
}
/// Shared terminal path for Activity Stop and the delegated chat's own
/// Stop button. The latter has already stopped the session; do not enter
/// its cleanup a second time from the synchronous streaming observer.
private func finishChatCancellation(_ state: BackgroundTaskState, stopSession: Bool) {
let backgroundId = state.id
// A queued task never started — drop its deferred start so a later
// pump can't resurrect it.
scheduler.cancelPending(schedulerTaskId(backgroundId))
// stop() synchronously publishes isStreaming=false. Mark cancellation
// first so the streaming observer cannot resume a delegation waiter
// with .completed and promote its buffered partial answer to success.
state.status = .cancelled
if stopSession { state.chatSession?.stop() }
state.captureContextPreview()
if let runId = state.agentRunId {
Self.writeRunTrace(
runId: runId,
state: state,
status: .cancelled,
endedAt: Date(),
errorMessage: state.budgetExhaustedReason.map { "Budget exhausted: \($0)" }
)
state.agentRunId = nil
}
resumeCompletion(for: backgroundId, result: .cancelled)
emitPluginEvent(
state,
type: .cancelled,
json: PluginHostContext.serializeCancelledEvent(taskTitle: state.taskTitle)
)
releaseResidencyAndRearmChatWarmup(after: state)
scheduleAutoFinalize(backgroundId)
persistRetainedTabs()
recomputeSortedToastTasks()
pumpQueue()
}
/// Close an Activity agent tab: cancel every active (running / queued /
/// waiting) Activity-visible task for the agent and finalize the whole
/// group atomically. Terminal tasks in the group are finalized without
/// a cancel pass.
///
/// The group's deferred queued starts are dropped up front:
/// `cancelTask` pumps the queue after each cancellation, and a running
/// task's freed slot must not briefly promote (and start) this agent's
/// own queued work mid-close.
public func closeAgentTaskGroup(agentId: UUID) {
let ids = sortedToastTasks.filter { $0.agentId == agentId }.map(\.id)
guard !ids.isEmpty else { return }
for id in ids {
scheduler.cancelPending(schedulerTaskId(id))
}
for id in ids where backgroundTasks[id]?.status.isActive == true {
cancelTask(id)
}
for id in ids {
finalizeTask(id)
}
}
/// Submit a quick reply (channels, plugins) straight into a task's retained
/// `ChatSession`, using the same canonical send path as the chat
/// window. For a `.waitingForInput` task this answers the pending
/// clarify prompt (`send` clears `awaitingClarify` and resumes the
/// loop); for a `.completed` task it starts a follow-up turn and
/// revives the session before terminal cleanup dehydrates it.
///
/// Returns false when the task is missing, its session is gone, the
/// text is empty, or the task is not in a replyable state (running /
/// queued work takes input via the chat window; failed / cancelled
/// runs are view-only).
@discardableResult
public func submitQuickReply(_ backgroundId: UUID, text: String, author: ParticipantRef? = nil) -> Bool {
// Inbound shared-agent runs are the remote caller's conversation —
// read-only on the host, never replyable from here.
guard let state = backgroundTasks[backgroundId], !state.isSubagentMirror, !state.isInboundRun
else { return false }
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return false }
switch state.status {
case .waitingForInput, .completed:
break
case .queued, .running, .failed, .cancelled:
return false
}
// A completed task is already on its terminal-cleanup timer; a
// follow-up revives the run, so stop dehydration before dispatching.
cancelAutoFinalize(backgroundId)
let wasRetained = state.chatSession == nil
guard let context = state.executionContext ?? hydrateRetainedTask(state),
let session = state.chatSession
else { return false }
if taskObservers[backgroundId] == nil {
observeChatTask(state, session: session)
}
if wasRetained {
state.status = .running
state.currentStep = "Preparing follow-up..."
persistRetainedTabs()
recomputeSortedToastTasks()
Task { @MainActor in
await context.prepare()
session.nextSendAuthor = author
session.send(trimmed)
}
return true
}
// Headless conversations follow the agent's current default model
// on every turn (no-op for window chats); the retained branch above
// gets the same treatment via `context.prepare()`.
session.applyAgentDefaultModelForDispatch()
// `send` clears any clarify pause / stale prompt overlay and starts
// the next run; the streaming observer transitions the task back to
// `.running`, so no status write is needed here.
session.nextSendAuthor = author
session.send(trimmed)
return true
}
/// The task currently streaming for this grouping key, or nil. The
/// running twin of `replyableTaskId`, used to steer a live turn.
public func runningTaskId(
source: SessionSource,
externalSessionKey: String,
target: AgentDispatchTarget
) -> UUID? {
backgroundTasks.values.first { state in
guard state.source == source,
state.externalSessionKey == externalSessionKey,
state.target == target,
case .running = state.status
else { return false }
return state.chatSession?.isStreaming == true
}?.id
}
/// Hand a running task a new user message without stopping it. The text
/// joins the conversation at the loop's next iteration boundary, so the
/// agent sees it after the current tool call returns. Text that misses
/// the last boundary stays queued for `takeRemoteSteers`. Returns false
/// when the task is not streaming, so the caller dispatches normally.
public func steerTask(_ backgroundId: UUID, text: String) -> Bool {
// Inbound shared-agent runs belong to the remote caller; the host
// cannot write into their conversation.
guard let state = backgroundTasks[backgroundId], !state.isSubagentMirror, !state.isInboundRun,
let session = state.chatSession, session.isStreaming
else { return false }
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return false }
session.remoteSteers.append(trimmed)
return true
}
/// Steers that arrived too late for the run's last iteration boundary.
/// The caller that queued them sends these as the follow-up turn.
public func takeRemoteSteers(_ backgroundId: UUID) -> [String] {
guard let session = backgroundTasks[backgroundId]?.chatSession else { return [] }
let leftover = session.remoteSteers
session.remoteSteers = []
return leftover
}
/// Soft-stop a running task by cancelling its current stream.
///
/// When `message` is non-empty, the trimmed content is appended to the
/// session as a `user`-role turn before the stream is cancelled. The
/// model picks the message up on the next user turn — i.e. when the
/// user opens the chat window, when the plugin dispatches a follow-up,
/// or when the session is otherwise resumed. This is the documented
/// behavior of `dispatch_interrupt` on the v3 surface.
///
/// Empty / whitespace-only messages just cancel the stream, matching
/// the original soft-stop semantics. The chat task can always be
/// resumed by the user opening its window and sending a follow-up.
public func interruptTask(_ backgroundId: UUID, message: String?) {
guard let state = backgroundTasks[backgroundId], state.status.isActive else { return }
// The host cannot inject into a remote caller's conversation; a
// soft-stop on an inbound run is a plain Stop.
if state.isInboundRun {
cancelTask(backgroundId)
return
}
if let trimmed = message?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmed.isEmpty {
// Inject as a user-role turn so the next user-driven completion
// round (which the user or another dispatch will trigger) sees
// it as part of the conversation history.
state.chatSession?.appendInterruptMessage(trimmed)
}
// Programmatic redirect, not the user's Stop button: the interrupt
// turn itself is the transcript record, so no cancelled marker.
state.chatSession?.stop(preservesCancelledMarker: false)
}
/// Emit a draft event to the originating plugin.
func emitDraftEvent(_ state: BackgroundTaskState, draftJSON: String) {
emitPluginEvent(
state,
type: .draft,
json: PluginHostContext.serializeDraftEvent(draftJSON: draftJSON, taskTitle: state.taskTitle)
)
}
// MARK: - Subagent Mirrors
/// Register a visibility-only mirror of a live spawned-helper run.
/// Called by `SubagentBackgroundTaskBridge` when a spawn feed appears in
/// the registry. Mirrors reuse the ordinary task pipeline (Activity row,
/// activity feed, power assertion) but are excluded from execution-slot
/// accounting and relaunch persistence.
func registerSubagentMirror(_ state: BackgroundTaskState) {
guard state.isSubagentMirror else { return }
registerTask(state)
}
/// Append an activity row to a mirror and nudge the throttled view
/// update (mirrors have no `observeChatTask` observers forwarding
/// their state changes).
func appendSubagentMirrorActivity(
_ backgroundId: UUID,
kind: BackgroundTaskActivityItem.Kind,
title: String,
detail: String? = nil
) {
guard let state = backgroundTasks[backgroundId], state.isSubagentMirror else { return }
state.appendActivity(kind: kind, title: title, detail: detail)
viewUpdateSubject.send()
}
/// Update a mirror's one-line current step (latest feed phase/progress).
func updateSubagentMirrorStep(_ backgroundId: UUID, step: String) {
guard let state = backgroundTasks[backgroundId],
state.isSubagentMirror,
state.status.isActive
else { return }
state.currentStep = step
viewUpdateSubject.send()
}
/// Transition a mirror to its terminal state when the mirrored feed
/// finishes. No-op once the mirror is already terminal (e.g. the user
/// cancelled from the Activity section and the run's own failure lands later).
func finishSubagentMirror(_ backgroundId: UUID, success: Bool, summary: String) {
guard let state = backgroundTasks[backgroundId],
state.isSubagentMirror,
state.status.isActive
else { return }
state.status = success ? .completed(summary: summary) : .failed(summary: summary)
state.currentStep = nil
state.appendActivity(kind: success ? .success : .error, title: summary)
scheduleAutoFinalize(backgroundId)
persistRetainedTabs()
recomputeSortedToastTasks()
}
// MARK: - Inbound Shared-Agent Runs
/// Register a session-backed task hosting a remote caller's run of a
/// shared agent. Goes through the ordinary `registerTask` path, so the
/// run surfaces as a tab of its agent (`taskRegistered`) and is retained
/// across relaunch once terminal. Driven by `InboundSharedRunBridge`.
func registerInboundRun(_ state: BackgroundTaskState) {
guard state.isInboundRun else { return }
registerTask(state)
}
/// Bring a terminal inbound-run task back to `.running` for a follow-up
/// remote turn on the same conversation (same caller + `session_id`).
/// Returns the live session to mirror turns into: a window already
/// showing the conversation lends its instance (so the visible tab keeps
/// updating), otherwise the retained row is hydrated from disk. nil when