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
|
import Foundation
// MARK: - Response types (file-private to avoid @MainActor Decodable issues)
private struct JobsResponse: Decodable, Sendable {
let jobs: JobsPage
}
private struct JobsPage: Decodable, Sendable {
let results: [JobSummary]
let cursor: String?
}
private struct SubmitJobResponse: Decodable, Sendable {
let submit: SubmittedJob
}
private struct SubmittedJob: Decodable, Sendable {
let id: Int
}
enum BuildListFilter: String, CaseIterable, Sendable {
case attention = "Attention"
case active = "Active"
case all = "All"
}
enum AutoRefreshInterval: Int, CaseIterable, Sendable {
case off = 0
case fiveSeconds = 5
case tenSeconds = 10
var label: String {
switch self {
case .off: "Off"
case .fiveSeconds: "5s"
case .tenSeconds: "10s"
}
}
}
// MARK: - View Model
@Observable
@MainActor
final class BuildListViewModel {
private static let searchHistoryScopeID = "builds"
private(set) var jobs: [JobSummary] = [] {
didSet { updateFilteredJobs() }
}
private(set) var recentSearches: [ScopedSearchHistoryEntry]
private(set) var isLoading = false
private(set) var isLoadingMore = false
private(set) var isRefreshing = false
private(set) var isSubmitting = false
var error: String?
var filter: BuildListFilter = .attention {
didSet { updateFilteredJobs() }
}
var searchText = "" {
didSet { updateFilteredJobs() }
}
var repoFilter: String = "" {
didSet {
guard repoFilter != oldValue else { return }
repoFilterDidChange()
updateFilteredJobs()
}
}
// Cached filtered result. Updated whenever jobs, filter, searchText, or
// repoFilter changes. Only notifies observers when the content actually
// differs, which prevents the list from re-rendering on auto-refresh when
// no visible data changed.
private(set) var filteredJobs: [JobSummary] = []
private var cursor: String?
private var hasMore = true
private let client: SRHTClient
private let defaults: UserDefaults
private var refreshTask: Task<Void, Never>?
private var isAutoRefreshing = false
private static let cacheKey = "builds.jobs"
init(client: SRHTClient, defaults: UserDefaults = .standard) {
self.client = client
self.defaults = defaults
self.recentSearches = ScopedSearchHistoryStore.load(
scopeID: Self.searchHistoryScopeID,
defaults: defaults
)
}
/// Unique tags across all loaded jobs, sorted alphabetically.
var availableTags: [String] {
let allTags = Set(jobs.flatMap(\.tags))
return allTags.sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending }
}
private func updateFilteredJobs() {
var result = Self.filterJobs(jobs, filter: filter)
if !repoFilter.isEmpty {
result = result.filter { $0.tags.contains(repoFilter) }
}
let updated = Self.searchJobs(result, matching: searchText)
// Skip the assignment (and the resulting observer notification) when the
// filtered list hasn't actually changed — e.g. on auto-refresh when no
// builds have been added or updated.
if updated != filteredJobs {
filteredJobs = updated
}
}
// MARK: - Auto-Refresh
func startAutoRefresh(interval: AutoRefreshInterval) {
stopAutoRefresh()
guard interval != .off else { return }
let seconds = interval.rawValue
refreshTask = Task { [weak self] in
while !Task.isCancelled {
try? await Task.sleep(for: .seconds(seconds))
guard !Task.isCancelled, let self else { return }
guard !self.isAutoRefreshing, !self.isLoading, !self.isRefreshing else { continue }
self.isAutoRefreshing = true
await self.loadJobs()
self.isAutoRefreshing = false
}
}
}
func stopAutoRefresh() {
refreshTask?.cancel()
refreshTask = nil
}
private func repoFilterDidChange() {
// Reset to empty if the selected tag no longer exists
if !repoFilter.isEmpty, !availableTags.contains(repoFilter) {
repoFilter = ""
}
}
// MARK: - Query
private static let query = """
query jobs($cursor: Cursor) {
jobs(cursor: $cursor) {
results {
id
created
updated
status
note
tags
visibility
image
tasks { name status }
}
cursor
}
}
"""
private static let submitMutation = """
mutation submit($manifest: String!, $tags: [String!], $note: String, $secrets: Boolean, $execute: Boolean, $visibility: Visibility) {
submit(manifest: $manifest, tags: $tags, note: $note, secrets: $secrets, execute: $execute, visibility: $visibility) {
id
}
}
"""
private static let cancelMutation = """
mutation cancel($id: Int!) {
cancel(jobId: $id) { id }
}
"""
// MARK: - Public API
/// Fetch the first page of jobs. Shows cached data instantly if available,
/// then refreshes from the network in the background.
func loadJobs() async {
// Show cached data immediately on first load (may populate `jobs` from cache).
if jobs.isEmpty {
loadFromCache()
}
let treatAsInitialLoad = jobs.isEmpty
if treatAsInitialLoad {
isLoading = true
} else {
isRefreshing = true
}
error = nil
cursor = nil
hasMore = true
do {
let page = try await fetchPage(cursor: nil, useCache: true)
jobs = page.results
cursor = page.cursor
hasMore = page.cursor != nil
} catch {
if jobs.isEmpty {
self.error = error.userFacingMessage
}
}
isLoading = false
isRefreshing = false
}
func loadMoreIfNeeded(currentItem: JobSummary) async {
guard let last = jobs.last,
last.id == currentItem.id,
hasMore,
!isLoadingMore else {
return
}
isLoadingMore = true
do {
let page = try await fetchPage(cursor: cursor, useCache: false)
jobs.append(contentsOf: page.results)
cursor = page.cursor
hasMore = page.cursor != nil
} catch {
self.error = error.userFacingMessage
}
isLoadingMore = false
}
func submitBuild(
manifest: String,
tags: [String],
note: String,
secrets: Bool,
execute: Bool,
visibility: Visibility
) async -> Int? {
guard !isSubmitting else { return nil }
let trimmedManifest = manifest.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedManifest.isEmpty else {
error = "Paste a build manifest."
return nil
}
isSubmitting = true
error = nil
defer { isSubmitting = false }
var variables: [String: any Sendable] = [
"manifest": trimmedManifest,
"secrets": secrets,
"execute": execute,
"visibility": visibility.rawValue
]
if !tags.isEmpty {
variables["tags"] = tags
}
let trimmedNote = note.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmedNote.isEmpty {
variables["note"] = trimmedNote
}
do {
let result = try await client.execute(
service: .builds,
query: Self.submitMutation,
variables: variables,
responseType: SubmitJobResponse.self
)
await loadJobs()
return result.submit.id
} catch {
self.error = "Couldn’t submit the build. \(error.userFacingMessage)"
return nil
}
}
func cancelJob(_ job: JobSummary) async {
guard job.status.isCancellable else { return }
do {
_ = try await client.execute(
service: .builds,
query: Self.cancelMutation,
variables: ["id": job.id],
responseType: CancelResponse.self
)
if let index = jobs.firstIndex(where: { $0.id == job.id }) {
let updated = JobSummary(
id: job.id,
created: job.created,
updated: job.updated,
status: .cancelled,
note: job.note,
tags: job.tags,
visibility: job.visibility,
image: job.image,
tasks: job.tasks
)
jobs[index] = updated
}
} catch {
self.error = error.userFacingMessage
}
}
func recordRecentSearch(_ query: String) {
ScopedSearchHistoryStore.record(
query: query,
scopeID: Self.searchHistoryScopeID,
defaults: defaults
)
recentSearches = ScopedSearchHistoryStore.load(
scopeID: Self.searchHistoryScopeID,
defaults: defaults
)
}
func clearRecentSearches() {
ScopedSearchHistoryStore.clear(
scopeID: Self.searchHistoryScopeID,
defaults: defaults
)
recentSearches = []
}
// MARK: - Private
private func fetchPage(cursor: String?, useCache: Bool) async throws -> JobsPage {
var variables: [String: any Sendable] = [:]
if let cursor {
variables["cursor"] = cursor
}
if useCache && cursor == nil {
let result = try await client.executeAndCache(
service: .builds,
query: Self.query,
variables: variables.isEmpty ? nil : variables,
responseType: JobsResponse.self,
cacheKey: Self.cacheKey
)
return result.jobs
} else {
let result = try await client.execute(
service: .builds,
query: Self.query,
variables: variables.isEmpty ? nil : variables,
responseType: JobsResponse.self
)
return result.jobs
}
}
private func loadFromCache() {
guard let data = client.responseCache.get(forKey: Self.cacheKey) else { return }
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .srhtFlexible
if let response = try? decoder.decode(
GraphQLResponse<JobsResponse>.self,
from: data
), let page = response.data?.jobs {
jobs = page.results
cursor = page.cursor
hasMore = page.cursor != nil
}
}
private struct CancelResponse: Decodable, Sendable {
struct CancelResult: Decodable, Sendable {
let id: Int
}
let cancel: CancelResult
}
nonisolated static func filterJobs(_ jobs: [JobSummary], filter: BuildListFilter) -> [JobSummary] {
jobs.filter { job in
switch filter {
case .attention:
switch job.status {
case .failed, .timeout, .running, .queued, .pending:
return true
case .success, .cancelled:
return false
}
case .active:
switch job.status {
case .running, .queued, .pending:
return true
case .success, .failed, .cancelled, .timeout:
return false
}
case .all:
return true
}
}
}
nonisolated static func searchJobs(_ jobs: [JobSummary], matching query: String) -> [JobSummary] {
let normalizedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
guard !normalizedQuery.isEmpty else { return jobs }
return jobs.filter {
String($0.id).contains(normalizedQuery) ||
$0.status.rawValue.lowercased().contains(normalizedQuery) ||
$0.tags.contains { $0.lowercased().contains(normalizedQuery) } ||
($0.note?.lowercased().contains(normalizedQuery) == true) ||
($0.image?.lowercased().contains(normalizedQuery) == true)
}
}
}
|