Open History to see the last commit
1import SwiftUI
2import UIKit
3
4struct FeatureWorkspaceNavigationRequest: Equatable, Sendable {
5 enum Destination: Equatable, Sendable {
6 case thread(id: String)
7 case project(id: String)
8 case newTask(projectID: String?)
9 }
10
11 let id: UUID
12 let destination: Destination
13
14 init(id: UUID = UUID(), destination: Destination) {
15 self.id = id
16 self.destination = destination
17 }
18}
19
20struct WorkspaceThreadSelection: Equatable {
21 private(set) var selectedID: String?
22 private(set) var lastOpenedID: String?
23
24 var highlightedID: String? { selectedID ?? lastOpenedID }
25
26 mutating func open(_ id: String) {
27 selectedID = id
28 lastOpenedID = id
29 }
30
31 mutating func close() {
32 selectedID = nil
33 }
34}
35
36public struct WorkspaceView: View {
37 @SwiftUI.Environment(\.dynamicTypeSize) private var dynamicTypeSize
38
39 @Bindable var model: FeatureRootModel
40 private let navigationRequest: FeatureWorkspaceNavigationRequest?
41 private let onNavigationRequestConsumed: @MainActor (UUID) -> Void
42 private let submitNewTask: (NewTaskRequest) async -> FeatureThread?
43 private let submitMessage: (FeatureMessageSubmission) async -> Bool
44
45 @State private var threadSelection = WorkspaceThreadSelection()
46 @State private var selectedProjectID: String?
47 @State private var searchText = ""
48 @State private var isSearching = false
49 @AppStorage("t3.swiftui.home.snoozedExpanded") private var isSnoozedExpanded = false
50 @AppStorage("t3.swiftui.home.settledExpanded") private var isSettledExpanded = true
51 @AppStorage("t3.swiftui.home.archiveExpanded") private var isArchiveExpanded = false
52 @State private var settledLimit = 10
53 @State private var showingNewTask = false
54 @State private var newTaskInitialProjectID: String?
55 @State private var showingAddProject = false
56 @State private var showingEnvironments = false
57 @State private var showingSettings = false
58 @State private var renamingThread: FeatureThread?
59 @State private var deletingThread: FeatureThread?
60 @State private var renameTitle = ""
61 @State private var sidebarBoundaryNow = Date.now
62 @State private var preferredCompactColumn = NavigationSplitViewColumn.sidebar
63 @State private var homePresentationCache = HomePresentationCache()
64 @FocusState private var isSearchFocused: Bool
65
66 public init(
67 model: FeatureRootModel,
68 submitNewTask: ((NewTaskRequest) async -> FeatureThread?)? = nil,
69 submitMessage: ((FeatureMessageSubmission) async -> Bool)? = nil
70 ) {
71 self.init(
72 model: model,
73 navigationRequest: nil,
74 onNavigationRequestConsumed: { _ in },
75 submitNewTask: submitNewTask,
76 submitMessage: submitMessage
77 )
78 }
79
80 init(
81 model: FeatureRootModel,
82 navigationRequest: FeatureWorkspaceNavigationRequest?,
83 onNavigationRequestConsumed: @escaping @MainActor (UUID) -> Void,
84 submitNewTask: ((NewTaskRequest) async -> FeatureThread?)? = nil,
85 submitMessage: ((FeatureMessageSubmission) async -> Bool)? = nil
86 ) {
87 self.model = model
88 self.navigationRequest = navigationRequest
89 self.onNavigationRequestConsumed = onNavigationRequestConsumed
90 self.submitNewTask = submitNewTask ?? { request in
91 do {
92 let thread = try await model.client.createThreadAndSend(
93 projectID: request.projectID,
94 prompt: request.trimmedPrompt,
95 selection: request.selection,
96 runtimeMode: request.runtimeMode,
97 interactionMode: request.interactionMode,
98 workspaceMode: request.workspaceMode,
99 branch: request.branch,
100 worktreePath: request.worktreePath,
101 startFromOrigin: request.startFromOrigin,
102 attachments: request.attachments.map(\.uploadValue)
103 )
104 await model.reload()
105 return thread
106 } catch {
107 return nil
108 }
109 }
110 self.submitMessage = submitMessage ?? { submission in
111 if submission.attachments.isEmpty {
112 return await model.sendMessage(
113 threadID: submission.threadID,
114 text: submission.text,
115 selection: submission.selection
116 )
117 }
118 do {
119 try await model.client.sendMessage(
120 threadID: submission.threadID,
121 text: submission.text,
122 selection: submission.selection,
123 attachments: submission.attachments.map(\.uploadValue)
124 )
125 _ = await model.detail(for: submission.threadID, force: true)
126 return true
127 } catch {
128 return false
129 }
130 }
131 }
132
133 public var body: some View {
134 NavigationSplitView(preferredCompactColumn: $preferredCompactColumn) {
135 sidebar
136 .navigationSplitViewColumnWidth(
137 min: T3Metrics.minimumSidebarWidth,
138 ideal: T3Metrics.sidebarWidth,
139 max: T3Metrics.maximumSidebarWidth
140 )
141 } detail: {
142 detail
143 }
144 .navigationSplitViewStyle(.balanced)
145 .sheet(isPresented: $showingNewTask) {
146 NewThreadView(
147 model: model,
148 submit: submitNewTask,
149 onCreated: { thread in
150 openThread(thread.id)
151 showingNewTask = false
152 },
153 onCreateProject: openProjectCreation,
154 initialProjectID: newTaskInitialProjectID
155 )
156 }
157 .sheet(isPresented: $showingAddProject) {
158 AddProjectView(model: model)
159 }
160 .sheet(isPresented: $showingEnvironments) {
161 NavigationStack {
162 ConnectionsView(model: model)
163 .toolbar {
164 ToolbarItem(placement: .confirmationAction) {
165 Button("Done") { showingEnvironments = false }
166 }
167 }
168 }
169 .presentationDragIndicator(.visible)
170 .onAppear { model.setConnectionManagementPresented(true) }
171 .onDisappear { model.setConnectionManagementPresented(false) }
172 }
173 .sheet(isPresented: $showingSettings) {
174 SettingsView(model: model)
175 }
176 .alert(
177 "Rename thread",
178 isPresented: Binding(
179 get: { renamingThread != nil },
180 set: { if !$0 { renamingThread = nil } }
181 )
182 ) {
183 TextField("Thread title", text: $renameTitle)
184 Button("Cancel", role: .cancel) { renamingThread = nil }
185 Button("Save") {
186 guard let thread = renamingThread else { return }
187 let title = renameTitle
188 renamingThread = nil
189 Task { await model.renameThread(thread.id, title: title) }
190 }
191 .disabled(renameTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
192 }
193 .alert(
194 "Delete thread?",
195 isPresented: Binding(
196 get: { deletingThread != nil },
197 set: { if !$0 { deletingThread = nil } }
198 ),
199 presenting: deletingThread
200 ) { thread in
201 Button("Delete", role: .destructive) {
202 deletingThread = nil
203 Task { await model.deleteThread(thread.id) }
204 }
205 Button("Cancel", role: .cancel) { deletingThread = nil }
206 } message: { thread in
207 Text("\"\(thread.title)\" and its terminal history will be permanently deleted.")
208 }
209 .onChange(of: selectedThreadIsAvailable) { _, isAvailable in
210 if !isAvailable { closeSelectedThread() }
211 }
212 .onChange(of: selectedThreadID) { _, newValue in
213 preferredCompactColumn = newValue == nil ? .sidebar : .detail
214 }
215 .onChange(of: selectedProjectIsAvailable) { _, isAvailable in
216 if !isAvailable { selectedProjectID = nil }
217 }
218 .onChange(of: navigationRequest?.id, initial: true) { _, _ in
219 consumeNavigationRequest()
220 }
221 // A request that arrives before its thread or project exists in the
222 // snapshot stays pending; retry it as data lands so cold-start deep
223 // links are not silently stranded.
224 .onChange(of: model.homePresentationRevision) { _, _ in
225 if navigationRequest != nil { consumeNavigationRequest() }
226 }
227 .task(id: nextSidebarBoundary) {
228 guard let boundary = nextSidebarBoundary else { return }
229 do {
230 try await Task.sleep(for: .seconds(max(0, boundary.timeIntervalSinceNow)))
231 sidebarBoundaryNow = max(.now, boundary)
232 } catch {
233 return
234 }
235 }
236 }
237
238 private var sidebar: some View {
239 ZStack(alignment: .bottomTrailing) {
240 VStack(spacing: 0) {
241 homeBar
242 if isSearching {
243 searchBar
244 .transition(.opacity.combined(with: .move(edge: .top)))
245 }
246 threadList
247 }
248
249 composeButton
250 .padding(.trailing, 16)
251 .padding(.bottom, 14)
252 }
253 .background(T3Colors.background)
254 .toolbar(.hidden, for: .navigationBar)
255 .onChange(of: selectedProjectID) {
256 settledLimit = 10
257 }
258 }
259
260 private var threadList: some View {
261 let presentation = homePresentationCache.presentation(
262 snapshot: model.snapshot,
263 revision: model.homePresentationRevision,
264 query: searchText,
265 projectID: selectedProjectID,
266 now: sidebarBoundaryNow,
267 pullRequestsByThreadID: model.pullRequestsByThreadID
268 )
269
270 return VStack(spacing: 0) {
271 projectFilter
272 HomeThreadCollectionView(
273 presentation: presentation,
274 projectFaviconClient: model.client,
275 query: searchText,
276 selectedThreadID: threadSelection.highlightedID,
277 forceRichRows: dynamicTypeSize.isAccessibilitySize,
278 hapticsEnabled: model.snapshot.settings.hapticsEnabled,
279 settings: model.snapshot.settings,
280 pullRequestsByThreadID: model.pullRequestsByThreadID,
281 isSnoozedExpanded: isSnoozedExpanded,
282 isSettledExpanded: isSettledExpanded,
283 isArchiveExpanded: isArchiveExpanded,
284 settledLimit: settledLimit,
285 onOpen: openThread,
286 onToggleSnoozed: { isSnoozedExpanded.toggle() },
287 onToggleSettled: { isSettledExpanded.toggle() },
288 onToggleArchive: { isArchiveExpanded.toggle() },
289 onShowMoreSettled: { settledLimit += 25 },
290 onRename: { thread in
291 renameTitle = thread.title
292 renamingThread = thread
293 },
294 onRegenerateTitle: { thread in
295 Task { await model.regenerateThreadTitle(thread.id) }
296 },
297 onArchive: { thread, archived in
298 Task { await model.setArchived(thread.id, archived: archived) }
299 },
300 onSettle: { thread, settled, completion in
301 Task { completion(await model.setSettled(thread.id, settled: settled)) }
302 },
303 onSnooze: { thread, until in
304 Task { await model.setSnoozed(thread.id, until: until) }
305 },
306 onPin: { thread, pinned in
307 Task { await model.setPinned(thread.id, pinned: pinned) }
308 },
309 onDelete: { thread in
310 deletingThread = thread
311 },
312 onPullRequestChange: { threadID, observationIdentity, pullRequest in
313 model.updatePullRequest(
314 pullRequest,
315 threadID: threadID,
316 observationIdentity: observationIdentity
317 )
318 }
319 )
320 }
321 .background(T3Colors.background)
322 }
323
324 @ViewBuilder
325 private var detail: some View {
326 if let id = selectedThreadID,
327 let thread = model.snapshot.threads.first(where: { $0.id == id }) {
328 ThreadDetailView(
329 model: model,
330 thread: thread,
331 submitMessage: submitMessage,
332 onNavigateBack: closeSelectedThread
333 )
334 .id(id)
335 } else {
336 VStack(spacing: 14) {
337 Image(systemName: "square.and.pencil")
338 .font(.system(size: 30, weight: .light))
339 .foregroundStyle(T3Colors.textTertiary)
340 Text("Start a task")
341 .font(.title3.weight(.semibold))
342 Text("Choose a thread or compose something new.")
343 .font(.subheadline)
344 .foregroundStyle(T3Colors.textSecondary)
345 Button("New task", action: openNewTaskOrProjectCreation)
346 .buttonStyle(.borderedProminent)
347 .tint(T3Colors.primaryAction)
348 .foregroundStyle(T3Colors.primaryActionForeground)
349 }
350 .frame(maxWidth: .infinity, maxHeight: .infinity)
351 .background(T3Colors.background)
352 }
353 }
354
355 private var homeBar: some View {
356 HStack(spacing: 2) {
357 connectionBrand
358 .frame(maxWidth: .infinity, alignment: .leading)
359
360 Button {
361 withAnimation(.easeOut(duration: 0.16)) {
362 isSearching.toggle()
363 }
364 if isSearching {
365 Task { @MainActor in
366 await Task.yield()
367 isSearchFocused = true
368 }
369 } else {
370 searchText = ""
371 isSearchFocused = false
372 }
373 } label: {
374 Image(systemName: isSearching ? "xmark" : "magnifyingglass")
375 .font(.system(size: 17, weight: .medium))
376 .frame(width: 40, height: T3Metrics.minimumTapTarget)
377 }
378 .buttonStyle(.plain)
379 .foregroundStyle(T3Colors.textSecondary)
380 .accessibilityLabel(isSearching ? "Close search" : "Search tasks")
381 .accessibilityIdentifier("sidebar-search-button")
382
383 Button { showingSettings = true } label: {
384 Image(systemName: "slider.horizontal.3")
385 .font(.system(size: 17, weight: .medium))
386 .frame(width: 40, height: T3Metrics.minimumTapTarget)
387 }
388 .buttonStyle(.plain)
389 .foregroundStyle(T3Colors.textSecondary)
390 .accessibilityLabel("Settings")
391 .accessibilityIdentifier("sidebar-settings-button")
392 }
393 .padding(.leading, 15)
394 .padding(.trailing, 8)
395 .frame(height: 49)
396 .background(T3Colors.background)
397 }
398
399 @ViewBuilder
400 private var connectionBrand: some View {
401 if !unreachableEnvironments.isEmpty {
402 Button { showingEnvironments = true } label: {
403 HStack(spacing: 7) {
404 Image(systemName: "network.slash")
405 .font(.system(size: 13, weight: .semibold))
406 Text(unreachableBrandLabel)
407 .lineLimit(1)
408 .font(.system(size: 13, weight: .semibold))
409 Image(systemName: "chevron.right")
410 .font(.system(size: 10, weight: .semibold))
411 }
412 .frame(minHeight: T3Metrics.minimumTapTarget)
413 .contentShape(Rectangle())
414 }
415 .buttonStyle(.plain)
416 .foregroundStyle(T3Colors.danger)
417 .accessibilityLabel("\(unreachableBrandLabel). Manage environments")
418 .accessibilityIdentifier("sidebar-environments-button")
419 } else if let reconnecting = reconnectingEnvironments.first {
420 Button { showingEnvironments = true } label: {
421 HStack(spacing: 7) {
422 Image(systemName: "wifi.exclamationmark")
423 .font(.system(size: 13, weight: .semibold))
424 Text(reconnecting.name)
425 .lineLimit(1)
426 Text("reconnecting")
427 .fontWeight(.medium)
428 .opacity(0.76)
429 }
430 .font(.system(size: 14, weight: .semibold))
431 .foregroundStyle(T3Colors.warning)
432 .frame(minHeight: T3Metrics.minimumTapTarget)
433 .contentShape(Rectangle())
434 }
435 .buttonStyle(.plain)
436 .accessibilityLabel("\(reconnecting.name) reconnecting. Manage environments")
437 .accessibilityIdentifier("sidebar-environments-button")
438 } else {
439 Button { showingEnvironments = true } label: {
440 HStack(alignment: .firstTextBaseline, spacing: 4) {
441 Text("T3")
442 .fontWeight(.bold)
443 .foregroundStyle(T3Colors.textPrimary)
444 Text("Code")
445 .fontWeight(.medium)
446 .foregroundStyle(T3Colors.textSecondary)
447 Image(systemName: "chevron.down")
448 .font(.system(size: 10, weight: .semibold))
449 .foregroundStyle(T3Colors.textTertiary)
450 .padding(.leading, 2)
451 }
452 .font(.system(size: 16))
453 .frame(minHeight: T3Metrics.minimumTapTarget)
454 .contentShape(Rectangle())
455 }
456 .buttonStyle(.plain)
457 .accessibilityLabel("T3 Code. Manage environments")
458 .accessibilityIdentifier("sidebar-environments-button")
459 }
460 }
461
462 private var searchBar: some View {
463 HStack(spacing: 9) {
464 Image(systemName: "magnifyingglass")
465 .font(.system(size: 14, weight: .medium))
466 .foregroundStyle(T3Colors.textTertiary)
467 TextField("Search tasks and projects", text: $searchText)
468 .font(.subheadline)
469 .foregroundStyle(T3Colors.textPrimary)
470 .focused($isSearchFocused)
471 .submitLabel(.search)
472 .textInputAutocapitalization(.never)
473 .autocorrectionDisabled()
474 .accessibilityIdentifier("sidebar-search-field")
475 if !searchText.isEmpty {
476 Button { searchText = "" } label: {
477 Image(systemName: "xmark.circle.fill")
478 .foregroundStyle(T3Colors.textTertiary)
479 .frame(width: 28, height: 28)
480 }
481 .buttonStyle(.plain)
482 .accessibilityLabel("Clear search")
483 }
484 }
485 .padding(.horizontal, 12)
486 .frame(height: T3Metrics.minimumTapTarget)
487 .background(T3Colors.input, in: RoundedRectangle(cornerRadius: 12))
488 .overlay {
489 RoundedRectangle(cornerRadius: 12)
490 .stroke(T3Colors.border, lineWidth: 1)
491 }
492 .padding(.horizontal, 10)
493 .padding(.bottom, 4)
494 }
495
496 private var composeButton: some View {
497 Button {
498 isSearchFocused = false
499 openNewTaskOrProjectCreation()
500 } label: {
501 Image(systemName: "square.and.pencil")
502 .font(.system(size: 20, weight: .medium))
503 .foregroundStyle(T3Colors.primaryActionForeground)
504 .frame(width: 52, height: 52)
505 .background(T3Colors.primaryAction, in: Circle())
506 .shadow(color: T3Colors.shadow, radius: 16, y: 8)
507 }
508 .buttonStyle(.plain)
509 .accessibilityLabel("New task")
510 .accessibilityHint(
511 creationProjects.isEmpty
512 ? "Create a project to start a task"
513 : "Compose a message and start a thread"
514 )
515 .accessibilityIdentifier("sidebar-new-task-button")
516 }
517
518 private var projectFilter: some View {
519 HStack(spacing: 0) {
520 Menu {
521 Button {
522 selectedProjectID = nil
523 } label: {
524 if selectedProjectID == nil {
525 Label("All projects", systemImage: "checkmark")
526 } else {
527 Text("All projects")
528 }
529 }
530 ForEach(model.snapshot.projects) { project in
531 Button {
532 selectedProjectID = project.id
533 } label: {
534 let title = projectMenuTitle(project)
535 if selectedProjectID == project.id {
536 Label(title, systemImage: "checkmark")
537 } else {
538 Text(title)
539 }
540 }
541 }
542 } label: {
543 HStack(spacing: 7) {
544 Image(systemName: "folder")
545 .font(.system(size: 13, weight: .medium))
546 Text(selectedProject?.name ?? "All projects")
547 .lineLimit(1)
548 Image(systemName: "chevron.down")
549 .font(.system(size: 8, weight: .bold))
550 }
551 .font(T3Typography.homeMetadata.weight(.semibold))
552 .foregroundStyle(T3Colors.textSecondary)
553 .frame(maxWidth: .infinity, minHeight: 40, alignment: .leading)
554 .contentShape(Rectangle())
555 }
556 .buttonStyle(.plain)
557 .accessibilityLabel("Project filter")
558 .accessibilityValue(selectedProject?.name ?? "All projects")
559 .accessibilityIdentifier("sidebar-project-filter")
560
561 Button { showingAddProject = true } label: {
562 Image(systemName: "folder.badge.plus")
563 .font(.system(size: 13, weight: .medium))
564 .foregroundStyle(T3Colors.textTertiary)
565 .frame(width: T3Metrics.minimumTapTarget, height: 34)
566 }
567 .buttonStyle(.plain)
568 .accessibilityLabel("Add project")
569 .accessibilityIdentifier("sidebar-add-project-button")
570 }
571 .padding(.leading, 10)
572 .padding(.trailing, 2)
573 .accessibilityElement(children: .contain)
574 }
575
576 private var selectedProject: FeatureProject? {
577 model.snapshot.projects.first { $0.id == selectedProjectID }
578 }
579
580 private var creationProjects: [FeatureProject] {
581 DailyUXCreationContext.projects(in: model.snapshot)
582 }
583
584 private var unreachableEnvironments: [FeatureEnvironment] {
585 model.snapshot.environments.filter {
586 $0.isEnabled && $0.connectionState == .disconnected
587 }
588 }
589
590 private var reconnectingEnvironments: [FeatureEnvironment] {
591 model.snapshot.environments.filter {
592 $0.isEnabled
593 && ($0.connectionState == .connecting || $0.connectionState == .reconnecting)
594 }
595 }
596
597 private var unreachableBrandLabel: String {
598 if unreachableEnvironments.count == 1 {
599 return "\(unreachableEnvironments[0].name) offline"
600 }
601 return "\(unreachableEnvironments.count) environments offline"
602 }
603
604 private var nextSidebarBoundary: Date? {
605 DailyUXSidebarRefresh.nextBoundary(
606 for: model.snapshot.threads,
607 after: max(sidebarBoundaryNow, .now),
608 settings: model.snapshot.settings,
609 pullRequestsByThreadID: model.pullRequestsByThreadID
610 )
611 }
612
613 private var selectedThreadIsAvailable: Bool {
614 guard let selectedThreadID else { return true }
615 return model.snapshot.threads.contains { $0.id == selectedThreadID }
616 }
617
618 private var selectedThreadID: String? { threadSelection.selectedID }
619
620 private var selectedProjectIsAvailable: Bool {
621 guard let selectedProjectID else { return true }
622 return model.snapshot.projects.contains { $0.id == selectedProjectID }
623 }
624
625 private func openThread(_ id: String) {
626 threadSelection.open(id)
627 preferredCompactColumn = .detail
628 }
629
630 private func closeSelectedThread() {
631 threadSelection.close()
632 preferredCompactColumn = .sidebar
633 }
634
635 @MainActor
636 private func openProjectCreation() {
637 showingNewTask = false
638 showingAddProject = true
639 }
640
641 private func openNewTaskOrProjectCreation() {
642 openNewTaskOrProjectCreation(initialProjectID: selectedProjectID)
643 }
644
645 private func openNewTaskOrProjectCreation(initialProjectID: String?) {
646 if creationProjects.isEmpty {
647 showingAddProject = true
648 } else {
649 newTaskInitialProjectID = initialProjectID
650 showingNewTask = true
651 }
652 }
653
654 private func consumeNavigationRequest() {
655 guard let navigationRequest else { return }
656 switch navigationRequest.destination {
657 case let .thread(id):
658 guard model.snapshot.threads.contains(where: { $0.id == id }) else { return }
659 dismissTransientPresentations()
660 openThread(id)
661 case let .project(id):
662 guard model.snapshot.projects.contains(where: { $0.id == id }) else { return }
663 dismissTransientPresentations()
664 selectedProjectID = id
665 closeSelectedThread()
666 case let .newTask(projectID):
667 if let projectID,
668 model.snapshot.projects.contains(where: { $0.id == projectID }) {
669 selectedProjectID = projectID
670 }
671 dismissTransientPresentations()
672 Task { @MainActor in
673 await Task.yield()
674 openNewTaskOrProjectCreation(initialProjectID: projectID)
675 }
676 }
677 onNavigationRequestConsumed(navigationRequest.id)
678 }
679
680 private func dismissTransientPresentations() {
681 showingNewTask = false
682 showingAddProject = false
683 showingEnvironments = false
684 showingSettings = false
685 renamingThread = nil
686 }
687
688 private func projectMenuTitle(_ project: FeatureProject) -> String {
689 guard model.snapshot.environments.count > 1,
690 let environment = model.snapshot.environments.first(where: {
691 $0.id == project.environmentID
692 }) else {
693 return project.name
694 }
695 return "\(project.name) · \(environment.name)"
696 }
697}
698
699private extension FeatureDraftAttachment {
700 var uploadValue: FeatureUploadAttachment {
701 FeatureUploadAttachment(self)
702 }
703}
704
705struct HomePresentation {
706 let pinned: [FeatureThread]
707 let active: [FeatureThread]
708 let snoozed: [FeatureThread]
709 let settled: [FeatureThread]
710 let archived: [FeatureThread]
711 let searchResults: [FeatureThread]
712 let rowContexts: [String: HomeThreadRowContext]
713
714 init(
715 snapshot: FeatureSnapshot,
716 query: String,
717 projectID: String?,
718 now: Date,
719 pullRequestsByThreadID: [String: HomeThreadPullRequestPresentation] = [:]
720 ) {
721 let index = DailyUXSidebarIndex(
722 snapshot: snapshot,
723 query: "",
724 projectID: projectID,
725 now: now,
726 pullRequestsByThreadID: pullRequestsByThreadID
727 )
728 let archived = snapshot.threads
729 .filter { thread in
730 thread.isArchived && (projectID == nil || thread.projectID == projectID)
731 }
732 .sorted {
733 if $0.updatedAt != $1.updatedAt { return $0.updatedAt > $1.updatedAt }
734 return $0.id < $1.id
735 }
736
737 pinned = index.pinned
738 active = index.active
739 snoozed = index.snoozed
740 settled = index.settled
741 self.archived = archived
742 let normalizedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
743 searchResults = normalizedQuery.isEmpty
744 ? []
745 : DailyUXSidebarIndex.matchingThreads(
746 index.pinned + index.active + index.snoozed + index.settled + archived,
747 snapshot: snapshot,
748 query: normalizedQuery
749 )
750 rowContexts = HomeThreadRowContext.index(snapshot: snapshot)
751 }
752}
753
754@MainActor
755private final class HomePresentationCache {
756 private struct Key: Equatable {
757 let revision: UInt64
758 let query: String
759 let projectID: String?
760 let now: Date
761 }
762
763 private var cachedKey: Key?
764 private var cachedPresentation: HomePresentation?
765
766 func presentation(
767 snapshot: FeatureSnapshot,
768 revision: UInt64,
769 query: String,
770 projectID: String?,
771 now: Date,
772 pullRequestsByThreadID: [String: HomeThreadPullRequestPresentation]
773 ) -> HomePresentation {
774 let key = Key(
775 revision: revision,
776 query: query,
777 projectID: projectID,
778 now: now
779 )
780 if cachedKey == key, let cachedPresentation {
781 return cachedPresentation
782 }
783
784 let presentation = HomePresentation(
785 snapshot: snapshot,
786 query: query,
787 projectID: projectID,
788 now: max(now, .now),
789 pullRequestsByThreadID: pullRequestsByThreadID
790 )
791 cachedKey = key
792 cachedPresentation = presentation
793 return presentation
794 }
795}
796
797struct HomeShelfHeader: View {
798 let title: String
799 let count: Int
800 let isExpanded: Bool
801 let accent: Color?
802
803 var body: some View {
804 HStack(spacing: 8) {
805 Text(count > 0 ? "\(title) (\(count))" : title)
806 .lineLimit(1)
807 Rectangle()
808 .fill((accent ?? T3Colors.textTertiary).opacity(accent == nil ? 0.16 : 0.24))
809 .frame(height: 1)
810 Image(systemName: isExpanded ? "chevron.up" : "chevron.down")
811 .font(.system(size: 8, weight: .bold))
812 }
813 .font(T3Typography.homeMetadata.weight(.bold))
814 .foregroundStyle(accent ?? T3Colors.textTertiary)
815 .padding(.horizontal, 10)
816 .padding(.top, 4)
817 .frame(minHeight: 40)
818 .contentShape(Rectangle())
819 }
820}
821
822struct HomeThreadRowContext: Equatable {
823 var projectIcon: ProjectIconOverride? = nil
824 let projectName: String
825 let projectEnvironmentID: String?
826 let projectWorkspaceRoot: String?
827 let environmentLabel: String?
828 let providerID: String
829 let providerDriver: String
830 let providerName: String
831 let connectionState: FeatureConnection.State?
832
833 static let fallback = HomeThreadRowContext(
834 projectName: "Project",
835 projectEnvironmentID: nil,
836 projectWorkspaceRoot: nil,
837 environmentLabel: nil,
838 providerID: "agent",
839 providerDriver: "",
840 providerName: "Agent",
841 connectionState: nil
842 )
843
844 var copyContext: ThreadCopyContext {
845 ThreadCopyContext(
846 projectName: projectWorkspaceRoot == nil ? nil : projectName,
847 projectWorkspaceRoot: projectWorkspaceRoot,
848 environmentName: environmentLabel,
849 environmentID: projectEnvironmentID
850 )
851 }
852
853 var providerLooksTerminal: Bool {
854 let normalized = [providerDriver, providerID, providerName]
855 .joined(separator: " ")
856 .lowercased()
857 return normalized.contains("codex")
858 || normalized.contains("cursor")
859 || normalized.contains("open")
860 }
861
862 static func index(snapshot: FeatureSnapshot) -> [String: HomeThreadRowContext] {
863 let projectByID = snapshot.projects.reduce(into: [String: FeatureProject]()) {
864 $0[$1.id] = $1
865 }
866 let projectGroupNameByID = DailyUXCreationContext.projectGroups(in: snapshot).reduce(
867 into: [String: String]()
868 ) { result, group in
869 for projectID in group.memberProjectIDs {
870 result[projectID] = group.name
871 }
872 }
873 let environmentByID = snapshot.environments.reduce(into: [String: FeatureEnvironment]()) {
874 $0[$1.id] = $1
875 }
876 return snapshot.threads.reduce(into: [String: HomeThreadRowContext]()) { result, thread in
877 let project = projectByID[thread.projectID]
878 let normalizedThreadEnvironmentID = thread.environmentID?
879 .trimmingCharacters(in: .whitespacesAndNewlines)
880 let environmentID = normalizedThreadEnvironmentID?.isEmpty == false
881 ? normalizedThreadEnvironmentID
882 : project?.environmentID
883 let environment = environmentID.flatMap { environmentByID[$0] }
884 let environmentLabel = (environment?.name ?? thread.environmentName)?
885 .trimmingCharacters(in: .whitespacesAndNewlines)
886 let explicitProvider = thread.providerName?
887 .trimmingCharacters(in: .whitespacesAndNewlines)
888 let configuredProvider = thread.providerID.flatMap { providerID in
889 environmentID.flatMap {
890 snapshot.providersByEnvironment?[$0]?.first(where: { $0.id == providerID })
891 }
892 }
893 let providerName = (explicitProvider?.isEmpty == false ? explicitProvider : nil)
894 ?? configuredProvider?.name
895 ?? thread.providerID
896 ?? "Agent"
897 let providerID = thread.providerID ?? providerName
898 let providerDriver = configuredProvider?.driver ?? thread.providerID ?? ""
899
900 let connectionState = environment?.isEnabled == false
901 ? FeatureConnection.State.disconnected
902 : environment?.connectionState
903
904 result[thread.id] = HomeThreadRowContext(
905 projectIcon: project?.projectIcon,
906 projectName: projectGroupNameByID[thread.projectID] ?? project?.name ?? "Project",
907 projectEnvironmentID: project?.environmentID,
908 projectWorkspaceRoot: project?.path,
909 environmentLabel: environmentLabel?.isEmpty == false ? environmentLabel : nil,
910 providerID: providerID,
911 providerDriver: providerDriver,
912 providerName: providerName,
913 connectionState: connectionState
914 )
915 }
916 }
917}
918
919struct HomeThreadPullRequestPresentation: Equatable {
920 enum State: String {
921 case open
922 case merged
923 case closed
924 }
925
926 let number: Int
927 let state: State
928 let updatedAt: Date?
929
930 var label: String { "#\(number)" }
931
932 var accessibilityLabel: String {
933 "Pull request #\(number), \(state.rawValue)"
934 }
935
936 static func resolve(
937 thread: FeatureThread,
938 status: FeatureSourceControlStatus
939 ) -> Self? {
940 guard let branch = thread.branch?.trimmingCharacters(in: .whitespacesAndNewlines),
941 !branch.isEmpty,
942 status.branch == branch,
943 let pullRequest = status.pullRequest,
944 let state = State(rawValue: pullRequest.state.lowercased()) else {
945 return nil
946 }
947 return Self(
948 number: pullRequest.number,
949 state: state,
950 updatedAt: parseDate(pullRequest.updatedAt)
951 )
952 }
953
954 static func resolve(
955 linkedPullRequest: ThreadLinkedPullRequest,
956 detail: PullRequestDetail
957 ) -> Self? {
958 guard detail.number == linkedPullRequest.number,
959 detail.repository.caseInsensitiveCompare(linkedPullRequest.repository) == .orderedSame,
960 let state = State(rawValue: detail.state.rawValue) else {
961 return nil
962 }
963 return Self(
964 number: detail.number,
965 state: state,
966 updatedAt: parseDate(detail.updatedAt)
967 )
968 }
969
970 private static func parseDate(_ value: String?) -> Date? {
971 guard let value else { return nil }
972 let fractional = ISO8601DateFormatter()
973 fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
974 return fractional.date(from: value) ?? ISO8601DateFormatter().date(from: value)
975 }
976}
977
978extension FeatureThread {
979 var pullRequestObservationIdentity: String? {
980 let environment = environmentID ?? ""
981 if let linkedPullRequest {
982 return [
983 id,
984 environment,
985 projectID,
986 linkedPullRequest.projectId,
987 linkedPullRequest.repository.lowercased(),
988 String(linkedPullRequest.number),
989 ].joined(separator: "\u{0}")
990 }
991 guard let branch = branch?.trimmingCharacters(in: .whitespacesAndNewlines),
992 !branch.isEmpty else {
993 return nil
994 }
995 return [id, environment, projectID, worktreePath ?? "", branch]
996 .joined(separator: "\u{0}")
997 }
998}
999
1000struct FeatureThreadRow: View {
1001 enum Style: Equatable {
1002 case rich
1003 case slim
1004 }
1005
1006 let thread: FeatureThread
1007 private let context: HomeThreadRowContext
1008 private let projectFaviconClient: (any FeatureClient)?
1009 private let onPullRequestChange: (HomeThreadPullRequestPresentation?) -> Void
1010 let isSelected: Bool
1011 let style: Style
1012 let now: Date
1013 let allowsMultilineTitle: Bool
1014 @State private var pullRequest: HomeThreadPullRequestPresentation?
1015
1016 init(
1017 thread: FeatureThread,
1018 context: HomeThreadRowContext,
1019 projectFaviconClient: (any FeatureClient)? = nil,
1020 onPullRequestChange: @escaping (HomeThreadPullRequestPresentation?) -> Void = { _ in },
1021 isSelected: Bool = false,
1022 style: Style = .rich,
1023 now: Date = .now,
1024 allowsMultilineTitle: Bool = false
1025 ) {
1026 self.thread = thread
1027 self.context = context
1028 self.projectFaviconClient = projectFaviconClient
1029 self.onPullRequestChange = onPullRequestChange
1030 self.isSelected = isSelected
1031 self.style = style
1032 self.now = now
1033 self.allowsMultilineTitle = allowsMultilineTitle
1034 }
1035
1036 var body: some View {
1037 row(at: now)
1038 .accessibilityElement(children: .ignore)
1039 .accessibilityLabel(thread.title)
1040 .accessibilityValue(accessibilityValue(at: now))
1041 .accessibilityHint("Opens task")
1042 .accessibilityIdentifier("thread-\(thread.id)")
1043 .accessibilityAddTraits(isSelected ? .isSelected : [])
1044 .task(id: pullRequestObservationID) {
1045 await observePullRequest()
1046 }
1047 }
1048
1049 @ViewBuilder
1050 private func row(at now: Date) -> some View {
1051 Group {
1052 switch style {
1053 case .rich: richRow(at: now)
1054 case .slim: slimRow(at: now)
1055 }
1056 }
1057 .contentShape(Rectangle())
1058 }
1059
1060 private func richRow(at now: Date) -> some View {
1061 VStack(alignment: .leading, spacing: 0) {
1062 HStack(spacing: 6) {
1063 projectBadge
1064 Text(context.projectName)
1065 .lineLimit(1)
1066 .foregroundStyle(T3Colors.textSecondary)
1067 Spacer(minLength: 8)
1068 status(at: now)
1069 }
1070 .font(T3Typography.homeMetadata.weight(.medium))
1071 .frame(minHeight: 20)
1072
1073 Text(thread.title)
1074 .font(T3Typography.homeTitle)
1075 .tracking(-0.14)
1076 .foregroundStyle(T3Colors.textPrimary)
1077 .lineLimit(allowsMultilineTitle ? 2 : 1)
1078 .padding(.top, 4)
1079
1080 HStack(spacing: 6) {
1081 Image(systemName: "arrow.triangle.branch")
1082 .font(.system(size: 10, weight: .medium))
1083 Text(branchLabel)
1084 .lineLimit(1)
1085 if context.providerLooksTerminal {
1086 Text(">_")
1087 .font(.system(size: 9.5, weight: .bold, design: .monospaced))
1088 .foregroundStyle(T3Colors.syntaxProperty)
1089 }
1090 Spacer(minLength: 8)
1091 if let environmentLabel {
1092 HStack(spacing: 4) {
1093 Image(systemName: environmentIcon)
1094 .font(.system(size: 9))
1095 Text(environmentLabel)
1096 .lineLimit(1)
1097 }
1098 .foregroundStyle(environmentColor)
1099 }
1100 if let pullRequest {
1101 pullRequestIndicator(pullRequest)
1102 }
1103 if thread.pinnedAt != nil {
1104 Image(systemName: "pin.fill")
1105 .font(.system(size: 9, weight: .semibold))
1106 .foregroundStyle(T3Colors.textSecondary)
1107 }
1108 providerIcon(size: 16)
1109 }
1110 .font(T3Typography.homeMetadata)
1111 .foregroundStyle(T3Colors.textTertiary)
1112 .frame(minHeight: 20)
1113 .padding(.top, 3)
1114 }
1115 .padding(.horizontal, 10)
1116 .padding(.vertical, 8)
1117 .frame(minHeight: 88)
1118 .background(
1119 isSelected ? T3Colors.subtleStrong : Color.clear,
1120 in: RoundedRectangle(cornerRadius: 8)
1121 )
1122 .padding(.horizontal, 8)
1123 }
1124
1125 private func slimRow(at now: Date) -> some View {
1126 HStack(spacing: 9) {
1127 projectBadge
1128 .saturation(0)
1129 .opacity(0.48)
1130 Text(thread.title)
1131 .font(T3Typography.homeTitle)
1132 .foregroundStyle(T3Colors.textSecondary)
1133 .lineLimit(allowsMultilineTitle ? 2 : 1)
1134 Spacer(minLength: 8)
1135 if let pullRequest {
1136 pullRequestIndicator(pullRequest)
1137 }
1138 if thread.pinnedAt != nil {
1139 Image(systemName: "pin.fill")
1140 .font(.system(size: 9, weight: .semibold))
1141 .foregroundStyle(T3Colors.textSecondary)
1142 }
1143 providerIcon(size: 15)
1144 Text(SidebarRelativeAge.compact(since: thread.updatedAt, now: now))
1145 .font(T3Typography.homeMetadata.monospacedDigit())
1146 .foregroundStyle(T3Colors.textTertiary)
1147 }
1148 .padding(.horizontal, 10)
1149 .frame(minHeight: 44)
1150 .padding(.horizontal, 8)
1151 .background(
1152 isSelected ? T3Colors.subtleStrong : Color.clear,
1153 in: RoundedRectangle(cornerRadius: 7)
1154 )
1155 }
1156
1157 @ViewBuilder
1158 private func status(at now: Date) -> some View {
1159 HStack(spacing: 5) {
1160 if let icon = statusIcon {
1161 Image(systemName: icon)
1162 .font(.system(size: 11, weight: .semibold))
1163 }
1164 Text(thread.homeRowStatusLabel(at: now))
1165 if let duration = thread.homeWorkingDuration(at: now) {
1166 Text(duration)
1167 .font(.system(.footnote, design: .monospaced, weight: .semibold))
1168 .monospacedDigit()
1169 }
1170 }
1171 .font(T3Typography.status)
1172 .foregroundStyle(statusColor)
1173 }
1174
1175 private var statusIcon: String? {
1176 switch thread.homeStatus {
1177 case .working: "circle.dotted"
1178 case .failed: "exclamationmark.circle"
1179 case .approval, .input, .monitoring, .done, .ready: nil
1180 }
1181 }
1182
1183 private var statusColor: Color {
1184 switch thread.homeStatus {
1185 case .working: T3Colors.statusRunning
1186 case .monitoring: T3Colors.statusRunning
1187 case .approval: T3Colors.warning
1188 case .input: T3Colors.statusInput
1189 case .failed: T3Colors.danger
1190 case .done, .ready: T3Colors.textTertiary
1191 }
1192 }
1193
1194 private var environmentIcon: String {
1195 switch context.connectionState {
1196 case .connecting, .reconnecting:
1197 "wifi"
1198 case .disconnected:
1199 "wifi.slash"
1200 case .connected, nil:
1201 "server.rack"
1202 }
1203 }
1204
1205 private var environmentColor: Color {
1206 switch context.connectionState {
1207 case .connecting, .reconnecting:
1208 T3Colors.warning.opacity(0.78)
1209 case .disconnected:
1210 T3Colors.danger.opacity(0.78)
1211 case .connected, nil:
1212 T3Colors.textTertiary
1213 }
1214 }
1215
1216 private var isConnectionStale: Bool {
1217 context.connectionState == .connecting
1218 || context.connectionState == .reconnecting
1219 || context.connectionState == .disconnected
1220 }
1221
1222 private var branchLabel: String {
1223 if let branch = thread.branch?.trimmingCharacters(in: .whitespacesAndNewlines),
1224 !branch.isEmpty {
1225 return branch
1226 }
1227 if let worktreePath = thread.worktreePath,
1228 !worktreePath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
1229 return URL(fileURLWithPath: worktreePath).lastPathComponent
1230 }
1231 return "workspace"
1232 }
1233
1234 private var environmentLabel: String? {
1235 context.environmentLabel
1236 }
1237
1238 private var pullRequestObservationID: String? {
1239 guard projectFaviconClient != nil else { return nil }
1240 return thread.pullRequestObservationIdentity
1241 }
1242
1243 @MainActor
1244 private func observePullRequest() async {
1245 guard pullRequestObservationID != nil,
1246 let projectFaviconClient else {
1247 pullRequest = nil
1248 onPullRequestChange(nil)
1249 return
1250 }
1251
1252 if let linked = thread.linkedPullRequest,
1253 let environmentID = thread.environmentID {
1254 let target = FeaturePullRequestTarget(
1255 environmentID: environmentID,
1256 environmentName: thread.environmentName ?? environmentID,
1257 reference: PullRequestRef(
1258 projectId: linked.projectId,
1259 repository: linked.repository,
1260 number: linked.number
1261 )
1262 )
1263 while !Task.isCancelled {
1264 if let detail = try? await projectFaviconClient.pullRequestDetail(target),
1265 let next = HomeThreadPullRequestPresentation.resolve(
1266 linkedPullRequest: linked,
1267 detail: detail
1268 ),
1269 next != pullRequest {
1270 pullRequest = next
1271 onPullRequestChange(next)
1272 }
1273 do {
1274 try await Task.sleep(for: .seconds(30))
1275 } catch {
1276 return
1277 }
1278 }
1279 return
1280 }
1281
1282 for await status in projectFaviconClient.sourceControlStatusEvents(threadID: thread.id) {
1283 guard !Task.isCancelled else { return }
1284 let next = HomeThreadPullRequestPresentation.resolve(
1285 thread: thread,
1286 status: status
1287 )
1288 guard next != pullRequest else { continue }
1289 pullRequest = next
1290 onPullRequestChange(next)
1291 }
1292 }
1293
1294 private func pullRequestIndicator(_ pullRequest: HomeThreadPullRequestPresentation) -> some View {
1295 HStack(spacing: 3) {
1296 Image(systemName: "arrow.triangle.pull")
1297 .font(.system(size: 10, weight: .semibold))
1298 Text(pullRequest.label)
1299 .font(T3Typography.homeMetadata.monospacedDigit().weight(.medium))
1300 .lineLimit(1)
1301 }
1302 .foregroundStyle(pullRequestColor(pullRequest.state))
1303 .accessibilityElement(children: .ignore)
1304 .accessibilityLabel(pullRequest.accessibilityLabel)
1305 }
1306
1307 private func pullRequestColor(_ state: HomeThreadPullRequestPresentation.State) -> Color {
1308 switch state {
1309 case .open: T3Colors.success
1310 case .merged: T3Colors.syntaxKeyword
1311 case .closed: T3Colors.danger
1312 }
1313 }
1314
1315 private var projectBadge: some View {
1316 ProjectBadge(
1317 name: context.projectName,
1318 icon: context.projectIcon,
1319 environmentID: context.projectEnvironmentID,
1320 workspaceRoot: context.projectWorkspaceRoot,
1321 client: projectFaviconClient
1322 )
1323 }
1324
1325 private func providerIcon(size: CGFloat) -> some View {
1326 ProviderIcon(
1327 driver: context.providerDriver,
1328 providerID: context.providerID,
1329 fallbackName: context.providerName,
1330 size: size
1331 )
1332 }
1333
1334 private func accessibilityValue(at now: Date) -> String {
1335 var values = [thread.homeStatusLabel ?? "Ready", "Project \(context.projectName)"]
1336 values.append("Harness \(context.providerName)")
1337 if let duration = thread.homeWorkingDuration(at: now) {
1338 values.append("for \(duration)")
1339 }
1340 values.append("Branch \(branchLabel)")
1341 if let pullRequest {
1342 values.append(pullRequest.accessibilityLabel)
1343 }
1344 if let environmentLabel {
1345 values.append("on \(environmentLabel)")
1346 }
1347 if isConnectionStale {
1348 values.append("last known state")
1349 }
1350 return values.joined(separator: ". ")
1351 }
1352
1353}
1354
1355private struct ProjectBadge: View {
1356 let name: String
1357 let icon: ProjectIconOverride?
1358 let environmentID: String?
1359 let workspaceRoot: String?
1360 let client: (any FeatureClient)?
1361 @State private var favicon: UIImage?
1362
1363 init(
1364 name: String,
1365 icon: ProjectIconOverride? = nil,
1366 environmentID: String?,
1367 workspaceRoot: String?,
1368 client: (any FeatureClient)?
1369 ) {
1370 self.name = name
1371 self.icon = icon
1372 self.environmentID = environmentID
1373 self.workspaceRoot = workspaceRoot
1374 self.client = client
1375 let initialKey = environmentID.flatMap { environmentID in
1376 workspaceRoot.map { workspaceRoot in
1377 FeatureProjectFaviconCacheKey(
1378 environmentID: environmentID,
1379 workspaceRoot: workspaceRoot
1380 ).fingerprint
1381 }
1382 }
1383 _favicon = State(initialValue: initialKey.flatMap {
1384 FeatureProjectFaviconImageCache.shared.image(for: $0)
1385 })
1386 }
1387
1388 var body: some View {
1389 Group {
1390 if let icon, icon.kind == "emoji", let emoji = icon.emoji {
1391 Text(emoji).font(.system(size: 14))
1392 } else if let icon, icon.kind == "lucide" {
1393 Image(systemName: ProjectIconPresentation.symbol(icon.name))
1394 .font(.system(size: 13))
1395 .foregroundStyle(ProjectIconPresentation.color(icon.color))
1396 } else if let favicon {
1397 Image(uiImage: favicon)
1398 .resizable()
1399 .scaledToFit()
1400 .clipShape(RoundedRectangle(cornerRadius: 3))
1401 } else {
1402 Text(label)
1403 .font(.system(size: 8, weight: .heavy))
1404 .foregroundStyle(foreground)
1405 .frame(width: 16, height: 16)
1406 .background(background, in: RoundedRectangle(cornerRadius: 4))
1407 }
1408 }
1409 .frame(width: 16, height: 16)
1410 .accessibilityHidden(true)
1411 .task(id: faviconKey) {
1412 await loadFavicon()
1413 }
1414 }
1415
1416 private var faviconKey: String? {
1417 guard let environmentID, let workspaceRoot else { return nil }
1418 return FeatureProjectFaviconCacheKey(
1419 environmentID: environmentID,
1420 workspaceRoot: workspaceRoot
1421 ).fingerprint
1422 }
1423
1424 private func loadFavicon() async {
1425 guard icon == nil else { return }
1426 guard let environmentID, let workspaceRoot, let client, let faviconKey else {
1427 return
1428 }
1429 favicon = FeatureProjectFaviconImageCache.shared.image(for: faviconKey)
1430 if let cached = await client.cachedProjectFavicon(
1431 environmentID: environmentID,
1432 workspaceRoot: workspaceRoot
1433 ) {
1434 apply(cached, key: faviconKey)
1435 }
1436 guard !Task.isCancelled else { return }
1437 if let refreshed = await client.refreshProjectFavicon(
1438 environmentID: environmentID,
1439 workspaceRoot: workspaceRoot
1440 ) {
1441 apply(refreshed, key: faviconKey)
1442 }
1443 }
1444
1445 private func apply(_ data: Data, key: String) {
1446 guard let image = UIImage(data: data) else { return }
1447 FeatureProjectFaviconImageCache.shared.set(image, for: key)
1448 favicon = image
1449 }
1450
1451 private var label: String {
1452 let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
1453 guard !trimmed.isEmpty else { return "?" }
1454 if trimmed.lowercased().hasPrefix("t3") { return "T3" }
1455 return String(trimmed.prefix(1)).uppercased()
1456 }
1457
1458 private var paletteIndex: Int {
1459 if label == "T3" { return 0 }
1460 return name.unicodeScalars.reduce(0) { ($0 + Int($1.value)) % 4 }
1461 }
1462
1463 private var background: Color {
1464 switch paletteIndex {
1465 case 0: Color(red: 0.03, green: 0.24, blue: 0.21)
1466 case 1: Color(red: 0.19, green: 0.13, blue: 0.37)
1467 case 2: Color(red: 0.29, green: 0.18, blue: 0.02)
1468 default: Color(red: 0.10, green: 0.18, blue: 0.34)
1469 }
1470 }
1471
1472 private var foreground: Color {
1473 switch paletteIndex {
1474 case 0: Color(red: 0.78, green: 0.98, blue: 0.95)
1475 case 1: Color(red: 0.93, green: 0.91, blue: 1)
1476 case 2: Color(red: 1, green: 0.95, blue: 0.78)
1477 default: Color(red: 0.82, green: 0.9, blue: 1)
1478 }
1479 }
1480}
1481
1482@MainActor
1483private final class FeatureProjectFaviconImageCache {
1484 static let shared = FeatureProjectFaviconImageCache()
1485
1486 private let images = NSCache<NSString, UIImage>()
1487
1488 private init() {
1489 images.countLimit = FeatureProjectFaviconStore.maximumEntryCount
1490 }
1491
1492 func image(for key: String) -> UIImage? {
1493 images.object(forKey: key as NSString)
1494 }
1495
1496 func set(_ image: UIImage, for key: String) {
1497 images.setObject(image, forKey: key as NSString)
1498 }
1499}