Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FeatureActiveSubagentTracker.swift

91 lines2.8 KB

1import Foundation
2​
3/// Keeps only the small part of subagent state that mobile displays. The
4/// server-provided `agentKind` is authoritative; legacy unmarked tasks remain
5/// ordinary work-log entries.
6struct FeatureActiveSubagentTracker {
7 private enum Status: String {
8 case pending
9 case running
10 case waiting
11 case idle
12 case completed
13 case failed
14 case cancelled
15 case interrupted
16​
17 var isActive: Bool {
18 self == .pending || self == .running || self == .waiting
19 }
20​
21 var isTerminal: Bool {
22 self == .completed || self == .failed || self == .cancelled || self == .interrupted
23 }
24 }
25​
26 private var statuses: [String: Status] = [:]
27​
28 var activeCount: Int {
29 statuses.values.count(where: \.isActive)
30 }
31​
32 mutating func reset(with activities: [OrchestrationActivity]) {
33 statuses.removeAll(keepingCapacity: true)
34 for activity in activities {
35 apply(activity)
36 }
37 }
38​
39 mutating func apply(_ activity: OrchestrationActivity) {
40 guard activity.kind == "task.started"
41 || activity.kind == "task.progress"
42 || activity.kind == "task.updated"
43 || activity.kind == "task.completed",
44 let taskID = activity.payload["taskId"]?.stringValue?
45 .trimmingCharacters(in: .whitespacesAndNewlines),
46 !taskID.isEmpty else {
47 return
48 }
49​
50 let isKnownAgent = statuses[taskID] != nil
51 let isExplicitAgent = activity.payload["agentKind"]?.stringValue == "agent"
52 guard isKnownAgent || isExplicitAgent else { return }
53​
54 switch activity.kind {
55 case "task.started":
56 if let current = statuses[taskID], current.isTerminal {
57 return
58 }
59 statuses[taskID] = .running
60​
61 case "task.progress":
62 if let status = status(from: activity.payload["status"]) {
63 statuses[taskID] = status
64 } else if statuses[taskID] != .idle,
65 statuses[taskID]?.isTerminal != true {
66 statuses[taskID] = .running
67 }
68​
69 case "task.updated":
70 statuses[taskID] = status(from: activity.payload["status"])
71 ?? statuses[taskID]
72 ?? .pending
73​
74 case "task.completed":
75 guard statuses[taskID]?.isTerminal != true else { return }
76 statuses[taskID] = switch activity.payload["status"]?.stringValue {
77 case "failed": .failed
78 case "stopped": .interrupted
79 default: .completed
80 }
81​
82 default:
83 break
84 }
85 }
86​
87 private func status(from value: JSONValue?) -> Status? {
88 guard let rawValue = value?.stringValue else { return nil }
89 return Status(rawValue: rawValue)
90 }